maka-agent 0.2.0-dev.6.20260830 → 0.2.0-dev.9.20260831

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 (86) hide show
  1. package/dist/cli-core.js +11 -0
  2. package/dist/runtime-host-cli.js +44 -0
  3. package/dist/runtime-host-installed-update-activator.js +70 -33
  4. package/dist/runtime-host-installed-update-coordinator.js +11 -96
  5. package/dist/runtime-host-lifecycle-transaction.js +2 -0
  6. package/dist/runtime-host-local-handoff.js +169 -38
  7. package/dist/runtime-host-local-source-retirement.js +103 -0
  8. package/dist/runtime-host-local-target-activation.js +141 -0
  9. package/dist/runtime-host-peer-management-command.js +10 -4
  10. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  11. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  12. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  13. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  14. package/node_modules/@maka/core/dist/agent-run.js +0 -2
  15. package/node_modules/@maka/core/dist/artifacts.js +23 -15
  16. package/node_modules/@maka/core/dist/durable-tool-result-projection.js +124 -0
  17. package/node_modules/@maka/core/dist/foreign-session.js +1 -1
  18. package/node_modules/@maka/core/dist/llm-connections.js +20 -0
  19. package/node_modules/@maka/core/dist/runtime-event.js +28 -3
  20. package/node_modules/@maka/core/dist/session-name.js +0 -1
  21. package/node_modules/@maka/core/dist/task-ledger.js +6 -134
  22. package/node_modules/@maka/core/dist/usage-record-schema.js +1 -0
  23. package/node_modules/@maka/core/package.json +1 -0
  24. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +97 -133
  25. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +4 -18
  26. package/node_modules/@maka/runtime/dist/context-budget.js +0 -1
  27. package/node_modules/@maka/runtime/dist/conversation-copy.js +67 -0
  28. package/node_modules/@maka/runtime/dist/durable-tool-result-projection.js +390 -0
  29. package/node_modules/@maka/runtime/dist/model-history.js +12 -39
  30. package/node_modules/@maka/runtime/dist/plan-mode.js +0 -65
  31. package/node_modules/@maka/runtime/dist/recovery-resolver.js +18 -14
  32. package/node_modules/@maka/runtime/dist/run-trace.js +0 -10
  33. package/node_modules/@maka/runtime/dist/runtime-kernel.js +0 -1
  34. package/node_modules/@maka/runtime/dist/sandbox/index.js +0 -1
  35. package/node_modules/@maka/runtime/dist/sandbox/linux-sandbox.js +0 -12
  36. package/node_modules/@maka/runtime/dist/sandbox/macos-seatbelt.js +0 -12
  37. package/node_modules/@maka/runtime/dist/sandbox/sandbox-manager.js +0 -35
  38. package/node_modules/@maka/runtime/dist/sandbox/windows-sandbox.js +0 -12
  39. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +20 -11
  40. package/node_modules/@maka/runtime/dist/session-manager.js +0 -170
  41. package/node_modules/@maka/runtime/dist/shell-detect.js +3 -7
  42. package/node_modules/@maka/runtime/dist/shell-run-contract.js +0 -1
  43. package/node_modules/@maka/runtime/dist/shell-run-manager.js +1 -39
  44. package/node_modules/@maka/runtime/dist/shell-tools.js +1 -1
  45. package/node_modules/@maka/runtime/dist/task-ledger-tools.js +2 -2
  46. package/node_modules/@maka/runtime/dist/tool-runtime.js +118 -71
  47. package/node_modules/@maka/runtime/package.json +1 -1
  48. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +6 -1
  49. package/node_modules/@maka/runtime-host/dist/candidate-launch-owner-guard.js +13 -0
  50. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +4 -1
  51. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +27 -1
  52. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  53. package/node_modules/@maka/runtime-host/dist/client/launcher.js +8 -2
  54. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +11 -1
  55. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +1 -1
  56. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +394 -113
  57. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +90 -21
  58. package/node_modules/@maka/runtime-host/dist/protocol/index.js +8 -1
  59. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +60 -7
  60. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +4 -0
  61. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -4
  62. package/node_modules/@maka/runtime-host/dist/server/candidate.js +3 -0
  63. package/node_modules/@maka/runtime-host/dist/server/client-capability-recovery.js +10 -7
  64. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +6 -9
  65. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +9 -7
  66. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +10 -0
  67. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +2 -58
  68. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +91 -42
  69. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +10 -1
  70. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +45 -5
  71. package/node_modules/@maka/storage/dist/artifact-attachments.js +62 -11
  72. package/node_modules/@maka/storage/dist/artifact-store.js +11 -0
  73. package/node_modules/@maka/storage/dist/artifact-stores.js +4 -1
  74. package/node_modules/@maka/storage/dist/quiescent-session-snapshot.js +1154 -0
  75. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +36 -0
  76. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +213 -46
  77. package/node_modules/@maka/storage/dist/runtime-policy/document-io.js +1 -1
  78. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +186 -0
  79. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +120 -1
  80. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -1
  81. package/node_modules/@maka/storage/dist/session-bundle-ustar.js +12 -0
  82. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +5 -0
  83. package/package.json +1 -1
  84. package/node_modules/@maka/runtime/dist/sandbox/diagnostics.js +0 -285
  85. package/node_modules/@maka/runtime/dist/system-prompt/sandbox-context-prompt.js +0 -77
  86. package/node_modules/@maka/runtime/dist/system-prompt/session-environment-prompt.js +0 -47
