@foldrun/core 18.3.2 → 18.5.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/src/runner.ts CHANGED
@@ -126,6 +126,7 @@ import { NEWER_ACTIONS, resolveActionApi } from "./web-actions.ts";
126
126
  import { resolveLanguage, languageName, type LanguageChoice } from "./language.ts";
127
127
  import { resolveRegion, deriveLocale, localeProse, regionName, type RegionChoice, type LocaleFacts } from "./locale.ts";
128
128
  import { trimChars } from "./paths.ts";
129
+ import { earlierTurns, conversationBlock, type RunContext, type RunInput } from "./conversation.ts";
129
130
  import { resolveClock, localDate, type ClockChoice } from "./clock.ts";
130
131
 
131
132
  export { localDate } from "./clock.ts";
@@ -136,7 +137,7 @@ export { localDate } from "./clock.ts";
136
137
  /** Remote MCP servers with each bound secret's value put back as its
137
138
  * `${NAME}`, granted to that server's host — the sandbox then holds the
138
139
  * name and the proxy fills it, as for an http tool. */
139
- function unbindMcpHeaders(
140
+ export function unbindMcpHeaders(
140
141
  servers: Record<string, McpServerConfig>,
141
142
  bound: string[],
142
143
  values: Record<string, string>,
@@ -145,34 +146,80 @@ function unbindMcpHeaders(
145
146
  const known = Object.fromEntries(bound.filter((n) => n in values).map((n) => [n, values[n]]));
146
147
  const out: Record<string, McpServerConfig> = {};
147
148
  for (const [name, server] of Object.entries(servers)) {
148
- if (server.type !== "http" || !server.headers) {
149
+ if (server.type !== "http") {
149
150
  out[name] = server;
150
151
  continue;
151
152
  }
152
153
  const host = hostOf(server.url);
154
+ const tpl = MCP_TEMPLATES.get(server);
155
+ if (host && tpl) {
156
+ // From the server's own text, not by finding values in it (FOL-160,
157
+ // Codex): a bound name stays ${NAME} — granted to this host for the
158
+ // proxy to fill — however short its value; every other name is filled
159
+ // exactly as mcpConfig filled it.
160
+ const render = (text: string) =>
161
+ text.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (whole, n: string) => {
162
+ if (n in known) {
163
+ addGrant(grant, n, known[n]!, host);
164
+ return whole;
165
+ }
166
+ return getSecret(tpl.tenant, n, tpl.workspace)?.value ?? whole;
167
+ });
168
+ // The address itself — scheme and host — must stay routable: a bound
169
+ // secret there would leave the sandbox a URL it cannot call, and filling
170
+ // it would send the secret in. Refused, saying where it may go (Codex).
171
+ const origin = /^[^:/?#]*:\/\/[^/?#]*/.exec(tpl.url)?.[0] ?? tpl.url;
172
+ const inOrigin = placeholderNames(origin).filter((n) => n in known);
173
+ if (inOrigin.length) {
174
+ throw new Error(`MCP server ${name}: ${inOrigin.join(", ")} is bound to sites and names part of the server's address — bind it to the server's host and put it in a header or the URL's path or query`);
175
+ }
176
+ out[name] = { ...server, url: render(tpl.url), headers: Object.fromEntries(Object.entries(tpl.headers).map(([k, v]) => [k, render(v)])) };
177
+ continue;
178
+ }
179
+ // A config made elsewhere (no template): put each bound value back by value.
153
180
  out[name] = host
154
- ? { ...server, headers: Object.fromEntries(Object.entries(server.headers).map(([k, v]) => [k, unsubstitute(v, known, host, grant)])) }
181
+ ? {
182
+ ...server,
183
+ url: unsubstitute(server.url, known, host, grant),
184
+ ...(server.headers ? { headers: Object.fromEntries(Object.entries(server.headers).map(([k, v]) => [k, unsubstitute(v, known, host, grant)])) } : {}),
185
+ }
155
186
  : server;
156
187
  }
157
188
  return out;
158
189
  }
159
190
 
160
- function mcpConfig(spec: McpSpec, tenant: string, workspace: string): McpServerConfig {
191
+ function remembered(cfg: McpServerConfig, tpl: { url: string; headers: Record<string, string>; tenant: string; workspace: string }): McpServerConfig {
192
+ MCP_TEMPLATES.set(cfg, tpl);
193
+ return cfg;
194
+ }
195
+
196
+ /** The secrets a remote MCP server names in its URL and headers. */
197
+ function mcpSecretNames(spec: McpSpec): string[] {
198
+ return spec.url ? [...placeholderNames(spec.url), ...Object.values(spec.headers ?? {}).flatMap(placeholderNames)] : [];
199
+ }
200
+
201
+ /** A remote server's config → the text it was filled from, so a bound secret
202
+ * is put back by NAME (unbindMcpHeaders), never found by its value. */
203
+ const MCP_TEMPLATES = new WeakMap<McpServerConfig, { url: string; headers: Record<string, string>; tenant: string; workspace: string }>();
204
+
205
+ export function mcpConfig(spec: McpSpec, tenant: string, workspace: string): McpServerConfig {
206
+ const fillOne = (v: string) =>
207
+ v.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (whole, secretName) => {
208
+ const hit = getSecret(tenant, secretName, workspace);
209
+ return hit ? hit.value : whole;
210
+ });
161
211
  const fill = (values: Record<string, string>) => {
162
212
  const out: Record<string, string> = {};
163
- for (const [k, v] of Object.entries(values)) {
164
- out[k] = v.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (whole, secretName) => {
165
- const hit = getSecret(tenant, secretName, workspace);
166
- return hit ? hit.value : whole;
167
- });
168
- }
213
+ for (const [k, v] of Object.entries(values)) out[k] = fillOne(v);
169
214
  return out;
170
215
  };
171
216
  // alwaysLoad: the SDK defers MCP tools behind tool search by default, which
172
217
  // hides them from an agent whose toolset we've already narrowed. A server
173
218
  // the author explicitly granted should be present from turn one.
174
219
  return spec.url
175
- ? { type: "http", url: spec.url, headers: fill(spec.headers), alwaysLoad: true }
220
+ ? // ${NAME} in the URL as in the headers (FOL-160); a site-bound one goes
221
+ // back to its name for the egress proxy (unbindMcpHeaders).
222
+ remembered({ type: "http", url: fillOne(spec.url), headers: fill(spec.headers), alwaysLoad: true }, { url: spec.url, headers: spec.headers, tenant, workspace })
176
223
  : {
177
224
  type: "stdio",
178
225
  command: spec.command!,
@@ -1190,6 +1237,10 @@ export function agentContext(
1190
1237
  // Does any granted tool act outside the workspace (`outward: true`)? The
1191
1238
  // retry policy reads it: see launchStep.
1192
1239
  let outward = false;
1240
+ // The secrets a REMOTE MCP server names in its URL or headers (FOL-160,
1241
+ // Codex): resolved and checked for site bindings as an API's are, so a
1242
+ // bound one is put back by name and filled by the proxy, never sent in.
1243
+ const mcpSecretRefs: string[] = [];
1193
1244
  const grantOwnTool = (name: string) => {
1194
1245
  const def = available[name];
1195
1246
  if (!def) {
@@ -1208,6 +1259,7 @@ export function agentContext(
1208
1259
  else {
1209
1260
  mcpServers[def.name] = mcpConfig(def.spec, tenant, workspace);
1210
1261
  mcpNames.push(def.name);
1262
+ mcpSecretRefs.push(...mcpSecretNames(def.spec));
1211
1263
  }
1212
1264
  };
1213
1265
 
@@ -1220,6 +1272,7 @@ export function agentContext(
1220
1272
  if (def?.kind === "mcp") {
1221
1273
  mcpServers[name] = mcpConfig(def.spec, tenant, workspace);
1222
1274
  mcpNames.push(name);
1275
+ mcpSecretRefs.push(...mcpSecretNames(def.spec));
1223
1276
  }
1224
1277
  }
1225
1278
  }
@@ -1315,7 +1368,7 @@ export function agentContext(
1315
1368
  ];
1316
1369
  // One name once, however many places asked for it.
1317
1370
  declared.splice(0, declared.length, ...new Set(declared));
1318
- const referenced = [...new Set(apis.flatMap(secretsUsedByApi))];
1371
+ const referenced = [...new Set([...apis.flatMap(secretsUsedByApi), ...mcpSecretRefs])];
1319
1372
  // A remote's secret travels with the remote, as an API's does: naming it
1320
1373
  // under remotes: is enough. One nothing else in the step uses is resolved
1321
1374
  // apart, into remoteSecretEnv, and reaches the a2a tools alone — never
@@ -2065,6 +2118,11 @@ async function notifyQuestion(tenant: string, workspace: string, runId: string,
2065
2118
  headline: `${agent} is asking you something`,
2066
2119
  detail: `${question}${options?.length ? `\n\nOptions: ${options.join(" · ")}` : ""}\n\nAnswer it on ${where}, or \`foldrun answer ${runId} "…"\`.`,
2067
2120
  runId,
2121
+ }, {
2122
+ // A webhook tells a question from a gate (FOL-159), and `events: [asking]`
2123
+ // subscribes to questions alone; awaiting-approval keeps getting them.
2124
+ asking: true,
2125
+ extra: { reason: "question", question: { text: question, ...(options?.length ? { options } : {}), agent } },
2068
2126
  }).catch(() => false);
2069
2127
  }
2070
2128
 
@@ -2167,6 +2225,10 @@ async function runStep(
2167
2225
  * mayDefer). Absent: it waits here, however long — a rescue, a step
2168
2226
  * outside a flow, a foreground run. */
2169
2227
  mayDefer?: () => boolean,
2228
+ /** FOL-162: the earlier turns of the run's conversation, as the block
2229
+ * conversation.ts built — read before the instruction. Already escaped;
2230
+ * never resolved for [[links]] (it is other runs' words). */
2231
+ conversation?: string,
2170
2232
  ) {
2171
2233
  // Secret values are injected into scripts as environment variables and
2172
2234
  // substituted into API headers, so a model that reads one back — from a
@@ -2303,6 +2365,8 @@ async function runStep(
2303
2365
  // The ceiling it was given rides on the line, so the budget arithmetic
2304
2366
  // around fan-out is testable without a model to stop.
2305
2367
  push("info", `stub call ${call + 1}${stepBudgetUsd !== null ? ` (ceiling $${stepBudgetUsd.toFixed(2)})` : ""}`);
2368
+ // What a real step would have read before its instruction (FOL-162).
2369
+ if (conversation) push("info", `stub conversation: ${conversation}`);
2306
2370
  step.status = "completed";
2307
2371
  // A stub answer may open with `cost: 0.25` — a pretend price, so the
2308
2372
  // parts of orchestration that watch money (budget:) are testable too.
@@ -2722,6 +2786,9 @@ async function runStep(
2722
2786
  let prompt = step.instruction
2723
2787
  ? resolveDocLinks(step.instruction, workspaceRoot)
2724
2788
  : "Begin your run now, following your instructions.";
2789
+ // The conversation's earlier turns go first, the request after them —
2790
+ // in the user turn, not the system prompt (conversation.ts says why).
2791
+ if (conversation) prompt = `${conversation}\n\n${prompt}`;
2725
2792
  if (context) prompt += `\n\n<previous_step_results>\n${context.slice(0, CONTEXT_CHARS)}\n</previous_step_results>`;
2726
2793
  if (priorData !== undefined) {
2727
2794
  // The value itself, beside the prose that mentioned it. This is the
@@ -4522,6 +4589,10 @@ export function createFlowRun(
4522
4589
  /** A snapshot run's folder (Part B3): the id POST …/snapshots answered.
4523
4590
  * Its own trailing argument, as a2a is, so the signature only widened. */
4524
4591
  snapshot?: string,
4592
+ /** FOL-162: the conversation this run is a turn of, and what it was
4593
+ * asked — written with the record, before any worker can see it. The
4594
+ * run's first step (the one its task reaches) reads the earlier turns. */
4595
+ conversation?: { context: RunContext; input?: RunInput },
4525
4596
  ): RunRecord {
4526
4597
  let flowMaxOut: number | undefined;
4527
4598
  try {
@@ -4585,6 +4656,11 @@ export function createFlowRun(
4585
4656
  costUsd: null,
4586
4657
  })),
4587
4658
  };
4659
+ if (conversation?.context) {
4660
+ run.context = conversation.context;
4661
+ if (conversation.input) run.input = conversation.input;
4662
+ if (run.steps[0]) run.steps[0].conversationTurn = true;
4663
+ }
4588
4664
  writeRun(tenant, workspace, run);
4589
4665
 
4590
4666
  // Start every run from an empty outputs/ for each agent it will touch.
@@ -5679,6 +5755,32 @@ function driveRunInner(
5679
5755
  // of its group is under way (a sibling still running keeps the run
5680
5756
  // here anyway), and only once the group has waited a while, so a
5681
5757
  // short wait stays a short wait. Never on a foreground run.
5758
+ // FOL-162: the earlier turns of the run's conversation, for the step
5759
+ // the run's task reaches. Read fresh at each start (a retry, a
5760
+ // resume) — the same turns each time, since which runs count is
5761
+ // fixed by when this run was made. A lookup that fails costs the
5762
+ // step its history, never the step.
5763
+ const conversationFor = (step: StepRecord): string | undefined => {
5764
+ if (!step.conversationTurn || !run.context) return undefined;
5765
+ try {
5766
+ const built = conversationBlock(run, earlierTurns(tenant, workspace, run));
5767
+ if (!built) {
5768
+ delete step.history;
5769
+ return undefined;
5770
+ }
5771
+ step.history = built.record;
5772
+ const r = built.record;
5773
+ step.events.push({
5774
+ t: new Date().toISOString(),
5775
+ type: "info",
5776
+ text: `conversation ${run.context.id}: given ${r.runs.length} earlier run${r.runs.length === 1 ? "" : "s"} (${r.chars.toLocaleString("en")} characters)${r.omitted ? `, ${r.omitted} older not given` : ""}${r.truncated ? `, ${r.truncated} cut short` : ""}`,
5777
+ });
5778
+ return built.text;
5779
+ } catch (err) {
5780
+ step.events.push({ t: new Date().toISOString(), type: "info", text: `conversation ${run.context.id}: the earlier runs could not be read (${err instanceof Error ? err.message : String(err)}) — this step runs without them` });
5781
+ return undefined;
5782
+ }
5783
+ };
5682
5784
  const mayDefer = (step: StepRecord) => () => {
5683
5785
  if (!opts.parkOnApproval) return false;
5684
5786
  if (launching.some((s) => s !== step && s.status === "running" && !s.roomWait)) return false;
@@ -5818,6 +5920,7 @@ function driveRunInner(
5818
5920
  peerBus,
5819
5921
  delegateFor(step),
5820
5922
  mayDefer(step),
5923
+ conversationFor(step),
5821
5924
  ).finally(() => reserved.delete(step));
5822
5925
  // Sent back for room: not a try. The run parks once the
5823
5926
  // group is done (below) and this attempt starts again later.
@@ -6006,7 +6109,7 @@ function driveRunInner(
6006
6109
  resumed.attempts = Math.max(1, resumed.attempts ?? 0);
6007
6110
  resumed.status = "running";
6008
6111
  save();
6009
- await runStep(rescuerDir, tenant, resumed, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(resumed));
6112
+ await runStep(rescuerDir, tenant, resumed, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(resumed), [], undefined, undefined, undefined, conversationFor(resumed));
6010
6113
  settleRescue(step, resumed);
6011
6114
  return;
6012
6115
  }
@@ -6049,6 +6152,8 @@ function driveRunInner(
6049
6152
  // medium-desk).
6050
6153
  output: step.output,
6051
6154
  ...(step.verify ? { verify: step.verify } : {}),
6155
+ // Taking over the step the run's task reached: the conversation too.
6156
+ ...(step.conversationTurn ? { conversationTurn: true } : {}),
6052
6157
  attempts: 0,
6053
6158
  status: "pending",
6054
6159
  events: [],
@@ -6060,7 +6165,7 @@ function driveRunInner(
6060
6165
  rescue.attempts = 1;
6061
6166
  rescue.status = "running";
6062
6167
  save();
6063
- await runStep(rescuerDir, tenant, rescue, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(rescue));
6168
+ await runStep(rescuerDir, tenant, rescue, ctx, save, modelOverride, tags, effortOverride, run.id, ctxData, null, undefined, run.test === true, stopPoll, flowTimezone, run.steps.indexOf(rescue), [], undefined, undefined, undefined, conversationFor(rescue));
6064
6169
  settleRescue(step, rescue);
6065
6170
  };
6066
6171
  // What a rescue's end means for the step it took over.
@@ -16,10 +16,12 @@ export interface RunFilter {
16
16
  minTokens?: number;
17
17
  /** The run took at least this many seconds. */
18
18
  minSecs?: number;
19
+ /** The run is a turn of this conversation: its `context` id, exactly (FOL-162). */
20
+ context?: string;
19
21
  }
20
22
 
21
23
  /** The query parameters a filter comes from: tool, tool_error, agent,
22
- * model, min_tokens, min_secs. Unreadable numbers are refused in words. */
24
+ * model, min_tokens, min_secs, context. Unreadable numbers are refused in words. */
23
25
  export function parseRunFilter(q: { get(name: string): string | null }): { filter: RunFilter; problems: string[] } {
24
26
  const filter: RunFilter = {};
25
27
  const problems: string[] = [];
@@ -32,6 +34,8 @@ export function parseRunFilter(q: { get(name: string): string | null }): { filte
32
34
  if (agent) filter.agent = agent;
33
35
  const model = text("model");
34
36
  if (model) filter.model = model.toLowerCase();
37
+ const context = q.get("context");
38
+ if (context) filter.context = context;
35
39
  for (const [k, field] of [["min_tokens", "minTokens"], ["min_secs", "minSecs"]] as const) {
36
40
  const v = text(k);
37
41
  if (v === undefined) continue;
@@ -57,7 +61,7 @@ type FilterableStep = {
57
61
  startedAt?: string;
58
62
  finishedAt?: string;
59
63
  };
60
- type FilterableRun = { startedAt: string; finishedAt?: string | null; steps: FilterableStep[] };
64
+ type FilterableRun = { startedAt: string; finishedAt?: string | null; context?: { id: string }; steps: FilterableStep[] };
61
65
 
62
66
  /** The index's facts, or worked out from a whole record's events (Codex
63
67
  * review: the workspace runs page reads whole records). */
@@ -74,6 +78,7 @@ function factsOf(s: FilterableStep): { tools: string[]; toolErrors: number } {
74
78
  }
75
79
 
76
80
  export function matchesRunFilter(run: FilterableRun, f: RunFilter, now = Date.now()): boolean {
81
+ if (f.context !== undefined && run.context?.id !== f.context) return false;
77
82
  const steps = (run.steps ?? []).map((s) => ({ ...s, ...factsOf(s) }));
78
83
  if (f.tool && !steps.some((s) => (s.tools ?? []).some((t) => t.toLowerCase().includes(f.tool!)))) return false;
79
84
  if (f.toolError !== undefined && steps.some((s) => (s.toolErrors ?? 0) > 0) !== f.toolError) return false;
package/src/store.ts CHANGED
@@ -71,6 +71,7 @@ import { readTransport, KINDS } from "./kinds.ts";
71
71
  import { providerPreset, looksOpenAiShaped, PROTECTED_PARAMS, type WireFormat, type AuthShape } from "./providers.ts";
72
72
  import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.ts";
73
73
  import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.ts";
74
+ import type { RunContext, RunInput, ConversationRecord } from "./conversation.ts";
74
75
 
75
76
  // Where workspaces live. The hosted app keeps many under data/; the CLI runs
76
77
  // against one folder, which is what `foldrun run ./my-desk` has to mean.
@@ -3794,6 +3795,14 @@ export interface StepRecord {
3794
3795
  delegation?: string;
3795
3796
  /** On a step that delegated to isolated sub-agents: each job, in order. */
3796
3797
  delegations?: StepDelegation[];
3798
+ /** FOL-162: this step reads the run's conversation — the earlier runs of
3799
+ * its `context` — before its instruction. Set when the run is made on
3800
+ * the step the run's task reaches (its fan-out instances and an on-fail
3801
+ * rescue of it inherit it; a re-run sets it on the first step it runs). */
3802
+ conversationTurn?: boolean;
3803
+ /** What that step was given, written when it starts: which runs, how many
3804
+ * did not fit, and a hash of the block (conversation.ts). Never the text. */
3805
+ history?: ConversationRecord;
3797
3806
  /** On an isolated sub-agent's run: the workspace paths its sandbox's
3798
3807
  * changes were applied to — what its delegating step is told it wrote. */
3799
3808
  wrote?: string[];
@@ -4007,6 +4016,14 @@ export interface RunRecord {
4007
4016
  * changed is outputs/snapshot.patch. Set when the run is made, never by a
4008
4017
  * step. */
4009
4018
  snapshot?: { id: string };
4019
+ /** FOL-162: the conversation this run belongs to — the id its caller
4020
+ * gave and the key it is found by (conversation.ts). Set when the run
4021
+ * is made, carried onto a re-run. */
4022
+ context?: RunContext;
4023
+ /** What the run was asked, as given: the task of an agent or flow run,
4024
+ * an A2A message's text and data. Kept on a run with a `context`, so a
4025
+ * later turn reads the question, never a step's decorated instruction. */
4026
+ input?: RunInput;
4010
4027
  steps: StepRecord[];
4011
4028
  }
4012
4029
 
@@ -4409,6 +4426,8 @@ export interface RunSummary {
4409
4426
  /** RunRecord.trigger and .a2a: an outside agent started it. */
4410
4427
  trigger?: "a2a";
4411
4428
  a2a?: { task: string; key: string };
4429
+ /** RunRecord.context: the conversation it belongs to (FOL-162). */
4430
+ context?: RunContext;
4412
4431
  steps: RunSummaryStep[];
4413
4432
  }
4414
4433
 
@@ -4453,6 +4472,7 @@ export function summarizeRun(run: RunRecord): RunSummary {
4453
4472
  ...(run.revision ? { revision: run.revision } : {}),
4454
4473
  ...(run.trigger ? { trigger: run.trigger } : {}),
4455
4474
  ...(run.a2a ? { a2a: run.a2a } : {}),
4475
+ ...(run.context ? { context: run.context } : {}),
4456
4476
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
4457
4477
  steps: run.steps.map((s) => {
4458
4478
  // A failed step's last error — and, on a run that failed between