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.
Files changed (96) hide show
  1. package/dist/agent-helpers.js +1146 -212
  2. package/dist/agent-helpers.js.map +27 -19
  3. package/dist/background-bash.js.map +1 -1
  4. package/dist/browser-runtime.js.map +1 -1
  5. package/dist/{chunk-kkftbxh2.js → chunk-7he9nzfa.js} +1 -1
  6. package/dist/{chunk-55dd0xw7.js → chunk-ad6xqvqy.js} +2 -2
  7. package/dist/{chunk-55dd0xw7.js.map → chunk-ad6xqvqy.js.map} +2 -2
  8. package/dist/{chunk-exqz8bez.js → chunk-hh3f0yr7.js} +3 -3
  9. package/dist/{chunk-exqz8bez.js.map → chunk-hh3f0yr7.js.map} +2 -2
  10. package/dist/{chunk-aqqmzmft.js → chunk-nm59q3em.js} +1 -1
  11. package/dist/{chunk-cv7vdsrn.js → chunk-w3c6fc0p.js} +286 -9
  12. package/dist/{chunk-cv7vdsrn.js.map → chunk-w3c6fc0p.js.map} +10 -7
  13. package/dist/hosted-agent.js +290 -12
  14. package/dist/hosted-agent.js.map +10 -7
  15. package/dist/main.js +4599 -2724
  16. package/dist/main.js.map +49 -38
  17. package/dist/mcp-factories.js +1166 -162
  18. package/dist/mcp-factories.js.map +27 -19
  19. package/dist/media.js.map +1 -1
  20. package/dist/prompts.js.map +1 -1
  21. package/dist/query-runtime.js.map +3 -3
  22. package/dist/registry.js +3 -3
  23. package/dist/rollout.js +2 -2
  24. package/dist/runtime/src/agents/explicit-agent-switch.ts +101 -0
  25. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +126 -43
  26. package/dist/runtime/src/agents/public-helpers.ts +5 -0
  27. package/dist/runtime/src/agents/self-config-core.ts +28 -58
  28. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +34 -8
  29. package/dist/runtime/src/index.ts +75 -0
  30. package/dist/runtime/src/mcp/peer-bridge.ts +6 -1
  31. package/dist/runtime/src/mcp/runtime-spec.ts +145 -10
  32. package/dist/runtime/src/mcp/session-comm/actor-policy.ts +87 -0
  33. package/dist/runtime/src/mcp/session-comm/context.ts +42 -1
  34. package/dist/runtime/src/mcp/session-comm/default-host.ts +178 -2
  35. package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
  36. package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
  37. package/dist/runtime/src/mcp/session-comm/peer-forward.ts +78 -3
  38. package/dist/runtime/src/mcp/session-comm/server.ts +167 -4
  39. package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +7 -0
  40. package/dist/runtime/src/mcp/session-comm/topics.ts +32 -10
  41. package/dist/runtime/src/mcp-runtime-host.ts +2 -1
  42. package/dist/runtime/src/node-host.ts +26 -0
  43. package/dist/runtime/src/platform/mcp-config.ts +56 -2
  44. package/dist/runtime/src/query/active-rooms.ts +6 -0
  45. package/dist/runtime/src/runtime/actor-topic-reach.ts +85 -0
  46. package/dist/runtime/src/runtime/actor-topic-scope.ts +175 -0
  47. package/dist/runtime/src/runtime/ask-callbacks.ts +73 -20
  48. package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
  49. package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
  50. package/dist/runtime/src/runtime/remote-session-inbox.ts +476 -0
  51. package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +156 -0
  52. package/dist/runtime/src/runtime/turn-runner.ts +157 -33
  53. package/dist/runtime/src/runtime-gateway.ts +20 -0
  54. package/dist/runtime/src/storage/api-topics.ts +22 -3
  55. package/dist/runtime/src/storage/remote-session.ts +526 -0
  56. package/dist/runtime/src/storage/runtime-turn-requests.ts +75 -2
  57. package/dist/runtime/src/topics/derive.ts +3 -0
  58. package/dist/runtime/src/types/api.ts +6 -0
  59. package/dist/runtime/src/types.ts +42 -0
  60. package/dist/runtime/src/version.ts +1 -1
  61. package/dist/runtime-gateway.js.map +2 -2
  62. package/dist/runtime-helpers.js.map +1 -1
  63. package/dist/storage.js +16 -4
  64. package/dist/storage.js.map +4 -4
  65. package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
  66. package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +12 -2
  67. package/dist/types/packages/core/src/agents/public-helpers.d.ts +1 -0
  68. package/dist/types/packages/core/src/agents/self-config-core.d.ts +15 -1
  69. package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +6 -1
  70. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +69 -2
  71. package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +17 -1
  72. package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
  73. package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
  74. package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +23 -2
  75. package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +6 -0
  76. package/dist/types/packages/core/src/platform/mcp-config.d.ts +10 -1
  77. package/dist/types/packages/core/src/query/active-rooms.d.ts +6 -0
  78. package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +49 -0
  79. package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +91 -0
  80. package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +8 -2
  81. package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
  82. package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +83 -0
  83. package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
  84. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +22 -3
  85. package/dist/types/packages/core/src/runtime-gateway.d.ts +20 -0
  86. package/dist/types/packages/core/src/storage/api-topics.d.ts +3 -0
  87. package/dist/types/packages/core/src/storage/remote-session.d.ts +135 -0
  88. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +12 -1
  89. package/dist/types/packages/core/src/topics/derive.d.ts +2 -0
  90. package/dist/types/packages/core/src/types/api.d.ts +6 -0
  91. package/dist/types/packages/core/src/types.d.ts +40 -0
  92. package/dist/types/packages/core/src/version.d.ts +1 -1
  93. package/dist/vault.js.map +1 -1
  94. package/package.json +1 -1
  95. /package/dist/{chunk-kkftbxh2.js.map → chunk-7he9nzfa.js.map} +0 -0
  96. /package/dist/{chunk-aqqmzmft.js.map → chunk-nm59q3em.js.map} +0 -0
