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
@@ -35,7 +35,6 @@ import { DEFAULT_TOOL_MODE } from '@maka/core/tool-mode';
35
35
  import { PLAN_USER_ABANDON_REASON, PLAN_USER_CANCEL_REASON, PlanConflictError, } from '@maka/core/plan';
36
36
  import { DEFAULT_SESSION_NAME } from '@maka/core/session-name';
37
37
  import { DEEP_RESEARCH_SESSION_LABEL, isDeepResearchSession } from '@maka/core/deep-research';
38
- import { SIDE_CONVERSATION_SESSION_LABEL } from '@maka/core/side-conversation';
39
38
  import { SUBAGENT_SESSION_RUNTIME_SCHEMA_VERSION, SUBAGENT_SESSION_SPAWN_SCHEMA_VERSION, childSessionsForParent, deriveTurnRecords, subagentSessionRuntimeSummary, } from '@maka/core/session';
40
39
  import { decodeAgentGraphIntentClaim } from '@maka/core/agent-graph-control';
41
40
  import { executionBoundaryContains } from '@maka/core/sandbox-boundary';
@@ -46,7 +45,6 @@ import { isTerminalRuntimeEvent } from '@maka/core/runtime-event';
46
45
  import { AGENT_GRAPH_OPERATOR_PROVISION_SCHEMA_VERSION } from '@maka/core/agent-graph-topology';
47
46
  import { RuntimeReadModel, RuntimeReadModelError, } from './runtime-read-model.js';
48
47
  import { inspectAgentRunReadModel } from './agent-run-inspect.js';
49
- import { cloneConversationRuntimeLedger as cloneConversationLedger, createConversationCopySlice, prepareConversationRuntimeLedgerCopy, } from './conversation-copy.js';
50
48
  import { firstRuntimeRepairRunId, RuntimeLedgerRepair } from './runtime-ledger-repair.js';
51
49
  import { buildRecoveredTerminalRuntimeEvent, classifyTerminalRuntimeLedger, commitTerminalRunWithRuntimeFact, effectiveRunHeaderFromTerminalFact, terminalRunStatusFromRuntimeEvent, } from './terminal-run-commit.js';
52
50
  import { readLatestContextDiagnostics } from './context-diagnostics.js';
@@ -2578,13 +2576,6 @@ export class SessionManager {
2578
2576
  content: normalizeMessageContent(user),
2579
2577
  };
2580
2578
  }
2581
- async branchFromTurn(sessionId, input) {
2582
- const sourceView = await this.getSessionView(sessionId);
2583
- const slice = createConversationCopySlice(sourceView.messages, input.sourceTurnId, 'through');
2584
- if (!slice)
2585
- throw new Error(`Cannot branch from unknown turn ${input.sourceTurnId}`);
2586
- return this.createBranchSession(sessionId, sourceView, [...slice.messages], input);
2587
- }
2588
2579
  /** Canonical, repaired source view for a Host-owned cross-Session copy. */
2589
2580
  async readConversationCopySnapshot(sessionId) {
2590
2581
  const readMessagesSnapshot = this.deps.store.readMessagesSnapshot;
@@ -2604,130 +2595,6 @@ export class SessionManager {
2604
2595
  turns: deriveTurnRecords(messages),
2605
2596
  };
2606
2597
  }
