@nomadop/session-watcher-dsh 0.10.1 → 0.10.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/client.js CHANGED
@@ -84,7 +84,13 @@ var en = {
84
84
  "dock.stock": "Context stock",
85
85
  "dock.baseline": "Rebuild baseline",
86
86
  "dock.effective": "Effective context",
87
- "dock.growth": "Growth per call"
87
+ "dock.growth": "Growth per call",
88
+ "picker.search": "Search by token or task",
89
+ "picker.empty": "No handoffs available for this project.",
90
+ "picker.noResults": "No handoffs match.",
91
+ "picker.group.undelivered": "Undelivered",
92
+ "picker.group.delivered": "Delivered",
93
+ "picker.noSession": "This session is no longer open."
88
94
  };
89
95
  var zh = {
90
96
  "view.label": "SW Meter",
@@ -120,7 +126,13 @@ var zh = {
120
126
  "dock.stock": "\u4E0A\u4E0B\u6587\u5B58\u91CF",
121
127
  "dock.baseline": "\u91CD\u5EFA\u57FA\u7EBF",
122
128
  "dock.effective": "\u6709\u6548\u4E0A\u4E0B\u6587",
123
- "dock.growth": "\u6BCF\u6B21\u8C03\u7528\u589E\u957F"
129
+ "dock.growth": "\u6BCF\u6B21\u8C03\u7528\u589E\u957F",
130
+ "picker.search": "\u6309 token \u6216\u4EFB\u52A1\u641C\u7D22",
131
+ "picker.empty": "\u5F53\u524D\u9879\u76EE\u6CA1\u6709\u53EF\u7528\u7684 handoff\u3002",
132
+ "picker.noResults": "\u6CA1\u6709\u5339\u914D\u7684 handoff\u3002",
133
+ "picker.group.undelivered": "\u672A\u4EA4\u4ED8",
134
+ "picker.group.delivered": "\u5DF2\u4EA4\u4ED8",
135
+ "picker.noSession": "\u6B64\u4F1A\u8BDD\u5DF2\u4E0D\u518D\u6253\u5F00\u3002"
124
136
  };
125
137
 
126
138
  // dsh/src/client/tab.js
@@ -18633,6 +18645,47 @@ function createDock({ useAnchoredPosition: useAnchoredPosition2, useDismissOnOut
18633
18645
  return { Dock, DockView };
18634
18646
  }
18635
18647
 
18648
+ // dsh/src/client/handoff-picker.js
18649
+ var COMMAND = "sw-load";
18650
+ var LIST_ENDPOINT = "handoff/list";
18651
+ var DETAIL_SEPARATOR = " \xB7 ";
18652
+ function registerHandoffPicker(child, { call, t }) {
18653
+ const { commandUi, sessions, conversation } = child;
18654
+ commandUi.decorate({
18655
+ name: COMMAND,
18656
+ available: () => true,
18657
+ ui: {
18658
+ kind: "popupSelect",
18659
+ searchLabels: () => ({ placeholder: t("picker.search"), empty: t("picker.empty"), noResults: t("picker.noResults") }),
18660
+ async options({ sessionId }, signal) {
18661
+ const reply = await call(LIST_ENDPOINT, { sessionId }, signal);
18662
+ if (reply.ok !== true) throw new Error(stateText({ kind: "unreachable", message: reply.error.message }, t));
18663
+ if (reply.value.state !== "live") {
18664
+ throw new Error(stateText({ kind: "state", state: reply.value.state, diagnostic: reply.value.diagnostic }, t));
18665
+ }
18666
+ const groups = {
18667
+ undelivered: { name: "undelivered", label: t("picker.group.undelivered") },
18668
+ delivered: { name: "delivered", label: t("picker.group.delivered") }
18669
+ };
18670
+ return reply.value.payload.items.map(({ loadToken, age, nextTask, deliveredAt }) => ({
18671
+ id: loadToken,
18672
+ label: loadToken,
18673
+ detail: nextTask ? `${age}${DETAIL_SEPARATOR}${nextTask}` : age,
18674
+ group: deliveredAt == null ? groups.undelivered : groups.delivered
18675
+ }));
18676
+ },
18677
+ onSelect(option, { sessionId }) {
18678
+ const actx = sessions.scope(sessionId);
18679
+ if (actx === void 0) throw new Error(t("picker.noSession"));
18680
+ conversation.input.for(actx).setDraft(`/${COMMAND} ${option.id}`);
18681
+ }
18682
+ }
18683
+ });
18684
+ child.effect(() => () => {
18685
+ commandUi.dismiss(COMMAND);
18686
+ }, "session-watcher: /sw-load popup dismissal");
18687
+ }
18688
+
18636
18689
  // dsh/src/client/plugin.js
18637
18690
  var PLUGIN_ID = "@nomadop/session-watcher-dsh";
18638
18691
  var CHANNEL = "/session-watcher";
@@ -18649,9 +18702,8 @@ function applyClient(ctx, { tabCss, useAnchoredPosition: useAnchoredPosition2, u
18649
18702
  tag.remove();
18650
18703
  };
18651
18704
  }, "session-watcher: tab stylesheet");
18652
- const sessions = createSessionStores({
18653
- call: (endpoint, payload, signal) => ctx.connection.rpc.call(CHANNEL, endpoint, payload, signal)
18654
- });
18705
+ const call = (endpoint, payload, signal) => ctx.connection.rpc.call(CHANNEL, endpoint, payload, signal);
18706
+ const sessions = createSessionStores({ call });
18655
18707
  let signalState = "connecting";
18656
18708
  const signalListeners = /* @__PURE__ */ new Set();
18657
18709
  const signalStore = {
@@ -18734,6 +18786,7 @@ function applyClient(ctx, { tabCss, useAnchoredPosition: useAnchoredPosition2, u
18734
18786
  locale: NS,
18735
18787
  inject: (sessionId) => ({ store: sessions.for(sessionId) })
18736
18788
  }, Dock));
18789
+ ctx.inject(["commandUi", "sessions", "conversation"], (child) => registerHandoffPicker(child, { call, t }));
18737
18790
  }
18738
18791
 
18739
18792
  // public/themes/base.css
package/dist/index.js CHANGED
@@ -516,6 +516,7 @@ var C_RATIO_TABLE = [
516
516
  { match: /fable.?5.?1/i, ratio: { [DEFAULT_CACHE_TTL]: 50, [LONG_CACHE_TTL]: 80 } },
517
517
  { match: /(opus|sonnet).?5.?5/i, ratio: { [DEFAULT_CACHE_TTL]: 25, [LONG_CACHE_TTL]: 40 } },
518
518
  { match: /claude|opus|sonnet|haiku|fable/i, ratio: { [DEFAULT_CACHE_TTL]: 12.5, [LONG_CACHE_TTL]: 20 } },
519
+ { match: /6.?1.?(sol|terra)/i, ratio: { [DEFAULT_CACHE_TTL]: 25, [LONG_CACHE_TTL]: 50 } },
519
520
  { match: /deepseek.*pro/i, ratio: 30 },
520
521
  { match: /deepseek/i, ratio: 50 }
521
522
  ];