@@ -37,11 +37,17 @@ export declare function registerAskCallback(entry: AskPending): void;
37
37
  * turn's queryId. Returns the AskPending or null if not found.
38
38
  * Past TTL: returns entry with timedOut=true (caller gets timeout notice). */
39
39
  export declare function resolveAskCallback(queryId: string): AskPending | null;
40
+ /** The hub-routed answer is durably queued: the callback row has served its purpose. */
41
+ export declare function deleteHubRemoteAskCallbackRow(requestId: string): void;
40
42
  /** Clean up stale asks that outlived their TTL (periodic, lightweight). */
41
43
  export declare function purgeStaleAsks(now?: number): void;
42
44
  /** Drop callbacks whose caller topic was hard-deleted. */
43
45
  export declare function cancelAskCallbacksForTopic(topicId: string): number;
44
46
  /** Fail remote asks whose target turn was interrupted by the previous process.
45
- * Call once during startup after the peer session bridge is registered. */
46
- export declare function failInterruptedRemoteAskCallbacks(): Promise<number>;
47
+ * Call once during startup after the peer session bridge is registered.
48
+ * `routes: "hub"` limits the pass to hub-routed asks, which need no adapter
49
+ * bridge and are therefore failed by the node itself at startup. */
50
+ export declare function failInterruptedRemoteAskCallbacks(options?: {
51
+ routes?: "all" | "hub";
52
+ }): Promise<number>;
47
53
  export {};
