@nowcrew/daemon 0.6.88 → 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 (122) hide show
  1. package/README.md +66 -4
  2. package/dist/agent-ability/controller.js +11 -1
  3. package/dist/agent-ability/git-errors.js +22 -0
  4. package/dist/agent-ability/materializer.js +21 -10
  5. package/dist/agent-ability/resolver.js +12 -4
  6. package/dist/agent-environment-contract.js +55 -0
  7. package/dist/agent-environment-control.js +24 -0
  8. package/dist/agent-environment-execution.js +98 -0
  9. package/dist/agent-environments.js +275 -0
  10. package/dist/automatic-daemon-installer.js +51 -2
  11. package/dist/automatic-install-target.js +8 -0
  12. package/dist/computer-main.js +18 -0
  13. package/dist/computer-profile.js +17 -4
  14. package/dist/computer-setup-client.js +318 -0
  15. package/dist/computer-setup-orchestration.js +203 -0
  16. package/dist/computer-setup.js +244 -0
  17. package/dist/config.js +30 -12
  18. package/dist/console-formatter.js +3 -3
  19. package/dist/console.js +15 -2
  20. package/dist/daemon-update-eligibility.js +1 -1
  21. package/dist/execution-journal.js +9 -6
  22. package/dist/execution-protocol.js +1 -0
  23. package/dist/execution-runner.js +13 -8
  24. package/dist/i18n.js +19 -0
  25. package/dist/list-models.js +12 -12
  26. package/dist/local-execution-lease.js +22 -0
  27. package/dist/local-executor.js +57 -84
  28. package/dist/local-memory/candidate.js +43 -0
  29. package/dist/local-memory/index-budget.js +8 -0
  30. package/dist/local-memory/inventory-cli.js +61 -0
  31. package/dist/local-memory/inventory-preview.js +159 -0
  32. package/dist/local-memory/inventory-source.js +159 -0
  33. package/dist/local-memory/pending-match.js +29 -0
  34. package/dist/local-memory/pending-query.js +100 -0
  35. package/dist/local-memory/pending-schema.js +29 -0
  36. package/dist/local-memory/pending-source.js +126 -0
  37. package/dist/local-memory/pending.js +34 -84
  38. package/dist/local-memory/prompt.js +19 -12
  39. package/dist/local-memory/read-cli.js +97 -12
  40. package/dist/local-memory/rollout.js +82 -0
  41. package/dist/local-memory/runtime.js +23 -17
  42. package/dist/local-memory/work-log-execution.js +31 -0
  43. package/dist/local-memory/work-log.js +58 -0
  44. package/dist/local-memory/write.js +27 -58
  45. package/dist/local-runtime-environment.js +50 -0
  46. package/dist/machine-environment-cache.js +147 -0
  47. package/dist/machine-environment-contract.js +10 -0
  48. package/dist/machine-environment-control.js +27 -0
  49. package/dist/machine-environment-policy.js +75 -0
  50. package/dist/machine-environment-process.js +110 -0
  51. package/dist/machine-info.js +70 -25
  52. package/dist/machine-runtime-environment.js +189 -0
  53. package/dist/machine-shell-environment-capture.js +135 -0
  54. package/dist/machine-windows-environment-capture.js +215 -0
  55. package/dist/machine-windows-environment-script.js +158 -0
  56. package/dist/main.js +4 -69
  57. package/dist/marketplace-command.js +21 -0
  58. package/dist/marketplace-controller.js +80 -0
  59. package/dist/marketplace-protocol.js +38 -0
  60. package/dist/marketplace-remote.js +48 -0
  61. package/dist/marketplace-runner.js +235 -0
  62. package/dist/marketplace-serve.js +17 -0
  63. package/dist/marketplace-source.js +103 -0
  64. package/dist/message-file-preview.js +246 -0
  65. package/dist/pre-admission-rejection.js +64 -0
  66. package/dist/project-skills/execution-adapter.js +3 -2
  67. package/dist/project-skills/runtime-launch.js +14 -0
  68. package/dist/provider-env.js +26 -15
  69. package/dist/runner.js +17 -4
  70. package/dist/runtime-environment-merge.js +16 -0
  71. package/dist/runtime-health-handler.js +10 -0
  72. package/dist/runtime-health.js +3 -1
  73. package/dist/runtime-path.js +22 -12
  74. package/dist/runtime-probe.js +35 -6
  75. package/dist/runtimes/acp-probe-transport.js +69 -0
  76. package/dist/runtimes/claude-models.js +20 -9
  77. package/dist/runtimes/deepseek-harness-launch.js +10 -0
  78. package/dist/runtimes/deepseek-harness-profile.js +92 -0
  79. package/dist/runtimes/deepseek-harness-runner.js +226 -0
  80. package/dist/runtimes/deepseek-harness.js +76 -15
  81. package/dist/runtimes/harness-probe-retry.js +42 -0
  82. package/dist/runtimes/hermes-models.js +2 -1
  83. package/dist/runtimes/kimi-acp-runner.js +78 -13
  84. package/dist/runtimes/opencode.js +2 -2
  85. package/dist/serve.js +88 -176
  86. package/dist/server-url.js +25 -0
  87. package/dist/slog.js +2 -1
  88. package/dist/storage-identity.js +0 -3
  89. package/dist/storage-runtime.js +2 -2
  90. package/dist/storage-serve-adapter.js +6 -72
  91. package/dist/supervised-runtime.js +17 -2
  92. package/dist/token.js +0 -1
  93. package/dist/workspace-control-handler.js +27 -0
  94. package/dist/workspace-fs.js +66 -15
  95. package/dist/workspace.js +1 -1
  96. package/package.json +6 -4
  97. package/dist/codex-home-launch.js +0 -7
  98. package/dist/codex-home-mode-controller.js +0 -68
  99. package/dist/daemon-migration-controller.js +0 -211
  100. package/dist/daemon-migration-wiring.js +0 -22
  101. package/dist/runtimes/codex-home-migration-cli.js +0 -26
  102. package/dist/runtimes/codex-home-migration.js +0 -112
  103. package/dist/runtimes/codex-home.js +0 -236
  104. package/dist/storage-control.js +0 -212
  105. package/dist/storage-copy.js +0 -628
  106. package/dist/storage-credential-guard.js +0 -21
  107. package/dist/storage-doctor.js +0 -228
  108. package/dist/storage-manifest.js +0 -1027
  109. package/dist/storage-migration-controller.js +0 -440
  110. package/dist/storage-migration-manifest.js +0 -105
  111. package/dist/storage-migration-policy.js +0 -100
  112. package/dist/storage-runtime-controller.js +0 -381
  113. package/dist/storage-runtime-readiness.js +0 -240
  114. package/dist/storage-safe-fs.js +0 -302
  115. package/dist/storage-status-delivery.js +0 -224
  116. package/dist/storage-status-replay.js +0 -140
  117. package/dist/storage-target-confirmation.js +0 -129
  118. package/dist/storage-worker-command.js +0 -37
  119. package/dist/storage-worker-executor.js +0 -449
  120. package/dist/storage-worker-handoff.js +0 -151
  121. package/dist/storage-worker-operation.js +0 -294
  122. package/dist/storage-worker-status.js +0 -259
