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
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The explicit-switch gate behind `set_agent`: an agent may move a topic to
3
+ * another backend only when the *person's* current message asked for it.
4
+ *
5
+ * The decision is derived here, once, from the full prompt on the node that
6
+ * mints the per-turn runtime MCP token, and the token then carries only the
7
+ * result ({@link explicitAgentSwitchTargets}) — a bounded list of agent kinds
8
+ * — instead of the prompt itself. That keeps the token small whatever the
9
+ * prompt's length and means a long message cannot push the phrase past a
10
+ * cap and turn a request the user made into a refusal.
11
+ */
12
+ import { type AgentKind } from "../types";
13
+ /** Whether `prompt` explicitly asks to switch this topic to `agent`. */
14
+ export declare function hasExplicitAgentSwitchRequest(prompt: string | undefined, agent: AgentKind): boolean;
15
+ /**
16
+ * The agents `prompt` explicitly asks to switch to, in {@link SUPPORTED_AGENTS}
17
+ * order — the same test as {@link hasExplicitAgentSwitchRequest}, evaluated for
18
+ * every agent kind over the whole prompt. Empty when nothing was asked for.
19
+ */
20
+ export declare function explicitAgentSwitchTargets(prompt: string | undefined): AgentKind[];
21
+ /**
22
+ * Shape check for the derived field where it crosses a trust boundary (the
23
+ * signed token): a de-duplicated list of known agent kinds. It cannot hold
24
+ * more entries than there are agents, so its size is fixed.
25
+ */
26
+ export declare function isExplicitAgentSwitchTargets(value: unknown): value is AgentKind[];
@@ -1,5 +1,5 @@
1
1
  import { type SharedMcpTool } from "./common";
2
- import { type AgentKind } from "../../types";
2
+ import { type ActorTopicScope, type AgentKind } from "../../types";
3
3
  import type { MessageDto, SubagentCardDto, SubagentReportMode, TopicDto } from "../../types/api";
4
4
  export declare const MAX_SUBAGENT_DEPTH = 2;
