@nowcrew/daemon 0.6.98-beta.6 → 0.6.98-beta.8

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 (42) hide show
  1. package/README.md +29 -20
  2. package/dist/automatic-daemon-installer.js +15 -11
  3. package/dist/automatic-service-capture.js +27 -0
  4. package/dist/computer-main.js +0 -0
  5. package/dist/computer-service.js +30 -5
  6. package/dist/console.js +17 -2
  7. package/dist/execution-journal-lock.js +51 -2
  8. package/dist/execution-protocol.js +2 -0
  9. package/dist/execution-runner.js +19 -13
  10. package/dist/host-execution-coordinator.js +10 -0
  11. package/dist/local-executor.js +8 -1
  12. package/dist/machine-info.js +6 -1
  13. package/dist/machine-runtime-environment.js +1 -0
  14. package/dist/main.js +0 -0
  15. package/dist/managed-service-lifecycle.js +10 -0
  16. package/dist/marketplace-controller.js +21 -8
  17. package/dist/marketplace-maintenance-bridge.js +79 -0
  18. package/dist/marketplace-maintenance-protocol.js +40 -0
  19. package/dist/marketplace-serve.js +4 -2
  20. package/dist/project-skills/execution-projection.js +4 -5
  21. package/dist/project-skills/reconciler.js +8 -9
  22. package/dist/project-skills/scanner.js +9 -2
  23. package/dist/project-skills/source-directory.js +13 -0
  24. package/dist/runtime-observation.js +219 -0
  25. package/dist/runtime-tool-update-bridge.js +126 -0
  26. package/dist/runtime-tool-update-controller.js +151 -0
  27. package/dist/runtime-tool-update-protocol.js +24 -0
  28. package/dist/runtime-tool-update-serve.js +54 -0
  29. package/dist/runtimes/claude-observation-runner.js +55 -0
  30. package/dist/runtimes/claude-thread-runner.js +17 -3
  31. package/dist/runtimes/claude.js +5 -3
  32. package/dist/runtimes/codex-app-server-runner.js +16 -2
  33. package/dist/runtimes/deepseek-harness-runner.js +16 -0
  34. package/dist/runtimes/kimi-acp-runner.js +19 -0
  35. package/dist/runtimes/observation-context.js +18 -0
  36. package/dist/runtimes/observation-mapper.js +314 -0
  37. package/dist/runtimes/opencode-runner.js +18 -4
  38. package/dist/runtimes/pi-runner.js +18 -1
  39. package/dist/runtimes/pi.js +54 -20
  40. package/dist/serve.js +10 -1
  41. package/dist/token.js +4 -1
  42. package/package.json +9 -9
