agent-gear 2.23.0 → 2.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENTS.md +45 -13
  2. package/dist/acp/auth-gate.d.ts +35 -19
  3. package/dist/acp/auth-gate.d.ts.map +1 -1
  4. package/dist/acp/auth-gate.js +59 -41
  5. package/dist/acp/auth-gate.js.map +1 -1
  6. package/dist/acp/auth-gate.test.js +53 -56
  7. package/dist/acp/auth-gate.test.js.map +1 -1
  8. package/dist/acp/bridge.d.ts +13 -3
  9. package/dist/acp/bridge.d.ts.map +1 -1
  10. package/dist/acp/bridge.js +61 -18
  11. package/dist/acp/bridge.js.map +1 -1
  12. package/dist/acp/bridge.test.js +134 -20
  13. package/dist/acp/bridge.test.js.map +1 -1
  14. package/dist/acp/capabilities.d.ts.map +1 -1
  15. package/dist/acp/capabilities.js +2 -4
  16. package/dist/acp/capabilities.js.map +1 -1
  17. package/dist/acp/capabilities.test.js +2 -2
  18. package/dist/acp/capabilities.test.js.map +1 -1
  19. package/dist/acp/spawner.js +1 -1
  20. package/dist/acp/spawner.js.map +1 -1
  21. package/dist/acp/sync-bridge.d.ts.map +1 -1
  22. package/dist/acp/sync-bridge.js +2 -1
  23. package/dist/acp/sync-bridge.js.map +1 -1
  24. package/dist/harness/kimi-login.d.ts +44 -3
  25. package/dist/harness/kimi-login.d.ts.map +1 -1
  26. package/dist/harness/kimi-login.js +133 -4
  27. package/dist/harness/kimi-login.js.map +1 -1
  28. package/dist/harness/kimi-login.test.js +54 -1
  29. package/dist/harness/kimi-login.test.js.map +1 -1
  30. package/dist/socketio-client.auth-gate.test.js +48 -60
  31. package/dist/socketio-client.auth-gate.test.js.map +1 -1
  32. package/dist/socketio-client.d.ts.map +1 -1
  33. package/dist/socketio-client.js +80 -11
  34. package/dist/socketio-client.js.map +1 -1
  35. package/dist/version.d.ts +9 -0
  36. package/dist/version.d.ts.map +1 -0
  37. package/dist/version.js +10 -0
  38. package/dist/version.js.map +1 -0
  39. package/dist/version.test.d.ts +2 -0
  40. package/dist/version.test.d.ts.map +1 -0
  41. package/dist/version.test.js +27 -0
  42. package/dist/version.test.js.map +1 -0
  43. package/dist/worktree-handler.test.js +26 -0
  44. package/dist/worktree-handler.test.js.map +1 -1
  45. package/package.json +1 -1
  46. package/src/acp/auth-gate.test.ts +55 -58
  47. package/src/acp/auth-gate.ts +73 -43
  48. package/src/acp/bridge.test.ts +158 -20
  49. package/src/acp/bridge.ts +69 -18
  50. package/src/acp/capabilities.test.ts +2 -2
  51. package/src/acp/capabilities.ts +2 -4
  52. package/src/acp/spawner.ts +1 -1
  53. package/src/acp/sync-bridge.ts +2 -1
  54. package/src/harness/kimi-login.test.ts +60 -0
  55. package/src/harness/kimi-login.ts +149 -4
  56. package/src/socketio-client.auth-gate.test.ts +49 -60
  57. package/src/socketio-client.ts +98 -13
  58. package/src/version.test.ts +36 -0
  59. package/src/version.ts +13 -0
  60. package/src/worktree-handler.test.ts +31 -0
  61. package/tests/acp-bridge.test.ts +36 -5
  62. package/tests/acp-sync-bridge.test.ts +17 -1
  63. package/tests/manual/repro-question-tool.ts +8 -3
  64. package/tests/socketio-client.test.ts +138 -0
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi } from 'vitest';
2
- import { AcpAuthGate, AuthRequiredError } from './auth-gate.js';
2
+ import { AcpAuthGate } from './auth-gate.js';
3
3
  import type { KimiLoginHandlers, KimiLoginTerminal } from '../harness/kimi-login.js';
