@theoremjs/agents 0.3.4-next.693.g4ab1526 → 0.3.4-next.711.g78e504a

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 (53) hide show
  1. package/README.md +1 -1
  2. package/esm/mod.d.ts +3 -2
  3. package/esm/mod.js +1 -1
  4. package/esm/src/guardrails/labels.d.ts +1 -1
  5. package/esm/src/guardrails/labels.js +6 -0
  6. package/esm/src/interface/history.d.ts +2 -2
  7. package/esm/src/interface/history.js +7 -4
  8. package/esm/src/interface/mod.d.ts +1 -1
  9. package/esm/src/interface/mod.js +1 -1
  10. package/esm/src/interface/tool-calls.d.ts +3 -3
  11. package/esm/src/interface/tool-calls.js +5 -8
  12. package/esm/src/interface/tool-invoke.d.ts +3 -1
  13. package/esm/src/interface/tool-invoke.js +6 -1
  14. package/esm/src/interface/types.d.ts +1 -1
  15. package/esm/src/kernel/api-catalog.js +8 -0
  16. package/esm/src/kernel/engine/background.d.ts +7 -0
  17. package/esm/src/kernel/engine/background.js +18 -0
  18. package/esm/src/kernel/engine/runner/mod.js +23 -1
  19. package/esm/src/kernel/engine/runner/state.d.ts +4 -0
  20. package/esm/src/kernel/engine/runner/state.js +1 -0
  21. package/esm/src/kernel/engine/runner/step-order.d.ts +8 -0
  22. package/esm/src/kernel/engine/runner/step-order.js +1 -1
  23. package/esm/src/kernel/engine/runner/steps.js +1 -0
  24. package/esm/src/kernel/engine/session/mod.d.ts +2 -0
  25. package/esm/src/kernel/engine/session/mod.js +19 -2
  26. package/esm/src/kernel/mod.d.ts +3 -2
  27. package/esm/src/kernel/mod.js +1 -1
  28. package/esm/src/kernel/schema.js +12 -0
  29. package/esm/src/kernel/tools/background.d.ts +81 -0
  30. package/esm/src/kernel/tools/background.js +70 -0
  31. package/esm/src/kernel/tools/call-order.d.ts +3 -1
  32. package/esm/src/kernel/tools/call-order.js +10 -6
  33. package/esm/src/kernel/tools/coordinate.d.ts +8 -1
  34. package/esm/src/kernel/tools/coordinate.js +274 -34
  35. package/esm/src/kernel/tools/execute.d.ts +2 -0
  36. package/esm/src/kernel/tools/execute.js +17 -4
  37. package/esm/src/kernel/tools/invoke.js +40 -13
  38. package/esm/src/kernel/tools/memory-execution.js +10 -1
  39. package/esm/src/kernel/tools/operation.d.ts +21 -0
  40. package/esm/src/kernel/tools/operation.js +19 -10
  41. package/esm/src/kernel/tools/registry.js +20 -1
  42. package/esm/src/kernel/tools/resolve.d.ts +4 -2
  43. package/esm/src/kernel/tools/resolve.js +23 -7
  44. package/esm/src/kernel/tools/run.d.ts +2 -2
  45. package/esm/src/kernel/tools/run.js +4 -1
  46. package/esm/src/kernel/tools/stage-run.d.ts +2 -0
  47. package/esm/src/kernel/tools/stage-run.js +1 -0
  48. package/esm/src/kernel/tools/types.d.ts +7 -0
  49. package/esm/src/kernel/turn-events.d.ts +8 -1
  50. package/esm/src/kernel/turn-events.js +2 -0
  51. package/esm/src/kernel/types.d.ts +8 -0
  52. package/esm/src/providers/open-ai/protocol.js +8 -4
  53. package/package.json +1 -1