@@ -0,0 +1,91 @@
1
+ import type { RemoteSessionGrant } from "../types";
2
+ /**
3
+ * Hard caps on a hub-supplied remote-session grant.
4
+ *
5
+ * Like the actor room assertion (`actor-topic-scope.ts`), the grant rides the
6
+ * signed per-turn `session-comm` MCP token in a URL query and — with
7
+ * `NEGOTIUM_BUILTIN_MCP_TRANSPORT=stdio` — one base64url argv entry, so the
8
+ * transport bounds it, not the database. A capability is ≈330–440 characters
9
+ * (`rsc1.<base64url JSON>.<base64url HMAC>`) and adds ≈680 URL characters
10
+ * beside the maximal 8 KiB assertion (12,800 of the 14,336 budget, measured
11
+ * in `hosted-runtime-spec.test.ts`). The caps below leave a hub room to grow
12
+ * the payload, but a grant at both caps (≈3,475 URL characters) does not fit
13
+ * beside the *maximal* assertion — `MCP_URL_BUDGET_CHARS` is the backstop and
14
+ * refuses that mint loudly rather than dropping a field. A capability up to
15
+ * ≈1,590 characters always fits.
16
+ */
17
+ export declare const REMOTE_SESSION_GRANT_LIMITS: Readonly<{
18
+ /** Characters of `hubUrl`, after trimming. */
19
+ maxHubUrlLength: 512;
20
+ /** Characters of `capability`, after trimming. */
21
+ maxCapabilityLength: number;
22
+ /** The only capability format this node forwards. */
23
+ capabilityPrefix: "rsc1.";
24
+ }>;
25
+ export type RemoteSessionGrantValidation = {
26
+ ok: true;
27
+ grant: RemoteSessionGrant | undefined;
28
+ } | {
29
+ ok: false;
30
+ error: string;
31
+ };
32
+ /**
33
+ * Normalize a hub URL the node may present a bearer to: loopback `http://`
34
+ * or any `https://` origin, ≤ 512 characters, no credentials, no query or
35
+ * fragment. Returns the canonical string (trailing slash dropped) or the
36
+ * reason it is refused. The one rule for every hub URL the node stores — the
37
+ * turn grant's `hubUrl` and an ask's `remoteReply.hubUrl` alike — so a
38
+ * bearer can never be steered to an attacker-chosen host.
39
+ */
40
+ export declare function normalizeHubUrl(raw: string, name?: string): {
41
+ url: string;
42
+ } | {
43
+ error: string;
44
+ };
45
+ /** Shape of the hub's one-shot `rsr1` reply token; the node never verifies it. */
46
+ export declare const REMOTE_SESSION_REPLY_TOKEN_PATTERN: RegExp;
47
+ /** Same cap as the capability: the hub's tokens are ≈200 characters. */
48
+ export declare const MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH: number;
49
+ /**
50
+ * Validate a hub-supplied remote-session grant and say why it failed.
51
+ *
52
+ * `undefined` in means `undefined` out (no grant: remote session-comm stays
53
+ * fail-closed on `otium`); anything else must be exactly
54
+ * `{ hubUrl, capability }` — a plain object with those two own keys — with a
55
+ * callable hub URL and an opaque `rsc1.` capability within
56
+ * {@link REMOTE_SESSION_GRANT_LIMITS}. The node never decodes or verifies the
57
+ * capability: it is a bearer the hub issued and only the hub can check.
58
+ */
59
+ export declare function validateRemoteSessionGrant(value: unknown): RemoteSessionGrantValidation;
60
+ /** {@link validateRemoteSessionGrant} collapsed to `null` on failure. */
61
+ export declare function parseRemoteSessionGrant(value: unknown): RemoteSessionGrant | undefined | null;
62
+ export declare function isRemoteSessionGrant(value: unknown): value is RemoteSessionGrant;
63
+ /**
64
+ * Read a validated grant out of a persisted or signed context. Anything that
65
+ * does not validate collapses to "no grant" rather than throwing: a stale row
66
+ * only loses remote reach, it never breaks the turn.
67
+ */
68
+ export declare function remoteSessionGrantFrom(value: unknown): RemoteSessionGrant | undefined;
69
+ /**
70
+ * Best-effort peek at the capability's expiry (`e`, epoch seconds), used only
71
+ * to order grants when several requests fold into one turn. Untrusted: the
72
+ * node never decides validity from it — the hub does.
73
+ */
74
+ export declare function remoteSessionGrantExpiry(grant: RemoteSessionGrant): number | null;
75
+ /**
76
+ * The grant a merged turn runs with: symmetric to `intersectActorTopicScopes`
77
+ * — a request without a grant leaves the batch without one (fail-closed), and
78
+ * a batch of grants for one hub keeps the one that expires last so the merged
79
+ * turn is not cut short by the oldest message's capability. Grants naming
80
+ * different hubs never merge (the batch runs with none). The caller has
81
+ * already ensured the folded requests speak for the same actor.
82
+ */
83
+ export declare function mergeRemoteSessionGrants(grants: ReadonlyArray<RemoteSessionGrant | undefined>): RemoteSessionGrant | undefined;
84
+ /**
85
+ * Argv-safe encoding for the stdio session-comm server
86
+ * (`--remote-session-grant=`). Re-validated before encoding, so an in-process
87
+ * caller cannot put an unbounded or malformed grant into argv.
88
+ */
89
+ export declare function encodeRemoteSessionGrantArg(grant: RemoteSessionGrant): string;
90
+ /** Inverse of {@link encodeRemoteSessionGrantArg}; `null` when malformed. */
91
+ export declare function decodeRemoteSessionGrantArg(value: string): RemoteSessionGrant | null;
@@ -0,0 +1,83 @@
1
+ import { type HubRemoteReplyRoute } from "../mcp/session-comm/peer-forward";
2
+ import type { TopicDto } from "../types/api";
3
+ export declare const MAX_REMOTE_SESSION_REQUEST_ID_LENGTH = 200;
4
+ export declare const MAX_REMOTE_SESSION_LABEL_LENGTH = 300;
5
+ export interface RemoteSessionInboxFrom {
6
+ /** "<originNode>/<originTitle>", shown to the target as the sender. */
7
+ label: string;
8
+ /** The hub's own id of the origin room, for the hub's audit trail; opaque here. */
9
+ hubTopicId?: string;
10
+ }
11
+ export type RemoteSessionInboxDelivery = {
12
+ kind: "tell";
13
+ requestId: string;
14
+ from: RemoteSessionInboxFrom;
15
+ message: string;
16
+ depth: number;
17
+ } | {
18
+ kind: "ask";
19
+ requestId: string;
20
+ from: RemoteSessionInboxFrom;
21
+ message: string;
22
+ fromDepth: number;
23
+ remoteReply: HubRemoteReplyRoute;
24
+ } | {
25
+ kind: "abort";
26
+ requestId: string;
27
+ } | {
28
+ kind: "ask-reply";
29
+ requestId: string;
30
+ fromLabel: string;
31
+ replyKind: "reply" | "error";
32
+ replyText: string;
33
+ };
34
+ /** A malformed delivery, answered with its status (400 or 413). */
35
+ export declare class RemoteSessionInboxError extends Error {
36
+ readonly status: number;
37
+ constructor(status: number, message: string);
38
+ }
39
+ /** Validate a delivery body; throws {@link RemoteSessionInboxError}. */
40
+ export declare function parseRemoteSessionInboxDelivery(body: Record<string, unknown>): RemoteSessionInboxDelivery;
41
+ export type RemoteSessionInboxOutcome = {
42
+ ok: true;
43
+ replayed: boolean;
44
+ } | {
45
+ ok: false;
46
+ status: number;
47
+ error: string;
48
+ code?: string;
49
+ };
50
+ /** Answer for a duplicate that meets a live `processing` claim: come back later. */
51
+ export declare const REMOTE_SESSION_INBOX_IN_PROGRESS_CODE = "in_progress";
52
+ /**
53
+ * Hand one hub delivery to the durable session inbox exactly once.
54
+ *
55
+ * The claim and the enqueue share a transaction: a retried delivery with the
56
+ * same payload is acknowledged as a replay without a second entry, the same
57
+ * `requestId` with a different payload is a conflict, and a failed enqueue
58
+ * leaves no claim behind so the hub's retry is accepted. `ask-reply` is the
59
+ * caller side: the row `recordRemoteSessionAsk` wrote when the ask went out
60
+ * says which room (and thread) the answer belongs in.
61
+ */
62
+ export declare function deliverRemoteSessionInbox(args: {
63
+ topic: Pick<TopicDto, "id" | "title" | "agent">;
64
+ /** Execution principal the inbox entry is queued under (a participant). */
65
+ userId: string;
66
+ delivery: RemoteSessionInboxDelivery;
67
+ }): Promise<RemoteSessionInboxOutcome>;
68
+ type AskReplyDeliverer = typeof import("./turn-runner").deliverAskCallbackToCaller;
69
+ /** Test seam: replace the caller-room injection (to fail it, or to observe it). */
70
+ export declare function setRemoteSessionAskReplyDeliverer(next: AskReplyDeliverer | null): void;
71
+ /**
72
+ * Re-run deliveries a previous process (or a hung one) left `processing`
73
+ * past their lease. Called from the periodic maintenance pass, and at startup
74
+ * with `includeLive` (a fresh process knows no lease is really held). An ask-reply whose ask row is gone can only be a completed delivery
75
+ * whose completion did not persist (impossible by construction, but cheap to
76
+ * tolerate): it is completed. Claims of the other kinds complete in the same
77
+ * transaction as their enqueue, so an expired `processing` one is a claim
78
+ * whose enqueue never happened — released, so the hub's retry is accepted.
79
+ */
80
+ export declare function recoverRemoteSessionInbox(now?: number, options?: {
81
+ includeLive?: boolean;
82
+ }): Promise<number>;
83
+ export {};
@@ -0,0 +1,37 @@
1
+ /** Test seam: make the backoff jitter deterministic. */
2
+ export declare function setRemoteSessionRetryRandom(random: (() => number) | null): void;
3
+ export interface HubRemoteReplyRoute {
4
+ via: "hub";
5
+ hubUrl: string;
6
+ /** One-shot `rsr1.` reply token, verified by the hub only. */
7
+ token: string;
8
+ /** Origin node's name, for the "[Reply from node/room]" label on the caller side. */
9
+ nodeName: string;
10
+ /** Caller's node topic id, as the hub recorded it; informational on this side. */
11
+ topicId: string;
12
+ requestId: string;
13
+ }
14
+ /**
15
+ * Queue the answer and try to post it right away. Always durable, hence
16
+ * always true. The outbox insert and the removal of the durable ask-callback
17
+ * row (`remote_ask_callbacks`, kept by `resolveAskCallback` for hub routes)
18
+ * are one transaction: at no point is there neither a callback nor an outbox
19
+ * row, so a crash anywhere leaves either the startup "interrupted" error or
20
+ * the real answer to be posted — never silence.
21
+ */
22
+ export declare function deliverHubRemoteReply(route: HubRemoteReplyRoute, fromLabel: string, replyText: string, kind: "reply" | "error"): Promise<boolean>;
23
+ /** Post every due answer once. Concurrent callers share one pass. */
24
+ export declare function flushRemoteSessionReplyOutbox(now?: number): Promise<void>;
25
+ /**
26
+ * One maintenance pass: flush due answers, forget inbox claims past their
27
+ * 24 h TTL and caller asks past the 15 min pending-ask TTL (and the in-memory
28
+ * ask callbacks past theirs), then re-run inbox deliveries whose lease
29
+ * expired. Returns what was purged, for tests and logs.
30
+ */
31
+ export declare function runRemoteSessionMaintenance(now?: number): Promise<{
32
+ claims: number;
33
+ asks: number;
34
+ recovered: number;
35
+ }>;
36
+ /** Periodic retry + maintenance loop; returns a stop function. */
37
+ export declare function startRemoteSessionReplyOutboxWorker(intervalMs?: number): () => void;
@@ -5,7 +5,7 @@ import { type StreamAgentOutcome } from "./turn-event-stream";
5
5
  import { type AiTurnTopic } from "./turn-session";
