maka-agent 0.2.0-dev.24.20260907 → 0.2.0-dev.25.20260908

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/README.md +38 -19
  2. package/README.zh-CN.md +34 -19
  3. package/dist/pi-transcript-tools.js +6 -0
  4. package/dist/pi-tui-layout.js +56 -10
  5. package/dist/pi-tui-pickers.js +102 -1
  6. package/dist/pi-tui-runner.js +156 -42
  7. package/dist/pi-tui-todo.js +221 -0
  8. package/dist/pi-tui-transcript-viewer.js +134 -7
  9. package/dist/runtime-host-cli-context.js +70 -13
  10. package/dist/runtime-host-handoff-surface.js +51 -26
  11. package/dist/runtime-host-local-handoff.js +11 -1
  12. package/dist/runtime-host-service-manager.js +0 -3
  13. package/dist/runtime-host-session-channel.js +13 -0
  14. package/dist/runtime-host-session-driver.js +42 -1
  15. package/dist/tui-copy-catalog.js +79 -3
  16. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  17. package/node_modules/@maka/core/dist/agent-run.js +1 -0
  18. package/node_modules/@maka/core/dist/attachments.js +3 -0
  19. package/node_modules/@maka/core/dist/canonical-json.js +27 -0
  20. package/node_modules/@maka/core/dist/capabilities.js +35 -0
  21. package/node_modules/@maka/core/dist/computer-use.js +0 -1
  22. package/node_modules/@maka/core/dist/display-redaction.js +18 -0
  23. package/node_modules/@maka/core/dist/llm-connections.js +13 -0
  24. package/node_modules/@maka/core/dist/model-call-attempt.js +2 -0
  25. package/node_modules/@maka/core/dist/model-metadata.js +4 -0
  26. package/node_modules/@maka/core/dist/redaction.js +35 -0
  27. package/node_modules/@maka/core/dist/run-composition.js +77 -2
  28. package/node_modules/@maka/core/dist/session.js +30 -4
  29. package/node_modules/@maka/core/dist/slash-command-catalog.js +1 -0
  30. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  31. package/node_modules/@maka/core/package.json +1 -0
  32. package/node_modules/@maka/eval/dist/experiment-directory.js +4 -13
  33. package/node_modules/@maka/runtime/dist/agent-run-inspect.js +0 -13
  34. package/node_modules/@maka/runtime/dist/agent-run.js +80 -1
  35. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +16 -8
  36. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +57 -50
  37. package/node_modules/@maka/runtime/dist/archive-read-tool.js +2 -2
  38. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +0 -16
  39. package/node_modules/@maka/runtime/dist/conversation-copy.js +153 -11
  40. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +3 -3
  41. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +69 -1
  42. package/node_modules/@maka/runtime/dist/mcp-tools.js +7 -2
  43. package/node_modules/@maka/runtime/dist/model-fetcher.js +42 -2
  44. package/node_modules/@maka/runtime/dist/model-history.js +0 -112
  45. package/node_modules/@maka/runtime/dist/plugin-runtime.js +20 -10
  46. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +205 -0
  47. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +8 -1
  48. package/node_modules/@maka/runtime/dist/request-shape.js +23 -0
  49. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +1 -1
  50. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +4 -0
  51. package/node_modules/@maka/runtime/dist/runtime-kernel.js +7 -0
  52. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +21 -0
  53. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +0 -5
  54. package/node_modules/@maka/runtime/dist/test-connection.js +0 -1
  55. package/node_modules/@maka/runtime/dist/tool-activation-identity.js +41 -0
  56. package/node_modules/@maka/runtime/dist/tool-availability.js +11 -1
  57. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +63 -1
  58. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +42 -12
  59. package/node_modules/@maka/runtime/dist/tool-result-archive.js +27 -4
  60. package/node_modules/@maka/runtime/package.json +1 -0
  61. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +35 -12
  62. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +2 -0
  63. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +19 -0
  64. package/node_modules/@maka/runtime-host/dist/control/endpoint.js +1 -3
  65. package/node_modules/@maka/runtime-host/dist/node-error.js +22 -0
  66. package/node_modules/@maka/runtime-host/dist/operator/managed-deployment.js +1 -3
  67. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +0 -1
  68. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +1 -1
  69. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +1 -3
  70. package/node_modules/@maka/runtime-host/dist/protocol/index.js +5 -1
  71. package/node_modules/@maka/runtime-host/dist/protocol/plan.js +1 -0
  72. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +27 -5
  73. package/node_modules/@maka/runtime-host/dist/protocol/project-catalog.js +2 -2
  74. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +31 -2
  75. package/node_modules/@maka/runtime-host/dist/server/agent-graph-coordinator.js +0 -3
  76. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +32 -32
  77. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +44 -9
  78. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +42 -14
  79. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +47 -22
  80. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  81. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  82. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +5 -2
  83. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +4 -0
  84. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +20 -2
  85. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +13 -3
  86. package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +46 -0
  87. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -1
  88. package/node_modules/@maka/storage/dist/codex-session-adapter.js +284 -196
  89. package/node_modules/@maka/storage/dist/git-exec.js +61 -0
  90. package/node_modules/@maka/storage/dist/git-worktree-child-executor.js +8 -35
  91. package/node_modules/@maka/storage/dist/goal-authority.js +2 -2
  92. package/node_modules/@maka/storage/dist/interaction-store.js +2 -2
  93. package/node_modules/@maka/storage/dist/project-catalog.js +2 -23
  94. package/node_modules/@maka/storage/dist/runtime-event-invariants.js +2 -2
  95. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +8 -3
  96. package/node_modules/@maka/storage/dist/scheduled-task-store.js +249 -283
  97. package/node_modules/@maka/storage/dist/session-bundle-manifest.js +5 -17
  98. package/node_modules/@maka/storage/dist/session-bundle-policy.js +2 -1
  99. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +2 -1
  100. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +1 -2
  101. package/node_modules/@maka/storage/dist/storage-id.js +28 -0
  102. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +31 -4
  103. package/node_modules/@maka/storage/dist/workspace-identity.js +2 -15
  104. package/node_modules/@maka/storage/dist/workspace-version-authority-internal.js +1 -8
  105. package/package.json +1 -1
