maka-agent 0.2.0-dev.8.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 (63) 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/artifacts.js +23 -15
  15. package/node_modules/@maka/core/dist/durable-tool-result-projection.js +124 -0
  16. package/node_modules/@maka/core/dist/llm-connections.js +20 -0
  17. package/node_modules/@maka/core/dist/runtime-event.js +28 -3
  18. package/node_modules/@maka/core/dist/session-name.js +0 -1
  19. package/node_modules/@maka/core/package.json +1 -0
  20. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +95 -19
  21. package/node_modules/@maka/runtime/dist/conversation-copy.js +67 -0
  22. package/node_modules/@maka/runtime/dist/durable-tool-result-projection.js +390 -0
  23. package/node_modules/@maka/runtime/dist/model-history.js +12 -39
  24. package/node_modules/@maka/runtime/dist/recovery-resolver.js +18 -14
  25. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +20 -11
  26. package/node_modules/@maka/runtime/dist/session-manager.js +0 -170
  27. package/node_modules/@maka/runtime/dist/tool-runtime.js +118 -71
  28. package/node_modules/@maka/runtime/package.json +1 -0
  29. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +6 -1
  30. package/node_modules/@maka/runtime-host/dist/candidate-launch-owner-guard.js +13 -0
  31. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +4 -1
  32. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +27 -1
  33. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  34. package/node_modules/@maka/runtime-host/dist/client/launcher.js +8 -2
  35. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +11 -1
  36. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +1 -1
  37. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +394 -113
  38. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +90 -21
  39. package/node_modules/@maka/runtime-host/dist/protocol/index.js +8 -1
  40. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +60 -7
  41. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +4 -0
  42. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -4
  43. package/node_modules/@maka/runtime-host/dist/server/candidate.js +3 -0
  44. package/node_modules/@maka/runtime-host/dist/server/client-capability-recovery.js +10 -7
  45. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +5 -1
  46. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +9 -1
  47. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +10 -0
  48. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +91 -42
  49. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +10 -1
  50. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +45 -5
  51. package/node_modules/@maka/storage/dist/artifact-attachments.js +62 -11
  52. package/node_modules/@maka/storage/dist/artifact-store.js +11 -0
  53. package/node_modules/@maka/storage/dist/artifact-stores.js +4 -1
  54. package/node_modules/@maka/storage/dist/quiescent-session-snapshot.js +1154 -0
  55. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +36 -0
  56. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +213 -46
  57. package/node_modules/@maka/storage/dist/runtime-policy/document-io.js +1 -1
  58. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +186 -0
  59. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +120 -1
  60. package/node_modules/@maka/storage/dist/runtime-policy-stores.js +2 -1
  61. package/node_modules/@maka/storage/dist/session-bundle-ustar.js +12 -0
  62. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +5 -0
  63. package/package.json +1 -1
