jaxon-agents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,11 +8,11 @@ import * as store from "../agents/directory-store.js";
8
8
  import { JAXON, STATE } from "../agents/directory-store.js";
9
9
  import { fail } from "../ops/errors.js";
10
10
  import { buildLaunchSpec } from "../environment/pi-launch-spec.js";
11
- import { RELEASE } from "../root.js";
11
+ import { DATA_ROOT, RELEASE } from "../root.js";
12
12
  import { hasLocalModelEndpoint } from "../environment/local-model-endpoint.js";
13
13
  import { PiTerminalHost } from "../pi-host/interactive-client.js";
14
14
  import { readFromByteOffset, truncatePartialTail } from "../pi-host/event-tailer.js";
15
- import { branch, findPersistedUser, readEntries } from "../pi-host/history-reader.js";
15
+ import { branch, cueOriginEntries, findPersistedUser, readEntries } from "../pi-host/history-reader.js";
16
16
  import { sumUsage } from "./usage-ledger.js";
17
17
  import { AssistantUsageLog } from "./dashboard-usage.js";
18
18
  const SESSIONS = path.join(STATE, "sessions");
@@ -27,6 +27,9 @@ const CONSOLE_HISTORY_SIZE = 30;
27
27
  const STEER_TIMEOUT_MS = 15_000;
28
28
  const MAX_QUEUED_TURNS = 8;
29
29
  const MAX_PENDING_CUES = 20;
30
+ const CUE_WAKE_COOLDOWN = 60_000;
31
+ const CUE_WAKE_HOUR = 60 * 60_000;
32
+ const CUE_BLOCK_RETRY = 30_000;
30
33
  const BUSY = ["starting", "running", "stopping", "waiting_input"];
31
34
  const LIVE = [...BUSY, "idle"];
32
35
  const pollBusy = (status) => status === "starting" || status === "running" || status === "stopping";
@@ -40,6 +43,47 @@ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
40
43
  const EXT = Object.fromEntries(Object.entries(MIME).map(([e, m]) => [m, e]));
41
44
  const ANSWER_FOR_KIND = { select: "select_index", confirm: "confirm", input: "text", editor: "text" };
42
45
  const MB = 1024 * 1024;
46
+ const THINKING_BLOCK_BYTES = 16 * 1024;
47
+ const THINKING_RESPONSE_BYTES = 64 * 1024;
48
+ function thinkingPart(part) {
49
+ if (part.redacted === true)
50
+ return { type: "thinking", redacted: true };
51
+ const text = typeof part.thinking === "string" ? part.thinking : "";
52
+ if (Buffer.byteLength(text) <= THINKING_BLOCK_BYTES)
53
+ return { type: "thinking", text, redacted: false };
54
+ let bytes = 0, end = 0, chars = 0;
55
+ for (const char of text) {
56
+ chars++;
57
+ bytes += Buffer.byteLength(char);
58
+ if (bytes <= THINKING_BLOCK_BYTES)
59
+ end += char.length;
60
+ }
61
+ return { type: "thinking", text: text.slice(0, end), redacted: false, truncated: true, original_chars: chars };
62
+ }
63
+ function limitThinking(history) {
64
+ const blocks = [];
65
+ let total = 0;
66
+ for (const { content } of history) {
67
+ if (!Array.isArray(content))
68
+ continue;
69
+ content.forEach((part, index) => {
70
+ if (part?.type !== "thinking" || typeof part.text !== "string")
71
+ return;
72
+ const bytes = Buffer.byteLength(part.text);
73
+ blocks.push({ content, index, bytes });
74
+ total += bytes;
75
+ });
76
+ }
77
+ for (const { content, index, bytes } of blocks) {
78
+ if (total <= THINKING_RESPONSE_BYTES)
79
+ break;
80
+ if (!bytes)
81
+ continue;
82
+ const part = content[index];
83
+ content[index] = { type: "thinking", omitted: true, chars: part.original_chars ?? [...part.text].length };
84
+ total -= bytes;
85
+ }
86
+ }
43
87
  const missingFile = (error) => ["ENOENT", "ENOTDIR"].includes(error?.code ?? "");