@@ -31,11 +31,13 @@ import { buildToolOperationId } from './runtime-commit-sink.js';
31
31
  import { isContinuationStartRuntimeEvent } from './runtime-event-read-model.js';
32
32
  import { runtimeHandoffPause } from '@maka/core/runtime-handoff';
33
33
  import { buildToolResultArchiveResourceRef, parseToolResultArchiveResourceRef, } from './tool-result-archive-resource.js';
34
- import { deserializeToolResultArchive, isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
34
+ import { deserializeToolResultArchive, isArchivedToolResultPlaceholder, buildLedgerArchivedToolResultPlaceholder, } from './tool-result-archive.js';
35
35
  import { rewriteDurableToolResultProjectionArtifactRefs } from './durable-tool-result-projection.js';
36
- import { buildModelProjectionTransition, decodeModelProjectionTransition, MODEL_PROJECTION_TRANSITION_EVENT_TYPE, } from '@maka/core/model-projection-transition';
36
+ import { buildModelProjectionTransition, durableToolResultProjectionDigest, decodeModelProjectionTransition, MODEL_PROJECTION_TRANSITION_EVENT_TYPE, } from '@maka/core/model-projection-transition';
37
37
  import { baseToolResultProjection, decodeLedgerTransition, reduceEffectiveModelProjections, } from './model-projection-transition-ledger.js';
38
38
  import { archivedToolResultProjection } from './tool-result-archive-transition.js';
39
+ import { serializeToolResultProjectionV1 } from './tool-result-archive-encoding.js';
40
+ import { createHash } from 'node:crypto';
39
41
  /** Walks every typed StorageRef site reached by conversation-copy rewriting. */
40
42
  function collectConversationCopyStorageRefs(input) {
41
43
  const refs = [];
@@ -308,6 +310,7 @@ export async function cloneConversationRuntimeLedger(input) {
308
310
  runtimeEventIds,
309
311
  providerTraceIds,
310
312
  agentRunEventIds: operationalEventIds,
313
+ ledgerArchives: new Map(),
311
314
  };
312
315
  const clonedEventBySourceId = new Map();
313
316
  for (const plan of flattenedPlans) {
@@ -328,6 +331,64 @@ export async function cloneConversationRuntimeLedger(input) {
328
331
  // successor is rebuilt against the projection it actually replaces.
329
332
  const transitionIds = new Map();
330
333
  const transitionState = new Map();
334
+ const clonedTransitions = new Map();
335
+ const visiting = new Set();
336
+ const finished = new Set();
337
+ const transitionsByTarget = new Map();
338
+ for (const plan of flattenedPlans) {
339
+ for (const record of plan.operationalEvents) {
340
+ if (record.type !== MODEL_PROJECTION_TRANSITION_EVENT_TYPE)
341
+ continue;
342
+ const transition = decodeModelProjectionTransition(record.data?.transition, record.sessionId);
343
+ const group = transitionsByTarget.get(transition.target.runtimeEventId) ?? [];
344
+ group.push(record);
345
+ transitionsByTarget.set(transition.target.runtimeEventId, group);
346
+ }
347
+ }
348
+ // ArchiveRead can itself be archived. Resolve its referenced target first,
349
+ // then rebuild this result's transitions against its final copied projection.
350
+ const finishTarget = (sourceId) => {
351
+ if (finished.has(sourceId))
352
+ return;
353
+ if (visiting.has(sourceId))
354
+ throw new Error('Cyclic copied archive reference');
355
+ visiting.add(sourceId);
356
+ const target = clonedEventBySourceId.get(sourceId);
357
+ if (target?.content?.kind === 'function_response' && target.content.name === 'ArchiveRead') {
358
+ const resolveResult = (value) => rewriteArchiveReadResult(value, references, (ref) => {
359
+ const identity = parseToolResultArchiveResourceRef(ref);
360
+ if (identity?.storage === 'ledger' && clonedEventBySourceId.has(identity.runtimeEventId))
361
+ finishTarget(identity.runtimeEventId);
362
+ });
363
+ target.content.result = resolveResult(target.content.result);
364
+ const projection = target.content.modelProjection;
365
+ if (projection?.kind === 'json')
366
+ target.content.modelProjection = {
367
+ ...projection,
368
+ value: resolveResult(projection.value),
369
+ };
370
+ }
371
+ for (const record of transitionsByTarget.get(sourceId) ?? []) {
372
+ clonedTransitions.set(record, cloneModelProjectionTransition(record, references, clonedEventBySourceId, transitionIds, transitionState));
373
+ }
374
+ visiting.delete(sourceId);
375
+ finished.add(sourceId);
376
+ };
377
+ for (const sourceId of clonedEventBySourceId.keys())
378
+ finishTarget(sourceId);
379
+ for (const event of clonedEventBySourceId.values()) {
380
+ if (event.content?.kind === 'text')
381
+ event.content.text = rewriteLedgerArchiveText(event.content.text, references);
382
+ if (event.content?.kind === 'function_call' && event.content.name === 'ArchiveRead') {
383
+ const args = event.content.args;
384
+ if (args && typeof args === 'object' && 'ref' in args && typeof args.ref === 'string') {
385
+ event.content = {
386
+ ...event.content,
387
+ args: { ...args, ref: rewriteLedgerArchiveText(args.ref, references) },
388
+ };
389
+ }
390
+ }
391
+ }
331
392
  const preparedPlans = flattenedPlans.map((plan) => {
332
393
  const runId = runIds.get(plan.run.runId);
333
394
  const clonedOperationalEvents = plan.operationalEvents.flatMap((event) => {
@@ -335,7 +396,7 @@ export async function cloneConversationRuntimeLedger(input) {
335
396
  sessionId: input.referenceMap.targetSessionId,
336
397
  runId,
337
398
  eventId: operationalEventIds.get(event.id),
338
- }, references, sourceCompactableEvents.get(plan.run.runId) ?? [], clonedEventBySourceId, checkpointIds, transitionIds, transitionState, providerTraceIds, logicalCallIds);
399
+ }, references, sourceCompactableEvents.get(plan.run.runId) ?? [], clonedEventBySourceId, checkpointIds, providerTraceIds, logicalCallIds, clonedTransitions);
339
400
  return clonedEvent ? [clonedEvent] : [];
340
401
  });
341
402
  const terminalEvent = plan.terminal.kind === 'fact'
@@ -351,7 +412,22 @@ export async function cloneConversationRuntimeLedger(input) {
351
412
  terminalEvent,
352
413
  };
353
414
  });
354
- const copiedMessages = input.copiedMessages.map((message) => rewriteConversationCopyMessage(message, references));
415
+ const archiveReadCalls = new Set(flattenedPlans.flatMap((plan) => plan.events.flatMap((event) => event.content?.kind === 'function_response' && event.content.name === 'ArchiveRead'
416
+ ? [`${event.turnId}:${event.content.id}`]
417
+ : [])));
418
+ const copiedMessages = input.copiedMessages.map((message) => {
419
+ const copied = rewriteConversationCopyMessage(message, references);
420
+ if (copied.type === 'user' || copied.type === 'assistant')
421
+ return { ...copied, text: rewriteLedgerArchiveText(copied.text, references) };
422
+ if (copied.type === 'tool_result' &&
423
+ archiveReadCalls.has(`${copied.turnId}:${copied.toolUseId}`)) {
424
+ return {
425
+ ...copied,
426
+ content: rewriteArchiveReadResult(copied.content, references),
427
+ };
428
+ }
429
+ return copied;
430
+ });
355
431
  const importedSourceEventIds = new Set();
356
432
  const orderedBatches = input.plan.inlineRuntimeEvents.flatMap((event) => {
357
433
  const cloned = clonedEventBySourceId.get(event.id);
@@ -400,6 +476,33 @@ export async function cloneConversationRuntimeLedger(input) {
400
476
  })),
401
477
  };
