@crewhaus/runtime-core 0.8.0 → 0.8.1

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/dist/index.d.ts CHANGED
@@ -1293,9 +1293,10 @@ export type RunChatLoopOptions = {
1293
1293
  * in-run ledger ({@link CONTINUITY_LEDGER_MAX_CHARS} cap, oldest-first
1294
1294
  * eviction), which re-injects on every model call — the user's answer
1295
1295
  * survives any number of compactions regardless of summary quality.
1296
- * Evicted assistant text and tool findings are also persisted as
1297
- * `context_evicted` events (episodic externalization for a later
1298
- * recall integration). `--resume` rebuilds the ledger from the logged
1296
+ * Evicted assistant text, tool findings and runtime-authored turns
1297
+ * (logged `synthetic: true`) are also persisted as `context_evicted`
1298
+ * events (episodic externalization for a later recall integration) and
1299
+ * stay out of the ledger. `--resume` rebuilds the ledger from the logged
1299
1300
  * events. The autocompact summarizer's prompt receives the ledger text
1300
1301
  * as an anchor, but nothing depends on the summary being right.
1301
1302
  * - `onHandoff` fires ONCE at teardown (the same finally slot as
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ import { claimReasons, isProvabilityLevel, summarizeBundle, unverifiedBundle, }
22
22
  import { createRateLimiter } from "@crewhaus/rate-limiter";
23
23
  import { BUILTIN_FAILURE_CLASSES, advanceState, initialRecoveryState, recover, } from "@crewhaus/recovery-engine";
24
24
  import { SHADOW_LANE_PRIMARY_ARM, SHADOW_LANE_SHADOW_ARM, computeReward, freezeScoreboard, openScoreboard, readRouteFreeze, readRoutingPriorsRaw, routingPriorsPath, shadowLaneQuality, shadowRouteKey, } from "@crewhaus/routing-store";
25
- import { createRunContext, tagContent } from "@crewhaus/run-context";
25
+ import { DATA_LINEAGE_CAP, createRunContext, tagContent, } from "@crewhaus/run-context";
26
26
  import { createSessionStore, evictExpiredApprovals, generateApprovalId, hashApprovalInput, mergeSessionModels, resolveSessionPin, } from "@crewhaus/session-store";
27
27
  import { formatSkillsForPrompt } from "@crewhaus/skills-registry";
28
28
  import { expand as expandSlash } from "@crewhaus/slash-commands";
@@ -37,6 +37,7 @@ import { executeTool, operativeValuesFor, preparePermissionSubject } from "@crew
37
37
  import { detectLoop } from "@crewhaus/tool-loop-detection";
38
38
  import { partitionToolCalls } from "@crewhaus/tool-orchestrator";
39
39
  import { storeAndPreview } from "@crewhaus/tool-result-store";
40
+ import { homeHeldBy } from "@crewhaus/tool-safety/fs";
40
41
  import { AUXILIARY_MODEL_ROLES, TraceEventBus, } from "@crewhaus/trace-event-bus";
41
42
  import { initialState, transition, } from "@crewhaus/turn-state-machine";
42
43
  import { zodToJsonSchema } from "zod-to-json-schema";
@@ -53,7 +54,7 @@ import { placeRecordingCanonicalizer } from "./path-canonical";
53
54
  import { describeHintEvidence, isSyntheticMessage, latestHumanUserMessage, markSynthetic, messageText, preRoute, stripDirectiveFromMessage, } from "./pre-route";
54
55
  import { loadProjectMemory } from "./project-memory";
55
56
  import { createCliOutput, isSpinnerEnabled } from "./spinner";
56
- import { runtimeStateRoots } from "./state-roots";
57
+ import { credentialFileRoots, credentialFloorScope, relocatingFieldLeftOut, runtimeRecordRoots, runtimeStateRoots, } from "./state-roots";
57
58
  import { checkServingToolLimits, unreportedToolLimitLines, } from "./tool-limit";
58
59
  /**
59
60
  * Slice-scope runtime: a multi-turn streaming chat loop with prompt
@@ -665,6 +666,14 @@ export function sanitizeOrphanToolUses(messages) {
665
666
  }
666
667
  return { messages: out, removed };
667
668
  }
669
+ /**
670
+ * A line the runtime wrote to a session log: `appendEvent`'s version and an
671
+ * object payload. The readers that rebuild a run count only these, so anything
672
+ * else in the file changes nothing about the replay.
673
+ */
674
+ function isRuntimeLogLine(ev) {
675
+ return ev.version === 1 && typeof ev.payload === "object" && ev.payload !== null;
676
+ }
668
677
  /**
669
678
  * Walk an `EventLog` and reconstruct the SDK message history. Only
670
679
  * `user_message` and `assistant_message` events contribute — `tool_use`
@@ -688,6 +697,8 @@ export async function replayMessageHistory(log) {
688
697
  // surface user/assistant events at depth 0.
689
698
  let depth = 0;
690
699
  for await (const ev of log.read()) {
700
+ if (!isRuntimeLogLine(ev))
701
+ continue;
691
702
  if (ev.kind === "a2a_turn_start" || ev.kind === "sub_agent_start") {
692
703
  depth += 1;
693
704
  continue;
@@ -730,6 +741,50 @@ export async function replayMessageHistory(log) {
730
741
  // request. Drop such orphans so `--resume` self-heals. No-op on healthy logs.
731
742
  return sanitizeOrphanToolUses(messages).messages;
732
743
  }
744
+ /**
745
+ * The egress check reads a run's lineage, and a run resumed from its log should
746
+ * read the same lineage it had. Each tool result is tagged at `tool`, including
747
+ * one from a tool that sets `classifyOutput: false`, so a verbatim copy of it
748
+ * meets the egress check as a tool result does within one run. Oldest first, so
749
+ * the lineage cap keeps the newest, and only the newest `DATA_LINEAGE_CAP`
750
+ * results, since a long session replays its whole history; a result gives at
751
+ * least one piece unless it is too short to match. What the caller tagged
752
+ * before the run, such as the message that started it, is newer than anything
753
+ * replayed and stays newest.
754
+ */
755
+ function tagReplayedToolResults(runContext, messages) {
756
+ const replayed = [];
757
+ for (const message of messages) {
758
+ if (message.role !== "user" || typeof message.content === "string")
759
+ continue;
760
+ for (const block of message.content) {
761
+ if (block.type !== "tool_result")
762
+ continue;
763
+ const content = block.content;
764
+ const text = typeof content === "string"
765
+ ? content
766
+ : (content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("\n");
767
+ if (text.length > 0)
768
+ replayed.push(text);
769
+ }
770
+ }
771
+ const held = [...(runContext.dataLineage ?? [])];
772
+ for (const text of replayed.slice(-DATA_LINEAGE_CAP))
773
+ tagContent(runContext, text, "tool");
774
+ const lineage = runContext.dataLineage;
775
+ if (lineage === undefined)
776
+ return;
777
+ for (const [piece, origin] of held) {
778
+ lineage.delete(piece);
779
+ lineage.set(piece, origin);
780
+ }
781
+ while (lineage.size > DATA_LINEAGE_CAP) {
782
+ const oldest = lineage.keys().next().value;
783
+ if (oldest === undefined)
784
+ break;
785
+ lineage.delete(oldest);
786
+ }
787
+ }
733
788
  /**
734
789
  * 0.8.0 (design/0.8.0-provability-release.md §5.3) — how many turns a
735
790
  * replayed transcript (`replayMessageHistory`) already holds: its user
@@ -1095,6 +1150,15 @@ function reportToolLimits(verdict) {
1095
1150
  process.stderr.write(`[tools] ${line}\n`);
1096
1151
  }
1097
1152
  }
1153
+ /** One `[workspace]` line on stderr when the working directory holds the home directory, once per process. */
1154
+ function reportWorkspaceHoldsHome() {
1155
+ const cwd = process.cwd();
1156
+ if (homeHeldBy(cwd, process.env) === undefined)
1157
+ return;
1158
+ const line = `this harness runs in ${cwd}, which holds your home directory. A harness's tools work inside its directory, so give it a directory of its own.`;
1159
+ for (const fresh of unreportedToolLimitLines([line]))
1160
+ process.stderr.write(`[workspace] ${fresh}\n`);
1161
+ }
1098
1162
  /**
1099
1163
  * Item 3 (G32) — merge plugin-contributed tools into the run's advertised tool
1100
1164
  * set. First-party `base` tools WIN any name collision, so an activated plugin
@@ -1353,6 +1417,13 @@ function withoutNarration(text, echo) {
1353
1417
  .trim();
1354
1418
  }
1355
1419
  export async function runChatLoop(opts) {
1420
+ // A `channel` or `managed` run answers people other than its operator, so it
1421
+ // and the loops it starts (a sub-agent, a consult) share one scope, and each
1422
+ // keeps the credential files from its tools (`./state-roots`).
1423
+ if ((opts.sessionTarget === "channel" || opts.sessionTarget === "managed") &&
1424
+ credentialFloorScope.getStore() !== true) {
1425
+ return credentialFloorScope.run(true, () => runChatLoop(opts));
1426
+ }
1356
1427
  // Item 3 (G32) — resolve the advertised tool set ONCE, up front, folding in
1357
1428
  // any plugin-contributed tools so the tool-capable-model feature gate and the
1358
1429
  // per-turn advertisement below read the same list.
@@ -1635,19 +1706,25 @@ export async function runChatLoop(opts) {
1635
1706
  if (opts.sideCalls?.committee !== undefined && opts.singleTurn !== true) {
1636
1707
  throw new RuntimeError("runChatLoop: `sideCalls.committee` is legal in singleTurn mode only (a workflow step, a graph node, a crew role) — a REPL or per-message turn is one the user is waiting on");
1637
1708
  }
1709
+ reportWorkspaceHoldsHome();
1638
1710
  const sessionRootDir = resolveSessionRootDir(opts.sessionRootDir);
1639
1711
  // 0.8.0 (design §1 principle 1, §5.2) — the session logs, the spilled
1640
1712
  // tool results and the proof bundles this run's gates read as evidence: no
1641
1713
  // tool call the agent makes may write there, whatever a rule says
1642
1714
  // (permission-engine's runtime-state floor, `./state-roots`).
1643
1715
  const protectedRoots = runtimeStateRoots(sessionRootDir, currentTenantContext()?.tenant);
1716
+ const credentialRoots = credentialFloorScope.getStore() === true ? credentialFileRoots() : undefined;
1717
+ const recordRoots = runtimeRecordRoots(sessionRootDir, currentTenantContext()?.tenant);
1644
1718
  /**
1645
1719
  * The floor's reading of a call: where it WRITES. Two kinds of field are
1646
1720
  * left out, field by field:
1647
1721
  *
1648
- * - one declared `relocates` names the store a tool works in through its
1649
- * own format (EmitTraceEvent's namespaced `custom.*` lines,
1650
- * IncidentBundle's sessions it reads whole), not a file the call names;
1722
+ * - one declared `relocates` that names a store the tool works in through
1723
+ * its own format inside the run's record (EmitTraceEvent's namespaced
1724
+ * `custom.*` lines) or in the gate record that is its own store
1725
+ * (DatasetPut's versions, EvalBaselinePin's pins), or one it reads whole
1726
+ * (IncidentBundle's sessions). A store anywhere else is read as any path
1727
+ * is (`relocatingFieldLeftOut`, `./state-roots`);
1651
1728
  * - one declared `source` holds where the tool takes a value FROM (the
1652
1729
  * files IndexBuild indexes, the file DatasetPut reads, the reference
1653
1730
  * EnvFileUpsert copies a secret out of): reading a spilled output or a
@@ -1666,16 +1743,24 @@ export async function runChatLoop(opts) {
1666
1743
  * Every other operative value counts — a secret reference's file included
1667
1744
  * (SecretRotate's `ref` names the file it writes). `undefined` ⇒ the
1668
1745
  * call's operative values as they are (a tool with neither kind of field).
1746
+ *
1747
+ * A tool that declares `[]` says no argument decides where it acts: what it
1748
+ * carries is text (a memory, a plan step, a clipboard's contents), so the
1749
+ * floor reads none of it as a path. One that declares nothing (an MCP or
1750
+ * plugin tool) says nothing, and the floor reads every string it carries.
1669
1751
  */
1670
1752
  const floorValuesOf = (tool, parsedInput) => {
1671
1753
  const args = tool.operativeArgs;
1754
+ if (args !== undefined && args.length === 0)
1755
+ return [];
1672
1756
  const named = (name) => {
1673
1757
  if (typeof parsedInput !== "object" || parsedInput === null)
1674
1758
  return false;
1675
1759
  const value = parsedInput[name];
1676
1760
  return value !== undefined && value !== null && value !== "";
1677
1761
  };
1678
- const skipped = (arg) => arg.relocates === true ||
1762
+ const skipped = (arg) => (arg.relocates === true &&
1763
+ relocatingFieldLeftOut(arg, parsedInput, recordRoots, protectedRoots)) ||
1679
1764
  arg.source === true ||
1680
1765
  arg.reads === true ||
1681
1766
  (arg.readsWhen !== undefined && named(arg.readsWhen));
@@ -1688,6 +1773,15 @@ export async function runChatLoop(opts) {
1688
1773
  canonicalizePath: placeRecordingCanonicalizer().canonicalizePath,
1689
1774
  }) ?? []);
1690
1775
  };
1776
+ /**
1777
+ * `floorValues` as a gate hands them to the engine: `floorValuesOf` for a call
1778
+ * that writes, and for a tool that declares `[]` whatever it does, since the
1779
+ * engine reads that empty list as "this call carries text" when it looks for a
1780
+ * credential file.
1781
+ */
1782
+ const gateFloorValues = (tool, parsedInput) => tool.readOnly && tool.operativeArgs?.length !== 0
1783
+ ? undefined
1784
+ : floorValuesOf(tool, parsedInput);
1691
1785
  const sessionStore = persistSession
1692
1786
  ? createSessionStore({ rootDir: sessionRootDir })
1693
1787
  : createMemorySessionStore();
@@ -2141,6 +2235,8 @@ export async function runChatLoop(opts) {
2141
2235
  // must not be mistaken for this context's previous one.
2142
2236
  let nestDepth = 0;
2143
2237
  for await (const ev of replayLog.read()) {
2238
+ if (!isRuntimeLogLine(ev))
2239
+ continue;
2144
2240
  if (ev.kind === "a2a_turn_start" || ev.kind === "sub_agent_start") {
2145
2241
  nestDepth += 1;
2146
2242
  continue;
@@ -2184,6 +2280,8 @@ export async function runChatLoop(opts) {
2184
2280
  if (!wantLedger || ev.kind !== "context_evicted")
2185
2281
  continue;
2186
2282
  const p = ev.payload;
2283
+ if (p.synthetic === true)
2284
+ continue;
2187
2285
  if (p.role === "user" && typeof p.text === "string") {
2188
2286
  resumedLedgerSeed.push({
2189
2287
  role: "user",
@@ -2225,6 +2323,8 @@ export async function runChatLoop(opts) {
2225
2323
  return createRunContext({ runId, sessionId, eventBus });
2226
2324
  })()
2227
2325
  : createRunContext({ sessionId }));
2326
+ if (resumedMessages !== undefined)
2327
+ tagReplayedToolResults(runContext, resumedMessages);
2228
2328
  // G01 — surface the max-tokens lift once, at boot (see `effectiveMaxTokens`).
2229
2329
  if (effectiveMaxTokens !== maxTokens) {
2230
2330
  runContext.logger.info("thinking budget >= max_tokens — lifting the per-request ceiling", {
@@ -2854,8 +2954,8 @@ export async function runChatLoop(opts) {
2854
2954
  // -------------------------------------------------------------------------
2855
2955
  const continuity = opts.continuity;
2856
2956
  const continuityLedgerEnabled = continuity !== undefined && continuity.ledger !== false;
2857
- // The in-run requirements ledger: evicted USER messages, oldest-first,
2858
- // verbatim. `ledgerTruncated` flags that oldest entries were dropped at
2957
+ // The in-run requirements ledger: evicted USER messages the runtime did not
2958
+ // write, oldest-first, verbatim. `ledgerTruncated` flags that oldest entries were dropped at
2859
2959
  // the CONTINUITY_LEDGER_MAX_CHARS cap so the rendered block says so.
2860
2960
  const ledgerEntries = [];
2861
2961
  let ledgerTruncated = false;
@@ -2894,19 +2994,23 @@ export async function runChatLoop(opts) {
2894
2994
  * text-bearing record is appended verbatim to the session event log as
2895
2995
  * `context_evicted` (zero model trust — the recall integration comes in a
2896
2996
  * later PR); user records additionally fold into the in-run ledger for
2897
- * per-call reinjection.
2997
+ * per-call reinjection. A turn the runtime wrote (a grader's correction, a
2998
+ * retry or loop nudge) is logged with `synthetic: true` and stays out of the
2999
+ * ledger.
2898
3000
  */
2899
3001
  const externalizeEvicted = async (evicted) => {
2900
3002
  if (!continuityLedgerEnabled)
2901
3003
  return;
2902
3004
  for (const message of evicted) {
3005
+ const runtimeAuthored = isSyntheticMessage(message);
2903
3006
  for (const entry of extractEvictedEntries(message)) {
2904
3007
  await logEvent("context_evicted", {
2905
3008
  role: entry.role,
2906
3009
  text: entry.text,
2907
3010
  ...(entry.turnNumber !== undefined ? { turnNumber: entry.turnNumber } : {}),
3011
+ ...(runtimeAuthored ? { synthetic: true } : {}),
2908
3012
  });
2909
- if (entry.role === "user")
3013
+ if (entry.role === "user" && !runtimeAuthored)
2910
3014
  foldLedgerEntry(entry);
2911
3015
  }
2912
3016
  }
@@ -3294,6 +3398,11 @@ export async function runChatLoop(opts) {
3294
3398
  // #400 — approval ids this RUN has already replayed. Claimed synchronously
3295
3399
  // so two concurrent tool calls cannot both spend one one-shot grant.
3296
3400
  const replayedApprovalIds = new Set();
3401
+ // Grants an approved call holds between the gate that honoured them and the
3402
+ // last gate that can still refuse it, the rate gate, after which it spends
3403
+ // them. A parallel call must not run under one meanwhile, as a spent grant
3404
+ // would not let it.
3405
+ const grantsInFlight = new Set();
3297
3406
  const justificationInjectedTools = new Set(advertisedTools
3298
3407
  .filter(({ advertised }) => advertised.justificationInjected)
3299
3408
  .map(({ tool }) => tool.name));
@@ -3965,7 +4074,7 @@ export async function runChatLoop(opts) {
3965
4074
  // by the profile's `permissions.deny` / `.ask` through `narrowRuleSet`
3966
4075
  // (a decision-level meet — a profile can only tighten). The primary plan
3967
4076
  // carries the run's rules by reference, so a single-model run is unchanged.
3968
- const floorValues = tool.readOnly ? undefined : floorValuesOf(tool, subject.input);
4077
+ const floorValues = gateFloorValues(tool, subject.input);
3969
4078
  const decisionDetails = evaluateWithReason({
3970
4079
  toolName: tu.name,
3971
4080
  input: subject.input,
@@ -3976,7 +4085,11 @@ export async function runChatLoop(opts) {
3976
4085
  readOnly: tool.readOnly,
3977
4086
  destructive: tool.destructive,
3978
4087
  requiresSandbox: tool.requiresSandbox,
3979
- }, permissionMode, servingPlan.permissionRules, { sandboxAvailable: opts.sandboxAvailable === true, protectedRoots });
4088
+ }, permissionMode, servingPlan.permissionRules, {
4089
+ sandboxAvailable: opts.sandboxAvailable === true,
4090
+ protectedRoots,
4091
+ ...(credentialRoots !== undefined ? { credentialRoots } : {}),
4092
+ });
3980
4093
  const decision = decisionDetails.decision;
3981
4094
  bus.publish({
3982
4095
  ...bus.envelope(),
@@ -3989,6 +4102,26 @@ export async function runChatLoop(opts) {
3989
4102
  });
3990
4103
  let approved = decision === "allow";
3991
4104
  let denialMessage;
4105
+ // The store grant this call runs under, spent once it has passed every
4106
+ // check below that can refuse it; `release` lets it go unspent.
4107
+ let heldGrant;
4108
+ // Held synchronously, so a parallel identical call cannot run under it too.
4109
+ const holdGrant = (grant, store) => {
4110
+ grantsInFlight.add(grant.id);
4111
+ return {
4112
+ approvalId: grant.id,
4113
+ spend: async () => {
4114
+ await store.persist({ ...grant, consumedAt: new Date().toISOString() });
4115
+ grantsInFlight.delete(grant.id);
4116
+ },
4117
+ // A refused call can be retried, and the same refusal answers it
4118
+ // without a new card for the operator.
4119
+ release: () => {
4120
+ grantsInFlight.delete(grant.id);
4121
+ replayedApprovalIds.delete(grant.id);
4122
+ },
4123
+ };
4124
+ };
3992
4125
  if (decision === "deny") {
3993
4126
  denialMessage = decisionDetails.reason ?? "tool denied by permission policy";
3994
4127
  }
@@ -4037,6 +4170,8 @@ export async function runChatLoop(opts) {
4037
4170
  movedFrom = existing;
4038
4171
  existing = await findApprovalForPlace(approvals.store, approvalKeys, gateView);
4039
4172
  }
4173
+ if (existing?.decision === "grant" && grantsInFlight.has(existing.id))
4174
+ existing = null;
4040
4175
  // #400 — THE RESUMED CALL IS NOT THE PARKED CALL.
4041
4176
  //
4042
4177
  // A grant is keyed on whole-input equality, which silently assumes the
@@ -4077,7 +4212,9 @@ export async function runChatLoop(opts) {
4077
4212
  // 0.7.1 — and bound like the exact match: the APPROVED input must
4078
4213
  // still land where it did when the operator approved it. Read here,
4079
4214
  // once, and re-checked against policy below from this same reading.
4080
- if (replay !== undefined && !replayedApprovalIds.has(replay.id)) {
4215
+ if (replay !== undefined &&
4216
+ !replayedApprovalIds.has(replay.id) &&
4217
+ !grantsInFlight.has(replay.id)) {
4081
4218
  const replayView = placeRecordingCanonicalizer();
4082
4219
  const subjectOfReplay = preparePermissionSubject(tool, operativeToolInput(tu.name, replay.input), {
4083
4220
  canonicalizePath: replayView.canonicalizePath,
@@ -4131,8 +4268,8 @@ export async function runChatLoop(opts) {
4131
4268
  readProgramPath: approvedView.readProgramPath,
4132
4269
  ...(gateToolConfig !== undefined ? { toolConfig: gateToolConfig } : {}),
4133
4270
  });
4134
- const approvedFloor = approvedSubject.ok && !tool.readOnly
4135
- ? floorValuesOf(tool, approvedSubject.input)
4271
+ const approvedFloor = approvedSubject.ok
4272
+ ? gateFloorValues(tool, approvedSubject.input)
4136
4273
  : undefined;
4137
4274
  const recheck = approvedSubject.ok
4138
4275
  ? evaluateWithReason({
@@ -4145,7 +4282,11 @@ export async function runChatLoop(opts) {
4145
4282
  readOnly: tool.readOnly,
4146
4283
  destructive: tool.destructive,
4147
4284
  requiresSandbox: tool.requiresSandbox,
4148
- }, permissionMode, servingPlan.permissionRules, { sandboxAvailable: opts.sandboxAvailable === true, protectedRoots })
4285
+ }, permissionMode, servingPlan.permissionRules, {
4286
+ sandboxAvailable: opts.sandboxAvailable === true,
4287
+ protectedRoots,
4288
+ ...(credentialRoots !== undefined ? { credentialRoots } : {}),
4289
+ })
4149
4290
  : { decision: "deny", reason: approvedSubject.reason };
4150
4291
  if (recheck.decision === "deny") {
4151
4292
  approved = false;
@@ -4176,12 +4317,12 @@ export async function runChatLoop(opts) {
4176
4317
  }
4177
4318
  if (approved) {
4178
4319
  // Consume only once the call is really going to run: a replay the
4179
- // policy or a hook then refused must leave the operator's grant
4180
- // unspent, or they have to approve the same action twice.
4181
- await approvals.store.persist({
4182
- ...existing,
4183
- consumedAt: new Date().toISOString(),
4184
- });
4320
+ // policy or a hook then refused, and a call the justification
4321
+ // check below refuses, must leave the operator's grant unspent, or
4322
+ // they have to approve the same action twice. The egress check
4323
+ // records a match on this call and lets it go out as approved.
4324
+ // Held synchronously, as the replay claim above is held.
4325
+ heldGrant = holdGrant(existing, approvals.store);
4185
4326
  }
4186
4327
  if (replayedFrom !== undefined && approved) {
4187
4328
  bus.publish({
@@ -4300,6 +4441,45 @@ export async function runChatLoop(opts) {
4300
4441
  ...callAttribution,
4301
4442
  });
4302
4443
  }
4444
+ /**
4445
+ * A call a rule allows may be the one a person approved on a parked
4446
+ * approval: `--always` and Slack's "Always allow" save a settings rule
4447
+ * beside the grant, and that rule decides the resumed call before the
4448
+ * store is asked. The grant for this exact call, made where it lands and
4449
+ * not yet spent, is held as the ask branch holds it, so the call goes out
4450
+ * as approved and the grant is spent once. Any later call under the rule
4451
+ * alone meets every check as any call does. The egress check asks for it
4452
+ * only when its verdict for the call is `block`, where a held grant changes
4453
+ * the outcome. A lookup that fails finds no grant: the call meets the
4454
+ * egress check as any call a rule allows does.
4455
+ */
4456
+ const holdRuleAllowedGrant = async () => {
4457
+ if (decision !== "allow" || approvals === undefined)
4458
+ return;
4459
+ let grant = null;
4460
+ try {
4461
+ grant = await approvals.store.get(tu.name, hashApprovalInput(tu.name, operativeInput));
4462
+ const legacyToolName = legacyMcpToolName(tu.name);
4463
+ if (grant === null && legacyToolName !== undefined) {
4464
+ grant = await approvals.store.get(legacyToolName, hashApprovalInput(legacyToolName, operativeInput));
4465
+ }
4466
+ }
4467
+ catch (err) {
4468
+ runContext.logger.warn("approval lookup failed", {
4469
+ toolUseId: tu.id,
4470
+ toolName: tu.name,
4471
+ error: err.message,
4472
+ });
4473
+ grant = null;
4474
+ }
4475
+ if (grant !== null &&
4476
+ grant.decision === "grant" &&
4477
+ grant.consumedAt === undefined &&
4478
+ !grantsInFlight.has(grant.id) &&
4479
+ landsWhereApproved(grant, gateView)) {
4480
+ heldGrant = holdGrant(grant, approvals.store);
4481
+ }
4482
+ };
4303
4483
  if (!approved) {
4304
4484
  return finish({
4305
4485
  type: "tool_result",
@@ -4385,6 +4565,7 @@ export async function runChatLoop(opts) {
4385
4565
  }
4386
4566
  }
4387
4567
  if (!verdict.allow) {
4568
+ heldGrant?.release();
4388
4569
  return finish({
4389
4570
  type: "tool_result",
4390
4571
  tool_use_id: tu.id,
@@ -4409,7 +4590,7 @@ export async function runChatLoop(opts) {
4409
4590
  // tools this is what `executeTool` actually transmits to the sink.
4410
4591
  const payload = JSON.stringify(operativeInput ?? null);
4411
4592
  const sinkScope = (opts.resolveSinkScope ?? defaultSinkScope)(tu.name, tool);
4412
- const egress = await classifyEgress(payload, runContext, {
4593
+ const classified = await classifyEgress(payload, runContext, {
4413
4594
  sinkId: tu.name,
4414
4595
  sinkScope,
4415
4596
  // FR-006: forward the caller-selected matcher when present. Absent
@@ -4418,6 +4599,21 @@ export async function runChatLoop(opts) {
4418
4599
  // below are byte-for-byte unchanged.
4419
4600
  ...(opts.egressMatcher !== undefined ? { matcher: opts.egressMatcher } : {}),
4420
4601
  });
4602
+ // An ordinary call, whose verdict is `pass` or `warn`, reads no approval.
4603
+ if (classified.verdict === "block" && heldGrant === undefined) {
4604
+ await holdRuleAllowedGrant();
4605
+ }
4606
+ // A call that runs under a grant a person gave on a parked approval goes
4607
+ // out as approved: for this call alone a `block` is a `warn`, and its
4608
+ // records name the approval. A live approval, and every other call in the
4609
+ // run, keep the policy's verdict.
4610
+ const approvedOver = classified.verdict === "block" && heldGrant !== undefined
4611
+ ? heldGrant.approvalId
4612
+ : undefined;
4613
+ const egress = approvedOver !== undefined ? { ...classified, verdict: "warn" } : classified;
4614
+ const approvedReason = approvedOver !== undefined
4615
+ ? `approval ${approvedOver} granted by a person: sent as approved`
4616
+ : undefined;
4421
4617
  const egressOutcome = egress.verdict === "pass"
4422
4618
  ? "egress-passed"
4423
4619
  : egress.verdict === "warn"
@@ -4430,7 +4626,11 @@ export async function runChatLoop(opts) {
4430
4626
  decision: egress.verdict === "block" ? "deny" : "allow",
4431
4627
  mode: permissionMode,
4432
4628
  outcome: egressOutcome,
4433
- ...(egress.originsFound.length > 0 ? { reason: `egress: ${summarizeEgress(egress)}` } : {}),
4629
+ ...(egress.originsFound.length > 0
4630
+ ? {
4631
+ reason: `egress: ${summarizeEgress(egress)}${approvedReason !== undefined ? `; ${approvedReason}` : ""}`,
4632
+ }
4633
+ : {}),
4434
4634
  ...callAttribution,
4435
4635
  });
4436
4636
  if (egress.verdict !== "pass") {
@@ -4440,6 +4640,7 @@ export async function runChatLoop(opts) {
4440
4640
  verdict: egress.verdict,
4441
4641
  originsFound: egress.originsFound,
4442
4642
  matchCount: egress.matchCount,
4643
+ ...(approvedOver !== undefined ? { approvalId: approvedOver } : {}),
4443
4644
  });
4444
4645
  // Item 20 — emit the durable `egress_decision` audit record for every
4445
4646
  // non-pass verdict so egress history is triageable offline (the
@@ -4460,6 +4661,9 @@ export async function runChatLoop(opts) {
4460
4661
  verdict: egress.verdict,
4461
4662
  originsFound: egress.originsFound,
4462
4663
  matchCount: egress.matchCount,
4664
+ ...(approvedOver !== undefined
4665
+ ? { approvalId: approvedOver, reason: approvedReason }
4666
+ : {}),
4463
4667
  },
4464
4668
  });
4465
4669
  }
@@ -4473,6 +4677,7 @@ export async function runChatLoop(opts) {
4473
4677
  }
4474
4678
  }
4475
4679
  if (egress.verdict === "block") {
4680
+ heldGrant?.release();
4476
4681
  return finish({
4477
4682
  type: "tool_result",
4478
4683
  tool_use_id: tu.id,
@@ -4505,6 +4710,7 @@ export async function runChatLoop(opts) {
4505
4710
  }
4506
4711
  }
4507
4712
  catch (err) {
4713
+ heldGrant?.release();
4508
4714
  runContext.logger.warn("tool rate limit exhausted", {
4509
4715
  toolUseId: tu.id,
4510
4716
  toolName: tu.name,
@@ -4518,6 +4724,9 @@ export async function runChatLoop(opts) {
4518
4724
  });
4519
4725
  }
4520
4726
  }
4727
+ // The call has passed every gate that can refuse it, so the grant it runs
4728
+ // under is spent here; a call a gate above refused left it unspent.
4729
+ await heldGrant?.spend();
4521
4730
  const toolAbort = turnAbort.child();
4522
4731
  // Build the bridge for this call. Built on EVERY run (#160 follow-up):
4523
4732
  // it carries `runContext`, which Pillar-3 boundary-site tools (tool-mcp,
@@ -4553,6 +4762,9 @@ export async function runChatLoop(opts) {
4553
4762
  // 0.8.0 — the runtime-state roots, for the tools that write beneath a
4554
4763
  // directory they name and must not reach one (see RuntimeBridge).
4555
4764
  ...(protectedRoots.length > 0 ? { protectedRoots } : {}),
4765
+ // The files a `channel` or `managed` run keeps from its tools, for the tools
4766
+ // RuntimeBridge names.
4767
+ ...(credentialRoots !== undefined ? { credentialRoots } : {}),
4556
4768
  permissionMode,
4557
4769
  permissionRules: servingPlan.permissionRules,
4558
4770
  tools: bridgeTools,