@theoremjs/agents 0.3.4-next.871.gea9bbcc → 0.3.4

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
@@ -464,7 +464,7 @@ Named exports from the root barrel (same symbols hosts get from `@theoremjs/agen
464
464
  | Scope | `KernelScope`, `createKernelScope`, `defaultKernelScope`, `KernelRegistry`, `createKernelRegistry` |
465
465
  | Profiles | `ProfileDefinition`, `ProfileDefinitionBase`, `TextProfileDefinition`, `ImageProfileDefinition`, `SpeechProfileDefinition`, `TranscriptionProfileDefinition`, `LiveProfileDefinition`, `HostProfileDefinition`, `DecisionProfileDefinition`, `EmbeddingProfileDefinition`, `ProfileRegistry`, `createProfileRegistry`, `clearProfiles`, `defineProfile`, `getProfile`, `hasProfile`, `listProfiles`, `registerProfile`, `registerProfiles`, `projectProfile`, `resolveTurn`, `pickModel`, `resolveTurnSystemPrompt`, `systemLinesProblem` |
466
466
  | Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `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` |
467
- | Tool execution | `ToolBackground`, `ToolBackgroundCall`, `ToolBackgroundHandle`, `ToolBackgroundService`, `ToolOperationReply`, `toolOperationReplySchema`, `BackgroundToolEvent`, `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
467
+ | Tool execution | `ToolBackground`, `ToolBackgroundCall`, `ToolBackgroundHandle`, `ToolBackgroundService`, `ToolBackgroundSettled`, `ToolSteerReceipt`, `ToolOperationReply`, `toolOperationReplySchema`, `BackgroundToolEvent`, `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
468
468
  | Structured | `SchemaRegistry`, `createSchemaRegistry`, `getStructured`, `registerStructured` |
469
469
  | Stop / resume | `ProfileTurnBehaviourSpec`, `MediaTurnBehaviourSpec`, `ProfileTurnResumptionSpec`, `TurnContinueFrom`, `TurnStop`, `TurnStopKind`, `ContinueStopKind`, `StepLimitMode`, `CONTINUE_STOP_KINDS`, `AUTO_CONTINUE_DELAY_MS`, `DEFAULT_ALLOW_CONTINUE`, `DEFAULT_AUTO_CONTINUE`, `GenerationStopError`, `isContinueStopKind`, `isGenerationStopError`, `isResumeableStop`, `isUserCancelledStop`, `profileAllowsSteering`, `profileAllowsInject`, `profileTurnResumption`, `shouldAutoContinue`, `turnStopFromClientStreamEnd`, `turnStopFromInteractionStatus`, `turnStopFromOpenAiFinishReason` |
470
470
  | Stages (target foundation) | `TURN_STAGES`, `TURN_INJECT_STAGES`, `STAGE_AFFORDANCES`, `STAGE_AFFORDANCE_MATRIX`, `TOOL_GATE_KINDS`, `AWAITING_USER_INPUT_KINDS`, `AWAITING_USER_INPUT_STATUS`, `applyStageResult`, `awaitingUserInputSchema`, `toolGateSchema`, `isTurnStage`, `isTurnInjectStage`, `isToolGateKind`, `isAwaitingUserInput`, `stageAllowsAffordance`, `stageEventFields`, `profileAllowsInject`, `StageAffordance`, `StageContext`, `StageResult`, `StageMutate`, `StageHandler`, `StageApplyInput`, `StageApplyOutput`, `StageApplyWarning`, `StageApplyWarningCode`, `StageEventExtra`, `AwaitingUserInput`, `ToolGate` — contract [`docs/contracts/stages.md`](https://github.com/masudl-hub/theoremai/blob/main/docs/contracts/stages.md) |
@@ -67,6 +67,8 @@ function runNestedTurn(args) {
67
67
  ctx.agentDepth = args.agentDepth;
68
68
  if (args.compacting)
69
69
  ctx.compacting = args.compacting;
70
+ if (args.steers)
71
+ ctx.steers = args.steers;
70
72
  ctx.observability = resolveObservabilityPolicy(ctx.known?.observability);
71
73
  return runTracedTurn(ctx, nestedTurnModel(args.provider, args.req.profile, args.req.model, args.req));
72
74
  }
@@ -247,6 +249,7 @@ async function* emitTurn(args) {
247
249
  trace: args.trace,
248
250
  ...(args.agents ? { agents: args.agents } : {}),
249
251
  ...(args.background ? { background: args.background } : {}),
252
+ ...(args.steers ? { steers: args.steers } : {}),
250
253
  });
251
254
  args.outState.state = state;
252
255
  if (state.lateResults !== undefined) {
@@ -316,6 +319,7 @@ async function* streamTurnEvents(ctx, profile, gen, provider, compactionSpec) {
316
319
  trace: ctx.trace,
317
320
  agents: ctx.agents,
318
321
  background: ctx.background,
322
+ steers: ctx.steers,
319
323
  outState: ctx,
320
324
  })) {
321
325
  const attached = await maybeAttachAfter(event, ctx, gen, compactionSpec);
@@ -2,6 +2,7 @@ import type { ErrorKind } from '../../../guardrails/error.js';
2
2
  import type { SpanHandle } from '../../../observability/trace-span.js';
3
3
  import type { KernelRegistry } from '../../registry/kernel-registry.js';
4
4
  import { type AgentCaller } from '../../tools/agent.js';
5
+ import type { SteerQueue } from '../../tools/steer.js';
5
6
  import type { ModelBinding, TurnEvent, TurnEventOf, TurnModel, TurnRequest } from '../../types.js';
6
7
  /** Errors only the host can fix: a nested turn throws them rather than failing quietly every call. */
7
8
  declare const NESTED_THROWS: ReadonlySet<ErrorKind>;
@@ -12,6 +13,7 @@ type RunNestedTurn = (args: {
12
13
  provider: TurnModel;
13
14
  parent: SpanHandle;
14
15
  agentDepth: number;
16
+ steers?: SteerQueue;
15
17
  }) => AsyncGenerator<TurnEvent>;
16
18
  /**
17
19
  * Agent tool calls for one turn. `own` is the turn's model binding: its
@@ -1,6 +1,7 @@
1
1
  import { errorCopyText, isAbortError, TheoremError, throwIfAborted, toErrorEvent, } from '../../../guardrails/error.js';
2
2
  import { labelText } from '../../../guardrails/labels.js';
3
3
  import { nestedTurnModel, resolveRegisteredTurnModel } from '../../provider-dispatch.js';
4
+ import { profileAllowsInject } from '../../stop.js';
4
5
  import { agentProfileProblem, agentToolOutputOf, splitHostInput, } from '../../tools/agent.js';
5
6
  import { findLast } from '../../util/find-last.js';
6
7
  import { sumEventTokens } from '../usage.js';
@@ -19,7 +20,11 @@ function createAgentCaller(args) {
19
20
  const calls = new Map();
20
21
  const { registry, req } = args;
21
22
  return {
22
- async *run({ tool, callId, input, caller, span, signal }) {
23
+ takesSteers(tool) {
24
+ const profile = registry.profiles.find(tool.profile);
25
+ return profile !== undefined && profileAllowsInject(profile);
26
+ },
27
+ async *run({ tool, callId, input, caller, span, signal, steers, }) {
23
28
  const labels = caller.labels;
24
29
  const settled = (code, kind, message) => ({
25
30
  failure: { code, kind, message },
@@ -58,39 +63,45 @@ function createAgentCaller(args) {
58
63
  throw new TheoremError('internal', `Agent tool "${tool.name}" ran without a span`); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
59
64
  }
60
65
  const { speech, ...sent } = modelInput;
61
- const events = [];
62
- try {
63
- for await (const event of args.runNested({
64
- req: {
65
- ...(speech ? { speech } : {}),
66
- ...fields,
67
- profile: tool.profile,
68
- execution: req.execution,
69
- pageExecution: req.pageExecution,
70
- input: fields.input ?? sent,
71
- ...(signal ? { signal } : {}),
72
- ...(req.onAgentCall ? { onAgentCall: req.onAgentCall } : {}),
73
- },
74
- provider,
75
- parent: span,
76
- agentDepth: args.depth + 1,
77
- })) {
78
- events.push(event);
79
- yield event;
80
- }
81
- }
82
- catch (err) {
83
- // why: A turn refused before it starts (a file the agent does not take) throws; the caller's model reads it like any other failed call.
84
- if (!(err instanceof TheoremError) || NESTED_THROWS.has(err.kind) || isAbortError(err)) {
85
- throw err;
86
- }
87
- events.push(toErrorEvent(err));
88
- }
66
+ const events = yield* nestedEvents(args.runNested({
67
+ req: {
68
+ ...(speech ? { speech } : {}),
69
+ ...fields,
70
+ profile: tool.profile,
71
+ execution: req.execution,
72
+ pageExecution: req.pageExecution,
73
+ input: fields.input ?? sent,
74
+ ...(signal ? { signal } : {}),
75
+ ...(req.onAgentCall ? { onAgentCall: req.onAgentCall } : {}),
76
+ },
77
+ provider,
78
+ parent: span,
79
+ agentDepth: args.depth + 1,
80
+ ...(steers ? { steers } : {}),
81
+ }));
89
82
  throwIfAborted(signal);
90
83
  return agentRunOf(events, tool.name, tool.profile, labels);
91
84
  },
92
85
  };
93
86
  }
87
+ /** Relays an agent's turn and keeps its events; a turn refused before it starts ends in its error event. */
88
+ async function* nestedEvents(turn) {
89
+ const events = [];
90
+ try {
91
+ for await (const event of turn) {
92
+ events.push(event);
93
+ yield event;
94
+ }
95
+ }
96
+ catch (err) {
97
+ // why: A turn refused before it starts (a file the agent does not take) throws; the caller's model reads it like any other failed call.
98
+ if (!(err instanceof TheoremError) || NESTED_THROWS.has(err.kind) || isAbortError(err)) {
99
+ throw err;
100
+ }
101
+ events.push(toErrorEvent(err));
102
+ }
103
+ return events;
104
+ }
94
105
  /** The provider an agent's turn runs on: the host's for this call, else the caller's, else the registry's. */
95
106
  function agentProvider(from, profileId, model, hostProvider) {
96
107
  if (hostProvider)
@@ -35,4 +35,16 @@ export declare function applyStageInjects(state: StepExecutionState, stage: Turn
35
35
  callId?: string;
36
36
  toolName?: string;
37
37
  }): Generator<TurnEvent, number>;
38
+ /**
39
+ * The steers waiting for this turn, sanitized, when `stage` takes an inject the turn can read.
40
+ * `waiting` is what the queue gave, to mark joined once `units` land.
41
+ */
42
+ export declare function steersToLand(state: StepExecutionState, profile: Profile, stage: TurnStage, injectWouldExceedMaxSteps: boolean | undefined): Generator<TurnEvent, {
43
+ waiting: readonly InjectUnit[];
44
+ units: InjectUnit[];
45
+ } | undefined>;
46
+ /**
47
+ * Runs a turn stage: the host's handler, then the steers waiting for the turn. Both land together,
48
+ * the host's first; an abort lands neither.
49
+ */
38
50
  export declare function applyTurnStage(args: ApplyTurnStageArgs): AsyncGenerator<TurnEvent, ApplyTurnStageResult>;
@@ -1,5 +1,5 @@
1
1
  import { throwIfAborted } from '../../../guardrails/error.js';
2
- import { injectedStageEvent, injectMessages, runStage, } from '../../stages.js';
2
+ import { injectedStageEvent, injectMessages, runStage, sanitizeInjects, stageAllowsAffordance, } from '../../stages.js';
3
3
  import { profileAllowsInject } from '../../stop.js';
4
4
  /**
5
5
  * A model call's reply joins turn history. Its text message, whose text begins at `at` in the
@@ -88,6 +88,31 @@ export function* applyStageInjects(state, stage, units, extra) {
88
88
  }
89
89
  return inject.length;
90
90
  }
91
+ /**
92
+ * The steers waiting for this turn, sanitized, when `stage` takes an inject the turn can read.
93
+ * `waiting` is what the queue gave, to mark joined once `units` land.
94
+ */
95
+ export function* steersToLand(state, profile, stage, injectWouldExceedMaxSteps) {
96
+ const waiting = state.steers?.waiting() ?? [];
97
+ if (waiting.length === 0)
98
+ return undefined;
99
+ if (!stageAllowsAffordance(stage, 'inject') || !profileAllowsInject(profile))
100
+ return undefined;
101
+ if (injectWouldExceedMaxSteps)
102
+ return undefined;
103
+ const guarded = sanitizeInjects(waiting, profile.guardrails, state.trace.root);
104
+ let next = guarded.next();
105
+ while (!next.done) {
106
+ state.allEmittedEvents.push(next.value);
107
+ yield next.value;
108
+ next = guarded.next();
109
+ }
110
+ return { waiting, units: next.value };
111
+ }
112
+ /**
113
+ * Runs a turn stage: the host's handler, then the steers waiting for the turn. Both land together,
114
+ * the host's first; an abort lands neither.
115
+ */
91
116
  export async function* applyTurnStage(args) {
92
117
  const { profile, generation, state, onStage, host, reply, replyAt, ...call } = args;
93
118
  throwIfAborted(call.signal);
@@ -108,12 +133,15 @@ export async function* applyTurnStage(args) {
108
133
  next = await run.next();
109
134
  }
110
135
  const out = next.value;
136
+ const steers = out.abort
137
+ ? undefined
138
+ : yield* steersToLand(state, profile, call.stage, call.injectWouldExceedMaxSteps);
139
+ const units = [...out.inject, ...(steers?.units ?? [])];
111
140
  // why: The model goes on after the inject, so it reads the answer it wrote before it.
112
- if (reply && injectMessages(out.inject).length > 0)
141
+ if (reply && injectMessages(units).length > 0)
113
142
  recordReply(state, reply, replyAt);
114
- return {
115
- abort: out.abort,
116
- injectCount: yield* applyStageInjects(state, call.stage, out.inject),
117
- warnings: out.warnings,
118
- };
143
+ const injectCount = yield* applyStageInjects(state, call.stage, units);
144
+ if (steers)
145
+ state.steers?.joined(steers.waiting);
146
+ return { abort: out.abort, injectCount, warnings: out.warnings };
119
147
  }
@@ -6,6 +6,7 @@ import type { SpanHandle } from '../../../observability/trace-span.js';
6
6
  import type { AgentCaller } from '../../tools/agent.js';
7
7
  import type { ToolBackgroundSupport } from '../../tools/background.js';
8
8
  import type { ToolRegistry } from '../../tools/registry.js';
9
+ import type { SteerQueue } from '../../tools/steer.js';
9
10
  import type { MediaRefused } from '../../turn-events.js';
10
11
  import type { InteractionPart, ModelBinding, Profile, ResolvedGeneration, TurnEvent, TurnHistoryMessage, TurnRequest, TurnStop, TurnToolResult } from '../../types.js';
11
12
  import type { ItemFailure } from './schema-validation.js';
@@ -25,6 +26,8 @@ interface StepExecutionState {
25
26
  agents?: AgentCaller;
26
27
  /** Absent where every tool runs inline: a nested turn, or no background service. */
27
28
  background?: ToolBackgroundSupport;
29
+ /** A detached agent call's own turn: what its host tells it while it runs. */
30
+ steers?: SteerQueue;
28
31
  trace: TurnTraceState;
29
32
  currentHistory: TurnHistoryMessage[];
30
33
  /** Where this turn begins in `currentHistory`: what came before is the conversation the host passed. */
@@ -126,6 +129,7 @@ declare function openTurnState(args: {
126
129
  allEmittedEvents?: TurnEvent[];
127
130
  agents?: AgentCaller;
128
131
  background?: ToolBackgroundSupport;
132
+ steers?: SteerQueue;
129
133
  }): StepExecutionState;
130
134
  /** The history the next model call reads: this turn alone once a retry has cut it. */
131
135
  declare function modelHistory(state: StepExecutionState): TurnHistoryMessage[];
@@ -117,6 +117,7 @@ function openTurnState(args) {
117
117
  ...(ownTools ? { ownTools } : {}),
118
118
  ...(args.agents ? { agents: args.agents } : {}),
119
119
  ...(args.background ? { background: args.background } : {}),
120
+ ...(args.steers ? { steers: args.steers } : {}),
120
121
  };
121
122
  if (profile.type === 'text') {
122
123
  if (args.request && continuesReply(args.request)) {
@@ -21,7 +21,7 @@ import { findLast } from '../../util/find-last.js';
21
21
  import { startToolTrace } from '../tool-trace.js';
22
22
  import { startCallTrace } from '../turn-trace.js';
23
23
  import { canDropMedia, dropMedia, refusedReport, restoreMedia, } from './refused-media.js';
24
- import { applyStageInjects, recordReply } from './stages.js';
24
+ import { applyStageInjects, recordReply, steersToLand } from './stages.js';
25
25
  import { modelHistory, recordStepEvent } from './state.js';
26
26
  import { inStep, runSideBySide, stepOrder } from './step-order.js';
27
27
  import { isWithheldOnBlock, StructuredDrafts, yieldProviderEvents, } from './stream.js';
@@ -619,6 +619,14 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
619
619
  if (outcome === 'gated')
620
620
  gated = true;
621
621
  }
622
+ // why: Steers land once a step, after every call's own post_tool inject, so calls side by side never land one twice.
623
+ if (!cancelled && !gated && calls.length > 0) {
624
+ const steers = yield* steersToLand(state, profile, 'post_tool', stages.injectWouldExceedMaxSteps);
625
+ if (steers) {
626
+ yield* applyStageInjects(state, 'post_tool', steers.units);
627
+ state.steers?.joined(steers.waiting);
628
+ }
629
+ }
622
630
  if (cancelled)
623
631
  return false;
624
632
  if (gated) {
@@ -63,7 +63,7 @@ export { systemLinesProblem } from './system-lines.js';
63
63
  export { systemPromptProblem } from './system-parts.js';
64
64
  export { activityLabelProblem } from './tools/activity-label.js';
65
65
  export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
66
- export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, } from './tools/background.js';
66
+ export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, ToolBackgroundSettled, ToolSteerReceipt, } from './tools/background.js';
67
67
  export { type AnsweredGate, answerGatedCall, GATE_DECISIONS, type GateAnswerRequest, type GateDecision, gateExpired, type HeldGatedCall, resolveGateTtlMs, sessionPermissionsAfterApproval, type ToolGateAuth, } from './tools/gate-answer.js';
68
68
  export type { MemoryToolExecutionOptions } from './tools/memory-execution.js';
69
69
  export { createMemoryToolExecution } from './tools/memory-execution.js';
@@ -193,3 +193,8 @@ export interface RunStageOutput extends Omit<StageApplyOutput, 'inject'> {
193
193
  }
194
194
  /** Stage events always emit, even with no handlers. */
195
195
  export declare function runStage(args: RunStageArgs): AsyncGenerator<TurnEvent, RunStageOutput>;
196
+ /**
197
+ * `units` as the profile's guardrails let them into the conversation. What they find is reported
198
+ * once; a block refuses the turn.
199
+ */
200
+ export declare function sanitizeInjects(units: readonly InjectUnit[], guardrails: Profile['guardrails'], span?: SpanHandle): Generator<TurnEvent, InjectUnit[]>;
@@ -431,8 +431,15 @@ export async function* runStage(args) {
431
431
  }
432
432
  if (applied.inject.length === 0)
433
433
  return applied;
434
+ return { ...applied, inject: yield* sanitizeInjects(applied.inject, guardrails, span) };
435
+ }
436
+ /**
437
+ * `units` as the profile's guardrails let them into the conversation. What they find is reported
438
+ * once; a block refuses the turn.
439
+ */
440
+ export function* sanitizeInjects(units, guardrails, span) {
434
441
  const reader = boundaryReader('injected', resolveGuardrailPolicy(guardrails).detect);
435
- const sanitized = applied.inject.map((unit) => ({
442
+ const sanitized = units.map((unit) => ({
436
443
  ...unit,
437
444
  messages: sanitizeHistory(unit.messages, reader),
438
445
  }));
@@ -444,5 +451,5 @@ export async function* runStage(args) {
444
451
  }
445
452
  if (found.action === 'block')
446
453
  throw requestRefused('injected');
447
- return { ...applied, inject: sanitized };
454
+ return sanitized;
448
455
  }
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import type { ToolOrigin } from '../../guardrails/types.js';
3
3
  import type { SpanHandle } from '../../observability/trace-span.js';
4
4
  import type { Profile, ProfileId, ProfileInputsSpec, TurnEvent, TurnTokens } from '../types.js';
5
+ import type { SteerQueue } from './steer.js';
5
6
  import type { AgentToolDef, AgentToolInput, AgentToolOutput, RegisteredAgentTool, RegisteredTool, ToolFailure } from './types.js';
6
7
  /** How one agent tool call settled, with what the called agent used. */
7
8
  type AgentRun = {
@@ -21,7 +22,11 @@ interface AgentCaller {
21
22
  /** The call's `execute_tool` span; the agent's turn opens under it. */
22
23
  span?: SpanHandle;
23
24
  signal?: AbortSignal;
25
+ /** A detached call's steers, which only the agent's own turn reads. */
26
+ steers?: SteerQueue;
24
27
  }): AsyncGenerator<TurnEvent, AgentRun>;
28
+ /** Whether a running call of `tool` can be steered: its agent's profile allows injects. */
29
+ takesSteers(tool: RegisteredAgentTool): boolean;
25
30
  }
26
31
  /** A call that settled without a reply; the model reads `failure`. */
27
32
  declare class AgentCallFailed extends Error {
@@ -2,8 +2,10 @@ import { z } from 'zod';
2
2
  import { labelText } from '../../guardrails/labels.js';
3
3
  import type { SpanHandle, TraceAttributes } from '../../observability/trace-span.js';
4
4
  import type { TurnEvent } from '../types.js';
5
+ import type { AgentCaller } from './agent.js';
5
6
  import { type ToolCallBase } from './events.js';
6
7
  import { type ToolExecutionCoordinator, type ToolOperationReply } from './operation.js';
8
+ import type { RegisteredTool } from './types.js';
7
9
  /** When the model gets its reply: at the hand-off, past a time, if it asks, or when the body ends. */
8
10
  export type ToolBackground = 'always' | {
9
11
  /**
@@ -28,8 +30,29 @@ export interface ToolBackgroundHandle extends ToolBackgroundCall {
28
30
  stop(reason?: string, options?: {
29
31
  graceMs?: number;
30
32
  }): void;
33
+ /**
34
+ * Tells the call's agent `text`, as a user message with `id`. It joins the agent's turn at the
35
+ * next stage that takes an inject, or never if the call settles first.
36
+ */
37
+ steer(text: string, options: {
38
+ id: string;
39
+ }): ToolSteerReceipt;
31
40
  /** Resolves when the call has settled or been marked. */
32
- done: Promise<void>;
41
+ done: Promise<ToolBackgroundSettled>;
42
+ }
43
+ /** Whether a steer waits for the agent's turn, or why it was refused at once. */
44
+ export type ToolSteerReceipt = {
45
+ queued: true;
46
+ } | {
47
+ queued: false;
48
+ reason: 'settled' | 'stopped' | ToolSteerRefusal;
49
+ };
50
+ /** Why a detached call takes no steers at all. */
51
+ export type ToolSteerRefusal = 'not_agent' | 'steering_off';
52
+ /** How a detached call ended, for its host. */
53
+ export interface ToolBackgroundSettled {
54
+ /** Ids of steers that were queued and never landed. */
55
+ unreadSteers: string[];
33
56
  }
34
57
  /** The host's service for detached calls. Without it every tool runs inline. */
35
58
  export interface ToolBackgroundService {
@@ -54,6 +77,8 @@ export interface ToolDetach {
54
77
  support: ToolBackgroundSupport;
55
78
  trace: DetachedToolTrace;
56
79
  reply: () => ToolOperationReply;
80
+ /** Why the call takes no steers; unset when its agent's turn reads them. */
81
+ refuseSteers?: ToolSteerRefusal;
57
82
  }
58
83
  /** The `ask` argument, as the model reads it. */
59
84
  export declare function backgroundField(): z.ZodOptional<z.ZodBoolean>;
@@ -66,12 +91,10 @@ export declare function splitBackground(tool: {
66
91
  };
67
92
  /** How this call detaches, or `undefined` when it runs inline. */
68
93
  export declare function planDetach(args: {
69
- tool: {
70
- background?: ToolBackground;
71
- name: string;
72
- } | undefined;
94
+ tool: RegisteredTool | undefined;
73
95
  input: unknown;
74
96
  support: ToolBackgroundSupport | undefined;
97
+ agents: AgentCaller | undefined;
75
98
  base: ToolCallBase;
76
99
  labels: Parameters<typeof labelText>[2];
77
100
  }): ToolDetach | undefined;
@@ -31,17 +31,26 @@ function detachAt(tool, input) {
31
31
  return splitBackground(tool, input).asked ? 'claim' : undefined;
32
32
  return background;
33
33
  }
34
+ /** Why a detached call of `tool` takes no steers: only an agent whose profile allows injects does. */
35
+ function steerRefusal(tool, agents) {
36
+ if (tool.type !== 'agent')
37
+ return 'not_agent';
38
+ return agents?.takesSteers(tool) ? undefined : 'steering_off';
39
+ }
34
40
  /** How this call detaches, or `undefined` when it runs inline. */
35
41
  export function planDetach(args) {
36
42
  const { tool, support, base, labels } = args;
37
- if (!tool || !support)
43
+ // why: A builtin runs at the provider, inside the model's call.
44
+ if (!tool || tool.type === 'builtin' || !support)
38
45
  return undefined;
39
46
  const at = detachAt(tool, args.input);
40
47
  if (at === undefined)
41
48
  return undefined;
49
+ const refuseSteers = steerRefusal(tool, args.agents);
42
50
  return {
43
51
  at,
44
52
  support,
53
+ ...(refuseSteers ? { refuseSteers } : {}),
45
54
  trace: support.openTrace(base.callId),
46
55
  reply: () => {
47
56
  const modelResult = {
@@ -2,11 +2,14 @@ import type { TurnEvent, TurnTokens } from '../types.js';
2
2
  import type { ToolDetach } from './background.js';
3
3
  import type { ToolExecuteSettlement } from './execute.js';
4
4
  import { type ToolExecutionCoordinator, type ToolOperationClaim, type ToolOperationIdentity, type ToolOperationOutcome } from './operation.js';
5
+ import { SteerQueue } from './steer.js';
5
6
  /** What the run gives a body: its stop signal, and how it tells that the body has ended. */
6
7
  export interface ToolCallHooks {
7
8
  signal: AbortSignal | undefined;
8
9
  bodyEnded?: () => void;
9
10
  spent?: (tokens: TurnTokens) => void;
11
+ /** A detached agent call's steers, for its agent's own turn. */
12
+ steers?: SteerQueue;
10
13
  }
11
14
  export type ToolRun = (beginBody: ((preparedInput: unknown) => Promise<ToolOperationClaim | undefined>) | undefined, hooks: ToolCallHooks) => AsyncGenerator<TurnEvent, ToolExecuteSettlement>;
12
15
  export declare function coordinateTool(coordinator: ToolExecutionCoordinator | undefined, identity: Omit<ToolOperationIdentity, 'invocationHash'>, invocation: unknown, signal: AbortSignal | undefined, run: ToolRun, authorizeReplay?: (outcome?: ToolOperationOutcome) => void | Promise<void>, detach?: ToolDetach): AsyncGenerator<TurnEvent, ToolExecuteSettlement>;
@@ -4,6 +4,7 @@ import { jsonObjectSchema } from '../json.js';
4
4
  import { failureEvent } from './events.js';
5
5
  import { formatToolFailureForModel } from './model-text.js';
6
6
  import { heldOperation, operationBroken, operationWireValue, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, unresolvedOperation, } from './operation.js';
7
+ import { SteerQueue } from './steer.js';
7
8
  class ReplayedOperation {
8
9
  outcome;
9
10
  constructor(outcome) {
@@ -176,7 +177,7 @@ class CoordinatedExecution {
176
177
  * Saves the reply, and only then gives the turn its answer. A failed save stops the body: the
177
178
  * model never read a reply, so the work must not go on.
178
179
  */
179
- async detach(detach, iterator, pending) {
180
+ async detach(detach, iterator, pending, steers) {
180
181
  const { claim, coordinator, trigger } = this;
181
182
  if (!claim || !coordinator.detach || !trigger) {
182
183
  throw operationBroken('The tool detached with no claim'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
@@ -186,6 +187,7 @@ class CoordinatedExecution {
186
187
  const handle = {
187
188
  ...this.call(),
188
189
  stop: (reason, options) => this.stop(reason, options),
190
+ steer: (text, options) => this.steer(detach, steers, text, options.id),
189
191
  done: done.promise,
190
192
  };
191
193
  try {
@@ -199,13 +201,22 @@ class CoordinatedExecution {
199
201
  throw error;
200
202
  }
201
203
  trigger.release();
202
- this.goOn(detach, iterator, pending).finally(() => done.resolve());
204
+ this.goOn(detach, iterator, pending).finally(() => done.resolve({ unreadSteers: steers.close() }));
203
205
  return reply;
204
206
  }
205
207
  call() {
206
208
  const { operationId, callId, toolId } = this.operation;
207
209
  return { operationId, callId, toolId };
208
210
  }
211
+ steer(detach, steers, text, id) {
212
+ if (this.committed || steers.isClosed)
213
+ return { queued: false, reason: 'settled' };
214
+ if (this.stopped)
215
+ return { queued: false, reason: 'stopped' };
216
+ if (detach.refuseSteers)
217
+ return { queued: false, reason: detach.refuseSteers };
218
+ return steers.push(id, text) ? { queued: true } : { queued: false, reason: 'settled' };
219
+ }
209
220
  stop(reason, options) {
210
221
  if (this.committed)
211
222
  return;
@@ -366,12 +377,23 @@ function savedResult(known) {
366
377
  return new ReplayedOperation(known.outcome);
367
378
  return undefined;
368
379
  }
380
+ /** A detaching call's trigger and steers, and the hooks its body gets from them. */
381
+ function detaching(detach, signal) {
382
+ const trigger = new DetachTrigger(detach.at, signal);
383
+ const steers = new SteerQueue();
384
+ const hooks = {
385
+ bodyEnded: trigger.bodyEnded,
386
+ ...(detach.refuseSteers ? {} : { steers }),
387
+ };
388
+ return { plan: detach, trigger, steers, hooks };
389
+ }
369
390
  export async function* coordinateTool(coordinator, identity, invocation, signal, run, authorizeReplay, detach) {
370
391
  if (!coordinator)
371
392
  return yield* run(undefined, { signal });
372
393
  const accepted = jsonObjectSchema.parse(operationWireValue(invocation));
373
394
  const operation = { ...identity, invocationHash: await toolInvocationHash(accepted) };
374
- const trigger = detach ? new DetachTrigger(detach.at, signal) : undefined;
395
+ const detached = detach ? detaching(detach, signal) : undefined;
396
+ const trigger = detached?.trigger;
375
397
  const callSignal = trigger ? trigger.signal : signal;
376
398
  const execution = new CoordinatedExecution(coordinator, operation, accepted, callSignal, trigger);
377
399
  throwIfAborted(signal);
@@ -389,7 +411,7 @@ export async function* coordinateTool(coordinator, identity, invocation, signal,
389
411
  const iterator = run((input) => execution.beginBody(input), {
390
412
  signal: callSignal,
391
413
  spent: (tokens) => execution.spend(tokens),
392
- ...(trigger ? { bodyEnded: trigger.bodyEnded } : {}),
414
+ ...detached?.hooks,
393
415
  });
394
416
  let handedOff = false;
395
417
  try {
@@ -397,9 +419,9 @@ export async function* coordinateTool(coordinator, identity, invocation, signal,
397
419
  for (;;) {
398
420
  const next = await (trigger ? Promise.race([pending, trigger.fired]) : pending);
399
421
  if (next === FIRED) {
400
- if (!detach)
422
+ if (!detached)
401
423
  throw operationBroken('The tool detached with no plan'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
402
- const reply = await execution.detach(detach, iterator, pending);
424
+ const reply = await execution.detach(detached.plan, iterator, pending, detached.steers);
403
425
  handedOff = true;
404
426
  yield reply.event;
405
427
  return { ...reply.replay };
@@ -855,6 +855,7 @@ export async function* executeRegisteredTool(args) {
855
855
  input: args.input,
856
856
  support: args.background,
857
857
  base: { name: args.name, callId: args.callId, operationId },
858
+ agents: args.agents,
858
859
  labels: args.profile.labels,
859
860
  });
860
861
  return yield* coordinateTool(args.execution, {
@@ -1089,6 +1090,7 @@ async function* executeAgentTool(args) {
1089
1090
  caller: handlerCtx.profile,
1090
1091
  ...(span ? { span } : {}),
1091
1092
  ...(handlerCtx.signal ? { signal: handlerCtx.signal } : {}),
1093
+ ...(args.stages?.steers ? { steers: args.stages.steers } : {}),
1092
1094
  });
1093
1095
  // why: A retry throws away the reply drafted so far; the drafts stop there, and the output arrives whole.
1094
1096
  let retried = false;
@@ -227,10 +227,12 @@ async function* invokeTraced(registry, request, callId, openSpan, failBeforeTool
227
227
  function runCall(registry, request, profile, snapshot, callId, openSpan, failBeforeTool, canaries, background, step) {
228
228
  const operationId = request.operationId ?? crypto.randomUUID();
229
229
  const tool = registry.tools.get(request.name);
230
+ const agents = invokeAgentCaller(registry, request, canaries);
230
231
  const detach = planDetach({
231
- tool: tool?.type === 'builtin' ? undefined : tool,
232
+ tool,
232
233
  input: request.input,
233
234
  support: background,
235
+ agents,
234
236
  base: { name: request.name, callId, operationId },
235
237
  labels: profile.labels,
236
238
  });
@@ -248,10 +250,11 @@ function runCall(registry, request, profile, snapshot, callId, openSpan, failBef
248
250
  turnInput: request.turnInput,
249
251
  promoted: request.promoted,
250
252
  },
251
- }, request.signal, (beginBody, hooks) => invokePrepared(registry, { ...request, ...(hooks.signal ? { signal: hooks.signal } : {}) }, profile, snapshot, callId, detach?.trace.open ?? openSpan, failBeforeTool, canaries, beginBody, {
253
+ }, request.signal, (beginBody, hooks) => invokePrepared(registry, { ...request, ...(hooks.signal ? { signal: hooks.signal } : {}) }, profile, snapshot, callId, detach?.trace.open ?? openSpan, failBeforeTool, agents, beginBody, {
252
254
  ...step,
253
255
  ...(hooks.bodyEnded ? { bodyEnded: hooks.bodyEnded } : {}),
254
256
  ...(hooks.spent ? { spent: hooks.spent } : {}),
257
+ ...(hooks.steers ? { steers: hooks.steers } : {}),
255
258
  }), (outcome) => authorizeToolReplay({
256
259
  outcome,
257
260
  tools: registry.tools,
@@ -261,7 +264,7 @@ function runCall(registry, request, profile, snapshot, callId, openSpan, failBef
261
264
  snapshot,
262
265
  }), detach);
263
266
  }
264
- async function* invokePrepared(registry, request, profile, snapshot, callId, openSpan, failBeforeTool, canaries, beginBody, step) {
267
+ async function* invokePrepared(registry, request, profile, snapshot, callId, openSpan, failBeforeTool, agents, beginBody, step) {
265
268
  if (request.promoted?.length) {
266
269
  const { failure } = promoteLoadedTools(registry.tools, snapshot, request.promoted, profile);
267
270
  if (failure) {
@@ -279,7 +282,7 @@ async function* invokePrepared(registry, request, profile, snapshot, callId, ope
279
282
  return yield* executeRegisteredTool({
280
283
  tools: registry.tools,
281
284
  beginBody,
282
- agents: invokeAgentCaller(registry, request, canaries),
285
+ agents,
283
286
  profile,
284
287
  name: request.name,
285
288
  input: request.input,
@@ -5,6 +5,7 @@ import type { ToolAccess } from '../schema.js';
5
5
  import { type InjectUnit, type StageHandler, type StageResult, type StepCall } from '../stages.js';
6
6
  import type { Profile, TurnEvent, TurnHistoryMessage, TurnTokens } from '../types.js';
7
7
  import { type ToolCallBase } from './events.js';
8
+ import type { SteerQueue } from './steer.js';
8
9
  import type { ModelToolResult, ToolContext, ToolFailure, ToolGate, ToolLabels } from './types.js';
9
10
  /** How a call's wait for other calls in its step ended: they settled, or the wait cannot end. */
10
11
  export type StepWaitOutcome = {
@@ -38,6 +39,8 @@ export interface ToolStageSupport {
38
39
  bodyEnded?: () => void;
39
40
  /** Told what an agent tool's turn has spent so far. */
40
41
  spent?: (tokens: TurnTokens) => void;
42
+ /** A detached agent call's steers, which its agent's own turn reads. */
43
+ steers?: SteerQueue;
41
44
  }
42
45
  export type PreBodyOutcome = {
43
46
  ok: true;
@@ -0,0 +1,21 @@
1
+ import type { InjectUnit } from '../stages.js';
2
+ /**
3
+ * The steers a detached call was given and its agent's turn has not read yet. The call's handle
4
+ * writes to it; its agent's turn lands what waits at a stage that takes an inject.
5
+ *
6
+ * invariant: A steer leaves the queue only when its message has joined the turn's history, or when
7
+ * the call settles and the queue closes.
8
+ */
9
+ export declare class SteerQueue {
10
+ private units;
11
+ private closed;
12
+ get isClosed(): boolean;
13
+ /** Queues `text` as a user message with `id`; false once the queue is closed. */
14
+ push(id: string, text: string): boolean;
15
+ /** What waits now, in the order it was given. */
16
+ waiting(): readonly InjectUnit[];
17
+ /** `landed`, as `waiting` gave them, have joined the turn's history. */
18
+ joined(landed: readonly InjectUnit[]): void;
19
+ /** Closes the queue and gives the ids of the steers that never landed. */
20
+ close(): string[];
21
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The steers a detached call was given and its agent's turn has not read yet. The call's handle
3
+ * writes to it; its agent's turn lands what waits at a stage that takes an inject.
4
+ *
5
+ * invariant: A steer leaves the queue only when its message has joined the turn's history, or when
6
+ * the call settles and the queue closes.
7
+ */
8
+ export class SteerQueue {
9
+ units = [];
10
+ closed = false;
11
+ get isClosed() {
12
+ return this.closed;
13
+ }
14
+ /** Queues `text` as a user message with `id`; false once the queue is closed. */
15
+ push(id, text) {
16
+ if (this.closed)
17
+ return false;
18
+ this.units.push({ id, messages: [{ role: 'user', content: text }] });
19
+ return true;
20
+ }
21
+ /** What waits now, in the order it was given. */
22
+ waiting() {
23
+ return [...this.units];
24
+ }
25
+ /** `landed`, as `waiting` gave them, have joined the turn's history. */
26
+ joined(landed) {
27
+ this.units = this.units.filter((unit) => !landed.includes(unit));
28
+ }
29
+ /** Closes the queue and gives the ids of the steers that never landed. */
30
+ close() {
31
+ this.closed = true;
32
+ const unread = this.units.flatMap((unit) => (unit.id === undefined ? [] : [unit.id]));
33
+ this.units = [];
34
+ return unread;
35
+ }
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.871.gea9bbcc",
3
+ "version": "0.3.4",
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",