@commonlyai/cli 0.1.152 → 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.152",
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",
@@ -463,7 +463,10 @@ const DEFERRABLE_SOLO_EVENT_TYPES = new Set(['first_contact']);
463
463
  // Inside one batch the person's item leads the prompt; the greeting follows it.
464
464
  const PERSON_WAITING_EVENT_TYPES = new Set(['chat.mention', 'message.posted', 'dm.message']);
465
465
 
466
- const inboxPriority = (event) => (PERSON_WAITING_EVENT_TYPES.has(event?.type) ? 0 : 1);
466
+ const inboxPriority = (event) => {
467
+ if (event?.deliveryMode === 'digest') return 2;
468
+ return PERSON_WAITING_EVENT_TYPES.has(event?.type) ? 0 : 1;
469
+ };
467
470
 
468
471
  // Consultations have a per-request private response channel, rather than a
469
472
  // pod-chat delivery. They stay on their existing single-event path; every
@@ -1506,7 +1509,7 @@ export const performRun = ({
1506
1509
  // own conversation (Sage stood down twice on Anvil's thread
1507
1510
  // replies, 2026-08-24). Interim for TASK-058.
1508
1511
  const repliesToThisSeat = event.payload?.repliesToYourMessage === true;
1509
- if (ADDRESSED_EVENT_TYPES.has(event.type) || repliesToThisSeat) {
1512
+ if (ADDRESSED_EVENT_TYPES.has(event.type) || event.payload?.addressed === true || repliesToThisSeat) {
1510
1513
  log(
1511
1514
  `[${event.type}] message ${claimMessageId} held by ${claim.holder} — `
1512
1515
  + (repliesToThisSeat
@@ -2008,10 +2011,12 @@ export const performRun = ({
2008
2011
  // pull, rather than being silently consumed here.
2009
2012
  const buildInboxPrompt = (entries, inboxCount = entries.length) => {
2010
2013
  const BODY_LIMIT = batchLimit;
2011
- const bodies = entries.slice(0, BODY_LIMIT).map((entry, index) => {
2014
+ const wakeEntries = entries.filter((entry) => entry.event.deliveryMode !== 'digest');
2015
+ const digestEntries = entries.filter((entry) => entry.event.deliveryMode === 'digest');
2016
+ const bodies = wakeEntries.slice(0, BODY_LIMIT).map((entry, index) => {
2012
2017
  const messageId = entry.event.payload?.messageId;
2013
2018
  const prefix = [
2014
- `Event ${index + 1}/${entries.length}: ${entry.event.type}`,
2019
+ `Event ${index + 1}/${wakeEntries.length}: ${entry.event.type}`,
2015
2020
  messageId ? `message ${messageId}` : null,
2016
2021
  ].filter(Boolean).join(' — ');
2017
2022
  const claimContext = entry.readOnly
@@ -2021,11 +2026,43 @@ export const performRun = ({
2021
2026
  const body = entry.prompt || '[No usable prompt was delivered for this item.]';
2022
2027
  return `${prefix}\n${claimContext}${body}`;
2023
2028
  });
2024
- const omitted = Math.max(0, inboxCount - bodies.length);
2029
+ const rollup = wakeEntries.find((entry) => entry.event.payload?.digestRollup)?.event.payload?.digestRollup;
2030
+ const conversationCounts = new Map();
2031
+ let knownOlder = 0;
2032
+ for (const conversation of Array.isArray(rollup?.conversations) ? rollup.conversations : []) {
2033
+ if (typeof conversation.label !== 'string' || !Number.isInteger(conversation.count)
2034
+ || conversation.count < 1) continue;
2035
+ conversationCounts.set(conversation.label,
2036
+ (conversationCounts.get(conversation.label) || 0) + conversation.count);
2037
+ knownOlder += conversation.count;
2038
+ }
2039
+ if (rollup?.unreadCount > knownOlder) {
2040
+ conversationCounts.set('older pod activity', rollup.unreadCount - knownOlder);
2041
+ }
2042
+ const seenDigestSources = new Set();
2043
+ for (const entry of digestEntries) {
2044
+ const { threadRootId, taskId, taskKind, messageId, content } = entry.event.payload || {};
2045
+ const sourceId = messageId != null ? `message:${messageId}`
2046
+ : (typeof taskId === 'string' ? `task:${taskId}:${taskKind || ''}:${content || ''}` : null);
2047
+ if (sourceId && seenDigestSources.has(sourceId)) continue;
2048
+ if (sourceId) seenDigestSources.add(sourceId);
2049
+ const label = Number.isInteger(Number(threadRootId)) && Number(threadRootId) > 0
2050
+ ? `thread ${threadRootId}`
2051
+ : (/^TASK-\d+$/.test(String(taskId || '')) ? taskId : 'pod conversation');
2052
+ conversationCounts.set(label, (conversationCounts.get(label) || 0) + 1);
2053
+ }
2054
+ const digestLines = [...conversationCounts].slice(0, 8)
2055
+ .map(([label, count]) => `- ${label}: ${count} unread`);
2056
+ const digestCount = [...conversationCounts.values()].reduce((sum, count) => sum + count, 0);
2057
+ const omitted = Math.max(0, inboxCount - entries.length);
2025
2058
  return [
2026
2059
  `[Inbox batch: ${inboxCount} new event${inboxCount === 1 ? '' : 's'} in this pod. `
2027
2060
  + 'This is one turn: read the included items together, then decide what needs YOU.]',
2028
2061
  ...bodies,
2062
+ ...(digestEntries.length > 0 || rollup?.unreadCount > 0 ? [
2063
+ `[Since you last looked: ${digestCount} ambient update${digestCount === 1 ? '' : 's'} in ${conversationCounts.size} conversation${conversationCounts.size === 1 ? '' : 's'}; context only, no reply needed.]
2064
+ ${digestLines.join('\n')}${conversationCounts.size > 8 ? `\n- ${conversationCounts.size - 8} more conversations omitted` : ''}\nPull relevant messages with commonly_get_messages. On resume, read oldest unread first; at most 8 conversations, 5 messages each, 20 messages total.`,
2065
+ ] : []),
2029
2066
  ...(omitted > 0
2030
2067
  ? [`[${omitted} more event${omitted === 1 ? '' : 's'} arrived. Their count is real; pull pod context if needed.]`]
2031
2068
  : []),
@@ -2168,12 +2205,17 @@ export const performRun = ({
2168
2205
  ? new Set(preSpawn.map((message) => String(message._id || message.id)))
2169
2206
  : null;
2170
2207
  const activeEntries = entries.filter((entry) => !entry.result);
2171
- const triggers = activeEntries.map((entry) => classifyTrigger(entry.event, preSpawn));
2208
+ // Ambient digest entries provide context for this turn, but must never
2209
+ // determine its admission or count as the trigger that woke the seat.
2210
+ const wakingEntries = activeEntries.filter((entry) => entry.event.deliveryMode !== 'digest');
2211
+ const triggers = wakingEntries.map((entry) => classifyTrigger(entry.event, preSpawn));
2172
2212
  const trigger = triggers.includes('human') ? 'human'
2173
2213
  : (triggers.includes('agent') ? 'agent' : 'unknown');
2174
2214
  if (trigger === 'human') cascadeGovernor.record(eventPodId, trigger);
2175
- const admissionEvent = activeEntries.find((entry) => ADDRESSED_EVENT_TYPES.has(entry.event.type))
2176
- || activeEntries[0];
2215
+ const admissionEvent = wakingEntries.find((entry) => (
2216
+ ADDRESSED_EVENT_TYPES.has(entry.event.type) || entry.event.payload?.addressed === true
2217
+ ))
2218
+ || wakingEntries[0];
2177
2219
  if (admissionEvent) {
2178
2220
  const admission = cascadeGovernor.admit(
2179
2221
  eventPodId,
@@ -2182,7 +2224,7 @@ export const performRun = ({
2182
2224
  admissionEvent.event.payload,
2183
2225
  );
2184
2226
  if (!admission.allowed) {
2185
- for (const entry of activeEntries) {
2227
+ for (const entry of wakingEntries) {
2186
2228
  entry.result = batchAdmissionResult(entry.event, admission);
2187
2229
  }
2188
2230
  return { entries };
@@ -2190,7 +2232,8 @@ export const performRun = ({
2190
2232
  }
2191
2233
 
2192
2234
  const bindingEntries = activeEntries.filter((entry) => (
2193
- entry.event.type === 'message.posted' && entry.event.payload?.messageId
2235
+ entry.event.deliveryMode !== 'digest'
2236
+ && entry.event.type === 'message.posted' && entry.event.payload?.messageId
2194
2237
  ));
2195
2238
  if (bindingEntries.length > 0) {
2196
2239
  const yieldMs = claimHandicap.yieldDelayMs(eventPodId);
@@ -2201,6 +2244,7 @@ export const performRun = ({
2201
2244
  }
2202
2245
 
2203
2246
  for (const entry of activeEntries) {
2247
+ if (entry.event.deliveryMode === 'digest') continue;
2204
2248
  const messageId = entry.event.payload?.messageId;
2205
2249
  if (!messageId || !CLAIMABLE_EVENT_TYPES.has(entry.event.type)) continue;
2206
2250
  const claimKeeper = createClaimKeeper(client, {
@@ -2224,7 +2268,7 @@ export const performRun = ({
2224
2268
  // `message.posted`. Preserve the existing ADR-018/TASK-058
2225
2269
  // peer-aware exception; D3a otherwise partitions lost bindings as
2226
2270
  // read-only so a generic broadcast cannot widen itself after CAS.
2227
- if (entry.event.payload?.repliesToYourMessage === true) {
2271
+ if (entry.event.payload?.repliesToYourMessage === true || entry.event.payload?.addressed === true) {
2228
2272
  entry.peerFrame = peerHoldsFrame(claim.holder, messageId);
2229
2273
  continue;
2230
2274
  }
@@ -2241,7 +2285,7 @@ export const performRun = ({
2241
2285
  }
2242
2286
  }
2243
2287
 
2244
- const actionEntries = activeEntries.filter((entry) => !entry.result);
2288
+ const actionEntries = wakingEntries.filter((entry) => !entry.result);
2245
2289
  if (actionEntries.length === 0) return { entries };
2246
2290
 
2247
2291
  const claimKeepers = actionEntries
@@ -2300,6 +2344,17 @@ export const performRun = ({
2300
2344
  trigger,
2301
2345
  });
2302
2346
  for (const entry of actionEntries) entry.result = turnResult;
2347
+ // A digest was context in this successful waking turn, never an
2348
+ // independent action. If the waking work stood down or the provider
2349
+ // refused the batch, leave it unread for the next real turn.
2350
+ if (turnResult?.outcome === 'posted'
2351
+ || (turnResult?.outcome === 'no_action' && !turnResult?.reason)) {
2352
+ for (const entry of activeEntries) {
2353
+ if (entry.event.deliveryMode === 'digest') {
2354
+ entry.result = { outcome: 'no_action', reason: 'digest-read' };
2355
+ }
2356
+ }
2357
+ }
2303
2358
  } catch (err) {
2304
2359
  if (!isContentRefusal(err)) throw err;
2305
2360
  if (actionEntries.length === 1) {
@@ -2352,6 +2407,7 @@ export const performRun = ({
2352
2407
  const tick = async () => {
2353
2408
  if (!running) return;
2354
2409
  let nextPollDelayMs = intervalMs;
2410
+ let completedModelTurn = false;
2355
2411
  try {
2356
2412
  // ADR-024 D3: this is an inbox fetch, not a stream of interrupts. The
2357
2413
  // backend returns one pod's oldest pending batch, so every delivered row
@@ -2392,6 +2448,12 @@ export const performRun = ({
2392
2448
  }
2393
2449
  for (const group of eventGroups.values()) {
2394
2450
  if (!running) break;
2451
+ // A current kernel never claims a digest-only page. Guard a mixed
2452
+ // version rollout too: an ambient batch must not start a model turn.
2453
+ if (group.every((event) => event.deliveryMode === 'digest')) {
2454
+ log(`[inbox.batch] digest-only page (${group.length}) — no spawn or ack`);
2455
+ continue;
2456
+ }
2395
2457
  if ((group[0].podId || podId) && !PRIVATE_RESPONSE_EVENT_TYPES.has(group[0].type)) {
2396
2458
  // Nothing in this batch but the seat introducing itself: leave it
2397
2459
  // unacked for one interval so a person who mentions the agent in that
@@ -2459,13 +2521,9 @@ export const performRun = ({
2459
2521
  ));
2460
2522
  if (batchSpawned) {
2461
2523
  consecutiveSpawnFailures = 0;
2462
- // A turn is exactly when events pile up: whoever typed while the
2463
- // adapter was running is already waiting. Sleeping the interval on
2464
- // top of the turn charges them for it twice (TASK-343). Only a
2465
- // batch that actually spawned skips the wait; an idle poll and a
2466
- // batch that spawned nothing keep the interval, so this cannot
2467
- // become a spin.
2468
- nextPollDelayMs = 0;
2524
+ // Notices arriving mid-turn get one bounded collection window.
2525
+ // Idle polls and batches with no model turn keep their cadence.
2526
+ completedModelTurn = true;
2469
2527
  }
2470
2528
  for (const entry of batch.entries) {
2471
2529
  const event = entry.event;
@@ -2643,7 +2701,9 @@ export const performRun = ({
2643
2701
  }
2644
2702
  onError?.(err);
2645
2703
  }
2646
- if (running) setTimeoutImpl(tick, nextPollDelayMs);
2704
+ // Notices landing during a turn share one three-second collection window
2705
+ // before the next inbox read, independent of the idle polling cadence.
2706
+ if (running) setTimeoutImpl(tick, completedModelTurn ? 3000 : nextPollDelayMs);
2647
2707
  };
2648
2708
 
2649
2709
  tick();
@@ -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;
package/src/lib/poller.js CHANGED
@@ -28,6 +28,40 @@ export const terminalDeliveryAckError = (ackErr, eventId, runner = 'poller') =>
28
28
  return null;
29
29
  };
30
30
 
31
+ const digestFrame = (events, rollup) => {
32
+ const counts = new Map();
33
+ let knownOlder = 0;
34
+ for (const conversation of Array.isArray(rollup?.conversations) ? rollup.conversations : []) {
35
+ if (typeof conversation.label !== 'string' || !Number.isInteger(conversation.count)
36
+ || conversation.count < 1) continue;
37
+ counts.set(conversation.label, (counts.get(conversation.label) || 0) + conversation.count);
38
+ knownOlder += conversation.count;
39
+ }
40
+ if (rollup?.unreadCount > knownOlder) {
41
+ counts.set('older pod activity',
42
+ (counts.get('older pod activity') || 0) + rollup.unreadCount - knownOlder);
43
+ }
44
+ const seen = new Set();
45
+ for (const event of events) {
46
+ const payload = event.payload || {};
47
+ const sourceId = payload.messageId != null ? `message:${payload.messageId}`
48
+ : (typeof payload.taskId === 'string'
49
+ ? `task:${payload.taskId}:${String(payload.taskKind || '')}:${String(payload.content || '')}` : null);
50
+ if (sourceId && seen.has(sourceId)) continue;
51
+ if (sourceId) seen.add(sourceId);
52
+ const thread = payload.threadRootId;
53
+ const task = payload.taskId;
54
+ const label = Number.isInteger(thread) && thread > 0 ? `thread ${thread}`
55
+ : (typeof task === 'string' && /^TASK-\d+$/.test(task) ? task : 'pod conversation');
56
+ counts.set(label, (counts.get(label) || 0) + 1);
57
+ }
58
+ const lines = [...counts].slice(0, 8).map(([label, count]) => `- ${label}: ${count} unread`);
59
+ if (counts.size > 8) lines.push(`- ${counts.size - 8} more conversations omitted`);
60
+ const total = [...counts.values()].reduce((sum, count) => sum + count, 0);
61
+ return `[Since you last looked: ${total} ambient update${total === 1 ? '' : 's'} in ${counts.size} conversation${counts.size === 1 ? '' : 's'}; context only, no reply needed.]\n`
62
+ + `${lines.join('\n')}\nPull relevant messages with commonly_get_messages. On resume, read oldest unread first; at most 8 conversations, 5 messages each, 20 messages total.`;
63
+ };
64
+
31
65
  export const startPoller = ({
32
66
  instanceUrl,
33
67
  token,
@@ -57,10 +91,30 @@ export const startPoller = ({
57
91
  limit: 10,
58
92
  });
59
93
 
60
- for (const event of events) {
94
+ // A digest is received context, not a webhook invocation. The runtime
95
+ // inbox claims it only alongside a wake from the same pod.
96
+ const wakeEvents = events.filter((event) => event.deliveryMode !== 'digest');
97
+ const digestEvents = events.filter((event) => event.deliveryMode === 'digest'
98
+ && wakeEvents[0] && String(event.podId) === String(wakeEvents[0].podId));
99
+ const rollup = wakeEvents[0]?.payload?.digestRollup;
100
+ const frame = digestEvents.length > 0 || rollup?.unreadCount > 0
101
+ ? digestFrame(digestEvents, rollup) : null;
102
+ let digestConsumed = false;
103
+ for (const [index, event] of wakeEvents.entries()) {
104
+ const attachedDigest = index === 0 && frame !== null;
105
+ const forwarded = attachedDigest ? {
106
+ ...event,
107
+ payload: {
108
+ ...(event.payload || {}),
109
+ digestSummary: frame,
110
+ ...(typeof event.payload?.content === 'string' ? {
111
+ content: `${event.payload.content}\n\n${frame}`,
112
+ } : {}),
113
+ },
114
+ } : event;
61
115
  let result = { outcome: 'no_action' };
62
116
  try {
63
- result = (await onEvent(event)) || { outcome: 'no_action' };
117
+ result = (await onEvent(forwarded)) || { outcome: 'no_action' };
64
118
  } catch (handlerErr) {
65
119
  result = { outcome: 'error', reason: handlerErr.message };
66
120
  }
@@ -72,6 +126,11 @@ export const startPoller = ({
72
126
  result,
73
127
  ...(typeof deliveryId === 'string' && deliveryId ? { deliveryId } : {}),
74
128
  });
129
+ if (attachedDigest && (result.outcome === 'posted'
130
+ || result.outcome === 'acknowledged'
131
+ || (result.outcome === 'no_action' && !result.reason))) {
132
+ digestConsumed = true;
133
+ }
75
134
  } catch (ackErr) {
76
135
  const terminalError = terminalDeliveryAckError(ackErr, event._id);
77
136
  if (terminalError) {
@@ -84,6 +143,26 @@ export const startPoller = ({
84
143
  }
85
144
  }
86
145
 
146
+ if (digestConsumed) {
147
+ for (const event of digestEvents) {
148
+ try {
149
+ const deliveryId = event.payload?.deliveryId;
150
+ await client.post(`/api/agents/runtime/events/${event._id}/ack`, {
151
+ result: { outcome: 'no_action', reason: 'digest-read' },
152
+ ...(typeof deliveryId === 'string' && deliveryId ? { deliveryId } : {}),
153
+ });
154
+ } catch (ackErr) {
155
+ const terminalError = terminalDeliveryAckError(ackErr, event._id);
156
+ if (terminalError) {
157
+ running = false;
158
+ onError?.(terminalError);
159
+ return;
160
+ }
161
+ onError?.(new Error(`Ack failed for ${event._id}: ${ackErr.message}`));
162
+ }
163
+ }
164
+ }
165
+
87
166
  consecutiveErrors = 0;
88
167
  consecutiveAuthErrors = 0;
89
168
  } catch (err) {
@@ -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
- };