6
6
  import { type UserTurnEnvelope } from "./user-turn-envelope";
7
7
  import type { PendingAskUserId } from "../storage/session-asks";
8
- import type { AgentKind, EffortLevel, PeerRuntimeBridgeContext, UnifiedEvent } from "../types";
8
+ import type { ActorTopicScope, AgentKind, EffortLevel, PeerRuntimeBridgeContext, RemoteSessionGrant, UnifiedEvent } from "../types";
9
9
  import type { MessageDto, TopicDto } from "../types/api";
10
10
  export * from "../agents/model-catalog";
11
11
  export * from "./attachments";
@@ -49,14 +49,19 @@ type AskPendingFileRef = {
49
49
  sourceLabel?: string;
50
50
  };
51
51
  /** Caller-side injection of an ask reply — delivers the target AI's answer (or
52
- * error) back into the caller topic, triggering its AI when one is invited. */
52
+ * error) back into the caller topic, triggering its AI when one is invited.
53
+ * `options.onRecorded` runs inside the same storage transaction as the durable
54
+ * room record (the appended reply message), so a caller that must consume its
55
+ * own bookkeeping exactly when the answer is durable can do so atomically. */
53
56
  export declare function deliverAskCallbackToCaller(pending: AskPendingFileRef & {
54
57
  requestId: string;
55
58
  contextId?: string;
56
59
  callerTopicId: string;
57
60
  callerThreadRootId?: string;
58
61
  callerUserId: string;
59
- }, sourceLabel: string, body: string, kind: "reply" | "error"): Promise<boolean>;
62
+ }, sourceLabel: string, body: string, kind: "reply" | "error", options?: {
63
+ onRecorded?: () => void;
64
+ }): Promise<boolean>;
60
65
  export type TopicRolloutReconstruction = {
61
66
  kind: "rebuilt";
62
67
  sessionId: string;
@@ -110,6 +115,10 @@ export interface AiTurnExecutionOptions {
110
115
  origin?: string;
111
116
  /** Product actor identity when the node executes as a shared principal. */
112
117
  actorUserId?: string;
118
+ /** Host-asserted rooms the actor may reach; absent confines cross-room tools. */
119
+ actorTopicScope?: ActorTopicScope;
120
+ /** Hub-issued per-turn remote session-comm grant; absent keeps it fail-closed. */
121
+ remoteSession?: RemoteSessionGrant;
113
122
  /** Origin node for transcript echo suppression. */
114
123
  sourceNode?: string;
115
124
  /** Answer inside this thread instead of the room's main flow (S-13). */
@@ -216,6 +225,16 @@ export interface TriggerTopicAiTurnOptions extends AiTurnExecutionOptions {
216
225
  injectSourceNode?: string;
217
226
  injectSourceMessageId?: string;
218
227
  }
228
+ /**
229
+ * Whether a new human message comes from the person a running user turn is
230
+ * answering. Only that person may steer the turn (abort it and fold the new
231
+ * message into a resumed batch); anyone else's message queues behind it. The
232
+ * comparison mirrors the durable merge rule: two turns without a recorded
233
+ * actor are one conversation, but an unrecorded actor never matches a named
234
+ * one — the conservative reading, since the alternative is folding a
235
+ * stranger's message into a turn whose author is unknown.
236
+ */
237
+ export declare function sameTurnActor(runningActorUserId: string | undefined, incomingActorUserId: string | undefined): boolean;
219
238
  export declare function mergeSupersedingUserTurn(running: Pick<RoomQueryControl, "prompt" | "userMessages" | "attachments" | "sessionId">, incoming: {
220
239
  prompt: string;
221
240
  userMessages?: UserTurnEnvelope[];
@@ -1,3 +1,4 @@
1
+ import type { ActorTopicScope, RemoteSessionGrant } from "./types";
1
2
  import type { MessageDto } from "./types/api";
2
3
  export declare const RUNTIME_GATEWAY_VERSION: 1;
3
4
  export declare const RUNTIME_GATEWAY_CONTROL_PATH = "/api/v1/control/runtime/v1";
@@ -30,6 +31,25 @@ export interface RuntimeGatewayTurnInput {
30
31
  userId: string;
31
32
  /** Product-side actor, when it differs from the execution principal. */
32
33
  actorUserId?: string;
34
+ /**
35
+ * The node topic ids `actorUserId` may reach on the receiving node, as the
36
+ * host's membership store sees it. Omitted by hosts that predate it; the
37
+ * node then confines the turn's cross-room tools to the current room.
38
+ */
39
+ actorTopicScope?: ActorTopicScope;
40
+ /**
41
+ * Hub-issued per-turn authority for remote (`node/topic`) session-comm:
42
+ * `{ hubUrl, capability }`. `hubUrl` must be a loopback `http://` or any
43
+ * `https://` origin (≤ 512 chars); `capability` an opaque `rsc1.` bearer
44
+ * (≤ 2 KiB) the node presents back to the hub and cannot verify — it holds
45
+ * no key. It does base64-decode the payload's `e` (expiry) for one purpose,
46
+ * ordering grants when several requests fold into one turn
47
+ * (`remoteSessionGrantExpiry`); that value is untrusted and takes part in no
48
+ * security decision. Omitted
49
+ * by hosts that predate it or have the feature off; the node then keeps
50
+ * remote session-comm fail-closed on the `otium` surface. Malformed → 400.
51
+ */
52
+ remoteSession?: RemoteSessionGrant;
33
53
  actorLabel?: string;
34
54
  vaultUserId?: string;
35
55
  /** Adapter provenance recorded on the canonical message. */
@@ -55,6 +55,7 @@ export interface TopicRow {
55
55
  is_fork: number;
56
56
  is_subagent: number;
57
57
  subagent_report_mode: string | null;
58
+ derived_by_user_id: string | null;
58
59
  visibility: string | null;
59
60
  surface: string | null;
60
61
  surface_scope: string | null;
@@ -205,6 +206,8 @@ export declare function revokeSubagentTellTarget(subagentTopicId: string, target
205
206
  * Direct children move to the deleted topic's parent (or become roots) rather
206
207
  * than retaining a dangling parent id that would break memory-origin lookup.
207
208
  */
209
+ /** Ids of the subagent worker rooms spawned directly from `parentTopicId`. */
210
+ export declare function listSubagentChildTopicIds(parentTopicId: string): string[];
208
211
  export declare function reparentTopicChildren(deletedTopicId: string, replacementParentTopicId: string | null): string[];
209
212
  export declare function addParticipantToDB(topicId: string, userId: string, role: "member" | "owner"): boolean;
210
213
  export declare function removeParticipantFromDB(topicId: string, userId: string): boolean;
@@ -0,0 +1,135 @@
1
+ /** Claims older than this are forgotten; the hub never retries a call this late. */
2
+ export declare const REMOTE_SESSION_INBOX_CLAIM_TTL_MS: number;
3
+ /** A reply the hub has not acknowledged by then is dropped: the caller's pending ask has timed out. */
4
+ export declare const REMOTE_SESSION_REPLY_OUTBOX_TTL_MS: number;
5
+ /** Poll cadence of the reply outbox worker; individual rows back off (see {@link remoteSessionRetryDelayMs}). */
6
+ export declare const REMOTE_SESSION_REPLY_RETRY_MS = 5000;
7
+ /** Backoff ladder for a reply the hub did not accept: 5, 10, 20, 30 s (cap), with jitter. */
8
+ export declare const REMOTE_SESSION_REPLY_BACKOFF_BASE_MS = 5000;
9
+ export declare const REMOTE_SESSION_REPLY_BACKOFF_MAX_MS = 30000;
10
+ /**
11
+ * How long a `processing` claim is held before another delivery (a hub retry
12
+ * or the maintenance pass) may take it over. Longer than any single delivery
13
+ * attempt, so a live process is never raced by its own retry.
14
+ */
15
+ export declare const REMOTE_SESSION_INBOX_CLAIM_LEASE_MS = 60000;
16
+ export type RemoteSessionInboxKind = "tell" | "ask" | "abort" | "ask-reply";
17
+ export type RemoteSessionInboxClaimState = "processing" | "completed";
18
+ /**
19
+ * `claimed`: this caller now holds the `processing` lease (fresh, or taken
20
+ * over from an expired one). `replay`: a `completed` claim with the same
21
+ * payload. `in_progress`: another delivery holds a live lease. `conflict`:
22
+ * the id is bound to a different payload/kind/room.
23
+ */
24
+ export type RemoteSessionInboxClaimOutcome = "claimed" | "replay" | "in_progress" | "conflict";
25
+ /**
26
+ * Delay before retry number `attempts` (1-based: the first retry after the
27
+ * immediate attempt is `attempts = 1`): 5, 10, 20, 30 s and 30 s thereafter,
28
+ * each with ±20 % jitter from `random` (injectable for deterministic tests).
29
+ */
30
+ export declare function remoteSessionRetryDelayMs(attempts: number, random?: () => number): number;
31
+ /** Stable digest of a delivery body, so a retried delivery is recognised as one. */
32
+ export declare function remoteSessionPayloadHash(payload: unknown): string;
33
+ export interface RemoteSessionInboxClaimRecord {
34
+ requestId: string;
35
+ kind: RemoteSessionInboxKind;
36
+ topicId: string;
37
+ payloadHash: string;
38
+ state: RemoteSessionInboxClaimState;
39
+ leaseUntil: number;
40
+ payload: unknown;
41
+ createdAt: number;
42
+ }
43
+ /**
44
+ * Claim one hub delivery as `processing` under a lease. For tell/ask/abort
45
+ * the caller completes it in the same transaction as the enqueue; for an
46
+ * ask-reply it stays `processing` — with `payload` persisted — until the
47
+ * answer is durably in the caller's room, or is released so the hub's retry
48
+ * runs the delivery again.
49
+ */
50
+ export declare function claimRemoteSessionInbox(args: {
51
+ requestId: string;
52
+ kind: RemoteSessionInboxKind;
53
+ topicId: string;
54
+ payloadHash: string;
55
+ /** Persisted while `processing` so an interrupted delivery can be re-run. */
56
+ payload?: unknown;
57
+ now?: number;
58
+ leaseMs?: number;
59
+ /** Take over even a live lease (a fresh process knows nobody holds one). */
60
+ force?: boolean;
61
+ }): RemoteSessionInboxClaimOutcome;
62
+ /** The delivery is durably recorded: replays may now be acknowledged. */
63
+ export declare function completeRemoteSessionInboxClaim(requestId: string, now?: number): boolean;
64
+ export declare function getRemoteSessionInboxClaim(requestId: string): RemoteSessionInboxClaimRecord | null;
65
+ /** `processing` claims whose lease ran out: deliveries a dead process left behind. */
66
+ export declare function listExpiredRemoteSessionInboxClaims(now?: number, options?: {
67
+ includeLive?: boolean;
68
+ }): RemoteSessionInboxClaimRecord[];
69
+ export declare function releaseRemoteSessionInboxClaim(requestId: string): boolean;
70
+ export declare function purgeRemoteSessionInboxClaims(now?: number): number;
71
+ export interface RemoteSessionAskRecord {
72
+ requestId: string;
73
+ callerTopicId: string;
74
+ userId: string;
75
+ fromKey: string;
76
+ toKey: string;
77
+ callerThreadRootId?: string;
78
+ createdAt: number;
79
+ }
80
+ /** Remember an outbound remote ask before the hub is asked to forward it. */
81
+ export declare function recordRemoteSessionAsk(args: Omit<RemoteSessionAskRecord, "createdAt"> & {
82
+ createdAt?: number;
83
+ }): void;
84
+ export declare function getRemoteSessionAsk(requestId: string): RemoteSessionAskRecord | null;
85
+ export declare function deleteRemoteSessionAsk(requestId: string): boolean;
86
+ /** Consume the caller record exactly once: the row is gone after this returns it. */
87
+ export declare function takeRemoteSessionAsk(requestId: string): RemoteSessionAskRecord | null;
88
+ export declare function deleteRemoteSessionAsksForTopic(callerTopicId: string): number;
89
+ export declare function purgeStaleRemoteSessionAsks(now?: number): number;
90
+ export interface RemoteSessionReplyOutboxEntry {
91
+ requestId: string;
92
+ hubUrl: string;
93
+ token: string;
94
+ kind: "reply" | "error";
95
+ replyText: string;
96
+ fromLabel: string;
97
+ createdAt: number;
98
+ attempts: number;
99
+ nextAttemptAt: number;
100
+ lastError?: string;
101
+ }
102
+ /**
103
+ * Queue an answer for the hub. One row per ask: a second answer for the same
104
+ * request (a retry after a partial failure) replaces the first, which is what
105
+ * the hub's one-shot reply token would enforce anyway.
106
+ */
107
+ export declare function upsertRemoteSessionReplyOutbox(args: {
108
+ requestId: string;
109
+ hubUrl: string;
110
+ token: string;
111
+ kind: "reply" | "error";
112
+ replyText: string;
113
+ fromLabel: string;
114
+ createdAt?: number;
115
+ }): void;
116
+ export declare function listRemoteSessionReplyOutbox(args?: {
117
+ now?: number;
118
+ limit?: number;
119
+ due?: boolean;
120
+ }): RemoteSessionReplyOutboxEntry[];
121
+ export declare function deleteRemoteSessionReplyOutbox(requestId: string): boolean;
122
+ /**
123
+ * Record a failed attempt and schedule the next one on the backoff ladder
124
+ * (5, 10, 20, 30 s cap, jittered) — the immediate first attempt is
125
+ * `attempts = 0`, so the first deferral waits ≈5 s. `retryMs` pins the delay.
126
+ */
127
+ export declare function deferRemoteSessionReplyOutbox(args: {
128
+ requestId: string;
129
+ error: string;
130
+ now?: number;
131
+ retryMs?: number;
132
+ random?: () => number;
133
+ }): void;
134
+ /** Drop answers nobody is waiting for any more. Returns what was dropped, for the log. */
135
+ export declare function purgeExpiredRemoteSessionReplyOutbox(now?: number): RemoteSessionReplyOutboxEntry[];
@@ -1,6 +1,6 @@
1
1
  import { type UserTurnEnvelope } from "../runtime/user-turn-envelope";
2
2
  import type { StorageDatabase } from "./storage-contract";
3
- import type { AgentKind, EffortLevel, PeerRuntimeBridgeContext } from "../types";
3
+ import type { ActorTopicScope, AgentKind, EffortLevel, PeerRuntimeBridgeContext, RemoteSessionGrant } from "../types";
4
4
  /** Serializable execution details that must survive a cross-process handoff. */
5
5
  export interface RuntimeUserTurnExecution {
6
6
  runtimeEpoch?: number;
@@ -24,6 +24,10 @@ export interface RuntimeUserTurnExecution {
24
24
  vaultUserId?: string;
25
25
  /** Product actor identity, independent from the canonical execution principal. */
26
26
  actorUserId?: string;
27
+ /** Host-asserted rooms the actor may reach; kept with the row so retries keep it. */
28
+ actorTopicScope?: ActorTopicScope;
29
+ /** Hub-issued per-turn remote session-comm grant; kept with the row like the assertion. */
30
+ remoteSession?: RemoteSessionGrant;
27
31
  /** Newly accepted user texts not yet recorded in the unified conversation log. */
28
32
  conversationPrompts?: string[];
29
33
  /** Number of leading userMessages already present in the unified conversation log. */
@@ -109,4 +113,11 @@ export declare function completeRuntimeUserTurnRequest(topicId: string, requestI
109
113
  /** Cancel work captured before a reset/delete epoch began. */
110
114
  export declare function cancelRuntimeUserTurnRequestsBeforeEpoch(topicId: string, epoch: number): string[];
111
115
  export declare function cancelRuntimeUserTurnRequests(topicId: string): string[];
116
+ /**
117
+ * The request a worker currently holds for `topicId` — claimed or already
118
+ * running — if any. This is the turn a new human message could steer; whether
119
+ * it may is decided by whoever folds the new message (see
120
+ * `submitRuntimeGatewayTurn`).
121
+ */
122
+ export declare function getActiveRuntimeUserTurnRequest(topicId: string): RuntimeUserTurnRequest | null;
112
123
  export declare function getRuntimeUserTurnRequest(topicId: string): RuntimeUserTurnRequest | null;
@@ -41,6 +41,8 @@ export declare class TopicForkCompactionError extends Error {
41
41
  }
42
42
  interface DerivedTopicOptions {
43
43
  name?: string;
44
+ /** Product actor who asked for the derive, when `userId` is a shared principal. */
45
+ derivedByUserId?: string;
44
46
  subagent?: {
45
47
  agent?: AgentKind;
46
48
  model?: string;
@@ -111,6 +111,12 @@ export interface TopicDto {
111
111
  memoryKey?: string;
112
112
  /** True when the topic was created via fork (copies history). */
113
113
  isFork?: boolean;
114
+ /**
115
+ * The person whose turn asked for this spawn/fork, when the node executed it
116
+ * under a shared principal. A host that mirrors the room seeds its owner from
117
+ * this; absent for rooms not derived by an agent tool.
118
+ */
119
+ derivedByUserId?: string;
114
120
  /** True when this topic was spawned by an agent as a subagent worker room. */
115
121
  isSubagent?: boolean;
116
122
  /** Extra tell_session targets granted to this subagent; direct parent is implicit. */
@@ -164,6 +164,42 @@ export interface PeerRuntimeBridgeContext {
164
164
  hostQueryId: string;
165
165
  canSpawnSubagents: boolean;
166
166
  }
167
+ /**
168
+ * The rooms the turn's human actor may reach on this node, asserted by the
169
+ * hub that owns per-person membership for the `otium` surface.
170
+ *
171
+ * Node topic ids, valid on the node the turn was submitted to. `visible` is
172
+ * every room the actor participates in (owner or member); `owned` is the
173
+ * subset the actor owns. The assertion rides the signed per-turn MCP token,
174
+ * so the agent can never widen it. With one, it is authoritative: reachable is
175
+ * exactly the current room plus `visible`, owned exactly `owned` — the node
176
+ * adds nothing of its own, not even subagent lineage. A turn without one
177
+ * (older hub, or a turn no person started: cron, self-schedule, a subagent's
178
+ * spawn/report/follow-up) is fail-closed to the current room plus the node's
179
+ * own subagent lineage (direct parent, `grant_subagent_tell` targets, own
180
+ * child workers).
181
+ */
182
+ export interface ActorTopicScope {
183
+ visibleNodeTopicIds: string[];
184
+ ownedNodeTopicIds: string[];
185
+ }
186
+ /**
187
+ * Hub-issued authority for the `node/topic` branches of `session-comm` on
188
+ * the `otium` surface, one per turn. `capability` is an opaque bearer
189
+ * (`rsc1.<payload>.<hmac>`) only the hub can verify: it binds the person who
190
+ * spoke, the origin room and this turn's request id, and the hub re-checks
191
+ * the person's membership of the origin and target rooms on every call. The
192
+ * node holds no key, so it can neither mint nor verify one; the only thing it
193
+ * reads out of the payload is `e` (expiry), base64-decoded untrusted to order
194
+ * grants when several requests fold into one turn. `hubUrl` is where the
195
+ * node presents it (`/api/v1/session-comm/remote/*`). Absent — an older hub,
196
+ * a hub with the feature off, or a turn no person started (cron,
197
+ * self-schedule, subagent lineage) — remote session-comm stays fail-closed.
198
+ */
199
+ export interface RemoteSessionGrant {
200
+ hubUrl: string;
201
+ capability: string;
202
+ }
167
203
  export interface AgentQueryOptions {
168
204
  agent: AgentKind;
169
205
  prompt: string;
@@ -180,6 +216,10 @@ export interface AgentQueryOptions {
180
216
  userId?: string;
181
217
  /** Product actor identity when execution uses a canonical node principal. */
182
218
  actorUserId?: string;
219
+ /** Hub-asserted rooms the product actor may reach; absent means fail-closed. */
220
+ actorTopicScope?: ActorTopicScope;
221
+ /** Hub-issued per-turn authority for remote (`node/topic`) session-comm. */
222
+ remoteSession?: RemoteSessionGrant;
183
223
  /** Credential namespace when it differs from the execution principal. */
184
224
  vaultUserId?: string;
185
225
  session?: string;
@@ -1 +1 @@
1
- export declare const NEGOTIUM_VERSION = "0.19.2";
1
+ export declare const NEGOTIUM_VERSION = "0.20.0";