@theoremjs/agents 0.3.5-next.898.gf800d9a → 0.3.5-next.900.g35bbf80

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.
@@ -1,7 +1,7 @@
1
1
  /** Values that fill a label template's `{param}` placeholders. */
2
2
  export type LabelParams = Record<string, string | number>;
3
3
  /** Keys are stable API. */
4
- export declare const LABEL_KEYS: readonly ["provider.decision_failed", "provider.decision_unavailable", "provider.decision_model_missing", "provider.decision_ended", "provider.decision_images_off", "provider.decision_box_model", "provider.budget_exhausted", "provider.adapter_version", "provider.adapter_methods", "provider.adapter_schemas", "provider.fallback_slot", "provider.model_fallback_slot", "provider.host_model", "turn.media_refused_image", "turn.media_refused_video", "turn.media_refused_file", "provider.turn_profile", "provider.model_binding_missing", "provider.session_closed", "provider.settled_call", "provider.session_unavailable", "provider.live_input", "provider.tool_cancel_missing", "provider.kernel_gate", "provider.event_invalid", "provider.response_identity", "provider.credential_resolution", "provider.credential_shape", "provider.stored_continuation", "provider.continuation_mismatch", "provider.continuation_contract", "provider.stateless_history", "provider.events_after_completion", "provider.duplicate_call", "provider.tool_cancel_live", "provider.complete_unavailable", "provider.parallel_tools", "provider.binding_identity", "provider.profile_type", "provider.event_type", "provider.feature", "provider.input_kind", "provider.output_kind", "provider.builtin", "provider.credential_missing", "provider.profile_configuration", "continue.instruction", "canary.bind_note", "user_data.note", "context.note", "taint.blocked", "taint.reason_steered", "taint.reason_tainted", "taint.destination_blocked", "taint.destination_confirm", "advisory.notice_elevated", "advisory.notice_high", "advisory.guidance", "attachments.too_many_files", "attachments.too_many_of_kind", "attachments.file_too_large", "attachments.turn_too_large", "attachments.not_accepted", "attachments.mime_not_allowed", "attachments.limits_unconfigured", "quota.exhausted", "quota.busy", "error.config", "error.request", "error.conflict", "error.not_found", "error.input", "error.action", "error.auth", "error.rate_limit", "error.busy", "error.unsupported", "error.unavailable", "error.bad_response", "error.network", "error.timeout", "error.safety", "error.blocked", "error.declined", "error.failed", "error.cancelled", "error.internal", "repair.default_guidance", "repair.items_guidance", "repair.cut_off_guidance", "repair.reply_cut_off", "repair.call_cut_off", "repair.call_cut_off_guidance", "repair.nothing_written", "repair.nothing_written_guidance", "repair.prompt_header", "repair.prompt_intro", "repair.prompt_instructions", "repair.history_heading", "repair.section_previous_output", "repair.section_validator_rejection", "repair.section_repair_guidance", "repair.section_instructions", "structured.answer_tool", "structured.answer_missing", "structured.cut_off", "structured.not_json", "compaction.request", "compaction.tool_call", "compaction.tool_result", "compaction.tool_files", "decision.box_image", "detect.blocked", "detect.call_blocked", "detect.output_blocked", "detect.shown_blocked", "detect.hint.ids", "detect.hint.financial", "detect.hint.network", "detect.hint.credentials", "detect.hint.email", "detect.hint.phone", "detect.hint.bank_account", "detect.hint.injection", "detect.hint.canary_leak", "detect.hint.prompt_leak", "detect.hint.marker_leak", "detect.hint.ungiven_images", "detect.hint.ungiven_links", "detect.hint.tool_leak", "detect.hint.own", "egress.default_repair_guidance", "egress.refusal", "egress.refusal_cut", "egress.rejection", "egress.rejection_found", "egress.hint_unscannable", "egress.hint_provider_tool_leak", "thought.omitted_image", "thought.omitted_link", "thought.omitted_instructions", "session.abandon_gated", "session.tool_denied", "session.tool_aborted", "session.sign_in", "sign_in.link", "sign_in.pending", "sign_in.done", "sign_in.declined", "sign_in.expired", "sign_in.out_of_scope", "session.gate_expired", "session.provider_state_unowned", "session.conversation_unknown", "session.full", "session.busy", "session.turn_ended", "session.gate_pending", "session.part_skipped", "live.session_ended", "voice.unsupported", "voice.permission", "voice.unavailable", "voice.failed", "voice.empty", "stop.cancelled", "stop.interrupted", "stop.length", "stop.filtered", "stop.provider_error", "stop.stream_incomplete", "stop.step_limit", "stop.answer_missing", "composer.model", "composer.effort", "tool.awaiting_user", "tool.completed_hidden", "tool.t2_loader_needs_snapshot", "tool.t2_loader_shape", "tool.t2_loader_output_invalid", "tool.execution_uncertain", "tool.input_invalid", "tool.input_invalid_after_mutate", "tool.output_invalid_after_mutate", "tool.handler_no_output", "tool.did_not_run", "tool.unreachable", "tool.page_no_answer", "tool.page_timed_out", "tool.output_invalid", "tool.not_loaded_t2", "tool.wait_unknown", "tool.wait_cycle", "tool.after_field", "tool.background_field", "tool.background_started", "tool.late_result", "tool.not_visible", "tool.builtin_not_enabled", "tool.provider_native", "tool.not_registered", "tool.builtin_needs_snapshot", "tool.not_allowed", "tool.not_eligible", "tool.unsupported_type", "tool.agent_call_limit", "tool.agent_failed", "tool.activity_failed", "protocol.not_served", "protocol.profile_type", "protocol.options", "protocol.option_clash", "protocol.base_options", "protocol.id_clash", "protocol.ws_headers", "protocol.builtin_unwritten", "protocol.provider_missing", "protocol.connection", "protocol.part_schema", "protocol.part_invalid", "protocol.key_invalid", "protocol.no_key", "protocol.reply_shape", "protocol.endpoint_url", "protocol.endpoint_host", "protocol.http", "protocol.no_operation", "protocol.definition", "protocol.provider_id_clash", "protocol.history_needed"];
4
+ export declare const LABEL_KEYS: readonly ["provider.decision_failed", "provider.decision_unavailable", "provider.decision_model_missing", "provider.decision_ended", "provider.decision_images_off", "provider.decision_box_model", "provider.budget_exhausted", "provider.adapter_version", "provider.adapter_methods", "provider.adapter_schemas", "provider.fallback_slot", "provider.model_fallback_slot", "provider.host_model", "turn.media_refused_image", "turn.media_refused_video", "turn.media_refused_file", "provider.turn_profile", "provider.model_binding_missing", "provider.session_closed", "provider.settled_call", "provider.session_unavailable", "provider.live_input", "provider.tool_cancel_missing", "provider.kernel_gate", "provider.event_invalid", "provider.response_identity", "provider.credential_resolution", "provider.credential_shape", "provider.stored_continuation", "provider.continuation_mismatch", "provider.continuation_contract", "provider.stateless_history", "provider.events_after_completion", "provider.duplicate_call", "provider.tool_cancel_live", "provider.complete_unavailable", "provider.parallel_tools", "provider.binding_identity", "provider.profile_type", "provider.event_type", "provider.feature", "provider.input_kind", "provider.output_kind", "provider.builtin", "provider.credential_missing", "provider.profile_configuration", "continue.instruction", "canary.bind_note", "user_data.note", "context.note", "taint.blocked", "taint.reason_steered", "taint.reason_tainted", "taint.destination_blocked", "taint.destination_confirm", "advisory.notice_elevated", "advisory.notice_high", "advisory.guidance", "attachments.too_many_files", "attachments.too_many_of_kind", "attachments.file_too_large", "attachments.turn_too_large", "attachments.not_accepted", "attachments.mime_not_allowed", "attachments.limits_unconfigured", "quota.exhausted", "quota.busy", "error.config", "error.request", "error.conflict", "error.not_found", "error.input", "error.action", "error.auth", "error.rate_limit", "error.busy", "error.unsupported", "error.unavailable", "error.bad_response", "error.network", "error.timeout", "error.safety", "error.blocked", "error.declined", "error.failed", "error.cancelled", "error.internal", "repair.default_guidance", "repair.items_guidance", "repair.cut_off_guidance", "repair.reply_cut_off", "repair.call_cut_off", "repair.call_cut_off_guidance", "repair.nothing_written", "repair.nothing_written_guidance", "repair.prompt_header", "repair.prompt_intro", "repair.prompt_instructions", "repair.history_heading", "repair.section_previous_output", "repair.section_validator_rejection", "repair.section_repair_guidance", "repair.section_instructions", "structured.answer_tool", "structured.answer_missing", "structured.cut_off", "structured.not_json", "compaction.request", "compaction.tool_call", "compaction.tool_result", "compaction.tool_files", "decision.box_image", "detect.blocked", "detect.call_blocked", "detect.output_blocked", "detect.shown_blocked", "detect.hint.ids", "detect.hint.financial", "detect.hint.network", "detect.hint.credentials", "detect.hint.email", "detect.hint.phone", "detect.hint.bank_account", "detect.hint.injection", "detect.hint.canary_leak", "detect.hint.prompt_leak", "detect.hint.marker_leak", "detect.hint.ungiven_images", "detect.hint.ungiven_links", "detect.hint.tool_leak", "detect.hint.own", "egress.default_repair_guidance", "egress.refusal", "egress.refusal_cut", "egress.rejection", "egress.rejection_found", "egress.hint_unscannable", "egress.hint_provider_tool_leak", "thought.omitted_image", "thought.omitted_link", "thought.omitted_instructions", "session.abandon_gated", "session.tool_denied", "session.tool_aborted", "session.sign_in", "sign_in.link", "sign_in.pending", "sign_in.done", "sign_in.declined", "sign_in.expired", "sign_in.out_of_scope", "session.gate_expired", "session.provider_state_unowned", "session.conversation_unknown", "session.full", "session.busy", "session.turn_ended", "session.gate_pending", "session.part_skipped", "live.session_ended", "voice.unsupported", "voice.permission", "voice.unavailable", "voice.failed", "voice.empty", "stop.cancelled", "stop.interrupted", "stop.length", "stop.filtered", "stop.provider_error", "stop.stream_incomplete", "stop.step_limit", "stop.answer_missing", "composer.model", "composer.effort", "tool.awaiting_user", "tool.completed_hidden", "tool.t2_loader_needs_snapshot", "tool.t2_loader_shape", "tool.t2_loader_output_invalid", "tool.execution_uncertain", "tool.input_invalid", "tool.hook_failed", "tool.input_invalid_after_mutate", "tool.output_invalid_after_mutate", "tool.handler_no_output", "tool.did_not_run", "tool.unreachable", "tool.page_no_answer", "tool.page_timed_out", "tool.output_invalid", "tool.not_loaded_t2", "tool.wait_unknown", "tool.wait_cycle", "tool.after_field", "tool.background_field", "tool.background_started", "tool.late_result", "tool.not_visible", "tool.builtin_not_enabled", "tool.provider_native", "tool.not_registered", "tool.builtin_needs_snapshot", "tool.not_allowed", "tool.not_eligible", "tool.unsupported_type", "tool.agent_call_limit", "tool.agent_failed", "tool.activity_failed", "protocol.not_served", "protocol.profile_type", "protocol.options", "protocol.option_clash", "protocol.base_options", "protocol.id_clash", "protocol.ws_headers", "protocol.builtin_unwritten", "protocol.provider_missing", "protocol.connection", "protocol.part_schema", "protocol.part_invalid", "protocol.key_invalid", "protocol.no_key", "protocol.reply_shape", "protocol.endpoint_url", "protocol.endpoint_host", "protocol.http", "protocol.no_operation", "protocol.definition", "protocol.provider_id_clash", "protocol.history_needed"];
5
5
  /** One of {@linkcode LABEL_KEYS}. */
