@otium-team/negotium 0.23.11 → 0.23.14

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 (95) hide show
  1. package/README.md +8 -0
  2. package/dist/agent-helpers.js +821 -1516
  3. package/dist/agent-helpers.js.map +22 -21
  4. package/dist/background-bash.js +48 -19
  5. package/dist/background-bash.js.map +6 -5
  6. package/dist/browser-runtime.js +96 -69
  7. package/dist/browser-runtime.js.map +6 -5
  8. package/dist/canonical-mcp-bridge.js +8 -9
  9. package/dist/canonical-mcp-bridge.js.map +1 -1
  10. package/dist/{chunk-0fenxbe6.js → chunk-3v58ejrk.js} +4 -5
  11. package/dist/{chunk-0fenxbe6.js.map → chunk-3v58ejrk.js.map} +2 -2
  12. package/dist/chunk-d1c2wt8q.js +83 -0
  13. package/dist/{chunk-ad7kxsaq.js.map → chunk-d1c2wt8q.js.map} +1 -1
  14. package/dist/{chunk-jtv8yzy1.js → chunk-m1ngkjdd.js} +12 -12
  15. package/dist/{chunk-jtv8yzy1.js.map → chunk-m1ngkjdd.js.map} +2 -2
  16. package/dist/{chunk-da9ad838.js → chunk-ng13grfj.js} +180 -152
  17. package/dist/{chunk-da9ad838.js.map → chunk-ng13grfj.js.map} +11 -10
  18. package/dist/{chunk-mxxwx5mg.js → chunk-pesnv5zv.js} +134 -143
  19. package/dist/chunk-pesnv5zv.js.map +14 -0
  20. package/dist/{chunk-f7p0h1gs.js → chunk-ww8a4ej4.js} +5 -5
  21. package/dist/{chunk-f7p0h1gs.js.map → chunk-ww8a4ej4.js.map} +2 -2
  22. package/dist/hosted-agent.js +204 -136
  23. package/dist/hosted-agent.js.map +7 -7
  24. package/dist/main.js +4340 -4529
  25. package/dist/main.js.map +31 -28
  26. package/dist/mcp-catalog.js +4 -4
  27. package/dist/mcp-catalog.js.map +1 -1
  28. package/dist/mcp-factories.js +1080 -1767
  29. package/dist/mcp-factories.js.map +21 -20
  30. package/dist/mcp-servers.js +5 -5
  31. package/dist/mcp-servers.js.map +1 -1
  32. package/dist/media.js +42 -13
  33. package/dist/media.js.map +6 -5
  34. package/dist/outbox.js +15 -15
  35. package/dist/outbox.js.map +2 -2
  36. package/dist/platform-runtime.js +7 -7
  37. package/dist/platform-runtime.js.map +1 -1
  38. package/dist/prompts.js +74 -15
  39. package/dist/prompts.js.map +8 -7
  40. package/dist/query-runtime.js +57 -30
  41. package/dist/query-runtime.js.map +7 -6
  42. package/dist/registry.js +22 -21
  43. package/dist/registry.js.map +3 -3
  44. package/dist/rollout.js +41 -41
  45. package/dist/rollout.js.map +2 -2
  46. package/dist/runtime/src/agents/claude-provider.ts +80 -5
  47. package/dist/runtime/src/agents/claude-registry.ts +2 -1
  48. package/dist/runtime/src/agents/explicit-agent-switch.ts +1 -1
  49. package/dist/runtime/src/agents/mcp-tools/self-config.ts +1 -1
  50. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +9 -1
  51. package/dist/runtime/src/agents/model-catalog.ts +13 -0
  52. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +84 -20
  53. package/dist/runtime/src/application/topic-service.ts +6 -2
  54. package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
  55. package/dist/runtime/src/bus.ts +6 -0
  56. package/dist/runtime/src/node-host.ts +11 -0
  57. package/dist/runtime/src/platform/browser-backend.ts +73 -0
  58. package/dist/runtime/src/platform/config.ts +3 -0
  59. package/dist/runtime/src/platform/mcp-config.ts +3 -0
  60. package/dist/runtime/src/prompts/builders.ts +11 -2
  61. package/dist/runtime/src/prompts/sessions/_shared-tools.md +2 -0
  62. package/dist/runtime/src/query/active-rooms.ts +7 -1
  63. package/dist/runtime/src/runtime/turn-event-stream.ts +34 -6
  64. package/dist/runtime/src/runtime/turn-runner.ts +54 -9
  65. package/dist/runtime/src/runtime-gateway.ts +198 -1
  66. package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
  67. package/dist/runtime/src/storage/runtime-turn-requests.ts +43 -2
  68. package/dist/runtime/src/storage/token-stats.ts +4 -0
  69. package/dist/runtime/src/types/api.ts +9 -0
  70. package/dist/runtime/src/types.ts +23 -0
  71. package/dist/runtime/src/version.ts +1 -1
  72. package/dist/runtime-gateway.js +73 -12
  73. package/dist/runtime-gateway.js.map +3 -3
  74. package/dist/runtime-helpers.js +107 -80
  75. package/dist/runtime-helpers.js.map +6 -5
  76. package/dist/sqlite.js +3 -5
  77. package/dist/sqlite.js.map +2 -2
  78. package/dist/storage.js +4843 -4812
  79. package/dist/storage.js.map +4 -4
  80. package/dist/types/packages/core/src/bus.d.ts +3 -0
  81. package/dist/types/packages/core/src/platform/browser-backend.d.ts +8 -0
  82. package/dist/types/packages/core/src/platform/config.d.ts +2 -0
  83. package/dist/types/packages/core/src/query/active-rooms.d.ts +7 -1
  84. package/dist/types/packages/core/src/runtime-gateway.d.ts +59 -1
  85. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +25 -0
  86. package/dist/types/packages/core/src/types/api.d.ts +5 -0
  87. package/dist/types/packages/core/src/types.d.ts +21 -0
  88. package/dist/types/packages/core/src/version.d.ts +1 -1
  89. package/dist/vault.js +64 -37
  90. package/dist/vault.js.map +6 -5
  91. package/package.json +1 -1
  92. package/dist/chunk-2mx7fq49.js +0 -6
  93. package/dist/chunk-2mx7fq49.js.map +0 -9
  94. package/dist/chunk-ad7kxsaq.js +0 -202
  95. package/dist/chunk-mxxwx5mg.js.map +0 -13
