@vellumai/assistant 0.12.1-dev.202609141913.5e16607 → 0.12.1-dev.202609142113.d1590bc

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.
Files changed (118) hide show
  1. package/ARCHITECTURE.md +9 -9
  2. package/openapi.yaml +35 -2
  3. package/package.json +2 -1
  4. package/src/__tests__/anthropic-provider.test.ts +0 -63
  5. package/src/__tests__/assistant-event-hub-machine-name.test.ts +6 -7
  6. package/src/__tests__/assistant-event-hub.test.ts +44 -0
  7. package/src/__tests__/computer-use-skill-manifest-regression.test.ts +1 -1
  8. package/src/__tests__/computer-use-tools.test.ts +2 -2
  9. package/src/__tests__/heartbeat-service.test.ts +56 -40
  10. package/src/__tests__/host-cu-proxy.test.ts +539 -0
  11. package/src/__tests__/list-messages-camera-frame.test.ts +121 -0
  12. package/src/__tests__/oauth-commands-routes.test.ts +113 -0
  13. package/src/__tests__/oauth-provider-profiles.test.ts +18 -0
  14. package/src/__tests__/openai-provider.test.ts +1 -0
  15. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -0
  16. package/src/__tests__/qdrant-manager.test.ts +132 -0
  17. package/src/__tests__/scaffold-managed-skill-tool.test.ts +229 -6
  18. package/src/__tests__/skills.test.ts +9 -4
  19. package/src/__tests__/test-support/computer-use-skill-harness.ts +3 -2
  20. package/src/__tests__/unicode.test.ts +13 -0
  21. package/src/acp/agent-process.ts +2 -1
  22. package/src/agent/loop.ts +1 -0
  23. package/src/api/events/user-message-echo.ts +7 -1
  24. package/src/api/responses/conversation-message.ts +5 -0
  25. package/src/avatar/identity-avatar.ts +7 -2
  26. package/src/config/bundled-skills/computer-use/SKILL.md +20 -2
  27. package/src/config/bundled-skills/computer-use/TOOLS.json +99 -0
  28. package/src/config/bundled-skills/computer-use/tools/computer-use-sequence.ts +12 -0
  29. package/src/config/bundled-skills/media-processing/services/preprocess.ts +2 -1
  30. package/src/config/bundled-skills/media-processing/services/processing-pipeline.ts +2 -1
  31. package/src/config/bundled-skills/media-processing/tools/generate-clip.ts +2 -1
  32. package/src/config/bundled-skills/playbooks/tools/playbook-create.ts +2 -1
  33. package/src/config/bundled-skills/playbooks/tools/playbook-update.ts +2 -1
  34. package/src/config/bundled-skills/skill-management/TOOLS.json +4 -0
  35. package/src/config/bundled-skills/transcribe/tools/transcribe-media.ts +5 -2
  36. package/src/credential-health/credential-health-service.ts +11 -17
  37. package/src/daemon/conversation-error.ts +3 -2
  38. package/src/daemon/conversation-media-retry.ts +2 -1
  39. package/src/daemon/conversation-runtime-assembly.ts +2 -1
  40. package/src/daemon/conversation-surfaces.ts +5 -1
  41. package/src/daemon/dictation-profile-store.ts +2 -1
  42. package/src/daemon/handlers/shared.ts +2 -1
  43. package/src/daemon/handlers/skills.ts +6 -3
  44. package/src/daemon/host-cu-proxy.ts +186 -19
  45. package/src/daemon/host-proxy-preactivation.ts +2 -1
  46. package/src/daemon/reaction-history-render.ts +2 -1
  47. package/src/heartbeat/heartbeat-service.ts +21 -3
  48. package/src/live-voice/__tests__/live-voice-sight-frame-echo.test.ts +238 -0
  49. package/src/live-voice/live-voice-photo.ts +25 -6
  50. package/src/oauth/AGENTS.md +2 -0
  51. package/src/oauth/byo-connection.test.ts +60 -0
  52. package/src/oauth/scope-utils.ts +24 -0
  53. package/src/oauth/seed-providers.ts +39 -25
  54. package/src/persistence/conversation-queries.ts +2 -2
  55. package/src/persistence/embeddings/qdrant-manager.ts +163 -18
  56. package/src/plugins/defaults/memory/__tests__/memory-retrospective-prompt.test.ts +5 -0
  57. package/src/plugins/defaults/memory/context-search/agent-runner.ts +3 -2
  58. package/src/plugins/defaults/memory/context-search/format.ts +3 -2
  59. package/src/plugins/defaults/memory/context-search/sources/memory-v2.ts +6 -3
  60. package/src/plugins/defaults/memory/context-search/sources/workspace.ts +3 -2
  61. package/src/plugins/defaults/memory/graph/capability-seed.ts +2 -1
  62. package/src/plugins/defaults/memory/host-utils.ts +10 -0
  63. package/src/plugins/defaults/memory/memory-retrospective-prompt.ts +1 -1
  64. package/src/plugins/defaults/memory/startup.ts +22 -1
  65. package/src/plugins/defaults/memory/substrate/page-index.ts +6 -1
  66. package/src/plugins/defaults/memory/v1/graph/consolidation.ts +4 -2
  67. package/src/plugins/defaults/memory/v1/graph/extraction.ts +4 -2
  68. package/src/plugins/defaults/memory/v1/graph/retriever.ts +4 -1
  69. package/src/plugins/defaults/memory/v2/reranker.ts +6 -1
  70. package/src/plugins/defaults/memory/v3/__tests__/card.test.ts +24 -0
  71. package/src/plugins/defaults/memory/v3/__tests__/pool-select.test.ts +39 -3
  72. package/src/plugins/defaults/memory/v3/__tests__/sections.test.ts +26 -0
  73. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +30 -0
  74. package/src/plugins/defaults/memory/v3/card.ts +3 -2
  75. package/src/plugins/defaults/memory/v3/pool-select.ts +5 -3
  76. package/src/plugins/defaults/memory/v3/sections.ts +9 -3
  77. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +5 -2
  78. package/src/providers/__tests__/retry-outbound-sanitize.test.ts +176 -0
  79. package/src/providers/anthropic/client.ts +0 -47
  80. package/src/providers/openai/__tests__/chat-completions-output-token-limit.test.ts +141 -0
  81. package/src/providers/openai/chat-completions-provider.ts +20 -1
  82. package/src/providers/openrouter/client.ts +20 -0
  83. package/src/providers/outbound-request-sanitize.ts +96 -0
  84. package/src/providers/retry.ts +24 -3
  85. package/src/providers/unparseable-tool-args.ts +5 -1
  86. package/src/runtime/AGENTS.md +1 -1
  87. package/src/runtime/__tests__/host-observe.test.ts +40 -1
  88. package/src/runtime/agent-wake.ts +2 -1
  89. package/src/runtime/assistant-event-hub.ts +21 -3
  90. package/src/runtime/host-observe.ts +11 -1
  91. package/src/runtime/routes/conversation-routes.ts +16 -3
  92. package/src/runtime/routes/diagnostics-routes.ts +6 -1
  93. package/src/runtime/routes/events-routes.ts +4 -0
  94. package/src/runtime/routes/host-cu-routes.ts +6 -0
  95. package/src/runtime/routes/oauth-commands-routes.ts +36 -0
  96. package/src/runtime/routes/workspace-routes.test.ts +55 -26
  97. package/src/runtime/routes/workspace-routes.ts +46 -63
  98. package/src/runtime/routes/workspace-tree-walk.test.ts +244 -0
  99. package/src/runtime/routes/workspace-tree-walk.ts +240 -0
  100. package/src/runtime/routes/workspace-utils.ts +17 -0
  101. package/src/schedule/run-script.ts +2 -1
  102. package/src/schedule/schedule-store.ts +9 -2
  103. package/src/security/untrusted-content.ts +3 -1
  104. package/src/tools/__tests__/side-effect-abort-guard.test.ts +1 -0
  105. package/src/tools/browser/browser-execution.ts +1 -1
  106. package/src/tools/browser/cdp-client/accessibility-snapshot.ts +9 -3
  107. package/src/tools/browser/cdp-client/cdp-inspect/discovery.ts +2 -1
  108. package/src/tools/browser/cdp-client/extension-cdp-client.ts +3 -2
  109. package/src/tools/browser/network-recorder.ts +2 -1
  110. package/src/tools/computer-use/definitions.ts +117 -0
  111. package/src/tools/filesystem/search.ts +2 -1
  112. package/src/tools/network/web-search.ts +6 -1
  113. package/src/tools/skills/scaffold-managed.ts +61 -3
  114. package/src/types/host-capabilities.ts +5 -3
  115. package/src/util/unicode.ts +15 -1
  116. package/src/watch/watch-timeline.ts +2 -2
  117. package/src/workflows/run-manager.ts +2 -1
  118. package/src/workspace/git-service.ts +1 -1
