@staix/agent-hub 0.36.0 → 0.38.0
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/CHANGELOG.md +27 -0
- package/README.md +6 -2
- package/THIRD_PARTY_NOTICES.md +0 -18
- package/docs/agent-notes/README.md +13 -3
- package/docs/agent-notes/daemon.md +4 -4
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/models.md +2 -1
- package/docs/agent-notes/tasks.md +1 -1
- package/docs/agent-notes/tests.md +1 -2
- package/docs/contracts/companion-cli-v1.json +70 -0
- package/docs/design/adapters.md +43 -2
- package/docs/design/agent-hub-architecture.md +9 -1
- package/docs/design/guidance-probes.md +1167 -0
- package/docs/design/model-routes.md +437 -12
- package/docs/dogfood.md +12 -13
- package/docs/events.md +20 -1
- package/docs/memory.md +3 -3
- package/docs/operations.md +123 -151
- package/docs/profiles.md +1 -1
- package/docs/quickstart.md +15 -3
- package/docs/research.md +1 -1
- package/docs/sdlc.md +5 -3
- package/docs/security.md +25 -1
- package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
- package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
- package/docs/verification/2026-11-11-0.37.0.md +40 -0
- package/docs/verification/2026-11-11-0.38.0.md +41 -0
- package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
- package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
- package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
- package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
- package/docs/verified.json +25 -25
- package/package.json +3 -4
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +2403 -1444
- package/plugins/agent-hub/server.js +2480 -1509
- package/src/adapters/channel-peer.ts +7 -1
- package/src/adapters/claude-channel.ts +2 -1
- package/src/adapters/compat.ts +1 -1
- package/src/adapters/local-probe.ts +233 -0
- package/src/adapters/local-worker.ts +232 -21
- package/src/cli/console-state.ts +25 -6
- package/src/cli/console-versions.ts +99 -0
- package/src/cli/console.ts +13 -1
- package/src/cli/help.ts +2 -1
- package/src/cli/init.ts +3 -1
- package/src/cli/install-paths.ts +7 -2
- package/src/cli/main.ts +78 -7
- package/src/cli/output.ts +8 -4
- package/src/cli/runtime-version-warning.ts +2 -2
- package/src/cli/sdlc-output.ts +9 -5
- package/src/cli/upgrade-runtime.ts +1 -1
- package/src/hub/bus.ts +2 -2
- package/src/hub/config-apply.ts +4 -2
- package/src/hub/config-trust.ts +6 -1
- package/src/hub/control-client.ts +5 -2
- package/src/hub/daemon.ts +195 -13
- package/src/hub/envelope.ts +6 -1
- package/src/hub/events.ts +3 -2
- package/src/hub/guidance-probe-store.ts +1044 -0
- package/src/hub/guidance-probes.ts +692 -0
- package/src/hub/inference.ts +18 -5
- package/src/hub/manager.ts +24 -1
- package/src/hub/operational-authority.ts +14 -1
- package/src/hub/peers.ts +5 -0
- package/src/hub/person-command.ts +25 -0
- package/src/hub/ports.ts +1 -1
- package/src/hub/progress.ts +23 -16
- package/src/hub/report.ts +2 -0
- package/src/hub/research.ts +1 -0
- package/src/hub/restart.ts +7 -0
- package/src/hub/sdlc-release-authorization.ts +139 -17
- package/src/hub/sdlc-release-policy.ts +100 -0
- package/src/hub/sdlc-release.ts +59 -7
- package/src/hub/supervision.ts +3 -2
- package/src/hub/tasks.ts +363 -7
- package/src/local/probe-errors.ts +28 -0
- package/src/local/probe-sandbox.ts +224 -0
- package/src/local/probe-types.ts +110 -0
- package/src/local/probe-workspace.ts +426 -0
- package/src/local/sandbox.ts +71 -2
- package/src/local/tools.ts +135 -9
- package/src/models/route/advisor-trigger.ts +88 -0
- package/src/models/route/config.ts +21 -17
- package/src/models/route/conversation-view.ts +179 -0
- package/src/models/route/decision-evidence.ts +1 -1
- package/src/models/route/decision.ts +114 -19
- package/src/models/route/escalation-control.ts +30 -0
- package/src/models/route/hub-prompts.ts +97 -0
- package/src/models/route/judge-choice.ts +155 -0
- package/src/models/route/judge-replies.ts +102 -0
- package/src/models/route/labels.ts +14 -70
- package/src/models/route/observation-signals.ts +250 -0
- package/src/models/route/plan-execute-choice.ts +27 -0
- package/src/models/route/relay-selector.ts +2 -2
- package/src/models/route/runtime.ts +115 -52
- package/src/models/route/turn-state.ts +77 -0
- package/src/omniroute/client.ts +3 -0
- package/src/ui/guidance-panel.ts +34 -2
- package/src/ui/guidance-view.ts +33 -0
- package/src/ui/plugin.ts +80 -23
- package/src/version.ts +4 -0
- package/templates/AGENTS.block.md +14 -14
- package/templates/adec/README.md +32 -0
- package/templates/adec/ahub.plan-execute.json +23 -0
- package/templates/adec/ahub.stage.json +23 -0
- package/templates/profiles/general.json +1 -1
- package/templates/profiles/research.json +1 -1
- package/templates/profiles/writing.json +1 -1
- package/LICENSES/Apache-2.0.txt +0 -204
- package/src/models/route/advisor.ts +0 -102
- package/src/models/route/escalation.ts +0 -82
- package/src/models/route/judge.ts +0 -23
- package/src/models/route/normalize.ts +0 -103
- package/src/models/route/plan-execute.ts +0 -52
- package/src/models/route/prompts.ts +0 -8
- package/src/models/route/signals.ts +0 -247
- package/src/models/route/state.ts +0 -54
- package/src/models/route/text.ts +0 -61
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { chmodSync, constants, closeSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, opendirSync, readSync, rmSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import { executionText, EXECUTION_REFERENCE_LIMITS } from "../hub/execution-reference.ts";
|
|
6
|
+
import { hubGitSync } from "../hub/git.ts";
|
|
7
|
+
import { guidanceProbeCanonical, GUIDANCE_PROBE_LIMITS, PROBE_OUTPUT_LIMITS, probeOutputName, type ProbeDataPolicyV1, type ProbeExcludedReason, type ProbeOutputEntry, type ProbeOutputExcluded,
|
|
8
|
+
type ProbeOutputManifestV1, type ProbeRetainedRecord, type ProbeSlot, type ProbeTree } from "../hub/guidance-probes.ts";
|
|
9
|
+
import { foldSegment } from "../hub/permission-mode.ts";
|
|
10
|
+
import { realPath } from "../hub/project.ts";
|
|
11
|
+
import { isDenied } from "./deny.ts";
|
|
12
|
+
import { ProbeToolRefusal } from "./probe-errors.ts";
|
|
13
|
+
|
|
14
|
+
/** Availability ceilings, narrowed by the admitted budget. ponytail: manifest-declared materialization ceilings are the upgrade path. */
|
|
15
|
+
export const PROBE_WORKSPACE_LIMITS = Object.freeze({ fileBytes: 1024 * 1024, workspaceBytes: 64 * 1024 * 1024 });
|
|
16
|
+
export interface ProbeMaterializedFile { dataId: string; relative: string; sha256: string; bytes: Uint8Array }
|
|
17
|
+
export type ProbeSourceClass = "tree" | "task_source" | "closed_artifact" | "anonymized_deliverable" | "closed_round_evidence" | "improver_context";
|
|
18
|
+
export interface ProbeWorkspaceInput {
|
|
19
|
+
role: ProbeSlot["role"];
|
|
20
|
+
policy: ProbeDataPolicyV1;
|
|
21
|
+
files: readonly ProbeMaterializedFile[];
|
|
22
|
+
sourceTree?: { repo: string; tree: ProbeTree; files: readonly { dataId: string; path: string }[] };
|
|
23
|
+
/** Trusted source-owner verification, never a declaration or model-selected classifier. */
|
|
24
|
+
verifySource(file: ProbeMaterializedFile, role: ProbeSlot["role"]): ProbeSourceClass | Promise<ProbeSourceClass>;
|
|
25
|
+
/** Completes the owner ledger reservation before this module creates a directory or writes bytes. */
|
|
26
|
+
reserveStorage(bytes: number): void | Promise<void>;
|
|
27
|
+
current(): void;
|
|
28
|
+
maxBytes: number;
|
|
29
|
+
}
|
|
30
|
+
export interface ProbeWorkspace {
|
|
31
|
+
readonly role: ProbeSlot["role"];
|
|
32
|
+
readonly root: string;
|
|
33
|
+
readonly home: string;
|
|
34
|
+
readonly scratch: string;
|
|
35
|
+
readonly output: string;
|
|
36
|
+
readonly inputDigest: string;
|
|
37
|
+
readonly files: readonly Readonly<{ dataId: string; relative: string; sha256: string; bytes: number }>[];
|
|
38
|
+
readonly allowedWrites: readonly string[];
|
|
39
|
+
}
|
|
40
|
+
interface DirectoryIdentity { file: string; dev: number; ino: number }
|
|
41
|
+
interface WorkspaceState { parent: string; temporaryRoot: string; current(): void; reserveStorage(bytes: number): void | Promise<void>; maximum: number; charged: number; directories: readonly DirectoryIdentity[]; identities: readonly { file: string; dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }[] }
|
|
42
|
+
const workspaces = new WeakMap<ProbeWorkspace, WorkspaceState>();
|
|
43
|
+
const digest = (bytes: Uint8Array | string): string => createHash("sha256").update(bytes).digest("hex");
|
|
44
|
+
function refused(): never { throw new Error("probe workspace source, role, path or resource proof is unavailable"); }
|
|
45
|
+
const integer = (value: number): boolean => Number.isSafeInteger(value) && value >= 0;
|
|
46
|
+
const sha = (value: string): boolean => /^[a-f0-9]{64}$/.test(value);
|
|
47
|
+
const roleNames: readonly ProbeSlot["role"][] = ["worker", "proposal", "compose", "select", "reflect"];
|
|
48
|
+
function directoryIdentity(file: string): DirectoryIdentity {
|
|
49
|
+
const stat = lstatSync(file);
|
|
50
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || realPath(file) !== file) refused();
|
|
51
|
+
return { file, dev: stat.dev, ino: stat.ino };
|
|
52
|
+
}
|
|
53
|
+
function requireDirectory(identity: DirectoryIdentity): void {
|
|
54
|
+
const current = directoryIdentity(identity.file);
|
|
55
|
+
if (current.dev !== identity.dev || current.ino !== identity.ino) refused();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The same folded names as ordinary guards, with no Git, hub or dependency tree in a probe. */
|
|
59
|
+
export function probeRelativePath(value: string): boolean {
|
|
60
|
+
return executionText(value, EXECUTION_REFERENCE_LIMITS.id) && !isAbsolute(value) && !value.includes("\\")
|
|
61
|
+
&& !/^[a-z]:/i.test(value) && !isDenied(value)
|
|
62
|
+
&& value.split("/").every(part => !!part && ![".", "..", ".git", ".agenthub", "node_modules", ".probe-temp"].includes(foldSegment(part)));
|
|
63
|
+
}
|
|
64
|
+
function permitted(role: ProbeSlot["role"], source: ProbeSourceClass, policy: ProbeDataPolicyV1): boolean {
|
|
65
|
+
if (role === "worker") return policy.roles.worker.guidanceOnlyExperience === true && (source === "tree" || source === "task_source");
|
|
66
|
+
if (role === "proposal" || role === "compose") return source === "tree" || source === "task_source" || source === "closed_artifact"
|
|
67
|
+
|| source === "improver_context" && policy.roles[role].improverContext === true;
|
|
68
|
+
if (role === "select") return policy.roles.select.anonymizedDeliverables === true && (source === "task_source" || source === "anonymized_deliverable");
|
|
69
|
+
return role === "reflect" && policy.roles.reflect.closedRoundOnly === true && source === "closed_round_evidence";
|
|
70
|
+
}
|
|
71
|
+
function sourceTreeFile(input: ProbeWorkspaceInput, file: ProbeMaterializedFile, paths: Map<string, string>): void {
|
|
72
|
+
const source = input.sourceTree, path = paths.get(file.dataId);
|
|
73
|
+
if (!source || !path || !probeRelativePath(path)) refused();
|
|
74
|
+
const oid = source.tree.oid;
|
|
75
|
+
if (!(source.tree.objectFormat === "sha1" && /^[a-f0-9]{40}$/.test(oid)
|
|
76
|
+
|| source.tree.objectFormat === "sha256" && /^[a-f0-9]{64}$/.test(oid))) refused();
|
|
77
|
+
const repo = realPath(source.repo);
|
|
78
|
+
const git = (args: string[], maximum: number) => {
|
|
79
|
+
input.current();
|
|
80
|
+
const result = hubGitSync(["-C", repo, ...args], { encoding: "utf8", timeout: 5000, maxBuffer: maximum });
|
|
81
|
+
input.current();
|
|
82
|
+
if (result.error || result.status !== 0) refused();
|
|
83
|
+
return result.stdout;
|
|
84
|
+
};
|
|
85
|
+
if (git(["rev-parse", "--show-object-format"], EXECUTION_REFERENCE_LIMITS.id).trim() !== source.tree.objectFormat
|
|
86
|
+
|| git(["cat-file", "-t", oid], EXECUTION_REFERENCE_LIMITS.id).trim() !== "tree") refused();
|
|
87
|
+
const entry = git(["--literal-pathspecs", "ls-tree", "-z", "--full-tree", oid, "--", path], EXECUTION_REFERENCE_LIMITS.id * 2);
|
|
88
|
+
const match = /^(100644|100755) blob ([a-f0-9]{40}|[a-f0-9]{64})\t([^\0]+)\0$/.exec(entry);
|
|
89
|
+
if (!match || match[3] !== path) refused();
|
|
90
|
+
const nativeObject = createHash(source.tree.objectFormat).update(`blob ${file.bytes.byteLength}`).update(Buffer.alloc(1)).update(file.bytes).digest("hex");
|
|
91
|
+
if (nativeObject !== match[2]) refused();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Materialize only verified admitted bytes. It never creates a Git worktree or exposes an object store. */
|
|
95
|
+
export async function materializeProbeWorkspace(input: ProbeWorkspaceInput): Promise<ProbeWorkspace> {
|
|
96
|
+
if (!roleNames.includes(input.role) || !integer(input.maxBytes)
|
|
97
|
+
|| typeof input.current !== "function" || typeof input.reserveStorage !== "function" || typeof input.verifySource !== "function") refused();
|
|
98
|
+
if (input.maxBytes > PROBE_WORKSPACE_LIMITS.workspaceBytes) throw new ProbeToolRefusal("workspace_ceiling");
|
|
99
|
+
input.current();
|
|
100
|
+
// Keep the host's checked declaration stable across source/reservation awaits.
|
|
101
|
+
input = { ...input, policy: JSON.parse(guidanceProbeCanonical(input.policy, GUIDANCE_PROBE_LIMITS.snapshotBytes)) as ProbeDataPolicyV1,
|
|
102
|
+
...(input.sourceTree ? { sourceTree: { repo: input.sourceTree.repo, tree: { ...input.sourceTree.tree }, files: input.sourceTree.files.map(item => ({ ...item })) } } : {}) };
|
|
103
|
+
const member = new Set(input.policy.roles[input.role].dataIds), declared = new Map(input.policy.admittedData.map(row => [row.id, row]));
|
|
104
|
+
if (member.size !== input.policy.roles[input.role].dataIds.length || declared.size !== input.policy.admittedData.length) refused();
|
|
105
|
+
const seenIds = new Set<string>(), foldedPaths = new Map<string, { spelling: string; directory: boolean }>(), treePaths = new Map<string, string>();
|
|
106
|
+
for (const item of input.sourceTree?.files ?? []) {
|
|
107
|
+
if (treePaths.has(item.dataId) || !probeRelativePath(item.path)) refused();
|
|
108
|
+
treePaths.set(item.dataId, item.path);
|
|
109
|
+
}
|
|
110
|
+
let total = 0;
|
|
111
|
+
const files: ProbeMaterializedFile[] = [];
|
|
112
|
+
for (const original of input.files) {
|
|
113
|
+
if (!executionText(original.dataId, EXECUTION_REFERENCE_LIMITS.id) || !probeRelativePath(original.relative)
|
|
114
|
+
|| !sha(original.sha256) || !(original.bytes instanceof Uint8Array) || seenIds.has(original.dataId) || !member.has(original.dataId)) refused();
|
|
115
|
+
if (original.bytes.byteLength > PROBE_WORKSPACE_LIMITS.fileBytes) throw new ProbeToolRefusal("file_ceiling");
|
|
116
|
+
const file = Object.freeze({ dataId: original.dataId, relative: original.relative, sha256: original.sha256, bytes: Buffer.from(original.bytes) });
|
|
117
|
+
const admission = declared.get(file.dataId);
|
|
118
|
+
if (!admission || !integer(admission.bytes) || admission.bytes !== file.bytes.length || admission.sha256 !== file.sha256
|
|
119
|
+
|| file.bytes.length > PROBE_WORKSPACE_LIMITS.fileBytes || digest(file.bytes) !== file.sha256) refused();
|
|
120
|
+
seenIds.add(file.dataId); total += file.bytes.length;
|
|
121
|
+
if (total > input.maxBytes) throw new ProbeToolRefusal("workspace_ceiling");
|
|
122
|
+
const parts = file.relative.split("/");
|
|
123
|
+
if (["scratch", "output"].includes(foldSegment(parts[0]!))) refused();
|
|
124
|
+
for (let index = 1; index <= parts.length; index++) {
|
|
125
|
+
const spelling = parts.slice(0, index).join("/"), directory = index < parts.length, key = parts.slice(0, index).map(foldSegment).join("/");
|
|
126
|
+
const prior = foldedPaths.get(key);
|
|
127
|
+
if (prior && (prior.spelling !== spelling || prior.directory !== directory || !directory)) refused();
|
|
128
|
+
foldedPaths.set(key, { spelling, directory });
|
|
129
|
+
}
|
|
130
|
+
files.push(file);
|
|
131
|
+
}
|
|
132
|
+
if (seenIds.size !== member.size || [...member].some(id => !seenIds.has(id)) || [...treePaths.keys()].some(id => !seenIds.has(id))) refused();
|
|
133
|
+
for (const file of files) {
|
|
134
|
+
input.current();
|
|
135
|
+
const source = await input.verifySource(file, input.role);
|
|
136
|
+
input.current();
|
|
137
|
+
if (!permitted(input.role, source, input.policy) || digest(file.bytes) !== file.sha256) refused();
|
|
138
|
+
if (source === "tree") sourceTreeFile(input, file, treePaths);
|
|
139
|
+
else if (treePaths.has(file.dataId)) refused();
|
|
140
|
+
}
|
|
141
|
+
const writes = input.policy.allowedWrites.map(row => {
|
|
142
|
+
if (!["scratch", "output"].includes(row.root) || !probeRelativePath(row.relative)) refused();
|
|
143
|
+
return `${row.root}/${row.relative}`;
|
|
144
|
+
});
|
|
145
|
+
if (new Set(writes.map(value => value.split("/").map(foldSegment).join("/"))).size !== writes.length) refused();
|
|
146
|
+
input.current();
|
|
147
|
+
await input.reserveStorage(total);
|
|
148
|
+
input.current();
|
|
149
|
+
// The complete setup charge has succeeded. No filesystem write occurs before it.
|
|
150
|
+
const parent = realPath(mkdtempSync(join(tmpdir(), "ahub-probe-")));
|
|
151
|
+
const directories = [directoryIdentity(parent)];
|
|
152
|
+
const directoryMap = new Map(directories.map(entry => [entry.file, entry]));
|
|
153
|
+
const setupFiles = new Map<string, { dev: number; ino: number }>();
|
|
154
|
+
const root = join(parent, "workspace"), home = join(parent, "home"), temporaryRoot = join(root, ".probe-temp");
|
|
155
|
+
const mkdir = (directory: string): void => {
|
|
156
|
+
requireDirectory(directories[0]!);
|
|
157
|
+
const actualRoot = directoryMap.get(root); if (actualRoot) requireDirectory(actualRoot);
|
|
158
|
+
const existing = directoryMap.get(directory);
|
|
159
|
+
if (existing) { requireDirectory(existing); return; }
|
|
160
|
+
if (lstatSync(directory, { throwIfNoEntry: false })) refused();
|
|
161
|
+
if (dirname(directory) !== parent) mkdir(dirname(directory));
|
|
162
|
+
mkdirSync(directory, { mode: 0o700 }); const identity = directoryIdentity(directory); directories.push(identity); directoryMap.set(directory, identity);
|
|
163
|
+
};
|
|
164
|
+
try {
|
|
165
|
+
chmodSync(parent, 0o700);
|
|
166
|
+
for (const directory of [root, home, temporaryRoot, join(root, "scratch"), join(root, "output")]) mkdir(directory);
|
|
167
|
+
const physicalRoots = [...directories];
|
|
168
|
+
for (const file of files) {
|
|
169
|
+
input.current();
|
|
170
|
+
if (digest(file.bytes) !== file.sha256) refused();
|
|
171
|
+
const dest = join(root, file.relative); mkdir(dirname(dest));
|
|
172
|
+
const fd = openSync(dest, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o400);
|
|
173
|
+
try {
|
|
174
|
+
const created = fstatSync(fd); setupFiles.set(dest, { dev: created.dev, ino: created.ino });
|
|
175
|
+
writeFileSync(fd, file.bytes); const stat = fstatSync(fd); if (!stat.isFile() || stat.nlink !== 1 || stat.size !== file.bytes.length) refused();
|
|
176
|
+
} finally { closeSync(fd); }
|
|
177
|
+
}
|
|
178
|
+
input.current();
|
|
179
|
+
const descriptors = files.map(({ dataId, relative, sha256, bytes }) => Object.freeze({ dataId, relative, sha256, bytes: bytes.length }));
|
|
180
|
+
const workspace: ProbeWorkspace = Object.freeze({ role: input.role, root, home, scratch: join(root, "scratch"), output: join(root, "output"),
|
|
181
|
+
inputDigest: digest(JSON.stringify(descriptors)), files: Object.freeze(descriptors), allowedWrites: Object.freeze(writes.map(path => join(root, path))) });
|
|
182
|
+
const identities = descriptors.map(item => {
|
|
183
|
+
const file = join(root, item.relative), stat = lstatSync(file);
|
|
184
|
+
return { file, dev: stat.dev, ino: stat.ino, size: stat.size, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs };
|
|
185
|
+
});
|
|
186
|
+
for (const entry of directories) requireDirectory(entry);
|
|
187
|
+
workspaces.set(workspace, { parent, temporaryRoot, current: input.current, reserveStorage: input.reserveStorage, maximum: input.maxBytes, charged: total, directories: physicalRoots, identities });
|
|
188
|
+
return workspace;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
// No child has been exposed. Remove only the same bounded fresh namespace we created, never a replacement.
|
|
191
|
+
for (const entry of directories) requireDirectory(entry);
|
|
192
|
+
const ownedDirs = new Map(directories.map(entry => [entry.file, entry]));
|
|
193
|
+
const check = (directory: string) => {
|
|
194
|
+
const handle = opendirSync(directory);
|
|
195
|
+
try {
|
|
196
|
+
for (let entry = handle.readSync(); entry; entry = handle.readSync()) {
|
|
197
|
+
const file = join(directory, entry.name), ownedDirectory = ownedDirs.get(file), ownedFile = setupFiles.get(file);
|
|
198
|
+
if (ownedDirectory) { requireDirectory(ownedDirectory); check(file); }
|
|
199
|
+
else {
|
|
200
|
+
const stat = lstatSync(file);
|
|
201
|
+
if (!ownedFile || !stat.isFile() || stat.nlink !== 1 || stat.dev !== ownedFile.dev || stat.ino !== ownedFile.ino) refused();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
} finally { handle.closeSync(); }
|
|
205
|
+
};
|
|
206
|
+
check(parent); requireDirectory(directories[0]!); rmSync(parent, { recursive: true, force: true });
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Narrow physical ownership only, usable after role/privacy withdrawal to stop our own resources. */
|
|
212
|
+
export function probeWorkspacePhysical(workspace: ProbeWorkspace): void {
|
|
213
|
+
const state = workspaces.get(workspace); if (!state) refused();
|
|
214
|
+
for (const directory of state.directories) requireDirectory(directory);
|
|
215
|
+
}
|
|
216
|
+
export function probeWorkspaceCurrent(workspace: ProbeWorkspace): void {
|
|
217
|
+
const state = workspaces.get(workspace); if (!state) refused(); state.current();
|
|
218
|
+
probeWorkspacePhysical(workspace);
|
|
219
|
+
for (const entry of state.identities) {
|
|
220
|
+
const stat = lstatSync(entry.file);
|
|
221
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size !== entry.size
|
|
222
|
+
|| stat.mtimeMs !== entry.mtimeMs || stat.ctimeMs !== entry.ctimeMs) refused();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
export function probeWorkspacePrivateRoot(workspace: ProbeWorkspace): string { probeWorkspaceCurrent(workspace); return workspaces.get(workspace)!.parent; }
|
|
226
|
+
export function probeWorkspaceTemporaryRoot(workspace: ProbeWorkspace): string { probeWorkspaceCurrent(workspace); return workspaces.get(workspace)!.temporaryRoot; }
|
|
227
|
+
/** Local conservative ceiling, called before the owner ledger's compound admission; never performs a second ledger effect. */
|
|
228
|
+
export function reserveProbeWorkspaceBytes(workspace: ProbeWorkspace, bytes: number): void {
|
|
229
|
+
probeWorkspaceCurrent(workspace); const state = workspaces.get(workspace)!;
|
|
230
|
+
if (!integer(bytes)) refused();
|
|
231
|
+
if (state.charged + bytes > state.maximum) throw new ProbeToolRefusal("workspace_ceiling");
|
|
232
|
+
state.charged += bytes;
|
|
233
|
+
}
|
|
234
|
+
export async function reserveProbeWorkspaceStorage(workspace: ProbeWorkspace, bytes: number): Promise<void> {
|
|
235
|
+
reserveProbeWorkspaceBytes(workspace, bytes); const state = workspaces.get(workspace)!;
|
|
236
|
+
await state.reserveStorage(bytes); state.current();
|
|
237
|
+
probeWorkspaceCurrent(workspace);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
241
|
+
// T3 (#1226): output collection and owned cleanup. Contract: docs/design/guidance-probes.md "T3 receipts, reconcile and cleanup contract".
|
|
242
|
+
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
/** What `collectProbeOutput` read: the manifest, the exact bytes it hashed (kept for retention, never re-read from a path), and the measured scratch. */
|
|
245
|
+
export interface ProbeCollected {
|
|
246
|
+
manifest: ProbeOutputManifestV1;
|
|
247
|
+
/** The bytes hashed for each manifest entry, read once through the opened file. Retention copies these and never re-reads the workspace. Bounded by 64 files of 1 MiB. */
|
|
248
|
+
contents: ReadonlyMap<string, Buffer>;
|
|
249
|
+
scratchBytes: number;
|
|
250
|
+
/** True when scratch was not fully measured (a tree deeper than the walk limit): its size is unknown, so it must be treated as over the cap. */
|
|
251
|
+
scratchUnmeasured: boolean;
|
|
252
|
+
}
|
|
253
|
+
/** The deepest directory level read under output or scratch. Anything deeper is excluded (output) or makes scratch unmeasured, never silently skipped. */
|
|
254
|
+
export const PROBE_WALK_DEPTH = 8;
|
|
255
|
+
/**
|
|
256
|
+
* The most directory entries read in ONE walk (output, then scratch separately). The walk is synchronous on the daemon's event loop, so a confined child that
|
|
257
|
+
* leaves a million empty files (well under every byte cap) must not stall the control socket and every peer. Reaching it is a limit, never a silent stop:
|
|
258
|
+
* output is excluded whole (`over_walk_cap`, nothing hashed or retained from a walk that did not finish) and scratch becomes unmeasured, which is over the cap.
|
|
259
|
+
*/
|
|
260
|
+
export const PROBE_WALK_ENTRIES = 4096;
|
|
261
|
+
/** Test seam only: a hook that runs between a file's lstat and its open, to swap the file the way a racing process would. */
|
|
262
|
+
export interface ProbeCollectSeam { beforeOpen?(file: string): void; walkEntries?: number }
|
|
263
|
+
class WalkCapReached extends Error {}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Collect a finished session's declared output into a manifest: every regular, link-count-1 file under the output root is read through its opened descriptor
|
|
267
|
+
* and hashed, and the identity is re-checked after the read. Anything else (a symlink, a hardlink, a device, a directory entry the policy does not
|
|
268
|
+
* declare, a file past the per-file cap, a file that changed while read, a tree deeper than the walk limit) is recorded as an exclusion and is NOT hashed.
|
|
269
|
+
* Bytes past `maxBytes` are not read. Files are opened O_NONBLOCK|O_NOFOLLOW and must still be regular files once open, so a file swapped for a FIFO
|
|
270
|
+
* or a device after its lstat can neither block this call nor be read. Call it only after the confinement stop has reported quiescence: until then a
|
|
271
|
+
* child may still be writing. Reads only; it deletes nothing and follows no link.
|
|
272
|
+
*/
|
|
273
|
+
export function collectProbeOutput(workspace: ProbeWorkspace, maxBytes: number, seam: ProbeCollectSeam = {}): ProbeCollected {
|
|
274
|
+
probeWorkspacePhysical(workspace);
|
|
275
|
+
const entries: ProbeOutputEntry[] = [], excluded: ProbeOutputExcluded[] = [], contents = new Map<string, Buffer>();
|
|
276
|
+
let total = 0, visited = 0;
|
|
277
|
+
const walkCap = seam.walkEntries ?? PROBE_WALK_ENTRIES;
|
|
278
|
+
const declared = workspace.allowedWrites.filter(path => path === workspace.output || path.startsWith(workspace.output + "/"));
|
|
279
|
+
const within = (file: string): boolean => declared.some(path => file === path || file.startsWith(path + "/"));
|
|
280
|
+
// An exclusion is itself a receipt field, so its name must pass the same check as any other: a name that is too long or carries a control or format
|
|
281
|
+
// character is recorded under a stable digest label with the `invalid_name` reason, never dropped and never written raw.
|
|
282
|
+
const exclude = (relative: string, reason: ProbeExcludedReason): void => {
|
|
283
|
+
if (excluded.length >= PROBE_OUTPUT_LIMITS.entries) return;
|
|
284
|
+
if (!probeOutputName(relative)) { excluded.push({ relative: `invalid-name-${digest(relative).slice(0, 32)}`, reason: "invalid_name" }); return; }
|
|
285
|
+
excluded.push({ relative, reason });
|
|
286
|
+
};
|
|
287
|
+
const walk = (directory: string, depth: number): void => {
|
|
288
|
+
if (depth > PROBE_WALK_DEPTH) { exclude(directory.slice(workspace.root.length + 1), "over_depth"); return; }
|
|
289
|
+
const handle = opendirSync(directory);
|
|
290
|
+
try {
|
|
291
|
+
for (let item = handle.readSync(); item; item = handle.readSync()) {
|
|
292
|
+
if (++visited > walkCap) throw new WalkCapReached();
|
|
293
|
+
const file = join(directory, item.name), relative = file.slice(workspace.root.length + 1);
|
|
294
|
+
const before = lstatSync(file, { throwIfNoEntry: false });
|
|
295
|
+
if (!before) continue;
|
|
296
|
+
if (before.isSymbolicLink()) { exclude(relative, "not_regular"); continue; }
|
|
297
|
+
if (before.isDirectory()) { walk(file, depth + 1); continue; }
|
|
298
|
+
if (!before.isFile()) { exclude(relative, "not_regular"); continue; }
|
|
299
|
+
if (before.nlink !== 1) { exclude(relative, "linked"); continue; }
|
|
300
|
+
// A name the receipt could not carry (past the name bound, or with a control or format character) is never hashed or retained: it is an exclusion.
|
|
301
|
+
if (!probeOutputName(relative)) { exclude(relative, "invalid_name"); continue; }
|
|
302
|
+
if (!within(file)) { exclude(relative, "outside_declared_writes"); continue; }
|
|
303
|
+
if (before.size > PROBE_OUTPUT_LIMITS.fileBytes) { exclude(relative, "over_file_cap"); continue; }
|
|
304
|
+
if (entries.length >= PROBE_OUTPUT_LIMITS.entries) { exclude(relative, "over_entry_cap"); continue; }
|
|
305
|
+
if (total + before.size > maxBytes) { exclude(relative, "over_total_cap"); continue; }
|
|
306
|
+
seam.beforeOpen?.(file);
|
|
307
|
+
let fd: number;
|
|
308
|
+
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
|
309
|
+
catch { exclude(relative, "changed_while_read"); continue; }
|
|
310
|
+
let bytes: Buffer;
|
|
311
|
+
try {
|
|
312
|
+
const opened = fstatSync(fd);
|
|
313
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.nlink !== 1) { exclude(relative, "changed_while_read"); continue; }
|
|
314
|
+
bytes = Buffer.alloc(Math.min(opened.size, PROBE_OUTPUT_LIMITS.fileBytes));
|
|
315
|
+
let read = 0; while (read < bytes.length) { const n = readSync(fd, bytes, read, bytes.length - read, read); if (n === 0) break; read += n; }
|
|
316
|
+
const after = fstatSync(fd);
|
|
317
|
+
if (read !== opened.size || after.size !== opened.size || after.ino !== opened.ino || after.mtimeMs !== opened.mtimeMs) { exclude(relative, "changed_while_read"); continue; }
|
|
318
|
+
} finally { closeSync(fd); }
|
|
319
|
+
entries.push({ relative, sha256: digest(bytes), bytes: bytes.length }); contents.set(relative, bytes); total += bytes.length;
|
|
320
|
+
}
|
|
321
|
+
} finally { handle.closeSync(); }
|
|
322
|
+
};
|
|
323
|
+
try { walk(workspace.output, 0); }
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (!(error instanceof WalkCapReached)) throw error;
|
|
326
|
+
// The walk did not finish, so nothing it read is a complete answer: discard it and exclude the whole output with the reason that forbids a success.
|
|
327
|
+
entries.length = 0; excluded.length = 0; contents.clear(); total = 0;
|
|
328
|
+
exclude(workspace.output.slice(workspace.root.length + 1), "over_walk_cap");
|
|
329
|
+
}
|
|
330
|
+
let scratch = 0, scratchUnmeasured = false;
|
|
331
|
+
const measure = (directory: string, depth: number): void => {
|
|
332
|
+
if (depth > PROBE_WALK_DEPTH) { scratchUnmeasured = true; return; }
|
|
333
|
+
const handle = opendirSync(directory);
|
|
334
|
+
try {
|
|
335
|
+
for (let item = handle.readSync(); item; item = handle.readSync()) {
|
|
336
|
+
if (++visited > walkCap) throw new WalkCapReached();
|
|
337
|
+
const file = join(directory, item.name), stat = lstatSync(file, { throwIfNoEntry: false });
|
|
338
|
+
if (!stat) continue;
|
|
339
|
+
if (stat.isDirectory()) measure(file, depth + 1); else if (stat.isFile()) scratch += stat.size;
|
|
340
|
+
}
|
|
341
|
+
} finally { handle.closeSync(); }
|
|
342
|
+
};
|
|
343
|
+
visited = 0;
|
|
344
|
+
try { measure(workspace.scratch, 0); }
|
|
345
|
+
catch (error) { if (!(error instanceof WalkCapReached)) throw error; scratchUnmeasured = true; }
|
|
346
|
+
entries.sort((a, b) => a.relative < b.relative ? -1 : a.relative > b.relative ? 1 : 0);
|
|
347
|
+
return { manifest: { v: 1, entries, excluded, totalBytes: total }, contents, scratchBytes: scratch, scratchUnmeasured };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** A retained output directory the host itself created, with the identity it recorded at creation. Prune acts on nothing else. */
|
|
351
|
+
export type ProbeRetained = ProbeRetainedRecord;
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Copy the collected output into a fresh host-owned retention directory (mode 0700, O_EXCL files, link count 1) and return what was created. The retention
|
|
355
|
+
* directory is outside the workspace so the workspace can be released at once; what is retained is exactly the manifest's entries, nothing else.
|
|
356
|
+
*/
|
|
357
|
+
export function retainProbeOutput(workspace: ProbeWorkspace, collected: Pick<ProbeCollected, "manifest" | "contents">, root: string): ProbeRetained {
|
|
358
|
+
probeWorkspacePhysical(workspace);
|
|
359
|
+
const { manifest, contents } = collected;
|
|
360
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
361
|
+
const directory = realPath(mkdtempSync(join(root, "retained-")));
|
|
362
|
+
const identity = directoryIdentity(directory);
|
|
363
|
+
chmodSync(directory, 0o700);
|
|
364
|
+
const files: { relative: string; dev: number; ino: number; bytes: number; ctimeNs: string }[] = [];
|
|
365
|
+
try {
|
|
366
|
+
for (const entry of manifest.entries) {
|
|
367
|
+
// The bytes already read and hashed through the opened descriptor. The workspace path is never read again: a swap to a symlink, a FIFO or /dev/zero
|
|
368
|
+
// after collection can neither hang this call nor change what is retained.
|
|
369
|
+
const bytes = contents.get(entry.relative);
|
|
370
|
+
if (!bytes || bytes.length !== entry.bytes || digest(bytes) !== entry.sha256) refused();
|
|
371
|
+
// The manifest already holds only workspace-relative names; refuse anything that could leave the retention directory before joining.
|
|
372
|
+
if (!probeRelativePath(entry.relative)) refused();
|
|
373
|
+
const dest = join(directory, entry.relative);
|
|
374
|
+
mkdirSync(dirname(dest), { recursive: true, mode: 0o700 });
|
|
375
|
+
const fd = openSync(dest, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o400);
|
|
376
|
+
try { writeFileSync(fd, bytes); const created = fstatSync(fd, { bigint: true }); files.push({ relative: entry.relative, dev: Number(created.dev), ino: Number(created.ino), bytes: bytes.length, ctimeNs: created.ctimeNs.toString() }); }
|
|
377
|
+
finally { closeSync(fd); }
|
|
378
|
+
}
|
|
379
|
+
} catch (error) {
|
|
380
|
+
// Remove only what this call created, by identity, never a replaced name.
|
|
381
|
+
removeRetained({ directory, dev: identity.dev, ino: identity.ino, files }, true);
|
|
382
|
+
throw error;
|
|
383
|
+
}
|
|
384
|
+
return Object.freeze({ directory, dev: identity.dev, ino: identity.ino, files: Object.freeze(files.map(item => Object.freeze(item))) });
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** What a prune would remove from one retained directory, and why anything is kept. Read-only. */
|
|
388
|
+
export function previewRetained(retained: ProbeRetained): { remove: { relative: string; bytes: number }[]; keep: { relative: string; reason: string }[] } {
|
|
389
|
+
const remove: { relative: string; bytes: number }[] = [], keep: { relative: string; reason: string }[] = [];
|
|
390
|
+
const root = lstatSync(retained.directory, { throwIfNoEntry: false });
|
|
391
|
+
if (!root || !root.isDirectory() || root.isSymbolicLink() || root.dev !== retained.dev || root.ino !== retained.ino) {
|
|
392
|
+
return { remove, keep: [{ relative: ".", reason: "directory_replaced_or_missing" }] };
|
|
393
|
+
}
|
|
394
|
+
for (const file of retained.files) {
|
|
395
|
+
const stat = lstatSync(join(retained.directory, file.relative), { throwIfNoEntry: false, bigint: true });
|
|
396
|
+
if (!stat) continue;
|
|
397
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || Number(stat.dev) !== file.dev || Number(stat.ino) !== file.ino || stat.ctimeNs.toString() !== file.ctimeNs) keep.push({ relative: file.relative, reason: "identity_changed" });
|
|
398
|
+
else remove.push({ relative: file.relative, bytes: Number(stat.size) });
|
|
399
|
+
}
|
|
400
|
+
return { remove, keep };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Remove only the files and directories this host created, each verified by captured device and inode at the moment of removal. A name that is a
|
|
405
|
+
* replacement, a symlink, a hardlink or a bystander is left exactly where it is. Never recurses through a name it did not create and never follows a link.
|
|
406
|
+
* Returns what it removed and what it kept; a retained name makes the directory itself stay.
|
|
407
|
+
*/
|
|
408
|
+
export function removeRetained(retained: ProbeRetained, partial = false): { removed: string[]; kept: { relative: string; reason: string }[] } {
|
|
409
|
+
const removed: string[] = [], kept: { relative: string; reason: string }[] = [];
|
|
410
|
+
const root = lstatSync(retained.directory, { throwIfNoEntry: false });
|
|
411
|
+
if (!root || !root.isDirectory() || root.isSymbolicLink() || root.dev !== retained.dev || root.ino !== retained.ino) {
|
|
412
|
+
return { removed, kept: [{ relative: ".", reason: "directory_replaced_or_missing" }] };
|
|
413
|
+
}
|
|
414
|
+
const parents = new Set<string>();
|
|
415
|
+
for (const file of retained.files) {
|
|
416
|
+
const path = join(retained.directory, file.relative), stat = lstatSync(path, { throwIfNoEntry: false, bigint: true });
|
|
417
|
+
if (!stat) continue;
|
|
418
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || Number(stat.dev) !== file.dev || Number(stat.ino) !== file.ino || stat.ctimeNs.toString() !== file.ctimeNs) { kept.push({ relative: file.relative, reason: "identity_changed" }); continue; }
|
|
419
|
+
unlinkSync(path); removed.push(file.relative);
|
|
420
|
+
for (let parent = dirname(path); parent !== retained.directory && parent.startsWith(retained.directory + "/"); parent = dirname(parent)) parents.add(parent);
|
|
421
|
+
}
|
|
422
|
+
// Directories this call may have created: removed only if now empty, deepest first; a non-empty one holds a bystander and stays.
|
|
423
|
+
for (const parent of [...parents].sort((a, b) => b.length - a.length)) { try { rmdirSync(parent); } catch { kept.push({ relative: parent.slice(retained.directory.length + 1), reason: "not_empty" }); } }
|
|
424
|
+
if (kept.length === 0 || partial) { try { rmdirSync(retained.directory); } catch { kept.push({ relative: ".", reason: "not_empty" }); } }
|
|
425
|
+
return { removed, kept };
|
|
426
|
+
}
|
package/src/local/sandbox.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { existsSync, mkdtempSync, readdirSync, rmSync, type Dirent } from "node:fs";
|
|
2
|
+
import { existsSync, lstatSync, mkdtempSync, readdirSync, rmdirSync, rmSync, type Dirent } from "node:fs";
|
|
3
3
|
import { homedir, tmpdir } from "node:os";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
5
|
import { realPath } from "../hub/project.ts";
|
|
6
6
|
import { hubGitSync } from "../hub/git.ts";
|
|
7
7
|
import { denyRegexes, hubWriteRegexes, objectStoreRules, sbplString } from "./deny.ts";
|
|
8
|
+
import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
|
|
8
9
|
|
|
9
10
|
const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
|
|
10
11
|
export const OUTPUT_CAP = 20_000;
|
|
@@ -197,10 +198,15 @@ export function profile(cwd: string, network: SandboxNetwork, readAllow: string[
|
|
|
197
198
|
export interface ExecResult {
|
|
198
199
|
code: number | null;
|
|
199
200
|
output: string;
|
|
201
|
+
/** Probe-only owned-process proof; ordinary command results retain their existing shape. */
|
|
202
|
+
quiescent?: boolean;
|
|
203
|
+
stop?: () => Promise<void>;
|
|
200
204
|
}
|
|
205
|
+
export interface ProbeCommandOptions { workspaceRoot: string; temporaryRoot: string; home: string; current(): void; physical(): void }
|
|
201
206
|
|
|
202
207
|
/** Run argv under seatbelt with a scrubbed environment. Never runs unsandboxed: no sandbox, no exec. */
|
|
203
|
-
export function sandboxedExec(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record<string, string>; signal?: AbortSignal; readOnlyData?: boolean }): Promise<ExecResult> {
|
|
208
|
+
export function sandboxedExec(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record<string, string>; signal?: AbortSignal; readOnlyData?: boolean; probe?: ProbeCommandOptions }): Promise<ExecResult> {
|
|
209
|
+
if (opts.probe) return probeCommand(argv, opts as Parameters<typeof probeCommand>[1]);
|
|
204
210
|
if (opts.readOnlyData && /\(allow file-write\* \(subpath /.test(opts.profile)) return Promise.resolve({ code: null, output: "error: data.readonly command profile contains a broad write grant" });
|
|
205
211
|
if (!sandboxAvailable()) return Promise.resolve({ code: null, output: "error: command execution needs macOS sandbox-exec and is disabled on this host" });
|
|
206
212
|
if (opts.signal?.aborted) return Promise.resolve({ code: null, output: "error: command cancelled before execution" });
|
|
@@ -255,6 +261,69 @@ export function sandboxedExec(argv: string[], opts: { cwd: string; profile: stri
|
|
|
255
261
|
});
|
|
256
262
|
}
|
|
257
263
|
|
|
264
|
+
/** Same sandbox entry point, with a readonly owned temp and verified cleanup for fixed host proof commands. */
|
|
265
|
+
async function probeCommand(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record<string, string>; signal?: AbortSignal; probe: ProbeCommandOptions }): Promise<ExecResult> {
|
|
266
|
+
const proof = opts.probe;
|
|
267
|
+
if (!sandboxAvailable()) return { code: null, output: "error: probe confinement needs macOS sandbox-exec", quiescent: true };
|
|
268
|
+
try {
|
|
269
|
+
proof.physical(); proof.current();
|
|
270
|
+
const root = realPath(proof.workspaceRoot), temporary = realPath(proof.temporaryRoot), home = realPath(proof.home);
|
|
271
|
+
if (realPath(opts.cwd) !== root || !temporary.startsWith(root + "/") || !opts.env || opts.env.HOME !== home
|
|
272
|
+
|| opts.env.PATH !== "/usr/bin:/bin:/usr/sbin:/sbin" || opts.env.LANG !== "C" || opts.env.TERM !== "dumb"
|
|
273
|
+
|| Object.keys(opts.env).some(key => !["PATH", "HOME", "LANG", "TERM"].includes(key))) throw new Error("probe command binding unavailable");
|
|
274
|
+
if (opts.signal?.aborted) throw new Error("probe command cancelled");
|
|
275
|
+
} catch { return { code: null, output: "error: probe command authority or environment unavailable", quiescent: true }; }
|
|
276
|
+
const own = realPath(mkdtempSync(join(proof.temporaryRoot, "command-")));
|
|
277
|
+
const created = lstatSync(own);
|
|
278
|
+
let removed = false;
|
|
279
|
+
const dropOwn = () => {
|
|
280
|
+
if (removed) return;
|
|
281
|
+
proof.physical();
|
|
282
|
+
const current = lstatSync(own);
|
|
283
|
+
if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== created.dev || current.ino !== created.ino || realPath(own) !== own) throw new Error("probe command temp ownership changed");
|
|
284
|
+
// The lane grants no temp writes. Unexpected contents are retained rather than recursively removed.
|
|
285
|
+
rmdirSync(own); removed = true;
|
|
286
|
+
};
|
|
287
|
+
// Never append the ordinary broad temp read/write/exec suffix: the verified profile already bounds this directory.
|
|
288
|
+
const env = { ...opts.env, TMPDIR: `${own}/` };
|
|
289
|
+
return new Promise<ExecResult>(resolve => {
|
|
290
|
+
let child: ReturnType<typeof spawn>;
|
|
291
|
+
try { proof.current(); child = spawn(SANDBOX_EXEC, ["-p", opts.profile, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true }); }
|
|
292
|
+
catch {
|
|
293
|
+
try { dropOwn(); resolve({ code: null, output: "error: probe command did not launch", quiescent: true }); }
|
|
294
|
+
catch { resolve({ code: null, output: "error: probe command setup cleanup is unconfirmed", quiescent: false, stop: async () => dropOwn() }); }
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
trackGroup(child);
|
|
298
|
+
let output = "", settled = false, cancelled = false;
|
|
299
|
+
let pipeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
300
|
+
const take = (data: Buffer) => { if (output.length < OUTPUT_CAP) output += data.toString(); };
|
|
301
|
+
child.stdout?.on("data", take); child.stderr?.on("data", take);
|
|
302
|
+
const stop = async () => { await stopOwnedProcess(child, { group: true }); dropOwn(); };
|
|
303
|
+
const finish = async (code: number | null) => {
|
|
304
|
+
if (settled) return; settled = true;
|
|
305
|
+
clearTimeout(timer); if (pipeTimer) clearTimeout(pipeTimer); opts.signal?.removeEventListener("abort", abort);
|
|
306
|
+
let quiescent = false;
|
|
307
|
+
try { await stop(); quiescent = true; } catch { /* keep the child and directory in the returned owned stop handle */ }
|
|
308
|
+
const clipped = output.length >= OUTPUT_CAP ? `${output.slice(0, OUTPUT_CAP)}\n(output truncated)` : output;
|
|
309
|
+
const observed = child.signalCode ? `${clipped}\n(probe command signal: ${child.signalCode}; owned pid: ${child.pid})` : clipped;
|
|
310
|
+
resolve({ code, output: cancelled ? `${observed}\n(probe command cancelled)` : observed, quiescent, ...(quiescent ? {} : { stop }) });
|
|
311
|
+
};
|
|
312
|
+
const abort = () => { cancelled = true; void finish(null); };
|
|
313
|
+
const timer = setTimeout(abort, opts.timeoutMs ?? 5000);
|
|
314
|
+
opts.signal?.addEventListener("abort", abort, { once: true });
|
|
315
|
+
child.once("error", error => {
|
|
316
|
+
output = `error: probe command spawn failed (${(error as NodeJS.ErrnoException).code ?? "unknown"})`;
|
|
317
|
+
void finish(null);
|
|
318
|
+
});
|
|
319
|
+
child.once("close", code => { void finish(code); });
|
|
320
|
+
// A leader exit is not proof that descendants released pipes. The owned stop proves or retains uncertainty.
|
|
321
|
+
child.once("exit", code => { pipeTimer = setTimeout(() => { void finish(code); }, 500); });
|
|
322
|
+
if (child.exitCode !== null || child.signalCode !== null) pipeTimer = setTimeout(() => { void finish(child.exitCode); }, 500);
|
|
323
|
+
if (opts.signal?.aborted) abort();
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
258
327
|
/** The environment that sends a command's HTTPS through the egress proxy (#65); empty without one. */
|
|
259
328
|
export function proxyEnv(network: SandboxNetwork): Record<string, string> {
|
|
260
329
|
if (typeof network !== "object") return {};
|