@commonlyai/cli 0.1.118 → 0.1.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.118",
3
+ "version": "0.1.120",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -15,6 +15,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, readdirSync
15
15
  import { join, dirname, resolve as pathResolve } from 'path';
16
16
  import { homedir, tmpdir } from 'os';
17
17
  import { fileURLToPath } from 'url';
18
+ import { createHash } from 'crypto';
18
19
 
19
20
  import { createClient } from '../lib/api.js';
20
21
  import {
@@ -1241,6 +1242,16 @@ export const performRun = ({
1241
1242
  `${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`,
1242
1243
  ),
1243
1244
  });
1245
+ // OpenCode retains tool-call IDs in its resumed history. A Gemini proxy
1246
+ // marks those IDs with signature references, so changing providers must
1247
+ // start a fresh session before another upstream can receive them.
1248
+ const sessionBinding = adapter?.name === 'opencode'
1249
+ ? createHash('sha256').update(JSON.stringify([
1250
+ seatEnvironment?.provider?.id || null,
1251
+ seatEnvironment?.provider?.baseURL || null,
1252
+ seatEnvironment?.provider?.keyFile || null,
1253
+ ])).digest('hex')
1254
+ : null;
1244
1255
  let running = true;
1245
1256
  // Stop-after-N-auth-failures: without this, a revoked token leaves the
1246
1257
  // poller hammering 401s forever at 60s backoff — invisible to the user.