@@ -0,0 +1,176 @@
1
+ /**
2
+ * `RetryProvider` strips orphaned UTF-16 surrogates from every outbound
3
+ * request before the inner adapter sees it. An orphan (half of a surrogate
4
+ * pair left by a code-unit `.slice()`) serializes to a `\udXXX` escape that
5
+ * strict provider parsers reject with a 400, so the guard sits at the one
6
+ * layer every adapter shares instead of inside each client.
7
+ */
8
+
9
+ import { describe, expect, test } from "bun:test";
10
+
11
+ import { stripOrphanedSurrogates } from "../../util/unicode.js";
12
+ import { RetryProvider } from "../retry.js";
13
+ import type {
14
+ Message,
15
+ Provider,
16
+ ProviderResponse,
17
+ SendMessageOptions,
18
+ } from "../types.js";
19
+
20
+ const OK_RESPONSE = {
21
+ content: [{ type: "text", text: "ok" }],
22
+ model: "test-model",
23
+ usage: { inputTokens: 1, outputTokens: 1 },
24
+ } as unknown as ProviderResponse;
25
+
26
+ const LONE_HIGH = "\uD83C";
27
+ const LONE_LOW = "\uDF89";
28
+ const EMOJI = "🎉";
29
+
30
+ function capturingProvider(): {
31
+ provider: Provider;
32
+ received: () => { messages: Message[]; options?: SendMessageOptions };
33
+ } {
34
+ let captured: { messages: Message[]; options?: SendMessageOptions } | null =
35
+ null;
36
+ const provider: Provider = {
37
+ name: "openai",
38
+ sendMessage: async (messages, options) => {
39
+ captured = { messages, options };
40
+ return OK_RESPONSE;
41
+ },
42
+ };
43
+ return {
44
+ provider,
45
+ received: () => {
46
+ if (!captured) {
47
+ throw new Error("inner provider was not called");
48
+ }
49
+ return captured;
50
+ },
51
+ };
52
+ }
53
+
54
+ describe("RetryProvider outbound surrogate sanitization", () => {
55
+ test("an orphaned surrogate in a text block, a tool result, the system prompt, and a tool description never reaches the inner adapter", async () => {
56
+ const { provider, received } = capturingProvider();
57
+ const messages: Message[] = [
58
+ {
59
+ role: "user",
60
+ content: [{ type: "text", text: `memory preview ${LONE_HIGH} cut` }],
61
+ },
62
+ {
63
+ role: "assistant",
64
+ content: [{ type: "tool_use", id: "tu1", name: "bash", input: {} }],
65
+ },
66
+ {
67
+ role: "user",
68
+ content: [
69
+ {
70
+ type: "tool_result",
71
+ tool_use_id: "tu1",
72
+ content: `shell output ${LONE_LOW} more`,
73
+ },
74
+ ],
75
+ },
76
+ ];
77
+
78
+ await new RetryProvider(provider).sendMessage(messages, {
79
+ systemPrompt: `system ${LONE_HIGH}`,
80
+ tools: [
81
+ {
82
+ name: "select_pages",
83
+ description: `pick ${LONE_LOW}`,
84
+ input_schema: { type: "object", properties: {} },
85
+ },
86
+ ],
87
+ });
88
+
89
+ const sent = received();
90
+ expect(stripOrphanedSurrogates(JSON.stringify(sent.messages))).toBe(
91
+ JSON.stringify(sent.messages),
92
+ );
93
+ const systemPrompt = sent.options?.systemPrompt ?? "";
94
+ expect(stripOrphanedSurrogates(systemPrompt)).toBe(systemPrompt);
95
+ expect(stripOrphanedSurrogates(JSON.stringify(sent.options?.tools))).toBe(
96
+ JSON.stringify(sent.options?.tools),
97
+ );
98
+ // The orphan is replaced, not dropped, so surrounding text survives.
99
+ const text = sent.messages[0]!.content[0] as { text: string };
100
+ expect(text.text).toBe("memory preview � cut");
101
+ });
102
+
103
+ test("an inline base64 payload is passed through by reference, not scanned", async () => {
104
+ const { provider, received } = capturingProvider();
105
+ // Base64 is ASCII by construction; the guard must not walk a payload that
106
+ // can run to a hundred megabytes. A deliberately corrupt payload proves
107
+ // the field was skipped rather than scanned and found clean.
108
+ const source = {
109
+ type: "base64" as const,
110
+ media_type: "image/png",
111
+ data: `AAAA${LONE_HIGH}`,
112
+ };
113
+ const messages: Message[] = [
114
+ {
115
+ role: "user",
116
+ content: [
117
+ { type: "image", source },
118
+ { type: "text", text: `caption ${LONE_LOW}` },
119
+ ],
120
+ },
121
+ ];
122
+
123
+ await new RetryProvider(provider).sendMessage(messages);
124
+
125
+ const sent = received();
126
+ const image = sent.messages[0]!.content[0] as { source: unknown };
127
+ expect(image.source).toBe(source);
128
+ const text = sent.messages[0]!.content[1] as { text: string };
129
+ expect(text.text).toBe("caption �");
130
+ });
131
+
132
+ test("token-count requests are sanitized the same way", async () => {
133
+ let counted: {
134
+ messages: Message[];
135
+ systemPrompt: string;
136
+ tools: unknown;
137
+ } | null = null;
138
+ const provider: Provider = {
139
+ name: "anthropic",
140
+ sendMessage: async () => OK_RESPONSE,
141
+ countInputTokens: async (messages, systemPrompt, tools) => {
142
+ counted = { messages, systemPrompt, tools };
143
+ return 7;
144
+ },
145
+ };
146
+ const messages: Message[] = [
147
+ { role: "user", content: [{ type: "text", text: `count ${LONE_HIGH}` }] },
148
+ ];
149
+
150
+ const total = await new RetryProvider(provider).countInputTokens!(
151
+ messages,
152
+ `system ${LONE_LOW}`,
153
+ undefined,
154
+ );
155
+
156
+ expect(total).toBe(7);
157
+ const seen = counted!;
158
+ const text = seen.messages[0]!.content[0] as { text: string };
159
+ expect(text.text).toBe("count �");
160
+ expect(seen.systemPrompt).toBe("system �");
161
+ });
162
+
163
+ test("a well-formed request passes through by reference, emoji intact", async () => {
164
+ const { provider, received } = capturingProvider();
165
+ const messages: Message[] = [
166
+ { role: "user", content: [{ type: "text", text: `hello ${EMOJI}` }] },
167
+ ];
168
+
169
+ await new RetryProvider(provider).sendMessage(messages);
170
+
171
+ const sent = received();
172
+ expect(sent.messages).toBe(messages);
173
+ const text = sent.messages[0]!.content[0] as { text: string };
174
+ expect(text.text).toContain(EMOJI);
175
+ });
176
+ });
@@ -9,7 +9,6 @@ import {
9
9
  INSUFFICIENT_CREDITS_PATTERNS,
10
10
  } from "../../util/provider-error-patterns.js";
