zapagent 1.14.14 → 1.14.16
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.
- package/package.json +1 -1
- package/src/App.tsx +7 -3
- package/src/agent/goalPresentation.ts +43 -0
- package/src/commands/dispatcher.ts +9 -3
- package/src/goal-command.ts +25 -17
- package/src/goal-host.ts +2 -1
- package/src/goal-runner.ts +39 -6
- package/src/goal-session.ts +100 -0
- package/src/goal-turn-host.ts +410 -0
- package/src/goal-turn.ts +41 -0
- package/src/headless/goalPhase.ts +78 -30
- package/src/headless/runHeadless.ts +15 -3
- package/src/headless/sharedGoalTurn.ts +34 -0
- package/src/hooks/useAgentRunner.ts +72 -3
- package/src/hooks/useTurnDispatcher.ts +8 -0
- package/src/index.tsx +19 -3
- package/src/ui/slash-palette.tsx +1 -1
- package/zapsdk/builtin-tools/subagent.ts +52 -17
- package/zapsdk/core/retry.ts +9 -0
- package/zapsdk/goal/contracts.ts +2 -0
- package/zapsdk/goal/store.ts +2 -2
- package/zapsdk/merge/copy.ts +13 -4
- package/zapsdk/runtime/recovery-controller.ts +1 -0
- package/zapsdk/runtime/state-tracker.ts +2 -0
- package/zapsdk/runtime/state-types.ts +1 -0
- package/zapsdk/workspace/copy.ts +29 -4
- package/zapsdk/workspace/manager.ts +34 -3
- package/zapsdk/workspace/types.ts +2 -0
|
@@ -109,7 +109,7 @@ const READONLY_BIN_ALLOWLIST = new Set([
|
|
|
109
109
|
// Searching
|
|
110
110
|
"find", "grep", "rg", "fgrep", "egrep",
|
|
111
111
|
// Dir / file metadata
|
|
112
|
-
"tree", "file", "stat", "pwd", "basename", "dirname", "readlink", "realpath",
|
|
112
|
+
"tree", "file", "stat", "pwd", "du", "basename", "dirname", "readlink", "realpath",
|
|
113
113
|
// Text inspection (read-only flags only; no `sed -i`, no awk `system`)
|
|
114
114
|
"sort", "uniq", "cut", "tr", "comm", "diff", "cmp",
|
|
115
115
|
"column", "paste", "fold", "rev", "od", "hexdump", "strings",
|
|
@@ -137,9 +137,17 @@ const READONLY_BIN_ALLOWLIST = new Set([
|
|
|
137
137
|
const READONLY_GIT_SUBCOMMANDS = new Set([
|
|
138
138
|
"log", "diff", "status", "blame", "show", "ls-files", "ls-tree",
|
|
139
139
|
"rev-parse", "rev-list", "describe", "grep", "shortlog", "whatchanged",
|
|
140
|
-
"cat-file", "for-each-ref", "name-rev",
|
|
140
|
+
"cat-file", "for-each-ref", "name-rev", "merge-base", "worktree",
|
|
141
141
|
]);
|
|
142
142
|
|
|
143
|
+
/** getopt_long accepts any unique prefix of a long option (`sort --out=FILE`), so a plain
|
|
144
|
+
* `startsWith("--output")` check is bypassed by abbreviations. */
|
|
145
|
+
function isLongOptionAbbreviation(part: string, full: string, minLength: number): boolean {
|
|
146
|
+
if (!part.startsWith("--")) return false;
|
|
147
|
+
const name = part.split("=")[0]!;
|
|
148
|
+
return name.length >= minLength && full.startsWith(name);
|
|
149
|
+
}
|
|
150
|
+
|
|
143
151
|
/** Returns null if safe, else a human-readable reject reason. */
|
|
144
152
|
export function validateReadOnlyBash(cmd: string): string | null {
|
|
145
153
|
const trimmed = cmd.trim();
|
|
@@ -147,8 +155,8 @@ export function validateReadOnlyBash(cmd: string): string | null {
|
|
|
147
155
|
|
|
148
156
|
// Reject shell control that could chain unsafe commands or redirect output.
|
|
149
157
|
// Pipes (|) are allowed because they compose read-only filters.
|
|
150
|
-
if (
|
|
151
|
-
return "shell control (;, &&, ||, >, <, $(), backticks) is not allowed in read-only mode. Plain pipes (|) are allowed.";
|
|
158
|
+
if (/[\r\n&;]|\|\||>|<|\$\(|`/.test(trimmed)) {
|
|
159
|
+
return "shell control (;, &, &&, ||, >, <, $(), backticks, newlines) is not allowed in read-only mode. Plain pipes (|) are allowed.";
|
|
152
160
|
}
|
|
153
161
|
// Reject trailing `&` (background).
|
|
154
162
|
if (/&\s*$/.test(trimmed)) return "background (&) is not allowed in read-only mode";
|
|
@@ -170,9 +178,13 @@ export function validateReadOnlyBash(cmd: string): string | null {
|
|
|
170
178
|
if (!READONLY_GIT_SUBCOMMANDS.has(sub)) {
|
|
171
179
|
return `git ${sub} is not in the read-only allowlist (allowed: log, diff, status, blame, show, ls-files, …)`;
|
|
172
180
|
}
|
|
181
|
+
if (sub === "worktree" && parts[2] !== "list") return "only git worktree list is allowed in read-only mode";
|
|
173
182
|
if (parts.some((part) => part === "--output" || part.startsWith("--output="))) {
|
|
174
183
|
return "git --output is not allowed in read-only mode";
|
|
175
184
|
}
|
|
185
|
+
if (sub === "grep" && parts.some((part) => part.startsWith("-O") || isLongOptionAbbreviation(part, "--open-files-in-pager", 4))) {
|
|
186
|
+
return "git grep -O / --open-files-in-pager run external programs and are not allowed";
|
|
187
|
+
}
|
|
176
188
|
}
|
|
177
189
|
|
|
178
190
|
if (first === "find") {
|
|
@@ -180,10 +192,33 @@ export function validateReadOnlyBash(cmd: string): string | null {
|
|
|
180
192
|
if (/\s-(exec|delete|ok|execdir|okdir)\b/.test(seg)) {
|
|
181
193
|
return "find -exec / -delete / -ok / -execdir / -okdir are not allowed";
|
|
182
194
|
}
|
|
195
|
+
// -fprint* / -fls write their results to a file.
|
|
196
|
+
if (/\s-(fprint|fprint0|fprintf|fls)\b/.test(seg)) {
|
|
197
|
+
return "find -fprint / -fprint0 / -fprintf / -fls write files and are not allowed";
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Short-option clusters such as `-oFILE` or `-uo FILE` also select an output file.
|
|
202
|
+
if (first === "sort" && parts.slice(1).some((part) => /^-[A-Za-z]*o/.test(part) || isLongOptionAbbreviation(part, "--output", 3) || isLongOptionAbbreviation(part, "--compress-program", 4))) {
|
|
203
|
+
return "sort output-file / compress-program options are not allowed in read-only mode";
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (first === "tree" && parts.slice(1).some((part) => /^-[A-Za-z]*o/.test(part) || isLongOptionAbbreviation(part, "--output", 3))) {
|
|
207
|
+
return "tree output-file options are not allowed in read-only mode";
|
|
183
208
|
}
|
|
184
209
|
|
|
185
|
-
if (first === "
|
|
186
|
-
return "
|
|
210
|
+
if (first === "rg" && parts.slice(1).some((part) => /^--(pre|hostname-bin)(=|$)/.test(part))) {
|
|
211
|
+
return "rg --pre / --hostname-bin run external programs and are not allowed";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (first === "uniq") {
|
|
215
|
+
// `uniq INPUT OUTPUT` writes OUTPUT. Option values (-f/-s/-w N) are not files.
|
|
216
|
+
const operands: string[] = [];
|
|
217
|
+
for (let i = 1; i < parts.length; i++) {
|
|
218
|
+
if (/^-[fsw]$/.test(parts[i]!)) { i++; continue; }
|
|
219
|
+
if (!parts[i]!.startsWith("-")) operands.push(parts[i]!);
|
|
220
|
+
}
|
|
221
|
+
if (operands.length > 1) return "uniq with an output operand is not allowed in read-only mode";
|
|
187
222
|
}
|
|
188
223
|
|
|
189
224
|
if (first === "yq" && parts.some((part) => part === "-i" || part === "--inplace")) {
|
|
@@ -205,8 +240,8 @@ export function validateReadOnlyBash(cmd: string): string | null {
|
|
|
205
240
|
* argument. Registered under the same name ("bash") so the subagent's
|
|
206
241
|
* tool schema is indistinguishable from the main agent's — the model
|
|
207
242
|
* doesn't need to learn a new tool name. */
|
|
208
|
-
function readOnlyBashTool(defaultCwd?: string): Tool {
|
|
209
|
-
const inner = executeCommandTool({ defaultCwd, allowUnsandboxed: false });
|
|
243
|
+
export function readOnlyBashTool(defaultCwd?: string): Tool {
|
|
244
|
+
const inner = executeCommandTool({ defaultCwd, allowUnsandboxed: false, sandboxNetwork: false, restrictedNetwork: false, disableBackgroundTasks: true });
|
|
210
245
|
return {
|
|
211
246
|
...inner,
|
|
212
247
|
definition: {
|
|
@@ -221,6 +256,7 @@ function readOnlyBashTool(defaultCwd?: string): Tool {
|
|
|
221
256
|
kind: "process",
|
|
222
257
|
operation: "spawn",
|
|
223
258
|
commandClass: "read-only-shell",
|
|
259
|
+
readOnly: true,
|
|
224
260
|
background: false,
|
|
225
261
|
}],
|
|
226
262
|
external: [],
|
|
@@ -229,16 +265,15 @@ function readOnlyBashTool(defaultCwd?: string): Tool {
|
|
|
229
265
|
}),
|
|
230
266
|
},
|
|
231
267
|
handler: async (args, signal, context) => {
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
};
|
|
268
|
+
const parsed = inner.definition.parameters.safeParse(args);
|
|
269
|
+
if (!parsed.success) return { success: false, output: "", error: `Invalid read-only bash arguments: ${parsed.error.message}` };
|
|
270
|
+
const checked = parsed.data as Record<string, unknown>;
|
|
271
|
+
const commands = Array.isArray(checked.check_steps) ? checked.check_steps : [checked.command];
|
|
272
|
+
for (const command of commands) {
|
|
273
|
+
const reject = typeof command === "string" ? validateReadOnlyBash(command) : "command or check_steps is required";
|
|
274
|
+
if (reject) return { success: false, output: "", error: `bash blocked in read-only mode: ${reject}` };
|
|
240
275
|
}
|
|
241
|
-
return inner.handler(
|
|
276
|
+
return inner.handler(checked, signal, context);
|
|
242
277
|
},
|
|
243
278
|
};
|
|
244
279
|
}
|
package/zapsdk/core/retry.ts
CHANGED
|
@@ -39,6 +39,15 @@ export class RetryProvider implements LLMProvider {
|
|
|
39
39
|
this.onRetry = options.onRetry;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
/** Per-run instrumentation inside retries, without mutating a shared provider. */
|
|
43
|
+
withInnerAdapter(adapter: (provider: LLMProvider) => LLMProvider): RetryProvider {
|
|
44
|
+
return new RetryProvider(adapter(this.inner), {
|
|
45
|
+
maxRetries: this.maxRetries, initialDelayMs: this.initialDelayMs,
|
|
46
|
+
maxDelayMs: this.maxDelayMs, backoffMultiplier: this.backoffMultiplier,
|
|
47
|
+
retryableErrors: this.retryableErrors, onRetry: this.onRetry,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
42
51
|
getImageTokenContext(options?: LLMCallOptions) {
|
|
43
52
|
return this.inner.getImageTokenContext?.(options) ?? { model: options?.model };
|
|
44
53
|
}
|
package/zapsdk/goal/contracts.ts
CHANGED
|
@@ -28,6 +28,8 @@ export interface GoalReceipt {
|
|
|
28
28
|
export interface GoalRecord {
|
|
29
29
|
id: string;
|
|
30
30
|
objective: string;
|
|
31
|
+
/** Absent on legacy Goals, whose isolated snapshots retain their old host. */
|
|
32
|
+
executionMode?: "session" | "isolated";
|
|
31
33
|
deliveryPolicy: "artifact" | "workspace";
|
|
32
34
|
machineCheck?: "bun" | "npm" | "pytest" | "go";
|
|
33
35
|
/** User-authorized, host-managed dependency preparation. */
|
package/zapsdk/goal/store.ts
CHANGED
|
@@ -16,10 +16,10 @@ export class GoalStore {
|
|
|
16
16
|
this.db.exec("CREATE TABLE IF NOT EXISTS goal_budget_extensions (id TEXT PRIMARY KEY, goal_id TEXT NOT NULL, at INTEGER NOT NULL, old_limits TEXT NOT NULL, new_limits TEXT NOT NULL)");
|
|
17
17
|
}
|
|
18
18
|
close(): void { this.db.close(); }
|
|
19
|
-
create(input: { objective: string; cwd: string; sessionId?: string; deadlineAt?: number; deliveryPolicy?: "artifact" | "workspace"; machineCheck?: "bun" | "npm" | "pytest" | "go"; dependencyInstall?: "npm"; permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions" }): GoalRecord {
|
|
19
|
+
create(input: { executionMode?: "session" | "isolated"; objective: string; cwd: string; sessionId?: string; deadlineAt?: number; deliveryPolicy?: "artifact" | "workspace"; machineCheck?: "bun" | "npm" | "pytest" | "go"; dependencyInstall?: "npm"; permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions" }): GoalRecord {
|
|
20
20
|
if (!input.objective.trim() || !input.cwd || (input.deadlineAt !== undefined && (!Number.isSafeInteger(input.deadlineAt) || input.deadlineAt <= Date.now())) || (input.dependencyInstall !== undefined && input.dependencyInstall !== "npm")) throw new Error("INVALID_GOAL");
|
|
21
21
|
const now = Date.now();
|
|
22
|
-
const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, ...(input.deadlineAt === undefined ? {} : { deadlineAt: input.deadlineAt }), ownerEpoch: 0, tasks: [] };
|
|
22
|
+
const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, ...(input.executionMode ? { executionMode: input.executionMode } : {}), deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, ...(input.deadlineAt === undefined ? {} : { deadlineAt: input.deadlineAt }), ownerEpoch: 0, tasks: [] };
|
|
23
23
|
this.db.query("INSERT INTO goals(id,revision,record) VALUES(?,?,?)").run(value.id, value.stateRevision, JSON.stringify(value));
|
|
24
24
|
return value;
|
|
25
25
|
}
|
package/zapsdk/merge/copy.ts
CHANGED
|
@@ -99,17 +99,22 @@ export async function mergeCopyArtifacts(
|
|
|
99
99
|
.sort((a, b) => a.path.split("/").length - b.path.split("/").length);
|
|
100
100
|
for (const operation of directories) operation.workingMode = operation.beforeMode! | 0o700;
|
|
101
101
|
async function checkRoot(): Promise<string[]> {
|
|
102
|
-
const
|
|
102
|
+
const rawLinks: Record<string, string> = Object.create(null);
|
|
103
|
+
const current = await scanCopyTree(root, true, true, true, undefined, undefined, rawLinks);
|
|
103
104
|
const conflicts = new Set<string>();
|
|
104
105
|
for (const path of changedPaths) {
|
|
105
106
|
if (!sameEntry(current[path], base[path])) conflicts.add(path);
|
|
107
|
+
const originalLink = manager.originalSourceLink(path) ?? (base[path]?.kind === "symlink" ? base[path].target : undefined);
|
|
108
|
+
if (originalLink !== undefined && originalLink !== rawLinks[path]) conflicts.add(path);
|
|
106
109
|
// A replaced/deleted directory also owns its descendants. Never discard
|
|
107
110
|
// concurrent additions or excluded private/control files inside it.
|
|
108
111
|
if (base[path]?.kind === "directory" && desired[path]?.kind !== "directory") {
|
|
109
112
|
for (const child of new Set([...Object.keys(base), ...Object.keys(current)])) {
|
|
110
113
|
if (descendant(child, path) && !sameEntry(current[child], base[child])) conflicts.add(child);
|
|
111
114
|
}
|
|
112
|
-
|
|
115
|
+
// Root validation above already checked link targets; this subtree
|
|
116
|
+
// inventory never follows links and may contain links to root siblings.
|
|
117
|
+
const complete = await scanCopyTree(join(root, path), false, false);
|
|
113
118
|
for (const child of Object.keys(complete)) {
|
|
114
119
|
// Excluded environments may contain only regular files (--copies).
|
|
115
120
|
// Replacing their parent must not silently delete those local files.
|
|
@@ -140,15 +145,19 @@ export async function mergeCopyArtifacts(
|
|
|
140
145
|
// on failure if rollback cannot complete; never discard the user's originals.
|
|
141
146
|
const transaction = join(root, `.zap-copy-merge-${randomUUID()}`);
|
|
142
147
|
for (const operation of operations) {
|
|
143
|
-
operation.before = await operationOid(join(
|
|
148
|
+
operation.before = await operationOid(join(root, operation.path), operation.modeOnly);
|
|
144
149
|
operation.after = await operationOid(join(staging, operation.path), operation.modeOnly);
|
|
145
150
|
if (!operation.modeOnly && operation.beforeMode !== undefined) {
|
|
146
|
-
operation.beforeWorking = await copyPathOid(join(
|
|
151
|
+
operation.beforeWorking = await copyPathOid(join(root, operation.path), operation.beforeMode | 0o700);
|
|
147
152
|
}
|
|
148
153
|
if (!operation.modeOnly && operation.afterMode !== undefined) {
|
|
149
154
|
operation.afterWorking = await copyPathOid(join(staging, operation.path), operation.afterMode | 0o700);
|
|
150
155
|
}
|
|
151
156
|
}
|
|
157
|
+
// Compare the canonical baseline again after binding the original raw bytes
|
|
158
|
+
// for rollback (source absolute symlinks are relocated in snapshots).
|
|
159
|
+
drift = await checkRoot();
|
|
160
|
+
if (drift.length) return rejected("Root workspace changed while binding the merge", drift);
|
|
152
161
|
const journal: CopyMergeJournal = { version: 1, root, transaction, artifactIds, operations, state: "applying" };
|
|
153
162
|
await writeCopyMergeJournal(batch, journal);
|
|
154
163
|
await mkdir(transaction, { mode: 0o700 });
|
|
@@ -191,6 +191,7 @@ function leaseFromState(workspace: PersistedWorkspaceState): WorkspaceLease {
|
|
|
191
191
|
repoPath: workspace.repoPath,
|
|
192
192
|
baseOid: workspace.baseOid,
|
|
193
193
|
batchPath: workspace.batchPath,
|
|
194
|
+
...(workspace.sourceLinksHash ? { sourceLinksHash: workspace.sourceLinksHash } : {}),
|
|
194
195
|
};
|
|
195
196
|
}
|
|
196
197
|
|
|
@@ -431,6 +431,7 @@ export class RuntimeStateTracker {
|
|
|
431
431
|
mode: event.lease.mode,
|
|
432
432
|
path: event.lease.path,
|
|
433
433
|
batchPath: event.lease.batchPath,
|
|
434
|
+
...(event.lease.sourceLinksHash ? { sourceLinksHash: event.lease.sourceLinksHash } : {}),
|
|
434
435
|
status: "acquiring",
|
|
435
436
|
acquiredAt: event.timestamp,
|
|
436
437
|
updatedAt: event.timestamp,
|
|
@@ -449,6 +450,7 @@ export class RuntimeStateTracker {
|
|
|
449
450
|
repoPath: event.lease.repoPath,
|
|
450
451
|
baseOid: event.lease.baseOid,
|
|
451
452
|
batchPath: event.lease.batchPath,
|
|
453
|
+
...(event.lease.sourceLinksHash ? { sourceLinksHash: event.lease.sourceLinksHash } : {}),
|
|
452
454
|
status: event.type === "workspace_hydrated" ? "preserved" : "active",
|
|
453
455
|
acquiredAt: existing?.acquiredAt ?? event.timestamp,
|
|
454
456
|
updatedAt: event.timestamp,
|
package/zapsdk/workspace/copy.ts
CHANGED
|
@@ -105,10 +105,26 @@ async function fileEntry(path: string, mode: number): Promise<CopyEntry> {
|
|
|
105
105
|
} finally { await handle.close(); }
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/** Find the source-root spelling without flattening any link inside it. */
|
|
109
|
+
async function sourceLinkPath(root: string, canonicalRoot: string, target: string): Promise<string> {
|
|
110
|
+
for (const spelling of [resolve(root), canonicalRoot]) {
|
|
111
|
+
if (target === spelling) return "";
|
|
112
|
+
if (target.startsWith(spelling + sep)) return target.slice(spelling.length + 1);
|
|
113
|
+
}
|
|
114
|
+
// A host prefix such as /tmp may itself alias /private/tmp. Resolve only
|
|
115
|
+
// ancestors that denote the root, preserving the target's internal chain.
|
|
116
|
+
for (let parent = target; ; parent = dirname(parent)) {
|
|
117
|
+
if (await realpath(parent) === canonicalRoot) return target === parent ? "" : target.slice(parent.length + 1);
|
|
118
|
+
if (dirname(parent) === parent) break;
|
|
119
|
+
}
|
|
120
|
+
throw new Error("Absolute symlink does not name this source workspace");
|
|
121
|
+
}
|
|
122
|
+
|
|
108
123
|
/** Never follows directory links. Hashing is streamed, including large inputs.
|
|
109
124
|
* source=true excludes private/control files from the initial snapshot only;
|
|
110
125
|
* introducing one in a child is rejected rather than silently losing edits. */
|
|
111
|
-
export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding): Promise<CopyTree> {
|
|
126
|
+
export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding, originalLinks?: Record<string, string>): Promise<CopyTree> {
|
|
127
|
+
const canonicalRoot = await realpath(root);
|
|
112
128
|
const info = await lstat(root);
|
|
113
129
|
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`Unsafe copy workspace root: ${root}`);
|
|
114
130
|
const validatePrivateGit = async () => {
|
|
@@ -134,16 +150,25 @@ export async function scanCopyTree(root: string, source = false, validateLinks =
|
|
|
134
150
|
const full = join(root, path);
|
|
135
151
|
const stat = await lstat(full);
|
|
136
152
|
if (stat.isSymbolicLink()) {
|
|
137
|
-
|
|
138
|
-
if (
|
|
153
|
+
let target = await readlink(full);
|
|
154
|
+
if (originalLinks) originalLinks[path] = target;
|
|
155
|
+
if (validateLinks && (!source && isAbsolute(target) || !isAbsolute(target) && !isWithin(root, resolve(dirname(full), target)))) {
|
|
139
156
|
throw new Error(`Symlink escapes copy workspace: ${path}`);
|
|
140
157
|
}
|
|
141
158
|
// Reject dangling/cyclic links, and links which escape indirectly.
|
|
142
159
|
if (validateLinks) {
|
|
143
160
|
const resolved = await realpath(full);
|
|
144
|
-
if (!isWithin(
|
|
161
|
+
if (!isWithin(canonicalRoot, resolved) || excludedCopyPath(relative(canonicalRoot, resolved).split(sep).join("/"))) {
|
|
145
162
|
throw new Error(`Unsafe copy workspace symlink: ${path}`);
|
|
146
163
|
}
|
|
164
|
+
// Source links may name a host path inside the same tree. Relocate
|
|
165
|
+
// only that verified target; snapshots must never point at the host.
|
|
166
|
+
if (source && isAbsolute(target)) {
|
|
167
|
+
const sourcePath = await sourceLinkPath(root, canonicalRoot, target);
|
|
168
|
+
if (excludedCopyPath(sourcePath)) throw new Error(`Unsafe copy workspace symlink: ${path}`);
|
|
169
|
+
const depth = dirname(path) === "." ? 0 : dirname(path).split("/").length;
|
|
170
|
+
target = "../".repeat(depth) + (sourcePath || ".");
|
|
171
|
+
}
|
|
147
172
|
}
|
|
148
173
|
tree[path] = { kind: "symlink", target };
|
|
149
174
|
} else if (stat.isDirectory()) {
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import {
|
|
4
4
|
copyFile,
|
|
5
5
|
lstat,
|
|
6
6
|
mkdir,
|
|
7
7
|
mkdtemp,
|
|
8
8
|
realpath,
|
|
9
|
+
readFile,
|
|
9
10
|
readlink,
|
|
10
11
|
rm,
|
|
11
12
|
symlink,
|
|
@@ -142,6 +143,8 @@ export class WorkspaceManager {
|
|
|
142
143
|
private mode: "isolated-git" | "isolated-copy" = "isolated-git";
|
|
143
144
|
private templatePath?: string;
|
|
144
145
|
private baseOid?: string;
|
|
146
|
+
private sourceLinksHash?: string;
|
|
147
|
+
private sourceLinks: Record<string, string> = Object.create(null);
|
|
145
148
|
private initializePromise?: Promise<void>;
|
|
146
149
|
private artifacts = new Map<string, AgentArtifact>();
|
|
147
150
|
private leases = new Map<string, WorkspaceLease>();
|
|
@@ -233,6 +236,7 @@ export class WorkspaceManager {
|
|
|
233
236
|
repoPath,
|
|
234
237
|
baseOid: this.baseOid,
|
|
235
238
|
batchPath: this.batchRoot,
|
|
239
|
+
...(this.sourceLinksHash ? { sourceLinksHash: this.sourceLinksHash } : {}),
|
|
236
240
|
...(privateGit ? { privateGit } : {}),
|
|
237
241
|
};
|
|
238
242
|
this.leases.set(lease.workspaceId, lease);
|
|
@@ -499,6 +503,19 @@ export class WorkspaceManager {
|
|
|
499
503
|
this.batchRoot = realBatch;
|
|
500
504
|
this.templatePath = snapshotPath;
|
|
501
505
|
this.baseOid = input.leases[0].baseOid;
|
|
506
|
+
const sourceLinksHash = input.leases[0].sourceLinksHash;
|
|
507
|
+
if (input.leases.some(lease => lease.sourceLinksHash !== sourceLinksHash)) throw new Error("Source link baseline identity mismatch");
|
|
508
|
+
if (copy && sourceLinksHash) {
|
|
509
|
+
const sourceLinksPath = join(realBatch, "source-links.json");
|
|
510
|
+
const info = await lstat(sourceLinksPath);
|
|
511
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 16 * 1024 * 1024) throw new Error("Unsafe source link baseline");
|
|
512
|
+
const bytes = await readFile(sourceLinksPath);
|
|
513
|
+
if (createHash("sha256").update(bytes).digest("hex") !== sourceLinksHash) throw new Error("Source link baseline was modified");
|
|
514
|
+
const links = JSON.parse(bytes.toString("utf8"));
|
|
515
|
+
const baseline = await scanCopyTree(snapshotPath);
|
|
516
|
+
if (!links || Array.isArray(links) || typeof links !== "object" || Object.entries(links).some(([path, target]) => baseline[path]?.kind !== "symlink" || typeof target !== "string")) throw new Error("Invalid source link baseline");
|
|
517
|
+
this.sourceLinks = links; this.sourceLinksHash = sourceLinksHash;
|
|
518
|
+
}
|
|
502
519
|
this.initializePromise = Promise.resolve();
|
|
503
520
|
for (const lease of input.leases) this.leases.set(lease.workspaceId, { ...lease });
|
|
504
521
|
for (const artifact of input.artifacts) this.artifacts.set(artifact.artifactId, { ...artifact });
|
|
@@ -525,6 +542,10 @@ export class WorkspaceManager {
|
|
|
525
542
|
return this.templatePath;
|
|
526
543
|
}
|
|
527
544
|
|
|
545
|
+
originalSourceLink(path: string): string | undefined {
|
|
546
|
+
return Object.hasOwn(this.sourceLinks, path) ? this.sourceLinks[path] : undefined;
|
|
547
|
+
}
|
|
548
|
+
|
|
528
549
|
rootRepoPath(): string {
|
|
529
550
|
if (!this.repoRoot) throw new Error("Workspace snapshot is not initialized");
|
|
530
551
|
return this.repoRoot;
|
|
@@ -557,6 +578,7 @@ export class WorkspaceManager {
|
|
|
557
578
|
this.workspaceTempRoot = undefined;
|
|
558
579
|
this.templatePath = undefined;
|
|
559
580
|
this.baseOid = undefined;
|
|
581
|
+
this.sourceLinksHash = undefined; this.sourceLinks = Object.create(null);
|
|
560
582
|
this.initializePromise = undefined;
|
|
561
583
|
this.artifacts.clear();
|
|
562
584
|
this.leases.clear();
|
|
@@ -575,6 +597,7 @@ export class WorkspaceManager {
|
|
|
575
597
|
this.workspaceTempRoot = undefined;
|
|
576
598
|
this.templatePath = undefined;
|
|
577
599
|
this.baseOid = undefined;
|
|
600
|
+
this.sourceLinksHash = undefined; this.sourceLinks = Object.create(null);
|
|
578
601
|
this.repoRoot = undefined;
|
|
579
602
|
this.initializePromise = undefined;
|
|
580
603
|
throw error;
|
|
@@ -631,9 +654,17 @@ export class WorkspaceManager {
|
|
|
631
654
|
if (copyTreeOid(before) !== copyTreeOid(after)) throw new Error("Parent workspace changed during child Git capture");
|
|
632
655
|
this.copyWithPrivateGit = { ownerDirectory, snapshotRepository: join(history, "repository.git") };
|
|
633
656
|
}
|
|
634
|
-
const
|
|
657
|
+
const links: Record<string, string> = Object.create(null);
|
|
658
|
+
const tree = await scanCopyTree(this.repoRoot, true, true, true, undefined, undefined, links);
|
|
635
659
|
await materializeCopyTree(this.repoRoot, this.templatePath, tree);
|
|
636
|
-
|
|
660
|
+
const afterLinks: Record<string, string> = Object.create(null);
|
|
661
|
+
if (copyTreeOid(await scanCopyTree(this.repoRoot, true, true, true, undefined, undefined, afterLinks)) !== copyTreeOid(tree)
|
|
662
|
+
|| JSON.stringify(links) !== JSON.stringify(afterLinks)) throw new Error("Copy workspace changed during snapshot");
|
|
663
|
+
if (Object.keys(links).length) {
|
|
664
|
+
const json = JSON.stringify(links);
|
|
665
|
+
await writeFile(join(this.batchRoot!, "source-links.json"), json, { flag: "wx", mode: 0o600 });
|
|
666
|
+
this.sourceLinks = links; this.sourceLinksHash = createHash("sha256").update(json).digest("hex");
|
|
667
|
+
}
|
|
637
668
|
this.baseOid = copyTreeOid(tree);
|
|
638
669
|
return;
|
|
639
670
|
}
|
|
@@ -15,6 +15,8 @@ export interface WorkspaceLease {
|
|
|
15
15
|
repoPath?: string;
|
|
16
16
|
baseOid?: string;
|
|
17
17
|
batchPath?: string;
|
|
18
|
+
/** Host-owned raw source-link baseline, outside every writable clone. */
|
|
19
|
+
sourceLinksHash?: string;
|
|
18
20
|
/** Host-created private metadata, excluded from delivered file artifacts. */
|
|
19
21
|
privateGit?: PrivateGitBinding;
|
|
20
22
|
}
|