jaxon-agents 0.2.0 → 0.3.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.
Files changed (57) hide show
  1. package/README.agent.md +203 -168
  2. package/README.md +15 -6
  3. package/README.zh-CN.md +16 -7
  4. package/dist/BUILD_INFO.json +3 -3
  5. package/dist/PACKAGE_MANIFEST.json +56 -41
  6. package/dist/RELEASE_META.json +3 -3
  7. package/dist/agents/directory-store.js +66 -11
  8. package/dist/agents/jaxon-admin.entry.js +5 -3
  9. package/dist/agents/session-switch.js +6 -0
  10. package/dist/api/mcp-tools.js +75 -45
  11. package/dist/console/activity-client.js +84 -60
  12. package/dist/console/activity-topics.js +82 -24
  13. package/dist/console/activity.js +4 -4
  14. package/dist/console/assets.js +219 -257
  15. package/dist/console/chat-library.js +685 -0
  16. package/dist/console/console-info.js +30 -0
  17. package/dist/console/icons.js +14 -0
  18. package/dist/console/pages.js +71 -29
  19. package/dist/console/server.js +8 -4
  20. package/dist/console/station-pages.js +53 -29
  21. package/dist/daemon/host.js +14 -3
  22. package/dist/index.js +87 -8
  23. package/dist/launcher.js +17 -26
  24. package/dist/ops/catalog.js +18 -15
  25. package/dist/ops/core.js +85 -59
  26. package/dist/pi-host/mcp-bridge.entry.js +41 -10
  27. package/dist/platform/index.js +22 -0
  28. package/dist/platform/linux.js +64 -0
  29. package/dist/release/handoff.js +6 -8
  30. package/dist/release/store.js +3 -13
  31. package/dist/sessions/supervisor.js +61 -32
  32. package/dist/stations/activity.js +24 -28
  33. package/dist/stations/boards.js +10 -5
  34. package/dist/stations/cues.js +14 -2
  35. package/dist/stations/member-instructions.js +4 -6
  36. package/dist/stations/station-member.entry.js +28 -11
  37. package/examples/README.md +23 -8
  38. package/examples/agents/README.md +93 -35
  39. package/examples/agents/coder/README.md +37 -0
  40. package/examples/agents/custom-gateway/README.md +42 -0
  41. package/examples/agents/local-qwen/README.md +46 -0
  42. package/examples/agents/planner/README.md +39 -0
  43. package/examples/agents/reviewer/README.md +42 -0
  44. package/examples/mcp-clients/README.md +35 -16
  45. package/examples/stations/README.md +98 -21
  46. package/examples/stations/dev-loop/README.md +40 -0
  47. package/examples/stations/parallel-coders/README.md +40 -0
  48. package/examples/stations/parallel-coders/STATION.md +2 -2
  49. package/examples/stations/research-writer/README.md +39 -0
  50. package/examples/stations/research-writer/STATION.md +1 -1
  51. package/examples/workflows/01-dev-loop-e2e.md +27 -5
  52. package/examples/workflows/02-human-auth-and-roster-switch.md +25 -3
  53. package/examples/workflows/README.md +17 -0
  54. package/package.json +3 -3
  55. package/runtime/provenance.json +3 -3
  56. package/runtime/runtime-lock.json +2 -2
  57. package/runtime/runtime-package.json +1 -1
@@ -29,6 +29,16 @@ export default function mcpBridge(pi) {
29
29
  pi.on("session_start", checkModel);
30
30
  pi.on("before_agent_start", checkModel);
31
31
  }
32
+ // Pi appends a system message whenever a structured prompt section changes. The harness `mcp_servers`
33
+ // section alternates between with/without its one-line server descriptions while codemode
34
+ // connections settle, which otherwise adds an empty system entry on every turn. Canonicalise it to
35
+ // the stable name list: server names and their reach stay, only the advisory summary is dropped.
36
+ pi.on("before_agent_start", (event) => {
37
+ const sections = event?.systemPromptOptions?.sections;
38
+ if (sections && typeof sections.mcp_servers === "string")
39
+ sections.mcp_servers = sections.mcp_servers.split("\n")
40
+ .map((line) => line.startsWith("- ") ? line.replace(/: [\s\S]*$/, "") : line).join("\n");
41
+ });
32
42
  const eventFile = process.env.MCP_EVENT_FILE;
33
43
  const inboxDir = process.env.MCP_INBOX_DIR;
34
44
  const instanceId = process.env.MCP_INSTANCE_ID ?? "inst_unknown";
