maka-agent 0.2.0-dev.15.20260902 → 0.2.0-dev.16.20260903

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 (160) hide show
  1. package/dist/cli-core.js +0 -1
  2. package/dist/pi-transcript.js +48 -0
  3. package/dist/pi-tui-form-interaction.js +497 -0
  4. package/dist/pi-tui-pickers.js +256 -55
  5. package/dist/pi-tui-runner.js +215 -12
  6. package/dist/runtime-host-cli.js +17 -42
  7. package/dist/runtime-host-lifecycle-transaction.js +31 -13
  8. package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
  9. package/dist/runtime-host-onboarding.js +3 -1
  10. package/dist/runtime-host-openrc-service.js +469 -0
  11. package/dist/runtime-host-run-command.js +6 -2
  12. package/dist/runtime-host-service-command.js +3 -3
  13. package/dist/runtime-host-service-management-command.js +43 -15
  14. package/dist/runtime-host-session-channel.js +3 -0
  15. package/dist/runtime-host-session-driver.js +21 -6
  16. package/dist/runtime-host-setup-command.js +30 -31
  17. package/dist/tui-context-refresh.js +103 -0
  18. package/dist/tui-copy-catalog.js +73 -0
  19. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  21. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  22. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  23. package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
  24. package/node_modules/@maka/core/dist/computer-use.js +27 -92
  25. package/node_modules/@maka/core/dist/interaction.js +577 -3
  26. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  27. package/node_modules/@maka/core/dist/local-memory.js +2 -2
  28. package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
  29. package/node_modules/@maka/core/dist/model-metadata.js +26 -7
  30. package/node_modules/@maka/core/dist/model-thinking.js +17 -0
  31. package/node_modules/@maka/core/dist/provider-registry.js +1 -0
  32. package/node_modules/@maka/core/dist/runtime-event.js +23 -1
  33. package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
  34. package/node_modules/@maka/core/dist/session.js +95 -2
  35. package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
  36. package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
  37. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
  38. package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
  39. package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
  40. package/node_modules/@maka/core/package.json +2 -0
  41. package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
  42. package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
  43. package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
  44. package/node_modules/@maka/eval/dist/process-termination.js +83 -0
  45. package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
  46. package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
  49. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
  50. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
  51. package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
  52. package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
  53. package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
  54. package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
  55. package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
  56. package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
  57. package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
  58. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
  59. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
  60. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
  61. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
  63. package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
  64. package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
  65. package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
  66. package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
  67. package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
  68. package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
  69. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
  70. package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
  71. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
  72. package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
  73. package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
  74. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
  75. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
  76. package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
  77. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
  78. package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
  79. package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
  80. package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
  81. package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
  82. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
  83. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
  84. package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
  85. package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
  86. package/node_modules/@maka/runtime/package.json +1 -0
  87. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
  88. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
  89. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
  90. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  91. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
  92. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
  93. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
  94. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
  95. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
  96. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
  97. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
  98. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
  99. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
  100. package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
  101. package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
  102. package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
  103. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
  104. package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
  105. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
  106. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
  107. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
  112. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
  114. package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
  116. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
  117. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
  118. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  119. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
  120. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
  121. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
  122. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
  123. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
  124. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
  125. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
  126. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
  127. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
  128. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
  129. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
  130. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
  131. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
  132. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
  133. package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
  134. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
  135. package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
  136. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
  137. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
  138. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
  139. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
  140. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
  141. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
  142. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
  143. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
  144. package/node_modules/@maka/runtime-host/package.json +1 -0
  145. package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
  146. package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
  147. package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
  148. package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
  149. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
  150. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
  151. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
  152. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
  153. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
  154. package/node_modules/@maka/storage/dist/session-store.js +39 -6
  155. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
  156. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
  157. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
  158. package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
  159. package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
  160. package/package.json +1 -1
