agent-gear 2.4.0 → 2.6.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 (159) hide show
  1. package/AGENTS.md +108 -5
  2. package/dist/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  3. package/dist/acp/bridge.d.ts +23 -1
  4. package/dist/acp/bridge.d.ts.map +1 -1
  5. package/dist/acp/bridge.js +152 -17
  6. package/dist/acp/bridge.js.map +1 -1
  7. package/dist/acp/bridge.test.js +366 -1
  8. package/dist/acp/bridge.test.js.map +1 -1
  9. package/dist/acp/capabilities.d.ts +81 -0
  10. package/dist/acp/capabilities.d.ts.map +1 -0
  11. package/dist/acp/capabilities.js +211 -0
  12. package/dist/acp/capabilities.js.map +1 -0
  13. package/dist/acp/capabilities.test.d.ts +2 -0
  14. package/dist/acp/capabilities.test.d.ts.map +1 -0
  15. package/dist/acp/capabilities.test.js +156 -0
  16. package/dist/acp/capabilities.test.js.map +1 -0
  17. package/dist/acp/elicitation.integration.test.d.ts +2 -0
  18. package/dist/acp/elicitation.integration.test.d.ts.map +1 -0
  19. package/dist/acp/elicitation.integration.test.js +98 -0
  20. package/dist/acp/elicitation.integration.test.js.map +1 -0
  21. package/dist/acp/prober.d.ts +4 -0
  22. package/dist/acp/prober.d.ts.map +1 -1
  23. package/dist/acp/prober.js +1 -0
  24. package/dist/acp/prober.js.map +1 -1
  25. package/dist/acp/spawner.d.ts.map +1 -1
  26. package/dist/acp/spawner.js +3 -0
  27. package/dist/acp/spawner.js.map +1 -1
  28. package/dist/acp/sync-bridge.d.ts.map +1 -1
  29. package/dist/acp/sync-bridge.js +5 -1
  30. package/dist/acp/sync-bridge.js.map +1 -1
  31. package/dist/cloud-host/supervisor.d.ts +105 -0
  32. package/dist/cloud-host/supervisor.d.ts.map +1 -0
  33. package/dist/cloud-host/supervisor.js +237 -0
  34. package/dist/cloud-host/supervisor.js.map +1 -0
  35. package/dist/cloud-host/supervisor.test.d.ts +2 -0
  36. package/dist/cloud-host/supervisor.test.d.ts.map +1 -0
  37. package/dist/cloud-host/supervisor.test.js +367 -0
  38. package/dist/cloud-host/supervisor.test.js.map +1 -0
  39. package/dist/commands/harness.d.ts +17 -0
  40. package/dist/commands/harness.d.ts.map +1 -0
  41. package/dist/commands/harness.js +35 -0
  42. package/dist/commands/harness.js.map +1 -0
  43. package/dist/config.d.ts.map +1 -1
  44. package/dist/config.js +10 -3
  45. package/dist/config.js.map +1 -1
  46. package/dist/github/credential-manager.d.ts +70 -0
  47. package/dist/github/credential-manager.d.ts.map +1 -0
  48. package/dist/github/credential-manager.js +205 -0
  49. package/dist/github/credential-manager.js.map +1 -0
  50. package/dist/github/credential-manager.test.d.ts +2 -0
  51. package/dist/github/credential-manager.test.d.ts.map +1 -0
  52. package/dist/github/credential-manager.test.js +215 -0
  53. package/dist/github/credential-manager.test.js.map +1 -0
  54. package/dist/github/gh-config.d.ts +17 -0
  55. package/dist/github/gh-config.d.ts.map +1 -0
  56. package/dist/github/gh-config.js +68 -0
  57. package/dist/github/gh-config.js.map +1 -0
  58. package/dist/github/gh-config.test.d.ts +2 -0
  59. package/dist/github/gh-config.test.d.ts.map +1 -0
  60. package/dist/github/gh-config.test.js +90 -0
  61. package/dist/github/gh-config.test.js.map +1 -0
  62. package/dist/harness/env.d.ts +36 -0
  63. package/dist/harness/env.d.ts.map +1 -0
  64. package/dist/harness/env.js +78 -0
  65. package/dist/harness/env.js.map +1 -0
  66. package/dist/harness/env.test.d.ts +2 -0
  67. package/dist/harness/env.test.d.ts.map +1 -0
  68. package/dist/harness/env.test.js +70 -0
  69. package/dist/harness/env.test.js.map +1 -0
  70. package/dist/harness/opencode-cli.d.ts +24 -0
  71. package/dist/harness/opencode-cli.d.ts.map +1 -0
  72. package/dist/harness/opencode-cli.js +74 -0
  73. package/dist/harness/opencode-cli.js.map +1 -0
  74. package/dist/harness/opencode-cli.test.d.ts +2 -0
  75. package/dist/harness/opencode-cli.test.d.ts.map +1 -0
  76. package/dist/harness/opencode-cli.test.js +62 -0
  77. package/dist/harness/opencode-cli.test.js.map +1 -0
  78. package/dist/harness/opencode-config.atomic-failure.test.d.ts +2 -0
  79. package/dist/harness/opencode-config.atomic-failure.test.d.ts.map +1 -0
  80. package/dist/harness/opencode-config.atomic-failure.test.js +35 -0
  81. package/dist/harness/opencode-config.atomic-failure.test.js.map +1 -0
  82. package/dist/harness/opencode-config.d.ts +54 -0
  83. package/dist/harness/opencode-config.d.ts.map +1 -0
  84. package/dist/harness/opencode-config.js +130 -0
  85. package/dist/harness/opencode-config.js.map +1 -0
  86. package/dist/harness/opencode-config.test.d.ts +2 -0
  87. package/dist/harness/opencode-config.test.d.ts.map +1 -0
  88. package/dist/harness/opencode-config.test.js +183 -0
  89. package/dist/harness/opencode-config.test.js.map +1 -0
  90. package/dist/harness/prepare.d.ts +34 -0
  91. package/dist/harness/prepare.d.ts.map +1 -0
  92. package/dist/harness/prepare.js +46 -0
  93. package/dist/harness/prepare.js.map +1 -0
  94. package/dist/harness/prepare.test.d.ts +2 -0
  95. package/dist/harness/prepare.test.d.ts.map +1 -0
  96. package/dist/harness/prepare.test.js +96 -0
  97. package/dist/harness/prepare.test.js.map +1 -0
  98. package/dist/heartbeat.d.ts.map +1 -1
  99. package/dist/heartbeat.js +2 -0
  100. package/dist/heartbeat.js.map +1 -1
  101. package/dist/index.js +21 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/socketio-client.d.ts +74 -3
  104. package/dist/socketio-client.d.ts.map +1 -1
  105. package/dist/socketio-client.github.test.d.ts +2 -0
  106. package/dist/socketio-client.github.test.d.ts.map +1 -0
  107. package/dist/socketio-client.github.test.js +66 -0
  108. package/dist/socketio-client.github.test.js.map +1 -0
  109. package/dist/socketio-client.js +267 -78
  110. package/dist/socketio-client.js.map +1 -1
  111. package/dist/socketio-client.test.d.ts +2 -0
  112. package/dist/socketio-client.test.d.ts.map +1 -0
  113. package/dist/socketio-client.test.js +382 -0
  114. package/dist/socketio-client.test.js.map +1 -0
  115. package/dist/workload-executor.d.ts +37 -1
  116. package/dist/workload-executor.d.ts.map +1 -1
  117. package/dist/workload-executor.js +111 -19
  118. package/dist/workload-executor.js.map +1 -1
  119. package/dist/workload-executor.test.js +205 -3
  120. package/dist/workload-executor.test.js.map +1 -1
  121. package/package.json +2 -1
  122. package/src/acp/__fixtures__/fake-elicitation-agent.mjs +113 -0
  123. package/src/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  124. package/src/acp/bridge.test.ts +480 -1
  125. package/src/acp/bridge.ts +163 -18
  126. package/src/acp/capabilities.test.ts +200 -0
  127. package/src/acp/capabilities.ts +274 -0
  128. package/src/acp/elicitation.integration.test.ts +126 -0
  129. package/src/acp/prober.ts +4 -0
  130. package/src/acp/spawner.ts +3 -0
  131. package/src/acp/sync-bridge.ts +5 -1
  132. package/src/cloud-host/supervisor.test.ts +462 -0
  133. package/src/cloud-host/supervisor.ts +326 -0
  134. package/src/commands/harness.ts +44 -0
  135. package/src/config.ts +9 -3
  136. package/src/github/credential-manager.test.ts +268 -0
  137. package/src/github/credential-manager.ts +251 -0
  138. package/src/github/gh-config.test.ts +103 -0
  139. package/src/github/gh-config.ts +76 -0
  140. package/src/harness/env.test.ts +79 -0
  141. package/src/harness/env.ts +89 -0
  142. package/src/harness/opencode-cli.test.ts +82 -0
  143. package/src/harness/opencode-cli.ts +99 -0
  144. package/src/harness/opencode-config.atomic-failure.test.ts +51 -0
  145. package/src/harness/opencode-config.test.ts +238 -0
  146. package/src/harness/opencode-config.ts +176 -0
  147. package/src/harness/prepare.test.ts +117 -0
  148. package/src/harness/prepare.ts +69 -0
  149. package/src/heartbeat.ts +2 -0
  150. package/src/index.ts +22 -0
  151. package/src/socketio-client.github.test.ts +76 -0
  152. package/src/socketio-client.test.ts +460 -0
  153. package/src/socketio-client.ts +314 -68
  154. package/src/workload-executor.test.ts +264 -2
  155. package/src/workload-executor.ts +147 -18
  156. package/tests/acp-sync-bridge.test.ts +5 -1
  157. package/tests/commands/harness.test.ts +90 -0
  158. package/tests/socketio-client.test.ts +140 -2
  159. package/vitest.config.ts +5 -1