@@ -0,0 +1,151 @@
1
+ import { RuntimeToolRequestSchema, RuntimeToolResponseSchema } from "./runtime-tool-update-protocol.js";
2
+ const finalStates = new Set(["completed", "failed", "unknown", "cancelled"]);
3
+ const phaseRank = (state) => ({ queued: 0, preflight: 1, installing: 2, verifying: 3, completed: 4, failed: 4, unknown: 4, cancelled: 4 })[state];
4
+ function advancesProgress(previous, next) {
5
+ if (finalStates.has(previous.state) || finalStates.has(next.state)
6
+ || next.operationId !== previous.operationId || JSON.stringify(next.targets) !== JSON.stringify(previous.targets)
7
+ || next.currentIndex < previous.currentIndex || next.currentIndex >= previous.targets.length
8
+ || (next.currentIndex === previous.currentIndex && phaseRank(next.state) < phaseRank(previous.state)))
9
+ return false;
10
+ return previous.items.every((item, index) => {
11
+ const candidate = next.items[index];
12
+ if (!candidate || candidate.runtime !== item.runtime)
13
+ return false;
14
+ return finalStates.has(item.state) ? candidate.state === item.state && candidate.errorCode === item.errorCode
15
+ : phaseRank(candidate.state) >= phaseRank(item.state);
16
+ });
17
+ }
18
+ export function createRuntimeToolUpdateController(deps) {
19
+ const entries = new Map();
20
+ let current = null;
21
+ let stopped = false;
22
+ let orphaned = false;
23
+ const now = deps.now ?? Date.now;
24
+ const date = () => new Date(now()).toISOString();
25
+ const wait = deps.wait ?? (() => new Promise(resolve => setTimeout(resolve, 500)));
26
+ const fail = (error) => ({ ok: false, error });
27
+ const result = (data) => ({ ok: true, data });
28
+ const set = (entry, patch) => { entry.operation = { ...entry.operation, ...patch, updatedAt: date() }; };
29
+ async function execute(entry) {
30
+ const deadline = now() + 10 * 60_000;
31
+ let acceptingProgress = false;
32
+ let lease = null;
33
+ try {
34
+ while (!stopped && entry.operation.state === "queued" && now() < deadline && !lease) {
35
+ lease = await deps.acquire();
36
+ if (!lease)
37
+ await wait();
38
+ }
39
+ if (entry.operation.state === "cancelled")
40
+ return;
41
+ if (!lease || stopped || now() >= deadline) {
42
+ set(entry, { state: "failed", errorCode: "runtime_busy" });
43
+ return;
44
+ }
45
+ set(entry, { state: "preflight" });
46
+ // Mark unsafe before spawning: an exception or lost response cannot authorize another writer.
47
+ entry.processStopped = false;
48
+ acceptingProgress = true;
49
+ const output = await deps.run(entry.request, raw => {
50
+ if (!acceptingProgress)
51
+ return;
52
+ const parsed = RuntimeToolResponseSchema.safeParse(raw);
53
+ if (parsed.success && parsed.data.operation && advancesProgress(entry.operation, parsed.data.operation))
54
+ entry.operation = parsed.data.operation;
55
+ }, lease.protectProcessGroup);
56
+ acceptingProgress = false;
57
+ const data = RuntimeToolResponseSchema.parse(output.data);
58
+ entry.processStopped = output.processStopped;
59
+ if (!data.operation || data.operation.operationId !== entry.operation.operationId
60
+ || JSON.stringify(data.operation.targets) !== JSON.stringify(entry.request.targets)
61
+ || data.operation.currentIndex < entry.operation.currentIndex || !finalStates.has(data.operation.state))
62
+ throw new Error("operation_mismatch");
63
+ entry.operation = data.operation;
64
+ if (!entry.processStopped)
65
+ set(entry, { state: "unknown", errorCode: "operation_unknown" });
66
+ }
67
+ catch {
68
+ acceptingProgress = false;
69
+ set(entry, { state: "unknown", errorCode: "operation_unknown" });
70
+ }
71
+ finally {
72
+ acceptingProgress = false;
73
+ // Retain the barrier if process-group termination could not be proved.
74
+ if (entry.processStopped) {
75
+ try {
76
+ await lease?.release();
77
+ }
78
+ catch {
79
+ entry.processStopped = false;
80
+ set(entry, { state: "unknown", errorCode: "operation_unknown" });
81
+ }
82
+ }
83
+ }
84
+ }
85
+ return {
86
+ async handle(raw) {
87
+ const parsed = RuntimeToolRequestSchema.safeParse(raw);
88
+ if (!parsed.success || stopped)
89
+ return fail("invalid_request");
90
+ const request = parsed.data;
91
+ if (request.action === "inspect") {
92
+ try {
93
+ const data = RuntimeToolResponseSchema.parse((await deps.run(request)).data);
94
+ return data.snapshot ? result(data) : fail("inspection_failed");
95
+ }
96
+ catch {
97
+ return fail("inspection_failed");
98
+ }
99
+ }
100
+ const entry = entries.get(request.operationId);
101
+ if (request.action === "start") {
102
+ if (entry)
103
+ return result({ operation: entry.operation });
104
+ if (orphaned || [...entries.values()].some(x => x.operation.state === "unknown"))
105
+ return fail("operation_unknown");
106
+ if (current)
107
+ return fail("runtime_busy");
108
+ if (entries.size >= 100)
109
+ return fail("operation_limit");
110
+ if (new Set(request.targets.map(t => t.installation.runtime)).size !== request.targets.length)
111
+ return fail("invalid_request");
112
+ const operation = { operationId: request.operationId, state: "queued", currentIndex: 0, targets: request.targets,
113
+ items: request.targets.map(t => ({ runtime: t.installation.runtime, state: "queued", errorCode: null })), updatedAt: date(), errorCode: null };
114
+ const next = { operation, request, processStopped: true };
115
+ entries.set(request.operationId, next);
116
+ current = execute(next).finally(() => { current = null; });
117
+ return result({ operation });
118
+ }
119
+ if (!entry) {
120
+ orphaned = true;
121
+ return fail("operation_unknown");
122
+ }
123
+ if (request.action === "status")
124
+ return result({ operation: entry.operation });
125
+ if (request.action === "cancel") {
126
+ if (entry.operation.state !== "queued")
127
+ return fail("already_started");
128
+ set(entry, { state: "cancelled", items: entry.operation.items.map(x => ({ ...x, state: "cancelled" })) });
129
+ return result({ operation: entry.operation });
130
+ }
131
+ if (!entry.processStopped || current)
132
+ return fail("operation_unknown");
133
+ try {
134
+ const output = await deps.run({ action: "inspect", runner: entry.request.runner });
135
+ const snapshot = RuntimeToolResponseSchema.parse(output.data).snapshot;
136
+ if (!snapshot || !output.processStopped)
137
+ return fail("operation_unknown");
138
+ const matches = entry.operation.targets.every(target => snapshot.tools.some(tool => tool.runtime === target.installation.runtime
139
+ && tool.version === target.targetVersion && tool.path === target.installation.path && tool.source === target.installation.source
140
+ && tool.prefix === target.installation.prefix && tool.brewPath === target.installation.brewPath && tool.automatic));
141
+ set(entry, { state: matches ? "completed" : "failed", errorCode: matches ? null : "verification_failed", snapshot,
142
+ items: entry.operation.items.map(x => ({ ...x, state: matches ? "completed" : "failed", errorCode: matches ? null : "verification_failed" })) });
143
+ return result({ operation: entry.operation, snapshot });
144
+ }
145
+ catch {
146
+ return fail("inspection_failed");
147
+ }
148
+ },
149
+ async stop() { stopped = true; await current; },
150
+ };
151
+ }
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ export const RUNTIME_TOOL_UPDATES_CAPABILITY = "runtime_tool_updates_v1";
3
+ const boundedPath = z.string().min(1).max(4096);
4
+ export const RuntimeToolRunnerSchema = z.object({ releaseId: z.string().regex(/^[a-f0-9]{64}$/), sha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
5
+ export const RuntimeToolInstallationSchema = z.object({
6
+ runtime: z.enum(["codex", "claude"]), path: boundedPath, realPath: boundedPath,
7
+ version: z.string().max(100).nullable(), source: z.enum(["npm", "homebrew", "native", "unknown"]),
8
+ nodeVersion: z.string().max(100).nullable(), nodePath: boundedPath.nullable(), npmPath: boundedPath.nullable(), prefix: boundedPath.nullable(),
9
+ brewPath: boundedPath.nullable(), brewKind: z.enum(["formula", "cask"]).nullable(), brewName: z.enum(["codex", "claude-code"]).nullable(),
10
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/), alternatives: z.array(boundedPath).max(32), automatic: z.boolean(), reason: z.string().max(100).nullable(),
11
+ }).strict();
12
+ export const RuntimeToolSnapshotSchema = z.object({ checkedAt: z.string().datetime(), tools: z.array(RuntimeToolInstallationSchema).max(2) }).strict();
13
+ export const RuntimeToolTargetSchema = z.object({ installation: RuntimeToolInstallationSchema, targetVersion: z.string().regex(/^\d+\.\d+\.\d+$/).max(100) }).strict();
14
+ export const RuntimeToolStateSchema = z.enum(["queued", "preflight", "installing", "verifying", "completed", "failed", "unknown", "cancelled"]);
15
+ export const RuntimeToolOperationSchema = z.object({ operationId: z.string().uuid(), state: RuntimeToolStateSchema, currentIndex: z.number().int().min(0).max(2),
16
+ targets: z.array(RuntimeToolTargetSchema).min(1).max(2), items: z.array(z.object({ runtime: z.enum(["codex", "claude"]), state: RuntimeToolStateSchema, errorCode: z.string().max(100).nullable() }).strict()).max(2),
17
+ updatedAt: z.string().datetime(), errorCode: z.string().max(100).nullable(), snapshot: RuntimeToolSnapshotSchema.optional(),
18
+ }).strict();
19
+ export const RuntimeToolRequestSchema = z.discriminatedUnion("action", [
20
+ z.object({ action: z.literal("inspect"), runner: RuntimeToolRunnerSchema }).strict(),
21
+ z.object({ action: z.literal("start"), operationId: z.string().uuid(), targets: z.array(RuntimeToolTargetSchema).min(1).max(2), runner: RuntimeToolRunnerSchema }).strict(),
22
+ ...["status", "cancel", "verify"].map(action => z.object({ action: z.literal(action), operationId: z.string().uuid() }).strict()),
23
+ ]);
24
+ export const RuntimeToolResponseSchema = z.object({ snapshot: RuntimeToolSnapshotSchema.optional(), operation: RuntimeToolOperationSchema.optional() }).strict();
@@ -0,0 +1,54 @@
1
+ import { prepareDaemonRestart } from "./daemon-updater.js";
2
+ import { createRuntimeToolUpdateController } from "./runtime-tool-update-controller.js";
3
+ import { augmentedPath } from "./runtime-path.js";
4
+ import { runRuntimeToolBridge } from "./runtime-tool-update-bridge.js";
5
+ export async function acquireRuntimeToolLease(localSlots, host) {
6
+ const local = await prepareDaemonRestart({ localSlots });
7
+ if (!local.ok)
8
+ return null;
9
+ try {
10
+ const shared = await host.tryAcquireExclusiveExecution();
11
+ if (!shared) {
12
+ await local.release();
13
+ return null;
14
+ }
15
+ let released = false;
16
+ return { protectProcessGroup: async (pid) => {
17
+ if (!shared.protectProcessGroup)
18
+ throw new Error("lease protection unavailable");
19
+ await shared.protectProcessGroup(pid);
20
+ }, async release() { if (released)
21
+ return; await shared.release(); await local.release(); released = true; } };
22
+ }
23
+ catch (error) {
24
+ await local.release();
25
+ throw error;
26
+ }
27
+ }
28
+ export function createServeRuntimeToolUpdates(config, localSlots, host, acquireEnv, refresh) {
29
+ const controller = createRuntimeToolUpdateController({ acquire: () => acquireRuntimeToolLease(localSlots, host),
30
+ run: async (request, progress, protectProcessGroup) => {
31
+ const result = await runRuntimeToolBridge(config, request, async () => {
32
+ const env = await acquireEnv();
33
+ return { ...env, PATH: augmentedPath(env, {}, process.platform, "append") };
34
+ }, progress, { ...(protectProcessGroup ? { protectProcessGroup } : {}) });
35
+ if (request.action === "start" && result.processStopped)
36
+ refresh();
37
+ return result;
38
+ } });
39
+ return {
40
+ handle(raw, send) {
41
+ if (!raw || typeof raw !== "object" || !("type" in raw) || raw.type !== "runtime-tools:operation")
42
+ return false;
43
+ const { reqId, type: _type, ...request } = raw;
44
+ if (typeof reqId === "string") {
45
+ if (process.platform !== "linux" && process.platform !== "darwin")
46
+ send({ type: "fs:result", reqId, ok: false, error: "unsupported_platform" });
47
+ else
48
+ void controller.handle(request).then(result => send({ type: "fs:result", reqId, ...result })).catch(() => send({ type: "fs:result", reqId, ok: false, error: "operation_unknown" }));
49
+ }
50
+ return true;
51
+ },
52
+ stop: controller.stop,
53
+ };
54
+ }
@@ -0,0 +1,55 @@
1
+ /** 无线程 Claude 的短命观察桥:保留原命令/参数,不引入线程或原生会话约束。 */
2
+ import { createInterface } from "node:readline";
3
+ import { pathToFileURL } from "node:url";
4
+ import spawn from "cross-spawn";
5
+ import { z } from "zod";
6
+ import { createRuntimeObservationCapture } from "../runtime-observation.js";
7
+ import { createObservationMapper } from "./observation-mapper.js";
8
+ import { observeClaudeContext } from "./observation-context.js";
9
+ const Input = z.object({ bin: z.string().min(1), args: z.array(z.string()) }).strict();
10
+ export async function runClaudeObservation(bin, args) {
11
+ const capture = createRuntimeObservationCapture("claude");
12
+ const observer = createObservationMapper("claude", capture);
13
+ await observeClaudeContext(observer, args, args.at(-1) ?? "");
14
+ const child = spawn(bin, [...args], { cwd: process.cwd(), env: process.env, stdio: ["ignore", "pipe", "pipe"], detached: false });
15
+ const stopped = new Promise((resolve, reject) => {
16
+ child.once("error", reject);
17
+ child.once("close", (code, signal) => resolve(code ?? (signal ? 128 : 1)));
18
+ });
19
+ void stopped.catch(() => undefined);
20
+ const cancel = () => { child.kill("SIGTERM"); };
21
+ process.once("SIGTERM", cancel);
22
+ process.once("SIGINT", cancel);
23
+ try {
24
+ if (!child.stdout || !child.stderr)
25
+ throw new Error("Claude observation runner requires output streams");
26
+ child.stderr.pipe(process.stderr, { end: false });
27
+ for await (const line of createInterface({ input: child.stdout })) {
28
+ try {
29
+ observer.observe(JSON.parse(line));
30
+ }
31
+ catch { /* 原非 JSON 输出仍透传 */ }
32
+ process.stdout.write(`${line}\n`);
33
+ }
34
+ return await stopped;
35
+ }
36
+ finally {
37
+ observer.finish();
38
+ capture.finish();
39
+ process.off("SIGTERM", cancel);
40
+ process.off("SIGINT", cancel);
41
+ }
42
+ }
43
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
44
+ let raw = "";
45
+ for await (const chunk of process.stdin) {
46
+ raw += String(chunk);
47
+ if (Buffer.byteLength(raw) > 8 * 1024 * 1024)
48
+ throw new Error("Claude observation input too large");
49
+ }
50
+ const input = Input.parse(JSON.parse(raw));
51
+ runClaudeObservation(input.bin, input.args).then(code => { process.exitCode = code; }).catch(() => {
52
+ process.stderr.write("Claude observation runner failed\n");
53
+ process.exitCode = 1;
54
+ });
55
+ }
@@ -8,6 +8,9 @@ import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  import spawn from "cross-spawn";
9
9
  import { z } from "zod";
