@senpi-ai/runtime 3.0.179 → 3.0.189

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.
Files changed (212) hide show
  1. package/dist/actions/close-position/close-position.action.d.ts.map +1 -1
  2. package/dist/actions/close-position/close-position.action.js +1 -6
  3. package/dist/actions/close-position/close-position.action.js.map +1 -1
  4. package/dist/actions/llm-decision/openclaw-llm-decision.d.ts +8 -0
  5. package/dist/actions/llm-decision/openclaw-llm-decision.d.ts.map +1 -1
  6. package/dist/actions/llm-decision/openclaw-llm-decision.js +56 -1
  7. package/dist/actions/llm-decision/openclaw-llm-decision.js.map +1 -1
  8. package/dist/actions/position-tracker/position-tracker.action.d.ts.map +1 -1
  9. package/dist/actions/position-tracker/position-tracker.action.js +0 -1
  10. package/dist/actions/position-tracker/position-tracker.action.js.map +1 -1
  11. package/dist/approvals/approval-store.d.ts +37 -7
  12. package/dist/approvals/approval-store.d.ts.map +1 -1
  13. package/dist/approvals/approval-store.js +127 -23
  14. package/dist/approvals/approval-store.js.map +1 -1
  15. package/dist/approvals/telemetry.d.ts +28 -3
  16. package/dist/approvals/telemetry.d.ts.map +1 -1
  17. package/dist/approvals/telemetry.js +8 -4
  18. package/dist/approvals/telemetry.js.map +1 -1
  19. package/dist/approvals/tool-approval-gate.d.ts +85 -0
  20. package/dist/approvals/tool-approval-gate.d.ts.map +1 -1
  21. package/dist/approvals/tool-approval-gate.js +197 -15
  22. package/dist/approvals/tool-approval-gate.js.map +1 -1
  23. package/dist/approvals/turn-context.d.ts +296 -0
  24. package/dist/approvals/turn-context.d.ts.map +1 -0
  25. package/dist/approvals/turn-context.js +594 -0
  26. package/dist/approvals/turn-context.js.map +1 -0
  27. package/dist/cli/guide-commands.d.ts.map +1 -1
  28. package/dist/cli/guide-commands.js +18 -3
  29. package/dist/cli/guide-commands.js.map +1 -1
  30. package/dist/cli/senpi-commands.d.ts.map +1 -1
  31. package/dist/cli/senpi-commands.js +80 -5
  32. package/dist/cli/senpi-commands.js.map +1 -1
  33. package/dist/deploy/job.d.ts +32 -0
  34. package/dist/deploy/job.d.ts.map +1 -1
  35. package/dist/deploy/job.js +72 -7
  36. package/dist/deploy/job.js.map +1 -1
  37. package/dist/deploy/register.d.ts +12 -0
  38. package/dist/deploy/register.d.ts.map +1 -1
  39. package/dist/deploy/register.js +85 -2
  40. package/dist/deploy/register.js.map +1 -1
  41. package/dist/dsl/events/build-closed-event.d.ts +0 -11
  42. package/dist/dsl/events/build-closed-event.d.ts.map +1 -1
  43. package/dist/dsl/events/build-closed-event.js +0 -13
  44. package/dist/dsl/events/build-closed-event.js.map +1 -1
  45. package/dist/dsl/events/handlers.d.ts.map +1 -1
  46. package/dist/dsl/events/handlers.js +5 -9
  47. package/dist/dsl/events/handlers.js.map +1 -1
  48. package/dist/dsl/monitor/dsl-failure-events.d.ts +38 -2
  49. package/dist/dsl/monitor/dsl-failure-events.d.ts.map +1 -1
  50. package/dist/dsl/monitor/dsl-failure-events.js +67 -4
  51. package/dist/dsl/monitor/dsl-failure-events.js.map +1 -1
  52. package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
  53. package/dist/dsl/monitor/process-one-position.js +33 -13
  54. package/dist/dsl/monitor/process-one-position.js.map +1 -1
  55. package/dist/host/openclaw-host.d.ts +138 -0
  56. package/dist/host/openclaw-host.d.ts.map +1 -0
  57. package/dist/host/openclaw-host.js +177 -0
  58. package/dist/host/openclaw-host.js.map +1 -0
  59. package/dist/host/plugin-logger.d.ts +99 -0
  60. package/dist/host/plugin-logger.d.ts.map +1 -0
  61. package/dist/host/plugin-logger.js +142 -0
  62. package/dist/host/plugin-logger.js.map +1 -0
  63. package/dist/index.d.ts +56 -8
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +688 -177
  66. package/dist/index.js.map +1 -1
  67. package/dist/prompt/session-context-seed-hook.d.ts +0 -7
  68. package/dist/prompt/session-context-seed-hook.d.ts.map +1 -1
  69. package/dist/prompt/session-context-seed-hook.js +1 -1
  70. package/dist/prompt/session-context-seed-hook.js.map +1 -1
  71. package/dist/runtime/auto-update/coordinator.d.ts +220 -0
  72. package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
  73. package/dist/runtime/auto-update/coordinator.js +715 -22
  74. package/dist/runtime/auto-update/coordinator.js.map +1 -1
  75. package/dist/runtime/auto-update/gateway-restart.d.ts +60 -1
  76. package/dist/runtime/auto-update/gateway-restart.d.ts.map +1 -1
  77. package/dist/runtime/auto-update/gateway-restart.js +95 -21
  78. package/dist/runtime/auto-update/gateway-restart.js.map +1 -1
  79. package/dist/runtime/auto-update/idle-gate.d.ts +175 -0
  80. package/dist/runtime/auto-update/idle-gate.d.ts.map +1 -0
  81. package/dist/runtime/auto-update/idle-gate.js +229 -0
  82. package/dist/runtime/auto-update/idle-gate.js.map +1 -0
  83. package/dist/runtime/auto-update/install-results.d.ts +130 -0
  84. package/dist/runtime/auto-update/install-results.d.ts.map +1 -0
  85. package/dist/runtime/auto-update/install-results.js +264 -0
  86. package/dist/runtime/auto-update/install-results.js.map +1 -0
  87. package/dist/runtime/auto-update/money-call-tracker.d.ts +36 -0
  88. package/dist/runtime/auto-update/money-call-tracker.d.ts.map +1 -0
  89. package/dist/runtime/auto-update/money-call-tracker.js +129 -0
  90. package/dist/runtime/auto-update/money-call-tracker.js.map +1 -0
  91. package/dist/runtime/auto-update/register-idle-gate.d.ts +70 -0
  92. package/dist/runtime/auto-update/register-idle-gate.d.ts.map +1 -0
  93. package/dist/runtime/auto-update/register-idle-gate.js +127 -0
  94. package/dist/runtime/auto-update/register-idle-gate.js.map +1 -0
  95. package/dist/runtime/auto-update/run-update-command.d.ts +13 -0
  96. package/dist/runtime/auto-update/run-update-command.d.ts.map +1 -1
  97. package/dist/runtime/auto-update/run-update-command.js +18 -0
  98. package/dist/runtime/auto-update/run-update-command.js.map +1 -1
  99. package/dist/runtime/auto-update/state-store.d.ts +14 -1
  100. package/dist/runtime/auto-update/state-store.d.ts.map +1 -1
  101. package/dist/runtime/auto-update/state-store.js +37 -3
  102. package/dist/runtime/auto-update/state-store.js.map +1 -1
  103. package/dist/runtime/auto-update/types.d.ts +52 -0
  104. package/dist/runtime/auto-update/types.d.ts.map +1 -1
  105. package/dist/runtime/auto-update/types.js.map +1 -1
  106. package/dist/runtime/auto-update/update-marker.d.ts +95 -0
  107. package/dist/runtime/auto-update/update-marker.d.ts.map +1 -0
  108. package/dist/runtime/auto-update/update-marker.js +185 -0
  109. package/dist/runtime/auto-update/update-marker.js.map +1 -0
  110. package/dist/runtime/auto-update/update-schedule.d.ts +67 -0
  111. package/dist/runtime/auto-update/update-schedule.d.ts.map +1 -0
  112. package/dist/runtime/auto-update/update-schedule.js +91 -0
  113. package/dist/runtime/auto-update/update-schedule.js.map +1 -0
  114. package/dist/runtime/decision-errors.d.ts +7 -0
  115. package/dist/runtime/decision-errors.d.ts.map +1 -1
  116. package/dist/runtime/decision-errors.js +15 -0
  117. package/dist/runtime/decision-errors.js.map +1 -1
  118. package/dist/runtime/process-state.d.ts +168 -0
  119. package/dist/runtime/process-state.d.ts.map +1 -0
  120. package/dist/runtime/process-state.js +81 -0
  121. package/dist/runtime/process-state.js.map +1 -0
  122. package/dist/runtime/reconcile-state.d.ts.map +1 -1
  123. package/dist/runtime/reconcile-state.js +18 -7
  124. package/dist/runtime/reconcile-state.js.map +1 -1
  125. package/dist/runtime/strategy-registry.d.ts +16 -0
  126. package/dist/runtime/strategy-registry.d.ts.map +1 -1
  127. package/dist/runtime/strategy-registry.js +7 -3
  128. package/dist/runtime/strategy-registry.js.map +1 -1
  129. package/dist/runtime/update-apply-deps.d.ts +5 -3
  130. package/dist/runtime/update-apply-deps.d.ts.map +1 -1
  131. package/dist/runtime/update-apply-deps.js +15 -3
  132. package/dist/runtime/update-apply-deps.js.map +1 -1
  133. package/dist/senpi/client.d.ts +29 -0
  134. package/dist/senpi/client.d.ts.map +1 -1
  135. package/dist/senpi/client.js +71 -2
  136. package/dist/senpi/client.js.map +1 -1
  137. package/dist/skills-manager/version-manager.d.ts +0 -14
  138. package/dist/skills-manager/version-manager.d.ts.map +1 -1
  139. package/dist/skills-manager/version-manager.js +3 -31
  140. package/dist/skills-manager/version-manager.js.map +1 -1
  141. package/dist/strategy/strategy-state.d.ts +3 -11
  142. package/dist/strategy/strategy-state.d.ts.map +1 -1
  143. package/dist/strategy/strategy-state.js +8 -18
  144. package/dist/strategy/strategy-state.js.map +1 -1
  145. package/dist/telemetry/event-builders.d.ts +2 -4
  146. package/dist/telemetry/event-builders.d.ts.map +1 -1
  147. package/dist/telemetry/event-builders.js +2 -4
  148. package/dist/telemetry/event-builders.js.map +1 -1
  149. package/dist/telemetry/metrics.d.ts +15 -1
  150. package/dist/telemetry/metrics.d.ts.map +1 -1
  151. package/dist/telemetry/metrics.js +25 -1
  152. package/dist/telemetry/metrics.js.map +1 -1
  153. package/dist/telemetry/otel-sdk.d.ts +12 -0
  154. package/dist/telemetry/otel-sdk.d.ts.map +1 -1
  155. package/dist/telemetry/otel-sdk.js +47 -1
  156. package/dist/telemetry/otel-sdk.js.map +1 -1
  157. package/dist/telemetry/spans/span-hooks.d.ts +18 -1
  158. package/dist/telemetry/spans/span-hooks.d.ts.map +1 -1
  159. package/dist/telemetry/spans/span-hooks.js +304 -103
  160. package/dist/telemetry/spans/span-hooks.js.map +1 -1
  161. package/dist/telemetry/tool-plane.d.ts +2 -0
  162. package/dist/telemetry/tool-plane.d.ts.map +1 -1
  163. package/dist/telemetry/tool-plane.js +1 -0
  164. package/dist/telemetry/tool-plane.js.map +1 -1
  165. package/dist/test-setup.js +7 -1
  166. package/dist/test-setup.js.map +1 -1
  167. package/dist/tool-surface/crib-cache.d.ts +21 -0
  168. package/dist/tool-surface/crib-cache.d.ts.map +1 -0
  169. package/dist/tool-surface/crib-cache.js +54 -0
  170. package/dist/tool-surface/crib-cache.js.map +1 -0
  171. package/dist/tool-surface/crib-hook.d.ts +78 -0
  172. package/dist/tool-surface/crib-hook.d.ts.map +1 -0
  173. package/dist/tool-surface/crib-hook.js +225 -0
  174. package/dist/tool-surface/crib-hook.js.map +1 -0
  175. package/dist/tool-surface/crib-sheet.d.ts +56 -0
  176. package/dist/tool-surface/crib-sheet.d.ts.map +1 -0
  177. package/dist/tool-surface/crib-sheet.js +129 -0
  178. package/dist/tool-surface/crib-sheet.js.map +1 -0
  179. package/dist/tool-surface/mcp-tool-source.d.ts +64 -0
  180. package/dist/tool-surface/mcp-tool-source.d.ts.map +1 -0
  181. package/dist/tool-surface/mcp-tool-source.js +189 -0
  182. package/dist/tool-surface/mcp-tool-source.js.map +1 -0
  183. package/dist/utils/event-catalog.d.ts +144 -90
  184. package/dist/utils/event-catalog.d.ts.map +1 -1
  185. package/dist/utils/event-catalog.js +25 -7
  186. package/dist/utils/event-catalog.js.map +1 -1
  187. package/dist/widgets/tool.d.ts +9 -0
  188. package/dist/widgets/tool.d.ts.map +1 -1
  189. package/dist/widgets/tool.js +1 -0
  190. package/dist/widgets/tool.js.map +1 -1
  191. package/openclaw.plugin.json +11 -1
  192. package/package.json +5 -2
  193. package/dist/prompt/skill-router-hook.d.ts +0 -24
  194. package/dist/prompt/skill-router-hook.d.ts.map +0 -1
  195. package/dist/prompt/skill-router-hook.js +0 -381
  196. package/dist/prompt/skill-router-hook.js.map +0 -1
  197. package/dist/skill-router/catalog.d.ts +0 -30
  198. package/dist/skill-router/catalog.d.ts.map +0 -1
  199. package/dist/skill-router/catalog.js +0 -131
  200. package/dist/skill-router/catalog.js.map +0 -1
  201. package/dist/skill-router/classify-client.d.ts +0 -80
  202. package/dist/skill-router/classify-client.d.ts.map +0 -1
  203. package/dist/skill-router/classify-client.js +0 -283
  204. package/dist/skill-router/classify-client.js.map +0 -1
  205. package/dist/skill-router/prompt.d.ts +0 -36
  206. package/dist/skill-router/prompt.d.ts.map +0 -1
  207. package/dist/skill-router/prompt.js +0 -318
  208. package/dist/skill-router/prompt.js.map +0 -1
  209. package/dist/skill-router/resolve.d.ts +0 -41
  210. package/dist/skill-router/resolve.d.ts.map +0 -1
  211. package/dist/skill-router/resolve.js +0 -43
  212. package/dist/skill-router/resolve.js.map +0 -1
