@aiwayds/dsh-opentui 0.28.1 → 0.29.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/CHANGELOG.md +83 -0
- package/dist/bridge/bundle-fingerprint.json +1 -1
- package/dist/bridge/index.js +2935 -207
- package/dist/client/index.js +1572 -93
- package/dist/client/index.js.map +22 -19
- package/dist/locales/en.json +71 -1
- package/dist/locales/zh-CN.json +71 -1
- package/package.json +1 -1
- package/scripts/lib/inproc-companions.mjs +1 -1
package/dist/bridge/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// ../bridge/src/index.ts
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { readFileSync as readFileSync2, realpathSync } from "node:fs";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
4
|
+
import { appendFile, lstat, mkdir, open as open2, readFile, readdir, realpath, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
6
|
+
import { homedir as homedir2 } from "node:os";
|
|
7
|
+
import { dirname as dirname4, join as join6 } from "node:path";
|
|
6
8
|
|
|
7
9
|
// ../bridge/src/ask-frames.ts
|
|
8
10
|
var ASK_FRAME_TYPES = {
|
|
@@ -25,6 +27,19 @@ var ASK_ERROR_CODE_SET = new Set(Object.values(ASK_ERROR_CODES));
|
|
|
25
27
|
function isAskErrorCode(value) {
|
|
26
28
|
return typeof value === "string" && ASK_ERROR_CODE_SET.has(value);
|
|
27
29
|
}
|
|
30
|
+
var SETTLE_REASONS = [
|
|
31
|
+
"answered",
|
|
32
|
+
"rejected",
|
|
33
|
+
"unavailable",
|
|
34
|
+
"timeout",
|
|
35
|
+
"aborted",
|
|
36
|
+
"turn-ended",
|
|
37
|
+
"session-closed",
|
|
38
|
+
"detached",
|
|
39
|
+
"connection-closed",
|
|
40
|
+
"no-channel",
|
|
41
|
+
"auto-approved"
|
|
42
|
+
];
|
|
28
43
|
function isRecord(value) {
|
|
29
44
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
30
45
|
}
|
|
@@ -245,7 +260,45 @@ function validateAskSettled(value) {
|
|
|
245
260
|
const outcome = oneOf(value.outcome, OUTCOMES, "outcome", code);
|
|
246
261
|
if (typeof outcome !== "string")
|
|
247
262
|
return outcome;
|
|
248
|
-
|
|
263
|
+
let reason;
|
|
264
|
+
if (value.reason !== undefined) {
|
|
265
|
+
const parsed = oneOf(value.reason, SETTLE_REASONS, "reason", code);
|
|
266
|
+
if (typeof parsed !== "string")
|
|
267
|
+
return parsed;
|
|
268
|
+
reason = parsed;
|
|
269
|
+
}
|
|
270
|
+
const sessionId = optionalString(value.sessionId, "sessionId", code);
|
|
271
|
+
if (typeof sessionId === "object")
|
|
272
|
+
return sessionId;
|
|
273
|
+
let kind;
|
|
274
|
+
if (value.kind !== undefined) {
|
|
275
|
+
const parsed = oneOf(value.kind, KINDS, "kind", code);
|
|
276
|
+
if (typeof parsed !== "string")
|
|
277
|
+
return parsed;
|
|
278
|
+
kind = parsed;
|
|
279
|
+
}
|
|
280
|
+
const toolName = optionalString(value.toolName, "toolName", code);
|
|
281
|
+
if (typeof toolName === "object")
|
|
282
|
+
return toolName;
|
|
283
|
+
const callId = optionalString(value.callId, "callId", code);
|
|
284
|
+
if (typeof callId === "object")
|
|
285
|
+
return callId;
|
|
286
|
+
const childSessionId = optionalString(value.childSessionId, "childSessionId", code);
|
|
287
|
+
if (typeof childSessionId === "object")
|
|
288
|
+
return childSessionId;
|
|
289
|
+
return {
|
|
290
|
+
ok: true,
|
|
291
|
+
value: {
|
|
292
|
+
eventId,
|
|
293
|
+
outcome,
|
|
294
|
+
...reason !== undefined ? { reason } : {},
|
|
295
|
+
...sessionId !== undefined ? { sessionId } : {},
|
|
296
|
+
...kind !== undefined ? { kind } : {},
|
|
297
|
+
...toolName !== undefined ? { toolName } : {},
|
|
298
|
+
...callId !== undefined ? { callId } : {},
|
|
299
|
+
...childSessionId !== undefined ? { childSessionId } : {}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
249
302
|
}
|
|
250
303
|
function validateAskResponse(value) {
|
|
251
304
|
const code = ASK_ERROR_CODES.INVALID_RESPONSE;
|
|
@@ -408,6 +461,11 @@ var WRITE_TOOL_POLICY = Object.freeze({
|
|
|
408
461
|
|
|
409
462
|
// ../bridge/src/ask-registry.ts
|
|
410
463
|
var DEFAULT_RECORD_LIMIT = 256;
|
|
464
|
+
var ANSWER_SETTLE_REASON = {
|
|
465
|
+
approved: "answered",
|
|
466
|
+
denied: "rejected",
|
|
467
|
+
unavailable: "unavailable"
|
|
468
|
+
};
|
|
411
469
|
var DEFAULT_MAX_ASK_WAIT_MS = 3600000;
|
|
412
470
|
function remember(ids, id, limit) {
|
|
413
471
|
ids.add(id);
|
|
@@ -482,9 +540,11 @@ class AskRegistry {
|
|
|
482
540
|
sessionId: redactIdentifier(input.sessionId) ?? input.sessionId,
|
|
483
541
|
turnId: redactIdentifier(turnId) ?? turnId,
|
|
484
542
|
...redactIdentifier(input.toolName) !== undefined ? { toolName: redactIdentifier(input.toolName) } : {},
|
|
543
|
+
...redactIdentifier(input.childSessionId) !== undefined ? { childSessionId: redactIdentifier(input.childSessionId) } : {},
|
|
485
544
|
verdict: "allowed-once",
|
|
486
545
|
outcome: "approved",
|
|
487
546
|
behavior: "always",
|
|
547
|
+
settleReason: "auto-approved",
|
|
488
548
|
source: "summary",
|
|
489
549
|
at: this.#now()
|
|
490
550
|
});
|
|
@@ -520,6 +580,13 @@ class AskRegistry {
|
|
|
520
580
|
#emit(frame) {
|
|
521
581
|
this.#sink(frame);
|
|
522
582
|
}
|
|
583
|
+
#emitTerminal(frame) {
|
|
584
|
+
try {
|
|
585
|
+
this.#emit(frame);
|
|
586
|
+
} catch (err) {
|
|
587
|
+
this.#logger?.warn?.("[ask-registry] terminal frame emit failed (decision unchanged): %s", err);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
523
590
|
create(turnId, input) {
|
|
524
591
|
const eventId = this.nextEventId(turnId);
|
|
525
592
|
const request = { ...input, eventId };
|
|
@@ -531,6 +598,7 @@ class AskRegistry {
|
|
|
531
598
|
if (deadlineAt !== undefined) {
|
|
532
599
|
entry.deadlineTimer = this.#arm(() => {
|
|
533
600
|
this.#settle(entry, this.#deadlineOutcome(entry.request.kind), {
|
|
601
|
+
settleReason: "timeout",
|
|
534
602
|
code: ASK_ERROR_CODES.DEADLINE_EXCEEDED,
|
|
535
603
|
cancelReason: "deadline",
|
|
536
604
|
message: "ask deadline exceeded",
|
|
@@ -540,29 +608,43 @@ class AskRegistry {
|
|
|
540
608
|
}
|
|
541
609
|
entry.hardCapTimer = this.#arm(() => {
|
|
542
610
|
this.#settle(entry, "unavailable", {
|
|
611
|
+
settleReason: "timeout",
|
|
543
612
|
code: ASK_ERROR_CODES.DEADLINE_EXCEEDED,
|
|
544
613
|
cancelReason: "deadline",
|
|
545
614
|
message: "maxAskWaitMs hard cap exceeded",
|
|
546
615
|
source: "timeout"
|
|
547
616
|
});
|
|
548
617
|
}, this.#maxAskWaitMs);
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
618
|
+
try {
|
|
619
|
+
this.#writeJournal({
|
|
620
|
+
eventId,
|
|
621
|
+
kind: ASK_JOURNAL_KINDS.REQUESTED,
|
|
622
|
+
askKind: request.kind,
|
|
623
|
+
sessionId: redactIdentifier(request.sessionId) ?? request.sessionId,
|
|
624
|
+
turnId: redactIdentifier(turnId) ?? turnId,
|
|
625
|
+
...redactIdentifier(request.toolName) !== undefined ? { toolName: redactIdentifier(request.toolName) } : {},
|
|
626
|
+
...redactIdentifier(request.childSessionId) !== undefined ? { childSessionId: redactIdentifier(request.childSessionId) } : {},
|
|
627
|
+
source: "request",
|
|
628
|
+
at: createdAt
|
|
629
|
+
});
|
|
630
|
+
this.#emit({ type: ASK_FRAME_TYPES.REQUEST, payload: request });
|
|
631
|
+
} catch (err) {
|
|
632
|
+
this.#disarm(entry.deadlineTimer);
|
|
633
|
+
this.#disarm(entry.graceTimer);
|
|
634
|
+
this.#disarm(entry.hardCapTimer);
|
|
635
|
+
entry.deadlineTimer = undefined;
|
|
636
|
+
entry.graceTimer = undefined;
|
|
637
|
+
entry.hardCapTimer = undefined;
|
|
638
|
+
this.#pending.delete(eventId);
|
|
639
|
+
this.#logger?.warn?.("[ask-registry] ask.request emit failed; rolled back %s: %s", eventId, err);
|
|
640
|
+
throw err;
|
|
641
|
+
}
|
|
560
642
|
return request;
|
|
561
643
|
}
|
|
562
644
|
#deadlineOutcome(kind) {
|
|
563
645
|
return kind === "approval" ? "denied" : "cancelled";
|
|
564
646
|
}
|
|
565
|
-
#settle(entry, outcome, options
|
|
647
|
+
#settle(entry, outcome, options) {
|
|
566
648
|
const eventId = entry.request.eventId;
|
|
567
649
|
this.#disarm(entry.deadlineTimer);
|
|
568
650
|
this.#disarm(entry.graceTimer);
|
|
@@ -576,7 +658,7 @@ class AskRegistry {
|
|
|
576
658
|
else
|
|
577
659
|
remember(this.#settledIds, eventId, this.#recordLimit);
|
|
578
660
|
if (options.cancelReason !== undefined) {
|
|
579
|
-
this.#
|
|
661
|
+
this.#emitTerminal({ type: ASK_FRAME_TYPES.CANCEL, payload: { eventId, reason: options.cancelReason } });
|
|
580
662
|
}
|
|
581
663
|
const settlement = {
|
|
582
664
|
eventId,
|
|
@@ -596,6 +678,8 @@ class AskRegistry {
|
|
|
596
678
|
sessionId: redactIdentifier(entry.request.sessionId) ?? entry.request.sessionId,
|
|
597
679
|
turnId: redactIdentifier(entry.turnId) ?? entry.turnId,
|
|
598
680
|
...redactIdentifier(entry.request.toolName) !== undefined ? { toolName: redactIdentifier(entry.request.toolName) } : {},
|
|
681
|
+
...redactIdentifier(entry.request.childSessionId) !== undefined ? { childSessionId: redactIdentifier(entry.request.childSessionId) } : {},
|
|
682
|
+
settleReason: options.settleReason,
|
|
599
683
|
...options.verdict !== undefined ? { verdict: options.verdict } : {},
|
|
600
684
|
outcome,
|
|
601
685
|
...options.behavior !== undefined ? { behavior: options.behavior } : {},
|
|
@@ -605,9 +689,42 @@ class AskRegistry {
|
|
|
605
689
|
source: options.source ?? (cancelled ? "teardown" : "answer"),
|
|
606
690
|
at: settlement.at
|
|
607
691
|
});
|
|
608
|
-
this.#
|
|
692
|
+
this.#emitTerminal({
|
|
693
|
+
type: ASK_FRAME_TYPES.SETTLED,
|
|
694
|
+
payload: {
|
|
695
|
+
eventId,
|
|
696
|
+
outcome,
|
|
697
|
+
reason: options.settleReason,
|
|
698
|
+
sessionId: entry.request.sessionId,
|
|
699
|
+
kind: entry.request.kind,
|
|
700
|
+
...entry.request.toolName !== undefined ? { toolName: entry.request.toolName } : {},
|
|
701
|
+
...entry.request.callId !== undefined ? { callId: entry.request.callId } : {},
|
|
702
|
+
...entry.request.childSessionId !== undefined ? { childSessionId: entry.request.childSessionId } : {}
|
|
703
|
+
}
|
|
704
|
+
});
|
|
609
705
|
return settlement;
|
|
610
706
|
}
|
|
707
|
+
settleExternal(eventId, input) {
|
|
708
|
+
const entry = this.#pending.get(eventId);
|
|
709
|
+
if (entry === undefined)
|
|
710
|
+
return;
|
|
711
|
+
let outcome;
|
|
712
|
+
if (input.outcome !== undefined) {
|
|
713
|
+
outcome = input.outcome;
|
|
714
|
+
} else if (input.settleReason === "timeout") {
|
|
715
|
+
outcome = input.defaultOutcome === "rejected" ? "denied" : input.defaultOutcome === "unavailable" ? "unavailable" : this.#deadlineOutcome(entry.request.kind);
|
|
716
|
+
} else {
|
|
717
|
+
outcome = "cancelled";
|
|
718
|
+
}
|
|
719
|
+
return this.#settle(entry, outcome, {
|
|
720
|
+
settleReason: input.settleReason,
|
|
721
|
+
...input.code !== undefined ? { code: input.code } : input.settleReason === "timeout" ? { code: ASK_ERROR_CODES.DEADLINE_EXCEEDED } : {},
|
|
722
|
+
...input.message !== undefined ? { message: input.message } : {},
|
|
723
|
+
...input.cancelReason !== undefined ? { cancelReason: input.cancelReason } : {},
|
|
724
|
+
...input.settleReason !== "timeout" ? { ended: true } : {},
|
|
725
|
+
source: input.source ?? (input.settleReason === "timeout" ? "timeout" : "teardown")
|
|
726
|
+
});
|
|
727
|
+
}
|
|
611
728
|
answer(sessionId, rawParams) {
|
|
612
729
|
const parsed = validateAskResponse(rawParams);
|
|
613
730
|
if (!parsed.ok) {
|
|
@@ -670,9 +787,11 @@ class AskRegistry {
|
|
|
670
787
|
askKind: entry.request.kind,
|
|
671
788
|
sessionId: sourceSession,
|
|
672
789
|
turnId: sourceTurn,
|
|
790
|
+
...redactIdentifier(entry.request.childSessionId) !== undefined ? { childSessionId: redactIdentifier(entry.request.childSessionId) } : {},
|
|
673
791
|
toolName: tool,
|
|
674
792
|
verdict: "allowed-once",
|
|
675
793
|
outcome: "approved",
|
|
794
|
+
settleReason: "answered",
|
|
676
795
|
behavior: "always",
|
|
677
796
|
source: "answer",
|
|
678
797
|
at: this.#now()
|
|
@@ -680,6 +799,7 @@ class AskRegistry {
|
|
|
680
799
|
}
|
|
681
800
|
}
|
|
682
801
|
const settlement = this.#settle(entry, outcome, {
|
|
802
|
+
settleReason: ANSWER_SETTLE_REASON[outcome],
|
|
683
803
|
...params.verdict !== undefined ? { verdict: params.verdict } : {},
|
|
684
804
|
...params.behavior !== undefined ? { behavior: params.behavior } : {},
|
|
685
805
|
...params.answers !== undefined ? { answers: params.answers } : {},
|
|
@@ -704,13 +824,28 @@ class AskRegistry {
|
|
|
704
824
|
askKind: input.kind,
|
|
705
825
|
sessionId: redactIdentifier(input.sessionId) ?? input.sessionId,
|
|
706
826
|
turnId: redactIdentifier(input.turnId) ?? input.turnId,
|
|
827
|
+
...redactIdentifier(input.toolName) !== undefined ? { toolName: redactIdentifier(input.toolName) } : {},
|
|
828
|
+
...redactIdentifier(input.childSessionId) !== undefined ? { childSessionId: redactIdentifier(input.childSessionId) } : {},
|
|
707
829
|
verdict: "unavailable",
|
|
708
830
|
outcome: "unavailable",
|
|
831
|
+
settleReason: "no-channel",
|
|
709
832
|
code: ASK_ERROR_CODES.CHANNEL_UNAVAILABLE,
|
|
710
833
|
source: "fail-closed",
|
|
711
834
|
at: settlement.at
|
|
712
835
|
});
|
|
713
|
-
this.#
|
|
836
|
+
this.#emitTerminal({
|
|
837
|
+
type: ASK_FRAME_TYPES.SETTLED,
|
|
838
|
+
payload: {
|
|
839
|
+
eventId,
|
|
840
|
+
outcome: "unavailable",
|
|
841
|
+
reason: "no-channel",
|
|
842
|
+
sessionId: input.sessionId,
|
|
843
|
+
kind: input.kind,
|
|
844
|
+
...input.toolName !== undefined ? { toolName: input.toolName } : {},
|
|
845
|
+
...input.callId !== undefined ? { callId: input.callId } : {},
|
|
846
|
+
...input.childSessionId !== undefined ? { childSessionId: input.childSessionId } : {}
|
|
847
|
+
}
|
|
848
|
+
});
|
|
714
849
|
return { settlement, code: ASK_ERROR_CODES.CHANNEL_UNAVAILABLE };
|
|
715
850
|
}
|
|
716
851
|
markDetached(sessionId) {
|
|
@@ -719,6 +854,7 @@ class AskRegistry {
|
|
|
719
854
|
continue;
|
|
720
855
|
entry.graceTimer = this.#arm(() => {
|
|
721
856
|
this.#settle(entry, "cancelled", {
|
|
857
|
+
settleReason: "detached",
|
|
722
858
|
cancelReason: "host-abort",
|
|
723
859
|
code: ASK_ERROR_CODES.TURN_ENDED,
|
|
724
860
|
message: "client detached past the grace window",
|
|
@@ -740,7 +876,7 @@ class AskRegistry {
|
|
|
740
876
|
for (const entry of [...this.#pending.values()]) {
|
|
741
877
|
if (entry.turnId !== turnId)
|
|
742
878
|
continue;
|
|
743
|
-
out.push(this.#settle(entry, "cancelled", { cancelReason: reason, ended: true, message: "turn ended" }));
|
|
879
|
+
out.push(this.#settle(entry, "cancelled", { settleReason: "turn-ended", cancelReason: reason, ended: true, message: "turn ended" }));
|
|
744
880
|
}
|
|
745
881
|
return out;
|
|
746
882
|
}
|
|
@@ -749,7 +885,7 @@ class AskRegistry {
|
|
|
749
885
|
for (const entry of [...this.#pending.values()]) {
|
|
750
886
|
if (entry.deliveredTo !== sessionId)
|
|
751
887
|
continue;
|
|
752
|
-
out.push(this.#settle(entry, "cancelled", { cancelReason: reason, ended: true, message: "session ended" }));
|
|
888
|
+
out.push(this.#settle(entry, "cancelled", { settleReason: "session-closed", cancelReason: reason, ended: true, message: "session ended" }));
|
|
753
889
|
}
|
|
754
890
|
return out;
|
|
755
891
|
}
|
|
@@ -767,7 +903,6 @@ class AskRegistry {
|
|
|
767
903
|
this.#seqByTurn.clear();
|
|
768
904
|
this.#settledIds.clear();
|
|
769
905
|
this.#endedIds.clear();
|
|
770
|
-
this.#settlementLog.length = 0;
|
|
771
906
|
this.#summary.clear();
|
|
772
907
|
this.#logger?.debug?.("[ask-registry] disposed: all timers released");
|
|
773
908
|
}
|
|
@@ -859,159 +994,1938 @@ function registerAppendSection(ctx, options = {}) {
|
|
|
859
994
|
});
|
|
860
995
|
let disposer;
|
|
861
996
|
try {
|
|
862
|
-
disposer = sp.section({
|
|
863
|
-
name: APPEND_SECTION_NAME,
|
|
864
|
-
order: APPEND_SECTION_ORDER,
|
|
865
|
-
text,
|
|
866
|
-
interpolate: false
|
|
867
|
-
});
|
|
997
|
+
disposer = sp.section({
|
|
998
|
+
name: APPEND_SECTION_NAME,
|
|
999
|
+
order: APPEND_SECTION_ORDER,
|
|
1000
|
+
text,
|
|
1001
|
+
interpolate: false
|
|
1002
|
+
});
|
|
1003
|
+
} catch (err) {
|
|
1004
|
+
warn(ctx, "[dsh-opentui-bridge] append section registration contained (plugin stays live): %s", err);
|
|
1005
|
+
return NOOP;
|
|
1006
|
+
}
|
|
1007
|
+
if (typeof disposer !== "function")
|
|
1008
|
+
disposer = NOOP;
|
|
1009
|
+
let disposed = false;
|
|
1010
|
+
const cleanup = () => {
|
|
1011
|
+
if (disposed)
|
|
1012
|
+
return;
|
|
1013
|
+
disposed = true;
|
|
1014
|
+
try {
|
|
1015
|
+
disposer?.();
|
|
1016
|
+
} catch {}
|
|
1017
|
+
};
|
|
1018
|
+
ctx.effect(() => cleanup, EFFECT_LABEL);
|
|
1019
|
+
return cleanup;
|
|
1020
|
+
}
|
|
1021
|
+
function warn(ctx, format, ...params) {
|
|
1022
|
+
try {
|
|
1023
|
+
ctx.logger?.warn(format, ...params);
|
|
1024
|
+
} catch {}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// ../bridge/src/preset-migration.ts
|
|
1028
|
+
function presetMentionsAppend(value) {
|
|
1029
|
+
if (typeof value === "string")
|
|
1030
|
+
return value === APPEND_SYSTEM_PRESET_ID;
|
|
1031
|
+
if (Array.isArray(value))
|
|
1032
|
+
return value.some(presetMentionsAppend);
|
|
1033
|
+
if (value !== null && typeof value === "object") {
|
|
1034
|
+
return Object.values(value).some(presetMentionsAppend);
|
|
1035
|
+
}
|
|
1036
|
+
return false;
|
|
1037
|
+
}
|
|
1038
|
+
async function readSessionAgentPreset(persistence, sessionId) {
|
|
1039
|
+
if (persistence === undefined)
|
|
1040
|
+
return;
|
|
1041
|
+
let handle;
|
|
1042
|
+
try {
|
|
1043
|
+
handle = await persistence.open(sessionId, "read");
|
|
1044
|
+
return handle?.header?.agentPreset;
|
|
1045
|
+
} catch {
|
|
1046
|
+
return;
|
|
1047
|
+
} finally {
|
|
1048
|
+
if (handle !== undefined) {
|
|
1049
|
+
try {
|
|
1050
|
+
await handle.close();
|
|
1051
|
+
} catch {}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
function logLegacyAppendPreset(logger) {
|
|
1056
|
+
logger.debug(`[append-system] header.agentPreset="${APPEND_SYSTEM_PRESET_ID}" 为旧版合成 preset id,在本 profile 中不生效(无 agentPresets 服务);append 内容由 bridge section 注入,行为与新建会话一致`);
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
// ../bridge/src/subagent-index.ts
|
|
1060
|
+
class SubagentIndex {
|
|
1061
|
+
rows = new Map;
|
|
1062
|
+
built = false;
|
|
1063
|
+
reset() {
|
|
1064
|
+
this.rows.clear();
|
|
1065
|
+
this.built = false;
|
|
1066
|
+
}
|
|
1067
|
+
syncFromList(items) {
|
|
1068
|
+
const next = new Map;
|
|
1069
|
+
let subagentCount = 0;
|
|
1070
|
+
for (const row of items) {
|
|
1071
|
+
if (row === null || typeof row !== "object")
|
|
1072
|
+
continue;
|
|
1073
|
+
if (row.origin !== "subagent")
|
|
1074
|
+
continue;
|
|
1075
|
+
if (typeof row.sessionId !== "string" || row.sessionId === "")
|
|
1076
|
+
continue;
|
|
1077
|
+
subagentCount += 1;
|
|
1078
|
+
next.set(row.sessionId, {
|
|
1079
|
+
parentSessionId: typeof row.parentSessionId === "string" ? row.parentSessionId : "",
|
|
1080
|
+
startedAt: typeof row.updatedAt === "number" ? row.updatedAt : 0,
|
|
1081
|
+
status: row.running === true ? "running" : "settled"
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
for (const [childId, cached] of this.rows) {
|
|
1085
|
+
if (!next.has(childId))
|
|
1086
|
+
next.set(childId, cached);
|
|
1087
|
+
}
|
|
1088
|
+
this.rows.clear();
|
|
1089
|
+
for (const [childId, row] of next)
|
|
1090
|
+
this.rows.set(childId, row);
|
|
1091
|
+
this.built = true;
|
|
1092
|
+
return subagentCount;
|
|
1093
|
+
}
|
|
1094
|
+
noteCatalog(childId, parentSessionId, startedAt) {
|
|
1095
|
+
if (typeof childId !== "string" || childId === "")
|
|
1096
|
+
return;
|
|
1097
|
+
const existing = this.rows.get(childId);
|
|
1098
|
+
if (existing !== undefined) {
|
|
1099
|
+
if (!existing.startedAt && typeof startedAt === "number")
|
|
1100
|
+
existing.startedAt = startedAt;
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
this.rows.set(childId, {
|
|
1104
|
+
parentSessionId,
|
|
1105
|
+
startedAt: typeof startedAt === "number" ? startedAt : 0,
|
|
1106
|
+
status: "running"
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
noteSettled(childId, lastSeq) {
|
|
1110
|
+
if (typeof childId !== "string" || childId === "")
|
|
1111
|
+
return;
|
|
1112
|
+
const row = this.rows.get(childId);
|
|
1113
|
+
if (row === undefined)
|
|
1114
|
+
return;
|
|
1115
|
+
row.status = "settled";
|
|
1116
|
+
if (typeof lastSeq === "number")
|
|
1117
|
+
row.lastSeq = lastSeq;
|
|
1118
|
+
}
|
|
1119
|
+
noteRunning(childId) {
|
|
1120
|
+
if (typeof childId !== "string" || childId === "")
|
|
1121
|
+
return;
|
|
1122
|
+
const row = this.rows.get(childId);
|
|
1123
|
+
if (row !== undefined)
|
|
1124
|
+
row.status = "running";
|
|
1125
|
+
}
|
|
1126
|
+
has(childId) {
|
|
1127
|
+
return this.rows.has(childId);
|
|
1128
|
+
}
|
|
1129
|
+
get(childId) {
|
|
1130
|
+
return this.rows.get(childId);
|
|
1131
|
+
}
|
|
1132
|
+
runningChildrenOf(parentSessionId) {
|
|
1133
|
+
const out = [];
|
|
1134
|
+
for (const [childId, row] of this.rows) {
|
|
1135
|
+
if (row.parentSessionId === parentSessionId && row.status === "running") {
|
|
1136
|
+
out.push({ childId, row });
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return out;
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
var indexes = new WeakMap;
|
|
1143
|
+
function getSubagentIndex(ctx) {
|
|
1144
|
+
let index = indexes.get(ctx);
|
|
1145
|
+
if (index === undefined) {
|
|
1146
|
+
index = new SubagentIndex;
|
|
1147
|
+
indexes.set(ctx, index);
|
|
1148
|
+
}
|
|
1149
|
+
return index;
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
// ../bridge/src/session-prune.ts
|
|
1153
|
+
import { basename, dirname, join as join2, sep } from "node:path";
|
|
1154
|
+
var DEFAULT_RETENTION_DAYS = 90;
|
|
1155
|
+
var MS_PER_DAY = 86400000;
|
|
1156
|
+
function encodeSegment(raw) {
|
|
1157
|
+
if (raw.length === 0)
|
|
1158
|
+
throw new Error("cannot encode an empty path segment");
|
|
1159
|
+
if (raw === ".")
|
|
1160
|
+
return "~002E";
|
|
1161
|
+
if (raw === "..")
|
|
1162
|
+
return "~002E~002E";
|
|
1163
|
+
let out = "";
|
|
1164
|
+
for (let i = 0;i < raw.length; i++) {
|
|
1165
|
+
const code = raw.charCodeAt(i);
|
|
1166
|
+
const ch = String.fromCharCode(code);
|
|
1167
|
+
if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
|
|
1168
|
+
out += ch;
|
|
1169
|
+
} else {
|
|
1170
|
+
out += "~" + code.toString(16).toUpperCase().padStart(4, "0");
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
return out;
|
|
1174
|
+
}
|
|
1175
|
+
function hasStatCapability(value) {
|
|
1176
|
+
return value !== null && typeof value === "object" && typeof value.stat === "function";
|
|
1177
|
+
}
|
|
1178
|
+
var DEFAULT_MAX_PAGES = 64;
|
|
1179
|
+
async function listAllSessions(lister, options) {
|
|
1180
|
+
const requested = options?.maxPages;
|
|
1181
|
+
const maxPages = typeof requested === "number" && Number.isInteger(requested) && requested > 0 && requested <= 512 ? requested : DEFAULT_MAX_PAGES;
|
|
1182
|
+
const rows = [];
|
|
1183
|
+
const seenIds = new Set;
|
|
1184
|
+
const usedCursors = new Set;
|
|
1185
|
+
let cursor;
|
|
1186
|
+
let pages = 0;
|
|
1187
|
+
let truncated = false;
|
|
1188
|
+
while (pages < maxPages) {
|
|
1189
|
+
usedCursors.add(cursor ?? "");
|
|
1190
|
+
const page = await lister.list({ _request: cursor !== undefined ? { cursor } : {} });
|
|
1191
|
+
if (page === null || typeof page !== "object" || !Array.isArray(page.items)) {
|
|
1192
|
+
throw new Error("BAD_REPLY: session.list returned an object without an items array");
|
|
1193
|
+
}
|
|
1194
|
+
pages += 1;
|
|
1195
|
+
for (const raw of page.items) {
|
|
1196
|
+
if (raw === null || typeof raw !== "object")
|
|
1197
|
+
continue;
|
|
1198
|
+
const row = raw;
|
|
1199
|
+
if (typeof row.sessionId !== "string" || row.sessionId === "" || seenIds.has(row.sessionId))
|
|
1200
|
+
continue;
|
|
1201
|
+
seenIds.add(row.sessionId);
|
|
1202
|
+
rows.push(row);
|
|
1203
|
+
}
|
|
1204
|
+
const hasMore = page.hasMore === true;
|
|
1205
|
+
const next = typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : undefined;
|
|
1206
|
+
if (!hasMore)
|
|
1207
|
+
break;
|
|
1208
|
+
if (next === undefined) {
|
|
1209
|
+
truncated = true;
|
|
1210
|
+
break;
|
|
1211
|
+
}
|
|
1212
|
+
if (usedCursors.has(next)) {
|
|
1213
|
+
truncated = true;
|
|
1214
|
+
break;
|
|
1215
|
+
}
|
|
1216
|
+
cursor = next;
|
|
1217
|
+
}
|
|
1218
|
+
if (pages >= maxPages && cursor !== undefined)
|
|
1219
|
+
truncated = true;
|
|
1220
|
+
return { rows, pages, truncated };
|
|
1221
|
+
}
|
|
1222
|
+
function isInside(root, target) {
|
|
1223
|
+
const base = root.length > 1 && root.endsWith(sep) ? root.slice(0, -1) : root;
|
|
1224
|
+
return target === base || target.startsWith(base.endsWith(sep) ? base : base + sep);
|
|
1225
|
+
}
|
|
1226
|
+
function locationPath(location) {
|
|
1227
|
+
if (typeof location === "string")
|
|
1228
|
+
return location !== "" ? location : undefined;
|
|
1229
|
+
if (location !== null && typeof location === "object") {
|
|
1230
|
+
return typeof location.path === "string" && location.path !== "" ? location.path : undefined;
|
|
1231
|
+
}
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
function hasRunningDescendant(id, rows) {
|
|
1235
|
+
const children = new Map;
|
|
1236
|
+
for (const row of rows) {
|
|
1237
|
+
if (typeof row.sessionId !== "string" || row.sessionId === "")
|
|
1238
|
+
continue;
|
|
1239
|
+
const parent = typeof row.parentSessionId === "string" ? row.parentSessionId : "";
|
|
1240
|
+
if (parent !== "") {
|
|
1241
|
+
const list = children.get(parent) ?? [];
|
|
1242
|
+
list.push(row.sessionId);
|
|
1243
|
+
children.set(parent, list);
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
const queue = [id];
|
|
1247
|
+
const visited = new Set([id]);
|
|
1248
|
+
while (queue.length > 0) {
|
|
1249
|
+
const current = queue.shift();
|
|
1250
|
+
for (const childId of children.get(current) ?? []) {
|
|
1251
|
+
if (visited.has(childId))
|
|
1252
|
+
continue;
|
|
1253
|
+
visited.add(childId);
|
|
1254
|
+
const child = rows.find((r) => r.sessionId === childId);
|
|
1255
|
+
if (child?.running === true)
|
|
1256
|
+
return true;
|
|
1257
|
+
queue.push(childId);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return rows.some((row) => row.running === true && typeof row.sessionId === "string" && row.sessionId.startsWith(id + "/"));
|
|
1261
|
+
}
|
|
1262
|
+
function skip(id, reason, location, ageDays) {
|
|
1263
|
+
return location !== undefined ? { sessionId: id, decision: "skip", reason, location, ...ageDays !== undefined ? { ageDays } : {} } : { sessionId: id, decision: "skip", reason, ...ageDays !== undefined ? { ageDays } : {} };
|
|
1264
|
+
}
|
|
1265
|
+
async function planSessionPrune(rows, persistence, fs, config) {
|
|
1266
|
+
const rootReal = await fs.realpath(config.sessionsRoot);
|
|
1267
|
+
const now = Number.isFinite(config.now) ? config.now : Date.now();
|
|
1268
|
+
const entries = [];
|
|
1269
|
+
for (const row of rows) {
|
|
1270
|
+
const rawId = row.sessionId;
|
|
1271
|
+
if (typeof rawId !== "string" || rawId === "") {
|
|
1272
|
+
entries.push(skip("", "field-anomaly"));
|
|
1273
|
+
continue;
|
|
1274
|
+
}
|
|
1275
|
+
const id = rawId;
|
|
1276
|
+
if (config.retentionDays === 0) {
|
|
1277
|
+
entries.push(skip(id, "retention-disabled"));
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
if (id === config.currentSessionId) {
|
|
1281
|
+
entries.push(skip(id, "current"));
|
|
1282
|
+
continue;
|
|
1283
|
+
}
|
|
1284
|
+
if (config.stagedIds?.has(id) === true) {
|
|
1285
|
+
entries.push(skip(id, "staged"));
|
|
1286
|
+
continue;
|
|
1287
|
+
}
|
|
1288
|
+
if (row.agentAvailable === true) {
|
|
1289
|
+
entries.push(skip(id, "agent-available"));
|
|
1290
|
+
continue;
|
|
1291
|
+
}
|
|
1292
|
+
if (typeof row.agentAvailable !== "boolean") {
|
|
1293
|
+
entries.push(skip(id, "field-anomaly"));
|
|
1294
|
+
continue;
|
|
1295
|
+
}
|
|
1296
|
+
if (row.running === true) {
|
|
1297
|
+
entries.push(skip(id, "running"));
|
|
1298
|
+
continue;
|
|
1299
|
+
}
|
|
1300
|
+
if (row.running !== false) {
|
|
1301
|
+
entries.push(skip(id, "field-anomaly"));
|
|
1302
|
+
continue;
|
|
1303
|
+
}
|
|
1304
|
+
if (typeof row.blank !== "boolean") {
|
|
1305
|
+
entries.push(skip(id, "field-anomaly"));
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
const updatedAt = row.updatedAt;
|
|
1309
|
+
if (updatedAt === undefined || updatedAt === null) {
|
|
1310
|
+
entries.push(skip(id, "missing-time"));
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
if (typeof updatedAt !== "number" || !Number.isFinite(updatedAt)) {
|
|
1314
|
+
entries.push(skip(id, "field-anomaly"));
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
if (updatedAt > now) {
|
|
1318
|
+
entries.push(skip(id, "future-time"));
|
|
1319
|
+
continue;
|
|
1320
|
+
}
|
|
1321
|
+
if (hasRunningDescendant(id, rows)) {
|
|
1322
|
+
entries.push(skip(id, "subtree-running"));
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
let snapshot;
|
|
1326
|
+
try {
|
|
1327
|
+
snapshot = await persistence.stat(id);
|
|
1328
|
+
} catch {
|
|
1329
|
+
snapshot = undefined;
|
|
1330
|
+
}
|
|
1331
|
+
if (snapshot === undefined || snapshot === null) {
|
|
1332
|
+
entries.push(skip(id, "unknown"));
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
if (snapshot.header?.id !== id) {
|
|
1336
|
+
entries.push(skip(id, "header-mismatch"));
|
|
1337
|
+
continue;
|
|
1338
|
+
}
|
|
1339
|
+
const path = locationPath(snapshot.location);
|
|
1340
|
+
if (path === undefined) {
|
|
1341
|
+
entries.push(skip(id, "no-location"));
|
|
1342
|
+
continue;
|
|
1343
|
+
}
|
|
1344
|
+
const sessionDir = dirname(path);
|
|
1345
|
+
if (basename(sessionDir) !== encodeSegment(id)) {
|
|
1346
|
+
entries.push(skip(id, "basename-mismatch", path));
|
|
1347
|
+
continue;
|
|
1348
|
+
}
|
|
1349
|
+
try {
|
|
1350
|
+
const st = await fs.lstat(sessionDir);
|
|
1351
|
+
if (!st.isDirectory() || st.isSymbolicLink?.() === true) {
|
|
1352
|
+
entries.push(skip(id, "not-directory", path));
|
|
1353
|
+
continue;
|
|
1354
|
+
}
|
|
1355
|
+
} catch {
|
|
1356
|
+
entries.push(skip(id, "not-directory", path));
|
|
1357
|
+
continue;
|
|
1358
|
+
}
|
|
1359
|
+
try {
|
|
1360
|
+
const real = await fs.realpath(sessionDir);
|
|
1361
|
+
if (!isInside(rootReal, real)) {
|
|
1362
|
+
entries.push(skip(id, "escaped-root", path));
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
} catch {
|
|
1366
|
+
entries.push(skip(id, "escaped-root", path));
|
|
1367
|
+
continue;
|
|
1368
|
+
}
|
|
1369
|
+
const lockPath = join2(sessionDir, "session.lock");
|
|
1370
|
+
try {
|
|
1371
|
+
const lockStat = await fs.stat(lockPath);
|
|
1372
|
+
const mtime = lockStat.mtimeMs;
|
|
1373
|
+
if (typeof mtime === "number" && Number.isFinite(mtime) && now - mtime < config.lockGraceMs) {
|
|
1374
|
+
entries.push(skip(id, "lock-fresh", path));
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
} catch (err) {
|
|
1378
|
+
const code = err?.code;
|
|
1379
|
+
if (code !== "ENOENT") {
|
|
1380
|
+
entries.push(skip(id, "unknown", path));
|
|
1381
|
+
continue;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
if (typeof fs.lockProbe === "function") {
|
|
1385
|
+
let probe;
|
|
1386
|
+
try {
|
|
1387
|
+
probe = await fs.lockProbe(lockPath);
|
|
1388
|
+
} catch {
|
|
1389
|
+
probe = { status: "unknown", detail: "probe-threw" };
|
|
1390
|
+
}
|
|
1391
|
+
if (probe.status === "lock-held") {
|
|
1392
|
+
entries.push(skip(id, "lock-held", path));
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
1395
|
+
if (probe.status === "unknown") {
|
|
1396
|
+
entries.push(skip(id, "unknown", path));
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
const freshGrace = typeof config.freshMtimeGraceMs === "number" && Number.isFinite(config.freshMtimeGraceMs) && config.freshMtimeGraceMs > 0 ? config.freshMtimeGraceMs : 0;
|
|
1401
|
+
if (freshGrace > 0) {
|
|
1402
|
+
try {
|
|
1403
|
+
const artifactStat = await fs.stat(path);
|
|
1404
|
+
const artifactMtime = artifactStat.mtimeMs;
|
|
1405
|
+
if (typeof artifactMtime === "number" && Number.isFinite(artifactMtime) && now - artifactMtime < freshGrace) {
|
|
1406
|
+
entries.push(skip(id, "fresh-mtime", path));
|
|
1407
|
+
continue;
|
|
1408
|
+
}
|
|
1409
|
+
} catch {
|
|
1410
|
+
entries.push(skip(id, "unknown", path));
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
const ageDays = (now - updatedAt) / MS_PER_DAY;
|
|
1415
|
+
const threshold = config.retentionDays + (row.blank === true ? config.blankGraceDays : 0);
|
|
1416
|
+
if (ageDays < threshold) {
|
|
1417
|
+
entries.push(skip(id, row.blank === true ? "blank-grace" : "within-retention", path, ageDays));
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
entries.push({ sessionId: id, decision: "prune", location: path, ageDays });
|
|
1421
|
+
}
|
|
1422
|
+
const byReason = {};
|
|
1423
|
+
let prune = 0;
|
|
1424
|
+
let skipped = 0;
|
|
1425
|
+
for (const entry of entries) {
|
|
1426
|
+
if (entry.decision === "prune") {
|
|
1427
|
+
prune += 1;
|
|
1428
|
+
} else {
|
|
1429
|
+
skipped += 1;
|
|
1430
|
+
const reason = entry.reason ?? "unknown";
|
|
1431
|
+
byReason[reason] = (byReason[reason] ?? 0) + 1;
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
return {
|
|
1435
|
+
generatedAt: now,
|
|
1436
|
+
retentionDays: config.retentionDays,
|
|
1437
|
+
entries,
|
|
1438
|
+
counts: { prune, skip: skipped, byReason }
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
// ../bridge/src/prune-lock-probe.ts
|
|
1443
|
+
import { realpathSync } from "node:fs";
|
|
1444
|
+
import { open, stat as fsStat } from "node:fs/promises";
|
|
1445
|
+
import { createRequire } from "node:module";
|
|
1446
|
+
var defaultIo = {
|
|
1447
|
+
open(path) {
|
|
1448
|
+
return open(path, "r");
|
|
1449
|
+
},
|
|
1450
|
+
stat(path) {
|
|
1451
|
+
return fsStat(path);
|
|
1452
|
+
}
|
|
1453
|
+
};
|
|
1454
|
+
function errorCode(err) {
|
|
1455
|
+
if (err === null || typeof err !== "object")
|
|
1456
|
+
return;
|
|
1457
|
+
const code = err.code;
|
|
1458
|
+
return typeof code === "string" ? code : undefined;
|
|
1459
|
+
}
|
|
1460
|
+
var cachedTryLockExclusive;
|
|
1461
|
+
var resolved = false;
|
|
1462
|
+
function resolveFlockTryLockExclusive(extraRoots = []) {
|
|
1463
|
+
if (extraRoots.length === 0 && resolved)
|
|
1464
|
+
return cachedTryLockExclusive;
|
|
1465
|
+
const roots = [...extraRoots, import.meta.url];
|
|
1466
|
+
if (process.argv[1]) {
|
|
1467
|
+
try {
|
|
1468
|
+
roots.push(realpathSync(process.argv[1]));
|
|
1469
|
+
} catch {}
|
|
1470
|
+
}
|
|
1471
|
+
let found;
|
|
1472
|
+
for (const root of roots) {
|
|
1473
|
+
try {
|
|
1474
|
+
const req = createRequire(root);
|
|
1475
|
+
const mod = req("@deepseek-ai/node-addon-system/flock");
|
|
1476
|
+
const fn = mod.tryLockExclusive;
|
|
1477
|
+
if (typeof fn === "function") {
|
|
1478
|
+
found = fn;
|
|
1479
|
+
break;
|
|
1480
|
+
}
|
|
1481
|
+
} catch {}
|
|
1482
|
+
}
|
|
1483
|
+
if (extraRoots.length === 0) {
|
|
1484
|
+
resolved = true;
|
|
1485
|
+
cachedTryLockExclusive = found;
|
|
1486
|
+
}
|
|
1487
|
+
return found;
|
|
1488
|
+
}
|
|
1489
|
+
function createPruneLockProbe(tryLockExclusive, io = defaultIo) {
|
|
1490
|
+
return async (lockPath) => {
|
|
1491
|
+
let handle;
|
|
1492
|
+
try {
|
|
1493
|
+
try {
|
|
1494
|
+
handle = await io.open(lockPath, "r");
|
|
1495
|
+
} catch (err) {
|
|
1496
|
+
const code = errorCode(err);
|
|
1497
|
+
return code === "ENOENT" || code === "ENOTDIR" ? { status: "no-lock", detail: code } : { status: "unknown", detail: code ?? "open-failed" };
|
|
1498
|
+
}
|
|
1499
|
+
try {
|
|
1500
|
+
await tryLockExclusive(handle.fd);
|
|
1501
|
+
} catch (err) {
|
|
1502
|
+
const code = errorCode(err);
|
|
1503
|
+
if (code === "EAGAIN" || code === "EWOULDBLOCK")
|
|
1504
|
+
return { status: "lock-held", detail: code };
|
|
1505
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
1506
|
+
return { status: "no-lock", detail: code };
|
|
1507
|
+
return { status: "unknown", detail: code ?? "flock-failed" };
|
|
1508
|
+
}
|
|
1509
|
+
try {
|
|
1510
|
+
const opened = await handle.stat();
|
|
1511
|
+
const current = await io.stat(lockPath);
|
|
1512
|
+
if (opened.dev !== current.dev || opened.ino !== current.ino) {
|
|
1513
|
+
return { status: "unknown", detail: "lock-file-replaced" };
|
|
1514
|
+
}
|
|
1515
|
+
} catch (err) {
|
|
1516
|
+
return { status: "unknown", detail: errorCode(err) ?? "stat-failed" };
|
|
1517
|
+
}
|
|
1518
|
+
return { status: "unlocked" };
|
|
1519
|
+
} finally {
|
|
1520
|
+
if (handle !== undefined) {
|
|
1521
|
+
try {
|
|
1522
|
+
await handle.close();
|
|
1523
|
+
} catch {}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
// ../bridge/src/session-prune-apply.ts
|
|
1530
|
+
import { createHash } from "node:crypto";
|
|
1531
|
+
import { basename as basename2, dirname as dirname2, join as join3, sep as sep2 } from "node:path";
|
|
1532
|
+
class ApplyError extends Error {
|
|
1533
|
+
code;
|
|
1534
|
+
detail;
|
|
1535
|
+
constructor(code, message, detail) {
|
|
1536
|
+
super(message);
|
|
1537
|
+
this.name = "ApplyError";
|
|
1538
|
+
this.code = code;
|
|
1539
|
+
this.detail = detail;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
function fail(code, message, detail) {
|
|
1543
|
+
throw new ApplyError(code, message, detail);
|
|
1544
|
+
}
|
|
1545
|
+
function errorCode2(err) {
|
|
1546
|
+
if (err === null || typeof err !== "object")
|
|
1547
|
+
return;
|
|
1548
|
+
const code = err.code;
|
|
1549
|
+
return typeof code === "string" ? code : undefined;
|
|
1550
|
+
}
|
|
1551
|
+
function isEnoent(err) {
|
|
1552
|
+
return errorCode2(err) === "ENOENT";
|
|
1553
|
+
}
|
|
1554
|
+
function sha256(text) {
|
|
1555
|
+
return createHash("sha256").update(text, "utf8").digest("hex");
|
|
1556
|
+
}
|
|
1557
|
+
function computeConfigFingerprint(policy) {
|
|
1558
|
+
return sha256(JSON.stringify([
|
|
1559
|
+
policy.retentionDays,
|
|
1560
|
+
policy.blankGraceDays,
|
|
1561
|
+
policy.lockGraceMs,
|
|
1562
|
+
policy.freshMtimeGraceMs,
|
|
1563
|
+
policy.sessionsRoot
|
|
1564
|
+
]));
|
|
1565
|
+
}
|
|
1566
|
+
function computePlanFingerprint(plan) {
|
|
1567
|
+
const canonical = JSON.stringify({
|
|
1568
|
+
retentionDays: plan.retentionDays,
|
|
1569
|
+
entries: plan.entries.map((e) => [
|
|
1570
|
+
e.sessionId,
|
|
1571
|
+
e.decision,
|
|
1572
|
+
e.reason ?? "",
|
|
1573
|
+
e.location ?? ""
|
|
1574
|
+
]),
|
|
1575
|
+
counts: plan.counts
|
|
1576
|
+
});
|
|
1577
|
+
return sha256(canonical);
|
|
1578
|
+
}
|
|
1579
|
+
function utcStamp(now) {
|
|
1580
|
+
return new Date(now).toISOString().replace(/[:.]/g, "-");
|
|
1581
|
+
}
|
|
1582
|
+
function trashRoot(dshHome) {
|
|
1583
|
+
return join3(dshHome, "trash");
|
|
1584
|
+
}
|
|
1585
|
+
function trashSessionsRoot(dshHome) {
|
|
1586
|
+
return join3(trashRoot(dshHome), "sessions");
|
|
1587
|
+
}
|
|
1588
|
+
function trashJournalRoot(dshHome) {
|
|
1589
|
+
return join3(trashRoot(dshHome), "journal");
|
|
1590
|
+
}
|
|
1591
|
+
function isInside2(root, target) {
|
|
1592
|
+
const base = root.length > 1 && root.endsWith(sep2) ? root.slice(0, -1) : root;
|
|
1593
|
+
return target === base || target.startsWith(base.endsWith(sep2) ? base : base + sep2);
|
|
1594
|
+
}
|
|
1595
|
+
function sameDev(a, b) {
|
|
1596
|
+
return a !== undefined && b !== undefined && String(a) === String(b);
|
|
1597
|
+
}
|
|
1598
|
+
async function pathExists(fs, path) {
|
|
1599
|
+
try {
|
|
1600
|
+
await fs.lstat(path);
|
|
1601
|
+
return true;
|
|
1602
|
+
} catch (err) {
|
|
1603
|
+
if (isEnoent(err))
|
|
1604
|
+
return false;
|
|
1605
|
+
throw err;
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
var APPLY_WIRE_MSG = {
|
|
1609
|
+
STALE_PLAN: "apply refused: the plan is stale",
|
|
1610
|
+
BAD_PARAMS: "apply refused: invalid parameters",
|
|
1611
|
+
BAD_PATH: "apply refused: an unsafe path was rejected",
|
|
1612
|
+
EXDEV: "apply refused: cross-device rename",
|
|
1613
|
+
CONFLICT: "apply refused: destination already exists",
|
|
1614
|
+
LOCKED: "apply refused: session.lock is held or unknown",
|
|
1615
|
+
ROLLED_BACK: "apply reversed the rename because session.lock was held at trash",
|
|
1616
|
+
ROLLBACK_FAILED: "apply failed and the reverse rename also failed",
|
|
1617
|
+
JOURNAL_FAILED: "apply reversed the rename after a journal write failed",
|
|
1618
|
+
NO_RECOVERY: "apply refused: no recovery path is available",
|
|
1619
|
+
INTERNAL: "apply failed: internal error"
|
|
1620
|
+
};
|
|
1621
|
+
function applyWireMessage(err) {
|
|
1622
|
+
const code = err instanceof ApplyError ? err.code : "INTERNAL";
|
|
1623
|
+
return APPLY_WIRE_MSG[code];
|
|
1624
|
+
}
|
|
1625
|
+
async function writeAppliedMarker(fs, path, record) {
|
|
1626
|
+
const data = JSON.stringify(record);
|
|
1627
|
+
try {
|
|
1628
|
+
await fs.writeFile(path, data, { flag: "wx", mode: 384 });
|
|
1629
|
+
return;
|
|
1630
|
+
} catch (err) {
|
|
1631
|
+
if (errorCode2(err) !== "EEXIST")
|
|
1632
|
+
throw err;
|
|
1633
|
+
}
|
|
1634
|
+
let existing;
|
|
1635
|
+
try {
|
|
1636
|
+
existing = JSON.parse(await fs.readFile(path));
|
|
1637
|
+
} catch {
|
|
1638
|
+
fail("JOURNAL_FAILED", "existing applied marker is not readable JSON", { id: record.id });
|
|
1639
|
+
}
|
|
1640
|
+
if (existing === null || typeof existing !== "object") {
|
|
1641
|
+
fail("JOURNAL_FAILED", "existing applied marker is not an object", { id: record.id });
|
|
1642
|
+
}
|
|
1643
|
+
const marker = existing;
|
|
1644
|
+
if (marker.id !== record.id || marker.to !== record.to) {
|
|
1645
|
+
fail("JOURNAL_FAILED", "existing applied marker identity mismatch", { id: record.id });
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
async function probeLock(probe, lockPath) {
|
|
1649
|
+
if (probe === undefined)
|
|
1650
|
+
return;
|
|
1651
|
+
let result;
|
|
1652
|
+
try {
|
|
1653
|
+
result = await probe(lockPath);
|
|
1654
|
+
} catch {
|
|
1655
|
+
fail("LOCKED", "lock probe threw; refusing to move a session", { lockPath });
|
|
1656
|
+
}
|
|
1657
|
+
if (result.status === "lock-held" || result.status === "unknown") {
|
|
1658
|
+
fail("LOCKED", "session.lock probe is not unlocked", { lockPath, status: result.status, detail: result.detail });
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
async function validateRollbackManifest(fs, journalBase, id, sourceDir, trashPath) {
|
|
1662
|
+
let raw;
|
|
1663
|
+
try {
|
|
1664
|
+
raw = JSON.parse(await fs.readFile(`${journalBase}.pre.json`));
|
|
1665
|
+
} catch {
|
|
1666
|
+
fail("BAD_PATH", "rollback refused: no valid pre-rename journal", { id });
|
|
1667
|
+
}
|
|
1668
|
+
if (raw === null || typeof raw !== "object")
|
|
1669
|
+
fail("BAD_PATH", "rollback refused: pre-rename journal is not an object", { id });
|
|
1670
|
+
const proof = raw;
|
|
1671
|
+
if (proof.id !== id || proof.sourceDir !== sourceDir || proof.trashPath !== trashPath) {
|
|
1672
|
+
fail("BAD_PATH", "rollback refused: pre-rename journal identity mismatch", { id });
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
async function restoreFromTrash(fs, options) {
|
|
1676
|
+
if (await pathExists(fs, options.sourceDir)) {
|
|
1677
|
+
fail("CONFLICT", "restore refused: source path already exists", { id: options.id });
|
|
1678
|
+
}
|
|
1679
|
+
let st;
|
|
1680
|
+
try {
|
|
1681
|
+
st = await fs.lstat(options.trashPath);
|
|
1682
|
+
} catch (err) {
|
|
1683
|
+
fail("BAD_PATH", "restore refused: trash entry is not readable", { id: options.id, code: errorCode2(err) });
|
|
1684
|
+
}
|
|
1685
|
+
if (options.flippedAfterRename !== true && (!st.isDirectory() || st.isSymbolicLink?.() === true)) {
|
|
1686
|
+
fail("BAD_PATH", "restore refused: trash entry is not a real directory", { id: options.id });
|
|
1687
|
+
}
|
|
1688
|
+
if (options.journalBase !== undefined) {
|
|
1689
|
+
await validateRollbackManifest(fs, options.journalBase, options.id, options.sourceDir, options.trashPath);
|
|
1690
|
+
} else {
|
|
1691
|
+
let snapshot;
|
|
1692
|
+
try {
|
|
1693
|
+
snapshot = await options.persistence.stat(options.id);
|
|
1694
|
+
} catch {
|
|
1695
|
+
snapshot = undefined;
|
|
1696
|
+
}
|
|
1697
|
+
if (snapshot?.header?.id !== options.id) {
|
|
1698
|
+
fail("BAD_PATH", "restore refused: header.id mismatch", { id: options.id });
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
if (options.skipLock !== true)
|
|
1702
|
+
await probeLock(options.lockProbe, join3(options.trashPath, "session.lock"));
|
|
1703
|
+
try {
|
|
1704
|
+
await fs.rename(options.trashPath, options.sourceDir);
|
|
1705
|
+
} catch (err) {
|
|
1706
|
+
if (errorCode2(err) === "EXDEV")
|
|
1707
|
+
fail("EXDEV", "restore refused: cross-device rename", { id: options.id });
|
|
1708
|
+
throw err;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
async function rollbackAfterRename(fs, deps, options) {
|
|
1712
|
+
const markerPath = join3(options.trashPath, ".applied.json");
|
|
1713
|
+
if (await pathExists(fs, markerPath)) {
|
|
1714
|
+
try {
|
|
1715
|
+
await fs.rename(markerPath, `${options.journalBase}.discarded.json`);
|
|
1716
|
+
} catch {
|
|
1717
|
+
fail("ROLLBACK_FAILED", APPLY_WIRE_MSG.ROLLBACK_FAILED, {
|
|
1718
|
+
id: options.id,
|
|
1719
|
+
reason: options.reason,
|
|
1720
|
+
cause: "applied-marker-retire-failed"
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
try {
|
|
1725
|
+
await restoreFromTrash(fs, {
|
|
1726
|
+
sourceDir: options.sourceDir,
|
|
1727
|
+
trashPath: options.trashPath,
|
|
1728
|
+
id: options.id,
|
|
1729
|
+
persistence: deps.persistence,
|
|
1730
|
+
journalBase: options.journalBase,
|
|
1731
|
+
lockProbe: deps.lockProbe,
|
|
1732
|
+
skipLock: true
|
|
1733
|
+
});
|
|
1734
|
+
} catch (rollbackErr) {
|
|
1735
|
+
const causeMessage = options.cause instanceof Error ? options.cause.message : String(options.cause);
|
|
1736
|
+
const rollbackMessage = rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr);
|
|
1737
|
+
fail("ROLLBACK_FAILED", APPLY_WIRE_MSG.ROLLBACK_FAILED, {
|
|
1738
|
+
id: options.id,
|
|
1739
|
+
reason: options.reason,
|
|
1740
|
+
cause: causeMessage,
|
|
1741
|
+
rollback: rollbackMessage
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
try {
|
|
1745
|
+
await fs.writeFile(`${options.journalBase}.rollback.json`, JSON.stringify({
|
|
1746
|
+
opId: deps.opId,
|
|
1747
|
+
phase: "rolled-back",
|
|
1748
|
+
id: options.id,
|
|
1749
|
+
sourceDir: options.sourceDir,
|
|
1750
|
+
trashPath: options.trashPath,
|
|
1751
|
+
planFingerprint: options.planFingerprint,
|
|
1752
|
+
reason: options.reason
|
|
1753
|
+
}), { flag: "wx", mode: 384 });
|
|
1754
|
+
} catch {}
|
|
1755
|
+
}
|
|
1756
|
+
async function recoverTrashOrphans(fs, dshHome) {
|
|
1757
|
+
const runsRoot = trashSessionsRoot(dshHome);
|
|
1758
|
+
let runs;
|
|
1759
|
+
try {
|
|
1760
|
+
runs = await fs.readdir(runsRoot);
|
|
1761
|
+
} catch (err) {
|
|
1762
|
+
if (isEnoent(err))
|
|
1763
|
+
return [];
|
|
1764
|
+
throw err;
|
|
1765
|
+
}
|
|
1766
|
+
const marked = [];
|
|
1767
|
+
for (const run of runs) {
|
|
1768
|
+
let entries;
|
|
1769
|
+
try {
|
|
1770
|
+
entries = await fs.readdir(join3(runsRoot, run));
|
|
1771
|
+
} catch (err) {
|
|
1772
|
+
if (isEnoent(err))
|
|
1773
|
+
continue;
|
|
1774
|
+
throw err;
|
|
1775
|
+
}
|
|
1776
|
+
for (const entry of entries) {
|
|
1777
|
+
if (entry.startsWith("."))
|
|
1778
|
+
continue;
|
|
1779
|
+
const entryDir = join3(runsRoot, run, entry);
|
|
1780
|
+
try {
|
|
1781
|
+
const st = await fs.lstat(entryDir);
|
|
1782
|
+
if (!st.isDirectory() || st.isSymbolicLink?.() === true)
|
|
1783
|
+
continue;
|
|
1784
|
+
} catch {
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
if (await pathExists(fs, join3(entryDir, ".applied.json")))
|
|
1788
|
+
continue;
|
|
1789
|
+
const marker = join3(entryDir, ".orphan.json");
|
|
1790
|
+
try {
|
|
1791
|
+
await fs.writeFile(marker, JSON.stringify({ markedAt: Date.now(), reason: "no-applied-manifest", path: entryDir }), { flag: "wx", mode: 384 });
|
|
1792
|
+
marked.push(entryDir);
|
|
1793
|
+
} catch (err) {
|
|
1794
|
+
if (errorCode2(err) !== "EEXIST")
|
|
1795
|
+
throw err;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
return marked;
|
|
1800
|
+
}
|
|
1801
|
+
async function applyTrashPlan(fs, deps, plan, config) {
|
|
1802
|
+
return deps.withApplyLock(async () => {
|
|
1803
|
+
const trashBase = trashRoot(config.dshHome);
|
|
1804
|
+
const sessionsTrash = trashSessionsRoot(config.dshHome);
|
|
1805
|
+
const journalDir = trashJournalRoot(config.dshHome);
|
|
1806
|
+
await fs.mkdir(trashBase, { recursive: true, mode: 448 });
|
|
1807
|
+
await fs.mkdir(sessionsTrash, { recursive: true, mode: 448 });
|
|
1808
|
+
await fs.mkdir(journalDir, { recursive: true, mode: 448 });
|
|
1809
|
+
const runDir = join3(sessionsTrash, utcStamp(deps.now));
|
|
1810
|
+
await fs.mkdir(runDir, { mode: 448 });
|
|
1811
|
+
const applied = [];
|
|
1812
|
+
const failed = [];
|
|
1813
|
+
let roots;
|
|
1814
|
+
try {
|
|
1815
|
+
const rootReal = await fs.realpath(config.sessionsRoot);
|
|
1816
|
+
const rootStat = await fs.stat(config.sessionsRoot);
|
|
1817
|
+
const trashStat = await fs.stat(runDir);
|
|
1818
|
+
if (!sameDev(rootStat.dev, trashStat.dev)) {
|
|
1819
|
+
fail("EXDEV", "sessions root and trash are on different devices", { sessionsRoot: config.sessionsRoot, runDir });
|
|
1820
|
+
}
|
|
1821
|
+
roots = { rootReal, trashStat };
|
|
1822
|
+
} catch (err) {
|
|
1823
|
+
const code = err instanceof ApplyError ? err.code : "INTERNAL";
|
|
1824
|
+
const message = applyWireMessage(err);
|
|
1825
|
+
const ids = plan.entries.filter((entry) => entry.decision === "prune").map((entry) => entry.sessionId);
|
|
1826
|
+
for (const id of ids.length > 0 ? ids : ["<root>"])
|
|
1827
|
+
failed.push({ id, code, message });
|
|
1828
|
+
return { opId: deps.opId, runDir, applied, failed, markedOrphans: [] };
|
|
1829
|
+
}
|
|
1830
|
+
const { rootReal, trashStat } = roots;
|
|
1831
|
+
const markedOrphans = await recoverTrashOrphans(fs, config.dshHome);
|
|
1832
|
+
for (const entry of plan.entries) {
|
|
1833
|
+
if (entry.decision !== "prune")
|
|
1834
|
+
continue;
|
|
1835
|
+
const id = entry.sessionId;
|
|
1836
|
+
const encoded = encodeSegment(id);
|
|
1837
|
+
const journalBase = join3(journalDir, `${deps.opId}-${encoded}`);
|
|
1838
|
+
try {
|
|
1839
|
+
const snapshot = await deps.persistence.stat(id);
|
|
1840
|
+
if (snapshot?.header?.id !== id)
|
|
1841
|
+
fail("BAD_PATH", "header.id mismatch", { id });
|
|
1842
|
+
const location = snapshot.location;
|
|
1843
|
+
const locationPath = typeof location === "string" ? location : location !== null && typeof location === "object" && typeof location.path === "string" ? location.path : undefined;
|
|
1844
|
+
if (locationPath === undefined || locationPath === "")
|
|
1845
|
+
fail("BAD_PATH", "no host location", { id });
|
|
1846
|
+
const sourceDir = dirname2(locationPath);
|
|
1847
|
+
if (basename2(sourceDir) !== encoded)
|
|
1848
|
+
fail("BAD_PATH", "basename/encodeSegment mismatch", { id, sourceDir });
|
|
1849
|
+
const st = await fs.lstat(sourceDir);
|
|
1850
|
+
if (!st.isDirectory() || st.isSymbolicLink?.() === true)
|
|
1851
|
+
fail("BAD_PATH", "not a real directory", { id, sourceDir });
|
|
1852
|
+
const real = await fs.realpath(sourceDir);
|
|
1853
|
+
if (!isInside2(rootReal, real))
|
|
1854
|
+
fail("BAD_PATH", "source escaped sessions root", { id, sourceDir, real });
|
|
1855
|
+
const sourceStat = await fs.stat(sourceDir);
|
|
1856
|
+
if (!sameDev(sourceStat.dev, trashStat.dev))
|
|
1857
|
+
fail("EXDEV", "cross-device rename refused", { id, sourceDir, runDir });
|
|
1858
|
+
await probeLock(deps.lockProbe, join3(sourceDir, "session.lock"));
|
|
1859
|
+
const trashPath = join3(runDir, encoded);
|
|
1860
|
+
if (await pathExists(fs, trashPath))
|
|
1861
|
+
fail("CONFLICT", "trash destination exists; refusing to overwrite", { id, trashPath });
|
|
1862
|
+
const recheckSt = await fs.lstat(sourceDir);
|
|
1863
|
+
if (!recheckSt.isDirectory() || recheckSt.isSymbolicLink?.() === true) {
|
|
1864
|
+
fail("BAD_PATH", "source flipped to symlink/non-directory before rename", { id, sourceDir });
|
|
1865
|
+
}
|
|
1866
|
+
const recheckReal = await fs.realpath(sourceDir);
|
|
1867
|
+
if (!isInside2(rootReal, recheckReal)) {
|
|
1868
|
+
fail("BAD_PATH", "source escaped sessions root before rename", { id, sourceDir, real: recheckReal });
|
|
1869
|
+
}
|
|
1870
|
+
const recheckStat = await fs.stat(sourceDir);
|
|
1871
|
+
if (!sameDev(recheckStat.dev, trashStat.dev)) {
|
|
1872
|
+
fail("EXDEV", "cross-device rename refused at second check", { id, sourceDir, runDir });
|
|
1873
|
+
}
|
|
1874
|
+
const recheckSnapshot = await deps.persistence.stat(id);
|
|
1875
|
+
if (recheckSnapshot?.header?.id !== id)
|
|
1876
|
+
fail("BAD_PATH", "header.id mismatch before rename", { id });
|
|
1877
|
+
await fs.writeFile(`${journalBase}.pre.json`, JSON.stringify({
|
|
1878
|
+
opId: deps.opId,
|
|
1879
|
+
phase: "pre-rename",
|
|
1880
|
+
id,
|
|
1881
|
+
sourceDir,
|
|
1882
|
+
trashPath,
|
|
1883
|
+
planFingerprint: config.planFingerprint,
|
|
1884
|
+
generatedAt: deps.now
|
|
1885
|
+
}), { flag: "wx", mode: 384 });
|
|
1886
|
+
try {
|
|
1887
|
+
await fs.rename(sourceDir, trashPath);
|
|
1888
|
+
} catch (err) {
|
|
1889
|
+
if (errorCode2(err) === "EXDEV")
|
|
1890
|
+
fail("EXDEV", "rename returned EXDEV; no copy fallback", { id, sourceDir, trashPath });
|
|
1891
|
+
throw err;
|
|
1892
|
+
}
|
|
1893
|
+
let movedSt;
|
|
1894
|
+
try {
|
|
1895
|
+
movedSt = await fs.lstat(trashPath);
|
|
1896
|
+
} catch (err) {
|
|
1897
|
+
fail("BAD_PATH", "moved entry is not readable at trash path", { id, trashPath, code: errorCode2(err) });
|
|
1898
|
+
}
|
|
1899
|
+
if (!movedSt.isDirectory() || movedSt.isSymbolicLink?.() === true) {
|
|
1900
|
+
await restoreFromTrash(fs, {
|
|
1901
|
+
sourceDir,
|
|
1902
|
+
trashPath,
|
|
1903
|
+
id,
|
|
1904
|
+
persistence: deps.persistence,
|
|
1905
|
+
journalBase,
|
|
1906
|
+
lockProbe: deps.lockProbe,
|
|
1907
|
+
skipLock: true,
|
|
1908
|
+
flippedAfterRename: true
|
|
1909
|
+
});
|
|
1910
|
+
await fs.writeFile(`${journalBase}.rollback.json`, JSON.stringify({
|
|
1911
|
+
opId: deps.opId,
|
|
1912
|
+
phase: "rolled-back",
|
|
1913
|
+
id,
|
|
1914
|
+
sourceDir,
|
|
1915
|
+
trashPath,
|
|
1916
|
+
planFingerprint: config.planFingerprint,
|
|
1917
|
+
reason: "flipped-to-symlink-or-non-directory"
|
|
1918
|
+
}), { flag: "wx", mode: 384 });
|
|
1919
|
+
fail("BAD_PATH", "moved entry flipped to symlink/non-directory; reversed rename", { id, trashPath });
|
|
1920
|
+
}
|
|
1921
|
+
let heldAtTrash = false;
|
|
1922
|
+
try {
|
|
1923
|
+
await probeLock(deps.lockProbe, join3(trashPath, "session.lock"));
|
|
1924
|
+
} catch (err) {
|
|
1925
|
+
heldAtTrash = true;
|
|
1926
|
+
if (!(err instanceof ApplyError) || err.code !== "LOCKED")
|
|
1927
|
+
throw err;
|
|
1928
|
+
}
|
|
1929
|
+
if (heldAtTrash) {
|
|
1930
|
+
await restoreFromTrash(fs, {
|
|
1931
|
+
sourceDir,
|
|
1932
|
+
trashPath,
|
|
1933
|
+
id,
|
|
1934
|
+
persistence: deps.persistence,
|
|
1935
|
+
journalBase,
|
|
1936
|
+
lockProbe: deps.lockProbe,
|
|
1937
|
+
skipLock: true
|
|
1938
|
+
});
|
|
1939
|
+
await fs.writeFile(`${journalBase}.rollback.json`, JSON.stringify({
|
|
1940
|
+
opId: deps.opId,
|
|
1941
|
+
phase: "rolled-back",
|
|
1942
|
+
id,
|
|
1943
|
+
sourceDir,
|
|
1944
|
+
trashPath,
|
|
1945
|
+
planFingerprint: config.planFingerprint
|
|
1946
|
+
}), { flag: "wx", mode: 384 });
|
|
1947
|
+
fail("ROLLED_BACK", "lock held/unknown at trash path; reversed rename", { id, trashPath });
|
|
1948
|
+
}
|
|
1949
|
+
const appliedRecord = {
|
|
1950
|
+
opId: deps.opId,
|
|
1951
|
+
phase: "applied",
|
|
1952
|
+
id,
|
|
1953
|
+
from: sourceDir,
|
|
1954
|
+
to: trashPath,
|
|
1955
|
+
planFingerprint: config.planFingerprint,
|
|
1956
|
+
appliedAt: deps.now
|
|
1957
|
+
};
|
|
1958
|
+
try {
|
|
1959
|
+
await fs.writeFile(`${journalBase}.post.json`, JSON.stringify(appliedRecord), { flag: "wx", mode: 384 });
|
|
1960
|
+
await fs.appendFile(join3(runDir, "manifest.jsonl"), JSON.stringify(appliedRecord) + `
|
|
1961
|
+
`);
|
|
1962
|
+
await writeAppliedMarker(fs, join3(trashPath, ".applied.json"), appliedRecord);
|
|
1963
|
+
} catch (journalErr) {
|
|
1964
|
+
await rollbackAfterRename(fs, deps, {
|
|
1965
|
+
sourceDir,
|
|
1966
|
+
trashPath,
|
|
1967
|
+
id,
|
|
1968
|
+
journalBase,
|
|
1969
|
+
planFingerprint: config.planFingerprint,
|
|
1970
|
+
cause: journalErr,
|
|
1971
|
+
reason: "post-rename-journal-write-failed"
|
|
1972
|
+
});
|
|
1973
|
+
fail("JOURNAL_FAILED", APPLY_WIRE_MSG.JOURNAL_FAILED, {
|
|
1974
|
+
id,
|
|
1975
|
+
cause: journalErr instanceof Error ? journalErr.message : String(journalErr)
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
applied.push({ id, from: sourceDir, to: trashPath });
|
|
1979
|
+
} catch (err) {
|
|
1980
|
+
const code = err instanceof ApplyError ? err.code : "INTERNAL";
|
|
1981
|
+
const message = applyWireMessage(err);
|
|
1982
|
+
failed.push({ id, code, message });
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
return { opId: deps.opId, runDir, applied, failed, markedOrphans };
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
// ../bridge/src/session-prune-purge.ts
|
|
1990
|
+
import { createHash as createHash2, createHmac, timingSafeEqual } from "node:crypto";
|
|
1991
|
+
import { zstdDecompressSync as nodeZstdDecompressSync } from "node:zlib";
|
|
1992
|
+
import { basename as basename3, isAbsolute, join as join4, relative, sep as sep3 } from "node:path";
|
|
1993
|
+
var MS_PER_DAY2 = 86400000;
|
|
1994
|
+
var DEFAULT_PURGE_RETENTION_DAYS = 7;
|
|
1995
|
+
|
|
1996
|
+
class PurgeError extends Error {
|
|
1997
|
+
code;
|
|
1998
|
+
detail;
|
|
1999
|
+
constructor(code, message, detail) {
|
|
2000
|
+
super(message);
|
|
2001
|
+
this.name = "PurgeError";
|
|
2002
|
+
this.code = code;
|
|
2003
|
+
this.detail = detail;
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
function fail2(code, message, detail) {
|
|
2007
|
+
throw new PurgeError(code, message, detail);
|
|
2008
|
+
}
|
|
2009
|
+
function purgeWireMessage(err) {
|
|
2010
|
+
return err instanceof PurgeError ? err.message : "purge entry could not be processed";
|
|
2011
|
+
}
|
|
2012
|
+
function errorCode3(err) {
|
|
2013
|
+
if (err === null || typeof err !== "object")
|
|
2014
|
+
return;
|
|
2015
|
+
const code = err.code;
|
|
2016
|
+
return typeof code === "string" ? code : undefined;
|
|
2017
|
+
}
|
|
2018
|
+
function sha2562(text) {
|
|
2019
|
+
return createHash2("sha256").update(text, "utf8").digest("hex");
|
|
2020
|
+
}
|
|
2021
|
+
function isInside3(root, target) {
|
|
2022
|
+
const base = root.length > 1 && root.endsWith(sep3) ? root.slice(0, -1) : root;
|
|
2023
|
+
return target === base || target.startsWith(base.endsWith(sep3) ? base : base + sep3);
|
|
2024
|
+
}
|
|
2025
|
+
function canonicalTokenPayload(p) {
|
|
2026
|
+
return JSON.stringify([
|
|
2027
|
+
p.v,
|
|
2028
|
+
p.opId,
|
|
2029
|
+
[...p.ids],
|
|
2030
|
+
[...p.paths],
|
|
2031
|
+
p.root,
|
|
2032
|
+
p.retentionDays,
|
|
2033
|
+
p.issuedAt,
|
|
2034
|
+
p.expiresAt,
|
|
2035
|
+
p.nonce
|
|
2036
|
+
]);
|
|
2037
|
+
}
|
|
2038
|
+
function issuePurgeToken(input, secret, ttlMs) {
|
|
2039
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0)
|
|
2040
|
+
fail2("BAD_PARAMS", "tokenTtlMs must be positive");
|
|
2041
|
+
const payload = {
|
|
2042
|
+
...input,
|
|
2043
|
+
v: 1,
|
|
2044
|
+
expiresAt: input.issuedAt + ttlMs
|
|
2045
|
+
};
|
|
2046
|
+
const body = Buffer.from(canonicalTokenPayload(payload), "utf8").toString("base64url");
|
|
2047
|
+
const sig = createHmac("sha256", secret).update(body).digest("hex");
|
|
2048
|
+
return { token: `${body}.${sig}`, payload };
|
|
2049
|
+
}
|
|
2050
|
+
function verifyPurgeToken(token, secret, now) {
|
|
2051
|
+
if (typeof token !== "string" || token === "")
|
|
2052
|
+
fail2("BAD_TOKEN", "purge requires a server-issued token");
|
|
2053
|
+
const parts = token.split(".");
|
|
2054
|
+
if (parts.length !== 2 || parts[0] === "" || parts[1] === "")
|
|
2055
|
+
fail2("BAD_TOKEN", "malformed purge token");
|
|
2056
|
+
const expected = createHmac("sha256", secret).update(parts[0]).digest();
|
|
2057
|
+
const actual = Buffer.from(parts[1], "hex");
|
|
2058
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
|
2059
|
+
fail2("BAD_TOKEN", "purge token signature mismatch");
|
|
2060
|
+
}
|
|
2061
|
+
let raw = undefined;
|
|
2062
|
+
try {
|
|
2063
|
+
raw = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
|
|
2064
|
+
} catch {}
|
|
2065
|
+
if (!Array.isArray(raw) || raw.length !== 9 || raw[0] !== 1)
|
|
2066
|
+
fail2("BAD_TOKEN", "purge token payload shape mismatch");
|
|
2067
|
+
const [v, opId, ids, paths, root, retentionDays, issuedAt, expiresAt, nonce] = raw;
|
|
2068
|
+
if (typeof opId !== "string" || !Array.isArray(ids) || !Array.isArray(paths) || ids.some((id) => typeof id !== "string") || paths.some((p) => typeof p !== "string") || ids.length !== paths.length || typeof root !== "string" || typeof retentionDays !== "number" || typeof issuedAt !== "number" || typeof expiresAt !== "number" || typeof nonce !== "string") {
|
|
2069
|
+
fail2("BAD_TOKEN", "purge token payload fields are invalid");
|
|
2070
|
+
}
|
|
2071
|
+
if (!Number.isFinite(issuedAt) || !Number.isFinite(expiresAt))
|
|
2072
|
+
fail2("BAD_TOKEN", "purge token timestamps are invalid");
|
|
2073
|
+
if (issuedAt > now + 1000)
|
|
2074
|
+
fail2("STALE_TOKEN", "purge token issued in the future");
|
|
2075
|
+
if (now >= expiresAt)
|
|
2076
|
+
fail2("STALE_TOKEN", "purge token expired");
|
|
2077
|
+
return { v: 1, opId, ids, paths, root, retentionDays, issuedAt, expiresAt, nonce };
|
|
2078
|
+
}
|
|
2079
|
+
async function resolvePurgeSecret(fs, dshHome, newSecret) {
|
|
2080
|
+
const path = join4(trashRoot(dshHome), ".purge.secret");
|
|
2081
|
+
try {
|
|
2082
|
+
const value = (await fs.readFile(path)).trim();
|
|
2083
|
+
if (value !== "")
|
|
2084
|
+
return value;
|
|
2085
|
+
fail2("INTERNAL", "purge secret file is empty");
|
|
2086
|
+
} catch (err) {
|
|
2087
|
+
if (err instanceof PurgeError)
|
|
2088
|
+
throw err;
|
|
2089
|
+
if (errorCode3(err) !== "ENOENT")
|
|
2090
|
+
throw err;
|
|
2091
|
+
}
|
|
2092
|
+
await fs.mkdir(trashRoot(dshHome), { recursive: true, mode: 448 });
|
|
2093
|
+
try {
|
|
2094
|
+
await fs.writeFile(path, newSecret(), { flag: "wx", mode: 384 });
|
|
2095
|
+
} catch (err) {
|
|
2096
|
+
if (errorCode3(err) !== "EEXIST")
|
|
2097
|
+
throw err;
|
|
2098
|
+
}
|
|
2099
|
+
const value = (await fs.readFile(path)).trim();
|
|
2100
|
+
if (value === "")
|
|
2101
|
+
fail2("INTERNAL", "purge secret file is empty");
|
|
2102
|
+
return value;
|
|
2103
|
+
}
|
|
2104
|
+
function readLocationPath(location) {
|
|
2105
|
+
if (typeof location === "string")
|
|
2106
|
+
return location || undefined;
|
|
2107
|
+
if (location !== null && typeof location === "object" && typeof location.path === "string")
|
|
2108
|
+
return location.path || undefined;
|
|
2109
|
+
return;
|
|
2110
|
+
}
|
|
2111
|
+
var RUN_NAME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;
|
|
2112
|
+
var ARTIFACT_FILENAME = "session.v4.jsonl.zstd";
|
|
2113
|
+
var RUN_MANIFEST_FILENAME = "manifest.jsonl";
|
|
2114
|
+
function zstdDecompress(frame) {
|
|
2115
|
+
const bun = globalThis.Bun;
|
|
2116
|
+
if (bun?.zstdDecompressSync !== undefined)
|
|
2117
|
+
return bun.zstdDecompressSync(frame);
|
|
2118
|
+
return nodeZstdDecompressSync(frame);
|
|
2119
|
+
}
|
|
2120
|
+
async function readTrashArtifactHeaderId(fs, dir) {
|
|
2121
|
+
const artifact = join4(dir, ARTIFACT_FILENAME);
|
|
2122
|
+
let frame;
|
|
2123
|
+
try {
|
|
2124
|
+
frame = await fs.readFileBuffer(artifact);
|
|
2125
|
+
} catch {
|
|
2126
|
+
fail2("BAD_MANIFEST", "trash entry has no readable session artifact");
|
|
2127
|
+
}
|
|
2128
|
+
if (frame.length === 0)
|
|
2129
|
+
fail2("BAD_MANIFEST", "trash session artifact is empty");
|
|
2130
|
+
let text;
|
|
2131
|
+
try {
|
|
2132
|
+
text = zstdDecompress(frame).toString("utf8");
|
|
2133
|
+
} catch {
|
|
2134
|
+
fail2("BAD_MANIFEST", "trash session artifact is not a valid zstd frame");
|
|
2135
|
+
}
|
|
2136
|
+
const firstLine = text.split(`
|
|
2137
|
+
`, 1)[0] ?? "";
|
|
2138
|
+
let header;
|
|
2139
|
+
try {
|
|
2140
|
+
header = JSON.parse(firstLine);
|
|
2141
|
+
} catch {
|
|
2142
|
+
fail2("BAD_MANIFEST", "trash session artifact header is not JSON");
|
|
2143
|
+
}
|
|
2144
|
+
if (header === null || typeof header !== "object") {
|
|
2145
|
+
fail2("BAD_MANIFEST", "trash session artifact header is not an object");
|
|
2146
|
+
}
|
|
2147
|
+
const id = header.id;
|
|
2148
|
+
if (typeof id !== "string" || id === "") {
|
|
2149
|
+
fail2("BAD_MANIFEST", "trash artifact header.id is missing");
|
|
2150
|
+
}
|
|
2151
|
+
return id;
|
|
2152
|
+
}
|
|
2153
|
+
function parseAppliedManifest(text) {
|
|
2154
|
+
let raw;
|
|
2155
|
+
try {
|
|
2156
|
+
raw = JSON.parse(text);
|
|
2157
|
+
} catch {
|
|
2158
|
+
fail2("BAD_MANIFEST", "trash entry .applied.json is not JSON");
|
|
2159
|
+
}
|
|
2160
|
+
if (raw === null || typeof raw !== "object")
|
|
2161
|
+
fail2("BAD_MANIFEST", "trash entry .applied.json is not an object");
|
|
2162
|
+
const m = raw;
|
|
2163
|
+
if (typeof m.id !== "string" || m.id === "")
|
|
2164
|
+
fail2("BAD_MANIFEST", "applied manifest id is missing");
|
|
2165
|
+
if (typeof m.to !== "string" || m.to === "")
|
|
2166
|
+
fail2("BAD_MANIFEST", "applied manifest to is missing");
|
|
2167
|
+
if (typeof m.opId !== "string" || m.opId === "")
|
|
2168
|
+
fail2("BAD_MANIFEST", "applied manifest opId is missing");
|
|
2169
|
+
if (typeof m.appliedAt !== "number" || !Number.isFinite(m.appliedAt)) {
|
|
2170
|
+
fail2("BAD_MANIFEST", "applied manifest appliedAt is invalid");
|
|
2171
|
+
}
|
|
2172
|
+
return {
|
|
2173
|
+
id: m.id,
|
|
2174
|
+
to: m.to,
|
|
2175
|
+
...typeof m.from === "string" && m.from !== "" ? { from: m.from } : {},
|
|
2176
|
+
opId: m.opId,
|
|
2177
|
+
appliedAt: m.appliedAt
|
|
2178
|
+
};
|
|
2179
|
+
}
|
|
2180
|
+
async function readRunManifestRow(fs, manifestPath, entryPath) {
|
|
2181
|
+
let text;
|
|
2182
|
+
try {
|
|
2183
|
+
text = await fs.readFile(manifestPath);
|
|
2184
|
+
} catch {
|
|
2185
|
+
fail2("BAD_MANIFEST", "trash entry has no in-place marker or same-run manifest");
|
|
2186
|
+
}
|
|
2187
|
+
for (const line of text.split(`
|
|
2188
|
+
`)) {
|
|
2189
|
+
if (line === "")
|
|
2190
|
+
continue;
|
|
2191
|
+
let row;
|
|
2192
|
+
try {
|
|
2193
|
+
row = JSON.parse(line);
|
|
2194
|
+
} catch {
|
|
2195
|
+
continue;
|
|
2196
|
+
}
|
|
2197
|
+
if (row === null || typeof row !== "object")
|
|
2198
|
+
continue;
|
|
2199
|
+
const r = row;
|
|
2200
|
+
if (r.phase !== "applied" || r.to !== entryPath)
|
|
2201
|
+
continue;
|
|
2202
|
+
return parseAppliedManifest(line);
|
|
2203
|
+
}
|
|
2204
|
+
fail2("BAD_MANIFEST", "no same-run manifest row matches this trash entry");
|
|
2205
|
+
}
|
|
2206
|
+
async function readAppliedManifest(fs, dir, runManifest) {
|
|
2207
|
+
let text;
|
|
2208
|
+
try {
|
|
2209
|
+
text = await fs.readFile(join4(dir, ".applied.json"));
|
|
2210
|
+
} catch (err) {
|
|
2211
|
+
if (errorCode3(err) === "ENOENT" && runManifest !== undefined)
|
|
2212
|
+
return readRunManifestRow(fs, runManifest, dir);
|
|
2213
|
+
fail2("BAD_MANIFEST", "trash entry has no readable .applied.json");
|
|
2214
|
+
}
|
|
2215
|
+
return parseAppliedManifest(text);
|
|
2216
|
+
}
|
|
2217
|
+
async function probeLockForPurge(lockProbe, lockPath) {
|
|
2218
|
+
if (lockProbe === undefined)
|
|
2219
|
+
fail2("UNSUPPORTED", "lockProbe capability unavailable; purge refuses to assume unlocked");
|
|
2220
|
+
let result;
|
|
2221
|
+
try {
|
|
2222
|
+
result = await lockProbe(lockPath);
|
|
2223
|
+
} catch {
|
|
2224
|
+
fail2("LOCKED", "lock probe threw; refusing to purge");
|
|
2225
|
+
}
|
|
2226
|
+
if (result.status === "lock-held" || result.status === "unknown") {
|
|
2227
|
+
fail2("LOCKED", "session.lock probe is not unlocked", { status: result.status });
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
async function assessTrashEntry(fs, deps, dshHome, run, encoded, liveIds) {
|
|
2231
|
+
if (deps.lockProbe === undefined) {
|
|
2232
|
+
fail2("UNSUPPORTED", "lockProbe capability unavailable; purge refuses to assume unlocked");
|
|
2233
|
+
}
|
|
2234
|
+
if (!RUN_NAME_RE.test(run))
|
|
2235
|
+
fail2("BAD_PATH", "trash run directory name is not a UTC stamp", { run });
|
|
2236
|
+
const entryPath = join4(trashSessionsRoot(dshHome), run, encoded);
|
|
2237
|
+
const st = await fs.lstat(entryPath);
|
|
2238
|
+
if (!st.isDirectory() || st.isSymbolicLink?.() === true) {
|
|
2239
|
+
fail2("BAD_PATH", "trash entry is not a real directory");
|
|
2240
|
+
}
|
|
2241
|
+
const manifest = await readAppliedManifest(fs, entryPath, join4(trashSessionsRoot(dshHome), run, RUN_MANIFEST_FILENAME));
|
|
2242
|
+
if (encodeSegment(manifest.id) !== encoded || basename3(entryPath) !== encoded) {
|
|
2243
|
+
fail2("BAD_MANIFEST", "manifest id does not encode to the entry basename", { id: manifest.id });
|
|
2244
|
+
}
|
|
2245
|
+
const toRel = relative(trashSessionsRoot(dshHome), manifest.to);
|
|
2246
|
+
if (!isAbsolute(manifest.to) || toRel.startsWith("..") || isAbsolute(toRel)) {
|
|
2247
|
+
fail2("BAD_MANIFEST", "applied manifest to escapes the trash sessions root");
|
|
2248
|
+
}
|
|
2249
|
+
const expectedRel = join4(run, encoded);
|
|
2250
|
+
if (toRel !== expectedRel && toRel !== expectedRel.split(sep3).join("/")) {
|
|
2251
|
+
fail2("BAD_MANIFEST", "applied manifest to does not match the scanned entry", { expectedRel });
|
|
2252
|
+
}
|
|
2253
|
+
const trashReal = await fs.realpath(trashSessionsRoot(dshHome));
|
|
2254
|
+
const real = await fs.realpath(entryPath);
|
|
2255
|
+
if (!isInside3(trashReal, real) || relative(trashReal, real) !== expectedRel) {
|
|
2256
|
+
fail2("BAD_PATH", "trash entry realpath escaped the sessions trash root");
|
|
2257
|
+
}
|
|
2258
|
+
const liveState = liveIds.get(manifest.id);
|
|
2259
|
+
if (liveState === "LIVE_AGENT") {
|
|
2260
|
+
fail2("LIVE_AGENT", "purge refused: a live agent still owns this session id", { id: manifest.id });
|
|
2261
|
+
}
|
|
2262
|
+
if (liveState === "CONFLICT") {
|
|
2263
|
+
fail2("CONFLICT", "purge refused: session.id exists outside trash (restore conflict)", { id: manifest.id });
|
|
2264
|
+
}
|
|
2265
|
+
const artifactHeaderId = await readTrashArtifactHeaderId(fs, entryPath);
|
|
2266
|
+
if (artifactHeaderId !== manifest.id) {
|
|
2267
|
+
fail2("BAD_MANIFEST", "trash artifact header.id mismatch", { id: manifest.id, artifactHeaderId });
|
|
2268
|
+
}
|
|
2269
|
+
let liveSnapshot;
|
|
2270
|
+
try {
|
|
2271
|
+
liveSnapshot = await deps.persistence.stat(manifest.id);
|
|
2272
|
+
} catch {
|
|
2273
|
+
liveSnapshot = undefined;
|
|
2274
|
+
}
|
|
2275
|
+
const hintedPath = readLocationPath(liveSnapshot?.location);
|
|
2276
|
+
const originalPath = manifest.from === undefined ? undefined : join4(manifest.from, ARTIFACT_FILENAME);
|
|
2277
|
+
for (const livePath of [hintedPath, originalPath]) {
|
|
2278
|
+
if (livePath === undefined || livePath === entryPath)
|
|
2279
|
+
continue;
|
|
2280
|
+
try {
|
|
2281
|
+
await fs.lstat(livePath);
|
|
2282
|
+
fail2("CONFLICT", "purge refused: live path for this id exists again", { id: manifest.id });
|
|
2283
|
+
} catch (err) {
|
|
2284
|
+
if (err instanceof PurgeError)
|
|
2285
|
+
throw err;
|
|
2286
|
+
if (errorCode3(err) !== "ENOENT")
|
|
2287
|
+
throw err;
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
const ageDays = (deps.now - manifest.appliedAt) / MS_PER_DAY2;
|
|
2291
|
+
if (!Number.isFinite(deps.retentionDays) || deps.retentionDays < 0) {
|
|
2292
|
+
fail2("BAD_PARAMS", "host purge retentionDays is invalid");
|
|
2293
|
+
}
|
|
2294
|
+
if (ageDays < deps.retentionDays) {
|
|
2295
|
+
fail2("FRESH", "trash entry has not served the residence window", { id: manifest.id, ageDays, retentionDays: deps.retentionDays });
|
|
2296
|
+
}
|
|
2297
|
+
await probeLockForPurge(deps.lockProbe, join4(entryPath, "session.lock"));
|
|
2298
|
+
return {
|
|
2299
|
+
id: manifest.id,
|
|
2300
|
+
encoded,
|
|
2301
|
+
run,
|
|
2302
|
+
path: real,
|
|
2303
|
+
appliedAt: manifest.appliedAt,
|
|
2304
|
+
ageDays,
|
|
2305
|
+
manifest
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
async function readLiveIds(deps) {
|
|
2309
|
+
const listing = await listAllSessions(deps.lister);
|
|
2310
|
+
if (listing.truncated)
|
|
2311
|
+
fail2("BLOCKED", "purge aborted: session.list roster is incomplete", { pages: listing.pages });
|
|
2312
|
+
const ids = new Map;
|
|
2313
|
+
for (const row of listing.rows) {
|
|
2314
|
+
const raw = row.sessionId;
|
|
2315
|
+
if (raw === undefined || raw === null)
|
|
2316
|
+
continue;
|
|
2317
|
+
const id = String(raw);
|
|
2318
|
+
if (row.agentAvailable === true) {
|
|
2319
|
+
ids.set(id, "LIVE_AGENT");
|
|
2320
|
+
} else if (!ids.has(id)) {
|
|
2321
|
+
ids.set(id, "CONFLICT");
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
return ids;
|
|
2325
|
+
}
|
|
2326
|
+
async function scanPurgeCandidates(fs, deps, dshHome, liveIds) {
|
|
2327
|
+
const root = trashSessionsRoot(dshHome);
|
|
2328
|
+
let runs;
|
|
2329
|
+
try {
|
|
2330
|
+
runs = await fs.readdir(root);
|
|
2331
|
+
} catch (err) {
|
|
2332
|
+
if (errorCode3(err) === "ENOENT")
|
|
2333
|
+
return { candidates: [], rejected: [] };
|
|
2334
|
+
throw err;
|
|
2335
|
+
}
|
|
2336
|
+
const candidates = [];
|
|
2337
|
+
const rejected = [];
|
|
2338
|
+
for (const run of runs) {
|
|
2339
|
+
let entries;
|
|
2340
|
+
try {
|
|
2341
|
+
entries = await fs.readdir(join4(root, run));
|
|
2342
|
+
} catch (err) {
|
|
2343
|
+
if (errorCode3(err) === "ENOENT")
|
|
2344
|
+
continue;
|
|
2345
|
+
rejected.push({ path: join4(root, run), code: "INTERNAL", message: purgeWireMessage(err) });
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
for (const encoded of entries) {
|
|
2349
|
+
if (encoded.startsWith(".") || encoded === RUN_MANIFEST_FILENAME)
|
|
2350
|
+
continue;
|
|
2351
|
+
try {
|
|
2352
|
+
candidates.push(await assessTrashEntry(fs, deps, dshHome, run, encoded, liveIds));
|
|
2353
|
+
} catch (err) {
|
|
2354
|
+
rejected.push({
|
|
2355
|
+
path: join4(root, run, encoded),
|
|
2356
|
+
code: err instanceof PurgeError ? err.code : "INTERNAL",
|
|
2357
|
+
message: purgeWireMessage(err)
|
|
2358
|
+
});
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
candidates.sort((a, b) => a.id.localeCompare(b.id));
|
|
2363
|
+
return { candidates, rejected };
|
|
2364
|
+
}
|
|
2365
|
+
async function removeNode(fs, path, rootReal) {
|
|
2366
|
+
const st = await fs.lstat(path);
|
|
2367
|
+
if (st.isSymbolicLink?.() === true) {
|
|
2368
|
+
await fs.unlink(path);
|
|
2369
|
+
return;
|
|
2370
|
+
}
|
|
2371
|
+
if (st.isDirectory()) {
|
|
2372
|
+
const real = await fs.realpath(path);
|
|
2373
|
+
if (!isInside3(rootReal, real))
|
|
2374
|
+
fail2("BAD_PATH", "delete target escaped the trash session directory");
|
|
2375
|
+
for (const child of await fs.readdir(path)) {
|
|
2376
|
+
await removeNode(fs, join4(path, child), rootReal);
|
|
2377
|
+
}
|
|
2378
|
+
await fs.rmdir(path);
|
|
2379
|
+
return;
|
|
2380
|
+
}
|
|
2381
|
+
await fs.unlink(path);
|
|
2382
|
+
}
|
|
2383
|
+
async function removeTrashTree(fs, candidate) {
|
|
2384
|
+
const st = await fs.lstat(candidate.path);
|
|
2385
|
+
if (!st.isDirectory() || st.isSymbolicLink?.() === true) {
|
|
2386
|
+
fail2("BAD_PATH", "delete target flipped to symlink/non-directory");
|
|
2387
|
+
}
|
|
2388
|
+
const real = await fs.realpath(candidate.path);
|
|
2389
|
+
if (real !== candidate.path)
|
|
2390
|
+
fail2("BAD_PATH", "delete target realpath changed");
|
|
2391
|
+
await removeNode(fs, candidate.path, real);
|
|
2392
|
+
}
|
|
2393
|
+
function purgeManifestPath(dshHome, opId) {
|
|
2394
|
+
return join4(trashJournalRoot(dshHome), `purge-${opId}.jsonl`);
|
|
2395
|
+
}
|
|
2396
|
+
function usedTokenPath(dshHome, token) {
|
|
2397
|
+
return join4(trashJournalRoot(dshHome), "purge-tokens", `${sha2562(token)}.used`);
|
|
2398
|
+
}
|
|
2399
|
+
async function claimToken(fs, dshHome, token, payload, now) {
|
|
2400
|
+
await fs.mkdir(join4(trashJournalRoot(dshHome), "purge-tokens"), { recursive: true, mode: 448 });
|
|
2401
|
+
try {
|
|
2402
|
+
await fs.writeFile(usedTokenPath(dshHome, token), JSON.stringify({
|
|
2403
|
+
opId: payload.opId,
|
|
2404
|
+
issuedAt: payload.issuedAt,
|
|
2405
|
+
claimedAt: now,
|
|
2406
|
+
tokenHash: sha2562(token)
|
|
2407
|
+
}), { flag: "wx", mode: 384 });
|
|
2408
|
+
} catch (err) {
|
|
2409
|
+
if (errorCode3(err) === "EEXIST")
|
|
2410
|
+
fail2("REPLAY", "purge token already consumed", { opId: payload.opId });
|
|
2411
|
+
throw err;
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
async function appendManifest(fs, dshHome, opId, row) {
|
|
2415
|
+
await fs.appendFile(purgeManifestPath(dshHome, opId), JSON.stringify(row) + `
|
|
2416
|
+
`);
|
|
2417
|
+
}
|
|
2418
|
+
async function purgeRootForToken(fs, dshHome) {
|
|
2419
|
+
const root = trashSessionsRoot(dshHome);
|
|
2420
|
+
try {
|
|
2421
|
+
return await fs.realpath(root);
|
|
2422
|
+
} catch (err) {
|
|
2423
|
+
if (errorCode3(err) === "ENOENT")
|
|
2424
|
+
return root;
|
|
2425
|
+
throw err;
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
async function preparePurge(fs, deps, dshHome) {
|
|
2429
|
+
return deps.withApplyLock(async () => {
|
|
2430
|
+
const liveIds = await readLiveIds(deps);
|
|
2431
|
+
const scan = await scanPurgeCandidates(fs, deps, dshHome, liveIds);
|
|
2432
|
+
const root = await purgeRootForToken(fs, dshHome);
|
|
2433
|
+
const issued = issuePurgeToken({
|
|
2434
|
+
opId: deps.opId,
|
|
2435
|
+
ids: scan.candidates.map((c) => c.id),
|
|
2436
|
+
paths: scan.candidates.map((c) => c.path),
|
|
2437
|
+
root,
|
|
2438
|
+
retentionDays: deps.retentionDays,
|
|
2439
|
+
issuedAt: deps.now,
|
|
2440
|
+
nonce: `${deps.opId}:${deps.newSecret()}`
|
|
2441
|
+
}, deps.secret, deps.tokenTtlMs);
|
|
2442
|
+
return {
|
|
2443
|
+
opId: deps.opId,
|
|
2444
|
+
candidates: scan.candidates,
|
|
2445
|
+
rejected: scan.rejected,
|
|
2446
|
+
token: issued.token,
|
|
2447
|
+
tokenPayload: issued.payload
|
|
2448
|
+
};
|
|
2449
|
+
});
|
|
2450
|
+
}
|
|
2451
|
+
async function purgeTrashSessions(fs, deps, dshHome, token) {
|
|
2452
|
+
return deps.withApplyLock(async () => {
|
|
2453
|
+
const payload = verifyPurgeToken(token, deps.secret, deps.now);
|
|
2454
|
+
if (payload.v !== 1)
|
|
2455
|
+
fail2("BAD_TOKEN", "unsupported purge token version");
|
|
2456
|
+
const liveIds = await readLiveIds(deps);
|
|
2457
|
+
const scan = await scanPurgeCandidates(fs, deps, dshHome, liveIds);
|
|
2458
|
+
const root = await purgeRootForToken(fs, dshHome);
|
|
2459
|
+
if (root !== payload.root || payload.retentionDays !== deps.retentionDays) {
|
|
2460
|
+
fail2("STALE_TOKEN", "host trash root or retention policy changed since prepare", {
|
|
2461
|
+
retentionDays: deps.retentionDays
|
|
2462
|
+
});
|
|
2463
|
+
}
|
|
2464
|
+
const byId = new Map(scan.candidates.map((c) => [c.id, c]));
|
|
2465
|
+
const rejectedByPath = new Map(scan.rejected.map((r) => [r.path, r]));
|
|
2466
|
+
await claimToken(fs, dshHome, String(token), payload, deps.now);
|
|
2467
|
+
const purged = [];
|
|
2468
|
+
const failed = [];
|
|
2469
|
+
const manifestPath = purgeManifestPath(dshHome, payload.opId);
|
|
2470
|
+
for (let i = 0;i < payload.ids.length; i++) {
|
|
2471
|
+
const id = payload.ids[i];
|
|
2472
|
+
const tokenPath = payload.paths[i];
|
|
2473
|
+
const candidate = byId.get(id);
|
|
2474
|
+
if (candidate === undefined || candidate.path !== tokenPath) {
|
|
2475
|
+
const rejection = rejectedByPath.get(tokenPath);
|
|
2476
|
+
failed.push({
|
|
2477
|
+
id,
|
|
2478
|
+
path: tokenPath,
|
|
2479
|
+
code: rejection?.code ?? "STALE_TOKEN",
|
|
2480
|
+
message: rejection?.message ?? "candidate disappeared or moved after token verification"
|
|
2481
|
+
});
|
|
2482
|
+
continue;
|
|
2483
|
+
}
|
|
2484
|
+
try {
|
|
2485
|
+
const fresh = await assessTrashEntry(fs, deps, dshHome, candidate.run, candidate.encoded, liveIds);
|
|
2486
|
+
if (fresh.path !== tokenPath)
|
|
2487
|
+
fail2("STALE_TOKEN", "candidate realpath moved after token verification", { id });
|
|
2488
|
+
await appendManifest(fs, dshHome, payload.opId, {
|
|
2489
|
+
phase: "intent",
|
|
2490
|
+
opId: payload.opId,
|
|
2491
|
+
id: fresh.id,
|
|
2492
|
+
path: fresh.path,
|
|
2493
|
+
at: deps.now,
|
|
2494
|
+
tokenHash: sha2562(String(token))
|
|
2495
|
+
});
|
|
2496
|
+
await removeTrashTree(fs, fresh);
|
|
2497
|
+
await appendManifest(fs, dshHome, payload.opId, {
|
|
2498
|
+
phase: "done",
|
|
2499
|
+
opId: payload.opId,
|
|
2500
|
+
id: fresh.id,
|
|
2501
|
+
path: fresh.path,
|
|
2502
|
+
at: deps.now
|
|
2503
|
+
});
|
|
2504
|
+
purged.push({ id: fresh.id, path: fresh.path });
|
|
2505
|
+
} catch (err) {
|
|
2506
|
+
failed.push({
|
|
2507
|
+
id: candidate.id,
|
|
2508
|
+
path: candidate.path,
|
|
2509
|
+
code: err instanceof PurgeError ? err.code : "DELETE_FAILED",
|
|
2510
|
+
message: purgeWireMessage(err)
|
|
2511
|
+
});
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
return { opId: payload.opId, purged, failed, manifestPath };
|
|
2515
|
+
});
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
// ../bridge/src/session-prune-restore.ts
|
|
2519
|
+
import { basename as basename4, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, sep as sep4 } from "node:path";
|
|
2520
|
+
import { zstdDecompressSync as nodeZstdDecompressSync2 } from "node:zlib";
|
|
2521
|
+
var RUN_NAME_RE2 = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;
|
|
2522
|
+
var ARTIFACT_FILENAME2 = "session.v4.jsonl.zstd";
|
|
2523
|
+
var APPLIED_MARKER = ".applied.json";
|
|
2524
|
+
var RUN_MANIFEST_FILENAME2 = "manifest.jsonl";
|
|
2525
|
+
function runManifestPath(dshHome, run) {
|
|
2526
|
+
return join5(trashSessionsRoot(dshHome), run, RUN_MANIFEST_FILENAME2);
|
|
2527
|
+
}
|
|
2528
|
+
function restoredMarkerPath(dshHome, opId, encoded) {
|
|
2529
|
+
return join5(trashJournalRoot(dshHome), `${opId}-${encoded}.restored.json`);
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
class RestoreError extends Error {
|
|
2533
|
+
code;
|
|
2534
|
+
detail;
|
|
2535
|
+
constructor(code, message, detail) {
|
|
2536
|
+
super(message);
|
|
2537
|
+
this.name = "RestoreError";
|
|
2538
|
+
this.code = code;
|
|
2539
|
+
this.detail = detail;
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
function fail3(code, message, detail) {
|
|
2543
|
+
throw new RestoreError(code, message, detail);
|
|
2544
|
+
}
|
|
2545
|
+
function errorCode4(err) {
|
|
2546
|
+
if (err === null || typeof err !== "object")
|
|
2547
|
+
return;
|
|
2548
|
+
const code = err.code;
|
|
2549
|
+
return typeof code === "string" ? code : undefined;
|
|
2550
|
+
}
|
|
2551
|
+
function isEnoent2(err) {
|
|
2552
|
+
return errorCode4(err) === "ENOENT";
|
|
2553
|
+
}
|
|
2554
|
+
function isInside4(root, target) {
|
|
2555
|
+
const base = root.length > 1 && root.endsWith(sep4) ? root.slice(0, -1) : root;
|
|
2556
|
+
return target === base || target.startsWith(base.endsWith(sep4) ? base : base + sep4);
|
|
2557
|
+
}
|
|
2558
|
+
function sameDev2(a, b) {
|
|
2559
|
+
return a !== undefined && b !== undefined && String(a) === String(b);
|
|
2560
|
+
}
|
|
2561
|
+
var FS_MSG = {
|
|
2562
|
+
vanished: "trash entry is no longer available",
|
|
2563
|
+
unreadable: "trash entry could not be read",
|
|
2564
|
+
pathUnreadable: "path could not be resolved",
|
|
2565
|
+
statUnavailable: "path metadata is unavailable",
|
|
2566
|
+
rootUnreadable: "sessions root could not be resolved",
|
|
2567
|
+
destinationUnreadable: "live destination could not be resolved"
|
|
2568
|
+
};
|
|
2569
|
+
async function lstatGuest(fs, path) {
|
|
2570
|
+
try {
|
|
2571
|
+
return await fs.lstat(path);
|
|
868
2572
|
} catch (err) {
|
|
869
|
-
|
|
870
|
-
return NOOP;
|
|
2573
|
+
fail3(isEnoent2(err) ? "NOT_FOUND" : "BAD_PATH", isEnoent2(err) ? FS_MSG.vanished : FS_MSG.unreadable);
|
|
871
2574
|
}
|
|
872
|
-
if (typeof disposer !== "function")
|
|
873
|
-
disposer = NOOP;
|
|
874
|
-
let disposed = false;
|
|
875
|
-
const cleanup = () => {
|
|
876
|
-
if (disposed)
|
|
877
|
-
return;
|
|
878
|
-
disposed = true;
|
|
879
|
-
try {
|
|
880
|
-
disposer?.();
|
|
881
|
-
} catch {}
|
|
882
|
-
};
|
|
883
|
-
ctx.effect(() => cleanup, EFFECT_LABEL);
|
|
884
|
-
return cleanup;
|
|
885
2575
|
}
|
|
886
|
-
function
|
|
2576
|
+
async function realpathGuest(fs, path) {
|
|
887
2577
|
try {
|
|
888
|
-
|
|
889
|
-
} catch {
|
|
2578
|
+
return await fs.realpath(path);
|
|
2579
|
+
} catch (err) {
|
|
2580
|
+
fail3(isEnoent2(err) ? "NOT_FOUND" : "BAD_PATH", isEnoent2(err) ? FS_MSG.vanished : FS_MSG.pathUnreadable);
|
|
2581
|
+
}
|
|
890
2582
|
}
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
if (Array.isArray(value))
|
|
897
|
-
return value.some(presetMentionsAppend);
|
|
898
|
-
if (value !== null && typeof value === "object") {
|
|
899
|
-
return Object.values(value).some(presetMentionsAppend);
|
|
2583
|
+
async function statGuest(fs, path) {
|
|
2584
|
+
try {
|
|
2585
|
+
return await fs.stat(path);
|
|
2586
|
+
} catch (err) {
|
|
2587
|
+
fail3(isEnoent2(err) ? "NOT_FOUND" : "BAD_PATH", isEnoent2(err) ? FS_MSG.vanished : FS_MSG.statUnavailable);
|
|
900
2588
|
}
|
|
901
|
-
return false;
|
|
902
2589
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
2590
|
+
function zstdDecompress2(frame) {
|
|
2591
|
+
const bun = globalThis.Bun;
|
|
2592
|
+
if (bun?.zstdDecompressSync !== undefined)
|
|
2593
|
+
return bun.zstdDecompressSync(frame);
|
|
2594
|
+
return nodeZstdDecompressSync2(frame);
|
|
2595
|
+
}
|
|
2596
|
+
async function readTrashArtifactHeaderId2(fs, dir) {
|
|
2597
|
+
const artifact = join5(dir, ARTIFACT_FILENAME2);
|
|
2598
|
+
let frame;
|
|
907
2599
|
try {
|
|
908
|
-
|
|
909
|
-
|
|
2600
|
+
frame = await fs.readFileBuffer(artifact);
|
|
2601
|
+
} catch (err) {
|
|
2602
|
+
fail3("BAD_MANIFEST", "trash entry has no readable session artifact", { code: errorCode4(err) });
|
|
2603
|
+
}
|
|
2604
|
+
if (frame.length === 0)
|
|
2605
|
+
fail3("BAD_MANIFEST", "trash session artifact is empty");
|
|
2606
|
+
let text;
|
|
2607
|
+
try {
|
|
2608
|
+
text = zstdDecompress2(frame).toString("utf8");
|
|
910
2609
|
} catch {
|
|
911
|
-
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
2610
|
+
fail3("BAD_MANIFEST", "trash session artifact is not a valid zstd frame");
|
|
2611
|
+
}
|
|
2612
|
+
const firstLine = text.split(`
|
|
2613
|
+
`, 1)[0] ?? "";
|
|
2614
|
+
let header;
|
|
2615
|
+
try {
|
|
2616
|
+
header = JSON.parse(firstLine);
|
|
2617
|
+
} catch {
|
|
2618
|
+
fail3("BAD_MANIFEST", "trash session artifact header is not JSON");
|
|
918
2619
|
}
|
|
2620
|
+
if (header === null || typeof header !== "object")
|
|
2621
|
+
fail3("BAD_MANIFEST", "trash session artifact header is not an object");
|
|
2622
|
+
const id = header.id;
|
|
2623
|
+
if (typeof id !== "string" || id === "")
|
|
2624
|
+
fail3("BAD_MANIFEST", "trash artifact header.id is missing");
|
|
2625
|
+
return id;
|
|
919
2626
|
}
|
|
920
|
-
function
|
|
921
|
-
|
|
2627
|
+
function parseAppliedManifest2(text) {
|
|
2628
|
+
let raw;
|
|
2629
|
+
try {
|
|
2630
|
+
raw = JSON.parse(text);
|
|
2631
|
+
} catch {
|
|
2632
|
+
fail3("BAD_MANIFEST", "trash entry .applied.json is not JSON");
|
|
2633
|
+
}
|
|
2634
|
+
if (raw === null || typeof raw !== "object")
|
|
2635
|
+
fail3("BAD_MANIFEST", "trash entry .applied.json is not an object");
|
|
2636
|
+
const m = raw;
|
|
2637
|
+
if (typeof m.id !== "string" || m.id === "")
|
|
2638
|
+
fail3("BAD_MANIFEST", "applied manifest id is missing");
|
|
2639
|
+
if (typeof m.to !== "string" || m.to === "")
|
|
2640
|
+
fail3("BAD_MANIFEST", "applied manifest to is missing");
|
|
2641
|
+
if (typeof m.appliedAt !== "number" || !Number.isFinite(m.appliedAt))
|
|
2642
|
+
fail3("BAD_MANIFEST", "applied manifest appliedAt is invalid");
|
|
2643
|
+
return {
|
|
2644
|
+
id: m.id,
|
|
2645
|
+
to: m.to,
|
|
2646
|
+
...typeof m.from === "string" && m.from !== "" ? { from: m.from } : {},
|
|
2647
|
+
appliedAt: m.appliedAt
|
|
2648
|
+
};
|
|
922
2649
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
this.rows.clear();
|
|
930
|
-
this.built = false;
|
|
931
|
-
}
|
|
932
|
-
syncFromList(items) {
|
|
933
|
-
const next = new Map;
|
|
934
|
-
let subagentCount = 0;
|
|
935
|
-
for (const row of items) {
|
|
936
|
-
if (row === null || typeof row !== "object")
|
|
937
|
-
continue;
|
|
938
|
-
if (row.origin !== "subagent")
|
|
939
|
-
continue;
|
|
940
|
-
if (typeof row.sessionId !== "string" || row.sessionId === "")
|
|
941
|
-
continue;
|
|
942
|
-
subagentCount += 1;
|
|
943
|
-
next.set(row.sessionId, {
|
|
944
|
-
parentSessionId: typeof row.parentSessionId === "string" ? row.parentSessionId : "",
|
|
945
|
-
startedAt: typeof row.updatedAt === "number" ? row.updatedAt : 0,
|
|
946
|
-
status: row.running === true ? "running" : "settled"
|
|
947
|
-
});
|
|
948
|
-
}
|
|
949
|
-
for (const [childId, cached] of this.rows) {
|
|
950
|
-
if (!next.has(childId))
|
|
951
|
-
next.set(childId, cached);
|
|
952
|
-
}
|
|
953
|
-
this.rows.clear();
|
|
954
|
-
for (const [childId, row] of next)
|
|
955
|
-
this.rows.set(childId, row);
|
|
956
|
-
this.built = true;
|
|
957
|
-
return subagentCount;
|
|
2650
|
+
async function readRunManifestRow2(fs, manifestPath, entryPath) {
|
|
2651
|
+
let text;
|
|
2652
|
+
try {
|
|
2653
|
+
text = await fs.readFile(manifestPath);
|
|
2654
|
+
} catch {
|
|
2655
|
+
fail3("BAD_MANIFEST", "trash entry has no in-place marker or same-run manifest");
|
|
958
2656
|
}
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
2657
|
+
for (const line of text.split(`
|
|
2658
|
+
`)) {
|
|
2659
|
+
if (line === "")
|
|
2660
|
+
continue;
|
|
2661
|
+
let row;
|
|
2662
|
+
try {
|
|
2663
|
+
row = JSON.parse(line);
|
|
2664
|
+
} catch {
|
|
2665
|
+
continue;
|
|
967
2666
|
}
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
2667
|
+
if (row === null || typeof row !== "object")
|
|
2668
|
+
continue;
|
|
2669
|
+
const r = row;
|
|
2670
|
+
if (r.phase !== "applied" || r.to !== entryPath)
|
|
2671
|
+
continue;
|
|
2672
|
+
return parseAppliedManifest2(line);
|
|
973
2673
|
}
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
if (
|
|
982
|
-
|
|
2674
|
+
fail3("BAD_MANIFEST", "no same-run manifest row matches this trash entry");
|
|
2675
|
+
}
|
|
2676
|
+
async function readAppliedManifest2(fs, dir, runManifest) {
|
|
2677
|
+
let text;
|
|
2678
|
+
try {
|
|
2679
|
+
text = await fs.readFile(join5(dir, APPLIED_MARKER));
|
|
2680
|
+
} catch (err) {
|
|
2681
|
+
if (isEnoent2(err) && runManifest !== undefined)
|
|
2682
|
+
return readRunManifestRow2(fs, runManifest, dir);
|
|
2683
|
+
fail3("BAD_MANIFEST", "trash entry has no readable .applied.json", { code: errorCode4(err) });
|
|
983
2684
|
}
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
2685
|
+
return parseAppliedManifest2(text);
|
|
2686
|
+
}
|
|
2687
|
+
async function probeLockForRestore(lockProbe, lockPath) {
|
|
2688
|
+
if (lockProbe === undefined)
|
|
2689
|
+
fail3("UNSUPPORTED", "lockProbe capability unavailable; restore refuses to assume unlocked");
|
|
2690
|
+
let result;
|
|
2691
|
+
try {
|
|
2692
|
+
result = await lockProbe(lockPath);
|
|
2693
|
+
} catch {
|
|
2694
|
+
fail3("LOCKED", "lock probe threw; refusing to restore");
|
|
990
2695
|
}
|
|
991
|
-
|
|
992
|
-
|
|
2696
|
+
if (result.status === "lock-held" || result.status === "unknown") {
|
|
2697
|
+
fail3("LOCKED", "session.lock probe is not unlocked", { status: result.status });
|
|
993
2698
|
}
|
|
994
|
-
|
|
995
|
-
|
|
2699
|
+
}
|
|
2700
|
+
async function pathExists2(fs, path) {
|
|
2701
|
+
try {
|
|
2702
|
+
await fs.lstat(path);
|
|
2703
|
+
return true;
|
|
2704
|
+
} catch (err) {
|
|
2705
|
+
if (isEnoent2(err))
|
|
2706
|
+
return false;
|
|
2707
|
+
fail3("BAD_PATH", FS_MSG.unreadable);
|
|
996
2708
|
}
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
2709
|
+
}
|
|
2710
|
+
async function assessEntry(fs, dshHome, run, encoded) {
|
|
2711
|
+
if (!RUN_NAME_RE2.test(run))
|
|
2712
|
+
fail3("BAD_PATH", "trash run directory name is not a UTC stamp");
|
|
2713
|
+
const entryPath = join5(trashSessionsRoot(dshHome), run, encoded);
|
|
2714
|
+
const st = await lstatGuest(fs, entryPath);
|
|
2715
|
+
if (!st.isDirectory() || st.isSymbolicLink?.() === true)
|
|
2716
|
+
fail3("BAD_PATH", "trash entry is not a real directory");
|
|
2717
|
+
const manifest = await readAppliedManifest2(fs, entryPath, runManifestPath(dshHome, run));
|
|
2718
|
+
if (encodeSegment(manifest.id) !== encoded || basename4(entryPath) !== encoded) {
|
|
2719
|
+
fail3("BAD_MANIFEST", "manifest id does not encode to the entry basename");
|
|
2720
|
+
}
|
|
2721
|
+
const toRel = relative2(trashSessionsRoot(dshHome), manifest.to);
|
|
2722
|
+
const expectedRel = join5(run, encoded);
|
|
2723
|
+
if (!isAbsolute2(manifest.to) || toRel.startsWith("..") || isAbsolute2(toRel)) {
|
|
2724
|
+
fail3("BAD_MANIFEST", "applied manifest to escapes the trash sessions root");
|
|
2725
|
+
}
|
|
2726
|
+
if (toRel !== expectedRel && toRel !== expectedRel.split(sep4).join("/")) {
|
|
2727
|
+
fail3("BAD_MANIFEST", "applied manifest to does not match the scanned entry");
|
|
2728
|
+
}
|
|
2729
|
+
const trashReal = await realpathGuest(fs, trashSessionsRoot(dshHome));
|
|
2730
|
+
const real = await realpathGuest(fs, entryPath);
|
|
2731
|
+
if (!isInside4(trashReal, real) || relative2(trashReal, real) !== expectedRel) {
|
|
2732
|
+
fail3("BAD_PATH", "trash entry realpath escaped the sessions trash root");
|
|
2733
|
+
}
|
|
2734
|
+
const headerId = await readTrashArtifactHeaderId2(fs, entryPath);
|
|
2735
|
+
if (headerId !== manifest.id)
|
|
2736
|
+
fail3("BAD_MANIFEST", "trash artifact header.id mismatch");
|
|
2737
|
+
return { id: manifest.id, run, encoded, path: entryPath, manifest };
|
|
2738
|
+
}
|
|
2739
|
+
async function listRestoreEntries(fs, dshHome) {
|
|
2740
|
+
const root = trashSessionsRoot(dshHome);
|
|
2741
|
+
let runs;
|
|
2742
|
+
try {
|
|
2743
|
+
runs = await fs.readdir(root);
|
|
2744
|
+
} catch (err) {
|
|
2745
|
+
if (isEnoent2(err))
|
|
2746
|
+
return { entries: [], rejected: [] };
|
|
2747
|
+
fail3("BAD_PATH", FS_MSG.rootUnreadable);
|
|
2748
|
+
}
|
|
2749
|
+
const entries = [];
|
|
2750
|
+
const rejected = [];
|
|
2751
|
+
for (const run of runs) {
|
|
2752
|
+
let leaves;
|
|
2753
|
+
try {
|
|
2754
|
+
leaves = await fs.readdir(join5(root, run));
|
|
2755
|
+
} catch (err) {
|
|
2756
|
+
if (isEnoent2(err))
|
|
2757
|
+
continue;
|
|
2758
|
+
rejected.push({ code: "INTERNAL", message: "cannot read a trash run directory" });
|
|
2759
|
+
continue;
|
|
2760
|
+
}
|
|
2761
|
+
for (const encoded of leaves) {
|
|
2762
|
+
if (encoded.startsWith(".") || encoded === RUN_MANIFEST_FILENAME2)
|
|
2763
|
+
continue;
|
|
2764
|
+
try {
|
|
2765
|
+
const scanned = await assessEntry(fs, dshHome, run, encoded);
|
|
2766
|
+
let size;
|
|
2767
|
+
try {
|
|
2768
|
+
const artifactStat = await fs.stat(join5(scanned.path, ARTIFACT_FILENAME2));
|
|
2769
|
+
if (typeof artifactStat.size === "number" && Number.isFinite(artifactStat.size))
|
|
2770
|
+
size = artifactStat.size;
|
|
2771
|
+
} catch {}
|
|
2772
|
+
entries.push({
|
|
2773
|
+
id: scanned.id,
|
|
2774
|
+
movedAt: scanned.manifest.appliedAt,
|
|
2775
|
+
...size !== undefined ? { size } : {}
|
|
2776
|
+
});
|
|
2777
|
+
} catch (err) {
|
|
2778
|
+
if (err instanceof RestoreError && err.code === "NOT_FOUND")
|
|
2779
|
+
continue;
|
|
2780
|
+
rejected.push({
|
|
2781
|
+
code: err instanceof RestoreError ? err.code : "INTERNAL",
|
|
2782
|
+
message: err instanceof RestoreError ? err.message : "trash entry could not be assessed"
|
|
2783
|
+
});
|
|
1002
2784
|
}
|
|
1003
2785
|
}
|
|
1004
|
-
return out;
|
|
1005
2786
|
}
|
|
2787
|
+
entries.sort((a, b) => b.movedAt - a.movedAt || a.id.localeCompare(b.id));
|
|
2788
|
+
return { entries, rejected };
|
|
1006
2789
|
}
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
2790
|
+
async function readLiveIds2(lister) {
|
|
2791
|
+
const listing = await listAllSessions(lister);
|
|
2792
|
+
if (listing.truncated)
|
|
2793
|
+
fail3("BLOCKED", "restore aborted: session.list roster is incomplete", { pages: listing.pages });
|
|
2794
|
+
const ids = new Map;
|
|
2795
|
+
for (const row of listing.rows) {
|
|
2796
|
+
const raw = row.sessionId;
|
|
2797
|
+
if (raw === undefined || raw === null)
|
|
2798
|
+
continue;
|
|
2799
|
+
const id = String(raw);
|
|
2800
|
+
if (row.agentAvailable === true)
|
|
2801
|
+
ids.set(id, "LIVE_AGENT");
|
|
2802
|
+
else if (!ids.has(id))
|
|
2803
|
+
ids.set(id, "CONFLICT");
|
|
1013
2804
|
}
|
|
1014
|
-
return
|
|
2805
|
+
return ids;
|
|
2806
|
+
}
|
|
2807
|
+
async function liveDestination(fs, deps, scanned, rootReal) {
|
|
2808
|
+
let destination;
|
|
2809
|
+
const from = scanned.manifest.from;
|
|
2810
|
+
if (typeof from === "string" && from !== "" && isAbsolute2(from)) {
|
|
2811
|
+
const rel = relative2(deps.sessionsRoot, from);
|
|
2812
|
+
if (rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel))
|
|
2813
|
+
destination = from;
|
|
2814
|
+
}
|
|
2815
|
+
if (destination === undefined) {
|
|
2816
|
+
let snapshot;
|
|
2817
|
+
try {
|
|
2818
|
+
snapshot = await deps.persistence.stat(scanned.id);
|
|
2819
|
+
} catch {
|
|
2820
|
+
snapshot = undefined;
|
|
2821
|
+
}
|
|
2822
|
+
const location = snapshot?.location;
|
|
2823
|
+
const path = typeof location === "string" ? location : location !== null && typeof location === "object" && typeof location.path === "string" ? location.path : undefined;
|
|
2824
|
+
if (path !== undefined && path !== "" && isAbsolute2(path)) {
|
|
2825
|
+
const candidate = dirname3(path);
|
|
2826
|
+
const rel = relative2(deps.sessionsRoot, candidate);
|
|
2827
|
+
if (rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel))
|
|
2828
|
+
destination = candidate;
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
if (destination === undefined)
|
|
2832
|
+
fail3("BAD_PATH", "restore refused: no host-derived live destination");
|
|
2833
|
+
const dir = basename4(destination);
|
|
2834
|
+
if (dir !== encodeSegment(scanned.id))
|
|
2835
|
+
fail3("BAD_PATH", "restore refused: live destination basename mismatch");
|
|
2836
|
+
if (await pathExists2(fs, destination))
|
|
2837
|
+
fail3("CONFLICT", "restore refused: live destination already exists");
|
|
2838
|
+
const parent = join5(destination, "..");
|
|
2839
|
+
const parentReal = await realpathGuest(fs, parent);
|
|
2840
|
+
if (!isInside4(rootReal, parentReal))
|
|
2841
|
+
fail3("BAD_PATH", "restore refused: live destination escaped sessions root");
|
|
2842
|
+
return destination;
|
|
2843
|
+
}
|
|
2844
|
+
async function restoreTrashEntry(fs, deps, dshHome, id) {
|
|
2845
|
+
if (typeof id !== "string" || id === "")
|
|
2846
|
+
fail3("BAD_PARAMS", "session.prune.restore requires a non-empty id");
|
|
2847
|
+
return deps.withApplyLock(async () => {
|
|
2848
|
+
const liveIds = await readLiveIds2(deps.lister);
|
|
2849
|
+
const live = liveIds.get(id);
|
|
2850
|
+
if (live === "LIVE_AGENT")
|
|
2851
|
+
fail3("LIVE_AGENT", "restore refused: a live agent still owns this session id");
|
|
2852
|
+
if (live === "CONFLICT")
|
|
2853
|
+
fail3("CONFLICT", "restore refused: session id already exists outside trash");
|
|
2854
|
+
const rootReal = await realpathGuest(fs, deps.sessionsRoot);
|
|
2855
|
+
const root = trashSessionsRoot(dshHome);
|
|
2856
|
+
let runs;
|
|
2857
|
+
try {
|
|
2858
|
+
runs = await fs.readdir(root);
|
|
2859
|
+
} catch (err) {
|
|
2860
|
+
if (isEnoent2(err))
|
|
2861
|
+
fail3("NOT_FOUND", "restore refused: no such trash entry");
|
|
2862
|
+
fail3("BAD_PATH", FS_MSG.rootUnreadable);
|
|
2863
|
+
}
|
|
2864
|
+
const matches = [];
|
|
2865
|
+
for (const run of runs) {
|
|
2866
|
+
let leaves;
|
|
2867
|
+
try {
|
|
2868
|
+
leaves = await fs.readdir(join5(root, run));
|
|
2869
|
+
} catch (err) {
|
|
2870
|
+
if (isEnoent2(err))
|
|
2871
|
+
continue;
|
|
2872
|
+
fail3("BAD_PATH", FS_MSG.rootUnreadable);
|
|
2873
|
+
}
|
|
2874
|
+
for (const encoded of leaves) {
|
|
2875
|
+
if (encoded.startsWith(".") || encoded === RUN_MANIFEST_FILENAME2)
|
|
2876
|
+
continue;
|
|
2877
|
+
try {
|
|
2878
|
+
const scanned = await assessEntry(fs, dshHome, run, encoded);
|
|
2879
|
+
if (scanned.id === id)
|
|
2880
|
+
matches.push(scanned);
|
|
2881
|
+
} catch (err) {
|
|
2882
|
+
if (err instanceof RestoreError)
|
|
2883
|
+
continue;
|
|
2884
|
+
fail3("INTERNAL", "trash entry could not be assessed");
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
if (matches.length === 0)
|
|
2889
|
+
fail3("NOT_FOUND", "restore refused: no such trash entry");
|
|
2890
|
+
if (matches.length > 1)
|
|
2891
|
+
fail3("CONFLICT", "restore refused: duplicate trash entries for this id");
|
|
2892
|
+
const scanned = matches[0];
|
|
2893
|
+
const destination = await liveDestination(fs, deps, scanned, rootReal);
|
|
2894
|
+
const trashStat = await statGuest(fs, scanned.path);
|
|
2895
|
+
const parentStat = await statGuest(fs, join5(destination, ".."));
|
|
2896
|
+
if (!sameDev2(trashStat.dev, parentStat.dev))
|
|
2897
|
+
fail3("EXDEV", "restore refused: cross-device rename");
|
|
2898
|
+
const recheckSt = await lstatGuest(fs, scanned.path);
|
|
2899
|
+
if (!recheckSt.isDirectory() || recheckSt.isSymbolicLink?.() === true) {
|
|
2900
|
+
fail3("BAD_PATH", "restore refused: trash entry flipped to symlink/non-directory");
|
|
2901
|
+
}
|
|
2902
|
+
if (await pathExists2(fs, destination))
|
|
2903
|
+
fail3("CONFLICT", "restore refused: live destination already exists");
|
|
2904
|
+
await probeLockForRestore(deps.lockProbe, join5(scanned.path, "session.lock"));
|
|
2905
|
+
const markerPath = join5(scanned.path, APPLIED_MARKER);
|
|
2906
|
+
if (await pathExists2(fs, markerPath)) {
|
|
2907
|
+
const retiredPath = restoredMarkerPath(dshHome, deps.opId, scanned.encoded);
|
|
2908
|
+
if (await pathExists2(fs, retiredPath)) {
|
|
2909
|
+
fail3("RESTORE_FAILED", "restore refused: retired marker journal already exists");
|
|
2910
|
+
}
|
|
2911
|
+
try {
|
|
2912
|
+
await fs.rename(markerPath, retiredPath);
|
|
2913
|
+
} catch {
|
|
2914
|
+
fail3("RESTORE_FAILED", "restore refused: could not retire the applied marker");
|
|
2915
|
+
}
|
|
2916
|
+
if (await pathExists2(fs, markerPath)) {
|
|
2917
|
+
fail3("RESTORE_FAILED", "restore refused: applied marker still present after retirement");
|
|
2918
|
+
}
|
|
2919
|
+
}
|
|
2920
|
+
try {
|
|
2921
|
+
await fs.rename(scanned.path, destination);
|
|
2922
|
+
} catch (err) {
|
|
2923
|
+
if (errorCode4(err) === "EXDEV")
|
|
2924
|
+
fail3("EXDEV", "restore refused: cross-device rename");
|
|
2925
|
+
fail3("RESTORE_FAILED", "restore rename failed", { code: errorCode4(err) });
|
|
2926
|
+
}
|
|
2927
|
+
return { id, restored: true, opId: deps.opId };
|
|
2928
|
+
});
|
|
1015
2929
|
}
|
|
1016
2930
|
|
|
1017
2931
|
// ../bridge/src/settings-adapter.ts
|
|
@@ -1194,75 +3108,103 @@ var ledger_default = {
|
|
|
1194
3108
|
},
|
|
1195
3109
|
wired_protocol: {
|
|
1196
3110
|
mark: "bridge-protocol (ADR-0010)",
|
|
1197
|
-
count:
|
|
3111
|
+
count: 14,
|
|
1198
3112
|
methods: [
|
|
1199
3113
|
{
|
|
1200
3114
|
method: "bridge.ping",
|
|
1201
3115
|
kind: "meta",
|
|
1202
|
-
source_line:
|
|
3116
|
+
source_line: 5682,
|
|
1203
3117
|
capir_id: null,
|
|
1204
3118
|
note: "protocol version negotiation (no host call)"
|
|
1205
3119
|
},
|
|
1206
3120
|
{
|
|
1207
3121
|
method: "bridge.hello",
|
|
1208
3122
|
kind: "meta",
|
|
1209
|
-
source_line:
|
|
3123
|
+
source_line: 5691,
|
|
1210
3124
|
capir_id: null,
|
|
1211
3125
|
note: "protocol version negotiation (no host call)"
|
|
1212
3126
|
},
|
|
3127
|
+
{
|
|
3128
|
+
method: "session.prune.plan",
|
|
3129
|
+
kind: "business",
|
|
3130
|
+
source_line: 5725,
|
|
3131
|
+
capir_id: null,
|
|
3132
|
+
note: "retention P1 read-only dry run: session.list drain + sessionPersistence.stat locations + read-only path gates; no CapIR id, no host write, no deletion"
|
|
3133
|
+
},
|
|
3134
|
+
{
|
|
3135
|
+
method: "session.prune.apply",
|
|
3136
|
+
kind: "business",
|
|
3137
|
+
source_line: 5731,
|
|
3138
|
+
capir_id: null,
|
|
3139
|
+
note: "retention P2 host-recomputed trash apply: fingerprint/max-age/config checks + host-side apply lock + rename-to-trash with rollback/journal; client entries/policy rejected; no CapIR id"
|
|
3140
|
+
},
|
|
3141
|
+
{
|
|
3142
|
+
method: "session.prune.purge",
|
|
3143
|
+
kind: "business",
|
|
3144
|
+
source_line: 5737,
|
|
3145
|
+
capir_id: null,
|
|
3146
|
+
note: "retention P3 trash-only deletion: server-issued single-use HMAC token + host re-validation of trash realpath/header/manifest/residence + full gate re-probe (live agent, live path, flock) + recursive delete with per-entry failure and crash manifest; client path/policy rejected; no CapIR id"
|
|
3147
|
+
},
|
|
3148
|
+
{
|
|
3149
|
+
method: "session.prune.restore",
|
|
3150
|
+
kind: "business",
|
|
3151
|
+
source_line: 5743,
|
|
3152
|
+
capir_id: null,
|
|
3153
|
+
note: "retention B4/C7 trash restore by entry id: read-only list of {id,movedAt,size?} (no path) + host re-validation of trash realpath/manifest/artifact header.id/live roster/live destination containment + refuse-if-exists + read-only flock probe + reverse rename; client path/policy rejected; no CapIR id"
|
|
3154
|
+
},
|
|
1213
3155
|
{
|
|
1214
3156
|
method: "subagents.interrupt",
|
|
1215
3157
|
kind: "business",
|
|
1216
|
-
source_line:
|
|
3158
|
+
source_line: 5810,
|
|
1217
3159
|
capir_id: null,
|
|
1218
3160
|
note: "L1 0.23.1 added; subagent authorization gate (binding ownership) + index reconcile + per-child cancel"
|
|
1219
3161
|
},
|
|
1220
3162
|
{
|
|
1221
3163
|
method: "subagents.stopChildren",
|
|
1222
3164
|
kind: "business",
|
|
1223
|
-
source_line:
|
|
3165
|
+
source_line: 5814,
|
|
1224
3166
|
capir_id: null,
|
|
1225
3167
|
note: "L1 0.23.1 added; subagent authorization gate (binding ownership) + index reconcile + per-child cancel"
|
|
1226
3168
|
},
|
|
1227
3169
|
{
|
|
1228
3170
|
method: "session.open",
|
|
1229
3171
|
kind: "business",
|
|
1230
|
-
source_line:
|
|
3172
|
+
source_line: 5818,
|
|
1231
3173
|
capir_id: null,
|
|
1232
3174
|
note: "binding orchestration (agents.create/resume + push relay/grants); multi-step, stateful"
|
|
1233
3175
|
},
|
|
1234
3176
|
{
|
|
1235
3177
|
method: "session.send",
|
|
1236
3178
|
kind: "business",
|
|
1237
|
-
source_line:
|
|
3179
|
+
source_line: 5822,
|
|
1238
3180
|
capir_id: null,
|
|
1239
3181
|
note: "single in-flight turn state machine + streaming turn"
|
|
1240
3182
|
},
|
|
1241
3183
|
{
|
|
1242
3184
|
method: "session.close",
|
|
1243
3185
|
kind: "business",
|
|
1244
|
-
source_line:
|
|
3186
|
+
source_line: 5826,
|
|
1245
3187
|
capir_id: null,
|
|
1246
3188
|
note: "binding dispose"
|
|
1247
3189
|
},
|
|
1248
3190
|
{
|
|
1249
3191
|
method: "turn.abort",
|
|
1250
3192
|
kind: "business",
|
|
1251
|
-
source_line:
|
|
3193
|
+
source_line: 5830,
|
|
1252
3194
|
capir_id: null,
|
|
1253
3195
|
note: "turn state machine + terminalTurnIds FIFO idempotency + fire-and-forget agent.cancel"
|
|
1254
3196
|
},
|
|
1255
3197
|
{
|
|
1256
3198
|
method: "ask.response",
|
|
1257
3199
|
kind: "business",
|
|
1258
|
-
source_line:
|
|
3200
|
+
source_line: 5834,
|
|
1259
3201
|
capir_id: null,
|
|
1260
3202
|
note: "bridge-internal AskRegistry settlement (no host call)"
|
|
1261
3203
|
},
|
|
1262
3204
|
{
|
|
1263
3205
|
method: "journal.replay",
|
|
1264
3206
|
kind: "business",
|
|
1265
|
-
source_line:
|
|
3207
|
+
source_line: 5838,
|
|
1266
3208
|
capir_id: null,
|
|
1267
3209
|
note: "I-class persistence read (persistence.open(id,'read')); no same-name CapIR id"
|
|
1268
3210
|
}
|
|
@@ -7683,14 +9625,14 @@ var BRIDGE_CAPABILITIES = ["subagents.interrupt", "subagents.stopChildren"];
|
|
|
7683
9625
|
var TERMINAL_TURN_ID_LIMIT = 64;
|
|
7684
9626
|
function findPackageVersion(entryFile, wantedName) {
|
|
7685
9627
|
try {
|
|
7686
|
-
let dir =
|
|
7687
|
-
for (let i = 0;i < 12 && dir !==
|
|
9628
|
+
let dir = dirname4(realpathSync2(entryFile));
|
|
9629
|
+
for (let i = 0;i < 12 && dir !== dirname4(dir); i++) {
|
|
7688
9630
|
try {
|
|
7689
|
-
const pkg = JSON.parse(readFileSync2(
|
|
9631
|
+
const pkg = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
|
|
7690
9632
|
if (pkg?.name === wantedName && typeof pkg.version === "string")
|
|
7691
9633
|
return pkg.version;
|
|
7692
9634
|
} catch {}
|
|
7693
|
-
dir =
|
|
9635
|
+
dir = dirname4(dir);
|
|
7694
9636
|
}
|
|
7695
9637
|
} catch {}
|
|
7696
9638
|
return;
|
|
@@ -7711,7 +9653,7 @@ function readHostVersion() {
|
|
|
7711
9653
|
return v;
|
|
7712
9654
|
}
|
|
7713
9655
|
try {
|
|
7714
|
-
const req =
|
|
9656
|
+
const req = createRequire2(import.meta.url);
|
|
7715
9657
|
const path = req.resolve("@deepseek-ai/dsh/package.json");
|
|
7716
9658
|
const pkg = JSON.parse(readFileSync2(path, "utf8"));
|
|
7717
9659
|
if (typeof pkg.version === "string")
|
|
@@ -7724,15 +9666,127 @@ function resolveAgents(ctx) {
|
|
|
7724
9666
|
const svc = fromGet ?? ctx.agents;
|
|
7725
9667
|
return svc !== undefined && typeof svc.create === "function" ? svc : undefined;
|
|
7726
9668
|
}
|
|
7727
|
-
function resolveDefaultModel(ctx) {
|
|
7728
|
-
const fromGet = typeof ctx.get === "function" ? ctx.get("agentDefaultModel") : undefined;
|
|
7729
|
-
const svc = fromGet ?? ctx.agentDefaultModel;
|
|
7730
|
-
return svc !== undefined && typeof svc.currentSelection === "function" ? svc : undefined;
|
|
9669
|
+
function resolveDefaultModel(ctx) {
|
|
9670
|
+
const fromGet = typeof ctx.get === "function" ? ctx.get("agentDefaultModel") : undefined;
|
|
9671
|
+
const svc = fromGet ?? ctx.agentDefaultModel;
|
|
9672
|
+
return svc !== undefined && typeof svc.currentSelection === "function" ? svc : undefined;
|
|
9673
|
+
}
|
|
9674
|
+
function resolvePersistence(ctx) {
|
|
9675
|
+
const fromGet = typeof ctx.get === "function" ? ctx.get("sessionPersistence") : undefined;
|
|
9676
|
+
const svc = fromGet ?? ctx.sessionPersistence;
|
|
9677
|
+
return svc !== undefined && typeof svc.open === "function" ? svc : undefined;
|
|
9678
|
+
}
|
|
9679
|
+
function resolvePrunePersistence(ctx) {
|
|
9680
|
+
const base = resolvePersistence(ctx);
|
|
9681
|
+
return base !== undefined && hasStatCapability(base) ? base : undefined;
|
|
9682
|
+
}
|
|
9683
|
+
function resolvePruneSessionsRoot(ctx, config) {
|
|
9684
|
+
const fromConfig = config !== null && typeof config === "object" ? config : {};
|
|
9685
|
+
if (typeof fromConfig.sessionsRoot === "string" && fromConfig.sessionsRoot !== "")
|
|
9686
|
+
return fromConfig.sessionsRoot;
|
|
9687
|
+
if (typeof fromConfig.dshHome === "string" && fromConfig.dshHome !== "")
|
|
9688
|
+
return join6(fromConfig.dshHome, "sessions");
|
|
9689
|
+
try {
|
|
9690
|
+
const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
|
|
9691
|
+
if (hostConfig !== null && typeof hostConfig === "object") {
|
|
9692
|
+
const hc = hostConfig;
|
|
9693
|
+
if (typeof hc.sessionsRoot === "string" && hc.sessionsRoot !== "")
|
|
9694
|
+
return hc.sessionsRoot;
|
|
9695
|
+
if (typeof hc.dshHome === "string" && hc.dshHome !== "")
|
|
9696
|
+
return join6(hc.dshHome, "sessions");
|
|
9697
|
+
}
|
|
9698
|
+
} catch {}
|
|
9699
|
+
return join6(process.env.DSH_HOME || join6(homedir2(), ".dsh"), "sessions");
|
|
9700
|
+
}
|
|
9701
|
+
function resolvePruneDshHome(ctx, config) {
|
|
9702
|
+
const fromConfig = config !== null && typeof config === "object" ? config : {};
|
|
9703
|
+
if (typeof fromConfig.dshHome === "string" && fromConfig.dshHome !== "")
|
|
9704
|
+
return fromConfig.dshHome;
|
|
9705
|
+
try {
|
|
9706
|
+
const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
|
|
9707
|
+
if (hostConfig !== null && typeof hostConfig === "object") {
|
|
9708
|
+
const hc = hostConfig;
|
|
9709
|
+
if (typeof hc.dshHome === "string" && hc.dshHome !== "")
|
|
9710
|
+
return hc.dshHome;
|
|
9711
|
+
}
|
|
9712
|
+
} catch {}
|
|
9713
|
+
return process.env.DSH_HOME || join6(homedir2(), ".dsh");
|
|
9714
|
+
}
|
|
9715
|
+
function resolveHostProfileConfig(ctx) {
|
|
9716
|
+
try {
|
|
9717
|
+
const profile = typeof ctx.get === "function" ? ctx.get("profileContext") : undefined;
|
|
9718
|
+
const dir = profile !== null && typeof profile === "object" ? profile.dir : undefined;
|
|
9719
|
+
if (typeof dir !== "string" || dir === "")
|
|
9720
|
+
return;
|
|
9721
|
+
const parsed = JSON.parse(readFileSync2(join6(dir, "config.json"), "utf8"));
|
|
9722
|
+
return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
|
|
9723
|
+
} catch {
|
|
9724
|
+
return;
|
|
9725
|
+
}
|
|
9726
|
+
}
|
|
9727
|
+
function resolveHostPrunePolicy(ctx, config, sessionsRoot) {
|
|
9728
|
+
const fromConfig = config !== null && typeof config === "object" ? config : {};
|
|
9729
|
+
const hostConfig = (() => {
|
|
9730
|
+
try {
|
|
9731
|
+
const value = typeof ctx.get === "function" ? ctx.get("config") : undefined;
|
|
9732
|
+
return value !== null && typeof value === "object" ? value : {};
|
|
9733
|
+
} catch {
|
|
9734
|
+
return {};
|
|
9735
|
+
}
|
|
9736
|
+
})();
|
|
9737
|
+
const profileConfig = resolveHostProfileConfig(ctx);
|
|
9738
|
+
const numberFrom = (key, fallback, min, max) => {
|
|
9739
|
+
for (const source of [profileConfig, hostConfig, fromConfig]) {
|
|
9740
|
+
if (source === undefined)
|
|
9741
|
+
continue;
|
|
9742
|
+
const value = source[key];
|
|
9743
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max)
|
|
9744
|
+
return value;
|
|
9745
|
+
}
|
|
9746
|
+
return fallback;
|
|
9747
|
+
};
|
|
9748
|
+
const retentionDays = numberFrom("retentionDays", DEFAULT_RETENTION_DAYS, 0, 3650);
|
|
9749
|
+
const blankGraceDays = numberFrom("blankGraceDays", 30, 0, 3650);
|
|
9750
|
+
const lockGraceMs = numberFrom("lockGraceMs", 300000, 0, 86400000);
|
|
9751
|
+
const freshMtimeGraceMs = numberFrom("freshMtimeGraceMs", lockGraceMs, 0, 86400000);
|
|
9752
|
+
return { retentionDays, blankGraceDays, lockGraceMs, freshMtimeGraceMs, sessionsRoot };
|
|
9753
|
+
}
|
|
9754
|
+
function resolveHostPurgePolicy(ctx, config) {
|
|
9755
|
+
const fromConfig = config !== null && typeof config === "object" ? config : {};
|
|
9756
|
+
const hostConfig = (() => {
|
|
9757
|
+
try {
|
|
9758
|
+
const value = typeof ctx.get === "function" ? ctx.get("config") : undefined;
|
|
9759
|
+
return value !== null && typeof value === "object" ? value : {};
|
|
9760
|
+
} catch {
|
|
9761
|
+
return {};
|
|
9762
|
+
}
|
|
9763
|
+
})();
|
|
9764
|
+
const numberFrom = (key, fallback, min, max) => {
|
|
9765
|
+
for (const source of [fromConfig, hostConfig]) {
|
|
9766
|
+
const value = source[key];
|
|
9767
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max)
|
|
9768
|
+
return value;
|
|
9769
|
+
}
|
|
9770
|
+
return fallback;
|
|
9771
|
+
};
|
|
9772
|
+
return {
|
|
9773
|
+
retentionDays: numberFrom("purgeRetentionDays", DEFAULT_PURGE_RETENTION_DAYS, 0, 3650),
|
|
9774
|
+
tokenTtlMs: numberFrom("purgeTokenTtlMs", 120000, 1, 86400000)
|
|
9775
|
+
};
|
|
7731
9776
|
}
|
|
7732
|
-
function
|
|
7733
|
-
const
|
|
7734
|
-
|
|
7735
|
-
|
|
9777
|
+
async function withHostApplyLock(dshHome, tryLockExclusive, fn) {
|
|
9778
|
+
const root = trashRoot(dshHome);
|
|
9779
|
+
await mkdir(root, { recursive: true, mode: 448 });
|
|
9780
|
+
const path = join6(root, ".apply.lock");
|
|
9781
|
+
const handle = await open2(path, "w", 384);
|
|
9782
|
+
try {
|
|
9783
|
+
await tryLockExclusive(handle.fd);
|
|
9784
|
+
return await fn();
|
|
9785
|
+
} finally {
|
|
9786
|
+
try {
|
|
9787
|
+
await handle.close();
|
|
9788
|
+
} catch {}
|
|
9789
|
+
}
|
|
7736
9790
|
}
|
|
7737
9791
|
var cachedAppendPluginRecord;
|
|
7738
9792
|
var appendPluginRecordResolved = false;
|
|
@@ -7743,12 +9797,12 @@ function resolveAppendPluginRecord() {
|
|
|
7743
9797
|
const roots = [import.meta.url];
|
|
7744
9798
|
if (process.argv[1]) {
|
|
7745
9799
|
try {
|
|
7746
|
-
roots.push(
|
|
9800
|
+
roots.push(realpathSync2(process.argv[1]));
|
|
7747
9801
|
} catch {}
|
|
7748
9802
|
}
|
|
7749
9803
|
for (const root of roots) {
|
|
7750
9804
|
try {
|
|
7751
|
-
const req =
|
|
9805
|
+
const req = createRequire2(root);
|
|
7752
9806
|
const mod = req("@deepseek-ai/dsh-session");
|
|
7753
9807
|
if (typeof mod.appendPluginRecord === "function") {
|
|
7754
9808
|
cachedAppendPluginRecord = mod.appendPluginRecord;
|
|
@@ -7951,10 +10005,23 @@ function resolveAskDeadlineMs(raw, maxAskWaitMs = DEFAULT_MAX_ASK_WAIT_MS, warn
|
|
|
7951
10005
|
}
|
|
7952
10006
|
return raw;
|
|
7953
10007
|
}
|
|
10008
|
+
function resolveMaxAskWaitMs(raw, cap = DEFAULT_MAX_ASK_WAIT_MS, warn = () => {}) {
|
|
10009
|
+
if (raw === undefined || raw === null)
|
|
10010
|
+
return cap;
|
|
10011
|
+
if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > cap) {
|
|
10012
|
+
warn("[dsh-opentui-bridge] invalid maxAskWaitMs %s ignored (using hard cap %d)", String(raw), cap);
|
|
10013
|
+
return cap;
|
|
10014
|
+
}
|
|
10015
|
+
return raw;
|
|
10016
|
+
}
|
|
7954
10017
|
var agentProgressResidues = new WeakMap;
|
|
7955
10018
|
function probeAgentProgressResidue(ctx) {
|
|
7956
10019
|
return agentProgressResidues.get(ctx)?.();
|
|
7957
10020
|
}
|
|
10021
|
+
var agentTranscriptResidues = new WeakMap;
|
|
10022
|
+
function probeAgentTranscriptResidue(ctx) {
|
|
10023
|
+
return agentTranscriptResidues.get(ctx)?.();
|
|
10024
|
+
}
|
|
7958
10025
|
function apply(ctx, config) {
|
|
7959
10026
|
const logger = ctx.logger;
|
|
7960
10027
|
if (process.env[STDIO_SWITCH] !== "1") {
|
|
@@ -8373,6 +10440,7 @@ function apply(ctx, config) {
|
|
|
8373
10440
|
childProgress: childProgress.size,
|
|
8374
10441
|
progressSentFp: progressSentFp.size
|
|
8375
10442
|
}));
|
|
10443
|
+
agentTranscriptResidues.set(ctx, () => ({ childTranscripts: childTranscripts.size }));
|
|
8376
10444
|
function flushProgress(childId) {
|
|
8377
10445
|
const snap = progressPending.get(childId);
|
|
8378
10446
|
if (snap === undefined)
|
|
@@ -8416,6 +10484,80 @@ function apply(ctx, config) {
|
|
|
8416
10484
|
progressPending.clear();
|
|
8417
10485
|
progressSentFp.clear();
|
|
8418
10486
|
childProgress.clear();
|
|
10487
|
+
clearTranscriptState();
|
|
10488
|
+
}
|
|
10489
|
+
const childTranscripts = new Map;
|
|
10490
|
+
const MAX_PENDING_TOOL_CALLS = 64;
|
|
10491
|
+
const childTranscriptRunIds = new Map;
|
|
10492
|
+
function transcriptTurnId() {
|
|
10493
|
+
return inFlightTurnId ?? "";
|
|
10494
|
+
}
|
|
10495
|
+
function childTranscriptRunId(childId) {
|
|
10496
|
+
const fromSpawn = childTranscriptRunIds.get(childId);
|
|
10497
|
+
if (fromSpawn !== undefined && fromSpawn !== "")
|
|
10498
|
+
return fromSpawn;
|
|
10499
|
+
const indexed = getSubagentIndex(ctx).get(childId);
|
|
10500
|
+
return indexed !== undefined && indexed.startedAt > 0 ? `child@${indexed.startedAt}` : "";
|
|
10501
|
+
}
|
|
10502
|
+
function childTranscriptState(childId) {
|
|
10503
|
+
let st = childTranscripts.get(childId);
|
|
10504
|
+
const turnId = transcriptTurnId();
|
|
10505
|
+
if (st === undefined || st.turnId !== turnId) {
|
|
10506
|
+
st = { turnId, seq: 0, pending: [], toolCalls: new Map };
|
|
10507
|
+
childTranscripts.set(childId, st);
|
|
10508
|
+
}
|
|
10509
|
+
return st;
|
|
10510
|
+
}
|
|
10511
|
+
function flushTranscript(childId) {
|
|
10512
|
+
const st = childTranscripts.get(childId);
|
|
10513
|
+
if (st === undefined || st.pending.length === 0 || binding === undefined)
|
|
10514
|
+
return;
|
|
10515
|
+
const rows = st.pending.splice(0);
|
|
10516
|
+
emitEvent("agent.transcript", {
|
|
10517
|
+
turnId: st.turnId,
|
|
10518
|
+
sessionId: binding.sessionId,
|
|
10519
|
+
childId,
|
|
10520
|
+
runId: childTranscriptRunId(childId),
|
|
10521
|
+
seq: st.seq,
|
|
10522
|
+
rows
|
|
10523
|
+
});
|
|
10524
|
+
st.seq += 1;
|
|
10525
|
+
}
|
|
10526
|
+
function flushTranscriptNow(childId) {
|
|
10527
|
+
flushTranscript(childId);
|
|
10528
|
+
const st = childTranscripts.get(childId);
|
|
10529
|
+
if (st !== undefined)
|
|
10530
|
+
st.toolCalls.clear();
|
|
10531
|
+
}
|
|
10532
|
+
function flushAllTranscript() {
|
|
10533
|
+
for (const childId of [...childTranscripts.keys()])
|
|
10534
|
+
flushTranscriptNow(childId);
|
|
10535
|
+
}
|
|
10536
|
+
function clearTranscriptState() {
|
|
10537
|
+
childTranscripts.clear();
|
|
10538
|
+
childTranscriptRunIds.clear();
|
|
10539
|
+
}
|
|
10540
|
+
function clearChildTranscript(childId) {
|
|
10541
|
+
childTranscripts.delete(childId);
|
|
10542
|
+
}
|
|
10543
|
+
function noteChildTranscriptRow(childId, row) {
|
|
10544
|
+
if (binding === undefined || childId === "" || childId === binding.sessionId)
|
|
10545
|
+
return;
|
|
10546
|
+
const indexed = getSubagentIndex(ctx).get(childId);
|
|
10547
|
+
if (indexed === undefined || indexed.parentSessionId !== binding.sessionId || indexed.status === "settled")
|
|
10548
|
+
return;
|
|
10549
|
+
const st = childTranscriptState(childId);
|
|
10550
|
+
st.pending.push(row);
|
|
10551
|
+
flushTranscript(childId);
|
|
10552
|
+
}
|
|
10553
|
+
function assistantMessageText(data) {
|
|
10554
|
+
const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
|
|
10555
|
+
const content = message?.content ?? data.content ?? message?.text ?? data.text;
|
|
10556
|
+
if (typeof content === "string")
|
|
10557
|
+
return content;
|
|
10558
|
+
if (Array.isArray(content))
|
|
10559
|
+
return contentText(content);
|
|
10560
|
+
return "";
|
|
8419
10561
|
}
|
|
8420
10562
|
function noteChildProgress(childId, roundsDelta, textDelta, lastLineOverride) {
|
|
8421
10563
|
if (binding === undefined || childId === "" || childId === binding.sessionId)
|
|
@@ -8481,6 +10623,16 @@ function apply(ctx, config) {
|
|
|
8481
10623
|
return last.slice(0, 80);
|
|
8482
10624
|
}
|
|
8483
10625
|
const pendingAnswerers = new Map;
|
|
10626
|
+
const approvalGateListeners = new Map;
|
|
10627
|
+
function clearApprovalGate(eventId) {
|
|
10628
|
+
const dispose = approvalGateListeners.get(eventId);
|
|
10629
|
+
if (dispose === undefined)
|
|
10630
|
+
return;
|
|
10631
|
+
approvalGateListeners.delete(eventId);
|
|
10632
|
+
try {
|
|
10633
|
+
dispose();
|
|
10634
|
+
} catch {}
|
|
10635
|
+
}
|
|
8484
10636
|
function settleAnswerer(eventId, settlement) {
|
|
8485
10637
|
const pending = pendingAnswerers.get(eventId);
|
|
8486
10638
|
if (pending === undefined)
|
|
@@ -8492,18 +10644,24 @@ function apply(ctx, config) {
|
|
|
8492
10644
|
return new Promise((resolve) => {
|
|
8493
10645
|
const pending = { resolve };
|
|
8494
10646
|
pendingAnswerers.set(eventId, pending);
|
|
10647
|
+
const original = pending.resolve;
|
|
10648
|
+
let onAbort;
|
|
10649
|
+
pending.resolve = (settlement) => {
|
|
10650
|
+
if (signal !== undefined && onAbort !== undefined) {
|
|
10651
|
+
signal.removeEventListener("abort", onAbort);
|
|
10652
|
+
}
|
|
10653
|
+
clearApprovalGate(eventId);
|
|
10654
|
+
original(settlement);
|
|
10655
|
+
};
|
|
8495
10656
|
if (signal !== undefined) {
|
|
8496
|
-
|
|
10657
|
+
onAbort = () => {
|
|
10658
|
+
ask.settleExternal(eventId, { settleReason: "aborted" });
|
|
8497
10659
|
settleAnswerer(eventId, { outcome: "cancelled" });
|
|
8498
|
-
}
|
|
8499
|
-
|
|
8500
|
-
|
|
8501
|
-
|
|
8502
|
-
signal.removeEventListener("abort", onAbort);
|
|
8503
|
-
original(settlement);
|
|
8504
|
-
};
|
|
10660
|
+
};
|
|
10661
|
+
if (signal.aborted)
|
|
10662
|
+
onAbort();
|
|
10663
|
+
else
|
|
8505
10664
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
8506
|
-
}
|
|
8507
10665
|
}
|
|
8508
10666
|
});
|
|
8509
10667
|
}
|
|
@@ -8525,21 +10683,27 @@ function apply(ctx, config) {
|
|
|
8525
10683
|
logger.warn("[dsh-opentui-bridge] ask journal append failed (decision unchanged): %s", err);
|
|
8526
10684
|
}
|
|
8527
10685
|
}
|
|
8528
|
-
const
|
|
8529
|
-
const
|
|
10686
|
+
const configObject = config !== null && typeof config === "object" ? config : undefined;
|
|
10687
|
+
const maxAskWaitMs = resolveMaxAskWaitMs(configObject?.maxAskWaitMs, DEFAULT_MAX_ASK_WAIT_MS, (fmt, ...params) => logger.warn(fmt, ...params));
|
|
10688
|
+
const askDeadlineMsRaw = configObject?.askDeadlineMs;
|
|
10689
|
+
const askDeadlineMs = resolveAskDeadlineMs(askDeadlineMsRaw, maxAskWaitMs, (fmt, ...params) => logger.warn(fmt, ...params));
|
|
8530
10690
|
const ask = new AskRegistry({
|
|
8531
10691
|
askDeadlineMs,
|
|
10692
|
+
maxAskWaitMs,
|
|
8532
10693
|
logger,
|
|
8533
10694
|
journal: writeAskJournal,
|
|
8534
10695
|
sink: (frame) => {
|
|
8535
|
-
|
|
8536
|
-
|
|
8537
|
-
|
|
8538
|
-
|
|
8539
|
-
|
|
8540
|
-
|
|
8541
|
-
|
|
8542
|
-
|
|
10696
|
+
try {
|
|
10697
|
+
emitEvent(frame.type, frame.payload);
|
|
10698
|
+
} finally {
|
|
10699
|
+
if (frame.type === ASK_FRAME_TYPES.SETTLED) {
|
|
10700
|
+
const settled = frame.payload;
|
|
10701
|
+
const pending = pendingAnswerers.get(settled.eventId);
|
|
10702
|
+
settleAnswerer(settled.eventId, {
|
|
10703
|
+
outcome: settled.outcome,
|
|
10704
|
+
...pending?.params !== undefined ? { params: pending.params } : {}
|
|
10705
|
+
});
|
|
10706
|
+
}
|
|
8543
10707
|
}
|
|
8544
10708
|
}
|
|
8545
10709
|
});
|
|
@@ -8778,6 +10942,7 @@ function apply(ctx, config) {
|
|
|
8778
10942
|
if (!childId)
|
|
8779
10943
|
return;
|
|
8780
10944
|
getSubagentIndex(ctx).noteCatalog(childId, sessionId, typeof data.childCreatedAt === "number" ? data.childCreatedAt : undefined);
|
|
10945
|
+
childTranscriptRunIds.set(childId, `catalog:${childId}@${typeof data.childCreatedAt === "number" ? data.childCreatedAt : ""}`);
|
|
8781
10946
|
syncChildApprovalPolicy(childId, sessionId);
|
|
8782
10947
|
const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
|
|
8783
10948
|
const label = typeof data.label === "string" && data.label !== "" ? data.label : typeof data.name === "string" ? data.name : "";
|
|
@@ -8803,6 +10968,7 @@ function apply(ctx, config) {
|
|
|
8803
10968
|
const childId = idString(data.childId);
|
|
8804
10969
|
if (!childId)
|
|
8805
10970
|
return;
|
|
10971
|
+
childTranscriptRunIds.set(childId, idString(data.runId));
|
|
8806
10972
|
emitEvent("agent.spawn", {
|
|
8807
10973
|
turnId,
|
|
8808
10974
|
sessionId: boundId,
|
|
@@ -8813,6 +10979,7 @@ function apply(ctx, config) {
|
|
|
8813
10979
|
});
|
|
8814
10980
|
} else {
|
|
8815
10981
|
flushAllProgress();
|
|
10982
|
+
flushAllTranscript();
|
|
8816
10983
|
emitEvent("agent.settle", {
|
|
8817
10984
|
turnId,
|
|
8818
10985
|
sessionId: boundId,
|
|
@@ -8825,6 +10992,44 @@ function apply(ctx, config) {
|
|
|
8825
10992
|
}
|
|
8826
10993
|
if (type === "assistant/message" && binding !== undefined && sessionId !== binding.sessionId) {
|
|
8827
10994
|
noteChildProgress(sessionId, 1, "", assistantMessageLastLine(data));
|
|
10995
|
+
const text = assistantMessageText(data);
|
|
10996
|
+
if (text !== "")
|
|
10997
|
+
noteChildTranscriptRow(sessionId, { kind: "assistant", text });
|
|
10998
|
+
}
|
|
10999
|
+
if (binding !== undefined && sessionId !== binding.sessionId) {
|
|
11000
|
+
if (type === "tool/call") {
|
|
11001
|
+
const callId = idString(data.callId);
|
|
11002
|
+
if (callId !== "undefined" && callId !== "") {
|
|
11003
|
+
const indexed = getSubagentIndex(ctx).get(sessionId);
|
|
11004
|
+
if (indexed !== undefined && indexed.parentSessionId === binding.sessionId && indexed.status !== "settled") {
|
|
11005
|
+
const st = childTranscriptState(sessionId);
|
|
11006
|
+
const name = typeof data.name === "string" ? data.name : "";
|
|
11007
|
+
if (!st.toolCalls.has(callId) && st.toolCalls.size >= MAX_PENDING_TOOL_CALLS) {
|
|
11008
|
+
const oldest = st.toolCalls.keys().next().value;
|
|
11009
|
+
if (oldest !== undefined)
|
|
11010
|
+
st.toolCalls.delete(oldest);
|
|
11011
|
+
}
|
|
11012
|
+
st.toolCalls.set(callId, name);
|
|
11013
|
+
}
|
|
11014
|
+
}
|
|
11015
|
+
} else if (type === "tool/result") {
|
|
11016
|
+
const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
|
|
11017
|
+
const callId = idString(message?.toolCallId);
|
|
11018
|
+
if (callId !== "undefined" && callId !== "") {
|
|
11019
|
+
const indexed = getSubagentIndex(ctx).get(sessionId);
|
|
11020
|
+
if (indexed !== undefined && indexed.parentSessionId === binding.sessionId && indexed.status !== "settled") {
|
|
11021
|
+
const state = childTranscripts.get(sessionId);
|
|
11022
|
+
const name = state?.toolCalls.get(callId) ?? "";
|
|
11023
|
+
state?.toolCalls.delete(callId);
|
|
11024
|
+
if (name !== "")
|
|
11025
|
+
noteChildTranscriptRow(sessionId, {
|
|
11026
|
+
kind: "tool",
|
|
11027
|
+
text: name,
|
|
11028
|
+
...contentText(message?.content) !== "" ? { output: contentText(message?.content) } : {}
|
|
11029
|
+
});
|
|
11030
|
+
}
|
|
11031
|
+
}
|
|
11032
|
+
}
|
|
8828
11033
|
}
|
|
8829
11034
|
if (type === "turn/end") {
|
|
8830
11035
|
const index = getSubagentIndex(ctx);
|
|
@@ -8833,8 +11038,10 @@ function apply(ctx, config) {
|
|
|
8833
11038
|
const boundId = binding?.sessionId;
|
|
8834
11039
|
const shouldSettle = row.status === "running" && boundId !== undefined && row.parentSessionId === boundId;
|
|
8835
11040
|
flushProgressNow(sessionId);
|
|
11041
|
+
flushTranscriptNow(sessionId);
|
|
8836
11042
|
index.noteSettled(sessionId, typeof data.seq === "number" ? data.seq : undefined);
|
|
8837
11043
|
clearChildProgress(sessionId);
|
|
11044
|
+
clearChildTranscript(sessionId);
|
|
8838
11045
|
if (shouldSettle) {
|
|
8839
11046
|
const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
|
|
8840
11047
|
emitEvent("agent.settle", {
|
|
@@ -8961,28 +11168,57 @@ function apply(ctx, config) {
|
|
|
8961
11168
|
return { turn: state, sessionId: binding.sessionId, childSessionId: agentSessionId };
|
|
8962
11169
|
}
|
|
8963
11170
|
const FAIL_CLOSED_UNKNOWN_SESSION = "unknown";
|
|
8964
|
-
function failClosedAsk(kind, turnId, sessionId, reason) {
|
|
8965
|
-
const result = ask.failClosed({
|
|
11171
|
+
function failClosedAsk(kind, turnId, sessionId, reason, meta = {}) {
|
|
11172
|
+
const result = ask.failClosed({
|
|
11173
|
+
turnId,
|
|
11174
|
+
sessionId,
|
|
11175
|
+
kind,
|
|
11176
|
+
reason,
|
|
11177
|
+
...meta.toolName !== undefined ? { toolName: meta.toolName } : {},
|
|
11178
|
+
...meta.callId !== undefined ? { callId: meta.callId } : {},
|
|
11179
|
+
...meta.childSessionId !== undefined ? { childSessionId: meta.childSessionId } : {}
|
|
11180
|
+
});
|
|
8966
11181
|
logger.warn("[dsh-opentui-bridge] ask fail-closed kind=%s session=%s eventId=%s code=%s reason=%s", kind, sessionId, result.settlement.eventId, result.code, reason);
|
|
8967
11182
|
}
|
|
11183
|
+
function armApprovalGate(eventId, expiry) {
|
|
11184
|
+
if (expiry === undefined || !pendingAnswerers.has(eventId))
|
|
11185
|
+
return;
|
|
11186
|
+
const signal = expiry.signal;
|
|
11187
|
+
if (signal === undefined || typeof signal.addEventListener !== "function")
|
|
11188
|
+
return;
|
|
11189
|
+
const defaultOutcome = expiry.defaultOutcome === "unavailable" ? "unavailable" : "rejected";
|
|
11190
|
+
const onGateAbort = () => {
|
|
11191
|
+
ask.settleExternal(eventId, { settleReason: "timeout", defaultOutcome });
|
|
11192
|
+
};
|
|
11193
|
+
if (signal.aborted) {
|
|
11194
|
+
onGateAbort();
|
|
11195
|
+
return;
|
|
11196
|
+
}
|
|
11197
|
+
signal.addEventListener("abort", onGateAbort, { once: true });
|
|
11198
|
+
approvalGateListeners.set(eventId, () => signal.removeEventListener("abort", onGateAbort));
|
|
11199
|
+
}
|
|
8968
11200
|
async function onApprovalRequest(raw, _next) {
|
|
8969
11201
|
const req = raw !== null && typeof raw === "object" ? raw : {};
|
|
11202
|
+
const toolName = typeof req.toolName === "string" && req.toolName !== "" ? req.toolName : undefined;
|
|
11203
|
+
const callId = req.callId === undefined ? undefined : idString(req.callId);
|
|
8970
11204
|
const target = askTarget(req.agent);
|
|
8971
11205
|
if (target === undefined) {
|
|
8972
|
-
failClosedAsk("approval", "no-turn", binding?.sessionId ?? FAIL_CLOSED_UNKNOWN_SESSION, "no open in-flight turn to deliver an approval ask"
|
|
11206
|
+
failClosedAsk("approval", "no-turn", binding?.sessionId ?? FAIL_CLOSED_UNKNOWN_SESSION, "no open in-flight turn to deliver an approval ask", {
|
|
11207
|
+
...toolName !== undefined ? { toolName } : {},
|
|
11208
|
+
...callId !== undefined ? { callId } : {}
|
|
11209
|
+
});
|
|
8973
11210
|
return "unavailable";
|
|
8974
11211
|
}
|
|
8975
|
-
const toolName = typeof req.toolName === "string" && req.toolName !== "" ? req.toolName : undefined;
|
|
8976
11212
|
if (toolName !== undefined && ask.hasGrant(target.sessionId, toolName)) {
|
|
8977
11213
|
const grantedEventId = ask.recordSummaryDecision(target.turn.turnId, {
|
|
8978
11214
|
sessionId: target.sessionId,
|
|
8979
11215
|
askKind: "approval",
|
|
8980
|
-
toolName
|
|
11216
|
+
toolName,
|
|
11217
|
+
...target.childSessionId !== undefined ? { childSessionId: target.childSessionId } : {}
|
|
8981
11218
|
});
|
|
8982
11219
|
logger.info("[dsh-opentui-bridge] ask always-grant from session summary: session=%s tool=%s eventId=%s (no card)", target.sessionId, toolName, grantedEventId);
|
|
8983
11220
|
return "allowed-once";
|
|
8984
11221
|
}
|
|
8985
|
-
const callId = req.callId === undefined ? undefined : idString(req.callId);
|
|
8986
11222
|
const reason = typeof req.reason === "string" && req.reason !== "" ? req.reason : undefined;
|
|
8987
11223
|
let request;
|
|
8988
11224
|
try {
|
|
@@ -8997,10 +11233,16 @@ function apply(ctx, config) {
|
|
|
8997
11233
|
});
|
|
8998
11234
|
} catch (err) {
|
|
8999
11235
|
logger.error("[dsh-opentui-bridge] ask.create(approval) failed: %s", err);
|
|
9000
|
-
failClosedAsk("approval", target.turn.turnId, target.sessionId, "ask.create(approval) threw"
|
|
11236
|
+
failClosedAsk("approval", target.turn.turnId, target.sessionId, "ask.create(approval) threw", {
|
|
11237
|
+
...toolName !== undefined ? { toolName } : {},
|
|
11238
|
+
...callId !== undefined ? { callId } : {},
|
|
11239
|
+
...target.childSessionId !== undefined ? { childSessionId: target.childSessionId } : {}
|
|
11240
|
+
});
|
|
9001
11241
|
return "unavailable";
|
|
9002
11242
|
}
|
|
9003
|
-
const
|
|
11243
|
+
const answer = waitForAnswerer(request.eventId, req.signal);
|
|
11244
|
+
armApprovalGate(request.eventId, req.approvalGateExpiry);
|
|
11245
|
+
const settled = await answer;
|
|
9004
11246
|
switch (settled.outcome) {
|
|
9005
11247
|
case "approved":
|
|
9006
11248
|
return "allowed-once";
|
|
@@ -9014,9 +11256,12 @@ function apply(ctx, config) {
|
|
|
9014
11256
|
}
|
|
9015
11257
|
async function onUserQuestionsRequest(raw, _next) {
|
|
9016
11258
|
const req = raw !== null && typeof raw === "object" ? raw : {};
|
|
11259
|
+
const callId = req.wait?.callId === undefined ? undefined : idString(req.wait.callId);
|
|
9017
11260
|
const target = askTarget(req.agent);
|
|
9018
11261
|
if (target === undefined) {
|
|
9019
|
-
failClosedAsk("questions", "no-turn", binding?.sessionId ?? FAIL_CLOSED_UNKNOWN_SESSION, "no open in-flight turn to deliver a questions ask"
|
|
11262
|
+
failClosedAsk("questions", "no-turn", binding?.sessionId ?? FAIL_CLOSED_UNKNOWN_SESSION, "no open in-flight turn to deliver a questions ask", {
|
|
11263
|
+
...callId !== undefined ? { callId } : {}
|
|
11264
|
+
});
|
|
9020
11265
|
throw new Error("ASK_CHANNEL_UNAVAILABLE: no in-flight turn to deliver user questions");
|
|
9021
11266
|
}
|
|
9022
11267
|
const questions = (req.questions ?? []).map((q) => {
|
|
@@ -9035,7 +11280,6 @@ function apply(ctx, config) {
|
|
|
9035
11280
|
...q.multiSelect === true ? { multiSelect: true } : {}
|
|
9036
11281
|
};
|
|
9037
11282
|
});
|
|
9038
|
-
const callId = req.wait?.callId === undefined ? undefined : idString(req.wait.callId);
|
|
9039
11283
|
let request;
|
|
9040
11284
|
try {
|
|
9041
11285
|
request = ask.create(target.turn.turnId, {
|
|
@@ -9047,7 +11291,10 @@ function apply(ctx, config) {
|
|
|
9047
11291
|
});
|
|
9048
11292
|
} catch (err) {
|
|
9049
11293
|
logger.error("[dsh-opentui-bridge] ask.create(questions) failed: %s", err);
|
|
9050
|
-
failClosedAsk("questions", target.turn.turnId, target.sessionId, "ask.create(questions) threw"
|
|
11294
|
+
failClosedAsk("questions", target.turn.turnId, target.sessionId, "ask.create(questions) threw", {
|
|
11295
|
+
...callId !== undefined ? { callId } : {},
|
|
11296
|
+
...target.childSessionId !== undefined ? { childSessionId: target.childSessionId } : {}
|
|
11297
|
+
});
|
|
9051
11298
|
throw new Error("ASK_CHANNEL_UNAVAILABLE: ask.create(questions) failed");
|
|
9052
11299
|
}
|
|
9053
11300
|
const settled = await waitForAnswerer(request.eventId, req.signal);
|
|
@@ -9467,6 +11714,460 @@ function apply(ctx, config) {
|
|
|
9467
11714
|
replyError(req.id, mapped.code, mapped.message, mapped.detail);
|
|
9468
11715
|
}
|
|
9469
11716
|
}
|
|
11717
|
+
async function handlePlanSessionPrune(req) {
|
|
11718
|
+
const persistence = resolvePrunePersistence(ctx);
|
|
11719
|
+
if (persistence === undefined) {
|
|
11720
|
+
replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.plan requires stat capability", {
|
|
11721
|
+
capability: "session.prune.plan",
|
|
11722
|
+
service: "sessionPersistence"
|
|
11723
|
+
});
|
|
11724
|
+
return;
|
|
11725
|
+
}
|
|
11726
|
+
const controller = resolveSessionController(ctx);
|
|
11727
|
+
if (controller === undefined) {
|
|
11728
|
+
replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.plan requires session.list", {
|
|
11729
|
+
capability: "session.prune.plan",
|
|
11730
|
+
service: "sessionController"
|
|
11731
|
+
});
|
|
11732
|
+
return;
|
|
11733
|
+
}
|
|
11734
|
+
const tryLockExclusive = resolveFlockTryLockExclusive();
|
|
11735
|
+
if (tryLockExclusive === undefined) {
|
|
11736
|
+
replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.plan requires tryLockExclusive", {
|
|
11737
|
+
capability: "session.prune.plan",
|
|
11738
|
+
service: "node-addon-system/flock",
|
|
11739
|
+
detail: "tryLockExclusive"
|
|
11740
|
+
});
|
|
11741
|
+
return;
|
|
11742
|
+
}
|
|
11743
|
+
const lockProbe = createPruneLockProbe(tryLockExclusive);
|
|
11744
|
+
const params = req.params ?? {};
|
|
11745
|
+
for (const key of ["sessionsRoot", "retentionDays", "blankGraceDays", "lockGraceMs", "freshMtimeGraceMs"]) {
|
|
11746
|
+
if (params[key] !== undefined) {
|
|
11747
|
+
replyError(req.id, "BAD_PARAMS", `session.prune.plan ${key} is host-derived; clients may not set it`);
|
|
11748
|
+
return;
|
|
11749
|
+
}
|
|
11750
|
+
}
|
|
11751
|
+
const stagedIds = new Set;
|
|
11752
|
+
if (params.stagedIds !== undefined) {
|
|
11753
|
+
if (!Array.isArray(params.stagedIds) || params.stagedIds.some((s) => typeof s !== "string")) {
|
|
11754
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.plan stagedIds must be a string array");
|
|
11755
|
+
return;
|
|
11756
|
+
}
|
|
11757
|
+
for (const id of params.stagedIds)
|
|
11758
|
+
stagedIds.add(id);
|
|
11759
|
+
}
|
|
11760
|
+
const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
|
|
11761
|
+
const policy = resolveHostPrunePolicy(ctx, config, sessionsRoot);
|
|
11762
|
+
const planConfigFingerprint = computeConfigFingerprint(policy);
|
|
11763
|
+
const lister = {
|
|
11764
|
+
list: (request) => controller.list(request)
|
|
11765
|
+
};
|
|
11766
|
+
const nodePruneFs = { lstat, realpath, stat, lockProbe };
|
|
11767
|
+
try {
|
|
11768
|
+
const listing = await listAllSessions(lister);
|
|
11769
|
+
if (listing.truncated) {
|
|
11770
|
+
replyError(req.id, "BLOCKED", "session.prune.plan aborted: session.list roster is incomplete (truncated pagination)", {
|
|
11771
|
+
capability: "session.prune.plan",
|
|
11772
|
+
reason: "incomplete-roster",
|
|
11773
|
+
pages: listing.pages
|
|
11774
|
+
});
|
|
11775
|
+
return;
|
|
11776
|
+
}
|
|
11777
|
+
const plan = await planSessionPrune(listing.rows, persistence, nodePruneFs, {
|
|
11778
|
+
retentionDays: policy.retentionDays,
|
|
11779
|
+
now: Date.now(),
|
|
11780
|
+
sessionsRoot,
|
|
11781
|
+
currentSessionId: binding?.sessionId,
|
|
11782
|
+
stagedIds,
|
|
11783
|
+
blankGraceDays: policy.blankGraceDays,
|
|
11784
|
+
lockGraceMs: policy.lockGraceMs,
|
|
11785
|
+
freshMtimeGraceMs: policy.freshMtimeGraceMs
|
|
11786
|
+
});
|
|
11787
|
+
replyOk(req.id, {
|
|
11788
|
+
...plan,
|
|
11789
|
+
fingerprint: computePlanFingerprint(plan),
|
|
11790
|
+
configFingerprint: planConfigFingerprint
|
|
11791
|
+
});
|
|
11792
|
+
} catch (err) {
|
|
11793
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
11794
|
+
logger.error("[dsh-opentui-bridge] session.prune.plan failed: %s", message);
|
|
11795
|
+
const mapped = mapHostError(err);
|
|
11796
|
+
replyError(req.id, mapped.code, mapped.message, mapped.detail);
|
|
11797
|
+
}
|
|
11798
|
+
}
|
|
11799
|
+
async function handleApplySessionPrune(req) {
|
|
11800
|
+
const params = req.params;
|
|
11801
|
+
if (params === null || typeof params !== "object" || Array.isArray(params)) {
|
|
11802
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.apply params must be an object");
|
|
11803
|
+
return;
|
|
11804
|
+
}
|
|
11805
|
+
const p = params;
|
|
11806
|
+
for (const key of [
|
|
11807
|
+
"entries",
|
|
11808
|
+
"retentionDays",
|
|
11809
|
+
"blankGraceDays",
|
|
11810
|
+
"lockGraceMs",
|
|
11811
|
+
"freshMtimeGraceMs",
|
|
11812
|
+
"sessionsRoot",
|
|
11813
|
+
"dshHome"
|
|
11814
|
+
]) {
|
|
11815
|
+
if (p[key] !== undefined) {
|
|
11816
|
+
replyError(req.id, "BAD_PARAMS", `session.prune.apply ${key} is host-owned; clients may not set it`);
|
|
11817
|
+
return;
|
|
11818
|
+
}
|
|
11819
|
+
}
|
|
11820
|
+
const stagedIds = new Set;
|
|
11821
|
+
if (p.stagedIds !== undefined) {
|
|
11822
|
+
if (!Array.isArray(p.stagedIds) || p.stagedIds.some((s) => typeof s !== "string")) {
|
|
11823
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.apply stagedIds must be a string array");
|
|
11824
|
+
return;
|
|
11825
|
+
}
|
|
11826
|
+
for (const id of p.stagedIds)
|
|
11827
|
+
stagedIds.add(id);
|
|
11828
|
+
}
|
|
11829
|
+
const fingerprint = p.fingerprint;
|
|
11830
|
+
const configFingerprint = p.configFingerprint;
|
|
11831
|
+
const generatedAt = p.generatedAt;
|
|
11832
|
+
if (typeof fingerprint !== "string" || fingerprint === "") {
|
|
11833
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.apply requires fingerprint from session.prune.plan");
|
|
11834
|
+
return;
|
|
11835
|
+
}
|
|
11836
|
+
if (typeof configFingerprint !== "string" || configFingerprint === "") {
|
|
11837
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.apply requires configFingerprint from session.prune.plan");
|
|
11838
|
+
return;
|
|
11839
|
+
}
|
|
11840
|
+
if (typeof generatedAt !== "number" || !Number.isFinite(generatedAt)) {
|
|
11841
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.apply requires numeric generatedAt from session.prune.plan");
|
|
11842
|
+
return;
|
|
11843
|
+
}
|
|
11844
|
+
const persistence = resolvePrunePersistence(ctx);
|
|
11845
|
+
if (persistence === undefined) {
|
|
11846
|
+
replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.apply requires stat capability", {
|
|
11847
|
+
capability: "session.prune.apply",
|
|
11848
|
+
service: "sessionPersistence"
|
|
11849
|
+
});
|
|
11850
|
+
return;
|
|
11851
|
+
}
|
|
11852
|
+
const controller = resolveSessionController(ctx);
|
|
11853
|
+
if (controller === undefined) {
|
|
11854
|
+
replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.apply requires session.list", {
|
|
11855
|
+
capability: "session.prune.apply",
|
|
11856
|
+
service: "sessionController"
|
|
11857
|
+
});
|
|
11858
|
+
return;
|
|
11859
|
+
}
|
|
11860
|
+
const tryLockExclusive = resolveFlockTryLockExclusive();
|
|
11861
|
+
if (tryLockExclusive === undefined) {
|
|
11862
|
+
replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.apply requires tryLockExclusive", {
|
|
11863
|
+
capability: "session.prune.apply",
|
|
11864
|
+
service: "node-addon-system/flock",
|
|
11865
|
+
detail: "tryLockExclusive"
|
|
11866
|
+
});
|
|
11867
|
+
return;
|
|
11868
|
+
}
|
|
11869
|
+
const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
|
|
11870
|
+
const dshHome = resolvePruneDshHome(ctx, config);
|
|
11871
|
+
const policy = resolveHostPrunePolicy(ctx, config, sessionsRoot);
|
|
11872
|
+
const maxPlanAgeMs = (() => {
|
|
11873
|
+
const fromConfig = config !== null && typeof config === "object" ? config : {};
|
|
11874
|
+
let hostValue;
|
|
11875
|
+
try {
|
|
11876
|
+
const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
|
|
11877
|
+
if (hostConfig !== null && typeof hostConfig === "object")
|
|
11878
|
+
hostValue = hostConfig.maxPlanAgeMs;
|
|
11879
|
+
} catch {}
|
|
11880
|
+
const value = fromConfig.maxPlanAgeMs ?? hostValue;
|
|
11881
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= 86400000 ? value : 60000;
|
|
11882
|
+
})();
|
|
11883
|
+
const lockProbe = createPruneLockProbe(tryLockExclusive);
|
|
11884
|
+
const nodePruneFs = { lstat, realpath, stat, lockProbe };
|
|
11885
|
+
const nodeApplyFs = {
|
|
11886
|
+
lstat,
|
|
11887
|
+
realpath,
|
|
11888
|
+
stat,
|
|
11889
|
+
rename,
|
|
11890
|
+
mkdir: (path, options) => options?.recursive ? mkdir(path, { recursive: true, mode: options.mode }) : mkdir(path, { mode: options?.mode }),
|
|
11891
|
+
writeFile: (path, data, options) => writeFile(path, data, options),
|
|
11892
|
+
appendFile,
|
|
11893
|
+
readdir,
|
|
11894
|
+
readFile: (path) => readFile(path, "utf8")
|
|
11895
|
+
};
|
|
11896
|
+
const now = Date.now();
|
|
11897
|
+
const deps = {
|
|
11898
|
+
persistence,
|
|
11899
|
+
lockProbe,
|
|
11900
|
+
now,
|
|
11901
|
+
opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
|
|
11902
|
+
withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
|
|
11903
|
+
};
|
|
11904
|
+
if (computeConfigFingerprint(policy) !== configFingerprint) {
|
|
11905
|
+
replyError(req.id, "STALE_PLAN", "session.prune.apply config fingerprint mismatch", {
|
|
11906
|
+
capability: "session.prune.apply",
|
|
11907
|
+
reason: "config-fingerprint"
|
|
11908
|
+
});
|
|
11909
|
+
return;
|
|
11910
|
+
}
|
|
11911
|
+
if (generatedAt > now + 1000 || now - generatedAt > maxPlanAgeMs) {
|
|
11912
|
+
replyError(req.id, "STALE_PLAN", "session.prune.apply plan is outside the max-age window", {
|
|
11913
|
+
capability: "session.prune.apply",
|
|
11914
|
+
reason: "max-age",
|
|
11915
|
+
maxPlanAgeMs
|
|
11916
|
+
});
|
|
11917
|
+
return;
|
|
11918
|
+
}
|
|
11919
|
+
try {
|
|
11920
|
+
const listing = await listAllSessions({ list: (request) => controller.list(request) });
|
|
11921
|
+
if (listing.truncated) {
|
|
11922
|
+
replyError(req.id, "BLOCKED", "session.prune.apply aborted: session.list roster is incomplete", {
|
|
11923
|
+
capability: "session.prune.apply",
|
|
11924
|
+
reason: "incomplete-roster",
|
|
11925
|
+
pages: listing.pages
|
|
11926
|
+
});
|
|
11927
|
+
return;
|
|
11928
|
+
}
|
|
11929
|
+
const freshPlan = await planSessionPrune(listing.rows, persistence, nodePruneFs, {
|
|
11930
|
+
retentionDays: policy.retentionDays,
|
|
11931
|
+
now,
|
|
11932
|
+
sessionsRoot,
|
|
11933
|
+
currentSessionId: binding?.sessionId,
|
|
11934
|
+
stagedIds,
|
|
11935
|
+
blankGraceDays: policy.blankGraceDays,
|
|
11936
|
+
lockGraceMs: policy.lockGraceMs,
|
|
11937
|
+
freshMtimeGraceMs: policy.freshMtimeGraceMs
|
|
11938
|
+
});
|
|
11939
|
+
const freshFingerprint = computePlanFingerprint(freshPlan);
|
|
11940
|
+
if (freshFingerprint !== fingerprint) {
|
|
11941
|
+
replyError(req.id, "STALE_PLAN", "session.prune.apply plan fingerprint mismatch", {
|
|
11942
|
+
capability: "session.prune.apply",
|
|
11943
|
+
reason: "plan-fingerprint"
|
|
11944
|
+
});
|
|
11945
|
+
return;
|
|
11946
|
+
}
|
|
11947
|
+
const result = await applyTrashPlan(nodeApplyFs, deps, freshPlan, {
|
|
11948
|
+
dshHome,
|
|
11949
|
+
sessionsRoot,
|
|
11950
|
+
planFingerprint: freshFingerprint
|
|
11951
|
+
});
|
|
11952
|
+
replyOk(req.id, { ...result });
|
|
11953
|
+
} catch (err) {
|
|
11954
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
11955
|
+
logger.error("[dsh-opentui-bridge] session.prune.apply failed: %s", message);
|
|
11956
|
+
if (err instanceof ApplyError) {
|
|
11957
|
+
replyError(req.id, err.code, message, err.detail);
|
|
11958
|
+
return;
|
|
11959
|
+
}
|
|
11960
|
+
replyError(req.id, "INTERNAL", "session.prune.apply failed");
|
|
11961
|
+
}
|
|
11962
|
+
}
|
|
11963
|
+
async function handlePurgeSessionPrune(req) {
|
|
11964
|
+
const params = req.params;
|
|
11965
|
+
if (params === null || typeof params !== "object" || Array.isArray(params)) {
|
|
11966
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.purge params must be an object");
|
|
11967
|
+
return;
|
|
11968
|
+
}
|
|
11969
|
+
const p = params;
|
|
11970
|
+
for (const key of [
|
|
11971
|
+
"entries",
|
|
11972
|
+
"retentionDays",
|
|
11973
|
+
"purgeRetentionDays",
|
|
11974
|
+
"tokenTtlMs",
|
|
11975
|
+
"sessionsRoot",
|
|
11976
|
+
"dshHome",
|
|
11977
|
+
"trashRoot",
|
|
11978
|
+
"path",
|
|
11979
|
+
"paths",
|
|
11980
|
+
"secret",
|
|
11981
|
+
"algorithm"
|
|
11982
|
+
]) {
|
|
11983
|
+
if (p[key] !== undefined) {
|
|
11984
|
+
replyError(req.id, "BAD_PARAMS", `session.prune.purge ${key} is host-owned; clients may not set it`);
|
|
11985
|
+
return;
|
|
11986
|
+
}
|
|
11987
|
+
}
|
|
11988
|
+
if (p.phase !== "prepare" && p.phase !== "commit") {
|
|
11989
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.purge phase must be 'prepare' or 'commit'");
|
|
11990
|
+
return;
|
|
11991
|
+
}
|
|
11992
|
+
if (p.phase === "commit" && (typeof p.token !== "string" || p.token === "")) {
|
|
11993
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.purge commit requires the prepare token");
|
|
11994
|
+
return;
|
|
11995
|
+
}
|
|
11996
|
+
const persistence = resolvePrunePersistence(ctx);
|
|
11997
|
+
if (persistence === undefined) {
|
|
11998
|
+
replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.purge requires stat capability", {
|
|
11999
|
+
capability: "session.prune.purge",
|
|
12000
|
+
service: "sessionPersistence"
|
|
12001
|
+
});
|
|
12002
|
+
return;
|
|
12003
|
+
}
|
|
12004
|
+
const controller = resolveSessionController(ctx);
|
|
12005
|
+
if (controller === undefined) {
|
|
12006
|
+
replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.purge requires session.list", {
|
|
12007
|
+
capability: "session.prune.purge",
|
|
12008
|
+
service: "sessionController"
|
|
12009
|
+
});
|
|
12010
|
+
return;
|
|
12011
|
+
}
|
|
12012
|
+
const tryLockExclusive = resolveFlockTryLockExclusive();
|
|
12013
|
+
if (tryLockExclusive === undefined) {
|
|
12014
|
+
replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.purge requires tryLockExclusive", {
|
|
12015
|
+
capability: "session.prune.purge",
|
|
12016
|
+
service: "node-addon-system/flock",
|
|
12017
|
+
detail: "tryLockExclusive"
|
|
12018
|
+
});
|
|
12019
|
+
return;
|
|
12020
|
+
}
|
|
12021
|
+
try {
|
|
12022
|
+
const dshHome = resolvePruneDshHome(ctx, config);
|
|
12023
|
+
const hostPolicy = resolveHostPurgePolicy(ctx, config);
|
|
12024
|
+
const lockProbe = createPruneLockProbe(tryLockExclusive);
|
|
12025
|
+
const nodePurgeFs = {
|
|
12026
|
+
lstat,
|
|
12027
|
+
realpath,
|
|
12028
|
+
stat,
|
|
12029
|
+
readdir,
|
|
12030
|
+
readFile: (path) => readFile(path, "utf8"),
|
|
12031
|
+
readFileBuffer: (path) => readFile(path),
|
|
12032
|
+
writeFile: (path, data, options) => writeFile(path, data, options),
|
|
12033
|
+
appendFile,
|
|
12034
|
+
unlink,
|
|
12035
|
+
rmdir,
|
|
12036
|
+
mkdir: (path, options) => options?.recursive ? mkdir(path, { recursive: true, mode: options.mode }) : mkdir(path, { mode: options?.mode })
|
|
12037
|
+
};
|
|
12038
|
+
const now = Date.now();
|
|
12039
|
+
const deps = {
|
|
12040
|
+
persistence,
|
|
12041
|
+
lister: { list: (request) => controller.list(request) },
|
|
12042
|
+
lockProbe,
|
|
12043
|
+
now,
|
|
12044
|
+
opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
|
|
12045
|
+
secret: await resolvePurgeSecret(nodePurgeFs, dshHome, () => randomUUID() + randomUUID()),
|
|
12046
|
+
retentionDays: hostPolicy.retentionDays,
|
|
12047
|
+
tokenTtlMs: hostPolicy.tokenTtlMs,
|
|
12048
|
+
newSecret: () => randomUUID() + randomUUID(),
|
|
12049
|
+
withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
|
|
12050
|
+
};
|
|
12051
|
+
if (p.phase === "prepare") {
|
|
12052
|
+
const result = await preparePurge(nodePurgeFs, deps, dshHome);
|
|
12053
|
+
replyOk(req.id, {
|
|
12054
|
+
opId: result.opId,
|
|
12055
|
+
candidates: result.candidates,
|
|
12056
|
+
rejected: result.rejected,
|
|
12057
|
+
token: result.token
|
|
12058
|
+
});
|
|
12059
|
+
return;
|
|
12060
|
+
}
|
|
12061
|
+
const result = await purgeTrashSessions(nodePurgeFs, deps, dshHome, p.token);
|
|
12062
|
+
replyOk(req.id, { ...result });
|
|
12063
|
+
} catch (err) {
|
|
12064
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
12065
|
+
logger.error("[dsh-opentui-bridge] session.prune.purge failed: %s", message);
|
|
12066
|
+
if (err instanceof PurgeError) {
|
|
12067
|
+
replyError(req.id, err.code, message, err.detail);
|
|
12068
|
+
return;
|
|
12069
|
+
}
|
|
12070
|
+
const mapped = mapHostError(err);
|
|
12071
|
+
replyError(req.id, mapped.code, mapped.message, mapped.detail);
|
|
12072
|
+
}
|
|
12073
|
+
}
|
|
12074
|
+
async function handleRestoreSessionPrune(req) {
|
|
12075
|
+
const params = req.params;
|
|
12076
|
+
if (params === null || typeof params !== "object" || Array.isArray(params)) {
|
|
12077
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.restore params must be an object");
|
|
12078
|
+
return;
|
|
12079
|
+
}
|
|
12080
|
+
const p = params;
|
|
12081
|
+
for (const key of [
|
|
12082
|
+
"entries",
|
|
12083
|
+
"path",
|
|
12084
|
+
"paths",
|
|
12085
|
+
"sessionsRoot",
|
|
12086
|
+
"dshHome",
|
|
12087
|
+
"trashRoot",
|
|
12088
|
+
"manifest",
|
|
12089
|
+
"root",
|
|
12090
|
+
"retentionDays"
|
|
12091
|
+
]) {
|
|
12092
|
+
if (p[key] !== undefined) {
|
|
12093
|
+
replyError(req.id, "BAD_PARAMS", `session.prune.restore ${key} is host-owned; clients may not set it`);
|
|
12094
|
+
return;
|
|
12095
|
+
}
|
|
12096
|
+
}
|
|
12097
|
+
const phase = p.phase ?? "list";
|
|
12098
|
+
if (phase !== "list" && phase !== "restore") {
|
|
12099
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.restore phase must be 'list' or 'restore'");
|
|
12100
|
+
return;
|
|
12101
|
+
}
|
|
12102
|
+
if (phase === "restore" && (typeof p.id !== "string" || p.id === "")) {
|
|
12103
|
+
replyError(req.id, "BAD_PARAMS", "session.prune.restore requires a non-empty id");
|
|
12104
|
+
return;
|
|
12105
|
+
}
|
|
12106
|
+
const persistence = resolvePrunePersistence(ctx);
|
|
12107
|
+
if (persistence === undefined) {
|
|
12108
|
+
replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.restore requires stat capability", {
|
|
12109
|
+
capability: "session.prune.restore",
|
|
12110
|
+
service: "sessionPersistence"
|
|
12111
|
+
});
|
|
12112
|
+
return;
|
|
12113
|
+
}
|
|
12114
|
+
const controller = resolveSessionController(ctx);
|
|
12115
|
+
if (controller === undefined) {
|
|
12116
|
+
replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.restore requires session.list", {
|
|
12117
|
+
capability: "session.prune.restore",
|
|
12118
|
+
service: "sessionController"
|
|
12119
|
+
});
|
|
12120
|
+
return;
|
|
12121
|
+
}
|
|
12122
|
+
const tryLockExclusive = resolveFlockTryLockExclusive();
|
|
12123
|
+
if (tryLockExclusive === undefined) {
|
|
12124
|
+
replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.restore requires tryLockExclusive", {
|
|
12125
|
+
capability: "session.prune.restore",
|
|
12126
|
+
service: "node-addon-system/flock",
|
|
12127
|
+
detail: "tryLockExclusive"
|
|
12128
|
+
});
|
|
12129
|
+
return;
|
|
12130
|
+
}
|
|
12131
|
+
try {
|
|
12132
|
+
const dshHome = resolvePruneDshHome(ctx, config);
|
|
12133
|
+
const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
|
|
12134
|
+
const lockProbe = createPruneLockProbe(tryLockExclusive);
|
|
12135
|
+
const nodeRestoreFs = {
|
|
12136
|
+
lstat,
|
|
12137
|
+
realpath,
|
|
12138
|
+
stat,
|
|
12139
|
+
readdir,
|
|
12140
|
+
readFile: (path) => readFile(path, "utf8"),
|
|
12141
|
+
readFileBuffer: (path) => readFile(path),
|
|
12142
|
+
rename
|
|
12143
|
+
};
|
|
12144
|
+
const now = Date.now();
|
|
12145
|
+
const deps = {
|
|
12146
|
+
persistence,
|
|
12147
|
+
lister: { list: (request) => controller.list(request) },
|
|
12148
|
+
lockProbe,
|
|
12149
|
+
now,
|
|
12150
|
+
opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
|
|
12151
|
+
sessionsRoot,
|
|
12152
|
+
withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
|
|
12153
|
+
};
|
|
12154
|
+
if (phase === "list") {
|
|
12155
|
+
const result = await listRestoreEntries(nodeRestoreFs, dshHome);
|
|
12156
|
+
replyOk(req.id, { entries: result.entries, rejected: result.rejected });
|
|
12157
|
+
return;
|
|
12158
|
+
}
|
|
12159
|
+
const result = await restoreTrashEntry(nodeRestoreFs, deps, dshHome, p.id);
|
|
12160
|
+
replyOk(req.id, { ...result });
|
|
12161
|
+
} catch (err) {
|
|
12162
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
12163
|
+
logger.error("[dsh-opentui-bridge] session.prune.restore failed: %s", message);
|
|
12164
|
+
if (err instanceof RestoreError) {
|
|
12165
|
+
replyError(req.id, err.code, message, err.detail);
|
|
12166
|
+
return;
|
|
12167
|
+
}
|
|
12168
|
+
replyError(req.id, "INTERNAL", "session.prune.restore failed");
|
|
12169
|
+
}
|
|
12170
|
+
}
|
|
9470
12171
|
async function reconcileSubagentIndex() {
|
|
9471
12172
|
const controller = resolveSessionController(ctx);
|
|
9472
12173
|
if (controller === undefined) {
|
|
@@ -9666,6 +12367,22 @@ function apply(ctx, config) {
|
|
|
9666
12367
|
await handleListSessions(req);
|
|
9667
12368
|
return;
|
|
9668
12369
|
}
|
|
12370
|
+
if (req.method === "session.prune.plan") {
|
|
12371
|
+
await handlePlanSessionPrune(req);
|
|
12372
|
+
return;
|
|
12373
|
+
}
|
|
12374
|
+
if (req.method === "session.prune.apply") {
|
|
12375
|
+
await handleApplySessionPrune(req);
|
|
12376
|
+
return;
|
|
12377
|
+
}
|
|
12378
|
+
if (req.method === "session.prune.purge") {
|
|
12379
|
+
await handlePurgeSessionPrune(req);
|
|
12380
|
+
return;
|
|
12381
|
+
}
|
|
12382
|
+
if (req.method === "session.prune.restore") {
|
|
12383
|
+
await handleRestoreSessionPrune(req);
|
|
12384
|
+
return;
|
|
12385
|
+
}
|
|
9669
12386
|
const sessionQueryMethodId = CAP_SESSION_QUERY_WIRE_METHODS[req.method];
|
|
9670
12387
|
if (sessionQueryMethodId !== undefined) {
|
|
9671
12388
|
try {
|
|
@@ -9866,9 +12583,18 @@ function apply(ctx, config) {
|
|
|
9866
12583
|
clearTurnSubscriptions();
|
|
9867
12584
|
pushRelay.stopAll();
|
|
9868
12585
|
accountRelay.stopAll();
|
|
12586
|
+
for (const eventId of ask.pendingIds()) {
|
|
12587
|
+
ask.settleExternal(eventId, { settleReason: "connection-closed" });
|
|
12588
|
+
}
|
|
9869
12589
|
for (const eventId of [...pendingAnswerers.keys()]) {
|
|
9870
12590
|
settleAnswerer(eventId, { outcome: "cancelled" });
|
|
9871
12591
|
}
|
|
12592
|
+
for (const dispose of [...approvalGateListeners.values()]) {
|
|
12593
|
+
try {
|
|
12594
|
+
dispose();
|
|
12595
|
+
} catch {}
|
|
12596
|
+
}
|
|
12597
|
+
approvalGateListeners.clear();
|
|
9872
12598
|
try {
|
|
9873
12599
|
unsubApprovalAnswerer?.();
|
|
9874
12600
|
} catch {}
|
|
@@ -9970,11 +12696,13 @@ export {
|
|
|
9970
12696
|
isAskErrorCode,
|
|
9971
12697
|
name,
|
|
9972
12698
|
probeAgentProgressResidue,
|
|
12699
|
+
probeAgentTranscriptResidue,
|
|
9973
12700
|
probeOwnedAbortRelease,
|
|
9974
12701
|
projectAccountScalarResult,
|
|
9975
12702
|
projectAccountViewForFrame,
|
|
9976
12703
|
redactIdentifier,
|
|
9977
12704
|
resolveAskDeadlineMs,
|
|
12705
|
+
resolveMaxAskWaitMs,
|
|
9978
12706
|
sanitizeFrameForWire,
|
|
9979
12707
|
summarizeAnswers,
|
|
9980
12708
|
turnIdOf,
|