@hattoriai/poney 0.1.1 → 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 (35) hide show
  1. package/brief.md +4 -4
  2. package/dist/{chunk-BCOS4LFB.js → chunk-FN43OHT5.js} +693 -244
  3. package/dist/chunk-FN43OHT5.js.map +1 -0
  4. package/dist/{chunk-YLKV6LIU.js → chunk-KV5CB763.js} +5 -5
  5. package/dist/{chunk-YLKV6LIU.js.map → chunk-KV5CB763.js.map} +1 -1
  6. package/dist/{chunk-TPJZDQG6.js → chunk-PRXFQAW2.js} +3 -3
  7. package/dist/{chunk-TPJZDQG6.js.map → chunk-PRXFQAW2.js.map} +1 -1
  8. package/dist/cli.js +3 -3
  9. package/dist/cli.js.map +1 -1
  10. package/dist/hub-OLUM6VK4.js +4 -0
  11. package/dist/hub-OLUM6VK4.js.map +1 -0
  12. package/dist/mcp.js +14 -8
  13. package/dist/mcp.js.map +1 -1
  14. package/dist/ops.d.ts +27 -27
  15. package/dist/ops.js +1 -1
  16. package/dist/plugins/index.js +1 -1
  17. package/dist/run-AYEEUZVG.js +3 -0
  18. package/dist/run-AYEEUZVG.js.map +1 -0
  19. package/examples/tour.poney +498 -75
  20. package/examples/walkthrough.poney +5 -5
  21. package/package.json +7 -13
  22. package/studio/assets/{dist-_ey1iXf6.js → dist-CGLReTF9.js} +1 -1
  23. package/studio/assets/{elk.bundled-Bw5WzyyE.js → elk.bundled-DY947aeZ.js} +1 -1
  24. package/studio/assets/index-DxRueLYJ.js +944 -0
  25. package/studio/assets/index-ugML0yPo.css +1 -0
  26. package/studio/assets/src-DZ2JOWW7.js +88 -0
  27. package/studio/index.html +2 -2
  28. package/dist/chunk-BCOS4LFB.js.map +0 -1
  29. package/dist/hub-FERXNPJS.js +0 -4
  30. package/dist/hub-FERXNPJS.js.map +0 -1
  31. package/dist/run-25PP2HWH.js +0 -3
  32. package/dist/run-25PP2HWH.js.map +0 -1
  33. package/studio/assets/index-B-C2JUUu.css +0 -1
  34. package/studio/assets/index-DOjop_HJ.js +0 -889
  35. package/studio/assets/src-Br__iChL.js +0 -88