@@ -0,0 +1,124 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ import { isCanonicalStorageRef } from './events.js';
20
+ import { isCanonicalArtifactEntityId, normalizeArtifactImagePreviewMime } from './artifacts.js';
21
+ import { hasExactShape, isRecord } from './record-schema.js';
22
+ import { serializedByteLength } from './serialized-byte-length.js';
23
+ export const DURABLE_TOOL_RESULT_PROJECTION_VERSION = 1;
24
+ export const DURABLE_TOOL_RESULT_PROJECTION_MAX_BYTES = 256 * 1024;
25
+ export const DURABLE_TOOL_RESULT_PROJECTION_MAX_PARTS = 64;
26
+ export const DURABLE_TOOL_RESULT_PROJECTION_MAX_JSON_DEPTH = 32;
27
+ export const DURABLE_TOOL_RESULT_PROJECTION_MAX_JSON_NODES = 20_000;
28
+ export const DURABLE_TOOL_RESULT_PROJECTION_FAILURE_MESSAGE = 'The tool completed, but its model-visible result could not be projected safely.';
29
+ export const DURABLE_TOOL_RESULT_PROJECTION_FAILURE = Object.freeze({
30
+ version: DURABLE_TOOL_RESULT_PROJECTION_VERSION,
31
+ kind: 'failure',
32
+ reason: 'projection_failed',
33
+ message: DURABLE_TOOL_RESULT_PROJECTION_FAILURE_MESSAGE,
34
+ });
35
+ export function decodeDurableToolResultProjection(value) {
36
+ if (!isDurableToolResultProjection(value) ||
37
+ serializedByteLength(value, DURABLE_TOOL_RESULT_PROJECTION_MAX_BYTES) >
38
+ DURABLE_TOOL_RESULT_PROJECTION_MAX_BYTES) {
39
+ throw new Error('Invalid durable Tool Result projection');
40
+ }
41
+ return value;
42
+ }
43
+ function isDurableToolResultProjection(value) {
44
+ if (!isRecord(value) || value.version !== DURABLE_TOOL_RESULT_PROJECTION_VERSION)
45
+ return false;
46
+ switch (value.kind) {
47
+ case 'text':
48
+ return (hasExactShape(value, {
49
+ required: ['version', 'kind', 'text'],
50
+ allowed: new Set(['version', 'kind', 'text', 'isError']),
51
+ }) &&
52
+ typeof value.text === 'string' &&
53
+ (value.isError === undefined || value.isError === true));
54
+ case 'json':
55
+ return (hasExactShape(value, {
56
+ required: ['version', 'kind', 'value'],
57
+ allowed: new Set(['version', 'kind', 'value', 'isError']),
58
+ }) &&
59
+ isDurableProjectionJson(value.value, { nodes: 0 }, 0) &&
60
+ (value.isError === undefined || value.isError === true));
61
+ case 'content':
62
+ return (hasExactShape(value, {
63
+ required: ['version', 'kind', 'parts'],
64
+ allowed: new Set(['version', 'kind', 'parts']),
65
+ }) &&
66
+ Array.isArray(value.parts) &&
67
+ value.parts.length > 0 &&
68
+ value.parts.length <= DURABLE_TOOL_RESULT_PROJECTION_MAX_PARTS &&
69
+ value.parts.every(isProjectionPart));
70
+ case 'execution_denied':
71
+ return (hasExactShape(value, {
72
+ required: ['version', 'kind'],
73
+ allowed: new Set(['version', 'kind', 'reason']),
74
+ }) &&
75
+ (value.reason === undefined || typeof value.reason === 'string'));
76
+ case 'failure':
77
+ return (hasExactShape(value, {
78
+ required: ['version', 'kind', 'reason', 'message'],
79
+ allowed: new Set(['version', 'kind', 'reason', 'message']),
80
+ }) &&
81
+ value.reason === 'projection_failed' &&
82
+ value.message === DURABLE_TOOL_RESULT_PROJECTION_FAILURE_MESSAGE);
83
+ default:
84
+ return false;
85
+ }
86
+ }
87
+ function isProjectionPart(value) {
88
+ if (!isRecord(value))
89
+ return false;
90
+ if (value.kind === 'text') {
91
+ return (hasExactShape(value, {
92
+ required: ['kind', 'text'],
93
+ allowed: new Set(['kind', 'text']),
94
+ }) && typeof value.text === 'string');
95
+ }
96
+ return (value.kind === 'artifact' &&
97
+ hasExactShape(value, {
98
+ required: ['kind', 'mediaType', 'ref'],
99
+ allowed: new Set(['kind', 'mediaType', 'ref']),
100
+ }) &&
101
+ typeof value.mediaType === 'string' &&
102
+ normalizeArtifactImagePreviewMime(value.mediaType) === value.mediaType &&
103
+ isCanonicalStorageRef(value.ref) &&
104
+ (value.ref.kind === 'session_context' ||
105
+ (value.ref.kind === 'session_file' && isCanonicalArtifactEntityId(value.ref.relativePath))));
106
+ }
107
+ function isDurableProjectionJson(value, state, depth) {
108
+ state.nodes += 1;
109
+ if (state.nodes > DURABLE_TOOL_RESULT_PROJECTION_MAX_JSON_NODES ||
110
+ depth > DURABLE_TOOL_RESULT_PROJECTION_MAX_JSON_DEPTH) {
111
+ return false;
112
+ }
113
+ if (value === null ||
114
+ typeof value === 'string' ||
115
+ typeof value === 'boolean' ||
116
+ (typeof value === 'number' && Number.isFinite(value))) {
117
+ return true;
118
+ }
119
+ if (Array.isArray(value)) {
120
+ return value.every((item) => isDurableProjectionJson(item, state, depth + 1));
121
+ }
122
+ return (isRecord(value) &&
123
+ Object.values(value).every((item) => isDurableProjectionJson(item, state, depth + 1)));
124
+ }
@@ -296,6 +296,26 @@ export function deriveConnectionSlug(providerType, existingSlugs = []) {
296
296
  return candidate;
297
297
  }
298
298
  }
299
+ /** Stable human-facing slug base for one interactive OAuth Connection. */
300
+ export function interactiveOAuthConnectionSlugBase(providerType) {
301
+ switch (providerType) {
302
+ case 'openai-codex':
303
+ return 'codex-subscription';
304
+ case 'xai-oauth':
305
+ return 'xai-oauth';
306
+ }
307
+ }
308
+ /** Derive an unused OAuth Connection slug without moving allocation into a surface. */
309
+ export function deriveInteractiveOAuthConnectionSlug(providerType, existingSlugs = []) {
310
+ const base = interactiveOAuthConnectionSlugBase(providerType);
311
+ if (!existingSlugs.includes(base))
312
+ return base;
313
+ for (let suffix = 2;; suffix += 1) {
314
+ const candidate = `${base}-${suffix}`;
315
+ if (!existingSlugs.includes(candidate))
316
+ return candidate;
317
+ }
318
+ }
299
319
  /**
300
320
  * PR-UI-IPC-1 (@kenji msg 35260e29 + 2e495eb7): connection `baseUrl`
301
321
  * scheme allowlist gate.
@@ -39,6 +39,7 @@ import { isPermissionDecisionFields, isPermissionRequestPayload, isUserQuestionR
39
39
  import { isTokenUsageFields } from './usage-record-schema.js';
40
40
  import { isToolRecoveryFactEnvelope } from './tool-recovery-fact.js';
41
41
  import { isRuntimeEventWorkspaceFactEnvelope, } from './workspace-version-authority.js';
42
+ import { decodeDurableToolResultProjection, } from './durable-tool-result-projection.js';
42
43
  // ============================================================================
43
44
  // Role / Author / Status
44
45
  // ============================================================================
@@ -170,7 +171,7 @@ const TEXT_CONTENT_SHAPE = defineObjectShape()(['kind', 'text'], [
170
171
  ]);
171
172
  const THINKING_CONTENT_SHAPE = defineObjectShape()(['kind', 'text'], ['signature', 'providerOptions']);
172
173
  const FUNCTION_CALL_CONTENT_SHAPE = defineObjectShape()(['kind', 'id', 'name', 'args'], ['providerOptions', 'providerExecuted']);
173
- const FUNCTION_RESPONSE_CONTENT_SHAPE = defineObjectShape()(['kind', 'id', 'name', 'result'], ['isError', 'providerExecuted', 'providerOutput']);
174
+ const FUNCTION_RESPONSE_CONTENT_SHAPE = defineObjectShape()(['kind', 'id', 'name', 'result'], ['isError', 'providerExecuted', 'providerOutput', 'modelProjection']);
174
175
  const ERROR_CONTENT_SHAPE = defineObjectShape()(['kind', 'message'], ['code', 'reason', 'details']);
175
176
  const RUNTIME_ACTIONS_SHAPE = defineObjectShape()([], [
176
177
  'stateDelta',
@@ -203,7 +204,7 @@ const RUNTIME_TOOL_DISPATCH_SHAPE = defineObjectShape()([
203
204
  'toolName',
204
205
  'canonicalArgsHash',
205
206
  'recoveryMode',
206
- ], ['managedMutation']);
207
+ ], ['managedMutation', 'resultProjectionVersion']);
207
208
  const RUNTIME_MANAGED_WORKSPACE_MUTATION_SHAPE = defineObjectShape()([
208
209
  'protocol',
209
210
  'repositoryId',
@@ -293,6 +294,7 @@ export function decodeRuntimeEvent(value) {
293
294
  !isOptionalMember(value.modelVisibility, RUNTIME_EVENT_MODEL_VISIBILITIES) ||
294
295
  (value.status !== undefined && !isRuntimeEventStatus(value.status)) ||
295
296
  (value.content !== undefined && !isRuntimeEventContent(value.content)) ||
297
+ !hasOwnedModelProjection(value.content, value.sessionId) ||
296
298
  (value.actions !== undefined && !isRuntimeEventActions(value.actions)) ||
297
299
  (value.refs !== undefined && !isRuntimeEventRefs(value.refs))) {
298
300
  throw new Error('Invalid RuntimeEvent schema');
@@ -312,6 +314,17 @@ export function decodeRuntimeEvent(value) {
312
314
  }
313
315
  return value;
314
316
  }
317
+ function hasOwnedModelProjection(content, sessionId) {
318
+ if (!isRecord(content) || content.kind !== 'function_response')
319
+ return true;
320
+ const projection = content.modelProjection;
321
+ if (!isRecord(projection) || projection.kind !== 'content' || !Array.isArray(projection.parts)) {
322
+ return true;
323
+ }
324
+ return projection.parts.every((part) => !isRecord(part) ||
325
+ part.kind !== 'artifact' ||
326
+ (isRecord(part.ref) && part.ref.sessionId === sessionId));
327
+ }
315
328
  function isRuntimeEventContent(value) {
316
329
  if (!isRecord(value))
317
330
  return false;
@@ -350,7 +363,9 @@ function isRuntimeEventContent(value) {
350
363
  typeof value.name === 'string' &&
351
364
  Object.hasOwn(value, 'result') &&
352
365
  (value.isError === undefined || typeof value.isError === 'boolean') &&
353
- (value.providerExecuted === undefined || typeof value.providerExecuted === 'boolean'));
366
+ (value.providerExecuted === undefined || typeof value.providerExecuted === 'boolean') &&
367
+ (value.modelProjection === undefined ||
368
+ decodesDurableToolResultProjection(value.modelProjection)));
354
369
  case 'error':
355
370
  return (hasExactShape(value, ERROR_CONTENT_SHAPE) &&
356
371
  isOptionalString(value.code) &&
@@ -361,6 +376,15 @@ function isRuntimeEventContent(value) {
361
376
  return false;
362
377
  }
363
378
  }
379
+ function decodesDurableToolResultProjection(value) {
380
+ try {
381
+ decodeDurableToolResultProjection(value);
382
+ return true;
383
+ }
384
+ catch {
385
+ return false;
386
+ }
387
+ }
364
388
  function isTurnOrigin(value) {
365
389
  return decodeTurnOrigin(value) !== undefined;
366
390
  }
@@ -439,6 +463,7 @@ function isRuntimeToolDispatch(value) {
439
463
  return (isRecord(value) &&
440
464
  hasExactShape(value, RUNTIME_TOOL_DISPATCH_SHAPE) &&
441
465
  value.protocol === TOOL_BOUNDARY_PROTOCOL_V1 &&
466
+ (value.resultProjectionVersion === undefined || value.resultProjectionVersion === 1) &&
442
467
  typeof value.operationId === 'string' &&
443
468
  typeof value.providerToolCallId === 'string' &&
444
469
  typeof value.toolName === 'string' &&
@@ -30,7 +30,6 @@
30
30
  * module so every write path can call it:
31
31
  * - `sessions:create` IPC → runtime.create → store.create
32
32
  * - `sessions:rename` IPC → runtime.renameSession → store.rename
33
- * - `sessions:branchFromTurn` IPC → runtime.branchFromTurn → store.create
34
33
  *
35
34
  * Pipeline (applied in order):
36
35
  * 1. **Runtime type guard**: `typeof input !== 'string'` → typed
@@ -6,6 +6,7 @@
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "exports": {
9
+ "./durable-tool-result-projection": "./dist/durable-tool-result-projection.js",
9
10
  "./canonical-runtime-event": "./dist/canonical-runtime-event.js",
10
11
  "./runtime-boundary": "./dist/runtime-boundary.js",
11
12
  "./runtime-event": "./dist/runtime-event.js",
@@ -40,6 +40,7 @@ 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
46
  import { SandboxCommandError } from './sandbox/errors.js';
@@ -403,6 +404,33 @@ function nativeApplyPatchFailureOutput(output) {
403
404
  value: { status: 'failed', ...(message ? { output: message } : {}) },
404
405
  };
405
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
+ }
406
434
  /**
407
435
  * One Code Mode cell runs at a time on a backend, with one allowed to wait.
408
436
  * Widening either needs evidence that concurrent cells are wanted; none exists
@@ -617,7 +645,7 @@ export class AiSdkBackend {
617
645
  now: this.now,
618
646
  modelAdapter: this.modelAdapter,
619
647
  createProviderRequestTracker: (trackerInput) => this.createProviderRequestTracker(trackerInput),
620
- materializeRuntimeReplayPlan: (plan, imageBudget, checkpoint) => this.materializeRuntimeReplayPlan(plan, imageBudget, undefined, checkpoint),
648
+ materializeRuntimeReplayPlan: (plan, imageBudget, checkpoint) => this.materializeRuntimeReplayPlan(plan, imageBudget, checkpoint),
621
649
  canReplayProviderNative: (plan) => this.canReplayProviderNative(plan),
622
650
  });
623
651
  if (input.tools.some((tool) => tool.name === MEMORY_REMEMBER_TOOL_NAME || tool.name === MEMORY_EXTRACT_TOOL_NAME)) {
@@ -787,7 +815,7 @@ export class AiSdkBackend {
787
815
  ...(identity.runId ? { runId: identity.runId } : {}),
788
816
  orchestrationMode: identity.orchestrationMode,
789
817
  ...(identity.invocationId ? { invocationId: identity.invocationId } : {}),
790
- materializeDefaultToolResultOutput: ({ toolCallId, output }) => this.materializeToolResultOutput(identity.scope().imageBudget, output, false, toolCallId),
818
+ prepareDurableProjectionArtifact: input.prepareDurableProjectionArtifact,
791
819
  spawnChildSession: input.spawnChildSession,
792
820
  listChildAgents: input.listChildAgents,
793
821
  readChildAgentOutput: input.readChildAgentOutput,
@@ -1267,7 +1295,6 @@ export class AiSdkBackend {
1267
1295
  content: currentUserContent,
1268
1296
  },
1269
1297
  ];
1270
- const settledModelOutputs = new Map();
1271
1298
  const loadDurableTurnEvents = async () => {
1272
1299
  const loadTurnRuntimeEvents = this.input.loadTurnRuntimeEvents;
1273
1300
  if (!loadTurnRuntimeEvents) {
@@ -1307,7 +1334,7 @@ export class AiSdkBackend {
1307
1334
  (replayPlan.hasProviderNativeSemantics && !this.canReplayProviderNative(replayPlan))) {
1308
1335
  throw new Error('durable current-run projection is not replayable');
1309
1336
  }
1310
- const currentTurnMessages = await this.materializeRuntimeReplayPlan(replayPlan, scope.imageBudget, settledModelOutputs, projectionCheckpoint);
1337
+ const currentTurnMessages = await this.materializeRuntimeReplayPlan(replayPlan, scope.imageBudget, projectionCheckpoint);
1311
1338
  return projectionCheckpoint
1312
1339
  ? currentTurnMessages
1313
1340
  : [...priorReplay.messages, ...currentTurnMessages];
@@ -1985,13 +2012,6 @@ export class AiSdkBackend {
1985
2012
  }
1986
2013
  }
1987
2014
  await queue.waitUntilConsumedThroughCurrent();
1988
- for (let index = 0; index < returnedToolCalls.length; index += 1) {
1989
- const toolCall = returnedToolCalls[index];
1990
- const settlement = settlements[index];
1991
- if (toolCall && settlement) {
1992
- settledModelOutputs.set(toolCall.toolCallId, settlement.modelOutput);
1993
- }
1994
- }
1995
2015
  const continuationWillRun = (maxSteps === undefined || runtimeSteps < maxSteps) &&
1996
2016
  !scope.loopStopRequested &&
1997
2017
  !scope.aborted;
@@ -2380,7 +2400,7 @@ export class AiSdkBackend {
2380
2400
  if (!tool)
2381
2401
  throw new Error(`Tool "${name}" is not active or nestable in this cell`);
2382
2402
  const parsedInput = await validateCodeModeToolInput(tool, input);
2383
- const settlement = await scope.toolRuntime.settleToolCallRaw({
2403
+ const settlement = await scope.toolRuntime.settleToolCall({
2384
2404
  tool,
2385
2405
  turnId: context.turnId,
2386
2406
  toolCallId: `${context.toolCallId}:nested:${this.newId()}`,
@@ -2791,7 +2811,7 @@ export class AiSdkBackend {
2791
2811
  if (!plan.hasProviderNativeSemantics) {
2792
2812
  return {
2793
2813
  status: 'ready',
2794
- messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, undefined, projectedHistoryCompactCheckpoint),
2814
+ messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, projectedHistoryCompactCheckpoint),
2795
2815
  gate: 'runtime_replay_text_only',
2796
2816
  diagnostics: plan.diagnostics,
2797
2817
  runtimeEventCount: runtimeContext.length,
@@ -2808,7 +2828,7 @@ export class AiSdkBackend {
2808
2828
  return {
2809
2829
  status: 'ready',
2810
2830
  messages: degradedPlan.items.length > 0 || hasProviderHistoryCompactCheckpoint
2811
- ? await this.materializeRuntimeReplayPlan(degradedPlan, scope.imageBudget, undefined, projectedHistoryCompactCheckpoint)
2831
+ ? await this.materializeRuntimeReplayPlan(degradedPlan, scope.imageBudget, projectedHistoryCompactCheckpoint)
2812
2832
  : await materializeReplayFallback(),
2813
2833
  gate: input.continuation
2814
2834
  ? 'runtime_replay_text_only'
@@ -2821,7 +2841,7 @@ export class AiSdkBackend {
2821
2841
  }
2822
2842
  return {
2823
2843
  status: 'ready',
2824
- messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, undefined, projectedHistoryCompactCheckpoint),
2844
+ messages: await this.materializeRuntimeReplayPlan(plan, scope.imageBudget, projectedHistoryCompactCheckpoint),
2825
2845
  gate: 'runtime_replay_provider_native',
2826
2846
  diagnostics: plan.diagnostics,
2827
2847
  runtimeEventCount: runtimeContext.length,
@@ -2886,7 +2906,7 @@ export class AiSdkBackend {
2886
2906
  * id) keep the older shape: tool calls form a tool-only assistant,
2887
2907
  * text/thinking become standalone messages.
2888
2908
  */
2889
- async materializeRuntimeReplayPlan(plan, budget, settledModelOutputs, historyCompactCheckpoint) {
2909
+ async materializeRuntimeReplayPlan(plan, budget, historyCompactCheckpoint) {
2890
2910
  const out = [];
2891
2911
  const push = (message, eventIds) => {
2892
2912
  out.push(message);
@@ -2989,8 +3009,9 @@ export class AiSdkBackend {
2989
3009
  // diagnostic precisely so this drop path is reachable; see
2990
3010
  // hasBlockingReplayDiagnostics).
2991
3011
  const materializeReplayToolResult = async (result, toolName) => {
2992
- const output = settledModelOutputs?.get(result.toolCallId) ??
2993
- (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`);
2994
3015
  if (toolName !== 'apply_patch')
2995
3016
  return output;
2996
3017
  return result.isError ? nativeApplyPatchFailureOutput(output) : output;
@@ -3175,7 +3196,9 @@ export class AiSdkBackend {
3175
3196
  break;
3176
3197
  }
3177
3198
  downgradedApplyPatchCalls.delete(item.toolCallId);
3178
- 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);
3179
3202
  if (!replayFact)
3180
3203
  break;
3181
3204
  if (downgradedCall.stepId) {
@@ -3461,6 +3484,59 @@ export class AiSdkBackend {
3461
3484
  ],
3462
3485
  };
3463
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
+ }
3464
3540
  async buildCurrentUserContent(budget, text, attachments, quotes, runtimeEventId) {
3465
3541
  return await this.appendImageParts(budget, formatTextWithInlineRefs(text, {
3466
3542
  ...(attachments !== undefined ? { attachments } : {}),
@@ -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