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
package/dist/index.js CHANGED
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
2
5
  import { callDaemon, ensureDaemonConnection } from "./daemon/client.js";
3
- import { builtVersion, DATA_ROOT, PACKAGE, PREFLIGHT, RELEASE } from "./root.js";
6
+ import { builtVersion, DATA_ROOT, PACKAGE, PREFLIGHT, RELEASE, STATE } from "./root.js";
7
+ import { consoleInfoFrom, consoleUrl } from "./console/console-info.js";
4
8
  import { readCurrent } from "./launcher.js";
5
9
  import { acquireLease, storeLock } from "./release/store.js";
6
10
  import { upgradeCli } from "./release/cli.js";
@@ -162,12 +166,87 @@ async function runRelay() {
162
166
  process.stdin.resume();
163
167
  await connect(false);
164
168
  }
165
- async function runConsole() {
166
- const result = await callDaemon("agent", "service_status", {});
167
- const url = result?.console_url;
168
- if (typeof url !== "string")
169
+ const inSshSession = () => Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY);
170
+ /** config.console.open_browser, overridden per run by --open/--no-open and JAXON_OPEN_BROWSER. */
171
+ function openPreference(args) {
172
+ if (args.includes("--no-open"))
173
+ return "never";
174
+ if (args.includes("--open"))
175
+ return "always";
176
+ const env = String(process.env.JAXON_OPEN_BROWSER ?? "").toLowerCase();
177
+ if (["0", "false", "no"].includes(env))
178
+ return "never";
179
+ if (["1", "true", "yes"].includes(env))
180
+ return "always";
181
+ try {
182
+ const value = JSON.parse(fs.readFileSync(path.join(DATA_ROOT, "config.json"), "utf8"))?.console?.open_browser;
183
+ if (value === "always" || value === "first_run" || value === "never")
184
+ return value;
185
+ }
186
+ catch { }
187
+ return "never";
188
+ }
189
+ function printConsoleGuide(info, connectionsConfigured) {
190
+ const tty = Boolean(process.stdout.isTTY);
191
+ const lines = [`JaXon console: ${info.console_url}`];
192
+ const rows = [
193
+ ["Overview", consoleUrl(info, "/"), ""],
194
+ ["Stations", consoleUrl(info, "/stations"), ""],
195
+ ["Connections", consoleUrl(info, "/connections"), connectionsConfigured ? "" : "configure model credentials here first"],
196
+ ];
197
+ for (const [label, url, note] of rows)
198
+ lines.push(` ${label.padEnd(13)} ${url}${note ? ` ← ${note}` : ""}`);
199
+ if (inSshSession()) {
200
+ lines.push("");
201
+ lines.push(`SSH session detected. Forward the console port, then open ${info.console_url}`);
202
+ lines.push(` ssh -L ${info.port}:127.0.0.1:${info.port} <user>@<host>`);
203
+ }
204
+ lines.push("");
205
+ lines.push("Open it in your browser. Run `jaxon-agents console` any time to see this again.");
206
+ if (!tty) {
207
+ process.stdout.write(lines.join("\n") + "\n");
208
+ return;
209
+ }
210
+ const color = (code, text) => `\u001b[${code}m${text}\u001b[0m`;
211
+ const width = Math.min(100, Math.max(...lines.map(line => [...line].length)) + 2);
212
+ const border = color("1;36", "─".repeat(width));
213
+ process.stdout.write([border, color("1", lines[0]), ...lines.slice(1, -1), color("2", lines[lines.length - 1]), border].join("\n") + "\n");
214
+ }
215
+ async function maybeOpenConsole(info, args) {
216
+ const preference = openPreference(args);
217
+ if (preference === "never")
218
+ return;
219
+ if (!process.stdout.isTTY || inSshSession() || process.env.CI || !(process.env.DISPLAY || process.env.WAYLAND_DISPLAY))
220
+ return;
221
+ if (preference === "first_run") {
222
+ const marker = path.join(STATE, "console-opened");
223
+ if (fs.existsSync(marker))
224
+ return;
225
+ try {
226
+ fs.mkdirSync(STATE, { recursive: true });
227
+ fs.writeFileSync(marker, new Date().toISOString() + "\n", { mode: 0o600 });
228
+ }
229
+ catch { }
230
+ }
231
+ try {
232
+ const child = spawn("xdg-open", [info.console_url], { detached: true, stdio: "ignore" });
233
+ child.on("error", () => { });
234
+ child.unref();
235
+ }
236
+ catch { /* browser launch is best effort */ }
237
+ }
238
+ async function runConsole(args) {
239
+ const json = args.includes("--json");
240
+ const result = await callDaemon("agent", "service_status", json ? {} : { include_connections_configured: true });
241
+ if (typeof result?.console_url !== "string")
169
242
  throw new Error("service_status did not return a console URL");
170
- process.stdout.write(url + "\n");
243
+ const info = consoleInfoFrom(result);
244
+ if (json) {
245
+ process.stdout.write(JSON.stringify(info, null, 2) + "\n");
246
+ return;
247
+ }
248
+ printConsoleGuide(info, result.connections_configured !== false);
249
+ await maybeOpenConsole(info, args);
171
250
  }