@@ -1073,6 +1074,11 @@ var Store = class _Store {
1073
1074
  ORDER BY loaded_at DESC, handoff_id DESC LIMIT 1
1074
1075
  ) AS latest JOIN handoff AS h ON h.handoff_id = latest.handoff_id`),
1075
1076
  getHandoff: db.prepare("SELECT * FROM handoff WHERE handoff_id = ?"),
1077
+ // The whole retained catalog of one project, for a person to browse: no age window, no producer exclusion,
1078
+ // no cap. `delivered_at` alone splits the groups; the row's identity breaks a creation-time tie.
1079
+ listHandoffCandidates: db.prepare(`SELECT load_token, created_at, next_task, delivered_at FROM handoff
1080
+ WHERE project_id = ?
1081
+ ORDER BY delivered_at IS NOT NULL, created_at DESC, handoff_id DESC`),
1076
1082
  // Turn note CRUD
1077
1083
  // created_at is written on insert only and deliberately absent from the SET list: the first
1078
1084
  // write's timestamp is the row's own age, while a later submission only revises its content.
@@ -1792,6 +1798,19 @@ var Store = class _Store {
1792
1798
  if (rows.length > 1) return { status: "ambiguous", rows };
1793
1799
  return { status: "unique", row: rows[0] };
1794
1800
  }
1801
+ // Every retained handoff of one project in browsing order — undelivered first, then delivered, each newest
1802
+ // first — as `{ loadToken, createdAt, nextTask, deliveredAt }` rows. READ-ONLY: unlike `deliverHandoffByToken`
1803
+ // it stamps no delivery. A project that is null or empty names no catalog, and the rows stored without a
1804
+ // project are no project's.
1805
+ listHandoffCandidatesByProject(projectId) {
1806
+ if (!projectId) return [];
1807
+ return this._stmts.listHandoffCandidates.all(projectId).map((r) => ({
1808
+ loadToken: r.load_token,
1809
+ createdAt: r.created_at,
1810
+ nextTask: r.next_task,
1811
+ deliveredAt: r.delivered_at
1812
+ }));
1813
+ }
1795
1814
  // R1-H: project-scoped FTS search. Statement prepared LAZILY (handoff_fts may not exist).
1796
1815
  searchHandoff(matchExpr, { projectId = null, limit = 3 } = {}) {
1797
1816
  if (!this.ftsAvailable) return [];
@@ -1995,14 +2014,6 @@ function loadIsIgnored(cwd) {
1995
2014
  }
1996
2015
  }
1997
2016
 
1998
- // lib/project-key.js
1999
- import { resolve } from "node:path";
2000
- function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
2001
- const raw = claudeProjectDir || cwd;
2002
- if (!raw) return null;
2003
- return resolve(raw);
2004
- }
2005
-
2006
2017
  // lib/harness/dsh/cache-ttl.js
2007
2018
  function cacheTtlForRetention(retention) {
2008
2019
  return retention === "long" ? LONG_CACHE_TTL : null;
@@ -2036,7 +2047,7 @@ function createResourcePolicy({ projectRoot = null, isIgnored = null } = {}) {
2036
2047
  if (relative && ignoreMatcher && ignoreMatcher(relative)) return "gitignore";
2037
2048
  return null;
2038
2049
  }
2039
- function resolve2(resourceKey) {
2050
+ function resolve3(resourceKey) {
2040
2051
  const defaultDiscardReason = discardReasonFor(resourceKey);
2041
2052
  return { selectedByDefault: defaultDiscardReason === null, defaultDiscardReason };
2042
2053
  }
@@ -2076,7 +2087,7 @@ function createResourcePolicy({ projectRoot = null, isIgnored = null } = {}) {
2076
2087
  }
2077
2088
  return inferred;
2078
2089
  }
2079
- return { resolve: resolve2, infer };
2090
+ return { resolve: resolve3, infer };
2080
2091
  }
2081
2092
 
2082
2093
  // lib/dialogue-fold.js
@@ -4194,6 +4205,12 @@ var SessionWatcher = class {
4194
4205
  }
4195
4206
  return this._handoff.searchResponse(results);
4196
4207
  }
4208
+ // The handoffs of this session's project a person may pick one from, in the Store's browsing order. Unlike
4209
+ // `deliverHandoff` it delivers nothing and applies no auto-match window, producer exclusion or cap; a null
4210
+ // project is an empty catalog, and a Store failure propagates.
4211
+ listHandoffCandidates() {
4212
+ return this._store.listHandoffCandidatesByProject(this._projectId);
4213
+ }
4197
4214
  // One session, segment and project captured at entry: the response is composed after the delivery
4198
4215
  // transaction commits, and it must describe the consumer that actually claimed the row.
4199
4216
  async deliverHandoff({ loadToken } = {}) {
@@ -5926,13 +5943,13 @@ async function Module2(moduleArg = {}) {
5926
5943
  }
5927
5944
  readAsync = /* @__PURE__ */ __name(async (url) => {
5928
5945
  if (isFileURI(url)) {
5929
- return new Promise((resolve2, reject) => {
5946
+ return new Promise((resolve3, reject) => {
5930
5947
  var xhr = new XMLHttpRequest();
5931
5948
  xhr.open("GET", url, true);
5932
5949
  xhr.responseType = "arraybuffer";
5933
5950
  xhr.onload = () => {
5934
5951
  if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
5935
- resolve2(xhr.response);
5952
+ resolve3(xhr.response);
5936
5953
  return;
5937
5954
  }
5938
5955
  reject(xhr.status);
@@ -6128,9 +6145,9 @@ async function Module2(moduleArg = {}) {
6128
6145
  __name(receiveInstantiationResult, "receiveInstantiationResult");
6129
6146
  var info2 = getWasmImports();
6130
6147
  if (Module["instantiateWasm"]) {
6131
- return new Promise((resolve2, reject) => {
6148
+ return new Promise((resolve3, reject) => {
6132
6149
  Module["instantiateWasm"](info2, (mod, inst) => {
6133
- resolve2(receiveInstance(mod, inst));
6150
+ resolve3(receiveInstance(mod, inst));
6134
6151
  });
6135
6152
  });
6136
6153
  }
@@ -7461,8 +7478,8 @@ async function Module2(moduleArg = {}) {
7461
7478
  if (runtimeInitialized) {
7462
7479
  moduleRtn = Module;
7463
7480
  } else {
7464
- moduleRtn = new Promise((resolve2, reject) => {
7465
- readyPromiseResolve = resolve2;
7481
+ moduleRtn = new Promise((resolve3, reject) => {
7482
+ readyPromiseResolve = resolve3;
7466
7483
  readyPromiseReject = reject;
7467
7484
  });
7468
7485
  }
@@ -9549,11 +9566,12 @@ function createMeasurementEngine({ resolveModelPolicy, resolveResourcePolicy } =
9549
9566
  const totalStock = usage.input + usage.cacheRead + usage.cacheWrite;
9550
9567
  const model = record.model ?? null;
9551
9568
  const firstOfEpoch = segmentSteps.length === 0;
9569
+ const totals = ledger.residentTotals();
9552
9570
  if (settlementCursor === null && totalStock > 0) {
9553
- dead = totalStock;
9571
+ dead = totalStock - Math.min(totalStock, residentTotalOf(totals));
9554
9572
  sessionFloor = totalStock;
9573
+ pendingResiduals = [];
9555
9574
  }
9556
- const totals = ledger.residentTotals();
9557
9575
  const residentTotal = residentTotalOf(totals);
9558
9576
  const miss = settlementCursor !== null && classifyMiss({ cacheRead: usage.cacheRead, prevL: settlementCursor.L });
9559
9577
  const L = miss ? totalStock : usage.cacheRead;
@@ -10097,10 +10115,18 @@ function deletePricingOverride(model) {
10097
10115
  getStore().deleteConfig(`pricing:${model}`);
10098
10116
  }
10099
10117
 
10118
+ // lib/project-key.js
10119
+ import { resolve } from "node:path";
10120
+ function resolveProjectKey({ claudeProjectDir, cwd } = {}) {
10121
+ const raw = claudeProjectDir || cwd;
10122
+ if (!raw) return null;
10123
+ return resolve(raw);
10124
+ }
10125
+
10100
10126
  // package.json
10101
10127
  var package_default = {
10102
10128
  name: "@nomadop/session-watcher",
10103
- version: "0.10.1",
10129
+ version: "0.10.2",
10104
10130
  description: "Local Claude Code context-cost monitor, transcript replay, buckets, and handoff",
10105
10131
  type: "module",
10106
10132
  license: "MIT",
@@ -10192,7 +10218,7 @@ function createResolver({ path: path3, homeDir }) {
10192
10218
  if (homeDir !== null && typeof homeDir !== "string") {
10193
10219
  throw new TypeError("Working Tree homeDir must be a string or null");
10194
10220
  }
10195
- return function resolve2(base, raw) {
10221
+ return function resolve3(base, raw) {
10196
10222
  if (typeof raw !== "string" || raw.length === 0) return null;
10197
10223
  let value = raw;
10198
10224
  if (homeDir !== null && raw === "~") value = homeDir;
@@ -10208,7 +10234,7 @@ function createResolver({ path: path3, homeDir }) {
10208
10234
  };
10209
10235
  }
10210
10236
  function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars } = {}) {
10211
- const resolve2 = createResolver({ path: path3, homeDir });
10237
+ const resolve3 = createResolver({ path: path3, homeDir });
10212
10238
  requireBound("cacheEntries", cacheEntries);
10213
10239
  requireBound("cacheChars", cacheChars);
10214
10240
  const cache = /* @__PURE__ */ new Map();
@@ -10236,7 +10262,7 @@ function createNodeWorkingTree({ path: path3, homeDir, cacheEntries, cacheChars
10236
10262
  }
10237
10263
  }
10238
10264
  return {
10239
- resolve: resolve2,
10265
+ resolve: resolve3,
10240
10266
  stat: (file) => orNull(() => {
10241
10267
  const st = statSync3(file);
10242
10268
  return { size: st.size, isFile: st.isFile() };
@@ -11223,12 +11249,38 @@ function createToolEvidenceInterpreter({ attribution, profile, limits } = {}) {
11223
11249
  return { interpretToolUse, completeToolResult, resourceKeysOf };
11224
11250
  }
11225
11251
 
11252
+ // lib/harness/dsh/load-message.js
11253
+ var LOAD_MESSAGE_KIND = "session-watcher-load";
11254
+ function loadMessageInput({ route, calls }) {
11255
+ return {
11256
+ content: calls.map(({ text }) => ({ type: "text", text })),
11257
+ source: {
11258
+ kind: LOAD_MESSAGE_KIND,
11259
+ route: { provider: route.provider, model: route.model },
11260
+ calls: calls.map(({ id, name: name3, arguments: args2 }) => ({ id, name: name3, arguments: args2 }))
11261
+ }
11262
+ };
11263
+ }
11264
+ function loadRouteOf(message) {
11265
+ return message?.source?.kind === LOAD_MESSAGE_KIND ? message.source.route : void 0;
11266
+ }
11267
+ var isId = (value) => typeof value === "string" && value !== "";
11268
+ var isCall = (call) => call !== null && typeof call === "object" && isId(call.id) && typeof call.name === "string" && typeof call.arguments === "string";
11269
+ var isTextBlock = (block) => block?.type === "text" && typeof block.text === "string";
11270
+ function loadCallsOf(message) {
11271
+ const calls = message?.source?.calls;
11272
+ const content = message?.content;
11273
+ if (!Array.isArray(calls) || !Array.isArray(content) || calls.length !== content.length) return null;
11274
+ if (!calls.every(isCall) || !content.every(isTextBlock)) return null;
11275
+ return calls.map(({ id, name: name3, arguments: args2 }, index) => ({ id, name: name3, arguments: args2, text: content[index].text }));
11276
+ }
11277
+
11226
11278
  // lib/harness/dsh/transcript-observation.js
11227
11279
  var SCOPE = "dsh-transcript-observation";
11228
11280
  var MESSAGE_NAMESPACE = "dsh:message:";
11229
11281
  var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11230
11282
  var isIndex = (value) => Number.isSafeInteger(value) && value >= 0;
11231
- var isId = (value) => typeof value === "string" && value !== "";
11283
+ var isId2 = (value) => typeof value === "string" && value !== "";
11232
11284
  var isSurfaceOp = (value) => value === "append" || isObject2(value) && value.op === "replace";
11233
11285
  var nothing = () => ({ observations: [], diagnostics: [] });
11234
11286
  function violation(event, field) {
@@ -11248,7 +11300,7 @@ function baseOf2(event) {
11248
11300
  return { sourceOrdinal: event.seq, sourceEntryId: String(event.seq), timestamp: event.time };
11249
11301
  }
11250
11302
  var textShaped = (block) => block.type !== "text" || typeof block.text === "string";
11251
- var toolCallShaped = (block) => block.type !== "tool-call" || isId(block.id) && typeof block.name === "string" && typeof block.arguments === "string";
11303
+ var toolCallShaped = (block) => block.type !== "tool-call" || isId2(block.id) && typeof block.name === "string" && typeof block.arguments === "string";
11252
11304
  function isContent(content, ...shapes) {
11253
11305
  return Array.isArray(content) && content.every((block) => isObject2(block) && shapes.every((shaped) => shaped(block)));
11254
11306
  }
@@ -11280,7 +11332,7 @@ function reduceHumanMessage(event) {
11280
11332
  const { data } = event;
11281
11333
  const fault = faultOf([
11282
11334
  ...envelopeChecks(event),
11283
- ["data.id", isId(data.id)],
11335
+ ["data.id", isId2(data.id)],
11284
11336
  ["data.content", isContent(data.content, textShaped)]
11285
11337
  ]);
11286
11338
  if (fault !== null) return violation(event, fault);
@@ -11306,10 +11358,49 @@ function reduceCheckpoint(event) {
11306
11358
  if (fault !== null) return violation(event, fault);
11307
11359
  return { observations: [{ type: "epoch-boundary", ...baseOf2(event), provenance: "harness" }], diagnostics: [] };
11308
11360
  }
11361
+ var isRoute = (route) => isObject2(route) && typeof route.provider === "string" && typeof route.model === "string";
11362
+ function reduceLoadMessage(event) {
11363
+ const { data } = event;
11364
+ const calls = loadCallsOf(data);
11365
+ const fault = faultOf([
11366
+ ...envelopeChecks(event),
11367
+ ["data.id", isId2(data.id)],
11368
+ ["data.source.route", isRoute(loadRouteOf(data))],
11369
+ ["data.source.calls", calls !== null]
11370
+ ]);
11371
+ if (fault !== null) return violation(event, fault);
11372
+ const base = baseOf2(event);
11373
+ const messageId = MESSAGE_NAMESPACE + data.id;
11374
+ const { model } = loadRouteOf(data);
11375
+ const observations = calls.flatMap(({ id, name: name3, arguments: args2, text }) => [
11376
+ {
11377
+ type: "tool-use",
11378
+ messageId,
11379
+ model,
11380
+ cwd: null,
11381
+ toolUseId: id,
11382
+ name: name3,
11383
+ input: parseArguments(args2),
11384
+ ...base,
11385
+ provenance: "harness"
11386
+ },
11387
+ {
11388
+ type: "tool-result",
11389
+ toolUseId: id,
11390
+ content: text,
11391
+ isError: false,
11392
+ resultMeta: { meta: null, error: null },
11393
+ ...base,
11394
+ provenance: "harness"
11395
+ }
11396
+ ]);
11397
+ return { observations, diagnostics: [] };
11398
+ }
11309
11399
  function reduceUserMessage(event) {
11310
11400
  const kind = event.data?.source?.kind;
11311
11401
  if (kind === "user") return reduceHumanMessage(event);
11312
11402
  if (kind === "compact-checkpoint") return reduceCheckpoint(event);
11403
+ if (kind === LOAD_MESSAGE_KIND) return reduceLoadMessage(event);
11313
11404
  return typeof kind === "string" ? nothing() : violation(event, "data.source.kind");
11314
11405
  }
11315
11406
  function reduceAssistantMessage(event) {
@@ -11319,7 +11410,7 @@ function reduceAssistantMessage(event) {
11319
11410
  ...envelopeChecks(event),
11320
11411
  ["data.turn", isIndex(data?.turn)],
11321
11412
  ["data.step", isIndex(data?.step)],
11322
- ["data.message.id", isId(message?.id)],
11413
+ ["data.message.id", isId2(message?.id)],
11323
11414
  ["data.message.source.model", typeof message?.source?.model === "string"],
11324
11415
  ["data.message.content", isContent(message?.content, textShaped, toolCallShaped)],
11325
11416
  ["data.usage", data?.usage === void 0 || isUsage(data.usage)]
@@ -11368,7 +11459,7 @@ function reduceToolResult(event) {
11368
11459
  ...envelopeChecks(event),
11369
11460
  ["data.turn", isIndex(data?.turn)],
11370
11461
  ["data.step", isIndex(data?.step)],
11371
- ["data.message.toolCallId", isId(message?.toolCallId)],
11462
+ ["data.message.toolCallId", isId2(message?.toolCallId)],
11372
11463
  ["data.message.isError", message?.isError === void 0 || typeof message.isError === "boolean"],
11373
11464
  ["data.message.content", isContent(message?.content, textShaped)]
11374
11465
  ]);
@@ -12629,9 +12720,9 @@ function createWatcherTable({ compose, readSession, cacheTtlFor = () => null, mo
12629
12720
  if (entry.state === "live") return Promise.resolve(liveView(entry));
12630
12721
  if (entry.state === "failed") return Promise.reject(new Error(entry.diagnostic.message));
12631
12722
  if (signal.aborted) return Promise.reject(aborted(sessionId, signal));
12632
- return new Promise((resolve2, reject) => {
12723
+ return new Promise((resolve3, reject) => {
12633
12724
  const onAbort = () => reject(aborted(sessionId, signal));
12634
- const waiter = { resolve: resolve2, reject, release: () => signal.removeEventListener("abort", onAbort) };
12725
+ const waiter = { resolve: resolve3, reject, release: () => signal.removeEventListener("abort", onAbort) };
12635
12726
  entry.waiters.add(waiter);
12636
12727
  signal.addEventListener("abort", onAbort, { once: true });
12637
12728
  });
@@ -12655,9 +12746,10 @@ function pairOf(fields) {
12655
12746
  function pairOfEvent(event) {
12656
12747
  if (event?.type === "request/header") return pairOf(event.data?.header?.config);
12657
12748
  if (event?.type === "assistant/message") return pairOf(event.data?.message?.source);
12749
+ if (event?.type === "user/message") return pairOf(loadRouteOf(event.data));
12658
12750
  return void 0;
12659
12751
  }
12660
- function createModelNames({ resolve: resolve2 }) {
12752
+ function createModelNames({ resolve: resolve3 }) {
12661
12753
  const names = /* @__PURE__ */ new Map();
12662
12754
  const inFlight = /* @__PURE__ */ new Map();
12663
12755
  const store = (key) => ({ name: name3 }) => {
@@ -12671,7 +12763,7 @@ function createModelNames({ resolve: resolve2 }) {
12671
12763
  if (names.has(key)) continue;
12672
12764
  let pending = inFlight.get(key);
12673
12765
  if (pending === void 0) {
12674
- pending = resolve2(provider, model).then(store(key)).finally(() => inFlight.delete(key));
12766
+ pending = resolve3(provider, model).then(store(key)).finally(() => inFlight.delete(key));
12675
12767
  inFlight.set(key, pending);
12676
12768
  }
12677
12769
  waits.push(pending);
@@ -12687,11 +12779,14 @@ function createModelNames({ resolve: resolve2 }) {
12687
12779
  return [...pairs.values()];
12688
12780
  }
12689
12781
  function mapEvent(event) {
12690
- if (event?.type !== "assistant/message") return event;
12691
- const pair = pairOf(event.data?.message?.source);
12692
- const name3 = pair && nameOf(pair.provider, pair.model);
12782
+ const pair = pairOfEvent(event);
12783
+ if (pair === void 0 || event.type === "request/header") return event;
12784
+ const name3 = nameOf(pair.provider, pair.model);
12693
12785
  if (name3 === void 0) return event;
12694
12786
  const { data } = event;
12787
+ if (event.type === "user/message") {
12788
+ return { ...event, data: { ...data, source: { ...data.source, route: { ...data.source.route, model: name3 } } } };
12789
+ }
12695
12790
  const { message } = data;
12696
12791
  return { ...event, data: { ...data, message: { ...message, source: { ...message.source, model: name3 } } } };
12697
12792
  }
@@ -12922,6 +13017,18 @@ async function loadedHandoffPayload(core, { store, turnPageBuilder, dialogueSour
12922
13017
  }
12923
13018
  }
12924
13019
 
13020
+ // lib/handoff-discovery.js
13021
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13022
+ function formatAge(createdAt) {
13023
+ const diffMs = Math.max(0, Date.now() - createdAt);
13024
+ const mins = Math.floor(diffMs / 6e4);
13025
+ if (mins < 60) return `${mins} min ago`;
13026
+ const hours = Math.floor(mins / 60);
13027
+ if (hours < 24) return `${hours}h ago`;
13028
+ const days = Math.floor(hours / 24);
13029
+ return `${days}d ago`;
13030
+ }
13031
+
12925
13032
  // dsh/src/rpc.js
12926
13033
  var failure = (code, message) => ({ ok: false, error: { code, message, details: {} } });
12927
13034
  var live = (payload) => ({ ok: true, value: { state: "live", payload } });
@@ -12985,7 +13092,17 @@ function createRpcHandler({ table, store, now = Date.now, publish = () => {
12985
13092
  }
12986
13093
  return writePricing(entry, (model) => savePricingOverride(model, { readPrice, writePrice, presetId: sanitizePresetId(presetId) }));
12987
13094
  },
12988
- "pricing/delete": (entry) => writePricing(entry, deletePricingOverride)
13095
+ "pricing/delete": (entry) => writePricing(entry, deletePricingOverride),
13096
+ // A Store failure rejects the call, which the carrier answers as a transport failure; no empty catalog stands in for it.
13097
+ // The Host shapes each item's age, since the Client imports no `lib/`.
13098
+ "handoff/list": ({ watcher }) => live({
13099
+ items: watcher.listHandoffCandidates().map(({ loadToken, createdAt, nextTask, deliveredAt }) => ({
13100
+ loadToken,
13101
+ age: formatAge(createdAt),
13102
+ nextTask,
13103
+ deliveredAt
13104
+ }))
13105
+ })
12989
13106
  };
12990
13107
  return async (endpoint, payload) => {
12991
13108
  if (!Object.hasOwn(endpoints, endpoint)) return failure("unknown_endpoint", `unknown endpoint ${endpoint}`);
@@ -13596,13 +13713,43 @@ function assertQuery(q) {
13596
13713
  }
13597
13714
  }
13598
13715
  var lossless = (value) => JSON.parse(JSON.stringify(value));
13716
+ function createHandoffDelivery({ table, store, sessionTitle = () => void 0 }) {
13717
+ const recovery = createDshTurnRecovery();
13718
+ function retitle(session, handoffId) {
13719
+ try {
13720
+ const titles = sessionTitle();
13721
+ const nextTask = store.getHandoff(handoffId)?.nextTask;
13722
+ if (titles === void 0 || !nextTask?.trim()) return;
13723
+ titles.rename(session, nextTask);
13724
+ } catch (error) {
13725
+ writeDiagnostic(session.id, titleRenameFailed(error));
13726
+ }
13727
+ }
13728
+ async function payloadOf({ watcher, dialogueSource, dialogueProjection }, session, { load_token }) {
13729
+ const delivered = await watcher.deliverHandoff(load_token ? { loadToken: String(load_token) } : {});
13730
+ if (delivered.ok === false) return { error: delivered.error, retryable: delivered.retryable === true };
13731
+ if (!delivered.found) return delivered;
13732
+ retitle(session, delivered.handoff_id);
13733
+ return loadedHandoffPayload(delivered, {
13734
+ store,
13735
+ turnPageBuilder: buildTurnPage,
13736
+ dialogueSource,
13737
+ dialogueProjection,
13738
+ notice: recovery.notice
13739
+ });
13740
+ }
13741
+ return async ({ agent, signal, args: args2 }) => {
13742
+ const { session } = agent;
13743
+ const entry = await table.waitLive(session.id, signal);
13744
+ return lossless(withLoadRecovery(await payloadOf(entry, session, args2)));
13745
+ };
13746
+ }
13599
13747
  function createTools({
13600
13748
  defineTool: defineTool2,
13601
13749
  table,
13602
13750
  store,
13603
13751
  now = Date.now,
13604
- resolvePersisted = async () => null,
13605
- sessionTitle = () => void 0
13752
+ resolvePersisted = async () => null
13606
13753
  }) {
13607
13754
  const recovery = createDshTurnRecovery();
13608
13755
  const tool = ({ name: name3, description, parameters = {}, check = () => {
@@ -13625,30 +13772,6 @@ function createTools({
13625
13772
  dialogueProjection,
13626
13773
  recovery
13627
13774
  });
13628
- function retitle(session, handoffId) {
13629
- try {
13630
- const titles = sessionTitle();
13631
- const nextTask = store.getHandoff(handoffId)?.nextTask;
13632
- if (titles === void 0 || !nextTask?.trim()) return;
13633
- titles.rename(session, nextTask);
13634
- } catch (error) {
13635
- writeDiagnostic(session.id, titleRenameFailed(error));
13636
- }
13637
- }
13638
- async function loadHandoff({ watcher, session, dialogueSource, dialogueProjection }, { load_token, query, query_mode }) {
13639
- if (!load_token && query) return watcher.searchHandoffs({ query: String(query), queryMode: query_mode });
13640
- const delivered = await watcher.deliverHandoff(load_token ? { loadToken: String(load_token) } : {});
13641
- if (delivered.ok === false) return { error: delivered.error, retryable: delivered.retryable === true };
13642
- if (!delivered.found) return delivered;
13643
- retitle(session, delivered.handoff_id);
13644
- return loadedHandoffPayload(delivered, {
13645
- store,
13646
- turnPageBuilder: buildTurnPage,
13647
- dialogueSource,
13648
- dialogueProjection,
13649
- notice: recovery.notice
13650
- });
13651
- }
13652
13775
  return [
13653
13776
  defineTool2({
13654
13777
  name: "watcher_status",
@@ -13718,16 +13841,6 @@ function createTools({
13718
13841
  loadToken: load_token
13719
13842
  })
13720
13843
  }),
13721
- tool({
13722
- name: "load_handoff",
13723
- description: "Retrieve a prepared handoff package by token, by free-text search, or \u2014 with neither given \u2014 by auto-match over undelivered handoffs of this project from other sessions. A retrieved package carries the lineage behind it, oldest to newest, as the headlines of the newest sessions within a budget, ahead of them the older sessions collapsed into runs marked omitted, beside the newest page of its turns.",
13724
- parameters: {
13725
- load_token: { type: "string", description: "Semantic token from prepare_handoff (exact match)" },
13726
- query: { type: "string", description: "Free-text search when the token is unknown; returns top matches" },
13727
- query_mode: { type: "string", enum: ["plain", "advanced"], description: "plain (default) escapes input; advanced passes raw FTS5 syntax" }
13728
- },
13729
- run: async (args2, entry) => withLoadRecovery(await loadHandoff(entry, args2))
13730
- }),
13731
13844
  tool({
13732
13845
  name: "get_turn_skeleton",
13733
13846
  description: "Write the current context epoch to a turn skeleton file and a notes file whose `## NOTE[T]` headings are the slot set, and return both paths, the snapshot id to submit against, and the protocol for filling them.",
