@nomadop/session-watcher-dsh 0.11.0 → 0.11.1

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
 
@@ -13519,10 +13520,11 @@ var SessionWatcher = class {
13519
13520
  cacheRead: point.cacheRead,
13520
13521
  cacheCreation: point.cacheWrite,
13521
13522
  turnSeq: point.turnSeq,
13522
- foldedSeq: point.foldedSeq
13523
+ foldedSeq: point.foldedSeq,
13524
+ ...point.amberStockL === void 0 ? {} : { amberStockL: point.amberStockL }
13523
13525
  }));
13524
13526
  }
13525
- // The only bucket/resource query. It reads the Engine first, then passes only default-selected file rows
13527
+ // Reads the Engine first, then passes only default-selected file rows
13526
13528
  // to Resource Enrichment — a row the position basis excludes buys no symbols, and a Skill has no file.
13527
13529
  getBucketData({ includeSymbols = false } = {}) {
13528
13530
  const bucket = this._engine.getBucketData();
@@ -13566,6 +13568,12 @@ var SessionWatcher = class {
13566
13568
  segment: bucket.segment
13567
13569
  };
13568
13570
  }
13571
+ // The Engine's held line numbers of one file, ascending; null when it has no resource at that path, and for a Skill
13572
+ // key, whose number key 1 is no line of any file.
13573
+ getHeldLines(path3) {
13574
+ if (path3.startsWith(SKILL_RESOURCE_PREFIX)) return null;
13575
+ return this._engine.heldLines().get(path3) ?? null;
13576
+ }
13569
13577
  // The value host wiring persists unchanged as `profile_snapshot`. `b_total` is the UNCAPPED resident total:
13570
13578
  // the read-time cap belongs to the live dashboard, while persistence needs the belief its own path rows sum
13571
13579
  // into, or `dead + Σ paths` would exceed the total it is stored beside.
@@ -18529,11 +18537,12 @@ function fitAffine(points) {
18529
18537
  if (!(Number.isFinite(d) && d > 0)) return null;
18530
18538
  return { a: sx / n - d * uMean, d };
18531
18539
  }
18540
+ var xOn = (reference, u) => reference.a + reference.d * u;
18532
18541
  function landmarksOf(reference, mf) {
18533
18542
  if (!reference || !(Number.isFinite(mf) && mf > 0)) {
18534
18543
  return { xSweet: null, xBrAmberL: null, xBrAmberR: null, xBrRedR: null };
18535
18544
  }
18536
- const xAt = (u) => reference.a + reference.d * u;
18545
+ const xAt = (u) => xOn(reference, u);
18537
18546
  return {
18538
18547
  xSweet: xAt(1),
18539
18548
  xBrAmberL: xAt(uLeftAtBr(mf, BR_AMBER)),
@@ -18541,6 +18550,10 @@ function landmarksOf(reference, mf) {
18541
18550
  xBrRedR: xAt(uAtBr(mf, BR_RED))
18542
18551
  };
18543
18552
  }
18553
+ function amberStockOf({ reference, u, xBrAmberR, bDefault }, anchorL) {
18554
+ if (!reference || !Number.isFinite(u) || !Number.isFinite(xBrAmberR) || !(Number.isFinite(bDefault) && bDefault > 0)) return null;
18555
+ return anchorL + bDefault * (xBrAmberR - xOn(reference, u));
18556
+ }
18544
18557
 
18545
18558
  // lib/measurement/resident-ledger.js
18546
18559
  var TOUCH_HISTORY_MAX = 128;
@@ -18739,6 +18752,10 @@ function createResidentLedger() {
18739
18752
  return { applyEffect, applyResidualAllocation, residentTotals, snapshot };
18740
18753
  }
18741
18754
 
18755
+ // lib/measurement/usage.js
18756
+ var stockOf = ({ input, cacheRead, cacheWrite }) => input + cacheRead + cacheWrite;
18757
+ var uncachedOf = ({ input, cacheWrite }) => input + cacheWrite;
18758
+
18742
18759
  // lib/measurement/engine.js
18743
18760
  var USAGE_KEYS = ["input", "output", "cacheRead", "cacheWrite"];
18744
18761
  var SETTLEMENT_EPSILON = 1e-6;
@@ -19094,7 +19111,7 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19094
19111
  segmentGMin = Math.min(segmentGMin, effectiveG(gEma));
19095
19112
  }
19096
19113
  function acceptNewStep(record, usage, usageTotal, timestamp, result) {
19097
- const totalStock = usage.input + usage.cacheRead + usage.cacheWrite;
19114
+ const totalStock = stockOf(usage);
19098
19115
  const model = record.model ?? null;
19099
19116
  const firstOfEpoch = segmentSteps.length === 0;
19100
19117
  if (totalStock > 0 && frames.length > 0) {
@@ -19193,8 +19210,8 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19193
19210
  pendingTurn = true;
19194
19211
  break;
19195
19212
  case "epoch": {
19196
- const closed2 = finalizeSegment();
19197
- if (closed2) result.closedSegments.push(closed2);
19213
+ const closed = finalizeSegment();
19214
+ if (closed) result.closedSegments.push(closed);
19198
19215
  break;
19199
19216
  }
19200
19217
  case "residual":
@@ -19249,7 +19266,7 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19249
19266
  }
19250
19267
  const oAvg = segmentUsageCount > 0 ? segmentOutputSum / segmentUsageCount : null;
19251
19268
  const durationMs = Number.isFinite(segmentFirstTs) && Number.isFinite(segmentLastTs) ? segmentLastTs - segmentFirstTs : null;
19252
- const closed2 = {
19269
+ const closed = {
19253
19270
  segment: segmentSeq,
19254
19271
  epochModel,
19255
19272
  steps,
@@ -19276,12 +19293,15 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19276
19293
  },
19277
19294
  paths
19278
19295
  };
19296
+ const { rateLamp } = readView();
19297
+ const lastStep = segmentSteps.at(-1);
19298
+ lastStep.amberStockL = rateLamp.reference?.provisional ? null : amberStockOf(rateLamp, stockOf(lastStep.usage));
19279
19299
  openFreshSegment();
19280
- return closed2;
19300
+ return closed;
19281
19301
  }
19282
19302
  function closeCurrentSegment() {
19283
- const closed2 = finalizeSegment();
19284
- return { closedSegments: closed2 ? [closed2] : [], diagnostics: [] };
19303
+ const closed = finalizeSegment();
19304
+ return { closedSegments: closed ? [closed] : [], diagnostics: [] };
19285
19305
  }
19286
19306
  function readView() {
19287
19307
  const lastStep = segmentSteps.length ? segmentSteps[segmentSteps.length - 1] : null;
@@ -19354,7 +19374,7 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19354
19374
  function getHistory() {
19355
19375
  return calls.map((step) => {
19356
19376
  const B = step.bAtCall;
19357
- const L = step.usage.input + step.usage.cacheRead + step.usage.cacheWrite;
19377
+ const L = stockOf(step.usage);
19358
19378
  return {
19359
19379
  ts: step.timestamp,
19360
19380
  segment: step.segment,
@@ -19369,7 +19389,8 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19369
19389
  cacheRead: step.usage.cacheRead,
19370
19390
  cacheWrite: step.usage.cacheWrite,
19371
19391
  turnSeq: step.turn,
19372
- foldedSeq: step.foldedSeq
19392
+ foldedSeq: step.foldedSeq,
19393
+ ...step.amberStockL === void 0 ? {} : { amberStockL: step.amberStockL }
19373
19394
  };
19374
19395
  });
19375
19396
  }
@@ -19581,6 +19602,40 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19581
19602
  };
19582
19603
  }
19583
19604
 
19605
+ // lib/held-view.js
19606
+ var SELECTED = () => ({ selectedByDefault: true, defaultDiscardReason: null });
19607
+ function createHeldView({ createProjection, completeToolResult, resolveModelPolicy, frameCtx }) {
19608
+ return (observations) => {
19609
+ let completed = [];
19610
+ const projection = createProjection({
19611
+ completeToolResult: (pending, observation, context, options) => {
19612
+ const answer = completeToolResult(pending, observation, context, options);
19613
+ completed.push({ effects: answer.effects, text: observation.content, seq: observation.sourceOrdinal });
19614
+ return answer;
19615
+ }
19616
+ });
19617
+ const engine = createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy: SELECTED });
19618
+ let skills = /* @__PURE__ */ new Map();
19619
+ const effects = [];
19620
+ for (const observation of observations) {
19621
+ completed = [];
19622
+ const { records } = projection.project(observation, frameCtx);
19623
+ engine.ingest(records.filter((record) => record.type === "effect" || record.type === "epoch"));
19624
+ if (records.some((record) => record.type === "epoch")) skills = /* @__PURE__ */ new Map();
19625
+ for (const { effects: answered, text, seq } of completed) {
19626
+ for (const { resourceKey } of answered.flatMap((effect) => effect.impacts)) {
19627
+ const isSkill = resourceKey.startsWith(SKILL_RESOURCE_PREFIX);
19628
+ const key = isSkill ? resourceKey.slice(SKILL_RESOURCE_PREFIX.length) : resourceKey;
19629
+ if (isSkill) skills.set(key, text);
19630
+ effects.push({ seq, kind: isSkill ? "skill" : "path", key });
19631
+ }
19632
+ }
19633
+ }
19634
+ const paths = new Map([...engine.heldLines()].filter(([key]) => !key.startsWith(SKILL_RESOURCE_PREFIX)));
19635
+ return { paths, skills, effects };
19636
+ };
19637
+ }
19638
+
19584
19639
  // lib/pricing-store.js
