maka-agent 0.2.0-dev.12.20260901 → 0.2.0-dev.14.20260902

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 (105) hide show
  1. package/THIRD_PARTY_NOTICES.txt +2 -2
  2. package/dist/acp/maka-acp-agent.js +6 -3
  3. package/dist/acp/session-registry.js +307 -0
  4. package/dist/acp/stdio-server.js +20 -1
  5. package/dist/cli-core.js +15 -2
  6. package/dist/pi-transcript.js +1 -1
  7. package/dist/pi-tui-layout.js +1 -1
  8. package/dist/pi-tui-mcp-status.js +1 -1
  9. package/dist/pi-tui-runner.js +1 -1
  10. package/dist/runtime-host-access-command.js +37 -4
  11. package/dist/runtime-host-capability-provider-command.js +16 -2
  12. package/dist/runtime-host-cli-context.js +73 -3
  13. package/dist/runtime-host-cli.js +37 -6
  14. package/dist/runtime-host-run-command.js +3 -1
  15. package/dist/runtime-host-update-command.js +59 -31
  16. package/dist/tui-copy-catalog.js +4 -2
  17. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  18. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  19. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  21. package/node_modules/@maka/core/dist/attachments.js +12 -0
  22. package/node_modules/@maka/core/dist/connection-error-copy.js +17 -34
  23. package/node_modules/@maka/core/dist/events.js +0 -13
  24. package/node_modules/@maka/core/dist/maka-wordmark.js +23 -0
  25. package/node_modules/@maka/core/dist/model-catalog.js +22 -1
  26. package/node_modules/@maka/core/dist/runtime-event.js +1 -0
  27. package/node_modules/@maka/core/dist/runtime-policy/connection-catalog-codec.js +50 -1
  28. package/node_modules/@maka/core/dist/runtime-policy/credential-vault-codec.js +9 -1
  29. package/node_modules/@maka/core/dist/runtime-policy/model-catalog-entry-codec.js +10 -1
  30. package/node_modules/@maka/core/dist/runtime-policy/policy-codec.js +75 -0
  31. package/node_modules/@maka/core/dist/runtime-policy.js +4 -2
  32. package/node_modules/@maka/core/dist/session.js +1 -0
  33. package/node_modules/@maka/core/dist/settings.js +10 -2
  34. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -1
  35. package/node_modules/@maka/core/package.json +2 -1
  36. package/node_modules/@maka/mcp/dist/index.js +1 -0
  37. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +52 -80
  38. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +178 -140
  39. package/node_modules/@maka/runtime/dist/archive-read-tool.js +26 -5
  40. package/node_modules/@maka/runtime/dist/builtin-tools.js +27 -2
  41. package/node_modules/@maka/runtime/dist/context-budget-policy.js +0 -12
  42. package/node_modules/@maka/runtime/dist/conversation-copy.js +66 -43
  43. package/node_modules/@maka/runtime/dist/durable-tool-result-projection.js +31 -0
  44. package/node_modules/@maka/runtime/dist/history-compact-error.js +10 -2
  45. package/node_modules/@maka/runtime/dist/history-compact-input-fit.js +7 -1
  46. package/node_modules/@maka/runtime/dist/history-compaction.js +13 -22
  47. package/node_modules/@maka/runtime/dist/model-history.js +41 -16
  48. package/node_modules/@maka/runtime/dist/provider-image-overflow-recovery.js +12 -31
  49. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +3 -0
  50. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +13 -2
  51. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +3 -6
  52. package/node_modules/@maka/runtime/dist/shell-tools.js +77 -1
  53. package/node_modules/@maka/runtime/dist/tool-availability.js +74 -5
  54. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +333 -52
  55. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +34 -3
  56. package/node_modules/@maka/runtime/dist/tool-runtime.js +12 -0
  57. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +0 -3
  58. package/node_modules/@maka/runtime-host/dist/client/catalog-reader.js +40 -13
  59. package/node_modules/@maka/runtime-host/dist/client/connection.js +50 -31
  60. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +48 -4
  61. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -2
  62. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +32 -1
  63. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +22 -4
  64. package/node_modules/@maka/runtime-host/dist/operator/access-management-frame.js +10 -1
  65. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +56 -12
  66. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +3 -0
  67. package/node_modules/@maka/runtime-host/dist/protocol/configuration.js +55 -9
  68. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +37 -0
  69. package/node_modules/@maka/runtime-host/dist/protocol/index.js +17 -1
  70. package/node_modules/@maka/runtime-host/dist/protocol/network-proxy.js +1 -7
  71. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  72. package/node_modules/@maka/runtime-host/dist/protocol/runtime-policy.js +48 -1
  73. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +4 -2
  74. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +2 -12
  75. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +2 -1
  76. package/node_modules/@maka/runtime-host/dist/server/agent-graph-execution-coordinator.js +1 -2
  77. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +0 -9
  78. package/node_modules/@maka/runtime-host/dist/server/configuration-coordinator.js +20 -1
  79. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +46 -24
  80. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +4 -1
  81. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +15 -0
  82. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +8 -4
  83. package/node_modules/@maka/runtime-host/dist/server/network-proxy-coordinator.js +0 -1
  84. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +3 -0
  85. package/node_modules/@maka/runtime-host/dist/server/runtime-policy-coordinator.js +28 -1
  86. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +3 -3
  87. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +35 -3
  88. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +16 -0
  89. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +189 -6
  90. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +4 -1
  91. package/node_modules/@maka/storage/dist/settings-store.js +16 -25
  92. package/node_modules/fast-uri/index.js +215 -47
  93. package/node_modules/fast-uri/lib/schemes.js +9 -4
  94. package/node_modules/fast-uri/lib/utils.js +396 -92
  95. package/node_modules/fast-uri/package.json +1 -1
  96. package/node_modules/qs/.github/THREAT_MODEL.md +3 -3
  97. package/node_modules/qs/CHANGELOG.md +15 -0
  98. package/node_modules/qs/README.md +19 -1
  99. package/node_modules/qs/dist/qs.js +21 -21
  100. package/node_modules/qs/eslint.config.mjs +1 -1
  101. package/node_modules/qs/lib/parse.js +3 -4
  102. package/node_modules/qs/lib/stringify.js +23 -8
  103. package/node_modules/qs/lib/utils.js +10 -3
  104. package/node_modules/qs/package.json +4 -4
  105. package/package.json +1 -1