@@ -13785,7 +13898,191 @@ function createTools({
13785
13898
  }
13786
13899
 
13787
13900
  // dsh/src/continue.js
13901
+ import { randomUUID as randomUUID2 } from "node:crypto";
13902
+
13903
+ // dsh/src/load.js
13788
13904
  import { randomUUID } from "node:crypto";
13905
+ import { statSync as statSync4 } from "node:fs";
13906
+ import { isAbsolute as isAbsolute3, resolve as resolve2 } from "node:path";
13907
+ var READ_LINE_CAP = 2e3;
13908
+ var HEAD_LINES = 40;
13909
+ var RANGED = /\(lines (\d+)-(\d+)\)/;
13910
+ var NO_ROUTE = "No model route is known for this session yet.";
13911
+ var messageOf2 = (error) => error instanceof Error ? error.message : String(error);
13912
+ function locate(path3, cwd, projectDir) {
13913
+ const candidates = isAbsolute3(path3) ? [path3] : [resolve2(cwd, path3), ...projectDir ? [resolve2(projectDir, path3)] : []];
13914
+ return candidates.find((candidate) => statSync4(candidate, { throwIfNoEntry: false })?.isFile()) ?? null;
13915
+ }
13916
+ function windowsOf(entry) {
13917
+ if (entry.lines?.length) return entry.lines.map(([from, to]) => [from, to]);
13918
+ const ranged = (entry.resolvedSymbols ?? []).map((text) => RANGED.exec(text)).filter(Boolean).map(([, from, to]) => [Number(from), Number(to)]);
13919
+ return ranged.length > 0 ? ranged : null;
13920
+ }
13921
+ function planReads({ paths_to_keep: entries = [], project_dir: projectDir }, { cwd }) {
13922
+ const reads = [];
13923
+ const skipped = [];
13924
+ const toPlace = [];
13925
+ for (const entry of entries) {
13926
+ const file = locate(entry.path, cwd, projectDir);
13927
+ if (file === null) {
13928
+ skipped.push({ path: entry.path, reason: "no regular file at this path under the working directory or the project directory" });
13929
+ continue;
13930
+ }
13931
+ const windows = windowsOf(entry);
13932
+ if (windows === null && entry.symbols?.length) toPlace.push({ path: file, names: entry.symbols });
13933
+ for (const [offset, end] of windows ?? [[1, HEAD_LINES]]) {
13934
+ reads.push({ file_path: file, offset, limit: Math.min(end - offset + 1, READ_LINE_CAP), end });
13935
+ }
13936
+ }
13937
+ return { reads, skipped, toPlace };
13938
+ }
13939
+ var textOf2 = (content) => (content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("");
13940
+ function routeOf(agent) {
13941
+ const selection = agent.model.current();
13942
+ return selection ? { provider: selection.provider, model: selection.model } : null;
13943
+ }
13944
+ function ambiguityText(candidates) {
13945
+ const lines = candidates.map(({ load_token: token, created_at: createdAt, next_task_preview: preview }) => `- ${token} (${formatAge(createdAt)})${preview ? ` \u2014 ${preview}` : ""}`);
13946
+ return ["Several handoffs are pending for this project; run /sw-load <token> with one of them:", ...lines].join("\n");
13947
+ }
13948
+ function refusalOf(payload, token) {
13949
+ if (payload.error !== void 0) return `Loading failed: ${payload.error}`;
13950
+ if (payload.ambiguous) return ambiguityText(payload.candidates);
13951
+ if (!payload.found) return `No handoff found${token ? ` for ${token}; it may have expired` : " pending for this project"}`;
13952
+ return null;
13953
+ }
13954
+ var failed = (reason) => ({ failed: { reason } });
13955
+ async function loadHandoffInto({ agent, session, tools, deliver, kit, signal, token, cwdOf }) {
13956
+ const route = routeOf(agent);
13957
+ if (route === null) return failed(NO_ROUTE);
13958
+ const args2 = token ? { load_token: token } : {};
13959
+ let payload;
13960
+ try {
13961
+ payload = await deliver({ agent, signal, args: args2 });
13962
+ } catch (error) {
13963
+ return failed(`Loading failed: ${messageOf2(error)}`);
13964
+ }
13965
+ const refusal = refusalOf(payload, token);
13966
+ if (refusal !== null) return failed(refusal);
13967
+ const plan = planReads(payload, { cwd: cwdOf(session) });
13968
+ const idPrefix = `sw-load-${randomUUID().slice(0, 8)}`;
13969
+ const calls = [{ id: `${idPrefix}-0`, name: "load_handoff", arguments: JSON.stringify(args2), text: JSON.stringify(payload) }];
13970
+ const skipped = [...plan.skipped];
13971
+ const unread = [];
13972
+ const contexts = [];
13973
+ for (const [index, { file_path, offset, limit, end }] of plan.reads.entries()) {
13974
+ const id = `${idPrefix}-${index + 1}`;
13975
+ const readArgs = { file_path, offset, limit };
13976
+ let batch;
13977
+ try {
13978
+ batch = await tools.execute({ calls: [{ type: "tool-call", id, name: "read", arguments: JSON.stringify(readArgs) }], signal, agent });
13979
+ } catch (error) {
13980
+ skipped.push({ path: file_path, reason: messageOf2(error) });
13981
+ continue;
13982
+ }
13983
+ contexts.push(...batch.additionalContexts);
13984
+ const { result } = batch.results[0];
13985
+ if (result.isError) {
13986
+ skipped.push({ path: file_path, reason: result.error.message });
13987
+ continue;
13988
+ }
13989
+ calls.push({ id, name: "read", arguments: JSON.stringify(readArgs), text: textOf2(result.content) });
13990
+ const { lines = [], totalLines = 0 } = result.meta ?? {};
13991
+ const last = lines.at(-1)?.number ?? offset - 1;
13992
+ if (last < end && last < totalLines) unread.push({ path: file_path, range: [last + 1, end] });
13993
+ }
13994
+ let message;
13995
+ try {
13996
+ message = kit.createUserMessage(loadMessageInput({ route, calls }));
13997
+ } catch (error) {
13998
+ return failed(`Loading did not finish: ${messageOf2(error)}`);
13999
+ }
14000
+ const readCalls = calls.slice(1);
14001
+ return {
14002
+ loaded: {
14003
+ token: payload.load_token,
14004
+ reads: readCalls.length,
14005
+ files: new Set(readCalls.map((call) => JSON.parse(call.arguments).file_path)).size,
14006
+ skipped,
14007
+ unread,
14008
+ toPlace: plan.toPlace,
14009
+ skills: payload.skills_to_keep ?? [],
14010
+ empty: (payload.paths_to_keep ?? []).length === 0,
14011
+ message,
14012
+ contexts
14013
+ }
14014
+ };
14015
+ }
14016
+ var quoted = (value) => JSON.stringify(value).replace(/(?<=\s)\//g, "\\/");
14017
+ var lineageStepOf = (listing, closing) => `1. Place the summary in its lineage. \`lineage\` in the payload runs oldest to newest. The sessions the budget left out are collapsed into runs marked \`omitted\`, ahead of the newest sessions' headlines, and the budget may keep none. When the next task or what is already in context needs the headlines of an omitted run, \`lineage_headlines\` with that run's numbers as \`k\` (\`S2-S5\` is \`2-5\`) reads them; read a run for that need only, not by default. The payload's turn page holds the newest turns. From the page, ${listing}. When a headline bears on the next task and the page does not reach that member, call \`turn_page\` with that member's label as \`before\`; a session inside an omitted run is \`S{k}\`, \`k\` being its own number.${closing}`;
14018
+ var presentStep = "3. Present, then hold. Run `git status --short && git log -1 --oneline` once, then write, from the kept paths and that output: the objective, in one line; the working state, each claim the summary makes about the current state set against what the kept paths and the git output show (matches, differs and how, or reaches neither and so unverified); the next task and its entry points, with where the names to place below sit and the turns step 1 named; blockers and risks; the kept paths now in context and the load token. Then stop and wait for the user to confirm or correct it. The next task's first act begins after the reply.";
14019
+ var resumeStep = "3. Resume. Run `git status --short && git log -1 --oneline` once and set each claim the summary makes about the current state against the kept paths and that output; a claim they do not reach counts as a deviation when your next step depends on it. Before your first step on the task, say in one sentence which task you are resuming and your next step, adding a deviation or risk only when it changes that step. Then carry the task on in this turn from the summary and the history, within what it was already authorized to do. A question, approval or permission the task left open still stands: ask it and wait. When a deviation from the summary leaves the task's direction or authorization, or a safe next step, undecided, ask one specific question about it and wait; otherwise carry on.";
14020
+ function loadedText({ token, skipped, unread, toPlace, skills, empty }, { resume = false } = {}) {
14021
+ const summaryOnly = resume ? "when the task calls for it" : "after the user agrees";
14022
+ const skillStep = skills.length > 0 ? `2. Load the kept skills: invoke ${skills.map(quoted).join(", ")} through the skill tool. A skill named only in the summary is invoked ${summaryOnly}.` : `2. The handoff keeps no skills; a skill named only in the summary is invoked through the skill tool ${summaryOnly}.`;
14023
+ const lineageStep = resume ? lineageStepOf("read the turns whose `A:` note bears on the next task", "") : lineageStepOf("list the turns whose `A:` note bears on the next task, by their `S{k}:{T}` address", " That list is what step 3 reports.");
14024
+ const sections = [
14025
+ `Handoff ${quoted(token)} is loaded. The harness has run its delivery, recorded as the \`load_handoff\` call, and the \`read\` calls for the kept ranges, except those listed as skipped below. Their results are in the message the harness placed before this one, in that order and as returned: the delivery's payload, then each read result, which opens with its \`<path>\` line. Do not repeat any of those calls; where a result says part of it was cut or failed, complete it as that result says.`,
14026
+ ["Then:", lineageStep, skillStep, resume ? resumeStep : presentStep].join("\n")
14027
+ ];
14028
+ if (skipped.length > 0) {
14029
+ sections.push(["Skipped, not read:", ...skipped.map(({ path: path3, reason }) => `- ${quoted(path3)}: ${quoted(reason)}`)].join("\n"));
14030
+ }
14031
+ if (unread.length > 0) {
14032
+ sections.push(["Not reached by its read; read the rest of the range:", ...unread.map(({ path: path3, range: [from, to] }) => `- ${quoted(path3)} lines ${from}-${to}`)].join("\n"));
14033
+ }
14034
+ if (toPlace.length > 0) {
14035
+ sections.push(["Names to place with a `grep -n` in the file:", ...toPlace.map(({ path: path3, names }) => `- ${quoted(path3)}: ${names.map(quoted).join(", ")}`)].join("\n"));
14036
+ }
14037
+ if (empty) sections.push(resume ? "The handoff keeps no paths: resume from the summary and the history." : "The handoff keeps no paths: ask the user what they are working on.");
14038
+ return sections.join("\n\n");
14039
+ }
14040
+ function handOver({ agent, loaded, resume }) {
14041
+ agent.inject(loaded.message);
14042
+ for (const context of loaded.contexts) agent.inject(context);
14043
+ agent.followup({
14044
+ id: randomUUID(),
14045
+ role: "user",
14046
+ content: [{ type: "text", text: loadedText(loaded, { resume }) }],
14047
+ source: { kind: "user" }
14048
+ });
14049
+ }
14050
+ var COMMAND_NAME = "sw-load";
14051
+ var COMMAND_DESCRIPTION = "Load a handoff into the session";
14052
+ var COMMAND_INPUT = { hint: "handoff token (optional)" };
14053
+ var USAGE = "Usage: /sw-load [token]";
14054
+ var NOT_IDLE = "/sw-load runs only while the agent is idle.";
14055
+ var failure2 = (text) => ({ kind: "error", text });
14056
+ var success = (text) => ({ kind: "success", text });
14057
+ function createLoadCommand({ deliver, tools, kit, cwdOf }) {
14058
+ async function handler({ agent, rawInput, signal }) {
14059
+ const token = rawInput.trim();
14060
+ if (/\s/.test(token)) return failure2(USAGE);
14061
+ let maintenance;
14062
+ try {
14063
+ maintenance = agent.runMaintenance(() => loadHandoffInto({
14064
+ agent,
14065
+ session: agent.session,
14066
+ tools,
14067
+ deliver,
14068
+ kit,
14069
+ signal,
14070
+ token,
14071
+ cwdOf
14072
+ }));
14073
+ } catch {
14074
+ return failure2(NOT_IDLE);
14075
+ }
14076
+ const outcome = await maintenance;
14077
+ if (outcome.failed) return failure2(outcome.failed.reason);
14078
+ const { loaded } = outcome;
14079
+ handOver({ agent, loaded });
14080
+ return success(`Loaded handoff ${loaded.token}: ${loaded.reads} reads over ${loaded.files} files, ${loaded.skipped.length} skipped.`);
14081
+ }
14082
+ return { name: COMMAND_NAME, description: COMMAND_DESCRIPTION, input: COMMAND_INPUT, handler };
14083
+ }
14084
+
14085
+ // dsh/src/continue.js
13789
14086
  var SUMMARY_PROVIDER = "session-watcher";
13790
14087
  var SUMMARY_MODEL = "sw-continue";
13791
14088
  var ClearError = class extends Error {
@@ -13795,21 +14092,21 @@ var ClearError = class extends Error {
13795
14092
  this.code = code;
13796
14093
  }
13797
14094
  };
13798
- var COMMAND_NAME = "sw-continue";
13799
- var COMMAND_DESCRIPTION = "Clear the session and resume from its last handoff";
13800
- var USAGE = "Usage: /sw-continue (no arguments)";
14095
+ var COMMAND_NAME2 = "sw-continue";
14096
+ var COMMAND_DESCRIPTION2 = "Clear the session and resume from its last handoff";
14097
+ var USAGE2 = "Usage: /sw-continue (no arguments)";
13801
14098
  var NO_HANDOFF = "No handoff has been prepared in this session. Run the sw-handoff skill first.";
13802
14099
  var STALE_HANDOFF = "The last handoff was prepared before the session's latest context reset. Run the sw-handoff skill again.";
13803
- var NOT_IDLE = "/sw-continue runs only while the agent is idle.";
14100
+ var NOT_IDLE2 = "/sw-continue runs only while the agent is idle.";
13804
14101
  var NOT_STARTED = "Clearing could not start; the session history is unchanged.";
13805
14102
  var NOT_FINISHED = "Clearing did not finish cleanly; some history may be shadowed. Inspect the session before retrying.";
13806
14103
  var NOT_SAVED = "Clearing finished, but the session could not be saved.";
13807
14104
  var NOTHING_TO_CLEAR = "No history to clear.";
13808
14105
  var checkpointText = (token) => `[Session Watcher] Context cleared by /sw-continue. Handoff token: ${token}`;
13809
- var followupText = (token) => `Continue from handoff ${token}: load it with the sw-load skill.`;
13810
- var clearedText = ({ count, shadowedTokenCount }, token) => `Cleared ${count} history items (~${shadowedTokenCount} tokens); loading handoff ${token}.`;
14106
+ var clearedText = ({ count, shadowedTokenCount }, token) => `Cleared ${count} history items (~${shadowedTokenCount} tokens); loaded handoff ${token}.`;
14107
+ var notLoadedText = (reason, token) => `Context cleared, but the handoff was not loaded: ${reason}. Run /sw-load ${token}.`;
13811
14108
  var textBlocks = (token) => [{ type: "text", text: checkpointText(token) }];
13812
- var messageOf2 = (error) => error instanceof Error ? error.message : String(error);
14109
+ var messageOf3 = (error) => error instanceof Error ? error.message : String(error);
13813
14110
  function nodesAfterHead(session, meter) {
13814
14111
  const { nodes } = meter.measure(session);
13815
14112
  const first = nodes.length > 0 && session.eventAt(nodes[0].seq).type === "system/message" ? 1 : 0;
@@ -13817,12 +14114,12 @@ function nodesAfterHead(session, meter) {
13817
14114
  }
13818
14115
  function closeWithError(session, lifecycle, cause) {
13819
14116
  try {
13820
- session.append("compaction/end", { ...lifecycle, error: messageOf2(cause) });
14117
+ session.append("compaction/end", { ...lifecycle, error: messageOf3(cause) });
13821
14118
  } catch {
13822
14119
  }
13823
14120
  }
13824
14121
  function clearSurface({ session, meter, kit, commandId, token }) {
13825
- const compactionId = kit.CompactionId(randomUUID());
14122
+ const compactionId = kit.CompactionId(randomUUID2());
13826
14123
  const lifecycle = { compactionId, sourceCommandId: commandId, turn: null };
13827
14124
  let range;
13828
14125
  let checkpoint;
@@ -13836,7 +14133,7 @@ function clearSurface({ session, meter, kit, commandId, token }) {
13836
14133
  });
13837
14134
  startEvent = session.append("compaction/start", lifecycle);
13838
14135
  } catch (cause) {
13839
- throw new ClearError("start", `clearing could not start: ${messageOf2(cause)}`, { cause });
14136
+ throw new ClearError("start", `clearing could not start: ${messageOf3(cause)}`, { cause });
13840
14137
  }
13841
14138
  const shadowedSeqs = range.map((node) => node.seq);
13842
14139
  const shadowedRange = { start: shadowedSeqs[0], end: shadowedSeqs.at(-1) };
@@ -13859,54 +14156,56 @@ function clearSurface({ session, meter, kit, commandId, token }) {
13859
14156
  });
13860
14157
  } catch (cause) {
13861
14158
  closeWithError(session, lifecycle, cause);
13862
- throw new ClearError("commit", `clearing did not finish: ${messageOf2(cause)}`, { cause });
14159
+ throw new ClearError("commit", `clearing did not finish: ${messageOf3(cause)}`, { cause });
13863
14160
  }
13864
14161
  try {
13865
14162
  session.append("compaction/end", lifecycle);
13866
14163
  } catch (cause) {
13867
- throw new ClearError("commit", `clearing did not close: ${messageOf2(cause)}`, { cause });
14164
+ throw new ClearError("commit", `clearing did not close: ${messageOf3(cause)}`, { cause });
13868
14165
  }
13869
14166
  return { count: shadowedSeqs.length, shadowedTokenCount };
13870
14167
  }