@@ -32,19 +32,26 @@ export class ClientCapabilityInvocationError extends Error {
32
32
  export class ClientCapabilityInvocationBroker {
33
33
  #senderFor;
34
34
  #onRegistrationIdle;
35
+ #scheduleTimeout;
35
36
  #invocations = new Map();
36
37
  #retiredInvocationIds = new Set();
37
38
  constructor(options) {
38
39
  this.#senderFor = options.senderFor;
39
40
  this.#onRegistrationIdle = options.onRegistrationIdle;
41
+ this.#scheduleTimeout =
42
+ options.scheduleTimeout ??
43
+ ((callback, timeoutMs) => {
44
+ const timer = setTimeout(callback, timeoutMs);
45
+ return () => clearTimeout(timer);
46
+ });
40
47
  }
41
- async invoke(registration, binding, args, context, signal, timeoutMs, onProgress) {
42
- const prepared = this.prepare(registration, binding, args, context, signal, timeoutMs, onProgress);
48
+ async invoke(registration, binding, args, context, signal, timeoutMs, onProgress, requestInteraction) {
49
+ const prepared = this.prepare(registration, binding, args, context, signal, timeoutMs, onProgress, requestInteraction);
43
50
  await prepared.waitUntilAccepted();
44
51
  return prepared.admit();
45
52
  }
46
- prepare(registration, binding, args, context, signal, timeoutMs, onProgress) {
47
- return this.#prepare(registration, signal, timeoutMs, onProgress, (invocationId) => ({
53
+ prepare(registration, binding, args, context, signal, timeoutMs, onProgress, requestInteraction) {
54
+ return this.#prepare(registration, signal, timeoutMs, onProgress, requestInteraction, (invocationId) => ({
48
55
  kind: 'client.capability.call',
49
56
  invocationId,
50
57
  registrationId: registration.registrationId,
@@ -64,7 +71,7 @@ export class ClientCapabilityInvocationBroker {
64
71
  return prepared.admit();
65
72
  }
66
73
  prepareService(registration, serviceId, version, method, input, signal, timeoutMs) {
67
- return this.#prepare(registration, signal, timeoutMs, undefined, (invocationId) => ({
74
+ return this.#prepare(registration, signal, timeoutMs, undefined, undefined, (invocationId) => ({
68
75
  kind: 'client.capability.service_call',
69
76
  invocationId,
70
77
  registrationId: registration.registrationId,
@@ -74,7 +81,7 @@ export class ClientCapabilityInvocationBroker {
74
81
  input,
75
82
  }));
76
83
  }
77
- #prepare(registration, signal, timeoutMs, onProgress, frameFor) {
84
+ #prepare(registration, signal, timeoutMs, onProgress, requestInteraction, frameFor) {
78
85
  const sender = this.#senderFor(registration.connectionId);
79
86
  if (!sender) {
80
87
  throw new ClientCapabilityInvocationError('capability_lost', 'Client Capability provider is unavailable');
@@ -99,9 +106,15 @@ export class ClientCapabilityInvocationBroker {
99
106
  if (!invocation)
100
107
  return;
101
108
  void sender.send({ kind: 'client.capability.cancel', invocationId }).catch(() => { });
102
- this.#settle(invocation, undefined, invocation.phase === 'dispatched' || invocation.phase === 'accepted'
109
+ const error = invocation.phase === 'dispatched' || invocation.phase === 'accepted'
103
110
  ? asError(abortReason(signal))
104
- : new ToolOutcomeUnknownError('Client Capability invocation was cancelled after admission'), true);
111
+ : new ToolOutcomeUnknownError('Client Capability invocation was cancelled after admission');
112
+ if (invocation.interaction) {
113
+ this.#terminateInteraction(invocation, error, true, true);
114
+ }
115
+ else {
116
+ this.#settle(invocation, undefined, error, true);
117
+ }
105
118
  }
106
119
  : undefined;
107
120
  const invocation = {
@@ -114,14 +127,14 @@ export class ClientCapabilityInvocationBroker {
114
127
  signal,
115
128
  onAbort,
116
129
  onProgress,
130
+ requestInteraction,
117
131
  timeoutMs,
118
132
  providerAvailability: new AbortController(),
119
- timer: undefined,
120
133
  acceptedSettled: false,
121
134
  phase: 'dispatched',
122
135
  };
123
136
  this.#invocations.set(invocationId, invocation);
124
- this.#startTimeout(invocation);
137
+ this.#armTimer(invocation);
125
138
  if (onAbort)
126
139
  signal?.addEventListener('abort', onAbort, { once: true });
127
140
  void sender.send(frameFor(invocationId)).catch(() => {
@@ -139,15 +152,16 @@ export class ClientCapabilityInvocationBroker {
139
152
  invocationId,
140
153
  providerSignal: this.#invocations.get(invocationId)?.providerAvailability.signal ?? AbortSignal.abort(),
141
154
  waitUntilAccepted: () => accepted,
142
- admit: async (onProgress) => {
155
+ admit: async (onProgress, requestInteraction) => {
143
156
  await accepted;
144
157
  const invocation = this.#invocations.get(invocationId);
145
158
  if (!invocation)
146
159
  return result;
147
160
  if (invocation.phase === 'accepted') {
148
161
  invocation.onProgress = onProgress ?? invocation.onProgress;
162
+ invocation.requestInteraction = requestInteraction ?? invocation.requestInteraction;
149
163
  invocation.phase = 'admitted';
150
- this.#startTimeout(invocation);
164
+ this.#armTimer(invocation);
151
165
  const currentSender = this.#senderFor(invocation.registration.connectionId);
152
166
  if (!currentSender) {
153
167
  this.#settle(invocation, undefined, new ClientCapabilityInvocationError('capability_lost', 'Client Capability provider disappeared before admission'), false);
@@ -193,9 +207,7 @@ export class ClientCapabilityInvocationBroker {
193
207
  throw new Error('Client Capability invocation was accepted more than once');
194
208
  }
195
209
  invocation.phase = 'accepted';
196
- if (invocation.timer)
197
- clearTimeout(invocation.timer);
198
- invocation.timer = undefined;
210
+ this.#clearTimer(invocation);
199
211
  invocation.acceptedSettled = true;
200
212
  invocation.resolveAccepted(frame.admissionEvidence);
201
213
  return;
@@ -207,13 +219,20 @@ export class ClientCapabilityInvocationBroker {
207
219
  this.#settle(invocation, undefined, new ClientCapabilityInvocationError('provider_rejected', frame.message), true);
208
220
  return;
209
221
  case 'client.capability.failed':
210
- if (invocation.phase !== 'admitted' && invocation.phase !== 'chunks') {
222
+ if (invocation.phase === 'dispatched' || invocation.phase === 'accepted') {
211
223
  throw new Error('Client Capability failure arrived before admission');
212
224
  }
213
- this.#settle(invocation, undefined, new ClientCapabilityInvocationError('provider_failed', frame.message), true);
225
+ if (invocation.interaction) {
226
+ this.#terminateInteraction(invocation, new ClientCapabilityInvocationError('provider_failed', frame.message), true, true);
227
+ }
228
+ else {
229
+ this.#settle(invocation, undefined, new ClientCapabilityInvocationError('provider_failed', frame.message), true);
230
+ }
214
231
  return;
215
232
  case 'client.capability.progress':
216
- if (invocation.phase !== 'admitted' && invocation.phase !== 'chunks') {
233
+ if (invocation.phase !== 'admitted' &&
234
+ invocation.phase !== 'delivering_interaction_result' &&
235
+ invocation.phase !== 'chunks') {
217
236
  throw new Error('Client Capability progress arrived before admission');
218
237
  }
219
238
  if (invocation.progress &&
@@ -225,14 +244,27 @@ export class ClientCapabilityInvocationBroker {
225
244
  invocation.progress = { current: frame.current, total: frame.total };
226
245
  invocation.onProgress?.(frame.current, frame.total);
227
246
  return;
247
+ case 'client.capability.interaction_request':
248
+ this.#acceptInteraction(invocation, frame.interactionId, frame.request);
249
+ return;
228
250
  case 'client.capability.result':
229
- if (invocation.phase !== 'admitted') {
251
+ if (invocation.phase === 'awaiting_interaction') {
252
+ this.#terminateInteraction(invocation, new ClientCapabilityInvocationError('provider_failed', 'Client Capability provider returned before its interaction completed'), true, true);
253
+ return;
254
+ }
255
+ if (invocation.phase !== 'admitted' &&
256
+ invocation.phase !== 'delivering_interaction_result') {
230
257
  throw new Error('Client Capability result arrived outside the admitted phase');
231
258
  }
232
259
  this.#settle(invocation, frame.result, undefined, true);
233
260
  return;
234
261
  case 'client.capability.result_start':
235
- if (invocation.phase !== 'admitted') {
262
+ if (invocation.phase === 'awaiting_interaction') {
263
+ this.#terminateInteraction(invocation, new ClientCapabilityInvocationError('provider_failed', 'Client Capability provider returned before its interaction completed'), true, true);
264
+ return;
265
+ }
266
+ if (invocation.phase !== 'admitted' &&
267
+ invocation.phase !== 'delivering_interaction_result') {
236
268
  throw new Error('Client Capability result chunks started outside the admitted phase');
237
269
  }
238
270
  invocation.phase = 'chunks';
@@ -247,17 +279,26 @@ export class ClientCapabilityInvocationBroker {
247
279
  this.#acceptChunk(invocation, frame.index, frame.data);
248
280
  }
249
281
  }
250
- releaseConnection(connectionId) {
282
+ async releaseConnection(connectionId) {
283
+ const interactions = [];
251
284
  for (const invocation of [...this.#invocations.values()]) {
252
285
  if (invocation.registration.connectionId !== connectionId)
253
286
  continue;
254
287
  if (invocation.phase === 'dispatched' || invocation.phase === 'accepted') {
255
288
  invocation.providerAvailability.abort(new ClientCapabilityInvocationError('capability_lost', 'Client Capability provider disconnected before admission'));
256
289
  }
257
- this.#settle(invocation, undefined, invocation.phase === 'dispatched' || invocation.phase === 'accepted'
290
+ const error = invocation.phase === 'dispatched' || invocation.phase === 'accepted'
258
291
  ? new ClientCapabilityInvocationError('capability_lost', 'Client Capability provider disconnected before admission')
259
- : new ToolOutcomeUnknownError('Client Capability provider disconnected after accepting the call'), false);
292
+ : new ToolOutcomeUnknownError('Client Capability provider disconnected after accepting the call');
293
+ if (invocation.interaction) {
294
+ interactions.push(invocation.interaction.done);
295
+ this.#terminateInteraction(invocation, error, false, true);
296
+ }
297
+ else {
298
+ this.#settle(invocation, undefined, error, false);
299
+ }
260
300
  }
301
+ await Promise.all(interactions);
261
302
  }
262
303
  holdsRegistration(registration) {
263
304
  return [...this.#invocations.values()].some((invocation) => invocation.registration === registration);
@@ -296,12 +337,101 @@ export class ClientCapabilityInvocationBroker {
296
337
  }
297
338
  this.#settle(invocation, decodeClientCapabilityResult(decoded), undefined, true);
298
339
  }
299
- #startTimeout(invocation) {
300
- if (invocation.timer)
301
- clearTimeout(invocation.timer);
302
- invocation.timer = setTimeout(() => {
340
+ #acceptInteraction(invocation, interactionId, request) {
341
+ if ((invocation.phase !== 'admitted' && invocation.phase !== 'delivering_interaction_result') ||
342
+ invocation.interaction) {
343
+ if (invocation.interaction) {
344
+ this.#terminateInteraction(invocation, new ClientCapabilityInvocationError('provider_failed', 'Client Capability provider requested overlapping interactions'), true, true);
345
+ return;
346
+ }
347
+ throw new Error('Client Capability interaction arrived outside the admitted phase');
348
+ }
349
+ if (!invocation.requestInteraction) {
350
+ this.#settle(invocation, undefined, new ClientCapabilityInvocationError('provider_failed', 'Client Capability interaction is unavailable for this invocation'), true);
351
+ return;
352
+ }
353
+ this.#clearTimer(invocation);
354
+ invocation.phase = 'awaiting_interaction';
355
+ let resolveDone;
356
+ const interaction = {
357
+ interactionId,
358
+ controller: new AbortController(),
359
+ done: new Promise((resolve) => {
360
+ resolveDone = resolve;
361
+ }),
362
+ resolveDone: () => resolveDone(),
363
+ };
364
+ invocation.interaction = interaction;
365
+ void this.#runInteraction(invocation, interaction, request);
366
+ }
367
+ async #runInteraction(invocation, interaction, request) {
368
+ try {
369
+ const signal = invocation.signal
370
+ ? AbortSignal.any([invocation.signal, interaction.controller.signal])
371
+ : interaction.controller.signal;
372
+ const result = await invocation.requestInteraction(request, {
373
+ cancellationSignal: signal,
374
+ });
375
+ if (!this.#isCurrentInteraction(invocation, interaction))
376
+ return;
377
+ const terminalBeforeSend = interaction.terminal;
378
+ if (terminalBeforeSend) {
379
+ this.#settle(invocation, undefined, terminalBeforeSend.error, terminalBeforeSend.releaseRemote);
380
+ return;
381
+ }
382
+ const sender = this.#senderFor(invocation.registration.connectionId);
383
+ if (!sender) {
384
+ this.#settle(invocation, undefined, new ToolOutcomeUnknownError('Client Capability provider disappeared before receiving an interaction result'), false);
385
+ return;
386
+ }
387
+ invocation.interaction = undefined;
388
+ invocation.phase = 'delivering_interaction_result';
389
+ this.#armTimer(invocation);
390
+ await sender.send({
391
+ kind: 'client.capability.interaction_result',
392
+ invocationId: invocation.invocationId,
393
+ interactionId: interaction.interactionId,
394
+ result,
395
+ });
396
+ if (this.#invocations.get(invocation.invocationId) !== invocation)
397
+ return;
398
+ if (invocation.phase !== 'delivering_interaction_result')
399
+ return;
400
+ invocation.phase = 'admitted';
401
+ this.#armTimer(invocation);
402
+ }
403
+ catch (error) {
404
+ if (this.#invocations.get(invocation.invocationId) !== invocation)
405
+ return;
406
+ if (invocation.interaction !== interaction) {
407
+ if (invocation.phase !== 'delivering_interaction_result')
408
+ return;
409
+ this.#settle(invocation, undefined, new ToolOutcomeUnknownError(`Client Capability interaction result could not be delivered: ${asError(error).message}`), false);
410
+ return;
411
+ }
412
+ this.#settle(invocation, undefined, interaction.terminal?.error ?? asError(error), interaction.terminal?.releaseRemote ?? true);
413
+ }
414
+ finally {
415
+ interaction.resolveDone();
416
+ }
417
+ }
418
+ #terminateInteraction(invocation, error, releaseRemote, cancelProducer) {
419
+ const interaction = invocation.interaction;
420
+ if (!interaction || interaction.terminal)
421
+ return;
422
+ interaction.terminal = { error, releaseRemote };
423
+ if (cancelProducer)
424
+ interaction.controller.abort(error);
425
+ }
426
+ #isCurrentInteraction(invocation, interaction) {
427
+ return (this.#invocations.get(invocation.invocationId) === invocation &&
428
+ invocation.interaction === interaction);
429
+ }
430
+ #armTimer(invocation) {
431
+ this.#clearTimer(invocation);
432
+ invocation.cancelTimer = this.#scheduleTimeout(() => {
303
433
  const current = this.#invocations.get(invocation.invocationId);
304
- if (!current)
434
+ if (current !== invocation)
305
435
  return;
306
436
  const sender = this.#senderFor(current.registration.connectionId);
307
437
  void sender
@@ -312,12 +442,15 @@ export class ClientCapabilityInvocationBroker {
312
442
  : new ToolOutcomeUnknownError('Client Capability invocation timed out after admission'), true);
313
443
  }, invocation.timeoutMs);
314
444
  }
445
+ #clearTimer(invocation) {
446
+ invocation.cancelTimer?.();
447
+ invocation.cancelTimer = undefined;
448
+ }
315
449
  #settle(invocation, result, error, releaseRemote) {
316
450
  if (this.#invocations.get(invocation.invocationId) !== invocation)
317
451
  return;
318
452
  this.#invocations.delete(invocation.invocationId);
319
- if (invocation.timer)
320
- clearTimeout(invocation.timer);
453
+ this.#clearTimer(invocation);
321
454
  if (invocation.onAbort && invocation.signal) {
322
455
  invocation.signal.removeEventListener('abort', invocation.onAbort);
323
456
  }
@@ -20,7 +20,7 @@ import { parseRequestHeaders } from '@maka/core/runtime-policy';
20
20
  import { PROVIDER_REGISTRY, providerFallbackModelIds } from '@maka/core/llm-connections';
21
21
  import { createConnectionEffectFetchTransport, } from '@maka/runtime/network/scoped-fetch-transport';
22
22
  import { createRequestCustomizationFetch } from '@maka/runtime/request-customization-fetch';
23
- import { isOAuthSubscriptionProvider } from '@maka/runtime/subscription-credentials';
23
+ import { isOAuthSubscriptionProvider, parseOAuthSubscriptionTokens, } from '@maka/runtime/subscription-credentials';
24
24
  import { runConnectionModelDiscoveryEffect } from '@maka/runtime/model-fetcher';
25
25
  import { runConnectionTestEffect } from '@maka/runtime/test-connection';
26
26
  import { authenticateRuntimePolicyStoresWriter, RuntimePolicyStoreError, } from '@maka/storage/runtime-policy-stores';
@@ -101,6 +101,8 @@ export class HostConnectionEffectCoordinator {
101
101
  const lane = onboardingLane(input);
102
102
  return this.#admit(lane, 'connection.onboarding.verify', async () => {
103
103
  const prepared = await this.#discoverOnboarding(input);
104
+ if (prepared.kind === 'empty')
105
+ return { kind: 'failed', errorClass: 'invalid_response' };
104
106
  return prepared.kind === 'ready' ? { kind: 'verified', models: prepared.models } : prepared;
105
107
  });
106
108
  }
@@ -108,13 +110,22 @@ export class HostConnectionEffectCoordinator {
108
110
  const lane = onboardingLane(input);
109
111
  return this.#admit(lane, 'connection.onboarding.save', async () => {
110
112
  const prepared = await this.#discoverOnboarding(input);
113
+ if (prepared.kind === 'empty')
114
+ return { kind: 'rejected', reason: 'model_unavailable' };
111
115
  if (prepared.kind !== 'ready')
112
116
  return prepared;
113
117
  const available = new Set(prepared.models.map(({ id }) => id));
114
- if (input.enabledModelIds.some((modelId) => !available.has(modelId))) {
118
+ // An adoption caller has no model inventory before the Host performs this
119
+ // discovery. Empty therefore means "enable everything this operation
120
+ // verified"; ordinary onboarding callers may still submit an explicit
121
+ // non-empty subset.
122
+ const enabledModelIds = input.enabledModelIds.length > 0
123
+ ? input.enabledModelIds
124
+ : prepared.models.map(({ id }) => id);
125
+ if (enabledModelIds.some((modelId) => !available.has(modelId))) {
115
126
  return { kind: 'rejected', reason: 'model_unavailable' };
116
127
  }
117
- return this.#activation.runMutation(async () => this.#commitOnboarding(input, prepared));
128
+ return this.#activation.runMutation(async () => this.#commitOnboarding(enabledModelIds, prepared));
118
129
  });
119
130
  }
120
131
  async #discoverOnboarding(input) {
@@ -138,13 +149,25 @@ export class HostConnectionEffectCoordinator {
138
149
  if (begun.kind === 'catalog_full') {
139
150
  return { kind: 'rejected', reason: 'catalog_full' };
140
151
  }
152
+ if (begun.kind === 'slug_taken') {
153
+ return { kind: 'rejected', reason: 'slug_taken' };
154
+ }
141
155
  const providerType = begun.candidate.providerType;
142
156
  const candidate = begun.existingConnection ?? undefined;
143
157
  const supplied = input.apiKey?.trim() ?? '';
144
- const secret = supplied || begun.storedSecret || '';
145
- if (PROVIDER_REGISTRY[providerType].authKind === 'api_key' && secret.length === 0) {
158
+ const persistedSecret = supplied || begun.storedSecret || '';
159
+ if ((PROVIDER_REGISTRY[providerType].authKind === 'api_key' ||
160
+ PROVIDER_REGISTRY[providerType].authKind === 'oauth_token') &&
161
+ persistedSecret.length === 0) {
146
162
  return { kind: 'rejected', reason: 'credential_not_configured' };
147
163
  }
164
+ let discoverySecret = persistedSecret;
165
+ if (isOAuthSubscriptionProvider(providerType) && persistedSecret.length > 0) {
166
+ const tokens = parseOAuthSubscriptionTokens(persistedSecret);
167
+ if (!tokens)
168
+ return { kind: 'failed', errorClass: 'auth' };
169
+ discoverySecret = tokens.access_token;
170
+ }
148
171
  // Mirrors the blank-key contract above: a null baseUrl reuses the
149
172
  // existing connection's persisted endpoint or the registry default.
150
173
  // A relay provider with no endpoint from any of those sources cannot
@@ -165,7 +188,7 @@ export class HostConnectionEffectCoordinator {
165
188
  // The probe must go out the way the models path sends it (#withTransport):
166
189
  // with the connection's custom request headers and body overlay, both
167
190
  // pinned by the ticket whose basis the commit revalidates.
168
- const effect = await this.#runModelDiscovery(base, secret, {
191
+ const effect = await this.#runModelDiscovery(base, discoverySecret, {
169
192
  fetch: createRequestCustomizationFetch(transport.fetch, {
170
193
  headers: begun.requestHeadersSecret
171
194
  ? parseRequestHeaders(begun.requestHeadersSecret)
@@ -173,12 +196,10 @@ export class HostConnectionEffectCoordinator {
173
196
  bodyOverlay: base.requestBodyOverlay,
174
197
  }),
175
198
  });
176
- if (!effect.ok || effect.models.length === 0) {
177
- return {
178
- kind: 'failed',
179
- errorClass: effect.ok ? 'invalid_response' : effect.error.kind,
180
- };
181
- }
199
+ if (!effect.ok)
200
+ return { kind: 'failed', errorClass: effect.error.kind };
201
+ if (effect.models.length === 0)
202
+ return { kind: 'empty' };
182
203
  return {
183
204
  kind: 'ready',
184
205
  ticket: begun.ticket,
@@ -190,11 +211,11 @@ export class HostConnectionEffectCoordinator {
190
211
  await transport.close();
191
212
  }
192
213
  }
193
- async #commitOnboarding(input, prepared) {
214
+ async #commitOnboarding(enabledModelIds, prepared) {
194
215
  try {
195
216
  const committed = await this.#stores.operations.completeConnectionOnboarding(prepared.ticket, {
196
217
  suppliedSecret: prepared.suppliedSecret || null,
197
- enabledModelIds: input.enabledModelIds,
218
+ enabledModelIds,
198
219
  discovery: {
199
220
  models: prepared.models,
200
221
  source: 'fetched',
@@ -207,6 +228,9 @@ export class HostConnectionEffectCoordinator {
207
228
  if (committed.kind === 'target_missing') {
208
229
  return { kind: 'rejected', reason: 'connection_not_found' };
209
230
  }
231
+ if (committed.kind === 'slug_taken') {
232
+ return { kind: 'rejected', reason: 'slug_taken' };
233
+ }
210
234
  if (committed.kind === 'superseded') {
211
235
  return { kind: 'rejected', reason: 'superseded' };
212
236
  }
@@ -116,11 +116,13 @@ export class HostDailyReviewCoordinator {
116
116
  const snapshot = await this.#store.readConfig();
117
117
  return querySuccess({ kind: 'config', ...snapshot });
118
118
  }
119
- case 'summary':
119
+ case 'summary': {
120
+ const now = this.#now();
120
121
  return querySuccess({
121
122
  kind: 'summary',
122
- summary: await this.#buildSummary(input.offsetDays, input.daySpan),
123
+ summary: await this.#buildSummary(dayRange(now, input.offsetDays, input.daySpan), now),
123
124
  });
125
+ }
124
126
  case 'archives': {
125
127
  const beforeArchiveId = input.beforeArchiveId;
126
128
  const page = await this.#store.listArchivePage(beforeArchiveId, input.limit);
@@ -192,13 +194,7 @@ export class HostDailyReviewCoordinator {
192
194
  return mutateFailure('persistence_failed', 'Daily Review mutation failed');
193
195
  }
194
196
  }
195
- async #buildSummary(offsetDays, daySpan) {
196
- const offset = Math.trunc(offsetDays);
197
- const span = Math.max(1, Math.min(30, Math.trunc(daySpan)));
198
- const now = this.#now();
199
- const endDay = offset === 0 ? localDayBoundsForInstant(now) : localDayBoundsAt(now, offset);
200
- const startDay = localDayBoundsAt(endDay.fromMs, -(span - 1));
201
- const range = { fromMs: startDay.fromMs, toMs: endDay.toMs };
197
+ async #buildSummary(range, now) {
202
198
  const query = dailyUsageQuery(range);
203
199
  const canonical = await readCompleteCanonicalUsage(this.#usage, query, now);
204
200
  const [usageSummary, toolBuckets, modelBuckets, sessions] = await Promise.all([
@@ -216,22 +212,36 @@ export class HostDailyReviewCoordinator {
216
212
  });
217
213
  }
218
214
  async #run(input) {
219
- const summary = await this.#buildSummary(input.offsetDays, input.range);
220
- const archiveId = dailyReviewArchiveId(summary.day, input.range);
221
- const existing = await this.#store.getArchive(archiveId);
222
- if (existing && !input.replaceExisting)
223
- return existing;
224
- const config = await this.#store.readConfig();
225
- const modelKey = input.modelKeyOverride.trim() || config.config.modelKey;
215
+ const now = this.#now();
216
+ const day = dayRange(now, input.offsetDays, input.range);
217
+ const archiveId = dailyReviewArchiveId(day, input.range);
218
+ const modelKeyOverride = input.modelKeyOverride.trim();
219
+ // Claim the archive before the first await. Two Clients asking for the
220
+ // same archive at once share one generation; a claim taken only after the
221
+ // reads let the second request slip past a first that had already
222
+ // published, and each Client then saw its own archive. Requests match on
223
+ // the override they asked for, not the resolved model key: resolving it
224
+ // needs the config read, which would put the claim back after an await.
226
225
  const inFlight = this.#inFlight.get(archiveId);
227
226
  if (inFlight) {
228
- if (inFlight.modelKey === modelKey && inFlight.trigger === input.trigger) {
229
- return inFlight.promise;
227
+ if (inFlight.modelKeyOverride !== modelKeyOverride || inFlight.trigger !== input.trigger) {
228
+ throw new DailyReviewRunConflictError(archiveId);
230
229
  }
231
- throw new DailyReviewRunConflictError(archiveId);
230
+ if (!input.replaceExisting || inFlight.replaceExisting)
231
+ return inFlight.promise;
232
+ // A non-replacing leader may hand back an archive it merely found. A
233
+ // replace must not inherit that, so it waits its turn and claims for
234
+ // itself.
235
+ await inFlight.promise.catch(() => undefined);
236
+ return this.#run(input);
232
237
  }
233
- const pending = this.#generateArchive(archiveId, summary, modelKey, input);
234
- const entry = { modelKey, trigger: input.trigger, promise: pending };
238
+ const pending = this.#generateArchive(archiveId, day, now, modelKeyOverride, input);
239
+ const entry = {
240
+ modelKeyOverride,
241
+ trigger: input.trigger,
242
+ replaceExisting: input.replaceExisting,
243
+ promise: pending,
244
+ };
235
245
  this.#inFlight.set(archiveId, entry);
236
246
  try {
237
247
  return await pending;
@@ -241,7 +251,13 @@ export class HostDailyReviewCoordinator {
241
251
  this.#inFlight.delete(archiveId);
242
252
  }
243
253
  }
244
- async #generateArchive(archiveId, summary, modelKey, input) {
254
+ async #generateArchive(archiveId, day, now, modelKeyOverride, input) {
255
+ const summary = await this.#buildSummary(day, now);
256
+ const existing = await this.#store.getArchive(archiveId);
257
+ if (existing && !input.replaceExisting)
258
+ return existing;
259
+ const config = await this.#store.readConfig();
260
+ const modelKey = modelKeyOverride || config.config.modelKey;
245
261
  const base = {
246
262
  id: archiveId,
247
263
  day: summary.day,
@@ -372,6 +388,13 @@ export class HostDailyReviewCoordinator {
372
388
  this.#requestDrain();
373
389
  }
374
390
  }
391
+ function dayRange(nowMs, offsetDays, daySpan) {
392
+ const offset = Math.trunc(offsetDays);
393
+ const span = Math.max(1, Math.min(30, Math.trunc(daySpan)));
394
+ const endDay = offset === 0 ? localDayBoundsForInstant(nowMs) : localDayBoundsAt(nowMs, offset);
395
+ const startDay = localDayBoundsAt(endDay.fromMs, -(span - 1));
396
+ return { fromMs: startDay.fromMs, toMs: endDay.toMs };
397
+ }
375
398
  function scheduledTimeHasPassed(nowMs, executeTime) {
376
399
  const now = new Date(nowMs);
377
400
  const [hours, minutes] = executeTime.split(':').map(Number);