@@ -16,7 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { isModelModality, isRelayProviderType, PROVIDER_REGISTRY, providerDefaultsOf, validateSlug, } from '../llm-connections.js';
19
+ import { isModelModality, isRelayProviderType, effectiveBaseUrl, PROVIDER_REGISTRY, providerDefaultsOf, validateSlug, } from '../llm-connections.js';
20
20
  import { CONNECTION_MODEL_DESCRIPTION_MAX_LENGTH, CONNECTION_MODEL_DISPLAY_NAME_MAX_LENGTH, MAX_PREPENDED_FALLBACK_MODELS, } from '../model-catalog.js';
21
21
  import { DECLARABLE_RELAY_THINKING_LEVELS, isThinkingLevel, } from '../model-thinking.js';
22
22
  import { normalizeOptionalRequestBodyOverlay, RequestCustomizationValidationError, } from '../request-customization.js';
@@ -338,6 +338,55 @@ export function decodeConnectionVersionBasis(value) {
338
338
  revision: positiveRevisionValue(item.revision, 'connection revision'),
339
339
  };
340
340
  }
341
+ export function canonicalConnectionEffectiveBaseUrl(connection) {
342
+ const endpoint = effectiveBaseUrl(connection);
343
+ try {
344
+ return new URL(endpoint).toString();
345
+ }
346
+ catch {
347
+ throw domainError('connection has an invalid effective base URL');
348
+ }
349
+ }
350
+ export function connectionCredentialTarget(connection) {
351
+ return {
352
+ connectionId: connection.connectionId,
353
+ revision: connection.revision,
354
+ slug: connection.slug,
355
+ providerType: connection.providerType,
356
+ effectiveBaseUrl: canonicalConnectionEffectiveBaseUrl(connection),
357
+ };
358
+ }
359
+ export function decodeConnectionCredentialTarget(value) {
360
+ const item = exactRecord(value, 'connection credential target', [
361
+ 'connectionId',
362
+ 'revision',
363
+ 'slug',
364
+ 'providerType',
365
+ 'effectiveBaseUrl',
366
+ ]);
367
+ const version = decodeConnectionVersionBasis({
368
+ connectionId: item.connectionId,
369
+ revision: item.revision,
370
+ });
371
+ const providerType = decodeProviderType(item.providerType);
372
+ const effectiveBaseUrl = stringValue(item.effectiveBaseUrl, 'connection credential target effective base URL', 2_048);
373
+ let canonical;
374
+ try {
375
+ canonical = new URL(effectiveBaseUrl).toString();
376
+ }
377
+ catch {
378
+ throw domainError('connection credential target effective base URL must be valid');
379
+ }
380
+ if (canonical !== effectiveBaseUrl) {
381
+ throw domainError('connection credential target effective base URL must be canonical');
382
+ }
383
+ return {
384
+ ...version,
385
+ slug: decodeConnectionSlug(item.slug),
386
+ providerType,
387
+ effectiveBaseUrl,
388
+ };
389
+ }
341
390
  export function decodeConnectionTarget(value) {
342
391
  const item = exactRecord(value, 'connection target', ['connectionId', 'modelId']);
343
392
  return {
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { decodeConnectionCredentialTarget } from './connection-catalog-codec.js';
19
20
  import { WEB_SEARCH_CREDENTIAL_PROVIDERS } from '../web-search.js';
20
21
  import { parseRequestHeaders, RequestCustomizationValidationError, serializeRequestHeaders, } from '../request-customization.js';
21
22
  import { domainError, entityIdValue, exactRecord, integerValue, positiveRevisionValue, } from './domain-codec.js';
@@ -96,7 +97,7 @@ export function decodeCredentialStatus(value) {
96
97
  throw domainError('credential status configured flag is invalid');
97
98
  }
98
99
  export function normalizeSetCredentialInput(value) {
99
- const input = exactRecord(value, 'set credential input', ['locator', 'expected', 'secret']);
100
+ const input = exactRecord(value, 'set credential input', ['locator', 'expected', 'expectedConnection', 'secret'], ['locator', 'expected', 'secret']);
100
101
  let expected;
101
102
  if (input.expected === null) {
102
103
  expected = null;
@@ -112,10 +113,17 @@ export function normalizeSetCredentialInput(value) {
112
113
  };
113
114
  }
114
115
  const locator = decodeCredentialLocator(input.locator);
116
+ const expectedConnection = input.expectedConnection === undefined
117
+ ? undefined
118
+ : decodeConnectionCredentialTarget(input.expectedConnection);
119
+ if (expectedConnection && locator.scope !== 'connection') {
120
+ throw domainError('only connection credentials accept a connection target basis');
121
+ }
115
122
  const secret = normalizeCredentialSecret(input.secret);
116
123
  return {
117
124
  locator,
118
125
  expected,
126
+ ...(expectedConnection === undefined ? {} : { expectedConnection }),
119
127
  secret: locator.scope === 'connection' && locator.kind === 'request_headers'
120
128
  ? normalizeRequestHeadersSecret(secret)
121
129
  : secret,
@@ -36,7 +36,15 @@ export function decodeModelCatalogEntry(value) {
36
36
  'thinkingLevels',
37
37
  'contextWindow',
38
38
  'knowledgeCutoff',
39
- ], ['id', 'canUseAsChatDefault', 'isDefault', 'supportsVision', 'thinkingLevels']);
39
+ 'describedByMetadata',
40
+ ], [
41
+ 'id',
42
+ 'canUseAsChatDefault',
43
+ 'isDefault',
44
+ 'supportsVision',
45
+ 'thinkingLevels',
46
+ 'describedByMetadata',
47
+ ]);
40
48
  // The fields an entry shares with a stored model row keep one decoder, so a
41
49
  // bound that moves moves for both. `decodeConnectionModel` rejects unknown
42
50
  // fields, so it is handed exactly the subset it owns.
@@ -50,6 +58,7 @@ export function decodeModelCatalogEntry(value) {
50
58
  isDefault: booleanValue(item.isDefault, 'entry default flag'),
51
59
  supportsVision: booleanValue(item.supportsVision, 'entry vision support'),
52
60
  thinkingLevels: decodeThinkingLevels(item.thinkingLevels),
61
+ describedByMetadata: booleanValue(item.describedByMetadata, 'entry metadata coverage'),
53
62
  };
54
63
  }
