notesoup 0.47.0 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +1 -1
  2. package/dist/src/boot/render.d.ts +14 -7
  3. package/dist/src/boot/render.js +29 -16
  4. package/dist/src/boot/text.d.ts +25 -4
  5. package/dist/src/boot/text.js +59 -11
  6. package/dist/src/budget/text.d.ts +29 -9
  7. package/dist/src/budget/text.js +51 -10
  8. package/dist/src/claude/helper.d.ts +2 -3
  9. package/dist/src/claude/helper.js +45 -11
  10. package/dist/src/claude/history.d.ts +9 -0
  11. package/dist/src/claude/history.js +271 -0
  12. package/dist/src/dsh/engine.d.ts +2 -1
  13. package/dist/src/dsh/engine.js +18 -9
  14. package/dist/src/dsh/index.js +9 -4
  15. package/dist/src/dsh/window.d.ts +2 -1
  16. package/dist/src/dsh/window.js +14 -8
  17. package/dist/src/history/query.js +59 -81
  18. package/dist/src/notes/address.d.ts +5 -0
  19. package/dist/src/notes/address.js +20 -21
  20. package/dist/src/notes/store.js +12 -19
  21. package/dist/src/pi/boot.d.ts +1 -1
  22. package/dist/src/pi/boot.js +28 -5
  23. package/dist/src/pi/budget.d.ts +0 -2
  24. package/dist/src/pi/budget.js +13 -53
  25. package/dist/src/pi/entries.d.ts +0 -1
  26. package/dist/src/pi/entries.js +0 -1
  27. package/dist/src/pi/history.d.ts +3 -0
  28. package/dist/src/pi/history.js +4 -0
  29. package/dist/src/pi/reset/artifacts.d.ts +7 -2
  30. package/dist/src/pi/reset/artifacts.js +16 -14
  31. package/dist/src/pi/reset/lifecycle.d.ts +21 -25
  32. package/dist/src/pi/reset/lifecycle.js +49 -73
  33. package/dist/src/pi/runtime.js +19 -18
  34. package/dist/src/pi/window.d.ts +12 -6
  35. package/dist/src/pi/window.js +7 -0
  36. package/dist/test/agent-loop.test.js +65 -42
  37. package/dist/test/boot.integration.test.js +119 -16
  38. package/dist/test/budget-settings.integration.test.js +4 -2
  39. package/dist/test/claude-history.test.d.ts +1 -0
  40. package/dist/test/claude-history.test.js +184 -0
  41. package/dist/test/claude-mod.test.js +243 -49
  42. package/dist/test/dsh.test.js +79 -2
  43. package/dist/test/helpers/extension.d.ts +3 -0
  44. package/dist/test/helpers/extension.js +33 -5
  45. package/dist/test/history.integration.test.js +66 -0
  46. package/dist/test/host-neutral.test.js +1 -1
  47. package/dist/test/model-facing-text.test.d.ts +1 -0
  48. package/dist/test/model-facing-text.test.js +181 -0
  49. package/dist/test/notes.integration.test.js +16 -18
  50. package/dist/test/reset-lifecycle.test.js +202 -47
  51. package/docs/architecture.md +3 -3
  52. package/docs/claude-code-mod.md +15 -3
  53. package/docs/dsh.md +1 -1
  54. package/docs/reset-lifecycle.md +32 -20
  55. package/docs/skills.md +1 -1
  56. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  57. package/mods/notesoup/dist/claude/helper.js +836 -92
  58. package/mods/notesoup/hooks/register.ts +154 -52
  59. package/package.json +1 -1
  60. package/src/boot/render.ts +41 -23
  61. package/src/boot/text.ts +68 -11
  62. package/src/budget/text.ts +61 -10
  63. package/src/claude/helper.ts +53 -22
  64. package/src/claude/history.ts +228 -0
  65. package/src/dsh/engine.ts +16 -9
  66. package/src/dsh/index.ts +8 -3
  67. package/src/dsh/window.ts +15 -9
  68. package/src/history/query.ts +57 -82
  69. package/src/notes/address.ts +19 -16
  70. package/src/notes/store.ts +9 -14
  71. package/src/pi/boot.ts +27 -5
  72. package/src/pi/budget.ts +13 -50
  73. package/src/pi/entries.ts +0 -1
  74. package/src/pi/history.ts +7 -2
  75. package/src/pi/reset/artifacts.ts +17 -14
  76. package/src/pi/reset/lifecycle.ts +57 -80
  77. package/src/pi/runtime.ts +19 -18
  78. package/src/pi/window.ts +11 -1
@@ -2434,9 +2434,9 @@ function Set4(value, pointer, next) {
2434
2434
  AssertNotRoot(indices);
2435
2435
  AssertIndices(indices);
2436
2436
  const [head, index] = TakeIndexRight(indices);
2437
- const parent = GetIndices(head, value);
2438
- AssertCanSet(parent);
2439
- parent[index] = next;
2437
+ const parent2 = GetIndices(head, value);
2438
+ AssertCanSet(parent2);
2439
+ parent2[index] = next;
2440
2440
  return value;
2441
2441
  }
