@yankeguo/dsh-devlead 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/index.js +508 -225
  2. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -6,8 +6,7 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // packages/devlead/src/index.ts
9
- import { mkdir, stat } from "node:fs/promises";
10
- import { isAbsolute } from "node:path";
9
+ import { mkdir } from "node:fs/promises";
11
10
  import { Service } from "@deepseek-ai/cordis";
12
11
  import z2 from "@deepseek-ai/schemastery";
13
12
  import { appendPluginRecord as appendPluginRecord2 } from "@deepseek-ai/dsh-session";
@@ -29,6 +28,36 @@ import {
29
28
  isDevLeadTransition,
30
29
  notificationId
31
30
  } from "@yankeguo/dsh-devlead-protocol";
31
+
32
+ // packages/devlead/src/error.ts
33
+ var DevLeadError = class extends Error {
34
+ /**
35
+ * @param message - human-readable failure text.
36
+ * @param code - stable code from {@link DevLeadErrorCode}.
37
+ */
38
+ constructor(message, code) {
39
+ super(message);
40
+ this.code = code;
41
+ this.name = "DevLeadError";
42
+ }
43
+ code;
44
+ };
45
+ function isDevLeadError(error51) {
46
+ if (error51 instanceof DevLeadError) return true;
47
+ if (!(error51 instanceof Error)) return false;
48
+ const candidate = error51;
49
+ return typeof candidate.code === "string" && candidate.code.startsWith("DEVLEAD_");
50
+ }
51
+ function thrownMessage(error51) {
52
+ if (error51 instanceof Error) return error51.message;
53
+ if (typeof error51 === "object" && error51 !== null && "message" in error51) {
54
+ const message = error51.message;
55
+ if (typeof message === "string") return message;
56
+ }
57
+ return String(error51);
58
+ }
59
+
60
+ // packages/devlead/src/domain.ts
32
61
  function createDevLeadPromptMessage(text, lead) {
33
62
  return createUserMessage({
34
63
  content: [{ type: "text", text }],
@@ -62,12 +91,25 @@ function devLeadNotification(sessionId, sessionTitle, transition, turn, at, erro
62
91
  ...summary === void 0 ? {} : { summary }
63
92
  };
64
93
  }
94
+ var MAX_INSTANT = 864e13;
95
+ function representableInstant(at, fallback) {
96
+ return Number.isSafeInteger(at) && at >= 0 && at <= MAX_INSTANT ? at : fallback;
97
+ }
65
98
  function expectRecord(value, type) {
66
99
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
67
100
  throw new Error(`record "${type}" payload is not a plain object`);
68
101
  }
69
102
  return value;
70
103
  }
104
+ function expectFields(value, label, required2, optional2 = []) {
105
+ const allowed = /* @__PURE__ */ new Set([...required2, ...optional2]);
106
+ for (const key of Object.keys(value)) {
107
+ if (!allowed.has(key)) throw new Error(`${label} carries unexpected field ${JSON.stringify(key)}`);
108
+ }
109
+ for (const key of required2) {
110
+ if (!(key in value)) throw new Error(`${label} is missing field ${JSON.stringify(key)}`);
111
+ }
112
+ }
71
113
  function expectEnvelope(value, type, kind) {
72
114
  if (value.kind !== kind) {
73
115
  throw new Error(`record "${type}" carries unexpected kind ${JSON.stringify(value.kind)}`);
@@ -76,99 +118,102 @@ function expectEnvelope(value, type, kind) {
76
118
  throw new Error(`record "${type}" carries unsupported version ${JSON.stringify(value.version)}`);
77
119
  }
78
120
  }
121
+ function decodeInstant(value, label) {
122
+ if (!Number.isSafeInteger(value) || value < 0 || value > MAX_INSTANT) {
123
+ throw new Error(`${label} must be a non-negative integer instant in epoch milliseconds`);
124
+ }
125
+ return value;
126
+ }
127
+ function decodeTurn(value, label) {
128
+ if (!Number.isSafeInteger(value) || value < 1) {
129
+ throw new Error(`${label} must be a positive safe integer`);
130
+ }
131
+ return value;
132
+ }
79
133
  function decodeModeRecord(value) {
80
134
  const record2 = expectRecord(value, DEVLEAD_MODE_RECORD_TYPE);
135
+ const label = "mode record";
136
+ expectFields(record2, label, ["kind", "version", "enabled", "at"]);
81
137
  expectEnvelope(record2, DEVLEAD_MODE_RECORD_TYPE, "devlead/mode");
82
- if (typeof record2.enabled !== "boolean") throw new Error("mode record enabled must be a boolean");
83
- if (!Number.isSafeInteger(record2.at) || record2.at < 0) {
84
- throw new Error("mode record at must be a non-negative safe integer");
85
- }
86
- return { kind: "devlead/mode", version: DEVLEAD_RECORD_VERSION, enabled: record2.enabled, at: record2.at };
138
+ if (typeof record2.enabled !== "boolean") throw new Error(`${label} enabled must be a boolean`);
139
+ return {
140
+ kind: "devlead/mode",
141
+ version: DEVLEAD_RECORD_VERSION,
142
+ enabled: record2.enabled,
143
+ at: decodeInstant(record2.at, `${label} at`)
144
+ };
87
145
  }
88
146
  function decodeWatchRecord(value) {
89
147
  const record2 = expectRecord(value, DEVLEAD_WATCH_RECORD_TYPE);
148
+ const label = "watch record";
149
+ expectFields(record2, label, ["kind", "version", "sessions", "at"]);
90
150
  expectEnvelope(record2, DEVLEAD_WATCH_RECORD_TYPE, "devlead/watch");
91
151
  if (!Array.isArray(record2.sessions) || !record2.sessions.every((session) => typeof session === "string" && session.length > 0)) {
92
- throw new Error("watch record sessions must be a non-empty string array");
152
+ throw new Error(`${label} sessions must be a non-empty string array`);
93
153
  }
94
154
  if (new Set(record2.sessions).size !== record2.sessions.length) {
95
- throw new Error("watch record sessions must be unique");
96
- }
97
- if (!Number.isSafeInteger(record2.at) || record2.at < 0) {
98
- throw new Error("watch record at must be a non-negative safe integer");
155
+ throw new Error(`${label} sessions must be unique`);
99
156
  }
100
157
  return {
101
158
  kind: "devlead/watch",
102
159
  version: DEVLEAD_RECORD_VERSION,
103
160
  sessions: [...record2.sessions],
104
- at: record2.at
161
+ at: decodeInstant(record2.at, `${label} at`)
105
162
  };
106
163
  }
107
164
  function decodeNotification(value) {
108
165
  const record2 = expectRecord(value, DEVLEAD_NOTIFICATION_RECORD_TYPE);
109
- if (typeof record2.id !== "string" || record2.id.length === 0) throw new Error("notification id must be a non-empty string");
166
+ const label = "notification";
167
+ expectFields(record2, label, ["id", "sessionId", "transition", "turn", "at"], [
168
+ "sessionTitle",
169
+ "error",
170
+ "summary"
171
+ ]);
172
+ if (typeof record2.id !== "string" || record2.id.length === 0) {
173
+ throw new Error(`${label} id must be a non-empty string`);
174
+ }
110
175
  if (typeof record2.sessionId !== "string" || record2.sessionId.length === 0) {
111
- throw new Error("notification sessionId must be a non-empty string");
176
+ throw new Error(`${label} sessionId must be a non-empty string`);
112
177
  }
113
178
  if (record2.sessionTitle !== void 0 && (typeof record2.sessionTitle !== "string" || record2.sessionTitle.length === 0)) {
114
- throw new Error("notification sessionTitle must be a non-empty string when present");
179
+ throw new Error(`${label} sessionTitle must be a non-empty string when present`);
115
180
  }
116
181
  if (!isDevLeadTransition(record2.transition)) {
117
- throw new Error(`notification transition ${JSON.stringify(record2.transition)} is not recognized`);
118
- }
119
- if (!Number.isSafeInteger(record2.turn) || record2.turn < 1) {
120
- throw new Error("notification turn must be a positive safe integer");
121
- }
122
- if (!Number.isSafeInteger(record2.at) || record2.at < 0) {
123
- throw new Error("notification at must be a non-negative safe integer");
182
+ throw new Error(`${label} transition ${JSON.stringify(record2.transition)} is not recognized`);
124
183
  }
184
+ const turn = decodeTurn(record2.turn, `${label} turn`);
125
185
  if (record2.error !== void 0 && (typeof record2.error !== "string" || record2.error.length === 0)) {
126
- throw new Error("notification error must be a non-empty string when present");
186
+ throw new Error(`${label} error must be a non-empty string when present`);
127
187
  }
128
188
  if (record2.summary !== void 0 && (typeof record2.summary !== "string" || record2.summary.length === 0)) {
129
- throw new Error("notification summary must be a non-empty string when present");
189
+ throw new Error(`${label} summary must be a non-empty string when present`);
130
190
  }
131
- const id = notificationId(record2.sessionId, record2.turn, record2.transition);
132
- if (record2.id !== id) throw new Error(`notification id must be ${id}`);
191
+ const id = notificationId(record2.sessionId, turn, record2.transition);
192
+ if (record2.id !== id) throw new Error(`${label} id must be ${id}`);
133
193
  return {
134
194
  id,
135
195
  sessionId: record2.sessionId,
136
196
  ...record2.sessionTitle === void 0 ? {} : { sessionTitle: record2.sessionTitle },
137
197
  transition: record2.transition,
138
- turn: record2.turn,
139
- at: record2.at,
198
+ turn,
199
+ at: decodeInstant(record2.at, `${label} at`),
140
200
  ...record2.error === void 0 ? {} : { error: record2.error },
141
201
  ...record2.summary === void 0 ? {} : { summary: record2.summary }
142
202
  };
143
203
  }
144
204
  function decodeNotificationRecord(value) {
145
205
  const record2 = expectRecord(value, DEVLEAD_NOTIFICATION_RECORD_TYPE);
206
+ const label = "notification record";
207
+ expectFields(record2, label, ["kind", "version", "notification"]);
146
208
  expectEnvelope(record2, DEVLEAD_NOTIFICATION_RECORD_TYPE, "devlead/notification");
147
209
  return decodeNotification(record2.notification);
148
210
  }
149
211
  function failureExcerpt(error51) {
150
- const message = error51 instanceof Error ? error51.message : typeof error51 === "object" && error51 !== null && "message" in error51 && typeof error51.message === "string" ? error51.message : String(error51);
151
- return excerptLine(message, DEVLEAD_ERROR_EXCERPT_MAX);
212
+ return excerptLine(thrownMessage(error51), DEVLEAD_ERROR_EXCERPT_MAX);
152
213
  }
153
-
154
- // packages/devlead/src/error.ts
155
- var DevLeadError = class extends Error {
156
- /**
157
- * @param message - human-readable failure text.
158
- * @param code - stable code from {@link DevLeadErrorCode}.
159
- */
160
- constructor(message, code) {
161
- super(message);
162
- this.code = code;
163
- this.name = "DevLeadError";
164
- }
165
- code;
166
- };
167
- function isDevLeadError(error51) {
168
- if (error51 instanceof DevLeadError) return true;
169
- if (!(error51 instanceof Error)) return false;
170
- const candidate = error51;
171
- return typeof candidate.code === "string" && candidate.code.startsWith("DEVLEAD_");
214
+ function assistantExcerpt(blocks) {
215
+ const text = blocks.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
216
+ return excerptLine(text, DEVLEAD_ERROR_EXCERPT_MAX);
172
217
  }
173
218
 
174
219
  // packages/devlead/src/fold.ts
@@ -14716,12 +14761,15 @@ var notificationSchema = external_exports.object({
14716
14761
  at: external_exports.number().int().nonnegative(),
14717
14762
  error: external_exports.string().min(1).optional(),
14718
14763
  summary: external_exports.string().min(1).optional()
14719
- });
14764
+ }).strict();
14720
14765
  function retainNotification(notifications, notification) {
14721
14766
  if (notifications.some((existing) => existing.id === notification.id)) return notifications;
14722
14767
  const next = [...notifications, notification];
14723
14768
  return next.length <= DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2 ? next : next.slice(next.length - DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2);
14724
14769
  }
14770
+ function sameSessionIds(left, right) {
14771
+ return left.length === right.length && left.every((id, index) => id === right[index]);
14772
+ }
14725
14773
  var devLeadProjectionStateSchema = external_exports.object({
14726
14774
  enabled: external_exports.boolean(),
14727
14775
  sessions: external_exports.array(external_exports.string().min(1)),
@@ -14733,8 +14781,17 @@ var devLeadProjectionSchema = external_exports.object({
14733
14781
  sessions: external_exports.array(external_exports.string().min(1)),
14734
14782
  notifications: external_exports.array(notificationSchema)
14735
14783
  }).strict();
14784
+ var wireViews = /* @__PURE__ */ new WeakMap();
14736
14785
  function devLeadProjectionView(state) {
14737
- return { enabled: state.enabled, sessions: state.sessions, notifications: state.notifications };
14786
+ const cached2 = wireViews.get(state);
14787
+ if (cached2 !== void 0) return cached2;
14788
+ const view = {
14789
+ enabled: state.enabled,
14790
+ sessions: state.sessions,
14791
+ notifications: state.notifications
14792
+ };
14793
+ wireViews.set(state, view);
14794
+ return view;
14738
14795
  }
14739
14796
  function applyDevLeadProjection(state, event) {
14740
14797
  if (state.failure !== null) return state;
@@ -14748,7 +14805,7 @@ function applyDevLeadProjection(state, event) {
14748
14805
  }
14749
14806
  case DEVLEAD_WATCH_RECORD_TYPE2: {
14750
14807
  const watch = decodeWatchRecord(record2.data);
14751
- return { ...state, sessions: watch.sessions };
14808
+ return sameSessionIds(state.sessions, watch.sessions) ? state : { ...state, sessions: watch.sessions };
14752
14809
  }
14753
14810
  case DEVLEAD_NOTIFICATION_RECORD_TYPE2: {
14754
14811
  const notification = decodeNotificationRecord(record2.data);
@@ -14760,20 +14817,27 @@ function applyDevLeadProjection(state, event) {
14760
14817
  }
14761
14818
  } catch (error51) {
14762
14819
  const message = error51 instanceof Error ? error51.message : String(error51);
14763
- return {
14820
+ const failure = {
14764
14821
  ...state,
14765
14822
  failure: `devlead replay failed at session event ${event.seq} (${record2.type}): ${message}`
14766
14823
  };
14824
+ wireViews.set(failure, devLeadProjectionView(state));
14825
+ return failure;
14767
14826
  }
14768
14827
  }
14769
14828
  var devLeadProjectionDefinition = {
14770
14829
  key: DEVLEAD_PROJECTION_KEY,
14771
14830
  stateSchema: devLeadProjectionStateSchema,
14831
+ // The unit owns no Session-metadata-derived state, so it ignores the header
14832
+ // and inherited-prefix arguments the registry passes.
14772
14833
  init: emptyDevLeadProjectionState,
14773
14834
  apply: applyDevLeadProjection,
14774
14835
  wire: {
14775
14836
  viewSchema: devLeadProjectionSchema,
14776
- view: devLeadProjectionView
14837
+ view: devLeadProjectionView,
14838
+ // The retained digest makes this value large, and only the open
14839
+ // conversation reads it: keep it out of every Session summary/list row.
14840
+ summary: false
14777
14841
  },
14778
14842
  // 1: the initial durable representation of the mode, watch set, and keyed
14779
14843
  // notification records.
@@ -14785,15 +14849,15 @@ import { appendPluginRecord, pluginRecordOf as pluginRecordOf2 } from "@deepseek
14785
14849
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
14786
14850
  import {
14787
14851
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION as DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3,
14788
- DEVLEAD_ERROR_EXCERPT_MAX as DEVLEAD_ERROR_EXCERPT_MAX2,
14789
14852
  DEVLEAD_MESSAGE_KIND as DEVLEAD_MESSAGE_KIND2,
14790
14853
  DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE3,
14791
14854
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE3,
14792
14855
  DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE3,
14793
- excerptLine as excerptLine2,
14856
+ isDevLeadTransition as isDevLeadTransition2,
14794
14857
  notificationLine
14795
14858
  } from "@yankeguo/dsh-devlead-protocol";
14796
14859
  var MAX_DIGEST_LINES = 12;
14860
+ var DELIVERY_RETRY_MS = 1e3;
14797
14861
  function renderDevLeadNotice(notifications, total = notifications.length) {
14798
14862
  const shown = notifications.slice(-MAX_DIGEST_LINES);
14799
14863
  const omitted = total - shown.length;
@@ -14828,9 +14892,17 @@ var DevLeadNotificationHub = class {
14828
14892
  resuming = /* @__PURE__ */ new Set();
14829
14893
  /** Latest assistant excerpt observed per watched Session, bounded and pruned with the index. */
14830
14894
  lastAssistant = /* @__PURE__ */ new Map();
14895
+ /** Sessions whose replay failure has already been reported, so a corrupt log warns once. */
14896
+ warnedFailures = /* @__PURE__ */ new Set();
14897
+ started = false;
14831
14898
  stopping = false;
14832
- /** Install the lifecycle listeners and index every currently live lead. */
14899
+ /**
14900
+ * Install the lifecycle listeners and index every currently live lead.
14901
+ * Calling this twice is a no-op: the hub owns exactly one listener set.
14902
+ */
14833
14903
  start() {
14904
+ if (this.started) return;
14905
+ this.started = true;
14834
14906
  this.bootstrap();
14835
14907
  this.ctx.effect(function* () {
14836
14908
  this.ctx.on("agent/created", ({ agent }) => {
@@ -14872,15 +14944,22 @@ var DevLeadNotificationHub = class {
14872
14944
  }
14873
14945
  /**
14874
14946
  * Read one Session's fold state, treating a replay failure as unavailable.
14947
+ * A corrupt log is reported once per Session to keep a poisoned Session from
14948
+ * flooding the log on every event.
14875
14949
  * @param session - live Session.
14876
14950
  * @returns the fold state, or undefined when the projection is invalid.
14877
14951
  */
14878
14952
  stateOf(session) {
14879
14953
  const state = this.readState(session);
14954
+ const sessionId = String(session.id);
14880
14955
  if (state.failure !== null) {
14881
- this.ctx.logger.warn(`devlead: ${state.failure}`);
14956
+ if (!this.warnedFailures.has(sessionId)) {
14957
+ this.warnedFailures.add(sessionId);
14958
+ this.ctx.logger.warn(`devlead: ${state.failure}`);
14959
+ }
14882
14960
  return void 0;
14883
14961
  }
14962
+ this.warnedFailures.delete(sessionId);
14884
14963
  return state;
14885
14964
  }
14886
14965
  /**
@@ -14913,6 +14992,7 @@ var DevLeadNotificationHub = class {
14913
14992
  watched: /* @__PURE__ */ new Set(),
14914
14993
  pending: [],
14915
14994
  timer: void 0,
14995
+ scheduled: false,
14916
14996
  flushing: false
14917
14997
  };
14918
14998
  this.leads.set(sessionId, runtime);
@@ -14965,15 +15045,19 @@ var DevLeadNotificationHub = class {
14965
15045
  this.lastAssistant.delete(watched);
14966
15046
  }
14967
15047
  }
15048
+ runtime.pending = [];
14968
15049
  this.leads.delete(leadId);
14969
15050
  }
14970
15051
  this.resuming.delete(leadId);
15052
+ this.warnedFailures.delete(leadId);
14971
15053
  }
14972
- /** Clear one pending coalescing timer. */
15054
+ /** Clear one pending coalescing timer or queued zero-delay flush. */
14973
15055
  clearTimer(runtime) {
14974
- if (runtime.timer === void 0) return;
14975
- clearTimeout(runtime.timer);
14976
- runtime.timer = void 0;
15056
+ if (runtime.timer !== void 0) {
15057
+ clearTimeout(runtime.timer);
15058
+ runtime.timer = void 0;
15059
+ }
15060
+ runtime.scheduled = false;
14977
15061
  }
14978
15062
  /**
14979
15063
  * Observe one committed Session event for lead-state changes and watched
@@ -15006,8 +15090,7 @@ var DevLeadNotificationHub = class {
15006
15090
  * @param blocks - assistant message content blocks.
15007
15091
  */
15008
15092
  rememberAssistant(sessionId, blocks) {
15009
- const text = blocks.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
15010
- const excerpt = excerptLine2(text, DEVLEAD_ERROR_EXCERPT_MAX2);
15093
+ const excerpt = assistantExcerpt(blocks);
15011
15094
  if (excerpt !== void 0) this.lastAssistant.set(sessionId, excerpt);
15012
15095
  }
15013
15096
  /**
@@ -15018,8 +15101,10 @@ var DevLeadNotificationHub = class {
15018
15101
  */
15019
15102
  notificationOf(session, event) {
15020
15103
  if (event.type !== "turn/end") return void 0;
15104
+ const turn = event.data.turn;
15105
+ if (!Number.isSafeInteger(turn) || turn < 1) return void 0;
15021
15106
  const reason = event.data.reason.kind;
15022
- const transition = reason === "completed" || reason === "aborted" || reason === "blocked" || reason === "error" || reason === "max-tokens" || reason === "interrupted" || reason === "forked" ? reason : "interrupted";
15107
+ const transition = isDevLeadTransition2(reason) ? reason : "interrupted";
15023
15108
  const title = this.ctx.get("sessionTitle")?.get(session)?.title;
15024
15109
  const error51 = reason === "error" ? failureExcerpt(event.data.reason.error) : void 0;
15025
15110
  const summary = this.lastAssistant.get(String(session.id));
@@ -15027,14 +15112,16 @@ var DevLeadNotificationHub = class {
15027
15112
  String(session.id),
15028
15113
  title,
15029
15114
  transition,
15030
- event.data.turn,
15031
- event.time,
15115
+ turn,
15116
+ representableInstant(event.time, Date.now()),
15032
15117
  error51,
15033
15118
  summary
15034
15119
  );
15035
15120
  }
15036
15121
  /**
15037
- * Persist one notification into a lead Session and queue its wake-up.
15122
+ * Persist one notification into a lead Session and queue its wake-up. A
15123
+ * notification whose identity is already queued is not queued twice, so a
15124
+ * replayed `turn/end` cannot double a digest line.
15038
15125
  * @param leadId - lead Session identity.
15039
15126
  * @param notification - observed notification.
15040
15127
  */
@@ -15045,8 +15132,9 @@ var DevLeadNotificationHub = class {
15045
15132
  try {
15046
15133
  appendPluginRecord(session, DEVLEAD_NOTIFICATION_RECORD_TYPE3, notificationRecord(notification));
15047
15134
  } catch (error51) {
15048
- this.ctx.logger.warn(`devlead: could not record a notification for lead "${leadId}": ${String(error51)}`);
15135
+ this.ctx.logger.warn(`devlead: could not record a notification for lead "${leadId}": ${thrownMessage(error51)}`);
15049
15136
  }
15137
+ if (runtime.pending.some((existing) => existing.id === notification.id)) return;
15050
15138
  runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15051
15139
  this.scheduleFlush(runtime);
15052
15140
  }
@@ -15055,9 +15143,11 @@ var DevLeadNotificationHub = class {
15055
15143
  * @param runtime - lead runtime row.
15056
15144
  */
15057
15145
  scheduleFlush(runtime) {
15058
- if (this.stopping || runtime.timer !== void 0 || runtime.flushing) return;
15146
+ if (this.stopping || runtime.timer !== void 0 || runtime.scheduled || runtime.flushing) return;
15059
15147
  if (this.config.batchMs <= 0) {
15148
+ runtime.scheduled = true;
15060
15149
  queueMicrotask(() => {
15150
+ runtime.scheduled = false;
15061
15151
  void this.flush(runtime);
15062
15152
  });
15063
15153
  return;
@@ -15073,7 +15163,9 @@ var DevLeadNotificationHub = class {
15073
15163
  * @returns fulfillment after the delivery attempt settles.
15074
15164
  */
15075
15165
  async flush(runtime) {
15076
- if (this.stopping || runtime.flushing || runtime.pending.length === 0) return;
15166
+ if (this.stopping) return;
15167
+ if (this.leads.get(runtime.sessionId) !== runtime) return;
15168
+ if (runtime.flushing || runtime.pending.length === 0) return;
15077
15169
  const agent = this.ctx.agents.get(toSessionId(runtime.sessionId));
15078
15170
  if (agent === void 0) {
15079
15171
  if (this.config.wakeColdSession) await this.resumeCold(runtime);
@@ -15082,27 +15174,48 @@ var DevLeadNotificationHub = class {
15082
15174
  const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(toSessionId(runtime.sessionId)) ?? false;
15083
15175
  if (archived) {
15084
15176
  runtime.pending = [];
15177
+ this.clearTimer(runtime);
15085
15178
  return;
15086
15179
  }
15087
15180
  const batch = runtime.pending;
15088
15181
  runtime.pending = [];
15182
+ this.clearTimer(runtime);
15089
15183
  runtime.flushing = true;
15184
+ let failed = false;
15090
15185
  try {
15091
15186
  if (!this.hasQueuedNotice(agent)) {
15092
15187
  agent.followup(createDevLeadNoticeMessage(renderDevLeadNotice(batch)));
15093
15188
  try {
15094
15189
  await this.ctx.sessions.flush(agent.session);
15095
15190
  } catch (error51) {
15096
- this.ctx.logger.warn(`devlead: notification digest was not flushed for lead "${runtime.sessionId}": ${String(error51)}`);
15191
+ this.ctx.logger.warn(`devlead: notification digest could not be flushed for lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15097
15192
  }
15098
15193
  }
15099
15194
  } catch (error51) {
15100
- this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${String(error51)}`);
15195
+ this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15101
15196
  runtime.pending = [...batch, ...runtime.pending].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15197
+ failed = true;
15102
15198
  } finally {
15103
15199
  runtime.flushing = false;
15104
15200
  }
15105
- if (runtime.pending.length > 0) this.scheduleFlush(runtime);
15201
+ if (runtime.pending.length > 0 && this.leads.get(runtime.sessionId) === runtime) {
15202
+ if (failed) {
15203
+ this.scheduleRetry(runtime);
15204
+ } else {
15205
+ this.scheduleFlush(runtime);
15206
+ }
15207
+ }
15208
+ }
15209
+ /**
15210
+ * Arm one bounded retry after a failed wake-up delivery.
15211
+ * @param runtime - lead runtime row.
15212
+ */
15213
+ scheduleRetry(runtime) {
15214
+ if (this.stopping || runtime.timer !== void 0 || runtime.scheduled || runtime.flushing) return;
15215
+ runtime.timer = setTimeout(() => {
15216
+ runtime.timer = void 0;
15217
+ void this.flush(runtime);
15218
+ }, DELIVERY_RETRY_MS);
15106
15219
  }
15107
15220
  /**
15108
15221
  * Whether one lead Agent already holds an undelivered digest notice.
@@ -15121,6 +15234,7 @@ var DevLeadNotificationHub = class {
15121
15234
  * @returns fulfillment after the resume attempt settles.
15122
15235
  */
15123
15236
  async resumeCold(runtime) {
15237
+ if (this.stopping) return;
15124
15238
  const leadId = runtime.sessionId;
15125
15239
  if (this.resuming.has(leadId)) return;
15126
15240
  const controller = this.ctx.get("sessionController");
@@ -15128,13 +15242,16 @@ var DevLeadNotificationHub = class {
15128
15242
  this.resuming.add(leadId);
15129
15243
  try {
15130
15244
  const resolved = await controller.resolveAgent(toSessionId(leadId));
15245
+ if (this.stopping) return;
15131
15246
  if ("error" in resolved) {
15132
15247
  this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${resolved.error.message}`);
15133
15248
  return;
15134
15249
  }
15135
15250
  this.syncLead(resolved.agent);
15136
15251
  } catch (error51) {
15137
- this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${String(error51)}`);
15252
+ if (!this.stopping) {
15253
+ this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${thrownMessage(error51)}`);
15254
+ }
15138
15255
  } finally {
15139
15256
  this.resuming.delete(leadId);
15140
15257
  }
@@ -15143,11 +15260,7 @@ var DevLeadNotificationHub = class {
15143
15260
 
15144
15261
  // packages/devlead/src/views.ts
15145
15262
  import { SessionId as toSessionId2 } from "@deepseek-ai/dsh-session";
15146
- import {
15147
- DEVLEAD_ERROR_EXCERPT_MAX as DEVLEAD_ERROR_EXCERPT_MAX3,
15148
- excerptLine as excerptLine3,
15149
- isDevLeadTransition as isDevLeadTransition2
15150
- } from "@yankeguo/dsh-devlead-protocol";
15263
+ import { isDevLeadTransition as isDevLeadTransition3 } from "@yankeguo/dsh-devlead-protocol";
15151
15264
  async function devLeadWorkspaceView(workspace) {
15152
15265
  const status = await workspace.status();
15153
15266
  return {
@@ -15160,8 +15273,11 @@ async function devLeadWorkspaceView(workspace) {
15160
15273
  updatedAt: workspace.updatedAt
15161
15274
  };
15162
15275
  }
15163
- async function collectSessionIds(deps, workspace) {
15164
- const { ctx } = deps;
15276
+ function rethrowIfAborted(error51, signal) {
15277
+ if (signal?.aborted === true) throw error51;
15278
+ }
15279
+ async function collectSessionIds(deps, workspace, exhaustive = false) {
15280
+ const { ctx, signal } = deps;
15165
15281
  const ids = /* @__PURE__ */ new Set();
15166
15282
  const admissible = (id) => {
15167
15283
  const session = ctx.sessions.get(toSessionId2(id)) ?? ctx.agents.get(toSessionId2(id))?.session;
@@ -15186,20 +15302,22 @@ async function collectSessionIds(deps, workspace) {
15186
15302
  const query = ctx.get("sessionQuery");
15187
15303
  if (query !== void 0) {
15188
15304
  try {
15189
- const records = await query.listSessions();
15305
+ const records = await query.listSessions(signal);
15190
15306
  for (const record2 of records) {
15191
- if (ids.size >= deps.maxListedSessions) break;
15307
+ if (!exhaustive && ids.size >= deps.maxListedSessions) break;
15192
15308
  if (record2.header.origin === "subagent") continue;
15193
15309
  ids.add(record2.header.id);
15194
15310
  }
15195
- } catch {
15311
+ } catch (error51) {
15312
+ rethrowIfAborted(error51, signal);
15196
15313
  }
15197
15314
  }
15198
15315
  }
15316
+ signal?.throwIfAborted();
15199
15317
  return [...ids].filter(admissible);
15200
15318
  }
15201
15319
  async function knownSessions(deps, ids) {
15202
- const { ctx } = deps;
15320
+ const { ctx, signal } = deps;
15203
15321
  const result = /* @__PURE__ */ new Map();
15204
15322
  const pendingTitles = [];
15205
15323
  for (const id of ids) {
@@ -15207,7 +15325,7 @@ async function knownSessions(deps, ids) {
15207
15325
  const agent = ctx.agents.get(toSessionId2(id));
15208
15326
  const live = session !== void 0 || agent !== void 0;
15209
15327
  const sessionObject = session ?? agent?.session;
15210
- let title = sessionObject === void 0 ? void 0 : ctx.get("sessionTitle")?.get(sessionObject)?.title;
15328
+ const title = sessionObject === void 0 ? void 0 : ctx.get("sessionTitle")?.get(sessionObject)?.title;
15211
15329
  if (title === void 0) pendingTitles.push(id);
15212
15330
  result.set(id, { title, header: sessionObject?.header, live });
15213
15331
  }
@@ -15215,7 +15333,7 @@ async function knownSessions(deps, ids) {
15215
15333
  const query = ctx.get("sessionQuery");
15216
15334
  if (query !== void 0) {
15217
15335
  try {
15218
- const observations = await query.readTitleSnapshots(pendingTitles.map((id) => toSessionId2(id)));
15336
+ const observations = await query.readTitleSnapshots(pendingTitles.map((id) => toSessionId2(id)), signal);
15219
15337
  for (const observation of observations) {
15220
15338
  if (observation.status !== "fulfilled") continue;
15221
15339
  const { session, title: snapshot } = observation.value;
@@ -15224,19 +15342,53 @@ async function knownSessions(deps, ids) {
15224
15342
  if (entry === void 0) continue;
15225
15343
  result.set(id, { ...entry, title: snapshot?.title ?? entry.title, header: session });
15226
15344
  }
15227
- } catch {
15345
+ } catch (error51) {
15346
+ rethrowIfAborted(error51, signal);
15228
15347
  }
15229
15348
  }
15230
15349
  }
15231
15350
  return result;
15232
15351
  }
15352
+ async function readSessionFacts(deps, ids) {
15353
+ const known = await knownSessions(deps, ids);
15354
+ const workspaces = /* @__PURE__ */ new Map();
15355
+ const archived = /* @__PURE__ */ new Set();
15356
+ const registry2 = deps.ctx.get("workspaceRegistry");
15357
+ if (registry2 !== void 0) {
15358
+ const requested = new Set(ids);
15359
+ for (const sessionId of registry2.archivedSessionIds) {
15360
+ const id = String(sessionId);
15361
+ if (requested.has(id)) archived.add(id);
15362
+ }
15363
+ for (const workspace of registry2.list()) {
15364
+ for (const sessionId of workspace.sessionIds) {
15365
+ const id = String(sessionId);
15366
+ if (!requested.has(id) || workspaces.has(id)) continue;
15367
+ workspaces.set(id, workspace);
15368
+ }
15369
+ }
15370
+ }
15371
+ return { known, workspaces, archived };
15372
+ }
15373
+ function rankSessionIds(deps, ids, facts, limit) {
15374
+ const ranked = ids.map((id) => ({
15375
+ id,
15376
+ watched: deps.isWatched(id),
15377
+ running: deps.ctx.agents.get(toSessionId2(id))?.status === "running",
15378
+ createdAt: facts.known.get(id)?.header?.createdAt ?? 0
15379
+ }));
15380
+ ranked.sort((left, right) => {
15381
+ if (left.watched !== right.watched) return left.watched ? -1 : 1;
15382
+ if (left.running !== right.running) return left.running ? -1 : 1;
15383
+ return right.createdAt - left.createdAt || left.id.localeCompare(right.id);
15384
+ });
15385
+ return ranked.slice(0, Math.max(1, limit)).map((entry) => entry.id);
15386
+ }
15233
15387
  function lastAssistantExcerpt(events) {
15234
15388
  for (let index = events.length - 1; index >= 0; index -= 1) {
15235
15389
  const event = events[index];
15236
15390
  if (event === void 0 || event.type !== "assistant/message") continue;
15237
- const blocks = event.data.message.content;
15238
- const text = blocks.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
15239
- const excerpt = excerptLine3(text, DEVLEAD_ERROR_EXCERPT_MAX3);
15391
+ const excerpt = assistantExcerpt(event.data.message.content);
15240
15392
  if (excerpt !== void 0) return excerpt;
15241
15393
  }
15242
15394
  return void 0;
@@ -15244,13 +15396,16 @@ function lastAssistantExcerpt(events) {
15244
15396
  async function sessionLogFacts(deps, sessionId) {
15245
15397
  const query = deps.ctx.get("sessionQuery");
15246
15398
  if (query === void 0) return {};
15399
+ deps.signal?.throwIfAborted();
15247
15400
  let events;
15248
15401
  try {
15249
15402
  const snapshot = await query.readSession(toSessionId2(sessionId));
15250
15403
  events = snapshot.events;
15251
- } catch {
15404
+ } catch (error51) {
15405
+ rethrowIfAborted(error51, deps.signal);
15252
15406
  return {};
15253
15407
  }
15408
+ deps.signal?.throwIfAborted();
15254
15409
  const last = events.at(-1);
15255
15410
  let lastTurn;
15256
15411
  let lastTransition;
@@ -15261,10 +15416,8 @@ async function sessionLogFacts(deps, sessionId) {
15261
15416
  }
15262
15417
  if (event.type === "turn/end") {
15263
15418
  const kind = event.data.reason.kind;
15264
- if (isDevLeadTransition2(kind)) {
15265
- lastTransition = kind;
15266
- lastError = kind === "error" ? event.data.reason.error.message : void 0;
15267
- }
15419
+ lastTransition = isDevLeadTransition3(kind) ? kind : "interrupted";
15420
+ lastError = kind === "error" ? event.data.reason.error.message : void 0;
15268
15421
  }
15269
15422
  }
15270
15423
  const lastAssistant = lastAssistantExcerpt(events);
@@ -15276,52 +15429,43 @@ async function sessionLogFacts(deps, sessionId) {
15276
15429
  ...lastAssistant === void 0 ? {} : { lastAssistant }
15277
15430
  };
15278
15431
  }
15279
- async function buildSessionView(deps, sessionId, withLog, known) {
15432
+ async function buildSessionView(deps, sessionId, withLog, facts) {
15280
15433
  const { ctx } = deps;
15281
- const facts = known ?? (await knownSessions(deps, [sessionId])).get(sessionId);
15282
- const session = ctx.sessions.get(toSessionId2(sessionId));
15434
+ const known = facts.known.get(sessionId);
15283
15435
  const agent = ctx.agents.get(toSessionId2(sessionId));
15284
- const archived = ctx.get("workspaceRegistry")?.archivedSessionIds.includes(toSessionId2(sessionId)) ?? false;
15285
- const workspace = workspaceOf(deps, sessionId);
15286
- const live = facts?.live ?? false;
15436
+ const workspace = facts.workspaces.get(sessionId);
15287
15437
  const boundary = agent === void 0 ? void 0 : ctx.agents.turnBoundaryOf(agent.session);
15288
15438
  const log = withLog ? await sessionLogFacts(deps, sessionId) : {};
15439
+ const lastTurn = log.lastTurn ?? boundary?.lastTurn;
15289
15440
  return {
15290
15441
  sessionId,
15291
- ...facts?.title === void 0 ? {} : { title: facts.title },
15442
+ ...known?.title === void 0 ? {} : { title: known.title },
15292
15443
  ...workspace === void 0 ? {} : { workspaceId: workspace.id, workspaceTitle: workspace.title },
15293
- ...facts?.header?.cwd === void 0 ? {} : { cwd: facts.header.cwd },
15294
- live,
15444
+ ...known?.header?.cwd === void 0 ? {} : { cwd: known.header.cwd },
15445
+ live: known?.live ?? false,
15295
15446
  running: agent?.status === "running",
15296
15447
  watched: deps.isWatched(sessionId),
15297
- archived,
15298
- ...boundary === void 0 ? {} : { lastTurn: boundary.lastTurn },
15448
+ archived: facts.archived.has(sessionId),
15449
+ ...lastTurn === void 0 ? {} : { lastTurn },
15299
15450
  ...agent === void 0 ? {} : { pendingInputs: agent.inbox.nextTurn.length + agent.inbox.nextStep.length },
15300
15451
  ...log,
15301
- ...log.lastTurn === void 0 && boundary !== void 0 ? { lastTurn: boundary.lastTurn } : {},
15302
- ...facts?.header?.createdAt === void 0 ? {} : { createdAt: facts.header.createdAt }
15452
+ ...known?.header?.createdAt === void 0 ? {} : { createdAt: known.header.createdAt }
15303
15453
  };
15304
15454
  }
15305
- function workspaceOf(deps, sessionId) {
15306
- const registry2 = deps.ctx.get("workspaceRegistry");
15307
- if (registry2 === void 0) return void 0;
15308
- for (const workspace of registry2.list()) {
15309
- if (workspace.sessionIds.includes(toSessionId2(sessionId))) return workspace;
15310
- }
15311
- return void 0;
15312
- }
15313
15455
  async function devLeadSessionView(deps, sessionId, withLog) {
15314
- return await buildSessionView(deps, sessionId, withLog);
15456
+ const facts = await readSessionFacts(deps, [sessionId]);
15457
+ return await buildSessionView(deps, sessionId, withLog, facts);
15315
15458
  }
15316
- async function devLeadSessionViews(deps, ids, withLog) {
15317
- const facts = await knownSessions(deps, ids);
15459
+ async function devLeadSessionViews(deps, ids, withLog, facts) {
15460
+ const batch = facts ?? await readSessionFacts(deps, ids);
15318
15461
  const views = [];
15319
15462
  for (const id of ids) {
15320
- views.push(await buildSessionView(deps, id, withLog, facts.get(id)));
15463
+ deps.signal?.throwIfAborted();
15464
+ views.push(await buildSessionView(deps, id, withLog, batch));
15321
15465
  }
15322
15466
  return views;
15323
15467
  }
15324
- async function resolveWorkspaceReference(ctx, reference) {
15468
+ async function resolveWorkspaceReference(ctx, reference, signal) {
15325
15469
  const registry2 = ctx.get("workspaceRegistry");
15326
15470
  if (registry2 === void 0) {
15327
15471
  throw new DevLeadError("this Host composes no Workspace registry", "DEVLEAD_WORKSPACE_NOT_FOUND");
@@ -15330,33 +15474,58 @@ async function resolveWorkspaceReference(ctx, reference) {
15330
15474
  const byId = registry2.list().find((workspace) => workspace.id === trimmed);
15331
15475
  if (byId !== void 0) return byId;
15332
15476
  try {
15477
+ signal?.throwIfAborted();
15333
15478
  const byPath = await registry2.resolveByPath(trimmed);
15334
15479
  if (byPath !== void 0) return byPath;
15335
- } catch {
15480
+ } catch (error51) {
15481
+ rethrowIfAborted(error51, signal);
15336
15482
  }
15483
+ signal?.throwIfAborted();
15337
15484
  throw new DevLeadError(
15338
15485
  `no Workspace matches "${reference}"; register the repository directory first with devlead_use_workspace`,
15339
15486
  "DEVLEAD_WORKSPACE_NOT_FOUND"
15340
15487
  );
15341
15488
  }
15489
+ async function resolveExactSession(deps, reference) {
15490
+ const { ctx } = deps;
15491
+ const sessionId = toSessionId2(reference);
15492
+ const live = ctx.agents.get(sessionId) !== void 0;
15493
+ if (deps.watchedSessions.includes(reference)) return { sessionId, live };
15494
+ const session = ctx.sessions.get(sessionId) ?? ctx.agents.get(sessionId)?.session;
15495
+ if (session !== void 0) {
15496
+ if (session.header.origin === "subagent") return void 0;
15497
+ return { sessionId, live };
15498
+ }
15499
+ const query = ctx.get("sessionQuery");
15500
+ if (query === void 0) return void 0;
15501
+ try {
15502
+ const observation = await query.readTitleSnapshot(sessionId, deps.signal);
15503
+ if (observation.session.origin === "subagent") return void 0;
15504
+ return { sessionId, live: false };
15505
+ } catch (error51) {
15506
+ rethrowIfAborted(error51, deps.signal);
15507
+ return void 0;
15508
+ }
15509
+ }
15342
15510
  async function resolveSessionReference(deps, reference) {
15343
15511
  const trimmed = reference.trim();
15344
15512
  if (trimmed.length === 0) throw new DevLeadError("a Session id is required", "DEVLEAD_INVALID_INPUT");
15345
- const candidates = await collectSessionIds(deps, void 0);
15346
- const exact = candidates.find((id) => id === trimmed);
15347
- let resolvedId = exact;
15513
+ const exact = await resolveExactSession(deps, trimmed);
15514
+ if (exact !== void 0) return exact;
15515
+ const candidates = await collectSessionIds(deps, void 0, true);
15516
+ const matched = candidates.filter((id) => id.startsWith(trimmed));
15517
+ const resolvedId = matched.find((id) => id === trimmed) ?? (matched.length === 1 ? matched[0] : void 0);
15518
+ if (resolvedId === void 0 && matched.length === 0) {
15519
+ throw new DevLeadError(
15520
+ `no Session matches "${reference}"; list the addressable Sessions with devlead_list_sessions`,
15521
+ "DEVLEAD_SESSION_NOT_FOUND"
15522
+ );
15523
+ }
15348
15524
  if (resolvedId === void 0) {
15349
- const matched = candidates.filter((id) => id.startsWith(trimmed));
15350
- if (matched.length === 0) {
15351
- throw new DevLeadError(`no Session matches "${reference}"`, "DEVLEAD_SESSION_NOT_FOUND");
15352
- }
15353
- if (matched.length > 1) {
15354
- throw new DevLeadError(
15355
- `Session prefix "${reference}" is ambiguous: ${matched.slice(0, 8).join(", ")}`,
15356
- "DEVLEAD_INVALID_INPUT"
15357
- );
15358
- }
15359
- resolvedId = matched[0];
15525
+ throw new DevLeadError(
15526
+ `Session prefix "${reference}" is ambiguous: ${matched.slice(0, 8).join(", ")}`,
15527
+ "DEVLEAD_INVALID_INPUT"
15528
+ );
15360
15529
  }
15361
15530
  const sessionId = toSessionId2(resolvedId);
15362
15531
  return { sessionId, live: deps.ctx.agents.get(sessionId) !== void 0 };
@@ -15400,8 +15569,31 @@ function remoteCodeOf(error51) {
15400
15569
  const code = error51.code;
15401
15570
  return typeof code === "string" ? code : void 0;
15402
15571
  }
15403
- function renderThrown(error51) {
15404
- return error51 instanceof Error ? error51.message : String(error51);
15572
+ function listLimit(limit, maximum) {
15573
+ if (limit === void 0) return maximum;
15574
+ if (!Number.isSafeInteger(limit) || limit < 1) {
15575
+ throw new DevLeadError("limit must be a positive safe integer", "DEVLEAD_INVALID_INPUT");
15576
+ }
15577
+ return Math.min(limit, maximum);
15578
+ }
15579
+ function workspacePathFailure(error51, path) {
15580
+ const errno = error51?.code;
15581
+ if (errno === "ENOENT") {
15582
+ return new DevLeadError(
15583
+ `directory "${path}" does not exist; create it first or let this call create it`,
15584
+ "DEVLEAD_DIRECTORY_MISSING"
15585
+ );
15586
+ }
15587
+ if (error51 instanceof TypeError && /fully qualified/u.test(thrownMessage(error51))) {
15588
+ return new DevLeadError(
15589
+ `"${path}" is not a fully qualified path; pass an absolute directory path`,
15590
+ "DEVLEAD_INVALID_INPUT"
15591
+ );
15592
+ }
15593
+ return new DevLeadError(
15594
+ `could not register "${path}" as a Workspace: ${thrownMessage(error51)}`,
15595
+ "DEVLEAD_INVALID_INPUT"
15596
+ );
15405
15597
  }
15406
15598
  var DevLeadService = class extends Service {
15407
15599
  static inject = ["agents", "sessions", "sessionProjections"];
@@ -15463,7 +15655,8 @@ var DevLeadService = class extends Service {
15463
15655
  * @param agent - exact live Session Agent receiving the selection.
15464
15656
  * @param enabled - selected mode.
15465
15657
  * @param signal - cancellation checked before the write.
15466
- * @returns fulfillment after the selection is durable.
15658
+ * @returns fulfillment after the committed selection's durability checkpoint
15659
+ * was attempted (a host without a persistence participant keeps it in memory).
15467
15660
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
15468
15661
  */
15469
15662
  async setEnabled(agent, enabled, signal) {
@@ -15472,10 +15665,7 @@ var DevLeadService = class extends Service {
15472
15665
  const current = this.strictStateOf(agent.session);
15473
15666
  if (current.enabled === enabled) return;
15474
15667
  appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
15475
- const flushed = await this.ctx.sessions.flush(agent.session);
15476
- if (!flushed) {
15477
- this.ctx.logger.warn(`devlead: DevLead mode for Session "${agent.id}" was not flushed to persistence`);
15478
- }
15668
+ await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
15479
15669
  }
15480
15670
  // ---------------------------------------------------------------------------
15481
15671
  // Workspaces
@@ -15498,42 +15688,54 @@ var DevLeadService = class extends Service {
15498
15688
  /**
15499
15689
  * Register an existing directory as a Workspace, creating a missing
15500
15690
  * directory first when allowed.
15691
+ *
15692
+ * The Workspace registry itself canonicalizes the path (`fs.realpath`, so
15693
+ * trailing slashes and symlinks normalize), rejects relative spellings, and
15694
+ * requires an existing directory; this method only adds the optional
15695
+ * missing-directory creation and the stable DevLead error vocabulary.
15696
+ * An already-registered canonical path reuses its Workspace and keeps the
15697
+ * registered title: `options.title` applies only when a new record is created.
15501
15698
  * @param path - fully qualified directory path.
15502
- * @param options - optional title and missing-directory policy (default creates).
15699
+ * @param options - optional title (new registrations only), missing-directory
15700
+ * policy (default creates), and cancellation checked before the registry write.
15503
15701
  * @returns the registered or existing Workspace view.
15504
- * @throws {@link DevLeadError} when the path is not usable.
15702
+ * @throws {@link DevLeadError} `DEVLEAD_DIRECTORY_MISSING` when the directory
15703
+ * is missing and creation is disabled, `DEVLEAD_INVALID_INPUT` for every
15704
+ * other unusable path or registration failure.
15505
15705
  */
15506
15706
  async useWorkspace(path, options = {}) {
15507
15707
  const trimmed = path.trim();
15508
15708
  if (trimmed.length === 0) throw new DevLeadError("a directory path is required", "DEVLEAD_INVALID_INPUT");
15509
- if (!isAbsolute(trimmed)) {
15510
- throw new DevLeadError(`"${trimmed}" is not a fully qualified path`, "DEVLEAD_INVALID_INPUT");
15511
- }
15512
- options.signal?.throwIfAborted();
15709
+ const signal = options.signal;
15710
+ signal?.throwIfAborted();
15513
15711
  const create = options.create ?? true;
15514
- const exists = await stat(trimmed).then(() => true, () => false);
15515
- if (!exists) {
15712
+ const title = options.title?.trim();
15713
+ const resolvedTitle = title === void 0 || title.length === 0 ? void 0 : title;
15714
+ const registry2 = this.requireWorkspaceRegistry();
15715
+ let workspace;
15716
+ try {
15717
+ workspace = await registry2.create(trimmed, resolvedTitle);
15718
+ } catch (error51) {
15719
+ const failure = workspacePathFailure(error51, trimmed);
15720
+ if (failure.code !== "DEVLEAD_DIRECTORY_MISSING") throw failure;
15516
15721
  if (!create) {
15517
- throw new DevLeadError(`directory "${trimmed}" does not exist`, "DEVLEAD_DIRECTORY_MISSING");
15518
- }
15519
- try {
15520
- await mkdir(trimmed, { recursive: true });
15521
- } catch (error51) {
15522
15722
  throw new DevLeadError(
15523
- `could not create directory "${trimmed}": ${renderThrown(error51)}`,
15723
+ `directory "${trimmed}" does not exist; create it first or retry with create enabled`,
15524
15724
  "DEVLEAD_DIRECTORY_MISSING"
15525
15725
  );
15526
15726
  }
15527
- }
15528
- const registry2 = this.requireWorkspaceRegistry();
15529
- let workspace;
15530
- try {
15531
- workspace = await registry2.create(trimmed, options.title);
15532
- } catch (error51) {
15533
- throw new DevLeadError(
15534
- `could not register "${trimmed}" as a Workspace: ${renderThrown(error51)}`,
15535
- "DEVLEAD_DIRECTORY_MISSING"
15536
- );
15727
+ signal?.throwIfAborted();
15728
+ try {
15729
+ await mkdir(trimmed, { recursive: true });
15730
+ } catch (mkdirError) {
15731
+ throw workspacePathFailure(mkdirError, trimmed);
15732
+ }
15733
+ signal?.throwIfAborted();
15734
+ try {
15735
+ workspace = await registry2.create(trimmed, resolvedTitle);
15736
+ } catch (retryError) {
15737
+ throw workspacePathFailure(retryError, trimmed);
15738
+ }
15537
15739
  }
15538
15740
  return await devLeadWorkspaceView(workspace);
15539
15741
  }
@@ -15542,55 +15744,74 @@ var DevLeadService = class extends Service {
15542
15744
  // ---------------------------------------------------------------------------
15543
15745
  /**
15544
15746
  * List Sessions this lead can address.
15545
- * @param options - optional Workspace filter, watch-only filter, and row limit.
15546
- * @param signal - cancellation checked between rows.
15747
+ *
15748
+ * Rows are ranked by cheap live facts (watched, running, then most recently
15749
+ * created) before the limit is applied, so a watched or running Session
15750
+ * always survives truncation; only retained rows pay for full view assembly.
15751
+ * @param agent - exact live lead Agent.
15752
+ * @param options - optional Workspace filter, watch-only filter, row limit
15753
+ * (capped by `maxListedSessions`), and cancellation checked between reads
15754
+ * and rows. A watched-only listing is never truncated below the watch set:
15755
+ * that set is already bounded by `maxWatchedSessions`, and the `/devlead`
15756
+ * status view would otherwise report truncated watch rows as missing.
15547
15757
  * @returns detached Session views, watched and running rows first.
15758
+ * @throws {@link DevLeadError} when the Agent is not live, the Workspace does
15759
+ * not resolve, the projection replay failed, or `limit` is not a positive
15760
+ * safe integer.
15548
15761
  */
15549
- async listSessions(agent, options = {}, signal) {
15762
+ async listSessions(agent, options = {}) {
15550
15763
  this.assertLive(agent);
15551
- const deps = this.viewDeps(agent);
15764
+ const signal = options.signal;
15765
+ const deps = this.viewDeps(agent, signal);
15552
15766
  signal?.throwIfAborted();
15553
15767
  let ids;
15554
15768
  if (options.workspace !== void 0 && options.workspace.trim().length > 0) {
15555
- const workspace = await resolveWorkspaceReference(this.ctx, options.workspace);
15769
+ const workspace = await resolveWorkspaceReference(this.ctx, options.workspace, signal);
15556
15770
  ids = await collectSessionIds(deps, workspace);
15557
15771
  } else {
15558
15772
  ids = await collectSessionIds(deps, void 0);
15559
15773
  }
15774
+ signal?.throwIfAborted();
15560
15775
  if (options.watchedOnly === true) ids = ids.filter((id) => deps.isWatched(id));
15561
- const limit = options.limit ?? this.resolved.maxListedSessions;
15562
- const views = await devLeadSessionViews(deps, ids, false);
15563
- views.sort((left, right) => {
15564
- if (left.watched !== right.watched) return left.watched ? -1 : 1;
15565
- if (left.running !== right.running) return left.running ? -1 : 1;
15566
- return (right.updatedAt ?? right.createdAt ?? 0) - (left.updatedAt ?? left.createdAt ?? 0) || left.sessionId.localeCompare(right.sessionId);
15567
- });
15568
- return views.slice(0, Math.max(1, limit));
15776
+ const listingCap = options.watchedOnly === true ? Math.max(this.resolved.maxListedSessions, deps.watchedSessions.length) : this.resolved.maxListedSessions;
15777
+ const limit = listLimit(options.limit, listingCap);
15778
+ const facts = await readSessionFacts(deps, ids);
15779
+ signal?.throwIfAborted();
15780
+ const retained = rankSessionIds(deps, ids, facts, limit);
15781
+ return await devLeadSessionViews(deps, retained, false, facts);
15569
15782
  }
15570
15783
  /**
15571
15784
  * Read one Session in detail, including folded turn and assistant facts.
15572
- * @param sessionId - Session id or unique prefix.
15573
- * @param signal - cancellation checked before the log read.
15785
+ * @param agent - exact live lead Agent.
15786
+ * @param sessionId - Session id or unique prefix; exact ids stay addressable
15787
+ * beyond the bounded listing window.
15788
+ * @param signal - cancellation checked before and between the query reads.
15574
15789
  * @returns the detached Session view.
15575
15790
  * @throws {@link DevLeadError} when the reference is missing or ambiguous.
15576
15791
  */
15577
15792
  async getSession(agent, sessionId, signal) {
15578
15793
  this.assertLive(agent);
15579
- const deps = this.viewDeps(agent);
15794
+ const deps = this.viewDeps(agent, signal);
15580
15795
  const resolved = await resolveSessionReference(deps, sessionId);
15581
15796
  signal?.throwIfAborted();
15582
15797
  return await devLeadSessionView(deps, String(resolved.sessionId), true);
15583
15798
  }
15584
15799
  /**
15585
15800
  * Create one ordinary Session in a Workspace and optionally prompt it.
15801
+ *
15802
+ * Cancellation is cooperative: the signal is checked before each awaited
15803
+ * stage, so a cancelled call stops before it watches or prompts the new
15804
+ * Session. Session creation itself is not abortable once started.
15586
15805
  * @param agent - exact live lead Agent.
15587
15806
  * @param request - Workspace, optional title, initial prompt, watch policy, and preset.
15807
+ * @param signal - cancellation checked between stages.
15588
15808
  * @returns the created Session and the Workspace it joined.
15589
15809
  * @throws {@link DevLeadError} when the mode is off, the Host cannot create
15590
15810
  * Sessions, or the destination is not usable.
15591
15811
  */
15592
- async createSession(agent, request) {
15812
+ async createSession(agent, request, signal) {
15593
15813
  this.assertReady(agent);
15814
+ signal?.throwIfAborted();
15594
15815
  const controller = this.ctx.get("sessionController");
15595
15816
  if (controller === void 0) {
15596
15817
  throw new DevLeadError(
@@ -15598,7 +15819,10 @@ var DevLeadService = class extends Service {
15598
15819
  "DEVLEAD_SESSION_UNAVAILABLE"
15599
15820
  );
15600
15821
  }
15822
+ const watch = request.watch ?? true;
15823
+ if (watch) this.assertWatchCapacity(agent);
15601
15824
  const workspace = await this.createTargetWorkspace(agent, request.workspace);
15825
+ signal?.throwIfAborted();
15602
15826
  const preset = request.preset?.trim() ?? this.resolved.defaultAgentPreset;
15603
15827
  let created;
15604
15828
  try {
@@ -15607,20 +15831,20 @@ var DevLeadService = class extends Service {
15607
15831
  ...preset === void 0 || preset.length === 0 ? {} : { agentPreset: preset }
15608
15832
  });
15609
15833
  } catch (error51) {
15610
- throw this.sessionUnavailable(`could not create a Session in "${workspace.title}": ${renderThrown(error51)}`, error51);
15834
+ throw this.sessionUnavailable(`could not create a Session in "${workspace.title}": ${thrownMessage(error51)}`, error51);
15611
15835
  }
15836
+ signal?.throwIfAborted();
15612
15837
  const sessionId = String(created.sessionId);
15613
15838
  if (request.title !== void 0 && request.title.trim().length > 0) {
15614
15839
  this.tryRename(created.sessionId, request.title.trim());
15615
15840
  }
15616
- const watch = request.watch ?? true;
15617
- if (watch) await this.setWatching(agent, created.sessionId, true);
15841
+ if (watch) await this.setWatching(agent, created.sessionId, true, signal);
15618
15842
  const prompt = request.prompt?.trim() ?? "";
15619
15843
  const prompted = prompt.length > 0;
15620
15844
  if (prompted) {
15621
- await this.admitPrompt(agent, created.sessionId, prompt, false);
15845
+ await this.admitPrompt(agent, created.sessionId, prompt, false, signal);
15622
15846
  }
15623
- const deps = this.viewDeps(agent);
15847
+ const deps = this.viewDeps(agent, signal);
15624
15848
  return {
15625
15849
  session: await devLeadSessionView(deps, sessionId, true),
15626
15850
  workspace: await devLeadWorkspaceView(workspace),
@@ -15633,16 +15857,20 @@ var DevLeadService = class extends Service {
15633
15857
  * @param agent - exact live lead Agent.
15634
15858
  * @param sessionId - Session id or unique prefix.
15635
15859
  * @param prompt - non-empty prompt text.
15636
- * @param options - optional watch policy (default watches).
15860
+ * @param options - optional watch policy (default watches) and cancellation
15861
+ * checked between stages.
15637
15862
  * @returns the admitted prompt receipt.
15638
15863
  * @throws {@link DevLeadError} when the Session is missing, archived, or cannot be resumed.
15639
15864
  */
15640
15865
  async promptSession(agent, sessionId, prompt, options = {}) {
15641
15866
  this.assertReady(agent);
15867
+ const signal = options.signal;
15868
+ signal?.throwIfAborted();
15642
15869
  const text = prompt.trim();
15643
15870
  if (text.length === 0) throw new DevLeadError("a non-empty prompt is required", "DEVLEAD_INVALID_INPUT");
15644
- const deps = this.viewDeps(agent);
15871
+ const deps = this.viewDeps(agent, signal);
15645
15872
  const resolved = await resolveSessionReference(deps, sessionId);
15873
+ signal?.throwIfAborted();
15646
15874
  if (String(resolved.sessionId) === String(agent.id)) {
15647
15875
  throw new DevLeadError(
15648
15876
  "a DevLead Session cannot prompt itself; end this turn and continue from a new human turn",
@@ -15650,9 +15878,15 @@ var DevLeadService = class extends Service {
15650
15878
  );
15651
15879
  }
15652
15880
  this.assertNotArchived(resolved.sessionId);
15881
+ if (!resolved.live && this.ctx.get("sessionController") === void 0) {
15882
+ throw new DevLeadError(
15883
+ `Session "${resolved.sessionId}" is not live and this Host composes no Session activator, so it cannot be prompted`,
15884
+ "DEVLEAD_SESSION_UNAVAILABLE"
15885
+ );
15886
+ }
15653
15887
  const watch = options.watch ?? true;
15654
- if (watch) await this.setWatching(agent, resolved.sessionId, true);
15655
- const resumed = await this.admitPrompt(agent, resolved.sessionId, text, true);
15888
+ if (watch) await this.setWatching(agent, resolved.sessionId, true, signal);
15889
+ const resumed = await this.admitPrompt(agent, resolved.sessionId, text, true, signal);
15656
15890
  return {
15657
15891
  sessionId: String(resolved.sessionId),
15658
15892
  watched: this.strictStateOf(agent.session).sessions.includes(String(resolved.sessionId)),
@@ -15664,23 +15898,27 @@ var DevLeadService = class extends Service {
15664
15898
  * @param agent - exact live lead Agent.
15665
15899
  * @param sessionId - Session id or unique prefix.
15666
15900
  * @param watching - whether the Session should be watched.
15901
+ * @param signal - cancellation checked before resolving and before the write.
15667
15902
  * @returns the resulting watch mutation.
15668
15903
  * @throws {@link DevLeadError} when the Session is missing, self-addressed, or over the limit.
15669
15904
  */
15670
- async watchSession(agent, sessionId, watching) {
15905
+ async watchSession(agent, sessionId, watching, signal) {
15671
15906
  this.assertReady(agent);
15672
- const deps = this.viewDeps(agent);
15907
+ signal?.throwIfAborted();
15908
+ const deps = this.viewDeps(agent, signal);
15673
15909
  const resolved = await resolveSessionReference(deps, sessionId);
15910
+ signal?.throwIfAborted();
15674
15911
  if (String(resolved.sessionId) === String(agent.id)) {
15675
15912
  throw new DevLeadError("a DevLead Session cannot watch itself", "DEVLEAD_SELF_WATCH");
15676
15913
  }
15677
- return await this.setWatching(agent, resolved.sessionId, watching);
15914
+ return await this.setWatching(agent, resolved.sessionId, watching, signal);
15678
15915
  }
15679
15916
  /**
15680
15917
  * Read the retained notification digest of one live lead Session.
15681
15918
  * @param agent - exact live lead Agent.
15682
- * @param options - maximum rows (newest last).
15683
- * @returns retained notifications, oldest first.
15919
+ * @param options - newest-row limit; omitted or not a positive safe integer
15920
+ * keeps the default of 20 rows.
15921
+ * @returns the newest retained notifications, oldest first.
15684
15922
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
15685
15923
  */
15686
15924
  notifications(agent, options = {}) {
@@ -15696,7 +15934,40 @@ var DevLeadService = class extends Service {
15696
15934
  /** Reject an Agent that is not this registry's exact live instance. */
15697
15935
  assertLive(agent) {
15698
15936
  if (this.ctx.agents.get(agent.id) !== agent) {
15699
- throw new DevLeadError(`agent "${agent.id}" is not live in this registry`, "DEVLEAD_AGENT_NOT_LIVE");
15937
+ throw new DevLeadError(
15938
+ `agent "${agent.id}" is not live in this registry; reopen its Session and retry`,
15939
+ "DEVLEAD_AGENT_NOT_LIVE"
15940
+ );
15941
+ }
15942
+ }
15943
+ /**
15944
+ * Check that one more watched Session fits under the configured cap, before a
15945
+ * write path creates side effects it cannot roll back.
15946
+ * @param agent - exact live lead Agent.
15947
+ */
15948
+ assertWatchCapacity(agent) {
15949
+ const state = this.strictStateOf(agent.session);
15950
+ if (state.sessions.length < this.resolved.maxWatchedSessions) return;
15951
+ throw new DevLeadError(
15952
+ `watch limit reached (${this.resolved.maxWatchedSessions}); unwatch a Session before adding another`,
15953
+ "DEVLEAD_WATCH_LIMIT"
15954
+ );
15955
+ }
15956
+ /**
15957
+ * Flush one Session's durability checkpoint. `SessionStore.flush` returns
15958
+ * false when no durability participant is composed (a headless/SDK host that
15959
+ * keeps logs in memory) — that is not a failure, so it stays silent; only a
15960
+ * composed participant's own rejection is reported, and it is downgraded to a
15961
+ * warning because the append already committed to the live log and a later
15962
+ * checkpoint can still reach storage.
15963
+ * @param session - Session whose buffered events should be persisted.
15964
+ * @param what - operation name used in the warning text.
15965
+ */
15966
+ async flushDurably(session, what) {
15967
+ try {
15968
+ await this.ctx.sessions.flush(session);
15969
+ } catch (error51) {
15970
+ this.ctx.logger.warn(`devlead: ${what} could not be flushed to persistence: ${thrownMessage(error51)}`);
15700
15971
  }
15701
15972
  }
15702
15973
  /** Reject any use of a tool surface while DevLead mode is off. */
@@ -15726,14 +15997,21 @@ var DevLeadService = class extends Service {
15726
15997
  }
15727
15998
  return registry2;
15728
15999
  }
15729
- /** Build the read-side dependency bundle for one live lead Agent. */
15730
- viewDeps(agent) {
16000
+ /**
16001
+ * Build the read-side dependency bundle for one live lead Agent.
16002
+ * @param agent - exact live lead Agent.
16003
+ * @param signal - optional cancellation threaded into every read.
16004
+ * @returns the view dependencies.
16005
+ */
16006
+ viewDeps(agent, signal) {
15731
16007
  const state = this.strictStateOf(agent.session);
16008
+ const watched = new Set(state.sessions);
15732
16009
  return {
15733
16010
  ctx: this.ctx,
15734
16011
  maxListedSessions: this.resolved.maxListedSessions,
15735
16012
  watchedSessions: state.sessions,
15736
- isWatched: (sessionId) => state.sessions.includes(sessionId)
16013
+ isWatched: (sessionId) => watched.has(sessionId),
16014
+ ...signal === void 0 ? {} : { signal }
15737
16015
  };
15738
16016
  }
15739
16017
  /**
@@ -15759,7 +16037,15 @@ var DevLeadService = class extends Service {
15759
16037
  if (byPath !== void 0) return byPath;
15760
16038
  const recorded = registry2.list().find((workspace) => workspace.path === cwd);
15761
16039
  if (recorded !== void 0) return recorded;
15762
- return await registry2.create(cwd);
16040
+ try {
16041
+ return await registry2.create(cwd);
16042
+ } catch (error51) {
16043
+ const failure = workspacePathFailure(error51, cwd);
16044
+ throw new DevLeadError(
16045
+ `the lead Session's working directory "${cwd}" is not usable: ${thrownMessage(error51)}; name a Workspace or path explicitly`,
16046
+ failure.code
16047
+ );
16048
+ }
15763
16049
  }
15764
16050
  /** Rename a freshly created Session, logging a failure instead of aborting creation. */
15765
16051
  tryRename(sessionId, title) {
@@ -15769,7 +16055,7 @@ var DevLeadService = class extends Service {
15769
16055
  try {
15770
16056
  titles.rename(session, title);
15771
16057
  } catch (error51) {
15772
- this.ctx.logger.warn(`devlead: Session "${sessionId}" was not renamed: ${renderThrown(error51)}`);
16058
+ this.ctx.logger.warn(`devlead: Session "${sessionId}" was not renamed: ${thrownMessage(error51)}`);
15773
16059
  }
15774
16060
  }
15775
16061
  /** Reject a Session the Workspace registry lists as archived. */
@@ -15794,9 +16080,11 @@ var DevLeadService = class extends Service {
15794
16080
  * @param sessionId - target Session identity.
15795
16081
  * @param text - non-empty prompt text.
15796
16082
  * @param allowResume - whether a cold Session may be resumed.
16083
+ * @param signal - cancellation checked before the resume and the admission.
15797
16084
  * @returns whether the Host resumed a cold Session.
15798
16085
  */
15799
- async admitPrompt(leadAgent, sessionId, text, allowResume) {
16086
+ async admitPrompt(leadAgent, sessionId, text, allowResume, signal) {
16087
+ signal?.throwIfAborted();
15800
16088
  let target = this.ctx.agents.get(sessionId);
15801
16089
  let resumed = false;
15802
16090
  if (target === void 0) {
@@ -15823,23 +16111,22 @@ var DevLeadService = class extends Service {
15823
16111
  } catch (error51) {
15824
16112
  if (error51 instanceof DevLeadError) throw error51;
15825
16113
  throw new DevLeadError(
15826
- `could not resume Session "${sessionId}": ${renderThrown(error51)}`,
16114
+ `could not resume Session "${sessionId}": ${thrownMessage(error51)}`,
15827
16115
  "DEVLEAD_SESSION_UNAVAILABLE"
15828
16116
  );
15829
16117
  }
16118
+ signal?.throwIfAborted();
15830
16119
  }
16120
+ signal?.throwIfAborted();
15831
16121
  try {
15832
16122
  target.followup(createDevLeadPromptMessage(text, leadAgent));
15833
16123
  } catch (error51) {
15834
16124
  throw new DevLeadError(
15835
- `could not admit a prompt into Session "${sessionId}": ${renderThrown(error51)}`,
16125
+ `could not admit a prompt into Session "${sessionId}": ${thrownMessage(error51)}`,
15836
16126
  "DEVLEAD_SESSION_UNAVAILABLE"
15837
16127
  );
15838
16128
  }
15839
- const flushed = await this.ctx.sessions.flush(target.session);
15840
- if (!flushed) {
15841
- this.ctx.logger.warn(`devlead: prompt into Session "${sessionId}" was not flushed to persistence`);
15842
- }
16129
+ await this.flushDurably(target.session, `prompt into Session "${sessionId}"`);
15843
16130
  return resumed;
15844
16131
  }
15845
16132
  /**
@@ -15847,9 +16134,11 @@ var DevLeadService = class extends Service {
15847
16134
  * @param agent - exact live lead Agent.
15848
16135
  * @param sessionId - target Session identity.
15849
16136
  * @param watching - whether to include the Session.
16137
+ * @param signal - cancellation checked before the write.
15850
16138
  * @returns the resulting watch mutation.
15851
16139
  */
15852
- async setWatching(agent, sessionId, watching) {
16140
+ async setWatching(agent, sessionId, watching, signal) {
16141
+ signal?.throwIfAborted();
15853
16142
  const id = String(sessionId);
15854
16143
  if (id === String(agent.id)) {
15855
16144
  throw new DevLeadError("a DevLead Session cannot watch itself", "DEVLEAD_SELF_WATCH");
@@ -15859,18 +16148,10 @@ var DevLeadService = class extends Service {
15859
16148
  if (present === watching) {
15860
16149
  return { sessionId: id, watched: present, sessions: state.sessions };
15861
16150
  }
15862
- if (watching && state.sessions.length >= this.resolved.maxWatchedSessions) {
15863
- throw new DevLeadError(
15864
- `watch limit reached (${this.resolved.maxWatchedSessions}); unwatch a Session before adding another`,
15865
- "DEVLEAD_WATCH_LIMIT"
15866
- );
15867
- }
16151
+ if (watching) this.assertWatchCapacity(agent);
15868
16152
  const next = watching ? [...state.sessions, id] : state.sessions.filter((existing) => existing !== id);
15869
16153
  appendPluginRecord2(agent.session, DEVLEAD_WATCH_RECORD_TYPE, watchRecord(next, Date.now()));
15870
- const flushed = await this.ctx.sessions.flush(agent.session);
15871
- if (!flushed) {
15872
- this.ctx.logger.warn(`devlead: watch set for lead "${agent.id}" was not flushed to persistence`);
15873
- }
16154
+ await this.flushDurably(agent.session, `watch set for lead "${agent.id}"`);
15874
16155
  return { sessionId: id, watched: watching, sessions: next };
15875
16156
  }
15876
16157
  };
@@ -15888,6 +16169,7 @@ export {
15888
16169
  DevLeadError,
15889
16170
  DevLeadService,
15890
16171
  applyDevLeadProjection,
16172
+ assistantExcerpt,
15891
16173
  createDevLeadNoticeMessage,
15892
16174
  createDevLeadPromptMessage,
15893
16175
  decodeModeRecord,
@@ -15907,5 +16189,6 @@ export {
15907
16189
  notificationId,
15908
16190
  notificationRecord,
15909
16191
  renderDevLeadNotice,
16192
+ representableInstant,
15910
16193
  watchRecord
15911
16194
  };