5
5
  export interface SubagentLifecycleLimits {
@@ -13,8 +13,18 @@ export interface SpawnSubagentToolContext {
13
13
  queryId?: string;
14
14
  agent: AgentKind;
15
15
  model?: string;
16
+ /** Surface of the room the turn runs in; the actor rules apply on `otium`. */
17
+ surface?: string;
18
+ /**
19
+ * Hub-asserted rooms the person who sent the message may see and owns. On
20
+ * `otium` a human turn carries one and it is authoritative: the management
21
+ * tools list only the asserted-visible workers and act only on the
22
+ * asserted-owned ones. Absent on turns no person started (the spawn, the
23
+ * report back, the follow-up), which keep the room's own lineage.
24
+ */
25
+ actorTopicScope?: ActorTopicScope;
16
26
  }
17
- export type SubagentToolContext = Pick<SpawnSubagentToolContext, "userId" | "topicId">;
27
+ export type SubagentToolContext = Pick<SpawnSubagentToolContext, "userId" | "topicId" | "surface" | "actorTopicScope">;
18
28
  export interface SubagentToolDefinitionOptions {
19
29
  /** Otium owns provider routing, so its public tools inherit execution and omit overrides. */
20
30
  executionOverrides?: boolean;
@@ -1,6 +1,7 @@
1
1
  export { type ArchiverAgentRuntimeHost, type ArchiverConfigHost, type ArchiverHost, type ArchiverMessagingHost, type ArchiverRuntime, type ArchiverStorageHost, createArchiverRuntime, type RunArchiverTurnParams, } from "./archiver";
2
2
  export { type AgentAuthHost, type AuthCheckResult, checkAgentAuth, checkAgentModelAuth, } from "./auth-check";
3
3
  export { acquireCodexSpawnLock, type CodexProcStamp, type CodexTreeHost, type CodexTreeLogger, type CodexTreeManager, type CodexTreeManagerOptions, createCodexTreeManager, findNewCodexChildren, killCodexTrees, killOwnedCodexTreesForShutdown, registerOwnedCodexPids, snapshotCodexChildren, unregisterOwnedCodexPids, withCodexSpawnSerial, } from "./codex-tree-kill";
4
+ export { explicitAgentSwitchTargets, hasExplicitAgentSwitchRequest, isExplicitAgentSwitchTargets, } from "./explicit-agent-switch";
4
5
  export { type AgentForkHelpers, type AgentForkHost, cleanupAgentFork, createAgentForkHelpers, type ForkAgentSessionOptions, type ForkHandle, forkAgentSession, } from "./fork";
5
6
  export { type ActiveTopicArchiveOptions, archiveActiveTopicForMemory, } from "./idle-archiver";
6
7
  export { type AnswerAskUserQuestionResult, type AskUserChoice, type AskUserRuntime, type AskUserRuntimeHost, type AskUserToolContext, createAskUserRuntime, defaultAskUserDurabilityHost, normalizeAskUserChoices, normalizeAskUserQuestionInput, } from "./mcp-tools/ask-user";
@@ -7,8 +7,21 @@ export type SelfConfigField = "agent" | "model" | "effort";
7
7
  export interface SelfConfigContext {
8
8
  topicId: string;
9
9
  userId: string;
10
+ /** Product-side human actor when `userId` is a shared execution principal. */
11
+ actorUserId?: string;
10
12
  cwd?: string;
11
- /** Raw current user request. Used to prevent autonomous MCP agent switches. */
13
+ /**
14
+ * Agents the current user message explicitly asked to switch to, derived
15
+ * server-side from the full prompt (`explicitAgentSwitchTargets`). This is
16
+ * what `set_agent` authorizes against; it rides the signed runtime token in
17
+ * place of the prompt, so its length does not depend on the message.
18
+ */
19
+ explicitAgentSwitchTargets?: readonly AgentKind[];
20
+ /**
21
+ * Raw current user request, for in-process callers that still hold it and
22
+ * did not derive the field above. Ignored when `explicitAgentSwitchTargets`
23
+ * is present.
24
+ */
12
25
  currentUserPrompt?: string;
13
26
  /** Called after a successful set_* so the caller can trigger a follow-up turn. */
14
27
  onConfigChanged?: (field: SelfConfigField) => void;
@@ -93,6 +106,7 @@ export interface SelfConfigAgentSwitchOptions {
93
106
  export interface SelfConfigDerivedTopics {
94
107
  create(sourceTopicId: string, userId: string, copyHistory: boolean, options: {
95
108
  name?: string;
109
+ derivedByUserId?: string;
96
110
  }): Promise<SelfConfigTopic | null>;
97
111
  link(topicId: string): string;
98
112
  isTitleConflict(error: unknown): boolean;
@@ -50,7 +50,12 @@ export interface PeerRuntimeSelfConfigRequest {
50
50
  userId: string;
51
51
  tool: string;
52
52
  input: Record<string, unknown>;
53
- currentUserPrompt?: string;
53
+ /**
54
+ * Agents the current user message explicitly asked to switch to, derived
55
+ * on the executing node from the full prompt; the hub authorizes
56
+ * `set_agent` against it. The raw prompt is not carried.
57
+ */
58
+ explicitAgentSwitchTargets?: readonly AgentKind[];
54
59
  }
55
60
  export interface PeerRuntimeBridge {
56
61
  spawnSubagent(request: PeerRuntimeSpawnRequest): Promise<McpToolResult>;
@@ -7,23 +7,77 @@
7
7
  * never trusts the agent to say who it is. Ported from otium runtime-api
8
8
  * `mcp/runtime-server.ts` (transport-agnostic parts only).
9
9
  */
10
- import { type AgentKind, type PeerRuntimeBridgeContext } from "../types";
10
+ import { type ActorTopicScope, type AgentKind, type PeerRuntimeBridgeContext, type RemoteSessionGrant } from "../types";
11
11
  export declare const RUNTIME_MCP_KEY = "runtime";
12
12
  export declare const RUNTIME_MCP_BASE_PATH = "/mcp/runtime";
13
13
  export declare const HOSTED_MCP_SURFACES: readonly ["task", "decision", "token-stats", "system-health", "vault", "wiki", "skills", "session-comm", "agent-health"];
14
14
  export type HostedMcpSurface = (typeof HOSTED_MCP_SURFACES)[number];
15
+ /**
16
+ * Hard ceiling on the length of a built-in MCP URL (path plus `?token=...`).
17
+ *
18
+ * The signed per-turn token rides the URL query of an `http://127.0.0.1`
19
+ * request, and `Bun.serve` answers 431 once the request line is too long:
20
+ * measured on Bun 1.3.14 with a plain `fetch`, a 16,205-character URL is
21
+ * served (200) and a 16,305-character one is refused (431). The budget stays
22
+ * 1,869 characters under the last known-good length so the server, the
23
+ * agent's own client and a slightly different Bun release all have room.
24
+ *
25
+ * Real sizes (UUID ids, base64url growth of 4/3 on the JSON payload):
26
+ * - runtime token, no assertion, every optional field set (peer bridge,
27
+ * thread, 64-char title, workspace cwd, all three explicit-switch
28
+ * targets): ~1,150-character URL;
29
+ * - the same with the largest assertion `validateActorTopicScope` admits
30
+ * (8,159 bytes of JSON = 208 UUIDs): 12,052–12,055 characters, under this
31
+ * budget with ~2,280 characters to spare for an unusually long cwd or title;
32
+ * the hosted tokens (`buildHostedMcpSpec`) with the same assertion measure
33
+ * 12,100–12,118, so neither variant is the "small" one.
34
+ * The token has no free-text field: the user's prompt never rides it. It used
35
+ * to, and an uncapped prompt made the assertion cap meaningless (3,000 Korean
36
+ * characters on top of the maximal assertion gave a 24,009-character URL and
37
+ * 10,000 gave 52,009 — every built-in MCP unreachable for that turn), while a
38
+ * capped one broke `set_agent` for any request phrased after the cap. The
39
+ * prompt's only consumer was that gate, so the node now derives the gate's
40
+ * answer from the full prompt when it mints the token
41
+ * (`explicitAgentSwitchTargets`, at most three agent names) and signs that.
42
+ *
43
+ * Over budget, {@link buildRuntimeMcpSpec} throws
44
+ * {@link McpUrlBudgetExceededError} rather than minting a URL that will 431.
45
+ * Nothing is dropped or trimmed to fit: every remaining field either
46
+ * authorizes (ids, assertion, switch targets) or changes behaviour (thread,
47
+ * capabilities, bridge), and a token missing one would widen or alter the
48
+ * turn, not narrow it.
49
+ */
50
+ export declare const MCP_URL_BUDGET_CHARS: number;
51
+ export declare class McpUrlBudgetExceededError extends Error {
52
+ readonly surface: string;
53
+ readonly urlLength: number;
54
+ constructor(surface: string, urlLength: number);
55
+ }
15
56
  export interface RuntimeMcpContext {
16
57
  /** Canonical principal authorized against this node's topic roster. */
17
58
  userId: string;
18
59
  /** Product-side human actor when it differs from the execution principal. */
19
60
  actorUserId?: string;
61
+ /**
62
+ * Hub-asserted rooms `actorUserId` may reach on this node. Signed with the
63
+ * rest of the context and authoritative when present (no lineage is added);
64
+ * absent means the tools reach only the current room plus its own subagent
65
+ * lineage.
66
+ */
67
+ actorTopicScope?: ActorTopicScope;
20
68
  topicId: string;
21
69
  topicTitle: string;
22
70
  queryId?: string;
23
71
  cwd: string;
24
72
  agent: AgentKind;
25
73
  model?: string;
26
- currentUserPrompt?: string;
74
+ /**
75
+ * Agents the current user message explicitly asked to switch to, derived
76
+ * from the full prompt at mint time (`explicitAgentSwitchTargets`). Signed
77
+ * with the rest of the context, so the agent cannot grant itself a switch;
78
+ * absent or empty means `set_agent` is refused this turn.
79
+ */
80
+ explicitAgentSwitchTargets?: AgentKind[];
27
81
  autoContinue?: boolean;
28
82
  /** Capability minted by the adapter. Visual tools are absent unless true. */
29
83
  visualTools?: boolean;
@@ -43,6 +97,19 @@ export interface RuntimeMcpContext {
43
97
  /** Signed identity/capability context shared by hosted built-in MCP surfaces. */
44
98
  export interface HostedMcpContext {
45
99
  userId: string;
100
+ /** Product-side human actor when it differs from the execution principal. */
101
+ actorUserId?: string;
102
+ /** Hub-asserted rooms `actorUserId` may reach; see {@link RuntimeMcpContext}. */
103
+ actorTopicScope?: ActorTopicScope;
104
+ /**
105
+ * Hub-issued per-turn authority for remote (`node/topic`) session-comm.
106
+ * Carried by the `session-comm` audience only. Signed with the rest of the
107
+ * context so the agent cannot mint or swap one; the capability inside is a
108
+ * bearer for the hub, which the node cannot verify (it holds no key) and
109
+ * only ever decodes for the untrusted `e` expiry it uses to order grants
110
+ * when several requests fold into one turn.
111
+ */
112
+ remoteSession?: RemoteSessionGrant;
46
113
  topicTitle: string;
47
114
  topicId?: string;
48
115
  queryId?: string;
@@ -1,6 +1,22 @@
1
- import type { AgentKind } from "../../types";
1
+ import type { ActorTopicScope, AgentKind, RemoteSessionGrant } from "../../types";
2
2
  export interface SessionCommContext {
3
3
  userId: string;
4
+ /** Product-side human actor when it differs from the execution principal. */
5
+ actorUserId?: string;
6
+ /**
7
+ * Hub-asserted rooms the actor may reach. Only consulted on the `otium`
8
+ * surface, where this node holds no per-person membership. Authoritative
9
+ * when present (exactly the current room plus the asserted rooms, no
10
+ * lineage); absent there (a turn no person started) means the tools reach
11
+ * only the current room plus its own subagent lineage.
12
+ */
13
+ actorTopicScope?: ActorTopicScope;
14
+ /**
15
+ * Hub-issued per-turn authority for the remote (`node/topic`) branches on
16
+ * the `otium` surface. Opaque to the node; presented to the hub as a bearer.
17
+ * Absent means those branches are fail-closed there.
18
+ */
19
+ remoteSession?: RemoteSessionGrant;
4
20
  currentTopic: string;
5
21
  currentTopicId?: string;
6
22
  /** Thread the calling turn is answering inside, when it is answering in one. */
@@ -0,0 +1,149 @@
1
+ import type { RemoteSessionGrant } from "../../types";
2
+ export declare const REMOTE_SESSION_HUB_BASE_PATH = "/api/v1/session-comm/remote";
3
+ export declare const REMOTE_SESSION_PROTOCOL_VERSION: 1;
4
+ /** The hub's "same requestId still in flight" verdict: retry, do not conclude. */
5
+ export declare const HUB_IN_PROGRESS_CODE = "in_progress";
6
+ export interface RemoteSessionTarget {
7
+ node: string;
8
+ topic: string;
9
+ }
10
+ export interface RemoteSessionFromLabel {
11
+ /** `kind:title` of the origin room, as `session-comm` labels senders. */
12
+ key: string;
13
+ title: string;
14
+ }
15
+ export interface RemoteSessionListedRoom {
16
+ name: string;
17
+ /**
18
+ * `null` = the hub says this room has no AI. Absent on `/peek`, whose
19
+ * entries carry only name + status (interface §2.2) — the node then keeps
20
+ * the room, having nothing that says otherwise.
21
+ */
22
+ agent?: string | null;
23
+ /**
24
+ * v1: "active" when the hub sees a turn in flight, otherwise "ready".
25
+ * Optional on `/sessions`, **required** on `/peek` — that is the whole
26
+ * answer a peek gives, and an absent one would read as idle.
27
+ */
28
+ status?: "active" | "ready";
29
+ description?: string | null;
30
+ role?: "owner" | "member";
31
+ }
32
+ /**
33
+ * One node in a listing: its rooms, or why the hub could not answer for it —
34
+ * exactly one of the two, never both and never neither (interface §2.1).
35
+ */
36
+ export type RemoteSessionNodeListing = {
37
+ node: string;
38
+ sessions: RemoteSessionListedRoom[];
39
+ error?: undefined;
40
+ } | {
41
+ node: string;
42
+ sessions?: undefined;
43
+ error: string;
44
+ };
45
+ export interface RemoteSessionPendingAsk {
46
+ to: string;
47
+ requestId: string;
48
+ status: "forwarded" | "reply_pending";
49
+ }
50
+ export type RemoteSessionCallError = {
51
+ ok: false;
52
+ /** Human-readable, safe to show the agent verbatim. */
53
+ error: string;
54
+ /** HTTP status the hub answered with; absent when it did not answer at all. */
55
+ status?: number;
56
+ code?: string;
57
+ /** The request may have been delivered (a response timed out after sending). */
58
+ uncertain?: boolean;
59
+ };
60
+ export type RemoteSessionsResult = {
61
+ ok: true;
62
+ nodes: RemoteSessionNodeListing[];
63
+ } | RemoteSessionCallError;
64
+ export type RemoteSessionPeekResult = {
65
+ ok: true;
66
+ nodes: RemoteSessionNodeListing[];
67
+ pendingAsks: RemoteSessionPendingAsk[];
68
+ } | RemoteSessionCallError;
69
+ export type RemoteSessionDeliveryResult = {
70
+ ok: true;
71
+ requestId: string;
72
+ replayed: boolean;
73
+ } | RemoteSessionCallError;
74
+ export type RemoteSessionHubFetch = (input: string, init: RequestInit) => Promise<Response>;
75
+ /** Test seam: replace the transport without an HTTP server. */
76
+ export declare function setRemoteSessionHubFetch(next: RemoteSessionHubFetch | null): void;
77
+ /**
78
+ * The v1 success envelope, checked exactly: `ok === true`, `v === 1`, and
79
+ * the fields the operation promises with their types. Anything else on a
80
+ * 2xx — an HTML page, a JSON error with the wrong `v`, a missing `ok` — is
81
+ * not the hub's answer and must not be treated as one.
82
+ */
83
+ export type HubEnvelopeShape = "sessions" | "peek" | "delivery" | "reply";
84
+ /**
85
+ * The parsed v1 success payload, or `null` for anything that is not it.
86
+ *
87
+ * `null` is not "an empty answer": every caller turns it into a protocol
88
+ * failure, which is retried and then reported as unconfirmed, exactly like a
89
+ * transport failure.
90
+ */
91
+ export type HubSuccessEnvelope = {
92
+ shape: "sessions";
93
+ nodes: RemoteSessionNodeListing[];
94
+ } | {
95
+ shape: "peek";
96
+ nodes: RemoteSessionNodeListing[];
97
+ pendingAsks: RemoteSessionPendingAsk[];
98
+ } | {
99
+ shape: "delivery";
100
+ replayed: boolean;
101
+ } | {
102
+ shape: "reply";
103
+ replayed: boolean;
104
+ };
105
+ export declare function validateHubSuccessEnvelope(body: unknown, shape: HubEnvelopeShape): HubSuccessEnvelope | null;
106
+ /** Rooms on other nodes the person who spoke may address, grouped by node. */
107
+ export declare function hubRemoteSessions(grant: RemoteSessionGrant): Promise<RemoteSessionsResult>;
108
+ /** Remote running/idle view plus this turn's asks the hub still holds. */
109
+ export declare function hubRemotePeek(grant: RemoteSessionGrant): Promise<RemoteSessionPeekResult>;
110
+ export declare function hubRemoteTell(grant: RemoteSessionGrant, args: {
111
+ requestId: string;
112
+ to: RemoteSessionTarget;
113
+ message: string;
114
+ depth: number;
115
+ fromLabel: RemoteSessionFromLabel;
116
+ }): Promise<RemoteSessionDeliveryResult>;
117
+ export declare function hubRemoteAsk(grant: RemoteSessionGrant, args: {
118
+ requestId: string;
119
+ to: RemoteSessionTarget;
120
+ message: string;
121
+ fromDepth: number;
122
+ fromLabel: RemoteSessionFromLabel;
123
+ }): Promise<RemoteSessionDeliveryResult>;
124
+ export declare function hubRemoteAbort(grant: RemoteSessionGrant, args: {
125
+ requestId: string;
126
+ to: RemoteSessionTarget;
127
+ }): Promise<RemoteSessionDeliveryResult>;
128
+ /**
129
+ * Post an ask's answer to the hub with the one-shot reply token the hub put
130
+ * in the inbox entry. Returns whether the outbox row may be dropped: the hub
131
+ * accepted it (or already had it) with the exact v1 envelope, or gave a final
132
+ * answer that no retry can change (bad/expired token, unknown request).
133
+ * Transport failures, 5xx, 429, `409 in_progress` and a 2xx without the
134
+ * envelope keep the row for the outbox worker.
135
+ */
136
+ export declare function hubRemoteReply(args: {
137
+ hubUrl: string;
138
+ token: string;
139
+ requestId: string;
140
+ kind: "reply" | "error";
141
+ replyText: string;
142
+ fromLabel: string;
143
+ }): Promise<{
144
+ settled: true;
145
+ replayed: boolean;
146
+ } | {
147
+ settled: false;
148
+ error: string;
149
+ }>;
@@ -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 declare const MAX_PEER_MESSAGE_LENGTH = 10000;
@@ -6,6 +6,8 @@
6
6
  * changing tool contracts. On a standalone node every remote call fails
7
7
  * gracefully and `peerSessionsForUser` contributes nothing to peek listings.
8
8
  */
9
+ import { type HubRemoteReplyRoute } from "../../runtime/remote-session-reply-outbox";
10
+ export type { HubRemoteReplyRoute };
9
11
  export interface PeerForwardArgs {
10
12
  action: "tell" | "ask" | "abort";
11
13
  toNode: string;
@@ -27,13 +29,32 @@ export type PeerForwardResult = {
27
29
  ok: false;
28
30
  error: string;
29
31
  };
30
- export interface RemoteReplyRoute {
32
+ /** Legacy adapter-owned route: the answer goes back over the Central peer protocol. */
33
+ export interface PeerRemoteReplyRoute {
34
+ via?: undefined;
31
35
  nodeName: string;
32
36
  nodeCellId: string;
33
37
  topicId: string;
34
38
  userId: string;
35
39
  requestId: string;
36
40
  }
41
+ /**
42
+ * Where a remote ask's answer goes. A hub-routed ask (`via: "hub"`) carries
43
+ * the hub URL and the hub's one-shot reply token and needs no adapter: core
44
+ * posts the answer itself from a durable outbox. The legacy peer route stays
45
+ * for the adapter bridge.
46
+ */
47
+ export type RemoteReplyRoute = PeerRemoteReplyRoute | HubRemoteReplyRoute;
48
+ export declare function isHubRemoteReplyRoute(route: RemoteReplyRoute): route is HubRemoteReplyRoute;
49
+ /**
50
+ * Strict check for a route read from an inbox entry or back from storage.
51
+ * The route names where a bearer (`token`) will be POSTed, so `hubUrl` obeys
52
+ * exactly the turn grant's rule (`normalizeHubUrl`: https, or loopback http;
53
+ * no credentials/query/fragment; ≤ 512 chars) and the token must be shaped
54
+ * like an `rsr1` token within the capability length cap. Anything else is
55
+ * not a route at all.
56
+ */
57
+ export declare function parseHubRemoteReplyRoute(value: unknown): HubRemoteReplyRoute | null;
37
58
  export interface PeerSessionBridge {
38
59
  forward(args: PeerForwardArgs): Promise<PeerForwardResult>;
39
60
  /**
@@ -42,7 +63,7 @@ export interface PeerSessionBridge {
42
63
  * workspace's nodes, which leaks one workspace's topology into another.
43
64
  */
44
65
  sessions(userId: string, sourceQueryId?: string, fromTopicId?: string): Promise<PeerSessionsResult>;
45
- reply(route: RemoteReplyRoute, sourceTitle: string, replyText: string, kind: "reply" | "error"): Promise<boolean>;
66
+ reply(route: PeerRemoteReplyRoute, sourceTitle: string, replyText: string, kind: "reply" | "error"): Promise<boolean>;
46
67
  }
47
68
  export declare function registerPeerSessionBridge(bridge: PeerSessionBridge): () => void;
48
69
  export declare function forwardToPeer(args: PeerForwardArgs): Promise<PeerForwardResult>;
@@ -43,6 +43,12 @@ export interface SessionTargetCatalogHost<TAgent extends string = string> {
43
43
  * surface: terminal with terminal, telegram with telegram, otium with otium.
44
44
  */
45
45
  readonly currentSurface?: string;
46
+ /**
47
+ * Drop rows with no AI agent entirely instead of listing them as targets
48
+ * that every messaging tool then refuses. The current room and manager rooms
49
+ * are always dropped; this adds AI-off rooms for surfaces that want it.
50
+ */
51
+ readonly excludeAgentless?: boolean;
46
52
  readonly isAgent: (value: string | null) => value is TAgent;
47
53
  }
48
54
  export interface SessionTargetCatalog<TAgent extends string = string> {
@@ -1,7 +1,7 @@
1
1
  import { type RuntimeMcpScope } from "./mcp-catalog-policy";
2
2
  import { browserOwnerCapability } from "./playwright/capability";
3
3
  import { buildPlaywrightMcpTransport, CODEX_BROWSER_CAPABILITY_ENV } from "./playwright/mcp-transport";
4
- import type { AgentKind, AgentQueryOptions, PeerRuntimeBridgeContext } from "../types";
4
+ import type { ActorTopicScope, AgentKind, AgentQueryOptions, PeerRuntimeBridgeContext, RemoteSessionGrant } from "../types";
5
5
  export type { RuntimeMcpScope } from "./mcp-catalog-policy";
6
6
  /**
7
7
  * Build the stdio transport spec for a Otium MCP server entry.
@@ -67,6 +67,10 @@ export interface RuntimeMcpBuildContext {
67
67
  userId: string;
68
68
  /** Product actor identity when it differs from the execution principal. */
69
69
  actorUserId?: string;
70
+ /** Hub-asserted rooms the product actor may reach; forwarded into signed tokens. */
71
+ actorTopicScope?: ActorTopicScope;
72
+ /** Hub-issued per-turn remote session-comm grant; session-comm only. */
73
+ remoteSession?: RemoteSessionGrant;
70
74
  /** Vault namespace when credentials belong to a different principal. */
71
75
  vaultUserId?: string;
72
76
  /** "dm" for DM scope, topic/session name for forum/fork. */
@@ -192,6 +196,9 @@ export declare function getDmMcpServers(opts: {
192
196
  */
193
197
  export declare function getManagerMcpServers(opts: {
194
198
  userId: string;
199
+ actorUserId?: string;
200
+ actorTopicScope?: ActorTopicScope;
201
+ remoteSession?: RemoteSessionGrant;
195
202
  session?: string;
196
203
  topicId?: string;
197
204
  queryId?: string;
@@ -215,6 +222,8 @@ export declare function getManagerMcpServers(opts: {
215
222
  export declare function getForumMcpServers(opts: {
216
223
  userId: string;
217
224
  actorUserId?: string;
225
+ actorTopicScope?: ActorTopicScope;
226
+ remoteSession?: RemoteSessionGrant;
218
227
  vaultUserId?: string;
219
228
  session: string;
220
229
  topicId?: string;
@@ -105,6 +105,12 @@ export interface RoomQueryControl {
105
105
  prompt: string;
106
106
  /** Original user submissions represented by prompt, in arrival order. */
107
107
  userMessages?: UserTurnEnvelope[];
108
+ /**
109
+ * Product actor a user turn speaks for, when recorded. Decides whether a
110
+ * later human message may steer this turn: only the same actor's follow-up
111
+ * aborts and folds into it; anyone else's waits its turn in the queue.
112
+ */
113
+ actorUserId?: string;
108
114
  /** Durable request rows whose messages are already represented by userMessages. */
109
115
  durableRequestIds?: string[];
110
116
  /** Attachment ids currently being processed. User-turn preemption carries them forward. */
@@ -0,0 +1,49 @@
1
+ import type { ActorTopicScope } from "../types";
2
+ /**
3
+ * Rooms a turn may reach because of lineage this node itself recorded, not
4
+ * because a person is in them: a subagent's direct parent and the targets an
5
+ * ancestor granted it, and a room's own subagent workers.
6
+ *
7
+ * Lineage stands in for an assertion only when there is none — the turns that
8
+ * manage subagents (the spawn, the report back, the follow-up) are turns no
9
+ * person started, they carry no `actorTopicScope`, and cutting them off would
10
+ * break delegation the moment it began. A turn that *does* carry an assertion
11
+ * never gets lineage on top of it: the hub mirrors a subagent room with its
12
+ * parent's roster, so an owner of the parent is asserted as owner of the child
13
+ * and needs no exception, while a member who is not the owner — or a person
14
+ * speaking from a subagent room an ancestor granted rooms outside that
15
+ * person's own — must not inherit authority the hub did not assert.
16
+ * `canSubagentTellTarget` still applies its own rules on top (status-only,
17
+ * grants).
18
+ */
19
+ export declare function subagentLineageTopicIds(currentTopicId: string | undefined): {
20
+ reachable: Set<string>;
21
+ children: Set<string>;
22
+ };
23
+ /**
24
+ * The rooms cross-room tools may name for this turn.
25
+ *
26
+ * Off the `otium` surface the node owns membership, so nothing narrows the
27
+ * caller's own rooms. On `otium` the hub does, and its assertion is
28
+ * authoritative: with one, exactly the current room plus the asserted visible
29
+ * rooms are reachable — no lineage. Without one (an older hub, or a turn no
30
+ * person started) only the current room and its subagent lineage are
31
+ * reachable (fail-closed).
32
+ */
33
+ export declare function actorReachableTopicIds(input: {
34
+ surface: string | undefined;
35
+ currentTopicId: string | undefined;
36
+ actorTopicScope: ActorTopicScope | undefined;
37
+ }): ReadonlySet<string> | null;
38
+ /**
39
+ * Rooms the actor may abort/restart/delete. With an assertion: exactly the
40
+ * rooms the hub says the actor owns (a parent's subagent workers are among
41
+ * them only if the hub asserted so). Without one: the current room's own
42
+ * subagent workers (a room controls what it delegated), nothing else. Same
43
+ * surface rule as {@link actorReachableTopicIds}.
44
+ */
45
+ export declare function actorOwnedTopicIds(input: {
46
+ surface: string | undefined;
47
+ currentTopicId?: string | undefined;
48
+ actorTopicScope: ActorTopicScope | undefined;
49
+ }): ReadonlySet<string> | null;
@@ -0,0 +1,91 @@
1
+ import type { ActorTopicScope } from "../types";
2
+ /**
3
+ * Hard caps on a hub-supplied room assertion.
4
+ *
5
+ * The assertion is not stored and forgotten: it rides the signed per-turn MCP
6
+ * token, which every hosted built-in MCP server receives in the URL query
7
+ * (`?token=`) of an `http://127.0.0.1` request, and — with
8
+ * `NEGOTIUM_BUILTIN_MCP_TRANSPORT=stdio` — one base64url argv entry of the
9
+ * session-comm child. The transport, not the database, is the tight bound:
10
+ *
11
+ * - `Bun.serve` answers 431 once the request line is too long (Bun 1.3.14:
12
+ * a 16,205-character URL is served, 16,305 is refused). These caps alone
13
+ * do not bound the URL — the token carries other fields — so the whole URL
14
+ * is budgeted at `MCP_URL_BUDGET_CHARS` (14 KiB) in `runtime-spec.ts`,
15
+ * where the numbers live. The 8 KiB assertion below becomes 10,924
16
+ * base64url characters at most; with every other runtime-token field at
17
+ * its largest (the prompt itself is not in the token — only the derived
18
+ * `explicitAgentSwitchTargets`, at most three agent names) the URL is
19
+ * ≤ ~13.4 KB.
20
+ * - argv: `encodeActorTopicScopeArg` is the assertion alone, ≤ 10,924
21
+ * characters, far below Linux `MAX_ARG_STRLEN` (128 KiB) for one argument
22
+ * and macOS `ARG_MAX` (1 MiB) overall. The encoder re-validates before it
23
+ * encodes, so an in-process caller that bypassed the gateway parser cannot
24
+ * put an unbounded object into argv either.
25
+ *
26
+ * With UUID room ids (39 bytes each serialized) the byte cap admits roughly
27
+ * 208 ids across both lists; the per-list count cap bounds the work done on
28
+ * an assertion before its size is known, and the id length cap keeps a single
29
+ * id from being the whole budget. Raising these means moving the assertion
30
+ * out of the token (server-side per-turn context), not editing the numbers.
31
+ */
32
+ export declare const ACTOR_TOPIC_SCOPE_LIMITS: Readonly<{
33
+ /** Ids per list, counted before de-duplication. */
34
+ maxIdsPerList: 200;
35
+ /** Characters per id, after trimming. */
36
+ maxIdLength: 128;
37
+ /** UTF-8 bytes of the normalized assertion as JSON. */
38
+ maxSerializedBytes: number;
39
+ }>;
40
+ export type ActorTopicScopeValidation = {
41
+ ok: true;
42
+ scope: ActorTopicScope | undefined;
43
+ } | {
44
+ ok: false;
45
+ error: string;
46
+ };
47
+ /**
48
+ * Validate a hub-supplied room assertion and say why it failed.
49
+ *
50
+ * `undefined` in means `undefined` out (no assertion, fail-closed downstream);
51
+ * anything else must be exactly `{ visibleNodeTopicIds, ownedNodeTopicIds }`
52
+ * — a plain object with those two own keys and nothing else (so a stray
53
+ * `__proto__` or `constructor` key is a rejection, not a property), each a
54
+ * list of non-empty strings within {@link ACTOR_TOPIC_SCOPE_LIMITS} — or it is
55
+ * rejected, so a malformed assertion can never be read as "everything".
56
+ */
57
+ export declare function validateActorTopicScope(value: unknown): ActorTopicScopeValidation;
58
+ /**
59
+ * Validate a hub-supplied room assertion.
60
+ *
61
+ * `undefined` in means `undefined` out (no assertion, fail-closed downstream);
62
+ * anything else must pass {@link validateActorTopicScope} or it is rejected
63
+ * with `null`. Every path an assertion can enter by — the gateway body, the
64
+ * signed MCP tokens, the stdio argv — goes through this one parser, so the
65
+ * limits cannot drift between them.
66
+ */
67
+ export declare function parseActorTopicScope(value: unknown): ActorTopicScope | undefined | null;
68
+ export declare function isActorTopicScope(value: unknown): value is ActorTopicScope;
69
+ /**
70
+ * Read a validated assertion out of a persisted or signed context. Anything
71
+ * that does not validate collapses to "no assertion" rather than throwing, so
72
+ * a stale row cannot break a turn — it only narrows it to what a turn without
73
+ * an assertion reaches: the current room plus its own subagent lineage.
74
+ */
75
+ export declare function actorTopicScopeFrom(value: unknown): ActorTopicScope | undefined;
76
+ /**
77
+ * The strictest assertion two requests agree on: an id is kept only when both
78
+ * assert it, and a request without an assertion leaves the result without one
79
+ * (fail-closed). Used when several pending requests of one actor fold into a
80
+ * single turn, so the merged turn never reaches a room one of them could not.
81
+ */
82
+ export declare function intersectActorTopicScopes(scopes: ReadonlyArray<ActorTopicScope | undefined>): ActorTopicScope | undefined;
83
+ /**
84
+ * Argv-safe encoding for the stdio session-comm server (`--actor-topic-scope=`).
85
+ * Bounded by {@link ACTOR_TOPIC_SCOPE_LIMITS}: 8,192 bytes of JSON become at
86
+ * most 10,924 base64url characters, see there. The input is put through
87
+ * {@link validateActorTopicScope} first and an invalid or oversized assertion
88
+ * throws — it is never truncated (which would narrow the turn silently) nor
89
+ * passed on (which would let a typed in-process caller overflow argv).
90
+ */
91
+ export declare function encodeActorTopicScopeArg(scope: ActorTopicScope): string;