personal-bot 0.3.7 → 0.4.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 (111) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +5 -8
  4. package/README.zh-CN.md +5 -8
  5. package/bin/pbot-pi-acp.mjs +1 -1
  6. package/docs/architecture/design.md +2 -2
  7. package/docs/architecture/extensibility.md +1 -1
  8. package/docs/guides/cross-harness-workers.md +4 -4
  9. package/docs/guides/history.md +1 -3
  10. package/docs/guides/workspace-configuration.md +4 -4
  11. package/docs/hosts/claude-code.md +2 -2
  12. package/docs/hosts/codex-qoder.md +1 -1
  13. package/lib/antigravity-plugin/bin/pbot-pi-acp.mjs +1 -1
  14. package/lib/antigravity-plugin/lib/extension/acp/member.d.ts +1 -1
  15. package/lib/antigravity-plugin/lib/extension/acp/member.js +11 -10
  16. package/lib/antigravity-plugin/lib/extension/acp-worker.js +346 -201
  17. package/lib/antigravity-plugin/lib/extension/cli.js +563 -538
  18. package/lib/antigravity-plugin/lib/extension/hosts/dsh/acp-member.js +1 -1
  19. package/lib/antigravity-plugin/lib/extension/hosts/pi/acp-member.js +3 -4
  20. package/lib/antigravity-plugin/lib/extension/hosts/plugin-runtime.js +0 -11
  21. package/lib/antigravity-plugin/lib/extension/mcp.js +397 -278
  22. package/lib/antigravity-plugin/lib/model/acp.d.ts +29 -35
  23. package/lib/antigravity-plugin/lib/model/agent.d.ts +33 -17
  24. package/lib/antigravity-plugin/lib/model/agent.js +0 -1
  25. package/lib/antigravity-plugin/lib/storage/acp-files.d.ts +5 -8
  26. package/lib/antigravity-plugin/lib/storage/acp-files.js +34 -40
  27. package/lib/antigravity-plugin/lib/storage/agent-files.d.ts +19 -10
  28. package/lib/antigravity-plugin/lib/storage/agent-files.js +147 -43
  29. package/lib/antigravity-plugin/package.json +1 -1
  30. package/lib/antigravity-plugin/plugin.json +1 -1
  31. package/lib/codex-marketplace/plugins/personal-bot/.codex-plugin/plugin.json +1 -1
  32. package/lib/codex-marketplace/plugins/personal-bot/.mcp.json +2 -2
  33. package/lib/codex-marketplace/plugins/personal-bot/hooks/hooks.json +3 -3
  34. package/lib/codex-marketplace/plugins/personal-bot/skills/pbot/SKILL.md +1 -1
  35. package/lib/extension/acp/member.d.ts +1 -1
  36. package/lib/extension/acp/member.js +11 -10
  37. package/lib/extension/acp/worker.js +34 -33
  38. package/lib/extension/acp-worker.js +346 -201
  39. package/lib/extension/cli.js +563 -538
  40. package/lib/extension/hosts/dsh/acp-member.js +1 -1
  41. package/lib/extension/hosts/dsh/command.js +1 -1
  42. package/lib/extension/hosts/dsh/workspace.js +1 -3
  43. package/lib/extension/hosts/pi/acp-member.js +3 -4
  44. package/lib/extension/hosts/plugin-runtime.js +0 -11
  45. package/lib/extension/mcp/tool-contract.d.ts +8 -50
  46. package/lib/extension/mcp/tool-contract.js +0 -8
  47. package/lib/extension/mcp/workers.d.ts +7 -27
  48. package/lib/extension/mcp/workers.js +35 -17
  49. package/lib/extension/mcp.js +397 -278
  50. package/lib/integrations/acp/agents.d.ts +2 -3
  51. package/lib/integrations/acp/agents.js +22 -22
  52. package/lib/integrations/acp/harnesses/claude.js +1 -1
  53. package/lib/model/acp.d.ts +29 -35
  54. package/lib/model/agent.d.ts +33 -17
  55. package/lib/model/agent.js +0 -1
  56. package/lib/qoder-plugin/.mcp.json +2 -2
  57. package/lib/qoder-plugin/.qoder-plugin/plugin.json +1 -1
  58. package/lib/qoder-plugin/hooks/hooks.json +3 -3
  59. package/lib/qoder-plugin/skills/pbot/SKILL.md +1 -1
  60. package/lib/services/agents/acp-run.d.ts +6 -4
  61. package/lib/services/agents/acp-run.js +62 -43
  62. package/lib/services/agents/agent-run.d.ts +10 -6
  63. package/lib/services/agents/agent-run.js +142 -65
  64. package/lib/services/agents/agent-service.d.ts +3 -21
  65. package/lib/services/agents/agent-service.js +180 -126
  66. package/lib/storage/acp-files.d.ts +5 -8
  67. package/lib/storage/acp-files.js +34 -40
  68. package/lib/storage/agent-files.d.ts +19 -10
  69. package/lib/storage/agent-files.js +147 -43
  70. package/package.json +1 -1
  71. package/src/extension/acp/member.ts +14 -11
  72. package/src/extension/acp/worker.ts +31 -28
  73. package/src/extension/cli/commands/upgrade.ts +8 -36
  74. package/src/extension/cli/commands/workspace.ts +3 -8
  75. package/src/extension/cli/index.ts +1 -2
  76. package/src/extension/hosts/dsh/acp-member.ts +1 -1
  77. package/src/extension/hosts/dsh/command.ts +1 -1
  78. package/src/extension/hosts/dsh/workspace.ts +1 -3
  79. package/src/extension/hosts/pi/acp-member.ts +3 -4
  80. package/src/extension/hosts/pi/command.ts +1 -1
  81. package/src/extension/hosts/pi/lifecycle.ts +0 -2
  82. package/src/extension/hosts/plugin-runtime.ts +0 -10
  83. package/src/extension/mcp/tool-contract.ts +0 -8
  84. package/src/extension/mcp/workers.ts +34 -17
  85. package/src/integrations/acp/agents.ts +28 -27
  86. package/src/integrations/acp/harnesses/claude.ts +1 -1
  87. package/src/integrations/hosts/dsh/session.ts +2 -2
  88. package/src/integrations/installation/cli-update.ts +2 -2
  89. package/src/integrations/installation/installers/claude.ts +4 -4
  90. package/src/integrations/installation/installers/qoder.ts +5 -5
  91. package/src/integrations/installation/upgraders/antigravity.ts +57 -15
  92. package/src/integrations/installation/upgraders/claude.ts +1 -4
  93. package/src/integrations/installation/upgraders/codex.ts +85 -15
  94. package/src/integrations/installation/upgraders/dsh.ts +46 -24
  95. package/src/integrations/installation/upgraders/pi.ts +18 -11
  96. package/src/integrations/installation/upgraders/qoder.ts +95 -20
  97. package/src/model/acp.ts +27 -29
  98. package/src/model/agent.ts +80 -16
  99. package/src/model/installation.ts +0 -2
  100. package/src/pbot.ts +1 -1
  101. package/src/services/agents/acp-run.ts +81 -49
  102. package/src/services/agents/agent-run.ts +154 -56
  103. package/src/services/agents/agent-service.ts +204 -133
  104. package/src/services/installation/upgrade-service.ts +1 -5
  105. package/src/storage/acp-files.ts +50 -45
  106. package/src/storage/agent-files.ts +159 -46
  107. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.d.ts +0 -15
  108. package/lib/antigravity-plugin/lib/services/workspace/plugin-releases.js +0 -126
  109. package/lib/services/workspace/plugin-releases.d.ts +0 -15
  110. package/lib/services/workspace/plugin-releases.js +0 -126
  111. package/src/services/workspace/plugin-releases.ts +0 -121
@@ -6,8 +6,7 @@ import { pathToFileURL as pathToFileURL2 } from "node:url";
6
6
  import { randomUUID as randomUUID4 } from "node:crypto";
7
7
  import { existsSync as existsSync3 } from "node:fs";
8
8
  import { realpath as realpath3, stat as stat3 } from "node:fs/promises";
9
- import { homedir } from "node:os";
10
- import { isAbsolute as isAbsolute5, join as join13 } from "node:path";
9
+ import { isAbsolute as isAbsolute5, join as join12 } from "node:path";
11
10
  import { setTimeout as delay3 } from "node:timers/promises";
12
11
 
13
12
  // src/common/json.ts
@@ -61,11 +60,11 @@ releaseLine(packageVersion);
61
60
  // src/integrations/acp/agents.ts
62
61
  import { fork, spawnSync } from "node:child_process";
63
62
  import { existsSync as existsSync2 } from "node:fs";
64
- import { join as join7, resolve as resolve4 } from "node:path";
63
+ import { resolve as resolve4 } from "node:path";
65
64
  import { setTimeout as delay } from "node:timers/promises";
66
65
 
67
66
  // src/storage/agent-files.ts
68
- import { existsSync, mkdirSync as mkdirSync3, readdirSync, rmSync } from "node:fs";
67
+ import { existsSync, mkdirSync as mkdirSync3, readdirSync, rmdirSync as rmdirSync2, rmSync, unlinkSync as unlinkSync2 } from "node:fs";
69
68
  import { join as join3 } from "node:path";
70
69
  import { randomUUID as randomUUID2 } from "node:crypto";
71
70
 
