@theoremjs/agents 0.3.4-next.574.g44edd0f → 0.3.4-next.590.g0246066
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 +1 -1
- package/esm/mod.d.ts +1 -1
- package/esm/mod.js +1 -1
- package/esm/src/guardrails/error.js +6 -0
- package/esm/src/guardrails/labels.d.ts +1 -1
- package/esm/src/guardrails/labels.js +6 -0
- package/esm/src/kernel/mod.d.ts +1 -1
- package/esm/src/kernel/mod.js +1 -1
- package/esm/src/kernel/tools/coordinate.js +28 -5
- package/esm/src/kernel/tools/memory-execution.d.ts +2 -0
- package/esm/src/kernel/tools/memory-execution.js +2 -1
- package/esm/src/kernel/tools/operation.d.ts +10 -0
- package/esm/src/kernel/tools/operation.js +5 -0
- package/esm/src/providers/open-ai/protocol.js +3 -3
- package/esm/src/providers/openrouter/openai/compat.d.ts +12 -3
- package/esm/src/providers/openrouter/openai/compat.js +27 -8
- package/package.json +1 -1
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.',
|
package/esm/src/kernel/mod.d.ts
CHANGED
|
@@ -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';
|
package/esm/src/kernel/mod.js
CHANGED
|
@@ -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';
|
|
@@ -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
|
|
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
|
|
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);
|
|
@@ -5,7 +5,7 @@ import { defineProtocol, } from '../../kernel/protocols/mod.js';
|
|
|
5
5
|
import { turnStopFromOpenAiFinishReason } from '../../kernel/stop.js';
|
|
6
6
|
import { base64ToBytes, bytesToBase64 } from '../../kernel/util/base64.js';
|
|
7
7
|
import { mimeEssence } from '../../kernel/util/mime.js';
|
|
8
|
-
import { buildChatMessages, resolveResponseFormat, wireTools, } from '../openrouter/openai/compat.js';
|
|
8
|
+
import { buildChatMessages, httpError, resolveResponseFormat, statedError, wireTools, } from '../openrouter/openai/compat.js';
|
|
9
9
|
import { openAiResponse, openAiUsageTokens } from '../openrouter/openai/usage.js';
|
|
10
10
|
import { pcmFormatFromMime, wrapPcmAsWav } from '../shared/pcm.js';
|
|
11
11
|
import { asProtocolEvent } from '../shared/protocol-events.js';
|
|
@@ -42,8 +42,7 @@ function errorRow(row) {
|
|
|
42
42
|
if (!error)
|
|
43
43
|
return;
|
|
44
44
|
const status = typeof error.code === 'number' ? error.code : 502;
|
|
45
|
-
|
|
46
|
-
throw new TheoremError(kindOfHttpStatus(status), message);
|
|
45
|
+
throw new TheoremError(kindOfHttpStatus(status), statedError(row) ?? JSON.stringify(error));
|
|
47
46
|
}
|
|
48
47
|
function citations(part, reply) {
|
|
49
48
|
const sources = (Array.isArray(part.annotations) ? part.annotations : []).flatMap((item) => {
|
|
@@ -176,6 +175,7 @@ export const openAi = defineProtocol({
|
|
|
176
175
|
description: 'The Chat Completions shape that OpenAI and most compatible servers speak.', // labels-exempt: builder field description, read by the studio and docs
|
|
177
176
|
endpoints: { text: '/chat/completions', speech: '/audio/speech' },
|
|
178
177
|
options: z.strictObject({}),
|
|
178
|
+
error: (failure) => httpError(failure, 'Chat Completions'),
|
|
179
179
|
create(context) {
|
|
180
180
|
return {
|
|
181
181
|
async *complete(request) {
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import { type ProducedError } from '../../../guardrails/error.js';
|
|
1
|
+
import { type ProducedError, TheoremError } from '../../../guardrails/error.js';
|
|
2
2
|
import type { InteractionPart, ModelRequest, ResolvedStructured, WireFunctionTool } from '../../../kernel/types.js';
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Why a Chat Completions body says the call failed: its `error.message`, then the provider's own
|
|
5
|
+
* fields (OpenRouter's `metadata.raw` names the upstream reason), else the raw body.
|
|
6
|
+
*/
|
|
7
|
+
declare function statedError(body: unknown): string | undefined;
|
|
8
|
+
/** A refused Chat Completions call, its kind from the status and its stated reason in the message. */
|
|
9
|
+
declare function httpError(failure: {
|
|
10
|
+
status: number;
|
|
11
|
+
body: unknown;
|
|
12
|
+
}, label: string): TheoremError;
|
|
4
13
|
declare function httpErrorEvent(res: Response, label: string): Promise<ProducedError>;
|
|
5
14
|
interface GatewayHeaderConfig {
|
|
6
15
|
siteUrl?: string;
|
|
@@ -16,4 +25,4 @@ declare function wireTools(wireTools?: WireFunctionTool[]): Record<string, unkno
|
|
|
16
25
|
declare function resolveResponseFormat(structured: ResolvedStructured | null): Record<string, unknown> | undefined;
|
|
17
26
|
declare function openAiGatewayHeaders(config: GatewayHeaderConfig): Record<string, string> | undefined;
|
|
18
27
|
export type { GatewayHeaderConfig };
|
|
19
|
-
export { buildChatMessages, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, wireTools, };
|
|
28
|
+
export { buildChatMessages, httpError, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, statedError, wireTools, };
|
|
@@ -3,20 +3,39 @@ import { asRecord } from '../../../kernel/engine/record.js';
|
|
|
3
3
|
import { historyMessageParts, isMediaRefPart } from '../../../kernel/interaction-parts.js';
|
|
4
4
|
import { withCarriedToolFiles } from '../../shared/carried-tool-files.js';
|
|
5
5
|
import { historyToolIdentity } from '../../shared/tool-args.js';
|
|
6
|
-
/** The
|
|
6
|
+
/** The fields Chat Completions gives every error; any other field is the provider's own detail. */
|
|
7
|
+
const STANDARD_ERROR_FIELDS = new Set(['message', 'type', 'param', 'code']);
|
|
8
|
+
/**
|
|
9
|
+
* Why a Chat Completions body says the call failed: its `error.message`, then the provider's own
|
|
10
|
+
* fields (OpenRouter's `metadata.raw` names the upstream reason), else the raw body.
|
|
11
|
+
*/
|
|
12
|
+
function statedError(body) {
|
|
13
|
+
if (typeof body === 'string')
|
|
14
|
+
return body.trim() || undefined;
|
|
15
|
+
const error = asRecord(asRecord(body)?.error);
|
|
16
|
+
if (!error)
|
|
17
|
+
return body === undefined || body === null ? undefined : JSON.stringify(body);
|
|
18
|
+
const own = Object.fromEntries(Object.entries(error).filter(([key]) => !STANDARD_ERROR_FIELDS.has(key)));
|
|
19
|
+
const said = typeof error.message === 'string' && error.message ? [error.message] : [];
|
|
20
|
+
const more = Object.keys(own).length > 0 ? [JSON.stringify(own)] : [];
|
|
21
|
+
return [...said, ...more].join(' ') || JSON.stringify(error);
|
|
22
|
+
}
|
|
23
|
+
/** A refused Chat Completions call, its kind from the status and its stated reason in the message. */
|
|
24
|
+
function httpError(failure, label) {
|
|
25
|
+
const detail = statedError(failure.body);
|
|
26
|
+
const head = `${label} HTTP ${String(failure.status)}`;
|
|
27
|
+
return new TheoremError(kindOfHttpStatus(failure.status), detail ? `${head}: ${detail}` : head);
|
|
28
|
+
}
|
|
7
29
|
async function httpErrorEvent(res, label) {
|
|
8
30
|
const text = (await res.text()).trim();
|
|
9
|
-
let
|
|
31
|
+
let body = text;
|
|
10
32
|
try {
|
|
11
|
-
|
|
12
|
-
if (typeof message === 'string' && message)
|
|
13
|
-
detail = message;
|
|
33
|
+
body = JSON.parse(text);
|
|
14
34
|
}
|
|
15
35
|
catch {
|
|
16
36
|
// why: Not JSON: the raw body is the detail.
|
|
17
37
|
}
|
|
18
|
-
|
|
19
|
-
return toErrorEvent(new TheoremError(kindOfHttpStatus(res.status), detail ? `${head}: ${detail}` : head));
|
|
38
|
+
return toErrorEvent(httpError({ status: res.status, body }, label));
|
|
20
39
|
}
|
|
21
40
|
function rejectMediaRef(part) {
|
|
22
41
|
if (isMediaRefPart(part)) {
|
|
@@ -159,4 +178,4 @@ function openAiGatewayHeaders(config) {
|
|
|
159
178
|
}
|
|
160
179
|
return Object.keys(headers).length > 0 ? headers : undefined;
|
|
161
180
|
}
|
|
162
|
-
export { buildChatMessages, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, wireTools, };
|
|
181
|
+
export { buildChatMessages, httpError, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, statedError, wireTools, };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/agents",
|
|
3
|
-
"version": "0.3.4-next.
|
|
3
|
+
"version": "0.3.4-next.590.g0246066",
|
|
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",
|