@@ -1531,7 +1542,7 @@ export const performRun = ({
1531
1542
  const runTurn = async ({
1532
1543
  event, eventPodId, prompt, preSpawnIds, snapshotMessages, claimKeeper, trigger,
1533
1544
  }) => {
1534
- const sessionId = getSession(agentName, eventPodId);
1545
+ const sessionId = getSession(agentName, eventPodId, { binding: sessionBinding });
1535
1546
  // ADR-005 §Memory bridge: read long_term before spawn, inject via ctx,
1536
1547
  // and (if the adapter returns a summary) patch-sync back after.
1537
1548
  const memoryLongTerm = await readLongTerm(client, { onError });
@@ -1666,7 +1677,7 @@ export const performRun = ({
1666
1677
  }
1667
1678
 
1668
1679
  if (result.newSessionId) {
1669
- setSession(agentName, eventPodId, result.newSessionId);
1680
+ setSession(agentName, eventPodId, result.newSessionId, { binding: sessionBinding });
1670
1681
  }
1671
1682
  // Decide whether to post the CLI's final text. The agent owns its posting:
1672
1683
  // if it already spoke this turn through commonly_post_message, echoing its
@@ -51,6 +51,9 @@ import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
51
51
  import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
52
52
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
53
53
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
54
+ import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
55
+ import { isAnswerableToolError } from '../public-tool-error.js';
56
+ import { createSignatureStore, isGeminiOpenAIUpstream } from '../gemini-signatures.js';
54
57
 
55
58
  const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
56
59
  const TERMINATION_GRACE_MS = 5000;
@@ -297,6 +300,9 @@ const makeEventParser = () => {
297
300
  let text = '';
298
301
  let usage = null;
299
302
  let errorMessage = null;
303
+ // Every tool call that came back as an error, for the public-seat check in
304
+ // spawn (publicToolFailure).
305
+ const toolErrors = [];
300
306
  const consumeLine = (line) => {
301
307
  if (!line.trim()) return;
302
308
  try {
@@ -306,6 +312,12 @@ const makeEventParser = () => {
306
312
  text += event.part.text;
307
313
  } else if (event.type === 'step_finish' && event.part?.tokens) {
308
314
  usage = event.part.tokens;
315
+ } else if (event.type === 'tool_use' && event.part?.state?.status === 'error') {
316
+ const { error } = event.part.state;
317
+ toolErrors.push({
318
+ tool: String(event.part.tool || ''),
319
+ error: typeof error === 'string' ? error : JSON.stringify(error ?? ''),
320
+ });
309
321
  } else if (event.type === 'error') {
310
322
  errorMessage = event.error?.data?.message || event.error?.message || 'OpenCode turn failed';
311
323
  }
@@ -332,9 +344,50 @@ const makeEventParser = () => {
332
344
  get text() { return text; },
333
345
  get usage() { return usage; },
334
346
  get errorMessage() { return errorMessage; },
347
+ get toolErrors() { return toolErrors; },
335
348
  };
336
349
  };
337
350
 
351
+ // A public seat must never show a stranger its own plumbing. When a Commonly
352
+ // tool can't reach the API, the model is left narrating the failure, and the
353
+ // run loop posted that narration: on 2026-10-21 a canary of Commonly HQ's
354
+ // support seat (this adapter, its prompt, an unreachable API) told the asker
355
+ // "every Commonly tool call (`list_pods`, `list_artifacts`) is returning
356
+ // `fetch failed`", and an instruction to answer NO_REPLY in that case held in
357
+ // only 1 of 3 turns. So the turn is withheld here instead: nothing is posted,
358
+ // and the run loop keeps the event unacked for its retry.
359
+ //
360
+ // OpenCode names an MCP tool `<server>_<tool>`, and a failed call reports
361
+ // `state.status: 'error'` with the message in `state.error` (measured on
362
+ // OpenCode 1.19.0). Only tools of the declared Commonly server count. Of
363
+ // those, only the errors `isAnswerableToolError` names (an API refusal the
364
+ // person can be told about, or a schema mistake the model fixes) leave the
365
+ // turn to be posted; any other failure withholds it. This adapter-level check
366
+ // stays beside the adapter-agnostic readiness witness (TASK-256): it sees the
367
+ // runtime's own view of each call, and the witness sees a server that never
368
+ // started, so each catches what the other cannot.
369
+ export const PUBLIC_TOOL_FAILED_CODE = 'public_tool_failed';
370
+
371
+ export const publicToolFailure = (toolErrors, mcpServers) => {
372
+ const prefixes = (Array.isArray(mcpServers) ? mcpServers : [])
373
+ .filter((server) => server?.name && isShippedCommonlyMcpCommand(server.command))
374
+ .map((server) => `${server.name}_`);
375
+ if (!prefixes.length) return null;
376
+ return (toolErrors || []).find(({ tool, error }) => (
377
+ prefixes.some((prefix) => tool.startsWith(prefix)) && !isAnswerableToolError(error)
378
+ )) || null;
379
+ };
380
+
381
+ const publicToolFailedError = ({ tool, error }) => {
382
+ const reason = String(error).replace(/\s+/g, ' ').slice(0, 160) || '(empty error)';
383
+ const failure = new Error(
384
+ `public seat withheld this turn's reply: Commonly tool ${tool} failed in a way the model must not narrate `
385
+ + `(${reason}), so nothing was posted and the event stays unacked for retry`,
386
+ );
387
+ failure.code = PUBLIC_TOOL_FAILED_CODE;
388
+ return failure;
389
+ };
390
+
338
391
  const runOpenCode = ({ cmd, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
339
392
  let proc;
340
393
  try {
@@ -376,7 +429,9 @@ const runOpenCode = ({ cmd, args, cwd, env, timeoutMs, credentials, spawnImpl =
376
429
  credentials, exitCode: code, limit: 500,
377
430
  }));
378
431
  }
379
- resolve({ sessionId: events.sessionId, text: events.text, usage: events.usage });
432
+ resolve({
433
+ sessionId: events.sessionId, text: events.text, usage: events.usage, toolErrors: events.toolErrors,
434
+ });
380
435
  });
381
436
  });
382
437
 
@@ -658,13 +713,26 @@ export default {
658
713
  let providerProxy = null;
659
714
  try {
660
715
  openCodeHome = await prepareOpenCodeDataHome(ctx, { publicSeat: isPublic });
661
- if (isPublic && provider) {
716
+ // Gemini 3 needs its thought signatures back on the next request, and
717
+ // OpenCode's provider drops them (gemini-signatures.js), so a Gemini seat
718
+ // goes through the proxy whatever its trust. The signatures are kept per
719
+ // seat under ~/.commonly, outside the workspace and OpenCode's own home.
720
+ const geminiUpstream = Boolean(provider) && isGeminiOpenAIUpstream(provider.baseURL);
721
+ if ((isPublic || geminiUpstream) && provider) {
722
+ let signatureStore = null;
723
+ if (geminiUpstream) {
724
+ const seat = createHash('sha256').update(seatIdentity(ctx)).digest('hex').slice(0, 24);
725
+ signatureStore = createSignatureStore(ctx._geminiSignatureDir
726
+ || join(homedir(), '.commonly', 'gemini-signatures', seat));
727
+ await signatureStore.prune();
728
+ }
662
729
  // OpenCode can spend the configured model budget through this proxy;
663
730
  // the bearer only prevents unrelated local processes from using it.
664
731
  providerProxy = await startProviderProxy({
665
732
  provider,
666
733
  keyFile: providerKeyFile,
667
734
  tokenFile: join(tempDir, 'provider-proxy-token'),
735
+ signatureStore,
668
736
  });
669
737
  }
670
738
  const stateHome = isPublic ? join(openCodeHome.root, 'state') : null;
@@ -783,6 +851,10 @@ export default {
783
851
  credentials,
784
852
  spawnImpl: ctx._spawnImpl,
785
853
  });
854
+ if (isPublic) {
855
+ const failure = publicToolFailure(result.toolErrors, ctx.environment?.mcp);
856
+ if (failure) throw publicToolFailedError(failure);
857
+ }
786
858
  return {
787
859
  text: result.text.trim(),
788
860
  newSessionId: result.sessionId || ctx.sessionId || null,
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Gemini thought signatures through an OpenAI-compatible client.
3
+ *
4
+ * Gemini 3 signs the function calls of each step it thinks through and turns
5
+ * the next request away without that signature back on the call: 400
6
+ * "Function call is missing a thought_signature in functionCall parts". Its
7
+ * OpenAI-compatible API returns the signature beside the call, in
8
+ * tool_calls[].extra_content.google.thought_signature, and takes it back
9
+ * there. OpenCode's provider (@ai-sdk/openai-compatible) knows no such field
10
+ * and drops it, so every Gemini 3 tool loop through OpenCode failed on its
11
+ * second request (walked 2026-10-19).
12
+ *
13
+ * Every Chat client does send a call's id back as it was given. So the proxy
14
+ * gives the client an id carrying a short reference to the signature,
15
+ * `<id>__cmts16__<key>`, keeps the signature in a store under that key, and on
16
+ * the way back takes the reference off the id and puts the signature into
17
+ * extra_content. A call whose signature can't be recovered (another model's
18
+ * call, an id the client shortened, a store that lost it) goes to Gemini with
19
+ * `skip_thought_signature_validator`, the value Google documents for history
20
+ * it didn't sign.
21
+ *
22
+ * The approach is yetone's, from magpie's gateway
23
+ * (https://github.com/yetone/magpie, internal/gateway/gemini_signature.go and
24
+ * gemini_sigstore.go at a9304efe). This is a separate JavaScript
25
+ * implementation for Commonly's per-spawn provider proxy, and magpie's notice
26
+ * is reproduced here:
27
+ *
28
+ * MIT License
29
+ *
30
+ * Copyright (c) 2026 yetone
31
+ *
32
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ * of this software and associated documentation files (the "Software"), to deal
34
+ * in the Software without restriction, including without limitation the rights
35
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ * copies of the Software, and to permit persons to whom the Software is
37
+ * furnished to do so, subject to the following conditions:
38
+ *
39
+ * The above copyright notice and this permission notice shall be included in all
40
+ * copies or substantial portions of the Software.
41
+ *
42
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
48
+ * SOFTWARE.
49
+ */
50
+ import { createHash, randomBytes } from 'crypto';
51
+ import {
52
+ mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile,
53
+ } from 'fs/promises';
54
+ import { join } from 'path';
55
+ import { StringDecoder } from 'string_decoder';
56
+
57
+ /** The hosts whose OpenAI-compatible API needs signatures carried back. */
58
+ const GEMINI_OPENAI_HOSTS = new Set(['generativelanguage.googleapis.com']);
59
+
60
+ export const isGeminiOpenAIUpstream = (baseURL) => {
61
+ try {
62
+ return GEMINI_OPENAI_HOSTS.has(new URL(baseURL).hostname.toLowerCase());
63
+ } catch {
64
+ return false;
65
+ }
66
+ };
67
+
68
+ export const SKIP_SIGNATURE = 'skip_thought_signature_validator';
69
+
70
+ // The reference in an id: MARK, the key's length, `__`, the key. The length
71
+ // tells a whole key from one a client cut short, which then reads as no
72
+ // signature rather than as some other key.
73
+ const MARK = '__cmts';
74
+ const KEY_BYTES = 12; // 16 base64url characters
75
+ const KEY_LENGTH = 16;
76
+ const SIGNED_ID_RE = new RegExp(`^([\\s\\S]*?)${MARK}(\\d+)__([A-Za-z0-9_-]*)$`);
77
+
78
+ export const signedId = (id, key) => `${id}${MARK}${key.length}__${key}`;
79
+
80
+ /** `{ id, key }`: the call's own id and its signature's key, or the id as given and null. */
81
+ export const unsignedId = (id) => {
82
+ if (typeof id !== 'string') return { id, key: null };
83
+ const match = SIGNED_ID_RE.exec(id);
84
+ if (!match || Number(match[2]) !== match[3].length || match[3].length !== KEY_LENGTH) {
85
+ return { id, key: null };
86
+ }
87
+ return { id: match[1], key: match[3] };
88
+ };
89
+
90
+ const signatureKey = (signature) => createHash('sha256').update(signature).digest()
91
+ .subarray(0, KEY_BYTES).toString('base64url');
92
+
93
+ const SIGNATURE_KEEP_MS = 30 * 24 * 60 * 60 * 1000;
94
+
95
+ /**
96
+ * Signatures by key: in memory for this spawn, and in `dir` (0700, one 0600
97
+ * file per signature, named by its hash) so a seat's next turn finds the calls
98
+ * its earlier turns made. Without a dir it is memory only. A file is written
99
+ * whole, staged then renamed. A failed write or read is no signature, which
100
+ * Gemini takes as unsigned history.
101
+ */
102
+ export const createSignatureStore = (dir = null) => {
103
+ const memory = new Map();
104
+ let ready = null;
105
+ const ensureDir = () => {
106
+ if (!dir) return Promise.resolve(false);
107
+ ready = ready || mkdir(dir, { recursive: true, mode: 0o700 }).then(() => true, () => false);
108
+ return ready;
109
+ };
110
+ return {
111
+ async keep(signature) {
112
+ const key = signatureKey(signature);
113
+ memory.set(key, signature);
114
+ if (await ensureDir()) {
115
+ const target = join(dir, key);
116
+ const staged = `${target}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
117
+ try {
118
+ await writeFile(staged, signature, { encoding: 'utf8', mode: 0o600 });
119
+ await rename(staged, target);
120
+ } catch {
121
+ await rm(staged, { force: true }).catch(() => {});
122
+ }
123
+ }
124
+ return key;
125
+ },
126
+ async lookup(key) {
127
+ if (memory.has(key)) return memory.get(key);
128
+ if (!dir || !/^[A-Za-z0-9_-]{16}$/.test(key)) return null;
129
+ try {
130
+ const path = join(dir, key);
131
+ const signature = await readFile(path, 'utf8');
132
+ if (!signature || signatureKey(signature) !== key) return null;
133
+ const now = new Date();
134
+ await utimes(path, now, now).catch(() => {});
135
+ memory.set(key, signature);
136
+ return signature;
137
+ } catch {
138
+ return null;
139
+ }
140
+ },
141
+ /** Remove signatures not read for 30 days, and staged files left behind. */
142
+ async prune(now = Date.now()) {
143
+ if (!dir) return;
144
+ let names = [];
145
+ try { names = await readdir(dir); } catch { return; }
146
+ await Promise.all(names.map(async (name) => {
147
+ try {
148
+ const details = await stat(join(dir, name));
149
+ const age = now - details.mtimeMs;
150
+ if (age > SIGNATURE_KEEP_MS || (name.endsWith('.tmp') && age > 60 * 60 * 1000)) {
151
+ await rm(join(dir, name), { force: true });
152
+ }
153
+ } catch { /* gone already */ }
154
+ }));
155
+ },
156
+ };
157
+ };
158
+
159
+ const googleSignature = (call) => {
160
+ const signature = call?.extra_content?.google?.thought_signature;
161
+ return typeof signature === 'string' && signature ? signature : null;
162
+ };
163
+
164
+ /**
165
+ * A chat/completions request body for Gemini with the references taken off
166
+ * its call ids and each signed step's signature back in extra_content. Gemini
167
+ * signs the first call of a step, so only a step with no signature at all gets
168
+ * the skip value, on every call. Returns the body unchanged when it is not
169
+ * JSON or nothing changed.
170
+ */
171
+ export const restoreRequestSignatures = async (body, store) => {
172
+ let request;
173
+ try { request = JSON.parse(body.toString('utf8')); } catch { return body; }
174
+ if (!request || !Array.isArray(request.messages)) return body;
175
+ let changed = false;
176
+ for (const message of request.messages) {
177
+ if (!message || typeof message !== 'object') continue;
178
+ if (typeof message.tool_call_id === 'string') {
179
+ const { id, key } = unsignedId(message.tool_call_id);
180
+ if (key) { message.tool_call_id = id; changed = true; }
181
+ }
182
+ if (!Array.isArray(message.tool_calls) || message.tool_calls.length === 0) continue;
183
+ const signatures = [];
184
+ for (const call of message.tool_calls) {
185
+ let signature = googleSignature(call);
186
+ const { id, key } = unsignedId(call?.id);
187
+ if (key) {
188
+ call.id = id;
189
+ changed = true;
190
+ // eslint-disable-next-line no-await-in-loop
191
+ signature = signature || await store.lookup(key);
192
+ }
193
+ signatures.push(signature);
194
+ }
195
+ const signedStep = signatures.some(Boolean);
196
+ message.tool_calls.forEach((call, index) => {
197
+ if (!call || typeof call !== 'object') return;
198
+ const signature = signatures[index] || (signedStep ? null : SKIP_SIGNATURE);
199
+ if (!signature || googleSignature(call) === signature) return;
200
+ call.extra_content = { ...(call.extra_content || {}), google: { ...(call.extra_content?.google || {}), thought_signature: signature } };
201
+ changed = true;
202
+ });
203
+ }
204
+ return changed ? Buffer.from(JSON.stringify(request), 'utf8') : body;
205
+ };
206
+
207
+ /** Give each signed call in one reply (or one streamed chunk) an id carrying its key. */
208
+ const signReplyObject = async (reply, store) => {
209
+ if (!reply || !Array.isArray(reply.choices)) return false;
210
+ let changed = false;
211
+ for (const choice of reply.choices) {
212
+ for (const field of ['message', 'delta']) {
213
+ const calls = choice?.[field]?.tool_calls;
214
+ if (!Array.isArray(calls)) continue;
215
+ for (const call of calls) {
216
+ const signature = googleSignature(call);
217
+ if (!signature || typeof call.id !== 'string' || !call.id) continue;
218
+ if (unsignedId(call.id).key) continue;
219
+ // eslint-disable-next-line no-await-in-loop
220
+ call.id = signedId(call.id, await store.keep(signature));
221
+ changed = true;
222
+ }
223
+ }
224
+ }
225
+ return changed;
226
+ };
227
+
228
+ const SIGNATURE_FIELD = '"thought_signature"';
229
+
230
+ /**
231
+ * Rewrites a Gemini chat/completions reply as it streams to the client. An SSE
232
+ * reply is rewritten line by line, and a line passes as it came unless it is a
233
+ * `data:` chunk carrying a signature; any other reply is rewritten whole at
234
+ * the end. `write` and `end` return the bytes to send now.
235
+ */
236
+ export const createReplySigner = ({ store, sse }) => {
237
+ // A chunk can end inside a multi-byte character; decode across chunks.
238
+ const decoder = new StringDecoder('utf8');
239
+ let pending = '';
240
+ const signLine = async (line) => {
241
+ if (!line.includes(SIGNATURE_FIELD)) return line;
242
+ const body = line.replace(/\r?\n$/, '');
243
+ if (!body.startsWith('data:')) return line;
244
+ let chunk;
245
+ try { chunk = JSON.parse(body.slice(5).trim()); } catch { return line; }
246
+ if (!await signReplyObject(chunk, store)) return line;
247
+ return `data: ${JSON.stringify(chunk)}${line.slice(body.length)}`;
248
+ };
249
+ const signLines = async (text) => {
250
+ if (!text.includes(SIGNATURE_FIELD)) return text;
251
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g) || [];
252
+ const out = [];
253
+ // eslint-disable-next-line no-await-in-loop
254
+ for (const line of lines) out.push(await signLine(line));
255
+ return out.join('');
256
+ };
257
+ return {
258
+ async write(chunk) {
259
+ pending += decoder.write(chunk);
260
+ if (!sse) return '';
261
+ const cut = pending.lastIndexOf('\n');
262
+ if (cut < 0) return '';
263
+ const complete = pending.slice(0, cut + 1);
264
+ pending = pending.slice(cut + 1);
265
+ return signLines(complete);
266
+ },
267
+ async end() {
268
+ const rest = pending + decoder.end();
269
+ pending = '';
270
+ if (sse) return signLines(rest);
271
+ if (!rest.includes(SIGNATURE_FIELD)) return rest;
272
+ let reply;
273
+ try { reply = JSON.parse(rest); } catch { return rest; }
274
+ return await signReplyObject(reply, store) ? JSON.stringify(reply) : rest;
275
+ },
276
+ };
277
+ };
@@ -5,6 +5,11 @@ import { createServer, request as httpRequest } from 'http';
5
5
  import { request as httpsRequest } from 'https';
6
6
  import { chmod, lstat, open, writeFile } from 'fs/promises';
7
7
  import { isAbsolute, relative, sep } from 'path';
8
+ import { createReplySigner, restoreRequestSignatures } from './gemini-signatures.js';
9
+
10
+ // A chat request is buffered only to restore Gemini's thought signatures; a
11
+ // body past this is refused rather than held in memory.
12
+ const SIGNED_REQUEST_MAX_BYTES = 64 * 1024 * 1024;
8
13
 
9
14
  const isPathWithin = (parent, candidate) => {
10
15
  const fromParent = relative(parent, candidate);
@@ -67,7 +72,15 @@ const readProviderKey = async (keyFile, adapterLabel) => {
67
72
  }
68
73
  };
69
74
 
70
- export const startProviderProxy = async ({ provider, keyFile, tokenFile, adapterLabel = 'OpenCode' }) => {
75
+ /**
76
+ * `signatureStore` (gemini-signatures.js) turns on Gemini's thought-signature
77
+ * round trip for chat/completions: ids in replies carry a reference, and the
78
+ * next request gets the signatures back. Without it every request and reply is
79
+ * piped through unchanged, as for every other provider.
80
+ */
81
+ export const startProviderProxy = async ({
82
+ provider, keyFile, tokenFile, adapterLabel = 'OpenCode', signatureStore = null,
83
+ }) => {
71
84
  const upstream = new URL(provider.baseURL);
72
85
  if (!['http:', 'https:'].includes(upstream.protocol)
73
86
  || upstream.username || upstream.password || upstream.search || upstream.hash) {
@@ -170,6 +183,9 @@ export const startProviderProxy = async ({ provider, keyFile, tokenFile, adapter
170
183
  ].includes(name.toLowerCase())));
171
184
  headers.authorization = `Bearer ${upstreamKey}`;
172
185
  headers.host = target.host;
186
+ const signing = Boolean(signatureStore) && target.path.endsWith('/chat/completions');
187
+ // The reply is rewritten, so ask for it uncompressed.
188
+ if (signing) headers['accept-encoding'] = 'identity';
173
189
  const request = (target.protocol === 'https:' ? httpsRequest : httpRequest)({
174
190
  protocol: target.protocol,
175
191
  hostname: target.hostname,
@@ -187,9 +203,31 @@ export const startProviderProxy = async ({ provider, keyFile, tokenFile, adapter
187
203
  .filter(([name]) => ![
188
204
  'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
189
205
  'te', 'trailer', 'transfer-encoding', 'upgrade',
206
+ ...(signing ? ['content-length'] : []),
190
207
  ].includes(name.toLowerCase())));
191
208
  outgoing.writeHead(response.statusCode || 502, responseHeaders);
192
- response.pipe(outgoing);
209
+ if (!signing) {
210
+ response.pipe(outgoing);
211
+ return;
212
+ }
213
+ const signer = createReplySigner({
214
+ store: signatureStore,
215
+ sse: /text\/event-stream/i.test(String(response.headers['content-type'] || '')),
216
+ });
217
+ // Chunks are signed in order; each waits for the one before it. A step
218
+ // that fails ends the reply rather than leaving a rejection unhandled,
219
+ // which would take the whole CLI process down.
220
+ let sent = Promise.resolve();
221
+ const open = () => !outgoing.destroyed && !outgoing.writableEnded;
222
+ const send = (produce) => {
223
+ sent = sent.then(produce).then((text) => { if (text && open()) outgoing.write(text); });
224
+ return sent;
225
+ };
226
+ response.on('data', (chunk) => { send(() => signer.write(chunk)).catch(() => outgoing.destroy()); });
227
+ response.on('end', () => {
228
+ send(() => signer.end()).catch(() => {}).finally(() => { if (open()) outgoing.end(); });
229
+ });
230
+ response.on('error', () => outgoing.destroy());
193
231
  });
194
232
  request.on('error', () => {
195
233
  if (!outgoing.headersSent) outgoing.writeHead(502);
@@ -197,7 +235,36 @@ export const startProviderProxy = async ({ provider, keyFile, tokenFile, adapter
197
235
  });
198
236
  outgoing.on('close', () => request.destroy());
199
237
  incoming.on('aborted', () => request.destroy());
200
- incoming.pipe(request);
238
+ if (!signing || incoming.method !== 'POST') {
239
+ incoming.pipe(request);
240
+ return;
241
+ }
242
+ const parts = [];
243
+ let size = 0;
244
+ let refused = false;
245
+ incoming.on('data', (chunk) => {
246
+ if (refused) return;
247
+ size += chunk.length;
248
+ if (size > SIGNED_REQUEST_MAX_BYTES) {
249
+ refused = true;
250
+ request.destroy();
251
+ if (!outgoing.headersSent) outgoing.writeHead(413);
252
+ outgoing.end();
253
+ return;
254
+ }
255
+ parts.push(chunk);
256
+ });
257
+ incoming.on('end', () => {
258
+ if (refused) return;
259
+ restoreRequestSignatures(Buffer.concat(parts), signatureStore).then((body) => {
260
+ request.setHeader('content-length', body.length);
261
+ request.end(body);
262
+ }, () => {
263
+ request.destroy();
264
+ if (!outgoing.headersSent) outgoing.writeHead(502);
265
+ outgoing.end('Provider request failed');
266
+ });
267
+ });
201
268
  });
202
269
 
203
270
  await new Promise((resolve, reject) => {
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Which failed Commonly tool calls a public seat's model may answer in plain
3
+ * words. Everything else withholds the turn (#2374, Vera 79595, Wren 79596).
4
+ *
5
+ * The rule is inverted on purpose. Matching known connection failures let an
6
+ * API 5xx through: the shipped MCP turns a non-2xx into a tool error carrying
7
+ * the status, and during a rollout the ingress answers 503 while the socket
8
+ * connects, so the model narrated the outage to a stranger. A list of failures
9
+ * fails open on the next one nobody listed; a list of answers fails closed.
10
+ *
11
+ * The answerable ones:
12
+ * - an API refusal the person can be told about: 400, 403, 404, 409, 410, 413
13
+ * or 422. 401 is NOT among them: a seat whose token the API rejects is
14
+ * broken plumbing, and every later call fails the same way.
15
+ * - the runtime's own schema check, which the model fixes on its next call.
16
+ * OpenCode 1.19.0 words it "The <tool> tool was called with invalid
17
+ * arguments: …" (ToolInvalidArgumentsError, read from the shipped binary).
18
+ *
19
+ * Everything else withholds: a 5xx, 401, 429 or any other status; a tool error
20
+ * with no status (the shipped MCP's network, timeout and token failures); an
21
+ * MCP transport error ("MCP error -32000: Connection closed"); an empty error;
22
+ * and any text this module does not recognise.
23
+ *
24
+ * How the status arrives: the shipped MCP answers a failed call with
25
+ * `isError: true` and one text part, `JSON.stringify({ status, body, message })`
26
+ * for an HTTP error or `{ message }` otherwise (commonly-mcp/src/tools.js,
27
+ * `err`). OpenCode throws that text as the tool's error, so the event's
28
+ * `state.error` is the JSON (measured on the 2026-10-21 canary).
29
+ *
30
+ * The TASK-256 readiness witness uses this same predicate, so the two
31
+ * witnesses cannot disagree about what counts as a failure.
32
+ */
33
+
34
+ export const ANSWERABLE_API_STATUSES = new Set([400, 403, 404, 409, 410, 413, 422]);
35
+
36
+ const INVALID_ARGUMENTS_RE = /^The \S+ tool was called with invalid arguments: /;
37
+
38
+ const parsePayload = (text) => {
39
+ try {
40
+ const parsed = JSON.parse(text);
41
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+
47
+ /** Whether a failed tool call's error text is one the model may answer. */
48
+ export const isAnswerableToolError = (error) => {
49
+ const text = typeof error === 'string' ? error.trim() : '';
50
+ if (!text) return false;
51
+ if (INVALID_ARGUMENTS_RE.test(text)) return true;
52
+ const payload = parsePayload(text);
53
+ return Boolean(payload && Number.isInteger(payload.status) && ANSWERABLE_API_STATUSES.has(payload.status));
54
+ };
@@ -82,9 +82,11 @@ const writeHandledEvents = (agentName, ids) => {
82
82
  writeFileSync(handledEventsFile(agentName), JSON.stringify(ids, null, 2), 'utf8');
83
83
  };
84
84
 
85
- export const getSession = (agentName, podId) => {
85
+ export const getSession = (agentName, podId, { binding = null } = {}) => {
86
86
  if (!agentName || !podId) return null;
87
- return readAgent(agentName)[podId]?.sessionId || null;
87
+ const entry = readAgent(agentName)[podId];
88
+ if (binding !== null && entry?.binding !== binding) return null;
89
+ return entry?.sessionId || null;
88
90
  };
89
91
 
90
92
  // Read-only diagnostic projection used by the daemon operator surface. A
@@ -99,10 +101,14 @@ export const getLastTurn = (agentName) => {
99
101
  .at(-1) || null;
100
102
  };
101
103
 
102
- export const setSession = (agentName, podId, sessionId) => {
104
+ export const setSession = (agentName, podId, sessionId, { binding = null } = {}) => {
103
105
  if (!agentName || !podId) return;
104
106
  const state = readAgent(agentName);
105
- state[podId] = { sessionId, lastTurn: new Date().toISOString() };
107
+ state[podId] = {
108
+ sessionId,
109
+ lastTurn: new Date().toISOString(),
110
+ ...(binding !== null ? { binding } : {}),
111
+ };
106
112
  writeAgent(agentName, state);
107
113
  };
108
114