@nowcrew/daemon 0.6.89 → 0.6.90

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 (115) hide show
  1. package/README.md +64 -3
  2. package/dist/agent-ability/materializer.js +21 -10
  3. package/dist/agent-environment-contract.js +55 -0
  4. package/dist/agent-environment-control.js +24 -0
  5. package/dist/agent-environment-execution.js +98 -0
  6. package/dist/agent-environments.js +275 -0
  7. package/dist/automatic-daemon-installer.js +49 -1
  8. package/dist/computer-main.js +18 -0
  9. package/dist/computer-profile.js +17 -4
  10. package/dist/computer-setup-client.js +318 -0
  11. package/dist/computer-setup-orchestration.js +203 -0
  12. package/dist/computer-setup.js +244 -0
  13. package/dist/config.js +30 -12
  14. package/dist/console-formatter.js +3 -3
  15. package/dist/console.js +15 -2
  16. package/dist/daemon-update-eligibility.js +1 -1
  17. package/dist/execution-journal.js +9 -6
  18. package/dist/execution-protocol.js +1 -0
  19. package/dist/execution-runner.js +13 -8
  20. package/dist/i18n.js +19 -0
  21. package/dist/list-models.js +12 -12
  22. package/dist/local-execution-lease.js +22 -0
  23. package/dist/local-executor.js +57 -84
  24. package/dist/local-memory/candidate.js +43 -0
  25. package/dist/local-memory/index-budget.js +8 -0
  26. package/dist/local-memory/inventory-cli.js +61 -0
  27. package/dist/local-memory/inventory-preview.js +159 -0
  28. package/dist/local-memory/inventory-source.js +159 -0
  29. package/dist/local-memory/pending-match.js +29 -0
  30. package/dist/local-memory/pending-query.js +100 -0
  31. package/dist/local-memory/pending-schema.js +29 -0
  32. package/dist/local-memory/pending-source.js +126 -0
  33. package/dist/local-memory/pending.js +34 -84
  34. package/dist/local-memory/prompt.js +19 -12
  35. package/dist/local-memory/read-cli.js +97 -12
  36. package/dist/local-memory/rollout.js +82 -0
  37. package/dist/local-memory/runtime.js +23 -17
  38. package/dist/local-memory/work-log-execution.js +31 -0
  39. package/dist/local-memory/work-log.js +58 -0
  40. package/dist/local-memory/write.js +27 -58
  41. package/dist/local-runtime-environment.js +50 -0
  42. package/dist/machine-environment-cache.js +147 -0
  43. package/dist/machine-environment-contract.js +10 -0
  44. package/dist/machine-environment-control.js +27 -0
  45. package/dist/machine-environment-policy.js +75 -0
  46. package/dist/machine-environment-process.js +110 -0
  47. package/dist/machine-info.js +70 -25
  48. package/dist/machine-runtime-environment.js +189 -0
  49. package/dist/machine-shell-environment-capture.js +135 -0
  50. package/dist/machine-windows-environment-capture.js +215 -0
  51. package/dist/machine-windows-environment-script.js +158 -0
  52. package/dist/main.js +4 -69
  53. package/dist/marketplace-command.js +21 -0
  54. package/dist/marketplace-controller.js +80 -0
  55. package/dist/marketplace-protocol.js +38 -0
  56. package/dist/marketplace-remote.js +48 -0
  57. package/dist/marketplace-runner.js +235 -0
  58. package/dist/marketplace-serve.js +17 -0
  59. package/dist/marketplace-source.js +103 -0
  60. package/dist/message-file-preview.js +246 -0
  61. package/dist/pre-admission-rejection.js +64 -0
  62. package/dist/project-skills/execution-adapter.js +3 -2
  63. package/dist/project-skills/runtime-launch.js +14 -0
  64. package/dist/provider-env.js +26 -15
  65. package/dist/runner.js +17 -4
  66. package/dist/runtime-environment-merge.js +16 -0
  67. package/dist/runtime-health-handler.js +10 -0
  68. package/dist/runtime-health.js +3 -1
  69. package/dist/runtime-path.js +22 -12
  70. package/dist/runtime-probe.js +35 -6
  71. package/dist/runtimes/acp-probe-transport.js +69 -0
  72. package/dist/runtimes/claude-models.js +20 -9
  73. package/dist/runtimes/deepseek-harness-launch.js +10 -0
  74. package/dist/runtimes/deepseek-harness-profile.js +92 -0
  75. package/dist/runtimes/deepseek-harness-runner.js +226 -0
  76. package/dist/runtimes/deepseek-harness.js +76 -15
  77. package/dist/runtimes/harness-probe-retry.js +42 -0
  78. package/dist/runtimes/hermes-models.js +2 -1
  79. package/dist/runtimes/kimi-acp-runner.js +78 -13
  80. package/dist/runtimes/opencode.js +2 -2
  81. package/dist/serve.js +88 -176
  82. package/dist/storage-identity.js +0 -3
  83. package/dist/storage-serve-adapter.js +6 -72
  84. package/dist/supervised-runtime.js +17 -2
  85. package/dist/token.js +0 -1
  86. package/dist/workspace-control-handler.js +27 -0
  87. package/dist/workspace-fs.js +66 -15
  88. package/dist/workspace.js +1 -1
  89. package/package.json +13 -12
  90. package/dist/codex-home-launch.js +0 -7
  91. package/dist/codex-home-mode-controller.js +0 -68
  92. package/dist/daemon-migration-controller.js +0 -211
  93. package/dist/daemon-migration-wiring.js +0 -22
  94. package/dist/runtimes/codex-home-migration-cli.js +0 -26
  95. package/dist/runtimes/codex-home-migration.js +0 -112
  96. package/dist/runtimes/codex-home.js +0 -236
  97. package/dist/storage-control.js +0 -212
  98. package/dist/storage-copy.js +0 -628
  99. package/dist/storage-credential-guard.js +0 -21
  100. package/dist/storage-doctor.js +0 -228
  101. package/dist/storage-manifest.js +0 -1027
  102. package/dist/storage-migration-controller.js +0 -440
  103. package/dist/storage-migration-manifest.js +0 -105
  104. package/dist/storage-migration-policy.js +0 -100
  105. package/dist/storage-runtime-controller.js +0 -381
  106. package/dist/storage-runtime-readiness.js +0 -241
  107. package/dist/storage-safe-fs.js +0 -302
  108. package/dist/storage-status-delivery.js +0 -224
  109. package/dist/storage-status-replay.js +0 -140
  110. package/dist/storage-target-confirmation.js +0 -129
  111. package/dist/storage-worker-command.js +0 -37
  112. package/dist/storage-worker-executor.js +0 -447
  113. package/dist/storage-worker-handoff.js +0 -151
  114. package/dist/storage-worker-operation.js +0 -294
  115. package/dist/storage-worker-status.js +0 -259
@@ -0,0 +1,92 @@
1
+ /** 短命执行配置:不读取全局 Harness home,不新增 daemon 状态。 */
2
+ import { mkdtemp, mkdir, writeFile, access } from "node:fs/promises";
3
+ import { join, isAbsolute } from "node:path";
4
+ import { stringify } from "yaml";
5
+ export const harnessPermissionMode = (permission) => permission === "sandboxed"
6
+ ? "read-only"
7
+ : permission === "workspace_write"
8
+ ? "workspace-write"
9
+ : "danger-full-access";
10
+ // A variable's returned value is interpolated once: literal {{...}} in NowWork
11
+ // instructions must not become unknown Harness template variables.
12
+ const instructionsPlugin = `export const name = 'nowwork-instructions';
13
+ export const inject = ['systemPrompt'];
14
+ export function apply(ctx, config) {
15
+ ctx.systemPrompt.variable('nowwork_instructions', () => config.text);
16
+ ctx.systemPrompt.section({name: 'nowwork-instructions', order: 100000, text: '{{nowwork_instructions}}'});
17
+ }
18
+ `;
19
+ export async function prepareHarnessProfile(input) {
20
+ if (![input.stateRoot, input.cwd, ...input.skillRoots].every(isAbsolute)) {
21
+ throw new Error("DeepSeek Harness execution paths must be absolute");
22
+ }
23
+ if (input.patchPath !== undefined) {
24
+ if (!isAbsolute(input.patchPath))
25
+ throw new Error("DeepSeek Harness patch must be absolute");
26
+ await access(input.patchPath);
27
+ }
28
+ await mkdir(input.stateRoot, { recursive: true, mode: 0o700 });
29
+ const home = await mkdtemp(join(input.stateRoot, ".deepseek-harness-"));
30
+ const pluginPath = join(home, "nowwork-instructions.mjs");
31
+ const policyPath = join(home, "nowwork-policy.yml");
32
+ const mode = harnessPermissionMode(input.effectivePermission);
33
+ await writeFile(pluginPath, instructionsPlugin, { mode: 0o600 });
34
+ await writeFile(policyPath, stringify([
35
+ {
36
+ id: "sandbox-policy",
37
+ disabled: false,
38
+ config: { mode, workspaceRoot: input.cwd },
39
+ },
40
+ { id: "approval", disabled: false, config: { policy: "never" } },
41
+ {
42
+ id: "permission",
43
+ disabled: false,
44
+ config: {
45
+ defaultPreset: "nowwork",
46
+ presets: { nowwork: { sandbox: mode, approval: "never" } },
47
+ },
48
+ },
49
+ {
50
+ id: "skill-filesystem",
51
+ disabled: false,
52
+ config: {
53
+ includeDefaultRoots: false,
54
+ customSkillDirs: [...input.skillRoots],
55
+ watch: false,
56
+ },
57
+ },
58
+ {
59
+ id: "session-persistence-jsonl",
60
+ disabled: false,
61
+ config: { root: join(home, "sessions") },
62
+ },
63
+ {
64
+ insert: [
65
+ {
66
+ id: "nowwork-instructions",
67
+ name: pluginPath,
68
+ config: { text: input.systemPrompt },
69
+ },
70
+ ],
71
+ },
72
+ ]), { mode: 0o600 });
73
+ const env = Object.fromEntries(Object.entries(input.env).filter(([key]) => !key.toUpperCase().startsWith("DSH_")));
74
+ return {
75
+ home,
76
+ policyPath,
77
+ args: [
78
+ "--profile",
79
+ "acp",
80
+ ...(input.patchPath ? ["--patch", input.patchPath] : []),
81
+ "--patch",
82
+ policyPath,
83
+ ],
84
+ env: {
85
+ ...env,
86
+ DSH_HOME: home,
87
+ DSH_AGENTS_HOME: join(home, "agents-home"),
88
+ DSH_PERMISSION_MODE: mode,
89
+ DSH_TELEMETRY_DISABLED: "1",
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,226 @@
1
+ /** 新版 Harness 的短命 ACP 桥:产品状态与重试仍属于 server。 */
2
+ import { once } from "node:events";
3
+ import { Readable, Writable } from "node:stream";
4
+ import { parseArgs } from "node:util";
5
+ import { pathToFileURL } from "node:url";
6
+ import { isAbsolute } from "node:path";
7
+ import spawn from "cross-spawn";
8
+ import { z } from "zod";
9
+ import { client, methods, ndJsonStream, PROTOCOL_VERSION, } from "@agentclientprotocol/sdk";
10
+ import { deepSeekHarnessLaunch } from "./deepseek-harness-launch.js";
11
+ import { prepareHarnessProfile } from "./deepseek-harness-profile.js";
12
+ import { mapAcpUpdate } from "./kimi-acp-runner.js";
13
+ import { prepareThreadDelivery } from "../thread-input-delivery.js";
14
+ const absolutePath = z.string().refine(isAbsolute, "must be an absolute path");
15
+ export const HarnessInputSchema = z
16
+ .object({
17
+ systemPrompt: z.string(),
18
+ wakePrompt: z.string().min(1),
19
+ stateRoot: absolutePath,
20
+ skillRoots: z.array(absolutePath).default([]),
21
+ effectivePermission: z.enum([
22
+ "sandboxed",
23
+ "workspace_write",
24
+ "full_access",
25
+ ]),
26
+ })
27
+ .strict();
28
+ const emit = async (event) => {
29
+ if (!process.stdout.write(`${JSON.stringify(event)}\n`))
30
+ await once(process.stdout, "drain");
31
+ };
32
+ async function settleWithin(promise, ms) {
33
+ let timer;
34
+ try {
35
+ return await Promise.race([
36
+ promise,
37
+ new Promise((resolve) => {
38
+ timer = setTimeout(() => resolve(undefined), ms);
39
+ }),
40
+ ]);
41
+ }
42
+ finally {
43
+ if (timer)
44
+ clearTimeout(timer);
45
+ }
46
+ }
47
+ export async function runHarness(input, bin, patchPath) {
48
+ const delivery = await prepareThreadDelivery({
49
+ env: process.env,
50
+ resumed: false,
51
+ sessionId: "cold-harness",
52
+ wakePrompt: input.wakePrompt,
53
+ });
54
+ const profile = await prepareHarnessProfile({
55
+ ...input,
56
+ cwd: process.cwd(),
57
+ env: process.env,
58
+ ...(patchPath ? { patchPath } : {}),
59
+ });
60
+ const launch = deepSeekHarnessLaunch(bin, profile.args);
61
+ const child = spawn(launch.bin, launch.args, {
62
+ cwd: profile.home,
63
+ env: profile.env,
64
+ stdio: ["pipe", "pipe", "pipe"],
65
+ });
66
+ // Boot away from the repository: the CLI must not load a project's .env into
67
+ // trusted process credentials. ACP session/new carries the real workspace.
68
+ let spawnError;
69
+ const closed = new Promise((resolve) => {
70
+ child.once("error", (error) => {
71
+ spawnError = error;
72
+ resolve();
73
+ });
74
+ child.once("close", () => resolve());
75
+ });
76
+ if (!child.stdin || !child.stdout || !child.stderr)
77
+ throw new Error("DeepSeek Harness stdio unavailable");
78
+ // Provider diagnostics may include secrets or prompts; do not stream raw stderr.
79
+ child.stderr.resume();
80
+ let context;
81
+ let sessionId;
82
+ let cancelled = false;
83
+ let stage = "initialize";
84
+ let exitCode = 1;
85
+ let stopping;
86
+ const stop = () => (stopping ??= (async () => {
87
+ child.stdin?.end();
88
+ if (await settleWithin(closed.then(() => true), 2000))
89
+ return;
90
+ child.kill("SIGTERM");
91
+ if (await settleWithin(closed.then(() => true), 1000))
92
+ return;
93
+ child.kill("SIGKILL");
94
+ if (!(await settleWithin(closed.then(() => true), 2000)))
95
+ throw new Error("DeepSeek Harness process stop unconfirmed");
96
+ })());
97
+ const cancel = () => {
98
+ cancelled = true;
99
+ void (async () => {
100
+ if (context && sessionId)
101
+ await settleWithin(context
102
+ .notify(methods.agent.session.cancel, { sessionId })
103
+ .catch(() => undefined), 1000);
104
+ await stop();
105
+ })().catch(() => {
106
+ /* finally reports stop failure; supervisor owns process tree */
107
+ });
108
+ };
109
+ process.once("SIGTERM", cancel);
110
+ process.once("SIGINT", cancel);
111
+ const app = client({ name: "nowwork-harness" })
112
+ .onRequest(methods.client.session.requestPermission, () => ({
113
+ outcome: { outcome: "cancelled" },
114
+ }))
115
+ .onNotification(methods.client.session.update, async ({ params }) => {
116
+ if (params.sessionId !== sessionId)
117
+ return;
118
+ for (const event of mapAcpUpdate("deepseek-harness", params.update))
119
+ await emit(event);
120
+ });
121
+ try {
122
+ const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
123
+ const result = await app.connectWith(stream, async (ctx) => {
124
+ context = ctx;
125
+ const initialized = await ctx.request(methods.agent.initialize, {
126
+ protocolVersion: PROTOCOL_VERSION,
127
+ clientCapabilities: {},
128
+ clientInfo: { name: "nowwork", version: "1" },
129
+ });
130
+ if (initialized.protocolVersion !== PROTOCOL_VERSION)
131
+ throw new Error("Incompatible ACP protocol");
132
+ if (cancelled)
133
+ throw new Error("cancelled");
134
+ stage = "session_new";
135
+ const session = await ctx.request(methods.agent.session.new, {
136
+ cwd: process.cwd(),
137
+ mcpServers: [],
138
+ });
139
+ sessionId = session.sessionId;
140
+ if (!sessionId || cancelled)
141
+ throw new Error("Harness session unavailable");
142
+ await emit({ type: "thread.started", thread_id: sessionId });
143
+ stage = "prompt";
144
+ const response = await ctx.request(methods.agent.session.prompt, {
145
+ sessionId,
146
+ prompt: [{ type: "text", text: delivery.prompt }],
147
+ });
148
+ if (initialized.agentCapabilities?.sessionCapabilities?.close != null) {
149
+ stage = "session_close";
150
+ const close = await settleWithin(ctx
151
+ .request(methods.agent.session.close, { sessionId })
152
+ .then(() => true), 5000);
153
+ if (!close)
154
+ throw new Error("Harness session close timed out");
155
+ }
156
+ return response;
157
+ });
158
+ const usage = result.usage;
159
+ if (!cancelled)
160
+ await emit({
161
+ type: "turn.completed",
162
+ stop_reason: result.stopReason,
163
+ ...(usage
164
+ ? {
165
+ usage: {
166
+ input_tokens: usage.inputTokens,
167
+ output_tokens: usage.outputTokens,
168
+ cache_read_input_tokens: usage.cachedReadTokens ?? 0,
169
+ cache_creation_input_tokens: usage.cachedWriteTokens ?? 0,
170
+ },
171
+ }
172
+ : {}),
173
+ });
174
+ exitCode =
175
+ result.stopReason === "end_turn"
176
+ ? 0
177
+ : result.stopReason === "cancelled"
178
+ ? 130
179
+ : 1;
180
+ }
181
+ catch {
182
+ if (!cancelled)
183
+ process.stderr.write(spawnError
184
+ ? "DeepSeek Harness launch failed; verify the installed dsh executable.\n"
185
+ : `DeepSeek Harness ACP execution failed at ${stage}; verify DEEPSEEK_API_KEY, model access, the pinned version and profile patch.\n`);
186
+ }
187
+ finally {
188
+ try {
189
+ await stop();
190
+ }
191
+ finally {
192
+ process.off("SIGTERM", cancel);
193
+ process.off("SIGINT", cancel);
194
+ }
195
+ }
196
+ if (cancelled)
197
+ return 130;
198
+ return child.exitCode !== 0 ? 1 : exitCode;
199
+ }
200
+ async function main() {
201
+ const { values } = parseArgs({
202
+ options: { bin: { type: "string" }, patch: { type: "string" } },
203
+ });
204
+ if (!values.bin)
205
+ throw new Error("DeepSeek Harness --bin is required");
206
+ process.stdin.setEncoding("utf8");
207
+ let text = "";
208
+ for await (const chunk of process.stdin) {
209
+ text += String(chunk);
210
+ if (Buffer.byteLength(text) > 16 * 1024 * 1024)
211
+ throw new Error("Harness input exceeds 16 MiB");
212
+ }
213
+ const input = HarnessInputSchema.parse(JSON.parse(text));
214
+ return runHarness(input, values.bin, values.patch);
215
+ }
216
+ if (process.argv[1] &&
217
+ import.meta.url === pathToFileURL(process.argv[1]).href) {
218
+ main()
219
+ .then((code) => {
220
+ process.exitCode = code;
221
+ })
222
+ .catch(() => {
223
+ process.stderr.write("DeepSeek Harness configuration or cleanup failed; check execution paths and machine patch.\n");
224
+ process.exitCode = 1;
225
+ });
226
+ }
@@ -1,20 +1,81 @@
1
1
  import spawn from "cross-spawn";
2
- import { isAbsolute } from "node:path";
3
- import { probeKimiAcp } from "./kimi-acp-runner.js";
2
+ import { isAbsolute, win32, join } from "node:path";
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { deepSeekHarnessLaunch } from "./deepseek-harness-launch.js";
6
+ import { prepareHarnessProfile } from "./deepseek-harness-profile.js";
7
+ import { probeKimiAcp, AcpProbeCleanupError } from "./kimi-acp-runner.js";
8
+ import { runtimeEnvironmentValue } from "../runtime-environment-merge.js";
9
+ import { augmentedPath } from "../runtime-path.js";
4
10
  export const DEEPSEEK_HARNESS_CONFIG_ENV = "NOWCREW_DEEPSEEK_HARNESS_CONFIG";
5
- export function deepSeekHarnessConfigPath(env = process.env) {
6
- const path = env[DEEPSEEK_HARNESS_CONFIG_ENV]?.trim();
7
- return path && isAbsolute(path) ? path : null;
11
+ export const DEEPSEEK_HARNESS_PATCH_ENV = "NOWCREW_DEEPSEEK_HARNESS_PATCH";
12
+ export function deepSeekHarnessLauncher(env = process.env, platform = process.platform) {
13
+ const configPath = runtimeEnvironmentValue(env, DEEPSEEK_HARNESS_CONFIG_ENV, platform)?.trim();
14
+ const patchPath = runtimeEnvironmentValue(env, DEEPSEEK_HARNESS_PATCH_ENV, platform)?.trim();
15
+ const absolute = platform === "win32" ? win32.isAbsolute : isAbsolute;
16
+ if (configPath && !absolute(configPath))
17
+ throw new Error(`${DEEPSEEK_HARNESS_CONFIG_ENV} must be an absolute path`);
18
+ if (patchPath && !absolute(patchPath))
19
+ throw new Error(`${DEEPSEEK_HARNESS_PATCH_ENV} must be an absolute path`);
20
+ if (configPath && patchPath)
21
+ throw new Error("DeepSeek Harness legacy config and profile patch are mutually exclusive");
22
+ return configPath
23
+ ? { kind: "legacy", bin: "dsh-acp-demo", configPath }
24
+ : { kind: "profile", bin: "dsh", ...(patchPath ? { patchPath } : {}) };
25
+ }
26
+ export function deepSeekHarnessConfigPath(env = process.env, platform = process.platform) {
27
+ const path = runtimeEnvironmentValue(env, DEEPSEEK_HARNESS_CONFIG_ENV, platform)?.trim();
28
+ return path && (platform === "win32" ? win32.isAbsolute(path) : isAbsolute(path)) ? path : null;
8
29
  }
9
30
  /** The published DeepSeek Harness ACP executable speaks JSON-RPC directly on stdio. */
10
- export function probeDeepSeekHarnessAcp(options, spawnProcess = spawn) {
11
- const configPath = options.configPath ?? deepSeekHarnessConfigPath();
12
- if (!configPath || !isAbsolute(configPath))
13
- return Promise.resolve(false);
14
- return probeKimiAcp({
15
- ...options,
16
- provider: "deepseek-harness",
17
- configPath,
18
- effectivePermission: "sandboxed",
19
- }, spawnProcess);
31
+ export async function probeDeepSeekHarnessAcp(options, spawnProcess = spawn) {
32
+ if (options.signal?.aborted)
33
+ return false;
34
+ const sourceEnv = options.env ?? { ...process.env, PATH: augmentedPath() };
35
+ let root;
36
+ try {
37
+ const launcher = options.configPath === undefined
38
+ ? deepSeekHarnessLauncher(sourceEnv)
39
+ : deepSeekHarnessLauncher({
40
+ ...sourceEnv,
41
+ [DEEPSEEK_HARNESS_CONFIG_ENV]: options.configPath,
42
+ });
43
+ if (launcher.kind === "legacy")
44
+ return await probeKimiAcp({
45
+ ...options,
46
+ env: sourceEnv,
47
+ provider: "deepseek-harness",
48
+ configPath: launcher.configPath,
49
+ effectivePermission: "sandboxed",
50
+ }, spawnProcess);
51
+ root = await mkdtemp(join(tmpdir(), "nowwork-dsh-probe-"));
52
+ const profile = await prepareHarnessProfile({
53
+ stateRoot: root,
54
+ cwd: root,
55
+ systemPrompt: "",
56
+ skillRoots: [],
57
+ effectivePermission: "sandboxed",
58
+ env: sourceEnv,
59
+ ...(launcher.patchPath ? { patchPath: launcher.patchPath } : {}),
60
+ });
61
+ const launch = deepSeekHarnessLaunch(options.bin, profile.args);
62
+ return await probeKimiAcp({
63
+ ...options,
64
+ bin: launch.bin,
65
+ provider: "deepseek-harness",
66
+ effectivePermission: "sandboxed",
67
+ launchArgs: launch.args,
68
+ launchEnv: profile.env,
69
+ launchCwd: root,
70
+ }, spawnProcess);
71
+ }
72
+ catch (error) {
73
+ if (error instanceof AcpProbeCleanupError)
74
+ throw error;
75
+ return false;
76
+ }
77
+ finally {
78
+ if (root)
79
+ await rm(root, { recursive: true, force: true }).catch(() => undefined);
80
+ }
20
81
  }
@@ -0,0 +1,42 @@
1
+ import { dslog } from "../slog.js";
2
+ const RETRY_DELAYS_MS = [1_000, 2_000];
3
+ /** 只延迟当前启动探测,不设后台定时任务;stop 立即清除等待。 */
4
+ function waitForRetry(ms, signal) {
5
+ if (signal?.aborted)
6
+ return Promise.resolve(false);
7
+ return new Promise((resolve) => {
8
+ const finish = (ready) => {
9
+ clearTimeout(timer);
10
+ signal?.removeEventListener("abort", onAbort);
11
+ resolve(ready);
12
+ };
13
+ const onAbort = () => finish(false);
14
+ const timer = setTimeout(() => finish(true), ms);
15
+ signal?.addEventListener("abort", onAbort, { once: true });
16
+ });
17
+ }
18
+ /** 成功才公布能力;每次 probe 返回前已完成进程清理,异常保持原有传播。 */
19
+ export async function retryHarnessProbe(probe, signal, probeId) {
20
+ for (let attempt = 1; attempt <= RETRY_DELAYS_MS.length + 1; attempt++) {
21
+ if (signal?.aborted)
22
+ return false;
23
+ const ready = await probe();
24
+ dslog("runtime_probe.harness_attempt", "Harness 启动探测尝试结束", {
25
+ probe_id: probeId, runtime: "deepseek-harness", attempt, ready,
26
+ aborted: signal?.aborted ?? false,
27
+ });
28
+ if (signal?.aborted)
29
+ return false;
30
+ if (ready)
31
+ return true;
32
+ const delayMs = RETRY_DELAYS_MS[attempt - 1];
33
+ if (delayMs === undefined)
34
+ return false;
35
+ dslog("runtime_probe.harness_retry", "延迟重试 Harness 启动探测", {
36
+ probe_id: probeId, runtime: "deepseek-harness", next_attempt: attempt + 1, delay_ms: delayMs,
37
+ });
38
+ if (!await waitForRetry(delayMs, signal))
39
+ return false;
40
+ }
41
+ return false;
42
+ }
@@ -71,9 +71,10 @@ async function stopChild(child) {
71
71
  }
72
72
  export async function listHermesModels(options = {}) {
73
73
  const spawnProcess = options.spawnProcess ?? spawn;
74
+ const env = options.env ?? { ...process.env, PATH: augmentedPath() };
74
75
  const child = spawnProcess("hermes", ["acp"], {
75
76
  cwd: process.cwd(),
76
- env: { ...process.env, PATH: augmentedPath() },
77
+ env,
77
78
  stdio: ["pipe", "pipe", "pipe"],
78
79
  });
79
80
  if (child.stdin === null || child.stdout === null || child.stderr === null)
@@ -1,3 +1,6 @@
1
+ import { AcpProbeTransport } from "./acp-probe-transport.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { dslog } from "../slog.js";
1
4
  import { once } from "node:events";
2
5
  import { isAbsolute } from "node:path";
3
6
  import { parseArgs } from "node:util";
@@ -10,7 +13,12 @@ import { prepareThreadDelivery } from "../thread-input-delivery.js";
10
13
  import { startFirstProgressWatchdog } from "./progress-watchdog.js";
11
14
  import { assertKimiLegacyPromptFits, buildKimiArgs } from "./kimi.js";
12
15
  const ERROR_MESSAGE_CAP = 2_000;
13
- const PROBE_TIMEOUT_MS = 5_000;
16
+ // macOS launchd cold-starts ACP runtimes materially slower than an interactive
17
+ // shell. DeepSeek Harness was measured at ~4.4s before returning initialize
18
+ // under launchd, while the daemon also creates an isolated profile. Keep this
19
+ // bounded below the control-plane request budget, with the existing 1s/2s
20
+ // Harness retries providing the outer bound.
21
+ export const ACP_PROBE_TIMEOUT_MS = 10_000;
14
22
  function jsonLine(event) {
15
23
  if (process.stdout.write(`${JSON.stringify(event)}\n`))
16
24
  return Promise.resolve();
@@ -128,10 +136,10 @@ function deepSeekPermissionMode(permission) {
128
136
  return "workspace-write";
129
137
  return "danger-full-access";
130
138
  }
131
- function providerEnv(provider, permission) {
139
+ function providerEnv(provider, permission, env = process.env) {
132
140
  return provider === "deepseek-harness"
133
- ? { ...process.env, DSH_PERMISSION_MODE: deepSeekPermissionMode(permission) }
134
- : process.env;
141
+ ? { ...env, DSH_PERMISSION_MODE: deepSeekPermissionMode(permission) }
142
+ : env;
135
143
  }
136
144
  function providerDisplayName(provider) {
137
145
  if (provider === "deepseek-harness")
@@ -194,18 +202,48 @@ async function stopChild(child) {
194
202
  await closed;
195
203
  }
196
204
  }
205
+ export class AcpProbeCleanupError extends Error {
206
+ constructor() { super("ACP probe process cleanup unconfirmed"); this.name = "AcpProbeCleanupError"; }
207
+ }
197
208
  /** Probe the ACP transport without starting a session or forcing an optional interactive login flow. */
198
209
  export async function probeKimiAcp(options, spawnProcess = spawn) {
199
210
  const provider = options.provider ?? "kimi";
200
211
  const permission = options.effectivePermission ?? "sandboxed";
201
- const child = spawnProcess(options.bin, providerArgs(provider, options.configPath), {
202
- cwd: process.cwd(),
203
- // probe 在 daemon 自身 PATH 下运行,补上用户级 CLI 目录,与 which 探测保持一致。
204
- env: { ...providerEnv(provider, permission), PATH: augmentedPath() },
212
+ const probeId = options.probeId ?? randomUUID();
213
+ const started = performance.now();
214
+ const elapsed = () => Math.round(performance.now() - started);
215
+ const transport = new AcpProbeTransport(elapsed);
216
+ let spawnConfirmedMs;
217
+ let reason = "initializing", protocolVersion;
218
+ let stderrSeen = false;
219
+ const fields = () => ({ probe_id: probeId, runtime: provider, duration_ms: elapsed(),
220
+ ...transport.fields(), spawn_confirmed_ms: spawnConfirmedMs, child_pid: child.pid,
221
+ reason, protocol_version: protocolVersion, stderr_seen: stderrSeen, aborted: options.signal?.aborted ?? false });
222
+ dslog("execution.acp_probe_started", "ACP 探测开始", { probe_id: probeId, runtime: provider, node_version: process.version });
223
+ const sourceEnv = options.env ?? { ...process.env, PATH: augmentedPath() };
224
+ const launchEnv = options.launchEnv ?? providerEnv(provider, permission, sourceEnv);
225
+ const child = spawnProcess(options.bin, options.launchArgs ?? providerArgs(provider, options.configPath), {
226
+ cwd: options.launchCwd ?? process.cwd(),
227
+ // 显式 launchEnv 已准备好 PATH/HOME,不能二次补 PATH 或混入父进程环境。
228
+ env: launchEnv,
205
229
  stdio: ["pipe", "pipe", "pipe"],
206
230
  });
231
+ // spawn errors are emitted by ChildProcess, not its stdio streams. A missing
232
+ // launcher must fail admission, not become an uncaught daemon exception.
233
+ const spawnFailed = new Promise((resolve) => {
234
+ child.once("error", () => {
235
+ if (reason === "initializing")
236
+ reason = "spawn_error";
237
+ resolve(false);
238
+ });
239
+ });
240
+ child.once("spawn", () => {
241
+ spawnConfirmedMs = elapsed();
242
+ dslog("execution.acp_probe_spawned", "ACP 探测子进程已启动", fields());
243
+ });
207
244
  if (child.stdin === null || child.stdout === null || child.stderr === null)
208
245
  return false;
246
+ child.stderr.on("data", () => { stderrSeen = true; });
209
247
  child.stderr.resume();
210
248
  const app = client({ name: `nowcrew-daemon-${provider}-probe` })
211
249
  .onRequest(methods.client.session.requestPermission, () => ({
@@ -215,25 +253,37 @@ export async function probeKimiAcp(options, spawnProcess = spawn) {
215
253
  let timeout;
216
254
  let onAbort;
217
255
  try {
218
- const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
256
+ const stream = ndJsonStream(transport.writable(child.stdin), transport.readable(child.stdout));
219
257
  const connected = app.connectWith(stream, async (context) => {
220
- await context.request(methods.agent.initialize, {
258
+ transport.initializeRequested();
259
+ const initialized = await context.request(methods.agent.initialize, {
221
260
  protocolVersion: PROTOCOL_VERSION,
222
261
  clientCapabilities: {},
223
262
  clientInfo: { name: "nowcrew-daemon", version: "1" },
224
263
  });
225
- return true;
264
+ transport.initializeResponse();
265
+ protocolVersion = initialized.protocolVersion;
266
+ const ready = protocolVersion === PROTOCOL_VERSION;
267
+ if (reason === "initializing")
268
+ reason = ready ? "ready" : "protocol_mismatch";
269
+ dslog("execution.acp_probe_handshake", "ACP 握手结果", { ...fields(), ready });
270
+ return ready;
226
271
  });
227
272
  const result = await Promise.race([
228
273
  connected,
274
+ spawnFailed,
229
275
  new Promise((resolve) => {
230
276
  timeout = setTimeout(() => {
277
+ if (reason === "initializing")
278
+ reason = "timeout";
231
279
  void stopChild(child);
232
280
  resolve(false);
233
- }, PROBE_TIMEOUT_MS);
281
+ }, ACP_PROBE_TIMEOUT_MS);
234
282
  }),
235
283
  new Promise((resolve) => {
236
284
  onAbort = () => {
285
+ if (reason === "initializing")
286
+ reason = "aborted";
237
287
  void stopChild(child);
238
288
  resolve(false);
239
289
  };
@@ -246,6 +296,8 @@ export async function probeKimiAcp(options, spawnProcess = spawn) {
246
296
  return result;
247
297
  }
248
298
  catch {
299
+ if (reason === "initializing")
300
+ reason = options.signal?.aborted ? "aborted" : "transport_error";
249
301
  return false;
250
302
  }
251
303
  finally {
@@ -253,7 +305,20 @@ export async function probeKimiAcp(options, spawnProcess = spawn) {
253
305
  clearTimeout(timeout);
254
306
  if (onAbort !== undefined)
255
307
  options.signal?.removeEventListener("abort", onAbort);
256
- await stopChild(child);
308
+ dslog("execution.acp_probe_cleanup_started", "ACP 探测清理开始", fields());
309
+ let cleanupFinished = false;
310
+ try {
311
+ await stopChild(child);
312
+ cleanupFinished = true;
313
+ }
314
+ catch {
315
+ throw new AcpProbeCleanupError();
316
+ }
317
+ finally {
318
+ dslog("execution.acp_probe_finished", "ACP 探测结束", { ...fields(),
319
+ cleanup_finished: cleanupFinished, exit_code: child.exitCode, exit_signal: child.signalCode,
320
+ level: reason === "ready" && cleanupFinished ? "INFO" : "WARN" });
321
+ }
257
322
  }
258
323
  }
259
324
  export async function runKimiAcp(requestedOptions) {
@@ -11,7 +11,7 @@ const REQUIRED_RUN_FLAGS = [
11
11
  "--variant",
12
12
  "--session",
13
13
  ];
14
- export async function probeOpenCodeRun(signal) {
14
+ export async function probeOpenCodeRun(signal, env = { ...process.env, PATH: augmentedPath() }) {
15
15
  try {
16
16
  const { stdout, stderr } = await execFileP("opencode", ["run", "--help"], {
17
17
  shell: isWin(),
@@ -19,7 +19,7 @@ export async function probeOpenCodeRun(signal) {
19
19
  killSignal: "SIGKILL",
20
20
  maxBuffer: 1024 * 1024,
21
21
  signal,
22
- env: { ...process.env, PATH: augmentedPath() },
22
+ env,
23
23
  });
24
24
  const help = `${stdout}\n${stderr}`;
25
25
  return REQUIRED_RUN_FLAGS.every((flag) => help.includes(flag));