@theoremjs/agents 0.3.4-next.729.g096feb6 → 0.3.4-next.733.g0520b79

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.
@@ -30,6 +30,11 @@ declare function addResultDestinations(turn: TurnDestinations, result: {
30
30
  finding: string;
31
31
  data?: unknown;
32
32
  }, provenance: Provenance): void;
33
+ /**
34
+ * Notes a remote result read back from its fence. `composeToolText` put any `data` on the last
35
+ * line, and without it a field reads as running text, which is the stricter way.
36
+ */
37
+ declare function addFencedDestinations(turn: TurnDestinations, text: string, provenance: Provenance): void;
33
38
  /** A call's verdict, and what an approval card says when the profile asks the user first. */
34
39
  interface DestinationVerdict {
35
40
  verdict: Verdict;
@@ -42,4 +47,4 @@ interface DestinationVerdict {
42
47
  */
43
48
  declare function checkDestinationGate(turn: TurnDestinations | undefined, args: unknown, policy: ResolvedGuardrailPolicy, labels?: LabelOverrides): DestinationVerdict;
44
49
  export type { DestinationVerdict, TurnDestinations };
45
- export { addGivenDestinations, addHistoryDestinations, addRequestDestinations, addResultDestinations, checkDestinationGate, turnDestinations, };
50
+ export { addFencedDestinations, addGivenDestinations, addHistoryDestinations, addRequestDestinations, addResultDestinations, checkDestinationGate, turnDestinations, };
@@ -198,6 +198,15 @@ function addResultDestinations(turn, result, provenance) {
198
198
  turn.remote.set(key, provenance.tool);
199
199
  }
200
200
  }
201
+ /**
202
+ * Notes a remote result read back from its fence. `composeToolText` put any `data` on the last
203
+ * line, and without it a field reads as running text, which is the stricter way.
204
+ */
205
+ function addFencedDestinations(turn, text, provenance) {
206
+ const cut = text.lastIndexOf('\n');
207
+ const data = cut < 0 ? undefined : parsedJson(text.slice(cut + 1));
208
+ addResultDestinations(turn, data === undefined ? { finding: text } : { finding: text.slice(0, cut), data }, provenance);
209
+ }
201
210
  /**
202
211
  * Reported whether or not the profile acts on it, so a host sees how often the
203
212
  * rule would hold a call before it turns that on.
@@ -235,4 +244,4 @@ function checkDestinationGate(turn, args, policy, labels) {
235
244
  : {}),
236
245
  };
237
246
  }
238
- export { addGivenDestinations, addHistoryDestinations, addRequestDestinations, addResultDestinations, checkDestinationGate, turnDestinations, };
247
+ export { addFencedDestinations, addGivenDestinations, addHistoryDestinations, addRequestDestinations, addResultDestinations, checkDestinationGate, turnDestinations, };
@@ -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", "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.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.injection", "detect.hint.tool_instructions", "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", "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.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.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", "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.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.injection", "detect.hint.tool_instructions", "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", "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.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.after_field',
187
187
  'tool.background_field',
188
188
  'tool.background_started',
189
+ 'tool.late_result',
189
190
  'tool.not_visible',
190
191
  'tool.builtin_not_enabled',
191
192
  'tool.provider_native',
@@ -521,6 +522,7 @@ const DEFAULTS = {
521
522
  'tool.wait_cycle': "Tool '{tool}' waits for calls that cannot finish before it: {calls}",
522
523
  'tool.background_field': 'Set to true to get a reply now and let this call finish after the turn. Leave out to wait for its result.',
523
524
  'tool.background_started': '{tool} has started and is still running. You do not have its result, so do not state or guess one, and do not call {tool} again. Tell the person it is under way and that the result comes later.',
525
+ 'tool.late_result': 'The {tool} call you started earlier has finished. This is what it returned:',
524
526
  'tool.after_field': 'Tools you are calling in this same step that must finish before this call starts. Leave out to set no order.',
525
527
  'tool.not_visible': "Tool '{tool}' is not visible this turn",
526
528
  'tool.builtin_not_enabled': "Builtin '{tool}' is not enabled this turn",
@@ -743,6 +745,7 @@ export const LABEL_NOTES = {
743
745
  'tool.wait_cycle': "Told to the model when a call's pre_tool waitFor names calls that cannot settle before it, because they wait for it or run after it. Takes {tool} and {calls}.",
744
746
  'tool.background_field': "What the model reads on the background field of a tool that sets registerTool.background to ask. Read when the tool registers, so a profile's labels do not change it.",
745
747
  'tool.background_started': 'Told to the model when a call goes on after its reply: the call runs in the background and its result comes later.',
748
+ 'tool.late_result': 'Put in front of a tool call result that a host passes in input.lateResults. Takes {tool}.',
746
749
  'tool.after_field': "What the model reads on the after field of a tool that sets registerTool.after. Read when the tool registers, so a profile's labels do not change it.",
747
750
  'tool.not_visible': 'Told to the model when it calls a tool it cannot see this turn. Takes {tool}.',
748
751
  'tool.builtin_not_enabled': 'Told to the model when it calls a provider builtin not turned on this turn. Takes {tool}.',
@@ -817,6 +820,7 @@ const LABEL_PLACEHOLDERS = {
817
820
  'sign_in.declined': SERVICE,
818
821
  'sign_in.expired': SERVICE,
819
822
  'sign_in.out_of_scope': SERVICE,
823
+ 'tool.late_result': ['tool'],
820
824
  'tool.awaiting_user': ['kind', 'prompt'],
821
825
  'tool.t2_loader_needs_snapshot': TOOL,
822
826
  'tool.t2_loader_shape': TOOL,
@@ -11,6 +11,18 @@ declare function isRemoteOrigin(origin: ToolOrigin): boolean;
11
11
  * friendlier provenance than it has by writing one into its own body.
12
12
  */
13
13
  declare function wrapToolData(text: string, provenance: Provenance, advisory?: AdvisoryLevel, labels?: LabelOverrides): string;
14
+ /** What a fence from `wrapToolData` says of the text inside it. */
15
+ export interface ToolDataRead {
16
+ provenance: Provenance;
17
+ suspicious: GuardrailHit[];
18
+ /** The result as `composeToolText` joined it. */
19
+ text: string;
20
+ }
21
+ /**
22
+ * Reads the fence at the start of a tool message. `stripToolFences` has taken any forged tag out of
23
+ * the body, so what the tag says is the kernel's. `undefined` when `content` is not one whole fence.
24
+ */
25
+ declare function readToolData(content: string): ToolDataRead | undefined;
14
26
  /** A tool result after the guard: the text the model sees, any event, and the suspicious hits. */
15
27
  export interface GuardedToolText {
16
28
  /** Absent when a match blocks: the model does not read the text. */
@@ -89,4 +101,4 @@ declare function isSuspicious(taint: TurnTaint | undefined): boolean;
89
101
  * or not enforcement is configured, so the risk is visible before a host opts in.
90
102
  */
91
103
  declare function checkTaintGate(taint: TurnTaint | undefined, access: string, policy: ResolvedGuardrailPolicy, labels?: LabelOverrides): Verdict;
92
- export { checkTaintGate, composeToolText, guardShownValue, guardToolFailureText, guardToolResult, inspectToolArguments, isRemoteOrigin, isSuspicious, isTainted, recordTaint, TOOL_CLOSE, toolCallEvent, wrapToolData, };
104
+ export { checkTaintGate, composeToolText, guardShownValue, guardToolFailureText, guardToolResult, inspectToolArguments, isRemoteOrigin, isSuspicious, isTainted, readToolData, recordTaint, TOOL_CLOSE, toolCallEvent, wrapToolData, };
@@ -66,6 +66,25 @@ function wrapToolData(text, provenance, advisory = 'none', labels) {
66
66
  : `${advisoryNotice(advisory, labels)}${guidance ? ` ${guidance}` : ''}\n`;
67
67
  return `<${'tool_data'} ${attrs}>\n${notice}${stripToolFences(text)}\n${TOOL_CLOSE}`;
68
68
  }
69
+ /**
70
+ * Reads the fence at the start of a tool message. `stripToolFences` has taken any forged tag out of
71
+ * the body, so what the tag says is the kernel's. `undefined` when `content` is not one whole fence.
72
+ */
73
+ function readToolData(content) {
74
+ const open = /^<tool_data tool="([^"]*)" origin="([^"]*)"(?: advisory="[^"]*")?>\n/.exec(content);
75
+ if (!(open && content.endsWith(`\n${TOOL_CLOSE}`)))
76
+ return undefined;
77
+ const [opening, tool = '', origin = ''] = open;
78
+ const body = content.slice(opening.length, -TOOL_CLOSE.length - 1);
79
+ const advised = opening.includes(' advisory=');
80
+ return {
81
+ provenance: { origin: origin, tool, depth: origin === 'delegated' ? 2 : 1 },
82
+ suspicious: advised
83
+ ? [{ rule: DETECT_RULES.tool_instructions, severity: 'high' }]
84
+ : [],
85
+ text: advised ? body.slice(body.indexOf('\n') + 1) : body,
86
+ };
87
+ }
69
88
  /**
70
89
  * Deliberately an observation, not an instruction: what the agent should do about
71
90
  * it is product behaviour, supplied by the host as labels `advisory.guidance`. Emitted
@@ -269,4 +288,4 @@ function checkTaintGate(taint, access, policy, labels) {
269
288
  rejection: labelText('taint.blocked', { access, sources: read, reason }, labels),
270
289
  };
271
290
  }
272
- export { checkTaintGate, composeToolText, guardShownValue, guardToolFailureText, guardToolResult, inspectToolArguments, isRemoteOrigin, isSuspicious, isTainted, recordTaint, TOOL_CLOSE, toolCallEvent, wrapToolData, };
291
+ export { checkTaintGate, composeToolText, guardShownValue, guardToolFailureText, guardToolResult, inspectToolArguments, isRemoteOrigin, isSuspicious, isTainted, readToolData, recordTaint, TOOL_CLOSE, toolCallEvent, wrapToolData, };
@@ -33,6 +33,11 @@ export const REQUEST_FIELDS = {
33
33
  doc: "What the page (client) or the host (server) wants the model to know, as any JSON or text; a sender the profile's inputs.context does not list, or a package over its maxChars, is refused.",
34
34
  unset: 'No context',
35
35
  },
36
+ 'runTurn.input.lateResults': {
37
+ type: 'ToolOperationOutcome[]',
38
+ doc: 'Background tool calls that settled after their turn, as the host stored them. The model reads each as a tool result, and this reply counts it as a remote read when the call was remote. Pass them on each run of the reply.',
39
+ unset: 'No late results',
40
+ },
36
41
  'runTurn.input.attachments': {
37
42
  type: 'Array<TurnBlob | TurnMediaRef>',
38
43
  doc: "Files sent with the turn, as bytes or as a provider file reference; each must pass the profile's inputs.attachments.",
@@ -163,6 +168,14 @@ export const REQUEST_FIELDS = {
163
168
  doc: 'Runs before each agent tool call, to shape the request to the called agent or to refuse the call.',
164
169
  unset: 'The agent runs on what the model sent',
165
170
  },
171
+ 'runTurn.onEvent': {
172
+ type: '(event: TurnEvent) => void | Promise<void>',
173
+ doc: "Reads each of the turn's events as it leaves runTurn, before the caller gets it. A throw ends the turn with that error.",
174
+ },
175
+ 'runTurn.answersHeldCall': {
176
+ type: 'true',
177
+ doc: "Set on the turn TurnWiring.prepare is given for a held call that goes on once answered: no model runs, and input is the paused turn's.",
178
+ },
166
179
  };
167
180
  /** The catalog of the exports a builder calls by name, keyed by that name. */
168
181
  export const API_EXPORTS = {
@@ -4,10 +4,7 @@ import type { KernelRegistry } from '../../registry/kernel-registry.js';
4
4
  import type { AgentCaller } from '../../tools/agent.js';
5
5
  import type { InvokeToolRequest } from '../../tools/types.js';
6
6
  import type { CompactHistoryRequest, CompactionResult, SessionRequest, TurnEvent, TurnModel, TurnRequest } from '../../types.js';
7
- /**
8
- * The trace record is written however the turn ends, including when the host stops reading early;
9
- * spans still open then close as `ERROR` / `unclosed`.
10
- */
7
+ /** A turn's events, each read by `req.onEvent` before the caller gets it. */
11
8
  declare function runTurnInRegistry(registry: KernelRegistry, req: TurnRequest, provider: TurnModel, sinkOverride?: TraceSink): AsyncGenerator<TurnEvent>;
12
9
  /**
13
10
  * A host's own call's agent tools: the host's provider, or the one `onAgentCall`
@@ -243,6 +243,7 @@ async function* emitTurn(args) {
243
243
  tools: args.registry.tools,
244
244
  profile,
245
245
  generation,
246
+ input: safe.input ?? {},
246
247
  trace: args.trace,
247
248
  ...(args.agents ? { agents: args.agents } : {}),
248
249
  ...(args.background ? { background: args.background } : {}),
@@ -380,7 +381,7 @@ async function* runTracedTurn(ctx, provider) {
380
381
  * The trace record is written however the turn ends, including when the host stops reading early;
381
382
  * spans still open then close as `ERROR` / `unclosed`.
382
383
  */
383
- async function* runTurnInRegistry(registry, req, provider, sinkOverride) {
384
+ async function* tracedTurnInRegistry(registry, req, provider, sinkOverride) {
384
385
  const tree = startTrace(`invoke_agent ${req.profile}`, {
385
386
  ...turnSpanOptions(req),
386
387
  ...(req.traceparent ? { traceparent: req.traceparent } : {}),
@@ -454,6 +455,13 @@ async function* emitCancelledDoneAfterAbort(ctx) {
454
455
  yield* emitObservedStage(ctx, stageEv, profile);
455
456
  }
456
457
  }
458
+ /** A turn's events, each read by `req.onEvent` before the caller gets it. */
459
+ async function* runTurnInRegistry(registry, req, provider, sinkOverride) {
460
+ for await (const event of tracedTurnInRegistry(registry, req, provider, sinkOverride)) {
461
+ await req.onEvent?.(event);
462
+ yield event;
463
+ }
464
+ }
457
465
  async function* runTurnBody(ctx, provider) {
458
466
  assertBackgroundCoordinator(ctx.req.background, ctx.req.execution);
459
467
  const checkStart = performance.now();
@@ -6,7 +6,7 @@ import type { SpanHandle } from '../../../observability/trace-span.js';
6
6
  import type { AgentCaller } from '../../tools/agent.js';
7
7
  import type { ToolBackgroundSupport } from '../../tools/background.js';
8
8
  import type { ToolRegistry } from '../../tools/registry.js';
9
- import type { InteractionPart, ModelBinding, Profile, ResolvedGeneration, TurnEvent, TurnHistoryMessage, TurnRequest, TurnStop, TurnToolResult } from '../../types.js';
9
+ import type { InteractionPart, ModelBinding, Profile, ResolvedGeneration, TurnEvent, TurnHistoryMessage, TurnInput, TurnRequest, TurnStop, TurnToolResult } from '../../types.js';
10
10
  import type { ItemFailure } from './schema-validation.js';
11
11
  import type { CallUsage } from './usage.js';
12
12
  interface TurnTraceState {
@@ -109,6 +109,8 @@ declare function openTurnState(args: {
109
109
  tools: ToolRegistry;
110
110
  profile: Profile;
111
111
  generation: ResolvedGeneration;
112
+ /** The request's input, on the run that opens the turn. */
113
+ input?: TurnInput;
112
114
  trace: TurnTraceState;
113
115
  allEmittedEvents?: TurnEvent[];
114
116
  agents?: AgentCaller;
@@ -1,5 +1,8 @@
1
- import { turnDestinations } from '../../../guardrails/destinations.js';
2
- import { givenUrlSets } from '../../../guardrails/egress-urls.js';
1
+ import { addFencedDestinations, addGivenDestinations, addResultDestinations, turnDestinations, } from '../../../guardrails/destinations.js';
2
+ import { addSeenUrls, givenUrlSets } from '../../../guardrails/egress-urls.js';
3
+ import { labelText } from '../../../guardrails/labels.js';
4
+ import { isRemoteOrigin, readToolData, recordTaint, wrapToolData, } from '../../../guardrails/tool-result.js';
5
+ import { originOfTool } from '../../tools/execute.js';
3
6
  import { ownToolsOf } from '../../tools/project.js';
4
7
  function recordStepEvent(event, state) {
5
8
  state.allEmittedEvents.push(event);
@@ -14,6 +17,53 @@ function appendUserInput(state, parts) {
14
17
  ? { role: 'user', content: parts.map((p) => (p.type === 'text' ? p.text : '')).join('') }
15
18
  : { role: 'user', parts: [...parts] });
16
19
  }
20
+ /** Whether this run goes on with a reply that an earlier run began, not with a new message. */
21
+ function continuesReply(input, history) {
22
+ if (input.text || input.attachments?.length || input.voice?.length)
23
+ return false;
24
+ return history.at(-1)?.role === 'tool';
25
+ }
26
+ /**
27
+ * invariant: Taint lasts for the reply that first read the text, and a pause does not end a reply.
28
+ * The run after a pause reads the marks back from the tool results of that reply.
29
+ */
30
+ function carryReplyReads(state, history) {
31
+ const start = history.findLastIndex((message) => message.role === 'user') + 1;
32
+ for (const message of history.slice(start)) {
33
+ if (message.role !== 'tool' || message.content === undefined)
34
+ continue;
35
+ const read = readToolData(message.content);
36
+ if (read) {
37
+ state.taint = recordTaint(state.taint, read.provenance, read.suspicious);
38
+ addFencedDestinations(state.destinations, read.text, read.provenance);
39
+ continue;
40
+ }
41
+ const tool = message.name ? state.tools.get(message.name) : undefined;
42
+ if (tool && !isRemoteOrigin(originOfTool(tool, state.tools))) {
43
+ addGivenDestinations(state.destinations, message.content);
44
+ }
45
+ }
46
+ }
47
+ /** A late result is read as a tool's result, so its message is no one's word to the model. */
48
+ function openLateResults(state, outcomes, labels) {
49
+ if (outcomes.length === 0)
50
+ return;
51
+ const blocks = outcomes.map(({ event, replay }) => {
52
+ const { name, readBack = '' } = event.tool;
53
+ const result = replay.modelResult;
54
+ const provenance = result?.provenance ?? { origin: 'local', tool: name, depth: 1 };
55
+ if (result?.provenance) {
56
+ state.taint = recordTaint(state.taint, result.provenance, result.suspicious);
57
+ addResultDestinations(state.destinations, result, result.provenance);
58
+ }
59
+ addSeenUrls(state.givenUrls.tools, readBack);
60
+ const fenced = readToolData(readBack) ? readBack : wrapToolData(readBack, provenance);
61
+ return `${labelText('tool.late_result', { tool: name }, labels)}\n${fenced}`;
62
+ });
63
+ const message = { role: 'user', content: blocks.join('\n\n') };
64
+ state.givenUrls.own.add(message);
65
+ state.currentHistory.push(message);
66
+ }
17
67
  /**
18
68
  * Step state for one turn. A text turn's history grows inside the turn (tool
19
69
  * steps, stage injects, repair retries), so its opening input moves into turn
@@ -46,6 +96,10 @@ function openTurnState(args) {
46
96
  ...(args.background ? { background: args.background } : {}),
47
97
  };
48
98
  if (profile.type === 'text') {
99
+ if (args.input && continuesReply(args.input, state.currentHistory)) {
100
+ carryReplyReads(state, state.currentHistory);
101
+ }
102
+ openLateResults(state, args.input?.lateResults ?? [], profile.labels);
49
103
  appendUserInput(state, generation.input);
50
104
  generation.input = [];
51
105
  }
@@ -163,10 +163,17 @@ export async function checkKey(provider, options = {}) {
163
163
  ...(said ? { said } : {}),
164
164
  };
165
165
  }
166
+ // why: A `/\/+$/` scan is quadratic on a long run of slashes.
167
+ function withoutTrailingSlashes(url) {
168
+ let end = url.length;
169
+ while (url[end - 1] === '/')
170
+ end--;
171
+ return url.slice(0, end);
172
+ }
166
173
  function urlFor(serve, path, apiId, stream) {
167
174
  if (serve.url)
168
175
  return new URL(serve.url({ path, apiId, stream }));
169
- return new URL(serve.baseUrl.replace(/\/+$/, '') + (path.startsWith('/') ? path : `/${path}`));
176
+ return new URL(withoutTrailingSlashes(serve.baseUrl) + (path.startsWith('/') ? path : `/${path}`));
170
177
  }
171
178
  async function* defaultFraming(response, stream) {
172
179
  const type = response.headers.get('content-type') ?? '';
@@ -1,6 +1,7 @@
1
1
  import { type ToolBoundary } from '../../guardrails/boundaries.js';
2
2
  import { type DetectScope } from '../../guardrails/detect-at.js';
3
3
  import { type LabelOverrides } from '../../guardrails/labels.js';
4
+ import type { ToolOrigin } from '../../guardrails/types.js';
4
5
  import type { SpanHandle, TraceAttributes } from '../../observability/trace-span.js';
5
6
  import { type ToolCallEnd } from '../engine/tool-trace.js';
6
7
  import type { InjectUnit } from '../stages.js';
@@ -11,8 +12,9 @@ import { startToolExecution, type ToolCallBase } from './events.js';
11
12
  import type { ToolExecutionCoordinator, ToolOperationClaim, ToolOperationOutcome } from './operation.js';
12
13
  import type { ToolRegistry } from './registry.js';
13
14
  import { type ToolStageSupport } from './stage-run.js';
14
- import type { FunctionToolDef, ModelToolResult, RegisteredAgentTool, ToolContext, ToolFailure, ToolGate, TurnToolSnapshot } from './types.js';
15
+ import type { FunctionToolDef, ModelToolResult, RegisteredAgentTool, RegisteredTool, ToolContext, ToolFailure, ToolGate, TurnToolSnapshot } from './types.js';
15
16
  export { checkPermission, isGateResumeGranted, isResumeContinuation, permissionGranted, } from './permission.js';
17
+ export declare function originOfTool(tool: RegisteredTool, tools: ToolRegistry): ToolOrigin;
16
18
  /**
17
19
  * The boundary a call of `name` is read at before its tool gets it: none for a provider builtin,
18
20
  * whose text the kernel never reads. A call no tool takes is read as a function tool's.
@@ -27,7 +27,7 @@ import { CredentialRefusedError, signedInFetch } from './signed-in-fetch.js';
27
27
  import { emitGateSettlement, runPostToolStages, runPreToolPipeline, } from './stage-run.js';
28
28
  export { checkPermission, isGateResumeGranted, isResumeContinuation, permissionGranted, } from './permission.js';
29
29
  import { UncheckedOutput } from './unchecked-output.js';
30
- function originOfTool(tool, tools) {
30
+ export function originOfTool(tool, tools) {
31
31
  if (tool.type === 'agent')
32
32
  return agentToolOrigin(tools.findProfile(tool.profile));
33
33
  if (tool.type === 'http')
@@ -4,7 +4,7 @@ import type { CacheMode, CacheTtl, CompactionMeter, CompactionOutcome, Compactio
4
4
  import type { StageHandler } from './stages.js';
5
5
  import type { ToolBackgroundService } from './tools/background.js';
6
6
  import type { GateDecision } from './tools/gate-answer.js';
7
- import type { PageToolExecution, ToolExecutionCoordinator } from './tools/operation.js';
7
+ import type { PageToolExecution, ToolExecutionCoordinator, ToolOperationOutcome } from './tools/operation.js';
8
8
  import type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, HostProfileToolsSpec, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, LiveProfileToolsSpec, ModelToolResult, PageAnswer, ProfileToolsSpec, RegisteredTool, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolPolicy, TurnToolSnapshot, WireFunctionTool } from './tools/types.js';
9
9
  import type { AttemptReason, CallDone, CompactionFailure, CompactionResult, CompactionSignal, DoneFields, GroundingEvent, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, ModelEvent, ProviderEvidence, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnTokenSide, TurnTokens } from './turn-events.js';
10
10
  export type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, AttemptReason, CacheMode, CacheTtl, CallDone, CompactionFailure, CompactionMeter, CompactionOutcome, CompactionResult, CompactionSignal, CompactionTiming, ContinueStopKind, DoneFields, FieldMeta, GroundingEvent, HostProfileToolsSpec, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveProfileToolsSpec, LiveStartSensitivity, MediaInputKind, ModelEvent, ProfileToolsSpec, ProfileType, ProviderEvidence, RegisteredTool, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolLoadTier, ToolPolicy, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnStage, TurnStopKind, TurnTokenSide, TurnTokens, TurnToolSnapshot, WireFunctionTool, };
@@ -737,6 +737,8 @@ export interface TurnInput {
737
737
  attachments?: Array<TurnBlob | TurnMediaRef>;
738
738
  voice?: TurnBlob[];
739
739
  history?: TurnHistoryMessage[];
740
+ /** Tool calls that settled after their turn, as the host stored them. Each counts as read in this reply. */
741
+ lateResults?: ToolOperationOutcome[];
740
742
  repair?: TurnRepairRequest;
741
743
  /**
742
744
  * Optional host-supplied history token count for `meter: 'history'`.
@@ -839,6 +841,17 @@ export interface TurnRequest extends AgentRunRequest {
839
841
  * so an answered call does not give the reply its steps back. Read `done.steps`.
840
842
  */
841
843
  stepsTaken?: number;
844
+ /**
845
+ * Reads each of this turn's events as it leaves `runTurn`, before the caller gets it. The app
846
+ * sets it in `TurnWiring.prepare` to act on a turn someone else runs, such as saving the reply
847
+ * when `done` arrives. A throw ends the turn with that error. `invokeTool` does not call it.
848
+ */
849
+ onEvent?: (event: TurnEvent) => void | Promise<void>;
850
+ /**
851
+ * Set on the turn `TurnWiring.prepare` is given for a held call that goes on once answered. No
852
+ * model runs and `input` is the paused turn's, so it is not a new message.
853
+ */
854
+ answersHeldCall?: true;
842
855
  input?: TurnInput;
843
856
  }
844
857
  /**
@@ -854,8 +867,8 @@ export interface TurnWiring {
854
867
  /**
855
868
  * The turn the application runs, from the one it is given: the profile, the input with the
856
869
  * conversation's history, and the application's context as `host`. Set what the application
857
- * sets per turn, such as `system`, `credentials`, `onStage`, `onAgentCall`, `path` and
858
- * `metadata`. Text, image and speech turns run through it.
870
+ * sets per turn, such as `system`, `credentials`, `onStage`, `onEvent`, `onAgentCall`, `path`
871
+ * and `metadata`. Text, image and speech turns run through it.
859
872
  */
860
873
  prepare?: (turn: NormalizedTurnRequest) => TurnRequest | Promise<TurnRequest>;
861
874
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.729.g096feb6",
3
+ "version": "0.3.4-next.733.g0520b79",
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",