maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907

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 (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. package/package.json +1 -1
@@ -71,6 +71,7 @@ export class HostScheduledTaskCoordinator {
71
71
  #prepared = false;
72
72
  #started = false;
73
73
  #draining = false;
74
+ #handoffHeld = false;
74
75
  #closed = false;
75
76
  #retiringSessions = new Set();
76
77
  constructor(input) {
@@ -156,6 +157,34 @@ export class HostScheduledTaskCoordinator {
156
157
  this.#started = true;
157
158
  void this.#refresh().catch((error) => this.#fatal(error));
158
159
  }
160
+ holdForHandoff() {
161
+ if (this.#draining || this.#handoffHeld)
162
+ return undefined;
163
+ this.#handoffHeld = true;
164
+ this.#stopTimer();
165
+ let released = false;
166
+ return {
167
+ settled: async () => {
168
+ // An admitted native effect or Agent fire finishes normally. No new
169
+ // fire may start while the handoff waits for this lane.
170
+ for (;;) {
171
+ const lane = this.#lane;
172
+ await lane;
173
+ if (lane === this.#lane)
174
+ return;
175
+ }
176
+ },
177
+ residencies: () => (this.#residency ? [this.#residency] : []),
178
+ release: () => {
179
+ if (released)
180
+ return;
181
+ released = true;
182
+ this.#handoffHeld = false;
183
+ if (!this.#draining)
184
+ void this.#refresh().catch((error) => this.#fatal(error));
185
+ },
186
+ };
187
+ }
159
188
  beginDrain() {
160
189
  if (this.#draining)
161
190
  return;
@@ -390,12 +419,16 @@ export class HostScheduledTaskCoordinator {
390
419
  }
391
420
  async #refresh() {
392
421
  await this.#exclusive(async () => {
422
+ if (this.#handoffHeld || this.#draining)
423
+ return;
393
424
  for (const claim of await this.#store.listPendingFires()) {
425
+ if (this.#handoffHeld || this.#draining)
426
+ break;
394
427
  if (claim.nativeState === 'waiting_for_provider') {
395
428
  await this.#fulfill(claim, true);
396
429
  }
397
430
  }
398
- while (!this.#draining) {
431
+ while (!this.#draining && !this.#handoffHeld) {
399
432
  const scan = await this.#store.claimNextDue(this.#now());
400
433
  for (const expired of scan.expired)
401
434
  this.#publish('updated', expired.id);
@@ -616,7 +649,7 @@ export class HostScheduledTaskCoordinator {
616
649
  async #refreshSchedule() {
617
650
  this.#stopTimer();
618
651
  await this.#refreshResidency();
619
- if (!this.#started || this.#draining)
652
+ if (!this.#started || this.#draining || this.#handoffHeld)
620
653
  return;
621
654
  const [tasks, claims] = await Promise.all([this.#store.list(), this.#store.listPendingFires()]);
622
655
  const next = tasks
@@ -626,6 +659,8 @@ export class HostScheduledTaskCoordinator {
626
659
  return earliest === null || deadline < earliest ? deadline : earliest;
627
660
  }, null);
628
661
  const waitingForProvider = claims.some((claim) => claim.nativeState === 'waiting_for_provider');
662
+ if (this.#draining || this.#handoffHeld)
663
+ return;
629
664
  if (next === null && !waitingForProvider)
630
665
  return;
631
666
  const nextTaskDelay = next === null
@@ -19,6 +19,22 @@
19
19
  import { encodeProtocolMessage, } from '../protocol/index.js';
20
20
  const MAX_QUEUED_FRAMES = 64;
21
21
  const MAX_QUEUED_BYTES = 2 * 1024 * 1024;
22
+ function frameLane(frame) {
23
+ if ('operation' in frame) {
24
+ if (frame.operation === 'subscription.close')
25
+ return 'barrier';
26
+ if (frame.operation === 'session.transcript.page' ||
27
+ frame.operation === 'artifact.query' ||
28
+ frame.operation === 'runtime.resource.query')
29
+ return 'bulk';
30
+ return 'control';
31
+ }
32
+ if (frame.kind === 'subscription.closed')
33
+ return 'barrier';
34
+ if (frame.kind === 'subscription.runtime_resource_pty_data')
35
+ return 'pty';
36
+ return frame.kind.startsWith('subscription.') ? 'state' : 'control';
37
+ }
22
38
  export class RuntimeHostOutboundQueueError extends Error {
23
39
  code;
24
40
  constructor(code) {
@@ -37,6 +53,8 @@ export class BoundedSerialOutboundWriter {
37
53
  #writing = false;
38
54
  #drainTask;
39
55
  #closed = false;
56
+ #controlBurst = 0;
57
+ #dataLane = 0;
40
58
  constructor(transport, onFailure) {
41
59
  this.#transport = transport;
42
60
  this.#onFailure = onFailure;
@@ -65,7 +83,7 @@ export class BoundedSerialOutboundWriter {
65
83
  throw failure;
66
84
  }
67
85
  const flushed = new Promise((resolve, reject) => {
68
- this.#queue.push({ message, resolve, reject });
86
+ this.#queue.push({ message, lane: frameLane(frame), resolve, reject });
69
87
  this.#queuedBytes += message.byteLength;
70
88
  if (!this.#writing) {
71
89
  this.#writing = true;
@@ -88,7 +106,7 @@ export class BoundedSerialOutboundWriter {
88
106
  async #drain() {
89
107
  try {
90
108
  while (!this.#closed) {
91
- const queued = this.#queue[0];
109
+ const queued = this.#nextFrame();
92
110
  if (!queued)
93
111
  return;
94
112
  try {
@@ -100,7 +118,7 @@ export class BoundedSerialOutboundWriter {
100
118
  }
101
119
  if (this.#closed)
102
120
  return;
103
- this.#queue.shift();
121
+ this.#queue.splice(this.#queue.indexOf(queued), 1);
104
122
  this.#queuedBytes -= queued.message.byteLength;
105
123
  queued.resolve();
106
124
  }
@@ -118,6 +136,30 @@ export class BoundedSerialOutboundWriter {
118
136
  this.close(error);
119
137
  this.#onFailure();
120
138
  }
139
+ #nextFrame() {
140
+ // Close acknowledgements are fences: no lower-priority subscription
141
+ // frames may arrive after a Client has retired their correlation ID.
142
+ const barrier = this.#queue.findIndex((frame) => frame.lane === 'barrier');
143
+ if (barrier === 0)
144
+ return this.#queue[0];
145
+ const eligible = barrier < 0 ? this.#queue : this.#queue.slice(0, barrier);
146
+ const control = eligible.find((frame) => frame.lane === 'control');
147
+ if (control && this.#controlBurst < 8) {
148
+ this.#controlBurst += 1;
149
+ return control;
150
+ }
151
+ const lanes = ['state', 'bulk', 'pty'];
152
+ for (let offset = 0; offset < lanes.length; offset += 1) {
153
+ const lane = (this.#dataLane + offset) % lanes.length;
154
+ const frame = eligible.find((candidate) => candidate.lane === lanes[lane]);
155
+ if (!frame)
156
+ continue;
157
+ this.#dataLane = (lane + 1) % lanes.length;
158
+ this.#controlBurst = 0;
159
+ return frame;
160
+ }
161
+ return control;
162
+ }
121
163
  }
122
164
  function asError(error) {
123
165
  return error instanceof Error ? error : new Error(String(error));
@@ -18,17 +18,21 @@
18
18
  */
19
19
  import { RuntimeHostProtocolError } from '../protocol/errors.js';
20
20
  import { createHash } from 'node:crypto';
21
- import { authorizeConnectionModel } from '@maka/core/llm-connections';
21
+ import { authorizeConnectionModel, connectionEnabledModelIds } from '@maka/core/llm-connections';
22
22
  import { isModelExplicitlyUnsupportedForChat } from '@maka/core/model-catalog';
23
23
  import { thinkingVariantsForConnection } from '@maka/core/model-thinking';
24
24
  import { executionBoundaryDisplayMode, } from '@maka/core/sandbox-boundary';
25
25
  import { DEFAULT_SESSION_NAME, normalizeUserSessionName } from '@maka/core/session-name';
26
26
  import { isSessionStartModeLabel as isExecutionSemanticLabel, sessionStartModeSpec, } from '@maka/core/session-start-mode';
27
27
  import { isWorkHubCoordinationSessionId, isWorkHubCoordinationSessionTarget, } from '@maka/core/session';
28
- import { isSessionNotFoundError, SessionMetadataConflictError, SessionMetadataVersionConflictError, SessionReadMarkerMessageNotFoundError, } from '@maka/storage/execution-stores';
28
+ import { isSessionNotFoundError, SessionMetadataConflictError, SessionMetadataVersionConflictError, } from '@maka/storage/execution-stores';
29
+ import { isVisibleSessionMessage } from '@maka/storage/session-message-projection';
29
30
  import { SessionConfigurationRevisionConflictError, SessionConfigurationTransitionError, } from '@maka/runtime/session-manager';
30
31
  import { decodeSessionCatalogProjection, decodeSharedSessionCatalogProjection, SESSION_CATALOG_LIVE_RUN_STATE_SCHEMA_VERSION, SESSION_CATALOG_LABEL_MAX_BYTES, SESSION_CATALOG_LABEL_MAX_ITEMS, SESSION_CATALOG_MODEL_MAX_BYTES, SESSION_CATALOG_PAGE_MAX_ITEMS, SESSION_CATALOG_RESULT_MAX_BYTES, SESSION_CATALOG_RUNNING_TURN_MAX_ITEMS, projectSessionTurnLandmarkForWire, SESSION_TURN_QUERY_RESULT_MAX_BYTES, projectSessionTurnContributionForWire, } from '../protocol/index.js';
31
32
  import { WorkspaceResolutionError } from './workspace-resolver.js';
33
+ /** One page of the backwards scan a read marker walks to find the newest visible message. */
34
+ const SESSION_READ_MARKER_TAIL_MAX_MESSAGES = 64;
35
+ const SESSION_READ_MARKER_TAIL_MAX_BYTES = 256 * 1024;
32
36
  export class SessionOperationFailure extends Error {
33
37
  code;
34
38
  constructor(code, message) {
@@ -37,6 +41,84 @@ export class SessionOperationFailure extends Error {
37
41
  this.name = 'SessionOperationFailure';
38
42
  }
39
43
  }
44
+ /**
45
+ * The import path found no ready connection+model to attach the task to. A
46
+ * distinct type (not just a message) so `#importSession` can map it to the
47
+ * stable `model_unavailable` wire code without inspecting the message — the
48
+ * generic `operation_unavailable` code it carries is also used for an
49
+ * unavailable source, which is a different failure.
50
+ */
51
+ export class NoUsableImportModelError extends SessionOperationFailure {
52
+ constructor(message) {
53
+ super('operation_unavailable', message);
54
+ this.name = 'NoUsableImportModelError';
55
+ }
56
+ }
57
+ /**
58
+ * Connection+model candidates for an imported task, most-preferred first: the
59
+ * configured default (kept at its exact precedence), then one ready model per
60
+ * enabled connection in catalog order. Model-level readiness that is a pure
61
+ * catalog fact — enabled, not quarantined, chat-capable — is applied here so an
62
+ * unusable connection costs one `#resolveModel` attempt, not one per enabled
63
+ * model (a connection may enable hundreds). Connection-level readiness
64
+ * (credential, retired provider, identity) stays in `#resolveModel`, which
65
+ * remains the sole arbiter of those.
66
+ */
67
+ function importModelCandidates(snapshot) {
68
+ const byId = new Map(snapshot.connections.map((connection) => [connection.connectionId, connection]));
69
+ const candidates = [];
70
+ const seen = new Set();
71
+ const push = (connection, modelId, isDefault) => {
72
+ const key = `${connection.connectionId} ${modelId}`;
73
+ if (seen.has(key))
74
+ return;
75
+ seen.add(key);
76
+ candidates.push({
77
+ connectionId: connection.connectionId,
78
+ connectionSlug: connection.slug,
79
+ modelId,
80
+ isDefault,
81
+ });
82
+ };
83
+ // The connection's first enabled model that is a valid chat target, by pure
84
+ // catalog facts alone (no credential or provider-liveness read). Emitting only
85
+ // this one — rather than every enabled model — bounds the enumeration to one
86
+ // candidate per connection, so a connection-level failure (missing credential,
87
+ // retired provider) costs a single `#resolveModel` round trip.
88
+ const firstReadyModel = (connection) => {
89
+ for (const modelId of connectionEnabledModelIds(connection)) {
90
+ // Mirror `#resolveModel`'s pure-catalog gates, the wire byte cap included:
91
+ // a model id can be within the catalog's code-unit limit yet exceed the
92
+ // byte cap (e.g. emoji), and taking it as the connection's sole candidate
93
+ // would let `#resolveModel` reject it and mask the connection's shorter,
94
+ // usable models. Skip it here so the next enabled model is considered.
95
+ if (Buffer.byteLength(modelId, 'utf8') > SESSION_CATALOG_MODEL_MAX_BYTES)
96
+ continue;
97
+ const model = authorizeConnectionModel(connection, modelId);
98
+ if (model && !isModelExplicitlyUnsupportedForChat(model))
99
+ return modelId;
100
+ }
101
+ return undefined;
102
+ };
103
+ // Default first, so a configured-and-ready default keeps today's behavior.
104
+ // `retainedDefaultTarget` + `isValidTarget` guarantee a persisted default is
105
+ // enabled and present in `enabledModelIds`, so its exact model is taken at its
106
+ // precedence rather than re-picked from the connection.
107
+ const preferred = snapshot.defaultTarget;
108
+ if (preferred) {
109
+ const connection = byId.get(preferred.connectionId);
110
+ if (connection?.enabled)
111
+ push(connection, preferred.modelId, true);
112
+ }
113
+ for (const connection of snapshot.connections) {
114
+ if (!connection.enabled)
115
+ continue;
116
+ const modelId = firstReadyModel(connection);
117
+ if (modelId !== undefined)
118
+ push(connection, modelId, false);
119
+ }
120
+ return candidates;
121
+ }
40
122
  /** Host-owned Session catalog, creation, and configuration authority. */
41
123
  export class HostSessionCatalogCoordinator {
42
124
  handlers = {
@@ -52,6 +134,7 @@ export class HostSessionCatalogCoordinator {
52
134
  'session.turns.query': (input) => this.#queryTurns(input),
53
135
  };
54
136
  #stores;
137
+ #turnIndex;
55
138
  #runtimePolicy;
56
139
  #manager;
57
140
  #admission;
@@ -61,6 +144,7 @@ export class HostSessionCatalogCoordinator {
61
144
  #sessionAccessAuthority;
62
145
  constructor(options) {
63
146
  this.#stores = options.stores;
147
+ this.#turnIndex = options.turnIndex;
64
148
  this.#runtimePolicy = options.runtimePolicy;
65
149
  this.#manager = options.manager;
66
150
  this.#admission = options.admission;
@@ -69,11 +153,29 @@ export class HostSessionCatalogCoordinator {
69
153
  this.#requestDrain = options.requestDrain;
70
154
  this.#sessionAccessAuthority = options.sessionAccessAuthority;
71
155
  }
156
+ /**
157
+ * Target for a task imported from another agent's conversation. Import is an
158
+ * explicit, one-off user action on a specific conversation, so it prefers the
159
+ * configured default but falls back to any ready connection+model — see
160
+ * `#resolveImportModel`.
161
+ */
72
162
  async resolveExternalSessionImportTarget() {
73
- const [model, policy] = await Promise.all([
74
- this.#resolveModel({ kind: 'default' }, undefined),
75
- this.#readRuntimePolicy(),
76
- ]);
163
+ return this.#composeCreateTarget(this.#resolveImportModel());
164
+ }
165
+ /**
166
+ * Target for the autonomous WorkHub coordination create path (its
167
+ * `resolveCreateTarget`). Unlike import there is no user in the loop to pick a
168
+ * model, so this fails closed when no default is configured rather than binding
169
+ * a connection the user never chose. Import's fallback deliberately does not
170
+ * reach here; keeping the two resolvers apart is what confines the guess to an
171
+ * explicit user
172
+ * action.
173
+ */
174
+ async resolveDefaultCreateTarget() {
175
+ return this.#composeCreateTarget(this.#resolveModel({ kind: 'default' }, undefined));
176
+ }
177
+ async #composeCreateTarget(modelResolution) {
178
+ const [model, policy] = await Promise.all([modelResolution, this.#readRuntimePolicy()]);
77
179
  return {
78
180
  llmConnectionId: model.connectionId,
79
181
  llmConnectionSlug: model.connectionSlug,
@@ -201,7 +303,7 @@ export class HostSessionCatalogCoordinator {
201
303
  let maxContributions = input.maxContributions;
202
304
  let throughSequence = input.throughSequence;
203
305
  while (true) {
204
- const page = await this.#stores.readTurnContributionsSnapshot(input.sessionId, throughSequence, input.position, maxContributions);
306
+ const page = await this.#turnIndex.readDurableTurnContributions(input.sessionId, throughSequence, input.position, maxContributions);
205
307
  throughSequence = page.throughSequence;
206
308
  const result = {
207
309
  sessionId: input.sessionId,
@@ -227,7 +329,7 @@ export class HostSessionCatalogCoordinator {
227
329
  }
228
330
  async #queryTurnLandmarks(input) {
229
331
  try {
230
- const snapshot = await this.#stores.readTurnLandmarksSnapshot(input.sessionId, input.maxLandmarks);
332
+ const snapshot = await this.#turnIndex.readDurableTurnLandmarks(input.sessionId, input.maxLandmarks);
231
333
  return {
232
334
  ok: true,
233
335
  result: {
@@ -437,7 +539,7 @@ export class HostSessionCatalogCoordinator {
437
539
  if (isWorkHubCoordinationSessionTarget(current.header)) {
438
540
  return readMarkerFailure('operation_conflict', 'WorkHub Coordination Session read state requires WorkHub authority');
439
541
  }
440
- await this.#stores.markSessionReadThroughMessage(input.sessionId, input.readThroughMessageId);
542
+ await this.#clearUnreadAtTranscriptTail(current, input.readThroughMessageId);
441
543
  await this.#continuity.refreshCanonical(input.sessionId, lease);
442
544
  return {
443
545
  ok: true,
@@ -447,9 +549,6 @@ export class HostSessionCatalogCoordinator {
447
549
  catch (error) {
448
550
  if (isNotFound(error))
449
551
  return readMarkerFailure('not_found', 'Session does not exist');
450
- if (error instanceof SessionReadMarkerMessageNotFoundError) {
451
- return readMarkerFailure('invalid_request', error.message);
452
- }
453
552
  if (error instanceof SessionMetadataVersionConflictError) {
454
553
  return readMarkerFailure('operation_conflict', 'Session changed while advancing the read marker');
455
554
  }
@@ -458,6 +557,46 @@ export class HostSessionCatalogCoordinator {
458
557
  }
459
558
  });
460
559
  }
560
+ /**
561
+ * A Session is read once the client has caught up with the ledger's newest
562
+ * visible message. `hasUnread` is the only thing the marker decides and every
563
+ * Turn raises it again, so a client still behind the tail changes nothing.
564
+ */
565
+ async #clearUnreadAtTranscriptTail(record, readThroughMessageId) {
566
+ const latest = await this.#newestVisibleMessage(record.header.id);
567
+ if (latest?.id !== readThroughMessageId)
568
+ return;
569
+ if (record.header.lastReadMessageId === readThroughMessageId && !record.header.hasUnread) {
570
+ return;
571
+ }
572
+ await this.#stores.updateHeaderVersioned(record.header.id, { lastReadMessageId: readThroughMessageId, hasUnread: false }, record.revision);
573
+ }
574
+ /**
575
+ * The ledger's newest message a client can actually see. A Turn that ends on
576
+ * tool traffic can put more hidden records at the tail than one page holds,
577
+ * so the scan pages past them instead of reading the Session as never caught
578
+ * up and leaving it unread for good.
579
+ */
580
+ async #newestVisibleMessage(sessionId) {
581
+ let throughSequence;
582
+ let position;
583
+ while (true) {
584
+ const page = await this.#turnIndex.readDurableRecords(sessionId, {
585
+ direction: 'older',
586
+ maxMessages: SESSION_READ_MARKER_TAIL_MAX_MESSAGES,
587
+ maxStoredBytes: SESSION_READ_MARKER_TAIL_MAX_BYTES,
588
+ ...(throughSequence === undefined ? {} : { throughSequence }),
589
+ ...(position === undefined ? {} : { position }),
590
+ });
591
+ const visible = page.records.find(({ message }) => isVisibleSessionMessage(message));
592
+ if (visible)
593
+ return visible.message;
594
+ if (page.nextPosition === null)
595
+ return undefined;
596
+ throughSequence = page.throughSequence;
597
+ position = page.nextPosition;
598
+ }
599
+ }
461
600
  async #committedUpdate(sessionId, lease) {
462
601
  await this.#continuity.refreshCanonical(sessionId, lease);
463
602
  return {
@@ -511,6 +650,56 @@ export class HostSessionCatalogCoordinator {
511
650
  throw error;
512
651
  }
513
652
  }
653
+ /**
654
+ * Model for an imported task. Prefers the configured default but falls back to
655
+ * any ready connection+model, because a default is only auto-set during
656
+ * onboarding bootstrap (`setDefaultIfMissing`) and a self-configured profile
657
+ * legitimately has `defaultTarget: null` while holding perfectly usable
658
+ * connections. Without the fallback, every import fails before the source is
659
+ * even read. Unlike interactive session creation, import has no model picker,
660
+ * so this is the only place that can choose one.
661
+ */
662
+ async #resolveImportModel() {
663
+ let snapshot;
664
+ try {
665
+ snapshot = await this.#runtimePolicy.connectionCatalog.getSnapshot();
666
+ }
667
+ catch {
668
+ throw new SessionOperationFailure('persistence_failed', 'Connection catalog is unavailable');
669
+ }
670
+ for (const candidate of importModelCandidates(snapshot)) {
671
+ try {
672
+ return await this.#resolveModel({
673
+ kind: 'explicit',
674
+ connectionId: candidate.connectionId,
675
+ connectionSlug: candidate.connectionSlug,
676
+ model: candidate.modelId,
677
+ }, undefined);
678
+ }
679
+ catch (error) {
680
+ if (!(error instanceof SessionOperationFailure))
681
+ throw error;
682
+ // The configured default is never substituted away from: if it is set
683
+ // but unusable (e.g. its credential was revoked), surface its failure
684
+ // exactly as an explicit default target does today, rather than silently
685
+ // attaching the task to a connection the user did not choose. The
686
+ // fallback below runs only when no default is set — the null-default
687
+ // state this fix is for, where there is nothing to substitute for.
688
+ if (candidate.isDefault)
689
+ throw error;
690
+ // Otherwise, only a genuinely unusable candidate is skippable:
691
+ // `invalid_request` (disabled / retired / not-enabled / non-chat) and
692
+ // `operation_unavailable` (no credential). Any other code — notably
693
+ // `operation_conflict`, thrown when the connection was deleted or
694
+ // renamed after the snapshot — is a real fault the caller must see, not
695
+ // a reason to silently fall through to a lower-priority connection.
696
+ if (error.code !== 'invalid_request' && error.code !== 'operation_unavailable') {
697
+ throw error;
698
+ }
699
+ }
700
+ }
701
+ throw new NoUsableImportModelError('No usable Session model connection is available for import');
702
+ }
514
703
  async #resolveModel(target, thinkingLevel) {
515
704
  const selected = await this.#selectModelTarget(target);
516
705
  const readiness = await this.#runtimePolicy.operations.resolveExecutionConnection({
@@ -43,6 +43,21 @@ export class SessionContinuityCoordinator {
43
43
  onPublicationFailure;
44
44
  onCatalogChanged;
45
45
  handlers = {
46
+ 'subscription.pty_interest.set': async (input, context) => {
47
+ const subscriber = this.#ownedSubscriber(context.connectionId, input.subscriptionId);
48
+ if (!subscriber || !this.#canObserve(subscriber, subscriber.sessionId)) {
49
+ return {
50
+ ok: false,
51
+ error: { code: 'not_found', message: 'Session subscription was not found' },
52
+ };
53
+ }
54
+ subscriber.ptyInterests = new Set(input.refs);
55
+ // An already writing frame may finish. Everything else belongs to the
56
+ // current visible set; reacquiring uses a fresh terminal snapshot.
57
+ subscriber.ptyQueue = subscriber.ptyQueue.filter((entry, index) => (index === 0 && subscriber.ptyPumping) || subscriber.ptyInterests.has(entry.frame.ref));
58
+ subscriber.ptyQueuedBytes = subscriber.ptyQueue.reduce((bytes, entry) => bytes + entry.encodedBytes, 0);
59
+ return { ok: true, result: { subscriptionId: input.subscriptionId } };
60
+ },
46
61
  'subscription.open': async (input, context) => {
47
62
  const result = await this.#open(context, input);
48
63
  return result.ok
@@ -267,35 +282,36 @@ export class SessionContinuityCoordinator {
267
282
  this.#scheduleSessionDomainChanges(sessionId, changes);
268
283
  }
269
284
  }
270
- /** Publish live PTY bytes on the same ordered Session subscription as its durable projection. */
285
+ /** PTY congestion never consumes Session sequence numbers or its queue budget. */
271
286
  async enqueueRuntimeResourcePtyData(event) {
272
- if (this.#closed ||
273
- Buffer.byteLength(event.data, 'utf8') > SESSION_RUNTIME_RESOURCE_PTY_DATA_MAX_BYTES) {
287
+ if (this.#closed)
274
288
  return;
275
- }
276
289
  try {
277
- await this.sessionAdmission.enqueueDetached(event.sessionId, () => {
278
- if (this.#closed)
279
- return;
280
- const state = this.#sessions.get(event.sessionId);
281
- if (!state)
282
- return;
283
- for (const subscriber of state.subscribers.values()) {
284
- const frame = {
285
- kind: 'subscription.runtime_resource_pty_data',
286
- hostEpoch: this.#hostEpoch,
287
- subscriptionId: subscriber.subscriptionId,
288
- sequence: subscriber.nextSequence,
289
- sessionId: event.sessionId,
290
- ref: event.ref,
291
- ptySequence: event.sequence,
292
- data: event.data,
293
- };
294
- if (Buffer.byteLength(JSON.stringify(frame), 'utf8') <= SESSION_SUBSCRIPTION_FRAME_MAX_BYTES) {
295
- this.#enqueue(subscriber, frame);
296
- }
290
+ const state = this.#sessions.get(event.sessionId);
291
+ if (!state)
292
+ return;
293
+ for (const subscriber of state.subscribers.values()) {
294
+ if (!this.#canObserve(subscriber, event.sessionId)) {
295
+ this.#closeSubscriber(subscriber, 'access_revoked');
296
+ continue;
297
297
  }
298
- });
298
+ if (!subscriber.ptyInterests.has(event.ref))
299
+ continue;
300
+ const frame = {
301
+ kind: 'subscription.runtime_resource_pty_data',
302
+ hostEpoch: this.#hostEpoch,
303
+ subscriptionId: subscriber.subscriptionId,
304
+ sessionId: event.sessionId,
305
+ ref: event.ref,
306
+ ptySequence: event.sequence,
307
+ ...(Buffer.byteLength(event.data, 'utf8') > SESSION_RUNTIME_RESOURCE_PTY_DATA_MAX_BYTES
308
+ ? { data: '', reset: true }
309
+ : { data: event.data }),
310
+ };
311
+ if (Buffer.byteLength(JSON.stringify(frame), 'utf8') <= SESSION_SUBSCRIPTION_FRAME_MAX_BYTES) {
312
+ this.#enqueuePty(subscriber, frame);
313
+ }
314
+ }
299
315
  }
300
316
  catch (error) {
301
317
  this.onPublicationFailure(error);
@@ -705,6 +721,10 @@ export class SessionContinuityCoordinator {
705
721
  nextSequence: 1,
706
722
  lastFlushedSequence: 0,
707
723
  queue: [],
724
+ ptyQueue: [],
725
+ ptyInterests: new Set(),
726
+ ptyQueuedBytes: 0,
727
+ ptyPumping: false,
708
728
  queuedBytes: 0,
709
729
  pumping: false,
710
730
  terminalQueued: false,
@@ -1073,6 +1093,7 @@ export class SessionContinuityCoordinator {
1073
1093
  return;
1074
1094
  subscriber.activated = true;
1075
1095
  this.#pump(subscriber);
1096
+ this.#pumpPty(subscriber);
1076
1097
  }
1077
1098
  #abortSubscription(connectionId, subscriptionId) {
1078
1099
  const subscriber = this.#ownedSubscriber(connectionId, subscriptionId);
@@ -1164,6 +1185,45 @@ export class SessionContinuityCoordinator {
1164
1185
  #evictSlowSubscriber(subscriber) {
1165
1186
  this.#closeSubscriber(subscriber, 'slow_consumer');
1166
1187
  }
1188
+ #enqueuePty(subscriber, frame) {
1189
+ if (subscriber.phase !== 'open' || subscriber.terminalQueued)
1190
+ return;
1191
+ let encodedBytes = encodeProtocolMessage(frame).byteLength;
1192
+ if (subscriber.ptyQueue.length >= 8 || subscriber.ptyQueuedBytes + encodedBytes > 128 * 1024) {
1193
+ // Reset is session-wide for terminal consumers, so one marker covers
1194
+ // every omitted resource without an unbounded per-resource dirty set.
1195
+ const inFlight = subscriber.ptyPumping ? subscriber.ptyQueue[0] : undefined;
1196
+ subscriber.ptyQueue = inFlight ? [inFlight] : [];
1197
+ subscriber.ptyQueuedBytes = inFlight?.encodedBytes ?? 0;
1198
+ frame = { ...frame, data: '', reset: true };
1199
+ encodedBytes = encodeProtocolMessage(frame).byteLength;
1200
+ }
1201
+ subscriber.ptyQueue.push({ frame, encodedBytes });
1202
+ subscriber.ptyQueuedBytes += encodedBytes;
1203
+ this.#pumpPty(subscriber);
1204
+ }
1205
+ #pumpPty(subscriber) {
1206
+ if (subscriber.ptyPumping || !subscriber.activated || subscriber.phase !== 'open')
1207
+ return;
1208
+ const queued = subscriber.ptyQueue[0];
1209
+ if (!queued)
1210
+ return;
1211
+ subscriber.ptyPumping = true;
1212
+ void Promise.resolve()
1213
+ .then(() => {
1214
+ if (subscriber.phase !== 'open')
1215
+ return;
1216
+ return subscriber.sink.send(queued.frame);
1217
+ })
1218
+ .then(() => {
1219
+ subscriber.ptyPumping = false;
1220
+ if (subscriber.ptyQueue[0] === queued) {
1221
+ subscriber.ptyQueue.shift();
1222
+ subscriber.ptyQueuedBytes -= queued.encodedBytes;
1223
+ }
1224
+ this.#pumpPty(subscriber);
1225
+ }, () => this.#removeSubscriber(subscriber));
1226
+ }
1167
1227
  #closeSubscriber(subscriber, reason) {
1168
1228
  if (subscriber.phase !== 'open')
1169
1229
  return;
@@ -1330,6 +1390,8 @@ export class SessionContinuityCoordinator {
1330
1390
  subscriber.phase = 'closed';
1331
1391
  subscriber.queue = [];
1332
1392
  subscriber.queuedBytes = 0;
1393
+ subscriber.ptyQueue = [];
1394
+ subscriber.ptyQueuedBytes = 0;
1333
1395
  const state = this.#sessions.get(subscriber.sessionId);
1334
1396
  const removed = state?.subscribers.delete(subscriber.subscriptionId);
1335
1397
  this.#subscriptions.delete(subscriber.subscriptionId);