@@ -1,5 +1,5 @@
1
- import { describe, it, expect, afterEach } from 'vitest';
2
- import { mkdtemp, mkdir, rm, access } from 'node:fs/promises';
1
+ import { describe, it, expect, afterEach, vi } from 'vitest';
2
+ import { mkdtemp, mkdir, rm, access, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  import {
@@ -7,6 +7,9 @@ import {
7
7
  MAX_OUTPUT_BYTES,
8
8
  MAX_PENDING_RESULTS,
9
9
  EMPTY_SCRIPT_MESSAGE,
10
+ redactSecrets,
11
+ collectSecretValues,
12
+ REDACTED,
10
13
  type WorkloadResult,
11
14
  } from './workload-executor.js';
12
15
 
@@ -556,3 +559,262 @@ describe('WorkloadExecutor required short-circuit (T-WE-REQ)', () => {
556
559
  expect(results[0].status).toBe('timeout');
557
560
  }, 10000);
558
561
  });
562
+
563
+ describe('WorkloadExecutor container env + secret redaction (T-AG13/T-AG14)', () => {
564
+ it('T-AG14: injects container env into every item and lets item params win on WORKLOAD_PARAM_*', async () => {
565
+ const executor = new WorkloadExecutor();
566
+ const { results, sink } = collect();
567
+
568
+ await executor.runBatch(
569
+ {
570
+ phase: 'init',
571
+ env: {
572
+ ZAG_MODEL_IDS: '["model-a","model-b"]',
573
+ ZAG_DEFAULT_WORKSPACE: '/root/workspace',
574
+ ZAG_USER_ID: 'user-1',
575
+ WORKLOAD_PARAM_VERSION: 'from-container-env',
576
+ },
577
+ items: [
578
+ {
579
+ logId: 'first',
580
+ workloadName: 'First',
581
+ script: `printf 'IDS=%s\\n' "$ZAG_MODEL_IDS"; printf 'WS=%s\\n' "$ZAG_DEFAULT_WORKSPACE"; printf 'USER=%s\\n' "$ZAG_USER_ID"; printf 'V=%s\\n' "$WORKLOAD_PARAM_VERSION"`,
582
+ timeoutMs: 5000,
583
+ params: { version: 'from-item-param' },
584
+ },
585
+ {
586
+ logId: 'second',
587
+ workloadName: 'Second',
588
+ script: `printf 'IDS=%s\\n' "$ZAG_MODEL_IDS"; printf 'V=%s\\n' "$WORKLOAD_PARAM_VERSION"`,
589
+ timeoutMs: 5000,
590
+ },
591
+ ],
592
+ },
593
+ sink,
594
+ );
595
+
596
+ expect(results.map((r) => r.logId)).toEqual(['first', 'second']);
597
+ expect(results[0].log).toContain('IDS=["model-a","model-b"]');
598
+ expect(results[0].log).toContain('WS=/root/workspace');
599
+ expect(results[0].log).toContain('USER=user-1');
600
+ // item 参数优先于容器 env 的同名 WORKLOAD_PARAM_*
601
+ expect(results[0].log).toContain('V=from-item-param');
602
+ expect(results[1].log).toContain('V=from-container-env');
603
+ });
604
+
605
+ it('T-AG14b: keeps legacy behavior when the payload has no container env', async () => {
606
+ const executor = new WorkloadExecutor();
607
+ const { results, sink } = collect();
608
+
609
+ await executor.runBatch(
610
+ {
611
+ phase: 'init',
612
+ items: [
613
+ {
614
+ logId: 'legacy',
615
+ workloadName: 'Legacy',
616
+ script: `printf 'ENV=%s\\n' "\${ZAG_MODEL_IDS-unset}"; printf 'P=%s\\n' "$WORKLOAD_PARAMS"`,
617
+ timeoutMs: 5000,
618
+ },
619
+ ],
620
+ },
621
+ sink,
622
+ );
623
+
624
+ expect(results[0].status).toBe('success');
625
+ expect(results[0].log).toContain('ENV=unset');
626
+ expect(results[0].log).toContain('P={}');
627
+ });
628
+
629
+ it('T-AG13: redacts secret values from script output (container env + process env)', async () => {
630
+ const executor = new WorkloadExecutor();
631
+ const { results, sink } = collect();
632
+ const previousHostKey = process.env.ZAG_HOST_KEY;
633
+ process.env.ZAG_HOST_KEY = 'zag_k_process_secret';
634
+ try {
635
+ await executor.runBatch(
636
+ {
637
+ phase: 'init',
638
+ env: {
639
+ ZAG_MODEL_API_KEY: 'zag_sk_container_secret',
640
+ ZAG_CONTROLLER_KEY: 'controller-token-secret',
641
+ },
642
+ items: [
643
+ {
644
+ logId: 'leak',
645
+ workloadName: 'Leak',
646
+ script: `printf 'A=%s\\n' "$ZAG_MODEL_API_KEY"; printf 'B=%s\\n' "$ZAG_HOST_KEY"; printf 'C=%s\\n' "$ZAG_CONTROLLER_KEY"`,
647
+ timeoutMs: 5000,
648
+ },
649
+ ],
650
+ },
651
+ sink,
652
+ );
653
+ } finally {
654
+ if (previousHostKey === undefined) delete process.env.ZAG_HOST_KEY;
655
+ else process.env.ZAG_HOST_KEY = previousHostKey;
656
+ }
657
+
658
+ expect(results).toHaveLength(1);
659
+ const log = results[0].log;
660
+ expect(log).not.toContain('zag_sk_container_secret');
661
+ expect(log).not.toContain('zag_k_process_secret');
662
+ expect(log).not.toContain('controller-token-secret');
663
+ expect(log).toContain(`A=${REDACTED}`);
664
+ expect(log).toContain(`B=${REDACTED}`);
665
+ expect(log).toContain(`C=${REDACTED}`);
666
+ });
667
+
668
+ it('T-AG13b: redactSecrets handles multiple secrets and ignores empty values', () => {
669
+ const secrets = collectSecretValues(
670
+ { ZAG_MODEL_API_KEY: 'sk-1', ZAG_HOST_KEY: '', ZAG_CONTROLLER_KEY: 'ct-2' },
671
+ { ZAG_HOST_KEY: 'host-3' },
672
+ );
673
+ expect(secrets.sort()).toEqual(['ct-2', 'host-3', 'sk-1'].sort());
674
+
675
+ expect(redactSecrets('a sk-1 b ct-2 c host-3 d', secrets)).toBe(`a ${REDACTED} b ${REDACTED} c ${REDACTED} d`);
676
+ expect(redactSecrets('nothing to hide', secrets)).toBe('nothing to hide');
677
+ });
678
+ });
679
+
680
+ describe('WorkloadExecutor githubAuth prefetch (T-WE-G)', () => {
681
+ const dirs: string[] = [];
682
+
683
+ afterEach(async () => {
684
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
685
+ });
686
+
687
+ async function tmp(): Promise<string> {
688
+ const dir = await makeTmpDir();
689
+ dirs.push(dir);
690
+ return dir;
691
+ }
692
+
693
+ it('T-WE-G1: githubAuth=true calls the hook once before the first script runs', async () => {
694
+ const executor = new WorkloadExecutor();
695
+ const dir = await tmp();
696
+ const marker = join(dir, 'hook.marker');
697
+ const { results, sink } = collect();
698
+ const calls: string[] = [];
699
+
700
+ const outcome = await executor.runBatch(
701
+ {
702
+ phase: 'init',
703
+ githubAuth: true,
704
+ items: [
705
+ { logId: 'g1', workloadName: 'One', script: `test -f "${marker}" && echo ready`, timeoutMs: 5000 },
706
+ { logId: 'g2', workloadName: 'Two', script: `test -f "${marker}" && echo ready`, timeoutMs: 5000 },
707
+ ],
708
+ },
709
+ sink,
710
+ {
711
+ beforeGithubAuth: async () => {
712
+ calls.push('hook');
713
+ await writeFile(marker, 'written');
714
+ },
715
+ },
716
+ );
717
+
718
+ expect(calls).toEqual(['hook']);
719
+ expect(outcome.failedCount).toBe(0);
720
+ expect(results.map((result) => result.status)).toEqual(['success', 'success']);
721
+ expect(results.map((result) => result.log.trim())).toEqual(['ready', 'ready']);
722
+ });
723
+
724
+ it('T-WE-G2: hook failure reports failed for every item and never spawns scripts', async () => {
725
+ const executor = new WorkloadExecutor();
726
+ const dir = await tmp();
727
+ const marker = join(dir, 'should-not-exist');
728
+ const { results, sink } = collect();
729
+
730
+ const outcome = await executor.runBatch(
731
+ {
732
+ phase: 'init',
733
+ githubAuth: true,
734
+ items: [
735
+ { logId: 'g1', workloadName: 'One', script: `touch "${marker}"`, timeoutMs: 5000 },
736
+ { logId: 'g2', workloadName: 'Two', script: `touch "${marker}"`, timeoutMs: 5000 },
737
+ ],
738
+ },
739
+ sink,
740
+ {
741
+ beforeGithubAuth: async () => {
742
+ throw new Error('未设置 Github 项目');
743
+ },
744
+ },
745
+ );
746
+
747
+ expect(outcome.failedCount).toBe(2);
748
+ expect(outcome.total).toBe(2);
749
+ expect(results.map((result) => result.status)).toEqual(['failed', 'failed']);
750
+ expect(results.map((result) => result.log)).toEqual([
751
+ 'Github 凭据申请失败:未设置 Github 项目',
752
+ 'Github 凭据申请失败:未设置 Github 项目',
753
+ ]);
754
+ expect(await fileExists(marker)).toBe(false);
755
+ });
756
+
757
+ it('T-WE-G3: no githubAuth field keeps legacy behavior and never calls the hook', async () => {
758
+ const executor = new WorkloadExecutor();
759
+ const { results, sink } = collect();
760
+ const hook = vi.fn(async () => {});
761
+
762
+ const outcome = await executor.runBatch(
763
+ {
764
+ phase: 'init',
765
+ items: [{ logId: 'legacy', workloadName: 'Legacy', script: 'echo legacy', timeoutMs: 5000 }],
766
+ },
767
+ sink,
768
+ { beforeGithubAuth: hook },
769
+ );
770
+
771
+ expect(hook).not.toHaveBeenCalled();
772
+ expect(outcome.failedCount).toBe(0);
773
+ expect(results.map((result) => result.status)).toEqual(['success']);
774
+ expect(results[0].log.trim()).toBe('legacy');
775
+ });
776
+
777
+ it('T-WE-G4: githubAuth=false is accepted and behaves like the legacy payload', async () => {
778
+ const executor = new WorkloadExecutor();
779
+ const { results, sink } = collect();
780
+ const hook = vi.fn(async () => {});
781
+
782
+ const outcome = await executor.runBatch(
783
+ {
784
+ phase: 'post',
785
+ githubAuth: false,
786
+ items: [{ logId: 'off', workloadName: 'Off', script: 'echo off', timeoutMs: 5000 }],
787
+ },
788
+ sink,
789
+ { beforeGithubAuth: hook },
790
+ );
791
+
792
+ expect(hook).not.toHaveBeenCalled();
793
+ expect(outcome.failedCount).toBe(0);
794
+ expect(results[0].status).toBe('success');
795
+ });
796
+
797
+ it('T-WE-G2b: redacts secrets from the hook failure reason', async () => {
798
+ const executor = new WorkloadExecutor();
799
+ const { results, sink } = collect();
800
+ const secret = 'zag_k_1_super_secret';
801
+
802
+ await executor.runBatch(
803
+ {
804
+ phase: 'init',
805
+ githubAuth: true,
806
+ env: { ZAG_HOST_KEY: secret },
807
+ items: [{ logId: 'redact', workloadName: 'Redact', script: 'echo nope', timeoutMs: 5000 }],
808
+ },
809
+ sink,
810
+ {
811
+ beforeGithubAuth: async () => {
812
+ throw new Error(`hook failed with ${secret}`);
813
+ },
814
+ },
815
+ );
816
+
817
+ expect(results[0].log).toContain(REDACTED);
818
+ expect(results[0].log).not.toContain(secret);
819
+ });
820
+ });
@@ -39,6 +39,66 @@ export interface WorkloadRunPayload {
39
39
  items: WorkloadItem[];
40
40
  /** `post` 批次共享总预算(毫秒);`init` 不携带。 */
41
41
  budgetMs?: number;
42
+ /**
43
+ * 容器级环境变量(仅 `purpose=harness` 下发,如 `ZAG_MODEL_*` / `ZAG_HOST_*`)。
44
+ * 对批次内所有 item 生效;`item.params` 派生的 `WORKLOAD_PARAM_*` 同名时优先。
45
+ */
46
+ env?: Record<string, string>;
47
+ /**
48
+ * `true` 时必须在执行本批第一条脚本前完成 gh 凭据申请与写入(由 `beforeGithubAuth` 承担);
49
+ * 缺省/false 行为与旧版完全一致。
50
+ */
51
+ githubAuth?: boolean;
52
+ }
53
+
54
+ /** `runBatch` 的可选行为注入(默认空实现,保证旧调用方零变化)。 */
55
+ export interface WorkloadRunOptions {
56
+ /**
57
+ * `payload.githubAuth === true` 时、执行首条脚本前调用一次。
58
+ * 抛错时本批所有 item 直接回报 `failed`,且不启动任何脚本。
59
+ */
60
+ beforeGithubAuth?: (payload: WorkloadRunPayload) => Promise<void>;
61
+ }
62
+
63
+ /** 需要在日志/错误/脚本输出中脱敏的环境变量名(契约 §2.9「云电脑初始化 env」)。 */
64
+ export const SECRET_ENV_KEYS = ['ZAG_MODEL_API_KEY', 'ZAG_HOST_KEY', 'ZAG_CONTROLLER_KEY'] as const;
65
+
66
+ /** 脱敏占位符。 */
67
+ export const REDACTED = '***';
68
+
69
+ /**
70
+ * 收集需要脱敏的 secret 值(仅非空值;调用方可叠加批次 `env` 与 `process.env`)。
71
+ */
72
+ export function collectSecretValues(...sources: Array<Record<string, string | undefined> | undefined>): string[] {
73
+ const values = new Set<string>();
74
+ for (const source of sources) {
75
+ if (!source) continue;
76
+ for (const key of SECRET_ENV_KEYS) {
77
+ const value = source[key];
78
+ if (typeof value === 'string' && value.length > 0) values.add(value);
79
+ }
80
+ }
81
+ // 长值优先替换,避免短 secret 是长 secret 的子串时留下残片。
82
+ return [...values].sort((a, b) => b.length - a.length);
83
+ }
84
+
85
+ /** 将文本中出现的 secret 值替换为 `***`(日志、错误与脚本输出统一口径)。 */
86
+ export function redactSecrets(text: string, secrets: Iterable<string>): string {
87
+ let result = text;
88
+ for (const secret of secrets) {
89
+ if (!secret) continue;
90
+ result = result.split(secret).join(REDACTED);
91
+ }
92
+ return result;
93
+ }
94
+
95
+ export interface WorkloadBatchOutcome {
96
+ /** 批次是否被新批次/销毁流程打断(打断时不得视为初始化完成)。 */
97
+ cancelled: boolean;
98
+ /** 已上报的失败/超时条目数(含 required 短路前的当前条)。 */
99
+ failedCount: number;
100
+ /** 本批条目总数。 */
101
+ total: number;
42
102
  }
