operon-agents-core 0.1.0-alpha.12 → 0.1.0-alpha.13

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.
@@ -653,6 +653,7 @@ class Engine {
653
653
  tools: toolset.tools,
654
654
  deferredToolNames: toolset.deferredToolNames,
655
655
  deferEnabled: toolset.deferEnabled,
656
+ serverToolSearch: toolset.serverToolSearch,
656
657
  onToolsPrepared: (tools) => { permissionTools = tools; },
657
658
  refreshTools: () => buildRunTools(current, state, (agent, childContext, childState, childResume) => this.run(agent, childContext, childState, childResume), model),
658
659
  hooks,
@@ -20,6 +20,8 @@ export interface RunToolset {
20
20
  readonly tools: readonly Tool[];
21
21
  readonly deferredToolNames: ReadonlySet<string>;
22
22
  readonly deferEnabled: boolean;
23
+ /** The provider runs tool search itself (`ChatModel.serverToolSearch`); no SearchTool. */
24
+ readonly serverToolSearch: boolean;
23
25
  }
24
26
  export declare function buildRunTools<TContext>(active: Agent<TContext>, state: RunState<TContext>, runAgent: RunAgentFn<TContext>, model: ChatModel): Promise<RunToolset>;
25
27
  //# sourceMappingURL=toolset.d.ts.map
@@ -31,7 +31,8 @@ export async function buildRunTools(active, state, runAgent, model) {
31
31
  return false;
32
32
  });
33
33
  const deferEnabled = active.deferTools !== false && model.supportsDeferredTools;
34
- const deferredToolNames = new Set(deferEnabled ? capTools.map((tool) => tool.schema.name) : []);
34
+ const serverToolSearch = active.deferTools !== false && !deferEnabled && model.serverToolSearch;
35
+ const deferredToolNames = new Set(deferEnabled || serverToolSearch ? capTools.map((tool) => tool.schema.name) : []);
35
36
  const tools = [...active.tools, ...capTools];
36
37
  if (deferEnabled)
37
38
  tools.push(buildSearchTool(capTools.map((t) => t.schema)));
