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
@@ -17,6 +17,240 @@ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
  var __promiseAll = (args) => Promise.all(args);
18
18
  var __require = import.meta.require;
19
19
 
20
+ // ../../packages/core/src/runtime/actor-topic-scope.ts
21
+ function idList(value, name) {
22
+ if (!Array.isArray(value))
23
+ return `${name} must be an array of topic ids`;
24
+ if (value.length > ACTOR_TOPIC_SCOPE_LIMITS.maxIdsPerList) {
25
+ return `${name} has ${value.length} ids; at most ${ACTOR_TOPIC_SCOPE_LIMITS.maxIdsPerList} are allowed`;
26
+ }
27
+ const ids = new Set;
28
+ for (const item of value) {
29
+ if (typeof item !== "string")
30
+ return `${name} must contain only strings`;
31
+ const id = item.trim();
32
+ if (!id)
33
+ return `${name} must not contain empty ids`;
34
+ if (id.length > ACTOR_TOPIC_SCOPE_LIMITS.maxIdLength) {
35
+ return `${name} contains an id longer than ${ACTOR_TOPIC_SCOPE_LIMITS.maxIdLength} characters`;
36
+ }
37
+ ids.add(id);
38
+ }
39
+ return [...ids];
40
+ }
41
+ function validateActorTopicScope(value) {
42
+ if (value === undefined)
43
+ return { ok: true, scope: undefined };
44
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
45
+ return {
46
+ ok: false,
47
+ error: "actorTopicScope must be { visibleNodeTopicIds: string[], ownedNodeTopicIds: string[] }"
48
+ };
49
+ }
50
+ const proto = Object.getPrototypeOf(value);
51
+ if (proto !== Object.prototype && proto !== null) {
52
+ return { ok: false, error: "actorTopicScope must be a plain object" };
53
+ }
54
+ const keys = Object.keys(value);
55
+ const unknown = keys.filter((key) => !SCOPE_KEYS.includes(key));
56
+ if (unknown.length || keys.length !== SCOPE_KEYS.length) {
57
+ return {
58
+ ok: false,
59
+ error: unknown.length ? `actorTopicScope has unexpected key(s): ${unknown.join(", ")}` : "actorTopicScope must have both visibleNodeTopicIds and ownedNodeTopicIds"
60
+ };
61
+ }
62
+ const record = value;
63
+ const visible = idList(record.visibleNodeTopicIds, "actorTopicScope.visibleNodeTopicIds");
64
+ if (typeof visible === "string")
65
+ return { ok: false, error: visible };
66
+ const owned = idList(record.ownedNodeTopicIds, "actorTopicScope.ownedNodeTopicIds");
67
+ if (typeof owned === "string")
68
+ return { ok: false, error: owned };
69
+ const scope = { visibleNodeTopicIds: visible, ownedNodeTopicIds: owned };
70
+ const bytes = Buffer.byteLength(JSON.stringify(scope), "utf-8");
71
+ if (bytes > ACTOR_TOPIC_SCOPE_LIMITS.maxSerializedBytes) {
72
+ return {
73
+ ok: false,
74
+ error: `actorTopicScope is ${bytes} bytes serialized; at most ${ACTOR_TOPIC_SCOPE_LIMITS.maxSerializedBytes} are allowed`
75
+ };
76
+ }
77
+ return { ok: true, scope };
78
+ }
79
+ function parseActorTopicScope(value) {
80
+ const validated = validateActorTopicScope(value);
81
+ return validated.ok ? validated.scope : null;
82
+ }
83
+ function actorTopicScopeFrom(value) {
84
+ return parseActorTopicScope(value) ?? undefined;
85
+ }
86
+ function intersectActorTopicScopes(scopes) {
87
+ if (scopes.length === 0 || scopes.some((scope) => scope === undefined))
88
+ return;
89
+ const [first, ...rest] = scopes;
90
+ const keep = (key) => first[key].filter((id) => rest.every((scope) => scope[key].includes(id)));
91
+ return {
92
+ visibleNodeTopicIds: keep("visibleNodeTopicIds"),
93
+ ownedNodeTopicIds: keep("ownedNodeTopicIds")
94
+ };
95
+ }
96
+ function encodeActorTopicScopeArg(scope) {
97
+ const validated = validateActorTopicScope(scope);
98
+ if (!validated.ok)
99
+ throw new Error(validated.error);
100
+ if (!validated.scope)
101
+ throw new Error("actorTopicScope is required");
102
+ return Buffer.from(JSON.stringify(validated.scope), "utf-8").toString("base64url");
103
+ }
104
+ var ACTOR_TOPIC_SCOPE_LIMITS, SCOPE_KEYS;
105
+ var init_actor_topic_scope = __esm(() => {
106
+ ACTOR_TOPIC_SCOPE_LIMITS = Object.freeze({
107
+ maxIdsPerList: 200,
108
+ maxIdLength: 128,
109
+ maxSerializedBytes: 8 * 1024
110
+ });
111
+ SCOPE_KEYS = ["visibleNodeTopicIds", "ownedNodeTopicIds"];
112
+ });
113
+
114
+ // ../../packages/core/src/runtime/remote-session-grant.ts
115
+ function normalizeHubUrl(raw, name = "remoteSession.hubUrl") {
116
+ if (raw.length > REMOTE_SESSION_GRANT_LIMITS.maxHubUrlLength) {
117
+ return {
118
+ error: `${name} is longer than ${REMOTE_SESSION_GRANT_LIMITS.maxHubUrlLength} characters`
119
+ };
120
+ }
121
+ let url;
122
+ try {
123
+ url = new URL(raw);
124
+ } catch {
125
+ return { error: `${name} must be an absolute URL` };
126
+ }
127
+ if (url.username || url.password) {
128
+ return { error: `${name} must not carry credentials` };
129
+ }
130
+ if (url.search || url.hash || raw.includes("?") || raw.includes("#")) {
131
+ return { error: `${name} must not carry a query or fragment` };
132
+ }
133
+ if (url.protocol === "http:") {
134
+ if (!LOOPBACK_HOSTS.has(url.hostname)) {
135
+ return { error: `${name} must be https:// or a loopback http:// origin` };
136
+ }
137
+ } else if (url.protocol !== "https:") {
138
+ return { error: `${name} must be https:// or a loopback http:// origin` };
139
+ }
140
+ return { url: url.toString().replace(/\/+$/, "") };
141
+ }
142
+ function validateRemoteSessionGrant(value) {
143
+ if (value === undefined)
144
+ return { ok: true, grant: undefined };
145
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
146
+ return { ok: false, error: "remoteSession must be { hubUrl: string, capability: string }" };
147
+ }
148
+ const proto = Object.getPrototypeOf(value);
149
+ if (proto !== Object.prototype && proto !== null) {
150
+ return { ok: false, error: "remoteSession must be a plain object" };
151
+ }
152
+ const keys = Object.keys(value);
153
+ const unknown = keys.filter((key) => !GRANT_KEYS.includes(key));
154
+ if (unknown.length || keys.length !== GRANT_KEYS.length) {
155
+ return {
156
+ ok: false,
157
+ error: unknown.length ? `remoteSession has unexpected key(s): ${unknown.join(", ")}` : "remoteSession must have both hubUrl and capability"
158
+ };
159
+ }
160
+ const record = value;
161
+ if (typeof record.hubUrl !== "string" || !record.hubUrl.trim()) {
162
+ return { ok: false, error: "remoteSession.hubUrl must be a non-empty string" };
163
+ }
164
+ const hubUrl = normalizeHubUrl(record.hubUrl.trim());
165
+ if ("error" in hubUrl)
166
+ return { ok: false, error: hubUrl.error };
167
+ if (typeof record.capability !== "string" || !record.capability.trim()) {
168
+ return { ok: false, error: "remoteSession.capability must be a non-empty string" };
169
+ }
170
+ const capability = record.capability.trim();
171
+ if (capability.length > REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength) {
172
+ return {
173
+ ok: false,
174
+ error: `remoteSession.capability is ${capability.length} characters; at most ${REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength} are allowed`
175
+ };
176
+ }
177
+ if (!capability.startsWith(REMOTE_SESSION_GRANT_LIMITS.capabilityPrefix)) {
178
+ return {
179
+ ok: false,
180
+ error: `remoteSession.capability must start with "${REMOTE_SESSION_GRANT_LIMITS.capabilityPrefix}"`
181
+ };
182
+ }
183
+ if (!/^rsc1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(capability)) {
184
+ return { ok: false, error: "remoteSession.capability is malformed" };
185
+ }
186
+ return { ok: true, grant: { hubUrl: hubUrl.url, capability } };
187
+ }
188
+ function parseRemoteSessionGrant(value) {
189
+ const validated = validateRemoteSessionGrant(value);
190
+ return validated.ok ? validated.grant : null;
191
+ }
192
+ function remoteSessionGrantFrom(value) {
193
+ return parseRemoteSessionGrant(value) ?? undefined;
194
+ }
195
+ function remoteSessionGrantExpiry(grant) {
196
+ const payload = grant.capability.split(".")[1];
197
+ if (!payload)
198
+ return null;
199
+ try {
200
+ const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
201
+ const exp = decoded?.e;
202
+ return typeof exp === "number" && Number.isFinite(exp) ? exp : null;
203
+ } catch {
204
+ return null;
205
+ }
206
+ }
207
+ function mergeRemoteSessionGrants(grants) {
208
+ if (grants.length === 0 || grants.some((grant) => grant === undefined))
209
+ return;
210
+ const present = grants;
211
+ const hubUrl = present[0].hubUrl;
212
+ if (present.some((grant) => grant.hubUrl !== hubUrl))
213
+ return;
214
+ let chosen = present[present.length - 1];
215
+ let chosenExpiry = remoteSessionGrantExpiry(chosen);
216
+ for (const grant of present) {
217
+ const expiry = remoteSessionGrantExpiry(grant);
218
+ if (expiry !== null && (chosenExpiry === null || expiry > chosenExpiry)) {
219
+ chosen = grant;
220
+ chosenExpiry = expiry;
221
+ }
222
+ }
223
+ return chosen;
224
+ }
225
+ function encodeRemoteSessionGrantArg(grant) {
226
+ const validated = validateRemoteSessionGrant(grant);
227
+ if (!validated.ok)
228
+ throw new Error(validated.error);
229
+ if (!validated.grant)
230
+ throw new Error("remoteSession is required");
231
+ return Buffer.from(JSON.stringify(validated.grant), "utf-8").toString("base64url");
232
+ }
233
+ function decodeRemoteSessionGrantArg(value) {
234
+ try {
235
+ const decoded = JSON.parse(Buffer.from(value, "base64url").toString("utf-8"));
236
+ return parseRemoteSessionGrant(decoded) ?? null;
237
+ } catch {
238
+ return null;
239
+ }
240
+ }
241
+ var REMOTE_SESSION_GRANT_LIMITS, GRANT_KEYS, LOOPBACK_HOSTS, REMOTE_SESSION_REPLY_TOKEN_PATTERN, MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH;
242
+ var init_remote_session_grant = __esm(() => {
243
+ REMOTE_SESSION_GRANT_LIMITS = Object.freeze({
244
+ maxHubUrlLength: 512,
245
+ maxCapabilityLength: 2 * 1024,
246
+ capabilityPrefix: "rsc1."
247
+ });
248
+ GRANT_KEYS = ["hubUrl", "capability"];
249
+ LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
250
+ REMOTE_SESSION_REPLY_TOKEN_PATTERN = /^rsr1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
251
+ MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH = REMOTE_SESSION_GRANT_LIMITS.maxCapabilityLength;
252
+ });
253
+
20
254
  // ../../packages/core/src/types.ts
