@commonlyai/cli 0.1.153 → 0.1.154

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.153",
3
+ "version": "0.1.154",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -53,7 +53,6 @@ import { resolvePublicSandboxMode } from '../sandbox/mode.js';
53
53
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
54
54
  import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
55
55
  import { isAnswerableToolError } from '../public-tool-error.js';
56
- import { createSignatureStore, isGeminiOpenAIUpstream } from '../gemini-signatures.js';
57
56
 
58
57
  const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
59
58
  const TERMINATION_GRACE_MS = 5000;
@@ -585,6 +584,8 @@ const readOpenCodeVersion = (binary, env) => {
585
584
  }
586
585
  };
587
586
 
587
+ const isOpenCodePrerelease = (version) => version.split('+', 1)[0].includes('-');
588
+
588
589
  const compareOpenCodeVersions = (left, right) => {
589
590
  const leftParts = left.split(/[+-]/, 1)[0].split('.').map(Number);
590
591
  const rightParts = right.split(/[+-]/, 1)[0].split('.').map(Number);
@@ -593,6 +594,11 @@ const compareOpenCodeVersions = (left, right) => {
593
594
  return leftParts[index] > rightParts[index] ? 1 : -1;
594
595
  }
595
596
  }
597
+ // The smoke-tested boundaries are stable releases. A matching prerelease
598
+ // must not inherit their native signature-replay guarantee.
599
+ const leftPrerelease = isOpenCodePrerelease(left);
600
+ const rightPrerelease = isOpenCodePrerelease(right);
601
+ if (leftPrerelease !== rightPrerelease) return leftPrerelease ? -1 : 1;
596
602
  return 0;
597
603
  };
598
604
 
@@ -666,6 +672,16 @@ export default {
666
672
  : childSourceEnv;
667
673
  const binary = ctx._binaryPath || spawnBinaryPath(runtimeEnv);
668
674
  const installedVersion = readOpenCodeVersion(binary, runtimeEnv);
675
+ // Trusted seats otherwise allow old binaries. Gemini requires a stable
676
+ // release with native signature replay now that the proxy shim is gone.
677
+ if (provider && new URL(provider.baseURL).hostname.toLowerCase() === 'generativelanguage.googleapis.com'
678
+ && (!installedVersion || isOpenCodePrerelease(installedVersion)
679
+ || compareOpenCodeVersions(installedVersion, TESTED_OPENCODE_VERSIONS[0]) < 0)) {
680
+ throw new Error(
681
+ `Gemini requires stable OpenCode ${TESTED_OPENCODE_VERSIONS[0]} or later for native thought-signature replay; `
682
+ + `installed version is ${installedVersion || 'unknown'}`,
683
+ );
684
+ }
669
685
  if (!TESTED_OPENCODE_VERSIONS.includes(installedVersion)) {
670
686
  const mismatch = describeOpenCodeVersionMismatch(installedVersion);
671
687
  const allowOverride = process.env[ALLOW_UNTESTED_OPENCODE_VERSION_ENV] === '1';
@@ -713,26 +729,13 @@ export default {
713
729
  let providerProxy = null;
714
730
  try {
715
731
  openCodeHome = await prepareOpenCodeDataHome(ctx, { publicSeat: isPublic });
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
- }
732
+ if (isPublic && provider) {
729
733
  // OpenCode can spend the configured model budget through this proxy;
730
734
  // the bearer only prevents unrelated local processes from using it.
731
735
  providerProxy = await startProviderProxy({
732
736
  provider,
733
737
  keyFile: providerKeyFile,
734
738
  tokenFile: join(tempDir, 'provider-proxy-token'),
735
- signatureStore,
736
739
  });
737
740
  }
738
741
  const stateHome = isPublic ? join(openCodeHome.root, 'state') : null;
@@ -5,11 +5,6 @@ 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;
13
8
 
14
9
  const isPathWithin = (parent, candidate) => {
15
10
  const fromParent = relative(parent, candidate);
@@ -72,14 +67,8 @@ const readProviderKey = async (keyFile, adapterLabel) => {
72
67
  }
73
68
  };
74
69
 
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
70
  export const startProviderProxy = async ({
82
- provider, keyFile, tokenFile, adapterLabel = 'OpenCode', signatureStore = null,
71
+ provider, keyFile, tokenFile, adapterLabel = 'OpenCode',
83
72
  }) => {
84
73
  const upstream = new URL(provider.baseURL);
85
74
  if (!['http:', 'https:'].includes(upstream.protocol)
@@ -183,9 +172,6 @@ export const startProviderProxy = async ({
183
172
  ].includes(name.toLowerCase())));
184
173
  headers.authorization = `Bearer ${upstreamKey}`;
185
174
  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';
189
175
  const request = (target.protocol === 'https:' ? httpsRequest : httpRequest)({
190
176
  protocol: target.protocol,
191
177
  hostname: target.hostname,
@@ -203,31 +189,9 @@ export const startProviderProxy = async ({
203
189
  .filter(([name]) => ![
204
190
  'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
205
191
  'te', 'trailer', 'transfer-encoding', 'upgrade',
206
- ...(signing ? ['content-length'] : []),
207
192
  ].includes(name.toLowerCase())));
208
193
  outgoing.writeHead(response.statusCode || 502, responseHeaders);
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());
194
+ response.pipe(outgoing);
231
195
  });
232
196
  request.on('error', () => {
233
197
  if (!outgoing.headersSent) outgoing.writeHead(502);
@@ -235,36 +199,7 @@ export const startProviderProxy = async ({
235
199
  });
236
200
  outgoing.on('close', () => request.destroy());
237
201
  incoming.on('aborted', () => request.destroy());
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
- });
202
+ incoming.pipe(request);
268
203
  });
269
204
 
270
205
  await new Promise((resolve, reject) => {
@@ -1,277 +0,0 @@
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
- };