11
11
  import { extractRetryAfterMs } from "../../util/retry.js";
12
- import { stripOrphanedSurrogatesDeep } from "../../util/unicode.js";
13
12
  import {
14
13
  clampProviderString,
15
14
  isDecodableTextMimeType,
@@ -201,43 +200,6 @@ export function deriveAnthropicReason(
201
200
  return "unknown";
202
201
  }
203
202
 
204
- /** Rate-limit the orphaned-surrogate warning so a single bad stream can't flood logs. */
205
- const ORPHAN_WARNING_THROTTLE_MS = 60_000;
206
- let lastOrphanWarningMs = 0;
207
-
208
- function logOrphanedSurrogateWarning(
209
- fixedStringCount: number,
210
- messages: Anthropic.MessageParam[],
211
- ): void {
212
- const now = Date.now();
213
- if (now - lastOrphanWarningMs < ORPHAN_WARNING_THROTTLE_MS) {
214
- return;
215
- }
216
- lastOrphanWarningMs = now;
217
- const blockTypes = new Set<string>();
218
- for (const msg of messages) {
219
- if (!Array.isArray(msg.content)) {
220
- continue;
221
- }
222
- for (const block of msg.content) {
223
- if (typeof block !== "object" || block == null) {
224
- continue;
225
- }
226
- const type = (block as { type?: string }).type;
227
- if (type) {
228
- blockTypes.add(type);
229
- }
230
- }
231
- }
232
- log.warn(
233
- {
234
- fixedStringCount,
235
- blockTypes: Array.from(blockTypes),
236
- },
237
- "stripped orphaned UTF-16 surrogates from outbound Anthropic request — upstream truncation is not surrogate-aware",
238
- );
239
- }
240
-
241
203
  /**
242
204
  * Validate an Anthropic API key by making a lightweight GET /v1/models call.
243
205
  * Returns `{ valid: true }` on success or `{ valid: false, reason: string }` on failure.
@@ -1299,15 +1261,6 @@ export class AnthropicProvider implements Provider {
1299
1261
  // previous turn exists to anchor). At most two message-level
1300
1262
  // breakpoints are placed, so the total can't drift past 4.
1301
1263
 
1302
- // Strip orphaned UTF-16 surrogates so the Anthropic JSON parser never
1303
- // sees invalid strings produced by upstream surrogate-splitting `.slice()` calls.
1304
- const sanitized = stripOrphanedSurrogatesDeep(params);
1305
- if (sanitized.changed) {
1306
- logOrphanedSurrogateWarning(sanitized.fixedStringCount, sentMessages);
1307
- params = sanitized.value;
1308
- sentMessages = params.messages;
1309
- }
1310
-
1311
1264
  // Callers can stamp `cache_control` on message blocks before the
1312
1265
  // provider sees them. Two repairs apply:
1313
1266
  // - `disableCache`: strip the marker entirely — this call opted out of
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Request-shape coverage for the output-token-limit wire key.
3
+ *
4
+ * The shared OpenAI-compatible transport defaults to `max_completion_tokens`.
5
+ * OpenRouter's parameter router matches `max_tokens` on `require_parameters`
6
+ * routes, except GPT-5.1/5.2 Codex and Chat which advertise only
7
+ * `max_completion_tokens`.
8
+ */
9
+
10
+ import { describe, expect, test } from "bun:test";
11
+
12
+ import {
13
+ openRouterOutputTokenLimitField,
14
+ OpenRouterProvider,
15
+ } from "../../openrouter/client.js";
16
+ import { OpenAIChatCompletionsProvider } from "../chat-completions-provider.js";
17
+
18
+ type MockChunk = {
19
+ choices: Array<{
20
+ delta: { content?: string | null };
21
+ finish_reason?: string | null;
22
+ }>;
23
+ usage?: { prompt_tokens: number; completion_tokens: number };
24
+ };
25
+
26
+ const OK_CHUNKS: MockChunk[] = [
27
+ {
28
+ choices: [{ delta: { content: "ok" }, finish_reason: "stop" }],
29
+ usage: { prompt_tokens: 1, completion_tokens: 1 },
30
+ },
31
+ ];
32
+
33
+ function makeStream(chunks: MockChunk[]): AsyncIterable<MockChunk> {
34
+ return {
35
+ async *[Symbol.asyncIterator]() {
36
+ for (const c of chunks) {
37
+ yield c;
38
+ }
39
+ },
40
+ };
41
+ }
42
+
43
+ function stubCreate(provider: OpenAIChatCompletionsProvider): {
44
+ requests: Record<string, unknown>[];
45
+ } {
46
+ const requests: Record<string, unknown>[] = [];
47
+ const inner = provider as unknown as {
48
+ client: {
49
+ chat: {
50
+ completions: {
51
+ create: (
52
+ params: Record<string, unknown>,
53
+ ) => Promise<AsyncIterable<MockChunk>>;
54
+ };
55
+ };
56
+ };
57
+ };
58
+ inner.client.chat.completions.create = async (params) => {
59
+ requests.push(params);
60
+ return makeStream(OK_CHUNKS);
61
+ };
62
+ return { requests };
63
+ }
64
+
65
+ describe("chat-completions output-token-limit wire key", () => {
66
+ test("default OpenAI path sends max_completion_tokens and omits max_tokens", async () => {
67
+ const provider = new OpenAIChatCompletionsProvider(
68
+ "test-key",
69
+ "test-model",
70
+ );
71
+ const { requests } = stubCreate(provider);
72
+
73
+ await provider.sendMessage(
74
+ [{ role: "user", content: [{ type: "text", text: "hi" }] }],
75
+ { config: { max_tokens: 64000 } },
76
+ );
77
+
78
+ expect(requests).toHaveLength(1);
79
+ expect(requests[0].max_completion_tokens).toBe(64000);
80
+ expect(requests[0]).not.toHaveProperty("max_tokens");
81
+ });
82
+
83
+ test("OpenRouter chat-completions path sends max_tokens and omits max_completion_tokens", async () => {
84
+ const provider = new OpenRouterProvider("or-key", "@preset/example");
85
+ const { requests } = stubCreate(provider);
86
+
87
+ await provider.sendMessage(
88
+ [{ role: "user", content: [{ type: "text", text: "hi" }] }],
89
+ { config: { max_tokens: 64000 } },
90
+ );
91
+
92
+ expect(requests).toHaveLength(1);
93
+ expect(requests[0].max_tokens).toBe(64000);
94
+ expect(requests[0]).not.toHaveProperty("max_completion_tokens");
95
+ });
96
+
97
+ test("OpenRouter GPT-5.2 Codex sends max_completion_tokens and omits max_tokens", async () => {
98
+ const provider = new OpenRouterProvider("or-key", "openai/gpt-5.2-codex");
99
+ const { requests } = stubCreate(provider);
100
+
101
+ await provider.sendMessage(
102
+ [{ role: "user", content: [{ type: "text", text: "hi" }] }],
103
+ { config: { max_tokens: 64000 } },
104
+ );
105
+
106
+ expect(requests).toHaveLength(1);
107
+ expect(requests[0].max_completion_tokens).toBe(64000);
108
+ expect(requests[0]).not.toHaveProperty("max_tokens");
109
+ });
110
+
111
+ test("OpenRouter per-call model override uses the overridden model's wire key", async () => {
112
+ const provider = new OpenRouterProvider("or-key", "x-ai/grok-4.20");
113
+ const { requests } = stubCreate(provider);
114
+
115
+ await provider.sendMessage(
116
+ [{ role: "user", content: [{ type: "text", text: "hi" }] }],
117
+ { config: { model: "openai/gpt-5.1-codex-mini", max_tokens: 64000 } },
118
+ );
119
+
120
+ expect(requests).toHaveLength(1);
121
+ expect(requests[0].max_completion_tokens).toBe(64000);
122
+ expect(requests[0]).not.toHaveProperty("max_tokens");
123
+ });
124
+ });
125
+
126
+ describe("openRouterOutputTokenLimitField", () => {
127
+ test.each([
128
+ ["@preset/example", "max_tokens"],
129
+ ["x-ai/grok-4.20", "max_tokens"],
130
+ ["openai/gpt-5.2", "max_tokens"],
131
+ ["openai/gpt-5.2-pro", "max_tokens"],
132
+ ["openai/gpt-5.3-codex", "max_tokens"],
133
+ ["openai/gpt-5.2-codex", "max_completion_tokens"],
134
+ ["openai/gpt-5.2-chat", "max_completion_tokens"],
135
+ ["openai/gpt-5.1-codex", "max_completion_tokens"],
136
+ ["openai/gpt-5.1-codex-max", "max_completion_tokens"],
137
+ ["openai/gpt-5.1-codex-mini", "max_completion_tokens"],
138
+ ] as const)("%s -> %s", (model, field) => {
139
+ expect(openRouterOutputTokenLimitField(model)).toBe(field);
140
+ });
141
+ });
@@ -208,6 +208,12 @@ export interface OpenAIChatCompletionsProviderOptions {
208
208
  * (Fireworks, Together) keep sending `none` / forced choices. Enabled for
209
209
  * the generic `openai-compatible` adapter, whose upstream is unknown. */
210
210
  omitToolChoiceWhenReasoning?: boolean;
211
+ /** Wire field for the output-token limit. OpenAI and OpenAI-compatible
212
+ * backends use `max_completion_tokens`. OpenRouter defaults to
213
+ * `max_tokens` because its parameter router matches that key on
214
+ * `require_parameters` routes; see
215
+ * {@link OpenAIChatCompletionsProvider.resolveOutputTokenLimitField}. */
216
+ outputTokenLimitField?: "max_completion_tokens" | "max_tokens";
211
217
  }
212
218
 
213
219
  const log = getLogger("chat-completions");
@@ -813,6 +819,7 @@ export class OpenAIChatCompletionsProvider implements Provider {
813
819
  private coerceObjectArgsToJsonString: boolean;
814
820
  private salvageXmlToolCalls: boolean;
815
821
  private omitToolChoiceWhenReasoning: boolean;
822
+ private outputTokenLimitField: "max_completion_tokens" | "max_tokens";
816
823
 
817
824
  constructor(
818
825
  apiKey: string,
@@ -844,6 +851,8 @@ export class OpenAIChatCompletionsProvider implements Provider {
844
851
  options.salvageXmlToolCalls ?? shouldSalvageXmlToolCalls(model);
845
852
  this.omitToolChoiceWhenReasoning =
846
853
  options.omitToolChoiceWhenReasoning ?? false;
854
+ this.outputTokenLimitField =
855
+ options.outputTokenLimitField ?? "max_completion_tokens";
847
856
  }
848
857
 
849
858
  get defaultModel(): string {
@@ -899,7 +908,8 @@ export class OpenAIChatCompletionsProvider implements Provider {
899
908
  };
900
909
 
901
910
  if (maxTokens) {
902
- params.max_completion_tokens = maxTokens;
911
+ params[this.resolveOutputTokenLimitField(modelOverride ?? this.model)] =
912
+ maxTokens;
903
913
  }
904
914
 
905
915
  // Profile-scoped token biasing (e.g. the `suppress-cjk` preset). Resolved
@@ -1577,6 +1587,15 @@ export class OpenAIChatCompletionsProvider implements Provider {
1577
1587
  return this.maxReasoningEffort;
1578
1588
  }
1579
1589
 
1590
+ /** Per-request output-token-limit wire key. Defaults to the constructor
1591
+ * `outputTokenLimitField`. Subclasses override when support varies by
1592
+ * model. */
1593
+ protected resolveOutputTokenLimitField(
1594
+ _model: string,
1595
+ ): "max_completion_tokens" | "max_tokens" {
1596
+ return this.outputTokenLimitField;
1597
+ }
1598
+
1580
1599
  /**
1581
1600
  * Per-model sparse `reasoning_effort` support. Subclasses return the
1582
1601
  * accepted values for models that 4xx on in-between tiers (e.g. GLM 5.3's
@@ -36,6 +36,19 @@ const OPENROUTER_APP_ATTRIBUTION_HEADERS = {
36
36
 
37
37
  const OPENROUTER_MODEL_EFFORT_CEILINGS = modelEffortCeilings("openrouter");
38
38
 
39
+ const OPENROUTER_MAX_COMPLETION_TOKENS_ONLY = /gpt-5\.[12]-(?:codex|chat)/;
40
+
41
+ /** Output-token-limit wire key for an OpenRouter model id. Most endpoints
42
+ * advertise `max_tokens`; GPT-5.1/5.2 Codex and Chat advertise only
43
+ * `max_completion_tokens`. Exported for tests. */
44
+ export function openRouterOutputTokenLimitField(
45
+ model: string,
46
+ ): "max_completion_tokens" | "max_tokens" {
47
+ return OPENROUTER_MAX_COMPLETION_TOKENS_ONLY.test(model)
48
+ ? "max_completion_tokens"
49
+ : "max_tokens";
50
+ }
51
+
39
52
  /**
40
53
  * Extract the normalized `openrouter.only` list from a per-call config. Returns
41
54
  * an empty array when the field is absent, empty, or contains no usable string
@@ -143,6 +156,7 @@ export class OpenRouterProvider extends OpenAIChatCompletionsProvider {
143
156
  streamTimeoutMs: options.streamTimeoutMs,
144
157
  requestHeaders: OPENROUTER_APP_ATTRIBUTION_HEADERS,
145
158
  assistantReasoningField: "reasoning",
159
+ outputTokenLimitField: "max_tokens",
146
160
  });
147
161
  this.openRouterApiKey = apiKey;
148
162
  this.resolvedBaseURL = baseURL;
@@ -250,6 +264,12 @@ export class OpenRouterProvider extends OpenAIChatCompletionsProvider {
250
264
  );
251
265
  }
252
266
 
267
+ protected override resolveOutputTokenLimitField(
268
+ model: string,
269
+ ): "max_completion_tokens" | "max_tokens" {
270
+ return openRouterOutputTokenLimitField(model);
271
+ }
272
+
253
273
  private resolveEffectiveModel(options?: SendMessageOptions): string {
254
274
  const config = options?.config as Record<string, unknown> | undefined;
255
275
  const override =
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Outbound-request Unicode guard for every provider adapter.
3
+ *
4
+ * JavaScript strings are UTF-16, and any `.slice()` on a code-unit boundary
5
+ * can orphan half of a surrogate pair. `JSON.stringify` emits the orphan as a
6
+ * `\udXXX` escape, which strict API parsers reject with a 400 before the model
7
+ * runs (Anthropic: "no low surrogate in string"; OpenAI: `invalid_json`).
8
+ * `RetryProvider` sanitizes the caller's messages and options once at entry,
9
+ * so every attempt, corrective resend, credential refresh, and backup route
10
+ * sends a clean payload, and sanitizes token-count requests the same way.
11
+ * Nothing beneath the wrapper truncates text, so this is the one place the
12
+ * invariant is enforced.
13
+ *
14
+ * The replacement is lossy (U+FFFD), so the warning names the block types
15
+ * involved: the durable fix for any offender is a surrogate-safe slice at the
16
+ * truncation site (`safeStringSlice` in `util/unicode.ts`).
17
+ */
18
+
19
+ import { getLogger } from "../util/logger.js";
20
+ import { stripOrphanedSurrogatesDeep } from "../util/unicode.js";
21
+ import type { Message, SendMessageOptions } from "./types.js";
22
+
23
+ const log = getLogger("outbound-request-sanitize");
24
+
25
+ /** Rate-limit the warning so a poisoned conversation cannot flood the log. */
26
+ const ORPHAN_WARNING_THROTTLE_MS = 60_000;
27
+ let lastOrphanWarningMs = 0;
28
+
29
+ export interface OutboundRequest {
30
+ messages: Message[];
31
+ options: SendMessageOptions | undefined;
32
+ }
33
+
34
+ /**
35
+ * Fields that hold provider-bound base64 (an inline media source's payload,
36
+ * a redacted-thinking blob) are ASCII by construction and can run to over a
37
+ * hundred megabytes, so scanning them is pure event-loop cost.
38
+ */
39
+ function isBase64Payload(
40
+ key: string,
41
+ parent: Record<string, unknown>,
42
+ ): boolean {
43
+ return (
44
+ key === "data" &&
45
+ (parent.type === "base64" || parent.type === "redacted_thinking")
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Replace every orphaned UTF-16 surrogate in the request's messages and
51
+ * options with U+FFFD. Returns the same references when nothing needed
52
+ * fixing, so the happy path allocates nothing.
53
+ */
54
+ export function sanitizeOutboundRequest(
55
+ providerName: string,
56
+ request: OutboundRequest,
57
+ ): OutboundRequest {
58
+ const sanitized = stripOrphanedSurrogatesDeep(request, {
59
+ skipKey: isBase64Payload,
60
+ });
61
+ if (!sanitized.changed) {
62
+ return request;
63
+ }
64
+ logOrphanedSurrogateWarning(
65
+ providerName,
66
+ sanitized.fixedStringCount,
67
+ request.messages,
68
+ );
69
+ return sanitized.value;
70
+ }
71
+
72
+ function logOrphanedSurrogateWarning(
73
+ providerName: string,
74
+ fixedStringCount: number,
75
+ messages: Message[],
76
+ ): void {
77
+ const now = Date.now();
78
+ if (now - lastOrphanWarningMs < ORPHAN_WARNING_THROTTLE_MS) {
79
+ return;
80
+ }
81
+ lastOrphanWarningMs = now;
82
+ const blockTypes = new Set<string>();
83
+ for (const msg of messages) {
84
+ for (const block of msg.content) {
85
+ blockTypes.add(block.type);
86
+ }
87
+ }
88
+ log.warn(
89
+ {
90
+ provider: providerName,
91
+ fixedStringCount,
92
+ blockTypes: Array.from(blockTypes),
93
+ },
94
+ "stripped orphaned UTF-16 surrogates from an outbound LLM request; an upstream truncation is not surrogate-aware",
95
+ );
96
+ }
@@ -44,6 +44,7 @@ import {
44
44
  isAdaptiveThinkingUnsupportedModel,
45
45
  } from "./model-catalog.js";
46
46
  import { buildOpenCodeRequestHeaders } from "./opencode/client.js";
47
+ import { sanitizeOutboundRequest } from "./outbound-request-sanitize.js";
47
48
  import { dispatchProviderResolvable } from "./provider-resolvability.js";
48
49
  import {
49
50
  isThinkingConfigAdaptive,
@@ -1142,8 +1143,9 @@ export class RetryProvider implements Provider {
1142
1143
 
1143
1144
  // Forward the optional token-counting endpoint so the capability survives
1144
1145
  // the wrapper chain (callers gate on its presence). Bound straight to the
1145
- // inner provider — count_tokens is a cheap separate endpoint and its caller
1146
- // already falls back on error, so it needs no retry wrapping.
1146
+ // inner provider behind the same surrogate sanitizer as `sendMessage` —
1147
+ // count_tokens is a cheap separate endpoint and its caller already falls
1148
+ // back on error, so it needs no retry wrapping.
1147
1149
  // Deliberately not re-bound when a credential refresh swaps `inner`: every
1148
1150
  // outer wrapper snapshots this the same way at construction, so a re-bind
1149
1151
  // here would never reach callers. count_tokens on the pre-refresh credential
@@ -1188,7 +1190,18 @@ export class RetryProvider implements Provider {
1188
1190
  this.inner = inner;
1189
1191
  this.name = inner.name;
1190
1192
  if (inner.countInputTokens) {
1191
- this.countInputTokens = inner.countInputTokens.bind(inner);
1193
+ const countInputTokens = inner.countInputTokens.bind(inner);
1194
+ this.countInputTokens = (messages, systemPrompt, tools) => {
1195
+ const clean = sanitizeOutboundRequest(this.name, {
1196
+ messages,
1197
+ options: { systemPrompt, tools },
1198
+ });
1199
+ return countInputTokens(
1200
+ clean.messages,
1201
+ clean.options?.systemPrompt ?? systemPrompt,
1202
+ clean.options?.tools,
1203
+ );
1204
+ };
1192
1205
  }
1193
1206
  }
1194
1207
 
@@ -1262,6 +1275,14 @@ export class RetryProvider implements Provider {
1262
1275
  let credentialRefreshAttempted = false;
1263
1276
  let correctiveResendAttempted = false;
1264
1277
  let fallbackAttempted = false;
1278
+
1279
+ // Every attempt below, the backup route included, sends what this
1280
+ // wrapper was handed, so an orphaned UTF-16 surrogate is stripped here
1281
+ // once rather than rejected by the upstream parser on every resend.
1282
+ ({ messages, options } = sanitizeOutboundRequest(this.name, {
1283
+ messages,
1284
+ options,
1285
+ }));
1265
1286
  let messagesForAttempt = messages;
1266
1287
 
1267
1288
  const normalizedOptions = normalizeSendMessageOptions(this.name, options, {
@@ -12,6 +12,8 @@
12
12
  * an error tool result, so the model sees the failure and can retry, instead
13
13
  * of a tool executing with garbage input.
14
14
  */
15
+
16
+ import { safeStringSlice } from "../util/unicode.js";
15
17
  const UNPARSEABLE_TOOL_ARGS_KEY = "_raw";
16
18
 
17
19
  /**
@@ -56,7 +58,9 @@ export function unparseableToolArgsMessage(
56
58
  ): string {
57
59
  const PREVIEW_LIMIT = 200;
58
60
  const preview =
59
- raw.length > PREVIEW_LIMIT ? `${raw.slice(0, PREVIEW_LIMIT)}…` : raw;
61
+ raw.length > PREVIEW_LIMIT
62
+ ? `${safeStringSlice(raw, 0, PREVIEW_LIMIT)}…`
63
+ : raw;
60
64
  return (
61
65
  `Error: the arguments for "${toolName}" were not valid JSON — the argument stream was malformed or truncated, so the tool was NOT executed. ` +
62
66
  `Received: ${preview || "(empty)"}\n` +
@@ -97,7 +97,7 @@ Host CU allows the assistant to proxy computer-use actions (screenshots, mouse/k
97
97
 
98
98
  - **Discovery**: Clients discover pending host CU requests via SSE events (`host_cu_request`) which include a `requestId`.
99
99
  - **Resolution**: Clients execute the CU action on the host and respond via:
100
- - `POST /v1/host-cu-result` — `{ requestId, axTree?, axDiff?, screenshot?, screenshotWidthPx?, screenshotHeightPx?, screenWidthPt?, screenHeightPt?, executionResult?, executionError?, secondaryWindows?, userGuidance? }`
100
+ - `POST /v1/host-cu-result`: `{ requestId, axTree?, axDiff?, screenshot?, screenshotWidthPx?, screenshotHeightPx?, screenWidthPt?, screenHeightPt?, executionResult?, executionError?, secondaryWindows?, userGuidance?, timings? }`, where `timings` is optional per-phase helper timings in milliseconds
101
101
  - **Tracking**: Uses the same `pending-interactions` tracker as the other host proxy types, with `kind: "host_cu"`. Registration happens in `conversation-routes.ts` and the route handler is in `host-cu-routes.ts`.
102
102
  - **Conversation-agnostic observation**: `observeHostScreen()` in `host-observe.ts` issues a `computer_use_observe` request with no conversation, for callers outside an agent turn (`HostCuProxy` only exists inside one). It takes the initiating actor's principal id and reaches only that actor's own `host_cu` clients: `pickSameUserAutoResolve` picks the default target and `enforceSameActorOrErrorResult` gates an explicitly named one, both before the request is registered or broadcast. Its pending interaction carries no `conversationId`, so `host-cu-routes.ts` hands the raw observation fields straight to the waiting caller instead of routing through a conversation's CU proxy. On the desktop side the ordinary `host_cu` executor services the request.
103
103