@@ -18,6 +18,7 @@ Use a tool only when it is actually available; otherwise say so instead of prete
18
18
  - Heavy work (large files, video encode, big crawls, browser automation): check `get_system_health` first and back off under resource pressure.
19
19
  - Computer Use: if unavailable, check `get_mcp_config` for optional `cua-rs`; MCP changes apply next session.
20
20
 
21
+ <!-- CHROME_BROWSER_START -->
21
22
  ## Browser
22
23
  Reading pages:
23
24
  - Escalate in this order: `browser_snapshot` (interactive elements only) → full snapshot → wait briefly and re-snapshot if the page is still changing → screenshot as a last resort. Never make a screenshot the first move.
@@ -36,3 +37,4 @@ When something fails:
36
37
 
37
38
  Coordinate input:
38
39
  - Use `browser_pointer`, `browser_wheel`, and `browser_drag` only for things the accessibility tree cannot expose (canvases, drag handles, maps), and return to ref-based actions immediately afterward.
40
+ <!-- CHROME_BROWSER_END -->
@@ -27,7 +27,7 @@ import {
27
27
  requestRuntimeTurnAbort,
28
28
  } from "#storage/runtime-leases";
29
29
  import type { AskReplySource } from "#storage/session-asks";
30
- import type { AgentKind, PeerRuntimeBridgeContext } from "#types";
30
+ import type { AgentKind, MidTurnMessage, PeerRuntimeBridgeContext } from "#types";
31
31
  import { createRoomQueryRegistry, type RoomQueryDecision } from "./room-query-registry";
32
32
  import { AbortReason } from "./types";
33
33
 
