negotium 0.19.2 → 0.20.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.
- package/dist/agent-helpers.js +1146 -212
- package/dist/agent-helpers.js.map +27 -19
- package/dist/background-bash.js.map +1 -1
- package/dist/browser-runtime.js.map +1 -1
- package/dist/{chunk-kkftbxh2.js → chunk-7he9nzfa.js} +1 -1
- package/dist/{chunk-55dd0xw7.js → chunk-ad6xqvqy.js} +2 -2
- package/dist/{chunk-55dd0xw7.js.map → chunk-ad6xqvqy.js.map} +2 -2
- package/dist/{chunk-exqz8bez.js → chunk-hh3f0yr7.js} +3 -3
- package/dist/{chunk-exqz8bez.js.map → chunk-hh3f0yr7.js.map} +2 -2
- package/dist/{chunk-aqqmzmft.js → chunk-nm59q3em.js} +1 -1
- package/dist/{chunk-cv7vdsrn.js → chunk-w3c6fc0p.js} +286 -9
- package/dist/{chunk-cv7vdsrn.js.map → chunk-w3c6fc0p.js.map} +10 -7
- package/dist/hosted-agent.js +290 -12
- package/dist/hosted-agent.js.map +10 -7
- package/dist/main.js +4599 -2724
- package/dist/main.js.map +49 -38
- package/dist/mcp-factories.js +1166 -162
- package/dist/mcp-factories.js.map +27 -19
- package/dist/media.js.map +1 -1
- package/dist/prompts.js.map +1 -1
- package/dist/query-runtime.js.map +3 -3
- package/dist/registry.js +3 -3
- package/dist/rollout.js +2 -2
- package/dist/runtime/src/agents/explicit-agent-switch.ts +101 -0
- package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +126 -43
- package/dist/runtime/src/agents/public-helpers.ts +5 -0
- package/dist/runtime/src/agents/self-config-core.ts +28 -58
- package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +34 -8
- package/dist/runtime/src/index.ts +75 -0
- package/dist/runtime/src/mcp/peer-bridge.ts +6 -1
- package/dist/runtime/src/mcp/runtime-spec.ts +145 -10
- package/dist/runtime/src/mcp/session-comm/actor-policy.ts +87 -0
- package/dist/runtime/src/mcp/session-comm/context.ts +42 -1
- package/dist/runtime/src/mcp/session-comm/default-host.ts +178 -2
- package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
- package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
- package/dist/runtime/src/mcp/session-comm/peer-forward.ts +78 -3
- package/dist/runtime/src/mcp/session-comm/server.ts +167 -4
- package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +7 -0
- package/dist/runtime/src/mcp/session-comm/topics.ts +32 -10
- package/dist/runtime/src/mcp-runtime-host.ts +2 -1
- package/dist/runtime/src/node-host.ts +26 -0
- package/dist/runtime/src/platform/mcp-config.ts +56 -2
- package/dist/runtime/src/query/active-rooms.ts +6 -0
- package/dist/runtime/src/runtime/actor-topic-reach.ts +85 -0
- package/dist/runtime/src/runtime/actor-topic-scope.ts +175 -0
- package/dist/runtime/src/runtime/ask-callbacks.ts +73 -20
- package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
- package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
- package/dist/runtime/src/runtime/remote-session-inbox.ts +476 -0
- package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +156 -0
- package/dist/runtime/src/runtime/turn-runner.ts +157 -33
- package/dist/runtime/src/runtime-gateway.ts +20 -0
- package/dist/runtime/src/storage/api-topics.ts +22 -3
- package/dist/runtime/src/storage/remote-session.ts +526 -0
- package/dist/runtime/src/storage/runtime-turn-requests.ts +75 -2
- package/dist/runtime/src/topics/derive.ts +3 -0
- package/dist/runtime/src/types/api.ts +6 -0
- package/dist/runtime/src/types.ts +42 -0
- package/dist/runtime/src/version.ts +1 -1
- package/dist/runtime-gateway.js.map +2 -2
- package/dist/runtime-helpers.js.map +1 -1
- package/dist/storage.js +16 -4
- package/dist/storage.js.map +4 -4
- package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
- package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +12 -2
- package/dist/types/packages/core/src/agents/public-helpers.d.ts +1 -0
- package/dist/types/packages/core/src/agents/self-config-core.d.ts +15 -1
- package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +6 -1
- package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +69 -2
- package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +17 -1
- package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
- package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +23 -2
- package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +6 -0
- package/dist/types/packages/core/src/platform/mcp-config.d.ts +10 -1
- package/dist/types/packages/core/src/query/active-rooms.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +49 -0
- package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +91 -0
- package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +8 -2
- package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
- package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +83 -0
- package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/turn-runner.d.ts +22 -3
- package/dist/types/packages/core/src/runtime-gateway.d.ts +20 -0
- package/dist/types/packages/core/src/storage/api-topics.d.ts +3 -0
- package/dist/types/packages/core/src/storage/remote-session.d.ts +135 -0
- package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +12 -1
- package/dist/types/packages/core/src/topics/derive.d.ts +2 -0
- package/dist/types/packages/core/src/types/api.d.ts +6 -0
- package/dist/types/packages/core/src/types.d.ts +40 -0
- package/dist/types/packages/core/src/version.d.ts +1 -1
- package/dist/vault.js.map +1 -1
- package/package.json +1 -1
- /package/dist/{chunk-kkftbxh2.js.map → chunk-7he9nzfa.js.map} +0 -0
- /package/dist/{chunk-aqqmzmft.js.map → chunk-nm59q3em.js.map} +0 -0
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node → hub client for remote (`node/topic`) session-comm on the `otium`
|
|
3
|
+
* surface.
|
|
4
|
+
*
|
|
5
|
+
* The node never decides who may reach what across nodes. It presents the
|
|
6
|
+
* turn's hub-issued capability (`RemoteSessionGrant.capability`, an opaque
|
|
7
|
+
* `rsc1.` bearer) to the hub, names the target as the person typed it, and
|
|
8
|
+
* the hub — the only party holding the signing key and the membership store —
|
|
9
|
+
* verifies the capability, re-checks the person's membership of the origin
|
|
10
|
+
* and target rooms at call time, and forwards into the target node over the
|
|
11
|
+
* Runtime Gateway. No actor id travels in these bodies: the hub recovers the
|
|
12
|
+
* actor from the capability.
|
|
13
|
+
*
|
|
14
|
+
* Wire contract (mirrored in `docs/RUNTIME-GATEWAY-CONTRACT.md`):
|
|
15
|
+
* POST {hubUrl}/api/v1/session-comm/remote/{sessions|peek|tell|ask|abort}
|
|
16
|
+
* Authorization: Bearer <capability> Content-Type: application/json
|
|
17
|
+
* Success: exactly `{ ok:true, v:1, ... }` (a 2xx with any other body is a
|
|
18
|
+
* protocol failure, never a success — a proxy's 200 error page must not
|
|
19
|
+
* settle anything). Errors: { ok:false, v:1, error, code? } with
|
|
20
|
+
* 400/401/404/409/413/429/502/503; `409 code:"in_progress"` means the hub
|
|
21
|
+
* is still working on the same requestId and is retried like a transport
|
|
22
|
+
* failure. Every POST carries a bearer and therefore never follows a
|
|
23
|
+
* redirect (`redirect: "error"`).
|
|
24
|
+
*/
|
|
25
|
+
import { logger } from "#platform/logger";
|
|
26
|
+
import type { RemoteSessionGrant } from "#types";
|
|
27
|
+
|
|
28
|
+
export const REMOTE_SESSION_HUB_BASE_PATH = "/api/v1/session-comm/remote";
|
|
29
|
+
export const REMOTE_SESSION_PROTOCOL_VERSION = 1 as const;
|
|
30
|
+
/** One attempt's wall clock, generous because the hub itself calls a node. */
|
|
31
|
+
const HUB_TIMEOUT_MS = 15_000;
|
|
32
|
+
/** Same `requestId` again after a transport failure: the hub claims it once. */
|
|
33
|
+
const HUB_RETRY_DELAYS_MS = [50, 150] as const;
|
|
34
|
+
/** The hub's "same requestId still in flight" verdict: retry, do not conclude. */
|
|
35
|
+
export const HUB_IN_PROGRESS_CODE = "in_progress";
|
|
36
|
+
|
|
37
|
+
export interface RemoteSessionTarget {
|
|
38
|
+
node: string;
|
|
39
|
+
topic: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface RemoteSessionFromLabel {
|
|
43
|
+
/** `kind:title` of the origin room, as `session-comm` labels senders. */
|
|
44
|
+
key: string;
|
|
45
|
+
title: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface RemoteSessionListedRoom {
|
|
49
|
+
name: string;
|
|
50
|
+
/**
|
|
51
|
+
* `null` = the hub says this room has no AI. Absent on `/peek`, whose
|
|
52
|
+
* entries carry only name + status (interface §2.2) — the node then keeps
|
|
53
|
+
* the room, having nothing that says otherwise.
|
|
54
|
+
*/
|
|
55
|
+
agent?: string | null;
|
|
56
|
+
/**
|
|
57
|
+
* v1: "active" when the hub sees a turn in flight, otherwise "ready".
|
|
58
|
+
* Optional on `/sessions`, **required** on `/peek` — that is the whole
|
|
59
|
+
* answer a peek gives, and an absent one would read as idle.
|
|
60
|
+
*/
|
|
61
|
+
status?: "active" | "ready";
|
|
62
|
+
description?: string | null;
|
|
63
|
+
role?: "owner" | "member";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* One node in a listing: its rooms, or why the hub could not answer for it —
|
|
68
|
+
* exactly one of the two, never both and never neither (interface §2.1).
|
|
69
|
+
*/
|
|
70
|
+
export type RemoteSessionNodeListing =
|
|
71
|
+
| { node: string; sessions: RemoteSessionListedRoom[]; error?: undefined }
|
|
72
|
+
| { node: string; sessions?: undefined; error: string };
|
|
73
|
+
|
|
74
|
+
export interface RemoteSessionPendingAsk {
|
|
75
|
+
to: string;
|
|
76
|
+
requestId: string;
|
|
77
|
+
status: "forwarded" | "reply_pending";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type RemoteSessionCallError = {
|
|
81
|
+
ok: false;
|
|
82
|
+
/** Human-readable, safe to show the agent verbatim. */
|
|
83
|
+
error: string;
|
|
84
|
+
/** HTTP status the hub answered with; absent when it did not answer at all. */
|
|
85
|
+
status?: number;
|
|
86
|
+
code?: string;
|
|
87
|
+
/** The request may have been delivered (a response timed out after sending). */
|
|
88
|
+
uncertain?: boolean;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
export type RemoteSessionsResult =
|
|
92
|
+
| { ok: true; nodes: RemoteSessionNodeListing[] }
|
|
93
|
+
| RemoteSessionCallError;
|
|
94
|
+
|
|
95
|
+
export type RemoteSessionPeekResult =
|
|
96
|
+
| { ok: true; nodes: RemoteSessionNodeListing[]; pendingAsks: RemoteSessionPendingAsk[] }
|
|
97
|
+
| RemoteSessionCallError;
|
|
98
|
+
|
|
99
|
+
export type RemoteSessionDeliveryResult =
|
|
100
|
+
| { ok: true; requestId: string; replayed: boolean }
|
|
101
|
+
| RemoteSessionCallError;
|
|
102
|
+
|
|
103
|
+
export type RemoteSessionHubFetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
104
|
+
|
|
105
|
+
let hubFetch: RemoteSessionHubFetch = (input, init) => fetch(input, init);
|
|
106
|
+
|
|
107
|
+
/** Test seam: replace the transport without an HTTP server. */
|
|
108
|
+
export function setRemoteSessionHubFetch(next: RemoteSessionHubFetch | null): void {
|
|
109
|
+
hubFetch = next ?? ((input, init) => fetch(input, init));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function isTimeout(error: unknown): boolean {
|
|
113
|
+
const name = (error as { name?: string } | null)?.name;
|
|
114
|
+
return name === "TimeoutError" || name === "AbortError";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Socket-level causes that prove the request never reached the hub: the
|
|
119
|
+
* connection was never established, so nothing could have been delivered.
|
|
120
|
+
* Everything else — including the bare `TypeError: fetch failed` a socket
|
|
121
|
+
* hangup after the bytes went out produces — has to count as *maybe*
|
|
122
|
+
* delivered.
|
|
123
|
+
*/
|
|
124
|
+
const NEVER_REACHED_HUB_CAUSE_CODES = new Set([
|
|
125
|
+
"ECONNREFUSED",
|
|
126
|
+
"ENOTFOUND",
|
|
127
|
+
"EAI_AGAIN",
|
|
128
|
+
"EHOSTUNREACH",
|
|
129
|
+
"ENETUNREACH",
|
|
130
|
+
"ERR_INVALID_URL",
|
|
131
|
+
"CERT_HAS_EXPIRED",
|
|
132
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
133
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
134
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
135
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
136
|
+
]);
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Whether a transport failure is provably *before* the request left: only
|
|
140
|
+
* then is "not delivered" a fact.
|
|
141
|
+
*
|
|
142
|
+
* The default has to be the other way round. Once `fetch` has been called the
|
|
143
|
+
* request may already be at the hub, and a hangup while waiting for the
|
|
144
|
+
* response surfaces as `TypeError("fetch failed")` — indistinguishable by
|
|
145
|
+
* name from a refused connection. Treating that as a clean failure is what
|
|
146
|
+
* loses messages: the caller then deletes its pending marker and the durable
|
|
147
|
+
* ask, so the hub's late `ask-reply` 404s and a `tell` retry duplicates.
|
|
148
|
+
* Erring the other way only costs a "delivery unconfirmed" line.
|
|
149
|
+
*/
|
|
150
|
+
function neverReachedHub(error: unknown): boolean {
|
|
151
|
+
if (isTimeout(error)) return false;
|
|
152
|
+
const cause = (error as { cause?: { code?: unknown } | null } | null)?.cause;
|
|
153
|
+
const code = cause?.code;
|
|
154
|
+
return typeof code === "string" && NEVER_REACHED_HUB_CAUSE_CODES.has(code);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The v1 success envelope, checked exactly: `ok === true`, `v === 1`, and
|
|
159
|
+
* the fields the operation promises with their types. Anything else on a
|
|
160
|
+
* 2xx — an HTML page, a JSON error with the wrong `v`, a missing `ok` — is
|
|
161
|
+
* not the hub's answer and must not be treated as one.
|
|
162
|
+
*/
|
|
163
|
+
export type HubEnvelopeShape = "sessions" | "peek" | "delivery" | "reply";
|
|
164
|
+
|
|
165
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
166
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Which listing the rooms came from. `/sessions` describes rooms (`status` is
|
|
171
|
+
* an optional extra); `/peek` exists *only* to say which of them are running,
|
|
172
|
+
* so there a room without `status` carries no answer at all — and read as an
|
|
173
|
+
* absent field it silently becomes "idle", which is the one reading a peek
|
|
174
|
+
* must never invent (interface §2.2).
|
|
175
|
+
*/
|
|
176
|
+
type ListingMode = "sessions" | "peek";
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* One room in a node's listing, parsed field by field.
|
|
180
|
+
*
|
|
181
|
+
* An array that merely *is* an array is not a listing: `[null]`, `[{}]` or a
|
|
182
|
+
* room whose `name` is a number all used to pass the envelope check and then
|
|
183
|
+
* crash (or silently render `undefined/undefined`) in the caller that reads
|
|
184
|
+
* `session.name`. The hub is a peer, not a trusted library, so its 200 gets
|
|
185
|
+
* the same scrutiny as its 400.
|
|
186
|
+
*/
|
|
187
|
+
function parseListedRoom(value: unknown, mode: ListingMode): RemoteSessionListedRoom | null {
|
|
188
|
+
if (!isPlainRecord(value)) return null;
|
|
189
|
+
const { name, agent, status, description, role } = value;
|
|
190
|
+
if (typeof name !== "string" || !name.trim()) return null;
|
|
191
|
+
if (agent !== undefined && agent !== null && typeof agent !== "string") return null;
|
|
192
|
+
if (status === undefined) {
|
|
193
|
+
// A peek entry is its status; without one the entry answers nothing.
|
|
194
|
+
if (mode === "peek") return null;
|
|
195
|
+
} else if (status !== "active" && status !== "ready") {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
if (description !== undefined && description !== null && typeof description !== "string") {
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
if (role !== undefined && role !== "owner" && role !== "member") return null;
|
|
202
|
+
return {
|
|
203
|
+
name,
|
|
204
|
+
...(agent !== undefined ? { agent } : {}),
|
|
205
|
+
...(status !== undefined ? { status } : {}),
|
|
206
|
+
...(description !== undefined ? { description } : {}),
|
|
207
|
+
...(role !== undefined ? { role } : {}),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* One node's entry: `sessions` or `error`, exactly one of the two.
|
|
213
|
+
*
|
|
214
|
+
* The contract makes them alternatives (interface §2.1), and the readers rely
|
|
215
|
+
* on it: a node reported as unreachable *and* carrying rooms would be printed
|
|
216
|
+
* as unreachable while its rooms vanish, and one carrying neither would be a
|
|
217
|
+
* node the person can neither address nor be told about. Either way the hub
|
|
218
|
+
* and this node no longer agree on what was said, which is a protocol failure,
|
|
219
|
+
* not a listing.
|
|
220
|
+
*/
|
|
221
|
+
function parseNodeListing(value: unknown, mode: ListingMode): RemoteSessionNodeListing | null {
|
|
222
|
+
if (!isPlainRecord(value)) return null;
|
|
223
|
+
const { node, sessions, error } = value;
|
|
224
|
+
// The node name is what the person types before the slash, so a name
|
|
225
|
+
// containing one could never be addressed and is not a valid listing.
|
|
226
|
+
if (typeof node !== "string" || !node.trim() || node.includes("/")) return null;
|
|
227
|
+
if (error !== undefined && (typeof error !== "string" || !error.trim())) return null;
|
|
228
|
+
if ((sessions === undefined) === (error === undefined)) return null;
|
|
229
|
+
if (sessions === undefined) return { node, error: error as string };
|
|
230
|
+
if (!Array.isArray(sessions)) return null;
|
|
231
|
+
const parsed: RemoteSessionListedRoom[] = [];
|
|
232
|
+
for (const entry of sessions) {
|
|
233
|
+
const room = parseListedRoom(entry, mode);
|
|
234
|
+
if (!room) return null;
|
|
235
|
+
parsed.push(room);
|
|
236
|
+
}
|
|
237
|
+
return { node, sessions: parsed };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function parseNodeListings(value: unknown, mode: ListingMode): RemoteSessionNodeListing[] | null {
|
|
241
|
+
if (!Array.isArray(value)) return null;
|
|
242
|
+
const listings: RemoteSessionNodeListing[] = [];
|
|
243
|
+
for (const entry of value) {
|
|
244
|
+
const listing = parseNodeListing(entry, mode);
|
|
245
|
+
if (!listing) return null;
|
|
246
|
+
listings.push(listing);
|
|
247
|
+
}
|
|
248
|
+
return listings;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function parsePendingAsks(value: unknown): RemoteSessionPendingAsk[] | null {
|
|
252
|
+
if (!Array.isArray(value)) return null;
|
|
253
|
+
const asks: RemoteSessionPendingAsk[] = [];
|
|
254
|
+
for (const entry of value) {
|
|
255
|
+
if (!isPlainRecord(entry)) return null;
|
|
256
|
+
const { to, requestId, status } = entry;
|
|
257
|
+
if (typeof to !== "string" || !to.trim()) return null;
|
|
258
|
+
if (typeof requestId !== "string" || !requestId.trim()) return null;
|
|
259
|
+
if (status !== "forwarded" && status !== "reply_pending") return null;
|
|
260
|
+
asks.push({ to, requestId, status });
|
|
261
|
+
}
|
|
262
|
+
return asks;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The parsed v1 success payload, or `null` for anything that is not it.
|
|
267
|
+
*
|
|
268
|
+
* `null` is not "an empty answer": every caller turns it into a protocol
|
|
269
|
+
* failure, which is retried and then reported as unconfirmed, exactly like a
|
|
270
|
+
* transport failure.
|
|
271
|
+
*/
|
|
272
|
+
export type HubSuccessEnvelope =
|
|
273
|
+
| { shape: "sessions"; nodes: RemoteSessionNodeListing[] }
|
|
274
|
+
| { shape: "peek"; nodes: RemoteSessionNodeListing[]; pendingAsks: RemoteSessionPendingAsk[] }
|
|
275
|
+
| { shape: "delivery"; replayed: boolean }
|
|
276
|
+
| { shape: "reply"; replayed: boolean };
|
|
277
|
+
|
|
278
|
+
export function validateHubSuccessEnvelope(
|
|
279
|
+
body: unknown,
|
|
280
|
+
shape: HubEnvelopeShape,
|
|
281
|
+
): HubSuccessEnvelope | null {
|
|
282
|
+
if (!isPlainRecord(body)) return null;
|
|
283
|
+
if (body.ok !== true || body.v !== REMOTE_SESSION_PROTOCOL_VERSION) return null;
|
|
284
|
+
switch (shape) {
|
|
285
|
+
case "sessions": {
|
|
286
|
+
const nodes = parseNodeListings(body.nodes, "sessions");
|
|
287
|
+
return nodes ? { shape, nodes } : null;
|
|
288
|
+
}
|
|
289
|
+
case "peek": {
|
|
290
|
+
const nodes = parseNodeListings(body.nodes, "peek");
|
|
291
|
+
const pendingAsks = parsePendingAsks(body.pendingAsks);
|
|
292
|
+
return nodes && pendingAsks ? { shape, nodes, pendingAsks } : null;
|
|
293
|
+
}
|
|
294
|
+
case "delivery":
|
|
295
|
+
case "reply":
|
|
296
|
+
return typeof body.replayed === "boolean" ? { shape, replayed: body.replayed } : null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function hubHeaders(bearer: string): Record<string, string> {
|
|
301
|
+
return {
|
|
302
|
+
authorization: `Bearer ${bearer}`,
|
|
303
|
+
"content-type": "application/json",
|
|
304
|
+
accept: "application/json",
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function errorText(status: number, body: unknown, fallback: string): string {
|
|
309
|
+
const text = (body as { error?: unknown } | null)?.error;
|
|
310
|
+
if (typeof text === "string" && text.trim()) return text.trim();
|
|
311
|
+
return `${fallback} (hub answered ${status})`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function describeFailure(status: number, body: unknown): string {
|
|
315
|
+
switch (status) {
|
|
316
|
+
case 401:
|
|
317
|
+
return "remote session authorization for this turn is no longer valid (expired or revoked); send a new message to start a turn with a fresh grant";
|
|
318
|
+
case 404:
|
|
319
|
+
return errorText(status, body, "remote session not found");
|
|
320
|
+
case 409:
|
|
321
|
+
return errorText(status, body, "remote session refused the request");
|
|
322
|
+
case 413:
|
|
323
|
+
return errorText(status, body, "message too long for the hub");
|
|
324
|
+
case 429:
|
|
325
|
+
return errorText(status, body, "remote session rate limit reached; try again shortly");
|
|
326
|
+
case 502:
|
|
327
|
+
return errorText(status, body, "the target node could not be reached by the hub");
|
|
328
|
+
case 503:
|
|
329
|
+
return errorText(status, body, "remote session-comm is disabled on the hub");
|
|
330
|
+
default:
|
|
331
|
+
return errorText(status, body, "hub refused the remote session call");
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function postHub(
|
|
336
|
+
grant: RemoteSessionGrant,
|
|
337
|
+
op: "sessions" | "peek" | "tell" | "ask" | "abort",
|
|
338
|
+
shape: HubEnvelopeShape,
|
|
339
|
+
body: Record<string, unknown>,
|
|
340
|
+
opts: { retry: boolean },
|
|
341
|
+
): Promise<{ ok: true; body: HubSuccessEnvelope } | RemoteSessionCallError> {
|
|
342
|
+
const url = `${grant.hubUrl}${REMOTE_SESSION_HUB_BASE_PATH}/${op}`;
|
|
343
|
+
const payload = JSON.stringify({ v: REMOTE_SESSION_PROTOCOL_VERSION, ...body });
|
|
344
|
+
let uncertain = false;
|
|
345
|
+
let lastError = "hub unreachable";
|
|
346
|
+
const attempts = opts.retry ? HUB_RETRY_DELAYS_MS.length + 1 : 1;
|
|
347
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
348
|
+
if (attempt > 0) {
|
|
349
|
+
await new Promise((resolve) => setTimeout(resolve, HUB_RETRY_DELAYS_MS[attempt - 1]));
|
|
350
|
+
}
|
|
351
|
+
let response: Response;
|
|
352
|
+
try {
|
|
353
|
+
response = await hubFetch(url, {
|
|
354
|
+
method: "POST",
|
|
355
|
+
headers: hubHeaders(grant.capability),
|
|
356
|
+
body: payload,
|
|
357
|
+
signal: AbortSignal.timeout(HUB_TIMEOUT_MS),
|
|
358
|
+
redirect: "error",
|
|
359
|
+
});
|
|
360
|
+
} catch (error) {
|
|
361
|
+
// Uncertain by default: the send has started, so only a failure that
|
|
362
|
+
// provably happened before the connection existed is a clean "not
|
|
363
|
+
// delivered" (see `neverReachedHub`).
|
|
364
|
+
if (!neverReachedHub(error)) uncertain = true;
|
|
365
|
+
lastError = `hub unreachable: ${error instanceof Error ? error.message : String(error)}`;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
let parsed: unknown = null;
|
|
369
|
+
try {
|
|
370
|
+
parsed = await response.json();
|
|
371
|
+
} catch {
|
|
372
|
+
parsed = null;
|
|
373
|
+
}
|
|
374
|
+
if (response.ok) {
|
|
375
|
+
const envelope = validateHubSuccessEnvelope(parsed, shape);
|
|
376
|
+
if (envelope) return { ok: true, body: envelope };
|
|
377
|
+
// A 2xx that is not the v1 envelope is not the hub speaking (a relay's
|
|
378
|
+
// error page, a version skew): the request may or may not have landed.
|
|
379
|
+
uncertain = true;
|
|
380
|
+
lastError = `hub answered ${response.status} with an unexpected body`;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
const code =
|
|
384
|
+
typeof (parsed as { code?: unknown } | null)?.code === "string"
|
|
385
|
+
? (parsed as { code: string }).code
|
|
386
|
+
: undefined;
|
|
387
|
+
if (code === HUB_IN_PROGRESS_CODE && (response.status === 409 || response.status === 502)) {
|
|
388
|
+
// The hub is still delivering this very requestId: the outcome is not
|
|
389
|
+
// known yet, so this is neither success nor a final refusal. The code —
|
|
390
|
+
// not the status — is what carries that meaning: the contract says 409,
|
|
391
|
+
// but a hub that flattens the target node's 409 into its own 502 while
|
|
392
|
+
// keeping the code is still saying "in flight", and reading it as a
|
|
393
|
+
// final 502 is exactly what drops a pending ask a late reply needs.
|
|
394
|
+
uncertain = true;
|
|
395
|
+
lastError = describeFailure(response.status, parsed);
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
// 5xx other than the hub's own "node unreachable" verdict is worth one
|
|
399
|
+
// more try; everything else is the hub's answer.
|
|
400
|
+
if (response.status >= 500 && response.status !== 502 && response.status !== 503) {
|
|
401
|
+
lastError = describeFailure(response.status, parsed);
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
return {
|
|
405
|
+
ok: false,
|
|
406
|
+
error: describeFailure(response.status, parsed),
|
|
407
|
+
status: response.status,
|
|
408
|
+
...(code ? { code } : {}),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
logger.warn({ op, hubUrl: grant.hubUrl, uncertain }, "session-comm: hub remote call failed");
|
|
412
|
+
return { ok: false, error: lastError, ...(uncertain ? { uncertain: true } : {}) };
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Rooms on other nodes the person who spoke may address, grouped by node. */
|
|
416
|
+
export async function hubRemoteSessions(grant: RemoteSessionGrant): Promise<RemoteSessionsResult> {
|
|
417
|
+
const result = await postHub(grant, "sessions", "sessions", {}, { retry: true });
|
|
418
|
+
if (!result.ok) return result;
|
|
419
|
+
if (result.body.shape !== "sessions") return { ok: false, error: "hub answered the wrong shape" };
|
|
420
|
+
return { ok: true, nodes: result.body.nodes };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Remote running/idle view plus this turn's asks the hub still holds. */
|
|
424
|
+
export async function hubRemotePeek(grant: RemoteSessionGrant): Promise<RemoteSessionPeekResult> {
|
|
425
|
+
const result = await postHub(grant, "peek", "peek", {}, { retry: true });
|
|
426
|
+
if (!result.ok) return result;
|
|
427
|
+
if (result.body.shape !== "peek") return { ok: false, error: "hub answered the wrong shape" };
|
|
428
|
+
return { ok: true, nodes: result.body.nodes, pendingAsks: result.body.pendingAsks };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function deliveryResult(
|
|
432
|
+
requestId: string,
|
|
433
|
+
result: { ok: true; body: HubSuccessEnvelope } | RemoteSessionCallError,
|
|
434
|
+
): RemoteSessionDeliveryResult {
|
|
435
|
+
if (!result.ok) return result;
|
|
436
|
+
if (result.body.shape !== "delivery") return { ok: false, error: "hub answered the wrong shape" };
|
|
437
|
+
return { ok: true, requestId, replayed: result.body.replayed };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export async function hubRemoteTell(
|
|
441
|
+
grant: RemoteSessionGrant,
|
|
442
|
+
args: {
|
|
443
|
+
requestId: string;
|
|
444
|
+
to: RemoteSessionTarget;
|
|
445
|
+
message: string;
|
|
446
|
+
depth: number;
|
|
447
|
+
fromLabel: RemoteSessionFromLabel;
|
|
448
|
+
},
|
|
449
|
+
): Promise<RemoteSessionDeliveryResult> {
|
|
450
|
+
return deliveryResult(
|
|
451
|
+
args.requestId,
|
|
452
|
+
await postHub(grant, "tell", "delivery", args, { retry: true }),
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export async function hubRemoteAsk(
|
|
457
|
+
grant: RemoteSessionGrant,
|
|
458
|
+
args: {
|
|
459
|
+
requestId: string;
|
|
460
|
+
to: RemoteSessionTarget;
|
|
461
|
+
message: string;
|
|
462
|
+
fromDepth: number;
|
|
463
|
+
fromLabel: RemoteSessionFromLabel;
|
|
464
|
+
},
|
|
465
|
+
): Promise<RemoteSessionDeliveryResult> {
|
|
466
|
+
return deliveryResult(
|
|
467
|
+
args.requestId,
|
|
468
|
+
await postHub(grant, "ask", "delivery", args, { retry: true }),
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export async function hubRemoteAbort(
|
|
473
|
+
grant: RemoteSessionGrant,
|
|
474
|
+
args: { requestId: string; to: RemoteSessionTarget },
|
|
475
|
+
): Promise<RemoteSessionDeliveryResult> {
|
|
476
|
+
return deliveryResult(
|
|
477
|
+
args.requestId,
|
|
478
|
+
await postHub(grant, "abort", "delivery", args, { retry: true }),
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Post an ask's answer to the hub with the one-shot reply token the hub put
|
|
484
|
+
* in the inbox entry. Returns whether the outbox row may be dropped: the hub
|
|
485
|
+
* accepted it (or already had it) with the exact v1 envelope, or gave a final
|
|
486
|
+
* answer that no retry can change (bad/expired token, unknown request).
|
|
487
|
+
* Transport failures, 5xx, 429, `409 in_progress` and a 2xx without the
|
|
488
|
+
* envelope keep the row for the outbox worker.
|
|
489
|
+
*/
|
|
490
|
+
export async function hubRemoteReply(args: {
|
|
491
|
+
hubUrl: string;
|
|
492
|
+
token: string;
|
|
493
|
+
requestId: string;
|
|
494
|
+
kind: "reply" | "error";
|
|
495
|
+
replyText: string;
|
|
496
|
+
fromLabel: string;
|
|
497
|
+
}): Promise<{ settled: true; replayed: boolean } | { settled: false; error: string }> {
|
|
498
|
+
const url = `${args.hubUrl}${REMOTE_SESSION_HUB_BASE_PATH}/reply`;
|
|
499
|
+
let response: Response;
|
|
500
|
+
try {
|
|
501
|
+
response = await hubFetch(url, {
|
|
502
|
+
method: "POST",
|
|
503
|
+
headers: hubHeaders(args.token),
|
|
504
|
+
body: JSON.stringify({
|
|
505
|
+
v: REMOTE_SESSION_PROTOCOL_VERSION,
|
|
506
|
+
requestId: args.requestId,
|
|
507
|
+
kind: args.kind,
|
|
508
|
+
replyText: args.replyText,
|
|
509
|
+
fromLabel: args.fromLabel,
|
|
510
|
+
}),
|
|
511
|
+
signal: AbortSignal.timeout(HUB_TIMEOUT_MS),
|
|
512
|
+
redirect: "error",
|
|
513
|
+
});
|
|
514
|
+
} catch (error) {
|
|
515
|
+
return {
|
|
516
|
+
settled: false,
|
|
517
|
+
error: `hub unreachable: ${error instanceof Error ? error.message : String(error)}`,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
let parsed: unknown = null;
|
|
521
|
+
try {
|
|
522
|
+
parsed = await response.json();
|
|
523
|
+
} catch {
|
|
524
|
+
parsed = null;
|
|
525
|
+
}
|
|
526
|
+
if (response.ok) {
|
|
527
|
+
const envelope = validateHubSuccessEnvelope(parsed, "reply");
|
|
528
|
+
if (!envelope) {
|
|
529
|
+
return {
|
|
530
|
+
settled: false,
|
|
531
|
+
error: `hub answered ${response.status} with an unexpected body`,
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
return { settled: true, replayed: envelope.shape === "reply" && envelope.replayed };
|
|
535
|
+
}
|
|
536
|
+
const code = (parsed as { code?: unknown } | null)?.code;
|
|
537
|
+
if (
|
|
538
|
+
response.status >= 500 ||
|
|
539
|
+
response.status === 429 ||
|
|
540
|
+
(response.status === 409 && code === HUB_IN_PROGRESS_CODE)
|
|
541
|
+
) {
|
|
542
|
+
return { settled: false, error: describeFailure(response.status, parsed) };
|
|
543
|
+
}
|
|
544
|
+
logger.warn(
|
|
545
|
+
{
|
|
546
|
+
requestId: args.requestId,
|
|
547
|
+
status: response.status,
|
|
548
|
+
error: describeFailure(response.status, parsed),
|
|
549
|
+
},
|
|
550
|
+
"session-comm: hub rejected an ask reply; dropping it",
|
|
551
|
+
);
|
|
552
|
+
return { settled: true, replayed: false };
|
|
553
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Largest message a remote (`node/topic`) tell/ask may carry, in characters.
|
|
3
|
+
* The same value as the adapter's `MAX_PEER_MESSAGE_LENGTH` (`protocol.ts`)
|
|
4
|
+
* and the local `MAX_MESSAGE_LENGTH`, so a message accepted locally is never
|
|
5
|
+
* refused only because it crossed a node boundary. Enforced by the hub on
|
|
6
|
+
* the way in and by the node's inbox route on the way out.
|
|
7
|
+
*/
|
|
8
|
+
export const MAX_PEER_MESSAGE_LENGTH = 10_000;
|
|
@@ -7,6 +7,21 @@
|
|
|
7
7
|
* gracefully and `peerSessionsForUser` contributes nothing to peek listings.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import {
|
|
11
|
+
MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH,
|
|
12
|
+
normalizeHubUrl,
|
|
13
|
+
REMOTE_SESSION_REPLY_TOKEN_PATTERN,
|
|
14
|
+
} from "#runtime/remote-session-grant";
|
|
15
|
+
import {
|
|
16
|
+
deliverHubRemoteReply,
|
|
17
|
+
type HubRemoteReplyRoute,
|
|
18
|
+
} from "#runtime/remote-session-reply-outbox";
|
|
19
|
+
|
|
20
|
+
const MAX_ROUTE_REQUEST_ID_LENGTH = 200;
|
|
21
|
+
const MAX_ROUTE_LABEL_LENGTH = 300;
|
|
22
|
+
|
|
23
|
+
export type { HubRemoteReplyRoute };
|
|
24
|
+
|
|
10
25
|
export interface PeerForwardArgs {
|
|
11
26
|
action: "tell" | "ask" | "abort";
|
|
12
27
|
toNode: string;
|
|
@@ -25,7 +40,9 @@ export interface PeerForwardArgs {
|
|
|
25
40
|
|
|
26
41
|
export type PeerForwardResult = { ok: true } | { ok: false; error: string };
|
|
27
42
|
|
|
28
|
-
|
|
43
|
+
/** Legacy adapter-owned route: the answer goes back over the Central peer protocol. */
|
|
44
|
+
export interface PeerRemoteReplyRoute {
|
|
45
|
+
via?: undefined;
|
|
29
46
|
nodeName: string;
|
|
30
47
|
nodeCellId: string;
|
|
31
48
|
topicId: string;
|
|
@@ -33,6 +50,60 @@ export interface RemoteReplyRoute {
|
|
|
33
50
|
requestId: string;
|
|
34
51
|
}
|
|
35
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Where a remote ask's answer goes. A hub-routed ask (`via: "hub"`) carries
|
|
55
|
+
* the hub URL and the hub's one-shot reply token and needs no adapter: core
|
|
56
|
+
* posts the answer itself from a durable outbox. The legacy peer route stays
|
|
57
|
+
* for the adapter bridge.
|
|
58
|
+
*/
|
|
59
|
+
export type RemoteReplyRoute = PeerRemoteReplyRoute | HubRemoteReplyRoute;
|
|
60
|
+
|
|
61
|
+
export function isHubRemoteReplyRoute(route: RemoteReplyRoute): route is HubRemoteReplyRoute {
|
|
62
|
+
return route.via === "hub";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Strict check for a route read from an inbox entry or back from storage.
|
|
67
|
+
* The route names where a bearer (`token`) will be POSTed, so `hubUrl` obeys
|
|
68
|
+
* exactly the turn grant's rule (`normalizeHubUrl`: https, or loopback http;
|
|
69
|
+
* no credentials/query/fragment; ≤ 512 chars) and the token must be shaped
|
|
70
|
+
* like an `rsr1` token within the capability length cap. Anything else is
|
|
71
|
+
* not a route at all.
|
|
72
|
+
*/
|
|
73
|
+
export function parseHubRemoteReplyRoute(value: unknown): HubRemoteReplyRoute | null {
|
|
74
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
75
|
+
const route = value as Partial<HubRemoteReplyRoute>;
|
|
76
|
+
if (
|
|
77
|
+
route.via !== "hub" ||
|
|
78
|
+
typeof route.hubUrl !== "string" ||
|
|
79
|
+
typeof route.token !== "string" ||
|
|
80
|
+
typeof route.nodeName !== "string" ||
|
|
81
|
+
typeof route.topicId !== "string" ||
|
|
82
|
+
typeof route.requestId !== "string"
|
|
83
|
+
) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
const requestId = route.requestId.trim();
|
|
87
|
+
const nodeName = route.nodeName.trim();
|
|
88
|
+
const topicId = route.topicId.trim();
|
|
89
|
+
const token = route.token.trim();
|
|
90
|
+
if (
|
|
91
|
+
!requestId ||
|
|
92
|
+
requestId.length > MAX_ROUTE_REQUEST_ID_LENGTH ||
|
|
93
|
+
!nodeName ||
|
|
94
|
+
nodeName.length > MAX_ROUTE_LABEL_LENGTH ||
|
|
95
|
+
!topicId ||
|
|
96
|
+
topicId.length > MAX_ROUTE_LABEL_LENGTH ||
|
|
97
|
+
token.length > MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH ||
|
|
98
|
+
!REMOTE_SESSION_REPLY_TOKEN_PATTERN.test(token)
|
|
99
|
+
) {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const hubUrl = normalizeHubUrl(route.hubUrl.trim(), "remoteReply.hubUrl");
|
|
103
|
+
if ("error" in hubUrl) return null;
|
|
104
|
+
return { via: "hub", hubUrl: hubUrl.url, token, nodeName, topicId, requestId };
|
|
105
|
+
}
|
|
106
|
+
|
|
36
107
|
export interface PeerSessionBridge {
|
|
37
108
|
forward(args: PeerForwardArgs): Promise<PeerForwardResult>;
|
|
38
109
|
/**
|
|
@@ -46,7 +117,7 @@ export interface PeerSessionBridge {
|
|
|
46
117
|
fromTopicId?: string,
|
|
47
118
|
): Promise<PeerSessionsResult>;
|
|
48
119
|
reply(
|
|
49
|
-
route:
|
|
120
|
+
route: PeerRemoteReplyRoute,
|
|
50
121
|
sourceTitle: string,
|
|
51
122
|
replyText: string,
|
|
52
123
|
kind: "reply" | "error",
|
|
@@ -64,7 +135,7 @@ type IpcRequest =
|
|
|
64
135
|
| { action: "sessions"; userId: string; sourceQueryId?: string; fromTopicId?: string }
|
|
65
136
|
| {
|
|
66
137
|
action: "reply";
|
|
67
|
-
route:
|
|
138
|
+
route: PeerRemoteReplyRoute;
|
|
68
139
|
sourceTitle: string;
|
|
69
140
|
replyText: string;
|
|
70
141
|
kind: "reply" | "error";
|
|
@@ -161,6 +232,10 @@ export async function deliverPeerReply(
|
|
|
161
232
|
replyText: string,
|
|
162
233
|
kind: "reply" | "error",
|
|
163
234
|
): Promise<boolean> {
|
|
235
|
+
// Hub-routed answers need no adapter and work on a loopback node too.
|
|
236
|
+
if (isHubRemoteReplyRoute(route)) {
|
|
237
|
+
return deliverHubRemoteReply(route, sourceTitle, replyText, kind);
|
|
238
|
+
}
|
|
164
239
|
if (activeBridge) return activeBridge.reply(route, sourceTitle, replyText, kind);
|
|
165
240
|
return (
|
|
166
241
|
(
|