@foldrun/core 22.0.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.
@@ -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
@@ -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
@@ -392,6 +392,9 @@ export interface DiscoveredSkill {
392
392
  /** The rest of the Agent Skills layout: references/ and assets/. */
393
393
  hasReferences: boolean;
394
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;
395
398
  }
396
399
 
397
400
  const toTags = (v: unknown): string[] =>
@@ -817,8 +820,11 @@ export function applicableSkills<T extends { name: string; when: string[] }>(
817
820
  only: string[],
818
821
  tags: string[],
819
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.
820
826
  return skills
821
- .filter((s) => only.length === 0 || only.includes(s.name))
827
+ .filter((s) => (only.length === 0 ? !(s as { gallery?: boolean }).gallery : only.includes(s.name)))
822
828
  .filter((s) => s.when.length === 0 || s.when.some((t) => tags.includes(t)));
823
829
  }
824
830
 
@@ -1078,7 +1084,9 @@ export function agentContext(
1078
1084
  // it's an allowlist, which is how you keep a focused agent focused.
1079
1085
  const only: string[] = refNames(front.skills);
1080
1086
  const applicable = applicableSkills(skills, only, tags);
1081
- 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;
1082
1090
 
1083
1091
  if (applicable.length) {
1084
1092
  const lines = applicable.map((s) => {
@@ -3140,6 +3148,9 @@ async function runStepBody(
3140
3148
  ...Object.values(boundSites).flat(),
3141
3149
  // remotes: each card's own host — never one its card names.
3142
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 ?? []),
3143
3154
  ],
3144
3155
  });
3145
3156
  grant.network = { level: network.level, hosts: network.hosts };
@@ -6837,6 +6848,23 @@ export function skillsInScope(agentDir: string, tenant: string): DiscoveredSkill
6837
6848
  // The account library keeps its relative path: `account/` is expanded by
6838
6849
  // the file tools only, and a skill's bundled scripts are run from the shell.
6839
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
+ }
6840
6868
  return skills;
6841
6869
  }
6842
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
  }
package/src/starter.ts CHANGED
@@ -502,9 +502,9 @@ model: default # fast | default | max
502
502
  effort: low # how hard to think about it
503
503
  size: large # small | large | heavy — the sandbox it rents
504
504
  resources: { memory: 4Gi } # optional: cpu, memory, disk in numbers, over the size class
505
- tools: [web, read, ask, peers, text, my-folder-tool] # built-ins and your own tools/, one list; \`ask\` lets it ask you mid-step, \`peers\` lets it message the steps running beside it, \`text\` reads images, PDFs, office files and recordings as text
505
+ tools: [web, read, ask, peers, text, my-folder-tool] # built-ins and your own tools/, one list; \`ask\` lets it ask you mid-step, \`peers\` lets it message the steps running beside it, \`text\` reads images, PDFs, office files and recordings as text, \`docs\` reads a library's current docs, \`video\` renders Remotion video
506
506
  disallowedTools: [Bash] # subtract from what it would otherwise have
507
- skills: [house-style] # from skills/
507
+ skills: [house-style] # from skills/, the library, or the platform's gallery (modern-website, motion-video, cloudhost-deploy — by name only)
508
508
  hooks: [no-force-push] # from hooks/ or the library: code at every tool call
509
509
  scripts: [summarise.py] # from scripts/, each becomes a callable tool
510
510
  apis: [{ name: crm }] # an HTTP API, as a tool
package/src/store.ts CHANGED
@@ -60,7 +60,7 @@ import { parseBudget, budgetProblem } from "./budget.ts";
60
60
  import { explainFailure, failureFactsOf, type FailureExplained, type FailureFacts } from "./failure.ts";
61
61
  import { timezoneProblem } from "./clock.ts";
62
62
  import { parseStepLimits, readLimits } from "./limits.ts";
63
- import { networkEnforceWanted, networkProblems, resolveNetwork, type NetworkPolicy } from "./network.ts";
63
+ import { networkEnforceWanted, networkProblems, resolveNetwork, toolSites, type NetworkPolicy } from "./network.ts";
64
64
  import { browseVendorOf } from "./browse-egress.ts";
65
65
  import { searchProvided, type SearchingAction } from "./search-egress.ts";
66
66
  import { webProblems, webWarnings, runnerEngines, webConfig } from "./providers.ts";
@@ -1664,6 +1664,22 @@ export function listAgents(tenant: string, workspace: string): AgentInfo[] {
1664
1664
  };
1665
1665
  const accountFront = frontOf(path.join(accountDir(tenant), "AGENTS.md"));
1666
1666
  const workspaceFront = frontOf(path.join(workspaceDir(tenant, workspace), "AGENTS.md"));
1667
+ // The sites each tool's own definition names (`network:` in its tool.md),
1668
+ // nearest copy wins — the gallery's, the account library's, the
1669
+ // workspace's — read once for every agent below, as the runner reads them.
1670
+ let toolSiteMap: Record<string, string[]> | null = null;
1671
+ const sitesOfTools = (names: string[]): string[] => {
1672
+ if (!toolSiteMap) {
1673
+ const gallery = platform.galleryDir();
1674
+ const defs = {
1675
+ ...(gallery ? readToolDir(path.join(gallery, "tools"), "account") : {}),
1676
+ ...readToolDir(path.join(dataRoot(), tenant, "library", "tools"), "account"),
1677
+ ...workspaceTools(tenant, workspace),
1678
+ };
1679
+ toolSiteMap = Object.fromEntries(Object.entries(defs).map(([n, d]) => [n, d.kind === "script" ? toolSites((d.spec as { network?: unknown }).network) : []]));
1680
+ }
1681
+ return names.flatMap((n) => toolSiteMap![n] ?? []);
1682
+ };
1667
1683
  return fs
1668
1684
  .readdirSync(dir)
1669
1685
  .filter((n) => fs.existsSync(path.join(dir, n, "agent.md")))
@@ -1693,6 +1709,8 @@ export function listAgents(tenant: string, workspace: string): AgentInfo[] {
1693
1709
  ...parseApis(data.apis).map((a) => { try { return new URL(a.base).host; } catch { return ""; } }),
1694
1710
  // remotes: — each card's own host, and nothing its card says.
1695
1711
  ...remoteNetworkHosts(parseRemotes(data.remotes)),
1712
+ // Each granted script tool's own network: list.
1713
+ ...sitesOfTools(ownToolNames(data)),
1696
1714
  ],
1697
1715
  }),
1698
1716
  readsWeb,