@theoremjs/agents 0.3.4-next.600.gb15be9a → 0.3.4-next.604.ge4d5866

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';
@@ -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';
@@ -12,10 +12,6 @@ export declare function fillActivityLabel(template: LabelTemplate | undefined, v
12
12
  input: unknown;
13
13
  output?: unknown;
14
14
  }): string | undefined;
15
- /**
16
- * Why a label can't be used with these JSON schemas, as a sentence for its author, or `undefined`
17
- * when it can. Pass `output` for a Done label. A list must end on a line that always fits.
18
- */
19
15
  export declare function activityLabelProblem(template: LabelTemplate, schemas: {
20
16
  input: unknown;
21
17
  output?: unknown;
@@ -428,7 +428,41 @@ function listProblem(entries) {
428
428
  * Why a label can't be used with these JSON schemas, as a sentence for its author, or `undefined`
429
429
  * when it can. Pass `output` for a Done label. A list must end on a line that always fits.
430
430
  */
431
+ /** The schemas' outputs, when a check names none. */
432
+ const NO_OUTPUT = {};
433
+ /** Answers by input schema, then output schema, then template: a schema object is read, never changed. */
434
+ const answered = new WeakMap();
435
+ /** The answers already given for these schemas, when both are objects that can key them. */
436
+ function answersFor(schemas) {
437
+ const { input } = schemas;
438
+ const output = 'output' in schemas ? schemas.output : NO_OUTPUT;
439
+ if (typeof input !== 'object' || input === null)
440
+ return undefined;
441
+ if (typeof output !== 'object' || output === null)
442
+ return undefined;
443
+ let byOutput = answered.get(input);
444
+ if (!byOutput) {
445
+ byOutput = new WeakMap();
446
+ answered.set(input, byOutput);
447
+ }
448
+ let byTemplate = byOutput.get(output);
449
+ if (!byTemplate) {
450
+ byTemplate = new Map();
451
+ byOutput.set(output, byTemplate);
452
+ }
453
+ return byTemplate;
454
+ }
455
+ // why: A studio compile checks every tool's labels for every agent that uses the tool, again on each edit that settles.
431
456
  export function activityLabelProblem(template, schemas) {
457
+ const answers = answersFor(schemas);
458
+ const key = JSON.stringify(template);
459
+ if (answers?.has(key))
460
+ return answers.get(key);
461
+ const problem = templateProblem(template, schemas);
462
+ answers?.set(key, problem);
463
+ return problem;
464
+ }
465
+ function templateProblem(template, schemas) {
432
466
  const sides = 'output' in schemas ? ['input', 'output'] : ['input'];
433
467
  const listed = typeof template !== 'string';
434
468
  const entries = entriesOf(template);
@@ -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;
@@ -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);
@@ -4,12 +4,30 @@ import { activityLabelProblem } from './activity-label.js';
4
4
  import { agentToolInputFor, agentToolOutput, agentToolProfile, normalizeAgent } from './agent.js';
5
5
  import { createMcpSessionCache } from './mcp-sessions.js';
6
6
  import { pageAnswerHandler } from './page-answer.js';
7
- import { assertFixedEndpointOrigin, jsonSchemaFromZod, validateToolSchema } from './schema.js';
7
+ import { assertFixedEndpointOrigin, jsonSchemaFromZod, validateToolSchema, } from './schema.js';
8
+ /** Each zod pair's JSON Schemas, as converted and checked: a zod schema is never changed. */
9
+ const converted = new WeakMap();
10
+ /** The pair's JSON Schemas, converted and checked once; registering the same schemas again reads them back. */
11
+ function checkedSchemas(input, output) {
12
+ let byOutput = converted.get(input);
13
+ if (!byOutput) {
14
+ byOutput = new WeakMap();
15
+ converted.set(input, byOutput);
16
+ }
17
+ let schemas = byOutput.get(output);
18
+ if (!schemas) {
19
+ const inputSchema = jsonSchemaFromZod(input, 'input');
20
+ validateToolSchema(inputSchema, 'input');
21
+ const outputSchema = jsonSchemaFromZod(output, 'output');
22
+ validateToolSchema(outputSchema, 'output');
23
+ schemas = { inputSchema, outputSchema };
24
+ byOutput.set(output, schemas);
25
+ }
26
+ return schemas;
27
+ }
8
28
  function schemasFromZod(def) {
9
- const inputSchema = jsonSchemaFromZod(def.input, 'input');
10
- validateToolSchema(inputSchema, 'input');
11
- const outputSchema = jsonSchemaFromZod(def.output, 'output');
12
- validateToolSchema(outputSchema, 'output');
29
+ // why: A studio compile registers each tool once for every agent that uses it, again on each edit that settles.
30
+ const { inputSchema, outputSchema } = checkedSchemas(def.input, def.output);
13
31
  const labels = {
14
32
  activity: { input: inputSchema },
15
33
  activityPast: { input: inputSchema, output: outputSchema },
@@ -23,7 +41,8 @@ function schemasFromZod(def) {
23
41
  throw new TheoremError('config', `Tool "${def.name}" ${field} label: ${problem}`);
24
42
  }
25
43
  }
26
- return { inputSchema, outputSchema };
44
+ // invariant: Each registration gets its own copy, so nothing a tool does to its schemas reaches another.
45
+ return { inputSchema: structuredClone(inputSchema), outputSchema: structuredClone(outputSchema) };
27
46
  }
28
47
  /** The person is told which service they sign in to; the tool's builder names it, never the model or the server. */
29
48
  function assertAuthService(name, auth) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.600.gb15be9a",
3
+ "version": "0.3.4-next.604.ge4d5866",
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",