agent-gear 2.22.0 → 2.24.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.
package/src/acp/bridge.ts CHANGED
@@ -12,6 +12,10 @@ import { withSpan } from '../observability/trace.js';
12
12
 
13
13
  const ACP_PROTOCOL_VERSION = 1;
14
14
 
15
+ /** 问询/授权兜底超时 = controller-api 权威超时 + 5s race 余量(提问 30 分钟 / 权限审批 15 分钟) */
16
+ const ELICITATION_FALLBACK_TIMEOUT_MS = 1_805_000;
17
+ const PERMISSION_FALLBACK_TIMEOUT_MS = 905_000;
18
+
15
19
  /** 初始 mode/model 应用后回读确认失败时的重试间隔 */
16
20
  const INITIAL_CONFIG_RETRY_DELAY_MS = 300;
17
21
 
@@ -418,7 +422,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
418
422
  this.activePrompt = null;
419
423
  this.inputQueue = [];
420
424
  // 会话关闭:所有在途问询/授权必须先同步收敛(在 cancel/closeSession 的 5s race 之前),
421
- // 否则 race 窗口内 65s timer 仍可能迟到发 timeout。
425
+ // 否则 race 窗口内 1805s/905s timer 仍可能迟到发 timeout。
422
426
  this.settlePendingRequests('session stopped by user');
423
427
  this.clearPendingInitialConfig();
424
428
  let stopTimer: ReturnType<typeof setTimeout> | undefined;
@@ -442,7 +446,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
442
446
 
443
447
  /**
444
448
  * 清空 pending 请求:clearTimeout + resolve(cancel) + delete。
445
- * 问询额外回发 resolved(cancelled),让服务端待办收敛为 cancelled 而不是等 65s 超时误标 expired。
449
+ * 问询额外回发 resolved(cancelled),让服务端待办收敛为 cancelled 而不是等 1805s 超时误标 expired。
446
450
  * 同时发出 settled 事件,供 socketio-client 清理 requestId → bridge 映射(避免 Map 单调增长/阻止 GC)。
447
451
  */
448
452
  private settlePendingRequests(detail: string): void {
@@ -979,7 +983,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
979
983
  this.pendingPermissions.delete(requestId);
980
984
  this.emit('permission:settled', requestId);
981
985
  resolve({ outcome: { outcome: 'cancelled' } });
982
- }, 65_000);
986
+ }, PERMISSION_FALLBACK_TIMEOUT_MS);
983
987
 
984
988
  this.pendingPermissions.set(requestId, { resolve, timeout });
985
989
 
@@ -1045,16 +1049,16 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1045
1049
  requestId,
1046
1050
  ...(pending?.elicitationId ? { elicitationId: pending.elicitationId } : {}),
1047
1051
  },
1048
- 'elicitation timed out after 65s, auto-cancelling',
1052
+ 'elicitation timed out after 1805s, auto-cancelling',
1049
1053
  );
1050
1054
  this.socket.emit('acp:elicitation:resolved', {
1051
1055
  requestId,
1052
1056
  sessionId: this.sessionId,
1053
1057
  reason: 'timeout',
1054
- detail: 'bridge timeout (65s)',
1058
+ detail: 'bridge timeout (1805s)',
1055
1059
  });
1056
1060
  resolve({ action: 'cancel' });
1057
- }, 65_000);
1061
+ }, ELICITATION_FALLBACK_TIMEOUT_MS);
1058
1062
 
1059
1063
  this.pendingElicitations.set(requestId, {
1060
1064
  resolve,
@@ -1124,7 +1128,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1124
1128
  elicitationId: params.elicitationId,
1125
1129
  });
1126
1130
 
1127
- // Agent 自行完成/取消:对匹配的 pending 就地收敛,避免悬挂到 65s 被误标 expired。
1131
+ // Agent 自行完成/取消:对匹配的 pending 就地收敛,避免悬挂到 1805s 被误标 expired。
1128
1132
  // 契约 reason:'cancelled' 的产生路径之一(另一处为会话关闭 settle)。
1129
1133
  const entry = [...this.pendingElicitations.entries()]
