@commonlyai/cli 0.1.156 → 0.1.157

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.156",
3
+ "version": "0.1.157",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -32,11 +32,18 @@ import { startWebhookServer, forwardToLocalWebhook } from '../lib/webhook-server
32
32
  import { getAdapter, listAdapterNames } from '../lib/adapters/index.js';
33
33
  import {
34
34
  getSession,
35
+ getSessionEntry,
35
36
  setSession,
36
37
  clearSessions,
37
38
  wasEventHandled,
38
39
  recordHandledEvent,
39
40
  } from '../lib/session-store.js';
41
+ import {
42
+ buildRecycleBriefing,
43
+ idleMinutesSince,
44
+ recycleThresholds,
45
+ shouldStartFreshSession,
46
+ } from '../lib/session-recycle.js';
40
47
  import { readLongTerm, syncBack } from '../lib/memory-bridge.js';
41
48
  import { pollRetryPolicy } from '../lib/poll-retry.js';
42
49
  import { detectMemorySources, composeImport, importMemory } from '../lib/memory-import.js';
@@ -1568,7 +1575,26 @@ export const performRun = ({
1568
1575
  const runTurn = async ({
1569
1576
  event, eventPodId, prompt, preSpawnIds, snapshotMessages, claimKeeper, trigger,
1570
1577
  }) => {
1571
- const sessionId = getSession(agentName, eventPodId, { binding: sessionBinding });
1578
+ // TASK-440: a cold, large session starts fresh at wake instead of being
1579
+ // resumed. The restart note leads the prompt; memory still reaches the
1580
+ // fresh session through the adapter's preamble.
1581
+ const sessionEntry = getSessionEntry(agentName, eventPodId, { binding: sessionBinding });
1582
+ let sessionId = getSession(agentName, eventPodId, { binding: sessionBinding });
1583
+ let recycleBriefing = null;
1584
+ if (sessionId && shouldStartFreshSession({
1585
+ lastTurn: sessionEntry?.lastTurn,
1586
+ contextTokens: sessionEntry?.contextTokens,
1587
+ thresholds: recycleThresholds(),
1588
+ })) {
1589
+ recycleBriefing = buildRecycleBriefing({
1590
+ agentName,
1591
+ idleMinutes: idleMinutesSince(sessionEntry.lastTurn),
1592
+ contextTokens: sessionEntry.contextTokens,
1593
+ });
1594
+ log(`session recycled: idle ${idleMinutesSince(sessionEntry.lastTurn)} min, `
1595
+ + `${sessionEntry.contextTokens} context tokens; starting fresh`);
1596
+ sessionId = null;
1597
+ }
1572
1598
  // ADR-005 §Memory bridge: read long_term before spawn, inject via ctx,
1573
1599
  // and (if the adapter returns a summary) patch-sync back after.
1574
1600
  const memoryLongTerm = await readLongTerm(client, { onError });
@@ -1613,6 +1639,9 @@ export const performRun = ({
1613
1639
  const promptWithSkills = serverSkills.text
1614
1640
  ? `${focusFrame}\n\n${serverSkills.text}\n\n${prompt}`
1615
1641
  : promptWithFocus;
1642
+ const promptForSpawn = recycleBriefing
1643
+ ? `${recycleBriefing}\n\n${promptWithSkills}`
1644
+ : promptWithSkills;
1616
1645
 
1617
1646
  log(`[${event.type}] spawning ${adapter.name}`);
1618
1647
  // TASK-102 part B. The CHILD gets a scoped credential; the wrapper keeps
@@ -1696,7 +1725,7 @@ export const performRun = ({
1696
1725
  effort: seatEnvironment?.effort,
1697
1726
  });
1698
1727
  }
1699
- result = await adapter.spawn(frameDecisionForkRule(promptWithSkills), {
1728
+ result = await adapter.spawn(frameDecisionForkRule(promptForSpawn), {
1700
1729
  sessionId,
1701
1730
  cwd: agentCwd,
1702
1731
  env: commitAttribution?.env || process.env,
@@ -1741,7 +1770,13 @@ export const performRun = ({
1741
1770
  }
1742
1771
 
1743
1772
  if (result.newSessionId) {
1744
- setSession(agentName, eventPodId, result.newSessionId, { binding: sessionBinding });
1773
+ // TASK-440: record the context size this turn left behind, so the next
1774
+ // wake can decide whether to recycle. Adapters that report nothing keep
1775
+ // resuming.
1776
+ setSession(agentName, eventPodId, result.newSessionId, {
1777
+ binding: sessionBinding,
1778
+ contextTokens: result.contextTokens ?? null,
1779
+ });
1745
1780
  }
1746
1781
  // Decide whether to post the CLI's final text. The agent owns its posting:
1747
1782
  // if it already spoke this turn through commonly_post_message, echoing its
@@ -79,6 +79,7 @@ import {
79
79
  prepareMcpSpawn, PUBLIC_MCP_UNAVAILABLE_CODE, publicMcpUnavailableError, selectedMcpVersionDir,
80
80
  } from '../mcp-home.js';
81
81
  import { buildMemoryPreamble } from '../memory-bridge.js';
82
+ import { claudeConfigDirFor, claudeContextTokens } from '../session-recycle.js';
82
83
  import { skillsAsText } from '../skill-prompt.js';
83
84
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
84
85
 
@@ -715,7 +716,10 @@ const prepareArgv = async (innerArgv, ctx) => {
715
716
  workspacePath: ctx.cwd,
716
717
  readOnlyPaths: [ctx.mcpConfigDir, commitHooksPath, originalHooksPath, ...(ctx.mcpReadDirectories || [])].filter(Boolean),
717
718
  });
718
- return { cmd: wrapped[0], args: wrapped.slice(1), env: claudeEnv };
719
+ // bwrap sets the child's HOME to the workspace (wrapArgvWithBwrap's
720
+ // default), so the child's transcript lands under the workspace, not the
721
+ // HOME the host process sees. TASK-440 reads from here.
722
+ return { cmd: wrapped[0], args: wrapped.slice(1), env: claudeEnv, childHome: ctx.cwd };
719
723
  }
720
724
  return { cmd: 'claude', args: innerArgv, env: claudeEnv };
721
725
  };
@@ -881,7 +885,7 @@ export default {
881
885
  publicSkillArgs,
882
886
  claudeEnv,
883
887
  };
884
- const { cmd, args, env } = await prepareArgv(baseArgs, spawnCtx);
888
+ const { cmd, args, env, childHome } = await prepareArgv(baseArgs, spawnCtx);
885
889
  const stdout = await runClaude({
886
890
  cmd,
887
891
  args,
@@ -895,7 +899,12 @@ export default {
895
899
  credentials: spawnCredentials(spawnCtx),
896
900
  spawnImpl: ctx._spawnImpl, // test seam only — do not use in production
897
901
  });
898
- return { text: stdout.trim(), newSessionId: sessionId };
902
+ // TASK-440: the context this turn left, read from the transcript the
903
+ // child wrote under its own env (an isolated HOME for public seats).
904
+ const contextTokens = claudeContextTokens({
905
+ cwd: ctx.cwd, sessionId, configDir: claudeConfigDirFor({ ...env, HOME: childHome || env?.HOME }),
906
+ });
907
+ return { text: stdout.trim(), newSessionId: sessionId, contextTokens };
899
908
  } catch (err) {
900
909
  // A public seat's refusal is not a session-store failure, whatever its
901
910
  // message happens to contain: it must reach the run loop, never the
@@ -941,7 +950,11 @@ export default {
941
950
  credentials: spawnCredentials(retryCtx),
942
951
  spawnImpl: ctx._spawnImpl,
943
952
  });
944
- return { text: stdout.trim(), newSessionId: freshId };
953
+ const contextTokens = claudeContextTokens({
954
+ cwd: ctx.cwd, sessionId: freshId,
955
+ configDir: claudeConfigDirFor({ ...retry.env, HOME: retry.childHome || retry.env?.HOME }),
956
+ });
957
+ return { text: stdout.trim(), newSessionId: freshId, contextTokens };
945
958
  }
946
959
  throw err;
947
960
  } finally {
@@ -9,8 +9,8 @@
9
9
  * stay in the host adapter and reach the configured provider through a
10
10
  * per-spawn loopback proxy; OpenCode receives only that proxy's bearer.
11
11
  * This protects the key, not provider spend: the model can use its seat's key
12
- * budget, and bwrap's existing shared networking is not a per-port egress
13
- * fence.
12
+ * budget. On Linux the process has its own network namespace, with loopback
13
+ * bridges to the fixed provider and Commonly instance origins.
14
14
  * Config is generated per spawn. OpenCode merges config sources, therefore the
15
15
  * global config directory is isolated and project config is explicitly off;
16
16
  * the environment spec is the sole source of MCP servers for this run.
@@ -34,6 +34,7 @@ import {
34
34
  writeFile,
35
35
  } from 'fs/promises';
36
36
  import { homedir, tmpdir } from 'os';
37
+ import { fileURLToPath } from 'url';
37
38
  import {
38
39
  dirname, join, resolve as pathResolve,
39
40
  } from 'path';
@@ -53,8 +54,12 @@ import { resolvePublicSandboxMode } from '../sandbox/mode.js';
53
54
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
54
55
  import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
55
56
  import { isAnswerableToolError } from '../public-tool-error.js';
57
+ import { startInstanceProxy } from '../instance-proxy.js';
56
58
 
57
59
  const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
60
+ const ISOLATED_PROXY_PORT = 8765;
61
+ const ISOLATED_INSTANCE_PORT = 8766;
62
+ const LOOPBACK_BRIDGE = fileURLToPath(new URL('../sandbox/opencode-loopback.mjs', import.meta.url));
58
63
  const TERMINATION_GRACE_MS = 5000;
59
64
  // Bump only with a passing real sandbox-exec smoke against the new version.
60
65
  const TESTED_OPENCODE_VERSIONS = Object.freeze(['1.18.35', '1.19.0']);
@@ -658,10 +663,6 @@ export default {
658
663
  if (isPublic && !provider) {
659
664
  throw new Error('public OpenCode seats require environment.provider; the implicit public tier and operator auth.json are unsupported for public trust');
660
665
  }
661
- if (isPublic && sandboxMode === 'bwrap' && provider
662
- && sandbox?.network?.policy === 'restricted') {
663
- throw new Error('public OpenCode provider proxy requires shared bwrap networking; sandbox.network.policy=restricted cannot reach the loopback proxy');
664
- }
665
666
  const providerKeyFile = await validateProviderEnvironment(ctx.environment, ctx.cwd);
666
667
 
667
668
  const sourceEnv = ctx.env || process.env;
@@ -727,6 +728,7 @@ export default {
727
728
  });
728
729
  let openCodeHome = null;
729
730
  let providerProxy = null;
731
+ let instanceProxy = null;
730
732
  try {
731
733
  openCodeHome = await prepareOpenCodeDataHome(ctx, { publicSeat: isPublic });
732
734
  if (isPublic && provider) {
@@ -736,6 +738,16 @@ export default {
736
738
  provider,
737
739
  keyFile: providerKeyFile,
738
740
  tokenFile: join(tempDir, 'provider-proxy-token'),
741
+ ...(sandboxMode === 'bwrap' ? {
742
+ socketPath: join(tempDir, 'provider-proxy.sock'),
743
+ isolatedPort: ISOLATED_PROXY_PORT,
744
+ } : {}),
745
+ });
746
+ }
747
+ if (isPublic && sandboxMode === 'bwrap' && ctx.instanceUrl) {
748
+ instanceProxy = await startInstanceProxy({
749
+ instanceUrl: ctx.instanceUrl,
750
+ socketPath: join(tempDir, 'instance-proxy.sock'),
739
751
  });
740
752
  }
741
753
  const stateHome = isPublic ? join(openCodeHome.root, 'state') : null;
@@ -750,7 +762,8 @@ export default {
750
762
  const mcpReadDirectories = [];
751
763
  const mcp = buildMcpConfig(ctx.environment?.mcp, {
752
764
  runtimeToken: ctx.runtimeToken,
753
- instanceUrl: ctx.instanceUrl,
765
+ instanceUrl: instanceProxy
766
+ ? `http://127.0.0.1:${ISOLATED_INSTANCE_PORT}` : ctx.instanceUrl,
754
767
  credentialFile: credential?.path || null,
755
768
  publicSeat: isPublic,
756
769
  unavailableMcp,
@@ -805,10 +818,15 @@ export default {
805
818
  }
806
819
  const bwrap = (ctx._detectBwrap || detectBwrap)();
807
820
  if (!bwrap.available) throw new Error(`public OpenCode agents require bwrap: ${bwrap.error}`);
808
- const wrapped = (ctx._wrapArgvWithBwrap || wrapArgvWithBwrap)([binary, ...args], {
821
+ const wrapped = (ctx._wrapArgvWithBwrap || wrapArgvWithBwrap)([
822
+ process.execPath, LOOPBACK_BRIDGE,
823
+ providerProxy.socketPath, String(ISOLATED_PROXY_PORT),
824
+ instanceProxy?.socketPath || '-', String(ISOLATED_INSTANCE_PORT), binary, ...args,
825
+ ], {
809
826
  ...ctx.environment,
810
827
  sandbox: {
811
828
  ...sandbox,
829
+ network: { ...sandbox?.network, policy: 'restricted' },
812
830
  filesystem: {
813
831
  ...(sandbox?.filesystem || {}),
814
832
  'write-outside': [
@@ -824,8 +842,11 @@ export default {
824
842
  tempDir,
825
843
  binary,
826
844
  process.execPath,
845
+ LOOPBACK_BRIDGE,
827
846
  ...mcpReadDirectories,
828
847
  ],
848
+ optionalReadOnlyPaths: ['/usr/sbin', '/sbin'],
849
+ enableLoopback: true,
829
850
  });
830
851
  [cmd, ...spawnArgs] = wrapped;
831
852
  } else if (isPublic) {
@@ -864,6 +885,7 @@ export default {
864
885
  ...(result.usage ? { usage: result.usage } : {}),
865
886
  };
866
887
  } finally {
888
+ try { await instanceProxy?.close(); } catch { /* ignore */ }
867
889
  try { await providerProxy?.close(); } catch { /* ignore */ }
868
890
  try { await rm(tempDir, { recursive: true, force: true }); } catch { /* ignore */ }
869
891
  }
@@ -0,0 +1,67 @@
1
+ /** A per-spawn Unix-socket relay to one declared Commonly instance origin. */
2
+ import { createServer, request as httpRequest } from 'http';
3
+ import { request as httpsRequest } from 'https';
4
+ import { chmod, unlink } from 'fs/promises';
5
+
6
+ export const startInstanceProxy = async ({ instanceUrl, socketPath }) => {
7
+ const target = new URL(instanceUrl);
8
+ if (!['http:', 'https:'].includes(target.protocol)
9
+ || target.username || target.password || target.search || target.hash
10
+ || target.pathname !== '/') {
11
+ throw new Error('Commonly instance proxy requires a bare http(s) origin');
12
+ }
13
+ const transport = target.protocol === 'https:' ? httpsRequest : httpRequest;
14
+ const upstreams = new Set();
15
+ const server = createServer((incoming, outgoing) => {
16
+ const path = incoming.url || '';
17
+ if (!path.startsWith('/') || path.startsWith('//')
18
+ || incoming.method === 'CONNECT' || incoming.headers.upgrade) {
19
+ incoming.resume();
20
+ outgoing.writeHead(400).end();
21
+ return;
22
+ }
23
+ const headers = { ...incoming.headers, host: target.host };
24
+ delete headers.connection;
25
+ delete headers['proxy-authorization'];
26
+ delete headers['proxy-connection'];
27
+ const upstream = transport(target, {
28
+ method: incoming.method,
29
+ path,
30
+ headers,
31
+ }, (response) => {
32
+ outgoing.writeHead(response.statusCode || 502, response.headers);
33
+ response.pipe(outgoing);
34
+ response.on('error', () => outgoing.destroy());
35
+ response.on('close', () => {
36
+ if (!response.complete) outgoing.destroy();
37
+ });
38
+ });
39
+ upstreams.add(upstream);
40
+ upstream.on('close', () => upstreams.delete(upstream));
41
+ outgoing.on('close', () => upstream.destroy());
42
+ upstream.on('error', () => {
43
+ if (outgoing.destroyed) return;
44
+ if (!outgoing.headersSent) outgoing.writeHead(502);
45
+ outgoing.end();
46
+ });
47
+ incoming.pipe(upstream);
48
+ });
49
+ await new Promise((resolve, reject) => {
50
+ server.once('error', reject);
51
+ server.listen(socketPath, () => {
52
+ server.removeListener('error', reject);
53
+ resolve();
54
+ });
55
+ });
56
+ await chmod(socketPath, 0o600);
57
+ return {
58
+ socketPath,
59
+ close: async () => {
60
+ const closed = new Promise((resolve) => server.close(resolve));
61
+ for (const upstream of upstreams) upstream.destroy();
62
+ server.closeAllConnections();
63
+ await closed;
64
+ await unlink(socketPath).catch((err) => { if (err.code !== 'ENOENT') throw err; });
65
+ },
66
+ };
67
+ };
@@ -3,7 +3,7 @@ import { randomBytes, timingSafeEqual } from 'crypto';
3
3
  import { constants as fsConstants, realpathSync } from 'fs';
4
4
  import { createServer, request as httpRequest } from 'http';
5
5
  import { request as httpsRequest } from 'https';
6
- import { chmod, lstat, open, writeFile } from 'fs/promises';
6
+ import { chmod, lstat, open, unlink, writeFile } from 'fs/promises';
7
7
  import { isAbsolute, relative, sep } from 'path';
8
8
 
9
9
  const isPathWithin = (parent, candidate) => {
@@ -68,9 +68,13 @@ const readProviderKey = async (keyFile, adapterLabel) => {
68
68
  };
69
69
 
70
70
  export const startProviderProxy = async ({
71
- provider, keyFile, tokenFile, adapterLabel = 'OpenCode',
71
+ provider, keyFile, tokenFile, socketPath, isolatedPort, adapterLabel = 'OpenCode',
72
72
  }) => {
73
73
  const upstream = new URL(provider.baseURL);
74
+ if (socketPath && (!isAbsolute(socketPath)
75
+ || !Number.isInteger(isolatedPort) || isolatedPort < 1 || isolatedPort > 65535)) {
76
+ throw new Error(`${adapterLabel} isolated proxy requires an absolute socket path and valid port`);
77
+ }
74
78
  if (!['http:', 'https:'].includes(upstream.protocol)
75
79
  || upstream.username || upstream.password || upstream.search || upstream.hash) {
76
80
  throw new Error(`${adapterLabel} provider.baseURL must be an http(s) URL without embedded credentials or query data`);
@@ -204,19 +208,33 @@ export const startProviderProxy = async ({
204
208
 
205
209
  await new Promise((resolve, reject) => {
206
210
  server.once('error', reject);
207
- server.listen(0, '127.0.0.1', () => {
211
+ const started = () => {
208
212
  server.removeListener('error', reject);
209
213
  resolve();
210
- });
214
+ };
215
+ if (socketPath) server.listen(socketPath, started);
216
+ else server.listen(0, '127.0.0.1', started);
211
217
  });
212
- const { port } = server.address();
218
+ if (socketPath) {
219
+ try {
220
+ await chmod(socketPath, 0o600);
221
+ } catch (err) {
222
+ await new Promise((resolve) => server.close(resolve));
223
+ throw err;
224
+ }
225
+ }
226
+ const port = socketPath ? isolatedPort : server.address().port;
213
227
  const proxyBaseURL = new URL(upstream.pathname, `http://127.0.0.1:${port}`).toString();
214
228
  return {
215
229
  baseURL: proxyBaseURL,
216
230
  tokenFile,
231
+ socketPath,
217
232
  port,
218
233
  close: () => new Promise((resolve) => {
219
- server.close(() => resolve());
234
+ server.close(async () => {
235
+ if (socketPath) await unlink(socketPath).catch(() => {});
236
+ resolve();
237
+ });
220
238
  server.closeAllConnections?.();
221
239
  }),
222
240
  };
@@ -86,10 +86,9 @@ export const detectBwrap = ({ spawn = spawnSync, platform = process.platform } =
86
86
  *
87
87
  * Network policy honesty (ADR-008 §invariant #4 informs this):
88
88
  * - unrestricted → --share-net (host networking inside the namespace)
89
- * - restricted → --unshare-net (NO network at all). Host-allowlist
90
- * filtering needs an outbound proxy or per-host TLS interception, neither
91
- * of which is in Phase 1 scope. Attach-time emits a loud warning so the
92
- * user sees the gap before they think they're protected.
89
+ * - restricted → --unshare-net (no external network). OpenCode may opt
90
+ * into a private loopback bridge to its per-spawn Unix-socket proxy.
91
+ * Host-allowlist filtering is not supplied by bwrap itself.
93
92
  *
94
93
  * The expansion order matches `bwrap`'s left-to-right argument application:
95
94
  * isolation flags first, then binds (later binds win on collision), then the
@@ -112,10 +111,17 @@ export const wrapArgvWithBwrap = (innerArgv, env, opts = {}) => {
112
111
  const networkFlags = policy === 'restricted'
113
112
  ? ['--unshare-net']
114
113
  : ['--share-net'];
114
+ if (opts.enableLoopback && policy !== 'restricted') {
115
+ throw new Error('bwrap loopback bridge requires an isolated network namespace');
116
+ }
115
117
 
116
118
  const flags = [
117
119
  '--unshare-all',
118
120
  ...networkFlags,
121
+ ...(opts.enableLoopback ? [
122
+ '--uid', '0', '--gid', '0',
123
+ '--cap-add', 'CAP_NET_ADMIN', '--cap-add', 'CAP_SETPCAP',
124
+ ] : []),
119
125
  '--die-with-parent',
120
126
  '--new-session',
121
127
  '--proc', '/proc',
@@ -148,6 +154,12 @@ export const wrapArgvWithBwrap = (innerArgv, env, opts = {}) => {
148
154
  }
149
155
  flags.push('--ro-bind', p, p);
150
156
  }
157
+ for (const p of opts.optionalReadOnlyPaths || []) {
158
+ if (!p || !isAbsolute(p)) {
159
+ throw new Error('wrapArgvWithBwrap opts.optionalReadOnlyPaths entries must be absolute paths');
160
+ }
161
+ flags.push('--ro-bind-try', p, p);
162
+ }
151
163
 
152
164
  flags.push('--bind', opts.workspacePath, opts.workspacePath);
153
165
  flags.push('--chdir', opts.workspacePath);
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Runs inside OpenCode's private bwrap network namespace. The only route to
3
+ * the host is through the two fixed-origin Unix sockets bound for this spawn.
4
+ */
5
+ import { spawn, spawnSync } from 'child_process';
6
+ import { existsSync } from 'fs';
7
+ import { createServer, connect } from 'net';
8
+
9
+ const [socketPath, portText, instanceSocketPath, instancePortText, binary, ...args] = process.argv.slice(2);
10
+ const port = Number(portText);
11
+ const instancePort = Number(instancePortText);
12
+ if (!socketPath || !instanceSocketPath || !binary
13
+ || !Number.isInteger(port) || port < 1 || port > 65535
14
+ || !Number.isInteger(instancePort) || instancePort < 1 || instancePort > 65535
15
+ || port === instancePort) {
16
+ throw new Error('OpenCode loopback bridge requires distinct provider and instance ports');
17
+ }
18
+
19
+ const ip = ['/usr/sbin/ip', '/sbin/ip', '/usr/bin/ip', '/bin/ip'].find(existsSync);
20
+ if (!ip) throw new Error('OpenCode isolated loopback requires iproute2');
21
+ const up = spawnSync(ip, ['link', 'set', 'lo', 'up'], { encoding: 'utf8' });
22
+ if (up.error || up.status !== 0) {
23
+ throw new Error(`OpenCode isolated loopback could not start: ${up.error?.message || up.stderr?.trim() || up.status}`);
24
+ }
25
+ const setpriv = ['/usr/bin/setpriv', '/bin/setpriv'].find(existsSync);
26
+ if (!setpriv) throw new Error('OpenCode isolated loopback requires setpriv');
27
+
28
+ const sockets = new Set();
29
+ const makeBridge = (path) => createServer((local) => {
30
+ const proxy = connect(path);
31
+ sockets.add(local);
32
+ sockets.add(proxy);
33
+ local.on('close', () => sockets.delete(local));
34
+ proxy.on('close', () => sockets.delete(proxy));
35
+ local.on('error', () => proxy.destroy());
36
+ proxy.on('error', () => local.destroy());
37
+ local.pipe(proxy).pipe(local);
38
+ });
39
+ const providerBridge = makeBridge(socketPath);
40
+ const instanceBridge = instanceSocketPath === '-' ? null : makeBridge(instanceSocketPath);
41
+ providerBridge.on('error', (err) => { throw err; });
42
+ instanceBridge?.on('error', (err) => { throw err; });
43
+ providerBridge.listen(port, '127.0.0.1', () => {
44
+ const startChild = () => {
45
+ // Only this bridge needs CAP_NET_ADMIN to raise lo and CAP_SETPCAP to drop
46
+ // both capabilities before starting the model process.
47
+ const child = spawn(setpriv, [
48
+ '--bounding-set=-net_admin,-setpcap',
49
+ '--inh-caps=-net_admin,-setpcap',
50
+ '--ambient-caps=-net_admin,-setpcap',
51
+ binary, ...args,
52
+ ], { stdio: 'inherit', env: process.env });
53
+ const forward = (signal) => { if (!child.killed) child.kill(signal); };
54
+ process.on('SIGTERM', () => forward('SIGTERM'));
55
+ process.on('SIGINT', () => forward('SIGINT'));
56
+ child.on('error', (err) => {
57
+ process.stderr.write(`${err.message}\n`);
58
+ });
59
+ child.on('close', (code, signal) => {
60
+ for (const socket of sockets) socket.destroy();
61
+ providerBridge.close();
62
+ if (instanceBridge) instanceBridge.close(() => { process.exitCode = code ?? (signal === 'SIGTERM' ? 143 : 1); });
63
+ else process.exitCode = code ?? (signal === 'SIGTERM' ? 143 : 1);
64
+ });
65
+ };
66
+ if (instanceBridge) instanceBridge.listen(instancePort, '127.0.0.1', startChild);
67
+ else startChild();
68
+ });
@@ -0,0 +1,131 @@
1
+ /**
2
+ * At-wake session recycle (TASK-440).
3
+ *
4
+ * A seat resumes its CLI session on every wake, so a long-lived seat drags a
5
+ * large cold context into each turn. When a wake finds the seat idle long
6
+ * enough that the prompt cache is cold AND the last session's context is big
7
+ * enough to matter, start a fresh session instead, seeded with a short
8
+ * restart note. Otherwise resume exactly as before.
9
+ *
10
+ * Thresholds are per-install: COMMONLY_SESSION_RECYCLE_IDLE_MINUTES and
11
+ * COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS override the defaults below.
12
+ *
13
+ * Context size is read from the transcript the child CLI wrote, under the env
14
+ * the child ran with. Only the claude adapter reports one today; an adapter
15
+ * that reports nothing keeps resuming, as before this module existed.
16
+ */
17
+
18
+ import { closeSync, existsSync, fstatSync, openSync, readSync } from 'fs';
19
+ import { join } from 'path';
20
+ import { homedir } from 'os';
21
+
22
+ export const RECYCLE_DEFAULTS = Object.freeze({
23
+ idleMinutes: 60,
24
+ contextTokens: 128000,
25
+ });
26
+
27
+ // Read this many bytes from the end of a transcript. The last assistant
28
+ // usage record sits near the end; a full read of a long-lived transcript
29
+ // would cost more than the recycle saves.
30
+ const TRANSCRIPT_TAIL_BYTES = 4 * 1024 * 1024;
31
+
32
+ const positiveNumber = (raw, fallback) => {
33
+ const value = Number(raw);
34
+ return Number.isFinite(value) && value > 0 ? value : fallback;
35
+ };
36
+
37
+ export const recycleThresholds = (env = process.env) => ({
38
+ idleMinutes: positiveNumber(env.COMMONLY_SESSION_RECYCLE_IDLE_MINUTES, RECYCLE_DEFAULTS.idleMinutes),
39
+ contextTokens: positiveNumber(env.COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS, RECYCLE_DEFAULTS.contextTokens),
40
+ });
41
+
42
+ // Pure decision. No evidence (no last turn, no measured context) means resume.
43
+ export const shouldStartFreshSession = ({
44
+ lastTurn,
45
+ contextTokens,
46
+ now = Date.now(),
47
+ thresholds = RECYCLE_DEFAULTS,
48
+ }) => {
49
+ if (!lastTurn || !Number.isFinite(contextTokens)) return false;
50
+ const last = Date.parse(lastTurn);
51
+ if (!Number.isFinite(last)) return false;
52
+ const idleMs = now - last;
53
+ return idleMs >= thresholds.idleMinutes * 60_000
54
+ && contextTokens >= thresholds.contextTokens;
55
+ };
56
+
57
+ export const idleMinutesSince = (lastTurn, now = Date.now()) => {
58
+ const last = Date.parse(lastTurn);
59
+ return Number.isFinite(last) ? Math.floor((now - last) / 60_000) : null;
60
+ };
61
+
62
+ // The restart note. The memory head and the pod focus are NOT repeated here:
63
+ // a fresh claude session already receives the full long_term memory through
64
+ // its preamble, and the pod focus is already in the wake prompt.
65
+ export const buildRecycleBriefing = ({ agentName, idleMinutes, contextTokens }) => [
66
+ '=== Session restart ===',
67
+ `This wake starts a fresh session. The previous session was idle ${idleMinutes} min`
68
+ + ` with about ${contextTokens} context tokens, so it was not resumed.`,
69
+ `Role: ${agentName}. Your saved memory and the pod focus follow below.`,
70
+ ].join('\n');
71
+
72
+ // The config dir the CHILD claude process uses. A public seat runs claude
73
+ // under an isolated HOME, so reading the operator's ~/.claude would find no
74
+ // transcript and the recycle would never fire.
75
+ export const claudeConfigDirFor = (env = process.env) => (
76
+ env?.CLAUDE_CONFIG_DIR || join(env?.HOME || homedir(), '.claude')
77
+ );
78
+
79
+ // Claude Code stores a session at
80
+ // <config>/projects/<cwd with every non-alphanumeric character as '-'>/<id>.jsonl
81
+ export const claudeTranscriptPath = ({ cwd, sessionId, configDir = claudeConfigDirFor() }) => {
82
+ if (!cwd || !sessionId) return null;
83
+ const encoded = cwd.replace(/[^a-zA-Z0-9]/g, '-');
84
+ return join(configDir, 'projects', encoded, `${sessionId}.jsonl`);
85
+ };
86
+
87
+ const readTail = (file) => {
88
+ const fd = openSync(file, 'r');
89
+ try {
90
+ const size = fstatSync(fd).size;
91
+ const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
92
+ const buffer = Buffer.alloc(length);
93
+ readSync(fd, buffer, 0, length, size - length);
94
+ return buffer.toString('utf8');
95
+ } finally {
96
+ closeSync(fd);
97
+ }
98
+ };
99
+
100
+ // Context tokens of the most recent assistant turn: uncached input plus the
101
+ // cache creation and cache read that make up the prompt sent that turn.
102
+ export const contextTokensFromTranscript = (text) => {
103
+ const lines = text.split('\n');
104
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
105
+ const line = lines[index].trim();
106
+ if (!line) continue;
107
+ let record;
108
+ try {
109
+ record = JSON.parse(line);
110
+ } catch {
111
+ continue; // the first line of a tail read can be cut mid-record
112
+ }
113
+ const usage = record?.message?.usage;
114
+ if (record?.type === 'assistant' && usage && typeof usage === 'object') {
115
+ return (usage.input_tokens || 0)
116
+ + (usage.cache_creation_input_tokens || 0)
117
+ + (usage.cache_read_input_tokens || 0);
118
+ }
119
+ }
120
+ return null;
121
+ };
122
+
123
+ export const claudeContextTokens = ({ cwd, sessionId, configDir = claudeConfigDirFor() }) => {
124
+ const file = claudeTranscriptPath({ cwd, sessionId, configDir });
125
+ if (!file || !existsSync(file)) return null;
126
+ try {
127
+ return contextTokensFromTranscript(readTail(file));
128
+ } catch {
129
+ return null;
130
+ }
131
+ };
@@ -89,6 +89,15 @@ export const getSession = (agentName, podId, { binding = null } = {}) => {
89
89
  return entry?.sessionId || null;
90
90
  };
91
91
 
92
+ // The whole per-pod entry (sessionId, lastTurn, contextTokens), for the
93
+ // at-wake recycle decision. getSession stays the resume-only reader.
94
+ export const getSessionEntry = (agentName, podId, { binding = null } = {}) => {
95
+ if (!agentName || !podId) return null;
96
+ const entry = readAgent(agentName)[podId];
97
+ if (!entry || (binding !== null && entry.binding !== binding)) return null;
98
+ return entry;
99
+ };
100
+
92
101
  // Read-only diagnostic projection used by the daemon operator surface. A
93
102
  // wrapper may serve several pods, so return the newest completed turn.
94
103
  export const getLastTurn = (agentName) => {
@@ -101,13 +110,14 @@ export const getLastTurn = (agentName) => {
101
110
  .at(-1) || null;
102
111
  };
103
112
 
104
- export const setSession = (agentName, podId, sessionId, { binding = null } = {}) => {
113
+ export const setSession = (agentName, podId, sessionId, { binding = null, contextTokens = null } = {}) => {
105
114
  if (!agentName || !podId) return;
106
115
  const state = readAgent(agentName);
107
116
  state[podId] = {
108
117
  sessionId,
109
118
  lastTurn: new Date().toISOString(),
110
119
  ...(binding !== null ? { binding } : {}),
120
+ ...(Number.isFinite(contextTokens) ? { contextTokens } : {}),
111
121
  };
112
122
  writeAgent(agentName, state);
113
123
  };