@@ -1,151 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { readFile, rm } from "node:fs/promises";
3
- import { join, posix, resolve, win32 } from "node:path";
4
- import { promisify } from "node:util";
5
- import { z } from "zod";
6
- import { atomicPrivateWrite } from "./atomic-private-write.js";
7
- import { readStorageWorkerOperation } from "./storage-worker-operation.js";
8
- const AbsolutePathSchema = z.string().min(1).max(32768)
9
- .refine((value) => !/[\0\r\n]/u.test(value), "path must be a single line")
10
- .refine((value) => posix.isAbsolute(value) || win32.isAbsolute(value), "path must be absolute");
11
- const HandoffSchema = z.object({
12
- version: z.literal(1),
13
- migrationId: z.string().uuid(),
14
- profile: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),
15
- operationPath: AbsolutePathSchema,
16
- operationSha256: z.string().regex(/^[0-9a-f]{64}$/u),
17
- }).strict();
18
- export async function writeStorageWorkerHandoff(raw, input) {
19
- let handoff;
20
- try {
21
- handoff = HandoffSchema.parse(raw);
22
- AbsolutePathSchema.parse(input.stateRoot);
23
- }
24
- catch (error) {
25
- throw new Error("Invalid storage worker handoff", { cause: error });
26
- }
27
- const path = join(input.stateRoot, "migrations", handoff.migrationId, "handoff.json");
28
- await atomicPrivateWrite(path, `${JSON.stringify(handoff, null, 2)}\n`);
29
- return path;
30
- }
31
- export async function readStorageWorkerHandoff(path) {
32
- try {
33
- AbsolutePathSchema.parse(path);
34
- return HandoffSchema.parse(JSON.parse(await readFile(path, "utf8")));
35
- }
36
- catch (error) {
37
- throw new Error("Invalid storage worker handoff", { cause: error });
38
- }
39
- }
40
- const execFileAsync = promisify(execFile);
41
- const systemSupervisorRun = async (command, args) => {
42
- try {
43
- const result = await execFileAsync(command, [...args], {
44
- encoding: "utf8",
45
- timeout: 15_000,
46
- maxBuffer: 64 * 1024,
47
- });
48
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
49
- }
50
- catch (error) {
51
- const failure = error;
52
- return {
53
- exitCode: typeof failure.code === "number" ? failure.code : 127,
54
- stdout: failure.stdout ?? "",
55
- stderr: failure.stderr ?? failure.message,
56
- };
57
- }
58
- };
59
- function workerUnitName(migrationId) {
60
- return `nowwork-storage-migration-${migrationId}.service`;
61
- }
62
- function workerUnitPath(userHome, migrationId) {
63
- return resolve(userHome, ".config", "systemd", "user", workerUnitName(migrationId));
64
- }
65
- function workerLaunchdLabel(migrationId) {
66
- return `com.nowcrew.storage-migration.${migrationId}`;
67
- }
68
- function workerLaunchdPath(userHome, migrationId) {
69
- return resolve(userHome, "Library", "LaunchAgents", `${workerLaunchdLabel(migrationId)}.plist`);
70
- }
71
- function xml(value) {
72
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
73
- .replaceAll('"', "&quot;").replaceAll("'", "&apos;");
74
- }
75
- function systemdArg(value) {
76
- if (/[\0\r\n]/u.test(value))
77
- throw new Error("storage worker service argument must be a single line");
78
- return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%")}"`;
79
- }
80
- async function checkedSupervisor(run, command, args) {
81
- const result = await run(command, args);
82
- if (result.exitCode !== 0)
83
- throw new Error(result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`);
84
- }
85
- export async function launchStorageMigrationWorker(input, runSupervisor = systemSupervisorRun) {
86
- AbsolutePathSchema.parse(input.entryPath);
87
- AbsolutePathSchema.parse(input.handoffPath);
88
- AbsolutePathSchema.parse(input.userHome);
89
- const migrationId = z.string().uuid().parse(input.migrationId).toLowerCase();
90
- const worker = [process.execPath, input.entryPath, "storage-migration-worker", "--job", input.handoffPath];
91
- if (input.platform === "darwin") {
92
- if (input.uid === undefined || !Number.isSafeInteger(input.uid) || input.uid < 0) {
93
- throw new Error("Persistent storage migration launchd worker requires a numeric uid");
94
- }
95
- const label = workerLaunchdLabel(migrationId);
96
- const path = workerLaunchdPath(input.userHome, migrationId);
97
- const args = worker.map((arg) => ` <string>${xml(arg)}</string>`).join("\n");
98
- const descriptor = `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key><string>${xml(label)}</string>\n <key>ProgramArguments</key>\n <array>\n${args}\n </array>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key>\n <dict>\n <key>SuccessfulExit</key><false/>\n </dict>\n <key>ProcessType</key><string>Background</string>\n</dict>\n</plist>\n`;
99
- await atomicPrivateWrite(path, descriptor);
100
- try {
101
- await checkedSupervisor(runSupervisor, "launchctl", ["bootstrap", `gui/${input.uid}`, path]);
102
- }
103
- catch (error) {
104
- await runSupervisor("launchctl", ["bootout", `gui/${input.uid}/${label}`]).catch(() => undefined);
105
- await rm(path, { force: true });
106
- throw new Error("Storage migration persistent service launch failed", { cause: error });
107
- }
108
- return;
109
- }
110
- const unit = workerUnitName(migrationId);
111
- const path = workerUnitPath(input.userHome, migrationId);
112
- const descriptor = `[Unit]\nDescription=NowWork storage migration ${migrationId}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=exec\nExecStart=${worker.map(systemdArg).join(" ")}\nRestart=on-abnormal\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`;
113
- await atomicPrivateWrite(path, descriptor);
114
- try {
115
- await checkedSupervisor(runSupervisor, "systemctl", ["--user", "daemon-reload"]);
116
- await checkedSupervisor(runSupervisor, "systemctl", ["--user", "enable", "--now", unit]);
117
- }
118
- catch (error) {
119
- await runSupervisor("systemctl", ["--user", "disable", "--now", unit]).catch(() => undefined);
120
- await rm(path, { force: true });
121
- await runSupervisor("systemctl", ["--user", "daemon-reload"]).catch(() => undefined);
122
- throw new Error("Storage migration persistent service launch failed", { cause: error });
123
- }
124
- }
125
- export async function completeStorageMigrationWorkerService(input, runSupervisor = systemSupervisorRun) {
126
- const migrationId = z.string().uuid().parse(input.migrationId).toLowerCase();
127
- AbsolutePathSchema.parse(input.userHome);
128
- if (input.platform === "darwin") {
129
- if (input.uid === undefined || !Number.isSafeInteger(input.uid) || input.uid < 0) {
130
- throw new Error("Persistent storage migration launchd worker requires a numeric uid");
131
- }
132
- const label = workerLaunchdLabel(migrationId);
133
- await rm(workerLaunchdPath(input.userHome, migrationId), { force: true });
134
- await runSupervisor("launchctl", ["bootout", `gui/${input.uid}/${label}`]);
135
- return;
136
- }
137
- const unit = workerUnitName(migrationId);
138
- await checkedSupervisor(runSupervisor, "systemctl", ["--user", "disable", unit]);
139
- await rm(workerUnitPath(input.userHome, migrationId), { force: true });
140
- await checkedSupervisor(runSupervisor, "systemctl", ["--user", "daemon-reload"]);
141
- }
142
- export async function completeStorageMigrationWorkerServiceForHandoff(path) {
143
- const handoff = await readStorageWorkerHandoff(path);
144
- const operation = await readStorageWorkerOperation(handoff.operationPath, handoff.operationSha256);
145
- await completeStorageMigrationWorkerService({
146
- migrationId: operation.migrationId,
147
- platform: operation.service.platform,
148
- userHome: operation.service.userHome,
149
- ...(operation.service.uid === undefined ? {} : { uid: operation.service.uid }),
150
- });
151
- }
@@ -1,294 +0,0 @@
1
- import { createHash, timingSafeEqual } from "node:crypto";
2
- import { realpathSync } from "node:fs";
3
- import { readFile } from "node:fs/promises";
4
- import { basename, dirname, join, posix, win32 } from "node:path";
5
- import { z } from "zod";
6
- import { atomicPrivateWrite } from "./atomic-private-write.js";
7
- import { assertStorageControlMaterialTokenFree } from "./storage-credential-guard.js";
8
- import { storageLayout } from "./storage-layout.js";
9
- import { StorageMigrationWarningCodeSchema } from "./storage-migration-policy.js";
10
- import { parseDaemonLocalHomeMode } from "./daemon-local-home.js";
11
- const CONTROL = /[\0\r\n]/u;
12
- const PROFILE = /^[a-z0-9][a-z0-9_-]{0,47}$/u;
13
- const ENVIRONMENT = /^[a-z0-9][a-z0-9_-]{0,31}$/u;
14
- const HASH = /^[0-9a-f]{64}$/u;
15
- const AbsolutePathSchema = z.string().min(1).max(32768)
16
- .refine((value) => !CONTROL.test(value), "path must be a single line")
17
- .refine((value) => posix.isAbsolute(value) || win32.isAbsolute(value), "path must be absolute");
18
- const RelativePathSchema = z.string().min(1).max(32768)
19
- .refine((value) => !CONTROL.test(value), "path must be a single line")
20
- .refine((value) => !posix.isAbsolute(value) && !win32.isAbsolute(value), "path must be relative")
21
- .refine((value) => !value.split(/[\\/]/u).some((segment) => segment === "" || segment === "." || segment === ".."), "path must be normalized");
22
- const SourceKindSchema = z.enum(["daemon-home", "agents-root", "legacy-agents-root"]);
23
- const PolicySchema = z.object({
24
- exclusions: z.array(z.object({
25
- sourceKind: SourceKindSchema,
26
- sourcePath: RelativePathSchema,
27
- reason: z.string().min(1).max(256),
28
- }).strict()).max(100_000),
29
- transformations: z.array(z.object({
30
- sourceKind: SourceKindSchema,
31
- sourcePath: RelativePathSchema,
32
- logicalDestination: RelativePathSchema,
33
- sourceSha256: z.string().regex(HASH),
34
- targetSha256: z.string().regex(HASH),
35
- targetMode: z.string().regex(/^[0-7]{4}$/u),
36
- transform: z.literal("redact_live_like_tokens_v1"),
37
- }).strict()).max(100_000),
38
- }).strict();
39
- const DoctorInputSchema = z.object({
40
- migrationId: z.string().uuid(),
41
- generatedAt: z.string().datetime({ offset: true }),
42
- environment: z.string().regex(ENVIRONMENT),
43
- workspaceId: z.string().uuid(),
44
- profile: z.string().regex(PROFILE),
45
- targetWorkspaceRoot: AbsolutePathSchema,
46
- sources: z.array(z.object({
47
- kind: SourceKindSchema,
48
- root: AbsolutePathSchema,
49
- logicalPrefix: RelativePathSchema,
50
- }).strict()).min(1).max(3),
51
- policy: PolicySchema,
52
- manifestStoreRoot: AbsolutePathSchema.optional(),
53
- state: z.object({
54
- profileIdentityExact: z.boolean(),
55
- duplicateWorkspaceMappings: z.number().int().nonnegative(),
56
- activeAgentExecutions: z.number().int().nonnegative(),
57
- activeScheduledRuns: z.number().int().nonnegative(),
58
- }).strict(),
59
- freeSpaceMultiplier: z.number().finite().min(1).max(10).optional(),
60
- }).strict();
61
- const ManagedServiceRecordSchema = z.object({
62
- version: z.literal(1),
63
- generation: z.string().uuid(),
64
- platform: z.enum(["darwin", "linux"]),
65
- serviceId: z.string().min(1).max(256),
66
- profile: z.string().regex(PROFILE),
67
- daemonHome: AbsolutePathSchema,
68
- agentsRoot: AbsolutePathSchema,
69
- nodePath: AbsolutePathSchema,
70
- entryPath: AbsolutePathSchema,
71
- packageRoot: AbsolutePathSchema,
72
- npmPrefix: AbsolutePathSchema,
73
- descriptorPath: AbsolutePathSchema,
74
- descriptorSha256: z.string().regex(HASH),
75
- createdAt: z.string().datetime({ offset: true }),
76
- }).strict();
77
- const InstallationRecordSchema = z.object({
78
- version: z.literal(1),
79
- installationId: z.string().uuid(),
80
- profile: z.string().regex(PROFILE),
81
- serverUrl: z.string().url().max(2048).refine((value) => {
82
- const url = new URL(value);
83
- return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
84
- }, "serverUrl must be HTTP(S) without credentials"),
85
- environment: z.string().regex(ENVIRONMENT),
86
- workspaceId: z.string().uuid(),
87
- storageId: z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/u),
88
- nowworkHome: AbsolutePathSchema,
89
- runtimeRoot: AbsolutePathSchema,
90
- credentialRef: z.string().regex(/^profile:[a-z0-9][a-z0-9_-]{0,47}$/u),
91
- storageMigrationId: z.string().uuid(),
92
- createdAt: z.string().datetime({ offset: true }),
93
- updatedAt: z.string().datetime({ offset: true }),
94
- }).strict();
95
- const StorageServiceEnvironmentSchema = z.object({
96
- NOWWORK_HOME: AbsolutePathSchema.optional(),
97
- NOWWORK_ENV_TAG: z.string().regex(ENVIRONMENT).optional(),
98
- NOWWORK_STORAGE_POLICY_PATH: AbsolutePathSchema.optional(),
99
- NOWWORK_LOCAL_HOME: AbsolutePathSchema.optional(),
100
- NOWWORK_LOCAL_HOME_MODE: z.string().min(1).max(32).optional(),
101
- }).strict();
102
- const OperationSchema = z.object({
103
- version: z.literal(1),
104
- migrationId: z.string().uuid(),
105
- createdAt: z.string().datetime({ offset: true }),
106
- environment: z.string().regex(ENVIRONMENT),
107
- workspaceId: z.string().uuid(),
108
- profile: z.string().regex(PROFILE),
109
- expectedManifestDigest: z.string().regex(HASH),
110
- doctorInput: DoctorInputSchema,
111
- migration: z.object({
112
- sourceRoots: z.object({
113
- "daemon-home": AbsolutePathSchema.optional(),
114
- "agents-root": AbsolutePathSchema.optional(),
115
- "legacy-agents-root": AbsolutePathSchema.optional(),
116
- }).strict(),
117
- stagingWorkspaceRoot: AbsolutePathSchema,
118
- targetWorkspaceRoot: AbsolutePathSchema,
119
- backupsRoot: AbsolutePathSchema,
120
- backupArtifacts: z.array(z.object({
121
- name: z.string().regex(/^[a-z0-9][a-z0-9_.-]{0,127}$/u),
122
- path: AbsolutePathSchema,
123
- }).strict()).max(32),
124
- ownership: z.object({
125
- ownerEpoch: z.number().int().positive().safe(),
126
- ownershipClaimFingerprint: z.string().regex(/^sha256:[0-9a-f]{64}$/u),
127
- }).strict().optional(),
128
- acceptedWarnings: z.array(StorageMigrationWarningCodeSchema)
129
- .max(StorageMigrationWarningCodeSchema.options.length),
130
- }).strict(),
131
- service: z.object({
132
- platform: z.enum(["darwin", "linux"]),
133
- userHome: AbsolutePathSchema,
134
- uid: z.number().int().nonnegative().optional(),
135
- serviceEnvironment: StorageServiceEnvironmentSchema.optional(),
136
- sourceWasRunning: z.boolean(),
137
- sourceRecord: ManagedServiceRecordSchema,
138
- targetRecord: ManagedServiceRecordSchema,
139
- }).strict(),
140
- installation: z.object({
141
- configRoot: AbsolutePathSchema,
142
- target: InstallationRecordSchema,
143
- }).strict(),
144
- }).strict();
145
- const pathsFor = (_platform) => posix;
146
- function canonicalPath(value, platform) {
147
- const paths = pathsFor(platform);
148
- const absolute = paths.resolve(value);
149
- try {
150
- return realpathSync.native(absolute);
151
- }
152
- catch (error) {
153
- const code = error.code;
154
- if (code === "ENOTDIR")
155
- return absolute;
156
- if (code !== "ENOENT")
157
- throw error;
158
- }
159
- const missing = [];
160
- let ancestor = absolute;
161
- for (;;) {
162
- const parent = paths.dirname(ancestor);
163
- if (parent === ancestor)
164
- return absolute;
165
- missing.unshift(paths.basename(ancestor));
166
- ancestor = parent;
167
- try {
168
- return paths.resolve(realpathSync.native(ancestor), ...missing);
169
- }
170
- catch (error) {
171
- const code = error.code;
172
- if (code === "ENOTDIR")
173
- return absolute;
174
- if (code !== "ENOENT")
175
- throw error;
176
- }
177
- }
178
- }
179
- function samePath(left, right, platform) {
180
- return canonicalPath(left, platform) === canonicalPath(right, platform);
181
- }
182
- function isInside(root, candidate, platform) {
183
- const paths = pathsFor(platform);
184
- const child = paths.relative(canonicalPath(root, platform), canonicalPath(candidate, platform));
185
- return child === "" || (!child.startsWith("..") && !paths.isAbsolute(child));
186
- }
187
- function assertSemanticIdentity(operation) {
188
- const localHomeMode = operation.service.serviceEnvironment?.NOWWORK_LOCAL_HOME_MODE;
189
- if (localHomeMode !== undefined)
190
- parseDaemonLocalHomeMode(localHomeMode);
191
- const identity = [operation.doctorInput, operation.installation.target];
192
- if (identity.some((value) => value.workspaceId !== operation.workspaceId
193
- || value.environment !== operation.environment || value.profile !== operation.profile)
194
- || operation.doctorInput.migrationId !== operation.migrationId
195
- || operation.installation.target.storageMigrationId !== operation.migrationId
196
- || operation.installation.target.credentialRef !== `profile:${operation.profile}`) {
197
- throw new Error("storage worker operation identity does not match");
198
- }
199
- if (operation.doctorInput.state.profileIdentityExact !== true
200
- || operation.doctorInput.state.duplicateWorkspaceMappings !== 0
201
- || operation.doctorInput.state.activeAgentExecutions !== 0
202
- || operation.doctorInput.state.activeScheduledRuns !== 0) {
203
- throw new Error("storage worker operation doctor state is not safe");
204
- }
205
- const { platform, sourceRecord, targetRecord } = operation.service;
206
- if (sourceRecord.platform !== platform || targetRecord.platform !== platform
207
- || sourceRecord.profile !== operation.profile || targetRecord.profile !== operation.profile
208
- || sourceRecord.serviceId === targetRecord.serviceId
209
- || !samePath(sourceRecord.nodePath, targetRecord.nodePath, platform)
210
- || !samePath(sourceRecord.entryPath, targetRecord.entryPath, platform)
211
- || !samePath(sourceRecord.packageRoot, targetRecord.packageRoot, platform)
212
- || !samePath(sourceRecord.npmPrefix, targetRecord.npmPrefix, platform)
213
- || !samePath(targetRecord.daemonHome, operation.installation.configRoot, platform)) {
214
- throw new Error("storage worker service identity does not match");
215
- }
216
- const sourceKinds = new Set();
217
- for (const source of operation.doctorInput.sources) {
218
- if (sourceKinds.has(source.kind) || !samePath(operation.migration.sourceRoots[source.kind] ?? "", source.root, platform)) {
219
- throw new Error("storage worker source roots do not match doctor input");
220
- }
221
- sourceKinds.add(source.kind);
222
- }
223
- const configuredSourceKinds = Object.entries(operation.migration.sourceRoots)
224
- .filter(([, value]) => value !== undefined)
225
- .map(([kind]) => kind);
226
- if (configuredSourceKinds.length !== sourceKinds.size || configuredSourceKinds.some((kind) => !sourceKinds.has(kind))
227
- || !samePath(operation.migration.sourceRoots["daemon-home"] ?? "", sourceRecord.daemonHome, platform)
228
- || !samePath(operation.migration.sourceRoots["agents-root"] ?? "", sourceRecord.agentsRoot, platform)) {
229
- throw new Error("storage worker source service roots do not match");
230
- }
231
- const projected = storageLayout({
232
- nowworkHome: operation.installation.target.nowworkHome,
233
- environment: operation.environment,
234
- workspaceId: operation.workspaceId,
235
- runtimeBase: join(operation.service.userHome, ".nowwork-worker-runtime-validation"),
236
- platform,
237
- });
238
- if (!samePath(projected.workspaceRoot, operation.migration.targetWorkspaceRoot, platform)
239
- || !samePath(projected.workspaceRoot, operation.doctorInput.targetWorkspaceRoot, platform)
240
- || !samePath(projected.agentItemsRoot, targetRecord.agentsRoot, platform)) {
241
- throw new Error("storage worker target layout does not match installation identity");
242
- }
243
- if (dirname(operation.migration.stagingWorkspaceRoot) !== dirname(operation.migration.targetWorkspaceRoot)
244
- || !basename(operation.migration.stagingWorkspaceRoot).includes(operation.migrationId)) {
245
- throw new Error("storage worker staging identity does not match target");
246
- }
247
- if (isInside(operation.installation.target.nowworkHome, operation.migration.backupsRoot, platform)
248
- || isInside(operation.installation.target.nowworkHome, operation.installation.configRoot, platform)) {
249
- throw new Error("storage worker local state must remain outside NOWWORK_HOME");
250
- }
251
- }
252
- function parseOperation(raw) {
253
- const operation = OperationSchema.parse(raw);
254
- assertSemanticIdentity(operation);
255
- return operation;
256
- }
257
- function sha256(value) {
258
- return createHash("sha256").update(value).digest("hex");
259
- }
260
- export async function writeStorageWorkerOperation(raw, input) {
261
- try {
262
- const operation = parseOperation(raw);
263
- const stateRoot = AbsolutePathSchema.parse(input.stateRoot);
264
- const path = join(stateRoot, "migrations", operation.migrationId, "operation.json");
265
- const serialized = `${JSON.stringify(operation, null, 2)}\n`;
266
- assertStorageControlMaterialTokenFree(serialized, "storage worker operation");
267
- await atomicPrivateWrite(path, serialized);
268
- return Object.freeze({ path, sha256: sha256(serialized) });
269
- }
270
- catch (error) {
271
- throw new Error("Invalid storage worker operation", { cause: error });
272
- }
273
- }
274
- export async function readStorageWorkerOperation(path, expectedSha256) {
275
- try {
276
- AbsolutePathSchema.parse(path);
277
- z.string().regex(HASH).parse(expectedSha256);
278
- const raw = await readFile(path);
279
- assertStorageControlMaterialTokenFree(raw.toString("utf8"), "storage worker operation");
280
- const actual = Buffer.from(sha256(raw), "hex");
281
- const expected = Buffer.from(expectedSha256, "hex");
282
- if (!timingSafeEqual(actual, expected))
283
- throw new Error("storage worker operation digest mismatch");
284
- const operation = parseOperation(JSON.parse(raw.toString("utf8")));
285
- if (basename(path) !== "operation.json" || basename(dirname(path)) !== operation.migrationId
286
- || basename(dirname(dirname(path))) !== "migrations") {
287
- throw new Error("storage worker operation path does not match migration identity");
288
- }
289
- return operation;
290
- }
291
- catch (error) {
292
- throw new Error("Invalid storage worker operation", { cause: error });
293
- }
294
- }