@bastani/atomic 0.9.78 → 0.9.79-alpha.2
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.
- package/CHANGELOG.md +50 -0
- package/dist/builtin/intercom/CHANGELOG.md +12 -0
- package/dist/builtin/intercom/broker/broker.ts +198 -72
- package/dist/builtin/intercom/broker/client-message-validation.ts +38 -0
- package/dist/builtin/intercom/broker/client.ts +150 -11
- package/dist/builtin/intercom/broker/delivery-failure-reason.ts +1 -0
- package/dist/builtin/intercom/broker/departed-children.ts +23 -0
- package/dist/builtin/intercom/broker/hosted-session-errors.ts +188 -0
- package/dist/builtin/intercom/broker/hosted-sessions.ts +113 -0
- package/dist/builtin/intercom/broker/multinode-router.ts +7 -2
- package/dist/builtin/intercom/broker/presence-handler.ts +2 -1
- package/dist/builtin/intercom/broker/protocol-version.ts +6 -1
- package/dist/builtin/intercom/broker/recipient-gone-errors.ts +46 -5
- package/dist/builtin/intercom/broker/released-reply-errors.ts +1 -1
- package/dist/builtin/intercom/broker/send-handler.ts +19 -3
- package/dist/builtin/intercom/broker/socket-writes.ts +20 -1
- package/dist/builtin/intercom/hosted-session-timeout-error.ts +59 -0
- package/dist/builtin/intercom/index.bundle.mjs +634 -125
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/types.ts +41 -3
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +8 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +90 -34
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +9 -0
- package/dist/builtin/workflows/builtin/{chunk-89we7r4p.js → chunk-5hrzxynt.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-8yfssw01.js → chunk-m56qhe4b.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-wh2p4qjg.js → chunk-x8m4t2jy.js} +182 -33
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +1243 -230
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +854 -170
- package/dist/builtin/workflows/src/index.js +854 -170
- package/dist/builtin/workflows/src/local-worker-entry.mjs +854 -170
- package/dist/cli/startup-progress.d.ts +30 -0
- package/dist/cli/startup-progress.d.ts.map +1 -0
- package/dist/cli/startup-progress.js +78 -0
- package/dist/cli/startup-progress.js.map +1 -0
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +3 -0
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +2 -0
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +2 -0
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-state.d.ts +12 -4
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-state.js +82 -15
- package/dist/core/agent-session-state.js.map +1 -1
- package/dist/core/agent-session.d.ts +3 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +3 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/builtin-resource-loader.d.ts.map +1 -1
- package/dist/core/builtin-resource-loader.js +3 -0
- package/dist/core/builtin-resource-loader.js.map +1 -1
- package/dist/core/debug.d.ts +4 -2
- package/dist/core/debug.d.ts.map +1 -1
- package/dist/core/debug.js +15 -1
- package/dist/core/debug.js.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts +5 -0
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +57 -20
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/template.js +1 -1
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +2 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.d.ts +7 -0
- package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
- package/dist/core/extensions/workflow-activity-hub.js +104 -6
- package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
- package/dist/core/keybindings.d.ts +0 -8
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +0 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mandatory-resource-loader.d.ts.map +1 -1
- package/dist/core/mandatory-resource-loader.js +3 -0
- package/dist/core/mandatory-resource-loader.js.map +1 -1
- package/dist/core/resume/session-resume.d.ts +7 -1
- package/dist/core/resume/session-resume.d.ts.map +1 -1
- package/dist/core/resume/session-resume.js +136 -16
- package/dist/core/resume/session-resume.js.map +1 -1
- package/dist/core/session-history-index.d.ts +31 -0
- package/dist/core/session-history-index.d.ts.map +1 -0
- package/dist/core/session-history-index.js +82 -0
- package/dist/core/session-history-index.js.map +1 -0
- package/dist/core/session-manager-core.d.ts +3 -0
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +22 -17
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-history.d.ts +3 -3
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +6 -5
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/storage/session/history-load-observer.d.ts +11 -0
- package/dist/core/storage/session/history-load-observer.d.ts.map +1 -0
- package/dist/core/storage/session/history-load-observer.js +25 -0
- package/dist/core/storage/session/history-load-observer.js.map +1 -0
- package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
- package/dist/core/storage/session/sql-session-store.js +6 -0
- package/dist/core/storage/session/sql-session-store.js.map +1 -1
- package/dist/core/tool-deactivation.d.ts +11 -0
- package/dist/core/tool-deactivation.d.ts.map +1 -0
- package/dist/core/tool-deactivation.js +13 -0
- package/dist/core/tool-deactivation.js.map +1 -0
- package/dist/core/tool-status.d.ts +6 -1
- package/dist/core/tool-status.d.ts.map +1 -1
- package/dist/core/tool-status.js +11 -3
- package/dist/core/tool-status.js.map +1 -1
- package/dist/extensions/llama/errors.js +1 -1
- package/dist/extensions/llama/errors.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts +1 -1
- package/dist/extensions/llama/provider.js +1 -1
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/main-session.d.ts +14 -2
- package/dist/main-session.d.ts.map +1 -1
- package/dist/main-session.js +42 -9
- package/dist/main-session.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +4 -2
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +6 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +13 -4
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-boundary-message.js +3 -4
- package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
- package/dist/modes/interactive/components/task-detail.d.ts +1 -1
- package/dist/modes/interactive/components/task-detail.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-detail.js +1 -3
- package/dist/modes/interactive/components/task-detail.js.map +1 -1
- package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-inspector.js +1 -7
- package/dist/modes/interactive/components/task-inspector.js.map +1 -1
- package/dist/modes/interactive/components/task-navigation.d.ts +0 -1
- package/dist/modes/interactive/components/task-navigation.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-navigation.js +1 -3
- package/dist/modes/interactive/components/task-navigation.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +5 -9
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-deferred-startup.js +8 -5
- package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +16 -10
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +2 -0
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-unavailable-tools.d.ts +20 -0
- package/dist/modes/interactive/interactive-unavailable-tools.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-unavailable-tools.js +40 -0
- package/dist/modes/interactive/interactive-unavailable-tools.js.map +1 -0
- package/dist/modes/interactive-engine/engine-diagnostic-view.d.ts +3 -2
- package/dist/modes/interactive-engine/engine-diagnostic-view.d.ts.map +1 -1
- package/dist/modes/interactive-engine/engine-diagnostic-view.js +5 -3
- package/dist/modes/interactive-engine/engine-diagnostic-view.js.map +1 -1
- package/dist/modes/interactive-engine/remote-component.js +1 -1
- package/dist/modes/interactive-engine/remote-component.js.map +1 -1
- package/docs/background-tasks.md +1 -1
- package/docs/compaction/reference.md +1 -1
- package/docs/compaction.md +3 -3
- package/docs/extensions/api-reference.md +1 -1
- package/docs/extensions/events.md +2 -0
- package/docs/extensions.md +1 -1
- package/docs/intercom/operations.md +2 -2
- package/docs/intercom/reference.md +12 -1
- package/docs/keybindings.md +2 -3
- package/docs/llama-cpp.md +9 -10
- package/docs/models/reference.md +1 -1
- package/docs/models-configuration.md +1 -1
- package/docs/sessions.md +6 -2
- package/docs/subagents.md +3 -1
- package/docs/usage.md +1 -1
- package/docs/workflows/operations.md +2 -2
- package/docs/worktree-snapshots.md +3 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +4 -4
- package/schemas/keybindings.schema.json +0 -4
- package/schemas/models.schema.json +1 -1
|
@@ -23,6 +23,8 @@ import type {
|
|
|
23
23
|
IntercomDeliveryMode,
|
|
24
24
|
DeliveryFailureReasonCode,
|
|
25
25
|
ReleasedChildRefusal,
|
|
26
|
+
HostedSessionAssignment,
|
|
27
|
+
HostedSessionFrameItem,
|
|
26
28
|
} from "../types.js";
|
|
27
29
|
import { buildSendSignature, PendingSendRegistry, PendingSendTimeoutError } from "./pending-send-registry.js";
|
|
28
30
|
import { readSubagentMessageSource } from "../source-ownership.js";
|
|
@@ -41,6 +43,15 @@ import {
|
|
|
41
43
|
rehydrateIntercomRecipientGoneError,
|
|
42
44
|
type SubagentEndedOutcome,
|
|
43
45
|
} from "./recipient-gone-errors.js";
|
|
46
|
+
import {
|
|
47
|
+
HostedSessionRequestError,
|
|
48
|
+
hostedSessionErrorFor,
|
|
49
|
+
type IntercomHostedSessionError,
|
|
50
|
+
readHostedSessionRefusal,
|
|
51
|
+
readSerializedIntercomHostedSessionError,
|
|
52
|
+
rehydrateIntercomHostedSessionError,
|
|
53
|
+
} from "./hosted-session-errors.js";
|
|
54
|
+
import { HOSTED_SESSION_FRAME_MAX, readHostedSessionAssignments, validateHostSessionsFrame } from "./hosted-sessions.js";
|
|
44
55
|
import { normalizeGroups } from "../group.js";
|
|
45
56
|
import {
|
|
46
57
|
BROKER_RETIRING_CODE,
|
|
@@ -53,11 +64,13 @@ import {
|
|
|
53
64
|
IntercomPendingStageRouteTimeoutError,
|
|
54
65
|
type IntercomPendingStageRouteTimeoutFields,
|
|
55
66
|
} from "../pending-stage-route-timeout-error.js";
|
|
67
|
+
import { type IntercomHostedSessionTimeoutFields, IntercomHostedSessionTimeoutError } from "../hosted-session-timeout-error.js";
|
|
56
68
|
import { isSocketAnswering } from "./socket-liveness.js";
|
|
57
69
|
import { IntercomBrokerProtocolError, IntercomRoutingChangedError, IntercomRoutingUnavailableError } from "@bastani/atomic";
|
|
58
70
|
import {
|
|
59
71
|
BROKER_PROTOCOL,
|
|
60
72
|
type BrokerProtocolRange,
|
|
73
|
+
HOSTED_SESSIONS_PROTOCOL,
|
|
61
74
|
isBrokerProtocolRange,
|
|
62
75
|
LEGACY_BROKER_PROTOCOL,
|
|
63
76
|
protocolRangeOf,
|
|
@@ -168,6 +181,8 @@ export interface SendOptions {
|
|
|
168
181
|
expectedRecipientId?: string;
|
|
169
182
|
/** Broker-authorized recipient identity for an ask, delivered before its recipient can reply. */
|
|
170
183
|
onReplyTarget?: (sessionId: string) => void;
|
|
184
|
+
/** #4642: send as this session, which this connection hosts (`hostSessions`). */
|
|
185
|
+
hostedSender?: string;
|
|
171
186
|
}
|
|
172
187
|
|
|
173
188
|
export interface IntercomClientOptions {
|
|
@@ -267,6 +282,15 @@ export type {
|
|
|
267
282
|
IntercomReleasedReplyErrorFields,
|
|
268
283
|
SerializedIntercomReleasedReplyError,
|
|
269
284
|
} from "./released-reply-errors.js";
|
|
285
|
+
export {
|
|
286
|
+
HostedSessionRequestError,
|
|
287
|
+
IntercomHostedSessionError,
|
|
288
|
+
isHostedSessionRequestError,
|
|
289
|
+
isIntercomHostedSessionError,
|
|
290
|
+
isNotHostedSessionError,
|
|
291
|
+
NotHostedSessionError,
|
|
292
|
+
} from "./hosted-session-errors.js";
|
|
293
|
+
export type { IntercomHostedSessionErrorCode } from "./hosted-session-errors.js";
|
|
270
294
|
|
|
271
295
|
function readReleasedChildRefusal(value: unknown): ReleasedChildRefusal | undefined {
|
|
272
296
|
if (typeof value !== "object" || value === null) return undefined;
|
|
@@ -283,10 +307,10 @@ export interface SendResult {
|
|
|
283
307
|
reason?: string;
|
|
284
308
|
reasonCode?: DeliveryFailureReasonCode;
|
|
285
309
|
/**
|
|
286
|
-
* #4386: the typed refusal of a reply to a released subagent. #
|
|
287
|
-
* Its `code` is `reasonCode`.
|
|
310
|
+
* #4386: the typed refusal of a reply to a released subagent. #4642: of a hosted sender. #4639: why a subagent with
|
|
311
|
+
* no live session is gone. Its `code` is `reasonCode`.
|
|
288
312
|
*/
|
|
289
|
-
error?: IntercomReleasedReplyError | IntercomRecipientGoneError;
|
|
313
|
+
error?: IntercomReleasedReplyError | IntercomHostedSessionError | IntercomRecipientGoneError;
|
|
290
314
|
target?: string;
|
|
291
315
|
position?: number;
|
|
292
316
|
/** How a queued workflow target relates to the run's stages (#4359). */
|
|
@@ -466,6 +490,10 @@ export class IntercomClient extends EventEmitter {
|
|
|
466
490
|
reject: (error: Error) => void;
|
|
467
491
|
}>();
|
|
468
492
|
private pendingRestoringRecipientRequests = new Map<string, { resolve(): void; reject(error: Error): void }>();
|
|
493
|
+
private pendingHostedSessionRequests = new Map<
|
|
494
|
+
string,
|
|
495
|
+
{ resolve(sessions: readonly HostedSessionAssignment[]): void; reject(error: Error): void }
|
|
496
|
+
>();
|
|
469
497
|
private disconnecting = false;
|
|
470
498
|
private disconnectError: Error | null = null;
|
|
471
499
|
private healthCheck: { socket: net.Socket; result: Promise<Error | undefined> } | undefined;
|
|
@@ -523,6 +551,7 @@ export class IntercomClient extends EventEmitter {
|
|
|
523
551
|
for (const pending of this.pendingLists.values()) pending.reject(error);
|
|
524
552
|
for (const pending of this.pendingSupervisorAuthorizations.values()) pending.reject(error);
|
|
525
553
|
for (const pending of this.pendingRestoringRecipientRequests.values()) pending.reject(error);
|
|
554
|
+
for (const pending of this.pendingHostedSessionRequests.values()) pending.reject(error);
|
|
526
555
|
for (const pending of this.pendingPresence.values()) pending.reject(error);
|
|
527
556
|
for (const pending of this.pendingMemberships.values()) pending.reject(error);
|
|
528
557
|
for (const pending of this.pendingLiveWorkflowStageRoutes.values()) pending.reject(error);
|
|
@@ -533,6 +562,7 @@ export class IntercomClient extends EventEmitter {
|
|
|
533
562
|
this.pendingGroupLists.clear();
|
|
534
563
|
this.pendingSupervisorAuthorizations.clear();
|
|
535
564
|
this.pendingRestoringRecipientRequests.clear();
|
|
565
|
+
this.pendingHostedSessionRequests.clear();
|
|
536
566
|
this.pendingPresence.clear();
|
|
537
567
|
this.pendingMemberships.clear();
|
|
538
568
|
this.pendingLiveWorkflowStageRoutes.clear();
|
|
@@ -988,11 +1018,18 @@ export class IntercomClient extends EventEmitter {
|
|
|
988
1018
|
break;
|
|
989
1019
|
}
|
|
990
1020
|
case "message": {
|
|
991
|
-
const { from, message, channel } = brokerMessage;
|
|
992
|
-
if (
|
|
1021
|
+
const { from, message, channel, hostedRecipient } = brokerMessage;
|
|
1022
|
+
if (
|
|
1023
|
+
!isSessionInfo(from) ||
|
|
1024
|
+
!isMessage(message) ||
|
|
1025
|
+
(channel !== undefined && channel !== "supervisor") ||
|
|
1026
|
+
(hostedRecipient !== undefined && typeof hostedRecipient !== "string")
|
|
1027
|
+
) {
|
|
993
1028
|
throw new Error("Invalid message event");
|
|
994
1029
|
}
|
|
995
|
-
|
|
1030
|
+
// #4642: a message for a session this connection hosts goes to its own listeners, never to this session's.
|
|
1031
|
+
if (hostedRecipient !== undefined) this.emit("hosted_message", hostedRecipient, from, message, channel);
|
|
1032
|
+
else this.emit("message", from, message, channel);
|
|
996
1033
|
break;
|
|
997
1034
|
}
|
|
998
1035
|
case "pending_stage_message": {
|
|
@@ -1173,6 +1210,20 @@ export class IntercomClient extends EventEmitter {
|
|
|
1173
1210
|
this.emit("released_child_reply", notice);
|
|
1174
1211
|
break;
|
|
1175
1212
|
}
|
|
1213
|
+
case "hosted_sessions_ack": {
|
|
1214
|
+
const { requestId, refusal, sessions } = brokerMessage;
|
|
1215
|
+
const parsedRefusal = readHostedSessionRefusal(refusal as JsonWireValue | undefined);
|
|
1216
|
+
const assignments = sessions === undefined ? [] : readHostedSessionAssignments(sessions as JsonWireValue);
|
|
1217
|
+
if (typeof requestId !== "string" || (refusal !== undefined && parsedRefusal === undefined) || assignments === undefined) {
|
|
1218
|
+
throw new Error("Invalid hosted_sessions_ack message");
|
|
1219
|
+
}
|
|
1220
|
+
const pending = this.pendingHostedSessionRequests.get(requestId);
|
|
1221
|
+
if (!pending) return;
|
|
1222
|
+
this.pendingHostedSessionRequests.delete(requestId);
|
|
1223
|
+
if (parsedRefusal === undefined) pending.resolve(assignments);
|
|
1224
|
+
else pending.reject(hostedSessionErrorFor(parsedRefusal));
|
|
1225
|
+
break;
|
|
1226
|
+
}
|
|
1176
1227
|
case "released_children_ack": {
|
|
1177
1228
|
const { requestId, refusal } = brokerMessage;
|
|
1178
1229
|
const parsed = refusal === undefined ? undefined : readReleasedChildRefusal(refusal);
|
|
@@ -1211,7 +1262,9 @@ export class IntercomClient extends EventEmitter {
|
|
|
1211
1262
|
case "delivery_failed": {
|
|
1212
1263
|
const { messageId, attemptId, reason, reasonCode } = brokerMessage;
|
|
1213
1264
|
const wireError = brokerMessage.error as JsonWireValue | undefined;
|
|
1214
|
-
const
|
|
1265
|
+
const releasedReplyError = readSerializedIntercomReleasedReplyError(wireError);
|
|
1266
|
+
const hostedSessionError = readSerializedIntercomHostedSessionError(wireError);
|
|
1267
|
+
const error = releasedReplyError ?? hostedSessionError;
|
|
1215
1268
|
const wireRecipientError = brokerMessage.recipientError as JsonWireValue | undefined;
|
|
1216
1269
|
const recipientError = readSerializedIntercomRecipientGoneError(wireRecipientError);
|
|
1217
1270
|
if (
|
|
@@ -1230,7 +1283,8 @@ export class IntercomClient extends EventEmitter {
|
|
|
1230
1283
|
delivered: false,
|
|
1231
1284
|
reason,
|
|
1232
1285
|
...(reasonCode === undefined ? {} : { reasonCode }),
|
|
1233
|
-
...(
|
|
1286
|
+
...(releasedReplyError === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(releasedReplyError) }),
|
|
1287
|
+
...(hostedSessionError === undefined ? {} : { error: rehydrateIntercomHostedSessionError(hostedSessionError) }),
|
|
1234
1288
|
...(recipientError === undefined
|
|
1235
1289
|
? {}
|
|
1236
1290
|
: { reasonCode: recipientError.code, error: rehydrateIntercomRecipientGoneError(recipientError) }),
|
|
@@ -1673,14 +1727,97 @@ export class IntercomClient extends EventEmitter {
|
|
|
1673
1727
|
* with, which would end the connection with a protocol error over a frame type it does not know. Without a
|
|
1674
1728
|
* registration the request fails as it always did, as not connected.
|
|
1675
1729
|
*/
|
|
1676
|
-
private requireBrokerProtocol(feature: string): void {
|
|
1730
|
+
private requireBrokerProtocol(feature: string, requiredProtocol = VERIFIED_REGISTRATION_PROTOCOL): void {
|
|
1677
1731
|
const broker = this._brokerProtocol;
|
|
1678
|
-
if (this._sessionId === null || broker.max >=
|
|
1732
|
+
if (this._sessionId === null || broker.max >= requiredProtocol) return;
|
|
1679
1733
|
throw new IntercomBrokerProtocolError({
|
|
1680
1734
|
feature,
|
|
1681
1735
|
brokerProtocolMin: broker.min,
|
|
1682
1736
|
brokerProtocolMax: broker.max,
|
|
1683
|
-
requiredProtocol
|
|
1737
|
+
requiredProtocol,
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
/**
|
|
1742
|
+
* #4642: host sessions on this connection, in frames of at most 500. Each is listed and addressed like a connected
|
|
1743
|
+
* session; messages for it arrive as `hosted_message` (recipient id, sender, message, channel), and
|
|
1744
|
+
* `send(..., { hostedSender })` sends as it. They leave when `unhostSessions` removes them or this connection
|
|
1745
|
+
* closes. Every item is validated before any frame is sent: an invalid one fails the call with a
|
|
1746
|
+
* `HostedSessionRequestError` naming its key and hosts nothing from its frame or any later one. Resolves with each
|
|
1747
|
+
* key's broker id and, for an item with a live workflow-stage route the broker refused, the refusal code; the
|
|
1748
|
+
* session stays hosted and addressable by name. Needs a broker of protocol 3.
|
|
1749
|
+
*/
|
|
1750
|
+
async hostSessions(sessions: readonly HostedSessionFrameItem[]): Promise<HostedSessionAssignment[]> {
|
|
1751
|
+
this.requireBrokerProtocol("host_sessions", HOSTED_SESSIONS_PROTOCOL);
|
|
1752
|
+
const frames: HostedSessionFrameItem[][] = [];
|
|
1753
|
+
for (let start = 0; start < sessions.length; start += HOSTED_SESSION_FRAME_MAX) {
|
|
1754
|
+
const frame = sessions.slice(start, start + HOSTED_SESSION_FRAME_MAX);
|
|
1755
|
+
// Validated exactly as the broker reads it: what JSON keeps of the frame.
|
|
1756
|
+
const wire: JsonWireValue = JSON.parse(JSON.stringify(frame));
|
|
1757
|
+
const validation = validateHostSessionsFrame(wire);
|
|
1758
|
+
if (!validation.ok) throw hostedSessionErrorFor(validation.refusal);
|
|
1759
|
+
frames.push(frame);
|
|
1760
|
+
}
|
|
1761
|
+
const assigned: HostedSessionAssignment[] = [];
|
|
1762
|
+
for (const frame of frames) assigned.push(...(await this.hostedSessionRequest({ type: "host_sessions", sessions: frame })));
|
|
1763
|
+
return assigned;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
/**
|
|
1767
|
+
* #4642: remove sessions this connection hosts, in frames of at most 500. A frame naming a session this connection
|
|
1768
|
+
* does not host fails with `NotHostedSessionError` and removes nothing from that frame.
|
|
1769
|
+
*/
|
|
1770
|
+
async unhostSessions(sessionIds: readonly string[]): Promise<void> {
|
|
1771
|
+
this.requireBrokerProtocol("unhost_sessions", HOSTED_SESSIONS_PROTOCOL);
|
|
1772
|
+
if (sessionIds.length === 0) throw new HostedSessionRequestError("invalid_hosted_frame");
|
|
1773
|
+
for (let start = 0; start < sessionIds.length; start += HOSTED_SESSION_FRAME_MAX) {
|
|
1774
|
+
await this.hostedSessionRequest({
|
|
1775
|
+
type: "unhost_sessions",
|
|
1776
|
+
sessionIds: sessionIds.slice(start, start + HOSTED_SESSION_FRAME_MAX),
|
|
1777
|
+
});
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
/** Its callers are async: a connection that is not active rejects their promise. */
|
|
1782
|
+
private hostedSessionRequest(frame: Record<string, unknown>): Promise<HostedSessionAssignment[]> {
|
|
1783
|
+
const socket = this.requireActiveSocket();
|
|
1784
|
+
const requestId = randomUUID();
|
|
1785
|
+
const startedAt = performance.now();
|
|
1786
|
+
return new Promise((resolve, reject) => {
|
|
1787
|
+
// Every other way the request settles clears this timer, so it only ever finds the request still pending.
|
|
1788
|
+
const timeout = setTimeout(() => {
|
|
1789
|
+
this.pendingHostedSessionRequests.delete(requestId);
|
|
1790
|
+
const timedOut: IntercomHostedSessionTimeoutFields = {
|
|
1791
|
+
requestType: frame.type === "unhost_sessions" ? "unhost_sessions" : "host_sessions",
|
|
1792
|
+
sessionCount: Array.isArray(frame.sessions) ? frame.sessions.length : Array.isArray(frame.sessionIds) ? frame.sessionIds.length : 0,
|
|
1793
|
+
timeoutMs: RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS,
|
|
1794
|
+
elapsedMs: Math.round(performance.now() - startedAt),
|
|
1795
|
+
};
|
|
1796
|
+
void this.requestTimeout(socket, new IntercomHostedSessionTimeoutError(timedOut)).then((error) =>
|
|
1797
|
+
reject(
|
|
1798
|
+
error instanceof IntercomBrokerTimeoutError && !(error instanceof IntercomHostedSessionTimeoutError)
|
|
1799
|
+
? new IntercomHostedSessionTimeoutError(timedOut, { cause: error })
|
|
1800
|
+
: error,
|
|
1801
|
+
),
|
|
1802
|
+
);
|
|
1803
|
+
}, RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS);
|
|
1804
|
+
this.pendingHostedSessionRequests.set(requestId, {
|
|
1805
|
+
resolve: (sessions) => {
|
|
1806
|
+
clearTimeout(timeout);
|
|
1807
|
+
resolve([...sessions]);
|
|
1808
|
+
},
|
|
1809
|
+
reject: (error) => {
|
|
1810
|
+
clearTimeout(timeout);
|
|
1811
|
+
reject(error);
|
|
1812
|
+
},
|
|
1813
|
+
});
|
|
1814
|
+
try {
|
|
1815
|
+
writeMessage(socket, { ...frame, requestId });
|
|
1816
|
+
} catch (error) {
|
|
1817
|
+
clearTimeout(timeout);
|
|
1818
|
+
this.pendingHostedSessionRequests.delete(requestId);
|
|
1819
|
+
reject(toError(error));
|
|
1820
|
+
}
|
|
1684
1821
|
});
|
|
1685
1822
|
}
|
|
1686
1823
|
|
|
@@ -2010,6 +2147,8 @@ export class IntercomClient extends EventEmitter {
|
|
|
2010
2147
|
...(options.onReplyTarget === undefined ? {} : { resolveReplyTarget: true as const }),
|
|
2011
2148
|
// #3760: this client understands `send_held`, so the broker may hold the send for a subagent being restored.
|
|
2012
2149
|
...(type === "send" ? { awaitRestoringRecipient: true as const } : {}),
|
|
2150
|
+
// The frame is JSON: an undefined sender is left out of it.
|
|
2151
|
+
hostedSender: options.hostedSender,
|
|
2013
2152
|
message,
|
|
2014
2153
|
attemptId: acquired.attempt.attemptId,
|
|
2015
2154
|
...extra,
|
|
@@ -7,6 +7,7 @@ const DELIVERY_FAILURE_REASON_CODES: ReadonlySet<string> = new Set<DeliveryFailu
|
|
|
7
7
|
"recipient_parked",
|
|
8
8
|
"released_reply_answered",
|
|
9
9
|
"released_reply_in_flight",
|
|
10
|
+
"not_hosted_by_connection",
|
|
10
11
|
]);
|
|
11
12
|
|
|
12
13
|
export function isDeliveryFailureReasonCode(value: string): value is DeliveryFailureReasonCode {
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
type IntercomRecipientGoneError,
|
|
7
7
|
SUBAGENT_ENDED_OUTCOMES,
|
|
8
8
|
type SubagentEndedOutcome,
|
|
9
|
+
StageRecipientReleasedError,
|
|
9
10
|
SubagentRecipientDisconnectedError,
|
|
10
11
|
subagentRecipientEnded,
|
|
11
12
|
} from "./recipient-gone-errors.js";
|
|
@@ -119,6 +120,7 @@ export function validateEndedChildrenFrame(
|
|
|
119
120
|
|
|
120
121
|
type Verdict =
|
|
121
122
|
| { readonly kind: "ended"; readonly outcome: SubagentEndedOutcome; readonly childId?: string }
|
|
123
|
+
| { readonly kind: "stage_released" }
|
|
122
124
|
| { readonly kind: "disconnected" };
|
|
123
125
|
|
|
124
126
|
/** The verdict of a subagent nobody said anything about before its wait ended. */
|
|
@@ -245,6 +247,25 @@ export class DepartedChildren {
|
|
|
245
247
|
return { refused, evicted };
|
|
246
248
|
}
|
|
247
249
|
|
|
250
|
+
/**
|
|
251
|
+
* #4642: a released workflow stage's hosted peer left: its host connection removed it or closed. Sends to its name,
|
|
252
|
+
* id or return address are refused at once with a {@link StageRecipientReleasedError}, until it is hosted again.
|
|
253
|
+
*/
|
|
254
|
+
markStageReleased(
|
|
255
|
+
ownerSessionId: string,
|
|
256
|
+
child: Omit<EndedChildMark, "outcome" | "childId">,
|
|
257
|
+
): { readonly refused: HeldSendRefusal[]; readonly evicted: HeldSend[] } {
|
|
258
|
+
const entry = this.entry(ownerSessionId, child.childName, child.group, child.aliases);
|
|
259
|
+
this.disarm(entry.departure);
|
|
260
|
+
entry.departure.verdict = { kind: "stage_released" };
|
|
261
|
+
return { refused: this.refuseHeld(entry.departure, entry.departure.verdict), evicted: entry.evicted };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Whether `target`, to a sender that may reach it, names a released stage whose hosted peer is gone (#4642). */
|
|
265
|
+
isReleasedStage(target: string, sender: { readonly id: string; readonly info: SessionInfo }): boolean {
|
|
266
|
+
return this.visible(target, sender)?.verdict?.kind === "stage_released";
|
|
267
|
+
}
|
|
268
|
+
|
|
248
269
|
/** Decide a send that found no live recipient. `canHold` is false for a client that cannot wait for a verdict. */
|
|
249
270
|
admit(
|
|
250
271
|
target: string,
|
|
@@ -406,6 +427,8 @@ export class DepartedChildren {
|
|
|
406
427
|
}
|
|
407
428
|
|
|
408
429
|
private errorFor(departure: Departure, verdict: Verdict, target: string): IntercomRecipientGoneError {
|
|
430
|
+
if (verdict.kind === "stage_released")
|
|
431
|
+
return new StageRecipientReleasedError({ target, childName: departure.childName });
|
|
409
432
|
if (verdict.kind !== "ended") return this.disconnectedError(departure, target);
|
|
410
433
|
return subagentRecipientEnded(verdict.outcome, {
|
|
411
434
|
target,
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import type { HostedSessionRefusal, HostedSessionRefusalCode } from "../types.js";
|
|
2
|
+
import type { JsonWireValue } from "./framing.js";
|
|
3
|
+
import { isWireObject } from "./hosted-sessions.js";
|
|
4
|
+
import { rehydrateErrorCause, type SerializedErrorCause, serializeErrorCause } from "./released-child-errors.js";
|
|
5
|
+
import { readCause } from "./released-reply-errors.js";
|
|
6
|
+
|
|
7
|
+
export type IntercomHostedSessionErrorCode = HostedSessionRefusalCode;
|
|
8
|
+
|
|
9
|
+
export const HOSTED_SESSION_ERROR_CODES: readonly IntercomHostedSessionErrorCode[] = [
|
|
10
|
+
"invalid_hosted_frame",
|
|
11
|
+
"invalid_hosted_session",
|
|
12
|
+
"not_hosted_by_connection",
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
const CODES: ReadonlySet<string> = new Set(HOSTED_SESSION_ERROR_CODES);
|
|
16
|
+
|
|
17
|
+
export function isHostedSessionErrorCode(value: string): value is IntercomHostedSessionErrorCode {
|
|
18
|
+
return CODES.has(value);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The item a refusal names: the host's key for a session being hosted, or the broker id of a hosted session. */
|
|
22
|
+
export interface IntercomHostedSessionErrorFields {
|
|
23
|
+
readonly key?: string;
|
|
24
|
+
readonly sessionId?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const HINTS: Readonly<Record<IntercomHostedSessionErrorCode, string>> = {
|
|
28
|
+
invalid_hosted_frame:
|
|
29
|
+
"Send between 1 and 500 sessions per frame, each under a distinct non-empty key, or 1 to 500 session ids to remove.",
|
|
30
|
+
invalid_hosted_session:
|
|
31
|
+
"Give each hosted session a non-empty name and a valid agent registration (cwd, model, pid and timestamps).",
|
|
32
|
+
not_hosted_by_connection:
|
|
33
|
+
"Only the connection that hosts a session may send as it or remove it; host the session again after a reconnect.",
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const BASE_NAME = "IntercomHostedSessionError";
|
|
37
|
+
const REQUEST_NAME = "HostedSessionRequestError";
|
|
38
|
+
const NOT_HOSTED_NAME = "NotHostedSessionError";
|
|
39
|
+
|
|
40
|
+
/** #4642: base of the broker's refusals of hosted-session requests. None is retryable as sent. */
|
|
41
|
+
export class IntercomHostedSessionError extends Error {
|
|
42
|
+
override readonly name: string = BASE_NAME;
|
|
43
|
+
readonly code: IntercomHostedSessionErrorCode;
|
|
44
|
+
readonly hint: string;
|
|
45
|
+
readonly retryable = false;
|
|
46
|
+
readonly key?: string;
|
|
47
|
+
readonly sessionId?: string;
|
|
48
|
+
|
|
49
|
+
constructor(
|
|
50
|
+
code: IntercomHostedSessionErrorCode,
|
|
51
|
+
fields: IntercomHostedSessionErrorFields = {},
|
|
52
|
+
options?: { readonly cause?: Error },
|
|
53
|
+
) {
|
|
54
|
+
const subject =
|
|
55
|
+
fields.key !== undefined
|
|
56
|
+
? `hosted session ${JSON.stringify(fields.key)}`
|
|
57
|
+
: fields.sessionId !== undefined
|
|
58
|
+
? `session ${JSON.stringify(fields.sessionId)}`
|
|
59
|
+
: "request";
|
|
60
|
+
super(`Hosted-session request refused: ${subject} (${code}). ${HINTS[code]}`, options);
|
|
61
|
+
this.code = code;
|
|
62
|
+
this.hint = HINTS[code];
|
|
63
|
+
if (fields.key !== undefined) this.key = fields.key;
|
|
64
|
+
if (fields.sessionId !== undefined) this.sessionId = fields.sessionId;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A `host_sessions` or `unhost_sessions` frame, or one of its items, is malformed; nothing in it took effect. */
|
|
69
|
+
export class HostedSessionRequestError extends IntercomHostedSessionError {
|
|
70
|
+
override readonly name = REQUEST_NAME;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The session named to send as, or to remove, is not hosted by this connection. */
|
|
74
|
+
export class NotHostedSessionError extends IntercomHostedSessionError {
|
|
75
|
+
override readonly name = NOT_HOSTED_NAME;
|
|
76
|
+
constructor(fields: IntercomHostedSessionErrorFields, options?: { readonly cause?: Error }) {
|
|
77
|
+
super("not_hosted_by_connection", fields, options);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const NAMES: ReadonlySet<string> = new Set([BASE_NAME, REQUEST_NAME, NOT_HOSTED_NAME]);
|
|
82
|
+
const REQUEST_NAMES: ReadonlySet<string> = new Set([REQUEST_NAME]);
|
|
83
|
+
const NOT_HOSTED_NAMES: ReadonlySet<string> = new Set([NOT_HOSTED_NAME]);
|
|
84
|
+
|
|
85
|
+
function hasStructure(error: Error, names: ReadonlySet<string>): boolean {
|
|
86
|
+
const code = (error as Error & { readonly code?: string | number }).code;
|
|
87
|
+
return names.has(error.name) && typeof code === "string" && isHostedSessionErrorCode(code);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function isIntercomHostedSessionError(error: Error): error is IntercomHostedSessionError {
|
|
91
|
+
return error instanceof IntercomHostedSessionError || hasStructure(error, NAMES);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function isHostedSessionRequestError(error: Error): error is HostedSessionRequestError {
|
|
95
|
+
return error instanceof HostedSessionRequestError || hasStructure(error, REQUEST_NAMES);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function isNotHostedSessionError(error: Error): error is NotHostedSessionError {
|
|
99
|
+
return error instanceof NotHostedSessionError || hasStructure(error, NOT_HOSTED_NAMES);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function fieldsOf(refusal: HostedSessionRefusal | IntercomHostedSessionErrorFields): IntercomHostedSessionErrorFields {
|
|
103
|
+
return {
|
|
104
|
+
...(refusal.key === undefined ? {} : { key: refusal.key }),
|
|
105
|
+
...(refusal.sessionId === undefined ? {} : { sessionId: refusal.sessionId }),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The typed error of a refusal read off the wire. */
|
|
110
|
+
export function hostedSessionErrorFor(
|
|
111
|
+
refusal: HostedSessionRefusal,
|
|
112
|
+
options?: { readonly cause?: Error },
|
|
113
|
+
): IntercomHostedSessionError {
|
|
114
|
+
return refusal.code === "not_hosted_by_connection"
|
|
115
|
+
? new NotHostedSessionError(fieldsOf(refusal), options)
|
|
116
|
+
: new HostedSessionRequestError(refusal.code, fieldsOf(refusal), options);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface SerializedIntercomHostedSessionError {
|
|
120
|
+
readonly name: string;
|
|
121
|
+
readonly code: IntercomHostedSessionErrorCode;
|
|
122
|
+
readonly message: string;
|
|
123
|
+
readonly hint: string;
|
|
124
|
+
readonly retryable: false;
|
|
125
|
+
readonly fields: IntercomHostedSessionErrorFields;
|
|
126
|
+
readonly cause?: SerializedErrorCause;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function serializeIntercomHostedSessionError(
|
|
130
|
+
error: IntercomHostedSessionError,
|
|
131
|
+
): SerializedIntercomHostedSessionError {
|
|
132
|
+
return {
|
|
133
|
+
name: error.name,
|
|
134
|
+
code: error.code,
|
|
135
|
+
message: error.message,
|
|
136
|
+
hint: error.hint,
|
|
137
|
+
retryable: false,
|
|
138
|
+
fields: fieldsOf(error),
|
|
139
|
+
...(error.cause instanceof Error ? { cause: serializeErrorCause(error.cause, 1) } : {}),
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The same class on this side of the boundary; an unknown name keeps its name and code on the family base. */
|
|
144
|
+
export function rehydrateIntercomHostedSessionError(
|
|
145
|
+
serialized: SerializedIntercomHostedSessionError,
|
|
146
|
+
): IntercomHostedSessionError {
|
|
147
|
+
const options = serialized.cause === undefined ? undefined : { cause: rehydrateErrorCause(serialized.cause, 1) };
|
|
148
|
+
if (serialized.name === NOT_HOSTED_NAME) return new NotHostedSessionError(serialized.fields, options);
|
|
149
|
+
if (serialized.name === REQUEST_NAME)
|
|
150
|
+
return new HostedSessionRequestError(serialized.code, serialized.fields, options);
|
|
151
|
+
const error = new IntercomHostedSessionError(serialized.code, serialized.fields, options);
|
|
152
|
+
Object.defineProperty(error, "name", { value: serialized.name });
|
|
153
|
+
return error;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Validate a refusal read off the wire; `undefined` when it is not one. */
|
|
157
|
+
export function readHostedSessionRefusal(value: JsonWireValue | undefined): HostedSessionRefusal | undefined {
|
|
158
|
+
if (!isWireObject(value)) return undefined;
|
|
159
|
+
const { code, key, sessionId } = value;
|
|
160
|
+
if (typeof code !== "string" || !isHostedSessionErrorCode(code)) return undefined;
|
|
161
|
+
if ((key !== undefined && typeof key !== "string") || (sessionId !== undefined && typeof sessionId !== "string")) {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
return { code, ...(key === undefined ? {} : { key }), ...(sessionId === undefined ? {} : { sessionId }) };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Validate a serialized hosted-session error read off the wire; `undefined` when it is not one. */
|
|
168
|
+
export function readSerializedIntercomHostedSessionError(
|
|
169
|
+
value: JsonWireValue | undefined,
|
|
170
|
+
): SerializedIntercomHostedSessionError | undefined {
|
|
171
|
+
if (!isWireObject(value)) return undefined;
|
|
172
|
+
const { name, code, message, hint, retryable, fields } = value;
|
|
173
|
+
if (typeof name !== "string" || typeof code !== "string" || !isHostedSessionErrorCode(code)) return undefined;
|
|
174
|
+
if (typeof message !== "string" || typeof hint !== "string" || retryable !== false) return undefined;
|
|
175
|
+
const refusal = isWireObject(fields) ? readHostedSessionRefusal({ ...fields, code }) : undefined;
|
|
176
|
+
if (refusal === undefined) return undefined;
|
|
177
|
+
const cause = readCause(value.cause, 1);
|
|
178
|
+
if (cause === false) return undefined;
|
|
179
|
+
return {
|
|
180
|
+
name,
|
|
181
|
+
code,
|
|
182
|
+
message,
|
|
183
|
+
hint,
|
|
184
|
+
retryable: false,
|
|
185
|
+
fields: fieldsOf(refusal),
|
|
186
|
+
...(cause === undefined ? {} : { cause }),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { isLiveWorkflowStageRouteRefusalCode } from "../live-route-refusal.js";
|
|
2
|
+
import type { HostedSessionAssignment, HostedSessionRefusal, SessionInfo } from "../types.js";
|
|
3
|
+
import { isSessionRegistration } from "./client-message-validation.js";
|
|
4
|
+
import type { JsonWireValue } from "./framing.js";
|
|
5
|
+
|
|
6
|
+
/** Sessions per `host_sessions` frame, and session ids per `unhost_sessions` frame (#4642). */
|
|
7
|
+
export const HOSTED_SESSION_FRAME_MAX = 500;
|
|
8
|
+
|
|
9
|
+
export interface ParsedHostedSession {
|
|
10
|
+
readonly key: string;
|
|
11
|
+
readonly session: Omit<SessionInfo, "id">;
|
|
12
|
+
readonly returnAddress?: string;
|
|
13
|
+
readonly liveRoute?: { readonly runId: string; readonly stageKeys: readonly string[]; readonly capability: string };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type HostedSessionFrameValidation =
|
|
17
|
+
| { readonly ok: true; readonly sessions: readonly ParsedHostedSession[] }
|
|
18
|
+
| { readonly ok: false; readonly refusal: HostedSessionRefusal };
|
|
19
|
+
|
|
20
|
+
export type UnhostSessionsFrameValidation =
|
|
21
|
+
| { readonly ok: true; readonly sessionIds: readonly string[] }
|
|
22
|
+
| { readonly ok: false; readonly refusal: HostedSessionRefusal };
|
|
23
|
+
|
|
24
|
+
type WireObject = { readonly [key: string]: JsonWireValue };
|
|
25
|
+
|
|
26
|
+
export const isWireObject = (value: JsonWireValue | undefined): value is WireObject =>
|
|
27
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
28
|
+
|
|
29
|
+
const isNonEmptyString = (value: JsonWireValue | undefined): value is string =>
|
|
30
|
+
typeof value === "string" && value.trim().length > 0;
|
|
31
|
+
|
|
32
|
+
function parseLiveRoute(value: JsonWireValue | undefined): ParsedHostedSession["liveRoute"] | false {
|
|
33
|
+
if (!isWireObject(value)) return false;
|
|
34
|
+
const { runId, stageKeys, capability } = value;
|
|
35
|
+
if (!isNonEmptyString(runId) || !isNonEmptyString(capability) || !Array.isArray(stageKeys)) return false;
|
|
36
|
+
if (stageKeys.length < 1 || stageKeys.length > 2 || !stageKeys.every(isNonEmptyString)) return false;
|
|
37
|
+
return { runId, stageKeys: stageKeys as string[], capability };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Validate one `host_sessions` frame as a whole, before anything is hosted: 1 to 500 items under distinct keys, each a
|
|
42
|
+
* named agent registration with an optional return address and live workflow-stage route. The first invalid item
|
|
43
|
+
* refuses the frame.
|
|
44
|
+
*/
|
|
45
|
+
export function validateHostSessionsFrame(sessions: JsonWireValue | undefined): HostedSessionFrameValidation {
|
|
46
|
+
if (!Array.isArray(sessions) || sessions.length === 0 || sessions.length > HOSTED_SESSION_FRAME_MAX) {
|
|
47
|
+
return { ok: false, refusal: { code: "invalid_hosted_frame" } };
|
|
48
|
+
}
|
|
49
|
+
const keys = new Set<string>();
|
|
50
|
+
const parsed: ParsedHostedSession[] = [];
|
|
51
|
+
for (const item of sessions) {
|
|
52
|
+
if (!isWireObject(item) || !isNonEmptyString(item.key) || keys.has(item.key)) {
|
|
53
|
+
return {
|
|
54
|
+
ok: false,
|
|
55
|
+
refusal:
|
|
56
|
+
isWireObject(item) && typeof item.key === "string"
|
|
57
|
+
? { code: "invalid_hosted_frame", key: item.key }
|
|
58
|
+
: { code: "invalid_hosted_frame" },
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const key = item.key;
|
|
62
|
+
keys.add(key);
|
|
63
|
+
const invalid = { ok: false, refusal: { code: "invalid_hosted_session", key } } as const;
|
|
64
|
+
const { session, returnAddress } = item;
|
|
65
|
+
if (
|
|
66
|
+
!isSessionRegistration(session) ||
|
|
67
|
+
!isNonEmptyString(session.name) ||
|
|
68
|
+
session.recipientPurpose === "control"
|
|
69
|
+
) {
|
|
70
|
+
return invalid;
|
|
71
|
+
}
|
|
72
|
+
if (returnAddress !== undefined && !isNonEmptyString(returnAddress)) return invalid;
|
|
73
|
+
const liveRoute = item.liveRoute === undefined ? undefined : parseLiveRoute(item.liveRoute);
|
|
74
|
+
if (liveRoute === false) return invalid;
|
|
75
|
+
parsed.push({
|
|
76
|
+
key,
|
|
77
|
+
session,
|
|
78
|
+
...(returnAddress === undefined ? {} : { returnAddress }),
|
|
79
|
+
...(liveRoute === undefined ? {} : { liveRoute }),
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return { ok: true, sessions: parsed };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Validate one `unhost_sessions` frame: 1 to 500 session ids. */
|
|
86
|
+
export function validateUnhostSessionsFrame(sessionIds: JsonWireValue | undefined): UnhostSessionsFrameValidation {
|
|
87
|
+
if (
|
|
88
|
+
!Array.isArray(sessionIds) ||
|
|
89
|
+
sessionIds.length === 0 ||
|
|
90
|
+
sessionIds.length > HOSTED_SESSION_FRAME_MAX ||
|
|
91
|
+
!sessionIds.every(isNonEmptyString)
|
|
92
|
+
) {
|
|
93
|
+
return { ok: false, refusal: { code: "invalid_hosted_frame" } };
|
|
94
|
+
}
|
|
95
|
+
return { ok: true, sessionIds: sessionIds as string[] };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Validate the assignments of a `hosted_sessions_ack` read off the wire; `undefined` when they are not. */
|
|
99
|
+
export function readHostedSessionAssignments(value: JsonWireValue | undefined): HostedSessionAssignment[] | undefined {
|
|
100
|
+
if (!Array.isArray(value)) return undefined;
|
|
101
|
+
const assignments: HostedSessionAssignment[] = [];
|
|
102
|
+
for (const item of value) {
|
|
103
|
+
if (!isWireObject(item) || typeof item.key !== "string" || !isNonEmptyString(item.sessionId)) return undefined;
|
|
104
|
+
const { liveRouteRefusal } = item;
|
|
105
|
+
if (liveRouteRefusal !== undefined && !isLiveWorkflowStageRouteRefusalCode(liveRouteRefusal)) return undefined;
|
|
106
|
+
assignments.push({
|
|
107
|
+
key: item.key,
|
|
108
|
+
sessionId: item.sessionId,
|
|
109
|
+
...(liveRouteRefusal === undefined ? {} : { liveRouteRefusal }),
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return assignments;
|
|
113
|
+
}
|
|
@@ -65,6 +65,7 @@ import {
|
|
|
65
65
|
import {
|
|
66
66
|
type BrokerConnectedSession,
|
|
67
67
|
deliveryTargetIdentity,
|
|
68
|
+
messageFrameFor,
|
|
68
69
|
type RemoteSendRequest,
|
|
69
70
|
type SendClientMessage,
|
|
70
71
|
senderGroupIdentity,
|
|
@@ -524,7 +525,10 @@ export class MultiNodeRouter {
|
|
|
524
525
|
const claims = [...this.inflight.values()].filter((inflight) => inflight.session === session);
|
|
525
526
|
for (const inflight of claims) this.inflight.delete(inflight.row.messageId);
|
|
526
527
|
for (const waiter of [...this.waiters.values()]) {
|
|
527
|
-
|
|
528
|
+
// #4642: a hosted session shares its host's socket; only its own sends end with it.
|
|
529
|
+
const sentBySession =
|
|
530
|
+
session.hostedBy === undefined ? waiter.socket === session.socket : waiter.senderSessionId === session.info.id;
|
|
531
|
+
if (sentBySession) this.dropWaiter(waiter);
|
|
528
532
|
}
|
|
529
533
|
const holds = [...this.holds.values()].filter((hold) => hold.senderId === session.info.id);
|
|
530
534
|
for (const hold of holds) {
|
|
@@ -1701,7 +1705,8 @@ export class MultiNodeRouter {
|
|
|
1701
1705
|
}
|
|
1702
1706
|
const inflight: Inflight = { claim, row, session, identity };
|
|
1703
1707
|
this.inflight.set(row.messageId, inflight);
|
|
1704
|
-
|
|
1708
|
+
const delivery = messageFrameFor(session, frame.from, frame.message, frame.channel);
|
|
1709
|
+
this.host.writeConfirmed(session.socket, delivery, (written) => {
|
|
1705
1710
|
if (this.inflight.get(row.messageId) !== inflight) return;
|
|
1706
1711
|
if (!written) {
|
|
1707
1712
|
this.inflight.delete(row.messageId);
|
|
@@ -22,7 +22,8 @@ function broadcastMembershipChange(
|
|
|
22
22
|
if (!isAgentRecipient(session.info)) return;
|
|
23
23
|
const previousInfo = { ...session.info, groups: [...previous], group: previous.values().next().value };
|
|
24
24
|
for (const [id, peer] of sessions) {
|
|
25
|
-
|
|
25
|
+
// #4642: a hosted session shares its host's socket and needs no copy of its own.
|
|
26
|
+
if (id === session.info.id || peer.hostedBy !== undefined) continue;
|
|
26
27
|
const sharedBefore = sessionsShareGroup(previousInfo, peer.info);
|
|
27
28
|
const sharedAfter = sessionsShareGroup(session.info, peer.info);
|
|
28
29
|
if (!sharedBefore && sharedAfter) {
|