13871
- var failure2 = (text) => ({ kind: "error", text });
13872
- var success = (text) => ({ kind: "success", text });
13873
- function createContinueCommand({ table, store, kit, meter, flush }) {
14168
+ var failure3 = (text) => ({ kind: "error", text });
14169
+ var success2 = (text) => ({ kind: "success", text });
14170
+ function createContinueCommand({ table, store, kit, meter, flush, deliver, tools, cwdOf }) {
13874
14171
  async function handler({ commandId, agent, rawInput, signal }) {
13875
- if (rawInput.trim().length > 0) return failure2(USAGE);
14172
+ if (rawInput.trim().length > 0) return failure3(USAGE2);
13876
14173
  const { session } = agent;
13877
14174
  const handoff = store.loadHandoffBySession(session.id);
13878
- if (handoff === null) return failure2(NO_HANDOFF);
14175
+ if (handoff === null) return failure3(NO_HANDOFF);
13879
14176
  const { watcher } = await table.waitLive(session.id, signal);
13880
- if (handoff.segment !== watcher.getStatus().segment) return failure2(STALE_HANDOFF);
14177
+ if (handoff.segment !== watcher.getStatus().segment) return failure3(STALE_HANDOFF);
13881
14178
  const token = handoff.loadToken;
13882
14179
  let maintenance;
13883
14180
  try {
13884
14181
  maintenance = agent.runMaintenance(async () => {
13885
14182
  const cleared = clearSurface({ session, meter, kit, commandId, token });
13886
14183
  if (cleared === null) return { status: "empty" };
14184
+ const load = await loadHandoffInto({ agent, session, tools, deliver, kit, signal, token, cwdOf });
13887
14185
  try {
13888
14186
  await flush(session);
13889
14187
  } catch {
13890
14188
  return { status: "unsaved" };
13891
14189
  }
13892
- return { status: "cleared", cleared };
14190
+ return { status: "cleared", cleared, load };
13893
14191
  });
13894
14192
  } catch {
13895
- return failure2(NOT_IDLE);
14193
+ return failure3(NOT_IDLE2);
13896
14194
  }
13897
14195
  let outcome;
13898
14196
  try {
13899
14197
  outcome = await maintenance;
13900
14198
  } catch (error) {
13901
- if (error instanceof ClearError) return failure2(error.code === "start" ? NOT_STARTED : NOT_FINISHED);
14199
+ if (error instanceof ClearError) return failure3(error.code === "start" ? NOT_STARTED : NOT_FINISHED);
13902
14200
  throw error;
13903
14201
  }
13904
- if (outcome.status === "empty") return success(NOTHING_TO_CLEAR);
13905
- if (outcome.status === "unsaved") return failure2(NOT_SAVED);
13906
- agent.followup(kit.createUserMessage({ content: [{ type: "text", text: followupText(token) }], source: { kind: "user" } }));
13907
- return success(clearedText(outcome.cleared, token));
14202
+ if (outcome.status === "empty") return success2(NOTHING_TO_CLEAR);
14203
+ if (outcome.status === "unsaved") return failure3(NOT_SAVED);
14204
+ if (outcome.load.failed) return failure3(notLoadedText(outcome.load.failed.reason, token));
14205
+ handOver({ agent, loaded: outcome.load.loaded, resume: true });
14206
+ return success2(clearedText(outcome.cleared, token));
13908
14207
  }
13909
- return { name: COMMAND_NAME, description: COMMAND_DESCRIPTION, handler };
14208
+ return { name: COMMAND_NAME2, description: COMMAND_DESCRIPTION2, handler };
13910
14209
  }
13911
14210
 
13912
14211
  // dsh/src/skills.js
@@ -13937,100 +14236,9 @@ function registerSkills(ctx, { skillsDir }) {
13937
14236
  }
13938
14237
  }