@@ -8,6 +8,21 @@
8
8
  * - subagent_* lifecycle → `invoke_agent` (INTERNAL), parented to the model span
9
9
  * - agent_end → ends any still-open spans for the run
10
10
  *
11
+ * On OpenClaw 10.x (`modernHost`):
12
+ * - there is no `subagent_spawning` hook, so `subagent_spawned` opens the `invoke_agent` span;
13
+ * - the tool-search tools (`tool_search`, `tool_describe`, and the dispatcher `dispatch_action`,
14
+ * `tool_call` on 10.4) get `execute_tool` spans with `senpi.tool.bridge = true` and count on
15
+ * `tool.bridge.calls`, not `tool.calls`. The inner tool a dispatcher runs (id
16
+ * `tool_call:<sanitized outer id>:…`) nests under the dispatcher's span. Its own
17
+ * `after_tool_call` normally closes it (10.10 `embedded-agent-subscribe.handlers.tools.completion.ts:603-626`);
18
+ * any inner span still open when the dispatcher's `after_tool_call` fires is closed there with
19
+ * the outer outcome, and a late inner `after_tool_call` for it is then ignored, so each inner call
20
+ * is counted and evented once under its own name.
21
+ *
22
+ * On both hosts each `chat` span carries `senpi.llm.calls` (the run's `model_call_ended` count),
23
+ * and the drift alarm skips any unoffered name the host ran in the run (a direct call to a deferred
24
+ * tool is legal in 10.x tool-search directory mode).
25
+ *
11
26
  * Open and finalize are separate callbacks, so we can't use `withSpan`; we `startSpan`
12
27
  * and hold the handle in a session-keyed registry until the finalize hook, recording
13
28
  * errors directly on the held span (it's never the active span, so `logger.error` won't).
@@ -21,15 +36,27 @@ import { SpanKind, context as otelContext, propagation, trace, } from "@opentele
21
36
  import { getTracer } from "../../telemetry/tracing.js";
22
37
  import { HEADER_ADDRESS, HEADER_CORRELATION_ID, HEADER_RECIPE_NAME, HEADER_RUNTIME_ID, HEADER_RUNTIME_VERSION, } from "./constants.js";
23
38
  import { GEN_AI, errorTypeOf, firstNumber, normalizeGenAiMessages, recordSpanError, setDefinedAttributes, setGenAiContentAttribute, toFinishReasons, } from "./gen-ai.js";
24
- import { elapsedSeconds, recordToolCall, recordInvokeAgentDuration, recordOperationDuration, recordTokenUsage, } from "../../telemetry/metrics.js";
39
+ import { elapsedSeconds, recordToolBridgeCall, recordToolCall, recordInvokeAgentDuration, recordOperationDuration, recordTokenUsage, } from "../../telemetry/metrics.js";
25
40
  import { emitToolCalled, offeredToolNames, requestedToolNames, } from "../../telemetry/tool-plane.js";
26
41
  import { createLogger } from "../../utils/logger.js";
27
42
  const logger = createLogger("[senpi-core][span-hooks]");
43
+ /** The tool-search bridge tools and their `senpi.tool.bridge_kind` (10.10 `src/agents/tool-search-types.ts:10-12`; `tool_call` is the 10.4 dispatcher). */
44
+ const BRIDGE_TOOL_KINDS = {
45
+ tool_search: "search",
46
+ tool_describe: "describe",
47
+ dispatch_action: "call",
48
+ tool_call: "call",
49
+ };
28
50
  /**
29
- * OpenClaw's per-run `runId` on the chat and execute_tool spans: the join key the skill router's
30
- * `skill_router.decision` event shares (`src/utils/event-catalog.ts`). Distinct from `senpi.run.id`.
51
+ * Port of OpenClaw's inner-call id sanitizer
52
+ * (`openclaw-worktrees/v2026.10.10/src/agents/tool-search-runtime.ts:211-214`): the inner
53
+ * call a dispatcher runs gets the id `tool_call:${sanitizeToolCallIdPart(outerToolCallId)}:…`
54
+ * (the literal `tool_call:` prefix is kept on 10.10, where only the dispatcher was renamed).
31
55
  */
32
- const OPENCLAW_RUN_ID_ATTR = "senpi.openclaw.run_id";
56
+ export function sanitizeToolCallIdPart(value) {
57
+ const safe = value.trim().replace(/[^A-Za-z0-9_.:-]+/g, "_");
58
+ return safe.slice(0, 120) || "call";
59
+ }
33
60
  /**
34
61
  * Grace window the `agent_end` sweep holds a finished model span before ending it, so a
35
62
  * trailing `llm_output` (observed ~1 ms later in the codex/harness flow, but timed generously)
@@ -37,9 +64,20 @@ const OPENCLAW_RUN_ID_ATTR = "senpi.openclaw.run_id";
37
64
  * process open; an orphan run with no `llm_output` lets the timer end the span.
38
65
  */
39
66
  export const MODEL_SPAN_END_GRACE_MS = 2000;
67
+ /**
68
+ * Registers the span hooks.
69
+ *
70
+ * @returns How many hooks were registered (10 on 5.x; 9 on 10.x, which has no `subagent_spawning`).
71
+ */
40
72
  export function registerSpanHooks(options) {
41
73
  const { api } = options;
74
+ const modernHost = options.modernHost === true;
42
75
  const tracer = getTracer();
76
+ let hookCount = 0;
77
+ const on = (hookName, handler, opts) => {
78
+ api.on(hookName, handler, opts);
79
+ hookCount += 1;
80
+ };
43
81
  // Cap on drift events per turn so a flood of invented tool calls can't balloon the log.
44
82
  const MAX_DRIFT_EVENTS_PER_TURN = 8;
45
83
  // Held model spans, keyed by (sessionKey, runId). The tool/subagent spans parent
@@ -54,13 +92,23 @@ export function registerSpanHooks(options) {
54
92
  // (agentId → sessionKey/runId) from llm_input, plus the last-seen pair, so tool
55
93
  // hooks can resolve their host session.
56
94
  const sessionByAgentId = new Map();
95
+ // Latest run per session, for a 10.x subagent_spawned whose ctx names the requester session but
96
+ // not its run (ctx.runId is the child run there).
97
+ const latestRunBySession = new Map();
57
98
  let lastActive = null;
58
99
  const rememberSession = (agentCtx, sessionKey, runId) => {
59
100
  const agentId = nonEmptyString(asRecord(agentCtx)?.agentId);
60
101
  if (agentId)
61
102
  sessionByAgentId.set(agentId, { sessionKey, runId });
103
+ latestRunBySession.set(sessionKey, runId);
62
104
  lastActive = { sessionKey, runId };
63
105
  };
106
+ /** Stamps the run's model-call count on a `chat` span about to end. */
107
+ const stampLlmCalls = (held) => {
108
+ if (held.llmCalls && held.llmCalls > 0) {
109
+ setDefinedAttributes(held.span, { "senpi.llm.calls": held.llmCalls });
110
+ }
111
+ };
64
112
  const resolveToolSession = (ctx) => {
65
113
  const direct = {
66
114
  sessionKey: readSessionKey(ctx, undefined),
@@ -86,7 +134,7 @@ export function registerSpanHooks(options) {
86
134
  return model ? trace.setSpan(otelContext.active(), model.span) : otelContext.active();
87
135
  };
88
136
  // ─── LLM (`chat` span) ───────────────────────────────────────────────────
89
- api.on("llm_input", (event, agentCtx) => {
137
+ on("llm_input", (event, agentCtx) => {
90
138
  try {
91
139
  const identity = readIdentity(agentCtx);
92
140
  const sessionKey = readSessionKey(agentCtx, event);
@@ -100,8 +148,13 @@ export function registerSpanHooks(options) {
100
148
  // A duplicate llm_input for the same (session, run) means a new turn opened
101
149
  // without the previous one closing — end the prior span before replacing it.
102
150
  const prior = modelSpans.get(key);
103
- if (prior)
151
+ if (prior) {
152
+ // Its agent_end grace timer would end the replaced span a second time.
153
+ if (prior.endTimer)
154
+ clearTimeout(prior.endTimer);
155
+ stampLlmCalls(prior);
104
156
  endSpan(prior.span);
157
+ }
105
158
  const ev = asRecord(event) ?? {};
106
159
  const requestModel = nonEmptyString(ev.model);
107
160
  const provider = nonEmptyString(ev.provider);
@@ -126,9 +179,6 @@ export function registerSpanHooks(options) {
126
179
  // Session key as the conversation id, so consecutive turns of one session correlate (a
127
180
  // single per-turn trace otherwise can't be tied to its neighbours — e.g. a runaway loop).
128
181
  [GEN_AI.CONVERSATION_ID]: sessionKey,
129
- // OpenClaw's own run id, so the skill router's decision event joins this turn exactly.
130
- // Not `senpi.run.id`, which is the trading run id from the correlation header.
131
- [OPENCLAW_RUN_ID_ATTR]: runId,
132
182
  [GEN_AI.PROVIDER_NAME]: provider,
133
183
  [GEN_AI.REQUEST_MODEL]: requestModel,
134
184
  [GEN_AI.REQUEST_TEMPERATURE]: firstNumber(ev.temperature),
@@ -148,7 +198,7 @@ export function registerSpanHooks(options) {
148
198
  logger.warn("llm_input handler failed", { err: errMsg(err) });
149
199
  }
150
200
  });
151
- api.on("llm_output", (event, agentCtx) => {
201
+ on("llm_output", (event, agentCtx) => {
152
202
  try {
153
203
  const sessionKey = readSessionKey(agentCtx, event);
154
204
  const runId = readRunId(agentCtx, event);
@@ -167,6 +217,7 @@ export function registerSpanHooks(options) {
167
217
  // Cancel any deferred teardown the agent_end sweep scheduled — we finalize the span here.
168
218
  if (held.endTimer)
169
219
  clearTimeout(held.endTimer);
220
+ stampLlmCalls(held);
170
221
  const ev = asRecord(event) ?? {};
171
222
  const usage = asRecord(ev.usage);
172
223
  // Token field naming varies by provider/wrapper; try every known spelling.
@@ -201,9 +252,14 @@ export function registerSpanHooks(options) {
201
252
  // deduped + capped so a flood of invented calls can't balloon the log.
202
253
  if (held.offeredTools) {
203
254
  const offered = held.offeredTools;
255
+ // A name the host ran in this run is not invented: in 10.x tool-search directory mode a
256
+ // direct call to any deferred tool (a `senpi__` MCP tool or a deferred OpenClaw tool) is
257
+ // legal though not in the offered set (`tool-search-directory.ts:194-197` on 10.10). An
258
+ // unoffered name that never ran is drift on every host and in every mode.
259
+ const ran = held.ranTools;
204
260
  const seen = new Set();
205
261
  for (const name of requestedToolNames(outputMessages)) {
206
- if (offered.has(name) || seen.has(name))
262
+ if (offered.has(name) || seen.has(name) || ran?.has(name))
207
263
  continue;
208
264
  if (seen.size >= MAX_DRIFT_EVENTS_PER_TURN)
209
265
  break;
@@ -237,7 +293,7 @@ export function registerSpanHooks(options) {
237
293
  // The provider-call result: `outcome`, `failureKind`, timing. This is the ONLY
238
294
  // signal for a failed/aborted turn — `llm_output` never fires when the call
239
295
  // errors, so without this a wedged turn is indistinguishable from a healthy one.
240
- api.on("model_call_ended", (event, agentCtx) => {
296
+ on("model_call_ended", (event, agentCtx) => {
241
297
  try {
242
298
  const sessionKey = readSessionKey(agentCtx, event);
243
299
  const runId = readRunId(agentCtx, event);
@@ -246,6 +302,7 @@ export function registerSpanHooks(options) {
246
302
  const held = modelSpans.get(sessionLlmKey(sessionKey, runId));
247
303
  if (!held)
248
304
  return; // span already finalized, or not one we opened — best effort.
305
+ held.llmCalls = (held.llmCalls ?? 0) + 1;
249
306
  const ev = asRecord(event) ?? {};
250
307
  const outcome = nonEmptyString(ev.outcome);
251
308
  const failureKind = nonEmptyString(ev.failureKind);
@@ -270,7 +327,59 @@ export function registerSpanHooks(options) {
270
327
  }
271
328
  });
272
329
  // ─── Tool (`execute_tool` span) ────────────────────────────────────────────
273
- api.on("before_tool_call", (event, toolCtx) => {
330
+ // Inner calls a dispatcher's after_tool_call closed, so their own late after_tool_call is not
331
+ // counted again; the value says whether that close already evented a failure (the outer call
332
+ // errored). FIFO-bounded: a host that never sends that late hook must not grow it.
333
+ const closedByDispatcher = new Map();
334
+ const CLOSED_BY_DISPATCHER_MAX = 512;
335
+ const innerKey = (sessionKey, runId, toolCallId) => `${sessionKey} ${runId} ${toolCallId}`;
336
+ const markClosedByDispatcher = (key, failureEvented) => {
337
+ closedByDispatcher.set(key, failureEvented);
338
+ while (closedByDispatcher.size > CLOSED_BY_DISPATCHER_MAX) {
339
+ const oldest = closedByDispatcher.keys().next().value;
340
+ closedByDispatcher.delete(oldest);
341
+ }
342
+ };
343
+ /**
344
+ * A 10.x dispatcher's open `execute_tool` span in this run whose inner-call prefix
345
+ * `tool_call:${sanitize(outer id)}:` starts `innerToolCallId`, for parenting the inner span.
346
+ */
347
+ const findDispatcherSpanFor = (sessionKey, runId, innerToolCallId) => {
348
+ for (const held of toolSpans.values()) {
349
+ if (held.bridgeKind !== "call" || !held.toolCallId)
350
+ continue;
351
+ if (held.sessionKey !== sessionKey || held.runId !== runId)
352
+ continue;
353
+ if (innerToolCallId.startsWith(`tool_call:${sanitizeToolCallIdPart(held.toolCallId)}:`))
354
+ return held;
355
+ }
356
+ return undefined;
357
+ };
358
+ /** Records the outcome on a held tool span and ends it, after its args stamping settles. */
359
+ const finalizeToolSpan = (held, errored, error, result) => {
360
+ const span = held.span;
361
+ void (async () => {
362
+ try {
363
+ if (held.pending)
364
+ await held.pending;
365
+ if (errored) {
366
+ recordSpanError(span, error);
367
+ }
368
+ else {
369
+ await setGenAiContentAttribute(span, GEN_AI.TOOL_CALL_RESULT, result);
370
+ }
371
+ }
372
+ finally {
373
+ try {
374
+ span.end();
375
+ }
376
+ catch {
377
+ /* best effort */
378
+ }
379
+ }
380
+ })();
381
+ };
382
+ on("before_tool_call", (event, toolCtx) => {
274
383
  try {
275
384
  const identity = readIdentity(toolCtx);
276
385
  const resolved = resolveToolSession(toolCtx);
@@ -283,22 +392,35 @@ export function registerSpanHooks(options) {
283
392
  const toolCallId = nonEmptyString(ev?.toolCallId) ??
284
393
  nonEmptyString(asRecord(toolCtx)?.toolCallId) ??
285
394
  null;
395
+ const model = modelSpans.get(sessionLlmKey(resolved.sessionKey, resolved.runId));
396
+ if (model)
397
+ (model.ranTools ??= new Set()).add(toolName);
398
+ const bridgeKind = modernHost ? BRIDGE_TOOL_KINDS[toolName] : undefined;
399
+ // An inner call a 10.x dispatcher runs nests under the dispatcher's span.
400
+ const dispatcher = modernHost && !bridgeKind && toolCallId?.startsWith("tool_call:")
401
+ ? findDispatcherSpanFor(resolved.sessionKey, resolved.runId, toolCallId)
402
+ : undefined;
286
403
  const key = toolKey(resolved.sessionKey, resolved.runId, toolCallId, toolName, ++toolSeq);
287
- const span = tracer.startSpan(`execute_tool ${toolName}`, { kind: SpanKind.INTERNAL }, parentContextForModel(resolved.sessionKey, resolved.runId));
404
+ const span = tracer.startSpan(`execute_tool ${toolName}`, { kind: SpanKind.INTERNAL }, dispatcher
405
+ ? trace.setSpan(otelContext.active(), dispatcher.span)
406
+ : parentContextForModel(resolved.sessionKey, resolved.runId));
288
407
  const held = {
289
408
  span,
290
409
  sessionKey: resolved.sessionKey,
291
410
  runId: resolved.runId,
292
411
  startMs: Date.now(),
293
412
  toolName,
413
+ ...(toolCallId ? { toolCallId } : {}),
414
+ ...(bridgeKind ? { bridgeKind } : {}),
415
+ ...(bridgeKind === "call" ? { requestedId: nonEmptyString(asRecord(ev?.params)?.id) } : {}),
294
416
  };
295
417
  toolSpans.set(key, held);
296
418
  setDefinedAttributes(span, {
297
419
  [GEN_AI.OPERATION_NAME]: "execute_tool",
298
420
  [GEN_AI.CONVERSATION_ID]: resolved.sessionKey,
299
- [OPENCLAW_RUN_ID_ATTR]: resolved.runId,
300
421
  [GEN_AI.TOOL_NAME]: toolName,
301
422
  [GEN_AI.TOOL_CALL_ID]: toolCallId ?? undefined,
423
+ "senpi.tool.bridge": bridgeKind ? true : undefined,
302
424
  // Best-effort skill attribution from a skill-file read (no first-class skill hook exists).
303
425
  "senpi.skill.name": skillNameFromToolArgs(ev?.params ?? ev?.input),
304
426
  ...identityAttributes(identity),
@@ -311,42 +433,117 @@ export function registerSpanHooks(options) {
311
433
  logger.warn("before_tool_call handler failed", { err: errMsg(err) });
312
434
  }
313
435
  });
314
- api.on("after_tool_call", (event, toolCtx) => {
436
+ on("after_tool_call", (event, toolCtx) => {
315
437
  try {
316
438
  const resolved = resolveToolSession(toolCtx);
317
- if (!resolved) {
318
- logger.debug("after_tool_call session unresolved; skipping");
319
- return;
320
- }
321
439
  const ev = asRecord(event);
322
440
  const toolName = nonEmptyString(ev?.toolName) ?? nonEmptyString(ev?.name) ?? "unknown";
323
441
  const error = ev?.error;
324
442
  const errored = error !== undefined && error !== null;
325
- // Tool-plane event (narrative): a failed tool call — the agent-blind hole, greppable instead
326
- // of span-only. A successful call already rides its span + (state-changing) its domain event,
327
- // so it is not re-evented here. Emitted before the span lookup so a failure is never lost when
328
- // the matching before_tool_call span wasn't registered.
329
- if (errored) {
443
+ const result = ev?.result;
444
+ const toolCallId = nonEmptyString(ev?.toolCallId) ??
445
+ nonEmptyString(asRecord(toolCtx)?.toolCallId) ??
446
+ null;
447
+ const bridgeKind = modernHost ? BRIDGE_TOOL_KINDS[toolName] : undefined;
448
+ const emitFailure = (name, bridge) => {
330
449
  emitToolCalled({
331
- name: toolName,
450
+ name,
332
451
  origin: "agent",
333
452
  outcome: "error",
334
453
  errorType: errorTypeOf(error),
335
454
  errorMessage: error instanceof Error ? error.message : String(error),
455
+ ...(bridge ? { bridge: true } : {}),
336
456
  });
457
+ };
458
+ const foundKey = resolved
459
+ ? findToolKey(toolSpans, resolved.sessionKey, resolved.runId, toolCallId, toolName)
460
+ : undefined;
461
+ const held = foundKey ? toolSpans.get(foundKey) : undefined;
462
+ if (foundKey)
463
+ toolSpans.delete(foundKey);
464
+ if (bridgeKind) {
465
+ // Inner calls of this dispatcher still open: their own after_tool_call normally closed them
466
+ // first (10.10/10.4), so these are the ones it missed. They take the outer outcome here,
467
+ // count once under their own names, and a late after_tool_call for them is ignored.
468
+ const inner = [];
469
+ if (bridgeKind === "call" && resolved && toolCallId) {
470
+ const prefix = `tool_call:${sanitizeToolCallIdPart(toolCallId)}:`;
471
+ for (const [k, h] of toolSpans) {
472
+ if (h.sessionKey !== resolved.sessionKey || h.runId !== resolved.runId)
473
+ continue;
474
+ if (!h.toolCallId?.startsWith(prefix))
475
+ continue;
476
+ toolSpans.delete(k);
477
+ markClosedByDispatcher(innerKey(h.sessionKey, h.runId, h.toolCallId), errored);
478
+ inner.push(h);
479
+ }
480
+ }
481
+ if (errored) {
482
+ if (inner.length > 0) {
483
+ for (const h of inner)
484
+ emitFailure(h.toolName ?? "unknown");
485
+ }
486
+ else if (bridgeKind === "call" && held?.innerErrored) {
487
+ // The inner call's own after_tool_call already reported this failure.
488
+ }
489
+ else if (bridgeKind === "call") {
490
+ // No inner call, or one that succeeded: the dispatcher's own failure (a cap, a result
491
+ // post-processing error) is still a failure the agent saw, so it is always evented.
492
+ const requested = held?.requestedId ?? nonEmptyString(asRecord(ev?.params)?.id);
493
+ emitFailure(requested ?? toolName, requested !== undefined);
494
+ }
495
+ else {
496
+ emitFailure(toolName);
497
+ }
498
+ }
499
+ for (const h of inner) {
500
+ recordToolCall({
501
+ toolName: h.toolName,
502
+ origin: "agent",
503
+ outcome: errored ? "error" : "ok",
504
+ errorType: errored ? errorTypeOf(error) : undefined,
505
+ durationSec: elapsedSeconds(h.startMs),
506
+ });
507
+ finalizeToolSpan(h, errored, error, result);
508
+ }
509
+ recordToolBridgeCall({ kind: bridgeKind, outcome: errored ? "error" : "ok" });
510
+ if (held)
511
+ finalizeToolSpan(held, errored, error, result);
512
+ return;
337
513
  }
338
- const toolCallId = nonEmptyString(ev?.toolCallId) ??
339
- nonEmptyString(asRecord(toolCtx)?.toolCallId) ??
340
- null;
341
- const foundKey = findToolKey(toolSpans, resolved.sessionKey, resolved.runId, toolCallId, toolName);
342
- if (!foundKey) {
514
+ // A late after_tool_call for an inner call its dispatcher already closed and counted. Its
515
+ // span and metric are done; a failure it reports is still evented unless the dispatcher's
516
+ // close already did (a dispatcher can return an inner error to the model as a result).
517
+ if (modernHost && resolved && toolCallId) {
518
+ const k = innerKey(resolved.sessionKey, resolved.runId, toolCallId);
519
+ const failureEvented = closedByDispatcher.get(k);
520
+ if (failureEvented !== undefined) {
521
+ closedByDispatcher.delete(k);
522
+ if (errored && !failureEvented)
523
+ emitFailure(toolName);
524
+ return;
525
+ }
526
+ }
527
+ // Tool-plane event (narrative): a failed tool call — the agent-blind hole, greppable instead
528
+ // of span-only. A successful call already rides its span + (state-changing) its domain event,
529
+ // so it is not re-evented here. Emitted before the span check so a failure is never lost when
530
+ // the matching before_tool_call span wasn't registered.
531
+ if (errored)
532
+ emitFailure(toolName);
533
+ // Tell the still-open dispatcher that its inner call's failure is already reported.
534
+ if (errored && modernHost && resolved && toolCallId?.startsWith("tool_call:")) {
535
+ const dispatcher = findDispatcherSpanFor(resolved.sessionKey, resolved.runId, toolCallId);
536
+ if (dispatcher)
537
+ dispatcher.innerErrored = true;
538
+ }
539
+ if (!resolved) {
540
+ logger.debug("after_tool_call session unresolved; skipping");
541
+ return;
542
+ }
543
+ if (!held) {
343
544
  logger.debug("after_tool_call: no open tool span", { toolName, toolCallId });
344
545
  return;
345
546
  }
346
- const held = toolSpans.get(foundKey);
347
- const span = held.span;
348
- toolSpans.delete(foundKey);
349
- const result = ev?.result;
350
547
  recordToolCall({
351
548
  toolName: held.toolName,
352
549
  origin: "agent",
@@ -354,83 +551,83 @@ export function registerSpanHooks(options) {
354
551
  errorType: errored ? errorTypeOf(error) : undefined,
355
552
  durationSec: elapsedSeconds(held.startMs),
356
553
  });
357
- void (async () => {
358
- try {
359
- if (held.pending)
360
- await held.pending;
361
- if (errored) {
362
- recordSpanError(span, error);
363
- }
364
- else {
365
- await setGenAiContentAttribute(span, GEN_AI.TOOL_CALL_RESULT, result);
366
- }
367
- }
368
- finally {
369
- try {
370
- span.end();
371
- }
372
- catch {
373
- /* best effort */
374
- }
375
- }
376
- })();
554
+ finalizeToolSpan(held, errored, error, result);
377
555
  }
378
556
  catch (err) {
379
557
  logger.warn("after_tool_call handler failed", { err: errMsg(err) });
380
558
  }
381
559
  });
382
- // ─── Subagent (`invoke_agent` span, four-hook lifecycle) ───────────────────
383
- api.on("subagent_spawning", (event, subagentCtx) => {
384
- try {
385
- const identity = readIdentity(subagentCtx);
386
- const ev = asRecord(event);
387
- const ctxObj = asRecord(subagentCtx);
388
- const hostSessionKey = nonEmptyString(ctxObj?.requesterSessionKey) ??
389
- nonEmptyString(ctxObj?.sessionKey) ??
390
- "";
391
- const hostRunId = nonEmptyString(ctxObj?.runId) ?? nonEmptyString(ctxObj?.requesterRunId) ?? "";
392
- const childSessionKey = nonEmptyString(ev?.childSessionKey) ?? nonEmptyString(ctxObj?.childSessionKey);
393
- if (!childSessionKey) {
394
- logger.warn("subagent_spawning missing childSessionKey; skipping span");
395
- return;
560
+ // ─── Subagent (`invoke_agent` span) ────────────────────────────────────────
561
+ // 5.x: subagent_spawning opens, subagent_spawned enriches. 10.x has no subagent_spawning, so
562
+ // subagent_spawned opens the span when none is held for the child.
563
+ /** Opens and holds the `invoke_agent` span for `childSessionKey`, hosted by the given run. */
564
+ const openSubagentSpan = (params) => {
565
+ const { childSessionKey, hostSessionKey, hostRunId, ev } = params;
566
+ const prior = subagentSpans.get(childSessionKey);
567
+ if (prior)
568
+ endSpan(prior.span);
569
+ const agentName = nonEmptyString(ev?.label) ?? nonEmptyString(ev?.agentId) ?? "unknown";
570
+ const span = tracer.startSpan(`invoke_agent ${agentName}`, { kind: SpanKind.INTERNAL }, hostSessionKey && hostRunId
571
+ ? parentContextForModel(hostSessionKey, hostRunId)
572
+ : otelContext.active());
573
+ // sessionKey/runId carry the HOST run so the agent_end sweep can reach this span.
574
+ const held = {
575
+ span,
576
+ sessionKey: hostSessionKey,
577
+ runId: hostRunId,
578
+ startMs: Date.now(),
579
+ agentName,
580
+ };
581
+ subagentSpans.set(childSessionKey, held);
582
+ setDefinedAttributes(span, {
583
+ [GEN_AI.OPERATION_NAME]: "invoke_agent",
584
+ [GEN_AI.CONVERSATION_ID]: nonEmptyString(hostSessionKey),
585
+ [GEN_AI.AGENT_NAME]: agentName,
586
+ "senpi.subagent.mode": nonEmptyString(ev?.mode),
587
+ "senpi.subagent.requester": nonEmptyString(ev?.requester),
588
+ "senpi.subagent.thread_requested": typeof ev?.threadRequested === "boolean" ? ev.threadRequested : undefined,
589
+ ...identityAttributes(params.identity),
590
+ });
591
+ return held;
592
+ };
593
+ if (!modernHost) {
594
+ on("subagent_spawning", (event, subagentCtx) => {
595
+ try {
596
+ const ev = asRecord(event);
597
+ const ctxObj = asRecord(subagentCtx);
598
+ const hostSessionKey = nonEmptyString(ctxObj?.requesterSessionKey) ??
599
+ nonEmptyString(ctxObj?.sessionKey) ??
600
+ "";
601
+ const hostRunId = nonEmptyString(ctxObj?.runId) ?? nonEmptyString(ctxObj?.requesterRunId) ?? "";
602
+ const childSessionKey = nonEmptyString(ev?.childSessionKey) ?? nonEmptyString(ctxObj?.childSessionKey);
603
+ if (!childSessionKey) {
604
+ logger.warn("subagent_spawning missing childSessionKey; skipping span");
605
+ return;
606
+ }
607
+ openSubagentSpan({ childSessionKey, hostSessionKey, hostRunId, ev, identity: readIdentity(subagentCtx) });
396
608
  }
397
- const prior = subagentSpans.get(childSessionKey);
398
- if (prior)
399
- endSpan(prior.span);
400
- const agentName = nonEmptyString(ev?.label) ?? nonEmptyString(ev?.agentId) ?? "unknown";
401
- const span = tracer.startSpan(`invoke_agent ${agentName}`, { kind: SpanKind.INTERNAL }, hostSessionKey && hostRunId
402
- ? parentContextForModel(hostSessionKey, hostRunId)
403
- : otelContext.active());
404
- // sessionKey/runId carry the HOST run so the agent_end sweep can reach this span.
405
- subagentSpans.set(childSessionKey, {
406
- span,
407
- sessionKey: hostSessionKey,
408
- runId: hostRunId,
409
- startMs: Date.now(),
410
- agentName,
411
- });
412
- setDefinedAttributes(span, {
413
- [GEN_AI.OPERATION_NAME]: "invoke_agent",
414
- [GEN_AI.CONVERSATION_ID]: nonEmptyString(hostSessionKey),
415
- [GEN_AI.AGENT_NAME]: agentName,
416
- "senpi.subagent.mode": nonEmptyString(ev?.mode),
417
- "senpi.subagent.requester": nonEmptyString(ev?.requester),
418
- "senpi.subagent.thread_requested": typeof ev?.threadRequested === "boolean" ? ev.threadRequested : undefined,
419
- ...identityAttributes(identity),
420
- });
421
- }
422
- catch (err) {
423
- logger.warn("subagent_spawning handler failed", { err: errMsg(err) });
424
- }
425
- });
426
- api.on("subagent_spawned", (event, subagentCtx) => {
609
+ catch (err) {
610
+ logger.warn("subagent_spawning handler failed", { err: errMsg(err) });
611
+ }
612
+ });
613
+ }
614
+ on("subagent_spawned", (event, subagentCtx) => {
427
615
  try {
428
616
  const ev = asRecord(event);
429
617
  const ctxObj = asRecord(subagentCtx);
430
618
  const childSessionKey = nonEmptyString(ev?.childSessionKey) ?? nonEmptyString(ctxObj?.childSessionKey);
431
619
  if (!childSessionKey)
432
620
  return;
433
- const held = subagentSpans.get(childSessionKey);
621
+ let held = subagentSpans.get(childSessionKey);
622
+ if (!held && modernHost) {
623
+ // 10.x ctx: `runId` is the CHILD run; the host is the requester session, whose run is
624
+ // `requesterRunId` when given, else that session's latest run seen at llm_input.
625
+ const hostSessionKey = nonEmptyString(ctxObj?.requesterSessionKey) ?? nonEmptyString(ctxObj?.sessionKey) ?? "";
626
+ const hostRunId = nonEmptyString(ctxObj?.requesterRunId) ??
627
+ (hostSessionKey ? latestRunBySession.get(hostSessionKey) : undefined) ??
628
+ "";
629
+ held = openSubagentSpan({ childSessionKey, hostSessionKey, hostRunId, ev, identity: readIdentity(subagentCtx) });
630
+ }
434
631
  if (!held)
435
632
  return;
436
633
  const span = held.span;
@@ -444,7 +641,7 @@ export function registerSpanHooks(options) {
444
641
  logger.warn("subagent_spawned handler failed", { err: errMsg(err) });
445
642
  }
446
643
  });
447
- api.on("subagent_delivery_target", (event, subagentCtx) => {
644
+ on("subagent_delivery_target", (event, subagentCtx) => {
448
645
  try {
449
646
  const ev = asRecord(event);
450
647
  const ctxObj = asRecord(subagentCtx);
@@ -468,7 +665,7 @@ export function registerSpanHooks(options) {
468
665
  logger.warn("subagent_delivery_target handler failed", { err: errMsg(err) });
469
666
  }
470
667
  });
471
- api.on("subagent_ended", (event, subagentCtx) => {
668
+ on("subagent_ended", (event, subagentCtx) => {
472
669
  try {
473
670
  const ev = asRecord(event);
474
671
  const ctxObj = asRecord(subagentCtx);
@@ -509,7 +706,7 @@ export function registerSpanHooks(options) {
509
706
  }
510
707
  });
511
708
  // ─── Agent end (orphan sweep) ──────────────────────────────────────────────
512
- api.on("agent_end", (event, agentCtx) => {
709
+ on("agent_end", (event, agentCtx) => {
513
710
  try {
514
711
  const sessionKey = readSessionKey(agentCtx, event);
515
712
  const runId = readRunId(agentCtx, event);
@@ -542,6 +739,7 @@ export function registerSpanHooks(options) {
542
739
  model.endTimer = setTimeout(() => {
543
740
  if (modelSpans.get(llmKey) === model)
544
741
  modelSpans.delete(llmKey);
742
+ stampLlmCalls(model);
545
743
  endSpan(model.span);
546
744
  }, MODEL_SPAN_END_GRACE_MS);
547
745
  model.endTimer.unref?.();
@@ -568,11 +766,14 @@ export function registerSpanHooks(options) {
568
766
  if (lastActive && lastActive.sessionKey === sessionKey && lastActive.runId === runId) {
569
767
  lastActive = null;
570
768
  }
769
+ if (latestRunBySession.get(sessionKey) === runId)
770
+ latestRunBySession.delete(sessionKey);
571
771
  }
572
772
  catch (err) {
573
773
  logger.warn("agent_end handler failed", { err: errMsg(err) });
574
774
  }
575
775
  });
776
+ return hookCount;
576
777
  }
577
778
  // ─── Span key helpers ───────────────────────────────────────────────────────
578
779
  const SEP = " ";