10
10
  import { prepareThreadDelivery, ThreadDeliveryColdStartRequired } from "../thread-input-delivery.js";
11
+ import { createRuntimeObservationCapture } from "../runtime-observation.js";
12
+ import { createObservationMapper } from "./observation-mapper.js";
13
+ import { observeClaudeContext } from "./observation-context.js";
11
14
  const InputSchema = z.object({ bin: z.string().min(1), args: z.array(z.string()),
12
15
  wakePrompt: z.string().min(1), sessionId: z.string().min(1).optional(), resume: z.boolean() }).strict();
13
16
  class PreflightError extends Error {
@@ -52,7 +55,7 @@ async function bounded(promise, milliseconds, label) {
52
55
  clearTimeout(timer);
53
56
  }
54
57
  }
55
- async function attempt(input, sessionId, resume, options) {
58
+ async function attempt(input, sessionId, resume, options, observer) {
56
59
  const proofDir = await mkdtemp(join(tmpdir(), "nowwork-claude-session-"));
57
60
  const proofPath = join(proofDir, "proof.json");
58
61
  const nonce = randomUUID();
@@ -182,6 +185,7 @@ async function attempt(input, sessionId, resume, options) {
182
185
  // work is outstanding; background shells must not hold it open forever.
183
186
  if (event.type === "result")
184
187
  sawResult = pendingAgents.size === 0;
188
+ observer.observe(event);
185
189
  output(event);
186
190
  }).catch(error => { fail(error instanceof Error ? error : new Error("claude_event_failed")); void stop().catch(fail); });
187
191
  });
@@ -207,6 +211,7 @@ async function attempt(input, sessionId, resume, options) {
207
211
  if (resume)
208
212
  output({ type: "nowwork.native_resume", runtime: "claude", session_id: sessionId });
209
213
  submitted = true;
214
+ await observeClaudeContext(observer, input.args, delivery.prompt);
210
215
  await send({ type: "user", session_id: "", uuid: userId, parent_tool_use_id: null,
211
216
  message: { role: "user", content: delivery.prompt } });
212
217
  await bounded(accepted.promise, options.ackTimeoutMs ?? 30_000, "claude_user_message_not_acknowledged");
@@ -237,16 +242,25 @@ async function attempt(input, sessionId, resume, options) {
237
242
  }
238
243
  }
239
244
  export async function runClaudeThread(input, options = {}) {
245
+ const capture = createRuntimeObservationCapture("claude", options.env ?? process.env, options.output);
246
+ try {
247
+ return await runClaudeObserved(input, options, capture);
248
+ }
249
+ finally {
250
+ capture.finish();
251
+ }
252
+ }
253
+ async function runClaudeObserved(input, options, capture) {
240
254
  const sessionId = input.sessionId ?? randomUUID();
241
255
  try {
242
- return await attempt(input, sessionId, input.resume, options);
256
+ return await attempt(input, sessionId, input.resume, options, createObservationMapper("claude", capture, "attempt:1"));
243
257
  }
244
258
  catch (error) {
245
259
  // The failed attempt never received a business user turn or entered its
246
260
  // model/tool loop. Native startup hooks may run again on cold recovery.
247
261
  if (!input.resume || !(error instanceof PreflightError || error instanceof ThreadDeliveryColdStartRequired))
248
262
  throw error;
249
- return attempt(input, randomUUID(), false, options);
263
+ return attempt(input, randomUUID(), false, options, createObservationMapper("claude", capture, "attempt:2"));
250
264
  }
251
265
  }
