@foldrun/core 21.2.0 → 22.1.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.
Files changed (43) hide show
  1. package/dist/src/agent-import.js +3 -0
  2. package/dist/src/capture.d.ts +3 -6
  3. package/dist/src/capture.js +7 -5
  4. package/dist/src/captured-calls.d.ts +30 -0
  5. package/dist/src/captured-calls.js +219 -0
  6. package/dist/src/completions.js +2 -0
  7. package/dist/src/confine.d.ts +6 -0
  8. package/dist/src/confine.js +33 -0
  9. package/dist/src/frontmatter-fields.js +1 -0
  10. package/dist/src/frontmatter-schema.js +2 -0
  11. package/dist/src/mirror-base.d.ts +24 -0
  12. package/dist/src/mirror-base.js +82 -0
  13. package/dist/src/network.d.ts +13 -0
  14. package/dist/src/network.js +27 -0
  15. package/dist/src/records.d.ts +6 -1
  16. package/dist/src/revision-store.d.ts +12 -0
  17. package/dist/src/revision-store.js +27 -0
  18. package/dist/src/runner.d.ts +3 -0
  19. package/dist/src/runner.js +43 -5
  20. package/dist/src/script-tools.d.ts +4 -0
  21. package/dist/src/script-tools.js +2 -0
  22. package/dist/src/starter.js +2 -2
  23. package/dist/src/store.d.ts +5 -6
  24. package/dist/src/store.js +53 -30
  25. package/dist/src/workspace-revisions.d.ts +20 -0
  26. package/dist/src/workspace-revisions.js +397 -13
  27. package/package.json +1 -1
  28. package/src/agent-import.ts +3 -0
  29. package/src/capture.ts +7 -6
  30. package/src/captured-calls.ts +226 -0
  31. package/src/completions.ts +2 -0
  32. package/src/confine.ts +31 -0
  33. package/src/frontmatter-fields.ts +1 -0
  34. package/src/frontmatter-schema.ts +2 -0
  35. package/src/mirror-base.ts +91 -0
  36. package/src/network.ts +28 -0
  37. package/src/records.ts +6 -1
  38. package/src/revision-store.ts +37 -0
  39. package/src/runner.ts +45 -5
  40. package/src/script-tools.ts +6 -0
  41. package/src/starter.ts +2 -2
  42. package/src/store.ts +50 -29
  43. package/src/workspace-revisions.ts +358 -12