172
251
  async function runStatus() {
173
252
  const result = await callDaemon("agent", "service_status", {});
@@ -216,8 +295,8 @@ try {
216
295
  process.exitCode = 2;
217
296
  }
218
297
  }
219
- else if (command === "console" && process.argv.length === 3)
220
- await runConsole();
298
+ else if (command === "console" && process.argv.slice(3).every((arg) => ["--json", "--open", "--no-open"].includes(arg)))
299
+ await runConsole(process.argv.slice(3));
221
300
  else if (command === "status" && process.argv.length === 3)
222
301
  await runStatus();
223
302
  else {
package/dist/launcher.js CHANGED
@@ -6,6 +6,7 @@ import * as net from "node:net";
6
6
  import * as os from "node:os";
7
7
  import * as path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { assertSupportedPlatform, platform } from "./platform/index.js";
9
10
  const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
10
11
  const hash = (content) => createHash("sha256").update(content).digest("hex");
11
12
  export const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
@@ -63,11 +64,8 @@ export function compareVersions(a, b) {
63
64
  }
64
65
  return xp.length - yp.length;
65
66
  }
66
- function releaseId(version, content, abi) {
67
- return `${version}-${content.slice(0, 12)}-linux-${process.arch}-abi${abi}`;
68
- }
69
67
  export function safeId(id) {
70
- return typeof id === "string" && id.length < 200 && /^[0-9][0-9A-Za-z.+-]*-linux-[a-z0-9]+-abi[0-9]+$/.test(id);
68
+ return platform.isReleaseId(id);
71
69
  }