@@ -41,7 +42,7 @@ export async function buildRunTools(active, state, runAgent, model) {
41
42
  // (e.g. profile-loaded agents). The unified "Agent" tool spawns/resumes by type.
42
43
  const providerAgents = state.subagentProvider !== undefined ? [...(await state.subagentProvider.list())] : [];
43
44
  if (active.subagents.length === 0 && providerAgents.length === 0) {
44
- return finish(state, tools, deferredToolNames, deferEnabled);
45
+ return finish(state, tools, deferredToolNames, deferEnabled, serverToolSearch);
45
46
  }
46
47
  // One spawner (the engine seam) shared by every subagent-spawning tool: the static
47
48
  // `agent_<name>` tools, the unified `Agent` tool, and `Workflow`.
@@ -56,26 +57,27 @@ export async function buildRunTools(active, state, runAgent, model) {
56
57
  if (state.workflowTool !== false && !tools.some((tool) => tool.schema.name === "Workflow")) {
57
58
  tools.push(buildWorkflowTool(spawner, state));
58
59
  }
59
- return finish(state, tools, deferredToolNames, deferEnabled);
60
+ return finish(state, tools, deferredToolNames, deferEnabled, serverToolSearch);
60
61
  }
61
62
  /**
62
63
  * Last stop before the turn: let capabilities narrow the complete registry (the extension
63
64
  * runtime's `setActiveTools` rides this). Filtering happens AFTER assembly so a filter sees
64
65
  * handoff and subagent tools too, and the deferred-name set is pruned to whatever survived.
65
66
  */
66
- function finish(state, tools, deferredToolNames, deferEnabled) {
67
+ function finish(state, tools, deferredToolNames, deferEnabled, serverToolSearch) {
67
68
  const filtered = state.capabilities.applyToolFilters(tools, {
68
69
  address: state.address,
69
70
  isRootAgent: state.address === DEFAULT_ADDRESS,
70
71
  });
71
72
  const enabled = deferEnabled && filtered.some((tool) => tool.schema.name === "SearchTool");
72
73
  if (filtered === tools)
73
- return { tools, deferredToolNames, deferEnabled: enabled };
74
+ return { tools, deferredToolNames, deferEnabled: enabled, serverToolSearch };
74
75
  const surviving = new Set(filtered.map((tool) => tool.schema.name));
75
76
  return {
76
77
  tools: filtered,
77
- deferredToolNames: new Set(enabled ? [...deferredToolNames].filter((name) => surviving.has(name)) : []),
78
+ deferredToolNames: new Set(enabled || serverToolSearch ? [...deferredToolNames].filter((name) => surviving.has(name)) : []),
78
79
  deferEnabled: enabled,
80
+ serverToolSearch,
79
81
  };
80
82
  }
81
83
  /**
@@ -159,16 +159,6 @@ function configureKnownModel(model, providerId, config) {
159
159
  ...(config.customHeaders !== undefined
160
160
  ? { headers: { ...(model.headers ?? {}), ...config.customHeaders } }
161
161
  : {}),
162
- ...(config.type === "kimi"
163
- ? { compat: { ...model.compat, deferredToolsMode: "kimi" } }
164
- : config.type === "anthropic"
165
- ? {
166
- compat: {
167
- ...model.compat,
168
- supportsToolReferences: defaultAnthropicToolReferences(model.id),
169
- },
170
- }
171
- : {}),
172
162
  };
173
163
  }
174
164
  function buildCustomPiModel(alias, providerId, providerConfig) {
@@ -177,11 +167,6 @@ function buildCustomPiModel(alias, providerId, providerConfig) {
177
167
  ? ["text", "image"]
178
168
  : ["text"];
179
169
  const api = apiForProviderType(providerConfig.type);
180
- const compat = providerConfig.type === "kimi"
181
- ? { deferredToolsMode: "kimi" }
182
- : providerConfig.type === "anthropic"
183
- ? { supportsToolReferences: defaultAnthropicToolReferences(alias.model) }
184
- : undefined;
185
170
  return {
186
171
  id: alias.model,
187
172
  name: alias.displayName ?? alias.model,
@@ -198,7 +183,6 @@ function buildCustomPiModel(alias, providerId, providerConfig) {
198
183
  ...(providerConfig.customHeaders !== undefined
199
184
  ? { headers: providerConfig.customHeaders }
200
185
  : {}),
201
- ...(compat !== undefined ? { compat } : {}),
202
186
  };
203
187
  }
204
188
  function configuredAuth(providerId, config, base, resolveApiKey) {
@@ -328,17 +312,5 @@ function apiForProviderType(type) {
328
312
  return "google-vertex";
329
313
  }
330
314
  }
331
- function defaultAnthropicToolReferences(modelId) {
332
- if (modelId.includes("haiku"))
333
- return false;
334
- const version = modelId.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
335
- if (version === null)
336
- return false;
337
- const major = Number(version[1]);
338
- const minor = version[2] !== undefined && version[2].length < 8
339
- ? Number(version[2])
340
- : 0;
341
- return major > 4 || (major === 4 && minor >= 5);
342
- }
343
315
  export { UNKNOWN_CAPABILITY };
344
316
  //# sourceMappingURL=provider-manager.js.map
@@ -87,7 +87,11 @@ export declare class ChatModel {
87
87
  * holds back for the summary against this — a model that cannot emit 20k never needs 20k
88
88
  * reserved. */
89
89
  readonly maxOutputTokens: number;
90
+ /** Loading a deferred tool mid-conversation keeps the request prefix: SearchTool mode. */
90
91
  readonly supportsDeferredTools: boolean;
92
+ /** The provider searches deferred tools itself (OpenRouter's `openrouter:tool_search`).
93
+ * Used only where `supportsDeferredTools` is false. */
94
+ readonly serverToolSearch: boolean;
91
95
  private readonly piModel;
92
96
  private readonly runtime;
93
97
  /** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
@@ -107,5 +111,7 @@ export declare class ChatModel {
107
111
  }
108
112
  export declare function defineModel(spec: ModelSpec): ChatModel;
109
113
  export declare function tryGetPiModel(provider: string, model: string, runtime?: ModelRuntime): Model<Api> | undefined;
114
+ /** `claude-opus-4-8`, `anthropic/claude-sonnet-5.5`, `claude-fable-5-20260101`, ... */
115
+ export declare function acceptsMidConvoToolChanges(modelId: string): boolean;
110
116
  export {};
111
117
  //# sourceMappingURL=define-model.d.ts.map
@@ -2,7 +2,7 @@ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
2
2
  import { emptyUsage } from "../loop/usage.js";
3
3
  import { createModelRuntime, forceRefreshOAuth, } from "./runtime.js";
4
4
  import { classifyError } from "./errors.js";
5
- import { withAnthropicDeferredMode } from "./deferred-tools.js";
5
+ import { supportsOpenRouterToolSearch, withOpenRouterToolSearch } from "./openrouter-tool-search.js";
6
6
  export class ChatModel {
7
7
  id;
8
8
  provider;
@@ -12,7 +12,11 @@ export class ChatModel {
12
12
  * holds back for the summary against this — a model that cannot emit 20k never needs 20k
13
13
  * reserved. */
14
14
  maxOutputTokens;
15
+ /** Loading a deferred tool mid-conversation keeps the request prefix: SearchTool mode. */
15
16
  supportsDeferredTools;
17
+ /** The provider searches deferred tools itself (OpenRouter's `openrouter:tool_search`).
18
+ * Used only where `supportsDeferredTools` is false. */
19
+ serverToolSearch;
16
20
  piModel;
17
21
  runtime;
18
22
  /** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
@@ -20,7 +24,7 @@ export class ChatModel {
20
24
  requestDefaults;
21
25
  constructor(spec) {
22
26
  this.runtime = spec.runtime ?? createModelRuntime();
23
- this.piModel = resolvePiModel(spec, this.runtime);
27
+ this.piModel = withAnthropicToolChanges(resolvePiModel(spec, this.runtime));
24
28
  this.requestDefaults = {
25
29
  ...(spec.apiKey !== undefined ? { apiKey: spec.apiKey } : {}),
26
30
  ...spec.connection,
@@ -31,6 +35,7 @@ export class ChatModel {
31
35
  this.contextWindow = this.piModel.contextWindow;
32
36
  this.maxOutputTokens = this.piModel.maxTokens;
33
37
  this.supportsDeferredTools = supportsNativeDeferredTools(this.piModel);
38
+ this.serverToolSearch = supportsOpenRouterToolSearch(this.piModel);
34
39
  }
35
40
  stream(req, call) {
36
41
  const ctx = toContext(req);
@@ -63,9 +68,10 @@ export class ChatModel {
63
68
  }
64
69
  options(req, call) {
65
70
  const options = toOptions(req, call, this.requestDefaults);
66
- return req.deferredTools && this.api === "anthropic-messages" && this.supportsDeferredTools
67
- ? withAnthropicDeferredMode(options)
68
- : options;
71
+ const deferred = this.serverToolSearch
72
+ ? new Set((req.tools ?? []).filter((tool) => tool.deferLoading === true).map((tool) => tool.name))
73
+ : undefined;
74
+ return deferred !== undefined && deferred.size > 0 ? withOpenRouterToolSearch(options, deferred) : options;
69
75
  }
70
76
  async streamWithAuthRetry(req, call, ctx, out) {
71
77
  const first = await this.runAttempt(req, call, ctx, out);
@@ -185,31 +191,65 @@ export function tryGetPiModel(provider, model, runtime = createModelRuntime()) {
185
191
  return runtime.models.getModel(provider, model);
186
192
  }
187
193
  /**
188
- * Mirror pi's public model-compat gates so Operon only hides capability tools
189
- * when the selected wire can materialize `addedToolNames`. pi remains the
190
- * authority for serialization; this gate only decides whether SearchTool mode
191
- * is safe to enter.
194
+ * Mirror pi's gates for anchoring a `toolsAdded` system message in place, so Operon only
195
+ * hides capability tools when loading one will not rewrite the request prefix. Everywhere
196
+ * else pi collapses later system messages into the leading one — the whole current tool list
197
+ * at the top — which is exactly the per-load prefix rewrite deferral must not cause.
192
198
  */
193
199
  function supportsNativeDeferredTools(model) {
194
200
  const compat = model.compat;
195
- if (model.api === "openai-completions")
196
- return compat?.deferredToolsMode === "kimi";
197
- if (model.api === "openai-responses" || model.api === "openai-codex-responses") {
198
- return compat?.supportsToolSearch === true;
201
+ if (compat?.supportsMidConvoSystemMessages !== true)
202
+ return false;
203
+ switch (model.api) {
204
+ case "anthropic-messages":
205
+ return compat.supportsMidConvoToolChanges === true;
206
+ case "openai-responses":
207
+ case "azure-openai-responses":
208
+ case "openai-codex-responses":
209
+ return compat.supportsAdditionalTools === true || compat.supportsToolSearch === true;
210
+ case "openai-completions":
211
+ return compat.supportsMidConvoToolAdditions === true;
212
+ default:
213
+ return false;
199
214
  }
215
+ }
216
+ /**
217
+ * Anthropic accepts mid-conversation `tool_addition` blocks from Opus 4.8 on, Sonnet 5
218
+ * excepted (the API's own rejection text; Sonnet 5.5 verified through OpenRouter). pi's
219
+ * catalog flags only the models it verified and none reached through other gateways, so
220
+ * fill in the Anthropic-wire models it leaves unset. An explicit flag always wins.
221
+ */
222
+ function withAnthropicToolChanges(model) {
200
223
  if (model.api !== "anthropic-messages")
224
+ return model;
225
+ const compat = model.compat;
226
+ if (compat?.supportsMidConvoToolChanges !== undefined || !acceptsMidConvoToolChanges(model.id))
227
+ return model;
228
+ return {
229
+ ...model,
230
+ compat: {
231
+ ...compat,
232
+ supportsMidConvoSystemMessages: compat?.supportsMidConvoSystemMessages ?? true,
233
+ supportsMidConvoToolChanges: true,
234
+ },
235
+ };
236
+ }
237
+ /** `claude-opus-4-8`, `anthropic/claude-sonnet-5.5`, `claude-fable-5-20260101`, ... */
238
+ export function acceptsMidConvoToolChanges(modelId) {
239
+ const match = modelId
240
+ .replace(/^.*\//, "")
241
+ .replace(/\./g, "-")
242
+ .match(/^claude-(opus|sonnet|fable)-(\d+)(?:-(\d{1,2}))?(?:-|$)/);
243
+ if (match === null)
201
244
  return false;
202
- if (compat?.supportsToolReferences !== undefined)
203
- return compat.supportsToolReferences;
204
- // pi's Anthropic default: first-party Claude >= 4.5, excluding Haiku.
205
- if (model.provider !== "anthropic" || model.id.includes("haiku"))
206
- return false;
207
- const version = model.id.match(/^claude-(?:opus|sonnet|fable)-(\d+)(?:-(\d+))?(?:-|$)/);
208
- if (!version)
245
+ const family = match[1];
246
+ const major = Number(match[2]);
247
+ const minor = match[3] === undefined ? 0 : Number(match[3]);
248
+ if (family === "fable")
249
+ return true;
250
+ if (family === "sonnet" && major === 5 && minor === 0)
209
251
  return false;
210
- const major = Number(version[1]);
211
- const minor = version[2] && version[2].length < 8 ? Number(version[2]) : 0;
212
- return major > 4 || (major === 4 && minor >= 5);
252
+ return major > 4 || (major === 4 && minor >= 8);
213
253
  }
214
254
  function toContext(req) {
215
255
  return {
@@ -28,9 +28,9 @@ export interface ModelSettings {
28
28
  export interface LlmRequest {
29
29
  readonly system?: string;
30
30
  readonly messages: readonly Message[];
31
+ /** Top-level tools. Tools that become available later in the conversation are declared
32
+ * by `system` messages in `messages` (pi's `toolsAdded`). */
31
33
  readonly tools?: readonly ToolSchema[];
32
- /** Keep native deferred loading active even before the first successful search. */
33
- readonly deferredTools?: boolean;
34
34
  readonly params?: ModelSettings;
35
35
  readonly providerOptions?: Readonly<Record<string, unknown>>;
36
36
  }
@@ -0,0 +1,18 @@
1
+ import type { Model, ModelsSimpleStreamOptions } from "@earendil-works/pi-ai";
2
+ import type { Api } from "../protocol/index.ts";
3
+ /**
4
+ * OpenRouter's server-side tool search. Every deferred function tool is sent with
5
+ * `defer_loading: true` next to `{ type: "openrouter:tool_search" }`; OpenRouter withholds
6
+ * those definitions from the upstream prompt and lets the model regex-search them, on any
7
+ * model. Measured on deepseek-v4-flash (2026-09-29): 31 tools 14.8k → 6.1k input tokens,
8
+ * and adding a deferred tool mid-conversation keeps the cached prefix. What the search
9
+ * revealed need not be replayed: a stripped history still calls the discovered tool.
10
+ *
11
+ * Responses API only — OpenRouter rejects it on Chat Completions (400), and its Messages
12
+ * API is reached here only by Claude models, which take the native `tool_addition` path.
13
+ */
14
+ export declare const OPENROUTER_TOOL_SEARCH = "openrouter:tool_search";
15
+ export declare function supportsOpenRouterToolSearch(model: Model<Api>): boolean;
16
+ /** Mark `deferred` function tools and add the search tool at pi's public payload seam. */
17
+ export declare function withOpenRouterToolSearch(options: ModelsSimpleStreamOptions, deferred: ReadonlySet<string>): ModelsSimpleStreamOptions;
18
+ //# sourceMappingURL=openrouter-tool-search.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * OpenRouter's server-side tool search. Every deferred function tool is sent with
3
+ * `defer_loading: true` next to `{ type: "openrouter:tool_search" }`; OpenRouter withholds
4
+ * those definitions from the upstream prompt and lets the model regex-search them, on any
5
+ * model. Measured on deepseek-v4-flash (2026-09-29): 31 tools 14.8k → 6.1k input tokens,
6
+ * and adding a deferred tool mid-conversation keeps the cached prefix. What the search
7
+ * revealed need not be replayed: a stripped history still calls the discovered tool.
8
+ *
9
+ * Responses API only — OpenRouter rejects it on Chat Completions (400), and its Messages
10
+ * API is reached here only by Claude models, which take the native `tool_addition` path.
11
+ */
12
+ export const OPENROUTER_TOOL_SEARCH = "openrouter:tool_search";
13
+ export function supportsOpenRouterToolSearch(model) {
14
+ return model.api === "openai-responses" && isOpenRouter(model.baseUrl);
15
+ }
16
+ function isOpenRouter(baseUrl) {
17
+ try {
18
+ const host = new URL(baseUrl).hostname;
19
+ return host === "openrouter.ai" || host.endsWith(".openrouter.ai");
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ /** Mark `deferred` function tools and add the search tool at pi's public payload seam. */
26
+ export function withOpenRouterToolSearch(options, deferred) {
27
+ const inspect = options.onPayload;
28
+ return {
29
+ ...options,
30
+ onPayload: async (payload, model) => {
31
+ let next = payload;
32
+ if (payload !== null && typeof payload === "object" && "tools" in payload && Array.isArray(payload.tools)) {
33
+ let marked = false;
34
+ const tools = payload.tools.map((tool) => {
35
+ if (tool === null || typeof tool !== "object" || !("name" in tool) || typeof tool.name !== "string")
36
+ return tool;
37
+ if (!deferred.has(tool.name))
38
+ return tool;
39
+ marked = true;
40
+ return { ...tool, defer_loading: true };
41
+ });
42
+ // OpenRouter rejects a deferred tool without the search tool, and the search tool
43
+ // with nothing to search is only noise.
44
+ if (marked)
45
+ next = { ...payload, tools: [{ type: OPENROUTER_TOOL_SEARCH }, ...tools] };
46
+ }
47
+ return (await inspect?.(next, model)) ?? next;
48
+ },
49
+ };
50
+ }
51
+ //# sourceMappingURL=openrouter-tool-search.js.map
@@ -34,6 +34,7 @@ export interface RunTurnInput {
34
34
  /** Capability tools hidden until transcript load/use evidence activates them. */
35
35
  readonly deferredToolNames?: ReadonlySet<string>;
36
36
  readonly deferEnabled?: boolean;
37
+ readonly serverToolSearch?: boolean;
37
38
  /** Snapshot after beforeStep, so a connection completed during a turn is seen next step. */
38
39
  readonly refreshTools?: () => Promise<ToolCatalogSnapshot>;
39
40
  readonly onToolsPrepared?: (tools: readonly Tool[]) => void;
@@ -30,7 +30,7 @@ export async function runTurn(input) {
30
30
  try {
31
31
  // HITL resume — re-run the interrupted batch with pre-loaded answers first.
32
32
  if (input.resumeFrom) {
33
- const resumeSnapshot = input.refreshTools ? await input.refreshTools() : { tools: toolList, deferredToolNames, deferEnabled: input.deferEnabled };
33
+ const resumeSnapshot = input.refreshTools ? await input.refreshTools() : { tools: toolList, deferredToolNames, deferEnabled: input.deferEnabled, serverToolSearch: input.serverToolSearch };
34
34
  const resumePrepared = prepareToolCatalog(input.context, resumeSnapshot, { announce: false });
35
35
  const resumeTools = resumePrepared.tools;
36
36
  input.onToolsPrepared?.(resumeTools);
@@ -87,6 +87,7 @@ export async function runTurn(input) {
87
87
  tools: toolList,
88
88
  deferredToolNames,
89
89
  deferEnabled: input.deferEnabled,
90
+ serverToolSearch: input.serverToolSearch,
90
91
  refreshTools: input.refreshTools,
91
92
  onToolsPrepared: input.onToolsPrepared,
92
93
  hooks: input.hooks,
@@ -403,8 +403,8 @@ function toResultMessage(call, result) {
403
403
  toolCallId: call.id,
404
404
  toolName: call.name,
405
405
  content: result.content,
406
+ // Tool details are persisted as JSON; pi now types that contract.
406
407
  details: result.details,
407
- ...(result.addedToolNames !== undefined ? { addedToolNames: [...result.addedToolNames] } : {}),
408
408
  isError: result.isError ?? false,
409
409
  timestamp: Date.now(),
410
410
  };
@@ -40,6 +40,7 @@ export interface ExecuteStepDeps {
40
40
  readonly tools: readonly Tool[];
41
41
  readonly deferredToolNames: ReadonlySet<string>;
42
42
  readonly deferEnabled?: boolean;
43
+ readonly serverToolSearch?: boolean;
43
44
  readonly refreshTools?: () => Promise<ToolCatalogSnapshot>;
44
45
  readonly onToolsPrepared?: (tools: readonly Tool[]) => void;
45
46
  readonly hooks?: LoopHooks;
@@ -1,7 +1,7 @@
1
1
  import { runToolCallBatch } from "./tool-call.js";
2
2
  import { streamWithRetry } from "../llm/retry.js";
3
3
  import { APIContextOverflowError, isContextOverflowMessage } from "../llm/errors.js";
4
- import { describeUnknownTool, prepareToolCatalog } from "../tool/search/catalog.js";
4
+ import { describeUnknownTool, prepareToolCatalog, withToolLoads } from "../tool/search/catalog.js";
5
5
  export async function executeStep(deps) {
6
6
  const { turnId, signal, model, currentStep, hooks } = deps;
7
7
  const messages = deps.context.messages; // backing array (reads/slices share this ref)
@@ -37,13 +37,14 @@ export async function executeStep(deps) {
37
37
  deps.logger?.log("warn", warning);
38
38
  const activeTools = prepared.tools;
39
39
  deps.onToolsPrepared?.(activeTools);
40
- const toolSchemas = prepared.schemas;
40
+ const toolSchemas = prepared.requestTools;
41
41
  const toolMap = new Map(activeTools.map((tool) => [tool.schema.name, tool]));
42
42
  let request = {
43
43
  system,
44
- messages,
44
+ messages: prepared.deferEnabled
45
+ ? withToolLoads(deps.context, new Set(toolSchemas.map((schema) => schema.name)))
46
+ : messages,
45
47
  tools: toolSchemas.length > 0 ? toolSchemas : undefined,
46
- ...(prepared.deferEnabled ? { deferredTools: true } : {}),
47
48
  ...(deps.params ? { params: deps.params } : {}),
48
49
  // Per conversation line, not per session: each address carries its own prefix, so keying
49
50
  // them apart is what actually helps the cache. Seeded here rather than merged, so an
@@ -1,4 +1,4 @@
1
- export type { Message, UserMessage, AssistantMessage, ToolResultMessage, ToolCall, TextContent, ThinkingContent, ImageContent, Usage, Context, Model, Api, KnownApi, KnownProvider, ThinkingLevel, ThinkingBudgets, ProviderHeaders, Transport, Tool as PiTool, AssistantMessageEvent, AssistantMessageEventStream, } from "@earendil-works/pi-ai";
1
+ export type { Message, SystemMessage, UserMessage, AssistantMessage, ToolResultMessage, ToolCall, TextContent, ThinkingContent, ImageContent, Usage, Context, Model, Api, KnownApi, KnownProvider, ThinkingLevel, ThinkingBudgets, ProviderHeaders, Transport, Tool as PiTool, AssistantMessageEvent, AssistantMessageEventStream, JsonObject, JsonValue, } from "@earendil-works/pi-ai";
2
2
  export type { ProviderId as Provider } from "@earendil-works/pi-ai";
3
3
  export type { ToolSchema } from "./tool-schema.ts";
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -2,5 +2,10 @@ export interface ToolSchema {
2
2
  readonly name: string;
3
3
  readonly description: string;
4
4
  readonly parameters: Readonly<Record<string, unknown>>;
5
+ /**
6
+ * Withheld by the provider until its own server-side tool search reveals it
7
+ * (`ChatModel.serverToolSearch`). Only the request's top-level list carries it.
8
+ */
9
+ readonly deferLoading?: boolean;
5
10
  }
6
11
  //# sourceMappingURL=tool-schema.d.ts.map
@@ -2,17 +2,24 @@ import type { ConversationContext } from "../../loop/context.ts";
2
2
  import type { ToolSchema } from "../../protocol/index.ts";
3
3
  import type { LoadedToolSchema } from "../../store/origin.ts";
4
4
  import type { Tool } from "../types.ts";
5
- export { loadedToolSchemas } from "./loaded.ts";
5
+ export { loadedToolSchemas, withToolLoads } from "./loaded.ts";
6
6
  export interface ToolCatalogSnapshot {
7
7
  readonly tools: readonly Tool[];
8
8
  readonly deferredToolNames: ReadonlySet<string>;
9
9
  readonly deferEnabled?: boolean;
10
+ /** The provider searches `deferredToolNames` itself: every tool executes and is sent,
11
+ * the deferred ones marked `deferLoading`. Exclusive with `deferEnabled`. */
12
+ readonly serverToolSearch?: boolean;
10
13
  }
11
14
  export interface PreparedToolCatalog {
12
15
  /** Only presently available, loaded tools can execute. */
13
16
  readonly tools: readonly Tool[];
14
- /** Includes retired definitions needed to replay surviving load points. */
17
+ /** Every definition the request declares, including retired ones needed to replay
18
+ * surviving load points. What the context-window accounting counts. */
15
19
  readonly schemas: readonly ToolSchema[];
20
+ /** The request's top-level tool list. With deferral on, only the immediate tools and
21
+ * SearchTool: loaded definitions are declared at their load points (`withToolLoads`). */
22
+ readonly requestTools: readonly ToolSchema[];
16
23
  readonly loaded: ReadonlyMap<string, LoadedToolSchema>;
17
24
  /** The deferred catalog this request offers through SearchTool, by wire name. */
18
25
  readonly catalog: ReadonlyMap<string, ToolSchema>;
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { SEARCH_TOOL_NAME } from "./deferral.js";
3
3
  import { loadedToolSchemas } from "./loaded.js";
4
4
  import { buildSearchTool } from "./search-tool.js";
5
- export { loadedToolSchemas } from "./loaded.js";
5
+ export { loadedToolSchemas, withToolLoads } from "./loaded.js";
6
6
  function canonical(value) {
7
7
  if (Array.isArray(value))
8
8
  return `[${value.map(canonical).join(",")}]`;
@@ -62,8 +62,16 @@ function announcementText(input) {
62
62
  /** Called after beforeStep/compaction, once per model request, never during a tool batch. */
63
63
  export function prepareToolCatalog(context, snapshot, options = {}) {
64
64
  const enabled = snapshot.deferEnabled ?? snapshot.deferredToolNames.size > 0;
65
+ if (snapshot.serverToolSearch === true) {
66
+ const all = snapshot.tools.map((tool) => tool.schema);
67
+ const requestTools = all.map((schema) => snapshot.deferredToolNames.has(schema.name) ? { ...schema, deferLoading: true } : schema);
68
+ // The provider keeps the deferred definitions out of the prompt: they cost no context.
69
+ const schemas = all.filter((schema) => !snapshot.deferredToolNames.has(schema.name));
70
+ return { tools: snapshot.tools, schemas, requestTools, loaded: new Map(), catalog: new Map(), deferEnabled: false, warnings: [] };
71
+ }
65
72
  if (!enabled) {
66
- return { tools: snapshot.tools, schemas: snapshot.tools.map((tool) => tool.schema), loaded: new Map(), catalog: new Map(), deferEnabled: false, warnings: [] };
73
+ const schemas = snapshot.tools.map((tool) => tool.schema);
74
+ return { tools: snapshot.tools, schemas, requestTools: schemas, loaded: new Map(), catalog: new Map(), deferEnabled: false, warnings: [] };
67
75
  }
68
76
  const warnings = [];
69
77
  const loaded = loadedToolSchemas(context);
@@ -146,6 +154,7 @@ export function prepareToolCatalog(context, snapshot, options = {}) {
146
154
  return {
147
155
  tools: active,
148
156
  schemas: [...schemas.values()],
157
+ requestTools: [...immediate.map((tool) => tool.schema), search.schema],
149
158
  loaded,
150
159
  catalog: new Map(catalog.map((tool) => [tool.schema.name, tool.schema])),
151
160
  deferEnabled: true,
@@ -4,8 +4,9 @@
4
4
  * When an agent has many tools (MCP / capability sprawl), most are marked
5
5
  * *deferred*: kept in Operon's execution catalog but out of the model's active
6
6
  * context. The model calls SearchTool to discover the few it needs; matches
7
- * are recorded as `ToolResultMessage.addedToolNames`, and pi 0.81 handles the
8
- * provider-specific transcript representation.
7
+ * are recorded in the SearchTool result's details, and the request projection
8
+ * declares them to pi as `toolsAdded` system messages; pi handles the
9
+ * provider-specific wire representation.
9
10
  *
10
11
  * This module holds only the pieces that don't depend on any provider: the
11
12
  * keyword search, the query DSL,
@@ -13,6 +13,16 @@ export declare function isLoadedSchema(value: unknown): value is LoadedToolSchem
13
13
  * compaction releases a load nothing after it depends on. First record wins.
14
14
  */
15
15
  export declare function loadedToolSchemas(history: HistoryView): Map<string, LoadedToolSchema>;
16
+ /**
17
+ * The history as pi should see it: every load point followed by a system message whose
18
+ * `toolsAdded` declares the definitions it loaded, so pi anchors them there (Anthropic
19
+ * `tool_addition`, Responses `additional_tools` / client tool search, Kimi `tools` system
20
+ * messages) instead of rewriting the top-level tool list. `declared` names the request's
21
+ * top-level tools; a name is declared once, at its first surviving load point, which keeps
22
+ * the projection of an unchanged prefix byte-identical as history grows. The declaration
23
+ * lands after the load point's whole tool-result batch, since results must stay contiguous.
24
+ */
25
+ export declare function withToolLoads(history: HistoryView, declared: ReadonlySet<string>): Message[];
16
26
  /**
17
27
  * What a compaction summary must carry: definitions loaded in the prefix being removed that
18
28
  * assistant messages in the kept tail still call. Anything else is released — the model is
@@ -16,26 +16,61 @@ export function isLoadedSchema(value) {
16
16
  export function loadedToolSchemas(history) {
17
17
  const loaded = new Map();
18
18
  for (const message of history.messages) {
19
- let entries = [];
20
- if (message.role === "user") {
21
- const origin = history.originOf(message);
22
- if (origin?.kind === "compaction_summary" && origin.loadedTools !== undefined) {
23
- entries = origin.loadedTools.filter(isLoadedSchema);
24
- }
25
- }
26
- else if (message.role === "toolResult" && message.toolName === SEARCH_TOOL_NAME && !message.isError) {
27
- const details = message.details;
28
- if (Array.isArray(details?.deferredToolSchemas)) {
29
- const selected = new Set(message.addedToolNames ?? []);
30
- entries = details.deferredToolSchemas.filter(isLoadedSchema).filter((entry) => selected.has(entry.schema.name));
31
- }
32
- }
33
- for (const entry of entries)
19
+ for (const entry of loadPointEntries(history, message))
34
20
  if (!loaded.has(entry.schema.name))
35
21
  loaded.set(entry.schema.name, entry);
36
22
  }
37
23
  return loaded;
38
24
  }
25
+ /** The definitions `message` records as loaded, if it is a load point. */
26
+ function loadPointEntries(history, message) {
27
+ if (message.role === "user") {
28
+ const origin = history.originOf(message);
29
+ return origin?.kind === "compaction_summary" && origin.loadedTools !== undefined ? origin.loadedTools.filter(isLoadedSchema) : [];
30
+ }
31
+ if (message.role === "toolResult" && message.toolName === SEARCH_TOOL_NAME && !message.isError) {
32
+ const details = message.details;
33
+ return Array.isArray(details?.deferredToolSchemas) ? details.deferredToolSchemas.filter(isLoadedSchema) : [];
34
+ }
35
+ return [];
36
+ }
37
+ /**
38
+ * The history as pi should see it: every load point followed by a system message whose
39
+ * `toolsAdded` declares the definitions it loaded, so pi anchors them there (Anthropic
40
+ * `tool_addition`, Responses `additional_tools` / client tool search, Kimi `tools` system
41
+ * messages) instead of rewriting the top-level tool list. `declared` names the request's
42
+ * top-level tools; a name is declared once, at its first surviving load point, which keeps
43
+ * the projection of an unchanged prefix byte-identical as history grows. The declaration
44
+ * lands after the load point's whole tool-result batch, since results must stay contiguous.
45
+ */
46
+ export function withToolLoads(history, declared) {
47
+ const seen = new Set(declared);
48
+ const out = [];
49
+ let pending;
50
+ const flush = () => {
51
+ if (pending !== undefined)
52
+ out.push(pending);
53
+ pending = undefined;
54
+ };
55
+ for (const message of history.messages) {
56
+ if (message.role !== "toolResult")
57
+ flush();
58
+ out.push(message);
59
+ const fresh = loadPointEntries(history, message).filter((entry) => !seen.has(entry.schema.name));
60
+ if (fresh.length === 0)
61
+ continue;
62
+ for (const entry of fresh)
63
+ seen.add(entry.schema.name);
64
+ pending ??= { role: "system", content: "", toolsAdded: [], timestamp: message.timestamp };
65
+ pending.toolsAdded.push(...fresh.map((entry) => toPiTool(entry.schema)));
66
+ }
67
+ flush();
68
+ return out;
69
+ }
70
+ function toPiTool(schema) {
71
+ // Protocol-level parameters are a JSON Schema object; pi serializes it as the tool schema.
72
+ return { name: schema.name, description: schema.description, parameters: schema.parameters };
73
+ }
39
74
  /**
40
75
  * What a compaction summary must carry: definitions loaded in the prefix being removed that
41
76
  * assistant messages in the kept tail still call. Anything else is released — the model is
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Built per turn over a snapshot of the deferred catalog (in `buildRunTools`),
5
5
  * so it can search names/descriptions without needing the live tool registry
6
- * at call time. Its result exposes matches through pi 0.81's
7
- * `ToolResultMessage.addedToolNames`; pi materializes the provider-specific
8
- * re-entry envelope.
6
+ * at call time. Its result records the matched definitions in
7
+ * `details.deferredToolSchemas`; the request projection (`withToolLoads`)
8
+ * declares them to pi as a `toolsAdded` system message right after the load.
9
9
  */
10
10
  import { z } from "zod";
11
11
  import { tool } from "../define.js";
@@ -50,7 +50,6 @@ export function buildSearchTool(deferred, sourceNames = new Map()) {
50
50
  text: matches.length > 0 ? `Loaded tools: ${matches.join(", ")}` : "No matching deferred tools found.",
51
51
  },
52
52
  ],
53
- addedToolNames: matches,
54
53
  details: {
55
54
  deferredToolSchemas: matches.map((name) => ({
56
55
  sourceName: sourceNames.get(name) ?? name,
@@ -41,11 +41,6 @@ export interface ToolResumeContext {
41
41
  export interface ToolResult<Details = unknown> {
42
42
  readonly content: ToolResultContent;
43
43
  readonly details?: Details;
44
- /**
45
- * Tool definitions made available by this result. pi 0.81 uses these names
46
- * as the transcript load point for native deferred-tool serialization.
47
- */
48
- readonly addedToolNames?: readonly string[];
49
44
  readonly isError?: boolean;
50
45
  readonly stopTurn?: boolean;
51
46
  }
@@ -307,6 +307,8 @@ function serializeMessage(message) {
307
307
  isError: message.isError,
308
308
  content: message.content.map(serializePart),
309
309
  };
310
+ case "system":
311
+ return { role: "system", content: typeof message.content === "string" ? message.content : message.content.map(serializePart) };
310
312
  }
311
313
  }
312
314
  function serializeToolResult(result) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "operon-agents-core",
3
- "version": "0.1.0-alpha.12",
3
+ "version": "0.1.0-alpha.13",
4
4
  "description": "Internal engine for operon-agents. Prefer operon-agents for application code.",
5
5
  "type": "module",
6
6
  "engines": {
@@ -71,7 +71,7 @@
71
71
  "README.md"
72
72
  ],
73
73
  "dependencies": {
74
- "@earendil-works/pi-ai": "0.84.1",
74
+ "@earendil-works/pi-ai": "0.87.1",
75
75
  "@modelcontextprotocol/sdk": "^1.29.0",
76
76
  "@opentelemetry/api": "^1.9.0",
77
77
  "acorn": "^8.17.0",
@@ -1,7 +0,0 @@
1
- import type { ModelsSimpleStreamOptions } from "@earendil-works/pi-ai";
2
- export declare const DEFERRED_TOOL_PLACEHOLDER = "OperonDeferredToolPlaceholder";
3
- /** pi has no option to keep Anthropic's deferred-mode hint present before the first
4
- * search. Add only that inert marker at its public payload seam; leave native tool
5
- * loading and history serialization to pi. Keep it after real tools disconnect too. */
6
- export declare function withAnthropicDeferredMode(options: ModelsSimpleStreamOptions): ModelsSimpleStreamOptions;
7
- //# sourceMappingURL=deferred-tools.d.ts.map
@@ -1,27 +0,0 @@
1
- export const DEFERRED_TOOL_PLACEHOLDER = "OperonDeferredToolPlaceholder";
2
- const placeholder = {
3
- name: DEFERRED_TOOL_PLACEHOLDER,
4
- description: "Reserved placeholder that keeps deferred tool loading active. Never call this tool.",
5
- input_schema: { type: "object", properties: {} },
6
- defer_loading: true,
7
- };
8
- /** pi has no option to keep Anthropic's deferred-mode hint present before the first
9
- * search. Add only that inert marker at its public payload seam; leave native tool
10
- * loading and history serialization to pi. Keep it after real tools disconnect too. */
11
- export function withAnthropicDeferredMode(options) {
12
- const inspect = options.onPayload;
13
- return {
14
- ...options,
15
- onPayload: async (payload, model) => {
16
- let next = payload;
17
- if (payload !== null && typeof payload === "object" && "tools" in payload && Array.isArray(payload.tools)) {
18
- if (payload.tools.some((tool) => tool !== null && typeof tool === "object" && "name" in tool && tool.name === DEFERRED_TOOL_PLACEHOLDER)) {
19
- throw new Error(`Reserved deferred tool name: ${DEFERRED_TOOL_PLACEHOLDER}`);
20
- }
21
- next = { ...payload, tools: [...payload.tools, structuredClone(placeholder)] };
22
- }
23
- return (await inspect?.(next, model)) ?? next;
24
- },
25
- };
26
- }
27
- //# sourceMappingURL=deferred-tools.js.map
@@ -1,17 +0,0 @@
1
- import type { Message } from "../../protocol/index.ts";
2
- import type { Tool } from "../types.ts";
3
- /**
4
- * Project a complete execution registry to the tools currently available to
5
- * the model. A load point is structural transcript state, not summary text:
6
- *
7
- * - `addedToolNames` activates newly searched tools.
8
- * - a surviving assistant tool call keeps an already-used tool immediate.
9
- * - full compaction unloads evidence removed with the compacted prefix.
10
- * - micro compaction keeps these fields while replacing only result content.
11
- *
12
- * `prepareToolCatalog` (catalog.ts) does not use this projection: it activates a catalog tool
13
- * only from recorded definitions (a SearchTool load point or a snapshot-carrying call), so a
14
- * guessed call to a never-loaded name is not evidence. This stays as the origin-free view.
15
- */
16
- export declare function activeDeferredTools(tools: readonly Tool[], deferredToolNames: ReadonlySet<string>, messages: readonly Message[]): Tool[];
17
- //# sourceMappingURL=activation.d.ts.map
@@ -1,35 +0,0 @@
1
- /**
2
- * Project a complete execution registry to the tools currently available to
3
- * the model. A load point is structural transcript state, not summary text:
4
- *
5
- * - `addedToolNames` activates newly searched tools.
6
- * - a surviving assistant tool call keeps an already-used tool immediate.
7
- * - full compaction unloads evidence removed with the compacted prefix.
8
- * - micro compaction keeps these fields while replacing only result content.
9
- *
10
- * `prepareToolCatalog` (catalog.ts) does not use this projection: it activates a catalog tool
11
- * only from recorded definitions (a SearchTool load point or a snapshot-carrying call), so a
12
- * guessed call to a never-loaded name is not evidence. This stays as the origin-free view.
13
- */
14
- export function activeDeferredTools(tools, deferredToolNames, messages) {
15
- if (deferredToolNames.size === 0)
16
- return [...tools];
17
- const activeDeferred = new Set();
18
- for (const message of messages) {
19
- if (message.role === "assistant") {
20
- for (const part of message.content) {
21
- if (part.type === "toolCall" && deferredToolNames.has(part.name)) {
22
- activeDeferred.add(part.name);
23
- }
24
- }
25
- }
26
- else if (message.role === "toolResult") {
27
- for (const name of message.addedToolNames ?? []) {
28
- if (deferredToolNames.has(name))
29
- activeDeferred.add(name);
30
- }
31
- }
32
- }
33
- return tools.filter((tool) => !deferredToolNames.has(tool.schema.name) || activeDeferred.has(tool.schema.name));
34
- }
35
- //# sourceMappingURL=activation.js.map