@vincemakes/kiso-runtime 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/session.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * AgentSession + Run — the durable multi-turn conversation (Phase C/D).
2
+ * AgentSession — the durable multi-turn conversation (Phase C/D).
3
3
  *
4
4
  * A session owns ONE EventLog, seeded from disk on load and continued in
5
5
  * memory. Each `run(input)`:
@@ -22,11 +22,17 @@
22
22
  *
23
23
  * Restart recovery is the same code path as a second run: rebuild the log
24
24
  * from the JSONL, continue numbering where the file ended.
25
+ *
26
+ * 手感批 B4 (pure move): the Run class lives in run.ts, the recovery
27
+ * support in recovery.ts, the E1/E2 composition helpers in compose.ts —
28
+ * same package, same exports (index.ts re-exports all four).
25
29
  */
26
- import { EventLog, executionLedger, loop, projectMessages, } from "@vincemakes/kiso-core";
30
+ import { EventLog, executionLedger, projectMessages, } from "@vincemakes/kiso-core";
27
31
  import { denialResult } from "@vincemakes/kiso-core";
28
32
  import { estimateSummarySavings, KEEP_RECENT_ROUNDS, lastSummaryPoint, summarizeConversation, summaryBoundarySeq, } from "@vincemakes/kiso-core";
29
33
  import { StaleWriterError } from "./store.js";
34
+ import { composeHooks } from "./compose.js";
35
+ import { Run } from "./run.js";
30
36
  /** A session whose disk write was rejected (stale handle) is PERMANENTLY
31
37
  * poisoned: its in-memory log no longer matches the disk, so no further
32
38
  * run may proceed — reload the session (一). */
@@ -428,632 +434,3 @@ export class AgentSession {
428
434
  this.#pendingResolvers.delete(decisionId);
429
435
  }
430
436
  }