@@ -1,16 +1,99 @@
1
- import { studioDist, mcpCommand, check } from './chunk-TPJZDQG6.js';
2
- import { methods, client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
3
- import { execFile, execFileSync, spawn } from 'child_process';
4
- import { Writable, Readable } from 'stream';
5
- import { join, dirname, normalize, extname, basename, resolve, delimiter } from 'path';
6
- import { createServer } from 'http';
7
- import { readFileSync, existsSync, mkdirSync, writeFileSync, watch, statSync, readdirSync, mkdtempSync, accessSync, constants } from 'fs';
1
+ import { studioDist, mcpCommand, check } from './chunk-PRXFQAW2.js';
2
+ import { execFile, spawn, execFileSync } from 'child_process';
3
+ import { existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync, watch, statSync, renameSync, realpathSync, accessSync, constants, mkdtempSync } from 'fs';
8
4
  import { createRequire } from 'module';
9
5
  import { homedir, tmpdir } from 'os';
10
6
  import { promisify } from 'util';
7
+ import { join, dirname, normalize, extname, basename, resolve, delimiter } from 'path';
8
+ import { methods, client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
9
+ import { Writable, Readable } from 'stream';
10
+ import { createServer } from 'http';
11
11
  import { fileURLToPath } from 'url';
12
12
  import { EventEmitter } from 'events';
13
13
 
14
+ var require2 = createRequire(import.meta.url);
15
+ var exec = promisify(execFile);
16
+ function packageBin(pkg) {
17
+ try {
18
+ const manifest = require2.resolve(`${pkg}/package.json`);
19
+ const { bin } = require2(manifest);
20
+ const file = typeof bin === "string" ? bin : bin && Object.values(bin)[0];
21
+ return file ? join(dirname(manifest), file) : void 0;
22
+ } catch {
23
+ return void 0;
24
+ }
25
+ }
26
+ function onPath(program) {
27
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
28
+ if (!dir) continue;
29
+ const file = join(dir, program);
30
+ try {
31
+ accessSync(file, constants.X_OK);
32
+ return file;
33
+ } catch {
34
+ }
35
+ }
36
+ return void 0;
37
+ }
38
+ async function run(command, args) {
39
+ try {
40
+ const { stdout, stderr } = await exec(command, args, { timeout: 2e4, env: { ...process.env, NO_COLOR: "1" } });
41
+ return { code: 0, out: strip(`${stdout}${stderr}`) };
42
+ } catch (e) {
43
+ const err = e;
44
+ return { code: typeof err.code === "number" ? err.code : 1, out: strip(`${err.stdout ?? ""}${err.stderr ?? err.message}`) };
45
+ }
46
+ }
47
+ var strip = (t) => t.replace(/\x1b\[[0-9;]*m/g, "").trim();
48
+ async function claudeStatus() {
49
+ const bin = onPath("claude");
50
+ if (!bin) return void 0;
51
+ const { out } = await run(bin, ["auth", "status"]);
52
+ try {
53
+ const s = JSON.parse(out.slice(out.indexOf("{")));
54
+ return s.loggedIn ? { state: "ready", detail: `Signed in${s.authMethod ? ` with ${s.authMethod}` : ""}${s.configDirectory ? ` (${s.configDirectory.replace(homedir(), "~")})` : ""}.` } : { state: "sign-in", detail: "Not signed in." };
55
+ } catch {
56
+ return { state: "unsure", detail: "Claude Code did not say whether it is signed in." };
57
+ }
58
+ }
59
+ async function codexStatus() {
60
+ const bin = onPath("codex");
61
+ if (!bin) return void 0;
62
+ const { code, out } = await run(bin, ["login", "status"]);
63
+ return code === 0 ? { state: "ready", detail: `${out.split("\n")[0] || "Signed in"}.` } : { state: "sign-in", detail: out.split("\n")[0] || "Not signed in." };
64
+ }
65
+ async function opencodeStatus(bin) {
66
+ const { out } = await run(bin, ["auth", "list"]);
67
+ const stored = Number(/(\d+)\s+credentials?/i.exec(out)?.[1] ?? 0);
68
+ const fromEnv = [...out.matchAll(/●\s+(.+?)\s+([A-Z][A-Z0-9_]+)\s*$/gm)].map((m) => `${m[1]} (${m[2]})`);
69
+ if (stored > 0) return { state: "ready", detail: `${stored} stored sign-in${stored > 1 ? "s" : ""}.` };
70
+ if (fromEnv.length) return { state: "unsure", detail: `No stored sign-in. It can only use keys from your environment: ${fromEnv.join(", ")}.` };
71
+ return { state: "sign-in", detail: "No sign-in, and no provider key in the environment." };
72
+ }
73
+ function builtInProviders() {
74
+ const claude = packageBin("@agentclientprotocol/claude-agent-acp");
75
+ const codex = packageBin("@agentclientprotocol/codex-acp");
76
+ const opencode = onPath("opencode");
77
+ const copilot = onPath("copilot");
78
+ return [
79
+ { id: "claude-code", name: "Claude Code", command: process.execPath, args: claude ? [claude] : [], available: !!claude, install: "Reinstall Poney's dependencies (npm install).", signIn: 'Run "claude" in a terminal and sign in with /login.', status: claudeStatus },
80
+ { id: "codex", name: "OpenAI Codex", command: process.execPath, args: codex ? [codex] : [], available: !!codex, install: "Reinstall Poney's dependencies (npm install).", signIn: 'Run "codex login" in a terminal.', status: codexStatus },
81
+ { id: "opencode", name: "OpenCode", command: opencode ?? "opencode", args: ["acp"], available: !!opencode, install: "Install OpenCode: https://opencode.ai", signIn: 'Run "opencode auth login" in a terminal.', status: opencode ? () => opencodeStatus(opencode) : void 0 },
82
+ { id: "copilot", name: "GitHub Copilot", command: copilot ?? "copilot", args: ["--acp", "--stdio"], available: !!copilot, install: "Install the Copilot CLI: npm install -g @github/copilot", signIn: 'Run "copilot" in a terminal and sign in with /login.' }
83
+ ];
84
+ }
85
+ function parseCommand(line) {
86
+ const words = [...line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((m) => m[1] ?? m[2] ?? m[3]);
87
+ if (!words.length) return void 0;
88
+ return { command: words[0], args: words.slice(1) };
89
+ }
90
+ function customProvider(name, commandLine) {
91
+ const parsed = parseCommand(commandLine);
92
+ if (!parsed) return void 0;
93
+ const found = parsed.command.includes("/") ? parsed.command : onPath(parsed.command);
94
+ return { id: `custom:${name}`, name, ...parsed, command: found ?? parsed.command, available: !!found, install: `"${parsed.command}" is not on PATH.`, signIn: "Sign in as the agent's documentation says.", custom: true };
95
+ }
96
+ var describeProvider = ({ id, name, install, available, signIn, custom }) => ({ id, name, install, available, signIn, ...custom ? { custom } : {} });
14
97
  var AUTH_REQUIRED = -32e3;
15
98
  var AgentStartError = class extends Error {
16
99
  constructor(message, signIn) {
@@ -19,6 +102,10 @@ var AgentStartError = class extends Error {
19
102
  }
20
103
  signIn;
21
104
  };
105
+ function isSignInError(e) {
106
+ const err = e;
107
+ return err.code === AUTH_REQUIRED || /auth|sign.?in|log.?in|credential|api key/i.test(err.message ?? "");
108
+ }
22
109
  async function startAgent(spec, cwd, options = {}) {
23
110
  if (!spec.available) throw new AgentStartError(`${spec.name} is not installed. ${spec.install}`, false);
24
111
  const child = spawn(spec.command, spec.args, { cwd, stdio: ["pipe", "pipe", "pipe"], env: process.env });
@@ -47,20 +134,33 @@ async function startAgent(spec, cwd, options = {}) {
47
134
  });
48
135
  const canAppend = init.agentCapabilities?.sessionCapabilities?.systemPrompt != null;
49
136
  const systemPrompt = canAppend && options.systemPrompt ? { mode: "append", content: [{ type: "text", text: options.systemPrompt }] } : void 0;
50
- const request = { cwd, mcpServers: options.mcpServers ?? [], ...systemPrompt ? { systemPrompt } : {} };
137
+ const can = { load: init.agentCapabilities?.loadSession === true, resume: init.agentCapabilities?.sessionCapabilities?.resume != null };
138
+ const base = { cwd, mcpServers: options.mcpServers ?? [], ...systemPrompt ? { systemPrompt } : {} };
139
+ const old = options.resume;
140
+ const how = old && (can[old.how] ? old.how : can.load ? "load" : void 0);
141
+ if (old && how) {
142
+ const request2 = { ...base, sessionId: old.sessionId };
143
+ try {
144
+ const session2 = how === "load" ? await connection.agent.request(methods.agent.session.load, request2) : await connection.agent.request(methods.agent.session.resume, request2);
145
+ return { sessionId: old.sessionId, how, can, session: { sessionId: old.sessionId, ...session2 }, systemPromptApplied: !!systemPrompt };
146
+ } catch (e) {
147
+ if (isSignInError(e)) throw e;
148
+ }
149
+ }
150
+ const request = base;
51
151
  const session = await connection.agent.request(methods.agent.session.new, request);
52
- return { sessionId: session.sessionId, session, systemPromptApplied: !!systemPrompt };
152
+ return { sessionId: session.sessionId, how: "new", can, session, systemPromptApplied: !!systemPrompt };
53
153
  })();
54
154
  const ms = options.timeoutMs ?? 6e4;
55
155
  const late = new Promise((_, reject) => setTimeout(() => reject(new AgentStartError(`${spec.name} did not answer within ${Math.round(ms / 1e3)} seconds.`, false)), ms));
56
156
  try {
57
- const { sessionId, session, systemPromptApplied } = await Promise.race([opened, exited, late]);
58
- return { child, connection, sessionId, session, systemPromptApplied, stderr: () => lines, stop };
157
+ const { sessionId, how, can, session, systemPromptApplied } = await Promise.race([opened, exited, late]);
158
+ return { child, connection, sessionId, how, can, session, systemPromptApplied, stderr: () => lines, stop };
59
159
  } catch (e) {
60
160
  stop();
61
161
  if (e instanceof AgentStartError) throw e;
62
162
  const err = e;
63
- const signIn = err.code === AUTH_REQUIRED || /auth|sign.?in|log.?in|credential|api key/i.test(err.message ?? "");
163
+ const signIn = isSignInError(err);
64
164
  throw new AgentStartError(signIn ? `${spec.name} needs a sign-in. ${spec.signIn}` : `${spec.name} failed: ${err.message ?? String(e)}`, signIn);
65
165
  }
66
166
  }
@@ -108,59 +208,163 @@ async function applySetting(connection, sessionId, settings, id, value) {
108
208
  else await connection.agent.request("session/set_model", { sessionId, modelId: String(value) });
109
209
  return settings.map((x) => x.id === id ? { ...x, current: value } : x);
110
210
  }
111
- function workspaceProject(cwd) {
112
- const name = basename(cwd) || "workspace";
113
- const id = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "workspace";
114
- return { cwd, id, name };
115
- }
116
- function emptyDocument(w) {
117
- return { poneyVersion: "0.1.0", project: { id: w.id, name: w.name, description: `The code in ${w.cwd}.` }, model: {}, views: [], walkthroughs: [] };
118
- }
119
- function intoWorkspace(document, w) {
120
- if (!document || typeof document !== "object") return document;
121
- const d = document;
122
- return { ...d, project: { ...d.project ?? {}, id: w.id, name: d.project?.name ?? w.name } };
211
+ var poneyHome = () => process.env.PONEY_HOME ?? join(homedir(), ".poney");
212
+
213
+ // src/agents/sessions.ts
214
+ var agentKey = (a) => "custom" in a ? `custom:${a.custom.name}` : a.providerId;
215
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
216
+ function readDefault(v) {
217
+ if (!isObject(v) || !isObject(v.agent)) return void 0;
218
+ const a = v.agent;
219
+ const known = typeof a.providerId === "string";
220
+ const custom = isObject(a.custom) && typeof a.custom.name === "string" && typeof a.custom.command === "string";
221
+ if (!known && !custom) return void 0;
222
+ return { agent: v.agent, settings: isObject(v.settings) ? v.settings : {} };
123
223
  }
224
+ var SessionStore = class {
225
+ constructor(file = join(poneyHome(), "sessions.json")) {
226
+ this.file = file;
227
+ }
228
+ file;
229
+ defaultAgent() {
230
+ return this.read().defaultAgent;
231
+ }
232
+ setDefaultAgent(d) {
233
+ const f = this.read();
234
+ f.defaultAgent = d;
235
+ this.write(f);
236
+ }
237
+ session(project) {
238
+ return this.read().projects[project];
239
+ }
240
+ setSession(project, s) {
241
+ const f = this.read();
242
+ f.projects[project] = s;
243
+ this.write(f);
244
+ }
245
+ forget(project) {
246
+ const f = this.read();
247
+ delete f.projects[project];
248
+ this.write(f);
249
+ }
250
+ read() {
251
+ const empty = { version: 1, projects: {} };
252
+ if (!existsSync(this.file)) return empty;
253
+ try {
254
+ const v = JSON.parse(readFileSync(this.file, "utf8"));
255
+ if (!isObject(v)) return empty;
256
+ const projects = isObject(v.projects) ? v.projects : {};
257
+ const defaultAgent = readDefault(v.defaultAgent);
258
+ return { version: 1, ...defaultAgent ? { defaultAgent } : {}, projects };
259
+ } catch {
260
+ return empty;
261
+ }
262
+ }
263
+ write(f) {
264
+ mkdirSync(dirname(this.file), { recursive: true });
265
+ const tmp = `${this.file}.${process.pid}.tmp`;
266
+ writeFileSync(tmp, JSON.stringify(f, null, 2));
267
+ renameSync(tmp, this.file);
268
+ }
269
+ };
124
270
 
125
271
  // src/agents/bridge.ts
126
- var AgentBridge = class {
127
- constructor(state, mcp) {
272
+ var ProjectAgent = class {
273
+ constructor(state, project, mcp, store) {
128
274
  this.state = state;
275
+ this.project = project;
129
276
  this.mcp = mcp;
277
+ this.store = store;
130
278
  }
131
279
  state;
280
+ project;
132
281
  mcp;
282
+ store;
133
283
  agent;
134
284
  connection;
285
+ /** The session whose updates this agent shows: the running one, or the one it resumes. */
135
286
  sessionId;
136
287
  spec;
288
+ key = "";
137
289
  cwd = "";
290
+ /** Counts starts and stops, so a start that a stop overtook does not keep its agent. */
291
+ run = 0;
138
292
  queue = [];
139
- busy = false;
293
+ working = false;
140
294
  settings = [];
141
295
  briefed = false;
142
296
  /** The agent took the briefing as system instructions; else each request carries a short reminder. */
143
297
  systemPrompt = false;
144
298
  /** The agent message being written in this turn, and tool calls by their ACP id. */
145
299
  writing;
300
+ /** In a replayed history, the person's message being written, and the prompt it was as sent. */
301
+ asking;
302
+ asked = "";
303
+ /** True while the agent replays a loaded session. */
304
+ replaying = false;
305
+ /** The thread already has the session's history: a replay of it is not shown again. */
306
+ keepThread = false;
307
+ /** The messages the agent replayed from its earlier session: they are not new questions. */
308
+ history = /* @__PURE__ */ new Set();
146
309
  tools = /* @__PURE__ */ new Map();
147
310
  choices = /* @__PURE__ */ new Map();
311
+ /** Called when the status changes: started, busy or not, settings, stopped. */
312
+ onChange;
313
+ /** The agent's name in the session store. */
314
+ get agentKey() {
315
+ return this.key;
316
+ }
148
317
  get connected() {
149
- return !!this.sessionId;
318
+ return !!this.agent;
150
319
  }
151
- /** Starts the agent in a folder and opens a session with the Poney tools. */
152
- async connect(spec, cwd) {
153
- await this.disconnect();
154
- const mcp = this.mcp();
155
- const agent = await startAgent(spec, cwd, {
156
- mcpServers: [{ name: "poney", command: mcp.command, args: mcp.args, env: [{ name: "PONEY_HUB_URL", value: mcp.hubUrl }] }],
157
- systemPrompt: briefing(cwd),
158
- onUpdate: (n) => this.onUpdate(n),
159
- onPermission: (p) => this.onPermission(p)
160
- });
161
- this.agent = agent;
320
+ /** True while the agent works on a request. */
321
+ get busy() {
322
+ return this.working;
323
+ }
324
+ /** Permission requests that wait for the person. */
325
+ get pendingChoices() {
326
+ return this.choices.size;
327
+ }
328
+ /** Starts the agent in a folder with the Poney tools, in the project's earlier session when it can. */
329
+ async start(spec, choice, cwd) {
330
+ this.stop();
331
+ const run3 = this.run;
162
332
  this.spec = spec;
333
+ this.key = agentKey(choice);
163
334
  this.cwd = cwd;
335
+ const saved = this.store.session(this.project);
336
+ const resume = saved?.agentKey === this.key ? { sessionId: saved.sessionId, how: this.state.thread(this.project).length ? "resume" : "load" } : void 0;
337
+ this.sessionId = resume?.sessionId;
338
+ this.keepThread = resume?.how === "resume";
339
+ const mcp = this.mcp();
340
+ let agent;
341
+ this.replaying = true;
342
+ try {
343
+ agent = await startAgent(spec, cwd, {
344
+ mcpServers: [{ name: "poney", command: mcp.command, args: mcp.args, env: [{ name: "PONEY_HUB_URL", value: mcp.hubUrl }, { name: "PONEY_PROJECT", value: this.project }] }],
345
+ systemPrompt: briefing(cwd),
346
+ resume,
347
+ onUpdate: (n) => this.onUpdate(n),
348
+ onPermission: (p) => this.onPermission(p)
349
+ });
350
+ } catch (e) {
351
+ if (run3 === this.run) {
352
+ this.replaying = false;
353
+ this.sessionId = void 0;
354
+ this.writing = void 0;
355
+ this.asking = void 0;
356
+ }
357
+ throw e;
358
+ }
359
+ if (run3 !== this.run) return agent.stop();
360
+ this.replaying = false;
361
+ this.asking = void 0;
362
+ const lost = !!resume && agent.how === "new";
363
+ if (lost && resume.how === "load") this.state.remove(this.project, this.history);
364
+ else if (this.writing) this.put({ ...this.writing, done: true });
365
+ this.writing = void 0;
366
+ this.tools.clear();
367
+ this.agent = agent;
164
368
  this.sessionId = agent.sessionId;
165
369
  this.connection = agent.connection;
166
370
  const offered = fromConfigOptions(agent.session.configOptions ?? []);
@@ -168,20 +372,31 @@ var AgentBridge = class {
168
372
  this.settings = [...offered, ...fromLists(raw.models, raw.modes, offered)].map((s) => ({ ...s, initial: s.current }));
169
373
  agent.child.once("exit", () => {
170
374
  if (this.agent !== agent) return;
171
- this.state.put({ from: "notice", text: `${spec.name} stopped. ${agent.stderr().slice(-2).join(" ")}`.trim(), tone: "error" });
172
- this.reset();
375
+ this.put({ from: "notice", text: `${spec.name} stopped. ${agent.stderr().slice(-2).join(" ")}`.trim(), tone: "error" });
376
+ this.stop();
173
377
  });
174
- this.briefed = agent.systemPromptApplied;
378
+ this.briefed = agent.systemPromptApplied || agent.how !== "new";
175
379
  this.systemPrompt = agent.systemPromptApplied;
176
- this.state.setWorkspace(workspaceProject(cwd), true);
177
- this.publish();
380
+ this.store.setSession(this.project, { agentKey: this.key, sessionId: agent.sessionId, at: (/* @__PURE__ */ new Date()).toISOString() });
381
+ if (lost) this.put({ from: "notice", text: "The earlier session did not resume. This is a new session.", tone: "info" });
382
+ await this.applyDefaults();
383
+ this.onChange?.();
178
384
  }
179
- /** Stops the agent. Questions go back to agents that listen over MCP. */
180
- async disconnect() {
385
+ /** Stops the agent. Its permission requests are cancelled. */
386
+ stop() {
387
+ this.run++;
181
388
  const agent = this.agent;
182
389
  for (const choose of this.choices.values()) choose(null);
183
- this.reset();
390
+ this.agent = void 0;
391
+ this.connection = void 0;
392
+ this.sessionId = void 0;
393
+ this.queue = [];
394
+ this.working = false;
395
+ this.writing = void 0;
396
+ this.tools.clear();
397
+ this.choices.clear();
184
398
  agent?.stop();
399
+ if (agent) this.onChange?.();
185
400
  }
186
401
  /** Stops the current request; the session stays. */
187
402
  async cancel() {
@@ -190,54 +405,69 @@ var AgentBridge = class {
190
405
  for (const choose of this.choices.values()) choose(null);
191
406
  await this.connection.agent.notify(methods.agent.session.cancel, { sessionId: this.sessionId });
192
407
  }
193
- /** Changes one of the session's settings (model, effort, mode…). */
408
+ /** Changes one of the session's settings (model, effort, mode…). The person's choice is the new default for this agent. */
194
409
  async setSetting(id, value) {
195
410
  if (!this.sessionId || !this.connection) throw new Error("No agent is connected.");
196
411
  this.settings = keepInitial(await applySetting(this.connection, this.sessionId, this.settings, id, value), this.settings);
197
- this.publish();
412
+ const d = this.store.defaultAgent();
413
+ if (d && agentKey(d.agent) === this.key) this.store.setDefaultAgent({ ...d, settings: { ...d.settings, [id]: value } });
414
+ this.onChange?.();
198
415
  }
199
- /** The person's answer to a permission request. */
416
+ /** The person's answer to a permission request. False when no request has this id. */
200
417
  choose(messageId, optionId) {
201
- this.choices.get(messageId)?.(optionId);
202
- }
203
- reset() {
204
- this.agent = void 0;
205
- this.connection = void 0;
206
- this.sessionId = void 0;
207
- this.queue = [];
208
- this.busy = false;
209
- this.writing = void 0;
210
- this.tools.clear();
211
- this.choices.clear();
212
- this.state.setSession(null, null);
418
+ const choose = this.choices.get(messageId);
419
+ choose?.(optionId);
420
+ return !!choose;
213
421
  }
214
- publish() {
215
- if (!this.spec || !this.sessionId) return this.state.setSession(null, null);
216
- this.state.setSession({ providerId: this.spec.id, name: this.spec.name, cwd: this.cwd, busy: this.busy, settings: this.settings }, (q) => this.enqueue(q));
422
+ status() {
423
+ return { providerId: this.spec?.id ?? "", name: this.spec?.name ?? "", cwd: this.cwd, busy: this.working, settings: this.settings };
217
424
  }
218
- enqueue(q) {
425
+ /** A question from the person. */
426
+ ask(q) {
219
427
  this.queue.push(q);
220
428
  void this.drain();
221
429
  }
430
+ /** Puts a message in the project's thread. */
431
+ put(m) {
432
+ const out = this.state.put(m, this.project);
433
+ if (this.replaying) this.history.add(out.id);
434
+ return out;
435
+ }
436
+ /** The default agent's settings, where the session's differ. A setting the agent does not offer, or refuses, stays as it is. */
437
+ async applyDefaults() {
438
+ const d = this.store.defaultAgent();
439
+ if (!d || agentKey(d.agent) !== this.key) return;
440
+ for (const [id, value] of Object.entries(d.settings)) {
441
+ const s = this.settings.find((x) => x.id === id);
442
+ if (!s || s.current === value || !this.sessionId || !this.connection) continue;
443
+ try {
444
+ this.settings = keepInitial(await applySetting(this.connection, this.sessionId, this.settings, id, value), this.settings);
445
+ } catch {
446
+ }
447
+ }
448
+ }
222
449
  /** Sends questions one at a time: an agent answers one prompt per turn. */
223
450
  async drain() {
224
- if (this.busy || !this.sessionId || !this.connection) return;
451
+ if (this.working || !this.sessionId || !this.connection) return;
225
452
  const q = this.queue.shift();
226
453
  if (!q) return;
227
- this.busy = true;
228
- this.publish();
454
+ const run3 = this.run;
455
+ this.working = true;
456
+ this.onChange?.();
229
457
  this.writing = void 0;
230
458
  try {
231
459
  await this.connection.agent.request(methods.agent.session.prompt, { sessionId: this.sessionId, prompt: [{ type: "text", text: this.promptFor(q) }] });
232
460
  } catch (e) {
233
- this.state.put({ from: "notice", text: `The request failed: ${e instanceof Error ? e.message : String(e)}`, tone: "error" });
461
+ if (run3 === this.run) this.put({ from: "notice", text: `The request failed: ${e instanceof Error ? e.message : String(e)}`, tone: "error" });
234
462
  } finally {
235
- const last = this.writing;
236
- if (last) this.state.put({ ...last, done: true });
237
- this.writing = void 0;
238
- this.busy = false;
239
- this.publish();
240
- void this.drain();
463
+ if (run3 === this.run) {
464
+ const last = this.writing;
465
+ if (last) this.put({ ...last, done: true });
466
+ this.writing = void 0;
467
+ this.working = false;
468
+ this.onChange?.();
469
+ void this.drain();
470
+ }
241
471
  }
242
472
  }
243
473
  /** The person's words, with where they are, and the first time, how to work with Poney. */
@@ -253,40 +483,52 @@ ${about.join("\n")}`);
253
483
  if (!this.briefed) {
254
484
  this.briefed = true;
255
485
  parts.unshift(briefing(this.cwd));
256
- } else if (!this.systemPrompt) parts.unshift(`[Poney Studio: explain the code in ${this.cwd}, with Poney documents when a picture helps. Say so briefly if the request is about something else.]`);
486
+ } else if (!this.systemPrompt) parts.unshift(reminder(this.cwd));
257
487
  return parts.join("\n\n");
258
488
  }
259
489
  onUpdate(n) {
260
490
  if (n.sessionId !== this.sessionId) return;
261
491
  const u = n.update;
492
+ if (this.replaying && this.keepThread && ["user_message_chunk", "agent_message_chunk", "tool_call", "tool_call_update"].includes(u.sessionUpdate)) return;
262
493
  switch (u.sessionUpdate) {
494
+ case "user_message_chunk": {
495
+ if (!this.replaying || u.content.type !== "text") return;
496
+ if (this.writing) this.put({ ...this.writing, done: true });
497
+ this.writing = void 0;
498
+ this.asked = (this.asking ? this.asked : "") + u.content.text;
499
+ const text = personWords(this.asked, this.cwd);
500
+ this.asking = this.put(this.asking ? { ...this.asking, text } : { from: "person", text });
501
+ return;
502
+ }
263
503
  case "agent_message_chunk": {
264
504
  if (u.content.type !== "text") return;
505
+ this.asking = void 0;
265
506
  const text = (this.writing?.text ?? "") + u.content.text;
266
- this.writing = this.state.put(this.writing ? { ...this.writing, text } : { from: "agent", text });
507
+ this.writing = this.put(this.writing ? { ...this.writing, text } : { from: "agent", text });
267
508
  return;
268
509
  }
269
510
  case "tool_call": {
270
- if (this.writing) this.state.put({ ...this.writing, done: true });
511
+ this.asking = void 0;
512
+ if (this.writing) this.put({ ...this.writing, done: true });
271
513
  this.writing = void 0;
272
- const m = this.state.put({ from: "tool", title: u.title, status: u.status ?? "pending", kind: u.kind });
514
+ const m = this.put({ from: "tool", title: u.title, status: u.status ?? "pending", kind: u.kind });
273
515
  this.tools.set(u.toolCallId, m);
274
516
  return;
275
517
  }
276
518
  case "config_option_update": {
277
519
  this.settings = keepInitial([...fromConfigOptions(u.configOptions), ...this.settings.filter((s) => s.via !== "config")], this.settings);
278
- this.publish();
520
+ this.onChange?.();
279
521
  return;
280
522
  }
281
523
  case "current_mode_update": {
282
524
  this.settings = this.settings.map((s) => s.via === "mode" ? { ...s, current: u.currentModeId } : s);
283
- this.publish();
525
+ this.onChange?.();
284
526
  return;
285
527
  }
286
528
  case "tool_call_update": {
287
529
  const m = this.tools.get(u.toolCallId);
288
530
  if (!m) return;
289
- this.tools.set(u.toolCallId, this.state.put({ ...m, title: u.title ?? m.title, status: u.status ?? m.status }));
531
+ this.tools.set(u.toolCallId, this.put({ ...m, title: u.title ?? m.title, status: u.status ?? m.status }));
290
532
  return;
291
533
  }
292
534
  default:
@@ -294,14 +536,25 @@ ${about.join("\n")}`);
294
536
  }
295
537
  }
296
538
  async onPermission(p) {
297
- const m = this.state.put({ from: "permission", title: p.toolCall.title ?? "The agent asks to continue", options: p.options.map((o) => ({ id: o.optionId, name: o.name, kind: o.kind })) });
539
+ const m = this.put({ from: "permission", title: p.toolCall.title ?? "The agent asks to continue", options: p.options.map((o) => ({ id: o.optionId, name: o.name, kind: o.kind })) });
298
540
  const optionId = await new Promise((resolve2) => this.choices.set(m.id, resolve2));
299
541
  this.choices.delete(m.id);
300
- this.state.put({ ...m, chosen: optionId ?? "cancelled" });
542
+ this.put({ ...m, chosen: optionId ?? "cancelled" });
301
543
  return { outcome: optionId ? { outcome: "selected", optionId } : { outcome: "cancelled" } };
302
544
  }
303
545
  };
304
546
  var keepInitial = (next, before) => next.map((s) => ({ ...s, initial: before.find((b) => b.id === s.id)?.initial ?? s.initial }));
547
+ var reminder = (cwd) => `[Poney Studio: explain the code in ${cwd}, with Poney documents when a picture helps. Say so briefly if the request is about something else.]`;
548
+ var WHERE = ["[They are reading ", "[They selected ", "[The question is about:"];
549
+ function personWords(sent, cwd) {
550
+ let text = sent;
551
+ for (const head of [briefing(cwd), reminder(cwd)]) if (text.startsWith(`${head}
552
+
553
+ `)) text = text.slice(head.length + 2);
554
+ const end = text.indexOf("]\n\n");
555
+ if (WHERE.some((w) => text.startsWith(w)) && end >= 0) text = text.slice(end + 3);
556
+ return text;
557
+ }
305
558
  function briefing(cwd) {
306
559
  return `You work for a person in Poney Studio. Poney Studio shows walkthroughs and tours of the code in ${cwd} as diagrams and scenes. Your job is to help the person understand this code, and the way you answer is with Poney documents.
307
560
 
@@ -319,6 +572,149 @@ How to answer questions:
319
572
  - If the person asks for something outside this code, say so briefly.`;
320
573
  }
321
574
 
575
+ // src/agents/pool.ts
576
+ var providerFor = (r, providers = builtInProviders) => "custom" in r && r.custom ? customProvider(r.custom.name, r.custom.command) : providers().find((p) => p.id === ("providerId" in r ? r.providerId : void 0));
577
+ var AgentPool = class {
578
+ constructor(state, mcp, store = new SessionStore(), max = 2, providers = builtInProviders, autoStart = false) {
579
+ this.state = state;
580
+ this.mcp = mcp;
581
+ this.store = store;
582
+ this.max = max;
583
+ this.providers = providers;
584
+ this.autoStart = autoStart;
585
+ state.on("workspace", () => void this.activate());
586
+ }
587
+ state;
588
+ mcp;
589
+ store;
590
+ max;
591
+ providers;
592
+ autoStart;
593
+ /** By project, the agent activated longest ago first. */
594
+ agents = /* @__PURE__ */ new Map();
595
+ /** Settles when the agent has started, or failed to. */
596
+ ready = /* @__PURE__ */ new WeakMap();
597
+ /** The agent of a project, if it runs or starts. */
598
+ get(project) {
599
+ return this.agents.get(project);
600
+ }
601
+ /** The open project's agent. */
602
+ active() {
603
+ return this.agents.get(this.state.projectKey());
604
+ }
605
+ /**
606
+ * Gives the person the open project's agent: the one that runs, or the default agent, started now
607
+ * when `start` (by default: when the pool may start agents by itself and no agent listens over MCP). Never throws.
608
+ */
609
+ async activate(start = this.autoStart && !this.state.status().listening) {
610
+ try {
611
+ await this.activateNow(start);
612
+ } catch (e) {
613
+ this.state.put({ from: "notice", text: e instanceof Error ? e.message : String(e), tone: "error" });
614
+ this.state.setSession(null, null);
615
+ }
616
+ }
617
+ async activateNow(start) {
618
+ const project = this.state.projectKey();
619
+ if (!project) return this.state.setSession(null, null);
620
+ let agent = this.agents.get(project);
621
+ if (agent) {
622
+ this.agents.delete(project);
623
+ this.agents.set(project, agent);
624
+ } else if (start) {
625
+ const d = this.store.defaultAgent();
626
+ if (d) agent = this.start(project, d.agent, this.state.project.cwd);
627
+ }
628
+ if (!agent) return this.state.setSession(null, null);
629
+ this.publish(agent);
630
+ await this.ready.get(agent);
631
+ this.publish(agent);
632
+ this.trim();
633
+ }
634
+ /** Makes an agent the default, and starts it for the open project. */
635
+ async connect(choice) {
636
+ const project = this.state.projectKey();
637
+ if (!project) throw new Error("Open a project first.");
638
+ const key = this.setDefault(choice);
639
+ const running = this.agents.get(project);
640
+ if (running && running.agentKey !== key) {
641
+ this.agents.delete(project);
642
+ running.stop();
643
+ }
644
+ await this.activate(true);
645
+ }
646
+ /** Makes an agent the default, without starting it. Returns its key. */
647
+ setDefault(choice) {
648
+ const key = agentKey(choice);
649
+ const d = this.store.defaultAgent();
650
+ this.store.setDefaultAgent({ agent: choice, settings: d && agentKey(d.agent) === key ? d.settings : {} });
651
+ return key;
652
+ }
653
+ /** The default agent, if the person chose one. */
654
+ defaultAgent() {
655
+ return this.store.defaultAgent()?.agent;
656
+ }
657
+ /** Stops the open project's agent. The default agent stays. */
658
+ async disconnect() {
659
+ const project = this.state.projectKey();
660
+ const agent = this.agents.get(project);
661
+ this.agents.delete(project);
662
+ agent?.stop();
663
+ this.state.setSession(null, null);
664
+ }
665
+ stopAll() {
666
+ const agents = [...this.agents.values()];
667
+ this.agents.clear();
668
+ for (const agent of agents) agent.stop();
669
+ this.state.setSession(null, null);
670
+ }
671
+ start(project, choice, cwd) {
672
+ const agent = new ProjectAgent(this.state, project, this.mcp, this.store);
673
+ agent.onChange = () => this.changed(agent);
674
+ this.agents.set(project, agent);
675
+ let started;
676
+ try {
677
+ const spec = providerFor(choice, this.providers);
678
+ started = spec ? agent.start(spec, choice, cwd) : Promise.reject(new Error(`Poney does not know the agent "${agentKey(choice)}".`));
679
+ } catch (e) {
680
+ started = Promise.reject(e);
681
+ }
682
+ this.ready.set(
683
+ agent,
684
+ started.catch((e) => {
685
+ if (this.agents.get(project) !== agent) return;
686
+ this.agents.delete(project);
687
+ this.state.put({ from: "notice", text: e instanceof Error ? e.message : String(e), tone: "error" }, project);
688
+ if (this.state.projectKey() === project) this.state.setSession(null, null);
689
+ })
690
+ );
691
+ return agent;
692
+ }
693
+ /** An agent's status changed: only the open project's agent shows. An agent that stopped leaves the pool. */
694
+ changed(agent) {
695
+ if (this.agents.get(agent.project) !== agent) return;
696
+ if (agent.connected) return this.publish(agent);
697
+ this.agents.delete(agent.project);
698
+ if (this.state.projectKey() === agent.project) this.state.setSession(null, null);
699
+ }
700
+ publish(agent) {
701
+ if (agent.project !== this.state.projectKey() || this.agents.get(agent.project) !== agent) return;
702
+ if (!agent.connected) return this.state.setSession(null, null);
703
+ this.state.setSession(agent.status(), (q) => agent.ask(q));
704
+ for (const q of this.state.takeQuestions(agent.project, agent.history)) agent.ask(q);
705
+ }
706
+ /** Above the limit, stops the agents activated longest ago, but never one that works or waits for the person. */
707
+ trim() {
708
+ const open = this.state.projectKey();
709
+ for (const [project, agent] of this.agents) {
710
+ if (this.agents.size <= this.max) return;
711
+ if (project === open || agent.busy || agent.pendingChoices) continue;
712
+ this.agents.delete(project);
713
+ agent.stop();
714
+ }
715
+ }
716
+ };
717
+
322
718
  // src/live/api.ts
323
719
  var LocalLive = class {
324
720
  constructor(state, server) {
@@ -363,10 +759,12 @@ var RemoteLive = class {
363
759
  return await res.json();
364
760
  }
365
761
  open(document) {
366
- return this.call("/api/live/open", { body: { document } });
762
+ const project = process.env.PONEY_PROJECT;
763
+ return this.call("/api/live/open", { body: { document, ...project ? { project } : {} } });
367
764
  }
368
765
  read() {
369
- return this.call("/api/live/read");
766
+ const project = process.env.PONEY_PROJECT;
767
+ return this.call(`/api/live/read${project ? `?project=${encodeURIComponent(project)}` : ""}`);
370
768
  }
371
769
  waitForQuestions(timeoutMs) {
372
770
  return this.call(`/api/live/wait?timeout=${timeoutMs}`, { timeoutMs: timeoutMs + 1e4 });
@@ -385,89 +783,6 @@ async function isPoneyHub(url) {
385
783
  return false;
386
784
  }
387
785
  }
388
- var require2 = createRequire(import.meta.url);
389
- var exec = promisify(execFile);
390
- function packageBin(pkg) {
391
- try {
392
- const manifest = require2.resolve(`${pkg}/package.json`);
393
- const { bin } = require2(manifest);
394
- const file = typeof bin === "string" ? bin : bin && Object.values(bin)[0];
395
- return file ? join(dirname(manifest), file) : void 0;
396
- } catch {
397
- return void 0;
398
- }
399
- }
400
- function onPath(program) {
401
- for (const dir of (process.env.PATH ?? "").split(delimiter)) {
402
- if (!dir) continue;
403
- const file = join(dir, program);
404
- try {
405
- accessSync(file, constants.X_OK);
406
- return file;
407
- } catch {
408
- }
409
- }
410
- return void 0;
411
- }
412
- async function run(command, args) {
413
- try {
414
- const { stdout, stderr } = await exec(command, args, { timeout: 2e4, env: { ...process.env, NO_COLOR: "1" } });
415
- return { code: 0, out: strip(`${stdout}${stderr}`) };
416
- } catch (e) {
417
- const err = e;
418
- return { code: typeof err.code === "number" ? err.code : 1, out: strip(`${err.stdout ?? ""}${err.stderr ?? err.message}`) };
419
- }
420
- }
421
- var strip = (t) => t.replace(/\x1b\[[0-9;]*m/g, "").trim();
422
- async function claudeStatus() {
423
- const bin = onPath("claude");
424
- if (!bin) return void 0;
425
- const { out } = await run(bin, ["auth", "status"]);
426
- try {
427
- const s = JSON.parse(out.slice(out.indexOf("{")));
428
- return s.loggedIn ? { state: "ready", detail: `Signed in${s.authMethod ? ` with ${s.authMethod}` : ""}${s.configDirectory ? ` (${s.configDirectory.replace(homedir(), "~")})` : ""}.` } : { state: "sign-in", detail: "Not signed in." };
429
- } catch {
430
- return { state: "unsure", detail: "Claude Code did not say whether it is signed in." };
431
- }
432
- }
433
- async function codexStatus() {
434
- const bin = onPath("codex");
435
- if (!bin) return void 0;
436
- const { code, out } = await run(bin, ["login", "status"]);
437
- return code === 0 ? { state: "ready", detail: `${out.split("\n")[0] || "Signed in"}.` } : { state: "sign-in", detail: out.split("\n")[0] || "Not signed in." };
438
- }
439
- async function opencodeStatus(bin) {
440
- const { out } = await run(bin, ["auth", "list"]);
441
- const stored = Number(/(\d+)\s+credentials?/i.exec(out)?.[1] ?? 0);
442
- const fromEnv = [...out.matchAll(/●\s+(.+?)\s+([A-Z][A-Z0-9_]+)\s*$/gm)].map((m) => `${m[1]} (${m[2]})`);
443
- if (stored > 0) return { state: "ready", detail: `${stored} stored sign-in${stored > 1 ? "s" : ""}.` };
444
- if (fromEnv.length) return { state: "unsure", detail: `No stored sign-in. It can only use keys from your environment: ${fromEnv.join(", ")}.` };
445
- return { state: "sign-in", detail: "No sign-in, and no provider key in the environment." };
446
- }
447
- function builtInProviders() {
448
- const claude = packageBin("@agentclientprotocol/claude-agent-acp");
449
- const codex = packageBin("@agentclientprotocol/codex-acp");
450
- const opencode = onPath("opencode");
451
- const copilot = onPath("copilot");
452
- return [
453
- { id: "claude-code", name: "Claude Code", command: process.execPath, args: claude ? [claude] : [], available: !!claude, install: "Reinstall Poney's dependencies (npm install).", signIn: 'Run "claude" in a terminal and sign in with /login.', status: claudeStatus },
454
- { id: "codex", name: "OpenAI Codex", command: process.execPath, args: codex ? [codex] : [], available: !!codex, install: "Reinstall Poney's dependencies (npm install).", signIn: 'Run "codex login" in a terminal.', status: codexStatus },
455
- { id: "opencode", name: "OpenCode", command: opencode ?? "opencode", args: ["acp"], available: !!opencode, install: "Install OpenCode: https://opencode.ai", signIn: 'Run "opencode auth login" in a terminal.', status: opencode ? () => opencodeStatus(opencode) : void 0 },
456
- { id: "copilot", name: "GitHub Copilot", command: copilot ?? "copilot", args: ["--acp", "--stdio"], available: !!copilot, install: "Install the Copilot CLI: npm install -g @github/copilot", signIn: 'Run "copilot" in a terminal and sign in with /login.' }
457
- ];
458
- }
459
- function parseCommand(line) {
460
- const words = [...line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((m) => m[1] ?? m[2] ?? m[3]);
461
- if (!words.length) return void 0;
462
- return { command: words[0], args: words.slice(1) };
463
- }
464
- function customProvider(name, commandLine) {
465
- const parsed = parseCommand(commandLine);
466
- if (!parsed) return void 0;
467
- const found = parsed.command.includes("/") ? parsed.command : onPath(parsed.command);
468
- return { id: `custom:${name}`, name, ...parsed, command: found ?? parsed.command, available: !!found, install: `"${parsed.command}" is not on PATH.`, signIn: "Sign in as the agent's documentation says.", custom: true };
469
- }
470
- var describeProvider = ({ id, name, install, available, signIn, custom }) => ({ id, name, install, available, signIn, ...custom ? { custom } : {} });
471
786
  var run2 = promisify(execFile);
472
787
  var CLONES = join(homedir(), ".poney", "workspaces");
473
788
  var isGit = (dir) => existsSync(join(dir, ".git"));
@@ -483,7 +798,7 @@ function listFolders(path) {
483
798
  function checkFolder(path) {
484
799
  const dir = resolve(path);
485
800
  if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new Error(`No folder "${dir}"`);
486
- return dir;
801
+ return realpathSync(dir);
487
802
  }
488
803
  var GIT_URL = /^(https:\/\/[\w.@:/~-]+|git@[\w.-]+:[\w./~-]+|ssh:\/\/[\w.@:/~-]+)$/;
489
804
  async function cloneRepository(url) {
@@ -560,6 +875,19 @@ async function check2(spec) {
560
875
  return { state: "error", detail: e instanceof Error ? e.message : String(e) };
561
876
  }
562
877
  }
878
+ function workspaceProject(cwd) {
879
+ const name = basename(cwd) || "workspace";
880
+ const id = name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "workspace";
881
+ return { cwd, id, name };
882
+ }
883
+ function emptyDocument(w) {
884
+ return { poneyVersion: "0.1.0", project: { id: w.id, name: w.name, description: `The code in ${w.cwd}.` }, model: {}, views: [], walkthroughs: [] };
885
+ }
886
+ function intoWorkspace(document, w) {
887
+ if (!document || typeof document !== "object") return document;
888
+ const d = document;
889
+ return { ...d, project: { ...d.project ?? {}, id: w.id, name: d.project?.name ?? w.name } };
890
+ }
563
891
  var SOURCES = ["../../src", "../../../core/src", "../../../react/src", "../../../layout/src"].map((p) => fileURLToPath(new URL(p, import.meta.url)));
564
892
  function buildStamp() {
565
893
  let newest = 0;
@@ -592,11 +920,13 @@ var TYPES = {
592
920
  ".png": "image/png",
593
921
  ".json": "application/json"
594
922
  };
923
+ var NOT_VALID = "The project's file is not a valid document.";
924
+ var NOT_SAVED = `${NOT_VALID} Not saved.`;
595
925
  var DEV_ORIGINS = ["http://localhost:5173", "http://127.0.0.1:5173"];
596
926
  var LiveServer = class {
597
- constructor(state, bridge, files) {
927
+ constructor(state, agents, files) {
598
928
  this.state = state;
599
- this.bridge = bridge;
929
+ this.agents = agents;
600
930
  this.files = files;
601
931
  const send = (event, data) => {
602
932
  const payload = `event: ${event}
@@ -607,13 +937,14 @@ data: ${JSON.stringify(data)}
607
937
  };
608
938
  state.on("document", (revision, document, source) => send("document", { revision, document, source }));
609
939
  state.on("message", (message) => send("message", message));
940
+ state.on("thread", (messages) => send("thread", { messages }));
610
941
  state.on("agent", (status) => send("agent", status));
611
942
  state.on("file", (path) => send("file", { path: path ?? null }));
612
943
  state.on("workspace", (w) => send("project", { root: w?.cwd ?? null, name: w?.name ?? null }));
613
944
  state.on("overlays", (o) => send("overlays", o));
614
945
  }
615
946
  state;
616
- bridge;
947
+ agents;
617
948
  files;
618
949
  server;
619
950
  clients = /* @__PURE__ */ new Set();
@@ -660,7 +991,7 @@ data: ${JSON.stringify(data)}
660
991
  stop() {
661
992
  this.state.close();
662
993
  this.files?.close();
663
- void this.bridge?.disconnect();
994
+ this.agents?.stopAll();
664
995
  for (const c of this.clients) c.end();
665
996
  this.server?.close();
666
997
  }
@@ -705,12 +1036,29 @@ data: ${JSON.stringify(data)}
705
1036
  s.report(await body(req));
706
1037
  return void res.writeHead(204).end();
707
1038
  case "POST /api/live/open": {
708
- const { document } = await body(req);
1039
+ const { document, project } = await body(req);
709
1040
  if (document === void 0) return json(res, 400, { error: "Give a document" });
1041
+ if (project && project !== s.projectKey()) {
1042
+ if (!this.files) return json(res, 400, { error: "This hub cannot save documents." });
1043
+ const w = workspaceProject(checkFolder(project));
1044
+ const saved = this.files.saveFor(w, document);
1045
+ if (saved === "invalid") return json(res, 200, { revision: s.shown()?.revision ?? 0, viewers: this.viewers, refused: NOT_SAVED });
1046
+ if (saved === "saved") {
1047
+ const name = document?.project?.name ?? w.name;
1048
+ s.put({ from: "notice", text: `The agent saved \u201C${name}\u201D. It shows when you open this project.`, tone: "info" }, project);
1049
+ }
1050
+ return json(res, 200, { revision: s.shown()?.revision ?? 0, viewers: this.viewers, saved: true });
1051
+ }
710
1052
  return json(res, 200, { revision: s.open(document), viewers: this.viewers });
711
1053
  }
712
- case "GET /api/live/read":
1054
+ case "GET /api/live/read": {
1055
+ const project = url.searchParams.get("project");
1056
+ if (project && project !== s.projectKey() && this.files) {
1057
+ const { document, invalid } = this.files.savedFor(workspaceProject(checkFolder(project)));
1058
+ return json(res, 200, { viewers: this.viewers, current: document ?? null, ...invalid ? { invalid: NOT_VALID } : {}, thread: s.thread(project) });
1059
+ }
713
1060
  return json(res, 200, { viewers: this.viewers, studio: s.studio, current: s.current(), thread: s.thread() });
1061
+ }
714
1062
  case "GET /api/live/wait": {
715
1063
  const ms = Math.min(9e5, Math.max(0, Number(url.searchParams.get("timeout") ?? 3e5)));
716
1064
  const questions = await s.waitForQuestions(ms);
@@ -730,7 +1078,7 @@ data: ${JSON.stringify(data)}
730
1078
  }
731
1079
  /* Agents the Studio starts */
732
1080
  case "GET /api/agent":
733
- return json(res, 200, { providers: builtInProviders().map(describeProvider), status: s.status(), canStart: !!this.bridge, mcpServer: mcpCommand() });
1081
+ return json(res, 200, { providers: builtInProviders().map(describeProvider), status: s.status(), defaultAgent: this.agents?.defaultAgent() ?? null, canStart: !!this.agents, mcpServer: mcpCommand() });
734
1082
  case "POST /api/agent/check": {
735
1083
  const r = await body(req);
736
1084
  const spec = providerFor(r);
@@ -738,40 +1086,46 @@ data: ${JSON.stringify(data)}
738
1086
  return json(res, 200, await checkProvider(spec, r.fresh));
739
1087
  }
740
1088
  case "POST /api/agent/connect": {
741
- if (!this.bridge) return json(res, 400, { error: "This hub cannot start agents." });
1089
+ if (!this.agents) return json(res, 400, { error: "This hub cannot start agents." });
742
1090
  const r = await body(req);
743
- const spec = providerFor(r);
744
- if (!spec) return json(res, 400, { error: "Unknown agent" });
745
- await this.bridge.connect(spec, checkFolder(r.cwd ?? ""));
1091
+ if (!providerFor(r)) return json(res, 400, { error: "Unknown agent" });
1092
+ if (r.folder) {
1093
+ const w = workspaceProject(checkFolder(r.folder));
1094
+ this.agents.setDefault(r);
1095
+ s.setWorkspace(w);
1096
+ }
1097
+ if (!s.project) return json(res, 400, { error: "Choose the folder with the code first." });
1098
+ await this.agents.connect(r);
746
1099
  return json(res, 200, s.status());
747
1100
  }
748
1101
  case "POST /api/agent/disconnect":
749
- await this.bridge?.disconnect();
1102
+ await this.agents?.disconnect();
750
1103
  return json(res, 200, s.status());
751
1104
  case "POST /api/agent/cancel":
752
- await this.bridge?.cancel();
1105
+ await this.agents?.active()?.cancel();
753
1106
  return json(res, 200, s.status());
754
1107
  case "POST /api/agent/setting": {
755
1108
  const r = await body(req);
756
- if (!this.bridge || !r.id || r.value === void 0) return json(res, 400, { error: "Give id and value" });
757
- await this.bridge.setSetting(r.id, r.value);
1109
+ const agent = this.agents?.active();
1110
+ if (!agent || !r.id || r.value === void 0) return json(res, 400, { error: "Give id and value" });
1111
+ await agent.setSetting(r.id, r.value);
758
1112
  return json(res, 200, s.status());
759
1113
  }
760
1114
  case "POST /api/agent/permission": {
761
1115
  const r = await body(req);
762
1116
  if (typeof r.messageId !== "number" || !r.optionId) return json(res, 400, { error: "Give messageId and optionId" });
763
- this.bridge?.choose(r.messageId, r.optionId);
1117
+ this.agents?.active()?.choose(r.messageId, r.optionId);
764
1118
  return json(res, 200, { ok: true });
765
1119
  }
766
1120
  /* The project folder */
767
1121
  case "GET /api/plugins": {
768
- const { available } = await import('./run-25PP2HWH.js');
1122
+ const { available } = await import('./run-AYEEUZVG.js');
769
1123
  const dir = s.project?.cwd;
770
1124
  if (!dir) return json(res, 200, { root: null, importers: [], overlays: [], problems: [] });
771
1125
  return json(res, 200, { root: dir, ...await available(dir) });
772
1126
  }
773
1127
  case "POST /api/import": {
774
- const { runImport } = await import('./run-25PP2HWH.js');
1128
+ const { runImport } = await import('./run-AYEEUZVG.js');
775
1129
  const r = await body(req);
776
1130
  if (!s.project) return json(res, 400, { error: "Choose the folder with the code first." });
777
1131
  const { document, summary } = await runImport(r.importer ?? "", s.project.cwd, { into: s.current(), path: r.path, store: r.store });
@@ -782,7 +1136,7 @@ ${checked.report}` });
782
1136
  return json(res, 200, { summary });
783
1137
  }
784
1138
  case "POST /api/overlays/run": {
785
- const { runOverlay } = await import('./run-25PP2HWH.js');
1139
+ const { runOverlay } = await import('./run-AYEEUZVG.js');
786
1140
  const r = await body(req);
787
1141
  if (!s.project) return json(res, 400, { error: "Choose the folder with the code first." });
788
1142
  const result = await runOverlay(r.id ?? "", s.project.cwd, s.current());
@@ -799,29 +1153,19 @@ ${checked.report}` });
799
1153
  s.setWorkspace(workspaceProject(checkFolder(r.path ?? "")));
800
1154
  return json(res, 200, { root: s.project?.cwd });
801
1155
  }
802
- case "POST /api/agent/connect-here": {
803
- if (!this.bridge) return json(res, 400, { error: "This hub cannot start agents." });
804
- const r = await body(req);
805
- if (r.folder) s.setWorkspace(workspaceProject(checkFolder(r.folder)), true);
806
- if (!s.project) return json(res, 400, { error: "Choose the folder with the code first." });
807
- const spec = providerFor(r);
808
- if (!spec) return json(res, 400, { error: "Unknown agent" });
809
- await this.bridge.connect(spec, s.project.cwd);
810
- return json(res, 200, s.status());
811
- }
812
1156
  /* Files */
813
1157
  case "POST /api/files/open": {
814
1158
  if (!this.files) return json(res, 400, { error: "This hub cannot open files." });
815
1159
  const r = await body(req);
816
1160
  if (!r.path) return json(res, 400, { error: "Give a path" });
817
- this.files.open(r.path);
818
- return json(res, 200, { path: r.path });
1161
+ this.files.open(r.path, r.document);
1162
+ return json(res, 200, { path: s.file });
819
1163
  }
820
1164
  /* Workspaces */
821
1165
  case "GET /api/workspace/folders":
822
1166
  return json(res, 200, listFolders(url.searchParams.get("path") ?? void 0));
823
1167
  case "GET /api/workspace/files": {
824
- const cwd = s.status().session?.cwd ?? (s.file ? dirname(s.file) : void 0);
1168
+ const cwd = s.project?.cwd ?? (s.file ? dirname(s.file) : void 0);
825
1169
  if (!cwd) return json(res, 200, { files: [] });
826
1170
  return json(res, 200, { root: cwd, files: await searchFiles(cwd, url.searchParams.get("q") ?? "") });
827
1171
  }
@@ -881,7 +1225,6 @@ data: ${JSON.stringify(this.state.overlays)}
881
1225
  res.end(readFileSync(file));
882
1226
  }
883
1227
  };
884
- var providerFor = (r) => r.custom ? customProvider(r.custom.name, r.custom.command) : builtInProviders().find((p) => p.id === r.providerId);
885
1228
  function json(res, status, value) {
886
1229
  res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(value));
887
1230
  }
@@ -906,9 +1249,11 @@ var LiveState = class extends EventEmitter {
906
1249
  document;
907
1250
  source = "agent";
908
1251
  revision = 0;
909
- messages = [];
910
- /** Questions an agent took over MCP (poney_wait). */
911
- delivered = 0;
1252
+ /** One conversation for each project, by folder. The empty key is the thread before any project opens. */
1253
+ threads = /* @__PURE__ */ new Map();
1254
+ lastId = 0;
1255
+ /** For each project, the last question an agent took over MCP (poney_wait). */
1256
+ delivered = /* @__PURE__ */ new Map();
912
1257
  waiters = /* @__PURE__ */ new Set();
913
1258
  responder = null;
914
1259
  session = null;
@@ -919,7 +1264,8 @@ var LiveState = class extends EventEmitter {
919
1264
  /* ─── The document ──────────────────────────────────────────────────── */
920
1265
  /** Shows a document in every open Studio. Returns its revision. While an agent works in a folder, the document joins that folder's project. */
921
1266
  open(document, source = "agent") {
922
- this.document = this.workspace && source === "agent" ? intoWorkspace(document, { ...this.workspace, id: this.openProjectId ?? this.workspace.id }) : document;
1267
+ const joins = !this.path || this.workspace && this.path.startsWith(`${this.workspace.cwd}/`);
1268
+ this.document = this.workspace && source === "agent" ? intoWorkspace(document, { ...this.workspace, id: (joins ? this.openProjectId : void 0) ?? this.workspace.id }) : document;
923
1269
  this.source = source;
924
1270
  this.revision++;
925
1271
  this.studio = void 0;
@@ -960,18 +1306,38 @@ var LiveState = class extends EventEmitter {
960
1306
  }
961
1307
  }
962
1308
  /* ─── The conversation ──────────────────────────────────────────────── */
963
- thread() {
964
- return [...this.messages];
965
- }
966
- /** Adds a message, or replaces the one with the same id. */
967
- put(input) {
968
- const existing = "id" in input ? this.messages.findIndex((m) => m.id === input.id) : -1;
969
- const message = existing >= 0 ? input : { ...input, id: this.messages.length + 1, at: (/* @__PURE__ */ new Date()).toISOString() };
970
- if (existing >= 0) this.messages[existing] = message;
971
- else this.messages.push(message);
972
- this.emit("message", message);
1309
+ /** The key of the open project's thread. */
1310
+ projectKey() {
1311
+ return this.workspace?.cwd ?? "";
1312
+ }
1313
+ thread(project = this.projectKey()) {
1314
+ return [...this.threads.get(project) ?? []];
1315
+ }
1316
+ /** Adds a message to a project's thread (the open project's by default), or replaces the one with the same id. Only the open project's messages are sent on. */
1317
+ put(input, project = this.projectKey()) {
1318
+ let messages = this.threads.get(project);
1319
+ if (!messages) this.threads.set(project, messages = []);
1320
+ const existing = "id" in input ? messages.findIndex((m) => m.id === input.id) : -1;
1321
+ const message = existing >= 0 ? input : { ...input, id: ++this.lastId, at: (/* @__PURE__ */ new Date()).toISOString() };
1322
+ if (existing >= 0) messages[existing] = message;
1323
+ else messages.push(message);
1324
+ if (project === this.projectKey()) this.emit("message", message);
973
1325
  return message;
974
1326
  }
1327
+ /** Removes messages from a project's thread. */
1328
+ remove(project, ids) {
1329
+ const messages = this.threads.get(project);
1330
+ if (!messages) return;
1331
+ this.threads.set(project, messages.filter((m) => !ids.has(m.id)));
1332
+ if (project === this.projectKey()) this.emit("thread", this.thread());
1333
+ }
1334
+ /** The person's questions in a project that no agent took yet, except `skip`. They count as taken now. */
1335
+ takeQuestions(project, skip = /* @__PURE__ */ new Set()) {
1336
+ const after = this.delivered.get(project) ?? 0;
1337
+ const asked = this.thread(project).filter((m) => m.from === "person" && m.id > after);
1338
+ if (asked.length) this.delivered.set(project, Math.max(...asked.map((m) => m.id)));
1339
+ return asked.filter((m) => !skip.has(m.id));
1340
+ }
975
1341
  /**
976
1342
  * A question from the person. An agent the Studio started answers at once;
977
1343
  * otherwise it waits for an agent that listens over MCP.
@@ -979,7 +1345,7 @@ var LiveState = class extends EventEmitter {
979
1345
  ask(text, place = {}) {
980
1346
  const m = this.put({ from: "person", text, ...place });
981
1347
  if (this.responder) {
982
- this.delivered = m.id;
1348
+ this.delivered.set(this.projectKey(), m.id);
983
1349
  this.responder(m);
984
1350
  } else for (const wake of this.waiters) wake();
985
1351
  return m;
@@ -994,7 +1360,8 @@ var LiveState = class extends EventEmitter {
994
1360
  */
995
1361
  async waitForQuestions(timeoutMs) {
996
1362
  if (this.responder) return [];
997
- const pending = () => this.messages.filter((m) => m.from === "person" && m.id > this.delivered);
1363
+ const project = this.projectKey();
1364
+ const pending = () => this.thread(project).filter((m) => m.from === "person" && m.id > (this.delivered.get(project) ?? 0));
998
1365
  if (!pending().length) {
999
1366
  let wake = () => {
1000
1367
  };
@@ -1008,7 +1375,7 @@ var LiveState = class extends EventEmitter {
1008
1375
  this.emitAgent();
1009
1376
  }
1010
1377
  const out = pending();
1011
- if (out.length) this.delivered = Math.max(this.delivered, ...out.map((m) => m.id));
1378
+ if (out.length) this.delivered.set(project, Math.max(this.delivered.get(project) ?? 0, ...out.map((m) => m.id)));
1012
1379
  return out;
1013
1380
  }
1014
1381
  /* ─── The workspace ─────────────────────────────────────────────────── */
@@ -1019,13 +1386,16 @@ var LiveState = class extends EventEmitter {
1019
1386
  /**
1020
1387
  * Opens a folder as the project, or, with a document tied to it, records
1021
1388
  * the folder it belongs to. What opens for it (its file, the document already
1022
- * open, or an empty project) is decided where files are known. With
1023
- * `keep`, the folder is only where agents work: the open document stays.
1389
+ * open, or an empty project) is decided where files are known.
1024
1390
  */
1025
- setWorkspace(w, keep = false) {
1026
- if (w?.cwd === this.workspace?.cwd) return;
1391
+ setWorkspace(w) {
1392
+ if (w?.cwd === this.workspace?.cwd) {
1393
+ if (!w || this.file?.startsWith(`${w.cwd}/`) && this.openProjectId === w.id) return;
1394
+ return void this.emit("workspace", w);
1395
+ }
1027
1396
  this.workspace = w;
1028
- this.emit("workspace", w, keep);
1397
+ this.emit("workspace", w);
1398
+ this.emit("thread", this.thread());
1029
1399
  }
1030
1400
  /** The id of the open document's project. */
1031
1401
  get openProjectId() {
@@ -1052,12 +1422,28 @@ var LiveState = class extends EventEmitter {
1052
1422
  };
1053
1423
  function repositoryOf(dir) {
1054
1424
  try {
1055
- return execFileSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
1425
+ const top = execFileSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
1426
+ return top ? realpathSync(top) : void 0;
1056
1427
  } catch {
1057
1428
  return void 0;
1058
1429
  }
1059
1430
  }
1431
+ function projectOf(path) {
1432
+ const inDocs = /^(.*)\/docs\/poney\/([^/]+\.poney)$/;
1433
+ if (!existsSync(path)) {
1434
+ const m = inDocs.exec(path);
1435
+ const root = m && existsSync(m[1]) ? realpathSync(m[1]) : void 0;
1436
+ return { root, file: root ? join(root, "docs", "poney", m[2]) : path };
1437
+ }
1438
+ const file = realpathSync(path);
1439
+ return { root: inDocs.exec(file)?.[1] ?? repositoryOf(dirname(file)), file };
1440
+ }
1060
1441
  var workspaceFile = (w) => join(w.cwd, "docs", "poney", `${w.id}.poney`);
1442
+ function invalidFile(path) {
1443
+ if (!existsSync(path)) return void 0;
1444
+ const { result, report } = check({ text: readFileSync(path, "utf8") });
1445
+ return result?.ok ? void 0 : report.split("\n")[0] || "Not a valid document.";
1446
+ }
1061
1447
  var isEmpty = (doc) => {
1062
1448
  const d = doc;
1063
1449
  return !d?.views?.length && !d?.walkthroughs?.length;
@@ -1069,7 +1455,7 @@ var DocumentFiles = class {
1069
1455
  if (source === "agent") this.save(doc);
1070
1456
  });
1071
1457
  state.on("edited", (doc) => this.save(doc));
1072
- state.on("workspace", (w, keep) => w && this.openWorkspace(w, keep));
1458
+ state.on("workspace", (w) => w && this.openWorkspace(w));
1073
1459
  }
1074
1460
  state;
1075
1461
  watcher;
@@ -1078,17 +1464,41 @@ var DocumentFiles = class {
1078
1464
  timer;
1079
1465
  /** The project the file holds. A document of another project releases the file; it never overwrites it. */
1080
1466
  project;
1081
- /** Opens a .poney file and ties the document to it. Throws with the check report when it is not a valid document. */
1082
- open(path) {
1467
+ /** The file a save was refused for, so the person is told once. */
1468
+ refused;
1469
+ /** The file each project is tied to, by project key (its folder). */
1470
+ tied = /* @__PURE__ */ new Map();
1471
+ /**
1472
+ * Opens a .poney file and ties the document to it, and its project (see projectOf) opens. Throws with the check report when it is not a valid document.
1473
+ * A file in docs/poney/ that was never written, with the document it holds (`given`, as a Studio gives it back to a hub that restarted), opens its project with that document.
1474
+ */
1475
+ open(path, given) {
1476
+ const { root, file } = projectOf(path);
1477
+ if (!existsSync(file) && root && given !== void 0) {
1478
+ this.tie(void 0);
1479
+ this.state.open(given, "file");
1480
+ return this.state.setWorkspace(workspaceProject(root));
1481
+ }
1482
+ this.load(file, root);
1483
+ }
1484
+ /** The file of a project: the one it is tied to, else the only .poney file in its docs/poney/, else the folder's own name there. */
1485
+ fileOf(w) {
1486
+ const tied = this.tied.get(w.cwd);
1487
+ if (tied) return tied;
1488
+ const dir = join(w.cwd, "docs", "poney");
1489
+ const found = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".poney")) : [];
1490
+ return found.length === 1 ? join(dir, found[0]) : workspaceFile(w);
1491
+ }
1492
+ load(path, root) {
1083
1493
  const text = readFileSync(path, "utf8");
1084
1494
  const { result, report } = check({ text });
1085
1495
  if (!result?.ok) throw new Error(`"${path}" is not a valid Poney document.
1086
1496
  ${report}`);
1087
1497
  const doc = JSON.parse(text);
1088
1498
  this.tie(path, doc.project?.id, text);
1499
+ if (root) this.tied.set(root, path);
1089
1500
  this.state.open(doc, "file");
1090
- const root = repositoryOf(dirname(path));
1091
- if (root && root !== this.state.project?.cwd) this.state.setWorkspace(workspaceProject(root));
1501
+ if (root !== this.state.project?.cwd) this.state.setWorkspace(root ? workspaceProject(root) : void 0);
1092
1502
  }
1093
1503
  /**
1094
1504
  * A project folder. The document already open stays when it belongs here,
@@ -1096,25 +1506,30 @@ ${report}`);
1096
1506
  * the folder's own file opens, or an empty project that becomes a file when
1097
1507
  * there is something to keep.
1098
1508
  */
1099
- openWorkspace(w, keep = false) {
1509
+ openWorkspace(w) {
1100
1510
  const open = this.state.shown()?.document;
1101
1511
  const file = this.state.file;
1102
1512
  if (file && file.startsWith(`${w.cwd}/`)) return;
1103
- if (keep && file && open && !isEmpty(open)) return;
1104
1513
  if (open && !file && !isEmpty(open)) {
1105
1514
  const id = this.state.openProjectId ?? w.id;
1106
- this.tie(join(w.cwd, "docs", "poney", `${id}.poney`), id);
1515
+ const path2 = join(w.cwd, "docs", "poney", `${id}.poney`);
1516
+ this.tie(path2, id);
1517
+ this.tied.set(w.cwd, path2);
1107
1518
  return this.save(open);
1108
1519
  }
1109
- const path = workspaceFile(w);
1520
+ const path = this.fileOf(w);
1110
1521
  if (existsSync(path)) {
1111
1522
  try {
1112
- return this.open(path);
1523
+ return this.load(path, w.cwd);
1113
1524
  } catch (e) {
1114
1525
  this.state.put({ from: "notice", text: e instanceof Error ? e.message.split("\n")[0] : String(e), tone: "error" });
1526
+ this.tie(void 0);
1527
+ if (this.state.openProjectId !== w.id) this.state.open(emptyDocument(w), "workspace");
1528
+ return;
1115
1529
  }
1116
1530
  }
1117
1531
  this.tie(path, w.id);
1532
+ this.tied.set(w.cwd, path);
1118
1533
  if (this.state.openProjectId !== w.id) this.state.open(emptyDocument(w), "workspace");
1119
1534
  }
1120
1535
  tie(path, project, text) {
@@ -1126,15 +1541,49 @@ ${report}`);
1126
1541
  if (!path) return;
1127
1542
  if (existsSync(path)) this.watch(path);
1128
1543
  }
1544
+ /**
1545
+ * Saves a document into another project's file, whether or not that project is open.
1546
+ * Nothing for an empty document or when unchanged, and never over a file that is not a valid document.
1547
+ */
1548
+ saveFor(w, doc) {
1549
+ const into = intoWorkspace(doc, w);
1550
+ if (isEmpty(into)) return "unchanged";
1551
+ const path = this.fileOf(w);
1552
+ if (invalidFile(path)) return "invalid";
1553
+ const text = `${JSON.stringify(into, null, 2)}
1554
+ `;
1555
+ if (existsSync(path) && readFileSync(path, "utf8") === text) return "unchanged";
1556
+ mkdirSync(dirname(path), { recursive: true });
1557
+ writeFileSync(path, text);
1558
+ return "saved";
1559
+ }
1560
+ /** The document saved in a project's file: none when the file is missing, `invalid` when it is not a valid document. */
1561
+ savedFor(w) {
1562
+ const path = this.fileOf(w);
1563
+ if (!existsSync(path)) return {};
1564
+ const invalid = invalidFile(path);
1565
+ return invalid ? { invalid } : { document: JSON.parse(readFileSync(path, "utf8")) };
1566
+ }
1129
1567
  /** Writes the document to its file, unless it is empty or unchanged. */
1130
1568
  save(doc) {
1131
1569
  const path = this.state.file;
1132
1570
  if (!path || isEmpty(doc)) return;
1133
1571
  const id = doc.project?.id;
1134
- if (this.project && id !== this.project) return this.tie(void 0);
1572
+ if (this.project && id !== this.project) {
1573
+ const w = this.state.project;
1574
+ if (!w || id !== w.id) return this.tie(void 0);
1575
+ this.tie(workspaceFile(w), w.id);
1576
+ return this.save(doc);
1577
+ }
1135
1578
  const text = `${JSON.stringify(doc, null, 2)}
1136
1579
  `;
1137
1580
  if (text === this.written) return;
1581
+ if (existsSync(path) && readFileSync(path, "utf8") !== this.written && invalidFile(path)) {
1582
+ if (this.refused !== path) this.state.put({ from: "notice", text: `${path} is not a valid document. Not saved.`, tone: "error" });
1583
+ this.refused = path;
1584
+ return;
1585
+ }
1586
+ this.refused = void 0;
1138
1587
  mkdirSync(dirname(path), { recursive: true });
1139
1588
  this.written = text;
1140
1589
  writeFileSync(path, text);
@@ -1161,14 +1610,14 @@ ${report}`);
1161
1610
  };
1162
1611
 
1163
1612
  // src/live/hub.ts
1164
- async function startHub(port) {
1613
+ async function startHub(port, options = {}) {
1165
1614
  const state = new LiveState();
1166
1615
  let server;
1167
- const bridge = new AgentBridge(state, () => ({ ...mcpCommand(), command: process.execPath, hubUrl: server.url }));
1616
+ const agents = new AgentPool(state, () => ({ ...mcpCommand(), command: process.execPath, hubUrl: server.url }), void 0, void 0, void 0, options.autoStart);
1168
1617
  const files = new DocumentFiles(state);
1169
- server = new LiveServer(state, bridge, files);
1618
+ server = new LiveServer(state, agents, files);
1170
1619
  await server.start(port);
1171
- return { state, files, server, live: new LocalLive(state, server), bridge };
1620
+ return { state, files, server, live: new LocalLive(state, server), agents };
1172
1621
  }
1173
1622
  async function attachOrStart() {
1174
1623
  const given = process.env.PONEY_HUB_URL;
@@ -1180,5 +1629,5 @@ async function attachOrStart() {
1180
1629
  }
1181
1630
 
1182
1631
  export { attachOrStart, startHub };
1183
- //# sourceMappingURL=chunk-BCOS4LFB.js.map
1184
- //# sourceMappingURL=chunk-BCOS4LFB.js.map
1632
+ //# sourceMappingURL=chunk-FN43OHT5.js.map
1633
+ //# sourceMappingURL=chunk-FN43OHT5.js.map