19585
19640
  function tryGetStore() {
19586
19641
  try {
@@ -19635,7 +19690,7 @@ function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
19635
19690
  // package.json
19636
19691
  var package_default2 = {
19637
19692
  name: "@nomadop/session-watcher",
19638
- version: "0.11.0",
19693
+ version: "0.11.1",
19639
19694
  description: "Local Claude Code context-cost monitor, transcript replay, buckets, and handoff",
19640
19695
  type: "module",
19641
19696
  license: "MIT",
@@ -19749,7 +19804,7 @@ function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars
19749
19804
  requireBound("cacheChars", cacheChars);
19750
19805
  const cache = /* @__PURE__ */ new Map();
19751
19806
  let cachedChars = 0;
19752
- const orNull2 = (attempt) => {
19807
+ const orNull3 = (attempt) => {
19753
19808
  try {
19754
19809
  return attempt();
19755
19810
  } catch {
@@ -19773,11 +19828,11 @@ function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars
19773
19828
  }
19774
19829
  return {
19775
19830
  resolve: resolve3,
19776
- stat: (file) => orNull2(() => {
19831
+ stat: (file) => orNull3(() => {
19777
19832
  const st = statSync3(file);
19778
19833
  return { size: st.size, isFile: st.isFile() };
19779
19834
  }),
19780
- readText: (file) => orNull2(() => {
19835
+ readText: (file) => orNull3(() => {
19781
19836
  const st = statSync3(file);
19782
19837
  if (!st.isFile()) return null;
19783
19838
  const hit = cache.get(file);
@@ -19942,29 +19997,6 @@ function renderFileEvidence(displayPath, { totalLines, runs }, { maxChars = Infi
19942
19997
  });
19943
19998
  return shown.every((count) => count === 0) && available.some((count) => count > 0) ? null : { text: parts2.join("\n"), shown };
19944
19999
  }
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
20000
 
19969
20001
  // lib/resource-attribution.js
19970
20002
  var LIMIT_NAMES = ["candidates", "fileBytes", "sideChars", "decodeDepth", "alignCells", "evidenceFloor"];
@@ -20889,9 +20921,23 @@ function loadCallsOf(message) {
20889
20921
  return calls.map(({ id, name: name3, arguments: args2 }, index) => ({ id, name: name3, arguments: args2, text: content[index].text }));
20890
20922
  }
20891
20923
 
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);
20924
+ // lib/carried-evidence.js
20925
+ var CARRIED_WORDING = {
20926
+ empty: (path3) => `${path3} is empty.`,
20927
+ 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.`,
20928
+ skill: (name3, text) => `Skill ${name3}:
20929
+ ${text}`
20930
+ };
20931
+ 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}`;
20932
+ function runsOf(numbers) {
20933
+ const runs = [];
20934
+ for (const number of numbers) {
20935
+ const last = runs.at(-1);
20936
+ if (last && last[1] + 1 === number) last[1] = number;
20937
+ else runs.push([number, number]);
20938
+ }
20939
+ return runs;
20940
+ }
20895
20941
  function foldCarried(sources) {
20896
20942
  const paths = /* @__PURE__ */ new Map();
20897
20943
  const skills = /* @__PURE__ */ new Map();
@@ -20944,59 +20990,6 @@ function carryChanges(baseline, current) {
20944
20990
  ...skills.length > 0 ? { skills } : {}
20945
20991
  };
20946
20992
  }
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
20993
  function omitShown(changes, earlier) {
21001
20994
  const shown = /* @__PURE__ */ new Map();
21002
20995
  for (const source of earlier) {
@@ -21015,12 +21008,30 @@ function omitShown(changes, earlier) {
21015
21008
  })
21016
21009
  };
21017
21010
  }
21018
- function renderCarried(source) {
21011
+ var carriedOf = (earlier, current) => omitShown(carryChanges(foldCarried(earlier), current), earlier);
21012
+ function shownRuns(write, omit) {
21013
+ const texts = new Map(write);
21014
+ const left = new Set(omit);
21015
+ return runsOf(write.map(([number]) => number).filter((number) => !left.has(number))).map(([first, last]) => ({
21016
+ offset: first,
21017
+ lines: Array.from({ length: last - first + 1 }, (_, at) => ({ number: first + at, text: texts.get(first + at) }))
21018
+ }));
21019
+ }
21020
+ function entryParts({ displayPath, totalLines, state, reason, write = [], omit = [] }) {
21021
+ const W = CARRIED_WORDING;
21022
+ const parts2 = [];
21023
+ if (state === "empty") parts2.push(W.empty(displayPath));
21024
+ if (state === "unreadable") parts2.push(W.unreadable(displayPath, reason));
21025
+ const runs = shownRuns(write, omit);
21026
+ if (runs.length > 0) parts2.push(renderFileEvidence(displayPath, { totalLines, runs }).text);
21027
+ return parts2;
21028
+ }
21029
+ function renderCarried(source, wording) {
21019
21030
  const carried = [
21020
21031
  ...source.paths.flatMap(entryParts),
21021
- ...(source.skills ?? []).filter((skill) => skill.removed !== true).map((skill) => CARRIER_WORDING.skill(skill.name, skill.text))
21032
+ ...(source.skills ?? []).filter((skill) => skill.removed !== true).map((skill) => CARRIED_WORDING.skill(skill.name, skill.text))
21022
21033
  ];
21023
- return carried.length > 0 ? [CARRIER_WORDING.carried, ...carried].join("\n\n") : null;
21034
+ return carried.length > 0 ? [carriedNote(wording), ...carried].join("\n\n") : null;
21024
21035
  }
21025
21036
  function showsChange(entry) {
21026
21037
  const { state, write = [], withdraw = [] } = entry;
@@ -21039,64 +21050,18 @@ function carriedEvidence(source) {
21039
21050
  const skills = (source.skills ?? []).map((skill) => skill.removed === true ? { name: skill.name, removed: true } : { name: skill.name, text: skill.text });
21040
21051
  return files.length + removed.length + skills.length > 0 ? { files, removed, skills } : null;
21041
21052
  }
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
- ]);
21053
+
21054
+ // lib/inner-seal/state-block.js
21055
+ var STATE_WORDING = {
21056
+ heading: (seq) => `Session state as of session seq ${seq}:`,
21057
+ unchanged: "unchanged since the last summary that shows it",
21058
+ empty: "(empty)"
21059
+ };
21094
21060
  var checkedCut = (asOfSeq) => {
21095
21061
  if (!Number.isSafeInteger(asOfSeq)) throw new Error("the session state names no session seq as its cut");
21096
21062
  return asOfSeq;
21097
21063
  };
21098
21064
  function shownIn(source, { key }) {
21099
- if (source.kind !== INNER_SEAL_KIND) return void 0;
21100
21065
  return Object.hasOwn(source.state?.items ?? {}, key) ? { value: source.state.items[key].value } : void 0;
21101
21066
  }
21102
21067
  function carryItem(item, value, earlier) {
@@ -21105,12 +21070,12 @@ function carryItem(item, value, earlier) {
21105
21070
  if (last === void 0) return item.isEmpty(current) ? null : { value: current };
21106
21071
  return !item.isEmpty(current) && item.same(current, item.normalize(last.value)) ? { value: current, unchanged: true } : { value: current };
21107
21072
  }
21108
- function carryState({ asOfSeq, items }, { tools, earlier, failed: failed2 }) {
21073
+ function carryState({ asOfSeq, items }, { stateItems, tools, earlier, failed: failed2 }) {
21109
21074
  checkedCut(asOfSeq);
21110
21075
  const shown = {};
21111
- for (const item of STATE_ITEMS) {
21076
+ for (const item of stateItems) {
21112
21077
  const read = items[item.key];
21113
- if (read === void 0 || !tools.has(item.tool)) continue;
21078
+ if (read === void 0 || item.tool !== void 0 && !tools.has(item.tool)) continue;
21114
21079
  try {
21115
21080
  const carried = carryItem(item, read(), earlier);
21116
21081
  if (carried !== null) shown[item.key] = carried;
@@ -21120,37 +21085,66 @@ function carryState({ asOfSeq, items }, { tools, earlier, failed: failed2 }) {
21120
21085
  }
21121
21086
  return Object.keys(shown).length === 0 ? null : { asOfSeq, items: shown };
21122
21087
  }
21123
- function renderState({ asOfSeq, items }) {
21124
- const W = CARRIER_WORDING;
21125
- const lines = STATE_ITEMS.filter(({ key }) => Object.hasOwn(items, key)).map((item) => {
21088
+ function renderState({ asOfSeq, items }, stateItems) {
21089
+ const W = STATE_WORDING;
21090
+ const lines = stateItems.filter(({ key }) => Object.hasOwn(items, key)).map((item) => {
21126
21091
  const { value, unchanged = false } = items[item.key];
21127
21092
  const shown = item.normalize(value);
21128
- return `${W.stateLabels[item.key](item.tool)} ${item.isEmpty(shown) ? W.stateEmpty : unchanged ? W.stateUnchanged : item.text(shown)}`;
21093
+ if (item.isEmpty(shown)) return `${item.label} ${W.empty}`;
21094
+ if (unchanged) return `${item.label} ${W.unchanged}`;
21095
+ return `${item.label}${item.multiline === true ? "\n" : " "}${item.text(shown)}`;
21129
21096
  });
21130
- return [W.stateHeading(checkedCut(asOfSeq)), ...lines].join("\n");
21097
+ return [W.heading(checkedCut(asOfSeq)), ...lines].join("\n");
21098
+ }
21099
+
21100
+ // lib/inner-seal/carrier.js
21101
+ var INNER_SEAL_KIND = "session-watcher-inner-seal";
21102
+ var sourceEventSeqsOf = ({ callSeq, pruneSeq, replaced }) => [callSeq, pruneSeq, ...replaced];
21103
+ var callSeqOf = (seqs) => seqs[0];
21104
+ function assembleCarrierSource({ slots, summaries, questions, attachments, verbatimSeqs = [], changes, state }) {
21105
+ const injected = [.../* @__PURE__ */ new Set([...verbatimSeqs, ...questions.flat().flatMap(({ seqs }) => seqs ?? [])])];
21106
+ return {
21107
+ kind: INNER_SEAL_KIND,
21108
+ v: 1,
21109
+ slots: slots.map(({ seqs }, index) => ({
21110
+ seqs,
21111
+ text: summaries[index],
21112
+ ...questions[index].length > 0 ? { questions: questions[index].map(({ question, user }) => ({ question, user })) } : {},
21113
+ ...attachments[index].length > 0 ? { attachments: attachments[index] } : {}
21114
+ })),
21115
+ ...injected.length > 0 ? { verbatimSeqs: injected } : {},
21116
+ ...changes,
21117
+ ...state === null ? {} : { state }
21118
+ };
21131
21119
  }
21132
- function renderCarrier(source) {
21120
+ var CARRIER_WORDING = {
21121
+ slotLine: (seqs) => `seq ${seqs.join(", ")}: `,
21122
+ imageSaved: (name3, tool) => `The image ${name3} is not in the current context; ${tool} can read the file below when it is needed.`,
21123
+ questionMark: "A line marked question: holds the question as it was asked, and the user: line under it the user's whole answer.",
21124
+ questionLine: (question) => `question: ${question}`,
21125
+ userLine: (user) => `user: ${user}`
21126
+ };
21127
+ function renderCarrier(source, wording) {
21133
21128
  const W = CARRIER_WORDING;
21134
21129
  const blocks = [];
21135
- let lines = [source.slots.some(({ questions }) => questions !== void 0) ? `${W.addresses} ${W.questionMark}` : W.addresses];
21130
+ let lines = [source.slots.some(({ questions }) => questions !== void 0) ? `${wording.addresses} ${W.questionMark}` : wording.addresses];
21136
21131
  const flush = () => {
21137
21132
  if (lines.length > 0) blocks.push({ type: "text", text: lines.join("\n") });
21138
21133
  lines = [];
21139
21134
  };
21140
- for (const { seqs, text, questions = [], asks = [], attachments = [] } of source.slots) {
21135
+ for (const { seqs, text, questions = [], attachments = [] } of source.slots) {
21141
21136
  lines.push(`${W.slotLine(seqs)}${text}`);
21142
21137
  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
21138
  for (const { file, image } of attachments) {
21145
- if (image !== void 0) lines.push(W.imageSaved(image.name ?? image.attachmentId));
21139
+ if (image !== void 0) lines.push(W.imageSaved(image.name ?? image.attachmentId, wording.imageReadTool));
21146
21140
  flush();
21147
21141
  blocks.push({ type: "file", attachment: file });
21148
21142
  }
21149
21143
  }
21150
21144
  flush();
21151
- const carried = renderCarried(source);
21145
+ const carried = renderCarried(source, wording);
21152
21146
  const carriedBlock = carried === null ? null : { type: "text", text: carried };
21153
- const stateBlock = Object.hasOwn(source, "state") ? { type: "text", text: renderState(source.state) } : null;
21147
+ const stateBlock = Object.hasOwn(source, "state") ? { type: "text", text: renderState(source.state, wording.stateItems) } : null;
21154
21148
  for (const block of [carriedBlock, stateBlock]) if (block !== null) blocks.push(block);
21155
21149
  return blocks.map((block, index) => {
21156
21150
  if (block.type !== "text") return block;
@@ -21287,7 +21281,7 @@ function reduceLoadMessage(event) {
21287
21281
  function reduceInnerSeal(event) {
21288
21282
  const seqs = event.sourceEventSeqs;
21289
21283
  if (!Array.isArray(seqs) || !seqs.every(isIndex)) return violation(event, "sourceEventSeqs");
21290
- return { observations: [], diagnostics: [], withdraws: seqs };
21284
+ return { observations: [], diagnostics: [], sealed: seqs };
21291
21285
  }
21292
21286
  function reduceUserMessage(event) {
21293
21287
  const kind = event.data?.source?.kind;
@@ -21385,6 +21379,10 @@ function reduceDshEvent(event) {
21385
21379
  return nothing();
21386
21380
  }
21387
21381
  }
21382
+ var isMainCall = (event) => event.type === "assistant/message" && isIndex(event.seq);
21383
+ function foldInputOf(event) {
21384
+ return { ...reduceDshEvent(event), seq: event.seq, mainCall: isMainCall(event) };
21385
+ }
21388
21386
  function reduceDshSnapshot(events) {
21389
21387
  const batches = [];
21390
21388
  const diagnostics = [];
@@ -21411,6 +21409,25 @@ function createDshDialogueSource({ readSession }) {
21411
21409
  };
21412
21410
  }
21413
21411
 
21412
+ // lib/harness/dsh/ask-result.js
21413
+ function askAnswersOf(resultText) {
21414
+ let value;
21415
+ try {
21416
+ value = JSON.parse(resultText);
21417
+ } catch {
21418
+ return [];
21419
+ }
21420
+ if (!Array.isArray(value?.answers)) return [];
21421
+ const answers = [];
21422
+ for (const answer of value.answers) {
21423
+ const { id, selected, custom } = answer ?? {};
21424
+ if (!Array.isArray(selected) || !selected.every((label) => typeof label === "string")) return [];
21425
+ if (custom !== void 0 && typeof custom !== "string") return [];
21426
+ answers.push(custom === void 0 ? { id, selected } : { id, selected, custom });
21427
+ }
21428
+ return answers;
21429
+ }
21430
+
21414
21431
  // lib/harness/dsh/history-turn-rules.js
21415
21432
  function createDshHumanHeadRule() {
21416
21433
  return (line) => {
@@ -21420,25 +21437,11 @@ function createDshHumanHeadRule() {
21420
21437
  };
21421
21438
  }
21422
21439
  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
21440
  function createDshAskHeadRule() {
21438
21441
  return (line) => {
21439
21442
  if (line.kind !== "tool" || line.tool.name !== ASK_TOOL_NAME) return PASS;
21440
21443
  if (line.tool.isError === true) return ABSORB;
21441
- const text = answerText(line.tool.result).trim();
21444
+ const text = askAnswersOf(line.tool.result).flatMap(({ selected, custom }) => custom ? [...selected, custom] : selected).join("\n").trim();
21442
21445
  return text === "" ? ABSORB : { kind: "HEAD", text };
21443
21446
  };
21444
21447
  }
@@ -21962,11 +21965,6 @@ function composeWatcher({
21962
21965
  resourceKeysOf,
21963
21966
  modelPolicyFor: policyFor
21964
21967
  });
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
21968
  const recall = (toolUseId) => {
21971
21969
  try {
21972
21970
  return store.recallAttribution(sessionId, toolUseId);
@@ -21974,41 +21972,20 @@ function heldViewOf({ sessionId, cwd, store, policyFor, interpretToolUse, comple
21974
21972
  return null;
21975
21973
  }
21976
21974
  };
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({
21975
+ const view = createHeldView({
21976
+ createProjection: ({ completeToolResult: recording }) => createDshMeasurementProjection({
21983
21977
  cwd,
21984
21978
  projectRoot: cwd,
21985
21979
  resolveModelPolicy: policyFor,
21986
21980
  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
- };
21981
+ completeToolResult: recording
21982
+ }),
21983
+ completeToolResult,
21984
+ resolveModelPolicy: policyFor,
21985
+ frameCtx: sessionId ? { recall } : {}
21986
+ });
21987
+ const heldView = (events) => view(reduceDshSnapshot(events).observations);
21988
+ return { watcher, dialogueSource, dialogueProjection, heldView };
22012
21989
  }
22013
21990
 
22014
21991
  // dsh/src/observed-read.js
@@ -22045,33 +22022,31 @@ async function readUnobserved({ fs: fs3, tree, key, ranges, fileBytes, signal })
22045
22022
  return { read: readTreeWindows(tree, key, ranges, { fileBytes }), displayPath };
22046
22023
  }
22047
22024
 
22048
- // lib/harness/dsh/source-facts.js
22025
+ // lib/measurement/source-facts.js
22049
22026
  function initialSourceFacts() {
22050
22027
  return { epoch: 0, headDone: false, points: [], carriers: [] };
22051
22028
  }
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);
22029
+ var isCarrier = (input) => Array.isArray(input.sealed);
22030
+ var usageOf2 = (input) => input.observations.find((observation) => observation.type === "usage")?.usage ?? null;
22031
+ var startsEpoch = ({ observations }) => observations.some((observation) => observation.type === "epoch-boundary");
22032
+ function withCarrier(facts, input) {
22033
+ const listed = new Set(input.sealed);
22058
22034
  return {
22059
22035
  ...facts,
22060
22036
  points: facts.points.filter((point) => point.role !== "current" || !listed.has(point.seq)),
22061
- carriers: [...facts.carriers, { seq: event.seq, epoch: facts.epoch, post: null }]
22037
+ carriers: [...facts.carriers, { seq: input.seq, epoch: facts.epoch, post: null }]
22062
22038
  };
22063
22039
  }
22064
- function withMainCall(facts, event, reduced) {
22065
- const usage = usageOf2(reduced);
22040
+ function withMainCall(facts, input) {
22041
+ const usage = usageOf2(input);
22066
22042
  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;
22043
+ const carriers = waiting ? facts.carriers.map((carrier) => carrier.epoch === facts.epoch && carrier.post === null ? { ...carrier, post: { seq: input.seq, usage } } : carrier) : facts.carriers;
22068
22044
  if (usage === null) return waiting ? { ...facts, carriers } : facts;
22069
22045
  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 };
22046
+ return { ...facts, headDone: facts.headDone || stockOf(usage) > 0, points: [...facts.points, { seq: input.seq, role }], carriers };
22071
22047
  }
22072
22048
  var isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
22073
22049
  var isIndex2 = (value) => Number.isSafeInteger(value) && value >= 0;
22074
- var isMainCall = (event) => event.type === "assistant/message" && isIndex2(event.seq);
22075
22050
  var isUsage2 = (value) => isObject3(value) && ["input", "output", "cacheRead", "cacheWrite"].every((field) => Number.isFinite(value[field]));
22076
22051
  var isPost = (value) => value === null || isObject3(value) && isIndex2(value.seq) && (value.usage === null || isUsage2(value.usage));
22077
22052
  function qualifiedCalls(facts) {
@@ -22081,16 +22056,16 @@ function qualifiedCalls(facts) {
22081
22056
  function isSourceFacts(value) {
22082
22057
  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
22058
  }
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);
22059
+ function foldSourceFacts(facts, input) {
22060
+ if (!isIndex2(input.seq)) return facts;
22061
+ if (startsEpoch(input)) return { ...facts, epoch: facts.epoch + 1, headDone: false, points: [] };
22062
+ if (isCarrier(input)) return withCarrier(facts, input);
22063
+ if (input.mainCall) return withMainCall(facts, input);
22089
22064
  return facts;
22090
22065
  }
22091
22066
 
22092
- // lib/harness/dsh/source-fold.js
22093
- function withdrawn(batch, selected) {
22067
+ // lib/measurement/source-fold.js
22068
+ function sealedBatch(batch, selected) {
22094
22069
  return batch.flatMap((observation) => {
22095
22070
  if (observation.type === "tool-result") return [observation.effectsOnly ? observation : { ...observation, effectsOnly: true }];
22096
22071
  if (observation.type === "usage") return selected ? [observation] : [];
@@ -22098,30 +22073,29 @@ function withdrawn(batch, selected) {
22098
22073
  });
22099
22074
  }
22100
22075
  var changed = (before, after) => before.length !== after.length || before.some((observation, index) => observation !== after[index]);
22101
- function createDshSourceFold() {
22076
+ function createSourceFold() {
22102
22077
  const kept = [];
22103
22078
  let epochStart = 0;
22104
22079
  let facts = initialSourceFacts();
22105
- function push(event) {
22106
- const reduced = reduceDshEvent(event);
22107
- const { observations, diagnostics, withdraws = [] } = reduced;
22108
- facts = foldSourceFacts(facts, event, reduced);
22080
+ function push(input) {
22081
+ const { observations, diagnostics, sealed = [] } = input;
22082
+ facts = foldSourceFacts(facts, input);
22109
22083
  let rewound = false;
22110
- if (withdraws.length > 0) {
22111
- const listed = new Set(withdraws);
22084
+ if (sealed.length > 0) {
22085
+ const listed = new Set(sealed);
22112
22086
  const selected = new Set(facts.points.map((point) => point.seq));
22113
22087
  for (let index = epochStart; index < kept.length; index += 1) {
22114
22088
  if (!listed.has(kept[index].seq)) continue;
22115
- const next = withdrawn(kept[index].batch, selected.has(kept[index].seq));
22089
+ const next = sealedBatch(kept[index].batch, selected.has(kept[index].seq));
22116
22090
  if (!changed(kept[index].batch, next)) continue;
22117
22091
  kept[index].batch = next;
22118
22092
  rewound = true;
22119
22093
  }
22120
22094
  }
22121
- const batch = isMainCall(event) ? [{ type: "main-call", sourceOrdinal: event.seq }, ...observations] : observations;
22095
+ const batch = input.mainCall ? [{ type: "main-call", sourceOrdinal: input.seq }, ...observations] : observations;
22122
22096
  if (batch.length === 0) return { batch: null, rewound, diagnostics };
22123
22097
  if (batch.some((observation) => observation.type === "epoch-boundary")) epochStart = kept.length;
22124
- kept.push({ seq: event.seq, batch });
22098
+ kept.push({ seq: input.seq, batch });
22125
22099
  return { batch, rewound, diagnostics };
22126
22100
  }
22127
22101
  function batches() {
@@ -22137,7 +22111,7 @@ function invariant5(ok, message) {
22137
22111
  function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () => false } = {}) {
22138
22112
  invariant5(typeof onDiagnostics === "function", "onDiagnostics must be a function");
22139
22113
  const queue = [];
22140
- const fold = createDshSourceFold();
22114
+ const fold = createSourceFold();
22141
22115
  let installed = false;
22142
22116
  let drained = false;
22143
22117
  let snapshotTail;
@@ -22153,7 +22127,7 @@ function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () =>
22153
22127
  captureMode: "replay"
22154
22128
  });
22155
22129
  function liveFrame(event) {
22156
- const { batch, rewound, diagnostics } = fold.push(event);
22130
+ const { batch, rewound, diagnostics } = fold.push(foldInputOf(event));
22157
22131
  report(diagnostics);
22158
22132
  if (rewound) return replayFrame();
22159
22133
  if (batch === null) return null;
@@ -22161,7 +22135,7 @@ function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () =>
22161
22135
  }
22162
22136
  function install(snapshotEvents) {
22163
22137
  invariant5(!installed, "install runs once");
22164
- const diagnostics = snapshotEvents.flatMap((event) => fold.push(event).diagnostics);
22138
+ const diagnostics = snapshotEvents.flatMap((event) => fold.push(foldInputOf(event)).diagnostics);
22165
22139
  installed = true;
22166
22140
  snapshotTail = snapshotEvents.length === 0 ? -1 : snapshotEvents.at(-1).seq;
22167
22141
  report(diagnostics);
@@ -22186,90 +22160,38 @@ function createDshSourceDriver({ sessionId, onDiagnostics, qualifyCalls = () =>
22186
22160
  return { install, feed, drain };
22187
22161
  }
22188
22162
 
22189
- // lib/harness/dsh/inner-source.js
22163
+ // lib/harness/dsh/event-facts.js
22190
22164
  var CHECKPOINT_KIND = "compact-checkpoint";
22191
22165
  var TURN_SKELETON_TOOL = "get_turn_skeleton";
22192
- var stepKey = ({ turn, step }) => `${turn}:${step}`;
22193
- function sourceFactOf(event) {
22166
+ function markerOf(source) {
22167
+ if (source?.kind === INNER_SEAL_KIND) return "carrier";
22168
+ if (source?.kind === CHECKPOINT_KIND) return "checkpoint";
22169
+ return isLoadPayload(source) ? "payload" : null;
22170
+ }
22171
+ function eventFactOf(event) {
22194
22172
  const message = event.data?.message ?? event.data;
22195
- const blocks = event.type === "assistant/message" && Array.isArray(message?.content) ? message.content : [];
22173
+ const assistant = event.type === "assistant/message";
22174
+ const blocks = assistant && Array.isArray(message?.content) ? message.content : [];
22175
+ const marker = event.type === "user/message" ? markerOf(message?.source) : null;
22196
22176
  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)),
22177
+ system: event.type === "system/message",
22178
+ header: event.type === "request/header",
22179
+ marker,
22180
+ epoch: marker === "checkpoint" && startsEpoch(reduceDshEvent(event)),
22201
22181
  step: blocks.length > 0 ? { turn: event.data.turn, step: event.data.step } : null,
22182
+ owner: { turn: event.data?.turn, step: event.data?.step },
22183
+ assistant,
22202
22184
  skeletonCall: blocks.some((block) => block?.type === "tool-call" && block.name === TURN_SKELETON_TOOL)
22203
22185
  };
22204
22186
  }
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
22187
  var isPrunedResult = (event) => event.type === "tool/result" && event.surfaceOp?.op === "replace";
22244
22188
  var originalsOf = (event, bySeq) => event.sourceEventSeqs.flatMap((seq) => {
22245
22189
  const cited = bySeq.get(seq);
22246
22190
  return isPrunedResult(cited) ? originalsOf(cited, bySeq) : [seq];
22247
22191
  });
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) {
22192
+ function eventFactsOf(events) {
22253
22193
  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;
22194
+ return new Map(events.map((event) => [event.seq, { ...eventFactOf(event), originals: isPrunedResult(event) ? originalsOf(event, bySeq) : [] }]));
22273
22195
  }
22274
22196
 
22275
22197
  // lib/ledger-schema.js
@@ -22705,7 +22627,7 @@ function createWatcherTable({
22705
22627
  }) {
22706
22628
  const entries = /* @__PURE__ */ new Map();
22707
22629
  const listeners = /* @__PURE__ */ new Set();
22708
- let closed2 = false;
22630
+ let closed = false;
22709
22631
  function notify(sessionId) {
22710
22632
  for (const listener of listeners) {
22711
22633
  try {
@@ -22781,7 +22703,7 @@ function createWatcherTable({
22781
22703
  fail(entry, hostDiagnostic("read_session_rejected", error));
22782
22704
  return;
22783
22705
  }
22784
- for (const event of snapshot.events) entry.facts.set(event.seq, sourceFactOf(event));
22706
+ for (const event of snapshot.events) entry.facts.set(event.seq, eventFactOf(event));
22785
22707
  entry.sourceReady = true;
22786
22708
  await modelNames.warm(modelNames.pairsOf([...snapshot.events, ...entry.pending]));
22787
22709
  if (entry.state !== "bootstrapping") return;
@@ -22805,7 +22727,7 @@ function createWatcherTable({
22805
22727
  }
22806
22728
  }
22807
22729
  function ensure(session) {
22808
- if (closed2) throw new Error("the watcher table is closed");
22730
+ if (closed) throw new Error("the watcher table is closed");
22809
22731
  const sessionId = session.id;
22810
22732
  if (entries.has(sessionId)) return;
22811
22733
  const entry = {
@@ -22837,7 +22759,7 @@ function createWatcherTable({
22837
22759
  function feed(sessionId, event) {
22838
22760
  const entry = entries.get(sessionId);
22839
22761
  if (entry === void 0) return;
22840
- entry.facts.set(event.seq, sourceFactOf(event));
22762
+ entry.facts.set(event.seq, eventFactOf(event));
22841
22763
  if (entry.state !== "bootstrapping" && entry.state !== "live") return;
22842
22764
  if (event.type === "request/header") void modelNames.warm(modelNames.pairsOf([event]));
22843
22765
  let frame = null;
@@ -22870,7 +22792,7 @@ function createWatcherTable({
22870
22792
  }
22871
22793
  }
22872
22794
  function disposeAll() {
22873
- closed2 = true;
22795
+ closed = true;
22874
22796
  for (const sessionId of [...entries.keys()]) {
22875
22797
  try {
22876
22798
  dispose(sessionId);
@@ -22905,15 +22827,15 @@ function createWatcherTable({
22905
22827
  function onChange(listener) {
22906
22828
  listeners.add(listener);
22907
22829
  }
22908
- function sourceFacts(sessionId) {
22830
+ function eventFacts(sessionId) {
22909
22831
  const entry = entries.get(sessionId);
22910
22832
  return entry?.sourceReady ? entry.facts : null;
22911
22833
  }
22912
- function heldView(sessionId, events, range) {
22834
+ function heldView(sessionId, events) {
22913
22835
  const entry = entries.get(sessionId);
22914
- return entry === void 0 ? null : entry.heldView(events, range);
22836
+ return entry === void 0 ? null : entry.heldView(events);
22915
22837
  }
22916
- return { ensure, feed, dispose, disposeAll, get, waitLive, live: live2, onChange, sourceFacts, heldView };
22838
+ return { ensure, feed, dispose, disposeAll, get, waitLive, live: live2, onChange, eventFacts, heldView };
22917
22839
  }
22918
22840
 
22919
22841
  // dsh/src/model-names.js
@@ -23196,6 +23118,14 @@ function pricingResponse({ model, saved, policy, cliRatio }) {
23196
23118
  presets
23197
23119
  };
23198
23120
  }
23121
+ var INVALID_BUCKET_FILE_MESSAGE = "Body must contain { path: string }";
23122
+ var NOT_HELD_MESSAGE = "The path is not held in the current context.";
23123
+ function heldFilePayload(path3, lineNumbers, workingTree, { fileBytes }) {
23124
+ const ranges = runsOf(lineNumbers).map(([first, last]) => ({ offset: first, limit: last - first + 1 }));
23125
+ const read = readTreeWindows(workingTree, path3, ranges, { fileBytes });
23126
+ if (read.status !== "readable") return { path: path3, reason: read.reason };
23127
+ return { path: path3, total: read.totalLines, runs: read.windows };
23128
+ }
23199
23129
  function turnPageWire({ turnPage, nextBefore }) {
23200
23130
  return {
23201
23131
  turn_page: turnPage,
@@ -23239,6 +23169,7 @@ var MONITOR_NOT_COMMITTED = failure("inner_monitor_not_committed", "The inner co
23239
23169
  function createRpcHandler({
23240
23170
  table,
23241
23171
  store,
23172
+ workingTree,
23242
23173
  now = Date.now,
23243
23174
  publish = () => {
23244
23175
  },
@@ -23280,6 +23211,13 @@ function createRpcHandler({
23280
23211
  sessionId,
23281
23212
  now: now()
23282
23213
  })),
23214
+ // 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.
23215
+ "bucket/file": ({ watcher }, { path: path3 }) => {
23216
+ if (typeof path3 !== "string") return failure("invalid_body", INVALID_BUCKET_FILE_MESSAGE);
23217
+ const lineNumbers = watcher.getHeldLines(path3);
23218
+ if (lineNumbers === null) return failure("not_held", NOT_HELD_MESSAGE);
23219
+ return live(heldFilePayload(path3, lineNumbers, workingTree, { fileBytes: ATTRIBUTION_LIMITS.fileBytes }));
23220
+ },
23283
23221
  "turn/browse": (_entry, { sessionId }) => {
23284
23222
  const { sections } = buildTurnBrowse({ store, lineage: forLoadedHandoff({ store, sessionId }) });
23285
23223
  return live({ sections });
@@ -23342,7 +23280,9 @@ function createRpcHandler({
23342
23280
  "inner-monitor/call": { addresses: ["attempt"], read: (access, { sessionId, attempt }) => access?.call(sessionId, attempt) },
23343
23281
  "inner-monitor/slots": { addresses: ["attempt"], read: (access, { sessionId, attempt }) => access?.slots(sessionId, attempt) },
23344
23282
  "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) }
23283
+ "inner-monitor/handoff": { addresses: ["handoff"], read: (access, { sessionId, handoff }) => access?.handoff(sessionId, handoff) },
23284
+ "inner-monitor/settlement": { addresses: ["handoff"], read: (access, { sessionId, handoff }) => access?.settlement(sessionId, handoff) },
23285
+ "inner-monitor/settlement/current": { addresses: [], read: (access, { sessionId }) => access?.currentSettlement(sessionId) }
23346
23286
  };
23347
23287
  const isAddress = (value) => Number.isSafeInteger(value) && value >= 0;
23348
23288
  async function answerMonitor(endpoint, body2) {
@@ -23408,32 +23348,54 @@ function createRpcHandler({
23408
23348
  var PI_AI_SERVICE = "sessionWatcherPiAi";
23409
23349
  var ORIGINAL_ROW = "include:llm-pi-ai";
23410
23350
  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"];
23351
+ var CARRIER_SETTINGS_SERVICE = "sessionWatcherCarrierSettings";
23413
23352
 
23414
23353
  // dsh/src/carrier-evidence.js
23415
23354
  import { AsyncLocalStorage } from "node:async_hooks";
23355
+
23356
+ // lib/inner-seal/call-record.js
23357
+ var CALL_RECORD_NAME = "inner-call";
23416
23358
  var MAX_CARRIER_EVIDENCE = 8;
23417
- function isCarrierResult(value) {
23359
+ var UNCACHED_SHARE_ALERT = 1 / 2;
23360
+ var isObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
23361
+ var isSeq = (value) => Number.isSafeInteger(value) && value >= 0;
23362
+ var isText2 = (value) => typeof value === "string";
23363
+ function callRecordOf({ purpose, selection, input, range, stream, endedAt, attempt, carrierCache, thrown }) {
23364
+ return {
23365
+ v: 1,
23366
+ purpose,
23367
+ selection,
23368
+ input,
23369
+ range,
23370
+ stream,
23371
+ endedAt,
23372
+ ...carrierCache == null ? {} : { carrierCache },
23373
+ ...thrown == null ? {} : { thrown },
23374
+ ...attempt == null ? {} : { attempt }
23375
+ };
23376
+ }
23377
+ 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));
23378
+ var isCarrierResult = (value) => isObject4(value) && isText2(value.result) && (value.reason === void 0 || isText2(value.reason));
23379
+ 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;
23380
+
23381
+ // lib/llm-adapter/carrier-results.js
23382
+ var CARRIER_RESULTS = ["added", "native", "skipped"];
23383
+ var SKIP_REASONS = ["no-carrier", "no-native-point", "points-full", "responses-off", "unsupported"];
23384
+ function isCarrierResult2(value) {
23418
23385
  if (value === null || typeof value !== "object" || Array.isArray(value) || !CARRIER_RESULTS.includes(value.result)) return false;
23419
23386
  const keys = Object.keys(value);
23420
23387
  return value.result === "skipped" ? keys.length === 2 && SKIP_REASONS.includes(value.reason) : keys.length === 1;
23421
23388
  }
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;
23426
- }
23427
- var closed = ({ result, reason }) => result === "skipped" ? { result, reason } : { result };
23428
- function createCarrierEvidence({ responsesBreakpoint = () => false } = {}) {
23389
+
23390
+ // dsh/src/carrier-evidence.js
23391
+ function createCarrierEvidence() {
23429
23392
  const store = new AsyncLocalStorage();
23430
23393
  return {
23431
23394
  service: Object.freeze({
23432
- responsesBreakpoint,
23433
23395
  record(result) {
23434
23396
  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));
23397
+ if (scope === void 0 || !isCarrierResult2(result)) return;
23398
+ if (scope.results.length < MAX_CARRIER_EVIDENCE) scope.results.push(result);
23437
23399
  else scope.omitted += 1;
23438
23400
  }
23439
23401
  }),
@@ -23441,7 +23403,7 @@ function createCarrierEvidence({ responsesBreakpoint = () => false } = {}) {
23441
23403
  const own = { results: [], omitted: 0 };
23442
23404
  return {
23443
23405
  run: (body2) => store.run(own, body2),
23444
- evidence: () => own.results.length === 0 ? null : { results: own.results.map(closed), omitted: own.omitted }
23406
+ evidence: () => own.results.length === 0 ? null : { results: [...own.results], omitted: own.omitted }
23445
23407
  };
23446
23408
  }
23447
23409
  };
@@ -24173,15 +24135,87 @@ function createTurnReadService({
24173
24135
  };
24174
24136
  }
24175
24137
 
24176
- // 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.";
24180
- function createDshTurnRecovery() {
24181
- return { notice: NOTICE, searchHit: SEARCH_HIT, locateHit: LOCATE_HIT };
24138
+ // lib/harness/dsh/event-read.js
24139
+ var EVENT_READ_TOOL = "sw_event_read";
24140
+ var NATIVE_EVENT_READ = "session_event_read";
24141
+ var EVENT_READ_GUIDANCE = `Use ${EVENT_READ_TOOL} when you need exact data from an earlier event.`;
24142
+ var isText3 = (value) => typeof value === "string";
24143
+ var listOf = (value) => Array.isArray(value) ? value : [];
24144
+ function eventReadTargetOf(call) {
24145
+ if (call?.name !== EVENT_READ_TOOL && call?.name !== NATIVE_EVENT_READ) return void 0;
24146
+ try {
24147
+ const { seq, session_id: sessionId } = JSON.parse(call.arguments);
24148
+ if (Number.isSafeInteger(seq) && seq >= 0 && (sessionId === void 0 || isText3(sessionId))) return { seq, sessionId };
24149
+ } catch {
24150
+ return void 0;
24151
+ }
24152
+ return void 0;
24182
24153
  }
24183
-
24184
- // dsh/src/tools.js
24154
+ var sourceOf = (source) => isText3(source?.kind) ? { source: { kind: source.kind } } : {};
24155
+ function blockOf(block) {
24156
+ switch (block?.type) {
24157
+ case "text":
24158
+ case "reasoning":
24159
+ return isText3(block.text) ? [{ type: block.type, text: block.text }] : [];
24160
+ case "tool-call":
24161
+ return [{ type: "tool-call", id: block.id, name: block.name, arguments: block.arguments }];
24162
+ case "file":
24163
+ case "image":
24164
+ return block.attachment === void 0 ? [] : [{ type: block.type, attachment: block.attachment }];
24165
+ default:
24166
+ return [];
24167
+ }
24168
+ }
24169
+ var blocksOf = (content) => listOf(content).flatMap(blockOf);
24170
+ var BODIES = {
24171
+ "user/message": (data) => ({ content: blocksOf(data.content), ...sourceOf(data.source) }),
24172
+ // `interrupted` marks a prefix a cancellation cut short, which a reader must not take for a finished message.
24173
+ "assistant/message": (data) => ({ message: { content: blocksOf(data.message?.content) }, ...data.interrupted === true ? { interrupted: true } : {} }),
24174
+ "tool/call": (data) => ({ callId: data.callId, name: data.name, arguments: data.arguments }),
24175
+ "tool/result": (data) => {
24176
+ const { message, error } = data;
24177
+ return {
24178
+ message: {
24179
+ ...isText3(message?.toolCallId) ? { toolCallId: message.toolCallId } : {},
24180
+ ...typeof message?.isError === "boolean" ? { isError: message.isError } : {},
24181
+ content: blocksOf(message?.content)
24182
+ },
24183
+ ...error === void 0 || error === null ? {} : { error: { name: error.name, code: error.code } }
24184
+ };
24185
+ }
24186
+ };
24187
+ function eventTextOf(event) {
24188
+ const { type, seq, time } = event;
24189
+ const body2 = Object.hasOwn(BODIES, type) ? BODIES[type](event.data ?? {}) : void 0;
24190
+ return { type, seq, time, ...body2 === void 0 ? {} : { data: body2 } };
24191
+ }
24192
+ var NO_TEXT = " | (no semantic text)";
24193
+ var CARRIER_KINDS = /* @__PURE__ */ new Set([LOAD_MESSAGE_KIND, INNER_SEAL_KIND, CHECKPOINT_KIND]);
24194
+ function neighborLine(event, textOf4) {
24195
+ const identity = `- seq ${event.seq} | ${event.type} | ${new Date(event.time).toISOString()}`;
24196
+ if (event.type === "user/message" && CARRIER_KINDS.has(event.data?.source?.kind)) return identity;
24197
+ const text = textOf4(event);
24198
+ return `${identity}${text.length === 0 ? NO_TEXT : `
24199
+ ${text.replaceAll("\n", "\n ")}`}`;
24200
+ }
24201
+ function formatEventRead({ sessionId, title, window: window2, textOf: textOf4 }) {
24202
+ const { target } = window2;
24203
+ const lines = [`Session ${sessionId} \u2014 ${title}`, `Target event seq ${target.seq}:`, "```json", JSON.stringify(eventTextOf(target), null, 2), "```"];
24204
+ for (const [heading, neighbors] of [["Before:", window2.events.filter((event) => event.seq < target.seq)], ["After:", window2.events.filter((event) => event.seq > target.seq)]]) {
24205
+ if (neighbors.length > 0) lines.push("", heading, ...neighbors.map((event) => neighborLine(event, textOf4)));
24206
+ }
24207
+ return lines.join("\n");
24208
+ }
24209
+
24210
+ // lib/harness/dsh/turn-recovery.js
24211
+ 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).`;
24212
+ 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.`;
24213
+ 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.`;
24214
+ function createDshTurnRecovery() {
24215
+ return { notice: NOTICE, searchHit: SEARCH_HIT, locateHit: LOCATE_HIT };
24216
+ }
24217
+
24218
+ // dsh/src/tools.js
24185
24219
  var OUTPUT = {
24186
24220
  schema: { type: "object", additionalProperties: true },
24187
24221
  render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }]
@@ -24739,6 +24773,98 @@ function createContinueCommand({ table, store, kit, meter, flush, deliver, readF
24739
24773
  return { name: COMMAND_NAME2, description: COMMAND_DESCRIPTION2, handler };
24740
24774
  }
24741
24775
 
24776
+ // dsh/src/event-read.js
24777
+ var UNTITLED = "untitled";
24778
+ var UNAUTHORIZED = "SESSION_QUERY_TOOL_UNAUTHORIZED";
24779
+ var FAILED = "SESSION_QUERY_TOOL_FAILED";
24780
+ var CARRIED = "SW_EVENT_CARRIED";
24781
+ var SAFE_FAILURES = {
24782
+ SESSION_QUERY_ABORTED: "session query was cancelled",
24783
+ SESSION_QUERY_EVENT_NOT_FOUND: "session event was not found",
24784
+ SESSION_QUERY_INVALID_WINDOW: "session event window is invalid",
24785
+ SESSION_QUERY_SESSION_NOT_FOUND: "session was not found"
24786
+ };
24787
+ function createEventReadTool({ defineTool: defineTool2, ctx, extractSessionEventText: extractSessionEventText2, HarnessError: HarnessError2, heldInContext: heldInContext2 = () => false }) {
24788
+ const failure4 = (message, code) => new HarnessError2(message, code);
24789
+ const unauthorized = () => failure4("session target is outside the caller workspace", UNAUTHORIZED);
24790
+ const assertCount = (name3, value) => {
24791
+ if (!Number.isSafeInteger(value) || value < 0) throw failure4(`${name3} must be a non-negative safe integer`, "SESSION_QUERY_INVALID_WINDOW");
24792
+ };
24793
+ const isHeld = (sessionId, seq) => {
24794
+ try {
24795
+ return heldInContext2(sessionId, seq);
24796
+ } catch (error) {
24797
+ writeDiagnostic(sessionId, hostDiagnostic("event_read_held_failed", error));
24798
+ return false;
24799
+ }
24800
+ };
24801
+ const guarded = async (sessionId, signal, call) => {
24802
+ signal.throwIfAborted();
24803
+ try {
24804
+ const value = await call();
24805
+ signal.throwIfAborted();
24806
+ return value;
24807
+ } catch (error) {
24808
+ signal.throwIfAborted();
24809
+ writeDiagnostic(sessionId, hostDiagnostic("event_read_failed", error));
24810
+ const message = typeof error?.code === "string" && Object.hasOwn(SAFE_FAILURES, error.code) ? SAFE_FAILURES[error.code] : void 0;
24811
+ throw message === void 0 ? failure4("session query operation failed", FAILED) : failure4(message, error.code);
24812
+ }
24813
+ };
24814
+ return defineTool2({
24815
+ name: EVENT_READ_TOOL,
24816
+ description: "Read the full unabridged text of one event and optional neighboring raw-event summaries from an authorized session.",
24817
+ parameters: {
24818
+ session_id: { type: "string", description: "Target session id. Omit for the current session." },
24819
+ seq: { type: "integer", required: true, description: "Target event sequence number." },
24820
+ before: { type: "integer", description: "Number of preceding raw events to summarize. Omit for none." },
24821
+ after: { type: "integer", description: "Number of following raw events to summarize. Omit for none." }
24822
+ },
24823
+ output: { schema: { type: "string" }, render: (_args, value) => [{ type: "text", text: value }] },
24824
+ isConcurrencySafe: () => true,
24825
+ async execute({ session_id: requested, seq, before, after }, { agent, signal }) {
24826
+ assertCount("seq", seq);
24827
+ if (before !== void 0) assertCount("before", before);
24828
+ if (after !== void 0) assertCount("after", after);
24829
+ const { id: callerId, header } = agent.session;
24830
+ const sessionId = requested ?? callerId;
24831
+ if (sessionId === callerId && isHeld(callerId, seq)) {
24832
+ throw failure4(`Event seq ${seq} is already in your context word for word; reading it gives the same text. Use it.`, CARRIED);
24833
+ }
24834
+ const run2 = (call) => guarded(callerId, signal, call);
24835
+ const assertObserved = (observed) => {
24836
+ if (observed?.id !== sessionId || observed.cwd !== header.cwd) throw unauthorized();
24837
+ };
24838
+ if (sessionId !== callerId) {
24839
+ if (header.cwd === void 0) throw unauthorized();
24840
+ const records = await run2(() => ctx.sessionQuery.filterSessions([{ kind: "id", values: [sessionId] }, { kind: "cwd", values: [header.cwd] }], signal));
24841
+ if (records.length !== 1) throw unauthorized();
24842
+ }
24843
+ const window2 = await run2(() => ctx.sessionQuery.readEvent({
24844
+ sessionId,
24845
+ seq,
24846
+ ...before === void 0 ? {} : { before },
24847
+ ...after === void 0 ? {} : { after }
24848
+ }, signal));
24849
+ assertObserved(window2.session);
24850
+ let title = UNTITLED;
24851
+ try {
24852
+ const [observation] = await run2(() => ctx.sessionQuery.readTitleSnapshots([sessionId], signal));
24853
+ if (observation?.status === "fulfilled") {
24854
+ assertObserved(observation.value.session);
24855
+ title = observation.value.title?.title ?? UNTITLED;
24856
+ } else {
24857
+ writeDiagnostic(callerId, hostDiagnostic("event_read_title_failed", observation?.reason));
24858
+ }
24859
+ } catch (error) {
24860
+ if (error.code === UNAUTHORIZED) throw error;
24861
+ signal.throwIfAborted();
24862
+ }
24863
+ return formatEventRead({ sessionId, title, window: window2, textOf: extractSessionEventText2 });
24864
+ }
24865
+ });
24866
+ }
24867
+
24742
24868
  // dsh/src/skills.js
24743
24869
  import { existsSync, readdirSync, readFileSync as readFileSync6 } from "node:fs";
24744
24870
  import { join as join7 } from "node:path";
@@ -24767,24 +24893,35 @@ function registerSkills(ctx, { skillsDir }) {
24767
24893
  }
24768
24894
  }
24769
24895
 
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";
24896
+ // lib/inner-seal/mode.js
24773
24897
  var MODES = ["off", "on", "invalid"];
24774
- var messageOf4 = (error) => error instanceof Error ? error.message : String(error);
24775
24898
  var STATES = Object.fromEntries(MODES.map((mode) => [mode, {
24776
24899
  unlocked: Object.freeze({ mode, locked: false }),
24777
24900
  locked: Object.freeze({ mode, locked: true })
24778
24901
  }]));
24779
24902
  var stateOf = (mode, locked) => STATES[mode][locked ? "locked" : "unlocked"];
24780
- var isModeInput = (event) => event.type === "turn/start" || event.type === MODE_RECORD_TYPE;
24781
24903
  var isModeData = (data) => data !== null && typeof data === "object" && data.v === 1 && typeof data.enabled === "boolean";
24904
+ var INITIAL_MODE = stateOf("off", false);
24905
+ function modeStateOf(value) {
24906
+ if (value === null || typeof value !== "object" || !MODES.includes(value.mode) || typeof value.locked !== "boolean") return null;
24907
+ return stateOf(value.mode, value.locked);
24908
+ }
24909
+ function foldMode(state, input) {
24910
+ if (state.locked) return state;
24911
+ if (input.turnStarted === true) return stateOf(state.mode, true);
24912
+ return stateOf(isModeData(input.record) ? input.record.enabled ? "on" : "off" : "invalid", false);
24913
+ }
24914
+
24915
+ // dsh/src/inner-mode.js
24916
+ var MODE_RECORD_TYPE = "plugin:session-watcher/inner-mode";
24917
+ var MODE_PROJECTION_KEY = "session-watcher/inner-mode";
24918
+ var messageOf4 = (error) => error instanceof Error ? error.message : String(error);
24919
+ var isModeInput = (event) => event.type === "turn/start" || event.type === MODE_RECORD_TYPE;
24782
24920
  var stateSchema = {
24783
24921
  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);
24922
+ const state = modeStateOf(value);
24923
+ if (state === null) throw new Error("the inner mode state is not { mode, locked }");
24924
+ return state;
24788
24925
  }
24789
24926
  };
24790
24927
  function innerModeProjection({ pluginRecordOf: pluginRecordOf2 }) {
@@ -24792,13 +24929,12 @@ function innerModeProjection({ pluginRecordOf: pluginRecordOf2 }) {
24792
24929
  key: MODE_PROJECTION_KEY,
24793
24930
  stateVersion: 1,
24794
24931
  stateSchema,
24795
- init: () => stateOf("off", false),
24932
+ init: () => INITIAL_MODE,
24796
24933
  apply(state, event) {
24797
- if (state.locked) return state;
24798
- if (event.type === "turn/start") return stateOf(state.mode, true);
24934
+ if (event.type === "turn/start") return foldMode(state, { turnStarted: true });
24799
24935
  const record = pluginRecordOf2(event);
24800
24936
  if (record?.type !== MODE_RECORD_TYPE) return state;
24801
- return stateOf(isModeData(record.data) ? record.data.enabled ? "on" : "off" : "invalid", false);
24937
+ return foldMode(state, { record: record.data });
24802
24938
  }
24803
24939
  };
24804
24940
  }
@@ -24859,7 +24995,235 @@ function createModeAccess({ sessionOf, readMode, select, readStored }) {
24859
24995
  return access;
24860
24996
  }
24861
24997
 
24862
- // dsh/src/inner-quote.js
24998
+ // lib/inner-seal/source.js
24999
+ var stepKey = ({ turn, step }) => `${turn}:${step}`;
25000
+ function headerSeqIn(facts, { latest, above }) {
25001
+ let found = null;
25002
+ for (const [seq, fact] of facts) {
25003
+ if (!fact.header || !latest && seq <= above) continue;
25004
+ if (found === null || (latest ? seq > found : seq < found)) found = seq;
25005
+ }
25006
+ return found;
25007
+ }
25008
+ function initialPrefixLength(facts, nodes) {
25009
+ let length = nodes.length > 0 && facts.get(nodes[0]).system ? 1 : 0;
25010
+ let opened = -1;
25011
+ nodes.forEach((seq, index) => {
25012
+ if (facts.get(seq).epoch && seq > opened) {
25013
+ opened = seq;
25014
+ length = Math.max(length, index + 1);
25015
+ }
25016
+ });
25017
+ const first = headerSeqIn(facts, { latest: false, above: opened });
25018
+ if (first === null) return length;
25019
+ while (length < nodes.length && nodes[length] > opened && nodes[length] < first) length += 1;
25020
+ return length;
25021
+ }
25022
+ function innerSource(facts, nodes) {
25023
+ const prefix = initialPrefixLength(facts, nodes);
25024
+ let at = -1;
25025
+ nodes.forEach((seq, index) => {
25026
+ const { marker } = facts.get(seq);
25027
+ if (marker !== null && (marker !== "payload" || index >= prefix) && (at < 0 || seq > nodes[at])) at = index;
25028
+ });
25029
+ const range = nodes.slice(Math.max(prefix, at + 1));
25030
+ const steps = new Set(range.map((seq) => facts.get(seq).step).filter((step) => step !== null).map(stepKey));
25031
+ const lastCall = range.findLastIndex((seq) => facts.get(seq).skeletonCall);
25032
+ const lastPayload = range.findLastIndex((seq) => facts.get(seq).marker === "payload");
25033
+ return { frontier: at < 0 ? null : nodes[at], range, stepN: steps.size, paused: lastCall > lastPayload };
25034
+ }
25035
+ function skeletonSlots(facts, nodes, range) {
25036
+ const selected = new Set(range);
25037
+ const sources = nodes.filter((seq) => selected.has(seq));
25038
+ const counted = new Set(sources.map((seq) => facts.get(seq).step).filter((step) => step !== null).map(stepKey));
25039
+ const slots = [];
25040
+ const stepSlots = /* @__PURE__ */ new Map();
25041
+ for (const seq of sources) {
25042
+ const { owner, assistant, originals } = facts.get(seq);
25043
+ const key = stepKey(owner);
25044
+ const seqs = [...originals, seq];
25045
+ if (!counted.has(key)) {
25046
+ if (!assistant) slots.push({ seqs });
25047
+ } else if (stepSlots.has(key)) {
25048
+ stepSlots.get(key).seqs.push(...seqs);
25049
+ } else {
25050
+ const slot = { seqs, step: { turn: owner.turn, step: owner.step } };
25051
+ stepSlots.set(key, slot);
25052
+ slots.push(slot);
25053
+ }
25054
+ }
25055
+ return slots;
25056
+ }
25057
+
25058
+ // lib/inner-seal/git-state.js
25059
+ import { execFile } from "node:child_process";
25060
+ import { promisify } from "node:util";
25061
+ var execFileAsync = promisify(execFile);
25062
+ var STATUS_COMMAND = ["status", "--short", "--branch"];
25063
+ var LOG_COMMAND = ["log", "-1", "--oneline"];
25064
+ var BRANCH_LINE_START = "## ";
25065
+ var GIT_SAFE_OPTIONS = ["-c", "core.fsmonitor=false"];
25066
+ function isGitStateCommand(command) {
25067
+ if (typeof command !== "string") return false;
25068
+ const [status, head, ...rest] = command.trim().split(/[ \t]*&&[ \t]*/u);
25069
+ return rest.length === 0 && /^git[ \t]+status(?:[ \t]+--?[\w=-]+)*$/u.test(status) && (head === void 0 || head.split(/[ \t]+/u).join(" ") === `git ${LOG_COMMAND.join(" ")}`);
25070
+ }
25071
+ var STATUS_LISTING = "git status --short";
25072
+ var GIT_STATUS_LINE_LIMIT = 20;
25073
+ var GIT_READ_TIMEOUT_MS = 5e3;
25074
+ var linesOf = (text) => text.split("\n").filter((line, at, all) => line !== "" || at < all.length - 1);
25075
+ var leftNotice = (count) => `\u2026 and ${count} more not shown; \`${STATUS_LISTING}\` lists them all`;
25076
+ var GIT_ENV = { LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0" };
25077
+ async function runGit(args2, { cwd, signal, timeoutMs }) {
25078
+ try {
25079
+ const { stdout } = await execFileAsync("git", [...GIT_SAFE_OPTIONS, ...args2], { cwd, signal, timeout: timeoutMs, encoding: "utf8", env: { ...process.env, ...GIT_ENV } });
25080
+ return { stdout };
25081
+ } catch (error) {
25082
+ if (typeof error.code === "number") return { exit: error.stderr };
25083
+ throw error;
25084
+ }
25085
+ }
25086
+ async function readGitState({ cwd, signal, timeoutMs = GIT_READ_TIMEOUT_MS }) {
25087
+ if (typeof cwd !== "string" || cwd === "") throw new Error("the git state has no working directory to be read in");
25088
+ const options = { cwd, signal, timeoutMs };
25089
+ const status = await runGit(STATUS_COMMAND, options);
25090
+ if ("exit" in status) {
25091
+ if (/not a git repository/i.test(status.exit)) return null;
25092
+ throw new Error(`git ${STATUS_COMMAND.join(" ")} failed: ${status.exit.trim()}`);
25093
+ }
25094
+ const [branch, ...entries] = linesOf(status.stdout);
25095
+ if (!branch?.startsWith(BRANCH_LINE_START)) throw new Error(`git ${STATUS_COMMAND.join(" ")} printed no branch line`);
25096
+ const log = await runGit(LOG_COMMAND, options);
25097
+ const heads = "exit" in log ? [] : linesOf(log.stdout);
25098
+ if (heads.length > 1 || heads.length === 1 && heads[0] === "") throw new Error(`git ${LOG_COMMAND.join(" ")} did not print one line`);
25099
+ const left = entries.length - GIT_STATUS_LINE_LIMIT;
25100
+ return [branch, ...entries.slice(0, GIT_STATUS_LINE_LIMIT), ...left > 0 ? [leftNotice(left)] : [], ...heads].join("\n");
25101
+ }
25102
+ var GIT_STATE_ITEM = Object.freeze({
25103
+ key: "git",
25104
+ label: `Git, as \`git ${STATUS_COMMAND.join(" ")} && git ${LOG_COMMAND.join(" ")}\` would show:`,
25105
+ multiline: true,
25106
+ normalize: (value) => {
25107
+ if (typeof value !== "string" || value === "") throw new Error("the git state is not a text");
25108
+ return value;
25109
+ },
25110
+ isEmpty: () => false,
25111
+ same: (a, b) => a === b,
25112
+ text: (value) => value
25113
+ });
25114
+
25115
+ // lib/harness/dsh/carrier-table.js
25116
+ var carriesEvidence = (source) => source?.kind === INNER_SEAL_KIND || source?.kind === LOAD_MESSAGE_KIND && Array.isArray(source.paths);
25117
+ var isTodoItem = (item) => item !== null && typeof item === "object" && typeof item.content === "string" && typeof item.status === "string";
25118
+ function todoItemsOf(value) {
25119
+ if (value === null) return [];
25120
+ 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");
25121
+ return value.map(({ content, status }) => ({ content, status }));
25122
+ }
25123
+ function textEntriesOf(value, fields, what) {
25124
+ if (!Array.isArray(value) || !value.every((entry) => entry !== null && typeof entry === "object" && fields.every((field) => typeof entry[field] === "string"))) {
25125
+ throw new Error(`the ${what} is not a list of entries with ${fields.join(" and ")} texts`);
25126
+ }
25127
+ return value.map((entry) => Object.fromEntries(fields.map((field) => [field, entry[field]])));
25128
+ }
25129
+ var sameEntries = (fields, a, b) => a.length === b.length && a.every((entry, at) => fields.every((field) => entry[field] === b[at][field]));
25130
+ var entryList = (entries) => entries.map(({ id, label }) => `${id} \u2014 ${label}`).join("; ");
25131
+ var AGENT_FIELDS = ["id", "label"];
25132
+ var TODO_FIELDS = ["content", "status"];
25133
+ var stateItem = ({ tool, label, ...rest }) => Object.freeze({ ...rest, tool, label: label(tool) });
25134
+ function argumentsOf(call) {
25135
+ try {
25136
+ return JSON.parse(call.arguments);
25137
+ } catch {
25138
+ return void 0;
25139
+ }
25140
+ }
25141
+ var CARRIER_TABLE = Object.freeze({
25142
+ 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.`,
25143
+ editGuard: "The reads behind this file text still count in this session, so edit a file without reading it again.",
25144
+ imageReadTool: "read_image",
25145
+ stateItems: Object.freeze([
25146
+ stateItem({
25147
+ key: "workingDirectory",
25148
+ tool: "working_directory",
25149
+ label: (tool) => `Working directory, as ${tool} would show:`,
25150
+ operation: (call) => typeof argumentsOf(call)?.cd === "string" ? "write" : "read",
25151
+ normalize: (value) => {
25152
+ if (typeof value !== "string" || value === "") throw new Error("the working directory is not a path text");
25153
+ return value;
25154
+ },
25155
+ isEmpty: () => false,
25156
+ same: (a, b) => a === b,
25157
+ text: (value) => value
25158
+ }),
25159
+ stateItem({
25160
+ key: "subagents",
25161
+ tool: "list_agents",
25162
+ label: (tool) => `Running subagents, as ${tool} would show:`,
25163
+ normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "subagent list"),
25164
+ isEmpty: (entries) => entries.length === 0,
25165
+ same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
25166
+ text: entryList
25167
+ }),
25168
+ stateItem({
25169
+ key: "jobs",
25170
+ tool: "job_list",
25171
+ label: (tool) => `Running jobs, as ${tool} would show:`,
25172
+ normalize: (value) => textEntriesOf(value, AGENT_FIELDS, "job list"),
25173
+ isEmpty: (entries) => entries.length === 0,
25174
+ same: (a, b) => sameEntries(AGENT_FIELDS, a, b),
25175
+ text: entryList
25176
+ }),
25177
+ stateItem({
25178
+ key: "todos",
25179
+ tool: "todo_write",
25180
+ operation: "write",
25181
+ label: (tool) => `Todo list, as ${tool} last left it:`,
25182
+ normalize: todoItemsOf,
25183
+ isEmpty: (items) => items.length === 0,
25184
+ same: (a, b) => sameEntries(TODO_FIELDS, a, b),
25185
+ text: (items) => JSON.stringify(items)
25186
+ }),
25187
+ Object.freeze({ ...GIT_STATE_ITEM, matchesCall: (call) => call.name === "bash" && isGitStateCommand(argumentsOf(call)?.command) })
25188
+ ])
25189
+ });
25190
+ function stateOperationOf(call) {
25191
+ if (typeof call?.name !== "string") return void 0;
25192
+ const item = CARRIER_TABLE.stateItems.find((item2) => item2.matchesCall?.(call) ?? item2.tool === call.name);
25193
+ if (item === void 0) return void 0;
25194
+ return typeof item.operation === "function" ? item.operation(call) : item.operation ?? "read";
25195
+ }
25196
+
25197
+ // lib/harness/dsh/message-blocks.js
25198
+ var blockText = (block) => block.type === "text" || block.type === "reasoning" ? block.text : block.type === "tool-call" ? `${block.name}${block.arguments}` : JSON.stringify(block);
25199
+ var requestTextOf = (message) => message.content.map(blockText).join("");
25200
+ var blocksOf2 = (message) => Array.isArray(message?.content) ? message.content : [];
25201
+ var textOf2 = (messages) => messages.flatMap(blocksOf2).filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
25202
+ function slotFactsOf(slot, messages) {
25203
+ const [first] = messages;
25204
+ const text = textOf2(messages);
25205
+ if (slot.step === void 0) {
25206
+ if (first?.role === "tool") return { own: false, kind: "result", text, toolCallId: first.toolCallId };
25207
+ return { own: first?.role === "user" && first.source?.kind === "user", kind: "other", text };
25208
+ }
25209
+ const failed2 = new Set(messages.filter((message) => message.role === "tool" && message.isError === true).map((message) => message.toolCallId));
25210
+ const assistant = messages.filter((message) => message.role === "assistant");
25211
+ 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) }));
25212
+ return { own: false, kind: "step", text, assistantText: textOf2(assistant), calls };
25213
+ }
25214
+
25215
+ // lib/inner-seal/touched.js
25216
+ function touchedOf({ paths, skills, effects }, seqs) {
25217
+ const replaced = new Set(seqs);
25218
+ const touched = { path: /* @__PURE__ */ new Set(), skill: /* @__PURE__ */ new Set() };
25219
+ for (const { seq, kind, key } of effects) if (replaced.has(seq)) touched[kind].add(key);
25220
+ return {
25221
+ paths: new Map([...paths].filter(([key]) => touched.path.has(key))),
25222
+ skills: new Map([...skills].filter(([name3]) => touched.skill.has(name3)))
25223
+ };
25224
+ }
25225
+
25226
+ // lib/inner-seal/quote.js
24863
25227
  var INNER_QUOTE = Object.freeze({ minSteps: 8, cPerStep: 200, fee: 1e4 });
24864
25228
  var KAPPA_PRICE_ANCHOR = 25;
24865
25229
  var KAPPA_WEIGHT_SHIFT = 23;
@@ -24882,22 +25246,16 @@ function kappaOf(n, cRatio, { p, alpha }) {
24882
25246
  const weight = (cRatio - KAPPA_PRICE_ANCHOR) / (cRatio + KAPPA_WEIGHT_SHIFT);
24883
25247
  return 1 + alpha * powInt(etaOf(n, cRatio), p) + weight * compensation;
24884
25248
  }
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);
25249
+ function estimateInnerA({ n, texts, bText, ctp }) {
25250
+ const lA = texts.reduce((sum, text) => sum + charsToTokens(text, ctp), 0);
25251
+ const bEst = charsToTokens(bText, ctp);
24894
25252
  const cEst = INNER_QUOTE.cPerStep * n;
24895
25253
  return { n, lA, bEst, cEst, sEst: lA - bEst - cEst };
24896
25254
  }
24897
25255
  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;
25256
+ function resultsOf(n, { bEst, cEst, sEst }, cRatio, readCost) {
25257
+ const fixed = cRatio * INNER_QUOTE.fee + (cRatio - 1) * bEst + readCost;
25258
+ const nRef = fixed / sEst;
24901
25259
  const v = (cRatio - 1) * cEst / sEst;
24902
25260
  const N = nRef + v;
24903
25261
  const jRef = 2 * Math.sqrt(n * nRef) + v;
@@ -24905,22 +25263,14 @@ function resultsOf(n, { bEst, cEst, sEst }, cRatio) {
24905
25263
  if (![nRef, N, jRef, q].every(Number.isFinite) || !(jRef > 0)) return null;
24906
25264
  return { nRef, N, jRef, q, arm: n >= nRef ? "right" : "left" };
24907
25265
  }
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 }) {
25266
+ function innerQuote({ n, estimate, cRatio, preset, summaryReadCost }) {
24915
25267
  const ratio = Number.isFinite(cRatio) ? cRatio : null;
24916
25268
  const priced2 = ratio === null ? NaN : kappaOf(n, ratio, KAPPA_PRESETS[preset]);
24917
25269
  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
- }
25270
+ const priceable = estimate !== null && ratio !== null && estimate.sEst > 0;
25271
+ const read = Number.isFinite(summaryReadCost) && summaryReadCost >= 0 ? summaryReadCost : null;
25272
+ const found = priceable ? resultsOf(n, estimate, ratio, read ?? 0) : null;
25273
+ const results = kappa === null ? null : found;
24924
25274
  const quoted2 = results !== null && n >= INNER_QUOTE.minSteps && (results.arm === "right" || results.q < kappa);
24925
25275
  return {
24926
25276
  n,
@@ -24933,54 +25283,78 @@ function innerQuote({ n, estimate, cRatio, preset }) {
24933
25283
  kappa,
24934
25284
  preset,
24935
25285
  ...results ?? NO_RESULT,
24936
- trigger: quoted2 ? "quote" : null,
24937
- missing
25286
+ ...results !== null && read !== null ? { summaryReadCost: read } : {},
25287
+ trigger: quoted2 ? "quote" : null
24938
25288
  };
24939
25289
  }
25290
+ var isObject5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25291
+ var isSeq2 = (value) => Number.isSafeInteger(value) && value >= 0;
25292
+ var orNull = (holds) => (value) => value === null || holds(value);
25293
+ var QUOTE_QUANTITIES = ["lA", "bEst", "cEst", "sEst", "cRatio", "nRef", "N", "jRef", "q"];
25294
+ function isQuote(value) {
25295
+ 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";
25296
+ }
24940
25297
 
24941
- // dsh/src/inner-summary.js
24942
- var SUMMARY_PURPOSE = "inner-compaction";
25298
+ // lib/inner-seal/attempt-record.js
25299
+ var ATTEMPT_RECORD_NAME = "inner-attempt";
25300
+ var isObject6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25301
+ var isSeq3 = (value) => Number.isSafeInteger(value) && value >= 0;
25302
+ var attemptRecordOf = ({ range, request, quote }) => ({ v: 1, range, request, quote });
25303
+ 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);
25304
+ var attemptQuoteOf = (data) => isQuote(data.quote) ? data.quote : null;
25305
+
25306
+ // lib/inner-seal/end-record.js
25307
+ var END_RECORD_NAME = "inner-end";
25308
+ var isObject7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25309
+ var isSeq4 = (value) => Number.isSafeInteger(value) && value >= 0;
25310
+ var isText4 = (value) => typeof value === "string";
25311
+ var endRecordOf = ({ attempt, outcome, reason }) => ({ v: 1, attempt, outcome, reason });
25312
+ var isEndRecord = (data) => isObject7(data) && data.v === 1 && isSeq4(data.attempt) && (data.outcome === "failed" || data.outcome === "cancelled") && isText4(data.reason);
25313
+
25314
+ // lib/inner-seal/ladder.js
24943
25315
  var FORMAT_FAILURE = "format";
24944
25316
  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;
25317
+ var SUMMARY_MAX_REQUESTS = 3;
25318
+ var SUMMARY_FILTER_RETRIES = 1;
25319
+ function createRetryLadder({ selection, fallback }) {
25320
+ const rungs = [selection, ...Array(SUMMARY_FILTER_RETRIES).fill(selection), ...fallback === null ? [] : [fallback]];
25321
+ let rung = 0;
25322
+ let requests = 1;
24951
25323
  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) })) }
25324
+ current: () => rungs[rung],
25325
+ next(failure4) {
25326
+ if (failure4 === FORMAT_FAILURE && requests < SUMMARY_MAX_REQUESTS) {
25327
+ requests += 1;
25328
+ return true;
25329
+ }
25330
+ if (failure4 === FILTER_FAILURE && rung < rungs.length - 1) {
25331
+ rung += 1;
25332
+ return true;
25333
+ }
25334
+ return false;
24958
25335
  }
24959
25336
  };
24960
25337
  }
25338
+
25339
+ // lib/inner-seal/summary.js
24961
25340
  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
25341
  function cueText(text) {
24965
25342
  const folded = text.replace(/\s+/gu, " ");
24966
25343
  const half = C_CUE_TEXT_CHARS / 2;
24967
25344
  return JSON.stringify(folded.length <= C_CUE_TEXT_CHARS ? folded : `${safePrefix(folded, half)}\u2026${safeSuffix(folded, half)}`);
24968
25345
  }
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}`;
25346
+ function verbatimNoteOf(facts) {
25347
+ if (!facts.own) return null;
25348
+ const { uText, uOriginalChars } = storedUText(facts.text);
25349
+ const truncated = uOriginalChars > uText.length;
25350
+ const u = truncated ? `${uText}${truncationMarker(uOriginalChars)}` : uText;
25351
+ return { text: `user: ${u}`, whole: !truncated && uText !== "" };
24980
25352
  }
24981
- function stringsOf(value, found = []) {
25353
+ function valuesOf(value, key, found = []) {
24982
25354
  if (typeof value === "string") found.push(value);
24983
- else if (value !== null && typeof value === "object") Object.values(value).forEach((item) => stringsOf(item, found));
25355
+ else if (typeof value === "number" || typeof value === "boolean") found.push(key === void 0 ? String(value) : `${key} ${value}`);
25356
+ else if (Array.isArray(value)) value.forEach((item) => valuesOf(item, key, found));
25357
+ else if (value !== null && typeof value === "object") Object.entries(value).forEach(([name3, item]) => valuesOf(item, name3, found));
24984
25358
  return found;
24985
25359
  }
24986
25360
  function argumentsCueOf(call) {
@@ -24990,28 +25364,21 @@ function argumentsCueOf(call) {
24990
25364
  } catch {
24991
25365
  parsed = call.arguments;
24992
25366
  }
24993
- const text = stringsOf(parsed).join(" ").trim();
25367
+ const text = valuesOf(parsed).join(" ").trim();
24994
25368
  return text === "" ? "" : `: ${cueText(text)}`;
24995
25369
  }
24996
- function rowsOf(entries) {
25370
+ function rowsOf(slotFacts, verbatim) {
24997
25371
  let number = 0;
24998
- return entries.map(({ slot, messages, verbatim }) => {
24999
- if (verbatim !== null) return `user, no note: ${cueText(textOf2(messages))}`;
25372
+ return slotFacts.map((facts, at) => {
25373
+ if (verbatim[at] !== null) return `user, no note: ${cueText(facts.text)}`;
25000
25374
  number += 1;
25001
25375
  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");
25376
+ if (facts.kind === "result") return `${label} tool result of call ${facts.toolCallId}`;
25377
+ if (facts.kind !== "step") return `${label} harness: ${cueText(facts.text)}`;
25011
25378
  return [
25012
25379
  `${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)}`)
25380
+ ` text: ${facts.assistantText === "" ? "none" : cueText(facts.assistantText)}`,
25381
+ ...facts.calls.map((call) => ` call ${call.id} ${call.name} \u2192 ${call.failed ? "error" : "ok"}${argumentsCueOf(call)}`)
25015
25382
  ].join("\n");
25016
25383
  }).join("\n");
25017
25384
  }
@@ -25041,21 +25408,21 @@ Held, beside the notes:
25041
25408
  {held}
25042
25409
 
25043
25410
  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);
25411
+ function planSummary(slotFacts, held) {
25412
+ const notes = slotFacts.map(verbatimNoteOf);
25413
+ const verbatim = notes.map((note) => note?.text ?? null);
25414
+ const wholeUserSlots = notes.flatMap((note, at) => note?.whole ? [at] : []);
25415
+ const askedCount = verbatim.filter((note) => note === null).length;
25046
25416
  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
- };
25417
+ const values = { rows: rowsOf(slotFacts, verbatim), N: String(askedCount), held: heldList };
25418
+ return { tailText: TAIL_TEMPLATE.replace(/\{(rows|N|held)\}/gu, (_, key) => values[key]), verbatim, wholeUserSlots, askedCount };
25419
+ }
25053
25420
  function notesOf(parsed, count) {
25054
25421
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || Object.keys(parsed).length !== count) return void 0;
25055
25422
  const notes = Array.from({ length: count }, (_, at) => parsed[String(at + 1)]);
25056
25423
  return notes.every((note) => typeof note === "string") ? notes : void 0;
25057
25424
  }
25058
- function parseSummaries(text, count, loads2) {
25425
+ function parseNotes(text, askedCount, loads2) {
25059
25426
  let parsed;
25060
25427
  try {
25061
25428
  parsed = JSON.parse(text);
@@ -25066,7 +25433,35 @@ function parseSummaries(text, count, loads2) {
25066
25433
  return void 0;
25067
25434
  }
25068
25435
  }
25069
- return notesOf(parsed, count);
25436
+ return notesOf(parsed, askedCount);
25437
+ }
25438
+ function mergeNotes(verbatim, notes) {
25439
+ let next = 0;
25440
+ return verbatim.map((note) => note ?? notes[next++]);
25441
+ }
25442
+
25443
+ // dsh/src/inner-summary.js
25444
+ var SUMMARY_PURPOSE = "inner-compaction";
25445
+ var FILTER_TEXT = "content_filtered";
25446
+ var DISPLAYED_OPTIONS = ["provider", "model", "reasoningEffort", "purpose", "sessionId"];
25447
+ var DISPLAYED_INPUT = ["throughSeq", "headerSeq"];
25448
+ var provided = (source, keys) => Object.fromEntries(keys.filter((key) => source[key] !== void 0).map((key) => [key, source[key]]));
25449
+ function requestDisplayOf(options, input) {
25450
+ const { messages, tools, toolHistory } = options;
25451
+ return {
25452
+ options: provided(options, DISPLAYED_OPTIONS),
25453
+ messages: { count: messages.length - 1, tail: messages.at(-1) },
25454
+ ...provided(input, DISPLAYED_INPUT),
25455
+ ...tools === void 0 ? {} : { tools: { count: tools.length } },
25456
+ ...toolHistory === void 0 ? {} : {
25457
+ toolHistory: { updates: toolHistory.updates.map(({ messageId, additions }) => ({ messageId, additions: additions.map((tool) => tool.name) })) }
25458
+ }
25459
+ };
25460
+ }
25461
+ function slotMessagesOf({ slots, session, events, range }) {
25462
+ const bySeq = new Map(events.map((event) => [event.seq, event]));
25463
+ const selected = new Set(range);
25464
+ return slots.map((slot) => slot.seqs.filter((seq) => selected.has(seq)).map((seq) => session.deriveEventMessage(bySeq.get(seq))).filter((message) => message != null));
25070
25465
  }
25071
25466
  var NO_OBSERVER = Object.freeze({ dispatch() {
25072
25467
  }, chunk() {
@@ -25077,11 +25472,9 @@ async function summarizeSlots({ llm, session, index, events, selection, slots, r
25077
25472
  const chosen = { provider, model, ...reasoningEffort === void 0 ? {} : { reasoningEffort } };
25078
25473
  const tools = session.requestHeader()?.tools;
25079
25474
  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 };
25475
+ const { tailText, verbatim, wholeUserSlots, askedCount } = planSummary(slots.map((slot, at) => slotFactsOf(slot, perSlot[at])), held);
25476
+ const tail = { role: "user", content: [{ type: "text", text: tailText }] };
25477
+ const input = { throughSeq: session.seq - 1, headerSeq: headerSeqIn(index, { latest: true }), tail };
25085
25478
  const options = {
25086
25479
  ...chosen,
25087
25480
  messages: [...session.deriveMessages(), tail],
@@ -25118,7 +25511,7 @@ async function summarizeSlots({ llm, session, index, events, selection, slots, r
25118
25511
  });
25119
25512
  const stream = accumulator.snapshot();
25120
25513
  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 } };
25514
+ const call = callRecordOf({ purpose: SUMMARY_PURPOSE, selection: chosen, input, range, stream, endedAt, carrierCache, thrown });
25122
25515
  if (thrown !== void 0) return { ok: false, reason: `the summary stream threw: ${thrown.message}`, call };
25123
25516
  const finish = kit.lastAssistantStreamChunk(stream, "finish");
25124
25517
  if (finish === void 0) return { ok: false, reason: "the summary stream ended without a finish chunk", call };
@@ -25126,35 +25519,23 @@ async function summarizeSlots({ llm, session, index, events, selection, slots, r
25126
25519
  const detail = finish.reason.failure === void 0 ? "" : `: ${finish.reason.failure.message}`;
25127
25520
  const reason = `the summary stream finished with ${finish.reason.kind}${detail}`;
25128
25521
  const filtered = finish.reason.kind === "error" && String(finish.reason.failure?.message).includes(FILTER_TEXT);
25129
- return { ok: false, ...filtered ? { failure: FILTER_FAILURE } : {}, reason, call };
25522
+ const failure4 = filtered ? FILTER_FAILURE : finish.reason.kind === "tool-calls" ? FORMAT_FAILURE : void 0;
25523
+ return { ok: false, ...failure4 === void 0 ? {} : { failure: failure4 }, reason, call };
25130
25524
  }
25131
- if (blocks.some((block) => block.type === "tool-call")) return { ok: false, reason: "the summary stream made a tool call", call };
25525
+ if (blocks.some((block) => block.type === "tool-call")) return { ok: false, failure: FORMAT_FAILURE, reason: "the summary stream made a tool call", call };
25132
25526
  const text = blocks.filter((block) => block.type === "text").map((block) => block.text).join("");
25133
- const notes = parseSummaries(text, asked.length, kit.loads);
25527
+ const notes = parseNotes(text, askedCount, kit.loads);
25134
25528
  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 };
25529
+ return { ok: false, failure: FORMAT_FAILURE, reason: `the summary text is not a JSON object of ${askedCount} strings keyed "1" to "${askedCount}"`, call };
25136
25530
  }
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 };
25531
+ return { ok: true, summaries: mergeNotes(verbatim, notes), verbatimSeqs: wholeUserSlots.map((at) => slots[at].seqs[0]), call };
25140
25532
  }
25141
25533
 
25142
25534
  // 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
- }
25535
+ var PLUGIN_RECORD_NAMESPACE = "plugin:session-watcher/";
25536
+ var INNER_CALL_RECORD_TYPE = `${PLUGIN_RECORD_NAMESPACE}${CALL_RECORD_NAME}`;
25537
+ var INNER_ATTEMPT_RECORD_TYPE = `${PLUGIN_RECORD_NAMESPACE}${ATTEMPT_RECORD_NAME}`;
25538
+ var INNER_END_RECORD_TYPE = `${PLUGIN_RECORD_NAMESPACE}${END_RECORD_NAME}`;
25158
25539
  var messageOf5 = (error) => error instanceof Error ? error.message : String(error);
25159
25540
  var USAGE_FIELDS = ["inputTokens", "cacheReadTokens", "cacheWriteTokens"];
25160
25541
  function diagnose({ session, recordSeq, call, range, kit }) {
@@ -25166,8 +25547,8 @@ function diagnose({ session, recordSeq, call, range, kit }) {
25166
25547
  writeDiagnostic(session.id, hostDiagnostic("inner_usage_gap", `${at}: the auxiliary call ${what}, so its uncached share is unknown`));
25167
25548
  return;
25168
25549
  }
25169
- const { inputTokens, cacheReadTokens, cacheWriteTokens } = usage;
25170
- const share = (inputTokens + cacheWriteTokens) / (inputTokens + cacheReadTokens + cacheWriteTokens);
25550
+ const canonical = { input: usage.inputTokens, cacheRead: usage.cacheReadTokens, cacheWrite: usage.cacheWriteTokens };
25551
+ const share = uncachedOf(canonical) / stockOf(canonical);
25171
25552
  if (!(share > UNCACHED_SHARE_ALERT)) return;
25172
25553
  const { provider, model, reasoningEffort } = call.selection;
25173
25554
  const selection = `${provider}/${model}${reasoningEffort === void 0 ? "" : ` ${reasoningEffort}`}`;
@@ -25207,27 +25588,20 @@ async function attachmentsOf({ slots, range, events, attachments, signal }) {
25207
25588
  return answer;
25208
25589
  }
25209
25590
  var textOfMessage = (message) => message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
25210
- var jsonOf = (text) => {
25591
+ function answeredOf(args2, result) {
25592
+ if (result === void 0 || result.isError === true) return [];
25593
+ let asked;
25211
25594
  try {
25212
- return JSON.parse(text);
25595
+ asked = JSON.parse(args2)?.questions;
25213
25596
  } catch {
25214
- return void 0;
25597
+ return [];
25215
25598
  }
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 [];
25599
+ if (!Array.isArray(asked)) return [];
25600
+ const answers = askAnswersOf(textOfMessage(result));
25228
25601
  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 }] : [];
25602
+ const answer = typeof item?.id === "string" ? answers.find((each) => each.id === item.id) : void 0;
25603
+ const user = answer === void 0 ? "" : [...answer.selected, ...answer.custom ? [answer.custom] : []].join("\n");
25604
+ return typeof item?.question === "string" && user.trim() !== "" ? [{ question: item.question, user }] : [];
25231
25605
  });
25232
25606
  }
25233
25607
  function questionsOf({ slots, bySeq }) {
@@ -25235,24 +25609,24 @@ function questionsOf({ slots, bySeq }) {
25235
25609
  try {
25236
25610
  const events = seqs.map((seq) => bySeq.get(seq));
25237
25611
  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)));
25612
+ for (const event of events) {
25613
+ if (event.type === "tool/result" && !results.has(event.data.message.toolCallId)) results.set(event.data.message.toolCallId, event);
25614
+ }
25615
+ 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 }) => {
25616
+ const result = results.get(id);
25617
+ if (result === void 0) return [];
25618
+ return answeredOf(args2, result.data.message).map((pair) => ({ ...pair, seqs: [result.seq] }));
25619
+ }));
25240
25620
  } catch {
25241
25621
  return [];
25242
25622
  }
25243
25623
  });
25244
25624
  }
25245
25625
  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
25626
  async function currentOf(held, read, agent, signal) {
25253
25627
  const current = { paths: /* @__PURE__ */ new Map(), skills: held.skills };
25254
25628
  for (const [key, lines] of held.paths) {
25255
- const { read: answer, displayPath } = await read(agent, key, rangesOf(lines), signal);
25629
+ const { read: answer, displayPath } = await read(agent, key, runsOf(lines).map(([first, last]) => ({ offset: first, limit: last - first + 1 })), signal);
25256
25630
  current.paths.set(key, { displayPath, read: answer });
25257
25631
  }
25258
25632
  return current;
@@ -25261,11 +25635,23 @@ function retainedSources(session, range, bySeq) {
25261
25635
  const inside = new Set(range.map((seq) => bySeq.get(seq)).filter(holdsEvidence2).map((event) => event.data.id));
25262
25636
  return session.deriveMessages().filter((each) => each.role === "user" && carriesEvidence(each.source) && !inside.has(each.id)).map((each) => each.source);
25263
25637
  }
25264
- var carriedOf = (earlier, current) => omitShown(carryChanges(foldCarried(earlier), current), earlier);
25265
- function stateAt(session, readState, earlier) {
25638
+ async function gitAhead(readGit, session, signal) {
25639
+ if (readGit === void 0) return void 0;
25640
+ try {
25641
+ const text = await readGit(session, signal);
25642
+ return text === null ? void 0 : () => text;
25643
+ } catch (error) {
25644
+ return () => {
25645
+ throw error;
25646
+ };
25647
+ }
25648
+ }
25649
+ function stateAt(session, readState, earlier, git) {
25266
25650
  try {
25267
25651
  const tools = new Set((session.requestHeader()?.tools ?? []).map(({ name: name3 }) => name3));
25268
- return carryState(readState(session), {
25652
+ const state = readState(session);
25653
+ return carryState({ ...state, items: { ...state.items, [GIT_STATE_ITEM.key]: git } }, {
25654
+ stateItems: CARRIER_TABLE.stateItems,
25269
25655
  tools,
25270
25656
  earlier,
25271
25657
  failed: (item, error) => writeDiagnostic(session.id, hostDiagnostic("inner_state_failed", `${item.key}: ${messageOf5(error)}`))
@@ -25275,14 +25661,25 @@ function stateAt(session, readState, earlier) {
25275
25661
  return null;
25276
25662
  }
25277
25663
  }
25278
- async function quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset }) {
25664
+ function historyReadOf(meter, session) {
25665
+ try {
25666
+ return { tokens: meter.measure(session).totalTokens };
25667
+ } catch (error) {
25668
+ return { error };
25669
+ }
25670
+ }
25671
+ async function quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset, history }) {
25279
25672
  let estimate = null;
25280
25673
  try {
25281
25674
  const ctp = ctpOf(session.id);
25282
25675
  if (ctp === null) throw new Error(`session ${session.id} has no model policy to price its range under`);
25283
25676
  const current = await currentOf(held, readUnobserved2, agent, signal);
25284
25677
  const carried = carriedOf(retainedSources(session, range, bySeq), current);
25285
- estimate = estimateInnerA({ n: stepN, range, messageOf: (seq) => session.deriveEventMessage(bySeq.get(seq)), carried, ctp });
25678
+ const texts = range.flatMap((seq) => {
25679
+ const message = session.deriveEventMessage(bySeq.get(seq));
25680
+ return message === null ? [] : [requestTextOf(message)];
25681
+ });
25682
+ estimate = estimateInnerA({ n: stepN, texts, bText: renderCarried(carried, CARRIER_TABLE), ctp });
25286
25683
  } catch (error) {
25287
25684
  writeDiagnostic(session.id, hostDiagnostic("inner_quote_failed", error));
25288
25685
  }
@@ -25292,20 +25689,20 @@ async function quoteOf({ session, agent, signal, range, stepN, held, bySeq, read
25292
25689
  } catch (error) {
25293
25690
  writeDiagnostic(session.id, hostDiagnostic("inner_quote_failed", error));
25294
25691
  }
25295
- return innerQuote({ n: stepN, estimate, cRatio: ratio, preset });
25692
+ if (history.error !== void 0) writeDiagnostic(session.id, hostDiagnostic("inner_quote_failed", history.error));
25693
+ return innerQuote({ n: stepN, estimate, cRatio: ratio, preset, summaryReadCost: history.tokens });
25296
25694
  }
25297
25695
  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; ; ) {
25696
+ const ladder = createRetryLadder({ selection, fallback });
25697
+ for (; ; ) {
25301
25698
  const attempt = monitor.begin(session, { range, quote });
25302
25699
  let again = false;
25303
25700
  try {
25304
- const summary = await summarizeSlots({ llm, session, index, events, selection: ladder[rung], slots, range, held, signal, kit, observer: attempt, carrier });
25701
+ const summary = await summarizeSlots({ llm, session, index, events, selection: ladder.current(), slots, range, held, signal, kit, observer: attempt, carrier });
25305
25702
  attempt.responded({ endedAt: summary.call.endedAt });
25306
25703
  let recorded = false;
25307
25704
  const settle = () => {
25308
- const call = attempt.startSeq === null ? summary.call : { ...summary.call, attempt: attempt.startSeq };
25705
+ const call = callRecordOf({ ...summary.call, attempt: attempt.startSeq });
25309
25706
  const recordSeq = kit.appendPluginRecord(session, INNER_CALL_RECORD_TYPE, call);
25310
25707
  diagnose({ session, recordSeq, call: summary.call, range, kit });
25311
25708
  recorded = true;
@@ -25328,13 +25725,7 @@ async function requestSummary({ monitor, session, range, quote, llm, index, even
25328
25725
  };
25329
25726
  if (summary.ok) return { attempt, summary, settle, failed: failed2 };
25330
25727
  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
- }
25728
+ again = recorded && ladder.next(summary.failure);
25338
25729
  throw error;
25339
25730
  } catch (error) {
25340
25731
  attempt.failed(error, { cancelled: signal.aborted, cancelReason: signal.reason });
@@ -25343,7 +25734,7 @@ async function requestSummary({ monitor, session, range, quote, llm, index, even
25343
25734
  }
25344
25735
  }
25345
25736
  }
25346
- function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFile, readUnobserved: readUnobserved2, readState, cRatio, ctpOf, llm, attachments, meter, kit, monitor, readSettings, carrier }) {
25737
+ function createInnerSeal({ readMode, eventFacts, readSession, heldView, readFile, readUnobserved: readUnobserved2, readState, readGit, cRatio, ctpOf, llm, attachments, meter, kit, monitor, readSettings, carrier }) {
25347
25738
  const reportedInvalid = /* @__PURE__ */ new Set();
25348
25739
  return async (payload, next) => {
25349
25740
  const { agent, signal, modelSelection } = payload;
@@ -25354,22 +25745,24 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25354
25745
  writeDiagnostic(session.id, hostDiagnostic("inner_mode_invalid", "the inner mode record does not read as a mode, so this session seals nothing"));
25355
25746
  }
25356
25747
  if (mode !== "on") return next();
25357
- const index = sourceFacts(session.id);
25748
+ const index = eventFacts(session.id);
25358
25749
  if (index === null) return next();
25359
25750
  const cheap = innerSource(index, session.surface.nodes);
25360
25751
  if (cheap.paused || cheap.stepN < INNER_QUOTE.minSteps) return next();
25361
25752
  const { preset, fallbackModel } = readSettings();
25362
25753
  const nodes = [...session.surface.nodes];
25754
+ const history = historyReadOf(meter, session);
25363
25755
  const reading = readSession(session.id);
25364
25756
  const { events } = await reading;
25365
- const facts = new Map(events.map((event) => [event.seq, sourceFactOf(event)]));
25757
+ const facts = eventFactsOf(events);
25366
25758
  const { range, stepN, paused } = innerSource(facts, nodes);
25367
25759
  if (paused || stepN < INNER_QUOTE.minSteps) return next();
25368
- const slots = skeletonSlots(events, nodes, range);
25760
+ const slots = skeletonSlots(facts, nodes, range);
25369
25761
  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 });
25762
+ const originals = range.flatMap((seq) => facts.get(seq).originals);
25763
+ const replaced = [...range, ...originals];
25764
+ const held = heldView(session.id, events);
25765
+ const quote = await quoteOf({ session, agent, signal, range, stepN, held, bySeq, readUnobserved: readUnobserved2, ctpOf, cRatio, preset, history });
25373
25766
  if (signal.aborted) throw signal.reason;
25374
25767
  if (quote.trigger === null) return next();
25375
25768
  const { attempt, summary, settle, failed: failed2 } = await requestSummary({
@@ -25383,7 +25776,7 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25383
25776
  selection: modelSelection,
25384
25777
  fallback: fallbackModel,
25385
25778
  slots,
25386
- held: touchedOf(held),
25779
+ held: touchedOf(held, replaced),
25387
25780
  signal,
25388
25781
  kit,
25389
25782
  carrier
@@ -25391,9 +25784,11 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25391
25784
  try {
25392
25785
  let slotAttachments;
25393
25786
  let current;
25787
+ let git;
25394
25788
  try {
25395
25789
  slotAttachments = await attachmentsOf({ slots, range, events, attachments, signal });
25396
25790
  current = await currentOf(held, readFile, agent, signal);
25791
+ git = await gitAhead(readGit, session, signal);
25397
25792
  } catch (error) {
25398
25793
  throw failed2(messageOf5(error));
25399
25794
  }
@@ -25409,21 +25804,16 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25409
25804
  const shadowed = new Set(range);
25410
25805
  try {
25411
25806
  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 });
25807
+ const source = assembleCarrierSource({
25808
+ slots,
25809
+ summaries: summary.summaries,
25810
+ questions: questionsOf({ slots, bySeq }),
25811
+ attachments: slotAttachments,
25812
+ verbatimSeqs: summary.verbatimSeqs,
25813
+ changes: carriedOf(earlier, current),
25814
+ state: stateAt(session, readState, earlier, git)
25815
+ });
25816
+ message = kit.createUserMessage({ content: renderCarrier(source, CARRIER_TABLE), source });
25427
25817
  shadowedTokenCount = meter.measure(session).nodes.filter((node) => shadowed.has(node.seq)).reduce((sum, node) => sum + node.heuristicTokens, 0);
25428
25818
  } catch (error) {
25429
25819
  throw failed2(messageOf5(error));
@@ -25436,7 +25826,7 @@ function createInnerSeal({ readMode, sourceFacts, readSession, heldView, readFil
25436
25826
  });
25437
25827
  session.append("user/message", message, {
25438
25828
  surfaceOp: { op: "replace", startSeq, endSeq },
25439
- sourceEventSeqs: [recordSeq, prune.seq, ...range, ...originals]
25829
+ sourceEventSeqs: sourceEventSeqsOf({ callSeq: recordSeq, pruneSeq: prune.seq, replaced })
25440
25830
  });
25441
25831
  } catch (error) {
25442
25832
  attempt.failed(error, { cancelled: signal.aborted, cancelReason: signal.reason });
@@ -25474,7 +25864,7 @@ function createInnerMonitor({ appendPluginRecord: appendPluginRecord2, publish }
25474
25864
  guard("inner_monitor_start_failed", () => {
25475
25865
  const request = requestDisplayOf(options, input);
25476
25866
  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 });
25867
+ attempt.startSeq = appendPluginRecord2(session, INNER_ATTEMPT_RECORD_TYPE, attemptRecordOf({ range: recorded, request, quote }));
25478
25868
  owner = { sessionId, entry: { attempt: attempt.startSeq, phase: "generating", endedAt: null, request, tools: options.tools, stream } };
25479
25869
  active.add(owner);
25480
25870
  });
@@ -25497,12 +25887,11 @@ function createInnerMonitor({ appendPluginRecord: appendPluginRecord2, publish }
25497
25887
  failed(error, circumstances) {
25498
25888
  if (attempt.startSeq === null) return;
25499
25889
  guard("inner_monitor_end_failed", () => {
25500
- appendPluginRecord2(session, INNER_END_RECORD_TYPE, {
25501
- v: 1,
25890
+ appendPluginRecord2(session, INNER_END_RECORD_TYPE, endRecordOf({
25502
25891
  attempt: attempt.startSeq,
25503
25892
  outcome: circumstances.cancelled ? "cancelled" : "failed",
25504
25893
  reason: reasonOf(error, circumstances)
25505
- });
25894
+ }));
25506
25895
  });
25507
25896
  active.delete(owner);
25508
25897
  changed2();
@@ -25515,7 +25904,7 @@ function createInnerMonitor({ appendPluginRecord: appendPluginRecord2, publish }
25515
25904
  }
25516
25905
 
25517
25906
  // lib/harness/dsh/inner-monitor-source.js
25518
- function blockOf(block) {
25907
+ function blockOf2(block) {
25519
25908
  switch (block?.type) {
25520
25909
  case "text":
25521
25910
  return { type: "text", text: block.text };
@@ -25533,10 +25922,24 @@ function blockOf(block) {
25533
25922
  }
25534
25923
  function sourceEventView(event, { visible }) {
25535
25924
  const message = event.data?.message ?? event.data;
25536
- const blocks = (Array.isArray(message?.content) ? message.content : []).map(blockOf);
25925
+ const blocks = (Array.isArray(message?.content) ? message.content : []).map(blockOf2);
25537
25926
  const shown = event.type === "tool/result" ? [{ type: "tool-result", callId: message?.toolCallId, isError: message?.isError === true, blocks }] : blocks;
25538
25927
  return { seq: event.seq, type: event.type, visible, blocks: shown, raw: event };
25539
25928
  }
25929
+ var SOURCE_CATEGORIES = { "system/message": "system", "developer/message": "developer", "tool/result": "tool", "assistant/message": "assistant" };
25930
+ var HUMAN_SOURCE_KIND = "user";
25931
+ function sourceCategoryOf({ type, kind }) {
25932
+ if (type === "user/message") {
25933
+ if (typeof kind !== "string") return "other";
25934
+ return kind === HUMAN_SOURCE_KIND ? "user" : "injected";
25935
+ }
25936
+ return SOURCE_CATEGORIES[type] ?? "other";
25937
+ }
25938
+ function slotSourceOf(event) {
25939
+ const message = event.data?.message ?? event.data;
25940
+ const source = { type: event.type, kind: message?.source?.kind ?? null };
25941
+ return { ...source, category: sourceCategoryOf(source) };
25942
+ }
25540
25943
  var placeholderOf = ({ type, attachment }) => `[${type}${attachment?.name === void 0 ? "" : ` ${attachment.name}`}]`;
25541
25944
  function callLabel(block) {
25542
25945
  const { groupKey, kind, detail } = dshToolEvidenceProfile.residualIdentity(block.name, parseArguments(block.arguments) ?? {});
@@ -25568,31 +25971,124 @@ function eventDisplayText(event) {
25568
25971
  return textOf3(sourceEventView(event, { visible: true }).blocks, displayCallText);
25569
25972
  }
25570
25973
 
25974
+ // dsh/src/monitor-settlement-recall.js
25975
+ var stepKey2 = ({ turn, step } = {}) => `${turn}:${step}`;
25976
+ var pureRecall = ({ tools, marked }) => marked.size > 0 && tools.every(({ id }) => marked.has(id));
25977
+ function reportPositions(seals, samples, tailCalls) {
25978
+ const positions = /* @__PURE__ */ new Map();
25979
+ let offset = 0;
25980
+ for (const { attempt, range } of seals.values()) {
25981
+ const steps = /* @__PURE__ */ new Map();
25982
+ for (const seq of range) {
25983
+ const sample = samples.get(seq);
25984
+ if (sample?.counted) steps.set(stepKey2(sample.event.data), seq);
25985
+ }
25986
+ const n = attempt.quote?.n ?? 0;
25987
+ if (steps.size === n) for (const seq of steps.values()) positions.set(seq, offset += 1);
25988
+ else offset += n;
25989
+ }
25990
+ const lastCarrier = [...seals.keys()].at(-1);
25991
+ const tail = [...samples.values()].filter(({ event, counted }) => counted && event.seq > lastCarrier);
25992
+ if (tail.length === tailCalls) for (const { event } of tail) positions.set(event.seq, offset += 1);
25993
+ return positions;
25994
+ }
25995
+ function settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls, sessionId, isNoise }) {
25996
+ const seals = new Map(attempts.map((attempt) => {
25997
+ const call = log.get(attempt.call?.seq)?.data;
25998
+ return [attempt.carrier.seq, { attempt, range: isCallRecord(call) ? call.range : [] }];
25999
+ }));
26000
+ if (seals.size === 0) return void 0;
26001
+ const starts = new Set(attempts.map(({ id }) => id));
26002
+ const samples = /* @__PURE__ */ new Map();
26003
+ const before = /* @__PURE__ */ new Map();
26004
+ const active = /* @__PURE__ */ new Map();
26005
+ let ctp;
26006
+ let lastMeasured;
26007
+ let seal;
26008
+ let sample;
26009
+ for (const event of events) {
26010
+ const { seq, type, data } = event;
26011
+ if (starts.has(seq)) before.set(seq, lastMeasured);
26012
+ if (seals.has(seq)) {
26013
+ seal = seals.get(seq);
26014
+ for (const replaced of seal.range) active.delete(replaced);
26015
+ lastMeasured = void 0;
26016
+ }
26017
+ if (isMainCall(event)) {
26018
+ const usage = callUsageOf(data?.usage);
26019
+ if (usage !== null) ctp ??= modelPolicyFor(data?.message?.source?.model).ctp;
26020
+ const resident = [...active.values()].reduce((sum, tokens) => sum + tokens, 0);
26021
+ const content = data?.message?.content;
26022
+ const tools = Array.isArray(content) ? content.filter((block) => block?.type === "tool-call") : [];
26023
+ sample = { event, counted: eventFactOf(event).step !== null, usage, resident, seal: seal?.attempt, tools, marked: /* @__PURE__ */ new Set() };
26024
+ if (!isNoise(event)) lastMeasured = usage === null ? void 0 : sample;
26025
+ samples.set(seq, sample);
26026
+ }
26027
+ if (seal === void 0 || sample === void 0) continue;
26028
+ if (type === "tool/call" && stepKey2(data) === stepKey2(sample.event.data) && sample.tools.some(({ id }) => id === data.callId)) {
26029
+ const target = eventReadTargetOf(data);
26030
+ if (target && (target.sessionId === void 0 || target.sessionId === sessionId) && target.seq >= events[0].seq && target.seq < sample.event.seq && log.has(target.seq)) sample.marked.add(data.callId);
26031
+ }
26032
+ if (type === "tool/result") {
26033
+ const op = event.surfaceOp;
26034
+ const replaced = op?.op === "replace" && op.startSeq === op.endSeq && active.delete(op.startSeq);
26035
+ const returned = op === "append" && data.message?.isError !== true && stepKey2(data) === stepKey2(sample.event.data) && sample.marked.has(data.message?.toolCallId);
26036
+ if (!replaced && !returned) continue;
26037
+ const content = data.message?.content;
26038
+ const text = Array.isArray(content) ? content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("") : "";
26039
+ const tokens = charsToTokens(text, ctp ?? modelPolicyFor().ctp);
26040
+ if (tokens > 0) active.set(seq, tokens);
26041
+ }
26042
+ }
26043
+ const cuts = attempts.flatMap(({ id }) => {
26044
+ const pre = before.get(id);
26045
+ const output = pre && pureRecall(pre) ? pre.usage.output : 0;
26046
+ const tokens = (pre?.resident ?? 0) + output - (samples.get(postByAttempt.get(id))?.resident ?? 0);
26047
+ return tokens === 0 ? [] : [{ id, tokens }];
26048
+ });
26049
+ const steps = [];
26050
+ let partial = false;
26051
+ const positions = reportPositions(seals, samples, tailCalls);
26052
+ for (const sample2 of samples.values()) {
26053
+ const { event, counted, usage, resident, seal: parent } = sample2;
26054
+ const pure = pureRecall(sample2);
26055
+ if (!counted || !pure && resident === 0) continue;
26056
+ const { seq } = event;
26057
+ const at = positions.get(seq);
26058
+ if (at === void 0) {
26059
+ partial = true;
26060
+ continue;
26061
+ }
26062
+ if (pure) {
26063
+ const ratio = parent?.quote?.cRatio ?? null;
26064
+ const post = postByAttempt.get(parent?.id) === seq ? parent.id : void 0;
26065
+ steps.push({ at, seq, usage, ratio, ...post === void 0 ? {} : { post } });
26066
+ } else {
26067
+ steps.push({ at, seq, resident });
26068
+ }
26069
+ }
26070
+ return steps.length === 0 && cuts.length === 0 && !partial ? void 0 : { steps, cuts, ...partial ? { partial } : {} };
26071
+ }
26072
+
25571
26073
  // dsh/src/inner-monitor-read.js
25572
26074
  var MONITOR_PROJECTION_KEY = "session-watcher/inner-monitor";
25573
26075
  var PREVIEW_SOURCE_CHARS = 500;
25574
26076
  var RECORD_TYPES = [INNER_ATTEMPT_RECORD_TYPE, INNER_CALL_RECORD_TYPE, INNER_END_RECORD_TYPE];
25575
26077
  var USAGE_FIELDS2 = ["input", "output", "cacheRead", "cacheWrite"];
25576
26078
  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";
26079
+ var isCarrier2 = (event) => eventFactOf(event).marker === "carrier";
25579
26080
  var firstTextOf = (message) => Array.isArray(message?.content) ? message.content.find((block) => block?.type === "text")?.text : void 0;
25580
26081
  var isHandoffPayload = (event) => isUserMessage(event) && isLoadPayload(event.data?.source);
25581
26082
  var isHandoffReads = (event) => isUserMessage(event) && event.data?.source?.kind === LOAD_MESSAGE_KIND && !isLoadPayload(event.data.source) && loadCallsOf(event.data) !== null;
25582
26083
  var isHandoffFollowUp = (event) => isUserMessage(event) && loadedTokenOf(firstTextOf(event.data)) !== null;
25583
- var isCheckpoint = (event) => isUserMessage(event) && event.data?.source?.kind === CHECKPOINT_KIND;
26084
+ var isCheckpoint = (event) => eventFactOf(event).marker === "checkpoint";
25584
26085
  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);
26086
+ var isObject8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
26087
+ var isSeq5 = (value) => Number.isSafeInteger(value) && value >= 0;
26088
+ var isText5 = (value) => typeof value === "string";
26089
+ var isMessage = (value) => isObject8(value) && Array.isArray(value.content);
26090
+ var orNull2 = (holds) => (value) => value === null || holds(value);
26091
+ var isCarrierShape = (event) => Array.isArray(event.sourceEventSeqs) && isSeq5(callSeqOf(event.sourceEventSeqs)) && Array.isArray(event.data.source.slots);
25596
26092
  var bounded = (text) => text.length > PREVIEW_SOURCE_CHARS ? text.slice(0, PREVIEW_SOURCE_CHARS) : text;
25597
26093
  var messageTextOf = (message) => bounded(message.content.filter((block) => block.type === "text").map((block) => block.text).join(""));
25598
26094
  function responseTextOf(stream, kit) {
@@ -25611,7 +26107,7 @@ function displayOf(text) {
25611
26107
  }
25612
26108
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return text;
25613
26109
  const values = Object.values(parsed);
25614
- return values.every(isText2) ? values.join("\n") : text;
26110
+ return values.every(isText5) ? values.join("\n") : text;
25615
26111
  }
25616
26112
  function streamSummaryOf(stream, kit) {
25617
26113
  const text = responseTextOf(stream, kit);
@@ -25623,78 +26119,127 @@ function streamSummaryOf(stream, kit) {
25623
26119
  };
25624
26120
  }
25625
26121
  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;
26122
+ var contextOfUsage = (usage) => usage === null ? null : stockOf(usage) + usage.output;
26123
+ var beforeOf = ({ lastMainUsage }) => contextOfUsage(lastMainUsage);
26124
+ var isSettlementNoise = ({ data }) => data?.interrupted === true && data.usage === void 0;
25629
26125
  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;
26126
+ var callsAfter = (calls, event) => eventFactOf(event).step === null ? calls : calls + 1;
25631
26127
  function foldMainCall(state, event) {
25632
26128
  const { seq, data } = event;
25633
26129
  const usage = callUsageOf(data?.usage);
25634
- const next = { ...state, lastMainUsage: usage, openSteps: stepsAfter(state.openSteps, event) };
26130
+ const next = {
26131
+ ...state,
26132
+ lastMainUsage: usage,
26133
+ openCalls: callsAfter(state.openCalls, event),
26134
+ settlementBefore: isSettlementNoise(event) ? state.settlementBefore : contextOfUsage(usage)
26135
+ };
25635
26136
  const last = state.handoffs.at(-1);
25636
26137
  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) } });
26138
+ return amendedLast(next, { after: { seq, stock: usage === null ? null : stockOf(usage), miss: usage === null ? null : uncachedOf(usage) } });
25638
26139
  }
25639
26140
  function afterOf({ carriers }, attempt) {
25640
26141
  if (attempt.carrier === null) return null;
25641
26142
  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) };
26143
+ return post === null ? null : { seq: post.seq, stock: post.usage === null ? null : stockOf(post.usage), miss: post.usage === null ? null : uncachedOf(post.usage) };
25643
26144
  }
25644
26145
  var withAfter = (state, attempt) => ({ ...attempt, after: afterOf(state.source, attempt) });
25645
26146
  function foldStart(state, { seq, time, data }) {
25646
- if (!isStartData(data)) return state;
26147
+ if (!isAttemptRecord(data)) return state;
26148
+ const { tail } = data.request.messages;
26149
+ if (!isMessage(tail)) return state;
25647
26150
  const { first, last, count } = data.range;
26151
+ const before = beforeOf(state);
25648
26152
  const attempt = {
25649
26153
  id: seq,
25650
26154
  startedAt: time,
25651
26155
  range: { first, last, count },
25652
- input: messageTextOf(data.request.messages.tail),
26156
+ input: messageTextOf(tail),
25653
26157
  call: null,
25654
26158
  end: null,
25655
26159
  carrier: null,
25656
- before: beforeOf(state),
25657
- quote: isQuote(data.quote) ? data.quote : null,
25658
- epoch: state.source.epoch
26160
+ before,
26161
+ quote: attemptQuoteOf(data),
26162
+ epoch: state.source.epoch,
26163
+ ...before === null && state.settlementBefore !== null ? { estimatedBefore: state.settlementBefore } : {}
25659
26164
  };
25660
26165
  return { ...state, attempts: [...state.attempts, attempt] };
25661
26166
  }
25662
26167
  function foldCall(state, { seq, data }, kit) {
25663
- if (!isCallData(data)) return state;
26168
+ if (!isCallRecord(data)) return state;
25664
26169
  const call = {
25665
26170
  seq,
25666
26171
  endedAt: Number.isFinite(data.endedAt) ? data.endedAt : null,
25667
26172
  thrown: data.thrown === void 0 ? null : bounded(data.thrown.message),
25668
26173
  ...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) } : {}
25671
- };
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
26174
+ // 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.
26175
+ ...isCarrierCache(data.carrierCache) ? { carrierCache: evidenceCopy(data.carrierCache) } : {}
25685
26176
  };
25686
- return { ...state, attempts: [...state.attempts, legacy] };
26177
+ return amended(state, state.attempts.findIndex((each) => each.id === data.attempt), { call });
25687
26178
  }
25688
26179
  function foldEnd(state, { seq, time, data }) {
25689
- if (!isEndData(data)) return state;
26180
+ if (!isEndRecord(data)) return state;
25690
26181
  const end = { seq, time, outcome: data.outcome, reason: bounded(data.reason) };
25691
26182
  return amended(state, state.attempts.findIndex((each) => each.id === data.attempt), { end });
25692
26183
  }
25693
26184
  function foldCarrier(state, event) {
25694
- const sealed = { ...state, openSteps: 0 };
26185
+ const sealed = { ...state, openCalls: 0, settlementBefore: null, postSeal: null };
25695
26186
  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 });
26187
+ const { slots, verbatimSeqs } = event.data.source;
26188
+ if (event.surfaceOp?.op === "replace" && Array.isArray(verbatimSeqs)) {
26189
+ sealed.verbatimSeqs = [...state.verbatimSeqs, ...verbatimSeqs.filter(isSeq5)];
26190
+ }
26191
+ const at = sealed.attempts.findIndex((each) => each.call?.seq === callSeqOf(event.sourceEventSeqs));
26192
+ if (at < 0) return sealed;
26193
+ const carrier = { seq: event.seq, time: event.time, slots: slots.length };
26194
+ const slotWarnings = {};
26195
+ const pending = state.postSeal?.pending;
26196
+ if (pending !== void 0) {
26197
+ for (const slot of slots) {
26198
+ const seqs = slot?.seqs;
26199
+ if (!Array.isArray(seqs) || seqs.length === 0 || !seqs.every(isSeq5)) continue;
26200
+ const warnings = new Set(seqs.flatMap((seq) => pending[seq] ?? []));
26201
+ if (warnings.size > 0) slotWarnings[seqs[0]] = [...warnings];
26202
+ }
26203
+ }
26204
+ return amended({ ...sealed, postSeal: { first: true, request: null, pending: {} } }, at, {
26205
+ carrier,
26206
+ ...Object.keys(slotWarnings).length > 0 && { slotWarnings }
26207
+ });
26208
+ }
26209
+ function foldPostSealRequest(state, event) {
26210
+ const { postSeal } = state;
26211
+ if (postSeal === null) return state;
26212
+ const { turn, step, message } = event.data ?? {};
26213
+ const count = Array.isArray(message?.content) ? message.content.filter((block) => block?.type === "tool-call").length : 0;
26214
+ const request = isMainCall(event) && isSeq5(turn) && isSeq5(step) && count > 0 ? { seq: event.seq, turn, step, count, first: postSeal.first } : null;
26215
+ if (!postSeal.first && request === null && postSeal.request === null) return state;
26216
+ return { ...state, postSeal: { ...postSeal, first: false, request } };
26217
+ }
26218
+ function recallWarningOf(state, call) {
26219
+ const target = eventReadTargetOf(call.data);
26220
+ if (target === void 0 || target.sessionId !== void 0 && target.sessionId !== state.sessionId || target.seq >= call.seq) return;
26221
+ if (state.handoffs.some((handoff) => handoff.id === target.seq)) return "handoff-recall";
26222
+ if (state.source.carriers.some((carrier) => carrier.seq === target.seq)) return "carrier-recall";
26223
+ if (state.verbatimSeqs.includes(target.seq)) return "verbatim-recall";
26224
+ }
26225
+ function heldInContext(state, seq) {
26226
+ const { epoch } = state.source;
26227
+ 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));
26228
+ }
26229
+ function stateWarningOf(request, call) {
26230
+ if (!request.first) return;
26231
+ const operation = stateOperationOf(call);
26232
+ if (operation !== void 0) return operation === "write" ? "state-write" : request.count === 1 ? "state-check" : "state-mixed";
26233
+ }
26234
+ function foldToolCall(state, event) {
26235
+ const { postSeal } = state;
26236
+ const request = postSeal?.request;
26237
+ if (!request || request.turn !== event.data?.turn || request.step !== event.data?.step) return state;
26238
+ const warning = recallWarningOf(state, event) ?? stateWarningOf(request, event.data);
26239
+ if (warning === void 0) return state;
26240
+ const warnings = postSeal.pending[request.seq] ?? [];
26241
+ if (warnings.includes(warning)) return state;
26242
+ return { ...state, postSeal: { ...postSeal, pending: { ...postSeal.pending, [request.seq]: [...warnings, warning] } } };
25698
26243
  }
25699
26244
  function payloadOf(message) {
25700
26245
  let payload;
@@ -25703,12 +26248,12 @@ function payloadOf(message) {
25703
26248
  } catch {
25704
26249
  return null;
25705
26250
  }
25706
- return isObject4(payload) && isText2(payload.load_token) ? payload : null;
26251
+ return isObject8(payload) && isText5(payload.load_token) ? payload : null;
25707
26252
  }
25708
26253
  var LABEL_POSITION = /^S(\d+)(?:-S(\d+))?$/;
25709
26254
  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);
26255
+ const match = isText5(entry?.label) ? LABEL_POSITION.exec(entry.label) : null;
26256
+ return match === null ? [] : [Number(match[2] ?? match[1])].filter(isSeq5);
25712
26257
  };
25713
26258
  function lineageNumberOf(lineage) {
25714
26259
  const positions = Array.isArray(lineage) ? lineage.flatMap(positionOf2) : [];
@@ -25723,7 +26268,7 @@ function foldPayload(state, { seq, time, data }) {
25723
26268
  time,
25724
26269
  type,
25725
26270
  token: payload.load_token,
25726
- handoffId: isSeq(payload.handoff_id) ? payload.handoff_id : null,
26271
+ handoffId: isSeq5(payload.handoff_id) ? payload.handoff_id : null,
25727
26272
  createdAt: Number.isFinite(payload.created_at) ? payload.created_at : null,
25728
26273
  epoch: state.source.epoch,
25729
26274
  kept: Array.isArray(payload.paths_to_keep) ? payload.paths_to_keep.length : null,
@@ -25734,7 +26279,7 @@ function foldPayload(state, { seq, time, data }) {
25734
26279
  followSeq: null,
25735
26280
  before: type === "continue" ? beforeOf(state) : null,
25736
26281
  after: null,
25737
- tailSteps: type === "continue" ? state.lastCheckpointSteps : null
26282
+ tailCalls: type === "continue" ? state.lastCheckpointCalls : null
25738
26283
  };
25739
26284
  return { ...state, handoffs: [...state.handoffs, handoff] };
25740
26285
  }
@@ -25749,27 +26294,31 @@ function foldFollowUp(state, { seq, data }) {
25749
26294
  return amendedLast(state, { followSeq: seq });
25750
26295
  }
25751
26296
  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);
26297
+ return { ...state, lastCheckpointToken: checkpointTokenOf(firstTextOf(data)), lastCheckpointCalls: state.openCalls, openCalls: 0 };
26298
+ }
26299
+ var isRange = (value) => isObject8(value) && isSeq5(value.first) && isSeq5(value.last) && isSeq5(value.count);
26300
+ var isUsageState = (value) => isObject8(value) && USAGE_FIELDS2.every((field) => Number.isFinite(value[field]));
26301
+ 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));
26302
+ var isEndState = (value) => isObject8(value) && isSeq5(value.seq) && Number.isFinite(value.time) && (value.outcome === "failed" || value.outcome === "cancelled") && isText5(value.reason);
26303
+ var isCarrierState = (value) => isObject8(value) && isSeq5(value.seq) && Number.isFinite(value.time) && isSeq5(value.slots);
26304
+ var isAfterState = (value) => isObject8(value) && isSeq5(value.seq) && orNull2(Number.isFinite)(value.stock) && orNull2(Number.isFinite)(value.miss);
26305
+ 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);
26306
+ 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));
26307
+ 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));
26308
+ var isPostSealRequest = orNull2((value) => isObject8(value) && isSeq5(value.seq) && isSeq5(value.turn) && isSeq5(value.step) && isSeq5(value.count) && typeof value.first === "boolean");
26309
+ var isPostSeal = orNull2((value) => isObject8(value) && typeof value.first === "boolean" && isPostSealRequest(value.request) && isWarningsBySeq(value.pending));
25762
26310
  var stateSchema2 = {
25763
26311
  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");
26312
+ 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)) {
26313
+ throw new Error("invalid inner monitor state");
25766
26314
  }
25767
26315
  return value;
25768
26316
  }
25769
26317
  };
25770
26318
  function innerMonitorProjection(kit) {
25771
26319
  const fold = (state, event) => {
25772
- if (isMainCall2(event)) return foldMainCall(state, event);
26320
+ if (isMainCall(event)) return foldMainCall(foldPostSealRequest(state, event), event);
26321
+ if (event.type === "assistant/attempt") return foldPostSealRequest(state, event);
25773
26322
  if (isCarrier2(event)) return foldCarrier(state, event);
25774
26323
  if (isHandoffPayload(event)) return foldPayload(state, event);
25775
26324
  if (isHandoffReads(event)) return foldReads(state, event);
@@ -25789,15 +26338,17 @@ function innerMonitorProjection(kit) {
25789
26338
  };
25790
26339
  return {
25791
26340
  key: MONITOR_PROJECTION_KEY,
25792
- stateVersion: 10,
26341
+ stateVersion: 16,
25793
26342
  stateSchema: stateSchema2,
25794
- init: () => ({ attempts: [], lastMainUsage: null, source: initialSourceFacts(), handoffs: [], lastCheckpointToken: null, lastCheckpointSteps: 0, openSteps: 0 }),
26343
+ init: (header) => ({ attempts: [], lastMainUsage: null, settlementBefore: null, source: initialSourceFacts(), handoffs: [], lastCheckpointToken: null, lastCheckpointCalls: 0, openCalls: 0, postSeal: null, verbatimSeqs: [], sessionId: header?.id ?? null }),
25795
26344
  apply(state, event) {
25796
- if (!isSeq(event.seq) || !Number.isFinite(event.time)) return state;
26345
+ if (!isSeq5(event.seq) || !Number.isFinite(event.time)) return state;
25797
26346
  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 };
26347
+ if (event.type === "tool/call") return foldToolCall(state, event);
26348
+ const source = foldSourceFacts(state.source, foldInputOf(event));
26349
+ const folded = isMonitorInput(event) || isMainCall(event) || event.type === "assistant/attempt" || isCheckpoint(event) ? fold(state, event) : state;
26350
+ if (source === state.source) return folded;
26351
+ return source.epoch === state.source.epoch ? { ...folded, source } : { ...folded, source, settlementBefore: null, postSeal: null, verbatimSeqs: [] };
25801
26352
  } catch {
25802
26353
  return state;
25803
26354
  }
@@ -25843,7 +26394,6 @@ function rowOf2(attempt, entry, kit) {
25843
26394
  id: attempt.id,
25844
26395
  revision: Math.max(attempt.id, attempt.call?.seq ?? 0, attempt.end?.seq ?? 0, attempt.carrier?.seq ?? 0, attempt.after?.seq ?? 0),
25845
26396
  status: attempt.carrier !== null ? "committed" : attempt.end?.outcome ?? entry?.phase ?? "unknown",
25846
- legacy: attempt.startedAt === null,
25847
26397
  startedAt: attempt.startedAt,
25848
26398
  endedAt: (attempt.carrier ?? attempt.end)?.time ?? null,
25849
26399
  range: { ...attempt.range },
@@ -25858,7 +26408,12 @@ function rowOf2(attempt, entry, kit) {
25858
26408
  };
25859
26409
  }
25860
26410
  function rowsOf2(state, live2, kit) {
25861
- return state.attempts.map((attempt) => rowOf2(withAfter(state, attempt), live2.find((entry) => entry.attempt === attempt.id), kit));
26411
+ return state.attempts.map((attempt) => {
26412
+ const row = rowOf2(withAfter(state, attempt), live2.find((entry) => entry.attempt === attempt.id), kit);
26413
+ if (row.status === "committed" && attempt.estimatedBefore !== void 0) row.estimatedBefore = attempt.estimatedBefore;
26414
+ if (attempt.slotWarnings !== void 0) row.slotWarnings = Object.fromEntries(Object.entries(attempt.slotWarnings).map(([key, warnings]) => [key, [...warnings]]));
26415
+ return row;
26416
+ });
25862
26417
  }
25863
26418
  function handoffRowOf(handoff, nextTaskOf) {
25864
26419
  const nextTask = handoff.handoffId === null ? null : nextTaskOf(handoff.handoffId);
@@ -25875,8 +26430,8 @@ function handoffRowOf(handoff, nextTaskOf) {
25875
26430
  skills: handoff.skills,
25876
26431
  lineage: handoff.lineage,
25877
26432
  contextChange: handoff.type === "continue" ? contextChangeOf(handoff) : null,
25878
- tailSteps: handoff.tailSteps,
25879
- nextTask: isText2(nextTask) ? bounded(nextTask) : null
26433
+ tailCalls: handoff.tailCalls,
26434
+ nextTask: isText5(nextTask) ? bounded(nextTask) : null
25880
26435
  };
25881
26436
  }
25882
26437
  function handoffRowsOf(state, nextTaskOf) {
@@ -25898,21 +26453,14 @@ function recordOf(log, seq, type, kit) {
25898
26453
  if (record?.type !== type) throw new Error(`the session log holds no ${type} record at seq ${seq}`);
25899
26454
  return record.data;
25900
26455
  }
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}` };
26456
+ function definitionsOf(log, headerSeq) {
26457
+ if (!isSeq5(headerSeq)) return { definitions: null, reason: "the request names no request header" };
26458
+ const event = log.get(headerSeq);
26459
+ if (event?.type !== "request/header") return { definitions: null, reason: `the log holds no request header at seq ${headerSeq}` };
25905
26460
  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` };
26461
+ return Array.isArray(tools) ? { definitions: tools } : { definitions: null, reason: `the request header at seq ${headerSeq} defines no tools` };
25907
26462
  }
25908
26463
  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
26464
  var detailRowOf = ({ call: { outputDisplay, ...call }, ...row }) => ({ ...row, call });
25917
26465
  var wholeRow = (row, end, call) => detailRowOf({
25918
26466
  ...row,
@@ -25935,8 +26483,8 @@ function usageOfStream(stream, kit) {
25935
26483
  const chunk = kit.lastAssistantStreamChunk(stream, "usage") ?? null;
25936
26484
  return { folded: callUsageOf(chunk?.usage), raw: chunk };
25937
26485
  }
25938
- var idsOf = (attempt, row) => ({
25939
- start: row.legacy ? null : attempt.id,
26486
+ var idsOf = (attempt) => ({
26487
+ start: attempt.id,
25940
26488
  call: attempt.call?.seq ?? null,
25941
26489
  end: attempt.end?.seq ?? null,
25942
26490
  carrier: attempt.carrier?.seq ?? null
@@ -25948,7 +26496,7 @@ function liveCall(attempt, entry, kit) {
25948
26496
  const row = rowOf2(attempt, { ...entry, stream: () => stream }, kit);
25949
26497
  return {
25950
26498
  row: detailRowOf(row),
25951
- ids: idsOf(attempt, row),
26499
+ ids: idsOf(attempt),
25952
26500
  request: requestOf(entry.request, () => ({ definitions: entry.tools })),
25953
26501
  response: responseOf(stream, kit, true),
25954
26502
  usage: usageOfStream(stream, kit),
@@ -25959,14 +26507,14 @@ function liveCall(attempt, entry, kit) {
25959
26507
  }
25960
26508
  function recordedCall(attempt, log, kit) {
25961
26509
  const row = rowOf2(attempt, void 0, kit);
25962
- const start2 = row.legacy ? null : recordOf(log, attempt.id, INNER_ATTEMPT_RECORD_TYPE, kit);
26510
+ const start2 = recordOf(log, attempt.id, INNER_ATTEMPT_RECORD_TYPE, kit);
25963
26511
  const call = attempt.call === null ? null : recordOf(log, attempt.call.seq, INNER_CALL_RECORD_TYPE, kit);
25964
26512
  const end = row.reason === null ? null : recordOf(log, attempt.end.seq, INNER_END_RECORD_TYPE, kit);
25965
- const ids = idsOf(attempt, row);
26513
+ const ids = idsOf(attempt);
25966
26514
  return {
25967
26515
  row: wholeRow(row, end, call),
25968
26516
  ids,
25969
- request: start2 === null ? partialRequestOf(call) : requestOf(start2.request, () => definitionsOf(log, start2.request.headerSeq)),
26517
+ request: requestOf(start2.request, () => definitionsOf(log, start2.request.headerSeq)),
25970
26518
  response: call === null ? null : responseOf(call.stream, kit, false),
25971
26519
  usage: call === null ? null : usageOfStream(call.stream, kit),
25972
26520
  timing: timingOf(row),
@@ -25976,7 +26524,7 @@ function recordedCall(attempt, log, kit) {
25976
26524
  }
25977
26525
  function carriedDetailOf(source) {
25978
26526
  const evidence = carriedEvidence(source);
25979
- return evidence === null ? null : { text: renderCarried(source), note: CARRIER_WORDING.carried, ...evidence };
26527
+ return evidence === null ? null : { text: renderCarried(source, CARRIER_TABLE), note: carriedNote(CARRIER_TABLE), ...evidence };
25980
26528
  }
25981
26529
  function carrierAt(log, seq) {
25982
26530
  const carrier = log.get(seq);
@@ -25989,9 +26537,8 @@ function committedOf(attempt, log, kit) {
25989
26537
  }
25990
26538
  function placeOf(slot, log) {
25991
26539
  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 };
26540
+ const step = events.map((event) => eventFactOf(event).step).find((counted) => counted !== null) ?? null;
26541
+ return { key: slot.seqs[0], seqs: slot.seqs, turn: step?.turn ?? null, step: step?.step ?? null, source: slotSourceOf(events[0]), events };
25995
26542
  }
25996
26543
  var NOT_COMMITTED = Object.freeze({ kind: "not_committed" });
25997
26544
  function handoffOf(state, id) {
@@ -25999,17 +26546,49 @@ function handoffOf(state, id) {
25999
26546
  if (handoff === void 0) throw new Error(`the inner monitor holds no handoff ${id}`);
26000
26547
  return handoff;
26001
26548
  }
26549
+ function clearingOf(state, id) {
26550
+ const handoff = handoffOf(state, id);
26551
+ if (handoff.type !== "continue") throw new Error(`the handoff ${id} is no /sw-continue clear`);
26552
+ return handoff;
26553
+ }
26554
+ function settlementEvidenceOf(state, log, sessionId, segment, tailCalls) {
26555
+ const attempts = state.attempts.filter((attempt) => attempt.epoch === segment && attempt.carrier !== null);
26556
+ const postByAttempt = new Map(attempts.map((attempt) => [attempt.id, afterOf(state.source, attempt)?.seq]));
26557
+ const posts = new Set(postByAttempt.values());
26558
+ const calls = [];
26559
+ const events = [];
26560
+ let epoch = 0;
26561
+ let pendingPost = false;
26562
+ let countedTail = 0;
26563
+ const lastCarrier = attempts.at(-1)?.carrier.seq ?? -1;
26564
+ for (const event of log.values()) {
26565
+ if (startsEpoch(foldInputOf(event))) epoch += 1;
26566
+ if (epoch > segment) break;
26567
+ if (epoch !== segment) continue;
26568
+ events.push(event);
26569
+ if (isCarrier2(event)) pendingPost = false;
26570
+ if (!isMainCall(event)) continue;
26571
+ if (tailCalls === void 0 && event.seq > lastCarrier) countedTail = callsAfter(countedTail, event);
26572
+ pendingPost ||= posts.has(event.seq);
26573
+ if (isSettlementNoise(event)) continue;
26574
+ const usage = callUsageOf(event.data?.usage);
26575
+ calls.push({ seq: event.seq, stock: usage === null ? null : stockOf(usage), post: pendingPost });
26576
+ pendingPost = false;
26577
+ }
26578
+ const recall = settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls: tailCalls ?? countedTail, sessionId, isNoise: isSettlementNoise });
26579
+ return { calls, ...recall === void 0 ? {} : { recall }, ...tailCalls === void 0 ? { tailCalls: countedTail } : {} };
26580
+ }
26002
26581
  function filesOf(message) {
26582
+ if (carriesEvidence(message.source)) return (carriedEvidence(message.source)?.files ?? []).map(({ path: path3, total, state, runs }) => ({ path: path3, total: state === "empty" ? 0 : total, runs }));
26003
26583
  return loadCallsOf(message).filter((call) => call.name === "read").map((call) => {
26004
26584
  const { file_path: path3 } = JSON.parse(call.arguments);
26005
26585
  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 ?? [] };
26586
+ return { path: path3, total: null, runs: [] };
26008
26587
  });
26009
26588
  }
26010
26589
  function followUpAt(log, seq) {
26011
26590
  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}`);
26591
+ if (!isText5(text)) throw new Error(`the session log holds no follow-up text at seq ${seq}`);
26013
26592
  return text;
26014
26593
  }
26015
26594
  function handoffDetailOf(handoff, row, log) {
@@ -26021,7 +26600,7 @@ function handoffDetailOf(handoff, row, log) {
26021
26600
  if (loadCallsOf(reads) === null) throw new Error(`the session log holds no load read message at seq ${handoff.readSeq}`);
26022
26601
  files = filesOf(reads);
26023
26602
  }
26024
- const turnPage = isText2(payload.turn_page) ? payload.turn_page : null;
26603
+ const turnPage = isText5(payload.turn_page) ? payload.turn_page : null;
26025
26604
  return {
26026
26605
  row,
26027
26606
  summary: payload.summary,
@@ -26052,6 +26631,20 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26052
26631
  const handoff = handoffOf(facts.state, id);
26053
26632
  return handoffDetailOf(handoff, handoffRowOf(handoff, nextTaskOf), await facts.log());
26054
26633
  },
26634
+ async settlement(sessionId, id) {
26635
+ const facts = await factsOf(sessionId);
26636
+ if (facts === void 0) return void 0;
26637
+ const handoff = clearingOf(facts.state, id);
26638
+ return settlementEvidenceOf(facts.state, await facts.log(), sessionId, handoff.epoch - 1, handoff.tailCalls);
26639
+ },
26640
+ async currentSettlement(sessionId) {
26641
+ const snapshot = await readStored(sessionId);
26642
+ if (snapshot === void 0) return void 0;
26643
+ const { state } = snapshot;
26644
+ const segment = state.source.epoch;
26645
+ const attempts = rowsOf2({ ...state, attempts: state.attempts.filter((attempt) => attempt.epoch === segment) }, [], kit).map(({ id, status, epoch, contextChange, estimatedBefore, call, stepN, cRatio }) => ({ id, status, epoch, contextChange, estimatedBefore, call: { usage: call.usage }, stepN, cRatio }));
26646
+ return { epoch: segment + 1, attempts, ...settlementEvidenceOf(state, logOf(snapshot), sessionId, segment) };
26647
+ },
26055
26648
  async call(sessionId, id) {
26056
26649
  const facts = await factsOf(sessionId);
26057
26650
  if (facts === void 0) return void 0;
@@ -26095,7 +26688,7 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26095
26688
  var HOST_INJECT = ["sessions", "sessionQuery", "tools", "skills", "llm"];
26096
26689
  var INNER_INJECT = ["sessionProjections", "agents", "fs", "attachments", "tokenMeter"];
26097
26690
  var SESSION_NOT_FOUND = "SESSION_QUERY_SESSION_NOT_FOUND";
26098
- function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, commandKit, innerKit, readSettings, carrierInstallTarget }) {
26691
+ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, commandKit, queryKit, innerKit, readSettings, carrierInstallTarget }) {
26099
26692
  initStore(storePath);
26100
26693
  ctx.effect(() => () => {
26101
26694
  try {
@@ -26151,8 +26744,9 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26151
26744
  if (record !== null) table.ensure({ id: record.header.id, header: record.header });
26152
26745
  return record;
26153
26746
  };
26154
- const carrierEvidence = createCarrierEvidence({ responsesBreakpoint: () => readSettings?.().carrierResponsesBreakpoint === true });
26747
+ const carrierEvidence = createCarrierEvidence();
26155
26748
  ctx.provide(CARRIER_EVIDENCE_SERVICE, carrierEvidence.service);
26749
+ ctx.provide(CARRIER_SETTINGS_SERVICE, { responsesBreakpoint: () => readSettings?.().carrierResponsesBreakpoint === true });
26156
26750
  const hub = createSignalHub();
26157
26751
  table.onChange((sessionId) => hub.publish(sessionId));
26158
26752
  ctx.on("agent/pre-step", createEpochModelName({
@@ -26181,6 +26775,17 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26181
26775
  ctx.on("session/disposed", (session) => guarded(session.id, () => table.dispose(session.id)));
26182
26776
  const sessionTitle = () => ctx.get("sessionTitle");
26183
26777
  for (const definition of createTools({ defineTool: defineTool2, table, store: getStore(), resolvePersisted })) ctx.tools.register(definition);
26778
+ let heldOf = null;
26779
+ if (queryKit !== void 0) {
26780
+ ctx.tools.register(createEventReadTool({ defineTool: defineTool2, ctx, ...queryKit, heldInContext: (sessionId, seq) => heldOf?.(sessionId, seq) === true }));
26781
+ ctx.inject(["systemPrompt"], (child) => {
26782
+ child.systemPrompt.section({
26783
+ name: `tool:${EVENT_READ_TOOL}`,
26784
+ order: child.systemPrompt.getSectionOrder("TOOL_SESSION_QUERY"),
26785
+ text: ({ scope, toolSet }) => ctx.tools.get(EVENT_READ_TOOL, scope, toolSet) === void 0 ? "" : EVENT_READ_GUIDANCE
26786
+ });
26787
+ });
26788
+ }
26184
26789
  const deliver = createHandoffDelivery({ table, store: getStore(), sessionTitle });
26185
26790
  registerSkills(ctx, { skillsDir });
26186
26791
  const readFileThrough = (fs3) => (agent, key, ranges, signal) => readObserved({
@@ -26217,6 +26822,10 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26217
26822
  }
26218
26823
  };
26219
26824
  };
26825
+ const gitStateOf = async (session, signal) => {
26826
+ const workingDirectory = ctx.get("workingDirectory");
26827
+ return workingDirectory === void 0 ? null : readGitState({ cwd: workingDirectory.get(session), signal });
26828
+ };
26220
26829
  const ratioOf = (sessionId) => {
26221
26830
  const entry = table.get(sessionId);
26222
26831
  return entry.state === "live" ? entry.watcher.getStatus().cRatio : null;
@@ -26274,12 +26883,13 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26274
26883
  const monitor = createInnerMonitor({ appendPluginRecord: innerKit.appendPluginRecord, publish: hub.publish });
26275
26884
  child.on("agent/pre-step", createInnerSeal({
26276
26885
  readMode: (session) => handle2.stateOf(session),
26277
- sourceFacts: (sessionId) => table.sourceFacts(sessionId),
26886
+ eventFacts: (sessionId) => table.eventFacts(sessionId),
26278
26887
  readSession,
26279
- heldView: (sessionId, events, range) => table.heldView(sessionId, events, range),
26888
+ heldView: (sessionId, events) => table.heldView(sessionId, events),
26280
26889
  readFile: readFileThrough(child.fs),
26281
26890
  readUnobserved: readUnobservedThrough(child.fs),
26282
26891
  readState: stateOf2(child),
26892
+ readGit: gitStateOf,
26283
26893
  cRatio: ratioOf,
26284
26894
  ctpOf,
26285
26895
  readSettings,
@@ -26309,6 +26919,10 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26309
26919
  // The store answers null for an id it holds no row of, so an absent handoff reads as no next task.
26310
26920
  nextTaskOf: (handoffId) => getStore().getHandoff(handoffId)?.nextTask ?? null
26311
26921
  });
26922
+ heldOf = (sessionId, seq) => {
26923
+ const session = sessionOf(sessionId);
26924
+ return session !== void 0 && heldInContext(monitorHandle.stateOf(session), seq);
26925
+ };
26312
26926
  } catch (error) {
26313
26927
  writeDiagnostic(null, hostDiagnostic("inner_monitor_register", error));
26314
26928
  }
@@ -26316,6 +26930,7 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26316
26930
  return () => {
26317
26931
  modeAccess = null;
26318
26932
  monitorAccess = null;
26933
+ heldOf = null;
26319
26934
  publishListed();
26320
26935
  };
26321
26936
  });
@@ -26329,6 +26944,7 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
26329
26944
  child.extend({ webServer: child.webServer }).connection.rpc.handle("/session-watcher", createRpcHandler({
26330
26945
  table,
26331
26946
  store: getStore(),
26947
+ workingTree,
26332
26948
  publish: hub.publish,
26333
26949
  resolvePersisted,
26334
26950
  innerMode: () => modeAccess,
@@ -26371,6 +26987,7 @@ function apply(ctx, config) {
26371
26987
  applyHost(ctx, {
26372
26988
  defineTool,
26373
26989
  commandKit: { CompactionId, compactCheckpointSource, createUserMessage },
26990
+ queryKit: { extractSessionEventText, HarnessError },
26374
26991
  innerKit: {
26375
26992
  appendPluginRecord,
26376
26993
  pluginRecordOf,