@nowcrew/daemon 0.6.101-beta.4 → 0.6.101-beta.6

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 (59) hide show
  1. package/dist/cloud-report-upload.js +1 -10
  2. package/dist/computer-main.js +0 -0
  3. package/dist/execution-journal.js +3 -1
  4. package/dist/execution-protocol.js +1 -1
  5. package/dist/execution-runner.js +4 -1
  6. package/dist/local-execution-prompt.js +8 -3
  7. package/dist/local-executor.js +78 -55
  8. package/dist/local-memory/commit-telemetry.js +30 -0
  9. package/dist/local-memory/execution-workspace.js +117 -0
  10. package/dist/local-memory/full-index-search.js +47 -0
  11. package/dist/local-memory/index-budget.js +9 -3
  12. package/dist/local-memory/initialization-identity.js +36 -0
  13. package/dist/local-memory/inventory-cli.js +52 -8
  14. package/dist/local-memory/inventory-source.js +15 -8
  15. package/dist/local-memory/inventory-v2.js +362 -0
  16. package/dist/local-memory/legacy-adapter.js +233 -0
  17. package/dist/local-memory/migration-access.js +242 -0
  18. package/dist/local-memory/migration-cli.js +54 -0
  19. package/dist/local-memory/migration-io.js +199 -0
  20. package/dist/local-memory/migration-pending.js +9 -0
  21. package/dist/local-memory/migration-plan.js +432 -0
  22. package/dist/local-memory/migration-schema.js +58 -0
  23. package/dist/local-memory/migration-state-invariants.js +65 -0
  24. package/dist/local-memory/migration-store.js +414 -0
  25. package/dist/local-memory/migration-tool-entry.js +21 -0
  26. package/dist/local-memory/pending-query.js +5 -2
  27. package/dist/local-memory/pending-schema.js +1 -1
  28. package/dist/local-memory/pending.js +16 -2
  29. package/dist/local-memory/prompt.js +21 -5
  30. package/dist/local-memory/read-cli.js +98 -76
  31. package/dist/local-memory/release-artifact-guard.js +55 -0
  32. package/dist/local-memory/rollout.js +79 -11
  33. package/dist/local-memory/runtime.js +191 -17
  34. package/dist/local-memory/source-path.js +13 -0
  35. package/dist/local-memory/storage-format.js +249 -0
  36. package/dist/local-memory/write.js +190 -21
  37. package/dist/local-memory/writer-mode.js +13 -0
  38. package/dist/local-memory-diagnostics.js +96 -15
  39. package/dist/local-memory-telemetry.js +31 -3
  40. package/dist/machine-info.js +3 -0
  41. package/dist/main.js +0 -0
  42. package/dist/marketplace-protocol.js +1 -1
  43. package/dist/marketplace-remote.js +1 -1
  44. package/dist/marketplace-runner.js +1 -1
  45. package/dist/memory-migration-controller.js +89 -0
  46. package/dist/memory-migration-inspect.js +116 -0
  47. package/dist/memory-migration-journal.js +14 -0
  48. package/dist/memory-migration-protocol.js +14 -0
  49. package/dist/memory-migration-runtime.js +367 -0
  50. package/dist/memory-prune-diagnostics.js +74 -4
  51. package/dist/message-file-preview.js +11 -1
  52. package/dist/prompt.js +9 -17
  53. package/dist/runner.js +1 -1
  54. package/dist/runtimes/claude-thread-runner.js +25 -4
  55. package/dist/serve.js +38 -3
  56. package/dist/token.js +1 -0
  57. package/dist/workspace-control-handler.js +16 -3
  58. package/dist/workspace.js +23 -4
  59. package/package.json +9 -10
package/dist/serve.js CHANGED
@@ -14,6 +14,7 @@ import { reconcileExecutionJournal } from "./execution-recovery.js";
14
14
  import { initReleaseSlog, reportDaemonConnectionClose, reportReleaseError } from "./release-channel-guard.js";