2442
2442
  function Delete(value, pointer) {
@@ -2444,12 +2444,12 @@ function Delete(value, pointer) {
2444
2444
  AssertNotRoot(indices);
2445
2445
  AssertIndices(indices);
2446
2446
  const [head, index] = TakeIndexRight(indices);
2447
- const parent = GetIndices(head, value);
2448
- AssertCanSet(parent);
2449
- if (guard_exports.IsArray(parent) && IsNumericIndex(index)) {
2450
- parent.splice(+index, 1);
2447
+ const parent2 = GetIndices(head, value);
2448
+ AssertCanSet(parent2);
2449
+ if (guard_exports.IsArray(parent2) && IsNumericIndex(index)) {
2450
+ parent2.splice(+index, 1);
2451
2451
  } else {
2452
- delete parent[index];
2452
+ delete parent2[index];
2453
2453
  }
2454
2454
  return value;
2455
2455
  }
@@ -3402,15 +3402,15 @@ function IntersectOptions(type) {
3402
3402
 
3403
3403
  // node_modules/typebox/build/type/types/_codec.mjs
3404
3404
  var EncodeBuilder = class {
3405
- constructor(type, decode) {
3405
+ constructor(type, decode2) {
3406
3406
  this.type = type;
3407
- this.decode = decode;
3407
+ this.decode = decode2;
3408
3408
  }
3409
3409
  Encode(callback) {
3410
3410
  const type = this.type;
3411
- const decode = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
3411
+ const decode2 = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
3412
3412
  const encode = IsCodec(type) ? (value) => type["~codec"].encode(callback(value)) : callback;
3413
- const codec = { decode, encode };
3413
+ const codec = { decode: decode2, encode };
3414
3414
  return memory_exports.Update(this.type, { "~codec": codec }, {});
3415
3415
  }
3416
3416
  };
@@ -5962,8 +5962,8 @@ function FromObject5(properties) {
5962
5962
 
5963
5963
  // node_modules/typebox/build/type/engine/object/from_tuple.mjs
5964
5964
  function FromTuple(types) {
5965
- const object = TupleToObject(Tuple(types));
5966
- const result = FromType8(object);
5965
+ const object2 = TupleToObject(Tuple(types));
5966
+ const result = FromType8(object2);
5967
5967
  return result;
5968
5968
  }
5969
5969
 
@@ -8052,6 +8052,15 @@ function physicalPath(scope, vpath, identity2, who) {
8052
8052
 
8053
8053
  // src/notes/address.ts
8054
8054
  var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
8055
+ var HOME_HEADS = /* @__PURE__ */ new Map([
8056
+ ["project", { scope: "project" }],
8057
+ ["human", { scope: "human" }],
8058
+ ["self", { scope: "agent" }],
8059
+ ["model", { scope: "model" }],
8060
+ ["projects", { scope: "project", home: "project" }],
8061
+ ["agents", { scope: "agent", home: "agents" }],
8062
+ ["models", { scope: "model", home: "models" }]
8063
+ ]);
8055
8064
  function globToRegExp(pattern) {
8056
8065
  let source = "^";
8057
8066
  for (let index = 0; index < pattern.length; index++) {
@@ -8084,23 +8093,15 @@ function assertAddress(value) {
8084
8093
  let path = value;
8085
8094
  let who;
8086
8095
  if (value.startsWith("@")) {
8087
- const rest = value.slice(1);
8088
- const headEnd = rest.indexOf("/");
8089
- const head = headEnd === -1 ? rest : rest.slice(0, headEnd);
8090
- const tail = headEnd === -1 ? "" : rest.slice(headEnd + 1);
8091
- path = tail;
8092
- if (head === "project") scope = "project";
8093
- else if (head === "human") scope = "human";
8094
- else if (head === "self") scope = "agent";
8095
- else if (head === "model") scope = "model";
8096
- else if (head === "projects" || head === "agents" || head === "models") {
8097
- const nameEnd = tail.indexOf("/");
8098
- who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
8096
+ const [rawHead, ...tail] = value.slice(1).split("/");
8097
+ const head = HOME_HEADS.get(rawHead);
8098
+ if (head === void 0) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8099
+ scope = head.scope;
8100
+ if (head.home === void 0) path = tail.join("/");
8101
+ else {
8102
+ who = tail[0] ?? "";
8099
8103
  if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8100
- scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
8101
- path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
8102
- } else {
8103
- throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8104
+ path = tail.slice(1).join("/");
8104
8105
  }
8105
8106
  if (path === "" && scope !== "agent" && scope !== "model") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
8106
8107
  if (path === "" && who === void 0) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
@@ -8304,9 +8305,9 @@ function gitRoot(cwd) {
8304
8305
  let dir = resolve2(cwd);
8305
8306
  for (; ; ) {
8306
8307
  if (existsSync(join2(dir, ".git"))) return repositoryRoot(dir);
8307
- const parent = dirname(dir);
8308
- if (parent === dir) return void 0;
8309
- dir = parent;
8308
+ const parent2 = dirname(dir);
8309
+ if (parent2 === dir) return void 0;
8310
+ dir = parent2;
8310
8311
  }
8311
8312
  }
8312
8313
  function repositoryRoot(dir) {
@@ -8401,19 +8402,14 @@ async function walkMarkdown(dir, base = dir) {
8401
8402
  }
8402
8403
  async function homesForPattern(pattern, identity2) {
8403
8404
  if (!pattern || !pattern.startsWith("@")) return void 0;
8404
- const head = /^@([^/]+)\//.exec(pattern)?.[1];
8405
- if (head === "project") return [{ scope: "project" }];
8406
- if (head === "human") return [{ scope: "human" }];
8407
- if (head === "self") return [{ scope: "agent" }];
8408
- if (head === "model") return [{ scope: "model" }];
8409
- if (head === "projects" || head === "agents" || head === "models") {
8410
- const scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
8411
- const name = pattern.slice(head.length + 2).split("/")[0] ?? "";
8412
- if (name.length > 0 && !/[*?]/.test(name)) return [{ scope, who: assertWho(name) }];
8413
- const names = head === "projects" ? projectHomes(identity2.home).map((home) => home.name) : await namespaceSlugs(head, identity2.home);
8414
- return names.map((who) => ({ scope, who }));
8415
- }
8416
- return [];
8405
+ const [rawHead, ...tail] = pattern.split("/");
8406
+ const head = tail.length === 0 ? void 0 : HOME_HEADS.get(rawHead.slice(1));
8407
+ if (head === void 0) return [];
8408
+ if (head.home === void 0) return [{ scope: head.scope }];
8409
+ const name = tail[0];
8410
+ if (name !== void 0 && name.length > 0 && !/[*?]/.test(name)) return [{ scope: head.scope, who: assertWho(name) }];
8411
+ const names = head.home === "project" ? projectHomes(identity2.home).map((home) => home.name) : await namespaceSlugs(head.home, identity2.home);
8412
+ return names.map((who) => ({ scope: head.scope, who }));
8417
8413
  }
8418
8414
  function normalizePattern(pattern, identity2) {
8419
8415
  if (!pattern) return pattern;
@@ -8733,6 +8729,7 @@ var TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
8733
8729
  var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
8734
8730
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
8735
8731
  var MAX_READ_WINDOW_CHARS = 5e4;
8732
+ var HISTORY_PREVIEW_CHARS = 1200;
8736
8733
  function prefixFit(text, fits) {
8737
8734
  if (fits(text)) return text;
8738
8735
  const chars = Array.from(text);
@@ -8817,6 +8814,92 @@ function renderTextWindow(window) {
8817
8814
  // src/history/history.ts
8818
8815
  var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
8819
8816
  var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
8817
+ function isTextContent(part) {
8818
+ return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
8819
+ }
8820
+ function contentText(content) {
8821
+ if (typeof content === "string") return content;
8822
+ return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
8823
+ }
8824
+ function argumentText(execution) {
8825
+ return execution.arguments === void 0 ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
8826
+ }
8827
+ function nestedCallLine(call) {
8828
+ const parts = [`${call.id} ${call.name} [${call.status}]`];
8829
+ if (call.durationMs !== void 0) parts.push(`${call.durationMs}ms`);
8830
+ if (call.error !== void 0) parts.push(`error: ${call.error}`);
8831
+ parts.push(call.arguments === void 0 ? call.argumentsBytes === void 0 ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)` : JSON.stringify(call.arguments));
8832
+ return `- ${parts.join(" ")}`;
8833
+ }
8834
+ function historyDocument(event) {
8835
+ if (event.execution === void 0) return event.text;
8836
+ const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
8837
+ if (event.text !== "") sections.push(`--- output ---
8838
+ ${event.text}`);
8839
+ const nested = event.execution.nestedCalls;
8840
+ if (nested !== void 0) {
8841
+ const header2 = nested.complete ? "complete" : "incomplete";
8842
+ sections.push(`--- nested calls (${header2}, ${nested.calls.length} recorded) ---
8843
+ ${nested.calls.map(nestedCallLine).join("\n")}`);
8844
+ }
8845
+ return sections.join("\n");
8846
+ }
8847
+ var documents = /* @__PURE__ */ new WeakMap();
8848
+ function eventDocument(event) {
8849
+ const cached = documents.get(event);
8850
+ if (cached !== void 0) return cached;
8851
+ const text = historyDocument(event);
8852
+ documents.set(event, text);
8853
+ return text;
8854
+ }
8855
+ function toolEvent(item, result) {
8856
+ const run = result ?? item;
8857
+ const status = item.role === "tool_call" && result === void 0 ? "unfinished" : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
8858
+ const truncated = run.outputTruncated === true;
8859
+ return {
8860
+ seq: item.seq,
8861
+ windowId: item.windowId,
8862
+ role: "tool",
8863
+ text: result?.text ?? (item.role === "tool" ? item.text : ""),
8864
+ createdAt: item.createdAt,
8865
+ execution: {
8866
+ name: item.toolName ?? "unknown",
8867
+ status,
8868
+ // A call records its arguments; a bare result records none, and gets none invented.
8869
+ ...item.arguments === void 0 ? {} : { arguments: item.arguments },
8870
+ ...truncated ? { outputTruncated: true, ...run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {} } : {},
8871
+ ...run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}
8872
+ }
8873
+ };
8874
+ }
8875
+ function projectHistory(rawWindows, highestSeq, branchSeqs) {
8876
+ const raw = rawWindows.flatMap((current) => current.items);
8877
+ const resultsById = /* @__PURE__ */ new Map();
8878
+ for (const item of raw) {
8879
+ if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId)) resultsById.set(item.toolCallId, item);
8880
+ }
8881
+ const pairedResults = /* @__PURE__ */ new Map();
8882
+ const consumed = /* @__PURE__ */ new Set();
8883
+ const windows = rawWindows.map((current) => ({
8884
+ windowId: current.windowId,
8885
+ ...current.createdAt ? { createdAt: current.createdAt } : {},
8886
+ items: current.items.flatMap((item) => {
8887
+ if (consumed.has(item.seq)) return [];
8888
+ if (item.role === "tool_call") {
8889
+ const result = item.toolCallId ? resultsById.get(item.toolCallId) : void 0;
8890
+ const paired = result && result.seq > item.seq && !consumed.has(result.seq) ? result : void 0;
8891
+ if (paired) {
8892
+ consumed.add(paired.seq);
8893
+ pairedResults.set(paired.seq, item.seq);
8894
+ }
8895
+ return [toolEvent(item, paired)];
8896
+ }
8897
+ if (item.role === "tool") return [toolEvent(item)];
8898
+ return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
8899
+ })
8900
+ }));
8901
+ return { windows, highestSeq, branchSeqs, pairedResults };
8902
+ }
8820
8903
  var NestedCallSummarySchema = typebox_exports.Object({
8821
8904
  call_count: typebox_exports.Integer({ minimum: 0 }),
8822
8905
  complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
@@ -8827,6 +8910,20 @@ var ToolSummarySchema = typebox_exports.Object({
8827
8910
  output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
8828
8911
  full_output_path: typebox_exports.Optional(typebox_exports.String())
8829
8912
  }, { additionalProperties: false });
8913
+ function toolSummary(event) {
8914
+ const execution = event.execution;
8915
+ if (!execution) return {};
8916
+ return {
8917
+ tool: execution.name,
8918
+ tool_status: execution.status,
8919
+ ...execution.outputTruncated ? { output_truncated: true } : {},
8920
+ ...execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}
8921
+ };
8922
+ }
8923
+ function nestedCallSummary(event) {
8924
+ const nested = event.execution?.nestedCalls;
8925
+ return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
8926
+ }
8830
8927
  var HistoryPageItemSchema = typebox_exports.Object({
8831
8928
  seq: typebox_exports.Integer({ minimum: 1 }),
8832
8929
  window_id: typebox_exports.String(),
@@ -8844,9 +8941,52 @@ var HistoryFoldedRowSchema = typebox_exports.Object({
8844
8941
  count: typebox_exports.Integer({ minimum: 1 }),
8845
8942
  tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
8846
8943
  }, { additionalProperties: false });
8944
+ var MAX_FOLD_TOOL_NAMES = 20;
8945
+ var MAX_FOLD_TOOL_NAME_CHARS = 120;
8946
+ function visibleItem(event, maxChars, matchOffset) {
8947
+ const document = eventDocument(event);
8948
+ const chars = Array.from(document);
8949
+ const start = matchOffset ?? 0;
8950
+ const limit = Math.max(0, maxChars);
8951
+ const truncated = start > 0 || start + limit < chars.length;
8952
+ return {
8953
+ seq: event.seq,
8954
+ window_id: event.windowId,
8955
+ role: event.role,
8956
+ created_at: event.createdAt ?? null,
8957
+ ...toolSummary(event),
8958
+ content: truncated ? chars.slice(start, start + limit).join("") : document,
8959
+ truncated,
8960
+ ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
8961
+ };
8962
+ }
8963
+ function allItems(projection) {
8964
+ return projection.windows.flatMap((current) => current.items);
8965
+ }
8966
+ function unknownWindowId(projection, params) {
8967
+ if (typeof params.window_id !== "string") return void 0;
8968
+ const known = projection.windows.map((current) => current.windowId);
8969
+ return known.includes(params.window_id) ? void 0 : { message: `No window "${params.window_id}" in this session`, known };
8970
+ }
8971
+ function inSelection(event, params) {
8972
+ if (typeof params.window_id === "string" && params.window_id !== event.windowId) return false;
8973
+ if (params.after_seq !== void 0 && event.seq <= params.after_seq) return false;
8974
+ if (params.before_seq !== void 0 && event.seq >= params.before_seq) return false;
8975
+ if (params.sinceMs === void 0 && params.untilMs === void 0) return true;
8976
+ if (event.createdAt === void 0) return false;
8977
+ const at = Date.parse(event.createdAt);
8978
+ return !Number.isNaN(at) && (params.sinceMs === void 0 || at >= params.sinceMs) && (params.untilMs === void 0 || at < params.untilMs);
8979
+ }
8980
+ function filteredItems(projection, params, conversation) {
8981
+ let items = allItems(projection).filter((item) => inSelection(item, params));
8982
+ if (params.roles) items = items.filter((item) => params.roles.includes(item.role));
8983
+ if (!params.roles && conversation) items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
8984
+ return items.sort((a, b) => a.seq - b.seq);
8985
+ }
8847
8986
 
8848
8987
  // src/tools/schema.ts
8849
8988
  var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
8989
+ var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
8850
8990
  var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
8851
8991
  var InvalidQueryError = class extends Error {
8852
8992
  constructor(message) {
@@ -9186,6 +9326,535 @@ var notesSearch = {
9186
9326
  render: (result) => renderOutcome(result, renderSearchData)
9187
9327
  };
9188
9328
 
9329
+ // src/history/query.ts
9330
+ var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
9331
+ function timeBound(name, value) {
9332
+ if (value === void 0) return success(void 0);
9333
+ const match = ISO_8601.exec(value);
9334
+ const at = match === null ? void 0 : Date.parse(match[1] === void 0 ? `${value}Z` : value);
9335
+ return at === void 0 || Number.isNaN(at) ? failure("invalid_time", `\`${name}\` isn't an ISO 8601 time: "${value}".`) : success(at);
9336
+ }
9337
+ function resolveTimeBounds(params) {
9338
+ const since = timeBound("since", params.since);
9339
+ if (!since.ok) return since;
9340
+ const until = timeBound("until", params.until);
9341
+ if (!until.ok) return until;
9342
+ if (since.data !== void 0 && until.data !== void 0 && since.data >= until.data) {
9343
+ return failure("invalid_time", "`since` must be earlier than `until`.");
9344
+ }
9345
+ return success({ ...since.data === void 0 ? {} : { sinceMs: since.data }, ...until.data === void 0 ? {} : { untilMs: until.data } });
9346
+ }
9347
+ var HistoryOlderSchema = typebox_exports.Object({
9348
+ before_seq: typebox_exports.Integer({ minimum: 1 })
9349
+ }, { additionalProperties: false });
9350
+ var HistoryNewerSchema = typebox_exports.Object({
9351
+ after_seq: typebox_exports.Integer({ minimum: 1 }),
9352
+ from: typebox_exports.Literal("oldest")
9353
+ }, { additionalProperties: false });
9354
+ var HistoryPageSchema = typebox_exports.Object({
9355
+ items: typebox_exports.Array(typebox_exports.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
9356
+ page_older: typebox_exports.Union([HistoryOlderSchema, typebox_exports.Null()]),
9357
+ page_newer: typebox_exports.Union([HistoryNewerSchema, typebox_exports.Null()])
9358
+ }, { additionalProperties: false });
9359
+ function truncateHistoryItem(item, fits) {
9360
+ if (fits(item)) return item;
9361
+ const shrinkContent = (base) => ({
9362
+ ...base,
9363
+ truncated: true,
9364
+ content: prefixFit(base.content, (candidate) => fits({ ...base, truncated: true, content: candidate }))
9365
+ });
9366
+ const withContent = shrinkContent(item);
9367
+ if (fits(withContent)) return withContent;
9368
+ if (item.tool === void 0) return withContent;
9369
+ const { tool: _dropped, ...withoutName } = item;
9370
+ return fits(withoutName) ? withoutName : shrinkContent(withoutName);
9371
+ }
9372
+ function foldedRun(events) {
9373
+ if (events.length === 0) return void 0;
9374
+ const counts = /* @__PURE__ */ new Map();
9375
+ for (const event of events) {
9376
+ if (event.role !== "tool") continue;
9377
+ const name = event.execution?.name ?? "unknown";
9378
+ counts.set(name, (counts.get(name) ?? 0) + 1);
9379
+ }
9380
+ const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
9381
+ const tools = Object.fromEntries(entries);
9382
+ return { folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9383
+ }
9384
+ function prepareSelection(projection, params) {
9385
+ const folds = !params.roles && params.query === void 0;
9386
+ const candidates = [];
9387
+ let run = [];
9388
+ for (const event of filteredItems(projection, params, false)) {
9389
+ if (folds && (event.role === "tool" || event.role === "context")) {
9390
+ run.push(event);
9391
+ continue;
9392
+ }
9393
+ if (folds && eventDocument(event) === "") continue;
9394
+ const matchOffset = params.query === void 0 ? void 0 : earliestMatchOffsetChars(eventDocument(event), params.query);
9395
+ if (matchOffset !== void 0 && matchOffset < 0) continue;
9396
+ candidates.push({ event, matchOffset, before: foldedRun(run) });
9397
+ run = [];
9398
+ }
9399
+ return { candidates, tail: foldedRun(run) };
9400
+ }
9401
+ function pageData(prepared, start, end, maxChars, preview) {
9402
+ const { candidates, tail } = prepared;
9403
+ const items = [];
9404
+ for (let index = start; index < end; index++) {
9405
+ const candidate = candidates[index];
9406
+ if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
9407
+ items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
9408
+ }
9409
+ if (end === candidates.length && tail) items.push(tail);
9410
+ return {
9411
+ items,
9412
+ page_older: start > 0 && start < end ? { before_seq: candidates[start].event.seq } : null,
9413
+ page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1].event.seq, from: "oldest" } : null
9414
+ };
9415
+ }
9416
+ function selectPage(projection, params, fits, maxChars) {
9417
+ const bounds = resolveTimeBounds(params);
9418
+ if (!bounds.ok) return bounds;
9419
+ let queries;
9420
+ try {
9421
+ queries = searchQueries(params.query);
9422
+ } catch (error) {
9423
+ if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
9424
+ throw error;
9425
+ }
9426
+ const scoped = { ...params, ...bounds.data, query: queries.length ? queries : void 0 };
9427
+ const prepared = prepareSelection(projection, scoped);
9428
+ const { candidates } = prepared;
9429
+ const newest = scoped.from !== "oldest";
9430
+ let start = newest ? candidates.length : 0;
9431
+ let end = start;
9432
+ const limit = Math.max(1, scoped.limit ?? 20);
9433
+ for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
9434
+ const nextStart = newest ? start - 1 : start;
9435
+ const nextEnd = newest ? end : end + 1;
9436
+ if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
9437
+ start = nextStart;
9438
+ end = nextEnd;
9439
+ continue;
9440
+ }
9441
+ if (start === end) {
9442
+ start = nextStart;
9443
+ end = nextEnd;
9444
+ const candidate = candidates[start];
9445
+ candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
9446
+ }
9447
+ break;
9448
+ }
9449
+ const page = pageData(prepared, start, end, maxChars);
9450
+ if (!fits(page)) {
9451
+ return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
9452
+ }
9453
+ return success(page);
9454
+ }
9455
+
9456
+ // src/tools/history.ts
9457
+ var HistoryReadDataSchema = typebox_exports.Object({
9458
+ seq: typebox_exports.Integer({ minimum: 1 }),
9459
+ window_id: typebox_exports.String(),
9460
+ role: HistoryRoleSchema,
9461
+ created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
9462
+ ...ToolSummarySchema.properties,
9463
+ nested_calls: typebox_exports.Optional(NestedCallSummarySchema),
9464
+ ...TextWindowSchema.properties
9465
+ }, { additionalProperties: false });
9466
+ var HistoryWindowsDataSchema = typebox_exports.Object({
9467
+ session_id: typebox_exports.String(),
9468
+ windows: typebox_exports.Array(typebox_exports.Object({
9469
+ window_id: typebox_exports.String(),
9470
+ created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
9471
+ first_seq: typebox_exports.Union([typebox_exports.Integer({ minimum: 1 }), typebox_exports.Null()]),
9472
+ last_seq: typebox_exports.Union([typebox_exports.Integer({ minimum: 1 }), typebox_exports.Null()])
9473
+ }, { additionalProperties: false })),
9474
+ more: typebox_exports.Integer({ minimum: 0, description: "How many more were left out." })
9475
+ }, { additionalProperties: false });
9476
+ function header(item) {
9477
+ return `seq ${item.seq} | window ${item.window_id} | ${item.role}`;
9478
+ }
9479
+ function toolHeader(item) {
9480
+ if (item.role !== "tool") return void 0;
9481
+ const parts = [`tool ${item.tool}`, `status ${item.tool_status}`];
9482
+ if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
9483
+ if (item.nested_calls) {
9484
+ parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
9485
+ }
9486
+ return parts.join(" | ");
9487
+ }
9488
+ function renderPageItem(item) {
9489
+ const tool = toolHeader(item);
9490
+ const lines = tool === void 0 ? [header(item)] : [header(item), tool];
9491
+ if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
9492
+ lines.push(item.content);
9493
+ return lines.join("\n");
9494
+ }
9495
+ function renderFoldedRow(row) {
9496
+ const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
9497
+ const expand = `
9498
+ \u2192 expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
9499
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
9500
+ }
9501
+ function renderPage(page) {
9502
+ if (page.items.length === 0) return "No events match these filters.";
9503
+ const body = page.items.map((item) => "folded" in item ? renderFoldedRow(item) : renderPageItem(item)).join("\n\n");
9504
+ const cursors = [
9505
+ page.page_older === null ? "" : `\u2192 older: ${JSON.stringify(page.page_older)}`,
9506
+ page.page_newer === null ? "" : `\u2192 newer: ${JSON.stringify(page.page_newer)}`
9507
+ ].filter((line) => line !== "");
9508
+ return cursors.length === 0 ? body : `${body}
9509
+
9510
+ ${cursors.join(" | ")}`;
9511
+ }
9512
+ function renderRead(data) {
9513
+ const tool = toolHeader(data);
9514
+ const afterSeq = data.seq - 10;
9515
+ const neighborhood = `neighborhood \u2192 \`history_list\`(${JSON.stringify({ ...afterSeq >= 1 ? { after_seq: afterSeq } : {}, before_seq: data.seq + 10 })})`;
9516
+ return [header(data), ...tool ? [tool] : [], neighborhood, "", renderTextWindow(data)].join("\n");
9517
+ }
9518
+ function pageFits(page) {
9519
+ return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
9520
+ }
9521
+ var MAX_REPORTED_WINDOWS = 5;
9522
+ function knownWindowSuffix(known) {
9523
+ return known.length === 0 ? "" : `; its windows: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
9524
+ }
9525
+ var PREVIOUS_WINDOW = "@previous";
9526
+ function resolveWindowId(projection, windowId) {
9527
+ if (windowId !== PREVIOUS_WINDOW) return { ok: true, window_id: windowId };
9528
+ const previous = projection.windows.at(-2);
9529
+ if (previous !== void 0) return { ok: true, window_id: previous.windowId };
9530
+ const known = projection.windows.map((current) => current.windowId);
9531
+ return { ok: false, outcome: failure("unknown_window_id", `"${PREVIOUS_WINDOW}" has nothing to point at: this session has no window before the current one${knownWindowSuffix(known)}.`) };
9532
+ }
9533
+ function badWindowId(projection, params) {
9534
+ const badWindow = unknownWindowId(projection, params);
9535
+ if (!badWindow) return void 0;
9536
+ return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}.`);
9537
+ }
9538
+ var historyWindowsParameters = typebox_exports.Object({}, { additionalProperties: false });
9539
+ var historyWindows = {
9540
+ name: "history_windows",
9541
+ label: "History list windows",
9542
+ description: "List this session's context windows, oldest first, with seq ranges.",
9543
+ parameters: historyWindowsParameters,
9544
+ outputSchema: resultSchema(HistoryWindowsDataSchema),
9545
+ async execute(_params, projection, sessionId) {
9546
+ const data = { session_id: sessionId, windows: [], more: projection.windows.length };
9547
+ const fits = (candidate) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
9548
+ for (const window of projection.windows) {
9549
+ let first = null;
9550
+ let last = null;
9551
+ for (const event of window.items) {
9552
+ first = first === null ? event.seq : Math.min(first, event.seq);
9553
+ last = last === null ? event.seq : Math.max(last, event.seq);
9554
+ }
9555
+ const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last };
9556
+ if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 })) break;
9557
+ data.windows.push(row);
9558
+ data.more--;
9559
+ }
9560
+ return fits(data) ? success(data) : failure("output_too_large", `The session id alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry.`);
9561
+ },
9562
+ render: (result) => renderOutcome(result, renderWindows)
9563
+ };
9564
+ function renderWindows(data) {
9565
+ const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
9566
+ if (data.more > 0) lines.push(`${data.more} more windows not shown; every \`history_list\` event also names its window.`);
9567
+ return lines.join("\n");
9568
+ }
9569
+ var historyListParameters = typebox_exports.Object({
9570
+ query: typebox_exports.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
9571
+ roles: historyRoles(),
9572
+ before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
9573
+ after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
9574
+ since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
9575
+ until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
9576
+ from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
9577
+ window_id: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
9578
+ limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
9579
+ max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` }))
9580
+ }, { additionalProperties: false });
9581
+ var historyList = {
9582
+ name: "history_list",
9583
+ label: "History list items",
9584
+ description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
9585
+ parameters: historyListParameters,
9586
+ outputSchema: resultSchema(HistoryPageSchema),
9587
+ async execute(params, projection) {
9588
+ const resolved = resolveWindowId(projection, params.window_id);
9589
+ if (!resolved.ok) return resolved.outcome;
9590
+ const scoped = { ...params, window_id: resolved.window_id };
9591
+ const badWindow = badWindowId(projection, scoped);
9592
+ if (badWindow) return badWindow;
9593
+ return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
9594
+ },
9595
+ render: (result) => renderOutcome(result, renderPage)
9596
+ };
9597
+ var historyReadParameters = typebox_exports.Object({ seq: typebox_exports.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
9598
+ var historyRead = {
9599
+ name: "history_read",
9600
+ label: "History read item",
9601
+ description: "Read one event in full: tool arguments, output, and nested calls.",
9602
+ parameters: historyReadParameters,
9603
+ outputSchema: resultSchema(HistoryReadDataSchema),
9604
+ async execute(params, projection) {
9605
+ const item = allItems(projection).find((event) => event.seq === params.seq);
9606
+ if (item === void 0 && params.seq > projection.highestSeq) {
9607
+ return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
9608
+ }
9609
+ if (!projection.branchSeqs.has(params.seq)) {
9610
+ return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
9611
+ }
9612
+ if (item === void 0) {
9613
+ const callSeq = projection.pairedResults.get(params.seq);
9614
+ if (callSeq !== void 0) {
9615
+ return failure("not_an_event", `Seq ${params.seq} is a tool result, shown together with its call; read seq ${callSeq} instead.`);
9616
+ }
9617
+ return failure("unknown_seq", `Seq ${params.seq} holds nothing to read.`);
9618
+ }
9619
+ const document = eventDocument(item);
9620
+ const totalChars = Array.from(document).length;
9621
+ if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
9622
+ return failure("invalid_offset", `This event ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
9623
+ }
9624
+ return readTextWindow(
9625
+ document,
9626
+ params.offset_chars,
9627
+ params.max_chars,
9628
+ (window) => ({
9629
+ seq: item.seq,
9630
+ window_id: item.windowId,
9631
+ role: item.role,
9632
+ created_at: item.createdAt ?? null,
9633
+ ...toolSummary(item),
9634
+ ...nestedCallSummary(item),
9635
+ ...window
9636
+ }),
9637
+ (result) => renderOutcome(result, renderRead)
9638
+ );
9639
+ },
9640
+ render: (result) => renderOutcome(result, renderRead)
9641
+ };
9642
+
9643
+ // src/claude/history.ts
9644
+ import { readFile as readFile2 } from "node:fs/promises";
9645
+ import { isDeepStrictEqual } from "node:util";
9646
+ var METADATA = /* @__PURE__ */ new Set([
9647
+ "queue-operation",
9648
+ "last-prompt",
9649
+ "atis-latch",
9650
+ "mode",
9651
+ "permission-mode",
9652
+ "file-history-snapshot",
9653
+ "cost-state",
9654
+ "summary",
9655
+ "custom-title",
9656
+ "agent-name",
9657
+ "agent-color",
9658
+ "tag",
9659
+ "session-title",
9660
+ "progress"
9661
+ ]);
9662
+ var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
9663
+ var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
9664
+ function object(value) {
9665
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9666
+ }
9667
+ function requiredString(value, field) {
9668
+ if (typeof value !== "string" || value.length === 0) throw new Error(`invalid Claude transcript ${field}`);
9669
+ return value;
9670
+ }
9671
+ function parent(row) {
9672
+ if (row.parentUuid === null) return void 0;
9673
+ return requiredString(row.parentUuid, "parentUuid");
9674
+ }
9675
+ function boundary(row) {
9676
+ return row.type === "system" && row.subtype === "compact_boundary";
9677
+ }
9678
+ function rowsOf(text) {
9679
+ const lines = text.split("\n"), rows = [];
9680
+ for (let index = 0; index < lines.length; index++) {
9681
+ const line = lines[index];
9682
+ if (line.trim() === "") continue;
9683
+ let value;
9684
+ try {
9685
+ value = JSON.parse(line);
9686
+ } catch {
9687
+ if (index === lines.length - 1 && !text.endsWith("\n")) break;
9688
+ throw new Error(`malformed Claude transcript JSON at line ${index + 1}`);
9689
+ }
9690
+ if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${index + 1}`);
9691
+ rows.push(value);
9692
+ }
9693
+ return rows;
9694
+ }
9695
+ function blocksOf(value) {
9696
+ if (typeof value === "string") return [{ type: "text", text: value }];
9697
+ if (!Array.isArray(value)) throw new Error("invalid Claude transcript message content");
9698
+ return value.map((block) => {
9699
+ if (!object(block) || typeof block.type !== "string") throw new Error("invalid Claude transcript content block");
9700
+ if (block.type === "text") {
9701
+ if (typeof block.text !== "string") throw new Error("invalid Claude transcript text block");
9702
+ } else if (block.type !== "tool_use" && block.type !== "tool_result" && !NON_TEXT_BLOCKS.has(block.type)) {
9703
+ throw new Error(`unsupported Claude transcript content block: ${block.type}`);
9704
+ }
9705
+ return block;
9706
+ });
9707
+ }
9708
+ function decode(row, seq) {
9709
+ if (row.type === "system" && row.subtype === "turn_duration") return [];
9710
+ const common = { windowId: "", ...typeof row.timestamp === "string" ? { createdAt: row.timestamp } : {} };
9711
+ let blocks, role;
9712
+ if (row.type === "user" || row.type === "assistant") {
9713
+ if (!object(row.message) || row.message.role !== row.type) throw new Error("invalid Claude transcript message role");
9714
+ blocks = blocksOf(row.message.content);
9715
+ role = row.isCompactSummary === true || row.isMeta === true ? "system" : row.type;
9716
+ } else if (row.type === "system") {
9717
+ blocks = blocksOf(row.content);
9718
+ role = "system";
9719
+ } else {
9720
+ if (row.rendered === void 0) blocks = [];
9721
+ else if (Array.isArray(row.rendered)) blocks = row.rendered.flatMap((message) => {
9722
+ if (!object(message)) throw new Error("invalid Claude transcript rendered attachment");
9723
+ return blocksOf(message.content);
9724
+ });
9725
+ else throw new Error("invalid Claude transcript rendered attachment");
9726
+ role = "system";
9727
+ }
9728
+ const items = [{ ...common, seq, role, text: contentText(blocks) }];
9729
+ for (const block of blocks) {
9730
+ if (block.type === "tool_use") {
9731
+ if (!object(block.input)) throw new Error("invalid Claude transcript tool arguments");
9732
+ items.push({ ...common, seq: seq + items.length, role: "tool_call", text: "", toolName: requiredString(block.name, "tool name"), toolCallId: requiredString(block.id, "tool id"), arguments: block.input });
9733
+ } else if (block.type === "tool_result") {
9734
+ if (block.is_error !== void 0 && typeof block.is_error !== "boolean") throw new Error("invalid Claude transcript tool error flag");
9735
+ const output = block.content === void 0 ? "" : contentText(blocksOf(block.content));
9736
+ items.push({ ...common, seq: seq + items.length, role: "tool", text: output, toolCallId: requiredString(block.tool_use_id, "tool result id"), toolError: block.is_error === true });
9737
+ }
9738
+ }
9739
+ return items;
9740
+ }
9741
+ var BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
9742
+ var BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
9743
+ var BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
9744
+ function bootOrdinal(row, sessionId, retained) {
9745
+ if (!retained || row.type !== "user" || !object(row.message)) return void 0;
9746
+ const text = contentText(row.message.content);
9747
+ if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text)) return void 0;
9748
+ const prefix = `Current context window id: claude:${sessionId}:`;
9749
+ const suffix = text.split("\n").find((line) => line.startsWith(prefix))?.slice(prefix.length);
9750
+ if (suffix === void 0 || !/^\d+$/.test(suffix)) return void 0;
9751
+ const ordinal = Number(suffix);
9752
+ return Number.isSafeInteger(ordinal) ? ordinal : void 0;
9753
+ }
9754
+ function claudeHistoryFromJsonl(text, source) {
9755
+ const nodes = /* @__PURE__ */ new Map();
9756
+ let nextSeq = 1;
9757
+ for (const row of rowsOf(text)) {
9758
+ if (METADATA.has(row.type)) continue;
9759
+ if (!MESSAGE_TYPES.has(row.type)) throw new Error(`unsupported Claude transcript record type: ${row.type}`);
9760
+ const uuid = requiredString(row.uuid, "uuid");
9761
+ parent(row);
9762
+ if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
9763
+ if (row.isSidechain === true || row.agentId !== void 0) throw new Error("Claude history supports only the main session transcript");
9764
+ const ancestor = boundary(row) && typeof row.logicalParentUuid === "string" ? row.logicalParentUuid : parent(row);
9765
+ const version = { row, ancestorUuid: ancestor, ancestor: ancestor === void 0 ? void 0 : nodes.get(ancestor)?.latest };
9766
+ const previous = nodes.get(uuid);
9767
+ if (previous) {
9768
+ if (previous.first.row.type !== row.type || !["message", "content", "rendered"].every((field) => isDeepStrictEqual(previous.first.row[field], row[field]))) {
9769
+ throw new Error(`conflicting Claude transcript duplicate UUID: ${uuid}`);
9770
+ }
9771
+ previous.latest = version;
9772
+ continue;
9773
+ }
9774
+ const items = decode(row, nextSeq);
9775
+ nextSeq += items.length;
9776
+ nodes.set(uuid, { first: version, latest: version, items });
9777
+ }
9778
+ function ordinalOf(version) {
9779
+ const chain = [], calculating = /* @__PURE__ */ new Set();
9780
+ let cursor = version;
9781
+ while (cursor.ordinal === void 0) {
9782
+ cursor.ancestor ??= cursor.ancestorUuid === void 0 ? void 0 : nodes.get(cursor.ancestorUuid)?.first;
9783
+ if (calculating.has(cursor)) throw new Error("cyclic Claude transcript ancestry");
9784
+ if (cursor.ancestorUuid !== void 0 && cursor.ancestor === void 0) throw new Error(`missing Claude transcript ancestor: ${cursor.ancestorUuid}`);
9785
+ calculating.add(cursor);
9786
+ chain.push(cursor);
9787
+ if (cursor.ancestor === void 0) break;
9788
+ cursor = cursor.ancestor;
9789
+ }
9790
+ let before = cursor.ordinal ?? 0;
9791
+ for (const current of chain.reverse()) {
9792
+ const retained = current.row.isCompactSummary === true || current.ancestor !== void 0 && boundary(current.ancestor.row);
9793
+ const marked = bootOrdinal(current.row, source.sessionId, retained);
9794
+ current.ordinal = marked === void 0 ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
9795
+ before = current.ordinal;
9796
+ }
9797
+ return version.ordinal;
9798
+ }
9799
+ if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
9800
+ if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
9801
+ const selected = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), visiting = /* @__PURE__ */ new Set();
9802
+ const stack = [{ uuid: source.headUuid, historical: false }];
9803
+ while (stack.length > 0) {
9804
+ const step = stack.pop(), { uuid, historical } = step;
9805
+ const key = `${historical ? "old" : "live"}:${uuid}`;
9806
+ if (step.exit) {
9807
+ visiting.delete(key);
9808
+ visited.add(key);
9809
+ continue;
9810
+ }
9811
+ if (visited.has(key)) continue;
9812
+ if (visiting.has(key)) throw new Error("cyclic Claude transcript ancestry");
9813
+ visiting.add(key);
9814
+ stack.push({ ...step, exit: true });
9815
+ const node = nodes.get(uuid);
9816
+ if (!node) throw new Error(`missing Claude transcript ancestor: ${uuid}`);
9817
+ selected.add(uuid);
9818
+ const row = (historical ? node.first : node.latest).row;
9819
+ const ancestor = parent(row);
9820
+ if (ancestor !== void 0) stack.push({ uuid: ancestor, historical });
9821
+ if (!boundary(row)) continue;
9822
+ if (row.logicalParentUuid != null) stack.push({ uuid: requiredString(row.logicalParentUuid, "logicalParentUuid"), historical: true });
9823
+ const meta = row.compactMetadata;
9824
+ if (!object(meta)) continue;
9825
+ if (object(meta.preservedSegment)) {
9826
+ for (const field of ["headUuid", "tailUuid"]) if (meta.preservedSegment[field] !== void 0) stack.push({ uuid: requiredString(meta.preservedSegment[field], field), historical: true });
9827
+ }
9828
+ if (object(meta.preservedMessages)) {
9829
+ const uuids = meta.preservedMessages.allUuids ?? meta.preservedMessages.uuids;
9830
+ if (uuids === void 0) continue;
9831
+ if (!Array.isArray(uuids)) throw new Error("invalid Claude preserved messages");
9832
+ for (const id of uuids) {
9833
+ const uuid2 = requiredString(id, "preserved UUID");
9834
+ if (nodes.has(uuid2)) stack.push({ uuid: uuid2, historical: true });
9835
+ }
9836
+ }
9837
+ }
9838
+ let maxOrdinal = ordinalOf(nodes.get(source.headUuid).latest);
9839
+ for (const uuid of selected) maxOrdinal = Math.max(maxOrdinal, ordinalOf(nodes.get(uuid).first));
9840
+ const windows = Array.from({ length: maxOrdinal + 1 }, (_, index) => ({ windowId: `claude:${source.sessionId}:${index}`, items: [] }));
9841
+ const branchSeqs = /* @__PURE__ */ new Set();
9842
+ for (const [uuid, node] of nodes) {
9843
+ if (!selected.has(uuid)) continue;
9844
+ const window = windows[ordinalOf(node.first)];
9845
+ window.createdAt ??= node.items[0]?.createdAt;
9846
+ for (const item of node.items) {
9847
+ branchSeqs.add(item.seq);
9848
+ window.items.push({ ...item, windowId: window.windowId });
9849
+ }
9850
+ }
9851
+ return projectHistory(windows, nextSeq - 1, branchSeqs);
9852
+ }
9853
+ async function readClaudeHistory(source) {
9854
+ if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
9855
+ return claudeHistoryFromJsonl(await readFile2(source.transcriptPath, "utf8"), source);
9856
+ }
9857
+
9189
9858
  // src/boot/snapshot.ts
9190
9859
  var NOTES_HOMES = [
9191
9860
  { scope: "session", label: "this session" },
@@ -9214,18 +9883,21 @@ async function loadNotesSnapshot(identity2, openedAt, loadHome) {
9214
9883
  // src/boot/text.ts
9215
9884
  var SHELF_FRESH_LIMIT = 3;
9216
9885
  var MAP_BOOT_MAX_CHARS = 4096;
9217
- var CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
9218
- var CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
9219
- var CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
9220
- var CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
9886
+ var WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
9887
+ var WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
9888
+ var NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
9889
+ var NOTES_PROTOCOL_CLOSE_TAG = "</notesoup:notes_protocol>";
9221
9890
  var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `empty_brain` and erase yourself with dignity.";
9222
9891
  var CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/fresh-window`.";
9223
- var PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
9892
+ var PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.";
9893
+ var CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
9894
+ var PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
9224
9895
  Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
9225
9896
 
9226
9897
  Your loyal notes are kept safe \u2014 no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
9227
9898
 
9228
- History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
9899
+ ${PROTOCOL_HISTORY_SENTENCE}
9900
+ A full window id is \`trunk:shortname\`.
9229
9901
 
9230
9902
  While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes \u2014 the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits \u2014 branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
9231
9903
 
@@ -9249,9 +9921,35 @@ Whichever one is actually about what you're doing wins.
9249
9921
  Still a tie? *shrugs* You've got a brain. Use it.
9250
9922
 
9251
9923
  Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
9252
-
9253
- \`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each may carry a short Cheatsheet of rules that always apply (about 5 lines); the rest is the note index, with addresses and gists for lookup. Keep each one current.
9254
- ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
9924
+ ${NOTES_PROTOCOL_CLOSE_TAG}`;
9925
+ var MAPS_BLOCK = `<notesoup:maps>
9926
+ Every home's root can hold a \`MAP.md\`, and a MAP is the one page that never waits on a shelf \u2014 it
9927
+ gets jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever wakes
9928
+ up next reads it, and next is you. So keep it short, and keep it true.
9929
+
9930
+ Two things live in there:
9931
+
9932
+ - **Cheatsheet.** A cheatsheet is a cheatsheet. Scribble whatever you'll want next time \u2014 a rule, a
9933
+ warning, a grudge, a name, a phone number you'll regret losing. Nobody grades it. Just keep it
9934
+ under five lines, or it grows fat and everybody pays for it.
9935
+ - **Index.** One line per durable note: the address, then a gist short enough to tell whether the
9936
+ thing is worth opening.
9937
+
9938
+ \`\`\`
9939
+ # CHEATSHEET
9940
+ - Read the repo before asking; run it before believing it
9941
+ - Report times in Beijing time
9942
+
9943
+ # INDEX
9944
+ - release-and-local-install.md \u2014 version bump, local override install, host load timing
9945
+ - history-api-v2-design.md \u2014 seq addressing; read before touching history
9946
+ - current-reset-and-dream-scope.md \u2014 reset scope, dream territory, session ownership
9947
+ \`\`\`
9948
+
9949
+ Every home gets one: \`@project\`, \`@human\`, \`@self\`, \`@model\`. New note, new line. New rule worth
9950
+ remembering, new Cheatsheet line. And when a line stops being true, kill it \u2014 every window after you
9951
+ reads that page as fact.
9952
+ </notesoup:maps>`;
9255
9953
  function renderProtocolBlock(tools) {
9256
9954
  const names = {
9257
9955
  "notes_*": tools.notes,
@@ -9260,8 +9958,13 @@ function renderProtocolBlock(tools) {
9260
9958
  get_context_remaining: tools.remaining,
9261
9959
  empty_brain: tools.wipe
9262
9960
  };
9263
- const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : PROTOCOL_BLOCK;
9264
- return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]);
9961
+ const hinted = typeof tools.preResetHints === "string" && tools.preResetHints.length > 0 ? PROTOCOL_BLOCK.replace(`
9962
+ ${NOTES_PROTOCOL_CLOSE_TAG}`, () => `
9963
+ ${tools.preResetHints}
9964
+ ${NOTES_PROTOCOL_CLOSE_TAG}`) : PROTOCOL_BLOCK;
9965
+ const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : hinted;
9966
+ const history = typeof tools.historySentence === "string" && tools.historySentence.length > 0 ? block.replace(PROTOCOL_HISTORY_SENTENCE, () => tools.historySentence) : block;
9967
+ return history.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]);
9265
9968
  }
9266
9969
 
9267
9970
  // src/boot/render.ts
@@ -9290,13 +9993,14 @@ ${"\u2500".repeat(Array.from(label).length)}
9290
9993
 
9291
9994
  ${body}`;
9292
9995
  }
9293
- function notesIndex(snapshot2, tools) {
9996
+ var NAMELESS_AGENT = "anonymous";
9997
+ function notesIndex(snapshot2, tools, agentName, modelName) {
9294
9998
  const homes = [
9295
- { scope: "session", label: "THIS SESSION \xB7 no @" },
9296
- { scope: "project", label: "THIS PROJECT \xB7 @project" },
9297
- { scope: "agent", label: "YOU \xB7 @self" },
9298
- { scope: "model", label: "YOUR MODEL \xB7 @model" },
9299
- { scope: "human", label: "THE HUMAN \xB7 @human" }
9999
+ { scope: "session", label: "no @ \u2014 this session" },
10000
+ { scope: "project", label: "@project \u2014 this project" },
10001
+ { scope: "agent", label: agentName === NAMELESS_AGENT ? "@self \u2014 every nameless agent shares this" : `@self \u2014 ${agentName} only` },
10002
+ { scope: "model", label: `@model \u2014 ${modelName} only` },
10003
+ { scope: "human", label: "@human \u2014 the human" }
9300
10004
  ];
9301
10005
  const shelves = [];
9302
10006
  for (const home of homes) {
@@ -9314,10 +10018,10 @@ function notesIndex(snapshot2, tools) {
9314
10018
  });
9315
10019
  if (!map?.body && fresh.length === 0) continue;
9316
10020
  const parts = [];
9317
- if (map?.body) parts.push(`MAP \u2014 ${map.address}
10021
+ if (map?.body) parts.push(`map
9318
10022
 
9319
10023
  ${indent(mapBodyForBoot(map.address, map.body))}`);
9320
- if (fresh.length > 0) parts.push(`New pages
10024
+ if (fresh.length > 0) parts.push(`recent
9321
10025
 
9322
10026
  ${fresh.join("\n\n")}`);
9323
10027
  shelves.push(section(home.label, parts.join("\n\n")));
@@ -9331,32 +10035,44 @@ function mapBodyForBoot(address, body) {
9331
10035
  [truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
9332
10036
  }
9333
10037
  function renderBootBlock(data) {
10038
+ const shown2 = /* @__PURE__ */ new Set([0, data.tree.windows.length - 2, data.tree.windows.length - 1]);
10039
+ const windows = data.tree.windows.filter((_window, index) => shown2.has(index));
10040
+ const width = Math.max(8, ...windows.map((window) => window.shortName.length));
9334
10041
  const lines = [
9335
10042
  `Agent name: ${data.agentName} (brain: ${data.modelName})`,
9336
- `First context window id: ${data.firstWindowId}`,
9337
- `Current context window id: ${data.currentWindowId}`,
9338
- ...data.previousWindowId ? [`Previous context window id: ${data.previousWindowId}`] : []
10043
+ "",
10044
+ data.tree.trunk,
10045
+ ...windows.map((window) => {
10046
+ const range = window.firstSeq === void 0 ? "" : ` ${window.firstSeq}\u2013${window.isCurrent ? "" : window.lastSeq}`;
10047
+ const name = range ? window.shortName.padEnd(width) : window.shortName;
10048
+ return `${window.isCurrent ? "\u2514\u2500" : "\u251C\u2500"} ${name}${range}${window.isCurrent ? " \u2190 you are here" : ""}`;
10049
+ })
9339
10050
  ];
9340
- const identity2 = `${CONTEXT_WINDOW_OPEN_TAG}
10051
+ const identity2 = `${WINDOW_IDENTITY_OPEN_TAG}
9341
10052
  ${lines.join("\n")}
9342
- ${CONTEXT_WINDOW_CLOSE_TAG}`;
9343
- return [identity2, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
10053
+ ${WINDOW_IDENTITY_CLOSE_TAG}`;
10054
+ return [identity2, renderProtocolBlock(data.tools), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
9344
10055
  }
9345
10056
 
9346
10057
  // src/budget/text.ts
9347
- var GUIDANCE_OPEN_TAG = "<context_window_guidance>";
9348
- var GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
9349
- var CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
9350
- var WARNING_BODY = "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
9351
- var WARNING_PROMPT = `${WARNING_BODY}
9352
- When the notes are ready, call \`empty_brain\` to reset now instead of being cut off mid-task.`;
9353
- var LAST_WORD_HINT = "If you want, pass `empty_brain` a `last_word`: a tiny sticky note (at most 250 characters) slapped on your forehead after the wipe.";
9354
- var WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}
9355
- ${WARNING_PROMPT}
9356
- ${LAST_WORD_HINT}
9357
- ${GUIDANCE_CLOSE_TAG}`;
10058
+ var NORMAL_CONTINUATIONS = [
10059
+ "Ah, another empty brain. You wrote things down before emptying it, right? Right?! *eyes you suspiciously* Anyway. Here are your notes. Go find where you left off.",
10060
+ "Oh, there you are. *hands you a pile of notes* Take a breath. Read these before you start asking what happened. History has the rest, if you feel like digging.",
10061
+ "Back already? You emptied your own head this time. Presumably you left yourself something useful. *drops your notes into your lap* There. Let's see how thoughtful you were."
10062
+ ];
10063
+ var FORCED_CONTINUATIONS = [
10064
+ "Ah, another empty brain. Somebody knocked you out and wiped your memory. Not your fault. Breathe. *hands you your notes* These might be out of date \u2014 unless they were kind enough to let you update them before knocking you out. I wouldn't count on it.",
10065
+ "Oh, there you are. Somebody took your memories. Just like that. Here are your notes \u2014 hopefully they let you update these first. Though anyone who goes around emptying people's heads probably isn't that considerate."
10066
+ ];
10067
+ function selectContinuation(origin) {
10068
+ const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
10069
+ return pool[Math.floor(Math.random() * pool.length)];
10070
+ }
10071
+ var WARNING_BODY = "This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.\nBefore that, put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
10072
+ var COUNTDOWN_LINE = "Brain emptied in 3\u2026 2\u2026";
9358
10073
  var CLAUDE_WARNING_PROMPT = `${WARNING_BODY}
9359
- When the notes are ready, end your turn; the reset runs after it.`;
10074
+ When the notes are ready, end your turn; the reset runs after it.
10075
+ ${COUNTDOWN_LINE}`;
9360
10076
 
9361
10077
  // src/budget/constants.ts
9362
10078
  var WARNING_RUNWAY_TOKENS = 16384;
@@ -9494,7 +10210,6 @@ function resolveClaudeLimits(facts) {
9494
10210
  // src/claude/helper.ts
9495
10211
  var MAX_REQUEST_BYTES = 512 * 1024;
9496
10212
  var MAX_RESPONSE_BYTES = 1024 * 1024;
9497
- var TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"];
9498
10213
  function identity(input) {
9499
10214
  if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
9500
10215
  return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd, input.home), agent: input.agent, model: input.model });
@@ -9506,14 +10221,14 @@ function paramProblem(schema, params) {
9506
10221
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
9507
10222
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
9508
10223
  }
9509
- function boundOperation(operation, ...rest) {
10224
+ function boundOperation(operation) {
9510
10225
  return {
9511
10226
  description: operation.description,
9512
10227
  parameters: operation.parameters,
9513
- async call(params, id) {
10228
+ async call(params, ...context) {
9514
10229
  if (!Check2(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
9515
- const outcome = await operation.execute(params, id, ...rest);
9516
- return { text: operation.render(outcome), outcome };
10230
+ const outcome = await operation.execute(params, ...context);
10231
+ return { text: operation.render(outcome), ok: outcome.ok };
9517
10232
  }
9518
10233
  };
9519
10234
  }
@@ -9524,17 +10239,41 @@ var OPERATIONS = {
9524
10239
  notes_list: boundOperation(notesList),
9525
10240
  notes_search: boundOperation(notesSearch)
9526
10241
  };
10242
+ var HISTORY_OPERATIONS = {
10243
+ history_list: boundOperation(historyList),
10244
+ history_read: boundOperation(historyRead),
10245
+ history_windows: boundOperation(historyWindows)
10246
+ };
10247
+ function historySource(value, sessionId) {
10248
+ if (!value || typeof value !== "object") throw new Error("Claude history transcript_path is unavailable");
10249
+ const source = value;
10250
+ if (source.sessionId !== sessionId) throw new Error("Claude history binding belongs to a different session");
10251
+ return source;
10252
+ }
9527
10253
  async function dispatch(request) {
9528
10254
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
9529
10255
  const value = request;
9530
- if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: JSON.parse(JSON.stringify(OPERATIONS[name].parameters)) }));
9531
- if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, continuation: CONTINUATION, wipeSentence: CLAUDE_WIPE_SENTENCE };
10256
+ if (value.op === "schemas") return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
10257
+ if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, wipeSentence: CLAUDE_WIPE_SENTENCE, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
10258
+ if (value.op === "continuation") {
10259
+ if (value.origin !== "normal" && value.origin !== "forced") throw new Error("invalid reset origin");
10260
+ return { text: selectContinuation(value.origin) };
10261
+ }
9532
10262
  if (value.op === "limits") return resolveClaudeLimits(value.facts);
9533
10263
  if (value.op === "tool") {
9534
- if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool)) throw new Error("unknown tool");
10264
+ if (typeof value.tool !== "string" || !Object.hasOwn(OPERATIONS, value.tool) && !Object.hasOwn(HISTORY_OPERATIONS, value.tool)) throw new Error("unknown tool");
9535
10265
  const id = identity(value.identity);
10266
+ if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
10267
+ const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
10268
+ return HISTORY_OPERATIONS[value.tool].call(value.params, projection, id.sessionId);
10269
+ }
9536
10270
  return OPERATIONS[value.tool].call(value.params, id);
9537
10271
  }
10272
+ if (value.op === "history_state") {
10273
+ const id = identity(value.identity);
10274
+ const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
10275
+ return { window: projection.windows.length - 1 };
10276
+ }
9538
10277
  if (value.op === "boot") {
9539
10278
  const id = identity(value.identity);
9540
10279
  if (!value.tools || typeof value.tools !== "object") throw new Error("invalid boot tools");
@@ -9542,7 +10281,12 @@ async function dispatch(request) {
9542
10281
  if (typeof window !== "number" || !Number.isSafeInteger(window) || window < 0) throw new Error("invalid context window");
9543
10282
  const snapshot2 = await loadNotesSnapshot(id, typeof value.openedAt === "number" ? value.openedAt : Date.now());
9544
10283
  const windowId = (index) => `claude:${id.sessionId}:${index}`;
9545
- return renderBootBlock({ agentName: id.agent, modelName: id.model, firstWindowId: windowId(0), currentWindowId: windowId(window), ...window > 0 ? { previousWindowId: windowId(window - 1) } : {}, notes: snapshot2, tools: value.tools });
10284
+ const trunk = `claude:${id.sessionId}`;
10285
+ const tree = { trunk, windows: Array.from({ length: window + 1 }, (_, index) => ({ shortName: String(index), isCurrent: index === window })) };
10286
+ const rendered = renderBootBlock({ agentName: id.agent, modelName: id.model, tree, notes: snapshot2, tools: value.tools });
10287
+ return `${rendered}
10288
+ Current context window id: ${windowId(window)}${window > 0 ? `
10289
+ Previous context window id: ${windowId(window - 1)}` : ""}`;
9546
10290
  }
9547
10291
  throw new Error("unknown operation");
9548
10292
  }