43
103
 
44
104
  export type WorkloadStatus = 'success' | 'failed' | 'timeout';
@@ -112,6 +172,20 @@ function nowIso(): string {
112
172
  return new Date().toISOString();
113
173
  }
114
174
 
175
+ /**
176
+ * 归一容器级 `env`:只接受字符串键值(服务端报文里 `ZAG_*` 均为字符串),
177
+ * 非对象/数组一律视为未下发(普通容器行为不变)。
178
+ */
179
+ function normalizeContainerEnv(env: Record<string, string> | undefined): Record<string, string> {
180
+ if (!env || typeof env !== 'object' || Array.isArray(env)) return {};
181
+ const normalized: Record<string, string> = {};
182
+ for (const [key, value] of Object.entries(env)) {
183
+ if (!key || typeof value !== 'string') continue;
184
+ normalized[key] = value;
185
+ }
186
+ return normalized;
187
+ }
188
+
115
189
  /** 单个参数值 → 环境变量字符串(契约 §2.9「参数注入约定」)。 */
116
190
  function encodeParamValue(value: unknown): string {
117
191
  if (typeof value === 'string') return value;
@@ -123,17 +197,23 @@ function encodeParamValue(value: unknown): string {
123
197
  }
124
198
 
125
199
  /**
126
- * 由 `process.env` 派生单条 item 的执行环境:
200
+ * 由 `process.env` + 容器级 `env` 派生单条 item 的执行环境:
201
+ * - 容器级 `env`(harness 下发的 `ZAG_*`)先合并,对批次所有 item 生效;
127
202
  * - `WORKLOAD_PARAMS`:完整参数 JSON 字符串(缺省 `{}`);
128
- * - `WORKLOAD_PARAM_<KEY_UPPER>`:单值编码(字符串原样、布尔 `"true"`/`"false"`、多选 JSON 数组字符串)。
203
+ * - `WORKLOAD_PARAM_<KEY_UPPER>`:单值编码(字符串原样、布尔 `"true"`/`"false"`、多选 JSON 数组字符串),
204
+ * 同名时**覆盖**容器 `env`(item 参数优先)。
129
205
  *
130
- * 每次 spawn 都从当前 `process.env` 重新派生,参数 env 仅对当前 item 生效、不污染后续脚本;
206
+ * 每次 spawn 都重新派生,参数 env 仅对当前 item 生效、不污染后续脚本;
131
207
  * 不修改脚本文本、不做字符串替换(避免注入)。
132
208
  */
133
- function buildWorkloadEnv(params: Record<string, unknown> | undefined): NodeJS.ProcessEnv {
209
+ function buildWorkloadEnv(
210
+ params: Record<string, unknown> | undefined,
211
+ containerEnv: Record<string, string> | undefined,
212
+ ): NodeJS.ProcessEnv {
134
213
  const normalized = params && typeof params === 'object' && !Array.isArray(params) ? params : {};
135
214
  const env: NodeJS.ProcessEnv = {
136
215
  ...process.env,
216
+ ...normalizeContainerEnv(containerEnv),
137
217
  WORKLOAD_PARAMS: JSON.stringify(normalized),
138
218
  };
139
219
  for (const [key, value] of Object.entries(normalized)) {
@@ -158,7 +238,7 @@ function buildWorkloadEnv(params: Record<string, unknown> | undefined): NodeJS.P
158
238
  */
159
239
  export class WorkloadExecutor {
160
240
  private active: ActiveRun | null = null;
161
- private activePromise: Promise<void> | null = null;
241
+ private activePromise: Promise<WorkloadBatchOutcome> | null = null;
162
242
  private pendingResults: WorkloadResult[] = [];
163
243
 
164
244
  /** 当前是否有批次正在执行。 */
@@ -207,12 +287,16 @@ export class WorkloadExecutor {
207
287
  /**
208
288
  * 执行一个批次。若已有批次在跑,先终止其进程组并停止推进,再执行新批次。
209
289
  */
210
- runBatch(payload: WorkloadRunPayload, onResult: WorkloadResultSink): Promise<void> {
290
+ runBatch(
291
+ payload: WorkloadRunPayload,
292
+ onResult: WorkloadResultSink,
293
+ options: WorkloadRunOptions = {},
294
+ ): Promise<WorkloadBatchOutcome> {
211
295
  this.interruptActive();
212
296
 
213
297
  const run: ActiveRun = { cancelled: false, child: null };
214
298
  this.active = run;
215
- const promise = this.executeBatch(payload, onResult, run).finally(() => {
299
+ const promise = this.executeBatch(payload, onResult, run, options).finally(() => {
216
300
  // 仅当自己仍是当前批次时才清空(被打断时 active 已指向新批次)
217
301
  if (this.active === run) {
218
302
  this.active = null;
@@ -227,22 +311,61 @@ export class WorkloadExecutor {
227
311
  payload: WorkloadRunPayload,
228
312
  onResult: WorkloadResultSink,
229
313
  run: ActiveRun,
230
- ): Promise<void> {
314
+ options: WorkloadRunOptions = {},
315
+ ): Promise<WorkloadBatchOutcome> {
231
316
  const items = Array.isArray(payload?.items) ? payload.items : [];
232
- if (items.length === 0) return;
317
+ const total = items.length;
318
+ let failedCount = 0;
319
+ const outcome = (): WorkloadBatchOutcome => ({
320
+ cancelled: run.cancelled,
321
+ failedCount,
322
+ total,
323
+ });
324
+ if (items.length === 0) return outcome();
233
325
 
234
326
  const budgetMs = typeof payload.budgetMs === 'number' && payload.budgetMs > 0 ? payload.budgetMs : null;
235
327
  const batchStart = Date.now();
236
328
  const phase = payload.phase;
329
+ const containerEnv = normalizeContainerEnv(payload.env);
330
+ const secrets = collectSecretValues(process.env, containerEnv);
331
+
332
+ // Github 凭据预取:仅在显式 `githubAuth === true` 时触发,失败则整批逐条 failed、不启动脚本。
333
+ // 缺省/false 时不调用 hook,行为与旧版完全一致。
334
+ if (payload.githubAuth === true && options.beforeGithubAuth) {
335
+ try {
336
+ await options.beforeGithubAuth(payload);
337
+ } catch (error) {
338
+ if (run.cancelled) return outcome();
339
+ const reason = error instanceof Error ? error.message : String(error);
340
+ const message = redactSecrets(`Github 凭据申请失败:${reason}`, secrets);
341
+ const now = nowIso();
342
+ for (const item of items) {
343
+ if (run.cancelled) return outcome();
344
+ failedCount += 1;
345
+ this.report(onResult, {
346
+ logId: item.logId,
347
+ status: 'failed',
348
+ exitCode: null,
349
+ log: message,
350
+ startedAt: now,
351
+ finishedAt: nowIso(),
352
+ });
353
+ }
354
+ return outcome();
355
+ }
356
+ if (run.cancelled) return outcome();
357
+ }
237
358
 
238
359
  for (const item of items) {
239
- if (run.cancelled) return;
360
+ if (run.cancelled) return outcome();
240
361
 
241
362
  // 必须项短路(省时优化,服务端仍为唯一裁决):init 阶段的必须项失败/超时后,
242
363
  // 上报本条结果即结束本批,不再启动后续条目。post 批次不参与必须判定。
243
364
  const shortCircuitOnFailure = phase === 'init' && item.required === true;
244
365
  const reportThenMaybeStop = (result: WorkloadResult): boolean => {
245
- this.report(onResult, result);
366
+ if (result.status !== 'success') failedCount += 1;
367
+ const redactedLog = redactSecrets(result.log, secrets);
368
+ this.report(onResult, redactedLog === result.log ? result : { ...result, log: redactedLog });
246
369
  return shortCircuitOnFailure && (result.status === 'failed' || result.status === 'timeout');
247
370
  };
248
371
 
@@ -251,21 +374,22 @@ export class WorkloadExecutor {
251
374
  const remaining = budgetMs - (Date.now() - batchStart);
252
375
  if (remaining <= 0) {
253
376
  // 预算耗尽:后续条目不再启动进程,直接回报 timeout
254
- if (reportThenMaybeStop(this.emptyResult(item.logId, 'timeout', ''))) return;
377
+ if (reportThenMaybeStop(this.emptyResult(item.logId, 'timeout', ''))) return outcome();
255
378
  continue;
256
379
  }
257
380
  effectiveTimeoutMs = Math.min(item.timeoutMs, remaining);
258
381
  }
259
382
 
260
383
  if (!item.script || item.script.trim().length === 0) {
261
- if (reportThenMaybeStop(this.emptyResult(item.logId, 'failed', EMPTY_SCRIPT_MESSAGE))) return;
384
+ if (reportThenMaybeStop(this.emptyResult(item.logId, 'failed', EMPTY_SCRIPT_MESSAGE))) return outcome();
262
385
  continue;
263
386
  }
264
387
 
265
- const outcome = await this.executeItem(item, effectiveTimeoutMs, run);
266
- if (outcome.cancelled) return;
267
- if (outcome.result && reportThenMaybeStop(outcome.result)) return;
388
+ const itemOutcome = await this.executeItem(item, effectiveTimeoutMs, run, containerEnv);
389
+ if (itemOutcome.cancelled) return outcome();
390
+ if (itemOutcome.result && reportThenMaybeStop(itemOutcome.result)) return outcome();
268
391
  }
392
+ return outcome();
269
393
  }
270
394
 
271
395
  private report(onResult: WorkloadResultSink, result: WorkloadResult): void {
@@ -281,7 +405,12 @@ export class WorkloadExecutor {
281
405
  return { logId, status, exitCode: null, log, startedAt: now, finishedAt: now };
282
406
  }
283
407
 
284
- private executeItem(item: WorkloadItem, timeoutMs: number, run: ActiveRun): Promise<ItemOutcome> {
408
+ private executeItem(
409
+ item: WorkloadItem,
410
+ timeoutMs: number,
411
+ run: ActiveRun,
412
+ containerEnv: Record<string, string>,
413
+ ): Promise<ItemOutcome> {
285
414
  return new Promise<ItemOutcome>((resolve) => {
286
415
  if (run.cancelled) {
287
416
  resolve({ cancelled: true });
@@ -294,7 +423,7 @@ export class WorkloadExecutor {
294
423
  child = spawn('bash', ['-c', item.script], {
295
424
  cwd: homedir(),
296
425
  detached: true,
297
- env: buildWorkloadEnv(item.params),
426
+ env: buildWorkloadEnv(item.params, containerEnv),
298
427
  });
299
428
  } catch (error) {
300
429
  resolve({
@@ -65,7 +65,11 @@ describe('AcpSyncBridge', () => {
65
65
  expect(mockSpawner.start).toHaveBeenCalledOnce();
66
66
  expect(mc().initialize).toHaveBeenCalledWith({
67
67
  protocolVersion: 1,
68
- clientCapabilities: {},
68
+ // 显式值断言(非 CLIENT_CAPABILITIES 自引用)
69
+ clientCapabilities: {
70
+ session: { configOptions: { boolean: {} } },
71
+ elicitation: { form: {}, url: {} },
72
+ },
69
73
  clientInfo: { name: 'agent-gear', version: '1.0.0' },
70
74
  });
71
75
  });
@@ -0,0 +1,90 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { Command } from 'commander';
3
+ import { registerHarnessCommands } from '../../src/commands/harness.js';
4
+ import type { HarnessPrepareResult } from '../../src/harness/prepare.js';
5
+
6
+ function buildProgram(deps: Parameters<typeof registerHarnessCommands>[1] = {}) {
7
+ const program = new Command();
8
+ program.name('agent-gear').exitOverride();
9
+ registerHarnessCommands(program, deps);
10
+ return program;
11
+ }
12
+
13
+ const SUCCESS_RESULT: HarnessPrepareResult = {
14
+ opencodeVersion: '1.2.3',
15
+ env: {
16
+ modelBaseUrl: 'http://admin-api:8002/v1',
17
+ defaultWorkspace: '/root/workspace',
18
+ modelCount: 2,
19
+ },
20
+ config: {
21
+ path: '/root/.config/opencode/opencode.jsonc',
22
+ created: true,
23
+ modelCount: 2,
24
+ },
25
+ };
26
+
27
+ describe('agent-gear harness command (T-AG15)', () => {
28
+ const originalExitCode = process.exitCode;
29
+
30
+ beforeEach(() => {
31
+ vi.spyOn(console, 'log').mockImplementation(() => {});
32
+ vi.spyOn(console, 'error').mockImplementation(() => {});
33
+ process.exitCode = undefined;
34
+ });
35
+
36
+ afterEach(() => {
37
+ vi.restoreAllMocks();
38
+ process.exitCode = originalExitCode;
39
+ delete process.env.ZAG_MODEL_API_KEY;
40
+ });
41
+
42
+ it('shows prepare in `agent-gear harness --help`', async () => {
43
+ let output = '';
44
+ const program = buildProgram();
45
+ program.configureOutput({ writeOut: (text) => { output += text; }, writeErr: () => {} });
46
+
47
+ await program.parseAsync(['node', 'agent-gear', 'harness', '--help']).catch(() => {});
48
+
49
+ expect(output).toContain('prepare');
50
+ });
51
+
52
+ it('rejects unknown subcommands with a non-zero exit code', async () => {
53
+ const program = buildProgram();
54
+ program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
55
+
56
+ await expect(
57
+ program.parseAsync(['node', 'agent-gear', 'harness', 'bogus']),
58
+ ).rejects.toMatchObject({ exitCode: 1 });
59
+ });
60
+
61
+ it('prints a secret-free summary on success', async () => {
62
+ const prepare = vi.fn(async () => SUCCESS_RESULT);
63
+ const program = buildProgram({ prepare });
64
+
65
+ await program.parseAsync(['node', 'agent-gear', 'harness', 'prepare']);
66
+
67
+ expect(prepare).toHaveBeenCalledTimes(1);
68
+ expect(process.exitCode).toBeUndefined();
69
+ const output = vi.mocked(console.log).mock.calls.flat().join(' ');
70
+ expect(output).toContain('OpenCode harness prepared');
71
+ expect(output).toContain('version=1.2.3');
72
+ expect(output).not.toContain('zag_sk_');
73
+ });
74
+
75
+ it('exits non-zero and redacts secrets when prepare fails', async () => {
76
+ process.env.ZAG_MODEL_API_KEY = 'zag_sk_super_secret';
77
+ const prepare = vi.fn(async () => {
78
+ throw new Error('failed with key zag_sk_super_secret');
79
+ });
80
+ const program = buildProgram({ prepare });
81
+
82
+ await program.parseAsync(['node', 'agent-gear', 'harness', 'prepare']);
83
+
84
+ expect(process.exitCode).toBe(1);
85
+ const errors = vi.mocked(console.error).mock.calls.flat().join(' ');
86
+ expect(errors).toContain('harness prepare failed');
87
+ expect(errors).not.toContain('zag_sk_super_secret');
88
+ expect(errors).toContain('***');
89
+ });
90
+ });