@crewhaus/runtime-core 0.5.3 → 0.5.5

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
@@ -126,6 +126,51 @@ export type { CreateJanitorOptions, Janitor, JanitorBuiltinStepName, JanitorRese
126
126
  export { AGENT_IDENTITY_SCHEMA_VERSION, DEFAULT_IDENTITY_DIR, IDENTITY_FILENAME, agentFingerprint, loadOrCreateAgentIdentity, } from "./identity";
127
127
  export type { AgentIdentityFile } from "./identity";
128
128
  export { type ApprovalDecision, type PendingApproval, type PendingApprovalStore, type PendingApprovalStoreOptions, createPendingApprovalStore, evictExpiredApprovals, generateApprovalId, hashApprovalInput, } from "@crewhaus/session-store";
129
+ /**
130
+ * How long after an operator's DECISION a grant may still satisfy a call the
131
+ * model has re-worded. Generous enough for a resume (which follows the grant
132
+ * within seconds on every surface), short enough that an unspent grant cannot
133
+ * be replayed onto an unrelated turn an hour later.
134
+ */
135
+ export declare const REPLAYABLE_GRANT_MAX_AGE_MS: number;
136
+ /**
137
+ * #400 — find the grant an operator made for a call this run has since
138
+ * REGENERATED differently.
139
+ *
140
+ * Only ever consulted after the exact-hash lookup misses, so the normal path
141
+ * (a byte-identical re-issue) is untouched. Every condition below is load-
142
+ * bearing; together they are what keeps a replay from becoming a standing
143
+ * allow:
144
+ *
145
+ * - `sessionId` — a grant never leaks into another conversation.
146
+ * - `toolName` — a grant for one tool never authorizes another.
147
+ * - `decision === "grant"` and no `consumedAt` — one-shot means one shot.
148
+ * - `runId !== <this run>` — the grant must come from a PRIOR run, i.e.
149
+ * this really is a resume. Without it a run could park, be granted, and
150
+ * then spend that grant on a *second, different* call inside the same
151
+ * run — turning one approval into a tool-wide licence for the turn.
152
+ * - `input !== undefined` — the record must actually carry what was
153
+ * approved. `PendingApproval.input` is optional and unvalidated, so a
154
+ * record written by an older or foreign writer has nothing to replay; the
155
+ * honest answer there is to park, not to guess.
156
+ *
157
+ * Newest-first, so when several grants are outstanding the most recent
158
+ * decision wins — the same "latest decision" posture the store's own `get`
159
+ * takes.
160
+ *
161
+ * `list` is optional on the injected store: a caller that supplies a minimal
162
+ * `{persist,get,resolve}` store simply never replays and keeps the pre-#400
163
+ * behaviour, rather than failing.
164
+ */
165
+ export declare function findReplayableGrant(store: Pick<PendingApprovalStore, "persist" | "get" | "resolve"> & Partial<Pick<PendingApprovalStore, "list">>, where: {
166
+ readonly toolName: string;
167
+ readonly sessionId: string;
168
+ readonly runId: string;
169
+ /** Epoch ms; the freshness window is measured from the DECISION. */
170
+ readonly now?: number;
171
+ /** Override the window (tests). */
172
+ readonly maxAgeMs?: number;
173
+ }): Promise<PendingApproval | undefined>;
129
174
  export { type AlertBreachPayload, type AlertSink, type AttachDefaultSubscribersOptions, attachDefaultSubscribers, } from "./observability";
130
175
  export { type AttachedSloMonitor, type AttachSloMonitorOptions, type SloBreach, type SloMitigationEvent, type SloMitigationRung, type SloMitigationSink, type SloTargets, type SloWindowMetrics, DEFAULT_SLO_WINDOW_MS, MIN_SLO_SAMPLES, SloWindow, attachSloMonitor, detectSloBreaches, } from "./slo-monitor";
131
176
  export { type AttachIncidentCollectorOptions, type IncidentCapture, type IncidentTriggerKind, attachIncidentCollector, classifyIncidentTrigger, } from "./incident-collector";
@@ -442,6 +487,16 @@ export type RunChatLoopOptions = {
442
487
  * to the session JSON for future filtering. Defaults to `"cli"`.
443
488
  */
444
489
  sessionTarget?: string;
490
+ /**
491
+ * #405 — identifies the AGENT CONTEXT that owns this run's toolset within a
492
+ * session several contexts share. A crew is the case that forces it: every
493
+ * role activation appends to ONE session log and each role carries its own
494
+ * tools, so a cross-role comparison would report a "toolset changed"
495
+ * that never happened. Records are written and read per scope; single-
496
+ * context sessions (cli, channel, managed) leave it unset and compare
497
+ * against their own unscoped history exactly as before.
498
+ */
499
+ toolsetScope?: string;
445
500
  /**
446
501
  * Resume an existing session: load its metadata, replay its event log
447
502
  * into the message history (only `user_message` + `assistant_message`
@@ -1134,7 +1189,7 @@ export type RunChatLoopOptions = {
1134
1189
  * from the full `PendingApprovalStore` so a caller may inject a minimal
1135
1190
  * store; the concrete `createPendingApprovalStore` satisfies it.
1136
1191
  */
1137
- readonly store: Pick<PendingApprovalStore, "persist" | "get" | "resolve">;
1192
+ readonly store: Pick<PendingApprovalStore, "persist" | "get" | "resolve"> & Partial<Pick<PendingApprovalStore, "list">>;
1138
1193
  readonly notify?: (approval: PendingApproval) => Promise<void>;
1139
1194
  readonly surface?: string;
1140
1195
  };
package/dist/index.js CHANGED
@@ -39,6 +39,7 @@ import { zodToJsonSchema } from "zod-to-json-schema";
39
39
  import { createCliMarkdownRenderer, isCliMarkdownEnabled, } from "./cli-markdown";
40
40
  import { FEEDBACK_EVENT_KIND, runExitRating } from "./exit-rating";
41
41
  import { attachIncidentCollector } from "./incident-collector";
42
+ import { LIST_TOOLS_NAME, buildListToolsTool } from "./list-tools";
42
43
  import { attachAdvisorPersistence, attachDefaultSubscribers, attachMcpStatsPersistence, attachWatchmeCapture, } from "./observability";
43
44
  import { loadProjectMemory } from "./project-memory";
44
45
  import { createCliOutput, isSpinnerEnabled } from "./spinner";
@@ -413,6 +414,91 @@ export { AGENT_IDENTITY_SCHEMA_VERSION, DEFAULT_IDENTITY_DIR, IDENTITY_FILENAME,
413
414
  // build the store + input hash it passes as `RunChatLoopOptions.approvals`
414
415
  // without depending on session-store directly.
415
416
  export { createPendingApprovalStore, evictExpiredApprovals, generateApprovalId, hashApprovalInput, } from "@crewhaus/session-store";
417
+ /**
418
+ * How long after an operator's DECISION a grant may still satisfy a call the
419
+ * model has re-worded. Generous enough for a resume (which follows the grant
420
+ * within seconds on every surface), short enough that an unspent grant cannot
421
+ * be replayed onto an unrelated turn an hour later.
422
+ */
423
+ export const REPLAYABLE_GRANT_MAX_AGE_MS = 15 * 60 * 1000;
424
+ /**
425
+ * #400 — find the grant an operator made for a call this run has since
426
+ * REGENERATED differently.
427
+ *
428
+ * Only ever consulted after the exact-hash lookup misses, so the normal path
429
+ * (a byte-identical re-issue) is untouched. Every condition below is load-
430
+ * bearing; together they are what keeps a replay from becoming a standing
431
+ * allow:
432
+ *
433
+ * - `sessionId` — a grant never leaks into another conversation.
434
+ * - `toolName` — a grant for one tool never authorizes another.
435
+ * - `decision === "grant"` and no `consumedAt` — one-shot means one shot.
436
+ * - `runId !== <this run>` — the grant must come from a PRIOR run, i.e.
437
+ * this really is a resume. Without it a run could park, be granted, and
438
+ * then spend that grant on a *second, different* call inside the same
439
+ * run — turning one approval into a tool-wide licence for the turn.
440
+ * - `input !== undefined` — the record must actually carry what was
441
+ * approved. `PendingApproval.input` is optional and unvalidated, so a
442
+ * record written by an older or foreign writer has nothing to replay; the
443
+ * honest answer there is to park, not to guess.
444
+ *
445
+ * Newest-first, so when several grants are outstanding the most recent
446
+ * decision wins — the same "latest decision" posture the store's own `get`
447
+ * takes.
448
+ *
449
+ * `list` is optional on the injected store: a caller that supplies a minimal
450
+ * `{persist,get,resolve}` store simply never replays and keeps the pre-#400
451
+ * behaviour, rather than failing.
452
+ */
453
+ export async function findReplayableGrant(store, where) {
454
+ if (typeof store.list !== "function")
455
+ return undefined;
456
+ let all;
457
+ try {
458
+ all = await store.list();
459
+ }
460
+ catch {
461
+ // A read that fails must not fail the tool call: park as before.
462
+ return undefined;
463
+ }
464
+ const now = where.now ?? Date.now();
465
+ const maxAgeMs = where.maxAgeMs ?? REPLAYABLE_GRANT_MAX_AGE_MS;
466
+ const matches = all.filter((a) => {
467
+ if (a.toolName !== where.toolName)
468
+ return false;
469
+ if (a.sessionId !== where.sessionId)
470
+ return false;
471
+ if (a.decision !== "grant")
472
+ return false;
473
+ if (a.consumedAt !== undefined)
474
+ return false;
475
+ if (a.runId === where.runId)
476
+ return false;
477
+ if (a.input === undefined)
478
+ return false;
479
+ // FRESHNESS, measured from the DECISION — not from the park.
480
+ //
481
+ // Without it a grant that was never spent sits in a long-lived session
482
+ // forever and is replayed onto an unrelated later turn: the operator
483
+ // asked for X an hour ago, approved it, the resume happened not to call
484
+ // the tool, and now an unrelated request runs X. Bounding from
485
+ // `decidedAt` is what makes the window track the approve→resume gap
486
+ // (seconds: the Slack button resumes immediately, and a CLI grant is
487
+ // followed by `runs resume`) rather than the park→approve gap, which is
488
+ // human-paced and may be hours.
489
+ //
490
+ // A grant older than this is not discarded — it stays a valid record for
491
+ // the EXACT-hash path, which is unbounded. Only the fuzzy replay is
492
+ // time-boxed.
493
+ const decidedAt = a.decidedAt !== undefined ? Date.parse(a.decidedAt) : Number.NaN;
494
+ if (!Number.isFinite(decidedAt))
495
+ return false;
496
+ return now - decidedAt <= maxAgeMs;
497
+ });
498
+ // `list()` is newest-first by contract, but sort defensively rather than
499
+ // trust the ordering of a store a caller injected.
500
+ return [...matches].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0];
501
+ }
416
502
  // Ops item 31 — alert watchdog seams re-exported so the CLI/codegen can build
417
503
  // the durable + off-box alert sink (audit append + settings.json alert hook /
418
504
  // webhook) it passes as `RunChatLoopOptions.alertSink`.
@@ -718,7 +804,18 @@ export async function runChatLoop(opts) {
718
804
  // Item 3 (G32) — resolve the advertised tool set ONCE, up front, folding in
719
805
  // any plugin-contributed tools so the tool-capable-model feature gate and the
720
806
  // per-turn advertisement below read the same list.
721
- const effectiveTools = mergeEffectiveTools(opts.tools ?? [], opts.plugins?.tools);
807
+ const mergedTools = mergeEffectiveTools(opts.tools ?? [], opts.plugins?.tools);
808
+ // #405 — the runtime's own toolset-introspection tool rides every
809
+ // TOOL-CARRYING loop. Late-bound: it is part of the list it reports, so it
810
+ // reads the advertised summaries assigned after that list is built below.
811
+ // A ZERO-tool loop stays zero-tool (the tool-capable-model gate reads this
812
+ // list, and a chat-only spec must not become tool-requiring), and a caller
813
+ // that brings its own tool under the same name wins — the same
814
+ // first-party-wins posture the plugin merge takes.
815
+ let listToolsSummaries = [];
816
+ const effectiveTools = mergedTools.length === 0 || mergedTools.some((t) => t.name === LIST_TOOLS_NAME)
817
+ ? mergedTools
818
+ : [...mergedTools, buildListToolsTool(() => listToolsSummaries)];
722
819
  // Pillar 3 — make the model-backed Layer-3 classifier reachable at EVERY
723
820
  // trust boundary (MCP / sub-agent / channel / federation / skill /
724
821
  // compaction / chain / orchestrator). Boundary call sites don't thread an
@@ -1032,6 +1129,9 @@ export async function runChatLoop(opts) {
1032
1129
  };
1033
1130
  let sessionId;
1034
1131
  let resumedMessages;
1132
+ // #405 — the toolset recorded by this session's LAST run (undefined when
1133
+ // the session predates the record, or on a fresh session).
1134
+ let resumedToolNames;
1035
1135
  // §2.3 — on resume, the requirements ledger rebuilds DETERMINISTICALLY
1036
1136
  // from the `context_evicted` events already on disk (dedup against
1037
1137
  // re-evictions happens at fold time): a resumed session recovers every
@@ -1045,18 +1145,50 @@ export async function runChatLoop(opts) {
1045
1145
  sessionId = existing.id;
1046
1146
  const replayLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
1047
1147
  resumedMessages = await replayMessageHistory(replayLog);
1048
- if (opts.continuity !== undefined && opts.continuity.ledger !== false) {
1049
- for await (const ev of replayLog.read()) {
1050
- if (ev.kind !== "context_evicted")
1148
+ // One pass gathers both resume-time reads: the continuity ledger seed
1149
+ // (conditional) and the LAST recorded toolset (#405 — unconditional, so
1150
+ // the marker below can tell a resumed session its capabilities changed
1151
+ // while it was parked).
1152
+ const wantLedger = opts.continuity !== undefined && opts.continuity.ledger !== false;
1153
+ // Mirror `replayMessageHistory` / the janitor's orphan scan: events nested
1154
+ // inside a2a_turn_start / sub_agent_start brackets belong to a PEER's or a
1155
+ // sub-agent's transcript — their toolsets are legitimately different and
1156
+ // must not be mistaken for this context's previous one.
1157
+ let nestDepth = 0;
1158
+ for await (const ev of replayLog.read()) {
1159
+ if (ev.kind === "a2a_turn_start" || ev.kind === "sub_agent_start") {
1160
+ nestDepth += 1;
1161
+ continue;
1162
+ }
1163
+ if (ev.kind === "a2a_turn_end" || ev.kind === "sub_agent_end") {
1164
+ nestDepth = Math.max(0, nestDepth - 1);
1165
+ continue;
1166
+ }
1167
+ if (ev.kind === "toolset") {
1168
+ if (nestDepth > 0)
1051
1169
  continue;
1052
1170
  const p = ev.payload;
1053
- if (p.role === "user" && typeof p.text === "string") {
1054
- resumedLedgerSeed.push({
1055
- role: "user",
1056
- text: p.text,
1057
- ...(typeof p.turnNumber === "number" ? { turnNumber: p.turnNumber } : {}),
1058
- });
1171
+ // Records from a DIFFERENT agent context in the same session (crew
1172
+ // roles share one log) describe a different toolset by design.
1173
+ const recordScope = typeof p.scope === "string" ? p.scope : undefined;
1174
+ if (recordScope !== opts.toolsetScope)
1175
+ continue;
1176
+ if (Array.isArray(p.toolNames) && p.toolNames.every((n) => typeof n === "string")) {
1177
+ resumedToolNames = p.toolNames;
1059
1178
  }
1179
+ continue;
1180
+ }
1181
+ // NOTE: the ledger seed below deliberately keeps its pre-#405 behaviour
1182
+ // (no depth filter) — the guard above applies to `toolset` only.
1183
+ if (!wantLedger || ev.kind !== "context_evicted")
1184
+ continue;
1185
+ const p = ev.payload;
1186
+ if (p.role === "user" && typeof p.text === "string") {
1187
+ resumedLedgerSeed.push({
1188
+ role: "user",
1189
+ text: p.text,
1190
+ ...(typeof p.turnNumber === "number" ? { turnNumber: p.turnNumber } : {}),
1191
+ });
1060
1192
  }
1061
1193
  }
1062
1194
  await replayLog.close();
@@ -1262,6 +1394,50 @@ export async function runChatLoop(opts) {
1262
1394
  out.write("\n");
1263
1395
  };
1264
1396
  const eventLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
1397
+ // #405 — reconcile the session's recorded toolset with THIS run's.
1398
+ //
1399
+ // The failure this closes: a session parked on build N enumerates its
1400
+ // toolset into the conversation; the daemon is rebuilt with tools added and
1401
+ // the session resumes with the new definitions attached to every request —
1402
+ // yet the transcript's own stale enumeration beats the live schema, and the
1403
+ // agent politely denies the new tools forever. A synthetic user message is
1404
+ // the established runtime-injected-turn convention (the control-plane poke
1405
+ // marker): the MODEL sees it on this and every later replay, while every
1406
+ // turn-deriving reader (feedback distill, eval digests, summarizers) skips
1407
+ // `synthetic: true`.
1408
+ //
1409
+ // The record is written only when the set CHANGED (or was never recorded),
1410
+ // so an unchanged fleet costs one `toolset` line per session, not one per
1411
+ // turn. Sessions from before this record exist get no marker on their first
1412
+ // resume — there is nothing to compare against — and are covered from then
1413
+ // on.
1414
+ {
1415
+ const currentToolNames = [...effectiveTools.map((t) => t.name)].sort();
1416
+ const prior = resumedToolNames === undefined ? undefined : [...resumedToolNames].sort();
1417
+ const changed = prior !== undefined &&
1418
+ (prior.length !== currentToolNames.length ||
1419
+ prior.some((name, i) => name !== currentToolNames[i]));
1420
+ if (changed && resumedMessages !== undefined) {
1421
+ const added = currentToolNames.filter((n) => !prior.includes(n));
1422
+ const removed = prior.filter((n) => !currentToolNames.includes(n));
1423
+ const delta = [...added.map((n) => `+${n}`), ...removed.map((n) => `−${n}`)].join(", ");
1424
+ const marker = `[system] The toolset changed while this session was idle: ${delta}. The tool schema attached to this request is the authoritative list — any toolset enumerated earlier in this conversation is stale. Call ListTools to verify.`;
1425
+ resumedMessages.push({ role: "user", content: marker });
1426
+ await eventLog.append({
1427
+ kind: "user_message",
1428
+ payload: { content: marker, synthetic: true, toolset: { added, removed } },
1429
+ });
1430
+ }
1431
+ if (prior === undefined || changed) {
1432
+ await eventLog.append({
1433
+ kind: "toolset",
1434
+ payload: {
1435
+ toolNames: currentToolNames,
1436
+ ...(opts.toolsetScope !== undefined ? { scope: opts.toolsetScope } : {}),
1437
+ },
1438
+ });
1439
+ }
1440
+ }
1265
1441
  // Section 27 — mirror per-call cost_accrual events from the trace bus into
1266
1442
  // the session JSONL so `crewhaus cost-summary --session <id>` can sum spend
1267
1443
  // after the run. Gated on the same switch that attaches the cost-tracker
@@ -1788,6 +1964,17 @@ export async function runChatLoop(opts) {
1788
1964
  // gate's `justification` contract injected for `requireJustification`
1789
1965
  // tools whose own schema doesn't declare it (see `toAdvertisedTool`).
1790
1966
  const advertisedTools = tools.map((t) => ({ tool: t, advertised: toAdvertisedTool(t) }));
1967
+ // #405 — what ListTools reports: the exact list advertised on this request,
1968
+ // with the gate flag reflecting the ADVERTISED contract (a runtime-injected
1969
+ // justification is part of that contract even though the tool's own schema
1970
+ // never declared it).
1971
+ listToolsSummaries = advertisedTools.map(({ tool, advertised }) => ({
1972
+ name: tool.name,
1973
+ description: tool.description,
1974
+ readOnly: tool.readOnly,
1975
+ destructive: tool.destructive,
1976
+ gated: tool.requireJustification === true || advertised.justificationInjected === true,
1977
+ }));
1791
1978
  const anthropicTools = advertisedTools.length > 0
1792
1979
  ? advertisedTools.map(({ tool, advertised }) => ({
1793
1980
  name: tool.name,
@@ -1814,6 +2001,9 @@ export async function runChatLoop(opts) {
1814
2001
  // justification gate, and the justification audit sink. Tools that
1815
2002
  // declare the field in their own schema are NOT in this set — for them
1816
2003
  // the field is genuine tool input everywhere.
2004
+ // #400 — approval ids this RUN has already replayed. Claimed synchronously
2005
+ // so two concurrent tool calls cannot both spend one one-shot grant.
2006
+ const replayedApprovalIds = new Set();
1817
2007
  const justificationInjectedTools = new Set(advertisedTools
1818
2008
  .filter(({ advertised }) => advertised.justificationInjected)
1819
2009
  .map(({ tool }) => tool.name));
@@ -1974,7 +2164,13 @@ export async function runChatLoop(opts) {
1974
2164
  * Used by both the partitioned (post-stream) path and the streaming
1975
2165
  * path so the permission/abort/store contract is uniform.
1976
2166
  */
1977
- async function executeOneToolUse(tu) {
2167
+ async function executeOneToolUse(tuAsRequested) {
2168
+ // REBINDABLE on purpose (#400): a replayed approval substitutes the
2169
+ // operator-approved input for the model's regenerated one, and every
2170
+ // consumer below — the validator, the executor, the justification gate,
2171
+ // the egress classifier, the result record — reads through `tu`. Rebinding
2172
+ // here is what makes the substitution reach all of them instead of one.
2173
+ let tu = tuAsRequested;
1978
2174
  // End the "thinking" wait — but only when no tool is already mid-flight.
1979
2175
  // The streaming executor dispatches concurrency-safe tools with overlap, so
1980
2176
  // an unconditional stop here would tear down a sibling tool's live spinner;
@@ -2008,7 +2204,30 @@ export async function runChatLoop(opts) {
2008
2204
  });
2009
2205
  const t0Tool = performance.now();
2010
2206
  const tool = toolByName.get(tu.name);
2011
- const finish = async (result) => {
2207
+ // #400 — set when this call ran the input an operator APPROVED rather
2208
+ // than the one the model regenerated. Function-scoped so `finish` (the
2209
+ // single choke point every result passes through) can tell the model,
2210
+ // whichever return path fires.
2211
+ let replayedFrom;
2212
+ const finish = async (resultIn) => {
2213
+ let result = resultIn;
2214
+ // Say so IN THE RESULT. The assistant message still shows the input the
2215
+ // model asked for, so without this the model would reason about an
2216
+ // action that did not happen — and might "correct" itself by re-issuing
2217
+ // the call it thinks failed.
2218
+ if (replayedFrom !== undefined) {
2219
+ const notice = `[approval ${replayedFrom.id} was granted for a different wording of this call; the APPROVED input was executed, not the one you just sent. Read the result as the outcome of the approved action.]`;
2220
+ // Block content (images, structured blocks) is just as capable of
2221
+ // misleading the model as a string, so the notice rides both shapes —
2222
+ // prepended as its own text block when the content is an array.
2223
+ result =
2224
+ typeof result.content === "string"
2225
+ ? { ...result, content: `${notice}\n${result.content}` }
2226
+ : {
2227
+ ...result,
2228
+ content: [{ type: "text", text: notice }, ...(result.content ?? [])],
2229
+ };
2230
+ }
2012
2231
  await logEvent("tool_result", {
2013
2232
  toolUseId: tu.id,
2014
2233
  content: typeof result.content === "string"
@@ -2072,7 +2291,7 @@ export async function runChatLoop(opts) {
2072
2291
  // DOES (rule matching, approval hashing, egress, execution) consumes
2073
2292
  // this; surfaces that record what the model DID keep `tu.input`. See the
2074
2293
  // `justificationInjectedTools` comment at loop start for the full split.
2075
- const operativeInput = operativeToolInput(tu.name, tu.input);
2294
+ let operativeInput = operativeToolInput(tu.name, tu.input);
2076
2295
  const decisionDetails = evaluateWithReason({
2077
2296
  toolName: tu.name,
2078
2297
  input: operativeInput,
@@ -2110,7 +2329,48 @@ export async function runChatLoop(opts) {
2110
2329
  // forever. The persisted record still carries the full `tu.input`
2111
2330
  // below so the approving operator SEES the justification.
2112
2331
  const inputHash = hashApprovalInput(tu.name, operativeInput);
2113
- const existing = await approvals.store.get(tu.name, inputHash);
2332
+ let existing = await approvals.store.get(tu.name, inputHash);
2333
+ // #400 — THE RESUMED CALL IS NOT THE PARKED CALL.
2334
+ //
2335
+ // A grant is keyed on whole-input equality, which silently assumes the
2336
+ // resumed run re-issues a byte-identical tool call. It does not: resume
2337
+ // re-drives the turn, the model regenerates the call, and
2338
+ // `sanitizeOrphanToolUses` has stripped the parked `tool_use` from the
2339
+ // replayed transcript — so the model is generating it FRESH and may
2340
+ // word any field differently. One re-worded argument moves the hash,
2341
+ // `get` misses, and the run parks AGAIN under a new id. Approve →
2342
+ // regenerate → re-park, forever: a plain one-shot grant could never
2343
+ // satisfy a model-driven tool, leaving `--always` (a STANDING allow on
2344
+ // a quota-spending or irreversible tool) as the only thing that landed
2345
+ // a single call.
2346
+ //
2347
+ // So when the exact key misses, look for the grant the operator
2348
+ // actually made — same session, same tool, still unspent — and run THE
2349
+ // INPUT THEY APPROVED rather than the one the model just regenerated.
2350
+ // Substituting is what keeps the security property intact: the
2351
+ // operator authorized a specific action shown to them on the approval
2352
+ // card, and that action is what executes. Honouring the grant for the
2353
+ // regenerated input instead would let a re-worded `place_call` dial a
2354
+ // different number under an approval for the first.
2355
+ if (existing === null) {
2356
+ const replay = await findReplayableGrant(approvals.store, {
2357
+ toolName: tu.name,
2358
+ sessionId,
2359
+ runId: bus.runId,
2360
+ now: Date.now(),
2361
+ });
2362
+ // CLAIM IT SYNCHRONOUSLY. The lookup reads and the consuming
2363
+ // `persist` writes, and up to `maxConcurrentTools` ask-gated calls
2364
+ // run through this gate at once — so without a claim two parallel
2365
+ // calls both find the same unconsumed grant and both execute. The
2366
+ // set is per-run and in-process, which is where that race is;
2367
+ // across processes the store's `consumedAt` remains the authority.
2368
+ if (replay !== undefined && !replayedApprovalIds.has(replay.id)) {
2369
+ replayedApprovalIds.add(replay.id);
2370
+ replayedFrom = replay;
2371
+ existing = replay;
2372
+ }
2373
+ }
2114
2374
  if (existing?.decision === "grant") {
2115
2375
  // One-shot allow: consume the grant so a later identical call
2116
2376
  // re-asks. A STANDING grant (#383, `existing.always`) is consumed
@@ -2121,7 +2381,86 @@ export async function runChatLoop(opts) {
2121
2381
  // revokes the standing allow (no unconsumed record lingers to
2122
2382
  // pre-approve the parked input until the TTL sweep).
2123
2383
  approved = true;
2124
- await approvals.store.persist({ ...existing, consumedAt: new Date().toISOString() });
2384
+ if (replayedFrom !== undefined) {
2385
+ // Run WHAT WAS APPROVED. `tu.input` is the model's regenerated
2386
+ // wording; the record carries the input the operator saw and said
2387
+ // yes to, and that is the one with an authorization behind it.
2388
+ const approvedInput = replayedFrom.input;
2389
+ const approvedOperative = operativeToolInput(tu.name, approvedInput);
2390
+ // Re-evaluate POLICY against what will actually run. The approved
2391
+ // input passed these rules in the run that parked it, but the
2392
+ // rules are read fresh each loop and an operator may have tightened
2393
+ // them since — and a grant is permission from a human, not an
2394
+ // exemption from the spec. A rule that now DENIES wins.
2395
+ const recheck = evaluateWithReason({
2396
+ toolName: tu.name,
2397
+ input: approvedOperative,
2398
+ readOnly: tool.readOnly,
2399
+ destructive: tool.destructive,
2400
+ requiresSandbox: tool.requiresSandbox,
2401
+ }, permissionMode, permissionRules, { sandboxAvailable: opts.sandboxAvailable === true });
2402
+ if (recheck.decision === "deny") {
2403
+ approved = false;
2404
+ denialMessage =
2405
+ `tool denied: approval ${replayedFrom.id} was granted, but \`${tu.name}\` is now denied by permission policy` +
2406
+ `${recheck.reason !== undefined ? ` (${recheck.reason})` : ""}.`;
2407
+ // The grant is NOT spent on a call that never ran, and the
2408
+ // result must not claim an approved input executed.
2409
+ replayedFrom = undefined;
2410
+ }
2411
+ else {
2412
+ tu = { ...tu, input: approvedInput };
2413
+ operativeInput = approvedOperative;
2414
+ // The `pre-tool` hook already judged the input the MODEL sent,
2415
+ // several steps above. A hook that can deny must judge what will
2416
+ // actually RUN, so re-fire it against the substituted input.
2417
+ const replayHook = await fireHook("pre-tool", {
2418
+ id: tu.id,
2419
+ name: tu.name,
2420
+ input: tu.input,
2421
+ });
2422
+ if (!replayHook.allowed) {
2423
+ approved = false;
2424
+ denialMessage = `[blocked by hook] ${replayHook.reason ?? "denied"}`;
2425
+ replayedFrom = undefined;
2426
+ }
2427
+ }
2428
+ }
2429
+ if (approved) {
2430
+ // Consume only once the call is really going to run: a replay the
2431
+ // policy or a hook then refused must leave the operator's grant
2432
+ // unspent, or they have to approve the same action twice.
2433
+ await approvals.store.persist({
2434
+ ...existing,
2435
+ consumedAt: new Date().toISOString(),
2436
+ });
2437
+ }
2438
+ if (replayedFrom !== undefined && approved) {
2439
+ bus.publish({
2440
+ ...bus.envelope(),
2441
+ kind: "permission_decision",
2442
+ toolName: tu.name,
2443
+ decision: "allow",
2444
+ mode: permissionMode,
2445
+ reason: `approval ${replayedFrom.id} replayed: executing the APPROVED input, not the regenerated one`,
2446
+ });
2447
+ runContext.logger.info("tool approval replayed", {
2448
+ approvalId: replayedFrom.id,
2449
+ toolName: tu.name,
2450
+ detail: "the resumed turn regenerated a different input; the operator-approved input was executed instead",
2451
+ });
2452
+ // The durable `tool_use` record holds what the MODEL asked for —
2453
+ // correct, that is what the model did — but nothing yet recorded
2454
+ // what RAN, and an audit trail showing only the discarded input is
2455
+ // worse than one showing both.
2456
+ await logEvent("tool_use", {
2457
+ id: tu.id,
2458
+ name: tu.name,
2459
+ input: replayedFrom.input,
2460
+ approvalReplayedFrom: replayedFrom.id,
2461
+ requestedInput: tuAsRequested.input,
2462
+ });
2463
+ }
2125
2464
  }
2126
2465
  else if (existing?.decision === "deny") {
2127
2466
  approved = false;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * #405 — `ListTools`, the runtime's own toolset-introspection tool.
3
+ *
4
+ * The failure it exists for: a long-running session began on a build where
5
+ * certain tools were absent, and the agent (correctly, then) enumerated its
6
+ * toolset into the conversation. The daemon was rebuilt with the tools added
7
+ * and the session resumed — with the NEW definitions attached to every
8
+ * request — yet the agent kept insisting the tools were not in its schema,
9
+ * reproducing its own earlier enumeration as if freshly scanned and refusing
10
+ * to "fabricate" calls to tools it believed absent. The transcript prior beat
11
+ * the live schema, and no amount of arguing helped, because an operator's
12
+ * assertion is exactly as much hearsay as the transcript.
13
+ *
14
+ * A tool_result is not hearsay. `ListTools` returns the runtime's ACTUAL
15
+ * advertised toolset — the same list attached to this very request — so its
16
+ * output enters the transcript as runtime truth, which is the kind of
17
+ * evidence that overrides a stale in-transcript enumeration. It also gives
18
+ * operators a one-line remedy for the deadlock ("call ListTools") instead of
19
+ * deleting session history.
20
+ *
21
+ * Named in the runtime-bookkeeping family (`Skill`, `FocusRead`, `GoalList`,
22
+ * …) and allowed by {@link BUILTIN_BOOKKEEPING_RULES} for the same reason
23
+ * they are: under `permissionMode: "default"` an unruled tool falls back to
24
+ * `ask`, and an introspection tool that PARKS on approval in a headless
25
+ * daemon is useless for exactly the deadlock it exists to break.
26
+ *
27
+ * The name list is LATE-BOUND: the tool is built before the final advertised
28
+ * list exists (it is itself part of that list), so the provider is a thunk
29
+ * resolved at call time.
30
+ */
31
+ import type { RegisteredTool } from "@crewhaus/tool-catalog";
32
+ export declare const LIST_TOOLS_NAME = "ListTools";
33
+ /** One advertised tool, as `ListTools` reports it. */
34
+ export type AdvertisedToolSummary = {
35
+ readonly name: string;
36
+ readonly description: string;
37
+ readonly readOnly: boolean;
38
+ readonly destructive: boolean;
39
+ /** The tool carries the Pillar 3 justification gate. */
40
+ readonly gated: boolean;
41
+ };
42
+ /**
43
+ * Render the report. One line per tool, sorted by name, with a header that
44
+ * states WHAT this list is — the set advertised on the current request —
45
+ * because that provenance claim is the entire point.
46
+ */
47
+ export declare function renderToolList(tools: ReadonlyArray<AdvertisedToolSummary>): string;
48
+ /**
49
+ * Build the `ListTools` tool over a late-bound provider of the CURRENT
50
+ * advertised list. Read-only, side-effect-free, safe to call repeatedly.
51
+ */
52
+ export declare function buildListToolsTool(currentTools: () => ReadonlyArray<AdvertisedToolSummary>): RegisteredTool;
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ export const LIST_TOOLS_NAME = "ListTools";
3
+ /**
4
+ * Render the report. One line per tool, sorted by name, with a header that
5
+ * states WHAT this list is — the set advertised on the current request —
6
+ * because that provenance claim is the entire point.
7
+ */
8
+ export function renderToolList(tools) {
9
+ const sorted = [...tools].sort((a, b) => a.name.localeCompare(b.name));
10
+ const lines = [
11
+ `This is the runtime's live toolset — the ${sorted.length} tool(s) advertised on THIS request. It is read from the bound tool catalog, not from conversation history; if the conversation says otherwise, the conversation is stale.`,
12
+ "",
13
+ ];
14
+ for (const t of sorted) {
15
+ const flags = [
16
+ ...(t.readOnly ? ["read-only"] : []),
17
+ ...(t.destructive ? ["destructive"] : []),
18
+ ...(t.gated ? ["requires justification"] : []),
19
+ ];
20
+ const firstSentence = t.description.split(/(?<=[.!?])\s/)[0] ?? t.description;
21
+ lines.push(`- ${t.name}${flags.length > 0 ? ` [${flags.join(", ")}]` : ""} — ${firstSentence}`);
22
+ }
23
+ return lines.join("\n");
24
+ }
25
+ /**
26
+ * Build the `ListTools` tool over a late-bound provider of the CURRENT
27
+ * advertised list. Read-only, side-effect-free, safe to call repeatedly.
28
+ */
29
+ export function buildListToolsTool(currentTools) {
30
+ return {
31
+ name: LIST_TOOLS_NAME,
32
+ description: "List the toolset actually bound to this runtime right now — the authoritative answer to " +
33
+ '"which tools do I have?". Call this whenever the conversation and the tool schema seem to ' +
34
+ "disagree about available tools (for example after a resume): the result is runtime truth " +
35
+ "and overrides any earlier in-conversation enumeration.",
36
+ inputSchema: z.object({}).strict(),
37
+ execute: async () => renderToolList(currentTools()),
38
+ concurrencySafe: true,
39
+ readOnly: true,
40
+ destructive: false,
41
+ requiresSandbox: false,
42
+ requireJustification: false,
43
+ classifyOutput: true,
44
+ scope: "internal",
45
+ };
46
+ }
@@ -565,6 +565,9 @@ const WATCHME_MIRRORED_KIND_RECORD = {
565
565
  assistant_message: true,
566
566
  tool_use: true,
567
567
  tool_result: true,
568
+ // #405 — the per-run toolset record. Durable metadata (names only), and
569
+ // exactly the kind of runtime fact watch-me mirrors should carry.
570
+ toolset: true,
568
571
  error: true,
569
572
  run_failed: true,
570
573
  context_evicted: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/runtime-core",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "type": "module",
5
5
  "description": "Minimal runtime imported by generated harness bundles",
6
6
  "main": "dist/index.js",
@@ -16,45 +16,45 @@
16
16
  },
17
17
  "dependencies": {
18
18
  "@anthropic-ai/sdk": "^0.96.0",
19
- "@crewhaus/abort-controller": "0.5.3",
20
- "@crewhaus/adapter-anthropic": "0.5.3",
21
- "@crewhaus/agent-context-isolation": "0.5.3",
22
- "@crewhaus/boundary-classifier": "0.5.3",
23
- "@crewhaus/circuit-breaker": "0.5.3",
24
- "@crewhaus/compaction-autocompact": "0.5.3",
25
- "@crewhaus/compaction-curator": "0.5.3",
26
- "@crewhaus/compaction-snip": "0.5.3",
27
- "@crewhaus/cost-tracker": "0.5.3",
28
- "@crewhaus/egress-classifier": "0.5.3",
29
- "@crewhaus/errors": "0.5.3",
30
- "@crewhaus/event-log": "0.5.3",
31
- "@crewhaus/hooks-engine": "0.5.3",
32
- "@crewhaus/model-router": "0.5.3",
33
- "@crewhaus/permission-engine": "0.5.3",
34
- "@crewhaus/prompt-cache-manager": "0.5.3",
35
- "@crewhaus/prompt-injection-detector": "0.5.3",
36
- "@crewhaus/rate-limiter": "0.5.3",
37
- "@crewhaus/recovery-engine": "0.5.3",
38
- "@crewhaus/routing-store": "0.5.3",
39
- "@crewhaus/run-context": "0.5.3",
40
- "@crewhaus/session-store": "0.5.3",
41
- "@crewhaus/skills-registry": "0.5.3",
42
- "@crewhaus/slash-commands": "0.5.3",
43
- "@crewhaus/state-store": "0.5.3",
44
- "@crewhaus/tenancy": "0.5.3",
45
- "@crewhaus/token-budget": "0.5.3",
46
- "@crewhaus/tool-catalog": "0.5.3",
47
- "@crewhaus/tool-executor": "0.5.3",
48
- "@crewhaus/tool-loop-detection": "0.5.3",
49
- "@crewhaus/tool-orchestrator": "0.5.3",
50
- "@crewhaus/tool-result-store": "0.5.3",
51
- "@crewhaus/streaming-tool-executor": "0.5.3",
52
- "@crewhaus/turn-state-machine": "0.5.3",
53
- "@crewhaus/trace-event-bus": "0.5.3",
54
- "@crewhaus/worker-runtime": "0.5.3",
55
- "@crewhaus/structured-event-printer": "0.5.3",
56
- "@crewhaus/metrics-collector": "0.5.3",
57
- "@crewhaus/otel-exporter": "0.5.3",
19
+ "@crewhaus/abort-controller": "0.5.5",
20
+ "@crewhaus/adapter-anthropic": "0.5.5",
21
+ "@crewhaus/agent-context-isolation": "0.5.5",
22
+ "@crewhaus/boundary-classifier": "0.5.5",
23
+ "@crewhaus/circuit-breaker": "0.5.5",
24
+ "@crewhaus/compaction-autocompact": "0.5.5",
25
+ "@crewhaus/compaction-curator": "0.5.5",
26
+ "@crewhaus/compaction-snip": "0.5.5",
27
+ "@crewhaus/cost-tracker": "0.5.5",
28
+ "@crewhaus/egress-classifier": "0.5.5",
29
+ "@crewhaus/errors": "0.5.5",
30
+ "@crewhaus/event-log": "0.5.5",
31
+ "@crewhaus/hooks-engine": "0.5.5",
32
+ "@crewhaus/model-router": "0.5.5",
33
+ "@crewhaus/permission-engine": "0.5.5",
34
+ "@crewhaus/prompt-cache-manager": "0.5.5",
35
+ "@crewhaus/prompt-injection-detector": "0.5.5",
36
+ "@crewhaus/rate-limiter": "0.5.5",
37
+ "@crewhaus/recovery-engine": "0.5.5",
38
+ "@crewhaus/routing-store": "0.5.5",
39
+ "@crewhaus/run-context": "0.5.5",
40
+ "@crewhaus/session-store": "0.5.5",
41
+ "@crewhaus/skills-registry": "0.5.5",
42
+ "@crewhaus/slash-commands": "0.5.5",
43
+ "@crewhaus/state-store": "0.5.5",
44
+ "@crewhaus/tenancy": "0.5.5",
45
+ "@crewhaus/token-budget": "0.5.5",
46
+ "@crewhaus/tool-catalog": "0.5.5",
47
+ "@crewhaus/tool-executor": "0.5.5",
48
+ "@crewhaus/tool-loop-detection": "0.5.5",
49
+ "@crewhaus/tool-orchestrator": "0.5.5",
50
+ "@crewhaus/tool-result-store": "0.5.5",
51
+ "@crewhaus/streaming-tool-executor": "0.5.5",
52
+ "@crewhaus/turn-state-machine": "0.5.5",
53
+ "@crewhaus/trace-event-bus": "0.5.5",
54
+ "@crewhaus/worker-runtime": "0.5.5",
55
+ "@crewhaus/structured-event-printer": "0.5.5",
56
+ "@crewhaus/metrics-collector": "0.5.5",
57
+ "@crewhaus/otel-exporter": "0.5.5",
58
58
  "zod-to-json-schema": "^3.23.5"
59
59
  },
60
60
  "devDependencies": {