@crewhaus/runtime-core 0.5.4 → 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
@@ -487,6 +487,16 @@ export type RunChatLoopOptions = {
487
487
  * to the session JSON for future filtering. Defaults to `"cli"`.
488
488
  */
489
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;
490
500
  /**
491
501
  * Resume an existing session: load its metadata, replay its event log
492
502
  * into the message history (only `user_message` + `assistant_message`
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";
@@ -803,7 +804,18 @@ export async function runChatLoop(opts) {
803
804
  // Item 3 (G32) — resolve the advertised tool set ONCE, up front, folding in
804
805
  // any plugin-contributed tools so the tool-capable-model feature gate and the
805
806
  // per-turn advertisement below read the same list.
806
- 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)];
807
819
  // Pillar 3 — make the model-backed Layer-3 classifier reachable at EVERY
808
820
  // trust boundary (MCP / sub-agent / channel / federation / skill /
809
821
  // compaction / chain / orchestrator). Boundary call sites don't thread an
@@ -1117,6 +1129,9 @@ export async function runChatLoop(opts) {
1117
1129
  };
1118
1130
  let sessionId;
1119
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;
1120
1135
  // §2.3 — on resume, the requirements ledger rebuilds DETERMINISTICALLY
1121
1136
  // from the `context_evicted` events already on disk (dedup against
1122
1137
  // re-evictions happens at fold time): a resumed session recovers every
@@ -1130,18 +1145,50 @@ export async function runChatLoop(opts) {
1130
1145
  sessionId = existing.id;
1131
1146
  const replayLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
1132
1147
  resumedMessages = await replayMessageHistory(replayLog);
1133
- if (opts.continuity !== undefined && opts.continuity.ledger !== false) {
1134
- for await (const ev of replayLog.read()) {
1135
- 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)
1136
1169
  continue;
1137
1170
  const p = ev.payload;
1138
- if (p.role === "user" && typeof p.text === "string") {
1139
- resumedLedgerSeed.push({
1140
- role: "user",
1141
- text: p.text,
1142
- ...(typeof p.turnNumber === "number" ? { turnNumber: p.turnNumber } : {}),
1143
- });
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;
1144
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
+ });
1145
1192
  }
1146
1193
  }
1147
1194
  await replayLog.close();
@@ -1347,6 +1394,50 @@ export async function runChatLoop(opts) {
1347
1394
  out.write("\n");
1348
1395
  };
1349
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
+ }
1350
1441
  // Section 27 — mirror per-call cost_accrual events from the trace bus into
1351
1442
  // the session JSONL so `crewhaus cost-summary --session <id>` can sum spend
1352
1443
  // after the run. Gated on the same switch that attaches the cost-tracker
@@ -1873,6 +1964,17 @@ export async function runChatLoop(opts) {
1873
1964
  // gate's `justification` contract injected for `requireJustification`
1874
1965
  // tools whose own schema doesn't declare it (see `toAdvertisedTool`).
1875
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
+ }));
1876
1978
  const anthropicTools = advertisedTools.length > 0
1877
1979
  ? advertisedTools.map(({ tool, advertised }) => ({
1878
1980
  name: tool.name,
@@ -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.4",
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.4",
20
- "@crewhaus/adapter-anthropic": "0.5.4",
21
- "@crewhaus/agent-context-isolation": "0.5.4",
22
- "@crewhaus/boundary-classifier": "0.5.4",
23
- "@crewhaus/circuit-breaker": "0.5.4",
24
- "@crewhaus/compaction-autocompact": "0.5.4",
25
- "@crewhaus/compaction-curator": "0.5.4",
26
- "@crewhaus/compaction-snip": "0.5.4",
27
- "@crewhaus/cost-tracker": "0.5.4",
28
- "@crewhaus/egress-classifier": "0.5.4",
29
- "@crewhaus/errors": "0.5.4",
30
- "@crewhaus/event-log": "0.5.4",
31
- "@crewhaus/hooks-engine": "0.5.4",
32
- "@crewhaus/model-router": "0.5.4",
33
- "@crewhaus/permission-engine": "0.5.4",
34
- "@crewhaus/prompt-cache-manager": "0.5.4",
35
- "@crewhaus/prompt-injection-detector": "0.5.4",
36
- "@crewhaus/rate-limiter": "0.5.4",
37
- "@crewhaus/recovery-engine": "0.5.4",
38
- "@crewhaus/routing-store": "0.5.4",
39
- "@crewhaus/run-context": "0.5.4",
40
- "@crewhaus/session-store": "0.5.4",
41
- "@crewhaus/skills-registry": "0.5.4",
42
- "@crewhaus/slash-commands": "0.5.4",
43
- "@crewhaus/state-store": "0.5.4",
44
- "@crewhaus/tenancy": "0.5.4",
45
- "@crewhaus/token-budget": "0.5.4",
46
- "@crewhaus/tool-catalog": "0.5.4",
47
- "@crewhaus/tool-executor": "0.5.4",
48
- "@crewhaus/tool-loop-detection": "0.5.4",
49
- "@crewhaus/tool-orchestrator": "0.5.4",
50
- "@crewhaus/tool-result-store": "0.5.4",
51
- "@crewhaus/streaming-tool-executor": "0.5.4",
52
- "@crewhaus/turn-state-machine": "0.5.4",
53
- "@crewhaus/trace-event-bus": "0.5.4",
54
- "@crewhaus/worker-runtime": "0.5.4",
55
- "@crewhaus/structured-event-printer": "0.5.4",
56
- "@crewhaus/metrics-collector": "0.5.4",
57
- "@crewhaus/otel-exporter": "0.5.4",
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": {