maka-agent 0.2.0-dev.47.20260922 → 0.2.0-dev.49.20260924

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 (155) hide show
  1. package/dist/acp/session-event-mapper.js +1 -4
  2. package/dist/onboarding-catalog.js +20 -4
  3. package/dist/pi-transcript.js +0 -8
  4. package/dist/pi-tui-pickers.js +1 -1
  5. package/dist/pi-tui-runner.js +6 -4
  6. package/dist/runtime-host-capability-provider-command.js +25 -6
  7. package/dist/runtime-host-onboarding.js +5 -3
  8. package/dist/runtime-host-session-channel.js +9 -3
  9. package/dist/tui-mcp-control.js +37 -24
  10. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  11. package/node_modules/@maka/acp-executor-plugin/dist/acp-errors.js +26 -0
  12. package/node_modules/@maka/acp-executor-plugin/dist/acp-filesystem.js +103 -0
  13. package/node_modules/@maka/acp-executor-plugin/dist/acp-process.js +119 -0
  14. package/node_modules/@maka/acp-executor-plugin/dist/acp-projection.js +146 -0
  15. package/node_modules/@maka/acp-executor-plugin/dist/index.js +653 -0
  16. package/node_modules/@maka/acp-executor-plugin/dist/plugin.mjs +24446 -0
  17. package/node_modules/@maka/acp-executor-plugin/package.json +15 -0
  18. package/node_modules/@maka/antigravity-acp-plugin/dist/index.js +88 -0
  19. package/node_modules/@maka/antigravity-acp-plugin/dist/model-presentation.js +53 -0
  20. package/node_modules/@maka/antigravity-acp-plugin/dist/plugin.mjs +115 -0
  21. package/node_modules/@maka/antigravity-acp-plugin/package.json +15 -0
  22. package/node_modules/@maka/core/dist/events.js +13 -0
  23. package/node_modules/@maka/core/dist/executor-catalog.js +106 -0
  24. package/node_modules/@maka/core/dist/llm-connections.js +2 -5
  25. package/node_modules/@maka/core/dist/mcp.js +4 -1
  26. package/node_modules/@maka/core/dist/model-facts.js +2 -4
  27. package/node_modules/@maka/core/dist/model-metadata.generated.js +345 -248
  28. package/node_modules/@maka/core/dist/model-metadata.js +28 -1
  29. package/node_modules/@maka/core/dist/model-thinking.js +17 -17
  30. package/node_modules/@maka/core/dist/model-web-search.js +7 -9
  31. package/node_modules/@maka/core/dist/models-dev-projection.js +1 -1
  32. package/node_modules/@maka/core/dist/onboarding.js +1 -4
  33. package/node_modules/@maka/core/dist/provider-registry.js +60 -86
  34. package/node_modules/@maka/core/dist/runtime-event-store.js +25 -0
  35. package/node_modules/@maka/core/dist/runtime-event.js +2 -2
  36. package/node_modules/@maka/core/dist/runtime-invocation.js +5 -0
  37. package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +28 -16
  38. package/node_modules/@maka/core/dist/runtime-policy/credential-vault-codec.js +6 -0
  39. package/node_modules/@maka/core/dist/runtime-policy/policy-codec.js +21 -0
  40. package/node_modules/@maka/core/dist/runtime-policy.js +1 -1
  41. package/node_modules/@maka/core/dist/session.js +25 -9
  42. package/node_modules/@maka/core/dist/settings.js +1 -0
  43. package/node_modules/@maka/core/dist/tool-ledger-scanner.js +365 -104
  44. package/node_modules/@maka/core/dist/transcript-search.js +1 -0
  45. package/node_modules/@maka/core/dist/turn-origin.js +14 -0
  46. package/node_modules/@maka/core/dist/usage-stats/types.js +1 -0
  47. package/node_modules/@maka/core/package.json +2 -0
  48. package/node_modules/@maka/eval/dist/harbor-maka-subject.js +3 -0
  49. package/node_modules/@maka/eval/dist/maka-subject.js +8 -1
  50. package/node_modules/@maka/mcp/dist/credential-coordinator.js +6 -1
  51. package/node_modules/@maka/mcp/dist/index.js +31 -5
  52. package/node_modules/@maka/mcp/dist/oauth.js +54 -6
  53. package/node_modules/@maka/runtime/dist/agent-run-inspect.js +1 -1
  54. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +1 -11
  55. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +2 -12
  56. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +3 -71
  57. package/node_modules/@maka/runtime/dist/conversation-copy.js +58 -3
  58. package/node_modules/@maka/runtime/dist/local-web-fetch.js +23 -11
  59. package/node_modules/@maka/runtime/dist/mcp-tools.js +9 -2
  60. package/node_modules/@maka/runtime/dist/model-adapter.js +10 -5
  61. package/node_modules/@maka/runtime/dist/model-factory.js +33 -30
  62. package/node_modules/@maka/runtime/dist/model-fetcher.js +4 -1
  63. package/node_modules/@maka/runtime/dist/model-runtime.js +3 -9
  64. package/node_modules/@maka/runtime/dist/plugin-executor-backend.js +116 -3
  65. package/node_modules/@maka/runtime/dist/plugin-executor-service.js +212 -16
  66. package/node_modules/@maka/runtime/dist/read-page.js +11 -8
  67. package/node_modules/@maka/runtime/dist/recovery-resolver.js +47 -20
  68. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +1 -0
  69. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +2 -2
  70. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +39 -8
  71. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +3 -0
  72. package/node_modules/@maka/runtime/dist/session-manager.js +182 -127
  73. package/node_modules/@maka/runtime/dist/shell-run-manager.js +3 -0
  74. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +29 -4
  75. package/node_modules/@maka/runtime/dist/telemetry/model-pricing.generated.js +141 -134
  76. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +3 -3
  77. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +7 -6
  78. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +28 -62
  79. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +8 -5
  80. package/node_modules/@maka/runtime-host/dist/client/hosted-execution-target.js +7 -1
  81. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  82. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +8 -1
  83. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +6 -1
  84. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +3 -0
  85. package/node_modules/@maka/runtime-host/dist/composition-identity.js +19 -0
  86. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +6 -3
  87. package/node_modules/@maka/runtime-host/dist/protocol/index.js +14 -2
  88. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +4 -1
  89. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +34 -0
  90. package/node_modules/@maka/runtime-host/dist/protocol/prompt-suggestions.js +61 -0
  91. package/node_modules/@maka/runtime-host/dist/protocol/runtime-policy.js +4 -1
  92. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +40 -2
  93. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +2 -1
  94. package/node_modules/@maka/runtime-host/dist/server/builtin-external-agent-plugins.js +188 -0
  95. package/node_modules/@maka/runtime-host/dist/server/candidate.js +12 -7
  96. package/node_modules/@maka/runtime-host/dist/server/client-capability-recovery.js +44 -46
  97. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +3 -0
  98. package/node_modules/@maka/runtime-host/dist/server/context-coordinator.js +2 -0
  99. package/node_modules/@maka/runtime-host/dist/server/execution-composition-factory.js +1 -1
  100. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +212 -24
  101. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +41 -2
  102. package/node_modules/@maka/runtime-host/dist/server/extension-bundle.js +4 -0
  103. package/node_modules/@maka/runtime-host/dist/server/generated-text.js +39 -0
  104. package/node_modules/@maka/runtime-host/dist/server/host-composition-source.js +47 -0
  105. package/node_modules/@maka/runtime-host/dist/server/host-composition.js +1 -29
  106. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +2 -9
  107. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +75 -9
  108. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +12 -0
  109. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +45 -0
  110. package/node_modules/@maka/runtime-host/dist/server/jev-routing-model.js +157 -0
  111. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -2
  112. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +4 -0
  113. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +11 -1
  114. package/node_modules/@maka/runtime-host/dist/server/process-lifecycle.js +1 -1
  115. package/node_modules/@maka/runtime-host/dist/server/process-termination-error.js +27 -0
  116. package/node_modules/@maka/runtime-host/dist/server/prompt-suggestion.js +179 -0
  117. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +93 -14
  118. package/node_modules/@maka/runtime-host/dist/server/runtime-policy-coordinator.js +2 -0
  119. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +99 -12
  120. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +48 -16
  121. package/node_modules/@maka/runtime-host/dist/server/session-effect-coordinator.js +12 -6
  122. package/node_modules/@maka/runtime-host/dist/server/session-title.js +3 -16
  123. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +71 -3
  124. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +3 -0
  125. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +6 -13
  126. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +39 -11
  127. package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +173 -0
  128. package/node_modules/@maka/runtime-host/dist/server/workhub-result-runtime.js +293 -0
  129. package/node_modules/@maka/runtime-host/package.json +2 -0
  130. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +8 -0
  131. package/node_modules/@maka/storage/dist/config-transfer.js +14 -8
  132. package/node_modules/@maka/storage/dist/execution-stores.js +19 -6
  133. package/node_modules/@maka/storage/dist/interaction-store.js +13 -0
  134. package/node_modules/@maka/storage/dist/mcp-config-store.js +91 -2
  135. package/node_modules/@maka/storage/dist/operational-state-store.js +15 -1
  136. package/node_modules/@maka/storage/dist/plan-authority.js +2 -0
  137. package/node_modules/@maka/storage/dist/plan-store.js +30 -0
  138. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  139. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +28 -17
  140. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +9 -3
  141. package/node_modules/@maka/storage/dist/runtime-policy/credential-vault-document.js +4 -1
  142. package/node_modules/@maka/storage/dist/runtime-policy/legacy-custom-connection.js +65 -0
  143. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +10 -5
  144. package/node_modules/@maka/storage/dist/runtime-policy/policy-document.js +2 -0
  145. package/node_modules/@maka/storage/dist/session-bundle-policy.js +11 -0
  146. package/node_modules/@maka/storage/dist/session-store-values.js +16 -4
  147. package/node_modules/@maka/storage/dist/session-store.js +29 -6
  148. package/node_modules/@maka/storage/dist/shell-run-authority.js +1 -0
  149. package/node_modules/@maka/storage/dist/shell-run-store.js +15 -0
  150. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +3 -0
  151. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +74 -1
  152. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +849 -91
  153. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +21 -3
  154. package/node_modules/@maka/storage/dist/usage-screen.js +138 -108
  155. package/package.json +1 -1