44
88
  const within = (root, file) => {
45
89
  const rel = path.relative(root, file);
@@ -66,6 +110,7 @@ class ManagedSession {
66
110
  ready = false;
67
111
  ticking = false;
68
112
  drainScheduled = false;
113
+ cueWaking = false;
69
114
  lastStop = null;
70
115
  lastScreen;
71
116
  watcher;
@@ -109,6 +154,13 @@ export class SessionSupervisor {
109
154
  sessions = new Map();
110
155
  verifying = new Set();
111
156
  onStationStatus;
157
+ onCueChange;
158
+ onCueBlocked;
159
+ onCueWoken;
160
+ admitCueWake;
161
+ cueWakePaused;
162
+ cueSchedulerStarted = false;
163
+ cueTimers = new Map();
112
164
  beforeMemberLaunch;
113
165
  admission;
114
166
  activeLeases = new Map();
@@ -119,6 +171,8 @@ export class SessionSupervisor {
119
171
  if (s.meta.station && before !== after)
120
172
  this.onStationStatus?.(s.meta.station, before, after);
121
173
  this.scheduleDrain(s);
174
+ if (before !== after || (s.meta.pending_cues?.length && ["idle", "dormant"].includes(after)))
175
+ this.scheduleCueWake(s);
122
176
  };
123
177
  /** Only one host may own state/: the lock is kernel-held and vanishes with its process. */
124
178
  connections;
@@ -149,6 +203,7 @@ export class SessionSupervisor {
149
203
  recoverOnStartup() {
150
204
  for (const s of this.sessions.values()) {
151
205
  if (!LIVE.includes(s.meta.status)) {
206
+ this.releaseCueReservation(s);
152
207
  if (s.meta.status === "dormant" && (s.meta.queue ?? []).length)
153
208
  this.scheduleDrain(s);
154
209
  continue;
@@ -184,7 +239,9 @@ export class SessionSupervisor {
184
239
  return [...this.sessions.values()].map((s) => s.meta);
185
240
  }
186
241
  usageFor(sessionId) {
187
- return sumUsage(this.get(sessionId).entries());
242
+ const entries = this.get(sessionId).entries();
243
+ const cue = cueOriginEntries(entries);
244
+ return { usage: sumUsage(entries), ...(cue.length ? { usage_by_origin: { cue: { origin: "cue", ...sumUsage(cue) } } } : {}) };
188
245
  }
189
246
  dashboardUsage(bounds) {
190
247
  const records = [];
@@ -326,6 +383,8 @@ export class SessionSupervisor {
326
383
  await this.refresh(s);
327
384
  if (s.meta.active_turn_id !== p.turn_id)
328
385
  return { status: s.meta.status, last_turn_outcome: s.meta.last_turn_outcome, abort_reason: s.meta.abort_reason ?? null };
386
+ if (s.meta.pending_cues?.length)
387
+ s.set({ cue_wake_paused: true });
329
388
  this.cancelQueued(s);
330
389
  await this.requestInterrupt(s, p.turn_id, "interrupt");
331
390
  return { status: s.meta.status, last_turn_outcome: s.meta.last_turn_outcome, abort_reason: s.meta.abort_reason ?? null };
@@ -365,7 +424,7 @@ export class SessionSupervisor {
365
424
  return { session_id: m.session_id, agent: m.agent, workspace: m.workspace, task_id: m.task_id, status: this.effectiveStatus(m),
366
425
  leaf_id: m.leaf_id, has_pending_request: Boolean(m.pending_request), updated_at: m.updated_at,
367
426
  queue: (m.queue ?? []).map((item, index) => ({ turn_id: item.turn_id, position: index + 1 })),
368
- queued_turns: m.queue?.length ?? 0, pending_cues: m.pending_cues?.length ?? 0,
427
+ queued_turns: m.queue?.length ?? 0, pending_cues: this.pendingCueSummary(m),
369
428
  last_turn_outcome: m.last_turn_outcome ?? null, abort_reason: m.abort_reason ?? null,
370
429
  ...(m.station ? { station: { ...stationRef(m.station), seat: m.station.seat ?? true } } : {}),
371
430
  turn_progress: this.turnProgress(s) };
@@ -393,7 +452,8 @@ export class SessionSupervisor {
393
452
  return counted(() => ({ ...summary(), return_reason, waited_ms: Math.round(performance.now() - start), changed: changed ?? [] }));
394
453
  }
395
454
  turnProgress(s, entries) {
396
- if (!pollBusy(this.effectiveStatus(s.meta)))
455
+ if (!pollBusy(this.effectiveStatus(s.meta)) &&
456
+ !(s.meta.status === "waiting_input" && s.meta.turn_origin === "cue"))
397
457
  return null;
398
458
  const all = entries ?? s.entries();
399
459
  const anchor = all.findLastIndex((e) => e.customType === "mcp_turn_intent" && e.data?.turn_id === s.meta.active_turn_id);
@@ -420,18 +480,42 @@ export class SessionSupervisor {
420
480
  activity = Math.max(activity, milliseconds(e.timestamp) || 0);
421
481
  }
422
482
  return { started_at, elapsed_ms: Math.max(0, now - started_at), assistant_messages, tool_calls, last_tool,
423
- last_activity_ago_ms: Math.max(0, now - activity), queued_turns: s.meta.queue?.length ?? 0 };
483
+ last_activity_ago_ms: Math.max(0, now - activity), queued_turns: s.meta.queue?.length ?? 0,
484
+ ...(s.meta.turn_origin === "cue" && !s.meta.last_turn_outcome ? { origin: "cue" } : {}) };
424
485
  }
425
- consoleHistoryBefore(sessionId, before) {
486
+ cueTurnLeaf(sessionId, turnId) {
487
+ const entries = this.get(sessionId).entries();
488
+ const intent = entries.find(entry => entry.customType === "mcp_turn_intent" && entry.data?.turn_id === turnId && entry.data.origin === "cue");
489
+ if (!intent)
490
+ return null;
491
+ const user = entries.find(entry => entry.parentId === intent.id && entry.message?.role === "user");
492
+ if (!user)
493
+ return null;
494
+ // Show the cue turn through its latest descendant, without crossing into the next turn.
495
+ const turn = new Set([user.id]);
496
+ let end = user.id;
497
+ for (const entry of entries) {
498
+ if (!turn.has(entry.parentId) || entry.customType === "mcp_turn_intent")
499
+ continue;
500
+ if (entry.message?.role === "user")
501
+ continue;
502
+ turn.add(entry.id);
503
+ end = entry.id;
504
+ }
505
+ return end;
506
+ }
507
+ consoleHistoryBefore(sessionId, before, atLeaf) {
426
508
  const s = this.get(sessionId);
427
509
  const entries = s.entries();
428
- const history = historyEntries(branch(entries, entries.at(-1)?.id ?? null));
510
+ const history = historyEntries(branch(entries, atLeaf ?? entries.at(-1)?.id ?? null));
429
511
  const end = history.findIndex((e) => e.id === before);
430
512
  if (end < 0)
431
513
  return { history: [], history_before: null, history_reset: true };
432
514
  const start = Math.max(0, end - CONSOLE_HISTORY_SIZE);
515
+ const page = history.slice(start, end).map((e) => this.toHistory(s, e, false, [], "include"));
516
+ limitThinking(page);
433
517
  return {
434
- history: history.slice(start, end).map((e) => this.toHistory(s, e, false, [])),
518
+ history: page,
435
519
  history_before: start > 0 ? history[start].id : null,
436
520
  history_reset: false,
437
521
  };
@@ -488,9 +572,17 @@ export class SessionSupervisor {
488
572
  const bounded = consoleHistory && (!cur || historyReset);
489
573
  const window = bounded ? entries.slice(-CONSOLE_HISTORY_SIZE) : entries;
490
574
  const images = [];
491
- const history = window.map((e) => this.toHistory(s, e, p.include_inline_images !== false, images));
575
+ const thinking = p.include_thinking === true ? "include" : "omit";
576
+ const cueIntents = new Set(v.entries.filter(entry => entry.customType === "mcp_turn_intent" && entry.data?.origin === "cue").map(entry => entry.id));
577
+ const history = window.map(e => {
578
+ const entry = this.toHistory(s, e, p.include_inline_images !== false, images, thinking);
579
+ return e.message?.role === "user" && cueIntents.has(e.parentId) ? { ...entry, origin: "cue" } : entry;
580
+ });
581
+ if (thinking === "include")
582
+ limitThinking(history);
492
583
  const intent = v.entries.findIndex((e) => e.customType === "mcp_turn_intent" && e.data?.turn_id === s.meta.active_turn_id);
493
584
  const task = s.meta.task_id ? [...this.sessions.values()].filter((o) => o.meta.task_id === s.meta.task_id).flatMap((o) => o.entries()) : v.entries;
585
+ const cueUsage = cueOriginEntries(v.entries);
494
586
  const result = {
495
587
  status: this.effectiveStatus(s.meta), turn_id: s.meta.active_turn_id, turn_delivery: s.meta.delivery?.stage ?? null,
496
588
  last_turn_outcome: s.meta.last_turn_outcome, abort_reason: s.meta.abort_reason ?? null,
@@ -501,7 +593,8 @@ export class SessionSupervisor {
501
593
  history, ...(consoleHistory ? { history_before: bounded && entries.length > window.length ? window[0].id : null } : {}),
502
594
  history_reset: historyReset,
503
595
  return_reason, waited_ms, turn_progress: this.turnProgress(s, v.entries),
504
- usage: { current_turn: sumUsage(intent >= 0 ? v.entries.slice(intent) : []), session_total: sumUsage(v.entries), task_total: sumUsage(task) },
596
+ usage: { current_turn: sumUsage(intent >= 0 ? v.entries.slice(intent) : []), session_total: sumUsage(v.entries), task_total: sumUsage(task),
597
+ ...(cueUsage.length ? { by_origin: { cue: { origin: "cue", ...sumUsage(cueUsage) } } } : {}) },
505
598
  // Do not delay an event-driven result with a round-trip to the PTY.
506
599
  screen: ["waiting_input", "failed"].includes(s.meta.status) ? s.lastScreen : undefined,
507
600
  cursor: Buffer.from(JSON.stringify({ view_leaf_id: v.viewLeaf, last_entry_id: v.br.at(-1)?.id ?? null, last_event_seq: s.meta.event_seq ?? 0 })).toString("base64url"),
@@ -587,10 +680,14 @@ export class SessionSupervisor {
587
680
  const previous = s.meta.turn_outcomes?.[turnId];
588
681
  const state = readJson(s.turnState(turnId));
589
682
  const queued = Boolean(state?.queued || state?.state === "queued" || previous?.queued);
683
+ const origin = state?.origin ?? previous?.origin;
684
+ const now = Date.now();
685
+ if (origin === "cue" && s.meta.active_turn_id === turnId)
686
+ s.meta.cue_wake_finished_at = now;
590
687
  const outcomes = { ...(s.meta.turn_outcomes ?? {}), [turnId]: {
591
688
  outcome, error_code: errorCode === undefined ? previous?.error_code ?? null : errorCode,
592
689
  abort_reason: abortReason === undefined ? previous?.abort_reason ?? s.meta.abort_reason ?? null : abortReason,
593
- at: Date.now(), queued, read: previous?.read ?? false,
690
+ at: now, queued, read: previous?.read ?? false, ...(origin === "cue" ? { origin } : {}),
594
691
  } };
595
692
  const ordered = Object.entries(outcomes).sort(([, a], [, b]) => a.at - b.at);
596
693
  const keep = new Set(ordered.slice(-32).map(([id]) => id));
@@ -613,7 +710,7 @@ export class SessionSupervisor {
613
710
  value.read = true;
614
711
  markRead = true;
615
712
  }
616
- return { turn_id, outcome: value.outcome,
713
+ return { turn_id, outcome: value.outcome, ...(value.origin === "cue" ? { origin: "cue" } : {}),
617
714
  ...(value.abort_reason ? { abort_reason: value.abort_reason } : {}), ...(value.error_code ? { error_code: value.error_code } : {}) };
618
715
  });
619
716
  if (markRead)
@@ -728,29 +825,266 @@ export class SessionSupervisor {
728
825
  return { turn_id: queued.turn_id, status: s.meta.status, leaf_id: s.meta.leaf_id, delivery: "steered",
729
826
  steered_turn_id: steeredTurnId, steered_turn_outcome: outcome, ...(forced ? { steer_forced: true } : {}) };
730
827
  }
828
+ cueConfigEnabled() {
829
+ try {
830
+ return JSON.parse(fs.readFileSync(path.join(DATA_ROOT, "config.json"), "utf8"))?.cue?.wake !== "off";
831
+ }
832
+ catch {
833
+ return true;
834
+ }
835
+ }
836
+ cueQuota(meta, now) {
837
+ const since = now - CUE_WAKE_HOUR;
838
+ const own = (meta.cue_wake_starts ?? []).filter((at) => at > since);
839
+ if (own.length >= 6)
840
+ return own[own.length - 6] + CUE_WAKE_HOUR;
841
+ const all = [];
842
+ for (const { meta: other } of this.sessions.values()) {
843
+ if (other.station?.station_id !== meta.station?.station_id)
844
+ continue;
845
+ for (const at of other.cue_wake_starts ?? [])
846
+ if (at > since)
847
+ all.push(at);
848
+ }
849
+ if (all.length < 20)
850
+ return 0;
851
+ all.sort((a, b) => a - b);
852
+ return all[all.length - 20] + CUE_WAKE_HOUR;
853
+ }
854
+ cueEligibility(meta, now = Date.now()) {
855
+ const cues = meta.pending_cues ?? [];
856
+ if (!meta.station || !cues.length || meta.status === "closed")
857
+ return {};
858
+ if (meta.status === "failed")
859
+ return { wake: "not_runnable" };
860
+ if (!this.cueConfigEnabled())
861
+ return {};
862
+ if (!cues.some(cue => (cue.hop ?? 0) < 3))
863
+ return { wake: "hop_limit" };
864
+ if (BUSY.includes(meta.status) || meta.queue?.length || meta.cue_wake_paused)
865
+ return { wake: "scheduled" };
866
+ if (!this.cueSchedulerStarted || this.admission.closed || this.cueWakePaused?.())
867
+ return { wake: "scheduled", at: now + 1000 };
868
+ if (meta.cue_deferred_until > now)
869
+ return { wake: "deferred_cap", at: meta.cue_deferred_until };
870
+ const cooled = (meta.cue_wake_finished_at ?? 0) + CUE_WAKE_COOLDOWN;
871
+ if (cooled > now)
872
+ return { wake: "cooldown", at: cooled };
873
+ const quota = this.cueQuota(meta, now);
874
+ if (quota > now)
875
+ return { wake: "rate_limited" };
876
+ if (meta.cue_retry_at > now)
877
+ return { wake: "blocked", at: meta.cue_retry_at, error_code: meta.cue_wake_error };
878
+ return { wake: "scheduled", at: now };
879
+ }
880
+ pendingCueSummary(meta) {
881
+ const cues = meta.pending_cues ?? [];
882
+ const { wake, error_code } = this.cueEligibility(meta);
883
+ return { count: cues.length, senders: [...new Set(cues.map(cue => cue.from.agent))],
884
+ ...(wake ? { wake } : {}), ...(error_code ? { error_code } : {}) };
885
+ }
731
886
  pendingCues(sessionId) {
732
- const cues = this.get(sessionId).meta.pending_cues ?? [];
733
- return { count: cues.length, from: [...new Set(cues.map((cue) => cue.from.agent))] };
887
+ const { count, senders } = this.pendingCueSummary(this.get(sessionId).meta);
888
+ return { count, from: senders };
889
+ }
890
+ cueHop(sessionId) {
891
+ const m = this.get(sessionId).meta;
892
+ return m.turn_origin === "cue" && BUSY.includes(m.status) && !m.last_turn_outcome ? (m.turn_cue_hop ?? 0) + 1 : 0;
734
893
  }
735
894
  enqueueCue(sessionId, cue) {
736
895
  const s = this.get(sessionId);
737
896
  const pending = (s.meta.pending_cues ?? []).filter((item) => item.from.session_id !== cue.from.session_id);
738
897
  pending.push(cue);
739
- let dropped = s.meta.dropped_cues ?? 0;
740
- if (pending.length > MAX_PENDING_CUES) {
741
- const remove = pending.length - MAX_PENDING_CUES;
898
+ const remove = Math.max(0, pending.length - MAX_PENDING_CUES);
899
+ if (remove)
742
900
  pending.splice(0, remove);
743
- dropped += remove;
901
+ s.set({ pending_cues: pending, dropped_cues: (s.meta.dropped_cues ?? 0) + remove, cue_wake_paused: false });
902
+ this.onCueChange?.(s.meta.station);
903
+ }
904
+ /** Queue priority, cooldown and hourly limits are rechecked under the recipient's lock. */
905
+ triggerCueWake(sessionId, allowImmediate) {
906
+ const s = this.get(sessionId);
907
+ const pending = () => {
908
+ const { wake, error_code } = this.cueEligibility(s.meta);
909
+ return { delivery: "pending", ...(wake ? { wake } : {}), ...(error_code ? { error_code } : {}) };
910
+ };
911
+ const due = this.cueEligibility(s.meta).at;
912
+ if (s.cueWaking || due === undefined || due > Date.now()) {
913
+ this.scheduleCueWake(s);
914
+ return { reserved: false, result: Promise.resolve(pending()) };
915
+ }
916
+ if (!allowImmediate) {
917
+ s.set({ cue_deferred_until: Date.now() + 30_000 });
918
+ this.onCueChange?.(s.meta.station);
919
+ this.scheduleCueWake(s);
920
+ return { reserved: false, result: Promise.resolve(pending()) };
921
+ }
922
+ const result = this.wakeCue(s).then(turn_id => turn_id ? { delivery: "woken", turn_id } : pending());
923
+ return { reserved: true, result };
924
+ }
925
+ startCueScheduler() {
926
+ if (this.cueSchedulerStarted)
927
+ return;
928
+ this.cueSchedulerStarted = true;
929
+ for (const s of this.sessions.values())
930
+ this.scheduleCueWake(s);
931
+ }
932
+ scheduleCueWake(s) {
933
+ const ref = s.meta.station;
934
+ if (!ref || !this.cueSchedulerStarted || s.cueWaking)
935
+ return;
936
+ const { at } = this.cueEligibility(s.meta);
937
+ if (at === undefined)
938
+ return;
939
+ const scheduled = this.cueTimers.get(ref.station_id);
940
+ if (scheduled && scheduled.at <= at)
941
+ return;
942
+ if (scheduled)
943
+ clearTimeout(scheduled.timer);
944
+ const timer = setTimeout(() => {
945
+ this.cueTimers.delete(ref.station_id);
946
+ if (!this.admission.closed)
947
+ this.onCueChange?.(ref);
948
+ for (const member of this.sessions.values()) {
949
+ if (member.meta.station?.station_id !== ref.station_id || member.cueWaking)
950
+ continue;
951
+ const due = this.cueEligibility(member.meta).at;
952
+ if (due !== undefined && due <= Date.now())
953
+ void this.wakeCue(member).catch(console.error);
954
+ else
955
+ this.scheduleCueWake(member);
956
+ }
957
+ }, Math.max(0, at - Date.now()));
958
+ timer.unref();
959
+ this.cueTimers.set(ref.station_id, { at, timer });
960
+ }
961
+ releaseCueReservation(s) {
962
+ const at = s.meta.cue_launch_pending;
963
+ if (typeof at !== "number")
964
+ return;
965
+ s.set({ cue_launch_pending: null, cue_wake_starts: (s.meta.cue_wake_starts ?? []).filter((start) => start !== at) });
966
+ }
967
+ async wakeCue(s) {
968
+ s.cueWaking = true;
969
+ try {
970
+ return await s.run(async () => {
971
+ const ref = s.meta.station;
972
+ const params = { session_id: s.meta.session_id };
973
+ const done = this.admission.tryEnter(`cue_wake:${params.session_id}`);
974
+ if (!done)
975
+ return;
976
+ let release;
977
+ let reservedAt;
978
+ let turnId;
979
+ let submitted = false;
980
+ try {
981
+ await this.refresh(s);
982
+ const now = Date.now();
983
+ const { at } = this.cueEligibility(s.meta, now);
984
+ if (!["idle", "dormant"].includes(s.meta.status) || s.meta.queue?.length || at === undefined || at > now)
985
+ return;
986
+ if (s.meta.error_code === "DELIVERY_UNKNOWN")
987
+ fail("DELIVERY_UNKNOWN");
988
+ this.gateSnapshot(s, "session_send", params);
989
+ release = this.admitCueWake?.(ref, s.meta.agent, params.session_id);
990
+ // Reserve the hourly slot before an asynchronous dormant launch.
991
+ reservedAt = now;
992
+ s.set({ cue_launch_pending: now, cue_wake_starts: [...(s.meta.cue_wake_starts ?? []).filter((at) => at > now - CUE_WAKE_HOUR), now] });
993
+ if (!s.host)
994
+ await this.launch(s);
995
+ if (!this.cueConfigEnabled() || this.cueWakePaused?.()) {
996
+ if (s.meta.status === "starting")
997
+ s.set({ status: "idle" });
998
+ return;
999
+ }
1000
+ this.gateSnapshot(s, "session_send", params);
1001
+ const cues = s.meta.pending_cues ?? [];
1002
+ if (!cues.some(cue => (cue.hop ?? 0) < 3)) {
1003
+ if (s.meta.status === "starting")
1004
+ s.set({ status: "idle" });
1005
+ return;
1006
+ }
1007
+ const content = cues.map(cue => `[cue] 来自 ${cue.from.agent}(${cue.from.session_id},看板 v${cue.board.version}):${cue.message || "(无文字)"}`)
1008
+ .concat("请查看发送者的看板并与之对齐;方向性问题以 master 看板为准。").join("\n");
1009
+ const hop = Math.max(...cues.filter(cue => (cue.hop ?? 0) < 3).map(cue => cue.hop ?? 0), 0);
1010
+ turnId = `turn_${++s.meta.turn_seq}`;
1011
+ writeJson(s.file(path.join("inbox", `${turnId}.json`)), { turn_id: turnId, content, origin: "cue" });
1012
+ writeJson(s.turnState(turnId), { state: "staged", updated_at: Date.now(), origin: "cue", hop, cues, dropped: s.meta.dropped_cues ?? 0 });
1013
+ // The rolling hour counts actual turn starts, not time spent booting Pi.
1014
+ s.meta.cue_wake_starts[s.meta.cue_wake_starts.length - 1] = Date.now();
1015
+ submitted = true;
1016
+ await this.submit(s, turnId);
1017
+ if (s.meta.turn_outcomes?.[turnId]?.outcome === "not_delivered" || s.meta.error_code === "DELIVERY_UNKNOWN")
1018
+ return;
1019
+ return s.meta.delivery?.stage === "sent_to_terminal" ? undefined : turnId;
1020
+ }
1021
+ catch (error) {
1022
+ const code = error?.code ?? "START_FAILED";
1023
+ if (submitted && turnId) {
1024
+ const state = readJson(s.turnState(turnId));
1025
+ if (state?.state === "staged") {
1026
+ // The PTY may still contain a command; the abandoned state prevents late execution.
1027
+ this.recordOutcome(s, turnId, "not_delivered", code, null);
1028
+ writeJson(s.turnState(turnId), { ...state, state: "abandoned", updated_at: Date.now() });
1029
+ s.set({ status: "failed", error_code: code, last_turn_outcome: "not_delivered" });
1030
+ }
1031
+ else if (state?.state === "persisted" || (s.meta.turn_outcomes?.[turnId] && s.meta.turn_outcomes[turnId].outcome !== "not_delivered")) {
1032
+ this.recordCueWake(s, turnId, state);
1033
+ return turnId;
1034
+ }
1035
+ else if (!s.meta.turn_outcomes?.[turnId])
1036
+ this.markUnknown(s, turnId, code);
1037
+ }
1038
+ else if (s.meta.status === "starting" && s.ready && s.host)
1039
+ s.set({ status: "idle" });
1040
+ const changed = s.meta.cue_wake_error !== code;
1041
+ s.set({ cue_wake_error: code, cue_retry_at: Date.now() + CUE_BLOCK_RETRY });
1042
+ if (!submitted && changed)
1043
+ this.onCueBlocked?.(ref, params.session_id, (s.meta.pending_cues ?? []).map((cue) => cue.cue_id), code);
1044
+ return;
1045
+ }
1046
+ finally {
1047
+ try {
1048
+ if (!submitted && reservedAt !== undefined)
1049
+ this.releaseCueReservation(s);
1050
+ }
1051
+ finally {
1052
+ try {
1053
+ release?.();
1054
+ }
1055
+ finally {
1056
+ done();
1057
+ this.onCueChange?.(ref);
1058
+ }
1059
+ }
1060
+ }
1061
+ });
1062
+ }
1063
+ finally {
1064
+ s.cueWaking = false;
1065
+ this.scheduleCueWake(s);
744
1066
  }
745
- s.set({ pending_cues: pending, dropped_cues: dropped });
746
1067
  }
747
1068
  consumeCues(sessionId) {
748
1069
  const s = this.get(sessionId);
749
- const cues = s.meta.pending_cues ?? [];
1070
+ const pending = s.meta.pending_cues ?? [];
750
1071
  const dropped = s.meta.dropped_cues ?? 0;
751
- if (cues.length || dropped)
752
- s.set({ pending_cues: [], dropped_cues: 0 });
753
- return { cues, dropped };
1072
+ const state = s.meta.turn_origin === "cue" && BUSY.includes(s.meta.status) ? readJson(s.turnState(s.meta.active_turn_id)) : null;
1073
+ if (state?.origin === "cue") {
1074
+ if (s.meta.cue_context_turn_id === s.meta.active_turn_id)
1075
+ return { cues: [], dropped: 0 };
1076
+ const cues = state.cues ?? [];
1077
+ const ids = new Set(cues.map(cue => cue.cue_id));
1078
+ s.set({ cue_context_turn_id: s.meta.active_turn_id, pending_cues: pending.filter(cue => !ids.has(cue.cue_id)),
1079
+ dropped_cues: Math.max(0, dropped - (state.dropped ?? 0)) });
1080
+ this.onCueChange?.(s.meta.station);
1081
+ return { cues, dropped: state.dropped ?? 0 };
1082
+ }
1083
+ if (pending.length || dropped) {
1084
+ s.set({ pending_cues: [], dropped_cues: 0, cue_deferred_until: null, cue_retry_at: null, cue_wake_error: null });
1085
+ this.onCueChange?.(s.meta.station);
1086
+ }
1087
+ return { cues: pending, dropped };
754
1088
  }
755
1089
  /** Starts a new turn; handles busy rejection, wake-up and explicit DELIVERY_UNKNOWN resolution. */
756
1090
  async deliver(s, content, resolve, rec, operation, originalParams, started, validateMembership, queuedId) {
@@ -775,7 +1109,7 @@ export class SessionSupervisor {
775
1109
  fail("DELIVERY_UNKNOWN", `resolve turn ${unknown} with resolve_unknown_turn first`);
776
1110
  s.set({ error_code: null, unknown_turn: null, last_error: null });
777
1111
  if (resolve.action === "retry") {
778
- writeJson(s.turnState(unknown), { state: "staged", updated_at: Date.now() });
1112
+ writeJson(s.turnState(unknown), { ...readJson(s.turnState(unknown)), state: "staged", updated_at: Date.now() });
779
1113
  if (!s.host)
780
1114
  await this.launch(s, started);
781
1115
  rec({ turn_id: unknown });
@@ -794,22 +1128,36 @@ export class SessionSupervisor {
794
1128
  await this.submit(s, turnId, started);
795
1129
  return turnId;
796
1130
  }
1131
+ recordCueWake(s, turnId, state) {
1132
+ if (state?.origin !== "cue" || s.meta.error_code === "DELIVERY_UNKNOWN" ||
1133
+ s.meta.turn_outcomes?.[turnId]?.outcome === "not_delivered")
1134
+ return;
1135
+ this.onCueWoken?.(s.meta.station, s.meta.session_id, (state.cues ?? []).map((cue) => cue.cue_id), turnId);
1136
+ }
797
1137
  /**
798
1138
  * Delivery has three recorded stages: sent_to_terminal (PTY got the command), accepted (bridge
799
1139
  * dispatched it) and persisted (verified in session.jsonl on disk). An unacknowledged command is
800
1140
  * cancelled while still staged, so it can never run later.
801
1141
  */
802
1142
  async submit(s, turnId, started) {
1143
+ const state = readJson(s.turnState(turnId));
803
1144
  s.lastStop = null;
804
- s.set({ status: "running", active_turn_id: turnId, turn_started_at: Date.now(), turn_event_at: null, last_turn_outcome: null,
1145
+ s.set({ turn_origin: state?.origin ?? null, turn_cue_hop: state?.hop ?? null, cue_wake_paused: false, cue_launch_pending: null,
1146
+ status: "running", active_turn_id: turnId, turn_started_at: Date.now(), turn_event_at: null, last_turn_outcome: null,
805
1147
  abort_reason: null, error_code: null, last_error: null, pending_request: null, delivery: { turn_id: turnId, stage: "sent_to_terminal" } });
806
1148
  started?.();
807
1149
  await s.host.submit(turnId);
808
- if (await this.waitFor(s, () => s.meta.delivery.stage !== "sent_to_terminal" || s.meta.status !== "running", ACK_TIMEOUT_MS))
1150
+ if (await this.waitFor(s, () => s.meta.delivery.stage !== "sent_to_terminal" || s.meta.status !== "running", ACK_TIMEOUT_MS)) {
1151
+ if (s.meta.delivery.stage !== "sent_to_terminal")
1152
+ this.recordCueWake(s, turnId, state);
809
1153
  return;
810
- if (readJson(s.turnState(turnId))?.state !== "staged")
811
- return s.set({ delivery: { turn_id: turnId, stage: "accepted" } });
812
- writeJson(s.turnState(turnId), { state: "abandoned", reason: "SUBMIT_NOT_ACKNOWLEDGED", updated_at: Date.now() });
1154
+ }
1155
+ if (readJson(s.turnState(turnId))?.state !== "staged") {
1156
+ s.set({ delivery: { turn_id: turnId, stage: "accepted" } });
1157
+ this.recordCueWake(s, turnId, state);
1158
+ return;
1159
+ }
1160
+ writeJson(s.turnState(turnId), { ...readJson(s.turnState(turnId)), state: "abandoned", reason: "SUBMIT_NOT_ACKNOWLEDGED", updated_at: Date.now() });
813
1161
  await s.host.keys(["ctrl+u"]).catch(() => { });
814
1162
  this.recordOutcome(s, turnId, "not_delivered", "SUBMIT_NOT_ACKNOWLEDGED", null);
815
1163
  s.set({ status: "failed", error_code: "SUBMIT_NOT_ACKNOWLEDGED", last_error: "Pi did not accept the submit command; the turn was not executed" });
@@ -1060,6 +1408,11 @@ export class SessionSupervisor {
1060
1408
  async recover(s, reason) {
1061
1409
  this.syncDisk(s);
1062
1410
  const m = s.meta;
1411
+ if (typeof m.cue_launch_pending === "number") {
1412
+ // No submit occurred; do not change the previous turn's outcome.
1413
+ this.releaseCueReservation(s);
1414
+ return s.set({ status: "dormant", instance_id: null, pending_request: null, pids: [] });
1415
+ }
1063
1416
  if (await this.expirePendingInput(s))
1064
1417
  return;
1065
1418
  if (!BUSY.includes(m.status))
@@ -1067,6 +1420,11 @@ export class SessionSupervisor {
1067
1420
  const turnId = m.active_turn_id;
1068
1421
  const state = turnId ? readJson(s.turnState(turnId)) : null;
1069
1422
  if (state?.state === "staged") {
1423
+ if (state.origin === "cue") {
1424
+ // An unaccepted cue is still in the inbox; re-run admission and queue priority after boot.
1425
+ this.recordOutcome(s, turnId, "not_delivered", reason, null);
1426
+ return s.set({ status: "dormant", instance_id: null, pending_request: null, pids: [], last_turn_outcome: "not_delivered" });
1427
+ }
1070
1428
  await this.launch(s);
1071
1429
  return this.submit(s, turnId);
1072
1430
  }
@@ -1082,13 +1440,15 @@ export class SessionSupervisor {
1082
1440
  s.set({ status: "failed", error_code: "DELIVERY_UNKNOWN", last_error: why, pending_request: null,
1083
1441
  unknown_turn: { turn_id: turnId, prompt_preview: text.slice(0, 200), state: "dispatched_unverified" } });
1084
1442
  }
1085
- toHistory(s, e, inline, images) {
1443
+ toHistory(s, e, inline, images, thinking) {
1086
1444
  const m = e.message;
1087
1445
  if (!m)
1088
1446
  return { id: e.id, type: e.type, summary: e.summary ?? null, timestamp: e.timestamp };
1089
1447
  let omitted = 0;
1090
1448
  const content = !Array.isArray(m.content) ? m.content : m.content.flatMap((c, i) => {
1091
1449
  if (c.type === "thinking") {
1450
+ if (thinking === "include")
1451
+ return [thinkingPart(c)];
1092
1452
  omitted++;
1093
1453
  return [];
1094
1454
  }