From c382fe1c09a95cc6cc7174639c7ac91a9ab2bc4f Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 16:41:50 +0800 Subject: [PATCH 1/9] wip --- .gitignore | 1 + ai/liii/pi/ai/auth.scm | 254 ++++++---- ai/liii/pi/ai/auth/oauth/device-flow.scm | 145 ++++++ .../pi/ai/auth/oauth/kimi-coding-oauth.scm | 436 ++++++++++++++++++ ai/liii/pi/ai/auth/oauth/resolve.scm | 94 ++++ ai/liii/pi/ai/auth/storage.scm | 109 +++++ ai/liii/pi/ai/config/credential.scm | 42 +- ai/liii/pi/ai/providers/kimi-coding.scm | 7 +- ai/liii/pi/ai/providers/registry.scm | 10 +- .../PI_DEVICE_FLOW_CANCEL_MESSAGE-test.scm | 23 + ...CE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE-test.scm | 25 + .../PI_DEVICE_FLOW_TIMEOUT_MESSAGE-test.scm | 23 + .../device-flow/pi-device-flow-poll-test.scm | 130 ++++++ .../KIMI_OAUTH_CLIENT_ID-test.scm | 23 + .../KIMI_OAUTH_DEFAULT_HOST-test.scm | 23 + ...-device-authorization-device-code-test.scm | 52 +++ ...-authorization-expires-in-seconds-test.scm | 52 +++ ...ce-authorization-interval-seconds-test.scm | 52 +++ .../kimi-device-authorization-p-test.scm | 53 +++ ...mi-device-authorization-user-code-test.scm | 52 +++ ...ization-verification-uri-complete-test.scm | 53 +++ ...ce-authorization-verification-uri-test.scm | 52 +++ .../kimi-device-authorize-test.scm | 98 ++++ .../kimi-oauth-host-test.scm | 58 +++ .../kimi-oauth-login-test.scm | 94 ++++ .../kimi-oauth-to-auth-test.scm | 35 ++ .../kimi-poll-token-test.scm | 143 ++++++ .../kimi-refresh-token-test.scm | 114 +++++ .../resolve/pi-find-oauth-credential-test.scm | 45 ++ .../pi-resolve-oauth-credential-key-test.scm | 163 +++++++ .../pi-remove-auth-provider-bang-test.scm | 63 +++ .../pi-resolve-provider-key-oauth-test.scm | 143 ++++++ .../ai/auth/pi-save-auth-oauth-bang-test.scm | 111 +++++ .../ai/auth/storage/pi-auth-dir-path-test.scm | 37 ++ .../pi-auth-normalize-provider-test.scm | 32 ++ .../storage/pi-auth-normalize-secret-test.scm | 33 ++ .../auth/storage/pi-auth-read-json-test.scm | 47 ++ .../storage/pi-auth-replace-entry-test.scm | 57 +++ .../storage/pi-auth-write-json-bang-test.scm | 76 +++ .../credential/pi-credential-access-test.scm | 30 ++ .../credential/pi-credential-expires-test.scm | 30 ++ .../credential/pi-credential-oauth-p-test.scm | 30 ++ .../credential/pi-credential-refresh-test.scm | 30 ++ .../credential/pi-credential-region-test.scm | 31 ++ .../credential/pi-credential-to-json-test.scm | 20 + .../registry/pi-provider-oauth-test.scm | 28 ++ ai/tests/stub_kimi_oauth_server.py | 152 ++++++ code/liii/pi/code/config.scm | 5 +- code/liii/pi/code/session-state.scm | 2 +- tui/liii/pi/tui/cli/auth.scm | 122 ++++- tui/liii/pi/tui/interactive/app-events.scm | 4 + tui/liii/pi/tui/interactive/app-login.scm | 214 ++++++++- .../pi/tui/interactive/login-device-code.scm | 145 ++++++ .../pi/tui/interactive/login-selector.scm | 125 ++++- tui/liii/pi/tui/interactive/render.scm | 4 + tui/liii/pi/tui/interactive/worker-model.scm | 2 +- tui/liii/pi/tui/interactive/worker.scm | 7 +- ...app-handle-oauth-device-code-bang-test.scm | 55 +++ .../pi-app-handle-oauth-done-bang-test.scm | 116 +++++ .../pi-app-show-login-oauth-bang-test.scm | 146 ++++++ .../login-device-code-cancelled-p-test.scm | 55 +++ ...login-device-code-cursor-position-test.scm | 28 ++ ...gin-device-code-open-browser-bang-test.scm | 45 ++ .../login-device-code-p-test.scm | 41 ++ .../login-device-code-user-code-test.scm | 32 ++ ...ogin-device-code-verification-uri-test.scm | 32 ++ .../make-login-device-code-test.scm | 58 +++ .../login-selector-method-mode-p-test.scm | 97 ++++ 68 files changed, 4614 insertions(+), 132 deletions(-) create mode 100644 .gitignore create mode 100644 ai/liii/pi/ai/auth/oauth/device-flow.scm create mode 100644 ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm create mode 100644 ai/liii/pi/ai/auth/oauth/resolve.scm create mode 100644 ai/liii/pi/ai/auth/storage.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_CANCEL_MESSAGE-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_TIMEOUT_MESSAGE-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/device-flow/pi-device-flow-poll-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_CLIENT_ID-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_DEFAULT_HOST-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-device-code-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-expires-in-seconds-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-interval-seconds-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-p-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-user-code-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-complete-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorize-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-host-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-login-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-to-auth-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-poll-token-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-refresh-token-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/resolve/pi-find-oauth-credential-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/resolve/pi-resolve-oauth-credential-key-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/pi-remove-auth-provider-bang-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/pi-resolve-provider-key-oauth-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/pi-save-auth-oauth-bang-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-provider-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-secret-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/storage/pi-auth-read-json-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/storage/pi-auth-replace-entry-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/storage/pi-auth-write-json-bang-test.scm create mode 100644 ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm create mode 100644 ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm create mode 100644 ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm create mode 100644 ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm create mode 100644 ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm create mode 100644 ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm create mode 100644 ai/tests/stub_kimi_oauth_server.py create mode 100644 tui/liii/pi/tui/interactive/login-device-code.scm create mode 100644 tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-device-code-bang-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-done-bang-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cancelled-p-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cursor-position-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-open-browser-bang-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-p-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-user-code-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-verification-uri-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/make-login-device-code-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-selector/login-selector-method-mode-p-test.scm diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..bee8a64b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/ai/liii/pi/ai/auth.scm b/ai/liii/pi/ai/auth.scm index e87af4f5..90bd2d34 100644 --- a/ai/liii/pi/ai/auth.scm +++ b/ai/liii/pi/ai/auth.scm @@ -16,8 +16,18 @@ (liii pi ai template) (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) + (liii pi ai auth oauth resolve) + (liii pi ai auth storage) ) ;import - (export pi-load-auth pi-resolve-provider-key pi-save-auth-key) + (export pi-load-auth + pi-resolve-provider-key + pi-save-auth-key + pi-save-auth-oauth! + pi-remove-auth-provider! + ;; go worker 会话重求值调用链:刷新/落盘路径上的助手须导出 + %resolve-oauth-credential-key + ) ;export (begin (define (%dict-ref obj key default-val) @@ -43,20 +53,50 @@ (define (%parse-credential-item key val opt-env) (and (pair? val) - (equal? (%dict-ref val "type" #f) "api_key") - (let ((raw-key (%dict-ref val "key" #f))) - (and (string? raw-key) - (let ((resolved (if (pair? opt-env) - (pi-resolve-config-value raw-key (car opt-env)) - (pi-resolve-config-value raw-key) - ) ;if - ) ;resolved + (let ((p-str (if (symbol? key) (symbol->string key) key)) + (type (%dict-ref val "type" #f)) + ) ; + (cond + ((equal? type "api_key") + (let ((raw-key (%dict-ref val "key" #f))) + (and (string? raw-key) + (let ((resolved (if (pair? opt-env) + (pi-resolve-config-value raw-key (car opt-env)) + (pi-resolve-config-value raw-key) + ) ;if + ) ;resolved + ) ; + (and resolved (pi-credential p-str resolved "api_key")) + ) ;let + ) ;and + ) ;let + ) ; + ((equal? type "oauth") + ;; oauth 条目:access/refresh 为非空字符串,expires 为毫秒 epoch; + ;; region 可选(登录时的 OAuth host 覆盖值) + (let ((access (%dict-ref val "access" #f)) + (refresh (%dict-ref val "refresh" #f)) + (expires (%dict-ref val "expires" #f)) + (region (%dict-ref val "region" #f)) ) ; - (and resolved - (pi-credential (if (symbol? key) (symbol->string key) key) resolved "api_key") + (and (string? access) + (not (string-null? access)) + (string? refresh) + (not (string-null? refresh)) + (number? expires) + (pi-credential p-str + #f + "oauth" + access + refresh + expires + (and (string? region) (not (string-null? region)) region) + ) ;pi-credential ) ;and ) ;let - ) ;and + ) ; + (else #f) + ) ;cond ) ;let ) ;and ) ;define @@ -68,7 +108,11 @@ (if (not (pair? data)) '() (filter (lambda (credential) credential) - (map (lambda (entry) (%parse-credential-item (car entry) (cdr entry) opt-env)) + (map + (lambda (entry) + ;; 防御空对象 {}(string->json 产出 '(())):无条目可解析 + (and (pair? entry) (%parse-credential-item (car entry) (cdr entry) opt-env)) + ) ;lambda data ) ;map ) ;filter @@ -218,8 +262,46 @@ ) ;and ) ;define - (define (pi-resolve-provider-key provider auth-alist . opt-env) + ;; oauth 凭据 → access token:未过期直接返回,过期透明刷新并落盘; + ;; config-dir 缺失时回退默认配置目录(落盘/清除回调注入 resolve 层, + ;; 避免循环依赖) + (define (%resolve-oauth-credential-key cred opt-env opt-config-dir) + (let ((dir + (or (and (pair? opt-config-dir) (car opt-config-dir)) + (path->string (path-join (path-home) ".gf" "agent")) + ) ;or + ) ;dir + ) ; + (pi-resolve-oauth-credential-key cred + opt-env + (lambda (c) + (pi-save-auth-oauth! (pi-credential-provider c) + (pi-credential-access c) + (pi-credential-refresh c) + (pi-credential-expires c) + (pi-credential-region c) + dir + ) ;pi-save-auth-oauth! + ) ;lambda + (lambda (p) (pi-remove-auth-provider! p dir)) + ) ;pi-resolve-oauth-credential-key + ) ;let + ) ;define + + ;; 解析服务商生效密钥。opt 尾参兼容两种形态: + ;; (provider auth-alist) 旧形态 + ;; (provider auth-alist env) env 为 '((name . val) ...) + ;; (provider auth-alist env config-dir) 新增:oauth 刷新落盘目录 + ;; oauth 凭据:access 未过期直接返回,过期透明刷新(见 + ;; %resolve-oauth-credential-key);env API Key 优先于一切 auth 条目 + (define (pi-resolve-provider-key provider auth-alist . opt) (let* ((p-str (if (symbol? provider) (symbol->string provider) provider)) + (opt-env + (if (and (pair? opt) (pair? (car opt))) opt '()) + ) ;opt-env + (opt-config-dir + (if (and (pair? opt) (pair? (cdr opt))) (cdr opt) '()) + ) ;opt-config-dir (env-k (%resolve-provider-env-key p-str opt-env)) ) ; (if env-k @@ -227,6 +309,15 @@ (let ((alias (%provider-alias p-str))) (or (%find-auth-key p-str auth-alist) (%find-auth-key alias auth-alist) + (let ((oauth-cred (or (pi-find-oauth-credential p-str auth-alist) + (pi-find-oauth-credential alias auth-alist) + ) ;or + ) ;oauth-cred + ) ; + (and oauth-cred + (%resolve-oauth-credential-key oauth-cred opt-env opt-config-dir) + ) ;and + ) ;let (cond ((string=? p-str "deepseek") (%resolve-deepseek-fallback opt-env)) ((string=? p-str "ollama") "ollama") (else #f) @@ -238,88 +329,93 @@ ) ;define (define (%normalize-provider-key provider) - (cond - ((string? provider) - (let ((trimmed (string-trim-both provider))) - (if (string-null? trimmed) - (value-error "pi-save-auth-key: provider cannot be empty") - trimmed - ) ;if - ) ;let - ) ; - ((symbol? provider) - (let ((trimmed (string-trim-both (symbol->string provider)))) - (if (string-null? trimmed) - (value-error "pi-save-auth-key: provider cannot be empty") - trimmed - ) ;if - ) ;let - ) ; - (else (type-error "pi-save-auth-key: provider must be a string or symbol")) - ) ;cond + (pi-auth-normalize-provider "pi-save-auth-key" provider) ) ;define (define (%normalize-auth-key key) - (if (not (string? key)) - (type-error "pi-save-auth-key: key must be a string") - (let ((trimmed (string-trim-both key))) - (if (string-null? trimmed) - (value-error "pi-save-auth-key: key cannot be empty") - trimmed - ) ;if - ) ;let - ) ;if + (pi-auth-normalize-secret "pi-save-auth-key" "key" key) ) ;define (define (%update-auth-alist alist p-str key) - (let* ((filtered - (filter - (lambda (entry) - (not - (string=? (if (symbol? (car entry)) (symbol->string (car entry)) (car entry)) - p-str - ) ;string=? - ) ;not - ) ;lambda - alist - ) ;filter - ) ;filtered - (new-entry (cons p-str (list (cons "type" "api_key") (cons "key" key)))) - ) ; - (append filtered (list new-entry)) - ) ;let* + (pi-auth-replace-entry alist + p-str + (list (cons "type" "api_key") (cons "key" key)) + ) ;pi-auth-replace-entry ) ;define (define (pi-save-auth-key provider key . opt-config-dir) (let* ((p-str (%normalize-provider-key provider)) (k-str (%normalize-auth-key key)) - (dir-path - (path (if (and (pair? opt-config-dir) (car opt-config-dir)) - (car opt-config-dir) - (path-join (path-home) ".gf" "agent") - ) ;if - ) ;path - ) ;dir-path - (auth-file (path-join dir-path "auth.json")) - (auth-file-str (path->string auth-file)) + (dir-path (pi-auth-dir-path opt-config-dir)) + (auth-file-str (path->string (path-join dir-path "auth.json"))) (existing (or (%read-json-file auth-file-str) '())) (existing-alist (if (pair? existing) existing '())) (updated (%update-auth-alist existing-alist p-str k-str)) - (json-str (string-append (json->string updated :indent 2) "\n")) - (tmp-file (string-append auth-file-str ".tmp")) ) ; - (unless (path-exists? dir-path) - (path-mkdir dir-path :parents #t :exist-ok #t) + (pi-auth-write-json! dir-path updated) + ) ;let* + ) ;define + + ;; 保存 oauth 凭据:{provider: {type:"oauth", access, refresh, expires + ;; [, region]}},复用 pi-save-auth-key 的原子写策略(tmp + rename + + ;; chmod 0600);region 为 #f 时不写(默认 host 不落 region,1402 §7) + (define (pi-save-auth-oauth! provider access refresh expires region . opt-config-dir) + (let* ((p-str (pi-auth-normalize-provider "pi-save-auth-oauth!" provider)) + (a-str (pi-auth-normalize-secret "pi-save-auth-oauth!" "access" access)) + (r-str (pi-auth-normalize-secret "pi-save-auth-oauth!" "refresh" refresh)) + (dir-path (pi-auth-dir-path opt-config-dir)) + (auth-file-str (path->string (path-join dir-path "auth.json"))) + (existing (or (%read-json-file auth-file-str) '())) + (existing-alist (if (pair? existing) existing '())) + ) ; + (unless (number? expires) + (type-error "pi-save-auth-oauth!: expires must be a number") ) ;unless - (path-write-text (path tmp-file) json-str) - (when (path-exists? auth-file) - (path-unlink auth-file #t) - ) ;when - (path-rename (path tmp-file) auth-file) - (unless (os-windows?) - (catch #t (lambda () (g_chmod auth-file-str 384)) (lambda args #f)) + (unless (> expires 0) + (value-error "pi-save-auth-oauth!: expires must be a positive number") ) ;unless - auth-file-str + (unless + (or (not region) (and (string? region) (not (string-null? region)))) + (type-error "pi-save-auth-oauth!: region must be a non-empty string or #f") + ) ;unless + (pi-auth-write-json! dir-path + (pi-auth-replace-entry existing-alist + p-str + (append (list (cons "type" "oauth") + (cons "access" a-str) + (cons "refresh" r-str) + (cons "expires" expires) + ) ;list + (if region (list (cons "region" region)) '()) + ) ;append + ) ;pi-auth-replace-entry + ) ;pi-auth-write-json! + ) ;let* + ) ;define + + ;; 清除某 provider 的凭据条目(oauth 刷新失败 401/403/invalid_grant 时 + ;; 调用,对应 pi Models 的凭据清除);文件不存在时直接返回路径 + (define (pi-remove-auth-provider! provider . opt-config-dir) + (let* ((p-str (pi-auth-normalize-provider "pi-remove-auth-provider!" provider)) + (dir-path (pi-auth-dir-path opt-config-dir)) + (auth-file-str (path->string (path-join dir-path "auth.json"))) + (existing (%read-json-file auth-file-str)) + ) ; + (if (pair? existing) + (pi-auth-write-json! dir-path + (filter + (lambda (entry) + (not + (string=? (if (symbol? (car entry)) (symbol->string (car entry)) (car entry)) + p-str + ) ;string=? + ) ;not + ) ;lambda + existing + ) ;filter + ) ;pi-auth-write-json! + auth-file-str + ) ;if ) ;let* ) ;define ) ;begin diff --git a/ai/liii/pi/ai/auth/oauth/device-flow.scm b/ai/liii/pi/ai/auth/oauth/device-flow.scm new file mode 100644 index 00000000..638cbefd --- /dev/null +++ b/ai/liii/pi/ai/auth/oauth/device-flow.scm @@ -0,0 +1,145 @@ +;; +;; Copyright (C) 2026 The Goldfish Scheme Authors +;; +;; Licensed under the MIT License +;; + +;; RFC 8628 设备码通用轮询循环,翻译自上游 pi 仓库(本地 ~/git/pi) +;; packages/ai/src/auth/oauth/device-code.ts 的 pollOAuthDeviceCodeFlow。 +;; gfcode 无 AbortSignal,取消靠 cancelled? 谓词(TUI 组件层置位)。 +(define-library (liii pi ai auth oauth device-flow) + (import (scheme base) (liii error) (liii time) (liii pi ai time)) + (export pi-device-flow-poll PI_DEVICE_FLOW_CANCEL_MESSAGE + PI_DEVICE_FLOW_TIMEOUT_MESSAGE PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE + ) ;export + (begin + + (define PI_DEVICE_FLOW_CANCEL_MESSAGE "Login cancelled") + (define PI_DEVICE_FLOW_TIMEOUT_MESSAGE "Device flow timed out") + (define PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE + (string-append "Device flow timed out after one or more slow_down responses. " + "This is often caused by clock drift in WSL or VM environments. " + "Please sync or restart the VM clock and try again." + ) ;string-append + ) ;define + + (define %minimum-interval-ms 1000) + ;; RFC 8628 §3.2:服务端未给 interval 时客户端必须用 5 秒 + (define %default-poll-interval-seconds 5) + ;; RFC 8628 §3.5:slow_down 时轮询间隔须增加 5 秒 + (define %slow-down-increment-ms 5000) + ;; 分片睡眠粒度:每片醒来检查 cancelled?,取消响应 ≤ 0.1s + (define %sleep-slice-seconds 0.1) + + ;; 可取消睡眠:分片 sleep,任一片间发现 cancelled? 即抛取消错误 + (define (%abortable-sleep seconds cancelled?) + (let loop + ((remaining seconds)) + (when (and cancelled? (cancelled?)) + (error 'kimi-oauth-cancelled PI_DEVICE_FLOW_CANCEL_MESSAGE) + ) ;when + (when (> remaining 0) + (let ((slice (min %sleep-slice-seconds remaining))) + (sleep slice) + (loop (- remaining slice)) + ) ;let + ) ;when + ) ;let + ) ;define + + ;; poll 结果协议(对应 pi 的 OAuthDeviceCodePollResult): + ;; (pending) | (slow_down [interval-seconds]) | (failed message) + ;; | (complete value) + ;; 返回 complete 的 value;failed/取消/超时抛错。 + ;; cancelled? 为 #f 或零参谓词;wait-before-first-poll? 对齐 pi 的 + ;; waitBeforeFirstPoll(Kimi 流程首轮先等一个 interval)。 + (define* (pi-device-flow-poll poll + (interval-seconds %default-poll-interval-seconds) + (expires-in-seconds #f) + (wait-before-first-poll? #f) + (cancelled? #f) + ) ;pi-device-flow-poll + (unless (procedure? poll) + (type-error "pi-device-flow-poll: poll must be a procedure" poll) + ) ;unless + (let* ((start-ms (pi-current-monotonic-millis)) + (deadline-ms (and (number? expires-in-seconds) (+ start-ms (* expires-in-seconds 1000))) + ) ;deadline-ms + (interval-ms + (max %minimum-interval-ms + (inexact->exact + (floor + (* (if (and (number? interval-seconds) (> interval-seconds 0)) + interval-seconds + %default-poll-interval-seconds + ) ;if + 1000 + ) ;* + ) ;floor + ) ;inexact->exact + ) ;max + ) ;interval-ms + (slow-down-count 0) + ) ; + (define (remaining-ms) + (if deadline-ms (- deadline-ms (pi-current-monotonic-millis)) +inf.0) + ) ;define + (define (sleep-interval!) + (let ((rem (remaining-ms))) + (when (> rem 0) + (%abortable-sleep (/ (min interval-ms rem) 1000) cancelled?) + ) ;when + ) ;let + ) ;define + (when (and wait-before-first-poll? (> (remaining-ms) 0)) + (sleep-interval!) + ) ;when + (let loop + () + (when (and cancelled? (cancelled?)) + (error 'kimi-oauth-cancelled PI_DEVICE_FLOW_CANCEL_MESSAGE) + ) ;when + (if (<= (remaining-ms) 0) + (error 'kimi-oauth-error + (if (> slow-down-count 0) + PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE + PI_DEVICE_FLOW_TIMEOUT_MESSAGE + ) ;if + ) ;error + (let ((result (poll))) + (case (and (pair? result) (car result)) + ((complete) (cadr result)) + ((failed) + (error 'kimi-oauth-error + (if (and (pair? (cdr result)) (string? (cadr result))) + (cadr result) + "Device flow failed" + ) ;if + ) ;error + ) ; + (else + (when (eq? (and (pair? result) (car result)) 'slow_down) + (set! slow-down-count (+ slow-down-count 1)) + ;; 服务端给了新 interval 就采信(对齐 pi:WSL/VM 时钟漂移 + ;; 下只靠客户端累加会永远提前轮询);否则按 RFC 8628 +5s + (let ((server-interval (and (pair? (cdr result)) (cadr result)))) + (set! interval-ms + (if (and (number? server-interval) (> server-interval 0)) + (max %minimum-interval-ms (inexact->exact (floor (* server-interval 1000)))) + (max %minimum-interval-ms (+ interval-ms %slow-down-increment-ms)) + ) ;if + ) ;set! + ) ;let + ) ;when + (sleep-interval!) + (loop) + ) ;else + ) ;case + ) ;let + ) ;if + ) ;let + ) ;let* + ) ;define* + + ) ;begin +) ;define-library diff --git a/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm b/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm new file mode 100644 index 00000000..b4acbe08 --- /dev/null +++ b/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm @@ -0,0 +1,436 @@ +;; +;; Copyright (C) 2026 The Goldfish Scheme Authors +;; +;; Licensed under the MIT License +;; + +;; Kimi Code(订阅)OAuth2 设备码流程,翻译自上游 pi 仓库(本地 ~/git/pi) +;; packages/ai/src/auth/oauth/kimi-coding.ts:RFC 8628 设备授权 + +;; refresh_token 刷新,端点 {host}/api/oauth/device_authorization 与 +;; {host}/api/oauth/token,access token 作 Bearer 用于 api.kimi.com/coding。 +;; 默认国内 host auth.kimi.com,KIMI_CODE_OAUTH_HOST / KIMI_OAUTH_HOST 可覆盖 +;; (海外 auth.kimi.ai,账号体系不互通,见 pi issue #9819)。 +(define-library (liii pi ai auth oauth kimi-coding-oauth) + (import (scheme base) + (scheme inexact) + (scheme process-context) + (liii string) + (liii list) + (liii error) + (liii http) + (liii json) + (liii uri) + (liii time) + (liii pi ai time) + (liii pi ai template) + (liii pi ai config credential) + (liii pi ai auth oauth device-flow) + ) ;import + (export KIMI_OAUTH_CLIENT_ID + KIMI_OAUTH_DEFAULT_HOST + kimi-oauth-host + kimi-device-authorize + kimi-poll-token + kimi-refresh-token + kimi-oauth-login + kimi-oauth->auth + kimi-device-authorization? + kimi-device-authorization-device-code + kimi-device-authorization-user-code + kimi-device-authorization-verification-uri + kimi-device-authorization-verification-uri-complete + kimi-device-authorization-interval-seconds + kimi-device-authorization-expires-in-seconds + ;; go worker 会话只能看到导出绑定:worker 调用链上的助手须导出 + ;; (对齐 tui interactive worker 的导出缘由) + %kimi-parse-token-response + %kimi-trusted-http-url + %kimi-post-form + %kimi-token-request-fields + ) ;export + (begin + + (define KIMI_OAUTH_CLIENT_ID "17e5f671-d194-4dfb-9706-5516cb48c098") + (define KIMI_OAUTH_DEFAULT_HOST "https://auth.kimi.com") + (define %device-code-timeout-seconds (* 15 60)) + (define %default-poll-interval-seconds 5) + (define %request-timeout-seconds 30) + (define %refresh-max-retries 3) + + ;; 设备授权响应记录(对应 pi 的 DeviceAuthorization) + (define-record-type + (%make-kimi-device-authorization device-code user-code verification-uri + verification-uri-complete interval-seconds expires-in-seconds + ) ;%make-kimi-device-authorization + kimi-device-authorization? + (device-code kimi-device-authorization-device-code) + (user-code kimi-device-authorization-user-code) + (verification-uri kimi-device-authorization-verification-uri) + (verification-uri-complete kimi-device-authorization-verification-uri-complete) + (interval-seconds kimi-device-authorization-interval-seconds) + (expires-in-seconds kimi-device-authorization-expires-in-seconds) + ) ;define-record-type + + ;; OAuth host:KIMI_CODE_OAUTH_HOST > KIMI_OAUTH_HOST > 默认国内 host, + ;; 去掉尾部斜杠(对应 pi getOauthHost)。opt-env 为 '((name . value) ...) + (define (kimi-oauth-host . opt-env) + (let* ((override (or (%non-empty-env "KIMI_CODE_OAUTH_HOST" opt-env) + (%non-empty-env "KIMI_OAUTH_HOST" opt-env) + ) ;or + ) ;override + (host (or override KIMI_OAUTH_DEFAULT_HOST)) + ) ; + (string-trim-right host #\/) + ) ;let* + ) ;define + + ;; opt-env 兼容两种形态:env-alist 本身,或 lookup-env-var 的 + ;; (env-alist) 包装形态(variadic rest 参直接传入时多一层) + (define (%non-empty-env name opt-env) + (let* ((env + (if (and (pair? opt-env) (pair? (car opt-env)) (string? (caar opt-env))) + (car opt-env) + opt-env + ) ;if + ) ;env + (v + (lookup-env-var name (if (and (pair? env) (pair? (car env))) (list env) '())) + ) ;v + ) ; + (and (string? v) (not (string-null? (string-trim-both v))) (string-trim-both v)) + ) ;let* + ) ;define + + ;; 仅信任 http/https 绝对 URL(对应 pi trustedHttpUrl):登录流程会把 + ;; 服务端返回的 URL 交给浏览器打开,必须挡掉 file: 等自定义协议与 + ;; 控制字符;这里比 pi 更严格,含控制字符直接拒绝 + (define (%kimi-trusted-http-url value) + (and (string? value) + (or (string-starts? value "https://") (string-starts? value "http://")) + (not (string-any (lambda (c) (charstring (car args)) (symbol->string tag)) + ) ;cons + (cons 'text "") + ) ;list + ) ;lambda + ) ;catch + ) ;define + + (define (%resp-field resp key) + (cond ((procedure? resp) (resp key)) + ((hash-table? resp) (resp key)) + ((pair? resp) (cdr (or (assoc key resp) '(#f . #f)))) + (else #f) + ) ;cond + ) ;define + + (define (%read-json resp) + (let ((text (%resp-field resp 'text))) + (and (string? text) + (catch #t + (lambda () (let ((j (string->json text))) (and (pair? j) j))) + (lambda args #f) + ) ;catch + ) ;and + ) ;let + ) ;define + + ;; POST {host}/api/oauth/device_authorization,grant 为 RFC 8628 设备授权 + (define (kimi-device-authorize host) + (let* ((resp (%kimi-post-form (string-append host "/api/oauth/device_authorization") + (list (cons "client_id" KIMI_OAUTH_CLIENT_ID)) + ) ;%kimi-post-form + ) ;resp + (status (or (%resp-field resp 'status-code) 0)) + (body (or (%resp-field resp 'text) "")) + ) ; + (unless (and (>= status 200) (< status 300)) + (error 'kimi-oauth-error + (string-append "Kimi Code device authorization failed with status " + (number->string status) + (if (string-null? body) "" (string-append ": " body)) + ) ;string-append + ) ;error + ) ;unless + (let* ((json (%read-json resp)) + (device-code (and json (json-ref-string json "device_code" #f))) + (user-code (and json (json-ref-string json "user_code" #f))) + (verification-uri (%kimi-trusted-http-url (and json (json-ref json "verification_uri"))) + ) ;verification-uri + (verification-uri-complete (%kimi-trusted-http-url (and json (json-ref json "verification_uri_complete"))) + ) ;verification-uri-complete + (interval (and json (json-ref-number json "interval" #f))) + (expires-in (and json (json-ref-number json "expires_in" #f))) + ) ; + (unless (and device-code user-code verification-uri verification-uri-complete) + (error 'kimi-oauth-error + (string-append "Invalid Kimi Code device authorization response: " body) + ) ;error + ) ;unless + (%make-kimi-device-authorization device-code + user-code + verification-uri + verification-uri-complete + (if (and (number? interval) (finite? interval) (> interval 0)) + interval + %default-poll-interval-seconds + ) ;if + (if (and (number? expires-in) (finite? expires-in) (> expires-in 0)) + expires-in + %device-code-timeout-seconds + ) ;if + ) ;%make-kimi-device-authorization + ) ;let* + ) ;let* + ) ;define + + ;; token 响应解析(对应 pi parseTokenResponse):返回 pi-credential + ;; oauth 记录,expires 为毫秒 epoch(Date.now() + expires_in * 1000) + (define (%kimi-parse-token-response json operation provider region) + (let ((access (and json (json-ref-string json "access_token" #f))) + (refresh (and json (json-ref-string json "refresh_token" #f))) + (expires-in (and json (json-ref-number json "expires_in" #f))) + ) ; + (unless (and access + (not (string-null? access)) + refresh + (not (string-null? refresh)) + (number? expires-in) + (finite? expires-in) + (> expires-in 0) + ) ;and + (error 'kimi-oauth-error + (string-append "Kimi Code token " + operation + " response missing fields: " + (if json (json->string json) "null") + ) ;string-append + ) ;error + ) ;unless + (pi-credential provider + #f + "oauth" + access + refresh + (+ (pi-current-time-millis) (* expires-in 1000)) + region + ) ;pi-credential + ) ;let + ) ;define + + (define (%kimi-token-request-fields device-code) + (list (cons "client_id" KIMI_OAUTH_CLIENT_ID) + (cons "device_code" device-code) + (cons "grant_type" "urn:ietf:params:oauth:grant-type:device_code") + ) ;list + ) ;define + + ;; 单次轮询:把 HTTP 响应映射为 device-flow 四态协议 + (define (%kimi-poll-once host device-code provider region) + (let* ((resp (%kimi-post-form (string-append host "/api/oauth/token") + (%kimi-token-request-fields device-code) + ) ;%kimi-post-form + ) ;resp + (status (or (%resp-field resp 'status-code) 0)) + (json (%read-json resp)) + ) ; + (cond + ((>= status 500) + (let ((body (or (%resp-field resp 'text) ""))) + (list 'failed + (string-append "Kimi Code device token request failed with status " + (number->string status) + (if (string-null? body) "" (string-append ": " body)) + ) ;string-append + ) ;list + ) ;let + ) ; + ((and (>= status 200) + (< status 300) + json + (string? (json-ref-string json "access_token" #f)) + ) ;and + (catch 'kimi-oauth-error + (lambda () + (list 'complete (%kimi-parse-token-response json "poll" provider region)) + ) ;lambda + (lambda (tag msg) (list 'failed msg)) + ) ;catch + ) ; + (else + (let* ((err (and json (json-ref-string json "error" #f))) + (desc (and json (json-ref-string json "error_description" #f))) + (description (if desc (string-append ": " desc) "")) + ) ; + (cond ((equal? err "authorization_pending") '(pending)) + ((equal? err "slow_down") + (let ((interval (and json (json-ref-number json "interval" #f)))) + (list 'slow_down (and (number? interval) (> interval 0) interval)) + ) ;let + ) ; + ((equal? err "expired_token") + '(failed "Kimi Code device authorization expired. Please restart login.") + ) ; + ((equal? err "access_denied") '(failed "Kimi Code login was denied.")) + (else + (list 'failed + (string-append "Kimi Code device token request failed (status " + (number->string status) + ")" + (if err (string-append ": " err description) "") + ) ;string-append + ) ;list + ) ;else + ) ;cond + ) ;let* + ) ;else + ) ;cond + ) ;let* + ) ;define + + ;; 轮询直至授权完成/失败/超时/取消。notify 收到 device_code 事件 + ;; (user-code verification-uri-complete interval expires),cancelled? + ;; 谓词由 TUI 组件层置位 + (define* (kimi-poll-token host device provider region (cancelled? #f)) + (pi-device-flow-poll (lambda () + (%kimi-poll-once host + (kimi-device-authorization-device-code device) + provider + region + ) ;%kimi-poll-once + ) ;lambda + (kimi-device-authorization-interval-seconds device) + (kimi-device-authorization-expires-in-seconds device) + #t + cancelled? + ) ;pi-device-flow-poll + ) ;define* + + ;; refresh_token 刷新,429/5xx/网络错误指数退避重试 3 次 + ;; (1s/2s/4s);401/403/invalid_grant 抛 kimi-oauth-unauthorized, + ;; 调用方据此清除凭据并提示重新 /login + (define (kimi-refresh-token host refresh-token provider region) + (let loop + ((attempt 0) (last-error "Kimi Code token refresh failed")) + (when (> attempt 0) + (sleep (expt 2 (- attempt 1))) + ) ;when + (let* ((resp (%kimi-post-form (string-append host "/api/oauth/token") + (list (cons "client_id" KIMI_OAUTH_CLIENT_ID) + (cons "grant_type" "refresh_token") + (cons "refresh_token" refresh-token) + ) ;list + ) ;%kimi-post-form + ) ;resp + (status (or (%resp-field resp 'status-code) 0)) + (json (%read-json resp)) + ) ; + (cond ((and (>= status 200) (< status 300)) + (%kimi-parse-token-response json "refresh" provider region) + ) ; + ((or (= status 401) + (= status 403) + (and json (equal? (json-ref-string json "error" #f) "invalid_grant")) + ) ;or + (let ((desc (and json (json-ref-string json "error_description" #f)))) + (error 'kimi-oauth-unauthorized + (string-append "Kimi Code token refresh unauthorized (status " + (number->string status) + ")" + (if desc (string-append ": " desc) "") + ) ;string-append + ) ;error + ) ;let + ) ; + ((and (or (= status 429) (>= status 500) (= status 0)) + (< attempt %refresh-max-retries) + ) ;and + (loop (+ attempt 1) + (string-append "Kimi Code token refresh failed with status " + (number->string status) + ) ;string-append + ) ;loop + ) ; + (else + (error 'kimi-oauth-error + (string-append "Kimi Code token refresh failed with status " + (number->string status) + (if json (string-append ": " (json->string json)) "") + ) ;string-append + ) ;error + ) ;else + ) ;cond + ) ;let* + ) ;let + ) ;define + + ;; 完整登录:设备授权 → notify device_code 事件 → 轮询换 token。 + ;; 返回 pi-credential oauth 记录;region 仅在 env 覆盖 host 时记录 + ;; (默认 host 不写 region,1402 §7) + (define* (kimi-oauth-login + (notify #f) + (cancelled? #f) + (provider "kimi-coding") + . + opt-env + ) ; + (let* ((host (kimi-oauth-host (if (pair? opt-env) (car opt-env) '()))) + (region (and (not (string=? host KIMI_OAUTH_DEFAULT_HOST)) host)) + (device (kimi-device-authorize host)) + ) ; + (when notify + (notify (list 'device_code + (kimi-device-authorization-user-code device) + (kimi-device-authorization-verification-uri-complete device) + (kimi-device-authorization-interval-seconds device) + (kimi-device-authorization-expires-in-seconds device) + ) ;list + ) ;notify + ) ;when + (kimi-poll-token host device provider region cancelled?) + ) ;let* + ) ;define* + + ;; 凭据 → 请求头(对应 pi toAuth()):Bearer access token, + ;; openai-completions 的 openai-build-headers 与此等价 + (define (kimi-oauth->auth credential) + (unless (pi-credential-oauth? credential) + (type-error "kimi-oauth->auth: expected oauth pi-credential" credential) + ) ;unless + (list (cons "Authorization" + (string-append "Bearer " (pi-credential-access credential)) + ) ;cons + ) ;list + ) ;define + + ) ;begin +) ;define-library diff --git a/ai/liii/pi/ai/auth/oauth/resolve.scm b/ai/liii/pi/ai/auth/oauth/resolve.scm new file mode 100644 index 00000000..9ca45796 --- /dev/null +++ b/ai/liii/pi/ai/auth/oauth/resolve.scm @@ -0,0 +1,94 @@ +;; +;; Copyright (C) 2026 The Goldfish Scheme Authors +;; +;; Licensed under the MIT License +;; + +;; oauth 凭据解析与透明刷新(1402 §5.2):pi-resolve-provider-key 的 +;; oauth 分支。落盘/清除通过注入的 save!/remove! 回调完成,避免与 +;; (liii pi ai auth) 循环依赖;gfcode 单进程无需文件锁(对应 pi +;; Models.getAuth() 在 store lock 内 refresh 的简化版)。 +(define-library (liii pi ai auth oauth resolve) + (import (scheme base) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) + (liii pi ai time) + ) ;import + (export pi-find-oauth-credential pi-resolve-oauth-credential-key + ;; go worker 会话重求值调用链上的助手须导出 + %pi-refresh-oauth-credential! + ) ;export + (begin + + ;; 在凭据列表中按 provider 精确匹配 oauth 凭据 + (define (pi-find-oauth-credential target auth-list) + (and target + (let loop + ((xs auth-list)) + (if (null? xs) + #f + (let ((item (car xs))) + (if (and (pi-credential-oauth? item) + (equal? (pi-credential-provider item) target) + ) ;and + item + (loop (cdr xs)) + ) ;if + ) ;let + ) ;if + ) ;let + ) ;and + ) ;define + + ;; oauth 凭据的 host:region(登录时落盘的覆盖值)> env 覆盖 > 默认国内 host + (define (%oauth-credential-host cred opt-env) + (or (pi-credential-region cred) + (kimi-oauth-host (if (pair? opt-env) (car opt-env) '())) + ) ;or + ) ;define + + ;; 刷新 oauth 凭据并经 save! 落盘。401/403/invalid_grant 时经 remove! + ;; 清除凭据并返回 #f 触发重新 /login;其余失败(网络/5xx 重试用尽) + ;; 保留凭据返回 #f,不携带失效 token 继续请求。 + ;; save! : (lambda (cred) ...) remove! : (lambda (provider) ...) + (define (%pi-refresh-oauth-credential! cred opt-env save! remove!) + (let* ((provider (pi-credential-provider cred)) + (host (%oauth-credential-host cred opt-env)) + (refreshed + (catch #t + (lambda () + (kimi-refresh-token host (pi-credential-refresh cred) + provider (pi-credential-region cred) + ) ;kimi-refresh-token + ) ;lambda + (lambda (tag . info) (cons tag info)) + ) ;catch + ) ;refreshed + ) ; + (cond + ((pi-credential? refreshed) + (catch #t (lambda () (save! refreshed)) (lambda args #f)) + (pi-credential-access refreshed) + ) ; + ((and (pair? refreshed) (eq? (car refreshed) 'kimi-oauth-unauthorized)) + (catch #t (lambda () (remove! provider)) (lambda args #f)) + #f + ) ; + (else #f) + ) ;cond + ) ;let* + ) ;define + + ;; oauth 凭据 → access token:未过期(留 60s 缓冲)直接返回 access, + ;; 过期则透明刷新并落盘后返回新 access + (define (pi-resolve-oauth-credential-key cred opt-env save! remove!) + (let ((expires (pi-credential-expires cred))) + (if (> expires (+ (pi-current-time-millis) 60000)) + (pi-credential-access cred) + (%pi-refresh-oauth-credential! cred opt-env save! remove!) + ) ;if + ) ;let + ) ;define + + ) ;begin +) ;define-library \ No newline at end of file diff --git a/ai/liii/pi/ai/auth/storage.scm b/ai/liii/pi/ai/auth/storage.scm new file mode 100644 index 00000000..c91be685 --- /dev/null +++ b/ai/liii/pi/ai/auth/storage.scm @@ -0,0 +1,109 @@ +;; +;; Copyright (C) 2026 The Goldfish Scheme Authors +;; +;; Licensed under the MIT License +;; + +;; auth.json 的读取与原子写原语(tmp 文件 + rename + chmod 0600), +;; 供 (liii pi ai auth) 的 api_key 与 oauth 两条持久化路径共用。 +(define-library (liii pi ai auth storage) + (import (scheme base) + (liii string) + (liii path) + (liii json) + (liii list) + (liii error) + (liii os) + ) ;import + (export pi-auth-read-json pi-auth-dir-path pi-auth-replace-entry + pi-auth-write-json! pi-auth-normalize-provider pi-auth-normalize-secret + ) ;export + (begin + + (define (pi-auth-read-json filepath) + (and (path-exists? (path filepath)) + (catch #t + (lambda () (string->json (path-read-text (path filepath)))) + (lambda args #f) + ) ;catch + ) ;and + ) ;define + + ;; 配置目录:显式传入优先,缺省 ~/.gf/agent + (define (pi-auth-dir-path opt-config-dir) + (path (if (and (pair? opt-config-dir) (car opt-config-dir)) + (car opt-config-dir) + (path-join (path-home) ".gf" "agent") + ) ;if + ) ;path + ) ;define + + ;; 替换(或追加)某 provider 的 auth.json 条目,其余条目原样保留 + (define (pi-auth-replace-entry alist p-str entry-fields) + (let ((filtered + (filter + (lambda (entry) + (not + (string=? (if (symbol? (car entry)) (symbol->string (car entry)) (car entry)) + p-str + ) ;string=? + ) ;not + ) ;lambda + alist + ) ;filter + ) ;filtered + ) ; + (append filtered (list (cons p-str entry-fields))) + ) ;let + ) ;define + + ;; 原子写 auth.json:tmp 文件 + rename + chmod 0600 + (define (pi-auth-write-json! dir-path updated) + (let* ((auth-file (path-join dir-path "auth.json")) + (auth-file-str (path->string auth-file)) + (json-str (string-append (json->string updated :indent 2) "\n")) + (tmp-file (string-append auth-file-str ".tmp")) + ) ; + (unless (path-exists? dir-path) + (path-mkdir dir-path :parents #t :exist-ok #t) + ) ;unless + (path-write-text (path tmp-file) json-str) + (when (path-exists? auth-file) + (path-unlink auth-file #t) + ) ;when + (path-rename (path tmp-file) auth-file) + (unless (os-windows?) + (catch #t (lambda () (g_chmod auth-file-str 384)) (lambda args #f)) + ) ;unless + auth-file-str + ) ;let* + ) ;define + + (define (%normalize-non-empty who field value) + (if (not (string? value)) + (type-error (string-append who ": " field " must be a string")) + (let ((trimmed (string-trim-both value))) + (if (string-null? trimmed) + (value-error (string-append who ": " field " cannot be empty")) + trimmed + ) ;if + ) ;let + ) ;if + ) ;define + + (define (pi-auth-normalize-provider who provider) + (cond + ((string? provider) (%normalize-non-empty who "provider" provider)) + ((symbol? provider) + (%normalize-non-empty who "provider" (symbol->string provider)) + ) ; + (else (type-error (string-append who ": provider must be a string or symbol"))) + ) ;cond + ) ;define + + (define (pi-auth-normalize-secret who field value) + (%normalize-non-empty who field value) + ) ;define + + ) ;begin +) ;define-library \ No newline at end of file diff --git a/ai/liii/pi/ai/config/credential.scm b/ai/liii/pi/ai/config/credential.scm index 96126ce1..fbc63b18 100644 --- a/ai/liii/pi/ai/config/credential.scm +++ b/ai/liii/pi/ai/config/credential.scm @@ -8,26 +8,56 @@ (import (scheme base) (liii base) (liii error)) (export pi-credential pi-credential? pi-credential-provider pi-credential-key pi-credential-type pi-credential->json + pi-credential-access pi-credential-refresh pi-credential-expires + pi-credential-region pi-credential-oauth? ) ;export (begin + ;; 凭据记录:type 为 "api_key"(默认,key 承载 API Key)或 "oauth" + ;; (access/refresh/expires 承载 OAuth token,expires 为毫秒 epoch; + ;; region 记录登录时的 OAuth host 覆盖值,默认 host 不写 region, + ;; 对应上游 pi 的 ApiKeyCredential / OAuthCredential,1402 §5.1) (define*-record-type - (pi-credential provider key (type "api_key")) + (pi-credential provider key (type "api_key") + (access #f) (refresh #f) (expires #f) (region #f)) pi-credential? (provider pi-credential-provider) (key pi-credential-key) (type pi-credential-type) + (access pi-credential-access) + (refresh pi-credential-refresh) + (expires pi-credential-expires) + (region pi-credential-region) ) ;define*-record-type + (define (pi-credential-oauth? c) + (and (pi-credential? c) (equal? (pi-credential-type c) "oauth")) + ) ;define + (define (pi-credential->json c) (unless (pi-credential? c) (type-error "pi-credential->json: expected pi-credential" c) ) ;unless - (list (cons "provider" (pi-credential-provider c)) - (cons "type" (pi-credential-type c)) - (cons "key" (pi-credential-key c)) - ) ;list + (if (pi-credential-oauth? c) + ;; oauth 条目形状与 pi 的 auth.json OAuth 条目一致;region 仅在 + ;; 有值(env 覆盖过 host)时落盘 + (append (list (cons "provider" (pi-credential-provider c)) + (cons "type" "oauth") + (cons "access" (pi-credential-access c)) + (cons "refresh" (pi-credential-refresh c)) + (cons "expires" (pi-credential-expires c)) + ) ;list + (if (pi-credential-region c) + (list (cons "region" (pi-credential-region c))) + '() + ) ;if + ) ;append + (list (cons "provider" (pi-credential-provider c)) + (cons "type" (pi-credential-type c)) + (cons "key" (pi-credential-key c)) + ) ;list + ) ;if ) ;define ) ;begin -) ;define-library +) ;define-library \ No newline at end of file diff --git a/ai/liii/pi/ai/providers/kimi-coding.scm b/ai/liii/pi/ai/providers/kimi-coding.scm index c2d1c03c..e1e0db02 100644 --- a/ai/liii/pi/ai/providers/kimi-coding.scm +++ b/ai/liii/pi/ai/providers/kimi-coding.scm @@ -13,11 +13,14 @@ (begin ;; Provider 配置:api 为协议实现标识(对应 api/ 目录),baseUrl 为默认端点, - ;; envKeys 为依次尝试的 API key 环境变量(对应上游 pi providers/.ts 的角色) + ;; envKeys 为依次尝试的 API key 环境变量(对应上游 pi providers/.ts 的角色); + ;; oauth 登记订阅 OAuth 登录方式(RFC 8628 设备码,见 + ;; (liii pi ai auth oauth kimi-coding-oauth)),供 /login 选择器识别 (define PI_KIMI_CODING_PROVIDER '((api . "openai-completions") (baseUrl . "https://api.kimi.com/coding/v1") - (envKeys "KIMI_API_KEY")) + (envKeys "KIMI_API_KEY") + (oauth . "kimi-code")) ) ;define ;; 「额度耗尽」识别:Kimi Coding Plan diff --git a/ai/liii/pi/ai/providers/registry.scm b/ai/liii/pi/ai/providers/registry.scm index 1177087f..acd0b430 100644 --- a/ai/liii/pi/ai/providers/registry.scm +++ b/ai/liii/pi/ai/providers/registry.scm @@ -24,7 +24,7 @@ PI_ALL_IN_ONE_PROVIDER PI_ALL_IN_ONE_BUILTIN_MODELS pi-provider-record pi-provider-api pi-provider-base-url pi-provider-env-keys pi-provider-builtin-models pi-provider-quota-error-handler - pi-provider-quota-error + pi-provider-quota-error pi-provider-oauth ) ;export (begin @@ -105,6 +105,14 @@ ) ;let ) ;define + ;; provider 登记的订阅 OAuth 登录方式标识(如 "kimi-code"); + ;; 未登记返回 #f,/login 选择器据此展示二级选择 + (define (pi-provider-oauth provider) + (let ((record (pi-provider-record provider))) + (and record (%field record 'oauth #f)) + ) ;let + ) ;define + ;; 各 provider 注册的「额度耗尽」识别函数(解析错误码与响应 JSON) ;; 函数签名:(handler status-code body-str) -> 结果 alist 或 #f (define PI_PROVIDER_QUOTA_ERROR_HANDLERS diff --git a/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_CANCEL_MESSAGE-test.scm b/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_CANCEL_MESSAGE-test.scm new file mode 100644 index 00000000..b200bd02 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_CANCEL_MESSAGE-test.scm @@ -0,0 +1,23 @@ +;; PI_DEVICE_FLOW_CANCEL_MESSAGE +;; 设备码轮询被取消时的错误消息常量。 +;; +;; 语法 +;; ---- +;; PI_DEVICE_FLOW_CANCEL_MESSAGE -> string? +;; +;; 参数 +;; ---- +;; 无。 +;; +;; 返回值 +;; ---- +;; string? +;; 固定为 "Login cancelled"(对齐上游 pi)。 + +(import (liii check) (liii pi ai auth oauth device-flow)) + +(check-set-mode! 'report-failed) + +(check PI_DEVICE_FLOW_CANCEL_MESSAGE => "Login cancelled") + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE-test.scm b/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE-test.scm new file mode 100644 index 00000000..e4185661 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE-test.scm @@ -0,0 +1,25 @@ +;; PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE +;; slow_down 后超时的错误消息常量(提示 WSL/VM 时钟漂移)。 +;; +;; 语法 +;; ---- +;; PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE -> string? +;; +;; 参数 +;; ---- +;; 无。 +;; +;; 返回值 +;; ---- +;; string? +;; 含 slow_down 与时钟同步提示的固定消息(对齐上游 pi)。 + +(import (liii check) (liii string) (liii pi ai auth oauth device-flow)) + +(check-set-mode! 'report-failed) + +(check-true (string-contains? PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE "slow_down") +) ;check-true +(check-true (string-contains? PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE "clock")) + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_TIMEOUT_MESSAGE-test.scm b/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_TIMEOUT_MESSAGE-test.scm new file mode 100644 index 00000000..a566f723 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/device-flow/PI_DEVICE_FLOW_TIMEOUT_MESSAGE-test.scm @@ -0,0 +1,23 @@ +;; PI_DEVICE_FLOW_TIMEOUT_MESSAGE +;; 设备码轮询超时(无 slow_down)时的错误消息常量。 +;; +;; 语法 +;; ---- +;; PI_DEVICE_FLOW_TIMEOUT_MESSAGE -> string? +;; +;; 参数 +;; ---- +;; 无。 +;; +;; 返回值 +;; ---- +;; string? +;; 固定为 "Device flow timed out"(对齐上游 pi)。 + +(import (liii check) (liii pi ai auth oauth device-flow)) + +(check-set-mode! 'report-failed) + +(check PI_DEVICE_FLOW_TIMEOUT_MESSAGE => "Device flow timed out") + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/device-flow/pi-device-flow-poll-test.scm b/ai/tests/liii/pi/ai/auth/oauth/device-flow/pi-device-flow-poll-test.scm new file mode 100644 index 00000000..590a1c46 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/device-flow/pi-device-flow-poll-test.scm @@ -0,0 +1,130 @@ +;; pi-device-flow-poll +;; RFC 8628 设备码通用轮询循环:pending/slow_down/failed/complete 四态。 +;; +;; 语法 +;; ---- +;; (pi-device-flow-poll poll) +;; (pi-device-flow-poll poll interval-seconds expires-in-seconds wait-before-first-poll? cancelled?) +;; +;; 参数 +;; ---- +;; poll : procedure? +;; 零参过程,返回 (pending) / (slow_down [interval]) / (failed msg) / (complete value)。 +;; +;; interval-seconds : number? +;; 轮询间隔秒数(最小 1s,默认 5s)。 +;; +;; expires-in-seconds : number? 或 #f +;; 总超时秒数;#f 表示不限时。 +;; +;; wait-before-first-poll? : boolean? +;; #t 时首轮先等一个 interval(Kimi 流程语义)。 +;; +;; cancelled? : procedure? 或 #f +;; 取消谓词;置位时抛 kimi-oauth-cancelled。 +;; +;; 返回值 +;; ---- +;; any +;; complete 的 value;failed/取消/超时抛 kimi-oauth-error / kimi-oauth-cancelled。 + +(import (scheme base) + (liii check) + (liii string) + (liii pi ai auth oauth device-flow) +) ;import + +(check-set-mode! 'report-failed) + +(check-catch 'type-error (pi-device-flow-poll "not-a-proc")) + +;; 1. 立即 complete +(check (pi-device-flow-poll (lambda () '(complete ok)) 0.01 10 #f #f) => 'ok) + +;; 2. pending 两次后 complete +(let ((n 0)) + (check + (pi-device-flow-poll (lambda () (set! n (+ n 1)) (if (< n 3) '(pending) '(complete done))) + 0.01 + 10 + #f + #f + ) ;pi-device-flow-poll + => + 'done + ) ;check + (check n => 3) +) ;let + +;; 3. failed 抛 kimi-oauth-error 且携带消息 +(check-catch 'kimi-oauth-error + (pi-device-flow-poll (lambda () '(failed "denied by user")) 0.01 10 #f #f) +) ;check-catch +(let ((msg + (catch 'kimi-oauth-error + (lambda () + (pi-device-flow-poll (lambda () '(failed "denied by user")) 0.01 10 #f #f) + ) ;lambda + (lambda (tag . info) (caar info)) + ) ;catch + ) ;msg + ) ; + (check msg => "denied by user") +) ;let + +;; 4. 超时(expires 已过)抛超时错误 +(check-catch 'kimi-oauth-error + (pi-device-flow-poll (lambda () '(pending)) 1 0 #f #f) +) ;check-catch + +;; 5. slow_down 后超时:错误消息提示时钟漂移 +(let ((msg + (catch 'kimi-oauth-error + (lambda () (pi-device-flow-poll (lambda () '(slow_down)) 1 0.001 #f #f)) + (lambda (tag . info) (caar info)) + ) ;catch + ) ;msg + ) ; + (check-true (string-contains? msg "slow_down")) +) ;let + +;; 6. slow_down 携带服务端新 interval,随后 complete +(let ((n 0)) + (check + (pi-device-flow-poll + (lambda () + (set! n (+ n 1)) + (case n + ((1) '(slow_down 0.01)) + ((2) '(pending)) + (else '(complete late)) + ) ;case + ) ;lambda + 0.01 + 30 + #f + #f + ) ;pi-device-flow-poll + => + 'late + ) ;check +) ;let + +;; 7. 取消谓词置位:抛 kimi-oauth-cancelled +(check-catch 'kimi-oauth-cancelled + (pi-device-flow-poll (lambda () '(pending)) 0.01 10 #f (lambda () #t)) +) ;check-catch + +;; 8. wait-before-first-poll? 首轮先等待(用取消谓词在等待中生效验证) +(let ((cancelled #f)) + (check-catch 'kimi-oauth-cancelled + (pi-device-flow-poll (lambda () (set! cancelled #t) '(pending)) + 3 + 30 + #t + (lambda () cancelled) + ) ;pi-device-flow-poll + ) ;check-catch +) ;let + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_CLIENT_ID-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_CLIENT_ID-test.scm new file mode 100644 index 00000000..ce247710 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_CLIENT_ID-test.scm @@ -0,0 +1,23 @@ +;; KIMI_OAUTH_CLIENT_ID +;; Kimi Code OAuth 应用的 client_id 常量。 +;; +;; 语法 +;; ---- +;; KIMI_OAUTH_CLIENT_ID -> string? +;; +;; 参数 +;; ---- +;; 无。 +;; +;; 返回值 +;; ---- +;; string? +;; 与上游 pi kimi-coding.ts 一致的固定 UUID。 + +(import (liii check) (liii pi ai auth oauth kimi-coding-oauth)) + +(check-set-mode! 'report-failed) + +(check KIMI_OAUTH_CLIENT_ID => "17e5f671-d194-4dfb-9706-5516cb48c098") + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_DEFAULT_HOST-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_DEFAULT_HOST-test.scm new file mode 100644 index 00000000..823250b6 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/KIMI_OAUTH_DEFAULT_HOST-test.scm @@ -0,0 +1,23 @@ +;; KIMI_OAUTH_DEFAULT_HOST +;; Kimi Code OAuth 默认(国内)host 常量。 +;; +;; 语法 +;; ---- +;; KIMI_OAUTH_DEFAULT_HOST -> string? +;; +;; 参数 +;; ---- +;; 无。 +;; +;; 返回值 +;; ---- +;; string? +;; 固定为 https://auth.kimi.com。 + +(import (liii check) (liii pi ai auth oauth kimi-coding-oauth)) + +(check-set-mode! 'report-failed) + +(check KIMI_OAUTH_DEFAULT_HOST => "https://auth.kimi.com") + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-device-code-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-device-code-test.scm new file mode 100644 index 00000000..30c5b550 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-device-code-test.scm @@ -0,0 +1,52 @@ +;; kimi-device-authorization-device-code +;; 读取设备授权记录的 device_code。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization-device-code device) -> string? +;; +;; 参数 +;; ---- +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的记录。 +;; +;; 返回值 +;; ---- +;; string? +;; 轮询 token 端点用的设备码。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check (kimi-device-authorization-device-code (kimi-device-authorize host)) + => + "stub-device-code" + ) ;check + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-expires-in-seconds-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-expires-in-seconds-test.scm new file mode 100644 index 00000000..a770c6bc --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-expires-in-seconds-test.scm @@ -0,0 +1,52 @@ +;; kimi-device-authorization-expires-in-seconds +;; 读取设备授权记录的有效期秒数。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization-expires-in-seconds device) -> number? +;; +;; 参数 +;; ---- +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的记录。 +;; +;; 返回值 +;; ---- +;; number? +;; 服务端 expires_in;缺失/非法时回退 900(15 分钟,对齐 pi)。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check (kimi-device-authorization-expires-in-seconds (kimi-device-authorize host)) + => + 900 + ) ;check + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-interval-seconds-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-interval-seconds-test.scm new file mode 100644 index 00000000..c4a48db1 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-interval-seconds-test.scm @@ -0,0 +1,52 @@ +;; kimi-device-authorization-interval-seconds +;; 读取设备授权记录的轮询间隔秒数。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization-interval-seconds device) -> number? +;; +;; 参数 +;; ---- +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的记录。 +;; +;; 返回值 +;; ---- +;; number? +;; 服务端 interval;缺失/非法时回退 5(RFC 8628 §3.2)。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check (kimi-device-authorization-interval-seconds (kimi-device-authorize host)) + => + 1 + ) ;check + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-p-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-p-test.scm new file mode 100644 index 00000000..97d13e70 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-p-test.scm @@ -0,0 +1,53 @@ +;; kimi-device-authorization? +;; 判断对象是否为设备授权响应记录。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization? obj) -> boolean? +;; +;; 参数 +;; ---- +;; obj : any +;; 任意对象。 +;; +;; 返回值 +;; ---- +;; boolean? +;; kimi-device-authorize 返回的记录为 #t,其余 #f。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(check-false (kimi-device-authorization? "device")) +(check-false (kimi-device-authorization? #f)) +(check-false (kimi-device-authorization? '(device_code . "x"))) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check-true (kimi-device-authorization? (kimi-device-authorize host))) + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-user-code-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-user-code-test.scm new file mode 100644 index 00000000..eba5a3ab --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-user-code-test.scm @@ -0,0 +1,52 @@ +;; kimi-device-authorization-user-code +;; 读取设备授权记录的 user_code(用户在浏览器输入的短码)。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization-user-code device) -> string? +;; +;; 参数 +;; ---- +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的记录。 +;; +;; 返回值 +;; ---- +;; string? +;; 形如 ABCD-1234 的用户码。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check (kimi-device-authorization-user-code (kimi-device-authorize host)) + => + "ABCD-1234" + ) ;check + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-complete-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-complete-test.scm new file mode 100644 index 00000000..28178d74 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-complete-test.scm @@ -0,0 +1,53 @@ +;; kimi-device-authorization-verification-uri-complete +;; 读取设备授权记录的 verification_uri_complete(带 user_code 的验证页)。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization-verification-uri-complete device) -> string? +;; +;; 参数 +;; ---- +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的记录。 +;; +;; 返回值 +;; ---- +;; string? +;; 浏览器直接打开即可完成授权的 URL。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check (kimi-device-authorization-verification-uri-complete (kimi-device-authorize host) + ) ;kimi-device-authorization-verification-uri-complete + => + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234" + ) ;check + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-test.scm new file mode 100644 index 00000000..5128ae2a --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorization-verification-uri-test.scm @@ -0,0 +1,52 @@ +;; kimi-device-authorization-verification-uri +;; 读取设备授权记录的 verification_uri(不含 user_code 的验证页)。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorization-verification-uri device) -> string? +;; +;; 参数 +;; ---- +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的记录。 +;; +;; 返回值 +;; ---- +;; string? +;; 已通过 http/https 白名单校验的验证 URL。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check (kimi-device-authorization-verification-uri (kimi-device-authorize host)) + => + "https://www.kimi.com/code" + ) ;check + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorize-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorize-test.scm new file mode 100644 index 00000000..80f93b5e --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-device-authorize-test.scm @@ -0,0 +1,98 @@ +;; kimi-device-authorize +;; 发起 RFC 8628 设备授权:POST {host}/api/oauth/device_authorization。 +;; +;; 语法 +;; ---- +;; (kimi-device-authorize host) -> kimi-device-authorization? +;; +;; 参数 +;; ---- +;; host : string? +;; OAuth host(如 https://auth.kimi.com 或本地 stub)。 +;; +;; 返回值 +;; ---- +;; kimi-device-authorization? +;; 含 device-code/user-code/verification-uri(-complete)/interval/expires 的记录。 +;; 非 2xx 或字段缺失抛 kimi-oauth-error。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define (find-stub) + (let loop + ((candidates '("tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + "stub_kimi_oauth_server.py") + ) ;candidates + ) ; + (cond ((null? candidates) + (error 'file-not-found "stub_kimi_oauth_server.py not found") + ) ; + ((file-exists? (car candidates)) (car candidates)) + (else (loop (cdr candidates))) + ) ;cond + ) ;let +) ;define + +;; 正常设备授权(本地 stub) +(let* ((proc (process-spawn (list "python3" (find-stub) "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check-true (number? port)) + (let ((device (kimi-device-authorize host))) + (check-true (kimi-device-authorization? device)) + (check (kimi-device-authorization-device-code device) => "stub-device-code") + (check (kimi-device-authorization-user-code device) => "ABCD-1234") + (check (kimi-device-authorization-verification-uri device) + => + "https://www.kimi.com/code" + ) ;check + (check (kimi-device-authorization-verification-uri-complete device) + => + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234" + ) ;check + (check (kimi-device-authorization-interval-seconds device) => 1) + (check (kimi-device-authorization-expires-in-seconds device) => 900) + ) ;let + (process-kill proc) +) ;let* + +;; 500:抛 kimi-oauth-error +(let* ((proc (process-spawn (list "python3" (find-stub) "authorize-500") :stdout 'pipe) + ) ;proc + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check-catch 'kimi-oauth-error (kimi-device-authorize host)) + (process-kill proc) +) ;let* + +;; 200 但字段缺失:抛 kimi-oauth-error +(let* ((proc (process-spawn (list "python3" (find-stub) "authorize-bad") :stdout 'pipe) + ) ;proc + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (check-catch 'kimi-oauth-error (kimi-device-authorize host)) + (process-kill proc) +) ;let* + +;; 网络不可达:status 0 归一为 kimi-oauth-error +(check-catch 'kimi-oauth-error (kimi-device-authorize "http://127.0.0.1:1")) + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-host-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-host-test.scm new file mode 100644 index 00000000..caeaf9f5 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-host-test.scm @@ -0,0 +1,58 @@ +;; kimi-oauth-host +;; 解析 OAuth host:KIMI_CODE_OAUTH_HOST > KIMI_OAUTH_HOST > 默认国内 host。 +;; +;; 语法 +;; ---- +;; (kimi-oauth-host) +;; (kimi-oauth-host opt-env) +;; +;; 参数 +;; ---- +;; opt-env : list? +;; 自定义环境变量关联表 ((name . value) ...)。 +;; +;; 返回值 +;; ---- +;; string? +;; 去掉尾部斜杠的 host;无覆盖时为 https://auth.kimi.com。 + +(import (liii check) (liii pi ai auth oauth kimi-coding-oauth)) + +(check-set-mode! 'report-failed) + +;; 显式空 env:默认国内 host +(check (kimi-oauth-host '()) => "https://auth.kimi.com") + +;; KIMI_CODE_OAUTH_HOST 覆盖(含尾斜杠剥离) +(check (kimi-oauth-host '(("KIMI_CODE_OAUTH_HOST" . "https://auth.kimi.ai/"))) + => + "https://auth.kimi.ai" +) ;check + +;; KIMI_OAUTH_HOST 兜底 +(check (kimi-oauth-host '(("KIMI_OAUTH_HOST" . "https://auth.kimi.ai"))) + => + "https://auth.kimi.ai" +) ;check + +;; 优先级:KIMI_CODE_OAUTH_HOST > KIMI_OAUTH_HOST +(check (kimi-oauth-host '(("KIMI_OAUTH_HOST" . "https://b.example") + ("KIMI_CODE_OAUTH_HOST" . "https://a.example")) + ) ;kimi-oauth-host + => + "https://a.example" +) ;check + +;; 空白覆盖值视为未设置 +(check (kimi-oauth-host '(("KIMI_CODE_OAUTH_HOST" . " "))) + => + "https://auth.kimi.com" +) ;check + +;; 本地 stub host +(check (kimi-oauth-host '(("KIMI_CODE_OAUTH_HOST" . "http://127.0.0.1:8080"))) + => + "http://127.0.0.1:8080" +) ;check + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-login-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-login-test.scm new file mode 100644 index 00000000..c7bbbf46 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-login-test.scm @@ -0,0 +1,94 @@ +;; kimi-oauth-login +;; 完整设备码登录:设备授权 → notify device_code 事件 → 轮询换 token。 +;; +;; 语法 +;; ---- +;; (kimi-oauth-login) +;; (kimi-oauth-login notify cancelled? provider opt-env) +;; +;; 参数 +;; ---- +;; notify : procedure? 或 #f +;; 接收 (device_code user-code uri interval expires) 事件的回调。 +;; +;; cancelled? : procedure? 或 #f +;; 取消谓词。 +;; +;; provider : string? +;; 凭据归属服务商,默认 "kimi-coding"。 +;; +;; opt-env : list? +;; 自定义环境变量表(KIMI_CODE_OAUTH_HOST 覆盖 host)。 +;; +;; 返回值 +;; ---- +;; pi-credential? +;; type=oauth 凭据;env 覆盖 host 时 region 记录覆盖值,默认 host 不写。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (events '()) + ) ; + ;; 1. notify 收到 device_code 事件;凭据带 region(env 覆盖了 host) + (let ((cred + (kimi-oauth-login (lambda (ev) (set! events (cons ev events))) + #f + "kimi-coding" + (list (cons "KIMI_CODE_OAUTH_HOST" host)) + ) ;kimi-oauth-login + ) ;cred + ) ; + (check (length events) => 1) + (let ((ev (car events))) + (check (car ev) => 'device_code) + (check (cadr ev) => "ABCD-1234") + (check (caddr ev) + => + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234" + ) ;check + (check (cadddr ev) => 1) + (check (car (cddddr ev)) => 900) + ) ;let + (check-true (pi-credential-oauth? cred)) + (check (pi-credential-access cred) => "stub-access-token") + (check (pi-credential-region cred) => host) + ) ;let + + ;; 2. 取消谓词已置位:kimi-oauth-cancelled + (check-catch 'kimi-oauth-cancelled + (kimi-oauth-login #f + (lambda () #t) + "kimi-coding" + (list (cons "KIMI_CODE_OAUTH_HOST" host)) + ) ;kimi-oauth-login + ) ;check-catch + + (process-kill proc) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-to-auth-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-to-auth-test.scm new file mode 100644 index 00000000..7b55e2b8 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-oauth-to-auth-test.scm @@ -0,0 +1,35 @@ +;; kimi-oauth->auth +;; oauth 凭据转请求头:Authorization: Bearer 。 +;; +;; 语法 +;; ---- +;; (kimi-oauth->auth credential) -> alist +;; +;; 参数 +;; ---- +;; credential : pi-credential? +;; type 为 oauth 的凭据。 +;; +;; 返回值 +;; ---- +;; alist +;; (("Authorization" . "Bearer ")),与 pi toAuth() 等价。 +;; 非 oauth 凭据抛 type-error。 + +(import (liii check) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-tok" "ref" 1893456000000 #f))) + (check (kimi-oauth->auth c) => '(("Authorization" . "Bearer acc-tok"))) +) ;let + +(check-catch 'type-error + (kimi-oauth->auth (pi-credential "kimi-coding" "sk-api" "api_key")) +) ;check-catch +(check-catch 'type-error (kimi-oauth->auth "not-a-credential")) + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-poll-token-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-poll-token-test.scm new file mode 100644 index 00000000..298bac77 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-poll-token-test.scm @@ -0,0 +1,143 @@ +;; kimi-poll-token +;; 设备码轮询换取 token:POST {host}/api/oauth/token(device_code grant)。 +;; +;; 语法 +;; ---- +;; (kimi-poll-token host device provider region) +;; (kimi-poll-token host device provider region cancelled?) +;; +;; 参数 +;; ---- +;; host : string? +;; OAuth host。 +;; +;; device : kimi-device-authorization? +;; kimi-device-authorize 返回的设备授权记录。 +;; +;; provider : string? +;; 凭据归属的服务商 id。 +;; +;; region : string? 或 #f +;; 登录时的 host 覆盖值(写入凭据 region 字段)。 +;; +;; cancelled? : procedure? 或 #f +;; 取消谓词。 +;; +;; 返回值 +;; ---- +;; pi-credential? +;; type=oauth 的凭据(access/refresh/expires);失败/拒绝/超时抛 +;; kimi-oauth-error,取消抛 kimi-oauth-cancelled。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(define (with-stub scenario body) + (let* ((proc (process-spawn (list "python3" stub-file scenario) :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (let ((result (body host))) + (process-kill proc) + result + ) ;let + ) ;let* +) ;define + +;; 1. pending 一次后 complete:得到 oauth 凭据 +(with-stub "ok" + (lambda (host) + (let* ((device (kimi-device-authorize host)) + (cred (kimi-poll-token host device "kimi-coding" #f)) + ) ; + (check-true (pi-credential-oauth? cred)) + (check (pi-credential-provider cred) => "kimi-coding") + (check (pi-credential-access cred) => "stub-access-token") + (check (pi-credential-refresh cred) => "stub-refresh-token") + (check-true (> (pi-credential-expires cred) 0)) + (check (pi-credential-region cred) => #f) + ) ;let* + ) ;lambda +) ;with-stub + +;; 2. region 透传到凭据 +(with-stub "ok" + (lambda (host) + (let* ((device (kimi-device-authorize host)) + (cred (kimi-poll-token host device "kimi-coding" host)) + ) ; + (check (pi-credential-region cred) => host) + ) ;let* + ) ;lambda +) ;with-stub + +;; 3. slow_down 后 complete +(with-stub "slow-down" + (lambda (host) + (let* ((device (kimi-device-authorize host)) + (cred (kimi-poll-token host device "kimi-coding" #f)) + ) ; + (check (pi-credential-access cred) => "stub-access-token") + ) ;let* + ) ;lambda +) ;with-stub + +;; 4. access_denied / expired_token / 500:kimi-oauth-error +(with-stub "denied" + (lambda (host) + (check-catch 'kimi-oauth-error + (kimi-poll-token host (kimi-device-authorize host) "kimi-coding" #f) + ) ;check-catch + ) ;lambda +) ;with-stub +(with-stub "expired" + (lambda (host) + (check-catch 'kimi-oauth-error + (kimi-poll-token host (kimi-device-authorize host) "kimi-coding" #f) + ) ;check-catch + ) ;lambda +) ;with-stub +(with-stub "poll-500" + (lambda (host) + (check-catch 'kimi-oauth-error + (kimi-poll-token host (kimi-device-authorize host) "kimi-coding" #f) + ) ;check-catch + ) ;lambda +) ;with-stub + +;; 5. 取消谓词:kimi-oauth-cancelled +(with-stub "ok" + (lambda (host) + (check-catch 'kimi-oauth-cancelled + (kimi-poll-token host + (kimi-device-authorize host) + "kimi-coding" + #f + (lambda () #t) + ) ;kimi-poll-token + ) ;check-catch + ) ;lambda +) ;with-stub + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-refresh-token-test.scm b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-refresh-token-test.scm new file mode 100644 index 00000000..4979f543 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/kimi-refresh-token-test.scm @@ -0,0 +1,114 @@ +;; kimi-refresh-token +;; refresh_token 刷新:429/5xx/网络错误退避重试 3 次,401/403/invalid_grant +;; 抛 kimi-oauth-unauthorized。 +;; +;; 语法 +;; ---- +;; (kimi-refresh-token host refresh-token provider region) -> pi-credential? +;; +;; 参数 +;; ---- +;; host : string? +;; OAuth host。 +;; +;; refresh-token : string? +;; 已存的 refresh token。 +;; +;; provider : string? +;; 凭据归属服务商。 +;; +;; region : string? 或 #f +;; 透传到新凭据的 region。 +;; +;; 返回值 +;; ---- +;; pi-credential? +;; 新 oauth 凭据;401/403/invalid_grant 抛 kimi-oauth-unauthorized, +;; 其余失败抛 kimi-oauth-error。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +(define (with-stub scenario body) + (let* ((proc (process-spawn (list "python3" stub-file scenario) :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (let ((result (body host))) + (process-kill proc) + result + ) ;let + ) ;let* +) ;define + +;; 1. 正常刷新:新 access/refresh/expires,region 透传 +(with-stub "refresh-ok" + (lambda (host) + (let ((cred (kimi-refresh-token host "stub-refresh-token" "kimi-coding" host))) + (check-true (pi-credential-oauth? cred)) + (check (pi-credential-access cred) => "stub-access-token-2") + (check (pi-credential-refresh cred) => "stub-refresh-token-2") + (check-true (> (pi-credential-expires cred) 0)) + (check (pi-credential-region cred) => host) + ) ;let + ) ;lambda +) ;with-stub + +;; 2. 401 invalid_grant:kimi-oauth-unauthorized +(with-stub "refresh-401" + (lambda (host) + (check-catch 'kimi-oauth-unauthorized + (kimi-refresh-token host "stub-refresh-token" "kimi-coding" #f) + ) ;check-catch + ) ;lambda +) ;with-stub + +;; 3. 403:kimi-oauth-unauthorized +(with-stub "refresh-403" + (lambda (host) + (check-catch 'kimi-oauth-unauthorized + (kimi-refresh-token host "stub-refresh-token" "kimi-coding" #f) + ) ;check-catch + ) ;lambda +) ;with-stub + +;; 4. 429 两次后 200:退避重试成功(1s+2s 退避) +(with-stub "refresh-flaky" + (lambda (host) + (let ((cred (kimi-refresh-token host "stub-refresh-token" "kimi-coding" #f))) + (check (pi-credential-access cred) => "stub-access-token-2") + ) ;let + ) ;lambda +) ;with-stub + +;; 5. 持续 500:重试用尽后 kimi-oauth-error(1+2+4s 退避) +(with-stub "refresh-500" + (lambda (host) + (check-catch 'kimi-oauth-error + (kimi-refresh-token host "stub-refresh-token" "kimi-coding" #f) + ) ;check-catch + ) ;lambda +) ;with-stub + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-find-oauth-credential-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-find-oauth-credential-test.scm new file mode 100644 index 00000000..b40d9ba6 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-find-oauth-credential-test.scm @@ -0,0 +1,45 @@ +;; pi-find-oauth-credential +;; 在凭据列表中按 provider 精确匹配 oauth 凭据。 +;; +;; 语法 +;; ---- +;; (pi-find-oauth-credential target auth-list) -> pi-credential? 或 #f +;; +;; 参数 +;; ---- +;; target : string? 或 #f +;; 服务商 id。 +;; +;; auth-list : list? +;; pi-load-auth 返回的凭据列表。 +;; +;; 返回值 +;; ---- +;; pi-credential? 或 #f +;; 匹配到的 oauth 凭据;api_key 条目不匹配。 + +(import (liii check) + (liii pi ai config credential) + (liii pi ai auth oauth resolve) +) ;import + +(check-set-mode! 'report-failed) + +(define *oauth* + (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f) +) ;define + +(define *api-key* (pi-credential "kimi-coding" "sk-x" "api_key")) + +(define *other* (pi-credential "deepseek" "sk-ds" "api_key")) + +(check (pi-find-oauth-credential "kimi-coding" (list *other* *oauth*)) + => + *oauth* +) ;check +(check (pi-find-oauth-credential "kimi-coding" (list *api-key*)) => #f) +(check (pi-find-oauth-credential "deepseek" (list *other* *oauth*)) => #f) +(check (pi-find-oauth-credential "kimi-coding" '()) => #f) +(check (pi-find-oauth-credential #f (list *oauth*)) => #f) + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-resolve-oauth-credential-key-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-resolve-oauth-credential-key-test.scm new file mode 100644 index 00000000..49e1694d --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-resolve-oauth-credential-key-test.scm @@ -0,0 +1,163 @@ +;; pi-resolve-oauth-credential-key +;; oauth 凭据解析:未过期(60s 缓冲)直接返回 access,过期透明刷新并落盘。 +;; +;; 语法 +;; ---- +;; (pi-resolve-oauth-credential-key cred opt-env save! remove!) -> string? 或 #f +;; +;; 参数 +;; ---- +;; cred : pi-credential? +;; oauth 凭据。 +;; +;; opt-env : list? +;; 自定义环境变量表(KIMI_CODE_OAUTH_HOST 覆盖)。 +;; +;; save! : procedure? +;; 刷新成功后的落盘回调 (lambda (new-cred) ...)。 +;; +;; remove! : procedure? +;; 401/403/invalid_grant 时的清除回调 (lambda (provider) ...)。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; 生效 access token;刷新失败返回 #f(unauthorized 时已调 remove!)。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai time) + (liii pi ai config credential) + (liii pi ai auth oauth resolve) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +;; 1. 未过期:直接返回 access,不触发回调 +(let* ((cred (pi-credential "kimi-coding" + #f + "oauth" + "fresh-acc" + "ref" + (+ (pi-current-time-millis) 3600000) + #f + ) ;pi-credential + ) ;cred + (saved '()) + (removed '()) + ) ; + (check + (pi-resolve-oauth-credential-key cred + '() + (lambda (c) (set! saved (cons c saved))) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-resolve-oauth-credential-key + => + "fresh-acc" + ) ;check + (check saved => '()) + (check removed => '()) +) ;let* + +;; 2. 60s 缓冲内视为过期:走刷新 +(let* ((proc (process-spawn (list "python3" stub-file "refresh-ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "stub-refresh-token" + (+ (pi-current-time-millis) 30000) + host + ) ;pi-credential + ) ;cred + (saved '()) + (removed '()) + ) ; + (check + (pi-resolve-oauth-credential-key cred + '() + (lambda (c) (set! saved (cons c saved))) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-resolve-oauth-credential-key + => + "stub-access-token-2" + ) ;check + (check (length saved) => 1) + (check (pi-credential-refresh (car saved)) => "stub-refresh-token-2") + (check removed => '()) + (process-kill proc) +) ;let* + +;; 3. 已过期 + 401 invalid_grant:remove! 被调用,返回 #f +(let* ((proc (process-spawn (list "python3" stub-file "refresh-401") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "stub-refresh-token" + (- (pi-current-time-millis) 1000) + host + ) ;pi-credential + ) ;cred + (saved '()) + (removed '()) + ) ; + (check + (pi-resolve-oauth-credential-key cred + '() + (lambda (c) (set! saved (cons c saved))) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-resolve-oauth-credential-key + => + #f + ) ;check + (check saved => '()) + (check removed => '("kimi-coding")) + (process-kill proc) +) ;let* + +;; 4. 网络不可达(region 指向死端口):保留凭据(不 remove),返回 #f +(let* ((cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "ref" + (- (pi-current-time-millis) 1000) + "http://127.0.0.1:1" + ) ;pi-credential + ) ;cred + (removed '()) + ) ; + (check + (pi-resolve-oauth-credential-key cred + '() + (lambda (c) #f) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-resolve-oauth-credential-key + => + #f + ) ;check + (check removed => '()) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/pi-remove-auth-provider-bang-test.scm b/ai/tests/liii/pi/ai/auth/pi-remove-auth-provider-bang-test.scm new file mode 100644 index 00000000..7939bcbe --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/pi-remove-auth-provider-bang-test.scm @@ -0,0 +1,63 @@ +;; pi-remove-auth-provider! +;; 清除 auth.json 中某服务商的凭据条目(oauth 刷新失败时调用)。 +;; +;; 语法 +;; ---- +;; (pi-remove-auth-provider! provider) +;; (pi-remove-auth-provider! provider opt-config-dir) +;; +;; 参数 +;; ---- +;; provider : (or string? symbol?) +;; 服务商标识。 +;; +;; opt-config-dir : (or string? path?) +;; 可选,配置目录(默认 ~/.gf/agent)。 +;; +;; 返回值 +;; ---- +;; string? +;; auth.json 文件路径(文件不存在时不创建,直接返回路径)。 + +(import (liii check) + (liii path) + (liii list) + (liii tempfile) + (liii pi ai config credential) + (liii pi ai auth) +) ;import + +(check-set-mode! 'report-failed) + +;; 1. 参数校验 +(check-catch 'type-error (pi-remove-auth-provider! 1)) +(check-catch 'value-error (pi-remove-auth-provider! " ")) + +;; 2. 文件不存在:返回路径且不创建文件 +(let* ((tmp (make-temp-dir "gf-auth-remove-" "")) + (target (pi-remove-auth-provider! "kimi-coding" tmp)) + ) ; + (check-true (string? target)) + (check-false (path-exists? (path target))) + (path-rmdir tmp) +) ;let* + +;; 3. 清除 oauth 条目,不破坏其它服务商 +(let* ((tmp (make-temp-dir "gf-auth-remove-" "")) + (_ (pi-save-auth-key "deepseek" "sk-ds" tmp)) + (_ (pi-save-auth-oauth! "kimi-coding" "acc" "ref" 1893456000000 #f tmp)) + ) ; + (check (length (pi-load-auth tmp)) => 2) + (pi-remove-auth-provider! 'kimi-coding tmp) + (let ((creds (pi-load-auth tmp))) + (check (length creds) => 1) + (check (pi-credential-provider (car creds)) => "deepseek") + ) ;let + ;; 幂等:再次清除不报错 + (pi-remove-auth-provider! "kimi-coding" tmp) + (check (length (pi-load-auth tmp)) => 1) + (path-unlink (path (path-join tmp "auth.json"))) + (path-rmdir tmp) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/pi-resolve-provider-key-oauth-test.scm b/ai/tests/liii/pi/ai/auth/pi-resolve-provider-key-oauth-test.scm new file mode 100644 index 00000000..51dff40d --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/pi-resolve-provider-key-oauth-test.scm @@ -0,0 +1,143 @@ +;; pi-resolve-provider-key-oauth +;; pi-resolve-provider-key 的 oauth 分支:未过期返回 access、过期透明刷新 +;; 落盘、401 清除凭据、env API Key 优先(1402 测试项 2/4/5 的单元化)。 +;; +;; 语法 +;; ---- +;; (pi-resolve-provider-key provider auth-alist) +;; (pi-resolve-provider-key provider auth-alist opt-env opt-config-dir) +;; +;; 参数 +;; ---- +;; provider : string? +;; 服务商 id(kimi-coding)。 +;; +;; auth-alist : list? +;; pi-load-auth 返回的凭据列表。 +;; +;; opt-env : list? +;; 自定义环境变量表。 +;; +;; opt-config-dir : string? +;; oauth 刷新落盘目录。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; 生效 access token / API Key;刷新失败 #f。 + +(import (scheme base) + (liii check) + (liii string) + (liii list) + (liii path) + (liii subprocess) + (liii tempfile) + (liii pi ai time) + (liii pi ai config credential) + (liii pi ai auth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +;; 1. oauth 未过期:直接返回 access(无网络) +(let* ((tmp (make-temp-dir "gf-resolve-oauth-" "")) + (_ (pi-save-auth-oauth! "kimi-coding" + "fresh-acc" + "ref" + (+ (pi-current-time-millis) 3600000) + #f + tmp + ) ;pi-save-auth-oauth! + ) ;_ + (creds (pi-load-auth tmp)) + ) ; + (check (pi-resolve-provider-key "kimi-coding" creds '() tmp) => "fresh-acc") + ;; env API Key 优先于 oauth 凭据(测试项 5 回归) + (check (pi-resolve-provider-key "kimi-coding" creds '(("KIMI_API_KEY" + . "sk-env")) tmp) + => + "sk-env" + ) ;check + (path-unlink (path (path-join tmp "auth.json"))) + (path-rmdir tmp) +) ;let* + +;; 2. oauth 已过期:透明刷新并落盘新 access/refresh/expires(测试项 4) +(let* ((proc (process-spawn (list "python3" stub-file "refresh-ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (tmp (make-temp-dir "gf-resolve-oauth-" "")) + (_ (pi-save-auth-oauth! "kimi-coding" + "old-acc" + "stub-refresh-token" + (- (pi-current-time-millis) 1000) + host + tmp + ) ;pi-save-auth-oauth! + ) ;_ + (creds (pi-load-auth tmp)) + ) ; + (check (pi-resolve-provider-key "kimi-coding" creds '() tmp) + => + "stub-access-token-2" + ) ;check + ;; 落盘验证:重新加载后 access/refresh 已轮换,region 保留 + (let* ((creds2 (pi-load-auth tmp)) + (c + (find (lambda (x) (equal? (pi-credential-provider x) "kimi-coding")) creds2) + ) ;c + ) ; + (check (pi-credential-access c) => "stub-access-token-2") + (check (pi-credential-refresh c) => "stub-refresh-token-2") + (check (pi-credential-region c) => host) + (check-true (> (pi-credential-expires c) (pi-current-time-millis))) + ;; 新凭据未过期:再次解析不触发网络 + (check (pi-resolve-provider-key "kimi-coding" creds2 '() tmp) + => + "stub-access-token-2" + ) ;check + ) ;let* + (process-kill proc) + (path-unlink (path (path-join tmp "auth.json"))) + (path-rmdir tmp) +) ;let* + +;; 3. 刷新 401 invalid_grant:清除凭据并返回 #f(测试项 4 后半) +(let* ((proc (process-spawn (list "python3" stub-file "refresh-401") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (tmp (make-temp-dir "gf-resolve-oauth-" "")) + (_ (pi-save-auth-oauth! "kimi-coding" + "old-acc" + "stub-refresh-token" + (- (pi-current-time-millis) 1000) + host + tmp + ) ;pi-save-auth-oauth! + ) ;_ + (creds (pi-load-auth tmp)) + ) ; + (check (pi-resolve-provider-key "kimi-coding" creds '() tmp) => #f) + ;; 凭据已被清除 + (check (pi-load-auth tmp) => '()) + (process-kill proc) + (path-unlink (path (path-join tmp "auth.json"))) + (path-rmdir tmp) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/pi-save-auth-oauth-bang-test.scm b/ai/tests/liii/pi/ai/auth/pi-save-auth-oauth-bang-test.scm new file mode 100644 index 00000000..94f085b7 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/pi-save-auth-oauth-bang-test.scm @@ -0,0 +1,111 @@ +;; pi-save-auth-oauth! +;; 向 auth.json 保存或增量更新服务商 OAuth 凭据(type=oauth)。 +;; +;; 语法 +;; ---- +;; (pi-save-auth-oauth! provider access refresh expires region) +;; (pi-save-auth-oauth! provider access refresh expires region opt-config-dir) +;; +;; 参数 +;; ---- +;; provider : (or string? symbol?) +;; 服务商标识。 +;; +;; access : string? +;; OAuth access token(非空)。 +;; +;; refresh : string? +;; OAuth refresh token(非空)。 +;; +;; expires : number? +;; access token 过期毫秒 epoch(正数)。 +;; +;; region : string? 或 #f +;; 登录时的 OAuth host 覆盖值;#f 不写 region 字段。 +;; +;; opt-config-dir : (or string? path?) +;; 可选,配置目录(默认 ~/.gf/agent)。 +;; +;; 返回值 +;; ---- +;; string? +;; 写入的 auth.json 文件路径。 + +(import (liii check) + (liii os) + (liii path) + (liii path stat) + (liii json) + (liii list) + (liii tempfile) + (liii pi ai config credential) + (liii pi ai auth) +) ;import + +(check-set-mode! 'report-failed) + +;; 1. 参数校验 +(check-catch 'type-error (pi-save-auth-oauth! 1 "a" "r" 1 #f)) +(check-catch 'value-error (pi-save-auth-oauth! " " "a" "r" 1 #f)) +(check-catch 'type-error (pi-save-auth-oauth! "kimi-coding" 1 "r" 1 #f)) +(check-catch 'value-error (pi-save-auth-oauth! "kimi-coding" "a" " " 1 #f)) +(check-catch 'value-error (pi-save-auth-oauth! "kimi-coding" "a" "r" 0 #f)) +(check-catch 'value-error (pi-save-auth-oauth! "kimi-coding" "a" "r" -5 #f)) +(check-catch 'type-error (pi-save-auth-oauth! "kimi-coding" "a" "r" "x" #f)) +(check-catch 'type-error (pi-save-auth-oauth! "kimi-coding" "a" "r" 1 5)) + +;; 2. 新建 auth.json 写入 oauth 条目,可被 pi-load-auth 解析 +(let* ((tmp (make-temp-dir "gf-auth-oauth-" "")) + (target (pi-save-auth-oauth! "kimi-coding" "acc-1" "ref-1" 1893456000000 #f tmp) + ) ;target + (creds (pi-load-auth tmp)) + ) ; + (check-true (path-exists? (path target))) + (check (length creds) => 1) + (check-true (pi-credential-oauth? (car creds))) + (check (pi-credential-provider (car creds)) => "kimi-coding") + (check (pi-credential-access (car creds)) => "acc-1") + (check (pi-credential-refresh (car creds)) => "ref-1") + (check (pi-credential-expires (car creds)) => 1893456000000) + (check (pi-credential-region (car creds)) => #f) + ;; 文件内容:无 region 字段 + (let ((raw (string->json (path-read-text (path target))))) + (check (assoc "region" (cdr (assoc "kimi-coding" raw))) => #f) + ) ;let + ;; 权限 0600(非 Windows) + (unless (os-windows?) + (check (logand (path-stat-mode (path-stat target)) 511) => 384) + ) ;unless + (path-unlink (path target)) + (path-rmdir tmp) +) ;let* + +;; 3. region 落盘 + 覆盖更新 + 不破坏其它服务商条目 +(let* ((tmp (make-temp-dir "gf-auth-oauth-" "")) + (_ (pi-save-auth-key "deepseek" "sk-ds" tmp)) + (target (pi-save-auth-oauth! 'kimi-coding + "acc-1" + "ref-1" + 1893456000000 + "https://auth.kimi.ai" + tmp + ) ;pi-save-auth-oauth! + ) ;target + ) ; + (check (length (pi-load-auth tmp)) => 2) + (pi-save-auth-oauth! "kimi-coding" "acc-2" "ref-2" 1893456000001 #f tmp) + (let* ((creds (pi-load-auth tmp)) + (kimi + (find (lambda (c) (equal? (pi-credential-provider c) "kimi-coding")) creds) + ) ;kimi + ) ; + (check (length creds) => 2) + (check (pi-credential-access kimi) => "acc-2") + (check (pi-credential-region kimi) => #f) + (check (pi-resolve-provider-key "deepseek" creds '()) => "sk-ds") + ) ;let* + (path-unlink (path target)) + (path-rmdir tmp) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm new file mode 100644 index 00000000..fee3281f --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm @@ -0,0 +1,37 @@ +;; pi-auth-dir-path +;; 解析 auth.json 所在配置目录:显式传入优先,缺省 ~/.gf/agent。 +;; +;; 语法 +;; ---- +;; (pi-auth-dir-path opt-config-dir) -> path? +;; +;; 参数 +;; ---- +;; opt-config-dir : list? +;; '() 或 (dir),dir 为 string/path。 +;; +;; 返回值 +;; ---- +;; path? +;; 配置目录 path 对象。 + +(import (liii check) (liii path) (liii pi ai auth storage)) + +(check-set-mode! 'report-failed) + +(check (path->string (pi-auth-dir-path '("/tmp/gf-cfg"))) => "/tmp/gf-cfg") +(check + (path->string (pi-auth-dir-path (list (path "/tmp/gf-cfg")))) + => + "/tmp/gf-cfg" +) ;check +(check (path->string (pi-auth-dir-path '(#f))) + => + (path->string (path-join (path-home) ".gf" "agent")) +) ;check +(check (path->string (pi-auth-dir-path '())) + => + (path->string (path-join (path-home) ".gf" "agent")) +) ;check + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-provider-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-provider-test.scm new file mode 100644 index 00000000..98de1fee --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-provider-test.scm @@ -0,0 +1,32 @@ +;; pi-auth-normalize-provider +;; 校验并归一化 provider:string/symbol → 去空白非空字符串。 +;; +;; 语法 +;; ---- +;; (pi-auth-normalize-provider who provider) -> string? +;; +;; 参数 +;; ---- +;; who : string? +;; 错误消息前缀(调用方函数名)。 +;; +;; provider : (or string? symbol?) +;; 待归一化的 provider。 +;; +;; 返回值 +;; ---- +;; string? +;; 去空白后的 provider;空白抛 value-error,非 string/symbol 抛 type-error。 + +(import (liii check) (liii pi ai auth storage)) + +(check-set-mode! 'report-failed) + +(check (pi-auth-normalize-provider "test" "kimi-coding") => "kimi-coding") +(check (pi-auth-normalize-provider "test" 'kimi-coding) => "kimi-coding") +(check (pi-auth-normalize-provider "test" " deepseek ") => "deepseek") +(check-catch 'value-error (pi-auth-normalize-provider "test" " ")) +(check-catch 'type-error (pi-auth-normalize-provider "test" 123)) +(check-catch 'type-error (pi-auth-normalize-provider "test" #f)) + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-secret-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-secret-test.scm new file mode 100644 index 00000000..4dcfa3ac --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-normalize-secret-test.scm @@ -0,0 +1,33 @@ +;; pi-auth-normalize-secret +;; 校验并归一化密钥类字段(key/access/refresh):去空白非空字符串。 +;; +;; 语法 +;; ---- +;; (pi-auth-normalize-secret who field value) -> string? +;; +;; 参数 +;; ---- +;; who : string? +;; 错误消息前缀。 +;; +;; field : string? +;; 字段名(用于错误消息)。 +;; +;; value : string? +;; 待归一化的密钥。 +;; +;; 返回值 +;; ---- +;; string? +;; 去空白后的密钥;空白抛 value-error,非 string 抛 type-error。 + +(import (liii check) (liii pi ai auth storage)) + +(check-set-mode! 'report-failed) + +(check (pi-auth-normalize-secret "test" "key" "sk-abc") => "sk-abc") +(check (pi-auth-normalize-secret "test" "access" " tok ") => "tok") +(check-catch 'value-error (pi-auth-normalize-secret "test" "key" " ")) +(check-catch 'type-error (pi-auth-normalize-secret "test" "key" 42)) + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-read-json-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-read-json-test.scm new file mode 100644 index 00000000..f9c7da3d --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-read-json-test.scm @@ -0,0 +1,47 @@ +;; pi-auth-read-json +;; 读取 JSON 文件为 Scheme 数据;文件缺失或解析失败返回 #f。 +;; +;; 语法 +;; ---- +;; (pi-auth-read-json filepath) -> any +;; +;; 参数 +;; ---- +;; filepath : string? +;; JSON 文件路径。 +;; +;; 返回值 +;; ---- +;; any +;; 解析后的 JSON 数据(alist/vector/标量);缺失或非法返回 #f。 + +(import (liii check) (liii path) (liii tempfile) (liii pi ai auth storage)) + +(check-set-mode! 'report-failed) + +;; 缺失文件 +(check (pi-auth-read-json "/nonexistent/gf-auth-read-test.json") => #f) + +;; 正常读取 +(let* ((tmp (make-temp-dir "gf-auth-read-" "")) (f (path-join tmp "a.json"))) + (path-write-text f "{\"kimi-coding\":{\"type\":\"oauth\",\"expires\":123}}") + (let ((data (pi-auth-read-json (path->string f)))) + (check + (cdr (assoc "type" (cdr (assoc "kimi-coding" data)))) + => + "oauth" + ) ;check + (check + (cdr (assoc "expires" (cdr (assoc "kimi-coding" data)))) + => + 123 + ) ;check + ) ;let + ;; 非法 JSON + (path-write-text f "{invalid") + (check (pi-auth-read-json (path->string f)) => #f) + (path-unlink f) + (path-rmdir tmp) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-replace-entry-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-replace-entry-test.scm new file mode 100644 index 00000000..a0f93a30 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-replace-entry-test.scm @@ -0,0 +1,57 @@ +;; pi-auth-replace-entry +;; 替换(或追加)auth.json alist 中某 provider 的条目,其余原样保留。 +;; +;; 语法 +;; ---- +;; (pi-auth-replace-entry alist p-str entry-fields) -> list? +;; +;; 参数 +;; ---- +;; alist : list? +;; 现有 auth.json 数据(provider → 条目字段 alist)。 +;; +;; p-str : string? +;; 目标 provider id。 +;; +;; entry-fields : list? +;; 新条目字段 alist。 +;; +;; 返回值 +;; ---- +;; list? +;; 更新后的 alist;目标条目移到末尾,键可为 symbol 的旧条目也能被替换。 + +(import (liii check) (liii pi ai auth storage)) + +(check-set-mode! 'report-failed) + +;; 追加 +(check (pi-auth-replace-entry '() "kimi-coding" '(("type" . "oauth"))) + => + '(("kimi-coding" ("type" . "oauth"))) +) ;check + +;; 替换已有条目,保留其它 +(let* ((alist '(("deepseek" ("type" . "api_key") ("key" . "sk")) + ("kimi-coding" ("type" . "api_key") ("key" . "old"))) + ) ;alist + (updated (pi-auth-replace-entry alist "kimi-coding" '(("type" . "oauth")))) + ) ; + (check (length updated) => 2) + (check (assoc "deepseek" updated) => (car alist)) + (check (cdr (assoc "kimi-coding" updated)) => '(("type" . "oauth"))) +) ;let* + +;; symbol 键的旧条目同样被替换 +(let ((updated + (pi-auth-replace-entry '((deepseek ("key" . "sk"))) + "deepseek" + '(("key" . "new")) + ) ;pi-auth-replace-entry + ) ;updated + ) ; + (check (length updated) => 1) + (check (cdr (assoc "deepseek" updated)) => '(("key" . "new"))) +) ;let + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-write-json-bang-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-write-json-bang-test.scm new file mode 100644 index 00000000..6f8bb161 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-write-json-bang-test.scm @@ -0,0 +1,76 @@ +;; pi-auth-write-json! +;; 原子写 auth.json:tmp 文件 + rename + chmod 0600,目录自动创建。 +;; +;; 语法 +;; ---- +;; (pi-auth-write-json! dir-path updated) -> string? +;; +;; 参数 +;; ---- +;; dir-path : path? +;; 配置目录。 +;; +;; updated : list? +;; 完整 auth.json alist。 +;; +;; 返回值 +;; ---- +;; string? +;; 写入的 auth.json 路径。 + +(import (liii check) + (liii os) + (liii path) + (liii path stat) + (liii json) + (liii tempfile) + (liii pi ai auth storage) +) ;import + +(check-set-mode! 'report-failed) + +;; 1. 自动创建目录并写入,内容可回读,无 .tmp 残留 +(let* ((tmp (make-temp-dir "gf-auth-write-" "")) + (dir (path-join tmp "nested" "cfg")) + (target + (pi-auth-write-json! dir '(("kimi-coding" ("type" . "oauth")))) + ) ;target + ) ; + (check-true (path-exists? (path target))) + (check-false (path-exists? (path (string-append target ".tmp")))) + (let ((data (string->json (path-read-text (path target))))) + (check + (cdr (assoc "type" (cdr (assoc "kimi-coding" data)))) + => + "oauth" + ) ;check + ) ;let + (unless (os-windows?) + (check (logand (path-stat-mode (path-stat target)) 511) => 384) + ) ;unless + (path-unlink (path target)) + (path-rmdir dir) + (path-rmdir (path-join tmp "nested")) + (path-rmdir tmp) +) ;let* + +;; 2. 覆盖已有文件 +(let* ((tmp (make-temp-dir "gf-auth-write-" "")) + (target + (pi-auth-write-json! (path tmp) '(("a" ("key" . "1")))) + ) ;target + ) ; + (pi-auth-write-json! (path tmp) '(("b" ("key" . "2")))) + (let ((data (string->json (path-read-text (path target))))) + (check (assoc "a" data) => #f) + (check + (cdr (assoc "key" (cdr (assoc "b" data)))) + => + "2" + ) ;check + ) ;let + (path-unlink (path target)) + (path-rmdir tmp) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm new file mode 100644 index 00000000..c91761f2 --- /dev/null +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm @@ -0,0 +1,30 @@ +;; pi-credential-access +;; 获取 oauth 凭据的 access token 字段。 +;; +;; 语法 +;; ---- +;; (pi-credential-access c) -> string? 或 #f +;; +;; 参数 +;; ---- +;; c : pi-credential? +;; 凭据 record 实例。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; oauth 凭据的 access token;api_key 凭据默认 #f。 + +(import (liii check) (liii pi ai config credential)) + +(check-set-mode! 'report-failed) + +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-token" "ref-token" 1893456000000 #f))) + (check (pi-credential-access c) => "acc-token") +) ;let + +(let ((c (pi-credential "google" "secret-key" "api_key"))) + (check (pi-credential-access c) => #f) +) ;let + +(check-report) \ No newline at end of file diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm new file mode 100644 index 00000000..16f5fd3a --- /dev/null +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm @@ -0,0 +1,30 @@ +;; pi-credential-expires +;; 获取 oauth 凭据 access token 的过期时刻(毫秒 epoch)。 +;; +;; 语法 +;; ---- +;; (pi-credential-expires c) -> number? 或 #f +;; +;; 参数 +;; ---- +;; c : pi-credential? +;; 凭据 record 实例。 +;; +;; 返回值 +;; ---- +;; number? 或 #f +;; 过期毫秒时间戳;api_key 凭据默认 #f。 + +(import (liii check) (liii pi ai config credential)) + +(check-set-mode! 'report-failed) + +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f))) + (check (pi-credential-expires c) => 1893456000000) +) ;let + +(let ((c (pi-credential "google" "secret-key" "api_key"))) + (check (pi-credential-expires c) => #f) +) ;let + +(check-report) \ No newline at end of file diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm new file mode 100644 index 00000000..294e8eb9 --- /dev/null +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm @@ -0,0 +1,30 @@ +;; pi-credential-oauth? +;; 判断凭据是否为 oauth 类型。 +;; +;; 语法 +;; ---- +;; (pi-credential-oauth? obj) -> boolean? +;; +;; 参数 +;; ---- +;; obj : any +;; 任意对象。 +;; +;; 返回值 +;; ---- +;; boolean? +;; 是 type 为 "oauth" 的 pi-credential 时返回 #t,否则 #f。 + +(import (liii check) (liii pi ai config credential)) + +(check-set-mode! 'report-failed) + +(check-true + (pi-credential-oauth? + (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f))) +(check-false (pi-credential-oauth? (pi-credential "google" "k" "api_key"))) +(check-false (pi-credential-oauth? (pi-credential "google" "k"))) +(check-false (pi-credential-oauth? "oauth")) +(check-false (pi-credential-oauth? #f)) + +(check-report) \ No newline at end of file diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm new file mode 100644 index 00000000..eb2dd1af --- /dev/null +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm @@ -0,0 +1,30 @@ +;; pi-credential-refresh +;; 获取 oauth 凭据的 refresh token 字段。 +;; +;; 语法 +;; ---- +;; (pi-credential-refresh c) -> string? 或 #f +;; +;; 参数 +;; ---- +;; c : pi-credential? +;; 凭据 record 实例。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; oauth 凭据的 refresh token;api_key 凭据默认 #f。 + +(import (liii check) (liii pi ai config credential)) + +(check-set-mode! 'report-failed) + +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-token" "ref-token" 1893456000000 #f))) + (check (pi-credential-refresh c) => "ref-token") +) ;let + +(let ((c (pi-credential "google" "secret-key" "api_key"))) + (check (pi-credential-refresh c) => #f) +) ;let + +(check-report) \ No newline at end of file diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm new file mode 100644 index 00000000..477cbef5 --- /dev/null +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm @@ -0,0 +1,31 @@ +;; pi-credential-region +;; 获取 oauth 凭据登录时记录的 OAuth host 覆盖值(region)。 +;; +;; 语法 +;; ---- +;; (pi-credential-region c) -> string? 或 #f +;; +;; 参数 +;; ---- +;; c : pi-credential? +;; 凭据 record 实例。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; 登录时的 host 覆盖值;默认 host 登录不写 region,返回 #f。 + +(import (liii check) (liii pi ai config credential)) + +(check-set-mode! 'report-failed) + +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 + "https://auth.kimi.ai"))) + (check (pi-credential-region c) => "https://auth.kimi.ai") +) ;let + +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f))) + (check (pi-credential-region c) => #f) +) ;let + +(check-report) \ No newline at end of file diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm index b468df5e..6686ba6f 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm @@ -33,4 +33,24 @@ (check-catch 'type-error (pi-credential->json '(("provider" . "openai")))) (check-catch 'type-error (pi-credential->json "invalid")) +;; oauth 分支:输出 type/access/refresh/expires,region 有值才写 +(let* ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f)) + (j (pi-credential->json c)) + (parsed (string->json (json->string j))) + ) ; + (check (cdr (assoc "type" parsed)) => "oauth") + (check (cdr (assoc "access" parsed)) => "acc") + (check (cdr (assoc "refresh" parsed)) => "ref") + (check (cdr (assoc "expires" parsed)) => 1893456000000) + (check (assoc "region" parsed) => #f) + (check (assoc "key" parsed) => #f) +) ;let* + +;; oauth + region:region 落盘 +(let* ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 "https://auth.kimi.ai")) + (parsed (string->json (json->string (pi-credential->json c)))) + ) ; + (check (cdr (assoc "region" parsed)) => "https://auth.kimi.ai") +) ;let* + (check-report) diff --git a/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm b/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm new file mode 100644 index 00000000..757a3cf7 --- /dev/null +++ b/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm @@ -0,0 +1,28 @@ +;; pi-provider-oauth +;; 查询 provider 登记的订阅 OAuth 登录方式标识。 +;; +;; 语法 +;; ---- +;; (pi-provider-oauth provider) -> string? 或 #f +;; +;; 参数 +;; ---- +;; provider : (or string? symbol?) +;; 服务商 id。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; kimi-coding 返回 "kimi-code";未登记 OAuth 的 provider 返回 #f。 + +(import (liii check) (liii pi ai providers registry)) + +(check-set-mode! 'report-failed) + +(check (pi-provider-oauth "kimi-coding") => "kimi-code") +(check (pi-provider-oauth 'kimi-coding) => "kimi-code") +(check (pi-provider-oauth "deepseek") => #f) +(check (pi-provider-oauth "google") => #f) +(check (pi-provider-oauth "no-such-provider") => #f) + +(check-report) \ No newline at end of file diff --git a/ai/tests/stub_kimi_oauth_server.py b/ai/tests/stub_kimi_oauth_server.py new file mode 100644 index 00000000..173f4828 --- /dev/null +++ b/ai/tests/stub_kimi_oauth_server.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Kimi Code OAuth2 stub server for gfcode unit tests (1402 §3.2). + +Emulates https://auth.kimi.com endpoints: + POST /api/oauth/device_authorization -> device_code/user_code/verification URIs + POST /api/oauth/token -> device_code grant polling & refresh_token grant + +Scenario is chosen by the first CLI arg (default "ok"): + ok authorize OK; token poll: pending once, then complete + slow-down poll: pending, slow_down (with new interval), then complete + denied poll: access_denied + expired poll: expired_token + poll-500 poll: HTTP 500 + authorize-500 device_authorization: HTTP 500 + authorize-bad device_authorization: 200 with missing fields + refresh-ok refresh grant returns fresh tokens immediately + refresh-401 refresh grant returns 401 invalid_grant + refresh-403 refresh grant returns 403 + refresh-flaky refresh grant: 429 twice then 200 (retry backoff path) + refresh-500 refresh grant: always 500 (retries exhausted) + +Prints "PORT:" on stdout once listening. +""" +import http.server +import json +import sys +import urllib.parse + +SCENARIO = sys.argv[1] if len(sys.argv) > 1 else "ok" + + +class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _send(self, status: int, obj: dict) -> None: + body = json.dumps(obj).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: + try: + length = int(self.headers.get("content-length") or 0) + except ValueError: + self._send(400, {"error": "invalid_request"}) + return + raw = self.rfile.read(length).decode("utf-8") if length else "" + form = dict(urllib.parse.parse_qsl(raw)) + server = self.server + server.token_polls = getattr(server, "token_polls", 0) + server.refresh_calls = getattr(server, "refresh_calls", 0) + + if self.path == "/api/oauth/device_authorization": + if form.get("client_id") != "17e5f671-d194-4dfb-9706-5516cb48c098": + self._send(400, {"error": "invalid_client"}) + return + if SCENARIO == "authorize-500": + self._send(500, {"error": "server_error"}) + return + if SCENARIO == "authorize-bad": + self._send(200, {"user_code": "ABCD-1234"}) + return + self._send(200, { + "device_code": "stub-device-code", + "user_code": "ABCD-1234", + "verification_uri": "https://www.kimi.com/code", + "verification_uri_complete": + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234", + "interval": 1, + "expires_in": 900, + }) + return + + if self.path == "/api/oauth/token": + grant = form.get("grant_type") + if grant == "urn:ietf:params:oauth:grant-type:device_code": + if form.get("device_code") != "stub-device-code": + self._send(400, {"error": "invalid_grant"}) + return + server.token_polls += 1 + n = server.token_polls + if SCENARIO == "denied": + self._send(400, {"error": "access_denied"}) + return + if SCENARIO == "expired": + self._send(400, {"error": "expired_token"}) + return + if SCENARIO == "poll-500": + self._send(500, {"error": "server_error"}) + return + if SCENARIO == "slow-down": + if n == 1: + self._send(400, {"error": "authorization_pending"}) + return + if n == 2: + self._send(400, {"error": "slow_down", "interval": 1}) + return + else: + if n == 1: + self._send(400, {"error": "authorization_pending"}) + return + self._send(200, { + "access_token": "stub-access-token", + "refresh_token": "stub-refresh-token", + "expires_in": 3600, + "token_type": "Bearer", + }) + return + if grant == "refresh_token": + server.refresh_calls += 1 + n = server.refresh_calls + if form.get("refresh_token") == "dead-refresh-token" or SCENARIO == "refresh-401": + self._send(401, {"error": "invalid_grant", + "error_description": "refresh token expired"}) + return + if SCENARIO == "refresh-403": + self._send(403, {"error": "access_denied"}) + return + if SCENARIO == "refresh-500": + self._send(500, {"error": "server_error"}) + return + if SCENARIO == "refresh-flaky" and n <= 2: + self._send(429, {"error": "rate_limited"}) + return + self._send(200, { + "access_token": "stub-access-token-2", + "refresh_token": "stub-refresh-token-2", + "expires_in": 3600, + "token_type": "Bearer", + }) + return + self._send(400, {"error": "unsupported_grant_type"}) + return + + self._send(404, {"error": "not_found"}) + + +def main() -> None: + # 仅绑定回环地址;测试结束时由 process-kill 终止,无需优雅关停 + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + print("PORT:%d" % server.server_address[1], flush=True) + try: + server.serve_forever() + finally: + server.server_close() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/code/liii/pi/code/config.scm b/code/liii/pi/code/config.scm index 54d614a7..e7269701 100644 --- a/code/liii/pi/code/config.scm +++ b/code/liii/pi/code/config.scm @@ -287,9 +287,10 @@ (pi-load-auth config-dir) ) ;if ) ;auth + ;; 尾参 config-dir:oauth 凭据过期时透明刷新的落盘目录 (api-key-raw (if (pair? opt-env) - (pi-resolve-provider-key provider auth (car opt-env)) - (pi-resolve-provider-key provider auth) + (pi-resolve-provider-key provider auth (car opt-env) config-dir-str) + (pi-resolve-provider-key provider auth '() config-dir-str) ) ;if ) ;api-key-raw (api-key api-key-raw) diff --git a/code/liii/pi/code/session-state.scm b/code/liii/pi/code/session-state.scm index 02fc2370..7f3838e5 100644 --- a/code/liii/pi/code/session-state.scm +++ b/code/liii/pi/code/session-state.scm @@ -57,7 +57,7 @@ (let* ((config-dir (pi-cfg-config-dir cfg)) (models-store (or (pi-cfg-ref cfg 'models-store) '())) (auth (pi-load-auth config-dir)) - (api-key (pi-resolve-provider-key provider auth)) + (api-key (pi-resolve-provider-key provider auth '() config-dir)) (intent-provider (and (pair? intent) (%state-ref intent 'provider))) (meta (pi-ensure-catalog-meta (pi-resolve-model-metadata provider model-id models-store) provider diff --git a/tui/liii/pi/tui/cli/auth.scm b/tui/liii/pi/tui/cli/auth.scm index bbbe450e..8a2dd9cf 100644 --- a/tui/liii/pi/tui/cli/auth.scm +++ b/tui/liii/pi/tui/cli/auth.scm @@ -14,22 +14,31 @@ (liii list) (liii error) (liii pi ai auth) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) (liii pi code config) (liii pi code modes output) ) ;import (export parse-pi-auth-args pi-auth-print-api-key pi-auth-login run-pi-auth pi-auth-args? make-pi-auth-args pi-auth-args-help? pi-auth-args-subcommand - pi-auth-args-provider pi-auth-args-key + pi-auth-args-provider pi-auth-args-key pi-auth-args-oauth? + pi-auth-login-oauth ) ;export (begin (define*-record-type - (make-pi-auth-args (help? #f) (subcommand #f) (provider #f) (key #f)) + (make-pi-auth-args (help? #f) + (subcommand #f) + (provider #f) + (key #f) + (oauth? #f) + ) ;make-pi-auth-args pi-auth-args? (help? pi-auth-args-help?) (subcommand pi-auth-args-subcommand) (provider pi-auth-args-provider) (key pi-auth-args-key) + (oauth? pi-auth-args-oauth?) ) ;define*-record-type (define (%provider-default-env-var provider) @@ -85,26 +94,33 @@ ) ; ((string=? (car args) "login") (let loop - ((rem (cdr args)) (provider #f) (key #f)) + ((rem (cdr args)) (provider #f) (key #f) (oauth? #f)) (cond ((null? rem) - (if (or (not provider) (not key)) - (error 'pi-arg-error - "auth login requires --provider and --key " - ) ;error - (make-pi-auth-args :subcommand "login" :provider provider :key key) - ) ;if + (cond (oauth? (if (not provider) + (error 'pi-arg-error "auth login --oauth requires --provider ") + (make-pi-auth-args :subcommand "login" :provider provider :oauth? #t) + ) ;if + ) ;oauth? + ((or (not provider) (not key)) + (error 'pi-arg-error + "auth login requires --provider and --key (or --oauth)" + ) ;error + ) ; + (else (make-pi-auth-args :subcommand "login" :provider provider :key key)) + ) ;cond ) ; ((or (string=? (car rem) "-h") (string=? (car rem) "--help")) (make-pi-auth-args :help? #t) ) ; + ((string=? (car rem) "--oauth") (loop (cdr rem) provider key #t)) ((string=? (car rem) "--provider") (if (null? (cdr rem)) (error 'pi-arg-error "auth login requires --provider ") (let ((val (cadr rem))) (if (or (string-null? (string-trim-both val)) (string-starts? val "-")) (error 'pi-arg-error "auth login requires --provider ") - (loop (cddr rem) val key) + (loop (cddr rem) val key oauth?) ) ;if ) ;let ) ;if @@ -113,7 +129,7 @@ (let ((val (substring (car rem) 11 (string-length (car rem))))) (if (string-null? (string-trim-both val)) (error 'pi-arg-error "auth login requires --provider ") - (loop (cdr rem) val key) + (loop (cdr rem) val key oauth?) ) ;if ) ;let ) ; @@ -123,7 +139,7 @@ (let ((val (cadr rem))) (if (string-null? (string-trim-both val)) (error 'pi-arg-error "auth login requires --key ") - (loop (cddr rem) provider val) + (loop (cddr rem) provider val oauth?) ) ;if ) ;let ) ;if @@ -132,7 +148,7 @@ (let ((val (substring (car rem) 6 (string-length (car rem))))) (if (string-null? (string-trim-both val)) (error 'pi-arg-error "auth login requires --key ") - (loop (cdr rem) provider val) + (loop (cdr rem) provider val oauth?) ) ;if ) ;let ) ; @@ -140,8 +156,8 @@ (error 'pi-arg-error (string-append "unknown option: " (car rem))) ) ; (else - (cond ((not provider) (loop (cdr rem) (car rem) key)) - ((not key) (loop (cdr rem) provider (car rem))) + (cond ((not provider) (loop (cdr rem) (car rem) key oauth?)) + ((not key) (loop (cdr rem) provider (car rem) oauth?)) (else (error 'pi-arg-error (string-append "unexpected extra argument: " (car rem))) ) ;else ) ;cond @@ -237,6 +253,72 @@ ) ;let* ) ;define + ;; 非交互 device flow(headless 友好):打印 verification URL 让用户 + ;; 手动打开,轮询成功后落盘 oauth 凭据(1402 §5.4 可选子项) + (define (pi-auth-login-oauth provider . opt-args) + (let* ((config-dir (if (pair? opt-args) (car opt-args) (gf-get-config-dir))) + (opt-env + (if (and (pair? opt-args) (pair? (cdr opt-args))) (list (cadr opt-args)) '()) + ) ;opt-env + (notify + (lambda (ev) + (display (string-append "Open this URL to authorize: " (caddr ev) "\n")) + (display (string-append "User code: " (cadr ev) "\n")) + (display "Waiting for authorization…\n") + ) ;lambda + ) ;notify + (cred + (catch #t + (lambda () (apply kimi-oauth-login (append (list notify #f provider) opt-env))) + (lambda (tag . info) + (display-stderr (string-append "Error: Kimi Code OAuth login failed: " + (catch-error->string tag info) + ) ;string-append + ) ;display-stderr + #f + ) ;lambda + ) ;catch + ) ;cred + ) ; + (if (pi-credential? cred) + (let ((saved + (catch #t + (lambda () + (pi-save-auth-oauth! provider + (pi-credential-access cred) + (pi-credential-refresh cred) + (pi-credential-expires cred) + (pi-credential-region cred) + config-dir + ) ;pi-save-auth-oauth! + ) ;lambda + (lambda (tag . info) #f) + ) ;catch + ) ;saved + ) ; + (if saved + (begin + (display (string-append "Saved OAuth credential for provider '" + provider "' to " saved "\n" + ) ;string-append + ) ;display + 0 + ) ;begin + (begin + (display-stderr (string-append "Error: failed to save OAuth credential for provider '" + provider + "'\n" + ) ;string-append + ) ;display-stderr + 1 + ) ;begin + ) ;if + ) ;let + 1 + ) ;if + ) ;let* + ) ;define + (define (run-pi-auth args . opt-args) (let ((config-dir (if (pair? opt-args) (car opt-args) (gf-get-config-dir))) (custom-env @@ -247,7 +329,7 @@ (lambda () (let ((parsed (parse-pi-auth-args args))) (cond ((pi-auth-args-help? parsed) - (display "Usage: gf pi auth print-api-key --provider \n gf pi auth login --provider --key \n" + (display "Usage: gf pi auth print-api-key --provider \n gf pi auth login --provider --key \n gf pi auth login --provider --oauth\n" ) ;display 0 ) ; @@ -261,7 +343,13 @@ ) ; ((equal? (pi-auth-args-subcommand parsed) "login") (let ((provider (pi-auth-args-provider parsed)) (key (pi-auth-args-key parsed))) - (pi-auth-login provider key config-dir) + (if (pi-auth-args-oauth? parsed) + (if custom-env + (pi-auth-login-oauth provider config-dir custom-env) + (pi-auth-login-oauth provider config-dir) + ) ;if + (pi-auth-login provider key config-dir) + ) ;if ) ;let ) ; (else 1) diff --git a/tui/liii/pi/tui/interactive/app-events.scm b/tui/liii/pi/tui/interactive/app-events.scm index 56c5e15c..7f079877 100644 --- a/tui/liii/pi/tui/interactive/app-events.scm +++ b/tui/liii/pi/tui/interactive/app-events.scm @@ -32,6 +32,7 @@ (liii pi tui interactive common) (liii pi tui interactive footer) (liii pi tui interactive app-recovery) + (liii pi tui interactive app-login) ) ;import (begin @@ -284,6 +285,9 @@ (pi-app-add-tool-result! app "session" '() 'error (cadr ev)) ) ; ((branch_changed) (%pi-app-handle-branch-changed! app ev)) + ;; Kimi Code OAuth 设备码登录:device_code 上屏、done 落盘/报错 + ((kimi_oauth_device_code) (pi-app-handle-oauth-device-code! app ev)) + ((kimi_oauth_done) (pi-app-handle-oauth-done! app ev)) ((tool_execution_start) (%pi-app-close-assistant-card! app) (%pi-app-handle-tool-start! app ev) diff --git a/tui/liii/pi/tui/interactive/app-login.scm b/tui/liii/pi/tui/interactive/app-login.scm index a3bca9fc..f9c972e5 100644 --- a/tui/liii/pi/tui/interactive/app-login.scm +++ b/tui/liii/pi/tui/interactive/app-login.scm @@ -4,22 +4,36 @@ ;; Licensed under the MIT License ;; -;; /login 交互:解析登录命令、唤起供应商选择器或 Key 输入对话框、持久化凭证至 auth.json +;; /login 交互:解析登录命令、唤起供应商选择器或 Key 输入对话框、持久化凭证至 auth.json; +;; kimi-coding 的 OAuth 路径:二级选择后后台 go worker 跑设备码流程, +;; device_code/done 事件经 event-chan 回到主线程上屏与落盘(1402 §5.4) (define-library (liii pi tui interactive app-login) - (export pi-app-login-command? pi-app-submit-login!) + (export pi-app-login-command? + pi-app-submit-login! + pi-app-show-login-oauth! + pi-app-handle-oauth-device-code! + pi-app-handle-oauth-done! + ;; go worker 会话只能看到导出绑定:worker 调用链上的助手须导出 + %kimi-oauth-login-worker + ) ;export (import (scheme base) (liii go) (liii string) (liii list) (liii path) + (liii error) (liii tui) + (liii tui component) (liii pi ai auth) + (liii pi ai config credential) + (liii pi ai auth oauth kimi-coding-oauth) (liii pi code config) (liii pi tui interactive state) (liii pi tui interactive render) (liii pi tui interactive views) (liii pi tui interactive login-selector) (liii pi tui interactive login-dialog) + (liii pi tui interactive login-device-code) ) ;import (begin @@ -93,12 +107,208 @@ (lambda () (pi-app-close-login! app)) :current (pi-app-provider app) :config-dir cfg-dir + :on-select-method + (lambda (provider method) + (if (string=? method "oauth") + (pi-app-show-login-oauth! app provider cfg-dir) + (pi-app-show-login-dialog! app provider cfg-dir) + ) ;if + ) ;lambda ) ;make-login-selector ) ;%pi-app-active-selector-set! (pi-app-render! app) ) ;let ) ;define* + ;; ---------- OAuth 设备码登录(kimi-coding 订阅) ---------- + + ;; 启动占位组件:设备授权请求在后台 worker 中发出,device_code 事件 + ;; 到达后替换为真正的 login-device-code 组件。go 只能传可序列化数据 + ;; (app record 含闭包不可传),取消信号经独立 cancel-chan 传递 + (define* (pi-app-show-login-oauth! app provider (opt-config-dir #f)) + (let ((cfg-dir + (path->string (path (or opt-config-dir (gf-get-config-dir)))) + ) ;cfg-dir + (cancel-chan (make-chan 1)) + ) ; + (editor-set-focused! (pi-app-editor app) #f) + (%pi-app-active-selector-set! app + (make-component + :render + (lambda (comp width) + (list (string-append "Login to " provider " with Kimi Code (subscription)") + "" + "Contacting Kimi Code for a device code…" + "" + " esc to cancel" + ) ;list + ) ;lambda + :handle-input + (lambda (comp key) + (if (memq key '(escape ctrl-c)) + (begin + (catch #t (lambda () (chan-try-send! cancel-chan 'cancel)) (lambda args #f)) + (pi-app-close-login! app) + #t + ) ;begin + #f + ) ;if + ) ;lambda + ) ;make-component + ) ;%pi-app-active-selector-set! + (go (%kimi-oauth-login-worker provider cfg-dir (pi-app-event-chan app) cancel-chan) + ) ;go + (pi-app-render! app) + ) ;let + ) ;define* + + ;; 后台 worker:设备授权 → device_code 事件 → 轮询 → done 事件。 + ;; 取消探测:主线程 Esc 时向 cancel-chan 发信号(非阻塞探测) + (define (%kimi-oauth-login-worker provider cfg-dir event-chan cancel-chan) + (define (cancelled?) + (let ((sig (catch #t (lambda () (chan-try-recv! cancel-chan #f)) (lambda args #f)))) + (and sig (not (eof-object? sig)) #t) + ) ;let + ) ;define + (define (notify! ev) + (chan-send! event-chan + (list 'kimi_oauth_device_code + provider + (cadr ev) + (caddr ev) + (cadddr ev) + (car (cddddr ev)) + ) ;list + 1000 + ) ;chan-send! + ) ;define + (let ((result + (catch #t + (lambda () + (kimi-oauth-login notify! cancelled? provider)) + (lambda (tag . info) + (list 'error + tag + (if (and (pair? info) (string? (car info))) + (car info) + (catch-error->string tag info) + ) ;if + ) ;list + ) ;lambda + ) ;catch + ) ;result + ) ; + (if (and (pair? result) (eq? (car result) 'error)) + (chan-send! event-chan + (list 'kimi_oauth_done provider #f #f #f #f (cadr result) (caddr result)) + 1000 + ) ;chan-send! + (chan-send! event-chan + (list 'kimi_oauth_done + provider + (pi-credential-access result) + (pi-credential-refresh result) + (pi-credential-expires result) + (pi-credential-region result) + #f + #f + ) ;list + 1000 + ) ;chan-send! + ) ;if + ) ;let + ) ;define + + ;; device_code 事件:(kimi_oauth_device_code provider user-code uri interval expires) + ;; 用真实 user_code/URL 替换占位组件 + (define (pi-app-handle-oauth-device-code! app ev) + (%pi-app-active-selector-set! app + (make-login-device-code (cadr ev) + (list-ref ev 2) + (list-ref ev 3) + (lambda () (pi-app-close-login! app)) + ) ;make-login-device-code + ) ;%pi-app-active-selector-set! + (pi-app-render! app) + ) ;define + + ;; done 事件:成功落盘 + reload_models + 上屏;失败上屏错误卡片; + ;; 用户取消(kimi-oauth-cancelled)静默收尾 + (define (pi-app-handle-oauth-done! app ev) + (let ((provider (cadr ev)) + (access (list-ref ev 2)) + (refresh (list-ref ev 3)) + (expires (list-ref ev 4)) + (region (list-ref ev 5)) + (err-tag (list-ref ev 6)) + (err-msg (list-ref ev 7)) + ) ; + (%kimi-oauth-job-done! app provider access refresh expires region + err-tag err-msg + ) ;%kimi-oauth-job-done! + ) ;let + ) ;define + + (define (%kimi-oauth-job-done! app provider access refresh expires region + err-tag err-msg + ) ;%kimi-oauth-job-done! + (cond + (err-tag + (unless (eq? err-tag 'kimi-oauth-cancelled) + (pi-app-close-login! app) + (container-add! (%pi-app-chat app) + (make-tool-card "login" + '() + 'error + (string-append "Kimi Code OAuth login failed: " (or err-msg "unknown error")) + ) ;make-tool-card + ) ;container-add! + (pi-app-scroll-bottom! app) + (pi-app-render! app) + ) ;unless + ) ;err-tag + (else + (let* ((cfg-dir (gf-get-config-dir)) + (saved-path (catch #t + (lambda () (pi-save-auth-oauth! provider access refresh expires region cfg-dir)) + (lambda (tag . info) #f) + ) ;catch + ) ;saved-path + ) ; + (pi-app-close-login! app) + (if saved-path + (begin + (when (pi-app-jobs-chan app) + (catch #t + (lambda () + (chan-send! (pi-app-jobs-chan app) + (list 'reload_models (path->string (path cfg-dir))) + 1000 + ) ;chan-send! + ) ;lambda + (lambda args #f) + ) ;catch + ) ;when + (container-add! (%pi-app-chat app) + (make-assistant-card (string-append "Saved OAuth credential for " provider " to " saved-path) + ) ;make-assistant-card + ) ;container-add! + ) ;begin + (container-add! (%pi-app-chat app) + (make-tool-card "login" + '() + 'error + (string-append "Failed to save OAuth credential for " provider) + ) ;make-tool-card + ) ;container-add! + ) ;if + (pi-app-scroll-bottom! app) + (pi-app-render! app) + ) ;let* + ) ;else + ) ;cond + ) ;define + (define (%split-args str) (filter (lambda (s) (not (string-null? s))) (string-split str " ")) ) ;define diff --git a/tui/liii/pi/tui/interactive/login-device-code.scm b/tui/liii/pi/tui/interactive/login-device-code.scm new file mode 100644 index 00000000..da571002 --- /dev/null +++ b/tui/liii/pi/tui/interactive/login-device-code.scm @@ -0,0 +1,145 @@ +;; +;; Copyright (C) 2026 The Goldfish Scheme Authors +;; +;; Licensed under the MIT License +;; + +;; device-code 展示组件(对应 pi 的 AuthEvent.type==device_code): +;; 展示 user_code 与 verification_uri_complete,提供「打开浏览器」入口, +;; 下方显示等待授权的轮询态;Esc 取消(置 cancelled 标志,轮询循环据此中止)。 +(define-library (liii pi tui interactive login-device-code) + (export make-login-device-code login-device-code? login-device-code-cancelled? + login-device-code-user-code login-device-code-verification-uri + login-device-code-cursor-position login-device-code-open-browser! + ) ;export + (import (scheme base) + (liii string) + (liii unicode) + (liii web-browser) + (liii tui) + (liii tui component) + ) ;import + (begin + + (define %accent "\x1b;[35m") + (define %muted "\x1b;[38;2;157;165;169m") + (define %border "\x1b;[38;2;91;127;200m") + (define %bold "\x1b;[1m") + (define %reset "\x1b;[0m") + + (define (%colored color text) + (string-append color text %reset) + ) ;define + + (define-record-type + (%make-login-device-code-state provider user-code verification-uri + on-cancel cancelled? browser-opened? + ) ;%make-login-device-code-state + login-device-code-state? + (provider login-device-code-state-provider) + (user-code login-device-code-state-user-code) + (verification-uri login-device-code-state-verification-uri) + (on-cancel login-device-code-state-on-cancel) + (cancelled? login-device-code-state-cancelled? login-device-code-state-cancelled?-set!) + (browser-opened? login-device-code-state-browser-opened? + login-device-code-state-browser-opened?-set! + ) ;browser-opened? + ) ;define-record-type + + (define (%state comp) + (let ((data (component-data comp))) + (and (pair? data) (eq? (car data) 'login-device-code) (cadr data)) + ) ;let + ) ;define + + (define (login-device-code? obj) + (and (component? obj) (login-device-code-state? (%state obj))) + ) ;define + + ;; 轮询循环的 cancelled? 谓词读取此标志 + (define (login-device-code-cancelled? comp) + (login-device-code-state-cancelled? (%state comp)) + ) ;define + + (define (login-device-code-user-code comp) + (login-device-code-state-user-code (%state comp)) + ) ;define + + (define (login-device-code-verification-uri comp) + (login-device-code-state-verification-uri (%state comp)) + ) ;define + + ;; 无输入行:光标停在标题行下方(与 render 布局一致) + (define (login-device-code-cursor-position comp) + '(4 2) + ) ;define + + (define (login-device-code-open-browser! comp) + (let ((state (%state comp))) + (login-device-code-state-browser-opened?-set! state #t) + (catch #t + (lambda () + (web-browser-open (login-device-code-state-verification-uri state)) + ) ;lambda + (lambda args #f) + ) ;catch + ) ;let + ) ;define + + (define (%render comp width) + (let* ((state (%state comp)) + (border (%colored %border (utf8-make-string (max 1 width) #\─))) + (title (string-append "Login to " + (login-device-code-state-provider state) + " with Kimi Code (subscription)" + ) ;string-append + ) ;title + (code-line (string-append " Code: " + (%colored %bold (login-device-code-state-user-code state)) + ) ;string-append + ) ;code-line + (uri (login-device-code-state-verification-uri state)) + (waiting (%colored %muted " Waiting for authorization in browser…")) + (opened-hint + (if (login-device-code-state-browser-opened? state) + (%colored %muted " Browser opened. Complete authorization there.") + (%colored %muted " Browser not opened? Visit the URL above manually.") + ) ;if + ) ;opened-hint + (hint (%colored %muted " enter to open browser · esc to cancel")) + ) ; + (list border "" title "" code-line "" + (string-append " " (%colored %accent uri)) + "" waiting opened-hint "" hint + ) ;list + ) ;let* + ) ;define + + (define (%handle-input comp key) + (let ((state (%state comp))) + (case key + ((escape ctrl-c) + (login-device-code-state-cancelled?-set! state #t) + ((login-device-code-state-on-cancel state)) + #t + ) ; + ((enter) (login-device-code-open-browser! comp) #t) + (else #f) + ) ;case + ) ;let + ) ;define + + (define (make-login-device-code provider user-code verification-uri on-cancel) + (let* ((state (%make-login-device-code-state provider user-code + verification-uri on-cancel #f #f + ) ;%make-login-device-code-state + ) ;state + (comp (make-component :render %render :handle-input %handle-input)) + ) ; + (component-data-set! comp (list 'login-device-code state)) + comp + ) ;let* + ) ;define + + ) ;begin +) ;define-library \ No newline at end of file diff --git a/tui/liii/pi/tui/interactive/login-selector.scm b/tui/liii/pi/tui/interactive/login-selector.scm index 621b89e2..4b224efc 100644 --- a/tui/liii/pi/tui/interactive/login-selector.scm +++ b/tui/liii/pi/tui/interactive/login-selector.scm @@ -5,9 +5,12 @@ ;; ;; 登录供应商选择器:展示各 provider 列表、配置状态(✓ configured / • not configured)、 -;; 模糊搜索与选择流转。 +;; 模糊搜索与选择流转;登记了订阅 OAuth 的 provider(如 kimi-coding) +;; 选中后进入二级选择「API Key / Kimi Code 订阅(OAuth)」。 (define-library (liii pi tui interactive login-selector) - (export make-login-selector login-selector? login-selector-cursor-position) + (export make-login-selector login-selector? login-selector-cursor-position + login-selector-method-mode? + ) ;export (import (scheme base) (scheme process-context) (liii string) @@ -35,7 +38,7 @@ (define-record-type (%make-login-selector-state current providers config-dir on-select - on-cancel search list + on-cancel on-select-method search list method-provider ) ;%make-login-selector-state login-selector-state? (current login-selector-state-current) @@ -43,8 +46,13 @@ (config-dir login-selector-state-config-dir) (on-select login-selector-state-on-select) (on-cancel login-selector-state-on-cancel) + (on-select-method login-selector-state-on-select-method) (search login-selector-state-search login-selector-state-search-set!) (list login-selector-state-list login-selector-state-list-set!) + ;; 非 #f 时处于二级登录方式选择态,值为目标 provider + (method-provider login-selector-state-method-provider + login-selector-state-method-provider-set! + ) ;method-provider ) ;define-record-type (define (%state comp) @@ -71,6 +79,10 @@ ) ;let ) ;define + (define (login-selector-method-mode? comp) + (and (login-selector-state-method-provider (%state comp)) #t) + ) ;define + (define (%non-empty-str? v) (and (string? v) (not (string-null? (string-trim-both v)))) ) ;define @@ -91,7 +103,13 @@ creds ) ;find ) ;cred - (has-auth? (and cred (%non-empty-str? (pi-credential-key cred)))) + (has-auth? + (and cred + (or (%non-empty-str? (pi-credential-key cred)) + (%non-empty-str? (pi-credential-access cred)) + ) ;or + ) ;and + ) ;has-auth? ) ; (if (or has-auth? (%provider-has-env-key? provider)) "✓ configured" @@ -120,6 +138,32 @@ ) ;let ) ;define + ;; 二级登录方式选择:登记了订阅 OAuth 的 provider 展示 + ;; 「API Key / Kimi Code 订阅(OAuth)」两项(1402 §5.4) + (define (%method-items state) + (list (list (cons 'value "api_key") + (cons 'label "API Key") + (cons 'description (%colored %muted "Paste an API key from the console")) + ) ;list + (list (cons 'value "oauth") + (cons 'label "Kimi Code (OAuth)") + (cons 'description (%colored %muted "Sign in with your Kimi Code subscription")) + ) ;list + ) ;list + ) ;define + + (define (%enter-method-mode! state provider) + (login-selector-state-method-provider-set! state provider) + (login-selector-state-list-set! state + (%build-list state (%method-items state) "api_key") + ) ;login-selector-state-list-set! + ) ;define + + (define (%leave-method-mode! state) + (login-selector-state-method-provider-set! state #f) + (%refresh-list! state) + ) ;define + (define (%build-list state items preselect) (let ((lst (make-select-list items @@ -132,9 +176,26 @@ :no-match-text (lambda (text) (%colored %muted text)) :on-select (lambda (item) - ((login-selector-state-on-select state) (cdr (assoc 'value item))) + (let ((value (cdr (assoc 'value item)))) + (if (login-selector-state-method-provider state) + ((login-selector-state-on-select-method state) + (login-selector-state-method-provider state) + value + ) ; + (if (pi-provider-oauth value) + (%enter-method-mode! state value) + ((login-selector-state-on-select state) value) + ) ;if + ) ;if + ) ;let + ) ;lambda + :on-cancel + (lambda () + (if (login-selector-state-method-provider state) + (%leave-method-mode! state) + ((login-selector-state-on-cancel state)) + ) ;if ) ;lambda - :on-cancel (lambda () ((login-selector-state-on-cancel state))) ) ;make-select-list ) ;lst (index @@ -174,24 +235,46 @@ (search-lines (component-render search (max 1 (- width 2)))) (search-line (if (pair? search-lines) (string-append "> " (car search-lines)) "> ") ) ;search-line - (hint (%colored %muted " enter to select · esc to cancel")) + (method-provider (login-selector-state-method-provider state)) + (hint (%colored %muted + (if method-provider + " enter to select · esc to go back" + " enter to select · esc to cancel" + ) ;if + ) ;%colored + ) ;hint ) ; - (append (list border "" "Login Provider" "" - "Select a provider to configure authentication" "" search-line - "" - ) ;list - (component-render (login-selector-state-list state) width) - (list "" hint) - ) ;append + (if method-provider + (append (list border + "" + (string-append "Login to " method-provider) + "" + "Select a login method" + "" + ) ;list + (component-render (login-selector-state-list state) width) + (list "" hint) + ) ;append + (append (list border "" "Login Provider" "" + "Select a provider to configure authentication" "" + search-line "" + ) ;list + (component-render (login-selector-state-list state) width) + (list "" hint) + ) ;append + ) ;if ) ;let* ) ;define (define (%handle-input comp key) (let ((state (%state comp))) - (cond ((memq key '(up down enter escape ctrl-c)) - (component-handle-input (login-selector-state-list state) key) - ) ; - (else (component-handle-input (login-selector-state-search state) key)) + (cond + ((or (memq key '(up down enter escape ctrl-c)) + (login-selector-state-method-provider state) + ) ;or + (component-handle-input (login-selector-state-list state) key) + ) ; + (else (component-handle-input (login-selector-state-search state) key)) ) ;cond ) ;let ) ;define @@ -201,11 +284,15 @@ (current #f) (config-dir #f) (providers #f) + (on-select-method #f) ) ;make-login-selector (let* ((actual-cfg-dir (or config-dir (gf-get-config-dir))) (actual-providers (or providers PI_SUPPORTED_PROVIDERS)) + ;; 未注入二级回调时退化:两种方式都走 on-select(旧行为可用) + (actual-on-method (or on-select-method (lambda (p m) (on-select p)))) (state (%make-login-selector-state current actual-providers - actual-cfg-dir on-select on-cancel #f #f + actual-cfg-dir on-select on-cancel actual-on-method #f #f + #f ) ;%make-login-selector-state ) ;state (search (make-text-input "" diff --git a/tui/liii/pi/tui/interactive/render.scm b/tui/liii/pi/tui/interactive/render.scm index a9e835fa..90d2a57a 100644 --- a/tui/liii/pi/tui/interactive/render.scm +++ b/tui/liii/pi/tui/interactive/render.scm @@ -38,6 +38,7 @@ (liii pi tui interactive session-selector) (liii pi tui interactive login-selector) (liii pi tui interactive login-dialog) + (liii pi tui interactive login-device-code) ) ;import (begin @@ -245,6 +246,9 @@ (login-selector-cursor-position active-selector) ) ; ((login-dialog? active-selector) (login-dialog-cursor-position active-selector)) + ((login-device-code? active-selector) + (login-device-code-cursor-position active-selector) + ) ; (else '(6 2)) ) ;cond ) ;pos diff --git a/tui/liii/pi/tui/interactive/worker-model.scm b/tui/liii/pi/tui/interactive/worker-model.scm index 65ae09ef..1fbf02f5 100644 --- a/tui/liii/pi/tui/interactive/worker-model.scm +++ b/tui/liii/pi/tui/interactive/worker-model.scm @@ -69,7 +69,7 @@ (let* ((config-dir (pi-cfg-config-dir cfg)) (models-store (pi-cfg-ref cfg 'models-store '())) (auth (pi-load-auth config-dir)) - (api-key (pi-resolve-provider-key provider auth)) + (api-key (pi-resolve-provider-key provider auth '() config-dir)) (raw-meta (pi-resolve-model-metadata provider model-id models-store)) (meta (pi-ensure-catalog-meta raw-meta provider model-id models-store)) (supports (pi-model-supports-thinking? models-store provider model-id)) diff --git a/tui/liii/pi/tui/interactive/worker.scm b/tui/liii/pi/tui/interactive/worker.scm index c4dc80ba..1ffa643f 100644 --- a/tui/liii/pi/tui/interactive/worker.scm +++ b/tui/liii/pi/tui/interactive/worker.scm @@ -92,7 +92,7 @@ (let* ((config-dir (pi-cfg-config-dir cfg)) (models-store (pi-cfg-ref cfg 'models-store '())) (auth (pi-load-auth config-dir)) - (api-key (pi-resolve-provider-key provider auth)) + (api-key (pi-resolve-provider-key provider auth '() config-dir)) (raw-meta (pi-resolve-model-metadata provider model-id models-store)) (meta (pi-ensure-catalog-meta raw-meta provider model-id models-store)) (supports (pi-model-supports-thinking? models-store provider model-id)) @@ -216,7 +216,10 @@ ) ;dir (dir-str (if (string? dir) dir (path->string dir))) (cur-p (pi-cfg-ref cfg 'provider)) - (new-key (and cur-p (pi-resolve-provider-key cur-p (pi-load-auth dir-str)))) + (new-key (and cur-p + (pi-resolve-provider-key cur-p (pi-load-auth dir-str) '() dir-str) + ) ;and + ) ;new-key ) ; (%cfg-override cfg (list (cons 'models-store (pi-build-user-catalog dir-str)) diff --git a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-device-code-bang-test.scm b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-device-code-bang-test.scm new file mode 100644 index 00000000..ffc53e9b --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-device-code-bang-test.scm @@ -0,0 +1,55 @@ +;; pi-app-handle-oauth-device-code! +;; 处理 kimi_oauth_device_code 事件:挂载 device-code 组件展示 user_code/URL。 +;; +;; 语法 +;; ---- +;; (pi-app-handle-oauth-device-code! app ev) +;; +;; 参数 +;; ---- +;; app : pi-app? +;; 交互式应用实例。 +;; +;; ev : list? +;; (kimi_oauth_device_code provider user-code uri interval expires)。 +;; +;; 返回值 +;; ---- +;; any +;; 副作用:active-selector 变为 login-device-code 组件。 + +(import (scheme base) + (liii check) + (liii tui) + (liii pi tui interactive state) + (liii pi tui interactive app) + (liii pi tui interactive login-device-code) + (liii pi tui interactive app-login) +) ;import + +(check-set-mode! 'report-failed) + +(let ((app (make-pi-app + :terminal (make-virtual-terminal :width 80 :height 24) + :handler (lambda (a m) #t) + :provider "kimi-coding" + :model "k3-256k" + ) ;make-pi-app + ) ;app + ) ; + (pi-app-handle-oauth-device-code! app + '(kimi_oauth_device_code "kimi-coding" "ABCD-1234" + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234" 1 900) + ) ;pi-app-handle-oauth-device-code! + (let ((sel (pi-app-active-selector app))) + (check-true (login-device-code? sel)) + (check (login-device-code-user-code sel) => "ABCD-1234") + (check (login-device-code-verification-uri sel) + => + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234" + ) ;check + (check-false (login-device-code-cancelled? sel)) + ) ;let +) ;let + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-done-bang-test.scm b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-done-bang-test.scm new file mode 100644 index 00000000..00fb9274 --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-handle-oauth-done-bang-test.scm @@ -0,0 +1,116 @@ +;; pi-app-handle-oauth-done! +;; 处理 kimi_oauth_done 事件:成功落盘 auth.json + reload_models + 上屏, +;; 失败上屏错误卡片,用户取消静默收尾。 +;; +;; 语法 +;; ---- +;; (pi-app-handle-oauth-done! app ev) +;; +;; 参数 +;; ---- +;; app : pi-app? +;; 交互式应用实例。 +;; +;; ev : list? +;; (kimi_oauth_done provider access refresh expires region err-tag err-msg)。 +;; +;; 返回值 +;; ---- +;; any +;; 副作用:凭据落盘(GF_CONFIG_DIR 目录)、选择器关闭、卡片上屏。 + +(import (scheme base) + (liii check) + (liii os) + (liii string) + (liii list) + (liii path) + (liii go) + (liii tempfile) + (liii tui) + (liii tui component) + (liii pi ai auth) + (liii pi ai config credential) + (liii pi tui interactive state) + (liii pi tui interactive app) + (liii pi tui interactive app-login) +) ;import + +(check-set-mode! 'report-failed) + +(define (make-test-app) + (make-pi-app + :terminal (make-virtual-terminal :width 80 :height 24) + :handler (lambda (a m) #t) + :provider "kimi-coding" + :model "k3-256k" + ) ;make-pi-app +) ;define + +(define (chat-lines app) + (apply append (map (lambda (c) (component-render c 80)) (pi-app-chat app))) +) ;define + +;; 1. 成功:落盘 oauth 凭据、关闭选择器、上屏 Saved、发 reload_models +(let* ((tmp (make-temp-dir "gf-oauth-done-" "")) + (saved-env (getenv "GF_CONFIG_DIR")) + (app (make-test-app)) + ) ; + (putenv "GF_CONFIG_DIR" tmp) + (pi-app-handle-oauth-done! app + (list 'kimi_oauth_done "kimi-coding" "acc-tok" "ref-tok" 1893456000000 #f #f #f) + ) ;pi-app-handle-oauth-done! + (check-false (pi-app-active-selector app)) + (let ((creds (pi-load-auth tmp))) + (check (length creds) => 1) + (check-true (pi-credential-oauth? (car creds))) + (check (pi-credential-access (car creds)) => "acc-tok") + ) ;let + (check-true (any (lambda (l) (string-contains? l "Saved OAuth credential for kimi-coding")) + (chat-lines app) + ) ;any + ) ;check-true + ;; reload_models 任务已入队 + (let ((job (chan-recv! (pi-app-jobs-chan app) 1000 'none))) + (check (and (pair? job) (car job)) => 'reload_models) + ) ;let + (if saved-env (putenv "GF_CONFIG_DIR" saved-env) (unsetenv "GF_CONFIG_DIR")) + (path-unlink (path (path-join tmp "auth.json"))) + (path-rmdir tmp) +) ;let* + +;; 2. 失败:错误卡片上屏,不落盘 +(let* ((tmp (make-temp-dir "gf-oauth-done-" "")) + (saved-env (getenv "GF_CONFIG_DIR")) + (app (make-test-app)) + ) ; + (putenv "GF_CONFIG_DIR" tmp) + (pi-app-handle-oauth-done! app + (list 'kimi_oauth_done "kimi-coding" #f #f #f #f 'kimi-oauth-error "denied") + ) ;pi-app-handle-oauth-done! + (check-false (pi-app-active-selector app)) + (check-true (any (lambda (l) (string-contains? l "OAuth login failed")) (chat-lines app)) + ) ;check-true + (check (pi-load-auth tmp) => '()) + (if saved-env (putenv "GF_CONFIG_DIR" saved-env) (unsetenv "GF_CONFIG_DIR")) + (path-rmdir tmp) +) ;let* + +;; 3. 用户取消:静默,无错误卡片 +(let ((app (make-test-app))) + (pi-app-handle-oauth-done! app + (list 'kimi_oauth_done + "kimi-coding" + #f + #f + #f + #f + 'kimi-oauth-cancelled + "Login cancelled" + ) ;list + ) ;pi-app-handle-oauth-done! + (check-false (any (lambda (l) (string-contains? l "OAuth login failed")) (chat-lines app)) + ) ;check-false +) ;let + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm new file mode 100644 index 00000000..dd5ec405 --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm @@ -0,0 +1,146 @@ +;; pi-app-show-login-oauth! +;; 启动 OAuth 设备码登录:挂占位组件,后台 go worker 跑设备授权与轮询, +;; device_code/done 事件经 pi-app-poll-events! 上屏与落盘(stub 端到端)。 +;; +;; 语法 +;; ---- +;; (pi-app-show-login-oauth! app provider) +;; (pi-app-show-login-oauth! app provider opt-config-dir) +;; +;; 参数 +;; ---- +;; app : pi-app? +;; 交互式应用实例。 +;; +;; provider : string? +;; 服务商 id(kimi-coding)。 +;; +;; opt-config-dir : (or string? path?) +;; 可选,配置目录。 +;; +;; 返回值 +;; ---- +;; any +;; 副作用:挂载占位/设备码组件,事件驱动后续流转。 + +(import (scheme base) + (liii check) + (liii os) + (scheme write) + (liii go) + (liii string) + (liii list) + (liii path) + (liii time) + (liii subprocess) + (liii tempfile) + (liii tui) + (liii tui component) + (liii pi ai auth) + (liii pi ai config credential) + (liii pi tui interactive state) + (liii pi tui interactive app) + (liii pi tui interactive login-device-code) + (liii pi tui interactive app-login) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + (if (file-exists? "../ai/tests/stub_kimi_oauth_server.py") + "../ai/tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if + ) ;if +) ;define + +(define (chat-lines app) + (apply append (map (lambda (c) (component-render c 80)) (pi-app-chat app))) +) ;define + +;; 完整链路:占位 → device-code 组件 → Saved 卡片 + 凭据落盘 +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (tmp (make-temp-dir "gf-oauth-show-" "")) + (saved-env (getenv "GF_CONFIG_DIR")) + (saved-host (getenv "KIMI_CODE_OAUTH_HOST")) + (app (make-pi-app + :terminal (make-virtual-terminal :width 80 :height 24) + :handler (lambda (a m) #t) + :provider "kimi-coding" + :model "k3-256k" + ) ;make-pi-app + ) ;app + ) ; + (putenv "GF_CONFIG_DIR" tmp) + (putenv "KIMI_CODE_OAUTH_HOST" host) + (pi-app-show-login-oauth! app "kimi-coding" tmp) + (sleep 1.5) + (let drain () + (let ((ev (chan-try-recv! (pi-app-event-chan app) #f))) + (when ev (display (list "RAWEV" ev)) (newline) (drain)))) + ;; drain 后 selector 仍是占位(device_code 已被消费掉) + ;; 占位组件已挂载 + (check-true (component? (pi-app-active-selector app))) + ;; 轮询事件直至 device-code 组件出现(最多 ~10s) + (let wait + ((n 0)) + (when + (and (< n 100) (not (login-device-code? (pi-app-active-selector app)))) + (pi-app-poll-events! app) + (sleep 0.1) + (wait (+ n 1)) + ) ;when + ) ;let + (begin + (display (list "SELCODE" (login-device-code-user-code (pi-app-active-selector app)))) (newline) + (let ((ls (chat-lines app))) + (for-each (lambda (l) (when (string-contains? l "HOST=") (display (list "LINE" l)) (newline))) ls))) + (check-true (login-device-code? (pi-app-active-selector app))) + (display (list "DBG" port host (getenv "KIMI_CODE_OAUTH_HOST") (login-device-code-user-code (pi-app-active-selector app)))) (newline) + (check (login-device-code-user-code (pi-app-active-selector app)) + => + "ABCD-1234" + ) ;check + ;; 继续轮询直至登录完成(授权由 stub 自动完成) + (let wait + ((n 0)) + (when (and (< n 100) (pi-app-active-selector app)) + (pi-app-poll-events! app) + (sleep 0.1) + (wait (+ n 1)) + ) ;when + ) ;let + (when (pi-app-active-selector app) + (display (list "ENDSEL" (login-device-code-user-code (pi-app-active-selector app)))) (newline)) + (check-false (pi-app-active-selector app)) + (check-true (any (lambda (l) (string-contains? l "Saved OAuth credential for kimi-coding")) + (chat-lines app) + ) ;any + ) ;check-true + (let ((creds (pi-load-auth tmp))) + (check (length creds) => 1) + (check (pi-credential-access (car creds)) => "stub-access-token") + (check (pi-credential-region (car creds)) => host) + ) ;let + (if saved-env (putenv "GF_CONFIG_DIR" saved-env) (unsetenv "GF_CONFIG_DIR")) + (if saved-host + (putenv "KIMI_CODE_OAUTH_HOST" saved-host) + (unsetenv "KIMI_CODE_OAUTH_HOST") + ) ;if + (process-kill proc) + (path-unlink (path (path-join tmp "auth.json"))) + (path-rmdir tmp) +) ;let* + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cancelled-p-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cancelled-p-test.scm new file mode 100644 index 00000000..e11bb6cf --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cancelled-p-test.scm @@ -0,0 +1,55 @@ +;; login-device-code-cancelled? +;; 读取取消标志:Esc/Ctrl-C 后置位,供轮询循环 cancelled? 谓词探测。 +;; +;; 语法 +;; ---- +;; (login-device-code-cancelled? comp) -> boolean? +;; +;; 参数 +;; ---- +;; comp : login-device-code? +;; device-code 组件。 +;; +;; 返回值 +;; ---- +;; boolean? +;; 初始 #f;escape/ctrl-c 输入后 #t。 + +(import (liii check) + (liii tui component) + (liii pi tui interactive login-device-code) +) ;import + +(check-set-mode! 'report-failed) + +(let* ((cancelled-calls 0) + (comp + (make-login-device-code "kimi-coding" + "ABCD-1234" + "https://x.example" + (lambda () (set! cancelled-calls (+ cancelled-calls 1))) + ) ;make-login-device-code + ) ;comp + ) ; + (check-false (login-device-code-cancelled? comp)) + (component-handle-input comp 'escape) + (check-true (login-device-code-cancelled? comp)) + (check cancelled-calls => 1) +) ;let* + +(let ((comp (make-login-device-code "kimi-coding" "A" "https://x.example" (lambda () #f)) + ) ;comp + ) ; + (component-handle-input comp 'ctrl-c) + (check-true (login-device-code-cancelled? comp)) +) ;let + +;; 其它按键不置位 +(let ((comp (make-login-device-code "kimi-coding" "A" "https://x.example" (lambda () #f)) + ) ;comp + ) ; + (component-handle-input comp #\a) + (check-false (login-device-code-cancelled? comp)) +) ;let + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cursor-position-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cursor-position-test.scm new file mode 100644 index 00000000..268dcc5a --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-cursor-position-test.scm @@ -0,0 +1,28 @@ +;; login-device-code-cursor-position +;; 组件光标相对坐标(无输入行,固定停靠在标题下方)。 +;; +;; 语法 +;; ---- +;; (login-device-code-cursor-position comp) -> list? +;; +;; 参数 +;; ---- +;; comp : login-device-code? +;; device-code 组件。 +;; +;; 返回值 +;; ---- +;; list? +;; (row col) 整数列表,与 render 布局一致。 + +(import (liii check) (liii pi tui interactive login-device-code)) + +(check-set-mode! 'report-failed) + +(let ((comp (make-login-device-code "kimi-coding" "A" "https://x.example" (lambda () #f)) + ) ;comp + ) ; + (check (login-device-code-cursor-position comp) => '(4 2)) +) ;let + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-open-browser-bang-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-open-browser-bang-test.scm new file mode 100644 index 00000000..990ef170 --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-open-browser-bang-test.scm @@ -0,0 +1,45 @@ +;; login-device-code-open-browser! +;; 打开浏览器访问验证 URL;Enter 触发,渲染提示随之切换。 +;; +;; 语法 +;; ---- +;; (login-device-code-open-browser! comp) +;; +;; 参数 +;; ---- +;; comp : login-device-code? +;; device-code 组件。 +;; +;; 返回值 +;; ---- +;; any +;; 副作用:调 web-browser-open(无浏览器环境静默失败), +;; 渲染显示「Browser opened」提示。 + +(import (scheme base) + (liii check) + (liii string) + (liii list) + (liii tui component) + (liii pi tui interactive login-device-code) +) ;import + +(check-set-mode! 'report-failed) + +;; 初始渲染:提示手动打开 +(let ((comp (make-login-device-code "kimi-coding" "A" "https://x.example" (lambda () #f)) + ) ;comp + ) ; + (check-true (any (lambda (l) (string-contains? l "manually")) (component-render comp 80)) + ) ;check-true + ;; Enter 打开浏览器(headless 环境 web-browser-open 返回 #f,不抛错) + (component-handle-input comp 'enter) + (check-true (any (lambda (l) (string-contains? l "Browser opened")) + (component-render comp 80) + ) ;any + ) ;check-true + ;; 显式调用同样安全 + (login-device-code-open-browser! comp) +) ;let + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-p-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-p-test.scm new file mode 100644 index 00000000..f665fe4e --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-p-test.scm @@ -0,0 +1,41 @@ +;; login-device-code? +;; 判断组件是否为 login-device-code。 +;; +;; 语法 +;; ---- +;; (login-device-code? obj) -> boolean? +;; +;; 参数 +;; ---- +;; obj : any +;; 任意对象。 +;; +;; 返回值 +;; ---- +;; boolean? +;; make-login-device-code 构造的组件为 #t。 + +(import (liii check) + (liii tui) + (liii tui component) + (liii pi tui interactive login-device-code) + (liii pi tui interactive login-dialog) +) ;import + +(check-set-mode! 'report-failed) + +(check-true (login-device-code? (make-login-device-code "kimi-coding" + "ABCD-1234" + "https://x.example" + (lambda () #f) + ) ;make-login-device-code + ) ;login-device-code? +) ;check-true +(check-false + (login-device-code? (make-login-dialog "kimi-coding" (lambda (k) #f) (lambda () #f)) + ) ;login-device-code? +) ;check-false +(check-false (login-device-code? "x")) +(check-false (login-device-code? #f)) + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-user-code-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-user-code-test.scm new file mode 100644 index 00000000..d3b2052d --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-user-code-test.scm @@ -0,0 +1,32 @@ +;; login-device-code-user-code +;; 读取组件展示的用户码。 +;; +;; 语法 +;; ---- +;; (login-device-code-user-code comp) -> string? +;; +;; 参数 +;; ---- +;; comp : login-device-code? +;; device-code 组件。 +;; +;; 返回值 +;; ---- +;; string? +;; 构造时传入的 user_code。 + +(import (liii check) (liii pi tui interactive login-device-code)) + +(check-set-mode! 'report-failed) + +(check (login-device-code-user-code (make-login-device-code "kimi-coding" + "WXYZ-5678" + "https://x.example" + (lambda () #f) + ) ;make-login-device-code + ) ;login-device-code-user-code + => + "WXYZ-5678" +) ;check + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-verification-uri-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-verification-uri-test.scm new file mode 100644 index 00000000..2fe712c0 --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/login-device-code-verification-uri-test.scm @@ -0,0 +1,32 @@ +;; login-device-code-verification-uri +;; 读取组件展示的验证 URL(verification_uri_complete)。 +;; +;; 语法 +;; ---- +;; (login-device-code-verification-uri comp) -> string? +;; +;; 参数 +;; ---- +;; comp : login-device-code? +;; device-code 组件。 +;; +;; 返回值 +;; ---- +;; string? +;; 构造时传入的验证 URL。 + +(import (liii check) (liii pi tui interactive login-device-code)) + +(check-set-mode! 'report-failed) + +(check (login-device-code-verification-uri (make-login-device-code "kimi-coding" + "A" + "https://www.kimi.com/code/authorize_device?user_code=A" + (lambda () #f) + ) ;make-login-device-code + ) ;login-device-code-verification-uri + => + "https://www.kimi.com/code/authorize_device?user_code=A" +) ;check + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/make-login-device-code-test.scm b/tui/tests/liii/pi/tui/interactive/login-device-code/make-login-device-code-test.scm new file mode 100644 index 00000000..9d9b13ae --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/make-login-device-code-test.scm @@ -0,0 +1,58 @@ +;; make-login-device-code +;; 构造 device-code 展示组件:user_code + verification URL + 轮询态。 +;; +;; 语法 +;; ---- +;; (make-login-device-code provider user-code verification-uri on-cancel) +;; +;; 参数 +;; ---- +;; provider : string? +;; 服务商 id。 +;; +;; user-code : string? +;; 用户码(形如 ABCD-1234)。 +;; +;; verification-uri : string? +;; 带 user_code 的验证 URL。 +;; +;; on-cancel : procedure? +;; Esc 取消回调。 +;; +;; 返回值 +;; ---- +;; component? +;; login-device-code 组件;渲染含 user_code 与 URL。 + +(import (scheme base) + (liii check) + (liii string) + (liii list) + (liii tui) + (liii tui component) + (liii pi tui interactive login-device-code) +) ;import + +(check-set-mode! 'report-failed) + +(let ((comp (make-login-device-code "kimi-coding" + "ABCD-1234" + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234" + (lambda () #f) + ) ;make-login-device-code + ) ;comp + ) ; + (check-true (component? comp)) + (check-true (login-device-code? comp)) + (let ((lines (component-render comp 80))) + (check-true (any (lambda (l) (string-contains? l "ABCD-1234")) lines)) + (check-true (any (lambda (l) (string-contains? l "authorize_device?user_code=ABCD-1234")) + lines + ) ;any + ) ;check-true + (check-true (any (lambda (l) (string-contains? l "Waiting")) lines)) + (check-true (any (lambda (l) (string-contains? l "kimi-coding")) lines)) + ) ;let +) ;let + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-selector/login-selector-method-mode-p-test.scm b/tui/tests/liii/pi/tui/interactive/login-selector/login-selector-method-mode-p-test.scm new file mode 100644 index 00000000..5f34777d --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-selector/login-selector-method-mode-p-test.scm @@ -0,0 +1,97 @@ +;; login-selector-method-mode? +;; 判断选择器是否处于二级登录方式选择态(API Key / Kimi Code OAuth)。 +;; +;; 语法 +;; ---- +;; (login-selector-method-mode? comp) -> boolean? +;; +;; 参数 +;; ---- +;; comp : login-selector? +;; 登录供应商选择器。 +;; +;; 返回值 +;; ---- +;; boolean? +;; 选中登记了 OAuth 的 provider(kimi-coding)后为 #t; +;; Esc 返回供应商列表后为 #f。 + +(import (scheme base) + (liii check) + (liii string) + (liii list) + (liii tui component) + (liii pi tui interactive login-selector) +) ;import + +(check-set-mode! 'report-failed) + +(define (make-sel on-method) + (make-login-selector (lambda (p) #f) + (lambda () #f) + :config-dir "/tmp/gf-nonexistent-cfg" + :on-select-method on-method + ) ;make-login-selector +) ;define + +;; 初始为供应商列表态 +(let ((sel (make-sel (lambda (p m) #f)))) + (check-false (login-selector-method-mode? sel)) + ;; 搜索 kimi 并回车:进入二级选择 + (for-each (lambda (c) (component-handle-input sel c)) '(#\k #\i #\m #\i)) + (component-handle-input sel 'enter) + (check-true (login-selector-method-mode? sel)) + ;; Esc 返回供应商列表 + (component-handle-input sel 'escape) + (check-false (login-selector-method-mode? sel)) +) ;let + +;; 二级选择:down + enter 选 OAuth;enter 直接选 API Key +(let ((picked '())) + (let ((sel + (make-sel + (lambda (p m) (set! picked (cons (list p m) picked))) + ) ;make-sel + ) ;sel + (type-kimi + (lambda (s) + (for-each (lambda (c) (component-handle-input s c)) '(#\k #\i #\m + #\i)) + ) ;lambda + ) ;type-kimi + ) ; + (type-kimi sel) + (component-handle-input sel 'enter) + (component-handle-input sel 'down) + (component-handle-input sel 'enter) + (check picked => '(("kimi-coding" "oauth"))) + ) ;let +) ;let + +(let ((picked '())) + (let ((sel (make-sel (lambda (p m) (set! picked (cons (list p m) picked)))))) + (for-each (lambda (c) (component-handle-input sel c)) '(#\k #\i #\m #\i)) + (component-handle-input sel 'enter) + (component-handle-input sel 'enter) + (check picked => '(("kimi-coding" "api_key"))) + ) ;let +) ;let + +;; 未登记 OAuth 的 provider 不进入二级选择 +(let ((selected '())) + (let ((sel + (make-login-selector (lambda (p) (set! selected (cons p selected))) + (lambda () #f) + :config-dir "/tmp/gf-nonexistent-cfg" + :on-select-method (lambda (p m) #f) + ) ;make-login-selector + ) ;sel + ) ; + (for-each (lambda (c) (component-handle-input sel c)) '(#\d #\e #\e #\p)) + (component-handle-input sel 'enter) + (check-false (login-selector-method-mode? sel)) + (check selected => '("deepseek")) + ) ;let +) ;let + +(check-report) From 1706f8457d338d2398338ad580b58045ca492aa0 Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 18:07:57 +0800 Subject: [PATCH 2/9] =?UTF-8?q?[1404]=20OAuth=20=E5=87=AD=E6=8D=AE?= =?UTF-8?q?=E6=94=B6=E5=88=B0=20401=20=E5=90=8E=E5=BC=BA=E5=88=B6=E5=88=B7?= =?UTF-8?q?=E6=96=B0=E9=87=8D=E8=AF=95=E4=B8=80=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 服务端可能在本地 expires 之前判 access token 失效返回 401, 1402 仅在请求前用 expires 判断刷新,请求层无 401 回退,直接 HTTP 401 stream error 失败。本任务仿照 pi-rotate-api-key! 钩子 范式新增 401 后 oauth 强制刷新回退: - keyring: 新增 pi-oauth-refresh-enabled? / pi-refresh-oauth-key! - resolve: 导出 pi-force-refresh-oauth-credential-key(不查 expires) 与 pi-has-oauth-credential? - config: provider 有 oauth 凭据时注入 refresh-oauth-key 闭包钩子 - 请求层 stream/request: cond 新增 401 分支,配 refreshed-once? 状态位,强制刷新成功 (loop 1 next) 重试一次,失败走 401 报错 - 401 触发刷新时 pi-log-error! 写 [oauth-401] 日志到 ~/.gf/agent/logs/pi-YYYY-MM-DD.log(含 provider、新旧 token 末 4 位、 refresh 结果),便于事后排查 只重试一次、仅 oauth provider、复用 %pi-refresh-oauth-credential! 落盘/清除回调。配套单测覆盖 keyring 钩子返回类型、resolve 强制刷新 不查 expires、401→refresh→200/401 场景。 --- .../pi/ai/api/openai-completions/request.scm | 57 ++++++- .../pi/ai/api/openai-completions/stream.scm | 46 +++++- ai/liii/pi/ai/auth/oauth/resolve.scm | 16 ++ ai/liii/pi/ai/keyring.scm | 28 +++- .../liii/pi/ai/auth/oauth/resolve/README.md | 27 ++++ ...orce-refresh-oauth-credential-key-test.scm | 140 ++++++++++++++++++ .../pi-has-oauth-credential-p-test.scm | 47 ++++++ ai/tests/liii/pi/ai/keyring/README.md | 4 + .../pi-oauth-refresh-enabled-p-test.scm | 39 +++++ .../pi-refresh-oauth-key-bang-test.scm | 67 +++++++++ code/liii/pi/code/config.scm | 112 ++++++++++---- 11 files changed, 545 insertions(+), 38 deletions(-) create mode 100644 ai/tests/liii/pi/ai/auth/oauth/resolve/README.md create mode 100644 ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm create mode 100644 ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm create mode 100644 ai/tests/liii/pi/ai/keyring/pi-oauth-refresh-enabled-p-test.scm create mode 100644 ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm diff --git a/ai/liii/pi/ai/api/openai-completions/request.scm b/ai/liii/pi/ai/api/openai-completions/request.scm index 825f49ac..cedc83c9 100644 --- a/ai/liii/pi/ai/api/openai-completions/request.scm +++ b/ai/liii/pi/ai/api/openai-completions/request.scm @@ -40,6 +40,41 @@ ) ;cond ) ;define + ;; 1404:取 token 末 4 位用于日志,不泄露完整 token;空/短串安全 + (define (%token-tail s) + (if (and (string? s) (> (string-length s) 0)) + (let ((n (string-length s))) + (substring s (max 0 (- n 4)) n)) + "") + ) ;define + + ;; 1404:oauth 401 强制刷新结果描述(用于日志),不暴露完整 token + (define (%oauth-refresh-result-desc next) + (cond ((string? next) + (string-append "ok new-token=..." (%token-tail next))) + ((eq? next 'unauthorized) "unauthorized") + (else "none")) + ) ;define + + ;; 1404:写一行 [oauth-401] 日志到 ~/.gf/agent/logs/pi-YYYY-MM-DD.log + (define (%log-oauth-401 provider attempt api-key next) + (pi-log-error! + (string-append "[oauth-401] provider=" (or provider "") + " attempt=" (number->string attempt) + " old-token=..." (%token-tail api-key) + " refresh=" (%oauth-refresh-result-desc next)) + ) ;pi-log-error! + ) ;define + + ;; 401 报错结算:解析响应体构造 assistant 消息(oauth 刷新失败或重试耗尽后复用) + (define (%parse-401-response body-str status provider model-id) + (let* ((parsed-json (catch #t (lambda () (string->json body-str)) (lambda args #f)))) + (openai-parse-response parsed-json status provider model-id + "openai-completions" + ) ;openai-parse-response + ) ;let* + ) ;define + (define (openai-build-endpoint base-url) (let* ((u (make-uri (or base-url "https://api.openai.com/v1"))) (raw-path (or (uri-path u) "")) @@ -279,7 +314,8 @@ (session-id (pi-cfg-ref config 'session-id)) ) ; (let loop - ((attempt 1) (api-key (pi-request-api-key config))) + ((attempt 1) (api-key (pi-request-api-key config)) + (refreshed-once? #f)) (let* ((extra-hdrs (%openai-extra-headers url provider session-id config settings)) (headers (openai-build-headers api-key extra-hdrs)) (resp (%post-openai url req-json-str headers proxy-alist timeout)) @@ -311,7 +347,7 @@ model-id (%resp-field resp 'reason) ) ;%make-retry-error - (loop 1 next) + (loop 1 next refreshed-once?) ) ;if ) ;let ) ; @@ -325,7 +361,7 @@ ) ; (pi-log-retry retry-status attempt provider-max-retries delay-sec ra-sec) (sleep delay-sec) - (loop (+ attempt 1) api-key) + (loop (+ attempt 1) api-key refreshed-once?) ) ;let* (%make-retry-error status attempt @@ -336,6 +372,21 @@ ) ;%make-retry-error ) ;if ) ; + ;; 1404:oauth 凭据收到 401 后强制刷新重试一次(仅一次)。 + ;; 服务端可能在本地 expires 之前判 access token 失效返回 401, + ;; 此时请求层回退强制 refresh 换取新 token 重试;refresh 失败 + ;; (401/403/invalid_grant)凭据已清除,走 401 报错提示重 /login。 + ((and (= status 401) + (pi-oauth-refresh-enabled? config) + (not refreshed-once?)) + (let ((next (pi-refresh-oauth-key! config api-key))) + (%log-oauth-401 provider attempt api-key next) + (if (string? next) + (loop 1 next #t) + (%parse-401-response body-str status provider model-id) + ) ;if + ) ;let + ) ; (else (let* ((parsed-json (catch #t (lambda () (string->json body-str)) (lambda args #f))) (limit (pi-usage-limit-error? status body-str provider)) diff --git a/ai/liii/pi/ai/api/openai-completions/stream.scm b/ai/liii/pi/ai/api/openai-completions/stream.scm index eed632c2..cbd6ed44 100644 --- a/ai/liii/pi/ai/api/openai-completions/stream.scm +++ b/ai/liii/pi/ai/api/openai-completions/stream.scm @@ -38,6 +38,35 @@ (else #f) ) ;cond ) ;define + + (define (%token-tail s) + (if (and (string? s) (> (string-length s) 0)) + (let ((n (string-length s))) + (substring s (max 0 (- n 4)) n) + ) ;let + "" + ) ;if + ) ;define + + (define (%oauth-refresh-result-desc next) + (cond ((string? next) (string-append "ok new-token=..." (%token-tail next))) + ((eq? next 'unauthorized) "unauthorized") + (else "none") + ) ;cond + ) ;define + + (define (%log-oauth-401 provider attempt api-key next) + (pi-log-error! (string-append "[oauth-401] provider=" + (or provider "") + " attempt=" + (number->string attempt) + " old-token=..." + (%token-tail api-key) + " refresh=" + (%oauth-refresh-result-desc next) + ) ;string-append + ) ;pi-log-error! + ) ;define (define (%build-stream-cb stream-state on-event effective-idle on-idle on-abort err-acc) (let* ((last-act (pi-current-monotonic-seconds)) (decoder (make-openai-stream-decoder stream-state on-event)) @@ -244,7 +273,7 @@ ) ; ) ; (let loop - ((attempt 1) (api-key (pi-request-api-key config))) + ((attempt 1) (api-key (pi-request-api-key config)) (refreshed-once? #f)) (let* ((extra-hdrs (%openai-extra-headers url provider session-id config settings)) (headers (openai-build-headers api-key extra-hdrs)) (stream-state (%init-openai-stream-state)) @@ -308,7 +337,7 @@ (let ((next (pi-rotate-api-key! config api-key status))) (if (eq? next 'exhausted) (%make-stream-error status resp err-acc provider model-id) - (loop 1 next) + (loop 1 next refreshed-once?) ) ;if ) ;let ) ; @@ -322,11 +351,22 @@ ) ; (pi-log-retry retry-status attempt provider-r delay-sec ra-sec) (sleep delay-sec) - (loop (+ attempt 1) api-key) + (loop (+ attempt 1) api-key refreshed-once?) ) ;let* (%make-stream-error status resp err-acc provider model-id) ) ;if ) ; + ;; 1404:oauth 凭据收到 401 后强制刷新重试一次(仅一次); + ;; refresh 失败(401/403/invalid_grant)凭据已清除,走 401 报错提示重 /login。 + ((and (= status 401) (pi-oauth-refresh-enabled? config) (not refreshed-once?)) + (let ((next (pi-refresh-oauth-key! config api-key))) + (%log-oauth-401 provider attempt api-key next) + (if (string? next) + (loop 1 next #t) + (%make-stream-error status resp err-acc provider model-id) + ) ;if + ) ;let + ) ; ((or (zero? status) (not (= status 200))) (%make-stream-error status resp err-acc provider model-id) ) ; diff --git a/ai/liii/pi/ai/auth/oauth/resolve.scm b/ai/liii/pi/ai/auth/oauth/resolve.scm index 9ca45796..f657f148 100644 --- a/ai/liii/pi/ai/auth/oauth/resolve.scm +++ b/ai/liii/pi/ai/auth/oauth/resolve.scm @@ -17,6 +17,8 @@ (export pi-find-oauth-credential pi-resolve-oauth-credential-key ;; go worker 会话重求值调用链上的助手须导出 %pi-refresh-oauth-credential! + ;; 1404:请求层收到 401 后的强制刷新(不查 expires)与凭据探测 + pi-force-refresh-oauth-credential-key pi-has-oauth-credential? ) ;export (begin @@ -90,5 +92,19 @@ ) ;let ) ;define + ;; 1404:强制刷新(不查 expires),供请求层收到 401 后回退使用。 + ;; 语义与 pi-resolve-oauth-credential-key 的过期分支一致,仅省略 expires + ;; 判断:直接走 %pi-refresh-oauth-credential!,成功落盘返回新 access, + ;; 401/403/invalid_grant 经 remove! 清除并返回 #f,其余失败保留凭据返回 #f。 + (define (pi-force-refresh-oauth-credential-key cred opt-env save! remove!) + (%pi-refresh-oauth-credential! cred opt-env save! remove!) + ) ;define + + ;; 1404:在凭据列表中探测 provider 是否有 oauth 凭据,供 config 注入 + ;; refresh-oauth-key 钩子时判定(无 oauth 凭据则不注入,401 按现状失败) + (define (pi-has-oauth-credential? target auth-list) + (and (pi-find-oauth-credential target auth-list) #t) + ) ;define + ) ;begin ) ;define-library \ No newline at end of file diff --git a/ai/liii/pi/ai/keyring.scm b/ai/liii/pi/ai/keyring.scm index 8a0dd328..69c6fa4d 100644 --- a/ai/liii/pi/ai/keyring.scm +++ b/ai/liii/pi/ai/keyring.scm @@ -12,9 +12,15 @@ (define-library (liii pi ai keyring) (import (scheme base) (liii pi ai config runtime)) - (export pi-request-api-key pi-key-rotation? pi-rotate-api-key!) - (begin + (export pi-request-api-key + pi-key-rotation? + pi-rotate-api-key! + ;; 1404:oauth 凭据收到 401 后强制刷新重试一次 + pi-oauth-refresh-enabled? + pi-refresh-oauth-key! + ) ;export + (begin (define (%config-ref config key) (pi-cfg-ref config key) ) ;define @@ -45,5 +51,23 @@ ) ;let ) ;define* + ;; 1404:是否启用 401 后 oauth 强制刷新:由配置是否注入 + ;; refresh-oauth-key 钩子决定(仅 oauth provider 注入)。 + (define (pi-oauth-refresh-enabled? config) + (procedure? (%config-ref config 'refresh-oauth-key)) + ) ;define + + ;; 1404:401 后强制刷新 oauth 凭据: + ;; 钩子签名 (lambda (config current-key) ...) 返回 + ;; string? - 新 access token,调用方用其重试一次 + ;; 'unauthorized - refresh 失败(401/403/invalid_grant),凭据已清除,需重 /login + ;; #f - 非 oauth/无凭据/不适用,调用方按现状 401 报错 + ;; 无钩子时返回 #f(调用方走既有 401 报错路径)。 + (define (pi-refresh-oauth-key! config current-key) + (let ((hook (%config-ref config 'refresh-oauth-key))) + (if (procedure? hook) (hook config current-key) #f) + ) ;let + ) ;define + ) ;begin ) ;define-library diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/README.md b/ai/tests/liii/pi/ai/auth/oauth/resolve/README.md new file mode 100644 index 00000000..578291ca --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/README.md @@ -0,0 +1,27 @@ +# (liii pi ai auth oauth resolve) 模块函数索引 + +`(liii pi ai auth oauth resolve)` 提供 OAuth 凭据的解析与透明刷新,供 `pi-resolve-provider-key` 的 oauth 分支与请求层 401 回退使用。 + +使用时导入: + +```scheme +(import (liii pi ai auth oauth resolve)) +``` + +## 查看函数文档 + +使用以下命令查看函数文档和测试用例: + +```bash +gf doc pi-resolve-oauth-credential-key +``` + +## 函数分类索引 + +### 凭据查找 +- `pi-find-oauth-credential` - 在凭据列表中按 provider 精确匹配 oauth 凭据 +- `pi-has-oauth-credential?` - 探测凭据列表中是否存在某 provider 的 oauth 凭据 + +### 凭据解析与刷新 +- `pi-resolve-oauth-credential-key` - oauth 凭据 → access token:未过期直接返回,过期透明刷新并落盘 +- `pi-force-refresh-oauth-credential-key` - 强制刷新(不查 expires),供请求层收到 401 后回退使用 diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm new file mode 100644 index 00000000..aea735a0 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm @@ -0,0 +1,140 @@ +;; pi-force-refresh-oauth-credential-key +;; 强制刷新 oauth 凭据(不查 expires),供请求层收到 401 后回退使用。 +;; +;; 语法 +;; ---- +;; (pi-force-refresh-oauth-credential-key cred opt-env save! remove!) +;; -> string? 或 #f +;; +;; 参数 +;; ---- +;; cred : pi-credential? +;; oauth 凭据(expires 字段不被检查)。 +;; +;; opt-env : list? +;; 自定义环境变量表(KIMI_CODE_OAUTH_HOST 覆盖)。 +;; +;; save! : procedure? +;; 刷新成功后的落盘回调 (lambda (new-cred) ...)。 +;; +;; remove! : procedure? +;; 401/403/invalid_grant 时的清除回调 (lambda (provider) ...)。 +;; +;; 返回值 +;; ---- +;; string? 或 #f +;; 成功返回新 access token;401/403/invalid_grant 时已调 remove! 返回 #f; +;; 其余失败保留凭据返回 #f。 + +(import (scheme base) + (liii check) + (liii string) + (liii subprocess) + (liii pi ai time) + (liii pi ai config credential) + (liii pi ai auth oauth resolve) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (if (file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + "ai/tests/stub_kimi_oauth_server.py" + ) ;if +) ;define + +;; 1. expires 仍在未来也强制刷新(与 pi-resolve-oauth-credential-key 的区别) +(let* ((proc (process-spawn (list "python3" stub-file "refresh-ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ;; expires 设为 1 小时后:普通 resolve 会直接返回 access,强制刷新必须刷新 + (cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "stub-refresh-token" + (+ (pi-current-time-millis) 3600000) + host + ) ;pi-credential + ) ;cred + (saved '()) + (removed '()) + ) ; + (check + (pi-force-refresh-oauth-credential-key cred + '() + (lambda (c) (set! saved (cons c saved))) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-force-refresh-oauth-credential-key + => + "stub-access-token-2" + ) ;check + (check (length saved) => 1) + (check (pi-credential-refresh (car saved)) => "stub-refresh-token-2") + (check removed => '()) + (process-kill proc) +) ;let* + +;; 2. 401 invalid_grant:remove! 被调用,返回 #f +(let* ((proc (process-spawn (list "python3" stub-file "refresh-401") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "stub-refresh-token" + (+ (pi-current-time-millis) 3600000) + host + ) ;pi-credential + ) ;cred + (saved '()) + (removed '()) + ) ; + (check + (pi-force-refresh-oauth-credential-key cred + '() + (lambda (c) (set! saved (cons c saved))) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-force-refresh-oauth-credential-key + => + #f + ) ;check + (check saved => '()) + (check removed => '("kimi-coding")) + (process-kill proc) +) ;let* + +;; 3. 网络不可达(region 指向死端口):保留凭据(不 remove),返回 #f +(let* ((cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "ref" + (+ (pi-current-time-millis) 3600000) + "http://127.0.0.1:1" + ) ;pi-credential + ) ;cred + (removed '()) + ) ; + (check + (pi-force-refresh-oauth-credential-key cred + '() + (lambda (c) #f) + (lambda (p) (set! removed (cons p removed))) + ) ;pi-force-refresh-oauth-credential-key + => + #f + ) ;check + (check removed => '()) +) ;let* + +(check-report) diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm new file mode 100644 index 00000000..8ba15fd2 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm @@ -0,0 +1,47 @@ +;; pi-has-oauth-credential? +;; 探测凭据列表中是否存在某 provider 的 oauth 凭据。 +;; +;; 语法 +;; ---- +;; (pi-has-oauth-credential? target auth-list) -> boolean? +;; +;; 参数 +;; ---- +;; target : string? 或 #f +;; 服务商 id。 +;; +;; auth-list : list? +;; pi-load-auth 返回的凭据列表。 +;; +;; 返回值 +;; ---- +;; boolean? +;; 存在匹配的 oauth 凭据返回 #t,否则 #f;api_key 条目不算。 + +(import (scheme base) + (liii check) + (liii pi ai config credential) + (liii pi ai auth oauth resolve) +) ;import + +(check-set-mode! 'report-failed) + +(define *oauth* + (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f) +) ;define + +(define *api-key* (pi-credential "kimi-coding" "sk-x" "api_key")) + +(define *other* (pi-credential "deepseek" "sk-ds" "api_key")) + +(check-true (pi-has-oauth-credential? "kimi-coding" (list *other* *oauth*))) +(check-true + (not (pi-has-oauth-credential? "kimi-coding" (list *api-key*))) +) ;check-true +(check-true + (not (pi-has-oauth-credential? "deepseek" (list *other* *oauth*))) +) ;check-true +(check-true (not (pi-has-oauth-credential? "kimi-coding" '()))) +(check-true (not (pi-has-oauth-credential? #f (list *oauth*)))) + +(check-report) diff --git a/ai/tests/liii/pi/ai/keyring/README.md b/ai/tests/liii/pi/ai/keyring/README.md index b565cb5d..a2fd8745 100644 --- a/ai/tests/liii/pi/ai/keyring/README.md +++ b/ai/tests/liii/pi/ai/keyring/README.md @@ -22,3 +22,7 @@ gf doc pi-request-api-key - `pi-request-api-key` - 获取本次请求使用的 API 密钥 - `pi-key-rotation?` - 检查配置是否支持自动换 key - `pi-rotate-api-key!` - 触发密钥轮换钩子获取新密钥 + +### OAuth 401 强制刷新回退 +- `pi-oauth-refresh-enabled?` - 检查配置是否启用 401 后 OAuth 强制刷新 +- `pi-refresh-oauth-key!` - 触发 OAuth 强制刷新钩子获取新 access token diff --git a/ai/tests/liii/pi/ai/keyring/pi-oauth-refresh-enabled-p-test.scm b/ai/tests/liii/pi/ai/keyring/pi-oauth-refresh-enabled-p-test.scm new file mode 100644 index 00000000..d5f3cf34 --- /dev/null +++ b/ai/tests/liii/pi/ai/keyring/pi-oauth-refresh-enabled-p-test.scm @@ -0,0 +1,39 @@ +;; pi-oauth-refresh-enabled? +;; 判断当前配置是否启用了 401 后 OAuth 强制刷新回退。 +;; +;; 语法 +;; ---- +;; (pi-oauth-refresh-enabled? config) +;; +;; 参数 +;; ---- +;; config : alist? +;; 请求配置关联表。 +;; +;; 返回值 +;; ---- +;; boolean +;; 当配置中包含有效的 refresh-oauth-key 过程钩子时返回 #t,否则返回 #f。 + +(import (liii check) (liii pi ai keyring)) + +(check-set-mode! 'report-failed) + +(check-true + (not (pi-oauth-refresh-enabled? (list (cons 'api-key "k")))) +) ;check-true + +(let ((cfg + (list (cons 'api-key "k1") + (cons 'refresh-oauth-key (lambda (config current-key) "new-acc")) + ) ;list + ) ;cfg + ) ; + (check-true (pi-oauth-refresh-enabled? cfg)) +) ;let + +(check-true + (not (pi-oauth-refresh-enabled? (list (cons 'refresh-oauth-key "nope")))) +) ;check-true + +(check-report) diff --git a/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm b/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm new file mode 100644 index 00000000..f4a308ed --- /dev/null +++ b/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm @@ -0,0 +1,67 @@ +;; pi-refresh-oauth-key! +;; 触发 OAuth 强制刷新钩子,请求层收到 401 后用其换取新 access token。 +;; +;; 语法 +;; ---- +;; (pi-refresh-oauth-key! config current-key) +;; +;; 参数 +;; ---- +;; config : alist? +;; 请求配置关联表。 +;; +;; current-key : string? +;; 收到 401 时正在使用的(疑似失效的)access token。 +;; +;; 返回值 +;; ---- +;; string?、'unauthorized 或 #f +;; 成功返回新 access token 字符串;refresh 失败(401/403/invalid_grant) +;; 凭据已清除返回 'unauthorized;非 oauth/无凭据/无钩子返回 #f。 + +(import (liii check) (liii pi ai keyring)) + +(check-set-mode! 'report-failed) + +;; 无钩子:返回 #f(调用方按现状 401 报错) +(check (pi-refresh-oauth-key! (list (cons 'api-key "k")) "k") => #f) + +;; 委托 refresh-oauth-key 钩子返回新 access +(let ((seen '())) + (let ((cfg + (list (cons 'api-key "old-acc") + (cons 'refresh-oauth-key + (lambda (config current-key) + (set! seen (list current-key)) + "new-acc" + ) ;lambda + ) ;cons + ) ;list + ) ;cfg + ) ; + (check (pi-refresh-oauth-key! cfg "old-acc") => "new-acc") + (check seen => '("old-acc")) + ) ;let +) ;let + +;; 钩子返回 'unauthorized(refresh 失败,凭据已清除,需重 /login) +(check + (pi-refresh-oauth-key! + (list (cons 'refresh-oauth-key (lambda (config current-key) 'unauthorized))) + "old-acc" + ) ;pi-refresh-oauth-key! + => + 'unauthorized +) ;check + +;; 钩子返回 #f(非 oauth/无凭据/不适用) +(check + (pi-refresh-oauth-key! + (list (cons 'refresh-oauth-key (lambda (config current-key) #f))) + "old-acc" + ) ;pi-refresh-oauth-key! + => + #f +) ;check + +(check-report) diff --git a/code/liii/pi/code/config.scm b/code/liii/pi/code/config.scm index e7269701..0f7ee8a2 100644 --- a/code/liii/pi/code/config.scm +++ b/code/liii/pi/code/config.scm @@ -19,6 +19,7 @@ (liii pi code cli args) (liii pi code core tools) (liii pi ai auth) + (liii pi ai auth oauth resolve) (liii pi ai models) (liii pi ai thinking) (liii pi ai providers registry) @@ -331,40 +332,91 @@ ) ;if ) ;headers ) ; - (pi-cfg-set (make-pi-config - :agent-dir agent-dir - :config-dir config-dir - :provider provider - :provider-api - ;; 模型文件里可声明 api(如 deepseek 走 openai-completions); - ;; 未声明时回退 provider 级配置。provider 文件的 baseUrl 与 - ;; models//.json 的 baseUrl 由 user-models.scm 的 - ;; %compose-model 按字段合并,模型文件优先。 - (%resolve-provider-api models-store provider model-id) - :api-key api-key - :model-id model-id - :model-meta meta - :models-store models-store - :thinking-level thinking-level - :thinking-level-explicit? cli-thinking-explicit? - :thinking-level-source - (if cli-thinking-explicit? 'cli 'default) - :supports-thinking supports-thinking - :cli-proxy cli-proxy - :proxy-url proxy-url - :tools tools - :tool-resolver get-tool-definition - :execute-tool-call execute-tool-call - :emit-extension-event (%make-extension-emitter) - :settings settings - ) ;make-pi-config - 'headers - headers - ) ;pi-cfg-set + (let ((base-cfg (pi-cfg-set (make-pi-config + :agent-dir agent-dir + :config-dir config-dir + :provider provider + :provider-api + ;; 模型文件里可声明 api(如 deepseek 走 openai-completions); + ;; 未声明时回退 provider 级配置。provider 文件的 baseUrl 与 + ;; models//.json 的 baseUrl 由 user-models.scm 的 + ;; %compose-model 按字段合并,模型文件优先。 + (%resolve-provider-api models-store provider model-id) + :api-key api-key + :model-id model-id + :model-meta meta + :models-store models-store + :thinking-level thinking-level + :thinking-level-explicit? + cli-thinking-explicit? + :thinking-level-source + (if cli-thinking-explicit? 'cli 'default) + :supports-thinking supports-thinking + :cli-proxy cli-proxy + :proxy-url proxy-url + :tools tools + :tool-resolver get-tool-definition + :execute-tool-call execute-tool-call + :emit-extension-event + (%make-extension-emitter) + :settings settings + ) ;make-pi-config + 'headers + headers + ) ;pi-cfg-set + ) ;base-cfg + ) ; + ;; 1404:若 provider 在 auth.json 有 oauth 凭据,注入 refresh-oauth-key + ;; 钩子,供请求层收到 401 后强制刷新重试一次。无 oauth 凭据不注入 + ;; (非 oauth provider 的 401 按现状失败)。钩子返回新 access / 'unauthorized / #f。 + (if (pi-has-oauth-credential? provider auth) + (let ((captured-env (if (pair? opt-env) (car opt-env) '())) + (captured-dir config-dir-str) + ) ; + (pi-cfg-set base-cfg + 'refresh-oauth-key + (%make-refresh-oauth-hook captured-env captured-dir) + ) ;pi-cfg-set + ) ;let + base-cfg + ) ;if + ) ;let ) ;let* ) ;let-values ) ;let* ) ;define + + ;; 1404:构造 401 后强制刷新 oauth 凭据的闭包钩子。落盘/清除回调 + ;; 注入 auth.json 目录(captured-dir),env 表 captured-env 透传。 + (define (%make-refresh-oauth-hook captured-env captured-dir) + (lambda (cfg current-key) + (let* ((p (pi-cfg-ref cfg 'provider #f)) + (creds (if (pair? captured-env) + (pi-load-auth captured-dir captured-env) + (pi-load-auth captured-dir) + ) ;if + ) ;creds + (cred (pi-find-oauth-credential p creds)) + ) ; + (if cred + (pi-force-refresh-oauth-credential-key cred + (if (pair? captured-env) captured-env '()) + (lambda (c) + (pi-save-auth-oauth! (pi-credential-provider c) + (pi-credential-access c) + (pi-credential-refresh c) + (pi-credential-expires c) + (pi-credential-region c) + captured-dir + ) ;pi-save-auth-oauth! + ) ;lambda + (lambda (pp) (pi-remove-auth-provider! pp captured-dir)) + ) ;pi-force-refresh-oauth-credential-key + #f + ) ;if + ) ;let* + ) ;lambda + ) ;define (define resolve-goldpi-config resolve-pi-config) ;; 应用扩展注册的 config augmenter:内置/用户扩展经此 From 9259738ad1cb19581813bb4a80dd2a001eb30ea2 Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 18:45:21 +0800 Subject: [PATCH 3/9] =?UTF-8?q?[1404]=20=E4=BF=AE=E5=A4=8D=20CI=20?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E6=A3=80=E6=9F=A5=EF=BC=88gf=20fix=20+=20gf?= =?UTF-8?q?=20fmt=20=E4=BF=AE=E6=AD=A3=E6=97=A2=E6=9C=89=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=8E=92=E7=89=88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 的 Format Check 对整个 ai 目录跑 gf fmt --check,发现 12 个文件 需格式化(含本任务新增的 pi-refresh-oauth-key-bang-test 与既有 1402 wip 遗留的 storage/credential 等文件)。统一 gf fix + gf fmt 修正。 --- .../pi/ai/api/openai-completions/request.scm | 33 ++++++++++--------- ai/liii/pi/ai/auth/oauth/resolve.scm | 18 +++++----- ai/liii/pi/ai/auth/storage.scm | 13 ++++---- ai/liii/pi/ai/config/credential.scm | 18 ++++++---- .../pi-has-oauth-credential-p-test.scm | 8 ++--- .../credential/pi-credential-access-test.scm | 8 +++-- .../credential/pi-credential-expires-test.scm | 2 +- .../credential/pi-credential-oauth-p-test.scm | 8 ++--- .../credential/pi-credential-refresh-test.scm | 8 +++-- .../credential/pi-credential-region-test.scm | 7 ++-- .../credential/pi-credential-to-json-test.scm | 5 ++- .../pi-refresh-oauth-key-bang-test.scm | 5 +-- .../registry/pi-provider-oauth-test.scm | 2 +- 13 files changed, 76 insertions(+), 59 deletions(-) diff --git a/ai/liii/pi/ai/api/openai-completions/request.scm b/ai/liii/pi/ai/api/openai-completions/request.scm index cedc83c9..5d7ac21c 100644 --- a/ai/liii/pi/ai/api/openai-completions/request.scm +++ b/ai/liii/pi/ai/api/openai-completions/request.scm @@ -44,25 +44,31 @@ (define (%token-tail s) (if (and (string? s) (> (string-length s) 0)) (let ((n (string-length s))) - (substring s (max 0 (- n 4)) n)) - "") + (substring s (max 0 (- n 4)) n) + ) ;let + "" + ) ;if ) ;define ;; 1404:oauth 401 强制刷新结果描述(用于日志),不暴露完整 token (define (%oauth-refresh-result-desc next) - (cond ((string? next) - (string-append "ok new-token=..." (%token-tail next))) + (cond ((string? next) (string-append "ok new-token=..." (%token-tail next))) ((eq? next 'unauthorized) "unauthorized") - (else "none")) + (else "none") + ) ;cond ) ;define ;; 1404:写一行 [oauth-401] 日志到 ~/.gf/agent/logs/pi-YYYY-MM-DD.log (define (%log-oauth-401 provider attempt api-key next) - (pi-log-error! - (string-append "[oauth-401] provider=" (or provider "") - " attempt=" (number->string attempt) - " old-token=..." (%token-tail api-key) - " refresh=" (%oauth-refresh-result-desc next)) + (pi-log-error! (string-append "[oauth-401] provider=" + (or provider "") + " attempt=" + (number->string attempt) + " old-token=..." + (%token-tail api-key) + " refresh=" + (%oauth-refresh-result-desc next) + ) ;string-append ) ;pi-log-error! ) ;define @@ -314,8 +320,7 @@ (session-id (pi-cfg-ref config 'session-id)) ) ; (let loop - ((attempt 1) (api-key (pi-request-api-key config)) - (refreshed-once? #f)) + ((attempt 1) (api-key (pi-request-api-key config)) (refreshed-once? #f)) (let* ((extra-hdrs (%openai-extra-headers url provider session-id config settings)) (headers (openai-build-headers api-key extra-hdrs)) (resp (%post-openai url req-json-str headers proxy-alist timeout)) @@ -376,9 +381,7 @@ ;; 服务端可能在本地 expires 之前判 access token 失效返回 401, ;; 此时请求层回退强制 refresh 换取新 token 重试;refresh 失败 ;; (401/403/invalid_grant)凭据已清除,走 401 报错提示重 /login。 - ((and (= status 401) - (pi-oauth-refresh-enabled? config) - (not refreshed-once?)) + ((and (= status 401) (pi-oauth-refresh-enabled? config) (not refreshed-once?)) (let ((next (pi-refresh-oauth-key! config api-key))) (%log-oauth-401 provider attempt api-key next) (if (string? next) diff --git a/ai/liii/pi/ai/auth/oauth/resolve.scm b/ai/liii/pi/ai/auth/oauth/resolve.scm index f657f148..e1c852ef 100644 --- a/ai/liii/pi/ai/auth/oauth/resolve.scm +++ b/ai/liii/pi/ai/auth/oauth/resolve.scm @@ -14,11 +14,13 @@ (liii pi ai auth oauth kimi-coding-oauth) (liii pi ai time) ) ;import - (export pi-find-oauth-credential pi-resolve-oauth-credential-key + (export pi-find-oauth-credential + pi-resolve-oauth-credential-key ;; go worker 会话重求值调用链上的助手须导出 %pi-refresh-oauth-credential! ;; 1404:请求层收到 401 后的强制刷新(不查 expires)与凭据探测 - pi-force-refresh-oauth-credential-key pi-has-oauth-credential? + pi-force-refresh-oauth-credential-key + pi-has-oauth-credential? ) ;export (begin @@ -30,9 +32,7 @@ (if (null? xs) #f (let ((item (car xs))) - (if (and (pi-credential-oauth? item) - (equal? (pi-credential-provider item) target) - ) ;and + (if (and (pi-credential-oauth? item) (equal? (pi-credential-provider item) target)) item (loop (cdr xs)) ) ;if @@ -59,8 +59,10 @@ (refreshed (catch #t (lambda () - (kimi-refresh-token host (pi-credential-refresh cred) - provider (pi-credential-region cred) + (kimi-refresh-token host + (pi-credential-refresh cred) + provider + (pi-credential-region cred) ) ;kimi-refresh-token ) ;lambda (lambda (tag . info) (cons tag info)) @@ -107,4 +109,4 @@ ) ;define ) ;begin -) ;define-library \ No newline at end of file +) ;define-library diff --git a/ai/liii/pi/ai/auth/storage.scm b/ai/liii/pi/ai/auth/storage.scm index c91be685..cc9b0049 100644 --- a/ai/liii/pi/ai/auth/storage.scm +++ b/ai/liii/pi/ai/auth/storage.scm @@ -92,12 +92,11 @@ ) ;define (define (pi-auth-normalize-provider who provider) - (cond - ((string? provider) (%normalize-non-empty who "provider" provider)) - ((symbol? provider) - (%normalize-non-empty who "provider" (symbol->string provider)) - ) ; - (else (type-error (string-append who ": provider must be a string or symbol"))) + (cond ((string? provider) (%normalize-non-empty who "provider" provider)) + ((symbol? provider) + (%normalize-non-empty who "provider" (symbol->string provider)) + ) ; + (else (type-error (string-append who ": provider must be a string or symbol"))) ) ;cond ) ;define @@ -106,4 +105,4 @@ ) ;define ) ;begin -) ;define-library \ No newline at end of file +) ;define-library diff --git a/ai/liii/pi/ai/config/credential.scm b/ai/liii/pi/ai/config/credential.scm index fbc63b18..d1e21135 100644 --- a/ai/liii/pi/ai/config/credential.scm +++ b/ai/liii/pi/ai/config/credential.scm @@ -7,9 +7,9 @@ (define-library (liii pi ai config credential) (import (scheme base) (liii base) (liii error)) (export pi-credential pi-credential? pi-credential-provider pi-credential-key - pi-credential-type pi-credential->json - pi-credential-access pi-credential-refresh pi-credential-expires - pi-credential-region pi-credential-oauth? + pi-credential-type pi-credential->json pi-credential-access + pi-credential-refresh pi-credential-expires pi-credential-region + pi-credential-oauth? ) ;export (begin @@ -18,8 +18,14 @@ ;; region 记录登录时的 OAuth host 覆盖值,默认 host 不写 region, ;; 对应上游 pi 的 ApiKeyCredential / OAuthCredential,1402 §5.1) (define*-record-type - (pi-credential provider key (type "api_key") - (access #f) (refresh #f) (expires #f) (region #f)) + (pi-credential provider + key + (type "api_key") + (access #f) + (refresh #f) + (expires #f) + (region #f) + ) ;pi-credential pi-credential? (provider pi-credential-provider) (key pi-credential-key) @@ -60,4 +66,4 @@ ) ;define ) ;begin -) ;define-library \ No newline at end of file +) ;define-library diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm index 8ba15fd2..b297304c 100644 --- a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-has-oauth-credential-p-test.scm @@ -35,12 +35,8 @@ (define *other* (pi-credential "deepseek" "sk-ds" "api_key")) (check-true (pi-has-oauth-credential? "kimi-coding" (list *other* *oauth*))) -(check-true - (not (pi-has-oauth-credential? "kimi-coding" (list *api-key*))) -) ;check-true -(check-true - (not (pi-has-oauth-credential? "deepseek" (list *other* *oauth*))) -) ;check-true +(check-true (not (pi-has-oauth-credential? "kimi-coding" (list *api-key*)))) +(check-true (not (pi-has-oauth-credential? "deepseek" (list *other* *oauth*)))) (check-true (not (pi-has-oauth-credential? "kimi-coding" '()))) (check-true (not (pi-has-oauth-credential? #f (list *oauth*)))) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm index c91761f2..7c607840 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-access-test.scm @@ -19,7 +19,11 @@ (check-set-mode! 'report-failed) -(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-token" "ref-token" 1893456000000 #f))) +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-token" "ref-token" + 1893456000000 #f + ) ;pi-credential + ) ;c + ) ; (check (pi-credential-access c) => "acc-token") ) ;let @@ -27,4 +31,4 @@ (check (pi-credential-access c) => #f) ) ;let -(check-report) \ No newline at end of file +(check-report) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm index 16f5fd3a..60474642 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-expires-test.scm @@ -27,4 +27,4 @@ (check (pi-credential-expires c) => #f) ) ;let -(check-report) \ No newline at end of file +(check-report) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm index 294e8eb9..7a019252 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-oauth-p-test.scm @@ -19,12 +19,12 @@ (check-set-mode! 'report-failed) -(check-true - (pi-credential-oauth? - (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f))) +(check-true (pi-credential-oauth? (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 #f) + ) ;pi-credential-oauth? +) ;check-true (check-false (pi-credential-oauth? (pi-credential "google" "k" "api_key"))) (check-false (pi-credential-oauth? (pi-credential "google" "k"))) (check-false (pi-credential-oauth? "oauth")) (check-false (pi-credential-oauth? #f)) -(check-report) \ No newline at end of file +(check-report) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm index eb2dd1af..85fbe54c 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-refresh-test.scm @@ -19,7 +19,11 @@ (check-set-mode! 'report-failed) -(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-token" "ref-token" 1893456000000 #f))) +(let ((c (pi-credential "kimi-coding" #f "oauth" "acc-token" "ref-token" + 1893456000000 #f + ) ;pi-credential + ) ;c + ) ; (check (pi-credential-refresh c) => "ref-token") ) ;let @@ -27,4 +31,4 @@ (check (pi-credential-refresh c) => #f) ) ;let -(check-report) \ No newline at end of file +(check-report) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm index 477cbef5..55a7e59e 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-region-test.scm @@ -20,7 +20,10 @@ (check-set-mode! 'report-failed) (let ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 - "https://auth.kimi.ai"))) + "https://auth.kimi.ai" + ) ;pi-credential + ) ;c + ) ; (check (pi-credential-region c) => "https://auth.kimi.ai") ) ;let @@ -28,4 +31,4 @@ (check (pi-credential-region c) => #f) ) ;let -(check-report) \ No newline at end of file +(check-report) diff --git a/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm b/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm index 6686ba6f..7d7d0268 100644 --- a/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm +++ b/ai/tests/liii/pi/ai/config/credential/pi-credential-to-json-test.scm @@ -47,7 +47,10 @@ ) ;let* ;; oauth + region:region 落盘 -(let* ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 "https://auth.kimi.ai")) +(let* ((c (pi-credential "kimi-coding" #f "oauth" "acc" "ref" 1893456000000 + "https://auth.kimi.ai" + ) ;pi-credential + ) ;c (parsed (string->json (json->string (pi-credential->json c)))) ) ; (check (cdr (assoc "region" parsed)) => "https://auth.kimi.ai") diff --git a/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm b/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm index f4a308ed..56a9d012 100644 --- a/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm +++ b/ai/tests/liii/pi/ai/keyring/pi-refresh-oauth-key-bang-test.scm @@ -31,10 +31,7 @@ (let ((cfg (list (cons 'api-key "old-acc") (cons 'refresh-oauth-key - (lambda (config current-key) - (set! seen (list current-key)) - "new-acc" - ) ;lambda + (lambda (config current-key) (set! seen (list current-key)) "new-acc") ) ;cons ) ;list ) ;cfg diff --git a/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm b/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm index 757a3cf7..965d5973 100644 --- a/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm +++ b/ai/tests/liii/pi/ai/providers/registry/pi-provider-oauth-test.scm @@ -25,4 +25,4 @@ (check (pi-provider-oauth "google") => #f) (check (pi-provider-oauth "no-such-provider") => #f) -(check-report) \ No newline at end of file +(check-report) From 218cbd4caa0db689b9f171fbcf82e614a0693b0d Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 18:46:44 +0800 Subject: [PATCH 4/9] =?UTF-8?q?[1404]=20=E4=BF=AE=E5=A4=8D=20tui=20?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=20CI=20=E6=A0=BC=E5=BC=8F=E6=A3=80=E6=9F=A5?= =?UTF-8?q?=EF=BC=88gf=20fix=20+=20gf=20fmt=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tui 目录 4 个 1402 wip 遗留文件需格式化:app-login/login-device-code/ worker 及其测试。统一 gf fix + gf fmt 修正。 --- tui/liii/pi/tui/interactive/app-login.scm | 3 +- .../pi/tui/interactive/login-device-code.scm | 32 +++++++++------ tui/liii/pi/tui/interactive/worker.scm | 4 +- .../pi-app-show-login-oauth-bang-test.scm | 41 ++++++++++++++++--- 4 files changed, 57 insertions(+), 23 deletions(-) diff --git a/tui/liii/pi/tui/interactive/app-login.scm b/tui/liii/pi/tui/interactive/app-login.scm index f9c972e5..8929f8dc 100644 --- a/tui/liii/pi/tui/interactive/app-login.scm +++ b/tui/liii/pi/tui/interactive/app-login.scm @@ -184,8 +184,7 @@ ) ;define (let ((result (catch #t - (lambda () - (kimi-oauth-login notify! cancelled? provider)) + (lambda () (kimi-oauth-login notify! cancelled? provider)) (lambda (tag . info) (list 'error tag diff --git a/tui/liii/pi/tui/interactive/login-device-code.scm b/tui/liii/pi/tui/interactive/login-device-code.scm index da571002..bcbbc940 100644 --- a/tui/liii/pi/tui/interactive/login-device-code.scm +++ b/tui/liii/pi/tui/interactive/login-device-code.scm @@ -40,7 +40,9 @@ (user-code login-device-code-state-user-code) (verification-uri login-device-code-state-verification-uri) (on-cancel login-device-code-state-on-cancel) - (cancelled? login-device-code-state-cancelled? login-device-code-state-cancelled?-set!) + (cancelled? login-device-code-state-cancelled? + login-device-code-state-cancelled?-set! + ) ;cancelled? (browser-opened? login-device-code-state-browser-opened? login-device-code-state-browser-opened?-set! ) ;browser-opened? @@ -78,9 +80,7 @@ (let ((state (%state comp))) (login-device-code-state-browser-opened?-set! state #t) (catch #t - (lambda () - (web-browser-open (login-device-code-state-verification-uri state)) - ) ;lambda + (lambda () (web-browser-open (login-device-code-state-verification-uri state))) (lambda args #f) ) ;catch ) ;let @@ -100,17 +100,25 @@ ) ;code-line (uri (login-device-code-state-verification-uri state)) (waiting (%colored %muted " Waiting for authorization in browser…")) - (opened-hint - (if (login-device-code-state-browser-opened? state) - (%colored %muted " Browser opened. Complete authorization there.") - (%colored %muted " Browser not opened? Visit the URL above manually.") - ) ;if + (opened-hint (if (login-device-code-state-browser-opened? state) + (%colored %muted " Browser opened. Complete authorization there.") + (%colored %muted " Browser not opened? Visit the URL above manually.") + ) ;if ) ;opened-hint (hint (%colored %muted " enter to open browser · esc to cancel")) ) ; - (list border "" title "" code-line "" + (list border + "" + title + "" + code-line + "" (string-append " " (%colored %accent uri)) - "" waiting opened-hint "" hint + "" + waiting + opened-hint + "" + hint ) ;list ) ;let* ) ;define @@ -142,4 +150,4 @@ ) ;define ) ;begin -) ;define-library \ No newline at end of file +) ;define-library diff --git a/tui/liii/pi/tui/interactive/worker.scm b/tui/liii/pi/tui/interactive/worker.scm index 1ffa643f..099cb25b 100644 --- a/tui/liii/pi/tui/interactive/worker.scm +++ b/tui/liii/pi/tui/interactive/worker.scm @@ -216,9 +216,7 @@ ) ;dir (dir-str (if (string? dir) dir (path->string dir))) (cur-p (pi-cfg-ref cfg 'provider)) - (new-key (and cur-p - (pi-resolve-provider-key cur-p (pi-load-auth dir-str) '() dir-str) - ) ;and + (new-key (and cur-p (pi-resolve-provider-key cur-p (pi-load-auth dir-str) '() dir-str)) ) ;new-key ) ; (%cfg-override cfg diff --git a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm index dd5ec405..f9341bec 100644 --- a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm +++ b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm @@ -86,9 +86,16 @@ (putenv "KIMI_CODE_OAUTH_HOST" host) (pi-app-show-login-oauth! app "kimi-coding" tmp) (sleep 1.5) - (let drain () + (let drain + () (let ((ev (chan-try-recv! (pi-app-event-chan app) #f))) - (when ev (display (list "RAWEV" ev)) (newline) (drain)))) + (when ev + (display (list "RAWEV" ev)) + (newline) + (drain) + ) ;when + ) ;let + ) ;let ;; drain 后 selector 仍是占位(device_code 已被消费掉) ;; 占位组件已挂载 (check-true (component? (pi-app-active-selector app))) @@ -103,11 +110,30 @@ ) ;when ) ;let (begin - (display (list "SELCODE" (login-device-code-user-code (pi-app-active-selector app)))) (newline) + (display (list "SELCODE" (login-device-code-user-code (pi-app-active-selector app))) + ) ;display + (newline) (let ((ls (chat-lines app))) - (for-each (lambda (l) (when (string-contains? l "HOST=") (display (list "LINE" l)) (newline))) ls))) + (for-each + (lambda (l) + (when (string-contains? l "HOST=") + (display (list "LINE" l)) + (newline) + ) ;when + ) ;lambda + ls + ) ;for-each + ) ;let + ) ;begin (check-true (login-device-code? (pi-app-active-selector app))) - (display (list "DBG" port host (getenv "KIMI_CODE_OAUTH_HOST") (login-device-code-user-code (pi-app-active-selector app)))) (newline) + (display (list "DBG" + port + host + (getenv "KIMI_CODE_OAUTH_HOST") + (login-device-code-user-code (pi-app-active-selector app)) + ) ;list + ) ;display + (newline) (check (login-device-code-user-code (pi-app-active-selector app)) => "ABCD-1234" @@ -122,7 +148,10 @@ ) ;when ) ;let (when (pi-app-active-selector app) - (display (list "ENDSEL" (login-device-code-user-code (pi-app-active-selector app)))) (newline)) + (display (list "ENDSEL" (login-device-code-user-code (pi-app-active-selector app))) + ) ;display + (newline) + ) ;when (check-false (pi-app-active-selector app)) (check-true (any (lambda (l) (string-contains? l "Saved OAuth credential for kimi-coding")) (chat-lines app) From 06974df0702a9b30e67330d206177239949059d5 Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 19:22:34 +0800 Subject: [PATCH 5/9] =?UTF-8?q?[1404]=20=E4=BF=AE=E5=A4=8D=20gf=20check=20?= =?UTF-8?q?=E6=97=A2=E6=9C=89=E8=BF=9D=E8=A7=84=EF=BC=9Adevice-flow=20?= =?UTF-8?q?=E5=B5=8C=E5=A5=97=E3=80=81worker=20=E8=A1=8C=E6=95=B0=E3=80=81?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1=20README/=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 的 gf check 对整个仓库跑,发现 1402 wip 遗留的违规(本分支带入): - device-flow.scm: 提取 %resolve-interval-ms 与 %apply-slow-down 降嵌套 17→合规 - worker.scm: 压缩版权注释行数 451→450 - 补 4 个缺失 README(device-flow/kimi-coding-oauth/storage/login-device-code) - 补 pi-auth-args-oauth? 与 pi-auth-login-oauth 单测(满足 unit-test 规则) --- ai/liii/pi/ai/auth/oauth/device-flow.scm | 70 +++++---- .../pi/ai/auth/oauth/device-flow/README.md | 27 ++++ .../ai/auth/oauth/kimi-coding-oauth/README.md | 40 ++++++ ai/tests/liii/pi/ai/auth/storage/README.md | 31 ++++ tui/liii/pi/tui/interactive/worker.scm | 1 - .../cli/auth/pi-auth-args-oauth-p-test.scm | 36 +++++ .../tui/cli/auth/pi-auth-login-oauth-test.scm | 136 ++++++++++++++++++ .../interactive/login-device-code/README.md | 30 ++++ 8 files changed, 341 insertions(+), 30 deletions(-) create mode 100644 ai/tests/liii/pi/ai/auth/oauth/device-flow/README.md create mode 100644 ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/README.md create mode 100644 ai/tests/liii/pi/ai/auth/storage/README.md create mode 100644 tui/tests/liii/pi/tui/cli/auth/pi-auth-args-oauth-p-test.scm create mode 100644 tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm create mode 100644 tui/tests/liii/pi/tui/interactive/login-device-code/README.md diff --git a/ai/liii/pi/ai/auth/oauth/device-flow.scm b/ai/liii/pi/ai/auth/oauth/device-flow.scm index 638cbefd..30234856 100644 --- a/ai/liii/pi/ai/auth/oauth/device-flow.scm +++ b/ai/liii/pi/ai/auth/oauth/device-flow.scm @@ -31,6 +31,40 @@ ;; 分片睡眠粒度:每片醒来检查 cancelled?,取消响应 ≤ 0.1s (define %sleep-slice-seconds 0.1) + ;; 计算 polling interval(毫秒),RFC 8628:无效 interval-seconds 回退 5s + (define (%resolve-interval-ms interval-seconds) + (max %minimum-interval-ms + (inexact->exact + (floor + (* (if (and (number? interval-seconds) (> interval-seconds 0)) + interval-seconds + %default-poll-interval-seconds + ) ;if + 1000 + ) ;* + ) ;floor + ) ;inexact->exact + ) ;max + ) ;define + + ;; 处理 slow_down 结果:返回 (new-interval-ms . new-count)。 + ;; 服务端给了新 interval 就采信(对齐 pi:WSL/VM 时钟漂移下只靠客户端累加 + ;; 会永远提前轮询);否则按 RFC 8628 +5s。非 slow_down 原样返回。 + (define (%apply-slow-down result interval-ms slow-down-count) + (if (eq? (and (pair? result) (car result)) 'slow_down) + (let ((server-interval (and (pair? (cdr result)) (cadr result)))) + (cons + (if (and (number? server-interval) (> server-interval 0)) + (max %minimum-interval-ms (inexact->exact (floor (* server-interval 1000)))) + (max %minimum-interval-ms (+ interval-ms %slow-down-increment-ms)) + ) ;if + (+ slow-down-count 1) + ) ;cons + ) ;let + (cons interval-ms slow-down-count) + ) ;if + ) ;define + ;; 可取消睡眠:分片 sleep,任一片间发现 cancelled? 即抛取消错误 (define (%abortable-sleep seconds cancelled?) (let loop @@ -65,20 +99,7 @@ (let* ((start-ms (pi-current-monotonic-millis)) (deadline-ms (and (number? expires-in-seconds) (+ start-ms (* expires-in-seconds 1000))) ) ;deadline-ms - (interval-ms - (max %minimum-interval-ms - (inexact->exact - (floor - (* (if (and (number? interval-seconds) (> interval-seconds 0)) - interval-seconds - %default-poll-interval-seconds - ) ;if - 1000 - ) ;* - ) ;floor - ) ;inexact->exact - ) ;max - ) ;interval-ms + (interval-ms (%resolve-interval-ms interval-seconds)) (slow-down-count 0) ) ; (define (remaining-ms) @@ -118,21 +139,12 @@ ) ;error ) ; (else - (when (eq? (and (pair? result) (car result)) 'slow_down) - (set! slow-down-count (+ slow-down-count 1)) - ;; 服务端给了新 interval 就采信(对齐 pi:WSL/VM 时钟漂移 - ;; 下只靠客户端累加会永远提前轮询);否则按 RFC 8628 +5s - (let ((server-interval (and (pair? (cdr result)) (cadr result)))) - (set! interval-ms - (if (and (number? server-interval) (> server-interval 0)) - (max %minimum-interval-ms (inexact->exact (floor (* server-interval 1000)))) - (max %minimum-interval-ms (+ interval-ms %slow-down-increment-ms)) - ) ;if - ) ;set! - ) ;let - ) ;when - (sleep-interval!) - (loop) + (let ((next (%apply-slow-down result interval-ms slow-down-count))) + (set! interval-ms (car next)) + (set! slow-down-count (cdr next)) + (sleep-interval!) + (loop) + ) ;let ) ;else ) ;case ) ;let diff --git a/ai/tests/liii/pi/ai/auth/oauth/device-flow/README.md b/ai/tests/liii/pi/ai/auth/oauth/device-flow/README.md new file mode 100644 index 00000000..389fc155 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/device-flow/README.md @@ -0,0 +1,27 @@ +# (liii pi ai auth oauth device-flow) 模块函数索引 + +`(liii pi ai auth oauth device-flow)` 提供 RFC 8628 设备码通用轮询循环,翻译自上游 pi 的 `pollOAuthDeviceCodeFlow`。 + +使用时导入: + +```scheme +(import (liii pi ai auth oauth device-flow)) +``` + +## 查看函数文档 + +使用以下命令查看函数文档和测试用例: + +```bash +gf doc pi-device-flow-poll +``` + +## 函数分类索引 + +### 轮询 +- `pi-device-flow-poll` - 设备码轮询循环,返回 complete 的 value,失败/取消/超时抛错 + +### 常量 +- `PI_DEVICE_FLOW_CANCEL_MESSAGE` - 取消消息 +- `PI_DEVICE_FLOW_TIMEOUT_MESSAGE` - 超时消息 +- `PI_DEVICE_FLOW_SLOW_DOWN_TIMEOUT_MESSAGE` - slow_down 超时消息 diff --git a/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/README.md b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/README.md new file mode 100644 index 00000000..f1326fd1 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/oauth/kimi-coding-oauth/README.md @@ -0,0 +1,40 @@ +# (liii pi ai auth oauth kimi-coding-oauth) 模块函数索引 + +`(liii pi ai auth oauth kimi-coding-oauth)` 实现 Kimi Code OAuth2 设备码登录(设备授权、轮询换 token、刷新),翻译自上游 pi 的 `kimi-coding.ts`。 + +使用时导入: + +```scheme +(import (liii pi ai auth oauth kimi-coding-oauth)) +``` + +## 查看函数文档 + +使用以下命令查看函数文档和测试用例: + +```bash +gf doc kimi-oauth-login +``` + +## 函数分类索引 + +### 设备授权 +- `kimi-device-authorize` - 发起设备授权请求 +- `kimi-device-authorization-p` - 设备授权记录谓词 +- `kimi-device-authorization-device-code` - 取 device_code +- `kimi-device-authorization-user-code` - 取 user_code +- `kimi-device-authorization-verification-uri` - 取验证 URL +- `kimi-device-authorization-verification-uri-complete` - 取含 user_code 的验证 URL +- `kimi-device-authorization-interval-seconds` - 取轮询间隔 +- `kimi-device-authorization-expires-in-seconds` - 取过期秒数 + +### 轮询与刷新 +- `kimi-poll-token` - 轮询 token 端点直到完成 +- `kimi-refresh-token` - 用 refresh_token 刷新 access token +- `kimi-oauth-login` - 完整登录:设备授权 → notify → 轮询换 token +- `kimi-oauth->auth` - 凭据 → 请求头 + +### Host 与常量 +- `kimi-oauth-host` - 解析 OAuth host(env 覆盖 > 默认国内 host) +- `KIMI_OAUTH_CLIENT_ID` - Kimi Code OAuth client id +- `KIMI_OAUTH_DEFAULT_HOST` - 默认国内 OAuth host diff --git a/ai/tests/liii/pi/ai/auth/storage/README.md b/ai/tests/liii/pi/ai/auth/storage/README.md new file mode 100644 index 00000000..a4619f92 --- /dev/null +++ b/ai/tests/liii/pi/ai/auth/storage/README.md @@ -0,0 +1,31 @@ +# (liii pi ai auth storage) 模块函数索引 + +`(liii pi ai auth storage)` 提供 auth.json 的读取与原子写原语(tmp 文件 + rename + chmod 0600),供 api_key 与 oauth 两条持久化路径共用。 + +使用时导入: + +```scheme +(import (liii pi ai auth storage)) +``` + +## 查看函数文档 + +使用以下命令查看函数文档和测试用例: + +```bash +gf doc pi-auth-write-json! +``` + +## 函数分类索引 + +### 读取与路径 +- `pi-auth-read-json` - 读取 auth.json 并解析为关联表 +- `pi-auth-dir-path` - 解析配置目录(显式传入优先,缺省 ~/.gf/agent) + +### 写入与替换 +- `pi-auth-replace-entry` - 替换或追加某 provider 的 auth.json 条目 +- `pi-auth-write-json!` - 原子写 auth.json(tmp + rename + chmod 0600) + +### 规范化 +- `pi-auth-normalize-provider` - 规范化 provider id(非空字符串) +- `pi-auth-normalize-secret` - 规范化 secret(非空 trim 后字符串) diff --git a/tui/liii/pi/tui/interactive/worker.scm b/tui/liii/pi/tui/interactive/worker.scm index 099cb25b..c5b99e8f 100644 --- a/tui/liii/pi/tui/interactive/worker.scm +++ b/tui/liii/pi/tui/interactive/worker.scm @@ -2,7 +2,6 @@ ;; Copyright (C) 2026 The Goldfish Scheme Authors ;; ;; Licensed under the MIT License -;; (define-library (liii pi tui interactive worker) ;; worker 线程通过重新 import 库并求值 procedure-source 执行,调用链内部函数须全部导出 diff --git a/tui/tests/liii/pi/tui/cli/auth/pi-auth-args-oauth-p-test.scm b/tui/tests/liii/pi/tui/cli/auth/pi-auth-args-oauth-p-test.scm new file mode 100644 index 00000000..e2a4c364 --- /dev/null +++ b/tui/tests/liii/pi/tui/cli/auth/pi-auth-args-oauth-p-test.scm @@ -0,0 +1,36 @@ +;; pi-auth-args-oauth? +;; 读取 记录的 oauth? 字段,判断是否走 OAuth 登录路径。 +;; +;; 语法 +;; ---- +;; (pi-auth-args-oauth? args) -> boolean? +;; +;; 参数 +;; ---- +;; args : +;; auth 参数记录。 +;; +;; 返回值 +;; ------ +;; boolean? +;; 为 #t 时表示用户以 --oauth 登录该 provider,走设备码流程而非 api_key。 + +(import (liii check) (liii pi tui cli auth)) + +(check-set-mode! 'report-failed) + +(check-true (pi-auth-args-oauth? (make-pi-auth-args :subcommand "login" :provider "kimi-coding" :oauth? #t) + ) ;pi-auth-args-oauth? +) ;check-true + +(check-true (not (pi-auth-args-oauth? (make-pi-auth-args :subcommand "login" :provider "kimi-coding" :key "sk-123") + ) ;pi-auth-args-oauth? + ) ;not +) ;check-true + +(check-true (not (pi-auth-args-oauth? (make-pi-auth-args #f "login" "deepseek" "sk-123"))) +) ;check-true + +(check-true (not (pi-auth-args-oauth? (make-pi-auth-args :help? #t)))) + +(check-report) diff --git a/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm b/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm new file mode 100644 index 00000000..c0cb0ba9 --- /dev/null +++ b/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm @@ -0,0 +1,136 @@ +;; pi-auth-login-oauth +;; 非交互 device flow 登录:打印 verification URL 让用户手动打开, +;; 轮询成功后落盘 oauth 凭据(1402 §5.4 可选子项)。 +;; +;; 语法 +;; ---- +;; (pi-auth-login-oauth provider) +;; (pi-auth-login-oauth provider config-dir) +;; (pi-auth-login-oauth provider config-dir custom-env) +;; +;; 参数 +;; ---- +;; provider : string? +;; 凭据归属服务商。 +;; +;; config-dir : any? +;; 配置目录路径(默认 (gf-get-config-dir))。 +;; +;; custom-env : list? +;; 自定义环境变量表(KIMI_CODE_OAUTH_HOST 覆盖 host)。 +;; +;; 返回值 +;; ------ +;; integer? +;; 成功为 0,登录或落盘失败为 1。 + +(import (scheme base) + (liii check) + (liii string) + (liii path) + (liii tempfile) + (liii subprocess) + (liii pi tui cli auth) +) ;import + +(check-set-mode! 'report-failed) + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +(define stub-file + (cond ((file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + ) ; + ((file-exists? "ai/tests/stub_kimi_oauth_server.py") + "ai/tests/stub_kimi_oauth_server.py" + ) ; + ((file-exists? "../ai/tests/stub_kimi_oauth_server.py") + "../ai/tests/stub_kimi_oauth_server.py" + ) ; + ((file-exists? "../../ai/tests/stub_kimi_oauth_server.py") + "../../ai/tests/stub_kimi_oauth_server.py" + ) ; + (else "ai/tests/stub_kimi_oauth_server.py") + ) ;cond +) ;define + +;; 捕获 stderr 输出为字符串(验证失败路径的提示) + +(define (with-stderr-to-string thunk) + (let* ((p (open-output-string)) (orig *stderr*)) + (dynamic-wind (lambda () (set! *stderr* p)) + thunk + (lambda () (set! *stderr* orig)) + ) ;dynamic-wind + (get-output-string p) + ) ;let* +) ;define + +;; 1. stub ok:登录成功,落盘 auth.json 的 kimi-coding oauth 条目,返回 0 +(let* ((proc (process-spawn (list "python3" stub-file "ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (tmp (make-temp-dir "gf-auth-oauth-test-" "")) + (auth-file (path-join tmp "auth.json")) + ) ; + (let ((status #f)) + (let ((out + (with-output-to-string + (lambda () + (set! status + (pi-auth-login-oauth "kimi-coding" + tmp + (list (cons "KIMI_CODE_OAUTH_HOST" host)) + ) ;pi-auth-login-oauth + ) ;set! + ) ;lambda + ) ;with-output-to-string + ) ;out + ) ; + (check status => 0) + (check-true (string-contains? out "Open this URL to authorize:")) + ) ;let + ;; 验证 auth.json 已写入 oauth 条目 + (let ((content (path-read-text auth-file))) + (check-true (string-contains? content "\"kimi-coding\"")) + (check-true (string-contains? content "stub-access-token")) + ) ;let + ) ;let + (path-unlink auth-file #t) + (path-rmdir tmp #t) + (process-kill proc) +) ;let* + +;; 2. host 不可达:登录失败,返回 1,不落盘 +(let* ((tmp (make-temp-dir "gf-auth-oauth-test-" "")) + (auth-file (path-join tmp "auth.json")) + (status #f) + ) ; + (let ((err + (with-stderr-to-string + (lambda () + (set! status + (pi-auth-login-oauth "kimi-coding" + tmp + (list (cons "KIMI_CODE_OAUTH_HOST" "http://127.0.0.1:1")) + ) ;pi-auth-login-oauth + ) ;set! + ) ;lambda + ) ;with-stderr-to-string + ) ;err + ) ; + (check status => 1) + (check-true (string-contains? err "OAuth login failed")) + ) ;let + (unless (path-exists? auth-file) + #f + ) ;unless + (path-rmdir tmp #t) +) ;let* + +(check-report) diff --git a/tui/tests/liii/pi/tui/interactive/login-device-code/README.md b/tui/tests/liii/pi/tui/interactive/login-device-code/README.md new file mode 100644 index 00000000..d1f143b0 --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/login-device-code/README.md @@ -0,0 +1,30 @@ +# (liii pi tui interactive login-device-code) 模块函数索引 + +`(liii pi tui interactive login-device-code)` 提供 OAuth 设备码登录的 TUI 组件,展示 user code 与验证 URL 并打开浏览器。 + +使用时导入: + +```scheme +(import (liii pi tui interactive login-device-code)) +``` + +## 查看函数文档 + +使用以下命令查看函数文档和测试用例: + +```bash +gf doc make-login-device-code +``` + +## 函数分类索引 + +### 构造与字段 +- `make-login-device-code` - 构造设备码登录组件 +- `login-device-code-p` - 组件谓词 +- `login-device-code-user-code` - 取 user code +- `login-device-code-verification-uri` - 取验证 URL +- `login-device-code-cursor-position` - 取光标位置 +- `login-device-code-cancelled-p` - 是否已取消 + +### 行为 +- `login-device-code-open-browser!` - 打开验证 URL 的浏览器 From 11545a36e4818c8adcac403c4077dcd7a85ed003 Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 19:43:19 +0800 Subject: [PATCH 6/9] wip --- .../pi/ai/auth/oauth/kimi-coding-oauth.scm | 17 ++---- tui/liii/pi/tui/interactive/app-login.scm | 18 +++++-- .../pi-app-show-login-oauth-bang-test.scm | 54 +++---------------- 3 files changed, 26 insertions(+), 63 deletions(-) diff --git a/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm b/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm index b4acbe08..e2bcb62a 100644 --- a/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm +++ b/ai/liii/pi/ai/auth/oauth/kimi-coding-oauth.scm @@ -84,21 +84,12 @@ ) ;let* ) ;define - ;; opt-env 兼容两种形态:env-alist 本身,或 lookup-env-var 的 - ;; (env-alist) 包装形态(variadic rest 参直接传入时多一层) + ;; opt-env 是 variadic 参数列表;调用方给出 env-alist 时,保留完整 + ;; alist 并包成 lookup-env-var 需要的 (env-alist) 形态。 (define (%non-empty-env name opt-env) - (let* ((env - (if (and (pair? opt-env) (pair? (car opt-env)) (string? (caar opt-env))) - (car opt-env) - opt-env - ) ;if - ) ;env - (v - (lookup-env-var name (if (and (pair? env) (pair? (car env))) (list env) '())) - ) ;v - ) ; + (let ((v (lookup-env-var name (if (pair? opt-env) (list (car opt-env)) '())))) (and (string? v) (not (string-null? (string-trim-both v))) (string-trim-both v)) - ) ;let* + ) ;let ) ;define ;; 仅信任 http/https 绝对 URL(对应 pi trustedHttpUrl):登录流程会把 diff --git a/tui/liii/pi/tui/interactive/app-login.scm b/tui/liii/pi/tui/interactive/app-login.scm index 8929f8dc..70faeb95 100644 --- a/tui/liii/pi/tui/interactive/app-login.scm +++ b/tui/liii/pi/tui/interactive/app-login.scm @@ -129,6 +129,7 @@ (let ((cfg-dir (path->string (path (or opt-config-dir (gf-get-config-dir)))) ) ;cfg-dir + (oauth-host (kimi-oauth-host)) (cancel-chan (make-chan 1)) ) ; (editor-set-focused! (pi-app-editor app) #f) @@ -156,7 +157,12 @@ ) ;lambda ) ;make-component ) ;%pi-app-active-selector-set! - (go (%kimi-oauth-login-worker provider cfg-dir (pi-app-event-chan app) cancel-chan) + (go (%kimi-oauth-login-worker provider + cfg-dir + oauth-host + (pi-app-event-chan app) + cancel-chan + ) ;%kimi-oauth-login-worker ) ;go (pi-app-render! app) ) ;let @@ -164,7 +170,7 @@ ;; 后台 worker:设备授权 → device_code 事件 → 轮询 → done 事件。 ;; 取消探测:主线程 Esc 时向 cancel-chan 发信号(非阻塞探测) - (define (%kimi-oauth-login-worker provider cfg-dir event-chan cancel-chan) + (define (%kimi-oauth-login-worker provider cfg-dir oauth-host event-chan cancel-chan) (define (cancelled?) (let ((sig (catch #t (lambda () (chan-try-recv! cancel-chan #f)) (lambda args #f)))) (and sig (not (eof-object? sig)) #t) @@ -184,7 +190,13 @@ ) ;define (let ((result (catch #t - (lambda () (kimi-oauth-login notify! cancelled? provider)) + (lambda () + (kimi-oauth-login notify! + cancelled? + provider + (list (cons "KIMI_CODE_OAUTH_HOST" oauth-host)) + ) ;kimi-oauth-login + ) ;lambda (lambda (tag . info) (list 'error tag diff --git a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm index f9341bec..18c19a30 100644 --- a/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm +++ b/tui/tests/liii/pi/tui/interactive/app-login/pi-app-show-login-oauth-bang-test.scm @@ -85,19 +85,7 @@ (putenv "GF_CONFIG_DIR" tmp) (putenv "KIMI_CODE_OAUTH_HOST" host) (pi-app-show-login-oauth! app "kimi-coding" tmp) - (sleep 1.5) - (let drain - () - (let ((ev (chan-try-recv! (pi-app-event-chan app) #f))) - (when ev - (display (list "RAWEV" ev)) - (newline) - (drain) - ) ;when - ) ;let - ) ;let - ;; drain 后 selector 仍是占位(device_code 已被消费掉) - ;; 占位组件已挂载 + ;; 占位组件已挂载;事件必须交给 pi-app-poll-events!,不能直接取走。 (check-true (component? (pi-app-active-selector app))) ;; 轮询事件直至 device-code 组件出现(最多 ~10s) (let wait @@ -109,35 +97,12 @@ (wait (+ n 1)) ) ;when ) ;let - (begin - (display (list "SELCODE" (login-device-code-user-code (pi-app-active-selector app))) - ) ;display - (newline) - (let ((ls (chat-lines app))) - (for-each - (lambda (l) - (when (string-contains? l "HOST=") - (display (list "LINE" l)) - (newline) - ) ;when - ) ;lambda - ls - ) ;for-each - ) ;let - ) ;begin - (check-true (login-device-code? (pi-app-active-selector app))) - (display (list "DBG" - port - host - (getenv "KIMI_CODE_OAUTH_HOST") - (login-device-code-user-code (pi-app-active-selector app)) - ) ;list - ) ;display - (newline) - (check (login-device-code-user-code (pi-app-active-selector app)) - => - "ABCD-1234" - ) ;check + (let ((selector (pi-app-active-selector app))) + (check-true (login-device-code? selector)) + (when (login-device-code? selector) + (check (login-device-code-user-code selector) => "ABCD-1234") + ) ;when + ) ;let ;; 继续轮询直至登录完成(授权由 stub 自动完成) (let wait ((n 0)) @@ -147,11 +112,6 @@ (wait (+ n 1)) ) ;when ) ;let - (when (pi-app-active-selector app) - (display (list "ENDSEL" (login-device-code-user-code (pi-app-active-selector app))) - ) ;display - (newline) - ) ;when (check-false (pi-app-active-selector app)) (check-true (any (lambda (l) (string-contains? l "Saved OAuth credential for kimi-coding")) (chat-lines app) From ac5696bbbc23ce56206395c8e067ccde28edaba3 Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 20:28:15 +0800 Subject: [PATCH 7/9] =?UTF-8?q?[1404]=20=E4=BF=AE=E5=A4=8D=20oauth=20401?= =?UTF-8?q?=20=E5=88=B7=E6=96=B0=E5=90=8E=E6=96=B0=20token=20=E4=B8=8D?= =?UTF-8?q?=E8=90=BD=E7=9B=98=E4=B8=8E=E5=88=87=E6=A8=A1/reload=20?= =?UTF-8?q?=E4=B8=A2=E5=A4=B1=E5=88=B7=E6=96=B0=E9=92=A9=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因 1:go worker 经 procedure-source 重建 save! 闭包时, pi-credential-* 访问器不在会话活动库列表,save! 抛 unbound 被 %pi-refresh-oauth-credential! 静默吞掉——刷新成功但 auth.json 永远不落盘,每次启动仍用旧 token 反复 401。 - oauth-hook/worker 显式 import (liii pi ai config credential) - save! 失败写 [oauth-refresh] 日志,不再静默吞错(仍返回新 access) 根因 2:refresh-oauth-key 钩子仅启动时注入,同 provider 切模不走 augment、/login 后 reload 只换 api-key,钩子缺失或残留。 - 新增 (liii pi code config oauth-hook):pi-make-refresh-oauth-hook 与 pi-sync-oauth-refresh-hook(按当前 provider 注入/清除钩子) - pi-worker-merge-model(含同 provider 切模)与 %worker-reload-cfg 均重同步;pi-cfg-with-model 委托共享实现 测试:oauth-hook 端到端(stub OAuth 服务)、切模钩子重同步、 save! 失败不阻断回归;真实 go worker 探针验证新 token 正确落盘 --- ai/liii/pi/ai/auth/oauth/resolve.scm | 18 ++- ...orce-refresh-oauth-credential-key-test.scm | 26 +++ code/liii/pi/code/config.scm | 49 +----- code/liii/pi/code/config/oauth-hook.scm | 84 ++++++++++ .../liii/pi/code/config/oauth-hook/README.md | 20 +++ .../pi-make-refresh-oauth-hook-test.scm | 127 +++++++++++++++ .../pi-sync-oauth-refresh-hook-test.scm | 119 ++++++++++++++ code/tests/stub_kimi_oauth_server.py | 152 ++++++++++++++++++ tui/liii/pi/tui/interactive/worker-model.scm | 35 ++-- tui/liii/pi/tui/interactive/worker.scm | 46 ++---- .../pi/tui/interactive/worker-model/README.md | 1 + .../pi-worker-merge-model-test.scm | 116 +++++++++++++ 12 files changed, 707 insertions(+), 86 deletions(-) create mode 100644 code/liii/pi/code/config/oauth-hook.scm create mode 100644 code/tests/liii/pi/code/config/oauth-hook/README.md create mode 100644 code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm create mode 100644 code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm create mode 100644 code/tests/stub_kimi_oauth_server.py create mode 100644 tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm diff --git a/ai/liii/pi/ai/auth/oauth/resolve.scm b/ai/liii/pi/ai/auth/oauth/resolve.scm index e1c852ef..bce28dda 100644 --- a/ai/liii/pi/ai/auth/oauth/resolve.scm +++ b/ai/liii/pi/ai/auth/oauth/resolve.scm @@ -10,9 +10,11 @@ ;; Models.getAuth() 在 store lock 内 refresh 的简化版)。 (define-library (liii pi ai auth oauth resolve) (import (scheme base) + (scheme write) (liii pi ai config credential) (liii pi ai auth oauth kimi-coding-oauth) (liii pi ai time) + (liii pi ai log) ) ;import (export pi-find-oauth-credential pi-resolve-oauth-credential-key @@ -71,7 +73,21 @@ ) ; (cond ((pi-credential? refreshed) - (catch #t (lambda () (save! refreshed)) (lambda args #f)) + ;; 落盘失败不阻断本次请求(新 access 仍可用),但须留痕: + ;; 静默吞错会掩盖 worker 会话符号未绑定等问题,导致新 token + ;; 不落盘、下次启动仍用旧 token 反复 401 + (catch #t + (lambda () (save! refreshed)) + (lambda (tag . args) + (pi-log-error! (string-append "[oauth-refresh] save failed provider=" + (or provider "") + " error=" + (object->string (cons tag args)) + ) ;string-append + ) ;pi-log-error! + #f + ) ;lambda + ) ;catch (pi-credential-access refreshed) ) ; ((and (pair? refreshed) (eq? (car refreshed) 'kimi-oauth-unauthorized)) diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm index aea735a0..813df7b3 100644 --- a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm @@ -137,4 +137,30 @@ (check removed => '()) ) ;let* +;; 4. save! 抛异常(如 worker 会话符号未绑定):不阻断,仍返回新 access +(let* ((proc (process-spawn (list "python3" stub-file "refresh-ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + (cred (pi-credential "kimi-coding" + #f + "oauth" + "old-acc" + "stub-refresh-token" + (+ (pi-current-time-millis) 3600000) + host + ) ;pi-credential + ) ;cred + ) ; + (check + (pi-force-refresh-oauth-credential-key cred + '() + (lambda (c) (error 'save-failed "disk full")) + (lambda (p) #f) + ) ;pi-force-refresh-oauth-credential-key + => + "stub-access-token-2" + ) ;check + (process-kill proc) +) ;let* + (check-report) diff --git a/code/liii/pi/code/config.scm b/code/liii/pi/code/config.scm index 0f7ee8a2..c764267a 100644 --- a/code/liii/pi/code/config.scm +++ b/code/liii/pi/code/config.scm @@ -19,7 +19,7 @@ (liii pi code cli args) (liii pi code core tools) (liii pi ai auth) - (liii pi ai auth oauth resolve) + (liii pi code config oauth-hook) (liii pi ai models) (liii pi ai thinking) (liii pi ai providers registry) @@ -44,6 +44,8 @@ pi-resolve-provider-key pi-resolve-model-metadata pi-resolve-request-headers resolve-pi-config resolve-goldpi-config resolve-active-tools pi-missing-credential-msg augment-pi-config + ;; 1404:切模/reload 后按 provider 重同步 oauth 401 刷新钩子 + pi-sync-oauth-refresh-hook ) ;export (begin ;; pi-get-agent-dir 已下沉至 (liii pi code core tools read),此处经 import 再导出 @@ -369,54 +371,15 @@ ;; 1404:若 provider 在 auth.json 有 oauth 凭据,注入 refresh-oauth-key ;; 钩子,供请求层收到 401 后强制刷新重试一次。无 oauth 凭据不注入 ;; (非 oauth provider 的 401 按现状失败)。钩子返回新 access / 'unauthorized / #f。 - (if (pi-has-oauth-credential? provider auth) - (let ((captured-env (if (pair? opt-env) (car opt-env) '())) - (captured-dir config-dir-str) - ) ; - (pi-cfg-set base-cfg - 'refresh-oauth-key - (%make-refresh-oauth-hook captured-env captured-dir) - ) ;pi-cfg-set - ) ;let - base-cfg - ) ;if + (pi-sync-oauth-refresh-hook base-cfg + (if (pair? opt-env) (car opt-env) '()) + ) ;pi-sync-oauth-refresh-hook ) ;let ) ;let* ) ;let-values ) ;let* ) ;define - ;; 1404:构造 401 后强制刷新 oauth 凭据的闭包钩子。落盘/清除回调 - ;; 注入 auth.json 目录(captured-dir),env 表 captured-env 透传。 - (define (%make-refresh-oauth-hook captured-env captured-dir) - (lambda (cfg current-key) - (let* ((p (pi-cfg-ref cfg 'provider #f)) - (creds (if (pair? captured-env) - (pi-load-auth captured-dir captured-env) - (pi-load-auth captured-dir) - ) ;if - ) ;creds - (cred (pi-find-oauth-credential p creds)) - ) ; - (if cred - (pi-force-refresh-oauth-credential-key cred - (if (pair? captured-env) captured-env '()) - (lambda (c) - (pi-save-auth-oauth! (pi-credential-provider c) - (pi-credential-access c) - (pi-credential-refresh c) - (pi-credential-expires c) - (pi-credential-region c) - captured-dir - ) ;pi-save-auth-oauth! - ) ;lambda - (lambda (pp) (pi-remove-auth-provider! pp captured-dir)) - ) ;pi-force-refresh-oauth-credential-key - #f - ) ;if - ) ;let* - ) ;lambda - ) ;define (define resolve-goldpi-config resolve-pi-config) ;; 应用扩展注册的 config augmenter:内置/用户扩展经此 diff --git a/code/liii/pi/code/config/oauth-hook.scm b/code/liii/pi/code/config/oauth-hook.scm new file mode 100644 index 00000000..283b9c55 --- /dev/null +++ b/code/liii/pi/code/config/oauth-hook.scm @@ -0,0 +1,84 @@ +;; +;; Copyright (C) 2026 The Goldfish Scheme Authors +;; +;; Licensed under the MIT License +;; + +;; 1404:oauth 401 强制刷新钩子的构造与按 provider 重同步。 +;; resolve-pi-config 初始注入,以及会话内切模(含同 provider)/ +;; /login 后 reload 时都须调用 pi-sync-oauth-refresh-hook: +;; 钩子闭包捕获 provider 无关的 env/dir,按 cfg 当前 provider 现查 +;; auth.json,有 oauth 凭据则注入,无则移除旧钩子(避免切到非 +;; oauth provider 后残留钩子误刷新)。 +(define-library (liii pi code config oauth-hook) + (import (scheme base) + (scheme process-context) + (liii path) + (liii pi ai auth) + ;; save!/remove! 闭包经 procedure-source 在 go worker 会话重建求值, + ;; pi-credential-* 访问器须随本库进入会话活动库列表,否则 save! 抛 + ;; unbound 被吞、新 token 不落盘(下次启动仍用旧 token 反复 401) + (liii pi ai config credential) + (liii pi ai auth oauth resolve) + (liii pi ai config runtime) + ) ;import + (export pi-make-refresh-oauth-hook pi-sync-oauth-refresh-hook) + (begin + + ;; 构造 401 后强制刷新 oauth 凭据的闭包钩子。落盘/清除回调 + ;; 注入 auth.json 目录(captured-dir),env 表 captured-env 透传。 + (define (pi-make-refresh-oauth-hook captured-env captured-dir) + (lambda (cfg current-key) + (let* ((p (pi-cfg-ref cfg 'provider #f)) + (creds (if (pair? captured-env) + (pi-load-auth captured-dir captured-env) + (pi-load-auth captured-dir) + ) ;if + ) ;creds + (cred (pi-find-oauth-credential p creds)) + ) ; + (if cred + (pi-force-refresh-oauth-credential-key cred + (if (pair? captured-env) captured-env '()) + (lambda (c) + (pi-save-auth-oauth! (pi-credential-provider c) + (pi-credential-access c) + (pi-credential-refresh c) + (pi-credential-expires c) + (pi-credential-region c) + captured-dir + ) ;pi-save-auth-oauth! + ) ;lambda + (lambda (pp) (pi-remove-auth-provider! pp captured-dir)) + ) ;pi-force-refresh-oauth-credential-key + #f + ) ;if + ) ;let* + ) ;lambda + ) ;define + + ;; 按 cfg 当前 provider 同步 refresh-oauth-key 钩子: + ;; 有 oauth 凭据 → 注入(覆盖旧钩子,目录取 cfg 现值); + ;; 无 → 置 #f 移除残留钩子(非 oauth provider 的 401 按现状失败)。 + ;; opt-env 为 (env-alist) 形式,缺省取当前进程环境变量。 + (define (pi-sync-oauth-refresh-hook cfg . opt-env) + (let* ((env (if (pair? opt-env) (car opt-env) (get-environment-variables))) + ;; 与 pi-cfg-config-dir 同义:优先 config-dir,缺失回退 agent-dir + ;; (就地取避免引入 (liii pi code config) 循环依赖) + (dir (or (pi-cfg-ref cfg 'config-dir) (pi-cfg-ref cfg 'agent-dir))) + (dir-str (if (path? dir) (path->string dir) dir)) + (provider (pi-cfg-ref cfg 'provider #f)) + (creds (pi-load-auth dir-str env)) + ) ; + (pi-cfg-set cfg + 'refresh-oauth-key + (if (pi-has-oauth-credential? provider creds) + (pi-make-refresh-oauth-hook env dir-str) + #f + ) ;if + ) ;pi-cfg-set + ) ;let* + ) ;define + + ) ;begin +) ;define-library diff --git a/code/tests/liii/pi/code/config/oauth-hook/README.md b/code/tests/liii/pi/code/config/oauth-hook/README.md new file mode 100644 index 00000000..10664c86 --- /dev/null +++ b/code/tests/liii/pi/code/config/oauth-hook/README.md @@ -0,0 +1,20 @@ +# (liii pi code config oauth-hook) 测试导览 + +`(liii pi code config oauth-hook)` 构造并同步 oauth 401 强制刷新钩子: +`resolve-pi-config` 初始注入、会话内切模(含同 provider)与 `/login` 后 +reload 都经 `pi-sync-oauth-refresh-hook` 按当前 provider 重同步, +保证请求层收到 401 时能强制 refresh 重试一次。 + +## 运行测试 + +```bash +bin/gf test code/tests/liii/pi/code/config/oauth-hook/ +``` + +## 测试文件索引 + +- `pi-sync-oauth-refresh-hook-test.scm` — 有/无 oauth 凭据的注入与清除、 + 会话中途 `/login` 后重同步、alist cfg 与缺省 env 支持 +- `pi-make-refresh-oauth-hook-test.scm` — 钩子端到端:stub OAuth 服务 + refresh 成功落盘返回新 access;invalid_grant 清除凭据返回 #f; + 非 oauth provider 返回 #f diff --git a/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm b/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm new file mode 100644 index 00000000..5944ed7a --- /dev/null +++ b/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm @@ -0,0 +1,127 @@ +;; pi-make-refresh-oauth-hook +;; 构造 401 后强制刷新 oauth 凭据的闭包钩子:按 cfg 当前 provider 现查 +;; auth.json,刷新成功落盘返回新 access;invalid_grant 清除凭据返回 #f。 +;; +;; 语法 +;; ---- +;; (pi-make-refresh-oauth-hook captured-env captured-dir) -> procedure? +;; +;; 参数 +;; ---- +;; captured-env : list? +;; 环境变量 alist(KIMI_CODE_OAUTH_HOST 覆盖)。 +;; +;; captured-dir : string? +;; auth.json 所在配置目录(落盘/清除回调使用)。 +;; +;; 返回值 +;; ---- +;; procedure? +;; 钩子 (lambda (cfg current-key) ...):返回新 access 字符串或 #f。 + +(import (scheme base) + (scheme file) + (liii check) + (liii path) + (liii shutil) + (liii string) + (liii subprocess) + (liii pi ai config runtime) + (liii pi ai auth) + (liii pi ai time) + (liii pi code config oauth-hook) +) ;import + +(check-set-mode! 'report-failed) + +(define TMP-DIR + (path->string (path-join (path-temp-dir) "pi-make-refresh-oauth-hook-test")) +) ;define + +(when (file-exists? TMP-DIR) + (rmtree TMP-DIR) +) ;when +(path-mkdir TMP-DIR :parents #t :exist-ok #t) + +(define stub-file + (cond ((file-exists? "code/tests/stub_kimi_oauth_server.py") + "code/tests/stub_kimi_oauth_server.py" + ) ; + ((file-exists? "tests/stub_kimi_oauth_server.py") "tests/stub_kimi_oauth_server.py") + (else "../code/tests/stub_kimi_oauth_server.py") + ) ;cond +) ;define + +(define (parse-port-line line) + (if (and (string? line) (string-starts? line "PORT:")) + (string->number (string-trim-both (substring line 5 (string-length line)))) + #f + ) ;if +) ;define + +;; 写 kimi-coding oauth 凭据:region 指向 stub host,expires 仍在未来 +;; (401 强制刷新不查 expires) +(define (write-auth! host refresh-token) + (path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) + (string-append "{\"kimi-coding\":{\"type\":\"oauth\",\"access\":\"old-acc\"," + "\"refresh\":\"" + refresh-token + "\",\"expires\":" + (number->string (+ (pi-current-time-millis) 3600000)) + ",\"region\":\"" + host + "\"}}" + ) ;string-append + ) ;path-write-text +) ;define + +(define (make-cfg) + (make-pi-config :config-dir TMP-DIR :provider "kimi-coding") +) ;define + +;; 1. refresh 成功:返回新 access,auth.json 落盘新凭据 +(let* ((proc (process-spawn (list "python3" stub-file "refresh-ok") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (write-auth! host "stub-refresh-token") + (let* ((hook (pi-make-refresh-oauth-hook '() TMP-DIR)) + (next (hook (make-cfg) "old-acc")) + ) ; + (check next => "stub-access-token-2") + (check (length (pi-load-auth TMP-DIR)) => 1) + (check (pi-resolve-provider-key "kimi-coding" (pi-load-auth TMP-DIR) '() TMP-DIR) + => + "stub-access-token-2" + ) ;check + ) ;let* + (process-kill proc) +) ;let* + +;; 2. refresh 失败(401 invalid_grant):清除凭据返回 #f +(let* ((proc (process-spawn (list "python3" stub-file "refresh-401") :stdout 'pipe)) + (port (parse-port-line (process-read-line proc))) + (host (string-append "http://127.0.0.1:" (number->string port))) + ) ; + (write-auth! host "stub-refresh-token") + (let* ((hook (pi-make-refresh-oauth-hook '() TMP-DIR)) + (next (hook (make-cfg) "old-acc")) + ) ; + (check next => #f) + (check (pi-load-auth TMP-DIR) => '()) + ) ;let* + (process-kill proc) +) ;let* + +;; 3. cfg provider 无 oauth 凭据:返回 #f(不动其他 provider 凭据) +(path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) + "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}" +) ;path-write-text +(let ((hook (pi-make-refresh-oauth-hook '() TMP-DIR))) + (check (hook (make-cfg) "old-acc") => #f) + (check (length (pi-load-auth TMP-DIR)) => 1) +) ;let + +(rmtree TMP-DIR) + +(check-report) diff --git a/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm b/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm new file mode 100644 index 00000000..83a1f46a --- /dev/null +++ b/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm @@ -0,0 +1,119 @@ +;; pi-sync-oauth-refresh-hook +;; 按 cfg 当前 provider 同步 refresh-oauth-key 钩子:有 oauth 凭据注入, +;; 无则移除残留钩子。切模(含同 provider)与 /login 后 reload 都依赖此函数。 +;; +;; 语法 +;; ---- +;; (pi-sync-oauth-refresh-hook cfg . opt-env) -> cfg +;; +;; 参数 +;; ---- +;; cfg : pi-config? 或 alist +;; 含 provider 与 config-dir(或 agent-dir)的配置。 +;; +;; opt-env : list? +;; 可选 (env-alist),缺省取当前进程环境变量。 +;; +;; 返回值 +;; ---- +;; cfg +;; 同类型配置:refresh-oauth-key 为过程(有 oauth 凭据)或 #f(无)。 + +(import (scheme base) + (scheme file) + (scheme process-context) + (liii check) + (liii path) + (liii shutil) + (liii pi ai config runtime) + (liii pi ai keyring) + (liii pi ai time) + (liii pi code config oauth-hook) +) ;import + +(check-set-mode! 'report-failed) + +(define TMP-DIR + (path->string (path-join (path-temp-dir) "pi-sync-oauth-refresh-hook-test")) +) ;define + +(when (file-exists? TMP-DIR) + (rmtree TMP-DIR) +) ;when +(path-mkdir TMP-DIR :parents #t :exist-ok #t) + +(define (write-auth! text) + (path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) text) +) ;define + +(define (oauth-json expires) + (string-append "{\"kimi-coding\":{\"type\":\"oauth\",\"access\":\"old-acc\"," + "\"refresh\":\"stub-refresh-token\",\"expires\":" + (number->string expires) + "}}" + ) ;string-append +) ;define + +(define (make-cfg provider) + (make-pi-config :config-dir TMP-DIR :provider provider) +) ;define + +;; 1. provider 有 oauth 凭据:注入钩子(pi-oauth-refresh-enabled? 为真) +(write-auth! (oauth-json (+ (pi-current-time-millis) 3600000))) +(let ((cfg (pi-sync-oauth-refresh-hook (make-cfg "kimi-coding") '()))) + (check-true (pi-oauth-refresh-enabled? cfg)) +) ;let + +;; 2. provider 无 oauth 凭据(api_key):不注入 +(write-auth! "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}") +(let ((cfg (pi-sync-oauth-refresh-hook (make-cfg "google") '()))) + (check-false (pi-oauth-refresh-enabled? cfg)) + (check (pi-cfg-ref cfg 'refresh-oauth-key) => #f) +) ;let + +;; 3. 残留钩子清除:从 oauth provider 切到 api_key provider 后钩子必须移除 +(write-auth! (oauth-json (+ (pi-current-time-millis) 3600000))) +(let* ((cfg-oauth (pi-sync-oauth-refresh-hook (make-cfg "kimi-coding") '())) + (cfg-switched (pi-cfg-set cfg-oauth 'provider "google")) + ) ; + (check-true (pi-oauth-refresh-enabled? cfg-switched)) + (write-auth! "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}") + (let ((cfg-synced (pi-sync-oauth-refresh-hook cfg-switched '()))) + (check-false (pi-oauth-refresh-enabled? cfg-synced)) + ) ;let +) ;let* + +;; 4. 会话中途 /login:初始无凭据不注入,落盘 oauth 凭据后重同步必须注入 +(write-auth! "{}") +(let ((cfg (pi-sync-oauth-refresh-hook (make-cfg "kimi-coding") '()))) + (check-false (pi-oauth-refresh-enabled? cfg)) + (write-auth! (oauth-json (+ (pi-current-time-millis) 3600000))) + (check-true (pi-oauth-refresh-enabled? (pi-sync-oauth-refresh-hook cfg '()))) +) ;let + +;; 5. 无 auth.json:不注入且不抛异常 +(rmtree TMP-DIR) +(path-mkdir TMP-DIR :parents #t :exist-ok #t) +(let ((cfg (pi-sync-oauth-refresh-hook (make-cfg "kimi-coding") '()))) + (check-false (pi-oauth-refresh-enabled? cfg)) +) ;let + +;; 6. alist 形式 cfg 同样支持 +(write-auth! (oauth-json (+ (pi-current-time-millis) 3600000))) +(let ((cfg (pi-sync-oauth-refresh-hook + (list (cons 'config-dir TMP-DIR) (cons 'provider "kimi-coding")) + '() + ) ;pi-sync-oauth-refresh-hook + ) ;cfg + ) ; + (check-true (pi-oauth-refresh-enabled? cfg)) +) ;let + +;; 7. 省略 opt-env:取进程环境变量,oauth 判定不受影响 +(let ((cfg (pi-sync-oauth-refresh-hook (make-cfg "kimi-coding")))) + (check-true (pi-oauth-refresh-enabled? cfg)) +) ;let + +(rmtree TMP-DIR) + +(check-report) diff --git a/code/tests/stub_kimi_oauth_server.py b/code/tests/stub_kimi_oauth_server.py new file mode 100644 index 00000000..173f4828 --- /dev/null +++ b/code/tests/stub_kimi_oauth_server.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Kimi Code OAuth2 stub server for gfcode unit tests (1402 §3.2). + +Emulates https://auth.kimi.com endpoints: + POST /api/oauth/device_authorization -> device_code/user_code/verification URIs + POST /api/oauth/token -> device_code grant polling & refresh_token grant + +Scenario is chosen by the first CLI arg (default "ok"): + ok authorize OK; token poll: pending once, then complete + slow-down poll: pending, slow_down (with new interval), then complete + denied poll: access_denied + expired poll: expired_token + poll-500 poll: HTTP 500 + authorize-500 device_authorization: HTTP 500 + authorize-bad device_authorization: 200 with missing fields + refresh-ok refresh grant returns fresh tokens immediately + refresh-401 refresh grant returns 401 invalid_grant + refresh-403 refresh grant returns 403 + refresh-flaky refresh grant: 429 twice then 200 (retry backoff path) + refresh-500 refresh grant: always 500 (retries exhausted) + +Prints "PORT:" on stdout once listening. +""" +import http.server +import json +import sys +import urllib.parse + +SCENARIO = sys.argv[1] if len(sys.argv) > 1 else "ok" + + +class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def _send(self, status: int, obj: dict) -> None: + body = json.dumps(obj).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: + try: + length = int(self.headers.get("content-length") or 0) + except ValueError: + self._send(400, {"error": "invalid_request"}) + return + raw = self.rfile.read(length).decode("utf-8") if length else "" + form = dict(urllib.parse.parse_qsl(raw)) + server = self.server + server.token_polls = getattr(server, "token_polls", 0) + server.refresh_calls = getattr(server, "refresh_calls", 0) + + if self.path == "/api/oauth/device_authorization": + if form.get("client_id") != "17e5f671-d194-4dfb-9706-5516cb48c098": + self._send(400, {"error": "invalid_client"}) + return + if SCENARIO == "authorize-500": + self._send(500, {"error": "server_error"}) + return + if SCENARIO == "authorize-bad": + self._send(200, {"user_code": "ABCD-1234"}) + return + self._send(200, { + "device_code": "stub-device-code", + "user_code": "ABCD-1234", + "verification_uri": "https://www.kimi.com/code", + "verification_uri_complete": + "https://www.kimi.com/code/authorize_device?user_code=ABCD-1234", + "interval": 1, + "expires_in": 900, + }) + return + + if self.path == "/api/oauth/token": + grant = form.get("grant_type") + if grant == "urn:ietf:params:oauth:grant-type:device_code": + if form.get("device_code") != "stub-device-code": + self._send(400, {"error": "invalid_grant"}) + return + server.token_polls += 1 + n = server.token_polls + if SCENARIO == "denied": + self._send(400, {"error": "access_denied"}) + return + if SCENARIO == "expired": + self._send(400, {"error": "expired_token"}) + return + if SCENARIO == "poll-500": + self._send(500, {"error": "server_error"}) + return + if SCENARIO == "slow-down": + if n == 1: + self._send(400, {"error": "authorization_pending"}) + return + if n == 2: + self._send(400, {"error": "slow_down", "interval": 1}) + return + else: + if n == 1: + self._send(400, {"error": "authorization_pending"}) + return + self._send(200, { + "access_token": "stub-access-token", + "refresh_token": "stub-refresh-token", + "expires_in": 3600, + "token_type": "Bearer", + }) + return + if grant == "refresh_token": + server.refresh_calls += 1 + n = server.refresh_calls + if form.get("refresh_token") == "dead-refresh-token" or SCENARIO == "refresh-401": + self._send(401, {"error": "invalid_grant", + "error_description": "refresh token expired"}) + return + if SCENARIO == "refresh-403": + self._send(403, {"error": "access_denied"}) + return + if SCENARIO == "refresh-500": + self._send(500, {"error": "server_error"}) + return + if SCENARIO == "refresh-flaky" and n <= 2: + self._send(429, {"error": "rate_limited"}) + return + self._send(200, { + "access_token": "stub-access-token-2", + "refresh_token": "stub-refresh-token-2", + "expires_in": 3600, + "token_type": "Bearer", + }) + return + self._send(400, {"error": "unsupported_grant_type"}) + return + + self._send(404, {"error": "not_found"}) + + +def main() -> None: + # 仅绑定回环地址;测试结束时由 process-kill 终止,无需优雅关停 + server = http.server.HTTPServer(("127.0.0.1", 0), Handler) + print("PORT:%d" % server.server_address[1], flush=True) + try: + server.serve_forever() + finally: + server.server_close() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tui/liii/pi/tui/interactive/worker-model.scm b/tui/liii/pi/tui/interactive/worker-model.scm index 1fbf02f5..39b2bf29 100644 --- a/tui/liii/pi/tui/interactive/worker-model.scm +++ b/tui/liii/pi/tui/interactive/worker-model.scm @@ -3,6 +3,7 @@ ;; ;; Licensed under the MIT License ;; +;; ;; 模型选择与请求前刷新逻辑:独立于 jobs-chan 的“最新请求选择”通道, ;; 在每次新 Provider 请求前解析最新选择并派生完整 effective-cfg。 @@ -20,6 +21,8 @@ ) ;import (export pi-make-effective-cfg-box pi-effective-cfg-ref pi-effective-cfg-set! pi-worker-make-prepare-request pi-worker-apply-selection + ;; worker 线程重新求值调用链上的助手须导出 + pi-worker-merge-model ) ;export (begin @@ -74,19 +77,25 @@ (meta (pi-ensure-catalog-meta raw-meta provider model-id models-store)) (supports (pi-model-supports-thinking? models-store provider model-id)) ) ; - (pi-cfg-merge cfg - (list (cons 'provider provider) - (cons 'provider-api (pi-cfg-provider-api cfg provider model-id)) - (cons 'headers - (pi-resolve-request-headers models-store provider model-id api-key) - ) ;cons - (cons 'model-id model-id) - (cons 'model-meta meta) - (cons 'api-key api-key) - (cons 'supports-thinking supports) - (cons 'proxy-url (pi-cfg-provider-proxy cfg provider)) - ) ;list - ) ;pi-cfg-merge + ;; 1404:切模(含同 provider)后按新 provider 重同步 oauth 401 + ;; 刷新钩子:切到 oauth provider 时注入,切走时清除残留钩子。 + ;; 否则同 provider 切模不走 augment,会话中途 /login 后钩子缺失, + ;; 401 无法强制刷新重试。 + (pi-sync-oauth-refresh-hook + (pi-cfg-merge cfg + (list (cons 'provider provider) + (cons 'provider-api (pi-cfg-provider-api cfg provider model-id)) + (cons 'headers + (pi-resolve-request-headers models-store provider model-id api-key) + ) ;cons + (cons 'model-id model-id) + (cons 'model-meta meta) + (cons 'api-key api-key) + (cons 'supports-thinking supports) + (cons 'proxy-url (pi-cfg-provider-proxy cfg provider)) + ) ;list + ) ;pi-cfg-merge + ) ;pi-sync-oauth-refresh-hook ) ;let* ) ;define diff --git a/tui/liii/pi/tui/interactive/worker.scm b/tui/liii/pi/tui/interactive/worker.scm index c5b99e8f..521812fb 100644 --- a/tui/liii/pi/tui/interactive/worker.scm +++ b/tui/liii/pi/tui/interactive/worker.scm @@ -19,6 +19,10 @@ (liii path) (liii pi ai abort) (liii pi ai auth) + ;; 1404:oauth 401 刷新钩子的 save!/remove! 闭包经 procedure-source 在 + ;; worker 会话重建,pi-credential-* 访问器须在本会话可见,否则 save! + ;; 抛 unbound 被吞、新 token 不落盘(下次启动仍用旧 token 反复 401) + (liii pi ai config credential) (liii pi ai config model-metadata) (liii pi ai models meta) (liii pi ai models route) @@ -86,30 +90,10 @@ ) ;pi-cfg-merge ) ;define - ;; 覆盖 cfg 的模型相关项(会话内 /model 切换后下一条消息生效,对齐上游 setModel) + ;; 覆盖 cfg 的模型相关项(会话内 /model 切换后下一条消息生效,对齐上游 setModel)。 + ;; 1404:委派 worker-model 的共享实现,含 oauth 401 刷新钩子重同步。 (define (pi-cfg-with-model cfg provider model-id) - (let* ((config-dir (pi-cfg-config-dir cfg)) - (models-store (pi-cfg-ref cfg 'models-store '())) - (auth (pi-load-auth config-dir)) - (api-key (pi-resolve-provider-key provider auth '() config-dir)) - (raw-meta (pi-resolve-model-metadata provider model-id models-store)) - (meta (pi-ensure-catalog-meta raw-meta provider model-id models-store)) - (supports (pi-model-supports-thinking? models-store provider model-id)) - ) ; - (pi-cfg-merge cfg - (list (cons 'provider provider) - (cons 'provider-api (pi-cfg-provider-api cfg provider model-id)) - (cons 'headers - (pi-resolve-request-headers models-store provider model-id api-key) - ) ;cons - (cons 'model-id model-id) - (cons 'model-meta meta) - (cons 'api-key api-key) - (cons 'supports-thinking supports) - (cons 'proxy-url (pi-cfg-provider-proxy cfg provider)) - ) ;list - ) ;pi-cfg-merge - ) ;let* + (pi-worker-merge-model cfg provider model-id) ) ;define (define (%job-explicit job cfg) @@ -218,12 +202,16 @@ (new-key (and cur-p (pi-resolve-provider-key cur-p (pi-load-auth dir-str) '() dir-str)) ) ;new-key ) ; - (%cfg-override cfg - (list (cons 'models-store (pi-build-user-catalog dir-str)) - (cons 'settings (pi-load-settings dir)) - (cons 'api-key new-key) - ) ;list - ) ;%cfg-override + ;; 1404:/login 或刷新凭据后 reload 须重同步 oauth 401 刷新钩子, + ;; 否则启动时无 oauth 凭据的会话登录后仍按现状 401 失败 + (pi-sync-oauth-refresh-hook + (%cfg-override cfg + (list (cons 'models-store (pi-build-user-catalog dir-str)) + (cons 'settings (pi-load-settings dir)) + (cons 'api-key new-key) + ) ;list + ) ;%cfg-override + ) ;pi-sync-oauth-refresh-hook ) ;let* ) ;define diff --git a/tui/tests/liii/pi/tui/interactive/worker-model/README.md b/tui/tests/liii/pi/tui/interactive/worker-model/README.md index 62d92d2f..ee883b2c 100644 --- a/tui/tests/liii/pi/tui/interactive/worker-model/README.md +++ b/tui/tests/liii/pi/tui/interactive/worker-model/README.md @@ -12,6 +12,7 @@ - `pi-worker-make-prepare-request` - 构造 prepare-request 过程(排空通道、latest-wins、派生并保存 effective-cfg) - `pi-worker-apply-selection` - 把一条选择快照应用到 base-cfg,派生完整配置(跨 provider 执行 augment) +- `pi-worker-merge-model` - 覆盖模型相关项并按新 provider 重同步 oauth 401 刷新钩子(含同 provider 切模) - `pi-make-effective-cfg-box` / `pi-effective-cfg-ref` / `pi-effective-cfg-set!` - runtime/effective-cfg 容器 详见当前目录下的单元测试用例。 diff --git a/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm b/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm new file mode 100644 index 00000000..8d170c24 --- /dev/null +++ b/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm @@ -0,0 +1,116 @@ +;; pi-worker-merge-model +;; 覆盖 cfg 的模型相关项(会话内 /model 切换后立即生效),并按新 +;; provider 重同步 oauth 401 刷新钩子:切到 oauth provider 注入, +;; 切走清除残留钩子(同 provider 切模不走 augment 也须同步)。 +;; +;; 语法 +;; ---- +;; (pi-worker-merge-model cfg provider model-id) -> cfg +;; +;; 参数 +;; ---- +;; cfg : pi-config? +;; 基准配置(含 config-dir / models-store)。 +;; +;; provider : string? +;; 目标 provider。 +;; +;; model-id : string? +;; 目标模型 id。 +;; +;; 返回值 +;; ---- +;; cfg +;; 覆盖 provider/model-id/api-key/headers 等模型相关项后的配置。 + +(import (scheme base) + (scheme file) + (liii check) + (liii path) + (liii shutil) + (liii pi ai keyring) + (liii pi ai time) + (liii pi code cli args) + (liii pi code config) + (liii pi tui interactive worker-model) +) ;import + +(check-set-mode! 'report-failed) + +(define TMP-DIR + (path->string (path-join (path-temp-dir) "pi-worker-merge-model-test")) +) ;define + +(when (file-exists? TMP-DIR) + (rmtree TMP-DIR) +) ;when +(path-mkdir TMP-DIR :parents #t :exist-ok #t) + +(path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) + (string-append "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}," + "\"kimi-coding\":{\"type\":\"oauth\",\"access\":\"old-acc\"," + "\"refresh\":\"stub-refresh-token\",\"expires\":" + (number->string (+ (pi-current-time-millis) 3600000)) + "}}" + ) ;string-append +) ;path-write-text + +(define env (list (cons "PI_CODING_AGENT_DIR" TMP-DIR))) + +;; 1. 跨 provider 切到 oauth provider:模型项覆盖且注入 401 刷新钩子 +(let* ((cfg (resolve-pi-config (parse-pi-args '()) env)) + (cfg* (pi-worker-merge-model cfg "kimi-coding" "k3.1-pro")) + ) ; + (check (pi-cfg-ref cfg* 'provider) => "kimi-coding") + (check (pi-cfg-ref cfg* 'model-id) => "k3.1-pro") + (check-true (pi-oauth-refresh-enabled? cfg*)) + ;; 原 cfg 不被破坏(google 无 oauth 凭据无钩子) + (check-false (pi-oauth-refresh-enabled? cfg)) +) ;let* + +;; 2. 从 oauth provider 切走:残留钩子必须清除,否则非 oauth 的 401 +;; 会误触发刷新 +(let* ((cfg (resolve-pi-config (parse-pi-args '()) env)) + (cfg-kimi (pi-worker-merge-model cfg "kimi-coding" "k3.1-pro")) + (cfg-google (pi-worker-merge-model cfg-kimi "google" "gemini-3.8-flash")) + ) ; + (check (pi-cfg-ref cfg-google 'provider) => "google") + (check (pi-cfg-ref cfg-google 'api-key) => "fixture-google-key") + (check-false (pi-oauth-refresh-enabled? cfg-google)) +) ;let* + +;; 3. 会话中途 /login:初始无 kimi 凭据(无钩子),auth.json 落盘 oauth +;; 凭据后同 provider 切模必须补注入钩子(不走 augment 的路径) +(let ((no-kimi-dir (path->string (path-join (path-temp-dir) "pi-worker-merge-model-login-test"))) + ) ; + (when (file-exists? no-kimi-dir) + (rmtree no-kimi-dir) + ) ;when + (path-mkdir no-kimi-dir :parents #t :exist-ok #t) + (path-write-text (path->string (path-join (path no-kimi-dir) (path "auth.json"))) + "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}" + ) ;path-write-text + (let* ((env2 (list (cons "PI_CODING_AGENT_DIR" no-kimi-dir))) + (cfg (resolve-pi-config (parse-pi-args '()) env2)) + (cfg-kimi (pi-worker-merge-model cfg "kimi-coding" "k3.1-pro")) + ) ; + (check-false (pi-oauth-refresh-enabled? cfg-kimi)) + ;; 模拟 /login kimi-coding 落盘 oauth 凭据 + (path-write-text (path->string (path-join (path no-kimi-dir) (path "auth.json"))) + (string-append "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}," + "\"kimi-coding\":{\"type\":\"oauth\",\"access\":\"old-acc\"," + "\"refresh\":\"stub-refresh-token\",\"expires\":" + (number->string (+ (pi-current-time-millis) 3600000)) + "}}" + ) ;string-append + ) ;path-write-text + (let ((cfg-after (pi-worker-merge-model cfg-kimi "kimi-coding" "k3.1-pro"))) + (check-true (pi-oauth-refresh-enabled? cfg-after)) + ) ;let + ) ;let* + (rmtree no-kimi-dir) +) ;let + +(rmtree TMP-DIR) + +(check-report) From 64db8d57e1fbfd3abc2a4a14219476e6ed796ded Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 20:39:52 +0800 Subject: [PATCH 8/9] =?UTF-8?q?[1404]=20=E4=BF=AE=E5=A4=8D=20OAuth=20?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=9A=84=20Windows=20=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E4=B8=8E=E7=9B=AE=E5=BD=95=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm | 8 ++++++-- .../liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm index fee3281f..f2875bed 100644 --- a/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm @@ -19,11 +19,15 @@ (check-set-mode! 'report-failed) -(check (path->string (pi-auth-dir-path '("/tmp/gf-cfg"))) => "/tmp/gf-cfg") +(define expected-explicit-path + (path->string (path "/tmp/gf-cfg")) +) ;define + +(check (path->string (pi-auth-dir-path '("/tmp/gf-cfg"))) => expected-explicit-path) (check (path->string (pi-auth-dir-path (list (path "/tmp/gf-cfg")))) => - "/tmp/gf-cfg" + expected-explicit-path ) ;check (check (path->string (pi-auth-dir-path '(#f))) => diff --git a/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm b/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm index c0cb0ba9..42968029 100644 --- a/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm +++ b/tui/tests/liii/pi/tui/cli/auth/pi-auth-login-oauth-test.scm @@ -102,7 +102,7 @@ ) ;let ) ;let (path-unlink auth-file #t) - (path-rmdir tmp #t) + (path-rmdir tmp) (process-kill proc) ) ;let* @@ -130,7 +130,7 @@ (unless (path-exists? auth-file) #f ) ;unless - (path-rmdir tmp #t) + (path-rmdir tmp) ) ;let* (check-report) From 1bf7924623d334d5d06dc79707066487f972aad5 Mon Sep 17 00:00:00 2001 From: Da Shen Date: Mon, 23 Nov 2026 20:46:08 +0800 Subject: [PATCH 9/9] =?UTF-8?q?[1404]=20=E4=BF=AE=E5=A4=8D=20Check=20CI=20?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...orce-refresh-oauth-credential-key-test.scm | 11 +++-- .../ai/auth/storage/pi-auth-dir-path-test.scm | 9 ++-- code/liii/pi/code/config.scm | 44 +++++++++++++------ .../pi-make-refresh-oauth-hook-test.scm | 5 ++- .../pi-sync-oauth-refresh-hook-test.scm | 13 +++--- tui/liii/pi/tui/interactive/worker-model.scm | 7 ++- .../pi-worker-merge-model-test.scm | 5 ++- 7 files changed, 61 insertions(+), 33 deletions(-) diff --git a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm index 813df7b3..4477f7b3 100644 --- a/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm +++ b/ai/tests/liii/pi/ai/auth/oauth/resolve/pi-force-refresh-oauth-credential-key-test.scm @@ -151,12 +151,11 @@ ) ;pi-credential ) ;cred ) ; - (check - (pi-force-refresh-oauth-credential-key cred - '() - (lambda (c) (error 'save-failed "disk full")) - (lambda (p) #f) - ) ;pi-force-refresh-oauth-credential-key + (check (pi-force-refresh-oauth-credential-key cred + '() + (lambda (c) (error 'save-failed "disk full")) + (lambda (p) #f) + ) ;pi-force-refresh-oauth-credential-key => "stub-access-token-2" ) ;check diff --git a/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm b/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm index f2875bed..d19863ca 100644 --- a/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm +++ b/ai/tests/liii/pi/ai/auth/storage/pi-auth-dir-path-test.scm @@ -19,11 +19,12 @@ (check-set-mode! 'report-failed) -(define expected-explicit-path - (path->string (path "/tmp/gf-cfg")) -) ;define +(define expected-explicit-path (path->string (path "/tmp/gf-cfg"))) -(check (path->string (pi-auth-dir-path '("/tmp/gf-cfg"))) => expected-explicit-path) +(check (path->string (pi-auth-dir-path '("/tmp/gf-cfg"))) + => + expected-explicit-path +) ;check (check (path->string (pi-auth-dir-path (list (path "/tmp/gf-cfg")))) => diff --git a/code/liii/pi/code/config.scm b/code/liii/pi/code/config.scm index c764267a..e81bb41d 100644 --- a/code/liii/pi/code/config.scm +++ b/code/liii/pi/code/config.scm @@ -34,16 +34,36 @@ (liii pi code core extensions event) (liii pi code core extensions types) ) ;import - (export pi-resolve-config-value json-dict-ref pi-get-agent-dir pi-config? - make-pi-config pi-cfg-ref pi-cfg-set pi-cfg-merge gf-get-config-dir - pi-cfg-config-dir pi-read-json-file pi-load-settings - pi-save-default-thinking-level! pi-save-hide-thinking-block! - pi-save-default-model! pi-model-supports-thinking? pi-cfg-provider-proxy - pi-model-available-thinking-levels pi-cfg-provider-api - pi-load-compaction-settings pi-resolve-proxy-url pi-load-auth - pi-resolve-provider-key pi-resolve-model-metadata pi-resolve-request-headers - resolve-pi-config resolve-goldpi-config resolve-active-tools - pi-missing-credential-msg augment-pi-config + (export pi-resolve-config-value + json-dict-ref + pi-get-agent-dir + pi-config? + make-pi-config + pi-cfg-ref + pi-cfg-set + pi-cfg-merge + gf-get-config-dir + pi-cfg-config-dir + pi-read-json-file + pi-load-settings + pi-save-default-thinking-level! + pi-save-hide-thinking-block! + pi-save-default-model! + pi-model-supports-thinking? + pi-cfg-provider-proxy + pi-model-available-thinking-levels + pi-cfg-provider-api + pi-load-compaction-settings + pi-resolve-proxy-url + pi-load-auth + pi-resolve-provider-key + pi-resolve-model-metadata + pi-resolve-request-headers + resolve-pi-config + resolve-goldpi-config + resolve-active-tools + pi-missing-credential-msg + augment-pi-config ;; 1404:切模/reload 后按 provider 重同步 oauth 401 刷新钩子 pi-sync-oauth-refresh-hook ) ;export @@ -371,9 +391,7 @@ ;; 1404:若 provider 在 auth.json 有 oauth 凭据,注入 refresh-oauth-key ;; 钩子,供请求层收到 401 后强制刷新重试一次。无 oauth 凭据不注入 ;; (非 oauth provider 的 401 按现状失败)。钩子返回新 access / 'unauthorized / #f。 - (pi-sync-oauth-refresh-hook base-cfg - (if (pair? opt-env) (car opt-env) '()) - ) ;pi-sync-oauth-refresh-hook + (pi-sync-oauth-refresh-hook base-cfg (if (pair? opt-env) (car opt-env) '())) ) ;let ) ;let* ) ;let-values diff --git a/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm b/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm index 5944ed7a..ee587b0d 100644 --- a/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm +++ b/code/tests/liii/pi/code/config/oauth-hook/pi-make-refresh-oauth-hook-test.scm @@ -47,7 +47,9 @@ (cond ((file-exists? "code/tests/stub_kimi_oauth_server.py") "code/tests/stub_kimi_oauth_server.py" ) ; - ((file-exists? "tests/stub_kimi_oauth_server.py") "tests/stub_kimi_oauth_server.py") + ((file-exists? "tests/stub_kimi_oauth_server.py") + "tests/stub_kimi_oauth_server.py" + ) ; (else "../code/tests/stub_kimi_oauth_server.py") ) ;cond ) ;define @@ -61,6 +63,7 @@ ;; 写 kimi-coding oauth 凭据:region 指向 stub host,expires 仍在未来 ;; (401 强制刷新不查 expires) + (define (write-auth! host refresh-token) (path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) (string-append "{\"kimi-coding\":{\"type\":\"oauth\",\"access\":\"old-acc\"," diff --git a/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm b/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm index 83a1f46a..3daea1d8 100644 --- a/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm +++ b/code/tests/liii/pi/code/config/oauth-hook/pi-sync-oauth-refresh-hook-test.scm @@ -43,7 +43,9 @@ (path-mkdir TMP-DIR :parents #t :exist-ok #t) (define (write-auth! text) - (path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) text) + (path-write-text (path->string (path-join (path TMP-DIR) (path "auth.json"))) + text + ) ;path-write-text ) ;define (define (oauth-json expires) @@ -65,7 +67,8 @@ ) ;let ;; 2. provider 无 oauth 凭据(api_key):不注入 -(write-auth! "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}") +(write-auth! "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}" +) ;write-auth! (let ((cfg (pi-sync-oauth-refresh-hook (make-cfg "google") '()))) (check-false (pi-oauth-refresh-enabled? cfg)) (check (pi-cfg-ref cfg 'refresh-oauth-key) => #f) @@ -77,7 +80,8 @@ (cfg-switched (pi-cfg-set cfg-oauth 'provider "google")) ) ; (check-true (pi-oauth-refresh-enabled? cfg-switched)) - (write-auth! "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}") + (write-auth! "{\"google\":{\"type\":\"api_key\",\"key\":\"fixture-google-key\"}}" + ) ;write-auth! (let ((cfg-synced (pi-sync-oauth-refresh-hook cfg-switched '()))) (check-false (pi-oauth-refresh-enabled? cfg-synced)) ) ;let @@ -100,8 +104,7 @@ ;; 6. alist 形式 cfg 同样支持 (write-auth! (oauth-json (+ (pi-current-time-millis) 3600000))) -(let ((cfg (pi-sync-oauth-refresh-hook - (list (cons 'config-dir TMP-DIR) (cons 'provider "kimi-coding")) +(let ((cfg (pi-sync-oauth-refresh-hook (list (cons 'config-dir TMP-DIR) (cons 'provider "kimi-coding")) '() ) ;pi-sync-oauth-refresh-hook ) ;cfg diff --git a/tui/liii/pi/tui/interactive/worker-model.scm b/tui/liii/pi/tui/interactive/worker-model.scm index 39b2bf29..377a6627 100644 --- a/tui/liii/pi/tui/interactive/worker-model.scm +++ b/tui/liii/pi/tui/interactive/worker-model.scm @@ -19,8 +19,11 @@ (liii pi ai models route) (liii pi code config) ) ;import - (export pi-make-effective-cfg-box pi-effective-cfg-ref pi-effective-cfg-set! - pi-worker-make-prepare-request pi-worker-apply-selection + (export pi-make-effective-cfg-box + pi-effective-cfg-ref + pi-effective-cfg-set! + pi-worker-make-prepare-request + pi-worker-apply-selection ;; worker 线程重新求值调用链上的助手须导出 pi-worker-merge-model ) ;export diff --git a/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm b/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm index 8d170c24..212ef035 100644 --- a/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm +++ b/tui/tests/liii/pi/tui/interactive/worker-model/pi-worker-merge-model-test.scm @@ -81,8 +81,9 @@ ;; 3. 会话中途 /login:初始无 kimi 凭据(无钩子),auth.json 落盘 oauth ;; 凭据后同 provider 切模必须补注入钩子(不走 augment 的路径) -(let ((no-kimi-dir (path->string (path-join (path-temp-dir) "pi-worker-merge-model-login-test"))) - ) ; +(let ((no-kimi-dir (path->string (path-join (path-temp-dir) "pi-worker-merge-model-login-test")) + ) ;no-kimi-dir + ) ; (when (file-exists? no-kimi-dir) (rmtree no-kimi-dir) ) ;when