@@ -191,7 +190,6 @@ function privateDirectory(root, relative3) {
191
190
  // src/model/agent.ts
192
191
  var messageDeliveries = ["steer", "followUp"];
193
192
  var cycleStates = ["running", "completed", "failed", "cancelled", "interrupted"];
194
- var cycleSources = ["parent", "interactive", "mixed"];
195
193
  var agentStates = ["starting", "busy", "idle", "stopping", "stopped", "error"];
196
194
 
197
195
  // src/storage/acp-files.ts
@@ -206,22 +204,21 @@ function isAcpElicitationValue(value) {
206
204
 
207
205
  // src/storage/acp-files.ts
208
206
  var text = (value) => typeof value === "string" && value.length > 0 && !value.includes("\0");
209
- function acpReference(value) {
210
- requireThat(object(value) && value.host === "acp" && isAcpBackend(value.backend) && text(value.command) && isAbsolute(value.command) && Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string" && !arg.includes("\0")) && (value.sessionId === null || text(value.sessionId)), "ACP \u4F1A\u8BDD\u5F15\u7528\u65E0\u6548\u3002");
207
+ function acpConfig(value) {
208
+ requireThat(object(value) && isAcpBackend(value.backend) && text(value.command) && isAbsolute(value.command) && Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string" && !arg.includes("\0")), "ACP \u542F\u52A8\u914D\u7F6E\u65E0\u6548\u3002");
211
209
  if (value.env !== void 0) {
212
210
  requireThat(object(value.env) && Object.entries(value.env).every(([k, v]) => text(k) && typeof v === "string" && !v.includes("\0")), "ACP \u73AF\u5883\u53D8\u91CF\u914D\u7F6E\u65E0\u6548\u3002");
213
211
  }
214
212
  requireThat(value.permission === void 0 || isOneOf(value.permission, acpPermissionPolicies), "ACP \u6743\u9650\u7B56\u7565\u65E0\u6548\u3002");
215
- const capabilities = value.capabilities;
216
- if (capabilities !== void 0) requireThat(object(capabilities) && ["resume", "load", "close"].every((key) => typeof capabilities[key] === "boolean"), "ACP \u4F1A\u8BDD\u80FD\u529B\u65E0\u6548\u3002");
217
- return value;
218
- }
219
- function acpModelState(value) {
220
- requireThat(object(value) && text(value.generation) && ["provider", "model", "resolvedModel", "thinking"].every((key) => value[key] === void 0 || text(value[key])), "ACP \u6A21\u578B\u9009\u62E9\u65E0\u6548\u3002");
221
213
  return value;
222
214
  }
223
- function acpProcess(value) {
224
- requireThat(object(value) && text(value.generation) && Number.isSafeInteger(value.pid) && Number(value.pid) > 1 && typeof value.startedAt === "number" && Number.isFinite(value.startedAt), "ACP \u8FDB\u7A0B\u8BB0\u5F55\u65E0\u6548\u3002");
215
+ function acpReference(value) {
216
+ requireThat(object(value) && value.host === "acp" && (value.sessionId === null || text(value.sessionId)), "ACP \u4F1A\u8BDD\u5F15\u7528\u65E0\u6548\u3002");
217
+ acpConfig(value);
218
+ const capabilities = value.capabilities;
219
+ if (capabilities !== void 0) {
220
+ requireThat(object(capabilities) && ["resume", "load", "close"].every((key) => typeof capabilities[key] === "boolean"), "ACP \u4F1A\u8BDD\u80FD\u529B\u65E0\u6548\u3002");
221
+ }
225
222
  return value;
226
223
  }
227
224
  function acpInput(value) {
@@ -229,50 +226,45 @@ function acpInput(value) {
229
226
  fileId(value.requestId);
230
227
  return value;
231
228
  }
232
- function acpReport(value) {
233
- requireThat(object(value) && text(value.generation) && text(value.cycleId) && typeof value.text === "string", "ACP \u5468\u671F\u62A5\u544A\u65E0\u6548\u3002");
234
- fileId(value.cycleId);
235
- return value;
236
- }
237
- function acpPermission(value) {
238
- acpInput(value);
239
- requireThat(object(value) && typeof value.description === "string" && Array.isArray(value.options) && value.options.every((option) => object(option) && text(option.optionId) && text(option.name) && isOneOf(option.kind, ["allow_once", "allow_always", "reject_once", "reject_always"])), "ACP \u786E\u8BA4\u8BF7\u6C42\u65E0\u6548\u3002");
240
- return value;
241
- }
242
- function acpPermissionReply(value) {
229
+ function acpInteraction(value) {
243
230
  acpInput(value);
244
- requireThat(object(value) && (value.optionId === null || text(value.optionId)), "ACP \u786E\u8BA4\u7B54\u590D\u65E0\u6548\u3002");
245
- return value;
246
- }
247
- function acpElicitation(value) {
248
- acpInput(value);
249
- requireThat(object(value) && (value.mode === "form" || value.mode === "url") && typeof value.message === "string", "ACP \u4EA4\u4E92\u8BF7\u6C42\u65E0\u6548\u3002");
250
- if (value.mode === "form") {
251
- requireThat(object(value.schema) && value.url === void 0, "ACP \u8868\u5355\u4EA4\u4E92\u8BF7\u6C42\u7F3A\u5C11\u6709\u6548 schema\u3002");
252
- } else {
253
- requireThat(text(value.url) && value.schema === void 0, "ACP URL \u4EA4\u4E92\u8BF7\u6C42\u7F3A\u5C11\u6709\u6548 url\u3002");
231
+ requireThat(object(value), "ACP \u4EA4\u4E92\u8BF7\u6C42\u65E0\u6548\u3002");
232
+ if (value.kind === "permission") {
233
+ requireThat(typeof value.description === "string" && Array.isArray(value.options) && value.options.every((option) => object(option) && text(option.optionId) && text(option.name) && isOneOf(option.kind, ["allow_once", "allow_always", "reject_once", "reject_always"])), "ACP \u786E\u8BA4\u8BF7\u6C42\u65E0\u6548\u3002");
234
+ return value;
235
+ }
236
+ if (value.kind === "form") {
237
+ requireThat(typeof value.message === "string" && object(value.schema), "ACP \u8868\u5355\u4EA4\u4E92\u8BF7\u6C42\u7F3A\u5C11\u6709\u6548 schema\u3002");
238
+ return value;
254
239
  }
240
+ requireThat(value.kind === "url" && typeof value.message === "string" && text(value.url), "ACP URL \u4EA4\u4E92\u8BF7\u6C42\u65E0\u6548\u3002");
255
241
  return value;
256
242
  }
257
- function acpElicitationReply(value) {
243
+ function acpInteractionReply(value) {
258
244
  acpInput(value);
259
- requireThat(object(value) && isOneOf(value.action, acpElicitationActions), "ACP \u4EA4\u4E92\u7B54\u590D\u65E0\u6548\u3002");
260
- if (value.content !== void 0) {
261
- requireThat(value.action === "accept" && object(value.content) && Object.values(value.content).every(isAcpElicitationValue), "ACP \u8868\u5355\u7B54\u590D content \u65E0\u6548\u3002");
245
+ requireThat(object(value), "ACP \u4EA4\u4E92\u7B54\u590D\u65E0\u6548\u3002");
246
+ if (value.kind === "permission") {
247
+ requireThat(value.optionId === null || text(value.optionId), "ACP \u786E\u8BA4\u7B54\u590D\u65E0\u6548\u3002");
248
+ return value;
249
+ }
250
+ if (value.kind === "form") {
251
+ requireThat(isOneOf(value.action, acpElicitationActions), "ACP \u8868\u5355\u7B54\u590D action \u65E0\u6548\u3002");
252
+ if (value.content !== void 0) {
253
+ requireThat(value.action === "accept" && object(value.content) && Object.values(value.content).every(isAcpElicitationValue), "ACP \u8868\u5355\u7B54\u590D content \u65E0\u6548\u3002");
254
+ }
255
+ return value;
262
256
  }
257
+ requireThat(value.kind === "url" && isOneOf(value.action, acpElicitationActions), "ACP URL \u4EA4\u4E92\u7B54\u590D\u65E0\u6548\u3002");
263
258
  return value;
264
259
  }
265
260
 
266
261
  // src/storage/agent-files.ts
267
262
  var text2 = (v) => typeof v === "string" && v.length > 0;
268
263
  var number = (v) => typeof v === "number" && Number.isFinite(v);
269
- function descriptor(v) {
270
- requireThat(object(v) && text2(v.agentId) && text2(v.release) && text2(v.workspace) && text2(v.cwd) && text2(v.parentSessionId) && (v.parentLeaf === null || text2(v.parentLeaf)) && number(v.createdAt) && object(v.options), "\u5B50\u4F1A\u8BDD\u8EAB\u4EFD\u65E0\u6548\u3002");
264
+ function workerRecord(v) {
265
+ requireThat(object(v) && text2(v.agentId) && text2(v.release) && text2(v.workspace) && text2(v.parentSessionId) && text2(v.generation) && Number.isSafeInteger(v.sequence) && typeof v.stop === "boolean" && number(v.startedAt) && (v.pid === void 0 || Number.isSafeInteger(v.pid) && Number(v.pid) > 1) && (v.options === void 0 || object(v.options)), "worker \u63A7\u5236\u8BB0\u5F55\u65E0\u6548\u3002");
271
266
  fileId(v.agentId);
272
- return v;
273
- }
274
- function launch(v) {
275
- requireThat(object(v) && text2(v.generation) && text2(v.name) && Number.isSafeInteger(v.sequence) && typeof v.stop === "boolean" && number(v.startedAt), "\u5B50\u4F1A\u8BDD\u542F\u52A8\u72B6\u6001\u65E0\u6548\u3002");
267
+ acpConfig(v.acp);
276
268
  return v;
277
269
  }
278
270
  function message(v) {
@@ -280,14 +272,56 @@ function message(v) {
280
272
  return v;
281
273
  }
282
274
  function cycle(v) {
283
- requireThat(object(v) && text2(v.cycleId) && text2(v.generation) && number(v.startedAt) && isOneOf(v.state, cycleStates) && (v.leaf === null || text2(v.leaf)) && Array.isArray(v.requestIds) && v.requestIds.every(text2) && isOneOf(v.source, cycleSources) && (v.finishedAt === void 0 || number(v.finishedAt)), "\u5B50\u4F1A\u8BDD\u5468\u671F\u65E0\u6548\u3002");
275
+ requireThat(object(v) && text2(v.cycleId) && text2(v.generation) && number(v.startedAt) && isOneOf(v.state, cycleStates) && Array.isArray(v.requestIds) && v.requestIds.every(text2) && (v.finishedAt === void 0 || number(v.finishedAt)) && (v.error === void 0 || typeof v.error === "string"), "\u5B50\u4F1A\u8BDD\u5468\u671F\u65E0\u6548\u3002");
284
276
  return v;
285
277
  }
286
278
  function status(v) {
287
279
  requireThat(object(v) && text2(v.generation) && isOneOf(v.state, agentStates) && typeof v.activity === "string" && number(v.updatedAt), "\u5B50\u4F1A\u8BDD\u72B6\u6001\u65E0\u6548\u3002");
288
- if (v.cycle) cycle(v.cycle);
280
+ if (v.sessionId !== void 0) requireThat(v.sessionId === null || text2(v.sessionId), "ACP \u4F1A\u8BDD ID \u65E0\u6548\u3002");
281
+ if (v.capabilities !== void 0) {
282
+ requireThat(object(v.capabilities) && ["resume", "load", "close"].every((key) => typeof v.capabilities[key] === "boolean"), "ACP \u4F1A\u8BDD\u80FD\u529B\u65E0\u6548\u3002");
283
+ }
284
+ if (v.selection !== void 0) {
285
+ requireThat(object(v.selection) && ["provider", "model", "resolvedModel", "thinking"].every((key) => v.selection[key] === void 0 || text2(v.selection[key])), "ACP \u6A21\u578B\u9009\u62E9\u65E0\u6548\u3002");
286
+ }
287
+ if (v.activeRequestId !== void 0) {
288
+ requireThat(text2(v.activeRequestId), "ACP \u8F93\u5165\u5173\u8054\u65E0\u6548\u3002");
289
+ fileId(v.activeRequestId);
290
+ }
291
+ if (v.accepted !== void 0) requireThat(Array.isArray(v.accepted) && v.accepted.every(text2), "\u5DF2\u9886\u53D6\u8BF7\u6C42\u5217\u8868\u65E0\u6548\u3002");
292
+ if (v.cycle !== void 0) cycle(v.cycle);
293
+ if (v.error !== void 0) requireThat(typeof v.error === "string", "\u5B50\u4F1A\u8BDD\u9519\u8BEF\u4FE1\u606F\u65E0\u6548\u3002");
289
294
  return v;
290
295
  }
296
+ function outputRecord(v) {
297
+ requireThat(object(v) && text2(v.cycleId) && text2(v.generation) && number(v.startedAt) && number(v.finishedAt) && isOneOf(v.state, ["completed", "failed", "cancelled", "interrupted"]) && Array.isArray(v.requestIds) && v.requestIds.every(text2) && typeof v.text === "string" && (v.error === void 0 || typeof v.error === "string"), "\u5B50\u4F1A\u8BDD\u8F93\u51FA\u8BB0\u5F55\u65E0\u6548\u3002");
298
+ fileId(v.cycleId);
299
+ return v;
300
+ }
301
+ function toDescriptor(record) {
302
+ return {
303
+ agentId: record.agentId,
304
+ release: record.release,
305
+ workspace: record.workspace,
306
+ parentSessionId: record.parentSessionId,
307
+ options: record.options ?? {}
308
+ };
309
+ }
310
+ function tryUnlink(path) {
311
+ try {
312
+ unlinkSync2(path);
313
+ } catch (error) {
314
+ if (error.code !== "ENOENT") throw error;
315
+ }
316
+ }
317
+ function tryRmdir(path) {
318
+ try {
319
+ rmdirSync2(path);
320
+ } catch (error) {
321
+ const code = error.code;
322
+ if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST") throw error;
323
+ }
324
+ }
291
325
  var AgentFiles = class {
292
326
  constructor(root) {
293
327
  this.root = root;
@@ -325,48 +359,99 @@ var AgentFiles = class {
325
359
  }
326
360
  requireThat(published, "\u5B50\u4F1A\u8BDD\u6587\u4EF6\u5DF2\u5B58\u5728\u3002");
327
361
  }
362
+ remove(id, path) {
363
+ tryUnlink(join3(this.directory(id), path));
364
+ }
328
365
  create(value, run, acp) {
329
366
  this.check();
330
367
  acpReference(acp);
331
368
  mkdirSync3(this.root, { recursive: true, mode: 448 });
332
369
  mkdirSync3(this.directory(value.agentId), { mode: 448 });
333
- for (const dir of ["inbox", "completions", "reports", "permissions", "elicitations"]) privateDirectory(this.directory(value.agentId), dir);
334
- this.write(value.agentId, "descriptor.json", value, descriptor, true);
335
- this.write(value.agentId, "launch.json", run, launch, true);
336
- this.write(value.agentId, "acp-session.json", acp, acpReference, true);
370
+ const hasOptions = Object.keys(value.options).length > 0;
371
+ const record = {
372
+ agentId: value.agentId,
373
+ release: value.release,
374
+ workspace: value.workspace,
375
+ parentSessionId: value.parentSessionId,
376
+ generation: run.generation,
377
+ sequence: run.sequence,
378
+ stop: run.stop,
379
+ startedAt: run.startedAt,
380
+ acp: {
381
+ backend: acp.backend,
382
+ command: acp.command,
383
+ args: acp.args,
384
+ ...acp.env ? { env: acp.env } : {},
385
+ ...acp.permission ? { permission: acp.permission } : {}
386
+ },
387
+ ...hasOptions ? { options: value.options } : {}
388
+ };
389
+ this.write(value.agentId, "worker.json", record, workerRecord, true);
390
+ }
391
+ worker(id) {
392
+ return this.read(id, "worker.json", workerRecord);
337
393
  }
338
394
  list() {
339
395
  if (!existsSync(this.root)) return [];
340
396
  return readdirSync(this.root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).flatMap((e) => {
341
- const d = this.optional(e.name, "descriptor.json", descriptor);
342
- return d ? [d] : [];
397
+ const record = this.optional(e.name, "worker.json", workerRecord);
398
+ return record ? [record] : [];
343
399
  });
344
400
  }
345
401
  messages(id) {
346
- return readdirSync(join3(this.directory(id), "inbox")).filter((n) => n.endsWith(".json")).map((n) => this.read(id, "inbox/" + n, message)).sort((a, b) => a.sequence - b.sequence);
402
+ const dir = join3(this.directory(id), "inbox");
403
+ if (!existsSync(dir)) return [];
404
+ return readdirSync(dir).filter((n) => n.endsWith(".json")).map((n) => this.read(id, "inbox/" + n, message)).sort((a, b) => a.sequence - b.sequence);
347
405
  }
348
- completions(id) {
349
- return readdirSync(join3(this.directory(id), "completions")).filter((n) => n.endsWith(".json")).map((n) => this.read(id, "completions/" + n, cycle)).sort((a, b) => (a.finishedAt ?? 0) - (b.finishedAt ?? 0));
406
+ removeMessage(id, requestId) {
407
+ fileId(requestId);
408
+ const dir = join3(this.directory(id), "inbox");
409
+ tryUnlink(join3(dir, requestId + ".json"));
410
+ tryRmdir(dir);
350
411
  }
351
- /** Permission requests of a generation that have no reply yet. */
352
- pendingPermissions(id, generation) {
353
- const dir = join3(this.directory(id), "permissions");
354
- if (!existsSync(dir)) return [];
355
- const names = readdirSync(dir);
356
- return names.filter((n) => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json")).map((n) => this.read(id, "permissions/" + n, acpPermission)).filter((item) => item.generation === generation);
412
+ output(id) {
413
+ return this.optional(id, "output.json", outputRecord);
357
414
  }
358
- /** Elicitation requests (forms, choices, text inputs, URL confirmations) of a generation that have no reply yet. */
359
- pendingElicitations(id, generation) {
360
- const dir = join3(this.directory(id), "elicitations");
415
+ pendingInteractions(id, generation) {
416
+ const dir = join3(this.directory(id), "interactions");
361
417
  if (!existsSync(dir)) return [];
362
418
  const names = readdirSync(dir);
363
- return names.filter((n) => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json")).map((n) => this.read(id, "elicitations/" + n, acpElicitation)).filter((item) => item.generation === generation);
419
+ return names.filter((n) => n.endsWith(".json") && !n.endsWith("-reply.json") && !names.includes(n.slice(0, -5) + "-reply.json")).map((n) => this.read(id, "interactions/" + n, acpInteraction)).filter((item) => item.generation === generation);
420
+ }
421
+ removeInteraction(id, requestId) {
422
+ fileId(requestId);
423
+ const dir = join3(this.directory(id), "interactions");
424
+ tryUnlink(join3(dir, requestId + ".json"));
425
+ tryUnlink(join3(dir, requestId + "-reply.json"));
426
+ tryRmdir(dir);
427
+ }
428
+ clearTransient(id) {
429
+ const base = this.directory(id);
430
+ if (!existsSync(base)) return;
431
+ rmSync(join3(base, "inbox"), { recursive: true, force: true });
432
+ rmSync(join3(base, "interactions"), { recursive: true, force: true });
433
+ tryUnlink(join3(base, "acp-answer.json"));
434
+ }
435
+ removeWorker(id) {
436
+ rmSync(this.directory(id), { recursive: true, force: true });
437
+ tryRmdir(this.root);
364
438
  }
365
439
  ensureSubdirectory(id, name) {
366
440
  privateDirectory(this.directory(id), name);
367
441
  }
368
442
  reference(id) {
369
- return this.read(id, "acp-session.json", acpReference);
443
+ const w = this.worker(id);
444
+ const saved = this.optional(id, "state.json", status);
445
+ return {
446
+ host: "acp",
447
+ backend: w.acp.backend,
448
+ command: w.acp.command,
449
+ args: w.acp.args,
450
+ ...w.acp.env ? { env: w.acp.env } : {},
451
+ ...w.acp.permission ? { permission: w.acp.permission } : {},
452
+ sessionId: saved?.sessionId ?? null,
453
+ ...saved?.capabilities ? { capabilities: saved.capabilities } : {}
454
+ };
370
455
  }
371
456
  /** Short controller edits are serialized; an abandoned lock fails closed. */
372
457
  control(work) {
@@ -387,14 +472,16 @@ var AgentFiles = class {
387
472
  }
388
473
  enqueue(id, text3, delivery, files = [], requestId = randomUUID2()) {
389
474
  fileId(requestId);
390
- const run = this.read(id, "launch.json", launch), previous = this.optional(id, "inbox/" + requestId + ".json", message);
475
+ const w = this.worker(id);
476
+ const previous = this.optional(id, "inbox/" + requestId + ".json", message);
391
477
  if (previous) {
392
- requireThat(previous.generation === run.generation && previous.message === text3 && previous.delivery === delivery && canonical(previous.files) === canonical(files), "\u8BF7\u6C42 ID \u5DF2\u88AB\u4E0D\u540C\u8F93\u5165\u4F7F\u7528\u3002");
478
+ requireThat(previous.generation === w.generation && previous.message === text3 && previous.delivery === delivery && canonical(previous.files) === canonical(files), "\u8BF7\u6C42 ID \u5DF2\u88AB\u4E0D\u540C\u8F93\u5165\u4F7F\u7528\u3002");
393
479
  return previous;
394
480
  }
395
- run.sequence++;
396
- this.write(id, "launch.json", run, launch);
397
- const value = { requestId, generation: run.generation, sequence: run.sequence, message: text3, delivery, files };
481
+ w.sequence++;
482
+ this.write(id, "worker.json", w, workerRecord);
483
+ this.ensureSubdirectory(id, "inbox");
484
+ const value = { requestId, generation: w.generation, sequence: w.sequence, message: text3, delivery, files };
398
485
  this.write(id, "inbox/" + value.requestId + ".json", value, message, true);
399
486
  return value;
400
487
  }
@@ -526,7 +613,7 @@ var claudeAcpHarness = {
526
613
  },
527
614
  async prepareLaunch(context) {
528
615
  const base = defaultPrepareLaunch(context);
529
- const claude = await claudeOptions(base.command, context.cwd, context.options.thinking, context.features?.skills !== false);
616
+ const claude = await claudeOptions(base.command, context.workspace, context.options.thinking, context.features?.skills !== false);
530
617
  return {
531
618
  ...base,
532
619
  ...claude.thinking ? { defaultThinking: claude.thinking } : {},
@@ -769,13 +856,13 @@ var AcpWorkerHost = class {
769
856
  return acpLaunch(backend, this.commands, options);
770
857
  }
771
858
  /** Probe a backend's advertised model and thinking choices in an isolated ACP process without prompting. */
772
- async inspectModels(backend, cwd, options = {}) {
859
+ async inspectModels(backend, workspace, options = {}) {
773
860
  this.available(backend);
774
861
  const filtered = this.filterOptions(backend, options);
775
862
  const reference = this.prepare(backend, filtered);
776
863
  return await new Promise((resolveResult, reject) => {
777
864
  const child = fork(this.worker, ["--probe"], {
778
- cwd,
865
+ cwd: workspace,
779
866
  env: { ...process.env },
780
867
  detached: true,
781
868
  stdio: ["ignore", "ignore", "ignore", "ipc"],
@@ -802,7 +889,7 @@ var AcpWorkerHost = class {
802
889
  child.once("spawn", () => {
803
890
  child.send({
804
891
  reference,
805
- cwd,
892
+ cwd: workspace,
806
893
  ...filtered.provider ? { provider: filtered.provider } : {},
807
894
  ...filtered.model ? { model: filtered.model } : {}
808
895
  });
@@ -815,8 +902,8 @@ var AcpWorkerHost = class {
815
902
  });
816
903
  }
817
904
  process(id) {
818
- const record = this.files.optional(id, "acp-process.json", acpProcess);
819
- if (!record || this.files.read(id, "launch.json", launch).generation !== record.generation) return;
905
+ const record = this.files.optional(id, "worker.json", workerRecord);
906
+ if (!record?.pid) return;
820
907
  let denied = false;
821
908
  try {
822
909
  process.kill(-record.pid, 0);
@@ -828,7 +915,7 @@ var AcpWorkerHost = class {
828
915
  }
829
916
  const leader = spawnSync("ps", ["-p", String(record.pid), "-o", "args="], { encoding: "utf8" });
830
917
  if (leader.status === 0 && !leader.stdout.includes("--pbot-acp-agent " + id + " --generation " + record.generation) || denied && leader.status !== 0) return;
831
- return record;
918
+ return { generation: record.generation, pid: record.pid };
832
919
  }
833
920
  alive(id) {
834
921
  return Boolean(this.process(id));
@@ -836,10 +923,11 @@ var AcpWorkerHost = class {
836
923
  async validateSession(d, reference) {
837
924
  requireThat(!this.alive(d.agentId), "ACP \u6210\u5458\u4ECD\u5728\u8FD0\u884C\uFF0C\u4E0D\u80FD\u6062\u590D\u3002");
838
925
  if (reference.sessionId === null) {
839
- requireThat(!this.files.optional(d.agentId, "acp-input.json", acpInput), "ACP \u8F93\u5165\u4EA4\u4ED8\u72B6\u6001\u4E0D\u660E\uFF1B\u8BF7\u6838\u5BF9\u539F\u8BF7\u6C42\u540E\u65B0\u5EFA\u6210\u5458\u3002");
926
+ const saved = this.files.optional(d.agentId, "state.json", status);
927
+ requireThat(!saved?.activeRequestId, "ACP \u8F93\u5165\u4EA4\u4ED8\u72B6\u6001\u4E0D\u660E\uFF1B\u8BF7\u6838\u5BF9\u539F\u8BF7\u6C42\u540E\u65B0\u5EFA\u6210\u5458\u3002");
840
928
  return;
841
929
  }
842
- const generation = this.files.read(d.agentId, "launch.json", launch).generation;
930
+ const generation = this.files.worker(d.agentId).generation;
843
931
  await new Promise((resolveResult, reject) => {
844
932
  const child = this.spawn(d, generation, true);
845
933
  let validated = false, failure;
@@ -877,7 +965,7 @@ var AcpWorkerHost = class {
877
965
  this.files.directory(d.agentId),
878
966
  ...validate ? ["--validate"] : []
879
967
  ], {
880
- cwd: d.cwd,
968
+ cwd: d.workspace,
881
969
  env: { ...process.env },
882
970
  detached: true,
883
971
  stdio: ["ignore", "ignore", "ignore", "ipc"],
@@ -891,12 +979,19 @@ var AcpWorkerHost = class {
891
979
  child.once("spawn", resolveResult);
892
980
  child.once("error", reject);
893
981
  });
894
- requireThat(child.pid, "ACP worker \u6CA1\u6709\u8FDB\u7A0B\u8EAB\u4EFD\u3002");
982
+ const pid = child.pid;
983
+ requireThat(pid, "ACP worker \u6CA1\u6709\u8FDB\u7A0B\u8EAB\u4EFD\u3002");
895
984
  try {
896
- this.files.write(d.agentId, "acp-process.json", { generation, pid: child.pid, startedAt: Date.now() }, acpProcess);
985
+ this.files.control(() => {
986
+ const w = this.files.worker(d.agentId);
987
+ if (w.generation === generation) {
988
+ w.pid = pid;
989
+ this.files.write(d.agentId, "worker.json", w, workerRecord);
990
+ }
991
+ });
897
992
  } catch (error) {
898
993
  try {
899
- process.kill(-child.pid, "SIGKILL");
994
+ process.kill(-pid, "SIGKILL");
900
995
  } catch (failure) {
901
996
  if (failure.code !== "ESRCH") throw new AggregateError([error, failure], "ACP \u542F\u52A8\u4E0E\u6E05\u7406\u5931\u8D25\u3002");
902
997
  }
@@ -929,17 +1024,11 @@ var AcpWorkerHost = class {
929
1024
  const current = this.process(id);
930
1025
  if (current?.generation === generation && current.pid === record.pid) terminate("SIGKILL");
931
1026
  }
932
- report(d, _reference, leaf) {
933
- requireThat(leaf.startsWith("acp:"), "ACP \u62A5\u544A\u5F15\u7528\u65E0\u6548\u3002");
934
- const cycleId = fileId(leaf.slice(4)), report = this.files.read(d.agentId, join7("reports", cycleId + ".json"), acpReport);
935
- requireThat(report.cycleId === cycleId, "ACP \u62A5\u544A\u5468\u671F\u4E0D\u5339\u914D\u3002");
936
- return report.text;
937
- }
938
1027
  };
939
1028
 
940
1029
  // src/integrations/hosts/antigravity/adapter.ts
941
1030
  import { readFile, realpath, stat } from "node:fs/promises";
942
- import { dirname as dirname2, isAbsolute as isAbsolute3, join as join8, relative, resolve as resolve5, sep } from "node:path";
1031
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join7, relative, resolve as resolve5, sep } from "node:path";
943
1032
  var supportedEvents = ["SessionStart", "PreToolUse", "Stop"];
944
1033
  function cleanUserRequest(content) {
945
1034
  const match = content.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/);
@@ -989,7 +1078,7 @@ function projectAntigravityTranscript(sessionId, content, terminationReason) {
989
1078
  return { sessionId, name: "", branches: exchanges.length ? [exchanges] : [] };
990
1079
  }
991
1080
  async function readAntigravityTranscript(transcriptPath) {
992
- const fullPath = join8(dirname2(transcriptPath), "transcript_full.jsonl");
1081
+ const fullPath = join7(dirname2(transcriptPath), "transcript_full.jsonl");
993
1082
  for (const path of [fullPath, transcriptPath]) {
994
1083
  try {
995
1084
  return await readFile(path, "utf8");
@@ -1313,10 +1402,6 @@ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = fa
1313
1402
  type: "string",
1314
1403
  description: "\u601D\u8003\u6DF1\u5EA6\uFF08\u5982 low / medium / high / xhigh / max\uFF0C\u4E0D\u533A\u5206\u5927\u5C0F\u5199\uFF09\uFF1B\u672A\u660E\u786E\u6307\u5B9A\u65F6\u7701\u7565\u4EE5\u7528\u9ED8\u8BA4\u8BBE\u7F6E\u3002"
1315
1404
  },
1316
- cwd: {
1317
- type: "string",
1318
- description: "\u6267\u884C\u76EE\u5F55\uFF08\u7EDD\u5BF9\u8DEF\u5F84\u6216\u76F8\u5BF9\u5DE5\u4F5C\u533A\u8DEF\u5F84\uFF09\uFF0C\u9ED8\u8BA4\u5DE5\u4F5C\u533A\u6839\u76EE\u5F55\u3002"
1319
- },
1320
1405
  workspace
1321
1406
  }
1322
1407
  }
@@ -1339,8 +1424,7 @@ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = fa
1339
1424
  workerId: {
1340
1425
  type: "string",
1341
1426
  description: "\u52A9\u624B\u4F1A\u8BDD ID\uFF08\u6765\u81EA worker_create \u6216 worker_discover\uFF09\u3002"
1342
- },
1343
- workspace
1427
+ }
1344
1428
  }
1345
1429
  }
1346
1430
  },
@@ -1372,8 +1456,7 @@ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = fa
1372
1456
  minimum: 0,
1373
1457
  maximum: maxWaitMs,
1374
1458
  description: `\u6700\u591A\u7B49\u5F85\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B0 \u8868\u793A\u7ACB\u5373\u8FD4\u56DE\u8F6C\u540E\u53F0\u6267\u884C\u3002`
1375
- },
1376
- workspace
1459
+ }
1377
1460
  }
1378
1461
  }
1379
1462
  },
@@ -1419,8 +1502,7 @@ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = fa
1419
1502
  minimum: 0,
1420
1503
  maximum: maxWaitMs,
1421
1504
  description: `\u63D0\u4EA4\u540E\u6700\u591A\u7B49\u5F85\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B0 \u8868\u793A\u7ACB\u5373\u8FD4\u56DE\u3002`
1422
- },
1423
- workspace
1505
+ }
1424
1506
  }
1425
1507
  }
1426
1508
  },
@@ -1453,8 +1535,7 @@ function buildPbotWorkerTools(commands = {}, defaultBackend, workspaceBound = fa
1453
1535
  minimum: 0,
1454
1536
  maximum: maxWaitMs,
1455
1537
  description: `\u8FD0\u884C\u4E2D\u6700\u591A\u7B49\u5F85\u6BEB\u79D2\u6570\uFF08\u9ED8\u8BA4 ${defaultWaitMs}\uFF09\uFF1B\u5DF2\u7ED3\u675F\u6216\u7FFB\u9875\u65F6\u7ACB\u5373\u8FD4\u56DE\u3002`
1456
- },
1457
- workspace
1538
+ }
1458
1539
  }
1459
1540
  }
1460
1541
  },
@@ -1693,56 +1774,50 @@ var AgentService = class {
1693
1774
  check() {
1694
1775
  requireThat(!this.#closed, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1695
1776
  }
1696
- owned(d, owner) {
1697
- return d.workspace === this.root && d.parentSessionId === owner.sessionId && (d.parentLeaf === null || owner.branch.includes(d.parentLeaf));
1777
+ owned(w, owner) {
1778
+ return w.workspace === this.root && w.parentSessionId === owner.sessionId;
1698
1779
  }
1699
1780
  get(id, owner) {
1700
1781
  this.check();
1701
- const d = this.files.read(id, "descriptor.json", descriptor);
1702
- requireThat(this.owned(d, owner), "worker \u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD\u3002");
1703
- requireThat(releaseLine(d.release) === releaseLine(packageVersion), "worker \u7248\u672C\u4E0D\u517C\u5BB9\uFF1B\u8BF7\u505C\u6B62\u540E\u4F7F\u7528\u5339\u914D\u7248\u672C\u3002");
1704
- return d;
1782
+ const w = this.files.worker(id);
1783
+ requireThat(this.owned(w, owner), "worker \u4E0D\u5C5E\u4E8E\u5F53\u524D\u4F1A\u8BDD\u3002");
1784
+ requireThat(releaseLine(w.release) === releaseLine(packageVersion), "worker \u7248\u672C\u4E0D\u517C\u5BB9\uFF1B\u8BF7\u505C\u6B62\u540E\u4F7F\u7528\u5339\u914D\u7248\u672C\u3002");
1785
+ return w;
1705
1786
  }
1706
1787
  records(owner) {
1707
1788
  this.check();
1708
- return this.files.list().filter((d) => d.workspace === this.root && d.parentSessionId === owner.sessionId && releaseLine(d.release) === releaseLine(packageVersion));
1789
+ return this.files.list().filter((w) => w.workspace === this.root && w.parentSessionId === owner.sessionId && releaseLine(w.release) === releaseLine(packageVersion));
1790
+ }
1791
+ has(id, owner) {
1792
+ if (this.#closed) return false;
1793
+ const w = this.files.optional(id, "worker.json", workerRecord);
1794
+ return Boolean(w && this.owned(w, owner) && releaseLine(w.release) === releaseLine(packageVersion));
1709
1795
  }
1710
1796
  list(owner) {
1711
- return this.records(owner).map((d) => this.view(d, owner));
1797
+ return this.records(owner).map((w) => this.view(w, owner));
1712
1798
  }
1713
- view(d, owner) {
1714
- const run = this.files.read(d.agentId, "launch.json", launch);
1715
- const saved = this.files.optional(d.agentId, "status.json", status);
1716
- const current = saved?.generation === run.generation ? saved : void 0;
1717
- const alive = this.alive(d.agentId), pending = this.#starting.get(d.agentId);
1799
+ view(w, owner) {
1800
+ const saved = this.files.optional(w.agentId, "state.json", status);
1801
+ const current = saved?.generation === w.generation ? saved : void 0;
1802
+ const alive = this.alive(w.agentId), pending = this.#starting.get(w.agentId);
1718
1803
  const starting = pending && !pending.controller.signal.aborted;
1719
- const reference = this.files.read(d.agentId, "acp-session.json", acpReference);
1720
- const model = this.files.optional(d.agentId, "acp-model.json", acpModelState);
1721
- const selection = model?.generation === run.generation ? {
1722
- ...model.provider ? { provider: model.provider } : {},
1723
- ...model.model ? { model: model.model } : {},
1724
- ...model.resolvedModel ? { resolvedModel: model.resolvedModel } : {},
1725
- ...model.thinking ? { thinking: model.thinking } : {}
1726
- } : void 0;
1727
- const pendingRequests = alive ? [
1728
- ...this.files.pendingPermissions(d.agentId, run.generation).map((item) => ({ requestId: item.requestId, kind: "permission", description: item.description, options: item.options })),
1729
- ...this.files.pendingElicitations(d.agentId, run.generation).map((item) => item.mode === "form" ? { requestId: item.requestId, kind: "form", message: item.message, schema: item.schema ?? { type: "object", properties: {} } } : { requestId: item.requestId, kind: "url", message: item.message, url: item.url ?? "" })
1730
- ] : [];
1804
+ const selection = current?.selection && Object.keys(current.selection).length ? current.selection : void 0;
1805
+ const pendingRequests = alive ? this.files.pendingInteractions(w.agentId, w.generation).map((item) => item.kind === "permission" ? { requestId: item.requestId, kind: "permission", description: item.description, options: item.options } : item.kind === "form" ? { requestId: item.requestId, kind: "form", message: item.message, schema: item.schema } : { requestId: item.requestId, kind: "url", message: item.message, url: item.url }) : [];
1806
+ const capabilities = saved?.capabilities;
1731
1807
  return {
1732
- ...d,
1733
- name: run.name,
1734
- generation: run.generation,
1735
- owned: this.owned(d, owner),
1808
+ ...toDescriptor(w),
1809
+ generation: w.generation,
1810
+ owned: this.owned(w, owner),
1736
1811
  alive,
1737
- backend: reference.backend,
1812
+ backend: w.acp.backend,
1738
1813
  transport: "acp",
1739
1814
  capabilities: {
1740
1815
  steer: false,
1741
- resume: Boolean(reference.capabilities?.resume || reference.capabilities?.load),
1816
+ resume: Boolean(capabilities?.resume || capabilities?.load),
1742
1817
  transcript: false
1743
1818
  },
1744
1819
  ...selection ? { selection } : {},
1745
- state: alive ? starting ? "starting" : run.stop || pending?.controller.signal.aborted ? "stopping" : current?.state ?? "starting" : current?.state === "error" ? "error" : "stopped",
1820
+ state: alive ? starting ? "starting" : w.stop || pending?.controller.signal.aborted ? "stopping" : current?.state ?? "starting" : current?.state === "error" ? "error" : "stopped",
1746
1821
  activity: starting ? "\u542F\u52A8" : alive ? current?.activity ?? "\u542F\u52A8" : current?.error ?? "\u5DF2\u505C\u6B62",
1747
1822
  ...current?.cycle ? { cycle: current.cycle } : {},
1748
1823
  ...current?.error ? { error: current.error } : {},
@@ -1751,13 +1826,14 @@ var AgentService = class {
1751
1826
  }
1752
1827
  /** Answer a pending permission or elicitation request forwarded by the worker. */
1753
1828
  respond(id, input, owner) {
1754
- const d = this.get(id, owner), run = this.files.read(id, "launch.json", launch);
1755
- const pending = this.view(d, owner).pendingRequests ?? [];
1829
+ const w = this.get(id, owner);
1830
+ const pending = this.view(w, owner).pendingRequests ?? [];
1756
1831
  if (!input.requestId && pending.length > 1) {
1757
1832
  throw new Error("\u5B58\u5728\u591A\u6761\u5F85\u56DE\u590D\u8BF7\u6C42\uFF0C\u8BF7\u6307\u5B9A requestId\uFF1A" + pending.map((item) => item.requestId).join(", "));
1758
1833
  }
1759
1834
  const target = input.requestId ? pending.find((item) => item.requestId === input.requestId) : pending[0];
1760
1835
  requireThat(target, input.requestId ? "\u6CA1\u6709\u5F85\u56DE\u590D\u7684\u8BF7\u6C42\uFF1A" + input.requestId + "\uFF1B\u7528 worker_discover \u67E5\u770B pendingRequests\u3002" : "\u5F53\u524D\u6CA1\u6709\u5F85\u56DE\u590D\u7684\u8BF7\u6C42\u3002");
1836
+ this.files.ensureSubdirectory(id, "interactions");
1761
1837
  if (target.kind === "permission") {
1762
1838
  requireThat(input.content === void 0, "\u6743\u9650\u8BF7\u6C42\u4E0D\u4F7F\u7528 content\uFF1B\u8BF7\u7528 action\uFF08accept / decline / cancel\uFF09\u6216\u6307\u5B9A optionId\u3002");
1763
1839
  let resolved = null;
@@ -1784,15 +1860,14 @@ var AgentService = class {
1784
1860
  resolved = pick("reject_once", "reject_always") ?? null;
1785
1861
  }
1786
1862
  }
1787
- this.files.ensureSubdirectory(id, "permissions");
1788
1863
  this.files.write(
1789
1864
  id,
1790
- "permissions/" + target.requestId + "-reply.json",
1791
- { generation: run.generation, requestId: target.requestId, optionId: resolved },
1792
- acpPermissionReply,
1865
+ "interactions/" + target.requestId + "-reply.json",
1866
+ { generation: w.generation, requestId: target.requestId, kind: "permission", optionId: resolved },
1867
+ acpInteractionReply,
1793
1868
  true
1794
1869
  );
1795
- return this.view(d, owner);
1870
+ return this.view(w, owner);
1796
1871
  }
1797
1872
  if (target.kind === "form") {
1798
1873
  requireThat(input.optionId === void 0, "\u95EE\u7B54/\u8868\u5355\u8BF7\u6C42\u4E0D\u4F7F\u7528 optionId\uFF1B\u8BF7\u5C06\u7B54\u6848\u586B\u5165 content\u3002");
@@ -1801,28 +1876,28 @@ var AgentService = class {
1801
1876
  } else {
1802
1877
  requireThat(input.content === void 0 || object(input.content), "\u95EE\u7B54/\u8868\u5355\u7B54\u590D\u7684 content \u5FC5\u987B\u662F\u5BF9\u8C61\u3002");
1803
1878
  }
1804
- this.files.ensureSubdirectory(id, "elicitations");
1805
- this.files.write(id, "elicitations/" + target.requestId + "-reply.json", {
1806
- generation: run.generation,
1879
+ this.files.write(id, "interactions/" + target.requestId + "-reply.json", {
1880
+ generation: w.generation,
1807
1881
  requestId: target.requestId,
1882
+ kind: "form",
1808
1883
  action: input.action,
1809
1884
  ...input.action === "accept" ? { content: input.content ?? {} } : {}
1810
- }, acpElicitationReply, true);
1811
- return this.view(d, owner);
1885
+ }, acpInteractionReply, true);
1886
+ return this.view(w, owner);
1812
1887
  }
1813
1888
  requireThat(input.optionId === void 0, "URL \u786E\u8BA4\u8BF7\u6C42\u4E0D\u4F7F\u7528 optionId\u3002");
1814
1889
  requireThat(input.content === void 0, "URL \u786E\u8BA4\u8BF7\u6C42\u4E0D\u4F7F\u7528 content\u3002");
1815
- this.files.ensureSubdirectory(id, "elicitations");
1816
- this.files.write(id, "elicitations/" + target.requestId + "-reply.json", {
1817
- generation: run.generation,
1890
+ this.files.write(id, "interactions/" + target.requestId + "-reply.json", {
1891
+ generation: w.generation,
1818
1892
  requestId: target.requestId,
1893
+ kind: "url",
1819
1894
  action: input.action
1820
- }, acpElicitationReply, true);
1821
- return this.view(d, owner);
1895
+ }, acpInteractionReply, true);
1896
+ return this.view(w, owner);
1822
1897
  }
1823
1898
  async start(input, owner) {
1824
1899
  this.check();
1825
- const { backend, ...supplied } = input;
1900
+ const { backend, message: initialMessage, files: initialFiles, ...supplied } = input;
1826
1901
  this.host.available(backend);
1827
1902
  const clean = Object.fromEntries(Object.entries(supplied).filter(([, v]) => v !== void 0));
1828
1903
  const options = this.host.filterOptions ? this.host.filterOptions(backend, clean) : clean;
@@ -1830,27 +1905,26 @@ var AgentService = class {
1830
1905
  const prepared = this.files.control(() => {
1831
1906
  requireThat(this.list(owner).filter((v) => v.alive).length < 50, "\u6700\u591A 50 \u4E2A\u5B58\u6D3B\u6216\u542F\u52A8\u4E2D worker\uFF1B\u8BF7\u5148\u505C\u6B62\u4E00\u4E2A\u7A7A\u95F2\u4F1A\u8BDD\u3002");
1832
1907
  const agentId = randomUUID3();
1833
- const cwd = realpathSync3(resolve6(this.root, options.cwd ?? "."));
1834
- const files = (options.files ?? []).map((p) => realpathSync3(resolve6(this.root, p)));
1908
+ const files = (initialFiles ?? []).map((p) => realpathSync3(resolve6(this.root, p)));
1835
1909
  const d = {
1836
1910
  agentId,
1837
1911
  release: packageVersion,
1838
1912
  workspace: this.root,
1839
- cwd,
1840
1913
  parentSessionId: owner.sessionId,
1841
- parentLeaf: owner.leaf,
1842
- createdAt: Date.now(),
1843
- options: { ...options, files, cwd }
1914
+ options
1844
1915
  };
1845
- const run = { generation: randomUUID3(), name: options.name ?? agentId.slice(0, 8), sequence: 0, stop: false, startedAt: Date.now() };
1916
+ const run = { generation: randomUUID3(), sequence: 0, stop: false, startedAt: Date.now() };
1846
1917
  this.files.create(d, run, reference);
1847
- const initial = options.message ?? "";
1918
+ const initial = initialMessage ?? "";
1848
1919
  const request = initial || files.length ? this.files.enqueue(agentId, initial, "steer", files) : void 0;
1849
1920
  this.#starting.set(agentId, { generation: run.generation, controller: new AbortController(), stage: "launch" });
1850
1921
  return { d, run, request };
1851
1922
  });
1852
1923
  await this.launch(prepared.d, prepared.run.generation);
1853
- return { ...this.view(prepared.d, owner), ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {} };
1924
+ return {
1925
+ ...this.view(this.files.worker(prepared.d.agentId), owner),
1926
+ ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {}
1927
+ };
1854
1928
  }
1855
1929
  async launch(d, generation, resume = false) {
1856
1930
  const pending = this.#starting.get(d.agentId);
@@ -1860,18 +1934,21 @@ var AgentService = class {
1860
1934
  await this.host.launch(d, this.files.directory(d.agentId), generation, this.files.reference(d.agentId), resume, pending.controller.signal);
1861
1935
  requireThat(!this.#closed || this.#preserve, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1862
1936
  pending.controller.signal.throwIfAborted();
1863
- const run = this.files.read(d.agentId, "launch.json", launch);
1864
- requireThat(run.generation === generation && !run.stop, "worker \u542F\u52A8\u5DF2\u53D6\u6D88\u6216\u4EE3\u6B21\u53D8\u5316\u3002");
1937
+ const w = this.files.worker(d.agentId);
1938
+ requireThat(w.generation === generation && !w.stop, "worker \u542F\u52A8\u5DF2\u53D6\u6D88\u6216\u4EE3\u6B21\u53D8\u5316\u3002");
1865
1939
  } catch (error) {
1866
- const run = this.files.read(d.agentId, "launch.json", launch);
1867
- if (run.generation === generation) {
1940
+ const w = this.files.worker(d.agentId);
1941
+ if (w.generation === generation) {
1868
1942
  if (this.host.alive(d.agentId)) await this.release(d.agentId);
1869
- this.files.write(d.agentId, "status.json", {
1943
+ const existing = this.files.optional(d.agentId, "state.json", status);
1944
+ this.files.write(d.agentId, "state.json", {
1870
1945
  generation,
1871
- state: run.stop ? "stopped" : "error",
1872
- activity: run.stop ? "\u5DF2\u505C\u6B62" : "\u542F\u52A8\u5931\u8D25",
1946
+ state: w.stop ? "stopped" : "error",
1947
+ activity: w.stop ? "\u5DF2\u505C\u6B62" : "\u542F\u52A8\u5931\u8D25",
1873
1948
  updatedAt: Date.now(),
1874
- ...run.stop ? {} : { error: String(error) }
1949
+ ...existing?.sessionId !== void 0 ? { sessionId: existing.sessionId } : {},
1950
+ ...existing?.capabilities ? { capabilities: existing.capabilities } : {},
1951
+ ...w.stop ? {} : { error: String(error) }
1875
1952
  }, status);
1876
1953
  }
1877
1954
  throw error;
@@ -1887,57 +1964,40 @@ var AgentService = class {
1887
1964
  }
1888
1965
  }
1889
1966
  send(id, text3, delivery, owner, attachments = []) {
1890
- const d = this.get(id, owner);
1967
+ const w = this.get(id, owner);
1891
1968
  return this.files.control(() => {
1892
- requireThat(this.alive(id) && this.#starting.get(id)?.stage !== "validate" && !this.files.read(id, "launch.json", launch).stop, "worker \u5DF2\u505C\u6B62\u6216\u4ECD\u5728\u6062\u590D\u6821\u9A8C\uFF0C\u8BF7\u7B49\u5F85\u663E\u5F0F\u6062\u590D\u5B8C\u6210\u3002");
1893
- const view = this.view(d, owner);
1969
+ const latest = this.files.worker(id);
1970
+ requireThat(this.alive(id) && this.#starting.get(id)?.stage !== "validate" && !latest.stop, "worker \u5DF2\u505C\u6B62\u6216\u4ECD\u5728\u6062\u590D\u6821\u9A8C\uFF0C\u8BF7\u7B49\u5F85\u663E\u5F0F\u6062\u590D\u5B8C\u6210\u3002");
1971
+ const view = this.view(latest, owner);
1894
1972
  requireThat(!(delivery === "steer" && view.state !== "idle"), "\u8BE5 ACP worker \u8FD0\u884C\u4E2D\u4E0D\u652F\u6301 steer\uFF1B\u8BF7\u7528 delivery: followUp \u6392\u961F\u3002");
1895
1973
  const files = attachments.map((path) => realpathSync3(resolve6(this.root, path)));
1896
1974
  const request = this.files.enqueue(id, text3, delivery, files);
1897
- return { ...this.view(d, owner), requestId: request.requestId, messageStatus: "queued" };
1975
+ return { ...this.view(this.files.worker(w.agentId), owner), requestId: request.requestId, messageStatus: "queued" };
1898
1976
  });
1899
1977
  }
1900
- rename(id, name, owner) {
1901
- requireThat(name.trim().length > 0 && name.length <= 64 && !/[\x00-\x1f]/.test(name), "\u540D\u79F0\u5FC5\u987B\u662F 1 \u5230 64 \u5B57\u7B26\u7684\u5355\u884C\u6587\u672C\u3002");
1902
- const d = this.get(id, owner);
1903
- this.files.control(() => {
1904
- const run = this.files.read(id, "launch.json", launch);
1905
- run.name = name;
1906
- this.files.write(id, "launch.json", run, launch);
1907
- });
1908
- return this.view(d, owner);
1909
- }
1910
1978
  stop(id, owner) {
1911
- const d = this.get(id, owner);
1979
+ this.get(id, owner);
1912
1980
  this.requestStop(id);
1913
- return this.view(d, owner);
1981
+ return this.view(this.files.worker(id), owner);
1914
1982
  }
1915
1983
  requestStop(id) {
1916
1984
  this.files.control(() => {
1917
- const run = this.files.read(id, "launch.json", launch);
1918
- run.stop = true;
1919
- this.files.write(id, "launch.json", run, launch);
1985
+ const w = this.files.worker(id);
1986
+ w.stop = true;
1987
+ this.files.write(id, "worker.json", w, workerRecord);
1920
1988
  });
1921
1989
  this.#starting.get(id)?.controller.abort();
1922
1990
  }
1923
- async enter(id, owner) {
1924
- const d = this.get(id, owner);
1925
- if (this.alive(id)) {
1926
- requireThat(!this.files.read(id, "launch.json", launch).stop, "worker \u6B63\u5728\u505C\u6B62\uFF0C\u8BF7\u7A0D\u540E\u64CD\u4F5C\u3002");
1927
- return this.view(d, owner);
1928
- }
1929
- return this.restart(id, owner);
1930
- }
1931
1991
  resume(id, text3, owner) {
1932
1992
  return this.restart(id, owner, text3);
1933
1993
  }
1934
1994
  async restart(id, owner, text3) {
1935
- const d = this.get(id, owner), reference = this.files.reference(id);
1995
+ const w = this.get(id, owner), d = toDescriptor(w), reference = this.files.reference(id);
1936
1996
  this.host.available(reference.backend);
1937
1997
  const reserved = this.files.control(() => {
1938
1998
  requireThat(!this.alive(id), "worker \u4ECD\u5728\u8FD0\u884C\u3002");
1939
1999
  requireThat(this.list(owner).filter((v) => v.alive).length < 50, "\u6700\u591A 50 \u4E2A\u5B58\u6D3B\u6216\u542F\u52A8\u4E2D worker\u3002");
1940
- const previous = this.files.read(id, "launch.json", launch), interrupted = this.cycles(id, owner);
2000
+ const previous = this.files.worker(id), interrupted = this.cycles(id, owner);
1941
2001
  const pending = { generation: previous.generation, controller: new AbortController(), stage: "validate" };
1942
2002
  this.#starting.set(id, pending);
1943
2003
  return { previous, interrupted, pending };
@@ -1947,21 +2007,43 @@ var AgentService = class {
1947
2007
  requireThat(!this.#closed || this.#preserve, "worker \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
1948
2008
  reserved.pending.controller.signal.throwIfAborted();
1949
2009
  const prepared = this.files.control(() => {
1950
- requireThat(!this.host.alive(id) && this.files.read(id, "launch.json", launch).generation === reserved.previous.generation, "worker \u5DF2\u7531\u5176\u4ED6\u64CD\u4F5C\u6062\u590D\u3002");
1951
- for (const ended of reserved.interrupted) {
1952
- if (ended.generation === reserved.previous.generation && !this.files.completions(id).some((c) => c.cycleId === ended.cycleId)) {
1953
- this.files.write(id, "completions/" + ended.cycleId + ".json", ended, cycle, true);
1954
- }
2010
+ requireThat(!this.host.alive(id) && this.files.worker(id).generation === reserved.previous.generation, "worker \u5DF2\u7531\u5176\u4ED6\u64CD\u4F5C\u6062\u590D\u3002");
2011
+ const existingOutput = this.files.output(id);
2012
+ const lastInterrupted = reserved.interrupted.findLast(
2013
+ (ended) => ended.generation === reserved.previous.generation && existingOutput?.cycleId !== ended.cycleId
2014
+ );
2015
+ if (lastInterrupted && lastInterrupted.state !== "running") {
2016
+ this.files.write(id, "output.json", {
2017
+ cycleId: lastInterrupted.cycleId,
2018
+ generation: lastInterrupted.generation,
2019
+ startedAt: lastInterrupted.startedAt,
2020
+ finishedAt: lastInterrupted.finishedAt ?? Date.now(),
2021
+ state: lastInterrupted.state,
2022
+ requestIds: lastInterrupted.requestIds,
2023
+ text: "",
2024
+ ...lastInterrupted.error ? { error: lastInterrupted.error } : {}
2025
+ }, outputRecord);
1955
2026
  }
1956
- const run = { ...reserved.previous, generation: randomUUID3(), sequence: 0, stop: false, startedAt: Date.now() };
1957
- this.files.write(id, "launch.json", run, launch);
2027
+ this.files.clearTransient(id);
2028
+ const next = {
2029
+ ...reserved.previous,
2030
+ generation: randomUUID3(),
2031
+ sequence: 0,
2032
+ stop: false,
2033
+ startedAt: Date.now()
2034
+ };
2035
+ delete next.pid;
2036
+ this.files.write(id, "worker.json", next, workerRecord);
1958
2037
  const request = text3 === void 0 ? void 0 : this.files.enqueue(id, text3, "steer");
1959
- reserved.pending.generation = run.generation;
2038
+ reserved.pending.generation = next.generation;
1960
2039
  reserved.pending.stage = "launch";
1961
- return { run, request };
2040
+ return { run: next, request };
1962
2041
  });
1963
2042
  await this.launch(d, prepared.run.generation, true);
1964
- return { ...this.view(d, owner), ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {} };
2043
+ return {
2044
+ ...this.view(this.files.worker(id), owner),
2045
+ ...prepared.request ? { requestId: prepared.request.requestId, messageStatus: "queued" } : {}
2046
+ };
1965
2047
  })();
1966
2048
  this.#launches.add(operation);
1967
2049
  try {
@@ -1976,36 +2058,44 @@ var AgentService = class {
1976
2058
  }
1977
2059
  cyclesFor(view) {
1978
2060
  const id = view.agentId;
1979
- const values = this.files.completions(id);
2061
+ const values = [];
2062
+ const output = this.files.output(id);
2063
+ if (output) {
2064
+ values.push({
2065
+ cycleId: output.cycleId,
2066
+ generation: output.generation,
2067
+ startedAt: output.startedAt,
2068
+ finishedAt: output.finishedAt,
2069
+ state: output.state,
2070
+ requestIds: output.requestIds,
2071
+ ...output.error ? { error: output.error } : {}
2072
+ });
2073
+ }
1980
2074
  if (view.cycle && !values.some((c) => c.cycleId === view.cycle.cycleId)) {
1981
2075
  values.push(view.state === "stopped" || view.state === "error" ? { ...view.cycle, state: "interrupted", finishedAt: view.cycle.finishedAt ?? Date.now() } : view.cycle);
1982
2076
  }
1983
2077
  if (["stopped", "error"].includes(view.state)) {
1984
- const run = this.files.read(id, "launch.json", launch), saved = this.files.optional(id, "status.json", status);
1985
- for (const requestId of saved?.generation === run.generation ? saved.accepted ?? [] : []) {
1986
- if (values.some((c) => c.generation === run.generation && c.requestIds.includes(requestId))) continue;
2078
+ const w = this.files.worker(id), saved = this.files.optional(id, "state.json", status);
2079
+ for (const requestId of saved?.generation === w.generation ? saved.accepted ?? [] : []) {
2080
+ if (values.some((c) => c.generation === w.generation && c.requestIds.includes(requestId))) continue;
1987
2081
  values.push({
1988
2082
  cycleId: requestId,
1989
- generation: run.generation,
1990
- startedAt: run.startedAt,
2083
+ generation: w.generation,
2084
+ startedAt: w.startedAt,
1991
2085
  finishedAt: Date.now(),
1992
2086
  state: "interrupted",
1993
- leaf: null,
1994
2087
  requestIds: [requestId],
1995
- source: "parent",
1996
2088
  error: "\u9886\u53D6\u540E\u6267\u884C\u7ED3\u679C\u4E0D\u660E\uFF1B\u672A\u91CD\u8DD1\u3002"
1997
2089
  });
1998
2090
  }
1999
- if (run.sequence > 0 && !values.some((c) => c.generation === view.generation)) {
2091
+ if (w.sequence > 0 && !values.some((c) => c.generation === view.generation)) {
2000
2092
  values.push({
2001
- cycleId: run.generation,
2002
- generation: run.generation,
2003
- startedAt: run.startedAt,
2004
- finishedAt: run.startedAt,
2093
+ cycleId: w.generation,
2094
+ generation: w.generation,
2095
+ startedAt: w.startedAt,
2096
+ finishedAt: w.startedAt,
2005
2097
  state: "interrupted",
2006
- leaf: null,
2007
2098
  requestIds: [],
2008
- source: "parent",
2009
2099
  error: view.error ?? "\u5B50\u8FDB\u7A0B\u5728\u4EA4\u4ED8\u524D\u9000\u51FA\u3002"
2010
2100
  });
2011
2101
  }
@@ -2030,14 +2120,15 @@ var AgentService = class {
2030
2120
  return { current, cycle: cycle2, terminal };
2031
2121
  }
2032
2122
  async read(id, owner, cycleId, offset = 0, limit = 16e3) {
2033
- const d = this.get(id, owner), cycles = this.cycles(id, owner);
2123
+ const w = this.get(id, owner), cycles = this.cycles(id, owner);
2034
2124
  const c = cycleId ? cycles.find((v) => v.cycleId === cycleId) : cycles.at(-1);
2035
2125
  requireThat(!cycleId || c, "\u5468\u671F\u4E0D\u5B58\u5728\u3002");
2036
- const report = c ? await this.report(d, c) : "";
2126
+ const output = this.files.output(id);
2127
+ const report = c && output?.cycleId === c.cycleId ? output.text : "";
2037
2128
  this.check();
2038
2129
  requireThat(offset <= report.length, "\u5206\u9875\u4F4D\u7F6E\u8D85\u51FA\u62A5\u544A\u3002");
2039
2130
  return {
2040
- ...this.view(d, owner),
2131
+ ...this.view(w, owner),
2041
2132
  ...c ? { cycle: c } : {},
2042
2133
  cycles: cycles.map((v) => ({ cycleId: v.cycleId, state: v.state })),
2043
2134
  report: report.slice(offset, offset + limit),
@@ -2045,16 +2136,15 @@ var AgentService = class {
2045
2136
  nextOffset: offset + limit < report.length ? offset + limit : null
2046
2137
  };
2047
2138
  }
2048
- report(d, c) {
2049
- if (c.leaf === null) return "";
2050
- return this.host.report(d, this.files.reference(d.agentId), c.leaf);
2051
- }
2052
2139
  release(id) {
2053
2140
  let pending = this.#releasing.get(id);
2054
2141
  if (!pending) {
2055
- const generation = this.files.read(id, "launch.json", launch).generation;
2142
+ const generation = this.files.worker(id).generation;
2056
2143
  pending = Promise.resolve().then(async () => {
2057
- if (this.files.read(id, "launch.json", launch).generation === generation) await this.host.release(id, generation);
2144
+ if (this.files.worker(id).generation === generation) {
2145
+ await this.host.release(id, generation);
2146
+ this.files.clearTransient(id);
2147
+ }
2058
2148
  }).finally(() => this.#releasing.delete(id));
2059
2149
  this.#releasing.set(id, pending);
2060
2150
  }
@@ -2065,11 +2155,12 @@ var AgentService = class {
2065
2155
  }
2066
2156
  async dispose(owner, preserve = false) {
2067
2157
  if (this.#closed) return;
2068
- const ids = !preserve && owner ? this.list(owner).filter((v) => v.alive).map((v) => v.agentId) : [];
2158
+ const ownedRecords = !preserve && owner ? this.records(owner) : [];
2159
+ const aliveIds = ownedRecords.filter((w) => this.alive(w.agentId)).map((w) => w.agentId);
2069
2160
  this.#closed = true;
2070
2161
  this.#preserve = preserve;
2071
2162
  const errors = [];
2072
- for (const id of ids) {
2163
+ for (const id of aliveIds) {
2073
2164
  try {
2074
2165
  this.requestStop(id);
2075
2166
  } catch (error) {
@@ -2078,18 +2169,29 @@ var AgentService = class {
2078
2169
  }
2079
2170
  if (!preserve) for (const pending of this.#starting.values()) pending.controller.abort();
2080
2171
  const deadline = Date.now() + 5e3;
2081
- while (ids.some((id) => this.alive(id)) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
2082
- const released = await Promise.allSettled(ids.filter((id) => this.host.alive(id)).map((id) => this.release(id)));
2172
+ while (aliveIds.some((id) => this.alive(id)) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
2173
+ const released = await Promise.allSettled(aliveIds.filter((id) => this.host.alive(id)).map((id) => this.release(id)));
2083
2174
  for (const value of released) if (value.status === "rejected") errors.push(value.reason);
2084
2175
  await Promise.allSettled([...this.#launches]);
2176
+ if (!preserve && owner) {
2177
+ for (const w of ownedRecords) {
2178
+ if (!this.host.alive(w.agentId)) {
2179
+ try {
2180
+ this.files.removeWorker(w.agentId);
2181
+ } catch (error) {
2182
+ errors.push(error);
2183
+ }
2184
+ }
2185
+ }
2186
+ }
2085
2187
  if (errors.length) throw new AggregateError(errors, "\u505C\u6B62\u6216\u91CA\u653E worker \u5931\u8D25\uFF1B\u8BF7\u6838\u5BF9\u4ECD\u5B58\u6D3B\u7684\u6267\u884C\u8D44\u6E90\u3002");
2086
2188
  }
2087
2189
  };
2088
2190
 
2089
2191
  // src/storage/history-files.ts
2090
2192
  import { spawnSync as spawnSync2 } from "node:child_process";
2091
- import { linkSync as linkSync2, lstatSync as lstatSync3, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, realpathSync as realpathSync4, rmdirSync as rmdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
2092
- import { basename as basename2, dirname as dirname3, join as join9, relative as relative2, resolve as resolve7 } from "node:path";
2193
+ import { linkSync as linkSync2, lstatSync as lstatSync3, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync3, realpathSync as realpathSync4, rmdirSync as rmdirSync3, unlinkSync as unlinkSync3 } from "node:fs";
2194
+ import { basename as basename2, dirname as dirname3, join as join8, relative as relative2, resolve as resolve7 } from "node:path";
2093
2195
  import { isDeepStrictEqual } from "node:util";
2094
2196
 
2095
2197
  // src/storage/history-format.ts
@@ -2234,7 +2336,7 @@ function bucketDirs(directory, depth) {
2234
2336
  buckets.push(...years);
2235
2337
  } else {
2236
2338
  for (const year of years) {
2237
- const yearDir = join9(directory, year);
2339
+ const yearDir = join8(directory, year);
2238
2340
  const months = readdirSync2(yearDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && monthPattern.test(entry.name)).map((entry) => entry.name).sort((a, b) => b.localeCompare(a));
2239
2341
  for (const month of months) buckets.push(`${year}/${month}`);
2240
2342
  }
@@ -2249,7 +2351,7 @@ function listLayoutJsonFiles(directory, layout, depth = "month") {
2249
2351
  if (layout === "flat") return topLevelJsonNames(directory);
2250
2352
  const results = [];
2251
2353
  for (const bucket of bucketDirs(directory, depth)) {
2252
- const dir = join9(directory, bucket);
2354
+ const dir = join8(directory, bucket);
2253
2355
  for (const name of topLevelJsonNames(dir)) {
2254
2356
  results.push(`${bucket}/${name}`);
2255
2357
  }
@@ -2259,10 +2361,10 @@ function listLayoutJsonFiles(directory, layout, depth = "month") {
2259
2361
  function locateLayoutFile(directory, name, layout, depth = "month") {
2260
2362
  if (!ordinaryDirectory(directory)) return void 0;
2261
2363
  if (layout === "flat") {
2262
- return ordinaryFile(join9(directory, name)) ? name : void 0;
2364
+ return ordinaryFile(join8(directory, name)) ? name : void 0;
2263
2365
  }
2264
2366
  for (const bucket of bucketDirs(directory, depth)) {
2265
- if (ordinaryFile(join9(directory, bucket, name))) return `${bucket}/${name}`;
2367
+ if (ordinaryFile(join8(directory, bucket, name))) return `${bucket}/${name}`;
2266
2368
  }
2267
2369
  return void 0;
2268
2370
  }
@@ -2329,7 +2431,7 @@ function findCandidateJsonFiles(directory, query, layout = "monthly", depth = "m
2329
2431
  const matched = [];
2330
2432
  for (const rel of listLayoutJsonFiles(directory, layout, depth)) {
2331
2433
  try {
2332
- const content = readFileSync3(join9(directory, rel), "utf8");
2434
+ const content = readFileSync3(join8(directory, rel), "utf8");
2333
2435
  if (content.toLowerCase().includes(needle)) matched.push(rel);
2334
2436
  } catch {
2335
2437
  }
@@ -2352,18 +2454,18 @@ var HistoryFiles = class {
2352
2454
  return this.#rawWarnings;
2353
2455
  }
2354
2456
  get rawDirectory() {
2355
- return join9(this.directory, "raw");
2457
+ return join8(this.directory, "raw");
2356
2458
  }
2357
2459
  get summariesDirectory() {
2358
- return join9(this.directory, "summaries");
2460
+ return join8(this.directory, "summaries");
2359
2461
  }
2360
2462
  summaryDirectory(dimension) {
2361
2463
  requireThat(isHistoryIdentifier(dimension), "\u5386\u53F2\u6458\u8981\u7EF4\u5EA6\u65E0\u6548\uFF1A" + dimension);
2362
- return join9(this.summariesDirectory, dimension);
2464
+ return join8(this.summariesDirectory, dimension);
2363
2465
  }
2364
2466
  withLock(lockName, label, operation) {
2365
2467
  ensureDirectory(this.directory);
2366
- const lock = join9(this.directory, lockName);
2468
+ const lock = join8(this.directory, lockName);
2367
2469
  try {
2368
2470
  mkdirSync4(lock, { mode: 448 });
2369
2471
  } catch (error) {
@@ -2375,7 +2477,7 @@ var HistoryFiles = class {
2375
2477
  try {
2376
2478
  return operation();
2377
2479
  } finally {
2378
- rmdirSync2(lock);
2480
+ rmdirSync3(lock);
2379
2481
  }
2380
2482
  }
2381
2483
  /** Synchronous host write lock for raw history files. */
@@ -2448,7 +2550,7 @@ var HistoryFiles = class {
2448
2550
  throw error;
2449
2551
  }
2450
2552
  syncDirectory(dirname3(dst));
2451
- unlinkSync2(src);
2553
+ unlinkSync3(src);
2452
2554
  syncDirectory(dirname3(src));
2453
2555
  return "moved";
2454
2556
  }
@@ -2459,7 +2561,7 @@ var HistoryFiles = class {
2459
2561
  const files = onlyFiles ?? listLayoutJsonFiles(this.rawDirectory, this.layout);
2460
2562
  const results = [];
2461
2563
  for (const rel of files) {
2462
- const path = join9(this.rawDirectory, rel);
2564
+ const path = join8(this.rawDirectory, rel);
2463
2565
  try {
2464
2566
  const raw = readJsonFile(this.directory, "raw/" + rel, (value) => namedRaw(value, rel));
2465
2567
  if (filterHost !== void 0 && raw.host !== filterHost) continue;
@@ -2513,7 +2615,7 @@ var HistoryFiles = class {
2513
2615
  const files = onlyFiles ?? listLayoutJsonFiles(dir, this.layout, this.summaryBucketDepth(dimension));
2514
2616
  const results = [];
2515
2617
  for (const rel of files) {
2516
- const path = join9(dir, rel);
2618
+ const path = join8(dir, rel);
2517
2619
  try {
2518
2620
  results.push(readJsonFile(this.directory, `summaries/${dimension}/${rel}`, (value) => namedSummary(value, rel, dimension)));
2519
2621
  } catch (error) {
@@ -2564,12 +2666,12 @@ var HistoryFiles = class {
2564
2666
  };
2565
2667
 
2566
2668
  // src/services/history/workspace-history.ts
2567
- import { join as join11 } from "node:path";
2669
+ import { join as join10 } from "node:path";
2568
2670
 
2569
2671
  // src/services/workspace/workspace-config.ts
2570
2672
  import { readFileSync as readFileSync4 } from "node:fs";
2571
2673
  import { mkdir, readFile as readFile2 } from "node:fs/promises";
2572
- import { dirname as dirname4, join as join10 } from "node:path";
2674
+ import { dirname as dirname4, join as join9 } from "node:path";
2573
2675
 
2574
2676
  // src/model/workspace-config.ts
2575
2677
  var summaryConcurrency = { default: 3, max: 8 };
@@ -2596,8 +2698,8 @@ function config(value) {
2596
2698
  throw new Error("acp \u952E\u540D\u5FC5\u987B\u4E3A\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\uFF081\u201364 \u5B57\u7B26\uFF09\u3002");
2597
2699
  }
2598
2700
  for (const command of Object.values(value.acp)) {
2599
- const launch2 = !object(command) ? false : command.command === void 0 ? command.args === void 0 : typeof command.command === "string" && command.command.trim() && !command.command.includes("\0") && (command.args === void 0 || Array.isArray(command.args) && command.args.every((arg) => typeof arg === "string" && !arg.includes("\0")));
2600
- if (!object(command) || !launch2 || command.env !== void 0 && (!object(command.env) || Object.entries(command.env).some(([k, v]) => !k || k.includes("\0") || typeof v !== "string" || v.includes("\0"))) || command.permission !== void 0 && !isOneOf(command.permission, acpPermissionPolicies) || Object.keys(command).some((key) => !["command", "args", "env", "permission"].includes(key))) {
2701
+ const launch = !object(command) ? false : command.command === void 0 ? command.args === void 0 : typeof command.command === "string" && command.command.trim() && !command.command.includes("\0") && (command.args === void 0 || Array.isArray(command.args) && command.args.every((arg) => typeof arg === "string" && !arg.includes("\0")));
2702
+ if (!object(command) || !launch || command.env !== void 0 && (!object(command.env) || Object.entries(command.env).some(([k, v]) => !k || k.includes("\0") || typeof v !== "string" || v.includes("\0"))) || command.permission !== void 0 && !isOneOf(command.permission, acpPermissionPolicies) || Object.keys(command).some((key) => !["command", "args", "env", "permission"].includes(key))) {
2601
2703
  throw new Error("ACP \u914D\u7F6E\u9700\u8981 command\uFF08\u5185\u7F6E\u76EE\u6807\u53EF\u7701\u7565\uFF09\u53CA\u53EF\u9009 args \u5B57\u7B26\u4E32\u6570\u7EC4\u3001env \u5B57\u7B26\u4E32\u6620\u5C04\u3001permission\uFF08ask\u3001allow \u6216 deny\uFF09\u3002");
2602
2704
  }
2603
2705
  }
@@ -2645,7 +2747,7 @@ function workspaceHistoryConfig(configuration) {
2645
2747
  };
2646
2748
  }
2647
2749
  function workspaceConfigPath(root) {
2648
- return join10(root, ".pbot", "config.json");
2750
+ return join9(root, ".pbot", "config.json");
2649
2751
  }
2650
2752
  function readWorkspaceHistoryLayoutSync(root) {
2651
2753
  const path = workspaceConfigPath(root);
@@ -2688,7 +2790,7 @@ function workspaceDisabledMessage(configuration) {
2688
2790
 
2689
2791
  // src/services/history/workspace-history.ts
2690
2792
  function workspaceHistoryFiles(root, host) {
2691
- return new HistoryFiles(join11(root, ".pbot/history"), host, readWorkspaceHistoryLayoutSync(root));
2793
+ return new HistoryFiles(join10(root, ".pbot/history"), host, readWorkspaceHistoryLayoutSync(root));
2692
2794
  }
2693
2795
 
2694
2796
  // src/services/history/history-index.ts
@@ -3032,7 +3134,7 @@ import { setTimeout as delay2 } from "node:timers/promises";
3032
3134
 
3033
3135
  // src/services/workspace/workspace-mcp.ts
3034
3136
  import { mkdir as mkdir2, readFile as readFile3 } from "node:fs/promises";
3035
- import { dirname as dirname5, join as join12, resolve as resolve8 } from "node:path";
3137
+ import { dirname as dirname5, join as join11, resolve as resolve8 } from "node:path";
3036
3138
  var serverNamePattern = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
3037
3139
  var reservedServerNames = /* @__PURE__ */ new Set(["pbot"]);
3038
3140
  var stdioKeys = /* @__PURE__ */ new Set(["command", "args", "env", "cwd", "description", "timeout", "enabled"]);
@@ -3142,7 +3244,7 @@ function validateMcpFile(value) {
3142
3244
  return { ...value, mcpServers: servers };
3143
3245
  }
3144
3246
  function workspaceMcpPath(root) {
3145
- return join12(root, ".pbot", "mcp.json");
3247
+ return join11(root, ".pbot", "mcp.json");
3146
3248
  }
3147
3249
  async function readWorkspaceMcpConfig(root) {
3148
3250
  const path = workspaceMcpPath(root);
@@ -3571,10 +3673,9 @@ function buildMcpInstructions(options) {
3571
3673
  }
3572
3674
  var mcpWorkerOnlyInstructions = buildMcpInstructions({ workspaceMcp: false, history: false });
3573
3675
  var mcpInstructions = buildMcpInstructions({ workspaceMcp: true, history: true });
3574
- function defaultWorkerDirectory() {
3676
+ function defaultWorkerDirectory(workspaceRoot) {
3575
3677
  if (process.env.PBOT_MCP_AGENT_DIR) return process.env.PBOT_MCP_AGENT_DIR;
3576
- if (process.env.PLUGIN_DATA) return join13(process.env.PLUGIN_DATA, "subagents");
3577
- return join13(homedir(), ".pbot/subagents");
3678
+ return join12(workspaceRoot, ".pbot", "subagents");
3578
3679
  }
3579
3680
  function asString(args, key, required = false) {
3580
3681
  const value = args[key];
@@ -3633,6 +3734,7 @@ function presentWorker(value) {
3633
3734
  }
3634
3735
  var McpWorkerRuntime = class {
3635
3736
  #services = /* @__PURE__ */ new Map();
3737
+ #workerWorkspaces = /* @__PURE__ */ new Map();
3636
3738
  #bridge = new WorkspaceMcpBridge();
3637
3739
  #sessionId;
3638
3740
  #directory;
@@ -3640,7 +3742,7 @@ var McpWorkerRuntime = class {
3640
3742
  #nativeWorkspaceMcp;
3641
3743
  #nativeHistory;
3642
3744
  #closing;
3643
- constructor(directory = defaultWorkerDirectory(), sessionId = process.env.PBOT_MCP_SESSION_ID || "mcp-" + randomUUID4(), defaultBackend = process.env.PBOT_HOST || void 0, nativeWorkspaceMcp = /^(1|true)$/i.test(process.env.PBOT_NATIVE_WORKSPACE_MCP ?? ""), nativeHistory = /^(1|true)$/i.test(process.env.PBOT_NATIVE_HISTORY ?? "")) {
3745
+ constructor(directory, sessionId = process.env.PBOT_MCP_SESSION_ID || "mcp-" + randomUUID4(), defaultBackend = process.env.PBOT_HOST || void 0, nativeWorkspaceMcp = /^(1|true)$/i.test(process.env.PBOT_NATIVE_WORKSPACE_MCP ?? ""), nativeHistory = /^(1|true)$/i.test(process.env.PBOT_NATIVE_HISTORY ?? "")) {
3644
3746
  this.#directory = directory;
3645
3747
  this.#sessionId = sessionId;
3646
3748
  this.#defaultBackend = defaultBackend?.trim() || void 0;
@@ -3649,7 +3751,7 @@ var McpWorkerRuntime = class {
3649
3751
  }
3650
3752
  /** Mount the stdio sibling with the same worker ownership as the native host command. */
3651
3753
  nativeServer(root) {
3652
- const entry = join13(resourceRoot, "../lib/extension/mcp.js");
3754
+ const entry = join12(resourceRoot, "../lib/extension/mcp.js");
3653
3755
  if (!existsSync3(entry)) return void 0;
3654
3756
  requireThat(this.#defaultBackend, "\u539F\u751F MCP \u6302\u8F7D\u9700\u8981\u5BBF\u4E3B\u540D\u79F0\u3002");
3655
3757
  return {
@@ -3658,7 +3760,7 @@ var McpWorkerRuntime = class {
3658
3760
  env: {
3659
3761
  PBOT_HOST: this.#defaultBackend,
3660
3762
  PBOT_WORKSPACE_ROOT: root,
3661
- PBOT_MCP_AGENT_DIR: this.#directory,
3763
+ PBOT_MCP_AGENT_DIR: this.#directory ?? defaultWorkerDirectory(root),
3662
3764
  PBOT_MCP_SESSION_ID: this.#sessionId,
3663
3765
  PBOT_NATIVE_WORKSPACE_MCP: "1",
3664
3766
  PBOT_NATIVE_HISTORY: "1"
@@ -3685,13 +3787,25 @@ var McpWorkerRuntime = class {
3685
3787
  requireThat((await stat3(root)).isDirectory(), "\u5DE5\u4F5C\u533A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55\u3002");
3686
3788
  return root;
3687
3789
  }
3790
+ async resolveWorkerWorkspace(workerId, defaultWorkspace) {
3791
+ const known = this.#workerWorkspaces.get(workerId);
3792
+ if (known) return known;
3793
+ for (const [root, entry] of this.#services) {
3794
+ if (entry.service.has(workerId, entry.owner)) {
3795
+ this.#workerWorkspaces.set(workerId, root);
3796
+ return root;
3797
+ }
3798
+ }
3799
+ return this.resolveWorkspace(defaultWorkspace);
3800
+ }
3688
3801
  workerService(root, commands = {}) {
3689
3802
  let entry = this.#services.get(root);
3690
3803
  if (!entry) {
3691
- const host = new AcpWorkerHost(this.#directory, commands);
3804
+ const directory = this.#directory ?? defaultWorkerDirectory(root);
3805
+ const host = new AcpWorkerHost(directory, commands);
3692
3806
  entry = {
3693
3807
  host,
3694
- service: new AgentService(root, this.#directory, host),
3808
+ service: new AgentService(root, directory, host),
3695
3809
  owner: { sessionId: this.#sessionId, leaf: null, branch: [] }
3696
3810
  };
3697
3811
  this.#services.set(root, entry);
@@ -3793,10 +3907,11 @@ var McpWorkerRuntime = class {
3793
3907
  await delay3(100);
3794
3908
  }
3795
3909
  }
3796
- async callTool(toolName, input, progress) {
3910
+ async callTool(toolName, input, progress, defaultWorkspace) {
3797
3911
  const { name, args: rawArgs } = parseMcpToolCall(toolName, input);
3798
3912
  requireThat(!this.#closing, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
3799
- const root = await this.resolveWorkspace(asString(rawArgs, "workspace"));
3913
+ const isWorkerScoped = name === "worker_close" || name === "worker_request" || name === "worker_response" || name === "worker_output";
3914
+ const root = isWorkerScoped ? await this.resolveWorkerWorkspace(asString(rawArgs, "workerId", true), defaultWorkspace) : await this.resolveWorkspace(asString(rawArgs, "workspace") ?? defaultWorkspace);
3800
3915
  const configuration = await readWorkspaceConfig(root);
3801
3916
  requireThat(!this.#closing, "Personal Bot MCP \u670D\u52A1\u5DF2\u5173\u95ED\u3002");
3802
3917
  requireThat(configuration.enabled, workspaceDisabledMessage(configuration));
@@ -3854,13 +3969,12 @@ var McpWorkerRuntime = class {
3854
3969
  const backend = this.resolveBackend(rawArgs, configuration.acp, false);
3855
3970
  const model = asString(rawArgs, "model");
3856
3971
  const thinking = asString(rawArgs, "thinking");
3857
- const cwd = asString(rawArgs, "cwd");
3858
3972
  const created = await service.start({
3859
3973
  backend,
3860
3974
  ...model ? { model } : {},
3861
- ...thinking ? { thinking } : {},
3862
- ...cwd ? { cwd } : {}
3975
+ ...thinking ? { thinking } : {}
3863
3976
  }, owner);
3977
+ this.#workerWorkspaces.set(created.agentId, root);
3864
3978
  const ready = await this.waitReady(service, owner, created.agentId, readyTimeoutMs, progress);
3865
3979
  return {
3866
3980
  ...presentWorker(ready),
@@ -3935,19 +4049,23 @@ var McpWorkerRuntime = class {
3935
4049
  requireThat(backendRaw === void 0 && model === void 0, '\u53C2\u6570 backend / model \u4EC5\u5728 target="models" \u65F6\u53EF\u7528\u3002');
3936
4050
  }
3937
4051
  if (target === "overview") {
4052
+ const workers = service.list(owner);
4053
+ for (const item of workers) this.#workerWorkspaces.set(item.agentId, root);
3938
4054
  return {
3939
4055
  target,
3940
4056
  backends: inspectAcpBackends(configuration.acp),
3941
- workers: service.list(owner).map(presentWorker)
4057
+ workers: workers.map(presentWorker)
3942
4058
  };
3943
4059
  }
3944
4060
  if (target === "backends") {
3945
4061
  return { target, backends: inspectAcpBackends(configuration.acp) };
3946
4062
  }
3947
4063
  if (target === "workers") {
4064
+ const workers = workerId ? [service.status(workerId, owner)] : service.list(owner);
4065
+ for (const item of workers) this.#workerWorkspaces.set(item.agentId, root);
3948
4066
  return {
3949
4067
  target,
3950
- workers: workerId ? [presentWorker(service.status(workerId, owner))] : service.list(owner).map(presentWorker)
4068
+ workers: workers.map(presentWorker)
3951
4069
  };
3952
4070
  }
3953
4071
  const backend = this.resolveBackend(rawArgs, configuration.acp, true);
@@ -3963,6 +4081,7 @@ var McpWorkerRuntime = class {
3963
4081
  if (this.#closing) return this.#closing;
3964
4082
  const entries = [...this.#services.values()];
3965
4083
  this.#services.clear();
4084
+ this.#workerWorkspaces.clear();
3966
4085
  this.#closing = Promise.allSettled([
3967
4086
  this.#bridge.close(),
3968
4087
  ...entries.map(({ service, owner }) => service.close(owner, preserve))