@commonlyai/cli 0.1.119 → 0.1.121
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/goose.js +254 -0
- package/src/lib/adapters/index.js +2 -0
- package/src/lib/adapters/opencode.js +15 -1
- package/src/lib/default-environment.js +5 -2
- 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
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/** Goose 1.54.0 wrapper. Public seats wait for TASK-236's deny-by-default proof. */
|
|
2
|
+
import { spawn as childSpawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
7
|
+
import { buildMemoryPreamble } from '../memory-bridge.js';
|
|
8
|
+
import { effectiveSandboxTrust, validateEnvironmentSpec } from '../environment.js';
|
|
9
|
+
import { writeCredentialFile } from '../credential-file.js';
|
|
10
|
+
import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
|
|
11
|
+
import { prepareMcpSpawn } from '../mcp-home.js';
|
|
12
|
+
import { resolveProviderKeyFile } from '../provider-proxy.js';
|
|
13
|
+
import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
|
|
14
|
+
|
|
15
|
+
// A version enters this list only after a real headless turn with that binary.
|
|
16
|
+
export const TESTED_GOOSE_VERSIONS = Object.freeze(['1.54.0']);
|
|
17
|
+
const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
|
|
18
|
+
const TERMINATION_GRACE_MS = 5000;
|
|
19
|
+
const DEFAULT_MODEL = 'deepseek-v4-flash';
|
|
20
|
+
const DEFAULT_PROVIDER_HOST = 'https://litellm.commonly.me';
|
|
21
|
+
const DEFAULT_PROVIDER_KEY = 'COMMONLY_LITELLM_KEY';
|
|
22
|
+
const PLACEHOLDER_RE = /\$\{(COMMONLY_[A-Z_]+)\}/g;
|
|
23
|
+
const SAFE_ENV = /^(?:PATH|LANG|LC_[A-Z_]+|TERM|USER|LOGNAME|NO_COLOR|CI|SSL_CERT_FILE|SSL_CERT_DIR)$/;
|
|
24
|
+
|
|
25
|
+
export const assertNoSandboxDeclared = (environment = {}) => {
|
|
26
|
+
const sandbox = environment?.sandbox || {};
|
|
27
|
+
if (effectiveSandboxTrust(sandbox.trust) === 'public') {
|
|
28
|
+
throw new Error('goose adapter: public-trust seats are not supported until the deny-by-default attack test passes');
|
|
29
|
+
}
|
|
30
|
+
if (sandbox.mode && sandbox.mode !== 'none') {
|
|
31
|
+
throw new Error(`goose adapter: sandbox.mode=${sandbox.mode} cannot be enforced by Goose`);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const versionOf = (value) => String(value || '').trim().match(/\b(\d+\.\d+\.\d+)\b/)?.[1] || null;
|
|
36
|
+
|
|
37
|
+
/** Goose splits this string itself; reject quotes it cannot represent safely. */
|
|
38
|
+
const gooseWord = (value) => {
|
|
39
|
+
const word = String(value);
|
|
40
|
+
if (!word || /["\r\n\0]/.test(word)) throw new Error('goose adapter: MCP argument contains an unsupported character');
|
|
41
|
+
return `"${word}"`;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const substitute = (value, ctx) => String(value).replace(PLACEHOLDER_RE, (whole, name) => ({
|
|
45
|
+
COMMONLY_TOKEN_FILE: ctx.credentialFile,
|
|
46
|
+
COMMONLY_API_URL: ctx.instanceUrl,
|
|
47
|
+
COMMONLY_INSTANCE_URL: ctx.instanceUrl,
|
|
48
|
+
}[name] || whole));
|
|
49
|
+
|
|
50
|
+
/** The flag contains paths and URLs only. Literal MCP secrets cannot ride argv. */
|
|
51
|
+
export const extensionArgs = (servers, ctx) => {
|
|
52
|
+
const args = [];
|
|
53
|
+
for (const server of servers || []) {
|
|
54
|
+
if (!/^[A-Za-z0-9_-]{2,}$/.test(server?.name || '')) {
|
|
55
|
+
throw new Error('goose adapter: MCP server needs a safe name');
|
|
56
|
+
}
|
|
57
|
+
const transport = server.transport || 'stdio';
|
|
58
|
+
if (transport === 'http') {
|
|
59
|
+
if (server.headers && Object.keys(server.headers).length) {
|
|
60
|
+
throw new Error(`goose adapter: HTTP MCP server ${server.name} has headers Goose cannot deliver without exposing credentials`);
|
|
61
|
+
}
|
|
62
|
+
if (typeof server.url !== 'string' || !server.url) throw new Error(`goose adapter: ${server.name} has no HTTP URL`);
|
|
63
|
+
const url = substitute(server.url, ctx);
|
|
64
|
+
const parsed = new URL(url);
|
|
65
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash) {
|
|
66
|
+
throw new Error(`goose adapter: HTTP MCP server ${server.name} contains a credential-bearing URL`);
|
|
67
|
+
}
|
|
68
|
+
if (parsed.origin !== new URL(ctx.instanceUrl).origin) {
|
|
69
|
+
throw new Error(`goose adapter: HTTP MCP server ${server.name} is outside the Commonly instance`);
|
|
70
|
+
}
|
|
71
|
+
args.push('--with-streamable-http-extension', url);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (transport !== 'stdio' || !Array.isArray(server.command) || !server.command.length) {
|
|
75
|
+
throw new Error(`goose adapter: MCP server ${server.name} has an unsupported transport or command`);
|
|
76
|
+
}
|
|
77
|
+
const command = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl });
|
|
78
|
+
const delivery = deliverSeatCredential({ ...server, command }, {
|
|
79
|
+
credentialFile: ctx.credentialFile, label: 'goose',
|
|
80
|
+
});
|
|
81
|
+
if (delivery.delivered === 'env' || delivery.delivered === 'unavailable') {
|
|
82
|
+
throw new Error(`goose adapter: MCP server ${server.name} cannot receive its credential by file`);
|
|
83
|
+
}
|
|
84
|
+
const env = Object.entries(delivery.env).map(([name, value]) => {
|
|
85
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error('goose adapter: invalid MCP environment key');
|
|
86
|
+
if (!['COMMONLY_TOKEN_FILE', 'COMMONLY_API_URL', 'COMMONLY_INSTANCE_URL'].includes(name)) {
|
|
87
|
+
throw new Error(`goose adapter: MCP server ${server.name} has ${name}, which cannot safely ride a CLI flag`);
|
|
88
|
+
}
|
|
89
|
+
const resolved = substitute(value, ctx);
|
|
90
|
+
if (resolved.includes('${COMMONLY_AGENT_TOKEN}') || (ctx.runtimeToken && resolved.includes(ctx.runtimeToken))) {
|
|
91
|
+
throw new Error(`goose adapter: MCP server ${server.name} would expose the runtime token in argv`);
|
|
92
|
+
}
|
|
93
|
+
return gooseWord(`${name}=${resolved}`);
|
|
94
|
+
});
|
|
95
|
+
const commandWords = command.map((part) => gooseWord(substitute(part, ctx)));
|
|
96
|
+
args.push('--with-extension', `${server.name}:${[...env, ...commandWords].join(' ')}`);
|
|
97
|
+
}
|
|
98
|
+
return args;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export const readGooseStream = (stdout) => {
|
|
102
|
+
let text = '';
|
|
103
|
+
let error = null;
|
|
104
|
+
let complete = false;
|
|
105
|
+
for (const line of String(stdout || '').split('\n')) {
|
|
106
|
+
let event;
|
|
107
|
+
try { event = JSON.parse(line); } catch { continue; }
|
|
108
|
+
if (event?.type === 'complete') complete = true;
|
|
109
|
+
if (event?.type === 'error') error = event.error?.message || event.message || 'Goose turn failed';
|
|
110
|
+
if (event?.type === 'message' && event.message?.role === 'assistant'
|
|
111
|
+
&& event.message?.metadata?.userVisible !== false) {
|
|
112
|
+
const body = event.message.content?.filter((item) => item?.type === 'text' && typeof item.text === 'string')
|
|
113
|
+
.map((item) => item.text).join('') || '';
|
|
114
|
+
if (body.trim()) text = body.trim();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { text, error, complete };
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const runGoose = ({ binary, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
|
|
121
|
+
const child = spawnImpl(binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
122
|
+
let stdout = '';
|
|
123
|
+
const stdoutDecoder = new StringDecoder('utf8');
|
|
124
|
+
let stderr = '';
|
|
125
|
+
let timedOut = false;
|
|
126
|
+
let streamOverflow = false;
|
|
127
|
+
let extensionFailure = null;
|
|
128
|
+
let settled = false;
|
|
129
|
+
let killTimer;
|
|
130
|
+
const finish = (error, result) => {
|
|
131
|
+
if (settled) return;
|
|
132
|
+
settled = true;
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
clearTimeout(killTimer);
|
|
135
|
+
if (error) reject(error); else resolve(result);
|
|
136
|
+
};
|
|
137
|
+
const timer = setTimeout(() => {
|
|
138
|
+
timedOut = true;
|
|
139
|
+
child.kill('SIGTERM');
|
|
140
|
+
killTimer = setTimeout(() => child.kill('SIGKILL'), TERMINATION_GRACE_MS);
|
|
141
|
+
}, timeoutMs);
|
|
142
|
+
child.stdout?.on('data', (chunk) => {
|
|
143
|
+
if (streamOverflow) return;
|
|
144
|
+
stdout += stdoutDecoder.write(chunk);
|
|
145
|
+
if (stdout.length > 2 * 1024 * 1024) {
|
|
146
|
+
streamOverflow = true;
|
|
147
|
+
stdout = '';
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
child.kill('SIGTERM');
|
|
150
|
+
killTimer = setTimeout(() => child.kill('SIGKILL'), TERMINATION_GRACE_MS);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
child.stderr?.on('data', (chunk) => {
|
|
154
|
+
const received = chunk.toString();
|
|
155
|
+
extensionFailure ||= (stderr + received).match(/Failed to start extension '[^']+'[^\n]*/)?.[0] || null;
|
|
156
|
+
stderr = (stderr + received).slice(-8192);
|
|
157
|
+
});
|
|
158
|
+
child.on('error', (error) => finish(error));
|
|
159
|
+
child.on('close', (code) => {
|
|
160
|
+
stdout += stdoutDecoder.end();
|
|
161
|
+
if (timedOut) return finish(new Error(`goose adapter: timed out after ${timeoutMs}ms`));
|
|
162
|
+
if (streamOverflow) return finish(new Error('goose adapter: stream exceeded 2 MiB'));
|
|
163
|
+
const result = readGooseStream(stdout);
|
|
164
|
+
// Goose reports an extension startup failure on stderr yet exits 0 and
|
|
165
|
+
// lets the model answer without that tool. A Commonly seat cannot silently
|
|
166
|
+
// lose its only path back to the pod.
|
|
167
|
+
if (code !== 0 || result.error || !result.complete || extensionFailure) {
|
|
168
|
+
return finish(adapterFailure('goose', extensionFailure || result.error || stderr.trim() || `exit ${code}; incomplete stream`, {
|
|
169
|
+
credentials, exitCode: code, limit: 500,
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
return finish(null, result.text);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
export default {
|
|
177
|
+
name: 'goose',
|
|
178
|
+
providerKeyEnv: DEFAULT_PROVIDER_KEY,
|
|
179
|
+
supportsProvider: true,
|
|
180
|
+
|
|
181
|
+
async validateEnvironment(environment, workspacePath) {
|
|
182
|
+
assertNoSandboxDeclared(environment);
|
|
183
|
+
const validation = validateEnvironmentSpec(environment || {});
|
|
184
|
+
if (!validation.ok) throw new Error(validation.errors.join('; '));
|
|
185
|
+
return resolveProviderKeyFile(environment?.provider, workspacePath, 'Goose');
|
|
186
|
+
},
|
|
187
|
+
|
|
188
|
+
async detect() {
|
|
189
|
+
const result = spawnSync('goose', ['--version'], { encoding: 'utf8', timeout: 5000 });
|
|
190
|
+
if (result.error || result.status !== 0) return null;
|
|
191
|
+
const where = spawnSync('which', ['goose'], { encoding: 'utf8', timeout: 5000 });
|
|
192
|
+
return { path: String(where.stdout || 'goose').trim() || 'goose', version: versionOf(result.stdout) || 'unknown' };
|
|
193
|
+
},
|
|
194
|
+
|
|
195
|
+
async spawn(prompt, ctx = {}) {
|
|
196
|
+
const keyFile = await this.validateEnvironment(ctx.environment, ctx.cwd);
|
|
197
|
+
const sourceEnv = ctx.env || process.env;
|
|
198
|
+
const configured = ctx.environment?.provider;
|
|
199
|
+
const key = configured
|
|
200
|
+
? (await readFile(keyFile, 'utf8')).trim() : sourceEnv[DEFAULT_PROVIDER_KEY];
|
|
201
|
+
if (!key) throw new Error(`goose adapter: ${configured ? 'provider.keyFile' : DEFAULT_PROVIDER_KEY} is missing`);
|
|
202
|
+
const baseUrl = new URL(configured?.baseURL || `${DEFAULT_PROVIDER_HOST}/v1`);
|
|
203
|
+
if (!/^https?:$/.test(baseUrl.protocol) || baseUrl.username || baseUrl.password || baseUrl.search || baseUrl.hash) {
|
|
204
|
+
throw new Error('goose adapter: provider.baseURL must be a plain HTTP(S) URL');
|
|
205
|
+
}
|
|
206
|
+
const model = ctx.environment?.model || DEFAULT_MODEL;
|
|
207
|
+
const binary = ctx._binaryPath || 'goose';
|
|
208
|
+
const version = ctx._version || versionOf(spawnSync(binary, ['--version'], { encoding: 'utf8', timeout: 5000 }).stdout);
|
|
209
|
+
if (!TESTED_GOOSE_VERSIONS.includes(version)) {
|
|
210
|
+
// eslint-disable-next-line no-console
|
|
211
|
+
console.warn(`[goose] installed ${version || 'unknown'} differs from smoke-tested ${TESTED_GOOSE_VERSIONS.join(', ')}; private seat continues`);
|
|
212
|
+
}
|
|
213
|
+
const home = await mkdtemp(join(tmpdir(), 'commonly-goose-'));
|
|
214
|
+
try {
|
|
215
|
+
const credential = writeCredentialFile(ctx.runtimeToken, {
|
|
216
|
+
root: home, agentName: ctx.agentName || 'agent',
|
|
217
|
+
});
|
|
218
|
+
const args = [
|
|
219
|
+
'run', '--no-session', '--no-profile', '--with-builtin', 'developer',
|
|
220
|
+
'--output-format', 'stream-json', '--provider', 'openai', '--model', model,
|
|
221
|
+
...extensionArgs(ctx.environment?.mcp, {
|
|
222
|
+
credentialFile: credential?.path || '', instanceUrl: ctx.instanceUrl || '',
|
|
223
|
+
runtimeToken: ctx.runtimeToken || '',
|
|
224
|
+
}),
|
|
225
|
+
'-t', buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: true }),
|
|
226
|
+
];
|
|
227
|
+
const env = {
|
|
228
|
+
...Object.fromEntries(Object.entries(sourceEnv).filter(([name]) => SAFE_ENV.test(name))),
|
|
229
|
+
HOME: home,
|
|
230
|
+
XDG_CONFIG_HOME: join(home, 'config'),
|
|
231
|
+
XDG_DATA_HOME: join(home, 'data'),
|
|
232
|
+
GOOSE_PROVIDER: 'openai',
|
|
233
|
+
GOOSE_MODEL: model,
|
|
234
|
+
GOOSE_MODE: 'auto',
|
|
235
|
+
GOOSE_TELEMETRY_ENABLED: 'false',
|
|
236
|
+
OPENAI_HOST: baseUrl.origin,
|
|
237
|
+
OPENAI_BASE_PATH: `${baseUrl.pathname.replace(/\/$/, '')}/chat/completions`.replace(/^\//, ''),
|
|
238
|
+
OPENAI_API_KEY: key,
|
|
239
|
+
};
|
|
240
|
+
withholdRuntimeCredential(env, { credentialFile: credential?.path || null });
|
|
241
|
+
const requestedTimeout = Number(ctx.timeoutMs);
|
|
242
|
+
const timeoutMs = Number.isFinite(requestedTimeout) && requestedTimeout > 0
|
|
243
|
+
? Math.min(requestedTimeout, DEFAULT_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
|
|
244
|
+
const text = await runGoose({
|
|
245
|
+
binary, args, cwd: ctx.cwd, env, timeoutMs,
|
|
246
|
+
credentials: [...spawnCredentials(ctx, [DEFAULT_PROVIDER_KEY]), key],
|
|
247
|
+
spawnImpl: ctx._spawnImpl,
|
|
248
|
+
});
|
|
249
|
+
return { text, newSessionId: null };
|
|
250
|
+
} finally {
|
|
251
|
+
await rm(home, { recursive: true, force: true });
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
};
|
|
@@ -14,6 +14,7 @@ import pi from './pi.js';
|
|
|
14
14
|
import opencode from './opencode.js';
|
|
15
15
|
import qwen from './qwen.js';
|
|
16
16
|
import dsh from './dsh.js';
|
|
17
|
+
import goose from './goose.js';
|
|
17
18
|
|
|
18
19
|
const ADAPTERS = {
|
|
19
20
|
[stub.name]: stub,
|
|
@@ -23,6 +24,7 @@ const ADAPTERS = {
|
|
|
23
24
|
[opencode.name]: opencode,
|
|
24
25
|
[qwen.name]: qwen,
|
|
25
26
|
[dsh.name]: dsh,
|
|
27
|
+
[goose.name]: goose,
|
|
26
28
|
};
|
|
27
29
|
|
|
28
30
|
export const listAdapterNames = () => Object.keys(ADAPTERS);
|
|
@@ -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;
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
* opencode — per-spawn config file with local/remote MCP entries (adapters/opencode.js)
|
|
20
20
|
* qwen — per-spawn --mcp-config with file-backed stdio credentials (adapters/qwen.js)
|
|
21
21
|
* dsh — per-spawn --patch with file-backed stdio credentials (adapters/dsh.js)
|
|
22
|
+
* goose — per-spawn --with-extension with file-backed stdio credentials (adapters/goose.js)
|
|
22
23
|
* `stub` has no consumption path and must keep being handed `environment: null`.
|
|
23
24
|
*
|
|
24
25
|
* The placeholders are substituted at spawn time by the adapter, so the
|
|
@@ -27,13 +28,15 @@
|
|
|
27
28
|
|
|
28
29
|
import { normalizeSandboxTrust } from './environment.js';
|
|
29
30
|
|
|
30
|
-
export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen', 'dsh']);
|
|
31
|
+
export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen', 'dsh', 'goose']);
|
|
31
32
|
|
|
32
33
|
/**
|
|
33
34
|
* The adapters that can ENFORCE the default sandbox — a strict subset of the
|
|
34
35
|
* ones that consume `mcp[]`.
|
|
35
36
|
*
|
|
36
|
-
* `pi`
|
|
37
|
+
* `pi` and `goose` are absent deliberately. Neither can enforce the declared
|
|
38
|
+
* sandbox; their adapters refuse effective public trust and non-none modes.
|
|
39
|
+
* `pi` has no sandbox path until #1740's transport
|
|
37
40
|
* work gives it one, and since #1727 it REFUSES TO START on a spec that
|
|
38
41
|
* declares one: `assertNoSandboxDeclared` in adapters/pi.js throws on an
|
|
39
42
|
* effective `trust: 'public'` (a legacy `internal` resolves to it) and on any
|
|
@@ -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
|
|