6
6
  export type LabelKey = (typeof LABEL_KEYS)[number];
7
7
  /**
@@ -186,6 +186,7 @@ export const LABEL_KEYS = [
186
186
  'tool.t2_loader_output_invalid',
187
187
  'tool.execution_uncertain',
188
188
  'tool.input_invalid',
189
+ 'tool.hook_failed',
189
190
  'tool.input_invalid_after_mutate',
190
191
  'tool.output_invalid_after_mutate',
191
192
  'tool.handler_no_output',
@@ -538,6 +539,7 @@ const DEFAULTS = {
538
539
  'tool.t2_loader_output_invalid': 'T2 loader output validation failed after promotion',
539
540
  'tool.execution_uncertain': 'This action has an unresolved execution. Check the destination before trying it again.',
540
541
  'tool.input_invalid': 'Tool input validation failed',
542
+ 'tool.hook_failed': 'This tool call did not run: the app hit an error before it could start.',
541
543
  'tool.did_not_run': "Tool '{tool}' did not run.",
542
544
  'tool.unreachable': "Sorry, a tool couldn't be reached. Please try again.",
543
545
  'tool.input_invalid_after_mutate': 'Tool input validation failed after mutate',
@@ -767,6 +769,7 @@ export const LABEL_NOTES = {
767
769
  'tool.t2_loader_output_invalid': "Told to the model when the T2 loader's output fails its schema after promotion.",
768
770
  'tool.execution_uncertain': 'Shown when a tool operation has no confirmed outcome and cannot execute again.',
769
771
  'tool.input_invalid': "Told to the model when a tool call's input fails the tool's input schema.",
772
+ 'tool.hook_failed': "Told to the model when a host hook threw before a tool call could start. The hook's own error goes to the host as hook_failed.",
770
773
  'tool.did_not_run': 'Given by runTool and runToolStep for a call that never settled when the invoke gave no error of its own. Takes {tool}.',
771
774
  'tool.unreachable': 'Shown to the user when a tool call never reached its host. Takes {tool}.',
772
775
  'tool.input_invalid_after_mutate': "Told to the model when a tool call's input fails its schema after a guardrail changed it.",
@@ -65,14 +65,26 @@ function stripEvidenceRaw(event) {
65
65
  const { raw: _raw, ...evidence } = event.evidence;
66
66
  return { ...event, evidence };
67
67
  }
68
+ /** A called agent's event, which rides in its call's progress, is copied by the same rule. */
69
+ function nestedForClient(event, options) {
70
+ if (event.type !== 'tool' || event.tool.phase !== 'progress')
71
+ return event;
72
+ const { data } = event.tool;
73
+ if (typeof data !== 'object' || data === null || !('agent' in data) || !('event' in data)) {
74
+ return event;
75
+ }
76
+ const inner = forClient(data.event, options);
77
+ return { ...event, tool: { ...event.tool, data: { ...data, event: inner } } };
78
+ }
68
79
  /**
69
80
  * The copy of an event its reader may have. For a visitor (the default) host-only diagnostics are
70
81
  * stripped, so the copy is safe to forward to browsers or end-user SSE.
71
82
  */
