@1agents/acp-service 0.10.11 → 0.11.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 (126) hide show
  1. package/README.md +26 -0
  2. package/dist/bin/acp-service.js +6 -0
  3. package/dist/bin/dsh.d.ts +21 -0
  4. package/dist/bin/dsh.js +171 -0
  5. package/dist/src/catalog.js +13 -3
  6. package/dist/src/dsh-archive.d.ts +123 -0
  7. package/dist/src/dsh-archive.js +99 -0
  8. package/dist/src/dsh-host-client.d.ts +97 -0
  9. package/dist/src/dsh-host-client.js +275 -0
  10. package/dist/src/dsh-registry-file.d.ts +22 -0
  11. package/dist/src/dsh-registry-file.js +55 -0
  12. package/dist/src/dsh-session-files.d.ts +7 -0
  13. package/dist/src/dsh-session-files.js +63 -0
  14. package/dist/src/dsh.js +1 -1
  15. package/package.json +4 -4
  16. package/skills/acp-service/SKILL.md +1 -1
  17. package/vendor/dsh/README.md +1 -20
  18. package/vendor/dsh/index.d.ts +1 -4
  19. package/vendor/dsh/index.js +0 -17
  20. package/vendor/runtime/README.md +36 -11
  21. package/vendor/runtime/dist/{agent-registry-DxcyXXqb.js → agent-registry-CsdsVpJb.js} +209 -177
  22. package/vendor/runtime/dist/agent-registry-CsdsVpJb.js.map +1 -0
  23. package/vendor/runtime/dist/agent-registry.d.ts +0 -2
  24. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  25. package/vendor/runtime/dist/agent-registry.js +1 -1
  26. package/vendor/runtime/dist/{cli-BKmMxgix.js → cli-B5gQOSDl.js} +33 -14
  27. package/vendor/runtime/dist/cli-B5gQOSDl.js.map +1 -0
  28. package/vendor/runtime/dist/cli.d.ts +2 -6
  29. package/vendor/runtime/dist/cli.d.ts.map +1 -1
  30. package/vendor/runtime/dist/cli.js +189 -164
  31. package/vendor/runtime/dist/cli.js.map +1 -1
  32. package/vendor/runtime/dist/{client-C5zneoBs.d.ts → client-D5y4RXME.d.ts} +4 -12
  33. package/vendor/runtime/dist/client-D5y4RXME.d.ts.map +1 -0
  34. package/vendor/runtime/dist/docs-site/CLI.html +19 -21
  35. package/vendor/runtime/dist/docs-site/VISION.html +3 -2
  36. package/vendor/runtime/dist/docs-site/agents.html +10 -15
  37. package/vendor/runtime/dist/docs-site/assets/agents/Apache-2.0.txt +202 -0
  38. package/vendor/runtime/dist/docs-site/assets/agents/LobeHub-MIT.txt +21 -0
  39. package/vendor/runtime/dist/docs-site/assets/agents/Mux-AGPL-3.0.txt +661 -0
  40. package/vendor/runtime/dist/docs-site/assets/agents/README.md +41 -0
  41. package/vendor/runtime/dist/docs-site/assets/agents/ante.png +0 -0
  42. package/vendor/runtime/dist/docs-site/assets/agents/antigravity.png +0 -0
  43. package/vendor/runtime/dist/docs-site/assets/agents/claude.png +0 -0
  44. package/vendor/runtime/dist/docs-site/assets/agents/codex.png +0 -0
  45. package/vendor/runtime/dist/docs-site/assets/agents/copilot.png +0 -0
  46. package/vendor/runtime/dist/docs-site/assets/agents/cursor.png +0 -0
  47. package/vendor/runtime/dist/docs-site/assets/agents/deepseek-harness.png +0 -0
  48. package/vendor/runtime/dist/docs-site/assets/agents/devin.png +0 -0
  49. package/vendor/runtime/dist/docs-site/assets/agents/droid.png +0 -0
  50. package/vendor/runtime/dist/docs-site/assets/agents/fast-agent.png +0 -0
  51. package/vendor/runtime/dist/docs-site/assets/agents/fx.png +0 -0
  52. package/vendor/runtime/dist/docs-site/assets/agents/gemini.png +0 -0
  53. package/vendor/runtime/dist/docs-site/assets/agents/goose.png +0 -0
  54. package/vendor/runtime/dist/docs-site/assets/agents/grok-build.png +0 -0
  55. package/vendor/runtime/dist/docs-site/assets/agents/iflow.png +0 -0
  56. package/vendor/runtime/dist/docs-site/assets/agents/junie.png +0 -0
  57. package/vendor/runtime/dist/docs-site/assets/agents/kilocode.png +0 -0
  58. package/vendor/runtime/dist/docs-site/assets/agents/kimi.png +0 -0
  59. package/vendor/runtime/dist/docs-site/assets/agents/kiro.png +0 -0
  60. package/vendor/runtime/dist/docs-site/assets/agents/mcode.png +0 -0
  61. package/vendor/runtime/dist/docs-site/assets/agents/mux.png +0 -0
  62. package/vendor/runtime/dist/docs-site/assets/agents/octomind.png +0 -0
  63. package/vendor/runtime/dist/docs-site/assets/agents/openclaw.png +0 -0
  64. package/vendor/runtime/dist/docs-site/assets/agents/opencode.png +0 -0
  65. package/vendor/runtime/dist/docs-site/assets/agents/pi.png +0 -0
  66. package/vendor/runtime/dist/docs-site/assets/agents/pool.png +0 -0
  67. package/vendor/runtime/dist/docs-site/assets/agents/qoder.png +0 -0
  68. package/vendor/runtime/dist/docs-site/assets/agents/qwen.png +0 -0
  69. package/vendor/runtime/dist/docs-site/assets/agents/trae.png +0 -0
  70. package/vendor/runtime/dist/docs-site/assets/agents/zeroclaw.png +0 -0
  71. package/vendor/runtime/dist/docs-site/compare.html +8 -7
  72. package/vendor/runtime/dist/docs-site/config.html +5 -4
  73. package/vendor/runtime/dist/docs-site/custom-agents.html +13 -13
  74. package/vendor/runtime/dist/docs-site/exit-codes.html +4 -3
  75. package/vendor/runtime/dist/docs-site/flows.html +21 -8
  76. package/vendor/runtime/dist/docs-site/index.html +7 -6
  77. package/vendor/runtime/dist/docs-site/install.html +7 -6
  78. package/vendor/runtime/dist/docs-site/llms.txt +6 -6
  79. package/vendor/runtime/dist/docs-site/output-formats.html +9 -8
  80. package/vendor/runtime/dist/docs-site/permissions.html +5 -4
  81. package/vendor/runtime/dist/docs-site/prompting.html +9 -7
  82. package/vendor/runtime/dist/docs-site/quickstart.html +5 -4
  83. package/vendor/runtime/dist/docs-site/releasing.html +9 -8
  84. package/vendor/runtime/dist/docs-site/runtime-environment.html +28 -5
  85. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +13 -7
  86. package/vendor/runtime/dist/docs-site/safe-errors.html +3 -2
  87. package/vendor/runtime/dist/docs-site/session-control.html +7 -6
  88. package/vendor/runtime/dist/docs-site/session-watch.html +6 -5
  89. package/vendor/runtime/dist/docs-site/sessions.html +13 -10
  90. package/vendor/runtime/dist/docs-site/shared-sessions.html +7 -4
  91. package/vendor/runtime/dist/{flows-VrII9VKZ.js → flows-CDj5YcTh.js} +136 -68
  92. package/vendor/runtime/dist/flows-CDj5YcTh.js.map +1 -0
  93. package/vendor/runtime/dist/flows.d.ts +28 -19
  94. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  95. package/vendor/runtime/dist/flows.js +1 -1
  96. package/vendor/runtime/dist/{invocation-options-DHMZ5Rrb.js → input-file-BsfVGZgn.js} +30 -15
  97. package/vendor/runtime/dist/input-file-BsfVGZgn.js.map +1 -0
  98. package/vendor/runtime/dist/{ipc-CNNM5DP_.js → ipc-DfqJsbk6.js} +114 -146
  99. package/vendor/runtime/dist/ipc-DfqJsbk6.js.map +1 -0
  100. package/vendor/runtime/dist/{output-DtzXtiBc.js → output-DOIF4iFc.js} +20 -47
  101. package/vendor/runtime/dist/output-DOIF4iFc.js.map +1 -0
  102. package/vendor/runtime/dist/{queue-owner-runtime-ehuh3SQU.js → queue-owner-runtime-DHBQbjXo.js} +394 -258
  103. package/vendor/runtime/dist/queue-owner-runtime-DHBQbjXo.js.map +1 -0
  104. package/vendor/runtime/dist/runtime.d.ts +37 -36
  105. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  106. package/vendor/runtime/dist/runtime.js +117 -172
  107. package/vendor/runtime/dist/runtime.js.map +1 -1
  108. package/vendor/runtime/dist/{session-options-NjpFwf-c.d.ts → session-options-Ci4aw1oD.d.ts} +13 -16
  109. package/vendor/runtime/dist/session-options-Ci4aw1oD.d.ts.map +1 -0
  110. package/vendor/runtime/dist/{session-watch-CbKfGRkZ.js → session-watch-DRwFHcWw.js} +5 -6
  111. package/vendor/runtime/dist/{session-watch-CbKfGRkZ.js.map → session-watch-DRwFHcWw.js.map} +1 -1
  112. package/vendor/runtime/dist/{watch-BGt4kcE6.js → watch-CUDGkljG.js} +3 -4
  113. package/vendor/runtime/dist/{watch-BGt4kcE6.js.map → watch-CUDGkljG.js.map} +1 -1
  114. package/vendor/runtime/package.json +3 -3
  115. package/vendor/runtime/skills/acpx/SKILL.md +42 -11
  116. package/vendor/dsh/auto-archive.d.ts +0 -103
  117. package/vendor/dsh/auto-archive.js +0 -175
  118. package/vendor/runtime/dist/agent-registry-DxcyXXqb.js.map +0 -1
  119. package/vendor/runtime/dist/cli-BKmMxgix.js.map +0 -1
  120. package/vendor/runtime/dist/client-C5zneoBs.d.ts.map +0 -1
  121. package/vendor/runtime/dist/flows-VrII9VKZ.js.map +0 -1
  122. package/vendor/runtime/dist/invocation-options-DHMZ5Rrb.js.map +0 -1
  123. package/vendor/runtime/dist/ipc-CNNM5DP_.js.map +0 -1
  124. package/vendor/runtime/dist/output-DtzXtiBc.js.map +0 -1
  125. package/vendor/runtime/dist/queue-owner-runtime-ehuh3SQU.js.map +0 -1
  126. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +0 -1
