@shumkov/orchestra 0.13.2 → 0.15.0
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/docs/PER_CHAT_CLAUDE_CONTEXT_CACHE_SPEC.md +40 -0
- package/lib/codex/app-server-client.js +132 -4
- package/lib/codex/protocol-schema.json +6 -2
- package/lib/process/cli-process.js +109 -26
- package/lib/process/codex-process.js +130 -0
- package/lib/process/factory.js +44 -7
- package/lib/process/process-manager.js +744 -118
- package/lib/process/sdk-process.js +28 -3
- package/lib/tmux/tmux-runner.js +6 -0
- package/package.json +1 -1
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Per-session Claude CLI context window and prompt cache
|
|
2
|
+
|
|
3
|
+
A consumer can choose the auto-compaction window and prompt-cache lifetime for
|
|
4
|
+
each chat or topic, even when sessions share a tmux server. Orchestra accepts
|
|
5
|
+
normalized values. The consumer owns configuration parsing and inheritance.
|
|
6
|
+
|
|
7
|
+
| Factory or spawn-context option | Accepted value | Claude CLI environment variable |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| `autoCompactWindow` | Safe integer from 100,000 through 1,000,000 tokens | `CLAUDE_CODE_AUTO_COMPACT_WINDOW` |
|
|
10
|
+
| `promptCacheTtl` | `'5m'` or `'1h'` | `CLAUDE_CODE_PROMPT_CACHE_TTL` |
|
|
11
|
+
|
|
12
|
+
Both options also accept `undefined` and `null`. For each option independently,
|
|
13
|
+
a defined spawn-context value takes precedence over the factory option. The
|
|
14
|
+
factory accepts a static value or a synchronous `(chatId, threadId, config)`
|
|
15
|
+
resolver. Only the Claude CLI backend evaluates these resolvers.
|
|
16
|
+
|
|
17
|
+
| Resolved value | tmux session environment |
|
|
18
|
+
| --- | --- |
|
|
19
|
+
| Omitted or `undefined` | Inherit the variable from tmux as before |
|
|
20
|
+
| `null` | Set the variable to an empty string so Claude applies its normal defaults or settings |
|
|
21
|
+
| Concrete value | Set the variable to the exact token count or TTL |
|
|
22
|
+
|
|
23
|
+
An invalid value raises a `TypeError` during CLI process construction. The tmux
|
|
24
|
+
runner accepts environment names matching `^[A-Za-z_][A-Za-z0-9_]*$` and string
|
|
25
|
+
values free of NUL characters. Codex rejects either Claude-specific context key
|
|
26
|
+
on presence, including a key with an undefined value. Typed options keep
|
|
27
|
+
validation and reload detection local to the CLI backend. A generic environment
|
|
28
|
+
map would expose unrelated variables. Server-wide settings would affect every chat.
|
|
29
|
+
|
|
30
|
+
Consumers that support live changes supply the resolved values on each spawn
|
|
31
|
+
context. A changed, defined value triggers the existing idle reload and resume
|
|
32
|
+
path. An active turn finishes before its next idle dispatch can apply a change.
|
|
33
|
+
An omitted option requests no reload for that field. The reload event records
|
|
34
|
+
the old and new values for each changed option. Proactive compaction warnings
|
|
35
|
+
measure transcript usage against the configured window or the existing default.
|
|
36
|
+
|
|
37
|
+
Unit tests cover constructor bounds, exact spawn environment, tmux argument
|
|
38
|
+
validation, resolver precedence, Codex isolation, idle reload and reuse, reload
|
|
39
|
+
telemetry and the warning threshold. Provider cache usage and actual CLI
|
|
40
|
+
compaction timing can be measured after consumer rollout.
|
|
@@ -85,6 +85,10 @@ const CLIENT_FAULT_CLASS_BY_CODE = Object.freeze({
|
|
|
85
85
|
});
|
|
86
86
|
const MAX_ID_BYTES = 512;
|
|
87
87
|
const MAX_TEXT_BYTES = 64 * 1024;
|
|
88
|
+
const CODEX_ERROR_KIND_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
89
|
+
const RESETS_AT_ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
90
|
+
const RESETS_AT_EPOCH_RE = /^\d{1,16}$/;
|
|
91
|
+
const DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
|
|
88
92
|
const MAX_COMPLETED_ITEMS = 512;
|
|
89
93
|
const MAX_RESPONSE_ARRAY_ITEMS = 512;
|
|
90
94
|
const MAX_RESPONSE_OBJECT_KEYS = 512;
|
|
@@ -900,6 +904,109 @@ function projectCollaborationMode(value) {
|
|
|
900
904
|
return projected;
|
|
901
905
|
}
|
|
902
906
|
|
|
907
|
+
function projectCodexErrorKind(value, label) {
|
|
908
|
+
const kind = protocolRequiredString(value, label);
|
|
909
|
+
if (!CODEX_ERROR_KIND_RE.test(kind)) {
|
|
910
|
+
throw new CodexAppServerError(
|
|
911
|
+
`app-server ${label} is malformed`,
|
|
912
|
+
'CODEX_PROTOCOL_ERROR',
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
return kind;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
function projectCodexErrorInfo(value, label) {
|
|
919
|
+
if (value == null) return null;
|
|
920
|
+
if (typeof value === 'string') {
|
|
921
|
+
return {
|
|
922
|
+
kind: projectCodexErrorKind(value, `${label} codexErrorInfo`),
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
const info = protocolObject(value, `${label} codexErrorInfo`);
|
|
926
|
+
const keys = Object.keys(info);
|
|
927
|
+
if (keys.length === 0) return null;
|
|
928
|
+
if (Object.hasOwn(info, 'kind') && typeof info.kind === 'string' && info.kind.length > 0) {
|
|
929
|
+
const projected = {
|
|
930
|
+
kind: projectCodexErrorKind(info.kind, `${label} codexErrorInfo kind`),
|
|
931
|
+
};
|
|
932
|
+
if (
|
|
933
|
+
Object.hasOwn(info, 'httpStatusCode')
|
|
934
|
+
&& Number.isSafeInteger(info.httpStatusCode)
|
|
935
|
+
&& info.httpStatusCode >= 0
|
|
936
|
+
&& info.httpStatusCode <= 65_535
|
|
937
|
+
) {
|
|
938
|
+
projected.httpStatusCode = info.httpStatusCode;
|
|
939
|
+
}
|
|
940
|
+
return projected;
|
|
941
|
+
}
|
|
942
|
+
if (keys.length === 1) {
|
|
943
|
+
const [variant] = keys;
|
|
944
|
+
const projected = {
|
|
945
|
+
kind: projectCodexErrorKind(variant, `${label} codexErrorInfo variant`),
|
|
946
|
+
};
|
|
947
|
+
const inner = info[variant];
|
|
948
|
+
if (inner && typeof inner === 'object' && !Array.isArray(inner)) {
|
|
949
|
+
if (
|
|
950
|
+
Object.hasOwn(inner, 'httpStatusCode')
|
|
951
|
+
&& Number.isSafeInteger(inner.httpStatusCode)
|
|
952
|
+
&& inner.httpStatusCode >= 0
|
|
953
|
+
&& inner.httpStatusCode <= 65_535
|
|
954
|
+
) {
|
|
955
|
+
projected.httpStatusCode = inner.httpStatusCode;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
return projected;
|
|
959
|
+
}
|
|
960
|
+
throw new CodexAppServerError(
|
|
961
|
+
`app-server ${label} codexErrorInfo is malformed`,
|
|
962
|
+
'CODEX_PROTOCOL_ERROR',
|
|
963
|
+
);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function projectOptionalResetsAt(raw) {
|
|
967
|
+
if (raw == null) return undefined;
|
|
968
|
+
if (Number.isSafeInteger(raw) && raw >= 0) return raw;
|
|
969
|
+
if (typeof raw === 'string') {
|
|
970
|
+
if (RESETS_AT_EPOCH_RE.test(raw)) return raw;
|
|
971
|
+
if (RESETS_AT_ISO_RE.test(raw) && !Number.isNaN(Date.parse(raw))) return raw;
|
|
972
|
+
}
|
|
973
|
+
return undefined;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
function projectTurnError(value, label) {
|
|
977
|
+
const err = protocolObject(value, label);
|
|
978
|
+
const projected = { present: true };
|
|
979
|
+
const codexErrorInfo = projectCodexErrorInfo(err.codexErrorInfo, label);
|
|
980
|
+
if (codexErrorInfo !== null) {
|
|
981
|
+
projected.codexErrorInfo = codexErrorInfo;
|
|
982
|
+
}
|
|
983
|
+
let rawResetsAt = Object.hasOwn(err, 'resetsAt') ? err.resetsAt : undefined;
|
|
984
|
+
if (
|
|
985
|
+
rawResetsAt == null
|
|
986
|
+
&& err.codexErrorInfo
|
|
987
|
+
&& typeof err.codexErrorInfo === 'object'
|
|
988
|
+
&& !Array.isArray(err.codexErrorInfo)
|
|
989
|
+
) {
|
|
990
|
+
rawResetsAt = Object.hasOwn(err.codexErrorInfo, 'resetsAt')
|
|
991
|
+
? err.codexErrorInfo.resetsAt
|
|
992
|
+
: undefined;
|
|
993
|
+
if (rawResetsAt == null) {
|
|
994
|
+
const infoKeys = Object.keys(err.codexErrorInfo);
|
|
995
|
+
if (infoKeys.length === 1) {
|
|
996
|
+
const inner = err.codexErrorInfo[infoKeys[0]];
|
|
997
|
+
if (inner && typeof inner === 'object' && !Array.isArray(inner) && Object.hasOwn(inner, 'resetsAt')) {
|
|
998
|
+
rawResetsAt = inner.resetsAt;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
const resetsAt = projectOptionalResetsAt(rawResetsAt);
|
|
1004
|
+
if (resetsAt !== undefined) {
|
|
1005
|
+
projected.resetsAt = resetsAt;
|
|
1006
|
+
}
|
|
1007
|
+
return projected;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
903
1010
|
function projectNotification(message, ownedCwd) {
|
|
904
1011
|
const source = protocolObject(
|
|
905
1012
|
message.params ?? {},
|
|
@@ -937,9 +1044,8 @@ function projectNotification(message, ownedCwd) {
|
|
|
937
1044
|
'CODEX_PROTOCOL_ERROR',
|
|
938
1045
|
);
|
|
939
1046
|
}
|
|
940
|
-
protocolObject(source.error, 'error notification payload');
|
|
941
1047
|
params.willRetry = source.willRetry;
|
|
942
|
-
params.error =
|
|
1048
|
+
params.error = projectTurnError(source.error, 'error notification payload');
|
|
943
1049
|
} else if (message.method === 'thread/status/changed') {
|
|
944
1050
|
params.status = projectThreadStatus(source.status, 'thread status');
|
|
945
1051
|
} else if (message.method === 'thread/settings/updated') {
|
|
@@ -1313,7 +1419,7 @@ function projectTurn(value, label) {
|
|
|
1313
1419
|
type: protocolRequiredString(projected.type, `${label} item type`),
|
|
1314
1420
|
};
|
|
1315
1421
|
}),
|
|
1316
|
-
error: turn.error == null ? null : {
|
|
1422
|
+
error: turn.error == null ? null : projectTurnError(turn.error, `${label} error`),
|
|
1317
1423
|
};
|
|
1318
1424
|
}
|
|
1319
1425
|
|
|
@@ -2111,6 +2217,22 @@ function projectRequestParams(method, params, spec, ownedCwd) {
|
|
|
2111
2217
|
}
|
|
2112
2218
|
: {}
|
|
2113
2219
|
);
|
|
2220
|
+
const developerInstructions = () => {
|
|
2221
|
+
if (!Object.hasOwn(params, 'developerInstructions')) return {};
|
|
2222
|
+
const value = params.developerInstructions;
|
|
2223
|
+
if (
|
|
2224
|
+
typeof value !== 'string'
|
|
2225
|
+
|| value.length === 0
|
|
2226
|
+
|| Buffer.byteLength(value, 'utf8') > MAX_TEXT_BYTES
|
|
2227
|
+
|| DEVELOPER_INSTRUCTIONS_CONTROL_CHAR_RE.test(value)
|
|
2228
|
+
) {
|
|
2229
|
+
throw new CodexAppServerError(
|
|
2230
|
+
'app-server developerInstructions is invalid',
|
|
2231
|
+
'CODEX_RPC_REJECTED',
|
|
2232
|
+
);
|
|
2233
|
+
}
|
|
2234
|
+
return { developerInstructions: value };
|
|
2235
|
+
};
|
|
2114
2236
|
if (method === 'initialize') {
|
|
2115
2237
|
plainObject(params.clientInfo, 'initialize clientInfo');
|
|
2116
2238
|
plainObject(params.capabilities, 'initialize capabilities');
|
|
@@ -2183,6 +2305,7 @@ function projectRequestParams(method, params, spec, ownedCwd) {
|
|
|
2183
2305
|
return {
|
|
2184
2306
|
cwd: ownedCwd,
|
|
2185
2307
|
model: boundedRequiredString(params.model, 'model'),
|
|
2308
|
+
...developerInstructions(),
|
|
2186
2309
|
};
|
|
2187
2310
|
}
|
|
2188
2311
|
if (method === 'hooks/list') {
|
|
@@ -2207,7 +2330,12 @@ function projectRequestParams(method, params, spec, ownedCwd) {
|
|
|
2207
2330
|
}
|
|
2208
2331
|
return { threadId: threadId(), includeTurns: false };
|
|
2209
2332
|
}
|
|
2210
|
-
if (method === 'thread/resume')
|
|
2333
|
+
if (method === 'thread/resume') {
|
|
2334
|
+
return {
|
|
2335
|
+
threadId: threadId(),
|
|
2336
|
+
...developerInstructions(),
|
|
2337
|
+
};
|
|
2338
|
+
}
|
|
2211
2339
|
if (method === 'turn/start') {
|
|
2212
2340
|
const projected = {
|
|
2213
2341
|
threadId: threadId(),
|
|
@@ -65,7 +65,9 @@
|
|
|
65
65
|
"cwd",
|
|
66
66
|
"model"
|
|
67
67
|
],
|
|
68
|
-
"optional": [
|
|
68
|
+
"optional": [
|
|
69
|
+
"developerInstructions"
|
|
70
|
+
],
|
|
69
71
|
"stateChanging": true
|
|
70
72
|
},
|
|
71
73
|
"thread/read": {
|
|
@@ -77,7 +79,9 @@
|
|
|
77
79
|
"required": [
|
|
78
80
|
"threadId"
|
|
79
81
|
],
|
|
80
|
-
"optional": [
|
|
82
|
+
"optional": [
|
|
83
|
+
"developerInstructions"
|
|
84
|
+
],
|
|
81
85
|
"stateChanging": true
|
|
82
86
|
},
|
|
83
87
|
"turn/start": {
|
|
@@ -283,6 +283,25 @@ function authDisabledError() {
|
|
|
283
283
|
return err;
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
+
function attachReplaySafety(err, pending) {
|
|
287
|
+
const replyCount = Array.isArray(pending?.replies) ? pending.replies.length : 0;
|
|
288
|
+
const inFlightReplies = pending?._replyDeliveriesInFlight || 0;
|
|
289
|
+
const consumedByText = Boolean(pending?._consumedByText);
|
|
290
|
+
const hadToolCall = Boolean(pending?._hadToolCall);
|
|
291
|
+
const foldedCount = pending?._foldedCount || 0;
|
|
292
|
+
err.replyCount = replyCount;
|
|
293
|
+
err.hadToolCall = hadToolCall;
|
|
294
|
+
err.foldedCount = foldedCount;
|
|
295
|
+
err.replaySafe = (
|
|
296
|
+
replyCount === 0
|
|
297
|
+
&& inFlightReplies === 0
|
|
298
|
+
&& !consumedByText
|
|
299
|
+
&& !hadToolCall
|
|
300
|
+
&& foldedCount === 0
|
|
301
|
+
);
|
|
302
|
+
return err;
|
|
303
|
+
}
|
|
304
|
+
|
|
286
305
|
class CliProcess extends Process {
|
|
287
306
|
/**
|
|
288
307
|
* @param {object} opts
|
|
@@ -317,6 +336,8 @@ class CliProcess extends Process {
|
|
|
317
336
|
// hint (appended to the system prompt) and outbound file-size cap, so the engine
|
|
318
337
|
// is transport-agnostic. Were hard `require`s in the polygram/water copy.
|
|
319
338
|
displayHint = '',
|
|
339
|
+
autoCompactWindow,
|
|
340
|
+
promptCacheTtl,
|
|
320
341
|
maxOutboundFileBytes = 100 * 1024 * 1024,
|
|
321
342
|
// orchestra identity options — the consumer's names, so the engine is neutral.
|
|
322
343
|
// sessionPrefix: tmux session + socket + mcp-config file prefix (MUST match the
|
|
@@ -378,6 +399,17 @@ class CliProcess extends Process {
|
|
|
378
399
|
// spawn context's string hint, so a null (from a resolver that returned
|
|
379
400
|
// one) would be drift no context could ever match — a permanent respawn.
|
|
380
401
|
this.displayHint = typeof displayHint === 'string' ? displayHint : '';
|
|
402
|
+
if (autoCompactWindow !== undefined && autoCompactWindow !== null && (
|
|
403
|
+
!Number.isSafeInteger(autoCompactWindow) || autoCompactWindow < 100_000 || autoCompactWindow > 1_000_000
|
|
404
|
+
)) {
|
|
405
|
+
throw new TypeError('autoCompactWindow must be null or a safe integer from 100000 to 1000000');
|
|
406
|
+
}
|
|
407
|
+
if (promptCacheTtl !== undefined && promptCacheTtl !== null
|
|
408
|
+
&& promptCacheTtl !== '5m' && promptCacheTtl !== '1h') {
|
|
409
|
+
throw new TypeError("promptCacheTtl must be null, '5m' or '1h'");
|
|
410
|
+
}
|
|
411
|
+
this.autoCompactWindow = autoCompactWindow;
|
|
412
|
+
this.promptCacheTtl = promptCacheTtl;
|
|
381
413
|
this._injectedMaxOutboundFileBytes = maxOutboundFileBytes;
|
|
382
414
|
this.sessionPrefix = sessionPrefix;
|
|
383
415
|
this.bridgeServerName = bridgeServerName;
|
|
@@ -1311,26 +1343,20 @@ class CliProcess extends Process {
|
|
|
1311
1343
|
// same fallback chain. The `--add-dir` flag is independent: it
|
|
1312
1344
|
// declares an additional trusted-roots entry, NOT the launch dir.
|
|
1313
1345
|
//
|
|
1314
|
-
//
|
|
1346
|
+
// Suppress Claude's resume-age dialog, whose default action compacts the session.
|
|
1347
|
+
const envExtras = { CLAUDE_CODE_RESUME_THRESHOLD_MINUTES: '525600' };
|
|
1348
|
+
if (this.autoCompactWindow !== undefined) {
|
|
1349
|
+
envExtras.CLAUDE_CODE_AUTO_COMPACT_WINDOW = this.autoCompactWindow === null ? '' : String(this.autoCompactWindow);
|
|
1350
|
+
}
|
|
1351
|
+
if (this.promptCacheTtl !== undefined) {
|
|
1352
|
+
envExtras.CLAUDE_CODE_PROMPT_CACHE_TTL = this.promptCacheTtl === null ? '' : this.promptCacheTtl;
|
|
1353
|
+
}
|
|
1315
1354
|
await this.runner.spawn({
|
|
1316
1355
|
name: tmuxName,
|
|
1317
1356
|
cwd: resolvedCwd || opts.cwd || process.cwd(),
|
|
1318
1357
|
command: this.sessionLauncher || this.claudeBin,
|
|
1319
1358
|
args: this.sessionLauncher ? [this.claudeBin, ...claudeArgs] : claudeArgs,
|
|
1320
|
-
envExtras
|
|
1321
|
-
// Resume-dialog suppression (docs/0.13-resume-dialog-fix-spec.md B1):
|
|
1322
|
-
// claude's session-age "resume-return" dialog fires when sessionAge ≥
|
|
1323
|
-
// this many minutes AND est. tokens ≥ CLAUDE_CODE_RESUME_TOKEN_THRESHOLD
|
|
1324
|
-
// (defaults 70 / 1e5, binary-verified on 2.1.158). Its pre-selected
|
|
1325
|
-
// option literally runs /compact — silently compacting every aged
|
|
1326
|
-
// --resume (and breaking the /model "conversation kept" guarantee).
|
|
1327
|
-
// A huge threshold (1 year) means the dialog never triggers and resume
|
|
1328
|
-
// is always full-session-as-is. Per-process env — the operator's own
|
|
1329
|
-
// interactive claude is untouched. Belt-and-braces: the session-age
|
|
1330
|
-
// gate trigger below still navigates to "full" if a future binary bump
|
|
1331
|
-
// renames this var.
|
|
1332
|
-
CLAUDE_CODE_RESUME_THRESHOLD_MINUTES: '525600',
|
|
1333
|
-
},
|
|
1359
|
+
envExtras,
|
|
1334
1360
|
});
|
|
1335
1361
|
|
|
1336
1362
|
// Dialog handling (Phase 0 finding) — poll capture-pane and Enter through:
|
|
@@ -2095,6 +2121,7 @@ class CliProcess extends Process {
|
|
|
2095
2121
|
this._writeToBridge({ kind: 'question_answer', tool_call_id: msg.tool_call_id, result: { cancelled: true, error: 'chat_id mismatch' } });
|
|
2096
2122
|
return;
|
|
2097
2123
|
}
|
|
2124
|
+
this._markPendingToolCall([args.turn_id]);
|
|
2098
2125
|
this._openQuestions.add(msg.tool_call_id);
|
|
2099
2126
|
this._startQuestionKeepAlive();
|
|
2100
2127
|
// 0.13 D1: waiting-on-user — claude is legitimately silent, so the
|
|
@@ -2286,6 +2313,11 @@ class CliProcess extends Process {
|
|
|
2286
2313
|
...(Array.isArray(args.consumed_turn_ids) ? args.consumed_turn_ids : []),
|
|
2287
2314
|
])
|
|
2288
2315
|
: [];
|
|
2316
|
+
this._markPendingToolCall([
|
|
2317
|
+
replyAttribution.effectiveTurnId,
|
|
2318
|
+
...(Array.isArray(args.consumed_turn_ids) ? args.consumed_turn_ids : []),
|
|
2319
|
+
args.turn_id,
|
|
2320
|
+
]);
|
|
2289
2321
|
const dispatchPromise = Promise.resolve().then(() => this.toolDispatcher({
|
|
2290
2322
|
sessionKey: this.sessionKey,
|
|
2291
2323
|
chatId: this.chatId,
|
|
@@ -2732,6 +2764,24 @@ class CliProcess extends Process {
|
|
|
2732
2764
|
return true;
|
|
2733
2765
|
}
|
|
2734
2766
|
|
|
2767
|
+
_markPendingToolCall(turnIds = []) {
|
|
2768
|
+
let matched = false;
|
|
2769
|
+
for (const tid of turnIds) {
|
|
2770
|
+
if (typeof tid !== 'string' || !tid) continue;
|
|
2771
|
+
const pending = this.pendingTurns.get(tid);
|
|
2772
|
+
if (pending) {
|
|
2773
|
+
pending._hadToolCall = true;
|
|
2774
|
+
matched = true;
|
|
2775
|
+
}
|
|
2776
|
+
}
|
|
2777
|
+
if (!matched && this.pendingTurns.size > 0) {
|
|
2778
|
+
// Unattributed tool dispatch: mark the sole live turn, or fail closed across all live turns.
|
|
2779
|
+
for (const pending of this.pendingTurns.values()) {
|
|
2780
|
+
pending._hadToolCall = true;
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
|
|
2735
2785
|
/**
|
|
2736
2786
|
* A follow-up picked up inside a pending turn's query (its UserPromptSubmit
|
|
2737
2787
|
* carries that turn's prompt_id) was folded into that turn. Remember the
|
|
@@ -2739,15 +2789,26 @@ class CliProcess extends Process {
|
|
|
2739
2789
|
* claude runs as its own query gets a new prompt_id and no host.
|
|
2740
2790
|
*/
|
|
2741
2791
|
_noteFoldHost(lEntry, promptId) {
|
|
2742
|
-
if (!promptId
|
|
2743
|
-
|
|
2744
|
-
let hostId = null;
|
|
2792
|
+
if (!promptId) return;
|
|
2793
|
+
const hosts = [];
|
|
2745
2794
|
for (const [turnId, pending] of this.pendingTurns) {
|
|
2746
2795
|
if (pending._promptId !== promptId) continue;
|
|
2747
|
-
|
|
2748
|
-
|
|
2796
|
+
hosts.push([turnId, pending]);
|
|
2797
|
+
}
|
|
2798
|
+
if (hosts.length === 0) return;
|
|
2799
|
+
for (const [turnId, host] of hosts) {
|
|
2800
|
+
if (!lEntry._foldCountedTurnIds?.has(turnId)) {
|
|
2801
|
+
host._foldedCount = (host._foldedCount || 0) + 1;
|
|
2802
|
+
(lEntry._foldCountedTurnIds ||= new Set()).add(turnId);
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
if (
|
|
2806
|
+
hosts.length === 1
|
|
2807
|
+
&& !lEntry.foldHostTurnId
|
|
2808
|
+
&& (lEntry.source === 'autosteer' || lEntry.source === 'edit-fold')
|
|
2809
|
+
) {
|
|
2810
|
+
lEntry.foldHostTurnId = hosts[0][0];
|
|
2749
2811
|
}
|
|
2750
|
-
if (hostId) lEntry.foldHostTurnId = hostId;
|
|
2751
2812
|
}
|
|
2752
2813
|
|
|
2753
2814
|
/**
|
|
@@ -3687,6 +3748,7 @@ class CliProcess extends Process {
|
|
|
3687
3748
|
err.code = 'CLAUDE_API_ERROR';
|
|
3688
3749
|
err.apiError = apiError;
|
|
3689
3750
|
}
|
|
3751
|
+
attachReplaySafety(err, pending);
|
|
3690
3752
|
// Reject BEFORE emitting: the turn's ceilings are already cleared, so a
|
|
3691
3753
|
// throwing listener must not be able to leave it pending forever.
|
|
3692
3754
|
try { pending.reject(err); } catch {}
|
|
@@ -3915,6 +3977,8 @@ class CliProcess extends Process {
|
|
|
3915
3977
|
// 0.13 D1: pickup marker — set when a UserPromptSubmit prompt carries
|
|
3916
3978
|
// this turn's envelope (the seen-slice). Rung 1's Stop attribution.
|
|
3917
3979
|
seen: false,
|
|
3980
|
+
_hadToolCall: false,
|
|
3981
|
+
_foldedCount: 0,
|
|
3918
3982
|
quietTimer: null,
|
|
3919
3983
|
_activityQuietTimer: null,
|
|
3920
3984
|
// hardTimer = idle ceiling. Resets on any activity (_noteActivity)
|
|
@@ -4361,6 +4425,12 @@ class CliProcess extends Process {
|
|
|
4361
4425
|
typeof spawnContext?.displayHint === 'string'
|
|
4362
4426
|
&& spawnContext.displayHint !== this.displayHint
|
|
4363
4427
|
) reasons.push('display-hint');
|
|
4428
|
+
if (spawnContext?.autoCompactWindow !== undefined && spawnContext.autoCompactWindow !== this.autoCompactWindow) {
|
|
4429
|
+
reasons.push('auto-compact-window');
|
|
4430
|
+
}
|
|
4431
|
+
if (spawnContext?.promptCacheTtl !== undefined && spawnContext.promptCacheTtl !== this.promptCacheTtl) {
|
|
4432
|
+
reasons.push('prompt-cache-ttl');
|
|
4433
|
+
}
|
|
4364
4434
|
return reasons;
|
|
4365
4435
|
}
|
|
4366
4436
|
|
|
@@ -4737,6 +4807,8 @@ class CliProcess extends Process {
|
|
|
4737
4807
|
// a tool-less sub-agent whose only post-boundary signal is its SubagentStop.
|
|
4738
4808
|
const orphanSubagentStop = ev.type === 'SubagentStop'
|
|
4739
4809
|
&& !(this._pendingSubagentStarts && this._pendingSubagentStarts.length);
|
|
4810
|
+
const isStreamToolHook = (ev.type === 'PreToolUse' || ev.type === 'PostToolUse')
|
|
4811
|
+
&& ev.toolName === this._streamToolHookName;
|
|
4740
4812
|
if (ev.type === 'Stop' || ev.type === 'StopFailure' || orphanSubagentStop) {
|
|
4741
4813
|
this._lastHookEventAt = Date.now();
|
|
4742
4814
|
} else if (ev.type && ev.type !== 'parse-error' && ev.type !== 'unknown') {
|
|
@@ -4755,8 +4827,6 @@ class CliProcess extends Process {
|
|
|
4755
4827
|
// (_lastHookEventAt and _workHookSeq above are deliberately left alone:
|
|
4756
4828
|
// neither touches stop-grace, and suppressing them would quietly change
|
|
4757
4829
|
// the other finalizer rungs.)
|
|
4758
|
-
const isStreamToolHook = (ev.type === 'PreToolUse' || ev.type === 'PostToolUse')
|
|
4759
|
-
&& ev.toolName === this._streamToolHookName;
|
|
4760
4830
|
if (!isStreamToolHook) this._noteActivity(`hook:${ev.type}`);
|
|
4761
4831
|
}
|
|
4762
4832
|
|
|
@@ -4855,6 +4925,11 @@ class CliProcess extends Process {
|
|
|
4855
4925
|
return;
|
|
4856
4926
|
|
|
4857
4927
|
case 'PreToolUse': {
|
|
4928
|
+
if (!isStreamToolHook) {
|
|
4929
|
+
for (const pending of this.pendingTurns.values()) {
|
|
4930
|
+
if (pending.seen === true) pending._hadToolCall = true;
|
|
4931
|
+
}
|
|
4932
|
+
}
|
|
4858
4933
|
const activePending = this.pendingTurns.size === 1
|
|
4859
4934
|
? this.pendingTurns.values().next().value
|
|
4860
4935
|
: null;
|
|
@@ -4912,6 +4987,9 @@ class CliProcess extends Process {
|
|
|
4912
4987
|
|
|
4913
4988
|
case 'PostToolUse':
|
|
4914
4989
|
for (const pending of this.pendingTurns.values()) {
|
|
4990
|
+
if (!isStreamToolHook && pending.seen === true) {
|
|
4991
|
+
pending._hadToolCall = true;
|
|
4992
|
+
}
|
|
4915
4993
|
pending.activeToolIds?.delete(ev.toolUseId);
|
|
4916
4994
|
}
|
|
4917
4995
|
this.emit('tool-result', {
|
|
@@ -5437,6 +5515,11 @@ class CliProcess extends Process {
|
|
|
5437
5515
|
// 0.13 D2: the injected turn_id is LEDGERED — pre-P3 it never escaped this
|
|
5438
5516
|
// function, making fold/new-turn/drop indistinguishable (seam S4).
|
|
5439
5517
|
this._ledgerAdd(turnId, { source, msgId });
|
|
5518
|
+
const lEntry = this.inputLedger.get(turnId);
|
|
5519
|
+
for (const [hostTurnId, pending] of this.pendingTurns) {
|
|
5520
|
+
pending._foldedCount = (pending._foldedCount || 0) + 1;
|
|
5521
|
+
if (lEntry) (lEntry._foldCountedTurnIds ||= new Set()).add(hostTurnId);
|
|
5522
|
+
}
|
|
5440
5523
|
this._logEvent('inject-user-message', {
|
|
5441
5524
|
session_key: this.sessionKey,
|
|
5442
5525
|
chat_id: this.chatId,
|
|
@@ -5808,7 +5891,7 @@ class CliProcess extends Process {
|
|
|
5808
5891
|
if (!this.compactionWarn?.enabled || this._compactionWarned) return;
|
|
5809
5892
|
const usage = await readContextTokens(transcriptPath);
|
|
5810
5893
|
if (!usage) return;
|
|
5811
|
-
const pct = contextPct(usage.total) * 100;
|
|
5894
|
+
const pct = contextPct(usage.total, this.autoCompactWindow ?? undefined) * 100;
|
|
5812
5895
|
if (pct < this.compactionWarn.thresholdPct) return;
|
|
5813
5896
|
if (this._compactionWarned) return; // re-check after the async gap
|
|
5814
5897
|
this._compactionWarned = true;
|
|
@@ -5850,7 +5933,7 @@ class CliProcess extends Process {
|
|
|
5850
5933
|
if (pending._stopGraceTimer) clearTimeout(pending._stopGraceTimer);
|
|
5851
5934
|
if (pending._activityQuietTimer) clearTimeout(pending._activityQuietTimer);
|
|
5852
5935
|
if (pending._onStop) this.off('stop-hook', pending._onStop);
|
|
5853
|
-
try { pending.reject(makeErr()); } catch {}
|
|
5936
|
+
try { pending.reject(attachReplaySafety(makeErr(), pending)); } catch {}
|
|
5854
5937
|
}
|
|
5855
5938
|
this.pendingTurns.clear();
|
|
5856
5939
|
|
|
@@ -5863,7 +5946,7 @@ class CliProcess extends Process {
|
|
|
5863
5946
|
for (const item of remaining) {
|
|
5864
5947
|
drained++;
|
|
5865
5948
|
try { item.clearTimers?.(); } catch {}
|
|
5866
|
-
try { item.reject?.(makeErr()); } catch {}
|
|
5949
|
+
try { item.reject?.(attachReplaySafety(makeErr(), item)); } catch {}
|
|
5867
5950
|
}
|
|
5868
5951
|
|
|
5869
5952
|
this.inFlight = false;
|