72
83
  function forClient(event, options) {
84
+ const outer = nestedForClient(event, options);
73
85
  let out = options?.reader === 'builder'
74
- ? builderWording(event)
75
- : stripMediaRefused(stripCompactionInternal(stripGuardrailInternal(stripErrorInternal(event))));
86
+ ? builderWording(outer)
87
+ : stripMediaRefused(stripCompactionInternal(stripGuardrailInternal(stripErrorInternal(outer))));
76
88
  if (!options?.includeEvidenceRaw) {
77
89
  out = stripEvidenceRaw(out);
78
90
  }
@@ -1,5 +1,6 @@
1
- import { describeError, errorCopyText, errorKind, isAbortError, TheoremError, throwIfAborted, toErrorEvent, } from '../../../guardrails/error.js';
1
+ import { errorCopyText, isAbortError, TheoremError, throwIfAborted, toErrorEvent, } from '../../../guardrails/error.js';
2
2
  import { labelText } from '../../../guardrails/labels.js';
3
+ import { hookCrashFailure, hookFailed } from '../../hook-failure.js';
3
4
  import { nestedTurnModel, resolveRegisteredTurnModel } from '../../provider-dispatch.js';
4
5
  import { profileAllowsInject } from '../../stop.js';
5
6
  import { agentProfileProblem, agentToolOutputOf, splitHostInput, } from '../../tools/agent.js';
@@ -60,7 +61,8 @@ function createAgentCaller(args) {
60
61
  catch (err) {
61
62
  throwIfAborted(signal);
62
63
  // why: The hook threw before the agent was sent, so no agent turn ran.
63
- return settled('hook_failed', errorKind(err), describeError(err));
64
+ yield hookFailed('onAgentCall', err, { callId, span });
65
+ return { failure: hookCrashFailure(err, labels) };
64
66
  }
65
67
  if (shaped && 'refuse' in shaped) {
66
68
  return settled('refused_by_host', 'declined', shaped.refuse);
@@ -347,7 +347,7 @@ export const FIELD_DOCS = {
347
347
  'registerTool.outputSchema': "The tool's result as a JSON Schema, which a function tool's stand-in result is built from.",
348
348
  'registerTool.paths': 'The turn paths this tool is offered on, where * means every path; a turn with no path gets only * tools. Host profiles ignore it.',
349
349
  'registerTool.permission': "Whether the host must approve a call before it runs; the provider's own tools never ask.",
350
- 'registerTool.preTool': "Runs before the host's pre_tool onStage. A throw fails the call, and the model reads why.",
350
+ 'registerTool.preTool': "Runs before the host's pre_tool onStage. A throw fails the call, reported as hook_failed.",
351
351
  'registerTool.profile': 'The profile this agent tool runs: text, image, or speech. Register it first. Nothing it calls may stop on a gate.',
352
352
  'registerTool.serverUrl': "The MCP server's URL.",
353
353
  'registerTool.session': "How long and how many of an MCP tool's server sessions the kernel keeps.",
@@ -1,3 +1,4 @@
1
+ import { type LabelOverrides } from '../guardrails/labels.js';
1
2
  import type { TraceSpan } from '../observability/trace-schema.js';
2
3
  import type { SpanHandle } from '../observability/trace-span.js';
3
4
  import type { TurnStage } from './schema.js';
@@ -8,8 +9,11 @@ export declare function hookFailed(hook: HookName, err: unknown, at?: {
8
9
  callId?: string;
9
10
  span?: SpanHandle | undefined;
10
11
  }): TurnEventOf<'hook_failed'>;
11
- /** A call a host hook could not approve, start or keep: it fails, and the model reads why. */
12
- export declare function hookCrashFailure(err: unknown): ToolFailure;
12
+ /**
13
+ * A call a host hook could not approve, start or keep. The model reads the profile's wording; the
14
+ * hook's own error reaches the host only as `hook_failed`.
15
+ */
16
+ export declare function hookCrashFailure(err: unknown, labels?: LabelOverrides, claimed?: boolean): ToolFailure;
13
17
  /**
14
18
  * The crash reports of a call that runs past its turn, on its own trace. Its span ends when the
15
19
  * call answers, so a crash after that, such as a failed late save, is kept and added to the span
@@ -1,4 +1,5 @@
1
1
  import { describeError, errorKind } from '../guardrails/error.js';
2
+ import { labelText } from '../guardrails/labels.js';
2
3
  /** The report of a host hook that threw: the one the host reads, with its copy on the span. */
3
4
  export function hookFailed(hook, err, at = {}) {
4
5
  const { span, ...where } = at;
@@ -17,9 +18,13 @@ export function hookFailed(hook, err, at = {}) {
17
18
  });
18
19
  return event;
19
20
  }
20
- /** A call a host hook could not approve, start or keep: it fails, and the model reads why. */
21
- export function hookCrashFailure(err) {
22
- return { code: 'hook_failed', kind: errorKind(err), message: describeError(err) };
21
+ /**
22
+ * A call a host hook could not approve, start or keep. The model reads the profile's wording; the
23
+ * hook's own error reaches the host only as `hook_failed`.
24
+ */
25
+ export function hookCrashFailure(err, labels, claimed = false) {
26
+ const key = claimed ? 'tool.execution_uncertain' : 'tool.hook_failed';
27
+ return { code: 'hook_failed', kind: errorKind(err), message: labelText(key, {}, labels) };
23
28
  }
24
29
  /**
25
30
  * The crash reports of a call that runs past its turn, on its own trace. Its span ends when the
@@ -1,3 +1,4 @@
1
+ import type { LabelOverrides } from '../../guardrails/labels.js';
1
2
  import type { TurnEvent, TurnTokens } from '../types.js';
2
3
  import type { ToolDetach } from './background.js';
3
4
  import type { ToolExecuteSettlement } from './execute.js';
@@ -12,4 +13,9 @@ export interface ToolCallHooks {
12
13
  steers?: SteerQueue;
13
14
  }
14
15
  export type ToolRun = (beginBody: ((preparedInput: unknown) => Promise<ToolOperationClaim | undefined>) | undefined, hooks: ToolCallHooks) => AsyncGenerator<TurnEvent, ToolExecuteSettlement>;
15
- export declare function coordinateTool(coordinator: ToolExecutionCoordinator | undefined, identity: Omit<ToolOperationIdentity, 'invocationHash'>, invocation: unknown, signal: AbortSignal | undefined, run: ToolRun, authorizeReplay?: (outcome?: ToolOperationOutcome) => void | Promise<void>, detach?: ToolDetach): AsyncGenerator<TurnEvent, ToolExecuteSettlement>;
16
+ export declare function coordinateTool(coordinator: ToolExecutionCoordinator | undefined, identity: Omit<ToolOperationIdentity, 'invocationHash'>, invocation: unknown, signal: AbortSignal | undefined, run: ToolRun, authorizeReplay?: (outcome?: ToolOperationOutcome) => void | Promise<void>,
17
+ /** A call that may finish in the background, and the profile's wording. */
18
+ call?: {
19
+ detach?: ToolDetach;
20
+ labels?: LabelOverrides;
21
+ }): AsyncGenerator<TurnEvent, ToolExecuteSettlement>;
@@ -101,6 +101,7 @@ class CoordinatedExecution {
101
101
  committed = false;
102
102
  writeFailed = false;
103
103
  closed = false;
104
+ labels;
104
105
  terminal;
105
106
  stopped;
106
107
  spent;
@@ -406,7 +407,7 @@ class CoordinatedExecution {
406
407
  /** A call the store could not start or keep: it fails, and the model reads that failure. */
407
408
  failed(crashed) {
408
409
  const effects = this.claim ? 'unknown' : 'not_started';
409
- const outcome = failedOutcome(this.base(), effects, hookCrashFailure(crashed.error), this.spent);
410
+ const outcome = failedOutcome(this.base(), effects, hookCrashFailure(crashed.error, this.labels, this.claim !== undefined), this.spent);
410
411
  const settlement = this.claim ? outcome.replay : { ...outcome.replay, callNotStarted: true };
411
412
  return { event: outcome.event, settlement };
412
413
  }
@@ -462,22 +463,26 @@ async function* closeReporting(execution, crashed) {
462
463
  yield hookFailed('execution', crash.error, { callId: execution.callId });
463
464
  }
464
465
  }
465
- /** A call the store could not start or keep fails, and the model reads why. */
466
+ /** A call the store could not start or keep fails, and its crash is reported. */
466
467
  async function* failCall(execution, crash) {
467
468
  const failed = execution.failed(crash);
468
469
  yield failed.event;
469
- yield* closeReporting(execution);
470
+ yield* closeReporting(execution, crash);
470
471
  return failed.settlement;
471
472
  }
472
- export async function* coordinateTool(coordinator, identity, invocation, signal, run, authorizeReplay, detach) {
473
+ export async function* coordinateTool(coordinator, identity, invocation, signal, run, authorizeReplay,
474
+ /** A call that may finish in the background, and the profile's wording. */
475
+ call = {}) {
473
476
  if (!coordinator)
474
477
  return yield* run(undefined, { signal });
478
+ const { detach, labels } = call;
475
479
  const accepted = jsonObjectSchema.parse(operationWireValue(invocation));
476
480
  const operation = { ...identity, invocationHash: await toolInvocationHash(accepted) };
477
481
  const detached = detach ? detaching(detach, signal) : undefined;
478
482
  const trigger = detached?.trigger;
479
483
  const callSignal = trigger ? trigger.signal : signal;
480
484
  const execution = new CoordinatedExecution(coordinator, operation, accepted, callSignal, trigger);
485
+ execution.labels = labels;
481
486
  throwIfAborted(signal);
482
487
  const existing = await lookup(coordinator, operation, signal);
483
488
  if (existing instanceof StoreCrashed)
@@ -885,7 +885,7 @@ export async function* executeRegisteredTool(args) {
885
885
  name: args.name,
886
886
  resume: args.ctx.resume,
887
887
  snapshot: args.snapshot,
888
- }), detach);
888
+ }), { detach, labels: args.profile.labels });
889
889
  }