@@ -40,12 +40,11 @@ import { decodePlaintextResponsesReasoningState, replayPlaintextResponsesProvide
40
40
  import { toolResultOutput } from './tool-result-output.js';
41
41
  import { contextDiagnosticsCompactionOf, } from './context-diagnostics.js';
42
42
  import { AiSdkCompaction, hasActiveToolResultPruneDiagnosticPatch, hasBlockingReplayDiagnostics, } from './ai-sdk-compaction.js';
43
+ import { durableProjectionToToolResultOutput } from './durable-tool-result-projection.js';
43
44
  import { openAiChatReasoningFieldFromProviderOptions } from './openai-chat-reasoning-transport.js';
44
45
  import { RunTrace } from './run-trace.js';
45
- import { toSandboxRunTraceProjection, } from './sandbox/diagnostics.js';
46
46
  import { SandboxCommandError } from './sandbox/errors.js';
47
47
  import { REQUEST_SANDBOX_BOUNDARY_TOOL_NAME, SANDBOX_BOUNDARY_DENIED_FOR_TURN, SANDBOX_BOUNDARY_FINALIZATION_PROMPT, } from './sandbox-boundary-tool.js';
48
- import { renderSandboxTurnTailPrompt } from './system-prompt/sandbox-context-prompt.js';
49
48
  import { computeCost } from './telemetry/cost.js';
50
49
  import { getBuiltinPricing } from './telemetry/builtin-pricing.js';
51
50
  import { buildRuntimeEventModelReplayPlan, buildSteeringEnvelope, collectToolActivityTurnIds, formatTextWithInlineRefs, steeringMessagesMissingFromBase, steeringModelMessage, steeringProviderOptions, } from './model-history.js';
@@ -405,6 +404,33 @@ function nativeApplyPatchFailureOutput(output) {
405
404
  value: { status: 'failed', ...(message ? { output: message } : {}) },
406
405
  };
407
406
  }
