@bastani/atomic 0.9.76-alpha.1 → 0.9.77-alpha.1

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 (183) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +13 -0
  3. package/dist/builtin/intercom/broker/broker.ts +153 -6
  4. package/dist/builtin/intercom/broker/client.ts +85 -3
  5. package/dist/builtin/intercom/broker/departed-children.ts +471 -0
  6. package/dist/builtin/intercom/broker/recipient-gone-errors.ts +280 -0
  7. package/dist/builtin/intercom/broker/restoring-recipients.ts +108 -7
  8. package/dist/builtin/intercom/broker/send-handler.ts +42 -0
  9. package/dist/builtin/intercom/broker/workflow-stage-aliases.ts +69 -0
  10. package/dist/builtin/intercom/index.bundle.mjs +374 -129
  11. package/dist/builtin/intercom/package.json +2 -2
  12. package/dist/builtin/intercom/types.ts +30 -1
  13. package/dist/builtin/mcp/package.json +1 -1
  14. package/dist/builtin/subagents/CHANGELOG.md +15 -0
  15. package/dist/builtin/subagents/README.md +1 -1
  16. package/dist/builtin/subagents/package.json +3 -3
  17. package/dist/builtin/subagents/skills/agent-browser/SKILL.md +1 -1
  18. package/dist/builtin/subagents/src/extension/index.bundle.mjs +64 -4
  19. package/dist/builtin/web-access/package.json +2 -2
  20. package/dist/builtin/workflows/CHANGELOG.md +14 -0
  21. package/dist/builtin/workflows/README.md +1 -1
  22. package/dist/builtin/workflows/package.json +2 -2
  23. package/dist/builtin/workflows/skills/impeccable/SKILL.md +3 -3
  24. package/dist/builtin/workflows/skills/impeccable/scripts/VERSION +1 -1
  25. package/dist/builtin/workflows/skills/impeccable/scripts/engine-checksums.txt +5 -5
  26. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +71 -56
  27. package/dist/builtin/workflows/src/extension/index.bundle.mjs +315 -112
  28. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +168 -9
  29. package/dist/builtin/workflows/src/index.js +168 -9
  30. package/dist/builtin/workflows/src/local-worker-entry.mjs +168 -9
  31. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  32. package/dist/core/agent-session-compaction.js +2 -1
  33. package/dist/core/agent-session-compaction.js.map +1 -1
  34. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  35. package/dist/core/agent-session-extension-bindings.js +2 -0
  36. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  37. package/dist/core/agent-session-methods.d.ts +1 -0
  38. package/dist/core/agent-session-methods.d.ts.map +1 -1
  39. package/dist/core/agent-session-methods.js.map +1 -1
  40. package/dist/core/agent-session-state.d.ts.map +1 -1
  41. package/dist/core/agent-session-state.js +7 -2
  42. package/dist/core/agent-session-state.js.map +1 -1
  43. package/dist/core/agent-session-tasks.d.ts +6 -0
  44. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  45. package/dist/core/agent-session-tasks.js +13 -25
  46. package/dist/core/agent-session-tasks.js.map +1 -1
  47. package/dist/core/agent-session-types.d.ts +2 -0
  48. package/dist/core/agent-session-types.d.ts.map +1 -1
  49. package/dist/core/agent-session-types.js.map +1 -1
  50. package/dist/core/agent-session.d.ts +1 -0
  51. package/dist/core/agent-session.d.ts.map +1 -1
  52. package/dist/core/agent-session.js +2 -0
  53. package/dist/core/agent-session.js.map +1 -1
  54. package/dist/core/extensions/loader-rollback.d.ts.map +1 -1
  55. package/dist/core/extensions/loader-rollback.js +1 -0
  56. package/dist/core/extensions/loader-rollback.js.map +1 -1
  57. package/dist/core/extensions/runner-context.d.ts +3 -3
  58. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  59. package/dist/core/extensions/runner-context.js +2 -1
  60. package/dist/core/extensions/runner-context.js.map +1 -1
  61. package/dist/core/extensions/runner.d.ts +9 -0
  62. package/dist/core/extensions/runner.d.ts.map +1 -1
  63. package/dist/core/extensions/runner.js +16 -1
  64. package/dist/core/extensions/runner.js.map +1 -1
  65. package/dist/core/sdk-types.d.ts +5 -0
  66. package/dist/core/sdk-types.d.ts.map +1 -1
  67. package/dist/core/sdk-types.js.map +1 -1
  68. package/dist/core/sdk.d.ts.map +1 -1
  69. package/dist/core/sdk.js +8 -1
  70. package/dist/core/sdk.js.map +1 -1
  71. package/dist/core/system-prompt.d.ts +6 -0
  72. package/dist/core/system-prompt.d.ts.map +1 -1
  73. package/dist/core/system-prompt.js +26 -18
  74. package/dist/core/system-prompt.js.map +1 -1
  75. package/dist/core/tasks/agent-adapter.js +2 -2
  76. package/dist/core/tasks/agent-adapter.js.map +1 -1
  77. package/dist/core/tasks/cancel-reason.d.ts +20 -0
  78. package/dist/core/tasks/cancel-reason.d.ts.map +1 -0
  79. package/dist/core/tasks/cancel-reason.js +47 -0
  80. package/dist/core/tasks/cancel-reason.js.map +1 -0
  81. package/dist/core/tasks/child-command-owner.d.ts +1 -1
  82. package/dist/core/tasks/child-command-owner.d.ts.map +1 -1
  83. package/dist/core/tasks/child-command-owner.js +22 -0
  84. package/dist/core/tasks/child-command-owner.js.map +1 -1
  85. package/dist/core/tasks/completion-message.d.ts +11 -0
  86. package/dist/core/tasks/completion-message.d.ts.map +1 -0
  87. package/dist/core/tasks/completion-message.js +30 -0
  88. package/dist/core/tasks/completion-message.js.map +1 -0
  89. package/dist/core/tasks/completion.d.ts +2 -0
  90. package/dist/core/tasks/completion.d.ts.map +1 -1
  91. package/dist/core/tasks/completion.js +30 -14
  92. package/dist/core/tasks/completion.js.map +1 -1
  93. package/dist/core/tasks/contracts.d.ts +4 -0
  94. package/dist/core/tasks/contracts.d.ts.map +1 -1
  95. package/dist/core/tasks/contracts.js.map +1 -1
  96. package/dist/core/tasks/supervisor.d.ts +29 -3
  97. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  98. package/dist/core/tasks/supervisor.js +48 -25
  99. package/dist/core/tasks/supervisor.js.map +1 -1
  100. package/dist/core/tasks/task-view-source.d.ts +6 -0
  101. package/dist/core/tasks/task-view-source.d.ts.map +1 -1
  102. package/dist/core/tasks/task-view-source.js +49 -0
  103. package/dist/core/tasks/task-view-source.js.map +1 -1
  104. package/dist/core/tools/bash-pty-native.d.ts +6 -1
  105. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  106. package/dist/core/tools/bash-pty-native.js +5 -1
  107. package/dist/core/tools/bash-pty-native.js.map +1 -1
  108. package/dist/core/tools/bash.d.ts +5 -0
  109. package/dist/core/tools/bash.d.ts.map +1 -1
  110. package/dist/core/tools/bash.js +14 -5
  111. package/dist/core/tools/bash.js.map +1 -1
  112. package/dist/core/tools/history-protocol.d.ts +15 -1
  113. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  114. package/dist/core/tools/history-protocol.js +9 -7
  115. package/dist/core/tools/history-protocol.js.map +1 -1
  116. package/dist/core/tools/shell-task-status.d.ts.map +1 -1
  117. package/dist/core/tools/shell-task-status.js +3 -13
  118. package/dist/core/tools/shell-task-status.js.map +1 -1
  119. package/dist/core/workflow-stage-admission.d.ts +2 -0
  120. package/dist/core/workflow-stage-admission.d.ts.map +1 -1
  121. package/dist/core/workflow-stage-admission.js +36 -6
  122. package/dist/core/workflow-stage-admission.js.map +1 -1
  123. package/dist/index.d.ts +1 -1
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +2 -2
  126. package/dist/index.js.map +1 -1
  127. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  128. package/dist/modes/interactive/components/chat-session-host-rendering.js +12 -8
  129. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  130. package/dist/modes/interactive/components/chat-session-host-state.d.ts +2 -0
  131. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  132. package/dist/modes/interactive/components/chat-session-host-state.js +2 -0
  133. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  134. package/dist/modes/interactive/components/chat-session-host-types.d.ts +6 -0
  135. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  136. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  137. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/chat-session-host.js +5 -2
  139. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  140. package/dist/modes/interactive/components/footer.d.ts +8 -5
  141. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  142. package/dist/modes/interactive/components/footer.js +5 -2
  143. package/dist/modes/interactive/components/footer.js.map +1 -1
  144. package/dist/modes/interactive/components/index.d.ts +1 -0
  145. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  146. package/dist/modes/interactive/components/index.js +1 -0
  147. package/dist/modes/interactive/components/index.js.map +1 -1
  148. package/dist/modes/interactive/components/input-label.d.ts +29 -0
  149. package/dist/modes/interactive/components/input-label.d.ts.map +1 -0
  150. package/dist/modes/interactive/components/input-label.js +75 -0
  151. package/dist/modes/interactive/components/input-label.js.map +1 -0
  152. package/dist/modes/interactive/components/task-inspector.d.ts +4 -1
  153. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  154. package/dist/modes/interactive/components/task-inspector.js +6 -2
  155. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  156. package/dist/modes/interactive/components/task-transcript-page.d.ts +12 -1
  157. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  158. package/dist/modes/interactive/components/task-transcript-page.js +63 -6
  159. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  160. package/dist/modes/interactive/interactive-input-handling.js +1 -0
  161. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  162. package/dist/modes/interactive/interactive-slash-commands.js +1 -0
  163. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  164. package/dist/modes/interactive-engine/engine-session-stats.d.ts +1 -1
  165. package/dist/modes/interactive-engine/engine-session-stats.d.ts.map +1 -1
  166. package/dist/modes/interactive-engine/engine-session-stats.js.map +1 -1
  167. package/dist/modes/rpc/task-ui-bridge.d.ts +2 -2
  168. package/dist/modes/rpc/task-ui-bridge.d.ts.map +1 -1
  169. package/dist/modes/rpc/task-ui-bridge.js +2 -0
  170. package/dist/modes/rpc/task-ui-bridge.js.map +1 -1
  171. package/docs/background-tasks.md +14 -1
  172. package/docs/getting-started/first-session.md +1 -1
  173. package/docs/intercom/operations.md +4 -2
  174. package/docs/intercom/reference.md +18 -1
  175. package/docs/llama-cpp.md +1 -1
  176. package/docs/sessions.md +1 -1
  177. package/docs/subagents.md +5 -1
  178. package/docs/tools.md +1 -1
  179. package/docs/usage.md +1 -12
  180. package/docs/workflows/operations.md +3 -1
  181. package/docs/workflows/verification.md +1 -8
  182. package/npm-shrinkwrap.json +83 -98
  183. package/package.json +6 -6
