@commonlyai/cli 0.1.323 → 0.1.324
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
|
@@ -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
|
};
|
|
@@ -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;
|