@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
@@ -1,9 +1,16 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { hostMcpGrantRefusal, isReservedRuntimeMcpServerName } from "#platform/mcp-config";
3
+ import { abortRoom, getRoomQuery } from "#query/active-rooms";
4
+ import { AbortReason } from "#query/types";
3
5
  import { stampActorTopicScope } from "#runtime/actor-topic-scope";
4
6
  import { resolveAttachmentByFileId } from "#runtime/file-hooks";
5
7
  import { describeQuotedAuthor } from "#runtime/thread-context";
6
- import type { UserTurnReplyContext } from "#runtime/user-turn-envelope";
8
+ import {
9
+ renderUserTurnBatch,
10
+ renderUserTurnPrompt,
11
+ type UserTurnEnvelope,
12
+ type UserTurnReplyContext,
13
+ } from "#runtime/user-turn-envelope";
7
14
  import { type HostMcpServerSpec, parseHostMcpServers } from "#runtime-gateway";
8
15
  import { appendApiMessage, getApiMessage } from "#storage/api-messages";
9
16
  import { getTopicSessionId } from "#storage/api-topics";
@@ -15,9 +22,9 @@ import {
15
22
  type RuntimeGatewaySubmission,
16
23
  recordRuntimeGatewaySubmission,
17
24
  } from "#storage/runtime-gateway-submissions";
18
- import { requestRuntimeTurnAbort } from "#storage/runtime-leases";
19
25
  import { getRuntimeTopicEpoch } from "#storage/runtime-topic-state";
20
26
  import {
27
+ enqueueRuntimeUserTurnRequest,
21
28
  getActiveRuntimeUserTurnRequest,
22
29
  mergeRuntimeUserTurnRequest,
23
30
  } from "#storage/runtime-turn-requests";