431
- /**
432
- * A single turn. Async-iterable, so `for await (const ev of session.run(x))`
433
- * is the natural shape; the handle also carries the runId and the abort.
434
- */
435
- export class Run {
436
- runId;
437
- #store;
438
- #adapter;
439
- #config;
440
- #session;
441
- #input;
442
- #resume;
443
- #abort = new AbortController();
444
- #externalSignal;
445
- #decisionIds = [];
446
- #uncertaintyIds = [];
447
- #started = false;
448
- constructor(store, adapter, config, session, input, externalSignal, resume) {
449
- this.#store = store;
450
- this.#adapter = adapter;
451
- this.#config = config;
452
- this.#session = session;
453
- this.#input = input;
454
- this.#externalSignal = externalSignal;
455
- this.#resume = resume;
456
- this.runId = crypto.randomUUID();
457
- }
458
- /** Cancel the run: propagates to the adapter (SDK) and future executions. */
459
- abort() {
460
- this.#abort.abort();
461
- }
462
- async *[Symbol.asyncIterator]() {
463
- if (this.#started)
464
- throw new Error("a run may only be consumed once");
465
- this.#started = true;
466
- // The WHOLE body is one try/finally: a consumer that abandons the
467
- // run at ANY yield (even the user_input one) must release the
468
- // session's single-run slot and its approval resolvers.
469
- try {
470
- // 第四轮: health is re-checked when the iterator ACTUALLY starts —
471
- // a run constructed before the session was poisoned must fail
472
- // here, before any log or disk mutation.
473
- this.#session.ensureHealthy();
474
- this.#session.beginRun(this);
475
- const log = this.#session.log;
476
- const signal = this.#externalSignal ? new MergedSignal(this.#abort.signal, this.#externalSignal) : this.#abort.signal;
477
- // E2: the session's own microcompact wins; otherwise the FIRST
478
- // extension providing a compaction config supplies it.
479
- const microcompact = microcompactFor(this.#config);
480
- // E2: the session's own systemPrompt first, then every extension
481
- // append in LOAD order — deterministic (same extensions → same
482
- // prompt); no appends → byte-identical to the extension-less run.
483
- const systemPrompt = composeSystemPrompt(this.#config.systemPrompt, this.#config.extensions ?? []);
484
- const loopConfig = () => ({
485
- adapter: this.#adapter,
486
- model: this.#config.model,
487
- sessionId: this.#session.id, // P3: tools see their session (ToolContext.sessionId)
488
- ...(systemPrompt !== undefined ? { systemPrompt } : {}),
489
- registry: this.#config.registry,
490
- ...(this.#config.hooks !== undefined ? { hooks: this.#config.hooks } : {}),
491
- ...(this.#config.maxTurns !== undefined ? { maxTurns: this.#config.maxTurns } : {}),
492
- ...(this.#config.maxTokens !== undefined ? { maxTokens: this.#config.maxTokens } : {}),
493
- ...(this.#config.temperature !== undefined ? { temperature: this.#config.temperature } : {}),
494
- ...(this.#config.compaction !== undefined ? { compaction: this.#config.compaction } : {}),
495
- ...(microcompact !== undefined ? { microcompact } : {}),
496
- ...(this.#config.maxRetries !== undefined ? { maxRetries: this.#config.maxRetries } : {}),
497
- approvalPolicies: (this.#config.extensions ?? []).flatMap((e) => (e.approvals ?? []).map((policy) => ({ extension: e.name, policy }))),
498
- log,
499
- signal,
500
- resolveApproval: (decisionId) => new Promise((resolve) => {
501
- this.#decisionIds.push(decisionId);
502
- this.#session.registerResolver(decisionId, resolve);
503
- }),
504
- // 第四轮(对抗): the abort paths consult these so a verdict
505
- // the human gave in the same instant as the abort is
506
- // recorded, exactly once.
507
- approvalVerdict: (decisionId) => this.#session.approvalVerdict(decisionId),
508
- uncertaintyVerdict: (executionId) => this.#session.uncertaintyVerdict(executionId),
509
- resolveUncertainty: (executionId) => new Promise((resolve) => {
510
- this.#uncertaintyIds.push(executionId);
511
- this.#session.registerUncertaintyResolver(executionId, resolve);
512
- }),
513
- });
514
- const self = this;
515
- const runLoop = async function* () {
516
- for await (const ev of loop(loopConfig())) {
517
- await self.#session.persist(self.runId, ev);
518
- yield ev;
519
- }
520
- };
521
- if (this.#resume) {
522
- // ── B 组: recovery is PER-RUN, keyed by StoreRecord.runId ──
523
- // Rebuild run boundaries; only the LAST unterminated run is
524
- // recovered. Earlier runs that DID terminate have their
525
- // dangling approvals closed (permission_expired) — a dead
526
- // run's approval is never re-presented or resurrected.
527
- const records = this.#store.load(this.#session.id);
528
- const runs = new Map();
529
- const order = [];
530
- for (const r of records) {
531
- if (!runs.has(r.runId)) {
532
- runs.set(r.runId, []);
533
- order.push(r.runId);
534
- }
535
- runs.get(r.runId).push(r.event);
536
- }
537
- let lastOpen;
538
- for (const runId of order) {
539
- const events = runs.get(runId);
540
- if (!events.some((e) => e.type === "terminal"))
541
- lastOpen = { runId, events };
542
- }
543
- if (!lastOpen)
544
- return; // everything terminated — nothing to resume
545
- // Adopt the ORIGINAL runId so the whole trajectory stays one
546
- // run in the audit.
547
- this.runId = lastOpen.runId;
548
- // Close dangling approvals of TERMINATED runs.
549
- for (const [runId, events] of runs) {
550
- if (runId === lastOpen.runId)
551
- continue;
552
- if (!events.some((e) => e.type === "terminal"))
553
- continue; // an open earlier run? impossible — lastOpen is the LAST
554
- for (const ev of events) {
555
- if (ev.type !== "permission_requested")
556
- continue;
557
- const dead = this.#session.log.all.some((e) => (e.type === "permission_decided" || e.type === "permission_expired") &&
558
- e.decisionId === ev.decisionId);
559
- if (dead)
560
- continue;
561
- const expired = this.#session.log.append({
562
- type: "permission_expired",
563
- decisionId: ev.decisionId,
564
- reason: `run ${runId} terminated before the request was answered`,
565
- });
566
- await this.#session.persist(runId, expired);
567
- }
568
- }
569
- // Uncertain executions block until a human decides.
570
- const uncertain = this.#session.uncertainExecutions();
571
- if (uncertain.length > 0) {
572
- throw new ResumeBlockedError(uncertain.map((u) => ({ executionId: u.executionId, callId: u.callId, name: u.name })));
573
- }
574
- // 1. Recovery scoped to the LAST OPEN RUN's events. The recover
575
- // phase re-announces ALREADY-PERSISTED events (the stored
576
- // permission_requested) for the consumer to re-prompt on —
577
- // those must never be written to the store again, or seq
578
- // would duplicate. Only events newer than the base log
579
- // entry are durable.
580
- const baseSeq = log.lastSeq;
581
- const persist = async (ev) => {
582
- if (ev.seq > baseSeq)
583
- await this.#session.persist(this.runId, ev);
584
- };
585
- for await (const ev of this.#recover(log, signal, lastOpen.events)) {
586
- await persist(ev);
587
- yield ev;
588
- }
589
- // 2. Continuation: drive the LAST OPEN run to its terminal.
590
- // The guard is scoped to that run — an earlier run's
591
- // terminal must not suppress it (B 组).
592
- if (!lastOpen.events.some((e) => e.type === "terminal")) {
593
- for await (const ev of runLoop())
594
- yield ev;
595
- }
596
- return;
597
- }
598
- // 四: a session with an open run REFUSES new runs at the
599
- // persistence layer — a second open run would be permanently
600
- // orphaned (recovery only ever recovers the last one). The
601
- // open run is continued via resume(), never by starting another.
602
- const openRun = openRunId(this.#store.load(this.#session.id));
603
- if (openRun !== undefined) {
604
- throw new Error(`session ${this.#session.id} still has an open run (${openRun}) — resume() it instead of starting a new run`);
605
- }
606
- // 1. Durable first: the prompt enters the log and the store
607
- // before any model call — a crash here leaves a restorable
608
- // session. The prompt is also the first event the consumer
609
- // sees, so what was asked and what happened live in the same
610
- // stream.
611
- const inputEvent = log.append({ type: "user_input", content: this.#input });
612
- await this.#session.persist(this.runId, inputEvent);
613
- yield inputEvent;
614
- // 2. The loop projects from the session log — multi-turn context
615
- // is the projection, not a second copy.
616
- for await (const ev of runLoop())
617
- yield ev;
618
- }
619
- finally {
620
- // 第五轮(P1-5): flush verdicts the consumer submitted before the
621
- // generator was abandoned — an approve()/resolveUncertain() whose
622
- // durable event the loop never got to persist must STILL land on
623
- // disk, exactly once.
624
- try {
625
- await this.#session.flushPendingVerdicts(this.runId, this.#session.log);
626
- }
627
- catch {
628
- // the flush itself failed (poisoned session) — the error
629
- // already poisoned everything; nothing more can be done.
630
- }
631
- // The run is over (or abandoned): its unanswered approvals must
632
- // fall back to the direct-persist path, so a late approve() is
633
- // still durable.
634
- for (const decisionId of this.#decisionIds) {
635
- this.#session.dropResolver(decisionId);
636
- }
637
- for (const executionId of this.#uncertaintyIds) {
638
- this.#session.dropUncertaintyResolver(executionId);
639
- }
640
- this.#session.endRun(this);
641
- }
642
- }
643
- // ── Area 2: the durable recovery state machine ───────────────────────
644
- /**
645
- * Apply every durable decision and fill every missing receipt, in log
646
- * order. A decision with no execution yet EXECUTES the persisted call
647
- * (its original name/input/callId — never re-asked of the model, never
648
- * re-approved); a denial writes its tool result; a succeeded/failed
649
- * execution whose tool_result never landed is completed from the
650
- * receipt. Undecided requests pause and await approve().
651
- */
652
- async *#recover(log, signal, scope) {
653
- const requests = scope.filter((e) => e.type === "permission_requested");
654
- for (const pending of requests) {
655
- const decided = log.all.find((e) => e.type === "permission_decided" && e.decisionId === pending.decisionId);
656
- // 四: paired by events NEWER than the request — a historical
657
- // same-callId execution from an earlier run must not count as THIS
658
- // request's execution (the provider callId may repeat across runs).
659
- const hasExecution = log.all.some((e) => e.type === "tool_execution_started" && e.callId === pending.callId && e.seq > pending.seq);
660
- const hasResult = log.all.some((e) => e.type === "tool_result" && e.callId === pending.callId && e.seq > pending.seq);
661
- if (decided === undefined) {
662
- // Pause: announce the stored request, await the human.
663
- const pendingDecision = new Promise((resolve) => {
664
- this.#decisionIds.push(pending.decisionId);
665
- this.#session.registerResolver(pending.decisionId, resolve);
666
- });
667
- yield pending;
668
- // Area 4: an abort during the resumed approval wait ends the
669
- // run; the request stays durable and pending.
670
- if (signal.aborted) {
671
- // 第五轮(P1-6): a verdict given in the same instant as the
672
- // abort is still recorded — the abort must not bypass the
673
- // durable fallback (aligned with the loop's abort path).
674
- const verdict = this.#session.approvalVerdict(pending.decisionId);
675
- if (verdict !== undefined) {
676
- yield log.append({
677
- type: "permission_decided",
678
- decisionId: pending.decisionId,
679
- callId: pending.callId,
680
- decision: verdict ? "approved" : "denied",
681
- ...(verdict ? {} : { reason: "denied by user" }),
682
- });
683
- }
684
- return;
685
- }
686
- const final = await abortable(pendingDecision, signal);
687
- if (final === ABORTED) {
688
- // 第四轮(对抗): a verdict given in the same instant as the
689
- // abort is recorded (exactly once), never lost.
690
- const verdict = this.#session.approvalVerdict(pending.decisionId);
691
- if (verdict !== undefined) {
692
- yield log.append({
693
- type: "permission_decided",
694
- decisionId: pending.decisionId,
695
- callId: pending.callId,
696
- decision: verdict ? "approved" : "denied",
697
- ...(verdict ? {} : { reason: "denied by user" }),
698
- });
699
- }
700
- return;
701
- }
702
- // The decision is written here — exactly one writer per event.
703
- yield log.append({
704
- type: "permission_decided",
705
- decisionId: pending.decisionId,
706
- callId: pending.callId, // binds the decision to the invocation (B 组)
707
- decision: final.action === "allow" ? "approved" : "denied",
708
- ...(final.action === "deny" && final.reason !== undefined ? { reason: final.reason } : {}),
709
- });
710
- if (final.action === "allow") {
711
- if (!hasExecution)
712
- yield* this.#executePersisted(pending.callId, pending.name, pending.input, signal);
713
- }
714
- else if (!hasResult) {
715
- yield* this.#denialResult(pending.callId, final.reason ?? "denied by user");
716
- }
717
- }
718
- else if (decided.decision === "approved") {
719
- // Decided while no process was running: apply without pausing.
720
- // An abort during recovery must stop the pending executions,
721
- // exactly like the live loop's sibling guard (finding 3).
722
- if (signal.aborted)
723
- return;
724
- if (!hasExecution)
725
- yield* this.#executePersisted(pending.callId, pending.name, pending.input, signal);
726
- }
727
- else if (!hasResult) {
728
- yield* this.#denialResult(pending.callId, decided.reason ?? "denied by user");
729
- }
730
- }
731
- // Receipt repair: an execution that reached a terminal state but
732
- // whose model-facing result never landed is completed FROM THE
733
- // RECEIPT — never re-executed. Snapshot the scope first: this phase
734
- // appends the repaired results, and iterating a growing array would
735
- // re-visit them. 四: pairing is by executionId — a same-callId result
736
- // from a different execution never suppresses the repair.
737
- for (const ev of [...scope]) {
738
- if (ev.type !== "tool_execution_succeeded" && ev.type !== "tool_execution_failed")
739
- continue;
740
- const hasResult = log.all.some((e) => e.type === "tool_result" && e.executionId === ev.executionId);
741
- if (hasResult)
742
- continue;
743
- yield log.append(ev.type === "tool_execution_succeeded"
744
- ? {
745
- type: "tool_result",
746
- callId: ev.callId,
747
- content: ev.result.content,
748
- isError: false,
749
- // 八: the repaired result reproduces the normal path
750
- // losslessly — the tags ride on the durable receipt.
751
- ...(ev.tags !== undefined ? { tags: ev.tags } : {}),
752
- executionId: ev.executionId,
753
- }
754
- : {
755
- type: "tool_result",
756
- callId: ev.callId,
757
- content: ev.error,
758
- isError: true,
759
- ...(ev.errorKind !== undefined ? { errorKind: ev.errorKind } : {}),
760
- ...(ev.tags !== undefined ? { tags: ev.tags } : {}),
761
- executionId: ev.executionId,
762
- });
763
- }
764
- // B 组 crash window: a resolution was persisted but its tool_result
765
- // fill never landed — complete it so the model is never left staring
766
- // at a dangling tool_use. 四: keyed by executionId, and the fill
767
- // carries it, so a same-callId result from another execution is never
768
- // confused with this one.
769
- for (const ev of [...scope]) {
770
- if (ev.type !== "tool_execution_resolved")
771
- continue;
772
- const hasResult = log.all.some((e) => e.type === "tool_result" && e.executionId === ev.executionId);
773
- if (hasResult)
774
- continue;
775
- const denial = denialResult(ev.resolution === "rerun"
776
- ? "interrupted execution — rerun approved: the attempt is treated as NOT applied; the model may retry"
777
- : "abandoned by human decision — the interrupted attempt must not be treated as applied");
778
- yield log.append({
779
- type: "tool_result",
780
- callId: ev.callId,
781
- content: denial.content,
782
- isError: true,
783
- errorKind: denial.errorKind,
784
- executionId: ev.executionId,
785
- });
786
- }
787
- }
788
- /**
789
- * Execute a call whose approval is already durable: the original
790
- * name/input/callId from the persisted permission_requested, bypassing
791
- * the permission hook (it was decided) and the model (it was never
792
- * asked to re-issue). Full ledgered lifecycle.
793
- */
794
- async *#executePersisted(callId, name, input, signal) {
795
- const log = this.#session.log;
796
- const tool = this.#config.registry.get(name);
797
- const executionId = `ex-${log.lastSeq + 1}`;
798
- // An abort that landed while the decision was being applied must
799
- // not start the side effect (finding 3).
800
- if (signal.aborted)
801
- return;
802
- yield log.append({ type: "tool_execution_started", executionId, callId, name, input });
803
- let result;
804
- if (tool === undefined) {
805
- result = { content: `Unknown tool: ${name}`, isError: true, errorKind: "invalid_input" };
806
- }
807
- else {
808
- try {
809
- if (signal.aborted) {
810
- result = { content: "aborted before execution", isError: true, errorKind: "fatal" };
811
- }
812
- else {
813
- result = await tool.execute(input, { signal });
814
- }
815
- }
816
- catch (err) {
817
- result = {
818
- content: err instanceof Error ? err.message : String(err),
819
- isError: true,
820
- errorKind: "fatal",
821
- };
822
- }
823
- if (this.#config.hooks?.onPostTool) {
824
- result = await this.#config.hooks.onPostTool({ callId, name, input }, result, { sessionId: this.#session.id });
825
- }
826
- }
827
- // 裁决 #12 修正一: the honest note rides the recovered failure too —
828
- // the receipt and the repaired tool_result reproduce the live path
829
- // losslessly.
830
- if (result.isError && tool?.idempotent !== true) {
831
- result = {
832
- ...result,
833
- content: `${result.content}\n[non-idempotent tool failed — its side effects may have partially applied; verify before retrying]`,
834
- };
835
- }
836
- if (result.isError) {
837
- yield log.append({
838
- type: "tool_execution_failed",
839
- executionId,
840
- callId,
841
- error: result.content,
842
- // P1-9: errorKind only exists on errors — runtime-guarded too.
843
- ...(result.isError && result.errorKind !== undefined ? { errorKind: result.errorKind } : {}),
844
- safeToRetry: tool?.idempotent === true,
845
- ...(result.tags !== undefined ? { tags: result.tags } : {}),
846
- });
847
- }
848
- else {
849
- yield log.append({
850
- type: "tool_execution_succeeded",
851
- executionId,
852
- callId,
853
- result: { content: result.content, isError: false },
854
- ...(result.tags !== undefined ? { tags: result.tags } : {}),
855
- });
856
- }
857
- yield log.append({
858
- type: "tool_result",
859
- callId,
860
- content: result.content,
861
- isError: result.isError,
862
- // P1-9: errorKind only exists on errors — runtime-guarded too.
863
- ...(result.isError && result.errorKind !== undefined ? { errorKind: result.errorKind } : {}),
864
- // 五: live tags survive the resumed path too.
865
- ...(result.tags !== undefined ? { tags: result.tags } : {}),
866
- executionId,
867
- });
868
- // 裁决 #12 (ADR-0038): the failed-receipt uncertain PAUSE is REMOVED
869
- // here too (it mirrored the live loop's C 组 pause) — a complete
870
- // receipt IS the outcome; uncertainty belongs to the crash window
871
- // alone. A retry passes the approval chain again.
872
- }
873
- /** The model-facing result of a durable denial — no execution happened. */
874
- async *#denialResult(callId, reason) {
875
- const denial = denialResult(reason);
876
- yield this.#session.log.append({
877
- type: "tool_result",
878
- callId,
879
- content: denial.content,
880
- isError: true,
881
- errorKind: denial.errorKind,
882
- });
883
- }
884
- }
885
- /**
886
- * E2: the session's systemPrompt plus every extension's append, in LOAD
887
- * order, \n\n-joined — deterministic (same extension list → same prompt).
888
- * No appends → the base passes through byte-identical.
889
- */
890
- function composeSystemPrompt(base, extensions) {
891
- const appends = extensions.flatMap((e) => (e.systemPrompt?.append === undefined ? [] : [e.systemPrompt.append]));
892
- if (appends.length === 0)
893
- return base;
894
- return base === undefined ? appends.join("\n\n") : `${base}\n\n${appends.join("\n\n")}`;
895
- }
896
- /**
897
- * E1: extension hooks compose AFTER the agent's own (既有先行 — the existing
898
- * hook sees every event first). Observers all run, in order; onUserMessage
899
- * and onPreTool — the FIRST decisive answer wins (the existing hook
900
- * outranks extensions; defers fall through); onPostTool folds — each
901
- * transforms the previous result. Returns the existing host unchanged when
902
- * no extension provides hooks.
903
- */
904
- function composeHooks(existing, extensions) {
905
- const extHooks = extensions.flatMap((e) => (e.hooks === undefined ? [] : [e.hooks]));
906
- if (extHooks.length === 0)
907
- return existing;
908
- const out = { ...existing };
909
- const sources = existing === undefined ? extHooks : [existing, ...extHooks];
910
- const observers = (key) => {
911
- const handlers = sources.map(key).filter((h) => h !== undefined);
912
- if (handlers.length <= 1)
913
- return handlers[0];
914
- return async (payload, ctx) => {
915
- for (const h of handlers)
916
- await h(payload, ctx);
917
- };
918
- };
919
- for (const key of ["onPreLlm", "onEvent", "onPreCompact", "onPostCompact", "onPause", "onStop"]) {
920
- const handler = observers((h) => h[key]);
921
- if (handler !== undefined)
922
- out[key] = handler;
923
- }
924
- const messageHandlers = sources
925
- .map((h) => h.onUserMessage)
926
- .filter((h) => h !== undefined);
927
- if (messageHandlers.length === 1) {
928
- out.onUserMessage = messageHandlers[0]; // length 1 guarantees the element
929
- }
930
- else if (messageHandlers.length > 1) {
931
- // 复审 E1-P2: the pipe + veto short-circuit — each handler sees the
932
- // message as the PREVIOUS one left it (既有先行), and a null (veto)
933
- // anywhere ends the chain immediately: never "no opinion" for the
934
- // next handler to outvote. Adding an extension can therefore never
935
- // make the chain MORE permissive (the approval chain's deny>ask>allow
936
- // monotonicity, on the message side).
937
- out.onUserMessage = async (msg, ctx) => {
938
- let current = msg;
939
- for (const h of messageHandlers) {
940
- const r = await h(current, ctx);
941
- if (r === null)
942
- return null;
943
- current = r;
944
- }
945
- return current;
946
- };
947
- }
948
- const preToolHandlers = sources
949
- .map((h) => h.onPreTool)
950
- .filter((h) => h !== undefined);
951
- if (preToolHandlers.length === 1) {
952
- out.onPreTool = preToolHandlers[0];
953
- }
954
- else if (preToolHandlers.length > 1) {
955
- out.onPreTool = async (call, ctx) => {
956
- for (const h of preToolHandlers) {
957
- const d = await h(call, ctx);
958
- if (d.action !== "defer")
959
- return d;
960
- }
961
- return { action: "defer" };
962
- };
963
- }
964
- const postToolHandlers = sources
965
- .map((h) => h.onPostTool)
966
- .filter((h) => h !== undefined);
967
- if (postToolHandlers.length === 1) {
968
- out.onPostTool = postToolHandlers[0];
969
- }
970
- else if (postToolHandlers.length > 1) {
971
- out.onPostTool = async (call, result, ctx) => {
972
- let r = result;
973
- for (const h of postToolHandlers)
974
- r = await h(call, r, ctx);
975
- return r;
976
- };
977
- }
978
- return out;
979
- }
980
- /**
981
- * E2: the loop's microcompact config — the session's own microcompact wins;
982
- * otherwise the FIRST extension providing a compaction config supplies it.
983
- * An extension config without a threshold contributes nothing (a boundary
984
- * needs a threshold to ever fire).
985
- */
986
- function microcompactFor(config) {
987
- if (config.microcompact !== undefined)
988
- return config.microcompact;
989
- for (const ext of config.extensions ?? []) {
990
- const c = ext.compaction;
991
- if (c !== undefined && c.thresholdTokens !== undefined) {
992
- return { thresholdTokens: c.thresholdTokens, ...(c.keepResults !== undefined ? { keepResults: c.keepResults } : {}) };
993
- }
994
- }
995
- return undefined;
996
- }
997
- /**
998
- * The most recent run WITHOUT a terminal, or undefined when every recorded
999
- * run terminated. Recovery can only drive ONE run to its terminal, so an
1000
- * open run must be the exclusive reason a session refuses new runs (四).
1001
- */
1002
- function openRunId(records) {
1003
- const terminated = new Set(records.filter((r) => r.event.type === "terminal").map((r) => r.runId));
1004
- for (let i = records.length - 1; i >= 0; i--) {
1005
- const runId = records[i].runId;
1006
- if (!terminated.has(runId))
1007
- return runId;
1008
- }
1009
- return undefined;
1010
- }
1011
- /** Sentinel: the signal aborted while the recovery awaited a decision. */
1012
- const ABORTED = Symbol("kiso-resume-aborted");
1013
- /** Resolve with the decision, or ABORTED when the signal fires first. */
1014
- async function abortable(promise, signal) {
1015
- if (signal.aborted)
1016
- return ABORTED;
1017
- return new Promise((resolve) => {
1018
- const onAbort = () => {
1019
- signal.removeEventListener("abort", onAbort);
1020
- resolve(ABORTED);
1021
- };
1022
- signal.addEventListener("abort", onAbort, { once: true });
1023
- promise.then((value) => {
1024
- signal.removeEventListener("abort", onAbort);
1025
- resolve(value);
1026
- }, (err) => {
1027
- signal.removeEventListener("abort", onAbort);
1028
- throw err;
1029
- });
1030
- });
1031
- }
1032
- /**
1033
- * A signal that fires when ANY source fires — the run's own controller and
1034
- * an optional external signal (the CLI's Ctrl+C, a fixture's flip).
1035
- */
1036
- class MergedSignal {
1037
- #sources;
1038
- #listeners = new Set();
1039
- constructor(...sources) {
1040
- this.#sources = sources;
1041
- for (const source of sources) {
1042
- if (source.aborted)
1043
- continue;
1044
- source.addEventListener("abort", () => {
1045
- for (const listener of this.#listeners)
1046
- listener();
1047
- });
1048
- }
1049
- }
1050
- get aborted() {
1051
- return this.#sources.some((s) => s.aborted);
1052
- }
1053
- addEventListener(_type, listener) {
1054
- this.#listeners.add(() => listener.call(this, undefined));
1055
- }
1056
- removeEventListener(_type, listener) {
1057
- this.#listeners.delete(listener);
1058
- }
1059
- }