@ouro.bot/cli 0.1.0-alpha.1373 → 0.1.0-alpha.1375

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/changelog.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1375",
6
+ "changes": [
7
+ "Senses: an iMessage turn can no longer wait forever to send; an iMessage turn that ends without a reply stays pending for replay or records a visible failure, and one the friend already heard from is never replayed; SIGTERM stops iMessage and Shepherd within 3 s; ouro status shows a reply stuck waiting to send."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1374",
12
+ "changes": [
13
+ "Every agent now loads tools through the Ouro AX tool catalog: eager doors up front and the rest through find_tools (Anthropic loads them natively with tool_reference), cutting tool-definition tokens per request by about 85%. OURO_DEFERRED_TOOLS is gone."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1373",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1373",
2
+ "runtimeVersion": "0.1.0-alpha.1375",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1373</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1375</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -27,7 +27,8 @@ const model_limits_1 = require("./model-limits");
27
27
  const source_grounding_1 = require("./source-grounding");
28
28
  const shelf_claims_1 = require("./shelf-claims");
29
29
  const reply_style_1 = require("./reply-style");
30
- const deferred_tools_1 = require("../repertoire/deferred-tools");
30
+ const tool_catalog_1 = require("../repertoire/tool-catalog");
31
+ const skill_summaries_1 = require("../repertoire/skill-summaries");
31
32
  const tools_1 = require("../repertoire/tools");
32
33
  const tools_base_1 = require("../repertoire/tools-base");
33
34
  const tools_flow_1 = require("../repertoire/tools-flow");
@@ -1527,6 +1528,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
1527
1528
  // This prevents stale provider caches from replaying prior-turn context.
1528
1529
  providerRuntime.resetTurnState(messages);
1529
1530
  const loadedDeferredTools = [];
1531
+ const ordinaryDefinitionsByName = new Map(toolSelection.ordinary.map((definition) => [definition.tool.function.name, definition]));
1530
1532
  while (!done) {
1531
1533
  // Channel-based tool filtering:
1532
1534
  // - Private runtime: exclude send_message (delivery via surface), observe (no one to observe)
@@ -1544,15 +1546,21 @@ async function runAgent(messages, callbacks, channel, signal, options) {
1544
1546
  const scopedOrdinaryActiveTools = relationshipToolNames
1545
1547
  ? unscopedOrdinaryActiveTools.filter((tool) => relationshipToolNames.includes(tool.function.name))
1546
1548
  : unscopedOrdinaryActiveTools;
1547
- // Deferred loading narrows only what is advertised; the scoped list above is still the authority on what may exist.
1548
- const deferralPossible = (0, deferred_tools_1.deferredToolLoadingEnabled)() && !options?.hardDisableTools && options?.toolProfile !== "sanctuary-health-private";
1549
+ // The catalog narrows only what is advertised; the scoped list above is still the authority on what may exist.
1550
+ // Doors whose card isn't eager wait for find_tools (or a skill that declares them).
1551
+ // A caller that hands the turn its own tool list has already chosen the menu, so only the default selection defers.
1552
+ const deferralPossible = !options?.hardDisableTools && options?.tools === undefined && options?.toolProfile !== "sanctuary-health-private";
1549
1553
  const deferralKeep = new Set(requiredToolCallNames);
1550
1554
  for (const effect of unresolvedHistoricalEffects)
1551
1555
  deferralKeep.add(effect.name);
1552
- const deferralPool = deferralPossible ? (0, deferred_tools_1.partitionTools)(scopedOrdinaryActiveTools, [], deferralKeep).deferred : [];
1553
- const deferralHistory = deferralPossible ? (0, deferred_tools_1.deferredNamesCalledInHistory)(messages, deferralPool) : [];
1556
+ const toolCatalog = (0, tool_catalog_1.buildToolCatalog)(scopedOrdinaryActiveTools.map((tool) => {
1557
+ const definition = ordinaryDefinitionsByName.get(tool.function.name);
1558
+ return { tool, ax: definition?.ax, mcpServer: definition?.mcpServer };
1559
+ }));
1560
+ const deferralPool = deferralPossible ? (0, tool_catalog_1.partitionCatalog)(scopedOrdinaryActiveTools, toolCatalog, [], deferralKeep).deferred : [];
1561
+ const deferralHistory = deferralPossible ? (0, tool_catalog_1.namesLoadedInHistory)(messages, new Set(deferralPool.map((tool) => tool.function.name))) : [];
1554
1562
  const ordinaryActiveTools = deferralPossible
1555
- ? (0, deferred_tools_1.partitionTools)(scopedOrdinaryActiveTools, [...new Set([...loadedDeferredTools, ...deferralHistory])], deferralKeep).active
1563
+ ? (0, tool_catalog_1.partitionCatalog)(scopedOrdinaryActiveTools, toolCatalog, [...new Set([...loadedDeferredTools, ...deferralHistory])], deferralKeep).active
1556
1564
  : scopedOrdinaryActiveTools;
1557
1565
  const candidateActiveTools = options?.hardDisableTools
1558
1566
  ? []
@@ -1644,6 +1652,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
1644
1652
  return await providerRuntime.streamTurn({
1645
1653
  messages: attemptMessages,
1646
1654
  activeTools,
1655
+ // A step narrowed to one tool (a step report, a forced repeat) sends no held-back doors either.
1656
+ ...(deferralPool.length > 0 && activeTools === candidateActiveTools ? { deferredTools: deferralPool } : {}),
1647
1657
  callbacks: turnCallbackBufferRef.current?.callbacks ?? callbacks,
1648
1658
  signal,
1649
1659
  traceId,
@@ -2042,11 +2052,21 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2042
2052
  // Reset the retry counter on any successful tool call.
2043
2053
  noToolCallRetries = 0;
2044
2054
  const preCallMessages = structuredClone(messages.filter((message) => message.role !== "system"));
2045
- const validatedCalls = validateToolCallBatchAtProductionBoundary(result.toolCalls, activeTools);
2055
+ // A held-back door called by name (find_tools's description lists every one) counts as found: it is checked
2056
+ // against its own schema, runs, and stays loaded. A step narrowed to one tool admits none.
2057
+ const calledHeldBack = activeTools === candidateActiveTools
2058
+ ? deferralPool.filter((tool) => !activeToolNames.has(tool.function.name) && result.toolCalls.some((call) => call.name === tool.function.name))
2059
+ : [];
2060
+ // Not advertised means not yet loaded, so each is new to the loaded list.
2061
+ for (const tool of calledHeldBack)
2062
+ loadedDeferredTools.push(tool.function.name);
2063
+ const callableTools = [...activeTools, ...calledHeldBack];
2064
+ const callableToolNames = new Set(callableTools.map((tool) => tool.function.name));
2065
+ const validatedCalls = validateToolCallBatchAtProductionBoundary(result.toolCalls, callableTools);
2046
2066
  const invalidCall = validatedCalls.find((entry) => "error" in entry);
2047
2067
  if (invalidCall) {
2048
2068
  streamCallbackBuffer?.discard();
2049
- const unadvertisedCall = validatedCalls.find((entry) => !activeToolNames.has(entry.call.name));
2069
+ const unadvertisedCall = validatedCalls.find((entry) => !callableToolNames.has(entry.call.name));
2050
2070
  const rejections = [];
2051
2071
  for (const entry of validatedCalls) {
2052
2072
  const detail = "error" in entry ? entry.error : "another call in this batch had invalid arguments";
@@ -2056,7 +2076,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2056
2076
  rejections.push(rejection);
2057
2077
  options?.toolBoundaryObserver?.({
2058
2078
  name: entry.call.name,
2059
- reason: activeToolNames.has(entry.call.name) ? "invalid_arguments" : "profile_excluded",
2079
+ reason: callableToolNames.has(entry.call.name) ? "invalid_arguments" : "profile_excluded",
2060
2080
  globallyResolvable: typeof (0, tools_1.resolveToolDefinition)(entry.call.name)?.handler === "function",
2061
2081
  invoked: false,
2062
2082
  sideEffect: false,
@@ -2090,7 +2110,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2090
2110
  ]));
2091
2111
  const preflightRejections = new Map();
2092
2112
  for (const entry of validCalls) {
2093
- if (entry.call.name === deferred_tools_1.FIND_TOOLS_NAME)
2113
+ if (entry.call.name === tool_catalog_1.FIND_TOOLS_NAME)
2094
2114
  continue;
2095
2115
  if (!relationship && !toolSelection.engine.some((tool) => tool.function.name === entry.call.name))
2096
2116
  continue;
@@ -2516,21 +2536,23 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2516
2536
  if (tc.name === "send_message" && args.friendId === "self") {
2517
2537
  sawSendMessageSelf = true;
2518
2538
  }
2519
- if (tc.name === deferred_tools_1.FIND_TOOLS_NAME) {
2539
+ if (tc.name === tool_catalog_1.FIND_TOOLS_NAME) {
2520
2540
  // The pre-batch schema gate guarantees a string query.
2521
2541
  const query = args.query;
2522
- callbacks.onToolStart(deferred_tools_1.FIND_TOOLS_NAME, { query });
2523
- const matched = (0, deferred_tools_1.searchDeferredTools)(deferralPool, query);
2524
- for (const tool of matched)
2525
- if (!loadedDeferredTools.includes(tool.function.name))
2526
- loadedDeferredTools.push(tool.function.name);
2527
- const found = (0, deferred_tools_1.formatFindToolsResult)(matched);
2542
+ callbacks.onToolStart(tool_catalog_1.FIND_TOOLS_NAME, { query });
2543
+ const matchedNames = (0, tool_catalog_1.searchCatalog)(toolCatalog, deferralPool, query);
2544
+ const matched = deferralPool.filter((tool) => matchedNames.includes(tool.function.name))
2545
+ .sort((a, b) => matchedNames.indexOf(a.function.name) - matchedNames.indexOf(b.function.name));
2546
+ for (const name of matchedNames)
2547
+ if (!loadedDeferredTools.includes(name))
2548
+ loadedDeferredTools.push(name);
2549
+ const found = (0, tool_catalog_1.formatLoadedDoors)(matched);
2528
2550
  pushGenerated({ role: "tool", tool_call_id: tc.id, content: found });
2529
2551
  providerRuntime.appendToolOutput(tc.id, found);
2530
2552
  if (matched.length > 0)
2531
2553
  lastIterationMadeProgress = true;
2532
- callbacks.onToolEnd(deferred_tools_1.FIND_TOOLS_NAME, query, matched.length > 0);
2533
- (0, deferred_tools_1.recordDeferredToolsLoaded)(query, matched);
2554
+ callbacks.onToolEnd(tool_catalog_1.FIND_TOOLS_NAME, query, matched.length > 0);
2555
+ (0, tool_catalog_1.recordFindTools)({ query, matched: matched.length, deferred: deferralPool.length });
2534
2556
  continue;
2535
2557
  }
2536
2558
  if (tc.name === "speak") {
@@ -2780,6 +2802,16 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2780
2802
  toolResult = `error: ${e}`;
2781
2803
  success = false;
2782
2804
  }
2805
+ if (success && tc.name === "load_skill") {
2806
+ // A skill names the doors its steps use; they load with it so the agent needn't find them one by one.
2807
+ const declared = (0, skill_summaries_1.declaredTools)(toolResult);
2808
+ const skillDoors = deferralPool.filter((tool) => declared.includes(tool.function.name));
2809
+ for (const tool of skillDoors)
2810
+ if (!loadedDeferredTools.includes(tool.function.name))
2811
+ loadedDeferredTools.push(tool.function.name);
2812
+ if (skillDoors.length > 0)
2813
+ toolResult = `${toolResult}\n\n${(0, tool_catalog_1.formatLoadedDoors)(skillDoors)}`;
2814
+ }
2783
2815
  if (success && toolImages.length > 0) {
2784
2816
  const visible = (0, tool_images_1.canModelSeeToolImages)(providerRuntime.model);
2785
2817
  toolResult = `${toolResult}${toolResult ? "\n\n" : ""}${(0, tool_images_1.toolImagesNote)(toolImages.length, providerRuntime.model, visible)}`;
@@ -38,6 +38,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.toAnthropicMessages = toAnthropicMessages;
40
40
  exports.toAnthropicTools = toAnthropicTools;
41
+ exports.anthropicToolPlan = anthropicToolPlan;
41
42
  exports.classifyAnthropicError = classifyAnthropicError;
42
43
  exports.withoutThinkingBlocks = withoutThinkingBlocks;
43
44
  exports.createAnthropicProviderRuntime = createAnthropicProviderRuntime;
@@ -227,6 +228,21 @@ function toAnthropicTools(tools, deferred = new Set()) {
227
228
  };
228
229
  });
229
230
  }
231
+ /**
232
+ * The tools an Anthropic request sends: the loaded ones, then every held-back door marked deferred, in one fixed order,
233
+ * so loading a door never changes the tool list (the front of the cached prefix). A door `find_tools` loaded stays
234
+ * deferred and is loaded by its `tool_reference`; a held-back door the engine made callable another way (a skill that
235
+ * declares it, a call from an earlier turn) has no reference, so it is sent loaded.
236
+ */
237
+ function anthropicToolPlan(activeTools, deferredTools = [], messages) {
238
+ const pool = new Set(deferredTools.map((tool) => tool.function.name));
239
+ const found = new Set((0, tool_catalog_1.doorsFoundInHistory)(messages));
240
+ const callable = new Set(activeTools.map((tool) => tool.function.name));
241
+ return {
242
+ tools: [...activeTools.filter((tool) => !pool.has(tool.function.name)), ...deferredTools],
243
+ deferred: new Set([...pool].filter((name) => !callable.has(name) || found.has(name))),
244
+ };
245
+ }
230
246
  function toAnthropicUsage(raw) {
231
247
  const inputTokens = Number(raw.input_tokens ?? 0) || 0;
232
248
  const cacheCreateTokens = Number(raw.cache_creation_input_tokens ?? 0) || 0;
@@ -307,13 +323,14 @@ function withoutThinkingBlocks(messages) {
307
323
  });
308
324
  }
309
325
  async function streamAnthropicMessages(client, model, request, options = { claudeCodePreamble: true }) {
310
- const { system, messages } = toAnthropicMessages(request.messages);
326
+ const toolPlan = anthropicToolPlan(request.activeTools, request.deferredTools, request.messages);
327
+ const { system, messages } = toAnthropicMessages(request.messages, { toolReferences: toolPlan.deferred });
311
328
  const additionalSystemParts = request.messages
312
329
  .filter((message) => message.role === "system")
313
330
  .slice(1)
314
331
  .map((message) => toAnthropicTextContent(message.content).trim())
315
332
  .filter((text) => text.length > 0);
316
- const anthropicTools = toAnthropicTools(request.activeTools);
333
+ const anthropicTools = toAnthropicTools(toolPlan.tools, toolPlan.deferred);
317
334
  const modelCaps = (0, model_capabilities_1.getModelCapabilities)(model);
318
335
  const maxTokens = modelCaps.maxOutputTokens ?? 16384;
319
336
  const params = {
@@ -5,15 +5,63 @@ const node_async_hooks_1 = require("node:async_hooks");
5
5
  const runtime_1 = require("../nerves/runtime");
6
6
  const leaseContext = new node_async_hooks_1.AsyncLocalStorage();
7
7
  let queueTail = Promise.resolve();
8
- async function withTurnExecutionLease(work) {
8
+ /** Turns holding or waiting for the lease. */
9
+ let queuedTurns = 0;
10
+ function untilReadyOrAborted(previous, signal) {
11
+ return new Promise((resolve, reject) => {
12
+ if (signal.aborted) {
13
+ reject(signal.reason);
14
+ return;
15
+ }
16
+ const onAbort = () => reject(signal.reason);
17
+ signal.addEventListener("abort", onAbort, { once: true });
18
+ void previous.then(() => {
19
+ signal.removeEventListener("abort", onAbort);
20
+ resolve();
21
+ });
22
+ });
23
+ }
24
+ /**
25
+ * Run `work` once every turn queued ahead of it has finished. With a signal,
26
+ * an abort (turn deadline, supersession, shutdown) ends the wait instead of
27
+ * leaving the turn queued behind one that may never finish. A turn that finds
28
+ * the lease free runs as before, whatever its signal says.
29
+ */
30
+ async function withTurnExecutionLease(work, signal) {
9
31
  if (leaseContext.getStore())
10
32
  return work();
11
- let release;
33
+ let resolveTail;
12
34
  const previous = queueTail;
35
+ const mustWait = queuedTurns > 0;
36
+ queuedTurns += 1;
13
37
  queueTail = new Promise((resolve) => {
14
- release = resolve;
38
+ resolveTail = resolve;
15
39
  });
16
- await previous;
40
+ const release = () => {
41
+ queuedTurns -= 1;
42
+ resolveTail();
43
+ };
44
+ if (signal && mustWait) {
45
+ try {
46
+ await untilReadyOrAborted(previous, signal);
47
+ }
48
+ catch (error) {
49
+ // Give up this place in line only when the turn ahead ends, so the turn
50
+ // behind still runs after it rather than alongside it.
51
+ void previous.then(release);
52
+ (0, runtime_1.emitNervesEvent)({
53
+ level: "warn",
54
+ component: "heart",
55
+ event: "heart.turn_execution_lease_abandoned",
56
+ message: "turn stopped waiting for the turn ahead of it",
57
+ meta: { reason: error instanceof Error ? error.message : String(error) },
58
+ });
59
+ throw error;
60
+ }
61
+ }
62
+ else {
63
+ await previous;
64
+ }
17
65
  (0, runtime_1.emitNervesEvent)({
18
66
  component: "heart",
19
67
  event: "heart.turn_execution_lease_acquired",
@@ -1,12 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TURN_TOOL_NAMES = exports.FIND_TOOLS_NAME = void 0;
3
+ exports.findToolsDefinition = exports.TURN_TOOL_NAMES = exports.FIND_TOOLS_NAME = void 0;
4
4
  exports.catalogDoor = catalogDoor;
5
5
  exports.buildToolCatalog = buildToolCatalog;
6
6
  exports.searchCatalog = searchCatalog;
7
7
  exports.formatLoadedDoors = formatLoadedDoors;
8
8
  exports.loadedDoorNames = loadedDoorNames;
9
+ exports.partitionCatalog = partitionCatalog;
10
+ exports.buildFindToolsSchema = buildFindToolsSchema;
11
+ exports.doorsFoundInHistory = doorsFoundInHistory;
12
+ exports.namesLoadedInHistory = namesLoadedInHistory;
13
+ exports.recordFindTools = recordFindTools;
9
14
  const runtime_1 = require("../nerves/runtime");
15
+ const tool_error_code_1 = require("./tool-error-code");
10
16
  /** The door that loads deferred doors on every provider. */
11
17
  exports.FIND_TOOLS_NAME = "find_tools";
12
18
  /** The engine's turn tools: a turn can't end, think or reply without them, so they are never deferred. */
@@ -26,7 +32,8 @@ function catalogDoor(source) {
26
32
  group: card?.group ?? (source.mcpServer ? `mcp:${source.mcpServer}` : "other"),
27
33
  when: card?.when ?? firstSentence(source.tool.function.description ?? ""),
28
34
  effect: card?.effect ?? "write",
29
- eager: exports.TURN_TOOL_NAMES.has(name) || card?.eager === true,
35
+ // A door with neither a card nor an MCP server came straight from the caller and can't be described for search.
36
+ eager: exports.TURN_TOOL_NAMES.has(name) || card?.eager === true || (!card && !source.mcpServer),
30
37
  };
31
38
  }
32
39
  /** Builds the catalog for the doors selected this turn; groups keep their census `when` line, or none if unknown. */
@@ -101,7 +108,7 @@ function signature(tool) {
101
108
  /** `find_tools`'s reply: the doors it loaded, one per line, or how to try again. */
102
109
  function formatLoadedDoors(loaded) {
103
110
  if (loaded.length === 0)
104
- return "no matching tools. try different words, or select:name1,name2 using a name from the list in find_tools.";
111
+ return (0, tool_error_code_1.withCode)("no matching tools. try different words, or select:name1,name2 using a name from the list in find_tools.", "no-matching-tools");
105
112
  return `${LOADED_HEADER}\n${loaded.map((tool) => `- ${tool.function.name}(${signature(tool)}): ${tool.function.description ?? ""}`).join("\n")}`;
106
113
  }
107
114
  /** The door names a `find_tools` reply loaded, read back from its text so the reply itself stays the record. */
@@ -110,3 +117,90 @@ function loadedDoorNames(reply) {
110
117
  return [];
111
118
  return reply.split("\n").slice(1).flatMap((line) => /^- ([A-Za-z0-9_-]+)\(/.exec(line)?.[1] ?? []);
112
119
  }
120
+ /**
121
+ * Splits a turn's doors. Eager doors, names in `keep` and doors the catalog doesn't know stay in canonical order;
122
+ * `find_tools` follows when anything is held back, then loaded doors in the order they were loaded, so the request's
123
+ * tool list only grows at its end.
124
+ */
125
+ function partitionCatalog(tools, catalog, loaded, keep) {
126
+ const doors = new Map(catalog.doors.map((door) => [door.name, door]));
127
+ const held = (name) => !keep.has(name) && doors.get(name)?.eager === false;
128
+ const kept = tools.filter((tool) => !held(tool.function.name));
129
+ const deferred = tools.filter((tool) => held(tool.function.name));
130
+ if (deferred.length === 0)
131
+ return { active: kept, deferred };
132
+ const loadedTools = loaded.flatMap((name) => deferred.filter((tool) => tool.function.name === name));
133
+ return { active: [...kept, buildFindToolsSchema(deferred, catalog), ...loadedTools], deferred };
134
+ }
135
+ /** `find_tools`'s schema; its description names every held-back door by catalog group, so a select needs no search. */
136
+ function buildFindToolsSchema(deferred, catalog) {
137
+ const groupOf = new Map(catalog.doors.map((door) => [door.name, door.group]));
138
+ const groups = new Map();
139
+ for (const tool of deferred) {
140
+ const group = groupOf.get(tool.function.name) ?? "other";
141
+ groups.set(group, [...(groups.get(group) ?? []), tool.function.name]);
142
+ }
143
+ const listing = [...groups.entries()].map(([group, names]) => `${group}: ${names.join(", ")}`).join("; ");
144
+ return {
145
+ type: "function",
146
+ function: {
147
+ name: exports.FIND_TOOLS_NAME,
148
+ description: `more tools exist than are listed. call find_tools with a short query (what you need to do) or select:name1,name2 to load them; they become callable on your next step. not loaded now, by group: ${listing}`,
149
+ parameters: {
150
+ type: "object",
151
+ properties: { query: { type: "string", description: "what you need, or select:name1,name2" } },
152
+ required: ["query"],
153
+ },
154
+ },
155
+ };
156
+ }
157
+ /** Doors that `find_tools` replies in the conversation loaded, once each, in order. */
158
+ function doorsFoundInHistory(messages) {
159
+ return scanHistory(messages, false);
160
+ }
161
+ /** Held-back doors the conversation already called or loaded with `find_tools`, so a later turn needn't find them again. */
162
+ function namesLoadedInHistory(messages, pool) {
163
+ return scanHistory(messages, true).filter((name) => pool.has(name));
164
+ }
165
+ function scanHistory(messages, withCalls) {
166
+ const names = [];
167
+ const add = (name) => { if (!names.includes(name))
168
+ names.push(name); };
169
+ const findCalls = new Set();
170
+ for (const message of messages) {
171
+ if (message.role === "assistant") {
172
+ for (const call of message.tool_calls ?? []) {
173
+ /* v8 ignore next -- type narrowing: the engine only records function tool calls @preserve */
174
+ if (call.type !== "function")
175
+ continue;
176
+ if (call.function.name === exports.FIND_TOOLS_NAME)
177
+ findCalls.add(call.id);
178
+ else if (withCalls)
179
+ add(call.function.name);
180
+ }
181
+ }
182
+ else if (message.role === "tool" && findCalls.has(message.tool_call_id) && typeof message.content === "string") {
183
+ for (const name of loadedDoorNames(message.content))
184
+ add(name);
185
+ }
186
+ }
187
+ return names;
188
+ }
189
+ /** One `find_tools` search, as counts: never the query text, which can carry what the person asked for. */
190
+ function recordFindTools(search) {
191
+ (0, runtime_1.emitNervesEvent)({
192
+ component: "repertoire", event: "repertoire.find_tools_searched", message: "find_tools searched the held-back doors",
193
+ meta: { select: search.query.trim().toLowerCase().startsWith("select:"), matched: search.matched, deferred: search.deferred },
194
+ });
195
+ }
196
+ /**
197
+ * find_tools's Ouro AX card and risk profile. The engine runs find_tools itself, so this is a declaration rather than
198
+ * a dispatched definition: loading a door changes only which schemas this turn sends.
199
+ */
200
+ exports.findToolsDefinition = {
201
+ tool: buildFindToolsSchema([], { doors: [], groups: [] }),
202
+ riskProfile: { mutates: "none", risk: "low" },
203
+ ax: { id: "tool:find_tools", group: "turn-skills", when: "Pick this when the tool you need isn't in your list; it searches the tools held back from this turn and makes the matches callable.", effect: "read", idempotent: true, errors: [
204
+ { code: "no-matching-tools", means: "No held-back tool matched the query, so nothing was loaded.", fix: "Try other words for the job, or select:name1,name2 with names from the find_tools list." },
205
+ ] },
206
+ };
@@ -33,8 +33,10 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS = void 0;
36
37
  exports.beginBlueBubblesActiveTurn = beginBlueBubblesActiveTurn;
37
38
  exports.noteBlueBubblesActiveTurnVisibleActivity = noteBlueBubblesActiveTurnVisibleActivity;
39
+ exports.noteBlueBubblesActiveTurnAdmissionWait = noteBlueBubblesActiveTurnAdmissionWait;
38
40
  exports.finishBlueBubblesActiveTurn = finishBlueBubblesActiveTurn;
39
41
  exports.listBlueBubblesActiveTurns = listBlueBubblesActiveTurns;
40
42
  exports.snapshotBlueBubblesActiveTurns = snapshotBlueBubblesActiveTurns;
@@ -43,6 +45,8 @@ const path = __importStar(require("node:path"));
43
45
  const config_1 = require("../../heart/config");
44
46
  const identity_1 = require("../../heart/identity");
45
47
  const runtime_1 = require("../../nerves/runtime");
48
+ /** A reply waiting this long for permission to send counts as a stalled turn. */
49
+ exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS = 60_000;
46
50
  function activeTurnsDir(agentName) {
47
51
  return path.join((0, identity_1.getAgentRoot)(agentName), "state", "senses", "bluebubbles", "active-turns");
48
52
  }
@@ -72,6 +76,9 @@ function parseActiveTurn(raw) {
72
76
  lastVisibleActivityAt: typeof parsed.lastVisibleActivityAt === "string"
73
77
  ? parsed.lastVisibleActivityAt
74
78
  : undefined,
79
+ admissionWaitingSince: typeof parsed.admissionWaitingSince === "string"
80
+ ? parsed.admissionWaitingSince
81
+ : undefined,
75
82
  messageGuid: parsed.messageGuid,
76
83
  sessionKey: parsed.sessionKey,
77
84
  chatGuid: parsed.chatGuid ?? null,
@@ -116,6 +123,13 @@ function beginBlueBubblesActiveTurn(agentName, event) {
116
123
  return turnId;
117
124
  }
118
125
  function noteBlueBubblesActiveTurnVisibleActivity(agentName, turnId) {
126
+ updateActiveTurn(agentName, turnId, (entry) => ({ ...entry, lastVisibleActivityAt: new Date().toISOString() }));
127
+ }
128
+ /** Marks (or, with null, clears) a turn whose reply is stuck waiting for permission to send. */
129
+ function noteBlueBubblesActiveTurnAdmissionWait(agentName, turnId, waitingSince) {
130
+ updateActiveTurn(agentName, turnId, ({ admissionWaitingSince: _cleared, ...entry }) => (waitingSince ? { ...entry, admissionWaitingSince: waitingSince } : entry));
131
+ }
132
+ function updateActiveTurn(agentName, turnId, update) {
119
133
  const filePath = activeTurnPath(agentName, turnId);
120
134
  let entry = null;
121
135
  try {
@@ -127,7 +141,7 @@ function noteBlueBubblesActiveTurnVisibleActivity(agentName, turnId) {
127
141
  if (!entry)
128
142
  return;
129
143
  try {
130
- fs.writeFileSync(filePath, JSON.stringify({ ...entry, lastVisibleActivityAt: new Date().toISOString() }, null, 2) + "\n", "utf-8");
144
+ fs.writeFileSync(filePath, JSON.stringify(update(entry), null, 2) + "\n", "utf-8");
131
145
  }
132
146
  catch (error) {
133
147
  (0, runtime_1.emitNervesEvent)({
@@ -207,9 +221,20 @@ function snapshotBlueBubblesActiveTurns(agentName, stalledAfterMs, nowMs = Date.
207
221
  .filter((entry) => Number.isFinite(entry.ms))
208
222
  .sort((left, right) => left.ms - right.ms);
209
223
  const oldest = started[0];
224
+ const admissionWaitAges = entries
225
+ .map((entry) => nowMs - Date.parse(entry.admissionWaitingSince ?? ""))
226
+ .filter((ageMs) => Number.isFinite(ageMs) && ageMs >= exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS);
227
+ const stalledTurns = entries.filter((entry) => {
228
+ const startedMs = Date.parse(entry.startedAt);
229
+ const waitingMs = Date.parse(entry.admissionWaitingSince ?? "");
230
+ return (Number.isFinite(startedMs) && nowMs - startedMs >= stalledAfterMs)
231
+ || (Number.isFinite(waitingMs) && nowMs - waitingMs >= exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS);
232
+ });
210
233
  return {
211
234
  activeTurnCount: entries.length,
212
- stalledTurnCount: started.filter((entry) => nowMs - entry.ms >= stalledAfterMs).length,
235
+ stalledTurnCount: stalledTurns.length,
236
+ admissionStalledTurnCount: admissionWaitAges.length,
237
+ ...(admissionWaitAges.length > 0 ? { oldestAdmissionWaitAgeMs: Math.max(...admissionWaitAges) } : {}),
213
238
  oldestActiveTurnStartedAt: oldest?.value,
214
239
  oldestActiveTurnAgeMs: oldest ? Math.max(0, nowMs - oldest.ms) : undefined,
215
240
  };
@@ -60,21 +60,10 @@ Promise.resolve().then(() => __importStar(require("../../heart/runtime-credentia
60
60
  if (!machineConfig.ok) {
61
61
  await refreshMachineRuntimeCredentialConfig(agentName, machine.machineId, { preserveCachedOnFailure: true }).catch(() => undefined);
62
62
  }
63
- const { startBlueBubblesApp } = await Promise.resolve().then(() => __importStar(require("./index")));
64
- const server = await startBlueBubblesApp();
65
- let shutdownStarted = false;
66
- const closeOnSignal = () => {
67
- if (shutdownStarted)
68
- return;
69
- shutdownStarted = true;
70
- server.close();
71
- };
72
- process.once("SIGTERM", closeOnSignal);
73
- process.once("SIGINT", closeOnSignal);
74
- server.once("close", () => {
75
- process.removeListener("SIGTERM", closeOnSignal);
76
- process.removeListener("SIGINT", closeOnSignal);
77
- });
63
+ const { startBlueBubblesApp, stopBlueBubblesApp } = await Promise.resolve().then(() => __importStar(require("./index")));
64
+ const { installSenseShutdown } = await Promise.resolve().then(() => __importStar(require("../sense-shutdown")));
65
+ const server = startBlueBubblesApp();
66
+ installSenseShutdown({ sense: "bluebubbles", stop: () => stopBlueBubblesApp(server) });
78
67
  void refreshRuntimeCredentialConfig(agentName, { preserveCachedOnFailure: true }).catch(() => undefined);
79
68
  })
80
69
  .catch((error) => {