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.
@@ -1,5 +1,6 @@
1
1
  import { badge, layout, viewNav } from "./pages.js";
2
2
  import { esc, formatTime } from "./util.js";
3
+ import { activityPanel } from "./activity-page.js";
3
4
  export const stationViews = [
4
5
  ["overview", "Overview"], ["members", "Members"], ["boards", "Boards"], ["revisions", "Revisions"], ["settings", "Settings"],
5
6
  ];
@@ -95,6 +96,17 @@ function queueCard(station, regions) {
95
96
  <div class="actions"><button type="button" data-ask-jaxon>Ask JaXon</button><a class="quiet-link" href="/sessions?view=jaxon&amp;agent=JaXon">Open JaXon in Sessions</a></div>
96
97
  </aside></section>`;
97
98
  }
99
+ const cueWakeLabels = {
100
+ scheduled: "Next turn", cooldown: "Wake cooling down", rate_limited: "Wake limit reached", deferred_cap: "Wake deferred",
101
+ hop_limit: "Relay limit — next turn only", blocked: "Wake blocked", not_runnable: "Session cannot run",
102
+ };
103
+ function pendingCueBadge(pending) {
104
+ if (!pending?.count)
105
+ return "";
106
+ const wake = pending.wake ? cueWakeLabels[pending.wake] : undefined;
107
+ const title = [`${pending.count} unread cues`, pending.senders.join(", "), wake].filter(Boolean).join(" · ");
108
+ return `<span class="cue-badge" title="${esc(title)}" aria-label="${esc(title)}">${pending.count}</span>${wake ? `<small>${esc(wake)}</small>` : ""}`;
109
+ }
98
110
  function membersContent(station, members, pages) {
99
111
  const roster = station.agents.map(a => a.name);
100
112
  const joining = new Set(station.station_pending?.join);
@@ -119,14 +131,14 @@ function membersContent(station, members, pages) {
119
131
  <section id="member-sessions"><div class="section-heading"><h2>Member sessions</h2></div>
120
132
  ${pages.list("members_page", "Member sessions", orderedMembers, rows => rows.length ? `<div class="table-wrap"><table class="resource-list"><thead><tr>
121
133
  <th scope="col">Member session</th><th scope="col">Status</th><th scope="col">Updated</th><th scope="col">Turn progress</th></tr></thead>
122
- <tbody>${rows.map(m => `<tr><td><a href="${sessionUrl(m.session_id)}">${m.station.seat ? "" : "↳ "}${esc(m.agent)}</a>${badge(m.station.seat ? "Seat" : "Independent")}<small><code>${esc(m.session_id)}</code></small></td><td><div class="status-group">${badge(m.status)}${m.in_roster === false ? badge("Outside effective roster") : ""}</div></td>
134
+ <tbody>${rows.map(m => `<tr><td><a href="${sessionUrl(m.session_id)}">${m.station.seat ? "" : "↳ "}${esc(m.agent)}</a>${badge(m.station.seat ? "Seat" : "Independent")}<small><code>${esc(m.session_id)}</code></small></td><td><div class="status-group">${badge(m.status)}${m.in_roster === false ? badge("Outside effective roster") : ""}${m.turn_progress?.origin === "cue" ? badge("Woken by cue") : ""}${pendingCueBadge(m.pending_cues)}</div></td>
123
135
  <td>${esc(formatTime(m.updated_at))}</td><td>${m.turn_progress ? `${esc(m.turn_progress.elapsed_ms)} ms · ${esc(m.turn_progress.tool_calls)} tool calls${m.turn_progress.last_tool ? `<small>Last tool: ${esc(m.turn_progress.last_tool)}</small>` : ""}` : "—"}</td></tr>`).join("")}</tbody></table></div>` : empty("No open member sessions."), "member-sessions")}</section>`;
124
136
  }
125
137
  function boardsContent(station, boards, pages) {
126
138
  const id = field("station", station.station_id);
127
139
  return pages.list("boards_page", "Boards", boards, rows => `<div data-board-list>${rows.length ? rows.map(b => {
128
140
  const by = b.updated_by ? ` · ${b.updated_by.kind}${b.updated_by.kind === "member" ? ` (${b.updated_by.session_id})` : ""}` : "";
129
- return `<article class="card station-board" data-board="${esc(b.owner)}" data-version="${b.version}">
141
+ return `<article class="card station-board" id="board-${esc(b.owner)}" data-board="${esc(b.owner)}" data-version="${b.version}">
130
142
  <div class="section-heading" data-board-title><h3>${esc(b.owner)}</h3><div class="status-group">${b.active_sessions.length ? badge(`${b.active_sessions.length} active session${b.active_sessions.length === 1 ? "" : "s"}`) : ""}${b.in_roster ? "" : badge("Former member")}${badge(b.owner_active ? "Active owner" : "No active owner")}</div></div>
131
143
  <p class="muted" data-board-meta>Version ${b.version}${esc(by)}${b.updated_at ? ` · ${esc(formatTime(b.updated_at))}` : ""}</p>
132
144
  <p class="warning" data-board-stale hidden>Your draft is based on an older version.</p><pre data-board-content>\n${esc(b.content || "(empty)")}</pre>
@@ -144,12 +156,28 @@ function revisionsContent(station, pages) {
144
156
  <tbody>${rows.map(r => `<tr><td><a href="${esc(pages.href({ revision: r }))}"><code>${esc(r)}</code></a></td><td><div class="status-group">${r === station.revision ? badge("Current") : ""}${r === station.active_revision ? badge("Effective") : ""}</div></td>
145
157
  <td class="row-action-cell"><div class="row-actions">${r === station.revision ? "—" : `${form("station_update", 'data-confirm="Publish a rollback as a new revision?"')}${target}${field("from_revision", r)}<button class="secondary" type="submit">Roll back</button></form>`}</div></td></tr>`).join("")}</tbody></table></div>` : empty("No revision history."), "station-revisions")}</section>`;
146
158
  }
159
+ function cueLogRow(cue) {
160
+ const to = cue.to.session_id ? `<a href="${sessionUrl(cue.to.session_id)}">${esc(cue.to.target)}</a> <small><code>${esc(cue.to.session_id)}</code></small>` : esc(cue.to.target);
161
+ const outcome = cue.woken_turn_id && cue.to.session_id
162
+ ? `<a href="${sessionUrl(cue.to.session_id)}?turn=${encodeURIComponent(cue.woken_turn_id)}">Woken · ${esc(cue.woken_turn_id)}</a>`
163
+ : cue.skipped ? "Skipped · no session" : cue.delivered_at ? "Delivered on a turn" : cue.wake ? `Pending · ${esc(cueWakeLabels[cue.wake])}` : "Pending";
164
+ return `<tr><td>${esc(formatTime(cue.at))}</td><td>${esc(cue.from.agent)} <small><code>${esc(cue.from.session_id)}</code></small> → ${to}</td>
165
+ <td><a href="?view=boards#${esc(encodeURIComponent(`board-${cue.board.owner}`))}">${esc(cue.board.owner)} · v${esc(cue.board.version)}</a></td>
166
+ <td>${esc(cue.message ?? "—")}</td><td>${outcome}<small>Hop ${esc(cue.hop ?? 0)}</small></td></tr>`;
167
+ }
168
+ function cueActivityContent(station, pages) {
169
+ const cues = (station.cue_log ?? []).slice().reverse();
170
+ return pages.list("cues_page", "Cue activity", cues, rows => rows.length
171
+ ? `<div class="table-wrap"><table class="resource-list"><thead><tr>
172
+ <th scope="col">Time</th><th scope="col">From → to</th><th scope="col">Board</th><th scope="col">Reminder</th><th scope="col">Delivery</th>
173
+ </tr></thead><tbody>${rows.map(cueLogRow).join("")}</tbody></table></div>`
174
+ : empty("No cues sent yet."), "cue-activity");
175
+ }
147
176
  function overviewContent(station) {
148
177
  return `<section class="card"><h2>Station details</h2><dl class="details"><dt>Station ID</dt><dd><code>${esc(station.station_id)}</code></dd>
149
178
  <dt>Station state</dt><dd>${stateBadge(station.state)}</dd><dt>Delivery state</dt><dd>${esc(deliveryLabels[station.delivery_state])}</dd>
150
179
  <dt>Current revision</dt><dd><code>${esc(station.revision)}</code></dd><dt>Effective revision</dt><dd><code>${esc(effectiveRevision(station))}</code></dd></dl></section>
151
- <section class="card"><h2>Effective shared description</h2><pre>\n${esc(station.station_context.description)}</pre></section>
152
- <section class="card"><h2>Cue activity</h2>${station.cue_log?.length ? `<div class="table-wrap"><table class="resource-list"><thead><tr><th>Time</th><th>From → to</th><th>Board</th><th>Reminder</th></tr></thead><tbody>${station.cue_log.slice().reverse().slice(0, 20).map(cue => `<tr><td>${esc(formatTime(cue.at))}</td><td>${esc(cue.from.agent)} <small><code>${esc(cue.from.session_id)}</code></small> → ${esc(cue.to.target)}${cue.to.session_id ? ` <small><code>${esc(cue.to.session_id)}</code></small>` : ""}</td><td><a href="?view=boards">${esc(cue.board.owner)} · v${esc(cue.board.version)}</a></td><td>${esc(cue.message ?? "—")}</td></tr>`).join("")}</tbody></table></div>` : empty("No cues sent yet.")}</section>`;
180
+ <section class="card"><h2>Effective shared description</h2><pre>\n${esc(station.station_context.description)}</pre></section>`;
153
181
  }
154
182
  export const hasRosterControls = (view) => view === "overview" || view === "members";
155
183
  export function stationLiveRegions(station, members, boards, pages, view, presetNames) {
@@ -164,6 +192,7 @@ export function stationLiveRegions(station, members, boards, pages, view, preset
164
192
  switch (view) {
165
193
  case "overview":
166
194
  regions["station-overview"] = overviewContent(station);
195
+ regions["cue-activity-content"] = cueActivityContent(station, pages);
167
196
  break;
168
197
  case "members":
169
198
  regions["station-members"] = membersContent(station, members, pages);
@@ -202,13 +231,18 @@ export function stationDetailPage(station, members, boards, pages, view, presetN
202
231
  <details class="drawer destructive"><summary>Delete Station</summary><section class="card danger-zone"><p>Permanently delete this Station and its boards.</p>
203
232
  ${form("station_delete", 'data-redirect="/stations" data-confirm="Delete this Station and its boards?"')}${target}<button class="danger" type="submit">Delete Station</button></form></section></details>`;
204
233
  break;
205
- default: content = `<div id="station-overview">${regions["station-overview"]}</div>`;
234
+ default: content = `<div id="station-overview">${regions["station-overview"]}</div>
235
+ <section class="card" id="cue-activity" aria-labelledby="cue-activity-heading">
236
+ <h2 id="cue-activity-heading">Cue activity</h2>
237
+ <p class="muted">Recent reminders, including ones that couldn’t be delivered or woke a member.</p>
238
+ <div id="cue-activity-content">${regions["cue-activity-content"]}</div>
239
+ </section>`;
206
240
  }
207
241
  return layout(name, `<a class="back" href="/stations">← Stations</a>
208
242
  <div data-station-live="${esc(station_id)}"><header class="page-heading"><div><div class="title-row"><h1>${esc(name)}</h1><div class="status-group" id="station-state">${regions["station-state"]}</div></div>
209
243
  <p id="station-summary">${regions["station-summary"]}</p><small data-station-connection role="status">Connecting to live updates…</small></div>
210
244
  <a class="primary-link" href="/sessions?view=new&amp;station=${encodeURIComponent(station_id)}">Start member session</a></header>
211
- ${viewNav("Station sections", stationViews, view)}<div class="resource-content">${hasRosterControls(view) ? queueCard(station, regions) : ""}${content}</div></div>`, "station");
245
+ ${activityPanel(station_id)}${viewNav("Station sections", stationViews, view)}<div class="resource-content">${hasRosterControls(view) ? `<details class="drawer activity-secondary"><summary>Station operations &amp; queued changes</summary>${queueCard(station, regions)}</details>` : ""}${content}</div></div>`, "station");
212
246
  }
213
247
  export function stationRevisionPage(station, pages) {
214
248
  const back = stationUrl(station.station_id) + pages.href({ view: "revisions", revision: null, revision_members_page: null });
@@ -19,7 +19,7 @@ function spawnDaemon() {
19
19
  const child = spawn(process.execPath, [daemonEntry()], {
20
20
  detached: true,
21
21
  stdio: ["ignore", log, log],
22
- env: Object.fromEntries(["PATH", "LANG", "HOME", "XDG_RUNTIME_DIR"]
22
+ env: Object.fromEntries(["PATH", "LANG", "LC_ALL", "LC_MESSAGES", "HOME", "XDG_RUNTIME_DIR"]
23
23
  .filter((name) => process.env[name] !== undefined)
24
24
  .map((name) => [name, process.env[name]])),
25
25
  });
@@ -381,6 +381,8 @@ export async function main() {
381
381
  updater?.start();
382
382
  }
383
383
  startupComplete = true;
384
+ ops.activityGraph.startBackground();
385
+ ops.supervisor.startCueScheduler();
384
386
  if (!RELEASE) {
385
387
  ops.admission.onChange = scheduleRestartCheck;
386
388
  restartTimer = setInterval(scheduleRestartCheck, 30_000);
@@ -6,7 +6,7 @@ import { daemonSocketPath } from "../daemon/paths.js";
6
6
  import { CODE_ROOT } from "../root.js";
7
7
  import { piExec } from "./runtime-binaries.js";
8
8
  export const shellEscape = (arg) => `'${arg.replace(/'/g, `'\\''`)}'`;
9
- const HARNESS_EXTENSION = path.join(CODE_ROOT, "dist/pi-host/mcp-bridge.entry.js");
9
+ export const HARNESS_EXTENSION = path.join(CODE_ROOT, "dist/pi-host/mcp-bridge.entry.js");
10
10
  const JAXON_EXTENSION = path.join(CODE_ROOT, "dist/agents/jaxon-admin.entry.js");
11
11
  const MEMBER_EXTENSION = path.join(CODE_ROOT, "dist/stations/station-member.entry.js");
12
12
  export function piEnvironment(agentDir, _home, extra = {}) {
@@ -21,6 +21,7 @@ const defs = [
21
21
  { name: "session_read", description: "Read status, final outcome, incremental history, pending prompt, screen and usage.", write: false, schema: {
22
22
  session_id: z.string(), after: z.string().optional(), wait_ms: wait, wait_until: z.enum(["turn_end", "change"]).optional(),
23
23
  at_leaf: z.string().optional(), include_inline_images: z.boolean().optional(),
24
+ include_thinking: z.boolean().optional().describe("Default false. Avoid unless you specifically need a sub-agent's reasoning: thinking blocks greatly enlarge the context and work against context minimization. Track actions, boards and results instead."),
24
25
  } },
25
26
  { name: "session_send", description: "Send a follow-up. Busy turns queue by default; delivery=steer interrupts the current turn, preserves history and starts this instruction next.", write: true, schema: {
26
27
  session_id: z.string(), prompt: z.string(), attachments, delivery: z.enum(["queued", "steer"]).optional(),
package/dist/ops/core.js CHANGED
@@ -5,6 +5,7 @@ import { allocateSessionId, SessionSupervisor } from "../sessions/supervisor.js"
5
5
  import { StationStore, lint } from "../stations/station-store.js";
6
6
  import { StationActivity, stationContext, stationRef } from "../stations/activity.js";
7
7
  import { BoardStore } from "../stations/boards.js";
8
+ import { stationMemberInstructions } from "../stations/member-instructions.js";
8
9
  import { StationCueStore } from "../stations/cues.js";
9
10
  import { performance } from "node:perf_hooks";
10
11
  import { randomUUID } from "node:crypto";
@@ -12,6 +13,7 @@ import { operationDefs, operationNames, nonIdempotent, operationSchema, stationP
12
13
  import { fail, OpError } from "./errors.js";
13
14
  import { IdempotencyStore } from "./idempotency.js";
14
15
  import { ActivityRegistry } from "../daemon/activity.js";
16
+ import { StationActivityGraph } from "../console/activity.js";
15
17
  const json = (v) => JSON.stringify(v, null, 2) + "\n";
16
18
  const jaxonOps = new Set([...operationDefs.filter(({ name }) => name.startsWith("agent_") || name.startsWith("station_")).map(({ name }) => name), "connection_list"]);
17
19
  const memberOps = new Set(["member_context", "board_read", "board_write", "cue"]);
@@ -29,6 +31,7 @@ export class OperationsCore {
29
31
  boards = new BoardStore(this.activity);
30
32
  cues = new StationCueStore(this.activity.root);
31
33
  stationListeners = new Set();
34
+ activityGraph = new StationActivityGraph(this);
32
35
  onStationChange(listener) {
33
36
  this.stationListeners.add(listener);
34
37
  return () => { this.stationListeners.delete(listener); };
@@ -43,6 +46,15 @@ export class OperationsCore {
43
46
  constructor() {
44
47
  this.connections.onConnectionChanged = (id) => this.readiness.onConnectionChanged(id);
45
48
  this.activity.onChange = (id) => this.stationChanged(id);
49
+ this.cues.onChange = (id) => this.stationChanged(id);
50
+ this.supervisor.onCueChange = ref => this.stationChanged(ref.station_id);
51
+ this.supervisor.onCueBlocked = (ref, session_id, cue_ids, error_code) => this.cues.event(ref, { session_id, cue_ids, wake: "blocked", error_code, at: Date.now() });
52
+ this.supervisor.onCueWoken = (ref, session_id, cue_ids, woken_turn_id) => this.cues.event(ref, { session_id, cue_ids, woken_turn_id, at: Date.now() });
53
+ this.supervisor.cueWakePaused = () => ["waiting_quiet", "handing_off", "maintenance"].includes(this.serviceInfo?.()?.runtime?.update?.state);
54
+ this.supervisor.admitCueWake = (ref, agent, sessionId) => {
55
+ this.activity.validateAdmittedStart(ref, agent);
56
+ return this.activity.admit(ref, agent, sessionId);
57
+ };
46
58
  this.supervisor.beforeMemberLaunch = (ref) => this.activity.launching(ref);
47
59
  this.supervisor.onStationStatus = (ref, before, after) => this.activity.statusChanged(ref, before, after);
48
60
  this.supervisor.recoverOnStartup();
@@ -73,12 +85,15 @@ export class OperationsCore {
73
85
  return this.counted(() => this.boards.snapshot(this.stations.resolve(station)));
74
86
  }
75
87
  /** The console starts with a bounded tail and uses the same cursor as MCP for live updates. */
76
- async consoleSessionRead(sessionId, after) {
77
- const { result } = await this.supervisor.readSession({ session_id: sessionId, after, include_inline_images: false }, { counted: this.counted }, true);
88
+ async consoleSessionRead(sessionId, after, atLeaf) {
89
+ const { result } = await this.supervisor.readSession({ session_id: sessionId, after, at_leaf: atLeaf, include_inline_images: false, include_thinking: true }, { counted: this.counted }, true);
78
90
  return result;
79
91
  }
80
- consoleSessionHistoryBefore(sessionId, before) {
81
- return this.counted(() => this.supervisor.consoleHistoryBefore(sessionId, before));
92
+ consoleCueTurnLeaf(sessionId, turnId) {
93
+ return this.counted(() => this.supervisor.cueTurnLeaf(sessionId, turnId));
94
+ }
95
+ consoleSessionHistoryBefore(sessionId, before, atLeaf) {
96
+ return this.counted(() => this.supervisor.consoleHistoryBefore(sessionId, before, atLeaf));
82
97
  }
83
98
  consoleAgentList() {
84
99
  return this.counted(() => store.listPresets().map((agent) => {
@@ -126,12 +141,8 @@ export class OperationsCore {
126
141
  context = cold?.();
127
142
  }
128
143
  const status = ref && projection ? this.activity.status(ref, projection) : undefined;
129
- const pendingCues = front === "master" && ref && (name === "session_list" || (name === "board_read" && "boards" in base))
130
- ? this.cues.masterPending(ref) : undefined;
131
- const received = front === "master" && ref ? this.cues.consumeMaster(ref) : { cues: [], dropped: 0 };
132
144
  return { ...base, ...projection, ...status, ...(context ? { station_context: context } : {}),
133
- ...(pending ? { station_pending: pending } : {}), ...(pendingCues ? { pending_cues: pendingCues } : {}),
134
- ...(received.cues.length ? { cues: received.cues } : {}), ...(received.dropped ? { dropped_cues: received.dropped } : {}) };
145
+ ...(pending ? { station_pending: pending } : {}) };
135
146
  }
136
147
  async poll(name, params, front, options) {
137
148
  const start = performance.now();
@@ -141,6 +152,8 @@ export class OperationsCore {
141
152
  ? this.stations.resolve(params.station) : this.stationFor(name, params));
142
153
  const reply = name === "session_read" ? await this.supervisor.readSession(params, wait)
143
154
  : { result: await this.supervisor.listSessions(ref ? { ...params, station: ref.station_id } : params, wait), images: [] };
155
+ if (ref && name === "session_read" && front === "master")
156
+ this.activityGraph.recordReports(ref, params.session_id, reply.result);
144
157
  if (params.wait_ms !== undefined && "waited_ms" in reply.result)
145
158
  console.log(JSON.stringify({ op: name, wait_ms: params.wait_ms,
146
159
  waited_ms: reply.result.waited_ms, return_reason: reply.result.return_reason }));
@@ -197,6 +210,14 @@ export class OperationsCore {
197
210
  const result = requestId
198
211
  ? await this.idempotency.execute(name, params, (rec) => this.dispatch(name, params, rec, front, claim), front, ref?.station_id)
199
212
  : await this.dispatch(name, params, () => { }, front, claim);
213
+ if (ref && ["session_start", "session_send", "session_reply", "session_interrupt", "session_close"].includes(name)) {
214
+ const meta = name === "session_start" ? undefined : this.supervisor.sessions.get(params.session_id)?.meta;
215
+ const sessionId = name === "session_start" ? result.session_id : params.session_id;
216
+ this.activityGraph.recordDispatch(ref, { op: name, agent: name === "session_start" ? params.agent : meta.agent,
217
+ session_id: sessionId, seat: name === "session_start" ? result.seat : meta.station.seat ?? true,
218
+ turn_id: result.turn_id ?? meta?.active_turn_id ?? undefined, delivery: result.delivery ?? (name === "session_start" ? "started" : undefined),
219
+ source: front === "human" ? "human" : "master" });
220
+ }
200
221
  if (!stationParamOps.has(name) && !stationSessionOps.has(name))
201
222
  return result;
202
223
  const id = (requestId ? this.idempotency.stationFor(requestId) : undefined)
@@ -223,9 +244,15 @@ export class OperationsCore {
223
244
  if (name === "member_context") {
224
245
  const board = this.boards.own(ref, member.agent);
225
246
  this.memberBoardVersions.set(member.session_id, board.version);
247
+ const station = this.activity.effective(ref);
248
+ const master_board = this.boards.read(ref, "master").board;
226
249
  const { cues, dropped } = this.supervisor.consumeCues(member.session_id);
227
- return { station: this.activity.effective(ref), agent: member.agent, session_id: member.session_id, seat: member.seat,
228
- master_board: this.boards.read(ref, "master").board, board, cues, dropped_cues: dropped };
250
+ if (cues.length) {
251
+ const now = Date.now();
252
+ this.cues.event(ref, { session_id: member.session_id, cue_ids: cues.map(cue => cue.cue_id), at: now, delivered_at: now });
253
+ }
254
+ return { station, agent: member.agent, session_id: member.session_id, seat: member.seat,
255
+ member_instructions: stationMemberInstructions(member.agent, member.seat), master_board, board, cues, dropped_cues: dropped };
229
256
  }
230
257
  if (params?.station !== undefined || (name === "board_write" && params?.owner !== undefined && params.owner !== member.agent))
231
258
  fail("BOARD_FORBIDDEN", "The board is outside the member's scope", { owner: params?.owner });
@@ -256,13 +283,15 @@ export class OperationsCore {
256
283
  done();
257
284
  }
258
285
  }
259
- sendCue(member, params) {
286
+ async sendCue(member, params) {
260
287
  const ref = member.station;
261
288
  if (!Array.isArray(params?.to))
262
289
  fail("CUE_INVALID_TARGET", "to must contain 1-8 targets");
263
290
  const targets = [...new Set(params.to)];
264
291
  if (!targets.length || targets.length > 8 || targets.some((target) => typeof target !== "string" || !target))
265
292
  fail("CUE_INVALID_TARGET", "to must contain 1-8 nonempty targets");
293
+ if (targets.includes("master"))
294
+ fail("CUE_INVALID_TARGET", "Write conclusions on the board; the master reads every board", { reason: "master_not_cue_target" });
266
295
  if (params.message !== undefined && typeof params.message !== "string")
267
296
  fail("CUE_MESSAGE_INVALID", "message must be a string");
268
297
  const raw = params.message;
@@ -272,16 +301,13 @@ export class OperationsCore {
272
301
  if (message && [...message].length > 100)
273
302
  fail("CUE_MESSAGE_INVALID", "message exceeds 100 Unicode characters");
274
303
  const roster = new Set(this.activity.roster(ref));
275
- const metadata = this.supervisor.allMetadata().filter((m) => m.station?.station_id === ref.station_id && m.status !== "closed");
304
+ const metadata = this.supervisor.allMetadata().filter(m => m.station?.station_id === ref.station_id && m.status !== "closed")
305
+ .sort((a, b) => Number(b.station.seat ?? true) - Number(a.station.seat ?? true) || b.updated_at - a.updated_at || a.session_id.localeCompare(b.session_id));
276
306
  const plans = [];
277
307
  const skipped = [];
278
308
  if (targets.every((target) => target === member.session_id))
279
- fail("CUE_SELF", "A cue must reach another session or master");
309
+ fail("CUE_SELF", "A cue must reach another member session");
280
310
  for (const target of targets) {
281
- if (target === "master") {
282
- plans.push({ target, sessions: ["master"], master: true });
283
- continue;
284
- }
285
311
  if (roster.has(target)) {
286
312
  const sessions = metadata.filter((m) => m.agent === target && m.session_id !== member.session_id).map((m) => m.session_id);
287
313
  if (sessions.length)
@@ -298,23 +324,45 @@ export class OperationsCore {
298
324
  plans.push({ target, sessions: [target] });
299
325
  }
300
326
  const board = this.boards.own(ref, member.agent);
301
- const base = { from: { agent: member.agent, session_id: member.session_id, seat: member.seat }, at: Date.now(),
327
+ const base = { hop: this.supervisor.cueHop(member.session_id), from: { agent: member.agent, session_id: member.session_id, seat: member.seat }, at: Date.now(),
302
328
  ...(message ? { message } : {}), board: { owner: member.agent, version: board.version } };
303
- const cue_ids = [];
304
- const delivered_to = [];
305
- for (const plan of plans) {
306
- for (const sessionId of plan.sessions) {
307
- const cue = { cue_id: `cue_${randomUUID().replaceAll("-", "").slice(0, 16)}`, ...base };
308
- if (plan.master)
309
- this.cues.enqueueMaster(ref, cue);
310
- else
311
- this.supervisor.enqueueCue(sessionId, cue);
312
- this.cues.append(ref, cue, { target: plan.target, ...(plan.master ? {} : { session_id: sessionId }) });
313
- cue_ids.push(cue.cue_id);
329
+ const cueId = `cue_${randomUUID().replaceAll("-", "").slice(0, 16)}`;
330
+ const cue = { cue_id: cueId, ...base };
331
+ const ids = new Set(plans.flatMap(plan => plan.sessions));
332
+ const recipients = metadata.filter(meta => ids.has(meta.session_id));
333
+ for (const { session_id } of recipients)
334
+ this.supervisor.enqueueCue(session_id, cue);
335
+ for (const item of skipped)
336
+ this.cues.append(ref, { ...cue, to: { target: item.target }, skipped: item.reason });
337
+ const deliveries = new Map();
338
+ let reserved = 0;
339
+ for (const { session_id } of recipients) {
340
+ const delivery = this.supervisor.triggerCueWake(session_id, reserved < 4);
341
+ deliveries.set(session_id, delivery.result);
342
+ const { wake, error_code } = this.supervisor.pendingCueSummary(this.supervisor.sessions.get(session_id).meta);
343
+ for (const plan of plans) {
344
+ if (!plan.sessions.includes(session_id))
345
+ continue;
346
+ this.cues.append(ref, { ...cue, to: { target: plan.target, session_id }, delivery: "pending",
347
+ ...(wake ? { wake } : {}), ...(error_code ? { error_code } : {}) });
314
348
  }
315
- delivered_to.push({ target: plan.target, sessions: plan.sessions });
349
+ void delivery.result.then(status => {
350
+ if (status.delivery === "pending" && status.wake && status.wake !== "blocked" && (status.wake !== wake || status.error_code !== error_code)) {
351
+ this.cues.event(ref, { cue_ids: [cueId], session_id, at: Date.now(), wake: status.wake,
352
+ ...(status.error_code ? { error_code: status.error_code } : {}) });
353
+ }
354
+ }).catch(error => console.error("Recording cue delivery", session_id, error));
355
+ if (delivery.reserved)
356
+ reserved++;
316
357
  }
317
- return { cue_ids, delivered_to, skipped };
358
+ const delivered_to = await Promise.all(plans.map(async ({ target, sessions }) => ({
359
+ target,
360
+ sessions: await Promise.all(sessions.map(async (session_id) => {
361
+ const status = await deliveries.get(session_id);
362
+ return { session_id, ...status };
363
+ })),
364
+ })));
365
+ return { cue_ids: recipients.length ? [cueId] : [], delivered_to, skipped };
318
366
  }
319
367
  async dispatch(name, p, rec, front, claimRevised) {
320
368
  switch (name) {
@@ -413,11 +461,12 @@ export class OperationsCore {
413
461
  throw e;
414
462
  }
415
463
  }), revisions: this.stations.revisions(ref), members, station_context: stationContext(snapshot, "requested"),
416
- lint: lint(version.station_md), cue_log: this.cues.list(ref) };
464
+ lint: lint(version.station_md), ...(front === "human" ? { cue_log: this.cues.list(ref) } : {}) };
417
465
  }
418
466
  case "station_create": {
419
467
  const result = this.stations.create(p, (allocated) => rec({ ...allocated }));
420
468
  this.boards.ensure(result);
469
+ this.stationChanged(result.station_id);
421
470
  return result;
422
471
  }
423
472
  case "station_update": {
@@ -527,7 +576,10 @@ export class OperationsCore {
527
576
  usageSummary() {
528
577
  const sessions = this.supervisor.allMetadata().map((m) => ({ session_id: m.session_id, agent: m.agent, task_id: m.task_id,
529
578
  ...(m.station ? { station: { station_id: m.station.station_id, name: m.station.name, revision: m.station.revision } } : {}),
530
- status: m.status, usage: this.supervisor.usageFor(m.session_id) }));
579
+ status: m.status, ...this.supervisor.usageFor(m.session_id) }));
580
+ const activityUsage = this.activityGraph.topicUsage();
581
+ if (activityUsage.totalTokens > 0)
582
+ sessions.push({ session_id: "activity-topic", agent: store.JAXON, task_id: "activity-topic", status: "closed", usage: activityUsage });
531
583
  const group = (key, rows = sessions) => {
532
584
  const out = Object.create(null);
533
585
  for (const s of rows) {
@@ -547,7 +599,9 @@ export class OperationsCore {
547
599
  };
548
600
  const stationSessions = sessions.filter((s) => s.station);
549
601
  const stationNames = new Map(stationSessions.map((s) => [s.station.station_id, s.station.name]));
550
- return { sessions, tasks: group((s) => s.task_id ?? "(unassigned)"), agents: group((s) => s.agent),
602
+ const cueSessions = sessions.flatMap(s => s.usage_by_origin ? [{ ...s, usage: s.usage_by_origin.cue }] : []);
603
+ const cueUsage = group(() => "cue", cueSessions).map(({ name: origin, ...stats }) => ({ origin, ...stats }));
604
+ return { sessions, ...(cueUsage.length ? { origins: cueUsage } : {}), tasks: group((s) => s.task_id ?? "(unassigned)"), agents: group((s) => s.agent),
551
605
  stations: group((s) => s.station.station_id, stationSessions).map(({ name, ...stats }) => ({
552
606
  station_id: name, name: stationNames.get(name), ...stats,
553
607
  })) };
@@ -1,5 +1,14 @@
1
1
  import * as fs from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
+ /** Extract only visible assistant text; tool calls, reasoning and attachments are not topic input. */
4
+ export function assistantText(message) {
5
+ if (message?.role !== "assistant")
6
+ return "";
7
+ const content = message.content;
8
+ const text = typeof content === "string" ? content : Array.isArray(content)
9
+ ? content.filter(part => part?.type === "text" && typeof part.text === "string").map(part => part.text).join("\n") : "";
10
+ return text.replace(/<attachment\b[^>]*>[\s\S]*?(?:<\/attachment>|$)/gi, " ");
11
+ }
3
12
  /** imageData=false hashes text plus image count only, so it survives Pi re-encoding images. */
4
13
  export function contentSha256(content, imageData = true) {
5
14
  const parts = typeof content === "string" ? [{ type: "text", text: content }]
@@ -20,6 +29,17 @@ export function readEntries(sessionFile, sessionId = "") {
20
29
  }
21
30
  });
22
31
  }
32
+ /** Origin follows the native branch, not global entry order (forks can diverge). */
33
+ export function cueOriginEntries(entries) {
34
+ const cue = new Set();
35
+ return entries.filter(entry => {
36
+ const intent = entry.type === "custom" && entry.customType === "mcp_turn_intent";
37
+ if (intent ? entry.data?.origin !== "cue" : !cue.has(entry.parentId))
38
+ return false;
39
+ cue.add(entry.id);
40
+ return true;
41
+ });
42
+ }
23
43
  /** A turn is persisted only if a native user message hangs directly under its mcp_turn_intent with matching content. */
24
44
  export function findPersistedUser(entries, turnId) {
25
45
  for (const intent of entries) {
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { contentSha256, findPersistedUser } from "./history-reader.js";
3
+ import { assistantText, contentSha256, findPersistedUser } from "./history-reader.js";
4
4
  /**
5
5
  * Injected by the harness into every Pi process. Reads prompt envelopes from the session inbox
6
6
  * and reports lifecycle events to events.jsonl. The turn state file only moves forward:
@@ -34,6 +34,7 @@ export default function mcpBridge(pi) {
34
34
  const instanceId = process.env.MCP_INSTANCE_ID ?? "inst_unknown";
35
35
  if (!eventFile)
36
36
  return;
37
+ const activityPreview = process.env.MCP_MEMBER_TOKEN ? path.join(path.dirname(eventFile), 'activity-preview.json') : null;
37
38
  let seq = 0;
38
39
  let turnId = null;
39
40
  let lastStreamActivity = 0;
@@ -75,7 +76,8 @@ export default function mcpBridge(pi) {
75
76
  writeState(statePath, { ...prev, state: "dispatched", content_sha256: contentSha256(envelope.content) });
76
77
  turnId = id;
77
78
  lastStreamActivity = 0;
78
- pending = { turnId: id, matchKey: contentSha256(envelope.content, false) };
79
+ pending = { turnId: id, matchKey: contentSha256(envelope.content, false),
80
+ ...(envelope.origin === "cue" ? { origin: "cue" } : {}) };
79
81
  try {
80
82
  pi.sendUserMessage(envelope.content, { expandPromptTemplates: false });
81
83
  emit("dispatched", {}, ctx);
@@ -88,16 +90,31 @@ export default function mcpBridge(pi) {
88
90
  pi.on("session_start", async (_e, ctx) => emit("ready", { pid: process.pid }, ctx));
89
91
  pi.on("ui_prompt_start", async (e, ctx) => emit("ui_prompt_start", { kind: e.kind, title: e.title ?? null }, ctx));
90
92
  pi.on("ui_prompt_end", async (_e, ctx) => emit("ui_prompt_end", {}, ctx));
91
- pi.on("agent_settled", async (e, ctx) => emit("settled", { aborted: Boolean(e.aborted) }, ctx));
93
+ pi.on("agent_settled", async (e, ctx) => {
94
+ if (activityPreview)
95
+ try {
96
+ fs.rmSync(activityPreview, { force: true });
97
+ }
98
+ catch { }
99
+ emit("settled", { aborted: Boolean(e.aborted) }, ctx);
100
+ });
92
101
  pi.on("tool_execution_start", (e, ctx) => emit("tool_execution_start", { tool: e.toolName }, ctx));
93
102
  pi.on("tool_execution_end", (e, ctx) => emit("tool_execution_end", { tool: e.toolName }, ctx));
94
103
  pi.on("message_update", (e, ctx) => {
95
- // Send activity only, not text or thinking deltas, at most once per second.
104
+ // Lifecycle events remain text-free. The optional activity projection has its own bounded preview.
96
105
  const now = Date.now();
97
106
  if (!turnId || e.message.role !== "assistant" || now - lastStreamActivity < 1_000)
98
107
  return;
99
108
  lastStreamActivity = now;
100
109
  emit("stream_activity", {}, ctx);
110
+ if (activityPreview) {
111
+ const text = [...assistantText(e.message).trim()].slice(-600).join("");
112
+ if (text)
113
+ try {
114
+ writeState(activityPreview, { turn_id: turnId, text });
115
+ }
116
+ catch { }
117
+ }
101
118
  });
102
119
  pi.on("message_end", async (e, ctx) => {
103
120
  const m = e.message;
@@ -107,7 +124,7 @@ export default function mcpBridge(pi) {
107
124
  // so the intent becomes its direct parent. The full hash covers what Pi actually persists.
108
125
  if (m.role !== "user" || !pending || contentSha256(m.content, false) !== pending.matchKey)
109
126
  return;
110
- pi.appendEntry("mcp_turn_intent", { turn_id: pending.turnId, instance_id: instanceId, content_sha256: contentSha256(m.content) });
127
+ pi.appendEntry("mcp_turn_intent", { turn_id: pending.turnId, instance_id: instanceId, content_sha256: contentSha256(m.content), ...(pending.origin ? { origin: pending.origin } : {}) });
111
128
  pending = null;
112
129
  emit("user_message_appended", {}, ctx);
113
130
  });
@@ -1,5 +1,5 @@
1
1
  import { statSync } from "node:fs";
2
- import { readEntries } from "../pi-host/history-reader.js";
2
+ import { cueOriginEntries, readEntries } from "../pi-host/history-reader.js";
3
3
  export const usageParts = ["input", "cacheWrite", "cacheRead", "output"];
4
4
  export const emptyAmounts = () => ({ input: 0, cacheWrite: 0, cacheRead: 0, output: 0, total: 0 });
5
5
  const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
@@ -20,7 +20,9 @@ export class AssistantUsageLog {
20
20
  if (this.cached?.identity === identity)
21
21
  return this.cached.entries;
22
22
  const entries = [];
23
- for (const entry of readEntries(file)) {
23
+ const history = readEntries(file);
24
+ const cue = new Set(cueOriginEntries(history));
25
+ for (const entry of history) {
24
26
  const usage = entry.type === "message" && entry.message?.role === "assistant" ? entry.message.usage : null;
25
27
  if (!usage || typeof usage !== "object" || Array.isArray(usage))
26
28
  continue;
@@ -36,7 +38,7 @@ export class AssistantUsageLog {
36
38
  for (const key of usageParts)
37
39
  cost[key] = number(usage.cost?.[key]);
38
40
  cost.total = number(usage.cost?.total);
39
- entries.push({ ts: timestamp(entry.timestamp), tokens, cost });
41
+ entries.push({ ts: timestamp(entry.timestamp), tokens, cost, ...(cue.has(entry) ? { origin: "cue" } : {}) });
40
42
  }
41
43
  this.cached = { identity, entries };
42
44
  return entries;