@nomadop/session-watcher-dsh 0.11.1 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9919,8 +9919,8 @@ var repairJson = Object.assign(jsonRepair, { parse: jsonParse });
9919
9919
  // dsh/carrier-cache/package.json
9920
9920
  var package_default = {
9921
9921
  name: "@nomadop/session-watcher-dsh-carrier-cache",
9922
- version: "0.1.0",
9923
- description: "Activation bundle of Session Watcher's carrier cache adapter for DeepSeek Harness",
9922
+ version: "0.2.0",
9923
+ description: "Session Watcher's carrier cache adapter for DeepSeek Harness, with the profile layer that activates it",
9924
9924
  type: "module",
9925
9925
  license: "MIT",
9926
9926
  author: "Longju Cheng",
@@ -9937,15 +9937,27 @@ var package_default = {
9937
9937
  dsh: ">=0.2.2-rc.1"
9938
9938
  },
9939
9939
  exports: {
9940
+ "./pi-ai": "./dist/pi-ai-index.js",
9940
9941
  "./locale/*.json": "./locale/*.json",
9941
9942
  "./icon": "./icon.svg"
9942
9943
  },
9943
9944
  files: [
9945
+ "dist/pi-ai-index.js",
9944
9946
  "cordis.patch.yml",
9945
9947
  "locale/*.json",
9946
9948
  "icon.svg",
9947
9949
  "README.md"
9948
9950
  ],
9951
+ peerDependencies: {
9952
+ "@deepseek-ai/dsh-credentials": ">=0.2.2-rc.1",
9953
+ "@deepseek-ai/dsh-launch-environment": ">=0.2.2-rc.1",
9954
+ "@deepseek-ai/dsh-llm": ">=0.2.2-rc.1",
9955
+ "@deepseek-ai/dsh-llm-pi-ai": ">=0.2.2-rc.1",
9956
+ "@deepseek-ai/dsh-timeout": ">=0.2.2-rc.1",
9957
+ "@deepseek-ai/dsh-util-values": ">=0.2.2-rc.1",
9958
+ "@deepseek-ai/schemastery": ">=3.19.0",
9959
+ "@earendil-works/pi-ai": "^1.3.0"
9960
+ },
9949
9961
  dsh: {
9950
9962
  bundle: {
9951
9963
  patch: "./cordis.patch.yml"
@@ -19602,6 +19614,92 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
19602
19614
  };
19603
19615
  }
19604
19616
 
19617
+ // lib/old-attribution.js
19618
+ var OLD_SHARE_ABOVE = 0.9;
19619
+ function createOldAttributionScorer() {
19620
+ const hits = [];
19621
+ let step = null;
19622
+ let gapSeen = false;
19623
+ const startStep = (key) => {
19624
+ step = { key, scored: !gapSeen, undo: /* @__PURE__ */ new Map() };
19625
+ };
19626
+ const startEpoch = () => {
19627
+ step = null;
19628
+ gapSeen = false;
19629
+ };
19630
+ function freeze(record, scratch) {
19631
+ for (const { impacts } of record.effects) {
19632
+ for (const { resourceKey, kind, entries } of impacts) {
19633
+ const before = scratch.get(resourceKey);
19634
+ const undone = step.undo.get(resourceKey) ?? /* @__PURE__ */ new Map();
19635
+ if (kind === "replace-fragments") {
19636
+ for (const [line, entry] of before ?? []) if (!undone.has(line)) undone.set(line, entry);
19637
+ }
19638
+ for (const { key } of entries) if (!undone.has(key)) undone.set(key, before?.get(key) ?? null);
19639
+ step.undo.set(resourceKey, undone);
19640
+ }
19641
+ }
19642
+ }
19643
+ function heldIn(resourceKey, scratch) {
19644
+ const undone = step.undo.get(resourceKey);
19645
+ let overview = null;
19646
+ const overviewOf = () => {
19647
+ const lines = new Map(scratch.get(resourceKey));
19648
+ for (const [line, entry] of undone ?? []) {
19649
+ if (entry === null) lines.delete(line);
19650
+ else lines.set(line, entry);
19651
+ }
19652
+ const fps = /* @__PURE__ */ new Set();
19653
+ let unfingerprinted = false;
19654
+ for (const entry of lines.values()) {
19655
+ if (entry.fp === void 0) unfingerprinted = true;
19656
+ else fps.add(entry.fp);
19657
+ }
19658
+ return { fps, unfingerprinted };
19659
+ };
19660
+ return {
19661
+ entryAt: (line) => undone?.has(line) ? undone.get(line) ?? void 0 : scratch.get(resourceKey)?.get(line),
19662
+ mayHaveMoved(fp) {
19663
+ overview ??= overviewOf();
19664
+ return overview.unfingerprinted || overview.fps.has(fp);
19665
+ }
19666
+ };
19667
+ }
19668
+ function returnedBy(record) {
19669
+ const byResource = /* @__PURE__ */ new Map();
19670
+ for (const { access, impacts } of record.effects) {
19671
+ if (access !== "read") continue;
19672
+ for (const { resourceKey, entries } of impacts) {
19673
+ const lines = byResource.get(resourceKey) ?? /* @__PURE__ */ new Map();
19674
+ for (const { key, fp, moved } of entries) if (moved !== true && fp !== void 0) lines.set(key, fp);
19675
+ byResource.set(resourceKey, lines);
19676
+ }
19677
+ }
19678
+ return byResource;
19679
+ }
19680
+ function score({ pending, observation, record, scratch }) {
19681
+ let oldLines = 0;
19682
+ let newLines = 0;
19683
+ for (const [resourceKey, lines] of returnedBy(record)) {
19684
+ const held = heldIn(resourceKey, scratch);
19685
+ for (const [key, fp] of lines) {
19686
+ if (held.entryAt(key)?.fp === fp) oldLines += 1;
19687
+ else if (!held.mayHaveMoved(fp)) newLines += 1;
19688
+ }
19689
+ }
19690
+ if (oldLines > 0 && oldLines / (oldLines + newLines) > OLD_SHARE_ABOVE) {
19691
+ hits.push({ toolUseId: pending.toolUseId, seq: observation.sourceOrdinal, oldLines, newLines });
19692
+ }
19693
+ }
19694
+ function observe(call) {
19695
+ if (!call.recalled) gapSeen = true;
19696
+ if (step === null || !step.scored) return;
19697
+ if (call.recalled && call.observation.isError !== true && call.observation.stepKey === step.key) score(call);
19698
+ freeze(call.record, call.scratch);
19699
+ }
19700
+ return { hits, startStep, startEpoch, observe };
19701
+ }
19702
+
19605
19703
  // lib/held-view.js
19606
19704
  var SELECTED = () => ({ selectedByDefault: true, defaultDiscardReason: null });
19607
19705
  function createHeldView({ createProjection, completeToolResult, resolveModelPolicy, frameCtx }) {
@@ -19614,14 +19712,23 @@ function createHeldView({ createProjection, completeToolResult, resolveModelPoli
19614
19712
  return answer;
19615
19713
  }
19616
19714
  });
19715
+ const scorer = createOldAttributionScorer();
19716
+ const scoringCtx = { ...frameCtx, observeRecord: scorer.observe };
19617
19717
  const engine = createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy: SELECTED });
