@theoremjs/agents 0.3.5-next.911.g193d75c → 0.3.5-next.914.ga9d17c6
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 +2 -0
- package/esm/mod.js +1 -0
- package/esm/src/kernel/engine/runner/gates.js +4 -0
- package/esm/src/kernel/engine/runner/state.d.ts +2 -0
- package/esm/src/kernel/engine/runner/steps.js +12 -3
- package/esm/src/kernel/mod.d.ts +2 -0
- package/esm/src/kernel/mod.js +1 -0
- package/esm/src/kernel/schema.d.ts +1 -1
- package/esm/src/kernel/schema.js +2 -0
- package/esm/src/kernel/stages.d.ts +14 -2
- package/esm/src/kernel/stages.js +25 -4
- package/esm/src/kernel/tools/agent.d.ts +1 -6
- package/esm/src/kernel/tools/agent.js +1 -9
- package/esm/src/kernel/tools/coordinate.js +4 -3
- package/esm/src/kernel/tools/execute.d.ts +2 -0
- package/esm/src/kernel/tools/execute.js +9 -8
- package/esm/src/kernel/tools/failed.d.ts +12 -0
- package/esm/src/kernel/tools/failed.js +13 -0
- package/esm/src/kernel/tools/operation.d.ts +1 -0
- package/esm/src/kernel/tools/operation.js +1 -0
- package/esm/src/kernel/tools/stage-run.d.ts +4 -0
- package/esm/src/kernel/tools/stage-run.js +2 -0
- package/esm/src/observability/trace-catalog.js +1 -0
- 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
|
| Schema | `PROFILE_FIELDS`, `PROFILE_GRAPH`, `PROFILE_TYPES`, `PROFILE_ID_MAX_CHARS`, `PROFILE_HANDLE_MAX_CHARS`, `EXTRA_FIELDS`, `REQUEST_FIELDS`, `API_EXPORTS`, `fieldMeta`, `catalogPathFor`, `DYNAMIC_FIELD_PARENTS`, `spineFacetsForProfileType`, `profileGraphFacet`, `ProfileGraphFacet`, `ProfileGraphFacetId`, `ProfileGraphEditor`, `ProfileGraphRole`, `THINKING_LEVELS`, `KEY_SLOT_NAME`, `isKeySlotName`, `MEDIA_INPUT_KINDS`, `MEDIA_INPUT_KIND_VALUES`, `MEDIA_WILDCARDS`, `ATTACHMENT_ACCEPT_MIMES`, `IMAGE_ATTACHMENT_ACCEPT_MIMES`, `VOICE_ACCEPT_MIMES`, `SUMMARY_MODES`, `STREAM_MODES`, `SPEECH_AUDIO_FORMATS`, `COMPACTION_METERS`, `COMPACTION_OUTCOMES`, `COMPACTION_TIMINGS`, `TURN_STAGES`, `TURN_INJECT_STAGES`, `TURN_STOP_KINDS`, `CONTINUE_STOP_KINDS`, `TOOL_GATE_KINDS`, `AWAITING_USER_INPUT_KINDS`, `AWAITING_USER_INPUT_STATUS`, `TOOL_LOAD_TIERS`, `TOOL_ACCESS`, `TOOL_PERMISSION`, `TOOL_TYPES`, `AUTH_UNAUTHENTICATED_POLICIES`, `HTTP_METHODS`, `STUDIO_AUTH_TYPES`, `TOOL_AUTH_TYPES`, `AuthUnauthenticatedPolicy`, `CustomToolType`, `HttpMethod`, `StudioAuthType`, `ToolAccess`, `ToolAuthType`, `ToolPermission`, `ToolType`, `LIVE_ACTIVITY_HANDLINGS`, `LIVE_START_SENSITIVITIES`, `LIVE_END_SENSITIVITIES` |
|
|
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
|
-
| Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `assertToolSettings`, `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
|
+
| Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `assertToolSettings`, `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`, `ToolFailed`, `StatedToolFailure`, `McpRpcResponse`, `ModelToolResult`, `PageAnswer` |
|
|
467
467
|
| Tool execution | `ToolBackground`, `ToolBackgroundCall`, `ToolBackgroundHandle`, `ToolBackgroundService`, `ToolBackgroundSettled`, `ToolSteerReceipt`, `ToolSteerRefusal`, `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` |
|
package/esm/mod.d.ts
CHANGED
|
@@ -67,6 +67,8 @@ export { AUTO_CONTINUE_DELAY_MS, DEFAULT_ALLOW_CONTINUE, DEFAULT_AUTO_CONTINUE,
|
|
|
67
67
|
export { systemLinesProblem } from './src/kernel/system-lines.js';
|
|
68
68
|
export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, ToolBackgroundSettled, ToolSteerReceipt, ToolSteerRefusal, } from './src/kernel/tools/background.js';
|
|
69
69
|
export { authorizeToolReplay } from './src/kernel/tools/execute.js';
|
|
70
|
+
export type { StatedToolFailure } from './src/kernel/tools/failed.js';
|
|
71
|
+
export { ToolFailed } from './src/kernel/tools/failed.js';
|
|
70
72
|
export { GATE_DECISIONS, type GateDecision } from './src/kernel/tools/gate-answer.js';
|
|
71
73
|
export type { MemoryToolExecutionOptions } from './src/kernel/tools/memory-execution.js';
|
|
72
74
|
export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
|
package/esm/mod.js
CHANGED
|
@@ -42,6 +42,7 @@ export { applyStageResult, STAGE_AFFORDANCE_MATRIX, STAGE_AFFORDANCES, stageAllo
|
|
|
42
42
|
export { AUTO_CONTINUE_DELAY_MS, DEFAULT_ALLOW_CONTINUE, DEFAULT_AUTO_CONTINUE, GenerationStopError, isContinueStopKind, isGenerationStopError, isResumeableStop, isUserCancelledStop, profileAllowsInject, profileAllowsSteering, profileTurnResumption, shouldAutoContinue, turnStopFromClientStreamEnd, } from './src/kernel/stop.js';
|
|
43
43
|
export { systemLinesProblem } from './src/kernel/system-lines.js';
|
|
44
44
|
export { authorizeToolReplay } from './src/kernel/tools/execute.js';
|
|
45
|
+
export { ToolFailed } from './src/kernel/tools/failed.js';
|
|
45
46
|
export { GATE_DECISIONS } from './src/kernel/tools/gate-answer.js';
|
|
46
47
|
export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
|
|
47
48
|
export { askUserTool, assertToolSettings, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
|
|
@@ -565,6 +565,7 @@ async function* executeSingleAttemptCycle(args) {
|
|
|
565
565
|
for (;;) {
|
|
566
566
|
state.attemptEvents = [];
|
|
567
567
|
state.released = '';
|
|
568
|
+
delete state.endedByStage;
|
|
568
569
|
state.withheldVisible = false;
|
|
569
570
|
state.promptLeaks = undefined;
|
|
570
571
|
const attempt = yield* executeAttempt({
|
|
@@ -585,6 +586,9 @@ async function* executeSingleAttemptCycle(args) {
|
|
|
585
586
|
if (state.lastStop?.kind === 'cancelled') {
|
|
586
587
|
return { status: 'terminal' };
|
|
587
588
|
}
|
|
589
|
+
// why: A post_tool `end` closed the turn; its reply still passes the checks below.
|
|
590
|
+
if (state.endedByStage)
|
|
591
|
+
break;
|
|
588
592
|
const beforeEnd = yield* applyTurnStage({
|
|
589
593
|
profile,
|
|
590
594
|
generation: flow.currentGen,
|
|
@@ -91,6 +91,8 @@ interface StepExecutionState {
|
|
|
91
91
|
toolResults: TurnToolResult[];
|
|
92
92
|
/** Last provider stop from a discarded provider `done` event. */
|
|
93
93
|
lastStop?: TurnStop;
|
|
94
|
+
/** A `post_tool` stage ended this attempt: no model step follows, and `before_end` does not run. */
|
|
95
|
+
endedByStage?: true;
|
|
94
96
|
providerState?: import('../../checkpoint.js').ProviderCheckpoint;
|
|
95
97
|
/** Usage of the last model call; a continuation's prompt estimate extends it. */
|
|
96
98
|
lastCall?: CallUsage;
|
|
@@ -484,7 +484,7 @@ function* applyToolSettlement(settlement, state, call) {
|
|
|
484
484
|
toolName: call.name,
|
|
485
485
|
});
|
|
486
486
|
}
|
|
487
|
-
return 'continue';
|
|
487
|
+
return settlement.ended ? 'ended' : 'continue';
|
|
488
488
|
}
|
|
489
489
|
/** A step's reply as the model reads it back: its text, then its calls with the reasoning before them. */
|
|
490
490
|
function stepReply(outcome) {
|
|
@@ -549,6 +549,7 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
|
|
|
549
549
|
history: () => state.currentHistory,
|
|
550
550
|
injectAllowed: profileAllowsInject(profile),
|
|
551
551
|
injectWouldExceedMaxSteps: injectWouldExceedMaxSteps(state.stepCount, generation.maxSteps),
|
|
552
|
+
endAllowed: true,
|
|
552
553
|
host: generation.host,
|
|
553
554
|
signal,
|
|
554
555
|
stepCalls: calls.map((call) => ({ callId: call.callId, tool: call.name, input: call.shown })),
|
|
@@ -601,6 +602,7 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
|
|
|
601
602
|
const settlements = yield* runSideBySide(calls.map((call) => call.failure ? undefined : inStep(order, call.callId, () => execute(call))));
|
|
602
603
|
let gated = false;
|
|
603
604
|
let cancelled = false;
|
|
605
|
+
let ended = false;
|
|
604
606
|
for (const [index, call] of calls.entries()) {
|
|
605
607
|
if (call.failure) {
|
|
606
608
|
yield recordProviderToolFailure(state, { ...call, activityFailed: failedActivity(call.name, profile.labels) }, call.failure);
|
|
@@ -614,9 +616,11 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
|
|
|
614
616
|
cancelled = true;
|
|
615
617
|
if (outcome === 'gated')
|
|
616
618
|
gated = true;
|
|
619
|
+
if (outcome === 'ended')
|
|
620
|
+
ended = true;
|
|
617
621
|
}
|
|
618
|
-
// why: Steers land once a step, after every call's own post_tool inject, so calls side by side never land one twice.
|
|
619
|
-
if (!cancelled && !gated && calls.length > 0) {
|
|
622
|
+
// why: Steers land once a step, after every call's own post_tool inject, so calls side by side never land one twice; an ended turn reads nothing more, so its steers stay waiting.
|
|
623
|
+
if (!cancelled && !gated && !ended && calls.length > 0) {
|
|
620
624
|
const steers = yield* steersToLand(state, profile, 'post_tool', stages.injectWouldExceedMaxSteps);
|
|
621
625
|
if (steers) {
|
|
622
626
|
yield* applyStageInjects(state, 'post_tool', steers.units);
|
|
@@ -629,6 +633,11 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
|
|
|
629
633
|
state.lastStop = { kind: 'gate' };
|
|
630
634
|
return false;
|
|
631
635
|
}
|
|
636
|
+
if (ended) {
|
|
637
|
+
state.lastStop = { kind: 'completed' };
|
|
638
|
+
state.endedByStage = true;
|
|
639
|
+
return false;
|
|
640
|
+
}
|
|
632
641
|
return calls.length > 0;
|
|
633
642
|
}
|
|
634
643
|
async function* executeAttempt(args) {
|
package/esm/src/kernel/mod.d.ts
CHANGED
|
@@ -65,6 +65,8 @@ export { systemPromptProblem } from './system-parts.js';
|
|
|
65
65
|
export { activityLabelProblem } from './tools/activity-label.js';
|
|
66
66
|
export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
|
|
67
67
|
export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, ToolBackgroundSettled, ToolSteerReceipt, ToolSteerRefusal, } from './tools/background.js';
|
|
68
|
+
export type { StatedToolFailure } from './tools/failed.js';
|
|
69
|
+
export { ToolFailed } from './tools/failed.js';
|
|
68
70
|
export { type AnsweredGate, answerGatedCall, GATE_DECISIONS, type GateAnswerRequest, type GateDecision, gateExpired, type HeldGatedCall, resolveGateTtlMs, sessionPermissionsAfterApproval, type ToolGateAuth, } from './tools/gate-answer.js';
|
|
69
71
|
export type { MemoryToolExecutionOptions } from './tools/memory-execution.js';
|
|
70
72
|
export { createMemoryToolExecution } from './tools/memory-execution.js';
|
package/esm/src/kernel/mod.js
CHANGED
|
@@ -39,6 +39,7 @@ export { systemLinesProblem, systemReading } from './system-lines.js';
|
|
|
39
39
|
export { systemPromptProblem } from './system-parts.js';
|
|
40
40
|
export { activityLabelProblem } from './tools/activity-label.js';
|
|
41
41
|
export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
|
|
42
|
+
export { ToolFailed } from './tools/failed.js';
|
|
42
43
|
export { answerGatedCall, GATE_DECISIONS, gateExpired, resolveGateTtlMs, sessionPermissionsAfterApproval, } from './tools/gate-answer.js';
|
|
43
44
|
export { createMemoryToolExecution } from './tools/memory-execution.js';
|
|
44
45
|
export { askUserTool, assertToolSettings, authorizeToolReplay, coerceToolResultParts, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, withCredentialQuery, } from './tools/mod.js';
|
|
@@ -114,7 +114,7 @@ export declare const AWAITING_USER_INPUT_KINDS: readonly ["confirm", "choice", "
|
|
|
114
114
|
/** One of {@linkcode AWAITING_USER_INPUT_KINDS}. */
|
|
115
115
|
export type AwaitingUserInputKind = (typeof AWAITING_USER_INPUT_KINDS)[number];
|
|
116
116
|
/** Why a stage handler's result was partly or wholly ignored. */
|
|
117
|
-
export declare const STAGE_APPLY_WARNING_CODES: readonly ["affordance_not_allowed", "inject_not_allowed", "inject_rejected_max_steps", "inject_invalid_messages", "inject_id_invalid", "inject_released_invalid", "deny_invalid", "confirm_invalid", "mutate_invalid", "label_failed_invalid", "abort_invalid", "wait_for_invalid", "unknown_field", "result_invalid"];
|
|
117
|
+
export declare const STAGE_APPLY_WARNING_CODES: readonly ["affordance_not_allowed", "inject_not_allowed", "inject_rejected_max_steps", "inject_invalid_messages", "inject_id_invalid", "inject_released_invalid", "deny_invalid", "confirm_invalid", "mutate_invalid", "label_failed_invalid", "abort_invalid", "wait_for_invalid", "end_not_allowed", "end_invalid", "unknown_field", "result_invalid"];
|
|
118
118
|
/** One of {@linkcode STAGE_APPLY_WARNING_CODES}. */
|
|
119
119
|
export type StageApplyWarningCode = (typeof STAGE_APPLY_WARNING_CODES)[number];
|
|
120
120
|
/** The `status` of a tool output that asks the user a question. */
|
package/esm/src/kernel/schema.js
CHANGED
|
@@ -7,9 +7,10 @@ import type { Profile, TurnEvent, TurnHistoryMessage } from './types.js';
|
|
|
7
7
|
export type { AwaitingUserInput, ToolGate };
|
|
8
8
|
/**
|
|
9
9
|
* What a stage handler can ask for: inject messages, abort, deny a tool call, ask for
|
|
10
|
-
* confirmation, mutate it, label it failed,
|
|
10
|
+
* confirmation, mutate it, label it failed, have it wait for other calls in its step, or end
|
|
11
|
+
* the turn once its step's calls settle.
|
|
11
12
|
*/
|
|
12
|
-
export declare const STAGE_AFFORDANCES: readonly ["inject", "abort", "deny", "confirm", "mutate", "labelFailed", "waitFor"];
|
|
13
|
+
export declare const STAGE_AFFORDANCES: readonly ["inject", "abort", "deny", "confirm", "mutate", "labelFailed", "waitFor", "end"];
|
|
13
14
|
/** One of {@linkcode STAGE_AFFORDANCES}. */
|
|
14
15
|
export type StageAffordance = (typeof STAGE_AFFORDANCES)[number];
|
|
15
16
|
/** Inject still needs the inject gate at apply time. Empty = observe only. */
|
|
@@ -102,6 +103,13 @@ export interface StageResult {
|
|
|
102
103
|
* starts. A call held for confirmation is held at once and does not wait.
|
|
103
104
|
*/
|
|
104
105
|
waitFor?: string[];
|
|
106
|
+
/**
|
|
107
|
+
* `post_tool` on a text turn only: the turn ends once every call of this step has settled. The
|
|
108
|
+
* model takes no further step, `before_end` does not run, and `done` stops as `completed`. The
|
|
109
|
+
* reply is what the model wrote before its calls, possibly empty, and still passes its checks: a
|
|
110
|
+
* refused reply is retried like any other, as a new step `end` no longer holds.
|
|
111
|
+
*/
|
|
112
|
+
end?: true;
|
|
105
113
|
}
|
|
106
114
|
/** A rewrite of a tool call's input or output. */
|
|
107
115
|
export type StageMutate = {
|
|
@@ -124,6 +132,8 @@ export interface StageApplyInput {
|
|
|
124
132
|
* `mutate` is then a `mutate_invalid` warning, never a silent no-op.
|
|
125
133
|
*/
|
|
126
134
|
mutable?: boolean;
|
|
135
|
+
/** True on a text turn's tool step, the only place `end` has a turn to end. */
|
|
136
|
+
endAllowed?: boolean;
|
|
127
137
|
}
|
|
128
138
|
export interface InjectUnit {
|
|
129
139
|
id?: string;
|
|
@@ -147,6 +157,7 @@ export interface StageApplyOutput {
|
|
|
147
157
|
mutate?: StageMutate;
|
|
148
158
|
labelFailed?: true;
|
|
149
159
|
waitFor?: string[];
|
|
160
|
+
end?: true;
|
|
150
161
|
warnings: StageApplyWarning[];
|
|
151
162
|
}
|
|
152
163
|
/** True when the affordance is physically allowed at `stage` (ignores inject gate). */
|
|
@@ -189,6 +200,7 @@ export interface RunStageArgs extends StageCallBag {
|
|
|
189
200
|
injectAllowed: boolean;
|
|
190
201
|
injectWouldExceedMaxSteps?: boolean;
|
|
191
202
|
mutable?: boolean;
|
|
203
|
+
endAllowed?: boolean;
|
|
192
204
|
host?: unknown;
|
|
193
205
|
signal?: AbortSignal;
|
|
194
206
|
span?: SpanHandle;
|
package/esm/src/kernel/stages.js
CHANGED
|
@@ -8,7 +8,8 @@ import { hookFailed } from './hook-failure.js';
|
|
|
8
8
|
import { isRecord } from './util/record.js';
|
|
9
9
|
/**
|
|
10
10
|
* What a stage handler can ask for: inject messages, abort, deny a tool call, ask for
|
|
11
|
-
* confirmation, mutate it, label it failed,
|
|
11
|
+
* confirmation, mutate it, label it failed, have it wait for other calls in its step, or end
|
|
12
|
+
* the turn once its step's calls settle.
|
|
12
13
|
*/
|
|
13
14
|
export const STAGE_AFFORDANCES = [
|
|
14
15
|
'inject',
|
|
@@ -18,12 +19,13 @@ export const STAGE_AFFORDANCES = [
|
|
|
18
19
|
'mutate',
|
|
19
20
|
'labelFailed',
|
|
20
21
|
'waitFor',
|
|
22
|
+
'end',
|
|
21
23
|
];
|
|
22
24
|
/** Inject still needs the inject gate at apply time. Empty = observe only. */
|
|
23
25
|
export const STAGE_AFFORDANCE_MATRIX = Object.freeze({
|
|
24
26
|
pre_turn: Object.freeze(['inject', 'abort']),
|
|
25
27
|
pre_tool: Object.freeze(['abort', 'deny', 'confirm', 'mutate', 'waitFor']),
|
|
26
|
-
post_tool: Object.freeze(['inject', 'abort', 'deny', 'mutate', 'labelFailed']),
|
|
28
|
+
post_tool: Object.freeze(['inject', 'abort', 'deny', 'mutate', 'labelFailed', 'end']),
|
|
27
29
|
before_end: Object.freeze(['inject', 'abort']),
|
|
28
30
|
post_turn: Object.freeze([]),
|
|
29
31
|
});
|
|
@@ -237,6 +239,22 @@ function applyWaitForField(result, stage, out) {
|
|
|
237
239
|
out.waitFor = [...new Set(result.waitFor)];
|
|
238
240
|
}
|
|
239
241
|
}
|
|
242
|
+
function applyEndField(result, input, out) {
|
|
243
|
+
if (!('end' in result) || result.end === undefined)
|
|
244
|
+
return;
|
|
245
|
+
if (!stageAllowsAffordance(input.stage, 'end')) {
|
|
246
|
+
warn(out.warnings, 'affordance_not_allowed', 'end', `end is not allowed at stage ${input.stage}`);
|
|
247
|
+
}
|
|
248
|
+
else if (result.end !== true) {
|
|
249
|
+
warn(out.warnings, 'end_invalid', 'end', 'end must be true'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
250
|
+
}
|
|
251
|
+
else if (!input.endAllowed) {
|
|
252
|
+
warn(out.warnings, 'end_not_allowed', 'end', "end is ignored outside a text turn's tool step");
|
|
253
|
+
}
|
|
254
|
+
else {
|
|
255
|
+
out.end = true;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
240
258
|
const MUTATE_SUBJECT = { pre_tool: 'input', post_tool: 'output' };
|
|
241
259
|
function mutateSubject(stage) {
|
|
242
260
|
return stage in MUTATE_SUBJECT ? MUTATE_SUBJECT[stage] : undefined;
|
|
@@ -295,6 +313,7 @@ export function applyStageResult(input) {
|
|
|
295
313
|
applyMutateField(result, input, out);
|
|
296
314
|
applyLabelFailedField(result, stage, out);
|
|
297
315
|
applyWaitForField(result, stage, out);
|
|
316
|
+
applyEndField(result, input, out);
|
|
298
317
|
if (out.deny && out.confirm) {
|
|
299
318
|
warn(warnings, 'confirm_invalid', 'confirm', 'confirm ignored because deny is set'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
300
319
|
delete out.confirm;
|
|
@@ -367,6 +386,8 @@ function mergeApplied(parts) {
|
|
|
367
386
|
out.labelFailed = true;
|
|
368
387
|
if (part.waitFor)
|
|
369
388
|
out.waitFor = [...new Set([...(out.waitFor ?? []), ...part.waitFor])];
|
|
389
|
+
if (part.end)
|
|
390
|
+
out.end = true;
|
|
370
391
|
if (part.inject)
|
|
371
392
|
out.inject.push(part.inject);
|
|
372
393
|
}
|
|
@@ -405,7 +426,7 @@ async function applyHandlers(handlers, ctx, apply, signal) {
|
|
|
405
426
|
}
|
|
406
427
|
/** Stage events always emit, even with no handlers. */
|
|
407
428
|
export async function* runStage(args) {
|
|
408
|
-
const { stage, step, history, handlers, guardrails, injectAllowed, injectWouldExceedMaxSteps, mutable, host, signal, span, ...bag } = args;
|
|
429
|
+
const { stage, step, history, handlers, guardrails, injectAllowed, injectWouldExceedMaxSteps, mutable, endAllowed, host, signal, span, ...bag } = args;
|
|
409
430
|
throwIfAborted(signal);
|
|
410
431
|
// why: Stream stage events stay lean (no outputRaw/failure). Hosts read those on
|
|
411
432
|
// StageContext via onStage; tool failures also ride tool events.
|
|
@@ -423,7 +444,7 @@ export async function* runStage(args) {
|
|
|
423
444
|
}
|
|
424
445
|
const ctx = { stage, step, history, host, ...bag };
|
|
425
446
|
const startedMs = span?.msSinceStart();
|
|
426
|
-
const { parts, crashes } = await applyHandlers(handlers, ctx, { stage, injectAllowed, injectWouldExceedMaxSteps, mutable }, signal);
|
|
447
|
+
const { parts, crashes } = await applyHandlers(handlers, ctx, { stage, injectAllowed, injectWouldExceedMaxSteps, mutable, endAllowed }, signal);
|
|
427
448
|
if (stage === 'pre_tool' && crashes.length > 0) {
|
|
428
449
|
span?.event('theorem.stage', { stage, affordance: [] });
|
|
429
450
|
return { warnings: [], inject: [], crashed: { error: crashes[0] } };
|
|
@@ -28,11 +28,6 @@ interface AgentCaller {
|
|
|
28
28
|
/** Whether a running call of `tool` can be steered: its agent's profile allows injects. */
|
|
29
29
|
takesSteers(tool: RegisteredAgentTool): boolean;
|
|
30
30
|
}
|
|
31
|
-
/** A call that settled without a reply; the model reads `failure`. */
|
|
32
|
-
declare class AgentCallFailed extends Error {
|
|
33
|
-
readonly failure: ToolFailure;
|
|
34
|
-
constructor(failure: ToolFailure);
|
|
35
|
-
}
|
|
36
31
|
/**
|
|
37
32
|
* What the model sent, split into what goes to the called agent and what only the host reads.
|
|
38
33
|
*
|
|
@@ -68,4 +63,4 @@ declare function normalizeAgent(def: AgentToolDef, input: z.ZodType<AgentToolInp
|
|
|
68
63
|
outputSchema: Record<string, unknown>;
|
|
69
64
|
}): RegisteredAgentTool;
|
|
70
65
|
export type { AgentCaller, AgentRun };
|
|
71
|
-
export {
|
|
66
|
+
export { agentProfileProblem, agentToolInputFor, agentToolOrigin, agentToolOutput, agentToolOutputOf, agentToolProfile, normalizeAgent, splitHostInput, };
|
|
@@ -4,14 +4,6 @@ import { optionValues } from '../registry/options.js';
|
|
|
4
4
|
import { interactionPartSchema, keptReply, sourceSchema } from '../turn-events.js';
|
|
5
5
|
import { findLast } from '../util/find-last.js';
|
|
6
6
|
import { profileToolAllow } from './resolve.js';
|
|
7
|
-
/** A call that settled without a reply; the model reads `failure`. */
|
|
8
|
-
class AgentCallFailed extends Error {
|
|
9
|
-
failure;
|
|
10
|
-
constructor(failure) {
|
|
11
|
-
super(failure.message);
|
|
12
|
-
this.failure = failure;
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
7
|
/** The agents an agent tool can run: each has a turn that takes text, which a transcription turn does not. */
|
|
16
8
|
const AGENT_TOOL_TYPES = new Set(['text', 'image', 'speech']);
|
|
17
9
|
// why: Bytes that are not base64, or a text of only spaces, would be refused inside the called turn as the host's error and end the caller's turn; checked here, the model reads a failed call.
|
|
@@ -213,4 +205,4 @@ function normalizeAgent(def, input, schemas) {
|
|
|
213
205
|
...schemas,
|
|
214
206
|
};
|
|
215
207
|
}
|
|
216
|
-
export {
|
|
208
|
+
export { agentProfileProblem, agentToolInputFor, agentToolOrigin, agentToolOutput, agentToolOutputOf, agentToolProfile, normalizeAgent, splitHostInput, };
|
|
@@ -167,7 +167,7 @@ class CoordinatedExecution {
|
|
|
167
167
|
}
|
|
168
168
|
if (!this.terminal)
|
|
169
169
|
throw operationBroken('The tool run ended with no terminal event'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
170
|
-
const { modelResult, outputRaw, failure, awaiting, denied, callNotStarted, aborted, pendingInject, } = settlement;
|
|
170
|
+
const { modelResult, outputRaw, failure, awaiting, denied, callNotStarted, aborted, pendingInject, ended, } = settlement;
|
|
171
171
|
const effects = this.claim ? (failure ? 'unknown' : 'completed') : 'not_started';
|
|
172
172
|
const outcome = {
|
|
173
173
|
event: this.terminal,
|
|
@@ -181,6 +181,7 @@ class CoordinatedExecution {
|
|
|
181
181
|
callNotStarted,
|
|
182
182
|
aborted,
|
|
183
183
|
pendingInject,
|
|
184
|
+
ended,
|
|
184
185
|
},
|
|
185
186
|
};
|
|
186
187
|
const whole = toolOperationOutcomeSchema.parse(operationWireValue(outcome));
|
|
@@ -327,8 +328,8 @@ class CoordinatedExecution {
|
|
|
327
328
|
message: 'The tool asked to wait for a result after its turn ended', // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
328
329
|
}, emit);
|
|
329
330
|
}
|
|
330
|
-
// why: No turn is open, so a post_tool inject or
|
|
331
|
-
const { pendingInject: _inject, aborted: _aborted, ...kept } = settlement;
|
|
331
|
+
// why: No turn is open, so a post_tool inject, abort, or end has nothing to reach.
|
|
332
|
+
const { pendingInject: _inject, aborted: _aborted, ended: _ended, ...kept } = settlement;
|
|
332
333
|
const { terminal, crashed } = await this.finish(kept);
|
|
333
334
|
if (terminal)
|
|
334
335
|
await emit(terminal);
|
|
@@ -42,6 +42,8 @@ export type ToolExecuteSettlement = {
|
|
|
42
42
|
denied?: true;
|
|
43
43
|
/** Landed after the provider tool result is recorded: the Interactions continuation must exist first. */
|
|
44
44
|
pendingInject?: InjectUnit[];
|
|
45
|
+
/** `post_tool` ended the turn: no model step follows this call's step. */
|
|
46
|
+
ended?: true;
|
|
45
47
|
};
|
|
46
48
|
export declare function executeFunction(tools: ToolRegistry, tool: FunctionToolDef, rawInput: unknown, ctx: ToolContext, base: ToolCallBase, snapshot?: TurnToolSnapshot, stages?: ToolStageSupport,
|
|
47
49
|
/** Set when `tool` runs an agent tool: its trust, and its handler's failures and faults. */
|
|
@@ -11,10 +11,11 @@ import { jsonObjectSchema } from '../json.js';
|
|
|
11
11
|
import { isAwaitingUserInput } from '../turn-events.js';
|
|
12
12
|
import { isRecord } from '../util/record.js';
|
|
13
13
|
import { fillActivityLabel } from './activity-label.js';
|
|
14
|
-
import {
|
|
14
|
+
import { agentToolOrigin } from './agent.js';
|
|
15
15
|
import { planDetach, splitBackground } from './background.js';
|
|
16
16
|
import { coordinateTool } from './coordinate.js';
|
|
17
17
|
import { dispatchToolBody, failedActivity, failedActivityOf, failureEvent, messageOf, networkBlocked, networkBlockedEvent, requestChecks, sourceEvents, startToolExecution, toolCallArguments, toolEvent, } from './events.js';
|
|
18
|
+
import { ToolFailed } from './failed.js';
|
|
18
19
|
import { HandlerEvents } from './handler-events.js';
|
|
19
20
|
import { fetchToolImages } from './image-fetch.js';
|
|
20
21
|
import { formatToolFailureForModel, formatToolResult, frameToolFailure } from './model-text.js';
|
|
@@ -357,11 +358,12 @@ async function* withFetchedImages(base, result, images, outputRaw) {
|
|
|
357
358
|
: { finding: result.finding + note }),
|
|
358
359
|
};
|
|
359
360
|
}
|
|
360
|
-
/** What the after-call stages add to a settlement: a turn to stop, input to hand the model. */
|
|
361
|
+
/** What the after-call stages add to a settlement: a turn to stop or end, input to hand the model. */
|
|
361
362
|
function stageSettlement(post) {
|
|
362
363
|
return {
|
|
363
364
|
...(post?.abort !== undefined ? { aborted: post.abort } : {}),
|
|
364
365
|
...(post?.inject.length ? { pendingInject: post.inject } : {}),
|
|
366
|
+
...(post?.end ? { ended: true } : {}),
|
|
365
367
|
};
|
|
366
368
|
}
|
|
367
369
|
function settleToolFailure(guard, base, failure, stages, args) {
|
|
@@ -584,12 +586,11 @@ agent, beginBody) {
|
|
|
584
586
|
checks.record();
|
|
585
587
|
}
|
|
586
588
|
catch (err) {
|
|
587
|
-
if (
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
589
|
+
if (err instanceof ToolFailed)
|
|
590
|
+
return yield* fail(err.failure);
|
|
591
|
+
// why: Anything but a settled failure is the host's to fix, as a compactor's is.
|
|
592
|
+
if (agent)
|
|
591
593
|
throw err;
|
|
592
|
-
}
|
|
593
594
|
if (signedIn.prepared && err instanceof CredentialRefusedError) {
|
|
594
595
|
checks.record();
|
|
595
596
|
const refused = yield* refusedCredentialOutcome(tool, err.refusal, signedIn.secret !== undefined, ctx, base);
|
|
@@ -1141,7 +1142,7 @@ async function* executeAgentTool(args) {
|
|
|
1141
1142
|
if (next.done) {
|
|
1142
1143
|
tokens = next.value.tokens;
|
|
1143
1144
|
if ('failure' in next.value)
|
|
1144
|
-
throw new
|
|
1145
|
+
throw new ToolFailed(next.value.failure);
|
|
1145
1146
|
yield { kind: 'complete', output: next.value.output };
|
|
1146
1147
|
return;
|
|
1147
1148
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ToolFailure } from '../turn-events.js';
|
|
2
|
+
/** A failure a tool states itself: the person's wording (`error`) is added where the event reaches the host. */
|
|
3
|
+
export type StatedToolFailure = Omit<ToolFailure, 'error'>;
|
|
4
|
+
/**
|
|
5
|
+
* Thrown by a handler whose call ran and did not do what it was asked. The call settles as
|
|
6
|
+
* `failure`, under its own `code` and `kind`, and the model reads it; any other throw is a
|
|
7
|
+
* `handler_error`.
|
|
8
|
+
*/
|
|
9
|
+
export declare class ToolFailed extends Error {
|
|
10
|
+
readonly failure: StatedToolFailure;
|
|
11
|
+
constructor(failure: StatedToolFailure);
|
|
12
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown by a handler whose call ran and did not do what it was asked. The call settles as
|
|
3
|
+
* `failure`, under its own `code` and `kind`, and the model reads it; any other throw is a
|
|
4
|
+
* `handler_error`.
|
|
5
|
+
*/
|
|
6
|
+
export class ToolFailed extends Error {
|
|
7
|
+
failure;
|
|
8
|
+
constructor(failure) {
|
|
9
|
+
super(failure.message);
|
|
10
|
+
this.name = 'ToolFailed';
|
|
11
|
+
this.failure = failure;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -26,6 +26,8 @@ export interface ToolStageSupport {
|
|
|
26
26
|
history: () => readonly TurnHistoryMessage[];
|
|
27
27
|
injectAllowed: boolean;
|
|
28
28
|
injectWouldExceedMaxSteps?: boolean;
|
|
29
|
+
/** True on a text turn's tool step: `post_tool` may `end` the turn. */
|
|
30
|
+
endAllowed?: boolean;
|
|
29
31
|
host?: unknown;
|
|
30
32
|
signal?: AbortSignal;
|
|
31
33
|
span?: SpanHandle;
|
|
@@ -78,6 +80,8 @@ export type PostToolStageOutcome = {
|
|
|
78
80
|
output: unknown;
|
|
79
81
|
};
|
|
80
82
|
labelFailed?: true;
|
|
83
|
+
/** The turn ends once the step's calls settle. */
|
|
84
|
+
end?: true;
|
|
81
85
|
};
|
|
82
86
|
export declare function runPreToolPipeline(args: {
|
|
83
87
|
tool: {
|
|
@@ -190,6 +190,7 @@ export async function* runPostToolStages(args) {
|
|
|
190
190
|
injectAllowed: stages.injectAllowed,
|
|
191
191
|
injectWouldExceedMaxSteps: stages.injectWouldExceedMaxSteps,
|
|
192
192
|
mutable,
|
|
193
|
+
...(stages.endAllowed ? { endAllowed: true } : {}),
|
|
193
194
|
host: stages.host,
|
|
194
195
|
signal: stages.signal,
|
|
195
196
|
span: stages.span,
|
|
@@ -201,6 +202,7 @@ export async function* runPostToolStages(args) {
|
|
|
201
202
|
...(applied.deny ? { deny: applied.deny } : {}),
|
|
202
203
|
...(applied.mutate && 'output' in applied.mutate ? { mutate: applied.mutate } : {}),
|
|
203
204
|
...(applied.labelFailed ? { labelFailed: true } : {}),
|
|
205
|
+
...(applied.end ? { end: true } : {}),
|
|
204
206
|
inject: applied.inject,
|
|
205
207
|
};
|
|
206
208
|
}
|
|
@@ -215,6 +215,7 @@ const AFFORDANCES = {
|
|
|
215
215
|
doc: "Showed the tool's failed label for a call that completed.",
|
|
216
216
|
},
|
|
217
217
|
waitFor: { label: 'Waited', doc: 'Held a tool call until other calls in its step settled.' },
|
|
218
|
+
end: { label: 'Ended', doc: 'Ended the turn once the calls in its step settled.' },
|
|
218
219
|
};
|
|
219
220
|
const GUARDRAIL_STAGE_OPTIONS = {
|
|
220
221
|
input: { label: 'User input', doc: 'Text the user sent.' },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/agents",
|
|
3
|
-
"version": "0.3.5-next.
|
|
3
|
+
"version": "0.3.5-next.914.ga9d17c6",
|
|
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",
|