13939
14238
 
13940
- // dsh/src/catalog.js
13941
- import { randomUUID as randomUUID2 } from "node:crypto";
13942
-
13943
- // lib/handoff-discovery.js
13944
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13945
- function discoverHandoffs(dbPath, projectId, sessionId, { ttlDays, queryLimit }) {
13946
- if (!projectId || !sessionId) return [];
13947
- let db;
13948
- try {
13949
- db = new DatabaseSync2(dbPath, { readOnly: true });
13950
- const tableCheck = db.prepare(
13951
- "SELECT name FROM sqlite_master WHERE type='table' AND name='handoff'"
13952
- ).get();
13953
- if (!tableCheck) return [];
13954
- const cutoff = Date.now() - ttlDays * 24 * 3600 * 1e3;
13955
- const stmt = db.prepare(`SELECT load_token, next_task, created_at, summary_tokens, kept_tokens
13956
- FROM handoff
13957
- WHERE project_id = ? AND delivered_at IS NULL AND session_id <> ? AND created_at > ?
13958
- ORDER BY created_at DESC LIMIT ?`);
13959
- return stmt.all(projectId, sessionId, cutoff, queryLimit);
13960
- } catch {
13961
- return [];
13962
- } finally {
13963
- try {
13964
- if (db) db.close();
13965
- } catch {
13966
- }
13967
- }
13968
- }
13969
- function formatHandoffContext(rows, maxDisplay, taskPreviewChars) {
13970
- if (!rows || rows.length === 0) return null;
13971
- const hasMore = rows.length > maxDisplay;
13972
- const display = rows.slice(0, maxDisplay);
13973
- const formatTokens = (summaryTok, keptTok) => {
13974
- const total = (summaryTok || 0) + (keptTok || 0);
13975
- if (total === 0) return null;
13976
- if (total >= 1e3) return `~${Math.round(total / 1e3)}k tokens`;
13977
- return `~${total} tokens`;
13978
- };
13979
- const formatAge = (createdAt) => {
13980
- const diffMs = Math.max(0, Date.now() - createdAt);
13981
- const mins = Math.floor(diffMs / 6e4);
13982
- if (mins < 60) return `${mins} min ago`;
13983
- const hours = Math.floor(mins / 60);
13984
- if (hours < 24) return `${hours}h ago`;
13985
- const days = Math.floor(hours / 24);
13986
- return `${days}d ago`;
13987
- };
13988
- const truncTask = (task) => {
13989
- if (!task) return "";
13990
- if (task.length <= taskPreviewChars) return task;
13991
- return task.slice(0, taskPreviewChars - 3) + "...";
13992
- };
13993
- if (display.length === 1) {
13994
- const r = display[0];
13995
- const age = formatAge(r.created_at);
13996
- const tokens = formatTokens(r.summary_tokens, r.kept_tokens);
13997
- const tokStr = tokens ? `, ${tokens} to restore` : "";
13998
- const taskLine = r.next_task ? `
13999
- Task: ${truncTask(r.next_task)}` : "";
14000
- return `[Session Watcher] Handoff available (token: ${r.load_token}, ${age}${tokStr}).${taskLine}`;
14001
- }
14002
- const header = hasMore ? `[Session Watcher] ${maxDisplay}+ pending handoffs (showing newest ${maxDisplay}):` : `[Session Watcher] ${display.length} pending handoffs for this project:`;
14003
- const lines = display.map((r, i2) => {
14004
- const age = formatAge(r.created_at);
14005
- const tokens = formatTokens(r.summary_tokens, r.kept_tokens);
14006
- const tokStr = tokens ? `, ${tokens}` : "";
14007
- const task = truncTask(r.next_task);
14008
- const taskStr = task ? ` \u2014 ${task}` : "";
14009
- return `${i2 + 1}. ${r.load_token} (${age}${tokStr})${taskStr}`;
14010
- });
14011
- const footer = hasMore ? "(older handoffs available \u2014 use load_handoff with a query to search)" : "";
14012
- return [header, ...lines, footer].join("\n");
14013
- }
14014
-
14015
- // dsh/src/catalog.js
14016
- function catalogMessageFor({ dbPath, projectId, sessionId }) {
14017
- const rows = discoverHandoffs(dbPath, projectId, sessionId, {
14018
- ttlDays: HANDOFF_HOOK_TTL_DAYS,
14019
- queryLimit: HANDOFF_HOOK_QUERY_LIMIT
14020
- });
14021
- const text = formatHandoffContext(rows, HANDOFF_HOOK_MAX_DISPLAY, HANDOFF_HOOK_TASK_PREVIEW_CHARS);
14022
- if (text === null) return null;
14023
- return {
14024
- id: randomUUID2(),
14025
- role: "user",
14026
- content: [{ type: "text", text }],
14027
- source: { kind: "session-watcher", form: "catalog" }
14028
- };
14029
- }
14030
-
14031
14239
  // dsh/src/host.js