1130
1134
  .find(([, pending]) => pending.elicitationId === params.elicitationId);
@@ -1205,7 +1209,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1205
1209
  );
1206
1210
  const wasStopped = this.stopped || this.silentStop;
1207
1211
  this.stopped = true;
1208
- // 进程崩溃同样必须收敛 pending:否则 65s timer 泄漏且迟发 timeout 事件
1212
+ // 进程崩溃同样必须收敛 pending:否则 1805s timer 泄漏且迟发 timeout 事件
1209
1213
  this.settlePendingRequests('session failed');
1210
1214
  this.clearPendingInitialConfig();
1211
1215
  // 已停止(含 silent 替换/对账)后迟到的初始化失败:不得再发 stopped,
@@ -125,7 +125,7 @@ export class AcpSpawner {
125
125
 
126
126
  this.process.on('error', (error) => {
127
127
  this.log.error({ event: 'acp_process_error', command: cmd, err: error }, 'acp process error');
128
- // spawn 失败同样视为进程终止:必须 resolve closed,让 bridge 收敛 pending,避免 65s 迟到 timeout
128
+ // spawn 失败同样视为进程终止:必须 resolve closed,让 bridge 收敛 pending,避免 1805s(提问)/905s(权限审批)迟到 timeout
129
129
  this.process = null;
130
130
  this.resolveClosed?.();
131
131
  });
@@ -12,6 +12,7 @@ import {
12
12
  let root: string;
13
13
  let zagDir: string;
14
14
  let docsDir: string;
15
+ let docsRoot: string;
15
16
 
16
17
  async function makeKb(sourceDir: string, folder: string, schema = '{"name":"kb"}') {
17
18
  const dir = join(sourceDir, folder);
@@ -24,6 +25,7 @@ beforeEach(async () => {
24
25
  root = await mkdtemp(join(tmpdir(), 'rkb-scan-'));
25
26
  zagDir = join(root, '.zag', 'knowledges');
26
27
  docsDir = join(root, 'docs', 'knowledges');
28
+ docsRoot = join(root, 'docs');
27
29
  await mkdir(zagDir, { recursive: true });
28
30
  await mkdir(docsDir, { recursive: true });
29
31
  });
@@ -43,7 +45,7 @@ describe('scanKnowledgeBases', () => {
43
45
  const result = await scanKnowledgeBases(root);
44
46
 
45
47
  expect(result.success).toBe(true);
46
- expect(result.sources.map((item) => item.source)).toEqual(['zag', 'docs']);
48
+ expect(result.sources.map((item) => item.source)).toEqual(['zag', 'docs', 'docs-root']);
47
49
  expect(result.sources[0].knowledgeBases.map((item) => item.folder)).toEqual(['a']);
48
50
  expect(result.sources[1].knowledgeBases.map((item) => item.folder)).toEqual(['b']);
49
51
  expect(result.sources[0].knowledgeBases[0].schema).toBe('{"name":"A"}');
@@ -100,6 +102,7 @@ describe('scanKnowledgeBases', () => {
100
102
  sources: [
101
103
  { source: 'zag', knowledgeBases: [], truncated: false },
102
104
  { source: 'docs', knowledgeBases: [], truncated: false },
105
+ { source: 'docs-root', knowledgeBases: [], truncated: false },
103
106
  ],
104
107
  truncated: false,
105
108
  });
@@ -234,6 +237,104 @@ describe('scanKnowledgeBases', () => {
234
237
  expect(result.truncated).toBe(true);
235
238
  });
236
239
 
240
+ it('T-RKB3-SCAN1 docs 一层文件夹含 knowledge-base.json → 第三来源识别,文档路径正确', async () => {
241
+ const kb = await makeKb(docsRoot, 'guides', '{"name":"指南"}');
242
+ await writeFile(join(kb, 'intro.md'), '# 简介');
243
+ await mkdir(join(kb, 'api'), { recursive: true });
244
+ await writeFile(join(kb, 'api', 'rest.md'), '# REST');
245
+
246
+ const result = await scanKnowledgeBases(root);
247
+ const source = result.sources.find((item) => item.source === 'docs-root');
248
+
249
+ expect(source?.knowledgeBases.map((item) => item.folder)).toEqual(['guides']);
250
+ expect(source?.knowledgeBases[0].schema).toBe('{"name":"指南"}');
251
+ expect(source?.knowledgeBases[0].documents?.map((doc) => doc.path)).toEqual([
252
+ 'api/rest.md',
253
+ 'intro.md',
254
+ ]);
255
+ });
256
+
257
+ it('T-RKB3-SCAN2 三来源同名文件夹互不覆盖,来源顺序固定', async () => {
258
+ await makeKb(zagDir, 'same', '{"name":"ZAG 库"}');
259
+ await makeKb(docsDir, 'same', '{"name":"DOCS 库"}');
260
+ await makeKb(docsRoot, 'same', '{"name":"DOCS_ROOT 库"}');
261
+
262
+ const result = await scanKnowledgeBases(root);
263
+
264
+ expect(result.sources.map((item) => item.source)).toEqual(['zag', 'docs', 'docs-root']);
265
+ expect(result.sources.map((item) => item.knowledgeBases[0]?.schema)).toEqual([
266
+ '{"name":"ZAG 库"}',
267
+ '{"name":"DOCS 库"}',
268
+ '{"name":"DOCS_ROOT 库"}',
269
+ ]);
270
+ });
271
+
272
+ it('T-RKB3-SCAN3 docs/knowledges 容器本身不被识别;其子文件夹仍属 docs 来源', async () => {
273
+ // 容器目录直接含 knowledge-base.json:docs-root 必须跳过
274
+ await writeFile(join(docsRoot, 'knowledges', 'knowledge-base.json'), '{"name":"容器"}', 'utf8');
275
+ await makeKb(docsDir, 'child', '{"name":"子库"}');
276
+ await makeKb(docsRoot, 'guides', '{"name":"指南"}');
277
+
278
+ const result = await scanKnowledgeBases(root);
279
+ const docsSource = result.sources.find((item) => item.source === 'docs');
280
+ const docsRootSource = result.sources.find((item) => item.source === 'docs-root');
281
+
282
+ expect(docsSource?.knowledgeBases.map((item) => item.folder)).toEqual(['child']);
283
+ expect(docsRootSource?.knowledgeBases.map((item) => item.folder)).toEqual(['guides']);
284
+ });
285
+
286
+ it('T-RKB3-SCAN4 docs 深层嵌套 knowledge-base.json 不识别(发现不递归)', async () => {
287
+ const nested = join(docsRoot, 'outer', 'inner');
288
+ await mkdir(nested, { recursive: true });
289
+ await writeFile(join(nested, 'knowledge-base.json'), '{"name":"inner"}', 'utf8');
290
+
291
+ const result = await scanKnowledgeBases(root);
292
+ const source = result.sources.find((item) => item.source === 'docs-root');
293
+
294
+ expect(source?.knowledgeBases).toEqual([]);
295
+ });
296
+
297
+ it('T-RKB3-SCAN5 docs 目录不存在 → 第三来源空列表;子项 >1000 → 来源截断', async () => {
298
+ const emptyRoot = await mkdtemp(join(tmpdir(), 'rkb-docs-root-empty-'));
299
+ const empty = await scanKnowledgeBases(emptyRoot);
300
+ expect(empty.sources.find((item) => item.source === 'docs-root')).toEqual({
301
+ source: 'docs-root',
302
+ knowledgeBases: [],
303
+ truncated: false,
304
+ });
305
+ await rm(emptyRoot, { recursive: true, force: true });
306
+
307
+ for (let i = 0; i <= MAX_ENTRIES_PER_FOLDER; i += 1) {
308
+ await makeKb(docsRoot, `kb${String(i).padStart(4, '0')}`);
309
+ }
310
+ const result = await scanKnowledgeBases(root);
311
+ const source = result.sources.find((item) => item.source === 'docs-root');
312
+ expect(source?.knowledgeBases).toHaveLength(MAX_ENTRIES_PER_FOLDER);
313
+ expect(source?.truncated).toBe(true);
314
+ expect(result.truncated).toBe(true);
315
+ });
316
+
317
+ it('T-RKB3-SCAN6 docs-root 单文件上限:schema 超限整库 error、单文档超限逐条 error', async () => {
318
+ const badSchema = join(docsRoot, 'bad-schema');
319
+ await mkdir(badSchema, { recursive: true });
320
+ await writeFile(join(badSchema, 'knowledge-base.json'), 'x'.repeat(MAX_FILE_BYTES + 1));
321
+ const mixed = await makeKb(docsRoot, 'mixed', '{"name":"混合"}');
322
+ await writeFile(join(mixed, 'big.md'), 'x'.repeat(MAX_FILE_BYTES + 1));
323
+ await writeFile(join(mixed, 'ok.md'), '# ok');
324
+
325
+ const result = await scanKnowledgeBases(root);
326
+ const source = result.sources.find((item) => item.source === 'docs-root');
327
+ const bad = source?.knowledgeBases.find((item) => item.folder === 'bad-schema');
328
+ const entry = source?.knowledgeBases.find((item) => item.folder === 'mixed');
329
+
330
+ expect(bad).toEqual({ folder: 'bad-schema', error: 'file too large' });
331
+ expect(entry?.documents?.find((doc) => doc.path === 'big.md')).toEqual({
332
+ path: 'big.md',
333
+ error: 'file too large',
334
+ });
335
+ expect(entry?.documents?.find((doc) => doc.path === 'ok.md')?.content).toBe('# ok');
336
+ });
337
+
237
338
  it('T-RKB-SCAN8 符号链接:指向常规 .md 文件读取;指向目录/悬空跳过', async () => {
238
339
  const kb = await makeKb(zagDir, 'kb');
239
340
  await writeFile(join(kb, 'real.md'), '# real');
@@ -254,10 +355,11 @@ describe('scanKnowledgeBases', () => {
254
355
  });
255
356
 
256
357
  describe('REPO_KNOWLEDGE_BASE_SOURCES', () => {
257
- it('两个固定约定目录', () => {
358
+ it('三个来源(zag / docs / docs-root,docs-root 跳过 knowledges 容器)', () => {
258
359
  expect(REPO_KNOWLEDGE_BASE_SOURCES).toEqual([
259
360
  { source: 'zag', subdir: '.zag/knowledges' },
260
361
  { source: 'docs', subdir: 'docs/knowledges' },
362
+ { source: 'docs-root', subdir: 'docs', excludeFolders: ['knowledges'] },
261
363
  ]);
262
364
  });
263
365
  });
@@ -4,8 +4,9 @@ import { join, resolve, sep } from 'node:path';
4
4
  /**
5
5
  * 项目仓库内建知识库扫描(契约 agent-session-websocket.md §3.29/§3.30)。
6
6
  *
7
- * 仓库为知识库唯一事实源:仅直读 `<workspacePath>/.zag/knowledges/` 与
8
- * `<workspacePath>/docs/knowledges/` 两个固定子目录。知识库发现不递归(仅直接子文件夹,
7
+ * 仓库为知识库唯一事实源:仅直读 `<workspacePath>/.zag/knowledges/`、
8
+ * `<workspacePath>/docs/knowledges/` 与 `<workspacePath>/docs/` 的一层文件夹(来源 `docs-root`,
9
+ * 跳过 `docs/knowledges` 容器)。知识库发现不递归(仅直接子文件夹,
9
10
  * 含常规文件 `knowledge-base.json` 即识别),库内文档递归收集 `.md` 常规文件并读取内容。
10
11
  * 仅读不写、不执行;不使用会话路径白名单。
11
12
  *
@@ -17,6 +18,8 @@ import { join, resolve, sep } from 'node:path';
17
18
  export const REPO_KNOWLEDGE_BASE_SOURCES = [
18
19
  { source: 'zag', subdir: '.zag/knowledges' },
19
20
  { source: 'docs', subdir: 'docs/knowledges' },
21
+ // 仓库 docs/ 的一层文件夹(跳过既有 docs/knowledges 容器目录)
22
+ { source: 'docs-root', subdir: 'docs', excludeFolders: ['knowledges'] },
20
23
  ] as const;
21
24
 
22
25
  export type RepoKnowledgeBaseSource = (typeof REPO_KNOWLEDGE_BASE_SOURCES)[number]['source'];
@@ -195,6 +198,7 @@ async function scanSource(
195
198
  workspacePath: string,
196
199
  source: RepoKnowledgeBaseSource,
197
200
  subdir: string,
201
+ excludeFolders: readonly string[] = [],
198
202
  ): Promise<KnowledgeBaseSourceResult | null> {
199
203
  const sourceDir = resolve(workspacePath, subdir);
200
204
 
@@ -221,6 +225,8 @@ async function scanSource(
221
225
 
222
226
  const folders: string[] = [];
223
227
  for (const entry of ordered) {
228
+ // 已知容器目录(docs-root 的 docs/knowledges):不参与知识库发现
229
+ if (excludeFolders.includes(entry.name)) continue;
224
230
  if (entry.isDirectory()) {
225
231
  folders.push(entry.name);
226
232
  continue;
@@ -258,7 +264,12 @@ export async function scanKnowledgeBases(
258
264
  ): Promise<KnowledgeBaseScanResult> {
259
265
  const sources: KnowledgeBaseSourceResult[] = [];
260
266
  for (const item of REPO_KNOWLEDGE_BASE_SOURCES) {
261
- const result = await scanSource(workspacePath, item.source, item.subdir);
267
+ const result = await scanSource(
268
+ workspacePath,
269
+ item.source,
270
+ item.subdir,
271
+ 'excludeFolders' in item ? item.excludeFolders : [],
272
+ );
262
273
  if (!result) {
263
274
  return { success: false, sources: [], truncated: false, error: 'permission denied' };
264
275
  }
@@ -683,6 +683,7 @@ describe('knowledge-bases:scan 事件注册(契约 §3.29/§3.30)', () => {
683
683
  truncated: false,
684
684
  },
685
685
  { source: 'docs', knowledgeBases: [], truncated: false },
686
+ { source: 'docs-root', knowledgeBases: [], truncated: false },
686
687
  ],
687
688
  truncated: false,
688
689
  });
@@ -31,6 +31,7 @@ import { logger as rootLogger, type ObservationLogger } from './observability/lo
31
31
  import { injectTraceparent, withSpan } from './observability/trace.js';
32
32
 
33
33
  // 版本号唯一事实源为 package.json(register 上报的完整版本;服务端按 MIN_WORKER_VERSION=2.2.0 门禁)。
34
+ // 2.23.0 起仓库知识库扫描新增第三来源 `docs-root`(docs 一层文件夹,跳过 knowledges 容器);
34
35
  // 2.8.0 起 `kimi_code` 使用前登录闸门(`kimi login` stdio 判定 + `harness:login:*` 事件族);
35
36
  // 2.6.0 起支持 `workload:run.githubAuth` 与云电脑 Github 凭据管理器(该能力自 2.10.0 起,当前 harness 基线 MIN_HARNESS_WORKER_VERSION=2.12.0);
36
37
  // 2.5.0 起支持云电脑双连接(`/worker` + controller-api)与 `harness prepare`。
@@ -1621,7 +1622,7 @@ export function connectToServer(
1621
1622
  socket.emit('workflow-templates:scan:result', { requestId: data.requestId, ...result });
1622
1623
  });
1623
1624
 
1624
- // 仓库内建知识库扫描(契约 §3.29/§3.30:两个约定子目录 + knowledge-base.json + 分级上限)
1625
+ // 仓库内建知识库扫描(契约 §3.29/§3.30:三个来源 + knowledge-base.json + 分级上限)
1625
1626
  socket.on('knowledge-bases:scan', async (data: { requestId: string; path: string }) => {
1626
1627
  log.info(
1627
1628
  { event: 'knowledge_bases_scan', requestId: data.requestId, path: data.path },
@@ -1806,7 +1807,7 @@ export function connectToServer(
1806
1807
  heartbeat.stop();
1807
1808
  gatewayManager.closeAll();
1808
1809
  // 断线后 pending 计时器必须就地收敛:socket.io 会缓存断线期间 emit,
1809
- // 不收敛会在重连后补发 65s timeout(待办被误标 expired)。
1810
+ // 不收敛会在重连后补发 1805s(提问)/905s(权限审批)timeout(待办被误标 expired)。
1810
1811
  for (const bridge of acpBridges.values()) {
1811
1812
  bridge.settlePendingOnDisconnect();
1812
1813
  }
@@ -519,7 +519,7 @@ describe('AcpSessionBridge', () => {
519
519
  expect(result).toEqual({ outcome: { outcome: 'selected', optionId: 'opt-1' } });
520
520
  });
521
521
 
522
- it('should resolve with cancelled on 65s timeout', async () => {
522
+ it('should resolve with cancelled on 905s timeout', async () => {
523
523
  const bridge = createBridge();
524
524
 
525
525
  const promise = bridge.requestPermission({
@@ -527,7 +527,7 @@ describe('AcpSessionBridge', () => {
527
527
  toolCall: { toolCallId: 'tc-1' },
528
528
  } as never);
529
529
 
530
- await vi.advanceTimersByTimeAsync(65_000);
530
+ await vi.advanceTimersByTimeAsync(905_000);
531
531
 
532
532
  const result = await promise;
533
533
  expect(result).toEqual({ outcome: { outcome: 'cancelled' } });
@@ -609,7 +609,7 @@ describe('AcpSessionBridge', () => {
609
609
  expect(mockSocket.emit).not.toHaveBeenCalledWith('acp:elicitation', expect.anything());
610
610
  });
611
611
 
612
- it('65s 超时自动 resolve cancel', async () => {
612
+ it('1805s 超时自动 resolve cancel', async () => {
613
613
  const bridge = createBridge();
614
614
 
615
615
  const promise = bridge.unstable_createElicitation({
@@ -619,7 +619,7 @@ describe('AcpSessionBridge', () => {
619
619
  requestedSchema: { type: 'object' },
620
620
  } as never);
621
621
 
622
- await vi.advanceTimersByTimeAsync(65_000);
622
+ await vi.advanceTimersByTimeAsync(1_805_000);
623
623
 
624
624
  const result = await promise;
625
625
  expect(result).toEqual({ action: 'cancel' });
@@ -13,7 +13,8 @@
13
13
  * 用法(在 packages/agent-controller 目录):
14
14
  * npx tsx tests/manual/repro-question-tool.ts <policy> [prompt]
15
15
  *
16
- * policy = none 不响应问询(观测 65s bridge 超时后的工具结果)
16
+ * policy = none 不响应问询(观测提问兜底超时后的工具结果;bridge 兜底为 1805s,
17
+ * 需等待约 30 分钟,脚本定时器留 15s 余量)
17
18
  * accept 收到问询立即 accept(对照组:question 工具应 completed)
18
19
  * decline 收到问询立即 decline
19
20
  * cancel 收到问询立即 cancel(秒级复现 "dismissed")
@@ -97,8 +98,12 @@ async function main(): Promise<void> {
97
98
  log('prompt sent');
98
99
 
99
100
  await new Promise<void>((resolve) => {
100
- // 65s bridge 超时 + 余量
101
- const timer = setTimeout(() => { log('TIMEOUT 100s'); resolve(); }, 100_000);
101
+ // 提问 bridge 兜底 1805s(30 分钟 5 秒,= controller-api 权威 1800s + 5s race 余量)+ 15s 余量
102
+ const BRIDGE_ELICITATION_FALLBACK_MS = 1_805_000;
103
+ const timer = setTimeout(() => {
104
+ log('TIMEOUT 1820s(未观测到 bridge timeout,请检查策略/进程)');
105
+ resolve();
106
+ }, BRIDGE_ELICITATION_FALLBACK_MS + 15_000);
102
107
  bridge.on('acp:stopped', () => {
103
108
  log('bridge stopped');
104
109
  clearTimeout(timer);