@@ -38,6 +48,8 @@ export default function mcpBridge(pi) {
38
48
  let seq = 0;
39
49
  let turnId = null;
40
50
  let lastStreamActivity = 0;
51
+ let lastPreviewBucket = -1;
52
+ let lastPreviewWrite = 0;
41
53
  let pending = null;
42
54
  const emit = (type, data = {}, ctx) => {
43
55
  try {
@@ -50,6 +62,26 @@ export default function mcpBridge(pi) {
50
62
  fs.writeFileSync(`${p}.tmp.${process.pid}`, JSON.stringify({ ...rec, instance_id: instanceId, updated_at: Date.now() }));
51
63
  fs.renameSync(`${p}.tmp.${process.pid}`, p);
52
64
  };
65
+ // The preview feeds coarse topic fingerprints: write it at most once a second, but always
66
+ // the moment the streamed length crosses a 400-character bucket (chunks alone must not).
67
+ const writePreview = (message) => {
68
+ if (!activityPreview || !turnId)
69
+ return;
70
+ const raw = assistantText(message).trim();
71
+ if (!raw)
72
+ return;
73
+ const bucket = Math.floor(raw.length / 400);
74
+ const now = Date.now();
75
+ if (bucket === lastPreviewBucket && now - lastPreviewWrite < 1_000)
76
+ return;
77
+ lastPreviewBucket = bucket;
78
+ lastPreviewWrite = now;
79
+ const full = [...raw];
80
+ try {
81
+ writeState(activityPreview, { active_turn_id: turnId, turn_id: turnId, text: full.slice(-600).join(""), chars: raw.length });
82
+ }
83
+ catch { }
84
+ };
53
85
  pi.registerCommand("jaxon-submit", {
54
86
  description: "Internal: submit a prompt envelope from the session inbox",
55
87
  handler: async (args, ctx) => {
@@ -76,6 +108,8 @@ export default function mcpBridge(pi) {
76
108
  writeState(statePath, { ...prev, state: "dispatched", content_sha256: contentSha256(envelope.content) });
77
109
  turnId = id;
78
110
  lastStreamActivity = 0;
111
+ lastPreviewBucket = -1;
112
+ lastPreviewWrite = 0;
79
113
  pending = { turnId: id, matchKey: contentSha256(envelope.content, false),
80
114
  ...(envelope.origin === "cue" ? { origin: "cue" } : {}) };
81
115
  try {
@@ -102,24 +136,21 @@ export default function mcpBridge(pi) {
102
136
  pi.on("tool_execution_end", (e, ctx) => emit("tool_execution_end", { tool: e.toolName }, ctx));
103
137
  pi.on("message_update", (e, ctx) => {
104
138
  // Lifecycle events remain text-free. The optional activity projection has its own bounded preview.
139
+ if (!turnId || e.message.role !== "assistant")
140
+ return;
141
+ writePreview(e.message);
105
142
  const now = Date.now();
106
- if (!turnId || e.message.role !== "assistant" || now - lastStreamActivity < 1_000)
143
+ if (now - lastStreamActivity < 1_000)
107
144
  return;
108
145
  lastStreamActivity = now;
109
146
  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
- }
118
147
  });
119
148
  pi.on("message_end", async (e, ctx) => {
120
149
  const m = e.message;
121
- if (m.role === "assistant")
150
+ if (m.role === "assistant") {
151
+ writePreview(m);
122
152
  return void emit("assistant_message_end", { stop_reason: m.stopReason ?? null, error_message: m.errorMessage ?? null }, ctx);
153
+ }
123
154
  // Only the user message carrying our envelope gets the anchor; Pi appends it right after this handler,
124
155
  // so the intent becomes its direct parent. The full hash covers what Pi actually persists.
125
156
  if (m.role !== "user" || !pending || contentSha256(m.content, false) !== pending.matchKey)
@@ -0,0 +1,22 @@
1
+ import { linux } from "./linux.js";
2
+ function unsupportedError(tag, operation) {
3
+ return new Error(`PLATFORM_UNSUPPORTED: ${tag}${operation === undefined ? "" : ` does not implement ${String(operation)}`}`);
4
+ }
5
+ function unsupported(tag) {
6
+ return new Proxy({ tag }, {
7
+ get(target, key) {
8
+ if (key === "tag")
9
+ return target.tag;
10
+ throw unsupportedError(target.tag, key);
11
+ },
12
+ });
13
+ }
14
+ // X1/X2 provide the native implementations for these placeholders.
15
+ const darwin = unsupported("darwin");
16
+ const win32 = unsupported("win32");
17
+ export const platform = process.platform === "linux" ? linux :
18
+ process.platform === "darwin" ? darwin : process.platform === "win32" ? win32 : unsupported(process.platform);
19
+ export function assertSupportedPlatform() {
20
+ if (platform !== linux)
21
+ throw unsupportedError(platform.tag);
22
+ }
@@ -0,0 +1,64 @@
1
+ import { spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ const afterComm = (stat) => stat.slice(stat.lastIndexOf(")") + 2);
6
+ const pidDirectory = (pid) => `/proc/${pid}`;
7
+ const systemRoot = "/";
8
+ export const linux = {
9
+ tag: "linux",
10
+ systemRoot,
11
+ processIdentity(pid) {
12
+ if (!Number.isSafeInteger(pid) || pid <= 1)
13
+ return null;
14
+ try {
15
+ if (fs.statSync(pidDirectory(pid)).uid !== process.getuid?.())
16
+ return null;
17
+ const fields = afterComm(fs.readFileSync(`${pidDirectory(pid)}/stat`, "utf8")).trim().split(/\s+/);
18
+ return fields[0] !== "Z" && fields[0] !== "X" && /^\d+$/.test(fields[19] ?? "") ? { pid, starttime: fields[19] } : null;
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ },
24
+ launcherStarttime() {
25
+ const starttime = afterComm(fs.readFileSync("/proc/self/stat", "utf8")).split(/\s+/)[19];
26
+ if (!/^\d+$/.test(starttime ?? ""))
27
+ throw new Error("Could not establish launcher release lease");
28
+ return starttime;
29
+ },
30
+ processIds() {
31
+ return fs.readdirSync("/proc").filter(name => /^\d+$/.test(name)).map(Number);
32
+ },
33
+ processEnvironmentHas(pid, entry) {
34
+ return fs.readFileSync(`${pidDirectory(pid)}/environ`, "utf8").split("\0").includes(entry);
35
+ },
36
+ processArgs(pid) {
37
+ return fs.readFileSync(`${pidDirectory(pid)}/cmdline`, "utf8").split("\0");
38
+ },
39
+ dataRoot() {
40
+ return path.resolve(process.env.JAXON_HOME ||
41
+ path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local/share"), "jaxon-agents"));
42
+ },
43
+ *otherUserHomes() {
44
+ for (const line of fs.readFileSync("/etc/passwd", "utf8").split("\n")) {
45
+ const [, , uid, , , home] = line.split(":");
46
+ if (Number(uid) === process.getuid?.() || !home?.startsWith(systemRoot) || home === systemRoot)
47
+ continue;
48
+ yield home;
49
+ }
50
+ },
51
+ createPrivateDirectory(dir) {
52
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
53
+ },
54
+ assertPrivateDirectory(dir) {
55
+ const stat = fs.lstatSync(dir);
56
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
57
+ throw new Error("DATA_ROOT_INVALID: expected a private directory owned by the current user");
58
+ },
59
+ spawnDetached: (command, args, options) => spawn(command, args, { ...options, detached: true }),
60
+ signalProcess: (pid, signal) => { process.kill(pid, signal); },
61
+ signalProcessGroup: (pid, signal) => { process.kill(-pid, signal); },
62
+ releaseId: (version, content, abi) => `${version}-${content.slice(0, 12)}-linux-${process.arch}-abi${abi}`,
63
+ isReleaseId: (id) => typeof id === "string" && id.length < 200 && /^[0-9][0-9A-Za-z.+-]*-linux-[a-z0-9]+-abi[0-9]+$/.test(id),
64
+ };
@@ -1,8 +1,8 @@
1
- import { spawn } from "node:child_process";
2
1
  import { randomUUID } from "node:crypto";
3
2
  import * as fs from "node:fs";
4
3
  import * as path from "node:path";
5
4
  import { acquireRootLock, readCurrent, writeCurrent } from "../launcher.js";
5
+ import { platform } from "../platform/index.js";
6
6
  import { assertRestartable, releaseTier, sameNode } from "./meta.js";
7
7
  import { attachBoot, containsEnv, file, forgetPending, isAlive, markBoot, pending, processIdentity, recordBoot, recordFailure, releaseFor, releasePath, sleep, storeLock, writeAtomic } from "./store.js";
8
8
  const nonceKey = (id) => `JAXON_HANDOFF_ID=${id}`;
@@ -17,7 +17,7 @@ function launch(command, args, env, log) {
17
17
  fs.mkdirSync(path.dirname(log), { recursive: true, mode: 0o700 });
18
18
  const fd = fs.openSync(log, "a", 0o600);
19
19
  try {
20
- const child = spawn(command, args, { env, cwd: "/", detached: true, stdio: ["ignore", fd, fd] });
20
+ const child = platform.spawnDetached(command, args, { env, cwd: platform.systemRoot, stdio: ["ignore", fd, fd] });
21
21
  child.on("error", error => console.error(error.message));
22
22
  child.unref();
23
23
  return child;
@@ -93,7 +93,7 @@ function signal(identity, sig, marker) {
93
93
  if (!isAlive(identity) || (marker && !matchingCandidate(identity, marker)))
94
94
  return;
95
95
  try {
96
- process.kill(identity.pid, sig);
96
+ platform.signalProcess(identity.pid, sig);
97
97
  }
98
98
  catch (error) {
99
99
  if (error.code !== "ESRCH")
@@ -102,10 +102,8 @@ function signal(identity, sig, marker) {
102
102
  }
103
103
  function candidates(p) {
104
104
  const found = [];
105
- for (const name of fs.readdirSync("/proc")) {
106
- if (!/^\d+$/.test(name))
107
- continue;
108
- const who = processIdentity(Number(name));
105
+ for (const pid of platform.processIds()) {
106
+ const who = processIdentity(pid);
109
107
  if (!who || !matchingCandidate(who, p.handoff_id))
110
108
  continue;
111
109
  if (who.pid === p.candidate?.pid && who.starttime !== p.candidate.starttime)
@@ -214,7 +212,7 @@ export async function watchdog(root, id) {
214
212
  return;
215
213
  let args = [];
216
214
  try {
217
- args = fs.readFileSync(`/proc/${latest.from_daemon.pid}/cmdline`, "utf8").split("\0");
215
+ args = platform.processArgs(latest.from_daemon.pid);
218
216
  }
219
217
  catch { /* Cannot prove the old daemon is the recorded retiring process. */ }
220
218
  const entry = path.join(releasePath(root, latest.from), "dist/daemon/main.js");
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { acquireRootLock, missing, readJson, readRelease, safeId, setWritable, unpublishedReleasePrefix } from "../launcher.js";
5
+ import { platform } from "../platform/index.js";
5
6
  export const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
6
7
  export const file = (root, name) => path.join(root, "runtime", name);
7
8
  export function readOptional(name) {
@@ -35,25 +36,14 @@ export async function storeLock(root, action, timeout = 5_000) {
35
36
  }
36
37
  }
37
38
  export function processIdentity(pid) {
38
- if (!Number.isSafeInteger(pid) || pid <= 1)
39
- return null;
40
- try {
41
- if (fs.statSync(`/proc/${pid}`).uid !== process.getuid?.())
42
- return null;
43
- const raw = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
44
- const fields = raw.slice(raw.lastIndexOf(")") + 2).trim().split(/\s+/);
45
- return fields[0] !== "Z" && fields[0] !== "X" && /^\d+$/.test(fields[19] ?? "") ? { pid, starttime: fields[19] } : null;
46
- }
47
- catch {
48
- return null;
49
- }
39
+ return platform.processIdentity(pid);
50
40
  }
51
41
  export function isAlive(identity) {
52
42
  return identity !== undefined && processIdentity(identity.pid)?.starttime === identity.starttime;
53
43
  }
54
44
  export function containsEnv(identity, keyValue) {
55
45
  try {
56
- return isAlive(identity) && fs.readFileSync(`/proc/${identity.pid}/environ`, "utf8").split("\0").includes(keyValue) && isAlive(identity);
46
+ return isAlive(identity) && platform.processEnvironmentHas(identity.pid, keyValue) && isAlive(identity);
57
47
  }
58
48
  catch {
59
49
  return false;
@@ -9,6 +9,7 @@ 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
11
  import { DATA_ROOT, RELEASE } from "../root.js";
12
+ import { platform } from "../platform/index.js";
12
13
  import { hasLocalModelEndpoint } from "../environment/local-model-endpoint.js";
13
14
  import { PiTerminalHost } from "../pi-host/interactive-client.js";
14
15
  import { readFromByteOffset, truncatePartialTail } from "../pi-host/event-tailer.js";
@@ -29,13 +30,25 @@ const MAX_QUEUED_TURNS = 8;
29
30
  const MAX_PENDING_CUES = 20;
30
31
  const CUE_WAKE_COOLDOWN = 60_000;
31
32
  const CUE_WAKE_HOUR = 60 * 60_000;
33
+ // v3.4: a continuous cue chain wakes at most 5 hops; the 5th only queues, never wakes or spawns.
34
+ export const CUE_HOP_LIMIT = 5;
32
35
  const CUE_BLOCK_RETRY = 30_000;
33
36
  const BUSY = ["starting", "running", "stopping", "waiting_input"];
34
37
  const LIVE = [...BUSY, "idle"];
35
38
  const pollBusy = (status) => status === "starting" || status === "running" || status === "stopping";
36
39
  const endReason = (status) => status === "waiting_input" ? "waiting_input" : "turn_end";
37
40
  const noCount = (fn) => fn();
38
- const historyEntries = (entries) => entries.filter((e) => ["message", "compaction", "branch_summary"].includes(e.type));
41
+ // Pi records a system message whenever a structured prompt section changes; those rows carry only
42
+ // `sections`/`toolsAdded` metadata and an empty content string. They are not conversation history,
43
+ // so the console/MCP projection drops them (see PLAN §20.1).
44
+ const emptySystemMessage = (message) => {
45
+ if (message?.role !== "system")
46
+ return false;
47
+ const content = typeof message.content === "string" ? message.content
48
+ : Array.isArray(message.content) ? message.content.filter((part) => part?.type === "text").map((part) => part.text).join("") : "";
49
+ return !String(content ?? "").trim();
50
+ };
51
+ const historyEntries = (entries) => entries.filter((e) => ["message", "compaction", "branch_summary"].includes(e.type) && !emptySystemMessage(e.message));
39
52
  const milliseconds = (time) => typeof time === "number" ? time : typeof time === "string" ? Date.parse(time) : NaN;
40
53
  const tokenHash = (token) => createHash("sha256").update(token).digest();
41
54
  export const allocateSessionId = () => `ses_${randomUUID().replace(/-/g, "").slice(0, 12)}`;
@@ -98,8 +111,8 @@ const readJson = (file) => (fs.existsSync(file) ? JSON.parse(fs.readFileSync(fil
98
111
  /** Kills a recorded PID only if that process really belongs to the given instance (PIDs get reused). */
99
112
  function killOwned(pid, instanceId) {
100
113
  try {
101
- if (fs.readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").includes(`MCP_INSTANCE_ID=${instanceId}`))
102
- process.kill(pid, "SIGKILL");
114
+ if (platform.processEnvironmentHas(pid, `MCP_INSTANCE_ID=${instanceId}`))
115
+ platform.signalProcess(pid, "SIGKILL");
103
116
  }
104
117
  catch { }
105
118
  }
@@ -316,8 +329,15 @@ export class SessionSupervisor {
316
329
  const turnId = await s.run(() => this.deliver(s, content, undefined, rec, "session_start", p, membership?.started, membership?.validate));
317
330
  return { session_id: s.meta.session_id, turn_id: turnId, task_id: s.meta.task_id, workspace: s.meta.workspace,
318
331
  preset_revision: s.meta.preset_revision, status: s.meta.status, leaf_id: s.meta.leaf_id,
319
- ...(s.meta.station ? { station: stationRef(s.meta.station), seat: s.meta.station.seat ?? true,
320
- ...(membership?.renewedFrom ? { renewed_from: membership.renewedFrom } : {}) } : {}) };
332
+ ...(s.meta.station ? { station: stationRef(s.meta.station), same_role_sessions: this.sameRoleSessions(s) } : {}) };
333
+ }
334
+ /** The role's other unclosed sessions, oldest first; siblings are peers, not successors (§16.3). */
335
+ sameRoleSessions(s) {
336
+ const ref = s.meta.station;
337
+ return [...this.sessions.values()]
338
+ .filter((other) => other !== s && other.meta.status !== "closed" && other.meta.agent === s.meta.agent && other.meta.station?.station_id === ref.station_id)
339
+ .sort((a, b) => (a.meta.created_at ?? 0) - (b.meta.created_at ?? 0))
340
+ .map((other) => ({ session_id: other.meta.session_id, status: this.effectiveStatus(other.meta), last_activity_at: other.meta.updated_at ?? null }));
321
341
  }
322
342
  async askJaXon(p, rec) {
323
343
  const content = this.buildContent(p.text, p.attachments, null);
@@ -341,6 +361,8 @@ export class SessionSupervisor {
341
361
  const content = this.buildContent(p.prompt, p.attachments, s.meta.workspace);
342
362
  return s.run(async () => {
343
363
  await this.refresh(s);
364
+ if (s.meta.status === "closed")
365
+ fail("SESSION_CLOSED");
344
366
  const mode = p.delivery ?? "queued";
345
367
  if (BUSY.includes(s.meta.status)) {
346
368
  if (mode === "steer")
@@ -350,8 +372,23 @@ export class SessionSupervisor {
350
372
  return { turn_id: queued.turn_id, status: s.meta.status, leaf_id: s.meta.leaf_id,
351
373
  delivery: "queued", queued: true, queue_position: queued.position };
352
374
  }
353
- const turnId = await this.deliver(s, content, p.resolve_unknown_turn, rec, "session_send", p, started);
354
- return { turn_id: turnId, status: s.meta.status, leaf_id: s.meta.leaf_id, delivery: "started" };
375
+ // A failed session recovers on the same session.jsonl before the new turn (§16.9).
376
+ const recovered = s.meta.status === "failed";
377
+ if (recovered) {
378
+ await this.stopProcess(s);
379
+ s.set({ status: "dormant", error_code: null, last_error: null, last_turn_outcome: null, abort_reason: null });
380
+ }
381
+ try {
382
+ const turnId = await this.deliver(s, content, p.resolve_unknown_turn, rec, "session_send", p, started);
383
+ return { turn_id: turnId, status: s.meta.status, leaf_id: s.meta.leaf_id, delivery: "started", ...(recovered ? { recovered: true } : {}) };
384
+ }
385
+ catch (error) {
386
+ if (!recovered)
387
+ throw error;
388
+ const code = error?.code ?? "START_FAILED";
389
+ s.set({ status: "failed", error_code: code, last_turn_outcome: "not_delivered" });
390
+ return { turn_id: null, status: "failed", leaf_id: s.meta.leaf_id, delivery: "not_delivered", recovered: false, error_code: code };
391
+ }
355
392
  });
356
393
  }
357
394
  replyToSession(p) {
@@ -377,17 +414,20 @@ export class SessionSupervisor {
377
414
  return { accepted, status: s.meta.status };
378
415
  });
379
416
  }
417
+ /** No turn_id: a session is single-threaded, so the live turn is the interrupt target (§16.9.4). */
380
418
  interruptSession(p) {
381
419
  const s = this.get(p.session_id);
382
420
  return s.run(async () => {
383
421
  await this.refresh(s);
384
- if (s.meta.active_turn_id !== p.turn_id)
385
- return { status: s.meta.status, last_turn_outcome: s.meta.last_turn_outcome, abort_reason: s.meta.abort_reason ?? null };
422
+ const turnId = s.meta.active_turn_id;
423
+ if (!turnId || !BUSY.includes(s.meta.status))
424
+ return { interrupted: false, status: s.meta.status };
386
425
  if (s.meta.pending_cues?.length)
387
426
  s.set({ cue_wake_paused: true });
388
427
  this.cancelQueued(s);
389
- await this.requestInterrupt(s, p.turn_id, "interrupt");
390
- return { status: s.meta.status, last_turn_outcome: s.meta.last_turn_outcome, abort_reason: s.meta.abort_reason ?? null };
428
+ await this.requestInterrupt(s, turnId, "interrupt");
429
+ return { interrupted: true, turn_id: turnId, outcome: s.meta.turn_outcomes?.[turnId]?.outcome ?? null,
430
+ status: s.meta.status, abort_reason: s.meta.abort_reason ?? null };
391
431
  });
392
432
  }
393
433
  closeSession(sessionId, onClosed) {
@@ -416,8 +456,7 @@ export class SessionSupervisor {
416
456
  }
417
457
  matching(p) {
418
458
  return [...this.sessions.values()].filter(({ meta: m }) => (!p.agent || m.agent === p.agent) && (!p.status || this.effectiveStatus(m) === p.status) &&
419
- (!p.task_id || m.task_id === p.task_id) && (p.station === undefined || m.station?.station_id === p.station) &&
420
- (p.seat === undefined || (m.station && (m.station.seat ?? true) === p.seat)));
459
+ (!p.task_id || m.task_id === p.task_id) && (p.station === undefined || m.station?.station_id === p.station));
421
460
  }
422
461
  sessionSummary(s) {
423
462
  const m = s.meta;
@@ -426,7 +465,7 @@ export class SessionSupervisor {
426
465
  queue: (m.queue ?? []).map((item, index) => ({ turn_id: item.turn_id, position: index + 1 })),
427
466
  queued_turns: m.queue?.length ?? 0, pending_cues: this.pendingCueSummary(m),
428
467
  last_turn_outcome: m.last_turn_outcome ?? null, abort_reason: m.abort_reason ?? null,
429
- ...(m.station ? { station: { ...stationRef(m.station), seat: m.station.seat ?? true } } : {}),
468
+ ...(m.station ? { station: { ...stationRef(m.station), ...store.sessionSwitchFields(m.agent) } } : {}),
430
469
  turn_progress: this.turnProgress(s) };
431
470
  }
432
471
  subscribe(sessions, notify) {
@@ -435,21 +474,12 @@ export class SessionSupervisor {
435
474
  return () => { for (const s of sessions)
436
475
  s.listeners.delete(notify); };
437
476
  }
477
+ /** A pure collective snapshot: it always returns immediately; waiting lives in readSession. */
438
478
  async listSessions(p, options = {}) {
439
479
  const counted = options.counted ?? noCount;
440
- const start = performance.now();
441
- const initial = counted(() => this.matching(p).filter((s) => pollBusy(this.effectiveStatus(s.meta))));
442
480
  const created = (m) => milliseconds(m.created_at) || 0;
443
481
  const updated = (m) => milliseconds(m.updated_at) || created(m);
444
- const summary = () => ({ sessions: this.matching(p).sort(({ meta: a }, { meta: b }) => updated(b) - updated(a) || created(b) - created(a) || a.session_id.localeCompare(b.session_id, "en")).map((s) => this.sessionSummary(s)) });
445
- if (p.wait_ms === undefined)
446
- return counted(summary);
447
- let return_reason = initial.length ? "timeout" : "not_busy";
448
- const left = () => initial.filter((s) => !pollBusy(this.effectiveStatus(s.meta))).map(({ meta: m }) => ({ session_id: m.session_id, status: this.effectiveStatus(m) }));
449
- const changed = initial.length && p.wait_ms > 0 ? await waitForChange(p.wait_ms, (notify) => this.subscribe(initial, notify), () => counted(() => { const items = left(); return items.length ? items : undefined; }), () => counted(() => initial.map((s) => ({ session_id: s.meta.session_id, status: s.meta.status, turn_progress: this.turnProgress(s) }))), options) : undefined;
450
- if (changed)
451
- return_reason = changed.some((m) => m.status === "waiting_input") ? "waiting_input" : "turn_end";
452
- return counted(() => ({ ...summary(), return_reason, waited_ms: Math.round(performance.now() - start), changed: changed ?? [] }));
482
+ return counted(() => ({ sessions: this.matching(p).sort(({ meta: a }, { meta: b }) => updated(b) - updated(a) || created(b) - created(a) || a.session_id.localeCompare(b.session_id, "en")).map((s) => this.sessionSummary(s)) }));
453
483
  }
454
484
  turnProgress(s, entries) {
455
485
  if (!pollBusy(this.effectiveStatus(s.meta)) &&
@@ -610,8 +640,7 @@ export class SessionSupervisor {
610
640
  !["starting", "running", "waiting_input"].includes(m.status) ||
611
641
  !timingSafeEqual(tokenHash(credentials.member_token), Buffer.from(m.station.member_token_sha256, "hex")))
612
642
  return fail("MEMBER_NOT_ACTIVE", "Member identity is invalid or not active", { session_id: credentials.session_id });
613
- return { station: stationRef(m.station), session_id: m.session_id, agent: m.agent,
614
- seat: m.station.seat ?? true };
643
+ return { station: stationRef(m.station), session_id: m.session_id, agent: m.agent };
615
644
  }
616
645
  /** Background: consume events without waiting for callers, then put long-idle sessions to sleep. */
617
646
  tick() {
@@ -656,7 +685,7 @@ export class SessionSupervisor {
656
685
  status: "dormant", instance_id: null, active_turn_id: null, last_turn_outcome: null, leaf_id: null,
657
686
  event_offset: 0, event_seq: 0, delivery: null, pending_request: null, pids: [], turn_seq: 0, created_at: Date.now(),
658
687
  queue: [], turn_outcomes: {}, abort_reason: null, pending_cues: [], dropped_cues: 0,
659
- ...(membership ? { station: { ...membership.ref, seat: membership.seat } } : {}),
688
+ ...(membership ? { station: { ...membership.ref } } : {}),
660
689
  }, this.onSave);
661
690
  s.save();
662
691
  this.sessions.set(id, s);
@@ -859,7 +888,7 @@ export class SessionSupervisor {
859
888
  return { wake: "not_runnable" };
860
889
  if (!this.cueConfigEnabled())
861
890
  return {};
862
- if (!cues.some(cue => (cue.hop ?? 0) < 3))
891
+ if (!cues.some(cue => (cue.hop ?? 0) < CUE_HOP_LIMIT))
863
892
  return { wake: "hop_limit" };
864
893
  if (BUSY.includes(meta.status) || meta.queue?.length || meta.cue_wake_paused)
865
894
  return { wake: "scheduled" };
@@ -999,14 +1028,14 @@ export class SessionSupervisor {
999
1028
  }
1000
1029
  this.gateSnapshot(s, "session_send", params);
1001
1030
  const cues = s.meta.pending_cues ?? [];
1002
- if (!cues.some(cue => (cue.hop ?? 0) < 3)) {
1031
+ if (!cues.some(cue => (cue.hop ?? 0) < CUE_HOP_LIMIT)) {
1003
1032
  if (s.meta.status === "starting")
1004
1033
  s.set({ status: "idle" });
1005
1034
  return;
1006
1035
  }
1007
1036
  const content = cues.map(cue => `[cue] 来自 ${cue.from.agent}(${cue.from.session_id},看板 v${cue.board.version}):${cue.message || "(无文字)"}`)
1008
1037
  .concat("请查看发送者的看板并与之对齐;方向性问题以 master 看板为准。").join("\n");
1009
- const hop = Math.max(...cues.filter(cue => (cue.hop ?? 0) < 3).map(cue => cue.hop ?? 0), 0);
1038
+ const hop = Math.max(...cues.filter(cue => (cue.hop ?? 0) < CUE_HOP_LIMIT).map(cue => cue.hop ?? 0), 0);
1010
1039
  turnId = `turn_${++s.meta.turn_seq}`;
1011
1040
  writeJson(s.file(path.join("inbox", `${turnId}.json`)), { turn_id: turnId, content, origin: "cue" });
1012
1041
  writeJson(s.turnState(turnId), { state: "staged", updated_at: Date.now(), origin: "cue", hop, cues, dropped: s.meta.dropped_cues ?? 0 });
@@ -1178,7 +1207,7 @@ export class SessionSupervisor {
1178
1207
  s.lastScreen = undefined;
1179
1208
  const effective = member ? this.beforeMemberLaunch?.(s.meta.station) : undefined;
1180
1209
  const station = member ? { ...(firstLaunch && effective ? effective : stationRef(s.meta.station)),
1181
- seat: s.meta.station.seat ?? true, member_token_sha256: tokenHash(member.token).toString("hex") } : undefined;
1210
+ member_token_sha256: tokenHash(member.token).toString("hex") } : undefined;
1182
1211
  s.set({ status: "starting", instance_id: instanceId, turn_started_at: Date.now(), turn_event_at: null,
1183
1212
  ...(station ? { station } : {}), ...(RELEASE ? { last_runtime_release: RELEASE.id } : {}), event_offset: fs.existsSync(spec.eventFile) ? fs.statSync(spec.eventFile).size : 0, error_code: null });
1184
1213
  started?.();
@@ -2,11 +2,21 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { STATE } from "../agents/directory-store.js";
5
+ import { DATA_ROOT } from "../root.js";
5
6
  import { fail } from "../ops/errors.js";
6
7
  import { atomic, json } from "./station-store.js";
7
8
  export const stationRef = ({ station_id, name, revision }) => ({ station_id, name, revision });
8
- export const MAX_INDEPENDENT = 4;
9
- export const isSeatSession = (member) => member.station?.seat ?? true;
9
+ const DEFAULT_MAX_SESSIONS_PER_ROLE = 5;
10
+ /** Ceiling on unclosed sessions per (Station, role); PLAN-MCP-SESSIONS v4.0 §16.2. Configurable via config.json. */
11
+ function maxSessionsPerRole() {
12
+ try {
13
+ const value = JSON.parse(fs.readFileSync(path.join(DATA_ROOT, 'config.json'), 'utf8'))?.sessions?.max_per_role;
14
+ if (Number.isInteger(value) && value >= 1)
15
+ return value;
16
+ }
17
+ catch { /* no config */ }
18
+ return DEFAULT_MAX_SESSIONS_PER_ROLE;
19
+ }
10
20
  const busyStates = new Set(['starting', 'running', 'stopping', 'waiting_input']);
11
21
  const activeStates = new Set([...busyStates, 'idle']);
12
22
  export const stationContext = (s, reason) => ({ ...stationRef(s), reason, description: s.description });
@@ -36,7 +46,6 @@ export class StationActivity {
36
46
  members(id) { return this.metadata().filter((m) => m.station?.station_id === id && m.status !== 'closed'); }
37
47
  activeMembers(id) { return this.members(id).filter((m) => activeStates.has(m.status)); }
38
48
  admitting(id) { return [...this.admissions].filter((m) => m.station?.station_id === id); }
39
- renewing(id) { return this.admitting(id).some((member) => member.renewal); }
40
49
  inUse(id) {
41
50
  const members = this.members(id);
42
51
  const seen = new Set(members.map((m) => m.session_id));
@@ -54,31 +63,19 @@ export class StationActivity {
54
63
  fail('AGENT_NOT_IN_STATION', agent, { station_id: ref.station_id, agent, agents,
55
64
  ...(options.reportPending && pending && (pending.join.includes(agent) || pending.leave.includes(agent)) ? { station_pending: pending } : {}) });
56
65
  const existing = this.inUse(ref.station_id).filter((m) => m.agent === agent);
57
- const currentSeat = existing.find(isSeatSession);
58
- if (options.seat === 'none') {
59
- const independent = existing.filter((m) => !isSeatSession(m));
60
- if (independent.length >= MAX_INDEPENDENT)
61
- fail('STATION_SESSION_LIMIT', `${agent} already has ${MAX_INDEPENDENT} independent sessions`, {
62
- limit: MAX_INDEPENDENT, sessions: independent.map((m) => m.session_id),
63
- });
64
- }
65
- else if (currentSeat && options.seat === 'claim') {
66
- fail('STATION_AGENT_TAKEN', agent, { station_id: ref.station_id, agent, session_id: currentSeat.session_id, status: currentSeat.status,
67
- options: ['session_send', 'seat:renew', 'seat:none'],
68
- advice: 'Use session_send to continue the seat, seat:renew to replace stale context, or seat:none for an independent session.' });
69
- }
70
- else if (currentSeat && options.seat === 'renew' && !['idle', 'dormant', 'failed'].includes(currentSeat.status)) {
71
- fail('STATION_SEAT_BUSY', 'The current seat session is busy', { session_id: currentSeat.session_id, status: currentSeat.status });
72
- }
73
- const seat = options.seat !== 'none';
74
- const admission = { session_id, agent, status: 'pending', renewal: options.seat === 'renew' && Boolean(currentSeat), station: { ...ref, seat } };
66
+ const limit = maxSessionsPerRole();
67
+ if (existing.length >= limit)
68
+ fail('STATION_SESSION_LIMIT', `${agent} already has ${existing.length} open sessions`, {
69
+ limit, sessions: existing.map((m) => ({ session_id: m.session_id, status: m.status })),
70
+ });
71
+ const admission = { session_id, agent, status: 'pending', station: ref };
75
72
  this.admissions.add(admission);
76
73
  this.onChange?.(ref.station_id);
77
- return { release: () => this.release(ref, admission), renewed: options.seat === 'renew' ? currentSeat : undefined };
74
+ return { release: () => this.release(ref, admission) };
78
75
  }
79
76
  admit(ref, agent, session_id, start) {
80
77
  if (start)
81
- return this.admitStart(ref, agent, session_id, { ...start, seat: 'claim' }).release;
78
+ return this.admitStart(ref, agent, session_id, start).release;
82
79
  const admission = { session_id, agent, status: 'pending', station: ref };
83
80
  this.admissions.add(admission);
84
81
  this.onChange?.(ref.station_id);
@@ -165,7 +162,7 @@ export class StationActivity {
165
162
  return stationRef(active.snapshot);
166
163
  }
167
164
  statusChanged(ref, before, after) {
168
- if (activeStates.has(before) && !activeStates.has(after) && !this.activeMembers(ref.station_id).length && !this.renewing(ref.station_id)) {
165
+ if (activeStates.has(before) && !activeStates.has(after) && !this.activeMembers(ref.station_id).length) {
169
166
  this.snapshots.delete(ref.station_id);
170
167
  this.delivery.delete(ref.station_id);
171
168
  this.discard(this.activeDir(ref.station_id), true);
@@ -192,7 +189,7 @@ export class StationActivity {
192
189
  this.onChange?.(ref.station_id);
193
190
  }
194
191
  frozenState(ref) {
195
- return this.activeMembers(ref.station_id).length || this.renewing(ref.station_id) ? this.activeSnapshot(ref) : undefined;
192
+ return this.activeMembers(ref.station_id).length ? this.activeSnapshot(ref) : undefined;
196
193
  }
197
194
  frozen(ref) { return this.frozenState(ref)?.snapshot; }
198
195
  effective(ref) { return this.frozen(ref) ?? this.store.snapshot(this.currentVersion(ref)); }
@@ -206,9 +203,8 @@ export class StationActivity {
206
203
  if (!join.length && !leave.length && !rules_changed)
207
204
  return;
208
205
  const blockers = new Map();
209
- for (const { session_id, agent, status, renewal } of this.admitting(s.station_id))
210
- if (!renewal || join.length > 0 || leave.length > 0)
211
- blockers.set(session_id, { session_id, agent, status, reason: 'busy_turn' });
206
+ for (const { session_id, agent, status } of this.admitting(s.station_id))
207
+ blockers.set(session_id, { session_id, agent, status, reason: 'busy_turn' });
212
208
  for (const { session_id, agent, status } of this.members(s.station_id)) {
213
209
  if (busyStates.has(status))
214
210
  blockers.set(session_id, { session_id, agent, status, reason: 'busy_turn' });
@@ -3,7 +3,7 @@ import * as path from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { fail } from "../ops/errors.js";
5
5
  import { atomic, json, TEXT_LIMIT } from "./station-store.js";
6
- import { isSeatSession } from "./activity.js";
6
+ const BOARD_SOFT_LIMIT = 8 * 1024;
7
7
  const hash = (text) => createHash('sha256').update(text).digest('hex');
8
8
  /** All mutations are synchronous; no awaited work can interleave the version check and commit. */
9
9
  export class BoardStore {
@@ -85,10 +85,9 @@ export class BoardStore {
85
85
  return this.knownOwners(ref, roster).map((owner) => {
86
86
  const board = this.stored(ref, owner);
87
87
  const sessions = active.get(owner) ?? [];
88
- const ownerSession = sessions.find(isSeatSession) ?? sessions[0];
89
88
  return { ...board, bytes: Buffer.byteLength(board.content), in_roster: roster.has(owner), owner_active: sessions.length > 0,
90
- active_sessions: sessions.map((member) => ({ session_id: member.session_id, seat: isSeatSession(member) })),
91
- ...(ownerSession ? { owner_session_id: ownerSession.session_id } : {}) };
89
+ active_sessions: sessions.map((member) => ({ session_id: member.session_id })),
90
+ ...(sessions[0] ? { owner_session_id: sessions[0].session_id } : {}) };
92
91
  });
93
92
  }
94
93
  replace(ref, owner, content, writer, expected, record) {
@@ -99,7 +98,13 @@ export class BoardStore {
99
98
  if (expected !== undefined && expected !== current.version)
100
99
  fail('BOARD_VERSION_CONFLICT', owner, { owner, current_version: current.version, current_content: current.content });
101
100
  const version = current.version + 1;
102
- const result = { owner, version };
101
+ const warning = bytes > BOARD_SOFT_LIMIT ? {
102
+ code: 'BOARD_SOFT_LIMIT',
103
+ bytes,
104
+ soft_limit_bytes: BOARD_SOFT_LIMIT,
105
+ message: 'Board saved. It exceeds the 8 KiB recommended size; keep conclusions and links, and move lengthy detail elsewhere.',
106
+ } : undefined;
107
+ const result = { owner, version, ...(warning ? { warning } : {}) };
103
108
  record?.(result);
104
109
  const file = this.file(ref, owner);
105
110
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });