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
@@ -25,6 +25,20 @@ const AGENT_GRAPH_ORIGIN_SHAPE = defineObjectShape()(['kind', 'graphId', 'wakeId
25
25
  export function decodeTurnOrigin(value) {
26
26
  if (!isRecord(value))
27
27
  return undefined;
28
+ if (value.kind === 'workhub_result') {
29
+ const keys = ['kind', 'eventId', 'actionId', 'delegationId', 'targetSessionId', 'targetTurnId'];
30
+ if (Object.keys(value).length !== keys.length ||
31
+ !keys.every((key) => typeof value[key] === 'string' && value[key].length > 0 && value[key].length <= 256))
32
+ return undefined;
33
+ return {
34
+ kind: 'workhub_result',
35
+ eventId: value.eventId,
36
+ actionId: value.actionId,
37
+ delegationId: value.delegationId,
38
+ targetSessionId: value.targetSessionId,
39
+ targetTurnId: value.targetTurnId,
40
+ };
41
+ }
28
42
  if (hasExactShape(value, SCHEDULED_TASK_ORIGIN_SHAPE) &&
29
43
  value.kind === 'scheduled_task' &&
30
44
  typeof value.scheduledTaskId === 'string') {
@@ -27,6 +27,7 @@ export const MODEL_CALL_KINDS = [
27
27
  'goal_evaluation',
28
28
  'session_title',
29
29
  'session_recap',
30
+ 'prompt_suggestion',
30
31
  'daily_review',
31
32
  'memory_extraction',
32
33
  'workhub_intent',
@@ -6,6 +6,7 @@
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "exports": {
9
+ "./executor-catalog": "./dist/executor-catalog.js",
9
10
  "./executor-id": "./dist/executor-id.js",
10
11
  "./durable-tool-result-projection": "./dist/durable-tool-result-projection.js",
11
12
  "./model-projection-transition": "./dist/model-projection-transition.js",
@@ -29,6 +30,7 @@
29
30
  "./provider-retry-countdown": "./dist/provider-retry-countdown.js",
30
31
  "./interaction": "./dist/interaction.js",
31
32
  "./session": "./dist/session.js",
33
+ "./turn-origin": "./dist/turn-origin.js",
32
34
  "./session-reference": "./dist/session-reference.js",
33
35
  "./session-revisions": "./dist/session-revisions.js",
34
36
  "./collaboration": "./dist/collaboration.js",
@@ -62,6 +62,9 @@ try {
62
62
  ? {
63
63
  connection: {
64
64
  providerType: payload.connection.providerType,
65
+ ...(payload.connection.defaultApiProtocol === undefined
66
+ ? {}
67
+ : { defaultApiProtocol: payload.connection.defaultApiProtocol }),
65
68
  apiKey: process.env[payload.connection.apiKeyEnvironment] ?? '',
66
69
  },
67
70
  }
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { randomUUID } from 'node:crypto';
20
- import { PROVIDER_REGISTRY } from '@maka/core/llm-connections';
20
+ import { isModelApiProtocol, PROVIDER_REGISTRY } from '@maka/core/llm-connections';
21
21
  import { isThinkingLevel } from '@maka/core/model-thinking';
22
22
  import { isSessionToolProfile } from '@maka/core/session';
23
23
  import { decodeHostedExecutionProjection } from '@maka/runtime-host/protocol';
@@ -63,6 +63,9 @@ export function createMakaSubjectAdapter() {
63
63
  ? {
64
64
  connection: {
65
65
  providerType: config.providerType,
66
+ ...(config.defaultApiProtocol === undefined
67
+ ? {}
68
+ : { defaultApiProtocol: config.defaultApiProtocol }),
66
69
  apiKeyEnvironment: config.apiKeyEnvironment,
67
70
  },
68
71
  }
@@ -237,6 +240,7 @@ function decodeConfig(value) {
237
240
  'connectionSlug',
238
241
  'model',
239
242
  ...(Object.hasOwn(value, 'providerType') ? ['providerType', 'apiKeyEnvironment'] : []),
243
+ ...(value.providerType === 'custom' ? ['defaultApiProtocol'] : []),
240
244
  ...(Object.hasOwn(value, 'thinkingLevel') ? ['thinkingLevel'] : []),
241
245
  'permissionMode',
242
246
  'collaborationMode',
@@ -249,6 +253,9 @@ function decodeConfig(value) {
249
253
  !Object.hasOwn(PROVIDER_REGISTRY, String(config.providerType))) {
250
254
  throw new Error('Maka config.providerType is invalid');
251
255
  }
256
+ if (config.providerType === 'custom' && !isModelApiProtocol(config.defaultApiProtocol)) {
257
+ throw new Error('Maka config.defaultApiProtocol is invalid');
258
+ }
252
259
  if (config.thinkingLevel !== undefined && !isThinkingLevel(config.thinkingLevel)) {
253
260
  throw new Error('Maka config.thinkingLevel is invalid');
254
261
  }
@@ -44,7 +44,10 @@ export class McpCredentialCoordinator {
44
44
  *
45
45
  * The optional signal fences an ABANDONED erase: a logout whose round
46
46
  * timed out must not resume later, adopt whatever record a newer login
47
- * just stored as its basis, and tombstone the fresh tokens. */
47
+ * just stored as its basis, and tombstone the fresh tokens.
48
+ *
49
+ * `spare` must be decided here, on the lane's read: checked outside, a
50
+ * login could land between the check and the erase. */
48
51
  async erase(serverId, options = {}) {
49
52
  this.epochs.set(serverId, this.epoch(serverId) + 1);
50
53
  await this.run(serverId, async () => {
@@ -54,6 +57,8 @@ export class McpCredentialCoordinator {
54
57
  // storage read was in flight — committing past it would erase a
55
58
  // record the caller no longer owns.
56
59
  this.assertNotAbandoned(serverId, options.signal);
60
+ if (basis && options.spare?.(basis))
61
+ return;
57
62
  // Absence still gets a tombstone: a cross-process flow that captured
58
63
  // generation 0 on absence must not CAS its credentials back in after
59
64
  // this revocation.
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { randomBytes } from 'node:crypto';
20
- import { auth, Client, extractWWWAuthenticateParams, LATEST_PROTOCOL_VERSION, CLIENT_CAPABILITIES_META_KEY, isInputRequiredResult, SdkErrorCode, SdkHttpError, SSEClientTransport, StreamableHTTPClientTransport, } from '@modelcontextprotocol/client';
20
+ import { auth, validateAuthorizationResponseIssuer, Client, extractWWWAuthenticateParams, LATEST_PROTOCOL_VERSION, CLIENT_CAPABILITIES_META_KEY, isInputRequiredResult, SdkErrorCode, SdkHttpError, SSEClientTransport, StreamableHTTPClientTransport, } from '@modelcontextprotocol/client';
21
21
  import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
22
22
  import { setTimeout as delay } from 'node:timers/promises';
23
23
  import { containsMcpFormState, prepareMcpForm } from './form-elicitation.js';
@@ -34,7 +34,7 @@ import { McpToolCallPreparer } from './tool-output-validation.js';
34
34
  import { mapMcpToolProgress } from './tool-progress.js';
35
35
  import { McpCredentialCoordinator } from './credential-coordinator.js';
36
36
  import { assertTransportSecurity, urlProvenance, } from './transport-security.js';
37
- import { McpAuthRequiredError, McpOAuthProvider, } from './oauth.js';
37
+ import { McpAuthRequiredError, McpOAuthProvider, authorizationCallbackError, mcpOAuthRecordBoundTo, } from './oauth.js';
38
38
  export { formatMcpDiagnosticText } from './diagnostic-text.js';
39
39
  export { McpToolCallError } from './tool-call-error.js';
40
40
  export { createCredentialMcpOAuthStorage, } from './credential-oauth-storage.js';
@@ -259,7 +259,7 @@ export class McpClientManager {
259
259
  : undefined;
260
260
  if (owed) {
261
261
  try {
262
- await this.forgetAuthorization(serverId, owed);
262
+ await this.forgetAuthorization(serverId, owed, { successor: serverConfig });
263
263
  }
264
264
  catch (error) {
265
265
  await this.blockForCredentialCleanup(serverId, current, owed, error);
@@ -1272,7 +1272,6 @@ export class McpClientManager {
1272
1272
  }
1273
1273
  }
1274
1274
  async finishAuthorizationRound(serverId, callback, options = {}) {
1275
- const authorizationCode = callback.code;
1276
1275
  const { config } = this.requireRemoteEntry(serverId);
1277
1276
  // The immediate read doubles as the flow's generation/version pin.
1278
1277
  const storage = this.flowStorage(serverId, options.signal);
@@ -1298,6 +1297,25 @@ export class McpClientManager {
1298
1297
  if (record?.pendingServerUrl !== config.url) {
1299
1298
  throw new Error(`MCP server "${serverId}" changed its URL during authorization`);
1300
1299
  }
1300
+ const metadata = record.discovery?.authorizationServerMetadata;
1301
+ const expectedIssuer = metadata?.issuer ?? record.discovery?.authorizationServerUrl;
1302
+ if (!expectedIssuer)
1303
+ throw new Error('OAuth callback has no recorded issuer');
1304
+ try {
1305
+ validateAuthorizationResponseIssuer({
1306
+ iss: callback.iss,
1307
+ expectedIssuer: String(expectedIssuer),
1308
+ issParameterSupported: metadata?.authorization_response_iss_parameter_supported === true,
1309
+ });
1310
+ }
1311
+ catch {
1312
+ // SDK errors echo the untrusted iss parameter; it must not cross IPC.
1313
+ throw new Error('OAuth callback issuer validation failed');
1314
+ }
1315
+ if ('error' in callback) {
1316
+ throw authorizationCallbackError(callback.error);
1317
+ }
1318
+ const authorizationCode = callback.code;
1301
1319
  const provider = new McpOAuthProvider({
1302
1320
  serverId,
1303
1321
  serverUrl: config.url,
@@ -1432,7 +1450,15 @@ export class McpClientManager {
1432
1450
  return;
1433
1451
  if (config && isMcpStdioConfig(config) && !(await this.coordinator.read(serverId)))
1434
1452
  return;
1435
- await this.coordinator.erase(serverId, options);
1453
+ const { successor, ...eraseOptions } = options;
1454
+ await this.coordinator.erase(serverId, {
1455
+ ...eraseOptions,
1456
+ // Another process may have applied the same change and signed in first.
1457
+ ...(successor &&
1458
+ !isMcpStdioConfig(successor) && {
1459
+ spare: (record) => mcpOAuthRecordBoundTo(record, successor.url, successor.oauth),
1460
+ }),
1461
+ });
1436
1462
  }
1437
1463
  /** Drops stored tokens and registration, returning the server to needs-auth. */
1438
1464
  async clearAuthorization(serverId, options = {}) {
@@ -16,6 +16,25 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { createHash } from 'node:crypto';
20
+ const OAUTH_ERROR_CODES = new Set([
21
+ 'invalid_request',
22
+ 'unauthorized_client',
23
+ 'access_denied',
24
+ 'unsupported_response_type',
25
+ 'invalid_scope',
26
+ 'server_error',
27
+ 'temporarily_unavailable',
28
+ 'invalid_client',
29
+ 'invalid_grant',
30
+ 'unsupported_grant_type',
31
+ 'interaction_required',
32
+ 'login_required',
33
+ 'consent_required',
34
+ ]);
35
+ export function authorizationCallbackError(code) {
36
+ return new Error(`Authorization failed: ${OAUTH_ERROR_CODES.has(code) ? code : 'unknown_error'}`);
37
+ }
19
38
  export function createMemoryMcpOAuthStorage() {
20
39
  const records = new Map();
21
40
  return {
@@ -31,6 +50,16 @@ export function createMemoryMcpOAuthStorage() {
31
50
  },
32
51
  };
33
52
  }
53
+ function mcpOAuthClientConfigHash(config) {
54
+ if (!config?.clientId)
55
+ return undefined;
56
+ return createHash('sha256')
57
+ .update(JSON.stringify([config.issuer, config.clientId, config.clientSecret]))
58
+ .digest('hex');
59
+ }
60
+ export function mcpOAuthRecordBoundTo(record, serverUrl, config) {
61
+ return (record.serverUrl === serverUrl && record.clientConfigHash === mcpOAuthClientConfigHash(config));
62
+ }
34
63
  /** Thrown (via the SDK's UnauthorizedError path) when a background connect
35
64
  * would need the user in a browser. The manager maps it to `needs-auth`. */
36
65
  export class McpAuthRequiredError extends Error {
@@ -64,6 +93,9 @@ export class McpOAuthProvider {
64
93
  if (state)
65
94
  this.state = () => state;
66
95
  }
96
+ get clientConfigHash() {
97
+ return mcpOAuthClientConfigHash(this.options.config);
98
+ }
67
99
  get redirectUrl() {
68
100
  return this.options.interactive?.redirectUrl ?? BACKGROUND_REDIRECT_URL;
69
101
  }
@@ -82,10 +114,17 @@ export class McpOAuthProvider {
82
114
  : {}),
83
115
  };
84
116
  }
85
- async clientInformation() {
117
+ async clientInformation(context) {
86
118
  const configured = this.options.config;
87
119
  if (configured?.clientId) {
120
+ if (!configured.issuer) {
121
+ throw new Error(`MCP server "${this.options.serverId}" requires oauth.issuer for its pre-registered client`);
122
+ }
123
+ if (context && context.issuer !== configured.issuer) {
124
+ throw new Error(`MCP server "${this.options.serverId}" discovered a different OAuth issuer; reconfigure its client credentials`);
125
+ }
88
126
  return {
127
+ issuer: configured.issuer,
89
128
  client_id: configured.clientId,
90
129
  ...(configured.clientSecret ? { client_secret: configured.clientSecret } : {}),
91
130
  };
@@ -106,7 +145,13 @@ export class McpOAuthProvider {
106
145
  });
107
146
  }
108
147
  async tokens() {
109
- return (await this.read()).tokens;
148
+ if (this.options.config?.clientId)
149
+ await this.clientInformation();
150
+ const record = await this.read();
151
+ const tokens = record.tokens;
152
+ if (this.options.config?.issuer && tokens?.issuer !== this.options.config.issuer)
153
+ return undefined;
154
+ return tokens;
110
155
  }
111
156
  async saveTokens(tokens) {
112
157
  await this.mutate((record) => {
@@ -148,9 +193,7 @@ export class McpOAuthProvider {
148
193
  // A dynamically registered client belongs to the authorization server
149
194
  // that issued it. When discovery moves the resource to a DIFFERENT
150
195
  // authorization server, carrying the old registration over would send
151
- // one AS's client credentials (and any secret) to another. Static
152
- // config-supplied clients are unaffected — they never live in the
153
- // record.
196
+ // one AS's client credentials (and any secret) to another.
154
197
  const previousIssuer = record.discovery?.authorizationServerUrl;
155
198
  const nextIssuer = state.authorizationServerUrl;
156
199
  if (previousIssuer && nextIssuer && `${previousIssuer}` !== `${nextIssuer}`) {
@@ -217,7 +260,8 @@ export class McpOAuthProvider {
217
260
  record.pendingRedirectUrl ||
218
261
  record.pendingServerUrl ||
219
262
  record.pendingState;
220
- return Boolean(boundable) && record.serverUrl !== this.options.serverUrl;
263
+ return (Boolean(boundable) &&
264
+ !mcpOAuthRecordBoundTo(record, this.options.serverUrl, this.options.config));
221
265
  }
222
266
  /** The same fail-closed binding rule as read(), applied to a mutation
223
267
  * basis: a record bound elsewhere contributes NOTHING to the new write —
@@ -239,6 +283,10 @@ export class McpOAuthProvider {
239
283
  const stamp = (record) => {
240
284
  apply(record);
241
285
  record.serverUrl = this.options.serverUrl;
286
+ if (this.clientConfigHash)
287
+ record.clientConfigHash = this.clientConfigHash;
288
+ else
289
+ delete record.clientConfigHash;
242
290
  return record;
243
291
  };
244
292
  // The coordinator-provided storage view makes read-apply-write one
@@ -38,7 +38,7 @@ export async function inspectAgentRunReadModel(runStore, runtimeEventStore, opti
38
38
  diagnostics.push(inspectDiagnostic(invocation, 'runtime_terminal_missing', 'runtime ledger has no complete terminal RuntimeEvent fact'));
39
39
  }
40
40
  }
41
- const projection = runtimeEvents.length > 0
41
+ const projection = runtimeEvents.length > 0 && options.includeProjection !== false
42
42
  ? projectRuntimeEventsToStoredMessages(runtimeEvents, { invocations: [invocation] })
43
43
  : undefined;
44
44
  if (projection) {
@@ -91,17 +91,7 @@ export class AiSdkBackend {
91
91
  */
92
92
  activeTurns = new Set();
93
93
  compaction;
94
- /**
95
- * The provider has been reported dropping context, for this backend.
96
- *
97
- * Not per send: the condition persists once a provider starts truncating, so
98
- * a note on every later turn would repeat one fact the user has already been
99
- * told. The scope is this backend's lifetime rather than the Session's, so a
100
- * backend that is disposed and rebuilt may say it once more.
101
- */
102
- turnSessionState = {
103
- contextProviderDroppingReported: false,
104
- };
94
+ turnSessionState = {};
105
95
  constructor(input) {
106
96
  this.input = input;
107
97
  this.sessionId = input.sessionId;
@@ -536,7 +536,6 @@ export class AiSdkCompaction {
536
536
  if (persisted) {
537
537
  state.baselineTokens = persisted.inputTokens + (persisted.outputTokens ?? 0);
538
538
  state.lastAcceptedTotalTokens = state.baselineTokens;
539
- state.priorAcceptedInputTokens = persisted.inputTokens;
540
539
  }
541
540
  if (persisted)
542
541
  state.replyReserveTokens = replyReserveTokens(persisted.outputTokens);
@@ -1034,9 +1033,8 @@ export class MidTurnCapacityCompactState {
1034
1033
  }
1035
1034
  /**
1036
1035
  * What has reshaped the request since the last one a provider accepted. The
1037
- * turn clears it at that acceptance, every shaper records itself here, and
1038
- * every consumer reads it here — an empty set is the only proof that the next
1039
- * request is a pure append of its predecessor.
1036
+ * turn clears it at that acceptance; overflow recovery reads it so a request
1037
+ * that was already folded or stripped of images is not reshaped again.
1040
1038
  */
1041
1039
  stepShaping = new Set();
1042
1040
  /**
@@ -1050,14 +1048,6 @@ export class MidTurnCapacityCompactState {
1050
1048
  omittedImageToolResults = new Map();
1051
1049
  /** Malformed summaries spend one bounded repair budget for this whole Turn. */
1052
1050
  summarizerFailure;
1053
- /**
1054
- * Input tokens of the last request a provider accepted before this send.
1055
- *
1056
- * Input against input, across the send boundary: the first request of a send
1057
- * has no earlier step to compare with, and `baselineTokens` counts the reply
1058
- * too, which the next request does not always carry.
1059
- */
1060
- priorAcceptedInputTokens;
1061
1051
  constructor(headAnchor, priorContentEvents, priorInvocations,
1062
1052
  /**
1063
1053
  * The Maka window: the context window the USER declared for this model,
@@ -695,8 +695,6 @@ export class AiSdkTurn {
695
695
  // result.usage.inputTokens is cumulative across steps and would produce
696
696
  // misleading >100% percentages, so the per-step value is captured here.
697
697
  let lastStepInputTokens;
698
- /** Tool count of the request that produced `lastStepInputTokens`. */
699
- let lastStepActiveToolCount;
700
698
  // Output tokens of the same step: with the input they are the baseline the
701
699
  // next request is judged from (everything the model produced is re-sent).
702
700
  let lastStepOutputTokens;
@@ -977,8 +975,6 @@ export class AiSdkTurn {
977
975
  const turnEvents = await loadDurableTurnEvents();
978
976
  const pruned = await this.deps.compaction.pruneToolResults(turnEvents, turnId);
979
977
  if (pruned.stats) {
980
- if (pruned.stats.prunedToolResults > 0)
981
- midTurnState?.stepShaping.add('prune');
982
978
  contextBudgetForTelemetry = addToolResultPruneStats(contextBudgetForTelemetry ?? minimalContextBudgetDiagnostic(), pruned.stats);
983
979
  }
984
980
  const projectionCheckpoint = midTurnState?.projectionCheckpoint;
@@ -1151,14 +1147,6 @@ export class AiSdkTurn {
1151
1147
  ? codeModeCatalogPrompt
1152
1148
  : undefined,
1153
1149
  ]);
1154
- // A finalization step resolves an empty tool set, so its request
1155
- // legitimately drops several thousand schema tokens with no fold,
1156
- // prune or image omission. Maka shaped that request; the provider did
1157
- // not drop anything.
1158
- if (lastStepActiveToolCount !== undefined &&
1159
- activeToolsForRequest.length < lastStepActiveToolCount) {
1160
- midTurnState?.stepShaping.add('tools');
1161
- }
1162
1150
  const requestCompositionId = this.runId && this.deps.backend.recordRequestComposition
1163
1151
  ? await this.deps.backend.recordRequestComposition(this.runId, {
1164
1152
  compositionId: this.deps.newId(),
@@ -1440,61 +1428,6 @@ export class AiSdkTurn {
1440
1428
  providerStepUsage = stepUsage;
1441
1429
  if (!stepUsage)
1442
1430
  sawUnusableStepUsage = true;
1443
- // Silent eviction / rewrite check (#4559): this step only
1444
- // appended (no fold, no prune, no image omission) yet the
1445
- // provider counted no more input tokens than for the previous
1446
- // request. Not-greater, not strictly-fewer: a provider that
1447
- // truncates to a fixed window (Ollama's `num_ctx`) reports the
1448
- // same total on every later request while Maka keeps
1449
- // appending, so a plateau is the signal, and an equal count
1450
- // after an append is already impossible without provider-side
1451
- // eviction or rewriting. Input against input: the previous
1452
- // reply's reasoning may not be resent, so input + output is
1453
- // not the floor of the next input on every wire.
1454
- const completedRequestIndex = runtimeSteps - 1;
1455
- // Across the send boundary the comparison is the same one,
1456
- // against the last request a provider accepted before this
1457
- // send. A provider that truncates to a fixed window reports
1458
- // the same input on every later request while the user keeps
1459
- // adding turns, and a send of one or two steps never sees
1460
- // that from the inside: the live evidence plateaus at 3,716
1461
- // input tokens across eight turns with nothing reported
1462
- // (#4623). The first request of a send therefore compares
1463
- // against the persisted anchor, which is route-validated
1464
- // where it is read.
1465
- const acrossSends = completedRequestIndex === 0;
1466
- const priorInput = acrossSends
1467
- ? midTurnState?.priorAcceptedInputTokens
1468
- : lastStepInputTokens;
1469
- if (!this.deps.session.contextProviderDroppingReported &&
1470
- midTurnState &&
1471
- priorInput !== undefined &&
1472
- midTurnState.stepShaping.size === 0 &&
1473
- stepUsage !== undefined &&
1474
- Number.isFinite(stepUsage.inputTokens) &&
1475
- stepUsage.inputTokens > 0 &&
1476
- // Across sends the test is equality, not "did not grow".
1477
- // Inside a send Maka knows it only appended, so any
1478
- // shortfall is the provider's. Across the boundary it does
1479
- // not: a manual compaction leaves the pre-compaction anchor
1480
- // behind, a turn can carry a smaller tool set, and a user
1481
- // can edit or branch history. All three shrink the input
1482
- // legitimately, and none of them lands on exactly the same
1483
- // count. A provider truncating to a fixed window does, on
1484
- // every later request.
1485
- (acrossSends
1486
- ? stepUsage.inputTokens === priorInput
1487
- : stepUsage.inputTokens <= priorInput)) {
1488
- this.deps.session.contextProviderDroppingReported = true;
1489
- await this.recordSystemNote('context_provider_dropping', turnId, {
1490
- inputTokens: stepUsage.inputTokens,
1491
- priorInputTokens: priorInput,
1492
- });
1493
- }
1494
- // Clear here, not at the top of the next step: the continuation
1495
- // lane archives its prune below, after this point, and archiving
1496
- // is idempotent — the next step's re-projection reports no prune,
1497
- // so a clear above it would lose the only record of this one.
1498
1431
  midTurnState?.stepShaping.clear();
1499
1432
  // Fail closed: reset on every step boundary so a missing final
1500
1433
  // step's usage does not leave a stale value from an earlier step.
@@ -1520,9 +1453,9 @@ export class AiSdkTurn {
1520
1453
  }
1521
1454
  // Nothing declared, and the provider accepted a request past
1522
1455
  // the window this model reports. Every other signal in this
1523
- // design stays dark there: no rejection to recover from, no
1524
- // plateau to read, and no declaration to arm the proactive
1525
- // threshold, so the session degrades quietly and
1456
+ // design stays dark there: no rejection to recover from and
1457
+ // no declaration to arm the proactive threshold, so the
1458
+ // session degrades quietly and
1526
1459
  // indefinitely (#4634). Report the two real numbers and
1527
1460
  // leave the decision with the user: a reported window is a
1528
1461
  // hint, and Maka still declares nothing on their behalf.
@@ -1560,7 +1493,6 @@ export class AiSdkTurn {
1560
1493
  }
1561
1494
  lastStepInputTokens = stepUsage?.inputTokens;
1562
1495
  lastStepOutputTokens = stepUsage?.outputTokens;
1563
- lastStepActiveToolCount = activeToolsForRequest.length;
1564
1496
  // A `finishReason: length` is deliberately not a trigger. The
1565
1497
  // reply may have been cut because the provider ran out of
1566
1498
  // window room, or because the provider's own output cap is
@@ -23,6 +23,7 @@ import { decodePersistedToolResultContent } from '@maka/core/tool-result-record-
23
23
  import { isEmittedAgentRunEventType } from '@maka/core/agent-run';
24
24
  import { decodeModelCallAttempt, MODEL_CALL_ATTEMPT_EVENT_TYPE, } from '@maka/core/model-call-attempt';
25
25
  import { TOOL_RECOVERY_DECISION_FACT_KIND } from '@maka/core/tool-recovery-fact';
26
+ import { canonicalToolArgsHash } from '@maka/core/tool-args-identity';
26
27
  import { buildHistoryCompactCheckpoint, historyCompactSourceDigest, matchHistoryCompactCheckpointPrefix, validateHistoryCompactCheckpointShape, } from './history-compact-checkpoint.js';
27
28
  import { findCheckpointSummaryDefect } from './history-compact-summary-validation.js';
28
29
  import { isHistoryCompactContentEvent } from './history-compaction.js';
@@ -38,7 +39,7 @@ import { baseToolResultProjection, decodeLedgerTransition, reduceEffectiveModelP
38
39
  import { archivedToolResultProjection } from './tool-result-archive-transition.js';
39
40
  import { serializeToolResultProjectionV1 } from './tool-result-archive-encoding.js';
40
41
  import { createHash } from 'node:crypto';
41
- import { readToolResultPage, readableToolResult, resolveReadInput, READ_PAGE_MAX_CHARS, } from './read-page.js';
42
+ import { readToolResultPage, readableToolResult, resolveReadInput, READ_PAGE_MAX_BYTES, } from './read-page.js';
42
43
  /** Walks every typed StorageRef site reached by conversation-copy rewriting. */
43
44
  function collectConversationCopyStorageRefs(input) {
44
45
  const refs = [];
@@ -281,6 +282,20 @@ function assertConversationRuntimeLedgerCopySupported(run, runtimeEvents) {
281
282
  error.code = 'branch_runtime_fact_rewrite_unsupported';
282
283
  throw error;
283
284
  }
285
+ /**
286
+ * Mirrors the T1 scanner's identity semantics: a call whose args are not
287
+ * strict JSON cannot authenticate, which the scanner surfaces as a
288
+ * `canonical_args_hash_conflict` rather than an exception — so the copy pass
289
+ * must see `undefined` there, not a thrown error.
290
+ */
291
+ const tryCanonicalToolArgsHash = (toolName, args) => {
292
+ try {
293
+ return canonicalToolArgsHash(toolName, args);
294
+ }
295
+ catch {
296
+ return undefined;
297
+ }
298
+ };
284
299
  export async function cloneConversationRuntimeLedger(input) {
285
300
  if (input.plan.sourceSessionId !== input.referenceMap.sourceSessionId) {
286
301
  throw new Error('Conversation copy plan does not belong to the source Session');
@@ -386,10 +401,22 @@ export async function cloneConversationRuntimeLedger(input) {
386
401
  };
387
402
  for (const sourceId of clonedEventBySourceId.keys())
388
403
  finishTarget(sourceId);
404
+ // The identity rewrite changes a copied call's canonical args, so the paired
405
+ // dispatch's recorded hash stops authenticating them and the copied ledger
406
+ // fails its own T1 re-scan. Collect the source and rewritten identities per
407
+ // (invocation, tool call) and re-authenticate the dispatches after the
408
+ // rewrite pass — but only when the source dispatch actually authenticated
409
+ // the source call. Stamping the rewritten identity over a mismatched hash
410
+ // would launder an already-corrupt source ledger into a valid-looking copy
411
+ // instead of preserving the corruption for the re-scan to reject (#5466
412
+ // review). Identity derivation mirrors the scanner's semantics: args that
413
+ // are not strict JSON cannot authenticate at all.
414
+ const rewrittenArgsIdentities = new Map();
389
415
  for (const event of clonedEventBySourceId.values()) {
390
416
  if (event.content?.kind === 'function_call' && event.content.name === 'Read') {
391
417
  const args = event.content.args;
392
- if (args && typeof args === 'object' && 'path' in args && typeof args.path === 'string')
418
+ if (args && typeof args === 'object' && 'path' in args && typeof args.path === 'string') {
419
+ const sourceArgsHash = tryCanonicalToolArgsHash(event.content.name, args);
393
420
  event.content = {
394
421
  ...event.content,
395
422
  args: {
@@ -397,19 +424,47 @@ export async function cloneConversationRuntimeLedger(input) {
397
424
  ...rewriteReadInput(args, references, clonedEventBySourceId),
398
425
  },
399
426
  };
427
+ rewrittenArgsIdentities.set(`${event.invocationId}\u0000${event.content.id}`, {
428
+ sourceArgsHash,
429
+ rewrittenArgsHash: tryCanonicalToolArgsHash(event.content.name, event.content.args),
430
+ });
431
+ }
400
432
  }
401
433
  if (event.content?.kind === 'text')
402
434
  event.content.text = rewriteCopiedText(event.content.text, references, clonedEventBySourceId);
403
435
  if (event.content?.kind === 'function_call' && event.content.name === 'ArchiveRead') {
404
436
  const args = event.content.args;
405
437
  if (args && typeof args === 'object' && 'ref' in args && typeof args.ref === 'string') {
438
+ const sourceArgsHash = tryCanonicalToolArgsHash(event.content.name, args);
406
439
  event.content = {
407
440
  ...event.content,
408
441
  args: { ...args, ref: rewriteLedgerArchiveText(args.ref, references) },
409
442
  };
443
+ rewrittenArgsIdentities.set(`${event.invocationId}\u0000${event.content.id}`, {
444
+ sourceArgsHash,
445
+ rewrittenArgsHash: tryCanonicalToolArgsHash(event.content.name, event.content.args),
446
+ });
410
447
  }
411
448
  }
412
449
  }
450
+ if (rewrittenArgsIdentities.size > 0) {
451
+ for (const event of clonedEventBySourceId.values()) {
452
+ const dispatch = event.actions?.toolDispatch;
453
+ if (dispatch?.canonicalArgsHash === undefined)
454
+ continue;
455
+ const identity = rewrittenArgsIdentities.get(`${event.invocationId}\u0000${dispatch.providerToolCallId}`);
456
+ if (identity === undefined)
457
+ continue;
458
+ if (identity.sourceArgsHash !== dispatch.canonicalArgsHash)
459
+ continue;
460
+ if (identity.rewrittenArgsHash === undefined)
461
+ continue;
462
+ event.actions = {
463
+ ...event.actions,
464
+ toolDispatch: { ...dispatch, canonicalArgsHash: identity.rewrittenArgsHash },
465
+ };
466
+ }
467
+ }
413
468
  const preparedPlans = flattenedPlans.map((plan) => {
414
469
  const runId = runIds.get(plan.run.runId);
415
470
  const clonedOperationalEvents = plan.operationalEvents.flatMap((event) => {
@@ -882,7 +937,7 @@ function cloneModelProjectionTransition(event, references, clonedRuntimeEvents,
882
937
  });
883
938
  if (rewritten.page) {
884
939
  delete rewritten.page;
885
- rewritten.page = readToolResultPage(serialized, { path: rewritten.resourceRef }, READ_PAGE_MAX_CHARS - JSON.stringify(rewritten).length - 32);
940
+ rewritten.page = readToolResultPage(serialized, { path: rewritten.resourceRef }, READ_PAGE_MAX_BYTES - Buffer.byteLength(JSON.stringify(rewritten)) - 32);
886
941
  }
887
942
  references.ledgerArchives?.set(placeholder.resourceRef ?? buildToolResultArchiveResourceRef(placeholder), rewritten);
888
943
  }