407
+ function durableApplyPatchReplayFactText(input, projection, isError) {
408
+ if (projection.kind === 'json') {
409
+ const fact = applyPatchReplayFactText(input, projection, isError);
410
+ if (fact)
411
+ return fact;
412
+ }
413
+ const output = durableProjectionToToolResultOutput(projection);
414
+ switch (output.type) {
415
+ case 'text':
416
+ case 'error-text':
417
+ return output.value;
418
+ case 'json':
419
+ case 'error-json':
420
+ return JSON.stringify(output.value);
421
+ case 'content': {
422
+ const text = output.value
423
+ .filter((part) => part.type === 'text')
424
+ .map((part) => part.text)
425
+ .join('\n');
426
+ return text || null;
427
+ }
428
+ case 'execution-denied':
429
+ return output.reason
430
+ ? `ApplyPatch execution denied: ${output.reason}`
431
+ : 'ApplyPatch execution denied.';
432
+ }
433
+ }
408
434
  /**
409
435
  * One Code Mode cell runs at a time on a backend, with one allowed to wait.
410
436
  * Widening either needs evidence that concurrent cells are wanted; none exists
@@ -619,9 +645,8 @@ export class AiSdkBackend {
619
645
  now: this.now,
620
646
  modelAdapter: this.modelAdapter,
621
647
  createProviderRequestTracker: (trackerInput) => this.createProviderRequestTracker(trackerInput),
622
- materializeRuntimeReplayPlan: (plan, imageBudget, checkpoint) => this.materializeRuntimeReplayPlan(plan, imageBudget, undefined, checkpoint),
648
+ materializeRuntimeReplayPlan: (plan, imageBudget, checkpoint) => this.materializeRuntimeReplayPlan(plan, imageBudget, checkpoint),
623
649
  canReplayProviderNative: (plan) => this.canReplayProviderNative(plan),
624
- appendTurnTailPrompt: (content, turnTailPrompt) => this.appendTurnTailPrompt(content, turnTailPrompt),
625
650
  });
626
651
  if (input.tools.some((tool) => tool.name === MEMORY_REMEMBER_TOOL_NAME || tool.name === MEMORY_EXTRACT_TOOL_NAME)) {
627
652
  throw new Error('Long-term Memory trigger tool names are reserved by Runtime');
@@ -790,7 +815,7 @@ export class AiSdkBackend {
790
815
  ...(identity.runId ? { runId: identity.runId } : {}),
791
816
  orchestrationMode: identity.orchestrationMode,
792
817
  ...(identity.invocationId ? { invocationId: identity.invocationId } : {}),
793
- materializeDefaultToolResultOutput: ({ toolCallId, output }) => this.materializeToolResultOutput(identity.scope().imageBudget, output, false, toolCallId),
818
+ prepareDurableProjectionArtifact: input.prepareDurableProjectionArtifact,
794
819
  spawnChildSession: input.spawnChildSession,
795
820
  listChildAgents: input.listChildAgents,
796
821
  readChildAgentOutput: input.readChildAgentOutput,
@@ -1032,48 +1057,6 @@ export class AiSdkBackend {
1032
1057
  });
1033
1058
  }
1034
1059
  }
1035
- let sandboxDiagnosticsSnapshot;
1036
- let sandboxPrompt;
1037
- let sandboxContextStage = 'resolve';
1038
- try {
1039
- sandboxDiagnosticsSnapshot = this.input.sandboxDiagnostics
1040
- ? await raceWithTurnAbort(this.resolveTurnSandboxDiagnostics(), turnAbortController.signal)
1041
- : undefined;
1042
- sandboxContextStage = 'render';
1043
- sandboxPrompt = sandboxDiagnosticsSnapshot
1044
- ? renderSandboxTurnTailPrompt(sandboxDiagnosticsSnapshot)
1045
- : undefined;
1046
- }
1047
- catch (err) {
1048
- if (scope.aborted || turnAbortController.signal.aborted) {
1049
- queue.push({
1050
- type: 'abort',
1051
- id: this.newId(),
1052
- turnId,
1053
- ts: this.now(),
1054
- reason: 'user_stop',
1055
- });
1056
- queue.push({
1057
- type: 'complete',
1058
- id: this.newId(),
1059
- turnId,
1060
- ts: this.now(),
1061
- stopReason: 'user_stop',
1062
- });
1063
- queue.close();
1064
- yield* this.drain(queue);
1065
- return;
1066
- }
1067
- trace.sandboxContextFailed(sandboxContextStage, err);
1068
- // This context is model guidance, not execution authority. Never fall
1069
- // back to a stale snapshot; continue without the prompt while the live
1070
- // ExecutionBoundary remains authoritative for every tool invocation.
1071
- sandboxDiagnosticsSnapshot = undefined;
1072
- sandboxPrompt = undefined;
1073
- }
1074
- if (sandboxDiagnosticsSnapshot) {
1075
- trace.sandboxContextResolved(toSandboxRunTraceProjection(sandboxDiagnosticsSnapshot));
1076
- }
1077
1060
  const providerRequestTracker = this.createProviderRequestTracker({
1078
1061
  turnId,
1079
1062
  callKind: 'main',
@@ -1167,11 +1150,6 @@ export class AiSdkBackend {
1167
1150
  await this.resolveSystemPrompt(scope),
1168
1151
  scope.orchestration?.mode === 'swarm' ? renderSwarmModePrompt() : undefined,
1169
1152
  scope.orchestration?.mode === 'graph' ? renderGraphModePrompt() : undefined,
1170
- // A safe continuation deliberately has no new user message. Keep its
1171
- // replay byte-for-byte intact and carry only the current authority fact
1172
- // in the effective system envelope; ordinary volatile turn-tail facts
1173
- // remain excluded from continuation.
1174
- input.continuation ? sandboxPrompt : undefined,
1175
1153
  ]);
1176
1154
  }
1177
1155
  catch (err) {
@@ -1305,13 +1283,6 @@ export class AiSdkBackend {
1305
1283
  next.start();
1306
1284
  };
1307
1285
  const activeTools = plan.activeTools;
1308
- const turnTailPrompt = input.continuation
1309
- ? undefined
1310
- : joinPromptFragments([
1311
- await this.resolveTurnTailPrompt(turnId),
1312
- await this.resolveShellRunContextSummary(),
1313
- sandboxPrompt,
1314
- ]);
1315
1286
  const currentUserContent = input.continuation
1316
1287
  ? undefined
1317
1288
  : await this.buildCurrentUserContent(scope.imageBudget, input.text, input.attachments, input.quotes, input.headAnchorRuntimeEvent?.id);
@@ -1321,10 +1292,9 @@ export class AiSdkBackend {
1321
1292
  ...priorReplay.messages,
1322
1293
  {
1323
1294
  role: 'user',
1324
- content: this.appendTurnTailPrompt(currentUserContent, turnTailPrompt),
1295
+ content: currentUserContent,
1325
1296
  },
1326
1297
  ];
1327
- const settledModelOutputs = new Map();
1328
1298
  const loadDurableTurnEvents = async () => {
1329
1299
  const loadTurnRuntimeEvents = this.input.loadTurnRuntimeEvents;
1330
1300
  if (!loadTurnRuntimeEvents) {
@@ -1364,22 +1334,7 @@ export class AiSdkBackend {
1364
1334
  (replayPlan.hasProviderNativeSemantics && !this.canReplayProviderNative(replayPlan))) {
1365
1335
  throw new Error('durable current-run projection is not replayable');
1366
1336
  }
1367
- const anchorEventId = input.headAnchorRuntimeEvent?.id;
1368
- let decoratedCurrentUser = false;
1369
- const replayItems = replayPlan.items.map((item) => {
1370
- if (item.kind !== 'text' || item.role !== 'user') {
1371
- return item;
1372
- }
1373
- if (anchorEventId !== undefined ? item.eventId !== anchorEventId : decoratedCurrentUser) {
1374
- return item;
1375
- }
1376
- decoratedCurrentUser = true;
1377
- return {
1378
- ...item,
1379
- content: this.appendTurnTailPrompt(item.content, turnTailPrompt),
1380
- };
1381
- });
1382
- const currentTurnMessages = await this.materializeRuntimeReplayPlan({ ...replayPlan, items: replayItems }, scope.imageBudget, settledModelOutputs, projectionCheckpoint);
1337
+ const currentTurnMessages = await this.materializeRuntimeReplayPlan(replayPlan, scope.imageBudget, projectionCheckpoint);
1383
1338
  return projectionCheckpoint
1384
1339
  ? currentTurnMessages
1385
1340
  : [...priorReplay.messages, ...currentTurnMessages];
@@ -1408,7 +1363,6 @@ export class AiSdkBackend {
1408
1363
  ...(input.attachments !== undefined ? { attachments: input.attachments } : {}),
1409
1364
  ...(input.quotes !== undefined ? { quotes: input.quotes } : {}),
1410
1365
  }),
1411
- turnTailPrompt,
1412
1366
  }),
1413
1367
  requestShape: computeRequestShapeDiagnostic({
1414
1368
  connection: this.input.connection,
@@ -1460,7 +1414,7 @@ export class AiSdkBackend {
1460
1414
  midTurnCompactDiagnosticPatch = mergeContextBudgetDiagnosticPatches(midTurnCompactDiagnosticPatch, patch);
1461
1415
  };
1462
1416
  const midTurnSystemPromptChars = systemPrompt?.length ?? 0;
1463
- const midTurnCapacityHook = this.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, providerTools, () => currentRepairToolNames(), turnTailPrompt, midTurnSystemPromptChars, onMidTurnDiagnosticPatch, scope, this.automaticMemoryCompactionSupported()
1417
+ const midTurnCapacityHook = this.compaction.buildMidTurnCapacityCompactProjection(turnId, midTurnState, queue, providerTools, () => currentRepairToolNames(), midTurnSystemPromptChars, onMidTurnDiagnosticPatch, scope, this.automaticMemoryCompactionSupported()
1464
1418
  ? () => this.automaticMemoryCompactionDecision()
1465
1419
  : undefined, this.automaticMemoryCompactionSupported()
1466
1420
  ? (dispatch) => this.dispatchAutomaticMemoryCompaction(scope, dispatch)
@@ -1855,7 +1809,6 @@ export class AiSdkBackend {
1855
1809
  providerTools,
1856
1810
  activeTools: activeToolsForRequest,
1857
1811
  systemPromptChars: midTurnSystemPromptChars,
1858
- turnTailPrompt,
1859
1812
  queue,
1860
1813
  onDiagnosticPatch: onMidTurnDiagnosticPatch,
1861
1814
  origin: scope,
@@ -2059,13 +2012,6 @@ export class AiSdkBackend {
2059
2012
  }
2060
2013
  }
2061
2014
  await queue.waitUntilConsumedThroughCurrent();
2062
- for (let index = 0; index < returnedToolCalls.length; index += 1) {
2063
- const toolCall = returnedToolCalls[index];
2064
- const settlement = settlements[index];
2065
- if (toolCall && settlement) {
2066
- settledModelOutputs.set(toolCall.toolCallId, settlement.modelOutput);
2067
- }
2068
- }
2069
2015
  const continuationWillRun = (maxSteps === undefined || runtimeSteps < maxSteps) &&
2070
2016
  !scope.loopStopRequested &&
2071
2017
  !scope.aborted;
@@ -2454,7 +2400,7 @@ export class AiSdkBackend {
2454
2400
  if (!tool)
2455
2401
  throw new Error(`Tool "${name}" is not active or nestable in this cell`);
2456
2402
  const parsedInput = await validateCodeModeToolInput(tool, input);
2457
- const settlement = await scope.toolRuntime.settleToolCallRaw({
2403
+ const settlement = await scope.toolRuntime.settleToolCall({
2458
2404
  tool,
2459
2405
  turnId: context.turnId,
2460
2406
  toolCallId: `${context.toolCallId}:nested:${this.newId()}`,
@@ -2865,7 +2811,7 @@ export class AiSdkBackend {
2865
2811
  if (!plan.hasProviderNativeSemantics) {
2866
2812
  return {
2867
2813
  status: 'ready',
2868
- messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, undefined, projectedHistoryCompactCheckpoint),
2814
+ messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, projectedHistoryCompactCheckpoint),
2869
2815
  gate: 'runtime_replay_text_only',
2870
2816
  diagnostics: plan.diagnostics,
2871
2817
  runtimeEventCount: runtimeContext.length,
@@ -2882,7 +2828,7 @@ export class AiSdkBackend {
2882
2828
  return {
2883
2829
  status: 'ready',
2884
2830
  messages: degradedPlan.items.length > 0 || hasProviderHistoryCompactCheckpoint
2885
- ? await this.materializeRuntimeReplayPlan(degradedPlan, scope.imageBudget, undefined, projectedHistoryCompactCheckpoint)
2831
+ ? await this.materializeRuntimeReplayPlan(degradedPlan, scope.imageBudget, projectedHistoryCompactCheckpoint)
2886
2832
  : await materializeReplayFallback(),
2887
2833
  gate: input.continuation
2888
2834
  ? 'runtime_replay_text_only'
@@ -2895,7 +2841,7 @@ export class AiSdkBackend {
2895
2841
  }
2896
2842
  return {
2897
2843
  status: 'ready',
2898
- messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, undefined, projectedHistoryCompactCheckpoint),
2844
+ messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, projectedHistoryCompactCheckpoint),
2899
2845
  gate: 'runtime_replay_provider_native',
2900
2846
  diagnostics: plan.diagnostics,
2901
2847
  runtimeEventCount: runtimeContext.length,
@@ -2960,7 +2906,7 @@ export class AiSdkBackend {
2960
2906
  * id) keep the older shape: tool calls form a tool-only assistant,
2961
2907
  * text/thinking become standalone messages.
2962
2908
  */