@@ -434,6 +434,7 @@ export class SessionContinuityCoordinator {
434
434
  await this.#refreshTranscriptHighWater(sessionId, state);
435
435
  const nextRevision = state.revision + 1;
436
436
  const snapshot = createSessionContinuitySnapshot(canonical, nextRevision);
437
+ this.#invalidateSettledChoiceTranscript(state, canonical);
437
438
  state.canonical = canonical;
438
439
  state.revision = nextRevision;
439
440
  delete state.terminalPublicationFence;
@@ -513,7 +514,7 @@ export class SessionContinuityCoordinator {
513
514
  this.#payAssistantBacklog(subscriber, state);
514
515
  }
515
516
  else {
516
- this.#deliverInOrder(subscriber, () => this.#enqueueAssistantDelta(subscriber, sessionId, runId, event, kind, startOffset));
517
+ this.#deliverInOrder(subscriber, () => this.#enqueueAssistantDelta(subscriber, sessionId, runId, event, kind, startOffset), () => Buffer.byteLength(event.text, 'utf8'));
517
518
  }
518
519
  }
519
520
  return;
@@ -564,16 +565,18 @@ export class SessionContinuityCoordinator {
564
565
  state.toolResultPreviews.delete(event.toolUseId);
565
566
  }
566
567
  for (const subscriber of state.subscribers.values()) {
567
- const frame = {
568
- kind: 'subscription.session_event',
569
- hostEpoch: this.#hostEpoch,
570
- subscriptionId: subscriber.subscriptionId,
571
- sequence: subscriber.nextSequence,
572
- sessionId,
573
- runId,
574
- event: projectSessionEvent(event, sessionId, subscriber.principalKind === 'session_guest'),
575
- };
576
- this.#enqueue(subscriber, frame);
568
+ this.#deliverInOrder(subscriber, () => {
569
+ const frame = {
570
+ kind: 'subscription.session_event',
571
+ hostEpoch: this.#hostEpoch,
572
+ subscriptionId: subscriber.subscriptionId,
573
+ sequence: subscriber.nextSequence,
574
+ sessionId,
575
+ runId,
576
+ event: projectSessionEvent(event, sessionId, subscriber.principalKind === 'session_guest'),
577
+ };
578
+ this.#enqueue(subscriber, frame);
579
+ }, () => Buffer.byteLength(JSON.stringify(event), 'utf8'));
577
580
  }
578
581
  });
579
582
  }
@@ -738,6 +741,7 @@ export class SessionContinuityCoordinator {
738
741
  terminalQueued: false,
739
742
  assistantBacklog: new Map([...committed.state.assistantStreams.keys()].map((key) => [key, { sent: 0 }])),
740
743
  deferred: [],
744
+ deferredBytes: 0,
741
745
  ...(transcript ? { transcript } : {}),
742
746
  };
743
747
  committed.state.subscribers.set(subscriptionId, subscriber);
@@ -995,6 +999,8 @@ export class SessionContinuityCoordinator {
995
999
  const inFlight = subscriber.pumping ? subscriber.queue[0] : undefined;
996
1000
  subscriber.queue = [];
997
1001
  subscriber.queuedBytes = 0;
1002
+ subscriber.deferred = [];
1003
+ subscriber.deferredBytes = 0;
998
1004
  subscriber.nextSequence = (inFlight?.frame.sequence ?? subscriber.lastFlushedSequence) + 1;
999
1005
  const frame = {
1000
1006
  kind: 'subscription.closed',
@@ -1170,6 +1176,7 @@ export class SessionContinuityCoordinator {
1170
1176
  ?.subscriptionIds.delete(subscriber.subscriptionId);
1171
1177
  subscriber.assistantBacklog.clear();
1172
1178
  subscriber.deferred = [];
1179
+ subscriber.deferredBytes = 0;
1173
1180
  if (!this.#closed && state && removed && state.subscribers.size === 0) {
1174
1181
  this.#scheduleInactiveStateCleanup(subscriber.sessionId, state);
1175
1182
  }
@@ -1219,7 +1226,7 @@ export class SessionContinuityCoordinator {
1219
1226
  return;
1220
1227
  }
1221
1228
  subscriber.assistantBacklog.delete(key);
1222
- this.#deliverInOrder(subscriber, () => this.#enqueueAssistantCompletion(subscriber, subscriber.sessionId, runId, { ...stream, text: held }, stream.kind, finalText, interrupted));
1229
+ this.#deliverInOrder(subscriber, () => this.#enqueueAssistantCompletion(subscriber, subscriber.sessionId, runId, { ...stream, text: held }, stream.kind, finalText, interrupted), () => Buffer.byteLength(finalText, 'utf8'));
1223
1230
  }
1224
1231
  #ownedSubscriber(connectionId, subscriptionId) {
1225
1232
  const connection = this.#connections.get(connectionId);
@@ -1278,6 +1285,7 @@ export class SessionContinuityCoordinator {
1278
1285
  }
1279
1286
  const nextRevision = state.revision + 1;
1280
1287
  const value = createSessionContinuitySnapshot(canonical, nextRevision);
1288
+ this.#invalidateSettledChoiceTranscript(state, canonical);
1281
1289
  state.canonical = canonical;
1282
1290
  state.revision = nextRevision;
1283
1291
  return { changed, state, value };
@@ -1288,11 +1296,25 @@ export class SessionContinuityCoordinator {
1288
1296
  value: createSessionContinuitySnapshot(state.canonical, state.revision),
1289
1297
  };
1290
1298
  }
1299
+ #invalidateSettledChoiceTranscript(state, next) {
1300
+ const pending = new Set(next.interactions.pending.map((item) => item.interactionId));
1301
+ if (!state.canonical.interactions.pending.some((item) => (item.request.kind === 'form' || item.request.kind === 'question') &&
1302
+ !pending.has(item.interactionId)))
1303
+ return;
1304
+ // Outcomes can settle after their owner's last event. Their historical rows
1305
+ // then lie behind an already-consumed cursor: advancing the event high water
1306
+ // cannot deliver them. Close explicitly so observers rebuild their bounded tail.
1307
+ for (const subscriber of state.subscribers.values()) {
1308
+ if (subscriber.transcript)
1309
+ this.#closeSubscriber(subscriber, 'transcript_changed');
1310
+ }
1311
+ }
1291
1312
  #publishCanonical(state, canonical) {