14032
14240
  var HOST_INJECT = ["sessions", "sessionQuery", "tools", "skills", "llm"];
14033
- function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, continueKit }) {
14241
+ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored2, defineTool: defineTool2, skillsDir, commandKit }) {
14034
14242
  initStore(storePath);
14035
14243
  ctx.effect(() => () => {
14036
14244
  try {
@@ -14082,36 +14290,37 @@ function applyHost(ctx, { storePath, turnNotesRoot, loadIsIgnored: loadIsIgnored
14082
14290
  table.feed(session.id, event);
14083
14291
  }));
14084
14292
  ctx.on("session/disposed", (session) => guarded(session.id, () => table.dispose(session.id)));
14085
- ctx.on("agent/created", ({ agent, source }) => guarded(agent.session.id, () => {
14086
- if (source !== "startup" && source !== "resume") return;
14087
- if (agent.session.header.origin === "subagent") return;
14088
- const message = catalogMessageFor({
14089
- dbPath: storePath,
14090
- projectId: resolveProjectKey({ cwd: agent.session.header.cwd }),
14091
- sessionId: agent.session.id
14092
- });
14093
- if (message !== null) agent.inject(message);
14094
- }));
14095
14293
  const sessionTitle = () => ctx.get("sessionTitle");
14096
- for (const definition of createTools({ defineTool: defineTool2, table, store: getStore(), resolvePersisted, sessionTitle })) ctx.tools.register(definition);
14294
+ for (const definition of createTools({ defineTool: defineTool2, table, store: getStore(), resolvePersisted })) ctx.tools.register(definition);
14295
+ const deliver = createHandoffDelivery({ table, store: getStore(), sessionTitle });
14097
14296
  registerSkills(ctx, { skillsDir });
14098
- ctx.inject(["commands", "tokenMeter"], (child) => {
14297
+ ctx.inject(["commands", "tokenMeter", "workingDirectory"], (child) => {
14099
14298
  child.commands.register(createContinueCommand({
14100
14299
  table,
14101
14300
  store: getStore(),
14102
- kit: continueKit,
14301
+ kit: commandKit,
14103
14302
  meter: child.tokenMeter,
14104
- flush: (session) => ctx.sessions.flush(session)
14303
+ flush: (session) => ctx.sessions.flush(session),
14304
+ deliver,
14305
+ tools: ctx.tools,
14306
+ cwdOf: (session) => child.workingDirectory.get(session)
14307
+ }));
14308
+ });
14309
+ ctx.inject(["commands", "workingDirectory"], (child) => {
14310
+ child.commands.register(createLoadCommand({
14311
+ deliver,
14312
+ tools: ctx.tools,
14313
+ kit: commandKit,
14314
+ cwdOf: (session) => child.workingDirectory.get(session)
14105
14315
  }));
14106
14316
  });
14107
- ctx.inject(["connection"], (child) => {
14108
- const remove = child.root.get("connection").rpc.handle("/session-watcher", createRpcHandler({
14317
+ ctx.inject(["connection", "webServer"], (child) => {
14318
+ child.extend({ webServer: child.webServer }).connection.rpc.handle("/session-watcher", createRpcHandler({
14109
14319
  table,
14110
14320
  store: getStore(),
14111
14321
  publish: hub.publish,
14112
14322
  resolvePersisted
14113
14323
  }));
14114
- child.effect(() => remove);
14115
14324
  child.connection.fetch.register(hub.route());
14116
14325
  child.effect(() => () => hub.closeAll());
14117
14326
  });
@@ -14138,7 +14347,7 @@ var inject = HOST_INJECT;
14138
14347
  function apply(ctx) {
14139
14348
  applyHost(ctx, {
14140
14349
  defineTool,
14141
- continueKit: { CompactionId, compactCheckpointSource, createUserMessage },
14350
+ commandKit: { CompactionId, compactCheckpointSource, createUserMessage },
14142
14351
  storePath: defaultDbPath(),
14143
14352
  turnNotesRoot: DSH_TURN_NOTES_ROOT,
14144
14353
  loadIsIgnored,
@@ -13,6 +13,8 @@ Prepare a handoff package so the next session can resume without re-reading what
13
13
 
14
14
  - **The call fails** — an error instead of that shape, whatever its cause. Stop this run: report to the user that the turn skeleton could not be captured; do not produce or submit notes, and do not go on to `prepare_handoff`.
15
15
 
16
+ - A successful reply freezes the run: perform steps 2–7 using the returned metadata and existing context. Unverified facts remain in Blockers / risks; resolving them belongs to next_task.
17
+
16
18
  2. **Produce turn notes** you MUST follow [`NOTES.md`](NOTES.md) exactly for what each note says. Write them inline — do not delegate to a subagent.
17
19
 
18
20
  3. **Submit notes** via the `submit_turn_notes` tool with `snapshot_id`. The tool reads `notes_path` itself.
@@ -24,20 +26,16 @@ Prepare a handoff package so the next session can resume without re-reading what
24
26
  - **`invalid_snapshot`** — the capture's source identity or required metadata is invalid, including a transcript that cannot be read. Stop: report to the user.
25
27
  - **`storage_unavailable`** (`retryable: true`) — store temporarily unavailable. Stop: report to the user; they may re-run the skill when ready.
26
28
 
27
- 4. **Fetch bucket data** via the `get_bucket_summary` tool.
28
-
29
- If `metrics.br < 0.05` AND few turns: note "Context is still light — handoff may not be necessary yet, but proceeding as requested."
29
+ 4. **Fetch bucket data** via the `get_bucket_summary` tool and complete any explicitly requested runtime handoff actions before this call. Call `get_bucket_summary` once per handoff.
30
30
 
31
31
  5. **Select paths to keep.** The kept set is what the next task must have in hand before it can act. Candidates are the bucket summary plus any path this segment used that the bucket lacks. For each candidate, name the act of `next_task` that opens it; a candidate with no such act is not kept, whatever this segment did with it.
32
32
  - The repo outlives the context reset and the conversation does not, so a file the next session can read on demand is kept only where that first act needs it in hand: the file the task edits, the test that guards it, the artifact under discussion.
33
33
  - A blob under review is read by its reviewer, so what the next task needs is the review's return and the sources it cites.
34
- - Read each candidate's `tokens` from the bucket summary and total them before prepare. Where one path carries more than half that total, state which act needs all of it, or keep its `symbols` alone.
34
+ - Use the returned `tokens` to estimate the kept total. Where one path carries more than half that total, state which act needs all of it, or keep its `symbols` alone. Unavailable or symbol-only costs may remain unknown, `prepare_handoff` returns the final total.
35
35
 
36
36
  Always: `userOverride` decides that path; a `keep:` list in the arguments is kept verbatim; symbols come from `activeSymbols` into `paths_to_keep[].symbols`; memories, `CONTEXT.md`, `CLAUDE.md` stay off the list.
37
37
 
38
- Before prepare, tell the user the kept total, each kept path with the act that opens it, and every edited or repeatedly read bucket path left out.
39
-
40
- 6. **Select skills** — `skills_to_keep`: only skills actively guiding the workflow or required by next_task. Skip one-shot completed skills. Never include `sw-load` — it drives the load flow itself and is always invoked automatically. If the user's `keep:` list includes skill names, use those directly.
38
+ 6. **Select skills** — `skills_to_keep`: only skills actively guiding the workflow or required by next_task. Skip one-shot completed skills. Never include `sw-load` — it drives the load flow itself. If the user's `keep:` list includes skill names, use those directly.
41
39
 
42
40
  7. **Write the summary** you MUST following [`SUMMARY.md`](SUMMARY.md) exactly. Redact secrets as `[REDACTED]`
43
41
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nomadop/session-watcher-dsh",
3
- "version": "0.10.1",
3
+ "version": "0.10.2",
4
4
  "description": "Session Watcher as a DeepSeek Harness host plugin",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -15,10 +15,13 @@
15
15
  "publishConfig": {
16
16
  "access": "public"
17
17
  },
18
+ "engines": {
19
+ "dsh": ">=0.2.2-rc.1"
20
+ },
18
21
  "peerDependencies": {
19
- "@deepseek-ai/dsh-compaction": ">=0.2.0-rc.1",
20
- "@deepseek-ai/dsh-llm": ">=0.2.0-rc.1",
21
- "@deepseek-ai/dsh-tools": ">=0.2.0-rc.1"
22
+ "@deepseek-ai/dsh-compaction": ">=0.2.2-rc.1",
23
+ "@deepseek-ai/dsh-llm": ">=0.2.2-rc.1",
24
+ "@deepseek-ai/dsh-tools": ">=0.2.2-rc.1"
22
25
  },
23
26
  "dsh": {
24
27
  "client": {
@@ -1,45 +0,0 @@
1
- ---
2
- name: sw-load
3
- description: "Use when the user provides a handoff token, asks to resume or continue previous work, the host's handoff notice announces a handoff, or you are about to call load_handoff."
4
- ---
5
-
6
- # Session Watcher Load Handoff
7
-
8
- Restore a previous session's handoff package into context so work can resume.
9
-
10
- ## Steps
11
-
12
- 1. **Load the handoff.** Resolve a token from the skill `args`, from the user's message, or from the host's own handoff notice, which names pending handoffs by token: the Claude Code SessionStart hook's additionalContext, or the message DSH injects when the agent starts or resumes. Then call the `load_handoff` tool, whose schema carries the three ways in.
13
-
14
- A token you were handed is the one path that proceeds without asking. Any other way in — a free-text match, an auto-match, or several tokens offered at once — means listing what came back with each one's age and task preview and letting the user pick before you go on. Nothing found → tell the user the token is expired or invalid, and ask for direction.
15
-
16
- 2. **Read the kept paths.** Relative paths resolve against CWD, then `project_dir`.
17
-
18
- One strategy per entry, the first row that applies:
19
-
20
- | Entry has | Read at load |
21
- |---|---|
22
- | `lines` | each range |
23
- | `resolvedSymbols` | the `(lines a-b)` each string carries |
24
- | neither | the file's first 40 lines; with `symbols`, also `grep -n` each name in the file to place the entry points |
25
-
26
- Each read is the host's file-reading tool over a line range of the kept file. Each call names one file. Issue every read for every entry in one message — each further turn re-reads the whole accumulated context.
27
-
28
- Unresolvable path → tell the user, skip. Empty `paths_to_keep` → ask the user what they are working on.
29
-
30
- 3. **Place the summary in its lineage.** `lineage` runs oldest to newest. The sessions the budget left out are collapsed into runs marked `omitted`, ahead of the newest sessions' headlines, and the budget may keep none. When the next task or what is already in context needs the headlines of an omitted run, `lineage_headlines` with that run's numbers as `k` (`S2-S5` is `2-5`) reads them; read a run for that need only, not by default. The injected page holds the newest turns and is already in context. From the page, list the turns whose `A:` note bears on the next task, by their `S{k}:{T}` address. When a headline bears on the next task and the page does not reach that member, call `turn_page` with that member's label as `before`; a session inside an omitted run is `S{k}`, `k` being its own number. That list is what step 5 reports.
31
-
32
- 4. **Load the kept skills** — invoke each name in `skills_to_keep` through the host's skill tool. A skill named only in the summary text is invoked after the user agrees.
33
-
34
- 5. **Present, then hold.** One `git status --short && git log -1 --oneline`, then write, from the kept paths and that output:
35
- - Objective, one line
36
- - Working state — each claim the summary makes about the current state, set against what the kept paths and the git output show: matches, differs (say how), or reaches neither (say unverified)
37
- - Next task and its entry points — the `neither` entries with where their symbols sit, and the turns step 3 named
38
- - Blockers and risks
39
- - The kept paths now in context and the load token you used
40
-
41
- Then stop and wait for the user to confirm or correct it. The next task's first act begins after the reply.
42
-
43
- ### Completion criterion
44
-
45
- Done when the kept paths are in context, the state is presented in the shape step 5 gives, and the user has replied confirming or correcting it.