@theoremjs/agents 0.3.4-next.602.gb5a7fab → 0.3.4-next.606.g8936f75

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
@@ -273,7 +273,7 @@ Each tool call gets an operation ID from the kernel, `ToolContext.operationId`.
273
273
  Pass it as `execution` on the `TurnRequest`. A tool that the page answers also needs `pageExecution`, a `PageToolExecution`.
274
274
  Profile JSON and provider events cannot supply either one.
275
275
 
276
- - **One process.** `createMemoryToolExecution` keeps claims and outcomes in memory. It refuses new operations after `maxOperations` (256 by default). Nothing survives a restart.
276
+ - **One process.** `createMemoryToolExecution` keeps claims and outcomes in memory. It refuses new operations after `maxOperations`, when you set it. Nothing survives a restart.
277
277
  - **Several workers.** Write a coordinator over durable shared storage. The `@theoremjs/web` server handler builds one from its session store.
278
278
  - **Replay.** Before you deliver a saved outcome on your own path, call `authorizeToolReplay`. It checks that the call is still allowed and may still be shown, and it runs no handler.
279
279
 
@@ -463,7 +463,7 @@ Named exports from the root barrel (same symbols hosts get from `@theoremjs/agen
463
463
  | Scope | `KernelScope`, `createKernelScope`, `defaultKernelScope`, `KernelRegistry`, `createKernelRegistry` |
464
464
  | Profiles | `ProfileDefinition`, `ProfileDefinitionBase`, `TextProfileDefinition`, `ImageProfileDefinition`, `SpeechProfileDefinition`, `LiveProfileDefinition`, `HostProfileDefinition`, `DecisionProfileDefinition`, `EmbeddingProfileDefinition`, `ProfileRegistry`, `createProfileRegistry`, `clearProfiles`, `defineProfile`, `getProfile`, `hasProfile`, `listProfiles`, `registerProfile`, `registerProfiles`, `projectProfile`, `resolveTurn`, `pickModel` |
465
465
  | Tools | `ToolContext`, `GateReference`, `gateReferenceSchema`, `ToolRegistry`, `createToolRegistry`, `registerTool`, `registerTools`, `invokeTool`, `invokeToolStep`, `runTool`, `runToolStep`, `SettledToolCall`, `ToolCallResult`, `ToolStepCallResult`, `GATE_DECISIONS`, `GateDecision`, `askUserTool`, `registerHarnessTools`, `getTool`, `hasTool`, `requireTool`, `listTools`, `resetTools`, `formatToolResult`, `prepareTurnToolSnapshot`, `buildHttpToolTarget`, `executeHttpTool`, `executeMcpTool`, `parseMcpRpcResponse`, `isUnsupportedMcpProtocolError`, `MCP_PROTOCOL_VERSIONS`, `mcpRequestMeta`, `McpProtocolVersion`, `resolveToolAuth`, `credentialPlacement`, `withCredentialQuery`, `CredentialQuery`, `uncheckedOutput`, `UncheckedOutput`, `McpRpcResponse`, `ModelToolResult`, `PageAnswer` |
466
- | Tool execution | `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `DEFAULT_MAX_OUTCOME_BYTES`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
466
+ | Tool execution | `ToolExecutionCoordinator`, `createMemoryToolExecution`, `MemoryToolExecutionOptions`, `authorizeToolReplay`, `BeginToolOperationResult`, `ToolOperationClaim`, `ToolOperationIdentity`, `ToolOperationOutcome`, `ToolOperationUncertainty`, `toolOperationOutcomeSchema`, `SavedToolInvocation`, `savedToolInvocationSchema`, `toolInvocationHash`, `TerminalToolEvent`, `PageToolDispatch`, `PageToolExecution` |
467
467
  | Structured | `SchemaRegistry`, `createSchemaRegistry`, `getStructured`, `registerStructured` |
468
468
  | Stop / resume | `ProfileTurnBehaviourSpec`, `MediaTurnBehaviourSpec`, `ProfileTurnResumptionSpec`, `TurnContinueFrom`, `TurnStop`, `TurnStopKind`, `ContinueStopKind`, `StepLimitMode`, `CONTINUE_STOP_KINDS`, `AUTO_CONTINUE_DELAY_MS`, `DEFAULT_ALLOW_CONTINUE`, `DEFAULT_AUTO_CONTINUE`, `GenerationStopError`, `isContinueStopKind`, `isGenerationStopError`, `isResumeableStop`, `isUserCancelledStop`, `profileAllowsSteering`, `profileAllowsInject`, `profileTurnResumption`, `shouldAutoContinue`, `turnStopFromClientStreamEnd`, `turnStopFromInteractionStatus`, `turnStopFromOpenAiFinishReason` |
469
469
  | Stages (target foundation) | `TURN_STAGES`, `TURN_INJECT_STAGES`, `STAGE_AFFORDANCES`, `STAGE_AFFORDANCE_MATRIX`, `TOOL_GATE_KINDS`, `AWAITING_USER_INPUT_KINDS`, `AWAITING_USER_INPUT_STATUS`, `applyStageResult`, `awaitingUserInputSchema`, `toolGateSchema`, `isTurnStage`, `isTurnInjectStage`, `isToolGateKind`, `isAwaitingUserInput`, `stageAllowsAffordance`, `stageEventFields`, `profileAllowsInject`, `StageAffordance`, `StageContext`, `StageResult`, `StageMutate`, `StageHandler`, `StageApplyInput`, `StageApplyOutput`, `StageApplyWarning`, `StageApplyWarningCode`, `StageEventExtra`, `AwaitingUserInput`, `ToolGate` — contract [`docs/contracts/stages.md`](https://github.com/masudl-hub/theoremai/blob/main/docs/contracts/stages.md) |
package/esm/mod.d.ts CHANGED
@@ -70,7 +70,7 @@ export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.j
70
70
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './src/kernel/tools/mod.js';
71
71
  export { askUserTool, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
72
72
  export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
73
- export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
73
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
74
74
  export type { SettledToolCall, ToolCallResult, ToolStepCallResult, } from './src/kernel/tools/run.js';
75
75
  export type { ModelToolResult, PageAnswer, ToolContext } from './src/kernel/tools/types.js';
76
76
  export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
package/esm/mod.js CHANGED
@@ -43,7 +43,7 @@ export { authorizeToolReplay } from './src/kernel/tools/execute.js';
43
43
  export { GATE_DECISIONS } from './src/kernel/tools/gate-answer.js';
44
44
  export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
45
45
  export { askUserTool, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
46
- export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
46
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
47
47
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
48
48
  export { buildRecord, clearTraceDestinations, contentOf, getTraceDestination, inlineContent, isTraceSink, listTraceDestinationIds, memorySink, noopSink, readTraceparent, registerTraceDestination, requireTraceDestination, resolveObservabilityPolicy, resolveTraceWriter, startTrace, TRACE_ATTRIBUTE_GROUPS, TRACE_FIELDS, TRACE_SPAN_TYPES, TRACE_STATUS, toOtlpJson, traceAttributeMeta, traceBytes, traceContent, traceEventAttributeMeta, traceEventMeta, traceJson, traceRecordSchema, traceSpanMeta, writeTrace, } from './src/observability/mod.js';
49
49
  export * from './src/providers/mod.js';
@@ -11,8 +11,9 @@ export interface RunSessionOptions extends ProviderHostOptions {
11
11
  /** The host's keys by slot; the session uses the slots its profile names. */
12
12
  vault?: KeyVault;
13
13
  /**
14
- * Milliseconds a gated call waits for its decision (default 30 minutes). A later decision is
15
- * refused (`session.gate_expired`), and the model reads the call as abandoned.
14
+ * Milliseconds a gated call waits for its decision. A later decision is refused
15
+ * (`session.gate_expired`), and the model reads the call as abandoned. Unset, the call waits
16
+ * until it is decided or the session closes.
16
17
  */
17
18
  gateTtlMs?: number;
18
19
  /**
@@ -437,8 +437,8 @@ function buildLiveSession(args) {
437
437
  };
438
438
  /**
439
439
  * A call that ran into `gate`. A sign-in gate this session answers at once tells the model its
440
- * pending note and releases the call; a call already released stays released. Either waits
441
- * `gateTtlMs` for its outcome. False: the call is not released, and the caller holds it.
440
+ * pending note and releases the call; a call already released stays released. Either waits for
441
+ * its outcome, for `gateTtlMs` when it is set. False: the call is not released, and the caller holds it.
442
442
  */
443
443
  const releaseGated = (callId, held, wasReleased, gate, readBack) => {
444
444
  const answersNow = signInGate === 'answer' && gate.kind === 'auth' && readBack !== undefined;
@@ -448,7 +448,10 @@ function buildLiveSession(args) {
448
448
  answerModel(callId, held, readBack);
449
449
  clearTimeout(held.lapse);
450
450
  held.state = { gate, createdAt: Date.now(), released: true };
451
- held.lapse = setTimeout(() => lapseReleased(callId, held), gateTtlMs);
451
+ held.lapse =
452
+ gateTtlMs === undefined
453
+ ? undefined
454
+ : setTimeout(() => lapseReleased(callId, held), gateTtlMs);
452
455
  return true;
453
456
  };
454
457
  /**
@@ -66,7 +66,7 @@ export { createMemoryToolExecution } from './tools/memory-execution.js';
66
66
  export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './tools/mod.js';
67
67
  export { askUserTool, authorizeToolReplay, coerceToolResultParts, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, withCredentialQuery, } from './tools/mod.js';
68
68
  export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './tools/operation.js';
69
- export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
69
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
70
70
  export { jsonSchemaFromZod } from './tools/schema.js';
71
71
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
72
72
  export type { ModelToolResult, PageAnswer, ToolAuthConfig, ToolContext, ToolLabels, } from './tools/types.js';
@@ -39,7 +39,7 @@ export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
39
39
  export { answerGatedCall, GATE_DECISIONS, gateExpired, resolveGateTtlMs, sessionPermissionsAfterApproval, } from './tools/gate-answer.js';
40
40
  export { createMemoryToolExecution } from './tools/memory-execution.js';
41
41
  export { askUserTool, authorizeToolReplay, coerceToolResultParts, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, executeRegisteredTool, formatToolResult, isUnsupportedMcpProtocolError, leanToolResultData, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, projectForModel, registerHarnessTools, resolveToolAuth, withCredentialQuery, } from './tools/mod.js';
42
- export { DEFAULT_MAX_OUTCOME_BYTES, savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
42
+ export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './tools/operation.js';
43
43
  export { jsonSchemaFromZod } from './tools/schema.js';
44
44
  export { CredentialRefusedError } from './tools/signed-in-fetch.js';
45
45
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './turn-events.js';
@@ -95,8 +95,10 @@ class CoordinatedExecution {
95
95
  * a failure that names its size instead, and the model reads that failure, not the result.
96
96
  */
97
97
  withinLimit(outcome) {
98
- const bytes = new TextEncoder().encode(JSON.stringify(outcome)).byteLength;
99
98
  const limit = this.coordinator.maxOutcomeBytes;
99
+ if (limit === undefined)
100
+ return outcome;
101
+ const bytes = new TextEncoder().encode(JSON.stringify(outcome)).byteLength;
100
102
  if (bytes <= limit)
101
103
  return outcome;
102
104
  const { name, callId, operationId } = outcome.event.tool;
@@ -4,10 +4,13 @@ import type { ToolAuthChallenge } from '../turn-events.js';
4
4
  import type { InvokeToolResume, PageAnswer } from './types.js';
5
5
  /** What a sign-in gate asks for, minus the challenge's OAuth details. */
6
6
  export type ToolGateAuth = Pick<ToolAuthChallenge, 'slot' | 'authType' | 'service'>;
7
- /** A bad value is refused when `owner` is built, not when a gate expires. */
8
- export declare function resolveGateTtlMs(owner: string, gateTtlMs: number | undefined): number;
9
- /** True when the gate has waited as long as its time limit. */
10
- export declare function gateExpired(createdAt: number, now: number, ttlMs: number): boolean;
7
+ /**
8
+ * A bad value is refused when `owner` is built, not when a gate expires. Unset, a gate waits until
9
+ * it is answered.
10
+ */
11
+ export declare function resolveGateTtlMs(owner: string, gateTtlMs: number | undefined): number | undefined;
12
+ /** True when the gate has waited as long as its time limit. With no limit, never. */
13
+ export declare function gateExpired(createdAt: number, now: number, ttlMs: number | undefined): boolean;
11
14
  /** How a user can answer a tool gate: approve it, deny it, or walk away. */
12
15
  export declare const GATE_DECISIONS: readonly ["approve", "deny", "abandon"];
13
16
  /** One of {@linkcode GATE_DECISIONS}. */
@@ -1,17 +1,20 @@
1
1
  import { TheoremError } from '../../guardrails/error.js';
2
2
  import { credentialForSignInGate } from '../auth/typed-secret.js';
3
- const DEFAULT_GATE_TTL_MS = 30 * 60 * 1000;
4
- /** A bad value is refused when `owner` is built, not when a gate expires. */
3
+ /**
4
+ * A bad value is refused when `owner` is built, not when a gate expires. Unset, a gate waits until
5
+ * it is answered.
6
+ */
5
7
  export function resolveGateTtlMs(owner, gateTtlMs) {
6
- const ttl = gateTtlMs ?? DEFAULT_GATE_TTL_MS;
7
- if (!Number.isFinite(ttl) || ttl <= 0) {
8
- throw new TheoremError('config', `${owner} gateTtlMs must be a positive number of milliseconds; got ${ttl}.`);
8
+ if (gateTtlMs === undefined)
9
+ return undefined;
10
+ if (!Number.isFinite(gateTtlMs) || gateTtlMs <= 0) {
11
+ throw new TheoremError('config', `${owner} gateTtlMs must be a positive number of milliseconds; got ${gateTtlMs}.`);
9
12
  }
10
- return ttl;
13
+ return gateTtlMs;
11
14
  }
12
- /** True when the gate has waited as long as its time limit. */
15
+ /** True when the gate has waited as long as its time limit. With no limit, never. */
13
16
  export function gateExpired(createdAt, now, ttlMs) {
14
- return now - createdAt >= ttlMs;
17
+ return ttlMs !== undefined && now - createdAt >= ttlMs;
15
18
  }
16
19
  /** How a user can answer a tool gate: approve it, deny it, or walk away. */
17
20
  export const GATE_DECISIONS = ['approve', 'deny', 'abandon'];
@@ -1,8 +1,8 @@
1
1
  import { type ToolExecutionCoordinator } from './operation.js';
2
2
  export interface MemoryToolExecutionOptions {
3
- /** The most operations it holds. A full coordinator refuses dispatch and keeps what it has. */
3
+ /** The most operations it holds. Unset, it holds any number. A full coordinator refuses dispatch and keeps what it has. */
4
4
  maxOperations?: number;
5
- /** The most bytes it keeps for one tool result. Default {@linkcode DEFAULT_MAX_OUTCOME_BYTES}. */
5
+ /** The most bytes it keeps for one tool result. Unset, it keeps any size. */
6
6
  maxOutcomeBytes?: number;
7
7
  }
8
8
  /**
@@ -1,14 +1,12 @@
1
1
  import { TheoremError } from '../../guardrails/error.js';
2
- import { DEFAULT_MAX_OUTCOME_BYTES, operationBroken, } from './operation.js';
3
- /** How many operations a memory coordinator tracks before it refuses new ones. */
4
- const DEFAULT_MEMORY_EXECUTION_LIMIT = 256;
2
+ import { operationBroken, } from './operation.js';
5
3
  /**
6
4
  * A coordinator that keeps claims and outcomes in process memory.
7
5
  * Use one per turn or per process when nothing needs to resume after a restart.
8
6
  * A host that resumes across requests or workers supplies its own `ToolExecutionCoordinator`.
9
7
  */
10
8
  export function createMemoryToolExecution(options = {}) {
11
- const limit = options.maxOperations ?? DEFAULT_MEMORY_EXECUTION_LIMIT;
9
+ const limit = options.maxOperations ?? Number.POSITIVE_INFINITY;
12
10
  const records = new Map();
13
11
  // invariant: callId and operationId never contain a NUL byte, so the joined key is unambiguous.
14
12
  const keyOf = (operation) => `${operation.callId}\0${operation.operationId}`;
@@ -27,7 +25,7 @@ export function createMemoryToolExecution(options = {}) {
27
25
  const full = () => new TheoremError('config', `The memory tool coordinator holds its maxOperations of ${limit}`);
28
26
  const notHeld = () => operationBroken('The memory tool coordinator holds no running claim for this token'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
29
27
  return {
30
- maxOutcomeBytes: options.maxOutcomeBytes ?? DEFAULT_MAX_OUTCOME_BYTES,
28
+ ...(options.maxOutcomeBytes === undefined ? {} : { maxOutcomeBytes: options.maxOutcomeBytes }),
31
29
  lookup: (operation) => Promise.resolve(known(operation)),
32
30
  begin: (operation) => {
33
31
  const earlier = known(operation);
@@ -58,17 +58,13 @@ export type BeginToolOperationResult = {
58
58
  } | {
59
59
  kind: 'uncertain';
60
60
  };
61
- /**
62
- * The default most bytes a coordinator keeps for one tool result, as UTF-8 JSON. A result that
63
- * size is about 250,000 tokens, already more than one tool result should give a model.
64
- */
65
- export declare const DEFAULT_MAX_OUTCOME_BYTES: number;
66
61
  export interface ToolExecutionCoordinator {
67
62
  /**
68
- * The most bytes, as UTF-8 JSON, it keeps for one outcome. The kernel settles a larger result as
69
- * the call's `result_too_large` failure, so a call that ran is never left unresolved by its size.
63
+ * The most bytes, as UTF-8 JSON, it keeps for one outcome. Unset, it keeps any size. The kernel
64
+ * settles a larger result as the call's `result_too_large` failure, so a call that ran is never
65
+ * left unresolved by its size.
70
66
  */
71
- readonly maxOutcomeBytes: number;
67
+ readonly maxOutcomeBytes?: number;
72
68
  lookup(operation: ToolOperationIdentity): Promise<Exclude<BeginToolOperationResult, {
73
69
  kind: 'acquired';
74
70
  }> | undefined>;
@@ -7,11 +7,6 @@ export const savedToolInvocationSchema = z.strictObject({
7
7
  accepted: jsonObjectSchema,
8
8
  preparedInput: jsonValueSchema,
9
9
  });
10
- /**
11
- * The default most bytes a coordinator keeps for one tool result, as UTF-8 JSON. A result that
12
- * size is about 250,000 tokens, already more than one tool result should give a model.
13
- */
14
- export const DEFAULT_MAX_OUTCOME_BYTES = 1024 * 1024;
15
10
  /** A coordinator, a page dispatch or the kernel broke the tool-operation contract. */
16
11
  export function operationBroken(reason) {
17
12
  return new TheoremError('internal', reason);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.602.gb5a7fab",
3
+ "version": "0.3.4-next.606.g8936f75",
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",