4
4
  import type { KimiLoginFlowLike } from './auth-gate.js';
5
5
 
@@ -27,10 +27,10 @@ function createFakeFlow(): FakeFlow {
27
27
  };
28
28
  }
29
29
 
30
- function setup(options: { cacheTtlMs?: number; now?: () => number } = {}) {
30
+ function setup(options: { loggedIn?: () => Promise<boolean> } = {}) {
31
31
  const flows: FakeFlow[] = [];
32
32
  const emitted: Array<{ event: string; payload: Record<string, unknown> }> = [];
33
- let seq = 0;
33
+ const logoutRun = vi.fn(async () => ({ success: true, usedFallback: false }));
34
34
  const gate = new AcpAuthGate({
35
35
  emit: (event, payload) => emitted.push({ event, payload }),
36
36
  createFlow: () => {
@@ -38,108 +38,105 @@ function setup(options: { cacheTtlMs?: number; now?: () => number } = {}) {
38
38
  flows.push(flow);
39
39
  return flow as unknown as KimiLoginFlowLike;
40
40
  },
41
- createRequestId: () => `req-${++seq}`,
42
- ...(options.cacheTtlMs != null ? { cacheTtlMs: options.cacheTtlMs } : {}),
43
- ...(options.now ? { now: options.now } : {}),
41
+ createLogoutFlow: () => ({ run: logoutRun }),
42
+ isLoggedIn: options.loggedIn ?? (async () => false),
44
43
  });
45
- return { gate, flows, emitted };
44
+ return { gate, flows, emitted, logoutRun };
46
45
  }
47
46
 
48
47
  const DEVICE_FLOW = { url: 'https://kimi.test/login', userCode: 'CODE-1', expiresInSeconds: 1800 };
49
48
 
50
- describe('AcpAuthGate', () => {
51
- it('T-AG1: 非 kimi_code 立即 resolve,不创建流程、不发事件', async () => {
49
+ describe('AcpAuthGate(2.26.0 设置项主动发起)', () => {
50
+ it('T-AG1: 非 kimi_code 视为已登录,不创建流程、不发事件', async () => {
52
51
  const { gate, flows, emitted } = setup();
52
+ await expect(gate.isLoggedIn('opencode')).resolves.toBe(true);
53
53
  await expect(gate.ensure('opencode', 'acp:start')).resolves.toBeUndefined();
54
+ await expect(gate.logout('opencode')).resolves.toEqual({ success: true, usedFallback: false });
54
55
  expect(flows).toHaveLength(0);
55
56
  expect(emitted).toHaveLength(0);
56
57
  });
57
58
 
58
- it('T-AG2/AG3: 缓存命中不重复登录,TTL 过期后重新登录', async () => {
59
- let now = 1_000;
60
- const { gate, flows } = setup({ cacheTtlMs: 100, now: () => now });
61
- const first = gate.ensure('kimi_code', 'probe-options');
62
- await Promise.resolve();
63
- flows[0].handlers().onDeviceFlow?.(DEVICE_FLOW);
64
- flows[0].finish({ state: 'logged-in', account: 'managed:kimi-code' });
65
- await first;
66
-
59
+ it('T-AG2: 使用动作前只探测(未登录也不发起登录、不抛错)', async () => {
60
+ const probe = vi.fn(async () => false);
61
+ const { gate, flows, emitted } = setup({ loggedIn: probe });
62
+ await expect(gate.ensure('kimi_code', 'probe-options')).resolves.toBeUndefined();
67
63
  await expect(gate.ensure('kimi_code', 'acp:start')).resolves.toBeUndefined();
68
- expect(flows).toHaveLength(1);
64
+ await expect(gate.ensure('kimi_code', 'acp:resume')).resolves.toBeUndefined();
65
+ expect(probe).toHaveBeenCalledTimes(3);
66
+ expect(flows).toHaveLength(0);
67
+ expect(emitted).toHaveLength(0);
68
+ });
69
69
 
70
- now += 101;
71
- const second = gate.ensure('kimi_code', 'acp:start');
72
- await Promise.resolve();
73
- expect(flows).toHaveLength(2);
74
- flows[1].finish({ state: 'logged-in' });
75
- await second;
70
+ it('T-AG3: 探测异常保守视为未登录,不抛错', async () => {
71
+ const { gate } = setup({
72
+ loggedIn: async () => {
73
+ throw new Error('stat failed');
74
+ },
75
+ });
76
+ await expect(gate.isLoggedIn('kimi_code')).resolves.toBe(false);
77
+ await expect(gate.ensure('kimi_code', 'acp:start')).resolves.toBeUndefined();
76
78
  });
77
79
 
78
- it('T-AG4: 并发 3 次 ensure → 只 1 次 spawn、1 次 required、3 个 resolve', async () => {
80
+ it('T-AG4: startLogin 上行 required/succeeded,requestId 由服务端回带', async () => {
79
81
  const { gate, flows, emitted } = setup();
80
- const all = [
81
- gate.ensure('kimi_code', 'probe-options'),
82
- gate.ensure('kimi_code', 'acp:start'),
83
- gate.ensure('kimi_code', 'acp:resume'),
84
- ];
82
+ const pending = gate.startLogin('kimi_code', 'req-settings-1');
85
83
  await Promise.resolve();
86
84
  expect(flows).toHaveLength(1);
87
85
  flows[0].handlers().onDeviceFlow?.(DEVICE_FLOW);
88
- flows[0].finish({ state: 'logged-in' });
89
- await expect(Promise.all(all)).resolves.toEqual([undefined, undefined, undefined]);
90
- expect(emitted.filter((item) => item.event === 'harness:login:required')).toHaveLength(1);
86
+ flows[0].finish({ state: 'logged-in', account: 'managed:kimi-code' });
87
+ await expect(pending).resolves.toEqual({ state: 'logged-in', account: 'managed:kimi-code' });
88
+
91
89
  expect(emitted.map((item) => item.event)).toEqual([
92
90
  'harness:login:required',
93
91
  'harness:login:succeeded',
94
92
  ]);
95
93
  expect(emitted[0].payload).toEqual({
96
- requestId: 'req-1',
94
+ requestId: 'req-settings-1',
97
95
  serverType: 'kimi_code',
98
- trigger: 'probe-options',
96
+ trigger: 'settings',
99
97
  ...DEVICE_FLOW,
100
98
  });
99
+ expect(emitted[1].payload).toEqual({
100
+ requestId: 'req-settings-1',
101
+ account: 'managed:kimi-code',
102
+ });
103
+ expect(gate.pendingRequestId).toBeNull();
101
104
  });
102
105
 
103
- it('T-AG5: 失败 → 三次均 reject AuthRequiredError 并上行 failed', async () => {
106
+ it('T-AG5: startLogin 失败 → 上行 failed 并返回失败终态', async () => {
104
107
  const { gate, flows, emitted } = setup();
105
- const all = [
106
- gate.ensure('kimi_code', 'probe-options'),
107
- gate.ensure('kimi_code', 'acp:start'),
108
- gate.ensure('kimi_code', 'acp:resume'),
109
- ];
108
+ const pending = gate.startLogin('kimi_code', 'req-2');
110
109
  await Promise.resolve();
111
110
  flows[0].finish({ state: 'failed', reason: 'cancelled' });
112
- for (const promise of all) {
113
- await expect(promise).rejects.toBeInstanceOf(AuthRequiredError);
114
- await expect(promise).rejects.toThrow('Kimi Code 未登录');
115
- }
111
+ await expect(pending).resolves.toEqual({ state: 'failed', reason: 'cancelled' });
116
112
  expect(emitted.at(-1)).toEqual({
117
113
  event: 'harness:login:failed',
118
- payload: { requestId: 'req-1', reason: 'cancelled' },
114
+ payload: { requestId: 'req-2', reason: 'cancelled' },
119
115
  });
120
116
  });
121
117
 
122
118
  it('T-AG6: cancel 定向(其他 requestId 无效,当前生效)', async () => {
123
119
  const { gate, flows } = setup();
124
- const pending = gate.ensure('kimi_code', 'acp:start');
120
+ const pending = gate.startLogin('kimi_code', 'req-3');
125
121
  await Promise.resolve();
126
122
  gate.cancel('req-other');
127
123
  expect(flows[0].cancel).not.toHaveBeenCalled();
128
- gate.cancel('req-1');
124
+ gate.cancel('req-3');
129
125
  expect(flows[0].cancel).toHaveBeenCalledTimes(1);
130
126
  flows[0].finish({ state: 'failed', reason: 'cancelled' });
131
- await expect(pending).rejects.toBeInstanceOf(AuthRequiredError);
127
+ await pending;
132
128
  expect(gate.pendingRequestId).toBeNull();
133
129
  });
134
130
 
135
- it('T-AG7: 无 device-flow 且成功 → 仍写缓存(不误判)', async () => {
136
- const { gate, flows, emitted } = setup();
137
- const pending = gate.ensure('kimi_code', 'probe-options');
131
+ it('T-AG7: logout 成功后重置进程内状态', async () => {
132
+ const { gate, logoutRun } = setup();
133
+ const pending = gate.startLogin('kimi_code', 'req-4');
138
134
  await Promise.resolve();
139
- flows[0].finish({ state: 'logged-in' });
140
- await expect(pending).resolves.toBeUndefined();
141
- expect(emitted.map((item) => item.event)).toEqual(['harness:login:succeeded']);
142
- await expect(gate.ensure('kimi_code', 'acp:start')).resolves.toBeUndefined();
143
- expect(flows).toHaveLength(1);
135
+ expect(gate.pendingRequestId).toBe('req-4');
136
+ await expect(gate.logout('kimi_code')).resolves.toEqual({ success: true, usedFallback: false });
137
+ expect(logoutRun).toHaveBeenCalledTimes(1);
138
+ expect(gate.pendingRequestId).toBeNull();
139
+ // 结束挂起的登录 Promise,避免测试悬挂
140
+ void pending.catch(() => {});
144
141
  });
145
142
  });
@@ -1,14 +1,22 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { KimiLoginFlow, resolveKimiAuthCacheTtlMs, type KimiLoginHandlers, type KimiLoginTerminal } from '../harness/kimi-login.js';
2
+ import {
3
+ KimiLoginFlow,
4
+ KimiLogoutFlow,
5
+ detectKimiLoggedIn,
6
+ resolveKimiCredentialsDir,
7
+ type KimiLoginHandlers,
8
+ type KimiLoginTerminal,
9
+ type KimiLogoutResult,
10
+ } from '../harness/kimi-login.js';
3
11
 
4
12
  /** 本期唯一需要登录闸门的 harness 类型。 */
5
13
  export const KIMI_SERVER_TYPE = 'kimi_code';
6
14
  /** 统一失败文案(前端原样展示,不新增错误码)。 */
7
15
  export const AUTH_REQUIRED_MESSAGE = 'Kimi Code 未登录';
8
16
 
9
- export type AuthTrigger = 'probe-options' | 'acp:start' | 'acp:resume';
17
+ export type AuthTrigger = 'probe-options' | 'acp:start' | 'acp:resume' | 'settings';
10
18
 
11
- /** 使用动作因未登录失败(handler 据此在 result 上带 `reason:'auth'`)。 */
19
+ /** 使用动作因未登录失败(保留导出与文案;自 2.26.0 起使用动作不再抛出,仅按需提示)。 */
12
20
  export class AuthRequiredError extends Error {
13
21
  readonly reason = 'auth' as const;
14
22
  constructor(message: string = AUTH_REQUIRED_MESSAGE) {
@@ -37,37 +45,41 @@ export interface KimiLoginFlowLike {
37
45
 
38
46
  export interface AcpAuthGateOptions {
39
47
  emit?: HarnessLoginEmitter;
40
- /** 登录缓存 TTL(默认 KIMI_AUTH_CACHE_TTL_MS / 300000)。 */
41
- cacheTtlMs?: number;
42
- now?: () => number;
43
48
  createFlow?: () => KimiLoginFlowLike;
49
+ /** 登出流程(缺省 KimiLogoutFlow)。 */
50
+ createLogoutFlow?: () => { run(): Promise<KimiLogoutResult> };
51
+ /** 登录态探测(缺省读凭据目录 stat;测试注入)。 */
52
+ isLoggedIn?: () => Promise<boolean>;
44
53
  createRequestId?: () => string;
54
+ /** 凭据目录(缺省 `~/.kimi-code/credentials`)。 */
55
+ credentialsDir?: string;
45
56
  }
46
57
 
47
58
  /**
48
- * harness 使用前登录闸门(仅 `kimi_code`,其余 serverType 立即 resolve 零开销)。
59
+ * harness 登录闸门(仅 `kimi_code`,其余 serverType 立即 resolve 零开销)。
49
60
  *
50
- * 单进程 single-flight:同一时刻只有一个 `kimi login` 与一条 `required`;
51
- * 并发使用动作共享同一 Promise,登录成功后写入进程内 TTL 缓存(无 Redis 依赖)。
61
+ * 自 agent-gear 2.26.0 起「登录作为设置项主动操作」:
62
+ * - `ensure()` 只做**登录态探测 + 温和提示**,不再自动拉起 `kimi login`、不抛错不阻断使用动作;
63
+ * - `startLogin()` 供服务端 `harness:login:start` 主动发起(复用 `KimiLoginFlow` 设备码流程);
64
+ * - `logout()` 供 `harness:logout` 主动登出(`kimi logout` + 凭据目录回退删除);
65
+ * - 登录态判定 = 凭据目录 `*.json` 存在性(只 stat,不读取不解析),**无 TTL 过期语义**。
52
66
  */
53
67
  export class AcpAuthGate {
54
68
  private readonly emit: HarnessLoginEmitter;
55
- private readonly cacheTtlMs: number;
56
- private readonly now: () => number;
57
69
  private readonly createFlow: () => KimiLoginFlowLike;
70
+ private readonly createLogoutFlow: () => { run(): Promise<KimiLogoutResult> };
71
+ private readonly probe: () => Promise<boolean>;
58
72
  private readonly createRequestId: () => string;
59
73
 
60
- /** serverType → 缓存到期时间戳。 */
61
- private readonly cache = new Map<string, number>();
62
- private readonly inflight = new Map<string, Promise<void>>();
63
74
  private current: { requestId: string; flow: KimiLoginFlowLike } | null = null;
64
75
 
65
76
  constructor(options: AcpAuthGateOptions = {}) {
66
77
  this.emit = options.emit ?? (() => {});
67
- this.cacheTtlMs = options.cacheTtlMs ?? resolveKimiAuthCacheTtlMs();
68
- this.now = options.now ?? Date.now;
69
78
  this.createRequestId = options.createRequestId ?? randomUUID;
70
79
  this.createFlow = options.createFlow ?? (() => new KimiLoginFlow());
80
+ this.createLogoutFlow = options.createLogoutFlow ?? (() => new KimiLogoutFlow());
81
+ const credentialsDir = options.credentialsDir ?? resolveKimiCredentialsDir();
82
+ this.probe = options.isLoggedIn ?? (() => detectKimiLoggedIn(credentialsDir));
71
83
  }
72
84
 
73
85
  /** 当前进行中的登录 requestId(无登录流程时为 null;供日志/测试)。 */
@@ -75,34 +87,45 @@ export class AcpAuthGate {
75
87
  return this.current?.requestId ?? null;
76
88
  }
77
89
 
78
- /** 缓存命中/非 kimi_code 立即 resolve;否则走(或复用)登录流程。 */
79
- async ensure(serverType: string, trigger: AuthTrigger): Promise<void> {
80
- if (serverType !== KIMI_SERVER_TYPE) return;
81
- const expiresAt = this.cache.get(serverType);
82
- if (expiresAt !== undefined && this.now() < expiresAt) return;
83
- const existing = this.inflight.get(serverType);
84
- if (existing) return existing;
90
+ /** 登录态探测(不发起登录、不抛错)。 */
91
+ async isLoggedIn(serverType: string): Promise<boolean> {
92
+ if (serverType !== KIMI_SERVER_TYPE) return true;
93
+ try {
94
+ return await this.probe();
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
85
99
 
86
- const promise = this.runLogin(serverType, trigger).finally(() => {
87
- if (this.inflight.get(serverType) === promise) this.inflight.delete(serverType);
88
- });
89
- this.inflight.set(serverType, promise);
90
- return promise;
100
+ /**
101
+ * 使用动作前的温和探测(不再拦截):未登录只由调用方记录提示,不发起登录、不抛错。
102
+ * 返回值仅表示「是否已登录」,调用方不得据此阻断动作。
103
+ */
104
+ async ensure(serverType: string, _trigger: AuthTrigger): Promise<void> {
105
+ if (serverType !== KIMI_SERVER_TYPE) return;
106
+ await this.isLoggedIn(serverType);
91
107
  }
92
108
 
93
- private async runLogin(serverType: string, trigger: AuthTrigger): Promise<void> {
94
- const requestId = this.createRequestId();
109
+ /**
110
+ * 服务端 `harness:login:start`:主动发起设备码登录流程。
111
+ * 终态经 `harness:login:succeeded` / `harness:login:failed` 上行(requestId 原样回带)。
112
+ */
113
+ async startLogin(serverType: string, requestId?: string): Promise<KimiLoginTerminal> {
114
+ if (serverType !== KIMI_SERVER_TYPE) {
115
+ return { state: 'failed', reason: 'error', error: 'unsupported serverType' };
116
+ }
117
+ const id = requestId && requestId.length > 0 ? requestId : this.createRequestId();
95
118
  const flow = this.createFlow();
96
- this.current = { requestId, flow };
119
+ this.current = { requestId: id, flow };
97
120
 
98
121
  let outcome: KimiLoginTerminal;
99
122
  try {
100
123
  outcome = await flow.run({
101
124
  onDeviceFlow: ({ url, userCode, expiresInSeconds }) => {
102
125
  this.emit('harness:login:required', {
103
- requestId,
126
+ requestId: id,
104
127
  serverType: KIMI_SERVER_TYPE,
105
- trigger,
128
+ trigger: 'settings' satisfies AuthTrigger,
106
129
  url,
107
130
  userCode,
108
131
  expiresInSeconds,
@@ -110,35 +133,42 @@ export class AcpAuthGate {
110
133
  },
111
134
  });
112
135
  } finally {
113
- if (this.current?.requestId === requestId) this.current = null;
136
+ if (this.current?.requestId === id) this.current = null;
114
137
  }
115
138
 
116
139
  if (outcome.state === 'logged-in') {
117
- this.cache.set(serverType, this.now() + this.cacheTtlMs);
118
140
  this.emit('harness:login:succeeded', {
119
- requestId,
141
+ requestId: id,
120
142
  ...(outcome.account ? { account: outcome.account } : {}),
121
143
  });
122
- return;
144
+ return outcome;
123
145
  }
124
146
  this.emit('harness:login:failed', {
125
- requestId,
147
+ requestId: id,
126
148
  reason: outcome.reason,
127
149
  ...(outcome.error ? { error: outcome.error } : {}),
128
150
  });
129
- throw new AuthRequiredError();
151
+ return outcome;
152
+ }
153
+
154
+ /** 服务端 `harness:logout`:主动登出并重置进程内状态。 */
155
+ async logout(serverType: string): Promise<KimiLogoutResult> {
156
+ if (serverType !== KIMI_SERVER_TYPE) {
157
+ return { success: true, usedFallback: false };
158
+ }
159
+ const result = await this.createLogoutFlow().run();
160
+ if (result.success) this.reset();
161
+ return result;
130
162
  }
131
163
 
132
- /** 服务端 `harness:login:cancel` 下行:requestId 不匹配时忽略。 */
164
+ /** 执行中的登录 requestId 匹配时终止 `kimi login`。 */
133
165
  cancel(requestId: string): void {
134
166
  if (!requestId || this.current?.requestId !== requestId) return;
135
167
  this.current.flow.cancel();
136
168
  }
137
169
 
138
- /** 清空进程内登录状态(测试/调试用;不影响已登录凭证)。 */
170
+ /** 清空进程内登录流程状态(登出后/测试用;不影响已登录凭证)。 */
139
171
  reset(): void {
140
- this.cache.clear();
141
- this.inflight.clear();
142
172
  this.current = null;
143
173
  }
144
174
  }