72
70
  export function readRelease(root, dataRoot) {
73
71
  if (fs.realpathSync(root) !== root || fs.realpathSync(path.join(root, ".jaxon-release.json")) !== path.join(root, ".jaxon-release.json"))
@@ -75,7 +73,7 @@ export function readRelease(root, dataRoot) {
75
73
  const m = readJson(path.join(root, ".jaxon-release.json"));
76
74
  if (m?.data_root !== dataRoot || !safeId(m.id) || root !== path.join(dataRoot, "runtime", "releases", m.id) ||
77
75
  typeof m.version !== "string" || !semverPattern.test(m.version) || typeof m.content_hash !== "string" || !/^[a-f0-9]{64}$/.test(m.content_hash) ||
78
- typeof m.node?.abi !== "string" || !/^\d+$/.test(m.node.abi) || m.id !== releaseId(m.version, m.content_hash, m.node.abi) ||
76
+ typeof m.node?.abi !== "string" || !/^\d+$/.test(m.node.abi) || m.id !== platform.releaseId(m.version, m.content_hash, m.node.abi) ||
79
77
  typeof m.node.exec_path !== "string" || !path.isAbsolute(m.node.exec_path) ||
80
78
  !["dev", "ino", "mtime", "size"].every((key) => typeof m.node.stat?.[key] === "string") || !runtimeValid(m.runtime))
81
79
  throw new Error("Invalid release marker");
@@ -84,6 +82,7 @@ export function readRelease(root, dataRoot) {
84
82
  return m;
85
83
  }
86
84
  export function codeContext(moduleUrl) {
85
+ assertSupportedPlatform();
87
86
  let codeRoot = path.dirname(fs.realpathSync(fileURLToPath(moduleUrl)));
88
87
  while (!fs.existsSync(path.join(codeRoot, "package.json"))) {
89
88
  const parent = path.dirname(codeRoot);
@@ -116,24 +115,20 @@ function projectPath(requested) {
116
115
  const inside = (parent, dir) => dir === parent || dir.startsWith(parent + path.sep);
117
116
  function privateDirectory(dir, create) {
118
117
  if (create)
119
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
120
- if (!pathExists(dir))
121
- return;
122
- const stat = fs.lstatSync(dir);
123
- if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0)
124
- throw new Error("DATA_ROOT_INVALID: expected a private directory owned by the current user");
118
+ platform.createPrivateDirectory(dir);
119
+ if (pathExists(dir))
120
+ platform.assertPrivateDirectory(dir);
125
121
  }
126
122
  function validateDataRoot(dir, packageName, create) {
127
- if (dir === "/" || dir.split(path.sep).includes("node_modules"))
123
+ if (dir === platform.systemRoot || dir.split(path.sep).includes("node_modules"))
128
124
  throw new Error("DATA_ROOT_INVALID: inside an installation");
129
- for (let ancestor = dir; ancestor !== "/"; ancestor = path.dirname(ancestor)) {
125
+ for (let ancestor = dir; ancestor !== platform.systemRoot; ancestor = path.dirname(ancestor)) {
130
126
  if (pathExists(path.join(ancestor, ".git")) && pathExists(path.join(ancestor, "package.json")) &&
131
127
  readJson(path.join(ancestor, "package.json")).name === packageName)
132
128
  throw new Error("DATA_ROOT_INVALID: inside a source checkout");
133
129
  }
134
- for (const line of fs.readFileSync("/etc/passwd", "utf8").split("\n")) {
135
- const [, , uid, , , home] = line.split(":");
136
- if (Number(uid) === process.getuid?.() || !home?.startsWith("/") || home === "/" || !pathExists(home))
130
+ for (const home of platform.otherUserHomes()) {
131
+ if (!pathExists(home))
137
132
  continue;
138
133
  if (inside(fs.realpathSync(home), dir))
139
134
  throw new Error("DATA_ROOT_INVALID: inside another user's home");
@@ -299,13 +294,13 @@ export async function copyAndVerify(source, dest, packageName) {
299
294
  }
300
295
  function runChild(command, args, cwd, env, log, timeout) {
301
296
  return new Promise((resolve, reject) => {
302
- const child = spawn(command, args, { cwd, env, detached: true, stdio: ["ignore", log, log] });
297
+ const child = platform.spawnDetached(command, args, { cwd, env, stdio: ["ignore", log, log] });
303
298
  let timedOut = false;
304
299
  const timer = setTimeout(() => {
305
300
  timedOut = true;
306
301
  if (child.pid) {
307
302
  try {
308
- process.kill(-child.pid, "SIGKILL");
303
+ platform.signalProcessGroup(child.pid, "SIGKILL");
309
304
  }
310
305
  catch { /* child already exited */ }
311
306
  }
@@ -361,7 +356,7 @@ export async function installSelf(root, source, packageName, options = {}) {
361
356
  throw new Error("STATE_SCHEMA_UNSUPPORTED");
362
357
  const stat = nodeStat(executable);
363
358
  const { abi, version: nodeVersion } = probeNodeIdentity(executable);
364
- const id = releaseId(meta.version, meta.content_hash, abi);
359
+ const id = platform.releaseId(meta.version, meta.content_hash, abi);
365
360
  const final = path.join(runtime, "releases", id);
366
361
  if (pathExists(final)) {
367
362
  const existing = readRelease(final, root);
@@ -520,7 +515,7 @@ async function launch() {
520
515
  return;
521
516
  }
522
517
  const [major, minor] = process.versions.node.split(".").map(Number);
523
- if (process.platform !== "linux" || major < 22 || (major === 22 && minor < 19))
518
+ if (major < 22 || (major === 22 && minor < 19))
524
519
  throw new Error("Linux and Node.js 22.19.0 or newer are required");
525
520
  const args = process.argv.slice(2);
526
521
  if (args[0] === "upgrade") {
@@ -531,8 +526,7 @@ async function launch() {
531
526
  if (args.includes("--repair-node") && !args.includes("--accept-no-rollback"))
532
527
  throw new Error("ROLLBACK_UNAVAILABLE_REQUIRES_CONSENT");
533
528
  }
534
- const dataRoot = projectPath(path.resolve(process.env.JAXON_HOME ||
535
- path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local/share"), "jaxon-agents")));
529
+ const dataRoot = projectPath(platform.dataRoot());
536
530
  const version = (args[0] === "--version" || args[0] === "version") && (args.length === 1 || args.length === 2 && args[1] === "--json");
537
531
  validateDataRoot(dataRoot, context.pkg.name, false);
538
532
  const current = readCurrent(dataRoot);
@@ -560,10 +554,7 @@ async function launch() {
560
554
  if (!refreshed)
561
555
  throw new Error("RUNTIME_STORE_CORRUPT");
562
556
  selected = refreshed;
563
- const proc = fs.readFileSync("/proc/self/stat", "utf8");
564
- const starttime = proc.slice(proc.lastIndexOf(")") + 2).split(/\s+/)[19];
565
- if (!/^\d+$/.test(starttime ?? ""))
566
- throw new Error("Could not establish launcher release lease");
557
+ const starttime = platform.launcherStarttime();
567
558
  privateDirectory(leaseDir, true);
568
559
  const name = path.join(leaseDir, `${process.pid}-${starttime}.json`);
569
560
  fs.writeFileSync(name, JSON.stringify({ release: selected.marker.id, pid: process.pid, starttime }), { flag: "wx", mode: 0o600 });
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { sessionSwitchValues } from "../agents/session-switch.js";
2
3
  const requestId = z.string().optional();
3
4
  const wait = z.number().min(0).optional();
4
5
  const station = z.string();
@@ -13,17 +14,18 @@ const attachments = z.array(z.union([
13
14
  const patch = z.record(z.string(), z.string().nullable()).optional();
14
15
  const resolveUnknown = z.object({ turn_id: z.string(), action: z.enum(["retry", "abandon"]) }).optional();
15
16
  const tools = z.array(z.string()).optional();
17
+ const session_switch = z.enum(sessionSwitchValues).nullable().optional().describe("How much context redundancy this role tolerates, from strictly_eager (lowest) to conservative (highest); null clears it to the default Balanced. It belongs to the role and applies to all its sessions. Not applicable to JaXon.");
16
18
  const defs = [
17
- { name: "session_start", description: "Start a ready preset. With a Station, omit seat or use claim for its continuing seat, none for clean parallel work, or renew to replace stale seat context while keeping its board.", write: true, schema: {
18
- agent: z.string(), workspace: z.string(), prompt: z.string(), attachments, task_id: z.string().optional(), station: station.optional(),
19
- seat: z.enum(["claim", "renew", "none"]).optional(), client_request_id: requestId,
19
+ { name: "session_start", description: "Start a ready preset as a new member session. Starting a role that already has sessions creates another equal session and returns the others in same_role_sessions; to continue an existing session use session_send.", write: true, schema: {
20
+ agent: z.string(), workspace: z.string(), prompt: z.string(), attachments, task_id: z.string().optional(), station: station.optional(), client_request_id: requestId,
20
21
  } },
21
- { name: "session_read", description: "Read status, final outcome, incremental history, pending prompt, screen and usage.", write: false, schema: {
22
- session_id: z.string(), after: z.string().optional(), wait_ms: wait, wait_until: z.enum(["turn_end", "change"]).optional(),
22
+ { name: "session_read", description: "Read status, final outcome, incremental history, pending prompt, screen and usage. With wait_ms it waits for the turn to end, the session to block on input, or the session to fail or close.", write: false, schema: {
23
+ session_id: z.string(), after: z.string().optional(), wait_ms: wait,
24
+ wait_until: z.enum(["turn_end", "change"]).optional().describe("turn_end returns when the turn ends or the session blocks on input; change also returns when new history arrives."),
23
25
  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."),
26
+ include_thinking: z.boolean().optional().describe("Provides thinking when true (default false). Thinking greatly enlarges the context, so prefer actions, boards and results."),
25
27
  } },
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: {
28
+ { name: "session_send", description: "Continue a session; it adapts to the session state. idle/dormant start a new turn, busy turns queue by default, delivery=steer interrupts the current turn and runs this instruction next, and a failed session recovers first (recovered: true).", write: true, schema: {
27
29
  session_id: z.string(), prompt: z.string(), attachments, delivery: z.enum(["queued", "steer"]).optional(),
28
30
  resolve_unknown_turn: resolveUnknown, client_request_id: requestId,
29
31
  } },
@@ -31,14 +33,15 @@ const defs = [
31
33
  session_id: z.string(), request_id: z.string(),
32
34
  answer: z.object({ confirm: z.boolean().optional(), select_index: z.number().int().min(0).optional(), text: z.string().optional() }), client_request_id: requestId,
33
35
  } },
34
- { name: "session_interrupt", description: "Abort the specified turn and cancel queued messages without starting another. Use session_send delivery=steer to redirect instead.", write: true, schema: {
35
- session_id: z.string(), turn_id: z.string(), client_request_id: requestId,
36
+ { name: "session_interrupt", description: "Stop the session's live turn and clear its queue. Use session_send delivery=steer to redirect instead.", write: true, schema: {
37
+ session_id: z.string(), client_request_id: requestId,
36
38
  } },
37
39
  { name: "session_close", description: "Close a session and terminate its processes; history and usage remain readable.", write: true, schema: {
38
40
  session_id: z.string(), client_request_id: requestId,
39
41
  } },
40
- { name: "session_list", description: "List matching sessions; with wait_ms, wait for the first initially busy match to stop being busy.", write: false, schema: {
41
- agent: z.string().optional(), status: z.string().optional(), task_id: z.string().optional(), station: station.optional(), seat: z.boolean().optional(), wait_ms: wait,
42
+ { name: "session_list", description: "List matching sessions as an immediate snapshot. Filter by agent, status, task_id or station; to wait for one session use session_read.", write: false, schema: {
43
+ agent: z.string().optional(), status: z.string().optional(), task_id: z.string().optional(),
44
+ station: station.optional(),
42
45
  } },
43
46
  { name: "ask_jaxon", description: "Manage presets in natural language via JaXon. Creation, duplication and auth requests use the same operations core.", write: true, schema: {
44
47
  text: z.string(), attachments, session_id: z.string().optional(), resolve_unknown_turn: resolveUnknown, client_request_id: requestId,
@@ -47,17 +50,17 @@ const defs = [
47
50
  { name: "agent_get", description: "Get a preset's redacted files, revisions, connection and readiness.", write: false, schema: { name: z.string() } },
48
51
  { name: "agent_create", description: "Create a preset, optionally without a connection; readiness testing starts automatically.", write: true, schema: {
49
52
  name: z.string(), description: z.string(), provider: z.string().optional(), model: z.string().optional(), connection: z.string().nullable().optional(),
50
- thinking: z.string().optional(), tools, instructions: z.string().optional(), files: patch, client_request_id: requestId,
53
+ thinking: z.string().optional(), tools, instructions: z.string().optional(), files: patch, session_switch, client_request_id: requestId,
51
54
  } },
52
55
  { name: "agent_duplicate", description: "Duplicate a preset revision with optional overrides. Model credentials stay shared; MCP credentials are not copied.", write: true, schema: {
53
56
  source: z.string(), name: z.string(), description: z.string().optional(), from_revision: z.string().optional(), instructions: z.string().optional(),
54
- tools, thinking: z.string().optional(), model: z.string().optional(), connection: z.string().nullable().optional(), patch, client_request_id: requestId,
57
+ tools, thinking: z.string().optional(), model: z.string().optional(), connection: z.string().nullable().optional(), patch, session_switch, client_request_id: requestId,
55
58
  } },
56
59
  { name: "agent_update", description: "Publish a patched revision, change description/connection, or roll back from an older revision.", write: true, schema: {
57
- name: z.string(), patch, description: z.string().optional(), connection: z.string().nullable().optional(),
60
+ name: z.string(), patch, description: z.string().optional(), connection: z.string().nullable().optional(), session_switch,
58
61
  from_revision: z.string().optional(), expected_rev: z.string().optional(), client_request_id: requestId,
59
62
  } },
60
- { name: "agent_delete", description: "Delete a non-JaXon preset without affecting existing session snapshots.", write: true, schema: {
63
+ { name: "agent_delete", description: "Delete a non-JaXon preset. Existing session snapshots keep working.", write: true, schema: {
61
64
  name: z.string(), expected_rev: z.string().optional(), client_request_id: requestId,
62
65
  } },
63
66
  { name: "agent_test", description: "Run or await a real one-shot Pi readiness test for a preset.", write: false, schema: { name: z.string(), wait_ms: wait } },
package/dist/ops/core.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import * as store from "../agents/directory-store.js";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { sessionSwitchKey } from "../agents/session-switch.js";
2
4
  import { ConnectionManager } from "../connections/manager.js";
3
5
  import { ReadinessService } from "../readiness/service.js";
4
6
  import { allocateSessionId, SessionSupervisor } from "../sessions/supervisor.js";
@@ -15,6 +17,15 @@ import { IdempotencyStore } from "./idempotency.js";
15
17
  import { ActivityRegistry } from "../daemon/activity.js";
16
18
  import { StationActivityGraph } from "../console/activity.js";
17
19
  const json = (v) => JSON.stringify(v, null, 2) + "\n";
20
+ function samePiSettings(next, previous) {
21
+ if (!next || !previous || typeof next !== "object" || typeof previous !== "object" || Array.isArray(next) || Array.isArray(previous))
22
+ return false;
23
+ if (!Object.hasOwn(next, sessionSwitchKey) && !Object.hasOwn(previous, sessionSwitchKey))
24
+ return false;
25
+ const { [sessionSwitchKey]: _next, ...nextPi } = next;
26
+ const { [sessionSwitchKey]: _previous, ...previousPi } = previous;
27
+ return isDeepStrictEqual(nextPi, previousPi);
28
+ }
18
29
  const jaxonOps = new Set([...operationDefs.filter(({ name }) => name.startsWith("agent_") || name.startsWith("station_")).map(({ name }) => name), "connection_list"]);
19
30
  const memberOps = new Set(["member_context", "board_read", "board_write", "cue"]);
20
31
  const stationParamOps = new Set(["session_start", "station_get", "station_update", "board_read", "board_write", "board_clear", "session_list"]);
@@ -68,7 +79,8 @@ export class OperationsCore {
68
79
  return params;
69
80
  const parsed = operationSchema(def).safeParse(params);
70
81
  if (!parsed.success)
71
- fail(stationPublishing(name) ? "STATION_INVALID" : "INVALID_PARAMS", parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "), { issues: parsed.error.issues });
82
+ fail(parsed.error.issues.some(issue => issue.path[0] === "session_switch") ? "INVALID_ARGUMENT"
83
+ : stationPublishing(name) ? "STATION_INVALID" : "INVALID_PARAMS", parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "), { issues: parsed.error.issues });
72
84
  return parsed.data;
73
85
  }
74
86
  counted = (read) => {
@@ -97,8 +109,9 @@ export class OperationsCore {
97
109
  }
98
110
  consoleAgentList() {
99
111
  return this.counted(() => store.listPresets().map((agent) => {
100
- const settings = store.settingsOf(store.current(agent.name, agent.revision).dir);
101
- return { ...agent, readiness: this.readiness.status(agent.name).readiness,
112
+ const { dir } = store.current(agent.name, agent.revision);
113
+ const settings = store.settingsOf(dir);
114
+ return { ...agent, ...store.sessionSwitchFields(agent.name, dir), readiness: this.readiness.status(agent.name).readiness,
102
115
  model: typeof settings.defaultModel === "string" ? settings.defaultModel : "",
103
116
  provider: typeof settings.defaultProvider === "string" ? settings.defaultProvider : "" };
104
117
  }));
@@ -154,9 +167,10 @@ export class OperationsCore {
154
167
  : { result: await this.supervisor.listSessions(ref ? { ...params, station: ref.station_id } : params, wait), images: [] };
155
168
  if (ref && name === "session_read" && front === "master")
156
169
  this.activityGraph.recordReports(ref, params.session_id, reply.result);
157
- if (params.wait_ms !== undefined && "waited_ms" in reply.result)
170
+ const outcome = reply.result;
171
+ if (name === "session_read" && params.wait_ms !== undefined && "waited_ms" in outcome)
158
172
  console.log(JSON.stringify({ op: name, wait_ms: params.wait_ms,
159
- waited_ms: reply.result.waited_ms, return_reason: reply.result.return_reason }));
173
+ waited_ms: outcome.waited_ms, return_reason: outcome.return_reason }));
160
174
  if (!ref)
161
175
  return reply;
162
176
  return this.counted(() => {
@@ -214,7 +228,7 @@ export class OperationsCore {
214
228
  const meta = name === "session_start" ? undefined : this.supervisor.sessions.get(params.session_id)?.meta;
215
229
  const sessionId = name === "session_start" ? result.session_id : params.session_id;
216
230
  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,
231
+ session_id: sessionId,
218
232
  turn_id: result.turn_id ?? meta?.active_turn_id ?? undefined, delivery: result.delivery ?? (name === "session_start" ? "started" : undefined),
219
233
  source: front === "human" ? "human" : "master" });
220
234
  }
@@ -251,8 +265,8 @@ export class OperationsCore {
251
265
  const now = Date.now();
252
266
  this.cues.event(ref, { session_id: member.session_id, cue_ids: cues.map(cue => cue.cue_id), at: now, delivered_at: now });
253
267
  }
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 };
268
+ return { station, agent: member.agent, session_id: member.session_id,
269
+ member_instructions: stationMemberInstructions(member.agent), master_board, board, cues, dropped_cues: dropped };
256
270
  }
257
271
  if (params?.station !== undefined || (name === "board_write" && params?.owner !== undefined && params.owner !== member.agent))
258
272
  fail("BOARD_FORBIDDEN", "The board is outside the member's scope", { owner: params?.owner });
@@ -301,8 +315,10 @@ export class OperationsCore {
301
315
  if (message && [...message].length > 100)
302
316
  fail("CUE_MESSAGE_INVALID", "message exceeds 100 Unicode characters");
303
317
  const roster = new Set(this.activity.roster(ref));
318
+ const pending = this.activity.pending(ref);
319
+ const knownRoles = new Set([...roster, ...(pending?.join ?? []), ...(pending?.leave ?? [])]);
304
320
  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));
321
+ .sort((a, b) => b.updated_at - a.updated_at || a.session_id.localeCompare(b.session_id));
306
322
  const plans = [];
307
323
  const skipped = [];
308
324
  if (targets.every((target) => target === member.session_id))
@@ -316,34 +332,46 @@ export class OperationsCore {
316
332
  skipped.push({ target, reason: "no_session" });
317
333
  continue;
318
334
  }
319
- const session = metadata.find((m) => m.session_id === target);
320
- if (!session)
321
- fail("CUE_INVALID_TARGET", target, { target });
322
- if (target === member.session_id)
335
+ if (knownRoles.has(target)) {
336
+ skipped.push({ target, reason: "not_in_roster" });
337
+ continue;
338
+ }
339
+ if (metadata.some((m) => m.session_id === target)) {
340
+ if (target !== member.session_id)
341
+ plans.push({ target, sessions: [target] });
323
342
  continue;
324
- plans.push({ target, sessions: [target] });
343
+ }
344
+ const existing = this.supervisor.sessions.get(target);
345
+ if (existing ? existing.meta.station?.station_id !== ref.station_id : !target.startsWith("ses_"))
346
+ fail("CUE_INVALID_TARGET", target, { target });
347
+ skipped.push({ target, reason: "not_found" });
325
348
  }
326
349
  const board = this.boards.own(ref, member.agent);
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(),
350
+ const base = { hop: this.supervisor.cueHop(member.session_id),
351
+ from: { agent: member.agent, session_id: member.session_id }, at: Date.now(),
328
352
  ...(message ? { message } : {}), board: { owner: member.agent, version: board.version } };
353
+ for (const { target, reason } of skipped)
354
+ this.cues.append(ref, { ...base, to: { target }, delivery: "undelivered", reason });
355
+ const hint = skipped.some(({ reason }) => reason === "no_session")
356
+ ? "Write the conclusion on your board so the master can open a session." : undefined;
357
+ if (!plans.length)
358
+ fail("CUE_NOT_DELIVERED", hint ?? "No target received the cue", { skipped });
329
359
  const cueId = `cue_${randomUUID().replaceAll("-", "").slice(0, 16)}`;
330
360
  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)
361
+ const recipientIds = [...new Set(plans.flatMap((plan) => plan.sessions))];
362
+ for (const session_id of recipientIds)
334
363
  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
364
  const deliveries = new Map();
338
365
  let reserved = 0;
339
- for (const { session_id } of recipients) {
366
+ for (const session_id of recipientIds) {
340
367
  const delivery = this.supervisor.triggerCueWake(session_id, reserved < 4);
341
368
  deliveries.set(session_id, delivery.result);
342
369
  const { wake, error_code } = this.supervisor.pendingCueSummary(this.supervisor.sessions.get(session_id).meta);
343
370
  for (const plan of plans) {
344
371
  if (!plan.sessions.includes(session_id))
345
372
  continue;
346
- this.cues.append(ref, { ...cue, to: { target: plan.target, session_id }, delivery: "pending",
373
+ this.cues.append(ref, { ...cue, to: { target: plan.target, session_id },
374
+ delivery: "pending",
347
375
  ...(wake ? { wake } : {}), ...(error_code ? { error_code } : {}) });
348
376
  }
349
377
  void delivery.result.then(status => {
@@ -357,41 +385,25 @@ export class OperationsCore {
357
385
  }
358
386
  const delivered_to = await Promise.all(plans.map(async ({ target, sessions }) => ({
359
387
  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
- })),
388
+ sessions: await Promise.all(sessions.map(async (session_id) => ({ session_id, ...await deliveries.get(session_id) }))),
364
389
  })));
365
- return { cue_ids: recipients.length ? [cueId] : [], delivered_to, skipped };
390
+ return { cue_ids: [cueId], delivered_to, skipped, ...(hint ? { hint } : {}) };
366
391
  }
367
392
  async dispatch(name, p, rec, front, claimRevised) {
368
393
  switch (name) {
369
394
  case "session_start": {
370
395
  if (p.station === undefined) {
371
- if (p.seat !== undefined)
372
- fail("INVALID_ARGUMENT", "seat is only valid with station", { seat: p.seat });
373
396
  const stations = this.stations.all().filter((s) => s.agents.includes(p.agent)).map(({ station_id, name }) => ({ station_id, name }));
374
397
  const result = await this.supervisor.startSession(p, rec);
375
398
  return stations.length ? { ...result, station_hint: { stations, advice: "Prefer running this agent in a matching Station." } } : result;
376
399
  }
377
400
  const ref = this.stations.resolve(p.station);
378
- const mode = p.seat ?? "claim";
379
401
  const session_id = allocateSessionId();
380
- const seat = mode !== "none";
381
- const admission = this.activity.admitStart(ref, p.agent, session_id, { reportPending: front === "master", seat: mode });
382
- let renewedFrom;
402
+ // One lock covers the per-role limit and creation; a full role fails before any session exists.
403
+ const admission = this.activity.admitStart(ref, p.agent, session_id, { reportPending: front === "master" });
383
404
  try {
384
- // Busy renewal fails during admission; every other start gate still precedes the close.
385
- if (mode === "renew")
386
- this.supervisor.prepareStart(p);
387
- if (admission.renewed) {
388
- await this.supervisor.closeSession(admission.renewed.session_id, claimRevised ? () => claimRevised(ref) : undefined);
389
- renewedFrom = admission.renewed.session_id;
390
- this.memberBoardVersions.delete(renewedFrom);
391
- rec({ renewed_from: renewedFrom });
392
- }
393
- return await this.supervisor.startSession(p, rec, { ref: stationRef(this.activity.frozen(ref) ?? ref), session_id, seat,
394
- renewedFrom, validate: () => this.activity.validateAdmittedStart(ref, p.agent), started: admission.release });
405
+ return await this.supervisor.startSession(p, rec, { ref: stationRef(this.activity.frozen(ref) ?? ref), session_id,
406
+ validate: () => this.activity.validateAdmittedStart(ref, p.agent), started: admission.release });
395
407
  }
396
408
  catch (error) {
397
409
  const created = this.supervisor.sessions.get(session_id);
@@ -404,10 +416,6 @@ export class OperationsCore {
404
416
  }
405
417
  }
406
418
  this.memberBoardVersions.delete(session_id);
407
- if (renewedFrom && error instanceof OpError)
408
- error.details.renewed_from ??= renewedFrom;
409
- else if (renewedFrom)
410
- throw new OpError("START_FAILED", error instanceof Error ? error.message : String(error), { renewed_from: renewedFrom });
411
419
  throw error;
412
420
  }
413
421
  finally {
@@ -452,12 +460,13 @@ export class OperationsCore {
452
460
  const roster = new Set(frozen?.agents ?? (p.revision === undefined ? version.agents : this.activity.roster(ref)));
453
461
  const members = this.activity.members(ref.station_id).map(({ session_id, agent, status }) => ({ session_id, agent, status, in_roster: roster.has(agent) }));
454
462
  return { ...version, agents: version.agents.map((agent) => {
463
+ const policy = store.sessionSwitchFields(agent);
455
464
  try {
456
- return { name: agent, readiness: this.readiness.status(agent).readiness };
465
+ return { name: agent, readiness: this.readiness.status(agent).readiness, ...policy };
457
466
  }
458
467
  catch (e) {
459
468
  if (e instanceof OpError && e.code === "PRESET_NOT_FOUND")
460
- return { name: agent, readiness: "missing" };
469
+ return { name: agent, readiness: "missing", ...policy };
461
470
  throw e;
462
471
  }
463
472
  }), revisions: this.stations.revisions(ref), members, station_context: stationContext(snapshot, "requested"),
@@ -509,7 +518,19 @@ export class OperationsCore {
509
518
  return result;
510
519
  }
511
520
  case "ask_jaxon": return this.supervisor.askJaXon(p, rec);
512
- case "agent_list": return { agents: store.listPresets().map((a) => ({ ...a, readiness: this.readiness.status(a.name).readiness })) };
521
+ case "agent_list": return { agents: store.listPresets().map(agent => {
522
+ const policy = store.sessionSwitchFields(agent.name);
523
+ try {
524
+ return { ...agent, ...policy, readiness: this.readiness.status(agent.name).readiness };
525
+ }
526
+ catch (error) {
527
+ // A revision may disappear between enumeration and projection. A
528
+ // removed preset must not break the list or expose a stale policy.
529
+ if (error instanceof OpError && error.code === "PRESET_NOT_FOUND")
530
+ return { ...agent, ...store.sessionSwitchFields(agent.name), readiness: "missing" };
531
+ throw error;
532
+ }
533
+ }) };
513
534
  case "agent_get": return { ...store.getPresetRedacted(p.name), readiness: this.readiness.status(p.name) };
514
535
  case "agent_create": {
515
536
  const settings = {
@@ -526,7 +547,7 @@ export class OperationsCore {
526
547
  if (custom.modelsJson && !files["models.json"])
527
548
  files["models.json"] = custom.modelsJson;
528
549
  }
529
- const result = await store.createPreset(p.name, files, p.description);
550
+ const result = await store.createPreset(p.name, files, p.description, p.session_switch);
530
551
  return { ...result, readiness: this.readiness.status(p.name).readiness };
531
552
  }
532
553
  case "agent_duplicate": {
@@ -535,8 +556,8 @@ export class OperationsCore {
535
556
  }
536
557
  case "agent_update": {
537
558
  const files = { ...(p.patch ?? {}) };
538
- if (!Object.keys(files).length && p.description === undefined && p.connection === undefined && p.from_revision === undefined)
539
- fail("INVALID_PARAMS", "Specify a nonempty patch, description, connection, or from_revision");
559
+ if (!Object.keys(files).length && p.description === undefined && p.connection === undefined && p.from_revision === undefined && p.session_switch === undefined)
560
+ fail("INVALID_PARAMS", "Specify a nonempty patch, description, connection, from_revision, or session_switch");
540
561
  if (p.connection !== undefined)
541
562
  files["harness.json"] = json({ connection: p.connection });
542
563
  const bound = p.connection !== undefined ? p.connection : store.harnessOf(store.current(p.name).dir).connection;
@@ -544,12 +565,17 @@ export class OperationsCore {
544
565
  const baseSettings = files["settings.json"]
545
566
  ? JSON.parse(files["settings.json"])
546
567
  : store.settingsOf(store.current(p.name, p.from_revision).dir);
547
- const custom = store.revisionForConnection(baseSettings, bound);
548
- files["settings.json"] = json(custom.settings);
549
- if (custom.modelsJson && !files["models.json"])
550
- files["models.json"] = custom.modelsJson;
568
+ // Policy-only JSON writes must not regenerate a custom provider's models.json.
569
+ const policyOnly = p.connection === undefined && p.patch?.["harness.json"] === undefined && files["settings.json"] &&
570
+ samePiSettings(baseSettings, store.settingsOf(store.current(p.name, p.from_revision).dir));
571
+ if (!policyOnly) {
572
+ const custom = store.revisionForConnection(baseSettings, bound);
573
+ files["settings.json"] = json(custom.settings);
574
+ if (custom.modelsJson && !files["models.json"])
575
+ files["models.json"] = custom.modelsJson;
576
+ }
551
577
  }
552
- const result = await store.updatePresetRevision(p.name, files, p.expected_rev, p.description, p.from_revision);
578
+ const result = await store.updatePresetRevision(p.name, files, p.expected_rev, p.description, p.from_revision, p.session_switch);
553
579
  return { ...result, readiness: this.readiness.status(p.name).readiness };
554
580
  }
555
581
  case "agent_delete": return store.deletePreset(p.name, p.expected_rev);