252
266
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
@@ -7,6 +7,7 @@ import { posix, win32 } from "node:path";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  // cross-spawn:win32 上 npm CLI 是 .cmd shim,node 原生 spawn 不带 shell 无法执行(ENOENT/EINVAL)
9
9
  import spawn from "cross-spawn";
10
+ import { observationPolicyFromEnvironment } from "../runtime-observation.js";
10
11
  // Claude Code 原生 --effort 档位(claude 2.1.196 实测:--help 与非法值告警均枚举这五档)。
11
12
  // 白名单外的值(含 "default" 与 codex 专属档)回落 CLAUDE_DEFAULT_EFFORT,脏数据不影响启动。
12
13
  export const CLAUDE_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
@@ -280,14 +281,15 @@ export function buildClaudeArgs(input) {
280
281
  }
281
282
  export function buildClaudeLaunch(input) {
282
283
  const args = buildClaudeArgs(input);
283
- if (!input.env.CREW_THREAD_ROOT?.trim())
284
+ const thread = Boolean(input.env.CREW_THREAD_ROOT?.trim());
285
+ if (!thread && !observationPolicyFromEnvironment(input.env))
284
286
  return { command: input.bin, args, cwd: input.cwd, env: input.env };
285
287
  const source = import.meta.url.endsWith(".ts");
286
288
  return { command: process.execPath,
287
289
  args: [...(source ? ["--import", pathToFileURL(createRequire(import.meta.url).resolve("tsx/esm")).href] : []),
288
- fileURLToPath(new URL(`./claude-thread-runner.${source ? "ts" : "js"}`, import.meta.url))],
290
+ fileURLToPath(new URL(`./${thread ? "claude-thread-runner" : "claude-observation-runner"}.${source ? "ts" : "js"}`, import.meta.url))],
289
291
  cwd: input.cwd, env: input.env,
290
- stdinText: JSON.stringify({ bin: input.bin, args: args.slice(0, -1), wakePrompt: input.wakePrompt,
292
+ stdinText: JSON.stringify(!thread ? { bin: input.bin, args } : { bin: input.bin, args: args.slice(0, -1), wakePrompt: input.wakePrompt,
291
293
  ...(input.sessionId ? { sessionId: input.sessionId } : {}), resume: input.resume === true }) };
292
294
  }
293
295
  export function spawnClaude(input) {
@@ -11,6 +11,8 @@ import { decideTurnRetry, itemMakesTurnUnsafe } from "./codex-turn-retry.js";
11
11
  import { startFirstProgressWatchdog } from "./progress-watchdog.js";
12
12
  import { prepareThreadDelivery, ThreadDeliveryColdStartRequired } from "../thread-input-delivery.js";
13
13
  import { codexExecutionPolicyArgs } from "./codex-execution-policy.js";
14
+ import { createRuntimeObservationCapture } from "../runtime-observation.js";
15
+ import { createObservationMapper } from "./observation-mapper.js";
14
16
  const RunnerInputSchema = z.object({
15
17
  systemPrompt: z.string().min(1),
16
18
  wakePrompt: z.string().min(1),
@@ -443,7 +445,8 @@ async function stopChildTree(child) {
443
445
  throw new Error(`Codex app-server process tree ${child.pid ?? "unknown"} did not exit`);
444
446
  }
445
447
  }
446
- async function runCodexAppServerAttempt(bin, input, attempt, initializeTimeoutMs, resumeEventSessionId) {
448
+ async function runCodexAppServerAttempt(bin, input, attempt, initializeTimeoutMs, resumeEventSessionId, capture) {
449
+ const observer = createObservationMapper("codex", capture, `attempt:${attempt}`);
447
450
  const attemptStartedAt = Date.now();
448
451
  const child = spawn(bin, codexAppServerArgs({
449
452
  ...(input.projectRootMarkers === undefined ? {} : { projectRootMarkers: input.projectRootMarkers }),
@@ -483,6 +486,7 @@ async function runCodexAppServerAttempt(bin, input, attempt, initializeTimeoutMs
483
486
  let firstProgress = startFirstProgressWatchdog(() => undefined);
484
487
  firstProgress.stop();
485
488
  const rpc = new CodexRpcClient(child, input.effectivePermission, async (method, params) => {
489
+ observer.observe(params, method);
486
490
  if (method === "thread/tokenUsage/updated") {
487
491
  lastUsage = params.tokenUsage;
488
492
  }
@@ -625,6 +629,7 @@ async function runCodexAppServerAttempt(bin, input, attempt, initializeTimeoutMs
625
629
  });
626
630
  activeStage = "model_init";
627
631
  stageStartedAt = Date.now();
632
+ observer.context({ systemPrompt: input.systemPrompt, prompt: delivery.prompt });
628
633
  const started = await rpc.request("turn/start", {
629
634
  threadId,
630
635
  input: [
@@ -712,6 +717,15 @@ async function runCodexAppServerAttempt(bin, input, attempt, initializeTimeoutMs
712
717
  }
713
718
  }
714
719
  export async function runCodexAppServer(bin, options = {}) {
720
+ const capture = createRuntimeObservationCapture("codex");
721
+ try {
722
+ return await runCodexObserved(bin, options, capture);
723
+ }
724
+ finally {
725
+ capture.finish();
726
+ }
727
+ }
728
+ async function runCodexObserved(bin, options, capture) {
715
729
  const input = await readRunnerInput();
716
730
  const initializeTimeoutMs = Math.min(options.initializeTimeoutMs ?? INITIALIZE_RPC_TIMEOUT_MS, INITIALIZE_RPC_TIMEOUT_MS);
717
731
  const turnRetryDelayMs = options.turnRetryDelayMs ?? TRANSIENT_TURN_RETRY_DELAY_MS;
@@ -721,7 +735,7 @@ export async function runCodexAppServer(bin, options = {}) {
721
735
  let attemptInput = input;
722
736
  const resumeEventSessionId = input.resume ? input.sessionId : undefined;
723
737
  for (let attempt = 1;; attempt += 1) {
724
- const result = await runCodexAppServerAttempt(bin, attemptInput, attempt, initializeTimeoutMs, resumeEventSessionId);
738
+ const result = await runCodexAppServerAttempt(bin, attemptInput, attempt, initializeTimeoutMs, resumeEventSessionId, capture);
725
739
  if (result.restartCold) {
726
740
  if (coldRestarted)
727
741
  return result.code;
@@ -11,6 +11,8 @@ import { deepSeekHarnessLaunch } from "./deepseek-harness-launch.js";
11
11
  import { prepareHarnessProfile } from "./deepseek-harness-profile.js";
12
12
  import { mapAcpUpdate } from "./kimi-acp-runner.js";
13
13
  import { prepareThreadDelivery } from "../thread-input-delivery.js";
14
+ import { createRuntimeObservationCapture } from "../runtime-observation.js";
15
+ import { createObservationMapper } from "./observation-mapper.js";
14
16
  const absolutePath = z.string().refine(isAbsolute, "must be an absolute path");
15
17
  export const HarnessInputSchema = z
16
18
  .object({
@@ -45,6 +47,17 @@ async function settleWithin(promise, ms) {
45
47
  }
46
48
  }
47
49
  export async function runHarness(input, bin, patchPath) {
50
+ const capture = createRuntimeObservationCapture("deepseek-harness");
51
+ const observer = createObservationMapper("deepseek-harness", capture);
52
+ try {
53
+ return await runHarnessObserved(input, bin, patchPath, observer);
54
+ }
55
+ finally {
56
+ observer.finish();
57
+ capture.finish();
58
+ }
59
+ }
60
+ async function runHarnessObserved(input, bin, patchPath, observer) {
48
61
  const delivery = await prepareThreadDelivery({
49
62
  env: process.env,
50
63
  resumed: false,
@@ -115,6 +128,7 @@ export async function runHarness(input, bin, patchPath) {
115
128
  .onNotification(methods.client.session.update, async ({ params }) => {
116
129
  if (params.sessionId !== sessionId)
117
130
  return;
131
+ observer.observe(params);
118
132
  for (const event of mapAcpUpdate("deepseek-harness", params.update))
119
133
  await emit(event);
120
134
  });
@@ -141,6 +155,7 @@ export async function runHarness(input, bin, patchPath) {
141
155
  throw new Error("Harness session unavailable");
142
156
  await emit({ type: "thread.started", thread_id: sessionId });
143
157
  stage = "prompt";
158
+ observer.context({ systemPrompt: input.systemPrompt, prompt: delivery.prompt });
144
159
  const response = await ctx.request(methods.agent.session.prompt, {
145
160
  sessionId,
146
161
  prompt: [{ type: "text", text: delivery.prompt }],
@@ -155,6 +170,7 @@ export async function runHarness(input, bin, patchPath) {
155
170
  }
156
171
  return response;
157
172
  });
173
+ observer.observe({ type: "nowwork.acp.result", sessionId, ...result });
158
174
  const usage = result.usage;
159
175
  if (!cancelled)
160
176
  await emit({
@@ -12,6 +12,8 @@ import { augmentedPath } from "../runtime-path.js";
12
12
  import { prepareThreadDelivery } from "../thread-input-delivery.js";
13
13
  import { startFirstProgressWatchdog } from "./progress-watchdog.js";
14
14
  import { assertKimiLegacyPromptFits, buildKimiArgs } from "./kimi.js";
15
+ import { createRuntimeObservationCapture } from "../runtime-observation.js";
16
+ import { createObservationMapper } from "./observation-mapper.js";
15
17
  const ERROR_MESSAGE_CAP = 2_000;
16
18
  // macOS launchd cold-starts ACP runtimes materially slower than an interactive
17
19
  // shell. DeepSeek Harness was measured at ~4.4s before returning initialize
@@ -322,6 +324,18 @@ export async function probeKimiAcp(options, spawnProcess = spawn) {
322
324
  }
323
325
  }
324
326
  export async function runKimiAcp(requestedOptions) {
327
+ const provider = requestedOptions.provider ?? "kimi";
328
+ const capture = createRuntimeObservationCapture(provider);
329
+ const observer = createObservationMapper(provider, capture);
330
+ try {
331
+ return await runKimiObserved(requestedOptions, observer, capture);
332
+ }
333
+ finally {
334
+ observer.finish();
335
+ capture.finish();
336
+ }
337
+ }
338
+ async function runKimiObserved(requestedOptions, observer, capture) {
325
339
  // Until this adapter verifies native restoration, thread-bound runs are cold.
326
340
  const options = process.env.CREW_THREAD_ROOT ? { ...requestedOptions, resume: false } : requestedOptions;
327
341
  const provider = options.provider ?? "kimi";
@@ -364,6 +378,7 @@ export async function runKimiAcp(requestedOptions) {
364
378
  const app = client({ name: `nowcrew-daemon-${provider}` })
365
379
  .onRequest(methods.client.session.requestPermission, ({ params }) => selectKimiPermission(params, permission))
366
380
  .onNotification(methods.client.session.update, async ({ params }) => {
381
+ observer.observe(params);
367
382
  acpSemanticProgress = true;
368
383
  firstProgress.observe();
369
384
  for (const event of mapAcpUpdate(provider, params.update))
@@ -433,6 +448,7 @@ export async function runKimiAcp(requestedOptions) {
433
448
  progressTimedOut = true;
434
449
  void cancel();
435
450
  });
451
+ observer.context({ prompt });
436
452
  return nextContext.request(methods.agent.session.prompt, {
437
453
  sessionId,
438
454
  prompt: [{ type: "text", text: prompt }],
@@ -443,6 +459,7 @@ export async function runKimiAcp(requestedOptions) {
443
459
  process.stderr.write(`${displayName} produced no semantic progress within the startup window\n`);
444
460
  return 1;
445
461
  }
462
+ observer.observe({ type: "nowwork.acp.result", sessionId, ...result });
446
463
  const usage = result.usage;
447
464
  await jsonLine({
448
465
  type: "turn.completed",
@@ -464,6 +481,8 @@ export async function runKimiAcp(requestedOptions) {
464
481
  return 1;
465
482
  }
466
483
  if (provider === "kimi" && !acpSemanticProgress && isKimiAuthenticationRequired(error)) {
484
+ capture.observe({ observationId: "fallback", type: "event", phase: "event", name: "capture.unsupported",
485
+ unavailable: ["kimi_legacy_fallback_events"] });
467
486
  firstProgress.stop();
468
487
  await stopChild(child);
469
488
  process.stderr.write("Kimi ACP requires account login; falling back to configured CLI provider transport\n");
@@ -0,0 +1,18 @@
1
+ import { readFile } from "node:fs/promises";
2
+ /** 只观察实际发给 runtime 的 prompt;不读取配置、环境变量或凭据文件。 */
3
+ export async function observeClaudeContext(observer, args, prompt) {
4
+ if (!observer.enabled)
5
+ return;
6
+ const at = args.indexOf("--append-system-prompt-file");
7
+ const path = at >= 0 ? args[at + 1] : undefined;
8
+ if (!path) {
9
+ observer.context({ prompt }, ["system_prompt"]);
10
+ return;
11
+ }
12
+ try {
13
+ observer.context({ systemPrompt: await readFile(path, "utf8"), prompt });
14
+ }
15
+ catch {
16
+ observer.context({ prompt }, ["system_prompt"]);
17
+ }
18
+ }