55
64
  function decodeThinkingLevels(value) {
@@ -19,6 +19,7 @@
19
19
  import { isThinkingLevel } from '../model-thinking.js';
20
20
  import { CHAT_DEFAULT_PERMISSION_MODES } from '../settings.js';
21
21
  import { normalizeSubagentSettings } from '../subagent-settings.js';
22
+ import { decodeCredentialVersionBasis, normalizeCredentialSecret, } from './credential-vault-codec.js';
22
23
  import { WEB_SEARCH_PROVIDERS } from '../web-search.js';
23
24
  import { assertCanonicalValue, booleanValue, domainError, exactRecord, integerValue, revisionValue, stringArrayValue, stringValue, } from './domain-codec.js';
24
25
  export function decodeCanonicalRuntimePolicy(value) {
@@ -50,6 +51,80 @@ export function normalizeRuntimePolicyMutation(value) {
50
51
  operation: normalizeMutationOperation(operation),
51
52
  };
52
53
  }
54
+ export function normalizeNetworkProxyUpdate(value) {
55
+ const input = exactRecord(value, 'network proxy update', [
56
+ 'expectedPolicyRevision',
57
+ 'expectedCredential',
58
+ 'networkProxy',
59
+ 'credential',
60
+ ]);
61
+ const expectedCredential = input.expectedCredential === null
62
+ ? null
63
+ : decodeCredentialVersionBasis(input.expectedCredential);
64
+ if (expectedCredential !== null && expectedCredential.locator.scope !== 'network_proxy') {
65
+ throw domainError('network proxy update requires a network proxy credential basis');
66
+ }
67
+ const credential = normalizeNetworkProxyCredentialUpdate(input.credential);
68
+ const networkProxy = normalizeNetworkProxy(input.networkProxy);
69
+ if (!networkProxy.authEnabled && credential.kind !== 'delete') {
70
+ throw domainError('disabled proxy authentication requires credential deletion');
71
+ }
72
+ return {
73
+ expectedPolicyRevision: revisionValue(input.expectedPolicyRevision, 'network proxy expected policy revision'),
74
+ expectedCredential,
75
+ networkProxy,
76
+ credential,
77
+ };
78
+ }
79
+ function normalizeNetworkProxyCredentialUpdate(value) {
80
+ const base = exactRecord(value, 'network proxy credential update', ['kind', 'secret', 'expectedTarget'], ['kind']);
81
+ switch (base.kind) {
82
+ case 'keep':
83
+ case 'delete': {
84
+ exactRecord(value, `network proxy credential ${base.kind}`, ['kind']);
85
+ return { kind: base.kind };
86
+ }
87
+ case 'replace': {
88
+ const replacement = exactRecord(value, 'network proxy credential replacement', ['kind', 'secret', 'expectedTarget'], ['kind', 'secret']);
89
+ return {
90
+ kind: 'replace',
91
+ secret: normalizeCredentialSecret(replacement.secret),
92
+ ...(replacement.expectedTarget === undefined
93
+ ? {}
94
+ : {
95
+ expectedTarget: normalizeNetworkProxyCredentialTarget(replacement.expectedTarget),
96
+ }),
97
+ };
98
+ }
99
+ default:
100
+ throw domainError(`network proxy credential update '${String(base.kind)}' is unknown`);
101
+ }
102
+ }
103
+ export function normalizeNetworkProxyCredentialTarget(value) {
104
+ const item = exactRecord(value, 'network proxy credential target', [
105
+ 'protocol',
106
+ 'host',
107
+ 'port',
108
+ 'username',
109
+ ]);
110
+ if (item.protocol !== 'http' && item.protocol !== 'https' && item.protocol !== 'socks5') {
111
+ throw domainError('network proxy credential target protocol is invalid');
112
+ }
113
+ const rawHost = stringValue(item.host, 'network proxy credential target host', 255);
114
+ if (/[\u0000-\u001f\u007f-\u009f]/.test(rawHost)) {
115
+ throw domainError('network proxy credential target host must not contain control characters');
116
+ }
117
+ const host = rawHost.trim().toLowerCase();
118
+ if (host.length === 0) {
119
+ throw domainError('network proxy credential target host must not be empty');
120
+ }
121
+ return {
122
+ protocol: item.protocol,
123
+ host,
124
+ port: integerValue(item.port, 'network proxy credential target port', 1, 65_535),
125
+ username: stringValue(item.username, 'network proxy credential target username', 256),
126
+ };
127
+ }
53
128
  function normalizeRuntimePolicy(value) {
54
129
  const policy = exactRecord(value, 'runtime policy', [
55
130
  'networkProxy',
@@ -16,11 +16,13 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { networkProxyCredentialTarget, } from './settings.js';
19
20
  import { WEB_SEARCH_PROVIDERS, } from './web-search.js';
20
21
  export { WEB_SEARCH_PROVIDERS };
22
+ export { networkProxyCredentialTarget };
21
23
  export { decodeRuntimePolicyEntityId, RuntimePolicyDomainDecodeError, } from './runtime-policy/domain-codec.js';
22
- export { decodeCanonicalRuntimePolicy, decodeRuntimePolicyV2, normalizeRuntimePolicyMutation, } from './runtime-policy/policy-codec.js';
23
- export { CONNECTION_CATALOG_MAX_CONNECTIONS, CONNECTION_CATALOG_MAX_ENABLED_MODEL_IDS, CONNECTION_CATALOG_MAX_ENTRIES_PER_CONNECTION, CONNECTION_CATALOG_MAX_MODELS_PER_CONNECTION, CONNECTION_MODEL_ID_MAX_LENGTH, CONNECTION_NAME_MAX_LENGTH, decodeCanonicalConnectionBaseUrl, decodeCanonicalConnectionCatalogEntry, decodeConnectionModelId, decodeRelayModelProfilesTable, decodeConnectionModel, decodeConnectionName, decodeConnectionSlug, decodeConnectionTarget, decodeConnectionTestSummary, decodeConnectionVersionBasis, decodeProviderType, normalizeCatalogConnectionBaseUrl, normalizeConnectionCatalogEntryDraft, normalizeConnectionCatalogEntryUpdate, normalizeConnectionCatalogEntryUpdateForProvider, normalizeConnectionModelDiscoveryResult, normalizeCreateCatalogConnectionInput, normalizeRemoveCatalogConnectionInput, normalizeSetDefaultConnectionTargetInput, normalizeUpdateCatalogConnectionInput, } from './runtime-policy/connection-catalog-codec.js';
24
+ export { decodeCanonicalRuntimePolicy, normalizeNetworkProxyCredentialTarget, decodeRuntimePolicyV2, normalizeNetworkProxyUpdate, normalizeRuntimePolicyMutation, } from './runtime-policy/policy-codec.js';
25
+ export { CONNECTION_CATALOG_MAX_CONNECTIONS, CONNECTION_CATALOG_MAX_ENABLED_MODEL_IDS, CONNECTION_CATALOG_MAX_ENTRIES_PER_CONNECTION, CONNECTION_CATALOG_MAX_MODELS_PER_CONNECTION, CONNECTION_MODEL_ID_MAX_LENGTH, CONNECTION_NAME_MAX_LENGTH, decodeCanonicalConnectionBaseUrl, decodeCanonicalConnectionCatalogEntry, decodeConnectionModelId, decodeConnectionCredentialTarget, decodeRelayModelProfilesTable, decodeConnectionModel, decodeConnectionName, decodeConnectionSlug, decodeConnectionTarget, decodeConnectionTestSummary, decodeConnectionVersionBasis, decodeProviderType, normalizeCatalogConnectionBaseUrl, normalizeConnectionCatalogEntryDraft, normalizeConnectionCatalogEntryUpdate, normalizeConnectionCatalogEntryUpdateForProvider, normalizeConnectionModelDiscoveryResult, canonicalConnectionEffectiveBaseUrl, connectionCredentialTarget, normalizeCreateCatalogConnectionInput, normalizeRemoveCatalogConnectionInput, normalizeSetDefaultConnectionTargetInput, normalizeUpdateCatalogConnectionInput, } from './runtime-policy/connection-catalog-codec.js';
24
26
  export { decodeModelCatalogEntry } from './runtime-policy/model-catalog-entry-codec.js';
25
27
  export { decodeCredentialLocator, decodeCredentialStatus, decodeCredentialVersionBasis, normalizeCredentialSecret, normalizeDeleteCredentialInput, normalizeSetCredentialInput, } from './runtime-policy/credential-vault-codec.js';
26
28
  export { normalizeRequestBodyOverlay, normalizeOptionalRequestBodyOverlay, normalizeRequestHeaderUpdates, normalizeRequestHeaders, parseRequestHeaders, REQUEST_BODY_OVERLAY_MAX_BYTES, REQUEST_HEADERS_MAX_BYTES, RequestCustomizationValidationError, serializeRequestHeaders, } from './request-customization.js';
@@ -348,6 +348,7 @@ const TOKEN_USAGE_MESSAGE_SHAPE = defineObjectShape()(['type', 'id', 'turnId', '
348
348
  'promptSegments',
349
349
  'contextBudget',
350
350
  'providerRequestTraceId',
351
+ 'lastRequestAnchor',
351
352
  ]);
352
353
  const TURN_STATE_MESSAGE_SHAPE = defineObjectShape()(['type', 'id', 'turnId', 'ts', 'status', 'partialOutputRetained'], [
353
354
  'parentTurnId',
@@ -47,6 +47,14 @@ export const SETTINGS_SECTIONS = [
47
47
  'health',
48
48
  'about',
49
49
  ];
50
+ export function networkProxyCredentialTarget(proxy) {
51
+ return {
52
+ protocol: proxy.protocol,
53
+ host: proxy.host.trim().toLowerCase(),
54
+ port: proxy.port,
55
+ username: proxy.username,
56
+ };
57
+ }
50
58
  /** Palette ids shared with `[data-maka-theme]` CSS selectors. */
51
59
  export const THEME_PALETTES = [
52
60
  'default',
@@ -301,7 +309,6 @@ export function createDefaultSettings() {
301
309
  port: 7890,
302
310
  authEnabled: false,
303
311
  username: '',
304
- password: '',
305
312
  bypassList: ['metaso.cn', 'baidu.com'],
306
313
  autoBypassDomains: DEFAULT_PROXY_BYPASS_DOMAINS,
307
314
  },
@@ -357,6 +364,7 @@ export function createDefaultSettings() {
357
364
  };
358
365
  }
359
366
  export function mergeSettings(current, patch) {
367
+ const { credential: _credential, password: _legacyPassword, passwordConfigured: _derivedStatus, ...proxyPatch } = (patch.network?.proxy ?? {});
360
368
  return {
361
369
  ...current,
362
370
  network: {
@@ -364,7 +372,7 @@ export function mergeSettings(current, patch) {
364
372
  ...(patch.network ?? {}),
365
373
  proxy: {
366
374
  ...current.network.proxy,
367
- ...(patch.network?.proxy ?? {}),
375
+ ...proxyPatch,
368
376
  },
369
377
  },
370
378
  botChat: mergeBotChatSettings(current.botChat, patch.botChat),
@@ -213,6 +213,15 @@ const CONTEXT_NUMBERS = [
213
213
  'activeEstimatedTokensSaved',
214
214
  ];
215
215
  const CONTEXT_REASON_COUNTS = ['archivePlaceholderReasonCounts'];
216
+ const LAST_REQUEST_ANCHOR_SHAPE = defineObjectShape()(['inputTokens', 'payloadChars'], []);
217
+ export function isLastRequestAnchor(value) {
218
+ return (isRecord(value) &&
219
+ hasExactShape(value, LAST_REQUEST_ANCHOR_SHAPE) &&
220
+ isFiniteNumber(value.inputTokens) &&
221
+ isFiniteNumber(value.payloadChars) &&
222
+ value.inputTokens > 0 &&
223
+ value.payloadChars > 0);
224
+ }
216
225
  export function isTokenUsageFields(value) {
217
226
  if (!isRecord(value))
218
227
  return false;
@@ -233,7 +242,8 @@ export function isTokenUsageFields(value) {
233
242
  (value.promptSegments === undefined ||
234
243
  (Array.isArray(value.promptSegments) &&
235
244
  value.promptSegments.every(isPromptSegmentEstimate))) &&
236
- (value.contextBudget === undefined || isContextBudgetDiagnostic(value.contextBudget)));
245
+ (value.contextBudget === undefined || isContextBudgetDiagnostic(value.contextBudget)) &&
246
+ (value.lastRequestAnchor === undefined || isLastRequestAnchor(value.lastRequestAnchor)));
237
247
  }
238
248
  export function isPromptSegmentEstimate(value) {
239
249
  return (isRecord(value) &&
@@ -146,7 +146,8 @@
146
146
  "./tool-result-status": "./dist/tool-result-status.js",
147
147
  "./ui-locale": "./dist/ui-locale.js",
148
148
  "./unified-diff": "./dist/unified-diff.js",
149
- "./dev-single-instance": "./dist/dev-single-instance.js"
149
+ "./dev-single-instance": "./dist/dev-single-instance.js",
150
+ "./maka-wordmark": "./dist/maka-wordmark.js"
150
151
  },
151
152
  "dependencies": {
152
153
  "intl-messageformat": "11.2.12"
@@ -31,6 +31,7 @@ import { McpToolCallPreparer } from './tool-output-validation.js';
31
31
  import { McpCredentialCoordinator } from './credential-coordinator.js';
32
32
  import { assertTransportSecurity, urlProvenance, } from './transport-security.js';
33
33
  import { McpAuthRequiredError, McpOAuthProvider, } from './oauth.js';
34
+ export { formatMcpDiagnosticText } from './diagnostic-text.js';
34
35
  export { McpToolCallError } from './tool-call-error.js';
35
36
  export { createCredentialMcpOAuthStorage, } from './credential-oauth-storage.js';
36
37
  export { createMemoryMcpOAuthStorage, McpAuthRequiredError, McpOAuthProvider, } from './oauth.js';
@@ -38,6 +38,7 @@ import { persistedOpenAiResponsesStepMessages } from './openai-responses-continu
38
38
  import { composeRequestProjection, } from './request-projection.js';
39
39
  import { decodePlaintextResponsesReasoningState, replayPlaintextResponsesProviderOptions, responsesReasoningItemId, } from './responses-reasoning-state.js';
40
40
  import { toolResultOutput } from './tool-result-output.js';
41
+ import { finitePositive } from './context-budget-helpers.js';
41
42
  import { contextDiagnosticsCompactionOf, } from './context-diagnostics.js';
42
43
  import { AiSdkCompaction, hasActiveToolResultPruneDiagnosticPatch, hasBlockingReplayDiagnostics, } from './ai-sdk-compaction.js';
43
44
  import { durableProjectionToToolResultOutput } from './durable-tool-result-projection.js';
@@ -59,7 +60,6 @@ import { applyPatchReplayFactText, normalizeApplyPatchReplayInput, routeApplyPat
59
60
  import { applyRuntimeEventContextBudget, buildContextBudgetDiagnosticShell, estimateRuntimeEventsTokens, mergeContextBudgetDiagnostic, mergeContextBudgetDiagnosticPatches, minimalContextBudgetDiagnostic, shouldAppendContextCompactedNote, shouldAppendContextCompactionFailedOpenNote, } from './context-budget.js';
60
61
  import { evaluateHistoryCompactCheckpointReplay, isHistoryCompactContentEvent, } from './history-compaction.js';
61
62
  import { canContinueHistoryCompactCheckpointForModel, historyCompactCheckpointToModelMessage, isProviderHistoryCompactCheckpoint, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
62
- import { isMalformedHistoryCompactSummaryReason } from './history-compact-error.js';
63
63
  import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
64
64
  export { DEFAULT_PERMISSION_TIMEOUT_MS, MAX_ACTIVE_CHILD_AGENT_RUNS_PER_TURN, MAX_ACTIVE_SUBAGENT_TOOLS_PER_TURN, TOOL_ERROR_RESULT_MAX_CHARS, formatSyntheticToolErrorText, } from './tool-runtime.js';
65
65
  export { normalizeAiSdkUsage } from './model-adapter.js';
@@ -1142,7 +1142,7 @@ export class AiSdkBackend {
1142
1142
  return;
1143
1143
  }
1144
1144
  // --- Build messages from RuntimeEvent history and its compatibility projection. ---
1145
- const priorReplayResult = await this.buildPriorMessages(scope, input, this.automaticMemoryCompactionSupported() ? true : undefined);
1145
+ const priorReplayResult = await this.buildPriorMessages(scope, input, midTurnState, this.automaticMemoryCompactionSupported() ? true : undefined);
1146
1146
  if (scope.aborted) {
1147
1147
  queue.push({
1148
1148
  type: 'abort',
@@ -1162,20 +1162,6 @@ export class AiSdkBackend {
1162
1162
  yield* this.drain(queue);
1163
1163
  return;
1164
1164
  }
1165
- if (priorReplayResult.status === 'context_budget_exhausted') {
1166
- trace.modelStreamCompleted('context_budget_exhausted');
1167
- queue.push({
1168
- type: 'complete',
1169
- id: this.newId(),
1170
- turnId,
1171
- ts: this.now(),
1172
- stopReason: 'context_budget_exhausted',
1173
- contextBudgetExhaustedDetail: priorReplayResult.detail,
1174
- });
1175
- queue.close();
1176
- yield* this.drain(queue);
1177
- return;
1178
- }
1179
1165
  const priorReplay = priorReplayResult;
1180
1166
  if (input.continuation && priorReplay.messages.length === 0) {
1181
1167
  const replay = priorReplayFailureTrace(priorReplay);
@@ -1337,8 +1323,7 @@ export class AiSdkBackend {
1337
1323
  const onMidTurnDiagnosticPatch = (patch) => {
1338
1324
  midTurnCompactDiagnosticPatch = mergeContextBudgetDiagnosticPatches(midTurnCompactDiagnosticPatch, patch);
1339
1325
  };
1340
- const midTurnSystemPromptChars = systemPrompt?.length ?? 0;
1341
- const midTurnCapacityHook = this.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, providerTools, () => currentRepairToolNames(), midTurnSystemPromptChars, onMidTurnDiagnosticPatch, scope, this.automaticMemoryCompactionSupported()
1326
+ const midTurnCapacityHook = this.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, providerTools, onMidTurnDiagnosticPatch, scope, this.automaticMemoryCompactionSupported()
1342
1327
  ? () => this.automaticMemoryCompactionDecision()
1343
1328
  : undefined, this.automaticMemoryCompactionSupported()
1344
1329
  ? (dispatch) => this.dispatchAutomaticMemoryCompaction(scope, dispatch)
@@ -1353,16 +1338,12 @@ export class AiSdkBackend {
1353
1338
  // The verdict owner wraps the WHOLE shaping pipeline: hooks shape, one
1354
1339
  // owner measures the final payload and decides pass/terminate.
1355
1340
  const requestProjection = midTurnState && midTurnCapacityHook && shapedProjection
1356
- ? this.compaction.buildMidTurnFinalRequestVerdict({
1341
+ ? this.compaction.buildMidTurnFinalRequestRescue({
1357
1342
  shaped: shapedProjection,
1358
1343
  reentry: composeRequestProjection(undefined, midTurnCapacityHook, activeToolResultPruneHook),
1359
1344
  state: midTurnState,
1360
1345
  providerTools,
1361
- fallbackActiveTools: () => currentRepairToolNames(),
1362
1346
  charsPerToken: this.input.contextBudget?.charsPerToken ?? 4,
1363
- systemPromptChars: midTurnSystemPromptChars,
1364
- onDiagnosticPatch: onMidTurnDiagnosticPatch,
1365
- abortController: turnAbortController,
1366
1347
  })
1367
1348
  : shapedProjection;
1368
1349
  const completedProviderSteps = [];
@@ -1382,18 +1363,10 @@ export class AiSdkBackend {
1382
1363
  if (missingSteering.length > 0)
1383
1364
  requestMessages = [...requestMessages, ...missingSteering];
1384
1365
  }
1385
- const shaped = requestProjection
1386
- ? await requestProjection({
1387
- completedSteps: completedProviderSteps,
1388
- stepNumber: runtimeSteps,
1389
- model,
1390
- messages: requestMessages,
1391
- })
1392
- : undefined;
1393
- if (midTurnState?.exhaustedDetail) {
1394
- throw new Error(`context budget exhausted before provider dispatch: ${midTurnState.exhaustedDetail}`);
1395
- }
1396
- const projectedMessages = shaped?.messages ?? requestMessages;
1366
+ // Resolved BEFORE request projection so the capacity measurement and
1367
+ // the request that goes out are the same request: a finalization step
1368
+ // adds prompt fragments and sends no tool schemas, and an anchor
1369
+ // paired with the un-finalized shape describes a different payload.
1397
1370
  const finalChildSummaryStep = this.input.header.collaborationMode === 'agent' &&
1398
1371
  maxSteps !== undefined &&
1399
1372
  maxSteps > 1 &&
@@ -1406,15 +1379,29 @@ export class AiSdkBackend {
1406
1379
  if (sandboxBoundaryFinalizationStep) {
1407
1380
  toolRuntime.forceSandboxBoundaryFinalization();
1408
1381
  }
1409
- const activeToolsForRequest = finalChildSummaryStep || sandboxBoundaryFinalizationStep
1410
- ? []
1411
- : boundaryAwareToolNames(shaped?.activeTools ?? plan.currentRepairToolNames());
1412
1382
  const requestSystemPrompt = joinPromptFragments([
1413
1383
  systemPrompt,
1414
1384
  finalChildSummaryStep ? CHILD_STEP_BUDGET_FINALIZATION_PROMPT : undefined,
1415
1385
  toolRuntime.hasSandboxBoundaryDenial() ? SANDBOX_BOUNDARY_DENIED_FOR_TURN : undefined,
1416
1386
  sandboxBoundaryFinalizationStep ? SANDBOX_BOUNDARY_FINALIZATION_PROMPT : undefined,
1417
1387
  ]);
1388
+ const resolveDispatch = (active) => ({
1389
+ systemPromptChars: requestSystemPrompt?.length ?? 0,
1390
+ activeTools: finalChildSummaryStep || sandboxBoundaryFinalizationStep
1391
+ ? []
1392
+ : boundaryAwareToolNames(active ?? plan.currentRepairToolNames()),
1393
+ });
1394
+ const shaped = requestProjection
1395
+ ? await requestProjection({
1396
+ completedSteps: completedProviderSteps,
1397
+ stepNumber: runtimeSteps,
1398
+ model,
1399
+ messages: requestMessages,
1400
+ resolveDispatch,
1401
+ })
1402
+ : undefined;
1403
+ const projectedMessages = shaped?.messages ?? requestMessages;
1404
+ const activeToolsForRequest = resolveDispatch(shaped?.activeTools).activeTools;
1418
1405
  providerRequestTracker?.setStep(runtimeSteps);
1419
1406
  let attemptMessages = projectedMessages;
1420
1407
  let providerAttempt = 1;
@@ -1726,7 +1713,7 @@ export class AiSdkBackend {
1726
1713
  !attemptSawContinuationMetadata;
1727
1714
  const attemptFailure = settledWatchdogTimeout?.error ??
1728
1715
  (providerOutcome.kind === 'completed' ? undefined : providerOutcome.failure);
1729
- if (attemptFailure && !scope.aborted && !midTurnState?.exhaustedDetail) {
1716
+ if (attemptFailure && !scope.aborted) {
1730
1717
  const failure = settledWatchdogTimeout || providerOutcome.kind === 'completed'
1731
1718
  ? this.modelAdapter.normalizeFailure(attemptFailure)
1732
1719
  : providerOutcome.failure;
@@ -1752,7 +1739,7 @@ export class AiSdkBackend {
1752
1739
  currentMessages: attemptMessages,
1753
1740
  providerTools,
1754
1741
  activeTools: activeToolsForRequest,
1755
- systemPromptChars: midTurnSystemPromptChars,
1742
+ systemPromptChars: requestSystemPrompt?.length ?? 0,
1756
1743
  queue,
1757
1744
  onDiagnosticPatch: onMidTurnDiagnosticPatch,
1758
1745
  origin: scope,
@@ -1778,6 +1765,7 @@ export class AiSdkBackend {
1778
1765
  model,
1779
1766
  messages: recovered.messages,
1780
1767
  activeTools: activeToolsForRequest,
1768
+ resolveDispatch,
1781
1769
  })
1782
1770
  : undefined;
1783
1771
  attemptMessages = recoveredProjection?.messages ?? recovered.messages;
@@ -1858,12 +1846,6 @@ export class AiSdkBackend {
1858
1846
  if (scope.aborted) {
1859
1847
  throw Object.assign(new Error('aborted'), { name: 'AbortError' });
1860
1848
  }
1861
- // Mid-turn exhaustion aborts the SDK stream, but streamText ends
1862
- // gracefully on abort instead of throwing; route to the explicit
1863
- // outcome regardless of how the stream wound down.
1864
- if (midTurnState?.exhaustedDetail) {
1865
- throw Object.assign(new Error(`mid-turn context budget exhausted: ${midTurnState.exhaustedDetail}`), { name: 'MidTurnContextBudgetExhaustedError' });
1866
- }
1867
1849
  // Catch-all: flush any residual step content if the provider closed the
1868
1850
  // stream without a trailing `finish-step` for the last step.
1869
1851
  const providerStepId = currentStepMessageId;
@@ -2048,6 +2030,13 @@ export class AiSdkBackend {
2048
2030
  }
2049
2031
  return undefined;
2050
2032
  })();
2033
+ // The anchor the NEXT turn estimates its first request from — see
2034
+ // `LastRequestAnchor`. `input` below is the sum across this send's
2035
+ // steps and anchors nothing. Either half missing (no usable usage
2036
+ // sample, or no mid-turn seam to measure the payload) drops the
2037
+ // whole pair and the next turn cold starts.
2038
+ const anchorInputTokens = finitePositive(lastStepInputTokens);
2039
+ const anchorPayloadChars = finitePositive(midTurnState?.lastRequestPayloadChars);
2051
2040
  // One shared usage payload for the durable message and the live
2052
2041
  // event: twin per-field literals drifted before (#4019), so a field
2053
2042
  // now has exactly one definition site.
@@ -2076,6 +2065,14 @@ export class AiSdkBackend {
2076
2065
  ? { contextRemaining: contextRemainingForUsage }
2077
2066
  : {}),
2078
2067
  ...(providerRequestTraceId ? { providerRequestTraceId } : {}),
2068
+ ...(anchorInputTokens !== undefined && anchorPayloadChars !== undefined
2069
+ ? {
2070
+ lastRequestAnchor: {
2071
+ inputTokens: anchorInputTokens,
2072
+ payloadChars: anchorPayloadChars,
2073
+ },
2074
+ }
2075
+ : {}),
2079
2076
  };
2080
2077
  const tu = {
2081
2078
  type: 'token_usage',
@@ -2162,21 +2159,7 @@ export class AiSdkBackend {
2162
2159
  // BOTH exits — user stop and provider error / watchdog timeout — so
2163
2160
  // partialOutputRetained reflects what the user actually saw.
2164
2161
  await flushStep().catch(() => { });
2165
- if (!scope.aborted && midTurnState?.exhaustedDetail) {
2166
- // Mid-turn compaction could not produce a provider-safe request: end
2167
- // the turn with the explicit first-class outcome, not a raw error.
2168
- streamErrorClass = 'ContextBudgetExhausted';
2169
- trace.modelStreamCompleted('context_budget_exhausted');
2170
- queue.push({
2171
- type: 'complete',
2172
- id: this.newId(),
2173
- turnId,
2174
- ts: this.now(),
2175
- stopReason: 'context_budget_exhausted',
2176
- contextBudgetExhaustedDetail: midTurnState.exhaustedDetail,
2177
- });
2178
- }
2179
- else if (scope.aborted) {
2162
+ if (scope.aborted) {
2180
2163
  queue.push({
2181
2164
  type: 'abort',
2182
2165
  id: this.newId(),
@@ -2591,7 +2574,7 @@ export class AiSdkBackend {
2591
2574
  * V0.1: text-only round-tripping. Tool calls / results within projected
2592
2575
  * history are deliberately NOT replayed unless RuntimeEvent native replay
2593
2576
  * is available for the provider. */
2594
- async buildPriorMessages(scope, input, automaticMemory) {
2577
+ async buildPriorMessages(scope, input, midTurnState, automaticMemory) {
2595
2578
  const priorStored = input.context.filter((message) => message.turnId !== input.turnId);
2596
2579
  if (!input.runtimeContext) {
2597
2580
  return {
@@ -2622,9 +2605,14 @@ export class AiSdkBackend {
2622
2605
  buildContextBudgetDiagnosticShell(priorRuntimeContext, runtimeContext, contextBudget), preparedContextBudget.diagnosticPatch);
2623
2606
  }
2624
2607
  const maxHistoryTokens = contextBudget?.maxHistoryEstimatedTokens;
2625
- const needsCompaction = maxHistoryTokens !== undefined &&
2608
+ // FALLBACK, not a second authority: step 0's anchored estimate measures the
2609
+ // whole outgoing payload against the real window, where this gate only
2610
+ // weighs prior history events at chars/4. It stands in only where that
2611
+ // estimate cannot reach — no anchor, no mid-turn seam, or no declared
2612
+ // window — so an oversized history never goes out unshaped.
2613
+ const needsCompaction = !(midTurnState?.capacity !== undefined && midTurnState.lastRequestInputTokens !== undefined) &&
2614
+ maxHistoryTokens !== undefined &&
2626
2615
  estimateRuntimeEventsTokens(runtimeContext, contextBudget?.charsPerToken) > maxHistoryTokens;
2627
- let compactionFailure;
2628
2616
  if (needsCompaction &&
2629
2617
  contextBudget?.historyCompact?.enabled === true &&
2630
2618
  this.compaction.hasHistoryCompactCheckpointWriter()) {
@@ -2670,25 +2658,9 @@ export class AiSdkBackend {
2670
2658
  });
2671
2659
  }
2672
2660
  }
2673
- if (compactResult.outcome.kind === 'failed') {
2674
- compactionFailure =
2675
- compactResult.outcome.reason === 'no_safe_completed_span'
2676
- ? 'no_safe_completed_span'
2677
- : isMalformedHistoryCompactSummaryReason(compactResult.outcome.reason)
2678
- ? compactResult.outcome.reason
2679
- : 'summarizer_failed';
2680
- }
2681
2661
  contextBudgetDiagnostic = mergeContextBudgetDiagnostic(contextBudgetDiagnostic ??
2682
2662
  buildContextBudgetDiagnosticShell(priorRuntimeContext, runtimeContext, contextBudget), compactResult.contextBudget ?? {});
2683
2663
  }
2684
- if (maxHistoryTokens !== undefined &&
2685
- estimateRuntimeEventsTokens(runtimeContext, contextBudget?.charsPerToken) > maxHistoryTokens) {
2686
- return {
2687
- status: 'context_budget_exhausted',
2688
- detail: compactionFailure ?? 'no_safe_completed_span',
2689
- ...(contextBudgetDiagnostic ? { contextBudget: contextBudgetDiagnostic } : {}),
2690
- };
2691
- }
2692
2664
  // The boundary belongs to the runtime-event projection above. A gate that
2693
2665
  // falls back to the stored-message projection returns a prompt no
2694
2666
  // checkpoint shaped, so it reports none rather than one the request never