@theoremjs/agents 0.3.5-next.912.g25d311a → 0.3.5-next.915.ge040f25

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.
@@ -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) {
@@ -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. */
@@ -239,6 +239,8 @@ export const STAGE_APPLY_WARNING_CODES = [
239
239
  'label_failed_invalid',
240
240
  'abort_invalid',
241
241
  'wait_for_invalid',
242
+ 'end_not_allowed',
243
+ 'end_invalid',
242
244
  'unknown_field',
243
245
  'result_invalid',
244
246
  ];
@@ -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, or have it wait for other calls in its step.
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;
@@ -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, or have it wait for other calls in its step.
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] } };
@@ -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 abort has nothing to reach.
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. */
@@ -358,11 +358,12 @@ async function* withFetchedImages(base, result, images, outputRaw) {
358
358
  : { finding: result.finding + note }),
359
359
  };
360
360
  }
361
- /** 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. */
362
362
  function stageSettlement(post) {
363
363
  return {
364
364
  ...(post?.abort !== undefined ? { aborted: post.abort } : {}),
365
365
  ...(post?.inject.length ? { pendingInject: post.inject } : {}),
366
+ ...(post?.end ? { ended: true } : {}),
366
367
  };
367
368
  }
368
369
  function settleToolFailure(guard, base, failure, stages, args) {
@@ -56,6 +56,7 @@ export interface ToolOperationOutcome {
56
56
  reason?: string;
57
57
  };
58
58
  pendingInject?: InjectUnit[];
59
+ ended?: true;
59
60
  };
60
61
  }
61
62
  export type ToolOperationUncertainty = 'execution_interrupted' | 'settlement_write_failed' | 'worker_lost';
@@ -86,6 +86,7 @@ export const toolOperationOutcomeSchema = z.strictObject({
86
86
  released: z.number().int().nonnegative().optional(),
87
87
  }))
88
88
  .optional(),
89
+ ended: z.literal(true).optional(),
89
90
  }),
90
91
  });
91
92
  export function operationWireValue(value) {
@@ -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
  }
@@ -1258,7 +1258,8 @@ export interface TurnWiring {
1258
1258
  * The turn the application runs, from the one it is given: the profile, the input with the
1259
1259
  * conversation's history, and the application's context as `host`. Set what the application
1260
1260
  * sets per turn, such as `system`, `credentials`, `onStage`, `onEvent`, `onAgentCall`, `path`
1261
- * and `metadata`. Text, image and speech turns run through it.
1261
+ * and `metadata`, and the `execution` and `background` that keep its late tool calls. Text,
1262
+ * image and speech turns run through it.
1262
1263
  */
1263
1264
  prepare?: (turn: NormalizedTurnRequest) => TurnRequest | Promise<TurnRequest>;
1264
1265
  }
@@ -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.912.g25d311a",
3
+ "version": "0.3.5-next.915.ge040f25",
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",