2607
- async branchBeforeTurn(sessionId, input) {
2608
- const sourceView = await this.getSessionView(sessionId);
2609
- const slice = createConversationCopySlice(sourceView.messages, input.sourceTurnId, 'before');
2610
- if (!slice)
2611
- throw new Error(`Cannot branch before unknown turn ${input.sourceTurnId}`);
2612
- return this.createBranchSession(sessionId, sourceView, [...slice.messages], input);
2613
- }
2614
- /**
2615
- * Create a non-destructive edit-and-resend version. Unlike branchBeforeTurn,
2616
- * this is not a new sidebar conversation: revision lineage lets hosts fold
2617
- * every version into one conversation slot while keeping old transcripts.
2618
- */
2619
- async reviseBeforeTurn(sessionId, input) {
2620
- const sourceView = await this.getSessionView(sessionId);
2621
- const slice = createConversationCopySlice(sourceView.messages, input.sourceTurnId, 'before');
2622
- if (!slice)
2623
- throw new Error(`Cannot revise before unknown turn ${input.sourceTurnId}`);
2624
- return this.createRevisionSession(sessionId, sourceView, [...slice.messages], input);
2625
- }
2626
- async createRevisionSession(sessionId, sourceView, copied, input) {
2627
- const plan = await this.prepareConversationRuntimeLedgerClone(sessionId, sourceView, copied);
2628
- const [header, boundary] = await Promise.all([
2629
- this.deps.store.readHeader(sessionId),
2630
- this.deps.store.readExecutionBoundary(sessionId),
2631
- ]);
2632
- const revisionRootSessionId = header.revisionRootSessionId ?? sessionId;
2633
- const family = (await this.deps.store.list()).filter((candidate) => candidate.id === revisionRootSessionId ||
2634
- candidate.revisionRootSessionId === revisionRootSessionId);
2635
- const revisionIndex = Math.max(1, ...family.map((candidate) => candidate.revisionIndex ?? 1)) + 1;
2636
- const next = await this.deps.store.create({
2637
- cwd: header.cwd,
2638
- ...(header.projectId !== undefined ? { projectId: header.projectId } : {}),
2639
- ...(header.llmConnectionId === undefined
2640
- ? {}
2641
- : { llmConnectionId: header.llmConnectionId }),
2642
- llmConnectionSlug: header.llmConnectionSlug,
2643
- model: header.model,
2644
- thinkingLevel: header.thinkingLevel,
2645
- permissionMode: header.permissionMode,
2646
- collaborationMode: header.collaborationMode,
2647
- orchestrationMode: header.orchestrationMode ?? 'default',
2648
- name: header.name,
2649
- labels: header.labels,
2650
- // A revision of a real branch remains in that branch's conversation
2651
- // slot; revision lineage itself must not create a branch banner.
2652
- parentSessionId: header.parentSessionId,
2653
- branchOfTurnId: header.branchOfTurnId,
2654
- revisionRootSessionId,
2655
- revisionParentSessionId: sessionId,
2656
- revisionOfTurnId: input.sourceTurnId,
2657
- revisionIndex,
2658
- revisionState: 'preparing',
2659
- status: 'active',
2660
- }, boundary);
2661
- try {
2662
- const rewritten = await this.cloneConversationRuntimeLedger(next.id, copied, plan);
2663
- if (rewritten.length > 0)
2664
- await this.deps.store.appendMessages(next.id, [...rewritten]);
2665
- await this.deps.store.appendMessage(next.id, {
2666
- type: 'system_note',
2667
- id: this.deps.newId(),
2668
- ts: this.deps.now(),
2669
- kind: 'session_start',
2670
- data: {
2671
- revisionRootSessionId,
2672
- revisionParentSessionId: sessionId,
2673
- revisionOfTurnId: input.sourceTurnId,
2674
- revisionIndex,
2675
- revisionState: 'preparing',
2676
- },
2677
- });
2678
- await this.deps.store.updateHeader(next.id, {
2679
- isFlagged: header.isFlagged,
2680
- titleIsManual: header.titleIsManual,
2681
- });
2682
- return headerToSummary(await this.deps.store.readHeader(next.id));
2683
- }
2684
- catch (error) {
2685
- return this.rollbackLegacyConversationCopy(next.id, error);
2686
- }
2687
- }
2688
- async createBranchSession(sessionId, sourceView, copied, input) {
2689
- const plan = await this.prepareConversationRuntimeLedgerClone(sessionId, sourceView, copied);
2690
- const [header, boundary] = await Promise.all([
2691
- this.deps.store.readHeader(sessionId),
2692
- this.deps.store.readExecutionBoundary(sessionId),
2693
- ]);
2694
- const next = await this.deps.store.create({
2695
- cwd: header.cwd,
2696
- ...(header.projectId !== undefined ? { projectId: header.projectId } : {}),
2697
- ...(header.llmConnectionId === undefined
2698
- ? {}
2699
- : { llmConnectionId: header.llmConnectionId }),
2700
- llmConnectionSlug: header.llmConnectionSlug,
2701
- model: header.model,
2702
- thinkingLevel: header.thinkingLevel,
2703
- permissionMode: header.permissionMode,
2704
- collaborationMode: header.collaborationMode,
2705
- orchestrationMode: header.orchestrationMode ?? 'default',
2706
- name: input.name ?? `${header.name} · 分支`,
2707
- labels: input.sideConversation
2708
- ? [...new Set([...header.labels, SIDE_CONVERSATION_SESSION_LABEL])]
2709
- : header.labels,
2710
- parentSessionId: sessionId,
2711
- branchOfTurnId: input.sourceTurnId,
2712
- status: 'active',
2713
- }, boundary);
2714
- try {
2715
- const rewritten = await this.cloneConversationRuntimeLedger(next.id, copied, plan);
2716
- if (rewritten.length > 0)
2717
- await this.deps.store.appendMessages(next.id, [...rewritten]);
2718
- await this.deps.store.appendMessage(next.id, {
2719
- type: 'system_note',
2720
- id: this.deps.newId(),
2721
- ts: this.deps.now(),
2722
- kind: 'session_start',
2723
- data: { parentSessionId: sessionId, branchOfTurnId: input.sourceTurnId },
2724
- });
2725
- return headerToSummary(await this.deps.store.readHeader(next.id));
2726
- }
2727
- catch (error) {
2728
- return this.rollbackLegacyConversationCopy(next.id, error);
2729
- }
2730
- }
2731
2598
  async respondToSandboxBoundary(sessionId, response) {
2732
2599
  if (this.deps.interactionAuthority) {
2733
2600
  throw new RuntimeInteractionInvariantError('Hosted permission answers must use the captured continuation');
@@ -3049,43 +2916,6 @@ export class SessionManager {
3049
2916
  }
3050
2917
  this.preparedTranscriptLedgers.add(sessionId);
3051
2918
  }
3052
- async prepareConversationRuntimeLedgerClone(sourceSessionId, sourceView, copiedMessages) {
3053
- if (!this.deps.runStore || !this.deps.runtimeEventStore)
3054
- return undefined;
3055
- return prepareConversationRuntimeLedgerCopy({
3056
- sourceSessionId,
3057
- sourceEvents: sourceView.events,
3058
- copiedMessages,
3059
- runStore: this.deps.runStore,
3060
- runtimeEventStore: this.deps.runtimeEventStore,
3061
- });
3062
- }
3063
- async cloneConversationRuntimeLedger(childSessionId, copiedMessages, plan) {
3064
- if (!plan || !this.deps.runStore || !this.deps.runtimeEventStore)
3065
- return copiedMessages;
3066
- const copied = await cloneConversationLedger({
3067
- plan,
3068
- copiedMessages,
3069
- referenceMap: {
3070
- mode: 'preserve_external',
3071
- sourceSessionId: plan.sourceSessionId,
3072
- targetSessionId: childSessionId,
3073
- },
3074
- runStore: this.deps.runStore,
3075
- runtimeEventStore: this.deps.runtimeEventStore,
3076
- newId: this.deps.newId,
3077
- });
3078
- return copied.copiedMessages;
3079
- }
3080
- async rollbackLegacyConversationCopy(sessionId, error) {
3081
- try {
3082
- await this.deps.store.remove(sessionId);
3083
- }
3084
- catch (cleanupError) {
3085
- throw new AggregateError([error, cleanupError], `Conversation copy ${sessionId} failed and could not be removed`);
3086
- }
3087
- throw error;
3088
- }
3089
2919
  /**
3090
2920
  * Closes only the two provably pre-provider crash windows owned by B2:
3091
2921
  * claim-only and target-Run-created-without-start. A repaired claim never
@@ -32,7 +32,8 @@ import { truncateToolOutput } from './tool-output.js';
32
32
  import { stableHash } from './request-shape.js';
33
33
  import { classifyError } from './provider-error-classification.js';
34
34
  import { AwaitRegistry } from './await-registry.js';
35
- import { jsonValue } from './tool-result-output.js';
35
+ import { compatibilityToolResultProjection, encodeDefaultDurableToolResultOutput, encodeDurableToolResultOutput, encodeDurableToolResultOutputWithArtifacts, } from './durable-tool-result-projection.js';
36
+ import { DURABLE_TOOL_RESULT_PROJECTION_FAILURE, } from '@maka/core/durable-tool-result-projection';
36
37
  import { buildToolOperationId, canonicalToolArgsHash, } from './runtime-commit-sink.js';
37
38
  import { AdmissionLimiter } from './admission-limiter.js';
38
39
  import { SandboxCommandError, sandboxErrorMetadata, serializeSandboxError, } from './sandbox/errors.js';
@@ -262,37 +263,6 @@ export class ToolRuntime {
262
263
  * provider-facing error output; durable runtime commit failures still reject.
263
264
  */
264
265
  async settleToolCall(call) {
265
- const settlement = await this.settleToolCallRaw(call);
266
- const modelOutput = settlement.providerError
267
- ? call.tool.providerTool?.kind === 'openai-apply-patch'
268
- ? {
269
- type: 'json',
270
- value: { status: 'failed', output: settlement.providerError },
271
- }
272
- : { type: 'error-text', value: new Error(settlement.providerError).toString() }
273
- : call.tool.toModelOutput
274
- ? await call.tool.toModelOutput({
275
- toolCallId: call.toolCallId,
276
- input: call.input,
277
- output: settlement.result,
278
- })
279
- : this.input.materializeDefaultToolResultOutput
280
- ? await this.input.materializeDefaultToolResultOutput({
281
- toolCallId: call.toolCallId,
282
- output: settlement.result,
283
- })
284
- : typeof settlement.result === 'string'
285
- ? { type: 'text', value: settlement.result }
286
- : { type: 'json', value: jsonValue(settlement.result) };
287
- return { result: settlement.result, modelOutput };
288
- }
289
- /**
290
- * Settle a tool without producing provider-visible output. Runtime-owned
291
- * nested calls use this path because their result is consumed by Code Mode,
292
- * not sent as a provider tool-result part; materializing it could spend
293
- * turn-scoped provider resources such as the image budget.
294
- */
295
- async settleToolCallRaw(call) {
296
266
  const settlement = this.performToolSettlement(call);
297
267
  // Tracked so endTurn can wait out unwinds already in flight (#2253):
298
268
  // their T2 outcomes must land before the stop path settles the run's
@@ -317,6 +287,40 @@ export class ToolRuntime {
317
287
  const providerError = providerToolErrorMessage(result);
318
288
  return { result, ...(providerError ? { providerError } : {}) };
319
289
  }
290
+ projectToolResult(tool, turnId, toolCallId, input, result) {
291
+ try {
292
+ const providerError = providerToolErrorMessage(result);
293
+ if (providerError) {
294
+ return encodeDurableToolResultOutput(tool.providerTool?.kind === 'openai-apply-patch'
295
+ ? {
296
+ type: 'json',
297
+ value: { status: 'failed', output: providerError },
298
+ }
299
+ : { type: 'error-text', value: new Error(providerError).toString() }, this.input.sessionId);
300
+ }
301
+ if (!tool.toModelOutput) {
302
+ return encodeDefaultDurableToolResultOutput(result, this.input.sessionId);
303
+ }
304
+ const output = tool.toModelOutput({ toolCallId, input, output: result });
305
+ // Projection is deliberately synchronous and total at the tool boundary.
306
+ // Fail closed for untyped/plugin implementations that violate the
307
+ // contract so a completed effect can never be stranded before T2.
308
+ if (isPromiseLike(output)) {
309
+ return DURABLE_TOOL_RESULT_PROJECTION_FAILURE;
310
+ }
311
+ const encode = (resolved) => encodeDurableToolResultOutputWithArtifacts(resolved, this.input.sessionId, this.input.prepareDurableProjectionArtifact
312
+ ? ({ bytes, mediaType }) => this.input.prepareDurableProjectionArtifact({
313
+ turnId,
314
+ bytes,
315
+ mediaType,
316
+ })
317
+ : undefined);
318
+ return encode(output);
319
+ }
320
+ catch {
321
+ return DURABLE_TOOL_RESULT_PROJECTION_FAILURE;
322
+ }
323
+ }
320
324
  /**
321
325
  * Install the per-step tool-availability gating used at the execute boundary.
322
326
  * The backend recomputes the active snapshot before each step; the guard in
@@ -414,7 +418,7 @@ export class ToolRuntime {
414
418
  this.lastFailedToolCallBoundaryKind = boundaryKind;
415
419
  this.lastFailedToolCallBoundaryDetails = boundaryDetails;
416
420
  }
417
- async writeSyntheticToolResult(toolUseId, turnId, text, queue, sandboxDenial, sandboxFailure, uncertainOutcome, activityIdentity = {}, attempt) {
421
+ async writeSyntheticToolResult(toolUseId, turnId, toolName, text, queue, sandboxDenial, sandboxFailure, uncertainOutcome, activityIdentity = {}, attempt) {
418
422
  const content = {
419
423
  kind: 'text',
420
424
  text: formatSyntheticToolErrorText(text),
@@ -431,7 +435,14 @@ export class ToolRuntime {
431
435
  // identity_conflict. The map lookup remains for the pre-dispatch
432
436
  // guards, where no attempt exists and no identity is owed.
433
437
  const durableAttempt = attempt ?? this.durableToolAttempts.get(durableAttemptKey(turnId, toolUseId));
434
- const durableOutcome = await durableAttempt?.commitOutcome(content, true);
438
+ const modelProjection = compatibilityToolResultProjection({
439
+ kind: 'function_response',
440
+ id: toolUseId,
441
+ name: toolName,
442
+ result: content,
443
+ isError: true,
444
+ }, this.input.sessionId) ?? DURABLE_TOOL_RESULT_PROJECTION_FAILURE;
445
+ const durableOutcome = await durableAttempt?.commitOutcome(content, true, modelProjection);
435
446
  const msg = {
436
447
  type: 'tool_result',
437
448
  id: this.input.newId(),
@@ -452,6 +463,7 @@ export class ToolRuntime {
452
463
  ...(durableOutcome ? { operationId: durableOutcome.operationId } : {}),
453
464
  isError: true,
454
465
  content,
466
+ modelProjection,
455
467
  ...activityIdentity,
456
468
  });
457
469
  }
@@ -589,30 +601,24 @@ export class ToolRuntime {
589
601
  ...(tool.displayName ? { displayName: tool.displayName } : {}),
590
602
  ...(stepId !== undefined ? { stepId } : {}),
591
603
  };
592
- let pushedCallEvent;
593
- const pushCallEvent = (lane) => {
594
- // Idempotent by construction: one call, one call event, whichever lane
595
- // asks for it first. A second ask cannot mint a second id.
596
- if (pushedCallEvent)
597
- return pushedCallEvent;
604
+ let callEvent;
605
+ const buildCallEvent = (lane) => {
606
+ if (callEvent)
607
+ return callEvent;
598
608
  const operationId = lane === 'dispatch' ? dispatchOperationId : undefined;
599
- const event = {
609
+ callEvent = {
600
610
  ...callEventFacts,
601
611
  id: operationId ? `${operationId}_call` : this.input.newId(),
602
612
  ...(operationId ? { operationId } : {}),
603
613
  };
604
- queue.push(event);
605
- pushedCallEvent = event;
606
- return event;
614
+ return callEvent;
607
615
  };
608
- /**
609
- * One pre-dispatch refusal: the call fact on the generic lane, then the
610
- * refusal the model reads, on the same lane. Every refusal below routes
611
- * through here so the pair can never be split across lanes again.
612
- */
613
- const refuseBeforeDispatch = async (text, sandboxFailure) => {
614
- pushCallEvent('preflight');
615
- await this.writeSyntheticToolResult(toolUseId, turnId, text, queue, undefined, sandboxFailure, undefined, activityIdentity);
616
+ let callEventPublished = false;
617
+ const publishCallEvent = (event) => {
618
+ if (callEventPublished)
619
+ return;
620
+ queue.push(event);
621
+ callEventPublished = true;
616
622
  };
617
623
  const callMsg = {
618
624
  type: 'tool_call',
@@ -631,12 +637,31 @@ export class ToolRuntime {
631
637
  // timeline and post-restart backfill can pair this call with its step.
632
638
  ...(stepId !== undefined ? { stepId } : {}),
633
639
  };
634
- await this.input.appendMessage(callMsg);
635
- trace?.emit('tool', 'tool_started', 'Tool execution started', {
636
- toolUseId,
637
- toolName: tool.name,
638
- ...(tool.categoryHint !== undefined ? { categoryHint: tool.categoryHint } : {}),
639
- });
640
+ let callMessageAppended = false;
641
+ const appendCallMessage = async () => {
642
+ if (callMessageAppended)
643
+ return;
644
+ await this.input.appendMessage(callMsg);
645
+ callMessageAppended = true;
646
+ };
647
+ const emitToolStartedTrace = () => {
648
+ trace?.emit('tool', 'tool_started', 'Tool execution started', {
649
+ toolUseId,
650
+ toolName: tool.name,
651
+ ...(tool.categoryHint !== undefined ? { categoryHint: tool.categoryHint } : {}),
652
+ });
653
+ };
654
+ /**
655
+ * One pre-dispatch refusal: the call fact on the generic lane, then the
656
+ * refusal the model reads, on the same lane. Every refusal below routes
657
+ * through here so the pair can never be split across lanes again.
658
+ */
659
+ const refuseBeforeDispatch = async (text, sandboxFailure) => {
660
+ await appendCallMessage();
661
+ publishCallEvent(buildCallEvent('preflight'));
662
+ emitToolStartedTrace();
663
+ await this.writeSyntheticToolResult(toolUseId, turnId, tool.name, text, queue, undefined, sandboxFailure, undefined, activityIdentity);
664
+ };
640
665
  if (admissionFailure) {
641
666
  const boundaryKind = boundaryAuthorityAttempt ? 'invalid' : undefined;
642
667
  if (boundaryKind) {
@@ -847,7 +872,7 @@ export class ToolRuntime {
847
872
  try {
848
873
  durableAttempt = await this.prepareDurableToolAttempt({
849
874
  tool,
850
- startEvent: pushCallEvent('dispatch'),
875
+ startEvent: buildCallEvent('dispatch'),
851
876
  persistedArgs,
852
877
  modelFacingArgs,
853
878
  abortSignal: ctx.abortSignal,
@@ -864,6 +889,9 @@ export class ToolRuntime {
864
889
  await disposeManagedMutationAdmission(managedMutationAdmission);
865
890
  throw error;
866
891
  }
892
+ await appendCallMessage();
893
+ publishCallEvent(buildCallEvent('dispatch'));
894
+ emitToolStartedTrace();
867
895
  if (durableAttempt) {
868
896
  this.durableToolAttempts.set(durableAttemptKey(turnId, toolUseId), durableAttempt);
869
897
  }
@@ -911,7 +939,7 @@ export class ToolRuntime {
911
939
  toolCallId: toolUseId,
912
940
  // The id the call event actually carries, not the candidate: by here
913
941
  // `prepareDurableToolAttempt` has pushed it on the dispatch lane.
914
- ...(pushedCallEvent?.operationId ? { operationId: pushedCallEvent.operationId } : {}),
942
+ ...(callEvent?.operationId ? { operationId: callEvent.operationId } : {}),
915
943
  abortSignal: ctx.abortSignal,
916
944
  emitOutput: output.emit,
917
945
  emitProgress: (current, total) => {
@@ -967,10 +995,13 @@ export class ToolRuntime {
967
995
  const content = immutableSnapshot
968
996
  ? Object.freeze(coerceResultContent(result))
969
997
  : coerceResultContent(result);
998
+ const projected = this.projectToolResult(tool, turnId, toolUseId, executionArgs, result);
999
+ const modelProjection = isPromiseLike(projected) ? await projected : projected;
970
1000
  const outcome = {
971
1001
  content,
972
1002
  isError: deriveToolResultStatus(content, result) !== 'success',
973
1003
  durationMs: this.input.now() - startedAt,
1004
+ modelProjection,
974
1005
  };
975
1006
  const value = {
976
1007
  result,
@@ -1001,6 +1032,7 @@ export class ToolRuntime {
1001
1032
  content: value.outcome.content,
1002
1033
  isError: value.outcome.isError,
1003
1034
  durationMs: value.outcome.durationMs,
1035
+ modelProjection: value.outcome.modelProjection,
1004
1036
  };
1005
1037
  }
1006
1038
  finally {
@@ -1072,7 +1104,7 @@ export class ToolRuntime {
1072
1104
  }
1073
1105
  const { result, outcome } = settledExecution.value;
1074
1106
  output.flush();
1075
- const { content, durationMs } = outcome;
1107
+ const { content, durationMs, modelProjection } = outcome;
1076
1108
  // Keep the full provider-facing terminal classification. `isError` is
1077
1109
  // sufficient for the durable response envelope, but it intentionally
1078
1110
  // collapses `aborted` into an error bit and therefore cannot drive live
@@ -1083,10 +1115,10 @@ export class ToolRuntime {
1083
1115
  if (!durableAttempt) {
1084
1116
  throw new RuntimeManagedMutationUnsettledError(new Error('Managed mutation settlement has no durable T1 attempt'));
1085
1117
  }
1086
- durableOutcome = durableAttempt.adoptCommittedOutcome(settledExecution.durableOutcome, content, outcome.isError, durationMs);
1118
+ durableOutcome = durableAttempt.adoptCommittedOutcome(settledExecution.durableOutcome, content, outcome.isError, modelProjection, durationMs);
1087
1119
  }
1088
1120
  else {
1089
- durableOutcome = await durableAttempt?.commitOutcome(content, outcome.isError, durationMs);
1121
+ durableOutcome = await durableAttempt?.commitOutcome(content, outcome.isError, modelProjection, durationMs);
1090
1122
  }
1091
1123
  if (hasSandboxDenial(content)) {
1092
1124
  const denialKey = sandboxDenialKey(tool.name, this.input.header.cwd, executionArgs);
@@ -1123,6 +1155,7 @@ export class ToolRuntime {
1123
1155
  ...(durableOutcome ? { operationId: durableOutcome.operationId } : {}),
1124
1156
  isError: toolResultStatus !== 'success',
1125
1157
  content,
1158
+ modelProjection,
1126
1159
  durationMs,
1127
1160
  ...activityIdentity,
1128
1161
  });
@@ -1217,7 +1250,10 @@ export class ToolRuntime {
1217
1250
  });
1218
1251
  }
1219
1252
  const durationMs = Math.max(0, this.input.now() - startedAt);
1220
- const durableOutcome = await durableAttempt?.commitOutcome(terminalFailure.content, true, durationMs);
1253
+ const terminalResult = this.errorReturn(terminalFailure.message);
1254
+ const projected = this.projectToolResult(tool, turnId, toolUseId, executionArgs, terminalResult);
1255
+ const modelProjection = isPromiseLike(projected) ? await projected : projected;
1256
+ const durableOutcome = await durableAttempt?.commitOutcome(terminalFailure.content, true, modelProjection, durationMs);
1221
1257
  const resultMsg = {
1222
1258
  type: 'tool_result',
1223
1259
  id: this.input.newId(),
@@ -1239,6 +1275,7 @@ export class ToolRuntime {
1239
1275
  ...(durableOutcome ? { operationId: durableOutcome.operationId } : {}),
1240
1276
  isError: true,
1241
1277
  content: terminalFailure.content,
1278
+ modelProjection,
1242
1279
  durationMs,
1243
1280
  ...activityIdentity,
1244
1281
  });
@@ -1268,7 +1305,7 @@ export class ToolRuntime {
1268
1305
  errorClass,
1269
1306
  ...(sandboxError ? { sandbox: sandboxError } : {}),
1270
1307
  });
1271
- return this.errorReturn(terminalFailure.message);
1308
+ return terminalResult;
1272
1309
  }
1273
1310
  const msg = err instanceof ToolResultLimitError
1274
1311
  ? err.message
@@ -1277,7 +1314,7 @@ export class ToolRuntime {
1277
1314
  : uncertainOutcome
1278
1315
  ? `outcome_unknown: ${formatSyntheticToolErrorText(err)}`
1279
1316
  : formatSyntheticToolErrorText(err);
1280
- await this.writeSyntheticToolResult(toolUseId, turnId, msg, queue, sandboxDenialSignalFromError(err), attemptBoundaryDetails, uncertainOutcome, activityIdentity, durableAttempt);
1317
+ await this.writeSyntheticToolResult(toolUseId, turnId, tool.name, msg, queue, sandboxDenialSignalFromError(err), attemptBoundaryDetails, uncertainOutcome, activityIdentity, durableAttempt);
1281
1318
  this.input.recordToolInvocation?.({
1282
1319
  sessionId: this.input.sessionId,
1283
1320
  turnId,
@@ -1385,6 +1422,7 @@ export class ToolRuntime {
1385
1422
  actions: {
1386
1423
  toolDispatch: {
1387
1424
  protocol: TOOL_BOUNDARY_PROTOCOL_V1,
1425
+ resultProjectionVersion: 1,
1388
1426
  operationId,
1389
1427
  providerToolCallId: input.startEvent.toolUseId,
1390
1428
  toolName: input.tool.name,
@@ -1440,7 +1478,7 @@ export class ToolRuntime {
1440
1478
  catch (error) {
1441
1479
  throw new RuntimeCommitBoundaryError('T1', error);
1442
1480
  }
1443
- const buildResponseEvent = (result, isError, durationMs, ts) => ({
1481
+ const buildResponseEvent = (result, isError, modelProjection, durationMs, ts) => ({
1444
1482
  id: `${operationId}_response`,
1445
1483
  invocationId,
1446
1484
  runId,
@@ -1458,6 +1496,7 @@ export class ToolRuntime {
1458
1496
  name: input.tool.name,
1459
1497
  result,
1460
1498
  ...(isError ? { isError: true } : {}),
1499
+ modelProjection,
1461
1500
  },
1462
1501
  refs: {
1463
1502
  operationId,
@@ -1475,10 +1514,10 @@ export class ToolRuntime {
1475
1514
  return {
1476
1515
  operationId,
1477
1516
  responseEventId: `${operationId}_response`,
1478
- commitOutcome: async (result, isError, durationMs) => {
1517
+ commitOutcome: async (result, isError, modelProjection, durationMs) => {
1479
1518
  if (committedOutcome)
1480
1519
  return committedOutcome;
1481
- const responseEvent = buildResponseEvent(result, isError, durationMs, this.input.now());
1520
+ const responseEvent = buildResponseEvent(result, isError, modelProjection, durationMs, this.input.now());
1482
1521
  try {
1483
1522
  await sink.commitToolOutcome({
1484
1523
  operationId,
@@ -1498,10 +1537,10 @@ export class ToolRuntime {
1498
1537
  this.durableToolAttempts.delete(durableAttemptKey(input.startEvent.turnId, input.startEvent.toolUseId));
1499
1538
  return committedOutcome;
1500
1539
  },
1501
- adoptCommittedOutcome: (event, result, isError, durationMs) => {
1540
+ adoptCommittedOutcome: (event, result, isError, modelProjection, durationMs) => {
1502
1541
  if (committedOutcome)
1503
1542
  return committedOutcome;
1504
- const expected = buildResponseEvent(result, isError, durationMs, event.ts);
1543
+ const expected = buildResponseEvent(result, isError, modelProjection, durationMs, event.ts);
1505
1544
  if (!Number.isFinite(event.ts) || !isDeepStrictEqual(event, expected)) {
1506
1545
  throw new RuntimeCommitBoundaryError('T2', new Error('Managed mutation settlement returned a mismatched durable outcome'));
1507
1546
  }
@@ -2367,6 +2406,7 @@ function normalizeManagedMutationSettlement(settlement, maxResultBytes) {
2367
2406
  const response = durableOutcome.content;
2368
2407
  const expectedError = kind === 'operation_failed_no_effect_committed';
2369
2408
  if (response?.kind !== 'function_response' ||
2409
+ response.modelProjection === undefined ||
2370
2410
  (expectedError ? response.isError !== true : response.isError === true)) {
2371
2411
  throw new Error('Managed no-effect settlement has the wrong durable outcome state');
2372
2412
  }
@@ -2374,6 +2414,7 @@ function normalizeManagedMutationSettlement(settlement, maxResultBytes) {
2374
2414
  const outcome = Object.freeze({
2375
2415
  content,
2376
2416
  isError: expectedError,
2417
+ modelProjection: response.modelProjection,
2377
2418
  durationMs: typeof durableOutcome.actions?.stateDelta?.durationMs === 'number'
2378
2419
  ? durableOutcome.actions.stateDelta.durationMs
2379
2420
  : 0,
@@ -2770,6 +2811,12 @@ function providerToolErrorMessage(output) {
2770
2811
  }
2771
2812
  return record.error;
2772
2813
  }
2814
+ function isPromiseLike(value) {
2815
+ return (typeof value === 'object' &&
2816
+ value !== null &&
2817
+ 'then' in value &&
2818
+ typeof value.then === 'function');
2819
+ }
2773
2820
  function summarizeArgs(toolName, args) {
2774
2821
  const projected = toolName === 'WebSearch'
2775
2822
  ? projectWebSearchTelemetryArgs(args)
@@ -12,6 +12,7 @@
12
12
  "./shell-tools": "./dist/shell-tools.js",
13
13
  "./shell-run-manager": "./dist/shell-run-manager.js",
14
14
  "./deep-research-tools": "./dist/deep-research-tools.js",
15
+ "./durable-tool-result-projection": "./dist/durable-tool-result-projection.js",
15
16
  "./tool-artifacts": "./dist/tool-artifacts.js",
16
17
  "./model-factory": "./dist/model-factory.js",
17
18
  "./model-runtime": "./dist/model-runtime.js",
@@ -42,7 +42,12 @@ export async function runExecutionCandidateEntry(argv, entrypointUrl, hooks = {}
42
42
  rootId = parsed.expectedRootId;
43
43
  const { startupAttemptId: parsedStartupAttemptId, ...options } = parsed;
44
44
  startupAttemptId = parsedStartupAttemptId;
45
- result = await startExecutionRuntimeHostCandidate(hooks.overrideOptions ? hooks.overrideOptions(options) : options, {
45
+ result = await startExecutionRuntimeHostCandidate({
46
+ ...(hooks.overrideOptions ? hooks.overrideOptions(options) : options),
47
+ ...(launchOwnerGuard?.admission
48
+ ? { initialClientAdmission: launchOwnerGuard.admission }
49
+ : {}),
50
+ }, {
46
51
  ...hooks.dependencies,
47
52
  processLaunch: {
48
53
  executablePath: process.execPath,
@@ -19,6 +19,7 @@
19
19
  import { closeSync } from 'node:fs';
20
20
  export const RUNTIME_HOST_LAUNCH_OWNER_LEASE_FD_ENV = 'MAKA_RUNTIME_HOST_LAUNCH_OWNER_LEASE_FD';
21
21
  export const RUNTIME_HOST_LAUNCH_OWNER_GUARD_ENV = 'MAKA_RUNTIME_HOST_LAUNCH_OWNER_GUARD';
22
+ export const RUNTIME_HOST_LAUNCH_OWNER_CLIENT_ID_ENV = 'MAKA_RUNTIME_HOST_LAUNCH_OWNER_CLIENT_ID';
22
23
  export const RUNTIME_HOST_LAUNCH_OWNER_RELEASE_KIND = 'runtime-host-launch-owner-release';
23
24
  /**
24
25
  * Closes a launcher-owned Host if its launcher disappears. An optional updater
@@ -37,6 +38,17 @@ export function createRuntimeHostLaunchOwnerGuard(env = process.env) {
37
38
  throw new Error('Runtime Host launch-owner authority descriptor is invalid');
38
39
  }
39
40
  }
41
+ const clientInstanceId = env[RUNTIME_HOST_LAUNCH_OWNER_CLIENT_ID_ENV];
42
+ if (leaseFd !== undefined && !clientInstanceId) {
43
+ throw new Error('Runtime Host launch-owner Client identity is missing');
44
+ }
45
+ const admission = leaseFd === undefined
46
+ ? undefined
47
+ : {
48
+ isClientAdmitted(candidateClientInstanceId) {
49
+ return state === 'released' || candidateClientInstanceId === clientInstanceId;
50
+ },
51
+ };
40
52
  let state = process.connected ? 'owned' : 'lost';
41
53
  let closeHost;
42
54
  let lossSettlement;
@@ -75,6 +87,7 @@ export function createRuntimeHostLaunchOwnerGuard(env = process.env) {
75
87
  process.on('message', onMessage);
76
88
  process.once('disconnect', onDisconnect);
77
89
  return {
90
+ ...(admission ? { admission } : {}),
78
91
  bind(close) {
79
92
  closeHost = close;
80
93
  settleLoss();