openclaw-lark-multi-agent 1.8.9 → 1.8.10

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.
@@ -28,6 +28,7 @@ export class MessageStore {
28
28
  CREATE TABLE IF NOT EXISTS reaction_custody(bot_name TEXT NOT NULL,chat_id TEXT NOT NULL,row_id INTEGER NOT NULL,record_json TEXT NOT NULL,
29
29
  PRIMARY KEY(bot_name,chat_id,row_id));
30
30
  CREATE TABLE IF NOT EXISTS run_delivery_targets(bot_name TEXT NOT NULL,chat_id TEXT NOT NULL,run_id TEXT NOT NULL,record_json TEXT NOT NULL,PRIMARY KEY(bot_name,chat_id,run_id));
31
+ CREATE TABLE IF NOT EXISTS dispatch_custody(bot_name TEXT NOT NULL,chat_id TEXT NOT NULL,record_json TEXT NOT NULL,PRIMARY KEY(bot_name,chat_id));
31
32
  CREATE TABLE IF NOT EXISTS admission_custody(session_key TEXT NOT NULL,submission_id TEXT PRIMARY KEY,state TEXT NOT NULL,record_json TEXT NOT NULL);
32
33
  CREATE TABLE IF NOT EXISTS run_observations (
33
34
  session_key TEXT NOT NULL, run_id TEXT NOT NULL, record_json TEXT NOT NULL,
@@ -81,6 +82,38 @@ export class MessageStore {
81
82
  const row = this.db.prepare('SELECT record_json FROM run_delivery_targets WHERE bot_name=? AND chat_id=? AND run_id=?').get(bot, chat, runId);
82
83
  return row ? JSON.parse(row.record_json) : null;
83
84
  }
85
+ /** Scheduling custody is independent of exact-run result custody. */
86
+ saveDispatchCustody(bot, chat, record) {
87
+ this.db.prepare('INSERT OR REPLACE INTO dispatch_custody VALUES(?,?,?)').run(bot, chat, JSON.stringify(record));
88
+ }
89
+ getDispatchCustody(bot, chat) {
90
+ const row = this.db.prepare('SELECT record_json FROM dispatch_custody WHERE bot_name=? AND chat_id=?').get(bot, chat);
91
+ const item = row ? JSON.parse(row.record_json) : null;
92
+ return item?.stopEpoch === this.getStopGeneration(bot, chat) ? item : null;
93
+ }
94
+ clearDispatchCustody(bot, chat, ownerId, batchId) {
95
+ return this.db.prepare(`DELETE FROM dispatch_custody WHERE bot_name=? AND chat_id=?
96
+ AND json_extract(record_json,'$.id')=? AND json_extract(record_json,'$.batchId')=?`).run(bot, chat, ownerId, batchId).changes === 1;
97
+ }
98
+ /** Atomic release of proven never-attempted reservations only. Unknown and
99
+ * accepted inputs retain their exact target and never enter ordinary drain. */
100
+ releaseDispatchCustody(bot, chat, ownerId, batchId) {
101
+ return this.db.transaction(() => {
102
+ const custody = this.getDispatchCustody(bot, chat);
103
+ if (!custody || !this.clearDispatchCustody(bot, chat, ownerId, batchId))
104
+ return false;
105
+ this.db.prepare(`UPDATE run_delivery_targets SET record_json=json_set(record_json,'$.dispatchReleased',json('true'),
106
+ '$.dispatchOwnerId',?,'$.dispatchBatchId',?,'$.sessionId',?) WHERE bot_name=? AND chat_id=? AND run_id=?`)
107
+ .run(ownerId, batchId, custody.sessionId, bot, chat, custody.runId);
108
+ this.db.prepare(`UPDATE insertion_custody SET state='ordinary',next_check_at=0,
109
+ record_json=json_set(record_json,'$.reason','current session confirmed schedulable; no backend attempt')
110
+ WHERE bot_name=? AND chat_id=? AND state='pending'
111
+ AND COALESCE(json_extract(record_json,'$.attempted'),0)=0
112
+ AND json_extract(record_json,'$.ownerId')=? AND json_extract(record_json,'$.batchId')=?
113
+ AND json_extract(record_json,'$.stopEpoch')=?`).run(bot, chat, ownerId, batchId, this.getStopGeneration(bot, chat));
114
+ return true;
115
+ })();
116
+ }
84
117
  /** Reserved is persisted before the send-attempt callback; dispatching is
85
118
  * persisted before the RPC. Only reserved + unchanged stop generation proves
86
119
  * no business effect and may be restored on startup. Unknown never replays. */
@@ -116,6 +149,9 @@ export class MessageStore {
116
149
  return !!this.db.prepare("SELECT 1 FROM run_observations WHERE session_key=? AND run_id=? AND state='stopped'").get(sessionKey, runId);
117
150
  }
118
151
  settleRunReactionIntents(bot, chat, runId) {
152
+ this.db.prepare(`UPDATE insertion_custody SET state='committed' WHERE bot_name=? AND chat_id=? AND state='accepted'
153
+ AND json_extract(record_json,'$.expectedRunId')=? AND json_extract(record_json,'$.stopEpoch')=?`)
154
+ .run(bot, chat, runId, this.getStopGeneration(bot, chat));
119
155
  this.db.prepare(`UPDATE reaction_custody SET record_json=json_set(record_json,'$.desired','DONE')
120
156
  WHERE bot_name=? AND chat_id=? AND json_extract(record_json,'$.runId')=?
121
157
  AND json_extract(record_json,'$.desired') IN ('Get','Typing')
@@ -127,9 +163,16 @@ export class MessageStore {
127
163
  }
128
164
  saveRunObservation(sessionKey, runId, record, nextCheckAt = Date.now()) {
129
165
  this.db.prepare(`INSERT INTO run_observations VALUES(?,?,?,'observing',?)
130
- ON CONFLICT(session_key,run_id) DO UPDATE SET record_json=excluded.record_json,next_check_at=excluded.next_check_at
166
+ ON CONFLICT(session_key,run_id) DO UPDATE SET record_json=json_patch(run_observations.record_json,excluded.record_json),next_check_at=excluded.next_check_at
131
167
  WHERE run_observations.state='observing'`).run(sessionKey, runId, JSON.stringify(record), nextCheckAt);
132
168
  }
169
+ hasYieldedObservation(sessionKey) {
170
+ return !!this.db.prepare(`SELECT 1 FROM run_observations WHERE session_key=? AND json_extract(record_json,'$.yielded')=1 LIMIT 1`).get(sessionKey);
171
+ }
172
+ getRunObservation(sessionKey, runId) {
173
+ const row = this.db.prepare('SELECT record_json,state FROM run_observations WHERE session_key=? AND run_id=?').get(sessionKey, runId);
174
+ return row ? { ...JSON.parse(row.record_json), state: row.state } : null;
175
+ }
133
176
  runObservationState(sessionKey, runId) {
134
177
  return this.db.prepare('SELECT state FROM run_observations WHERE session_key=? AND run_id=?').get(sessionKey, runId)?.state;
135
178
  }
@@ -166,6 +209,19 @@ export class MessageStore {
166
209
  .run(bot, chat, `insertion:${insertionId}:%`);
167
210
  return r.changes;
168
211
  }
212
+ /** Reminder intent and its outbox row commit together. Never write a stale
213
+ * reconciliation snapshot over a later accepted/stopped insertion. */
214
+ queueInsertionUnknownNotice(bot, chat, row, delivery) {
215
+ return this.db.transaction(() => {
216
+ const current = this.getInsertion(bot, chat, row);
217
+ if (current?.state !== 'unknown' || current.stopEpoch !== this.getStopGeneration(bot, chat) || current.unknownNotified ||
218
+ !Number.isFinite(current.unknownSince) || Date.now() - current.unknownSince < 45_000)
219
+ return false;
220
+ this.enqueueDelivery(delivery);
221
+ this.saveInsertion(bot, chat, row, current.insertionId, 'unknown', { ...current, unknownNotified: true }, Date.now() + 15_000);
222
+ return true;
223
+ })();
224
+ }
169
225
  claimInsertionAttempt(bot, chat, row) {
170
226
  return this.db.prepare(`UPDATE insertion_custody SET state='dispatching',record_json=json_set(record_json,'$.attempted',json('true'))
171
227
  WHERE bot_name=? AND chat_id=? AND message_row_id=? AND state='pending'`).run(bot, chat, row).changes === 1;
@@ -183,6 +239,10 @@ export class MessageStore {
183
239
  const item = this.getInsertion(bot, chat, row);
184
240
  return !!item && !['ordinary', 'stopped'].includes(item.state);
185
241
  }
242
+ stopInsertionAtEpoch(bot, chat, row, epoch) {
243
+ this.db.prepare(`UPDATE insertion_custody SET state='stopped' WHERE bot_name=? AND chat_id=? AND message_row_id=?
244
+ AND json_extract(record_json,'$.stopEpoch')=? AND state NOT IN ('committed','ordinary')`).run(bot, chat, row, epoch);
245
+ }
186
246
  stopInsertions(bot, chat) {
187
247
  this.db.prepare("UPDATE insertion_custody SET state='stopped' WHERE bot_name=? AND chat_id=? AND state NOT IN ('committed','ordinary')").run(bot, chat);
188
248
  }
@@ -155,8 +155,8 @@ export declare class OpenClawClient {
155
155
  * Collect agent reply by polling accumulated events.
156
156
  * Matches by initial runId OR sessionKey to handle multi-turn tool calling
157
157
  * where OpenClaw creates new runIds for each tool-call round.
158
- * Existing event/anchor matching is retained. After 30 minutes of silence,
159
- * reconcile the original run instead of aborting or treating a draft as final.
158
+ * Existing event/anchor matching is retained. Foreground effective silence
159
+ * triggers read-only reconciliation, never a task-lifetime cutoff or draft final.
160
160
  * Explicit terminal/error/disconnect paths keep their existing behavior.
161
161
  */
162
162
  private collectReply;
@@ -192,7 +192,7 @@ export declare class OpenClawClient {
192
192
  * expectedSessionId, so describe first, then patch archived=false.
193
193
  */
194
194
  unarchiveSession(key: string): Promise<boolean>;
195
- getSessionStatus(key: string): Promise<any>;
195
+ getSessionStatus(key: string, timeoutMs?: number): Promise<any>;
196
196
  injectAssistantMessage(params: {
197
197
  sessionKey: string;
198
198
  message: string;
@@ -203,6 +203,7 @@ export declare class OpenClawClient {
203
203
  * missing/legacy plugin observations stay pending without blind mutation. */
204
204
  exactRunSettled(runId: string): Promise<boolean>;
205
205
  cancelSteerSession(sessionKey: string, stopEpoch: number): Promise<void>;
206
+ private readinessCause;
206
207
  steer(sessionKey: string, text: string, displayText?: string, identity?: {
207
208
  insertionId: string;
208
209
  expectedRunId: string;
@@ -251,9 +252,19 @@ export declare class OpenClawClient {
251
252
  * Used when queue custody is revoked or a new chat.send takes over, so a
252
253
  * stale poller cannot steal the replacement batch's frames (2026-10-16). */
253
254
  revokeSessionCollectors(sessionKey: string, reason: string): number;
255
+ waitForSessionStop(sessionKey: string): Promise<void>;
254
256
  getSessionRuntimeStatus(sessionKey: string): Promise<SessionRuntimeStatus>;
257
+ /** Strong public current-session activity, independent of expired root
258
+ * terminal caches. Unknown/missing fields never authorize scheduling. */
259
+ getSessionDispatchStatus(sessionKey: string): Promise<{
260
+ idleConfirmed: boolean;
261
+ sessionId?: string;
262
+ archived?: boolean;
263
+ activeRunId?: string;
264
+ busyConfirmed?: boolean;
265
+ }>;
255
266
  private classifyWaitTimeout;
256
- getSessionInfo(sessionKey: string): Promise<any>;
267
+ getSessionInfo(sessionKey: string, timeoutMs?: number): Promise<any>;
257
268
  /**
258
269
  * Ensure session is using the expected model. If not, patch it back.
259
270
  * Returns true if a correction was made.
@@ -283,6 +294,11 @@ export declare class OpenClawClient {
283
294
  private trackChatEventSession;
284
295
  inspectRunError(provenance: ErrorProvenance): Promise<import("./terminal-errors.js").ErrorVerdict>;
285
296
  private extractTextFromChatMessage;
297
+ private continuationChecks;
298
+ /** A child/requester continuation is not automatically its parent's final.
299
+ * Public task parentage selects the original root; only that exact root's
300
+ * committed terminalReply may enter its old trigger/outbox. */
301
+ private handoffLinkedContinuation;
286
302
  private emitProactiveForSession;
287
303
  private suppressSessionKeys;
288
304
  private releaseSuppressedSessionKeysAfter;
@@ -415,9 +431,14 @@ export declare class OpenClawClient {
415
431
  /** Called after chat.send RPC succeeds and OpenClaw has accepted the user message. */
416
432
  onSubmitted?: (runId: string) => void | Promise<void>;
417
433
  /** Identifies collection target; not an acceptance receipt. */
418
- onRunIdentified?: (runId: string) => void | Promise<void>;
434
+ onRunIdentified?: (runId: string, identity?: {
435
+ sessionId?: string;
436
+ }) => void | Promise<void>;
419
437
  onProgress?: (event: ProgressEvent) => void | Promise<void>;
420
438
  onWaitPaused?: (notice: SessionWaitPaused) => void | Promise<void>;
439
+ /** Synchronous durable scheduling handoff; never a task settlement. */
440
+ onYieldHandoff?: (runId: string) => void;
441
+ onCollectionStarted?: (runId: string) => void;
421
442
  }): Promise<string>;
422
443
  private shouldInjectBridgeAttachmentHint;
423
444
  private bridgeAttachmentHint;
@@ -452,9 +473,14 @@ export declare class OpenClawClient {
452
473
  /** Called after chat.send RPC succeeds and OpenClaw has accepted the combined message. */
453
474
  onSubmitted?: (runId: string) => void | Promise<void>;
454
475
  /** Identifies collection target; not an acceptance receipt. */
455
- onRunIdentified?: (runId: string) => void | Promise<void>;
476
+ onRunIdentified?: (runId: string, identity?: {
477
+ sessionId?: string;
478
+ }) => void | Promise<void>;
456
479
  onProgress?: (event: ProgressEvent) => void | Promise<void>;
457
480
  onWaitPaused?: (notice: SessionWaitPaused) => void | Promise<void>;
481
+ /** Synchronous durable scheduling handoff; never a task settlement. */
482
+ onYieldHandoff?: (runId: string) => void;
483
+ onCollectionStarted?: (runId: string) => void;
458
484
  }): Promise<string>;
459
485
  private formatContextLines;
460
486
  private writeContextSyncFile;
@@ -1,6 +1,6 @@
1
1
  import WebSocket from "ws";
2
- import { safeErrorSummary } from "./provider-errors.js";
3
- import { inspectError, genericFailure } from "./terminal-errors.js";
2
+ import { safeErrorSummary, rawErrorExcerpt } from "./provider-errors.js";
3
+ import { inspectError, genericFailure, announceCandidate } from "./terminal-errors.js";
4
4
  import { SessionWaitPaused, normalizeSessionRuntimeStatus, isWaitTimeout, FOREGROUND_WAIT_MS } from "./session-status.js";
5
5
  import { createHash, randomUUID } from "crypto";
6
6
  import { mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
@@ -155,7 +155,16 @@ export class OpenClawClient {
155
155
  forwardedFinals = new Map();
156
156
  /** One paced recovery scheduler for all persisted exact runs. No business
157
157
  * replay, no per-run infinite timers, and each query has its own deadline. */
158
- bindRecoveryStore(store) { this.recoveryStore = store; this.scheduleRecovery(); }
158
+ bindRecoveryStore(store) {
159
+ this.recoveryStore = store;
160
+ store.onClose(() => { if (this.recoveryStore === store) {
161
+ this.recoveryStore = undefined;
162
+ if (this.recoveryTimer)
163
+ clearTimeout(this.recoveryTimer);
164
+ this.recoveryTimer = undefined;
165
+ } });
166
+ this.scheduleRecovery();
167
+ }
159
168
  scheduleRecovery() {
160
169
  if (this.recoveryTimer || !this.shouldReconnect || !this.recoveryStore)
161
170
  return;
@@ -168,6 +177,8 @@ export class OpenClawClient {
168
177
  this.recoveryChecking = true;
169
178
  try {
170
179
  for (const item of this.recoveryStore.listRunObservations(undefined, Date.now(), 20)) {
180
+ if (!this.recoveryStore)
181
+ return;
171
182
  // Advance every selected row, including temporarily unsubscribed/owned
172
183
  // ones, so a due page cannot starve recoverable runs behind it.
173
184
  this.recoveryStore.saveRunObservation(item.sessionKey, item.runId, item, Date.now() + 60_000);
@@ -176,7 +187,7 @@ export class OpenClawClient {
176
187
  if (this.ownedDeliveryRuns.has(item.runId))
177
188
  continue;
178
189
  try {
179
- const snapshot = item.terminalObserved ? { runId: item.runId, status: 'ok', endedAt: Date.now(), terminalReply: { disposition: 'visible', text: item.terminalText } } : await this.rpc('agent.wait', { runId: item.runId, timeoutMs: 1 }, 2500);
190
+ const snapshot = item.terminalObserved ? { runId: item.runId, status: 'ok', endedAt: Date.now(), terminalReply: { disposition: item.terminalDisposition || (String(item.terminalText).trim().toUpperCase() === 'NO_REPLY' ? 'silent' : 'visible'), text: item.terminalText } } : await this.rpc('agent.wait', { runId: item.runId, timeoutMs: 1 }, 2500);
180
191
  if (this.recoveryStore.runObservationState(item.sessionKey, item.runId) !== 'observing' || this.isExplicitlyStoppedRun(item.sessionKey, item.runId) || this.ownedDeliveryRuns.has(item.runId))
181
192
  continue;
182
193
  if (snapshot?.runId !== item.runId || !Number.isFinite(snapshot.endedAt) || snapshot.endedAt <= 0 || snapshot.yielded || snapshot.pendingError || ['queue', 'gateway_draining'].includes(snapshot.timeoutPhase) || typeof snapshot.startedAt === 'number' && snapshot.endedAt < snapshot.startedAt)
@@ -187,7 +198,9 @@ export class OpenClawClient {
187
198
  // endedAt + exact run is terminal evidence; bare query timeouts never get here.
188
199
  await callback?.(String(snapshot.error || snapshot.status), { sourceType: 'run_error', sessionKey: item.sessionKey, runId: item.runId,
189
200
  error: { sessionKey: item.sessionKey, runId: item.runId, source: 'chat', state: 'error', detail: String(snapshot.error || snapshot.status) } });
201
+ this.recoveryStore.settleExactRunReactions(item.sessionKey, item.runId);
190
202
  this.recoveryStore.finishRunObservation(item.sessionKey, item.runId);
203
+ await this.sessionSettlementCallbacks.get(this.canonicalSessionKey(item.sessionKey))?.({ sessionKey: item.sessionKey, runId: item.runId, sessionId: item.sessionId, final: true });
191
204
  continue;
192
205
  }
193
206
  if (snapshot.status !== 'ok' || !['visible', 'silent', 'empty'].includes(terminal?.disposition))
@@ -872,8 +885,8 @@ export class OpenClawClient {
872
885
  * Collect agent reply by polling accumulated events.
873
886
  * Matches by initial runId OR sessionKey to handle multi-turn tool calling
874
887
  * where OpenClaw creates new runIds for each tool-call round.
875
- * Existing event/anchor matching is retained. After 30 minutes of silence,
876
- * reconcile the original run instead of aborting or treating a draft as final.
888
+ * Existing event/anchor matching is retained. Foreground effective silence
889
+ * triggers read-only reconciliation, never a task-lifetime cutoff or draft final.
877
890
  * Explicit terminal/error/disconnect paths keep their existing behavior.
878
891
  */
879
892
  collectReply(runId, timeoutMs = FOREGROUND_WAIT_MS, targetSessionKey, options) {
@@ -946,8 +959,8 @@ export class OpenClawClient {
946
959
  return;
947
960
  }
948
961
  if (error instanceof SessionWaitPaused) {
949
- // Foreground notice, background observation. Keep the original queue
950
- // owner/progress path so later input still steers into the same run.
962
+ // Presentation only. A separate trusted-yield callback may transfer
963
+ // scheduling custody; an ordinary timeout never authorizes that handoff.
951
964
  foregroundPaused = true;
952
965
  if (!waitNoticeSent) {
953
966
  waitNoticeSent = true;
@@ -1406,11 +1419,15 @@ export class OpenClawClient {
1406
1419
  }
1407
1420
  }
1408
1421
  if (ev.stream === "chatFinal") {
1422
+ // Only the exact admitted root's public chat envelope can yield
1423
+ // scheduling custody. Session fallback/foreign/tool flags cannot.
1424
+ if (ev.data?.gatewayYielded === true && (evRunId !== runId || !eventSessionMatches))
1425
+ continue;
1409
1426
  chatFinalSeen = true;
1410
1427
  if (ev.data?.gatewayYielded === true) {
1411
1428
  // A yielded turn is not a terminal answer, even if its buffered
1412
- // message contains a preface. Preserve the collector/queue owner
1413
- // and final-delivery key; only pause foreground presentation.
1429
+ // message contains a preface. Keep the final key unclaimed;
1430
+ // opt-in durable handoff can retire only foreground observation.
1414
1431
  if (chatFinalText.trim())
1415
1432
  continue; // an actual final wins
1416
1433
  foregroundYielded = true;
@@ -1427,7 +1444,23 @@ export class OpenClawClient {
1427
1444
  // Finish scanning this batch first so an already-arrived real
1428
1445
  // final/error wins over a stale waiting notice. No status RPC
1429
1446
  // (or ten-minute silence) is needed to confirm this wire fact.
1430
- void Promise.resolve().then(() => handleTimeoutResult(new SessionWaitPaused(normalizeSessionRuntimeStatus(undefined), false, "yield")));
1447
+ void Promise.resolve().then(() => {
1448
+ if (observationClosed || chatFinalText.trim())
1449
+ return;
1450
+ void handleTimeoutResult(new SessionWaitPaused(normalizeSessionRuntimeStatus(undefined), false, "yield"));
1451
+ if (options?.onYieldHandoff) {
1452
+ try {
1453
+ // Commit recoverable exact observation BEFORE opening
1454
+ // proactive delivery and fencing this destructive consumer.
1455
+ this.recoveryStore?.saveRunObservation(sessionKey, runId, { yielded: true });
1456
+ options.onYieldHandoff(runId);
1457
+ fenceSuperseded();
1458
+ }
1459
+ catch (error) {
1460
+ console.warn('[OpenClaw] yield handoff retained by collector:', safeErrorSummary(error));
1461
+ }
1462
+ }
1463
+ });
1431
1464
  continue;
1432
1465
  }
1433
1466
  chatFinalText = ev.data?.text || "";
@@ -1829,8 +1862,8 @@ export class OpenClawClient {
1829
1862
  return false;
1830
1863
  }
1831
1864
  }
1832
- async getSessionStatus(key) {
1833
- return this.rpc("sessions.describe", { key: this.canonicalSessionKey(key) });
1865
+ async getSessionStatus(key, timeoutMs = 120000) {
1866
+ return this.rpc("sessions.describe", { key: this.canonicalSessionKey(key) }, timeoutMs);
1834
1867
  }
1835
1868
  async injectAssistantMessage(params) {
1836
1869
  return this.rpc("chat.inject", { ...params, sessionKey: this.canonicalSessionKey(params.sessionKey) }, 10000);
@@ -1850,10 +1883,27 @@ export class OpenClawClient {
1850
1883
  async cancelSteerSession(sessionKey, stopEpoch) {
1851
1884
  await this.rpc('lma.steer.stop', { sessionKey: this.canonicalSessionKey(sessionKey), stopEpoch }, 2500);
1852
1885
  }
1886
+ readinessCause(error) {
1887
+ let detail = error instanceof Error ? error.message : '';
1888
+ let code = '';
1889
+ if (detail.startsWith('RPC error:')) {
1890
+ try {
1891
+ const value = JSON.parse(detail.slice('RPC error:'.length));
1892
+ if (typeof value.code === 'string' && /^[A-Z_]{1,48}$/.test(value.code))
1893
+ code = value.code;
1894
+ detail = typeof value.message === 'string' ? value.message : '';
1895
+ }
1896
+ catch {
1897
+ detail = '';
1898
+ }
1899
+ }
1900
+ return [code, rawErrorExcerpt(new Error(detail)) || safeErrorSummary(error)].filter(Boolean).join(': ');
1901
+ }
1853
1902
  async steer(sessionKey, text, displayText, identity) {
1854
1903
  if (!identity?.insertionId || !identity.expectedRunId)
1855
1904
  return { status: 'pending', attempted: false, reason: 'exact target not admitted yet' };
1856
1905
  let attempted = false;
1906
+ let stage = 'capabilities';
1857
1907
  const base = { insertionId: identity.insertionId, expectedRunId: identity.expectedRunId, sessionId: identity.expectedSessionId };
1858
1908
  try {
1859
1909
  const capability = await this.rpc('lma.steer.capabilities', {}, 2500);
@@ -1861,7 +1911,8 @@ export class OpenClawClient {
1861
1911
  // requirement. Builtin callbacks can be used with atomicRunBound=false.
1862
1912
  if (capability?.protocol !== 2 || capability?.durableAttempts !== true || capability?.acceptanceCallback !== true)
1863
1913
  return { ...base, status: 'unavailable', attempted: identity.queryOnly === true, reason: 'Update the coordinated LMA plugin; legacy booleans are not acceptance receipts' };
1864
- const info = await this.getSessionStatus(sessionKey);
1914
+ stage = 'sessions.describe';
1915
+ const info = await this.getSessionStatus(sessionKey, 1500);
1865
1916
  const currentId = info?.session?.sessionId;
1866
1917
  if (info?.session?.archived === true || (identity.expectedSessionId && currentId && currentId !== identity.expectedSessionId))
1867
1918
  return { ...base, status: 'target_changed', attempted: identity.queryOnly === true, reason: 'session archived or generation changed; no automatic migration' };
@@ -1869,6 +1920,7 @@ export class OpenClawClient {
1869
1920
  return { ...base, status: 'pending', attempted: identity.queryOnly === true, reason: 'session generation observation unavailable' };
1870
1921
  base.sessionId = currentId;
1871
1922
  attempted = true;
1923
+ stage = 'lma.steer';
1872
1924
  const result = await this.rpc('lma.steer', { sessionKey: this.canonicalSessionKey(sessionKey), text, ...identity,
1873
1925
  expectedSessionId: identity.expectedSessionId || currentId, stopEpoch: identity.stopEpoch ?? 0 }, 2500);
1874
1926
  if (result?.insertionId !== identity.insertionId || result?.expectedRunId !== identity.expectedRunId || result?.sessionId !== currentId ||
@@ -1880,7 +1932,7 @@ export class OpenClawClient {
1880
1932
  }
1881
1933
  catch (error) {
1882
1934
  return { ...base, status: attempted ? 'unknown' : 'pending', attempted: attempted || identity.queryOnly === true,
1883
- reason: attempted ? 'Insertion receipt unknown; query stable identity only' : 'Readiness observation unavailable; retained for paced recovery' };
1935
+ reason: `${attempted ? 'Insertion receipt unknown; query stable identity only' : 'Readiness observation unavailable; retained for paced recovery'} [${stage}: ${this.readinessCause(error)}]` };
1884
1936
  }
1885
1937
  }
1886
1938
  /** Callbacks fired when a steered message is confirmed consumed by the model
@@ -2047,6 +2099,9 @@ export class OpenClawClient {
2047
2099
  console.warn(`[OpenClaw] superseded ${count} stale collector(s) for ${key.slice(-24)}: ${reason}`);
2048
2100
  return count;
2049
2101
  }
2102
+ async waitForSessionStop(sessionKey) {
2103
+ await this.pendingExplicitStops.get(this.canonicalSessionKey(sessionKey));
2104
+ }
2050
2105
  async getSessionRuntimeStatus(sessionKey) {
2051
2106
  let timer;
2052
2107
  try {
@@ -2064,12 +2119,35 @@ export class OpenClawClient {
2064
2119
  clearTimeout(timer);
2065
2120
  }
2066
2121
  }
2122
+ /** Strong public current-session activity, independent of expired root
2123
+ * terminal caches. Unknown/missing fields never authorize scheduling. */
2124
+ async getSessionDispatchStatus(sessionKey) {
2125
+ let timer;
2126
+ try {
2127
+ const key = this.canonicalSessionKey(sessionKey);
2128
+ const history = await Promise.race([this.rpc('chat.history', { sessionKey: key, limit: 1 }, 1500),
2129
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('activity lookup timeout')), 1500); })]);
2130
+ const info = history?.sessionInfo;
2131
+ return { idleConfirmed: history?.sessionKey === key && info?.hasActiveRun === false &&
2132
+ history?.pendingInputs?.total === 0 && !history?.inFlightRun && info?.archived !== true,
2133
+ sessionId: info?.sessionId || history?.sessionId, archived: info?.archived === true,
2134
+ activeRunId: history?.sessionKey === key && typeof history?.inFlightRun?.runId === 'string' ? history.inFlightRun.runId : undefined,
2135
+ busyConfirmed: history?.sessionKey === key && (info?.hasActiveRun === true || !!history?.inFlightRun || history?.pendingInputs?.total > 0) };
2136
+ }
2137
+ catch {
2138
+ return { idleConfirmed: false };
2139
+ }
2140
+ finally {
2141
+ if (timer)
2142
+ clearTimeout(timer);
2143
+ }
2144
+ }
2067
2145
  async classifyWaitTimeout(text, sessionKey) {
2068
2146
  const status = await this.getSessionRuntimeStatus(sessionKey).catch(() => normalizeSessionRuntimeStatus(undefined));
2069
2147
  return status.running ? new SessionWaitPaused(status, true) : new Error(`Agent error: ${text}`);
2070
2148
  }
2071
- async getSessionInfo(sessionKey) {
2072
- return this.rpc("sessions.describe", { key: this.canonicalSessionKey(sessionKey) });
2149
+ async getSessionInfo(sessionKey, timeoutMs = 120000) {
2150
+ return this.rpc("sessions.describe", { key: this.canonicalSessionKey(sessionKey) }, timeoutMs);
2073
2151
  }
2074
2152
  /**
2075
2153
  * Ensure session is using the expected model. If not, patch it back.
@@ -2105,8 +2183,22 @@ export class OpenClawClient {
2105
2183
  return this.rpc("sessions.delete", { key: this.canonicalSessionKey(key), deleteTranscript });
2106
2184
  }
2107
2185
  async resetSession(key) {
2108
- // sessions.reset may not return a response; use short timeout
2109
- return this.rpc("sessions.reset", { key: this.canonicalSessionKey(key) }, 5000).catch(() => { });
2186
+ const canonical = this.canonicalSessionKey(key);
2187
+ this.stopGenerations.set(canonical, (this.stopGenerations.get(canonical) || 0) + 1);
2188
+ this.revokeSessionCollectors(canonical, 'explicit session reset');
2189
+ this.recoveryStore?.stopSessionObservations(canonical);
2190
+ let release;
2191
+ const barrier = new Promise(resolve => release = resolve);
2192
+ this.pendingExplicitStops.set(canonical, barrier);
2193
+ try {
2194
+ // sessions.reset may not return a response; this is only the RPC deadline.
2195
+ return await this.rpc("sessions.reset", { key: canonical }, 5000).catch(() => { });
2196
+ }
2197
+ finally {
2198
+ release();
2199
+ if (this.pendingExplicitStops.get(canonical) === barrier)
2200
+ this.pendingExplicitStops.delete(canonical);
2201
+ }
2110
2202
  }
2111
2203
  /** One-shot ToolTrim compaction: route the native semantic compaction
2112
2204
  * through the lma-core plugin's lma-tooltrim provider (keep text, keep only
@@ -2330,6 +2422,10 @@ export class OpenClawClient {
2330
2422
  this.suppressSessionKeys(keys);
2331
2423
  }
2332
2424
  else if (state === "final") {
2425
+ // A yielded acknowledgment is presentation, never a final delivery key,
2426
+ // including repeats after foreground collector custody was handed off.
2427
+ if (payload?.yielded === true)
2428
+ return;
2333
2429
  const text = this.extractTextFromChatMessage(payload?.message);
2334
2430
  if (text)
2335
2431
  this.emitProactiveForSession(sessionKey, text, {
@@ -2354,11 +2450,75 @@ export class OpenClawClient {
2354
2450
  const parts = Array.isArray(message?.content) ? message.content : [];
2355
2451
  return parts.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
2356
2452
  }
2357
- emitProactiveForSession(sessionKey, text, meta) {
2453
+ continuationChecks = new Map();
2454
+ /** A child/requester continuation is not automatically its parent's final.
2455
+ * Public task parentage selects the original root; only that exact root's
2456
+ * committed terminalReply may enter its old trigger/outbox. */
2457
+ async handoffLinkedContinuation(sessionKey, meta) {
2458
+ if (!this.recoveryStore || !meta.runId)
2459
+ return false;
2460
+ const key = this.canonicalSessionKey(sessionKey);
2461
+ const candidate = announceCandidate({ sessionKey: key, runId: meta.runId, source: 'chat', state: 'final', detail: '' });
2462
+ if (!candidate)
2463
+ return false;
2464
+ try {
2465
+ const matches = (task) => task?.kind === 'subagent' && task.runId === candidate.runId && task.sessionKey === key && task.ownerKey === key &&
2466
+ typeof task.childSessionKey === 'string' && (!candidate.childSessionKey || task.childSessionKey === candidate.childSessionKey);
2467
+ const found = new Set();
2468
+ let cursor;
2469
+ for (let page = 0; page < 2; page++) {
2470
+ const result = await this.rpc('tasks.list', { sessionKey: key, limit: 100, ...(cursor ? { cursor } : {}) }, 1500);
2471
+ if (!Array.isArray(result?.tasks))
2472
+ return false;
2473
+ for (const task of result.tasks)
2474
+ if (matches(task) && typeof task.id === 'string')
2475
+ found.add(task.id);
2476
+ cursor = typeof result.nextCursor === 'string' ? result.nextCursor : undefined;
2477
+ if (!cursor)
2478
+ break;
2479
+ }
2480
+ if (cursor || found.size !== 1)
2481
+ return false;
2482
+ const child = (await this.rpc('tasks.get', { taskId: [...found][0] }, 1500))?.task;
2483
+ if (!matches(child) || !child.parentTaskId || child.id !== [...found][0])
2484
+ return false;
2485
+ const parent = (await this.rpc('tasks.get', { taskId: child.parentTaskId }, 1500))?.task;
2486
+ if (parent?.id !== child.parentTaskId || parent.sessionKey !== key || parent.ownerKey !== key || typeof parent.runId !== 'string')
2487
+ return false;
2488
+ if (!this.recoveryStore)
2489
+ return true;
2490
+ const root = this.recoveryStore.getRunObservation(key, parent.runId);
2491
+ if (!root?.yielded)
2492
+ return false;
2493
+ if (root.state !== 'observing' || this.isExplicitlyStoppedRun(key, parent.runId))
2494
+ return true;
2495
+ this.recoveryStore.saveRunObservation(key, parent.runId, { ...root, continuationRunId: meta.runId, continuationTaskId: child.id }, 0);
2496
+ await this.recoverExactRuns();
2497
+ return true;
2498
+ }
2499
+ catch {
2500
+ return false;
2501
+ }
2502
+ }
2503
+ emitProactiveForSession(sessionKey, text, meta, lineageChecked = false) {
2358
2504
  const keys = this.sessionKeyVariants(sessionKey);
2359
2505
  const callback = keys.map(k => this.sessionMessageCallbacks.get(k)).find(Boolean);
2360
2506
  if (!callback)
2361
2507
  return false;
2508
+ if (!lineageChecked && meta?.final && meta.runId?.startsWith('announce:') && this.recoveryStore?.hasYieldedObservation(this.canonicalSessionKey(sessionKey))) {
2509
+ const candidate = announceCandidate({ sessionKey: this.canonicalSessionKey(sessionKey), runId: meta.runId, source: 'chat', state: 'final', detail: '' });
2510
+ if (candidate) {
2511
+ const identity = JSON.stringify([this.canonicalSessionKey(sessionKey), meta.runId]);
2512
+ if (!this.continuationChecks.has(identity)) {
2513
+ const store = this.recoveryStore;
2514
+ const work = this.handoffLinkedContinuation(sessionKey, meta).then(handled => { if (!handled && this.recoveryStore === store && this.shouldReconnect)
2515
+ this.emitProactiveForSession(sessionKey, text, meta, true); })
2516
+ .catch(() => { }).finally(() => this.continuationChecks.delete(identity));
2517
+ this.continuationChecks.set(identity, work);
2518
+ }
2519
+ return true;
2520
+ }
2521
+ }
2362
2522
  const identity = meta?.final && meta.runId ? JSON.stringify([this.canonicalSessionKey(sessionKey), meta.runId]) : '';
2363
2523
  const fingerprint = createHash('sha256').update(text).digest('hex');
2364
2524
  if (identity && this.forwardedFinals.get(identity) === fingerprint)
@@ -2369,7 +2529,15 @@ export class OpenClawClient {
2369
2529
  this.forwardedFinals.delete(this.forwardedFinals.keys().next().value);
2370
2530
  }
2371
2531
  if (identity)
2372
- this.recoveryStore?.saveRunObservation(this.canonicalSessionKey(sessionKey), meta.runId, { sessionId: meta?.sessionId, terminalText: text, terminalObserved: true }, Date.now() + 60_000);
2532
+ this.recoveryStore?.saveRunObservation(this.canonicalSessionKey(sessionKey), meta.runId, { sessionId: meta?.sessionId, terminalText: text, terminalObserved: true,
2533
+ ...(text.trim().toUpperCase() === 'NO_REPLY' ? { terminalDisposition: 'silent' } : {}) }, Date.now() + 60_000);
2534
+ if (identity && text.trim().toUpperCase() === 'NO_REPLY' && this.recoveryStore) {
2535
+ const key = this.canonicalSessionKey(sessionKey), runId = meta.runId;
2536
+ this.recoveryStore.settleExactRunReactions(key, runId);
2537
+ this.recoveryStore.finishRunObservation(key, runId);
2538
+ void Promise.resolve(this.sessionSettlementCallbacks.get(key)?.({ ...meta, sessionKey: key, runId, final: true })).catch(() => { });
2539
+ return true;
2540
+ }
2373
2541
  try {
2374
2542
  const result = meta ? callback(text, meta) : callback(text);
2375
2543
  if (identity)
@@ -2718,7 +2886,7 @@ export class OpenClawClient {
2718
2886
  fence();
2719
2887
  this.ownDeliveryRun(ownedRunId);
2720
2888
  console.log(`[OpenClaw] chat.send runId: ${result.runId} (rpc=${Date.now() - sendStartedAt}ms, attachments=${params.attachments?.length || 0})`);
2721
- await params.onRunIdentified?.(result.runId);
2889
+ await params.onRunIdentified?.(result.runId, { sessionId: result.sessionId });
2722
2890
  assertCurrent();
2723
2891
  // A reservation/in_flight reply is not confirmed acceptance. Keep UI
2724
2892
  // Typing while exact collection/read-only receipt reconciliation proceeds.
@@ -2732,7 +2900,9 @@ export class OpenClawClient {
2732
2900
  this.progressGenerations.set(fullSessionKey, generation);
2733
2901
  void params.onProgress({ kind: "lifecycle", text: "等待 OpenClaw 回复" });
2734
2902
  }
2735
- const reply = await this.collectReply(result.runId, params.timeoutMs || FOREGROUND_WAIT_MS, sk, { emptyFinalAsNoReply: params.emptyFinalAsNoReply, expectedUserText: params.message, onWaitPaused: params.onWaitPaused });
2903
+ const collecting = this.collectReply(result.runId, params.timeoutMs || FOREGROUND_WAIT_MS, sk, { emptyFinalAsNoReply: params.emptyFinalAsNoReply, expectedUserText: params.message, onWaitPaused: params.onWaitPaused, onYieldHandoff: params.onYieldHandoff });
2904
+ params.onCollectionStarted?.(result.runId);
2905
+ const reply = await collecting;
2736
2906
  if (reply.trim().toUpperCase() === 'NO_REPLY')
2737
2907
  this.recoveryStore?.finishRunObservation(fullSessionKey, ownedRunId);
2738
2908
  else
@@ -2818,6 +2988,8 @@ export class OpenClawClient {
2818
2988
  onRunIdentified: params.onRunIdentified,
2819
2989
  onProgress: params.onProgress,
2820
2990
  onWaitPaused: params.onWaitPaused,
2991
+ onYieldHandoff: params.onYieldHandoff,
2992
+ onCollectionStarted: params.onCollectionStarted,
2821
2993
  });
2822
2994
  }
2823
2995
  // Build context block + actual message in one chat.send, or write the
@@ -2856,6 +3028,8 @@ export class OpenClawClient {
2856
3028
  onRunIdentified: params.onRunIdentified,
2857
3029
  onProgress: params.onProgress,
2858
3030
  onWaitPaused: params.onWaitPaused,
3031
+ onYieldHandoff: params.onYieldHandoff,
3032
+ onCollectionStarted: params.onCollectionStarted,
2859
3033
  });
2860
3034
  }
2861
3035
  formatContextLines(messages) {
@@ -7,6 +7,8 @@ export type SessionRuntimeStatus = {
7
7
  checkedAt: number;
8
8
  /** Positive public activity evidence, never inferred from !running. */
9
9
  idleConfirmed?: boolean;
10
+ sessionId?: string;
11
+ archived?: boolean;
10
12
  contextUsedTokens?: number;
11
13
  contextLimitTokens?: number;
12
14
  };
@@ -14,6 +14,8 @@ export function normalizeSessionRuntimeStatus(value) {
14
14
  const contextUsedTokens = session?.totalTokensFresh !== false && typeof used === "number" && Number.isFinite(used) && used >= 0 ? used : undefined;
15
15
  const contextLimitTokens = typeof limit === "number" && Number.isFinite(limit) && limit > 0 ? limit : undefined;
16
16
  return { status: running ? "running" : status, running, checkedAt: Date.now(),
17
+ ...(typeof session?.sessionId === 'string' ? { sessionId: session.sessionId } : {}),
18
+ ...(session?.archived === true ? { archived: true } : {}),
17
19
  ...(session?.hasActiveRun === false && !running ? { idleConfirmed: true } : {}),
18
20
  ...(contextUsedTokens !== undefined ? { contextUsedTokens } : {}),
19
21
  ...(contextLimitTokens !== undefined ? { contextLimitTokens } : {}),