@0xmaxma/claude-gateway 2.1.14 → 2.1.16
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/dist/agent/model-catalog.d.ts +10 -0
- package/dist/agent/model-catalog.d.ts.map +1 -1
- package/dist/agent/model-catalog.js +93 -25
- package/dist/agent/model-catalog.js.map +1 -1
- package/dist/agent/model-registry.d.ts +15 -0
- package/dist/agent/model-registry.d.ts.map +1 -1
- package/dist/agent/model-registry.js +26 -0
- package/dist/agent/model-registry.js.map +1 -1
- package/dist/agent/runner.d.ts +5 -1
- package/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +48 -29
- package/dist/agent/runner.js.map +1 -1
- package/dist/api/gateway-router.js +2 -2
- package/dist/api/gateway-router.js.map +1 -1
- package/dist/api/packages.d.ts.map +1 -1
- package/dist/api/packages.js +12 -11
- package/dist/api/packages.js.map +1 -1
- package/dist/api/router.d.ts.map +1 -1
- package/dist/api/router.js +9 -7
- package/dist/api/router.js.map +1 -1
- package/dist/build-provenance.json +4 -4
- package/dist/cli/commands/update.d.ts.map +1 -1
- package/dist/cli/commands/update.js +18 -7
- package/dist/cli/commands/update.js.map +1 -1
- package/dist/cron/manager.d.ts.map +1 -1
- package/dist/cron/manager.js +6 -3
- package/dist/cron/manager.js.map +1 -1
- package/dist/cron/scheduler.d.ts +1 -0
- package/dist/cron/scheduler.d.ts.map +1 -1
- package/dist/cron/scheduler.js +76 -5
- package/dist/cron/scheduler.js.map +1 -1
- package/dist/cron/validate.d.ts +10 -0
- package/dist/cron/validate.d.ts.map +1 -0
- package/dist/cron/validate.js +37 -0
- package/dist/cron/validate.js.map +1 -0
- package/dist/heartbeat/parser.d.ts +12 -3
- package/dist/heartbeat/parser.d.ts.map +1 -1
- package/dist/heartbeat/parser.js +35 -97
- package/dist/heartbeat/parser.js.map +1 -1
- package/dist/history/types.d.ts +1 -1
- package/dist/history/types.js +1 -1
- package/dist/orchestration/agent-cli-session.d.ts +58 -6
- package/dist/orchestration/agent-cli-session.d.ts.map +1 -1
- package/dist/orchestration/agent-cli-session.js +207 -27
- package/dist/orchestration/agent-cli-session.js.map +1 -1
- package/dist/orchestration/bridge.d.ts +2 -0
- package/dist/orchestration/bridge.d.ts.map +1 -1
- package/dist/orchestration/bridge.js +54 -14
- package/dist/orchestration/bridge.js.map +1 -1
- package/dist/orchestration/context-delivery.d.ts +2 -0
- package/dist/orchestration/context-delivery.d.ts.map +1 -1
- package/dist/orchestration/context-delivery.js +8 -0
- package/dist/orchestration/context-delivery.js.map +1 -1
- package/dist/orchestration/gateway-tasks/computer.d.ts +2 -0
- package/dist/orchestration/gateway-tasks/computer.d.ts.map +1 -1
- package/dist/orchestration/gateway-tasks/computer.js +4 -2
- package/dist/orchestration/gateway-tasks/computer.js.map +1 -1
- package/dist/orchestration/input-images.d.ts +4 -0
- package/dist/orchestration/input-images.d.ts.map +1 -1
- package/dist/orchestration/input-images.js +28 -0
- package/dist/orchestration/input-images.js.map +1 -1
- package/dist/orchestration/runtime.d.ts +5 -0
- package/dist/orchestration/runtime.d.ts.map +1 -1
- package/dist/orchestration/runtime.js +105 -46
- package/dist/orchestration/runtime.js.map +1 -1
- package/dist/orchestration/session-compaction.d.ts.map +1 -1
- package/dist/orchestration/session-compaction.js +16 -6
- package/dist/orchestration/session-compaction.js.map +1 -1
- package/dist/orchestration/tasks/driver.d.ts.map +1 -1
- package/dist/orchestration/tasks/driver.js +12 -1
- package/dist/orchestration/tasks/driver.js.map +1 -1
- package/dist/orchestration/tasks/pool.d.ts +3 -2
- package/dist/orchestration/tasks/pool.d.ts.map +1 -1
- package/dist/orchestration/tasks/pool.js +4 -3
- package/dist/orchestration/tasks/pool.js.map +1 -1
- package/dist/orchestration/tasks/service.d.ts +3 -0
- package/dist/orchestration/tasks/service.d.ts.map +1 -1
- package/dist/orchestration/tasks/service.js +24 -3
- package/dist/orchestration/tasks/service.js.map +1 -1
- package/dist/orchestration/token-ledger.d.ts +6 -0
- package/dist/orchestration/token-ledger.d.ts.map +1 -1
- package/dist/orchestration/token-ledger.js +2 -1
- package/dist/orchestration/token-ledger.js.map +1 -1
- package/dist/orchestration/types.d.ts +4 -0
- package/dist/orchestration/types.d.ts.map +1 -1
- package/dist/orchestration/types.js.map +1 -1
- package/dist/packages/npm-staging.d.ts +55 -0
- package/dist/packages/npm-staging.d.ts.map +1 -0
- package/dist/packages/npm-staging.js +349 -0
- package/dist/packages/npm-staging.js.map +1 -0
- package/dist/packages/registry.d.ts +24 -10
- package/dist/packages/registry.d.ts.map +1 -1
- package/dist/packages/registry.js +125 -66
- package/dist/packages/registry.js.map +1 -1
- package/dist/types.d.ts +12 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/ui/memory-activity.js +1 -1
- package/mcp/tools/telegram/callback-failure.ts +10 -4
- package/mcp/tools/telegram/model-menu-request.ts +4 -1
- package/mcp/tools/telegram/receiver-server.ts +47 -53
- package/mcp/tools/telegram/session-list.ts +82 -0
- package/mcp/tools/telegram/task-browser.ts +2 -1
- package/package.json +1 -1
- package/dist/session/compactor.d.ts +0 -53
- package/dist/session/compactor.d.ts.map +0 -1
- package/dist/session/compactor.js +0 -274
- package/dist/session/compactor.js.map +0 -1
package/dist/heartbeat/parser.js
CHANGED
|
@@ -34,9 +34,11 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
36
|
exports.MissingScheduleError = exports.AmbiguousScheduleError = exports.MissingNameError = exports.MissingPromptError = exports.InvalidIntervalError = exports.InvalidCronError = void 0;
|
|
37
|
-
exports.
|
|
37
|
+
exports.parseInterval = parseInterval;
|
|
38
38
|
exports.parseHeartbeat = parseHeartbeat;
|
|
39
39
|
const yaml = __importStar(require("js-yaml"));
|
|
40
|
+
const nodeCron = __importStar(require("node-cron"));
|
|
41
|
+
const validate_1 = require("../cron/validate");
|
|
40
42
|
// ---------- Error classes ----------
|
|
41
43
|
class InvalidCronError extends Error {
|
|
42
44
|
constructor(taskName, expr) {
|
|
@@ -82,110 +84,46 @@ class MissingScheduleError extends Error {
|
|
|
82
84
|
exports.MissingScheduleError = MissingScheduleError;
|
|
83
85
|
// ---------- Cron validation ----------
|
|
84
86
|
/**
|
|
85
|
-
* Validate a 5-field cron expression
|
|
86
|
-
*
|
|
87
|
+
* Validate a 5-field cron expression with node-cron, the library that
|
|
88
|
+
* schedules it, so the parser never accepts what `nodeCron.schedule()` rejects
|
|
89
|
+
* or rejects what it supports (lists of ranges, MON-FRI, JAN, ...).
|
|
90
|
+
* node-cron also accepts a leading seconds field; heartbeats stay at 5 fields.
|
|
91
|
+
* Ranges that node-cron would silently misread (see hasMisreadCronRange) are rejected.
|
|
87
92
|
*/
|
|
88
93
|
function validateCron(expr) {
|
|
89
|
-
|
|
90
|
-
const fields = expr.trim().split(/\s+/);
|
|
91
|
-
if (fields.length !== 5)
|
|
92
|
-
return false;
|
|
93
|
-
// Ranges for each field: [min, max]
|
|
94
|
-
const ranges = [
|
|
95
|
-
[0, 59], // minute
|
|
96
|
-
[0, 23], // hour
|
|
97
|
-
[1, 31], // day-of-month
|
|
98
|
-
[1, 12], // month
|
|
99
|
-
[0, 7], // day-of-week (0 and 7 both = Sunday)
|
|
100
|
-
];
|
|
101
|
-
for (let i = 0; i < 5; i++) {
|
|
102
|
-
const field = fields[i];
|
|
103
|
-
const [min, max] = ranges[i];
|
|
104
|
-
if (!validateCronField(field, min, max)) {
|
|
105
|
-
return false;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
return true;
|
|
109
|
-
}
|
|
110
|
-
function validateCronField(field, min, max) {
|
|
111
|
-
if (field === '*')
|
|
112
|
-
return true;
|
|
113
|
-
// Step: */N or N/N
|
|
114
|
-
if (field.includes('/')) {
|
|
115
|
-
const parts = field.split('/');
|
|
116
|
-
if (parts.length !== 2)
|
|
117
|
-
return false;
|
|
118
|
-
const [base, step] = parts;
|
|
119
|
-
const stepNum = parseInt(step, 10);
|
|
120
|
-
if (isNaN(stepNum) || stepNum < 1)
|
|
121
|
-
return false;
|
|
122
|
-
if (base !== '*') {
|
|
123
|
-
const baseNum = parseInt(base, 10);
|
|
124
|
-
if (isNaN(baseNum) || baseNum < min || baseNum > max)
|
|
125
|
-
return false;
|
|
126
|
-
}
|
|
127
|
-
return true;
|
|
128
|
-
}
|
|
129
|
-
// Range: N-M
|
|
130
|
-
if (field.includes('-')) {
|
|
131
|
-
const parts = field.split('-');
|
|
132
|
-
if (parts.length !== 2)
|
|
133
|
-
return false;
|
|
134
|
-
const lo = parseInt(parts[0], 10);
|
|
135
|
-
const hi = parseInt(parts[1], 10);
|
|
136
|
-
if (isNaN(lo) || isNaN(hi))
|
|
137
|
-
return false;
|
|
138
|
-
if (lo < min || hi > max || lo > hi)
|
|
139
|
-
return false;
|
|
140
|
-
return true;
|
|
141
|
-
}
|
|
142
|
-
// List: N,M,...
|
|
143
|
-
if (field.includes(',')) {
|
|
144
|
-
const parts = field.split(',');
|
|
145
|
-
for (const p of parts) {
|
|
146
|
-
const num = parseInt(p, 10);
|
|
147
|
-
if (isNaN(num) || num < min || num > max)
|
|
148
|
-
return false;
|
|
149
|
-
}
|
|
150
|
-
return true;
|
|
151
|
-
}
|
|
152
|
-
// Plain number
|
|
153
|
-
const num = parseInt(field, 10);
|
|
154
|
-
if (isNaN(num) || num < min || num > max)
|
|
155
|
-
return false;
|
|
156
|
-
return true;
|
|
94
|
+
return expr.split(/\s+/).length === 5 && nodeCron.validate(expr) && !(0, validate_1.hasMisreadCronRange)(expr);
|
|
157
95
|
}
|
|
158
96
|
// ---------- Interval conversion ----------
|
|
97
|
+
const MINUTE_MS = 60000;
|
|
98
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
159
99
|
/**
|
|
160
|
-
* Convert an interval string to a
|
|
161
|
-
*
|
|
100
|
+
* Convert an interval string (30m, 2h, 1d, 1w) to a schedule.
|
|
101
|
+
*
|
|
102
|
+
* An interval that divides its cycle (60 minutes, 24 hours) maps to a
|
|
103
|
+
* wall-clock cron, so 30m fires at :00 and :30. Any other value has no even
|
|
104
|
+
* cron equivalent (a 45-minute step fires at :00 and :45, 15 minutes apart),
|
|
105
|
+
* so it becomes a fixed gap in milliseconds. Returns null for an invalid value.
|
|
162
106
|
*/
|
|
163
|
-
function
|
|
107
|
+
function parseInterval(interval) {
|
|
164
108
|
const match = interval.match(/^(\d+)([mhdw])$/);
|
|
165
|
-
if (!match)
|
|
166
|
-
return
|
|
167
|
-
}
|
|
109
|
+
if (!match)
|
|
110
|
+
return null;
|
|
168
111
|
const value = parseInt(match[1], 10);
|
|
169
|
-
|
|
170
|
-
switch (unit) {
|
|
112
|
+
switch (match[2]) {
|
|
171
113
|
case 'm':
|
|
172
114
|
if (value < 1 || value > 59)
|
|
173
|
-
return
|
|
174
|
-
return `*/${value} * * *
|
|
115
|
+
return null;
|
|
116
|
+
return 60 % value === 0 ? { cron: `*/${value} * * * *` } : { intervalMs: value * MINUTE_MS };
|
|
175
117
|
case 'h':
|
|
176
118
|
if (value < 1 || value > 23)
|
|
177
|
-
return
|
|
178
|
-
return `0 */${value} * *
|
|
119
|
+
return null;
|
|
120
|
+
return 24 % value === 0 ? { cron: `0 */${value} * * *` } : { intervalMs: value * HOUR_MS };
|
|
179
121
|
case 'd':
|
|
180
|
-
|
|
181
|
-
return '';
|
|
182
|
-
return `0 0 * * *`;
|
|
122
|
+
return value === 1 ? { cron: '0 0 * * *' } : null;
|
|
183
123
|
case 'w':
|
|
184
|
-
|
|
185
|
-
return '';
|
|
186
|
-
return `0 0 * * 0`;
|
|
124
|
+
return value === 1 ? { cron: '0 0 * * 0' } : null;
|
|
187
125
|
default:
|
|
188
|
-
return
|
|
126
|
+
return null;
|
|
189
127
|
}
|
|
190
128
|
}
|
|
191
129
|
// ---------- YAML extraction ----------
|
|
@@ -262,21 +200,21 @@ function parseHeartbeat(content) {
|
|
|
262
200
|
if (!hasCron && !hasInterval) {
|
|
263
201
|
throw new MissingScheduleError(name);
|
|
264
202
|
}
|
|
265
|
-
let cronExpr;
|
|
266
203
|
if (hasCron) {
|
|
267
|
-
|
|
268
|
-
if (!validateCron(
|
|
269
|
-
throw new InvalidCronError(name,
|
|
204
|
+
const cron = String(raw.cron).trim();
|
|
205
|
+
if (!validateCron(cron)) {
|
|
206
|
+
throw new InvalidCronError(name, cron);
|
|
270
207
|
}
|
|
208
|
+
tasks.push({ name, prompt, cron });
|
|
271
209
|
}
|
|
272
210
|
else {
|
|
273
211
|
const intervalStr = String(raw.interval).trim();
|
|
274
|
-
|
|
275
|
-
if (!
|
|
212
|
+
const schedule = parseInterval(intervalStr);
|
|
213
|
+
if (!schedule) {
|
|
276
214
|
throw new InvalidIntervalError(name, intervalStr);
|
|
277
215
|
}
|
|
216
|
+
tasks.push({ name, prompt, ...schedule });
|
|
278
217
|
}
|
|
279
|
-
tasks.push({ name, cron: cronExpr, prompt });
|
|
280
218
|
}
|
|
281
219
|
return tasks;
|
|
282
220
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/heartbeat/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/heartbeat/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,sCAmBC;AAsCD,wCAwEC;AA9MD,8CAAgC;AAChC,oDAAsC;AAEtC,+CAAuD;AAEvD,sCAAsC;AAEtC,MAAa,gBAAiB,SAAQ,KAAK;IACzC,YAAY,QAAgB,EAAE,IAAY;QACxC,KAAK,CAAC,SAAS,QAAQ,+BAA+B,IAAI,GAAG,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACjC,CAAC;CACF;AALD,4CAKC;AAED,MAAa,oBAAqB,SAAQ,KAAK;IAC7C,YAAY,QAAgB,EAAE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,CAAC;YAC7B,MAAM,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;QACvC,CAAC;QAED,IAAI,OAAO,EAAE,CAAC;YACZ,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;YACrC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;gBACxB,MAAM,IAAI,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACzC,CAAC;YACD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACrC,CAAC;aAAM,CAAC;YACN,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;YAChD,MAAM,QAAQ,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC5C,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,MAAM,IAAI,oBAAoB,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;YACpD,CAAC;YACD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
|
package/dist/history/types.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Canonical channel list — the SINGLE source of truth for the
|
|
3
3
|
* 'telegram' | 'discord' | 'line' | 'slack' union that used to be
|
|
4
4
|
* hand-copied into ~10 files (session/process.ts, agent/runner.ts,
|
|
5
|
-
* api/router.ts,
|
|
5
|
+
* api/router.ts, agent/builtin-commands.ts,
|
|
6
6
|
* cli-viewer/pairing-store.ts, ui/cli-viewer-ui.ts, ...).
|
|
7
7
|
*
|
|
8
8
|
* That duplication is exactly what caused three real bugs when Slack was
|
package/dist/history/types.js
CHANGED
|
@@ -7,7 +7,7 @@ exports.toChatChannel = toChatChannel;
|
|
|
7
7
|
* Canonical channel list — the SINGLE source of truth for the
|
|
8
8
|
* 'telegram' | 'discord' | 'line' | 'slack' union that used to be
|
|
9
9
|
* hand-copied into ~10 files (session/process.ts, agent/runner.ts,
|
|
10
|
-
* api/router.ts,
|
|
10
|
+
* api/router.ts, agent/builtin-commands.ts,
|
|
11
11
|
* cli-viewer/pairing-store.ts, ui/cli-viewer-ui.ts, ...).
|
|
12
12
|
*
|
|
13
13
|
* That duplication is exactly what caused three real bugs when Slack was
|
|
@@ -2,7 +2,31 @@ import { OrchestrationStore } from './store';
|
|
|
2
2
|
import type { AgentConfig } from '../types';
|
|
3
3
|
/** Why a decision turn could not continue the previous CLI session. Absent on the
|
|
4
4
|
* first turn of a session, which is an ordinary cold start rather than a fallback. */
|
|
5
|
-
export type CliSessionFallback = 'TRANSCRIPT_UNAVAILABLE' | 'WORKSPACE_CHANGED';
|
|
5
|
+
export type CliSessionFallback = 'TRANSCRIPT_UNAVAILABLE' | 'WORKSPACE_CHANGED' | 'TRANSCRIPT_TOO_LARGE';
|
|
6
|
+
/** The context-size ladder for a resumed turn. One mechanism, two triggers, one last resort:
|
|
7
|
+
*
|
|
8
|
+
* 1. Trigger. Claude Code's own auto-compact fires on tokens. Images are ~640 KB of base64
|
|
9
|
+
* but few tokens, so bytes need their own trigger: once what `--resume` would re-send
|
|
10
|
+
* plus this turn's new images passes COMPACT_TRANSCRIPT_BYTES, the turn compacts first.
|
|
11
|
+
* 2. Compact. The same Claude Code native `/compact` that `/compact` and nightly compaction
|
|
12
|
+
* run. After its compact_boundary nothing before it is re-sent, images included, so the
|
|
13
|
+
* transcript drops back to a summary. The compact request still carries the transcript,
|
|
14
|
+
* which is why the trigger sits well below the limit.
|
|
15
|
+
* 3. Reset. Only when compaction cannot run because the transcript alone is over
|
|
16
|
+
* MAX_RESUMABLE_TRANSCRIPT_BYTES (or it ran and the turn still does not fit): start a
|
|
17
|
+
* fresh session seeded with recent history as text, and tell the user.
|
|
18
|
+
*
|
|
19
|
+
* provider.getpod.ai rejects request bodies over 10 MiB, misleadingly as "400 missing or
|
|
20
|
+
* invalid model field". The 2 MiB margin covers the system prompt, tools and the prompt. */
|
|
21
|
+
export declare const MAX_RESUMABLE_TRANSCRIPT_BYTES: number;
|
|
22
|
+
export declare const COMPACT_TRANSCRIPT_BYTES: number;
|
|
23
|
+
/** Bytes `--resume` would re-send: the `message` (or `attachment`) of each main-chain message
|
|
24
|
+
* line after the last compact_boundary, or -1 when there is no usable transcript (missing or
|
|
25
|
+
* empty). Line metadata, the duplicated `toolUseResult` copy and sidechains are not sent, so
|
|
26
|
+
* the file overstates the request. A file no larger than `fastBelow` returns its size without
|
|
27
|
+
* parsing. Lines are scanned backwards in chunks and the scan stops at the boundary or once
|
|
28
|
+
* past `cap`. A probe error other than ENOENT throws. Self-contained so it runs in a container. */
|
|
29
|
+
export declare function resumableTranscriptBytes(file: string, fastBelow: number, cap: number): number;
|
|
6
30
|
export interface CliSessionDecision {
|
|
7
31
|
/** Session id handed to `--resume` or `--session-id`. */
|
|
8
32
|
id: string;
|
|
@@ -10,6 +34,8 @@ export interface CliSessionDecision {
|
|
|
10
34
|
resume: boolean;
|
|
11
35
|
/** Set only when a session we had previously started could not be continued. */
|
|
12
36
|
fallback?: CliSessionFallback;
|
|
37
|
+
/** Resume only after native compaction: what this turn would send passed the byte trigger. */
|
|
38
|
+
compact?: true;
|
|
13
39
|
}
|
|
14
40
|
/** Durable CLI session for an agent's decision turns.
|
|
15
41
|
*
|
|
@@ -26,18 +52,44 @@ export interface CliSessionDecision {
|
|
|
26
52
|
*/
|
|
27
53
|
export declare class AgentCliSessions {
|
|
28
54
|
private readonly store;
|
|
55
|
+
/** Per CLI id: the size the byte trigger last asked to compact at, and the size at which
|
|
56
|
+
* that compaction failed. In memory: a restart retries once, which is harmless. Entries
|
|
57
|
+
* live only while their id is the session's mapped one (see `start`/`forget`). */
|
|
58
|
+
private readonly compactRequested;
|
|
59
|
+
private readonly compactFailed;
|
|
29
60
|
constructor(store: OrchestrationStore);
|
|
30
|
-
/** Decide the CLI session for the next decision turn of `sessionId`, running in `cwd`.
|
|
31
|
-
|
|
61
|
+
/** Decide the CLI session for the next decision turn of `sessionId`, running in `cwd`.
|
|
62
|
+
* `reserveBytes` is what this turn adds on top of the transcript (its new images);
|
|
63
|
+
* `compacted` is set on the re-check after the ladder's compaction step. */
|
|
64
|
+
resolve(sessionId: string, cwd: string, requireExisting?: boolean, reserveBytes?: number, compacted?: boolean): CliSessionDecision;
|
|
32
65
|
/** Probe in the exact execution boundary; a Docker failure is not a missing
|
|
33
66
|
* transcript and must never trigger host execution or silently discard history. */
|
|
34
|
-
resolveContainer(sessionId: string, agent: AgentConfig, requireExisting?: boolean): Promise<CliSessionDecision>;
|
|
67
|
+
resolveContainer(sessionId: string, agent: AgentConfig, requireExisting?: boolean, reserveBytes?: number, compacted?: boolean): Promise<CliSessionDecision>;
|
|
68
|
+
/** The byte-triggered compaction of `cliSessionId` did not complete. Without a fence every
|
|
69
|
+
* later turn would pay for the same failing compaction before its own request. */
|
|
70
|
+
compactionFailed(cliSessionId: string): void;
|
|
35
71
|
/** A turn observed the CLI refusing the stored id; the next turn must start fresh. */
|
|
36
72
|
forget(sessionId: string): void;
|
|
73
|
+
/** The session's mapped CLI id is being replaced: its compaction bookkeeping goes with it. */
|
|
74
|
+
private dropCompactionState;
|
|
37
75
|
private start;
|
|
38
|
-
/**
|
|
39
|
-
|
|
76
|
+
/** The ladder (see MAX_RESUMABLE_TRANSCRIPT_BYTES). /compact (`requireExisting`) never
|
|
77
|
+
* asks for compaction itself; it is the compaction. */
|
|
78
|
+
private decide;
|
|
40
79
|
}
|
|
80
|
+
/** Shown to the user when a turn could not resume because the transcript is too large. */
|
|
81
|
+
export declare const TRANSCRIPT_TOO_LARGE_NOTICE = "This conversation's working context grew too large for the provider (over its 10 MiB request limit, usually from many images), so it was reset to a fresh session. Recent messages were reloaded as text; earlier images and tool output are no longer in context. Your chat history is unchanged.";
|
|
82
|
+
/** The same probe inside the container (cwd /workspace). A Docker failure is not a
|
|
83
|
+
* missing transcript, so it throws instead of guessing. */
|
|
84
|
+
export declare function containerResumableBytes(container: string, cliSessionId: string, reserveBytes?: number): Promise<number>;
|
|
85
|
+
/** Worker CLIs resume a pooled transcript for their next task. Past the limit they start
|
|
86
|
+
* fresh instead of compacting: the task brief carries the whole assignment, so a fresh
|
|
87
|
+
* session loses nothing a summary would keep. */
|
|
88
|
+
export declare function workerTranscriptTooLarge(cwd: string, cliSessionId: string): boolean;
|
|
89
|
+
/** The container worker's probe. Unlike a decision turn no history is at stake (the brief
|
|
90
|
+
* carries the task), so a failed probe keeps the pre-probe behaviour and resumes; if Docker
|
|
91
|
+
* is really down the spawn reports that itself. */
|
|
92
|
+
export declare function workerContainerTranscriptTooLarge(container: string, cliSessionId: string): Promise<boolean>;
|
|
41
93
|
/** The CLI prints this and exits non-zero when `--resume` names a transcript it cannot read. */
|
|
42
94
|
export declare function resumeRejected(stderr: string | null | undefined): boolean;
|
|
43
95
|
/** Execute identical checkpoint/rollback logic inside the app, returning only
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-cli-session.d.ts","sourceRoot":"","sources":["../../src/orchestration/agent-cli-session.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent-cli-session.d.ts","sourceRoot":"","sources":["../../src/orchestration/agent-cli-session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAG7C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAK5C;sFACsF;AACtF,MAAM,MAAM,kBAAkB,GAAG,wBAAwB,GAAG,mBAAmB,GAAG,sBAAsB,CAAC;AAEzG;;;;;;;;;;;;;;4FAc4F;AAC5F,eAAO,MAAM,8BAA8B,QAAkB,CAAC;AAC9D,eAAO,MAAM,wBAAwB,QAAkB,CAAC;AAMxD;;;;;mGAKmG;AACnG,wBAAgB,w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AAY,EAAE,MAAM,EAAE,YAAY,SAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CASxH;AAED;;iDAEiD;AACjD,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAEnF;AAED;;mDAEmD;AACnD,wBAAsB,iCAAiC,CAAC,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMjH;AAED,gGAAgG;AAChG,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAEzE;AAED;+EAC+E;AAC/E,wBAAsB,6BAA6B,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAShI"}
|
|
@@ -1,15 +1,109 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.AgentCliSessions = void 0;
|
|
3
|
+
exports.TRANSCRIPT_TOO_LARGE_NOTICE = exports.AgentCliSessions = exports.COMPACT_TRANSCRIPT_BYTES = exports.MAX_RESUMABLE_TRANSCRIPT_BYTES = void 0;
|
|
4
|
+
exports.resumableTranscriptBytes = resumableTranscriptBytes;
|
|
5
|
+
exports.containerResumableBytes = containerResumableBytes;
|
|
6
|
+
exports.workerTranscriptTooLarge = workerTranscriptTooLarge;
|
|
7
|
+
exports.workerContainerTranscriptTooLarge = workerContainerTranscriptTooLarge;
|
|
4
8
|
exports.resumeRejected = resumeRejected;
|
|
5
9
|
exports.containerTranscriptCheckpoint = containerTranscriptCheckpoint;
|
|
6
|
-
const fs_1 = require("fs");
|
|
7
10
|
const crypto_1 = require("crypto");
|
|
8
11
|
const claude_settings_1 = require("../config/claude-settings");
|
|
9
12
|
const container_1 = require("./container");
|
|
10
13
|
const os_1 = require("os");
|
|
11
14
|
const types_1 = require("./types");
|
|
12
15
|
const transcript_checkpoint_1 = require("./transcript-checkpoint");
|
|
16
|
+
/** The context-size ladder for a resumed turn. One mechanism, two triggers, one last resort:
|
|
17
|
+
*
|
|
18
|
+
* 1. Trigger. Claude Code's own auto-compact fires on tokens. Images are ~640 KB of base64
|
|
19
|
+
* but few tokens, so bytes need their own trigger: once what `--resume` would re-send
|
|
20
|
+
* plus this turn's new images passes COMPACT_TRANSCRIPT_BYTES, the turn compacts first.
|
|
21
|
+
* 2. Compact. The same Claude Code native `/compact` that `/compact` and nightly compaction
|
|
22
|
+
* run. After its compact_boundary nothing before it is re-sent, images included, so the
|
|
23
|
+
* transcript drops back to a summary. The compact request still carries the transcript,
|
|
24
|
+
* which is why the trigger sits well below the limit.
|
|
25
|
+
* 3. Reset. Only when compaction cannot run because the transcript alone is over
|
|
26
|
+
* MAX_RESUMABLE_TRANSCRIPT_BYTES (or it ran and the turn still does not fit): start a
|
|
27
|
+
* fresh session seeded with recent history as text, and tell the user.
|
|
28
|
+
*
|
|
29
|
+
* provider.getpod.ai rejects request bodies over 10 MiB, misleadingly as "400 missing or
|
|
30
|
+
* invalid model field". The 2 MiB margin covers the system prompt, tools and the prompt. */
|
|
31
|
+
exports.MAX_RESUMABLE_TRANSCRIPT_BYTES = 8 * 1024 * 1024;
|
|
32
|
+
exports.COMPACT_TRANSCRIPT_BYTES = 6 * 1024 * 1024;
|
|
33
|
+
/** Compaction replaces the transcript with a summary, so it only makes room when the
|
|
34
|
+
* transcript holds more than this; below it a turn's own images are what fills the request.
|
|
35
|
+
* A failed compaction is not retried until the transcript has grown by this much again. */
|
|
36
|
+
const MIN_COMPACTABLE_BYTES = 1024 * 1024;
|
|
37
|
+
/** Bytes `--resume` would re-send: the `message` (or `attachment`) of each main-chain message
|
|
38
|
+
* line after the last compact_boundary, or -1 when there is no usable transcript (missing or
|
|
39
|
+
* empty). Line metadata, the duplicated `toolUseResult` copy and sidechains are not sent, so
|
|
40
|
+
* the file overstates the request. A file no larger than `fastBelow` returns its size without
|
|
41
|
+
* parsing. Lines are scanned backwards in chunks and the scan stops at the boundary or once
|
|
42
|
+
* past `cap`. A probe error other than ENOENT throws. Self-contained so it runs in a container. */
|
|
43
|
+
function resumableTranscriptBytes(file, fastBelow, cap) {
|
|
44
|
+
const fs = require('fs');
|
|
45
|
+
// Only message lines are re-sent. api-request-blob request logs hold a second copy of
|
|
46
|
+
// each image, and cost/mode records are local bookkeeping.
|
|
47
|
+
const resent = ['user', 'assistant', 'attachment'];
|
|
48
|
+
let fd;
|
|
49
|
+
try {
|
|
50
|
+
fd = fs.openSync(file, 'r');
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code === 'ENOENT')
|
|
54
|
+
return -1;
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const stat = fs.fstatSync(fd);
|
|
59
|
+
if (!stat.isFile() || stat.size === 0)
|
|
60
|
+
return -1;
|
|
61
|
+
if (stat.size <= fastBelow)
|
|
62
|
+
return stat.size;
|
|
63
|
+
let sent = 0;
|
|
64
|
+
/** True once the scan can stop: a boundary, or already past the cap. */
|
|
65
|
+
const stop = (line) => {
|
|
66
|
+
if (!line.length)
|
|
67
|
+
return false;
|
|
68
|
+
let row;
|
|
69
|
+
try {
|
|
70
|
+
row = JSON.parse(line.toString('utf8'));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
sent += line.length;
|
|
74
|
+
return sent > cap;
|
|
75
|
+
}
|
|
76
|
+
if (row.type === 'system' && row.subtype === 'compact_boundary')
|
|
77
|
+
return true;
|
|
78
|
+
const payload = row.message ?? row.attachment;
|
|
79
|
+
if (!row.isSidechain && resent.includes(row.type) && payload !== undefined)
|
|
80
|
+
sent += Buffer.byteLength(JSON.stringify(payload));
|
|
81
|
+
return sent > cap;
|
|
82
|
+
};
|
|
83
|
+
let position = stat.size, carry = Buffer.alloc(0);
|
|
84
|
+
while (position > 0) {
|
|
85
|
+
const length = Math.min(1024 * 1024, position);
|
|
86
|
+
position -= length;
|
|
87
|
+
const chunk = Buffer.allocUnsafe(length);
|
|
88
|
+
fs.readSync(fd, chunk, 0, length, position);
|
|
89
|
+
const data = Buffer.concat([chunk, carry]);
|
|
90
|
+
let end = data.length;
|
|
91
|
+
for (let i = end - 1; i >= 0; i--) {
|
|
92
|
+
if (data[i] !== 10)
|
|
93
|
+
continue;
|
|
94
|
+
if (stop(data.subarray(i + 1, end)))
|
|
95
|
+
return sent;
|
|
96
|
+
end = i;
|
|
97
|
+
}
|
|
98
|
+
carry = data.subarray(0, end);
|
|
99
|
+
}
|
|
100
|
+
stop(carry);
|
|
101
|
+
return sent;
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
fs.closeSync(fd);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
13
107
|
/** Durable CLI session for an agent's decision turns.
|
|
14
108
|
*
|
|
15
109
|
* Decision turns keep the per-turn spawn/kill lifecycle, so without a stable id every
|
|
@@ -26,12 +120,19 @@ const transcript_checkpoint_1 = require("./transcript-checkpoint");
|
|
|
26
120
|
class AgentCliSessions {
|
|
27
121
|
constructor(store) {
|
|
28
122
|
this.store = store;
|
|
123
|
+
/** Per CLI id: the size the byte trigger last asked to compact at, and the size at which
|
|
124
|
+
* that compaction failed. In memory: a restart retries once, which is harmless. Entries
|
|
125
|
+
* live only while their id is the session's mapped one (see `start`/`forget`). */
|
|
126
|
+
this.compactRequested = new Map();
|
|
127
|
+
this.compactFailed = new Map();
|
|
29
128
|
store.run(`CREATE TABLE IF NOT EXISTS agent_cli_sessions (
|
|
30
129
|
session_id TEXT PRIMARY KEY, cli_session_id TEXT NOT NULL, cwd TEXT NOT NULL,
|
|
31
130
|
updated_at INTEGER NOT NULL)`);
|
|
32
131
|
}
|
|
33
|
-
/** Decide the CLI session for the next decision turn of `sessionId`, running in `cwd`.
|
|
34
|
-
|
|
132
|
+
/** Decide the CLI session for the next decision turn of `sessionId`, running in `cwd`.
|
|
133
|
+
* `reserveBytes` is what this turn adds on top of the transcript (its new images);
|
|
134
|
+
* `compacted` is set on the re-check after the ladder's compaction step. */
|
|
135
|
+
resolve(sessionId, cwd, requireExisting = false, reserveBytes = 0, compacted = false) {
|
|
35
136
|
const start = (fallback) => {
|
|
36
137
|
if (requireExisting)
|
|
37
138
|
throw new types_1.OrchestrationError('NO_CLI_SESSION', 'No existing Claude Code transcript to compact. Chat history was not changed.');
|
|
@@ -44,15 +145,13 @@ class AgentCliSessions {
|
|
|
44
145
|
// names a transcript this process would not be resuming into.
|
|
45
146
|
if (String(row.cwd) !== cwd)
|
|
46
147
|
return start('WORKSPACE_CHANGED');
|
|
47
|
-
|
|
48
|
-
return { id: previous, resume: true };
|
|
49
|
-
return start('TRANSCRIPT_UNAVAILABLE');
|
|
148
|
+
return this.decide(hostResumableBytes(cwd, previous, reserveBytes), reserveBytes, compacted, previous, start, requireExisting);
|
|
50
149
|
}
|
|
51
150
|
return start();
|
|
52
151
|
}
|
|
53
152
|
/** Probe in the exact execution boundary; a Docker failure is not a missing
|
|
54
153
|
* transcript and must never trigger host execution or silently discard history. */
|
|
55
|
-
async resolveContainer(sessionId, agent, requireExisting = false) {
|
|
154
|
+
async resolveContainer(sessionId, agent, requireExisting = false, reserveBytes = 0, compacted = false) {
|
|
56
155
|
await (0, container_1.validateContainer)(agent);
|
|
57
156
|
const cwd = `container:${agent.container}:/workspace`;
|
|
58
157
|
const start = (fallback) => {
|
|
@@ -66,41 +165,122 @@ class AgentCliSessions {
|
|
|
66
165
|
if (row.cwd !== cwd)
|
|
67
166
|
return start('WORKSPACE_CHANGED');
|
|
68
167
|
const id = String(row.cli_session_id);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
if (result === 'missing')
|
|
79
|
-
return start('TRANSCRIPT_UNAVAILABLE');
|
|
80
|
-
throw new types_1.OrchestrationError('CONTAINER_TRANSCRIPT_CHECK_FAILED');
|
|
168
|
+
return this.decide(await containerResumableBytes(agent.container, id, reserveBytes), reserveBytes, compacted, id, start, requireExisting);
|
|
169
|
+
}
|
|
170
|
+
/** The byte-triggered compaction of `cliSessionId` did not complete. Without a fence every
|
|
171
|
+
* later turn would pay for the same failing compaction before its own request. */
|
|
172
|
+
compactionFailed(cliSessionId) {
|
|
173
|
+
const bytes = this.compactRequested.get(cliSessionId);
|
|
174
|
+
this.compactRequested.delete(cliSessionId);
|
|
175
|
+
if (bytes !== undefined)
|
|
176
|
+
this.compactFailed.set(cliSessionId, bytes);
|
|
81
177
|
}
|
|
82
178
|
/** A turn observed the CLI refusing the stored id; the next turn must start fresh. */
|
|
83
179
|
forget(sessionId) {
|
|
180
|
+
this.dropCompactionState(sessionId);
|
|
84
181
|
this.store.run('DELETE FROM agent_cli_sessions WHERE session_id=?', sessionId);
|
|
85
182
|
}
|
|
183
|
+
/** The session's mapped CLI id is being replaced: its compaction bookkeeping goes with it. */
|
|
184
|
+
dropCompactionState(sessionId) {
|
|
185
|
+
const row = this.store.get('SELECT cli_session_id FROM agent_cli_sessions WHERE session_id=?', sessionId);
|
|
186
|
+
if (!row)
|
|
187
|
+
return;
|
|
188
|
+
this.compactRequested.delete(String(row.cli_session_id));
|
|
189
|
+
this.compactFailed.delete(String(row.cli_session_id));
|
|
190
|
+
}
|
|
86
191
|
start(sessionId, cwd, fallback) {
|
|
192
|
+
this.dropCompactionState(sessionId);
|
|
87
193
|
const id = (0, crypto_1.randomUUID)();
|
|
88
194
|
this.store.run(`INSERT INTO agent_cli_sessions(session_id,cli_session_id,cwd,updated_at) VALUES(?,?,?,?)
|
|
89
195
|
ON CONFLICT(session_id) DO UPDATE SET cli_session_id=excluded.cli_session_id,cwd=excluded.cwd,updated_at=excluded.updated_at`, sessionId, id, cwd, Date.now());
|
|
90
196
|
return { id, resume: false, ...(fallback ? { fallback } : {}) };
|
|
91
197
|
}
|
|
92
|
-
/**
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
return (
|
|
198
|
+
/** The ladder (see MAX_RESUMABLE_TRANSCRIPT_BYTES). /compact (`requireExisting`) never
|
|
199
|
+
* asks for compaction itself; it is the compaction. */
|
|
200
|
+
decide(bytes, reserveBytes, compacted, id, start, requireExisting) {
|
|
201
|
+
if (bytes < 0)
|
|
202
|
+
return start('TRANSCRIPT_UNAVAILABLE');
|
|
203
|
+
if (bytes > exports.MAX_RESUMABLE_TRANSCRIPT_BYTES) {
|
|
204
|
+
// Compaction would send the same oversized body. /compact keeps the mapping and says why.
|
|
205
|
+
if (requireExisting)
|
|
206
|
+
throw new types_1.OrchestrationError('CLI_TRANSCRIPT_TOO_LARGE', TRANSCRIPT_TOO_LARGE_TO_COMPACT);
|
|
207
|
+
return start('TRANSCRIPT_TOO_LARGE');
|
|
208
|
+
}
|
|
209
|
+
if (requireExisting)
|
|
210
|
+
return { id, resume: true };
|
|
211
|
+
// The re-check after this turn's compaction: the request it recorded is settled.
|
|
212
|
+
if (compacted)
|
|
213
|
+
this.compactRequested.delete(id);
|
|
214
|
+
// A turn whose images alone fill the limit would not fit a fresh session either, so they
|
|
215
|
+
// decide neither a compaction nor a reset.
|
|
216
|
+
const reserve = reserveBytes < exports.MAX_RESUMABLE_TRANSCRIPT_BYTES ? reserveBytes : 0;
|
|
217
|
+
let failed = this.compactFailed.get(id);
|
|
218
|
+
// Smaller than when it failed: a compaction (this ladder's, /compact or nightly) has since run.
|
|
219
|
+
if (failed !== undefined && bytes < failed) {
|
|
220
|
+
this.compactFailed.delete(id);
|
|
221
|
+
failed = undefined;
|
|
97
222
|
}
|
|
98
|
-
|
|
99
|
-
|
|
223
|
+
if (!compacted && bytes > MIN_COMPACTABLE_BYTES && bytes + reserve > exports.COMPACT_TRANSCRIPT_BYTES &&
|
|
224
|
+
(failed === undefined || bytes >= failed + MIN_COMPACTABLE_BYTES)) {
|
|
225
|
+
this.compactRequested.set(id, bytes);
|
|
226
|
+
return { id, resume: true, compact: true };
|
|
100
227
|
}
|
|
228
|
+
// Past the trigger without compacting (already tried, or nothing to remove): reset only
|
|
229
|
+
// once the request cannot fit.
|
|
230
|
+
return bytes + reserve > exports.MAX_RESUMABLE_TRANSCRIPT_BYTES ? start('TRANSCRIPT_TOO_LARGE') : { id, resume: true };
|
|
101
231
|
}
|
|
102
232
|
}
|
|
103
233
|
exports.AgentCliSessions = AgentCliSessions;
|
|
234
|
+
const TRANSCRIPT_TOO_LARGE_TO_COMPACT = 'The Claude Code context is too large to compact within the provider request size limit. Send a message to continue in a fresh session, or use /clear. Chat history was not changed.';
|
|
235
|
+
/** Shown to the user when a turn could not resume because the transcript is too large. */
|
|
236
|
+
exports.TRANSCRIPT_TOO_LARGE_NOTICE = 'This conversation\'s working context grew too large for the provider (over its 10 MiB request limit, usually from many images), so it was reset to a fresh session. Recent messages were reloaded as text; earlier images and tool output are no longer in context. Your chat history is unchanged.';
|
|
237
|
+
/** Below this file size no line needs parsing: the turn fits without compaction. */
|
|
238
|
+
function fastBelow(reserveBytes) {
|
|
239
|
+
return Math.max(0, exports.COMPACT_TRANSCRIPT_BYTES - reserveBytes);
|
|
240
|
+
}
|
|
241
|
+
/** An unreadable host transcript is treated as missing, so the turn starts fresh, as before. */
|
|
242
|
+
function hostResumableBytes(cwd, cliSessionId, reserveBytes = 0) {
|
|
243
|
+
try {
|
|
244
|
+
return resumableTranscriptBytes((0, claude_settings_1.transcriptPath)(cwd, cliSessionId), fastBelow(reserveBytes), exports.MAX_RESUMABLE_TRANSCRIPT_BYTES);
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
const code = error?.code;
|
|
248
|
+
console.warn('[orchestration] CLI transcript probe failed; treating it as unavailable', { cliSessionId, code: typeof code === 'string' && /^[A-Za-z0-9_]{1,80}$/.test(code) ? code : 'ERROR' });
|
|
249
|
+
return -1;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** The same probe inside the container (cwd /workspace). A Docker failure is not a
|
|
253
|
+
* missing transcript, so it throws instead of guessing. */
|
|
254
|
+
async function containerResumableBytes(container, cliSessionId, reserveBytes = 0) {
|
|
255
|
+
const result = await (0, container_1.containerNode)(container, `
|
|
256
|
+
const path=require('path');
|
|
257
|
+
const root=process.env.CLAUDE_CONFIG_DIR||path.join(process.argv[2],'.claude');
|
|
258
|
+
const file=path.join(root,'projects','-workspace',process.argv[1]+'.jsonl');
|
|
259
|
+
process.stdout.write(String((${resumableTranscriptBytes.toString()})(file,${fastBelow(reserveBytes)},${exports.MAX_RESUMABLE_TRANSCRIPT_BYTES})));
|
|
260
|
+
`, [cliSessionId, (0, os_1.homedir)()]);
|
|
261
|
+
if (!/^(?:-1|\d{1,12})$/.test(result))
|
|
262
|
+
throw new types_1.OrchestrationError('CONTAINER_TRANSCRIPT_CHECK_FAILED');
|
|
263
|
+
return Number(result);
|
|
264
|
+
}
|
|
265
|
+
/** Worker CLIs resume a pooled transcript for their next task. Past the limit they start
|
|
266
|
+
* fresh instead of compacting: the task brief carries the whole assignment, so a fresh
|
|
267
|
+
* session loses nothing a summary would keep. */
|
|
268
|
+
function workerTranscriptTooLarge(cwd, cliSessionId) {
|
|
269
|
+
return hostResumableBytes(cwd, cliSessionId) > exports.MAX_RESUMABLE_TRANSCRIPT_BYTES;
|
|
270
|
+
}
|
|
271
|
+
/** The container worker's probe. Unlike a decision turn no history is at stake (the brief
|
|
272
|
+
* carries the task), so a failed probe keeps the pre-probe behaviour and resumes; if Docker
|
|
273
|
+
* is really down the spawn reports that itself. */
|
|
274
|
+
async function workerContainerTranscriptTooLarge(container, cliSessionId) {
|
|
275
|
+
try {
|
|
276
|
+
return await containerResumableBytes(container, cliSessionId) > exports.MAX_RESUMABLE_TRANSCRIPT_BYTES;
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
const code = error?.code;
|
|
280
|
+
console.warn('[orchestration] worker container transcript probe failed; resuming', { cliSessionId, code: typeof code === 'string' && /^[A-Za-z0-9_]{1,80}$/.test(code) ? code : 'ERROR' });
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
104
284
|
/** The CLI prints this and exits non-zero when `--resume` names a transcript it cannot read. */
|
|
105
285
|
function resumeRejected(stderr) {
|
|
106
286
|
return typeof stderr === 'string' && /No conversation found with session ID/i.test(stderr);
|