15
15
  import { handleWorkspaceControlRequest } from "./workspace-control-handler.js";
16
16
  import { inspectRaftWorkspace, importRaftWorkspace } from "./workspace-import.js";
17
+ import { withMemoryAccess } from "./local-memory/migration-access.js";
17
18
  import { normalizeScheduledContext } from "./scheduled-report.js";
18
19
  import { formatDaemonLogLine } from "./log-format.js";
19
20
  import { reportAgentRunComplete } from "./scheduled-run-report.js";
@@ -51,6 +52,8 @@ import { createServeMarketplace } from "./marketplace-serve.js";
51
52
  import { createServeRuntimeToolUpdates } from "./runtime-tool-update-serve.js";
52
53
  import { buildControlPlaneUrl } from "./control-plane-url.js";
53
54
  import { resolveDaemonLocalStateRootFromEnv } from "./daemon-local-home.js";
55
+ import { createMemoryMigrationController } from "./memory-migration-controller.js";
56
+ import { createMemoryMigrationJournal, replayExecutionJournals } from "./memory-migration-journal.js";
54
57
  import { bindStorageServerIdentity, createStorageIdentityAdmission, } from "./storage-serve-adapter.js";
55
58
  export { buildControlPlaneUrl } from "./control-plane-url.js";
56
59
  // normalize.ts 的活动种类 → activity 枚举
@@ -76,6 +79,8 @@ export function serve(config, opts = {}) {
76
79
  let reconnectTimer = null;
77
80
  let stopPromise = null;
78
81
  let executionJournal;
82
+ let migrationExecutionJournal;
83
+ let migrationJournalReady = false;
79
84
  const injectedExecutionJournal = opts.execution?.journal;
80
85
  const agentMemory = opts.execution?.dependencies?.agentMemory
81
86
  ?? (config.agentMemory === null ? undefined : createAgentMemoryBridge(config.agentMemory));
@@ -90,6 +95,15 @@ export function serve(config, opts = {}) {
90
95
  startupGapMs: config.executionLimits.startupGapMs,
91
96
  });
92
97
  const localSlots = createSharedSlotManager(config.executionLimits);
98
+ const memoryMigrations = createMemoryMigrationController({ config, coordinator: hostCoordinator,
99
+ isAdmissionClosed: () => stopped || storageIdentityAdmission.isAdmissionClosed(),
100
+ journal: () => { if (!migrationJournalReady)
101
+ throw new Error("memory_migration_journal_unavailable"); return migrationExecutionJournal; }, send: frame => {
102
+ if (frame.type === "execution:completed")
103
+ completionRetransmitter.track(frame);
104
+ else if (ws?.readyState === WebSocket.OPEN)
105
+ ws.send(JSON.stringify(frame));
106
+ } });
93
107
  const sharedSlots = hostCoordinatedSlotManager(localSlots, hostCoordinator);
