@opencode/ai 0.0.0-dev-1337 → 0.0.0-dev-1341

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.
@@ -12,7 +12,7 @@ import { AIError, CacheTTL, LLMEvent, mergeJsonRecords, Usage, } from "../schema
12
12
  import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js";
13
13
  import { classifyProviderFailure } from "../provider-error.js";
14
14
  import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js";
15
- import { addsTools, foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js";
15
+ import { addsTools, toolsUpdate } from "../tool-updates.js";
16
16
  import * as Cache from "./utils/cache.js";
17
17
  import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js";
18
18
  import { Lifecycle } from "./utils/lifecycle.js";
@@ -643,7 +643,7 @@ const lowerWrappedSystemUpdate = Effect.fnUntraced(function* (message, breakpoin
643
643
  const part = yield* ProviderShared.wrappedSystemUpdate("Anthropic Messages", message);
644
644
  return { type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) };
645
645
  });
646
- const lowerToolsUpdate = Effect.fnUntraced(function* (message, update, withdrawn, breakpoints) {
646
+ const lowerToolsUpdate = Effect.fnUntraced(function* (message, update, breakpoints) {
647
647
  const text = message.content.length === 0 ? [] : (yield* lowerNativeSystemUpdate(message, breakpoints)).content;
648
648
  return {
649
649
  role: "system",
@@ -652,7 +652,7 @@ const lowerToolsUpdate = Effect.fnUntraced(function* (message, update, withdrawn
652
652
  type: "tool_addition",
653
653
  tool: { type: "tool_definition", definition: lowerTool(breakpoints, tool) },
654
654
  })),
655
- ...withdrawn.map((name) => ({
655
+ ...update.remove.map((name) => ({
656
656
  type: "tool_removal",
657
657
  tool: { type: "tool_reference", name },
658
658
  })),
@@ -674,8 +674,6 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
674
674
  // user turn, the nearest spot where Anthropic accepts a native system message.
675
675
  const holdUpdates = supportsNativeSystemUpdates(request);
676
676
  const held = [];
677
- // The tools declared so far, so each tool update can name the flattened tools it takes away.
678
- let declared = request.tools;
679
677
  const releaseHeld = Effect.fnUntraced(function* () {
680
678
  const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"));
681
679
  for (const update of held.splice(0)) {
@@ -683,9 +681,7 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
683
681
  if (tools !== undefined) {
684
682
  if (!native)
685
683
  return yield* invalid("Anthropic Messages tool updates must follow a user message or tool result");
686
- const next = foldTools(declared, tools.add, tools.remove);
687
- const lowered = yield* lowerToolsUpdate(update, tools, withdrawnTools(declared, next), breakpoints);
688
- declared = next;
684
+ const lowered = yield* lowerToolsUpdate(update, tools, breakpoints);
689
685
  if (lowered.content.length > 0)
690
686
  messages.push(lowered);
691
687
  continue;
@@ -866,8 +862,8 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
866
862
  // messages. Tools live highest in the cache hierarchy, so when callers
867
863
  // over-mark we keep their tool hints and shed the message-tail ones first.
868
864
  const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP);
869
- const flattened = ProviderShared.flattenToolRequest(updates.request);
870
- const tools = flattened.tools.length === 0 ? undefined : flattened.tools.map((tool) => lowerTool(breakpoints, tool));
865
+ const definitions = ProviderShared.flattenTools(updates.request.tools);
866
+ const tools = definitions.length === 0 ? undefined : definitions.map((tool) => lowerTool(breakpoints, tool));
871
867
  // Anthropic rejects tool_choice when no tool is declared; "none" is only meaningful with tools present.
872
868
  const declared = tools !== undefined || addsTools(request);
873
869
  const toolChoice = !declared || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice);
@@ -879,7 +875,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
879
875
  text: part.text,
880
876
  cache_control: cacheControl(breakpoints, part.cache),
881
877
  }));
882
- const messages = yield* lowerMessages(flattened.request, breakpoints);
878
+ const messages = yield* lowerMessages(updates.request, breakpoints);
883
879
  yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP);
884
880
  const output_config = updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format };
885
881
  const maxTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS;
@@ -233,7 +233,7 @@ const removeEmptyToolInputKeys = (input) => {
233
233
  const lowerToolCall = (part, normalizeID) => ({
234
234
  toolUse: {
235
235
  toolUseId: normalizeID(part.id),
236
- // Converse rejects replayed names over 64 characters; flattenToolRequest already fixed invalid characters.
236
+ // Converse rejects replayed names over 64 characters; flattenRequest already fixed invalid characters.
237
237
  name: part.name.slice(0, 64),
238
238
  input: removeEmptyToolInputKeys(part.input),
239
239
  },
@@ -459,7 +459,7 @@ const applyThinkingBindingDefault = (request, thinking) => {
459
459
  };
460
460
  const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request) {
461
461
  const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined;
462
- const flattened = ProviderShared.flattenToolRequest(request);
462
+ const definitions = ProviderShared.flattenTools(request.tools);
463
463
  const options = yield* decodeOptions(request.providerOptions ?? {});
464
464
  const maxTokens = isNova2(request.model) && (options.effort === "high" || isHighReasoningEffort(request.http?.body))
465
465
  ? undefined
@@ -486,17 +486,17 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request)
486
486
  // tools → system → messages order to favour the highest-impact prefixes.
487
487
  const breakpoints = BedrockCache.breakpoints(request.model);
488
488
  const toolConfig = (() => {
489
- if (flattened.tools.length === 0)
489
+ if (definitions.length === 0)
490
490
  return undefined;
491
491
  return {
492
- tools: lowerTools(breakpoints, flattened.tools),
492
+ tools: lowerTools(breakpoints, definitions),
493
493
  // Converse has no native "none". Keep definitions stable for prompt
494
494
  // caching and omit only the unsupported choice.
495
495
  toolChoice,
496
496
  };
497
497
  })();
498
498
  const system = lowerSystem(breakpoints, request.system);
499
- const messages = yield* lowerMessages(flattened.request, breakpoints);
499
+ const messages = yield* lowerMessages(request, breakpoints);
500
500
  yield* warnDropped(breakpoints, "Bedrock Converse", BedrockCache.BEDROCK_BREAKPOINT_CAP);
501
501
  const inferenceConfig = (() => {
502
502
  if (maxTokens === undefined &&
@@ -125,7 +125,7 @@ const Event = Schema.Union([
125
125
  const TOOL_CHOICE = { auto: undefined, none: "NONE", required: "REQUIRED", tool: "REQUIRED" };
126
126
  const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request) {
127
127
  const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(request.providerOptions ?? {});
128
- const flattened = ProviderShared.flattenToolRequest(request);
128
+ const definitions = ProviderShared.flattenTools(request.tools);
129
129
  const messages = request.system.length
130
130
  ? [
131
131
  {
@@ -136,7 +136,7 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request) {
136
136
  },
137
137
  ]
138
138
  : [];
139
- for (const message of flattened.request.messages) {
139
+ for (const message of request.messages) {
140
140
  if (message.role === "system") {
141
141
  messages.push({ role: "user", content: (yield* ProviderShared.wrappedSystemUpdate("Cohere Chat", message)).text });
142
142
  continue;
@@ -187,7 +187,7 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request) {
187
187
  });
188
188
  }
189
189
  const selected = request.toolChoice?.type === "tool" ? request.toolChoice.name : undefined;
190
- const tools = selected === undefined ? flattened.tools : flattened.tools.filter((tool) => tool.name === selected);
190
+ const tools = selected === undefined ? definitions : definitions.filter((tool) => tool.name === selected);
191
191
  if (selected !== undefined && tools.length === 0)
192
192
  return yield* ProviderShared.invalidRequest("Cohere Chat tool choice must name an available tool");
193
193
  if (tools.some((tool) => tool.native !== undefined))
@@ -339,8 +339,8 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
339
339
  return contents;
340
340
  });
341
341
  const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request) {
342
- const flattened = ProviderShared.flattenToolRequest(request);
343
- const hasTools = flattened.tools.length > 0;
342
+ const definitions = ProviderShared.flattenTools(request.tools);
343
+ const hasTools = definitions.length > 0;
344
344
  const options = yield* decodeOptions(request.providerOptions ?? {});
345
345
  const generationConfig = {
346
346
  maxOutputTokens: request.maxTokens,
@@ -364,14 +364,14 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request) {
364
364
  };
365
365
  return {
366
366
  cachedContent: options.cachedContent,
367
- contents: yield* lowerMessages(flattened.request),
367
+ contents: yield* lowerMessages(request),
368
368
  safetySettings: options.safetySettings,
369
369
  serviceTier: options.serviceTier,
370
370
  systemInstruction: request.system.length === 0 ? undefined : { parts: request.system.map((part) => ({ text: part.text })) },
371
371
  tools: hasTools
372
372
  ? [
373
373
  {
374
- functionDeclarations: flattened.tools.map(lowerTool),
374
+ functionDeclarations: definitions.map(lowerTool),
375
375
  },
376
376
  ]
377
377
  : undefined,
@@ -298,8 +298,8 @@ const lowerToolResult = Effect.fnUntraced(function* (part) {
298
298
  });
299
299
  const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (request) {
300
300
  const options = yield* decodeOptions(request.providerOptions ?? {});
301
- const flattened = ProviderShared.flattenToolRequest(request);
302
- if (flattened.tools.some((tool) => tool.native !== undefined))
301
+ const definitions = ProviderShared.flattenTools(request.tools);
302
+ if (definitions.some((tool) => tool.native !== undefined))
303
303
  return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported");
304
304
  if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined)
305
305
  return yield* ProviderShared.invalidRequest("Google Interactions does not support topK, frequencyPenalty, or presencePenalty");
@@ -313,7 +313,7 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
313
313
  });
314
314
  return {
315
315
  model: request.model.id,
316
- input: yield* lowerMessages(flattened.request),
316
+ input: yield* lowerMessages(request),
317
317
  stream: true,
318
318
  // Full-history replay need not create retained provider resources. Continuation callers opt in to storage.
319
319
  store: options.store ?? false,
@@ -324,8 +324,8 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
324
324
  type: setting.category.replace(/^HARM_CATEGORY_/, "").toLowerCase(),
325
325
  threshold: setting.threshold.toLowerCase(),
326
326
  })),
327
- tools: flattened.tools.length
328
- ? flattened.tools.map((tool) => ({
327
+ tools: definitions.length
328
+ ? definitions.map((tool) => ({
329
329
  type: "function",
330
330
  name: tool.name,
331
331
  description: tool.description,
@@ -24,8 +24,8 @@ const Body = Schema.Struct({
24
24
  tools: optionalArray(Schema.Union([FunctionTool, WebSearch])),
25
25
  });
26
26
  const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request) {
27
- const projected = ProviderShared.flattenToolRequest(request);
28
- const body = yield* AnthropicMessages.protocol.body.from(projected.request);
27
+ const body = yield* AnthropicMessages.protocol.body.from(request);
28
+ const definitions = ProviderShared.flattenTools(request.tools);
29
29
  return {
30
30
  ...body,
31
31
  messages: body.messages.map((message) => {
@@ -43,7 +43,7 @@ const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request) {
43
43
  tools: body.tools === undefined
44
44
  ? undefined
45
45
  : yield* Effect.forEach(body.tools, (tool, index) => Effect.gen(function* () {
46
- const native = projected.tools[index]?.native;
46
+ const native = definitions[index]?.native;
47
47
  if (native === undefined)
48
48
  return tool;
49
49
  const search = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MetaResponses.WebSearch))(native.meta);
@@ -123,6 +123,7 @@ export declare const MistralBody: Schema.Struct<{
123
123
  readonly prompt_mode: Schema.optional<Schema.Literal<"reasoning">>;
124
124
  }>;
125
125
  export type MistralBody = Schema.Schema.Type<typeof MistralBody>;
126
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
126
127
  export declare const fromRequest: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
127
128
  readonly [x: string]: unknown;
128
129
  }, import("../route/client.js").CompactionOperations | undefined>>) => Effect.Effect<{
@@ -283,6 +283,7 @@ const lowerTool = (tool) => ({
283
283
  type: "function",
284
284
  function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: false },
285
285
  });
286
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
286
287
  export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (request) {
287
288
  const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MistralOptions))(request.providerOptions ?? {});
288
289
  if (options.reasoningEffort !== undefined && options.promptMode !== undefined)
@@ -295,11 +296,10 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
295
296
  tool: (name) => ({ type: "function", function: { name } }),
296
297
  })
297
298
  : undefined;
298
- const flattened = ProviderShared.flattenToolRequest(request);
299
299
  return {
300
300
  model: request.model.id,
301
- messages: yield* lowerMessages(flattened.request),
302
- tools: flattened.tools.length > 0 ? flattened.tools.map(lowerTool) : undefined,
301
+ messages: yield* lowerMessages(request),
302
+ tools: request.tools.length > 0 ? ProviderShared.flattenTools(request.tools).map(lowerTool) : undefined,
303
303
  tool_choice: toolChoice,
304
304
  stream: true,
305
305
  max_tokens: request.maxTokens,
@@ -1412,6 +1412,7 @@ export declare const allowedToolChoice: (options: OpenResponsesOptions.Resolved,
1412
1412
  name: string;
1413
1413
  }[];
1414
1414
  } | undefined;
1415
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
1415
1416
  export declare const fromRequestWithAdapter: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
1416
1417
  readonly [x: string]: unknown;
1417
1418
  }, import("../route.js").CompactionOperations | undefined>>, adapter: ProviderAdapter) => Effect.Effect<{
@@ -1600,6 +1601,7 @@ export declare const fromRequestWithAdapter: (request: LLMRequest<import("../sch
1600
1601
  }[];
1601
1602
  } | undefined;
1602
1603
  }, AIError, never>;
1604
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
1603
1605
  export declare const fromRequest: (request: LLMRequest) => Effect.Effect<{
1604
1606
  model: string & import("effect/Brand").Brand<"AI.ModelID">;
1605
1607
  input: ({
@@ -670,18 +670,20 @@ export const allowedToolChoice = (options, custom) => {
670
670
  tools: allowed.toolNames.map((name) => namedTool(name, custom)),
671
671
  };
672
672
  };
673
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
673
674
  export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (request, adapter) {
674
- const projected = ProviderShared.flattenToolRequest(request);
675
+ const definitions = ProviderShared.flattenTools(request.tools);
675
676
  const options = OpenResponsesOptions.resolve(request);
676
677
  const custom = OpenAIFreeform.tools(request);
677
678
  return {
678
- ...(yield* lowerConversation(projected.request, adapter)),
679
+ ...(yield* lowerConversation(request, adapter)),
679
680
  ...lowerGeneration(request, options),
680
- tools: projected.tools.length === 0 ? undefined : yield* lowerTools(projected.tools, adapter, custom),
681
+ tools: definitions.length === 0 ? undefined : yield* lowerTools(definitions, adapter, custom),
681
682
  tool_choice: allowedToolChoice(options, custom) ??
682
683
  (request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice, custom) : undefined),
683
684
  };
684
685
  });
686
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
685
687
  export const fromRequest = (request) => fromRequestWithAdapter(request, BASE_ADAPTER);
686
688
  // =============================================================================
687
689
  // Stream Parsing
@@ -718,6 +718,7 @@ interface LoweringOptions {
718
718
  /** Project provider-specific fields from the exact source, even when other messages are dropped during lowering. */
719
719
  readonly assistant?: (source: AssistantMessage, message: OpenAIChatMessage) => OpenAIChatMessage;
720
720
  }
721
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
721
722
  export declare const fromRequest: (request: LLMRequest<import("../schema/options.js").LanguageModel<{
722
723
  readonly [x: string]: unknown;
723
724
  }, import("../route/client.js").CompactionOperations | undefined>>, options?: LoweringOptions | undefined) => Effect.Effect<{
@@ -676,13 +676,14 @@ const lowerOptions = (request, supportsStore, hasActiveTools) => {
676
676
  ...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
677
677
  };
678
678
  };
679
+ /** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
679
680
  export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (request, options = {}) {
680
681
  // `fromRequest` returns the provider body only. Endpoint, auth, framing,
681
682
  // validation, and HTTP execution are composed by `Route.make`.
682
683
  const reasoningField = request.model.compatibility?.reasoningField;
683
684
  if (reasoningField && RESERVED_REASONING_FIELDS.has(reasoningField))
684
685
  return yield* ProviderShared.invalidRequest(`OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`);
685
- const flattened = ProviderShared.flattenToolRequest(request);
686
+ const definitions = ProviderShared.flattenTools(request.tools);
686
687
  const provider = request.model.provider;
687
688
  const baseURL = request.model.route.endpoint.baseURL;
688
689
  const detectedMaxTokensField = detectMaxTokensField(provider, baseURL);
@@ -691,17 +692,17 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (reques
691
692
  const supportsStrictMode = request.model.capabilities?.tools?.strict ?? detectSupportsStrictMode(provider, baseURL);
692
693
  const zaiToolStream = request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id);
693
694
  const hasHistory = hasToolHistory(request.messages);
694
- const hasActiveTools = flattened.tools.length > 0;
695
+ const hasActiveTools = definitions.length > 0;
695
696
  const custom = OpenAIFreeform.tools(request);
696
697
  const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom };
697
698
  return {
698
699
  model: request.model.id,
699
- messages: yield* lowerMessages(flattened.request, lowering),
700
- tools: flattened.tools.length === 0
700
+ messages: yield* lowerMessages(request, lowering),
701
+ tools: definitions.length === 0
701
702
  ? hasHistory
702
703
  ? []
703
704
  : undefined
704
- : flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
705
+ : definitions.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
705
706
  tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined,
706
707
  stream: true,
707
708
  ...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
@@ -326,6 +326,7 @@ export const protocol = Protocol.make({
326
326
  }),
327
327
  supportsEffortUpdates,
328
328
  toolUpdates,
329
+ namespaces: true,
329
330
  });
330
331
  const endpoint = Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL });
331
332
  const auth = Auth.none;
@@ -184,9 +184,20 @@ export declare const unsupportedOperation: (input: {
184
184
  /**
185
185
  * Lower namespaces to flat definitions for protocols without a native
186
186
  * namespace construct. Leaf names join their namespace path with `_` because
187
- * `.` is not broadly accepted in provider tool names.
187
+ * `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
188
+ * it to type their tools.
188
189
  */
189
190
  export declare const flattenTools: (tools: ReadonlyArray<ToolEntry>, path?: ReadonlyArray<string>) => ToolDefinition[];
191
+ /**
192
+ * The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
193
+ * use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
194
+ * requests.
195
+ */
196
+ export declare const flattenRequest: (request: LLMRequest) => LLMRequest;
197
+ /**
198
+ * @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
199
+ * the next minor.
200
+ */
190
201
  export declare const flattenToolRequest: (request: LLMRequest) => {
191
202
  tools: ToolDefinition[];
192
203
  request: LLMRequest<import("../schema/options.js").LanguageModel<{
@@ -2,9 +2,10 @@ import { Tool } from "@opencode/schema/tool";
2
2
  import { Effect, Option, Predicate, Schema, SchemaGetter, SchemaTransformation } from "effect";
3
3
  import { Headers, HttpClientRequest } from "effect/http";
4
4
  import { Media } from "../media.js";
5
- import { InvalidProviderOutputError, InvalidRequestError, UnsupportedOperationError, AIError, AssistantMessage, Message, ToolDefinition, ToolMessage, } from "../schema/index.js";
5
+ import { InvalidProviderOutputError, InvalidRequestError, UnsupportedOperationError, AIError, AssistantMessage, Message, SystemMessage, ToolChoice, ToolDefinition, ToolMessage, } from "../schema/index.js";
6
6
  import { Json, decodeJson, encodeJson } from "../utils/json.js";
7
7
  import { isRecord } from "../utils/record.js";
8
+ import { foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js";
8
9
  export { Json, decodeJson, encodeJson, isRecord };
9
10
  const isJson = Schema.is(Schema.Json);
10
11
  export const JsonObject = Schema.Record(Schema.String, Schema.Unknown);
@@ -269,7 +270,8 @@ export const unsupportedOperation = (input) => new AIError({
269
270
  /**
270
271
  * Lower namespaces to flat definitions for protocols without a native
271
272
  * namespace construct. Leaf names join their namespace path with `_` because
272
- * `.` is not broadly accepted in provider tool names.
273
+ * `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
274
+ * it to type their tools.
273
275
  */
274
276
  export const flattenTools = (tools, path = []) => {
275
277
  const flat = tools.flatMap((tool) => {
@@ -281,11 +283,25 @@ export const flattenTools = (tools, path = []) => {
281
283
  });
282
284
  return [...new Map(flat.map((tool) => [tool.name, tool])).values()];
283
285
  };
284
- export const flattenToolRequest = (request) => {
285
- const tools = flattenTools(request.tools);
286
- const declared = new Set(tools.map((tool) => tool.name));
286
+ /**
287
+ * The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
288
+ * use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
289
+ * requests.
290
+ */
291
+ export const flattenRequest = (request) => {
292
+ const all = [...request.tools, ...request.messages.flatMap((message) => toolsUpdate(message)?.add ?? [])];
293
+ const declared = new Set(flattenTools(all).map((tool) => tool.name));
287
294
  const flatten = (part) => flattenToolName(part, declared);
295
+ // A tool update that redefines a namespace drops the tools it leaves out, which only the namespace shows, so name
296
+ // them as explicit removals.
297
+ let tools = request.tools;
288
298
  const messages = request.messages.map((message) => {
299
+ if (message.role === "system" && message.tools !== undefined) {
300
+ const next = foldTools(tools, message.tools.add, message.tools.remove);
301
+ const remove = withdrawnTools(tools, next);
302
+ tools = next;
303
+ return new SystemMessage({ ...message, tools: { add: flattenTools(message.tools.add), remove } });
304
+ }
289
305
  if (message.role === "assistant") {
290
306
  const content = message.content.map((part) => part.type === "tool-call" || part.type === "tool-result" ? flatten(part) : part);
291
307
  return sameParts(content, message.content) ? message : new AssistantMessage({ ...message, content });
@@ -296,12 +312,33 @@ export const flattenToolRequest = (request) => {
296
312
  return sameParts(content, message.content) ? message : new ToolMessage({ ...message, content });
297
313
  });
298
314
  return {
299
- tools,
300
- request: messages.every((message, index) => message === request.messages[index])
301
- ? request
302
- : { ...request, messages },
315
+ ...request,
316
+ tools: flattenTools(request.tools),
317
+ messages,
318
+ toolChoice: flattenToolChoice(request.toolChoice, all, declared),
303
319
  };
304
320
  };
321
+ /**
322
+ * @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
323
+ * the next minor.
324
+ */
325
+ export const flattenToolRequest = (request) => {
326
+ const flat = flattenRequest(request);
327
+ return { tools: flattenTools(flat.tools), request: flat };
328
+ };
329
+ // A forced choice names a namespaced tool by its path (`crm.lookup`); point it at the flattened definition.
330
+ const flattenToolChoice = (choice, tools, declared) => {
331
+ if (choice?.type !== "tool" || choice.name === undefined || declared.has(choice.name))
332
+ return choice;
333
+ const name = new Map(namespacedPaths(tools)).get(choice.name);
334
+ return name === undefined ? choice : new ToolChoice({ ...choice, name });
335
+ };
336
+ // Each namespaced tool's path and the name flattenTools gives it.
337
+ const namespacedPaths = (tools, path = []) => tools.flatMap((tool) => {
338
+ if (tool.type === "namespace")
339
+ return namespacedPaths(tool.tools, [...path, tool.name]);
340
+ return path.length === 0 ? [] : [[[...path, tool.name].join("."), [...path, tool.name].join("_")]];
341
+ });
305
342
  const flattenToolName = (part, declared) => {
306
343
  const flat = part.namespace === undefined ? part.name : `${part.namespace}_${part.name}`;
307
344
  // Models sometimes call names no tool declares, such as a Code Mode path like `a.b.c`. Several providers (OpenAI
@@ -37,6 +37,7 @@ export function gatewayProtocol(protocol, input) {
37
37
  },
38
38
  supportsEffortUpdates: protocol.supportsEffortUpdates,
39
39
  toolUpdates: protocol.toolUpdates,
40
+ namespaces: protocol.namespaces,
40
41
  sanitizer: protocol.sanitizer,
41
42
  stream: {
42
43
  event: protocol.stream.event,
@@ -1,5 +1,6 @@
1
1
  import { Schema } from "effect";
2
2
  import { Protocol } from "../route/protocol.js";
3
+ import type { CompactOperation } from "../route/client.js";
3
4
  import { OpenResponses } from "./open-responses.js";
4
5
  declare const Options: Schema.Struct<{
5
6
  readonly minP: Schema.optional<Schema.Number>;
@@ -289,5 +290,5 @@ export declare const protocol: Protocol<{
289
290
  readonly status?: unknown;
290
291
  readonly status_code?: unknown;
291
292
  }, OpenResponses.ParserState>;
292
- export declare const compact: import("../route/client.js").CompactOperation;
293
+ export declare const compact: CompactOperation;
293
294
  export * as XAIResponses from "./xai-responses.js";
@@ -78,5 +78,8 @@ export const protocol = Protocol.make({
78
78
  },
79
79
  stream: ResponsesHostedTools.stream(adapter, HOSTED_TOOLS),
80
80
  });
81
- export const compact = ResponsesCompaction.make(adapter, (request) => OpenResponses.lowerTools(ProviderShared.flattenTools(request.tools), adapter, OpenAIFreeform.tools(request)));
81
+ const compactFlat = ResponsesCompaction.make(adapter, (request) => OpenResponses.lowerTools(ProviderShared.flattenTools(request.tools), adapter, OpenAIFreeform.tools(request)));
82
+ // /compact lowers the history itself, so flatten the whole request as `Protocol.make` does before every step's body:
83
+ // past calls to namespaced tools then carry the same names as on those steps, and /compact reads the prefix they cached.
84
+ export const compact = (request, executor, options) => compactFlat(ProviderShared.flattenRequest(request), executor, options);
82
85
  export * as XAIResponses from "./xai-responses.js";
@@ -45,6 +45,8 @@ export interface Protocol<Body, Frame, Event, State> {
45
45
  readonly supportsEffortUpdates?: (request: LLMRequest) => boolean;
46
46
  /** Tool changes `body.from` can send in place of `Message.tools(...)` markers; wrappers around another `body.from` must forward it. */
47
47
  readonly toolUpdates?: ToolUpdateEncoding;
48
+ /** Whether `body.from` sends tool namespaces natively; otherwise `make` hands it flattened requests. Wrappers around another `body.from` must forward it. */
49
+ readonly namespaces?: boolean;
48
50
  /** Tool schema sanitizer for every model on this protocol unless the model's compatibility sets one; wrappers around another `body.from` must forward it. */
49
51
  readonly sanitizer?: LanguageModelSanitizerCompatibility;
50
52
  }
@@ -1,4 +1,5 @@
1
1
  import { Schema } from "effect";
2
+ import { flattenRequest } from "../protocols/shared.js";
2
3
  /**
3
4
  * Construct a `Protocol` from its body and stream pieces:
4
5
  *
@@ -11,6 +12,8 @@ import { Schema } from "effect";
11
12
  * without explicit type arguments; the schemas and parser functions are the
12
13
  * source of truth.
13
14
  */
14
- export const make = (input) => input;
15
+ export const make = (input) => input.namespaces
16
+ ? input
17
+ : { ...input, body: { ...input.body, from: (request) => input.body.from(flattenRequest(request)) } };
15
18
  export const jsonEvent = (schema) => Schema.fromJsonString(schema);
16
19
  export * as Protocol from "./protocol.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "0.0.0-dev-1337",
3
+ "version": "0.0.0-dev-1341",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -624,7 +624,7 @@
624
624
  "devDependencies": {
625
625
  "@clack/prompts": "1.0.0-alpha.1",
626
626
  "@effect/platform-node": "4.1.0",
627
- "@opencode/http-recorder": "0.0.0-dev-1337",
627
+ "@opencode/http-recorder": "0.0.0-dev-1341",
628
628
  "@tsconfig/bun": "1.0.9",
629
629
  "@types/bun": "1.4.3",
630
630
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -634,7 +634,7 @@
634
634
  "@aws-sdk/credential-providers": "3.1057.0",
635
635
  "@smithy/eventstream-codec": "4.2.14",
636
636
  "@smithy/util-utf8": "4.2.2",
637
- "@opencode/schema": "0.0.0-dev-1337",
637
+ "@opencode/schema": "0.0.0-dev-1341",
638
638
  "aws4fetch": "1.0.20",
639
639
  "effect": "4.1.0",
640
640
  "google-auth-library": "10.5.0"