21
255
  function isAgentKind(value) {
22
256
  return typeof value === "string" && SUPPORTED_AGENTS.includes(value);
@@ -1303,6 +1537,66 @@ var init_vault_tool_policy = __esm(() => {
1303
1537
  DIRECT_VAULT_EXECUTION_TOOLS = new Set(["Bash", "WebFetch"]);
1304
1538
  });
1305
1539
 
1540
+ // ../../packages/core/src/agents/explicit-agent-switch.ts
1541
+ function escapeRegExp2(value2) {
1542
+ return value2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1543
+ }
1544
+ function agentAliases(agent) {
1545
+ switch (agent) {
1546
+ case "codex":
1547
+ return [
1548
+ "codex",
1549
+ "\uCF54\uB371\uC2A4",
1550
+ "gpt-6-luna",
1551
+ "gpt-6-sol",
1552
+ "gpt-5.6-luna",
1553
+ "gpt-5.6-terra",
1554
+ "gpt-5.6-sol",
1555
+ "gpt-6-astra"
1556
+ ];
1557
+ case "claude":
1558
+ return ["claude", "\uD074\uB85C\uB4DC", "sonnet", "opus", "fable"];
1559
+ case "maestro":
1560
+ return [
1561
+ "maestro",
1562
+ "\uB9C8\uC5D0\uC2A4\uD2B8\uB85C",
1563
+ "\uBA54\uC2A4\uD2B8\uB85C",
1564
+ "deepseek",
1565
+ "deepseek-pro",
1566
+ "kimi",
1567
+ "kimi-pro",
1568
+ "kimi-k3",
1569
+ "kimi-code",
1570
+ "kimi-k2.7-code",
1571
+ "\uB525\uC2DC\uD06C",
1572
+ "\uD0A4\uBBF8"
1573
+ ];
1574
+ }
1575
+ }
1576
+ function hasExplicitAgentSwitchRequest(prompt, agent) {
1577
+ if (!prompt?.trim())
1578
+ return false;
1579
+ const text = prompt.toLowerCase().replace(/\s+/g, " ").trim();
1580
+ const target = `(?:${agentAliases(agent).map(escapeRegExp2).join("|")})`;
1581
+ const switchVerb = "(?:\uBC14\uAFD4|\uBC14\uAFD4\uC918|\uBCC0\uACBD|\uBCC0\uACBD\uD574|\uC804\uD658|\uC804\uD658\uD574|\uC124\uC815|\uC124\uC815\uD574|\uC368\uC918|\uC0AC\uC6A9|\uAC00|switch|change|set|use)";
1582
+ const switchSubject = "(?:agent|runtime|model|\uC5D0\uC774\uC804\uD2B8|\uB7F0\uD0C0\uC784|\uBAA8\uB378)";
1583
+ return [
1584
+ new RegExp(`^/(?:agent|runtime)\\s+${target}(?:\\s|$)`, "iu"),
1585
+ new RegExp(`${target}\\s*(?:\uB85C|\uC73C\uB85C)\\s*.{0,16}${switchVerb}`, "iu"),
1586
+ new RegExp(`${switchSubject}.{0,24}${target}.{0,24}${switchVerb}`, "iu"),
1587
+ new RegExp(`${switchVerb}.{0,24}${switchSubject}.{0,24}${target}`, "iu"),
1588
+ new RegExp(`(?:switch|change|set|use).{0,24}${target}`, "iu")
1589
+ ].some((pattern) => pattern.test(text));
1590
+ }
1591
+ function explicitAgentSwitchTargets(prompt) {
1592
+ if (!prompt?.trim())
1593
+ return [];
1594
+ return SUPPORTED_AGENTS.filter((agent) => hasExplicitAgentSwitchRequest(prompt, agent));
1595
+ }
1596
+ var init_explicit_agent_switch = __esm(() => {
1597
+ init_types();
1598
+ });
1599
+
1306
1600
  // ../../packages/core/src/mcp/canonical-bridge-config.ts
1307
1601
  function turnKey(scope) {
1308
1602
  return JSON.stringify([
@@ -1356,18 +1650,26 @@ function issueHostedMcpToken(surface, ctx) {
1356
1650
  return `${payloadPart}.${signTokenPayload(payloadPart)}`;
1357
1651
  }
1358
1652
  function buildRuntimeMcpSpec(agent, ctx) {
1359
- const token = issueRuntimeMcpToken(ctx);
1360
1653
  const base = `http://127.0.0.1:${runtimePort}${RUNTIME_MCP_BASE_PATH}`;
1361
- const query = `token=${encodeURIComponent(token)}`;
1654
+ const query = `token=${encodeURIComponent(issueRuntimeMcpToken(ctx))}`;
1655
+ const url = agent === "codex" ? `${base}/mcp?${query}` : `${base}/sse?${query}`;
1656
+ assertMcpUrlWithinBudget(RUNTIME_MCP_KEY, url, ctx.topicId);
1362
1657
  if (agent === "codex")
1363
- return { url: `${base}/mcp?${query}` };
1658
+ return { url };
1364
1659
  return {
1365
1660
  type: "sse",
1366
- url: `${base}/sse?${query}`,
1661
+ url,
1367
1662
  timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,
1368
1663
  ...agent === "maestro" ? { lifecycle: "turn" } : {}
1369
1664
  };
1370
1665
  }
1666
+ function assertMcpUrlWithinBudget(surface, url, topicId) {
1667
+ if (url.length <= MCP_URL_BUDGET_CHARS)
1668
+ return;
1669
+ const error = new McpUrlBudgetExceededError(surface, url.length);
1670
+ logger.error({ topicId, surface, urlLength: url.length, budget: MCP_URL_BUDGET_CHARS }, "built-in MCP URL exceeds the transport budget; refusing to mint the token");
1671
+ throw error;
1672
+ }
1371
1673
  function hostedMcpCacheIdentity(surface, ctx) {
1372
1674
  let semanticContext;
1373
1675
  switch (surface) {
@@ -1398,6 +1700,9 @@ function hostedMcpCacheIdentity(surface, ctx) {
1398
1700
  case "session-comm":
1399
1701
  semanticContext = {
1400
1702
  userId: ctx.userId,
1703
+ actorUserId: ctx.actorUserId ?? null,
1704
+ actorTopicScope: ctx.actorTopicScope ?? null,
1705
+ remoteSession: ctx.remoteSession ?? null,
1401
1706
  topicTitle: ctx.topicTitle,
1402
1707
  topicId: ctx.topicId ?? null,
1403
1708
  subagentParentTopicId: ctx.subagentParentTopicId ?? null,
@@ -1416,13 +1721,15 @@ function buildHostedMcpSpec(agent, surface, ctx) {
1416
1721
  const token = issueHostedMcpToken(surface, ctx);
1417
1722
  const base = `http://127.0.0.1:${runtimePort}${RUNTIME_MCP_BASE_PATH}/${surface}`;
1418
1723
  const query = `token=${encodeURIComponent(token)}`;
1724
+ const url = agent === "codex" ? `${base}/mcp?${query}` : `${base}/sse?${query}`;
1725
+ assertMcpUrlWithinBudget(surface, url, ctx.topicId);
1419
1726
  if (agent === "codex")
1420
- return { url: `${base}/mcp?${query}` };
1421
- const queryBound = surface === "session-comm" && (ctx.silent === true || ctx.peerBridge !== undefined);
1727
+ return { url };
1728
+ const queryBound = surface === "session-comm" && (ctx.silent === true || ctx.peerBridge !== undefined || ctx.remoteSession !== undefined);
1422
1729
  const lifecycle = queryBound ? "turn" : surface === "session-comm" ? "session" : "process";
1423
1730
  return {
1424
1731
  type: "sse",
1425
- url: `${base}/sse?${query}`,
1732
+ url,
1426
1733
  timeout: CLAUDE_MCP_TOOL_TIMEOUT_MS,
1427
1734
  ...agent === "maestro" ? {
1428
1735
  lifecycle,
@@ -1430,11 +1737,26 @@ function buildHostedMcpSpec(agent, surface, ctx) {
1430
1737
  } : {}
1431
1738
  };
1432
1739
  }
1433
- var RUNTIME_MCP_KEY = "runtime", RUNTIME_MCP_BASE_PATH = "/mcp/runtime", TOKEN_TTL_MS, CLAUDE_MCP_TOOL_TIMEOUT_MS = 600000, runtimePort;
1740
+ var RUNTIME_MCP_KEY = "runtime", RUNTIME_MCP_BASE_PATH = "/mcp/runtime", TOKEN_TTL_MS, CLAUDE_MCP_TOOL_TIMEOUT_MS = 600000, MCP_URL_BUDGET_CHARS, McpUrlBudgetExceededError, runtimePort;
1434
1741
  var init_runtime_spec = __esm(() => {
1742
+ init_explicit_agent_switch();
1435
1743
  init_config();
1744
+ init_logger();
1745
+ init_actor_topic_scope();
1746
+ init_remote_session_grant();
1436
1747
  init_types();
1437
1748
  TOKEN_TTL_MS = 4 * 60 * 60 * 1000;
1749
+ MCP_URL_BUDGET_CHARS = 14 * 1024;
1750
+ McpUrlBudgetExceededError = class McpUrlBudgetExceededError extends Error {
1751
+ surface;
1752
+ urlLength;
1753
+ constructor(surface, urlLength) {
1754
+ super(`built-in MCP URL for "${surface}" is ${urlLength} characters; the transport allows at most ${MCP_URL_BUDGET_CHARS}`);
1755
+ this.surface = surface;
1756
+ this.urlLength = urlLength;
1757
+ this.name = "McpUrlBudgetExceededError";
1758
+ }
1759
+ };
1438
1760
  runtimePort = NEGOTIUM_PORT;
1439
1761
  });
1440
1762
 
@@ -2186,6 +2508,9 @@ function initializeApiTopicsSchema() {
2186
2508
  if (!tableColumns("api_topics").has("subagent_report_mode")) {
2187
2509
  db.exec("ALTER TABLE api_topics ADD COLUMN subagent_report_mode TEXT NOT NULL DEFAULT 'auto'");
2188
2510
  }
2511
+ if (!tableColumns("api_topics").has("derived_by_user_id")) {
2512
+ db.exec("ALTER TABLE api_topics ADD COLUMN derived_by_user_id TEXT");
2513
+ }
2189
2514
  if (!tableColumns("api_topics").has("memory_topic_id")) {
2190
2515
  db.exec("ALTER TABLE api_topics ADD COLUMN memory_topic_id TEXT");
2191
2516
  }
@@ -2298,6 +2623,7 @@ function rowToDto(r, participants = getTopicParticipants(r.id), tellTargets) {
2298
2623
  memoryTopicId: r.memory_topic_id ?? undefined,
2299
2624
  memoryKey: r.memory_key ?? undefined,
2300
2625
  isFork: r.is_fork !== 0,
2626
+ ...r.derived_by_user_id ? { derivedByUserId: r.derived_by_user_id } : {},
2301
2627
  ...r.is_subagent !== 0 ? { isSubagent: true } : {},
2302
2628
  ...r.is_subagent !== 0 ? {
2303
2629
  subagentTellTargetIds: tellTargets ? tellTargets.get(r.id) ?? [] : listSubagentTellTargetIds(r.id)
@@ -2372,8 +2698,8 @@ function upsertTopic(t) {
2372
2698
  db.query(`INSERT INTO api_topics
2373
2699
  (id,title,kind,description,agent,base_model,base_effort,response_policy,
2374
2700
  created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,
2375
- surface_scope,subagent_report_mode)
2376
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
2701
+ surface_scope,subagent_report_mode,derived_by_user_id)
2702
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
2377
2703
  ON CONFLICT(id) DO UPDATE SET
2378
2704
  title = excluded.title,
2379
2705
  kind = excluded.kind,
@@ -2395,7 +2721,10 @@ function upsertTopic(t) {
2395
2721
  -- assignment: an update may fill in a scope that was unknown when the
2396
2722
  -- room was created, but may never move a room to another workspace.
2397
2723
  surface_scope = COALESCE(api_topics.surface_scope, excluded.surface_scope),
2398
- subagent_report_mode = excluded.subagent_report_mode`).run(t.id, t.title, normalized.kind, t.description ?? null, normalized.agent ?? null, t.defaultModel ?? null, t.defaultEffort ?? null, normalized.aiMode, t.createdAt, t.lastMessageAt ?? null, t.parentTopicId ?? null, t.memoryTopicId ?? null, t.memoryKey ?? null, t.isFork ? 1 : 0, t.isSubagent ? 1 : 0, normalizeTopicVisibility(t.visibility), normalizeTopicSurface(t.surface ?? defaultTopicSurface()), surfaceScopeForWrite(t), t.subagentReportMode ?? "auto");
2724
+ subagent_report_mode = excluded.subagent_report_mode,
2725
+ -- Who asked for the derive is a fact about creation; a later update
2726
+ -- that omits it must not erase it.
2727
+ derived_by_user_id = COALESCE(excluded.derived_by_user_id, api_topics.derived_by_user_id)`).run(t.id, t.title, normalized.kind, t.description ?? null, normalized.agent ?? null, t.defaultModel ?? null, t.defaultEffort ?? null, normalized.aiMode, t.createdAt, t.lastMessageAt ?? null, t.parentTopicId ?? null, t.memoryTopicId ?? null, t.memoryKey ?? null, t.isFork ? 1 : 0, t.isSubagent ? 1 : 0, normalizeTopicVisibility(t.visibility), normalizeTopicSurface(t.surface ?? defaultTopicSurface()), surfaceScopeForWrite(t), t.subagentReportMode ?? "auto", t.derivedByUserId ?? null);
2399
2728
  db.query("DELETE FROM topic_members WHERE topic_id = ?").run(t.id);
2400
2729
  for (const participant of t.participants) {
2401
2730
  db.query("INSERT INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)").run(t.id, participant.userId, participant.role);
@@ -2548,6 +2877,9 @@ function grantSubagentTellTarget(subagentTopicId, targetTopicId, grantedByTopicI
2548
2877
  function revokeSubagentTellTarget(subagentTopicId, targetTopicId) {
2549
2878
  return db.query("DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? AND target_topic_id = ?").run(subagentTopicId, targetTopicId).changes > 0;
2550
2879
  }
2880
+ function listSubagentChildTopicIds(parentTopicId) {
2881
+ return db.query("SELECT id FROM api_topics WHERE parent_topic_id = ? AND is_subagent = 1 ORDER BY created_at").all(parentTopicId).map((row) => row.id);
2882
+ }
2551
2883
  function reparentTopicChildren(deletedTopicId, replacementParentTopicId) {
2552
2884
  const rows = db.query("SELECT id FROM api_topics WHERE parent_topic_id = ?").all(deletedTopicId);
2553
2885
  if (rows.length === 0)
@@ -2594,6 +2926,9 @@ function buildBuiltinMcpServer(surface, ctx, stdio) {
2594
2926
  const agent = ctx.agent ?? FALLBACK_AGENT;
2595
2927
  return buildHostedMcpSpec(agent, surface, {
2596
2928
  userId: ctx.userId,
2929
+ ...ctx.actorUserId ? { actorUserId: ctx.actorUserId } : {},
2930
+ ...ctx.actorTopicScope ? { actorTopicScope: ctx.actorTopicScope } : {},
2931
+ ...surface === "session-comm" && ctx.remoteSession ? { remoteSession: ctx.remoteSession } : {},
2597
2932
  topicTitle: ctx.session,
2598
2933
  ...ctx.topicId ? { topicId: ctx.topicId } : {},
2599
2934
  ...ctx.queryId ? { queryId: ctx.queryId } : {},
@@ -2785,6 +3120,9 @@ function getManagerMcpServers(opts) {
2785
3120
  const topicId = opts.topicId;
2786
3121
  return buildScope("manager", {
2787
3122
  userId: opts.userId,
3123
+ actorUserId: opts.actorUserId,
3124
+ actorTopicScope: opts.actorTopicScope,
3125
+ remoteSession: opts.remoteSession,
2788
3126
  session: opts.session ?? "General",
2789
3127
  topicId,
2790
3128
  queryId: opts.queryId,
@@ -2804,6 +3142,8 @@ function getForumMcpServers(opts) {
2804
3142
  const {
2805
3143
  userId,
2806
3144
  actorUserId,
3145
+ actorTopicScope,
3146
+ remoteSession,
2807
3147
  vaultUserId,
2808
3148
  session,
2809
3149
  topicId,
@@ -2837,6 +3177,8 @@ function getForumMcpServers(opts) {
2837
3177
  const base = buildScope("forum", {
2838
3178
  userId,
2839
3179
  actorUserId,
3180
+ actorTopicScope,
3181
+ remoteSession,
2840
3182
  vaultUserId,
2841
3183
  session,
2842
3184
  topicId,
@@ -2917,6 +3259,9 @@ function getMcpServersForQuery(opts) {
2917
3259
  if (opts.sessionType === "manager") {
2918
3260
  return hideProviderIntrospectionForOtium(mergeHostMcpServers(getManagerMcpServers({
2919
3261
  userId: opts.userId || "local",
3262
+ actorUserId: opts.actorUserId,
3263
+ actorTopicScope: opts.actorTopicScope,
3264
+ remoteSession: opts.remoteSession,
2920
3265
  session: opts.session,
2921
3266
  topicId: opts.topicId,
2922
3267
  queryId: opts.queryId,
@@ -2935,6 +3280,8 @@ function getMcpServersForQuery(opts) {
2935
3280
  return hideProviderIntrospectionForOtium(getForumMcpServers({
2936
3281
  userId: opts.userId || "local",
2937
3282
  actorUserId: opts.actorUserId,
3283
+ actorTopicScope: opts.actorTopicScope,
3284
+ remoteSession: opts.remoteSession,
2938
3285
  vaultUserId: opts.vaultUserId,
2939
3286
  session: opts.session || "default",
2940
3287
  topicId: opts.topicId,
@@ -2969,6 +3316,7 @@ function hideProviderIntrospectionForOtium(servers, topicId) {
2969
3316
  }
2970
3317
  var _playwrightUnavailableNotifier, _playwrightUnavailableLastNotifiedAt, _PLAYWRIGHT_UNAVAILABLE_COOLDOWN_MS, _playwrightUnavailableThisTurn, cuaRsMcpPort, cuaRsMcpToken, MCP_CATALOG, nodeMcpEntries, resolvedNodeMcpPorts, allForumMcpServerNames, requiredForumMcpServers, REQUIRED_FORUM_MCP_SERVERS, optionalForumMcpServers;
2971
3318
  var init_mcp_config = __esm(async () => {
3319
+ init_explicit_agent_switch();
2972
3320
  init_canonical_bridge_config();
2973
3321
  init_runtime_spec();
2974
3322
  init_bridge_ipc_config();
@@ -2978,7 +3326,9 @@ var init_mcp_config = __esm(async () => {
2978
3326
  init_mcp_catalog_policy();
2979
3327
  init_capability();
2980
3328
  init_mcp_transport();
3329
+ init_actor_topic_scope();
2981
3330
  init_cron_sessions();
3331
+ init_remote_session_grant();
2982
3332
  await init_api_topics();
2983
3333
  _playwrightUnavailableLastNotifiedAt = new Map;
2984
3334
  _PLAYWRIGHT_UNAVAILABLE_COOLDOWN_MS = 5 * 60000;
@@ -3006,6 +3356,7 @@ var init_mcp_config = __esm(async () => {
3006
3356
  build({
3007
3357
  userId,
3008
3358
  actorUserId,
3359
+ actorTopicScope,
3009
3360
  session,
3010
3361
  topicId,
3011
3362
  queryId,
@@ -3021,16 +3372,18 @@ var init_mcp_config = __esm(async () => {
3021
3372
  }) {
3022
3373
  if (!topicId || !agent)
3023
3374
  return null;
3375
+ const switchTargets = explicitAgentSwitchTargets(currentUserPrompt);
3024
3376
  return buildRuntimeMcpSpec(agent, {
3025
3377
  userId,
3026
3378
  ...actorUserId ? { actorUserId } : {},
3379
+ ...actorTopicScope ? { actorTopicScope } : {},
3027
3380
  topicId,
3028
3381
  topicTitle: session,
3029
3382
  queryId,
3030
3383
  cwd: cwd ?? resolveTopicWorkspaceDir(topicId),
3031
3384
  agent,
3032
3385
  model,
3033
- currentUserPrompt,
3386
+ ...switchTargets.length ? { explicitAgentSwitchTargets: switchTargets } : {},
3034
3387
  autoContinue,
3035
3388
  visualTools,
3036
3389
  fileDeliveryTools,
@@ -3100,6 +3453,9 @@ var init_mcp_config = __esm(async () => {
3100
3453
  build(ctx) {
3101
3454
  const {
3102
3455
  userId,
3456
+ actorUserId,
3457
+ actorTopicScope,
3458
+ remoteSession,
3103
3459
  session,
3104
3460
  topicId,
3105
3461
  subagentParentTopicId,
@@ -3113,6 +3469,9 @@ var init_mcp_config = __esm(async () => {
3113
3469
  const cronSessionId = topicId ? getRegisteredCronSession(topicId, effectiveAgent)?.sessionId : undefined;
3114
3470
  const args = [
3115
3471
  `--user-id=${userId}`,
3472
+ ...actorUserId ? [`--actor-user-id=${actorUserId}`] : [],
3473
+ ...actorTopicScope ? [`--actor-topic-scope=${encodeActorTopicScopeArg(actorTopicScope)}`] : [],
3474
+ ...remoteSession ? [`--remote-session-grant=${encodeRemoteSessionGrantArg(remoteSession)}`] : [],
3116
3475
  `--topic=${session}`,
3117
3476
  ...topicId ? [`--topic-id=${topicId}`] : [],
3118
3477
  ...subagentParentTopicId ? [`--subagent-parent-topic-id=${subagentParentTopicId}`] : [],
@@ -4005,7 +4364,7 @@ var init_codex = __esm(async () => {
4005
4364
  });
4006
4365
 
4007
4366
  // ../../packages/core/src/version.ts
4008
- var NEGOTIUM_VERSION = "0.19.2";
4367
+ var NEGOTIUM_VERSION = "0.20.0";
4009
4368
 
4010
4369
  // ../../packages/core/src/agents/codex-native-multi-agent.ts
4011
4370
  import { spawn as spawn2 } from "child_process";
@@ -5275,6 +5634,50 @@ var init_state = __esm(() => {
5275
5634
  });
5276
5635
  });
5277
5636
 
5637
+ // ../../packages/core/src/runtime/actor-topic-reach.ts
5638
+ function subagentLineageTopicIds(currentTopicId) {
5639
+ const reachable = new Set;
5640
+ const children = new Set;
5641
+ if (!currentTopicId)
5642
+ return { reachable, children };
5643
+ const current2 = getTopic(currentTopicId);
5644
+ if (current2?.isSubagent && current2.parentTopicId) {
5645
+ reachable.add(current2.parentTopicId);
5646
+ for (const id of listSubagentTellTargetIds(currentTopicId))
5647
+ reachable.add(id);
5648
+ }
5649
+ for (const id of listSubagentChildTopicIds(currentTopicId)) {
5650
+ reachable.add(id);
5651
+ children.add(id);
5652
+ }
5653
+ return { reachable, children };
5654
+ }
5655
+ function actorReachableTopicIds(input) {
5656
+ if (input.surface !== "otium")
5657
+ return null;
5658
+ const ids = new Set;
5659
+ if (input.currentTopicId)
5660
+ ids.add(input.currentTopicId);
5661
+ if (input.actorTopicScope) {
5662
+ for (const id of input.actorTopicScope.visibleNodeTopicIds)
5663
+ ids.add(id);
5664
+ return ids;
5665
+ }
5666
+ for (const id of subagentLineageTopicIds(input.currentTopicId).reachable)
5667
+ ids.add(id);
5668
+ return ids;
5669
+ }
5670
+ function actorOwnedTopicIds(input) {
5671
+ if (input.surface !== "otium")
5672
+ return null;
5673
+ if (input.actorTopicScope)
5674
+ return new Set(input.actorTopicScope.ownedNodeTopicIds);
5675
+ return subagentLineageTopicIds(input.currentTopicId).children;
5676
+ }
5677
+ var init_actor_topic_reach = __esm(async () => {
5678
+ await init_api_topics();
5679
+ });
5680
+
5278
5681
  // ../../packages/core/src/storage/api-messages.ts
5279
5682
  function initializeApiMessagesSchema() {
5280
5683
  db.exec(`
@@ -5837,6 +6240,9 @@ function rowToRequest(row) {
5837
6240
  runningQueryId: row.running_query_id ?? undefined
5838
6241
  };
5839
6242
  }
6243
+ function requestActor(actorUserId) {
6244
+ return actorUserId ?? null;
6245
+ }
5840
6246
  function loggedMessageCount(request) {
5841
6247
  const explicit = request.execution?.loggedUserMessageCount;
5842
6248
  if (typeof explicit === "number" && Number.isInteger(explicit)) {
@@ -5853,7 +6259,13 @@ function mergeRuntimeUserTurnRequest(input) {
5853
6259
  return db.transaction(() => {
5854
6260
  const rows = db.query("SELECT * FROM runtime_user_turn_requests WHERE topic_id = ? ORDER BY created_at ASC, rowid ASC").all(input.topicId);
5855
6261
  const thread = input.execution.threadRootId;
5856
- const previous = rows.map(rowToRequest).filter((request) => request.execution?.threadRootId === thread);
6262
+ const sameThread = rows.map(rowToRequest).filter((request) => request.execution?.threadRootId === thread);
6263
+ const actor = requestActor(input.execution.actorUserId);
6264
+ let firstMergeable = sameThread.length;
6265
+ while (firstMergeable > 0 && requestActor(sameThread[firstMergeable - 1].execution?.actorUserId) === actor) {
6266
+ firstMergeable -= 1;
6267
+ }
6268
+ const previous = sameThread.slice(firstMergeable);
5857
6269
  const omittedRequestIds = new Set([
5858
6270
  ...input.omitRequestIds ?? [],
5859
6271
  ...previous.filter((request) => Boolean(request.execution?.providerSessionId)).map((request) => request.requestId)
@@ -5872,8 +6284,18 @@ function mergeRuntimeUserTurnRequest(input) {
5872
6284
  ];
5873
6285
  const incomingLoggedCount = Math.min(Math.max(0, input.execution.loggedUserMessageCount ?? 0), input.userMessages.length);
5874
6286
  const loggedUserMessageCount = carried.reduce((count, request) => count + loggedMessageCount(request), 0) + Math.max(0, incomingLoggedCount - alreadyIncludedMessageCount);
6287
+ const actorTopicScope = intersectActorTopicScopes([
6288
+ ...previous.map((request) => request.execution?.actorTopicScope),
6289
+ input.execution.actorTopicScope
6290
+ ]);
6291
+ const remoteSession = mergeRemoteSessionGrants([
6292
+ ...previous.map((request) => request.execution?.remoteSession),
6293
+ input.execution.remoteSession
6294
+ ]);
5875
6295
  const execution = {
5876
6296
  ...input.execution,
6297
+ actorTopicScope,
6298
+ remoteSession,
5877
6299
  loggedUserMessageCount,
5878
6300
  supersededRequestIds: [
5879
6301
  ...new Set(previous.flatMap((request) => [
@@ -6009,12 +6431,21 @@ function cancelRuntimeUserTurnRequests(topicId) {
6009
6431
  db.query("DELETE FROM runtime_user_turn_requests WHERE topic_id = ?").run(topicId);
6010
6432
  return rows.map((row) => row.request_id);
6011
6433
  }
6434
+ function getActiveRuntimeUserTurnRequest(topicId) {
6435
+ const row = db.query(`SELECT * FROM runtime_user_turn_requests
6436
+ WHERE topic_id = ?
6437
+ AND (status = 'running' OR (claimed_by IS NOT NULL AND claimed_at >= ?))
6438
+ ORDER BY created_at ASC, rowid ASC LIMIT 1`).get(topicId, Date.now() - REQUEST_CLAIM_STALE_MS);
6439
+ return row ? rowToRequest(row) : null;
6440
+ }
6012
6441
  function getRuntimeUserTurnRequest(topicId) {
6013
6442
  const row = db.query("SELECT * FROM runtime_user_turn_requests WHERE topic_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 1").get(topicId);
6014
6443
  return row ? rowToRequest(row) : null;
6015
6444
  }
6016
6445
  var REQUEST_CLAIM_STALE_MS;
6017
6446
  var init_runtime_turn_requests = __esm(async () => {
6447
+ init_actor_topic_scope();
6448
+ init_remote_session_grant();
6018
6449
  init_user_turn_envelope();
6019
6450
  await __promiseAll([
6020
6451
  init_forum_db(),
@@ -14211,6 +14642,7 @@ async function createDerivedTopicImpl(topic, sourceTopicId, userId, copyHistory,
14211
14642
  parentTopicId: sourceTopicId,
14212
14643
  ...subagent?.memoryTopicId ? { memoryTopicId: subagent.memoryTopicId } : {},
14213
14644
  isFork: copyHistory,
14645
+ ...opts?.derivedByUserId ? { derivedByUserId: opts.derivedByUserId } : {},
14214
14646
  ...subagent ? { isSubagent: true } : {},
14215
14647
  visibility: topic.visibility,
14216
14648
  surface,
@@ -14539,96 +14971,210 @@ var init_session_inbox_cleanup = __esm(async () => {
14539
14971
  await init_session_inbox();
14540
14972
  });
14541
14973
 
14542
- // ../../packages/core/src/mcp/session-comm/peer-forward.ts
14543
- var exports_peer_forward = {};
14544
- __export(exports_peer_forward, {
14545
- registerPeerSessionBridge: () => registerPeerSessionBridge,
14546
- peerSessionsForUser: () => peerSessionsForUser,
14547
- forwardToPeer: () => forwardToPeer,
14548
- deliverPeerReply: () => deliverPeerReply
14549
- });
14550
- function loopbackBridgeConfig() {
14551
- const rawUrl = process.env[PEER_BRIDGE_URL_ENV]?.trim();
14552
- const token = process.env[PEER_BRIDGE_TOKEN_ENV]?.trim();
14553
- if (!rawUrl || !token)
14974
+ // ../../packages/core/src/mcp/session-comm/hub-remote-session.ts
14975
+ function isPlainRecord(value2) {
14976
+ return Boolean(value2) && typeof value2 === "object" && !Array.isArray(value2);
14977
+ }
14978
+ function parseListedRoom(value2, mode) {
14979
+ if (!isPlainRecord(value2))
14554
14980
  return null;
14555
- try {
14556
- const url = new URL(rawUrl);
14557
- if (url.protocol !== "http:" || !["127.0.0.1", "::1", "localhost"].includes(url.hostname)) {
14981
+ const { name, agent, status, description, role } = value2;
14982
+ if (typeof name !== "string" || !name.trim())
14983
+ return null;
14984
+ if (agent !== undefined && agent !== null && typeof agent !== "string")
14985
+ return null;
14986
+ if (status === undefined) {
14987
+ if (mode === "peek")
14558
14988
  return null;
14559
- }
14560
- return { url: url.toString(), token };
14561
- } catch {
14989
+ } else if (status !== "active" && status !== "ready") {
14562
14990
  return null;
14563
14991
  }
14992
+ if (description !== undefined && description !== null && typeof description !== "string") {
14993
+ return null;
14994
+ }
14995
+ if (role !== undefined && role !== "owner" && role !== "member")
14996
+ return null;
14997
+ return {
14998
+ name,
14999
+ ...agent !== undefined ? { agent } : {},
15000
+ ...status !== undefined ? { status } : {},
15001
+ ...description !== undefined ? { description } : {},
15002
+ ...role !== undefined ? { role } : {}
15003
+ };
14564
15004
  }
14565
- async function callLoopbackBridge(request) {
14566
- const config = loopbackBridgeConfig();
14567
- if (!config)
14568
- return { configured: false, result: null };
14569
- try {
14570
- const response = await fetch(config.url, {
14571
- method: "POST",
14572
- headers: {
14573
- authorization: `Bearer ${config.token}`,
14574
- "content-type": "application/json"
14575
- },
14576
- body: JSON.stringify(request),
14577
- signal: AbortSignal.timeout(PEER_BRIDGE_TIMEOUT_MS)
14578
- });
14579
- if (!response.ok)
14580
- return { configured: true, result: null };
14581
- return { configured: true, result: await response.json() };
14582
- } catch {
14583
- return { configured: true, result: null };
15005
+ function parseNodeListing(value2, mode) {
15006
+ if (!isPlainRecord(value2))
15007
+ return null;
15008
+ const { node, sessions, error } = value2;
15009
+ if (typeof node !== "string" || !node.trim() || node.includes("/"))
15010
+ return null;
15011
+ if (error !== undefined && (typeof error !== "string" || !error.trim()))
15012
+ return null;
15013
+ if (sessions === undefined === (error === undefined))
15014
+ return null;
15015
+ if (sessions === undefined)
15016
+ return { node, error };
15017
+ if (!Array.isArray(sessions))
15018
+ return null;
15019
+ const parsed = [];
15020
+ for (const entry of sessions) {
15021
+ const room = parseListedRoom(entry, mode);
15022
+ if (!room)
15023
+ return null;
15024
+ parsed.push(room);
14584
15025
  }
15026
+ return { node, sessions: parsed };
14585
15027
  }
14586
- function registerPeerSessionBridge(bridge) {
14587
- activeBridge = bridge;
14588
- return () => {
14589
- if (activeBridge === bridge)
14590
- activeBridge = null;
14591
- };
15028
+ function parseNodeListings(value2, mode) {
15029
+ if (!Array.isArray(value2))
15030
+ return null;
15031
+ const listings = [];
15032
+ for (const entry of value2) {
15033
+ const listing = parseNodeListing(entry, mode);
15034
+ if (!listing)
15035
+ return null;
15036
+ listings.push(listing);
15037
+ }
15038
+ return listings;
14592
15039
  }
14593
- async function forwardToPeer(args) {
14594
- if (activeBridge)
14595
- return activeBridge.forward(args);
14596
- const forwarded = await callLoopbackBridge({ action: "forward", args });
14597
- if (forwarded.result)
14598
- return forwarded.result;
15040
+ function parsePendingAsks(value2) {
15041
+ if (!Array.isArray(value2))
15042
+ return null;
15043
+ const asks = [];
15044
+ for (const entry of value2) {
15045
+ if (!isPlainRecord(entry))
15046
+ return null;
15047
+ const { to, requestId, status } = entry;
15048
+ if (typeof to !== "string" || !to.trim())
15049
+ return null;
15050
+ if (typeof requestId !== "string" || !requestId.trim())
15051
+ return null;
15052
+ if (status !== "forwarded" && status !== "reply_pending")
15053
+ return null;
15054
+ asks.push({ to, requestId, status });
15055
+ }
15056
+ return asks;
15057
+ }
15058
+ function validateHubSuccessEnvelope(body, shape) {
15059
+ if (!isPlainRecord(body))
15060
+ return null;
15061
+ if (body.ok !== true || body.v !== REMOTE_SESSION_PROTOCOL_VERSION)
15062
+ return null;
15063
+ switch (shape) {
15064
+ case "sessions": {
15065
+ const nodes = parseNodeListings(body.nodes, "sessions");
15066
+ return nodes ? { shape, nodes } : null;
15067
+ }
15068
+ case "peek": {
15069
+ const nodes = parseNodeListings(body.nodes, "peek");
15070
+ const pendingAsks = parsePendingAsks(body.pendingAsks);
15071
+ return nodes && pendingAsks ? { shape, nodes, pendingAsks } : null;
15072
+ }
15073
+ case "delivery":
15074
+ case "reply":
15075
+ return typeof body.replayed === "boolean" ? { shape, replayed: body.replayed } : null;
15076
+ }
15077
+ }
15078
+ function hubHeaders(bearer) {
14599
15079
  return {
14600
- ok: false,
14601
- error: forwarded.configured ? "remote session bridge is configured but unavailable" : "remote nodes are not connected on this negotium node (standalone mode)"
15080
+ authorization: `Bearer ${bearer}`,
15081
+ "content-type": "application/json",
15082
+ accept: "application/json"
14602
15083
  };
14603
15084
  }
14604
- async function peerSessionsForUser(userId, sourceQueryId, fromTopicId) {
14605
- if (activeBridge)
14606
- return activeBridge.sessions(userId, sourceQueryId, fromTopicId);
14607
- const sessions = await callLoopbackBridge({
14608
- action: "sessions",
14609
- userId,
14610
- sourceQueryId,
14611
- fromTopicId
14612
- });
14613
- if (sessions.result)
14614
- return sessions.result;
14615
- if (sessions.configured)
14616
- return { ok: false, nodes: [] };
14617
- return { ok: true, nodes: [] };
14618
- }
14619
- async function deliverPeerReply(route, sourceTitle, replyText, kind) {
14620
- if (activeBridge)
14621
- return activeBridge.reply(route, sourceTitle, replyText, kind);
14622
- return (await callLoopbackBridge({
14623
- action: "reply",
14624
- route,
14625
- sourceTitle,
14626
- replyText,
14627
- kind
14628
- })).result ?? false;
15085
+ function errorText(status, body, fallback) {
15086
+ const text2 = body?.error;
15087
+ if (typeof text2 === "string" && text2.trim())
15088
+ return text2.trim();
15089
+ return `${fallback} (hub answered ${status})`;
15090
+ }
15091
+ function describeFailure(status, body) {
15092
+ switch (status) {
15093
+ case 401:
15094
+ 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";
15095
+ case 404:
15096
+ return errorText(status, body, "remote session not found");
15097
+ case 409:
15098
+ return errorText(status, body, "remote session refused the request");
15099
+ case 413:
15100
+ return errorText(status, body, "message too long for the hub");
15101
+ case 429:
15102
+ return errorText(status, body, "remote session rate limit reached; try again shortly");
15103
+ case 502:
15104
+ return errorText(status, body, "the target node could not be reached by the hub");
15105
+ case 503:
15106
+ return errorText(status, body, "remote session-comm is disabled on the hub");
15107
+ default:
15108
+ return errorText(status, body, "hub refused the remote session call");
15109
+ }
15110
+ }
15111
+ async function hubRemoteReply(args) {
15112
+ const url = `${args.hubUrl}${REMOTE_SESSION_HUB_BASE_PATH}/reply`;
15113
+ let response;
15114
+ try {
15115
+ response = await hubFetch(url, {
15116
+ method: "POST",
15117
+ headers: hubHeaders(args.token),
15118
+ body: JSON.stringify({
15119
+ v: REMOTE_SESSION_PROTOCOL_VERSION,
15120
+ requestId: args.requestId,
15121
+ kind: args.kind,
15122
+ replyText: args.replyText,
15123
+ fromLabel: args.fromLabel
15124
+ }),
15125
+ signal: AbortSignal.timeout(HUB_TIMEOUT_MS),
15126
+ redirect: "error"
15127
+ });
15128
+ } catch (error) {
15129
+ return {
15130
+ settled: false,
15131
+ error: `hub unreachable: ${error instanceof Error ? error.message : String(error)}`
15132
+ };
15133
+ }
15134
+ let parsed = null;
15135
+ try {
15136
+ parsed = await response.json();
15137
+ } catch {
15138
+ parsed = null;
15139
+ }
15140
+ if (response.ok) {
15141
+ const envelope = validateHubSuccessEnvelope(parsed, "reply");
15142
+ if (!envelope) {
15143
+ return {
15144
+ settled: false,
15145
+ error: `hub answered ${response.status} with an unexpected body`
15146
+ };
15147
+ }
15148
+ return { settled: true, replayed: envelope.shape === "reply" && envelope.replayed };
15149
+ }
15150
+ const code = parsed?.code;
15151
+ if (response.status >= 500 || response.status === 429 || response.status === 409 && code === HUB_IN_PROGRESS_CODE) {
15152
+ return { settled: false, error: describeFailure(response.status, parsed) };
15153
+ }
15154
+ logger.warn({
15155
+ requestId: args.requestId,
15156
+ status: response.status,
15157
+ error: describeFailure(response.status, parsed)
15158
+ }, "session-comm: hub rejected an ask reply; dropping it");
15159
+ return { settled: true, replayed: false };
14629
15160
  }
14630
- var activeBridge = null, PEER_BRIDGE_URL_ENV = "NEGOTIUM_PEER_SESSION_BRIDGE_URL", PEER_BRIDGE_TOKEN_ENV = "NEGOTIUM_PEER_SESSION_BRIDGE_TOKEN", PEER_BRIDGE_TIMEOUT_MS = 5000;
14631
-
15161
+ var REMOTE_SESSION_HUB_BASE_PATH = "/api/v1/session-comm/remote", REMOTE_SESSION_PROTOCOL_VERSION = 1, HUB_TIMEOUT_MS = 15000, HUB_IN_PROGRESS_CODE = "in_progress", hubFetch = (input, init) => fetch(input, init), NEVER_REACHED_HUB_CAUSE_CODES;
15162
+ var init_hub_remote_session = __esm(() => {
15163
+ init_logger();
15164
+ NEVER_REACHED_HUB_CAUSE_CODES = new Set([
15165
+ "ECONNREFUSED",
15166
+ "ENOTFOUND",
15167
+ "EAI_AGAIN",
15168
+ "EHOSTUNREACH",
15169
+ "ENETUNREACH",
15170
+ "ERR_INVALID_URL",
15171
+ "CERT_HAS_EXPIRED",
15172
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
15173
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
15174
+ "ERR_TLS_CERT_ALTNAME_INVALID",
15175
+ "SELF_SIGNED_CERT_IN_CHAIN"
15176
+ ]);
15177
+ });
14632
15178
  // ../../packages/core/src/storage/session-asks.ts
14633
15179
  var exports_session_asks = {};
14634
15180
  __export(exports_session_asks, {
@@ -14994,6 +15540,326 @@ var init_session_asks = __esm(async () => {
14994
15540
  PENDING_ASK_TTL_MS = 15 * 60 * 1000;
14995
15541
  });
14996
15542
 
15543
+ // ../../packages/core/src/storage/remote-session.ts
15544
+ function remoteSessionRetryDelayMs(attempts, random = Math.random) {
15545
+ const step = Math.max(0, Math.floor(attempts) - 1);
15546
+ const base = Math.min(REMOTE_SESSION_REPLY_BACKOFF_BASE_MS * 2 ** step, REMOTE_SESSION_REPLY_BACKOFF_MAX_MS);
15547
+ const jitter = 0.8 + 0.4 * Math.min(1, Math.max(0, random()));
15548
+ return Math.round(base * jitter);
15549
+ }
15550
+ function toOutboxEntry(row) {
15551
+ return {
15552
+ requestId: row.request_id,
15553
+ hubUrl: row.hub_url,
15554
+ token: row.token,
15555
+ kind: row.kind,
15556
+ replyText: row.reply_text,
15557
+ fromLabel: row.from_label,
15558
+ createdAt: Number(row.created_at),
15559
+ attempts: Number(row.attempts),
15560
+ nextAttemptAt: Number(row.next_attempt_at),
15561
+ ...row.last_error ? { lastError: row.last_error } : {}
15562
+ };
15563
+ }
15564
+ function upsertRemoteSessionReplyOutbox(args) {
15565
+ db.query(`INSERT INTO remote_session_reply_outbox
15566
+ (request_id, hub_url, token, kind, reply_text, from_label, created_at, attempts, next_attempt_at, last_error)
15567
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0, NULL)
15568
+ ON CONFLICT(request_id) DO UPDATE SET
15569
+ hub_url = excluded.hub_url,
15570
+ token = excluded.token,
15571
+ kind = excluded.kind,
15572
+ reply_text = excluded.reply_text,
15573
+ from_label = excluded.from_label,
15574
+ attempts = 0,
15575
+ next_attempt_at = 0,
15576
+ last_error = NULL`).run(args.requestId, args.hubUrl, args.token, args.kind, args.replyText, args.fromLabel, args.createdAt ?? Date.now());
15577
+ }
15578
+ function listRemoteSessionReplyOutbox(args = {}) {
15579
+ const now = args.now ?? Date.now();
15580
+ const rows = args.due === false ? db.query("SELECT * FROM remote_session_reply_outbox ORDER BY created_at LIMIT ?").all(args.limit ?? 100) : db.query(`SELECT * FROM remote_session_reply_outbox
15581
+ WHERE next_attempt_at <= ?
15582
+ ORDER BY created_at LIMIT ?`).all(now, args.limit ?? 100);
15583
+ return rows.map(toOutboxEntry);
15584
+ }
15585
+ function deleteRemoteSessionReplyOutbox(requestId) {
15586
+ const result = db.query("DELETE FROM remote_session_reply_outbox WHERE request_id = ?").run(requestId);
15587
+ return Number(result.changes ?? 0) === 1;
15588
+ }
15589
+ function deferRemoteSessionReplyOutbox(args) {
15590
+ const now = args.now ?? Date.now();
15591
+ db.transaction(() => {
15592
+ const row = db.query("SELECT attempts FROM remote_session_reply_outbox WHERE request_id = ?").get(args.requestId);
15593
+ if (!row)
15594
+ return;
15595
+ const attempts = Number(row.attempts) + 1;
15596
+ const delay2 = args.retryMs ?? remoteSessionRetryDelayMs(attempts, args.random);
15597
+ db.query(`UPDATE remote_session_reply_outbox
15598
+ SET attempts = ?, next_attempt_at = ?, last_error = ?
15599
+ WHERE request_id = ?`).run(attempts, now + delay2, args.error.slice(0, 500), args.requestId);
15600
+ })();
15601
+ }
15602
+ function purgeExpiredRemoteSessionReplyOutbox(now = Date.now()) {
15603
+ const cutoff = now - REMOTE_SESSION_REPLY_OUTBOX_TTL_MS;
15604
+ const expired = db.query("SELECT * FROM remote_session_reply_outbox WHERE created_at < ?").all(cutoff).map(toOutboxEntry);
15605
+ if (expired.length) {
15606
+ db.query("DELETE FROM remote_session_reply_outbox WHERE created_at < ?").run(cutoff);
15607
+ }
15608
+ return expired;
15609
+ }
15610
+ var REMOTE_SESSION_INBOX_CLAIM_TTL_MS, REMOTE_SESSION_REPLY_OUTBOX_TTL_MS, REMOTE_SESSION_REPLY_BACKOFF_BASE_MS = 5000, REMOTE_SESSION_REPLY_BACKOFF_MAX_MS = 30000;
15611
+ var init_remote_session = __esm(async () => {
15612
+ await __promiseAll([
15613
+ init_forum_db(),
15614
+ init_session_asks(),
15615
+ init_storage_host()
15616
+ ]);
15617
+ registerStorageSchemaInitializer((database) => {
15618
+ database.exec(`
15619
+ CREATE TABLE IF NOT EXISTS remote_session_inbox_claims (
15620
+ request_id TEXT PRIMARY KEY,
15621
+ kind TEXT NOT NULL,
15622
+ topic_id TEXT NOT NULL,
15623
+ payload_hash TEXT NOT NULL,
15624
+ created_at INTEGER NOT NULL
15625
+ );
15626
+ CREATE INDEX IF NOT EXISTS idx_remote_session_inbox_claims_created
15627
+ ON remote_session_inbox_claims(created_at);
15628
+ CREATE TABLE IF NOT EXISTS remote_session_asks (
15629
+ request_id TEXT PRIMARY KEY,
15630
+ caller_topic_id TEXT NOT NULL,
15631
+ user_id TEXT NOT NULL,
15632
+ from_key TEXT NOT NULL,
15633
+ to_key TEXT NOT NULL,
15634
+ caller_thread_root_id TEXT,
15635
+ created_at INTEGER NOT NULL
15636
+ );
15637
+ CREATE INDEX IF NOT EXISTS idx_remote_session_asks_caller
15638
+ ON remote_session_asks(caller_topic_id);
15639
+ CREATE TABLE IF NOT EXISTS remote_session_reply_outbox (
15640
+ request_id TEXT PRIMARY KEY,
15641
+ hub_url TEXT NOT NULL,
15642
+ token TEXT NOT NULL,
15643
+ kind TEXT NOT NULL CHECK (kind IN ('reply', 'error')),
15644
+ reply_text TEXT NOT NULL,
15645
+ from_label TEXT NOT NULL,
15646
+ created_at INTEGER NOT NULL,
15647
+ attempts INTEGER NOT NULL DEFAULT 0,
15648
+ next_attempt_at INTEGER NOT NULL DEFAULT 0,
15649
+ last_error TEXT
15650
+ );
15651
+ `);
15652
+ for (const ddl of [
15653
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN state TEXT NOT NULL DEFAULT 'completed'",
15654
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN lease_until INTEGER NOT NULL DEFAULT 0",
15655
+ "ALTER TABLE remote_session_inbox_claims ADD COLUMN payload_json TEXT"
15656
+ ]) {
15657
+ try {
15658
+ database.exec(ddl);
15659
+ } catch {}
15660
+ }
15661
+ }, 36);
15662
+ REMOTE_SESSION_INBOX_CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
15663
+ REMOTE_SESSION_REPLY_OUTBOX_TTL_MS = PENDING_ASK_TTL_MS;
15664
+ });
15665
+
15666
+ // ../../packages/core/src/runtime/remote-session-inbox.ts
15667
+ var inboxLocks;
15668
+ var init_remote_session_inbox = __esm(async () => {
15669
+ init_config();
15670
+ init_logger();
15671
+ await __promiseAll([
15672
+ init_peer_forward(),
15673
+ init_forum_db(),
15674
+ init_remote_session(),
15675
+ init_session_inbox()
15676
+ ]);
15677
+ inboxLocks = new Map;
15678
+ });
15679
+
15680
+ // ../../packages/core/src/runtime/remote-session-reply-outbox.ts
15681
+ async function deliverHubRemoteReply(route, fromLabel, replyText, kind) {
15682
+ db.transaction(() => {
15683
+ upsertRemoteSessionReplyOutbox({
15684
+ requestId: route.requestId,
15685
+ hubUrl: route.hubUrl,
15686
+ token: route.token,
15687
+ kind,
15688
+ replyText,
15689
+ fromLabel
15690
+ });
15691
+ deleteHubRemoteAskCallbackRow(route.requestId);
15692
+ })();
15693
+ await flushRemoteSessionReplyOutbox();
15694
+ return true;
15695
+ }
15696
+ function flushRemoteSessionReplyOutbox(now = Date.now()) {
15697
+ if (inFlight)
15698
+ return inFlight;
15699
+ inFlight = (async () => {
15700
+ for (const expired of purgeExpiredRemoteSessionReplyOutbox(now)) {
15701
+ logger.warn({ requestId: expired.requestId, attempts: expired.attempts, lastError: expired.lastError }, "session-comm: remote ask reply expired before the hub accepted it");
15702
+ }
15703
+ for (const entry of listRemoteSessionReplyOutbox({ now })) {
15704
+ const result = await hubRemoteReply({
15705
+ hubUrl: entry.hubUrl,
15706
+ token: entry.token,
15707
+ requestId: entry.requestId,
15708
+ kind: entry.kind,
15709
+ replyText: entry.replyText,
15710
+ fromLabel: entry.fromLabel
15711
+ });
15712
+ if (result.settled) {
15713
+ deleteRemoteSessionReplyOutbox(entry.requestId);
15714
+ continue;
15715
+ }
15716
+ deferRemoteSessionReplyOutbox({
15717
+ requestId: entry.requestId,
15718
+ error: result.error,
15719
+ now,
15720
+ random: retryRandom
15721
+ });
15722
+ logger.info({ requestId: entry.requestId, attempts: entry.attempts + 1, error: result.error }, "session-comm: remote ask reply deferred");
15723
+ }
15724
+ })().finally(() => {
15725
+ inFlight = null;
15726
+ });
15727
+ return inFlight;
15728
+ }
15729
+ var retryRandom, inFlight = null;
15730
+ var init_remote_session_reply_outbox = __esm(async () => {
15731
+ init_hub_remote_session();
15732
+ init_logger();
15733
+ await __promiseAll([
15734
+ init_ask_callbacks(),
15735
+ init_remote_session_inbox(),
15736
+ init_forum_db(),
15737
+ init_remote_session()
15738
+ ]);
15739
+ retryRandom = Math.random;
15740
+ });
15741
+
15742
+ // ../../packages/core/src/mcp/session-comm/peer-forward.ts
15743
+ var exports_peer_forward = {};
15744
+ __export(exports_peer_forward, {
15745
+ registerPeerSessionBridge: () => registerPeerSessionBridge,
15746
+ peerSessionsForUser: () => peerSessionsForUser,
15747
+ parseHubRemoteReplyRoute: () => parseHubRemoteReplyRoute,
15748
+ isHubRemoteReplyRoute: () => isHubRemoteReplyRoute,
15749
+ forwardToPeer: () => forwardToPeer,
15750
+ deliverPeerReply: () => deliverPeerReply
15751
+ });
15752
+ function isHubRemoteReplyRoute(route) {
15753
+ return route.via === "hub";
15754
+ }
15755
+ function parseHubRemoteReplyRoute(value2) {
15756
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
15757
+ return null;
15758
+ const route = value2;
15759
+ if (route.via !== "hub" || typeof route.hubUrl !== "string" || typeof route.token !== "string" || typeof route.nodeName !== "string" || typeof route.topicId !== "string" || typeof route.requestId !== "string") {
15760
+ return null;
15761
+ }
15762
+ const requestId = route.requestId.trim();
15763
+ const nodeName = route.nodeName.trim();
15764
+ const topicId = route.topicId.trim();
15765
+ const token = route.token.trim();
15766
+ if (!requestId || requestId.length > MAX_ROUTE_REQUEST_ID_LENGTH || !nodeName || nodeName.length > MAX_ROUTE_LABEL_LENGTH || !topicId || topicId.length > MAX_ROUTE_LABEL_LENGTH || token.length > MAX_REMOTE_SESSION_REPLY_TOKEN_LENGTH || !REMOTE_SESSION_REPLY_TOKEN_PATTERN.test(token)) {
15767
+ return null;
15768
+ }
15769
+ const hubUrl = normalizeHubUrl(route.hubUrl.trim(), "remoteReply.hubUrl");
15770
+ if ("error" in hubUrl)
15771
+ return null;
15772
+ return { via: "hub", hubUrl: hubUrl.url, token, nodeName, topicId, requestId };
15773
+ }
15774
+ function loopbackBridgeConfig() {
15775
+ const rawUrl = process.env[PEER_BRIDGE_URL_ENV]?.trim();
15776
+ const token = process.env[PEER_BRIDGE_TOKEN_ENV]?.trim();
15777
+ if (!rawUrl || !token)
15778
+ return null;
15779
+ try {
15780
+ const url = new URL(rawUrl);
15781
+ if (url.protocol !== "http:" || !["127.0.0.1", "::1", "localhost"].includes(url.hostname)) {
15782
+ return null;
15783
+ }
15784
+ return { url: url.toString(), token };
15785
+ } catch {
15786
+ return null;
15787
+ }
15788
+ }
15789
+ async function callLoopbackBridge(request) {
15790
+ const config = loopbackBridgeConfig();
15791
+ if (!config)
15792
+ return { configured: false, result: null };
15793
+ try {
15794
+ const response = await fetch(config.url, {
15795
+ method: "POST",
15796
+ headers: {
15797
+ authorization: `Bearer ${config.token}`,
15798
+ "content-type": "application/json"
15799
+ },
15800
+ body: JSON.stringify(request),
15801
+ signal: AbortSignal.timeout(PEER_BRIDGE_TIMEOUT_MS)
15802
+ });
15803
+ if (!response.ok)
15804
+ return { configured: true, result: null };
15805
+ return { configured: true, result: await response.json() };
15806
+ } catch {
15807
+ return { configured: true, result: null };
15808
+ }
15809
+ }
15810
+ function registerPeerSessionBridge(bridge) {
15811
+ activeBridge = bridge;
15812
+ return () => {
15813
+ if (activeBridge === bridge)
15814
+ activeBridge = null;
15815
+ };
15816
+ }
15817
+ async function forwardToPeer(args) {
15818
+ if (activeBridge)
15819
+ return activeBridge.forward(args);
15820
+ const forwarded = await callLoopbackBridge({ action: "forward", args });
15821
+ if (forwarded.result)
15822
+ return forwarded.result;
15823
+ return {
15824
+ ok: false,
15825
+ error: forwarded.configured ? "remote session bridge is configured but unavailable" : "remote nodes are not connected on this negotium node (standalone mode)"
15826
+ };
15827
+ }
15828
+ async function peerSessionsForUser(userId, sourceQueryId, fromTopicId) {
15829
+ if (activeBridge)
15830
+ return activeBridge.sessions(userId, sourceQueryId, fromTopicId);
15831
+ const sessions = await callLoopbackBridge({
15832
+ action: "sessions",
15833
+ userId,
15834
+ sourceQueryId,
15835
+ fromTopicId
15836
+ });
15837
+ if (sessions.result)
15838
+ return sessions.result;
15839
+ if (sessions.configured)
15840
+ return { ok: false, nodes: [] };
15841
+ return { ok: true, nodes: [] };
15842
+ }
15843
+ async function deliverPeerReply(route, sourceTitle, replyText, kind) {
15844
+ if (isHubRemoteReplyRoute(route)) {
15845
+ return deliverHubRemoteReply(route, sourceTitle, replyText, kind);
15846
+ }
15847
+ if (activeBridge)
15848
+ return activeBridge.reply(route, sourceTitle, replyText, kind);
15849
+ return (await callLoopbackBridge({
15850
+ action: "reply",
15851
+ route,
15852
+ sourceTitle,
15853
+ replyText,
15854
+ kind
15855
+ })).result ?? false;
15856
+ }
15857
+ var MAX_ROUTE_REQUEST_ID_LENGTH = 200, MAX_ROUTE_LABEL_LENGTH = 300, activeBridge = null, PEER_BRIDGE_URL_ENV = "NEGOTIUM_PEER_SESSION_BRIDGE_URL", PEER_BRIDGE_TOKEN_ENV = "NEGOTIUM_PEER_SESSION_BRIDGE_TOKEN", PEER_BRIDGE_TIMEOUT_MS = 5000;
15858
+ var init_peer_forward = __esm(async () => {
15859
+ init_remote_session_grant();
15860
+ await init_remote_session_reply_outbox();
15861
+ });
15862
+
14997
15863
  // ../../packages/core/src/runtime/ask-callbacks.ts
14998
15864
  var exports_ask_callbacks = {};
14999
15865
  __export(exports_ask_callbacks, {
@@ -15001,21 +15867,25 @@ __export(exports_ask_callbacks, {
15001
15867
  registerAskCallback: () => registerAskCallback,
15002
15868
  purgeStaleAsks: () => purgeStaleAsks,
15003
15869
  failInterruptedRemoteAskCallbacks: () => failInterruptedRemoteAskCallbacks,
15870
+ deleteHubRemoteAskCallbackRow: () => deleteHubRemoteAskCallbackRow,
15004
15871
  cancelAskCallbacksForTopic: () => cancelAskCallbacksForTopic
15005
15872
  });
15006
15873
  function registerAskCallback(entry) {
15007
15874
  pendingAsks.set(entry.targetQueryId, entry);
15008
15875
  if (entry.remoteReply) {
15876
+ const route = entry.remoteReply;
15877
+ const hub = isHubRemoteReplyRoute(route);
15009
15878
  db.query(`INSERT INTO remote_ask_callbacks
15010
- (target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, created_at)
15011
- VALUES (?, ?, ?, ?, ?, ?, ?)
15879
+ (target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, created_at, route_json)
15880
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
15012
15881
  ON CONFLICT(target_query_id) DO UPDATE SET
15013
15882
  request_id = excluded.request_id,
15014
15883
  node_name = excluded.node_name,
15015
15884
  node_cell_id = excluded.node_cell_id,
15016
15885
  topic_id = excluded.topic_id,
15017
15886
  user_id = excluded.user_id,
15018
- created_at = excluded.created_at`).run(entry.targetQueryId, entry.remoteReply.requestId, entry.remoteReply.nodeName, entry.remoteReply.nodeCellId, entry.remoteReply.topicId, entry.remoteReply.userId, entry.createdAt);
15887
+ created_at = excluded.created_at,
15888
+ route_json = excluded.route_json`).run(entry.targetQueryId, route.requestId, route.nodeName, hub ? "" : route.nodeCellId, route.topicId, hub ? "" : route.userId, entry.createdAt, hub ? JSON.stringify(route) : null);
15019
15889
  }
15020
15890
  }
15021
15891
  function resolveAskCallback(queryId) {
@@ -15026,9 +15896,14 @@ function resolveAskCallback(queryId) {
15026
15896
  entry.timedOut = true;
15027
15897
  }
15028
15898
  pendingAsks.delete(queryId);
15029
- db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(queryId);
15899
+ if (!entry.remoteReply || !isHubRemoteReplyRoute(entry.remoteReply)) {
15900
+ db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(queryId);
15901
+ }
15030
15902
  return entry;
15031
15903
  }
15904
+ function deleteHubRemoteAskCallbackRow(requestId) {
15905
+ db.query("DELETE FROM remote_ask_callbacks WHERE request_id = ? AND route_json IS NOT NULL").run(requestId);
15906
+ }
15032
15907
  function purgeStaleAsks(now = Date.now()) {
15033
15908
  for (const [id, entry] of pendingAsks) {
15034
15909
  if (now - entry.createdAt > MAX_ASK_AGE_MS)
@@ -15047,19 +15922,36 @@ function cancelAskCallbacksForTopic(topicId) {
15047
15922
  }
15048
15923
  return cancelled;
15049
15924
  }
15050
- async function failInterruptedRemoteAskCallbacks() {
15051
- const rows = db.query(`SELECT target_query_id, request_id, node_name, node_cell_id, topic_id, user_id
15925
+ function durableRoute(row) {
15926
+ if (row.route_json) {
15927
+ try {
15928
+ return parseHubRemoteReplyRoute(JSON.parse(row.route_json));
15929
+ } catch {
15930
+ return null;
15931
+ }
15932
+ }
15933
+ return {
15934
+ nodeName: row.node_name,
15935
+ nodeCellId: row.node_cell_id,
15936
+ topicId: row.topic_id,
15937
+ userId: row.user_id,
15938
+ requestId: row.request_id
15939
+ };
15940
+ }
15941
+ async function failInterruptedRemoteAskCallbacks(options = {}) {
15942
+ const rows = db.query(`SELECT target_query_id, request_id, node_name, node_cell_id, topic_id, user_id, route_json
15052
15943
  FROM remote_ask_callbacks
15053
15944
  ORDER BY created_at ASC`).all();
15054
15945
  let failed = 0;
15055
15946
  for (const row of rows) {
15056
- const delivered = await deliverPeerReply({
15057
- nodeName: row.node_name,
15058
- nodeCellId: row.node_cell_id,
15059
- topicId: row.topic_id,
15060
- userId: row.user_id,
15061
- requestId: row.request_id
15062
- }, "peer", "The remote worker restarted before this ask completed. Please retry the request.", "error");
15947
+ const route = durableRoute(row);
15948
+ if (!route) {
15949
+ db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
15950
+ continue;
15951
+ }
15952
+ if (options.routes === "hub" && !isHubRemoteReplyRoute(route))
15953
+ continue;
15954
+ const delivered = await deliverPeerReply(route, "peer", "The remote worker restarted before this ask completed. Please retry the request.", "error");
15063
15955
  if (!delivered)
15064
15956
  continue;
15065
15957
  db.query("DELETE FROM remote_ask_callbacks WHERE target_query_id = ?").run(row.target_query_id);
@@ -15070,6 +15962,7 @@ async function failInterruptedRemoteAskCallbacks() {
15070
15962
  var pendingAsks, MAX_ASK_AGE_MS;
15071
15963
  var init_ask_callbacks = __esm(async () => {
15072
15964
  await __promiseAll([
15965
+ init_peer_forward(),
15073
15966
  init_forum_db(),
15074
15967
  init_session_asks(),
15075
15968
  init_storage_host()
@@ -15086,6 +15979,9 @@ var init_ask_callbacks = __esm(async () => {
15086
15979
  created_at INTEGER NOT NULL
15087
15980
  )
15088
15981
  `);
15982
+ try {
15983
+ database.exec("ALTER TABLE remote_ask_callbacks ADD COLUMN route_json TEXT");
15984
+ } catch {}
15089
15985
  });
15090
15986
  pendingAsks = new Map;
15091
15987
  MAX_ASK_AGE_MS = PENDING_ASK_TTL_MS;
@@ -15947,12 +16843,12 @@ function buildMentionOnlyChannelPrompt(params) {
15947
16843
  ].filter((line) => line !== undefined).join(`
15948
16844
  `);
15949
16845
  }
15950
- function escapeRegExp2(s) {
16846
+ function escapeRegExp3(s) {
15951
16847
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15952
16848
  }
15953
16849
  function mentionsAi(text2, label) {
15954
16850
  const names = ["ai", "bot", "\uBD07", label.trim()].filter(Boolean);
15955
- const alt = names.map(escapeRegExp2).join("|");
16851
+ const alt = names.map(escapeRegExp3).join("|");
15956
16852
  return new RegExp(`(^|\\s)@(${alt})(?![\\p{L}\\p{N}])`, "iu").test(text2);
15957
16853
  }
15958
16854
  var CHANNEL_CONTEXT_CURRENT_MESSAGE_MATCH_MS, CHANNEL_CONTEXT_MAX_MESSAGES = 500, CHANNEL_CONTEXT_MAX_CHARS = 120000;
@@ -17770,6 +18666,7 @@ __export(exports_turn_runner, {
17770
18666
  startDurableTurnRequestWorker: () => startDurableTurnRequestWorker,
17771
18667
  startAiTurn: () => startAiTurn,
17772
18668
  selectableModel: () => selectableModel,
18669
+ sameTurnActor: () => sameTurnActor,
17773
18670
  safeAttachmentFilename: () => safeAttachmentFilename,
17774
18671
  resolveWorkerModel: () => resolveWorkerModel,
17775
18672
  resolveWorkerDefaultModel: () => resolveWorkerDefaultModel,
@@ -17807,7 +18704,7 @@ __export(exports_turn_runner, {
17807
18704
  ingestAttachment: () => ingestAttachment,
17808
18705
  formatSelectableModel: () => formatSelectableModel,
17809
18706
  formatChannelTranscriptLine: () => formatChannelTranscriptLine,
17810
- escapeRegExp: () => escapeRegExp2,
18707
+ escapeRegExp: () => escapeRegExp3,
17811
18708
  escapeHtml: () => escapeHtml2,
17812
18709
  deliverAskCallbackToCaller: () => deliverAskCallbackToCaller,
17813
18710
  composeAttachmentPrompt: () => composeAttachmentPrompt,
@@ -18018,20 +18915,27 @@ async function markPendingAskFile(pending, state) {
18018
18915
  logger.warn({ err, pendingAsk: pending.pendingAsk, state }, "sessions: pending ask mark failed");
18019
18916
  }
18020
18917
  }
18021
- async function deliverAskCallbackToCaller(pending, sourceLabel, body, kind) {
18918
+ async function deliverAskCallbackToCaller(pending, sourceLabel, body, kind, options = {}) {
18022
18919
  if (pending.remoteReply) {
18023
- const { deliverPeerReply: deliverPeerReply2 } = await Promise.resolve().then(() => exports_peer_forward);
18024
- return deliverPeerReply2(pending.remoteReply, sourceLabel, body, kind);
18920
+ const { deliverPeerReply: deliverPeerReply2 } = await init_peer_forward().then(() => exports_peer_forward);
18921
+ const delivered = await deliverPeerReply2(pending.remoteReply, sourceLabel, body, kind);
18922
+ if (delivered)
18923
+ options.onRecorded?.();
18924
+ return delivered;
18025
18925
  }
18026
18926
  const callerTopic = getTopic(pending.callerTopicId);
18027
18927
  const heading = kind === "error" ? `Error from ${sourceLabel}` : `Reply from ${sourceLabel}`;
18028
18928
  const prompt = `[${heading}]
18029
18929
 
18030
18930
  ${body}`;
18931
+ const record = (agentType) => db.transaction(() => {
18932
+ appendAskReplyMessage(pending.callerTopicId, prompt, sourceLabel, body, kind, agentType ?? undefined, pending.callerThreadRootId);
18933
+ options.onRecorded?.();
18934
+ })();
18031
18935
  await markPendingAskFile(pending, "reply_ready");
18032
18936
  if (!callerTopic?.agent) {
18033
18937
  try {
18034
- appendAskReplyMessage(pending.callerTopicId, prompt, sourceLabel, body, kind, undefined, pending.callerThreadRootId);
18938
+ record(undefined);
18035
18939
  await clearPendingAskFile(pending);
18036
18940
  return true;
18037
18941
  } catch (err) {
@@ -18062,16 +18966,25 @@ ${body}`;
18062
18966
  }
18063
18967
  });
18064
18968
  if (queued) {
18065
- appendAskReplyMessage(pending.callerTopicId, prompt, sourceLabel, body, kind, callerTopic.agent, pending.callerThreadRootId);
18969
+ try {
18970
+ record(callerTopic.agent);
18971
+ } catch (err) {
18972
+ interSessionQueue.remove(pending.callerTopicId, pending.requestId);
18973
+ logger.warn({ err, requestId: pending.requestId, callerTopicId: pending.callerTopicId }, "sessions: ask callback record failed after enqueue; queue entry withdrawn");
18974
+ return false;
18975
+ }
18066
18976
  await markPendingAskFile(pending, "queued_for_caller");
18067
18977
  return true;
18068
18978
  }
18069
18979
  if (interSessionQueue.hasRequest(pending.callerTopicId, pending.requestId)) {
18980
+ db.transaction(() => {
18981
+ options.onRecorded?.();
18982
+ })();
18070
18983
  await markPendingAskFile(pending, "queued_for_caller");
18071
18984
  return true;
18072
18985
  }
18073
18986
  logger.warn({ requestId: pending.requestId, callerTopicId: pending.callerTopicId, source: sourceLabel }, "sessions: ask callback could not enter caller batch; appending direct fallback");
18074
- appendAskReplyMessage(pending.callerTopicId, prompt, sourceLabel, body, kind, callerTopic.agent, pending.callerThreadRootId);
18987
+ record(callerTopic.agent);
18075
18988
  await clearPendingAskFile(pending);
18076
18989
  return true;
18077
18990
  }
@@ -18141,6 +19054,15 @@ function resolveTurnHostMcpServers(topic, sessionType) {
18141
19054
  return;
18142
19055
  return getTopicHostMcpGrant(topic.id) ?? undefined;
18143
19056
  }
19057
+ function sameTurnActor(runningActorUserId, incomingActorUserId) {
19058
+ return (runningActorUserId ?? null) === (incomingActorUserId ?? null);
19059
+ }
19060
+ function remoteTurnHasSameActor(topicId, incomingActorUserId, ownRequestIds) {
19061
+ const active = getActiveRuntimeUserTurnRequest(topicId);
19062
+ if (!active || ownRequestIds.includes(active.requestId))
19063
+ return false;
19064
+ return sameTurnActor(active.execution?.actorUserId, incomingActorUserId);
19065
+ }
18144
19066
  function mergeSupersedingUserTurn(running, incoming) {
18145
19067
  const userMessages = [
18146
19068
  ...running.userMessages ?? [legacyUserTurnEnvelope(running.prompt, running.attachments)],
@@ -18161,6 +19083,8 @@ function serializableUserTurnExecution(params) {
18161
19083
  runtimeEpoch: params._runtimeEpoch ?? getRuntimeTopicEpoch(params.topic.id),
18162
19084
  sourceRequestId: params.requestId,
18163
19085
  actorUserId: params.actorUserId,
19086
+ actorTopicScope: params.actorTopicScope,
19087
+ remoteSession: params.remoteSession,
18164
19088
  agentOverride: params.agentOverride,
18165
19089
  modelOverride: params.modelOverride,
18166
19090
  effortOverride: params.effortOverride,
@@ -18246,6 +19170,8 @@ async function drainOneDurableUserTurn() {
18246
19170
  topic,
18247
19171
  userId: request.userId,
18248
19172
  actorUserId: execution?.actorUserId,
19173
+ actorTopicScope: actorTopicScopeFrom(execution?.actorTopicScope),
19174
+ remoteSession: remoteSessionGrantFrom(execution?.remoteSession),
18249
19175
  vaultUserId: execution?.vaultUserId,
18250
19176
  prompt: request.prompt,
18251
19177
  _userMessages: request.userMessages,
@@ -18459,7 +19385,9 @@ function startAiTurn(params) {
18459
19385
  return null;
18460
19386
  }
18461
19387
  if (decision.action === "remote-abort-wait") {
18462
- requestRuntimeTurnAbort(topicId, "internal");
19388
+ if (remoteTurnHasSameActor(topicId, params.actorUserId, durableRequestIds)) {
19389
+ requestRuntimeTurnAbort(topicId, "internal");
19390
+ }
18463
19391
  const queuedQueryId = waitToStartRemoteUserTurn({
18464
19392
  ...params,
18465
19393
  topic,
@@ -18477,6 +19405,23 @@ function startAiTurn(params) {
18477
19405
  }
18478
19406
  if (decision.action === "abort-replace") {
18479
19407
  const running = decision.running;
19408
+ if (isUserOrigin(running.origin) && !sameTurnActor(running.actorUserId, params.actorUserId)) {
19409
+ const queuedQueryId2 = waitToStartRemoteUserTurn({
19410
+ ...params,
19411
+ topic,
19412
+ prompt,
19413
+ attachments: attachments2,
19414
+ sessionId,
19415
+ _userMessages: userMessages,
19416
+ _conversationPrompts: conversationPrompts,
19417
+ _loggedUserMessageCount: loggedUserMessageCount,
19418
+ _durableRequestIds: durableRequestIds,
19419
+ _runtimeEpoch: runtimeEpoch
19420
+ }, queryId);
19421
+ announceQueuedUserTurn({ ...params, topic }, queuedQueryId2);
19422
+ logger.info({ topicId, queryId: queuedQueryId2, runningQueryId: running.queryId }, "ai: user turn from another actor queued behind the running turn");
19423
+ return queuedQueryId2;
19424
+ }
18480
19425
  let omitRequestIds;
18481
19426
  if (isUserOrigin(running.origin)) {
18482
19427
  if (running.providerTurnContentObserved && running.sessionId) {
@@ -18536,6 +19481,7 @@ function startAiTurn(params) {
18536
19481
  origin,
18537
19482
  prompt,
18538
19483
  userMessages,
19484
+ ...isUserOrigin(origin) && params.actorUserId !== undefined ? { actorUserId: params.actorUserId } : {},
18539
19485
  durableRequestIds,
18540
19486
  attachments: attachments2,
18541
19487
  sessionId,
@@ -18581,7 +19527,9 @@ function startAiTurn(params) {
18581
19527
  return rejectIsolatedTurnBeforeDispatch("failed to claim isolated turn slot");
18582
19528
  }
18583
19529
  if (isUserOrigin(origin)) {
18584
- requestRuntimeTurnAbort(topicId, "internal");
19530
+ if (remoteTurnHasSameActor(topicId, params.actorUserId, durableRequestIds)) {
19531
+ requestRuntimeTurnAbort(topicId, "internal");
19532
+ }
18585
19533
  const queuedQueryId = waitToStartRemoteUserTurn({
18586
19534
  ...params,
18587
19535
  topic,
@@ -18841,6 +19789,8 @@ function startAiTurn(params) {
18841
19789
  sessionId,
18842
19790
  userId,
18843
19791
  actorUserId: params.actorUserId,
19792
+ actorTopicScope: params.actorTopicScope,
19793
+ remoteSession: params.remoteSession,
18844
19794
  vaultUserId,
18845
19795
  session: sessionName,
18846
19796
  sessionType: sessionType ?? (isManager ? "manager" : "forum"),
@@ -18905,12 +19855,10 @@ function startAiTurn(params) {
18905
19855
  error: "Provider session expired and conversation history could not be rebuilt; the existing session was preserved for retry."
18906
19856
  };
18907
19857
  } else {
18908
- if (!silent)
18909
- WsHub.get().broadcastAborted(topicId, queryId, "stopped");
18910
19858
  const retrySessionId = retry.sessionId;
18911
19859
  logger.info({
18912
19860
  topicId,
18913
- prevQueryId: queryId,
19861
+ queryId,
18914
19862
  agent: agentKind,
18915
19863
  retrySessionId: retrySessionId ? retrySessionId.slice(0, 8) : null
18916
19864
  }, "ai: retrying query after session expiry");
@@ -18921,6 +19869,9 @@ function startAiTurn(params) {
18921
19869
  startAiTurn({
18922
19870
  topic,
18923
19871
  userId,
19872
+ actorUserId: params.actorUserId,
19873
+ actorTopicScope: params.actorTopicScope,
19874
+ remoteSession: params.remoteSession,
18924
19875
  vaultUserId,
18925
19876
  prompt,
18926
19877
  _userMessages: userMessages,
@@ -18955,7 +19906,8 @@ function startAiTurn(params) {
18955
19906
  peerBridge,
18956
19907
  askReplySources,
18957
19908
  _runtimeEpoch: runtimeEpoch,
18958
- _sessionRetried: true
19909
+ _sessionRetried: true,
19910
+ _queryId: queryId
18959
19911
  });
18960
19912
  return;
18961
19913
  }
@@ -18964,12 +19916,13 @@ function startAiTurn(params) {
18964
19916
  if (emptyResponseRetried) {
18965
19917
  outcome = { kind: "provider-error", error: outcome.error };
18966
19918
  } else {
18967
- if (!silent)
18968
- WsHub.get().broadcastAborted(topicId, queryId, "stopped");
18969
- logger.info({ topicId, prevQueryId: queryId, agent: agentKind }, "ai: retrying query after empty provider response");
19919
+ logger.info({ topicId, queryId, agent: agentKind }, "ai: retrying query after empty provider response");
18970
19920
  startAiTurn({
18971
19921
  topic,
18972
19922
  userId,
19923
+ actorUserId: params.actorUserId,
19924
+ actorTopicScope: params.actorTopicScope,
19925
+ remoteSession: params.remoteSession,
18973
19926
  vaultUserId,
18974
19927
  prompt,
18975
19928
  _userMessages: userMessages,
@@ -19005,7 +19958,8 @@ function startAiTurn(params) {
19005
19958
  askReplySources,
19006
19959
  _runtimeEpoch: runtimeEpoch,
19007
19960
  _sessionRetried: sessionRetried,
19008
- _emptyResponseRetried: true
19961
+ _emptyResponseRetried: true,
19962
+ _queryId: queryId
19009
19963
  });
19010
19964
  return;
19011
19965
  }
@@ -19177,8 +20131,10 @@ var init_turn_runner = __esm(async () => {
19177
20131
  init_builders();
19178
20132
  init_state();
19179
20133
  init_types2();
20134
+ init_actor_topic_scope();
19180
20135
  init_attachments();
19181
20136
  init_errors();
20137
+ init_remote_session_grant();
19182
20138
  init_user_turn_envelope();
19183
20139
  init_wiki_summary_names();
19184
20140
  init_user_turn_envelope();
@@ -19204,6 +20160,7 @@ var init_turn_runner = __esm(async () => {
19204
20160
  init_app_settings(),
19205
20161
  init_browser_profiles(),
19206
20162
  init_conversations(),
20163
+ init_forum_db(),
19207
20164
  init_runtime_leases(),
19208
20165
  init_runtime_topic_state(),
19209
20166
  init_runtime_turn_requests(),
@@ -19762,6 +20719,18 @@ ${card.task}${reportInstruction}`;
19762
20719
  ].join(`
19763
20720
  `));
19764
20721
  }
20722
+ function assertedActorScope(ctx) {
20723
+ if (ctx.surface !== "otium" || !ctx.actorTopicScope)
20724
+ return null;
20725
+ const input = {
20726
+ surface: ctx.surface,
20727
+ currentTopicId: ctx.topicId,
20728
+ actorTopicScope: ctx.actorTopicScope
20729
+ };
20730
+ const visible = actorReachableTopicIds(input);
20731
+ const owned = actorOwnedTopicIds(input);
20732
+ return visible && owned ? { visible, owned } : null;
20733
+ }
19765
20734
  function ownedSubagentTree(ctx) {
19766
20735
  const parent = host.storage.getTopic(ctx.topicId);
19767
20736
  if (!parent)
@@ -19775,37 +20744,46 @@ ${card.task}${reportInstruction}`;
19775
20744
  error: "Error: subagent management is only available in agent rooms."
19776
20745
  };
19777
20746
  }
20747
+ const actorScope = assertedActorScope(ctx);
19778
20748
  const rootOwnerId = parent.participants.find((participant) => participant.role === "owner")?.userId;
20749
+ const descendants = rootOwnerId ? (() => {
20750
+ const topics = host.storage.listTopics();
20751
+ const byParent = new Map;
20752
+ for (const topic of topics) {
20753
+ if (!topic.parentTopicId || !topic.isSubagent)
20754
+ continue;
20755
+ const siblings = byParent.get(topic.parentTopicId) ?? [];
20756
+ siblings.push(topic);
20757
+ byParent.set(topic.parentTopicId, siblings);
20758
+ }
20759
+ for (const siblings of byParent.values()) {
20760
+ siblings.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
20761
+ }
20762
+ const descendants2 = [];
20763
+ const visited = new Set([ctx.topicId]);
20764
+ const visit = (parentId) => {
20765
+ for (const child of byParent.get(parentId) ?? []) {
20766
+ if (visited.has(child.id))
20767
+ continue;
20768
+ visited.add(child.id);
20769
+ if (!child.participants.some((participant) => participant.userId === rootOwnerId && participant.role === "owner")) {
20770
+ continue;
20771
+ }
20772
+ descendants2.push(child);
20773
+ visit(child.id);
20774
+ }
20775
+ };
20776
+ visit(ctx.topicId);
20777
+ return descendants2;
20778
+ })() : [];
20779
+ const children = actorScope ? descendants.filter((child) => actorScope.visible.has(child.id)) : descendants;
19779
20780
  return {
19780
20781
  ok: true,
19781
20782
  parent,
19782
- children: rootOwnerId ? (() => {
19783
- const topics = host.storage.listTopics();
19784
- const byParent = new Map;
19785
- for (const topic of topics) {
19786
- if (!topic.parentTopicId || !topic.isSubagent)
19787
- continue;
19788
- const siblings = byParent.get(topic.parentTopicId) ?? [];
19789
- siblings.push(topic);
19790
- byParent.set(topic.parentTopicId, siblings);
19791
- }
19792
- const descendants = [];
19793
- const visited = new Set([ctx.topicId]);
19794
- const visit = (parentId) => {
19795
- for (const child of byParent.get(parentId) ?? []) {
19796
- if (visited.has(child.id))
19797
- continue;
19798
- visited.add(child.id);
19799
- if (!child.participants.some((participant) => participant.userId === rootOwnerId && participant.role === "owner")) {
19800
- continue;
19801
- }
19802
- descendants.push(child);
19803
- visit(child.id);
19804
- }
19805
- };
19806
- visit(ctx.topicId);
19807
- return descendants;
19808
- })() : []
20783
+ children,
20784
+ owned: (childId) => children.some((child) => child.id === childId) && (!actorScope || actorScope.owned.has(childId)),
20785
+ visibleTarget: (topicId) => topicId === ctx.topicId || children.some((child) => child.id === topicId),
20786
+ visibleTellTargets: (targetIds) => actorScope ? targetIds.filter((targetId) => targetId === ctx.topicId || actorScope.visible.has(targetId) || children.some((child) => child.id === targetId)) : [...targetIds]
19809
20787
  };
19810
20788
  }
19811
20789
  function subagentStatus(parentTopicId, childTopicId) {
@@ -19869,7 +20847,7 @@ ${card.task}${reportInstruction}`;
19869
20847
  status: subagentStatus(child.parentTopicId ?? ctx.topicId, child.id),
19870
20848
  agent: child.agent ?? null,
19871
20849
  model: child.defaultModel ?? null,
19872
- tell_target_topic_ids: host.sessionCommunication.listTellTargetIds(child.id),
20850
+ tell_target_topic_ids: result.visibleTellTargets(host.sessionCommunication.listTellTargetIds(child.id)),
19873
20851
  created_at: child.createdAt
19874
20852
  }));
19875
20853
  return textResult(JSON.stringify({ subagents: children }, null, 2));
@@ -19886,7 +20864,7 @@ ${card.task}${reportInstruction}`;
19886
20864
  if (!result.ok)
19887
20865
  return errorResult(result.error);
19888
20866
  const topicId = String(input.topic_id ?? "").trim();
19889
- if (!result.children.some((child) => child.id === topicId)) {
20867
+ if (!result.owned(topicId)) {
19890
20868
  return errorResult("Error: topic is not a descendant subagent managed by this room.");
19891
20869
  }
19892
20870
  const cardMessage = findSubagentCardMessage(topicId);
@@ -19906,7 +20884,7 @@ ${card.task}${reportInstruction}`;
19906
20884
  if (!result.ok)
19907
20885
  return errorResult(result.error);
19908
20886
  const topicId = typeof input.topic_id === "string" ? input.topic_id.trim() : "";
19909
- const child = result.children.find((candidate) => candidate.id === topicId);
20887
+ const child = result.owned(topicId) ? result.children.find((candidate) => candidate.id === topicId) : undefined;
19910
20888
  if (!child) {
19911
20889
  return errorResult("Error: no owned descendant subagent with that topic_id exists under this room.");
19912
20890
  }
@@ -19932,11 +20910,10 @@ ${card.task}${reportInstruction}`;
19932
20910
  return errorResult(result.error);
19933
20911
  const sourceId = String(input.subagent_topic_id ?? "").trim();
19934
20912
  const targetId = String(input.target_topic_id ?? "").trim();
19935
- const descendantIds = new Set(result.children.map((child) => child.id));
19936
- if (!descendantIds.has(sourceId)) {
20913
+ if (!result.owned(sourceId)) {
19937
20914
  return errorResult("Error: source is not a descendant subagent managed by this room.");
19938
20915
  }
19939
- if (targetId !== ctx.topicId && !descendantIds.has(targetId)) {
20916
+ if (!result.visibleTarget(targetId)) {
19940
20917
  return errorResult("Error: target is outside this room's managed subagent tree.");
19941
20918
  }
19942
20919
  if (host.storage.getTopic(sourceId)?.parentTopicId === targetId) {
@@ -19959,11 +20936,10 @@ ${card.task}${reportInstruction}`;
19959
20936
  return errorResult(result.error);
19960
20937
  const sourceId = String(input.subagent_topic_id ?? "").trim();
19961
20938
  const targetId = String(input.target_topic_id ?? "").trim();
19962
- const descendantIds = new Set(result.children.map((child) => child.id));
19963
- if (!descendantIds.has(sourceId)) {
20939
+ if (!result.owned(sourceId)) {
19964
20940
  return errorResult("Error: source is not a descendant subagent managed by this room.");
19965
20941
  }
19966
- if (targetId !== ctx.topicId && !descendantIds.has(targetId)) {
20942
+ if (!result.visibleTarget(targetId)) {
19967
20943
  return errorResult("Error: target is outside this room's managed subagent tree.");
19968
20944
  }
19969
20945
  const removed = host.sessionCommunication.revokeTellTarget(sourceId, targetId);
@@ -20045,6 +21021,7 @@ var init_spawn_subagent = __esm(async () => {
20045
21021
  init_types();
20046
21022
  await __promiseAll([
20047
21023
  init_bus(),
21024
+ init_actor_topic_reach(),
20048
21025
  init_api_messages(),
20049
21026
  init_api_topics(),
20050
21027
  init_runtime_leases(),
@@ -20186,6 +21163,8 @@ var init_spawn_subagent = __esm(async () => {
20186
21163
  });
20187
21164
 
20188
21165
  // ../../packages/core/src/mcp/session-comm/context.ts
21166
+ init_actor_topic_scope();
21167
+ init_remote_session_grant();
20189
21168
  init_types();
20190
21169
  function value(args, name) {
20191
21170
  const prefix = `--${name}=`;
@@ -20201,8 +21180,33 @@ function parseSessionCommContext(args, defaults) {
20201
21180
  if (!Number.isInteger(depth) || depth < 0) {
20202
21181
  throw new Error(`Invalid --depth arg: ${depthValue}`);
20203
21182
  }
21183
+ const scopeValue = value(args, "actor-topic-scope");
21184
+ let actorTopicScope;
21185
+ if (scopeValue) {
21186
+ let decoded;
21187
+ try {
21188
+ decoded = JSON.parse(Buffer.from(scopeValue, "base64url").toString("utf-8"));
21189
+ } catch {
21190
+ throw new Error("Invalid --actor-topic-scope arg");
21191
+ }
21192
+ const parsed = parseActorTopicScope(decoded);
21193
+ if (!parsed)
21194
+ throw new Error("Invalid --actor-topic-scope arg");
21195
+ actorTopicScope = parsed;
21196
+ }
21197
+ const grantValue = value(args, "remote-session-grant");
21198
+ let remoteSession;
21199
+ if (grantValue) {
21200
+ const decoded = decodeRemoteSessionGrantArg(grantValue);
21201
+ if (!decoded)
21202
+ throw new Error("Invalid --remote-session-grant arg");
21203
+ remoteSession = decoded;
21204
+ }
20204
21205
  return {
20205
21206
  userId: value(args, "user-id") ?? defaults.userId,
21207
+ actorUserId: value(args, "actor-user-id") || undefined,
21208
+ ...actorTopicScope ? { actorTopicScope } : {},
21209
+ ...remoteSession ? { remoteSession } : {},
20206
21210
  currentTopic: value(args, "topic") ?? "",
20207
21211
  currentTopicId: value(args, "topic-id") || undefined,
20208
21212
  currentThreadRootId: value(args, "thread-root-id") || undefined,
@@ -20219,7 +21223,7 @@ function createSessionTargetCatalog(host) {
20219
21223
  const { currentTopicId, currentTopicName, isAgent, listRows } = host;
20220
21224
  function listTargets() {
20221
21225
  const currentSurface = host.currentSurface;
20222
- const eligibleRows = listRows().filter((row) => row.kind !== "manager" && (!currentSurface || (row.surface ?? currentSurface) === currentSurface));
21226
+ const eligibleRows = listRows().filter((row) => row.kind !== "manager" && (!host.excludeAgentless || isAgent(row.agent)) && (!currentSurface || (row.surface ?? currentSurface) === currentSurface));
20223
21227
  const titleCounts = new Map;
20224
21228
  const qualifiedCounts = new Map;
20225
21229
  for (const row of eligibleRows) {
@@ -23432,4 +24436,4 @@ export {
23432
24436
  createAgentHealthMcpServer
23433
24437
  };
23434
24438
 
23435
- //# debugId=8058FA42EBEC001764756E2164756E21
24439
+ //# debugId=9C345085140AA6E664756E2164756E21