@theoremjs/agents 0.3.4-next.586.ga59d695 → 0.3.4-next.594.g145ceaf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -463,7 +463,7 @@ Named exports from the root barrel (same symbols hosts get from `@theoremjs/agen
463
463
  | Scope | `KernelScope`, `createKernelScope`, `defaultKernelScope`, `KernelRegistry`, `createKernelRegistry` |
464
464
  | Profiles | `ProfileDefinition`, `ProfileDefinitionBase`, `TextProfileDefinition`, `ImageProfileDefinition`, `SpeechProfileDefinition`, `LiveProfileDefinition`, `HostProfileDefinition`, `DecisionProfileDefinition`, `EmbeddingProfileDefinition`, `ProfileRegistry`, `createProfileRegistry`, `clearProfiles`, `defineProfile`, `getProfile`, `hasProfile`, `listProfiles`, `registerProfile`, `registerProfiles`, `projectProfile`, `resolveTurn`, `pickModel` |
465
465
  | 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` |
466
- | Tool execution | `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
466
+ | Tool execution | `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `DEFAULT_MAX_OUTCOME_BYTES`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
467
467
  | Structured | `SchemaRegistry`, `createSchemaRegistry`, `getStructured`, `registerStructured` |
468
468
  | 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` |
469
469
  | 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
@@ -70,7 +70,7 @@ export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.j
70
70
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './src/kernel/tools/mod.js';
71
71
  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';
72
72
  export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
73
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
73
+ export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
74
74
  export type { SettledToolCall, ToolCallResult, ToolStepCallResult, } from './src/kernel/tools/run.js';
75
75
  export type { ModelToolResult, PageAnswer, ToolContext } from './src/kernel/tools/types.js';
76
76
  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
@@ -43,7 +43,7 @@ export { authorizeToolReplay } from './src/kernel/tools/execute.js';
43
43
  export { GATE_DECISIONS } from './src/kernel/tools/gate-answer.js';
44
44
  export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
45
45
  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';
46
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
46
+ export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
47
47
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
48
48
  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';
49
49
  export * from './src/providers/mod.js';
@@ -70,6 +70,12 @@ function messageOf(err) {
70
70
  if (err instanceof Error && err.message) {
71
71
  return err.message;
72
72
  }
73
+ // why: A plain-object cause such as `{ code }` would read `[object Object]`; its own scalar fields say what it holds.
74
+ if (err && typeof err === 'object' && !(err instanceof Error)) {
75
+ const fields = Object.entries(err).filter(([, value]) => value === null || ['string', 'number', 'boolean'].includes(typeof value));
76
+ if (fields.length)
77
+ return fields.map(([key, value]) => `${key}: ${value}`).join(', ');
78
+ }
73
79
  return String(err);
74
80
  }
75
81
  /** Raw diagnostic for hosts, traces, and logs; never shown to end users. Each cause that says something new follows on its own line. */
@@ -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", "compaction.request", "compaction.tool_call", "compaction.tool_result", "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.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.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", "compaction.request", "compaction.tool_call", "compaction.tool_result", "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.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
  /**
@@ -143,6 +143,8 @@ export const LABEL_KEYS = [
143
143
  'session.gate_expired',
144
144
  'session.provider_state_unowned',
145
145
  'session.conversation_unknown',
146
+ 'session.full',
147
+ 'session.busy',
146
148
  'session.turn_ended',
147
149
  'session.gate_pending',
148
150
  'session.part_skipped',
@@ -465,6 +467,8 @@ const DEFAULTS = {
465
467
  'sign_in.out_of_scope': "{service} needs access that this tool isn't set up for, so it can't do that.",
466
468
  'session.provider_state_unowned': 'Saved model state cannot be used in this conversation. Continue from your saved history.',
467
469
  'session.conversation_unknown': 'Sorry, this conversation is no longer available. Start a new one.',
470
+ 'session.full': 'Sorry, this conversation is full. Please start a new one.',
471
+ 'session.busy': 'Sorry, this conversation is busy. Please try again in a moment.',
468
472
  'session.gate_expired': 'Sorry, that step is no longer waiting for approval.',
469
473
  'session.turn_ended': 'Sorry, that reply has already finished.',
470
474
  'session.gate_pending': 'Please approve or decline the waiting step before sending a new message.',
@@ -679,6 +683,8 @@ export const LABEL_NOTES = {
679
683
  'sign_in.out_of_scope': 'Told to the model when a service asks for more access than the tool declares, so no sign-in is offered. Takes {service}.',
680
684
  'session.provider_state_unowned': 'Unowned or unavailable provider checkpoint.',
681
685
  'session.conversation_unknown': 'Shown to the user whose conversation the host no longer has, or whose saved conversation does not open in this session.',
686
+ 'session.full': "Shown to the user when the conversation's open work does not fit in what its session store holds.",
687
+ 'session.busy': 'Shown to the user when the conversation could not be saved because other work on it was in the way.',
682
688
  'session.gate_expired': 'Shown to the user who answers a step that is no longer waiting for approval.',
683
689
  'session.turn_ended': 'Shown to the user who tries to steer a reply that has already finished.',
684
690
  'session.gate_pending': 'Shown to the user who sends a message while a step is still waiting for their approval.',
@@ -66,7 +66,7 @@ export { createMemoryToolExecution } from './tools/memory-execution.js';
66
66
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './tools/mod.js';
67
67
  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';
68
68
  export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './tools/operation.js';
69
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
69
+ export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
70
70
  export { jsonSchemaFromZod } from './tools/schema.js';
71
71
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
72
72
  export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolContext, ToolLabels, } from './tools/types.js';
@@ -39,7 +39,7 @@ export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
39
39
  export { answerGatedCall, GATE_DECISIONS, gateExpired, resolveGateTtlMs, sessionPermissionsAfterApproval, } from './tools/gate-answer.js';
40
40
  export { createMemoryToolExecution } from './tools/memory-execution.js';
41
41
  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';
42
- export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
42
+ export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
43
43
  export { jsonSchemaFromZod } from './tools/schema.js';
44
44
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
45
45
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
@@ -26,6 +26,11 @@ export type StageCallBag = {
26
26
  input?: unknown;
27
27
  /** `pre_tool` in a turn's step: every call the model made in the step, in the order it made them. */
28
28
  stepCalls?: readonly StepCall[];
29
+ /**
30
+ * `pre_tool`: the user approved this call where it stopped, at its permission or a
31
+ * confirmation. A sign-in is not an approval.
32
+ */
33
+ approved?: true;
29
34
  callNotStarted?: boolean;
30
35
  outputRaw?: unknown;
31
36
  outputModel?: ModelToolResult;
@@ -1,5 +1,7 @@
1
1
  import { errorKind, throwIfAborted } from '../../guardrails/error.js';
2
2
  import { jsonObjectSchema } from '../json.js';
3
+ import { failureEvent } from './events.js';
4
+ import { formatToolFailureForModel } from './model-text.js';
3
5
  import { heldOperation, operationBroken, operationWireValue, toolInvocationHash, toolOperationOutcomeSchema, unresolvedOperation, } from './operation.js';
4
6
  class ReplayedOperation {
5
7
  outcome;
@@ -58,7 +60,7 @@ class CoordinatedExecution {
58
60
  if (settlement.gated) {
59
61
  if (this.claim)
60
62
  throw gateAfterClaim(settlement.gated);
61
- return undefined;
63
+ return { settlement };
62
64
  }
63
65
  if (!this.terminal)
64
66
  throw operationBroken('The tool run ended with no terminal event'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
@@ -78,14 +80,35 @@ class CoordinatedExecution {
78
80
  pendingInject,
79
81
  },
80
82
  };
83
+ const whole = toolOperationOutcomeSchema.parse(operationWireValue(outcome));
84
+ const saved = this.withinLimit(whole);
81
85
  this.writeFailed = true;
82
- const saved = toolOperationOutcomeSchema.parse(operationWireValue(outcome));
83
86
  if (this.claim)
84
87
  await this.coordinator.settle(this.claim, saved);
85
88
  else
86
89
  await this.coordinator.settleNotStarted(this.operation, saved);
87
90
  this.committed = true;
88
- return saved.event;
91
+ return { terminal: saved.event, settlement: saved === whole ? settlement : saved.replay };
92
+ }
93
+ /**
94
+ * why: A result the coordinator cannot keep would leave a call that ran unresolved. It settles as
95
+ * a failure that names its size instead, and the model reads that failure, not the result.
96
+ */
97
+ withinLimit(outcome) {
98
+ const bytes = new TextEncoder().encode(JSON.stringify(outcome)).byteLength;
99
+ const limit = this.coordinator.maxOutcomeBytes;
100
+ if (bytes <= limit)
101
+ return outcome;
102
+ const { name, callId, operationId } = outcome.event.tool;
103
+ const failure = {
104
+ code: 'result_too_large',
105
+ kind: 'bad_response',
106
+ message: `The result of ${name} is ${bytes} bytes, more than the ${limit} bytes kept for one tool result`, // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
107
+ details: { bytes, maxOutcomeBytes: limit },
108
+ };
109
+ const modelResult = formatToolFailureForModel(failure);
110
+ const event = failureEvent({ name, callId, ...(operationId ? { operationId } : {}) }, failure);
111
+ return toolOperationOutcomeSchema.parse(operationWireValue({ event, effects: outcome.effects, replay: { modelResult, failure } }));
89
112
  }
90
113
  replay(error) {
91
114
  const saved = toolOperationOutcomeSchema.parse(operationWireValue(error.outcome));
@@ -134,10 +157,10 @@ export async function* coordinateTool(coordinator, identity, invocation, signal,
134
157
  for (;;) {
135
158
  const next = await iterator.next();
136
159
  if (next.done) {
137
- const terminal = await execution.finish(next.value);
160
+ const { terminal, settlement } = await execution.finish(next.value);
138
161
  if (terminal)
139
162
  yield terminal;
140
- return next.value;
163
+ return settlement;
141
164
  }
142
165
  if (execution.observe(next.value))
143
166
  yield next.value;
@@ -2,6 +2,8 @@ import { type ToolExecutionCoordinator } from './operation.js';
2
2
  export interface MemoryToolExecutionOptions {
3
3
  /** The most operations it holds. A full coordinator refuses dispatch and keeps what it has. */
4
4
  maxOperations?: number;
5
+ /** The most bytes it keeps for one tool result. Default {@linkcode DEFAULT_MAX_OUTCOME_BYTES}. */
6
+ maxOutcomeBytes?: number;
5
7
  }
6
8
  /**
7
9
  * A coordinator that keeps claims and outcomes in process memory.
@@ -1,5 +1,5 @@
1
1
  import { TheoremError } from '../../guardrails/error.js';
2
- import { operationBroken, } from './operation.js';
2
+ import { DEFAULT_MAX_OUTCOME_BYTES, operationBroken, } from './operation.js';
3
3
  /** How many operations a memory coordinator tracks before it refuses new ones. */
4
4
  const DEFAULT_MEMORY_EXECUTION_LIMIT = 256;
5
5
  /**
@@ -27,6 +27,7 @@ export function createMemoryToolExecution(options = {}) {
27
27
  const full = () => new TheoremError('config', `The memory tool coordinator holds its maxOperations of ${limit}`);
28
28
  const notHeld = () => operationBroken('The memory tool coordinator holds no running claim for this token'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
29
29
  return {
30
+ maxOutcomeBytes: options.maxOutcomeBytes ?? DEFAULT_MAX_OUTCOME_BYTES,
30
31
  lookup: (operation) => Promise.resolve(known(operation)),
31
32
  begin: (operation) => {
32
33
  const earlier = known(operation);
@@ -58,7 +58,17 @@ export type BeginToolOperationResult = {
58
58
  } | {
59
59
  kind: 'uncertain';
60
60
  };
61
+ /**
62
+ * The default most bytes a coordinator keeps for one tool result, as UTF-8 JSON. A result that
63
+ * size is about 250,000 tokens, already more than one tool result should give a model.
64
+ */
65
+ export declare const DEFAULT_MAX_OUTCOME_BYTES: number;
61
66
  export interface ToolExecutionCoordinator {
67
+ /**
68
+ * The most bytes, as UTF-8 JSON, it keeps for one outcome. The kernel settles a larger result as
69
+ * the call's `result_too_large` failure, so a call that ran is never left unresolved by its size.
70
+ */
71
+ readonly maxOutcomeBytes: number;
62
72
  lookup(operation: ToolOperationIdentity): Promise<Exclude<BeginToolOperationResult, {
63
73
  kind: 'acquired';
64
74
  }> | undefined>;
@@ -7,6 +7,11 @@ export const savedToolInvocationSchema = z.strictObject({
7
7
  accepted: jsonObjectSchema,
8
8
  preparedInput: jsonValueSchema,
9
9
  });
10
+ /**
11
+ * The default most bytes a coordinator keeps for one tool result, as UTF-8 JSON. A result that
12
+ * size is about 250,000 tokens, already more than one tool result should give a model.
13
+ */
14
+ export const DEFAULT_MAX_OUTCOME_BYTES = 1024 * 1024;
10
15
  /** A coordinator, a page dispatch or the kernel broke the tool-operation contract. */
11
16
  export function operationBroken(reason) {
12
17
  return new TheoremError('internal', reason);
@@ -20,11 +20,13 @@ function defaultToolStageSupport(ctx) {
20
20
  export async function* runPreToolPipeline(args) {
21
21
  const { tool, ctx, base, stages } = args;
22
22
  let toolPreTool;
23
- // why: An approval skips the tool's own check it already passed — unless the user edited the arguments.
24
- const approvedAsIs = isGateResumeGranted(ctx.resume) &&
25
- ctx.resume?.edited === undefined &&
23
+ // why: Permission and sign-in gates come before `pre_tool`, so granting one answers nothing it asked.
24
+ const confirmed = isGateResumeGranted(ctx.resume) &&
26
25
  ctx.resume?.gateKind !== 'permission' &&
27
26
  ctx.resume?.gateKind !== 'auth';
27
+ // why: An approval skips the tool's own check it already passed — unless the user edited the arguments.
28
+ const approvedAsIs = confirmed && ctx.resume?.edited === undefined;
29
+ const approved = isGateResumeGranted(ctx.resume) && ctx.resume?.gateKind !== 'auth';
28
30
  if (tool.preTool && !approvedAsIs) {
29
31
  toolPreTool = (await tool.preTool(args.input, ctx)) ?? undefined;
30
32
  }
@@ -38,6 +40,8 @@ export async function* runPreToolPipeline(args) {
38
40
  input: args.input,
39
41
  toolPreTool,
40
42
  details: gateDetails(tool, args.input),
43
+ confirmed,
44
+ approved,
41
45
  });
42
46
  if (!pre.ok) {
43
47
  if (pre.kind === 'gated') {
@@ -91,7 +95,7 @@ export async function* runPreToolPipeline(args) {
91
95
  return { ok: true, input: reparsed ? reparsed.data : pre.input };
92
96
  }
93
97
  async function* runPreToolStages(args) {
94
- const { stages, toolName, callId, input, toolPreTool, details } = args;
98
+ const { stages, toolName, callId, input, toolPreTool, details, confirmed, approved } = args;
95
99
  const applied = yield* runStage({
96
100
  stage: 'pre_tool',
97
101
  step: stages.step,
@@ -105,6 +109,7 @@ async function* runPreToolStages(args) {
105
109
  callId,
106
110
  tool: toolName,
107
111
  input,
112
+ ...(approved ? { approved: true } : {}),
108
113
  ...(stages.stepCalls ? { stepCalls: stages.stepCalls } : {}),
109
114
  });
110
115
  if (applied.abort) {
@@ -118,7 +123,7 @@ async function* runPreToolStages(args) {
118
123
  denied: true,
119
124
  };
120
125
  }
121
- if (applied.confirm) {
126
+ if (applied.confirm && !confirmed) {
122
127
  const gate = {
123
128
  kind: 'confirmation',
124
129
  tool: toolName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.586.ga59d695",
3
+ "version": "0.3.4-next.594.g145ceaf",
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",