19618
19718
  let skills = /* @__PURE__ */ new Map();
19619
19719
  const effects = [];
19620
19720
  for (const observation of observations) {
19721
+ if (observation.type === "step-start") {
19722
+ scorer.startStep(observation.stepKey);
19723
+ continue;
19724
+ }
19621
19725
  completed = [];
19622
- const { records } = projection.project(observation, frameCtx);
19726
+ const { records } = projection.project(observation, scoringCtx);
19623
19727
  engine.ingest(records.filter((record) => record.type === "effect" || record.type === "epoch"));
19624
- if (records.some((record) => record.type === "epoch")) skills = /* @__PURE__ */ new Map();
19728
+ if (records.some((record) => record.type === "epoch")) {
19729
+ skills = /* @__PURE__ */ new Map();
19730
+ scorer.startEpoch();
19731
+ }
19625
19732
  for (const { effects: answered, text, seq } of completed) {
19626
19733
  for (const { resourceKey } of answered.flatMap((effect) => effect.impacts)) {
19627
19734
  const isSkill = resourceKey.startsWith(SKILL_RESOURCE_PREFIX);
@@ -19632,7 +19739,7 @@ function createHeldView({ createProjection, completeToolResult, resolveModelPoli
19632
19739
  }
19633
19740
  }
19634
19741
  const paths = new Map([...engine.heldLines()].filter(([key]) => !key.startsWith(SKILL_RESOURCE_PREFIX)));
19635
- return { paths, skills, effects };
19742
+ return { paths, skills, effects, oldReads: scorer.hits };
19636
19743
  };
19637
19744
  }
19638
19745
 
@@ -19690,7 +19797,7 @@ function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
19690
19797
  // package.json
19691
19798
  var package_default2 = {
19692
19799
  name: "@nomadop/session-watcher",
19693
- version: "0.11.1",
19800
+ version: "0.11.2",
19694
19801
  description: "Local Claude Code context-cost monitor, transcript replay, buckets, and handoff",
19695
19802
  type: "module",
19696
19803
  license: "MIT",
@@ -20808,10 +20915,10 @@ function createToolEvidenceInterpreter({ attribution, profile, limits } = {}) {
20808
20915
  }
20809
20916
  function recordOf2(pending, observation, frameCtx, scratch) {
20810
20917
  const recalled = typeof frameCtx.recall === "function" ? readRecord(frameCtx.recall(pending.toolUseId)) : null;
20811
- if (recalled !== null) return recalled;
20918
+ if (recalled !== null) return { record: recalled, recalled: true };
20812
20919
  const record = partition(pending, observation, scratch);
20813
20920
  if (typeof frameCtx.remember === "function") frameCtx.remember(pending.toolUseId, record);
20814
- return record;
20921
+ return { record, recalled: false };
20815
20922
  }
20816
20923
  function emit(record, pending, observation, telemetry, scratch) {
20817
20924
  const effects = priced(record.effects, pending.issuingPolicy.ctp);
@@ -20872,7 +20979,10 @@ function createToolEvidenceInterpreter({ attribution, profile, limits } = {}) {
20872
20979
  pathEvents: []
20873
20980
  };
20874
20981
  if (pending.nonFile !== null) return completeNonFileResource(pending, observation, telemetry);
20875
- return emit(recordOf2(pending, observation, frameCtx ?? {}, scratch), pending, observation, telemetry, scratch);
20982
+ const ctx = frameCtx ?? {};
20983
+ const { record, recalled } = recordOf2(pending, observation, ctx, scratch);
20984
+ if (typeof ctx.observeRecord === "function") ctx.observeRecord({ pending, observation, record, recalled, scratch });
20985
+ return emit(record, pending, observation, telemetry, scratch);
20876
20986
  }
20877
20987
  function resourceKeysOf(pair, capture) {
20878
20988
  try {
@@ -21101,7 +21211,7 @@ function renderState({ asOfSeq, items }, stateItems) {
21101
21211
  var INNER_SEAL_KIND = "session-watcher-inner-seal";
21102
21212
  var sourceEventSeqsOf = ({ callSeq, pruneSeq, replaced }) => [callSeq, pruneSeq, ...replaced];
21103
21213
  var callSeqOf = (seqs) => seqs[0];
21104
- function assembleCarrierSource({ slots, summaries, questions, attachments, verbatimSeqs = [], changes, state }) {
21214
+ function assembleCarrierSource({ slots, summaries, questions, attachments, oldReads = [], verbatimSeqs = [], changes, state }) {
21105
21215
  const injected = [.../* @__PURE__ */ new Set([...verbatimSeqs, ...questions.flat().flatMap(({ seqs }) => seqs ?? [])])];
21106
21216
  return {
21107
21217
  kind: INNER_SEAL_KIND,
@@ -21110,7 +21220,8 @@ function assembleCarrierSource({ slots, summaries, questions, attachments, verba
21110
21220
  seqs,
21111
21221
  text: summaries[index],
21112
21222
  ...questions[index].length > 0 ? { questions: questions[index].map(({ question, user }) => ({ question, user })) } : {},
21113
- ...attachments[index].length > 0 ? { attachments: attachments[index] } : {}
21223
+ ...attachments[index].length > 0 ? { attachments: attachments[index] } : {},
21224
+ ...oldReads[index]?.length > 0 ? { oldReads: oldReads[index] } : {}
21114
21225
  })),
21115
21226
  ...injected.length > 0 ? { verbatimSeqs: injected } : {},
21116
21227
  ...changes,
@@ -21207,6 +21318,10 @@ function usageOf(usage) {
21207
21318
  cacheWrite: usage.cacheWriteTokens ?? 0
21208
21319
  };
21209
21320
  }
21321
+ function dispatchedCallIdOf(event) {
21322
+ const data = event?.type === "tool/call" ? event.data : void 0;
21323
+ return isIndex(data?.turn) && isIndex(data?.step) && isId2(data?.callId) ? callIdOf(data.turn, data.step, data.callId) : null;
21324
+ }
21210
21325
  function callUsageOf(usage) {
21211
21326
  return isUsage(usage) ? usageOf(usage) : null;
21212
21327
  }
@@ -21393,6 +21508,15 @@ function reduceDshSnapshot(events) {
21393
21508
  }
21394
21509
  return { batches, observations: batches.flat(), diagnostics };
21395
21510
  }
21511
+ var stepKeyOf = (data) => isIndex(data?.turn) && isIndex(data?.step) ? `${data.turn}:${data.step}` : null;
21512
+ function heldObservationsOf(events) {
21513
+ return events.flatMap((event) => {
21514
+ const stepKey3 = stepKeyOf(event.data);
21515
+ if (event.type === "step/start") return stepKey3 === null ? [] : [{ type: "step-start", stepKey: stepKey3 }];
21516
+ const { observations } = reduceDshEvent(event);
21517
+ return event.type === "tool/result" ? observations.map((observation) => ({ ...observation, stepKey: stepKey3 })) : observations;
21518
+ });
21519
+ }
21396
21520
 
21397
21521
  // lib/harness/dsh/dialogue-source.js
21398
21522
  function createDshDialogueSource({ readSession }) {
@@ -21984,7 +22108,7 @@ function composeWatcher({
21984
22108
  resolveModelPolicy: policyFor,
21985
22109
  frameCtx: sessionId ? { recall } : {}
21986
22110
  });
21987
- const heldView = (events) => view(reduceDshSnapshot(events).observations);
22111
+ const heldView = (events) => view(heldObservationsOf(events));
21988
22112
  return { watcher, dialogueSource, dialogueProjection, heldView };
21989
22113
  }
21990
22114
 
@@ -23166,6 +23290,9 @@ var MONITOR_UNAVAILABLE = failure("inner_monitor_unavailable", "The inner compac
23166
23290
  var FORBIDDEN = failure("forbidden", "Only the owner of this host can manage the carrier cache.");
23167
23291
  var CARRIER_CACHE_UNAVAILABLE = failure("carrier_cache_unavailable", "The carrier cache switch is not available in this host.");
23168
23292
  var MONITOR_NOT_COMMITTED = failure("inner_monitor_not_committed", "The inner compaction attempt has no committed seal, so it has no slots.");
23293
+ var TARGET_FORBIDDEN = failure("forbidden", "Only the owner of this host can read the text of a recalled event.");
23294
+ var TARGET_NOT_RECALLED = failure("inner_monitor_not_recalled", "The event is not a recall target of this settlement at this cut.");
23295
+ var NO_CARRIER = { not_committed: MONITOR_NOT_COMMITTED };
23169
23296
  function createRpcHandler({
23170
23297
  table,
23171
23298
  store,
@@ -23282,18 +23409,24 @@ function createRpcHandler({
23282
23409
  "inner-monitor/slot": { addresses: ["attempt", "slot"], read: (access, { sessionId, attempt, slot }) => access?.slot(sessionId, attempt, slot) },
23283
23410
  "inner-monitor/handoff": { addresses: ["handoff"], read: (access, { sessionId, handoff }) => access?.handoff(sessionId, handoff) },
23284
23411
  "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) }
23412
+ "inner-monitor/settlement/current": { addresses: [], read: (access, { sessionId }) => access?.currentSettlement(sessionId) },
23413
+ "inner-monitor/settlement/target": {
23414
+ addresses: ["segment", "through", "seq"],
23415
+ owner: TARGET_FORBIDDEN,
23416
+ closed: { not_target: TARGET_NOT_RECALLED },
23417
+ read: (access, { sessionId, segment, through, seq }) => access?.settlementTarget(sessionId, { segment, through, seq })
23418
+ }
23286
23419
  };
23287
23420
  const isAddress = (value) => Number.isSafeInteger(value) && value >= 0;
23288
23421
  async function answerMonitor(endpoint, body2) {
23289
- const { addresses, read } = monitorEndpoints[endpoint];
23422
+ const { addresses, read, closed = NO_CARRIER } = monitorEndpoints[endpoint];
23290
23423
  if (!addresses.every((name3) => isAddress(body2[name3]))) {
23291
23424
  return failure("invalid_body", `Body must contain { sessionId: string${addresses.map((name3) => `, ${name3}: non-negative integer`).join("")} }`);
23292
23425
  }
23293
23426
  try {
23294
23427
  const value = await read(innerMonitor(), body2);
23295
23428
  if (value === void 0) return MONITOR_UNAVAILABLE;
23296
- return value.kind === "not_committed" ? MONITOR_NOT_COMMITTED : { ok: true, value };
23429
+ return Object.hasOwn(closed, value.kind) ? closed[value.kind] : { ok: true, value };
23297
23430
  } catch (error) {
23298
23431
  const diagnostic3 = hostDiagnostic("inner_monitor_read_failed", error);
23299
23432
  writeDiagnostic(body2.sessionId, diagnostic3);
@@ -23324,6 +23457,8 @@ function createRpcHandler({
23324
23457
  if (!Object.hasOwn(endpoints, endpoint) && !Object.hasOwn(modeEndpoints, endpoint) && !Object.hasOwn(monitorEndpoints, endpoint)) {
23325
23458
  return failure("unknown_endpoint", `unknown endpoint ${endpoint}`);
23326
23459
  }
23460
+ const owner = monitorEndpoints[endpoint]?.owner;
23461
+ if (owner !== void 0 && peer?.principal?.kind !== "owner") return owner;
23327
23462
  const body2 = payload || {};
23328
23463
  if (typeof body2.sessionId !== "string") return failure("invalid_body", "Body must contain { sessionId: string }");
23329
23464
  if (Object.hasOwn(modeEndpoints, endpoint)) return modeEndpoints[endpoint](body2);
@@ -25466,8 +25601,8 @@ function slotMessagesOf({ slots, session, events, range }) {
25466
25601
  var NO_OBSERVER = Object.freeze({ dispatch() {
25467
25602
  }, chunk() {
25468
25603
  } });
25469
- var NO_CARRIER = Object.freeze({ scope: () => ({ run: (body2) => body2(), evidence: () => null }) });
25470
- async function summarizeSlots({ llm, session, index, events, selection, slots, range, held, signal, kit, observer = NO_OBSERVER, carrier = NO_CARRIER }) {
25604
+ var NO_CARRIER2 = Object.freeze({ scope: () => ({ run: (body2) => body2(), evidence: () => null }) });
25605
+ async function summarizeSlots({ llm, session, index, events, selection, slots, range, held, signal, kit, observer = NO_OBSERVER, carrier = NO_CARRIER2 }) {
25471
25606
  const { provider, model, reasoningEffort } = selection;
25472
25607
  const chosen = { provider, model, ...reasoningEffort === void 0 ? {} : { reasoningEffort } };
25473
25608
  const tools = session.requestHeader()?.tools;
@@ -25809,6 +25944,7 @@ function createInnerSeal({ readMode, eventFacts, readSession, heldView, readFile
25809
25944
  summaries: summary.summaries,
25810
25945
  questions: questionsOf({ slots, bySeq }),
25811
25946
  attachments: slotAttachments,
25947
+ oldReads: slots.map(({ seqs }) => held.oldReads.filter(({ seq }) => seqs.includes(seq))),
25812
25948
  verbatimSeqs: summary.verbatimSeqs,
25813
25949
  changes: carriedOf(earlier, current),
25814
25950
  state: stateAt(session, readState, earlier, git)
@@ -25926,6 +26062,19 @@ function sourceEventView(event, { visible }) {
25926
26062
  const shown = event.type === "tool/result" ? [{ type: "tool-result", callId: message?.toolCallId, isError: message?.isError === true, blocks }] : blocks;
25927
26063
  return { seq: event.seq, type: event.type, visible, blocks: shown, raw: event };
25928
26064
  }
26065
+ function toolCallsOf(event) {
26066
+ if (event.type !== "assistant/message") return [];
26067
+ const uses = reduceDshEvent(event).observations.filter(({ type }) => type === "tool-use");
26068
+ const blocks = sourceEventView(event, { visible: true }).blocks.filter(({ type }) => type === "tool-call");
26069
+ return uses.map(({ toolUseId, name: name3 }, at) => ({ id: toolUseId, name: name3, arguments: blocks[at].arguments }));
26070
+ }
26071
+ function toolResultOf(event) {
26072
+ if (event.type !== "tool/result") return null;
26073
+ const [result] = reduceDshEvent(event).observations;
26074
+ if (result === void 0) return null;
26075
+ const [{ blocks }] = sourceEventView(event, { visible: true }).blocks;
26076
+ return { id: result.toolUseId, error: result.isError === true, empty: blocks.every((block) => block.type === "text" && block.text === "") };
26077
+ }
25929
26078
  var SOURCE_CATEGORIES = { "system/message": "system", "developer/message": "developer", "tool/result": "tool", "assistant/message": "assistant" };
25930
26079
  var HUMAN_SOURCE_KIND = "user";
25931
26080
  function sourceCategoryOf({ type, kind }) {
@@ -25973,39 +26122,73 @@ function eventDisplayText(event) {
25973
26122
 
25974
26123
  // dsh/src/monitor-settlement-recall.js
25975
26124
  var stepKey2 = ({ turn, step } = {}) => `${turn}:${step}`;
25976
- var pureRecall = ({ tools, marked }) => marked.size > 0 && tools.every(({ id }) => marked.has(id));
26125
+ var ABORTED_BEFORE_DISPATCH = "ABORTED_BEFORE_DISPATCH";
26126
+ var isInitiated = ({ target, dispatched, skipped }) => target !== void 0 && dispatched && !skipped;
26127
+ var callRecallOf = (call = {}) => isInitiated(call) ? "recall" : call.target === void 0 || call.dispatched || call.resulted ? "other" : "unknown";
26128
+ function judgeOf({ tools, calls }) {
26129
+ const states = tools.map(({ id }) => callRecallOf(calls.get(id)));
26130
+ if (states.includes("other") || states.length === 0) return "other";
26131
+ return states.includes("unknown") ? "unknown" : "pure";
26132
+ }
25977
26133
  function reportPositions(seals, samples, tailCalls) {
25978
26134
  const positions = /* @__PURE__ */ new Map();
26135
+ const landing = /* @__PURE__ */ new Map();
26136
+ const sealAt = /* @__PURE__ */ new Map();
25979
26137
  let offset = 0;
25980
- for (const { attempt, range } of seals.values()) {
26138
+ let proved = true;
26139
+ for (const [carrier, { attempt, range }] of seals) {
25981
26140
  const steps = /* @__PURE__ */ new Map();
25982
26141
  for (const seq of range) {
25983
26142
  const sample = samples.get(seq);
25984
26143
  if (sample?.counted) steps.set(stepKey2(sample.event.data), seq);
25985
26144
  }
25986
26145
  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;
26146
+ if (steps.size === n) {
26147
+ for (const [key, seq] of steps) {
26148
+ positions.set(seq, offset += 1);
26149
+ landing.set(key, offset);
26150
+ }
26151
+ } else {
26152
+ offset += n;
26153
+ if (sealAt.size > 0) proved = false;
26154
+ }
26155
+ sealAt.set(carrier, offset);
25989
26156
  }
25990
26157
  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;
26158
+ const tail = [...samples.values()].filter(({ counted, event }) => counted && event.seq > lastCarrier);
26159
+ if (tail.length === tailCalls) {
26160
+ for (const { event } of tail) {
26161
+ positions.set(event.seq, offset += 1);
26162
+ landing.set(stepKey2(event.data), offset);
26163
+ }
26164
+ } else {
26165
+ proved = false;
26166
+ }
26167
+ const firstCarrier = seals.keys().next().value;
26168
+ const covered = proved && [...samples.values()].every(({ counted, event }) => !counted || event.seq <= firstCarrier || positions.has(event.seq));
26169
+ return { positions, landing, sealAt, covered };
25994
26170
  }
26171
+ var placeOf = (seq, owners, { landing, sealAt }) => sealAt.get(seq) ?? landing.get(owners.get(seq)) ?? null;
25995
26172
  function settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls, sessionId, isNoise }) {
25996
26173
  const seals = new Map(attempts.map((attempt) => {
25997
26174
  const call = log.get(attempt.call?.seq)?.data;
25998
26175
  return [attempt.carrier.seq, { attempt, range: isCallRecord(call) ? call.range : [] }];
25999
26176
  }));
26000
- if (seals.size === 0) return void 0;
26177
+ if (seals.size === 0) return {};
26001
26178
  const starts = new Set(attempts.map(({ id }) => id));
26002
26179
  const samples = /* @__PURE__ */ new Map();
26003
26180
  const before = /* @__PURE__ */ new Map();
26004
26181
  const active = /* @__PURE__ */ new Map();
26182
+ const owners = /* @__PURE__ */ new Map();
26005
26183
  let ctp;
26006
26184
  let lastMeasured;
26007
26185
  let seal;
26008
26186
  let sample;
26187
+ let open = null;
26188
+ const targetOf2 = (call, requestSeq) => {
26189
+ const target = eventReadTargetOf(call);
26190
+ return target && (target.sessionId === void 0 || target.sessionId === sessionId) && target.seq >= events[0].seq && target.seq < requestSeq && log.has(target.seq) ? target.seq : void 0;
26191
+ };
26009
26192
  for (const event of events) {
26010
26193
  const { seq, type, data } = event;
26011
26194
  if (starts.has(seq)) before.set(seq, lastMeasured);
@@ -26014,25 +26197,37 @@ function settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls, s
26014
26197
  for (const replaced of seal.range) active.delete(replaced);
26015
26198
  lastMeasured = void 0;
26016
26199
  }
26200
+ if (type === "step/start") open = stepKey2(data);
26201
+ else if (type === "step/end") open = null;
26202
+ else if (type === "user/message" && eventFactOf(event).marker === null && open !== null) owners.set(seq, open);
26203
+ else if (type === "assistant/message" || type === "tool/call" || type === "tool/result") {
26204
+ if (Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)) owners.set(seq, stepKey2(data));
26205
+ }
26017
26206
  if (isMainCall(event)) {
26018
26207
  const usage = callUsageOf(data?.usage);
26019
26208
  if (usage !== null) ctp ??= modelPolicyFor(data?.message?.source?.model).ctp;
26020
26209
  const resident = [...active.values()].reduce((sum, tokens) => sum + tokens, 0);
26021
26210
  const content = data?.message?.content;
26022
26211
  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() };
26212
+ const calls = new Map(tools.map((block) => [block.id, { target: targetOf2(block, seq), dispatched: false, skipped: false, resulted: false }]));
26213
+ sample = { event, counted: eventFactOf(event).step !== null, usage, resident, seal: seal?.attempt, tools, calls };
26024
26214
  if (!isNoise(event)) lastMeasured = usage === null ? void 0 : sample;
26025
26215
  samples.set(seq, sample);
26026
26216
  }
26027
26217
  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);
26218
+ if (type === "tool/call" && stepKey2(data) === stepKey2(sample.event.data)) {
26219
+ const call = sample.calls.get(data.callId);
26220
+ if (call !== void 0) call.dispatched = true;
26031
26221
  }
26032
26222
  if (type === "tool/result") {
26033
26223
  const op = event.surfaceOp;
26224
+ const call = stepKey2(data) === stepKey2(sample.event.data) ? sample.calls.get(data.message?.toolCallId) : void 0;
26225
+ if (call !== void 0) {
26226
+ call.resulted = true;
26227
+ if (data.error?.code === ABORTED_BEFORE_DISPATCH) call.skipped = true;
26228
+ }
26034
26229
  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);
26230
+ const returned = op === "append" && data.message?.isError !== true && call !== void 0 && isInitiated(call);
26036
26231
  if (!replaced && !returned) continue;
26037
26232
  const content = data.message?.content;
26038
26233
  const text = Array.isArray(content) ? content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("") : "";
@@ -26040,26 +26235,44 @@ function settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls, s
26040
26235
  if (tokens > 0) active.set(seq, tokens);
26041
26236
  }
26042
26237
  }
26238
+ for (const sample2 of samples.values()) sample2.verdict = judgeOf(sample2);
26043
26239
  const cuts = attempts.flatMap(({ id }) => {
26044
26240
  const pre = before.get(id);
26045
- const output = pre && pureRecall(pre) ? pre.usage.output : 0;
26241
+ const output = pre?.verdict === "pure" ? pre.usage.output : 0;
26046
26242
  const tokens = (pre?.resident ?? 0) + output - (samples.get(postByAttempt.get(id))?.resident ?? 0);
26047
26243
  return tokens === 0 ? [] : [{ id, tokens }];
26048
26244
  });
26049
26245
  const steps = [];
26050
26246
  let partial = false;
26051
- const positions = reportPositions(seals, samples, tailCalls);
26247
+ const axis = reportPositions(seals, samples, tailCalls);
26248
+ const { positions } = axis;
26249
+ const reads = /* @__PURE__ */ new Map();
26250
+ let judged = 0;
26251
+ let pure = 0;
26052
26252
  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;
26253
+ const { event, counted, usage, resident, seal: parent, verdict } = sample2;
26056
26254
  const { seq } = event;
26057
26255
  const at = positions.get(seq);
26256
+ if (counted && parent !== void 0) {
26257
+ if (verdict === "pure") {
26258
+ for (const { id } of sample2.tools) {
26259
+ const { target } = sample2.calls.get(id);
26260
+ const landings = reads.get(target) ?? /* @__PURE__ */ new Map();
26261
+ reads.set(target, landings);
26262
+ if (at !== void 0) landings.set(at, { at, seq });
26263
+ }
26264
+ }
26265
+ if (at !== void 0 && verdict !== "unknown") {
26266
+ judged += 1;
26267
+ if (verdict === "pure") pure += 1;
26268
+ }
26269
+ }
26270
+ if (!counted || verdict !== "pure" && resident === 0) continue;
26058
26271
  if (at === void 0) {
26059
26272
  partial = true;
26060
26273
  continue;
26061
26274
  }
26062
- if (pure) {
26275
+ if (verdict === "pure") {
26063
26276
  const ratio = parent?.quote?.cRatio ?? null;
26064
26277
  const post = postByAttempt.get(parent?.id) === seq ? parent.id : void 0;
26065
26278
  steps.push({ at, seq, usage, ratio, ...post === void 0 ? {} : { post } });
@@ -26067,7 +26280,89 @@ function settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls, s
26067
26280
  steps.push({ at, seq, resident });
26068
26281
  }
26069
26282
  }
26070
- return steps.length === 0 && cuts.length === 0 && !partial ? void 0 : { steps, cuts, ...partial ? { partial } : {} };
26283
+ const targets = [...reads].sort(([a], [b]) => a - b).map(([seq, landings]) => ({
26284
+ seq,
26285
+ type: log.get(seq).type,
26286
+ at: placeOf(seq, owners, axis),
26287
+ reads: [...landings.values()].sort((a, b) => a.at - b.at)
26288
+ }));
26289
+ const recall = steps.length === 0 && cuts.length === 0 && !partial ? void 0 : { steps, cuts, ...partial ? { partial } : {} };
26290
+ return { recall, activity: { covered: axis.covered, judged, pure, targets } };
26291
+ }
26292
+
26293
+ // dsh/src/inner-monitor-tools.js
26294
+ var STATE_WARNING = Object.freeze({ check: "state-check", mixed: "state-mixed", write: "state-write" });
26295
+ var OLD_ATTRIBUTION_WARNING = "old-attribution";
26296
+ var STEP_LEVEL = Object.values(STATE_WARNING);
26297
+ var THRESHOLD_PERCENT = Math.round(OLD_SHARE_ABOVE * 100);
26298
+ function groupBy(list, key) {
26299
+ const groups = /* @__PURE__ */ new Map();
26300
+ for (const item of list) groups.set(key(item), [...groups.get(key(item)) ?? [], item]);
26301
+ return groups;
26302
+ }
26303
+ var soleOf = (groups, id) => groups.get(id)?.length === 1 ? groups.get(id)[0] : null;
26304
+ function standsFor(event, seq, log) {
26305
+ try {
26306
+ return originalsOf(event, log).includes(seq);
26307
+ } catch {
26308
+ return false;
26309
+ }
26310
+ }
26311
+ function shareOf({ oldLines, newLines }) {
26312
+ const total = oldLines + newLines;
26313
+ if (total === 0) return { percent: null, over: false };
26314
+ const percent = Math.floor(oldLines * 100 / total);
26315
+ return { percent, over: oldLines / total > OLD_SHARE_ABOVE && percent <= THRESHOLD_PERCENT };
26316
+ }
26317
+ var warn = (card, warning) => {
26318
+ if (!card.warnings.some(({ kind }) => kind === warning.kind)) card.warnings.push(warning);
26319
+ };
26320
+ function slotToolsOf({ events, range, log, kinds, dispatches, oldReads }) {
26321
+ const calls = events.flatMap(toolCallsOf);
26322
+ const results = events.flatMap((event) => {
26323
+ const result = toolResultOf(event);
26324
+ return result === null ? [] : [{ ...result, seq: event.seq }];
26325
+ });
26326
+ const callsById = groupBy(calls, ({ id }) => id);
26327
+ const resultsById = groupBy(results, ({ id }) => id);
26328
+ const resultOf = (id) => {
26329
+ const result = soleOf(callsById, id) === null ? null : soleOf(resultsById, id);
26330
+ return result === null ? null : { seq: result.seq, error: result.error, empty: result.empty };
26331
+ };
26332
+ const replacements = events.filter((event) => isPrunedResult(event) && range.has(event.seq));
26333
+ const prunedOf = (result) => {
26334
+ const seen = result === null ? [] : replacements.filter((event) => standsFor(event, result.seq, log));
26335
+ return seen.length === 1 ? { seq: seen[0].seq } : null;
26336
+ };
26337
+ const cards = calls.map((call) => {
26338
+ const result = resultOf(call.id);
26339
+ return { id: call.id, name: call.name, input: call.arguments, result, pruned: prunedOf(result), warnings: [] };
26340
+ });
26341
+ const paired = new Set(cards.map((card) => card.result?.seq));
26342
+ const lone = results.filter(({ seq }) => !paired.has(seq)).map(({ id, seq, error, empty }) => ({ id, name: null, input: null, result: { seq, error, empty }, pruned: prunedOf({ seq }), warnings: [] }));
26343
+ const all = [...cards, ...lone];
26344
+ const unplaced = /* @__PURE__ */ new Set();
26345
+ const settle = (kind, card, warning) => {
26346
+ if (card === null) unplaced.add(kind);
26347
+ else warn(card, warning);
26348
+ };
26349
+ for (const { kind, seq } of dispatches) {
26350
+ const dispatched = log.get(seq);
26351
+ const id = dispatchedCallIdOf(dispatched);
26352
+ const holders = cards.filter((card) => card.id === id);
26353
+ const [holder] = holders;
26354
+ const exact = holders.length === 1 && holder.name === dispatched.data.name && holder.input === dispatched.data.arguments;
26355
+ settle(kind, exact ? holder : null, { kind });
26356
+ }
26357
+ for (const hit of oldReads) {
26358
+ settle(
26359
+ OLD_ATTRIBUTION_WARNING,
26360
+ all.find((card) => card.id === hit.toolUseId && card.result?.seq === hit.seq) ?? null,
26361
+ { kind: OLD_ATTRIBUTION_WARNING, oldLines: hit.oldLines, newLines: hit.newLines, ...shareOf(hit) }
26362
+ );
26363
+ }
26364
+ const warnings = kinds.filter((kind) => STEP_LEVEL.includes(kind) || unplaced.has(kind));
26365
+ return { warnings, calls: all };
26071
26366
  }
26072
26367
 
26073
26368
  // dsh/src/inner-monitor-read.js
@@ -26088,6 +26383,8 @@ var isSeq5 = (value) => Number.isSafeInteger(value) && value >= 0;
26088
26383
  var isText5 = (value) => typeof value === "string";
26089
26384
  var isMessage = (value) => isObject8(value) && Array.isArray(value.content);
26090
26385
  var orNull2 = (holds) => (value) => value === null || holds(value);
26386
+ var isOldRead = (value) => isObject8(value) && isText5(value.toolUseId) && isSeq5(value.seq) && isSeq5(value.oldLines) && isSeq5(value.newLines);
26387
+ var oldReadsOf = (slot) => Array.isArray(slot?.oldReads) ? slot.oldReads.filter(isOldRead) : [];
26091
26388
  var isCarrierShape = (event) => Array.isArray(event.sourceEventSeqs) && isSeq5(callSeqOf(event.sourceEventSeqs)) && Array.isArray(event.data.source.slots);
26092
26389
  var bounded = (text) => text.length > PREVIEW_SOURCE_CHARS ? text.slice(0, PREVIEW_SOURCE_CHARS) : text;
26093
26390
  var messageTextOf = (message) => bounded(message.content.filter((block) => block.type === "text").map((block) => block.text).join(""));
@@ -26192,18 +26489,21 @@ function foldCarrier(state, event) {
26192
26489
  if (at < 0) return sealed;
26193
26490
  const carrier = { seq: event.seq, time: event.time, slots: slots.length };
26194
26491
  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
- }
26492
+ const slotDispatches = {};
26493
+ const pending = state.postSeal?.pending ?? {};
26494
+ for (const slot of slots) {
26495
+ const seqs = slot?.seqs;
26496
+ if (!Array.isArray(seqs) || seqs.length === 0 || !seqs.every(isSeq5)) continue;
26497
+ const dispatches = seqs.flatMap((seq) => pending[seq] ?? []);
26498
+ const warnings = new Set(dispatches.map(({ kind }) => kind));
26499
+ if (oldReadsOf(slot).length > 0) warnings.add(OLD_ATTRIBUTION_WARNING);
26500
+ if (warnings.size > 0) slotWarnings[seqs[0]] = [...warnings];
26501
+ if (dispatches.length > 0) slotDispatches[seqs[0]] = dispatches;
26203
26502
  }
26204
26503
  return amended({ ...sealed, postSeal: { first: true, request: null, pending: {} } }, at, {
26205
26504
  carrier,
26206
- ...Object.keys(slotWarnings).length > 0 && { slotWarnings }
26505
+ ...Object.keys(slotWarnings).length > 0 && { slotWarnings },
26506
+ ...Object.keys(slotDispatches).length > 0 && { slotDispatches }
26207
26507
  });
26208
26508
  }
26209
26509
  function foldPostSealRequest(state, event) {
@@ -26229,7 +26529,7 @@ function heldInContext(state, seq) {
26229
26529
  function stateWarningOf(request, call) {
26230
26530
  if (!request.first) return;
26231
26531
  const operation = stateOperationOf(call);
26232
- if (operation !== void 0) return operation === "write" ? "state-write" : request.count === 1 ? "state-check" : "state-mixed";
26532
+ if (operation !== void 0) return operation === "write" ? STATE_WARNING.write : request.count === 1 ? STATE_WARNING.check : STATE_WARNING.mixed;
26233
26533
  }
26234
26534
  function foldToolCall(state, event) {
26235
26535
  const { postSeal } = state;
@@ -26237,9 +26537,8 @@ function foldToolCall(state, event) {
26237
26537
  if (!request || request.turn !== event.data?.turn || request.step !== event.data?.step) return state;
26238
26538
  const warning = recallWarningOf(state, event) ?? stateWarningOf(request, event.data);
26239
26539
  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] } } };
26540
+ const dispatches = postSeal.pending[request.seq] ?? [];
26541
+ return { ...state, postSeal: { ...postSeal, pending: { ...postSeal.pending, [request.seq]: [...dispatches, { kind: warning, seq: event.seq }] } } };
26243
26542
  }
26244
26543
  function payloadOf(message) {
26245
26544
  let payload;
@@ -26304,9 +26603,10 @@ var isCarrierState = (value) => isObject8(value) && isSeq5(value.seq) && Number.
26304
26603
  var isAfterState = (value) => isObject8(value) && isSeq5(value.seq) && orNull2(Number.isFinite)(value.stock) && orNull2(Number.isFinite)(value.miss);
26305
26604
  var isHandoffState = (value) => isObject8(value) && isSeq5(value.id) && Number.isFinite(value.time) && (value.type === "load" || value.type === "continue") && isText5(value.token) && orNull2(isSeq5)(value.handoffId) && orNull2(Number.isFinite)(value.createdAt) && isSeq5(value.epoch) && orNull2(isSeq5)(value.kept) && isSeq5(value.skills) && orNull2(isSeq5)(value.lineage) && orNull2(isSeq5)(value.read) && orNull2(isSeq5)(value.readSeq) && orNull2(isSeq5)(value.followSeq) && orNull2(Number.isFinite)(value.before) && orNull2(isAfterState)(value.after) && orNull2(isSeq5)(value.tailCalls);
26306
26605
  var isWarningsBySeq = (value) => isObject8(value) && Object.entries(value).every(([seq, warnings]) => String(Number(seq)) === seq && isSeq5(Number(seq)) && Array.isArray(warnings) && warnings.length > 0 && warnings.every(isText5));
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));
26606
+ var isDispatchesBySeq = (value) => isObject8(value) && Object.entries(value).every(([seq, dispatches]) => String(Number(seq)) === seq && isSeq5(Number(seq)) && Array.isArray(dispatches) && dispatches.length > 0 && dispatches.every((dispatch) => isObject8(dispatch) && isText5(dispatch.kind) && isSeq5(dispatch.seq)));
26607
+ var isAttemptState = (value) => isObject8(value) && isSeq5(value.id) && Number.isFinite(value.startedAt) && isRange(value.range) && isText5(value.input) && orNull2(isCallState)(value.call) && orNull2(isEndState)(value.end) && orNull2(isCarrierState)(value.carrier) && orNull2(Number.isFinite)(value.before) && (value.estimatedBefore === void 0 || Number.isFinite(value.estimatedBefore)) && orNull2(isQuote)(value.quote) && isSeq5(value.epoch) && (value.slotWarnings === void 0 || isWarningsBySeq(value.slotWarnings)) && (value.slotDispatches === void 0 || isDispatchesBySeq(value.slotDispatches));
26308
26608
  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));
26609
+ var isPostSeal = orNull2((value) => isObject8(value) && typeof value.first === "boolean" && isPostSealRequest(value.request) && isDispatchesBySeq(value.pending));
26310
26610
  var stateSchema2 = {
26311
26611
  parse(value) {
26312
26612
  if (!isObject8(value) || !Array.isArray(value.attempts) || !value.attempts.every(isAttemptState) || !orNull2(isUsageState)(value.lastMainUsage) || !isSourceFacts(value.source) || !Array.isArray(value.handoffs) || !value.handoffs.every(isHandoffState) || !orNull2(isText5)(value.lastCheckpointToken) || !isSeq5(value.lastCheckpointCalls) || !isSeq5(value.openCalls) || !orNull2(Number.isFinite)(value.settlementBefore) || !isPostSeal(value.postSeal) || !orNull2(isText5)(value.sessionId) || !Array.isArray(value.verbatimSeqs) || !value.verbatimSeqs.every(isSeq5)) {
@@ -26338,7 +26638,7 @@ function innerMonitorProjection(kit) {
26338
26638
  };
26339
26639
  return {
26340
26640
  key: MONITOR_PROJECTION_KEY,
26341
- stateVersion: 16,
26641
+ stateVersion: 18,
26342
26642
  stateSchema: stateSchema2,
26343
26643
  init: (header) => ({ attempts: [], lastMainUsage: null, settlementBefore: null, source: initialSourceFacts(), handoffs: [], lastCheckpointToken: null, lastCheckpointCalls: 0, openCalls: 0, postSeal: null, verbatimSeqs: [], sessionId: header?.id ?? null }),
26344
26644
  apply(state, event) {
@@ -26535,12 +26835,13 @@ function committedOf(attempt, log, kit) {
26535
26835
  const { slots } = carrierAt(log, attempt.carrier.seq).data.source;
26536
26836
  return { slots, range: new Set(recordOf(log, attempt.call.seq, INNER_CALL_RECORD_TYPE, kit).range) };
26537
26837
  }
26538
- function placeOf(slot, log) {
26838
+ function placeOf2(slot, log) {
26539
26839
  const events = slot.seqs.map((seq) => loggedEvent(log, seq));
26540
26840
  const step = events.map((event) => eventFactOf(event).step).find((counted) => counted !== null) ?? null;
26541
26841
  return { key: slot.seqs[0], seqs: slot.seqs, turn: step?.turn ?? null, step: step?.step ?? null, source: slotSourceOf(events[0]), events };
26542
26842
  }
26543
26843
  var NOT_COMMITTED = Object.freeze({ kind: "not_committed" });
26844
+ var NOT_TARGET = Object.freeze({ kind: "not_target" });
26544
26845
  function handoffOf(state, id) {
26545
26846
  const handoff = state.handoffs.find((each) => each.id === id);
26546
26847
  if (handoff === void 0) throw new Error(`the inner monitor holds no handoff ${id}`);
@@ -26551,32 +26852,65 @@ function clearingOf(state, id) {
26551
26852
  if (handoff.type !== "continue") throw new Error(`the handoff ${id} is no /sw-continue clear`);
26552
26853
  return handoff;
26553
26854
  }
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 = [];
26855
+ var atCut = (attempt, cut) => ({
26856
+ ...attempt,
26857
+ call: attempt.call !== null && attempt.call.seq <= cut ? attempt.call : null,
26858
+ end: attempt.end !== null && attempt.end.seq <= cut ? attempt.end : null,
26859
+ carrier: attempt.carrier !== null && attempt.carrier.seq <= cut ? attempt.carrier : null
26860
+ });
26861
+ var pricingOf = (state, segment, kit, cut) => rowsOf2({
26862
+ ...state,
26863
+ attempts: state.attempts.filter((attempt) => attempt.epoch === segment && attempt.id <= cut).map((attempt) => atCut(attempt, cut))
26864
+ }, [], kit).map(({ id, status, epoch, contextChange, estimatedBefore, call, stepN, cRatio }) => ({ id, status, epoch, contextChange, estimatedBefore, call: { usage: call.usage }, stepN, cRatio }));
26865
+ function segmentEventsOf(log, segment, through) {
26559
26866
  const events = [];
26560
26867
  let epoch = 0;
26868
+ for (const event of log.values()) {
26869
+ if (startsEpoch(foldInputOf(event))) epoch += 1;
26870
+ if (epoch > segment || event.seq > through) break;
26871
+ if (epoch === segment) events.push(event);
26872
+ }
26873
+ return events;
26874
+ }
26875
+ function settlementEvidenceOf(state, log, sessionId, segment, kit, { tailCalls, through = Number.POSITIVE_INFINITY } = {}) {
26876
+ const events = segmentEventsOf(log, segment, through);
26877
+ const cut = events.at(-1)?.seq ?? -1;
26878
+ const attempts = state.attempts.filter((attempt) => attempt.epoch === segment && attempt.carrier !== null && attempt.carrier.seq <= cut);
26879
+ const postByAttempt = new Map(attempts.map((attempt) => {
26880
+ const seq = afterOf(state.source, attempt)?.seq;
26881
+ return [attempt.id, seq <= cut ? seq : void 0];
26882
+ }));
26883
+ const posts = new Set(postByAttempt.values());
26884
+ const calls = [];
26561
26885
  let pendingPost = false;
26562
26886
  let countedTail = 0;
26563
26887
  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);
26888
+ for (const event of events) {
26569
26889
  if (isCarrier2(event)) pendingPost = false;
26570
26890
  if (!isMainCall(event)) continue;
26571
- if (tailCalls === void 0 && event.seq > lastCarrier) countedTail = callsAfter(countedTail, event);
26891
+ if (event.seq > lastCarrier) countedTail = callsAfter(countedTail, event);
26572
26892
  pendingPost ||= posts.has(event.seq);
26573
26893
  if (isSettlementNoise(event)) continue;
26574
26894
  const usage = callUsageOf(event.data?.usage);
26575
26895
  calls.push({ seq: event.seq, stock: usage === null ? null : stockOf(usage), post: pendingPost });
26576
26896
  pendingPost = false;
26577
26897
  }
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 } : {} };
26898
+ const tail = tailCalls ?? countedTail;
26899
+ const { recall, activity } = settlementRecallOf({ events, log, attempts, postByAttempt, tailCalls: tail, sessionId, isNoise: isSettlementNoise });
26900
+ return {
26901
+ epoch: segment + 1,
26902
+ attempts: pricingOf(state, segment, kit, cut),
26903
+ tailCalls: tail,
26904
+ calls,
26905
+ cut: { segment, through: cut },
26906
+ ...recall === void 0 ? {} : { recall },
26907
+ ...activity === void 0 ? {} : { activity }
26908
+ };
26909
+ }
26910
+ function plainTextOf(event) {
26911
+ const content = (event.data?.message ?? event.data)?.content;
26912
+ const text = Array.isArray(content) ? content.filter((block) => block?.type === "text" && isText5(block.text)).map((block) => block.text).join("") : "";
26913
+ return text === "" ? null : text;
26580
26914
  }
26581
26915
  function filesOf(message) {
26582
26916
  if (carriesEvidence(message.source)) return (carriedEvidence(message.source)?.files ?? []).map(({ path: path3, total, state, runs }) => ({ path: path3, total: state === "empty" ? 0 : total, runs }));
@@ -26635,15 +26969,19 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26635
26969
  const facts = await factsOf(sessionId);
26636
26970
  if (facts === void 0) return void 0;
26637
26971
  const handoff = clearingOf(facts.state, id);
26638
- return settlementEvidenceOf(facts.state, await facts.log(), sessionId, handoff.epoch - 1, handoff.tailCalls);
26972
+ return settlementEvidenceOf(facts.state, await facts.log(), sessionId, handoff.epoch - 1, kit, { tailCalls: handoff.tailCalls });
26639
26973
  },
26640
26974
  async currentSettlement(sessionId) {
26641
26975
  const snapshot = await readStored(sessionId);
26642
26976
  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) };
26977
+ return settlementEvidenceOf(snapshot.state, logOf(snapshot), sessionId, snapshot.state.source.epoch, kit);
26978
+ },
26979
+ async settlementTarget(sessionId, { segment, through, seq }) {
26980
+ const snapshot = await readStored(sessionId);
26981
+ if (snapshot === void 0) return void 0;
26982
+ const log = logOf(snapshot);
26983
+ const target = settlementEvidenceOf(snapshot.state, log, sessionId, segment, kit, { through }).activity?.targets.find((each) => each.seq === seq);
26984
+ return target === void 0 ? NOT_TARGET : { seq, type: target.type, text: plainTextOf(log.get(seq)) };
26647
26985
  },
26648
26986
  async call(sessionId, id) {
26649
26987
  const facts = await factsOf(sessionId);
@@ -26661,7 +26999,7 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26661
26999
  const { slots, range } = committedOf(attempt, log, kit);
26662
27000
  return {
26663
27001
  slots: slots.map((slot) => {
26664
- const { events, seqs, ...place } = placeOf(slot, log);
27002
+ const { events, seqs, ...place } = placeOf2(slot, log);
26665
27003
  const seen = events.filter((event) => range.has(event.seq));
26666
27004
  const joined = (texts) => texts.filter((text) => text !== "").join("\n");
26667
27005
  return { ...place, input: bounded(joined(seen.map(eventPreviewText))), inputDisplay: bounded(joined(seen.map(eventDisplayText))), output: slot.text };
@@ -26678,8 +27016,16 @@ function createMonitorAccess({ sessionOf, readMonitor, live: live2, kit, readSes
26678
27016
  const at = slots.findIndex((each) => each.seqs[0] === key);
26679
27017
  if (at < 0) throw new Error(`the carrier of attempt ${id} holds no slot ${key}`);
26680
27018
  const slot = slots[at];
26681
- const { events, ...place } = placeOf(slot, log);
26682
- return { ...place, number: at + 1, c: slot.text, events: events.map((event) => sourceEventView(event, { visible: range.has(event.seq) })) };
27019
+ const { events, ...place } = placeOf2(slot, log);
27020
+ const tools = slotToolsOf({
27021
+ events,
27022
+ range,
27023
+ log,
27024
+ kinds: attempt.slotWarnings?.[key] ?? [],
27025
+ dispatches: attempt.slotDispatches?.[key] ?? [],
27026
+ oldReads: oldReadsOf(slot)
27027
+ });
27028
+ return { ...place, number: at + 1, c: slot.text, events: events.map((event) => sourceEventView(event, { visible: range.has(event.seq) })), tools };
26683
27029
  }
26684
27030
  };
26685
27031
  }