@@ -1,5 +1,4 @@
1
- import { AgentCapabilities, AnyMessage, ContentBlock, CreateElicitationRequest, ElicitationContentValue, JsonRpcId, McpServer, McpServer as McpServer$1, RequestPermissionRequest, SessionConfigOption, SessionNotification, SetSessionConfigOptionResponse, ToolKind } from "@1agents/acp-runtime-sdk";
2
- //#region src/acp/grok-ask-user.d.ts
1
+ import { AgentCapabilities, AnyMessage, ContentBlock, CreateElicitationRequest, ElicitationContentValue, JsonRpcId, McpServer, McpServer as McpServer$1, RequestPermissionRequest, SessionConfigOption, SessionNotification as SessionNotification$1, ToolKind } from "@1agents/acp-runtime-sdk";
3
2
  type GrokAskUserOption = {
4
3
  label: string;
5
4
  description: string;
@@ -31,8 +30,6 @@ type GrokAskUserQuestionResponse = {
31
30
  } | {
32
31
  outcome: "cancelled";
33
32
  };
34
- //#endregion
35
- //#region src/acp/grok-exit-plan.d.ts
36
33
  type GrokExitPlanModeRequest = {
37
34
  sessionId: string;
38
35
  toolCallId: string;
@@ -43,11 +40,7 @@ type GrokExitPlanModeResponse = {
43
40
  outcome: GrokExitPlanOutcome;
44
41
  comments?: string | null;
45
42
  };
46
- //#endregion
47
- //#region src/prompt-content.d.ts
48
43
  type PromptInput = ContentBlock[];
49
- //#endregion
50
- //#region src/types.d.ts
51
44
  type AcpPermissionRequest = {
52
45
  sessionId: string;
53
46
  raw: RequestPermissionRequest;
@@ -206,8 +199,15 @@ type AcpClientOptions = {
206
199
  agentArgv?: string[];
207
200
  /** Trusted child-only environment overlay; never persisted as session options. */
208
201
  agentProcessEnv?: Record<string, string>;
202
+ /**
203
+ * Opt-in allowlist: agent children, probes and terminals inherit only process essentials,
204
+ * these parent names and `ACPX_AUTH_*` grants.
205
+ */
206
+ agentProcessEnvAllow?: readonly string[];
207
+ /** Parent environment names that agent children, probes and terminals do not inherit. */
208
+ agentProcessEnvBlock?: readonly string[];
209
209
  cwd: string;
210
- mcpServers?: McpServer[];
210
+ mcpServers?: McpServer$1[];
211
211
  permissionMode: PermissionMode;
212
212
  nonInteractivePermissions?: NonInteractivePermissionPolicy;
213
213
  permissionPolicy?: PermissionPolicy;
@@ -231,7 +231,7 @@ type AcpClientOptions = {
231
231
  };
232
232
  onAcpMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;
233
233
  onAcpOutputMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;
234
- onSessionUpdate?: (notification: SessionNotification) => void;
234
+ onSessionUpdate?: (notification: SessionNotification$1) => void;
235
235
  onClientOperation?: (operation: ClientOperation) => void;
236
236
  onPermissionEscalation?: (event: PermissionEscalationEvent) => void;
237
237
  onPermissionRequest?: AcpPermissionHandler;
@@ -419,8 +419,6 @@ type SessionRecord = {
419
419
  acpx?: SessionAcpxState;
420
420
  importedFrom?: SessionImportedFrom;
421
421
  };
422
- //#endregion
423
- //#region src/runtime/engine/session-options.d.ts
424
422
  type SystemPromptOption = string | {
425
423
  append: string;
426
424
  };
@@ -429,7 +427,7 @@ type SessionAgentOptions = {
429
427
  allowedTools?: string[];
430
428
  maxTurns?: number;
431
429
  systemPrompt?: SystemPromptOption;
432
- mcpServers?: McpServer$1[];
430
+ mcpServers?: McpServer[];
433
431
  /**
434
432
  * Per-agent environment variables injected into the spawned agent child
435
433
  * process and persisted with the session record for reconnects. Keys here
@@ -441,6 +439,5 @@ type SessionAgentOptions = {
441
439
  */
442
440
  env?: Record<string, string>;
443
441
  };
444
- //#endregion
445
- export { GrokExitPlanModeRequest as A, PermissionPolicy as C, SafeErrorOrigin as D, SafeErrorCategory as E, GrokAskUserQuestionResponse as F, GrokExitPlanOutcome as M, GrokAskUserAnswers as N, SessionRecord as O, GrokAskUserQuestionRequest as P, PermissionMode as S, SafeError as T, AcpProcessSpawnFailure as _, AcpElicitationHandler as a, McpServer$1 as b, AcpElicitationResponse as c, AcpPermissionHandler as d, AcpPermissionRequest as f, AcpProcessLifecycle as g, AcpProcessLaunchScope as h, AcpElicitationContext as i, GrokExitPlanModeResponse as j, PromptInput as k, AcpJsonRpcMessage as l, AcpProcessLaunch as m, SystemPromptOption as n, AcpElicitationMode as o, AcpProcessExit as p, AcpClientOptions as r, AcpElicitationRequest as s, SessionAgentOptions as t, AcpPermissionDecision as u, AcpProcessStarted as v, PermissionStats as w, NonInteractivePermissionPolicy as x, AuthPolicy as y };
446
- //# sourceMappingURL=session-options-NjpFwf-c.d.ts.map
442
+ export { PromptInput as A, PermissionMode as C, SafeErrorCategory as D, SafeError as E, GrokAskUserQuestionRequest as F, GrokAskUserQuestionResponse as I, GrokExitPlanModeResponse as M, GrokExitPlanOutcome as N, SafeErrorOrigin as O, GrokAskUserAnswers as P, NonInteractivePermissionPolicy as S, PermissionStats as T, AcpProcessLifecycle as _, AcpElicitationHandler as a, AuthPolicy as b, AcpElicitationResponse as c, AcpPermissionDecision as d, AcpPermissionHandler as f, AcpProcessLaunchScope as g, AcpProcessLaunch as h, AcpElicitationContext as i, GrokExitPlanModeRequest as j, SessionRecord as k, AcpJsonRpcMessage as l, AcpProcessExit as m, SystemPromptOption as n, AcpElicitationMode as o, AcpPermissionRequest as p, AcpClientOptions as r, AcpElicitationRequest as s, SessionAgentOptions as t, AcpMessageDirection as u, AcpProcessSpawnFailure as v, PermissionPolicy as w, McpServer as x, AcpProcessStarted as y };
443
+ //# sourceMappingURL=session-options-Ci4aw1oD.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-options-Ci4aw1oD.d.ts","names":["McpServer","SessionNotification"],"sources":["../src/acp/grok-ask-user.ts","../src/acp/grok-exit-plan.ts","../src/prompt-content.ts","../src/types.ts","../src/runtime/engine/session-options.ts"],"mappings":";KAYY;EACV;EACA;EACA;;KAGU;EACV;EACA,SAAS;;EAET;;KAGU;EACV;EACA;EACA,WAAW;EACX;;;KAIU;KAEA,qBAAqB,eAAe;KAEpC;EAEN;EACA,SAAS;EACT;;EAEA;;EACA;;EACA;;KC7BM;EACV;EACA;EACA;;KAGU;KAEA;EACV,SAAS;EACT;;KCxBU,cAAc;KC0Bd;EACV;EACA,KAAK;EACL,cAAc;;KAGJ;EACN;EAAqB;;EACrB;;EACA;;EACA;;EACA;;EACA;;KAEM,wBACV,SAAS,sBACT;EAAW,QAAQ;MAChB,QAAQ;cAEA;KACD,6BAA6B;KAC7B,wBAAwB;KAExB;;EAEV,WAAW;;EAEX,QAAQ;;KAGL;EACH,QAAQ;;KAGE;EAEN;EACA,UAAU,eAAe;IACvB;EACD;IAAsB;EACtB;IAAqB;KAEhB,yBACV,SAAS,uBACT,SAAS,0BACN,QAAQ;cAiBA;KACD,yBAAyB;cAExB;KACD,qBAAqB;cAEpB;KACD,yCAAyC;cAExC;KACD,iCAAiC;KAEjC;EACV;EACA;EACA;EACA,gBAAgB;;KAGN;EACV;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX;EACA;EACA;EACA;;KAMU,oBAAoB;KACpB;cAaC;KACD,4BAA4B;KAE5B;KAUA,kBAAkB;;KAGlB;EACV;EACA,UAAU;EACV;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;;KA4BU;EACV;EACA;EACA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EACT;;KAGU;EAEN;;EAGA;IACE;IACA;;;EAIF;;EAGA,SAAS;;KAGH;EACV;EACA,SAAS;;KAGC;EACV,SAAS;EACT,cAAc,eAAe;EAC7B;;KAGU;EAEN,MAAM;;EAGN,OAAO;;KAID;EACV;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;EACA;EACA;;KAYU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA,yBAAyB;EACzB;EACA;EACA,wBAAwB;EACxB;EACA,qBAAqB;EACrB,iBAAiB;EACjB;IACE;IACA;IACA;IACA;MAA2B;;IAC3B,MAAM;;EAER,eAAe,eAAe;;KAGpB;EACV;EACA;EACA;EACA;;KAGU;EACV,eAAe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU;EACV;EACA;EACA;EACA;EACA;EACA;EACA,sBAAsB,OAAO;EAC7B;EACA;EACA;EACA,oBAAoB;EACpB;EACA,UAAU;EACV;EACA,wBAAwB;EACxB,kBAAkB;EAClB,qBAAqB,eAAe;EACpC,OAAO;EACP,eAAe;;KC/jBL;EAAgC;;KAEhC;EACV;EACA;EACA;EACA,eAAe;EAKf,aAAa;;;;;;;;;;EAUb,MAAM"}
@@ -1,8 +1,8 @@
1
- import { i as JsonMessageSanitizer, t as createOutputFormatter } from "./output-DtzXtiBc.js";
2
- import { it as isAcpJsonRpcMessage, lt as parsePromptStopReason } from "./ipc-CNNM5DP_.js";
3
- import { t as watchSession } from "./watch-BGt4kcE6.js";
1
+ import { at as isAcpJsonRpcMessage, ut as parsePromptStopReason } from "./ipc-DfqJsbk6.js";
2
+ import { t as watchSession } from "./watch-CUDGkljG.js";
3
+ import { i as JsonMessageSanitizer, t as createOutputFormatter } from "./output-DOIF4iFc.js";
4
4
  import { once } from "node:events";
5
- //#region src/cli/session-watch.ts
5
+ // src/cli/session-watch.ts
6
6
  function watchRenderer(policy) {
7
7
  const chunks = [];
8
8
  const stdout = { write: (chunk) => {
@@ -70,7 +70,6 @@ async function runSessionWatch(record, options) {
70
70
  }
71
71
  if (outputError) throw outputError;
72
72
  }
73
- //#endregion
74
73
  export { runSessionWatch };
75
74
 
76
- //# sourceMappingURL=session-watch-CbKfGRkZ.js.map
75
+ //# sourceMappingURL=session-watch-DRwFHcWw.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-watch-CbKfGRkZ.js","names":[],"sources":["../src/cli/session-watch.ts"],"sourcesContent":["import { once } from \"node:events\";\nimport { isAcpJsonRpcMessage, parsePromptStopReason } from \"../acp/jsonrpc.js\";\nimport type { SessionWatchEvent } from \"../session/journal.js\";\nimport { watchSession } from \"../session/watch.js\";\nimport type { OutputFormatter, OutputPolicy, SessionRecord } from \"../types.js\";\nimport { JsonMessageSanitizer } from \"./output/json-formatter.js\";\nimport { createOutputFormatter } from \"./output/output.js\";\n\nfunction watchRenderer(policy: OutputPolicy): (event: SessionWatchEvent) => string[] {\n const chunks: string[] = [];\n const stdout = {\n write: (chunk: string) => {\n chunks.push(chunk);\n },\n };\n let sanitizer = new JsonMessageSanitizer(policy.suppressReads, true);\n let formatter = createOutputFormatter(policy.format, { stdout });\n return (event) => {\n chunks.length = 0;\n if (event.type === \"turn_started\") {\n sanitizer = new JsonMessageSanitizer(policy.suppressReads, true);\n formatter = createOutputFormatter(policy.format, { stdout });\n }\n if (policy.format === \"json\") {\n chunks.push(\n JSON.stringify(\n event.type === \"message\"\n ? { ...event, message: sanitizer.sanitize(event.message) }\n : event,\n ) + \"\\n\",\n );\n } else if (event.type === \"message\") {\n renderWatchMessage(event, sanitizer, formatter, policy.format === \"quiet\");\n } else {\n if (event.type === \"turn_result\") {\n formatter.flush();\n }\n if (policy.format !== \"quiet\") {\n chunks.push(watchLifecycleLine(event));\n }\n }\n return chunks;\n };\n}\n\nfunction renderWatchMessage(\n event: Extract<SessionWatchEvent, { type: \"message\" }>,\n sanitizer: JsonMessageSanitizer,\n formatter: OutputFormatter,\n quiet: boolean,\n): void {\n const message = sanitizer.sanitize(event.message);\n if (!isAcpJsonRpcMessage(message)) {\n throw new Error(\"Invalid sanitized session message\");\n }\n if (quiet || parsePromptStopReason(message) === undefined) {\n formatter.onAcpMessage(message);\n }\n}\n\nfunction watchLifecycleLine(event: Exclude<SessionWatchEvent, { type: \"message\" }>): string {\n if (event.type === \"turn_started\") {\n return `\\n[${event.requestId}] started cursor=${event.cursor}\\n`;\n }\n const detail =\n event.result.status === \"failed\" ? event.result.error.message : event.result.stopReason;\n return `\\n[${event.requestId}] ${event.result.status}${detail ? `: ${detail}` : \"\"} cursor=${event.cursor}\\n`;\n}\n\nexport async function runSessionWatch(\n record: SessionRecord,\n options: { cursor?: string; policy: OutputPolicy },\n): Promise<void> {\n const stopped = new AbortController();\n let outputError: Error | undefined;\n const stop = () => stopped.abort();\n const onOutputError = (error: Error) => {\n if ((error as NodeJS.ErrnoException).code !== \"EPIPE\") {\n outputError = error;\n }\n stop();\n };\n const render = watchRenderer(options.policy);\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n process.on(\"SIGHUP\", stop);\n process.stdout.on(\"error\", onOutputError);\n try {\n for await (const event of watchSession({\n record,\n cursor: options.cursor,\n signal: stopped.signal,\n })) {\n for (const chunk of render(event)) {\n if (stopped.signal.aborted) {\n break;\n }\n if (!process.stdout.write(chunk)) {\n await once(process.stdout, \"drain\", { signal: stopped.signal });\n }\n }\n }\n } catch (error) {\n if (!stopped.signal.aborted) {\n throw error;\n }\n } finally {\n process.off(\"SIGINT\", stop);\n process.off(\"SIGTERM\", stop);\n process.off(\"SIGHUP\", stop);\n process.stdout.off(\"error\", onOutputError);\n }\n if (outputError) {\n throw outputError;\n }\n}\n"],"mappings":";;;;;AAQA,SAAS,cAAc,QAA8D;CACnF,MAAM,SAAmB,CAAC;CAC1B,MAAM,SAAS,EACb,QAAQ,UAAkB;EACxB,OAAO,KAAK,KAAK;CACnB,EACF;CACA,IAAI,YAAY,IAAI,qBA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AM,iBAAiB,UAAiB;EACtC,IAAK,MAAgC,SAAS,SAC5C,cAAc;EAEhB,KAAK;CACP;CACA,MAAM,SAAS,cAAc,QAAQ,MAAM;CAC3C,QAAQ,GAAG,UAAU,IAAI;CACzB,QAAQ,GAAG,WAAW,IAAI;CAC1B,QAAQ,GAAG,UAAU,IAAI;CACzB,QAAQ,OAAO,GAAG,SAAS,aAAa;CACxC,IAAI;EACF,WAAW,MAAM,SAAS,aAAa;GACrC;GACA,QAAQ,QAAQ;GAChB,QAAQ,QAAQ;EAClB,CAAC,GACC,KAAK,MAAM,SAAS,OAAO,KAAK,GAAG;GACjC,IAAI,QAAQ,OAAO,SACjB;GAEF,IAAI,CAAC,QAAQ,OAAO,MAAM,KAAK,GAC7B,MAAM,KAAK,QAAQ,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,CAAC;EAElE;CAEJ,SAAS,OAAO;EACd,IAAI,CAAC,QAAQ,OAAO,SAClB,MAAM;CAEV,UAAU;EACR,QAAQ,IAAI,UAAU,IAAI;EAC1B,QAAQ,IAAI,WAAW,IAAI;EAC3B,QAAQ,IAAI,UAAU,IAAI;EAC1B,QAAQ,OAAO,IAAI,SAAS,aAAa;CAC3C;CACA,IAAI,aACF,MAAM;AAEV"}
1
+ {"version":3,"file":"session-watch-DRwFHcWw.js","names":[],"sources":["../src/cli/session-watch.ts"],"sourcesContent":["import { once } from \"node:events\";\nimport { isAcpJsonRpcMessage, parsePromptStopReason } from \"../acp/jsonrpc.js\";\nimport type { SessionWatchEvent } from \"../session/journal.js\";\nimport { watchSession } from \"../session/watch.js\";\nimport type { OutputFormatter, OutputPolicy, SessionRecord } from \"../types.js\";\nimport { JsonMessageSanitizer } from \"./output/json-formatter.js\";\nimport { createOutputFormatter } from \"./output/output.js\";\n\nfunction watchRenderer(policy: OutputPolicy): (event: SessionWatchEvent) => string[] {\n const chunks: string[] = [];\n const stdout = {\n write: (chunk: string) => {\n chunks.push(chunk);\n },\n };\n let sanitizer = new JsonMessageSanitizer(policy.suppressReads, true);\n let formatter = createOutputFormatter(policy.format, { stdout });\n return (event) => {\n chunks.length = 0;\n if (event.type === \"turn_started\") {\n sanitizer = new JsonMessageSanitizer(policy.suppressReads, true);\n formatter = createOutputFormatter(policy.format, { stdout });\n }\n if (policy.format === \"json\") {\n chunks.push(\n JSON.stringify(\n event.type === \"message\"\n ? { ...event, message: sanitizer.sanitize(event.message) }\n : event,\n ) + \"\\n\",\n );\n } else if (event.type === \"message\") {\n renderWatchMessage(event, sanitizer, formatter, policy.format === \"quiet\");\n } else {\n if (event.type === \"turn_result\") {\n formatter.flush();\n }\n if (policy.format !== \"quiet\") {\n chunks.push(watchLifecycleLine(event));\n }\n }\n return chunks;\n };\n}\n\nfunction renderWatchMessage(\n event: Extract<SessionWatchEvent, { type: \"message\" }>,\n sanitizer: JsonMessageSanitizer,\n formatter: OutputFormatter,\n quiet: boolean,\n): void {\n const message = sanitizer.sanitize(event.message);\n if (!isAcpJsonRpcMessage(message)) {\n throw new Error(\"Invalid sanitized session message\");\n }\n if (quiet || parsePromptStopReason(message) === undefined) {\n formatter.onAcpMessage(message);\n }\n}\n\nfunction watchLifecycleLine(event: Exclude<SessionWatchEvent, { type: \"message\" }>): string {\n if (event.type === \"turn_started\") {\n return `\\n[${event.requestId}] started cursor=${event.cursor}\\n`;\n }\n const detail =\n event.result.status === \"failed\" ? event.result.error.message : event.result.stopReason;\n return `\\n[${event.requestId}] ${event.result.status}${detail ? `: ${detail}` : \"\"} cursor=${event.cursor}\\n`;\n}\n\nexport async function runSessionWatch(\n record: SessionRecord,\n options: { cursor?: string; policy: OutputPolicy },\n): Promise<void> {\n const stopped = new AbortController();\n let outputError: Error | undefined;\n const stop = () => stopped.abort();\n const onOutputError = (error: Error) => {\n if ((error as NodeJS.ErrnoException).code !== \"EPIPE\") {\n outputError = error;\n }\n stop();\n };\n const render = watchRenderer(options.policy);\n process.on(\"SIGINT\", stop);\n process.on(\"SIGTERM\", stop);\n process.on(\"SIGHUP\", stop);\n process.stdout.on(\"error\", onOutputError);\n try {\n for await (const event of watchSession({\n record,\n cursor: options.cursor,\n signal: stopped.signal,\n })) {\n for (const chunk of render(event)) {\n if (stopped.signal.aborted) {\n break;\n }\n if (!process.stdout.write(chunk)) {\n await once(process.stdout, \"drain\", { signal: stopped.signal });\n }\n }\n }\n } catch (error) {\n if (!stopped.signal.aborted) {\n throw error;\n }\n } finally {\n process.off(\"SIGINT\", stop);\n process.off(\"SIGTERM\", stop);\n process.off(\"SIGHUP\", stop);\n process.stdout.off(\"error\", onOutputError);\n }\n if (outputError) {\n throw outputError;\n }\n}\n"],"mappings":";;;;;AAQA,SAAS,cAAc,QAA8D;CACnF,MAAM,SAAmB,CAAC;CAC1B,MAAM,SAAS,EACb,QAAQ,UAAkB;EACxB,OAAO,KAAK,KAAK;CACnB,EACF;CACA,IAAI,YAAY,IAAI,qBAAqB,OAAO,eAAe,IAAI;CACnE,IAAI,YAAY,sBAAsB,OAAO,QAAQ,EAAE,OAAO,CAAC;CAC/D,QAAQ,UAAU;EAChB,OAAO,SAAS;EAChB,IAAI,MAAM,SAAS,gBAAgB;GACjC,YAAY,IAAI,qBAAqB,OAAO,eAAe,IAAI;GAC/D,YAAY,sBAAsB,OAAO,QAAQ,EAAE,OAAO,CAAC;EAC7D;EACA,IAAI,OAAO,WAAW,QACpB,OAAO,KACL,KAAK,UACH,MAAM,SAAS,YACX;GAAE,GAAG;GAAO,SAAS,UAAU,SAAS,MAAM,OAAO;EAAE,IACvD,KACN,IAAI,IACN;OACK,IAAI,MAAM,SAAS,WACxB,mBAAmB,OAAO,WAAW,WAAW,OAAO,WAAW,OAAO;OACpE;GACL,IAAI,MAAM,SAAS,eACjB,UAAU,MAAM;GAElB,IAAI,OAAO,WAAW,SACpB,OAAO,KAAK,mBAAmB,KAAK,CAAC;EAEzC;EACA,OAAO;CACT;AACF;AAEA,SAAS,mBACP,OACA,WACA,WACA,OACM;CACN,MAAM,UAAU,UAAU,SAAS,MAAM,OAA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,IAAI,UAAU,IAAI;EAC1B,QAAQ,OAAO,IAAI,SAAS,aAAa;CAC3C;CACA,IAAI,aACF,MAAM;AAEV"}
@@ -1,5 +1,5 @@
1
- import { E as observeProcessIncarnation, J as SessionWatchError, L as readSessionRecord, Y as watchSession$1, l as readQueueOwnerRecord, tn as SessionNotFoundError } from "./ipc-CNNM5DP_.js";
2
- //#region src/session/watch.ts
1
+ import { D as observeProcessIncarnation, R as readSessionRecord, X as watchSession$1, Y as SessionWatchError, tn as SessionNotFoundError, u as readQueueOwnerRecord } from "./ipc-DfqJsbk6.js";
2
+ // src/session/watch.ts
3
3
  const OWNER_OBSERVATION_REUSE_MS = 1e3;
4
4
  function reuseObservation(cached) {
5
5
  if (!cached) return false;
@@ -79,7 +79,6 @@ function watchSession(options) {
79
79
  })[Symbol.asyncIterator]();
80
80
  } };
81
81
  }
82
- //#endregion
83
82
  export { watchSession as t };
84
83
 
85
- //# sourceMappingURL=watch-BGt4kcE6.js.map
84
+ //# sourceMappingURL=watch-CUDGkljG.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"watch-BGt4kcE6.js","names":["watchJournal"],"sources":["../src/session/watch.ts"],"sourcesContent":["import { SessionNotFoundError } from \"../errors.js\";\nimport { observeProcessIncarnation, type ProcessIncarnation } from \"../process-identity.js\";\nimport type { SessionRecord } from \"../types.js\";\nimport {\n SessionWatchError,\n watchSession as watchJournal,\n type SessionWatchEvent,\n} from \"./journal.js\";\nimport { readSessionRecord } from \"./persistence.js\";\nimport { readQueueOwnerRecord, type QueueOwnerRecord } from \"./queue/lease-store.js\";\n\nconst OWNER_OBSERVATION_REUSE_MS = 1_000;\n\ntype WatchObservation = {\n ownerKey: string | null;\n incarnation?: { state: ProcessIncarnation; checkedAt: number; decisionPending: boolean };\n missingRequest: string | null;\n};\n\nfunction reuseObservation(cached: WatchObservation[\"incarnation\"]): boolean {\n if (!cached) {\n return false;\n }\n // A query first forces a journal reread, then gets one decision pass even\n // after a slow consumer. Otherwise repeated probes can defer errors forever.\n if (cached.decisionPending) {\n cached.decisionPending = false;\n return true;\n }\n return (\n cached.state === \"gone\" || performance.now() - cached.checkedAt < OWNER_OBSERVATION_REUSE_MS\n );\n}\n\nfunction selectOwner(owner: QueueOwnerRecord | undefined, observation: WatchObservation): boolean {\n // Heartbeats and retirement receipts do not change the owner's incarnation.\n // Keep only this small key, never the potentially large descendant receipt.\n const key = owner\n ? JSON.stringify([owner.pid, owner.ownerGeneration, owner.processIdentity])\n : null;\n if (key === observation.ownerKey) {\n return false;\n }\n observation.ownerKey = key;\n observation.incarnation = undefined;\n observation.missingRequest = null;\n return true;\n}\n\nasync function runningOwner(\n recordId: string,\n observation: WatchObservation,\n): Promise<{ owner?: QueueOwnerRecord; queried: boolean }> {\n let owner = await readQueueOwnerRecord(recordId);\n selectOwner(owner, observation);\n if (!owner) {\n return { queried: false };\n }\n const cached = observation.incarnation;\n let queried = false;\n // A verified departed incarnation cannot return. Cache that fact even for\n // idle watches; other observations are bounded independently of journal polls.\n if (!reuseObservation(cached)) {\n queried = true;\n // Observation cadence must not truncate the canonical provider's query budget.\n const state = await observeProcessIncarnation(owner.pid, owner.processIdentity);\n owner = await readQueueOwnerRecord(recordId);\n if (selectOwner(owner, observation)) {\n // A replacement may have settled or recovered the journal during the\n // query. Let the reader revisit it before interpreting the old result.\n return { owner, queried };\n }\n observation.incarnation = { state, checkedAt: performance.now(), decisionPending: true };\n }\n return { owner: observation.incarnation?.state === \"gone\" ? undefined : owner, queried };\n}\n\nasync function continueWatching(\n recordId: string,\n pendingRequestId: string | null,\n observation: WatchObservation,\n): Promise<boolean> {\n const { owner, queried } = await runningOwner(recordId, observation);\n if (queried) {\n // A probe can outlast a journal update, including replacement by an older\n // owner. Revisit the journal before any unsupported/unknown/end decision.\n observation.missingRequest = owner ? null : pendingRequestId;\n return true;\n }\n if (owner) {\n if (!owner.sessionWatch) {\n throw new SessionWatchError(\n \"WATCH_OWNER_UNSUPPORTED\",\n \"This running session owner predates passive watching. Let it expire when idle or explicitly close the session before starting new work.\",\n );\n }\n observation.missingRequest = null;\n return true;\n }\n if (pendingRequestId && pendingRequestId === observation.missingRequest) {\n throw new SessionWatchError(\n \"WATCH_OUTCOME_UNKNOWN\",\n `Session owner ended without a settled result for request ${pendingRequestId}; its outcome is unknown. Resume watching from the last cursor after recovery, and do not automatically replay the prompt.`,\n );\n }\n observation.missingRequest = pendingRequestId;\n if (pendingRequestId) {\n return true;\n }\n return await isSessionOpen(recordId);\n}\n\nasync function isSessionOpen(recordId: string): Promise<boolean> {\n const record = await readSessionRecord(recordId);\n if (!record || record.acpxRecordId !== recordId) {\n throw new SessionNotFoundError(recordId);\n }\n return record.closed !== true;\n}\n\nexport function watchSession(options: {\n record: SessionRecord | Promise<SessionRecord>;\n cursor?: string;\n signal?: AbortSignal;\n}): AsyncIterable<SessionWatchEvent> {\n return {\n [Symbol.asyncIterator]() {\n const observation: WatchObservation = { ownerKey: null, missingRequest: null };\n return watchJournal({\n ...options,\n continueWatching: (record, requestId) =>\n continueWatching(record.acpxRecordId, requestId, observation),\n })[Symbol.asyncIterator]();\n },\n };\n}\n"],"mappings":";;AAWA,MAAM,6BAA6B;AAQnC,SAAS,iBAAiB,QAAkD;CAC1E,IAAI,CAAC,QACH,OAAO;CAIT,IAAI,OAAO,iBAAiB;EAC1B,OAAO,kBAAkB;EACzB,OAAO;CACT;CACA,OACE,OAAO,UAAU,UAAU,YAAY,IAAI,IAAI,OAAO,YAAY;AAEtE;AAEA,SAAS,YAAY,OAAqC,aAAwC;CAGhG,MAAM,MAAM,QACR,KAAK,UAAU;EAAC,MAAM;EAAK,MAAM;EAAiB,MAAM;CAAe,CAAC,IACxE;CACJ,IAAI,QAAQ,YAAY,UACtB,OAAO;CAET,YAAY,WAAW;CACvB,YAAY,cAAc,KAAA;CAC1B,YAAY,iBAAiB;CAC7B,OAAO;AACT;AAEA,eAAe,aACb,UACA,aACyD;CACzD,IAAI,QAAQ,MAAM,qBAAqB,QAAQ;CAC/C,YAA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G;GACH,mBAAmB,QAAQ,cACzB,iBAAiB,OAAO,cAAc,WAAW,WAAW;EAChE,CAAC,CAAC,CAAC,OAAO,cAAc,CAAC;CAC3B,EACF;AACF"}
1
+ {"version":3,"file":"watch-CUDGkljG.js","names":["watchJournal"],"sources":["../src/session/watch.ts"],"sourcesContent":["import { SessionNotFoundError } from \"../errors.js\";\nimport { observeProcessIncarnation, type ProcessIncarnation } from \"../process-identity.js\";\nimport type { SessionRecord } from \"../types.js\";\nimport {\n SessionWatchError,\n watchSession as watchJournal,\n type SessionWatchEvent,\n} from \"./journal.js\";\nimport { readSessionRecord } from \"./persistence.js\";\nimport { readQueueOwnerRecord, type QueueOwnerRecord } from \"./queue/lease-store.js\";\n\nconst OWNER_OBSERVATION_REUSE_MS = 1_000;\n\ntype WatchObservation = {\n ownerKey: string | null;\n incarnation?: { state: ProcessIncarnation; checkedAt: number; decisionPending: boolean };\n missingRequest: string | null;\n};\n\nfunction reuseObservation(cached: WatchObservation[\"incarnation\"]): boolean {\n if (!cached) {\n return false;\n }\n // A query first forces a journal reread, then gets one decision pass even\n // after a slow consumer. Otherwise repeated probes can defer errors forever.\n if (cached.decisionPending) {\n cached.decisionPending = false;\n return true;\n }\n return (\n cached.state === \"gone\" || performance.now() - cached.checkedAt < OWNER_OBSERVATION_REUSE_MS\n );\n}\n\nfunction selectOwner(owner: QueueOwnerRecord | undefined, observation: WatchObservation): boolean {\n // Heartbeats and retirement receipts do not change the owner's incarnation.\n // Keep only this small key, never the potentially large descendant receipt.\n const key = owner\n ? JSON.stringify([owner.pid, owner.ownerGeneration, owner.processIdentity])\n : null;\n if (key === observation.ownerKey) {\n return false;\n }\n observation.ownerKey = key;\n observation.incarnation = undefined;\n observation.missingRequest = null;\n return true;\n}\n\nasync function runningOwner(\n recordId: string,\n observation: WatchObservation,\n): Promise<{ owner?: QueueOwnerRecord; queried: boolean }> {\n let owner = await readQueueOwnerRecord(recordId);\n selectOwner(owner, observation);\n if (!owner) {\n return { queried: false };\n }\n const cached = observation.incarnation;\n let queried = false;\n // A verified departed incarnation cannot return. Cache that fact even for\n // idle watches; other observations are bounded independently of journal polls.\n if (!reuseObservation(cached)) {\n queried = true;\n // Observation cadence must not truncate the canonical provider's query budget.\n const state = await observeProcessIncarnation(owner.pid, owner.processIdentity);\n owner = await readQueueOwnerRecord(recordId);\n if (selectOwner(owner, observation)) {\n // A replacement may have settled or recovered the journal during the\n // query. Let the reader revisit it before interpreting the old result.\n return { owner, queried };\n }\n observation.incarnation = { state, checkedAt: performance.now(), decisionPending: true };\n }\n return { owner: observation.incarnation?.state === \"gone\" ? undefined : owner, queried };\n}\n\nasync function continueWatching(\n recordId: string,\n pendingRequestId: string | null,\n observation: WatchObservation,\n): Promise<boolean> {\n const { owner, queried } = await runningOwner(recordId, observation);\n if (queried) {\n // A probe can outlast a journal update, including replacement by an older\n // owner. Revisit the journal before any unsupported/unknown/end decision.\n observation.missingRequest = owner ? null : pendingRequestId;\n return true;\n }\n if (owner) {\n if (!owner.sessionWatch) {\n throw new SessionWatchError(\n \"WATCH_OWNER_UNSUPPORTED\",\n \"This running session owner predates passive watching. Let it expire when idle or explicitly close the session before starting new work.\",\n );\n }\n observation.missingRequest = null;\n return true;\n }\n if (pendingRequestId && pendingRequestId === observation.missingRequest) {\n throw new SessionWatchError(\n \"WATCH_OUTCOME_UNKNOWN\",\n `Session owner ended without a settled result for request ${pendingRequestId}; its outcome is unknown. Resume watching from the last cursor after recovery, and do not automatically replay the prompt.`,\n );\n }\n observation.missingRequest = pendingRequestId;\n if (pendingRequestId) {\n return true;\n }\n return await isSessionOpen(recordId);\n}\n\nasync function isSessionOpen(recordId: string): Promise<boolean> {\n const record = await readSessionRecord(recordId);\n if (!record || record.acpxRecordId !== recordId) {\n throw new SessionNotFoundError(recordId);\n }\n return record.closed !== true;\n}\n\nexport function watchSession(options: {\n record: SessionRecord | Promise<SessionRecord>;\n cursor?: string;\n signal?: AbortSignal;\n}): AsyncIterable<SessionWatchEvent> {\n return {\n [Symbol.asyncIterator]() {\n const observation: WatchObservation = { ownerKey: null, missingRequest: null };\n return watchJournal({\n ...options,\n continueWatching: (record, requestId) =>\n continueWatching(record.acpxRecordId, requestId, observation),\n })[Symbol.asyncIterator]();\n },\n };\n}\n"],"mappings":";;AAWA,MAAM,6BAA6B;AAQnC,SAAS,iBAAiB,QAAkD;CAC1E,IAAI,CAAC,QACH,OAAO;CAIT,IAAI,OAAO,iBAAiB;EAC1B,OAAO,kBAAkB;EACzB,OAAO;CACT;CACA,OACE,OAAO,UAAU,UAAU,YAAY,IAAI,IAAI,OAAO,YAAY;AAEtE;AAEA,SAAS,YAAY,OAAqC,aAAwC;CAGhG,MAAM,MAAM,QACR,KAAK,UAAU;EAAC,MAAM;EAAK,MAAM;EAAiB,MAAM;CAAe,CAAC,IACxE;CACJ,IAAI,QAAQ,YAAY,UACtB,OAAO;CAET,YAAY,WAAW;CACvB,YAAY,cAAc,KAAA;CAC1B,YAAY,iBAAiB;CAC7B,OAAO;AACT;AAEA,eAAe,aACb,UACA,aACyD;CACzD,IAAI,QAAQ,MAAM,qBAAqB,QAAQ;CAC/C,YAAY,OAAO,WAAW;CAC9B,IAAI,CAAC,OACH,OAAO,EAAE,SAAS,MAAM;CAE1B,MAAM,SAAS,YAAY;CAC3B,IAAI,UAAU;CAGd,IAAI,CAAC,iBAAiB,MAAM,GAAG;EAC7B,UAAU;EAEV,MAAM,QAAQ,MAAM,0BAA0B,MAAM,KAAK,MAAM,eAAe;EAC9E,QAAQ,MAAM,qBAAqB,QAAQ;EAC3C,IAAI,YAAY,OAAO,WAAW,GAGhC,OAAO;GAAE;GAAO;EAAQ;EAE1B,YAAY,cAAc;GAAE;GAAO,WAAW,YAAY,IAAI;GAAG,iBAAiB;EAAK;CACzF;CACA,OAAO;EAAE,OAAO,YAAY,aAAa,UAAU,SAAS,KAAA,IAAY;EAAO;CAAQ;AACzF;AAEA,eAAe,iBACb,UACA,kBACA,aACkB;CAClB,MAAM,EAAE,OAAO,YAAY,MAAM,aAAa,UAAU,WAAW;CACnE,IAAI,SAAS;EAGX,YAAY,iBAAiB,QAAQ,OAAO;EAC5C,OAAO;CACT;CACA,IAAI,OAAO;EACT,IAAI,CAAC,MAAM,cACT,MAAM,IAAI,kBACR,2BACA,yIACF;EAEF,YAAY,iBAAiB;EAC7B,OAAO;CACT;CACA,IAAI,oBAAoB,qBAAqB,YAAY,gBACvD,MAAM,IAAI,kBACR,yBACA,4DAA4D,iBAAiB,2HAC/E;CAEF,YAAY,iBAAiB;CAC7B,IAAI,kBACF,OAAO;CAET,OAAO,MAAM,cAAc,QAAQ;AACrC;AAEA,eAAe,cAAc,UAAoC;CAC/D,MAAM,SAAS,MAAM,kBAAkB,QAAQ;CAC/C,IAAI,CAAC,UAAU,OAAO,iBAAiB,UACrC,MAAM,IAAI,qBAAqB,QAAQ;CAEzC,OAAO,OAAO,WAAW;AAC3B;AAEA,SAAgB,aAAa,SAIQ;CACnC,OAAO,EACL,CAAC,OAAO,iBAAiB;EACvB,MAAM,cAAgC;GAAE,UAAU;GAAM,gBAAgB;EAAK;EAC7E,OAAOA,eAAa;GAClB,GAAG;GACH,mBAAmB,QAAQ,cACzB,iBAAiB,OAAO,cAAc,WAAW,WAAW;EAChE,CAAC,CAAC,CAAC,OAAO,cAAc,CAAC;CAC3B,EACF;AACF"}
@@ -34,12 +34,12 @@
34
34
  "./agent-registry": "./dist/agent-registry.js"
35
35
  },
36
36
  "dependencies": {
37
- "@1agents/acp-runtime-sdk": "npm:@agentclientprotocol/sdk@^1.5.0",
38
- "@openclaw/fs-safe": "^0.26.7",
37
+ "@1agents/acp-runtime-sdk": "npm:@agentclientprotocol/sdk@^1.9.0",
38
+ "@openclaw/fs-safe": "^0.28.0",
39
39
  "commander": "^15.0.0",
40
40
  "skillflag": "^0.2.1",
41
41
  "tsx": "^4.23.15",
42
- "zod": "^4.6.5"
42
+ "zod": "^4.6.7"
43
43
  },
44
44
  "engines": {
45
45
  "node": ">=22.13.0"
@@ -89,33 +89,36 @@ The `@1agents/acp-service` host prefers adapter packages in its search roots, th
89
89
 
90
90
  Friendly agent names resolve to commands:
91
91
 
92
- - `pi` -> `npx pi-acp` (ACPX-owned package range; see `agents/Pi.md`)
92
+ - `pi` -> `npx --package=pi-acp -- pi-acp` (ACPX-owned package range; see `agents/Pi.md`)
93
93
  - `openclaw` -> `openclaw acp` (see the [OpenClaw guide](https://github.com/openclaw/acpx/blob/main/agents/OpenClaw.md))
94
- - `codex` -> `npx -y @agentclientprotocol/codex-acp` (ACPX-owned package range)
95
- - `claude` -> `npx -y @agentclientprotocol/claude-agent-acp` (ACPX-owned package range; see `agents/Claude.md`)
94
+ - `codex` -> `npx -y --package=@agentclientprotocol/codex-acp -- codex-acp` (ACPX-owned package range)
95
+ - `claude` -> `npx -y --package=@agentclientprotocol/claude-agent-acp -- claude-agent-acp` (ACPX-owned package range; see `agents/Claude.md`)
96
96
  - `gemini` -> `gemini --acp`
97
97
  - `cursor` -> `cursor-agent acp` (calls `authenticate` with `cursor_login` before creating a session; sign in with `agent login` first. See `agents/Cursor.md`)
98
98
  - `copilot` -> `copilot --acp --stdio`
99
+ - `ante` -> `ante acp` (experimental). Requires Ante 0.2.1 or newer and a separately installed `ante-acp` on `PATH`. Prefer `exec` for fresh work; context is limited to the live ACP connection, with no reopening after disconnect. AskUser is excluded, and client-supplied MCP servers and extra directories are ignored. See [Ante](https://github.com/openclaw/acpx/blob/main/agents/Ante.md).
99
100
  - `antigravity` -> `agy_acp_server.par` (`--uid=` on Linux; `agy_acp_server.exe` on Windows). Install the official runtime/helper pair and configure its own sign-in first; see [Antigravity](https://github.com/openclaw/acpx/blob/main/agents/Antigravity.md). Fixed-choice interaction questions are cancelled, including with `--approve-all`, host permission callbacks, and existing custom launchers; acpx cannot supply user answers through permission approval.
100
101
  - `codebuddy` -> `codebuddy --acp` (install `@tencent-ai/codebuddy-code` and sign in with the CodeBuddy CLI first; acpx does not run its login. See `agents/CodeBuddy.md`)
102
+ - `deepseek-harness` -> `dsh --profile acp` (DeepSeek Harness, separate from DeepSeek models; configure the provider in dsh first. Uses advertised `session/resume` without transcript replay, not `session/load`; see the [DeepSeek Harness guide](https://github.com/openclaw/acpx/blob/main/agents/DeepSeekHarness.md))
101
103
  - `devin` -> `devin acp`
102
104
  - `droid` -> `droid exec --output-format acp` (`factory-droid` and `factorydroid` also resolve to `droid`)
103
- - `fast-agent` -> `uvx fast-agent-mcp acp`
105
+ - `fast-agent` -> `uvx fast-agent-mcp acp` (operator-owned Python/tool environment; see [Fast Agent](https://github.com/openclaw/acpx/blob/main/agents/FastAgent.md) for patched-runtime selection and isolated recovery)
104
106
  - `fx` -> `fx acp` (install and authenticate a provider first; see the [fx guide](https://github.com/openclaw/acpx/blob/main/agents/Fx.md))
105
- - `grok-build` -> `grok agent stdio`
107
+ - `grok-build` -> `grok agent stdio` (Grok Build CLI, distinct from Grok Bot cloud routines and their webhook triggers; see the [Grok Build guide](https://github.com/openclaw/acpx/blob/main/agents/GrokBuild.md)).
108
+ - `goose` -> `goose acp` (install Goose and configure its provider first; see the [Goose guide](https://github.com/openclaw/acpx/blob/main/agents/Goose.md))
106
109
  - `iflow` -> `iflow --experimental-acp`
107
110
  - `junie` -> `junie --acp=true` (install and authenticate Junie first; see the [Junie guide](https://github.com/openclaw/acpx/blob/main/agents/Junie.md))
108
- - `kilocode` -> `npx -y @kilocode/cli acp`
111
+ - `kilocode` -> `npx -y --package=@kilocode/cli -- kilo acp`
109
112
  - `kimi` -> `kimi acp`
110
113
  - `kiro` -> `kiro-cli-chat acp`
111
114
  - `mcode` -> `mcode acp` (install/authenticate MCode first; prefer `exec` for one-shot work, and require advertised ACP reload support for cross-invocation continuity)
112
- - `mux` -> `mux acp` via an ACPX-owned npm range
115
+ - `mux` -> `npx -y --package=mux -- mux acp` via an ACPX-owned npm range
113
116
  - `octomind` -> `octomind acp developer:general` (install Octomind and sign in with `octomind login` or provider keys first; see the [Octomind guide](https://github.com/openclaw/acpx/blob/main/agents/Octomind.md))
114
- - `opencode` -> `npx -y opencode-ai acp`
117
+ - `opencode` -> `npx -y --package=opencode-ai -- opencode acp`
115
118
  - `pool` -> `pool acp`
116
119
  - `qoder` -> `qodercli --acp`
117
- Forwards Qoder-native `--allowed-tools` and `--max-turns` startup flags from `acpx` session options.
118
- - `qwen` -> `qwen --acp`
120
+ Forwards Qoder-native `--allowed-tools` and `--max-turns` startup flags from `acpx` session options. Custom `qoder --acp` launchers receive the same startup and shutdown handling.
121
+ - `qwen` -> `qwen --acp` (Qwen Code, distinct from QwenWork; see the [Qwen Code guide](https://github.com/openclaw/acpx/blob/main/agents/Qwen.md) for text filesystem delegation and native file discovery)
119
122
  - `trae` -> `traecli acp serve`
120
123
  - `zeroclaw` -> `zeroclaw acp`
121
124
 
@@ -124,6 +127,7 @@ Rules:
124
127
  - Default agent is `codex` for top-level `prompt`, `exec`, and `sessions`.
125
128
  - Unknown positional agent tokens are treated as raw agent commands.
126
129
  - `--agent <command>` explicitly sets a raw ACP adapter command.
130
+ - Claude package fallback uses the ACPX-owned adapter range. An adapter installed alongside ACPX takes precedence; update it and any explicitly selected native Claude executable separately. Existing custom launchers stay operator-controlled.
127
131
  - Do not combine a positional agent and `--agent` in the same command.
128
132
  - Gemini version checks, Copilot ACP support checks, and their startup diagnostics use the selected agent's working directory and child environment, including session environment and embedded runtime overrides.
129
133
  - Embedded host lifecycle admission also covers compatibility and diagnostic invocations. Correlate their events by `launchId`; one session can produce several adapter processes. Checks retire their owned processes and output pipes before settling.
@@ -408,7 +412,32 @@ Use `acpx config show` to inspect the resolved config and `acpx config init` to
408
412
  For ACP `authenticate` handshakes, use either config `auth` entries or explicit
409
413
  `ACPX_AUTH_<METHOD_ID>` environment variables such as `ACPX_AUTH_OPENAI_API_KEY`.
410
414
  Ambient provider env vars such as `OPENAI_API_KEY` are still passed through to
411
- child agents, but they do not trigger ACP auth-method selection on their own.
415
+ child agents by default, but they do not trigger ACP auth-method selection on
416
+ their own.
417
+
418
+ ## Embedded environment inheritance
419
+
420
+ Embedding hosts can set `agentProcessEnvAllow` or `agentProcessEnvBlock` on
421
+ `createAcpRuntime()` to keep parent variables, such as the host's own service
422
+ credentials, out of agents, command probes, and ACP terminals. Both are off by
423
+ default and the CLI does not set them, so without them children inherit the
424
+ whole environment as before.
425
+
426
+ - `agentProcessEnvAllow` keeps only process essentials (`PATH`, `HOME`, locale,
427
+ temp and similar names) plus the listed names. An empty list keeps only the
428
+ essentials and explicit grants.
429
+ - `agentProcessEnvBlock` removes the listed names, applied after the allowlist.
430
+ - Explicit grants still apply: `ACPX_AUTH_<METHOD_ID>` variables pass through
431
+ both lists, and `agentProcessEnv`, saved session `env`, and a terminal
432
+ request's own `env` are layered on top.
433
+
434
+ A filtered provider key does not reach the agent. Agent-specific environment
435
+ authentication that ACPX selects itself, such as Grok Build's `XAI_API_KEY` for
436
+ `xai.api_key`, is skipped as well when the key is filtered. Keep such a key by
437
+ listing it in the allowlist and leaving it off the blocklist, or pass it as an
438
+ `ACPX_AUTH_*` grant (for Grok Build, `ACPX_AUTH_XAI_API_KEY`). See
439
+ [`docs/runtime-environment.md`](https://github.com/openclaw/acpx/blob/main/docs/runtime-environment.md)
440
+ and [`agents/GrokBuild.md`](https://github.com/openclaw/acpx/blob/main/agents/GrokBuild.md).
412
441
 
413
442
  ## Devin ACP compatibility
414
443
 
@@ -528,6 +557,8 @@ Run artifacts persist under `~/.acpx/flows/runs/<runId>/`. Default per-step time
528
557
 
529
558
  Each attempt has one deadline across preparation, execution, and parsing. Callbacks receive `context.signal`; function actions also receive `context.runShell` to run commands whose processes and output streams the runner owns. A command's own timeout returns partial output with `timedOut: true`; enclosing node cancellation rejects after cleanup and prevents later managed commands. Admitted runtime writes finish before routing or final publication. Check the signal around custom asynchronous side effects: arbitrary JavaScript cannot be forcibly stopped, and completed effects are not rolled back. Persistent reconnects must load the same backend session or fail. See `docs/flows.md` for the command result and cancellation contracts.
530
559
 
560
+ ACP nodes accept `modelId` and ordered `configOptions: [{ configId, value }]` before the first prompt. Global `--model` and repeatable `flow run --config-option key=value` provide defaults; node modelId wins and node config options execute last. Legacy node `model` metadata remains inert. Persistent handles pin their first settings, inherit omitted fields, and reject conflicting explicit settings. Use separate handles for different selections. Inspect bundle `requestedSettings` / `acceptedSettings` and adapter response receipts; `model.applied: false` means no model catalog was available. Option `reported: false` marks an acknowledged request whose accepted value was not supplied by the adapter catalog. Persistent creation controls are recorded in binding and step settings evidence, not in `events.ndjson`.
561
+
531
562
  ### Authoring a flow
532
563
 
533
564
  The authoring surface lives in `acpx/flows`. The minimal example:
@@ -1,103 +0,0 @@
1
- /**
2
- * Optional automatic archiving of silent DSH sessions.
3
- *
4
- * DSH already owns the durable archive set through `ctx.workspaceRegistry`:
5
- * archiving a session hides it from the workspace grouping, clears its pin and
6
- * gates every model step for it and its subagent descendants. This module only
7
- * decides *when* to call that API. It never deletes sessions or changes their
8
- * history, and it never archives a session that DSH currently reports as
9
- * pinned, so a pinned session is always archived manually by the user.
10
- */
11
- export interface AutoArchiveConfig {
12
- /** Whether the periodic sweep runs. Off by default. */
13
- enabled: boolean;
14
- /** Archive sessions silent for at least this many milliseconds. */
15
- inactivityMs: number;
16
- /** Milliseconds between two sweeps. */
17
- scanIntervalMs: number;
18
- /** Milliseconds to wait after startup before the first sweep. */
19
- initialDelayMs: number;
20
- }
21
- /** Default policy: idle for seven days, check once a day, first check a minute after startup. */
22
- export declare const DEFAULT_AUTO_ARCHIVE: AutoArchiveConfig;
23
- /** Normalize user config while preserving the shipped defaults for absent fields. */
24
- export declare function resolveAutoArchiveConfig(input: Partial<AutoArchiveConfig> | undefined): AutoArchiveConfig;
25
- /** A candidate produced by one sweep. `lastActiveAt` is epoch milliseconds. */
26
- export interface ArchiveCandidate {
27
- readonly sessionId: string;
28
- readonly lastActiveAt: number;
29
- }
30
- /** The small surface of DSH services the sweep needs. Injected for testability. */
31
- export interface AutoArchiveHost {
32
- /** Session summary items with `updatedAt`, from `sessionController.list({}, signal).items`. */
33
- listSummaries(signal?: AbortSignal): Promise<readonly {
34
- sessionId: string;
35
- updatedAt: number;
36
- }[]>;
37
- /** Lightweight stored-session snapshots, as returned by `sessionPersistence.list()`. */
38
- listStored(): Promise<readonly {
39
- header: {
40
- id: string;
41
- createdAt: number;
42
- };
43
- location?: {
44
- path: string;
45
- };
46
- }[]>;
47
- /** Session ids the user pinned; these are never auto-archived. */
48
- pinnedSessionIds(): readonly string[];
49
- /** Session ids already archived; these need no further work. */
50
- archivedSessionIds(): readonly string[];
51
- /** Whether a session is currently attached and running work in DSH. */
52
- isActive?(sessionId: string): boolean;
53
- /** Perform the durable archive. */
54
- archive(sessionId: string): Promise<void>;
55
- /** Logger-compatible sink. */
56
- log?(message: string): void;
57
- }
58
- /**
59
- * Build the list of sessions that have been silent long enough to archive.
60
- *
61
- * Last activity is the later of DSH's own recency (`updatedAt`, which is the
62
- * session creation time or its last real user message) and the modification
63
- * time of the durable session file. This matches both interpretations of
64
- * "last activity" — the last message block and the backing file's mtime — and
65
- * treats a session with a newer file as active. Pinned and already-archived
66
- * sessions are excluded; pinned sessions stay a manual archive decision.
67
- *
68
- * @param host - minimal DSH service surface.
69
- * @param now - current epoch milliseconds.
70
- * @param inactivityMs - silence threshold in milliseconds.
71
- * @returns sessions to archive, newest activity first.
72
- */
73
- export declare function findSilentSessions(host: AutoArchiveHost, now: number, inactivityMs: number): Promise<ArchiveCandidate[]>;
74
- /** Run one sweep: find silent sessions and archive them one by one. */
75
- export declare function sweepAutoArchive(host: AutoArchiveHost, now: number, inactivityMs: number): Promise<{
76
- candidates: number;
77
- archived: string[];
78
- failed: string[];
79
- }>;
80
- /** Context surface needed for timer installation. */
81
- export interface TimerContext {
82
- interval?: (callback: () => void, delay: number) => () => void;
83
- timeout?: (callback: () => void, delay: number) => () => void;
84
- effect?: (callback: any) => any;
85
- logger?: {
86
- warn?: (...args: unknown[]) => void;
87
- };
88
- }
89
- /**
90
- * Install the periodic sweep on a Cordis context.
91
- *
92
- * Uses the host's disposal-aware `ctx.interval()` when the timer plugin is
93
- * composed and falls back to a plain interval otherwise; either way the timer
94
- * is cleared when the owning plugin fiber is disposed. The first sweep is
95
- * delayed so a freshly started DSH does not archive sessions before its
96
- * workspace registry and persistence listings have settled.
97
- *
98
- * @param ctx - plugin context.
99
- * @param config - normalized auto-archive config.
100
- * @param run - one sweep; called with no arguments.
101
- * @returns a disposer for the installed timer(s).
102
- */
103
- export declare function installAutoArchiveTimer(ctx: TimerContext, config: AutoArchiveConfig, run: () => void): () => void;
@@ -1,175 +0,0 @@
1
- /**
2
- * Optional automatic archiving of silent DSH sessions.
3
- *
4
- * DSH already owns the durable archive set through `ctx.workspaceRegistry`:
5
- * archiving a session hides it from the workspace grouping, clears its pin and
6
- * gates every model step for it and its subagent descendants. This module only
7
- * decides *when* to call that API. It never deletes sessions or changes their
8
- * history, and it never archives a session that DSH currently reports as
9
- * pinned, so a pinned session is always archived manually by the user.
10
- */
11
- import { stat } from 'node:fs/promises';
12
- /** One day in milliseconds. */
13
- const DAY_MS = 24 * 60 * 60 * 1000;
14
- /** Default policy: idle for seven days, check once a day, first check a minute after startup. */
15
- export const DEFAULT_AUTO_ARCHIVE = Object.freeze({
16
- enabled: false,
17
- inactivityMs: 7 * DAY_MS,
18
- scanIntervalMs: DAY_MS,
19
- initialDelayMs: 60 * 1000,
20
- });
21
- /** Normalize user config while preserving the shipped defaults for absent fields. */
22
- export function resolveAutoArchiveConfig(input) {
23
- if (input === undefined || input === null || typeof input !== 'object')
24
- return { ...DEFAULT_AUTO_ARCHIVE };
25
- const result = { ...DEFAULT_AUTO_ARCHIVE };
26
- if ('enabled' in input) {
27
- if (typeof input.enabled !== 'boolean')
28
- throw new Error('autoArchive.enabled must be a boolean');
29
- result.enabled = input.enabled;
30
- }
31
- for (const key of ['inactivityMs', 'scanIntervalMs', 'initialDelayMs']) {
32
- if (!(key in input))
33
- continue;
34
- const value = input[key];
35
- if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
36
- throw new Error(`autoArchive.${key} must be a positive integer`);
37
- }
38
- result[key] = value;
39
- }
40
- return result;
41
- }
42
- /**
43
- * Build the list of sessions that have been silent long enough to archive.
44
- *
45
- * Last activity is the later of DSH's own recency (`updatedAt`, which is the
46
- * session creation time or its last real user message) and the modification
47
- * time of the durable session file. This matches both interpretations of
48
- * "last activity" — the last message block and the backing file's mtime — and
49
- * treats a session with a newer file as active. Pinned and already-archived
50
- * sessions are excluded; pinned sessions stay a manual archive decision.
51
- *
52
- * @param host - minimal DSH service surface.
53
- * @param now - current epoch milliseconds.
54
- * @param inactivityMs - silence threshold in milliseconds.
55
- * @returns sessions to archive, newest activity first.
56
- */
57
- export async function findSilentSessions(host, now, inactivityMs) {
58
- if (!Number.isSafeInteger(now) || now < 0)
59
- throw new Error('now must be a non-negative safe integer');
60
- if (!Number.isSafeInteger(inactivityMs) || inactivityMs < 1)
61
- throw new Error('inactivityMs must be a positive integer');
62
- const pinned = new Set(host.pinnedSessionIds());
63
- const archived = new Set(host.archivedSessionIds());
64
- const cutoff = now - inactivityMs;
65
- const byId = new Map();
66
- // Collect every observed activity time before applying the threshold: a
67
- // durable file written after the last user message must be able to lift a
68
- // session from the candidate set even if its summary was read first.
69
- const record = (sessionId, lastActiveAt) => {
70
- if (pinned.has(sessionId) || archived.has(sessionId))
71
- return;
72
- if (!Number.isFinite(lastActiveAt) || lastActiveAt < 0)
73
- return;
74
- byId.set(sessionId, Math.max(byId.get(sessionId) ?? 0, lastActiveAt));
75
- };
76
- for (const summary of await host.listSummaries())
77
- record(summary.sessionId, summary.updatedAt);
78
- // A durable file written after the last user message (a tool result, a
79
- // title/compaction update, an imported history) still counts as activity.
80
- await Promise.all((await host.listStored()).map(async (snapshot) => {
81
- const { id, createdAt } = snapshot.header;
82
- let lastActiveAt = createdAt;
83
- const path = snapshot.location?.path;
84
- if (path !== undefined) {
85
- try {
86
- lastActiveAt = Math.max(lastActiveAt, (await stat(path)).mtimeMs);
87
- }
88
- catch (error) {
89
- // A missing or unreadable artifact must not make the session look
90
- // newer than the header alone says; keep the header timestamp.
91
- host.log?.(`auto-archive: cannot stat ${path}: ${String(error)}`);
92
- }
93
- }
94
- record(id, lastActiveAt);
95
- }));
96
- return [...byId.entries()]
97
- .filter(([, lastActiveAt]) => lastActiveAt < cutoff)
98
- .map(([sessionId, lastActiveAt]) => ({ sessionId, lastActiveAt }))
99
- .sort((a, b) => b.lastActiveAt - a.lastActiveAt);
100
- }
101
- /** Run one sweep: find silent sessions and archive them one by one. */
102
- export async function sweepAutoArchive(host, now, inactivityMs) {
103
- const candidates = await findSilentSessions(host, now, inactivityMs);
104
- const archived = [];
105
- const failed = [];
106
- for (const { sessionId } of candidates) {
107
- // A live session whose turn started after the scan began has become
108
- // active again; leave it to the next sweep instead of stopping its work.
109
- if (host.isActive?.(sessionId))
110
- continue;
111
- try {
112
- await host.archive(sessionId);
113
- archived.push(sessionId);
114
- }
115
- catch (error) {
116
- failed.push(sessionId);
117
- host.log?.(`auto-archive: failed to archive ${sessionId}: ${String(error)}`);
118
- }
119
- }
120
- return { candidates: candidates.length, archived, failed };
121
- }
122
- /**
123
- * Install the periodic sweep on a Cordis context.
124
- *
125
- * Uses the host's disposal-aware `ctx.interval()` when the timer plugin is
126
- * composed and falls back to a plain interval otherwise; either way the timer
127
- * is cleared when the owning plugin fiber is disposed. The first sweep is
128
- * delayed so a freshly started DSH does not archive sessions before its
129
- * workspace registry and persistence listings have settled.
130
- *
131
- * @param ctx - plugin context.
132
- * @param config - normalized auto-archive config.
133
- * @param run - one sweep; called with no arguments.
134
- * @returns a disposer for the installed timer(s).
135
- */
136
- export function installAutoArchiveTimer(ctx, config, run) {
137
- const disposers = [];
138
- const own = (dispose) => { disposers.push(dispose); };
139
- const disposeAll = () => {
140
- for (const dispose of disposers.splice(0)) {
141
- try {
142
- dispose();
143
- }
144
- catch (error) {
145
- ctx.logger?.warn?.('auto-archive: timer disposal failed: %s', error);
146
- }
147
- }
148
- };
149
- if (!config.enabled)
150
- return disposeAll;
151
- let intervalDispose;
152
- const startInterval = () => {
153
- if (typeof ctx.interval === 'function') {
154
- intervalDispose = ctx.interval(() => { void run(); }, config.scanIntervalMs);
155
- }
156
- else {
157
- const timer = setInterval(() => { void run(); }, config.scanIntervalMs);
158
- // Node's timer object is disposable through its own clear method.
159
- intervalDispose = () => clearInterval(timer);
160
- }
161
- own(intervalDispose);
162
- };
163
- if (typeof ctx.timeout === 'function') {
164
- own(ctx.timeout(() => { startInterval(); void run(); }, config.initialDelayMs));
165
- }
166
- else {
167
- const startTimer = setTimeout(() => { startInterval(); void run(); }, config.initialDelayMs);
168
- own(() => clearTimeout(startTimer));
169
- }
170
- // Cordis invokes an effect body immediately and treats its *return value* as
171
- // the cleanup. Returning `() => disposeAll` (not `disposeAll` itself) keeps
172
- // the timers alive until the owning fiber is actually disposed.
173
- ctx.effect?.(() => () => disposeAll);
174
- return disposeAll;
175
- }