@@ -61,6 +68,19 @@ export interface SubmitRuntimeGatewayTurnParams {
61
68
  * `false`: leave the running turn alone and queue this message behind it.
62
69
  */
63
70
  steer?: boolean;
71
+ /**
72
+ * Deliver into the same person's running turn, read after the step it is on,
73
+ * and the work goes on (Codex-style steer; wins over `steer`). Only a turn
74
+ * this process runs on a provider that takes live input can; otherwise the
75
+ * message waits in the queue as with `steer: false`. Either way it is queued
76
+ * first, so a delivered message the turn does not read still runs next.
77
+ */
78
+ inject?: boolean;
79
+ /**
80
+ * Run as a turn of its own: never folded into a queued request or into the
81
+ * running one. A held follow-up goes out this way (`turn-follow-ups`).
82
+ */
83
+ ownTurn?: boolean;
64
84
  /** Hide both the injected prompt and provider output from the visible topic. */
65
85
  silent?: boolean;
66
86
  /** Answer inside this thread instead of the room's main flow (S-13). */
@@ -318,6 +338,7 @@ export function submitRuntimeGatewayTurn(
318
338
  // never recorded, stays a separate queue entry), and only a folded turn has
319
339
  // a replacement batch to resume from after the abort.
320
340
  let steersActiveTurn = false;
341
+ let delivery: "injected" | "queued" | "steered" | "started" | undefined;
321
342
  try {
322
343
  db.transaction(() => {
323
344
  if (!params.silent) appendApiMessage(message, { notify: false });
@@ -327,20 +348,32 @@ export function submitRuntimeGatewayTurn(
327
348
  // except that no turn is queued for it.
328
349
  if (respond) {
329
350
  const active = getActiveRuntimeUserTurnRequest(params.topic.id);
330
- const merged = mergeRuntimeUserTurnRequest({
351
+ const envelope: UserTurnEnvelope = {
352
+ prompt: params.text,
353
+ actorUserId,
354
+ ...(params.actorLabel ? { actorLabel: params.actorLabel } : {}),
355
+ ...(params.attachments?.length ? { attachments: params.attachments } : {}),
356
+ ...(replyTo ? { replyTo } : {}),
357
+ };
358
+ // The running turn this message can be read inside: the same person's,
359
+ // in the same flow, run by this process on a provider that takes live
360
+ // input. Attachments wait for a turn of their own.
361
+ const live =
362
+ params.inject === true && active && !params.silent && !params.attachments?.length
363
+ ? getRoomQuery(params.topic.id)
364
+ : undefined;
365
+ const injectInto =
366
+ live?.deliverMidTurn &&
367
+ live.queryId === active?.runningQueryId &&
368
+ active?.execution?.actorUserId === actorUserId &&
369
+ active?.execution?.threadRootId === params.threadRootId
370
+ ? live.deliverMidTurn
371
+ : undefined;
372
+ const queued = {
331
373
  topicId: params.topic.id,
332
374
  userId: params.userId,
333
- userMessages: [
334
- {
335
- prompt: params.text,
336
- actorUserId,
337
- ...(params.actorLabel ? { actorLabel: params.actorLabel } : {}),
338
- ...(params.attachments?.length ? { attachments: params.attachments } : {}),
339
- ...(replyTo ? { replyTo } : {}),
340
- },
341
- ],
375
+ userMessages: [envelope],
342
376
  allowAutoContinue: params.allowAutoContinue ?? true,
343
- ...(params.steer === false && active ? { keepRequestIds: [active.requestId] } : {}),
344
377
  requestId,
345
378
  topicEpoch: getRuntimeTopicEpoch(params.topic.id),
346
379
  execution: {
@@ -368,9 +401,38 @@ export function submitRuntimeGatewayTurn(
368
401
  fileDeliveryTools: params.fileDeliveryTools,
369
402
  ...(params.threadRootId ? { threadRootId: params.threadRootId } : {}),
370
403
  },
371
- });
372
- steersActiveTurn =
373
- active !== null && merged.supersededRequestIds.includes(active.requestId);
404
+ };
405
+ if (injectInto?.({ id: message.id, text: renderUserTurnPrompt(envelope) }, requestId)) {
406
+ // Queued all the same, as its own row that is never folded into
407
+ // another: once the running turn reads the message exactly this row
408
+ // is dropped, and if the turn ends without reading it, it runs next.
409
+ enqueueRuntimeUserTurnRequest({
410
+ ...queued,
411
+ prompt: renderUserTurnBatch([envelope]),
412
+ execution: { ...queued.execution, deliveredMidTurn: true },
413
+ supersedeExisting: false,
414
+ });
415
+ delivery = "injected";
416
+ } else if (params.ownTurn === true) {
417
+ enqueueRuntimeUserTurnRequest({
418
+ ...queued,
419
+ prompt: renderUserTurnBatch([envelope]),
420
+ ...(params.attachments?.length ? { attachments: params.attachments } : {}),
421
+ execution: { ...queued.execution, ownTurn: true },
422
+ supersedeExisting: false,
423
+ });
424
+ delivery = active ? "queued" : "started";
425
+ } else {
426
+ const merged = mergeRuntimeUserTurnRequest({
427
+ ...queued,
428
+ ...((params.steer === false || params.inject === true) && active
429
+ ? { keepRequestIds: [active.requestId] }
430
+ : {}),
431
+ });
432
+ steersActiveTurn =
433
+ active !== null && merged.supersededRequestIds.includes(active.requestId);
434
+ delivery = steersActiveTurn ? "steered" : active ? "queued" : "started";
435
+ }
374
436
  }
375
437
  if (hostMcpServers !== undefined) {
376
438
  recordTopicHostMcpGrant(params.topic.id, hostMcpServers);
@@ -383,6 +445,7 @@ export function submitRuntimeGatewayTurn(
383
445
  requestId,
384
446
  clientMessageId: params.clientMessageId,
385
447
  messageId: message.id,
448
+ ...(delivery ? { delivery } : {}),
386
449
  },
387
450
  });
388
451
  const messageEvent = params.silent
@@ -404,9 +467,10 @@ export function submitRuntimeGatewayTurn(
404
467
  }
405
468
 
406
469
  // A new message from the *same* person steers the active topic turn. The
407
- // durable replacement is committed first; the provider observes this abort
408
- // on its next lease heartbeat and the worker resumes the merged batch after
409
- // unwind.
470
+ // durable replacement is committed first; `abortRoom` stops the provider at
471
+ // once when this process holds the turn (and still flags the lease so an
472
+ // owner in another process sees it on its next heartbeat), and the worker
473
+ // resumes the merged batch after unwind.
410
474
  //
411
475
  // That resume is the whole reason the abort is safe, so it is conditional on
412
476
  // the merge having absorbed the active turn: with `respond: false` there is
@@ -414,7 +478,7 @@ export function submitRuntimeGatewayTurn(
414
478
  // unknown) is being answered, that answer is left to finish — the new
415
479
  // request waits its turn in the queue and runs with its own actor and
416
480
  // assertion.
417
- if (steersActiveTurn) requestRuntimeTurnAbort(params.topic.id, "internal");
481
+ if (steersActiveTurn) abortRoom(params.topic.id, AbortReason.Internal);
418
482
 
419
483
  return { ...submission, message, deduplicated: false };
420
484
  }
@@ -6,8 +6,9 @@ import {
6
6
  import { answerPendingVaultSecretRequest } from "#agents/mcp-tools/request-vault";
7
7
  import { WsHub } from "#bus";
8
8
  import { abortRoom, getRoomQuery } from "#query/active-rooms";
9
+ import { AbortReason } from "#query/types";
9
10
  import { getTopic } from "#storage/api-topics";
10
- import { getRuntimeTurnLease, requestRuntimeTurnAbort } from "#storage/runtime-leases";
11
+ import { getRuntimeTurnLease } from "#storage/runtime-leases";
11
12
  import { beginRuntimeTopicMaintenance } from "#storage/runtime-topic-state";
12
13
  import {
13
14
  cancelRuntimeUserTurnRequestsBeforeEpoch,
@@ -157,7 +158,10 @@ export const topicService = {
157
158
  participantTopic(topicId, userId);
158
159
  const folded = foldQueuedIntoActiveRuntimeUserTurnRequest(topicId, randomUUID());
159
160
  if (!folded) return false;
160
- requestRuntimeTurnAbort(topicId, "internal");
161
+ // Abort in-process immediately when this runtime process holds the turn
162
+ // (the common single-process case); `requestRuntimeTurnAbort` alone would
163
+ // only mark the lease and wait for the next ~1s heartbeat poll to notice.
164
+ abortRoom(topicId, AbortReason.Internal);
161
165
  return true;
162
166
  },
163
167
 
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Follow-ups: messages a person sends while the room's AI works, held by the
3
+ * node instead of queued as a turn, the way Codex holds its queue. A host opts
4
+ * in per message with `hold`; without it nothing here runs, so hosts that never
5
+ * send it (the terminal, Telegram) keep the queue and steer they have.
6
+ *
7
+ * A held message is not in the transcript yet. Until it goes out it can be
8
+ * edited in place, moved or deleted, or sent now (into the running turn when it
9
+ * can take it). When the room is idle the oldest goes out as a turn of its own,
10
+ * one per turn. A person stopping the AI holds the rest until they send again.
11
+ * Every change is announced as a `follow_ups` ai-status with the whole line.
12
+ */
13
+ import { logger } from "#platform/logger";
14
+ import { getRoomQuery } from "#query/active-rooms";
15
+ import { stampActorTopicScope } from "#runtime/actor-topic-scope";
16
+ import { resolveAttachmentByFileId } from "#runtime/file-hooks";
17
+ import { getTopic } from "#storage/api-topics";
18
+ import { appendRuntimeEvent } from "#storage/runtime-events";
19
+ import {
20
+ areRuntimeFollowUpsPaused,
21
+ deleteRuntimeFollowUpsForTopic,
22
+ editRuntimeFollowUpText,
23
+ getRuntimeFollowUp,
24
+ holdRuntimeFollowUp,
25
+ listRuntimeFollowUps,
26
+ moveRuntimeFollowUp,
27
+ type RuntimeFollowUp,
28
+ restoreRuntimeFollowUp,
29
+ runtimeFollowUpTopicsReady,
30
+ setRuntimeFollowUpsPaused,
31
+ takeRuntimeFollowUp,
32
+ } from "#storage/runtime-follow-ups";
33
+ import { findRuntimeGatewaySubmission } from "#storage/runtime-gateway-submissions";
34
+ import { getRuntimeTurnLease } from "#storage/runtime-leases";
35
+ import { isRuntimeTopicMaintenance } from "#storage/runtime-topic-state";
36
+ import { getRuntimeUserTurnRequest } from "#storage/runtime-turn-requests";
37
+ import type { AttachmentDto } from "#types/api";
38
+ import {
39
+ type SubmitRuntimeGatewayTurnParams,
40
+ type SubmitRuntimeGatewayTurnResult,
41
+ submitRuntimeGatewayTurn,
42
+ } from "./submit-runtime-gateway-turn";
43
+
44
+ export interface FollowUpView {
45
+ id: string;
46
+ text: string;
47
+ actorUserId: string;
48
+ attachments: AttachmentDto[];
49
+ createdAt: string;
50
+ }
51
+
52
+ export interface FollowUpLine {
53
+ topicId: string;
54
+ followUps: FollowUpView[];
55
+ /** Held after a stop: nothing goes out by itself until the person sends again. */
56
+ paused: boolean;
57
+ }
58
+
59
+ export type HoldOrSubmitResult =
60
+ | { held: true; followUp: FollowUpView }
61
+ | { held: false; submission: SubmitRuntimeGatewayTurnResult };
62
+
63
+ function view(followUp: RuntimeFollowUp): FollowUpView {
64
+ return {
65
+ id: followUp.followUpId,
66
+ text: followUp.text,
67
+ actorUserId: followUp.actorUserId,
68
+ attachments: followUp.attachments
69
+ .map(resolveAttachmentByFileId)
70
+ .filter((attachment): attachment is AttachmentDto => attachment !== null),
71
+ createdAt: new Date(followUp.createdAt).toISOString(),
72
+ };
73
+ }
74
+
75
+ export function followUpLine(topicId: string): FollowUpLine {
76
+ return {
77
+ topicId,
78
+ followUps: listRuntimeFollowUps(topicId).map(view),
79
+ paused: areRuntimeFollowUpsPaused(topicId),
80
+ };
81
+ }
82
+
83
+ function announce(topicId: string): void {
84
+ const { followUps, paused } = followUpLine(topicId);
85
+ appendRuntimeEvent("runtime-follow-ups", {
86
+ type: "ai-status",
87
+ topicId,
88
+ payload: { kind: "follow_ups", followUps, paused },
89
+ });
90
+ }
91
+
92
+ /** Whether the room's AI has work now: a turn running or queued, or the room held for upkeep. */
93
+ export function isRoomWorking(topicId: string): boolean {
94
+ return (
95
+ getRuntimeUserTurnRequest(topicId) !== null ||
96
+ getRoomQuery(topicId) !== undefined ||
97
+ getRuntimeTurnLease(topicId) !== null ||
98
+ isRuntimeTopicMaintenance(topicId)
99
+ );
100
+ }
101
+
102
+ type StoredParams = Omit<SubmitRuntimeGatewayTurnParams, "topic" | "text">;
103
+
104
+ /**
105
+ * `hold: true` from a host: while the room works, or while earlier follow-ups
106
+ * wait their turn, the message is held; otherwise it goes out as usual. Sending
107
+ * while the line is held after a stop releases it: this message goes first.
108
+ */
109
+ export function holdOrSubmitRuntimeGatewayTurn(
110
+ params: SubmitRuntimeGatewayTurnParams,
111
+ ): HoldOrSubmitResult {
112
+ const topicId = params.topic.id;
113
+ const requestId = params.requestId ?? params.clientMessageId;
114
+ const replayed = getRuntimeFollowUp(params.clientMessageId);
115
+ if (replayed?.topicId === topicId) return { held: true, followUp: view(replayed) };
116
+ const alreadySent = findRuntimeGatewaySubmission(params.clientMessageId, requestId) !== null;
117
+ const waiting = listRuntimeFollowUps(topicId).length > 0;
118
+ const paused = areRuntimeFollowUpsPaused(topicId);
119
+ const holdable = !alreadySent && params.respond !== false && params.silent !== true;
120
+ if (holdable && (isRoomWorking(topicId) || (waiting && !paused))) {
121
+ const { topic: _topic, text, ...rest } = params;
122
+ // Stamped now: a held message's room assertion ages from when the host
123
+ // made it, not from when the message goes out.
124
+ const stored: StoredParams = {
125
+ ...rest,
126
+ ...(params.actorTopicScope
127
+ ? { actorTopicScope: stampActorTopicScope(params.actorTopicScope) }
128
+ : {}),
129
+ };
130
+ const followUp = holdRuntimeFollowUp({
131
+ followUpId: params.clientMessageId,
132
+ topicId,
133
+ actorUserId: params.actorUserId ?? params.userId,
134
+ text,
135
+ attachments: params.attachments ?? [],
136
+ params: stored as unknown as Record<string, unknown>,
137
+ });
138
+ announce(topicId);
139
+ return { held: true, followUp: view(followUp) };
140
+ }
141
+ const submission = submitRuntimeGatewayTurn(params);
142
+ if (holdable && paused && setRuntimeFollowUpsPaused(topicId, false)) announce(topicId);
143
+ return { held: false, submission };
144
+ }
145
+
146
+ function sendHeld(
147
+ followUp: RuntimeFollowUp,
148
+ how: { inject: boolean },
149
+ ): SubmitRuntimeGatewayTurnResult | null {
150
+ const index = listRuntimeFollowUps(followUp.topicId).findIndex(
151
+ (item) => item.followUpId === followUp.followUpId,
152
+ );
153
+ const taken = takeRuntimeFollowUp(followUp.followUpId);
154
+ if (!taken) return null;
155
+ const topic = getTopic(taken.topicId);
156
+ if (!topic) {
157
+ deleteRuntimeFollowUpsForTopic(taken.topicId);
158
+ return null;
159
+ }
160
+ try {
161
+ const stored = taken.params as unknown as StoredParams;
162
+ return submitRuntimeGatewayTurn({
163
+ ...stored,
164
+ topic,
165
+ text: taken.text,
166
+ steer: false,
167
+ inject: how.inject,
168
+ ownTurn: true,
169
+ });
170
+ } catch (error) {
171
+ // Back where it was, and the line holds so a failing message is not retried forever.
172
+ restoreRuntimeFollowUp(taken, index);
173
+ setRuntimeFollowUpsPaused(taken.topicId, true);
174
+ logger.warn(
175
+ {
176
+ topicId: taken.topicId,
177
+ followUpId: taken.followUpId,
178
+ error: error instanceof Error ? error.message : String(error),
179
+ },
180
+ "follow-up could not go out; the line holds",
181
+ );
182
+ return null;
183
+ } finally {
184
+ announce(taken.topicId);
185
+ }
186
+ }
187
+
188
+ /** Send the oldest follow-up of every idle room that is not held after a stop. */
189
+ export function dispatchReadyFollowUps(): void {
190
+ for (const topicId of runtimeFollowUpTopicsReady()) {
191
+ if (isRoomWorking(topicId)) continue;
192
+ const first = listRuntimeFollowUps(topicId)[0];
193
+ if (first) sendHeld(first, { inject: false });
194
+ }
195
+ }
196
+
197
+ export class FollowUpNotFoundError extends Error {
198
+ constructor() {
199
+ super("follow-up not found");
200
+ this.name = "FollowUpNotFoundError";
201
+ }
202
+ }
203
+
204
+ /** Only the person who sent it may change it; to anyone else it does not exist. */
205
+ function ownFollowUp(topicId: string, followUpId: string, actorUserId: string): RuntimeFollowUp {
206
+ const followUp = getRuntimeFollowUp(followUpId);
207
+ if (!followUp || followUp.topicId !== topicId || followUp.actorUserId !== actorUserId) {
208
+ throw new FollowUpNotFoundError();
209
+ }
210
+ return followUp;
211
+ }
212
+
213
+ export function editFollowUp(
214
+ topicId: string,
215
+ followUpId: string,
216
+ actorUserId: string,
217
+ text: string,
218
+ ): FollowUpLine {
219
+ const followUp = ownFollowUp(topicId, followUpId, actorUserId);
220
+ if (!text.trim() && followUp.attachments.length === 0) {
221
+ takeRuntimeFollowUp(followUpId);
222
+ } else {
223
+ editRuntimeFollowUpText(followUpId, text);
224
+ }
225
+ announce(topicId);
226
+ return followUpLine(topicId);
227
+ }
228
+
229
+ export function deleteFollowUp(
230
+ topicId: string,
231
+ followUpId: string,
232
+ actorUserId: string,
233
+ ): FollowUpLine {
234
+ ownFollowUp(topicId, followUpId, actorUserId);
235
+ takeRuntimeFollowUp(followUpId);
236
+ announce(topicId);
237
+ return followUpLine(topicId);
238
+ }
239
+
240
+ export function moveFollowUp(
241
+ topicId: string,
242
+ followUpId: string,
243
+ actorUserId: string,
244
+ toIndex: number,
245
+ ): FollowUpLine {
246
+ ownFollowUp(topicId, followUpId, actorUserId);
247
+ moveRuntimeFollowUp(followUpId, toIndex);
248
+ announce(topicId);
249
+ return followUpLine(topicId);
250
+ }
251
+
252
+ /**
253
+ * 지금 보내기: the message goes out now. Into the running turn when it is the
254
+ * same person's and can take it (read after the step it is on); otherwise as a
255
+ * turn of its own. Either way nothing stops, and the line is no longer held.
256
+ */
257
+ export function sendFollowUpNow(
258
+ topicId: string,
259
+ followUpId: string,
260
+ actorUserId: string,
261
+ ): { line: FollowUpLine; submission: SubmitRuntimeGatewayTurnResult | null } {
262
+ const followUp = ownFollowUp(topicId, followUpId, actorUserId);
263
+ setRuntimeFollowUpsPaused(topicId, false);
264
+ const submission = sendHeld(followUp, { inject: true });
265
+ return { line: followUpLine(topicId), submission };
266
+ }
267
+
268
+ /**
269
+ * A person stopped the AI: what waits stays until they send again. Called by
270
+ * the host's abort route; a room with nothing held is left as it was.
271
+ */
272
+ export function holdFollowUpsAfterStop(topicId: string): void {
273
+ if (listRuntimeFollowUps(topicId).length === 0) return;
274
+ if (setRuntimeFollowUpsPaused(topicId, true)) announce(topicId);
275
+ }
276
+
277
+ /** Watch for idle rooms with follow-ups waiting. Every node process may run one; taking a follow-up is atomic. */
278
+ export function startFollowUpDispatcher(intervalMs = 250): () => void {
279
+ const timer = setInterval(() => {
280
+ try {
281
+ dispatchReadyFollowUps();
282
+ } catch (error) {
283
+ logger.warn(
284
+ { error: error instanceof Error ? error.message : String(error) },
285
+ "follow-up dispatch failed",
286
+ );
287
+ }
288
+ }, intervalMs);
289
+ timer.unref?.();
290
+ return () => clearInterval(timer);
291
+ }
@@ -96,6 +96,7 @@ export interface RuntimeBus {
96
96
  severity: "info" | "warning" | "error",
97
97
  label: string,
98
98
  ): void;
99
+ broadcastMidTurnRead(topicId: string, queryId: string, messageIds: readonly string[]): void;
99
100
  broadcastAborted(topicId: string, queryId: string, reason?: "superseded" | "stopped"): void;
100
101
  broadcastToolCall(
101
102
  topicId: string,
@@ -278,6 +279,11 @@ export class SqliteRuntimeBus implements RuntimeBus {
278
279
  });
279
280
  }
280
281
 
282
+ /** The running turn read these messages the person sent while it worked. */
283
+ broadcastMidTurnRead(topicId: string, queryId: string, messageIds: readonly string[]): void {
284
+ this.broadcastAiStatus(topicId, { kind: "messages_read", queryId, messageIds });
285
+ }
286
+
281
287
  broadcastAborted(topicId: string, queryId: string, reason?: "superseded" | "stopped"): void {
282
288
  this.broadcastAiStatus(topicId, { kind: "ai_aborted", queryId, reason });
283
289
  }
@@ -20,6 +20,17 @@ export { submitUserMessage } from "#application/submit-user-message";
20
20
  export { switchTopicEffort } from "#application/switch-topic-effort";
21
21
  export { switchTopicModel } from "#application/switch-topic-model";
22
22
  export { TopicServiceError, topicService } from "#application/topic-service";
23
+ export {
24
+ deleteFollowUp,
25
+ editFollowUp,
26
+ FollowUpNotFoundError,
27
+ followUpLine,
28
+ holdFollowUpsAfterStop,
29
+ holdOrSubmitRuntimeGatewayTurn,
30
+ moveFollowUp,
31
+ sendFollowUpNow,
32
+ startFollowUpDispatcher,
33
+ } from "#application/turn-follow-ups";
23
34
  export {
24
35
  deleteVaultEntry,
25
36
  executeVaultCommand,
@@ -0,0 +1,73 @@
1
+ import { execFile } from "node:child_process";
2
+ import { accessSync, constants, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, isAbsolute, join } from "node:path";
5
+ import { promisify } from "node:util";
6
+
7
+ export type BrowserBackend = "chrome" | "egolite";
8
+
9
+ /** Resolve once at node startup; explicit overrides never depend on local discovery. */
10
+ export function resolveBrowserBackend(
11
+ value?: string,
12
+ findEgoBrowser: () => string | undefined = resolveEgoBrowserBin,
13
+ ): BrowserBackend {
14
+ const backend = value?.trim();
15
+ if (!backend) return findEgoBrowser() ? "egolite" : "chrome";
16
+ if (backend === "chrome" || backend === "egolite") return backend;
17
+ throw new Error("NEGOTIUM_BROWSER_BACKEND must be chrome or egolite");
18
+ }
19
+
20
+ /** Search executable locations only; never resolve a tool from the topic's cwd. */
21
+ export function resolveEgoBrowserBin(
22
+ path = process.env.PATH ?? "",
23
+ home = homedir(),
24
+ ): string | undefined {
25
+ const names = process.platform === "win32" ? ["ego-browser.exe"] : ["ego-browser"];
26
+ const directories = [...path.split(delimiter).filter(isAbsolute), join(home, ".local", "bin")];
27
+ for (const directory of directories) {
28
+ for (const name of names) {
29
+ const candidate = join(directory, name);
30
+ try {
31
+ accessSync(candidate, constants.X_OK);
32
+ if (statSync(candidate).isFile()) return candidate;
33
+ } catch {
34
+ // The CLI is optional; continue looking in the documented user install location.
35
+ }
36
+ }
37
+ }
38
+ return undefined;
39
+ }
40
+
41
+ /** Probe the CLI without opening a browser, changing profiles, or importing user data. */
42
+ export async function prepareEgoBrowser(): Promise<string> {
43
+ const command = resolveEgoBrowserBin();
44
+ if (!command) {
45
+ throw new Error("ego-browser is not installed on this Negotium node or is not executable");
46
+ }
47
+ await promisify(execFile)(command, ["--version"], {
48
+ timeout: 5_000,
49
+ maxBuffer: 16_384,
50
+ windowsHide: true,
51
+ });
52
+ return command;
53
+ }
54
+
55
+ export const EGO_BROWSER_INSTRUCTIONS = `## Browser
56
+ This node uses ego lite through the official ego-browser CLI, using its existing logged-in browser.
57
+ The Chrome browser_* MCP tools are not registered. Never start browser-rs, point AB_CHROME at ego lite,
58
+ attach to its debugging port, or create a replacement browser/profile.
59
+ Use browser automation only when this turn's runtime reminder authorizes it. If it is unavailable or
60
+ the topic owner check denies access, do not bypass that decision through a shell or another tool.
61
+ When authorized, use the executable supplied by the runtime through your foreground shell tool.
62
+ Before the first browser action in a session, run that executable with "skill" and read its entire
63
+ installed-version guide. Use its "nodejs" command and documented APIs; do not assume Playwright APIs.
64
+ Create one task space for the user goal and retain its spaceId across commands and follow-up turns.
65
+ Use a unique task name tied to this topic and goal; never claim another topic's or a user's space
66
+ without explicit authorization. Existing login state is shared, not the user's other task spaces.
67
+ Stop when the user takes control. Hand off authentication to the user and resume the same task space
68
+ only after confirmation. On successful completion, call finish({ keep: [] }) unless the user needs
69
+ specific result tabs. On interruption, preserve the space for resumption; never kill the browser or
70
+ delete its profile. Do not close a space just because an AI turn ended.
71
+ Verify each action through the guide's observation APIs. Report CLI/browser errors as errors and do
72
+ not silently switch to Chrome. The CLI probe does not prove the browser is connected or authenticated.
73
+ Vault secret injection through browser-rs is not available here; do not copy secrets into scripts or logs.`;
@@ -13,6 +13,7 @@ import { createRequire } from "node:module";
13
13
  import { homedir } from "node:os";
14
14
  import { dirname, join, resolve } from "node:path";
15
15
  import { fileURLToPath, pathToFileURL } from "node:url";
16
+ import { resolveBrowserBackend } from "#platform/browser-backend";
16
17
  import {
17
18
  parseRuntimePort,
18
19
  readEnvText,
@@ -99,6 +100,7 @@ export const TOPIC_WORKSPACE_DIR = resolve(WORKSPACE_DIR, "topics");
99
100
  export const SHARED_WIKI_DIR = resolve(WORKSPACE_DIR, "wiki");
100
101
  export const CRON_WORKSPACE_DIR = resolve(WORKSPACE_DIR, "cron");
101
102
  export const BROWSER_DIR = resolveLocalStateDir("NEGOTIUM_BROWSER_DIR", "browser");
103
+ export const BROWSER_BACKEND = resolveBrowserBackend(envText("NEGOTIUM_BROWSER_BACKEND"));
102
104
  export const BROWSER_PROFILES_DIR = resolve(BROWSER_DIR, "profiles");
103
105
  export const BINARIES_DIR = resolve(STATE_DIR, "binaries");
104
106
  export const SECRETS_DIR = resolve(STATE_DIR, "secrets");
@@ -530,6 +532,7 @@ export const MODEL_SONNET = "claude-sonnet-5";
530
532
  export const MODEL_OPUS = "claude-opus-5-5";
531
533
  export const MODEL_HAIKU = "claude-haiku-4-5-20251001";
532
534
  export const MODEL_FABLE = "claude-fable-5-1"; // Mythos-class, Fable 5.1 announced 2026-09-01 (was claude-fable-5)
535
+ export const MODEL_FABLE_5_2 = "claude-fable-5-2"; // Fable 5.2 announced 2026-11-09; selectable as `fable-5.2`, `fable` stays on 5.1
533
536
 
534
537
  // DeepSeek V4 (released 2026-04-24). API is OpenAI-compatible at
535
538
  // https://api.deepseek.com/v1/chat/completions; thinking mode is enabled via
@@ -14,6 +14,7 @@ import { peerSessionBridgeIpcEnv } from "#mcp/session-comm/bridge-ipc-config";
14
14
  import { bgBashContextCapability } from "#platform/background-bash/manager";
15
15
  import {
16
16
  AGENT_HEALTH_SERVER,
17
+ BROWSER_BACKEND,
17
18
  CANONICAL_MCP_PROXY_SERVER,
18
19
  DECISION_SERVER,
19
20
  envText,
@@ -365,6 +366,8 @@ const MCP_CATALOG: Record<string, RuntimeMcpCatalogEntry> = {
365
366
  playwright: {
366
367
  ...commonRuntimeMcpPolicy("playwright"),
367
368
  build({ userId, session, topicId, playwrightPort, playwrightCapability, agent }) {
369
+ // ego lite is driven by its native CLI; no Chrome process, MCP, or missing-port alert.
370
+ if (BROWSER_BACKEND === "egolite") return null;
368
371
  // Codex and Maestro use Streamable HTTP while Claude uses SSE. Both
369
372
  // transports terminate at the same long-lived browser/profile server.
370
373
  if (playwrightPort && playwrightCapability) {
@@ -5,8 +5,10 @@ import {
5
5
  MODEL_COST_ROUTING_SUMMARY,
6
6
  SELECTABLE_MODELS,
7
7
  } from "#agents/model-catalog";
8
+ import { EGO_BROWSER_INSTRUCTIONS } from "#platform/browser-backend";
8
9
  import {
9
10
  AGENTS_PROMPTS_DIR,
11
+ BROWSER_BACKEND,
10
12
  PROJECT_ROOT,
11
13
  RESOURCES_DIR,
12
14
  resolveOutputLanguage,
@@ -87,7 +89,14 @@ function loadSessionPrompt(filename: string, fallback: string): string {
87
89
  // `{{KEY}}` placeholders are resolved by the caller's replaceVars pass.
88
90
  function sharedToolsPartial(): string {
89
91
  if (_sharedToolsPartial === null) {
90
- _sharedToolsPartial = loadSessionPrompt("_shared-tools.md", "");
92
+ const shared = loadSessionPrompt("_shared-tools.md", "");
93
+ _sharedToolsPartial = shared.replace(
94
+ /<!-- CHROME_BROWSER_START -->[\s\S]*?<!-- CHROME_BROWSER_END -->/,
95
+ (chrome) =>
96
+ BROWSER_BACKEND === "egolite"
97
+ ? EGO_BROWSER_INSTRUCTIONS
98
+ : chrome.replace(/<!-- CHROME_BROWSER_(?:START|END) -->\n?/g, ""),
99
+ );
91
100
  }
92
101
  return _sharedToolsPartial;
93
102
  }
@@ -453,7 +462,7 @@ function buildRuntimeToolSection(
453
462
  "`set_effort` is available but discouraged; use it only when the user explicitly requests an effort change.",
454
463
  "`set_model` may be called autonomously only when the current model is clearly below the task's required capability, such as complex algorithm design, proof-level math, or broad multi-file refactoring. Choose the best-fit model directly from the same-agent catalog; model selection is not a mandatory one-step ladder. End the turn after changing it. Do not use vague task complexity as a trigger.",
455
464
  "`set_agent` autonomous calls are forbidden. Only switch agent when the user explicitly asks to switch runtime, e.g. “switch to codex”, “use claude”.",
456
- "Never use `fable` unless the user explicitly requests it; it is expensive.",
465
+ "Never use `fable` or `fable-5.2` unless the user explicitly requests it; they are expensive.",
457
466
  "",
458
467
  "Model catalog (capability/cost routing guidance):",
459
468
  MODEL_COST_ROUTING_SUMMARY,