2963
- async materializeRuntimeReplayPlan(plan, budget, settledModelOutputs, historyCompactCheckpoint) {
2909
+ async materializeRuntimeReplayPlan(plan, budget, historyCompactCheckpoint) {
2964
2910
  const out = [];
2965
2911
  const push = (message, eventIds) => {
2966
2912
  out.push(message);
@@ -3063,8 +3009,9 @@ export class AiSdkBackend {
3063
3009
  // diagnostic precisely so this drop path is reachable; see
3064
3010
  // hasBlockingReplayDiagnostics).
3065
3011
  const materializeReplayToolResult = async (result, toolName) => {
3066
- const output = settledModelOutputs?.get(result.toolCallId) ??
3067
- (await this.materializeToolResultOutput(budget, result.output, result.isError, `runtime-event:${result.eventId}:tool-result`));
3012
+ const output = result.modelProjection
3013
+ ? await this.materializeDurableToolResultProjection(budget, result.modelProjection, `runtime-event:${result.eventId}:tool-result`)
3014
+ : await this.materializeToolResultOutput(budget, result.output, result.isError, `runtime-event:${result.eventId}:tool-result`);
3068
3015
  if (toolName !== 'apply_patch')
3069
3016
  return output;
3070
3017
  return result.isError ? nativeApplyPatchFailureOutput(output) : output;
@@ -3249,7 +3196,9 @@ export class AiSdkBackend {
3249
3196
  break;
3250
3197
  }
3251
3198
  downgradedApplyPatchCalls.delete(item.toolCallId);
3252
- const replayFact = applyPatchReplayFactText(downgradedCall.input, item.output, item.isError);
3199
+ const replayFact = item.modelProjection
3200
+ ? durableApplyPatchReplayFactText(downgradedCall.input, item.modelProjection, item.isError)
3201
+ : applyPatchReplayFactText(downgradedCall.input, item.output, item.isError);
3253
3202
  if (!replayFact)
3254
3203
  break;
3255
3204
  if (downgradedCall.stepId) {
@@ -3432,17 +3381,6 @@ export class AiSdkBackend {
3432
3381
  }
3433
3382
  return out;
3434
3383
  }
3435
- /** Append provider-visible volatile turn facts after the durable user content. */
3436
- appendTurnTailPrompt(content, turnTailPrompt) {
3437
- if (!turnTailPrompt)
3438
- return content;
3439
- if (typeof content === 'string')
3440
- return `${content}\n\n${turnTailPrompt}`;
3441
- return [
3442
- ...content,
3443
- { type: 'text', text: turnTailPrompt },
3444
- ];
3445
- }
3446
3384
  /** A decision key deduplicates re-materialization; no key charges each occurrence. */
3447
3385
  chargeImageBudget(budget, bytes, decisionKey) {
3448
3386
  if (decisionKey !== undefined) {
@@ -3546,6 +3484,59 @@ export class AiSdkBackend {
3546
3484
  ],
3547
3485
  };
3548
3486
  }
3487
+ async materializeDurableToolResultProjection(budget, projection, decisionKey) {
3488
+ if (projection.kind !== 'content')
3489
+ return durableProjectionToToolResultOutput(projection);
3490
+ const value = [];
3491
+ for (const [index, part] of projection.parts.entries()) {
3492
+ if (part.kind === 'text') {
3493
+ value.push({ type: 'text', text: part.text });
3494
+ continue;
3495
+ }
3496
+ if (this.input.supportsVision !== true) {
3497
+ value.push({
3498
+ type: 'text',
3499
+ text: 'Image was read, but the selected model does not support image input.',
3500
+ });
3501
+ continue;
3502
+ }
3503
+ if (!this.input.readAttachmentBytes) {
3504
+ value.push({
3505
+ type: 'text',
3506
+ text: 'Image was read, but its stored bytes are unavailable.',
3507
+ });
3508
+ continue;
3509
+ }
3510
+ let read;
3511
+ try {
3512
+ read = await this.input.readAttachmentBytes(part.ref);
3513
+ }
3514
+ catch {
3515
+ value.push({
3516
+ type: 'text',
3517
+ text: 'Image could not be loaded from artifact storage: read_failed.',
3518
+ });
3519
+ continue;
3520
+ }
3521
+ if (!read.ok) {
3522
+ value.push({
3523
+ type: 'text',
3524
+ text: `Image could not be loaded from artifact storage: ${read.reason}.`,
3525
+ });
3526
+ continue;
3527
+ }
3528
+ if (!this.chargeImageBudget(budget, read.bytes.length, `${decisionKey}:artifact:${index}`)) {
3529
+ value.push({ type: 'text', text: PROVIDER_IMAGE_BUDGET_EXCEEDED_MESSAGE });
3530
+ continue;
3531
+ }
3532
+ value.push({
3533
+ type: 'file',
3534
+ data: { type: 'data', data: Buffer.from(read.bytes).toString('base64') },
3535
+ mediaType: part.mediaType,
3536
+ });
3537
+ }
3538
+ return { type: 'content', value };
3539
+ }
3549
3540
  async buildCurrentUserContent(budget, text, attachments, quotes, runtimeEventId) {
3550
3541
  return await this.appendImageParts(budget, formatTextWithInlineRefs(text, {
3551
3542
  ...(attachments !== undefined ? { attachments } : {}),
@@ -3558,39 +3549,12 @@ export class AiSdkBackend {
3558
3549
  return await this.input.systemPrompt({
3559
3550
  sessionId: this.sessionId,
3560
3551
  turnId,
3561
- ...(scope.runId ? { runId: scope.runId } : {}),
3562
3552
  cwd: this.input.header.cwd,
3563
- workspaceRoot: this.input.header.workspaceRoot,
3564
3553
  emitSkillCatalogTrace: (message, data) => scope.runTrace?.emit('skill', 'skill_catalog_built', message, data),
3565
3554
  });
3566
3555
  }
3567
3556
  return this.input.systemPrompt;
3568
3557
  }
3569
- async resolveTurnSandboxDiagnostics() {
3570
- const provider = this.input.sandboxDiagnostics;
3571
- if (!provider)
3572
- return undefined;
3573
- const boundary = await this.input.readExecutionBoundary();
3574
- if (boundary.kind === 'external')
3575
- return undefined;
3576
- return await provider.resolve(boundary.kind === 'managed'
3577
- ? { cwd: this.input.header.cwd, permissionProfile: boundary.profile }
3578
- : { cwd: this.input.header.cwd, mode: 'bypass' });
3579
- }
3580
- async resolveTurnTailPrompt(turnId) {
3581
- if (typeof this.input.turnTailPrompt === 'function') {
3582
- return await this.input.turnTailPrompt({
3583
- sessionId: this.sessionId,
3584
- turnId,
3585
- cwd: this.input.header.cwd,
3586
- workspaceRoot: this.input.header.workspaceRoot,
3587
- });
3588
- }
3589
- return this.input.turnTailPrompt;
3590
- }
3591
- async resolveShellRunContextSummary() {
3592
- return await this.input.shellRunContextSummary?.();
3593
- }
3594
3558
  async *drain(queue) {
3595
3559
  try {
3596
3560
  for await (const ev of queue) {
@@ -37,7 +37,6 @@ export class AiSdkCompaction {
37
37
  createProviderRequestTracker;
38
38
  materializeRuntimeReplayPlan;
39
39
  canReplayProviderNative;
40
- appendTurnTailPrompt;
41
40
  historyCompactAbortController = null;
42
41
  /**
43
42
  * Session-scoped circuit for exact malformed compaction inputs. A retry or
@@ -53,7 +52,6 @@ export class AiSdkCompaction {
53
52
  this.createProviderRequestTracker = deps.createProviderRequestTracker;
54
53
  this.materializeRuntimeReplayPlan = deps.materializeRuntimeReplayPlan;
55
54
  this.canReplayProviderNative = deps.canReplayProviderNative;
56
- this.appendTurnTailPrompt = deps.appendTurnTailPrompt;
57
55
  }
58
56
  /** Abort an in-flight manual history compaction (called by AiSdkBackend.stop). */
59
57
  abortHistoryCompact() {
@@ -409,7 +407,7 @@ export class AiSdkCompaction {
409
407
  * usage + a signed char/4 payload delta, tool schemas included) against
410
408
  * `contextWindow - reserve`; over the high-water, fold a safe completed
411
409
  * prefix into a durable mid_turn checkpoint and continue the same turn on
412
- * `[compact block, verbatim head anchor, preserved tail]`.
410
+ * `[compact block, verbatim head anchor]`.
413
411
  *
414
412
  * This hook never terminates the turn: every failure fails open with a
415
413
  * diagnostic and records itself for the final-request estimate owner, which
@@ -420,7 +418,7 @@ export class AiSdkCompaction {
420
418
  * approximate — a missed or spurious trigger is recoverable; the verdict is
421
419
  * not, so it does not live here.
422
420
  */
423
- buildMidTurnCapacityCompactProjection(turnId, state, queue, providerTools, fallbackActiveTools, turnTailPrompt, systemPromptChars, onDiagnosticPatch, origin, memoryCompactionDecision, onMemoryCompaction, abortSignal) {
421
+ buildMidTurnCapacityCompactProjection(turnId, state, queue, providerTools, fallbackActiveTools, systemPromptChars, onDiagnosticPatch, origin, memoryCompactionDecision, onMemoryCompaction, abortSignal) {
424
422
  if (!state)
425
423
  return undefined;
426
424
  const policy = this.input.contextBudget;
@@ -531,7 +529,6 @@ export class AiSdkCompaction {
531
529
  providerTools,
532
530
  activeToolsForStep,
533
531
  systemPromptChars,
534
- turnTailPrompt,
535
532
  memoryCompactionDecision,
536
533
  onMemoryCompaction,
537
534
  abortSignal,
@@ -565,7 +562,7 @@ export class AiSdkCompaction {
565
562
  * the pass/terminate verdict and the diagnostic emission are the caller's.
566
563
  */
567
564
  async compactActiveRequestHistory(input) {
568
- const { turnId, state, queue, providerTools, activeToolsForStep, systemPromptChars, turnTailPrompt, abortSignal, } = input;
565
+ const { turnId, state, queue, providerTools, activeToolsForStep, systemPromptChars, abortSignal, } = input;
569
566
  if (state.malformedSummaryFailure) {
570
567
  return {
571
568
  decision: 'fail',
@@ -726,17 +723,7 @@ export class AiSdkCompaction {
726
723
  diagnosticReason: 'replacement_unmaterializable',
727
724
  };
728
725
  }
729
- // The head anchor must render exactly like the raw projection's current
730
- // user message: the initial request decorates it with the volatile turn
731
- // tail (cwd, shell context, task state — see send()), which is not part
732
- // of the durable anchor bytes. Reuse the same decoration owner
733
- // (appendTurnTailPrompt) on the anchor's replay item so a replacement
734
- // never silently drops that context — and never counts the drop as
735
- // shrinkage in the guard below.
736
- const replayItemsWithAnchorTail = replayPlan.items.map((item) => item.kind === 'text' && item.role === 'user' && item.eventId === state.headAnchor.id
737
- ? { ...item, content: this.appendTurnTailPrompt(item.content, turnTailPrompt) }
738
- : item);
739
- const replacementMessages = await this.materializeRuntimeReplayPlan({ ...replayPlan, items: replayItemsWithAnchorTail }, input.origin.imageBudget, plan.checkpoint);
726
+ const replacementMessages = await this.materializeRuntimeReplayPlan(replayPlan, input.origin.imageBudget, plan.checkpoint);
740
727
  // Apply the shape only when it actually shrinks the request versus the
741
728
  // reference payload (the incoming request for the proactive hook, the
742
729
  // request that overflowed for reactive recovery): a materialized
@@ -848,7 +835,6 @@ export class AiSdkCompaction {
848
835
  providerTools: input.providerTools,
849
836
  activeToolsForStep: input.activeTools,
850
837
  systemPromptChars: input.systemPromptChars,
851
- turnTailPrompt: input.turnTailPrompt,
852
838
  memoryCompactionDecision: input.memoryCompactionDecision,
853
839
  onMemoryCompaction: input.onMemoryCompaction,
854
840
  abortSignal: input.abortSignal,
@@ -93,7 +93,6 @@ export function buildPromptSegmentEstimates(input) {
93
93
  : {}),
94
94
  },
95
95
  segment('current_user', input.currentUserContent.length, charsPerToken),
96
- segment('turn_tail', input.turnTailPrompt?.length ?? 0, charsPerToken),
97
96
  ];
98
97
  }
99
98
  export function estimateModelMessagesChars(messages) {
@@ -30,6 +30,7 @@ import { buildToolOperationId } from './runtime-commit-sink.js';
30
30
  import { isContinuationStartRuntimeEvent } from './runtime-event-read-model.js';
31
31
  import { buildToolResultArchiveResourceRef, parseToolResultArchiveResourceRef, } from './tool-result-archive-resource.js';
32
32
  import { deserializeToolResultArchive, isArchivedToolResultPlaceholder, } from './tool-result-archive.js';
33
+ import { rewriteDurableToolResultProjectionArtifactRefs } from './durable-tool-result-projection.js';
33
34
  export function createConversationCopySlice(messages, sourceTurnId, boundary) {
34
35
  const turnOrder = [];
35
36
  const seen = new Set();
@@ -374,6 +375,60 @@ export function collectConversationCopyLinkedChildReferences(input) {
374
375
  }
375
376
  return references;
376
377
  }
378
+ /**
379
+ * Collects the `relativePath` of every `session_file` StorageRef that the copied
380
+ * slice references and that belongs to the source Session. User-uploaded
381
+ * attachments carry `turnId === uploadId` (a sentinel, not a conversation turn),
382
+ * so the turn-scoped artifact copy never selects them; the coordinator feeds this
383
+ * set to `copyConversationArtifacts` as an explicit same-Session include list so
384
+ * their refs resolve in `rewriteStorageRef`. Walks exactly the ref sites reached
385
+ * by `rewriteStorageRef`: user-message attachments, tool_result image refs, text
386
+ * runtime-event attachments, and function_response / archived tool-result images.
387
+ */
388
+ export function collectConversationCopySessionFileRefs(input) {
389
+ const refs = new Set();
390
+ const addRef = (ref) => {
391
+ if (ref.kind === 'session_file' && ref.sessionId === input.sourceSessionId) {
392
+ refs.add(ref.relativePath);
393
+ }
394
+ };
395
+ const addContent = (content) => {
396
+ if (content.kind === 'image')
397
+ addRef(content.ref);
398
+ };
399
+ const addSerialized = (value) => {
400
+ if (isArchivedToolResultPlaceholder(value))
401
+ return;
402
+ try {
403
+ addContent(decodePersistedToolResultContent(markPersisted(value)));
404
+ }
405
+ catch {
406
+ // Opaque tool results carry no typed Session file reference.
407
+ }
408
+ };
409
+ for (const message of input.messages) {
410
+ if (message.type === 'user' && message.attachments) {
411
+ for (const attachment of message.attachments)
412
+ addRef(attachment.ref);
413
+ }
414
+ else if (message.type === 'tool_result') {
415
+ addContent(message.content);
416
+ }
417
+ }
418
+ for (const event of input.runtimeEvents) {
419
+ if (event.content?.kind === 'text' && event.content.attachments) {
420
+ for (const attachment of event.content.attachments)
421
+ addRef(attachment.ref);
422
+ }
423
+ else if (event.content?.kind === 'function_response') {
424
+ addSerialized(event.content.result);
425
+ }
426
+ }
427
+ for (const serializedResult of input.archivedResults) {
428
+ addSerialized(deserializeToolResultArchive(serializedResult));
429
+ }
430
+ return refs;
431
+ }
377
432
  function cloneAgentRunEvent(event, ids, references, sourceCompactableEvents, clonedRuntimeEvents, checkpointIds, operationalEventIds, providerTraceIds, logicalCallIds) {
378
433
  if (event.type === 'event_corrupt') {
379
434
  throw new Error(`Cannot copy corrupt AgentRun event ${event.id}`);
@@ -717,6 +772,11 @@ function rewriteRuntimeEventReferences(event, references) {
717
772
  ? {
718
773
  ...event.content,
719
774
  result: rewriteRuntimeToolResult(event.content.result, references),
775
+ ...(event.content.modelProjection
776
+ ? {
777
+ modelProjection: rewriteDurableToolResultProjectionArtifactRefs(event.content.modelProjection, (ref) => rewriteProjectionArtifactRef(ref, references)),
778
+ }
779
+ : {}),
720
780
  }
721
781
  : event.content;
722
782
  const refs = event.refs
@@ -1022,6 +1082,13 @@ function rewriteStorageRef(ref, references) {
1022
1082
  relativePath,
1023
1083
  };
1024
1084
  }
1085
+ function rewriteProjectionArtifactRef(ref, references) {
1086
+ const rewritten = rewriteStorageRef(ref, references);
1087
+ if (rewritten.kind !== 'session_context' && rewritten.kind !== 'session_file') {
1088
+ throw new Error('Conversation copy produced an invalid projection Artifact reference');
1089
+ }
1090
+ return rewritten;
1091
+ }
1025
1092
  function rewriteArchivedToolResult(value, references) {
1026
1093
  const artifactId = rewriteOwnedArtifactId(value.artifactId, references);
1027
1094
  const resource = value.resourceRef