1292
1313
  if (isDeepStrictEqual(state.canonical, canonical))
1293
1314
  return;
1294
1315
  const nextRevision = state.revision + 1;
1295
1316
  const snapshot = createSessionContinuitySnapshot(canonical, nextRevision);
1317
+ this.#invalidateSettledChoiceTranscript(state, canonical);
1296
1318
  state.canonical = immutableClone(canonical);
1297
1319
  state.revision = nextRevision;
1298
1320
  this.#broadcastProjection(state, snapshot);
@@ -1307,7 +1329,7 @@ export class SessionContinuityCoordinator {
1307
1329
  sequence: subscriber.nextSequence,
1308
1330
  snapshot: projectSessionSnapshot(snapshot, subscriber.principalKind),
1309
1331
  });
1310
- });
1332
+ }, () => Buffer.byteLength(JSON.stringify(snapshot), 'utf8'));
1311
1333
  }
1312
1334
  }
1313
1335
  /**
@@ -1315,18 +1337,28 @@ export class SessionContinuityCoordinator {
1315
1337
  * on. Every assistant frame and projection goes through here, so the order a
1316
1338
  * subscriber sees is the order the Host produced.
1317
1339
  */
1318
- #deliverInOrder(subscriber, work) {
1340
+ #deliverInOrder(subscriber, work, bytes) {
1341
+ if (subscriber.phase !== 'open')
1342
+ return;
1319
1343
  if (subscriber.assistantBacklog.size === 0 && subscriber.deferred.length === 0) {
1320
1344
  work();
1321
1345
  return;
1322
1346
  }
1323
- subscriber.deferred.push(work);
1347
+ const size = bytes();
1348
+ if (subscriber.queuedBytes + subscriber.deferredBytes + size > MAX_SUBSCRIBER_QUEUED_BYTES) {
1349
+ this.#evictSlowSubscriber(subscriber);
1350
+ return;
1351
+ }
1352
+ subscriber.deferred.push({ work, bytes: size });
1353
+ subscriber.deferredBytes += size;
1324
1354
  }
1325
1355
  #drainDeferred(subscriber) {
1326
1356
  while (subscriber.assistantBacklog.size === 0 &&
1327
1357
  subscriber.deferred.length > 0 &&
1328
1358
  subscriber.phase === 'open') {
1329
- subscriber.deferred.shift()?.();
1359
+ const next = subscriber.deferred.shift();
1360
+ subscriber.deferredBytes -= next.bytes;
1361
+ next.work();
1330
1362
  }
1331
1363
  }
1332
1364
  #runInSessionLane(sessionId, operation, admission) {
@@ -90,12 +90,15 @@ export class HostSessionEffectCoordinator {
90
90
  const header = await this.#readSessionHeader(sessionId);
91
91
  if (header.titleIsManual || header.name !== DEFAULT_SESSION_NAME)
92
92
  return;
93
- generated = await this.#model.generateTitle({
94
- sessionId,
95
- header,
96
- sourceText,
97
- abortSignal,
98
- });
93
+ generated =
94
+ header.backend === 'plugin-executor'
95
+ ? undefined
96
+ : await this.#model.generateTitle({
97
+ sessionId,
98
+ header,
99
+ sourceText,
100
+ abortSignal,
101
+ });
99
102
  }