890
890
  async function* executeTracedTool(args) {
891
891
  const tool = args.tools.get(args.name);
@@ -1081,6 +1081,8 @@ async function* executeAgentTool(args) {
1081
1081
  }
1082
1082
  let tokens;
1083
1083
  const span = args.stages?.span;
1084
+ // why: A hook's crash goes to the host as its own event, never inside the call's progress.
1085
+ const crashes = [];
1084
1086
  const handler = async function* (input, handlerCtx) {
1085
1087
  const run = agents.run({
1086
1088
  tool,
@@ -1105,6 +1107,10 @@ async function* executeAgentTool(args) {
1105
1107
  return;
1106
1108
  }
1107
1109
  const event = next.value;
1110
+ if (event.type === 'hook_failed') {
1111
+ crashes.push(event);
1112
+ continue;
1113
+ }
1108
1114
  if (event.type === 'tokens' || event.type === 'tool') {
1109
1115
  seen.push(event);
1110
1116
  const spent = sumTurnTokens(seen);
@@ -1127,6 +1133,7 @@ async function* executeAgentTool(args) {
1127
1133
  const exec = executeFunction(args.tools, asFunction, args.safeInput, ctx, base, args.snapshot, args.stages, tool, args.beginBody);
1128
1134
  for (;;) {
1129
1135
  const next = await exec.next();
1136
+ yield* crashes.splice(0);
1130
1137
  if (next.done)
1131
1138
  return next.value;
1132
1139
  yield withAgentTokens(next.value, base.callId, tokens);
@@ -270,7 +270,7 @@ function runCall(registry, request, profile, snapshot, callId, openSpan, failBef
270
270
  name: request.name,
271
271
  resume: request.resume,
272
272
  snapshot,
273
- }), detach);
273
+ }), { detach, labels: profile.labels });
274
274
  }
275
275
  async function* invokePrepared(registry, request, profile, snapshot, callId, openSpan, failBeforeTool, agents, beginBody, step) {
276
276
  if (request.promoted?.length) {
@@ -1,6 +1,6 @@
1
1
  import { throwIfAborted } from '../../guardrails/error.js';
2
2
  import { labelText } from '../../guardrails/labels.js';
3
- import { hookCrashFailure } from '../hook-failure.js';
3
+ import { hookCrashFailure, hookFailed } from '../hook-failure.js';
4
4
  import { jsonObjectSchema } from '../json.js';
5
5
  import { runStage, stageEventFields, } from '../stages.js';
6
6
  import { splitCallOrder, stepCallIds } from './call-order.js';
@@ -57,7 +57,8 @@ export async function* runPreToolPipeline(args) {
57
57
  }
58
58
  catch (err) {
59
59
  throwIfAborted(ctx.signal);
60
- return { ok: false, kind: 'failed', failure: hookCrashFailure(err) };
60
+ yield hookFailed('tools.preTool', err, { callId: base.callId, span: stages?.span });
61
+ return { ok: false, kind: 'failed', failure: hookCrashFailure(err, ctx.profile.labels) };
61
62
  }
62
63
  }
63
64
  if (!stages && toolPreTool === undefined && after.length === 0) {
@@ -123,7 +124,9 @@ async function* runPreToolStages(args) {
123
124
  ...(stages.stepCalls ? { stepCalls: stages.stepCalls } : {}),
124
125
  });
125
126
  if (applied.crashed) {
126
- return { ok: false, kind: 'failed', failure: hookCrashFailure(applied.crashed.error) };
127
+ const { error } = applied.crashed;
128
+ yield hookFailed('onStage', error, { stage: 'pre_tool', callId, span: stages.span });
129
+ return { ok: false, kind: 'failed', failure: hookCrashFailure(error, stages.profile.labels) };
127
130
  }
128
131
  if (applied.abort) {
129
132
  return { ok: false, kind: 'aborted', aborted: applied.abort };
@@ -207,7 +207,7 @@ export interface ToolHostHooks<TIn = unknown> {
207
207
  */
208
208
  outputSchema: Record<string, unknown>;
209
209
  /**
210
- * Runs before the host's pre_tool onStage. A throw fails the call, and the model reads why.
210
+ * Runs before the host's pre_tool onStage. A throw fails the call, reported as hook_failed.
211
211
  *
212
212
  * @remarks Runs before the host's `pre_tool` `onStage`.
213
213
  */
@@ -529,7 +529,7 @@ export interface AgentToolDef extends ToolBase {
529
529
  * them.
530
530
  */
531
531
  hostOnly?: AgentToolChannel[];
532
- /** Runs before the host's pre_tool onStage. A throw fails the call, and the model reads why. */
532
+ /** Runs before the host's pre_tool onStage. A throw fails the call, reported as hook_failed. */
533
533
  preTool?: ToolHostHooks<AgentToolInput>['preTool'];
534
534
  /**
535
535
  * Gives the model an after field on this tool: the tools called in the same step that must settle
@@ -271,7 +271,7 @@ export type SessionEventOf<K extends SessionEventKind> = Extract<SessionEvent, {
271
271
  kind: K;
272
272
  }>;
273
273
  /** The host hooks whose crash the turn survives and reports as `hook_failed`. */
274
- declare const HOOK_NAMES: readonly ["execution", "background", "onStage", "onEvent", "tools.t1Policy", "outputs.validation", "compaction.trigger"];
274
+ declare const HOOK_NAMES: readonly ["execution", "background", "onStage", "onEvent", "onAgentCall", "tools.preTool", "tools.t1Policy", "outputs.validation", "compaction.trigger"];
275
275
  /** A host hook a `hook_failed` event names. */
276
276
  export type HookName = (typeof HOOK_NAMES)[number];
277
277
  /** Why a tool call failed, for the builder and for the user. */
@@ -763,7 +763,7 @@ export type TurnEvent = {
763
763
  } & DoneEvent)
764
764
  /**
765
765
  * A host hook threw, and the turn went on without its answer. A crash at a tool call's gate
766
- * fails that call instead and is reported on the call's own `tool` event.
766
+ * also fails that call, which the model reads in the profile's wording.
767
767
  */
768
768
  | {
769
769
  type: 'hook_failed';
@@ -172,6 +172,8 @@ const HOOK_NAMES = [
172
172
  'background',
173
173
  'onStage',
174
174
  'onEvent',
175
+ 'onAgentCall',
176
+ 'tools.preTool',
175
177
  'tools.t1Policy',
176
178
  'outputs.validation',
177
179
  'compaction.trigger',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.5-next.898.gf800d9a",
3
+ "version": "0.3.5-next.900.g35bbf80",
4
4
  "description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
5
5
  "keywords": [
6
6
  "agent",