@@ -0,0 +1,226 @@
1
+ // Captured tool calls in the blob store (FOL-126 phase 7, step 2).
2
+ //
3
+ // A call's masked input and output used to be a file beside its run
4
+ // (runs/<run>/calls/<call>.json — store.ts writeCapturedCall), merged in place
5
+ // when the output arrived. With a database, a blob store and the setting
6
+ // `runs.calls_store` on, each call is ONE blob, written once when the call
7
+ // completes (the input waits in memory for its output: no read-merge-write),
8
+ // pinned by a run holder (`calls:<run>`, no lease — it lives until the run is
9
+ // deleted) before the upload, and indexed by a step-state row (kind "call",
10
+ // ref = the call id → {sha, size}). Masking is capture.ts's and is done before
11
+ // anything gets here; a part over the cap was cut and flagged there.
12
+ //
13
+ // Reads look at the row first, then at the file, so every run stays readable
14
+ // whichever way the switch is set. A row whose blob cannot be read is an error
15
+ // (CapturedCallUnavailable), never "nothing recorded".
16
+ //
17
+ // TEMPORARY, remove at cutover (phase 9): a write that fails with an error
18
+ // (store down, database refuses) falls back to the volume file and logs
19
+ // `captured_calls.fallback`. At cutover that branch becomes "the call is not
20
+ // recorded, and the event says so".
21
+
22
+ import { records } from "./records.ts";
23
+ import { blobObjectKey, sha256Hex } from "./manifest.ts";
24
+ import { opsError } from "./ops-log.ts";
25
+ import { BlobNotFound, readAll } from "./blob-store.ts";
26
+ import type { Deps } from "./publish.ts";
27
+ import { writeCapturedCall, readCapturedCall, registerRunRemovedHook, type CapturedCall } from "./store.ts";
28
+ import { processState } from "./process-state.ts";
29
+
30
+ const KIND = "call";
31
+ const SAFE = /^[A-Za-z0-9_.-]{1,128}$/;
32
+ const holderOf = (runId: string) => ({ kind: "run" as const, id: `calls:${runId}` });
33
+
34
+ /** One per process (process-state.ts): the store the boot registered and the
35
+ * clean-ups in flight, whichever copy of this module a route handler holds. */
36
+ const CALLS = processState("captured-calls", () => ({ backend: null as Deps | null, background: new Set<Promise<unknown>>() }));
37
+
38
+ /** Registered with the revision backend (workspace-revisions.ts): the blob store and the pins. */
39
+ export function setCallsBackend(deps: Deps | null): void {
40
+ CALLS.backend = deps;
41
+ registerRunRemovedHook(deps ? runGone : null, "captured-calls");
42
+ }
43
+
44
+ /** The call could not be read back from where it was recorded. */
45
+ export class CapturedCallUnavailable extends Error {
46
+ constructor(callId: string, cause?: unknown) {
47
+ super(`captured call unavailable: the recorded content of call "${callId}" could not be read from storage`);
48
+ this.name = "CapturedCallUnavailable";
49
+ if (cause !== undefined) this.cause = cause;
50
+ }
51
+ }
52
+
53
+ const portFor = (tenant: string, workspace: string) => {
54
+ const p = records(tenant, workspace);
55
+ // stepRuns too: without it a deleted workspace's calls could never be
56
+ // found again to release their pins (Codex review, 13 Nov 2026).
57
+ return p?.async?.stepPut && p.async.stepGet && p.async.stepRuns ? p : null;
58
+ };
59
+ const switchedOn = (p: { callsStoreOn?(): boolean }): boolean => {
60
+ try {
61
+ return p.callsStoreOn?.() === true;
62
+ } catch {
63
+ return false;
64
+ }
65
+ };
66
+ /** Where a new call goes: the store (deps + port), or null (the volume). */
67
+ function active(tenant: string, workspace: string) {
68
+ const deps = CALLS.backend;
69
+ const port = portFor(tenant, workspace);
70
+ return deps && port && switchedOn(port) ? { deps, port } : null;
71
+ }
72
+
73
+ const merge = (prev: CapturedCall | undefined, part: CapturedCall): CapturedCall => {
74
+ const next: CapturedCall = { ...prev, ...part, truncated: Boolean(prev?.truncated || part.truncated) || undefined };
75
+ if (!next.truncated) delete next.truncated;
76
+ return next;
77
+ };
78
+
79
+ interface Ctx {
80
+ tenant: string;
81
+ workspace: string;
82
+ runId: string;
83
+ workspaceRoot: string;
84
+ }
85
+ interface Session {
86
+ ctx: Ctx;
87
+ /** Inputs waiting for their output. */
88
+ pending: Map<string, CapturedCall>;
89
+ writes: Set<Promise<void>>;
90
+ }
91
+ const sessions = new WeakMap<object, Session>();
92
+
93
+ /** One blob per call: pin, upload, then the row that names it. */
94
+ async function storeCall(ctx: Ctx, call: CapturedCall): Promise<void> {
95
+ const a = active(ctx.tenant, ctx.workspace);
96
+ const fall = (err: unknown) => {
97
+ // TEMPORARY (see the header): the volume copy, so the call is not lost.
98
+ opsError("captured_calls.fallback", err, { tenant: ctx.tenant, workspace: ctx.workspace, runId: ctx.runId, callId: call.id });
99
+ try {
100
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, call);
101
+ } catch (e) {
102
+ opsError("capture.write_failed", e, { runId: ctx.runId });
103
+ }
104
+ };
105
+ if (!a) return fall(new Error("the call store went away before the call was written"));
106
+ try {
107
+ const bytes = Buffer.from(JSON.stringify(call));
108
+ const sha = sha256Hex(bytes);
109
+ await a.deps.pins?.pinBlobs(ctx.tenant, [sha], holderOf(ctx.runId));
110
+ await a.deps.blobs.putIfAbsent(blobObjectKey(ctx.tenant, sha), bytes, { contentType: "application/json" });
111
+ await a.port.async!.stepPut!(ctx.tenant, ctx.workspace, ctx.runId, KIND, call.id, { sha, size: bytes.length });
112
+ } catch (err) {
113
+ fall(err);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The runner's place to put a call's part (input on the call, output on its
119
+ * completion). Returns whether it was taken (the event says `captured`).
120
+ * `owner` is the step: flushCalls(owner) settles what it left.
121
+ */
122
+ export function callSink(owner: object, ctx: Ctx): (part: CapturedCall) => boolean {
123
+ const s: Session = { ctx, pending: new Map(), writes: new Set() };
124
+ sessions.set(owner, s);
125
+ return (part) => {
126
+ if (!SAFE.test(part.id) || !SAFE.test(ctx.runId)) return false;
127
+ const live = active(ctx.tenant, ctx.workspace);
128
+ const waiting = s.pending.get(part.id);
129
+ if (live && part.output === undefined) {
130
+ s.pending.set(part.id, merge(waiting, part));
131
+ return true;
132
+ }
133
+ s.pending.delete(part.id);
134
+ // A call whose input went to the volume before the switch flipped, or on another worker.
135
+ const prev = waiting ?? (live ? readCapturedCall(ctx.tenant, ctx.workspace, ctx.runId, part.id) ?? undefined : undefined);
136
+ const whole = merge(prev, part);
137
+ if (!live) {
138
+ writeCapturedCall(ctx.workspaceRoot, ctx.runId, whole);
139
+ return true;
140
+ }
141
+ const w: Promise<void> = storeCall(ctx, whole).finally(() => s.writes.delete(w));
142
+ s.writes.add(w);
143
+ return true;
144
+ };
145
+ }
146
+
147
+ /** The step ended: write the inputs that never got an output, wait for every write. Never throws. */
148
+ export async function flushCalls(owner: object): Promise<void> {
149
+ const s = sessions.get(owner);
150
+ if (!s) return;
151
+ sessions.delete(owner);
152
+ for (const call of s.pending.values()) {
153
+ if (active(s.ctx.tenant, s.ctx.workspace)) s.writes.add(storeCall(s.ctx, call));
154
+ else {
155
+ try {
156
+ writeCapturedCall(s.ctx.workspaceRoot, s.ctx.runId, call);
157
+ } catch (err) {
158
+ opsError("capture.write_failed", err, { runId: s.ctx.runId });
159
+ }
160
+ }
161
+ }
162
+ s.pending.clear();
163
+ await Promise.allSettled([...s.writes]);
164
+ }
165
+
166
+ /** One recorded call, or null (not recorded). The row first, then the file. */
167
+ export async function readCapturedCallAsync(tenant: string, workspace: string, runId: string, callId: string): Promise<CapturedCall | null> {
168
+ if (!SAFE.test(runId) || !SAFE.test(callId) || callId.startsWith(".") || runId.startsWith(".")) return null;
169
+ const port = portFor(tenant, workspace);
170
+ if (port) {
171
+ let row: { sha?: string } | undefined;
172
+ try {
173
+ row = (await port.async!.stepGet!(tenant, workspace, runId, KIND, callId)) as { sha?: string } | undefined;
174
+ } catch (err) {
175
+ throw new CapturedCallUnavailable(callId, err);
176
+ }
177
+ if (row) {
178
+ try {
179
+ if (!CALLS.backend || typeof row.sha !== "string") throw new Error("the call store is not available here");
180
+ const call = JSON.parse((await readAll(CALLS.backend.blobs, blobObjectKey(tenant, row.sha))).toString("utf8")) as CapturedCall;
181
+ if (!call || typeof call !== "object" || call.id !== callId) throw new Error("the stored object is not this call");
182
+ return call;
183
+ } catch (err) {
184
+ if (!(err instanceof BlobNotFound)) opsError("captured_calls.read_failed", err, { tenant, workspace, runId, callId });
185
+ throw new CapturedCallUnavailable(callId, err);
186
+ }
187
+ }
188
+ }
189
+ return readCapturedCall(tenant, workspace, runId, callId);
190
+ }
191
+
192
+ // ---------------------------------------------------------------- lifecycle
193
+
194
+ /** What the run-delete hook started and has not finished (tests, a process that is ending). */
195
+ export async function settleCalls(): Promise<void> {
196
+ while (CALLS.background.size) await Promise.allSettled([...CALLS.background]);
197
+ }
198
+
199
+ /** A run was deleted: its calls' pin goes (the rows went with it; the sweeper takes the blobs). */
200
+ function runGone(tenant: string, _workspace: string, runId: string): void {
201
+ const deps = CALLS.backend;
202
+ if (!deps?.pins || !SAFE.test(runId)) return;
203
+ const p = (async () => {
204
+ for (let attempt = 0; ; attempt++) {
205
+ try {
206
+ await deps.pins!.release(tenant, holderOf(runId));
207
+ return;
208
+ } catch (err) {
209
+ // A pin that cannot be released is kept: a leak is safe, a loss is not.
210
+ if (attempt >= 4) return opsError("captured_calls.drop_failed", err, { tenant, runId });
211
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
212
+ }
213
+ }
214
+ })();
215
+ const q = p.finally(() => CALLS.background.delete(q));
216
+ CALLS.background.add(q);
217
+ }
218
+
219
+ /** A workspace is being deleted (its rows still there): release the pin of every run that has calls
220
+ * in the store. Throws when the pins cannot be reached, so the delete can be retried. */
221
+ export async function dropWorkspaceCalls(tenant: string, workspace: string): Promise<void> {
222
+ const deps = CALLS.backend;
223
+ const port = records(tenant, workspace);
224
+ if (!deps?.pins || !port?.async?.stepRuns) return;
225
+ for (const runId of await port.async.stepRuns(tenant, workspace, KIND)) await deps.pins.release(tenant, holderOf(runId));
226
+ }
@@ -76,6 +76,8 @@ const TOOL_GROUPS: Completion[] = [
76
76
  { label: "write", hint: "Read, Write, Edit, Glob, Grep" },
77
77
  { label: "code", hint: "Bash — runs anything in the sandbox" },
78
78
  { label: "web", hint: "search, fetch, browse, crawl, map, extract, answer, monitor — providers under web:" },
79
+ { label: "docs", hint: "a library's current docs and code examples, pinned to a version (Context7) — gallery" },
80
+ { label: "video", hint: "motion graphics and video from React code: new, compositions, still, render (Remotion) — gallery" },
79
81
  { label: "ask", hint: "ask_person — ask the person running the desk mid-step, and wait for the answer" },
80
82
  { label: "peers", hint: "peers_list + peers_message — the colleagues running beside it in its parallel group, and a message to one of them" },
81
83
  { label: "text", hint: "extract_text — an image, scanned PDF, office file, audio or video as text (Persian + English OCR, speech)" },
package/src/confine.ts CHANGED
@@ -31,6 +31,7 @@
31
31
  import fs from "node:fs";
32
32
  import path from "node:path";
33
33
  import { refusedBack } from "./copy-back.ts";
34
+ import { platform } from "./platform.ts";
34
35
 
35
36
  /**
36
37
  * A path with its symlinks resolved, as far as it exists.
@@ -226,6 +227,24 @@ function linkedWorkspace(roots: Roots): boolean {
226
227
  }
227
228
  }
228
229
 
230
+ /**
231
+ * The platform shelf's copy of a library skill file the account does not
232
+ * have: `<library>/skills/<rest>` missing on disk, `<gallery>/skills/<rest>`
233
+ * there. Null otherwise — the account's own copy always wins.
234
+ */
235
+ export function gallerySkillFile(abs: string, library: string): string | null {
236
+ const gallery = platform.galleryDir();
237
+ if (!gallery) return null;
238
+ const rel = path.relative(library, abs);
239
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
240
+ const parts = rel.split(path.sep);
241
+ if (parts[0] !== "skills" || parts.length < 2 || fs.existsSync(abs)) return null;
242
+ const shelfSkills = real(path.resolve(gallery, "skills"));
243
+ const candidate = real(path.resolve(shelfSkills, ...parts.slice(1)));
244
+ if (path.relative(shelfSkills, candidate).startsWith("..")) return null;
245
+ return fs.existsSync(candidate) ? candidate : null;
246
+ }
247
+
229
248
  export function checkPaths(
230
249
  toolName: string,
231
250
  input: Record<string, unknown>,
@@ -253,6 +272,18 @@ export function checkPaths(
253
272
  const virtual = expandVirtual(raw, roots);
254
273
  const abs = real(virtual ? virtual.abs : path.resolve(roots.agentDir, raw));
255
274
 
275
+ // A gallery skill on a step with no sandbox. The prompt names every
276
+ // gallery skill under the account library (`../../../../library/skills/
277
+ // <name>/…`), because a sandbox has the gallery laid down there; on this
278
+ // host the library holds only the account's own files, so a read that
279
+ // finds nothing there is served from the platform's shelf. Reads only:
280
+ // the shelf is the platform's.
281
+ const shelf = !isWrite ? gallerySkillFile(abs, library) : null;
282
+ if (shelf) {
283
+ rewritten = { ...(rewritten ?? input), [key]: shelf };
284
+ continue;
285
+ }
286
+
256
287
  // Knowledge is given, not learned: an agent that rewrites the price list
257
288
  // it was handed has corrupted its own source of truth. What it discovers
258
289
  // goes to memory/, which it owns.
@@ -200,6 +200,7 @@ const TOOL: FieldSpec[] = [
200
200
  { key: "test_mode", type: "string", values: ["allow"], help: "script: allow — it may run in a test run" },
201
201
  { key: "secrets", type: ["list", "string"], help: "script: secret names, or proxied | materialised" },
202
202
  { key: "runtime", type: "object", help: "script: packages it needs" },
203
+ { key: "network", type: ["list", "string"], help: "script: the sites its program reaches, added to the granting step's network: list — [api.example.com]" },
203
204
  { key: "code", type: "string", help: "script: the program inline" },
204
205
  { key: "command", type: "string", help: "mcp: the server's command" },
205
206
  { key: "env", type: "object", help: "mcp: its environment" },
@@ -12,6 +12,7 @@ import { modelSecretCollision } from "./model-credential.ts";
12
12
  import { resourcesProblem, computeProblem } from "./resources.ts";
13
13
  import { remotesProblem } from "./a2a-remotes.ts";
14
14
  import { a2aPublishProblem } from "./a2a-publish.ts";
15
+ import { toolSiteProblems } from "./network.ts";
15
16
 
16
17
  export { FRONTMATTER, schemaKindOf, type FieldSpec, type FieldType, type SchemaKind } from "./frontmatter-fields.ts";
17
18
 
@@ -74,6 +75,7 @@ const CHECKS: Partial<Record<SchemaKind, Record<string, (value: unknown) => stri
74
75
  methods: methodsProblem,
75
76
  rate: (v) => (parseRate(v) ? null : `"${shown(v)}" is not a rate — N/s, N/minute, N/hour, or a number per second, above 0`),
76
77
  secrets: modelSecretCollision,
78
+ network: (v) => toolSiteProblems(v)[0] ?? null,
77
79
  },
78
80
  "eval": {
79
81
  effort: (v) => (resolveEffort(v) ? null : `"${String(v)}" is not an effort — low, medium, high, xhigh or max; the judge runs at none`),
@@ -0,0 +1,91 @@
1
+ // What a pod's copy of a workspace was last brought to (FOL-126, 13 Nov 2026):
2
+ // the two head ids and every file's sha as the heads held them. The mirror
3
+ // (workspace-mirror.ts) writes it after a sync; the reconcile reads it so a
4
+ // file that differs from it is this pod's own change, and one that differs
5
+ // only from the head is someone else's, not yet copied here.
6
+ //
7
+ // Kept on the pod's own disk beside the folders, outside every workspace:
8
+ // <data>/.mirror/<tenant>/<workspace>.json. Lost with the disk, it is rebuilt
9
+ // by the next full sync (a pod starts with an empty disk anyway).
10
+
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import crypto from "node:crypto";
14
+ import { dataRoot } from "./paths.ts";
15
+ import { processState } from "./process-state.ts";
16
+
17
+ export interface MirrorBase {
18
+ workspaceHead: string | null;
19
+ stateHead: string | null;
20
+ /** path → what the heads held for it at that sync (a path's base when this
21
+ * pod's change to it is published). */
22
+ files: Record<string, { sha: string; mode: number }>;
23
+ at: string;
24
+ }
25
+
26
+ const GATE = processState("mirror-gate", () => ({ on: (() => false) as () => boolean }));
27
+
28
+ /** The platform says whether this pod's folders are a copy of the heads
29
+ * (`revisions.mirror`). Off on a laptop, in the CLI and until switched on. */
30
+ export function setMirrorGate(fn: (() => boolean) | null): void {
31
+ GATE.on = fn ?? (() => false);
32
+ }
33
+
34
+ export function mirrorOn(): boolean {
35
+ try {
36
+ return GATE.on();
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ const SAFE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
43
+ export const mirrorBaseFile = (tenant: string, workspace: string): string | null =>
44
+ SAFE.test(tenant) && SAFE.test(workspace) ? path.join(dataRoot(), ".mirror", tenant, `${workspace}.json`) : null;
45
+
46
+ export function readMirrorBase(tenant: string, workspace: string): MirrorBase | null {
47
+ const f = mirrorBaseFile(tenant, workspace);
48
+ if (!f) return null;
49
+ try {
50
+ return JSON.parse(fs.readFileSync(f, "utf8")) as MirrorBase;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ export function writeMirrorBase(tenant: string, workspace: string, base: MirrorBase): void {
57
+ const f = mirrorBaseFile(tenant, workspace);
58
+ if (!f) return;
59
+ fs.mkdirSync(path.dirname(f), { recursive: true });
60
+ const tmp = `${f}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
61
+ fs.writeFileSync(tmp, JSON.stringify(base));
62
+ fs.renameSync(tmp, f);
63
+ }
64
+
65
+ export function dropMirrorBase(tenant: string, workspace: string): void {
66
+ const f = mirrorBaseFile(tenant, workspace);
67
+ if (f) fs.rmSync(f, { force: true });
68
+ }
69
+
70
+ /** Every workspace this pod holds a copy of, by its base files. */
71
+ export function mirroredWorkspaces(): { tenant: string; workspace: string }[] {
72
+ const root = path.join(dataRoot(), ".mirror");
73
+ const out: { tenant: string; workspace: string }[] = [];
74
+ let tenants: string[] = [];
75
+ try {
76
+ tenants = fs.readdirSync(root);
77
+ } catch {
78
+ return out;
79
+ }
80
+ for (const tenant of tenants) {
81
+ if (!SAFE.test(tenant)) continue;
82
+ let files: string[] = [];
83
+ try {
84
+ files = fs.readdirSync(path.join(root, tenant));
85
+ } catch {
86
+ continue;
87
+ }
88
+ for (const f of files) if (f.endsWith(".json") && SAFE.test(f.slice(0, -5))) out.push({ tenant, workspace: f.slice(0, -5) });
89
+ }
90
+ return out;
91
+ }
package/src/network.ts CHANGED
@@ -175,6 +175,34 @@ function siteList(v: unknown): string[] | null {
175
175
  return null;
176
176
  }
177
177
 
178
+ /**
179
+ * The sites a tool's own definition says its program reaches — `network:
180
+ * [context7.com]` in a script tool's tool.md (13 Nov 2026). Granting the tool
181
+ * adds them to the step's list, the way an `apis:` base or a bound secret's
182
+ * site always was: the capability travels with what it needs, and an agent
183
+ * on `trusted` need not learn which hosts a gallery tool calls. A list or
184
+ * one comma-separated line of domains; what is not a site is dropped here
185
+ * and reported by `toolSiteProblems`.
186
+ */
187
+ export function toolSites(raw: unknown): string[] {
188
+ const list = siteList(raw) ?? [];
189
+ return [...new Set(list.map(normalHost).filter((h) => SITE.test(h) && !NETWORK_LEVELS.includes(h as NetworkLevel)))];
190
+ }
191
+
192
+ /** What is wrong with a tool's `network:` — for check and deploy. A tool
193
+ * names sites only: the level (open, trusted, none) is the agent's to set. */
194
+ export function toolSiteProblems(raw: unknown): string[] {
195
+ if (raw === undefined || raw === null) return [];
196
+ const list = siteList(raw);
197
+ if (!list) return ["a tool's network: is a list of sites, e.g. [api.example.com]"];
198
+ return list.flatMap((x) =>
199
+ NETWORK_LEVELS.includes(normalHost(x) as NetworkLevel)
200
+ ? [`a tool's network: names sites, not a level — "${x}" is the agent's to set`]
201
+ : SITE.test(normalHost(x))
202
+ ? []
203
+ : [`"${x}" is not a site — a domain or *.domain, no scheme, path or port`]);
204
+ }
205
+
178
206
  /**
179
207
  * One `network:` value, read. Never throws: what cannot be read is a
180
208
  * problem `check` and deploy report, and the run treats that level as
package/src/records.ts CHANGED
@@ -41,12 +41,14 @@ export interface RecordsPortAsync {
41
41
  stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
42
42
  /** `ref` null: every ref of the kind. */
43
43
  stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
44
+ /** The ids of the runs that have rows of this kind in the workspace. */
45
+ stepRuns?(tenant: string, workspace: string, kind: string): Promise<string[]>;
44
46
  }
45
47
 
46
48
  /** Small per-workspace state that used to be files in the workspace's folder
47
49
  * (FOL-126, the last files on the volume): webhook generations and the
48
50
  * delivery log, eval results and their history, grades and grader cursors,
49
- * the deployed commit, captured tool calls. Two shapes: a DOCUMENT per
51
+ * the deployed commit. Two shapes: a DOCUMENT per
50
52
  * (kind, key), and an append-only LOG per kind. Synchronous like the rest of
51
53
  * the port; workspace-docs.ts is the only caller. */
52
54
  export interface DocsPort {
@@ -86,6 +88,9 @@ export interface RecordsPort {
86
88
  * state is written to the run's folder as before (it is still READ from
87
89
  * rows first, so switching off mid-run loses nothing). */
88
90
  stepStateOn?(): boolean;
91
+ /** The `runs.calls_store` setting, read per call: while false, a captured
92
+ * call is written to the run's folder as before (captured-calls.ts). */
93
+ callsStoreOn?(): boolean;
89
94
  // ---- runs: the whole record, and the row a list reads
90
95
  /** Insert or replace one run. `live`: queued, running or parked at a gate. Last write wins. */
91
96
  runPut(tenant: string, workspace: string, run: RunRecord, summary: RunSummary, live: boolean): void;
@@ -145,9 +145,22 @@ export interface IndexedFile {
145
145
  by: string;
146
146
  }
147
147
 
148
+ /** One workspace's head ids (RevisionStore.allHeads). */
149
+ export interface HeadIds {
150
+ tenant: string;
151
+ workspace: string;
152
+ /** The workspace head's revision id; null when only the state head exists. */
153
+ workspaceHead: string | null;
154
+ stateHead: string | null;
155
+ }
156
+
148
157
  export interface RevisionStore {
149
158
  readonly kind: "pg" | "local";
150
159
  head(ws: WorkspaceRef): Promise<Revision | null>;
160
+ /** Every workspace that has a head, with the ids of its two heads — what a
161
+ * pod whose folders are a copy of the heads compares itself with
162
+ * (workspace-mirror.ts). Optional: a store without it has no mirror. */
163
+ allHeads?(): Promise<HeadIds[]>;
151
164
  revision(ws: WorkspaceRef, id: string): Promise<Revision | null>;
152
165
  /** Newest first. `before` is a seq: pass the last page's lowest seq. */
153
166
  revisions(ws: WorkspaceRef, opts?: { limit?: number; before?: number }): Promise<Revision[]>;
@@ -295,6 +308,30 @@ export function localRevisionStore(root: string = path.join(dataRoot(), ".revisi
295
308
  async head(ws) {
296
309
  return headOf(ws);
297
310
  },
311
+ async allHeads() {
312
+ const out: HeadIds[] = [];
313
+ let tenants: string[] = [];
314
+ try {
315
+ tenants = fs.readdirSync(root).filter((n) => !n.startsWith("."));
316
+ } catch {
317
+ return out;
318
+ }
319
+ for (const tenant of tenants.sort()) {
320
+ let names: string[] = [];
321
+ try {
322
+ names = fs.readdirSync(path.join(root, tenant)).filter((n) => !n.startsWith("."));
323
+ } catch {
324
+ continue;
325
+ }
326
+ for (const workspace of names.sort()) {
327
+ const ws = { tenant, workspace };
328
+ const w = headOf(ws);
329
+ const st = headOf({ ...ws, scope: "state" } as WorkspaceRef);
330
+ if (w || st) out.push({ tenant, workspace, workspaceHead: w?.id ?? null, stateHead: st?.id ?? null });
331
+ }
332
+ }
333
+ return out;
334
+ },
298
335
  async revision(ws, id) {
299
336
  for (const seq of seqs(ws).reverse()) {
300
337
  const r = bySeq(ws, seq);
package/src/runner.ts CHANGED
@@ -7,6 +7,7 @@ import { opsLog, opsError } from "./ops-log.ts";
7
7
  import { globMatch } from "./bounded-match.ts";
8
8
  import { latestRevisionId } from "./history.ts";
9
9
  import { recordCallIo, redactionsFor } from "./capture.ts";
10
+ import { callSink, flushCalls } from "./captured-calls.ts";
10
11
  import { AUTH_REFUSAL, platformCause } from "./issues.ts";
11
12
  import { hookNames } from "./hooks.ts";
12
13
  import crypto from "node:crypto";
@@ -118,7 +119,7 @@ import { buildScriptTools, parseScripts, type ExecutionContext, type ScriptSpec
118
119
  import { libraryDir, libraryTools, libraryMemoryIndex } from "./library.ts";
119
120
  import { fingerprint, mergeRuntimes, parseRuntime, prepareRuntime, stepInstallEnv, type PreparedRuntime, type RuntimeSpec } from "./runtime.ts";
120
121
  import { buildInstallTool, INSTALL_TOOL } from "./install-tool.ts";
121
- import { dataRoot, singleWorkspace } from "./paths.ts";
122
+ import { dataRoot } from "./paths.ts";
122
123
  import { materializeFiles, harvestFiles, storageBaseline } from "./storage.ts";
123
124
  import { readStorageBaseline, writeStorageBaseline } from "./step-state.ts";
124
125
  import { chooseExecutor, ensureImage } from "./container.ts";
@@ -391,6 +392,9 @@ export interface DiscoveredSkill {
391
392
  /** The rest of the Agent Skills layout: references/ and assets/. */
392
393
  hasReferences: boolean;
393
394
  hasAssets: boolean;
395
+ /** From the platform's gallery, not the account's files: offered only to
396
+ * an agent whose `skills:` names it (applicableSkills). */
397
+ gallery?: boolean;
394
398
  }
395
399
 
396
400
  const toTags = (v: unknown): string[] =>
@@ -816,8 +820,11 @@ export function applicableSkills<T extends { name: string; when: string[] }>(
816
820
  only: string[],
817
821
  tags: string[],
818
822
  ): T[] {
823
+ // A gallery skill is the platform's, in every account: it reaches an agent
824
+ // only when its `skills:` names it, the way a gallery tool is granted only
825
+ // by `tools:` — so shipping one never grows every other agent's prompt.
819
826
  return skills
820
- .filter((s) => only.length === 0 || only.includes(s.name))
827
+ .filter((s) => (only.length === 0 ? !(s as { gallery?: boolean }).gallery : only.includes(s.name)))
821
828
  .filter((s) => s.when.length === 0 || s.when.some((t) => tags.includes(t)));
822
829
  }
823
830
 
@@ -1077,7 +1084,9 @@ export function agentContext(
1077
1084
  // it's an allowlist, which is how you keep a focused agent focused.
1078
1085
  const only: string[] = refNames(front.skills);
1079
1086
  const applicable = applicableSkills(skills, only, tags);
1080
- const withheld = skills.length - applicable.length;
1087
+ // The gallery's skills an agent did not name are not "withheld" from it —
1088
+ // they were never its to have — so they are not counted in the note.
1089
+ const withheld = skills.filter((s) => !s.gallery || only.includes(s.name)).length - applicable.length;
1081
1090
 
1082
1091
  if (applicable.length) {
1083
1092
  const lines = applicable.map((s) => {
@@ -2194,7 +2203,16 @@ export function operatorBlock(step: Pick<StepRecord, "ask" | "approvalNote" | "a
2194
2203
  }
2195
2204
 
2196
2205
 
2197
- async function runStep(
2206
+ /** A step, and then whatever its captured calls still hold (captured-calls.ts). */
2207
+ async function runStep(...args: Parameters<typeof runStepBody>): ReturnType<typeof runStepBody> {
2208
+ try {
2209
+ return await runStepBody(...args);
2210
+ } finally {
2211
+ await flushCalls(args[2]);
2212
+ }
2213
+ }
2214
+
2215
+ async function runStepBody(
2198
2216
  agentDir: string,
2199
2217
  tenant: string,
2200
2218
  step: StepRecord,
@@ -2312,6 +2330,8 @@ async function runStep(
2312
2330
  // calls keep their names, sizes and times (FOL-54 step 4).
2313
2331
  let capturedChars = 0;
2314
2332
  let captureFull = false;
2333
+ const callsRoot = path.resolve(agentDir, "..", "..");
2334
+ const sink = runId ? callSink(step, { tenant, workspace: path.basename(callsRoot), runId, workspaceRoot: callsRoot }) : undefined;
2315
2335
  const push = (type: StepRecord["events"][number]["type"], text: string, extra?: EventExtra) => {
2316
2336
  const t = new Date().toISOString();
2317
2337
  // The model has begun its first response: held only in memory, for
@@ -2346,7 +2366,7 @@ async function runStep(
2346
2366
  captureFull = true;
2347
2367
  step.events.push({ t, type: "info", text: `capture: this step recorded ${Math.round(capturedChars / 1000)}k characters of tool content — the rest of its calls keep only their names, sizes and times` });
2348
2368
  }
2349
- if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(path.resolve(agentDir, "..", ".."), runId, extra.call, text, io, redact, singleWorkspace() ? undefined : { tenant, workspace: path.basename(path.resolve(agentDir, "..", "..")) })) {
2369
+ if (runId && extra.call && capture === "full" && !captureFull && recordCallIo(callsRoot, runId, extra.call, text, io, redact, sink)) {
2350
2370
  capturedChars += size;
2351
2371
  rest = { ...others, captured: true };
2352
2372
  }
@@ -3128,6 +3148,9 @@ async function runStep(
3128
3148
  ...Object.values(boundSites).flat(),
3129
3149
  // remotes: each card's own host — never one its card names.
3130
3150
  ...remoteNetworkHosts(stepRemotes),
3151
+ // A granted script tool's own `network:` — the sites its program
3152
+ // reaches (a gallery `docs` tool reaching context7.com).
3153
+ ...scriptSpecs.flatMap((sc) => sc.network ?? []),
3131
3154
  ],
3132
3155
  });
3133
3156
  grant.network = { level: network.level, hosts: network.hosts };
@@ -6825,6 +6848,23 @@ export function skillsInScope(agentDir: string, tenant: string): DiscoveredSkill
6825
6848
  // The account library keeps its relative path: `account/` is expanded by
6826
6849
  // the file tools only, and a skill's bundled scripts are run from the shell.
6827
6850
  add(path.join(libraryDir(tenant)), "../../../../library/");
6851
+ // Then the platform's gallery: the skills foldrun ships to every account,
6852
+ // under the account library's path, because that is where a sandbox has
6853
+ // them (the staging step lays the gallery down beneath the library) and,
6854
+ // with no sandbox, the file tools serve that path from the shelf
6855
+ // (confine.ts gallerySkillFile). The account's own copy of a name wins.
6856
+ // The prefix is the library's place relative to this agent: the same
6857
+ // `../../../../library/` a sandbox stages in an account folder, and
6858
+ // `../../library/` in a flat single-workspace folder (Codex review).
6859
+ const gallery = platform.galleryDir();
6860
+ if (gallery) {
6861
+ const lib = `${path.relative(agentDir, libraryDir(tenant)).split(path.sep).join("/")}/`;
6862
+ for (const skill of discoverSkills(gallery, "skills")) {
6863
+ if (seen.has(skill.name)) continue;
6864
+ seen.add(skill.name);
6865
+ skills.push({ ...skill, gallery: true, path: `${lib}${skill.path}`, dir: skill.dir ? `${lib}${skill.dir}` : null });
6866
+ }
6867
+ }
6828
6868
  return skills;
6829
6869
  }
6830
6870
 
@@ -24,6 +24,7 @@ import { hostSafeEnv } from "./host-env.ts";
24
24
  import { workspaceLinkEnv } from "./confine.ts";
25
25
  import { platform } from "./platform.ts";
26
26
  import { previewOrKeep, RESULT_KEEP_CHARS } from "./tool-output.ts";
27
+ import { toolSites } from "./network.ts";
27
28
 
28
29
  // A script's only clock is the `timeout:` its own tool.md declares. There
29
30
  // was a two-minute default and a ten-minute cap here; both were the
@@ -72,6 +73,10 @@ export interface ScriptSpec {
72
73
  * secret's name (a GBP reader on a GBP token): on a test run the step
73
74
  * still gets the real values. An `outward` tool in the same step wins. */
74
75
  testMode?: "allow";
76
+ /** `network: [api.example.com]` in the tool's definition — the sites its
77
+ * program reaches, added to the step's list when the tool is granted
78
+ * (network.ts toolSites). */
79
+ network?: string[];
75
80
  }
76
81
 
77
82
  export function parseScripts(raw: unknown): ScriptSpec[] {
@@ -102,6 +107,7 @@ export function parseScripts(raw: unknown): ScriptSpec[] {
102
107
  secrets: e.secrets === "proxied" ? "proxied" : undefined,
103
108
  outward: e.outward === true ? true : undefined,
104
109
  testMode: e.test_mode === "allow" ? "allow" : undefined,
110
+ ...(toolSites(e.network).length ? { network: toolSites(e.network) } : {}),
105
111
  timeout: Number.isFinite(timeout) && timeout > 0 ? timeout : undefined,
106
112
  });
107
113
  }