@commonlyai/cli 0.1.119 → 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 +1 -1
- package/src/commands/agent.js +13 -2
- package/src/lib/adapters/opencode.js +15 -1
- package/src/lib/gemini-signatures.js +277 -0
- package/src/lib/provider-proxy.js +70 -3
- package/src/lib/session-store.js +10 -4
package/package.json
CHANGED
package/src/commands/agent.js
CHANGED
|
@@ -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
|
|
@@ -53,6 +53,7 @@ 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';
|
|
56
57
|
|
|
57
58
|
const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
|
|
58
59
|
const TERMINATION_GRACE_MS = 5000;
|
|
@@ -712,13 +713,26 @@ export default {
|
|
|
712
713
|
let providerProxy = null;
|
|
713
714
|
try {
|
|
714
715
|
openCodeHome = await prepareOpenCodeDataHome(ctx, { publicSeat: isPublic });
|
|
715
|
-
|
|
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
|
+
}
|
|
716
729
|
// OpenCode can spend the configured model budget through this proxy;
|
|
717
730
|
// the bearer only prevents unrelated local processes from using it.
|
|
718
731
|
providerProxy = await startProviderProxy({
|
|
719
732
|
provider,
|
|
720
733
|
keyFile: providerKeyFile,
|
|
721
734
|
tokenFile: join(tempDir, 'provider-proxy-token'),
|
|
735
|
+
signatureStore,
|
|
722
736
|
});
|
|
723
737
|
}
|
|
724
738
|
const stateHome = isPublic ? join(openCodeHome.root, 'state') : 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
|
-
|
|
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
|
-
|
|
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.
|
|
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) => {
|
package/src/lib/session-store.js
CHANGED
|
@@ -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
|
-
|
|
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] = {
|
|
107
|
+
state[podId] = {
|
|
108
|
+
sessionId,
|
|
109
|
+
lastTurn: new Date().toISOString(),
|
|
110
|
+
...(binding !== null ? { binding } : {}),
|
|
111
|
+
};
|
|
106
112
|
writeAgent(agentName, state);
|
|
107
113
|
};
|
|
108
114
|
|