@nomadop/session-watcher-dsh 0.11.0 → 0.11.2

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/index.js CHANGED
@@ -7723,8 +7723,9 @@ var require_ignore = __commonJS({
7723
7723
  // dsh/src/index.js
7724
7724
  import { fileURLToPath as fileURLToPath2 } from "node:url";
7725
7725
  import { CompactionId, compactCheckpointSource, toolPairingBalancedAfter, toolPairingBalancedBefore } from "@deepseek-ai/dsh-compaction";
7726
- import { AssistantStreamAccumulator, BlockAssembler, assembleAssistantStream, createUserMessage, errorChain, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
7726
+ import { AssistantStreamAccumulator, BlockAssembler, HarnessError, assembleAssistantStream, createUserMessage, errorChain, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
7727
7727
  import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
7728
+ import { extractSessionEventText } from "@deepseek-ai/dsh-session-query";
7728
7729
  import { defineTool } from "@deepseek-ai/dsh-tools";
7729
7730
  import z from "@deepseek-ai/schemastery";
7730
7731
 
@@ -9918,8 +9919,8 @@ var repairJson = Object.assign(jsonRepair, { parse: jsonParse });
9918
9919
  // dsh/carrier-cache/package.json
9919
9920
  var package_default = {
9920
9921
  name: "@nomadop/session-watcher-dsh-carrier-cache",
9921
- version: "0.1.0",
9922
- description: "Activation bundle of Session Watcher's carrier cache adapter for DeepSeek Harness",
9922
+ version: "0.2.0",
9923
+ description: "Session Watcher's carrier cache adapter for DeepSeek Harness, with the profile layer that activates it",
9923
9924
  type: "module",
9924
9925
  license: "MIT",
9925
9926
  author: "Longju Cheng",
@@ -9936,15 +9937,27 @@ var package_default = {
9936
9937
  dsh: ">=0.2.2-rc.1"
9937
9938
  },
9938
9939
  exports: {
9940
+ "./pi-ai": "./dist/pi-ai-index.js",
9939
9941
  "./locale/*.json": "./locale/*.json",
9940
9942
  "./icon": "./icon.svg"
9941
9943
  },
9942
9944
  files: [
9945
+ "dist/pi-ai-index.js",
9943
9946
  "cordis.patch.yml",
9944
9947
  "locale/*.json",
9945
9948
  "icon.svg",
9946
9949
  "README.md"
9947
9950
  ],
9951
+ peerDependencies: {
9952
+ "@deepseek-ai/dsh-credentials": ">=0.2.2-rc.1",
9953
+ "@deepseek-ai/dsh-launch-environment": ">=0.2.2-rc.1",
9954
+ "@deepseek-ai/dsh-llm": ">=0.2.2-rc.1",
9955
+ "@deepseek-ai/dsh-llm-pi-ai": ">=0.2.2-rc.1",
9956
+ "@deepseek-ai/dsh-timeout": ">=0.2.2-rc.1",
9957
+ "@deepseek-ai/dsh-util-values": ">=0.2.2-rc.1",
9958
+ "@deepseek-ai/schemastery": ">=3.19.0",
9959
+ "@earendil-works/pi-ai": "^1.3.0"
9960
+ },
9948
9961
  dsh: {
9949
9962
  bundle: {
9950
9963
  patch: "./cordis.patch.yml"
@@ -13519,10 +13532,11 @@ var SessionWatcher = class {
13519
13532
  cacheRead: point.cacheRead,
13520
13533
  cacheCreation: point.cacheWrite,
13521
13534
  turnSeq: point.turnSeq,
13522
- foldedSeq: point.foldedSeq
13535
+ foldedSeq: point.foldedSeq,
13536
+ ...point.amberStockL === void 0 ? {} : { amberStockL: point.amberStockL }
13523
13537
  }));
13524
13538
  }
13525
- // The only bucket/resource query. It reads the Engine first, then passes only default-selected file rows
13539
+ // Reads the Engine first, then passes only default-selected file rows
13526
13540
  // to Resource Enrichment — a row the position basis excludes buys no symbols, and a Skill has no file.
13527
13541
  getBucketData({ includeSymbols = false } = {}) {
13528
13542
  const bucket = this._engine.getBucketData();
@@ -13566,6 +13580,12 @@ var SessionWatcher = class {
13566
13580
  segment: bucket.segment
13567
13581
  };
13568
13582
  }
13583
+ // The Engine's held line numbers of one file, ascending; null when it has no resource at that path, and for a Skill
13584
+ // key, whose number key 1 is no line of any file.
13585
+ getHeldLines(path3) {
13586
+ if (path3.startsWith(SKILL_RESOURCE_PREFIX)) return null;
13587
+ return this._engine.heldLines().get(path3) ?? null;
13588
+ }
13569
13589
  // The value host wiring persists unchanged as `profile_snapshot`. `b_total` is the UNCAPPED resident total:
13570
13590
  // the read-time cap belongs to the live dashboard, while persistence needs the belief its own path rows sum
13571
13591
  // into, or `dead + Σ paths` would exceed the total it is stored beside.
@@ -18529,11 +18549,12 @@ function fitAffine(points) {
18529
18549
  if (!(Number.isFinite(d) && d > 0)) return null;
18530
18550
  return { a: sx / n - d * uMean, d };
18531
18551
  }
18552
+ var xOn = (reference, u) => reference.a + reference.d * u;
18532
18553
  function landmarksOf(reference, mf) {
18533
18554
  if (!reference || !(Number.isFinite(mf) && mf > 0)) {
18534
18555
  return { xSweet: null, xBrAmberL: null, xBrAmberR: null, xBrRedR: null };
18535
18556
  }
18536
- const xAt = (u) => reference.a + reference.d * u;
18557
+ const xAt = (u) => xOn(reference, u);
18537
18558
  return {
18538
18559
  xSweet: xAt(1),
18539
18560
  xBrAmberL: xAt(uLeftAtBr(mf, BR_AMBER)),
@@ -18541,6 +18562,10 @@ function landmarksOf(reference, mf) {
18541
18562
  xBrRedR: xAt(uAtBr(mf, BR_RED))
18542
18563
  };
18543
18564
  }
18565
+ function amberStockOf({ reference, u, xBrAmberR, bDefault }, anchorL) {
18566
+ if (!reference || !Number.isFinite(u) || !Number.isFinite(xBrAmberR) || !(Number.isFinite(bDefault) && bDefault > 0)) return null;
18567
+ return anchorL + bDefault * (xBrAmberR - xOn(reference, u));
18568
+ }
18544
18569
 
18545
18570
  // lib/measurement/resident-ledger.js
18546
18571
  var TOUCH_HISTORY_MAX = 128;
@@ -18739,6 +18764,10 @@ function createResidentLedger() {
18739
18764
  return { applyEffect, applyResidualAllocation, residentTotals, snapshot };
18740
18765
  }
18741
18766
 
18767
+ // lib/measurement/usage.js
18768
+ var stockOf = ({ input, cacheRead, cacheWrite }) => input + cacheRead + cacheWrite;
18769
+ var uncachedOf = ({ input, cacheWrite }) => input + cacheWrite;
18770
+
18742
18771
  // lib/measurement/engine.js
18743
18772
  var USAGE_KEYS = ["input", "output", "cacheRead", "cacheWrite"];
18744
18773
  var SETTLEMENT_EPSILON = 1e-6;
@@ -19094,7 +19123,7 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19094
19123
  segmentGMin = Math.min(segmentGMin, effectiveG(gEma));
19095
19124
  }
19096
19125
  function acceptNewStep(record, usage, usageTotal, timestamp, result) {
19097
- const totalStock = usage.input + usage.cacheRead + usage.cacheWrite;
19126
+ const totalStock = stockOf(usage);
19098
19127
  const model = record.model ?? null;
19099
19128
  const firstOfEpoch = segmentSteps.length === 0;
19100
19129
  if (totalStock > 0 && frames.length > 0) {
@@ -19193,8 +19222,8 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19193
19222
  pendingTurn = true;
19194
19223
  break;
19195
19224
  case "epoch": {
19196
- const closed2 = finalizeSegment();
19197
- if (closed2) result.closedSegments.push(closed2);
19225
+ const closed = finalizeSegment();
19226
+ if (closed) result.closedSegments.push(closed);
19198
19227
  break;
19199
19228
  }
19200
19229
  case "residual":
@@ -19249,7 +19278,7 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19249
19278
  }
19250
19279
  const oAvg = segmentUsageCount > 0 ? segmentOutputSum / segmentUsageCount : null;
19251
19280
  const durationMs = Number.isFinite(segmentFirstTs) && Number.isFinite(segmentLastTs) ? segmentLastTs - segmentFirstTs : null;
19252
- const closed2 = {
19281
+ const closed = {
19253
19282
  segment: segmentSeq,
19254
19283
  epochModel,
19255
19284
  steps,
@@ -19276,12 +19305,15 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19276
19305
  },
19277
19306
  paths
19278
19307
  };
19308
+ const { rateLamp } = readView();
19309
+ const lastStep = segmentSteps.at(-1);
19310
+ lastStep.amberStockL = rateLamp.reference?.provisional ? null : amberStockOf(rateLamp, stockOf(lastStep.usage));
19279
19311
  openFreshSegment();
19280
- return closed2;
19312
+ return closed;
19281
19313
  }
19282
19314
  function closeCurrentSegment() {
19283
- const closed2 = finalizeSegment();
19284
- return { closedSegments: closed2 ? [closed2] : [], diagnostics: [] };
19315
+ const closed = finalizeSegment();
19316
+ return { closedSegments: closed ? [closed] : [], diagnostics: [] };
19285
19317
  }
19286
19318
  function readView() {
19287
19319
  const lastStep = segmentSteps.length ? segmentSteps[segmentSteps.length - 1] : null;
@@ -19354,7 +19386,7 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19354
19386
  function getHistory() {
19355
19387
  return calls.map((step) => {
19356
19388
  const B = step.bAtCall;
19357
- const L = step.usage.input + step.usage.cacheRead + step.usage.cacheWrite;
19389
+ const L = stockOf(step.usage);
19358
19390
  return {
19359
19391
  ts: step.timestamp,
19360
19392
  segment: step.segment,
@@ -19369,7 +19401,8 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19369
19401
  cacheRead: step.usage.cacheRead,
19370
19402
  cacheWrite: step.usage.cacheWrite,
19371
19403
  turnSeq: step.turn,
19372
- foldedSeq: step.foldedSeq
19404
+ foldedSeq: step.foldedSeq,
19405
+ ...step.amberStockL === void 0 ? {} : { amberStockL: step.amberStockL }
19373
19406
  };
19374
19407
  });
19375
19408
  }
@@ -19581,6 +19614,135 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19581
19614
  };
19582
19615
  }
19583
19616
 
19617
+ // lib/old-attribution.js
19618
+ var OLD_SHARE_ABOVE = 0.9;
19619
+ function createOldAttributionScorer() {
19620
+ const hits = [];
19621
+ let step = null;
19622
+ let gapSeen = false;
19623
+ const startStep = (key) => {
19624
+ step = { key, scored: !gapSeen, undo: /* @__PURE__ */ new Map() };
19625
+ };
19626
+ const startEpoch = () => {
19627
+ step = null;
19628
+ gapSeen = false;
19629
+ };
19630
+ function freeze(record, scratch) {
19631
+ for (const { impacts } of record.effects) {
19632
+ for (const { resourceKey, kind, entries } of impacts) {
19633
+ const before = scratch.get(resourceKey);
19634
+ const undone = step.undo.get(resourceKey) ?? /* @__PURE__ */ new Map();
19635
+ if (kind === "replace-fragments") {
19636
+ for (const [line, entry] of before ?? []) if (!undone.has(line)) undone.set(line, entry);
19637
+ }
19638
+ for (const { key } of entries) if (!undone.has(key)) undone.set(key, before?.get(key) ?? null);
19639
+ step.undo.set(resourceKey, undone);
19640
+ }
19641
+ }
19642
+ }
19643
+ function heldIn(resourceKey, scratch) {
19644
+ const undone = step.undo.get(resourceKey);
19645
+ let overview = null;
19646
+ const overviewOf = () => {
19647
+ const lines = new Map(scratch.get(resourceKey));
19648
+ for (const [line, entry] of undone ?? []) {
19649
+ if (entry === null) lines.delete(line);
19650
+ else lines.set(line, entry);
19651
+ }
19652
+ const fps = /* @__PURE__ */ new Set();
19653
+ let unfingerprinted = false;
19654
+ for (const entry of lines.values()) {
19655
+ if (entry.fp === void 0) unfingerprinted = true;
19656
+ else fps.add(entry.fp);
19657
+ }
19658
+ return { fps, unfingerprinted };
19659
+ };
19660
+ return {
19661
+ entryAt: (line) => undone?.has(line) ? undone.get(line) ?? void 0 : scratch.get(resourceKey)?.get(line),
19662
+ mayHaveMoved(fp) {
19663
+ overview ??= overviewOf();
19664
+ return overview.unfingerprinted || overview.fps.has(fp);
19665
+ }
19666
+ };
19667
+ }
19668
+ function returnedBy(record) {
19669
+ const byResource = /* @__PURE__ */ new Map();
19670
+ for (const { access, impacts } of record.effects) {
19671
+ if (access !== "read") continue;
19672
+ for (const { resourceKey, entries } of impacts) {
19673
+ const lines = byResource.get(resourceKey) ?? /* @__PURE__ */ new Map();
19674
+ for (const { key, fp, moved } of entries) if (moved !== true && fp !== void 0) lines.set(key, fp);
19675
+ byResource.set(resourceKey, lines);
19676
+ }
19677
+ }
19678
+ return byResource;
19679
+ }
19680
+ function score({ pending, observation, record, scratch }) {
19681
+ let oldLines = 0;
19682
+ let newLines = 0;
19683
+ for (const [resourceKey, lines] of returnedBy(record)) {
19684
+ const held = heldIn(resourceKey, scratch);
19685
+ for (const [key, fp] of lines) {
19686
+ if (held.entryAt(key)?.fp === fp) oldLines += 1;
19687
+ else if (!held.mayHaveMoved(fp)) newLines += 1;
19688
+ }
19689
+ }
19690
+ if (oldLines > 0 && oldLines / (oldLines + newLines) > OLD_SHARE_ABOVE) {
19691
+ hits.push({ toolUseId: pending.toolUseId, seq: observation.sourceOrdinal, oldLines, newLines });
19692
+ }
19693
+ }
19694
+ function observe(call) {
19695
+ if (!call.recalled) gapSeen = true;
19696
+ if (step === null || !step.scored) return;
19697
+ if (call.recalled && call.observation.isError !== true && call.observation.stepKey === step.key) score(call);
19698
+ freeze(call.record, call.scratch);
19699
+ }
19700
+ return { hits, startStep, startEpoch, observe };
19701
+ }
19702
+
19703
+ // lib/held-view.js
19704
+ var SELECTED = () => ({ selectedByDefault: true, defaultDiscardReason: null });
19705
+ function createHeldView({ createProjection, completeToolResult, resolveModelPolicy, frameCtx }) {
19706
+ return (observations) => {
19707
+ let completed = [];
19708
+ const projection = createProjection({
19709
+ completeToolResult: (pending, observation, context, options) => {
19710
+ const answer = completeToolResult(pending, observation, context, options);
19711
+ completed.push({ effects: answer.effects, text: observation.content, seq: observation.sourceOrdinal });
19712
+ return answer;
19713
+ }
19714
+ });
19715
+ const scorer = createOldAttributionScorer();
19716
+ const scoringCtx = { ...frameCtx, observeRecord: scorer.observe };
19717
+ const engine = createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy: SELECTED });
19718
+ let skills = /* @__PURE__ */ new Map();
19719
+ const effects = [];
19720
+ for (const observation of observations) {
19721
+ if (observation.type === "step-start") {
19722
+ scorer.startStep(observation.stepKey);
19723
+ continue;
19724
+ }
19725
+ completed = [];
19726
+ const { records } = projection.project(observation, scoringCtx);
19727
+ engine.ingest(records.filter((record) => record.type === "effect" || record.type === "epoch"));
19728
+ if (records.some((record) => record.type === "epoch")) {
19729
+ skills = /* @__PURE__ */ new Map();
19730
+ scorer.startEpoch();
19731
+ }
19732
+ for (const { effects: answered, text, seq } of completed) {
19733
+ for (const { resourceKey } of answered.flatMap((effect) => effect.impacts)) {
19734
+ const isSkill = resourceKey.startsWith(SKILL_RESOURCE_PREFIX);
19735
+ const key = isSkill ? resourceKey.slice(SKILL_RESOURCE_PREFIX.length) : resourceKey;
19736
+ if (isSkill) skills.set(key, text);
19737
+ effects.push({ seq, kind: isSkill ? "skill" : "path", key });
19738
+ }
19739
+ }
19740
+ }
19741
+ const paths = new Map([...engine.heldLines()].filter(([key]) => !key.startsWith(SKILL_RESOURCE_PREFIX)));
19742
+ return { paths, skills, effects, oldReads: scorer.hits };
19743
+ };
19744
+ }
19745
+
19584
19746
  // lib/pricing-store.js
19585
19747
  function tryGetStore() {
19586
19748
  try {
@@ -19635,7 +19797,7 @@ function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
19635
19797
  // package.json
19636
19798
  var package_default2 = {
19637
19799
  name: "@nomadop/session-watcher",
19638
- version: "0.11.0",
19800
+ version: "0.11.2",
19639
19801
  description: "Local Claude Code context-cost monitor, transcript replay, buckets, and handoff",
19640
19802
  type: "module",
19641
19803
  license: "MIT",
@@ -19749,7 +19911,7 @@ function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars
19749
19911
  requireBound("cacheChars", cacheChars);
19750
19912
  const cache = /* @__PURE__ */ new Map();
19751
19913
  let cachedChars = 0;
19752
- const orNull2 = (attempt) => {
19914
+ const orNull3 = (attempt) => {
19753
19915
  try {
19754
19916
  return attempt();
19755
19917
  } catch {
@@ -19773,11 +19935,11 @@ function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars
19773
19935
  }
19774
19936
  return {
19775
19937
  resolve: resolve3,
19776
- stat: (file) => orNull2(() => {
19938
+ stat: (file) => orNull3(() => {
19777
19939
  const st = statSync3(file);
19778
19940
  return { size: st.size, isFile: st.isFile() };
19779
19941
  }),
19780
- readText: (file) => orNull2(() => {
19942
+ readText: (file) => orNull3(() => {
19781
19943
  const st = statSync3(file);
19782
19944
  if (!st.isFile()) return null;
19783
19945
  const hit = cache.get(file);
@@ -19942,29 +20104,6 @@ function renderFileEvidence(displayPath, { totalLines, runs }, { maxChars = Infi
19942
20104
  });
19943
20105
  return shown.every((count) => count === 0) && available.some((count) => count > 0) ? null : { text: parts2.join("\n"), shown };
19944
20106
  }
19945
- var HEADER_ROW = /^(.*) \(total lines: (\d+)\)$/s;
19946
- var NUMBERED_ROW = /^(\d+): (.*)$/s;
19947
- var NOTICE_ROW = /^\(Output capped after line \d+\. Use offset=\d+ to continue\.\)$/;
19948
- function parseFileEvidence(text) {
19949
- const rows = text.replace(/\n$/, "").split("\n");
19950
- const header = HEADER_ROW.exec(rows.shift());
19951
- if (header === null) return null;
19952
- const runs = [];
19953
- let apart = true;
19954
- for (const row of rows) {
19955
- if (row === SEPARATOR || NOTICE_ROW.test(row)) {
19956
- apart = true;
19957
- continue;
19958
- }
19959
- const numbered = NUMBERED_ROW.exec(row);
19960
- if (numbered === null) return null;
19961
- const number = Number(numbered[1]);
19962
- if (apart) runs.push({ offset: number, lines: [] });
19963
- runs.at(-1).lines.push({ number, text: numbered[2] });
19964
- apart = false;
19965
- }
19966
- return { path: header[1], totalLines: Number(header[2]), runs };
19967
- }
19968
20107
 
19969
20108
  // lib/resource-attribution.js
19970
20109
  var LIMIT_NAMES = ["candidates", "fileBytes", "sideChars", "decodeDepth", "alignCells", "evidenceFloor"];
@@ -20776,10 +20915,10 @@ function createToolEvidenceInterpreter({ attribution, profile, limits } = {}) {
20776
20915
  }
20777
20916
  function recordOf2(pending, observation, frameCtx, scratch) {
20778
20917
  const recalled = typeof frameCtx.recall === "function" ? readRecord(frameCtx.recall(pending.toolUseId)) : null;
20779
- if (recalled !== null) return recalled;
20918
+ if (recalled !== null) return { record: recalled, recalled: true };
20780
20919
  const record = partition(pending, observation, scratch);
20781
20920
  if (typeof frameCtx.remember === "function") frameCtx.remember(pending.toolUseId, record);
20782
- return record;
20921
+ return { record, recalled: false };
20783
20922
  }
20784
20923
  function emit(record, pending, observation, telemetry, scratch) {
20785
20924
  const effects = priced(record.effects, pending.issuingPolicy.ctp);
@@ -20840,7 +20979,10 @@ function createToolEvidenceInterpreter({ attribution, profile, limits } = {}) {
20840
20979
  pathEvents: []
20841
20980
  };
20842
20981
  if (pending.nonFile !== null) return completeNonFileResource(pending, observation, telemetry);
20843
- return emit(recordOf2(pending, observation, frameCtx ?? {}, scratch), pending, observation, telemetry, scratch);
20982
+ const ctx = frameCtx ?? {};
20983
+ const { record, recalled } = recordOf2(pending, observation, ctx, scratch);
20984
+ if (typeof ctx.observeRecord === "function") ctx.observeRecord({ pending, observation, record, recalled, scratch });
20985
+ return emit(record, pending, observation, telemetry, scratch);
20844
20986
  }
20845
20987
  function resourceKeysOf(pair, capture) {
20846
20988
  try {
@@ -20889,9 +21031,23 @@ function loadCallsOf(message) {
20889
21031
  return calls.map(({ id, name: name3, arguments: args2 }, index) => ({ id, name: name3, arguments: args2, text: content[index].text }));
20890
21032
  }
20891
21033
 
20892
- // lib/harness/dsh/inner-seal-message.js
20893
- var INNER_SEAL_KIND = "session-watcher-inner-seal";
20894
- var carriesEvidence = (source) => source?.kind === INNER_SEAL_KIND || source?.kind === LOAD_MESSAGE_KIND && Array.isArray(source.paths);
21034
+ // lib/carried-evidence.js
21035
+ var CARRIED_WORDING = {
21036
+ empty: (path3) => `${path3} is empty.`,
21037
+ unreadable: (path3, reason) => `${path3} could not be read (${reason}). This is not its text and not a tool failure; read the file directly when it is needed.`,
21038
+ skill: (name3, text) => `Skill ${name3}:
21039
+ ${text}`
21040
+ };
21041
+ var carriedNote = (wording) => `Evidence carried from the replaced context as of this summary: file text as read from disk when it was written, and skill text as the log recorded it. Each entry changes what the evidence of any earlier summary or kept file excerpt here states. ${wording.editGuard}`;
21042
+ function runsOf(numbers) {
21043
+ const runs = [];
21044
+ for (const number of numbers) {
21045
+ const last = runs.at(-1);
21046
+ if (last && last[1] + 1 === number) last[1] = number;
21047
+ else runs.push([number, number]);
21048
+ }
21049
+ return runs;
21050
+ }
20895
21051
  function foldCarried(sources) {
20896
21052
  const paths = /* @__PURE__ */ new Map();
20897
21053
  const skills = /* @__PURE__ */ new Map();
@@ -20944,59 +21100,6 @@ function carryChanges(baseline, current) {
20944
21100
  ...skills.length > 0 ? { skills } : {}
20945
21101
  };
20946
21102
  }
20947
- var CARRIER_WORDING = {
20948
- addresses: "These summaries stand in for earlier turns of this session; replacing them changed no file and no state, so the work carries on from them. Each summary line below opens with seq numbers: the addresses, in this session's log, of the events it summarizes, which the session history tools can read. A line marked user: holds the user's own words instead, cut where a marker says so.",
20949
- slotLine: (seqs) => `seq ${seqs.join(", ")}: `,
20950
- imageSaved: (name3) => `The image ${name3} is not in the current context; read_image can read the file below when it is needed.`,
20951
- carried: "Evidence carried from the replaced context as of this summary: file text as read from disk when it was written, and skill text as the log recorded it. Each entry changes what the evidence of any earlier summary or kept file excerpt here states. The reads behind this file text still count in this session, so edit a file without reading it again.",
20952
- empty: (path3) => `${path3} is empty.`,
20953
- unreadable: (path3, reason) => `${path3} could not be read (${reason}). This is not its text and not a tool failure; read the file directly when it is needed.`,
20954
- skill: (name3, text) => `Skill ${name3}:
20955
- ${text}`,
20956
- stateHeading: (seq) => `Session state as of session seq ${seq}:`,
20957
- stateLabels: {
20958
- workingDirectory: (tool) => `Working directory, as ${tool} would show:`,
20959
- subagents: (tool) => `Running subagents, as ${tool} would show:`,
20960
- jobs: (tool) => `Running jobs, as ${tool} would show:`,
20961
- todos: (tool) => `Todo list, as ${tool} last left it:`
20962
- },
20963
- stateList: (entries) => entries.map(({ id, label }) => `${id} \u2014 ${label}`).join("; "),
20964
- stateUnchanged: "unchanged since the last summary that shows it",
20965
- stateEmpty: "(empty)",
20966
- questionMark: "A line marked question: holds the original question.",
20967
- questionLine: (question) => `question: ${question}`,
20968
- userLine: (user) => `user: ${user}`,
20969
- askCall: ({ id, name: name3, arguments: args2 }) => `Original ${name3} call ${id}, arguments:
20970
- ${args2}`,
20971
- askResult: (id, { text, isError }) => `Original result of call ${id}${isError ? " (marked as an error)" : ""}:
20972
- ${text}`
20973
- };
20974
- function runsOf(numbers) {
20975
- const runs = [];
20976
- for (const number of numbers) {
20977
- const last = runs.at(-1);
20978
- if (last && last[1] + 1 === number) last[1] = number;
20979
- else runs.push([number, number]);
20980
- }
20981
- return runs;
20982
- }
20983
- function shownRuns(write, omit) {
20984
- const texts = new Map(write);
20985
- const left = new Set(omit);
20986
- return runsOf(write.map(([number]) => number).filter((number) => !left.has(number))).map(([first, last]) => ({
20987
- offset: first,
20988
- lines: Array.from({ length: last - first + 1 }, (_, at) => ({ number: first + at, text: texts.get(first + at) }))
20989
- }));
20990
- }
20991
- function entryParts({ displayPath, totalLines, state, reason, write = [], omit = [] }) {
20992
- const W = CARRIER_WORDING;
20993
- const parts2 = [];
20994
- if (state === "empty") parts2.push(W.empty(displayPath));
20995
- if (state === "unreadable") parts2.push(W.unreadable(displayPath, reason));
20996
- const runs = shownRuns(write, omit);
20997
- if (runs.length > 0) parts2.push(renderFileEvidence(displayPath, { totalLines, runs }).text);
20998
- return parts2;
20999
- }
21000
21103
  function omitShown(changes, earlier) {
21001
21104
  const shown = /* @__PURE__ */ new Map();
21002
21105
  for (const source of earlier) {
@@ -21015,12 +21118,30 @@ function omitShown(changes, earlier) {
21015
21118
  })
21016
21119
  };
21017
21120
  }
21018
- function renderCarried(source) {
21121
+ var carriedOf = (earlier, current) => omitShown(carryChanges(foldCarried(earlier), current), earlier);
21122
+ function shownRuns(write, omit) {
21123
+ const texts = new Map(write);
21124
+ const left = new Set(omit);
21125
+ return runsOf(write.map(([number]) => number).filter((number) => !left.has(number))).map(([first, last]) => ({
21126
+ offset: first,
21127
+ lines: Array.from({ length: last - first + 1 }, (_, at) => ({ number: first + at, text: texts.get(first + at) }))
21128
+ }));
21129
+ }
21130
+ function entryParts({ displayPath, totalLines, state, reason, write = [], omit = [] }) {
21131
+ const W = CARRIED_WORDING;
21132
+ const parts2 = [];
21133
+ if (state === "empty") parts2.push(W.empty(displayPath));
21134
+ if (state === "unreadable") parts2.push(W.unreadable(displayPath, reason));
21135
+ const runs = shownRuns(write, omit);
21136
+ if (runs.length > 0) parts2.push(renderFileEvidence(displayPath, { totalLines, runs }).text);
21137
+ return parts2;
21138
+ }
21139
+ function renderCarried(source, wording) {
21019
21140
  const carried = [
21020
21141
  ...source.paths.flatMap(entryParts),
21021
- ...(source.skills ?? []).filter((skill) => skill.removed !== true).map((skill) => CARRIER_WORDING.skill(skill.name, skill.text))
21142
+ ...(source.skills ?? []).filter((skill) => skill.removed !== true).map((skill) => CARRIED_WORDING.skill(skill.name, skill.text))
21022
21143
  ];
21023
- return carried.length > 0 ? [CARRIER_WORDING.carried, ...carried].join("\n\n") : null;
21144
+ return carried.length > 0 ? [carriedNote(wording), ...carried].join("\n\n") : null;
21024
21145
  }
21025
21146
  function showsChange(entry) {
21026
21147
  const { state, write = [], withdraw = [] } = entry;
@@ -21039,64 +21160,18 @@ function carriedEvidence(source) {
21039
21160
  const skills = (source.skills ?? []).map((skill) => skill.removed === true ? { name: skill.name, removed: true } : { name: skill.name, text: skill.text });
21040
21161
  return files.length + removed.length + skills.length > 0 ? { files, removed, skills } : null;
21041
21162
  }
21042
- var isTodoItem = (item) => item !== null && typeof item === "object" && typeof item.content === "string" && typeof item.status === "string";
21043
- function todoItemsOf(value) {
21044
- if (value === null) return [];
21045
- if (!Array.isArray(value) || !value.every(isTodoItem)) throw new Error("the todo list is neither null nor a list of items with a content text and a status text");
21046
- return value.map(({ content, status }) => ({ content, status }));
21047
- }
21048
- function textEntriesOf(value, fields, what) {
21049
- if (!Array.isArray(value) || !value.every((entry) => entry !== null && typeof entry === "object" && fields.every((field) => typeof entry[field] === "string"))) {
21050
- throw new Error(`the ${what} is not a list of entries with ${fields.join(" and ")} texts`);
21051
- }
21052
- return value.map((entry) => Object.fromEntries(fields.map((field) => [field, entry[field]])));
21053
- }
21054
- var sameEntries = (fields, a, b) => a.length === b.length && a.every((entry, at) => fields.every((field) => entry[field] === b[at][field]));
21055
- var AGENT_FIELDS = ["id", "label"];
21056
- var TODO_FIELDS = ["content", "status"];
21057
- var STATE_ITEMS = Object.freeze([
21058
- Object.freeze({
21059
- key: "workingDirectory",
21060
- tool: "working_directory",
21061
- normalize: (value) => {
21062
- if (typeof value !== "string" || value === "") throw new Error("the working directory is not a path text");
21063
- return value;
21064
- },
21065
- isEmpty: () => false,
21066
- same: (a, b) => a === b,
21067
- text: (value) => value
21068
- }),
21069
- Object.freeze({
21070
- key: "subagents",
21071
- tool: "list_agents",
21072
- normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "subagent list"),
21073
- isEmpty: (entries) => entries.length === 0,
21074
- same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
21075
- text: CARRIER_WORDING.stateList
21076
- }),
21077
- Object.freeze({
21078
- key: "jobs",
21079
- tool: "job_list",
21080
- normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "job list"),
21081
- isEmpty: (entries) => entries.length === 0,
21082
- same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
21083
- text: CARRIER_WORDING.stateList
21084
- }),
21085
- Object.freeze({
21086
- key: "todos",
21087
- tool: "todo_write",
21088
- normalize: todoItemsOf,
21089
- isEmpty: (items) => items.length === 0,
21090
- same: (a, b) => sameEntries(TODO_FIELDS, a, b),
21091
- text: (items) => JSON.stringify(items)
21092
- })
21093
- ]);
21163
+
21164
+ // lib/inner-seal/state-block.js
21165
+ var STATE_WORDING = {
21166
+ heading: (seq) => `Session state as of session seq ${seq}:`,
21167
+ unchanged: "unchanged since the last summary that shows it",
21168
+ empty: "(empty)"
21169
+ };
21094
21170
  var checkedCut = (asOfSeq) => {
21095
21171
  if (!Number.isSafeInteger(asOfSeq)) throw new Error("the session state names no session seq as its cut");
21096
21172
  return asOfSeq;
21097
21173
  };
21098
21174
  function shownIn(source, { key }) {
21099
- if (source.kind !== INNER_SEAL_KIND) return void 0;
21100
21175
  return Object.hasOwn(source.state?.items ?? {}, key) ? { value: source.state.items[key].value } : void 0;
21101
21176
  }
21102
21177
  function carryItem(item, value, earlier) {
@@ -21105,12 +21180,12 @@ function carryItem(item, value, earlier) {
21105
21180
  if (last === void 0) return item.isEmpty(current) ? null : { value: current };
21106
21181
  return !item.isEmpty(current) && item.same(current, item.normalize(last.value)) ? { value: current, unchanged: true } : { value: current };
21107
21182
  }
21108
- function carryState({ asOfSeq, items }, { tools, earlier, failed: failed2 }) {
21183
+ function carryState({ asOfSeq, items }, { stateItems, tools, earlier, failed: failed2 }) {
21109
21184
  checkedCut(asOfSeq);
21110
21185
  const shown = {};
21111
- for (const item of STATE_ITEMS) {
21186
+ for (const item of stateItems) {
21112
21187
  const read = items[item.key];
21113
- if (read === void 0 || !tools.has(item.tool)) continue;
21188
+ if (read === void 0 || item.tool !== void 0 && !tools.has(item.tool)) continue;
21114
21189
  try {
21115
21190
  const carried = carryItem(item, read(), earlier);
21116
21191
  if (carried !== null) shown[item.key] = carried;
@@ -21120,37 +21195,67 @@ function carryState({ asOfSeq, items }, { tools, earlier, failed: failed2 }) {
21120
21195
  }
21121
21196
  return Object.keys(shown).length === 0 ? null : { asOfSeq, items: shown };
21122
21197
  }
21123
- function renderState({ asOfSeq, items }) {
21124
- const W = CARRIER_WORDING;
21125
- const lines = STATE_ITEMS.filter(({ key }) => Object.hasOwn(items, key)).map((item) => {
21198
+ function renderState({ asOfSeq, items }, stateItems) {
21199
+ const W = STATE_WORDING;
21200
+ const lines = stateItems.filter(({ key }) => Object.hasOwn(items, key)).map((item) => {
21126
21201
  const { value, unchanged = false } = items[item.key];
21127
21202
  const shown = item.normalize(value);
21128
- return `${W.stateLabels[item.key](item.tool)} ${item.isEmpty(shown) ? W.stateEmpty : unchanged ? W.stateUnchanged : item.text(shown)}`;
21203
+ if (item.isEmpty(shown)) return `${item.label} ${W.empty}`;
21204
+ if (unchanged) return `${item.label} ${W.unchanged}`;
21205
+ return `${item.label}${item.multiline === true ? "\n" : " "}${item.text(shown)}`;
21129
21206
  });
21130
- return [W.stateHeading(checkedCut(asOfSeq)), ...lines].join("\n");
21207
+ return [W.heading(checkedCut(asOfSeq)), ...lines].join("\n");
21208
+ }
21209
+
21210
+ // lib/inner-seal/carrier.js
21211
+ var INNER_SEAL_KIND = "session-watcher-inner-seal";
21212
+ var sourceEventSeqsOf = ({ callSeq, pruneSeq, replaced }) => [callSeq, pruneSeq, ...replaced];
21213
+ var callSeqOf = (seqs) => seqs[0];
21214
+ function assembleCarrierSource({ slots, summaries, questions, attachments, oldReads = [], verbatimSeqs = [], changes, state }) {
21215
+ const injected = [.../* @__PURE__ */ new Set([...verbatimSeqs, ...questions.flat().flatMap(({ seqs }) => seqs ?? [])])];
21216
+ return {
21217
+ kind: INNER_SEAL_KIND,
21218
+ v: 1,
21219
+ slots: slots.map(({ seqs }, index) => ({
21220
+ seqs,
21221
+ text: summaries[index],
21222
+ ...questions[index].length > 0 ? { questions: questions[index].map(({ question, user }) => ({ question, user })) } : {},
21223
+ ...attachments[index].length > 0 ? { attachments: attachments[index] } : {},
21224
+ ...oldReads[index]?.length > 0 ? { oldReads: oldReads[index] } : {}
21225
+ })),
21226
+ ...injected.length > 0 ? { verbatimSeqs: injected } : {},
21227
+ ...changes,
21228
+ ...state === null ? {} : { state }
21229
+ };
21131
21230
  }
21132
- function renderCarrier(source) {
21231
+ var CARRIER_WORDING = {
21232
+ slotLine: (seqs) => `seq ${seqs.join(", ")}: `,
21233
+ imageSaved: (name3, tool) => `The image ${name3} is not in the current context; ${tool} can read the file below when it is needed.`,
21234
+ questionMark: "A line marked question: holds the question as it was asked, and the user: line under it the user's whole answer.",
21235
+ questionLine: (question) => `question: ${question}`,
21236
+ userLine: (user) => `user: ${user}`
21237
+ };
21238
+ function renderCarrier(source, wording) {
21133
21239
  const W = CARRIER_WORDING;
21134
21240
  const blocks = [];
21135
- let lines = [source.slots.some(({ questions }) => questions !== void 0) ? `${W.addresses} ${W.questionMark}` : W.addresses];
21241
+ let lines = [source.slots.some(({ questions }) => questions !== void 0) ? `${wording.addresses} ${W.questionMark}` : wording.addresses];
21136
21242
  const flush = () => {
21137
21243
  if (lines.length > 0) blocks.push({ type: "text", text: lines.join("\n") });
21138
21244
  lines = [];
21139
21245
  };
21140
- for (const { seqs, text, questions = [], asks = [], attachments = [] } of source.slots) {
21246
+ for (const { seqs, text, questions = [], attachments = [] } of source.slots) {
21141
21247
  lines.push(`${W.slotLine(seqs)}${text}`);
21142
21248
  for (const { question, user } of questions) lines.push(W.questionLine(question), W.userLine(user));
21143
- for (const { call, result } of asks) lines.push(W.askCall(call), W.askResult(call.id, result));
21144
21249
  for (const { file, image } of attachments) {
21145
- if (image !== void 0) lines.push(W.imageSaved(image.name ?? image.attachmentId));
21250
+ if (image !== void 0) lines.push(W.imageSaved(image.name ?? image.attachmentId, wording.imageReadTool));
21146
21251
  flush();
21147
21252
  blocks.push({ type: "file", attachment: file });
21148
21253
  }
21149
21254
  }
21150
21255
  flush();
21151
- const carried = renderCarried(source);
21256
+ const carried = renderCarried(source, wording);
21152
21257
  const carriedBlock = carried === null ? null : { type: "text", text: carried };
21153
- const stateBlock = Object.hasOwn(source, "state") ? { type: "text", text: renderState(source.state) } : null;
21258
+ const stateBlock = Object.hasOwn(source, "state") ? { type: "text", text: renderState(source.state, wording.stateItems) } : null;
21154
21259
  for (const block of [carriedBlock, stateBlock]) if (block !== null) blocks.push(block);
21155
21260
  return blocks.map((block, index) => {
21156
21261
  if (block.type !== "text") return block;
@@ -21213,6 +21318,10 @@ function usageOf(usage) {
21213
21318
  cacheWrite: usage.cacheWriteTokens ?? 0
21214
21319
  };
21215
21320
  }
21321
+ function dispatchedCallIdOf(event) {
21322
+ const data = event?.type === "tool/call" ? event.data : void 0;
21323
+ return isIndex(data?.turn) && isIndex(data?.step) && isId2(data?.callId) ? callIdOf(data.turn, data.step, data.callId) : null;
21324
+ }
21216
21325
  function callUsageOf(usage) {
21217
21326
  return isUsage(usage) ? usageOf(usage) : null;
21218
21327
  }
@@ -21287,7 +21396,7 @@ function reduceLoadMessage(event) {
21287
21396
  function reduceInnerSeal(event) {
21288
21397
  const seqs = event.sourceEventSeqs;
21289
21398
  if (!Array.isArray(seqs) || !seqs.every(isIndex)) return violation(event, "sourceEventSeqs");
21290
- return { observations: [], diagnostics: [], withdraws: seqs };
21399
+ return { observations: [], diagnostics: [], sealed: seqs };
21291
21400
  }
21292
21401
  function reduceUserMessage(event) {
21293
21402
  const kind = event.data?.source?.kind;
@@ -21385,6 +21494,10 @@ function reduceDshEvent(event) {
21385
21494
  return nothing();
21386
21495
  }
21387
21496
  }
21497
+ var isMainCall = (event) => event.type === "assistant/message" && isIndex(event.seq);
21498
+ function foldInputOf(event) {
21499
+ return { ...reduceDshEvent(event), seq: event.seq, mainCall: isMainCall(event) };
21500
+ }
21388
21501
  function reduceDshSnapshot(events) {
21389
21502
  const batches = [];
21390
21503
  const diagnostics = [];
@@ -21395,6 +21508,15 @@ function reduceDshSnapshot(events) {
21395
21508
  }
21396
21509
  return { batches, observations: batches.flat(), diagnostics };
21397
21510
  }
21511
+ var stepKeyOf = (data) => isIndex(data?.turn) && isIndex(data?.step) ? `${data.turn}:${data.step}` : null;
21512
+ function heldObservationsOf(events) {
21513
+ return events.flatMap((event) => {
21514
+ const stepKey3 = stepKeyOf(event.data);
21515
+ if (event.type === "step/start") return stepKey3 === null ? [] : [{ type: "step-start", stepKey: stepKey3 }];
21516
+ const { observations } = reduceDshEvent(event);
21517
+ return event.type === "tool/result" ? observations.map((observation) => ({ ...observation, stepKey: stepKey3 })) : observations;
21518
+ });
21519
+ }
21398
21520
 
21399
21521
  // lib/harness/dsh/dialogue-source.js
21400
21522
  function createDshDialogueSource({ readSession }) {
@@ -21411,6 +21533,25 @@ function createDshDialogueSource({ readSession }) {
21411
21533
  };
21412
21534
  }
21413
21535
 
21536
+ // lib/harness/dsh/ask-result.js
21537
+ function askAnswersOf(resultText) {
21538
+ let value;
21539
+ try {
21540
+ value = JSON.parse(resultText);
21541
+ } catch {
21542
+ return [];
21543
+ }
21544
+ if (!Array.isArray(value?.answers)) return [];
21545
+ const answers = [];
21546
+ for (const answer of value.answers) {
21547
+ const { id, selected, custom } = answer ?? {};
21548
+ if (!Array.isArray(selected) || !selected.every((label) => typeof label === "string")) return [];
21549
+ if (custom !== void 0 && typeof custom !== "string") return [];
21550
+ answers.push(custom === void 0 ? { id, selected } : { id, selected, custom });
21551
+ }
21552
+ return answers;
21553
+ }
21554
+
21414
21555
  // lib/harness/dsh/history-turn-rules.js
21415
21556
  function createDshHumanHeadRule() {
21416
21557
  return (line) => {
@@ -21420,25 +21561,11 @@ function createDshHumanHeadRule() {
21420
21561
  };
21421
21562
  }
21422
21563
  var ASK_TOOL_NAME = "ask_user_question";
21423
- function answerText(result) {
21424
- let value;
21425
- try {
21426
- value = JSON.parse(result);
21427
- } catch {
21428
- return "";
21429
- }
21430
- const lines = [];
21431
- for (const answer of Array.isArray(value?.answers) ? value.answers : []) {
21432
- if (Array.isArray(answer?.selected)) lines.push(...answer.selected);
21433
- if (answer?.custom) lines.push(answer.custom);
21434
- }
21435
- return lines.join("\n");
21436
- }
21437
21564
  function createDshAskHeadRule() {
21438
21565
  return (line) => {
21439
21566
  if (line.kind !== "tool" || line.tool.name !== ASK_TOOL_NAME) return PASS;
21440
21567
  if (line.tool.isError === true) return ABSORB;
21441
- const text = answerText(line.tool.result).trim();
21568
+ const text = askAnswersOf(line.tool.result).flatMap(({ selected, custom }) => custom ? [...selected, custom] : selected).join("\n").trim();
21442
21569
  return text === "" ? ABSORB : { kind: "HEAD", text };
21443
21570
  };
21444
21571
  }
@@ -21962,11 +22089,6 @@ function composeWatcher({
21962
22089
  resourceKeysOf,
21963
22090
  modelPolicyFor: policyFor
21964
22091
  });
21965
- const heldView = heldViewOf({ sessionId, cwd, store, policyFor, interpretToolUse, completeToolResult });
21966
- return { watcher, dialogueSource, dialogueProjection, heldView };
21967
- }
21968
- var SELECTED = () => ({ selectedByDefault: true, defaultDiscardReason: null });
21969
- function heldViewOf({ sessionId, cwd, store, policyFor, interpretToolUse, completeToolResult }) {
21970
22092
  const recall = (toolUseId) => {
21971
22093
  try {
21972
22094
  return store.recallAttribution(sessionId, toolUseId);
@@ -21974,41 +22096,20 @@ function heldViewOf({ sessionId, cwd, store, policyFor, interpretToolUse, comple
21974
22096
  return null;
21975
22097
  }
21976
22098
  };
21977
- const frameCtx = sessionId ? { recall } : {};
21978
- return (events, range) => {
21979
- const inRange = new Set(range);
21980
- const touched = { paths: /* @__PURE__ */ new Set(), skills: /* @__PURE__ */ new Set() };
21981
- let completed = [];
21982
- const projection = createDshMeasurementProjection({
22099
+ const view = createHeldView({
22100
+ createProjection: ({ completeToolResult: recording }) => createDshMeasurementProjection({
21983
22101
  cwd,
21984
22102
  projectRoot: cwd,
21985
22103
  resolveModelPolicy: policyFor,
21986
22104
  interpretToolUse,
21987
- completeToolResult: (pending, observation, context, options) => {
21988
- const answer = completeToolResult(pending, observation, context, options);
21989
- completed.push({ effects: answer.effects, text: observation.content, seq: observation.sourceOrdinal });
21990
- return answer;
21991
- }
21992
- });
21993
- const engine = createMeasurementEngine({ resolveModelPolicy: policyFor, resolveResourcePolicy: SELECTED });
21994
- let skills = /* @__PURE__ */ new Map();
21995
- for (const observation of reduceDshSnapshot(events).observations) {
21996
- completed = [];
21997
- const { records } = projection.project(observation, frameCtx);
21998
- engine.ingest(records.filter((record) => record.type === "effect" || record.type === "epoch"));
21999
- if (records.some((record) => record.type === "epoch")) skills = /* @__PURE__ */ new Map();
22000
- for (const { effects, text, seq } of completed) {
22001
- for (const { resourceKey } of effects.flatMap((effect) => effect.impacts)) {
22002
- const isSkill = resourceKey.startsWith(SKILL_RESOURCE_PREFIX);
22003
- const key = isSkill ? resourceKey.slice(SKILL_RESOURCE_PREFIX.length) : resourceKey;
22004
- if (isSkill) skills.set(key, text);
22005
- if (inRange.has(seq)) touched[isSkill ? "skills" : "paths"].add(key);
22006
- }
22007
- }
22008
- }
22009
- const paths = new Map([...engine.heldLines()].filter(([key]) => !key.startsWith(SKILL_RESOURCE_PREFIX)));
22010
- return { paths, skills, touched };
22011
- };
22105
+ completeToolResult: recording
22106
+ }),
22107
+ completeToolResult,
22108
+ resolveModelPolicy: policyFor,
22109
+ frameCtx: sessionId ? { recall } : {}
22110
+ });
22111
+ const heldView = (events) => view(heldObservationsOf(events));
22112
+ return { watcher, dialogueSource, dialogueProjection, heldView };
22012
22113
  }
22013
22114
 
22014
22115
  // dsh/src/observed-read.js
@@ -22045,33 +22146,31 @@ async function readUnobserved({ fs: fs3, tree, key, ranges, fileBytes, signal })
22045
22146
  return { read: readTreeWindows(tree, key, ranges, { fileBytes }), displayPath };
22046
22147
  }
22047
22148
 
22048
- // lib/harness/dsh/source-facts.js
22149
+ // lib/measurement/source-facts.js
22049
22150
  function initialSourceFacts() {
22050
22151
  return { epoch: 0, headDone: false, points: [], carriers: [] };
22051
22152
  }
22052
- var isCarrier = (reduced) => Array.isArray(reduced.withdraws);
22053
- var usageOf2 = (reduced) => reduced.observations.find((observation) => observation.type === "usage")?.usage ?? null;
22054
- var stockOf = ({ input, cacheRead, cacheWrite }) => input + cacheRead + cacheWrite;
22055
- var startsEpoch = (reduced) => reduced.observations.some((observation) => observation.type === "epoch-boundary");
22056
- function withCarrier(facts, event, reduced) {
22057
- const listed = new Set(reduced.withdraws);
22153
+ var isCarrier = (input) => Array.isArray(input.sealed);
22154
+ var usageOf2 = (input) => input.observations.find((observation) => observation.type === "usage")?.usage ?? null;
22155
+ var startsEpoch = ({ observations }) => observations.some((observation) => observation.type === "epoch-boundary");
22156
+ function withCarrier(facts, input) {
22157
+ const listed = new Set(input.sealed);
22058
22158
  return {
22059
22159
  ...facts,
22060
22160
  points: facts.points.filter((point) => point.role !== "current" || !listed.has(point.seq)),
22061
- carriers: [...facts.carriers, { seq: event.seq, epoch: facts.epoch, post: null }]
22161
+ carriers: [...facts.carriers, { seq: input.seq, epoch: facts.epoch, post: null }]
22062
22162
  };
22063
22163
  }
22064
- function withMainCall(facts, event, reduced) {
22065
- const usage = usageOf2(reduced);
22164
+ function withMainCall(facts, input) {
22165
+ const usage = usageOf2(input);
22066
22166
  const waiting = facts.carriers.some((carrier) => carrier.epoch === facts.epoch && carrier.post === null);
22067
- const carriers = waiting ? facts.carriers.map((carrier) => carrier.epoch === facts.epoch && carrier.post === null ? { ...carrier, post: { seq: event.seq, usage } } : carrier) : facts.carriers;
22167
+ const carriers = waiting ? facts.carriers.map((carrier) => carrier.epoch === facts.epoch && carrier.post === null ? { ...carrier, post: { seq: input.seq, usage } } : carrier) : facts.carriers;
22068
22168
  if (usage === null) return waiting ? { ...facts, carriers } : facts;
22069
22169
  const role = facts.headDone ? waiting ? "post" : "current" : "head";
22070
- return { ...facts, headDone: facts.headDone || stockOf(usage) > 0, points: [...facts.points, { seq: event.seq, role }], carriers };
22170
+ return { ...facts, headDone: facts.headDone || stockOf(usage) > 0, points: [...facts.points, { seq: input.seq, role }], carriers };
22071
22171
  }
22072
22172
  var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
22073
22173
  var isIndex2 = (value) => Number.isSafeInteger(value) && value >= 0;
22074
- var isMainCall = (event) => event.type === "assistant/message" && isIndex2(event.seq);
22075
22174
  var isUsage2 = (value) => isObject3(value) && ["input", "output", "cacheRead", "cacheWrite"].every((field) => Number.isFinite(value[field]));
22076
22175
  var isPost = (value) => value === null || isObject3(value) && isIndex2(value.seq) && (value.usage === null || isUsage2(value.usage));
22077
22176
  function qualifiedCalls(facts) {
@@ -22081,16 +22180,16 @@ function qualifiedCalls(facts) {
22081
22180
  function isSourceFacts(value) {
22082
22181
  return isObject3(value) && isIndex2(value.epoch) && typeof value.headDone === "boolean" && Array.isArray(value.points) && value.points.every((point) => isObject3(point) && isIndex2(point.seq) && ["head", "post", "current"].includes(point.role)) && Array.isArray(value.carriers) && value.carriers.every((carrier) => isObject3(carrier) && isIndex2(carrier.seq) && isIndex2(carrier.epoch) && isPost(carrier.post));
22083
22182
  }
22084
- function foldSourceFacts(facts, event, reduced = reduceDshEvent(event)) {
22085
- if (!isIndex2(event.seq)) return facts;
22086
- if (startsEpoch(reduced)) return { ...facts, epoch: facts.epoch + 1, headDone: false, points: [] };
22087
- if (isCarrier(reduced)) return withCarrier(facts, event, reduced);
22088
- if (isMainCall(event)) return withMainCall(facts, event, reduced);
22183
+ function foldSourceFacts(facts, input) {
22184
+ if (!isIndex2(input.seq)) return facts;
22185
+ if (startsEpoch(input)) return { ...facts, epoch: facts.epoch + 1, headDone: false, points: [] };
22186
+ if (isCarrier(input)) return withCarrier(facts, input);
22187
+ if (input.mainCall) return withMainCall(facts, input);
22089
22188
  return facts;
22090
22189
  }
22091
22190
 
22092
- // lib/harness/dsh/source-fold.js
22093
- function withdrawn(batch, selected) {
22191
+ // lib/measurement/source-fold.js
22192
+ function sealedBatch(batch, selected) {
22094
22193
  return batch.flatMap((observation) => {
22095
22194
  if (observation.type === "tool-result") return [observation.effectsOnly ? observation : { ...observation, effectsOnly: true }];
22096
22195
  if (observation.type === "usage") return selected ? [observation] : [];
@@ -22098,30 +22197,29 @@ function withdrawn(batch, selected) {
22098
22197
  });
22099
22198
  }
22100
22199
  var changed = (before, after) => before.length !== after.length || before.some((observation, index) => observation !== after[index]);
22101
- function createDshSourceFold() {
22200
+ function createSourceFold() {
22102
22201
  const kept = [];
22103
22202
  let epochStart = 0;
22104
22203
  let facts = initialSourceFacts();
22105
- function push(event) {
22106
- const reduced = reduceDshEvent(event);
22107
- const { observations, diagnostics, withdraws = [] } = reduced;
22108
- facts = foldSourceFacts(facts, event, reduced);
22204
+ function push(input) {
22205
+ const { observations, diagnostics, sealed = [] } = input;
22206
+ facts = foldSourceFacts(facts, input);
22109
22207
  let rewound = false;
22110
- if (withdraws.length > 0) {
22111
- const listed = new Set(withdraws);
22208
+ if (sealed.length > 0) {
22209
+ const listed = new Set(sealed);
22112
22210
  const selected = new Set(facts.points.map((point) => point.seq));
22113
22211
  for (let index = epochStart; index < kept.length; index += 1) {
22114
22212
  if (!listed.has(kept[index].seq)) continue;
22115
- const next = withdrawn(kept[index].batch, selected.has(kept[index].seq));
22213
+ const next = sealedBatch(kept[index].batch, selected.has(kept[index].seq));
22116
22214
  if (!changed(kept[index].batch, next)) continue;
22117
22215
  kept[index].batch = next;
22118
22216
  rewound = true;
22119
22217
  }
22120
22218
  }
22121
- const batch = isMainCall(event) ? [{ type: "main-call", sourceOrdinal: event.seq }, ...observations] : observations;
22219
+ const batch = input.mainCall ? [{ type: "main-call", sourceOrdinal: input.seq }, ...observations] : observations;
22122
22220
  if (batch.length === 0) return { batch: null, rewound, diagnostics };
22123
22221
  if (batch.some((observation) => observation.type === "epoch-boundary")) epochStart = kept.length;
22124
- kept.push({ seq: event.seq, batch });
22222
+ kept.push({ seq: input.seq, batch });
22125
22223
  return { batch, rewound, diagnostics };
22126
22224
  }
22127
22225
  function batches() {
@@ -22137,7 +22235,7 @@ function invariant5(ok, message) {
22137
22235
  function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () => false } = {}) {
22138
22236
  invariant5(typeof onDiagnostics === "function", "onDiagnostics must be a function");
22139
22237
  const queue = [];
22140
- const fold = createDshSourceFold();
22238
+ const fold = createSourceFold();
22141
22239
  let installed = false;
22142
22240
  let drained = false;
22143
22241
  let snapshotTail;
@@ -22153,7 +22251,7 @@ function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () =>
22153
22251
  captureMode: "replay"
22154
22252
  });
22155
22253
  function liveFrame(event) {
22156
- const { batch, rewound, diagnostics } = fold.push(event);
22254
+ const { batch, rewound, diagnostics } = fold.push(foldInputOf(event));
22157
22255
  report(diagnostics);
22158
22256
  if (rewound) return replayFrame();
22159
22257
  if (batch === null) return null;
@@ -22161,7 +22259,7 @@ function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () =>
22161
22259
  }
22162
22260
  function install(snapshotEvents) {
22163
22261
  invariant5(!installed, "install runs once");
22164
- const diagnostics = snapshotEvents.flatMap((event) => fold.push(event).diagnostics);
22262
+ const diagnostics = snapshotEvents.flatMap((event) => fold.push(foldInputOf(event)).diagnostics);
22165
22263
  installed = true;
22166
22264
  snapshotTail = snapshotEvents.length === 0 ? -1 : snapshotEvents.at(-1).seq;
22167
22265
  report(diagnostics);
@@ -22186,90 +22284,38 @@ function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () =>
22186
22284
  return { install, feed, drain };
22187
22285
  }
22188
22286
 
22189
- // lib/harness/dsh/inner-source.js
22287
+ // lib/harness/dsh/event-facts.js
22190
22288
  var CHECKPOINT_KIND = "compact-checkpoint";
22191
22289
  var TURN_SKELETON_TOOL = "get_turn_skeleton";
22192
- var stepKey = ({ turn, step }) => `${turn}:${step}`;
22193
- function sourceFactOf(event) {
22290
+ function markerOf(source) {
22291
+ if (source?.kind === INNER_SEAL_KIND) return "carrier";
22292
+ if (source?.kind === CHECKPOINT_KIND) return "checkpoint";
22293
+ return isLoadPayload(source) ? "payload" : null;
22294
+ }
22295
+ function eventFactOf(event) {
22194
22296
  const message = event.data?.message ?? event.data;
22195
- const blocks = event.type === "assistant/message" && Array.isArray(message?.content) ? message.content : [];
22297
+ const assistant = event.type === "assistant/message";
22298
+ const blocks = assistant && Array.isArray(message?.content) ? message.content : [];
22299
+ const marker = event.type === "user/message" ? markerOf(message?.source) : null;
22196
22300
  return {
22197
- type: event.type,
22198
- kind: message?.source?.kind ?? null,
22199
- payload: isLoadPayload(message?.source),
22200
- epoch: message?.source?.kind === CHECKPOINT_KIND && startsEpoch(reduceDshEvent(event)),
22301
+ system: event.type === "system/message",
22302
+ header: event.type === "request/header",
22303
+ marker,
22304
+ epoch: marker === "checkpoint" && startsEpoch(reduceDshEvent(event)),
22201
22305
  step: blocks.length > 0 ? { turn: event.data.turn, step: event.data.step } : null,
22306
+ owner: { turn: event.data?.turn, step: event.data?.step },
22307
+ assistant,
22202
22308
  skeletonCall: blocks.some((block) => block?.type === "tool-call" && block.name === TURN_SKELETON_TOOL)
22203
22309
  };
22204
22310
  }
22205
- function headerSeq(facts, latest, above = -1) {
22206
- let found = null;
22207
- for (const [seq, fact] of facts) {
22208
- if (fact.type === "request/header" && seq > above && (found === null || (latest ? seq > found : seq < found))) found = seq;
22209
- }
22210
- return found;
22211
- }
22212
- function initialPrefixLength(facts, nodes) {
22213
- let length = nodes.length > 0 && facts.get(nodes[0]).type === "system/message" ? 1 : 0;
22214
- let opened = -1;
22215
- nodes.forEach((seq, index) => {
22216
- if (facts.get(seq).epoch && seq > opened) {
22217
- opened = seq;
22218
- length = Math.max(length, index + 1);
22219
- }
22220
- });
22221
- const first = headerSeq(facts, false, opened);
22222
- if (first === null) return length;
22223
- while (length < nodes.length && nodes[length] > opened && nodes[length] < first) length += 1;
22224
- return length;
22225
- }
22226
- function innerSource(facts, nodes) {
22227
- const prefix = initialPrefixLength(facts, nodes);
22228
- let at = -1;
22229
- nodes.forEach((seq, index) => {
22230
- const { kind, payload } = facts.get(seq);
22231
- const marker = kind === INNER_SEAL_KIND || kind === CHECKPOINT_KIND || payload && index >= prefix;
22232
- if (marker && (at < 0 || seq > nodes[at])) at = index;
22233
- });
22234
- const range = nodes.slice(Math.max(prefix, at + 1));
22235
- const steps = new Set(range.map((seq) => facts.get(seq).step).filter((step) => step !== null).map(stepKey));
22236
- const lastCall = range.findLastIndex((seq) => facts.get(seq).skeletonCall);
22237
- const lastPayload = range.findLastIndex((seq) => facts.get(seq).payload);
22238
- return { frontier: at < 0 ? null : nodes[at], range, stepN: steps.size, paused: lastCall > lastPayload };
22239
- }
22240
- function headerSeqOf(facts) {
22241
- return headerSeq(facts, true);
22242
- }
22243
22311
  var isPrunedResult = (event) => event.type === "tool/result" && event.surfaceOp?.op === "replace";
22244
22312
  var originalsOf = (event, bySeq) => event.sourceEventSeqs.flatMap((seq) => {
22245
22313
  const cited = bySeq.get(seq);
22246
22314
  return isPrunedResult(cited) ? originalsOf(cited, bySeq) : [seq];
22247
22315
  });
22248
- function prunedOriginals(events, seqs) {
22249
- const bySeq = new Map(events.map((event) => [event.seq, event]));
22250
- return seqs.flatMap((seq) => isPrunedResult(bySeq.get(seq)) ? originalsOf(bySeq.get(seq), bySeq) : []);
22251
- }
22252
- function skeletonSlots(events, nodes, range) {
22316
+ function eventFactsOf(events) {
22253
22317
  const bySeq = new Map(events.map((event) => [event.seq, event]));
22254
- const selected = new Set(range);
22255
- const sources = nodes.filter((seq) => selected.has(seq)).map((seq) => bySeq.get(seq));
22256
- const counted = new Set(sources.map((event) => sourceFactOf(event).step).filter((step) => step !== null).map(stepKey));
22257
- const slots = [];
22258
- const stepSlots = /* @__PURE__ */ new Map();
22259
- for (const event of sources) {
22260
- const key = stepKey(event.data);
22261
- const seqs = [...isPrunedResult(event) ? originalsOf(event, bySeq) : [], event.seq];
22262
- if (!counted.has(key)) {
22263
- if (event.type !== "assistant/message") slots.push({ seqs });
22264
- } else if (stepSlots.has(key)) {
22265
- stepSlots.get(key).seqs.push(...seqs);
22266
- } else {
22267
- const slot = { seqs, step: { turn: event.data.turn, step: event.data.step } };
22268
- stepSlots.set(key, slot);
22269
- slots.push(slot);
22270
- }
22271
- }
22272
- return slots;
22318
+ return new Map(events.map((event) => [event.seq, { ...eventFactOf(event), originals: isPrunedResult(event) ? originalsOf(event, bySeq) : [] }]));
22273
22319
  }
22274
22320
 
22275
22321
  // lib/ledger-schema.js
@@ -22705,7 +22751,7 @@ function createWatcherTable({
22705
22751
  }) {
22706
22752
  const entries = /* @__PURE__ */ new Map();
22707
22753
  const listeners = /* @__PURE__ */ new Set();
22708
- let closed2 = false;
22754
+ let closed = false;
22709
22755
  function notify(sessionId) {
22710
22756
  for (const listener of listeners) {
22711
22757
  try {
@@ -22781,7 +22827,7 @@ function createWatcherTable({
22781
22827
  fail(entry, hostDiagnostic("read_session_rejected", error));
22782
22828
  return;
22783
22829
  }
22784
- for (const event of snapshot.events) entry.facts.set(event.seq, sourceFactOf(event));
22830
+ for (const event of snapshot.events) entry.facts.set(event.seq, eventFactOf(event));
22785
22831
  entry.sourceReady = true;
22786
22832
  await modelNames.warm(modelNames.pairsOf([...snapshot.events, ...entry.pending]));
22787
22833
  if (entry.state !== "bootstrapping") return;
@@ -22805,7 +22851,7 @@ function createWatcherTable({
22805
22851
  }
22806
22852
  }
22807
22853
  function ensure(session) {
22808
- if (closed2) throw new Error("the watcher table is closed");
22854
+ if (closed) throw new Error("the watcher table is closed");
22809
22855
  const sessionId = session.id;
22810
22856
  if (entries.has(sessionId)) return;
22811
22857
  const entry = {
@@ -22837,7 +22883,7 @@ function createWatcherTable({
22837
22883
  function feed(sessionId, event) {
22838
22884
  const entry = entries.get(sessionId);
22839
22885
  if (entry === void 0) return;
22840
- entry.facts.set(event.seq, sourceFactOf(event));
22886
+ entry.facts.set(event.seq, eventFactOf(event));
22841
22887
  if (entry.state !== "bootstrapping" && entry.state !== "live") return;
22842
22888
  if (event.type === "request/header") void modelNames.warm(modelNames.pairsOf([event]));
22843
22889
  let frame = null;
@@ -22870,7 +22916,7 @@ function createWatcherTable({
22870
22916
  }
22871
22917
  }
22872
22918
  function disposeAll() {
22873
- closed2 = true;
22919
+ closed = true;
22874
22920
  for (const sessionId of [...entries.keys()]) {
22875
22921
  try {
22876
22922
  dispose(sessionId);
@@ -22905,15 +22951,15 @@ function createWatcherTable({
22905
22951
  function onChange(listener) {
22906
22952
  listeners.add(listener);
22907
22953
  }
22908
- function sourceFacts(sessionId) {
22954
+ function eventFacts(sessionId) {
22909
22955
  const entry = entries.get(sessionId);
22910
22956
  return entry?.sourceReady ? entry.facts : null;
22911
22957
  }
22912
- function heldView(sessionId, events, range) {
22958
+ function heldView(sessionId, events) {
22913
22959
  const entry = entries.get(sessionId);
22914
- return entry === void 0 ? null : entry.heldView(events, range);
22960
+ return entry === void 0 ? null : entry.heldView(events);
22915
22961
  }
22916
- return { ensure, feed, dispose, disposeAll, get, waitLive, live: live2, onChange, sourceFacts, heldView };
22962
+ return { ensure, feed, dispose, disposeAll, get, waitLive, live: live2, onChange, eventFacts, heldView };
22917
22963
  }
22918
22964
 
22919
22965
  // dsh/src/model-names.js
@@ -23196,6 +23242,14 @@ function pricingResponse({ model, saved, policy, cliRatio }) {
23196
23242
  presets
23197
23243
  };
23198
23244
  }
23245
+ var INVALID_BUCKET_FILE_MESSAGE = "Body must contain { path: string }";
23246
+ var NOT_HELD_MESSAGE = "The path is not held in the current context.";
23247
+ function heldFilePayload(path3, lineNumbers, workingTree, { fileBytes }) {
23248
+ const ranges = runsOf(lineNumbers).map(([first, last]) => ({ offset: first, limit: last - first + 1 }));
23249
+ const read = readTreeWindows(workingTree, path3, ranges, { fileBytes });
23250
+ if (read.status !== "readable") return { path: path3, reason: read.reason };
23251
+ return { path: path3, total: read.totalLines, runs: read.windows };
23252
+ }
23199
23253
  function turnPageWire({ turnPage, nextBefore }) {
23200
23254
  return {
23201
23255
  turn_page: turnPage,
@@ -23236,9 +23290,13 @@ var MONITOR_UNAVAILABLE = failure("inner_monitor_unavailable", "The inner compac
23236
23290
  var FORBIDDEN = failure("forbidden", "Only the owner of this host can manage the carrier cache.");
23237
23291
  var CARRIER_CACHE_UNAVAILABLE = failure("carrier_cache_unavailable", "The carrier cache switch is not available in this host.");
23238
23292
  var MONITOR_NOT_COMMITTED = failure("inner_monitor_not_committed", "The inner compaction attempt has no committed seal, so it has no slots.");
23293
+ var TARGET_FORBIDDEN = failure("forbidden", "Only the owner of this host can read the text of a recalled event.");
23294
+ var TARGET_NOT_RECALLED = failure("inner_monitor_not_recalled", "The event is not a recall target of this settlement at this cut.");
23295
+ var NO_CARRIER = { not_committed: MONITOR_NOT_COMMITTED };
23239
23296
  function createRpcHandler({
23240
23297
  table,
23241
23298
  store,
23299
+ workingTree,
23242
23300
  now = Date.now,
23243
23301
  publish = () => {
23244
23302
  },
@@ -23280,6 +23338,13 @@ function createRpcHandler({
23280
23338
  sessionId,
23281
23339
  now: now()
23282
23340
  })),
23341
+ // The held lines of one path, read from the host's working tree now; a path the watcher has no resource at is refused, so the endpoint reads no file the session never held.
23342
+ "bucket/file": ({ watcher }, { path: path3 }) => {
23343
+ if (typeof path3 !== "string") return failure("invalid_body", INVALID_BUCKET_FILE_MESSAGE);
23344
+ const lineNumbers = watcher.getHeldLines(path3);
23345
+ if (lineNumbers === null) return failure("not_held", NOT_HELD_MESSAGE);
23346
+ return live(heldFilePayload(path3, lineNumbers, workingTree, { fileBytes: ATTRIBUTION_LIMITS.fileBytes }));
23347
+ },
23283
23348
  "turn/browse": (_entry, { sessionId }) => {
23284
23349
  const { sections } = buildTurnBrowse({ store, lineage: forLoadedHandoff({ store, sessionId }) });
23285
23350
  return live({ sections });
@@ -23342,18 +23407,26 @@ function createRpcHandler({
23342
23407
  "inner-monitor/call": { addresses: ["attempt"], read: (access, { sessionId, attempt }) => access?.call(sessionId, attempt) },
23343
23408
  "inner-monitor/slots": { addresses: ["attempt"], read: (access, { sessionId, attempt }) => access?.slots(sessionId, attempt) },
23344
23409
  "inner-monitor/slot": { addresses: ["attempt", "slot"], read: (access, { sessionId, attempt, slot }) => access?.slot(sessionId, attempt, slot) },
23345
- "inner-monitor/handoff": { addresses: ["handoff"], read: (access, { sessionId, handoff }) => access?.handoff(sessionId, handoff) }
23410
+ "inner-monitor/handoff": { addresses: ["handoff"], read: (access, { sessionId, handoff }) => access?.handoff(sessionId, handoff) },
23411
+ "inner-monitor/settlement": { addresses: ["handoff"], read: (access, { sessionId, handoff }) => access?.settlement(sessionId, handoff) },
23412
+ "inner-monitor/settlement/current": { addresses: [], read: (access, { sessionId }) => access?.currentSettlement(sessionId) },
23413
+ "inner-monitor/settlement/target": {
23414
+ addresses: ["segment", "through", "seq"],
23415
+ owner: TARGET_FORBIDDEN,
23416
+ closed: { not_target: TARGET_NOT_RECALLED },
23417
+ read: (access, { sessionId, segment, through, seq }) => access?.settlementTarget(sessionId, { segment, through, seq })
23418
+ }
23346
23419
  };
23347
23420
  const isAddress = (value) => Number.isSafeInteger(value) && value >= 0;
23348
23421
  async function answerMonitor(endpoint, body2) {
23349
- const { addresses, read } = monitorEndpoints[endpoint];
23422
+ const { addresses, read, closed = NO_CARRIER } = monitorEndpoints[endpoint];
23350
23423
  if (!addresses.every((name3) => isAddress(body2[name3]))) {
23351
23424
  return failure("invalid_body", `Body must contain { sessionId: string${addresses.map((name3) => `, ${name3}: non-negative integer`).join("")} }`);
23352
23425
  }
23353
23426
  try {
23354
23427
  const value = await read(innerMonitor(), body2);
23355
23428
  if (value === void 0) return MONITOR_UNAVAILABLE;
23356
- return value.kind === "not_committed" ? MONITOR_NOT_COMMITTED : { ok: true, value };
23429
+ return Object.hasOwn(closed, value.kind) ? closed[value.kind] : { ok: true, value };
23357
23430
  } catch (error) {
23358
23431
  const diagnostic3 = hostDiagnostic("inner_monitor_read_failed", error);
23359
23432
  writeDiagnostic(body2.sessionId, diagnostic3);
@@ -23384,6 +23457,8 @@ function createRpcHandler({
23384
23457
  if (!Object.hasOwn(endpoints, endpoint) && !Object.hasOwn(modeEndpoints, endpoint) && !Object.hasOwn(monitorEndpoints, endpoint)) {
23385
23458
  return failure("unknown_endpoint", `unknown endpoint ${endpoint}`);
23386
23459
  }
23460
+ const owner = monitorEndpoints[endpoint]?.owner;
23461
+ if (owner !== void 0 && peer?.principal?.kind !== "owner") return owner;
23387
23462
  const body2 = payload || {};
23388
23463
  if (typeof body2.sessionId !== "string") return failure("invalid_body", "Body must contain { sessionId: string }");
23389
23464
  if (Object.hasOwn(modeEndpoints, endpoint)) return modeEndpoints[endpoint](body2);
@@ -23408,32 +23483,54 @@ function createRpcHandler({
23408
23483
  var PI_AI_SERVICE = "sessionWatcherPiAi";
23409
23484
  var ORIGINAL_ROW = "include:llm-pi-ai";
23410
23485
  var CARRIER_EVIDENCE_SERVICE = "sessionWatcherCarrierEvidence";
23411
- var CARRIER_RESULTS = ["added", "native", "skipped"];
23412
- var SKIP_REASONS = ["no-carrier", "no-native-point", "points-full", "responses-off", "unsupported"];
23486
+ var CARRIER_SETTINGS_SERVICE = "sessionWatcherCarrierSettings";
23413
23487
 
23414
23488
  // dsh/src/carrier-evidence.js
23415
23489
  import { AsyncLocalStorage } from "node:async_hooks";
23490
+
23491
+ // lib/inner-seal/call-record.js
23492
+ var CALL_RECORD_NAME = "inner-call";
23416
23493
  var MAX_CARRIER_EVIDENCE = 8;
23417
- function isCarrierResult(value) {
23418
- if (value === null || typeof value !== "object" || Array.isArray(value) || !CARRIER_RESULTS.includes(value.result)) return false;
23419
- const keys = Object.keys(value);
23420
- return value.result === "skipped" ? keys.length === 2 && SKIP_REASONS.includes(value.reason) : keys.length === 1;
23494
+ var UNCACHED_SHARE_ALERT = 1 / 2;
23495
+ var isObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
23496
+ var isSeq = (value) => Number.isSafeInteger(value) && value >= 0;
23497
+ var isText2 = (value) => typeof value === "string";
23498
+ function callRecordOf({ purpose, selection, input, range, stream, endedAt, attempt, carrierCache, thrown }) {
23499
+ return {
23500
+ v: 1,
23501
+ purpose,
23502
+ selection,
23503
+ input,
23504
+ range,
23505
+ stream,
23506
+ endedAt,
23507
+ ...carrierCache == null ? {} : { carrierCache },
23508
+ ...thrown == null ? {} : { thrown },
23509
+ ...attempt == null ? {} : { attempt }
23510
+ };
23421
23511
  }
23422
- function isCarrierEvidence(value) {
23423
- if (value === null || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 2) return false;
23424
- const { results, omitted } = value;
23425
- return Array.isArray(results) && results.length > 0 && results.length <= MAX_CARRIER_EVIDENCE && results.every(isCarrierResult) && Number.isSafeInteger(omitted) && omitted >= 0;
23512
+ var isCallRecord = (data) => isObject4(data) && data.v === 1 && Array.isArray(data.range) && data.range.length > 0 && data.range.every(isSeq) && Array.isArray(data.stream) && isObject4(data.input) && isObject4(data.input.tail) && (data.thrown === void 0 || isObject4(data.thrown) && isText2(data.thrown.message));
23513
+ var isCarrierResult = (value) => isObject4(value) && isText2(value.result) && (value.reason === void 0 || isText2(value.reason));
23514
+ var isCarrierCache = (value) => isObject4(value) && Array.isArray(value.results) && value.results.length > 0 && value.results.length <= MAX_CARRIER_EVIDENCE && value.results.every(isCarrierResult) && Number.isSafeInteger(value.omitted) && value.omitted >= 0;
23515
+
23516
+ // lib/llm-adapter/carrier-results.js
23517
+ var CARRIER_RESULTS = ["added", "native", "skipped"];
23518
+ var SKIP_REASONS = ["no-carrier", "no-native-point", "points-full", "responses-off", "unsupported"];
23519
+ function isCarrierResult2(value) {
23520
+ if (value === null || typeof value !== "object" || Array.isArray(value) || !CARRIER_RESULTS.includes(value.result)) return false;
23521
+ const keys = Object.keys(value);
23522
+ return value.result === "skipped" ? keys.length === 2 && SKIP_REASONS.includes(value.reason) : keys.length === 1;
23426
23523
  }
23427
- var closed = ({ result, reason }) => result === "skipped" ? { result, reason } : { result };
23428
- function createCarrierEvidence({ responsesBreakpoint = () => false } = {}) {
23524
+
23525
+ // dsh/src/carrier-evidence.js
23526
+ function createCarrierEvidence() {
23429
23527
  const store = new AsyncLocalStorage();
23430
23528
  return {
23431
23529
  service: Object.freeze({
23432
- responsesBreakpoint,
23433
23530
  record(result) {
23434
23531
  const scope = store.getStore();
23435
- if (scope === void 0 || !isCarrierResult(result)) return;
23436
- if (scope.results.length < MAX_CARRIER_EVIDENCE) scope.results.push(closed(result));
23532
+ if (scope === void 0 || !isCarrierResult2(result)) return;
23533
+ if (scope.results.length < MAX_CARRIER_EVIDENCE) scope.results.push(result);
23437
23534
  else scope.omitted += 1;
23438
23535
  }
23439
23536
  }),
@@ -23441,7 +23538,7 @@ function createCarrierEvidence({ responsesBreakpoint = () => false } = {}) {
23441
23538
  const own = { results: [], omitted: 0 };
23442
23539
  return {
23443
23540
  run: (body2) => store.run(own, body2),
23444
- evidence: () => own.results.length === 0 ? null : { results: own.results.map(closed), omitted: own.omitted }
23541
+ evidence: () => own.results.length === 0 ? null : { results: [...own.results], omitted: own.omitted }
23445
23542
  };
23446
23543
  }
23447
23544
  };
@@ -24173,10 +24270,82 @@ function createTurnReadService({
24173
24270
  };
24174
24271
  }
24175
24272
 
24273
+ // lib/harness/dsh/event-read.js
24274
+ var EVENT_READ_TOOL = "sw_event_read";
24275
+ var NATIVE_EVENT_READ = "session_event_read";
24276
+ var EVENT_READ_GUIDANCE = `Use ${EVENT_READ_TOOL} when you need exact data from an earlier event.`;
24277
+ var isText3 = (value) => typeof value === "string";
24278
+ var listOf = (value) => Array.isArray(value) ? value : [];
24279
+ function eventReadTargetOf(call) {
24280
+ if (call?.name !== EVENT_READ_TOOL && call?.name !== NATIVE_EVENT_READ) return void 0;
24281
+ try {
24282
+ const { seq, session_id: sessionId } = JSON.parse(call.arguments);
24283
+ if (Number.isSafeInteger(seq) && seq >= 0 && (sessionId === void 0 || isText3(sessionId))) return { seq, sessionId };
24284
+ } catch {
24285
+ return void 0;
24286
+ }
24287
+ return void 0;
24288
+ }
24289
+ var sourceOf = (source) => isText3(source?.kind) ? { source: { kind: source.kind } } : {};
24290
+ function blockOf(block) {
24291
+ switch (block?.type) {
24292
+ case "text":
24293
+ case "reasoning":
24294
+ return isText3(block.text) ? [{ type: block.type, text: block.text }] : [];
24295
+ case "tool-call":
24296
+ return [{ type: "tool-call", id: block.id, name: block.name, arguments: block.arguments }];
24297
+ case "file":
24298
+ case "image":
24299
+ return block.attachment === void 0 ? [] : [{ type: block.type, attachment: block.attachment }];
24300
+ default:
24301
+ return [];
24302
+ }
24303
+ }
24304
+ var blocksOf = (content) => listOf(content).flatMap(blockOf);
24305
+ var BODIES = {
24306
+ "user/message": (data) => ({ content: blocksOf(data.content), ...sourceOf(data.source) }),
24307
+ // `interrupted` marks a prefix a cancellation cut short, which a reader must not take for a finished message.
24308
+ "assistant/message": (data) => ({ message: { content: blocksOf(data.message?.content) }, ...data.interrupted === true ? { interrupted: true } : {} }),
24309
+ "tool/call": (data) => ({ callId: data.callId, name: data.name, arguments: data.arguments }),
24310
+ "tool/result": (data) => {
24311
+ const { message, error } = data;
24312
+ return {
24313
+ message: {
24314
+ ...isText3(message?.toolCallId) ? { toolCallId: message.toolCallId } : {},
24315
+ ...typeof message?.isError === "boolean" ? { isError: message.isError } : {},
24316
+ content: blocksOf(message?.content)
24317
+ },
24318
+ ...error === void 0 || error === null ? {} : { error: { name: error.name, code: error.code } }
24319
+ };
24320
+ }
24321
+ };
24322
+ function eventTextOf(event) {
24323
+ const { type, seq, time } = event;
24324
+ const body2 = Object.hasOwn(BODIES, type) ? BODIES[type](event.data ?? {}) : void 0;
24325
+ return { type, seq, time, ...body2 === void 0 ? {} : { data: body2 } };
24326
+ }
24327
+ var NO_TEXT = " | (no semantic text)";
24328
+ var CARRIER_KINDS = /* @__PURE__ */ new Set([LOAD_MESSAGE_KIND, INNER_SEAL_KIND, CHECKPOINT_KIND]);
24329
+ function neighborLine(event, textOf4) {
24330
+ const identity = `- seq ${event.seq} | ${event.type} | ${new Date(event.time).toISOString()}`;
24331
+ if (event.type === "user/message" && CARRIER_KINDS.has(event.data?.source?.kind)) return identity;
24332
+ const text = textOf4(event);
24333
+ return `${identity}${text.length === 0 ? NO_TEXT : `
24334
+ ${text.replaceAll("\n", "\n ")}`}`;
24335
+ }
24336
+ function formatEventRead({ sessionId, title, window: window2, textOf: textOf4 }) {
24337
+ const { target } = window2;
24338
+ const lines = [`Session ${sessionId} \u2014 ${title}`, `Target event seq ${target.seq}:`, "```json", JSON.stringify(eventTextOf(target), null, 2), "```"];
24339
+ for (const [heading, neighbors] of [["Before:", window2.events.filter((event) => event.seq < target.seq)], ["After:", window2.events.filter((event) => event.seq > target.seq)]]) {
24340
+ if (neighbors.length > 0) lines.push("", heading, ...neighbors.map((event) => neighborLine(event, textOf4)));
24341
+ }
24342
+ return lines.join("\n");
24343
+ }
24344
+
24176
24345
  // lib/harness/dsh/turn-recovery.js
24177
- var NOTICE = "Historical turns are evidence of what happened; read them to confirm or correct the handoff summary. Each session header names that session's id, and a row's T is that session's event seq; read it in full with session_event_read(session_id, T).";
24178
- var SEARCH_HIT = "line is the event seq a match sits in, span the events of its fold from its anchor to its results, and transcript_path the session id; read session_event_read with transcript_path as session_id and line as seq for the full event. An entry's scope names its turn: pass it as scope to search that turn alone, or as turn_page's before to read the history leading up to it.";
24179
- var LOCATE_HIT = "A hit's transcript_path is the session id that holds its turn at event T of its scope; read session_event_read with transcript_path as session_id and T as seq for the full event. The other entries are the turns adjacent to a hit. Pass a scope as turn_search's scope to search that turn for a literal, or as turn_page's before to read the history leading up to it.";
24346
+ var NOTICE = `Historical turns are evidence of what happened; read them to confirm or correct the handoff summary. Each session header names that session's id, and a row's T is that session's event seq; read it in full with ${EVENT_READ_TOOL}(session_id, T).`;
24347
+ var SEARCH_HIT = `line is the event seq a match sits in, span the events of its fold from its anchor to its results, and transcript_path the session id; read ${EVENT_READ_TOOL} with transcript_path as session_id and line as seq for the full event. An entry's scope names its turn: pass it as scope to search that turn alone, or as turn_page's before to read the history leading up to it.`;
24348
+ var LOCATE_HIT = `A hit's transcript_path is the session id that holds its turn at event T of its scope; read ${EVENT_READ_TOOL} with transcript_path as session_id and T as seq for the full event. The other entries are the turns adjacent to a hit. Pass a scope as turn_search's scope to search that turn for a literal, or as turn_page's before to read the history leading up to it.`;
24180
24349
  function createDshTurnRecovery() {
24181
24350
  return { notice: NOTICE, searchHit: SEARCH_HIT, locateHit: LOCATE_HIT };
24182
24351
  }
@@ -24739,6 +24908,98 @@ function createContinueCommand({ table, store, kit, meter, flush, deliver, readF
24739
24908
  return { name: COMMAND_NAME2, description: COMMAND_DESCRIPTION2, handler };
24740
24909
  }
24741
24910
 
24911
+ // dsh/src/event-read.js
24912
+ var UNTITLED = "untitled";
24913
+ var UNAUTHORIZED = "SESSION_QUERY_TOOL_UNAUTHORIZED";
24914
+ var FAILED = "SESSION_QUERY_TOOL_FAILED";
24915
+ var CARRIED = "SW_EVENT_CARRIED";
24916
+ var SAFE_FAILURES = {
24917
+ SESSION_QUERY_ABORTED: "session query was cancelled",
24918
+ SESSION_QUERY_EVENT_NOT_FOUND: "session event was not found",
24919
+ SESSION_QUERY_INVALID_WINDOW: "session event window is invalid",
24920
+ SESSION_QUERY_SESSION_NOT_FOUND: "session was not found"
24921
+ };
24922
+ function createEventReadTool({ defineTool: defineTool2, ctx, extractSessionEventText: extractSessionEventText2, HarnessError: HarnessError2, heldInContext: heldInContext2 = () => false }) {
24923
+ const failure4 = (message, code) => new HarnessError2(message, code);
24924
+ const unauthorized = () => failure4("session target is outside the caller workspace", UNAUTHORIZED);
24925
+ const assertCount = (name3, value) => {
24926
+ if (!Number.isSafeInteger(value) || value < 0) throw failure4(`${name3} must be a non-negative safe integer`, "SESSION_QUERY_INVALID_WINDOW");
24927
+ };
24928
+ const isHeld = (sessionId, seq) => {
24929
+ try {
24930
+ return heldInContext2(sessionId, seq);
24931
+ } catch (error) {
24932
+ writeDiagnostic(sessionId, hostDiagnostic("event_read_held_failed", error));
24933
+ return false;
24934
+ }
24935
+ };
24936
+ const guarded = async (sessionId, signal, call) => {
24937
+ signal.throwIfAborted();
24938
+ try {
24939
+ const value = await call();
24940
+ signal.throwIfAborted();
24941
+ return value;
24942
+ } catch (error) {
24943
+ signal.throwIfAborted();
24944
+ writeDiagnostic(sessionId, hostDiagnostic("event_read_failed", error));
24945
+ const message = typeof error?.code === "string" && Object.hasOwn(SAFE_FAILURES, error.code) ? SAFE_FAILURES[error.code] : void 0;
24946
+ throw message === void 0 ? failure4("session query operation failed", FAILED) : failure4(message, error.code);
24947
+ }
24948
+ };
24949
+ return defineTool2({
24950
+ name: EVENT_READ_TOOL,
24951
+ description: "Read the full unabridged text of one event and optional neighboring raw-event summaries from an authorized session.",
24952
+ parameters: {
24953
+ session_id: { type: "string", description: "Target session id. Omit for the current session." },
24954
+ seq: { type: "integer", required: true, description: "Target event sequence number." },
24955
+ before: { type: "integer", description: "Number of preceding raw events to summarize. Omit for none." },
24956
+ after: { type: "integer", description: "Number of following raw events to summarize. Omit for none." }
24957
+ },
24958
+ output: { schema: { type: "string" }, render: (_args, value) => [{ type: "text", text: value }] },
24959
+ isConcurrencySafe: () => true,
24960
+ async execute({ session_id: requested, seq, before, after }, { agent, signal }) {
24961
+ assertCount("seq", seq);
24962
+ if (before !== void 0) assertCount("before", before);
24963
+ if (after !== void 0) assertCount("after", after);
24964
+ const { id: callerId, header } = agent.session;
24965
+ const sessionId = requested ?? callerId;
24966
+ if (sessionId === callerId && isHeld(callerId, seq)) {
24967
+ throw failure4(`Event seq ${seq} is already in your context word for word; reading it gives the same text. Use it.`, CARRIED);
24968
+ }
24969
+ const run2 = (call) => guarded(callerId, signal, call);
24970
+ const assertObserved = (observed) => {
24971
+ if (observed?.id !== sessionId || observed.cwd !== header.cwd) throw unauthorized();
24972
+ };
24973
+ if (sessionId !== callerId) {
24974
+ if (header.cwd === void 0) throw unauthorized();
24975
+ const records = await run2(() => ctx.sessionQuery.filterSessions([{ kind: "id", values: [sessionId] }, { kind: "cwd", values: [header.cwd] }], signal));
24976
+ if (records.length !== 1) throw unauthorized();
24977
+ }
24978
+ const window2 = await run2(() => ctx.sessionQuery.readEvent({
24979
+ sessionId,
24980
+ seq,
24981
+ ...before === void 0 ? {} : { before },
24982
+ ...after === void 0 ? {} : { after }
24983
+ }, signal));
24984
+ assertObserved(window2.session);
24985
+ let title = UNTITLED;
24986
+ try {
24987
+ const [observation] = await run2(() => ctx.sessionQuery.readTitleSnapshots([sessionId], signal));
24988
+ if (observation?.status === "fulfilled") {
24989
+ assertObserved(observation.value.session);
24990
+ title = observation.value.title?.title ?? UNTITLED;
24991
+ } else {
24992
+ writeDiagnostic(callerId, hostDiagnostic("event_read_title_failed", observation?.reason));
24993
+ }
24994
+ } catch (error) {
24995
+ if (error.code === UNAUTHORIZED) throw error;
24996
+ signal.throwIfAborted();
24997
+ }
24998
+ return formatEventRead({ sessionId, title, window: window2, textOf: extractSessionEventText2 });
24999
+ }
25000
+ });
25001
+ }
25002
+
24742
25003
  // dsh/src/skills.js
24743
25004
  import { existsSync, readdirSync, readFileSync as readFileSync6 } from "node:fs";
24744
25005
  import { join as join7 } from "node:path";
@@ -24767,24 +25028,35 @@ function registerSkills(ctx, { skillsDir }) {
24767
25028
  }
24768
25029
  }
24769
25030
 
24770
- // dsh/src/inner-mode.js
24771
- var MODE_RECORD_TYPE = "plugin:session-watcher/inner-mode";
24772
- var MODE_PROJECTION_KEY = "session-watcher/inner-mode";
25031
+ // lib/inner-seal/mode.js
24773
25032
  var MODES = ["off", "on", "invalid"];
24774
- var messageOf4 = (error) => error instanceof Error ? error.message : String(error);
24775
25033
  var STATES = Object.fromEntries(MODES.map((mode) => [mode, {
24776
25034
  unlocked: Object.freeze({ mode, locked: false }),
24777
25035
  locked: Object.freeze({ mode, locked: true })
24778
25036
  }]));
24779
25037
  var stateOf = (mode, locked) => STATES[mode][locked ? "locked" : "unlocked"];
24780
- var isModeInput = (event) => event.type === "turn/start" || event.type === MODE_RECORD_TYPE;
24781
25038
  var isModeData = (data) => data !== null && typeof data === "object" && data.v === 1 && typeof data.enabled === "boolean";
25039
+ var INITIAL_MODE = stateOf("off", false);
25040
+ function modeStateOf(value) {
25041
+ if (value === null || typeof value !== "object" || !MODES.includes(value.mode) || typeof value.locked !== "boolean") return null;
25042
+ return stateOf(value.mode, value.locked);
25043
+ }
25044
+ function foldMode(state, input) {
25045
+ if (state.locked) return state;
25046
+ if (input.turnStarted === true) return stateOf(state.mode, true);
25047
+ return stateOf(isModeData(input.record) ? input.record.enabled ? "on" : "off" : "invalid", false);
25048
+ }
25049
+
25050
+ // dsh/src/inner-mode.js
25051
+ var MODE_RECORD_TYPE = "plugin:session-watcher/inner-mode";
25052
+ var MODE_PROJECTION_KEY = "session-watcher/inner-mode";
25053
+ var messageOf4 = (error) => error instanceof Error ? error.message : String(error);
25054
+ var isModeInput = (event) => event.type === "turn/start" || event.type === MODE_RECORD_TYPE;
24782
25055
  var stateSchema = {
24783
25056
  parse(value) {
24784
- if (value === null || typeof value !== "object" || !MODES.includes(value.mode) || typeof value.locked !== "boolean") {
24785
- throw new Error("the inner mode state is not { mode, locked }");
24786
- }
24787
- return stateOf(value.mode, value.locked);
25057
+ const state = modeStateOf(value);
25058
+ if (state === null) throw new Error("the inner mode state is not { mode, locked }");
25059
+ return state;
24788
25060
  }
24789
25061
  };
24790
25062
  function innerModeProjection({ pluginRecordOf: pluginRecordOf2 }) {
@@ -24792,13 +25064,12 @@ function innerModeProjection({ pluginRecordOf: pluginRecordOf2 }) {
24792
25064
  key: MODE_PROJECTION_KEY,
24793
25065
  stateVersion: 1,
24794
25066
  stateSchema,
24795
- init: () => stateOf("off", false),
25067
+ init: () => INITIAL_MODE,
24796
25068
  apply(state, event) {
24797
- if (state.locked) return state;
24798
- if (event.type === "turn/start") return stateOf(state.mode, true);
25069
+ if (event.type === "turn/start") return foldMode(state, { turnStarted: true });
24799
25070
  const record = pluginRecordOf2(event);
24800
25071
  if (record?.type !== MODE_RECORD_TYPE) return state;
24801
- return stateOf(isModeData(record.data) ? record.data.enabled ? "on" : "off" : "invalid", false);
25072
+ return foldMode(state, { record: record.data });
24802
25073
  }
24803
25074
  };
24804
25075
  }
@@ -24859,7 +25130,235 @@ function createModeAccess({ sessionOf, readMode, select, readStored }) {
24859
25130
  return access;
24860
25131
  }
24861
25132
 
24862
- // dsh/src/inner-quote.js
25133
+ // lib/inner-seal/source.js
25134
+ var stepKey = ({ turn, step }) => `${turn}:${step}`;
25135
+ function headerSeqIn(facts, { latest, above }) {
25136
+ let found = null;
25137
+ for (const [seq, fact] of facts) {
25138
+ if (!fact.header || !latest && seq <= above) continue;
25139
+ if (found === null || (latest ? seq > found : seq < found)) found = seq;
25140
+ }
25141
+ return found;
25142
+ }
25143
+ function initialPrefixLength(facts, nodes) {
25144
+ let length = nodes.length > 0 && facts.get(nodes[0]).system ? 1 : 0;
25145
+ let opened = -1;
25146
+ nodes.forEach((seq, index) => {
25147
+ if (facts.get(seq).epoch && seq > opened) {
25148
+ opened = seq;
25149
+ length = Math.max(length, index + 1);
25150
+ }
25151
+ });
25152
+ const first = headerSeqIn(facts, { latest: false, above: opened });
25153
+ if (first === null) return length;
25154
+ while (length < nodes.length && nodes[length] > opened && nodes[length] < first) length += 1;
25155
+ return length;
25156
+ }
25157
+ function innerSource(facts, nodes) {
25158
+ const prefix = initialPrefixLength(facts, nodes);
25159
+ let at = -1;
25160
+ nodes.forEach((seq, index) => {
25161
+ const { marker } = facts.get(seq);
25162
+ if (marker !== null && (marker !== "payload" || index >= prefix) && (at < 0 || seq > nodes[at])) at = index;
25163
+ });
25164
+ const range = nodes.slice(Math.max(prefix, at + 1));
25165
+ const steps = new Set(range.map((seq) => facts.get(seq).step).filter((step) => step !== null).map(stepKey));
25166
+ const lastCall = range.findLastIndex((seq) => facts.get(seq).skeletonCall);
25167
+ const lastPayload = range.findLastIndex((seq) => facts.get(seq).marker === "payload");
25168
+ return { frontier: at < 0 ? null : nodes[at], range, stepN: steps.size, paused: lastCall > lastPayload };
25169
+ }
25170
+ function skeletonSlots(facts, nodes, range) {
25171
+ const selected = new Set(range);
25172
+ const sources = nodes.filter((seq) => selected.has(seq));
25173
+ const counted = new Set(sources.map((seq) => facts.get(seq).step).filter((step) => step !== null).map(stepKey));
25174
+ const slots = [];
25175
+ const stepSlots = /* @__PURE__ */ new Map();
25176
+ for (const seq of sources) {
25177
+ const { owner, assistant, originals } = facts.get(seq);
25178
+ const key = stepKey(owner);
25179
+ const seqs = [...originals, seq];
25180
+ if (!counted.has(key)) {
25181
+ if (!assistant) slots.push({ seqs });
25182
+ } else if (stepSlots.has(key)) {
25183
+ stepSlots.get(key).seqs.push(...seqs);
25184
+ } else {
25185
+ const slot = { seqs, step: { turn: owner.turn, step: owner.step } };
25186
+ stepSlots.set(key, slot);
25187
+ slots.push(slot);
25188
+ }
25189
+ }
25190
+ return slots;
25191
+ }
25192
+
25193
+ // lib/inner-seal/git-state.js
25194
+ import { execFile } from "node:child_process";
25195
+ import { promisify } from "node:util";
25196
+ var execFileAsync = promisify(execFile);
25197
+ var STATUS_COMMAND = ["status", "--short", "--branch"];
25198
+ var LOG_COMMAND = ["log", "-1", "--oneline"];
25199
+ var BRANCH_LINE_START = "## ";
25200
+ var GIT_SAFE_OPTIONS = ["-c", "core.fsmonitor=false"];
25201
+ function isGitStateCommand(command) {
25202
+ if (typeof command !== "string") return false;
25203
+ const [status, head, ...rest] = command.trim().split(/[ \t]*&&[ \t]*/u);
25204
+ return rest.length === 0 && /^git[ \t]+status(?:[ \t]+--?[\w=-]+)*$/u.test(status) && (head === void 0 || head.split(/[ \t]+/u).join(" ") === `git ${LOG_COMMAND.join(" ")}`);
25205
+ }
25206
+ var STATUS_LISTING = "git status --short";
25207
+ var GIT_STATUS_LINE_LIMIT = 20;
25208
+ var GIT_READ_TIMEOUT_MS = 5e3;
25209
+ var linesOf = (text) => text.split("\n").filter((line, at, all) => line !== "" || at < all.length - 1);
25210
+ var leftNotice = (count) => `\u2026 and ${count} more not shown; \`${STATUS_LISTING}\` lists them all`;
25211
+ var GIT_ENV = { LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0" };
25212
+ async function runGit(args2, { cwd, signal, timeoutMs }) {
25213
+ try {
25214
+ const { stdout } = await execFileAsync("git", [...GIT_SAFE_OPTIONS, ...args2], { cwd, signal, timeout: timeoutMs, encoding: "utf8", env: { ...process.env, ...GIT_ENV } });
25215
+ return { stdout };
25216
+ } catch (error) {
25217
+ if (typeof error.code === "number") return { exit: error.stderr };
25218
+ throw error;
25219
+ }
25220
+ }
25221
+ async function readGitState({ cwd, signal, timeoutMs = GIT_READ_TIMEOUT_MS }) {
25222
+ if (typeof cwd !== "string" || cwd === "") throw new Error("the git state has no working directory to be read in");
25223
+ const options = { cwd, signal, timeoutMs };
25224
+ const status = await runGit(STATUS_COMMAND, options);
25225
+ if ("exit" in status) {
25226
+ if (/not a git repository/i.test(status.exit)) return null;
25227
+ throw new Error(`git ${STATUS_COMMAND.join(" ")} failed: ${status.exit.trim()}`);
25228
+ }
25229
+ const [branch, ...entries] = linesOf(status.stdout);
25230
+ if (!branch?.startsWith(BRANCH_LINE_START)) throw new Error(`git ${STATUS_COMMAND.join(" ")} printed no branch line`);
25231
+ const log = await runGit(LOG_COMMAND, options);
25232
+ const heads = "exit" in log ? [] : linesOf(log.stdout);
25233
+ if (heads.length > 1 || heads.length === 1 && heads[0] === "") throw new Error(`git ${LOG_COMMAND.join(" ")} did not print one line`);
25234
+ const left = entries.length - GIT_STATUS_LINE_LIMIT;
25235
+ return [branch, ...entries.slice(0, GIT_STATUS_LINE_LIMIT), ...left > 0 ? [leftNotice(left)] : [], ...heads].join("\n");
25236
+ }
25237
+ var GIT_STATE_ITEM = Object.freeze({
25238
+ key: "git",
25239
+ label: `Git, as \`git ${STATUS_COMMAND.join(" ")} && git ${LOG_COMMAND.join(" ")}\` would show:`,
25240
+ multiline: true,
25241
+ normalize: (value) => {
25242
+ if (typeof value !== "string" || value === "") throw new Error("the git state is not a text");
25243
+ return value;
25244
+ },
25245
+ isEmpty: () => false,
25246
+ same: (a, b) => a === b,
25247
+ text: (value) => value
25248
+ });
25249
+
25250
+ // lib/harness/dsh/carrier-table.js
25251
+ var carriesEvidence = (source) => source?.kind === INNER_SEAL_KIND || source?.kind === LOAD_MESSAGE_KIND && Array.isArray(source.paths);
25252
+ var isTodoItem = (item) => item !== null && typeof item === "object" && typeof item.content === "string" && typeof item.status === "string";
25253
+ function todoItemsOf(value) {
25254
+ if (value === null) return [];
25255
+ if (!Array.isArray(value) || !value.every(isTodoItem)) throw new Error("the todo list is neither null nor a list of items with a content text and a status text");
25256
+ return value.map(({ content, status }) => ({ content, status }));
25257
+ }
25258
+ function textEntriesOf(value, fields, what) {
25259
+ if (!Array.isArray(value) || !value.every((entry) => entry !== null && typeof entry === "object" && fields.every((field) => typeof entry[field] === "string"))) {
25260
+ throw new Error(`the ${what} is not a list of entries with ${fields.join(" and ")} texts`);
25261
+ }
25262
+ return value.map((entry) => Object.fromEntries(fields.map((field) => [field, entry[field]])));
25263
+ }
25264
+ var sameEntries = (fields, a, b) => a.length === b.length && a.every((entry, at) => fields.every((field) => entry[field] === b[at][field]));
25265
+ var entryList = (entries) => entries.map(({ id, label }) => `${id} \u2014 ${label}`).join("; ");
25266
+ var AGENT_FIELDS = ["id", "label"];
25267
+ var TODO_FIELDS = ["content", "status"];
25268
+ var stateItem = ({ tool, label, ...rest }) => Object.freeze({ ...rest, tool, label: label(tool) });
25269
+ function argumentsOf(call) {
25270
+ try {
25271
+ return JSON.parse(call.arguments);
25272
+ } catch {
25273
+ return void 0;
25274
+ }
25275
+ }
25276
+ var CARRIER_TABLE = Object.freeze({
25277
+ addresses: `These summaries stand in for earlier turns of this session; replacing them changed no file and no state, so the work carries on from them. Each summary line below opens with seq numbers: the addresses, in this session's log, of the events it summarizes, which the session history tools can read. A line marked user: is that message's full text, word for word unless a marker says where it is cut.`,
25278
+ editGuard: "The reads behind this file text still count in this session, so edit a file without reading it again.",
25279
+ imageReadTool: "read_image",
25280
+ stateItems: Object.freeze([
25281
+ stateItem({
25282
+ key: "workingDirectory",
25283
+ tool: "working_directory",
25284
+ label: (tool) => `Working directory, as ${tool} would show:`,
25285
+ operation: (call) => typeof argumentsOf(call)?.cd === "string" ? "write" : "read",
25286
+ normalize: (value) => {
25287
+ if (typeof value !== "string" || value === "") throw new Error("the working directory is not a path text");
25288
+ return value;
25289
+ },
25290
+ isEmpty: () => false,
25291
+ same: (a, b) => a === b,
25292
+ text: (value) => value
25293
+ }),
25294
+ stateItem({
25295
+ key: "subagents",
25296
+ tool: "list_agents",
25297
+ label: (tool) => `Running subagents, as ${tool} would show:`,
25298
+ normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "subagent list"),
25299
+ isEmpty: (entries) => entries.length === 0,
25300
+ same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
25301
+ text: entryList
25302
+ }),
25303
+ stateItem({
25304
+ key: "jobs",
25305
+ tool: "job_list",
25306
+ label: (tool) => `Running jobs, as ${tool} would show:`,
25307
+ normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "job list"),
25308
+ isEmpty: (entries) => entries.length === 0,
25309
+ same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
25310
+ text: entryList
25311
+ }),
25312
+ stateItem({
25313
+ key: "todos",
25314
+ tool: "todo_write",
25315
+ operation: "write",
25316
+ label: (tool) => `Todo list, as ${tool} last left it:`,
25317
+ normalize: todoItemsOf,
25318
+ isEmpty: (items) => items.length === 0,
25319
+ same: (a, b) => sameEntries(TODO_FIELDS, a, b),
25320
+ text: (items) => JSON.stringify(items)
25321
+ }),
25322
+ Object.freeze({ ...GIT_STATE_ITEM, matchesCall: (call) => call.name === "bash" && isGitStateCommand(argumentsOf(call)?.command) })
25323
+ ])
25324
+ });
25325
+ function stateOperationOf(call) {
25326
+ if (typeof call?.name !== "string") return void 0;
25327
+ const item = CARRIER_TABLE.stateItems.find((item2) => item2.matchesCall?.(call) ?? item2.tool === call.name);
25328
+ if (item === void 0) return void 0;
25329
+ return typeof item.operation === "function" ? item.operation(call) : item.operation ?? "read";
25330
+ }
25331
+
25332
+ // lib/harness/dsh/message-blocks.js
25333
+ var blockText = (block) => block.type === "text" || block.type === "reasoning" ? block.text : block.type === "tool-call" ? `${block.name}${block.arguments}` : JSON.stringify(block);
25334
+ var requestTextOf = (message) => message.content.map(blockText).join("");
25335
+ var blocksOf2 = (message) => Array.isArray(message?.content) ? message.content : [];
25336
+ var textOf2 = (messages) => messages.flatMap(blocksOf2).filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
25337
+ function slotFactsOf(slot, messages) {
25338
+ const [first] = messages;
25339
+ const text = textOf2(messages);
25340
+ if (slot.step === void 0) {
25341
+ if (first?.role === "tool") return { own: false, kind: "result", text, toolCallId: first.toolCallId };
25342
+ return { own: first?.role === "user" && first.source?.kind === "user", kind: "other", text };
25343
+ }
25344
+ const failed2 = new Set(messages.filter((message) => message.role === "tool" && message.isError === true).map((message) => message.toolCallId));
25345
+ const assistant = messages.filter((message) => message.role === "assistant");
25346
+ const calls = assistant.flatMap(blocksOf2).filter((block) => block?.type === "tool-call").map((call) => ({ id: call.id, name: call.name, arguments: call.arguments, failed: failed2.has(call.id) }));
25347
+ return { own: false, kind: "step", text, assistantText: textOf2(assistant), calls };
25348
+ }
25349
+
25350
+ // lib/inner-seal/touched.js
25351
+ function touchedOf({ paths, skills, effects }, seqs) {
25352
+ const replaced = new Set(seqs);
25353
+ const touched = { path: /* @__PURE__ */ new Set(), skill: /* @__PURE__ */ new Set() };
25354
+ for (const { seq, kind, key } of effects) if (replaced.has(seq)) touched[kind].add(key);
25355
+ return {
25356
+ paths: new Map([...paths].filter(([key]) => touched.path.has(key))),
25357
+ skills: new Map([...skills].filter(([name3]) => touched.skill.has(name3)))
25358
+ };
25359
+ }
25360
+
25361
+ // lib/inner-seal/quote.js
24863
25362
  var INNER_QUOTE = Object.freeze({ minSteps: 8, cPerStep: 200, fee: 1e4 });
24864
25363
  var KAPPA_PRICE_ANCHOR = 25;
24865
25364
  var KAPPA_WEIGHT_SHIFT = 23;
@@ -24882,22 +25381,16 @@ function kappaOf(n, cRatio, { p, alpha }) {
24882
25381
  const weight = (cRatio - KAPPA_PRICE_ANCHOR) / (cRatio + KAPPA_WEIGHT_SHIFT);
24883
25382
  return 1 + alpha * powInt(etaOf(n, cRatio), p) + weight * compensation;
24884
25383
  }
24885
- var blockText = (block) => block.type === "text" || block.type === "reasoning" ? block.text : block.type === "tool-call" ? `${block.name}${block.arguments}` : JSON.stringify(block);
24886
- var messageTokens = (message, ctp) => charsToTokens(message.content.map(blockText).join(""), ctp);
24887
- var bTokens = (carried, ctp) => renderCarried(carried) === null ? 0 : charsToTokens(renderCarrier({ kind: INNER_SEAL_KIND, v: 1, slots: [], ...carried }).at(-1).text, ctp);
24888
- function estimateInnerA({ n, range, messageOf: messageOf6, carried, ctp }) {
24889
- const lA = range.reduce((sum, seq) => {
24890
- const message = messageOf6(seq);
24891
- return message === null ? sum : sum + messageTokens(message, ctp);
24892
- }, 0);
24893
- const bEst = bTokens(carried, ctp);
25384
+ function estimateInnerA({ n, texts, bText, ctp }) {
25385
+ const lA = texts.reduce((sum, text) => sum + charsToTokens(text, ctp), 0);
25386
+ const bEst = charsToTokens(bText, ctp);
24894
25387
  const cEst = INNER_QUOTE.cPerStep * n;
24895
25388
  return { n, lA, bEst, cEst, sEst: lA - bEst - cEst };
24896
25389
  }
24897
25390
  var NO_RESULT = Object.freeze({ nRef: null, N: null, jRef: null, q: null, arm: null });
24898
- function resultsOf(n, { bEst, cEst, sEst }, cRatio) {
24899
- const f0 = cRatio * INNER_QUOTE.fee + (cRatio - 1) * bEst;
24900
- const nRef = f0 / sEst;
25391
+ function resultsOf(n, { bEst, cEst, sEst }, cRatio, readCost) {
25392
+ const fixed = cRatio * INNER_QUOTE.fee + (cRatio - 1) * bEst + readCost;
25393
+ const nRef = fixed / sEst;
24901
25394
  const v = (cRatio - 1) * cEst / sEst;
24902
25395
  const N = nRef + v;
24903
25396
  const jRef = 2 * Math.sqrt(n * nRef) + v;
@@ -24905,22 +25398,14 @@ function resultsOf(n, { bEst, cEst, sEst }, cRatio) {
24905
25398
  if (![nRef, N, jRef, q].every(Number.isFinite) || !(jRef > 0)) return null;
24906
25399
  return { nRef, N, jRef, q, arm: n >= nRef ? "right" : "left" };
24907
25400
  }
24908
- function missingOf(estimate, cRatio) {
24909
- if (estimate === null) return "estimate_failed";
24910
- if (!Number.isFinite(cRatio)) return "ratio_unavailable";
24911
- if (!(estimate.sEst > 0)) return "non_positive_savings";
24912
- return null;
24913
- }
24914
- function innerQuote({ n, estimate, cRatio, preset }) {
25401
+ function innerQuote({ n, estimate, cRatio, preset, summaryReadCost }) {
24915
25402
  const ratio = Number.isFinite(cRatio) ? cRatio : null;
24916
25403
  const priced2 = ratio === null ? NaN : kappaOf(n, ratio, KAPPA_PRESETS[preset]);
24917
25404
  const kappa = Number.isFinite(priced2) ? priced2 : null;
24918
- let missing = missingOf(estimate, ratio);
24919
- let results = missing === null ? resultsOf(n, estimate, ratio) : null;
24920
- if (missing === null && (results === null || kappa === null)) {
24921
- missing = "undefined_result";
24922
- results = null;
24923
- }
25405
+ const priceable = estimate !== null && ratio !== null && estimate.sEst > 0;
25406
+ const read = Number.isFinite(summaryReadCost) && summaryReadCost >= 0 ? summaryReadCost : null;
25407
+ const found = priceable ? resultsOf(n, estimate, ratio, read ?? 0) : null;
25408
+ const results = kappa === null ? null : found;
24924
25409
  const quoted2 = results !== null && n >= INNER_QUOTE.minSteps && (results.arm === "right" || results.q < kappa);
24925
25410
  return {
24926
25411
  n,
@@ -24933,54 +25418,78 @@ function innerQuote({ n, estimate, cRatio, preset }) {
24933
25418
  kappa,
24934
25419
  preset,
24935
25420
  ...results ?? NO_RESULT,
24936
- trigger: quoted2 ? "quote" : null,
24937
- missing
25421
+ ...results !== null && read !== null ? { summaryReadCost: read } : {},
25422
+ trigger: quoted2 ? "quote" : null
24938
25423
  };
24939
25424
  }
25425
+ var isObject5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25426
+ var isSeq2 = (value) => Number.isSafeInteger(value) && value >= 0;
25427
+ var orNull = (holds) => (value) => value === null || holds(value);
25428
+ var QUOTE_QUANTITIES = ["lA", "bEst", "cEst", "sEst", "cRatio", "nRef", "N", "jRef", "q"];
25429
+ function isQuote(value) {
25430
+ return isObject5(value) && isSeq2(value.n) && QUOTE_QUANTITIES.every((key) => orNull(Number.isFinite)(value[key])) && Number.isFinite(value.fee) && Number.isFinite(value.kappa) && [null, "left", "right"].includes(value.arm) && value.trigger === "quote";
25431
+ }
24940
25432
 
24941
- // dsh/src/inner-summary.js
24942
- var SUMMARY_PURPOSE = "inner-compaction";
25433
+ // lib/inner-seal/attempt-record.js
25434
+ var ATTEMPT_RECORD_NAME = "inner-attempt";
25435
+ var isObject6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25436
+ var isSeq3 = (value) => Number.isSafeInteger(value) && value >= 0;
25437
+ var attemptRecordOf = ({ range, request, quote }) => ({ v: 1, range, request, quote });
25438
+ var isAttemptRecord = (data) => isObject6(data) && data.v === 1 && isObject6(data.range) && isSeq3(data.range.first) && isSeq3(data.range.last) && isSeq3(data.range.count) && isObject6(data.request) && isObject6(data.request.messages) && isObject6(data.request.messages.tail);
25439
+ var attemptQuoteOf = (data) => isQuote(data.quote) ? data.quote : null;
25440
+
25441
+ // lib/inner-seal/end-record.js
25442
+ var END_RECORD_NAME = "inner-end";
25443
+ var isObject7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25444
+ var isSeq4 = (value) => Number.isSafeInteger(value) && value >= 0;
25445
+ var isText4 = (value) => typeof value === "string";
25446
+ var endRecordOf = ({ attempt, outcome, reason }) => ({ v: 1, attempt, outcome, reason });
25447
+ var isEndRecord = (data) => isObject7(data) && data.v === 1 && isSeq4(data.attempt) && (data.outcome === "failed" || data.outcome === "cancelled") && isText4(data.reason);
25448
+
25449
+ // lib/inner-seal/ladder.js
24943
25450
  var FORMAT_FAILURE = "format";
24944
25451
  var FILTER_FAILURE = "filtered";
24945
- var FILTER_TEXT = "content_filtered";
24946
- var DISPLAYED_OPTIONS = ["provider", "model", "reasoningEffort", "purpose", "sessionId"];
24947
- var DISPLAYED_INPUT = ["throughSeq", "headerSeq"];
24948
- var provided = (source, keys) => Object.fromEntries(keys.filter((key) => source[key] !== void 0).map((key) => [key, source[key]]));
24949
- function requestDisplayOf(options, input) {
24950
- const { messages, tools, toolHistory } = options;
25452
+ var SUMMARY_MAX_REQUESTS = 3;
25453
+ var SUMMARY_FILTER_RETRIES = 1;
25454
+ function createRetryLadder({ selection, fallback }) {
25455
+ const rungs = [selection, ...Array(SUMMARY_FILTER_RETRIES).fill(selection), ...fallback === null ? [] : [fallback]];
25456
+ let rung = 0;
25457
+ let requests = 1;
24951
25458
  return {
24952
- options: provided(options, DISPLAYED_OPTIONS),
24953
- messages: { count: messages.length - 1, tail: messages.at(-1) },
24954
- ...provided(input, DISPLAYED_INPUT),
24955
- ...tools === void 0 ? {} : { tools: { count: tools.length } },
24956
- ...toolHistory === void 0 ? {} : {
24957
- toolHistory: { updates: toolHistory.updates.map(({ messageId, additions }) => ({ messageId, additions: additions.map((tool) => tool.name) })) }
25459
+ current: () => rungs[rung],
25460
+ next(failure4) {
25461
+ if (failure4 === FORMAT_FAILURE && requests < SUMMARY_MAX_REQUESTS) {
25462
+ requests += 1;
25463
+ return true;
25464
+ }
25465
+ if (failure4 === FILTER_FAILURE && rung < rungs.length - 1) {
25466
+ rung += 1;
25467
+ return true;
25468
+ }
25469
+ return false;
24958
25470
  }
24959
25471
  };
24960
25472
  }
25473
+
25474
+ // lib/inner-seal/summary.js
24961
25475
  var C_CUE_TEXT_CHARS = 60;
24962
- var blocksOf = (message) => Array.isArray(message?.content) ? message.content : [];
24963
- var textOf2 = (messages) => messages.flatMap(blocksOf).filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
24964
25476
  function cueText(text) {
24965
25477
  const folded = text.replace(/\s+/gu, " ");
24966
25478
  const half = C_CUE_TEXT_CHARS / 2;
24967
25479
  return JSON.stringify(folded.length <= C_CUE_TEXT_CHARS ? folded : `${safePrefix(folded, half)}\u2026${safeSuffix(folded, half)}`);
24968
25480
  }
24969
- function slotMessagesOf({ slots, session, events, range }) {
24970
- const bySeq = new Map(events.map((event) => [event.seq, event]));
24971
- const selected = new Set(range);
24972
- return slots.map((slot) => slot.seqs.filter((seq) => selected.has(seq)).map((seq) => session.deriveEventMessage(bySeq.get(seq))).filter((message) => message != null));
24973
- }
24974
- function verbatimNoteOf(slot, messages) {
24975
- const [message] = messages;
24976
- if (slot.step !== void 0 || message?.role !== "user" || message.source?.kind !== "user") return null;
24977
- const { uText, uOriginalChars } = storedUText(textOf2(messages));
24978
- const u = uOriginalChars > uText.length ? `${uText}${truncationMarker(uOriginalChars)}` : uText;
24979
- return `user: ${u}`;
25481
+ function verbatimNoteOf(facts) {
25482
+ if (!facts.own) return null;
25483
+ const { uText, uOriginalChars } = storedUText(facts.text);
25484
+ const truncated = uOriginalChars > uText.length;
25485
+ const u = truncated ? `${uText}${truncationMarker(uOriginalChars)}` : uText;
25486
+ return { text: `user: ${u}`, whole: !truncated && uText !== "" };
24980
25487
  }
24981
- function stringsOf(value, found = []) {
25488
+ function valuesOf(value, key, found = []) {
24982
25489
  if (typeof value === "string") found.push(value);
24983
- else if (value !== null && typeof value === "object") Object.values(value).forEach((item) => stringsOf(item, found));
25490
+ else if (typeof value === "number" || typeof value === "boolean") found.push(key === void 0 ? String(value) : `${key} ${value}`);
25491
+ else if (Array.isArray(value)) value.forEach((item) => valuesOf(item, key, found));
25492
+ else if (value !== null && typeof value === "object") Object.entries(value).forEach(([name3, item]) => valuesOf(item, name3, found));
24984
25493
  return found;
24985
25494
  }
24986
25495
  function argumentsCueOf(call) {
@@ -24990,28 +25499,21 @@ function argumentsCueOf(call) {
24990
25499
  } catch {
24991
25500
  parsed = call.arguments;
24992
25501
  }
24993
- const text = stringsOf(parsed).join(" ").trim();
25502
+ const text = valuesOf(parsed).join(" ").trim();
24994
25503
  return text === "" ? "" : `: ${cueText(text)}`;
24995
25504
  }
24996
- function rowsOf(entries) {
25505
+ function rowsOf(slotFacts, verbatim) {
24997
25506
  let number = 0;
24998
- return entries.map(({ slot, messages, verbatim }) => {
24999
- if (verbatim !== null) return `user, no note: ${cueText(textOf2(messages))}`;
25507
+ return slotFacts.map((facts, at) => {
25508
+ if (verbatim[at] !== null) return `user, no note: ${cueText(facts.text)}`;
25000
25509
  number += 1;
25001
25510
  const label = `[${number}]`;
25002
- if (slot.step === void 0) {
25003
- const [message] = messages;
25004
- if (message?.role === "tool") return `${label} tool result of call ${message.toolCallId}`;
25005
- return `${label} harness: ${cueText(textOf2(messages))}`;
25006
- }
25007
- const failed2 = new Set(messages.filter((message) => message.role === "tool" && message.isError === true).map((message) => message.toolCallId));
25008
- const assistant = messages.filter((message) => message.role === "assistant");
25009
- const text = textOf2(assistant);
25010
- const calls = assistant.flatMap(blocksOf).filter((block) => block?.type === "tool-call");
25511
+ if (facts.kind === "result") return `${label} tool result of call ${facts.toolCallId}`;
25512
+ if (facts.kind !== "step") return `${label} harness: ${cueText(facts.text)}`;
25011
25513
  return [
25012
25514
  `${label} assistant step`,
25013
- ` text: ${text === "" ? "none" : cueText(text)}`,
25014
- ...calls.map((call) => ` call ${call.id} ${call.name} \u2192 ${failed2.has(call.id) ? "error" : "ok"}${argumentsCueOf(call)}`)
25515
+ ` text: ${facts.assistantText === "" ? "none" : cueText(facts.assistantText)}`,
25516
+ ...facts.calls.map((call) => ` call ${call.id} ${call.name} \u2192 ${call.failed ? "error" : "ok"}${argumentsCueOf(call)}`)
25015
25517
  ].join("\n");
25016
25518
  }).join("\n");
25017
25519
  }
@@ -25041,21 +25543,21 @@ Held, beside the notes:
25041
25543
  {held}
25042
25544
 
25043
25545
  Name an identifier, path, command, version, number or error text only when the next step needs it and the held text does not give it. Copy exactly whatever a note names. Take a number from the slot; never recount it. Keep every scope word: not, never, only, except, unless, if; \u4E0D, \u6CA1, \u53EA, \u9664, \u82E5. Write each note in the dominant language of its slot. Fragments are fine, as in a commit message body; write a full sentence where a fragment would leave order, cause or scope unclear. Notes speak about the task's work, not about slots, notes or this request.`;
25044
- var tailMessage = ({ entries, asked, held }) => {
25045
- const rows = rowsOf(entries);
25546
+ function planSummary(slotFacts, held) {
25547
+ const notes = slotFacts.map(verbatimNoteOf);
25548
+ const verbatim = notes.map((note) => note?.text ?? null);
25549
+ const wholeUserSlots = notes.flatMap((note, at) => note?.whole ? [at] : []);
25550
+ const askedCount = verbatim.filter((note) => note === null).length;
25046
25551
  const heldList = [...[...held.paths.keys()].map((key) => `- file ${key}`), ...[...held.skills.keys()].map((name3) => `- skill ${name3}`)].join("\n") || "none";
25047
- const values = { rows, N: String(asked.length), held: heldList };
25048
- return {
25049
- role: "user",
25050
- content: [{ type: "text", text: TAIL_TEMPLATE.replace(/\{(rows|N|held)\}/gu, (_, key) => values[key]) }]
25051
- };
25052
- };
25552
+ const values = { rows: rowsOf(slotFacts, verbatim), N: String(askedCount), held: heldList };
25553
+ return { tailText: TAIL_TEMPLATE.replace(/\{(rows|N|held)\}/gu, (_, key) => values[key]), verbatim, wholeUserSlots, askedCount };
25554
+ }
25053
25555
  function notesOf(parsed, count) {
25054
25556
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || Object.keys(parsed).length !== count) return void 0;
25055
25557
  const notes = Array.from({ length: count }, (_, at) => parsed[String(at + 1)]);
25056
25558
  return notes.every((note) => typeof note === "string") ? notes : void 0;
25057
25559
  }
25058
- function parseSummaries(text, count, loads2) {
25560
+ function parseNotes(text, askedCount, loads2) {
25059
25561
  let parsed;
25060
25562
  try {
25061
25563
  parsed = JSON.parse(text);
@@ -25066,22 +25568,48 @@ function parseSummaries(text, count, loads2) {
25066
25568
  return void 0;
25067
25569
  }
25068
25570
  }
25069
- return notesOf(parsed, count);
25571
+ return notesOf(parsed, askedCount);
25572
+ }
25573
+ function mergeNotes(verbatim, notes) {
25574
+ let next = 0;
25575
+ return verbatim.map((note) => note ?? notes[next++]);
25576
+ }
25577
+
25578
+ // dsh/src/inner-summary.js
25579
+ var SUMMARY_PURPOSE = "inner-compaction";
25580
+ var FILTER_TEXT = "content_filtered";
25581
+ var DISPLAYED_OPTIONS = ["provider", "model", "reasoningEffort", "purpose", "sessionId"];
25582
+ var DISPLAYED_INPUT = ["throughSeq", "headerSeq"];
25583
+ var provided = (source, keys) => Object.fromEntries(keys.filter((key) => source[key] !== void 0).map((key) => [key, source[key]]));
25584
+ function requestDisplayOf(options, input) {
25585
+ const { messages, tools, toolHistory } = options;
25586
+ return {
25587
+ options: provided(options, DISPLAYED_OPTIONS),
25588
+ messages: { count: messages.length - 1, tail: messages.at(-1) },
25589
+ ...provided(input, DISPLAYED_INPUT),
25590
+ ...tools === void 0 ? {} : { tools: { count: tools.length } },
25591
+ ...toolHistory === void 0 ? {} : {
25592
+ toolHistory: { updates: toolHistory.updates.map(({ messageId, additions }) => ({ messageId, additions: additions.map((tool) => tool.name) })) }
25593
+ }
25594
+ };
25595
+ }
25596
+ function slotMessagesOf({ slots, session, events, range }) {
25597
+ const bySeq = new Map(events.map((event) => [event.seq, event]));
25598
+ const selected = new Set(range);
25599
+ return slots.map((slot) => slot.seqs.filter((seq) => selected.has(seq)).map((seq) => session.deriveEventMessage(bySeq.get(seq))).filter((message) => message != null));
25070
25600
  }
25071
25601
  var NO_OBSERVER = Object.freeze({ dispatch() {
25072
25602
  }, chunk() {
25073
25603
  } });
25074
- var NO_CARRIER = Object.freeze({ scope: () => ({ run: (body2) => body2(), evidence: () => null }) });
25075
- async function summarizeSlots({ llm, session, index, events, selection, slots, range, held, signal, kit, observer = NO_OBSERVER, carrier = NO_CARRIER }) {
25604
+ var NO_CARRIER2 = Object.freeze({ scope: () => ({ run: (body2) => body2(), evidence: () => null }) });
25605
+ async function summarizeSlots({ llm, session, index, events, selection, slots, range, held, signal, kit, observer = NO_OBSERVER, carrier = NO_CARRIER2 }) {
25076
25606
  const { provider, model, reasoningEffort } = selection;
25077
25607
  const chosen = { provider, model, ...reasoningEffort === void 0 ? {} : { reasoningEffort } };
25078
25608
  const tools = session.requestHeader()?.tools;
25079
25609
  const perSlot = slotMessagesOf({ slots, session, events, range });
25080
- const verbatim = slots.map((slot, index2) => verbatimNoteOf(slot, perSlot[index2]));
25081
- const entries = slots.map((slot, index2) => ({ slot, messages: perSlot[index2], verbatim: verbatim[index2], index: index2 }));
25082
- const asked = entries.filter((entry) => entry.verbatim === null);
25083
- const tail = tailMessage({ entries, asked, held });
25084
- const input = { throughSeq: session.seq - 1, headerSeq: headerSeqOf(index), tail };
25610
+ const { tailText, verbatim, wholeUserSlots, askedCount } = planSummary(slots.map((slot, at) => slotFactsOf(slot, perSlot[at])), held);
25611
+ const tail = { role: "user", content: [{ type: "text", text: tailText }] };
25612
+ const input = { throughSeq: session.seq - 1, headerSeq: headerSeqIn(index, { latest: true }), tail };
25085
25613
  const options = {
25086
25614
  ...chosen,
25087
25615
  messages: [...session.deriveMessages(), tail],
@@ -25118,7 +25646,7 @@ async function summarizeSlots({ llm, session, index, events, selection, slots, r
25118
25646
  });
25119
25647
  const stream = accumulator.snapshot();
25120
25648
  const carrierCache = watching.evidence();
25121
- const call = { v: 1, purpose: SUMMARY_PURPOSE, selection: chosen, input, range, stream, endedAt, ...carrierCache === null ? {} : { carrierCache }, ...thrown === void 0 ? {} : { thrown } };
25649
+ const call = callRecordOf({ purpose: SUMMARY_PURPOSE, selection: chosen, input, range, stream, endedAt, carrierCache, thrown });
25122
25650
  if (thrown !== void 0) return { ok: false, reason: `the summary stream threw: ${thrown.message}`, call };
25123
25651
  const finish = kit.lastAssistantStreamChunk(stream, "finish");
25124
25652
  if (finish === void 0) return { ok: false, reason: "the summary stream ended without a finish chunk", call };
@@ -25126,35 +25654,23 @@ async function summarizeSlots({ llm, session, index, events, selection, slots, r
25126
25654
  const detail = finish.reason.failure === void 0 ? "" : `: ${finish.reason.failure.message}`;
25127
25655
  const reason = `the summary stream finished with ${finish.reason.kind}${detail}`;
25128
25656
  const filtered = finish.reason.kind === "error" && String(finish.reason.failure?.message).includes(FILTER_TEXT);
25129
- return { ok: false, ...filtered ? { failure: FILTER_FAILURE } : {}, reason, call };
25657
+ const failure4 = filtered ? FILTER_FAILURE : finish.reason.kind === "tool-calls" ? FORMAT_FAILURE : void 0;
25658
+ return { ok: false, ...failure4 === void 0 ? {} : { failure: failure4 }, reason, call };
25130
25659
  }
25131
- if (blocks.some((block) => block.type === "tool-call")) return { ok: false, reason: "the summary stream made a tool call", call };
25660
+ if (blocks.some((block) => block.type === "tool-call")) return { ok: false, failure: FORMAT_FAILURE, reason: "the summary stream made a tool call", call };
25132
25661
  const text = blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
25133
- const notes = parseSummaries(text, asked.length, kit.loads);
25662
+ const notes = parseNotes(text, askedCount, kit.loads);
25134
25663
  if (notes === void 0) {
25135
- return { ok: false, failure: FORMAT_FAILURE, reason: `the summary text is not a JSON object of ${asked.length} strings keyed "1" to "${asked.length}"`, call };
25664
+ return { ok: false, failure: FORMAT_FAILURE, reason: `the summary text is not a JSON object of ${askedCount} strings keyed "1" to "${askedCount}"`, call };
25136
25665
  }
25137
- const answered = new Map(asked.map(({ index: index2 }, at) => [index2, notes[at]]));
25138
- const summaries = verbatim.map((note, index2) => note ?? answered.get(index2));
25139
- return { ok: true, summaries, call };
25666
+ return { ok: true, summaries: mergeNotes(verbatim, notes), verbatimSeqs: wholeUserSlots.map((at) => slots[at].seqs[0]), call };
25140
25667
  }
25141
25668
 
25142
25669
  // dsh/src/inner-seal.js
25143
- var INNER_CALL_RECORD_TYPE = "plugin:session-watcher/inner-call";
25144
- var INNER_ATTEMPT_RECORD_TYPE = "plugin:session-watcher/inner-attempt";
25145
- var INNER_END_RECORD_TYPE = "plugin:session-watcher/inner-end";
25146
- var UNCACHED_SHARE_ALERT = 1 / 2;
25147
- var SUMMARY_MAX_REQUESTS = 3;
25148
- var SUMMARY_FILTER_RETRIES = 1;
25149
- function rangesOf(lines) {
25150
- const ranges = [];
25151
- for (const line of [...lines].sort((a, b) => a - b)) {
25152
- const last = ranges.at(-1);
25153
- if (last !== void 0 && last.offset + last.limit === line) last.limit += 1;
25154
- else ranges.push({ offset: line, limit: 1 });
25155
- }
25156
- return ranges;
25157
- }
25670
+ var PLUGIN_RECORD_NAMESPACE = "plugin:session-watcher/";
25671
+ var INNER_CALL_RECORD_TYPE = `${PLUGIN_RECORD_NAMESPACE}${CALL_RECORD_NAME}`;
25672
+ var INNER_ATTEMPT_RECORD_TYPE = `${PLUGIN_RECORD_NAMESPACE}${ATTEMPT_RECORD_NAME}`;
25673
+ var INNER_END_RECORD_TYPE = `${PLUGIN_RECORD_NAMESPACE}${END_RECORD_NAME}`;
25158
25674
  var messageOf5 = (error) => error instanceof Error ? error.message : String(error);
25159
25675
  var USAGE_FIELDS = ["inputTokens", "cacheReadTokens", "cacheWriteTokens"];
25160
25676
  function diagnose({ session, recordSeq, call, range, kit }) {
@@ -25166,8 +25682,8 @@ function diagnose({ session, recordSeq, call, range, kit }) {
25166
25682
  writeDiagnostic(session.id, hostDiagnostic("inner_usage_gap", `${at}: the auxiliary call ${what}, so its uncached share is unknown`));
25167
25683
  return;
25168
25684
  }
25169
- const { inputTokens, cacheReadTokens, cacheWriteTokens } = usage;
25170
- const share = (inputTokens + cacheWriteTokens) / (inputTokens + cacheReadTokens + cacheWriteTokens);
25685
+ const canonical = { input: usage.inputTokens, cacheRead: usage.cacheReadTokens, cacheWrite: usage.cacheWriteTokens };
25686
+ const share = uncachedOf(canonical) / stockOf(canonical);
25171
25687
  if (!(share > UNCACHED_SHARE_ALERT)) return;
25172
25688
  const { provider, model, reasoningEffort } = call.selection;
25173
25689
  const selection = `${provider}/${model}${reasoningEffort === void 0 ? "" : ` ${reasoningEffort}`}`;
@@ -25207,27 +25723,20 @@ async function attachmentsOf({ slots, range, events, attachments, signal }) {
25207
25723
  return answer;
25208
25724
  }
25209
25725
  var textOfMessage = (message) => message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
25210
- var jsonOf = (text) => {
25726
+ function answeredOf(args2, result) {
25727
+ if (result === void 0 || result.isError === true) return [];
25728
+ let asked;
25211
25729
  try {
25212
- return JSON.parse(text);
25730
+ asked = JSON.parse(args2)?.questions;
25213
25731
  } catch {
25214
- return void 0;
25732
+ return [];
25215
25733
  }
25216
- };
25217
- function userTextOf(answer) {
25218
- const { selected, custom } = answer ?? {};
25219
- if (!Array.isArray(selected) || !selected.every((label) => typeof label === "string") || custom !== void 0 && typeof custom !== "string") return void 0;
25220
- const text = [...selected, ...custom ? [custom] : []].join("\n");
25221
- return text.trim() === "" ? void 0 : text;
25222
- }
25223
- function answeredOf(args2, result) {
25224
- if (result === void 0 || result.isError === true) return [];
25225
- const asked = jsonOf(args2)?.questions;
25226
- const answered = jsonOf(textOfMessage(result))?.answers;
25227
- if (!Array.isArray(asked) || !Array.isArray(answered)) return [];
25734
+ if (!Array.isArray(asked)) return [];
25735
+ const answers = askAnswersOf(textOfMessage(result));
25228
25736
  return asked.flatMap((item) => {
25229
- const user = userTextOf(typeof item?.id === "string" ? answered.find((answer) => answer?.id === item.id) : void 0);
25230
- return typeof item?.question === "string" && user !== void 0 ? [{ question: item.question, user }] : [];
25737
+ const answer = typeof item?.id === "string" ? answers.find((each) => each.id === item.id) : void 0;
25738
+ const user = answer === void 0 ? "" : [...answer.selected, ...answer.custom ? [answer.custom] : []].join("\n");
25739
+ return typeof item?.question === "string" && user.trim() !== "" ? [{ question: item.question, user }] : [];
25231
25740
  });
25232
25741
  }
25233
25742
  function questionsOf({ slots, bySeq }) {
@@ -25235,24 +25744,24 @@ function questionsOf({ slots, bySeq }) {
25235
25744
  try {
25236
25745
  const events = seqs.map((seq) => bySeq.get(seq));
25237
25746
  const results = /* @__PURE__ */ new Map();
25238
- for (const { type, data } of events) if (type === "tool/result" && !results.has(data.message.toolCallId)) results.set(data.message.toolCallId, data.message);
25239
- return events.filter((event) => event.type === "assistant/message").flatMap((event) => event.data.message.content).filter((block) => block.type === "tool-call" && block.name === ASK_TOOL_NAME).flatMap(({ id, arguments: args2 }) => answeredOf(args2, results.get(id)));
25747
+ for (const event of events) {
25748
+ if (event.type === "tool/result" && !results.has(event.data.message.toolCallId)) results.set(event.data.message.toolCallId, event);
25749
+ }
25750
+ return events.filter((event) => event.type === "assistant/message").flatMap(({ data }) => data.message.content.filter((block) => block.type === "tool-call" && block.name === ASK_TOOL_NAME).flatMap(({ id, arguments: args2 }) => {
25751
+ const result = results.get(id);
25752
+ if (result === void 0) return [];
25753
+ return answeredOf(args2, result.data.message).map((pair) => ({ ...pair, seqs: [result.seq] }));
25754
+ }));
25240
25755
  } catch {
25241
25756
  return [];
25242
25757
  }
25243
25758
  });
25244
25759
  }
25245
25760
  var holdsEvidence2 = (event) => event?.type === "user/message" && carriesEvidence(event.data?.source);
25246
- function touchedOf({ paths, skills, touched }) {
25247
- return {
25248
- paths: new Map([...paths].filter(([key]) => touched.paths.has(key))),
25249
- skills: new Map([...skills].filter(([name3]) => touched.skills.has(name3)))
25250
- };
25251
- }
25252
25761
  async function currentOf(held, read, agent, signal) {
25253
25762
  const current = { paths: /* @__PURE__ */ new Map(), skills: held.skills };
25254
25763
  for (const [key, lines] of held.paths) {
25255
- const { read: answer, displayPath } = await read(agent, key, rangesOf(lines), signal);
25764
+ const { read: answer, displayPath } = await read(agent, key, runsOf(lines).map(([first, last]) => ({ offset: first, limit: last - first + 1 })), signal);
25256
25765
  current.paths.set(key, { displayPath, read: answer });
25257
25766
  }
25258
25767
  return current;
@@ -25261,11 +25770,23 @@ function retainedSources(session, range, bySeq) {
25261
25770
  const inside = new Set(range.map((seq) => bySeq.get(seq)).filter(holdsEvidence2).map((event) => event.data.id));
25262
25771
  return session.deriveMessages().filter((each) => each.role === "user" && carriesEvidence(each.source) && !inside.has(each.id)).map((each) => each.source);
25263
25772
  }
25264
- var carriedOf = (earlier, current) => omitShown(carryChanges(foldCarried(earlier), current), earlier);
25265
- function stateAt(session, readState, earlier) {
25773
+ async function gitAhead(readGit, session, signal) {
25774
+ if (readGit === void 0) return void 0;
25775
+ try {
25776
+ const text = await readGit(session, signal);
25777
+ return text === null ? void 0 : () => text;
25778
+ } catch (error) {
25779
+ return () => {
25780
+ throw error;
25781
+ };
25782
+ }
25783
+ }
25784
+ function stateAt(session, readState, earlier, git) {
25266
25785
  try {
25267
25786
  const tools = new Set((session.requestHeader()?.tools ?? []).map(({ name: name3 }) => name3));
25268
- return carryState(readState(session), {
25787
+ const state = readState(session);
25788
+ return carryState({ ...state, items: { ...state.items, [GIT_STATE_ITEM.key]: git } }, {
25789
+ stateItems: CARRIER_TABLE.stateItems,
25269
25790
  tools,
25270
25791
  earlier,
25271
25792
  failed: (item, error) => writeDiagnostic(session.id, hostDiagnostic("inner_state_failed", `${item.key}: ${messageOf5(error)}`))
@@ -25275,14 +25796,25 @@ function stateAt(session, readState, earlier) {
25275
25796
  return null;
25276
25797
  }
25277
25798
  }
25278
- async function quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset }) {
25799
+ function historyReadOf(meter, session) {
25800
+ try {
25801
+ return { tokens: meter.measure(session).totalTokens };
25802
+ } catch (error) {
25803
+ return { error };
25804
+ }
25805
+ }
25806
+ async function quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset, history }) {
25279
25807
  let estimate = null;
25280
25808
  try {
25281
25809
  const ctp = ctpOf(session.id);
25282
25810
  if (ctp === null) throw new Error(`session ${session.id} has no model policy to price its range under`);
25283
25811
  const current = await currentOf(held, readUnobserved2, agent, signal);
25284
25812
  const carried = carriedOf(retainedSources(session, range, bySeq), current);
25285
- estimate = estimateInnerA({ n: stepN, range, messageOf: (seq) => session.deriveEventMessage(bySeq.get(seq)), carried, ctp });
25813
+ const texts = range.flatMap((seq) => {
25814
+ const message = session.deriveEventMessage(bySeq.get(seq));
25815
+ return message === null ? [] : [requestTextOf(message)];
25816
+ });
25817
+ estimate = estimateInnerA({ n: stepN, texts, bText: renderCarried(carried, CARRIER_TABLE), ctp });
25286
25818
  } catch (error) {
25287
25819
  writeDiagnostic(session.id, hostDiagnostic("inner_quote_failed", error));
25288
25820
  }
@@ -25292,20 +25824,20 @@ async function quoteOf({ session, agent, signal, range, stepN, held, bySeq, read
25292
25824
  } catch (error) {
25293
25825
  writeDiagnostic(session.id, hostDiagnostic("inner_quote_failed", error));
25294
25826
  }
25295
- return innerQuote({ n: stepN, estimate, cRatio: ratio, preset });
25827
+ if (history.error !== void 0) writeDiagnostic(session.id, hostDiagnostic("inner_quote_failed", history.error));
25828
+ return innerQuote({ n: stepN, estimate, cRatio: ratio, preset, summaryReadCost: history.tokens });
25296
25829
  }
25297
25830
  async function requestSummary({ monitor, session, range, quote, llm, index, events, selection, fallback, slots, held, signal, kit, carrier }) {
25298
- const ladder = [selection, ...Array(SUMMARY_FILTER_RETRIES).fill(selection), ...fallback === null ? [] : [fallback]];
25299
- let rung = 0;
25300
- for (let request = 1; ; ) {
25831
+ const ladder = createRetryLadder({ selection, fallback });
25832
+ for (; ; ) {
25301
25833
  const attempt = monitor.begin(session, { range, quote });
25302
25834
  let again = false;
25303
25835
  try {
25304
- const summary = await summarizeSlots({ llm, session, index, events, selection: ladder[rung], slots, range, held, signal, kit, observer: attempt, carrier });
25836
+ const summary = await summarizeSlots({ llm, session, index, events, selection: ladder.current(), slots, range, held, signal, kit, observer: attempt, carrier });
25305
25837
  attempt.responded({ endedAt: summary.call.endedAt });
25306
25838
  let recorded = false;
25307
25839
  const settle = () => {
25308
- const call = attempt.startSeq === null ? summary.call : { ...summary.call, attempt: attempt.startSeq };
25840
+ const call = callRecordOf({ ...summary.call, attempt: attempt.startSeq });
25309
25841
  const recordSeq = kit.appendPluginRecord(session, INNER_CALL_RECORD_TYPE, call);
25310
25842
  diagnose({ session, recordSeq, call: summary.call, range, kit });
25311
25843
  recorded = true;
@@ -25328,13 +25860,7 @@ async function requestSummary({ monitor, session, range, quote, llm, index, even
25328
25860
  };
25329
25861
  if (summary.ok) return { attempt, summary, settle, failed: failed2 };
25330
25862
  const error = failed2(summary.reason);
25331
- if (recorded && summary.failure === FORMAT_FAILURE && request < SUMMARY_MAX_REQUESTS) {
25332
- again = true;
25333
- request += 1;
25334
- } else if (recorded && summary.failure === FILTER_FAILURE && rung < ladder.length - 1) {
25335
- again = true;
25336
- rung += 1;
25337
- }
25863
+ again = recorded && ladder.next(summary.failure);
25338
25864
  throw error;
25339
25865
  } catch (error) {
25340
25866
  attempt.failed(error, { cancelled: signal.aborted, cancelReason: signal.reason });
@@ -25343,7 +25869,7 @@ async function requestSummary({ monitor, session, range, quote, llm, index, even
25343
25869
  }
25344
25870
  }
25345
25871
  }
25346
- function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFile, readUnobserved: readUnobserved2, readState, cRatio, ctpOf, llm, attachments, meter, kit, monitor, readSettings, carrier }) {
25872
+ function createInnerSeal({ readMode, eventFacts, readSession, heldView, readFile, readUnobserved: readUnobserved2, readState, readGit, cRatio, ctpOf, llm, attachments, meter, kit, monitor, readSettings, carrier }) {
25347
25873
  const reportedInvalid = /* @__PURE__ */ new Set();
25348
25874
  return async (payload, next) => {
25349
25875
  const { agent, signal, modelSelection } = payload;
@@ -25354,22 +25880,24 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25354
25880
  writeDiagnostic(session.id, hostDiagnostic("inner_mode_invalid", "the inner mode record does not read as a mode, so this session seals nothing"));
25355
25881
  }
25356
25882
  if (mode !== "on") return next();
25357
- const index = sourceFacts(session.id);
25883
+ const index = eventFacts(session.id);
25358
25884
  if (index === null) return next();
25359
25885
  const cheap = innerSource(index, session.surface.nodes);
25360
25886
  if (cheap.paused || cheap.stepN < INNER_QUOTE.minSteps) return next();
25361
25887
  const { preset, fallbackModel } = readSettings();
25362
25888
  const nodes = [...session.surface.nodes];
25889
+ const history = historyReadOf(meter, session);
25363
25890
  const reading = readSession(session.id);
25364
25891
  const { events } = await reading;
25365
- const facts = new Map(events.map((event) => [event.seq, sourceFactOf(event)]));
25892
+ const facts = eventFactsOf(events);
25366
25893
  const { range, stepN, paused } = innerSource(facts, nodes);
25367
25894
  if (paused || stepN < INNER_QUOTE.minSteps) return next();
25368
- const slots = skeletonSlots(events, nodes, range);
25895
+ const slots = skeletonSlots(facts, nodes, range);
25369
25896
  const bySeq = new Map(events.map((event) => [event.seq, event]));
25370
- const originals = prunedOriginals(events, range);
25371
- const held = heldView(session.id, events, [...range, ...originals]);
25372
- const quote = await quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset });
25897
+ const originals = range.flatMap((seq) => facts.get(seq).originals);
25898
+ const replaced = [...range, ...originals];
25899
+ const held = heldView(session.id, events);
25900
+ const quote = await quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset, history });
25373
25901
  if (signal.aborted) throw signal.reason;
25374
25902
  if (quote.trigger === null) return next();
25375
25903
  const { attempt, summary, settle, failed: failed2 } = await requestSummary({
@@ -25383,7 +25911,7 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25383
25911
  selection: modelSelection,
25384
25912
  fallback: fallbackModel,
25385
25913
  slots,
25386
- held: touchedOf(held),
25914
+ held: touchedOf(held, replaced),
25387
25915
  signal,
25388
25916
  kit,
25389
25917
  carrier
@@ -25391,9 +25919,11 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25391
25919
  try {
25392
25920
  let slotAttachments;
25393
25921
  let current;
25922
+ let git;
25394
25923
  try {
25395
25924
  slotAttachments = await attachmentsOf({ slots, range, events, attachments, signal });
25396
25925
  current = await currentOf(held, readFile, agent, signal);
25926
+ git = await gitAhead(readGit, session, signal);
25397
25927
  } catch (error) {
25398
25928
  throw failed2(messageOf5(error));
25399
25929
  }
@@ -25409,21 +25939,17 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25409
25939
  const shadowed = new Set(range);
25410
25940
  try {
25411
25941
  const earlier = retainedSources(session, range, bySeq);
25412
- const slotQuestions = questionsOf({ slots, bySeq });
25413
- const source = {
25414
- kind: INNER_SEAL_KIND,
25415
- v: 1,
25416
- slots: slots.map(({ seqs }, index2) => ({
25417
- seqs,
25418
- text: summary.summaries[index2],
25419
- ...slotQuestions[index2].length > 0 ? { questions: slotQuestions[index2] } : {},
25420
- ...slotAttachments[index2].length > 0 ? { attachments: slotAttachments[index2] } : {}
25421
- })),
25422
- ...carriedOf(earlier, current)
25423
- };
25424
- const state = stateAt(session, readState, earlier);
25425
- if (state !== null) source.state = state;
25426
- message = kit.createUserMessage({ content: renderCarrier(source), source });
25942
+ const source = assembleCarrierSource({
25943
+ slots,
25944
+ summaries: summary.summaries,
25945
+ questions: questionsOf({ slots, bySeq }),
25946
+ attachments: slotAttachments,
25947
+ oldReads: slots.map(({ seqs }) => held.oldReads.filter(({ seq }) => seqs.includes(seq))),
25948
+ verbatimSeqs: summary.verbatimSeqs,
25949
+ changes: carriedOf(earlier, current),
25950
+ state: stateAt(session, readState, earlier, git)
25951
+ });
25952
+ message = kit.createUserMessage({ content: renderCarrier(source, CARRIER_TABLE), source });
25427
25953
  shadowedTokenCount = meter.measure(session).nodes.filter((node) => shadowed.has(node.seq)).reduce((sum, node) => sum + node.heuristicTokens, 0);
25428
25954
  } catch (error) {
25429
25955
  throw failed2(messageOf5(error));
@@ -25436,7 +25962,7 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25436
25962
  });
25437
25963
  session.append("user/message", message, {
25438
25964
  surfaceOp: { op: "replace", startSeq, endSeq },
25439
- sourceEventSeqs: [recordSeq, prune.seq, ...range, ...originals]
25965
+ sourceEventSeqs: sourceEventSeqsOf({ callSeq: recordSeq, pruneSeq: prune.seq, replaced })
25440
25966
  });
25441
25967
  } catch (error) {
25442
25968
  attempt.failed(error, { cancelled: signal.aborted, cancelReason: signal.reason });
@@ -25474,7 +26000,7 @@ function createInnerMonitor({ appendPluginRecord: appendPluginRecord2, publish }
25474
26000
  guard("inner_monitor_start_failed", () => {
25475
26001
  const request = requestDisplayOf(options, input);
25476
26002
  const recorded = { first: range[0], last: range.at(-1), count: range.length };
25477
- attempt.startSeq = appendPluginRecord2(session, INNER_ATTEMPT_RECORD_TYPE, { v: 1, range: recorded, request, quote });
26003
+ attempt.startSeq = appendPluginRecord2(session, INNER_ATTEMPT_RECORD_TYPE, attemptRecordOf({ range: recorded, request, quote }));
25478
26004
  owner = { sessionId, entry: { attempt: attempt.startSeq, phase: "generating", endedAt: null, request, tools: options.tools, stream } };
25479
26005
  active.add(owner);
25480
26006
  });
@@ -25497,12 +26023,11 @@ function createInnerMonitor({ appendPluginRecord: appendPluginRecord2, publish }
25497
26023
  failed(error, circumstances) {
25498
26024
  if (attempt.startSeq === null) return;
25499
26025
  guard("inner_monitor_end_failed", () => {
25500
- appendPluginRecord2(session, INNER_END_RECORD_TYPE, {
25501
- v: 1,
26026
+ appendPluginRecord2(session, INNER_END_RECORD_TYPE, endRecordOf({
25502
26027
  attempt: attempt.startSeq,
25503
26028
  outcome: circumstances.cancelled ? "cancelled" : "failed",
25504
26029
  reason: reasonOf(error, circumstances)
25505
- });
26030
+ }));
25506
26031
  });
25507
26032
  active.delete(owner);
25508
26033
  changed2();
@@ -25515,7 +26040,7 @@ function createInnerMonitor({ appendPluginRecord: appendPluginRecord2, publish }
25515
26040
  }
25516
26041
 
25517
26042
  // lib/harness/dsh/inner-monitor-source.js
25518
- function blockOf(block) {
26043
+ function blockOf2(block) {
25519
26044
  switch (block?.type) {
25520
26045
  case "text":
25521
26046
  return { type: "text", text: block.text };
@@ -25533,10 +26058,37 @@ function blockOf(block) {
25533
26058
  }
25534
26059
  function sourceEventView(event, { visible }) {
25535
26060
  const message = event.data?.message ?? event.data;
25536
- const blocks = (Array.isArray(message?.content) ? message.content : []).map(blockOf);
26061
+ const blocks = (Array.isArray(message?.content) ? message.content : []).map(blockOf2);
25537
26062
  const shown = event.type === "tool/result" ? [{ type: "tool-result", callId: message?.toolCallId, isError: message?.isError === true, blocks }] : blocks;
25538
26063
  return { seq: event.seq, type: event.type, visible, blocks: shown, raw: event };
25539
26064
  }
26065
+ function toolCallsOf(event) {
26066
+ if (event.type !== "assistant/message") return [];
26067
+ const uses = reduceDshEvent(event).observations.filter(({ type }) => type === "tool-use");
26068
+ const blocks = sourceEventView(event, { visible: true }).blocks.filter(({ type }) => type === "tool-call");
26069
+ return uses.map(({ toolUseId, name: name3 }, at) => ({ id: toolUseId, name: name3, arguments: blocks[at].arguments }));
26070
+ }
26071
+ function toolResultOf(event) {
26072
+ if (event.type !== "tool/result") return null;
26073
+ const [result] = reduceDshEvent(event).observations;
26074
+ if (result === void 0) return null;
26075
+ const [{ blocks }] = sourceEventView(event, { visible: true }).blocks;
26076
+ return { id: result.toolUseId, error: result.isError === true, empty: blocks.every((block) => block.type === "text" && block.text === "") };
26077
+ }
26078
+ var SOURCE_CATEGORIES = { "system/message": "system", "developer/message": "developer", "tool/result": "tool", "assistant/message": "assistant" };
26079
+ var HUMAN_SOURCE_KIND = "user";
26080
+ function sourceCategoryOf({ type, kind }) {
26081
+ if (type === "user/message") {
26082
+ if (typeof kind !== "string") return "other";
26083
+ return kind === HUMAN_SOURCE_KIND ? "user" : "injected";
26084
+ }
26085
+ return SOURCE_CATEGORIES[type] ?? "other";
26086
+ }
26087
+ function slotSourceOf(event) {
26088
+ const message = event.data?.message ?? event.data;
26089
+ const source = { type: event.type, kind: message?.source?.kind ?? null };
26090
+ return { ...source, category: sourceCategoryOf(source) };
26091
+ }
25540
26092
  var placeholderOf = ({ type, attachment }) => `[${type}${attachment?.name === void 0 ? "" : ` ${attachment.name}`}]`;
25541
26093
  function callLabel(block) {
25542
26094
  const { groupKey, kind, detail } = dshToolEvidenceProfile.residualIdentity(block.name, parseArguments(block.arguments) ?? {});
@@ -25568,31 +26120,272 @@ function eventDisplayText(event) {
25568
26120
  return textOf3(sourceEventView(event, { visible: true }).blocks, displayCallText);
25569
26121
  }
25570
26122
 
26123
+ // dsh/src/monitor-settlement-recall.js
26124
+ var stepKey2 = ({ turn, step } = {}) => `${turn}:${step}`;
26125
+ var ABORTED_BEFORE_DISPATCH = "ABORTED_BEFORE_DISPATCH";
26126
+ var isInitiated = ({ target, dispatched, skipped }) => target !== void 0 && dispatched && !skipped;
26127
+ var callRecallOf = (call = {}) => isInitiated(call) ? "recall" : call.target === void 0 || call.dispatched || call.resulted ? "other" : "unknown";
26128
+ function judgeOf({ tools, calls }) {
26129
+ const states = tools.map(({ id }) => callRecallOf(calls.get(id)));
26130
+ if (states.includes("other") || states.length === 0) return "other";
26131
+ return states.includes("unknown") ? "unknown" : "pure";
26132
+ }
26133
+ function reportPositions(seals, samples, tailCalls) {
26134
+ const positions = /* @__PURE__ */ new Map();
26135
+ const landing = /* @__PURE__ */ new Map();
26136
+ const sealAt = /* @__PURE__ */ new Map();
26137
+ let offset = 0;
26138
+ let proved = true;
26139
+ for (const [carrier, { attempt, range }] of seals) {
26140
+ const steps = /* @__PURE__ */ new Map();
26141
+ for (const seq of range) {
26142
+ const sample = samples.get(seq);
26143
+ if (sample?.counted) steps.set(stepKey2(sample.event.data), seq);
26144
+ }
26145
+ const n = attempt.quote?.n ?? 0;
26146
+ if (steps.size === n) {
26147
+ for (const [key, seq] of steps) {
26148
+ positions.set(seq, offset += 1);
26149
+ landing.set(key, offset);
26150
+ }
26151
+ } else {
26152
+ offset += n;
26153
+ if (sealAt.size > 0) proved = false;
26154
+ }
26155
+ sealAt.set(carrier, offset);
26156
+ }
26157
+ const lastCarrier = [...seals.keys()].at(-1);
26158
+ const tail = [...samples.values()].filter(({ counted, event }) => counted && event.seq > lastCarrier);
26159
+ if (tail.length === tailCalls) {
26160
+ for (const { event } of tail) {
26161
+ positions.set(event.seq, offset += 1);
26162
+ landing.set(stepKey2(event.data), offset);
26163
+ }
26164
+ } else {
26165
+ proved = false;
26166
+ }
26167
+ const firstCarrier = seals.keys().next().value;
26168
+ const covered = proved && [...samples.values()].every(({ counted, event }) => !counted || event.seq <= firstCarrier || positions.has(event.seq));
26169
+ return { positions, landing, sealAt, covered };
26170
+ }
26171
+ var placeOf = (seq, owners, { landing, sealAt }) => sealAt.get(seq) ?? landing.get(owners.get(seq)) ?? null;
26172
+ function settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls, sessionId, isNoise }) {
26173
+ const seals = new Map(attempts.map((attempt) => {
26174
+ const call = log.get(attempt.call?.seq)?.data;
26175
+ return [attempt.carrier.seq, { attempt, range: isCallRecord(call) ? call.range : [] }];
26176
+ }));
26177
+ if (seals.size === 0) return {};
26178
+ const starts = new Set(attempts.map(({ id }) => id));
26179
+ const samples = /* @__PURE__ */ new Map();
26180
+ const before = /* @__PURE__ */ new Map();
26181
+ const active = /* @__PURE__ */ new Map();
26182
+ const owners = /* @__PURE__ */ new Map();
26183
+ let ctp;
26184
+ let lastMeasured;
26185
+ let seal;
26186
+ let sample;
26187
+ let open = null;
26188
+ const targetOf2 = (call, requestSeq) => {
26189
+ const target = eventReadTargetOf(call);
26190
+ return target && (target.sessionId === void 0 || target.sessionId === sessionId) && target.seq >= events[0].seq && target.seq < requestSeq && log.has(target.seq) ? target.seq : void 0;
26191
+ };
26192
+ for (const event of events) {
26193
+ const { seq, type, data } = event;
26194
+ if (starts.has(seq)) before.set(seq, lastMeasured);
26195
+ if (seals.has(seq)) {
26196
+ seal = seals.get(seq);
26197
+ for (const replaced of seal.range) active.delete(replaced);
26198
+ lastMeasured = void 0;
26199
+ }
26200
+ if (type === "step/start") open = stepKey2(data);
26201
+ else if (type === "step/end") open = null;
26202
+ else if (type === "user/message" && eventFactOf(event).marker === null && open !== null) owners.set(seq, open);
26203
+ else if (type === "assistant/message" || type === "tool/call" || type === "tool/result") {
26204
+ if (Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)) owners.set(seq, stepKey2(data));
26205
+ }
26206
+ if (isMainCall(event)) {
26207
+ const usage = callUsageOf(data?.usage);
26208
+ if (usage !== null) ctp ??= modelPolicyFor(data?.message?.source?.model).ctp;
26209
+ const resident = [...active.values()].reduce((sum, tokens) => sum + tokens, 0);
26210
+ const content = data?.message?.content;
26211
+ const tools = Array.isArray(content) ? content.filter((block) => block?.type === "tool-call") : [];
26212
+ const calls = new Map(tools.map((block) => [block.id, { target: targetOf2(block, seq), dispatched: false, skipped: false, resulted: false }]));
26213
+ sample = { event, counted: eventFactOf(event).step !== null, usage, resident, seal: seal?.attempt, tools, calls };
26214
+ if (!isNoise(event)) lastMeasured = usage === null ? void 0 : sample;
26215
+ samples.set(seq, sample);
26216
+ }
26217
+ if (seal === void 0 || sample === void 0) continue;
26218
+ if (type === "tool/call" && stepKey2(data) === stepKey2(sample.event.data)) {
26219
+ const call = sample.calls.get(data.callId);
26220
+ if (call !== void 0) call.dispatched = true;
26221
+ }
26222
+ if (type === "tool/result") {
26223
+ const op = event.surfaceOp;
26224
+ const call = stepKey2(data) === stepKey2(sample.event.data) ? sample.calls.get(data.message?.toolCallId) : void 0;
26225
+ if (call !== void 0) {
26226
+ call.resulted = true;
26227
+ if (data.error?.code === ABORTED_BEFORE_DISPATCH) call.skipped = true;
26228
+ }
26229
+ const replaced = op?.op === "replace" && op.startSeq === op.endSeq && active.delete(op.startSeq);
26230
+ const returned = op === "append" && data.message?.isError !== true && call !== void 0 && isInitiated(call);
26231
+ if (!replaced && !returned) continue;
26232
+ const content = data.message?.content;
26233
+ const text = Array.isArray(content) ? content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("") : "";
26234
+ const tokens = charsToTokens(text, ctp ?? modelPolicyFor().ctp);
26235
+ if (tokens > 0) active.set(seq, tokens);
26236
+ }
26237
+ }
26238
+ for (const sample2 of samples.values()) sample2.verdict = judgeOf(sample2);
26239
+ const cuts = attempts.flatMap(({ id }) => {
26240
+ const pre = before.get(id);
26241
+ const output = pre?.verdict === "pure" ? pre.usage.output : 0;
26242
+ const tokens = (pre?.resident ?? 0) + output - (samples.get(postByAttempt.get(id))?.resident ?? 0);
26243
+ return tokens === 0 ? [] : [{ id, tokens }];
26244
+ });
26245
+ const steps = [];
26246
+ let partial = false;
26247
+ const axis = reportPositions(seals, samples, tailCalls);
26248
+ const { positions } = axis;
26249
+ const reads = /* @__PURE__ */ new Map();
26250
+ let judged = 0;
26251
+ let pure = 0;
26252
+ for (const sample2 of samples.values()) {
26253
+ const { event, counted, usage, resident, seal: parent, verdict } = sample2;
26254
+ const { seq } = event;
26255
+ const at = positions.get(seq);
26256
+ if (counted && parent !== void 0) {
26257
+ if (verdict === "pure") {
26258
+ for (const { id } of sample2.tools) {
26259
+ const { target } = sample2.calls.get(id);
26260
+ const landings = reads.get(target) ?? /* @__PURE__ */ new Map();
26261
+ reads.set(target, landings);
26262
+ if (at !== void 0) landings.set(at, { at, seq });
26263
+ }
26264
+ }
26265
+ if (at !== void 0 && verdict !== "unknown") {
26266
+ judged += 1;
26267
+ if (verdict === "pure") pure += 1;
26268
+ }
26269
+ }
26270
+ if (!counted || verdict !== "pure" && resident === 0) continue;
26271
+ if (at === void 0) {
26272
+ partial = true;
26273
+ continue;
26274
+ }
26275
+ if (verdict === "pure") {
26276
+ const ratio = parent?.quote?.cRatio ?? null;
26277
+ const post = postByAttempt.get(parent?.id) === seq ? parent.id : void 0;
26278
+ steps.push({ at, seq, usage, ratio, ...post === void 0 ? {} : { post } });
26279
+ } else {
26280
+ steps.push({ at, seq, resident });
26281
+ }
26282
+ }
26283
+ const targets = [...reads].sort(([a], [b]) => a - b).map(([seq, landings]) => ({
26284
+ seq,
26285
+ type: log.get(seq).type,
26286
+ at: placeOf(seq, owners, axis),
26287
+ reads: [...landings.values()].sort((a, b) => a.at - b.at)
26288
+ }));
26289
+ const recall = steps.length === 0 && cuts.length === 0 && !partial ? void 0 : { steps, cuts, ...partial ? { partial } : {} };
26290
+ return { recall, activity: { covered: axis.covered, judged, pure, targets } };
26291
+ }
26292
+
26293
+ // dsh/src/inner-monitor-tools.js
26294
+ var STATE_WARNING = Object.freeze({ check: "state-check", mixed: "state-mixed", write: "state-write" });
26295
+ var OLD_ATTRIBUTION_WARNING = "old-attribution";
26296
+ var STEP_LEVEL = Object.values(STATE_WARNING);
26297
+ var THRESHOLD_PERCENT = Math.round(OLD_SHARE_ABOVE * 100);
26298
+ function groupBy(list, key) {
26299
+ const groups = /* @__PURE__ */ new Map();
26300
+ for (const item of list) groups.set(key(item), [...groups.get(key(item)) ?? [], item]);
26301
+ return groups;
26302
+ }
26303
+ var soleOf = (groups, id) => groups.get(id)?.length === 1 ? groups.get(id)[0] : null;
26304
+ function standsFor(event, seq, log) {
26305
+ try {
26306
+ return originalsOf(event, log).includes(seq);
26307
+ } catch {
26308
+ return false;
26309
+ }
26310
+ }
26311
+ function shareOf({ oldLines, newLines }) {
26312
+ const total = oldLines + newLines;
26313
+ if (total === 0) return { percent: null, over: false };
26314
+ const percent = Math.floor(oldLines * 100 / total);
26315
+ return { percent, over: oldLines / total > OLD_SHARE_ABOVE && percent <= THRESHOLD_PERCENT };
26316
+ }
26317
+ var warn = (card, warning) => {
26318
+ if (!card.warnings.some(({ kind }) => kind === warning.kind)) card.warnings.push(warning);
26319
+ };
26320
+ function slotToolsOf({ events, range, log, kinds, dispatches, oldReads }) {
26321
+ const calls = events.flatMap(toolCallsOf);
26322
+ const results = events.flatMap((event) => {
26323
+ const result = toolResultOf(event);
26324
+ return result === null ? [] : [{ ...result, seq: event.seq }];
26325
+ });
26326
+ const callsById = groupBy(calls, ({ id }) => id);
26327
+ const resultsById = groupBy(results, ({ id }) => id);
26328
+ const resultOf = (id) => {
26329
+ const result = soleOf(callsById, id) === null ? null : soleOf(resultsById, id);
26330
+ return result === null ? null : { seq: result.seq, error: result.error, empty: result.empty };
26331
+ };
26332
+ const replacements = events.filter((event) => isPrunedResult(event) && range.has(event.seq));
26333
+ const prunedOf = (result) => {
26334
+ const seen = result === null ? [] : replacements.filter((event) => standsFor(event, result.seq, log));
26335
+ return seen.length === 1 ? { seq: seen[0].seq } : null;
26336
+ };
26337
+ const cards = calls.map((call) => {
26338
+ const result = resultOf(call.id);
26339
+ return { id: call.id, name: call.name, input: call.arguments, result, pruned: prunedOf(result), warnings: [] };
26340
+ });
26341
+ const paired = new Set(cards.map((card) => card.result?.seq));
26342
+ const lone = results.filter(({ seq }) => !paired.has(seq)).map(({ id, seq, error, empty }) => ({ id, name: null, input: null, result: { seq, error, empty }, pruned: prunedOf({ seq }), warnings: [] }));
26343
+ const all = [...cards, ...lone];
26344
+ const unplaced = /* @__PURE__ */ new Set();
26345
+ const settle = (kind, card, warning) => {
26346
+ if (card === null) unplaced.add(kind);
26347
+ else warn(card, warning);
26348
+ };
26349
+ for (const { kind, seq } of dispatches) {
26350
+ const dispatched = log.get(seq);
26351
+ const id = dispatchedCallIdOf(dispatched);
26352
+ const holders = cards.filter((card) => card.id === id);
26353
+ const [holder] = holders;
26354
+ const exact = holders.length === 1 && holder.name === dispatched.data.name && holder.input === dispatched.data.arguments;
26355
+ settle(kind, exact ? holder : null, { kind });
26356
+ }
26357
+ for (const hit of oldReads) {
26358
+ settle(
26359
+ OLD_ATTRIBUTION_WARNING,
26360
+ all.find((card) => card.id === hit.toolUseId && card.result?.seq === hit.seq) ?? null,
26361
+ { kind: OLD_ATTRIBUTION_WARNING, oldLines: hit.oldLines, newLines: hit.newLines, ...shareOf(hit) }
26362
+ );
26363
+ }
26364
+ const warnings = kinds.filter((kind) => STEP_LEVEL.includes(kind) || unplaced.has(kind));
26365
+ return { warnings, calls: all };
26366
+ }
26367
+
25571
26368
  // dsh/src/inner-monitor-read.js
25572
26369
  var MONITOR_PROJECTION_KEY = "session-watcher/inner-monitor";
25573
26370
  var PREVIEW_SOURCE_CHARS = 500;
25574
26371
  var RECORD_TYPES = [INNER_ATTEMPT_RECORD_TYPE, INNER_CALL_RECORD_TYPE, INNER_END_RECORD_TYPE];
25575
26372
  var USAGE_FIELDS2 = ["input", "output", "cacheRead", "cacheWrite"];
25576
26373
  var isUserMessage = (event) => event.type === "user/message";
25577
- var isCarrier2 = (event) => isUserMessage(event) && event.data?.source?.kind === INNER_SEAL_KIND;
25578
- var isMainCall2 = (event) => event.type === "assistant/message";
26374
+ var isCarrier2 = (event) => eventFactOf(event).marker === "carrier";
25579
26375
  var firstTextOf = (message) => Array.isArray(message?.content) ? message.content.find((block) => block?.type === "text")?.text : void 0;
25580
26376
  var isHandoffPayload = (event) => isUserMessage(event) && isLoadPayload(event.data?.source);
25581
26377
  var isHandoffReads = (event) => isUserMessage(event) && event.data?.source?.kind === LOAD_MESSAGE_KIND && !isLoadPayload(event.data.source) && loadCallsOf(event.data) !== null;
25582
26378
  var isHandoffFollowUp = (event) => isUserMessage(event) && loadedTokenOf(firstTextOf(event.data)) !== null;
25583
- var isCheckpoint = (event) => isUserMessage(event) && event.data?.source?.kind === CHECKPOINT_KIND;
26379
+ var isCheckpoint = (event) => eventFactOf(event).marker === "checkpoint";
25584
26380
  var isMonitorInput = (event) => RECORD_TYPES.includes(event.type) || isCarrier2(event) || isHandoffPayload(event) || isHandoffReads(event) || isHandoffFollowUp(event);
25585
- var isObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25586
- var isSeq = (value) => Number.isSafeInteger(value) && value >= 0;
25587
- var isText2 = (value) => typeof value === "string";
25588
- var isMessage = (value) => isObject4(value) && Array.isArray(value.content);
25589
- var orNull = (holds) => (value) => value === null || holds(value);
25590
- var isStartData = (data) => isObject4(data) && data.v === 1 && isObject4(data.range) && isSeq(data.range.first) && isSeq(data.range.last) && isSeq(data.range.count) && isObject4(data.request) && isObject4(data.request.messages) && isMessage(data.request.messages.tail);
25591
- var isCallData = (data) => isObject4(data) && data.v === 1 && Array.isArray(data.range) && data.range.length > 0 && data.range.every(isSeq) && Array.isArray(data.stream) && isObject4(data.input) && isMessage(data.input.tail) && (data.thrown === void 0 || isObject4(data.thrown) && isText2(data.thrown.message));
25592
- var isEndData = (data) => isObject4(data) && data.v === 1 && isSeq(data.attempt) && (data.outcome === "failed" || data.outcome === "cancelled") && isText2(data.reason);
25593
- var QUOTE_QUANTITIES = ["lA", "bEst", "cEst", "sEst", "cRatio", "nRef", "N", "jRef", "q"];
25594
- var isQuote = (value) => isObject4(value) && isSeq(value.n) && QUOTE_QUANTITIES.every((key) => orNull(Number.isFinite)(value[key])) && Number.isFinite(value.fee) && Number.isFinite(value.kappa) && [null, "left", "right"].includes(value.arm) && (value.trigger === "quote" || value.trigger === "hard") && orNull(isText2)(value.missing);
25595
- var isCarrierShape = (event) => Array.isArray(event.sourceEventSeqs) && isSeq(event.sourceEventSeqs[0]) && Array.isArray(event.data.source.slots);
26381
+ var isObject8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
26382
+ var isSeq5 = (value) => Number.isSafeInteger(value) && value >= 0;
26383
+ var isText5 = (value) => typeof value === "string";
26384
+ var isMessage = (value) => isObject8(value) && Array.isArray(value.content);
26385
+ var orNull2 = (holds) => (value) => value === null || holds(value);
26386
+ var isOldRead = (value) => isObject8(value) && isText5(value.toolUseId) && isSeq5(value.seq) && isSeq5(value.oldLines) && isSeq5(value.newLines);
26387
+ var oldReadsOf = (slot) => Array.isArray(slot?.oldReads) ? slot.oldReads.filter(isOldRead) : [];
26388
+ var isCarrierShape = (event) => Array.isArray(event.sourceEventSeqs) && isSeq5(callSeqOf(event.sourceEventSeqs)) && Array.isArray(event.data.source.slots);
25596
26389
  var bounded = (text) => text.length > PREVIEW_SOURCE_CHARS ? text.slice(0, PREVIEW_SOURCE_CHARS) : text;
25597
26390
  var messageTextOf = (message) => bounded(message.content.filter((block) => block.type === "text").map((block) => block.text).join(""));
25598
26391
  function responseTextOf(stream, kit) {
@@ -25611,7 +26404,7 @@ function displayOf(text) {
25611
26404
  }
25612
26405
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return text;
25613
26406
  const values = Object.values(parsed);
25614
- return values.every(isText2) ? values.join("\n") : text;
26407
+ return values.every(isText5) ? values.join("\n") : text;
25615
26408
  }
25616
26409
  function streamSummaryOf(stream, kit) {
25617
26410
  const text = responseTextOf(stream, kit);
@@ -25623,78 +26416,129 @@ function streamSummaryOf(stream, kit) {
25623
26416
  };
25624
26417
  }
25625
26418
  var amended = (state, at, change) => at < 0 ? state : { ...state, attempts: state.attempts.map((each, index) => index === at ? { ...each, ...change } : each) };
25626
- var stockOf2 = ({ input, cacheRead, cacheWrite }) => input + cacheRead + cacheWrite;
25627
- var uncachedOf = ({ input, cacheWrite }) => input + cacheWrite;
25628
- var beforeOf = ({ lastMainUsage }) => lastMainUsage ? stockOf2(lastMainUsage) + lastMainUsage.output : null;
26419
+ var contextOfUsage = (usage) => usage === null ? null : stockOf(usage) + usage.output;
26420
+ var beforeOf = ({ lastMainUsage }) => contextOfUsage(lastMainUsage);
26421
+ var isSettlementNoise = ({ data }) => data?.interrupted === true && data.usage === void 0;
25629
26422
  var amendedLast = (state, change) => ({ ...state, handoffs: state.handoffs.map((each, index) => index === state.handoffs.length - 1 ? { ...each, ...change } : each) });
25630
- var stepsAfter = (steps, event) => sourceFactOf(event).step === null ? steps : steps + 1;
26423
+ var callsAfter = (calls, event) => eventFactOf(event).step === null ? calls : calls + 1;
25631
26424
  function foldMainCall(state, event) {
25632
26425
  const { seq, data } = event;
25633
26426
  const usage = callUsageOf(data?.usage);
25634
- const next = { ...state, lastMainUsage: usage, openSteps: stepsAfter(state.openSteps, event) };
26427
+ const next = {
26428
+ ...state,
26429
+ lastMainUsage: usage,
26430
+ openCalls: callsAfter(state.openCalls, event),
26431
+ settlementBefore: isSettlementNoise(event) ? state.settlementBefore : contextOfUsage(usage)
26432
+ };
25635
26433
  const last = state.handoffs.at(-1);
25636
26434
  if (last?.type !== "continue" || last.after !== null) return next;
25637
- return amendedLast(next, { after: { seq, stock: usage === null ? null : stockOf2(usage), miss: usage === null ? null : uncachedOf(usage) } });
26435
+ return amendedLast(next, { after: { seq, stock: usage === null ? null : stockOf(usage), miss: usage === null ? null : uncachedOf(usage) } });
25638
26436
  }
25639
26437
  function afterOf({ carriers }, attempt) {
25640
26438
  if (attempt.carrier === null) return null;
25641
26439
  const post = carriers.find((each) => each.seq === attempt.carrier.seq)?.post ?? null;
25642
- return post === null ? null : { seq: post.seq, stock: post.usage === null ? null : stockOf2(post.usage), miss: post.usage === null ? null : uncachedOf(post.usage) };
26440
+ return post === null ? null : { seq: post.seq, stock: post.usage === null ? null : stockOf(post.usage), miss: post.usage === null ? null : uncachedOf(post.usage) };
25643
26441
  }
25644
26442
  var withAfter = (state, attempt) => ({ ...attempt, after: afterOf(state.source, attempt) });
25645
26443
  function foldStart(state, { seq, time, data }) {
25646
- if (!isStartData(data)) return state;
26444
+ if (!isAttemptRecord(data)) return state;
26445
+ const { tail } = data.request.messages;
26446
+ if (!isMessage(tail)) return state;
25647
26447
  const { first, last, count } = data.range;
26448
+ const before = beforeOf(state);
25648
26449
  const attempt = {
25649
26450
  id: seq,
25650
26451
  startedAt: time,
25651
26452
  range: { first, last, count },
25652
- input: messageTextOf(data.request.messages.tail),
26453
+ input: messageTextOf(tail),
25653
26454
  call: null,
25654
26455
  end: null,
25655
26456
  carrier: null,
25656
- before: beforeOf(state),
25657
- quote: isQuote(data.quote) ? data.quote : null,
25658
- epoch: state.source.epoch
26457
+ before,
26458
+ quote: attemptQuoteOf(data),
26459
+ epoch: state.source.epoch,
26460
+ ...before === null && state.settlementBefore !== null ? { estimatedBefore: state.settlementBefore } : {}
25659
26461
  };
25660
26462
  return { ...state, attempts: [...state.attempts, attempt] };
25661
26463
  }
25662
26464
  function foldCall(state, { seq, data }, kit) {
25663
- if (!isCallData(data)) return state;
26465
+ if (!isCallRecord(data)) return state;
25664
26466
  const call = {
25665
26467
  seq,
25666
26468
  endedAt: Number.isFinite(data.endedAt) ? data.endedAt : null,
25667
26469
  thrown: data.thrown === void 0 ? null : bounded(data.thrown.message),
25668
26470
  ...streamSummaryOf(data.stream, kit),
25669
- // The field is the call's own only in the closed shape; a record that never held it, or holds anything else, reads as not observed.
25670
- ...isCarrierEvidence(data.carrierCache) ? { carrierCache: evidenceCopy(data.carrierCache) } : {}
26471
+ // The field is the call's own only in the structure the call record checks (`isCarrierCache`); a record that never held it, or holds anything else, reads as not observed.
26472
+ ...isCarrierCache(data.carrierCache) ? { carrierCache: evidenceCopy(data.carrierCache) } : {}
25671
26473
  };
25672
- const at = state.attempts.findIndex((each) => each.id === data.attempt);
25673
- if (at >= 0) return amended(state, at, { call });
25674
- const legacy = {
25675
- id: seq,
25676
- startedAt: null,
25677
- range: { first: data.range[0], last: data.range.at(-1), count: data.range.length },
25678
- input: messageTextOf(data.input.tail),
25679
- call,
25680
- end: null,
25681
- carrier: null,
25682
- before: beforeOf(state),
25683
- quote: null,
25684
- epoch: state.source.epoch
25685
- };
25686
- return { ...state, attempts: [...state.attempts, legacy] };
26474
+ return amended(state, state.attempts.findIndex((each) => each.id === data.attempt), { call });
25687
26475
  }
25688
26476
  function foldEnd(state, { seq, time, data }) {
25689
- if (!isEndData(data)) return state;
26477
+ if (!isEndRecord(data)) return state;
25690
26478
  const end = { seq, time, outcome: data.outcome, reason: bounded(data.reason) };
25691
26479
  return amended(state, state.attempts.findIndex((each) => each.id === data.attempt), { end });
25692
26480
  }
25693
26481
  function foldCarrier(state, event) {
25694
- const sealed = { ...state, openSteps: 0 };
26482
+ const sealed = { ...state, openCalls: 0, settlementBefore: null, postSeal: null };
25695
26483
  if (!isCarrierShape(event)) return sealed;
25696
- const carrier = { seq: event.seq, time: event.time, slots: event.data.source.slots.length };
25697
- return amended(sealed, sealed.attempts.findIndex((each) => each.call?.seq === event.sourceEventSeqs[0]), { carrier });
26484
+ const { slots, verbatimSeqs } = event.data.source;
26485
+ if (event.surfaceOp?.op === "replace" && Array.isArray(verbatimSeqs)) {
26486
+ sealed.verbatimSeqs = [...state.verbatimSeqs, ...verbatimSeqs.filter(isSeq5)];
26487
+ }
26488
+ const at = sealed.attempts.findIndex((each) => each.call?.seq === callSeqOf(event.sourceEventSeqs));
26489
+ if (at < 0) return sealed;
26490
+ const carrier = { seq: event.seq, time: event.time, slots: slots.length };
26491
+ const slotWarnings = {};
26492
+ const slotDispatches = {};
26493
+ const pending = state.postSeal?.pending ?? {};
26494
+ for (const slot of slots) {
26495
+ const seqs = slot?.seqs;
26496
+ if (!Array.isArray(seqs) || seqs.length === 0 || !seqs.every(isSeq5)) continue;
26497
+ const dispatches = seqs.flatMap((seq) => pending[seq] ?? []);
26498
+ const warnings = new Set(dispatches.map(({ kind }) => kind));
26499
+ if (oldReadsOf(slot).length > 0) warnings.add(OLD_ATTRIBUTION_WARNING);
26500
+ if (warnings.size > 0) slotWarnings[seqs[0]] = [...warnings];
26501
+ if (dispatches.length > 0) slotDispatches[seqs[0]] = dispatches;
26502
+ }
26503
+ return amended({ ...sealed, postSeal: { first: true, request: null, pending: {} } }, at, {
26504
+ carrier,
26505
+ ...Object.keys(slotWarnings).length > 0 && { slotWarnings },
26506
+ ...Object.keys(slotDispatches).length > 0 && { slotDispatches }
26507
+ });
26508
+ }
26509
+ function foldPostSealRequest(state, event) {
26510
+ const { postSeal } = state;
26511
+ if (postSeal === null) return state;
26512
+ const { turn, step, message } = event.data ?? {};
26513
+ const count = Array.isArray(message?.content) ? message.content.filter((block) => block?.type === "tool-call").length : 0;
26514
+ const request = isMainCall(event) && isSeq5(turn) && isSeq5(step) && count > 0 ? { seq: event.seq, turn, step, count, first: postSeal.first } : null;
26515
+ if (!postSeal.first && request === null && postSeal.request === null) return state;
26516
+ return { ...state, postSeal: { ...postSeal, first: false, request } };
26517
+ }
26518
+ function recallWarningOf(state, call) {
26519
+ const target = eventReadTargetOf(call.data);
26520
+ if (target === void 0 || target.sessionId !== void 0 && target.sessionId !== state.sessionId || target.seq >= call.seq) return;
26521
+ if (state.handoffs.some((handoff) => handoff.id === target.seq)) return "handoff-recall";
26522
+ if (state.source.carriers.some((carrier) => carrier.seq === target.seq)) return "carrier-recall";
26523
+ if (state.verbatimSeqs.includes(target.seq)) return "verbatim-recall";
26524
+ }
26525
+ function heldInContext(state, seq) {
26526
+ const { epoch } = state.source;
26527
+ return state.verbatimSeqs.includes(seq) || state.source.carriers.some((carrier) => carrier.seq === seq && carrier.epoch === epoch) || state.handoffs.some((handoff) => handoff.epoch === epoch && (handoff.id === seq || handoff.readSeq === seq || handoff.followSeq === seq));
26528
+ }
26529
+ function stateWarningOf(request, call) {
26530
+ if (!request.first) return;
26531
+ const operation = stateOperationOf(call);
26532
+ if (operation !== void 0) return operation === "write" ? STATE_WARNING.write : request.count === 1 ? STATE_WARNING.check : STATE_WARNING.mixed;
26533
+ }
26534
+ function foldToolCall(state, event) {
26535
+ const { postSeal } = state;
26536
+ const request = postSeal?.request;
26537
+ if (!request || request.turn !== event.data?.turn || request.step !== event.data?.step) return state;
26538
+ const warning = recallWarningOf(state, event) ?? stateWarningOf(request, event.data);
26539
+ if (warning === void 0) return state;
26540
+ const dispatches = postSeal.pending[request.seq] ?? [];
26541
+ return { ...state, postSeal: { ...postSeal, pending: { ...postSeal.pending, [request.seq]: [...dispatches, { kind: warning, seq: event.seq }] } } };
25698
26542
  }
25699
26543
  function payloadOf(message) {
25700
26544
  let payload;
@@ -25703,12 +26547,12 @@ function payloadOf(message) {
25703
26547
  } catch {
25704
26548
  return null;
25705
26549
  }
25706
- return isObject4(payload) && isText2(payload.load_token) ? payload : null;
26550
+ return isObject8(payload) && isText5(payload.load_token) ? payload : null;
25707
26551
  }
25708
26552
  var LABEL_POSITION = /^S(\d+)(?:-S(\d+))?$/;
25709
26553
  var positionOf2 = (entry) => {
25710
- const match = isText2(entry?.label) ? LABEL_POSITION.exec(entry.label) : null;
25711
- return match === null ? [] : [Number(match[2] ?? match[1])].filter(isSeq);
26554
+ const match = isText5(entry?.label) ? LABEL_POSITION.exec(entry.label) : null;
26555
+ return match === null ? [] : [Number(match[2] ?? match[1])].filter(isSeq5);
25712
26556
  };
25713
26557
  function lineageNumberOf(lineage) {
25714
26558
  const positions = Array.isArray(lineage) ? lineage.flatMap(positionOf2) : [];
@@ -25723,7 +26567,7 @@ function foldPayload(state, { seq, time, data }) {
25723
26567
  time,
25724
26568
  type,
25725
26569
  token: payload.load_token,
25726
- handoffId: isSeq(payload.handoff_id) ? payload.handoff_id : null,
26570
+ handoffId: isSeq5(payload.handoff_id) ? payload.handoff_id : null,
25727
26571
  createdAt: Number.isFinite(payload.created_at) ? payload.created_at : null,
25728
26572
  epoch: state.source.epoch,
25729
26573
  kept: Array.isArray(payload.paths_to_keep) ? payload.paths_to_keep.length : null,
@@ -25734,7 +26578,7 @@ function foldPayload(state, { seq, time, data }) {
25734
26578
  followSeq: null,
25735
26579
  before: type === "continue" ? beforeOf(state) : null,
25736
26580
  after: null,
25737
- tailSteps: type === "continue" ? state.lastCheckpointSteps : null
26581
+ tailCalls: type === "continue" ? state.lastCheckpointCalls : null
25738
26582
  };
25739
26583
  return { ...state, handoffs: [...state.handoffs, handoff] };
25740
26584
  }
@@ -25749,27 +26593,32 @@ function foldFollowUp(state, { seq, data }) {
25749
26593
  return amendedLast(state, { followSeq: seq });
25750
26594
  }
25751
26595
  function foldCheckpoint(state, { data }) {
25752
- return { ...state, lastCheckpointToken: checkpointTokenOf(firstTextOf(data)), lastCheckpointSteps: state.openSteps, openSteps: 0 };
25753
- }
25754
- var isRange = (value) => isObject4(value) && isSeq(value.first) && isSeq(value.last) && isSeq(value.count);
25755
- var isUsageState = (value) => isObject4(value) && USAGE_FIELDS2.every((field) => Number.isFinite(value[field]));
25756
- var isCallState = (value) => isObject4(value) && isSeq(value.seq) && orNull(Number.isFinite)(value.endedAt) && orNull(isText2)(value.thrown) && orNull(isText2)(value.output) && orNull(isText2)(value.outputDisplay) && orNull(isText2)(value.finish) && orNull(isUsageState)(value.usage) && (value.carrierCache === void 0 || isCarrierEvidence(value.carrierCache));
25757
- var isEndState = (value) => isObject4(value) && isSeq(value.seq) && Number.isFinite(value.time) && (value.outcome === "failed" || value.outcome === "cancelled") && isText2(value.reason);
25758
- var isCarrierState = (value) => isObject4(value) && isSeq(value.seq) && Number.isFinite(value.time) && isSeq(value.slots);
25759
- var isAfterState = (value) => isObject4(value) && isSeq(value.seq) && orNull(Number.isFinite)(value.stock) && orNull(Number.isFinite)(value.miss);
25760
- var isHandoffState = (value) => isObject4(value) && isSeq(value.id) && Number.isFinite(value.time) && (value.type === "load" || value.type === "continue") && isText2(value.token) && orNull(isSeq)(value.handoffId) && orNull(Number.isFinite)(value.createdAt) && isSeq(value.epoch) && orNull(isSeq)(value.kept) && isSeq(value.skills) && orNull(isSeq)(value.lineage) && orNull(isSeq)(value.read) && orNull(isSeq)(value.readSeq) && orNull(isSeq)(value.followSeq) && orNull(Number.isFinite)(value.before) && orNull(isAfterState)(value.after) && orNull(isSeq)(value.tailSteps);
25761
- var isAttemptState = (value) => isObject4(value) && isSeq(value.id) && orNull(Number.isFinite)(value.startedAt) && isRange(value.range) && isText2(value.input) && orNull(isCallState)(value.call) && orNull(isEndState)(value.end) && orNull(isCarrierState)(value.carrier) && orNull(Number.isFinite)(value.before) && orNull(isQuote)(value.quote) && isSeq(value.epoch);
26596
+ return { ...state, lastCheckpointToken: checkpointTokenOf(firstTextOf(data)), lastCheckpointCalls: state.openCalls, openCalls: 0 };
26597
+ }
26598
+ var isRange = (value) => isObject8(value) && isSeq5(value.first) && isSeq5(value.last) && isSeq5(value.count);
26599
+ var isUsageState = (value) => isObject8(value) && USAGE_FIELDS2.every((field) => Number.isFinite(value[field]));
26600
+ var isCallState = (value) => isObject8(value) && isSeq5(value.seq) && orNull2(Number.isFinite)(value.endedAt) && orNull2(isText5)(value.thrown) && orNull2(isText5)(value.output) && orNull2(isText5)(value.outputDisplay) && orNull2(isText5)(value.finish) && orNull2(isUsageState)(value.usage) && (value.carrierCache === void 0 || isCarrierCache(value.carrierCache));
26601
+ var isEndState = (value) => isObject8(value) && isSeq5(value.seq) && Number.isFinite(value.time) && (value.outcome === "failed" || value.outcome === "cancelled") && isText5(value.reason);
26602
+ var isCarrierState = (value) => isObject8(value) && isSeq5(value.seq) && Number.isFinite(value.time) && isSeq5(value.slots);
26603
+ var isAfterState = (value) => isObject8(value) && isSeq5(value.seq) && orNull2(Number.isFinite)(value.stock) && orNull2(Number.isFinite)(value.miss);
26604
+ var isHandoffState = (value) => isObject8(value) && isSeq5(value.id) && Number.isFinite(value.time) && (value.type === "load" || value.type === "continue") && isText5(value.token) && orNull2(isSeq5)(value.handoffId) && orNull2(Number.isFinite)(value.createdAt) && isSeq5(value.epoch) && orNull2(isSeq5)(value.kept) && isSeq5(value.skills) && orNull2(isSeq5)(value.lineage) && orNull2(isSeq5)(value.read) && orNull2(isSeq5)(value.readSeq) && orNull2(isSeq5)(value.followSeq) && orNull2(Number.isFinite)(value.before) && orNull2(isAfterState)(value.after) && orNull2(isSeq5)(value.tailCalls);
26605
+ var isWarningsBySeq = (value) => isObject8(value) && Object.entries(value).every(([seq, warnings]) => String(Number(seq)) === seq && isSeq5(Number(seq)) && Array.isArray(warnings) && warnings.length > 0 && warnings.every(isText5));
26606
+ var isDispatchesBySeq = (value) => isObject8(value) && Object.entries(value).every(([seq, dispatches]) => String(Number(seq)) === seq && isSeq5(Number(seq)) && Array.isArray(dispatches) && dispatches.length > 0 && dispatches.every((dispatch) => isObject8(dispatch) && isText5(dispatch.kind) && isSeq5(dispatch.seq)));
26607
+ var isAttemptState = (value) => isObject8(value) && isSeq5(value.id) && Number.isFinite(value.startedAt) && isRange(value.range) && isText5(value.input) && orNull2(isCallState)(value.call) && orNull2(isEndState)(value.end) && orNull2(isCarrierState)(value.carrier) && orNull2(Number.isFinite)(value.before) && (value.estimatedBefore === void 0 || Number.isFinite(value.estimatedBefore)) && orNull2(isQuote)(value.quote) && isSeq5(value.epoch) && (value.slotWarnings === void 0 || isWarningsBySeq(value.slotWarnings)) && (value.slotDispatches === void 0 || isDispatchesBySeq(value.slotDispatches));
26608
+ var isPostSealRequest = orNull2((value) => isObject8(value) && isSeq5(value.seq) && isSeq5(value.turn) && isSeq5(value.step) && isSeq5(value.count) && typeof value.first === "boolean");
26609
+ var isPostSeal = orNull2((value) => isObject8(value) && typeof value.first === "boolean" && isPostSealRequest(value.request) && isDispatchesBySeq(value.pending));
25762
26610
  var stateSchema2 = {
25763
26611
  parse(value) {
25764
- if (!isObject4(value) || !Array.isArray(value.attempts) || !value.attempts.every(isAttemptState) || !orNull(isUsageState)(value.lastMainUsage) || !isSourceFacts(value.source) || !Array.isArray(value.handoffs) || !value.handoffs.every(isHandoffState) || !orNull(isText2)(value.lastCheckpointToken) || !isSeq(value.lastCheckpointSteps) || !isSeq(value.openSteps)) {
25765
- throw new Error("the inner monitor state is not { attempts, lastMainUsage, source, handoffs, lastCheckpointToken, lastCheckpointSteps, openSteps } of attempt summaries, the usage of the last main call, the source facts, handoff summaries, the token of the last /sw-continue checkpoint, the steps it ended and the steps since the last carrier or checkpoint");
26612
+ if (!isObject8(value) || !Array.isArray(value.attempts) || !value.attempts.every(isAttemptState) || !orNull2(isUsageState)(value.lastMainUsage) || !isSourceFacts(value.source) || !Array.isArray(value.handoffs) || !value.handoffs.every(isHandoffState) || !orNull2(isText5)(value.lastCheckpointToken) || !isSeq5(value.lastCheckpointCalls) || !isSeq5(value.openCalls) || !orNull2(Number.isFinite)(value.settlementBefore) || !isPostSeal(value.postSeal) || !orNull2(isText5)(value.sessionId) || !Array.isArray(value.verbatimSeqs) || !value.verbatimSeqs.every(isSeq5)) {
26613
+ throw new Error("invalid inner monitor state");
25766
26614
  }
25767
26615
  return value;
25768
26616
  }
25769
26617
  };
25770
26618
  function innerMonitorProjection(kit) {
25771
26619
  const fold = (state, event) => {
25772
- if (isMainCall2(event)) return foldMainCall(state, event);
26620
+ if (isMainCall(event)) return foldMainCall(foldPostSealRequest(state, event), event);
26621
+ if (event.type === "assistant/attempt") return foldPostSealRequest(state, event);
25773
26622
  if (isCarrier2(event)) return foldCarrier(state, event);
25774
26623
  if (isHandoffPayload(event)) return foldPayload(state, event);
25775
26624
  if (isHandoffReads(event)) return foldReads(state, event);
@@ -25789,15 +26638,17 @@ function innerMonitorProjection(kit) {
25789
26638
  };
25790
26639
  return {
25791
26640
  key: MONITOR_PROJECTION_KEY,
25792
- stateVersion: 10,
26641
+ stateVersion: 18,
25793
26642
  stateSchema: stateSchema2,
25794
- init: () => ({ attempts: [], lastMainUsage: null, source: initialSourceFacts(), handoffs: [], lastCheckpointToken: null, lastCheckpointSteps: 0, openSteps: 0 }),
26643
+ init: (header) => ({ attempts: [], lastMainUsage: null, settlementBefore: null, source: initialSourceFacts(), handoffs: [], lastCheckpointToken: null, lastCheckpointCalls: 0, openCalls: 0, postSeal: null, verbatimSeqs: [], sessionId: header?.id ?? null }),
25795
26644
  apply(state, event) {
25796
- if (!isSeq(event.seq) || !Number.isFinite(event.time)) return state;
26645
+ if (!isSeq5(event.seq) || !Number.isFinite(event.time)) return state;
25797
26646
  try {
25798
- const source = foldSourceFacts(state.source, event);
25799
- const folded = isMonitorInput(event) || isMainCall2(event) || isCheckpoint(event) ? fold(state, event) : state;
25800
- return source === state.source ? folded : { ...folded, source };
26647
+ if (event.type === "tool/call") return foldToolCall(state, event);
26648
+ const source = foldSourceFacts(state.source, foldInputOf(event));
26649
+ const folded = isMonitorInput(event) || isMainCall(event) || event.type === "assistant/attempt" || isCheckpoint(event) ? fold(state, event) : state;
26650
+ if (source === state.source) return folded;
26651
+ return source.epoch === state.source.epoch ? { ...folded, source } : { ...folded, source, settlementBefore: null, postSeal: null, verbatimSeqs: [] };
25801
26652
  } catch {
25802
26653
  return state;
25803
26654
  }
@@ -25843,7 +26694,6 @@ function rowOf2(attempt, entry, kit) {
25843
26694
  id: attempt.id,
25844
26695
  revision: Math.max(attempt.id, attempt.call?.seq ?? 0, attempt.end?.seq ?? 0, attempt.carrier?.seq ?? 0, attempt.after?.seq ?? 0),
25845
26696
  status: attempt.carrier !== null ? "committed" : attempt.end?.outcome ?? entry?.phase ?? "unknown",
25846
- legacy: attempt.startedAt === null,
25847
26697
  startedAt: attempt.startedAt,
25848
26698
  endedAt: (attempt.carrier ?? attempt.end)?.time ?? null,
25849
26699
  range: { ...attempt.range },
@@ -25858,7 +26708,12 @@ function rowOf2(attempt, entry, kit) {
25858
26708
  };
25859
26709
  }
25860
26710
  function rowsOf2(state, live2, kit) {
25861
- return state.attempts.map((attempt) => rowOf2(withAfter(state, attempt), live2.find((entry) => entry.attempt === attempt.id), kit));
26711
+ return state.attempts.map((attempt) => {
26712
+ const row = rowOf2(withAfter(state, attempt), live2.find((entry) => entry.attempt === attempt.id), kit);
26713
+ if (row.status === "committed" && attempt.estimatedBefore !== void 0) row.estimatedBefore = attempt.estimatedBefore;
26714
+ if (attempt.slotWarnings !== void 0) row.slotWarnings = Object.fromEntries(Object.entries(attempt.slotWarnings).map(([key, warnings]) => [key, [...warnings]]));
26715
+ return row;
26716
+ });
25862
26717
  }
25863
26718
  function handoffRowOf(handoff, nextTaskOf) {
25864
26719
  const nextTask = handoff.handoffId === null ? null : nextTaskOf(handoff.handoffId);
@@ -25875,8 +26730,8 @@ function handoffRowOf(handoff, nextTaskOf) {
25875
26730
  skills: handoff.skills,
25876
26731
  lineage: handoff.lineage,
25877
26732
  contextChange: handoff.type === "continue" ? contextChangeOf(handoff) : null,
25878
- tailSteps: handoff.tailSteps,
25879
- nextTask: isText2(nextTask) ? bounded(nextTask) : null
26733
+ tailCalls: handoff.tailCalls,
26734
+ nextTask: isText5(nextTask) ? bounded(nextTask) : null
25880
26735
  };
25881
26736
  }
25882
26737
  function handoffRowsOf(state, nextTaskOf) {
@@ -25898,21 +26753,14 @@ function recordOf(log, seq, type, kit) {
25898
26753
  if (record?.type !== type) throw new Error(`the session log holds no ${type} record at seq ${seq}`);
25899
26754
  return record.data;
25900
26755
  }
25901
- function definitionsOf(log, headerSeq2) {
25902
- if (!isSeq(headerSeq2)) return { definitions: null, reason: "the request names no request header" };
25903
- const event = log.get(headerSeq2);
25904
- if (event?.type !== "request/header") return { definitions: null, reason: `the log holds no request header at seq ${headerSeq2}` };
26756
+ function definitionsOf(log, headerSeq) {
26757
+ if (!isSeq5(headerSeq)) return { definitions: null, reason: "the request names no request header" };
26758
+ const event = log.get(headerSeq);
26759
+ if (event?.type !== "request/header") return { definitions: null, reason: `the log holds no request header at seq ${headerSeq}` };
25905
26760
  const tools = event.data?.header?.tools;
25906
- return Array.isArray(tools) ? { definitions: tools } : { definitions: null, reason: `the request header at seq ${headerSeq2} defines no tools` };
26761
+ return Array.isArray(tools) ? { definitions: tools } : { definitions: null, reason: `the request header at seq ${headerSeq} defines no tools` };
25907
26762
  }
25908
26763
  var requestOf = (display, tools) => display.tools === void 0 ? display : { ...display, tools: { ...display.tools, ...tools() } };
25909
- var partialRequestOf = ({ selection, input }) => ({
25910
- recorded: "partial",
25911
- selection,
25912
- tail: input.tail,
25913
- throughSeq: input.throughSeq,
25914
- headerSeq: input.headerSeq
25915
- });
25916
26764
  var detailRowOf = ({ call: { outputDisplay, ...call }, ...row }) => ({ ...row, call });
25917
26765
  var wholeRow = (row, end, call) => detailRowOf({
25918
26766
  ...row,
@@ -25935,8 +26783,8 @@ function usageOfStream(stream, kit) {
25935
26783
  const chunk = kit.lastAssistantStreamChunk(stream, "usage") ?? null;
25936
26784
  return { folded: callUsageOf(chunk?.usage), raw: chunk };
25937
26785
  }
25938
- var idsOf = (attempt, row) => ({
25939
- start: row.legacy ? null : attempt.id,
26786
+ var idsOf = (attempt) => ({
26787
+ start: attempt.id,
25940
26788
  call: attempt.call?.seq ?? null,
25941
26789
  end: attempt.end?.seq ?? null,
25942
26790
  carrier: attempt.carrier?.seq ?? null
@@ -25948,7 +26796,7 @@ function liveCall(attempt, entry, kit) {
25948
26796
  const row = rowOf2(attempt, { ...entry, stream: () => stream }, kit);
25949
26797
  return {
25950
26798
  row: detailRowOf(row),
25951
- ids: idsOf(attempt, row),
26799
+ ids: idsOf(attempt),
25952
26800
  request: requestOf(entry.request, () => ({ definitions: entry.tools })),
25953
26801
  response: responseOf(stream, kit, true),
25954
26802
  usage: usageOfStream(stream, kit),
@@ -25959,14 +26807,14 @@ function liveCall(attempt, entry, kit) {
25959
26807
  }
25960
26808
  function recordedCall(attempt, log, kit) {
25961
26809
  const row = rowOf2(attempt, void 0, kit);
25962
- const start2 = row.legacy ? null : recordOf(log, attempt.id, INNER_ATTEMPT_RECORD_TYPE, kit);
26810
+ const start2 = recordOf(log, attempt.id, INNER_ATTEMPT_RECORD_TYPE, kit);
25963
26811
  const call = attempt.call === null ? null : recordOf(log, attempt.call.seq, INNER_CALL_RECORD_TYPE, kit);
25964
26812
  const end = row.reason === null ? null : recordOf(log, attempt.end.seq, INNER_END_RECORD_TYPE, kit);
25965
- const ids = idsOf(attempt, row);
26813
+ const ids = idsOf(attempt);
25966
26814
  return {
25967
26815
  row: wholeRow(row, end, call),
25968
26816
  ids,
25969
- request: start2 === null ? partialRequestOf(call) : requestOf(start2.request, () => definitionsOf(log, start2.request.headerSeq)),
26817
+ request: requestOf(start2.request, () => definitionsOf(log, start2.request.headerSeq)),
25970
26818
  response: call === null ? null : responseOf(call.stream, kit, false),
25971
26819
  usage: call === null ? null : usageOfStream(call.stream, kit),
25972
26820
  timing: timingOf(row),
@@ -25976,7 +26824,7 @@ function recordedCall(attempt, log, kit) {
25976
26824
  }
25977
26825
  function carriedDetailOf(source) {
25978
26826
  const evidence = carriedEvidence(source);
25979
- return evidence === null ? null : { text: renderCarried(source), note: CARRIER_WORDING.carried, ...evidence };
26827
+ return evidence === null ? null : { text: renderCarried(source, CARRIER_TABLE), note: carriedNote(CARRIER_TABLE), ...evidence };
25980
26828
  }
25981
26829
  function carrierAt(log, seq) {
25982
26830
  const carrier = log.get(seq);
@@ -25987,29 +26835,94 @@ function committedOf(attempt, log, kit) {
25987
26835
  const { slots } = carrierAt(log, attempt.carrier.seq).data.source;
25988
26836
  return { slots, range: new Set(recordOf(log, attempt.call.seq, INNER_CALL_RECORD_TYPE, kit).range) };
25989
26837
  }
25990
- function placeOf(slot, log) {
26838
+ function placeOf2(slot, log) {
25991
26839
  const events = slot.seqs.map((seq) => loggedEvent(log, seq));
25992
- const step = events.map((event) => sourceFactOf(event).step).find((counted) => counted !== null) ?? null;
25993
- const { type, kind } = sourceFactOf(events[0]);
25994
- return { key: slot.seqs[0], seqs: slot.seqs, turn: step?.turn ?? null, step: step?.step ?? null, source: { type, kind }, events };
26840
+ const step = events.map((event) => eventFactOf(event).step).find((counted) => counted !== null) ?? null;
26841
+ return { key: slot.seqs[0], seqs: slot.seqs, turn: step?.turn ?? null, step: step?.step ?? null, source: slotSourceOf(events[0]), events };
25995
26842
  }
25996
26843
  var NOT_COMMITTED = Object.freeze({ kind: "not_committed" });
26844
+ var NOT_TARGET = Object.freeze({ kind: "not_target" });
25997
26845
  function handoffOf(state, id) {
25998
26846
  const handoff = state.handoffs.find((each) => each.id === id);
25999
26847
  if (handoff === void 0) throw new Error(`the inner monitor holds no handoff ${id}`);
26000
26848
  return handoff;
26001
26849
  }
26850
+ function clearingOf(state, id) {
26851
+ const handoff = handoffOf(state, id);
26852
+ if (handoff.type !== "continue") throw new Error(`the handoff ${id} is no /sw-continue clear`);
26853
+ return handoff;
26854
+ }
26855
+ var atCut = (attempt, cut) => ({
26856
+ ...attempt,
26857
+ call: attempt.call !== null && attempt.call.seq <= cut ? attempt.call : null,
26858
+ end: attempt.end !== null && attempt.end.seq <= cut ? attempt.end : null,
26859
+ carrier: attempt.carrier !== null && attempt.carrier.seq <= cut ? attempt.carrier : null
26860
+ });
26861
+ var pricingOf = (state, segment, kit, cut) => rowsOf2({
26862
+ ...state,
26863
+ attempts: state.attempts.filter((attempt) => attempt.epoch === segment && attempt.id <= cut).map((attempt) => atCut(attempt, cut))
26864
+ }, [], kit).map(({ id, status, epoch, contextChange, estimatedBefore, call, stepN, cRatio }) => ({ id, status, epoch, contextChange, estimatedBefore, call: { usage: call.usage }, stepN, cRatio }));
26865
+ function segmentEventsOf(log, segment, through) {
26866
+ const events = [];
26867
+ let epoch = 0;
26868
+ for (const event of log.values()) {
26869
+ if (startsEpoch(foldInputOf(event))) epoch += 1;
26870
+ if (epoch > segment || event.seq > through) break;
26871
+ if (epoch === segment) events.push(event);
26872
+ }
26873
+ return events;
26874
+ }
26875
+ function settlementEvidenceOf(state, log, sessionId, segment, kit, { tailCalls, through = Number.POSITIVE_INFINITY } = {}) {
26876
+ const events = segmentEventsOf(log, segment, through);
26877
+ const cut = events.at(-1)?.seq ?? -1;
26878
+ const attempts = state.attempts.filter((attempt) => attempt.epoch === segment && attempt.carrier !== null && attempt.carrier.seq <= cut);
26879
+ const postByAttempt = new Map(attempts.map((attempt) => {
26880
+ const seq = afterOf(state.source, attempt)?.seq;
26881
+ return [attempt.id, seq <= cut ? seq : void 0];
26882
+ }));
26883
+ const posts = new Set(postByAttempt.values());
26884
+ const calls = [];
26885
+ let pendingPost = false;
26886
+ let countedTail = 0;
26887
+ const lastCarrier = attempts.at(-1)?.carrier.seq ?? -1;
26888
+ for (const event of events) {
26889
+ if (isCarrier2(event)) pendingPost = false;
26890
+ if (!isMainCall(event)) continue;
26891
+ if (event.seq > lastCarrier) countedTail = callsAfter(countedTail, event);
26892
+ pendingPost ||= posts.has(event.seq);
26893
+ if (isSettlementNoise(event)) continue;
26894
+ const usage = callUsageOf(event.data?.usage);
26895
+ calls.push({ seq: event.seq, stock: usage === null ? null : stockOf(usage), post: pendingPost });
26896
+ pendingPost = false;
26897
+ }
26898
+ const tail = tailCalls ?? countedTail;
26899
+ const { recall, activity } = settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls: tail, sessionId, isNoise: isSettlementNoise });
26900
+ return {
26901
+ epoch: segment + 1,
26902
+ attempts: pricingOf(state, segment, kit, cut),
26903
+ tailCalls: tail,
26904
+ calls,
26905
+ cut: { segment, through: cut },
26906
+ ...recall === void 0 ? {} : { recall },
26907
+ ...activity === void 0 ? {} : { activity }
26908
+ };
26909
+ }
26910
+ function plainTextOf(event) {
26911
+ const content = (event.data?.message ?? event.data)?.content;
26912
+ const text = Array.isArray(content) ? content.filter((block) => block?.type === "text" && isText5(block.text)).map((block) => block.text).join("") : "";
26913
+ return text === "" ? null : text;
26914
+ }
26002
26915
  function filesOf(message) {
26916
+ if (carriesEvidence(message.source)) return (carriedEvidence(message.source)?.files ?? []).map(({ path: path3, total, state, runs }) => ({ path: path3, total: state === "empty" ? 0 : total, runs }));
26003
26917
  return loadCallsOf(message).filter((call) => call.name === "read").map((call) => {
26004
26918
  const { file_path: path3 } = JSON.parse(call.arguments);
26005
26919
  if (typeof path3 !== "string") throw new Error(`the read call ${call.id} of the load read message names no file`);
26006
- const rendering = parseFileEvidence(call.text);
26007
- return { path: path3, total: rendering?.totalLines ?? null, runs: rendering?.runs ?? [] };
26920
+ return { path: path3, total: null, runs: [] };
26008
26921
  });
26009
26922
  }
26010
26923
  function followUpAt(log, seq) {
26011
26924
  const text = firstTextOf(loggedEvent(log, seq).data);
26012
- if (!isText2(text)) throw new Error(`the session log holds no follow-up text at seq ${seq}`);
26925
+ if (!isText5(text)) throw new Error(`the session log holds no follow-up text at seq ${seq}`);
26013
26926
  return text;
26014
26927
  }
26015
26928
  function handoffDetailOf(handoff, row, log) {
@@ -26021,7 +26934,7 @@ function handoffDetailOf(handoff, row, log) {
26021
26934
  if (loadCallsOf(reads) === null) throw new Error(`the session log holds no load read message at seq ${handoff.readSeq}`);
26022
26935
  files = filesOf(reads);
26023
26936
  }
26024
- const turnPage = isText2(payload.turn_page) ? payload.turn_page : null;
26937
+ const turnPage = isText5(payload.turn_page) ? payload.turn_page : null;
26025
26938
  return {
26026
26939
  row,
26027
26940
  summary: payload.summary,
@@ -26052,6 +26965,24 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26052
26965
  const handoff = handoffOf(facts.state, id);
26053
26966
  return handoffDetailOf(handoff, handoffRowOf(handoff, nextTaskOf), await facts.log());
26054
26967
  },
26968
+ async settlement(sessionId, id) {
26969
+ const facts = await factsOf(sessionId);
26970
+ if (facts === void 0) return void 0;
26971
+ const handoff = clearingOf(facts.state, id);
26972
+ return settlementEvidenceOf(facts.state, await facts.log(), sessionId, handoff.epoch - 1, kit, { tailCalls: handoff.tailCalls });
26973
+ },
26974
+ async currentSettlement(sessionId) {
26975
+ const snapshot = await readStored(sessionId);
26976
+ if (snapshot === void 0) return void 0;
26977
+ return settlementEvidenceOf(snapshot.state, logOf(snapshot), sessionId, snapshot.state.source.epoch, kit);
26978
+ },
26979
+ async settlementTarget(sessionId, { segment, through, seq }) {
26980
+ const snapshot = await readStored(sessionId);
26981
+ if (snapshot === void 0) return void 0;
26982
+ const log = logOf(snapshot);
26983
+ const target = settlementEvidenceOf(snapshot.state, log, sessionId, segment, kit, { through }).activity?.targets.find((each) => each.seq === seq);
26984
+ return target === void 0 ? NOT_TARGET : { seq, type: target.type, text: plainTextOf(log.get(seq)) };
26985
+ },
26055
26986
  async call(sessionId, id) {
26056
26987
  const facts = await factsOf(sessionId);
26057
26988
  if (facts === void 0) return void 0;
@@ -26068,7 +26999,7 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26068
26999
  const { slots, range } = committedOf(attempt, log, kit);
26069
27000
  return {
26070
27001
  slots: slots.map((slot) => {
26071
- const { events, seqs, ...place } = placeOf(slot, log);
27002
+ const { events, seqs, ...place } = placeOf2(slot, log);
26072
27003
  const seen = events.filter((event) => range.has(event.seq));
26073
27004
  const joined = (texts) => texts.filter((text) => text !== "").join("\n");
26074
27005
  return { ...place, input: bounded(joined(seen.map(eventPreviewText))), inputDisplay: bounded(joined(seen.map(eventDisplayText))), output: slot.text };
@@ -26085,8 +27016,16 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26085
27016
  const at = slots.findIndex((each) => each.seqs[0] === key);
26086
27017
  if (at < 0) throw new Error(`the carrier of attempt ${id} holds no slot ${key}`);
26087
27018
  const slot = slots[at];
26088
- const { events, ...place } = placeOf(slot, log);
26089
- return { ...place, number: at + 1, c: slot.text, events: events.map((event) => sourceEventView(event, { visible: range.has(event.seq) })) };
27019
+ const { events, ...place } = placeOf2(slot, log);
27020
+ const tools = slotToolsOf({
27021
+ events,
27022
+ range,
27023
+ log,
27024
+ kinds: attempt.slotWarnings?.[key] ?? [],
27025
+ dispatches: attempt.slotDispatches?.[key] ?? [],
27026
+ oldReads: oldReadsOf(slot)
27027
+ });
27028
+ return { ...place, number: at + 1, c: slot.text, events: events.map((event) => sourceEventView(event, { visible: range.has(event.seq) })), tools };
26090
27029
  }
26091
27030
  };
26092
27031
  }
@@ -26095,7 +27034,7 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26095
27034
  var HOST_INJECT = ["sessions", "sessionQuery", "tools", "skills", "llm"];
26096
27035
  var INNER_INJECT = ["sessionProjections", "agents", "fs", "attachments", "tokenMeter"];
26097
27036
  var SESSION_NOT_FOUND = "SESSION_QUERY_SESSION_NOT_FOUND";
26098
- function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, commandKit, innerKit, readSettings, carrierInstallTarget }) {
27037
+ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, commandKit, queryKit, innerKit, readSettings, carrierInstallTarget }) {
26099
27038
  initStore(storePath);
26100
27039
  ctx.effect(() => () => {
26101
27040
  try {
@@ -26151,8 +27090,9 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26151
27090
  if (record !== null) table.ensure({ id: record.header.id, header: record.header });
26152
27091
  return record;
26153
27092
  };
26154
- const carrierEvidence = createCarrierEvidence({ responsesBreakpoint: () => readSettings?.().carrierResponsesBreakpoint === true });
27093
+ const carrierEvidence = createCarrierEvidence();
26155
27094
  ctx.provide(CARRIER_EVIDENCE_SERVICE, carrierEvidence.service);
27095
+ ctx.provide(CARRIER_SETTINGS_SERVICE, { responsesBreakpoint: () => readSettings?.().carrierResponsesBreakpoint === true });
26156
27096
  const hub = createSignalHub();
26157
27097
  table.onChange((sessionId) => hub.publish(sessionId));
26158
27098
  ctx.on("agent/pre-step", createEpochModelName({
@@ -26181,6 +27121,17 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26181
27121
  ctx.on("session/disposed", (session) => guarded(session.id, () => table.dispose(session.id)));
26182
27122
  const sessionTitle = () => ctx.get("sessionTitle");
26183
27123
  for (const definition of createTools({ defineTool: defineTool2, table, store: getStore(), resolvePersisted })) ctx.tools.register(definition);
27124
+ let heldOf = null;
27125
+ if (queryKit !== void 0) {
27126
+ ctx.tools.register(createEventReadTool({ defineTool: defineTool2, ctx, ...queryKit, heldInContext: (sessionId, seq) => heldOf?.(sessionId, seq) === true }));
27127
+ ctx.inject(["systemPrompt"], (child) => {
27128
+ child.systemPrompt.section({
27129
+ name: `tool:${EVENT_READ_TOOL}`,
27130
+ order: child.systemPrompt.getSectionOrder("TOOL_SESSION_QUERY"),
27131
+ text: ({ scope, toolSet }) => ctx.tools.get(EVENT_READ_TOOL, scope, toolSet) === void 0 ? "" : EVENT_READ_GUIDANCE
27132
+ });
27133
+ });
27134
+ }
26184
27135
  const deliver = createHandoffDelivery({ table, store: getStore(), sessionTitle });
26185
27136
  registerSkills(ctx, { skillsDir });
26186
27137
  const readFileThrough = (fs3) => (agent, key, ranges, signal) => readObserved({
@@ -26217,6 +27168,10 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26217
27168
  }
26218
27169
  };
26219
27170
  };
27171
+ const gitStateOf = async (session, signal) => {
27172
+ const workingDirectory = ctx.get("workingDirectory");
27173
+ return workingDirectory === void 0 ? null : readGitState({ cwd: workingDirectory.get(session), signal });
27174
+ };
26220
27175
  const ratioOf = (sessionId) => {
26221
27176
  const entry = table.get(sessionId);
26222
27177
  return entry.state === "live" ? entry.watcher.getStatus().cRatio : null;
@@ -26274,12 +27229,13 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26274
27229
  const monitor = createInnerMonitor({ appendPluginRecord: innerKit.appendPluginRecord, publish: hub.publish });
26275
27230
  child.on("agent/pre-step", createInnerSeal({
26276
27231
  readMode: (session) => handle2.stateOf(session),
26277
- sourceFacts: (sessionId) => table.sourceFacts(sessionId),
27232
+ eventFacts: (sessionId) => table.eventFacts(sessionId),
26278
27233
  readSession,
26279
- heldView: (sessionId, events, range) => table.heldView(sessionId, events, range),
27234
+ heldView: (sessionId, events) => table.heldView(sessionId, events),
26280
27235
  readFile: readFileThrough(child.fs),
26281
27236
  readUnobserved: readUnobservedThrough(child.fs),
26282
27237
  readState: stateOf2(child),
27238
+ readGit: gitStateOf,
26283
27239
  cRatio: ratioOf,
26284
27240
  ctpOf,
26285
27241
  readSettings,
@@ -26309,6 +27265,10 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26309
27265
  // The store answers null for an id it holds no row of, so an absent handoff reads as no next task.
26310
27266
  nextTaskOf: (handoffId) => getStore().getHandoff(handoffId)?.nextTask ?? null
26311
27267
  });
27268
+ heldOf = (sessionId, seq) => {
27269
+ const session = sessionOf(sessionId);
27270
+ return session !== void 0 && heldInContext(monitorHandle.stateOf(session), seq);
27271
+ };
26312
27272
  } catch (error) {
26313
27273
  writeDiagnostic(null, hostDiagnostic("inner_monitor_register", error));
26314
27274
  }
@@ -26316,6 +27276,7 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26316
27276
  return () => {
26317
27277
  modeAccess = null;
26318
27278
  monitorAccess = null;
27279
+ heldOf = null;
26319
27280
  publishListed();
26320
27281
  };
26321
27282
  });
@@ -26329,6 +27290,7 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26329
27290
  child.extend({ webServer: child.webServer }).connection.rpc.handle("/session-watcher", createRpcHandler({
26330
27291
  table,
26331
27292
  store: getStore(),
27293
+ workingTree,
26332
27294
  publish: hub.publish,
26333
27295
  resolvePersisted,
26334
27296
  innerMode: () => modeAccess,
@@ -26371,6 +27333,7 @@ function apply(ctx, config) {
26371
27333
  applyHost(ctx, {
26372
27334
  defineTool,
26373
27335
  commandKit: { CompactionId, compactCheckpointSource, createUserMessage },
27336
+ queryKit: { extractSessionEventText, HarnessError },
26374
27337
  innerKit: {
26375
27338
  appendPluginRecord,
26376
27339
  pluginRecordOf,