100
103
  catch {
101
104
  // An unreachable title model is not a Session failure; the fallback name
@@ -195,6 +198,9 @@ export class HostSessionEffectCoordinator {
195
198
  if (header.isArchived) {
196
199
  return settledRecap(recapFailure('session_archived', 'Archived Session cannot generate a recap'));
197
200
  }
201
+ if (header.backend === 'plugin-executor') {
202
+ return settledRecap(recapFailure('operation_unavailable', 'Plugin executor Sessions do not support native recap generation'));
203
+ }
198
204
  const view = await this.#readModel.getSessionView(input.sessionId);
199
205
  if (abort.signal.aborted) {
200
206
  return settledRecap(recapFailure('host_draining', 'Runtime Host is draining'));
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { firstGeneratedLine, unquoteGeneratedText } from './generated-text.js';
19
20
  import { normalizeUserSessionName } from '@maka/core/session-name';
20
21
  const MAX_SOURCE_BYTES = 8 * 1024;
21
22
  const MAX_FALLBACK_CODE_POINTS = 42;
@@ -51,26 +52,12 @@ export function buildSessionTitlePrompt(sourceText) {
51
52
  return `Create a descriptive 5–10 word title for the user message below. Use the user's language; for Chinese and similar languages, use an equivalently brief natural title. Output only the title.\n\n${sourceText}`;
52
53
  }
53
54
  export function cleanGeneratedSessionTitle(text) {
54
- const firstLine = text
55
- .replace(/<think>[\s\S]*?(?:<\/think>|$)/gi, '')
56
- .split(/\r?\n/)
57
- .map((line) => line.trim())
58
- .find(Boolean)
55
+ const firstLine = firstGeneratedLine(text)
59
56
  ?.replace(/^(?:title|标题)\s*[::]\s*/i, '')
60
57
  .trim();
61
58
  if (!firstLine)
62
59
  return undefined;
63
- const pairs = [
64
- ['"', '"'],
65
- ["'", "'"],
66
- ['`', '`'],
67
- ['“', '”'],
68
- ['「', '」'],
69
- ['『', '』'],
70
- ];
71
- const unquoted = pairs.find(([left, right]) => firstLine.startsWith(left) && firstLine.endsWith(right))
72
- ? firstLine.slice(1, -1).trim()
73
- : firstLine;
60
+ const unquoted = unquoteGeneratedText(firstLine);
74
61
  const normalized = normalizeUserSessionName(unquoted);
75
62
  return normalized.ok ? normalized.value : undefined;
76
63
  }
@@ -22,7 +22,8 @@ import { createRuntimeEventStoredMessageProjector, projectTranscriptToolResult,
22
22
  import { foldTurnContribution } from '@maka/storage/session-message-projection';
23
23
  const PERMISSION_OUTCOME_READ_CONCURRENCY = 8;
24
24
  /** One event can emit content, a permission, usage, and terminal/notice rows. */
25
- const EVENT_SEQUENCE_STRIDE = 8;
25
+ // A single event can anchor a batch of Host interaction outcomes.
26
+ const EVENT_SEQUENCE_STRIDE = 4_096;
26
27
  const TRANSCRIPT_TURN_MAX_MESSAGES = 4_096;
27
28
  export const TRANSCRIPT_TURN_MAX_BYTES = 16 * 1024 * 1024;
28
29
  const TRANSCRIPT_SOURCE_MAX_EVENTS = TRANSCRIPT_TURN_MAX_MESSAGES * 2;
@@ -47,6 +48,16 @@ export function createSessionTranscriptReader(input) {
47
48
  readDurableTurnLandmarks: async (sessionId, request) => (await prepared(sessionId)).readTurnLandmarks(sessionId, request),
48
49
  };
49
50
  }
51
+ /** Reads only the delegated Turn's projected assistant output. The indexed
52
+ * Turn extent avoids materializing every earlier message in its Session.
53
+ */
54
+ export function createTurnResultReader(input) {
55
+ const ledger = createDurableLedgerTranscriptReader(input);
56
+ return async (sessionId, turnId) => {
57
+ await input.ensureTranscriptLedger?.(sessionId);
58
+ return ledger.readLatestAssistantForTurn(sessionId, turnId);
59
+ };
60
+ }
50
61
  /**
51
62
  * Pages seek immutable Session event ordinals before decoding payloads. One
52
63
  * Turn is projected at a time, so a page costs one Turn rather than the
@@ -67,6 +78,35 @@ function createDurableLedgerTranscriptReader(input) {
67
78
  if (projected.diagnostics.some(isHardRuntimeEventReadModelDiagnostic)) {
68
79
  throw new Error('Durable RuntimeEvent transcript projection is incomplete');
69
80
  }
81
+ const interactions = await input.stores.interactionStore.listTurnInteractions(turn.invocation.sessionId, turn.invocation.turnId);
82
+ interactions.sort((a, b) => (a.outcome?.outcome.committedAt ?? a.request.createdAt) -
83
+ (b.outcome?.outcome.committedAt ?? b.request.createdAt));
84
+ for (const record of interactions) {
85
+ const { request, outcome } = record;
86
+ if (request.runId !== turn.invocation.runId ||
87
+ (request.request.kind !== 'form' && request.request.kind !== 'question') ||
88
+ !outcome ||
89
+ (outcome.outcome.kind !== 'form_answer' &&
90
+ outcome.outcome.kind !== 'question_answer' &&
91
+ outcome.outcome.kind !== 'closure'))
92
+ continue;
93
+ // Anchor after acceptance, so an incremental reader that already saw the
94
+ // pending request receives the settled history row as well.
95
+ const source = turn.projection.anchors.find((event) => event.ts >= outcome.outcome.committedAt) ??
96
+ turn.projection.anchors.at(-1);
97
+ if (!source)
98
+ continue;
99
+ projected.messages.push({
100
+ type: 'form_interaction',
101
+ id: request.requestId,
102
+ turnId: request.turnId,
103
+ ts: outcome.outcome.committedAt,
104
+ request: request.request,
105
+ outcome: outcome.outcome,
106
+ });
107
+ projected.sourceEventIds.push(source.id);
108
+ }
109
+ assertTurnPresentationBounded(projected.messages);
70
110
  const admission = turn.invocation.sessionId === WORKHUB_COORDINATION_SESSION_ID
71
111
  ? await input.stores.agentRunStore.readRootTurnAdmission(turn.invocation.sessionId, turn.invocation.turnId)
72
112
  : undefined;
@@ -75,7 +115,8 @@ function createDurableLedgerTranscriptReader(input) {
75
115
  : undefined;
76
116
  const ordinals = turn.ordinals;
77
117
  const emitted = new Map();
78
- return projected.messages.map((message, index) => {
118
+ return projected.messages
119
+ .map((message, index) => {
79
120
  const ordinal = ordinals.get(projected.sourceEventIds[index]);
80
121
  if (ordinal === undefined) {
81
122
  throw new Error('Durable transcript message has no source RuntimeEvent');
@@ -91,7 +132,8 @@ function createDurableLedgerTranscriptReader(input) {
91
132
  ? { ...message, coordinationActionId: actionId }
92
133
  : message,
93
134
  };
94
- });
135
+ })
136
+ .sort((a, b) => a.sequence - b.sequence);
95
137
  };
96
138
  const readRun = async (sessionId, request) => store.readTranscriptRun(sessionId, {
97
139
  ...request,
@@ -149,6 +191,29 @@ function createDurableLedgerTranscriptReader(input) {
149
191
  source,
150
192
  readHighWater: highWater,
151
193
  ...pagedTranscriptReads(source),
194
+ async readLatestAssistantForTurn(sessionId, turnId) {
195
+ const extents = await store.readTranscriptTurns(sessionId, { turnId });
196
+ let result = '';
197
+ for (const extent of extents) {
198
+ for (let ordinal = extent.firstOrdinal; ordinal <= extent.lastOrdinal;) {
199
+ const run = await readRun(sessionId, {
200
+ direction: 'newer',
201
+ throughOrdinal: extent.lastOrdinal,
202
+ position: ordinal,
203
+ });
204
+ if (!run)
205
+ break;
206
+ if (run.invocation.turnId === turnId) {
207
+ for (const { message } of await projectTurn(run)) {
208
+ if (message.type === 'assistant' && message.text.trim())
209
+ result = message.text;
210
+ }
211
+ }
212
+ ordinal = run.lastOrdinal + 1;
213
+ }
214
+ }
215
+ return result;
216
+ },
152
217
  /** One row per Turn, folded from the Turn's own projected messages. */
153
218
  async readTurnContributions(sessionId, throughSequence, position, maxContributions) {
154
219
  const watermark = throughSequence ?? (await highWater(sessionId));
@@ -370,6 +435,7 @@ async function readCanonicalPermissionOutcomes(requestIds, reader) {
370
435
  /** Keep only presentation state while the storage snapshot visits complete facts. */
371
436
  function createTranscriptProjection(invocations) {
372
437
  const canonicalPermissionOutcomes = new Map();
438
+ const anchors = [];
373
439
  let messageCount = 0;
374
440
  let messageBytes = 0;
375
441
  let eventCount = 0;
@@ -386,7 +452,9 @@ function createTranscriptProjection(invocations) {
386
452
  },
387
453
  });
388
454
  return {
455
+ anchors,
389
456
  push(event) {
457
+ anchors.push({ id: event.id, ts: event.ts });
390
458
  eventCount += 1;
391
459
  const content = event.content;
392
460
  // The durable model projection is never a transcript input. Large Bash
@@ -49,6 +49,9 @@ export function projectSharedSessionTranscriptMessage(message, sessionId) {
49
49
  : { coordinationActionId: message.coordinationActionId }),
50
50
  };
51
51
  }
52
+ case 'form_interaction':
53
+ // Choice requests and answers are private decision evidence.
54
+ return null;
52
55
  case 'assistant':
53
56
  return {
54
57
  type: message.type,
@@ -112,17 +112,8 @@ export class WorkHubCoordinationActionGate {
112
112
  const source = await this.#stopSource(input.actionId, proposal.expects.targetSessionId);
113
113
  const stopFingerprint = stopActionFingerprint(input, source);
114
114
  await this.#claimAction(input.actionId, 'stop', stopFingerprint, source.delegationId);
115
- const existing = await this.#effects.readStopRequest(source.delegationId);
115
+ const existing = await this.#effects.readStopRequest(source.delegationId, input.actionId);
116
116
  if (existing) {
117
- if (existing.actionId !== input.actionId) {
118
- // `not_owned` deliberately leaves the delegation active, so the user
119
- // can and will try again with a fresh request. That later attempt has
120
- // its own identity and must converge on the immutable non-destructive
121
- // outcome instead of colliding with the first attempt's stop claim.
122
- const resolved = await this.#effects.readStopResolution(source.delegationId);
123
- if (resolved?.outcome === 'not_owned')
124
- return stopResult(resolved);
125
- }
126
117
  assertStopReplay(existing, input, source, stopFingerprint);
127
118
  return this.#stop(existing, source);
128
119
  }
@@ -280,7 +271,7 @@ export class WorkHubCoordinationActionGate {
280
271
  // nothing to converge on — and nothing destructive happened either, so
281
272
  // that case resolves from the active links below, subject to the claim
282
273
  // still naming what they resolve to.
283
- const requested = await this.#effects.readStopRequest(claim.subject);
274
+ const requested = await this.#effects.readStopRequest(claim.subject, actionId);
284
275
  if (requested) {
285
276
  const claimed = await this.#effects.readAssignment(requested.stopsActionId);
286
277
  if (!claimed || claimed.targetSessionId !== targetSessionId) {
@@ -302,7 +293,7 @@ export class WorkHubCoordinationActionGate {
302
293
  return resolved;
303
294
  }
304
295
  async #soleWorkingDelegation(targetSessionId, operation) {
305
- const onTarget = await this.#effects.listActiveAssignments(targetSessionId);
296
+ const onTarget = await this.#effects.listActiveAssignments(targetSessionId, true);
306
297
  if (onTarget.length === 0) {
307
298
  throw new WorkHubActionGateFailure('action_conflict', `WorkHub has no active durable delegation to ${operation} on that Session`);
308
299
  }
@@ -323,6 +314,8 @@ export class WorkHubCoordinationActionGate {
323
314
  holdingWork.push(assignment);
324
315
  }
325
316
  }
317
+ if (holdingWork.length === 0 && operation === 'resume')
318
+ return resolved;
326
319
  if (holdingWork.length !== 1) {
327
320
  throw new WorkHubActionGateFailure('action_conflict', `WorkHub ${operation} target does not identify one active durable delegation`);
328
321
  }
@@ -331,7 +324,7 @@ export class WorkHubCoordinationActionGate {
331
324
  return resolved;
332
325
  }
333
326
  async #stop(request, source) {
334
- const resolved = await this.#effects.readStopResolution(source.delegationId);
327
+ const resolved = await this.#effects.readStopResolution(source.delegationId, request.actionId);
335
328
  if (resolved)
336
329
  return stopResultFromRecord(resolved, request);
337
330
  const retirement = await this.#effects.retireDelegation(source, {
@@ -95,12 +95,12 @@ export class HostWorkHubCoordinationCoordinator {
95
95
  readAssignment: (actionId) => this.#stores.readWorkHubAssignment(actionId),
96
96
  // This lookup is advisory. Stop and replacement both repeat their exact
97
97
  // proof under the Coordination and target admissions before writing.
98
- listActiveAssignments: (targetSessionId) => this.#stores.readActiveWorkHubAssignmentsByTarget([targetSessionId]),
98
+ listActiveAssignments: (targetSessionId, includeStopped) => this.#stores.readActiveWorkHubAssignmentsByTarget([targetSessionId], undefined, includeStopped),
99
99
  readReplacement: (delegationId) => this.#stores.readWorkHubReplacement(delegationId),
100
100
  readReplacementAbort: (delegationId) => this.#stores.readWorkHubReplacementAbort(delegationId),
101
101
  readSupersession: (delegationId) => this.#stores.readWorkHubSupersession(delegationId),
102
- readStopRequest: (delegationId) => this.#stores.readWorkHubStopRequest(delegationId),
103
- readStopResolution: (delegationId) => this.#stores.readWorkHubStopResolution(delegationId),
102
+ readStopRequest: (delegationId, actionId) => this.#stores.readWorkHubStopRequest(delegationId, actionId),
103
+ readStopResolution: (delegationId, actionId) => this.#stores.readWorkHubStopResolution(delegationId, actionId),
104
104
  assign: options.sessionActions.assign,
105
105
  prepareReplacement: (input) => this.#prepareReplacement(input),
106
106
  abortReplacement: (input) => this.#abortReplacement(input),
@@ -165,7 +165,7 @@ export class HostWorkHubCoordinationCoordinator {
165
165
  });
166
166
  }
167
167
  async #prepareStop(input) {
168
- const suffix = workHubDestructiveClaimIdentitySuffix(input.stopsDelegationId);
168
+ let suffix;
169
169
  return this.#commitCoordinationFact({
170
170
  // Only the two Sessions this stop can change: the one whose delegation
171
171
  // ends, and the Coordination Session that records it. Holding a lane for
@@ -173,7 +173,14 @@ export class HostWorkHubCoordinationCoordinator {
173
173
  // delegation traffic behind one stop, and the proof below needs no lane
174
174
  // it does not already hold.
175
175
  admissionSessionIds: [WORKHUB_COORDINATION_SESSION_ID, input.targetSessionId],
176
- read: () => this.#stores.readWorkHubStopRequest(input.stopsDelegationId),
176
+ read: async () => {
177
+ // Choose the slot from the same admitted snapshot as the write.
178
+ const first = await this.#stores.readWorkHubStopRequest(input.stopsDelegationId);
179
+ suffix = workHubDestructiveClaimIdentitySuffix(first && first.actionId !== input.actionId
180
+ ? JSON.stringify([input.stopsDelegationId, input.actionId])
181
+ : input.stopsDelegationId);
182
+ return this.#stores.readWorkHubStopRequest(input.stopsDelegationId, input.actionId);
183
+ },
177
184
  build: (existing) => ({
178
185
  type: 'workhub_coordination',
179
186
  id: `whq_${suffix}`,
@@ -196,7 +203,7 @@ export class HostWorkHubCoordinationCoordinator {
196
203
  const [replacement, supersession, activeAssignments] = await Promise.all([
197
204
  this.#stores.readWorkHubReplacement(input.stopsDelegationId),
198
205
  this.#stores.readWorkHubSupersession(input.stopsDelegationId),
199
- this.#stores.readActiveWorkHubAssignmentsByTarget([input.targetSessionId]),
206
+ this.#stores.readActiveWorkHubAssignmentsByTarget([input.targetSessionId], undefined, true),
200
207
  ]);
201
208
  if (replacement || supersession) {
202
209
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub delegation is already being replaced');
@@ -225,9 +232,9 @@ export class HostWorkHubCoordinationCoordinator {
225
232
  }
226
233
  #resolveStop(input) {
227
234
  const request = input.request;
228
- const suffix = workHubDestructiveClaimIdentitySuffix(request.stopsDelegationId);
235
+ const suffix = workHubDestructiveClaimIdentitySuffix(JSON.stringify([request.stopsDelegationId, request.actionId]));
229
236
  return this.#commitCoordinationFact({
230
- read: () => this.#stores.readWorkHubStopResolution(request.stopsDelegationId),
237
+ read: () => this.#stores.readWorkHubStopResolution(request.stopsDelegationId, request.actionId),
231
238
  build: (existing) => ({
232
239
  type: 'workhub_coordination',
233
240
  id: `whz_${suffix}`,
@@ -244,9 +251,23 @@ export class HostWorkHubCoordinationCoordinator {
244
251
  outcome: input.outcome,
245
252
  ...(input.targetTurnId ? { targetTurnId: input.targetTurnId } : {}),
246
253
  }),
254
+ additionalMessages: async (resolved) => {
255
+ const primary = await this.#stores.readWorkHubStopResolution(request.stopsDelegationId);
256
+ // Keep immutable per-action receipts; the delegation slot aggregates only
257
+ // terminal knowledge. Upgrade not_owned at a distinct immutable identity;
258
+ // appendMessages never replaces an existing identity.
259
+ if (primary && (primary.outcome !== 'not_owned' || resolved.outcome === 'not_owned'))
260
+ return [];
261
+ return [
262
+ {
263
+ ...resolved,
264
+ id: `${primary ? 'whzt_' : 'whz_'}${workHubDestructiveClaimIdentitySuffix(request.stopsDelegationId)}`,
265
+ },
266
+ ];
267
+ },
247
268
  conflictMessage: 'WorkHub stop already has a different resolution',
248
269
  beforeAppend: async () => {
249
- const durable = await this.#stores.readWorkHubStopRequest(request.stopsDelegationId);
270
+ const durable = await this.#stores.readWorkHubStopRequest(request.stopsDelegationId, request.actionId);
250
271
  if (!durable || !isDeepStrictEqual(durable, request)) {
251
272
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop request identity changed');
252
273
  }
@@ -296,7 +317,10 @@ export class HostWorkHubCoordinationCoordinator {
296
317
  }
297
318
  await options.beforeAppend(lease);
298
319
  try {
299
- await this.#stores.appendMessages(WORKHUB_COORDINATION_SESSION_ID, [requested]);
320
+ await this.#stores.appendMessages(WORKHUB_COORDINATION_SESSION_ID, [
321
+ requested,
322
+ ...((await options.additionalMessages?.(requested)) ?? []),
323
+ ]);
300
324
  await this.#continuity.refreshCanonical(WORKHUB_COORDINATION_SESSION_ID, lease);
301
325
  return requested;
302
326
  }
@@ -314,7 +338,7 @@ export class HostWorkHubCoordinationCoordinator {
314
338
  const result = await this.#actionGate.candidates();
315
339
  // One bounded read for the whole page. The candidate set is already
316
340
  // capped, and a per-candidate lookup would rescan each target's history.
317
- const latestByTarget = new Map((await this.#stores.readActiveWorkHubAssignmentsByTarget(result.candidates.map(({ sessionId }) => sessionId), 1)).map((assignment) => [assignment.targetSessionId, assignment.actionId]));
341
+ const latestByTarget = new Map((await this.#stores.readActiveWorkHubAssignmentsByTarget(result.candidates.map(({ sessionId }) => sessionId), 1, true)).map((assignment) => [assignment.targetSessionId, assignment.actionId]));
318
342
  return {
319
343
  ok: true,
320
344
  result: {
@@ -731,6 +755,10 @@ export class HostWorkHubCoordinationCoordinator {
731
755
  catch {
732
756
  // Invalid output, unavailable candidates, or provider failure cannot
733
757
  // silently become creation or bind an arbitrary existing Session.
758
+ // Preparation failures (for example transcript reads) and injected-model
759
+ // throws bind this admission to clarify, preventing actions for this turn.
760
+ // This differs intentionally from Jev's internal provider/candidate errors:
761
+ // that opt-in adapter returns undefined to preserve the legacy unbound path.
734
762
  return { kind: 'routing', disposition: 'clarify' };
735
763
  }
736
764
  }