@@ -0,0 +1,280 @@
1
+ import type { JsonWireValue } from "./framing.js";
2
+ import { rehydrateErrorCause, type SerializedErrorCause, serializeErrorCause } from "./released-child-errors.js";
3
+
4
+ /** How a subagent's last run ended, as the session that launched it reports it (#4639). */
5
+ export type SubagentEndedOutcome = "completed" | "failed" | "stopped" | "cancelled";
6
+
7
+ export const SUBAGENT_ENDED_OUTCOMES: readonly SubagentEndedOutcome[] = ["completed", "failed", "stopped", "cancelled"];
8
+
9
+ /** The subagent ended and its launching session said why. */
10
+ export type SubagentRecipientEndedCode =
11
+ | "recipient_completed"
12
+ | "recipient_failed"
13
+ | "recipient_stopped"
14
+ | "recipient_cancelled";
15
+
16
+ /** The subagent's connection ended and neither it came back nor its launching session said why. */
17
+ export type SubagentRecipientDisconnectedCode = "recipient_disconnected";
18
+
19
+ /** The subagent is released and the session that would wake it is suspended or disconnected. */
20
+ export type SubagentRecipientOwnerSuspendedCode = "recipient_owner_suspended";
21
+
22
+ /** Why a send or ask to a subagent with no live session was refused (#4639). Codes are public API. */
23
+ export type IntercomRecipientGoneErrorCode =
24
+ | SubagentRecipientEndedCode
25
+ | SubagentRecipientDisconnectedCode
26
+ | SubagentRecipientOwnerSuspendedCode;
27
+
28
+ export const INTERCOM_RECIPIENT_GONE_ERROR_CODES: readonly IntercomRecipientGoneErrorCode[] = [
29
+ "recipient_completed",
30
+ "recipient_failed",
31
+ "recipient_stopped",
32
+ "recipient_cancelled",
33
+ "recipient_disconnected",
34
+ "recipient_owner_suspended",
35
+ ];
36
+
37
+ const CODES: ReadonlySet<unknown> = new Set(INTERCOM_RECIPIENT_GONE_ERROR_CODES);
38
+
39
+ export function isIntercomRecipientGoneErrorCode(value: unknown): value is IntercomRecipientGoneErrorCode {
40
+ return CODES.has(value);
41
+ }
42
+
43
+ const ENDED_CODE: Readonly<Record<SubagentEndedOutcome, SubagentRecipientEndedCode>> = {
44
+ completed: "recipient_completed",
45
+ failed: "recipient_failed",
46
+ stopped: "recipient_stopped",
47
+ cancelled: "recipient_cancelled",
48
+ };
49
+
50
+ /** The refusal code of a subagent that ended with `outcome`. */
51
+ export function subagentEndedCode(outcome: SubagentEndedOutcome): SubagentRecipientEndedCode {
52
+ return ENDED_CODE[outcome];
53
+ }
54
+
55
+ /** The send's target as it was addressed, and the subagent it named; ids and names only. */
56
+ export interface IntercomRecipientGoneErrorFields {
57
+ readonly target: string;
58
+ readonly childName: string;
59
+ /** The `<runId>:<index>` id its launching session resumes it by, when that session reported it. */
60
+ readonly childId?: string;
61
+ }
62
+
63
+ const WHAT: Readonly<Record<IntercomRecipientGoneErrorCode, string>> = {
64
+ recipient_completed: "completed and has no live session",
65
+ recipient_failed: "failed and has no live session",
66
+ recipient_stopped: "was stopped (paused or quit) and has no live session",
67
+ recipient_cancelled: "was cancelled for good and has no live session",
68
+ recipient_disconnected: "disconnected and has not reconnected",
69
+ recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now",
70
+ };
71
+
72
+ function hintFor(code: IntercomRecipientGoneErrorCode, childId: string | undefined): string {
73
+ if (code === "recipient_cancelled")
74
+ return "It cannot be resumed; launch a fresh subagent if its work is still needed.";
75
+ if (code === "recipient_disconnected")
76
+ return 'Its launching session has not said why; check subagent({ action: "status" }) there, or try again shortly.';
77
+ if (code === "recipient_owner_suspended")
78
+ return "Try again once its launching session is back; to reach that session now, send to its workflow stage target (workflow:<rootRunId>/<stage>), which queues the message until the stage reopens.";
79
+ return `Its launching session can continue it with subagent({ action: "resume", id: ${JSON.stringify(childId ?? "<child-id>")}, message: "<your message>" }).`;
80
+ }
81
+
82
+ const BASE_NAME = "IntercomRecipientGoneError";
83
+ const ENDED_NAME = "SubagentRecipientEndedError";
84
+ const DISCONNECTED_NAME = "SubagentRecipientDisconnectedError";
85
+ const OWNER_SUSPENDED_NAME = "SubagentRecipientOwnerSuspendedError";
86
+
87
+ /**
88
+ * #4639: base of the refusals of a send or ask to a subagent that has no live session, decided by the broker
89
+ * instead of a bare `Session not found`: it names why the subagent is gone and what to do next.
90
+ */
91
+ export class IntercomRecipientGoneError extends Error {
92
+ override readonly name: string = BASE_NAME;
93
+ readonly code: IntercomRecipientGoneErrorCode;
94
+ readonly hint: string;
95
+ readonly retryable: boolean;
96
+ readonly target: string;
97
+ readonly childName: string;
98
+ readonly childId?: string;
99
+
100
+ constructor(
101
+ code: IntercomRecipientGoneErrorCode,
102
+ fields: IntercomRecipientGoneErrorFields,
103
+ options?: { readonly cause?: Error },
104
+ ) {
105
+ const hint = hintFor(code, fields.childId);
106
+ super(`Subagent ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
107
+ this.code = code;
108
+ this.hint = hint;
109
+ this.retryable = code === "recipient_disconnected" || code === "recipient_owner_suspended";
110
+ this.target = fields.target;
111
+ this.childName = fields.childName;
112
+ this.childId = fields.childId;
113
+ }
114
+
115
+ get fields(): IntercomRecipientGoneErrorFields {
116
+ return {
117
+ target: this.target,
118
+ childName: this.childName,
119
+ ...(this.childId === undefined ? {} : { childId: this.childId }),
120
+ };
121
+ }
122
+ }
123
+
124
+ /** The subagent's launching session reported it ended: completed, failed, stopped or cancelled. Not retryable. */
125
+ export class SubagentRecipientEndedError extends IntercomRecipientGoneError {
126
+ override readonly name = ENDED_NAME;
127
+ declare readonly code: SubagentRecipientEndedCode;
128
+ constructor(
129
+ code: SubagentRecipientEndedCode,
130
+ fields: IntercomRecipientGoneErrorFields,
131
+ options?: { readonly cause?: Error },
132
+ ) {
133
+ super(code, fields, options);
134
+ }
135
+ }
136
+
137
+ /** The subagent disconnected and did not come back while the send waited, and nobody said why. Retryable. */
138
+ export class SubagentRecipientDisconnectedError extends IntercomRecipientGoneError {
139
+ override readonly name = DISCONNECTED_NAME;
140
+ declare readonly code: SubagentRecipientDisconnectedCode;
141
+ constructor(fields: IntercomRecipientGoneErrorFields, options?: { readonly cause?: Error }) {
142
+ super("recipient_disconnected", fields, options);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * The subagent is released and the session that launched it, which wakes it, is suspended or disconnected: a workflow
148
+ * stage that waits with its session released, for instance. Its sends were held and the hold ended first. Retryable.
149
+ */
150
+ export class SubagentRecipientOwnerSuspendedError extends IntercomRecipientGoneError {
151
+ override readonly name = OWNER_SUSPENDED_NAME;
152
+ declare readonly code: SubagentRecipientOwnerSuspendedCode;
153
+ constructor(fields: IntercomRecipientGoneErrorFields, options?: { readonly cause?: Error }) {
154
+ super("recipient_owner_suspended", fields, options);
155
+ }
156
+ }
157
+
158
+ const NAMES: ReadonlySet<string> = new Set([BASE_NAME, ENDED_NAME, DISCONNECTED_NAME, OWNER_SUSPENDED_NAME]);
159
+ const ENDED_NAMES: ReadonlySet<string> = new Set([ENDED_NAME]);
160
+ const DISCONNECTED_NAMES: ReadonlySet<string> = new Set([DISCONNECTED_NAME]);
161
+ const OWNER_SUSPENDED_NAMES: ReadonlySet<string> = new Set([OWNER_SUSPENDED_NAME]);
162
+
163
+ function hasStructure(error: Error, names: ReadonlySet<string>): boolean {
164
+ return names.has(error.name) && isIntercomRecipientGoneErrorCode((error as Error & { readonly code?: unknown }).code);
165
+ }
166
+
167
+ export function isIntercomRecipientGoneError(error: Error): error is IntercomRecipientGoneError {
168
+ return error instanceof IntercomRecipientGoneError || hasStructure(error, NAMES);
169
+ }
170
+
171
+ export function isSubagentRecipientEndedError(error: Error): error is SubagentRecipientEndedError {
172
+ return error instanceof SubagentRecipientEndedError || hasStructure(error, ENDED_NAMES);
173
+ }
174
+
175
+ export function isSubagentRecipientDisconnectedError(error: Error): error is SubagentRecipientDisconnectedError {
176
+ return error instanceof SubagentRecipientDisconnectedError || hasStructure(error, DISCONNECTED_NAMES);
177
+ }
178
+
179
+ export function isSubagentRecipientOwnerSuspendedError(error: Error): error is SubagentRecipientOwnerSuspendedError {
180
+ return error instanceof SubagentRecipientOwnerSuspendedError || hasStructure(error, OWNER_SUSPENDED_NAMES);
181
+ }
182
+
183
+ const MAX_CAUSE_DEPTH = 4;
184
+
185
+ /** Whether the error, or one of its first causes, is a gone-recipient refusal that may be retried. */
186
+ export function isRetryableIntercomRecipientGoneError(error: Error): boolean {
187
+ let current: Error | undefined = error;
188
+ for (let depth = 0; current !== undefined && depth <= MAX_CAUSE_DEPTH; depth++) {
189
+ if (isIntercomRecipientGoneError(current) && current.retryable) return true;
190
+ current = current.cause instanceof Error ? current.cause : undefined;
191
+ }
192
+ return false;
193
+ }
194
+
195
+ /** The refusal for a send addressed as `target` to a subagent that ended with `outcome`. */
196
+ export function subagentRecipientEnded(
197
+ outcome: SubagentEndedOutcome,
198
+ fields: IntercomRecipientGoneErrorFields,
199
+ ): SubagentRecipientEndedError {
200
+ return new SubagentRecipientEndedError(subagentEndedCode(outcome), fields);
201
+ }
202
+
203
+ export interface SerializedIntercomRecipientGoneError {
204
+ readonly name: string;
205
+ readonly code: IntercomRecipientGoneErrorCode;
206
+ readonly message: string;
207
+ readonly hint: string;
208
+ readonly retryable: boolean;
209
+ readonly fields: IntercomRecipientGoneErrorFields;
210
+ readonly cause?: SerializedErrorCause;
211
+ }
212
+
213
+ export function serializeIntercomRecipientGoneError(
214
+ error: IntercomRecipientGoneError,
215
+ ): SerializedIntercomRecipientGoneError {
216
+ return {
217
+ name: error.name,
218
+ code: error.code,
219
+ message: error.message,
220
+ hint: error.hint,
221
+ retryable: error.retryable,
222
+ fields: error.fields,
223
+ ...(error.cause instanceof Error ? { cause: serializeErrorCause(error.cause, 1) } : {}),
224
+ };
225
+ }
226
+
227
+ /** The same class on this side of the boundary; an unknown name keeps its name and code on the family base. */
228
+ export function rehydrateIntercomRecipientGoneError(
229
+ serialized: SerializedIntercomRecipientGoneError,
230
+ ): IntercomRecipientGoneError {
231
+ const options = serialized.cause === undefined ? undefined : { cause: rehydrateErrorCause(serialized.cause, 1) };
232
+ const { code, fields } = serialized;
233
+ if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended")
234
+ return new SubagentRecipientEndedError(code, fields, options);
235
+ if (serialized.name === DISCONNECTED_NAME && code === "recipient_disconnected")
236
+ return new SubagentRecipientDisconnectedError(fields, options);
237
+ if (serialized.name === OWNER_SUSPENDED_NAME && code === "recipient_owner_suspended")
238
+ return new SubagentRecipientOwnerSuspendedError(fields, options);
239
+ const error = new IntercomRecipientGoneError(code, fields, options);
240
+ Object.defineProperty(error, "name", { value: serialized.name });
241
+ return error;
242
+ }
243
+
244
+ type WireObject = { readonly [key: string]: JsonWireValue };
245
+
246
+ const isWireObject = (value: JsonWireValue | undefined): value is WireObject =>
247
+ typeof value === "object" && value !== null && !Array.isArray(value);
248
+
249
+ function readCause(value: JsonWireValue | undefined, depth: number): SerializedErrorCause | undefined | false {
250
+ if (value === undefined) return undefined;
251
+ if (!isWireObject(value) || typeof value.name !== "string" || typeof value.message !== "string") return false;
252
+ const next = depth < MAX_CAUSE_DEPTH ? readCause(value.cause, depth + 1) : undefined;
253
+ if (next === false) return false;
254
+ return { name: value.name, message: value.message, ...(next === undefined ? {} : { cause: next }) };
255
+ }
256
+
257
+ /** Validate a serialized refusal read off the wire; `undefined` when it is not one. */
258
+ export function readSerializedIntercomRecipientGoneError(
259
+ value: JsonWireValue | undefined,
260
+ ): SerializedIntercomRecipientGoneError | undefined {
261
+ if (!isWireObject(value)) return undefined;
262
+ const { name, code, message, hint, retryable, fields } = value;
263
+ if (typeof name !== "string" || !isIntercomRecipientGoneErrorCode(code)) return undefined;
264
+ if (typeof message !== "string" || typeof hint !== "string" || typeof retryable !== "boolean") return undefined;
265
+ if (!isWireObject(fields)) return undefined;
266
+ const { target, childName, childId } = fields;
267
+ if (typeof target !== "string" || typeof childName !== "string") return undefined;
268
+ if (childId !== undefined && typeof childId !== "string") return undefined;
269
+ const cause = readCause(value.cause, 1);
270
+ if (cause === false) return undefined;
271
+ return {
272
+ name,
273
+ code,
274
+ message,
275
+ hint,
276
+ retryable,
277
+ fields: { target, childName, ...(childId === undefined ? {} : { childId }) },
278
+ ...(cause === undefined ? {} : { cause }),
279
+ };
280
+ }
@@ -2,6 +2,7 @@ import type net from "node:net";
2
2
  import { hasGroup } from "../group.js";
3
3
  import type { DeliveryFailureReasonCode, SessionInfo } from "../types.js";
4
4
  import { sessionGroups } from "./group-membership.js";
5
+ import { type IntercomRecipientGoneError, SubagentRecipientOwnerSuspendedError } from "./recipient-gone-errors.js";
5
6
  import { ReleasedChildReservationError } from "./released-child-errors.js";
6
7
  import { isReleasedReservationKey, normalizeReservationTarget, releasedReservationKey } from "./released-children.js";
7
8
 
@@ -12,6 +13,11 @@ export const RESTORING_RECIPIENT_HOLD_MAX_MS = 120_000;
12
13
  /** A reservation covers the child's name plus its Atomic session id and its pre-restart Intercom id. */
13
14
  const MAX_RESERVED_TARGETS = 8;
14
15
  const MAX_HELD_SENDS = 256;
16
+ /**
17
+ * The most released-child reservations kept for owners that disconnected, across the broker (#4639); the oldest is
18
+ * forgotten first.
19
+ */
20
+ export const ORPHANED_RESERVATIONS_MAX = 4_096;
15
21
 
16
22
  /** A send the broker is holding for a subagent that is being restored. */
17
23
  export interface HeldSend {
@@ -34,7 +40,13 @@ export interface RestoringRecipientWake {
34
40
  export type RestoringRecipientAdmission =
35
41
  | { readonly kind: "none" }
36
42
  | { readonly kind: "held"; readonly timeoutMs: number; readonly wake?: RestoringRecipientWake }
37
- | { readonly kind: "refused"; readonly reason: string; readonly reasonCode?: DeliveryFailureReasonCode };
43
+ | {
44
+ readonly kind: "refused";
45
+ readonly reason: string;
46
+ readonly reasonCode?: DeliveryFailureReasonCode;
47
+ /** #4639: the typed refusal, when there is one; its message is `reason`. */
48
+ readonly error?: IntercomRecipientGoneError;
49
+ };
38
50
 
39
51
  /** One reservation as `RestoringRecipients.active` reports it; `gone` is the formatted gone refusal. */
40
52
  export interface RestoringReservationSnapshot {
@@ -62,7 +74,7 @@ interface HeldEntry {
62
74
 
63
75
  interface Reservation {
64
76
  readonly key: string;
65
- readonly ownerSessionId: string;
77
+ ownerSessionId: string;
66
78
  readonly childName: string;
67
79
  group: string;
68
80
  /**
@@ -99,6 +111,14 @@ export interface ReserveOptions {
99
111
  readonly replaceAliases?: boolean;
100
112
  }
101
113
 
114
+ /** The owner-suspended refusal of a send to a released child whose owner is away (#4639). */
115
+ function ownerSuspended(reservation: Reservation, held: Pick<HeldSend, "clientMessage">): IntercomRecipientGoneError {
116
+ return new SubagentRecipientOwnerSuspendedError({
117
+ target: held.clientMessage.to.trim(),
118
+ childName: reservation.childName,
119
+ });
120
+ }
121
+
102
122
  const normalizeTarget = normalizeReservationTarget;
103
123
 
104
124
  export function restoringRecipientRetryReason(childName: string): string {
@@ -136,7 +156,8 @@ const removeFromIndex = <Key, Value>(index: Map<Key, Set<Value>>, key: Key, valu
136
156
  * in the child's group finds no live session, it is held instead of failing with `Session not found`. A hold ends
137
157
  * in exactly one way: the child registers and every held send is dispatched again, once and in order; the owner
138
158
  * reports the child gone and held and later senders get the gone refusal; or the hold times out and the sender
139
- * is told to try again. Reservations end when their owner disconnects.
159
+ * is told to try again. Reservations end when their owner disconnects, except a released child's, which is kept for the
160
+ * owner's host session until it is back (#4639; see {@link dropOwner}).
140
161
  *
141
162
  * A reservation can start before the restore does: a resumed session reserves its recorded children at session
142
163
  * start, and the launching session of an interrupted workflow run reserves the children of the run's stages while
@@ -152,10 +173,29 @@ export class RestoringRecipients {
152
173
  private readonly byChild = new Map<string, Set<Reservation>>();
153
174
  private readonly byOwner = new Map<string, Set<Reservation>>();
154
175
  private readonly withHeld = new Set<Reservation>();
176
+ /**
177
+ * #4639: released-child reservations whose owner's connection closed, as a suspended workflow stage's does, oldest
178
+ * first, each with the owner's host session (its return address). An orphan goes on holding sends, waking nobody,
179
+ * until a session of that host session takes it over.
180
+ */
181
+ private readonly orphans = new Map<Reservation, string>();
155
182
  private heldTotal = 0;
156
183
  private liveTimers = 0;
157
184
 
158
- constructor(private readonly onExpired: (held: HeldSend, reason: string, reasonCode: DeliveryFailureReasonCode) => void) {}
185
+ constructor(
186
+ private readonly onExpired: (
187
+ held: HeldSend,
188
+ reason: string,
189
+ reasonCode: DeliveryFailureReasonCode,
190
+ error?: IntercomRecipientGoneError,
191
+ ) => void,
192
+ private readonly orphansMax = ORPHANED_RESERVATIONS_MAX,
193
+ ) {}
194
+
195
+ /** Reservations kept for owners that disconnected (#4639). */
196
+ get orphanCount(): number {
197
+ return this.orphans.size;
198
+ }
159
199
 
160
200
  /** Reservations in force, including gone markers. */
161
201
  get size(): number {
@@ -186,6 +226,24 @@ export class RestoringRecipients {
186
226
  return this.reservations.get(releasedReservationKey(childName))?.ownerSessionId;
187
227
  }
188
228
 
229
+ /**
230
+ * #4639: the session `ownerSessionId`, whose host session is `returnAddress`, comes back for the released children
231
+ * it kept before its connection closed: every orphaned reservation of that host session becomes its own again. The
232
+ * sends held for them wait for its next reservation, which asks it to wake the child.
233
+ */
234
+ adoptOrphans(ownerSessionId: string, returnAddress: string | undefined): void {
235
+ for (const [reservation, host] of [...this.orphans]) {
236
+ if (host !== returnAddress) continue;
237
+ this.orphans.delete(reservation);
238
+ removeFromIndex(this.byOwner, reservation.ownerSessionId, reservation);
239
+ reservation.ownerSessionId = ownerSessionId;
240
+ addToIndex(this.byOwner, ownerSessionId, reservation);
241
+ // Nobody was asked to wake the child for the sends held meanwhile: the owner's next reservation asks.
242
+ reservation.wake = false;
243
+ reservation.extended = false;
244
+ }
245
+ }
246
+
189
247
  /**
190
248
  * Reserve, or add targets to, the reservation for the child this capability authorizes. `group` is normalized.
191
249
  * A `dormant` reservation may be taken over by the supervisor that restores the child. Returns the wake to ask
@@ -283,6 +341,11 @@ export class RestoringRecipients {
283
341
  }
284
342
  if (reservation === undefined) return { kind: "none" };
285
343
  if (reservation.gone !== undefined) return { kind: "refused", reason: reservation.gone };
344
+ const orphaned = this.orphans.has(reservation);
345
+ if (orphaned && (!canHold || reservation.held.size >= MAX_HELD_SENDS)) {
346
+ const error = ownerSuspended(reservation, held);
347
+ return { kind: "refused", reason: error.message, error };
348
+ }
286
349
  if (!canHold || reservation.held.size >= MAX_HELD_SENDS) {
287
350
  return {
288
351
  kind: "refused",
@@ -290,7 +353,10 @@ export class RestoringRecipients {
290
353
  reasonCode: unrestoredReasonCode(reservation.key, reservation.wake),
291
354
  };
292
355
  }
293
- const wake = reservation.wake && reservation.held.size === 0 ? this.wakeOf(reservation) : undefined;
356
+ const wake =
357
+ reservation.wake && !orphaned && reservation.held.size === 0
358
+ ? this.wakeOf(reservation)
359
+ : undefined;
294
360
  if (reservation.held.size === 0) reservation.extended = false;
295
361
  const entry: HeldEntry = { timer: undefined, admittedAt: Date.now(), reservation };
296
362
  this.arm(held, entry, RESTORING_RECIPIENT_HOLD_MS);
@@ -382,10 +448,38 @@ export class RestoringRecipients {
382
448
  return { held, gone: reservation.gone };
383
449
  }
384
450
 
385
- /** The owner disconnected: end its reservations and return their held sends for ordinary routing. */
386
- dropOwner(ownerSessionId: string): HeldSend[] {
451
+ /**
452
+ * The owner disconnected: end its reservations and return their held sends for ordinary routing. #4639: given the
453
+ * owner's host session (`returnAddress`), its released children are kept instead, holding sends, until a session of
454
+ * that host session takes them over ({@link adoptOrphans}) or they are forgotten as the oldest beyond
455
+ * {@link ORPHANED_RESERVATIONS_MAX}, whose held sends are returned too.
456
+ */
457
+ dropOwner(ownerSessionId: string, returnAddress?: string): HeldSend[] {
387
458
  const released: HeldSend[] = [];
388
459
  for (const reservation of [...(this.byOwner.get(ownerSessionId) ?? [])]) {
460
+ if (returnAddress !== undefined && isReleasedReservationKey(reservation.key) && reservation.gone === undefined) {
461
+ this.orphans.set(reservation, returnAddress);
462
+ continue;
463
+ }
464
+ this.forget(reservation);
465
+ released.push(...this.take(reservation));
466
+ }
467
+ for (const oldest of this.orphans.keys()) {
468
+ if (this.orphans.size <= this.orphansMax) break;
469
+ this.forget(oldest);
470
+ released.push(...this.take(oldest));
471
+ }
472
+ return released;
473
+ }
474
+
475
+ /**
476
+ * #4639: the run whose stages kept these orphaned released children ended: forget every orphaned reservation in a
477
+ * group `inGroup` accepts, and return its held sends for ordinary routing.
478
+ */
479
+ dropOrphans(inGroup: (group: string) => boolean): HeldSend[] {
480
+ const released: HeldSend[] = [];
481
+ for (const reservation of [...this.orphans.keys()]) {
482
+ if (!inGroup(reservation.group)) continue;
389
483
  this.forget(reservation);
390
484
  released.push(...this.take(reservation));
391
485
  }
@@ -428,6 +522,7 @@ export class RestoringRecipients {
428
522
  this.byChild.clear();
429
523
  this.byOwner.clear();
430
524
  this.withHeld.clear();
525
+ this.orphans.clear();
431
526
  }
432
527
 
433
528
  private wakeOf(reservation: Reservation): RestoringRecipientWake {
@@ -460,6 +555,11 @@ export class RestoringRecipients {
460
555
  const reservation = entry.reservation;
461
556
  if (reservation.held.get(held) !== entry) return;
462
557
  this.detach(reservation, held);
558
+ if (this.orphans.has(reservation)) {
559
+ const error = ownerSuspended(reservation, held);
560
+ this.onExpired(held, error.message, error.code, error);
561
+ return;
562
+ }
463
563
  this.onExpired(
464
564
  held,
465
565
  restoringRecipientRetryReason(reservation.childName),
@@ -487,6 +587,7 @@ export class RestoringRecipients {
487
587
  }
488
588
 
489
589
  private forget(reservation: Reservation): void {
590
+ this.orphans.delete(reservation);
490
591
  this.reservations.delete(reservation.key);
491
592
  removeFromIndex(this.byChild, normalizeTarget(reservation.childName), reservation);
492
593
  removeFromIndex(this.byOwner, reservation.ownerSessionId, reservation);
@@ -37,6 +37,8 @@ export interface BrokerConnectedSession {
37
37
  readonly registrationReturnAddress?: string;
38
38
  /** Broker-bound supervisor relationship established by a capability. */
39
39
  supervisorId?: string;
40
+ /** #4639: the supervisor's host session, as it registered: where its next session takes its subagents over. */
41
+ readonly supervisorReturnAddress?: string;
40
42
  /** Private issuer identity used to restore child capabilities after reconnects. */
41
43
  supervisorOwnerToken?: string;
42
44
  /** #3761: the recipient confirms each message once it has saved it; `delivered` waits for that confirmation. */
@@ -181,6 +183,12 @@ export function handleBrokerSend(
181
183
  /** #4079: whether the sender's read-only `list` peek may inspect a group; names a hidden target's group. */
182
184
  canPeekGroup?: (sender: BrokerConnectedSession, group: string) => boolean,
183
185
  routeReleasedAskerReply?: ReleasedAskerReplyRouter,
186
+ /**
187
+ * #4639: the `workflow:` target a workflow-stage session's name or id stands for, when this sender may reach that
188
+ * stage; consulted only for a target nothing else resolved, so the stage is reached through its current session or
189
+ * its run's queue even after the session that held the name was replaced or released.
190
+ */
191
+ resolveWorkflowStageAlias?: (sender: BrokerConnectedSession, alias: string) => string | undefined,
184
192
  ): void {
185
193
  const message = clientMessage.message;
186
194
  const messageId = wireMessageId(message);
@@ -380,6 +388,38 @@ export function handleBrokerSend(
380
388
  (info) => sessions.get(info.id)?.registrationReturnAddress,
381
389
  )
382
390
  : nameOrIdResolution;
391
+ // #4639: a supervisor that is a workflow stage whose session was released or replaced is reached through its stage,
392
+ // as a plain send: the stage's next session is not the session the supervisor channel was authorized for.
393
+ const stageTarget =
394
+ resolution.kind === "not_found" && workflowTarget === undefined && !requirePendingReply &&
395
+ expectedRecipientId === undefined
396
+ ? resolveWorkflowStageAlias?.(fromSession, trimmedTo)
397
+ : undefined;
398
+ if (stageTarget !== undefined) {
399
+ handleBrokerSend(
400
+ socket,
401
+ { ...clientMessage, type: "send", to: stageTarget, logicalTarget: stageTarget },
402
+ currentId,
403
+ sessions,
404
+ deliveredMessages,
405
+ write,
406
+ supervisorCache,
407
+ pendingQuestions,
408
+ routePendingStage,
409
+ resolveLiveWorkflowStage,
410
+ canControlLiveWorkflowStage,
411
+ resolveLegacyWorkflowStageTarget,
412
+ writeConfirmed,
413
+ isNonAgentWorkflowTarget,
414
+ holdForRestoringRecipient,
415
+ receipts,
416
+ routeRemote,
417
+ canPeekGroup,
418
+ routeReleasedAskerReply,
419
+ resolveWorkflowStageAlias,
420
+ );
421
+ return;
422
+ }
383
423
  if (
384
424
  routeRemote !== undefined &&
385
425
  resolution.kind === "not_found" &&
@@ -437,6 +477,7 @@ export function handleBrokerSend(
437
477
  undefined,
438
478
  canPeekGroup,
439
479
  routeReleasedAskerReply,
480
+ resolveWorkflowStageAlias,
440
481
  ),
441
482
  });
442
483
  return;
@@ -506,6 +547,7 @@ export function handleBrokerSend(
506
547
  routeRemote,
507
548
  canPeekGroup,
508
549
  routeReleasedAskerReply,
550
+ resolveWorkflowStageAlias,
509
551
  );
510
552
  },
511
553
  });
@@ -0,0 +1,69 @@
1
+ /** The most session aliases kept for one run's stages; the oldest is forgotten first. */
2
+ export const WORKFLOW_STAGE_ALIASES_PER_RUN_MAX = 256;
3
+
4
+ /** The stage a session alias stands for: its run, its canonical `workflow:` target and the stage's own group. */
5
+ export interface WorkflowStageAlias {
6
+ readonly runId: string;
7
+ readonly target: string;
8
+ readonly group: string;
9
+ }
10
+
11
+ const normalizeAlias = (alias: string): string => alias.trim().toLowerCase();
12
+
13
+ /**
14
+ * #4639: the names and ids every session of a workflow stage registered under, kept per run, so a send to a stage's
15
+ * `subagent-chat-<id>` name or session id reaches the stage through its `workflow:` target even after that session was
16
+ * replaced or released: the canonical target routes to the stage's current session, or queues for it in the run's
17
+ * queue while it has none. Aliases live as long as their run's route; the broker forgets a run's aliases with it.
18
+ */
19
+ export class WorkflowStageAliases {
20
+ private readonly byAlias = new Map<string, WorkflowStageAlias>();
21
+ private readonly byRun = new Map<string, Set<string>>();
22
+
23
+ constructor(private readonly perRunMax = WORKFLOW_STAGE_ALIASES_PER_RUN_MAX) {}
24
+
25
+ /** Aliases kept, across every run. */
26
+ get size(): number {
27
+ return this.byAlias.size;
28
+ }
29
+
30
+ /** Remember that a session of the stage at `stage.target` registered under these aliases. */
31
+ record(stage: WorkflowStageAlias, aliases: readonly string[]): void {
32
+ for (const raw of aliases) {
33
+ const alias = normalizeAlias(raw);
34
+ if (alias.length === 0) continue;
35
+ const previous = this.byAlias.get(alias);
36
+ // Every alias kept is in its run's set.
37
+ if (previous !== undefined) (this.byRun.get(previous.runId) as Set<string>).delete(alias);
38
+ let run = this.byRun.get(stage.runId);
39
+ if (run === undefined) {
40
+ run = new Set();
41
+ this.byRun.set(stage.runId, run);
42
+ }
43
+ run.add(alias);
44
+ this.byAlias.set(alias, { runId: stage.runId, target: stage.target, group: stage.group });
45
+ if (run.size > this.perRunMax) {
46
+ const oldest = run.values().next().value as string;
47
+ run.delete(oldest);
48
+ this.byAlias.delete(oldest);
49
+ }
50
+ }
51
+ }
52
+
53
+ resolve(alias: string): WorkflowStageAlias | undefined {
54
+ return this.byAlias.get(normalizeAlias(alias));
55
+ }
56
+
57
+ /** The run's route is gone: none of its stages is reachable through an alias any more. */
58
+ forgetRun(runId: string): void {
59
+ const run = this.byRun.get(runId);
60
+ if (run === undefined) return;
61
+ for (const alias of run) this.byAlias.delete(alias);
62
+ this.byRun.delete(runId);
63
+ }
64
+
65
+ /** Aliases and runs held now; counted by tests. */
66
+ sizes(): { readonly aliases: number; readonly runs: number } {
67
+ return { aliases: this.byAlias.size, runs: this.byRun.size };
68
+ }
69
+ }