maka-agent 0.2.0-dev.14.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
@@ -118,6 +118,16 @@ export function questionCanonicalOutcome(answer, committedAt) {
118
118
  export function clientCapabilityCanonicalOutcome(answer, committedAt) {
119
119
  return { kind: 'client_capability_decision', decision: answer.decision, committedAt };
120
120
  }
121
+ export function formCanonicalOutcome(answer, committedAt) {
122
+ return answer.action === 'accept'
123
+ ? {
124
+ kind: 'form_answer',
125
+ action: 'accept',
126
+ values: structuredClone(answer.values),
127
+ committedAt,
128
+ }
129
+ : { kind: 'form_answer', action: answer.action, committedAt };
130
+ }
121
131
  export function runtimeQuestionOutcome(outcome) {
122
132
  if (outcome.kind === 'closure') {
123
133
  if (outcome.reason === 'timed_out') {
@@ -126,10 +136,27 @@ export function runtimeQuestionOutcome(outcome) {
126
136
  return { kind: 'closure', reason: outcome.reason };
127
137
  }
128
138
  if (outcome.kind !== 'question_answer') {
129
- throw new RuntimeInteractionInvariantError('Question Interaction resolved with a permission answer');
139
+ throw new RuntimeInteractionInvariantError('Question Interaction resolved with another answer');
130
140
  }
131
141
  return { kind: 'question_answer', answer: { answers: [...outcome.answers] } };
132
142
  }
143
+ export function runtimeFormOutcome(outcome) {
144
+ if (outcome.kind === 'closure') {
145
+ if (outcome.reason === 'timed_out') {
146
+ throw new RuntimeInteractionInvariantError('Form Interaction resolved with a timeout');
147
+ }
148
+ return { kind: 'closure', reason: outcome.reason };
149
+ }
150
+ if (outcome.kind !== 'form_answer') {
151
+ throw new RuntimeInteractionInvariantError('Form Interaction resolved with another answer');
152
+ }
153
+ return {
154
+ kind: 'form_answer',
155
+ answer: outcome.action === 'accept'
156
+ ? { action: 'accept', values: structuredClone(outcome.values) }
157
+ : { action: outcome.action },
158
+ };
159
+ }
133
160
  export function answerOutcome(record, candidate) {
134
161
  const snapshot = projectInteractionRecord(record);
135
162
  if (snapshot.status === 'closed') {
@@ -156,6 +183,8 @@ function canonicalOutcomeForHistoricalAnswer(answer, committedAt) {
156
183
  if (answer.kind === 'question') {
157
184
  return questionCanonicalOutcome(answer, committedAt);
158
185
  }
186
+ if (answer.kind === 'form')
187
+ return formCanonicalOutcome(answer, committedAt);
159
188
  if (answer.kind === 'sandbox_boundary') {
160
189
  throw new RuntimeInteractionInvariantError('Sandbox boundary answers require their canonical boundary settlement');
161
190
  }
@@ -52,10 +52,8 @@ export async function startRuntimeHostAuthenticatedListenerSet(input, options) {
52
52
  export function createRuntimeHostListenerSet(local, additional = []) {
53
53
  const listeners = Object.freeze([local, ...additional]);
54
54
  const peerListeners = Object.freeze(additional.filter(isRuntimeHostPeerListener).map((listener) => Object.freeze({
55
- peerId: listener.peerId,
56
- listenAddresses: Object.freeze([...listener.listenAddresses]),
57
- get coordinationRelays() {
58
- return Object.freeze([...listener.coordinationRelays]);
55
+ get reachability() {
56
+ return listener.reachability;
59
57
  },
60
58
  })));
61
59
  return {
@@ -134,10 +134,21 @@ export class HostMessageCoordinator {
134
134
  * Cancels exactly one durable pending Message, or returns the Turn that has
135
135
  * already consumed it. This is the target Session's ordinary Message
136
136
  * authority; WorkHub never edits the queue or admission tables directly.
137
+ *
138
+ * The claim identity is required: the cancellation tombstone it writes is the
139
+ * only proof that distinguishes this caller's own cancellation from one that
140
+ * had already happened, which is what makes a crash between cancelling and
141
+ * recording the outcome recoverable.
137
142
  */
138
- cancelMessageIfPending(sessionId, messageId) {
143
+ cancelMessageIfPending(sessionId, messageId, cancellationClaimId) {
139
144
  return this.#sessionAdmission.run(sessionId, async () => {
140
145
  const disposition = await this.#resolveMessageExecution(sessionId, messageId);
146
+ if (disposition.kind === 'cancelled') {
147
+ const outcome = await this.#admissions.claimMessageAdmissionCancellation(sessionId, messageId, cancellationClaimId);
148
+ return outcome === 'same_claim'
149
+ ? { kind: 'cancelled_pending' }
150
+ : { kind: 'cancelled' };
151
+ }
141
152
  if (disposition.kind !== 'pending')
142
153
  return disposition;
143
154
  const state = this.#sessions.get(sessionId);
@@ -150,7 +161,7 @@ export class HostMessageCoordinator {
150
161
  state.transition.entries.some((entry) => entry.messageId === messageId)) {
151
162
  return { kind: 'recovering' };
152
163
  }
153
- await this.#admissions.cancelMessageAdmissions(sessionId, [messageId]);
164
+ const claimOutcome = await this.#admissions.claimMessageAdmissionCancellation(sessionId, messageId, cancellationClaimId);
154
165
  if (state && steeringIndex >= 0) {
155
166
  const [entry] = state.steering.splice(steeringIndex, 1);
156
167
  if (entry)
@@ -168,7 +179,9 @@ export class HostMessageCoordinator {
168
179
  else {
169
180
  this.#onProjectionChanged(sessionId);
170
181
  }
171
- return { kind: 'cancelled' };
182
+ return claimOutcome === 'already_cancelled'
183
+ ? { kind: 'cancelled' }
184
+ : { kind: 'cancelled_pending' };
172
185
  });
173
186
  }
174
187
  readMessageExecutionDisposition(sessionId, messageId) {
@@ -20,6 +20,7 @@ import { OAuthTokenEndpointError } from '@maka/runtime/oauth-login';
20
20
  import { createProxiedFetchTransport } from '@maka/runtime/network/scoped-fetch-transport';
21
21
  import { exchangeCodexDeviceAuthorizationCode, pollCodexDeviceAuthorization, startCodexDeviceAuthorization, } from '@maka/runtime/codex-oauth-enrollment';
22
22
  import { OAuthDeviceAuthorizationExpiredError } from '@maka/runtime/oauth-provider-contracts';
23
+ import { GitHubCopilotEntitlementError, GitHubCopilotEntitlementUnavailableError, pollGitHubCopilotDeviceAuthorization, startGitHubCopilotDeviceAuthorization, verifyGitHubCopilotModelEntitlement, } from '@maka/runtime/github-copilot-oauth-enrollment';
23
24
  import { pollXaiDeviceAuthorization, startXaiDeviceAuthorization, } from '@maka/runtime/xai-oauth-enrollment';
24
25
  import { serializeOAuthSubscriptionTokens, } from '@maka/runtime/subscription-credentials';
25
26
  import { RuntimePolicyStoreError, } from '@maka/storage/runtime-policy-stores';
@@ -42,6 +43,7 @@ export class HostOAuthCoordinator {
42
43
  'oauth.login.start': (input, context) => this.#start(input, context.connectionId),
43
44
  'oauth.login.query': (input) => this.#query(input.attemptId),
44
45
  'oauth.login.cancel': (input) => this.#cancel(input.attemptId),
46
+ 'oauth.enrollment.query': (input) => this.#enrollment(input.provider),
45
47
  };
46
48
  #runtimePolicy;
47
49
  #oauthCredentials;
@@ -54,6 +56,9 @@ export class HostOAuthCoordinator {
54
56
  #now;
55
57
  #startXaiAuthorization;
56
58
  #pollXaiAuthorization;
59
+ #startGitHubCopilotAuthorization;
60
+ #pollGitHubCopilotAuthorization;
61
+ #verifyGitHubCopilotEntitlement;
57
62
  #startCodexAuthorization;
58
63
  #pollCodexAuthorization;
59
64
  #exchangeCodexCode;
@@ -80,6 +85,12 @@ export class HostOAuthCoordinator {
80
85
  this.#now = input.now ?? Date.now;
81
86
  this.#startXaiAuthorization = input.startXaiAuthorization ?? startXaiDeviceAuthorization;
82
87
  this.#pollXaiAuthorization = input.pollXaiAuthorization ?? pollXaiDeviceAuthorization;
88
+ this.#startGitHubCopilotAuthorization =
89
+ input.startGitHubCopilotAuthorization ?? startGitHubCopilotDeviceAuthorization;
90
+ this.#pollGitHubCopilotAuthorization =
91
+ input.pollGitHubCopilotAuthorization ?? pollGitHubCopilotDeviceAuthorization;
92
+ this.#verifyGitHubCopilotEntitlement =
93
+ input.verifyGitHubCopilotEntitlement ?? verifyGitHubCopilotModelEntitlement;
83
94
  this.#startCodexAuthorization = input.startCodexAuthorization ?? startCodexDeviceAuthorization;
84
95
  this.#pollCodexAuthorization = input.pollCodexAuthorization ?? pollCodexDeviceAuthorization;
85
96
  this.#exchangeCodexCode = input.exchangeCodexCode ?? exchangeCodexDeviceAuthorizationCode;
@@ -244,6 +255,15 @@ export class HostOAuthCoordinator {
244
255
  }
245
256
  return { ok: true, result: projection(attempt) };
246
257
  }
258
+ // The Host owns the enrollment gate: whether a provider may begin an
259
+ // interactive login is this Host's answer, and only the Host has it. Surfaces
260
+ // read it to avoid presenting a primary action that a default install refuses.
261
+ #enrollment(provider) {
262
+ return Promise.resolve({
263
+ ok: true,
264
+ result: { provider, enabled: this.#isProviderEnabled(provider) },
265
+ });
266
+ }
247
267
  #requestCancellation(attempt, reason) {
248
268
  attempt.cancelRequested = true;
249
269
  if (attempt.cancellationDeferred)
@@ -255,9 +275,8 @@ export class HostOAuthCoordinator {
255
275
  let transport;
256
276
  try {
257
277
  transport = createProxiedFetchTransport(toRuntimePolicyProxy(attempt.ticket.networkProxy, attempt.ticket.secretMaterial.networkProxy?.secret));
258
- // Switched rather than defaulted: with the retired provider gone the
259
- // union is two wide, and a ternary would route any future third member
260
- // into the Codex device flow without a compiler error.
278
+ // Switched rather than defaulted: routing any future provider into an
279
+ // unrelated device flow must be a compiler error, not a silent default.
261
280
  const tokens = await this.#runProviderLogin(attempt, transport.fetch);
262
281
  attempt.abort.signal.throwIfAborted();
263
282
  attempt.cancellationDeferred = true;
@@ -335,8 +354,43 @@ export class HostOAuthCoordinator {
335
354
  return this.#runXaiLogin(attempt, fetchFn);
336
355
  case 'openai-codex':
337
356
  return this.#runCodexDeviceLogin(attempt, fetchFn);
357
+ case 'github-copilot':
358
+ return this.#runGitHubCopilotLogin(attempt, fetchFn);
338
359
  }
339
360
  }
361
+ async #runGitHubCopilotLogin(attempt, fetchFn) {
362
+ const authorization = await this.#startGitHubCopilotAuthorization({
363
+ fetchFn,
364
+ signal: attempt.abort.signal,
365
+ now: this.#now,
366
+ });
367
+ await this.#present(attempt, {
368
+ method: 'open_external',
369
+ url: authorization.verificationUrl,
370
+ stateHint: authorization.userCode,
371
+ });
372
+ attempt.phase = 'exchanging';
373
+ const tokens = await this.#pollGitHubCopilotAuthorization({
374
+ authorization,
375
+ fetchFn,
376
+ signal: attempt.abort.signal,
377
+ now: this.#now,
378
+ onPollAdmission: () => {
379
+ attempt.cancellationDeferred = true;
380
+ },
381
+ onPollRetry: () => {
382
+ attempt.cancellationDeferred = false;
383
+ if (attempt.cancelRequested) {
384
+ this.#requestCancellation(attempt, new DOMException('OAuth login cancelled', 'AbortError'));
385
+ }
386
+ },
387
+ });
388
+ // A GitHub account is not a Copilot subscription. Adopt the account only
389
+ // once the provider says it can reach a model, so the commit below never
390
+ // stores a credential the connection cannot use.
391
+ await this.#verifyGitHubCopilotEntitlement({ tokens, fetchFn });
392
+ return tokens;
393
+ }
340
394
  async #runXaiLogin(attempt, fetchFn) {
341
395
  const authorization = await this.#startXaiAuthorization({
342
396
  fetchFn,
@@ -462,6 +516,15 @@ function loginFailureCode(error) {
462
516
  return error.code;
463
517
  if (error instanceof RuntimePolicyStoreError)
464
518
  return 'persistence_failed';
519
+ // The account authorized the grant and the provider then refused it: the
520
+ // login worked, the subscription behind it did not.
521
+ if (error instanceof GitHubCopilotEntitlementError)
522
+ return 'provider_rejected';
523
+ // The provider never answered the entitlement question. Nothing is known
524
+ // about the subscription, so this is a login that did not complete — the
525
+ // user retries, they do not go looking for a plan they already have.
526
+ if (error instanceof GitHubCopilotEntitlementUnavailableError)
527
+ return 'authorization_failed';
465
528
  // A local device window that elapsed without approval is a timeout, not
466
529
  // a provider rejection of the account.
467
530
  if (error instanceof OAuthDeviceAuthorizationExpiredError)
@@ -257,10 +257,23 @@ export function createHostOAuthModelFetch(input) {
257
257
  sessionId: input.sessionId,
258
258
  modelId: input.modelId,
259
259
  fetchFn: authenticatedFetch,
260
- ...(input.binding.forceRefresh &&
261
- (input.binding.providerType === 'openai-codex' || input.binding.providerType === 'xai-oauth')
260
+ ...(input.binding.forceRefresh
262
261
  ? {
263
- refreshOAuthAccessToken: async () => (tokens = await input.binding.forceRefresh()).access_token,
262
+ refreshOAuthAccessToken: async (signal) => {
263
+ const rejected = tokens.access_token;
264
+ const refreshing = input.binding.forceRefresh();
265
+ // The refresh is left to settle on its own: it may already have
266
+ // spent the grant, and a CAS-persisted newer generation is worth
267
+ // keeping even though this request no longer wants it. What the
268
+ // caller must not do is wait out its timeout after giving up.
269
+ observeSettled(refreshing);
270
+ tokens = await waitForCaller(refreshing, signal);
271
+ // A record with no refresh grant behind it (a GitHub account
272
+ // token GitHub declared no lifetime for) resolves to the token
273
+ // the provider just rejected. Replaying it would spend a second
274
+ // request to be told the same thing.
275
+ return tokens.access_token === rejected ? null : tokens.access_token;
276
+ },
264
277
  }
265
278
  : {}),
266
279
  });
@@ -270,6 +283,10 @@ export function createHostOAuthModelFetch(input) {
270
283
  function effectiveRequestSignal(url, init) {
271
284
  return init?.signal !== undefined ? init.signal : url instanceof Request ? url.signal : undefined;
272
285
  }
286
+ /** Keeps a promise the caller stopped awaiting from surfacing as unhandled. */
287
+ function observeSettled(pending) {
288
+ void pending.catch(() => undefined);
289
+ }
273
290
  async function waitForCaller(pending, signal) {
274
291
  if (!signal)
275
292
  return pending;
@@ -18,27 +18,19 @@
18
18
  */
19
19
  import { FramedByteStreamTransport } from '../transport/framed-byte-stream-transport.js';
20
20
  import { readRuntimeHostPeerAuthentication, RUNTIME_HOST_PEER_AUTHENTICATION_TIMEOUT_MS, RuntimeHostPeerByteStream, writeRuntimeHostPeerAuthenticationResult, } from '../transport/peer-native.js';
21
- import { createRuntimeHostPeerClient } from '../client/peer-client.js';
22
21
  const MAX_PENDING_AUTHENTICATIONS = 16;
23
22
  const MAX_ACTIVE_STREAMS = 64;
24
23
  const MAX_ACTIVE_STREAMS_PER_PEER = 4;
25
24
  export function startRuntimeHostPeerListener(options) {
26
- if ('client' in options) {
27
- return createRuntimeHostPeerListener(options.client, options.accessAuthority, options.accept, false);
28
- }
29
- const client = createRuntimeHostPeerClient(options);
30
- return createRuntimeHostPeerListener(client, options.accessAuthority, options.accept, true);
25
+ return createRuntimeHostPeerListener(options.client, options.reachability, options.accessAuthority, options.accept);
31
26
  }
32
- export function createRuntimeHostPeerListener(client, accessAuthority, accept, ownsClient = false) {
33
- return new RuntimeHostPeerListener(client, accessAuthority, accept, ownsClient);
27
+ export function createRuntimeHostPeerListener(client, reachability, accessAuthority, accept) {
28
+ return new RuntimeHostPeerListener(client, reachability, accessAuthority, accept);
34
29
  }
35
30
  class RuntimeHostPeerListener {
36
31
  kind = 'libp2p_direct';
37
32
  endpoint;
38
- peerId;
39
- listenAddresses;
40
- #client;
41
- #ownsClient;
33
+ #reachability;
42
34
  #accessAuthority;
43
35
  #accept;
44
36
  #transports = new Set();
@@ -50,13 +42,10 @@ class RuntimeHostPeerListener {
50
42
  #admitting = true;
51
43
  #closeAdmissionTask;
52
44
  #cleanupTask;
53
- constructor(client, accessAuthority, accept, ownsClient) {
45
+ constructor(client, reachability, accessAuthority, accept) {
54
46
  const identity = client.identity();
55
47
  this.endpoint = identity.peerId;
56
- this.peerId = identity.peerId;
57
- this.listenAddresses = Object.freeze([...identity.listenAddresses]);
58
- this.#client = client;
59
- this.#ownsClient = ownsClient;
48
+ this.#reachability = reachability;
60
49
  this.#accessAuthority = accessAuthority;
61
50
  this.#accept = accept;
62
51
  const captureFailure = (error) => {
@@ -66,8 +55,8 @@ class RuntimeHostPeerListener {
66
55
  .serveApplication((stream) => this.#acceptStream(stream), this.#serveLifetime.signal)
67
56
  .catch(captureFailure);
68
57
  }
69
- get coordinationRelays() {
70
- return this.#client.identity().coordinationRelays;
58
+ get reachability() {
59
+ return this.#reachability.current();
71
60
  }
72
61
  closeAdmission() {
73
62
  this.#closeAdmissionTask ??= (async () => {
@@ -85,8 +74,6 @@ class RuntimeHostPeerListener {
85
74
  transport.abort();
86
75
  this.#serveLifetime.abort();
87
76
  await this.#serving;
88
- if (this.#ownsClient)
89
- await this.#client.close();
90
77
  if (this.#acceptFailure)
91
78
  throw this.#acceptFailure;
92
79
  })();
@@ -151,7 +151,7 @@ export function projectPeerMeshStatus(status) {
151
151
  meshId: status.roster.roster.meshId,
152
152
  ...(status.roster.roster.displayName ? { displayName: status.roster.roster.displayName } : {}),
153
153
  role: status.role,
154
- authorityPeerId: status.authority.peerId,
154
+ authorityPeerId: status.authorityPeerId,
155
155
  revision: status.roster.roster.revision,
156
156
  closed: status.roster.roster.closed,
157
157
  members: Object.freeze(status.memberRoutes.map((member) => Object.freeze({ ...member }))),
@@ -25,7 +25,7 @@ import { decodeSkillInvocationResult, } from '@maka/core/skill-invocation';
25
25
  import { agentGraphIdForRootSession } from '@maka/runtime/stream-graph-coordinator';
26
26
  import { RuntimeHostedRootConflictError, RuntimeHostedRootUnavailableError, RuntimeMessageAuthorityInvariantError, } from '@maka/runtime/message-authority';
27
27
  import { RuntimeInteractionAdmissionRejectedError, RuntimeInteractionFailStopError, RuntimeInteractionInvariantError, } from '@maka/runtime/interaction-authority';
28
- import { RuntimeRegenerateTurnError } from '@maka/runtime/session-manager';
28
+ import { normalizeStopSessionSource, RuntimeRegenerateTurnError, } from '@maka/runtime/session-manager';
29
29
  import { RuntimeOwnerCleanupError } from '@maka/runtime/runtime-kernel';
30
30
  import { parseSkillInvocationTokens, } from '@maka/runtime/skill-invocation';
31
31
  import { skillInvocationInlineReferences } from '@maka/runtime/skill-invocation-receipt';
@@ -501,6 +501,7 @@ export class RootTurnCoordinator {
501
501
  async requestStop(input) {
502
502
  await this.stopRoot(input.execution, {
503
503
  ...(input.source ? { source: input.source } : {}),
504
+ ...(input.workHubActionId !== undefined ? { workHubActionId: input.workHubActionId } : {}),
504
505
  ...(input.mode ? { mode: input.mode } : {}),
505
506
  });
506
507
  return await this.read(input.execution);
@@ -515,6 +516,7 @@ export class RootTurnCoordinator {
515
516
  return (this.#executions.get(sessionId)?.done ?? this.#admissions.get(sessionId)?.whenIdle.promise);
516
517
  }
517
518
  stopRoot(identity, input = {}) {
519
+ normalizeStopSessionSource(input.source, input.workHubActionId);
518
520
  return this.runCommand(async () => {
519
521
  const declared = await this.sessionAdmission.run(identity.sessionId, (lease) => this.declareStopFence(identity, () => this.messages.commitStopFence(identity), lease, input));
520
522
  await declared?.deliverStop();
@@ -532,6 +534,7 @@ export class RootTurnCoordinator {
532
534
  });
533
535
  }
534
536
  stopSession(sessionId, input = {}) {
537
+ normalizeStopSessionSource(input.source, input.workHubActionId);
535
538
  return this.runCommand(async () => {
536
539
  const declared = await this.sessionAdmission.run(sessionId, (lease) => {
537
540
  const active = this.#executions.get(sessionId);
@@ -1633,7 +1636,7 @@ export class RootTurnCoordinator {
1633
1636
  else if (isInteractionAnswerAck(event)) {
1634
1637
  await this.continuity.refreshCanonical(input.sessionId);
1635
1638
  }
1636
- else if (event.type === 'user_question_request') {
1639
+ else if (event.type === 'user_question_request' || event.type === 'form_request') {
1637
1640
  this.continuity.enqueueCanonicalRefresh(input.sessionId);
1638
1641
  }
1639
1642
  }
@@ -2192,7 +2195,7 @@ function isRuntimeSessionForwardedEvent(event) {
2192
2195
  event.type === 'provider_retry');
2193
2196
  }
2194
2197
  function isInteractionAnswerAck(event) {
2195
- return event.type === 'user_question_answer_ack';
2198
+ return event.type === 'user_question_answer_ack' || event.type === 'form_answer_ack';
2196
2199
  }
2197
2200
  function completedStart(outcome) {
2198
2201
  return { kind: 'complete', outcome };
@@ -20,7 +20,9 @@ import { randomUUID } from 'node:crypto';
20
20
  import { botDisplayLabel } from '@maka/core/bot-events';
21
21
  import { isBotDeliveryProvider } from '@maka/core/bot-chat-settings';
22
22
  import { messageContentsEqual } from '@maka/core/events';
23
+ import { authorizeConnectionModel } from '@maka/core/llm-connections';
23
24
  import { buildAgentScheduledTaskCreatePayload, buildScheduledTaskTool, SCHEDULED_TASK_NATIVE_EFFECT_SERVICE_ID, SCHEDULED_TASK_NATIVE_EFFECT_SERVICE_VERSION, } from '@maka/runtime/scheduled-task-tools';
25
+ import { stableHash } from '@maka/runtime/request-shape';
24
26
  import { authenticateInteractiveScheduledTaskStoreWriter, ScheduledTaskStoreError, } from '@maka/storage/scheduled-task-store';
25
27
  import { isSessionNotFoundError, } from '@maka/storage/execution-stores';
26
28
  import { SCHEDULED_TASK_CATALOG_MAX_ITEMS, SCHEDULED_TASK_PAGE_MAX_ITEMS, SCHEDULED_TASK_RESULT_MAX_BYTES, } from '../protocol/index.js';
@@ -30,6 +32,17 @@ const SCHEDULED_AGENT_RUN_IDENTITY_REQUIRED = 'ScheduledTask Agent runs require
30
32
  export class HostScheduledTaskSessionBusyError extends Error {
31
33
  name = 'HostScheduledTaskSessionBusyError';
32
34
  }
35
+ /** Stable Agent ScheduledTask target identity used by root-admission retries. */
36
+ export function scheduledTaskExecutionFingerprint(execution) {
37
+ if (!execution.llmConnectionId)
38
+ return undefined;
39
+ return stableHash([
40
+ 'scheduled-task-agent-run.v1',
41
+ execution.llmConnectionId,
42
+ execution.llmConnectionSlug,
43
+ execution.model,
44
+ ]);
45
+ }
33
46
  /** Host-owned ScheduledTask catalog, scheduler, fire admission, and tool authority. */
34
47
  export class HostScheduledTaskCoordinator {
35
48
  handlers = {
@@ -96,6 +109,9 @@ export class HostScheduledTaskCoordinator {
96
109
  candidate.execution?.sessionId === admission.sessionId &&
97
110
  candidate.execution.turnId === admission.turnId);
98
111
  const execution = claim?.execution;
112
+ const fingerprintMatches = claim?.task.effect.kind !== 'agent_run' ||
113
+ admission.execution.executionFingerprint ===
114
+ scheduledTaskExecutionFingerprint(claim.task.effect.execution);
99
115
  if (!claim && state === 'run_recorded')
100
116
  return;
101
117
  if (!claim ||
@@ -104,6 +120,7 @@ export class HostScheduledTaskCoordinator {
104
120
  execution.turnId !== admission.turnId ||
105
121
  execution.runId !== admission.runId ||
106
122
  execution.userMessageId !== admission.userMessageId ||
123
+ !fingerprintMatches ||
107
124
  admission.normalizedInput === null ||
108
125
  !messageContentsEqual({ text: claim.task.intent.body }, admission.normalizedInput)) {
109
126
  throw new Error(`ScheduledTask admission ${admission.turnId} has no matching pending fire`);
@@ -435,10 +452,10 @@ export class HostScheduledTaskCoordinator {
435
452
  ? '本地提醒已触发。'
436
453
  : `已投递到 ${botDisplayLabel(task.effect.platform)}。`, 'fired');
437
454
  }
438
- // Persisted agent-run templates currently identify their model connection
439
- // by reusable slug only. Do not resolve that slug to a potentially
440
- // different Connection entity. #3927 will make the exact ID durable.
441
- if (task.effect.kind === 'agent_run') {
455
+ // Legacy persisted Agent-run templates may still identify their model
456
+ // connection by reusable slug only. Never resolve that slug to a
457
+ // potentially different Connection entity.
458
+ if (task.effect.kind === 'agent_run' && !task.effect.execution.llmConnectionId) {
442
459
  return this.#settleFailure(claim, SCHEDULED_AGENT_RUN_IDENTITY_REQUIRED);
443
460
  }
444
461
  let execution = claim.execution;
@@ -472,20 +489,21 @@ export class HostScheduledTaskCoordinator {
472
489
  await this.#readResumableSession(identity.sessionId);
473
490
  return;
474
491
  }
492
+ const execution = task.effect.execution;
493
+ const connection = await this.#resolveAgentRunConnection(execution);
475
494
  try {
476
- await this.#sessions.readHeaderSnapshot(identity.sessionId);
495
+ const existing = await this.#sessions.readHeaderSnapshot(identity.sessionId);
496
+ if (existing.llmConnectionId !== execution.llmConnectionId ||
497
+ existing.llmConnectionSlug !== execution.llmConnectionSlug ||
498
+ existing.model !== execution.model) {
499
+ throw new Error('ScheduledTask Session model identity changed');
500
+ }
477
501
  return;
478
502
  }
479
503
  catch (error) {
480
504
  if (!isSessionNotFoundError(error) && !isMissingRecord(error))
481
505
  throw error;
482
506
  }
483
- const execution = task.effect.execution;
484
- const catalog = await this.#runtimePolicy.connectionCatalog.getSnapshot();
485
- const connection = catalog.connections.find((candidate) => candidate.slug === execution.llmConnectionSlug);
486
- if (!connection) {
487
- throw new Error('ScheduledTask model connection does not exist');
488
- }
489
507
  await this.#createSession({
490
508
  sessionId: identity.sessionId,
491
509
  workspace: execution.projectId != null && execution.projectId !== ''
@@ -505,11 +523,49 @@ export class HostScheduledTaskCoordinator {
505
523
  orchestrationMode: execution.orchestrationMode,
506
524
  });
507
525
  }
526
+ async #resolveAgentRunConnection(execution) {
527
+ if (!execution.llmConnectionId) {
528
+ throw new Error(SCHEDULED_AGENT_RUN_IDENTITY_REQUIRED);
529
+ }
530
+ const resolved = await this.#runtimePolicy.operations.resolveExecutionConnection({
531
+ kind: 'bound',
532
+ connectionId: execution.llmConnectionId,
533
+ connectionSlug: execution.llmConnectionSlug,
534
+ });
535
+ if (resolved.kind !== 'ready') {
536
+ throw new Error(resolved.kind === 'identity_mismatch' || resolved.kind === 'not_found'
537
+ ? 'ScheduledTask model connection identity changed'
538
+ : resolved.kind === 'disabled'
539
+ ? 'ScheduledTask model connection is disabled'
540
+ : resolved.kind === 'credential_not_configured'
541
+ ? 'ScheduledTask model connection is not ready'
542
+ : resolved.kind === 'provider_retired'
543
+ ? 'ScheduledTask model connection uses a retired provider'
544
+ : 'ScheduledTask model connection is unavailable');
545
+ }
546
+ if (!authorizeConnectionModel(resolved.connection, execution.model)) {
547
+ throw new Error('ScheduledTask model is no longer enabled');
548
+ }
549
+ return resolved.connection;
550
+ }
508
551
  async #admitAgentRun(task, identity) {
552
+ if (task.effect.kind === 'agent_run') {
553
+ // Re-read the bound Connection immediately before admission. The
554
+ // Session/Connection stores have independent write lanes, so this
555
+ // second check closes the delete-and-recreate-same-slug window between
556
+ // Session creation and AgentRun admission.
557
+ await this.#resolveAgentRunConnection(task.effect.execution);
558
+ }
509
559
  const content = { text: task.intent.body };
510
560
  await this.#root.admit({
511
561
  ...identity,
512
- execution: { kind: 'scheduled_task', scheduledTaskId: task.id },
562
+ execution: {
563
+ kind: 'scheduled_task',
564
+ scheduledTaskId: task.id,
565
+ ...(task.effect.kind === 'agent_run'
566
+ ? { executionFingerprint: scheduledTaskExecutionFingerprint(task.effect.execution) }
567
+ : {}),
568
+ },
513
569
  content,
514
570
  start: ({ runId, userMessageId, onRunStarted }) => {
515
571
  if (runId !== identity.runId || userMessageId !== identity.userMessageId) {
@@ -630,9 +686,13 @@ class ScheduledTaskMutationError extends Error {
630
686
  }
631
687
  }
632
688
  function executionTemplateFromHeader(header) {
689
+ if (!header.llmConnectionId) {
690
+ throw new Error(SCHEDULED_AGENT_RUN_IDENTITY_REQUIRED);
691
+ }
633
692
  return {
634
693
  cwd: header.cwd,
635
694
  ...(header.projectId === undefined ? {} : { projectId: header.projectId }),
695
+ llmConnectionId: header.llmConnectionId,
636
696
  llmConnectionSlug: header.llmConnectionSlug,
637
697
  model: header.model,
638
698
  ...(header.thinkingLevel === undefined ? {} : { thinkingLevel: header.thinkingLevel }),