package/README.md CHANGED
@@ -464,7 +464,7 @@ Named exports from the root barrel (same symbols hosts get from `@theoremjs/agen
464
464
  | Scope | `KernelScope`, `createKernelScope`, `defaultKernelScope`, `KernelRegistry`, `createKernelRegistry` |
465
465
  | Profiles | `ProfileDefinition`, `ProfileDefinitionBase`, `TextProfileDefinition`, `ImageProfileDefinition`, `SpeechProfileDefinition`, `TranscriptionProfileDefinition`, `LiveProfileDefinition`, `HostProfileDefinition`, `DecisionProfileDefinition`, `EmbeddingProfileDefinition`, `ProfileRegistry`, `createProfileRegistry`, `clearProfiles`, `defineProfile`, `getProfile`, `hasProfile`, `listProfiles`, `registerProfile`, `registerProfiles`, `projectProfile`, `resolveTurn`, `pickModel`, `resolveTurnSystemPrompt`, `systemLinesProblem` |
466
466
  | Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `createToolRegistry`, `registerTool`, `registerTools`, `invokeTool`, `invokeToolStep`, `runTool`, `runToolStep`, `SettledToolCall`, `ToolCallResult`, `ToolStepCallResult`, `GATE_DECISIONS`, `GateDecision`, `askUserTool`, `registerHarnessTools`, `getTool`, `hasTool`, `requireTool`, `listTools`, `resetTools`, `formatToolResult`, `prepareTurnToolSnapshot`, `buildHttpToolTarget`, `executeHttpTool`, `executeMcpTool`, `parseMcpRpcResponse`, `isUnsupportedMcpProtocolError`, `MCP_PROTOCOL_VERSIONS`, `mcpRequestMeta`, `McpProtocolVersion`, `resolveToolAuth`, `credentialPlacement`, `withCredentialQuery`, `CredentialQuery`, `uncheckedOutput`, `UncheckedOutput`, `McpRpcResponse`, `ModelToolResult`, `PageAnswer` |
467
- | Tool execution | `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
467
+ | Tool execution | `ToolBackground`, `ToolBackgroundCall`, `ToolBackgroundHandle`, `ToolBackgroundService`, `ToolOperationReply`, `toolOperationReplySchema`, `BackgroundToolEvent`, `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
468
468
  | Structured | `SchemaRegistry`, `createSchemaRegistry`, `getStructured`, `registerStructured` |
469
469
  | Stop / resume | `ProfileTurnBehaviourSpec`, `MediaTurnBehaviourSpec`, `ProfileTurnResumptionSpec`, `TurnContinueFrom`, `TurnStop`, `TurnStopKind`, `ContinueStopKind`, `StepLimitMode`, `CONTINUE_STOP_KINDS`, `AUTO_CONTINUE_DELAY_MS`, `DEFAULT_ALLOW_CONTINUE`, `DEFAULT_AUTO_CONTINUE`, `GenerationStopError`, `isContinueStopKind`, `isGenerationStopError`, `isResumeableStop`, `isUserCancelledStop`, `profileAllowsSteering`, `profileAllowsInject`, `profileTurnResumption`, `shouldAutoContinue`, `turnStopFromClientStreamEnd`, `turnStopFromInteractionStatus`, `turnStopFromOpenAiFinishReason` |
470
470
  | Stages (target foundation) | `TURN_STAGES`, `TURN_INJECT_STAGES`, `STAGE_AFFORDANCES`, `STAGE_AFFORDANCE_MATRIX`, `TOOL_GATE_KINDS`, `AWAITING_USER_INPUT_KINDS`, `AWAITING_USER_INPUT_STATUS`, `applyStageResult`, `awaitingUserInputSchema`, `toolGateSchema`, `isTurnStage`, `isTurnInjectStage`, `isToolGateKind`, `isAwaitingUserInput`, `stageAllowsAffordance`, `stageEventFields`, `profileAllowsInject`, `StageAffordance`, `StageContext`, `StageResult`, `StageMutate`, `StageHandler`, `StageApplyInput`, `StageApplyOutput`, `StageApplyWarning`, `StageApplyWarningCode`, `StageEventExtra`, `AwaitingUserInput`, `ToolGate` — contract [`docs/contracts/stages.md`](https://github.com/masudl-hub/theoremai/blob/main/docs/contracts/stages.md) |
package/esm/mod.d.ts CHANGED
@@ -65,14 +65,15 @@ export { applyStageResult, STAGE_AFFORDANCE_MATRIX, STAGE_AFFORDANCES, stageAllo
65
65
  export type { MediaTurnBehaviourSpec, ProfileTurnBehaviourSpec, ProfileTurnResumptionSpec, TurnContinueFrom, TurnStop, } from './src/kernel/stop.js';
66
66
  export { AUTO_CONTINUE_DELAY_MS, DEFAULT_ALLOW_CONTINUE, DEFAULT_AUTO_CONTINUE, GenerationStopError, isContinueStopKind, isGenerationStopError, isResumeableStop, isUserCancelledStop, profileAllowsInject, profileAllowsSteering, profileTurnResumption, shouldAutoContinue, turnStopFromClientStreamEnd, turnStopFromInteractionStatus, turnStopFromOpenAiFinishReason, } from './src/kernel/stop.js';
67
67
  export { systemLinesProblem } from './src/kernel/system-lines.js';
68
+ export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, } from './src/kernel/tools/background.js';
68
69
  export { authorizeToolReplay } from './src/kernel/tools/execute.js';
69
70
  export { GATE_DECISIONS, type GateDecision } from './src/kernel/tools/gate-answer.js';
70
71
  export type { MemoryToolExecutionOptions } from './src/kernel/tools/memory-execution.js';
71
72
  export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
72
73
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './src/kernel/tools/mod.js';
73
74
  export { askUserTool, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
74
- export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
75
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
75
+ export type { BackgroundToolEvent, BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
76
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './src/kernel/tools/operation.js';
76
77
  export type { SettledToolCall, ToolCallResult, ToolStepCallResult, } from './src/kernel/tools/run.js';
77
78
  export type { ModelToolResult, PageAnswer, ToolContext } from './src/kernel/tools/types.js';
78
79
  export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
package/esm/mod.js CHANGED
@@ -45,7 +45,7 @@ export { authorizeToolReplay } from './src/kernel/tools/execute.js';
45
45
  export { GATE_DECISIONS } from './src/kernel/tools/gate-answer.js';
46
46
  export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
47
47
  export { askUserTool, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
48
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
48
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './src/kernel/tools/operation.js';
49
49
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
50
50
  export { buildRecord, clearTraceDestinations, contentOf, getTraceDestination, inlineContent, isTraceSink, listTraceDestinationIds, memorySink, noopSink, readTraceparent, registerTraceDestination, requireTraceDestination, resolveObservabilityPolicy, resolveTraceWriter, startTrace, TRACE_ATTRIBUTE_GROUPS, TRACE_FIELDS, TRACE_SPAN_TYPES, TRACE_STATUS, toOtlpJson, traceAttributeMeta, traceBytes, traceContent, traceEventAttributeMeta, traceEventMeta, traceJson, traceRecordSchema, traceSpanMeta, writeTrace, } from './src/observability/mod.js';
51
51
  export * from './src/providers/mod.js';
@@ -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.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.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
  /**
@@ -184,6 +184,8 @@ export const LABEL_KEYS = [
184
184
  'tool.wait_unknown',
185
185
  'tool.wait_cycle',
186
186
  'tool.after_field',
187
+ 'tool.background_field',
188
+ 'tool.background_started',
187
189
  'tool.not_visible',
188
190
  'tool.builtin_not_enabled',
189
191
  'tool.provider_native',
@@ -517,6 +519,8 @@ const DEFAULTS = {
517
519
  'tool.not_loaded_t2': "Tool '{tool}' is not loaded — call {loader} to load it first",
518
520
  'tool.wait_unknown': "Tool '{tool}' waits for calls that are not in this step: {calls}",
519
521
  'tool.wait_cycle': "Tool '{tool}' waits for calls that cannot finish before it: {calls}",
522
+ '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
+ '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.',
520
524
  'tool.after_field': 'Tools you are calling in this same step that must finish before this call starts. Leave out to set no order.',
521
525
  'tool.not_visible': "Tool '{tool}' is not visible this turn",
522
526
  'tool.builtin_not_enabled': "Builtin '{tool}' is not enabled this turn",
@@ -737,6 +741,8 @@ export const LABEL_NOTES = {
737
741
  'tool.not_loaded_t2': 'Told to the model when it calls a T2 tool the T2 loader has not loaded yet. Takes {tool} and {loader}, the loader tool.',
738
742
  'tool.wait_unknown': "Told to the model when a call's pre_tool waitFor names calls that are not in its step. Takes {tool} and {calls}.",
739
743
  '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
+ '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
+ '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.',
740
746
  '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.",
741
747
  'tool.not_visible': 'Told to the model when it calls a tool it cannot see this turn. Takes {tool}.',
742
748
  'tool.builtin_not_enabled': 'Told to the model when it calls a provider builtin not turned on this turn. Takes {tool}.',
@@ -3,8 +3,8 @@ import { type ToolCallRequest } from '../kernel/turn-events.js';
3
3
  import type { TurnBlob, TurnEvent, TurnHistoryMessage } from '../kernel/types.js';
4
4
  import type { ToolCall, TranscriptBlock, UserTurnDraft } from './types.js';
5
5
  /**
6
- * The kernel sets `readBack` on every `complete` and `error` event, so a call without it did not
7
- * come from a run and has no text the model read.
6
+ * The kernel sets `readBack` on every `complete`, `error` and `background` event, so a call without
7
+ * it did not come from a run and has no text the model read.
8
8
  */
9
9
  declare function toolReadBack(call: ToolCall): string;
10
10
  /** The files a user turn adds to the history beside its text. */
@@ -7,12 +7,13 @@ import { formatToolFailureForModel, formatToolResult } from '../kernel/tools/mod
7
7
  import { keptReply } from '../kernel/turn-events.js';
8
8
  import { applyToolEvent, toolCallRanWith } from './tool-calls.js';
9
9
  /**
10
- * The kernel sets `readBack` on every `complete` and `error` event, so a call without it did not
11
- * come from a run and has no text the model read.
10
+ * The kernel sets `readBack` on every `complete`, `error` and `background` event, so a call without
11
+ * it did not come from a run and has no text the model read.
12
12
  */
13
13
  function toolReadBack(call) {
14
14
  const state = call.state;
15
- if ((state?.phase !== 'complete' && state?.phase !== 'error') || state.readBack === undefined) {
15
+ if ((state?.phase !== 'complete' && state?.phase !== 'error' && state?.phase !== 'background') ||
16
+ state.readBack === undefined) {
16
17
  throw new TheoremError('request', `Tool call '${call.name}' has no readBack: only a settled call from a run carries one.`);
17
18
  }
18
19
  return state.readBack;
@@ -102,7 +103,9 @@ function appendToolDenialToHistory(history, tool, labels) {
102
103
  /** `undefined` while the call is open. */
103
104
  function settledToolContent(call) {
104
105
  const phase = call.state?.phase;
105
- return phase === 'complete' || phase === 'error' ? toolReadBack(call) : undefined;
106
+ return phase === 'complete' || phase === 'error' || phase === 'background'
107
+ ? toolReadBack(call)
108
+ : undefined;
106
109
  }
107
110
  /**
108
111
  * One model step's settled calls: a single assistant message holding every call
@@ -26,7 +26,7 @@ export type { WordedStopKind } from './stop.js';
26
26
  export { stopText, WORDED_STOP_KINDS } from './stop.js';
27
27
  export type { SettledToolCallEvent } from './tool-calls.js';
28
28
  export { argumentsSoFar, settlesToolCall, toolCallRanWith, toolCallsOf } from './tool-calls.js';
29
- export { promotedToolIdsFromEvents, toolSnapshotFromEvents } from './tool-invoke.js';
29
+ export { promotedToolIdsFromEvents, replyToolIdsFromEvents, toolSnapshotFromEvents, } from './tool-invoke.js';
30
30
  export type { PromotedToolMedia } from './tool-media.js';
31
31
  export { collectPromotedMediaFromToolOutput, promotedMediaFromUrlString, } from './tool-media.js';
32
32
  export type { AttachmentValidationResult, ComposerInterfaceFields, ComposerProfileInterface, FoldTurnEventsOptions, ImageProfileInterface, LiveProfileInterface, ModelBindingView, PendingAttachment, ProfileGuardrailsView, ProfileInputsInterface, ProfileInterface, ProfileObservabilityView, ProfileOutputsView, ProfileToolsView, SpeechProfileInterface, TextProfileInterface, TranscriptBlock, TranscriptBlockKind, TranscriptionProfileInterface, UserTurnDraft, } from './types.js';
@@ -17,6 +17,6 @@ export { profileInterfaceSchema } from './profile-interface.js';
17
17
  export { applyTurnEventsToSession, awaitingFromEvents, branchInterfaceTurnSession, emptyInterfaceTurnSession, gatedToolFromEvents, gatedToolsFromEvents, } from './session.js';
18
18
  export { stopText, WORDED_STOP_KINDS } from './stop.js';
19
19
  export { argumentsSoFar, settlesToolCall, toolCallRanWith, toolCallsOf } from './tool-calls.js';
20
- export { promotedToolIdsFromEvents, toolSnapshotFromEvents } from './tool-invoke.js';
20
+ export { promotedToolIdsFromEvents, replyToolIdsFromEvents, toolSnapshotFromEvents, } from './tool-invoke.js';
21
21
  export { collectPromotedMediaFromToolOutput, promotedMediaFromUrlString, } from './tool-media.js';
22
22
  export { streamThoughtsEnabled } from './types.js';
@@ -14,13 +14,13 @@ declare function applyToolDraft(call: ToolCall | undefined, draft: TurnEventOf<'
14
14
  declare function toolCallsOf(events: readonly TurnEvent[]): ToolCall[];
15
15
  /** The arguments shown for approval, or the user's edit, or the model's original call. */
16
16
  declare function toolCallRanWith(call: ToolCall): Record<string, unknown>;
17
- /** A tool event that settles its call: the call completed or failed. */
17
+ /** A tool event that settles its call for the turn: the call completed, failed or went on in the background. */
18
18
  type SettledToolCallEvent = TurnEventOf<'tool'> & {
19
19
  tool: Extract<ToolCallEvent, {
20
- phase: 'complete' | 'error';
20
+ phase: 'complete' | 'error' | 'background';
21
21
  }>;
22
22
  };
23
- /** True when the event is the complete or error event of the tool call with this id. */
23
+ /** True when the event settles the tool call with this id for its turn: it ended, or the model has its reply and the call goes on. */
24
24
  declare function settlesToolCall(event: TurnEvent, callId: string): event is SettledToolCallEvent;
25
25
  /**
26
26
  * A call's arguments as far as the model has written them: the whole arguments once the call has
@@ -39,12 +39,6 @@ function applyToolEvent(call, tool) {
39
39
  };
40
40
  }
41
41
  case 'complete':
42
- return {
43
- ...settled(call),
44
- state: tool,
45
- endedAt: tool.at,
46
- ...(tool.activityPast ? { activityPast: tool.activityPast } : {}),
47
- };
48
42
  case 'error':
49
43
  return {
50
44
  ...settled(call),
@@ -54,6 +48,7 @@ function applyToolEvent(call, tool) {
54
48
  };
55
49
  case 'cancel':
56
50
  case 'gate':
51
+ case 'background':
57
52
  return { ...settled(call), state: tool, endedAt: tool.at };
58
53
  case 'draft':
59
54
  return { ...call, outputDraft: (call.outputDraft ?? '') + tool.text };
@@ -150,11 +145,13 @@ function toolCallRanWith(call) {
150
145
  call.edited?.to ??
151
146
  call.arguments);
152
147
  }
153
- /** True when the event is the complete or error event of the tool call with this id. */
148
+ /** True when the event settles the tool call with this id for its turn: it ended, or the model has its reply and the call goes on. */
154
149
  function settlesToolCall(event, callId) {
155
150
  if (event.type !== 'tool' || event.tool.callId !== callId)
156
151
  return false;
157
- return event.tool.phase === 'complete' || event.tool.phase === 'error';
152
+ return (event.tool.phase === 'complete' ||
153
+ event.tool.phase === 'error' ||
154
+ event.tool.phase === 'background');
158
155
  }
159
156
  /**
160
157
  * A call's arguments as far as the model has written them: the whole arguments once the call has
@@ -3,4 +3,6 @@ import type { ToolId, TurnEvent, TurnToolSnapshot } from '../kernel/types.js';
3
3
  declare function promotedToolIdsFromEvents(events: readonly TurnEvent[]): ToolId[];
4
4
  /** The tool snapshot on the last `done` event that carries one, which only a turn stopped on a tool or gate does. */
5
5
  declare function toolSnapshotFromEvents(events: readonly TurnEvent[]): TurnToolSnapshot | undefined;
6
- export { promotedToolIdsFromEvents, toolSnapshotFromEvents };
6
+ /** The tools a paused reply holds: those on the list it paused with, and those a call has loaded since. */
7
+ declare function replyToolIdsFromEvents(events: readonly TurnEvent[]): ToolId[];
8
+ export { promotedToolIdsFromEvents, replyToolIdsFromEvents, toolSnapshotFromEvents };
@@ -19,4 +19,9 @@ function toolSnapshotFromEvents(events) {
19
19
  const done = findLast(events, (event) => event.type === 'done' && event.tools !== undefined);
20
20
  return done?.type === 'done' ? done.tools : undefined;
21
21
  }
22
- export { promotedToolIdsFromEvents, toolSnapshotFromEvents };
22
+ /** The tools a paused reply holds: those on the list it paused with, and those a call has loaded since. */
23
+ function replyToolIdsFromEvents(events) {
24
+ const visible = toolSnapshotFromEvents(events)?.visible ?? [];
25
+ return [...new Set([...visible, ...promotedToolIdsFromEvents(events)])];
26
+ }
27
+ export { promotedToolIdsFromEvents, replyToolIdsFromEvents, toolSnapshotFromEvents };
@@ -148,7 +148,7 @@ export interface TextBlock extends TranscriptBlockBase {
148
148
  }
149
149
  /** Where a call stands: the latest phase that changes its status. */
150
150
  export type ToolCallState = Extract<ToolPhaseEvent, {
151
- phase: 'running' | 'gate' | 'complete' | 'error' | 'cancel';
151
+ phase: 'running' | 'gate' | 'background' | 'complete' | 'error' | 'cancel';
152
152
  }>;
153
153
  /** invariant: An issued operation joins its request and phases; historical calls use callId. */
154
154
  export interface ToolCall {
@@ -1,6 +1,10 @@
1
1
  /** labels-exempt-file: authoring request-field and export meta — not runtime user or model copy (P2) */
2
2
  /** The catalog of the fields a `runTurn` request takes, keyed `runTurn.<field>`. */
3
3
  export const REQUEST_FIELDS = {
4
+ 'runTurn.background': {
5
+ type: 'ToolBackgroundService',
6
+ doc: 'Host-issued service for tool calls that go on after their reply. It needs a coordinator with detach. Without it every tool runs inline.',
7
+ },
4
8
  'runTurn.pageExecution': {
5
9
  type: 'PageToolExecution',
6
10
  doc: 'Host-issued browser dispatch with a claimed operation and correlated result.',
@@ -133,6 +137,10 @@ export const REQUEST_FIELDS = {
133
137
  type: 'number',
134
138
  doc: 'Which continue attempt this is, from 1; checked against the maxContinues of the profile.',
135
139
  },
140
+ 'runTurn.promoted': {
141
+ type: 'ToolId[]',
142
+ doc: 'Tools this reply already had when an earlier run of it paused; the turn opens with them on its list.',
143
+ },
136
144
  'runTurn.speech': {
137
145
  type: 'TurnSpeech',
138
146
  doc: "This turn's voice, style, and speed; each one given replaces the profile's speech field of that name. Refused on a profile that is not speech.",
@@ -0,0 +1,7 @@
1
+ import { startTrace } from '../../observability/trace-span.js';
2
+ import type { DetachedToolTrace } from '../tools/background.js';
3
+ /** A detached call's record, written at its real end: a span in its turn's tree cannot outlive the turn. */
4
+ export declare function detachedTrace(args: {
5
+ traceparent: string;
6
+ write: (spans: ReturnType<ReturnType<typeof startTrace>['collect']>) => void | Promise<void>;
7
+ }): DetachedToolTrace;
@@ -0,0 +1,18 @@
1
+ import { startTrace } from '../../observability/trace-span.js';
2
+ /** A detached call's record, written at its real end: a span in its turn's tree cannot outlive the turn. */
3
+ export function detachedTrace(args) {
4
+ let tree;
5
+ return {
6
+ open: (name, attributes) => {
7
+ tree = startTrace(name, {
8
+ ...(attributes ? { attributes } : {}),
9
+ traceparent: args.traceparent,
10
+ });
11
+ return tree.root;
12
+ },
13
+ end: () => {
14
+ if (tree)
15
+ return args.write(tree.collect());
16
+ },
17
+ };
18
+ }
@@ -13,9 +13,11 @@ import { hostAgentModel, nestedTurnModel } from '../../provider-dispatch.js';
13
13
  import { profileInputs, requireModelBinding } from '../../registry/catalog.js';
14
14
  import { resolveTurnInRegistry } from '../../registry/resolve.js';
15
15
  import { bindSystem } from '../../system-parts.js';
16
- import { cloneTurnToolSnapshot, expandT1Policy } from '../../tools/resolve.js';
16
+ import { assertBackgroundCoordinator } from '../../tools/background.js';
17
+ import { cloneTurnToolSnapshot, expandT1Policy, promoteTurnTools } from '../../tools/resolve.js';
17
18
  import { keptReply, turnDoneOf } from '../../turn-events.js';
18
19
  import { findLast } from '../../util/find-last.js';
20
+ import { detachedTrace } from '../background.js';
19
21
  import { compactionMeter, compactionResult, compactorHistory, resolveCompactionTokens, shouldCompact, splitForCompaction, } from '../compaction.js';
20
22
  import { endThrownSpan, endTurnSpan, guardrailAttributes, guardrailCheckAttributes, OutputFold, turnSpanOptions, } from '../turn-trace.js';
21
23
  import { sumEventTokens, sumTurnTokens } from '../usage.js';
@@ -243,6 +245,7 @@ async function* emitTurn(args) {
243
245
  generation,
244
246
  trace: args.trace,
245
247
  ...(args.agents ? { agents: args.agents } : {}),
248
+ ...(args.background ? { background: args.background } : {}),
246
249
  });
247
250
  args.outState.state = state;
248
251
  const pre = yield* applyTurnStage({
@@ -304,6 +307,7 @@ async function* streamTurnEvents(ctx, profile, gen, provider, compactionSpec) {
304
307
  provider,
305
308
  trace: ctx.trace,
306
309
  agents: ctx.agents,
310
+ background: ctx.background,
307
311
  outState: ctx,
308
312
  })) {
309
313
  const attached = await maybeAttachAfter(event, ctx, gen, compactionSpec);
@@ -387,6 +391,22 @@ async function* runTurnInRegistry(registry, req, provider, sinkOverride) {
387
391
  guardrails: ctx.known?.guardrails,
388
392
  });
389
393
  ctx.observability = policy;
394
+ const { background: service } = req;
395
+ if (service) {
396
+ ctx.background = {
397
+ service,
398
+ project: (event) => withPublicLabels(projectForObs(event, ctx.observability), ctx.known?.labels),
399
+ openTrace: () => detachedTrace({
400
+ traceparent: tree.root.traceparent(),
401
+ write: (spans) => writeTrace(sink, buildRecord({
402
+ spans,
403
+ policy,
404
+ canaries: ctx.canaries,
405
+ ...(req.metadata ? { metadata: req.metadata } : {}),
406
+ }), policy),
407
+ }),
408
+ };
409
+ }
390
410
  try {
391
411
  yield* runTracedTurn(ctx, provider);
392
412
  }
@@ -434,6 +454,7 @@ async function* emitCancelledDoneAfterAbort(ctx) {
434
454
  }
435
455
  }
436
456
  async function* runTurnBody(ctx, provider) {
457
+ assertBackgroundCoordinator(ctx.req.background, ctx.req.execution);
437
458
  const checkStart = performance.now();
438
459
  const sanitized = sanitizeTurnRequestWithEvents(ctx.req, ctx.registry.profiles.get(ctx.req.profile));
439
460
  const checkMs = performance.now() - checkStart;
@@ -455,6 +476,7 @@ async function* runTurnBody(ctx, provider) {
455
476
  throw sanitized.refusal;
456
477
  const { profile, generation: gen } = resolveTurnInRegistry(ctx.registry, ctx.safe);
457
478
  await expandT1Policy(ctx.registry.tools, gen.tools, profile, ctx.safe);
479
+ promoteTurnTools(ctx.registry.tools, gen.tools, ctx.safe.promoted);
458
480
  if (ctx.compacting === 'self')
459
481
  gen.tools = noTools();
460
482
  gen.builtins = gen.tools.builtins;
@@ -4,6 +4,7 @@ import type { OwnTools } from '../../../guardrails/tool-leak.js';
4
4
  import type { GuardrailHit, TurnTaint } from '../../../guardrails/types.js';
5
5
  import type { SpanHandle } from '../../../observability/trace-span.js';
6
6
  import type { AgentCaller } from '../../tools/agent.js';
7
+ import type { ToolBackgroundSupport } from '../../tools/background.js';
7
8
  import type { ToolRegistry } from '../../tools/registry.js';
8
9
  import type { InteractionPart, ModelBinding, Profile, ResolvedGeneration, TurnEvent, TurnHistoryMessage, TurnRequest, TurnStop, TurnToolResult } from '../../types.js';
9
10
  import type { ItemFailure } from './schema-validation.js';
@@ -21,6 +22,8 @@ interface StepExecutionState {
21
22
  tools: ToolRegistry;
22
23
  /** Runs the turn's agent tools; absent where none can run (a compactor's own turn). */
23
24
  agents?: AgentCaller;
25
+ /** Absent where every tool runs inline: a nested turn, or no background service. */
26
+ background?: ToolBackgroundSupport;
24
27
  trace: TurnTraceState;
25
28
  currentHistory: TurnHistoryMessage[];
26
29
  /** Where this turn begins in `currentHistory`: what came before is the conversation the host passed. */
@@ -109,6 +112,7 @@ declare function openTurnState(args: {
109
112
  trace: TurnTraceState;
110
113
  allEmittedEvents?: TurnEvent[];
111
114
  agents?: AgentCaller;
115
+ background?: ToolBackgroundSupport;
112
116
  }): StepExecutionState;
113
117
  /** The history the next model call reads: this turn alone once a retry has cut it. */
114
118
  declare function modelHistory(state: StepExecutionState): TurnHistoryMessage[];
@@ -43,6 +43,7 @@ function openTurnState(args) {
43
43
  canaryScanned: new WeakSet(),
44
44
  ...(ownTools ? { ownTools } : {}),
45
45
  ...(args.agents ? { agents: args.agents } : {}),
46
+ ...(args.background ? { background: args.background } : {}),
46
47
  };
47
48
  if (profile.type === 'text') {
48
49
  appendUserInput(state, generation.input);
@@ -8,6 +8,14 @@ export interface StepOrder {
8
8
  settle(callId: string): void;
9
9
  wait: StepWait;
10
10
  }
11
+ /**
12
+ * A promise and the function that settles it. `Promise.withResolvers` would do, but the React
13
+ * package compiles the kernel against ES2023, which lacks it.
14
+ */
15
+ export declare function settleable<T>(): {
16
+ promise: Promise<T>;
17
+ resolve: (value: T) => void;
18
+ };
11
19
  /**
12
20
  * The order of a step's calls. Side by side, every call starts at once. One at a time,
13
21
  * each starts when every call before it has settled. A call whose `pre_tool` answers `waitFor`
@@ -3,7 +3,7 @@ import { throwIfAborted } from '../../../guardrails/error.js';
3
3
  * A promise and the function that settles it. `Promise.withResolvers` would do, but the React
4
4
  * package compiles the kernel against ES2023, which lacks it.
5
5
  */
6
- function settleable() {
6
+ export function settleable() {
7
7
  let resolve = () => undefined;
8
8
  const promise = new Promise((settle) => {
9
9
  resolve = settle;
@@ -497,6 +497,7 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
497
497
  const execute = (call) => forwardToolEvents(executeRegisteredTool({
498
498
  tools: state.tools,
499
499
  execution: generation.execution,
500
+ ...(state.background ? { background: state.background } : {}),
500
501
  invocation: {
501
502
  model: generation.model,
502
503
  input: generation.input,
@@ -1,12 +1,14 @@
1
1
  import type { TraceSink } from '../../../observability/trace-sink.js';
2
2
  import type { ProviderHostOptions } from '../../protocols/runtime.js';
3
3
  import type { KernelRegistry } from '../../registry/kernel-registry.js';
4
+ import { type ToolBackgroundService } from '../../tools/background.js';
4
5
  import { type PageToolExecution, type ToolExecutionCoordinator } from '../../tools/operation.js';
5
6
  import type { KeyVault, LiveSession, SessionRequest } from '../../types.js';
6
7
  export type { LiveSession, SessionRequest };
7
8
  /** Options for opening a live session: the key vault, a provider's own settings, a WebSocket opener, how long a gated call waits for its decision, and the sign-in gate policy. */
8
9
  export interface RunSessionOptions extends ProviderHostOptions {
9
10
  execution?: ToolExecutionCoordinator;
11
+ background?: ToolBackgroundService;
10
12
  pageExecution?: PageToolExecution;
11
13
  /** The host's keys by slot; the session uses the slots its profile names. */
12
14
  vault?: KeyVault;
@@ -21,6 +21,7 @@ import { DEFAULT_RESUMED_AFTER_MS } from '../../schema.js';
21
21
  import { injectedStageEvent, runStage, stageEventFields, } from '../../stages.js';
22
22
  import { profileAllowsInject, stageAbortStop } from '../../stop.js';
23
23
  import { bindSystem } from '../../system-parts.js';
24
+ import { assertBackgroundCoordinator, } from '../../tools/background.js';
24
25
  import { failedActivity, failureEvent } from '../../tools/events.js';
25
26
  import { executeRegisteredTool, lapsedGateFailure, shownToolArguments, } from '../../tools/execute.js';
26
27
  import { answerGatedCall, gateExpired, resolveGateTtlMs, resumeForAnswer, } from '../../tools/gate-answer.js';
@@ -47,7 +48,10 @@ function isReleased(held) {
47
48
  return typeof held.state === 'object' && held.state.released === true;
48
49
  }
49
50
  function isSettledPhase(tool) {
50
- return tool.phase === 'complete' || tool.phase === 'error' || tool.phase === 'gate';
51
+ return (tool.phase === 'complete' ||
52
+ tool.phase === 'error' ||
53
+ tool.phase === 'gate' ||
54
+ tool.phase === 'background');
51
55
  }
52
56
  /**
53
57
  * The provider's close after it warned of it (`goAway`): the session's last
@@ -338,6 +342,14 @@ function buildLiveSession(args) {
338
342
  let wakeHost;
339
343
  const includeMatch = resolveObservabilityPolicy(profile.observability).include
340
344
  .guardrailMatchPreview;
345
+ const background = args.background && {
346
+ service: args.background,
347
+ project: (event) => projectGuardrailTurnEvent(withPublicLabels(event, profile.labels), includeMatch),
348
+ openTrace: (callId) => {
349
+ const { open, finish } = trace.toolRecord(callId);
350
+ return { open, end: finish };
351
+ },
352
+ };
341
353
  let cycle = 'idle';
342
354
  let cycleStep = 0;
343
355
  /** What this cycle's tool results read from outside the host; a cycle starts clean, as a turn does. */
@@ -666,6 +678,7 @@ function buildLiveSession(args) {
666
678
  tools: args.tools,
667
679
  agents: args.agents,
668
680
  execution: args.execution,
681
+ background,
669
682
  profile,
670
683
  name: held.name,
671
684
  input,
@@ -1072,6 +1085,8 @@ function buildLiveSession(args) {
1072
1085
  }
1073
1086
  forward();
1074
1087
  settleHeld(callId, held, readBack);
1088
+ if (settled.phase === 'background')
1089
+ return {};
1075
1090
  return settled.phase === 'complete'
1076
1091
  ? { outputRaw: settled.output, ...(settled.awaiting ? { awaiting: true } : {}) }
1077
1092
  : { failure: settled.failure };
@@ -1124,7 +1139,8 @@ async function openTracedSession(registry, req, options, trace) {
1124
1139
  if (refusal)
1125
1140
  throw refusal;
1126
1141
  throwIfAborted(safe.signal);
1127
- const { profile, generation: gen0 } = resolveTurnInRegistry(registry, safe);
1142
+ assertBackgroundCoordinator(options.background, options.execution);
1143
+ const { profile, generation: gen0 } = resolveTurnInRegistry(registry, options.background ? { ...safe, background: options.background } : safe);
1128
1144
  assertLiveProfile(profile);
1129
1145
  const openingContext = req.context ? readSessionContext(profile, req.context) : undefined;
1130
1146
  if (req.snapshot) {
@@ -1166,6 +1182,7 @@ async function openTracedSession(registry, req, options, trace) {
1166
1182
  trace.setup(connection.setup);
1167
1183
  return buildLiveSession({
1168
1184
  execution: options.execution,
1185
+ ...(options.background ? { background: options.background } : {}),
1169
1186
  pageExecution: options.pageExecution,
1170
1187
  tools: registry.tools,
1171
1188
  profile,
@@ -63,13 +63,14 @@ export { systemLinesProblem } from './system-lines.js';
63
63
  export { systemPromptProblem } from './system-parts.js';
64
64
  export { activityLabelProblem } from './tools/activity-label.js';
65
65
  export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
66
+ export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, } from './tools/background.js';
66
67
  export { type AnsweredGate, answerGatedCall, GATE_DECISIONS, type GateAnswerRequest, type GateDecision, gateExpired, type HeldGatedCall, resolveGateTtlMs, sessionPermissionsAfterApproval, type ToolGateAuth, } from './tools/gate-answer.js';
67
68
  export type { MemoryToolExecutionOptions } from './tools/memory-execution.js';
68
69
  export { createMemoryToolExecution } from './tools/memory-execution.js';
69
70
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './tools/mod.js';
70
71
  export { askUserTool, authorizeToolReplay, coerceToolResultParts, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, withCredentialQuery, } from './tools/mod.js';
71
- export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './tools/operation.js';
72
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
72
+ export type { BackgroundToolEvent, BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, } from './tools/operation.js';
73
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './tools/operation.js';
73
74
  export { jsonSchemaFromZod } from './tools/schema.js';
74
75
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
75
76
  export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolContext, ToolLabels, } from './tools/types.js';
@@ -42,7 +42,7 @@ export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
42
42
  export { answerGatedCall, GATE_DECISIONS, gateExpired, resolveGateTtlMs, sessionPermissionsAfterApproval, } from './tools/gate-answer.js';
43
43
  export { createMemoryToolExecution } from './tools/memory-execution.js';
44
44
  export { askUserTool, authorizeToolReplay, coerceToolResultParts, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, withCredentialQuery, } from './tools/mod.js';
45
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
45
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './tools/operation.js';
46
46
  export { jsonSchemaFromZod } from './tools/schema.js';
47
47
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
48
48
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
@@ -891,6 +891,18 @@ export const EXTRA_FIELDS = {
891
891
  ...field('boolean', 'Gives the model an after field on this tool: the tools called in the same step that must settle before this call starts. The kernel removes the field before the tool, the stages or a gate read the input. A name with no other call in the step fails the call wait_unknown.'),
892
892
  unset: 'The model sets no order',
893
893
  },
894
+ 'registerTool.background': {
895
+ ...field("'always' | { afterMs: number } | 'ask' | 'never'", "When the model gets its reply while the body goes on. 'always': at the hand-off. { afterMs }: once the body has run past this time. 'ask': at the hand-off if the model sets the background argument. A turn with no background service runs the tool inline."),
896
+ options: ['never', 'ask', 'always', 'afterMs'],
897
+ optionDescriptions: {
898
+ never: 'The model gets its reply when the body ends.',
899
+ ask: 'The model chooses, call by call, whether to go on without the result.',
900
+ always: 'The model gets its reply at once, and the body goes on after the turn.',
901
+ afterMs: 'The model gets its reply once the body has run past this time.',
902
+ },
903
+ unset: "'never': the model gets its reply when the body ends",
904
+ },
905
+ 'registerTool.background.afterMs': field('number', 'Milliseconds the body runs before the model gets its reply. A body that ends sooner answers in the turn.'),
894
906
  'registerTool.category': field('string', 'A label for grouping tools; nothing reads it yet.'),
895
907
  'registerTool.labels': field('ToolLabels', "Transcript text for a call. {path} reads a value from the call. {results.0.name} reads a list item. {path|text} shows the text when the value is unusable. {count hit|hits} shows a number with the word for one or for any other number: '1 hit', '3 hits'. With no fallback, the label is dropped. A label is one line, or a list read top to bottom: the first line that fits is shown. A line fits when each {path} has a value and its condition holds, as in 'when status is archived: archiving {title}'. Neighbouring lines that open with '+ ' show together, joined in words. The last line of a list must always fit."),
896
908
  'registerTool.labels.activity': {