94
108
  const concurrencyTelemetry = createExecutionConcurrencyTelemetry(sharedSlots, {
95
109
  ...(opts.execution?.concurrencySnapshotIntervalMs === undefined
@@ -272,7 +286,7 @@ export function serve(config, opts = {}) {
272
286
  return null;
273
287
  };
274
288
  const sendSnapshot = async (reqId) => {
275
- const entries = (await executionJournal.replay()).map(snapshotEntry).filter((entry) => entry !== null);
289
+ const entries = (await replayExecutionJournals(executionJournal, migrationExecutionJournal)).map(snapshotEntry).filter((entry) => entry !== null);
276
290
  safeExecutionSend(ExecutionSnapshotSchema.parse({
277
291
  type: "execution:snapshot", protocolVersion: 1, reqId, entries,
278
292
  }));
@@ -354,6 +368,12 @@ export function serve(config, opts = {}) {
354
368
  machineRuntime.open(openedSocket, { capabilities: capabilities.machineHello, beforePublish: Promise.resolve(), connectionId });
355
369
  opts.onOpen?.(ws);
356
370
  void sendSnapshot(`reconnect-${randomUUID()}`);
371
+ // 普通回执不等待维护日志IO;两类记录分别重放到同一发送器。
372
+ void migrationExecutionJournal.replay().then(entries => {
373
+ for (const entry of entries)
374
+ if (entry.completion && !entry.completionAcknowledged)
375
+ completionRetransmitter.track(entry.completion);
376
+ }).catch(() => dslog("memory_migration.journal_unavailable", "维护回执重放失败,普通回执继续", { level: "ERROR" }));
357
377
  void executionJournal.replay()
358
378
  .then((entries) => {
359
379
  for (const entry of entries) {
@@ -433,7 +453,8 @@ export function serve(config, opts = {}) {
433
453
  return;
434
454
  if (frame.type === "execution:completion-ack") {
435
455
  try {
436
- await executionJournal.acknowledgeCompletion(frame.executionId);
456
+ const journal = await executionJournal.get(frame.executionId) ? executionJournal : migrationExecutionJournal;
457
+ await journal.acknowledgeCompletion(frame.executionId);
437
458
  const attempts = completionRetransmitter.acknowledge(frame.executionId);
438
459
  dslog("execution.completion_acknowledged", "execution completion ACK 已持久化", {
439
460
  execution_id: frame.executionId,
@@ -459,6 +480,8 @@ export function serve(config, opts = {}) {
459
480
  return;
460
481
  }
461
482
  if (frame.type === "execution:cancel") {
483
+ if (memoryMigrations.cancel(frame.executionId))
484
+ return;
462
485
  if (!knownExecutionHashes.has(frame.executionId)
463
486
  && !executionRuns.has(frame.executionId)
464
487
  && await executionJournal.get(frame.executionId) === null)
@@ -691,6 +714,7 @@ export function serve(config, opts = {}) {
691
714
  const execution = executeProtocol(config, spec, {
692
715
  ...opts.execution?.dependencies,
693
716
  machineEnvironment: machineRuntime.provider,
717
+ ...(memoryMigrations.getIdentity() === null ? {} : { controlIdentity: memoryMigrations.getIdentity() }),
694
718
  capabilities: capabilities.executionRunner,
695
719
  projectSkills: opts.execution?.dependencies?.projectSkills ?? initializedProjectSkills,
696
720
  abilityRelease: opts.execution?.dependencies?.abilityRelease ?? agentAbilityRuntime.materializer,
@@ -781,6 +805,8 @@ export function serve(config, opts = {}) {
781
805
  // ready 帧带 server 视角的 machineId/workspaceId → 作为后续所有日志的默认关联键
782
806
  const r = msg;
783
807
  setSlogDefaults({ machine_id: r.machineId, workspace_id: r.workspaceId });
808
+ if (r.workspaceId && r.machineId)
809
+ memoryMigrations.setIdentity({ workspaceId: r.workspaceId, machineId: r.machineId });
784
810
  // 旧 server 无此字段 → 空集合(daemon 保持全部旧行为)。ackSupported() 依赖它判断是否重试,
785
811
  // 必须在任何 republish() 之前就位;否则本轮 republish 看到空集合→不排重试→整套 ack/重连机制哑火。
786
812
  serverCapabilities = new Set(Array.isArray(r.serverCapabilities)
@@ -855,6 +881,8 @@ export function serve(config, opts = {}) {
855
881
  }
856
882
  catch { /* server 会按请求超时处理 */ } }))
857
883
  return;
884
+ if (await memoryMigrations.handle(msg))
885
+ return;
858
886
  if (await agentAbilityRuntime.tryHandleControlMessage(msg, serverCapabilities, (frame) => ws?.send(JSON.stringify(frame))))
859
887
  return;
860
888
  // 导入 raft agent 工作区:inspect 反填 name/description;import 复制用户内容
@@ -869,7 +897,7 @@ export function serve(config, opts = {}) {
869
897
  try {
870
898
  const data2 = req.type === "raft:inspect"
871
899
  ? await inspectRaftWorkspace(req.path)
872
- : await importRaftWorkspace(req.path, join(config.agentsRoot, req.handle));
900
+ : await withMemoryAccess(join(config.agentsRoot, req.handle), () => importRaftWorkspace(req.path, join(config.agentsRoot, req.handle)), { create: true });
873
901
  if (req.type === "raft:import") {
874
902
  log(`📦 已导入 raft 工作区 → ${req.handle}: 复制 ${data2.copied.length} 项`);
875
903
  }
@@ -1262,6 +1290,7 @@ export function serve(config, opts = {}) {
1262
1290
  return;
1263
1291
  // server 能力随连接失效;下个连接的 ready 帧重新声明(防降级重连后沿用过期能力)。
1264
1292
  serverCapabilities = new Set();
1293
+ memoryMigrations.clearIdentity();
1265
1294
  completionRetransmitter.pause();
1266
1295
  // 4001 = 控制面应用级「鉴权失败」关闭码(见 server control-plane.ts)。即使上面的
1267
1296
  // error 帧因 close 抢先而丢失,也能据关闭码识别这是凭证失效——退避拉满,不再每秒热循环。
@@ -1314,6 +1343,9 @@ export function serve(config, opts = {}) {
1314
1343
  writeStderr: (line) => process.stderr.write(line),
1315
1344
  });
1316
1345
  await runProjectSkillStartupCleanup(config.agentsRoot, executionJournal, dslog);
1346
+ migrationExecutionJournal = createMemoryMigrationJournal(config.agentsRoot);
1347
+ await migrationExecutionJournal.reconcileAfterRestart().then(() => { migrationJournalReady = true; })
1348
+ .catch(() => dslog("memory_migration.journal_unavailable", "迁移日志恢复失败,普通执行继续,迁移请求单独报错", { level: "ERROR" }));
1317
1349
  await connect();
1318
1350
  })();
1319
1351
  const stop = () => {
@@ -1331,6 +1363,7 @@ export function serve(config, opts = {}) {
1331
1363
  const webSocketClosed = closeWebSocketWithinDeadline(ws, deadline.signal);
1332
1364
  const pending = [
1333
1365
  machineRuntime.stop(),
1366
+ memoryMigrations.stop(),
1334
1367
  webSocketClosed,
1335
1368
  updateController.drain(),
1336
1369
  marketplace.stop(),
@@ -1350,6 +1383,8 @@ export function serve(config, opts = {}) {
1350
1383
  if (executionJournal !== undefined) {
1351
1384
  await executionJournal.close({ signal: deadline.signal });
1352
1385
  }
1386
+ if (migrationExecutionJournal !== undefined)
1387
+ await migrationExecutionJournal.close({ signal: deadline.signal });
1353
1388
  }
1354
1389
  finally {
1355
1390
  deadline.dispose();
package/dist/token.js CHANGED
@@ -7,6 +7,7 @@ export async function mintAgentToken(serverUrl, machineToken, handle, displayNam
7
7
  },
8
8
  // 把本轮唤醒的线程根钉到 per-launch 令牌:服务端据此让 task/消息默认绑/回当前线程。
9
9
  body: JSON.stringify({
10
+ memoryStateGuardVersion: 1,
10
11
  handle,
11
12
  ...(displayName ? { displayName } : {}),
12
13
  ...(options.wakeThreadRoot ? { wakeThreadRoot: options.wakeThreadRoot } : {}),
@@ -1,9 +1,22 @@
1
1
  /** 控制面文件/技能查看的按需处理,独立于执行生命周期。 */
2
- import { join } from "node:path";
2
+ import { lstat } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
3
4
  import { readSharedMessageFile } from "./message-file-preview.js";
4
5
  import { listWorkspace, readWorkspaceFile } from "./workspace-fs.js";
5
6
  import { listSkills } from "./skills.js";
6
7
  import { listRuntimeModels } from "./list-models.js";
8
+ import { withMemoryAccess } from "./local-memory/migration-access.js";
9
+ async function listProtectedWorkspace(root, path) {
10
+ try {
11
+ await lstat(root);
12
+ }
13
+ catch (error) {
14
+ if (error.code !== "ENOENT")
15
+ throw error;
16
+ return { root: resolve(root), path: path.replace(/^\/+/, ""), entries: [] };
17
+ }
18
+ return withMemoryAccess(root, () => listWorkspace(root, path));
19
+ }
7
20
  export async function handleWorkspaceControlRequest(raw, agentsRoot, registry, models = listRuntimeModels) {
8
21
  if (!raw || typeof raw !== "object")
9
22
  return null;
@@ -15,8 +28,8 @@ export async function handleWorkspaceControlRequest(raw, agentsRoot, registry, m
15
28
  try {
16
29
  const root = join(agentsRoot, request.handle);
17
30
  const data = request.type === "fs:read-shared" ? await readSharedMessageFile(agentsRoot, raw, registry)
18
- : request.type === "fs:list" ? await listWorkspace(root, request.path)
19
- : request.type === "fs:read" ? await readWorkspaceFile(root, request.path)
31
+ : request.type === "fs:list" ? await listProtectedWorkspace(root, request.path)
32
+ : request.type === "fs:read" ? await withMemoryAccess(root, () => readWorkspaceFile(root, request.path))
20
33
  : request.type === "skills:list" ? await listSkills(request.runtime)
21
34
  : { models: await models(request.runtime ?? "") };
22
35
  return { type: "fs:result", reqId: request.reqId, ok: true, data };
package/dist/workspace.js CHANGED
@@ -8,12 +8,23 @@
8
8
  *
9
9
  * spawn runtime 时把 <ws>/.crew 置于 PATH 最前,于是 agent 的 `crew ...` 命中 wrapper。
10
10
  */
11
- import { mkdir, writeFile, readFile, chmod, access, lstat } from "node:fs/promises";
11
+ import { mkdir, writeFile, readFile, chmod, access, lstat, realpath } from "node:fs/promises";
12
12
  import { createHash, randomUUID } from "node:crypto";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath, pathToFileURL } from "node:url";
15
15
  import { createRequire } from "node:module";
16
16
  import { dslog } from "./slog.js";
17
+ import { MigrationStateSchema } from "./local-memory/migration-schema.js";
18
+ import { assertMigrationStateIntegrity } from "./local-memory/migration-state-invariants.js";
19
+ import { detectLocalMemoryStorageVersion } from "./local-memory/storage-format.js";
20
+ export class LocalMemoryWorkspacePrepareError extends Error {
21
+ cause;
22
+ constructor(code, cause) {
23
+ super(code);
24
+ this.name = "LocalMemoryWorkspacePrepareError";
25
+ this.cause = cause;
26
+ }
27
+ }
17
28
  /** 文件系统安全的 taskKey:仅留 [\w.-],其余转 _,截断,避免路径穿越/超长。 */
18
29
  export function safeKey(key) {
19
30
  return key.replace(/[^\w.-]+/g, "_").replace(/^[-.]+/, "").slice(0, 80) || "default";
@@ -49,7 +60,15 @@ async function hasLocalMemoryV2Marker(agentDir) {
49
60
  const stat = await lstat(markerPath);
50
61
  if (!stat.isFile() || stat.isSymbolicLink())
51
62
  return false;
52
- return (await readFile(markerPath, "utf8")) === "1\n";
63
+ if ((await readFile(markerPath, "utf8")) !== "1\n")
64
+ return false;
65
+ const root = await realpath(agentDir);
66
+ const state = MigrationStateSchema.parse(JSON.parse(await readFile(join(memoryDir, "migration.v1.json"), "utf8")));
67
+ assertMigrationStateIntegrity(state, state.identity);
68
+ return state.phase === "committed" && state.storageVersion === 2
69
+ && state.identity.rootFingerprint === createHash("sha256").update(root).digest("hex")
70
+ && state.identity.ownerIdentity === String((await lstat(root)).uid)
71
+ && detectLocalMemoryStorageVersion(await readFile(join(root, "MEMORY.md"), "utf8")) === 2;
53
72
  }
54
73
  catch {
55
74
  return false;
@@ -73,7 +92,7 @@ export async function prepareWorkspace(input) {
73
92
  }
74
93
  catch (error) {
75
94
  logMemoryPrepareFailure(input, "memory_seed_write", error);
76
- throw error;
95
+ throw new LocalMemoryWorkspacePrepareError("local_memory_workspace_seed_write_failed", error);
77
96
  }
78
97
  }
79
98
  let memory = "";
@@ -83,7 +102,7 @@ export async function prepareWorkspace(input) {
83
102
  }
84
103
  catch (error) {
85
104
  logMemoryPrepareFailure(input, "memory_read", error);
86
- throw error;
105
+ throw new LocalMemoryWorkspacePrepareError("local_memory_workspace_read_failed", error);
87
106
  }
88
107
  }
89
108
  // 系统提示词按 execution 隔离;省略 identity 的兼容调用每次使用随机路径。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nowcrew/daemon",
3
- "version": "0.6.101-beta.4",
3
+ "version": "0.6.101-beta.6",
4
4
  "type": "module",
5
5
  "description": "crew daemon — 运行在用户机器:拉起/管理 agent 进程,注入 crew CLI,归一化 runtime 事件",
6
6
  "license": "Apache-2.0",
@@ -18,14 +18,6 @@
18
18
  "publishConfig": {
19
19
  "access": "public"
20
20
  },
21
- "scripts": {
22
- "daemon": "pnpm --filter @nowcrew/cli build && tsx src/main.ts",
23
- "build": "tsc -p tsconfig.json",
24
- "prepublishOnly": "pnpm build && node ../scripts/daemon-release-artifact.mjs --strict-registry",
25
- "test": "vitest run",
26
- "test:release-critical": "vitest run test/automatic-daemon-installer.test.ts test/automatic-install-target.test.ts test/automatic-service-migration.test.ts test/computer-cli.test.ts test/computer-service.test.ts test/computer-setup-client.test.ts test/computer-setup-orchestration.test.ts test/computer-setup.test.ts test/daemon-release-version.test.ts test/daemon-update-controller.test.ts test/daemon-update-eligibility.test.ts test/daemon-updater.test.ts test/execution-protocol.test.ts test/machine-info.test.ts --maxWorkers=2 --minWorkers=1",
27
- "typecheck": "tsc --noEmit"
28
- },
29
21
  "dependencies": {
30
22
  "@agentclientprotocol/sdk": "1.2.1",
31
23
  "@nowcrew/cli": "0.4.17",
@@ -47,5 +39,12 @@
47
39
  "tsx": "^4.19.0",
48
40
  "typescript": "^5.6.0",
49
41
  "vitest": "^2.1.0"
42
+ },
43
+ "scripts": {
44
+ "daemon": "pnpm --filter @nowcrew/cli build && tsx src/main.ts",
45
+ "build": "tsc -p tsconfig.json",
46
+ "test": "vitest run",
47
+ "test:release-critical": "vitest run test/automatic-daemon-installer.test.ts test/automatic-install-target.test.ts test/automatic-service-migration.test.ts test/computer-cli.test.ts test/computer-service.test.ts test/computer-setup-client.test.ts test/computer-setup-orchestration.test.ts test/computer-setup.test.ts test/daemon-release-version.test.ts test/daemon-update-controller.test.ts test/daemon-update-eligibility.test.ts test/daemon-updater.test.ts test/execution-protocol.test.ts test/machine-info.test.ts --maxWorkers=2 --minWorkers=1",
48
+ "typecheck": "tsc --noEmit"
50
49
  }
51
- }
50
+ }