@@ -150,6 +150,12 @@ export interface RoomQueryControl {
150
150
  injectParams?: DeferredInject;
151
151
  /** True only after this process successfully queued a local replay. */
152
152
  injectRequeued?: boolean;
153
+ /**
154
+ * Set while this turn's provider takes messages mid-turn: hands it a message
155
+ * the same person sent, whose queued row is `requestId`. False when the turn
156
+ * can no longer take it, and the row then runs as the next turn.
157
+ */
158
+ deliverMidTurn?: (message: MidTurnMessage, requestId: string) => boolean;
153
159
  }
154
160
 
155
161
  // ── Room-keyed in-flight registry ──────────────────────────────────────
@@ -175,6 +175,12 @@ export async function runTurnEventStream(
175
175
  // Display-only text from `text_preview`, shown after pendingText until the
176
176
  // provider's completed `text` for that block arrives.
177
177
  let previewText = "";
178
+ // Where the text block currently streaming started in `accumulatedText` and
179
+ // `pendingText`, and the last completed block since the last tool boundary.
180
+ // A model can send the same sentence twice in a row (once as an interim note,
181
+ // once as the final answer); the second copy must not be glued onto the first.
182
+ let blockStart: { accumulated: number; pending: number } | null = null;
183
+ let lastCompletedBlock = "";
178
184
  let pendingMessage: { id: string; createdAt: string } | null = null;
179
185
  let previewTimer: ReturnType<typeof setTimeout> | null = null;
180
186
  const clearPreviewTimer = (): void => {
@@ -287,6 +293,8 @@ export async function runTurnEventStream(
287
293
  const text = pendingText.trimEnd();
288
294
  pendingText = "";
289
295
  previewText = "";
296
+ lastCompletedBlock = "";
297
+ blockStart = null;
290
298
  if (silent || !text.trim()) {
291
299
  // A `text_preview` that never got a completed `text` may already be on
292
300
  // screen; take it back like a discarded turn's preview.
@@ -409,6 +417,9 @@ export async function runTurnEventStream(
409
417
 
410
418
  switch (event.type) {
411
419
  case "text_delta": {
420
+ if (!pendingSawDelta) {
421
+ blockStart = { accumulated: accumulatedText.length, pending: pendingText.length };
422
+ }
412
423
  pendingSawDelta = true;
413
424
  const incoming = event.content;
414
425
  accumulatedText += incoming;
@@ -425,12 +436,29 @@ export async function runTurnEventStream(
425
436
  case "text":
426
437
  // The completed block replaces whatever preview was shown for it.
427
438
  previewText = "";
428
- if (pendingSawDelta) {
429
- // Some providers emit tool_use before the completed copy of the
430
- // streamed text block. A tool flush must not make that copy look
431
- // like a new segment; consume it here as the delta terminator.
432
- pendingSawDelta = false;
433
- break;
439
+ {
440
+ const completed = event.content.trim();
441
+ const repeatsPreviousBlock = completed !== "" && completed === lastCompletedBlock;
442
+ if (pendingSawDelta) {
443
+ // Some providers emit tool_use before the completed copy of the
444
+ // streamed text block. A tool flush must not make that copy look
445
+ // like a new segment; consume it here as the delta terminator.
446
+ pendingSawDelta = false;
447
+ if (repeatsPreviousBlock && blockStart) {
448
+ // The repeat already streamed in as deltas: take it back out.
449
+ accumulatedText = accumulatedText.slice(0, blockStart.accumulated);
450
+ pendingText = pendingText.slice(0, blockStart.pending);
451
+ assistantContextTokens = estimateTextTokens(accumulatedText);
452
+ broadcastContextProgress();
453
+ } else if (completed) {
454
+ lastCompletedBlock = completed;
455
+ }
456
+ blockStart = null;
457
+ break;
458
+ }
459
+ // The same block twice in a row, with no tool call between: keep one.
460
+ if (repeatsPreviousBlock) break;
461
+ if (completed) lastCompletedBlock = completed;
434
462
  }
435
463
  {
436
464
  const incoming = event.content;
@@ -20,6 +20,8 @@ import { getRegistryOperations } from "#agents/registry";
20
20
  import { WsHub } from "#bus";
21
21
  import { asTurnId, asTurnSlotKey, type TurnSlotKey } from "#identifiers";
22
22
  import { ensureBgBash } from "#platform/background-bash/manager";
23
+ import { prepareEgoBrowser } from "#platform/browser-backend";
24
+ import { BROWSER_BACKEND } from "#platform/config";
23
25
  import { FROM_AUTO_CONTINUE } from "#platform/constants";
24
26
  import { logger } from "#platform/logger";
25
27
  import { consumePlaywrightUnavailable, markPlaywrightUnavailable } from "#platform/mcp-config";
@@ -99,6 +101,7 @@ import { getRuntimeTopicEpoch, isRuntimeTopicMaintenance } from "#storage/runtim
99
101
  import {
100
102
  claimNextRuntimeUserTurnRequest,
101
103
  completeRuntimeUserTurnRequest,
104
+ dropReadMidTurnRequest,
102
105
  getActiveRuntimeUserTurnRequest,
103
106
  markRuntimeUserTurnMessagesLogged,
104
107
  markRuntimeUserTurnRunning,
@@ -121,6 +124,7 @@ import type {
121
124
  ActorTopicScope,
122
125
  AgentKind,
123
126
  EffortLevel,
127
+ MidTurnInput,
124
128
  PeerRuntimeBridgeContext,
125
129
  RemoteSessionGrant,
126
130
  UnifiedEvent,
@@ -196,7 +200,7 @@ function notifyPlaywrightUnavailable(topicId: string) {
196
200
  topicId,
197
201
  "Playwright browser tools are unavailable this turn. Browser automation was removed from the tool catalog; retry shortly if browser interaction is required.",
198
202
  );
199
- WsHub.get().broadcastTopicNotice(topicId, "info", "Playwright 사용 불가");
203
+ WsHub.get().broadcastTopicNotice(topicId, "info", "Playwright unavailable");
200
204
  }
201
205
 
202
206
  function appendAskReplyMessage(
@@ -1429,6 +1433,30 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1429
1433
  from: params.from,
1430
1434
  },
1431
1435
  };
1436
+ // A person's turn reads what they send while it works (gateway `inject`). The
1437
+ // provider opens this when it can feed its live turn; on close, a read
1438
+ // message's queued row is dropped, and every unread one runs as the next turn.
1439
+ const midTurnRows = new Map<string, string>();
1440
+ const midTurn: MidTurnInput | undefined =
1441
+ control.actorUserId !== undefined
1442
+ ? {
1443
+ open: (deliver) => {
1444
+ control.deliverMidTurn = (message, requestId) => {
1445
+ if (!deliver(message)) return false;
1446
+ midTurnRows.set(message.id, requestId);
1447
+ return true;
1448
+ };
1449
+ },
1450
+ close: (read) => {
1451
+ control.deliverMidTurn = undefined;
1452
+ const dropped = read.filter((id) => {
1453
+ const row = midTurnRows.get(id);
1454
+ return row !== undefined && dropReadMidTurnRequest(topicId, row);
1455
+ });
1456
+ if (dropped.length > 0) WsHub.get().broadcastMidTurnRead(topicId, queryId, dropped);
1457
+ },
1458
+ }
1459
+ : undefined;
1432
1460
  if (!setRoomQuery(control)) {
1433
1461
  // Another process won the lease between the decision and the atomic claim.
1434
1462
  // Preserve the same user-priority behavior and retry after that owner
@@ -1673,7 +1701,7 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1673
1701
 
1674
1702
  if (params.from === FROM_AUTO_CONTINUE) {
1675
1703
  turnReminders.push(
1676
- "<system-reminder>이 턴은 설정 자동 조정(effort/model/agent) 후 자동 재개된 턴이다. effort/model/agent 난이도 재평가 및 설정 변경 없이 즉시 작업을 시작할 것.</system-reminder>",
1704
+ "<system-reminder>This turn was auto-resumed after an automatic settings adjustment (effort/model/agent). Start the work immediately, without re-evaluating difficulty or changing effort/model/agent settings.</system-reminder>",
1677
1705
  );
1678
1706
  }
1679
1707
 
@@ -1722,7 +1750,10 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1722
1750
  const enabledMcp = withDefaultPlaywright(configuredMcp, isManager);
1723
1751
  const playwrightRequested = !isManager && enabledMcp.includes("playwright");
1724
1752
  const browserProfileOwner = isTopicBrowserProfileOwner(topic.id, userId);
1725
- const wantsPlaywright = playwrightRequested && browserProfileOwner;
1753
+ const wantsPlaywright =
1754
+ playwrightRequested && browserProfileOwner && BROWSER_BACKEND === "chrome";
1755
+ const wantsEgoBrowser =
1756
+ playwrightRequested && browserProfileOwner && BROWSER_BACKEND === "egolite";
1726
1757
  const turnMcpEnabled = browserProfileOwner
1727
1758
  ? enabledMcp
1728
1759
  : enabledMcp.filter((name) => name !== "playwright");
@@ -1752,6 +1783,19 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1752
1783
  let playwrightCapability: string | undefined;
1753
1784
  let playwrightInstanceKey: string | undefined;
1754
1785
  let bgBashPort: number | undefined;
1786
+ if (wantsEgoBrowser) {
1787
+ try {
1788
+ const command = await prepareEgoBrowser();
1789
+ turnReminders.push(
1790
+ `<system-reminder>Browser backend: ego lite. Browser automation is authorized for this topic owner on this Negotium node. Use the foreground shell with executable ${JSON.stringify(command)}. Read its full "skill" guide before the first browser action. Reuse this goal's task space across turns. No Chrome browser_* MCP tools are available. This probe checked only the CLI; actual browser connection and login must be verified when used.</system-reminder>`,
1791
+ );
1792
+ } catch (err) {
1793
+ logger.warn({ topicId, err }, "ai: ego-browser CLI unavailable");
1794
+ turnReminders.push(
1795
+ "<system-reminder>ego lite browser automation is UNAVAILABLE this turn: the ego-browser executable could not be found or its --version probe failed on this Negotium node. Tell the user when browser work is needed. Do not start Chrome, install software, or use another browser as a fallback.</system-reminder>",
1796
+ );
1797
+ }
1798
+ }
1755
1799
  if (wantsPlaywright) {
1756
1800
  try {
1757
1801
  playwrightInstanceKey = makeInstanceKey(userId, topic.id);
@@ -1795,7 +1839,7 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1795
1839
  }
1796
1840
  if (playwrightRequested && !browserProfileOwner) {
1797
1841
  turnReminders.push(
1798
- "<system-reminder>Browser tools are unavailable in this turn because browser profiles are private to the topic owner. Do not attempt browser calls or ask to reuse the owner's login state.</system-reminder>",
1842
+ "<system-reminder>Browser tools are unavailable in this turn because browser profiles are private to the topic owner. Do not attempt browser calls, run ego-browser through a shell, or ask to reuse the owner's login state.</system-reminder>",
1799
1843
  );
1800
1844
  }
1801
1845
  if (consumePlaywrightUnavailable(userId, topic.title)) {
@@ -1812,6 +1856,7 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
1812
1856
  yield* runAgent({
1813
1857
  agent: agentKind,
1814
1858
  ...reminderQuery,
1859
+ ...(midTurn ? { midTurn } : {}),
1815
1860
  attachments: promptAttachments,
1816
1861
  cwd: workspaceCwd,
1817
1862
  systemPrompt,
@@ -2061,7 +2106,7 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
2061
2106
  if (!silent) {
2062
2107
  appendSystemMessage(
2063
2108
  topicId,
2064
- "여기까지 완료했어요. 비용 예산 한도에 도달해 작업을 멈췄습니다.",
2109
+ "Completed up to this point. Work stopped because it reached the cost budget limit.",
2065
2110
  threadRootId,
2066
2111
  );
2067
2112
  WsHub.get().broadcastDone(
@@ -2078,7 +2123,7 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
2078
2123
  : undefined,
2079
2124
  { agent: agentKind, model: resolvedModel, budgetReason: outcome.reason },
2080
2125
  );
2081
- WsHub.get().broadcastTopicNotice(topicId, "warning", "예산 한도 도달");
2126
+ WsHub.get().broadcastTopicNotice(topicId, "warning", "Budget limit reached");
2082
2127
  }
2083
2128
  // Visible ask_session turns run on the target session too, so the
2084
2129
  // caller must hear about the cap regardless of `silent`.
@@ -2099,11 +2144,11 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
2099
2144
  // providers and explicitly change this topic with /model.
2100
2145
  appendSystemMessage(
2101
2146
  topicId,
2102
- `${classifyAgentError(outcome.error, agentKind)}\n\n다른 등록된 모델을 쓰려면 /model <model>로 바꾼 뒤 다시 보내세요.`,
2147
+ `${classifyAgentError(outcome.error, agentKind)}\n\nTo use another registered model, switch with /model <model> and send again.`,
2103
2148
  threadRootId,
2104
2149
  );
2105
2150
  WsHub.get().broadcastError(topicId, queryId, outcome.error);
2106
- WsHub.get().broadcastTopicNotice(topicId, "error", "응답 실패");
2151
+ WsHub.get().broadcastTopicNotice(topicId, "error", "Response failed");
2107
2152
  }
2108
2153
  await deliverAskError(queryId, topic.title, outcome.error);
2109
2154
  await settleSubagentFailure(queryId, classifyAgentError(outcome.error, agentKind));
@@ -2137,7 +2182,7 @@ export function startAiTurn(params: StartAiTurnParams): string | null {
2137
2182
  );
2138
2183
  if (!silent) {
2139
2184
  WsHub.get().broadcastError(topicId, queryId, error);
2140
- WsHub.get().broadcastTopicNotice(topicId, "error", "응답 실패");
2185
+ WsHub.get().broadcastTopicNotice(topicId, "error", "Response failed");
2141
2186
  }
2142
2187
  await deliverAskError(queryId, topic.title, error);
2143
2188
  await settleSubagentFailure(queryId, classifyAgentError(error, agentKind));
@@ -1,5 +1,5 @@
1
1
  import type { ActorTopicScope, RemoteSessionGrant } from "#types";
2
- import type { MessageDto } from "#types/api";
2
+ import type { AttachmentDto, MessageDto } from "#types/api";
3
3
 
4
4
  export const RUNTIME_GATEWAY_VERSION = 1 as const;
5
5
  export const RUNTIME_GATEWAY_CONTROL_PATH = "/api/v1/control/runtime/v1";
@@ -151,6 +151,20 @@ export interface RuntimeGatewayTurnInput {
151
151
  * resumes with the merged batch; `false` queues this message behind it.
152
152
  */
153
153
  steer?: boolean;
154
+ /**
155
+ * While a turn from the same person runs: deliver this message into it, read
156
+ * after the step it is on, and the work goes on (Codex-style steer). Wins over
157
+ * `steer`; when the turn cannot take it, the message is queued behind it. A
158
+ * node too old for this ignores the field, so send `steer: false` with it.
159
+ */
160
+ inject?: boolean;
161
+ /**
162
+ * While the room works, hold this message as a follow-up instead of queuing
163
+ * a turn (`turn-follow-ups` capability; use `holdOrSubmitTurn`). Held, it
164
+ * is not in the transcript and can be edited, moved, deleted or sent now; the
165
+ * node sends held follow-ups one per turn once the room is idle.
166
+ */
167
+ hold?: boolean;
154
168
  /** Run without adding the injected prompt or output to the visible transcript. */
155
169
  silent?: boolean;
156
170
  attachments?: string[];
@@ -174,6 +188,39 @@ export interface RuntimeGatewayTurnAcknowledgement {
174
188
  cursor: number;
175
189
  }
176
190
 
191
+ /** A message held while the room worked (`turn-follow-ups`). */
192
+ export interface RuntimeGatewayFollowUp {
193
+ id: string;
194
+ text: string;
195
+ actorUserId: string;
196
+ attachments: AttachmentDto[];
197
+ createdAt: string;
198
+ }
199
+
200
+ /** A room's held follow-ups, oldest first, and whether they wait after a stop. */
201
+ export interface RuntimeGatewayFollowUpLine {
202
+ topicId: string;
203
+ followUps: RuntimeGatewayFollowUp[];
204
+ paused: boolean;
205
+ }
206
+
207
+ export interface RuntimeGatewayHeldTurn {
208
+ ok: true;
209
+ v: typeof RUNTIME_GATEWAY_VERSION;
210
+ accepted: true;
211
+ held: true;
212
+ clientMessageId: string;
213
+ topicId: string;
214
+ followUp: RuntimeGatewayFollowUp;
215
+ }
216
+
217
+ export interface RuntimeGatewayFollowUpActor {
218
+ /** Canonical principal on the execution node. */
219
+ userId: string;
220
+ /** The person who sent it; only they may change it. Defaults to `userId`. */
221
+ actorUserId?: string;
222
+ }
223
+
177
224
  export interface RuntimeGatewayTopicDeriveInput {
178
225
  userId: string;
179
226
  copyHistory: boolean;
@@ -346,6 +393,40 @@ function validTurnAck(value: unknown): value is RuntimeGatewayTurnAcknowledgemen
346
393
  );
347
394
  }
348
395
 
396
+ function validFollowUp(value: unknown): value is RuntimeGatewayFollowUp {
397
+ const item = record(value);
398
+ return Boolean(
399
+ typeof item?.id === "string" &&
400
+ typeof item.text === "string" &&
401
+ typeof item.actorUserId === "string" &&
402
+ Array.isArray(item.attachments) &&
403
+ typeof item.createdAt === "string",
404
+ );
405
+ }
406
+
407
+ function validFollowUpLine(value: unknown): value is RuntimeGatewayFollowUpLine {
408
+ const body = record(value);
409
+ return Boolean(
410
+ typeof body?.topicId === "string" &&
411
+ Array.isArray(body.followUps) &&
412
+ body.followUps.every(validFollowUp) &&
413
+ typeof body.paused === "boolean",
414
+ );
415
+ }
416
+
417
+ function validHeldTurn(value: unknown): value is RuntimeGatewayHeldTurn {
418
+ const body = record(value);
419
+ return Boolean(
420
+ body?.ok === true &&
421
+ body.v === RUNTIME_GATEWAY_VERSION &&
422
+ body.accepted === true &&
423
+ body.held === true &&
424
+ typeof body.clientMessageId === "string" &&
425
+ typeof body.topicId === "string" &&
426
+ validFollowUp(body.followUp),
427
+ );
428
+ }
429
+
349
430
  function validManagerTopic(value: unknown): value is RuntimeGatewayManagerTopic {
350
431
  const topic = record(value);
351
432
  return Boolean(
@@ -529,6 +610,122 @@ export class RuntimeGatewayClient {
529
610
  return body;
530
611
  }
531
612
 
613
+ /**
614
+ * `submitTurn` with `hold: true`: while the room works the node holds the
615
+ * message as a follow-up and answers with it; otherwise it is a turn as usual.
616
+ */
617
+ async holdOrSubmitTurn(
618
+ input: RuntimeGatewayTurnInput,
619
+ ): Promise<RuntimeGatewayTurnAcknowledgement | RuntimeGatewayHeldTurn> {
620
+ const response = await this.send(
621
+ "/turns",
622
+ {
623
+ method: "POST",
624
+ headers: { "content-type": "application/json" },
625
+ body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...input, hold: true }),
626
+ },
627
+ this.requestTimeoutMs,
628
+ );
629
+ if (response.status !== 202) {
630
+ throw new RuntimeGatewayError(
631
+ "Runtime Gateway turn was not accepted",
632
+ "http",
633
+ response.status,
634
+ );
635
+ }
636
+ const body = await json(response);
637
+ if (validHeldTurn(body) || validTurnAck(body)) return body;
638
+ throw new RuntimeGatewayError(
639
+ "Runtime Gateway turn acknowledgement is incompatible",
640
+ "protocol",
641
+ );
642
+ }
643
+
644
+ async followUps(topicId: string, userId: string): Promise<RuntimeGatewayFollowUpLine> {
645
+ const response = await this.send(
646
+ `/topics/${encodeURIComponent(topicId)}/follow-ups?userId=${encodeURIComponent(userId)}`,
647
+ { method: "GET" },
648
+ this.requestTimeoutMs,
649
+ );
650
+ return this.followUpLineFrom(response, "list");
651
+ }
652
+
653
+ async editFollowUp(
654
+ topicId: string,
655
+ followUpId: string,
656
+ actor: RuntimeGatewayFollowUpActor,
657
+ text: string,
658
+ ): Promise<RuntimeGatewayFollowUpLine> {
659
+ return this.changeFollowUp(topicId, followUpId, "", "PATCH", { ...actor, text });
660
+ }
661
+
662
+ async deleteFollowUp(
663
+ topicId: string,
664
+ followUpId: string,
665
+ actor: RuntimeGatewayFollowUpActor,
666
+ ): Promise<RuntimeGatewayFollowUpLine> {
667
+ return this.changeFollowUp(topicId, followUpId, "", "DELETE", { ...actor });
668
+ }
669
+
670
+ async moveFollowUp(
671
+ topicId: string,
672
+ followUpId: string,
673
+ actor: RuntimeGatewayFollowUpActor,
674
+ toIndex: number,
675
+ ): Promise<RuntimeGatewayFollowUpLine> {
676
+ return this.changeFollowUp(topicId, followUpId, "/move", "POST", { ...actor, toIndex });
677
+ }
678
+
679
+ /** 지금 보내기: into the running turn when it can take it, else as a turn of its own. */
680
+ async sendFollowUpNow(
681
+ topicId: string,
682
+ followUpId: string,
683
+ actor: RuntimeGatewayFollowUpActor,
684
+ ): Promise<RuntimeGatewayFollowUpLine & { sent: boolean }> {
685
+ const line = await this.changeFollowUp(topicId, followUpId, "/send", "POST", { ...actor });
686
+ return line as RuntimeGatewayFollowUpLine & { sent: boolean };
687
+ }
688
+
689
+ private async changeFollowUp(
690
+ topicId: string,
691
+ followUpId: string,
692
+ suffix: "" | "/move" | "/send",
693
+ method: "PATCH" | "DELETE" | "POST",
694
+ body: Record<string, unknown>,
695
+ ): Promise<RuntimeGatewayFollowUpLine> {
696
+ const response = await this.send(
697
+ `/topics/${encodeURIComponent(topicId)}/follow-ups/${encodeURIComponent(followUpId)}${suffix}`,
698
+ {
699
+ method,
700
+ headers: { "content-type": "application/json" },
701
+ body: JSON.stringify({ v: RUNTIME_GATEWAY_VERSION, ...body }),
702
+ },
703
+ this.requestTimeoutMs,
704
+ );
705
+ return this.followUpLineFrom(response, method === "PATCH" ? "edit" : suffix || "delete");
706
+ }
707
+
708
+ private async followUpLineFrom(
709
+ response: Response,
710
+ what: string,
711
+ ): Promise<RuntimeGatewayFollowUpLine> {
712
+ if (!response.ok) {
713
+ throw new RuntimeGatewayError(
714
+ `Runtime Gateway follow-up ${what} failed`,
715
+ "http",
716
+ response.status,
717
+ );
718
+ }
719
+ const body = await json(response);
720
+ if (!validFollowUpLine(body)) {
721
+ throw new RuntimeGatewayError(
722
+ `Runtime Gateway follow-up ${what} response is incompatible`,
723
+ "protocol",
724
+ );
725
+ }
726
+ return body;
727
+ }
728
+
532
729
  async deriveTopic(
533
730
  topicId: string,
534
731
  input: RuntimeGatewayTopicDeriveInput,