402
478
  }
479
+ function rewriteLedgerArchiveText(text, references) {
480
+ for (const [source, target] of references.ledgerArchives ?? [])
481
+ text = text.split(source).join(target.resourceRef);
482
+ return text;
483
+ }
484
+ /** Only ArchiveRead's defined envelope is rewritten, never its opaque content/items. */
485
+ function rewriteArchiveReadResult(value, references, before) {
486
+ if (!value || typeof value !== 'object' || Array.isArray(value))
487
+ return value;
488
+ const record = value;
489
+ if (record.kind === 'json')
490
+ return { ...record, value: rewriteArchiveReadResult(record.value, references, before) };
491
+ if (record.kind !== 'tool_result_archive' || typeof record.ref !== 'string')
492
+ return value;
493
+ before?.(record.ref);
494
+ const mapped = references.ledgerArchives?.get(record.ref);
495
+ if (!mapped)
496
+ return value;
497
+ return {
498
+ ...record,
499
+ ref: mapped.resourceRef,
500
+ ...(record.storage === 'ledger' && typeof record.runtimeEventId === 'string'
501
+ ? { runtimeEventId: mapped.runtimeEventId }
502
+ : {}),
503
+ ...(typeof record.originalBytes === 'number' ? { originalBytes: mapped.originalBytes } : {}),
504
+ };
505
+ }
403
506
  async function loadConversationCopyRunEvents(sourceRuns, sourceEvents, copyTurnIds, runtimeEventStore) {
404
507
  const copiedTurnIds = new Set(copyTurnIds);
405
508
  return Promise.all(sourceRuns.flatMap((run) => {
@@ -546,7 +649,7 @@ export function collectConversationCopySessionFileRefs(input) {
546
649
  }
547
650
  return refs;
548
651
  }
549
- function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clonedRuntimeEvents, checkpointIds, transitionIds, transitionState, providerTraceIds, logicalCallIds) {
652
+ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clonedRuntimeEvents, checkpointIds, providerTraceIds, logicalCallIds, clonedTransitions) {
550
653
  if (event.type === 'event_corrupt') {
551
654
  throw new Error(`Cannot copy corrupt AgentRun event ${event.id}`);
552
655
  }
@@ -601,7 +704,7 @@ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clo
601
704
  const checkpoint = buildHistoryCompactCheckpoint({
602
705
  sessionId: references.targetSessionId,
603
706
  coveredRuntimeEvents,
604
- summary: sourceCheckpoint.summary,
707
+ summary: rewriteLedgerArchiveText(sourceCheckpoint.summary, references),
605
708
  highWaterName: sourceCheckpoint.highWaterName,
606
709
  highWaterSeq: sourceCheckpoint.highWaterSeq,
607
710
  now: sourceCheckpoint.createdAt,
@@ -622,7 +725,7 @@ function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clo
622
725
  };
623
726
  }
624
727
  else if (event.type === MODEL_PROJECTION_TRANSITION_EVENT_TYPE) {
625
- const cloned = cloneModelProjectionTransition(event, references, clonedRuntimeEvents, transitionIds, transitionState);
728
+ const cloned = clonedTransitions.get(event);
626
729
  // Every transition whose target is in the copied slice was gathered into
627
730
  // this run's ledger, wherever it was recorded. So a transition that finds no
628
731
  // cloned target has genuinely lost its target as well, and dropping it
@@ -660,16 +763,37 @@ function cloneModelProjectionTransition(event, references, clonedRuntimeEvents,
660
763
  const clonedTarget = clonedRuntimeEvents.get(source.target.runtimeEventId);
661
764
  if (!clonedTarget)
662
765
  return null;
663
- const placeholder = source.replacement.kind === 'json' ? source.replacement.value : undefined;
664
- if (!isArchivedToolResultPlaceholder(placeholder)) {
766
+ const rawPlaceholder = source.replacement.kind === 'json' ? source.replacement.value : undefined;
767
+ if (!isArchivedToolResultPlaceholder(rawPlaceholder)) {
665
768
  throw new Error(`Cannot copy unsupported model projection transition ${event.id}`);
666
769
  }
770
+ const placeholder = rawPlaceholder;
667
771
  const existing = transitionState.get(clonedTarget.id);
668
772
  const sourceProjection = existing?.projection ?? baseToolResultProjection(clonedTarget);
669
773
  if (!sourceProjection) {
670
774
  throw new Error(`Cannot copy model projection transition ${event.id} onto its target`);
671
775
  }
672
- const rewritten = rewriteArchivedToolResult(placeholder, references);
776
+ let rewritten;
777
+ if (placeholder.rewriteVersion === 2) {
778
+ const { previousTransitionId: _previous, ...rest } = placeholder;
779
+ const serialized = serializeToolResultProjectionV1(sourceProjection);
780
+ rewritten = buildLedgerArchivedToolResultPlaceholder({
781
+ ...rest,
782
+ runtimeEventId: clonedTarget.id,
783
+ sourceProjectionDigest: durableToolResultProjectionDigest(sourceProjection),
784
+ bodySha256: createHash('sha256').update(serialized).digest('hex'),
785
+ originalBytes: Buffer.byteLength(serialized),
786
+ ...(source.previousTransitionId
787
+ ? {
788
+ previousTransitionId: requiredMappedId(transitionIds, source.previousTransitionId, 'model projection transition'),
789
+ }
790
+ : {}),
791
+ });
792
+ references.ledgerArchives?.set(buildToolResultArchiveResourceRef(placeholder), rewritten);
793
+ }
794
+ else {
795
+ rewritten = rewriteArchivedToolResult(placeholder, references);
796
+ }
673
797
  const transition = buildModelProjectionTransition({
674
798
  sessionId: references.targetSessionId,
675
799
  target: {
@@ -1030,6 +1154,18 @@ function rewriteToolResultContent(content, references) {
1030
1154
  return { ...content, ref: rewriteStorageRef(content.ref, references) };
1031
1155
  }
1032
1156
  if (content.kind === 'archived_tool_result') {
1157
+ if (content.rewriteVersion === 2 && content.resourceRef) {
1158
+ const rewritten = references.ledgerArchives?.get(content.resourceRef);
1159
+ if (!rewritten)
1160
+ throw new Error('Cannot copy ledger archive without its committed transition');
1161
+ return {
1162
+ ...content,
1163
+ runtimeEventId: rewritten.runtimeEventId,
1164
+ resourceRef: rewritten.resourceRef,
1165
+ bodySha256: rewritten.bodySha256,
1166
+ originalBytes: rewritten.originalBytes,
1167
+ };
1168
+ }
1033
1169
  const snapshot = rewriteArchivedSnapshot(content, references);
1034
1170
  if (snapshot)
1035
1171
  return snapshot;
@@ -1257,6 +1393,12 @@ function rewriteProjectionArtifactRef(ref, references) {
1257
1393
  return rewritten;
1258
1394
  }
1259
1395
  function rewriteArchivedToolResult(value, references) {
1396
+ if (value.rewriteVersion === 2) {
1397
+ const rewritten = references.ledgerArchives?.get(buildToolResultArchiveResourceRef(value));
1398
+ if (!rewritten)
1399
+ throw new Error('Cannot copy ledger archive without its committed transition');
1400
+ return rewritten;
1401
+ }
1260
1402
  const artifactId = rewriteOwnedArtifactId(value.artifactId, references);
1261
1403
  const resource = value.resourceRef
1262
1404
  ? parseToolResultArchiveResourceRef(value.resourceRef)
@@ -1265,7 +1407,7 @@ function rewriteArchivedToolResult(value, references) {
1265
1407
  ...value,
1266
1408
  runtimeEventId: rewriteOwnedId(value.runtimeEventId, references.runtimeEventIds, 'RuntimeEvent'),
1267
1409
  artifactId,
1268
- ...(resource && artifactId !== value.artifactId
1410
+ ...(resource && resource.storage !== 'ledger' && artifactId !== value.artifactId
1269
1411
  ? {
1270
1412
  resourceRef: buildToolResultArchiveResourceRef({
1271
1413
  ...resource,
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { createGitHubCopilotAccountTokens, GITHUB_COPILOT_DEFAULT_API_ENDPOINT, isSupportedGitHubCopilotAccountToken, } from './subscription-credentials.js';
20
- import { fetchGitHubCopilotModels } from './model-fetcher.js';
20
+ import { fetchGitHubCopilotModels, GitHubCopilotModelPolicyError } from './model-fetcher.js';
21
21
  import { ConnectionEffectHttpError } from './connection-effect-outcome.js';
22
22
  import { OAUTH_LOGIN_MAX_TOKEN_CHARS, OAuthTokenEndpointError, requestOAuthEndpointJson, } from './oauth-login.js';
23
23
  import { OAUTH_PROVIDER_CONTRACTS, OAuthDeviceAuthorizationExpiredError, oauthExpiresAt, requireOAuthBoundedString, requireOAuthDataRecord, requireOAuthPositiveInteger, } from './oauth-provider-contracts.js';
@@ -185,8 +185,8 @@ export async function verifyGitHubCopilotModelEntitlement(input) {
185
185
  // body tell us nothing about the subscription, and reporting them as
186
186
  // ineligibility would send a paying user back through a device login that
187
187
  // was never the problem.
188
- if (error instanceof ConnectionEffectHttpError &&
189
- (error.status === 401 || error.status === 403)) {
188
+ if (error instanceof GitHubCopilotModelPolicyError ||
189
+ (error instanceof ConnectionEffectHttpError && (error.status === 401 || error.status === 403))) {
190
190
  throw new GitHubCopilotEntitlementError({ cause: error });
191
191
  }
192
192
  throw new GitHubCopilotEntitlementUnavailableError(error instanceof ConnectionEffectHttpError ? error.status : undefined, { cause: error });
@@ -18,9 +18,11 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { decodeDurableToolResultProjection } from '@maka/core/durable-tool-result-projection';
21
+ import { durableToolResultProjectionDigest, } from '@maka/core/model-projection-transition';
21
22
  import { decodeLedgerTransition, reduceEffectiveModelProjections, } from './model-projection-transition-ledger.js';
22
23
  import { isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
23
24
  import { serializeToolResultProjectionV1 } from './tool-result-archive-encoding.js';
25
+ import { TOOL_RESULT_ARCHIVE_EVIDENCE_MAX_BYTES, TOOL_RESULT_ARCHIVE_EVIDENCE_MAX_TRANSITIONS, } from '@maka/core/tool-result-archive-evidence';
24
26
  /**
25
27
  * Read-only v1 reconstruction. It never calls a live tool projector, reads an
26
28
  * Artifact, changes history, or authorizes access from a hash alone.
@@ -80,7 +82,13 @@ export function createLedgerToolResultArchiveReader(evidence) {
80
82
  const replacement = transition.replacement;
81
83
  const placeholder = replacement.kind === 'json' ? replacement.value : undefined;
82
84
  if (isArchivedToolResultPlaceholder(placeholder) &&
83
- placeholder.artifactId === request.artifactId) {
85
+ ((placeholder.rewriteVersion === 1 &&
86
+ request.rewriteVersion === 1 &&
87
+ placeholder.artifactId === request.artifactId) ||
88
+ (placeholder.rewriteVersion === 2 &&
89
+ request.rewriteVersion === 2 &&
90
+ placeholder.sourceProjectionDigest === request.sourceProjectionDigest &&
91
+ placeholder.previousTransitionId === request.previousTransitionId))) {
84
92
  if (placeholder.runtimeEventId !== request.runtimeEventId ||
85
93
  placeholder.toolCallId !== request.toolCallId ||
86
94
  placeholder.toolName !== request.toolName ||
@@ -88,6 +96,10 @@ export function createLedgerToolResultArchiveReader(evidence) {
88
96
  placeholder.originalBytes !== request.originalBytes ||
89
97
  placeholder.rewriteVersion !== request.rewriteVersion)
90
98
  return { ok: false, reason: 'source_mismatch' };
99
+ if (placeholder.rewriteVersion === 2 &&
100
+ (placeholder.sourceProjectionDigest !== transition.sourceProjectionDigest ||
101
+ placeholder.previousTransitionId !== transition.previousTransitionId))
102
+ return { ok: false, reason: 'corrupt' };
91
103
  const serializedResult = serializeToolResultProjectionV1(source);
92
104
  if (Buffer.byteLength(serializedResult, 'utf8') !== request.originalBytes)
93
105
  return { ok: false, reason: 'size_mismatch' };
@@ -104,3 +116,59 @@ export function createLedgerToolResultArchiveReader(evidence) {
104
116
  }
105
117
  };
106
118
  }
119
+ export function createLedgerArchiveResourceReader(evidence) {
120
+ const reader = createLedgerToolResultArchiveReader(evidence);
121
+ return (input) => reader({
122
+ ...input,
123
+ kind: 'maka.archived_tool_result',
124
+ rewriteVersion: 2,
125
+ originalEstimatedTokens: 1,
126
+ reason: 'stale_tool_result_pruned_before_compact',
127
+ });
128
+ }
129
+ /** Verify reconstructibility before committing a replacement; does not write any payload. */
130
+ export function createLedgerArchivePreparer(evidence) {
131
+ return async (input) => {
132
+ const request = { ...input };
133
+ const loaded = await evidence.read({
134
+ sessionId: request.sessionId,
135
+ runtimeEventId: request.runtimeEventId,
136
+ });
137
+ if (!loaded.ok ||
138
+ loaded.transitions.length >= TOOL_RESULT_ARCHIVE_EVIDENCE_MAX_TRANSITIONS ||
139
+ loaded.storedBytes === undefined ||
140
+ loaded.storedBytes > TOOL_RESULT_ARCHIVE_EVIDENCE_MAX_BYTES - 64 * 1024)
141
+ return;
142
+ const content = loaded.event.content;
143
+ if (loaded.event.sessionId !== request.sessionId ||
144
+ loaded.event.id !== request.runtimeEventId ||
145
+ content?.kind !== 'function_response' ||
146
+ content.providerExecuted ||
147
+ !content.modelProjection ||
148
+ content.id !== request.toolCallId ||
149
+ content.name !== request.toolName)
150
+ return;
151
+ const transitions = [];
152
+ for (const event of loaded.transitions) {
153
+ const decoded = decodeLedgerTransition(event, request.sessionId);
154
+ if (!decoded || decoded.target.runtimeEventId !== request.runtimeEventId)
155
+ return;
156
+ transitions.push(decoded);
157
+ }
158
+ const reduced = reduceEffectiveModelProjections([loaded.event], transitions);
159
+ const previous = reduced.applied.at(-1);
160
+ if (previous?.transitionId !== request.previousTransitionId)
161
+ return;
162
+ const source = previous?.replacement ?? content.modelProjection;
163
+ if (source.kind === 'json' && isArchivedToolResultPlaceholder(source.value))
164
+ return;
165
+ if (durableToolResultProjectionDigest(source) !== request.sourceProjectionDigest)
166
+ return;
167
+ const body = serializeToolResultProjectionV1(source);
168
+ if (body !== request.serializedResult ||
169
+ Buffer.byteLength(body) !== request.originalBytes ||
170
+ createHash('sha256').update(body).digest('hex') !== request.bodySha256)
171
+ return;
172
+ return { ledger: true };
173
+ };
174
+ }
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { jsonSchema } from 'ai';
21
+ import { REQUEST_COMPOSITION_MAX_TOOL_DESCRIPTION_LENGTH } from '@maka/core/run-composition';
21
22
  import { truncateUtf16Safe } from '@maka/core/text-sanitize';
22
23
  const MAX_PROVIDER_TOOL_NAME = 64;
23
24
  const HASH_CHARS = 10;
@@ -49,8 +50,7 @@ export function buildMcpToolsWithIdentities(provider, options = {}) {
49
50
  toolName: descriptor.name,
50
51
  tool: {
51
52
  name,
52
- description: descriptor.description?.trim() ||
53
- `MCP tool ${descriptor.name} provided by ${descriptor.serverId}`,
53
+ description: mcpToolDescription(descriptor),
54
54
  displayName: descriptor.annotations?.title?.trim() || descriptor.name,
55
55
  activityKind: options.activityKindForDescriptor?.(descriptor) ?? 'tool',
56
56
  // MCP annotations are advisory provider claims, not a security boundary.
@@ -129,6 +129,11 @@ export function buildMcpToolsWithIdentities(provider, options = {}) {
129
129
  };
130
130
  });
131
131
  }
132
+ function mcpToolDescription(descriptor) {
133
+ const description = descriptor.description?.trim() ||
134
+ `MCP tool ${descriptor.name} provided by ${descriptor.serverId}`;
135
+ return description.slice(0, REQUEST_COMPOSITION_MAX_TOOL_DESCRIPTION_LENGTH);
136
+ }
132
137
  export function mcpProxyToolName(serverId, toolName) {
133
138
  const raw = `mcp__${sanitizeNamePart(serverId)}__${sanitizeNamePart(toolName)}`;
134
139
  if (raw.length <= MAX_PROVIDER_TOOL_NAME)
@@ -257,6 +257,12 @@ function normalizeConnectionEffectModels(models) {
257
257
  });
258
258
  }
259
259
  }
260
+ export class GitHubCopilotModelPolicyError extends Error {
261
+ constructor() {
262
+ super('GitHub Copilot model policy is not enabled');
263
+ this.name = 'GitHubCopilotModelPolicyError';
264
+ }
265
+ }
260
266
  export async function fetchGitHubCopilotModels(baseUrl, accessToken, fetchFn) {
261
267
  const response = await fetchForConnectionEffect(fetchFn, `${stripTrailing(baseUrl)}/models`, {
262
268
  headers: {
@@ -272,7 +278,12 @@ export async function fetchGitHubCopilotModels(baseUrl, accessToken, fetchFn) {
272
278
  throw new ConnectionEffectHttpError(response.status);
273
279
  }
274
280
  const payload = await readProviderJson(response);
275
- return providerObjectArray(payload.data, 'GitHub Copilot models', true).flatMap(toGitHubCopilotModelInfo);
281
+ const rawModels = providerObjectArray(payload.data, 'GitHub Copilot models', true);
282
+ const models = rawModels.flatMap(toGitHubCopilotModelInfo);
283
+ if (models.length === 0 && rawModels.some(isGitHubCopilotModelBlockedByPolicy)) {
284
+ throw new GitHubCopilotModelPolicyError();
285
+ }
286
+ return models;
276
287
  }
277
288
  /**
278
289
  * Discovery error carrying the HTTP status, so callers (syncOpenAiCodexConnection)
@@ -347,7 +358,12 @@ function toGitHubCopilotModelInfo(model) {
347
358
  if (typeof model.id !== 'string' ||
348
359
  !model.id ||
349
360
  model.model_picker_enabled !== true ||
350
- model.policy?.state === 'disabled' ||
361
+ // GitHub historically returned enabled/disabled/unconfigured policy gates.
362
+ // A policy-free model needs no acknowledgement; when the gate is present,
363
+ // Maka can use the model only after another client has enabled it. Maka has
364
+ // no policy-acceptance flow, so fail closed over unconfigured and unknown
365
+ // states instead of advertising a model that inference will reject.
366
+ !isGitHubCopilotModelPolicyEnabled(model.policy) ||
351
367
  model.capabilities?.supports?.tool_calls !== true)
352
368
  return [];
353
369
  assertOptionalArray(model.supported_endpoints, 'model supported_endpoints');
@@ -385,6 +401,28 @@ function toGitHubCopilotModelInfo(model) {
385
401
  },
386
402
  ];
387
403
  }
404
+ function isGitHubCopilotModelPolicyEnabled(policy) {
405
+ if (policy === undefined)
406
+ return true;
407
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy))
408
+ return false;
409
+ return policy.state === 'enabled';
410
+ }
411
+ function isGitHubCopilotModelBlockedByPolicy(model) {
412
+ if (typeof model.id !== 'string' ||
413
+ !model.id ||
414
+ model.model_picker_enabled !== true ||
415
+ model.capabilities?.supports?.tool_calls !== true ||
416
+ !Array.isArray(model.supported_endpoints) ||
417
+ !model.supported_endpoints.some((endpoint) => ['/v1/messages', '/responses', '/chat/completions'].includes(endpoint))) {
418
+ return false;
419
+ }
420
+ if (!model.policy || typeof model.policy !== 'object' || Array.isArray(model.policy)) {
421
+ return false;
422
+ }
423
+ const state = model.policy.state;
424
+ return state === 'disabled' || state === 'unconfigured';
425
+ }
388
426
  async function fetchCohereModels(baseUrl, apiKey, fetchFn) {
389
427
  const root = stripTrailing(baseUrl).replace(/\/v2$/, '');
390
428
  const models = [];
@@ -655,6 +693,8 @@ function nextProviderPageToken(value) {
655
693
  return value;
656
694
  }
657
695
  function classifyDiscoveryError(error) {
696
+ if (error instanceof GitHubCopilotModelPolicyError)
697
+ return { kind: 'auth' };
658
698
  if (error instanceof ConnectionEffectFetchError)
659
699
  return { kind: error.kind };
660
700
  if (error instanceof ConnectionEffectHttpError) {
@@ -278,56 +278,6 @@ export function buildRuntimeEventReplayTimeline(items) {
278
278
  function replayToolIdentity(invocationId, toolCallId) {
279
279
  return JSON.stringify([invocationId, toolCallId]);
280
280
  }
281
- // ============================================================================
282
- // Projection
283
- // ============================================================================
284
- /**
285
- * Build the model-visible history from a RuntimeEvent stream.
286
- *
287
- * Events SHOULD be supplied in causal order; the projection preserves
288
- * input order. Partial events are always excluded — callers MUST NOT
289
- * replay transient streaming chunks into the next model call.
290
- *
291
- * The default options match the durable-history policy: user/model text
292
- * and tool calls/responses are kept; thinking, system notes, token usage,
293
- * permission acks, and diagnostics are dropped.
294
- */
295
- export function buildModelHistoryFromRuntimeEvents(events, options = {}) {
296
- const includeToolEvents = options.includeToolEvents ?? true;
297
- const includeSystemEvents = options.includeSystemEvents ?? false;
298
- const includeThinking = options.includeThinking ?? false;
299
- const out = [];
300
- for (const event of events) {
301
- // 1. Never replay transient streaming chunks.
302
- if (isPartialRuntimeEvent(event))
303
- continue;
304
- // 2. Only model-visible content kinds (text/thinking/function_*).
305
- if (!runtimeEventHasModelVisibleContent(event))
306
- continue;
307
- const content = event.content;
308
- if (!content)
309
- continue;
310
- // 3. System-role events are UI notes by default; opt in for
311
- // model-injected system instructions.
312
- if (event.role === 'system' && !includeSystemEvents)
313
- continue;
314
- // 4. Thinking replay is provider-specific; opt in.
315
- if (content.kind === 'thinking' && !includeThinking)
316
- continue;
317
- // 5. Tool function_call / function_response; opt out for text-only.
318
- if (!includeToolEvents &&
319
- (content.kind === 'function_call' || content.kind === 'function_response')) {
320
- continue;
321
- }
322
- out.push({
323
- role: event.role,
324
- content,
325
- ts: event.ts,
326
- eventId: event.id,
327
- });
328
- }
329
- return out;
330
- }
331
281
  /**
332
282
  * Collect the turn ids that contain tool activity (function_call /
333
283
  * function_response) from a RuntimeEvent ledger. Pass the result as
@@ -645,46 +595,6 @@ export function buildRuntimeEventModelReplayPlan(events, options = {}) {
645
595
  semanticKinds.includes('tool_result'),
646
596
  };
647
597
  }
648
- /**
649
- * Convert projected RuntimeEvent history into the current AI SDK text-only
650
- * message shape. Tool/function and thinking entries are intentionally skipped.
651
- */
652
- export function buildTextModelMessagesFromRuntimeEvents(events, options = {}) {
653
- const history = buildModelHistoryFromRuntimeEvents(events, {
654
- includeToolEvents: false,
655
- includeSystemEvents: options.includeSystemEvents ?? false,
656
- includeThinking: false,
657
- });
658
- const out = [];
659
- for (const entry of history) {
660
- if (entry.content.kind !== 'text')
661
- continue;
662
- if (entry.role === 'tool')
663
- continue;
664
- if (entry.role === 'system' && !options.includeSystemEvents)
665
- continue;
666
- const role = entry.role === 'model'
667
- ? 'assistant'
668
- : entry.role === 'user'
669
- ? 'user'
670
- : entry.role === 'system'
671
- ? 'system'
672
- : undefined;
673
- if (!role)
674
- continue;
675
- const steering = entry.content.steering === true && role === 'user';
676
- out.push({
677
- role,
678
- content: steering
679
- ? buildSteeringEnvelope(formatTextWithInlineRefs(entry.content))
680
- : formatTextWithInlineRefs(entry.content),
681
- // Keep the structured identity even in the text-only shape: dedupe
682
- // against the live injection set works by ledger event id.
683
- ...(steering ? { providerOptions: steeringProviderOptions(entry.eventId) } : {}),
684
- });
685
- }
686
- return out;
687
- }
688
598
  function modelTextRole(role) {
689
599
  switch (role) {
690
600
  case 'user':
@@ -770,28 +680,6 @@ export function steeringMessagesMissingFromBase(injected, baseMessages) {
770
680
  return eventId === undefined || !present.has(eventId);
771
681
  });
772
682
  }
773
- /**
774
- * The messages with THIS TURN'S injected steering removed (transport-retry
775
- * base). Only the injected set may be stripped: the retry attempt's own
776
- * request projection re-appends exactly that accumulator, while a historical,
777
- * ledger-replayed steering message (same marker, different event id) is part
778
- * of the base that nothing re-appends — stripping it would erase it from
779
- * every post-retry request.
780
- */
781
- export function stripSteeringMessages(messages, injected) {
782
- const ids = new Set();
783
- for (const message of injected) {
784
- const eventId = steeringEventIdOf(message);
785
- if (eventId !== undefined)
786
- ids.add(eventId);
787
- }
788
- if (ids.size === 0)
789
- return [...messages];
790
- return messages.filter((message) => {
791
- const eventId = steeringEventIdOf(message);
792
- return eventId === undefined || !ids.has(eventId);
793
- });
794
- }
795
683
  /**
796
684
  * Fold a user turn's inline references into its model-facing text. Attachments
797
685
  * render as a name/type block with exact Read instructions when the reference