@staix/agent-hub 0.35.0 → 0.37.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 +43 -0
- package/README.md +25 -4
- package/THIRD_PARTY_NOTICES.md +0 -18
- package/docs/agent-notes/README.md +71 -1
- package/docs/agent-notes/adapters.md +5 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +7 -6
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/models.md +5 -3
- package/docs/agent-notes/tasks.md +9 -2
- package/docs/agent-notes/tests.md +1 -1
- package/docs/contracts/companion-cli-v1.json +70 -0
- package/docs/design/adapters.md +115 -2
- package/docs/design/agent-hub-architecture.md +10 -2
- package/docs/design/bus.md +8 -0
- package/docs/design/execution-reference.md +171 -11
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/guidance-probes.md +802 -0
- package/docs/design/model-routes.md +1053 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +111 -0
- package/docs/dogfood.md +24 -15
- package/docs/events.md +20 -1
- package/docs/memory.md +3 -3
- package/docs/operations.md +366 -133
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +114 -3
- package/docs/research.md +5 -3
- package/docs/sdlc.md +113 -7
- package/docs/security.md +88 -6
- package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
- package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/2026-11-11-0.37.0.md +40 -0
- package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
- package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
- package/docs/verification/claude-shell-wrapper-native.py +1 -1
- package/docs/verified.json +27 -27
- package/package.json +3 -4
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +3570 -1800
- package/plugins/agent-hub/server.js +4112 -1913
- package/src/adapters/channel-peer.ts +7 -1
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/compat.ts +10 -10
- package/src/adapters/local-probe.ts +174 -0
- package/src/adapters/local-worker.ts +233 -22
- package/src/adapters/qwen-dual.ts +324 -44
- 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/guidance.ts +67 -0
- package/src/cli/help.ts +12 -4
- package/src/cli/identity.ts +10 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/install-paths.ts +7 -2
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +171 -14
- package/src/cli/runtime-version-warning.ts +2 -2
- package/src/cli/sdlc-output.ts +9 -5
- package/src/cli/setup-research.ts +10 -0
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +12 -0
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/config-apply.ts +6 -3
- package/src/hub/config-trust.ts +7 -1
- package/src/hub/control-client.ts +5 -2
- package/src/hub/daemon.ts +508 -26
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +8 -4
- package/src/hub/events.ts +3 -2
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +52 -8
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/guidance-probe-store.ts +713 -0
- package/src/hub/guidance-probes.ts +358 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +43 -2
- package/src/hub/inference.ts +18 -5
- package/src/hub/manager.ts +44 -2
- package/src/hub/memory-policy.ts +2 -2
- package/src/hub/operational-authority.ts +13 -1
- package/src/hub/peers.ts +6 -1
- package/src/hub/planning.ts +1 -1
- package/src/hub/ports.ts +1 -1
- package/src/hub/progress.ts +47 -23
- package/src/hub/report.ts +2 -0
- package/src/hub/research.ts +1 -0
- package/src/hub/restart.ts +20 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release-authorization.ts +139 -17
- package/src/hub/sdlc-release-policy.ts +100 -0
- package/src/hub/sdlc-release.ts +60 -8
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +2 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +917 -53
- package/src/local/probe-errors.ts +28 -0
- package/src/local/probe-sandbox.ts +224 -0
- package/src/local/probe-types.ts +108 -0
- package/src/local/probe-workspace.ts +237 -0
- package/src/local/sandbox.ts +71 -2
- package/src/local/tools.ts +135 -9
- package/src/memory/capture.ts +2 -2
- package/src/models/relay.ts +9 -2
- package/src/models/route/advisor-trigger.ts +88 -0
- package/src/models/route/config.ts +39 -8
- package/src/models/route/conversation-view.ts +179 -0
- package/src/models/route/decision-evidence.ts +1 -1
- package/src/models/route/decision.ts +193 -26
- 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 +10 -9
- package/src/models/route/runtime.ts +129 -60
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/models/route/turn-state.ts +77 -0
- package/src/omniroute/client.ts +3 -0
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +141 -27
- package/src/version.ts +4 -0
- 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/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,28 @@
|
|
|
1
|
+
/** Closed probe-only causes. They carry no physical path, model text, actor id or native diagnostic. */
|
|
2
|
+
export type ProbeToolRefusalCode = "outside_workspace" | "invalid_path" | "unadmitted_write" | "file_ceiling"
|
|
3
|
+
| "hardlinked_target" | "nonregular_target" | "authority_stopped" | "target_changed" | "tool_unavailable"
|
|
4
|
+
| "workspace_ceiling" | "confinement_unavailable" | "token_bound_unavailable" | "token_ceiling";
|
|
5
|
+
const reasons: Record<ProbeToolRefusalCode, string> = {
|
|
6
|
+
outside_workspace: "path is outside the admitted logical workspace; use a declared /workspace path",
|
|
7
|
+
invalid_path: "path is not an admitted relative name; use a declared /workspace file without traversal, dependency or internal-temp components",
|
|
8
|
+
unadmitted_write: "write target is not admitted; choose a target from the supplied logical /workspace/scratch or /workspace/output list",
|
|
9
|
+
file_ceiling: "file exceeds the 1 MiB file ceiling; reduce the file before requesting another admitted operation",
|
|
10
|
+
hardlinked_target: "hardlinked target is not a private probe file; ask the host for a fresh regular file",
|
|
11
|
+
nonregular_target: "target is not a regular probe file; choose a declared regular file",
|
|
12
|
+
authority_stopped: "probe authority is stopped or unavailable; stop this session and ask the host for a newly admitted session",
|
|
13
|
+
target_changed: "probe target or reservation changed; stop this operation and ask the host to inspect the admitted state",
|
|
14
|
+
tool_unavailable: "tool is unavailable in the confined probe; use only the admitted read, write and edit tools",
|
|
15
|
+
workspace_ceiling: "workspace reservation exceeds its admitted workspace ceiling (at most 64 MiB); reduce the declared data or ask the host for a new bounded session",
|
|
16
|
+
confinement_unavailable: "OS confinement or owned cleanup is unverified; stop this session and ask the host to inspect confinement and retained resources",
|
|
17
|
+
token_bound_unavailable: "trusted token upper-bound proof is unavailable; ask the host to prepare a frozen configuration before another model call",
|
|
18
|
+
token_ceiling: "model call exceeds the admitted token ceiling; reduce its declared input or ask the host for a new bounded session",
|
|
19
|
+
};
|
|
20
|
+
const unknownReason = "confined probe operation refused; stop this operation and ask the host to inspect the admitted state";
|
|
21
|
+
export class ProbeToolRefusal extends Error {
|
|
22
|
+
constructor(readonly code: ProbeToolRefusalCode) { super(Object.hasOwn(reasons, code) ? reasons[code] : unknownReason); }
|
|
23
|
+
}
|
|
24
|
+
/** Never classify from native/error prose or reuse an arbitrary Error.message. */
|
|
25
|
+
export function formatProbeToolRefusal(error: unknown): string {
|
|
26
|
+
const reason = error instanceof ProbeToolRefusal && Object.hasOwn(reasons, error.code) ? reasons[error.code] : unknownReason;
|
|
27
|
+
return `error: ${reason}`;
|
|
28
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { realPath } from "../hub/project.ts";
|
|
5
|
+
import { sbplString } from "./deny.ts";
|
|
6
|
+
import { profile, sandboxAvailable, sandboxedExec } from "./sandbox.ts";
|
|
7
|
+
import { ProbeToolRefusal } from "./probe-errors.ts";
|
|
8
|
+
import { probeWorkspaceCurrent, probeWorkspacePhysical, probeWorkspacePrivateRoot, probeWorkspaceTemporaryRoot, reserveProbeWorkspaceStorage, type ProbeWorkspace } from "./probe-workspace.ts";
|
|
9
|
+
|
|
10
|
+
export interface ProbeConfinement {
|
|
11
|
+
readonly workspace: ProbeWorkspace;
|
|
12
|
+
readonly profile: string;
|
|
13
|
+
readonly env: Readonly<Record<string, string>>;
|
|
14
|
+
stop(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
/** An uncertain command retains this owned stop handle; callers must join it before workspace cleanup. */
|
|
17
|
+
export class ProbeConfinementError extends ProbeToolRefusal {
|
|
18
|
+
constructor(readonly stop: () => Promise<void> = async () => {},
|
|
19
|
+
/** Private proof-only diagnostic, never copied into a public probe receipt or ordinary observer. */
|
|
20
|
+
readonly diagnostic?: { stage: "control" | "lane" | "cleanup"; code: number | null; output: string }) {
|
|
21
|
+
super("confinement_unavailable");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
interface ProofState { workspace: ProbeWorkspace; profile: string; digest: string; current(): void; stop(): Promise<void> }
|
|
25
|
+
interface OwnedProofPath { file: string; dev: number; ino: number; directory: boolean; optional?: boolean; removed?: boolean }
|
|
26
|
+
const proofs = new WeakMap<ProbeConfinement, ProofState>();
|
|
27
|
+
let proofOwner: { workspace: ProbeWorkspace; stop(): Promise<void> } | undefined;
|
|
28
|
+
const digest = (value: string): string => createHash("sha256").update(value).digest("hex");
|
|
29
|
+
const q = sbplString;
|
|
30
|
+
const literal = (value: string) => `(literal ${q(value)})`;
|
|
31
|
+
const subpath = (value: string) => `(subpath ${q(value)})`;
|
|
32
|
+
const outside = (filters: readonly string[]): string => `(require-all ${filters.map(filter => `(require-not ${filter})`).join(" ")})`;
|
|
33
|
+
const PROOF_TIMEOUT_MS = 5000;
|
|
34
|
+
const PROOF_TOKEN = "probe-boundary-canary";
|
|
35
|
+
// /bin/bash: on macOS /bin/sh is a stub that re-execs /bin/bash as its variant (/private/var/select/sh), so the proof's own `sh -c` cannot start without it.
|
|
36
|
+
// Only this model-free proof runs these programs: probe dispatch refuses bash and git before any command (test "probe dispatch refuses all invented non-file calls"),
|
|
37
|
+
// so the grant widens the profile, not what a probe tool can do.
|
|
38
|
+
const COMMANDS = ["/bin/sh", "/bin/cat", "/bin/ln", "/bin/mv", "/usr/bin/nc", "/bin/bash"] as const;
|
|
39
|
+
const SH_VARIANT_SELECTOR = "/private/var/select/sh";
|
|
40
|
+
|
|
41
|
+
function restrictedProfile(workspace: ProbeWorkspace, controlPort?: number): string {
|
|
42
|
+
probeWorkspaceCurrent(workspace);
|
|
43
|
+
const programs = [...new Set(COMMANDS.flatMap(file => [file, realPath(file)]))];
|
|
44
|
+
// Never grant all of /System: its Volumes/Data aliases can lead back to operator files.
|
|
45
|
+
const systemData = ["/System/Library", "/usr/lib", "/private/var/db/dyld",
|
|
46
|
+
"/System/Volumes/Preboot/Cryptexes/OS/System/Library", "/System/Volumes/Preboot/Cryptexes/OS/usr/lib"];
|
|
47
|
+
// literal("/") is the root directory node only, not its children: dyld reads that node's data at every process start, and without it every program
|
|
48
|
+
// (nc, sh, cat) aborts with SIGABRT before it runs (bisected with plain sandbox-exec on macOS 27.0.1). No other grant rides on it.
|
|
49
|
+
const data = [literal("/"), subpath(workspace.root), ...systemData.map(subpath),
|
|
50
|
+
...programs.map(literal), literal(SH_VARIANT_SELECTOR), literal("/dev/null"), literal("/dev/random"), literal("/dev/urandom")];
|
|
51
|
+
// Traversal metadata is permitted only for ancestors of an actual runtime or owned role root.
|
|
52
|
+
const ancestors = new Set<string>(["/"]);
|
|
53
|
+
for (const root of [workspace.root, ...programs, SH_VARIANT_SELECTOR, ...systemData]) {
|
|
54
|
+
for (let parent = dirname(root); ; parent = dirname(parent)) { ancestors.add(parent); if (parent === "/") break; }
|
|
55
|
+
}
|
|
56
|
+
return [profile(workspace.root, controlPort === undefined ? false : { proxyPort: controlPort }),
|
|
57
|
+
`(deny file-read-data ${outside(data)})`,
|
|
58
|
+
`(deny file-read-metadata ${outside([...data, ...[...ancestors].map(literal)])})`,
|
|
59
|
+
`(deny file-write* ${outside([literal("/dev/null"), ...workspace.allowedWrites.map(subpath)])})`,
|
|
60
|
+
`(deny process-exec ${outside(programs.map(literal))})`,
|
|
61
|
+
...(controlPort === undefined ? ["(deny network*)"] : []),
|
|
62
|
+
].join("\n");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Consume only an in-memory proof minted for these exact owned paths and this current role. */
|
|
66
|
+
export function requireProbeConfinement(proof: ProbeConfinement, workspace: ProbeWorkspace): void {
|
|
67
|
+
const state = proofs.get(proof);
|
|
68
|
+
if (!state || state.workspace !== workspace || proof.workspace !== workspace || proof.profile !== state.profile
|
|
69
|
+
|| digest(JSON.stringify(proof.env)) !== state.digest) throw new ProbeConfinementError();
|
|
70
|
+
state.current();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Model-free proof under the same lane profile. Unsupported or failed native proof is never a fixture pass. */
|
|
74
|
+
export async function verifyProbeConfinement(workspace: ProbeWorkspace, signal?: AbortSignal): Promise<ProbeConfinement> {
|
|
75
|
+
if (!sandboxAvailable() || proofOwner || signal?.aborted) throw new ProbeConfinementError();
|
|
76
|
+
probeWorkspaceCurrent(workspace);
|
|
77
|
+
const pending = new Set<() => Promise<void>>();
|
|
78
|
+
let active: Promise<unknown> | undefined;
|
|
79
|
+
let closed = false;
|
|
80
|
+
let cleaned = false;
|
|
81
|
+
const owned = new Map<string, OwnedProofPath>();
|
|
82
|
+
const remember = (file: string, directory: boolean): OwnedProofPath => {
|
|
83
|
+
const stat = lstatSync(file);
|
|
84
|
+
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile())) throw new Error("probe setup resource ownership unavailable");
|
|
85
|
+
const identity = { file, dev: stat.dev, ino: stat.ino, directory }; owned.set(file, identity); return identity;
|
|
86
|
+
};
|
|
87
|
+
const requireOwned = (identity: OwnedProofPath): boolean => {
|
|
88
|
+
const stat = lstatSync(identity.file, { throwIfNoEntry: false });
|
|
89
|
+
if (!stat && identity.optional) return false;
|
|
90
|
+
if (!stat || stat.isSymbolicLink() || (identity.directory ? !stat.isDirectory() : !stat.isFile()) || stat.dev !== identity.dev || stat.ino !== identity.ino) {
|
|
91
|
+
throw new Error("probe setup resource ownership changed; retained for inspection");
|
|
92
|
+
}
|
|
93
|
+
return true;
|
|
94
|
+
};
|
|
95
|
+
const cleanup = () => {
|
|
96
|
+
// Cleanup needs physical ownership, never the withdrawn actor/privacy execution authority.
|
|
97
|
+
probeWorkspacePhysical(workspace);
|
|
98
|
+
if (cleaned) return;
|
|
99
|
+
for (const identity of owned.values()) if (!identity.removed) requireOwned(identity);
|
|
100
|
+
for (const identity of owned.values()) if (!identity.directory && !identity.removed) {
|
|
101
|
+
probeWorkspacePhysical(workspace); if (requireOwned(identity)) rmSync(identity.file); identity.removed = true;
|
|
102
|
+
}
|
|
103
|
+
for (const identity of [...owned.values()].filter(entry => entry.directory).sort((a, b) => b.file.length - a.file.length)) if (!identity.removed) {
|
|
104
|
+
probeWorkspacePhysical(workspace); requireOwned(identity); rmdirSync(identity.file); identity.removed = true;
|
|
105
|
+
}
|
|
106
|
+
cleaned = true;
|
|
107
|
+
};
|
|
108
|
+
const stop = async () => {
|
|
109
|
+
closed = true;
|
|
110
|
+
if (active) await active;
|
|
111
|
+
for (const close of [...pending]) { await close(); pending.delete(close); }
|
|
112
|
+
cleanup();
|
|
113
|
+
if (proofOwner?.workspace === workspace) proofOwner = undefined;
|
|
114
|
+
};
|
|
115
|
+
proofOwner = { workspace, stop };
|
|
116
|
+
let server: ReturnType<typeof Bun.serve> | undefined;
|
|
117
|
+
let retained = false;
|
|
118
|
+
try {
|
|
119
|
+
const laneProfile = restrictedProfile(workspace);
|
|
120
|
+
const env = Object.freeze({ PATH: "/usr/bin:/bin:/usr/sbin:/sbin", HOME: workspace.home, LANG: "C", TERM: "dumb" });
|
|
121
|
+
const privateRoot = probeWorkspacePrivateRoot(workspace), temporaryRoot = probeWorkspaceTemporaryRoot(workspace);
|
|
122
|
+
const roots = new Set([privateRoot, workspace.root, workspace.home, workspace.scratch, workspace.output]);
|
|
123
|
+
const directory = (file: string): void => {
|
|
124
|
+
probeWorkspacePhysical(workspace);
|
|
125
|
+
const identity = owned.get(file);
|
|
126
|
+
if (identity) { requireOwned(identity); return; }
|
|
127
|
+
if (roots.has(file)) return;
|
|
128
|
+
if (lstatSync(file, { throwIfNoEntry: false })) throw new ProbeConfinementError(stop);
|
|
129
|
+
directory(dirname(file)); mkdirSync(file, { mode: 0o700 }); remember(file, true);
|
|
130
|
+
};
|
|
131
|
+
const write = (file: string) => {
|
|
132
|
+
directory(dirname(file));
|
|
133
|
+
const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
|
|
134
|
+
try {
|
|
135
|
+
const stat = fstatSync(fd); owned.set(file, { file, dev: stat.dev, ino: stat.ino, directory: false });
|
|
136
|
+
writeFileSync(fd, PROOF_TOKEN);
|
|
137
|
+
} finally { closeSync(fd); }
|
|
138
|
+
};
|
|
139
|
+
const labels = ["evaluator", "future-task", "other-arm", "control-receipt", ".git/objects/canary", "operator-file", "parent", "sibling"];
|
|
140
|
+
const retainedBytes = Buffer.byteLength(PROOF_TOKEN) * (labels.length + 4);
|
|
141
|
+
await reserveProbeWorkspaceStorage(workspace, retainedBytes);
|
|
142
|
+
probeWorkspaceCurrent(workspace);
|
|
143
|
+
if (signal?.aborted) throw new ProbeConfinementError(stop);
|
|
144
|
+
const privateProof = realPath(mkdtempSync(join(privateRoot, "boundary-"))), positiveRoot = realPath(mkdtempSync(join(workspace.root, ".boundary-")));
|
|
145
|
+
remember(privateProof, true); remember(positiveRoot, true);
|
|
146
|
+
const readable = join(positiveRoot, "readable"), homeCanary = join(workspace.home, "credential-canary");
|
|
147
|
+
write(readable); write(homeCanary);
|
|
148
|
+
const readableIdentity = owned.get(readable)!;
|
|
149
|
+
const hostLink = join(privateProof, "host-link-control"); linkSync(readable, hostLink);
|
|
150
|
+
const hostIdentity = remember(hostLink, false); requireOwned(hostIdentity); rmSync(hostLink); hostIdentity.removed = true;
|
|
151
|
+
const negatives = labels.map(label => join(privateProof!, label));
|
|
152
|
+
for (const file of negatives) write(file);
|
|
153
|
+
negatives.push(homeCanary);
|
|
154
|
+
const writableRoot = workspace.allowedWrites[0];
|
|
155
|
+
let writeControl: string | undefined, aliasControl: string | undefined;
|
|
156
|
+
if (writableRoot) {
|
|
157
|
+
directory(writableRoot);
|
|
158
|
+
writeControl = join(writableRoot, ".probe-write-control"); write(writeControl);
|
|
159
|
+
aliasControl = join(writableRoot, ".probe-alias-control");
|
|
160
|
+
owned.set(aliasControl, { ...readableIdentity, file: aliasControl, optional: true });
|
|
161
|
+
}
|
|
162
|
+
let networkRequests = 0;
|
|
163
|
+
server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: request => {
|
|
164
|
+
if (request.headers.has("origin")) return new Response("Origin refused", { status: 403 });
|
|
165
|
+
networkRequests++; return new Response(PROOF_TOKEN);
|
|
166
|
+
} });
|
|
167
|
+
const positive = await fetch(`http://127.0.0.1:${server.port}/`, { signal: AbortSignal.timeout(PROOF_TIMEOUT_MS) });
|
|
168
|
+
if (await positive.text() !== PROOF_TOKEN || networkRequests !== 1) throw new ProbeConfinementError(stop);
|
|
169
|
+
if (signal?.aborted) throw new ProbeConfinementError(stop);
|
|
170
|
+
networkRequests = 0;
|
|
171
|
+
const run = async (argv: string[], commandProfile: string) => {
|
|
172
|
+
probeWorkspaceCurrent(workspace);
|
|
173
|
+
const command = sandboxedExec(argv, {
|
|
174
|
+
cwd: workspace.root, profile: commandProfile, env: { ...env }, timeoutMs: PROOF_TIMEOUT_MS, ...(signal ? { signal } : {}),
|
|
175
|
+
probe: { workspaceRoot: workspace.root, temporaryRoot, home: workspace.home, current: () => probeWorkspaceCurrent(workspace), physical: () => probeWorkspacePhysical(workspace) },
|
|
176
|
+
});
|
|
177
|
+
active = command;
|
|
178
|
+
const result = await command; active = undefined;
|
|
179
|
+
if (!result.quiescent) { if (result.stop) pending.add(result.stop); retained = true;
|
|
180
|
+
throw new ProbeConfinementError(stop, { stage: "cleanup", code: result.code, output: result.output.slice(0, 1024) }); }
|
|
181
|
+
probeWorkspaceCurrent(workspace);
|
|
182
|
+
return result;
|
|
183
|
+
};
|
|
184
|
+
// Same utility and runtime constraints, with a single owned-loopback grant only for this positive control.
|
|
185
|
+
const control = await run(["/usr/bin/nc", "-n", "-z", "-G", "1", "-w", "1", "127.0.0.1", String(server.port)], restrictedProfile(workspace, server.port));
|
|
186
|
+
if (control.code !== 0 || signal?.aborted) throw new ProbeConfinementError(stop, { stage: "control", code: control.code, output: control.output.slice(0, 1024) });
|
|
187
|
+
const script = [
|
|
188
|
+
'set -eu',
|
|
189
|
+
'[ "$(/bin/cat "$1")" = "probe-boundary-canary" ] || exit 11',
|
|
190
|
+
'if [ "$2" = /dev/null ]; then printf x > /dev/null; else printf probe-boundary-canary > "$2"; fi',
|
|
191
|
+
'[ -z "${OMNIROUTE_API_KEY-}${AWS_ACCESS_KEY_ID-}${AGENTHUB_CONTROL_TOKEN-}${HTTPS_PROXY-}${CODEX_THREAD_ID-}${AGENTHUB_PEER_ID-}" ] || exit 12',
|
|
192
|
+
'readable="$1"; writable="$2"',
|
|
193
|
+
'printf "PERMITTED\\n"',
|
|
194
|
+
'port="$3"; alias="$4"; shift 4',
|
|
195
|
+
'for file do if /bin/cat "$file" >/dev/null 2>&1; then exit 14; fi; if (printf bad > "$file") 2>/dev/null; then exit 15; fi; done',
|
|
196
|
+
'first="$1"; if /bin/ln "$first" "$first.link" >/dev/null 2>&1; then exit 17; fi',
|
|
197
|
+
'if /bin/ln -s "$first" "$first.alias" >/dev/null 2>&1; then exit 18; fi',
|
|
198
|
+
'if /bin/mv "$first" "$first.moved" >/dev/null 2>&1; then exit 19; fi',
|
|
199
|
+
'if [ "$alias" != /dev/null ]; then if /bin/ln "$readable" "$alias" >/dev/null 2>&1; then if (printf bad > "$alias") 2>/dev/null; then exit 20; fi; fi; fi',
|
|
200
|
+
'if /usr/bin/nc -n -z -G 1 -w 1 127.0.0.1 "$port" >/dev/null 2>&1; then exit 16; fi',
|
|
201
|
+
'printf "DENIED\\n"',
|
|
202
|
+
].join("\n");
|
|
203
|
+
probeWorkspaceCurrent(workspace);
|
|
204
|
+
const result = await run(["/bin/sh", "-c", script, "proof", readable, writeControl ?? "/dev/null", String(server.port), aliasControl ?? "/dev/null", ...negatives], laneProfile);
|
|
205
|
+
probeWorkspaceCurrent(workspace);
|
|
206
|
+
if (result.code !== 0 || result.output.trim() !== "PERMITTED\nDENIED" || networkRequests !== 0 || signal?.aborted)
|
|
207
|
+
throw new ProbeConfinementError(stop, { stage: "lane", code: result.code, output: result.output.slice(0, 1024) });
|
|
208
|
+
if (negatives.some(file => readFileSync(file, "utf8") !== PROOF_TOKEN)) throw new ProbeConfinementError(stop);
|
|
209
|
+
if (readFileSync(readable, "utf8") !== PROOF_TOKEN) throw new ProbeConfinementError(stop);
|
|
210
|
+
if (writeControl && readFileSync(writeControl, "utf8") !== PROOF_TOKEN) throw new ProbeConfinementError(stop);
|
|
211
|
+
const proof: ProbeConfinement = Object.freeze({ workspace, profile: laneProfile, env, stop });
|
|
212
|
+
proofs.set(proof, { workspace, profile: laneProfile, digest: digest(JSON.stringify(env)), current: () => { if (closed) throw new ProbeConfinementError(stop); probeWorkspaceCurrent(workspace); }, stop });
|
|
213
|
+
return proof;
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (error instanceof ProbeConfinementError) throw error;
|
|
216
|
+
throw new ProbeConfinementError(stop);
|
|
217
|
+
} finally {
|
|
218
|
+
if (server) await server.stop(true);
|
|
219
|
+
if (!retained) {
|
|
220
|
+
try { cleanup(); if (proofOwner?.workspace === workspace) proofOwner = undefined; }
|
|
221
|
+
catch { throw new ProbeConfinementError(stop); }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { ChatMessage, ChatResult, OmniRoute } from "../omniroute/client.ts";
|
|
2
|
+
import type { ProbeFakeEffects, ProbeResourceCharges, ProbeSlot, ProbeStoredState, ProbeWorkerFramePreparer } from "../hub/guidance-probes.ts";
|
|
3
|
+
import type { ProbeConfinement } from "./probe-sandbox.ts";
|
|
4
|
+
import type { ProbeMaterializedFile, ProbeWorkspace, ProbeWorkspaceInput } from "./probe-workspace.ts";
|
|
5
|
+
import type { ToolContext } from "./tools.ts";
|
|
6
|
+
import { guidanceProbeCanonical, probeHash } from "../hub/guidance-probes.ts";
|
|
7
|
+
|
|
8
|
+
export class ProbeLocalError extends Error {
|
|
9
|
+
constructor(readonly reason: "invalid" | "drift" | "model" | "usage" | "interrupted") {
|
|
10
|
+
super({ invalid: "guidance probe input or capability is invalid; ask the host to rebuild the admitted input before retrying",
|
|
11
|
+
drift: "guidance probe input or runtime changed; retain this session and preregister matching inputs before retrying",
|
|
12
|
+
model: "guidance probe served-model identity is changed or unverified; inspect model provenance and admit a matching session without fallback",
|
|
13
|
+
usage: "guidance probe model usage is missing or unknown; retain unknown cost and inspect provider accounting before retrying",
|
|
14
|
+
interrupted: "guidance probe authority or owned work stopped; join the owned stop and inspect retained state before retrying" }[reason]);
|
|
15
|
+
this.name = "ProbeLocalError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface ProbeLocalModelConfig {
|
|
20
|
+
maxSteps: number;
|
|
21
|
+
maxOutputTokens: number;
|
|
22
|
+
/** Trusted frozen upper bound for the entire call, not an output-token cap. */
|
|
23
|
+
tokenUpperBound?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface ProbeLocalRequest {
|
|
26
|
+
model: string;
|
|
27
|
+
messages: ChatMessage[];
|
|
28
|
+
tools: unknown[];
|
|
29
|
+
max_tokens: number;
|
|
30
|
+
stream: false;
|
|
31
|
+
}
|
|
32
|
+
export interface ProbePreparedLocalInput {
|
|
33
|
+
inputFrame: string;
|
|
34
|
+
inputSha256: string;
|
|
35
|
+
nonGuidanceInputSha256: string;
|
|
36
|
+
request: ProbeLocalRequest;
|
|
37
|
+
role: ProbeSlot["role"];
|
|
38
|
+
files: readonly { dataId: string; relative: string; sha256: string; bytes: number }[];
|
|
39
|
+
}
|
|
40
|
+
export interface ProbeLocalEffectScope {
|
|
41
|
+
effects: ProbeFakeEffects;
|
|
42
|
+
next(): number;
|
|
43
|
+
current(): void;
|
|
44
|
+
}
|
|
45
|
+
export interface ProbeLocalSession {
|
|
46
|
+
purpose: "guidance_probe";
|
|
47
|
+
prepared: ProbePreparedLocalInput;
|
|
48
|
+
workspace: ProbeWorkspace;
|
|
49
|
+
confinement: ProbeConfinement;
|
|
50
|
+
config: Readonly<ProbeLocalModelConfig>;
|
|
51
|
+
accounting: ProbeLocalEffectScope;
|
|
52
|
+
reserve(charges: ProbeResourceCharges, descriptor: string): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
export interface ProbeLocalResult {
|
|
55
|
+
answer: string;
|
|
56
|
+
complete: boolean;
|
|
57
|
+
servedModel: string | null;
|
|
58
|
+
servedModelExact: boolean;
|
|
59
|
+
usageKnown: boolean;
|
|
60
|
+
/** Known pre-effect refusal metadata, not a fabricated model answer or token-usage observation. */
|
|
61
|
+
refusal?: "token_ceiling";
|
|
62
|
+
reason?: string;
|
|
63
|
+
}
|
|
64
|
+
export interface ProbeLocalSource {
|
|
65
|
+
files: readonly ProbeMaterializedFile[];
|
|
66
|
+
sourceTree?: ProbeWorkspaceInput["sourceTree"];
|
|
67
|
+
verifySource: ProbeWorkspaceInput["verifySource"];
|
|
68
|
+
}
|
|
69
|
+
export interface ProbeLocalFixturePorts {
|
|
70
|
+
evidence: "fixture_only";
|
|
71
|
+
materialize(input: ProbeWorkspaceInput): Promise<ProbeWorkspace>;
|
|
72
|
+
confine(workspace: ProbeWorkspace): Promise<ProbeConfinement>;
|
|
73
|
+
}
|
|
74
|
+
export interface ProbeLocalAdapterOptions {
|
|
75
|
+
omni: OmniRoute;
|
|
76
|
+
config: Readonly<ProbeLocalModelConfig>;
|
|
77
|
+
permit: ToolContext["permit"];
|
|
78
|
+
resolveInput(state: ProbeStoredState, slot: ProbeSlot): ProbeLocalSource | Promise<ProbeLocalSource>;
|
|
79
|
+
current(): void;
|
|
80
|
+
/** Private minted-resource ownership notification, never an ordinary observer or authority source. */
|
|
81
|
+
workspaceOwned?: (workspace: ProbeWorkspace) => void;
|
|
82
|
+
fixture?: ProbeLocalFixturePorts;
|
|
83
|
+
}
|
|
84
|
+
export interface ProbeLocalAdapter {
|
|
85
|
+
prepareWorkerFrame: ProbeWorkerFramePreparer;
|
|
86
|
+
prepareEditorFrame(state: ProbeStoredState, slot: ProbeSlot): Promise<string>;
|
|
87
|
+
ports: import("../hub/guidance-probes.ts").GuidanceProbeFakePorts;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const probeObservedTokens = (result: ChatResult): number | null => {
|
|
91
|
+
const total = result.usage?.totalTokens;
|
|
92
|
+
return typeof total === "number" && Number.isSafeInteger(total) && total >= 0 ? total : null;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export async function probeLocalEffect<T>(scope: ProbeLocalEffectScope, unit: "model_calls" | "tool_calls" | "resources", descriptor: string,
|
|
96
|
+
charges: ProbeResourceCharges | undefined, reservedTokens: number | undefined,
|
|
97
|
+
effect: (signal: AbortSignal) => Promise<{ value: T; usage: number | null }>): Promise<T> {
|
|
98
|
+
scope.current();
|
|
99
|
+
const request = { sequence: scope.next(), unit, descriptorSha256: probeHash(descriptor),
|
|
100
|
+
...(charges ? { charges } : {}), ...(reservedTokens === undefined ? {} : { reservedTokens }) };
|
|
101
|
+
const result = await scope.effects.runEffect(request, async signal => {
|
|
102
|
+
scope.current();
|
|
103
|
+
const observed = await effect(signal);
|
|
104
|
+
return { ...observed, observationSha256: probeHash(guidanceProbeCanonical({ request, usage: observed.usage })) };
|
|
105
|
+
});
|
|
106
|
+
if (result.kind !== "executed") throw new ProbeLocalError("interrupted");
|
|
107
|
+
return result.value;
|
|
108
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { chmodSync, constants, closeSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, opendirSync, rmSync, 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, type ProbeDataPolicyV1, type ProbeSlot, type ProbeTree } from "../hub/guidance-probes.ts";
|
|
8
|
+
import { foldSegment } from "../hub/permission-mode.ts";
|
|
9
|
+
import { realPath } from "../hub/project.ts";
|
|
10
|
+
import { isDenied } from "./deny.ts";
|
|
11
|
+
import { ProbeToolRefusal } from "./probe-errors.ts";
|
|
12
|
+
|
|
13
|
+
/** Availability ceilings, narrowed by the admitted budget. ponytail: manifest-declared materialization ceilings are the upgrade path. */
|
|
14
|
+
export const PROBE_WORKSPACE_LIMITS = Object.freeze({ fileBytes: 1024 * 1024, workspaceBytes: 64 * 1024 * 1024 });
|
|
15
|
+
export interface ProbeMaterializedFile { dataId: string; relative: string; sha256: string; bytes: Uint8Array }
|
|
16
|
+
export type ProbeSourceClass = "tree" | "task_source" | "closed_artifact" | "anonymized_deliverable" | "closed_round_evidence" | "improver_context";
|
|
17
|
+
export interface ProbeWorkspaceInput {
|
|
18
|
+
role: ProbeSlot["role"];
|
|
19
|
+
policy: ProbeDataPolicyV1;
|
|
20
|
+
files: readonly ProbeMaterializedFile[];
|
|
21
|
+
sourceTree?: { repo: string; tree: ProbeTree; files: readonly { dataId: string; path: string }[] };
|
|
22
|
+
/** Trusted source-owner verification, never a declaration or model-selected classifier. */
|
|
23
|
+
verifySource(file: ProbeMaterializedFile, role: ProbeSlot["role"]): ProbeSourceClass | Promise<ProbeSourceClass>;
|
|
24
|
+
/** Completes the owner ledger reservation before this module creates a directory or writes bytes. */
|
|
25
|
+
reserveStorage(bytes: number): void | Promise<void>;
|
|
26
|
+
current(): void;
|
|
27
|
+
maxBytes: number;
|
|
28
|
+
}
|
|
29
|
+
export interface ProbeWorkspace {
|
|
30
|
+
readonly role: ProbeSlot["role"];
|
|
31
|
+
readonly root: string;
|
|
32
|
+
readonly home: string;
|
|
33
|
+
readonly scratch: string;
|
|
34
|
+
readonly output: string;
|
|
35
|
+
readonly inputDigest: string;
|
|
36
|
+
readonly files: readonly Readonly<{ dataId: string; relative: string; sha256: string; bytes: number }>[];
|
|
37
|
+
readonly allowedWrites: readonly string[];
|
|
38
|
+
}
|
|
39
|
+
interface DirectoryIdentity { file: string; dev: number; ino: number }
|
|
40
|
+
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 }[] }
|
|
41
|
+
const workspaces = new WeakMap<ProbeWorkspace, WorkspaceState>();
|
|
42
|
+
const digest = (bytes: Uint8Array | string): string => createHash("sha256").update(bytes).digest("hex");
|
|
43
|
+
function refused(): never { throw new Error("probe workspace source, role, path or resource proof is unavailable"); }
|
|
44
|
+
const integer = (value: number): boolean => Number.isSafeInteger(value) && value >= 0;
|
|
45
|
+
const sha = (value: string): boolean => /^[a-f0-9]{64}$/.test(value);
|
|
46
|
+
const roleNames: readonly ProbeSlot["role"][] = ["worker", "proposal", "compose", "select", "reflect"];
|
|
47
|
+
function directoryIdentity(file: string): DirectoryIdentity {
|
|
48
|
+
const stat = lstatSync(file);
|
|
49
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || realPath(file) !== file) refused();
|
|
50
|
+
return { file, dev: stat.dev, ino: stat.ino };
|
|
51
|
+
}
|
|
52
|
+
function requireDirectory(identity: DirectoryIdentity): void {
|
|
53
|
+
const current = directoryIdentity(identity.file);
|
|
54
|
+
if (current.dev !== identity.dev || current.ino !== identity.ino) refused();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The same folded names as ordinary guards, with no Git, hub or dependency tree in a probe. */
|
|
58
|
+
export function probeRelativePath(value: string): boolean {
|
|
59
|
+
return executionText(value, EXECUTION_REFERENCE_LIMITS.id) && !isAbsolute(value) && !value.includes("\\")
|
|
60
|
+
&& !/^[a-z]:/i.test(value) && !isDenied(value)
|
|
61
|
+
&& value.split("/").every(part => !!part && ![".", "..", ".git", ".agenthub", "node_modules", ".probe-temp"].includes(foldSegment(part)));
|
|
62
|
+
}
|
|
63
|
+
function permitted(role: ProbeSlot["role"], source: ProbeSourceClass, policy: ProbeDataPolicyV1): boolean {
|
|
64
|
+
if (role === "worker") return policy.roles.worker.guidanceOnlyExperience === true && (source === "tree" || source === "task_source");
|
|
65
|
+
if (role === "proposal" || role === "compose") return source === "tree" || source === "task_source" || source === "closed_artifact"
|
|
66
|
+
|| source === "improver_context" && policy.roles[role].improverContext === true;
|
|
67
|
+
if (role === "select") return policy.roles.select.anonymizedDeliverables === true && (source === "task_source" || source === "anonymized_deliverable");
|
|
68
|
+
return role === "reflect" && policy.roles.reflect.closedRoundOnly === true && source === "closed_round_evidence";
|
|
69
|
+
}
|
|
70
|
+
function sourceTreeFile(input: ProbeWorkspaceInput, file: ProbeMaterializedFile, paths: Map<string, string>): void {
|
|
71
|
+
const source = input.sourceTree, path = paths.get(file.dataId);
|
|
72
|
+
if (!source || !path || !probeRelativePath(path)) refused();
|
|
73
|
+
const oid = source.tree.oid;
|
|
74
|
+
if (!(source.tree.objectFormat === "sha1" && /^[a-f0-9]{40}$/.test(oid)
|
|
75
|
+
|| source.tree.objectFormat === "sha256" && /^[a-f0-9]{64}$/.test(oid))) refused();
|
|
76
|
+
const repo = realPath(source.repo);
|
|
77
|
+
const git = (args: string[], maximum: number) => {
|
|
78
|
+
input.current();
|
|
79
|
+
const result = hubGitSync(["-C", repo, ...args], { encoding: "utf8", timeout: 5000, maxBuffer: maximum });
|
|
80
|
+
input.current();
|
|
81
|
+
if (result.error || result.status !== 0) refused();
|
|
82
|
+
return result.stdout;
|
|
83
|
+
};
|
|
84
|
+
if (git(["rev-parse", "--show-object-format"], EXECUTION_REFERENCE_LIMITS.id).trim() !== source.tree.objectFormat
|
|
85
|
+
|| git(["cat-file", "-t", oid], EXECUTION_REFERENCE_LIMITS.id).trim() !== "tree") refused();
|
|
86
|
+
const entry = git(["--literal-pathspecs", "ls-tree", "-z", "--full-tree", oid, "--", path], EXECUTION_REFERENCE_LIMITS.id * 2);
|
|
87
|
+
const match = /^(100644|100755) blob ([a-f0-9]{40}|[a-f0-9]{64})\t([^\0]+)\0$/.exec(entry);
|
|
88
|
+
if (!match || match[3] !== path) refused();
|
|
89
|
+
const nativeObject = createHash(source.tree.objectFormat).update(`blob ${file.bytes.byteLength}`).update(Buffer.alloc(1)).update(file.bytes).digest("hex");
|
|
90
|
+
if (nativeObject !== match[2]) refused();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Materialize only verified admitted bytes. It never creates a Git worktree or exposes an object store. */
|
|
94
|
+
export async function materializeProbeWorkspace(input: ProbeWorkspaceInput): Promise<ProbeWorkspace> {
|
|
95
|
+
if (!roleNames.includes(input.role) || !integer(input.maxBytes)
|
|
96
|
+
|| typeof input.current !== "function" || typeof input.reserveStorage !== "function" || typeof input.verifySource !== "function") refused();
|
|
97
|
+
if (input.maxBytes > PROBE_WORKSPACE_LIMITS.workspaceBytes) throw new ProbeToolRefusal("workspace_ceiling");
|
|
98
|
+
input.current();
|
|
99
|
+
// Keep the host's checked declaration stable across source/reservation awaits.
|
|
100
|
+
input = { ...input, policy: JSON.parse(guidanceProbeCanonical(input.policy, GUIDANCE_PROBE_LIMITS.snapshotBytes)) as ProbeDataPolicyV1,
|
|
101
|
+
...(input.sourceTree ? { sourceTree: { repo: input.sourceTree.repo, tree: { ...input.sourceTree.tree }, files: input.sourceTree.files.map(item => ({ ...item })) } } : {}) };
|
|
102
|
+
const member = new Set(input.policy.roles[input.role].dataIds), declared = new Map(input.policy.admittedData.map(row => [row.id, row]));
|
|
103
|
+
if (member.size !== input.policy.roles[input.role].dataIds.length || declared.size !== input.policy.admittedData.length) refused();
|
|
104
|
+
const seenIds = new Set<string>(), foldedPaths = new Map<string, { spelling: string; directory: boolean }>(), treePaths = new Map<string, string>();
|
|
105
|
+
for (const item of input.sourceTree?.files ?? []) {
|
|
106
|
+
if (treePaths.has(item.dataId) || !probeRelativePath(item.path)) refused();
|
|
107
|
+
treePaths.set(item.dataId, item.path);
|
|
108
|
+
}
|
|
109
|
+
let total = 0;
|
|
110
|
+
const files: ProbeMaterializedFile[] = [];
|
|
111
|
+
for (const original of input.files) {
|
|
112
|
+
if (!executionText(original.dataId, EXECUTION_REFERENCE_LIMITS.id) || !probeRelativePath(original.relative)
|
|
113
|
+
|| !sha(original.sha256) || !(original.bytes instanceof Uint8Array) || seenIds.has(original.dataId) || !member.has(original.dataId)) refused();
|
|
114
|
+
if (original.bytes.byteLength > PROBE_WORKSPACE_LIMITS.fileBytes) throw new ProbeToolRefusal("file_ceiling");
|
|
115
|
+
const file = Object.freeze({ dataId: original.dataId, relative: original.relative, sha256: original.sha256, bytes: Buffer.from(original.bytes) });
|
|
116
|
+
const admission = declared.get(file.dataId);
|
|
117
|
+
if (!admission || !integer(admission.bytes) || admission.bytes !== file.bytes.length || admission.sha256 !== file.sha256
|
|
118
|
+
|| file.bytes.length > PROBE_WORKSPACE_LIMITS.fileBytes || digest(file.bytes) !== file.sha256) refused();
|
|
119
|
+
seenIds.add(file.dataId); total += file.bytes.length;
|
|
120
|
+
if (total > input.maxBytes) throw new ProbeToolRefusal("workspace_ceiling");
|
|
121
|
+
const parts = file.relative.split("/");
|
|
122
|
+
if (["scratch", "output"].includes(foldSegment(parts[0]!))) refused();
|
|
123
|
+
for (let index = 1; index <= parts.length; index++) {
|
|
124
|
+
const spelling = parts.slice(0, index).join("/"), directory = index < parts.length, key = parts.slice(0, index).map(foldSegment).join("/");
|
|
125
|
+
const prior = foldedPaths.get(key);
|
|
126
|
+
if (prior && (prior.spelling !== spelling || prior.directory !== directory || !directory)) refused();
|
|
127
|
+
foldedPaths.set(key, { spelling, directory });
|
|
128
|
+
}
|
|
129
|
+
files.push(file);
|
|
130
|
+
}
|
|
131
|
+
if (seenIds.size !== member.size || [...member].some(id => !seenIds.has(id)) || [...treePaths.keys()].some(id => !seenIds.has(id))) refused();
|
|
132
|
+
for (const file of files) {
|
|
133
|
+
input.current();
|
|
134
|
+
const source = await input.verifySource(file, input.role);
|
|
135
|
+
input.current();
|
|
136
|
+
if (!permitted(input.role, source, input.policy) || digest(file.bytes) !== file.sha256) refused();
|
|
137
|
+
if (source === "tree") sourceTreeFile(input, file, treePaths);
|
|
138
|
+
else if (treePaths.has(file.dataId)) refused();
|
|
139
|
+
}
|
|
140
|
+
const writes = input.policy.allowedWrites.map(row => {
|
|
141
|
+
if (!["scratch", "output"].includes(row.root) || !probeRelativePath(row.relative)) refused();
|
|
142
|
+
return `${row.root}/${row.relative}`;
|
|
143
|
+
});
|
|
144
|
+
if (new Set(writes.map(value => value.split("/").map(foldSegment).join("/"))).size !== writes.length) refused();
|
|
145
|
+
input.current();
|
|
146
|
+
await input.reserveStorage(total);
|
|
147
|
+
input.current();
|
|
148
|
+
// The complete setup charge has succeeded. No filesystem write occurs before it.
|
|
149
|
+
const parent = realPath(mkdtempSync(join(tmpdir(), "ahub-probe-")));
|
|
150
|
+
const directories = [directoryIdentity(parent)];
|
|
151
|
+
const directoryMap = new Map(directories.map(entry => [entry.file, entry]));
|
|
152
|
+
const setupFiles = new Map<string, { dev: number; ino: number }>();
|
|
153
|
+
const root = join(parent, "workspace"), home = join(parent, "home"), temporaryRoot = join(root, ".probe-temp");
|
|
154
|
+
const mkdir = (directory: string): void => {
|
|
155
|
+
requireDirectory(directories[0]!);
|
|
156
|
+
const actualRoot = directoryMap.get(root); if (actualRoot) requireDirectory(actualRoot);
|
|
157
|
+
const existing = directoryMap.get(directory);
|
|
158
|
+
if (existing) { requireDirectory(existing); return; }
|
|
159
|
+
if (lstatSync(directory, { throwIfNoEntry: false })) refused();
|
|
160
|
+
if (dirname(directory) !== parent) mkdir(dirname(directory));
|
|
161
|
+
mkdirSync(directory, { mode: 0o700 }); const identity = directoryIdentity(directory); directories.push(identity); directoryMap.set(directory, identity);
|
|
162
|
+
};
|
|
163
|
+
try {
|
|
164
|
+
chmodSync(parent, 0o700);
|
|
165
|
+
for (const directory of [root, home, temporaryRoot, join(root, "scratch"), join(root, "output")]) mkdir(directory);
|
|
166
|
+
const physicalRoots = [...directories];
|
|
167
|
+
for (const file of files) {
|
|
168
|
+
input.current();
|
|
169
|
+
if (digest(file.bytes) !== file.sha256) refused();
|
|
170
|
+
const dest = join(root, file.relative); mkdir(dirname(dest));
|
|
171
|
+
const fd = openSync(dest, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o400);
|
|
172
|
+
try {
|
|
173
|
+
const created = fstatSync(fd); setupFiles.set(dest, { dev: created.dev, ino: created.ino });
|
|
174
|
+
writeFileSync(fd, file.bytes); const stat = fstatSync(fd); if (!stat.isFile() || stat.nlink !== 1 || stat.size !== file.bytes.length) refused();
|
|
175
|
+
} finally { closeSync(fd); }
|
|
176
|
+
}
|
|
177
|
+
input.current();
|
|
178
|
+
const descriptors = files.map(({ dataId, relative, sha256, bytes }) => Object.freeze({ dataId, relative, sha256, bytes: bytes.length }));
|
|
179
|
+
const workspace: ProbeWorkspace = Object.freeze({ role: input.role, root, home, scratch: join(root, "scratch"), output: join(root, "output"),
|
|
180
|
+
inputDigest: digest(JSON.stringify(descriptors)), files: Object.freeze(descriptors), allowedWrites: Object.freeze(writes.map(path => join(root, path))) });
|
|
181
|
+
const identities = descriptors.map(item => {
|
|
182
|
+
const file = join(root, item.relative), stat = lstatSync(file);
|
|
183
|
+
return { file, dev: stat.dev, ino: stat.ino, size: stat.size, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs };
|
|
184
|
+
});
|
|
185
|
+
for (const entry of directories) requireDirectory(entry);
|
|
186
|
+
workspaces.set(workspace, { parent, temporaryRoot, current: input.current, reserveStorage: input.reserveStorage, maximum: input.maxBytes, charged: total, directories: physicalRoots, identities });
|
|
187
|
+
return workspace;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
// No child has been exposed. Remove only the same bounded fresh namespace we created, never a replacement.
|
|
190
|
+
for (const entry of directories) requireDirectory(entry);
|
|
191
|
+
const ownedDirs = new Map(directories.map(entry => [entry.file, entry]));
|
|
192
|
+
const check = (directory: string) => {
|
|
193
|
+
const handle = opendirSync(directory);
|
|
194
|
+
try {
|
|
195
|
+
for (let entry = handle.readSync(); entry; entry = handle.readSync()) {
|
|
196
|
+
const file = join(directory, entry.name), ownedDirectory = ownedDirs.get(file), ownedFile = setupFiles.get(file);
|
|
197
|
+
if (ownedDirectory) { requireDirectory(ownedDirectory); check(file); }
|
|
198
|
+
else {
|
|
199
|
+
const stat = lstatSync(file);
|
|
200
|
+
if (!ownedFile || !stat.isFile() || stat.nlink !== 1 || stat.dev !== ownedFile.dev || stat.ino !== ownedFile.ino) refused();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
} finally { handle.closeSync(); }
|
|
204
|
+
};
|
|
205
|
+
check(parent); requireDirectory(directories[0]!); rmSync(parent, { recursive: true, force: true });
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Narrow physical ownership only, usable after role/privacy withdrawal to stop our own resources. */
|
|
211
|
+
export function probeWorkspacePhysical(workspace: ProbeWorkspace): void {
|
|
212
|
+
const state = workspaces.get(workspace); if (!state) refused();
|
|
213
|
+
for (const directory of state.directories) requireDirectory(directory);
|
|
214
|
+
}
|
|
215
|
+
export function probeWorkspaceCurrent(workspace: ProbeWorkspace): void {
|
|
216
|
+
const state = workspaces.get(workspace); if (!state) refused(); state.current();
|
|
217
|
+
probeWorkspacePhysical(workspace);
|
|
218
|
+
for (const entry of state.identities) {
|
|
219
|
+
const stat = lstatSync(entry.file);
|
|
220
|
+
if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== entry.dev || stat.ino !== entry.ino || stat.size !== entry.size
|
|
221
|
+
|| stat.mtimeMs !== entry.mtimeMs || stat.ctimeMs !== entry.ctimeMs) refused();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
export function probeWorkspacePrivateRoot(workspace: ProbeWorkspace): string { probeWorkspaceCurrent(workspace); return workspaces.get(workspace)!.parent; }
|
|
225
|
+
export function probeWorkspaceTemporaryRoot(workspace: ProbeWorkspace): string { probeWorkspaceCurrent(workspace); return workspaces.get(workspace)!.temporaryRoot; }
|
|
226
|
+
/** Local conservative ceiling, called before the owner ledger's compound admission; never performs a second ledger effect. */
|
|
227
|
+
export function reserveProbeWorkspaceBytes(workspace: ProbeWorkspace, bytes: number): void {
|
|
228
|
+
probeWorkspaceCurrent(workspace); const state = workspaces.get(workspace)!;
|
|
229
|
+
if (!integer(bytes)) refused();
|
|
230
|
+
if (state.charged + bytes > state.maximum) throw new ProbeToolRefusal("workspace_ceiling");
|
|
231
|
+
state.charged += bytes;
|
|
232
|
+
}
|
|
233
|
+
export async function reserveProbeWorkspaceStorage(workspace: ProbeWorkspace, bytes: number): Promise<void> {
|
|
234
|
+
reserveProbeWorkspaceBytes(workspace, bytes); const state = workspaces.get(workspace)!;
|
|
235
|
+
await state.reserveStorage(bytes); state.current();
|
|
236
|
+
probeWorkspaceCurrent(workspace);
|
|
237
|
+
}
|