@commonlyai/cli 0.1.323 → 0.1.325
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
package/src/commands/agent.js
CHANGED
|
@@ -96,6 +96,9 @@ import {
|
|
|
96
96
|
withDefaultSandbox,
|
|
97
97
|
} from '../lib/default-environment.js';
|
|
98
98
|
import { mergeGrantBrokers, withholdGrantBroker } from '../lib/grant-broker-guard.js';
|
|
99
|
+
import {
|
|
100
|
+
OUTSIDER_GRANT_MCP_UNCONFINED, outsiderGrantMcpRefusal, seatIsConfined, unshippedMcpEntries,
|
|
101
|
+
} from '../lib/outsider-grant-mcp.js';
|
|
99
102
|
import {
|
|
100
103
|
FOCUS_FRAME_MAX_CODE_POINTS,
|
|
101
104
|
formatPodFocusFrame,
|
|
@@ -2868,6 +2871,44 @@ export const performRun = ({
|
|
|
2868
2871
|
};
|
|
2869
2872
|
}
|
|
2870
2873
|
}
|
|
2874
|
+
// §12 C: a confined seat that a connector grant may reach runs with only the
|
|
2875
|
+
// shipped MCP servers (lib/outsider-grant-mcp.js). The server is asked only
|
|
2876
|
+
// when this turn's set holds something else, so an ordinary seat makes no
|
|
2877
|
+
// extra read. A failed read defers the turn, as the placement read does.
|
|
2878
|
+
if (seatIsConfined(placement.environment) && unshippedMcpEntries(placement.environment, instanceUrl).length) {
|
|
2879
|
+
let identity;
|
|
2880
|
+
try {
|
|
2881
|
+
identity = await client.get('/api/agents/runtime/installations', {}, {
|
|
2882
|
+
signal: AbortSignal.timeout(5000),
|
|
2883
|
+
});
|
|
2884
|
+
} catch (err) {
|
|
2885
|
+
throw Object.assign(
|
|
2886
|
+
new Error(`turn deferred, because whether a connector grant reaches this seat could not be read: ${err.message}`, {
|
|
2887
|
+
cause: err,
|
|
2888
|
+
}),
|
|
2889
|
+
{ status: err.status },
|
|
2890
|
+
);
|
|
2891
|
+
}
|
|
2892
|
+
const mcpRefusal = outsiderGrantMcpRefusal({ environment: placement.environment, identity, instanceUrl });
|
|
2893
|
+
if (mcpRefusal) {
|
|
2894
|
+
log(`turn refused: ${mcpRefusal.message}`);
|
|
2895
|
+
if (event.type === 'agent.ask' && event.payload?.requestId) {
|
|
2896
|
+
try {
|
|
2897
|
+
await client.post(
|
|
2898
|
+
`/api/agents/runtime/asks/${encodeURIComponent(event.payload.requestId)}/respond`,
|
|
2899
|
+
{ content: 'I can’t take this ask: I’m set up with tools that can’t run next to this pod’s connector.' },
|
|
2900
|
+
);
|
|
2901
|
+
} catch (err) {
|
|
2902
|
+
if (err?.status !== 409 || err?.body?.code !== 'already_responded') throw err;
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
return {
|
|
2906
|
+
outcome: 'no_action',
|
|
2907
|
+
refused: { reason: 'delivery-refused' },
|
|
2908
|
+
reason: OUTSIDER_GRANT_MCP_UNCONFINED,
|
|
2909
|
+
};
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2871
2912
|
// TASK-440: a cold, large session starts fresh at wake instead of being
|
|
2872
2913
|
// resumed, and F392: so does one past the hard ceiling, however recently it
|
|
2873
2914
|
// ran. The restart note leads the prompt; memory still reaches the fresh
|
|
@@ -87,6 +87,7 @@ import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
|
|
|
87
87
|
import { publicSeatWithheldTools } from '../public-withheld-tools.js';
|
|
88
88
|
import { startProviderProxy } from '../provider-proxy.js';
|
|
89
89
|
import { resolveLaunch, resolveMcpCommand, resolveWindowsCommandWithReason } from '../windows-command.js';
|
|
90
|
+
import { codexContextTokens, codexHomeFor } from '../session-recycle.js';
|
|
90
91
|
|
|
91
92
|
// Default timeout for a single codex spawn (exec mode).
|
|
92
93
|
//
|
|
@@ -1316,13 +1317,20 @@ export default {
|
|
|
1316
1317
|
// came in with > null. The wrapper persists whichever non-null value
|
|
1317
1318
|
// we return so subsequent turns hit `codex exec resume <id>`.
|
|
1318
1319
|
const newSessionId = threadId || ctx.sessionId || null;
|
|
1320
|
+
// F404: what the turn's last request was sent, from the rollout the child
|
|
1321
|
+
// wrote under its own CODEX_HOME. Null keeps resuming.
|
|
1322
|
+
const contextTokens = newSessionId
|
|
1323
|
+
? (ctx._codexContextTokens || codexContextTokens)({ codexHome: codexHomeFor(childEnv), sessionId: newSessionId })
|
|
1324
|
+
: null;
|
|
1319
1325
|
// D247: the reply receipt names the model and effort this spawn passed
|
|
1320
1326
|
// (`--model`, `model_reasoning_effort`); codex's own stream does not
|
|
1321
1327
|
// restate them.
|
|
1322
1328
|
const effort = ctx.environment?.effort;
|
|
1323
1329
|
const stats = { ...(seatModel ? { model: String(seatModel) } : {}),
|
|
1324
1330
|
...(typeof effort === 'string' && effort ? { effort } : {}) };
|
|
1325
|
-
return {
|
|
1331
|
+
return {
|
|
1332
|
+
text, newSessionId, contextTokens, ...(Object.keys(stats).length ? { stats } : {}),
|
|
1333
|
+
};
|
|
1326
1334
|
} finally {
|
|
1327
1335
|
try { await providerProxy?.close(); } catch { /* ignore */ }
|
|
1328
1336
|
try { await rm(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
package/src/lib/adapters/dsh.js
CHANGED
|
@@ -32,6 +32,7 @@ import { describeMcpCommand } from '../mcp-server-version.js';
|
|
|
32
32
|
import { writeCredentialFile } from '../credential-file.js';
|
|
33
33
|
import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
|
|
34
34
|
import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
|
|
35
|
+
import { promptTokens } from '../session-recycle.js';
|
|
35
36
|
|
|
36
37
|
export const TESTED_DSH_VERSIONS = Object.freeze(['0.2.1-rc.2']);
|
|
37
38
|
const PROXY_KEY_ENV = 'COMMONLY_DSH_PROXY_KEY';
|
|
@@ -269,6 +270,13 @@ const parseEvent = (line, state) => {
|
|
|
269
270
|
try { event = JSON.parse(line); } catch { throw new Error('dsh emitted invalid JSON event'); }
|
|
270
271
|
if (event.type === 'session' && typeof event.sessionId === 'string') state.sessionId = event.sessionId;
|
|
271
272
|
if (event.type === 'final' && typeof event.text === 'string') state.final = event.text;
|
|
273
|
+
// F404: each step_end carries that request's usage, input apart from the cache.
|
|
274
|
+
if (event.type === 'status' && event.phase === 'step_end' && event.usage && typeof event.usage === 'object') {
|
|
275
|
+
const tokens = promptTokens({
|
|
276
|
+
input: event.usage.inputTokens, cacheRead: event.usage.cacheReadTokens, cacheWrite: event.usage.cacheWriteTokens,
|
|
277
|
+
});
|
|
278
|
+
if (tokens !== null) state.contextTokens = tokens;
|
|
279
|
+
}
|
|
272
280
|
if (event.type === 'error') state.error = String(event.message || event.error || 'dsh error');
|
|
273
281
|
if (event.type === 'tool_result'
|
|
274
282
|
&& /SANDBOX_UNAVAILABLE|sandbox_apply: Operation not permitted/.test(JSON.stringify(event))) {
|
|
@@ -281,7 +289,9 @@ export const runDsh = ({
|
|
|
281
289
|
}) => new Promise((resolve, reject) => {
|
|
282
290
|
const proc = spawnInOwnGroup(spawnImpl, binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] }, { ownGroup });
|
|
283
291
|
observeSpawn(proc, onSpawn, controls);
|
|
284
|
-
const state = {
|
|
292
|
+
const state = {
|
|
293
|
+
sessionId: null, final: null, error: null, buffer: '', contextTokens: null,
|
|
294
|
+
};
|
|
285
295
|
let stderr = '';
|
|
286
296
|
let timedOut = false;
|
|
287
297
|
let parseFailure = null;
|
|
@@ -326,7 +336,7 @@ export const runDsh = ({
|
|
|
326
336
|
|| (code !== 0 ? stderr.trim() || `exit ${code}` : null)
|
|
327
337
|
|| (state.final === null ? 'no final event' : null);
|
|
328
338
|
if (failure) return finish(adapterFailure('dsh', failure, { credentials, exitCode: code, limit: 500 }));
|
|
329
|
-
return finish(null, { text: state.final.trim(), newSessionId: state.sessionId });
|
|
339
|
+
return finish(null, { text: state.final.trim(), newSessionId: state.sessionId, contextTokens: state.contextTokens });
|
|
330
340
|
});
|
|
331
341
|
});
|
|
332
342
|
|
package/src/lib/adapters/pi.js
CHANGED
|
@@ -72,6 +72,7 @@ import { resolvePublicSandboxMode } from '../sandbox/mode.js';
|
|
|
72
72
|
import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
|
|
73
73
|
import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
|
|
74
74
|
import { publicSeatWithheldTools } from '../public-withheld-tools.js';
|
|
75
|
+
import { promptTokens } from '../session-recycle.js';
|
|
75
76
|
|
|
76
77
|
const DEFAULT_TIMEOUT_MS = (() => {
|
|
77
78
|
const fallback = 15 * 60 * 1000;
|
|
@@ -544,6 +545,7 @@ export const buildArgs = ({
|
|
|
544
545
|
*/
|
|
545
546
|
export const extractReply = (stdout) => {
|
|
546
547
|
let text = '';
|
|
548
|
+
let usage = null;
|
|
547
549
|
let sawAssistant = false;
|
|
548
550
|
let finished = false;
|
|
549
551
|
let lastStop = null;
|
|
@@ -556,6 +558,8 @@ export const extractReply = (stdout) => {
|
|
|
556
558
|
if (event?.type === 'message_end' && event.message?.role === 'assistant') {
|
|
557
559
|
const parts = (event.message.content || []).filter((c) => c?.type === 'text').map((c) => c.text || '');
|
|
558
560
|
if (parts.length) { text = parts.join('\n').trim(); sawAssistant = true; }
|
|
561
|
+
// F404: the last request's prompt, input counted apart from the cache.
|
|
562
|
+
if (event.message.usage && typeof event.message.usage === 'object') usage = event.message.usage;
|
|
559
563
|
lastStop = event.message.stopReason;
|
|
560
564
|
lastError = typeof event.message.errorMessage === 'string' ? event.message.errorMessage : undefined;
|
|
561
565
|
finished = false;
|
|
@@ -564,7 +568,7 @@ export const extractReply = (stdout) => {
|
|
|
564
568
|
if (event?.type === 'error') errors.push(String(event.message || event.error || 'error'));
|
|
565
569
|
}
|
|
566
570
|
return {
|
|
567
|
-
text, sawAssistant, finished, lastStop, lastError, errors,
|
|
571
|
+
text, sawAssistant, finished, lastStop, lastError, errors, contextTokens: usage ? promptTokens(usage) : null,
|
|
568
572
|
};
|
|
569
573
|
};
|
|
570
574
|
|
|
@@ -976,6 +980,8 @@ export default {
|
|
|
976
980
|
return {
|
|
977
981
|
text: reply.text,
|
|
978
982
|
newSessionId: sessionId,
|
|
983
|
+
// F404: the F392 ceiling and cold rule read this; null keeps resuming.
|
|
984
|
+
contextTokens: reply.contextTokens ?? null,
|
|
979
985
|
upstream: reply.upstream ?? null,
|
|
980
986
|
...(reply.failure ? { failure: reply.failure } : {}),
|
|
981
987
|
};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A confined seat that an outsider-writable grant reaches runs with only the
|
|
3
|
+
* shipped MCP servers (docs/plans/hosted-mcp-connection-scope.md §12 C).
|
|
4
|
+
*
|
|
5
|
+
* While a grant whose source outsiders can write reaches one of a seat's pods,
|
|
6
|
+
* the server narrows what the seat's token can do (§12 A). It cannot see the
|
|
7
|
+
* MCP servers the seat loads on this machine, though. The daemon admits a
|
|
8
|
+
* declared stdio entry that equals one in the local token record
|
|
9
|
+
* (`auditDeclaredMcp`), so a server its owner installed locally can sit beside
|
|
10
|
+
* the grant's results, and content an outsider wrote can steer it. So before
|
|
11
|
+
* each turn, a confined seat that may be narrowed is refused while its MCP set
|
|
12
|
+
* holds anything but the shipped Commonly server or a shipped grant broker.
|
|
13
|
+
*
|
|
14
|
+
* The effective set is the declared one. A confined seat's adapter excludes
|
|
15
|
+
* user- and project-scope MCP config (claude `--strict-mcp-config`, codex
|
|
16
|
+
* `--ignore-user-config`, isolated homes for the others), and
|
|
17
|
+
* `outsider-grant-mcp.test.mjs` pins those flags, so a scope added to an
|
|
18
|
+
* adapter fails that test before it widens this set.
|
|
19
|
+
*
|
|
20
|
+
* Only confined seats (`sandbox.trust` public or workspace, with the legacy
|
|
21
|
+
* `internal` read as public) are checked. An
|
|
22
|
+
* unconfined seat named on a grant runs on its owner's machine with a shell,
|
|
23
|
+
* under the owner's consent that what it reads can leave, so a local MCP
|
|
24
|
+
* server adds nothing it lacks (§12, the F94 amendment).
|
|
25
|
+
*/
|
|
26
|
+
import { isShippedCommonlyMcpEntry, isShippedGrantBrokerEntry } from './declared-mcp-guard.js';
|
|
27
|
+
import { effectiveSandboxTrust } from './environment.js';
|
|
28
|
+
|
|
29
|
+
export const OUTSIDER_GRANT_MCP_UNCONFINED = 'outsider_grant_mcp_unconfined';
|
|
30
|
+
|
|
31
|
+
const CONFINED_TRUSTS = new Set(['public', 'workspace']);
|
|
32
|
+
|
|
33
|
+
// Read through the legacy table, as the broker guard and the adapters read it:
|
|
34
|
+
// a record still carrying `internal` is confined as `public`, and is handed
|
|
35
|
+
// the broker as a public seat, so it is checked as one.
|
|
36
|
+
export const seatIsConfined = (environment) => CONFINED_TRUSTS.has(
|
|
37
|
+
effectiveSandboxTrust(environment?.sandbox?.trust),
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
// The server flags a broker on a grant that names this seat (`byoNamed`). It is
|
|
41
|
+
// a marker for the guard, not something the client reads, so it is set aside
|
|
42
|
+
// before the whole-entry match, and only as exactly `true`.
|
|
43
|
+
const withoutByoNamedFlag = (server) => {
|
|
44
|
+
if (!server || typeof server !== 'object' || server.byoNamed !== true) return server;
|
|
45
|
+
const { byoNamed: _byoNamed, ...rest } = server;
|
|
46
|
+
return rest;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** The entries of a turn's MCP set that are neither shipped server. */
|
|
50
|
+
export const unshippedMcpEntries = (environment, instanceUrl) => {
|
|
51
|
+
const servers = Array.isArray(environment?.mcp) ? environment.mcp : [];
|
|
52
|
+
return servers.filter((server) => !isShippedCommonlyMcpEntry(server)
|
|
53
|
+
&& !isShippedGrantBrokerEntry(withoutByoNamedFlag(server), instanceUrl));
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Whether the server's answer leaves the seat possibly narrowed. Only an
|
|
58
|
+
* explicit `outsiderGrantNarrowed: false` clears it. A server from before the
|
|
59
|
+
* field, or an answer that lacks it, counts as narrowed, because the CLI
|
|
60
|
+
* publishes before the server change is deployed.
|
|
61
|
+
*/
|
|
62
|
+
export const mayBeNarrowed = (identity) => identity?.outsiderGrantNarrowed !== false;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @returns {null | { code: string, names: string[], message: string }}
|
|
66
|
+
*/
|
|
67
|
+
export const outsiderGrantMcpRefusal = ({ environment, identity, instanceUrl }) => {
|
|
68
|
+
if (!seatIsConfined(environment)) return null;
|
|
69
|
+
const extra = unshippedMcpEntries(environment, instanceUrl);
|
|
70
|
+
if (!extra.length || !mayBeNarrowed(identity)) return null;
|
|
71
|
+
const names = extra.map((server) => String(server?.name || '(unnamed)'));
|
|
72
|
+
const why = identity && 'outsiderGrantNarrowed' in identity
|
|
73
|
+
? 'a connector grant whose source outsiders can write reaches one of its pods'
|
|
74
|
+
: 'the server did not say whether a connector grant reaches its pods, so it is treated as if one does';
|
|
75
|
+
return {
|
|
76
|
+
code: OUTSIDER_GRANT_MCP_UNCONFINED,
|
|
77
|
+
names,
|
|
78
|
+
message: `${OUTSIDER_GRANT_MCP_UNCONFINED}: this seat loads MCP servers beyond the shipped Commonly server `
|
|
79
|
+
+ `and grant broker (${names.join(', ')}), and ${why}. Remove them from the seat's environment, `
|
|
80
|
+
+ 'or use a separate agent for the connector pod.',
|
|
81
|
+
};
|
|
82
|
+
};
|
|
@@ -15,12 +15,15 @@
|
|
|
15
15
|
* COMMONLY_SESSION_RECYCLE_CONTEXT_TOKENS and
|
|
16
16
|
* COMMONLY_SESSION_RECYCLE_MAX_CONTEXT_TOKENS override the defaults below.
|
|
17
17
|
*
|
|
18
|
-
* Context size is
|
|
19
|
-
* the child
|
|
20
|
-
*
|
|
18
|
+
* Context size is what the last model request of the turn was sent: claude and
|
|
19
|
+
* codex from the transcript the child CLI wrote, under the env it ran with; pi
|
|
20
|
+
* and dsh from the usage on their own JSON stream (F404). An adapter that
|
|
21
|
+
* reports nothing keeps resuming, as before this module existed.
|
|
21
22
|
*/
|
|
22
23
|
|
|
23
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
closeSync, existsSync, fstatSync, openSync, readdirSync, readSync,
|
|
26
|
+
} from 'fs';
|
|
24
27
|
import { join } from 'path';
|
|
25
28
|
import { homedir } from 'os';
|
|
26
29
|
|
|
@@ -136,6 +139,75 @@ export const contextTokensFromTranscript = (text) => {
|
|
|
136
139
|
return null;
|
|
137
140
|
};
|
|
138
141
|
|
|
142
|
+
/**
|
|
143
|
+
* The prompt one request was sent, from a usage block that counts cached tokens
|
|
144
|
+
* apart from `input` (pi's message usage, dsh's step usage). Null when `input`
|
|
145
|
+
* is missing, so a stream without usage reads as unknown, not as zero.
|
|
146
|
+
*/
|
|
147
|
+
export const promptTokens = ({ input, cacheRead, cacheWrite } = {}) => {
|
|
148
|
+
if (!Number.isFinite(input)) return null;
|
|
149
|
+
return input + (Number.isFinite(cacheRead) ? cacheRead : 0) + (Number.isFinite(cacheWrite) ? cacheWrite : 0);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// F404. codex keeps a session as <home>/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl,
|
|
153
|
+
// dated by when it began; `exec resume` appends to that same file. Newest day
|
|
154
|
+
// first, so a live session is found after a few directory reads.
|
|
155
|
+
const newestFirst = (dir) => {
|
|
156
|
+
try {
|
|
157
|
+
return readdirSync(dir).sort().reverse();
|
|
158
|
+
} catch {
|
|
159
|
+
return [];
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
export const codexHomeFor = (env = process.env) => env?.CODEX_HOME || join(env?.HOME || homedir(), '.codex');
|
|
164
|
+
|
|
165
|
+
export const codexRolloutPath = ({ codexHome = codexHomeFor(), sessionId }) => {
|
|
166
|
+
if (!sessionId) return null;
|
|
167
|
+
const root = join(codexHome, 'sessions');
|
|
168
|
+
const suffix = `-${sessionId}.jsonl`;
|
|
169
|
+
for (const year of newestFirst(root)) {
|
|
170
|
+
for (const month of newestFirst(join(root, year))) {
|
|
171
|
+
for (const day of newestFirst(join(root, year, month))) {
|
|
172
|
+
const name = newestFirst(join(root, year, month, day)).find((file) => file.endsWith(suffix));
|
|
173
|
+
if (name) return join(root, year, month, day, name);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return null;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// The last request's prompt from codex's own `token_count` record. Its
|
|
181
|
+
// `input_tokens` already includes the cached part (`cached_input_tokens` is a
|
|
182
|
+
// subset), and `last_token_usage` is one request, where `total_token_usage` and
|
|
183
|
+
// the stream's `turn.completed` sum every request in the turn.
|
|
184
|
+
export const contextTokensFromCodexRollout = (text) => {
|
|
185
|
+
const lines = text.split('\n');
|
|
186
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
187
|
+
const line = lines[index].trim();
|
|
188
|
+
if (!line || !line.includes('token_count')) continue;
|
|
189
|
+
let record;
|
|
190
|
+
try {
|
|
191
|
+
record = JSON.parse(line);
|
|
192
|
+
} catch {
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const input = record?.payload?.type === 'token_count'
|
|
196
|
+
? record.payload.info?.last_token_usage?.input_tokens : undefined;
|
|
197
|
+
if (Number.isFinite(input)) return input;
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
export const codexContextTokens = ({ codexHome = codexHomeFor(), sessionId }) => {
|
|
203
|
+
try {
|
|
204
|
+
const file = codexRolloutPath({ codexHome, sessionId });
|
|
205
|
+
return file ? contextTokensFromCodexRollout(readTail(file)) : null;
|
|
206
|
+
} catch {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
139
211
|
export const claudeContextTokens = ({ cwd, sessionId, configDir = claudeConfigDirFor() }) => {
|
|
140
212
|
const file = claudeTranscriptPath({ cwd, sessionId, configDir });
|
|
141
213
|
if (!file || !existsSync(file)) return null;
|