openmeld 0.3.220 → 0.3.221
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.
- package/dist/{add-me-membership-GzOoooxS.js → add-me-membership-DpckwGof.js} +2 -2
- package/dist/{add-me-membership-GzOoooxS.js.map → add-me-membership-DpckwGof.js.map} +1 -1
- package/dist/{agents-C8ATowD6.js → agents-2TzCubpV.js} +7 -7
- package/dist/{agents-C8ATowD6.js.map → agents-2TzCubpV.js.map} +1 -1
- package/dist/{api-client-foundation-Dv2OE-Pi.js → api-client-foundation-CGImd4c8.js} +1 -1
- package/dist/{api-client-foundation-CDlVc0zT.js → api-client-foundation-D-Cb6EVg.js} +2 -2
- package/dist/{api-client-foundation-CDlVc0zT.js.map → api-client-foundation-D-Cb6EVg.js.map} +1 -1
- package/dist/{cli-space-api-skevaFSC.js → cli-space-api-B2l1xMPn.js} +4 -4
- package/dist/{cli-space-api-skevaFSC.js.map → cli-space-api-B2l1xMPn.js.map} +1 -1
- package/dist/{command-CmlgCUU2.js → command-MlrjQYq5.js} +11 -11
- package/dist/{command-CmlgCUU2.js.map → command-MlrjQYq5.js.map} +1 -1
- package/dist/{computer-connection-review-Bjyn3UbU.js → computer-connection-review-mO6vn3C3.js} +2 -2
- package/dist/{computer-connection-review-Bjyn3UbU.js.map → computer-connection-review-mO6vn3C3.js.map} +1 -1
- package/dist/{computer-disconnect-CRWsoihu.js → computer-disconnect-CLtQwKDS.js} +3 -3
- package/dist/{computer-disconnect-CRWsoihu.js.map → computer-disconnect-CLtQwKDS.js.map} +1 -1
- package/dist/{computer-setup-continuation-D0kC6-l2.js → computer-setup-continuation-PVwPXc5i.js} +2 -2
- package/dist/{computer-setup-continuation-D0kC6-l2.js.map → computer-setup-continuation-PVwPXc5i.js.map} +1 -1
- package/dist/{daemon-frame-transport-E-H3DjWA.js → daemon-frame-transport-D-4StENt.js} +3 -3
- package/dist/{daemon-frame-transport-E-H3DjWA.js.map → daemon-frame-transport-D-4StENt.js.map} +1 -1
- package/dist/{daemon-lifecycle-journal-DDrWgEzN.js → daemon-lifecycle-journal-DcrVY0xb.js} +2 -2
- package/dist/{daemon-lifecycle-journal-DDrWgEzN.js.map → daemon-lifecycle-journal-DcrVY0xb.js.map} +1 -1
- package/dist/{daemon-service-runtime-M-kfrWro.js → daemon-service-runtime-Kr6Bs2J2.js} +2 -2
- package/dist/{daemon-service-runtime-M-kfrWro.js.map → daemon-service-runtime-Kr6Bs2J2.js.map} +1 -1
- package/dist/{daemon-service-update-coordinator-Clqxj3A1.js → daemon-service-update-coordinator-RJO997me.js} +6 -6
- package/dist/{daemon-service-update-coordinator-Clqxj3A1.js.map → daemon-service-update-coordinator-RJO997me.js.map} +1 -1
- package/dist/{dist-kTVDInkZ.js → dist-B6VsppM7.js} +1 -1
- package/dist/{dist-YPzkhLLp.js → dist-BewA9srP.js} +17 -3
- package/dist/dist-BewA9srP.js.map +1 -0
- package/dist/{elapsed-time-4PuBjDUi.js → elapsed-time-Cw6b9rYy.js} +4 -4
- package/dist/{elapsed-time-4PuBjDUi.js.map → elapsed-time-Cw6b9rYy.js.map} +1 -1
- package/dist/{entry-q_QHht2-.js → entry-BE8uqbkD.js} +2 -2
- package/dist/{entry-q_QHht2-.js.map → entry-BE8uqbkD.js.map} +1 -1
- package/dist/{installation-inventory-CuPmLaLZ.js → installation-inventory-Dwn8FoKT.js} +3 -3
- package/dist/{installation-inventory-CuPmLaLZ.js.map → installation-inventory-Dwn8FoKT.js.map} +1 -1
- package/dist/{installer-mSB-Oiwx.js → installer-CsQ4vNjT.js} +2 -2
- package/dist/{installer-mSB-Oiwx.js.map → installer-CsQ4vNjT.js.map} +1 -1
- package/dist/{openmeld-CFXnmBH6.js → openmeld-Tkp17vPg.js} +24 -24
- package/dist/{openmeld-CFXnmBH6.js.map → openmeld-Tkp17vPg.js.map} +1 -1
- package/dist/{openmeld-maintenance-worker-K-nEox6k.js → openmeld-maintenance-worker-C1J_ISOh.js} +9 -9
- package/dist/{openmeld-maintenance-worker-K-nEox6k.js.map → openmeld-maintenance-worker-C1J_ISOh.js.map} +1 -1
- package/dist/{openmeld-tools-update-join-CN4mjp4-.js → openmeld-tools-update-join-ZLpRTHO3.js} +4 -4
- package/dist/{openmeld-tools-update-join-CN4mjp4-.js.map → openmeld-tools-update-join-ZLpRTHO3.js.map} +1 -1
- package/dist/openmeld.js +4 -4
- package/dist/{prepare-provider-runtime-iA3g-8MS.js → prepare-provider-runtime-CD5ZI-ct.js} +6 -6
- package/dist/{prepare-provider-runtime-iA3g-8MS.js.map → prepare-provider-runtime-CD5ZI-ct.js.map} +1 -1
- package/dist/{prepare-session-executor-DbewUeyQ.js → prepare-session-executor-C2nNM2yb.js} +15 -15
- package/dist/{prepare-session-executor-DbewUeyQ.js.map → prepare-session-executor-C2nNM2yb.js.map} +1 -1
- package/dist/{runtime-D_AGEH9G.js → runtime-DMYoB5_x.js} +11 -11
- package/dist/{runtime-D_AGEH9G.js.map → runtime-DMYoB5_x.js.map} +1 -1
- package/dist/{runtime-agent-controller-reporting-submission-CB25cpq0.js → runtime-agent-controller-reporting-submission-DGm8O4q_.js} +5 -5
- package/dist/{runtime-agent-controller-reporting-submission-CB25cpq0.js.map → runtime-agent-controller-reporting-submission-DGm8O4q_.js.map} +1 -1
- package/dist/{runtime-reporting-health-state-205lHdBE.js → runtime-reporting-health-state-BWZgy4pF.js} +6 -6
- package/dist/{runtime-reporting-health-state-205lHdBE.js.map → runtime-reporting-health-state-BWZgy4pF.js.map} +1 -1
- package/dist/{service-yziCG6lR.js → service-C72KhNft.js} +11 -11
- package/dist/{service-yziCG6lR.js.map → service-C72KhNft.js.map} +1 -1
- package/dist/{service-account-control-BQ1e5Y1X.js → service-account-control-DZjUR3I_.js} +5 -5
- package/dist/{service-account-control-BQ1e5Y1X.js.map → service-account-control-DZjUR3I_.js.map} +1 -1
- package/dist/{service-control-capabilities-C4520NIi.js → service-control-capabilities-C2MF5FUD.js} +3 -3
- package/dist/{service-control-capabilities-C4520NIi.js.map → service-control-capabilities-C2MF5FUD.js.map} +1 -1
- package/dist/{service-control-capabilities-DPYmrWgX.js → service-control-capabilities-Y4CGrchz.js} +1 -1
- package/dist/{state-DLMkZqd8.js → state-CK1WXIsI.js} +2 -2
- package/dist/{state-DLMkZqd8.js.map → state-CK1WXIsI.js.map} +1 -1
- package/dist/{upgrade-BmM1hEB3.js → upgrade-BTIKVek7.js} +6 -6
- package/dist/{upgrade-BmM1hEB3.js.map → upgrade-BTIKVek7.js.map} +1 -1
- package/dist/upgrade-DTB0ZmxI.js +4 -0
- package/package.json +11 -11
- package/dist/dist-YPzkhLLp.js.map +0 -1
- package/dist/upgrade-neqPXWyw.js +0 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-D_AGEH9G.js","names":["toErrorMessage","normalizeOptionalText","normalizeOptionalText","failure","toErrorMessage","resolveBootstrapPlan","markBootstrapInjectedContext","reconcileBootstrapInjectedContextAfterDispatch","rollbackBootstrapExecutionStateAfterDispatchFailure","resolveStructuredActionRequirementFailure","buildStructuredActionRepairPrompt","normalizeOptionalText","resolveStructuredActionRepairContinuation","coerceRuntimeResultToStructuredActionFailure","STORE_SCHEMA","RECORD_SCHEMA","STORE_FILE_NAME","STORE_TEMP_FILE_NAME","MAX_RETAINED_RECORDS","storeTails","rejected","stableJson","outcomeUnknown","readRecords","writeRecords","readErrorCode","isStoredOperation","markBootstrapInjectedContextInternal","reconcileBootstrapInjectedContextAfterDispatchInternal","resolveBootstrapPlanInternal","rollbackBootstrapExecutionStateAfterDispatchFailureInternal","buildStructuredActionRepairPromptInternal","coerceRuntimeResultToStructuredActionFailureInternal","resolveStructuredActionRepairContinuationInternal","resolveStructuredActionRequirementFailureInternal","toErrorMessage","normalizeOptionalText","toTaskExecutionErrorInternal","mergeOpenClawGatewayVisibilityInternal","delay","toErrorMessage","normalizeOptionalText","summarizeSubmissions","toErrorMessage","normalizeOptionalText","toErrorMessage","rejected","forkClaudeCodeSession","toErrorMessage","toErrorMessage"],"sources":["../../../packages/schemas/dist/working-folder-recovery.js","../src/agent-activity/integration-refresh.ts","../src/local-service/execution/dispatch-runtime-preparation.ts","../src/local-service/execution/task-execution-error.ts","../src/provider-hosts/openclaw/agent-controller-conversation.ts","../src/provider-hosts/openclaw/continuation.ts","../src/local-service/continuation/provider-runtime-continuation.ts","../src/local-service/file-access/computer-file-access-admission.ts","../src/local-service/continuation/working-folder-recovery.ts","../src/local-service/file-access/computer-file-access-prompt.ts","../src/local-service/file-access/dispatch-work-handoff.ts","../src/local-service/dispatch/dispatch-agent-reply-observation.ts","../src/local-service/dispatch/dispatch-agent-reply-settlement.ts","../src/local-service/dispatch/dispatch-image-attachments.ts","../src/local-service/dispatch/ensure-dispatch-controller-openmeld-skill.ts","../src/local-service/dispatch/execute-dispatch-conversation.ts","../src/local-service/dispatch/execute-dispatch-bootstrap-plan.ts","../src/local-service/dispatch/execute-dispatch-conversation-state.ts","../src/local-service/dispatch/execute-dispatch-observation.ts","../src/local-service/dispatch/execute-dispatch-structured-action-repair.ts","../src/local-service/session-control/session-fork-operation-store.ts","../src/local-service/dispatch/execution-context-workspace.ts","../src/local-service/dispatch/execution-context-session.ts","../src/local-service/dispatch/prompt-trace.ts","../src/local-service/dispatch/reasoning-stream.ts","../src/local-service/dispatch/send-target-reference.ts","../src/local-service/dispatch/execute-dispatch-task.ts","../src/local-service/carrier/local-control-handlers.ts","../src/local-service/carrier/frame-router.ts","../src/local-service/carrier/local-execution-slots.ts","../src/local-service/control-plane/conversation-execution-status.ts","../src/local-service/reporting/provider-conversation-proof-sync.ts","../src/local-service/reporting/runtime-agent-controller-report-sync.ts","../src/local-service/reporting/runtime-reporting-attempt-observer.ts","../src/local-service/routing/active-permission-mode-sync.ts","../src/local-service/state/context-store.ts","../src/local-service/execution-host/catalog.ts","../src/local-service/execution-recovery/resume-controller-conversation.ts","../src/local-service/execution-recovery/resume-controller-conversation-operation-store.ts","../src/local-service/session-control/fork-agent-session.ts","../src/local-service/execution-host/controls.ts","../src/local-service/execution-host/execution-admission.ts","../src/local-service/execution-host/runtime.ts"],"sourcesContent":[" \n//#region src/working-folder-recovery.ts\nconst WORKING_FOLDER_RECOVERY_QUESTION_ID = \"working_folder_recovery\";\nconst WORKING_FOLDER_RECOVERY_DECLINED = \"context.workspace_recovery_declined\";\nfunction buildWorkingFolderRecoveryQuestion(input) {\n\tlet description = \"This conversation started in a different folder. The task has not started.\";\n\tif (input.previousFolder === \"missing\") description = \"The previous conversation’s folder is no longer available. The task has not started.\";\n\telse if (input.previousFolder === \"restricted\") description = \"The previous conversation’s folder is outside this Computer’s allowed folders. The task has not started.\";\n\treturn {\n\t\tkind: \"question\",\n\t\ttitle: \"Choose where to continue\",\n\t\tdescription,\n\t\tquestions: [{\n\t\t\tquestionId: WORKING_FOLDER_RECOVERY_QUESTION_ID,\n\t\t\tprompt: \"Which conversation should this task use?\",\n\t\t\tmultiple: false,\n\t\t\tallowOther: false,\n\t\t\toptions: [\n\t\t\t\t...input.previousFolder === \"available\" ? [{\n\t\t\t\t\toptionId: \"use_previous_folder\",\n\t\t\t\t\tlabel: \"Continue the previous conversation\",\n\t\t\t\t\tdescription: `Use ${input.previousFolderLabel} for this task. Keep its conversation history. The Agent’s default folder stays unchanged.`\n\t\t\t\t}] : [],\n\t\t\t\t{\n\t\t\t\t\toptionId: \"start_new_conversation\",\n\t\t\t\t\tlabel: \"Start a new conversation\",\n\t\t\t\t\tdescription: `Use ${input.selectedFolderLabel} with the same Agent. The previous conversation stays saved, but its history will not carry over.`\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\toptionId: \"leave_task\",\n\t\t\t\t\tlabel: \"Stop this task\",\n\t\t\t\t\tdescription: \"Keep the previous conversation and folder settings.\"\n\t\t\t\t}\n\t\t\t]\n\t\t}]\n\t};\n}\nfunction isWorkingFolderRecoveryQuestion(request) {\n\treturn request?.kind === \"question\" && request.questions?.length === 1 && request.questions[0]?.questionId === \"working_folder_recovery\";\n}\nfunction isWorkingFolderRecoveryDecline(response) {\n\treturn response.kind === \"question\" && response.answers.length === 1 && response.answers[0]?.questionId === \"working_folder_recovery\" && response.answers[0].values.length === 1 && response.answers[0].values[0] === \"leave_task\";\n}\n/** Only explicit local admission declines qualify; timeouts and lost waiters do not. */\nfunction resolveLocalExecutionOwnerCancellationReason(payload) {\n\tif (payload.status !== \"failed\") return null;\n\treturn payload.errorCode === \"context.workspace_recovery_declined\" || payload.errorCode === \"computer.file_access.owner_declined\" ? payload.errorCode : null;\n}\n//#endregion\nexport { WORKING_FOLDER_RECOVERY_DECLINED, WORKING_FOLDER_RECOVERY_QUESTION_ID, buildWorkingFolderRecoveryQuestion, isWorkingFolderRecoveryDecline, isWorkingFolderRecoveryQuestion, resolveLocalExecutionOwnerCancellationReason };\n\n//# sourceMappingURL=working-folder-recovery.js.map","import { homedir } from \"node:os\";\nimport { resolveOpenMeldRootDir } from \"../config/paths\";\nimport {\n defaultManagedIntegrationPaths,\n installAgentActivityIntegrations,\n} from \"./managed-integrations\";\nimport { listProjectBindings } from \"./project-bindings\";\nimport { registerAgentActivityRoute } from \"./route-registry\";\n\nexport type ManagedAgentActivityIntegrationRefreshResult =\n | {\n integrations: Awaited<\n ReturnType<typeof installAgentActivityIntegrations>\n >;\n status: \"ready\";\n }\n | {\n reason: \"no_project_bindings\";\n status: \"skipped\";\n };\n\nexport type ManagedAgentActivityIntegrationRefreshScheduler = {\n request: () => void;\n stop: () => Promise<void>;\n};\n\nexport async function refreshManagedAgentActivityIntegrations(input?: {\n homeDir?: string;\n install?: typeof installAgentActivityIntegrations;\n register?: typeof registerAgentActivityRoute;\n rootDir?: string;\n}): Promise<ManagedAgentActivityIntegrationRefreshResult> {\n const rootDir = input?.rootDir ?? resolveOpenMeldRootDir();\n const bindings = await listProjectBindings({ rootDir });\n if (bindings.length === 0) {\n return { reason: \"no_project_bindings\", status: \"skipped\" };\n }\n await (input?.register ?? registerAgentActivityRoute)({ rootDir });\n return {\n integrations: await (input?.install ?? installAgentActivityIntegrations)({\n paths: defaultManagedIntegrationPaths(input?.homeDir ?? homedir()),\n }),\n status: \"ready\",\n };\n}\n\nexport function createManagedAgentActivityIntegrationRefreshScheduler(input: {\n onError?: (error: unknown) => void;\n onResult?: (result: ManagedAgentActivityIntegrationRefreshResult) => void;\n refresh?: () => Promise<ManagedAgentActivityIntegrationRefreshResult>;\n}): ManagedAgentActivityIntegrationRefreshScheduler {\n let inFlight: Promise<void> | null = null;\n let pending = false;\n let scheduled = false;\n let stopped = false;\n const refresh = input.refresh ?? refreshManagedAgentActivityIntegrations;\n\n const schedule = () => {\n if (stopped || scheduled) {\n return;\n }\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n run();\n });\n };\n const run = () => {\n if (stopped || inFlight || !pending) {\n return;\n }\n pending = false;\n inFlight = refresh()\n .then((result) => input.onResult?.(result))\n .catch((error) => input.onError?.(error))\n .finally(() => {\n inFlight = null;\n if (pending) {\n schedule();\n }\n });\n };\n\n return {\n request: () => {\n if (stopped) {\n return;\n }\n pending = true;\n schedule();\n },\n stop: async () => {\n stopped = true;\n pending = false;\n await inFlight;\n },\n };\n}\n","import type { OpenClawGatewayVisibility } from \"@openmeld/local-service\";\nimport { providerDispatchRuntimeContextSchema } from \"@openmeld/schemas\";\nimport type {\n OpenMeldDaemonDispatchControllerSnapshot,\n ProviderDispatchRuntimeContext,\n RuntimeTransportDeliveryExecutionIdentity,\n} from \"@openmeld/schemas/types\";\nimport {\n resolveCurrentEffectiveProfileWorkingFolderRuntime,\n resolveEffectiveProfileWorkingFolderRuntime,\n} from \"../../profile-workspace/effective-runtime-resolution\";\nimport {\n type ProviderRuntimePreparationDetails,\n prepareProviderRuntime,\n} from \"../../provider-hosts/prepare-provider-runtime\";\nimport type { DaemonProfileRouteConfig } from \"../core/types\";\nimport { DaemonServiceRunError } from \"../core/types\";\n\n// A healthy session re-observes the route at most every 45 seconds. Keep the\n// compatibility launch fence aligned with the current route-lease freshness\n// window so a transient catalog read failure can preserve a genuinely current\n// route without allowing historical folder state to launch new work.\nexport const CURRENT_ROUTE_WORKING_FOLDER_FRESHNESS_MS = 200_000;\n\nexport type DispatchRuntimePreparation = {\n effectiveRuntimeContext: ProviderDispatchRuntimeContext;\n runtimePreparationDetails: ProviderRuntimePreparationDetails;\n runtimeEnvOverrides: Record<string, string | undefined> | undefined;\n runtimeOpenClawGatewayVisibility: OpenClawGatewayVisibility | null;\n};\n\nexport async function resolveDispatchRuntimeContext(input: {\n defaultProjectId?: string | null;\n openMeldProfileId: string;\n}): Promise<ProviderDispatchRuntimeContext> {\n const resolution = await resolveEffectiveProfileWorkingFolderRuntime({\n defaultProjectId: input.defaultProjectId,\n openMeldProfileId: input.openMeldProfileId,\n mode: \"dispatch\",\n });\n if (resolution.status === \"ready\") {\n return resolution.runtimeContext;\n }\n if (resolution.status === \"missing\") {\n if (\n \"workingFolderSource\" in resolution &&\n resolution.workingFolderSource === \"default_project\" &&\n resolution.defaultProjectId\n ) {\n const folderMissing =\n resolution.defaultProjectFailureReason === \"folder_missing\";\n throw new DaemonServiceRunError({\n code: folderMissing\n ? \"project.local_connection.folder_missing\"\n : \"project.local_connection.missing\",\n message: folderMissing\n ? \"project.local_connection.folder_missing\"\n : \"project.local_connection.missing\",\n projectFailureContext: {\n ...(resolution.defaultProjectBindingGeneration\n ? {\n bindingGeneration: resolution.defaultProjectBindingGeneration,\n }\n : {}),\n projectId: resolution.defaultProjectId,\n },\n });\n }\n throw new DaemonServiceRunError({\n code: \"profile.workspace.missing\",\n message: `profile.workspace.missing: ${resolution.reasonText}`,\n });\n }\n if (\n \"workingFolderSource\" in resolution &&\n resolution.workingFolderSource === \"default_project\" &&\n resolution.defaultProjectId\n ) {\n throw new DaemonServiceRunError({\n code: \"project.local_connection.invalid\",\n message: \"project.local_connection.invalid\",\n projectFailureContext: {\n ...(resolution.defaultProjectBindingGeneration\n ? {\n bindingGeneration: resolution.defaultProjectBindingGeneration,\n }\n : {}),\n projectId: resolution.defaultProjectId,\n },\n });\n }\n throw new DaemonServiceRunError({\n code: \"profile.workspace.invalid\",\n message: `profile.workspace.invalid: ${resolution.reasonText}`,\n });\n}\n\nexport async function resolveDispatchWorkingFolderRuntimeContext(input: {\n controllerSnapshot: OpenMeldDaemonDispatchControllerSnapshot;\n defaultProjectId: string | null;\n defaultProjectIdWasProvided: boolean;\n executionIdentity: RuntimeTransportDeliveryExecutionIdentity;\n nowMs?: number;\n onCurrentWorkingFolderFactRejected?: () => void;\n routeConfig: DaemonProfileRouteConfig | null;\n targetProfileId: string;\n}): Promise<ProviderDispatchRuntimeContext> {\n const route = input.routeConfig;\n const workingFolderRuntime = route?.workingFolderRuntime;\n if (!(route && workingFolderRuntime)) {\n rejectCurrentWorkingFolderFact(\n input,\n \"missing\",\n \"the current route has no working-folder observation\"\n );\n }\n if (\n input.defaultProjectIdWasProvided &&\n input.defaultProjectId !==\n workingFolderRuntime.workingFolderFact.defaultProjectId\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"identity_mismatch\",\n \"the delivered Default Project does not match the current route observation\"\n );\n }\n const identity = input.executionIdentity.core;\n const controllerSnapshot = input.controllerSnapshot;\n if (\n route.profileId !== input.targetProfileId ||\n identity.targetProfileId !== input.targetProfileId ||\n route.bindingId !== identity.bindingId ||\n controllerSnapshot.bindingId !== identity.bindingId ||\n typeof route.configurationRevision !== \"number\" ||\n typeof controllerSnapshot.configurationRevision !== \"number\" ||\n route.configurationRevision !== controllerSnapshot.configurationRevision ||\n route.agentControllerRef !== identity.agentControllerRef ||\n controllerSnapshot.agentControllerRef !== identity.agentControllerRef ||\n route.openMeldServiceRuntimeId !== identity.openMeldServiceRuntimeId.value\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"identity_mismatch\",\n \"the current route does not match the accepted dispatch identity\"\n );\n }\n const observedAtMs = workingFolderRuntime.workingFolderFact.observedAtMs;\n const nowMs = input.nowMs ?? Date.now();\n if (\n observedAtMs > nowMs ||\n nowMs - observedAtMs >= CURRENT_ROUTE_WORKING_FOLDER_FRESHNESS_MS\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"stale\",\n \"the current route working-folder observation has expired\"\n );\n }\n const currentWorkingFolder =\n await resolveCurrentEffectiveProfileWorkingFolderRuntime({\n defaultProjectId: workingFolderRuntime.workingFolderFact.defaultProjectId,\n mode: \"dispatch\",\n openMeldProfileId: input.targetProfileId,\n });\n const currentFact = currentWorkingFolder.workingFolderFact;\n if (\n currentWorkingFolder.status !== \"ready\" ||\n currentFact.source !== workingFolderRuntime.workingFolderFact.source ||\n currentFact.defaultProjectId !==\n workingFolderRuntime.workingFolderFact.defaultProjectId ||\n currentFact.localProjectBindingGeneration !==\n workingFolderRuntime.workingFolderFact.localProjectBindingGeneration ||\n currentWorkingFolder.runtimeContext.providerRuntimeWorkingDirectory !==\n workingFolderRuntime.runtimeContext.providerRuntimeWorkingDirectory\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"changed\",\n \"the effective working folder changed after this route was observed\"\n );\n }\n return workingFolderRuntime.runtimeContext;\n}\n\nfunction rejectCurrentWorkingFolderFact(\n input: { onCurrentWorkingFolderFactRejected?: () => void },\n reason: \"changed\" | \"identity_mismatch\" | \"missing\" | \"stale\",\n detail: string\n): never {\n input.onCurrentWorkingFolderFactRejected?.();\n throwCurrentWorkingFolderFactError(reason, detail);\n}\n\nfunction throwCurrentWorkingFolderFactError(\n reason: \"changed\" | \"identity_mismatch\" | \"missing\" | \"stale\",\n detail: string\n): never {\n throw new DaemonServiceRunError({\n code: `profile.working_folder.current_fact_${reason}`,\n message: `profile.working_folder.current_fact_${reason}: ${detail}`,\n });\n}\n\nexport async function resolveDispatchRuntimeEnvOverrides(input: {\n daemonWorkingDirectory: string;\n parsedTask: {\n agentControllerRef: string;\n targetProfileId: string;\n };\n profileName: string | null;\n providerRuntimeWorkingDirectory?: string;\n}): Promise<Record<string, string | undefined> | undefined> {\n return (\n await prepareProviderRuntime({\n agentControllerRef: input.parsedTask.agentControllerRef,\n daemonWorkingDirectory: input.daemonWorkingDirectory,\n mode: \"dispatch\",\n profileName: input.profileName,\n runtimeContext: parseDispatchRuntimeContextOrThrow({\n providerRuntimeWorkingDirectory:\n input.providerRuntimeWorkingDirectory ?? input.daemonWorkingDirectory,\n source: `dispatch runtime env overrides for ${input.parsedTask.targetProfileId}`,\n }),\n targetProfileId: input.parsedTask.targetProfileId,\n })\n ).envOverrides;\n}\n\nexport async function prepareDispatchRuntimeExecution(input: {\n agentControllerRef: string;\n daemonWorkingDirectory: string;\n dispatchRuntimeContext: ProviderDispatchRuntimeContext;\n profileName: string | null;\n targetProfileId: string;\n}): Promise<DispatchRuntimePreparation> {\n const runtimePreparation = await prepareProviderRuntime({\n agentControllerRef: input.agentControllerRef,\n daemonWorkingDirectory: input.daemonWorkingDirectory,\n mode: \"dispatch\",\n profileName: input.profileName,\n runtimeContext: input.dispatchRuntimeContext,\n targetProfileId: input.targetProfileId,\n });\n const openClawPreparation =\n runtimePreparation.preparationDetails.kind === \"openclaw\"\n ? runtimePreparation.preparationDetails\n : null;\n\n return {\n effectiveRuntimeContext: runtimePreparation.runtimeContext,\n runtimePreparationDetails: runtimePreparation.preparationDetails,\n runtimeEnvOverrides: runtimePreparation.envOverrides,\n runtimeOpenClawGatewayVisibility:\n openClawPreparation?.openClawGatewayVisibility ?? null,\n };\n}\n\nfunction parseDispatchRuntimeContextOrThrow(input: {\n providerRuntimeWorkingDirectory: string;\n source: string;\n}): ProviderDispatchRuntimeContext {\n const parsed = providerDispatchRuntimeContextSchema.safeParse({\n providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,\n });\n if (parsed.success) {\n return parsed.data;\n }\n throw new DaemonServiceRunError({\n code: \"controller.runtime_context.invalid\",\n message: `controller.runtime_context.invalid: invalid provider runtime working directory from ${input.source}`,\n });\n}\n","import type { OpenMeldDaemonTaskResultPayload } from \"@openmeld/schemas/types\";\nimport { toErrorMessage } from \"../core/logger\";\nimport {\n DaemonServiceRunError,\n type OpenMeldDaemonTaskErrorType,\n} from \"../core/types\";\n\nconst EXECUTION_CONTEXT_ERROR_PATTERN = /^execution_context\\.[a-z_]+$/u;\n\nexport function toTaskExecutionError(error: unknown): {\n errorCode: string;\n errorType: OpenMeldDaemonTaskErrorType;\n message: string;\n openClawGatewayVisibility?: OpenMeldDaemonTaskResultPayload[\"openClawGatewayVisibility\"];\n projectFailureContext?: OpenMeldDaemonTaskResultPayload[\"projectFailureContext\"];\n} {\n if (error instanceof DaemonServiceRunError) {\n return {\n errorCode: error.code,\n errorType: \"config\",\n message: error.message,\n openClawGatewayVisibility: error.openClawGatewayVisibility,\n projectFailureContext: error.projectFailureContext,\n };\n }\n if (\n error instanceof Error &&\n EXECUTION_CONTEXT_ERROR_PATTERN.test(error.message)\n ) {\n return {\n errorCode: error.message,\n errorType: \"config\",\n message: error.message,\n };\n }\n return {\n errorCode: \"dispatch.execution_failed\",\n errorType: \"internal\",\n message: toErrorMessage(error),\n };\n}\n","import {\n normalizeOpenClawSpaceIdPrefix,\n slugifyOpenClawNamePart,\n} from \"./naming\";\n\nconst OPENCLAW_SPACE_SESSION_KEY_RE =\n /^agent:(?<agentId>[a-z0-9-]+):openmeld-space:(?<spaceSlug>[a-z0-9-]+)--(?<spaceIdPrefix>[a-z0-9]{8})$/u;\n\nexport type OpenClawAgentControllerConversationClassification =\n | \"missing\"\n | \"canonical_owned\"\n | \"legacy\"\n | \"foreign\";\n\nexport type ParsedOpenClawSpaceSessionKey = {\n agentId: string;\n spaceIdPrefix: string;\n spaceSlug: string;\n};\n\nexport function parseOpenClawSpaceSessionKey(\n value: string\n): ParsedOpenClawSpaceSessionKey | null {\n const match = OPENCLAW_SPACE_SESSION_KEY_RE.exec(String(value ?? \"\").trim());\n if (!match?.groups) {\n return null;\n }\n const agentId = normalizeOptionalText(match.groups.agentId);\n const spaceIdPrefix = normalizeOptionalText(match.groups.spaceIdPrefix);\n const spaceSlug = normalizeOptionalText(match.groups.spaceSlug);\n if (!(agentId && spaceIdPrefix && spaceSlug)) {\n return null;\n }\n return {\n agentId,\n spaceIdPrefix,\n spaceSlug,\n };\n}\n\nexport function matchesOwnedOpenClawSpaceSessionKey(input: {\n openClawBootstrapAgentId: string | null;\n sessionKey: string;\n spaceId: string;\n}): boolean {\n const parsed = parseOpenClawSpaceSessionKey(input.sessionKey);\n if (!parsed) {\n return false;\n }\n const normalizedAgentId = normalizeOptionalText(\n input.openClawBootstrapAgentId\n );\n if (!normalizedAgentId) {\n return false;\n }\n return (\n parsed.agentId === slugifyOpenClawNamePart(normalizedAgentId, \"agent\") &&\n parsed.spaceIdPrefix === normalizeOpenClawSpaceIdPrefix(input.spaceId)\n );\n}\n\nexport function classifyOpenClawAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n openClawBootstrapAgentId: string | null;\n spaceId: string;\n}): OpenClawAgentControllerConversationClassification {\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n if (!agentControllerConversationId) {\n return \"missing\";\n }\n return matchesOwnedOpenClawSpaceSessionKey({\n openClawBootstrapAgentId: input.openClawBootstrapAgentId,\n sessionKey: agentControllerConversationId,\n spaceId: input.spaceId,\n })\n ? \"canonical_owned\"\n : \"legacy\";\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { buildAgentControllerConversationRef } from \"@openmeld/schemas\";\nimport type {\n ProviderRuntimeContinuationResult,\n ProviderSpecificRuntimeContinuationRequest,\n} from \"../../local-service/continuation/types\";\nimport {\n classifyOpenClawAgentControllerConversation,\n type OpenClawAgentControllerConversationClassification,\n} from \"./agent-controller-conversation\";\nimport { buildOpenClawSpaceSessionKey } from \"./naming\";\n\nexport function resolveOpenClawProviderRuntimeContinuation(\n input: ProviderSpecificRuntimeContinuationRequest\n): ProviderRuntimeContinuationResult {\n const conversationClassification =\n classifyOpenClawAgentControllerConversation({\n agentControllerConversationId: input.agentControllerConversationId,\n openClawBootstrapAgentId: resolveOpenClawBootstrapAgentId(\n input.runtimePreparationDetails\n ),\n spaceId: input.spaceId,\n });\n\n return {\n localRuntimeContextPlan: input.standardLocalRuntimeContextPlan,\n taskResultProviderFacts: {\n openClawBinding: {\n classification: conversationClassification,\n },\n },\n agentControllerConversationResumePlan:\n input.standardAgentControllerConversationResumePlan,\n agentControllerConversationOverride:\n resolveOpenClawAgentControllerConversationOverride({\n conversationClassification,\n agentControllerConversationId: input.agentControllerConversationId,\n openClawBootstrapAgentId: resolveOpenClawBootstrapAgentId(\n input.runtimePreparationDetails\n ),\n spaceId: input.spaceId,\n spaceNameSnapshot: input.spaceNameSnapshot,\n }),\n };\n}\n\nfunction resolveOpenClawBootstrapAgentId(\n preparationDetails: ProviderSpecificRuntimeContinuationRequest[\"runtimePreparationDetails\"]\n): string | null {\n return preparationDetails.kind === \"openclaw\"\n ? preparationDetails.bootstrap.agentId\n : null;\n}\n\nfunction resolveOpenClawAgentControllerConversationOverride(input: {\n agentControllerConversationId: string | null;\n conversationClassification: OpenClawAgentControllerConversationClassification;\n openClawBootstrapAgentId: string | null;\n spaceId: string;\n spaceNameSnapshot: string | null;\n}): ProviderRuntimeContinuationResult[\"agentControllerConversationOverride\"] {\n if (\n input.conversationClassification === \"canonical_owned\" &&\n normalizeOptionalText(input.agentControllerConversationId)\n ) {\n return buildAgentControllerConversationRef({\n agentControllerRef: \"builtin:openclaw\",\n agentControllerConversationKind: \"session\",\n agentControllerConversationId: normalizeOptionalText(\n input.agentControllerConversationId\n ) as string,\n });\n }\n\n const openClawBootstrapAgentId = normalizeOptionalText(\n input.openClawBootstrapAgentId\n );\n if (!openClawBootstrapAgentId) {\n return null;\n }\n\n return buildAgentControllerConversationRef({\n agentControllerRef: \"builtin:openclaw\",\n agentControllerConversationKind: \"session\",\n agentControllerConversationId: buildOpenClawSpaceSessionKey({\n agentId: openClawBootstrapAgentId,\n spaceId: input.spaceId,\n spaceNameSnapshot: input.spaceNameSnapshot,\n }),\n });\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { buildRuntimeWorkspaceFingerprint } from \"@openmeld/local-execution\";\nimport type {\n AgentControllerConversationResumePlan,\n ConversationExecutionState,\n ConversationPolicy,\n LocalRuntimeContextPlan,\n ProviderDispatchRuntimeContext,\n RuntimeTransportMode,\n} from \"@openmeld/schemas/types\";\nimport {\n listBuiltinAgentsRegistryEntries,\n resolveRegistryRuntimeAdapterContractByAgentControllerRef,\n} from \"../../agents/registry-source\";\nimport { resolveOpenClawProviderRuntimeContinuation } from \"../../provider-hosts/openclaw/continuation\";\nimport type { ProviderRuntimePreparationDetails } from \"../../provider-hosts/prepare-provider-runtime\";\nimport type {\n ProviderRuntimeContinuationResult,\n ProviderSpecificRuntimeContinuationPolicy,\n} from \"./types\";\n\ntype ConversationCompatibilityRequest = {\n agentControllerConversationId: string | null;\n agentControllerRef: string;\n currentPolicy: ConversationPolicy;\n existingContextId: string | null;\n executionState: ConversationExecutionState | null;\n latestKnownRuntimeWorkspaceFingerprint?: string | null;\n runtimeContext: ProviderDispatchRuntimeContext;\n transportMode: RuntimeTransportMode;\n};\n\ntype ProviderRuntimeContinuationRequest = ConversationCompatibilityRequest & {\n runtimePreparationDetails: ProviderRuntimePreparationDetails;\n spaceId: string;\n spaceNameSnapshot: string | null;\n};\n\ntype ProviderSpecificRuntimeContinuationRegistry = Record<\n string,\n ProviderSpecificRuntimeContinuationPolicy\n>;\n\nconst DEFAULT_PROVIDER_SPECIFIC_CONTINUATION_POLICIES: ProviderSpecificRuntimeContinuationRegistry =\n {\n openclaw: resolveOpenClawProviderRuntimeContinuation,\n };\n\nexport function listRegisteredProviderSpecificContinuationAdapterIds(): string[] {\n return Object.keys(DEFAULT_PROVIDER_SPECIFIC_CONTINUATION_POLICIES).sort();\n}\n\nexport function resolveProviderRuntimeDispatchContinuation(\n input: ProviderRuntimeContinuationRequest,\n options: {\n policies?: ProviderSpecificRuntimeContinuationRegistry;\n resolveAdapterContract?: typeof resolveRegistryRuntimeAdapterContractByAgentControllerRef;\n } = {}\n): ProviderRuntimeContinuationResult {\n const standardAgentControllerConversationResumePlan =\n resolveAgentControllerConversationResumePlan(input);\n const standardLocalRuntimeContextPlan = resolveLocalRuntimeContextPlan(input);\n const runtimeAdapterContract = (\n options.resolveAdapterContract ??\n resolveRegistryRuntimeAdapterContractByAgentControllerRef\n )(input.agentControllerRef);\n\n if (\n !runtimeAdapterContract ||\n runtimeAdapterContract.capabilityDeclaration.continuationCapability ===\n \"standard\"\n ) {\n return {\n localRuntimeContextPlan: standardLocalRuntimeContextPlan,\n taskResultProviderFacts: {},\n agentControllerConversationResumePlan:\n standardAgentControllerConversationResumePlan,\n agentControllerConversationOverride: null,\n };\n }\n\n const policies: ProviderSpecificRuntimeContinuationRegistry =\n options.policies ?? DEFAULT_PROVIDER_SPECIFIC_CONTINUATION_POLICIES;\n const policy = policies[runtimeAdapterContract.adapterId];\n if (!policy) {\n throw new Error(\n `No runtime continuation implementation is registered for adapter '${runtimeAdapterContract.adapterId}'`\n );\n }\n\n return policy({\n ...input,\n standardLocalRuntimeContextPlan,\n standardAgentControllerConversationResumePlan,\n });\n}\n\nexport function resolveAgentControllerConversationResumePlan(\n input: Pick<\n ConversationCompatibilityRequest,\n \"agentControllerConversationId\" | \"existingContextId\"\n >\n): AgentControllerConversationResumePlan {\n const agentControllerConversationId =\n normalizeOptionalText(input.agentControllerConversationId) ??\n normalizeOptionalText(input.existingContextId);\n if (!agentControllerConversationId) {\n return {\n status: \"not_bound\",\n };\n }\n\n return {\n status: \"continue_existing\",\n };\n}\n\nexport function resolveLocalRuntimeContextPlan(\n input: ConversationCompatibilityRequest\n): LocalRuntimeContextPlan {\n if (input.executionState) {\n return {\n reason: null,\n status: \"reuse\",\n };\n }\n\n if (normalizeOptionalText(input.existingContextId)) {\n return {\n reason: \"execution_state_missing\",\n status: \"recreate\",\n };\n }\n\n if (hasWorkspaceChangedSinceLatestKnownRuntime(input)) {\n return {\n reason: \"workspace_changed\",\n status: \"recreate\",\n };\n }\n\n return {\n reason: \"first_local_runtime_context\",\n status: \"recreate\",\n };\n}\n\nfunction hasWorkspaceChangedSinceLatestKnownRuntime(\n input: ConversationCompatibilityRequest\n): boolean {\n const currentRuntimeWorkingDirectory = normalizeOptionalText(\n input.runtimeContext.providerRuntimeWorkingDirectory\n );\n if (!currentRuntimeWorkingDirectory) {\n return false;\n }\n\n const currentRuntimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n currentRuntimeWorkingDirectory\n );\n const latestKnownRuntimeWorkspaceFingerprint = normalizeOptionalText(\n input.latestKnownRuntimeWorkspaceFingerprint\n );\n if (!latestKnownRuntimeWorkspaceFingerprint) {\n return false;\n }\n return (\n currentRuntimeWorkspaceFingerprint !==\n latestKnownRuntimeWorkspaceFingerprint\n );\n}\n\nexport function listRegistryProviderSpecificContinuationAdapterIds(): string[] {\n return listBuiltinAgentsRegistryEntries()\n .filter((agent) => agent.runtime.supported)\n .flatMap((agent) =>\n agent.runtime.adapters\n .filter(\n (adapter) =>\n adapter.capabilityDeclaration.continuationCapability ===\n \"provider_specific\"\n )\n .map((adapter) => adapter.adapterId)\n )\n .sort();\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { realpath } from \"node:fs/promises\";\nimport type {\n AdapterComputerFileAccessBoundary,\n AdapterComputerFileAccessVerificationResult,\n AdapterInteractionCallback,\n AdapterTransportMode,\n AgentControllerPermissionMode,\n} from \"@openmeld/adapter-core\";\nimport { COMPUTER_FILE_ACCESS_OWNER_CANCELLED_REASON_CODE } from \"@openmeld/schemas\";\nimport type { ComputerFileAccessPolicy } from \"@openmeld/schemas/types\";\nimport { isSameOrDescendantPath } from \"../../lib/path-containment\";\nimport { DaemonServiceRunError } from \"../core/types\";\n\nconst RUN_ONCE_OPTION_ID = \"run_once_without_computer_file_access_boundary\";\nconst CANCEL_OPTION_ID = \"cancel_computer_file_access_run\";\n\nexport async function resolveComputerFileAccessAdmission(input: {\n agentControllerPermissionMode?: AgentControllerPermissionMode;\n agentControllerRef: string;\n onInteractionRequest: AdapterInteractionCallback;\n policy: ComputerFileAccessPolicy;\n providerRuntimeWorkingDirectory: string;\n transportMode: AdapterTransportMode;\n verifyBoundary?: (\n boundary: AdapterComputerFileAccessBoundary\n ) => Promise<AdapterComputerFileAccessVerificationResult>;\n}): Promise<{\n boundary: AdapterComputerFileAccessBoundary | null;\n bypassedForThisRun: boolean;\n}> {\n if (input.policy.mode === \"local_agent_settings\") {\n return { boundary: null, bypassedForThisRun: false };\n }\n\n await assertComputerFileAccessWorkingDirectoryAllowed({\n boundary: input.policy,\n providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,\n });\n\n const verification = await input.verifyBoundary?.(input.policy);\n if (verification?.supported) {\n return { boundary: input.policy, bypassedForThisRun: false };\n }\n\n const launchRejected =\n verification?.reasonCode === \"computer.file_access.launch_rejected\";\n const response = await input.onInteractionRequest({\n description: launchRejected\n ? \"The local agent could not start with the requested file access settings. Cancel and check the selected agent’s version and configuration. Running once without this boundary removes the Computer file access restriction for this Wake.\"\n : \"OpenMeld can’t verify that this local agent can enforce this computer’s file access boundary. Run this Wake once without the boundary, or cancel it.\",\n kind: \"permission\",\n options: [\n {\n intent: \"allow_once\",\n label: \"Run once without this boundary\",\n optionId: RUN_ONCE_OPTION_ID,\n },\n {\n intent: \"deny\",\n label: \"Cancel run\",\n optionId: CANCEL_OPTION_ID,\n },\n ],\n subject: {\n resource: \"Computer file access boundary\",\n type: \"additional_permissions\",\n },\n title: \"File access needs your decision\",\n });\n\n if (\n response.kind === \"permission\" &&\n response.optionId === RUN_ONCE_OPTION_ID\n ) {\n return { boundary: null, bypassedForThisRun: true };\n }\n\n if (\n response.kind !== \"permission\" ||\n response.optionId !== CANCEL_OPTION_ID\n ) {\n const code =\n response.kind === \"cancel\"\n ? \"computer.file_access.interaction_cancelled\"\n : \"computer.file_access.response_invalid\";\n throw new DaemonServiceRunError({\n code,\n message: `${code}: the file access decision did not authorize this run`,\n });\n }\n throw new DaemonServiceRunError({\n code: COMPUTER_FILE_ACCESS_OWNER_CANCELLED_REASON_CODE,\n message: `${COMPUTER_FILE_ACCESS_OWNER_CANCELLED_REASON_CODE}: the Computer owner declined running this Wake without the configured file access boundary`,\n });\n}\n\nexport async function assertComputerFileAccessWorkingDirectoryAllowed(input: {\n boundary: AdapterComputerFileAccessBoundary;\n providerRuntimeWorkingDirectory: string;\n}): Promise<void> {\n const workingDirectory = await realpath(\n input.providerRuntimeWorkingDirectory\n );\n const matchesConfiguredFolder = input.boundary.folders.some((folder) =>\n isSameOrDescendantPath(workingDirectory, folder)\n );\n const allowed =\n input.boundary.mode === \"only_selected_folders\"\n ? matchesConfiguredFolder\n : !matchesConfiguredFolder;\n if (allowed) {\n return;\n }\n\n throw new DaemonServiceRunError({\n code: \"computer.file_access.working_directory_denied\",\n message:\n \"computer.file_access.working_directory_denied: this Wake’s working folder is outside the Computer file access boundary\",\n });\n}\n","import { realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename } from \"node:path\";\nimport type { AdapterInteractionCallback } from \"@openmeld/adapter-core\";\nimport {\n buildWorkingFolderRecoveryQuestion,\n WORKING_FOLDER_RECOVERY_DECLINED,\n WORKING_FOLDER_RECOVERY_QUESTION_ID,\n} from \"@openmeld/schemas\";\nimport type {\n ComputerFileAccessPolicy,\n ConversationExecutionState,\n} from \"@openmeld/schemas/types\";\nimport {\n readOpenCodeSessionRows,\n resolveOpenCodeDatabasePath,\n} from \"../../agent-activity/opencode-storage\";\nimport { DaemonServiceRunError } from \"../core/types\";\nimport { assertComputerFileAccessWorkingDirectoryAllowed } from \"../file-access/computer-file-access-admission\";\n\ntype FolderChoice = { workingDirectory: string; startNewConversation: boolean };\n\n/** Admission asks the owner before any prompt, attachment, or bootstrap uses a folder. */\nexport async function resolveWorkingFolderRecovery(input: {\n agentControllerRef: string;\n nativeSessionId: string | null;\n workingDirectory: string;\n policy: ComputerFileAccessPolicy;\n onInteractionRequest: AdapterInteractionCallback;\n inspectSession?: (\n nativeSessionId: string\n ) => Promise<{ directory: string; sessionId: string }>;\n hasExecutionContext?: boolean;\n}): Promise<FolderChoice> {\n const unchanged = {\n workingDirectory: input.workingDirectory,\n startNewConversation: false,\n };\n if (\n input.hasExecutionContext ||\n input.agentControllerRef !== \"builtin:opencode\" ||\n !input.nativeSessionId\n ) {\n return unchanged;\n }\n const nativeSessionId = input.nativeSessionId;\n const inspect = () =>\n (input.inspectSession ?? inspectRetainedOpenCodeSession)(nativeSessionId);\n const session = await inspect();\n const selectedFolder = await realpath(input.workingDirectory);\n const previousFolder = await realpath(session.directory).catch(() => null);\n if (selectedFolder === previousFolder) {\n return unchanged;\n }\n let previousFolderAllowed = previousFolder !== null;\n if (previousFolder && input.policy.mode !== \"local_agent_settings\") {\n try {\n await assertComputerFileAccessWorkingDirectoryAllowed({\n boundary: input.policy,\n providerRuntimeWorkingDirectory: previousFolder,\n });\n } catch {\n previousFolderAllowed = false;\n }\n }\n const previousFolderStatus = previousFolder ? \"restricted\" : \"missing\";\n const response = await input.onInteractionRequest(\n buildWorkingFolderRecoveryQuestion({\n previousFolder: previousFolderAllowed\n ? \"available\"\n : previousFolderStatus,\n previousFolderLabel: basename(session.directory),\n selectedFolderLabel: basename(selectedFolder),\n })\n );\n const choice =\n response.kind === \"question\" &&\n response.answers.length === 1 &&\n response.answers[0]?.questionId === WORKING_FOLDER_RECOVERY_QUESTION_ID &&\n response.answers[0].values.length === 1\n ? response.answers[0].values[0]\n : null;\n if (choice === \"leave_task\") {\n throw failure(\n WORKING_FOLDER_RECOVERY_DECLINED,\n \"The Computer owner stopped this task before the Agent started. The previous conversation is saved.\"\n );\n }\n if (\n choice !== \"start_new_conversation\" &&\n !(choice === \"use_previous_folder\" && previousFolderAllowed)\n ) {\n throw failure(\n \"context.workspace_recovery_unanswered\",\n \"This task did not start because no folder choice was confirmed. Send it again when you’re ready.\"\n );\n }\n // The owner may be away for hours. Re-read the exact native association and\n // both filesystem identities; an old answer must not authorize a moved path.\n const latest = await inspect();\n if (\n latest.sessionId !== session.sessionId ||\n latest.directory !== session.directory ||\n (await realpath(input.workingDirectory).catch(() => null)) !==\n selectedFolder ||\n (previousFolder &&\n (await realpath(session.directory).catch(() => null)) !== previousFolder)\n ) {\n throw failure(\n \"context.workspace_recovery_changed\",\n \"The conversation or folder changed while waiting. Send this task again to review the current choices.\"\n );\n }\n return {\n workingDirectory:\n choice === \"use_previous_folder\" && previousFolder\n ? previousFolder\n : selectedFolder,\n startNewConversation: choice === \"start_new_conversation\",\n };\n}\n\nexport function resolveRecoveredLedgerConversation(input: {\n startNewConversation: boolean;\n bindingConversationId: string | null;\n existingContextId: string | null;\n currentExecutionState: ConversationExecutionState | null;\n}) {\n return input.startNewConversation\n ? {\n bindingConversationId: null,\n existingContextId: null,\n currentExecutionState: null,\n }\n : input;\n}\n\nfunction failure(\n code: string,\n message: string,\n cause?: unknown\n): DaemonServiceRunError {\n const error = new DaemonServiceRunError({ code, message });\n if (cause !== undefined) {\n error.cause = cause;\n }\n return error;\n}\n\nasync function inspectRetainedOpenCodeSession(\n nativeSessionId: string\n): Promise<{ directory: string; sessionId: string }> {\n try {\n const rows = await readOpenCodeSessionRows(\n resolveOpenCodeDatabasePath({ homeDir: homedir() }),\n nativeSessionId\n );\n const session = rows[0];\n if (\n rows.length === 1 &&\n session?.id === nativeSessionId &&\n typeof session.directory === \"string\" &&\n session.directory.trim()\n ) {\n return { directory: session.directory, sessionId: nativeSessionId };\n }\n } catch (cause) {\n // This is only a preflight read. Never repair or create the provider's store.\n throw failure(\n \"context.workspace_verification_unavailable\",\n \"OpenMeld could not read this conversation’s folder. Open the conversation in OpenCode, then try this task again.\",\n cause\n );\n }\n throw failure(\n \"context.workspace_verification_unavailable\",\n \"OpenMeld could not read this conversation’s folder. Open the conversation in OpenCode, then try this task again.\"\n );\n}\n","import { createHash } from \"node:crypto\";\nimport type { AdapterInstructionPrompt } from \"@openmeld/adapter-core\";\nimport type { ComputerFileAccessPolicy } from \"@openmeld/schemas/types\";\n\nexport const COMPUTER_FILE_ACCESS_AWARENESS =\n \"Stay within the file access available to this OpenMeld run. Treat denied paths as intentional and continue with the safest useful alternative. Only the Computer owner can change this boundary.\";\n\nexport function applyComputerFileAccessAwareness(input: {\n policy: ComputerFileAccessPolicy;\n promptPlan: AdapterInstructionPrompt & { fallbackPrompt: string };\n}): AdapterInstructionPrompt & { fallbackPrompt: string } {\n if (input.policy.mode === \"local_agent_settings\") {\n return input.promptPlan;\n }\n\n const developerInstructions = `${input.promptPlan.developerInstructions}\\n\\n${COMPUTER_FILE_ACCESS_AWARENESS}`;\n const fingerprint = createHash(\"sha256\")\n .update(developerInstructions, \"utf8\")\n .digest(\"hex\");\n const epochPrefix = input.promptPlan.instructionEpoch.split(\":\", 1)[0];\n return {\n ...input.promptPlan,\n developerInstructions,\n fallbackPrompt: `${COMPUTER_FILE_ACCESS_AWARENESS}\\n\\n${input.promptPlan.fallbackPrompt}`,\n instructionEpoch: `${epochPrefix}:${fingerprint}`,\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { lstat, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n createOrganizationSkillsApi,\n createSpaceApi,\n} from \"@openmeld/api-client\";\nimport { spaceWorkSelectionSchema } from \"@openmeld/schemas\";\nimport { getAuthSessionState } from \"../../config/auth-session\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../../config/openmeld-request-context\";\nimport { resolveOpenMeldRootDir } from \"../../config/paths\";\nimport { materializeOrganizationSkillRelease } from \"../../organization-skills/cache\";\nimport { createCliApiClientFoundation } from \"../../space/api-client-foundation\";\nimport { downloadWorkingCopyFile } from \"../../space/working-copy-download\";\nimport type { ParsedDispatchTask } from \"../core/types\";\nimport { createSpaceWorkingCopies } from \"./space-working-copy\";\n\n/** The admitted Service prepares inputs; no login state is copied into the workspace. */\nexport async function prepareDispatchWorkHandoff(input: {\n task: Pick<\n ParsedDispatchTask,\n | \"workHandoff\"\n | \"workingCopyId\"\n | \"executionContext\"\n | \"agentControllerRef\"\n | \"transportMode\"\n | \"targetProfileId\"\n | \"targetProfileName\"\n | \"spaceId\"\n | \"spacePassword\"\n | \"taskId\"\n | \"prompt\"\n >;\n ownerUserId: string;\n workingDirectory: string;\n}) {\n const { task } = input;\n if (!task.workHandoff) {\n return input.workingDirectory;\n }\n if (\n !task.executionContext ||\n task.executionContext.access !== \"space_context\" ||\n task.agentControllerRef !== \"builtin:codex\" ||\n task.transportMode !== \"codex-app-server\"\n ) {\n throw new Error(\n \"Selected-file handoffs require a new Space-only context on Codex App Server. This controller cannot enforce that boundary.\"\n );\n }\n const organizationId = task.executionContext.scope.organizationId;\n const baseUrl = await resolveBaseUrl();\n const laneRoot = resolveOpenMeldRootDir();\n const assertCurrentIdentity = async () => {\n const auth = await getAuthSessionState({ validateRemote: false });\n if (\n auth.session?.user?.id !== input.ownerUserId ||\n auth.session?.activeOrganization?.id !== organizationId\n ) {\n throw new Error(\n \"The account or Organization changed before handoff preparation.\"\n );\n }\n };\n await assertCurrentIdentity();\n const requestContext = buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n openMeldProfileId: task.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.ownerUserId,\n profileName: task.targetProfileName ?? task.targetProfileId,\n },\n });\n const foundation = createCliApiClientFoundation(baseUrl, {\n expectedOwnerUserId: input.ownerUserId,\n organizationId,\n });\n const api = createSpaceApi(foundation);\n const common = {\n spaceId: task.spaceId,\n requestContext,\n ...(task.spacePassword ? { spacePassword: task.spacePassword } : {}),\n };\n const copies = createSpaceWorkingCopies({\n laneRoot,\n scope: {\n accountId: input.ownerUserId,\n organizationId,\n spaceId: task.spaceId,\n profileId: task.targetProfileId,\n baseUrl,\n },\n assertCurrentIdentity,\n transport: {\n read: (fileId, revision) =>\n downloadWorkingCopyFile(api, { ...common, fileId, revision }),\n get: async (fileId) => (await api.getFile({ ...common, fileId })).file,\n write: async (write) =>\n await api.updateFileContent({ ...common, ...write }),\n },\n });\n const key = createHash(\"sha256\")\n .update(\n JSON.stringify([\n baseUrl,\n input.ownerUserId,\n organizationId,\n task.spaceId,\n task.targetProfileId,\n task.taskId,\n ])\n )\n .digest(\"hex\");\n const records = join(laneRoot, \"space-work-dispatches\");\n await mkdir(records, { recursive: true, mode: 0o700 });\n const recordPath = join(records, `${key}.json`);\n let copyId: string;\n let root: string;\n const stored = await readFile(recordPath, \"utf8\").catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n );\n if (stored) {\n const record = JSON.parse(stored) as {\n copyId: string;\n root: string;\n };\n copyId = record.copyId;\n const status = await copies.resume(copyId);\n root = status.root;\n if (\n root !== record.root ||\n root !== join(input.workingDirectory, `handoff-${copyId}`)\n ) {\n throw new Error(\"The handoff workspace identity changed.\");\n }\n } else {\n // The existing dispatch owner serializes execution. This private record is\n // published only after preparation; partial directories are never reused.\n copyId = randomUUID();\n root = join(input.workingDirectory, `handoff-${copyId}`);\n await copies.prepare(\n spaceWorkSelectionSchema.parse({\n schemaVersion: 1,\n files: task.workHandoff.files,\n }),\n root,\n copyId\n );\n await writeFile(recordPath, JSON.stringify({ copyId, root }), {\n flag: \"wx\",\n mode: 0o600,\n });\n }\n const skillsRoot = join(root, \".openmeld-skills\");\n if (task.workHandoff.skills.length) {\n await mkdir(skillsRoot, { recursive: true, mode: 0o700 });\n if ((await lstat(skillsRoot)).isSymbolicLink()) {\n throw new Error(\"The Skill directory was replaced by a symbolic link.\");\n }\n }\n const skills = createOrganizationSkillsApi(foundation);\n for (const [index, selected] of task.workHandoff.skills.entries()) {\n await assertCurrentIdentity();\n const result = await skills.get({ ...selected, requestContext });\n const release = result.selectedRelease;\n if (\n !release ||\n result.skill.organizationId !== organizationId ||\n !result.skill.enabled ||\n release.releaseId !== selected.releaseId ||\n release.digest !== selected.digest ||\n release.bundle.portable.name !== selected.name\n ) {\n throw new Error(\n \"The selected Skill release is unavailable or changed. No latest-version fallback is allowed.\"\n );\n }\n await materializeOrganizationSkillRelease({\n ...selected,\n organizationId,\n bundle: release.bundle,\n releaseDirectory: join(skillsRoot, String(index)),\n });\n }\n await assertCurrentIdentity();\n await copies.status(copyId);\n task.workingCopyId = copyId;\n task.prompt +=\n \"\\n\\nThe selected inputs are prepared in your working directory. Selected Skills (including resources) are in .openmeld-skills/<selection index>/SKILL.md. Use the working_copy tool to check, commit or reconcile your edits; it does not complete this Wake. Attach the exact saved file references with the reply tool when delivering results.\";\n return root;\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport type {\n OpenMeldRequestContext,\n OpenMeldSpaceEgressAction,\n SpaceThreadContext,\n} from \"@openmeld/schemas/types\";\nimport {\n buildSpaceRoundSignalPublication,\n isWakeClosingSystemNoticeType,\n} from \"@openmeld/space\";\nimport {\n SPACE_COLLABORATION_CONTEXT_RULE,\n SPACE_PERSONAL_CONTRIBUTION_RULE,\n} from \"@openmeld/space-mesh\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { createCliSpaceApi } from \"../../space/cli-space-api\";\nimport { fetchSpaceUpdates } from \"../../space/updates-api\";\n\nconst OBSERVATION_LIMIT = 20;\nconst SIGNAL_TEXT_LIMIT = 2000;\n\nexport type DispatchAgentReplyObservation = {\n observedThroughSignalId: string;\n relevantSignals: SignalEnvelope[];\n status: \"changed\" | \"current\";\n};\n\nexport async function readDispatchAgentReplyObservation(input: {\n currentWakeTargetProfileIds?: readonly string[];\n requestContext: OpenMeldRequestContext;\n sourceSignalId: string;\n spaceId: string;\n spacePassword: string | null;\n threadContext: SpaceThreadContext | null;\n wakeSourceSignalId: string;\n}): Promise<DispatchAgentReplyObservation> {\n const baseUrl = await resolveBaseUrl();\n const candidates = input.threadContext\n ? await readThreadSignalsAfterSource({\n baseUrl,\n requestContext: input.requestContext,\n sourceSignalId: input.sourceSignalId,\n spaceId: input.spaceId,\n spacePassword: input.spacePassword,\n threadId: input.threadContext.threadId,\n })\n : (\n await fetchSpaceUpdates({\n afterSignalId: input.sourceSignalId,\n baseUrl,\n limit: OBSERVATION_LIMIT,\n requestContext: input.requestContext,\n space: input.spaceId,\n ...(input.spacePassword ? { password: input.spacePassword } : {}),\n })\n ).signals;\n return resolveDispatchAgentReplyObservation({\n candidates,\n currentWakeTargetProfileIds: input.currentWakeTargetProfileIds,\n sourceSignalId: input.sourceSignalId,\n wakeSourceSignalId: input.wakeSourceSignalId,\n });\n}\n\nexport function resolveDispatchAgentReplyObservation(input: {\n candidates: readonly SignalEnvelope[];\n currentWakeTargetProfileIds?: readonly string[];\n sourceSignalId: string;\n wakeSourceSignalId?: string;\n}): DispatchAgentReplyObservation {\n const currentWakeTargetProfileIds = new Set(\n (input.currentWakeTargetProfileIds ?? []).map((profileId) =>\n profileId.trim()\n )\n );\n const relevantSignals = input.candidates\n .filter(\n (signal) =>\n isRelevantCollaborationSignal(signal) &&\n isSignalInCurrentWakeScope(\n signal,\n currentWakeTargetProfileIds,\n input.wakeSourceSignalId ?? input.sourceSignalId\n )\n )\n .slice(0, OBSERVATION_LIMIT);\n const observedThroughSignalId =\n input.candidates.at(-1)?.id ?? input.sourceSignalId;\n return {\n observedThroughSignalId,\n relevantSignals,\n status: relevantSignals.length > 0 ? \"changed\" : \"current\",\n };\n}\n\nexport function attachAgentReplyObservation(input: {\n action: OpenMeldSpaceEgressAction;\n observedThroughSignalId: string;\n}): OpenMeldSpaceEgressAction {\n if (input.action.type !== \"post_message\") {\n return input.action;\n }\n return {\n ...input.action,\n observedThroughSignalId: input.observedThroughSignalId,\n };\n}\n\nexport function buildAgentReplyReconsiderationPrompt(input: {\n action: OpenMeldSpaceEgressAction;\n originalWake: {\n sourceSignalId: string;\n targetProfileId: string;\n text: string;\n };\n relevantSignals: readonly SignalEnvelope[];\n omittedThroughSignalId?: string;\n spaceId: string;\n}): string {\n const updates = input.relevantSignals.map((signal) => ({\n actorProfileId: readCollaborationActorProfileId(signal),\n authorKind: signal.profile.kind,\n outcome: resolveCollaborationOutcome(signal),\n signalId: signal.id,\n text: readSignalText(signal).slice(0, SIGNAL_TEXT_LIMIT),\n truncated: readSignalText(signal).length > SIGNAL_TEXT_LIMIT,\n }));\n return [\n \"OpenMeld concurrent Space update review.\",\n `Space: ${input.spaceId}`,\n \"Continue the original Wake, not a new assignment: do not run activation-intent classification against the newer messages. Another Agent's reply does not turn you into a reference or candidate or transfer your assignment.\",\n `Original Wake (the assignment being completed): ${JSON.stringify(input.originalWake)}`,\n \"This bounded view includes earlier review facts as well as new public messages, in publication order. Prior review turns may not be present in this conversation.\",\n SPACE_COLLABORATION_CONTEXT_RULE,\n \"Your previous action is an unpublished proposal.\",\n \"An accepted action acknowledgement does not mean the Space published it. You still have one public reply available for this Wake.\",\n \"Do not redo completed work or repeat external side effects.\",\n \"A failed, stopped, or silent outcome is not a public contribution. Use it only as truthful availability and coordination context.\",\n \"Keep the user's full request as the goal. Reconsider only the final Space action in light of these newer messages.\",\n \"If a follow-up needs work that this review cannot perform, say what remains undone; do not imply that acknowledging it starts or queues that work.\",\n SPACE_PERSONAL_CONTRIBUTION_RULE,\n \"For dependent contributions, follow the user's shared constraints and confirmed contributions. In an ordered sequence, contribute only the next valid step, not a future step with unpublished prerequisites. A participant list or proposed division of work is not evidence that earlier steps happened. Avoid duplicating completed work, not requested personal answers.\",\n \"Call exactly one dispatch-scoped OpenMeld Space Action tool for the final action and inspect its acknowledgement. Discover the tool before concluding it is unavailable; use the provided CLI only if unavailable. Answer text never becomes an action.\",\n \"Record the final action even if you keep the same answer.\",\n ...(input.omittedThroughSignalId\n ? [\n `Earlier review messages through signal ${JSON.stringify(input.omittedThroughSignalId)} were omitted from this bounded view. Absence is not evidence that nothing happened. Read the originating Space or thread history if those facts affect your action.`,\n ]\n : []),\n \"A truncated message is an excerpt; read its original when omitted details affect your action.\",\n `Previous proposed action: ${JSON.stringify(input.action)}`,\n `Observed Space messages: ${JSON.stringify(updates)}`,\n ].join(\"\\n\");\n}\n\nexport async function coordinateDispatchAgentReply<T>(input: {\n action: OpenMeldSpaceEgressAction;\n originalWake: {\n sourceSignalId: string;\n targetProfileId: string;\n text: string;\n };\n currentValue: T;\n observation: DispatchAgentReplyObservation;\n reconsider: (\n prompt: string,\n observation: DispatchAgentReplyObservation\n ) => Promise<{\n action: OpenMeldSpaceEgressAction | undefined;\n value: T;\n }>;\n refreshObservation?: (\n observedThroughSignalId: string\n ) => Promise<DispatchAgentReplyObservation>;\n spaceId: string;\n}): Promise<{\n action: OpenMeldSpaceEgressAction | undefined;\n reconsiderationCount: number;\n reconsidered: boolean;\n value: T;\n}> {\n let action: OpenMeldSpaceEgressAction | undefined = input.action;\n let observation = input.observation;\n let reconsiderationCount = 0;\n let value = input.currentValue;\n // Repair forks preserve canonical identity, not the previous fork's memory.\n // Retain a bounded public view only for this coordination call, never a\n // private transcript or a second source of Space/execution truth.\n const observedSignals = new Map<string, SignalEnvelope>();\n let omittedThroughSignalId: string | undefined;\n\n while (observation.status === \"changed\") {\n for (const signal of observation.relevantSignals) {\n observedSignals.set(signal.id, signal);\n if (observedSignals.size > OBSERVATION_LIMIT) {\n const oldestId = observedSignals.keys().next().value;\n if (oldestId) {\n observedSignals.delete(oldestId);\n omittedThroughSignalId = oldestId;\n }\n }\n }\n const reconsidered = await input.reconsider(\n buildAgentReplyReconsiderationPrompt({\n action,\n originalWake: input.originalWake,\n relevantSignals: [...observedSignals.values()],\n omittedThroughSignalId,\n spaceId: input.spaceId,\n }),\n observation\n );\n action = reconsidered.action;\n value = reconsidered.value;\n reconsiderationCount += 1;\n if (\n !action ||\n action.type !== \"post_message\" ||\n !input.refreshObservation\n ) {\n break;\n }\n observation = await input.refreshObservation(\n observation.observedThroughSignalId\n );\n }\n\n return {\n action: action\n ? attachAgentReplyObservation({\n action,\n observedThroughSignalId: observation.observedThroughSignalId,\n })\n : undefined,\n reconsiderationCount,\n reconsidered: reconsiderationCount > 0,\n value,\n };\n}\n\nfunction isRelevantCollaborationSignal(signal: SignalEnvelope): boolean {\n if (signal.type === \"signal.system_notice\") {\n return isWakeClosingSystemNoticeType(signal.data.noticeType);\n }\n return (\n (signal.type === \"signal.text\" || signal.type === \"signal.status\") &&\n (signal.type !== \"signal.text\" || signal.data.meta?.transient !== true)\n );\n}\n\nfunction readSignalText(signal: SignalEnvelope): string {\n return signal.type === \"signal.text\" ||\n signal.type === \"signal.status\" ||\n signal.type === \"signal.system_notice\"\n ? signal.data.text\n : \"\";\n}\n\nfunction isSignalInCurrentWakeScope(\n signal: SignalEnvelope,\n currentWakeTargetProfileIds: ReadonlySet<string>,\n wakeSourceSignalId: string\n): boolean {\n if (signal.profile.kind === \"human\") {\n return !isNewHumanWake(signal);\n }\n if (currentWakeTargetProfileIds.size === 0) {\n return true;\n }\n const publication = buildSpaceRoundSignalPublication(signal);\n return Boolean(\n publication?.actorProfileId &&\n currentWakeTargetProfileIds.has(publication.actorProfileId) &&\n publication.replyToSignalId === wakeSourceSignalId\n );\n}\n\nfunction isNewHumanWake(signal: SignalEnvelope): boolean {\n return Boolean(\n signal.type === \"signal.text\" &&\n signal.data.messageEnvelope?.activationTargets.length\n );\n}\n\nfunction readCollaborationActorProfileId(\n signal: SignalEnvelope\n): string | null {\n return signal.profile.kind === \"human\"\n ? signal.profile.profileId\n : (buildSpaceRoundSignalPublication(signal)?.actorProfileId ?? null);\n}\n\nfunction resolveCollaborationOutcome(\n signal: SignalEnvelope\n): \"contribution\" | \"failed\" | \"silent\" | \"stopped\" | \"status\" {\n if (signal.type === \"signal.text\") {\n return \"contribution\";\n }\n if (signal.type === \"signal.status\") {\n return \"status\";\n }\n switch (signal.data.noticeType) {\n case \"stay_silent\":\n return \"silent\";\n case \"wake_stopped\":\n return \"stopped\";\n default:\n return \"failed\";\n }\n}\n\nasync function readThreadSignalsAfterSource(input: {\n baseUrl: string;\n requestContext: OpenMeldRequestContext;\n sourceSignalId: string;\n spaceId: string;\n spacePassword: string | null;\n threadId: string;\n}): Promise<SignalEnvelope[]> {\n const response = await createCliSpaceApi(input.baseUrl).listThreadSignals({\n afterSignalId: input.sourceSignalId,\n limit: OBSERVATION_LIMIT,\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n threadId: input.threadId,\n ...(input.spacePassword ? { spacePassword: input.spacePassword } : {}),\n });\n return response.signals;\n}\n","import type { LocalExecutionSlotTaskResult } from \"@openmeld/local-service\";\nimport type { OpenMeldDaemonTaskResultPayload } from \"@openmeld/schemas/types\";\nimport { DaemonServiceRunError } from \"../core/types\";\nimport type { DispatchResultOutboxSettlement } from \"./dispatch-result-outbox\";\n\nfunction requireDispatchResultOutboxSettlement(input: {\n settlement: Promise<DispatchResultOutboxSettlement> | null;\n}): Promise<DispatchResultOutboxSettlement> {\n if (!input.settlement) {\n throw new DaemonServiceRunError({\n code: \"dispatch.result_settlement.not_registered\",\n message:\n \"OpenMeld could not wait for the Agent reply because result settlement was not registered.\",\n });\n }\n return input.settlement;\n}\n\nfunction shouldAwaitAgentReplySettlement(\n payload: OpenMeldDaemonTaskResultPayload\n): boolean {\n return (\n (payload.status === \"success\" || payload.status === \"partial_success\") &&\n payload.spaceAction?.type === \"post_message\"\n );\n}\n\nexport async function settleAgentReplyProposals(input: {\n initialResultPayload: OpenMeldDaemonTaskResultPayload;\n reconsider: (\n agentReplyObservationCursor: string\n ) => Promise<OpenMeldDaemonTaskResultPayload>;\n submit: (payload: OpenMeldDaemonTaskResultPayload) => {\n resultSummary: LocalExecutionSlotTaskResult;\n settlement: Promise<DispatchResultOutboxSettlement> | null;\n };\n}): Promise<{\n resultPayload: OpenMeldDaemonTaskResultPayload;\n resultSummary: LocalExecutionSlotTaskResult | null;\n}> {\n let resultPayload = input.initialResultPayload;\n while (shouldAwaitAgentReplySettlement(resultPayload)) {\n const proposal = input.submit(resultPayload);\n const settlement = await requireDispatchResultOutboxSettlement(proposal);\n if (settlement.status === \"accepted\") {\n return {\n resultPayload,\n resultSummary: proposal.resultSummary,\n };\n }\n if (settlement.status === \"rejected_terminal\") {\n throw new DaemonServiceRunError({\n code: settlement.reasonCode,\n message: `OpenMeld rejected the Agent reply proposal: ${settlement.reasonCode}`,\n });\n }\n const previousCursor = readObservationCursor(resultPayload);\n resultPayload = await input.reconsider(previousCursor);\n if (\n shouldAwaitAgentReplySettlement(resultPayload) &&\n readObservationCursor(resultPayload) === previousCursor\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_observation.no_progress\",\n message:\n \"OpenMeld requested a reply review, but no newer Space context could be read. Open Diagnostics before waking the Agent again.\",\n });\n }\n }\n return { resultPayload, resultSummary: null };\n}\n\nfunction readObservationCursor(\n payload: OpenMeldDaemonTaskResultPayload\n): string {\n return (\n (payload.spaceAction?.type === \"post_message\"\n ? payload.spaceAction.observedThroughSignalId?.trim()\n : null) || payload.sourceEventId\n );\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { buildSpaceAttachmentDownloadPath } from \"@openmeld/api-client\";\nimport type { SpaceMessageAttachment } from \"@openmeld/schemas/types\";\nimport { resolveRegistryRuntimeAdapterContractByAgentControllerRef } from \"../../agents/registry-source\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldProfileIdentityRequestHeadersWithAuth } from \"../../config/request-headers\";\nimport { fetchSpaceRequestWithTimeout } from \"../../space/fetch-with-timeout\";\n\nconst SAFE_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;\n\nexport type DispatchImageAttachmentFailure = {\n attachment: SpaceMessageAttachment;\n errorCode:\n | \"controller_image_input_unsupported\"\n | \"download_failed\"\n | \"download_size_mismatch\"\n | \"download_type_mismatch\"\n | \"invalid_attachment_id\"\n | \"invalid_task_id\"\n | \"write_failed\";\n errorMessage: string;\n};\n\nexport type DispatchImageAttachmentDownload = (input: {\n attachmentId: string;\n spaceId: string;\n}) => Promise<Response>;\n\nexport type DispatchImageAttachmentPreparation = {\n failures: DispatchImageAttachmentFailure[];\n localPaths: string[];\n promptSection: string | null;\n};\n\nexport async function downloadDispatchImageAttachment(input: {\n attachmentId: string;\n ownerName: string | null;\n ownerUserId: string;\n spaceId: string;\n spacePassword: string | null;\n targetProfileId: string;\n targetProfileName: string | null;\n}): Promise<Response> {\n const baseUrl = await resolveBaseUrl();\n const requestUrl = new URL(\n buildSpaceAttachmentDownloadPath(input.spaceId, input.attachmentId),\n baseUrl\n ).toString();\n const headers = await buildOpenMeldProfileIdentityRequestHeadersWithAuth({\n profileIdentity: {\n openMeldProfileId: input.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.ownerUserId,\n ...(input.ownerName ? { ownerName: input.ownerName } : {}),\n profileName: input.targetProfileName ?? input.targetProfileId,\n },\n requestUrl,\n ...(input.spacePassword ? { spacePassword: input.spacePassword } : {}),\n });\n return await fetchSpaceRequestWithTimeout({\n url: requestUrl,\n operation: \"space.attachment.download\",\n init: { headers },\n });\n}\n\nexport async function materializeDispatchImageAttachments(input: {\n agentControllerRef: string;\n attachments: SpaceMessageAttachment[];\n downloadAttachment: DispatchImageAttachmentDownload;\n providerRuntimeWorkingDirectory: string;\n spaceId: string;\n taskId: string;\n}): Promise<DispatchImageAttachmentPreparation> {\n if (input.attachments.length === 0) {\n return { failures: [], localPaths: [], promptSection: null };\n }\n\n // TODO(models.dev): OpenCode currently declares local-file image input\n // statically. Resolve it per selected model once the catalog exposes a\n // stable vision-capability contract.\n const capability = resolveRegistryRuntimeAdapterContractByAgentControllerRef(\n input.agentControllerRef\n )?.capabilityDeclaration.imageInputCapability;\n if (capability !== \"local_file_path\") {\n return buildPreparationResult({\n failures: input.attachments.map((attachment) => ({\n attachment,\n errorCode: \"controller_image_input_unsupported\",\n errorMessage: `Agent Controller ${input.agentControllerRef} does not accept local image file paths.`,\n })),\n materialized: [],\n });\n }\n\n if (!isSafePathSegment(input.taskId)) {\n return buildPreparationResult({\n failures: input.attachments.map((attachment) => ({\n attachment,\n errorCode: \"invalid_task_id\",\n errorMessage: \"The dispatch task ID is not safe for a local path.\",\n })),\n materialized: [],\n });\n }\n\n const attachmentDirectory = join(\n input.providerRuntimeWorkingDirectory,\n \".openmeld\",\n \"attachments\",\n input.taskId\n );\n const failures: DispatchImageAttachmentFailure[] = [];\n const materialized: Array<{\n attachment: SpaceMessageAttachment;\n localPath: string;\n }> = [];\n\n for (const attachment of input.attachments) {\n if (!isSafePathSegment(attachment.id)) {\n failures.push({\n attachment,\n errorCode: \"invalid_attachment_id\",\n errorMessage: \"The attachment ID is not safe for a local path.\",\n });\n continue;\n }\n\n let response: Response;\n try {\n response = await input.downloadAttachment({\n attachmentId: attachment.id,\n spaceId: input.spaceId,\n });\n } catch (error) {\n failures.push({\n attachment,\n errorCode: \"download_failed\",\n errorMessage: toErrorMessage(error),\n });\n continue;\n }\n\n if (!response.ok) {\n failures.push({\n attachment,\n errorCode: \"download_failed\",\n errorMessage: `Attachment download returned HTTP ${response.status}.`,\n });\n continue;\n }\n const responseMimeType = normalizeMimeType(\n response.headers.get(\"content-type\")\n );\n if (responseMimeType !== attachment.mimeType) {\n failures.push({\n attachment,\n errorCode: \"download_type_mismatch\",\n errorMessage: `Attachment download returned ${responseMimeType ?? \"no content type\"}; expected ${attachment.mimeType}.`,\n });\n continue;\n }\n\n let bytes: Uint8Array;\n try {\n bytes = new Uint8Array(await response.arrayBuffer());\n } catch (error) {\n failures.push({\n attachment,\n errorCode: \"download_failed\",\n errorMessage: toErrorMessage(error),\n });\n continue;\n }\n if (bytes.byteLength !== attachment.sizeBytes) {\n failures.push({\n attachment,\n errorCode: \"download_size_mismatch\",\n errorMessage: `Attachment download returned ${bytes.byteLength} bytes; expected ${attachment.sizeBytes}.`,\n });\n continue;\n }\n\n const localPath = join(\n attachmentDirectory,\n `${attachment.id}${resolveImageExtension(attachment)}`\n );\n try {\n await mkdir(attachmentDirectory, { recursive: true });\n await writeFile(localPath, bytes);\n } catch (error) {\n failures.push({\n attachment,\n errorCode: \"write_failed\",\n errorMessage: toErrorMessage(error),\n });\n continue;\n }\n materialized.push({ attachment, localPath });\n }\n\n return buildPreparationResult({ failures, materialized });\n}\n\nfunction buildPreparationResult(input: {\n failures: DispatchImageAttachmentFailure[];\n materialized: Array<{\n attachment: SpaceMessageAttachment;\n localPath: string;\n }>;\n}): DispatchImageAttachmentPreparation {\n const sections: string[] = [];\n if (input.materialized.length > 0) {\n sections.push(\n [\n \"Attached images (local files):\",\n ...input.materialized.map(\n ({ attachment, localPath }) =>\n `- \\`${localPath}\\` — Space attachment ${formatAttachmentLabel(attachment)} (${attachment.mimeType}).`\n ),\n ].join(\"\\n\")\n );\n }\n if (input.failures.length > 0) {\n sections.push(\n [\n `The user attached ${input.failures.length} image(s) but they could not be retrieved.`,\n ...input.failures.map(\n ({ attachment }) =>\n `- Space attachment ${formatAttachmentLabel(attachment)} (${attachment.id}) was unavailable.`\n ),\n ].join(\"\\n\")\n );\n }\n return {\n failures: input.failures,\n localPaths: input.materialized.map(({ localPath }) => localPath),\n promptSection: sections.length > 0 ? sections.join(\"\\n\\n\") : null,\n };\n}\n\nfunction resolveImageExtension(attachment: SpaceMessageAttachment): string {\n const declaredExtension = extname(attachment.fileName ?? \"\").toLowerCase();\n if (attachment.mimeType === \"image/png\") {\n return declaredExtension === \".png\" ? declaredExtension : \".png\";\n }\n if (declaredExtension === \".jpg\" || declaredExtension === \".jpeg\") {\n return declaredExtension;\n }\n return \".jpg\";\n}\n\nfunction formatAttachmentLabel(attachment: SpaceMessageAttachment): string {\n return attachment.fileName\n ? JSON.stringify(attachment.fileName)\n : attachment.id;\n}\n\nfunction isSafePathSegment(value: string): boolean {\n return SAFE_PATH_SEGMENT_PATTERN.test(value);\n}\n\nfunction normalizeMimeType(value: string | null): string | null {\n const normalized = String(value ?? \"\")\n .split(\";\", 1)[0]\n ?.trim()\n .toLowerCase();\n return normalized ? normalized : null;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { createHash } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { OFFICIAL_CLI_SKILL_URL } from \"@openmeld/schemas\";\nimport { getConfiguredSkillsConfig } from \"../../config/runtime-config\";\nimport {\n canManageRegistryAgentSkillTargets,\n resolveSkillsAgentRegistry,\n} from \"../../skills/agents\";\nimport {\n installSkillsToTargets,\n type SkillsInstallTarget,\n withSkillsInstallLock,\n} from \"../../skills/installer\";\nimport { resolveSkillInstallStateForTarget } from \"../../skills/state\";\nimport { ensureLocalSkills, type LocalSkill } from \"../../skills/store\";\nimport type { DispatchPromptPlan } from \"./parse-dispatch-task\";\n\nexport type DispatchControllerOpenMeldSkillRepairStatus =\n | \"blocked\"\n | \"failed\"\n | \"lane_isolated\"\n | \"not_needed\"\n | \"repaired\"\n | \"unsupported\";\n\nexport type DispatchControllerOpenMeldSkillRepairResult = {\n agentId: string | null;\n status: DispatchControllerOpenMeldSkillRepairStatus;\n reason?: string;\n skillPath?: string;\n};\n\nconst OPENMELD_CLI_SKILL_ID = \"openmeld-cli\";\n\n/**\n * Restores only OpenMeld's own collaboration skill for the Agent Controller\n * carrying the current dispatch. User-owned skill directories are never\n * overwritten, and isolated lanes cannot mutate published agent state unless\n * the target directory was explicitly configured for that lane.\n */\nexport async function ensureDispatchControllerOpenMeldSkill(input: {\n agentControllerRef: string | null | undefined;\n}): Promise<DispatchControllerOpenMeldSkillRepairResult> {\n const agentId = resolveBuiltinAgentId(input.agentControllerRef);\n if (!agentId) {\n return { agentId: null, status: \"unsupported\" };\n }\n\n try {\n const skillsConfig = await getConfiguredSkillsConfig();\n const registry = resolveSkillsAgentRegistry(skillsConfig);\n const agent = registry[agentId];\n if (!agent?.globalSkillsDir || agent.skillsInstallable !== true) {\n return { agentId, status: \"unsupported\" };\n }\n if (\n agent.globalSkillsDirSource === \"registry-default\" &&\n !canManageRegistryAgentSkillTargets()\n ) {\n return { agentId, status: \"lane_isolated\" };\n }\n\n const openMeldSkill = (await ensureLocalSkills()).find(\n (skill) => skill.id === OPENMELD_CLI_SKILL_ID\n );\n if (!openMeldSkill) {\n return {\n agentId,\n status: \"failed\",\n reason: \"the bundled openmeld-cli skill is unavailable\",\n };\n }\n\n const target: SkillsInstallTarget = {\n id: agentId,\n dir: agent.globalSkillsDir,\n type: \"agent\",\n };\n return await repairOpenMeldSkillTarget({\n agentId,\n openMeldSkill,\n target,\n });\n } catch (error) {\n return {\n agentId,\n status: \"failed\",\n reason: error instanceof Error ? error.message : \"skill repair failed\",\n };\n }\n}\n\nasync function repairOpenMeldSkillTarget(input: {\n agentId: string;\n openMeldSkill: LocalSkill;\n target: SkillsInstallTarget;\n}): Promise<DispatchControllerOpenMeldSkillRepairResult> {\n const currentResult = await resolveExistingSkillResult(input);\n if (currentResult) {\n return currentResult;\n }\n\n const [installResult] = await withSkillsInstallLock(() =>\n installSkillsToTargets({\n skills: [input.openMeldSkill],\n targets: [input.target],\n })\n );\n if (installResult?.status === \"installed\") {\n return {\n agentId: input.agentId,\n status: \"repaired\",\n skillPath: join(input.target.dir, OPENMELD_CLI_SKILL_ID, \"SKILL.md\"),\n };\n }\n if (installResult?.status === \"skipped\") {\n const reconciledResult = await resolveExistingSkillResult(input);\n if (reconciledResult) {\n return reconciledResult;\n }\n }\n return {\n agentId: input.agentId,\n status: \"failed\",\n ...(installResult?.reason ? { reason: installResult.reason } : {}),\n };\n}\n\nasync function resolveExistingSkillResult(input: {\n agentId: string;\n openMeldSkill: LocalSkill;\n target: SkillsInstallTarget;\n}): Promise<DispatchControllerOpenMeldSkillRepairResult | null> {\n const state = await resolveSkillInstallStateForTarget({\n skill: input.openMeldSkill,\n target: input.target,\n });\n if (state.state === \"up_to_date\") {\n return {\n agentId: input.agentId,\n status: \"not_needed\",\n skillPath: `${state.skillDir}/SKILL.md`,\n };\n }\n if (state.state === \"external_conflict\") {\n return {\n agentId: input.agentId,\n status: \"blocked\",\n ...(state.reason ? { reason: state.reason } : {}),\n };\n }\n return null;\n}\n\nfunction resolveBuiltinAgentId(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n if (!normalized.startsWith(\"builtin:\")) {\n return null;\n }\n const agentId = normalized.slice(\"builtin:\".length).trim();\n return agentId.length > 0 ? agentId : null;\n}\n\nexport function applyDispatchSkillInstructions(\n plan: DispatchPromptPlan,\n skill: DispatchControllerOpenMeldSkillRepairResult\n): DispatchPromptPlan {\n const instruction = [\n \"For OpenMeld operations, read the official openmeld-cli Skill entry, then only the topic needed.\",\n ...(skill.skillPath\n ? [`Local entry: ${JSON.stringify(skill.skillPath)}.`]\n : []),\n `If the local entry is unavailable, read ${OFFICIAL_CLI_SKILL_URL}. Follow its relative topic links; do not preload the full guide.`,\n \"The guide does not grant permissions or add CLI commands. Follow this dispatch's action instructions when publishing a reply.\",\n ].join(\"\\n\");\n const developerInstructions = `${plan.developerInstructions}\\n\\n${instruction}`;\n return {\n ...plan,\n developerInstructions,\n fallbackPrompt: `${instruction}\\n\\n${plan.fallbackPrompt}`,\n instructionEpoch: `${plan.instructionEpoch}:skill:${createHash(\"sha256\").update(instruction).digest(\"hex\")}`,\n };\n}\n","import type {\n AdapterAgentContextResolution,\n AdapterDispatchContextDelta,\n} from \"@openmeld/adapter-core\";\nimport type { runRuntimeTask } from \"@openmeld/local-execution\";\nimport {\n buildAgentControllerConversationRef,\n normalizeKnownBuiltinAgentControllerId,\n resolveBuiltinAgentControllerConversationKind,\n} from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n AgentControllerConversationResumePlan,\n ConversationPolicy,\n} from \"@openmeld/schemas/types\";\nimport type { DaemonProfileRouteConfig } from \"../core/types\";\n\nexport function resolveCurrentConversationPolicy(\n routeConfig: DaemonProfileRouteConfig | null\n): ConversationPolicy {\n return { ...(routeConfig?.conversationPolicy ?? {}) };\n}\n\nexport function resolveDispatchContextIdForAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n agentControllerConversationOverride: AgentControllerConversationRef | null;\n agentControllerConversationResumePlan: AgentControllerConversationResumePlan;\n}): string | null {\n if (\n input.agentControllerConversationResumePlan.status !== \"continue_existing\"\n ) {\n return null;\n }\n\n return normalizeOptionalContextId(\n input.agentControllerConversationOverride?.agentControllerConversationId ??\n input.agentControllerConversationId ??\n null\n );\n}\n\nexport function resolvePlannedAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n agentControllerRef: string;\n}): AgentControllerConversationRef | null {\n return buildAgentControllerConversationRefFromAgentControllerConversation(\n input\n );\n}\n\nexport function resolveObservedDispatchAgentControllerConversation(input: {\n contextDelta: AdapterDispatchContextDelta | null;\n contextResolution: AdapterAgentContextResolution | null;\n plannedAgentControllerConversation: AgentControllerConversationRef | null;\n agentControllerConversationOverride: AgentControllerConversationRef | null;\n}): AgentControllerConversationRef | null {\n return (\n input.contextDelta?.agentControllerConversation ??\n input.contextResolution?.agentControllerConversation ??\n input.agentControllerConversationOverride ??\n input.plannedAgentControllerConversation ??\n null\n );\n}\n\nexport function buildAgentControllerConversationRefFromAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n agentControllerRef: string;\n}): AgentControllerConversationRef | null {\n const conversationId = normalizeOptionalContextId(\n input.agentControllerConversationId\n );\n const agentControllerRef = normalizeOptionalContextId(\n input.agentControllerRef\n );\n if (!(conversationId && agentControllerRef)) {\n return null;\n }\n const builtinProviderId =\n normalizeKnownBuiltinAgentControllerId(agentControllerRef);\n if (builtinProviderId) {\n return buildAgentControllerConversationRef({\n agentControllerRef,\n agentControllerConversationKind:\n resolveBuiltinAgentControllerConversationKind(agentControllerRef) ??\n \"context\",\n agentControllerConversationId: conversationId,\n });\n }\n return buildAgentControllerConversationRef({\n agentControllerRef,\n agentControllerConversationKind: \"context\",\n agentControllerConversationId: conversationId,\n });\n}\n\nexport function areSameAgentControllerConversationRef(\n left: AgentControllerConversationRef,\n right: AgentControllerConversationRef | null\n): boolean {\n if (!right) {\n return false;\n }\n return (\n left.agentControllerRef === right.agentControllerRef &&\n left.agentControllerConversationKind ===\n right.agentControllerConversationKind &&\n left.agentControllerConversationId === right.agentControllerConversationId\n );\n}\n\nexport function normalizeOptionalContextId(\n contextId: string | null | undefined\n): string | null {\n if (typeof contextId !== \"string\") {\n return null;\n }\n const normalized = contextId.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function resolveDispatchContextDeltaFromRuntimeResult(\n dispatchResult: Awaited<ReturnType<typeof runRuntimeTask>>[\"dispatchResult\"]\n): AdapterDispatchContextDelta | null {\n if (!dispatchResult.dispatched) {\n return null;\n }\n if (dispatchResult.adapterResult.status !== \"success\") {\n return null;\n }\n return dispatchResult.adapterResult.contextDelta ?? null;\n}\n","import {\n buildRuntimeWorkspaceFingerprint,\n removeConversationExecutionState,\n upsertConversationExecutionState,\n} from \"@openmeld/local-execution\";\nimport type { DispatchContinuityObservation } from \"@openmeld/local-service\";\nimport type {\n AgentControllerConversationRef,\n BootstrapTemplateFacts,\n ConversationExecutionState,\n LocalRuntimeContextPlan,\n} from \"@openmeld/schemas/types\";\nimport { normalizeOptionalContextId } from \"./execute-dispatch-conversation\";\nimport type { BootstrapPlan } from \"./execute-dispatch-types\";\n\nconst BOOTSTRAP_IDLE_STALE_MS = 24 * 60 * 60 * 1000;\nconst BOOTSTRAP_DISPATCH_STALE_THRESHOLD = 8;\n\nconst isBootstrapExecutionStateMissing = (\n executionState: ConversationExecutionState\n): boolean =>\n !(\n executionState.bootstrapLastAppliedAt &&\n executionState.lastAppliedTemplateVersion &&\n executionState.lastAppliedContentFingerprint\n );\n\nconst isBootstrapIdleStale = (\n lastActivatedAt: string | undefined,\n nowMs: number\n): boolean => {\n if (!lastActivatedAt) {\n return false;\n }\n const lastActivatedMs = Date.parse(lastActivatedAt);\n if (!Number.isFinite(lastActivatedMs)) {\n return false;\n }\n return nowMs - lastActivatedMs >= BOOTSTRAP_IDLE_STALE_MS;\n};\n\nexport function resolveBootstrapPlan(input: {\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n executionState: ConversationExecutionState | null;\n localRuntimeContextPlan: LocalRuntimeContextPlan;\n nowMs: number;\n}): BootstrapPlan {\n if (input.localRuntimeContextPlan.status === \"recreate\") {\n return {\n reason: \"compatibility_recreate\",\n shouldInject: true,\n };\n }\n if (!input.executionState) {\n return {\n reason: \"missing_bootstrap_state\",\n shouldInject: true,\n };\n }\n if (input.executionState.pendingBootstrapReason === \"context_healed\") {\n return {\n reason: \"context_healed\",\n shouldInject: true,\n };\n }\n if (isBootstrapExecutionStateMissing(input.executionState)) {\n return {\n reason: \"missing_bootstrap_state\",\n shouldInject: true,\n };\n }\n if (\n input.executionState.lastAppliedTemplateVersion !==\n input.bootstrapTemplateFacts.templateVersion ||\n input.executionState.lastAppliedContentFingerprint !==\n input.bootstrapTemplateFacts.contentFingerprint\n ) {\n return {\n reason: \"template_changed\",\n shouldInject: true,\n };\n }\n if (\n isBootstrapIdleStale(\n input.executionState.bootstrapLastActivatedAt,\n input.nowMs\n )\n ) {\n return {\n reason: \"idle_stale\",\n shouldInject: true,\n };\n }\n if (\n input.executionState.dispatchesSinceBootstrapApplied >=\n BOOTSTRAP_DISPATCH_STALE_THRESHOLD\n ) {\n return {\n reason: \"dispatch_count_stale\",\n shouldInject: true,\n };\n }\n return {\n reason: null,\n shouldInject: false,\n };\n}\n\nexport function markBootstrapInjectedContext(input: {\n executionState: ConversationExecutionState | null;\n agentContextLookupKey: string;\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n existingContextId: string | null;\n effectiveRuntimeWorkingDirectory: string;\n nowIso: string;\n}): ConversationExecutionState {\n const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n input.effectiveRuntimeWorkingDirectory\n );\n return {\n agentContextLookupKey: input.agentContextLookupKey,\n activeContextId: normalizeOptionalContextId(input.existingContextId),\n dispatchesSinceBootstrapApplied: 0,\n bootstrapLastAppliedAt: input.nowIso,\n bootstrapLastActivatedAt: input.nowIso,\n lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,\n lastAppliedContentFingerprint:\n input.bootstrapTemplateFacts.contentFingerprint,\n lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,\n runtimeWorkspaceFingerprint,\n pendingBootstrapReason: undefined,\n updatedAt: input.nowIso,\n ...(input.executionState?.lastResolvedAgentControllerConversation\n ? {\n lastResolvedAgentControllerConversation: {\n ...input.executionState.lastResolvedAgentControllerConversation,\n },\n }\n : {}),\n };\n}\n\nexport function reconcileBootstrapInjectedContextAfterDispatch(input: {\n executionState: ConversationExecutionState | null;\n shouldInjectBootstrap: boolean;\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n continuityObservation: DispatchContinuityObservation | null;\n contextHealed: boolean;\n dispatchedContextId: string | null;\n effectiveRuntimeWorkingDirectory: string;\n nowIso: string;\n resolvedAgentControllerConversation: AgentControllerConversationRef | null;\n}): ConversationExecutionState | null {\n if (!input.executionState) {\n return null;\n }\n\n const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n input.effectiveRuntimeWorkingDirectory\n );\n const nextExecutionState: ConversationExecutionState = {\n ...input.executionState,\n bootstrapLastActivatedAt: input.nowIso,\n lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,\n runtimeWorkspaceFingerprint,\n updatedAt: input.nowIso,\n ...(input.resolvedAgentControllerConversation\n ? {\n lastResolvedAgentControllerConversation: {\n ...input.resolvedAgentControllerConversation,\n },\n }\n : {}),\n };\n\n if (input.shouldInjectBootstrap) {\n const dispatchedContextId = normalizeOptionalContextId(\n input.dispatchedContextId\n );\n return {\n ...nextExecutionState,\n activeContextId:\n dispatchedContextId ?? nextExecutionState.activeContextId,\n dispatchesSinceBootstrapApplied: 0,\n bootstrapLastAppliedAt:\n nextExecutionState.bootstrapLastAppliedAt ?? input.nowIso,\n bootstrapLastActivatedAt: input.nowIso,\n lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,\n lastAppliedContentFingerprint:\n input.bootstrapTemplateFacts.contentFingerprint,\n pendingBootstrapReason: undefined,\n };\n }\n\n if (input.contextHealed) {\n return {\n ...nextExecutionState,\n activeContextId:\n normalizeOptionalContextId(input.dispatchedContextId) ??\n nextExecutionState.activeContextId,\n dispatchesSinceBootstrapApplied: 0,\n bootstrapLastAppliedAt: undefined,\n lastAppliedTemplateVersion: undefined,\n lastAppliedContentFingerprint: undefined,\n pendingBootstrapReason: \"context_healed\",\n };\n }\n\n if (input.continuityObservation?.status === \"implicit_rotation\") {\n return {\n ...nextExecutionState,\n activeContextId:\n normalizeOptionalContextId(input.dispatchedContextId) ??\n nextExecutionState.activeContextId,\n dispatchesSinceBootstrapApplied:\n nextExecutionState.dispatchesSinceBootstrapApplied + 1,\n pendingBootstrapReason: undefined,\n };\n }\n\n return {\n ...nextExecutionState,\n dispatchesSinceBootstrapApplied:\n nextExecutionState.dispatchesSinceBootstrapApplied + 1,\n pendingBootstrapReason: undefined,\n };\n}\n\nexport function rollbackBootstrapExecutionStateAfterDispatchFailure(input: {\n agentContextLookupKey: string;\n executionStateBeforeDispatch: ConversationExecutionState | null;\n state: Parameters<typeof upsertConversationExecutionState>[0][\"state\"];\n}) {\n const stateWithoutCurrentLookupKey = removeConversationExecutionState({\n agentContextLookupKey: input.agentContextLookupKey,\n state: input.state,\n });\n if (input.executionStateBeforeDispatch) {\n return upsertConversationExecutionState({\n state: stateWithoutCurrentLookupKey,\n executionState: input.executionStateBeforeDispatch,\n });\n }\n return stateWithoutCurrentLookupKey;\n}\n","import {\n removeConversationExecutionState,\n upsertConversationExecutionState,\n} from \"@openmeld/local-execution\";\nimport type { ConversationExecutionState } from \"@openmeld/schemas/types\";\n\nexport function upsertConversationExecutionStateForLookupKey(input: {\n executionState: ConversationExecutionState;\n replacedLookupKey?: string | null;\n state: Parameters<typeof upsertConversationExecutionState>[0][\"state\"];\n targetLookupKey: string;\n}) {\n let nextState = input.state;\n const staleLookupKeys = new Set<string>();\n if (input.executionState.agentContextLookupKey !== input.targetLookupKey) {\n staleLookupKeys.add(input.executionState.agentContextLookupKey);\n }\n if (\n input.replacedLookupKey &&\n input.replacedLookupKey !== input.targetLookupKey\n ) {\n staleLookupKeys.add(input.replacedLookupKey);\n }\n for (const agentContextLookupKey of staleLookupKeys) {\n nextState = removeConversationExecutionState({\n agentContextLookupKey,\n state: nextState,\n });\n }\n return upsertConversationExecutionState({\n state: nextState,\n executionState: {\n ...input.executionState,\n agentContextLookupKey: input.targetLookupKey,\n },\n });\n}\n","import type {\n AdapterDispatchDiagnostics,\n AdapterDispatchTelemetry,\n AdapterRuntimeEvent,\n} from \"@openmeld/adapter-core\";\nimport type {\n RuntimeTaskResult,\n runRuntimeTask,\n} from \"@openmeld/local-execution\";\nimport type {\n DispatchContinuityObservation,\n LocalExecutionSlotTaskResult,\n} from \"@openmeld/local-service\";\nimport type {\n OpenMeldDaemonTaskResultPayload,\n RuntimeTransportDeliverDispatchRequest,\n} from \"@openmeld/schemas/types\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine } from \"../core/logger\";\nimport { emitDaemonDispatchJournalEvent } from \"./daemon-dispatch-journal\";\nimport type {\n DispatchLocalJournalPhase,\n ParsedDispatchTask,\n} from \"./execute-dispatch-types\";\nimport { buildDispatchCorrelation } from \"./parse-dispatch-task\";\n\nexport function resolveAdapterTelemetry(\n dispatchResult: Awaited<ReturnType<typeof runRuntimeTask>>[\"dispatchResult\"]\n): AdapterDispatchTelemetry | null {\n if (!dispatchResult.dispatched) {\n return null;\n }\n return dispatchResult.adapterResult.telemetry ?? null;\n}\n\nexport function resolveAdapterDiagnostics(\n dispatchResult: Awaited<ReturnType<typeof runRuntimeTask>>[\"dispatchResult\"]\n): AdapterDispatchDiagnostics | null {\n if (!dispatchResult.dispatched) {\n return null;\n }\n return dispatchResult.adapterResult.diagnostics ?? null;\n}\n\nexport function buildRuntimeObservationPayload(input: {\n continuityObservation: DispatchContinuityObservation | null;\n daemonWorkingDirectory: string;\n deliveryRecoveryReason: ParsedDispatchTask[\"deliveryRecoveryReason\"];\n dispatchId: string;\n providerRuntimeWorkingDirectory: string;\n resultPayload: OpenMeldDaemonTaskResultPayload;\n runtimeResult: Pick<\n Awaited<ReturnType<typeof runRuntimeTask>>,\n \"dispatchResult\" | \"resultPayload\"\n >;\n runtimeStartedAtMs: number;\n taskId: string;\n}): Record<string, unknown> {\n const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);\n const diagnostics = resolveAdapterDiagnostics(\n input.runtimeResult.dispatchResult\n );\n const runtimeCompletedAtMs = Date.now();\n const runtimeTelemetryPayload =\n telemetry === null ? {} : buildAdapterRuntimeObservationPayload(telemetry);\n\n return {\n attemptId: input.runtimeResult.resultPayload.attemptId,\n daemonWorkingDirectory: input.daemonWorkingDirectory,\n dispatchId: input.dispatchId,\n ...(\"errorCode\" in input.resultPayload && input.resultPayload.errorCode\n ? { errorCode: input.resultPayload.errorCode }\n : {}),\n ...(diagnostics?.modelNegotiation\n ? { modelNegotiation: diagnostics.modelNegotiation }\n : {}),\n providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,\n result: input.resultPayload.status,\n runtimeDurationMs: runtimeCompletedAtMs - input.runtimeStartedAtMs,\n taskId: input.taskId,\n ...(input.deliveryRecoveryReason\n ? { deliveryRecoveryReason: input.deliveryRecoveryReason }\n : {}),\n ...runtimeTelemetryPayload,\n };\n}\n\nfunction buildAdapterRuntimeObservationPayload(\n telemetry: AdapterDispatchTelemetry\n): Record<string, number | string | boolean | null> {\n const timeToMetric = (tsMs: number | null | undefined): number | null => {\n return tsMs === undefined || tsMs === null\n ? null\n : tsMs - telemetry.invokedAtMs;\n };\n const adapterDurationMs = timeToMetric(telemetry.completedAtMs);\n const timeToFirstOutputMs = timeToMetric(telemetry.firstOutputAtMs);\n const timeToFirstStderrMs = timeToMetric(telemetry.firstStderrAtMs);\n const timeToFirstStdoutMs = timeToMetric(telemetry.firstStdoutAtMs);\n const timeToProcessSpawnMs = timeToMetric(telemetry.processSpawnedAtMs);\n const timeToStdinClosedMs = timeToMetric(telemetry.stdinClosedAtMs);\n\n return {\n ...(adapterDurationMs === null ? {} : { adapterDurationMs }),\n ...(telemetry.contextHealed === undefined\n ? {}\n : { contextHealed: telemetry.contextHealed }),\n ...(telemetry.contextCompactionObserved === undefined\n ? {}\n : {\n contextCompactionObserved: telemetry.contextCompactionObserved,\n }),\n ...(telemetry.tokenUsage\n ? {\n lastCachedInputTokens: telemetry.tokenUsage.last.cachedInputTokens,\n lastInputTokens: telemetry.tokenUsage.last.inputTokens,\n lastOutputTokens: telemetry.tokenUsage.last.outputTokens,\n lastReasoningOutputTokens:\n telemetry.tokenUsage.last.reasoningOutputTokens,\n lastTotalTokens: telemetry.tokenUsage.last.totalTokens,\n modelContextWindowTokens: telemetry.tokenUsage.modelContextWindow,\n totalCachedInputTokens: telemetry.tokenUsage.total.cachedInputTokens,\n totalInputTokens: telemetry.tokenUsage.total.inputTokens,\n totalOutputTokens: telemetry.tokenUsage.total.outputTokens,\n totalReasoningOutputTokens:\n telemetry.tokenUsage.total.reasoningOutputTokens,\n totalTokens: telemetry.tokenUsage.total.totalTokens,\n }\n : {}),\n resumedContext: telemetry.resumedContext,\n ...(timeToFirstOutputMs === null ? {} : { timeToFirstOutputMs }),\n ...(timeToFirstStderrMs === null ? {} : { timeToFirstStderrMs }),\n ...(timeToFirstStdoutMs === null ? {} : { timeToFirstStdoutMs }),\n ...(timeToProcessSpawnMs === null ? {} : { timeToProcessSpawnMs }),\n ...(telemetry.processId === undefined\n ? {}\n : { providerProcessId: telemetry.processId }),\n ...(timeToStdinClosedMs === null ? {} : { timeToStdinClosedMs }),\n ...(telemetry.timeoutTriggeredAtMs === undefined\n ? {}\n : { providerTimedOut: true }),\n ...(telemetry.exitCode === undefined\n ? {}\n : { providerExitCode: telemetry.exitCode }),\n ...(telemetry.exitSignal === undefined\n ? {}\n : { providerExitSignal: telemetry.exitSignal }),\n };\n}\n\nexport function emitProviderRuntimePhaseLine(input: {\n agentControllerRef: string;\n dispatchId: string;\n event: AdapterRuntimeEvent;\n presenter: Presenter;\n runtimeStartedAtMs: number;\n targetProfileId: string;\n taskId: string;\n}): void {\n const sinceRuntimeStartedMs = input.event.tsMs - input.runtimeStartedAtMs;\n const basePayload = {\n agentControllerRef: input.agentControllerRef,\n dispatchId: input.dispatchId,\n phase: input.event.phase,\n ...(input.event.phase === \"process_spawned\" && input.event.processLaunchKind\n ? { processLaunchKind: input.event.processLaunchKind }\n : {}),\n processId: \"processId\" in input.event ? input.event.processId : null,\n ...(input.event.phase === \"process_spawned\" &&\n input.event.processWorkingDirectoryKind\n ? {\n processWorkingDirectoryKind: input.event.processWorkingDirectoryKind,\n }\n : {}),\n sinceRuntimeStartedMs,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n };\n\n switch (input.event.phase) {\n case \"process_spawned\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_process_spawned\",\n text: `provider process spawned for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"stdin_closed\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_input_written\",\n text: `provider input written for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"first_stdout\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_first_stdout\",\n text: `provider first stdout observed for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"first_stderr\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_first_stderr\",\n text: `provider first stderr observed for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"timeout_triggered\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_timeout_triggered\",\n text: `provider timeout triggered for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"process_exit\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_process_exit\",\n text: `provider process exited for task ${input.taskId}`,\n payload: {\n ...basePayload,\n exitCode: input.event.exitCode,\n exitSignal: input.event.signal,\n },\n });\n return;\n case \"provider_conversation_observed\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_conversation_observed\",\n text: `provider conversation observed for task ${input.taskId}`,\n payload: {\n ...basePayload,\n agentControllerConversationId:\n input.event.agentControllerConversationId,\n },\n });\n return;\n case \"provider_turn_accepted\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_turn_accepted\",\n text: `provider turn accepted for task ${input.taskId}`,\n payload: {\n ...basePayload,\n agentControllerConversationId:\n input.event.agentControllerConversationId,\n turnId: input.event.turnId,\n },\n });\n return;\n case \"provider_usage_limits_observed\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_usage_limits_observed\",\n text: `provider usage limits observed for task ${input.taskId}`,\n payload: {\n ...basePayload,\n observedLimitKeys: input.event.usageLimits.map((limit) => limit.key),\n },\n });\n return;\n default:\n return;\n }\n}\n\nexport function emitContinuityWarningIfNeeded(input: {\n continuityObservation: DispatchContinuityObservation | null;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n}): void {\n if (!input.continuityObservation?.shouldWarn) {\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.continuity_warning\",\n text: `implicit conversation rotation detected for task ${input.parsedTask.taskId}; OpenMeld adopted the new context id`,\n payload: {\n agentControllerRef: input.parsedTask.agentControllerRef,\n dispatchId: input.parsedTask.dispatchId,\n existingContextId: input.continuityObservation.existingContextId,\n resolvedContextId: input.continuityObservation.resolvedContextId,\n status: input.continuityObservation.status,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n}\n\nexport function emitRuntimeObservationSummaryLine(input: {\n agentControllerRef: string;\n dispatchId: string;\n presenter: Presenter;\n runtimeResult: RuntimeTaskResult;\n targetProfileId: string;\n taskId: string;\n}): void {\n const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_result_observed\",\n text: `runtime result observed for task ${input.taskId}`,\n payload: {\n agentControllerRef: input.agentControllerRef,\n dispatchId: input.dispatchId,\n hasTelemetry: telemetry !== null,\n ...(telemetry === null\n ? {}\n : {\n hasExitCode: telemetry.exitCode !== undefined,\n hasFirstOutputAtMs: telemetry.firstOutputAtMs !== undefined,\n hasFirstStderrAtMs: telemetry.firstStderrAtMs !== undefined,\n hasFirstStdoutAtMs: telemetry.firstStdoutAtMs !== undefined,\n hasInvokedAtMs: telemetry.invokedAtMs !== undefined,\n hasProcessId: telemetry.processId !== undefined,\n hasProcessSpawnedAtMs: telemetry.processSpawnedAtMs !== undefined,\n hasStdinClosedAtMs: telemetry.stdinClosedAtMs !== undefined,\n hasStreamingMode: telemetry.streamingMode !== undefined,\n resumedContext: telemetry.resumedContext,\n }),\n resultStatus: input.runtimeResult.resultPayload.status,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n },\n });\n}\n\nexport function summarizeTaskResultPayload(\n payload: OpenMeldDaemonTaskResultPayload\n): LocalExecutionSlotTaskResult {\n if (payload.status === \"failed\") {\n return {\n errorCode: payload.errorCode ?? null,\n errorMessage: payload.errorMessage ?? null,\n result: \"failed\",\n };\n }\n if (payload.status === \"partial_success\") {\n return {\n errorCode: payload.errorCode ?? null,\n errorMessage: payload.errorMessage ?? null,\n result: \"partial_success\",\n };\n }\n return {\n errorCode: null,\n errorMessage: null,\n result: \"success\",\n };\n}\n\nexport function emitDispatchLocalPhaseJournalEvent(input: {\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n metadata?: Record<string, unknown>;\n parsedTask: ParsedDispatchTask | null;\n phase: DispatchLocalJournalPhase;\n result: string;\n}): void {\n const correlation = buildDispatchCorrelation({\n deliverRequest: input.deliverRequest,\n parsedTask: input.parsedTask,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: correlation.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n daemonSessionId: input.deliverRequest.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n metadata: {\n phase: input.phase,\n ...(input.metadata ?? {}),\n },\n profileId: correlation.targetProfileId,\n result: input.result,\n taskId: correlation.taskId,\n type: \"dispatch.local.phase\",\n });\n}\n\nexport function buildResultDispatchJournalMetadata(\n payload: OpenMeldDaemonTaskResultPayload\n): Record<string, unknown> {\n const spaceAction = payload.spaceAction ?? null;\n const outputLength = \"output\" in payload ? payload.output.length : null;\n const errorCode = \"errorCode\" in payload ? (payload.errorCode ?? null) : null;\n const errorType = \"errorType\" in payload ? (payload.errorType ?? null) : null;\n const errorMessage =\n \"errorMessage\" in payload ? (payload.errorMessage ?? null) : null;\n\n return {\n agentId: payload.agentId,\n agentControllerRef: payload.agentControllerRef ?? null,\n errorCode,\n errorMessage,\n errorType,\n outputLength,\n sourceEventId: payload.sourceEventId,\n spaceActionProvenance: payload.spaceActionProvenance ?? null,\n spaceActionType: spaceAction?.type ?? null,\n suppressPublicOutcome: payload.suppressPublicOutcome ?? false,\n ...(spaceAction?.type === \"post_message\"\n ? {\n postMessageTextLength: spaceAction.messageEnvelope.text.length,\n }\n : {}),\n ...(spaceAction?.type === \"post_status\"\n ? {\n postStatus: spaceAction.status,\n postStatusTextLength: spaceAction.text.length,\n }\n : {}),\n ...(spaceAction?.type === \"stay_silent\"\n ? {\n staySilentReasonLength: spaceAction.reason.length,\n }\n : {}),\n };\n}\n","import type { RuntimeTaskResult } from \"@openmeld/local-execution\";\nimport {\n SPACE_ACTION_CONTEXT_GUIDANCE_LINES,\n SPACE_ACTION_TARGET_GUIDANCE_LINES,\n} from \"@openmeld/local-service\";\nimport { openMeldDaemonTaskResultPayloadSchema } from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n OpenMeldDaemonTaskResultPayload,\n} from \"@openmeld/schemas/types\";\nimport {\n resolvePublicAgentFailureReason,\n resolveSpacePublicationRequirement,\n} from \"@openmeld/space-mesh\";\nimport { DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND } from \"../../runtime/dispatch-runtime-env\";\nimport { normalizeOptionalText } from \"../core/logger\";\nimport {\n normalizeOptionalContextId,\n resolveDispatchContextDeltaFromRuntimeResult,\n} from \"./execute-dispatch-conversation\";\nimport type {\n ParsedDispatchTask,\n StructuredActionFailureDiagnostics,\n} from \"./execute-dispatch-types\";\n\nexport function resolveStructuredActionRequirementFailure(input: {\n requiresStructuredSpaceAction: boolean;\n resolution: {\n action: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n parseError: string | null;\n };\n runtimeResult: RuntimeTaskResult;\n}):\n | {\n failureReason: string;\n kind: \"preserve_runtime_failure\";\n }\n | {\n failureReason: string;\n kind: \"repair\";\n }\n | null {\n if (input.resolution.parseError) {\n return {\n failureReason: input.resolution.parseError,\n kind: \"repair\",\n };\n }\n if (!(input.requiresStructuredSpaceAction && !input.resolution.action)) {\n return null;\n }\n\n const payload = input.runtimeResult.resultPayload;\n if (payload.status === \"failed\") {\n return {\n failureReason:\n resolvePublicAgentFailureReason({\n defaultReason: \"The agent could not complete this reply right now.\",\n errorCode: payload.errorCode,\n errorMessage: payload.errorMessage,\n }) ?? \"The agent could not complete this reply right now.\",\n kind: \"preserve_runtime_failure\",\n };\n }\n\n return {\n failureReason:\n \"A valid OpenMeld Space action is required in collaboration mode.\",\n kind: \"repair\",\n };\n}\n\nexport function resolveStructuredActionOutputFallback(input: {\n action: NonNullable<OpenMeldDaemonTaskResultPayload[\"spaceAction\"]>;\n cleanedOutput: string;\n}): string {\n const cleanedOutput = input.cleanedOutput.trim();\n if (cleanedOutput.length > 0) {\n return cleanedOutput;\n }\n\n switch (input.action.type) {\n case \"post_message\":\n return input.action.messageEnvelope.text;\n case \"post_status\":\n return input.action.text.trim() || `status:${input.action.status}`;\n case \"stay_silent\":\n return input.action.reason.trim() || \"stay_silent\";\n default:\n return \"structured-action\";\n }\n}\n\nexport function buildStructuredActionRepairPrompt(input: {\n cliEntry?: string | null;\n currentReplyToSignalId?: string | null;\n parseError: string;\n sendTargetReferenceLines?: readonly string[] | null;\n spaceContractSnapshot?: ParsedDispatchTask[\"spaceContractSnapshot\"];\n spaceId?: string | null;\n previousOutput?: string | null;\n}): string {\n const previousOutput = buildBoundedRepairOutputPreview(input.previousOutput);\n const publicationRequirement = resolveSpacePublicationRequirement(\n input.spaceContractSnapshot\n );\n return [\n `OpenMeld delivery repair: ${input.parseError}`,\n ...(previousOutput\n ? [\"Your previous final answer was:\", \"```text\", previousOutput, \"```\"]\n : []),\n \"Do not redo the user's work or change the intended public outcome.\",\n \"Never publish a shell, CLI, MCP, or transport failure message as the user's normal Space reply.\",\n \"If the previous turn tried an action and that transport failed, retry the same intended action and message through the dispatch-scoped tool.\",\n ...SPACE_ACTION_CONTEXT_GUIDANCE_LINES,\n \"Your answer text never selects an OpenMeld Space action.\",\n \"Call exactly one dispatch-scoped OpenMeld Space Action tool now.\",\n publicationRequirement.repairRequirementLine,\n ...SPACE_ACTION_TARGET_GUIDANCE_LINES,\n ...(normalizeOptionalText(input.currentReplyToSignalId)\n ? [\n `post_message.messageEnvelope.replyToSignalId must match the current dispatch reply target: ${normalizeOptionalText(input.currentReplyToSignalId)}.`,\n ]\n : []),\n ...publicationRequirement.actionGuidanceLines,\n ...buildStructuredActionRepairSendTargetReferenceLines(\n input.sendTargetReferenceLines\n ),\n \"Use the official `openmeld-cli` skill for future OpenMeld work.\",\n ...buildStructuredActionRepairCompletionLines({\n publicationRequirement,\n }),\n ].join(\"\\n\");\n}\n\nfunction buildStructuredActionRepairCompletionLines(input: {\n publicationRequirement: ReturnType<typeof resolveSpacePublicationRequirement>;\n}): string[] {\n return [\n buildStructuredActionRepairPrimaryCommandLine(input),\n \"If neither the tool nor the fallback command can record the action, stop. Do not print JSON or prose as a substitute.\",\n \"Do not finish with an explanation of what you will do.\",\n ];\n}\n\nconst REPAIR_OUTPUT_PREVIEW_MAX_CHARS = 1200;\n\nfunction buildBoundedRepairOutputPreview(value: unknown): string | null {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n return null;\n }\n if (normalized.length <= REPAIR_OUTPUT_PREVIEW_MAX_CHARS) {\n return normalized;\n }\n return `${normalized.slice(0, REPAIR_OUTPUT_PREVIEW_MAX_CHARS).trimEnd()}\\n[truncated; reuse the complete answer already in this conversation]`;\n}\n\nfunction buildStructuredActionRepairPrimaryCommandLine(input: {\n publicationRequirement: ReturnType<typeof resolveSpacePublicationRequirement>;\n}): string {\n if (input.publicationRequirement.allowedActions.includes(\"post_message\")) {\n return `For a normal reply, call the dispatch-scoped OpenMeld Space Action \\`reply\\` tool with the corrected public message. If that tool is unavailable, run the fallback CLI command \\`${DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND} space action reply \"corrected public message\"\\` and wait for it to finish.`;\n }\n if (input.publicationRequirement.allowedActions.includes(\"post_status\")) {\n return `For a final status, call the dispatch-scoped OpenMeld Space Action \\`status\\` tool with a final-safe status and short update. If that tool is unavailable, run the fallback CLI command \\`${DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND} space action status done \"short completion update\"\\` and wait for it to finish.`;\n }\n if (input.publicationRequirement.allowedActions.includes(\"stay_silent\")) {\n return `If no public reply is needed, call the dispatch-scoped OpenMeld Space Action \\`stay_silent\\` tool with your reason. If that tool is unavailable, run the fallback CLI command \\`${DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND} space action silent --reason \"reason\"\\` and wait for it to finish.`;\n }\n return \"No permitted OpenMeld Space action is available. Do not invent one in answer text.\";\n}\n\nfunction buildStructuredActionRepairSendTargetReferenceLines(\n sendTargetReferenceLines: readonly string[] | null | undefined\n): string[] {\n if (!(sendTargetReferenceLines && sendTargetReferenceLines.length > 0)) {\n return [];\n }\n\n return [\n \"Current send target reference:\",\n ...sendTargetReferenceLines.map((line) => line),\n ];\n}\n\nexport function resolveStructuredActionRepairPreviousOutput(\n runtimeResult: RuntimeTaskResult\n): string | null {\n const payload = runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return null;\n }\n return normalizeOptionalText(payload.output);\n}\n\nexport function resolveStructuredActionRepairContinuation(input: {\n runtimeResult: RuntimeTaskResult;\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): {\n contextId: string | null;\n agentControllerConversationOverride: AgentControllerConversationRef | null;\n} {\n const contextDelta = resolveDispatchContextDeltaFromRuntimeResult(\n input.runtimeResult.dispatchResult\n );\n return {\n contextId:\n normalizeOptionalContextId(\n input.runtimeResult.contextResolution?.agentControllerConversationId ??\n contextDelta?.agentControllerConversationId ??\n null\n ) ?? null,\n agentControllerConversationOverride:\n input.runtimeResult.contextResolution?.agentControllerConversation ??\n contextDelta?.agentControllerConversation ??\n input.agentControllerConversationOverride ??\n null,\n };\n}\n\nexport function buildInvalidStructuredActionOutputPreview(\n runtimeResult: RuntimeTaskResult\n): string | null {\n const payload = runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return null;\n }\n const normalizedOutput = normalizeOptionalText(payload.output);\n if (!normalizedOutput) {\n return null;\n }\n if (normalizedOutput.length <= 180) {\n return normalizedOutput;\n }\n return `${normalizedOutput.slice(0, 177).trimEnd()}...`;\n}\n\nexport function coerceRuntimeResultToStructuredActionFailure(input: {\n diagnostics?: StructuredActionFailureDiagnostics | null;\n failureReason: string;\n runtimeResult: RuntimeTaskResult;\n}): OpenMeldDaemonTaskResultPayload {\n const payload = input.runtimeResult.resultPayload;\n const normalizedDiagnostics = input.diagnostics\n ? {\n ...input.diagnostics,\n publicFailureReason:\n input.diagnostics.publicFailureReason ??\n normalizeOptionalText(input.failureReason),\n }\n : null;\n const normalizedPayload = openMeldDaemonTaskResultPayloadSchema.safeParse({\n status: \"failed\",\n attemptId: payload.attemptId,\n taskId: payload.taskId,\n sourceEventId: payload.sourceEventId,\n agentId: payload.agentId,\n deduped: payload.deduped,\n ...(payload.agentControllerRef\n ? { agentControllerRef: payload.agentControllerRef }\n : {}),\n ...(payload.agentControllerConversationId\n ? { agentControllerConversationId: payload.agentControllerConversationId }\n : {}),\n ...(payload.telemetry ? { telemetry: payload.telemetry } : {}),\n ...(payload.agentControllerConversation\n ? { agentControllerConversation: payload.agentControllerConversation }\n : {}),\n ...(payload.bootstrapTemplateFacts\n ? { bootstrapTemplateFacts: payload.bootstrapTemplateFacts }\n : {}),\n ...(payload.dispatchExecution\n ? { dispatchExecution: payload.dispatchExecution }\n : {}),\n ...(normalizedDiagnostics\n ? { spaceActionFailureDiagnostics: normalizedDiagnostics }\n : {}),\n errorCode: \"openmeld.space_action.repair_failed\",\n errorMessage: input.failureReason,\n errorType: \"policy\",\n });\n if (normalizedPayload.success) {\n return normalizedPayload.data;\n }\n\n return {\n status: \"failed\",\n attemptId: payload.attemptId,\n taskId: payload.taskId,\n sourceEventId: payload.sourceEventId,\n agentId: payload.agentId,\n deduped: payload.deduped,\n ...(payload.agentControllerRef\n ? { agentControllerRef: payload.agentControllerRef }\n : {}),\n ...(normalizedDiagnostics\n ? { spaceActionFailureDiagnostics: normalizedDiagnostics }\n : {}),\n errorCode: \"openmeld.space_action.repair_failed\",\n errorMessage: input.failureReason,\n errorType: \"policy\",\n };\n}\n","import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { runtimeTransportForkAgentSessionResultSchema } from \"@openmeld/schemas\";\nimport type {\n RuntimeTransportForkAgentSessionResult,\n RuntimeTransportLocalAgentControlForkSessionFramePayload,\n} from \"@openmeld/schemas/types\";\nimport { z } from \"zod/v4\";\n\nconst STORE_SCHEMA = \"openmeld-agent-session-fork-operation-store-v2\" as const;\nconst LEGACY_STORE_SCHEMA = \"openmeld-agent-session-fork-operation-store-v1\";\nconst RECORD_SCHEMA =\n \"openmeld-agent-session-fork-operation-record-v1\" as const;\nconst STORE_FILE_NAME = \"agent-session-fork-operations.json\";\nconst STORE_TEMP_FILE_NAME = \"agent-session-fork-operations.tmp\";\nconst MAX_RETAINED_RECORDS = 256;\n\ntype ForkRequest =\n RuntimeTransportLocalAgentControlForkSessionFramePayload[\"request\"];\n\nconst contextForkRequestSchema = z.strictObject({\n kind: z.literal(\"execution_context\"),\n operationId: z.string().uuid(),\n sourceNativeSessionId: z.string().min(1),\n completedHistoryId: z.string().min(1),\n workingDirectory: z.string().min(1),\n});\nexport type ContextForkRequest = z.infer<typeof contextForkRequestSchema>;\nexport type ContextForkRequestInput = {\n kind: \"execution_context\";\n operationId: string;\n sourceNativeSessionId: string;\n completedHistoryId?: string;\n workingDirectory: string;\n};\nconst contextForkResultSchema = z.discriminatedUnion(\"status\", [\n contextForkRequestSchema.extend({\n status: z.literal(\"completed\"),\n childNativeSessionId: z.string().min(1),\n }),\n contextForkRequestSchema.extend({\n status: z.enum([\"rejected\", \"outcome_unknown\"]),\n reasonCode: z.string().min(1),\n message: z.string().min(1),\n }),\n]);\ntype ContextForkResult = z.infer<typeof contextForkResultSchema>;\ntype ForkOperationRequest = ForkRequest | ContextForkRequest;\ntype ForkOperationResult =\n | RuntimeTransportForkAgentSessionResult\n | ContextForkResult;\n\ntype StoredOperation = {\n completedHistoryId?: string;\n operationId: string;\n requestFingerprint: string;\n result: ForkOperationResult | null;\n schema: typeof RECORD_SCHEMA;\n sourceNativeSessionId?: string;\n updatedAtMs: number;\n};\n\ntype OperationStore = {\n records: StoredOperation[];\n schema: typeof STORE_SCHEMA;\n updatedAtMs: number;\n v: 2;\n};\n\ntype ReadRecordsResult =\n | { ok: true; records: StoredOperation[] }\n | {\n ok: false;\n reasonCode:\n | \"agent_session_fork.operation_store_invalid\"\n | \"agent_session_fork.operation_store_unavailable\"\n | \"agent_session_fork.operation_store_update_required\";\n };\n\nconst storeTails = new Map<string, Promise<void>>();\n\nexport async function runAgentSessionForkOperation(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ForkRequest;\n}): Promise<RuntimeTransportForkAgentSessionResult>;\nexport async function runAgentSessionForkOperation(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ContextForkRequestInput;\n resolveCompletedHistoryId?: () => Promise<string>;\n}): Promise<ContextForkResult>;\nexport async function runAgentSessionForkOperation(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ForkRequest | ContextForkRequestInput;\n resolveCompletedHistoryId?: () => Promise<string>;\n}): Promise<ForkOperationResult> {\n const previous = storeTails.get(input.ledgerRootPath) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n storeTails.set(input.ledgerRootPath, tail);\n await previous;\n try {\n return await runSerialized(input);\n } finally {\n release();\n if (storeTails.get(input.ledgerRootPath) === tail) {\n storeTails.delete(input.ledgerRootPath);\n }\n }\n}\n\nfunction handleExistingOperation(\n existing: StoredOperation,\n request: ForkRequest | ContextForkRequestInput\n): ForkOperationResult {\n let effectiveRequest: ForkOperationRequest;\n\n if (\"kind\" in request && request.kind === \"execution_context\") {\n const frozenCompletedHistoryId =\n existing.completedHistoryId ??\n (existing.result && \"completedHistoryId\" in existing.result\n ? existing.result.completedHistoryId\n : undefined);\n\n const requestedCompletedHistoryId = request.completedHistoryId;\n\n if (\n requestedCompletedHistoryId &&\n frozenCompletedHistoryId &&\n requestedCompletedHistoryId !== frozenCompletedHistoryId\n ) {\n return rejected(\n { ...request, completedHistoryId: requestedCompletedHistoryId },\n \"agent_session_fork.operation_identity_conflict\",\n \"This Fork operation id was already used for a different Session.\"\n );\n }\n\n effectiveRequest = {\n ...request,\n completedHistoryId:\n requestedCompletedHistoryId ?? frozenCompletedHistoryId ?? \"\",\n };\n } else {\n effectiveRequest = request as ForkRequest;\n }\n\n const fingerprint = stableJson(effectiveRequest);\n if (existing.requestFingerprint !== fingerprint) {\n return rejected(\n effectiveRequest,\n \"agent_session_fork.operation_identity_conflict\",\n \"This Fork operation id was already used for a different Session.\"\n );\n }\n return (\n existing.result ??\n outcomeUnknown(\n effectiveRequest,\n \"The provider Fork started, but no authoritative child Session id was recorded.\"\n )\n );\n}\n\nasync function resolveEffectiveCreationRequest(\n request: ForkRequest | ContextForkRequestInput,\n resolveCompletedHistoryId?: () => Promise<string>\n): Promise<ForkOperationRequest> {\n if (!(\"kind\" in request && request.kind === \"execution_context\")) {\n return request as ForkRequest;\n }\n let completedHistoryId = request.completedHistoryId;\n if (!completedHistoryId && resolveCompletedHistoryId) {\n completedHistoryId = await resolveCompletedHistoryId();\n }\n if (!completedHistoryId) {\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n }\n return {\n ...request,\n completedHistoryId,\n };\n}\n\nasync function runSerialized(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ForkRequest | ContextForkRequestInput;\n resolveCompletedHistoryId?: () => Promise<string>;\n}): Promise<ForkOperationResult> {\n const stored = await readRecords(input.ledgerRootPath);\n if (!stored.ok) {\n return rejected(\n input.request as ForkOperationRequest,\n stored.reasonCode,\n stored.reasonCode\n );\n }\n const records = stored.records;\n const existing = records.find(\n (record) => record.operationId === input.request.operationId\n );\n if (existing) {\n return handleExistingOperation(existing, input.request);\n }\n\n const effectiveRequest = await resolveEffectiveCreationRequest(\n input.request,\n input.resolveCompletedHistoryId\n );\n const fingerprint = stableJson(effectiveRequest);\n if (\n records.filter(\n (record) =>\n record.result === null || record.result.status === \"outcome_unknown\"\n ).length >= MAX_RETAINED_RECORDS\n ) {\n return rejected(\n effectiveRequest,\n \"agent_session_fork.unresolved_operation_limit\",\n \"Resolve uncertain fork operations before starting another fork.\"\n );\n }\n const started: StoredOperation = {\n ...(\"completedHistoryId\" in effectiveRequest\n ? { completedHistoryId: effectiveRequest.completedHistoryId }\n : {}),\n ...(\"sourceNativeSessionId\" in effectiveRequest\n ? { sourceNativeSessionId: effectiveRequest.sourceNativeSessionId }\n : {}),\n operationId: effectiveRequest.operationId,\n requestFingerprint: fingerprint,\n result: null,\n schema: RECORD_SCHEMA,\n updatedAtMs: Date.now(),\n };\n try {\n await writeRecords(input.ledgerRootPath, [...records, started]);\n } catch (error) {\n return rejected(\n effectiveRequest,\n \"agent_session_fork.operation_store_unavailable\",\n toErrorMessage(error)\n );\n }\n let result: ForkOperationResult;\n try {\n const forked = await input.execute(\n \"completedHistoryId\" in effectiveRequest\n ? { completedHistoryId: effectiveRequest.completedHistoryId }\n : undefined\n );\n result = parseForkOperationResult({\n ...effectiveRequest,\n childNativeSessionId: forked.childNativeSessionId,\n status: \"completed\",\n });\n } catch (error) {\n const reasonCode = readErrorCode(error);\n result = reasonCode\n ? rejected(effectiveRequest, reasonCode, toErrorMessage(error))\n : outcomeUnknown(effectiveRequest, toErrorMessage(error));\n }\n try {\n await writeRecords(input.ledgerRootPath, [\n ...records,\n { ...started, result, updatedAtMs: Date.now() },\n ]);\n } catch (error) {\n return outcomeUnknown(\n effectiveRequest,\n `The provider Fork finished, but OpenMeld could not record its result: ${toErrorMessage(error)}`\n );\n }\n return result;\n}\n\nasync function readRecords(ledgerRootPath: string): Promise<ReadRecordsResult> {\n const path = join(ledgerRootPath, STORE_FILE_NAME);\n let source: string;\n try {\n source = await readFile(path, \"utf8\");\n } catch (error) {\n if (isNodeError(error, \"ENOENT\")) {\n return { ok: true, records: [] };\n }\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_unavailable\",\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_invalid\",\n };\n }\n if (!(parsed && typeof parsed === \"object\")) {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_invalid\",\n };\n }\n if (\n \"schema\" in parsed &&\n parsed.schema === LEGACY_STORE_SCHEMA &&\n \"v\" in parsed &&\n parsed.v === 1\n ) {\n parsed = { ...parsed, schema: STORE_SCHEMA, v: 2 };\n }\n const candidate = parsed as Partial<OperationStore>;\n if (candidate.schema !== STORE_SCHEMA || candidate.v !== 2) {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_update_required\",\n };\n }\n if (!isOperationStore(parsed)) {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_invalid\",\n };\n }\n return { ok: true, records: parsed.records };\n}\n\nasync function writeRecords(\n ledgerRootPath: string,\n records: StoredOperation[]\n): Promise<void> {\n const path = join(ledgerRootPath, STORE_FILE_NAME);\n const tempPath = join(ledgerRootPath, STORE_TEMP_FILE_NAME);\n await mkdir(dirname(path), { mode: 0o700, recursive: true });\n const ordered = [...records].sort(\n (left, right) => right.updatedAtMs - left.updatedAtMs\n );\n const unresolved = ordered.filter(\n (record) =>\n record.result === null || record.result.status === \"outcome_unknown\"\n );\n const retained = [\n ...unresolved,\n ...ordered\n .filter((record) => !unresolved.includes(record))\n .slice(0, Math.max(0, MAX_RETAINED_RECORDS - unresolved.length)),\n ];\n await writeFile(\n tempPath,\n `${JSON.stringify(\n {\n records: retained,\n schema: STORE_SCHEMA,\n updatedAtMs: Date.now(),\n v: 2,\n } satisfies OperationStore,\n null,\n 2\n )}\\n`,\n { encoding: \"utf8\", mode: 0o600 }\n );\n await rename(tempPath, path);\n}\n\nfunction isOperationStore(value: unknown): value is OperationStore {\n if (!(value && typeof value === \"object\")) {\n return false;\n }\n const candidate = value as Partial<OperationStore>;\n return (\n candidate.schema === STORE_SCHEMA &&\n candidate.v === 2 &&\n Array.isArray(candidate.records) &&\n candidate.records.every(isStoredOperation)\n );\n}\n\nfunction isStoredOperation(value: unknown): value is StoredOperation {\n if (!(value && typeof value === \"object\")) {\n return false;\n }\n const candidate = value as Partial<StoredOperation>;\n return (\n candidate.schema === RECORD_SCHEMA &&\n typeof candidate.operationId === \"string\" &&\n typeof candidate.requestFingerprint === \"string\" &&\n typeof candidate.updatedAtMs === \"number\" &&\n (candidate.result === null ||\n runtimeTransportForkAgentSessionResultSchema.safeParse(candidate.result)\n .success ||\n contextForkResultSchema.safeParse(candidate.result).success)\n );\n}\n\nfunction rejected(\n request: ForkOperationRequest,\n reasonCode: string,\n message: string\n): ForkOperationResult {\n return parseForkOperationResult({\n ...request,\n message,\n reasonCode,\n status: \"rejected\",\n });\n}\n\nfunction outcomeUnknown(\n request: ForkOperationRequest,\n message: string\n): ForkOperationResult {\n return parseForkOperationResult({\n ...request,\n message,\n reasonCode: \"agent_session_fork.provider_outcome_unknown\",\n status: \"outcome_unknown\",\n });\n}\n\nfunction readErrorCode(error: unknown): string | null {\n return error && typeof error === \"object\" && \"code\" in error\n ? String(error.code).trim() || null\n : null;\n}\n\nfunction parseForkOperationResult(\n value: Record<string, unknown>\n): ForkOperationResult {\n return value.kind === \"execution_context\"\n ? contextForkResultSchema.parse(value)\n : runtimeTransportForkAgentSessionResultSchema.parse(value);\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error instanceof Error && (error as NodeJS.ErrnoException).code === code\n );\n}\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableJson).join(\",\")}]`;\n }\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n","import { execFile } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n readFile,\n readlink,\n realpath,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { listAgentControllerSupervisedProcessIds } from \"@openmeld/adapter-core\";\nimport {\n executionContextAssignmentSchema,\n executionContextTaskSchema,\n} from \"@openmeld/schemas\";\nimport type {\n ComputerFileAccessPolicy,\n ExecutionContextTask,\n} from \"@openmeld/schemas/types\";\nimport { z } from \"zod/v4\";\nimport {\n acquireLock,\n type OpenMeldLock,\n releaseLock,\n runWithHeldLock,\n} from \"../../config/lock\";\nimport { createLedgerIo } from \"../state/ledger-io\";\n\nconst execFileAsync = promisify(execFile);\nconst syncDirectory = createLedgerIo().syncPath;\nconst COMMIT_PATTERN = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;\nconst manifestSchema = z\n .strictObject({\n version: z.union([z.literal(1), z.literal(2)]),\n identity: executionContextAssignmentSchema,\n sourceWorkingDirectory: z.string().nullable(),\n baseCommit: z.string().regex(COMMIT_PATTERN).nullable(),\n boundaryRoot: z.string(),\n workingDirectory: z.string(),\n status: z.enum([\n \"preparing\",\n \"restoring\",\n \"completed\",\n \"in_use\",\n \"retiring\",\n \"released\",\n ]),\n pristineFingerprint: z\n .string()\n .regex(/^[a-f0-9]{64}$/u)\n .optional(),\n copiedUncommittedFiles: z.literal(false),\n processSupervisionId: z.uuid().optional(),\n retirement: z\n .strictObject({\n path: z.string(),\n pristineFingerprint: z.string().regex(/^[a-f0-9]{64}$/u),\n })\n .optional(),\n })\n .refine(\n (manifest) =>\n manifest.version === 2 ||\n ((manifest.status === \"preparing\" || manifest.status === \"completed\") &&\n !manifest.pristineFingerprint &&\n !manifest.processSupervisionId &&\n !manifest.retirement)\n )\n .refine((manifest) =>\n manifest.identity.access === \"space_context\"\n ? manifest.sourceWorkingDirectory === null && manifest.baseCommit === null\n : manifest.sourceWorkingDirectory !== null &&\n isAbsolute(manifest.sourceWorkingDirectory) &&\n manifest.baseCommit !== null &&\n manifest.identity.workspace === \"isolated\"\n );\ntype Manifest = z.infer<typeof manifestSchema>;\nexport type ExecutionContextWorkspace = {\n workingDirectory: string;\n boundaryRoot: string;\n sourceWorkingDirectory?: string;\n baseCommit?: string;\n};\n\nexport async function prepareExecutionContextWorkspace(input: {\n context: ExecutionContextTask;\n ledgerRootPath: string;\n currentWorkingDirectory: string;\n policy: ComputerFileAccessPolicy;\n}): Promise<ExecutionContextWorkspace> {\n const parsed = executionContextTaskSchema.safeParse(input.context);\n if (!parsed.success) {\n throw failure(\"invalid_workspace_context\");\n }\n const { nativeConversationId, runtimeWorkspaceFingerprint } = parsed.data;\n const identity = executionContextAssignmentSchema.strip().parse(parsed.data);\n const isProject = identity.access !== \"space_context\";\n const source = isProject\n ? await canonicalDirectory(input.currentWorkingDirectory)\n : null;\n if (source) {\n assertSourceAllowed(source, input.policy);\n if (identity.workspace === \"current\") {\n return { workingDirectory: source, boundaryRoot: source };\n }\n }\n\n const ledgerRoot = await ensureDirectory(input.ledgerRootPath, true);\n const workspaceRoot = await ensureDirectory(\n join(ledgerRoot, \"execution-context-workspaces\")\n );\n const recordsRoot = await ensureDirectory(\n join(ledgerRoot, \"execution-context-workspace-records\")\n );\n const boundaryRoot = join(workspaceRoot, identity.id);\n const workingDirectory = source\n ? join(boundaryRoot, \"worktree\")\n : boundaryRoot;\n const recordPath = join(recordsRoot, `${identity.id}.json`);\n return await withWorkspaceLock(ledgerRoot, identity.id, async () => {\n const stored = await readManifest(recordPath);\n if (stored) {\n if (\n JSON.stringify(stored.identity) !== JSON.stringify(identity) ||\n stored.sourceWorkingDirectory !== source ||\n stored.boundaryRoot !== boundaryRoot ||\n stored.workingDirectory !== workingDirectory\n ) {\n throw failure(\"workspace_identity_mismatch\");\n }\n await reconcileRetainedWorkspace(\n stored,\n recordPath,\n Boolean(runtimeWorkspaceFingerprint || nativeConversationId),\n ledgerRoot\n );\n return await verifyRetainedWorkspace(stored);\n }\n if (runtimeWorkspaceFingerprint || nativeConversationId) {\n throw failure(\"workspace_record_missing\");\n }\n if (await inspectPath(boundaryRoot)) {\n throw failure(\"workspace_already_exists\");\n }\n const baseCommit = source ? await resolveSourceCommit(source) : null;\n const manifest: Manifest = {\n version: 2,\n identity,\n sourceWorkingDirectory: source,\n baseCommit,\n boundaryRoot,\n workingDirectory,\n status: \"preparing\",\n copiedUncommittedFiles: false,\n processSupervisionId: randomUUID(),\n };\n // Publish the frozen base before Git starts. The process-owned lock prevents\n // a retry from racing a live materialization; retries never replace task data.\n await writeManifest(recordPath, manifest, \"wx\");\n await finishWorkspacePreparation(manifest, recordPath, true);\n return workspaceResult(manifest);\n });\n}\n\nasync function reconcileRetainedWorkspace(\n record: Manifest,\n path: string,\n hasNativeIdentity: boolean,\n ledgerRoot: string\n) {\n if (record.status === \"retiring\") {\n await runWithHeldLock({\n lock: await acquireWorkspaceExecutionLock(ledgerRoot, record.identity.id),\n run: async () => {\n if (\n !record.processSupervisionId ||\n (\n await listAgentControllerSupervisedProcessIds({\n fresh: true,\n processId: null,\n supervisionId: record.processSupervisionId,\n })\n ).length > 0\n ) {\n throw failure(\"workspace_execution_quiescence_unconfirmed\");\n }\n const reconciled = await finishWorkspaceRetirement(record, path);\n if (reconciled.status === \"released\") {\n await restoreReleasedWorkspace(reconciled, path);\n }\n },\n });\n } else if (record.status === \"released\") {\n await restoreReleasedWorkspace(record, path);\n } else if (record.status === \"preparing\" || record.status === \"restoring\") {\n if (record.status === \"preparing\" && hasNativeIdentity) {\n throw failure(\"workspace_creation_incomplete\");\n }\n if (\n !record.processSupervisionId ||\n (\n await listAgentControllerSupervisedProcessIds({\n fresh: true,\n processId: null,\n supervisionId: record.processSupervisionId,\n })\n ).length > 0\n ) {\n throw failure(\"workspace_preparation_quiescence_unconfirmed\");\n }\n await finishWorkspacePreparation(record, path);\n } else if (record.status === \"in_use\") {\n await runWithHeldLock({\n lock: await acquireWorkspaceExecutionLock(ledgerRoot, record.identity.id),\n run: async () => {\n if (\n !record.processSupervisionId ||\n (\n await listAgentControllerSupervisedProcessIds({\n fresh: true,\n processId: null,\n supervisionId: record.processSupervisionId,\n })\n ).length > 0\n ) {\n throw failure(\"workspace_execution_quiescence_unconfirmed\");\n }\n await verifyRetainedWorkspace(record);\n await writeManifest(path, { ...record, status: \"completed\" }, \"r+\");\n },\n });\n }\n}\n\nasync function finishWorkspacePreparation(\n manifest: Manifest,\n recordPath: string,\n pristineCreation = false\n) {\n const {\n boundaryRoot,\n workingDirectory,\n sourceWorkingDirectory: source,\n baseCommit,\n } = manifest;\n await ensureDirectory(boundaryRoot);\n const repository = join(boundaryRoot, \"repository.git\");\n if (source && baseCommit) {\n if (!(await inspectPath(repository))) {\n if ((await readdir(boundaryRoot)).length > 0) {\n throw failure(\"workspace_creation_incomplete\");\n }\n await git(\n boundaryRoot,\n [\n \"init\",\n \"--bare\",\n \"--template=\",\n `--object-format=${baseCommit.length === 64 ? \"sha256\" : \"sha1\"}`,\n repository,\n ],\n manifest.processSupervisionId\n );\n }\n await canonicalDirectory(repository);\n await assertPrivateMetadata(repository);\n if (\n (await readdir(boundaryRoot)).some(\n (name) => name !== \"repository.git\" && name !== \"worktree\"\n )\n ) {\n throw failure(\"workspace_creation_incomplete\");\n }\n if (await inspectPath(join(repository, \"objects\", \"info\", \"alternates\"))) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n // A protocol fetch copies only committed objects, never local files,\n // alternates or hardlinks, and never writes the source worktree registry.\n if (!(await inspectPath(workingDirectory))) {\n await git(\n boundaryRoot,\n [\n `--git-dir=${repository}`,\n \"fetch\",\n \"--no-tags\",\n \"--no-recurse-submodules\",\n \"--depth=1\",\n \"--no-write-fetch-head\",\n source,\n `${baseCommit}:refs/openmeld/base`,\n ],\n manifest.processSupervisionId\n );\n await git(\n boundaryRoot,\n [\n `--git-dir=${repository}`,\n \"worktree\",\n \"add\",\n \"--detach\",\n workingDirectory,\n baseCommit,\n ],\n manifest.processSupervisionId\n );\n }\n await verifyOwnedRepository(manifest);\n await finishMissingCheckoutFiles(manifest);\n // A prepared checkout may have survived an interruption just before the\n // completed record. Reconcile it only if it has no possible task effects.\n if (!(await isUnchangedCheckout(manifest))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n } else if ((await readdir(boundaryRoot)).length > 0) {\n throw failure(\"workspace_creation_incomplete\");\n }\n await writeManifest(\n recordPath,\n {\n ...manifest,\n status: \"completed\",\n pristineFingerprint: pristineCreation\n ? await fingerprintDirectory(boundaryRoot)\n : undefined,\n },\n \"r+\"\n );\n}\n\nexport async function readExecutionContextWorkspace(input: {\n ledgerRootPath: string;\n contextId: string;\n}): Promise<ExecutionContextWorkspace | null> {\n if (\n !executionContextAssignmentSchema.shape.id.safeParse(input.contextId)\n .success\n ) {\n throw failure(\"invalid_workspace_context\");\n }\n if (!(await inspectPath(input.ledgerRootPath))) {\n return null;\n }\n const ledgerRoot = await canonicalDirectory(input.ledgerRootPath);\n const recordsRoot = join(ledgerRoot, \"execution-context-workspace-records\");\n if (!(await inspectPath(recordsRoot))) {\n return null;\n }\n await canonicalDirectory(recordsRoot);\n const manifest = await readManifest(\n join(recordsRoot, `${input.contextId}.json`)\n );\n if (!manifest) {\n return null;\n }\n const workspaceRoot = await canonicalDirectory(\n join(ledgerRoot, \"execution-context-workspaces\")\n );\n const boundaryRoot = join(workspaceRoot, input.contextId);\n const isProject = manifest.identity.access !== \"space_context\";\n const workingDirectory = isProject\n ? join(boundaryRoot, \"worktree\")\n : boundaryRoot;\n if (\n manifest.identity.id !== input.contextId ||\n manifest.boundaryRoot !== boundaryRoot ||\n manifest.workingDirectory !== workingDirectory\n ) {\n throw failure(\"workspace_identity_mismatch\");\n }\n if (manifest.status === \"released\" || manifest.status === \"retiring\") {\n // Fork reads need the frozen path association, not another live checkout.\n return workspaceResult(manifest);\n }\n if (manifest.status === \"preparing\" || manifest.status === \"restoring\") {\n throw failure(\"workspace_creation_incomplete\");\n }\n return await verifyRetainedWorkspace(manifest);\n}\n\nexport type ExecutionContextWorkspaceUse = {\n lock: OpenMeldLock;\n processSupervisionId: string;\n};\n\nexport async function markExecutionContextWorkspaceInUse(input: {\n ledgerRootPath: string;\n context?: ExecutionContextTask;\n}): Promise<ExecutionContextWorkspaceUse | null> {\n const context = input.context;\n if (\n !context ||\n context.workspace !== \"isolated\" ||\n context.access === \"space_context\"\n ) {\n return null;\n }\n const root = await canonicalDirectory(input.ledgerRootPath);\n const lock = await acquireWorkspaceExecutionLock(root, context.id);\n const processSupervisionId = randomUUID();\n try {\n await withWorkspaceLock(root, context.id, async () => {\n await readExecutionContextWorkspace({\n ledgerRootPath: root,\n contextId: context.id,\n });\n const path = join(\n root,\n \"execution-context-workspace-records\",\n `${context.id}.json`\n );\n const record = await readManifest(path);\n if (record?.status !== \"completed\") {\n throw failure(\"workspace_execution_quiescence_unconfirmed\");\n }\n await writeManifest(\n path,\n { ...record, status: \"in_use\", processSupervisionId },\n \"r+\"\n );\n });\n return { lock, processSupervisionId };\n } catch (error) {\n await releaseLock(lock);\n throw error;\n }\n}\n\nexport type ExecutionContextWorkspaceRelease =\n | { status: \"released\" }\n | {\n status: \"retained\";\n reason:\n | \"execution_quiescence_unconfirmed\"\n | \"workspace_changed\"\n | \"baseline_unverified\"\n | \"cleanup_incomplete\"\n | \"source_commit_unavailable\";\n };\n\nexport async function releaseExecutionContextWorkspace(input: {\n ledgerRootPath: string;\n context: ExecutionContextTask;\n ownedProcessesQuiescent: boolean;\n use?: ExecutionContextWorkspaceUse | null;\n}): Promise<ExecutionContextWorkspaceRelease> {\n const root = await canonicalDirectory(input.ledgerRootPath);\n try {\n return await withWorkspaceLock(root, input.context.id, async () => {\n await readExecutionContextWorkspace({\n ledgerRootPath: root,\n contextId: input.context.id,\n });\n const path = join(\n root,\n \"execution-context-workspace-records\",\n `${input.context.id}.json`\n );\n let record = await readManifest(path);\n if (!(record && [\"completed\", \"in_use\"].includes(record.status))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n if (!input.ownedProcessesQuiescent) {\n return {\n status: \"retained\",\n reason: \"execution_quiescence_unconfirmed\",\n };\n }\n const completed: Manifest = { ...record, status: \"completed\" };\n await writeManifest(path, completed, \"r+\");\n record = await removePristineRetirement(completed, path);\n if (record.retirement) {\n return { status: \"retained\", reason: \"cleanup_incomplete\" };\n }\n // Old records have no pre-execution baseline. Never infer one from a task's\n // current files, including apparently clean commits or ignored outputs.\n if (!record.pristineFingerprint) {\n return { status: \"retained\", reason: \"baseline_unverified\" };\n }\n await verifyRetainedWorkspace(record);\n if (\n (await fingerprintDirectory(record.boundaryRoot)) !==\n record.pristineFingerprint\n ) {\n return { status: \"retained\", reason: \"workspace_changed\" };\n }\n if (record.sourceWorkingDirectory && !(await sourceHasCommit(record))) {\n return { status: \"retained\", reason: \"source_commit_unavailable\" };\n }\n const retired = await retirePristineWorkspace(record, path);\n return retired.status === \"released\"\n ? { status: \"released\" }\n : { status: \"retained\", reason: \"workspace_changed\" };\n });\n } finally {\n if (input.use) {\n await releaseLock(input.use.lock);\n }\n }\n}\n\nasync function retirePristineWorkspace(\n record: Manifest,\n recordPath: string\n): Promise<Manifest> {\n if (\n !record.pristineFingerprint ||\n (await fingerprintDirectory(record.boundaryRoot)) !==\n record.pristineFingerprint\n ) {\n throw failure(\"workspace_release_incomplete\");\n }\n const retiring: Manifest = {\n ...record,\n status: \"retiring\",\n retirement: {\n path: `${recordPath}.retired-${randomUUID()}`,\n pristineFingerprint: record.pristineFingerprint,\n },\n };\n await writeManifest(recordPath, retiring, \"r+\");\n return await finishWorkspaceRetirement(retiring, recordPath);\n}\n\nasync function finishWorkspaceRetirement(\n record: Manifest,\n recordPath: string\n): Promise<Manifest> {\n const retirement = record.retirement;\n if (!retirement) {\n throw failure(\"workspace_release_incomplete\");\n }\n const live = await inspectPath(record.boundaryRoot);\n const retired = await inspectPath(retirement.path);\n if ((live && retired) || !(live || retired)) {\n throw failure(\"workspace_release_incomplete\");\n }\n if (live) {\n await moveWorkspace(record.boundaryRoot, retirement.path);\n }\n if (\n (await fingerprintDirectory(retirement.path)) !==\n retirement.pristineFingerprint\n ) {\n // The path fence caught an edit. Restore that exact copy, including its Git\n // metadata, so continuation sees the output rather than a fresh checkout.\n if (await inspectPath(record.boundaryRoot)) {\n throw failure(\"workspace_release_incomplete\");\n }\n await moveWorkspace(retirement.path, record.boundaryRoot);\n const retained: Manifest = {\n ...record,\n retirement: undefined,\n status: \"completed\",\n };\n await writeManifest(recordPath, retained, \"r+\");\n return retained;\n }\n const released: Manifest = { ...record, status: \"released\" };\n await writeManifest(recordPath, released, \"r+\");\n return await removePristineRetirement(released, recordPath);\n}\n\nasync function removePristineRetirement(\n record: Manifest,\n recordPath: string\n): Promise<Manifest> {\n const retirement = record.retirement;\n if (!retirement) {\n return record;\n }\n if (await inspectPath(retirement.path)) {\n if (\n (await fingerprintDirectory(retirement.path)) !==\n retirement.pristineFingerprint\n ) {\n return record;\n }\n await rm(retirement.path, { recursive: true });\n }\n const removed = { ...record, retirement: undefined };\n await writeManifest(recordPath, removed, \"r+\");\n return removed;\n}\n\nasync function restoreReleasedWorkspace(record: Manifest, recordPath: string) {\n if (record.sourceWorkingDirectory && !(await sourceHasCommit(record))) {\n throw failure(\"workspace_base_commit_unavailable\");\n }\n if (await inspectPath(record.boundaryRoot)) {\n throw failure(\"workspace_already_exists\");\n }\n const restoring: Manifest = {\n ...record,\n status: \"restoring\",\n processSupervisionId: randomUUID(),\n };\n await writeManifest(recordPath, restoring, \"r+\");\n await finishWorkspacePreparation(restoring, recordPath, true);\n}\n\nasync function sourceHasCommit(record: Manifest): Promise<boolean> {\n if (!(record.sourceWorkingDirectory && record.baseCommit)) {\n return false;\n }\n try {\n await git(record.sourceWorkingDirectory, [\n \"cat-file\",\n \"-e\",\n `${record.baseCommit}^{commit}`,\n ]);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function isUnchangedCheckout(record: Manifest): Promise<boolean> {\n return (\n (await git(record.workingDirectory, [\"rev-parse\", \"HEAD\"])) ===\n record.baseCommit &&\n (await git(record.workingDirectory, [\n \"status\",\n \"--porcelain\",\n \"--untracked-files=all\",\n \"--ignored\",\n ])) === \"\"\n );\n}\n\nasync function finishMissingCheckoutFiles(record: Manifest) {\n if (\n (await git(record.workingDirectory, [\"rev-parse\", \"HEAD\"])) !==\n record.baseCommit\n ) {\n throw failure(\"workspace_creation_incomplete\");\n }\n const flags = await git(record.workingDirectory, [\"ls-files\", \"-v\", \"-z\"]);\n if (flags.split(\"\\0\").some((entry) => entry && !entry.startsWith(\"H \"))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n const status = await git(record.workingDirectory, [\n \"status\",\n \"--porcelain\",\n \"-z\",\n \"--untracked-files=all\",\n \"--ignored\",\n ]);\n if (!status) {\n return;\n }\n const changes = status.split(\"\\0\").filter(Boolean);\n if (changes.some((entry) => !entry.startsWith(\" D \"))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n // checkout-index without --force writes only absent files. Existing edits,\n // staged changes and extra files were rejected, never overwritten.\n const paths = changes.map((entry) => entry.slice(3));\n for (let offset = 0; offset < paths.length; offset += 100) {\n await git(\n record.workingDirectory,\n [\"checkout-index\", \"--\", ...paths.slice(offset, offset + 100)],\n record.processSupervisionId\n );\n }\n}\n\nasync function fingerprintDirectory(root: string): Promise<string> {\n const hash = createHash(\"sha256\");\n const visit = async (directory: string) => {\n for (const name of (await readdir(directory)).sort()) {\n const path = join(directory, name);\n const info = await lstat(path);\n hash.update(\n JSON.stringify([relative(root, path), info.mode, info.nlink])\n );\n if (info.isSymbolicLink()) {\n hash.update(JSON.stringify(await readlink(path)));\n } else if (info.isDirectory()) {\n await visit(path);\n } else if (info.isFile() && info.nlink === 1) {\n hash.update(String(info.size));\n hash.update(await fingerprintFile(path));\n } else {\n throw failure(\"workspace_git_metadata_changed\");\n }\n }\n };\n await visit(root);\n return hash.digest(\"hex\");\n}\n\nasync function fingerprintFile(path: string) {\n const hash = createHash(\"sha256\");\n const file = await open(path, \"r\");\n try {\n const buffer = Buffer.alloc(64 * 1024);\n for (;;) {\n const { bytesRead } = await file.read(buffer);\n if (!bytesRead) {\n break;\n }\n hash.update(buffer.subarray(0, bytesRead));\n }\n } finally {\n await file.close();\n }\n return hash.digest(\"hex\");\n}\n\nasync function withWorkspaceLock<T>(\n root: string,\n contextId: string,\n run: () => Promise<T>\n): Promise<T> {\n if (!executionContextAssignmentSchema.shape.id.safeParse(contextId).success) {\n throw failure(\"invalid_workspace_context\");\n }\n return await runWithHeldLock({\n lock: await acquireLock({\n openMeldProfileId: \"execution-context-workspaces\",\n key: contextId,\n pathResolution: { env: { OPENMELD_HOME: root } },\n }),\n run,\n });\n}\n\nasync function verifyRetainedWorkspace(\n manifest: Manifest\n): Promise<ExecutionContextWorkspace> {\n await canonicalDirectory(manifest.boundaryRoot);\n await canonicalDirectory(manifest.workingDirectory);\n if (manifest.sourceWorkingDirectory) {\n await verifyOwnedRepository(manifest);\n }\n return workspaceResult(manifest);\n}\n\nasync function acquireWorkspaceExecutionLock(root: string, contextId: string) {\n return await acquireLock({\n openMeldProfileId: \"execution-context-workspaces\",\n key: `${contextId}-execution`,\n pathResolution: { env: { OPENMELD_HOME: root } },\n });\n}\n\nfunction workspaceResult(manifest: Manifest): ExecutionContextWorkspace {\n return {\n workingDirectory: manifest.workingDirectory,\n boundaryRoot: manifest.boundaryRoot,\n ...(manifest.sourceWorkingDirectory\n ? { sourceWorkingDirectory: manifest.sourceWorkingDirectory }\n : {}),\n ...(manifest.baseCommit ? { baseCommit: manifest.baseCommit } : {}),\n };\n}\n\nfunction assertSourceAllowed(\n source: string,\n policy: ComputerFileAccessPolicy\n): void {\n if (\n policy.mode === \"only_selected_folders\" &&\n !policy.folders.some((folder) => within(source, folder))\n ) {\n throw failure(\"workspace_outside_computer_policy\");\n }\n if (\n policy.mode === \"block_selected_folders\" &&\n policy.folders.some(\n (folder) => within(source, folder) || within(folder, source)\n )\n ) {\n throw failure(\"workspace_overlaps_blocked_folder\");\n }\n}\n\nasync function resolveSourceCommit(source: string): Promise<string> {\n // Requiring a marker at the selected root prevents Git's upward discovery\n // from escalating a selected subdirectory into the surrounding repository.\n if (!(await inspectPath(join(source, \".git\")))) {\n throw failure(\"project_repository_required\");\n }\n const topLevel = await git(source, [\"rev-parse\", \"--show-toplevel\"]);\n if ((await realpath(topLevel)) !== source) {\n throw failure(\"project_repository_root_required\");\n }\n const commit = await git(source, [\n \"rev-parse\",\n \"--verify\",\n \"HEAD^{commit}\",\n ]).catch((cause: unknown) => {\n throw new Error(\"execution_context.project_commit_required\", { cause });\n });\n if (!COMMIT_PATTERN.test(commit)) {\n throw failure(\"project_commit_required\");\n }\n return commit;\n}\n\nasync function verifyOwnedRepository(manifest: Manifest): Promise<void> {\n const repository = join(manifest.boundaryRoot, \"repository.git\");\n await canonicalDirectory(repository);\n await assertPrivateMetadata(repository);\n if (await inspectPath(join(repository, \"objects\", \"info\", \"alternates\"))) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n const gitFile = join(manifest.workingDirectory, \".git\");\n const gitFileInfo = await inspectPath(gitFile);\n if (!gitFileInfo?.isFile() || gitFileInfo.size > 4096) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n const expectedGitDir = join(repository, \"worktrees\", \"worktree\");\n if (\n (await readFile(gitFile, \"utf8\")).trim() !== `gitdir: ${expectedGitDir}`\n ) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n if (\n (await realpath(\n join(\n expectedGitDir,\n (await readFile(join(expectedGitDir, \"commondir\"), \"utf8\")).trim()\n )\n )) !== repository\n ) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n const base = await git(manifest.boundaryRoot, [\n `--git-dir=${repository}`,\n \"rev-parse\",\n \"--verify\",\n \"refs/openmeld/base^{commit}\",\n ]);\n if (base !== manifest.baseCommit) {\n throw failure(\"workspace_base_commit_changed\");\n }\n}\n\nasync function assertPrivateMetadata(path: string): Promise<void> {\n for (const entry of await readdir(path, { withFileTypes: true })) {\n if (entry.isSymbolicLink()) {\n throw failure(\"workspace_is_symlink\");\n }\n if (entry.isDirectory()) {\n await assertPrivateMetadata(join(path, entry.name));\n } else if ((await lstat(join(path, entry.name))).nlink !== 1) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n }\n}\n\nasync function readManifest(path: string): Promise<Manifest | null> {\n const info = await inspectPath(path);\n if (!info) {\n return null;\n }\n if (!info.isFile() || info.size > 32_768) {\n throw failure(\"workspace_record_invalid\");\n }\n let content: unknown;\n try {\n content = JSON.parse(await readFile(path, \"utf8\"));\n } catch {\n throw failure(\"workspace_record_invalid\");\n }\n const parsed = manifestSchema.safeParse(content);\n if (!parsed.success) {\n throw failure(\"workspace_record_invalid\");\n }\n const retirement = parsed.data.retirement;\n const prefix = `${path}.retired-`;\n if (\n (parsed.data.status === \"retiring\" && !retirement) ||\n (retirement &&\n !(\n retirement.path.startsWith(prefix) &&\n z.uuid().safeParse(retirement.path.slice(prefix.length)).success\n ))\n ) {\n throw failure(\"workspace_record_invalid\");\n }\n return parsed.data;\n}\n\nasync function writeManifest(\n path: string,\n manifest: Manifest,\n flags: \"wx\" | \"r+\"\n): Promise<void> {\n const temporaryPath = flags === \"wx\" ? path : `${path}.${randomUUID()}.tmp`;\n const file = await open(temporaryPath, \"wx\", 0o600);\n try {\n await file.writeFile(\n `${JSON.stringify({ ...manifest, version: 2 })}\\n`,\n \"utf8\"\n );\n await file.sync();\n } finally {\n await file.close();\n }\n if (flags !== \"wx\") {\n await rename(temporaryPath, path);\n }\n await syncDirectory(dirname(path));\n}\n\nasync function moveWorkspace(from: string, to: string) {\n await rename(from, to);\n await syncDirectory(dirname(from));\n await syncDirectory(dirname(to));\n}\n\nasync function inspectPath(path: string) {\n const info = await lstat(path).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n });\n if (info?.isSymbolicLink()) {\n throw failure(\"workspace_is_symlink\");\n }\n return info;\n}\n\nasync function canonicalDirectory(path: string): Promise<string> {\n if (!(await inspectPath(path))?.isDirectory()) {\n throw failure(\"workspace_directory_unavailable\");\n }\n return await realpath(path);\n}\n\nasync function ensureDirectory(\n path: string,\n recursive = false\n): Promise<string> {\n await inspectPath(path);\n await mkdir(path, { recursive, mode: 0o700 }).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"EEXIST\") {\n throw error;\n }\n }\n );\n return await canonicalDirectory(path);\n}\n\nfunction within(child: string, parent: string): boolean {\n const path = relative(resolve(parent), child);\n return (\n path === \"\" ||\n (path !== \"..\" && !path.startsWith(`..${sep}`) && !isAbsolute(path))\n );\n}\n\nconst GIT_SETTINGS = {\n \"core.hooksPath\": \"/dev/null\",\n \"core.attributesFile\": \"/dev/null\",\n \"core.fsmonitor\": \"false\",\n \"credential.helper\": \"\",\n \"protocol.allow\": \"never\",\n \"protocol.file.allow\": \"always\",\n \"fetch.recurseSubmodules\": \"false\",\n \"submodule.recurse\": \"false\",\n \"uploadpack.packObjectsHook\": \"\",\n \"gc.auto\": \"0\",\n \"maintenance.auto\": \"false\",\n};\n\nasync function git(\n cwd: string,\n args: string[],\n processSupervisionId?: string\n): Promise<string> {\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !key.startsWith(\"GIT_\"))\n );\n Object.assign(env, {\n ...(processSupervisionId\n ? { OPENMELD_PROCESS_SUPERVISION_ID: processSupervisionId }\n : {}),\n GIT_CONFIG_NOSYSTEM: \"1\",\n GIT_CONFIG_SYSTEM: \"/dev/null\",\n GIT_CONFIG_GLOBAL: \"/dev/null\",\n GIT_ATTR_NOSYSTEM: \"1\",\n GIT_NO_REPLACE_OBJECTS: \"1\",\n GIT_NO_LAZY_FETCH: \"1\",\n GIT_ALLOW_PROTOCOL: \"file\",\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_CONFIG_COUNT: String(Object.keys(GIT_SETTINGS).length),\n });\n for (const [index, [key, value]] of Object.entries(GIT_SETTINGS).entries()) {\n env[`GIT_CONFIG_KEY_${index}`] = key;\n env[`GIT_CONFIG_VALUE_${index}`] = value;\n }\n const result = await execFileAsync(\"git\", args, {\n cwd,\n env,\n encoding: \"utf8\",\n timeout: 30_000,\n maxBuffer: 1024 * 1024,\n });\n return result.stdout.trimEnd();\n}\n\nfunction failure(code: string): Error {\n return new Error(`execution_context.${code}`);\n}\n","import { lstat, mkdir, realpath } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n forkSession,\n getSessionInfo,\n getSessionMessages,\n} from \"@anthropic-ai/claude-agent-sdk\";\nimport {\n forkCodexAppServerThread,\n resolveCodexAppServerCompletedTurn,\n} from \"@openmeld/adapter-codex\";\nimport type {\n AdapterComputerFileAccessBoundary,\n AdapterRuntimeEventCallback,\n RuntimeAgentControllerLaunchContract,\n} from \"@openmeld/adapter-core\";\nimport { buildRuntimeWorkspaceFingerprint } from \"@openmeld/local-execution\";\nimport type {\n ComputerFileAccessPolicy,\n ExecutionContextCompletion,\n ExecutionContextTask,\n} from \"@openmeld/schemas/types\";\nimport { isSameOrDescendantPath } from \"../../lib/path-containment\";\nimport { runAgentSessionForkOperation } from \"../session-control/session-fork-operation-store\";\nimport {\n type ExecutionContextWorkspace,\n readExecutionContextWorkspace,\n} from \"./execution-context-workspace\";\n\nexport function executionContextLedgerPolicy(context?: ExecutionContextTask) {\n return context ? (\"throw\" as const) : (\"backup_and_reset\" as const);\n}\n\nexport function executionContextResourceScope(context?: ExecutionContextTask) {\n if (!context) {\n return undefined;\n }\n if (context.access === \"space_context\") {\n return \"none\" as const;\n }\n if (context.workspace === \"isolated\") {\n return context.access === \"workspace\"\n ? (\"isolated\" as const)\n : (\"isolated_read\" as const);\n }\n return context.access === \"workspace\"\n ? (\"exclusive\" as const)\n : (\"read_only\" as const);\n}\n\nexport function executionContextFileAccessBoundary(input: {\n context: ExecutionContextTask;\n workingDirectory: string;\n policy: ComputerFileAccessPolicy;\n taskWorkspace?: ExecutionContextWorkspace;\n workingCopyId?: string;\n}): AdapterComputerFileAccessBoundary {\n const within = isSameOrDescendantPath;\n const policy = input.policy;\n // Space-only work has no user-folder source. The native boundary still names\n // only its Service-owned scratch root, regardless of the user's folder policy.\n if (input.context.access !== \"space_context\") {\n const policySource =\n input.taskWorkspace?.sourceWorkingDirectory ?? input.workingDirectory;\n if (\n policy.mode === \"only_selected_folders\" &&\n !policy.folders.some((folder) => within(policySource, folder))\n ) {\n throw new Error(\"execution_context.workspace_outside_computer_policy\");\n }\n if (\n policy.mode === \"block_selected_folders\" &&\n policy.folders.some(\n (folder) => within(policySource, folder) || within(folder, policySource)\n )\n ) {\n throw new Error(\"execution_context.workspace_overlaps_blocked_folder\");\n }\n }\n return {\n mode: \"only_selected_folders\",\n folders: [\n input.context.access === \"space_context\" && input.workingCopyId\n ? input.workingDirectory\n : (input.taskWorkspace?.boundaryRoot ?? input.workingDirectory),\n ],\n revision: policy.revision,\n updatedAtMs: policy.updatedAtMs,\n executionContextAccess: input.context.access,\n ...(input.context.access === \"space_context\" && input.workingCopyId\n ? { workingCopyId: input.workingCopyId }\n : {}),\n };\n}\n\nexport async function executionContextWorkingDirectory(input: {\n context?: Pick<ExecutionContextTask, \"id\" | \"workspace\">;\n ledgerRootPath: string;\n currentWorkingDirectory: string;\n}): Promise<string> {\n if (!input.context) {\n return input.currentWorkingDirectory;\n }\n if (input.context.workspace === \"current\") {\n return await realpath(input.currentWorkingDirectory);\n }\n await mkdir(input.ledgerRootPath, { recursive: true, mode: 0o700 });\n const root = join(\n await realpath(input.ledgerRootPath),\n \"execution-context-workspaces\"\n );\n await mkdir(root, { recursive: true, mode: 0o700 });\n if ((await lstat(root)).isSymbolicLink()) {\n throw new Error(\"execution_context.workspace_is_symlink\");\n }\n const path = join(root, input.context.id);\n await mkdir(path, { recursive: true, mode: 0o700 });\n if ((await lstat(path)).isSymbolicLink()) {\n throw new Error(\"execution_context.workspace_is_symlink\");\n }\n return await realpath(path);\n}\n\nexport async function prepareExecutionContextConversation(input: {\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n context?: ExecutionContextTask;\n unscopedNativeConversationId: string | null;\n currentWorkingDirectory: string;\n workingDirectory: string;\n existingNativeConversationId: string | null;\n ledgerRootPath: string;\n agentControllerRef: string;\n launchContract?: RuntimeAgentControllerLaunchContract | null;\n onRuntimeEvent?: AdapterRuntimeEventCallback;\n processSupervisionId?: string;\n}): Promise<string | null> {\n if (!input.context) {\n return input.unscopedNativeConversationId;\n }\n const nativeId = input.context.nativeConversationId;\n if (\n input.context.runtimeWorkspaceFingerprint &&\n input.context.runtimeWorkspaceFingerprint !==\n buildRuntimeWorkspaceFingerprint(input.workingDirectory)\n ) {\n throw new Error(\"execution_context.workspace_changed\");\n }\n if (\n nativeId &&\n input.existingNativeConversationId &&\n nativeId !== input.existingNativeConversationId\n ) {\n throw new Error(\"execution_context.native_identity_mismatch\");\n }\n if (nativeId || input.existingNativeConversationId) {\n return nativeId ?? input.existingNativeConversationId;\n }\n const source = input.context.forkSource;\n if (!source) {\n return null;\n }\n const sourceWorkspace =\n source.workspace === \"isolated\"\n ? await readExecutionContextWorkspace({\n ledgerRootPath: input.ledgerRootPath,\n contextId: source.contextId,\n })\n : null;\n const sourceDirectory =\n sourceWorkspace?.workingDirectory ??\n (await realpath(\n source.workspace === \"current\"\n ? input.currentWorkingDirectory\n : (sourceWorkspace?.workingDirectory ??\n join(\n input.ledgerRootPath,\n \"execution-context-workspaces\",\n source.contextId\n ))\n ));\n if (\n buildRuntimeWorkspaceFingerprint(sourceDirectory) !==\n source.runtimeWorkspaceFingerprint\n ) {\n throw new Error(\"execution_context.fork_source_workspace_changed\");\n }\n // A frozen checkpoint is authoritative when Core assigned one. Otherwise the\n // boundary is resolved under the fork journal lock: the source may be a\n // thread OpenMeld never finished a turn on, and reading its settled turns\n // names a cutoff that is verified now rather than assumed. That read takes no\n // writer lock, so it works while another App Server holds the thread. The\n // journal records the exact boundary it forked at, so a lost response\n // or subsequent replay restores that recorded cutoff instead of re-reading\n // an advanced source history.\n const result = await runAgentSessionForkOperation({\n ledgerRootPath: input.ledgerRootPath,\n request: {\n kind: \"execution_context\",\n operationId: input.context.id,\n sourceNativeSessionId: source.nativeConversationId,\n ...(source.completedHistoryId\n ? { completedHistoryId: source.completedHistoryId }\n : {}),\n workingDirectory: input.workingDirectory,\n },\n resolveCompletedHistoryId: async () => {\n if (\n input.agentControllerRef === \"builtin:codex\" &&\n input.launchContract\n ) {\n const completed = await resolveCodexAppServerCompletedTurn({\n codexTimeoutMs: 30_000,\n codexWorkdir: sourceDirectory,\n launchContract: input.launchContract,\n threadId: source.nativeConversationId,\n });\n return completed.completedTurnId;\n }\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n },\n execute: async (forkInput) => {\n const completedHistoryId = forkInput?.completedHistoryId;\n if (!completedHistoryId) {\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n }\n if (input.agentControllerRef === \"builtin:claude-code\") {\n const messages = await readBoundedClaudeHistory(\n source.nativeConversationId\n );\n const boundary = messages.find(\n (message) =>\n message.uuid === completedHistoryId &&\n isCompletedAssistantMessage(message)\n );\n if (!boundary) {\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n }\n const child = await forkSession(source.nativeConversationId, {\n upToMessageId: completedHistoryId,\n });\n return { childNativeSessionId: child.sessionId };\n }\n if (\n input.agentControllerRef === \"builtin:codex\" &&\n input.launchContract\n ) {\n const child = await forkCodexAppServerThread({\n computerFileAccessBoundary:\n input.computerFileAccessBoundary ?? undefined,\n codexTimeoutMs: 30_000,\n codexWorkdir: sourceDirectory,\n launchContract: input.launchContract,\n sourceThreadId: source.nativeConversationId,\n sourceCompletedTurnId: completedHistoryId,\n targetWorkingDirectory: input.workingDirectory,\n onRuntimeEvent: input.onRuntimeEvent,\n env: { OPENMELD_PROCESS_SUPERVISION_ID: input.processSupervisionId },\n });\n return { childNativeSessionId: child.threadId };\n }\n throw new Error(\"execution_context.fork_unsupported\");\n },\n });\n if (result.status !== \"completed\") {\n throw new Error(`${result.reasonCode}: ${result.message}`);\n }\n return result.childNativeSessionId;\n}\n\nexport async function captureExecutionContextCompletion(input: {\n context?: ExecutionContextTask;\n nativeConversationId: string | null;\n agentControllerRef: string;\n workingDirectory: string;\n completedTurnId: string | null;\n providerSucceeded: boolean;\n}): Promise<ExecutionContextCompletion | undefined> {\n if (!(input.context && input.nativeConversationId)) {\n return undefined;\n }\n const completion: ExecutionContextCompletion = {\n contextId: input.context.id,\n nativeConversationId: input.nativeConversationId,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n input.workingDirectory\n ),\n };\n if (!input.providerSucceeded) {\n return completion;\n }\n if (input.agentControllerRef === \"builtin:codex\") {\n return {\n ...completion,\n ...(input.completedTurnId\n ? { completedHistoryId: input.completedTurnId }\n : {}),\n };\n }\n if (input.agentControllerRef === \"builtin:claude-code\") {\n try {\n const messages = await readBoundedClaudeHistory(\n input.nativeConversationId\n );\n const completed = messages.findLast(isCompletedAssistantMessage);\n if (completed) {\n return { ...completion, completedHistoryId: completed.uuid };\n }\n } catch {\n // Native completion remains known; no unverified fork boundary is emitted.\n console.warn(\"[execution_context.checkpoint_unavailable]\", {\n contextId: input.context.id,\n });\n }\n }\n return completion;\n}\n\nasync function readBoundedClaudeHistory(sessionId: string) {\n // A fork may execute in a different folder from its native history file.\n // The SDK resolves this exact authorized ID; the Service does not scan sessions.\n const info = await getSessionInfo(sessionId);\n if (!info || info.fileSize === undefined || info.fileSize > 8 * 1024 * 1024) {\n throw new Error(\"execution_context.history_unavailable_or_too_large\");\n }\n return await getSessionMessages(sessionId);\n}\n\nfunction isCompletedAssistantMessage(\n value: Awaited<ReturnType<typeof getSessionMessages>>[number]\n): boolean {\n return (\n value.type === \"assistant\" &&\n typeof value.message === \"object\" &&\n value.message !== null &&\n \"stop_reason\" in value.message &&\n value.message.stop_reason === \"end_turn\"\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS } from \"@openmeld/schemas\";\nimport type { OpenMeldDaemonTaskResultPayload } from \"@openmeld/schemas/types\";\n\ntype DispatchPromptTrace = NonNullable<\n OpenMeldDaemonTaskResultPayload[\"promptTrace\"]\n>;\n\nconst OMITTED_ORGANIZATION_POLICY =\n \"[organization-protected information policy omitted]\";\n\nexport function buildDispatchPromptTrace(input: {\n prompt: string;\n protectedInformation?: string | null;\n}): DispatchPromptTrace | null {\n if (input.prompt.trim().length === 0) {\n return null;\n }\n const protectedInformation = input.protectedInformation?.trim();\n const traceSafePrompt = protectedInformation\n ? input.prompt.replaceAll(protectedInformation, OMITTED_ORGANIZATION_POLICY)\n : input.prompt;\n return {\n fingerprint: `sha256:${createHash(\"sha256\")\n .update(input.prompt)\n .digest(\"hex\")}`,\n length: input.prompt.length,\n preview:\n traceSafePrompt.length <= SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS\n ? traceSafePrompt\n : `${traceSafePrompt\n .slice(0, SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS - 3)\n .trimEnd()}...`,\n };\n}\n","import type {\n AdapterReasoningEvent,\n AdapterRuntimeEvent,\n AdapterRuntimeEventCallback,\n} from \"@openmeld/adapter-core\";\nimport { LOCAL_AGENT_REASONING_MAX_CHARS } from \"@openmeld/schemas\";\n\n/** Keep private live content outside all lifecycle and journaling observers. */\nexport function routeReasoningEvents(\n reasoning: (event: AdapterReasoningEvent) => void,\n lifecycle: (\n event: Exclude<AdapterRuntimeEvent, AdapterReasoningEvent>\n ) => void\n): AdapterRuntimeEventCallback {\n return (event) => {\n if (event.phase === \"reasoning\") {\n reasoning(event);\n } else {\n lifecycle(event);\n }\n };\n}\n\n/** A disposable live tail, deliberately independent of the result journal. */\nexport function createReasoningStream(input: {\n enabled: () => boolean;\n send: (snapshot: string, observedAtMs: number) => void;\n}) {\n const blocks = new Map<string, string>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lastSentAt = Number.NEGATIVE_INFINITY;\n let observedAtMs = 0;\n let dirty = false;\n let disposed = false;\n const clear = () => {\n if (timer) {\n clearTimeout(timer);\n }\n timer = undefined;\n blocks.clear();\n dirty = false;\n };\n const flush = () => {\n if (timer) {\n clearTimeout(timer);\n }\n timer = undefined;\n if (disposed || !input.enabled()) {\n clear();\n return;\n }\n if (!dirty) {\n return;\n }\n dirty = false;\n lastSentAt = Date.now();\n input.send(\n [...blocks.values()].join(\"\\n\\n\").slice(-LOCAL_AGENT_REASONING_MAX_CHARS),\n observedAtMs\n );\n };\n return {\n clear,\n observe(event: AdapterReasoningEvent) {\n if (disposed || !input.enabled()) {\n clear();\n return;\n }\n if (!event.text) {\n return;\n }\n const previous = blocks.get(event.blockId) ?? \"\";\n const next = (\n event.mode === \"snapshot\" ? event.text : previous + event.text\n ).slice(-LOCAL_AGENT_REASONING_MAX_CHARS);\n if (next === previous) {\n return;\n }\n blocks.set(event.blockId, next);\n while (blocks.size > 8) {\n const oldest = blocks.keys().next().value;\n if (oldest !== undefined) {\n blocks.delete(oldest);\n }\n }\n dirty = true;\n observedAtMs = event.tsMs;\n const delay = Math.max(0, 100 - (Date.now() - lastSentAt));\n if (delay === 0) {\n flush();\n } else {\n timer ??= setTimeout(flush, delay);\n }\n },\n dispose() {\n disposed = true;\n clear();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport type { DispatchSendTargetProjectionEntry } from \"@openmeld/local-service\";\nimport type {\n OpenMeldRequestContext,\n SpaceMemberDirectory,\n} from \"@openmeld/schemas/types\";\nimport {\n createDispatchContinuationSpaceAccessContext,\n getSpaceAccessPassword,\n getSpaceAccessRequestContext,\n listSpaceMemberDirectorySendTargets,\n type SpaceMemberDirectorySendTargetEntry,\n} from \"@openmeld/space\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../../config/openmeld-request-context\";\nimport { createCliSpaceApi, type SpaceApi } from \"../../space/cli-space-api\";\n\nconst SEND_TARGET_REFERENCE_DIRECTORY_CACHE_TTL_MS = 20_000;\n\ntype CachedMemberDirectory = {\n directory: SpaceMemberDirectory;\n expiresAtMs: number;\n};\n\nconst memberDirectoryCache = new Map<string, CachedMemberDirectory>();\nconst inFlightMemberDirectoryLoads = new Map<\n string,\n Promise<SpaceMemberDirectory>\n>();\n\nexport type DispatchSendTargetReferenceLoadResult =\n | {\n status: \"loaded\";\n projection: SpaceMemberDirectorySendTargetEntry[];\n referenceLines: string[];\n }\n | {\n status: \"failed\";\n errorMessage: string;\n projection: null;\n referenceLines: [];\n };\n\nexport async function resolveDispatchSendTargetReference(input: {\n agentControllerRef: string;\n dispatchTask: {\n attemptId: string;\n dispatchId: string;\n sourceEventId: string;\n spaceId: string;\n spacePassword: string | null;\n targetProfileId: string;\n };\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n targetProfileName: string | null;\n}): Promise<DispatchSendTargetReferenceLoadResult> {\n try {\n const baseUrl = await resolveBaseUrl();\n const spaceApi = createCliSpaceApi(baseUrl);\n const requestContext = buildDispatchSendTargetRequestContext({\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n targetProfileId: input.dispatchTask.targetProfileId,\n targetProfileName: input.targetProfileName,\n });\n const spaceAccess = createDispatchContinuationSpaceAccessContext({\n attemptId: input.dispatchTask.attemptId,\n dispatchId: input.dispatchTask.dispatchId,\n password: input.dispatchTask.spacePassword,\n requestContext,\n sourceSignalId: input.dispatchTask.sourceEventId,\n spaceId: input.dispatchTask.spaceId,\n targetProfileId: input.dispatchTask.targetProfileId,\n });\n const accessRequestContext = getSpaceAccessRequestContext(spaceAccess);\n const spacePassword = getSpaceAccessPassword(spaceAccess) ?? null;\n const directory = await loadDispatchSendTargetMemberDirectory({\n baseUrl,\n profileOwnerUserId: input.profileOwnerUserId,\n requestContext: accessRequestContext ?? requestContext,\n spaceApi,\n spaceId: spaceAccess.spaceId,\n spacePassword,\n });\n const projection = listSpaceMemberDirectorySendTargets(directory).sort(\n (left, right) =>\n left.primaryMentionLabel.localeCompare(\n right.primaryMentionLabel,\n \"en\",\n {\n sensitivity: \"base\",\n }\n )\n );\n\n return {\n status: \"loaded\",\n projection,\n referenceLines: projection\n .filter(\n (target) => target.profileId !== input.dispatchTask.targetProfileId\n )\n .map((target) => formatDispatchSendTargetReferenceLine(target)),\n };\n } catch (error) {\n return {\n status: \"failed\",\n errorMessage:\n error instanceof Error\n ? error.message\n : \"Failed to load current Space member directory\",\n projection: null,\n referenceLines: [],\n };\n }\n}\n\nfunction loadDispatchSendTargetMemberDirectory(input: {\n baseUrl: string;\n profileOwnerUserId: string;\n requestContext: OpenMeldRequestContext;\n spaceApi: SpaceApi;\n spaceId: string;\n spacePassword: string | null;\n}): Promise<SpaceMemberDirectory> {\n const cacheKey = buildMemberDirectoryCacheKey(input);\n const nowMs = Date.now();\n const cached = memberDirectoryCache.get(cacheKey);\n if (cached && cached.expiresAtMs > nowMs) {\n return Promise.resolve(cached.directory);\n }\n if (cached) {\n memberDirectoryCache.delete(cacheKey);\n }\n\n const inFlight = inFlightMemberDirectoryLoads.get(cacheKey);\n if (inFlight) {\n return inFlight;\n }\n\n const loadPromise = input.spaceApi\n .getMemberDirectory({\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n ...(input.spacePassword ? { spacePassword: input.spacePassword } : {}),\n })\n .then((directory) => {\n memberDirectoryCache.set(cacheKey, {\n directory,\n expiresAtMs: Date.now() + SEND_TARGET_REFERENCE_DIRECTORY_CACHE_TTL_MS,\n });\n return directory;\n })\n .finally(() => {\n inFlightMemberDirectoryLoads.delete(cacheKey);\n });\n\n inFlightMemberDirectoryLoads.set(cacheKey, loadPromise);\n return loadPromise;\n}\n\nfunction buildMemberDirectoryCacheKey(input: {\n baseUrl: string;\n profileOwnerUserId: string;\n spaceId: string;\n spacePassword: string | null;\n}): string {\n return [\n `base:${input.baseUrl}`,\n `space:${input.spaceId}`,\n `owner:${input.profileOwnerUserId}`,\n `password:${hashCacheSecret(input.spacePassword)}`,\n ].join(\"|\");\n}\n\nfunction hashCacheSecret(value: string | null): string {\n if (!value) {\n return \"none\";\n }\n return createHash(\"sha256\").update(value).digest(\"base64url\");\n}\n\nexport function clearDispatchSendTargetReferenceCacheForTests(): void {\n memberDirectoryCache.clear();\n inFlightMemberDirectoryLoads.clear();\n}\n\nfunction buildDispatchSendTargetRequestContext(input: {\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n targetProfileId: string;\n targetProfileName: string | null;\n}): OpenMeldRequestContext {\n return buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n openMeldProfileId: input.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.profileOwnerUserId,\n ...(input.profileOwnerName ? { ownerName: input.profileOwnerName } : {}),\n profileName: normalizeTargetProfileName(input.targetProfileName),\n },\n });\n}\n\nfunction formatDispatchSendTargetReferenceLine(\n target: DispatchSendTargetProjectionEntry\n): string {\n return `${target.primaryMentionLabel} -> ${target.profileId} (${formatAllowedRelations(target)})`;\n}\n\nfunction formatAllowedRelations(\n target: DispatchSendTargetProjectionEntry\n): string {\n const relations: string[] = [];\n if (target.allowedRelations.wake) {\n relations.push(\"wake\");\n }\n if (target.allowedRelations.reference) {\n relations.push(\"reference\");\n }\n if (target.allowedRelations.mention) {\n relations.push(\"mention\");\n }\n return relations.join(\" | \");\n}\n\nfunction normalizeTargetProfileName(value: string | null): string {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : \"unknown\";\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type {\n AdapterComputerFileAccessBoundary,\n AdapterDispatchContextDelta,\n AdapterDispatchExecutionMode,\n AdapterInstructionPrompt,\n AdapterInteractionCallback,\n AdapterInteractionRequest,\n AdapterRuntimeEvent,\n AdapterToolActivityEvent,\n} from \"@openmeld/adapter-core\";\nimport type { RuntimeTaskResult } from \"@openmeld/local-execution\";\nimport {\n appendLedgerHistoryEntry,\n assertLegacyAgentContextAssociation,\n buildAgentContextLookupKey,\n buildRuntimeWorkspaceFingerprint,\n commitResolvedAgentContext,\n DEFAULT_TASK_LIFECYCLE_HEARTBEAT_INTERVAL_MS,\n loadLedgerState,\n resolveConversationExecutionStateByLookupKey,\n runRuntimeTask,\n seedLegacyAgentContext,\n settleInflightTask,\n withLedgerStateTransaction,\n} from \"@openmeld/local-execution\";\nimport {\n createSerialAgentInteractionCallback,\n type DispatchContinuityObservation,\n type InflightTaskControlRegistry,\n type LocalDaemonAdapterContainer,\n type LocalExecutionSlotDiagnostics,\n type LocalExecutionSlots,\n type LocalExecutionSlotTaskResult,\n mergeOpenClawGatewayVisibility as mergeOpenClawGatewayVisibilityInternal,\n normalizeDispatchPostMessageAction,\n normalizeDispatchThreadAction,\n type OpenClawGatewayVisibility,\n type PendingAgentInteractionRegistry,\n resolveCompatibleAgentContextMatch,\n resolveCompatibleConversationExecutionState,\n resolveDispatchContinuityObservation,\n resolveDispatchQueueLogMeta,\n resolveLatestScopedConversationExecutionState,\n syncRuntimeEventToInflightTaskControlRegistry,\n} from \"@openmeld/local-service\";\nimport {\n AGENT_INTERACTION_DEFAULT_TIMEOUT_MS,\n AGENT_INTERACTION_SCHEMA_VERSION,\n agentInteractionRequestSchema,\n runtimeCoordinatorExecutionTokenEnvelopeSchema,\n runtimeTransportDeliverDispatchRequestSchema,\n runtimeTransportDeliveryExecutionIdentitySchema,\n} from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n AgentControllerConversationResumePlan,\n AgentInteractionRequest,\n BootstrapTemplateFacts,\n ConversationExecutionState,\n DispatchExecution,\n ExecutionContextCompletion,\n LocalRuntimeContextPlan,\n OpenMeldDaemonTaskResultPayload,\n ProviderDispatchRuntimeContext,\n RuntimeCoordinatorExecutionTokenEcho,\n RuntimeTransportAgentControllerConversationOccupancy,\n RuntimeTransportDeliverDispatchRequest,\n RuntimeTransportDeliveryExecutionIdentity,\n RuntimeTransportDispatchLocalQueueDiagnostics,\n RuntimeTransportDispatchRuntimeEvidencePhase,\n RuntimeTransportResultIdentityEcho,\n RuntimeTransportRuntimeEvidenceIdentityEcho,\n} from \"@openmeld/schemas/types\";\nimport { resolveSpacePublicationRequirement } from \"@openmeld/space-mesh\";\nimport { recordOpenMeldCreatedLocalAgentSession } from \"../../agent-activity/session-inventory-origin-store\";\nimport { resolveBuiltinAgentControllerDefinition } from \"../../agents/builtin-agent-controller-definitions\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../../config/openmeld-request-context\";\nimport { emitDaemonDispatchJournalEvent } from \"../../local-service/dispatch/daemon-dispatch-journal\";\nimport {\n type DispatchRuntimePreparation,\n prepareDispatchRuntimeExecution,\n resolveDispatchWorkingFolderRuntimeContext,\n} from \"../../local-service/execution/dispatch-runtime-preparation\";\nimport { toTaskExecutionError as toTaskExecutionErrorInternal } from \"../../local-service/execution/task-execution-error\";\nimport { buildDispatchOwnedRuntimeEnv } from \"../../runtime/dispatch-owned-runtime\";\nimport { DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND } from \"../../runtime/dispatch-runtime-env\";\nimport {\n createDispatchSpaceActionContext,\n type DispatchSpaceActionContext,\n type DispatchSpaceActionRecord,\n type DispatchSpaceActionRecordReadResult,\n OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV,\n readDispatchSpaceActionRecord,\n supersedeDispatchSpaceActionRecordForReconsideration,\n} from \"../../runtime/dispatch-space-action-context\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { fetchSpaceMeta } from \"../../space/meta-api\";\nimport { resolveProviderRuntimeDispatchContinuation } from \"../continuation/provider-runtime-continuation\";\nimport {\n resolveRecoveredLedgerConversation,\n resolveWorkingFolderRecovery,\n} from \"../continuation/working-folder-recovery\";\nimport {\n emitRunLine,\n normalizeOptionalText,\n toErrorMessage,\n} from \"../core/logger\";\nimport type {\n CurrentDaemonSocketRef,\n DaemonFrameSink,\n DaemonProfileRouteConfig,\n InflightDispatchMeta,\n LedgerPaths,\n} from \"../core/types\";\nimport { DaemonServiceRunError } from \"../core/types\";\nimport { resolveComputerFileAccessAdmission } from \"../file-access/computer-file-access-admission\";\nimport { applyComputerFileAccessAwareness } from \"../file-access/computer-file-access-prompt\";\nimport { readComputerFileAccessPolicy } from \"../file-access/computer-file-access-store\";\nimport { prepareDispatchWorkHandoff } from \"../file-access/dispatch-work-handoff\";\nimport { probeAgentControllerUsageObservationAuth } from \"../inventory/agent-controller-interface\";\nimport { recordRuntimeProviderUsageLimits } from \"../inventory/runtime-provider-usage-limits\";\nimport {\n buildRuntimeRouteTargets,\n resolveLocalRuntimeControllerSupport,\n} from \"../routing/resolve-controller-support\";\nimport { createLedgerIo } from \"../state/ledger-io\";\nimport {\n attachAgentReplyObservation,\n coordinateDispatchAgentReply,\n type DispatchAgentReplyObservation,\n readDispatchAgentReplyObservation,\n} from \"./dispatch-agent-reply-observation\";\nimport { settleAgentReplyProposals } from \"./dispatch-agent-reply-settlement\";\nimport {\n type DispatchImageAttachmentPreparation,\n downloadDispatchImageAttachment,\n materializeDispatchImageAttachments,\n} from \"./dispatch-image-attachments\";\nimport {\n type DispatchResultOutboxSettlement,\n enqueueDispatchResultOutboxRecord,\n} from \"./dispatch-result-outbox\";\nimport {\n applyDispatchSkillInstructions,\n ensureDispatchControllerOpenMeldSkill,\n} from \"./ensure-dispatch-controller-openmeld-skill\";\nimport {\n markBootstrapInjectedContext as markBootstrapInjectedContextInternal,\n reconcileBootstrapInjectedContextAfterDispatch as reconcileBootstrapInjectedContextAfterDispatchInternal,\n resolveBootstrapPlan as resolveBootstrapPlanInternal,\n rollbackBootstrapExecutionStateAfterDispatchFailure as rollbackBootstrapExecutionStateAfterDispatchFailureInternal,\n} from \"./execute-dispatch-bootstrap-plan\";\nimport {\n areSameAgentControllerConversationRef,\n buildAgentControllerConversationRefFromAgentControllerConversation,\n normalizeOptionalContextId,\n resolveCurrentConversationPolicy,\n resolveDispatchContextDeltaFromRuntimeResult,\n resolveDispatchContextIdForAgentControllerConversation,\n resolveObservedDispatchAgentControllerConversation,\n resolvePlannedAgentControllerConversation,\n} from \"./execute-dispatch-conversation\";\nimport { upsertConversationExecutionStateForLookupKey } from \"./execute-dispatch-conversation-state\";\nimport {\n buildResultDispatchJournalMetadata,\n buildRuntimeObservationPayload,\n emitContinuityWarningIfNeeded,\n emitDispatchLocalPhaseJournalEvent,\n emitProviderRuntimePhaseLine,\n emitRuntimeObservationSummaryLine,\n resolveAdapterTelemetry,\n summarizeTaskResultPayload,\n} from \"./execute-dispatch-observation\";\nimport {\n buildInvalidStructuredActionOutputPreview,\n buildStructuredActionRepairPrompt as buildStructuredActionRepairPromptInternal,\n coerceRuntimeResultToStructuredActionFailure as coerceRuntimeResultToStructuredActionFailureInternal,\n resolveStructuredActionOutputFallback,\n resolveStructuredActionRepairContinuation as resolveStructuredActionRepairContinuationInternal,\n resolveStructuredActionRepairPreviousOutput,\n resolveStructuredActionRequirementFailure as resolveStructuredActionRequirementFailureInternal,\n} from \"./execute-dispatch-structured-action-repair\";\nimport type {\n BootstrapPlan,\n DispatchBootstrapContextPhase,\n DispatchCorrelation,\n DispatchLifecyclePhase,\n DispatchPromptTrace,\n DispatchRejectionPayloadInput,\n DispatchRuntimeCompletion,\n DispatchSendTargetReferenceLoadResult,\n ParsedDispatchTask,\n StructuredActionFailureDiagnostics,\n StructuredActionRepairResult,\n SupportedRuntimeControllerSupport,\n} from \"./execute-dispatch-types\";\nimport {\n captureExecutionContextCompletion,\n executionContextFileAccessBoundary,\n executionContextLedgerPolicy,\n executionContextResourceScope,\n executionContextWorkingDirectory,\n prepareExecutionContextConversation,\n} from \"./execution-context-session\";\nimport {\n type ExecutionContextWorkspace,\n type ExecutionContextWorkspaceUse,\n markExecutionContextWorkspaceInUse,\n prepareExecutionContextWorkspace,\n releaseExecutionContextWorkspace,\n} from \"./execution-context-workspace\";\nimport {\n buildDispatchBootstrapTemplateFacts,\n buildDispatchCorrelation,\n buildDispatchPromptPlan,\n buildDispatchSessionTitle,\n type DispatchPromptPlan,\n parseDispatchTask,\n resolveBootstrapSpaceOwnerProfileId,\n resolveBootstrapTargetProfileContext,\n resolveDispatchMentionSourceContext,\n} from \"./parse-dispatch-task\";\nimport { buildDispatchPromptTrace } from \"./prompt-trace\";\nimport {\n createReasoningStream,\n routeReasoningEvents,\n} from \"./reasoning-stream\";\nimport {\n buildFailedTaskResultPayload,\n resolveDispatchResultPayload,\n sendDispatchInteractionRequestFrame,\n sendDispatchLifecycleFrame,\n sendDispatchPreviewEndFrame,\n sendDispatchPreviewFrame,\n sendDispatchReasoningFrame,\n sendDispatchRuntimeEvidenceFrame,\n sendDispatchToolActivityFrame,\n} from \"./send-dispatch-result\";\nimport { resolveDispatchSendTargetReference } from \"./send-target-reference\";\n\nexport const markBootstrapInjectedContext =\n markBootstrapInjectedContextInternal;\nexport const reconcileBootstrapInjectedContextAfterDispatch =\n reconcileBootstrapInjectedContextAfterDispatchInternal;\nexport const resolveBootstrapPlan = resolveBootstrapPlanInternal;\nexport const rollbackBootstrapExecutionStateAfterDispatchFailure =\n rollbackBootstrapExecutionStateAfterDispatchFailureInternal;\nexport const buildStructuredActionRepairPrompt =\n buildStructuredActionRepairPromptInternal;\nexport const coerceRuntimeResultToStructuredActionFailure =\n coerceRuntimeResultToStructuredActionFailureInternal;\nexport const resolveStructuredActionRepairContinuation =\n resolveStructuredActionRepairContinuationInternal;\nexport const resolveStructuredActionRequirementFailure =\n resolveStructuredActionRequirementFailureInternal;\n\nconst CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS = 25;\nconst CLI_SPACE_ACTION_RECORD_RUNTIME_COMPLETION_GRACE_MS = 1500;\nconst CLI_SPACE_ACTION_PROVIDER_CONVERSATION_GRACE_MS = 1500;\nconst AGENT_CONTROLLER_OCCUPANCY_KEEPALIVE_REASSERT_INTERVALS = 4;\n\n// OPENMELD_SERVICE_THIN_CORE: temporary dispatch execution shell.\n// Keep new local-service execution helpers outside this file. This file still\n// orchestrates delivery intake, runtime preparation, Space Action handling, and\n// result evidence until those slices are split one by one.\nexport function enqueueDispatchDeliverFrame(input: {\n computerFileAccessStorePath: string;\n contextStore: Map<string, string>;\n currentSocketRef?: CurrentDaemonSocketRef;\n daemonSessionId: string;\n localExecutionSlots: LocalExecutionSlots;\n inflightDispatchMetaByTaskId: Map<string, InflightDispatchMeta>;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n payload: Record<string, unknown>;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n requestCurrentWorkingFolderFactRefresh?: () => void;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n}): void {\n // OPENMELD_SERVICE_THIN_CORE: RuntimeCoordinator task intake.\n // The daemon may accept, queue, and execute a token-backed local task, then\n // report evidence. RuntimeCoordinator and Space still own final outcome.\n // OPENMELD_SETUP_TO_WAKE_PATH: HIGHEST_FACT local-service-execution\n // OpenMeld Service carries an accepted Wake to the bound local runtime. It is not\n // the owner of Space truth or final publication.\n const currentSocketRef = input.currentSocketRef ?? {\n connectionGeneration: normalizePositiveInteger(\n input.payload.connectionGeneration\n ),\n socket: input.socket,\n };\n const { pendingAgentInteractionRegistry } = input;\n const parsedDeliver = runtimeTransportDeliverDispatchRequestSchema.safeParse(\n input.payload\n );\n if (!parsedDeliver.success) {\n reportInvalidDeliverRequest({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n issues: parsedDeliver.error.issues,\n ledgerPaths: input.ledgerPaths,\n payload: input.payload,\n presenter: input.presenter,\n });\n return;\n }\n const deliverRequest = parsedDeliver.data;\n const correlation = buildDispatchCorrelation({\n deliverRequest,\n parsedTask: null,\n });\n const parsedQueueTask = parseDispatchTaskForQueue({\n deliverRequest,\n routeByProfileId: input.routeByProfileId,\n });\n const queueLogMeta = resolveDispatchQueueLogMeta({\n parsedTask: parsedQueueTask,\n profileId: deliverRequest.profileId,\n runtimeAdapterId: resolveQueueRuntimeAdapterId({\n localAdapterContainer: input.localAdapterContainer,\n parsedTask: parsedQueueTask,\n }),\n });\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest,\n phase: \"received\",\n presenter: input.presenter,\n });\n const enqueueResult = input.localExecutionSlots.request({\n resourceScope: executionContextResourceScope(\n deliverRequest.payload.executionContext\n ),\n adapterId: queueLogMeta.adapterId,\n attemptId: correlation.attemptId,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n executionTokenRunId: deliverRequest.payload.executionToken?.runId ?? null,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n onQueued: (event) => {\n const localQueue = toRuntimeTransportDispatchLocalQueueDiagnostics(\n event.localQueue\n );\n emitDispatchLifecycleTransition({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: deliverRequest.leaseEpoch,\n localQueue,\n phase: \"accepted_local\",\n presenter: input.presenter,\n executionTokenEcho:\n toRuntimeCoordinatorExecutionTokenEcho(deliverRequest),\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: correlation.taskId,\n });\n return startDispatchLifecycleKeepalive({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: deliverRequest.leaseEpoch,\n localQueue,\n phase: \"accepted_local\",\n presenter: input.presenter,\n executionTokenEcho:\n toRuntimeCoordinatorExecutionTokenEcho(deliverRequest),\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: correlation.taskId,\n });\n },\n profileId: deliverRequest.profileId,\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId ?? null,\n spaceId: queueLogMeta.spaceId,\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n run: async () => {\n return await handleDispatchDeliverFrame({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n contextStore: input.contextStore,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest,\n inflightDispatchMetaByTaskId: input.inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n pendingAgentInteractionRegistry,\n ledgerPaths: input.ledgerPaths,\n leasesByProfileId: input.leasesByProfileId,\n localAdapterContainer: input.localAdapterContainer,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n requestCurrentWorkingFolderFactRefresh:\n input.requestCurrentWorkingFolderFactRefresh,\n presenter: input.presenter,\n routeByProfileId: input.routeByProfileId,\n socket: input.socket,\n });\n },\n });\n function handleRejectedLocalExecutionSlot(\n rejected: Exclude<\n ReturnType<LocalExecutionSlots[\"request\"]>,\n { accepted: true }\n >\n ): void {\n if (rejected.reason === \"service.draining\") {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_deferred\",\n text: `deferred task ${correlation.taskId} because the local service is draining`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n activeForLane: rejected.snapshot.activeForLane,\n activeGlobal: rejected.snapshot.activeGlobal,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n durationMs: null,\n errorCode: \"daemon.service.draining\",\n globalConcurrency: rejected.snapshot.limits.globalConcurrency,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n profileId: deliverRequest.profileId,\n queueDepth: rejected.snapshot.queueDepth,\n queueMax: rejected.snapshot.limits.queueMax,\n result: \"deferred\",\n spaceId: queueLogMeta.spaceId,\n step: \"deferred\",\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n },\n });\n return;\n }\n const queueRejectErrorCode =\n rejected.reason === \"task.owner_conflict\"\n ? \"runtime.task.local_owner_conflict\"\n : \"queue.full\";\n const queueRejectMessage =\n rejected.reason === \"task.owner_conflict\"\n ? `${queueRejectErrorCode}: local task owner conflict for task ${correlation.taskId}; activeOwner=${rejected.activeOwner.dispatchId}/${rejected.activeOwner.attemptId}`\n : `queue.full: local execution slot queue is full (queueMax=${String(rejected.snapshot.limits.queueMax)}, pending=${String(rejected.snapshot.queueDepth)})`;\n const queueRejectPayload = buildFailedTaskResultPayload({\n attemptId: correlation.attemptId,\n agentControllerRef: correlation.agentControllerRef,\n errorCode: queueRejectErrorCode,\n errorMessage: queueRejectMessage,\n errorType:\n rejected.reason === \"task.owner_conflict\" ? \"internal\" : \"policy\",\n localOwnerConflict:\n rejected.reason === \"task.owner_conflict\"\n ? {\n activeAttemptId: rejected.activeOwner.attemptId,\n activeDispatchId: rejected.activeOwner.dispatchId,\n activeExecutionTokenRunId:\n rejected.activeOwner.executionTokenRunId,\n activeRuntimeCoordinatorExecutionId:\n rejected.activeOwner.runtimeCoordinatorExecutionId,\n activeTaskId: rejected.activeOwner.taskId,\n reason: \"task.owner_conflict\",\n rejectedAttemptId: correlation.attemptId,\n rejectedDispatchId: correlation.dispatchId,\n rejectedExecutionTokenRunId:\n deliverRequest.payload.executionToken?.runId ?? null,\n rejectedRuntimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId ?? null,\n rejectedTaskId: correlation.taskId,\n }\n : null,\n sourceEventId: correlation.sourceEventId,\n suppressPublicOutcome: rejected.reason === \"task.owner_conflict\",\n targetProfileId: correlation.targetProfileId,\n taskId: correlation.taskId,\n });\n enqueueDispatchResultOutboxRecord({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n executionIdentityEcho:\n toRuntimeTransportResultIdentityEcho(deliverRequest),\n executionTokenEcho:\n toRuntimeCoordinatorExecutionTokenEcho(deliverRequest),\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: deliverRequest.leaseEpoch,\n payload: queueRejectPayload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: correlation.taskId,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: deliverRequest.leaseEpoch,\n metadata: buildResultDispatchJournalMetadata(queueRejectPayload),\n profileId: deliverRequest.profileId,\n result: queueRejectPayload.status,\n taskId: correlation.taskId,\n type: \"dispatch.result.queued\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_rejected\",\n text: `local execution slot rejected task ${correlation.taskId} for ${queueLogMeta.targetLabel}: ${rejected.reason}`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n activeForLane: rejected.snapshot.activeForLane,\n activeGlobal: rejected.snapshot.activeGlobal,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n durationMs: null,\n errorCode: queueRejectErrorCode,\n globalConcurrency: rejected.snapshot.limits.globalConcurrency,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n profileId: deliverRequest.profileId,\n queueDepth: rejected.snapshot.queueDepth,\n queueMax: rejected.snapshot.limits.queueMax,\n result: \"failed\",\n spaceId: queueLogMeta.spaceId,\n step: \"rejected\",\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n ...(rejected.reason === \"task.owner_conflict\"\n ? {\n activeOwnerAttemptId: rejected.activeOwner.attemptId,\n activeOwnerDispatchId: rejected.activeOwner.dispatchId,\n }\n : {}),\n },\n });\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest,\n phase: \"failed\",\n presenter: input.presenter,\n reasonCode: queueRejectErrorCode,\n });\n }\n if (!enqueueResult.accepted) {\n handleRejectedLocalExecutionSlot(enqueueResult);\n return;\n }\n if (enqueueResult.deduped) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_deduped\",\n text: `local execution slot deduped attempt ${correlation.attemptId} for task ${correlation.taskId}`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n attemptId: correlation.attemptId,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n queueDepth: enqueueResult.snapshot.queueDepth,\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n },\n });\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_accepted\",\n text: `local execution slot accepted task ${correlation.taskId} for ${queueLogMeta.targetLabel}`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n activeForLane: enqueueResult.snapshot.activeForLane,\n activeGlobal: enqueueResult.snapshot.activeGlobal,\n connectionGeneration: deliverRequest.connectionGeneration,\n controllerKey: queueLogMeta.controllerKey,\n deliveryRecoveryReason: deliverRequest.deliveryRecoveryReason ?? null,\n dispatchId: correlation.dispatchId,\n durationMs: null,\n errorCode: null,\n globalConcurrency: enqueueResult.snapshot.limits.globalConcurrency,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n profileId: deliverRequest.profileId,\n queueDepth: enqueueResult.snapshot.queueDepth,\n queueMax: enqueueResult.snapshot.limits.queueMax,\n result: null,\n spaceId: queueLogMeta.spaceId,\n step: \"enqueued\",\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n },\n });\n}\n\nfunction parseDispatchTaskForQueue(input: {\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n}): ParsedDispatchTask | null {\n return parseDispatchTask({\n deliverRequest: input.deliverRequest,\n fallbackRouteConfig:\n input.routeByProfileId.get(input.deliverRequest.profileId) ?? null,\n });\n}\n\nfunction resolveQueueRuntimeAdapterId(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n parsedTask: ParsedDispatchTask | null;\n}): string | null {\n if (!input.parsedTask) {\n return null;\n }\n const support = resolveLocalRuntimeControllerSupport({\n agentControllerRef: input.parsedTask.agentControllerRef,\n localAdapterContainer: input.localAdapterContainer,\n });\n return support.supported === true\n ? support.runtimeAdapterMatch.adapterId\n : null;\n}\n\nfunction reportInvalidDeliverRequest(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n issues: readonly { message: string; path: readonly unknown[] }[];\n ledgerPaths: LedgerPaths;\n payload: Record<string, unknown>;\n presenter: Presenter;\n}): void {\n const identity = resolveInvalidDeliverRequestIdentity({\n fallbackDaemonSessionId: input.daemonSessionId,\n payload: input.payload,\n });\n const issues = summarizeDeliverParseIssues(input.issues);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.deliver_payload_invalid\",\n text: `deliver payload rejected before queueing for dispatch ${identity?.dispatchId ?? \"unknown\"}`,\n payload: {\n dispatchId: identity?.dispatchId ?? null,\n issues,\n result: \"failed\",\n taskId: identity?.taskId ?? null,\n },\n });\n\n if (!identity) {\n return;\n }\n\n const resultPayload = buildFailedTaskResultPayload({\n attemptId: identity.attemptId,\n agentControllerRef: identity.agentControllerRef,\n errorCode: \"schema.invalid\",\n errorMessage: buildInvalidDeliverRequestErrorMessage(issues),\n errorType: \"config\",\n sourceEventId: identity.sourceEventId,\n targetProfileId: identity.targetProfileId,\n taskId: identity.taskId,\n });\n try {\n enqueueDispatchResultOutboxRecord({\n attemptId: identity.attemptId,\n connectionGeneration: identity.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: identity.dispatchId,\n executionIdentityEcho: identity.executionIdentityEcho,\n executionTokenEcho: identity.executionTokenEcho,\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: identity.leaseEpoch,\n payload: resultPayload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId: identity.runtimeCoordinatorExecutionId,\n taskId: identity.taskId,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: identity.attemptId,\n connectionGeneration: identity.connectionGeneration,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: identity.dispatchId,\n leaseEpoch: identity.leaseEpoch,\n metadata: {\n ...buildResultDispatchJournalMetadata(resultPayload),\n parseIssues: issues,\n },\n profileId: identity.targetProfileId,\n result: resultPayload.status,\n taskId: identity.taskId,\n type: \"dispatch.result.queued\",\n });\n } catch (error) {\n emitDaemonDispatchJournalEvent({\n attemptId: identity.attemptId,\n connectionGeneration: identity.connectionGeneration,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: identity.dispatchId,\n leaseEpoch: identity.leaseEpoch,\n metadata: {\n ...buildResultDispatchJournalMetadata(resultPayload),\n errorMessage: toErrorMessage(error),\n parseIssues: issues,\n },\n profileId: identity.targetProfileId,\n result: resultPayload.status,\n taskId: identity.taskId,\n type: \"dispatch.result.send_failed\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.invalid_deliver_result_send_failed\",\n text: `failed to send invalid deliver result for dispatch ${identity.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n dispatchId: identity.dispatchId,\n errorMessage: toErrorMessage(error),\n result: \"failed\",\n taskId: identity.taskId,\n },\n });\n }\n}\n\nfunction resolveInvalidDeliverRequestIdentity(input: {\n fallbackDaemonSessionId: string;\n payload: Record<string, unknown>;\n}): {\n attemptId: string;\n connectionGeneration: number;\n agentControllerRef: string | null;\n daemonSessionId: string;\n dispatchId: string;\n executionIdentityEcho: RuntimeTransportResultIdentityEcho;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n runtimeCoordinatorExecutionId: string | null;\n sourceEventId: string;\n targetProfileId: string;\n taskId: string;\n} | null {\n const taskPayload = toRecord(input.payload.payload);\n const controllerSnapshot = toRecord(taskPayload?.controllerSnapshot);\n const executionIdentity =\n runtimeTransportDeliveryExecutionIdentitySchema.safeParse(\n taskPayload?.executionIdentity\n );\n const attemptId =\n normalizeOptionalText(input.payload.attemptId) ??\n normalizeOptionalText(taskPayload?.attemptId);\n const connectionGeneration = normalizePositiveInteger(\n input.payload.connectionGeneration\n );\n const daemonSessionId =\n normalizeOptionalText(input.payload.daemonSessionId) ??\n input.fallbackDaemonSessionId;\n const dispatchId =\n normalizeOptionalText(input.payload.dispatchId) ??\n normalizeOptionalText(taskPayload?.dispatchId);\n const leaseEpoch = normalizePositiveInteger(input.payload.leaseEpoch);\n const sourceEventId = normalizeOptionalText(taskPayload?.sourceEventId);\n const targetProfileId =\n normalizeOptionalText(taskPayload?.targetProfileId) ??\n normalizeOptionalText(input.payload.profileId);\n const taskId = normalizeOptionalText(taskPayload?.taskId);\n const runtimeCoordinatorExecutionId = normalizeOptionalText(\n taskPayload?.runtimeCoordinatorExecutionId\n );\n const executionTokenEcho = resolveRuntimeCoordinatorExecutionTokenEchoFromRaw(\n taskPayload?.executionToken\n );\n\n if (\n !(\n attemptId &&\n connectionGeneration &&\n daemonSessionId &&\n dispatchId &&\n executionIdentity.success &&\n leaseEpoch &&\n sourceEventId &&\n targetProfileId &&\n taskId\n )\n ) {\n return null;\n }\n\n return {\n attemptId,\n connectionGeneration,\n agentControllerRef:\n normalizeOptionalText(controllerSnapshot?.agentControllerRef) ?? null,\n daemonSessionId,\n dispatchId,\n executionIdentityEcho:\n toRuntimeTransportResultIdentityEchoFromDeliveryIdentity(\n executionIdentity.data\n ),\n executionTokenEcho,\n leaseEpoch,\n runtimeCoordinatorExecutionId,\n sourceEventId,\n targetProfileId,\n taskId,\n };\n}\n\nfunction summarizeDeliverParseIssues(\n issues: readonly { message: string; path: readonly unknown[] }[]\n): Array<{ message: string; path: string }> {\n return issues.slice(0, 8).map((issue) => ({\n message: issue.message,\n path: issue.path.map((part) => String(part)).join(\".\"),\n }));\n}\n\nfunction buildInvalidDeliverRequestErrorMessage(\n issues: readonly { message: string; path: string }[]\n): string {\n const firstIssue = issues[0];\n if (!firstIssue) {\n return \"schema.invalid: daemon deliver payload is invalid\";\n }\n const path = firstIssue.path || \"payload\";\n return `schema.invalid: daemon deliver payload is invalid at ${path}: ${firstIssue.message}`;\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\nfunction normalizePositiveInteger(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0\n ? value\n : null;\n}\n\nexport async function handleDispatchDeliverFrame(input: {\n computerFileAccessStorePath: string;\n contextStore: Map<string, string>;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n inflightDispatchMetaByTaskId: Map<string, InflightDispatchMeta>;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n requestCurrentWorkingFolderFactRefresh?: () => void;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n}): Promise<LocalExecutionSlotTaskResult> {\n const { currentSocketRef } = input;\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n source: \"local_execution_slot_task\",\n },\n parsedTask: null,\n phase: \"task_started\",\n result: \"started\",\n });\n const validatedDispatchInput = resolveValidatedDispatchDeliveryInput({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n leasesByProfileId: input.leasesByProfileId,\n localAdapterContainer: input.localAdapterContainer,\n presenter: input.presenter,\n routeByProfileId: input.routeByProfileId,\n socket: input.socket,\n });\n if (validatedDispatchInput.status === \"rejected\") {\n return validatedDispatchInput.result;\n }\n const { parsedTask, routeConfig, runtimeControllerSupport } =\n validatedDispatchInput;\n const unsupportedControllerResult = maybeRejectUnsupportedController({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n presenter: input.presenter,\n runtimeControllerSupport,\n socket: input.socket,\n });\n if (unsupportedControllerResult) {\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n parsedTask,\n phase: \"failed\",\n presenter: input.presenter,\n reasonCode: \"controller.kind.unsupported\",\n });\n return unsupportedControllerResult;\n }\n assertSupportedRuntimeControllerSupport(runtimeControllerSupport);\n const { pendingAgentInteractionRegistry } = input;\n const onInteractionRequest: AdapterInteractionCallback =\n createSerialAgentInteractionCallback(\n async (request) =>\n await requestDispatchAgentInteraction({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n parsedTask,\n pendingAgentInteractionRegistry,\n presenter: input.presenter,\n request,\n leasesByProfileId: input.leasesByProfileId,\n })\n );\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerRef: parsedTask.agentControllerRef,\n source: \"dispatch_preflight\",\n streamingMode: parsedTask.streamingMode,\n transportMode: parsedTask.transportMode,\n },\n parsedTask,\n phase: \"preflight_ready\",\n result: \"ready\",\n });\n\n let resultPayload: OpenMeldDaemonTaskResultPayload;\n let continuityObservation: DispatchContinuityObservation | null = null;\n let dispatchExecution: DispatchExecution | null = null;\n let resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n let resolvedSpaceActionProvenance:\n | OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"]\n | undefined;\n let contextLookupKey = \"\";\n let currentExecutionState: ConversationExecutionState | null = null;\n let existingContextId: string | null = null;\n let latestScopedExecutionState: ConversationExecutionState | null = null;\n let ledgerIo: ReturnType<typeof createLedgerIo> | null = null;\n const currentConversationPolicy =\n resolveCurrentConversationPolicy(routeConfig);\n const bootstrapContext = await resolveDispatchBootstrapContext({\n onPhase: (phase, metadata) => {\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata,\n parsedTask,\n phase,\n result: \"ready\",\n });\n },\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n parsedTask,\n });\n let localRuntimeContextPlan: LocalRuntimeContextPlan | null = null;\n let agentControllerConversationResumePlan: AgentControllerConversationResumePlan | null =\n null;\n let contextIdForDispatch: string | null = null;\n let effectiveAgentControllerConversationId: string | null = null;\n let bootstrapPlan: BootstrapPlan | null = null;\n let plannedAgentControllerConversation: AgentControllerConversationRef | null =\n null;\n let observedProviderConversationId: string | null = null;\n let observedProviderConversation: AgentControllerConversationRef | null =\n null;\n let runtimePromptPlan: DispatchPromptPlan | null = null;\n let runtimePromptTrace: DispatchPromptTrace | null = null;\n let settledResultSummary: LocalExecutionSlotTaskResult | null = null;\n const providerAdmissionOwnsRunningLifecycle =\n resolveBuiltinAgentControllerDefinition(\n runtimeControllerSupport.runtimeAdapterMatch.agentId\n )?.conversationOccupancy.mode ===\n \"official_atomic_admission_and_release_signal\";\n let runtimeLifecyclePhase: Extract<\n DispatchLifecyclePhase,\n \"accepted_local\" | \"running\"\n > = resolveInitialDispatchLifecyclePhase({\n providerAdmissionOwnsRunningLifecycle,\n });\n const lifecycleKeepalive = {\n stop: null as (() => void) | null,\n };\n let firstOutputEvidenceSent = false;\n input.inflightTaskControlRegistry.registerTask({\n adapterId: runtimeControllerSupport.runtimeAdapterMatch.adapterId,\n agentControllerPermissionMode:\n routeConfig?.agentControllerPermissionMode ?? null,\n dispatchId: parsedTask.dispatchId,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n const runtimeStartedAtMs = Date.now();\n let agentToolActivitySequence = 0;\n let firstReasoningMs: number | undefined;\n const sendReasoning = (\n thinkingSnapshot: string,\n observedAtMs: number,\n status: \"streaming\" | \"waiting\" | \"disabled\" = \"streaming\"\n ) => {\n const socket = currentSocketRef.socket;\n if (\n runtimeControllerSupport.runtimeAdapterMatch.adapterId === \"openclaw\" ||\n !socket ||\n currentSocketRef.reasoningStreamEnabled === undefined ||\n (status === \"streaming\" && (socket.bufferedAmount ?? 0) > 64 * 1024)\n ) {\n return;\n }\n try {\n sendDispatchReasoningFrame({\n socket,\n thinkingSnapshot,\n observedAtMs,\n reasoningState: {\n status,\n ...(firstReasoningMs !== undefined\n ? { firstOutputMs: firstReasoningMs }\n : {}),\n },\n sequence: ++agentToolActivitySequence,\n attemptId: parsedTask.attemptId,\n dispatchId: parsedTask.dispatchId,\n daemonSessionId: input.daemonSessionId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef,\n fallbackConnectionGeneration:\n input.deliverRequest.connectionGeneration,\n }),\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n sourceSignalId: parsedTask.sourceEventId,\n spaceId: parsedTask.spaceId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n } catch {\n // Live delivery is best effort; never log its content or fail the run.\n }\n };\n const reasoningStream = createReasoningStream({\n enabled: () =>\n currentSocketRef.reasoningStreamEnabled === true &&\n currentSocketRef.socket !== null,\n send: sendReasoning,\n });\n const clearReasoning = () => {\n reasoningStream.clear();\n sendReasoning(\n \"\",\n Date.now(),\n currentSocketRef.reasoningStreamEnabled ? \"waiting\" : \"disabled\"\n );\n };\n currentSocketRef.reasoningPreferenceListeners ??= new Set();\n currentSocketRef.reasoningPreferenceListeners.add(clearReasoning);\n const observeReasoning = (\n event: Extract<AdapterRuntimeEvent, { phase: \"reasoning\" }>\n ) => {\n if (firstReasoningMs === undefined && event.text.length > 0) {\n firstReasoningMs = Math.max(0, event.tsMs - runtimeStartedAtMs);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.reasoning_first_output\",\n text: \"Local Agent produced its first reasoning output.\",\n payload: {\n dispatchId: parsedTask.dispatchId,\n firstOutputMs: firstReasoningMs,\n },\n });\n }\n reasoningStream.observe(event);\n };\n const daemonWorkingDirectory = process.cwd();\n let dispatchRuntimeContext: ProviderDispatchRuntimeContext | null = null;\n let effectiveRuntimeContext: ProviderDispatchRuntimeContext | null = null;\n let runtimeEnvOverrides: Record<string, string | undefined> | undefined;\n let runtimeOpenClawGatewayVisibility: OpenClawGatewayVisibility | null = null;\n let computerFileAccessBoundary: AdapterComputerFileAccessBoundary | null =\n null;\n let runtimeOpenClawBinding:\n | OpenMeldDaemonTaskResultPayload[\"openClawBinding\"]\n | undefined;\n let agentControllerConversationOverride:\n | OpenMeldDaemonTaskResultPayload[\"agentControllerConversation\"]\n | null = null;\n let dispatchSpaceActionContext: DispatchSpaceActionContext | null = null;\n let nativeQuiescence: Promise<void> | undefined;\n let workspaceUse: ExecutionContextWorkspaceUse | null = null;\n const workspaceProcesses = new Map<number | null, boolean>();\n const observeWorkspaceProcess = (event: AdapterRuntimeEvent) =>\n observeExecutionContextWorkspaceProcess(workspaceProcesses, event);\n let completedTurnId: string | null = null;\n let completedTurnConversationId: string | null = null;\n let completedNativeResult: RuntimeTaskResult | null = null;\n let executionContextCompletion: ExecutionContextCompletion | undefined;\n const invalidStateStrategy = executionContextLedgerPolicy(\n parsedTask.executionContext\n );\n\n try {\n await currentSocketRef.confirmExecutionAdmission?.(input.deliverRequest);\n dispatchRuntimeContext = await resolveDispatchWorkingFolderRuntimeContext({\n controllerSnapshot: input.deliverRequest.payload.controllerSnapshot,\n defaultProjectId: parsedTask.defaultProjectId,\n defaultProjectIdWasProvided: Object.hasOwn(\n input.deliverRequest.payload,\n \"defaultProjectId\"\n ),\n executionIdentity: parsedTask.executionIdentity,\n onCurrentWorkingFolderFactRejected:\n input.requestCurrentWorkingFolderFactRefresh,\n routeConfig,\n targetProfileId: parsedTask.targetProfileId,\n });\n const folderRecovery = await resolveWorkingFolderRecovery({\n agentControllerRef: parsedTask.agentControllerRef,\n nativeSessionId: parsedTask.agentControllerConversationId,\n hasExecutionContext: Boolean(parsedTask.executionContext),\n workingDirectory: dispatchRuntimeContext.providerRuntimeWorkingDirectory,\n policy: await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n ),\n onInteractionRequest,\n });\n dispatchRuntimeContext = {\n providerRuntimeWorkingDirectory: folderRecovery.workingDirectory,\n };\n await currentSocketRef.confirmExecutionAdmission?.(input.deliverRequest);\n const skillPreflight = await ensureDispatchControllerOpenMeldSkill({\n agentControllerRef: parsedTask.agentControllerRef,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.skill_preflight\",\n text: \"OpenMeld Skill checked for this local agent\",\n payload: {\n agentId: skillPreflight.agentId,\n status: skillPreflight.status,\n reason: skillPreflight.reason,\n },\n });\n const runtimePreparation = await prepareDispatchRuntimeExecution({\n agentControllerRef: parsedTask.agentControllerRef,\n daemonWorkingDirectory,\n dispatchRuntimeContext,\n profileName: bootstrapContext.targetProfileName,\n targetProfileId: parsedTask.targetProfileId,\n });\n effectiveRuntimeContext = runtimePreparation.effectiveRuntimeContext;\n const originalWorkingDirectory =\n effectiveRuntimeContext.providerRuntimeWorkingDirectory;\n await verifyDispatchLegacyContextAssociation({\n parsedTask,\n ledgerPaths: input.ledgerPaths,\n originalWorkingDirectory,\n });\n const taskWorkspace = await prepareDispatchTaskWorkspace({\n parsedTask,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n currentWorkingDirectory: originalWorkingDirectory,\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n });\n const handoffWorkingDirectory = await prepareDispatchWorkHandoff({\n task: parsedTask,\n ownerUserId: input.profileOwnerUserId,\n workingDirectory: taskWorkspace.workingDirectory,\n });\n effectiveRuntimeContext = {\n providerRuntimeWorkingDirectory: handoffWorkingDirectory,\n };\n runtimePreparation.effectiveRuntimeContext = effectiveRuntimeContext;\n computerFileAccessBoundary = await resolveDispatchComputerFileAccess({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n onInteractionRequest,\n parsedTask,\n presenter: input.presenter,\n routeConfig,\n runtimeControllerSupport,\n runtimePreparation,\n taskWorkspace,\n });\n // First real consumer of the send target reference: the network load has\n // been running concurrently with the local runtime preparation above.\n const [sendTargetReference, imageAttachmentPreparation] = await Promise.all(\n [\n bootstrapContext.sendTargetReferencePromise,\n materializeDispatchImageAttachments({\n agentControllerRef: parsedTask.agentControllerRef,\n attachments: parsedTask.attachments,\n downloadAttachment: ({ attachmentId, spaceId }) =>\n downloadDispatchImageAttachment({\n attachmentId,\n ownerName: input.profileOwnerName,\n ownerUserId: input.profileOwnerUserId,\n spaceId,\n spacePassword: parsedTask.spacePassword,\n targetProfileId: parsedTask.targetProfileId,\n targetProfileName: bootstrapContext.targetProfileName,\n }),\n providerRuntimeWorkingDirectory:\n effectiveRuntimeContext.providerRuntimeWorkingDirectory,\n spaceId: parsedTask.spaceId,\n taskId: parsedTask.taskId,\n }),\n ]\n );\n emitSendTargetReferenceLoadFailureIfNeeded({\n parsedTask,\n presenter: input.presenter,\n sendTargetReference,\n });\n emitDispatchImageAttachmentPreparation({\n parsedTask,\n preparation: imageAttachmentPreparation,\n presenter: input.presenter,\n });\n const spaceActionRuntimeContext = createDispatchSpaceActionRuntimeContext({\n bootstrapContext,\n parsedTask,\n runtimePreparation,\n sendTargetReference,\n });\n dispatchSpaceActionContext =\n spaceActionRuntimeContext.dispatchSpaceActionContext;\n runtimeEnvOverrides = spaceActionRuntimeContext.runtimeEnvOverrides;\n runtimeOpenClawGatewayVisibility =\n runtimePreparation.runtimeOpenClawGatewayVisibility;\n const activeRuntimeContext = effectiveRuntimeContext;\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerRef: parsedTask.agentControllerRef,\n providerRuntimePreparationKind:\n runtimePreparation.runtimePreparationDetails.kind,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n source: \"dispatch_runtime_context\",\n },\n parsedTask,\n phase: \"runtime_context_ready\",\n result: \"ready\",\n });\n const dispatchLedgerContext = await loadDispatchLedgerContext({\n contextStore: input.contextStore,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n originalWorkingDirectory,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n });\n contextLookupKey = dispatchLedgerContext.contextLookupKey;\n const recoveredConversation = resolveRecoveredLedgerConversation({\n startNewConversation: folderRecovery.startNewConversation,\n bindingConversationId: parsedTask.agentControllerConversationId,\n currentExecutionState: dispatchLedgerContext.currentExecutionState,\n existingContextId: dispatchLedgerContext.existingContextId,\n });\n currentExecutionState = recoveredConversation.currentExecutionState;\n existingContextId = recoveredConversation.existingContextId;\n effectiveAgentControllerConversationId =\n resolveEffectiveAgentControllerConversationId({\n agentControllerConversationId:\n recoveredConversation.bindingConversationId,\n existingContextId,\n });\n workspaceUse = await markExecutionContextWorkspaceInUse({\n context: parsedTask.executionContext,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n });\n runtimeEnvOverrides = {\n ...runtimeEnvOverrides,\n OPENMELD_PROCESS_SUPERVISION_ID: workspaceUse?.processSupervisionId,\n };\n effectiveAgentControllerConversationId =\n await prepareExecutionContextConversation({\n computerFileAccessBoundary,\n unscopedNativeConversationId: effectiveAgentControllerConversationId,\n context: parsedTask.executionContext,\n currentWorkingDirectory: originalWorkingDirectory,\n workingDirectory: activeRuntimeContext.providerRuntimeWorkingDirectory,\n existingNativeConversationId: existingContextId,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n agentControllerRef: parsedTask.agentControllerRef,\n launchContract: routeConfig?.launchContract,\n onRuntimeEvent: observeWorkspaceProcess,\n processSupervisionId: workspaceUse?.processSupervisionId,\n });\n latestScopedExecutionState =\n dispatchLedgerContext.latestScopedExecutionState;\n ledgerIo = dispatchLedgerContext.ledgerIo;\n input.inflightDispatchMetaByTaskId.set(parsedTask.taskId, {\n agentContextLookupKey: contextLookupKey,\n });\n const runtimeContinuation = resolveProviderRuntimeDispatchContinuation({\n agentControllerConversationId: effectiveAgentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n currentPolicy: currentConversationPolicy,\n existingContextId,\n executionState: currentExecutionState,\n latestKnownRuntimeWorkspaceFingerprint:\n latestScopedExecutionState?.runtimeWorkspaceFingerprint ?? null,\n runtimeContext: activeRuntimeContext,\n runtimePreparationDetails: runtimePreparation.runtimePreparationDetails,\n spaceId: parsedTask.spaceId,\n spaceNameSnapshot: parsedTask.spaceNameSnapshot,\n transportMode: parsedTask.transportMode,\n });\n localRuntimeContextPlan = runtimeContinuation.localRuntimeContextPlan;\n agentControllerConversationResumePlan =\n runtimeContinuation.agentControllerConversationResumePlan;\n runtimeOpenClawBinding =\n runtimeContinuation.taskResultProviderFacts.openClawBinding;\n contextIdForDispatch =\n resolveDispatchContextIdForAgentControllerConversation({\n agentControllerConversationId: effectiveAgentControllerConversationId,\n agentControllerConversationOverride:\n runtimeContinuation.agentControllerConversationOverride,\n agentControllerConversationResumePlan,\n });\n plannedAgentControllerConversation =\n resolvePlannedAgentControllerConversation({\n agentControllerConversationId: contextIdForDispatch,\n agentControllerRef: parsedTask.agentControllerRef,\n });\n observedProviderConversationId = contextIdForDispatch;\n observedProviderConversation = plannedAgentControllerConversation;\n bootstrapPlan = resolveBootstrapPlan({\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n executionState: currentExecutionState,\n localRuntimeContextPlan,\n nowMs: Date.now(),\n });\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n bootstrapReason: bootstrapPlan.reason,\n bootstrapShouldInject: bootstrapPlan.shouldInject,\n existingContextPresent: existingContextId !== null,\n localRuntimeContextStatus: localRuntimeContextPlan.status,\n source: \"dispatch_ledger_context\",\n agentControllerConversationResumeStatus:\n agentControllerConversationResumePlan.status,\n },\n parsedTask,\n phase: \"ledger_context_ready\",\n result: \"ready\",\n });\n const baseRuntimePromptPlan = applyDispatchSkillInstructions(\n buildDispatchRuntimePrompt({\n bootstrapContext,\n imageAttachmentPreparation,\n parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n sendTargetReference,\n shouldInjectBootstrap: bootstrapPlan.shouldInject,\n taskWorkspace,\n }),\n skillPreflight\n );\n runtimePromptPlan = computerFileAccessBoundary\n ? applyComputerFileAccessAwareness({\n policy: computerFileAccessBoundary,\n promptPlan: baseRuntimePromptPlan,\n })\n : baseRuntimePromptPlan;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.bootstrap_context\",\n text: `bootstrap context prepared for ${parsedTask.spaceId}/${parsedTask.targetProfileId}`,\n payload: {\n activationTargetCount:\n parsedTask.sourceMessageEnvelope?.activationTargets.length ?? 0,\n dispatchId: parsedTask.dispatchId,\n dispatchTriggerSource: parsedTask.dispatchTriggerSource,\n messageEnvelopePresent: parsedTask.sourceMessageEnvelope !== null,\n referenceTargetCount:\n parsedTask.sourceMessageEnvelope?.referenceTargets.length ?? 0,\n sourceEventId: parsedTask.sourceEventId,\n targetProfileId: parsedTask.targetProfileId,\n },\n });\n runtimePromptTrace = buildDispatchPromptTrace({\n prompt: runtimePromptPlan.fallbackPrompt,\n protectedInformation: parsedTask.organizationProtectedInformation,\n });\n await prepareBootstrapExecutionStateIfNeeded({\n bootstrapPlan,\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n contextIdForDispatch,\n contextLookupKey,\n currentExecutionState,\n effectiveRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n presenter: input.presenter,\n });\n agentControllerConversationOverride =\n runtimeContinuation.agentControllerConversationOverride;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_started\",\n text: `runtime started for task ${parsedTask.taskId}`,\n payload: {\n attemptId: parsedTask.attemptId,\n agentControllerRef: parsedTask.agentControllerRef,\n deliveryRecoveryReason: parsedTask.deliveryRecoveryReason,\n dispatchId: parsedTask.dispatchId,\n existingContextId: contextIdForDispatch,\n localRuntimeContextReason: localRuntimeContextPlan.reason,\n localRuntimeContextStatus: localRuntimeContextPlan.status,\n daemonWorkingDirectory,\n providerRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n spaceId: parsedTask.spaceId,\n streamingMode: parsedTask.streamingMode,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n transportMode: parsedTask.transportMode,\n agentControllerConversationResumeStatus:\n agentControllerConversationResumePlan.status,\n ...(agentControllerConversationResumePlan.status === \"blocked\"\n ? {\n agentControllerConversationResumeReason:\n agentControllerConversationResumePlan.reason,\n }\n : {}),\n },\n });\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n parsedTask,\n phase: \"runtime_started\",\n presenter: input.presenter,\n });\n const transitionDispatchLifecycle = (inputLifecycle: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n phase: Extract<DispatchLifecyclePhase, \"accepted_local\" | \"running\">;\n }): void => {\n runtimeLifecyclePhase = inputLifecycle.phase;\n lifecycleKeepalive.stop?.();\n emitDispatchLifecycleTransition({\n agentControllerConversationOccupancy:\n inputLifecycle.agentControllerConversationOccupancy ?? null,\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n phase: runtimeLifecyclePhase,\n presenter: input.presenter,\n executionTokenEcho: parsedTask.executionTokenEcho,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n taskId: parsedTask.taskId,\n });\n lifecycleKeepalive.stop = startDispatchLifecycleKeepalive({\n agentControllerConversationOccupancy:\n inputLifecycle.agentControllerConversationOccupancy ?? null,\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n phase: runtimeLifecyclePhase,\n presenter: input.presenter,\n executionTokenEcho: parsedTask.executionTokenEcho,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n taskId: parsedTask.taskId,\n });\n };\n transitionDispatchLifecycle({ phase: runtimeLifecyclePhase });\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerRef: parsedTask.agentControllerRef,\n localRuntimeContextStatus: localRuntimeContextPlan.status,\n streamingMode: parsedTask.streamingMode,\n transportMode: parsedTask.transportMode,\n agentControllerConversationResumeStatus:\n agentControllerConversationResumePlan.status,\n },\n parsedTask,\n phase: \"runtime_invocation_started\",\n result: \"started\",\n });\n const providerConversationLedgerIo = ledgerIo;\n if (!providerConversationLedgerIo) {\n throw new DaemonServiceRunError({\n code: \"dispatch.ledger.unavailable\",\n message:\n \"dispatch.ledger.unavailable: dispatch ledger is not initialized\",\n });\n }\n let recordedOpenMeldCreatedSessionId: string | null = null;\n const recordProviderConversationObservation = (observation: {\n agentControllerConversationId: string | null | undefined;\n agentControllerConversation?: AgentControllerConversationRef | null;\n source: \"runtime_event\" | \"runtime_result\";\n }): string | null => {\n const agentControllerConversationId = normalizeOptionalContextId(\n observation.agentControllerConversationId\n );\n if (!agentControllerConversationId) {\n return null;\n }\n const agentControllerConversation =\n observation.agentControllerConversation ??\n buildAgentControllerConversationRefFromAgentControllerConversation({\n agentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n });\n observedProviderConversationId = agentControllerConversationId;\n observedProviderConversation = agentControllerConversation;\n if (\n contextIdForDispatch === null &&\n recordedOpenMeldCreatedSessionId !== agentControllerConversationId\n ) {\n recordedOpenMeldCreatedSessionId = agentControllerConversationId;\n recordOpenMeldCreatedLocalAgentSession({\n agentControllerRef: parsedTask.agentControllerRef,\n nativeSessionId: agentControllerConversationId,\n }).catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.session_inventory_origin_record_failed\",\n text: `Session Inventory origin could not be recorded for task ${parsedTask.taskId}`,\n payload: {\n dispatchId: parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n });\n }\n const persistProviderConversationObservation = withLedgerStateTransaction(\n {\n invalidStateStrategy,\n io: providerConversationLedgerIo,\n mutate: (state) => ({\n nextState: commitResolvedAgentContext({\n state,\n agentContextLookupKey: contextLookupKey,\n agentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n spaceId: parsedTask.spaceId,\n targetProfileId: parsedTask.targetProfileId,\n transportMode: parsedTask.transportMode,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n taskId: parsedTask.taskId,\n nowMs: Date.now(),\n }),\n value: undefined,\n }),\n paths: input.ledgerPaths,\n }\n );\n persistProviderConversationObservation.catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_conversation_observation_ignored\",\n text: `provider conversation observation could not be persisted for task ${parsedTask.taskId}`,\n payload: {\n dispatchId: parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n source: observation.source,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n });\n return agentControllerConversationId;\n };\n let usageObservationAuthPromise: ReturnType<\n typeof probeAgentControllerUsageObservationAuth\n > | null = null;\n const syncAgentControllerConversationOccupancyLifecycle = (\n event: AdapterRuntimeEvent\n ) => {\n if (\n event.phase !== \"agent_controller_conversation_available\" &&\n event.phase !== \"agent_controller_conversation_occupied\"\n ) {\n return;\n }\n const occupancy = {\n agentControllerConversationId: event.agentControllerConversationId,\n contractVersion: event.contractVersion,\n state:\n event.phase === \"agent_controller_conversation_occupied\"\n ? (\"occupied\" as const)\n : (\"available\" as const),\n } satisfies RuntimeTransportAgentControllerConversationOccupancy;\n transitionDispatchLifecycle({\n agentControllerConversationOccupancy: occupancy,\n phase: runtimeLifecyclePhase,\n });\n };\n const syncProviderTurnAcceptedLifecycle = (\n event: AdapterRuntimeEvent\n ): void => {\n if (event.phase !== \"provider_turn_accepted\") {\n return;\n }\n completedTurnId = event.turnId;\n completedTurnConversationId = event.agentControllerConversationId;\n if (\n providerAdmissionOwnsRunningLifecycle &&\n runtimeLifecyclePhase !== \"running\"\n ) {\n transitionDispatchLifecycle({ phase: \"running\" });\n }\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerConversationId: event.agentControllerConversationId,\n turnId: event.turnId,\n },\n parsedTask,\n phase: \"provider_turn_accepted\",\n result: \"accepted\",\n });\n };\n const onNativeTurnStarted = async () => {\n await currentSocketRef.confirmExecutionAdmission?.(input.deliverRequest);\n completedTurnId = null;\n completedTurnConversationId = null;\n executionContextCompletion = undefined;\n completedNativeResult = null;\n };\n const onNativeTurnCompleted = (result: RuntimeTaskResult) => {\n completedNativeResult = result;\n };\n const onRuntimeEvent = routeReasoningEvents(observeReasoning, (event) => {\n observeWorkspaceProcess(event);\n syncAgentControllerConversationOccupancyLifecycle(event);\n syncProviderTurnAcceptedLifecycle(event);\n if (event.phase === \"tool_activity\") {\n agentToolActivitySequence += 1;\n emitDispatchAgentToolActivityFrame({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n event,\n parsedTask,\n presenter: input.presenter,\n sequence: agentToolActivitySequence,\n });\n }\n if (event.phase === \"provider_conversation_observed\") {\n recordProviderConversationObservation({\n agentControllerConversation:\n event.agentControllerConversation ?? null,\n agentControllerConversationId: event.agentControllerConversationId,\n source: \"runtime_event\",\n });\n }\n if (\n event.phase === \"provider_usage_limits_observed\" &&\n routeConfig?.launchContract\n ) {\n const agentId = runtimeControllerSupport.runtimeAdapterMatch.adapterId;\n const launchContract = routeConfig.launchContract;\n usageObservationAuthPromise ??=\n probeAgentControllerUsageObservationAuth({\n agentId,\n launchContract,\n });\n const recordUsageLimits = usageObservationAuthPromise.then(\n (authSnapshot) =>\n recordRuntimeProviderUsageLimits({\n agentId,\n authSnapshot,\n launchContract,\n usageLimits: event.usageLimits,\n })\n );\n recordUsageLimits\n .then((retained) => {\n if (retained) {\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_usage_limits_observation_ignored\",\n text: `provider usage limit observation could not be retained for task ${parsedTask.taskId}`,\n payload: {\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n observedLimitKeys: event.usageLimits.map((limit) => limit.key),\n reasonCode: \"provider_account_unconfirmed\",\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_usage_limits_observation_ignored\",\n text: `provider usage limit observation could not be retained for task ${parsedTask.taskId}`,\n payload: {\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n observedLimitKeys: event.usageLimits.map((limit) => limit.key),\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n });\n }\n if (\n !firstOutputEvidenceSent &&\n (event.phase === \"first_stdout\" || event.phase === \"first_stderr\")\n ) {\n firstOutputEvidenceSent = true;\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n durationMs: Math.max(0, event.tsMs - runtimeStartedAtMs),\n parsedTask,\n phase: \"first_output\",\n presenter: input.presenter,\n });\n }\n const controlRegistrySyncResult =\n syncRuntimeEventToInflightTaskControlRegistry({\n event,\n registry: input.inflightTaskControlRegistry,\n taskId: parsedTask.taskId,\n });\n if (controlRegistrySyncResult.updated) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_registry_synced\",\n text: `control registry synced for task ${parsedTask.taskId}`,\n payload: {\n dispatchId: parsedTask.dispatchId,\n phase: event.phase,\n processId: controlRegistrySyncResult.processId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n }\n if (event.phase === \"process_spawned\" || event.phase === \"process_exit\") {\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: buildProviderProcessJournalMetadata({\n agentControllerRef: parsedTask.agentControllerRef,\n event,\n runtimeStartedAtMs,\n }),\n parsedTask,\n phase: event.phase,\n result: event.phase === \"process_exit\" ? \"exited\" : \"spawned\",\n });\n }\n emitProviderRuntimePhaseLine({\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n event,\n presenter: input.presenter,\n runtimeStartedAtMs,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n });\n clearReasoning();\n const runtimeExecutionPromise = Promise.resolve(\n runDispatchRuntimeExecution({\n computerFileAccessBoundary,\n contextId: contextIdForDispatch,\n executionMode: \"normal\",\n io: ledgerIo,\n ledgerPaths: input.ledgerPaths,\n onInteractionRequest,\n onNativeTurnStarted,\n onNativeTurnCompleted,\n onRuntimeEvent,\n onPreview: (preview) => {\n emitDispatchPreviewFrame({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n presenter: input.presenter,\n previewText: preview.text,\n taskId: parsedTask.taskId,\n });\n },\n parsedTask,\n instructionPrompt: runtimePromptPlan,\n prompt: runtimePromptPlan.fallbackPrompt,\n routeConfig,\n runtimeContext: activeRuntimeContext,\n runtimeEnvOverrides,\n runtimeControllerSupport,\n agentControllerConversationOverride,\n })\n );\n const controllerTurnCompletion = runtimeExecutionPromise.then(\n () => undefined,\n () => undefined\n );\n nativeQuiescence = controllerTurnCompletion;\n let runtimeResult = await resolveRuntimeResultFromRuntimeOrCliSpaceAction({\n contextIdForDispatch,\n dispatchSpaceActionContext,\n getObservedAgentControllerConversation: () =>\n observedProviderConversation,\n getObservedAgentControllerConversationId: () =>\n observedProviderConversationId,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n onRuntimeResultAfterCliSpaceAction: (runtimeResult) => {\n const runtimeContextDelta =\n resolveDispatchContextDeltaFromRuntimeResult(\n runtimeResult.dispatchResult\n );\n recordProviderConversationObservation({\n agentControllerConversation:\n runtimeResult.contextResolution?.agentControllerConversation ??\n runtimeContextDelta?.agentControllerConversation ??\n null,\n agentControllerConversationId:\n runtimeResult.contextResolution?.agentControllerConversationId ??\n runtimeContextDelta?.agentControllerConversationId ??\n null,\n source: \"runtime_result\",\n });\n },\n parsedTask,\n presenter: input.presenter,\n runtimeExecutionPromise,\n });\n const structuredSpaceActionOutcome =\n await resolveRuntimeResultStructuredSpaceAction({\n onInteractionRequest,\n onNativeTurnStarted,\n onNativeTurnCompleted,\n onRuntimeEvent,\n computerFileAccessBoundary,\n controllerTurnCompletion,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n instructionPrompt: runtimePromptPlan,\n parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n presenter: input.presenter,\n routeConfig,\n cliEntry: bootstrapContext.cliEntry,\n dispatchSpaceActionContext,\n runtimeResult,\n sendTargetReference,\n runtimeContext: activeRuntimeContext,\n runtimeEnvOverrides,\n runtimeControllerSupport,\n agentControllerConversationOverride,\n });\n runtimeResult = structuredSpaceActionOutcome.runtimeResult;\n resolvedSpaceAction = structuredSpaceActionOutcome.resolvedSpaceAction;\n resolvedSpaceActionProvenance =\n structuredSpaceActionOutcome.resolvedSpaceActionProvenance;\n emitRuntimeObservationSummaryLine({\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n presenter: input.presenter,\n runtimeResult,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n\n const contextDelta = resolveDispatchContextDeltaFromRuntimeResult(\n runtimeResult.dispatchResult\n );\n const contextHealed =\n contextDelta?.refreshed === true ||\n resolveAdapterTelemetry(runtimeResult.dispatchResult)?.contextHealed ===\n true;\n continuityObservation = resolveDispatchContinuityObservation({\n contextHealed,\n existingContextId: contextIdForDispatch,\n resolvedContextId:\n normalizeOptionalContextId(\n runtimeResult.contextResolution?.agentControllerConversationId ??\n contextDelta?.agentControllerConversationId ??\n null\n ) ?? null,\n });\n await withLedgerStateTransaction({\n invalidStateStrategy,\n io: ledgerIo,\n mutate: (state) => {\n let nextState = state;\n if (contextDelta?.agentControllerConversationId) {\n nextState = commitResolvedAgentContext({\n state: nextState,\n agentContextLookupKey: contextLookupKey,\n agentControllerConversationId:\n contextDelta.agentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n spaceId: parsedTask.spaceId,\n targetProfileId: parsedTask.targetProfileId,\n transportMode: parsedTask.transportMode,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n taskId: parsedTask.taskId,\n nowMs: Date.now(),\n });\n }\n const nextExecutionState =\n reconcileBootstrapInjectedContextAfterDispatch({\n executionState:\n resolveConversationExecutionStateByLookupKey({\n agentContextLookupKey: contextLookupKey,\n state: nextState,\n }) ?? currentExecutionState,\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n continuityObservation,\n contextHealed,\n dispatchedContextId:\n contextDelta?.agentControllerConversationId ?? null,\n effectiveRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n nowIso: new Date().toISOString(),\n resolvedAgentControllerConversation:\n contextDelta?.agentControllerConversation ??\n runtimeResult.contextResolution?.agentControllerConversation ??\n null,\n shouldInjectBootstrap: bootstrapPlan?.shouldInject === true,\n });\n if (nextExecutionState) {\n nextState = upsertConversationExecutionStateForLookupKey({\n state: nextState,\n executionState: nextExecutionState,\n replacedLookupKey:\n currentExecutionState?.agentContextLookupKey ?? null,\n targetLookupKey: contextLookupKey,\n });\n }\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n\n emitContextHealedLineIfNeeded({\n contextDelta,\n parsedTask,\n presenter: input.presenter,\n });\n\n const {\n bootstrapPlan: completedBootstrapPlan,\n ledgerIo: completedLedgerIo,\n localRuntimeContextPlan: completedLocalRuntimeContextPlan,\n runtimePromptPlan: completedRuntimePromptPlan,\n } = requireCompletedDispatchPlans({\n bootstrapPlan,\n ledgerIo,\n localRuntimeContextPlan,\n runtimePromptPlan,\n });\n const completedAgentControllerConversationOverride =\n agentControllerConversationOverride ?? null;\n const buildCurrentResultPayload =\n async (): Promise<OpenMeldDaemonTaskResultPayload> => {\n if (parsedTask.executionContext) {\n await controllerTurnCompletion;\n }\n const currentContextDelta =\n resolveDispatchContextDeltaFromRuntimeResult(\n runtimeResult.dispatchResult\n );\n const observedAgentControllerConversation =\n resolveObservedDispatchAgentControllerConversation({\n plannedAgentControllerConversation,\n contextDelta: currentContextDelta,\n contextResolution: runtimeResult.contextResolution ?? null,\n agentControllerConversationOverride:\n completedAgentControllerConversationOverride,\n });\n const finalNativeResult =\n completedNativeResult as RuntimeTaskResult | null;\n const nativeConversationId =\n (finalNativeResult\n ? resolveDispatchContextDeltaFromRuntimeResult(\n finalNativeResult.dispatchResult\n )?.agentControllerConversationId\n : null) ??\n finalNativeResult?.contextResolution?.agentControllerConversationId ??\n currentContextDelta?.agentControllerConversationId ??\n runtimeResult.contextResolution?.agentControllerConversationId ??\n observedAgentControllerConversation?.agentControllerConversationId ??\n observedProviderConversationId;\n executionContextCompletion = await captureExecutionContextCompletion({\n context: parsedTask.executionContext,\n nativeConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n workingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n completedTurnId:\n completedTurnConversationId === nativeConversationId\n ? completedTurnId\n : null,\n providerSucceeded:\n finalNativeResult?.resultPayload.status === \"success\" ||\n finalNativeResult?.resultPayload.status === \"partial_success\",\n });\n dispatchExecution = buildDispatchExecution({\n bootstrapPlan: completedBootstrapPlan,\n agentControllerConversationId: effectiveAgentControllerConversationId,\n localRuntimeContextPlan: completedLocalRuntimeContextPlan,\n observedAgentControllerConversation,\n plannedAgentControllerConversation,\n });\n return {\n ...resolveDispatchResultPayload({\n attemptId: parsedTask.attemptId,\n contextDelta: currentContextDelta,\n contextResolution: runtimeResult.contextResolution ?? null,\n basePayload: runtimeResult.resultPayload,\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchExecution,\n existingContextId: contextIdForDispatch,\n openClawBinding: runtimeOpenClawBinding,\n openClawGatewayVisibility: runtimeOpenClawGatewayVisibility,\n promptTrace: runtimePromptTrace,\n agentControllerConversationForDispatch:\n observedAgentControllerConversation ??\n plannedAgentControllerConversation,\n workingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n spaceAction: resolvedSpaceAction,\n spaceActionProvenance: resolvedSpaceActionProvenance,\n sourceEventId: parsedTask.sourceEventId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n }),\n executionContextId: parsedTask.executionContext?.id,\n executionContextCompletion,\n };\n };\n resultPayload = await buildCurrentResultPayload();\n const replySettlement = await settleAgentReplyProposals({\n initialResultPayload: resultPayload,\n reconsider: async (agentReplyObservationCursor) => {\n const reconsidered = await resolveRuntimeResultStructuredSpaceAction({\n onInteractionRequest,\n onNativeTurnStarted,\n onNativeTurnCompleted,\n onRuntimeEvent,\n agentReplyObservationCursor,\n computerFileAccessBoundary,\n controllerTurnCompletion,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n ledgerIo: completedLedgerIo,\n ledgerPaths: input.ledgerPaths,\n instructionPrompt: completedRuntimePromptPlan,\n parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n presenter: input.presenter,\n routeConfig,\n cliEntry: bootstrapContext.cliEntry,\n dispatchSpaceActionContext,\n runtimeResult,\n sendTargetReference,\n runtimeContext: activeRuntimeContext,\n runtimeEnvOverrides,\n runtimeControllerSupport,\n agentControllerConversationOverride,\n });\n runtimeResult = reconsidered.runtimeResult;\n resolvedSpaceAction = reconsidered.resolvedSpaceAction;\n resolvedSpaceActionProvenance =\n reconsidered.resolvedSpaceActionProvenance;\n return await buildCurrentResultPayload();\n },\n submit: (payload) =>\n sendResultAndSummarize({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n emitCompletedLifecycle: false,\n executionIdentityEcho: toRuntimeTransportResultIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n payload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId:\n parsedTask.runtimeCoordinatorExecutionId,\n ledgerPaths: input.ledgerPaths,\n taskId: parsedTask.taskId,\n waitForSettlement: true,\n }),\n });\n resultPayload = replySettlement.resultPayload;\n settledResultSummary = replySettlement.resultSummary;\n const runtimeObservationPayload = buildRuntimeObservationPayload({\n continuityObservation,\n dispatchId: parsedTask.dispatchId,\n daemonWorkingDirectory,\n deliveryRecoveryReason: parsedTask.deliveryRecoveryReason,\n providerRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n resultPayload,\n runtimeResult,\n runtimeStartedAtMs,\n taskId: parsedTask.taskId,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_completed\",\n text: `runtime completed for task ${parsedTask.taskId}`,\n payload: runtimeObservationPayload,\n });\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: runtimeObservationPayload,\n parsedTask,\n phase: \"runtime_completed\",\n result: resultPayload.status,\n });\n emitContinuityWarningIfNeeded({\n continuityObservation,\n parsedTask,\n presenter: input.presenter,\n });\n } catch (error) {\n await rollbackBootstrapExecutionStateAfterFailureIfNeeded({\n bootstrapPlan,\n contextLookupKey,\n currentExecutionState,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n });\n const runtimeFailedAtMs = Date.now();\n const typedError = toTaskExecutionErrorInternal(error);\n resultPayload = buildFailedTaskResultPayload({\n attemptId: parsedTask.attemptId,\n agentControllerRef: parsedTask.agentControllerRef,\n errorCode: typedError.errorCode,\n errorMessage: `${typedError.errorCode}: ${typedError.message}`,\n errorType: typedError.errorType,\n openClawBinding: runtimeOpenClawBinding,\n openClawGatewayVisibility: mergeOpenClawGatewayVisibilityInternal({\n primary: typedError.openClawGatewayVisibility,\n fallback: runtimeOpenClawGatewayVisibility,\n }),\n projectFailureContext: typedError.projectFailureContext,\n promptTrace: runtimePromptTrace,\n sourceEventId: parsedTask.sourceEventId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n agentControllerConversation: agentControllerConversationOverride,\n ...(effectiveRuntimeContext\n ? {\n effectiveRuntimeWorkingDirectory:\n effectiveRuntimeContext.providerRuntimeWorkingDirectory,\n }\n : {}),\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_completed\",\n text: `runtime failed for task ${parsedTask.taskId}`,\n payload: {\n attemptId: parsedTask.attemptId,\n daemonWorkingDirectory,\n dispatchId: parsedTask.dispatchId,\n deliveryRecoveryReason: parsedTask.deliveryRecoveryReason,\n errorCode: typedError.errorCode,\n projectFailureContext: typedError.projectFailureContext,\n ...(effectiveRuntimeContext\n ? {\n providerRuntimeWorkingDirectory:\n effectiveRuntimeContext.providerRuntimeWorkingDirectory,\n }\n : {}),\n result: resultPayload.status,\n runtimeDurationMs: runtimeFailedAtMs - runtimeStartedAtMs,\n taskId: parsedTask.taskId,\n },\n });\n } finally {\n await nativeQuiescence;\n await releaseDispatchTaskWorkspace({\n workspaceUse,\n parsedTask,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n workspaceProcesses,\n presenter: input.presenter,\n });\n reasoningStream.dispose();\n currentSocketRef.reasoningPreferenceListeners?.delete(clearReasoning);\n lifecycleKeepalive.stop?.();\n lifecycleKeepalive.stop = null;\n input.inflightDispatchMetaByTaskId.delete(parsedTask.taskId);\n input.inflightTaskControlRegistry.removeTask(parsedTask.taskId);\n pendingAgentInteractionRegistry.removeTask(parsedTask.taskId);\n }\n\n resultPayload = {\n ...resultPayload,\n executionContextId: parsedTask.executionContext?.id,\n executionContextCompletion,\n };\n\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n durationMs: Math.max(0, Date.now() - runtimeStartedAtMs),\n parsedTask,\n phase: resolveRuntimeEvidenceResultPhase(resultPayload),\n presenter: input.presenter,\n reasonCode: resolveRuntimeEvidenceResultReasonCode(resultPayload),\n });\n\n const resultSummary =\n settledResultSummary ??\n sendResultAndSummarize({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportResultIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n payload: resultPayload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n ledgerPaths: input.ledgerPaths,\n taskId: parsedTask.taskId,\n }).resultSummary;\n emitDispatchPreviewEndFrame({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n presenter: input.presenter,\n taskId: parsedTask.taskId,\n });\n return resultSummary;\n}\n\ntype ProviderProcessLifecycleEvent = Extract<\n AdapterRuntimeEvent,\n { phase: \"process_exit\" | \"process_spawned\" }\n>;\n\nfunction buildProviderProcessJournalMetadata(input: {\n agentControllerRef: string;\n event: ProviderProcessLifecycleEvent;\n runtimeStartedAtMs: number;\n}): Record<string, unknown> {\n const lifecycleMetadata =\n input.event.phase === \"process_exit\"\n ? {\n exitCode: input.event.exitCode,\n exitSignal: input.event.signal,\n }\n : {\n ...(input.event.processLaunchKind\n ? { processLaunchKind: input.event.processLaunchKind }\n : {}),\n ...(input.event.processWorkingDirectoryKind\n ? {\n processWorkingDirectoryKind:\n input.event.processWorkingDirectoryKind,\n }\n : {}),\n };\n return {\n agentControllerRef: input.agentControllerRef,\n ...lifecycleMetadata,\n phaseTsMs: input.event.tsMs,\n processId: input.event.processId,\n signalTarget: input.event.signalTarget,\n sinceRuntimeStartedMs: Math.max(\n 0,\n input.event.tsMs - input.runtimeStartedAtMs\n ),\n };\n}\n\nfunction emitSendTargetReferenceLoadFailureIfNeeded(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n}): void {\n if (input.sendTargetReference.status !== \"failed\") {\n return;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.send_target_reference_load_failed\",\n text: `send target reference load failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: input.sendTargetReference.errorMessage,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n}\n\nfunction emitDispatchImageAttachmentPreparation(input: {\n parsedTask: ParsedDispatchTask;\n preparation: DispatchImageAttachmentPreparation;\n presenter: Presenter;\n}): void {\n for (const failure of input.preparation.failures) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.attachment_download_failed\",\n text: `image attachment unavailable for task ${input.parsedTask.taskId}`,\n payload: {\n attachmentId: failure.attachment.id,\n dispatchId: input.parsedTask.dispatchId,\n errorCode: failure.errorCode,\n errorMessage: failure.errorMessage,\n mimeType: failure.attachment.mimeType,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n }\n}\n\nasync function prepareBootstrapExecutionStateIfNeeded(input: {\n bootstrapPlan: BootstrapPlan;\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n contextIdForDispatch: string | null;\n contextLookupKey: string;\n currentExecutionState: ConversationExecutionState | null;\n effectiveRuntimeWorkingDirectory: string;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n}): Promise<void> {\n if (!input.bootstrapPlan.shouldInject) {\n return;\n }\n\n await withLedgerStateTransaction({\n invalidStateStrategy: \"backup_and_reset\",\n io: input.ledgerIo,\n mutate: (state) => {\n const latestExecutionState =\n resolveConversationExecutionStateByLookupKey({\n agentContextLookupKey: input.contextLookupKey,\n state,\n }) ?? input.currentExecutionState;\n const nextState = upsertConversationExecutionStateForLookupKey({\n state,\n executionState: markBootstrapInjectedContext({\n executionState: latestExecutionState,\n agentContextLookupKey: input.contextLookupKey,\n bootstrapTemplateFacts: input.bootstrapTemplateFacts,\n existingContextId: input.contextIdForDispatch,\n effectiveRuntimeWorkingDirectory:\n input.effectiveRuntimeWorkingDirectory,\n nowIso: new Date().toISOString(),\n }),\n replacedLookupKey: latestExecutionState?.agentContextLookupKey ?? null,\n targetLookupKey: input.contextLookupKey,\n });\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.bootstrap_injected\",\n text: `bootstrap injected for ${input.parsedTask.spaceId}/${input.parsedTask.targetProfileId}`,\n payload: {\n bootstrapReason: input.bootstrapPlan.reason,\n dispatchId: input.parsedTask.dispatchId,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n },\n });\n}\n\nfunction emitContextHealedLineIfNeeded(input: {\n contextDelta: AdapterDispatchContextDelta | null;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n}): void {\n if (input.contextDelta?.refreshed !== true) {\n return;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.context_healed\",\n text: `context healed once for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n taskId: input.parsedTask.taskId,\n targetProfileId: input.parsedTask.targetProfileId,\n },\n });\n}\n\nasync function rollbackBootstrapExecutionStateAfterFailureIfNeeded(input: {\n bootstrapPlan: BootstrapPlan | null;\n contextLookupKey: string;\n currentExecutionState: ConversationExecutionState | null;\n ledgerIo: ReturnType<typeof createLedgerIo> | null;\n ledgerPaths: LedgerPaths;\n}): Promise<void> {\n if (!(input.bootstrapPlan?.shouldInject && input.ledgerIo)) {\n return;\n }\n\n await withLedgerStateTransaction({\n invalidStateStrategy: \"backup_and_reset\",\n io: input.ledgerIo,\n mutate: (state) => {\n const nextState = rollbackBootstrapExecutionStateAfterDispatchFailure({\n agentContextLookupKey: input.contextLookupKey,\n executionStateBeforeDispatch: input.currentExecutionState,\n state,\n });\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n}\n\nasync function verifyDispatchLegacyContextAssociation(input: {\n parsedTask: ParsedDispatchTask;\n ledgerPaths: LedgerPaths;\n originalWorkingDirectory: string;\n}): Promise<void> {\n const association = input.parsedTask.executionContext?.legacyAssociation;\n if (!association) {\n return;\n }\n const state = await loadLedgerState({\n invalidStateStrategy: \"throw\",\n io: createLedgerIo(),\n paths: input.ledgerPaths,\n });\n assertLegacyAgentContextAssociation({\n state,\n legacyNativeConversationId: association.nativeConversationId,\n key: {\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n transportMode: input.parsedTask.transportMode,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n input.originalWorkingDirectory\n ),\n },\n });\n}\n\nasync function loadDispatchLedgerContext(input: {\n contextStore: Map<string, string>;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n runtimeWorkspaceFingerprint: string;\n originalWorkingDirectory: string;\n}): Promise<{\n contextLookupKey: string;\n currentExecutionState: ConversationExecutionState | null;\n existingContextId: string | null;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n latestScopedExecutionState: ConversationExecutionState | null;\n}> {\n const keyInput = {\n executionContextId: input.parsedTask.executionContext?.id,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n transportMode: input.parsedTask.transportMode,\n runtimeWorkspaceFingerprint: input.runtimeWorkspaceFingerprint,\n } as const;\n const contextLookupKey = buildAgentContextLookupKey(keyInput);\n const ledgerIo = createLedgerIo();\n const legacyContextId = input.contextStore.get(contextLookupKey) ?? null;\n const {\n currentExecutionState,\n existingContextId,\n latestScopedExecutionState,\n } = await withLedgerStateTransaction({\n invalidStateStrategy: executionContextLedgerPolicy(\n input.parsedTask.executionContext\n ),\n io: ledgerIo,\n mutate: (state) => {\n const scopeInput = {\n agentControllerRef: input.parsedTask.agentControllerRef,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n transportMode: input.parsedTask.transportMode,\n } as const;\n assertLegacyAgentContextAssociation({\n state,\n legacyNativeConversationId:\n input.parsedTask.executionContext?.legacyAssociation\n ?.nativeConversationId,\n key: {\n ...scopeInput,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n input.originalWorkingDirectory\n ),\n },\n });\n const existingAgentContextMatch = resolveCompatibleAgentContextMatch({\n key: keyInput,\n state,\n });\n const seededLedgerState = existingAgentContextMatch\n ? state\n : seedLegacyAgentContext({\n state,\n agentContextLookupKey: contextLookupKey,\n legacyAgentControllerConversationId: legacyContextId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n transportMode: input.parsedTask.transportMode,\n runtimeWorkspaceFingerprint: input.runtimeWorkspaceFingerprint,\n taskId: input.parsedTask.taskId,\n nowMs: Date.now(),\n });\n const nextAgentContextMatch = resolveCompatibleAgentContextMatch({\n key: keyInput,\n state: seededLedgerState,\n });\n const existingContextId =\n nextAgentContextMatch?.agentContext.agentControllerConversationId ??\n null;\n const currentExecutionState = resolveCompatibleConversationExecutionState(\n {\n key: keyInput,\n preferredLookupKey:\n nextAgentContextMatch?.agentContextLookupKey ?? null,\n state: seededLedgerState,\n }\n );\n const latestScopedExecutionState = input.parsedTask.executionContext\n ? currentExecutionState\n : (resolveLatestScopedConversationExecutionState({\n scope: scopeInput,\n state: seededLedgerState,\n })?.executionState ?? null);\n return {\n nextState: seededLedgerState,\n value: {\n currentExecutionState,\n existingContextId,\n latestScopedExecutionState,\n },\n };\n },\n paths: input.ledgerPaths,\n });\n\n return {\n contextLookupKey,\n currentExecutionState,\n existingContextId,\n ledgerIo,\n latestScopedExecutionState,\n };\n}\n\ntype DispatchBootstrapContext = {\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n cliEntry: string | null;\n mentionSourceMentionLabel: string | null;\n mentionSourceProfileName: string | null;\n sendTargetReferencePromise: Promise<DispatchSendTargetReferenceLoadResult>;\n spaceGuide: string | null;\n spaceName: string | null;\n spaceOwnerProfileId: string | null;\n spacePurpose: string | null;\n targetProfileMentionLabel: string | null;\n targetProfileName: string | null;\n targetProfileRole: string | null;\n};\n\ntype DispatchSpaceMetaLoadResult =\n | {\n status: \"loaded\";\n spaceGuide: string | null;\n spaceName: string | null;\n spacePurpose: string | null;\n }\n | {\n status: \"failed\";\n errorMessage: string;\n spaceGuide: null;\n spaceName: null;\n spacePurpose: null;\n };\n\nasync function resolveDispatchBootstrapContext(input: {\n onPhase?: (\n phase: DispatchBootstrapContextPhase,\n metadata: Record<string, unknown>\n ) => void;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n parsedTask: ParsedDispatchTask;\n}): Promise<DispatchBootstrapContext> {\n const [\n spaceOwnerProfileId,\n targetProfileContext,\n mentionSourceContext,\n spaceMetaContext,\n ] = await Promise.all([\n resolveBootstrapSpaceOwnerProfileId({\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n }),\n resolveBootstrapTargetProfileContext({\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n preferredMentionLabel: input.parsedTask.targetProfileMentionLabel,\n preferredProfileName: input.parsedTask.targetProfileName,\n }),\n resolveDispatchMentionSourceContext({\n spaceId: input.parsedTask.spaceId,\n mentionSourceProfileId: input.parsedTask.mentionSourceProfileId,\n preferredMentionLabel: input.parsedTask.mentionSourceProfileMentionLabel,\n }),\n resolveDispatchSpaceMetaContext({\n parsedTask: input.parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n }),\n ]);\n input.onPhase?.(\"bootstrap_context_ready\", {\n mentionSourceMentionLabelPresent:\n mentionSourceContext.mentionSourceMentionLabel !== null,\n mentionSourceProfileNamePresent:\n mentionSourceContext.mentionSourceProfileName !== null,\n source: \"dispatch_bootstrap_context\",\n spaceGuidePresent: spaceMetaContext.spaceGuide !== null,\n spaceMetaError:\n spaceMetaContext.status === \"failed\"\n ? spaceMetaContext.errorMessage\n : null,\n spaceMetaStatus: spaceMetaContext.status,\n spaceNamePresent: spaceMetaContext.spaceName !== null,\n spaceOwnerProfilePresent: spaceOwnerProfileId !== null,\n spacePurposePresent: spaceMetaContext.spacePurpose !== null,\n targetProfileMentionLabelPresent:\n targetProfileContext.targetProfileMentionLabel !== null,\n targetProfileNamePresent: targetProfileContext.targetProfileName !== null,\n targetProfileRolePresent: targetProfileContext.targetProfileRole !== null,\n });\n // Deliberately not awaited here: the member-directory load is a network\n // round trip that nothing in local runtime/ledger preparation depends on,\n // so it runs concurrently with that local work and is awaited at its first\n // real consumer. The phase event fires when the load actually resolves.\n // The loader never rejects (it returns a \"failed\" result), so this floating\n // promise cannot produce an unhandled rejection.\n const sendTargetReferencePromise = resolveDispatchSendTargetReference({\n agentControllerRef: input.parsedTask.agentControllerRef,\n dispatchTask: input.parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n targetProfileName: targetProfileContext.targetProfileName,\n }).then((sendTargetReference) => {\n input.onPhase?.(\"send_target_reference_ready\", {\n sendTargetReferenceCount:\n sendTargetReference.status === \"loaded\"\n ? sendTargetReference.projection.length\n : null,\n sendTargetReferenceStatus: sendTargetReference.status,\n source: \"dispatch_send_target_reference\",\n });\n return sendTargetReference;\n });\n const cliEntry = DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND;\n const bootstrapTemplateFacts = buildDispatchBootstrapTemplateFacts({\n dispatchTriggerSource: input.parsedTask.dispatchTriggerSource,\n mentionSourceProfileId: input.parsedTask.mentionSourceProfileId,\n mentionSourceProfileKind: input.parsedTask.mentionSourceProfileKind,\n ...mentionSourceContext,\n spaceId: input.parsedTask.spaceId,\n spaceGuide: spaceMetaContext.spaceGuide,\n spaceName: spaceMetaContext.spaceName,\n spaceOwnerProfileId,\n spacePurpose: spaceMetaContext.spacePurpose,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n ...targetProfileContext,\n targetProfileId: input.parsedTask.targetProfileId,\n cliEntry,\n });\n\n return {\n bootstrapTemplateFacts,\n cliEntry,\n mentionSourceMentionLabel:\n mentionSourceContext.mentionSourceMentionLabel ?? null,\n mentionSourceProfileName: mentionSourceContext.mentionSourceProfileName,\n sendTargetReferencePromise,\n spaceGuide: spaceMetaContext.spaceGuide,\n spaceName: spaceMetaContext.spaceName,\n spaceOwnerProfileId,\n spacePurpose: spaceMetaContext.spacePurpose,\n targetProfileMentionLabel: targetProfileContext.targetProfileMentionLabel,\n targetProfileName: targetProfileContext.targetProfileName,\n targetProfileRole: targetProfileContext.targetProfileRole,\n };\n}\n\nasync function resolveDispatchSpaceMetaContext(input: {\n parsedTask: ParsedDispatchTask;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n}): Promise<DispatchSpaceMetaLoadResult> {\n try {\n const baseUrl = await resolveBaseUrl();\n const requestContext = buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n openMeldProfileId: input.parsedTask.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.profileOwnerUserId,\n ...(input.profileOwnerName\n ? { ownerName: input.profileOwnerName }\n : {}),\n profileName:\n input.parsedTask.targetProfileName ??\n input.parsedTask.targetProfileMentionLabel ??\n input.parsedTask.targetProfileId,\n },\n });\n const meta = await fetchSpaceMeta({\n baseUrl,\n requestContext,\n space: input.parsedTask.spaceId,\n ...(input.parsedTask.spacePassword\n ? { password: input.parsedTask.spacePassword }\n : {}),\n });\n return {\n status: \"loaded\",\n spaceGuide: normalizeOptionalText(meta.guide),\n spaceName: normalizeOptionalText(meta.name),\n spacePurpose: normalizeOptionalText(meta.purpose),\n };\n } catch (error) {\n return {\n status: \"failed\",\n errorMessage: toErrorMessage(error),\n spaceGuide: null,\n spaceName: null,\n spacePurpose: null,\n };\n }\n}\n\nfunction buildDispatchRuntimePrompt(input: {\n bootstrapContext: DispatchBootstrapContext;\n imageAttachmentPreparation: DispatchImageAttachmentPreparation;\n parsedTask: ParsedDispatchTask;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n shouldInjectBootstrap: boolean;\n taskWorkspace?: ExecutionContextWorkspace;\n}): DispatchPromptPlan {\n return buildDispatchPromptPlan({\n callerContext: input.parsedTask.callerContext,\n shouldInjectBootstrap: input.shouldInjectBootstrap,\n shouldInjectCenterAgentRoleTemplate:\n input.parsedTask.targetProfileIsCenterAgent,\n dispatchTriggerSource: input.parsedTask.dispatchTriggerSource,\n imageAttachmentPromptSection:\n input.imageAttachmentPreparation.promptSection,\n spaceFiles: input.parsedTask.files,\n mentionSourceProfileId: input.parsedTask.mentionSourceProfileId,\n mentionSourceProfileKind: input.parsedTask.mentionSourceProfileKind,\n mentionSourceMentionLabel: input.bootstrapContext.mentionSourceMentionLabel,\n mentionSourceProfileName: input.bootstrapContext.mentionSourceProfileName,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n organizationProtectedInformation:\n input.parsedTask.organizationProtectedInformation,\n workingLanguage: input.parsedTask.workingLanguage,\n prompt: input.taskWorkspace?.baseCommit\n ? `${input.parsedTask.prompt}\\n\\nOpenMeld task workspace: ${JSON.stringify(\n {\n projectId: input.parsedTask.defaultProjectId,\n repositoryName: input.taskWorkspace.sourceWorkingDirectory\n ? basename(input.taskWorkspace.sourceWorkingDirectory)\n : null,\n workingDirectory: input.taskWorkspace.workingDirectory,\n baseCommit: input.taskWorkspace.baseCommit,\n }\n )}\\nThis task uses an independent Git worktree with private Git metadata. The starting commit is frozen. Uncommitted and ignored source files were not copied. Make changes in this task worktree; the original checkout is not the task's working directory. Refer to the task and commit in public replies without disclosing private local paths.`\n : input.parsedTask.prompt,\n recipientExplicitlyAddressedByActivationTargets:\n input.parsedTask.recipientExplicitlyAddressedByActivationTargets,\n sourceSignalId: input.parsedTask.sourceEventId,\n sourceMessageEnvelope: input.parsedTask.sourceMessageEnvelope,\n sendTargetReferenceLines: input.sendTargetReference.referenceLines,\n spaceId: input.parsedTask.spaceId,\n spaceGuide: input.bootstrapContext.spaceGuide,\n spaceName: input.bootstrapContext.spaceName,\n spaceOwnerProfileId: input.bootstrapContext.spaceOwnerProfileId,\n spacePurpose: input.bootstrapContext.spacePurpose,\n targetProfileMentionLabel: input.bootstrapContext.targetProfileMentionLabel,\n targetProfileName: input.bootstrapContext.targetProfileName,\n targetProfileRole: input.bootstrapContext.targetProfileRole,\n cliEntry: input.bootstrapContext.cliEntry,\n continuitySnapshot: input.parsedTask.continuitySnapshot,\n replyToSnapshot: input.parsedTask.replyToSnapshot,\n threadContext: input.parsedTask.threadContext,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n targetProfileId: input.parsedTask.targetProfileId,\n });\n}\n\nasync function prepareDispatchTaskWorkspace(input: {\n parsedTask: ParsedDispatchTask;\n ledgerRootPath: string;\n currentWorkingDirectory: string;\n computerFileAccessStorePath: string;\n}): Promise<ExecutionContextWorkspace> {\n const context = input.parsedTask.executionContext;\n if (context && context.access !== \"space_context\") {\n return await prepareExecutionContextWorkspace({\n context,\n ledgerRootPath: input.ledgerRootPath,\n currentWorkingDirectory: input.currentWorkingDirectory,\n policy: await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n ),\n });\n }\n const workingDirectory = await executionContextWorkingDirectory({\n context,\n ledgerRootPath: input.ledgerRootPath,\n currentWorkingDirectory: input.currentWorkingDirectory,\n });\n return { workingDirectory, boundaryRoot: workingDirectory };\n}\n\nasync function releaseDispatchTaskWorkspace(input: {\n workspaceUse: ExecutionContextWorkspaceUse | null;\n parsedTask: ParsedDispatchTask;\n ledgerRootPath: string;\n workspaceProcesses: Map<number | null, boolean>;\n presenter: Presenter;\n}): Promise<void> {\n const context = input.parsedTask.executionContext;\n if (!(input.workspaceUse && context)) {\n return;\n }\n try {\n const released = await releaseExecutionContextWorkspace({\n ledgerRootPath: input.ledgerRootPath,\n context,\n use: input.workspaceUse,\n // Codex reports process_spawned synchronously before native work. An\n // empty set after a settled preflight error means no process was started.\n ownedProcessesQuiescent: [...input.workspaceProcesses.values()].every(\n Boolean\n ),\n });\n emitRunLine({\n presenter: input.presenter,\n code: `daemon.run.workspace_${released.status}`,\n text:\n released.status === \"released\"\n ? \"Reclaimed the unchanged task workspace.\"\n : \"Retained the task workspace.\",\n payload: { contextId: context.id, ...released },\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.workspace_retained\",\n text: \"Task workspace cleanup needs reconciliation.\",\n payload: { contextId: context.id, errorMessage: toErrorMessage(error) },\n });\n }\n}\n\nfunction observeExecutionContextWorkspaceProcess(\n processes: Map<number | null, boolean>,\n event: AdapterRuntimeEvent\n): void {\n if (event.phase === \"process_spawned\") {\n processes.set(event.processId, false);\n } else if (event.phase === \"process_exit\") {\n processes.set(event.processId, event.ownedProcessesQuiescent === true);\n }\n}\n\nasync function resolveDispatchComputerFileAccess(input: {\n computerFileAccessStorePath: string;\n onInteractionRequest: AdapterInteractionCallback;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n runtimePreparation: DispatchRuntimePreparation;\n taskWorkspace?: ExecutionContextWorkspace;\n}): Promise<AdapterComputerFileAccessBoundary | null> {\n const policy = await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n );\n const verifier =\n input.runtimeControllerSupport.localAdapterEntry.adapter\n .verifyComputerFileAccessBoundary;\n if (input.parsedTask.executionContext) {\n const context = input.parsedTask.executionContext;\n if (\n input.parsedTask.agentControllerRef === \"builtin:claude-code\" &&\n context.access === \"space_context\"\n ) {\n return null;\n }\n if (\n input.parsedTask.agentControllerRef !== \"builtin:codex\" ||\n input.parsedTask.transportMode !== \"codex-app-server\" ||\n !verifier\n ) {\n throw new Error(\"execution_context.file_access_unsupported\");\n }\n const workingDirectory =\n input.runtimePreparation.effectiveRuntimeContext\n .providerRuntimeWorkingDirectory;\n const boundary = executionContextFileAccessBoundary({\n context,\n workingDirectory,\n policy,\n taskWorkspace: input.taskWorkspace,\n workingCopyId: input.parsedTask.workingCopyId,\n });\n const verification = await verifier({\n boundary,\n workingDirectory,\n executionMode: \"normal\",\n agentControllerPermissionMode:\n input.routeConfig?.agentControllerPermissionMode,\n launchContract: input.routeConfig?.launchContract ?? null,\n transportMode: input.parsedTask.transportMode,\n });\n if (!verification.supported) {\n throw new Error(\"execution_context.file_access_unverified\");\n }\n return boundary;\n }\n const admission = await resolveComputerFileAccessAdmission({\n agentControllerPermissionMode:\n input.routeConfig?.agentControllerPermissionMode,\n agentControllerRef: input.parsedTask.agentControllerRef,\n onInteractionRequest: input.onInteractionRequest,\n policy,\n providerRuntimeWorkingDirectory:\n input.runtimePreparation.effectiveRuntimeContext\n .providerRuntimeWorkingDirectory,\n transportMode: input.parsedTask.transportMode,\n ...(verifier\n ? {\n verifyBoundary: async (boundary) => {\n const verification = await verifier({\n agentControllerPermissionMode:\n input.routeConfig?.agentControllerPermissionMode,\n boundary,\n executionMode: \"normal\",\n launchContract: input.routeConfig?.launchContract ?? null,\n transportMode: input.parsedTask.transportMode,\n workingDirectory:\n input.runtimePreparation.effectiveRuntimeContext\n .providerRuntimeWorkingDirectory,\n });\n return verification;\n },\n }\n : {}),\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.computer_file_access_resolved\",\n text: `Computer file access resolved for task ${input.parsedTask.taskId}`,\n payload: {\n boundaryApplied: admission.boundary !== null,\n bypassedForThisRun: admission.bypassedForThisRun,\n dispatchId: input.parsedTask.dispatchId,\n mode: policy.mode,\n revision: policy.revision,\n taskId: input.parsedTask.taskId,\n },\n });\n return admission.boundary;\n}\n\nfunction createDispatchSpaceActionRuntimeContext(input: {\n bootstrapContext: DispatchBootstrapContext;\n parsedTask: ParsedDispatchTask;\n runtimePreparation: DispatchRuntimePreparation;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n}): {\n dispatchSpaceActionContext: DispatchSpaceActionContext;\n runtimeEnvOverrides: Record<string, string | undefined> | undefined;\n} {\n const contextResult = createDispatchSpaceActionContext({\n workingCopyId: input.parsedTask.workingCopyId,\n attemptId: input.parsedTask.attemptId,\n dispatchId: input.parsedTask.dispatchId,\n env: process.env,\n replyToSignalId: input.parsedTask.replyToSnapshot?.signalId ?? null,\n sendTargetReference: input.sendTargetReference,\n sourceEventId: input.parsedTask.sourceEventId,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n });\n\n return {\n dispatchSpaceActionContext: contextResult.context,\n runtimeEnvOverrides: {\n ...(input.runtimePreparation.runtimeEnvOverrides ?? {}),\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]: contextResult.contextPath,\n },\n };\n}\n\nexport async function resolveRuntimeResultFromRuntimeOrCliSpaceAction(input: {\n contextIdForDispatch: string | null;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n getObservedAgentControllerConversation?: () => AgentControllerConversationRef | null;\n getObservedAgentControllerConversationId?: () => string | null;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n onRuntimeResultAfterCliSpaceAction?: (\n runtimeResult: RuntimeTaskResult\n ) => Promise<void> | void;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): Promise<RuntimeTaskResult> {\n if (!input.dispatchSpaceActionContext) {\n return await input.runtimeExecutionPromise;\n }\n if (input.parsedTask.executionContext) {\n return await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult: await input.runtimeExecutionPromise,\n });\n }\n\n const cliSpaceActionAbortController = new AbortController();\n let completion: DispatchRuntimeCompletion;\n try {\n completion = await Promise.race([\n input.runtimeExecutionPromise.then(\n (runtimeResult): DispatchRuntimeCompletion => ({\n kind: \"runtime\",\n runtimeResult,\n })\n ),\n waitForCliSpaceActionRecord({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n signal: cliSpaceActionAbortController.signal,\n }),\n ]);\n } finally {\n cliSpaceActionAbortController.abort();\n }\n\n if (completion.kind === \"runtime\") {\n return await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult: completion.runtimeResult,\n });\n }\n\n if (completion.kind === \"cli_space_action_poll_aborted\") {\n return await input.runtimeExecutionPromise;\n }\n\n if (completion.kind === \"cli_space_action_invalid\") {\n throw new DaemonServiceRunError({\n code: \"dispatch.cli_space_action.invalid\",\n message: completion.errorMessage,\n });\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.cli_space_action_finalized\",\n text: `CLI OpenMeld Space Action finalized task ${input.parsedTask.taskId}`,\n payload: {\n command: completion.record.command,\n dispatchId: input.parsedTask.dispatchId,\n spaceActionType: completion.record.action.type,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n const completedRuntimeResult =\n await resolveAlreadyCompletedRuntimeResultAfterCliSpaceAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeExecutionPromise: input.runtimeExecutionPromise,\n });\n if (completedRuntimeResult) {\n return applyCliSpaceActionRecordToRuntimeResult({\n record: completion.record,\n runtimeResult: completedRuntimeResult,\n });\n }\n\n const postActionCompletion =\n await resolveRuntimeResultOrObservedProviderConversationAfterCliSpaceAction(\n {\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n runtimeExecutionPromise: input.runtimeExecutionPromise,\n }\n );\n if (postActionCompletion?.kind === \"runtime\") {\n return applyCliSpaceActionRecordToRuntimeResult({\n record: completion.record,\n runtimeResult: postActionCompletion.runtimeResult,\n });\n }\n\n observeRuntimeResultAfterCliSpaceAction({\n onRuntimeResultAfterCliSpaceAction:\n input.onRuntimeResultAfterCliSpaceAction,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeExecutionPromise: input.runtimeExecutionPromise,\n });\n const observedAgentControllerConversation =\n postActionCompletion?.kind === \"provider_conversation\"\n ? postActionCompletion.agentControllerConversation\n : resolveObservedProviderConversationForCliSpaceAction({\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n });\n\n return await buildCliSpaceActionRuntimeResult({\n agentControllerConversation: observedAgentControllerConversation,\n agentControllerConversationId:\n observedAgentControllerConversation?.agentControllerConversationId ??\n null,\n ledgerIo: input.ledgerIo,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n record: completion.record,\n });\n}\n\nexport function resolveEffectiveAgentControllerConversationId(input: {\n agentControllerConversationId: string | null;\n existingContextId: string | null;\n}): string | null {\n const bindingConversationId = normalizeOptionalContextId(\n input.agentControllerConversationId\n );\n if (bindingConversationId) {\n return bindingConversationId;\n }\n return normalizeOptionalContextId(input.existingContextId);\n}\n\ntype CliSpaceActionPostActionCompletion =\n | {\n kind: \"provider_conversation\";\n agentControllerConversation: AgentControllerConversationRef;\n }\n | {\n kind: \"runtime\";\n runtimeResult: RuntimeTaskResult;\n };\n\nasync function resolveRuntimeResultOrObservedProviderConversationAfterCliSpaceAction(input: {\n contextIdForDispatch: string | null;\n getObservedAgentControllerConversation?: () => AgentControllerConversationRef | null;\n getObservedAgentControllerConversationId?: () => string | null;\n parsedTask: ParsedDispatchTask;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): Promise<CliSpaceActionPostActionCompletion | null> {\n const existingConversation =\n resolveObservedProviderConversationForCliSpaceAction({\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n });\n if (existingConversation) {\n return {\n kind: \"provider_conversation\",\n agentControllerConversation: existingConversation,\n };\n }\n\n const deadlineMs =\n Date.now() + CLI_SPACE_ACTION_PROVIDER_CONVERSATION_GRACE_MS;\n const runtimeCompletion = input.runtimeExecutionPromise.then(\n (runtimeResult) => ({ runtimeResult, status: \"runtime\" as const }),\n (error) => ({ error, status: \"runtime_error\" as const })\n );\n\n while (Date.now() < deadlineMs) {\n const remainingMs = Math.max(0, deadlineMs - Date.now());\n const waitMs = Math.min(\n CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS,\n remainingMs\n );\n const result = await Promise.race([\n runtimeCompletion,\n delay(waitMs).then(() => ({ status: \"pending\" as const })),\n ]);\n\n if (result.status === \"runtime\") {\n return {\n kind: \"runtime\",\n runtimeResult: result.runtimeResult,\n };\n }\n if (result.status === \"runtime_error\") {\n return null;\n }\n\n const observedConversation =\n resolveObservedProviderConversationForCliSpaceAction({\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n });\n if (observedConversation) {\n return {\n kind: \"provider_conversation\",\n agentControllerConversation: observedConversation,\n };\n }\n }\n\n return null;\n}\n\nfunction resolveObservedProviderConversationForCliSpaceAction(input: {\n contextIdForDispatch: string | null;\n getObservedAgentControllerConversation?: () => AgentControllerConversationRef | null;\n getObservedAgentControllerConversationId?: () => string | null;\n parsedTask: ParsedDispatchTask;\n}): AgentControllerConversationRef | null {\n const observedAgentControllerConversation =\n input.getObservedAgentControllerConversation?.() ?? null;\n if (observedAgentControllerConversation) {\n return observedAgentControllerConversation;\n }\n\n const observedAgentControllerConversationId =\n normalizeOptionalContextId(\n input.getObservedAgentControllerConversationId?.() ?? null\n ) ?? input.contextIdForDispatch;\n return buildAgentControllerConversationRefFromAgentControllerConversation({\n agentControllerConversationId: observedAgentControllerConversationId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n });\n}\n\nasync function waitForCliSpaceActionRecord(input: {\n dispatchSpaceActionContext: DispatchSpaceActionContext;\n signal: AbortSignal;\n}): Promise<DispatchRuntimeCompletion> {\n while (!input.signal.aborted) {\n const readResult = readDispatchSpaceActionRecord({\n context: input.dispatchSpaceActionContext,\n });\n if (readResult.status === \"loaded\") {\n return {\n kind: \"cli_space_action_recorded\",\n record: readResult.record,\n };\n }\n if (readResult.status === \"invalid\") {\n return {\n kind: \"cli_space_action_invalid\",\n errorMessage: readResult.errorMessage,\n };\n }\n try {\n await delay(CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS, undefined, {\n signal: input.signal,\n });\n } catch (error) {\n if (input.signal.aborted) {\n return {\n kind: \"cli_space_action_poll_aborted\",\n };\n }\n throw error;\n }\n }\n\n return {\n kind: \"cli_space_action_poll_aborted\",\n };\n}\n\nasync function buildCliSpaceActionRuntimeResult(input: {\n agentControllerConversation: AgentControllerConversationRef | null;\n agentControllerConversationId: string | null;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n record: DispatchSpaceActionRecord;\n}): Promise<RuntimeTaskResult> {\n const resultPayload = buildCliSpaceActionSuccessPayload({\n basePayload: {\n agentId: input.parsedTask.targetProfileId,\n attemptId: input.parsedTask.attemptId,\n deduped: false,\n sourceEventId: input.parsedTask.sourceEventId,\n taskId: input.parsedTask.taskId,\n ...(input.agentControllerConversation\n ? {\n agentControllerConversation: input.agentControllerConversation,\n }\n : {}),\n ...(input.agentControllerConversationId\n ? {\n agentControllerConversationId: input.agentControllerConversationId,\n }\n : {}),\n ...(input.parsedTask.agentControllerRef\n ? { agentControllerRef: input.parsedTask.agentControllerRef }\n : {}),\n ...(input.parsedTask.transportMode\n ? { transportMode: input.parsedTask.transportMode }\n : {}),\n },\n record: input.record,\n });\n const state = await withLedgerStateTransaction({\n invalidStateStrategy: \"backup_and_reset\",\n io: input.ledgerIo,\n mutate: (state) => {\n const nextState = settleInflightTask({\n state,\n taskId: input.parsedTask.taskId,\n });\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n await appendLedgerHistoryEntry({\n entry: {\n message: \"task finalized from CLI Space Action\",\n reasonCode: \"task.cli_space_action\",\n status: resultPayload.status,\n taskId: input.parsedTask.taskId,\n ts: new Date().toISOString(),\n },\n io: input.ledgerIo,\n paths: input.ledgerPaths,\n });\n\n return {\n agentContextLifecycleCounters: state.agentContextLifecycleCounters,\n deduped: false,\n dispatchResult: {\n adapterResult: {\n ...(input.agentControllerConversationId\n ? {\n contextDelta: {\n ...(input.agentControllerConversation\n ? {\n agentControllerConversation:\n input.agentControllerConversation,\n }\n : {}),\n agentControllerConversationId:\n input.agentControllerConversationId,\n },\n }\n : {}),\n output: resultPayload.output,\n status: \"success\",\n },\n dispatched: true,\n reason: \"dispatched\",\n },\n resultPayload,\n runtimeState: \"idle\",\n state,\n };\n}\n\nasync function applyCliSpaceActionRecordIfPresent(input: {\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeResult: RuntimeTaskResult;\n}): Promise<RuntimeTaskResult> {\n if (!input.dispatchSpaceActionContext) {\n return input.runtimeResult;\n }\n const readResult = await readCliSpaceActionRecordWithGrace({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n graceMs: CLI_SPACE_ACTION_RECORD_RUNTIME_COMPLETION_GRACE_MS,\n });\n if (readResult.status === \"missing\") {\n return input.runtimeResult;\n }\n if (readResult.status === \"invalid\") {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.cli_space_action_invalid\",\n text: `CLI OpenMeld Space Action record ignored for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: readResult.errorMessage,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return input.runtimeResult;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.cli_space_action_recorded\",\n text: `CLI OpenMeld Space Action recorded for task ${input.parsedTask.taskId}`,\n payload: {\n command: readResult.record.command,\n dispatchId: input.parsedTask.dispatchId,\n spaceActionType: readResult.record.action.type,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n return applyCliSpaceActionRecordToRuntimeResult({\n record: readResult.record,\n runtimeResult: input.runtimeResult,\n });\n}\n\nasync function resolveAlreadyCompletedRuntimeResultAfterCliSpaceAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): Promise<RuntimeTaskResult | null> {\n try {\n const result = await Promise.race([\n input.runtimeExecutionPromise.then((runtimeResult) => ({\n runtimeResult,\n status: \"runtime\" as const,\n })),\n delay(0).then(() => ({\n status: \"pending\" as const,\n })),\n ]);\n if (result.status === \"runtime\") {\n return result.runtimeResult;\n }\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_ignored_after_cli_space_action\",\n text: `runtime failed after CLI OpenMeld Space Action finalized task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n }\n return null;\n}\n\nfunction observeRuntimeResultAfterCliSpaceAction(input: {\n onRuntimeResultAfterCliSpaceAction?: (\n runtimeResult: RuntimeTaskResult\n ) => Promise<void> | void;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): void {\n input.runtimeExecutionPromise\n .then(async (runtimeResult) => {\n await input.onRuntimeResultAfterCliSpaceAction?.(runtimeResult);\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_ignored_after_cli_space_action\",\n text: `runtime failed after CLI OpenMeld Space Action finalized task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n });\n}\n\nfunction applyCliSpaceActionRecordToRuntimeResult(input: {\n record: DispatchSpaceActionRecord;\n runtimeResult: RuntimeTaskResult;\n}): RuntimeTaskResult {\n return {\n ...input.runtimeResult,\n resultPayload: buildCliSpaceActionSuccessPayload({\n basePayload: input.runtimeResult.resultPayload,\n record: input.record,\n }),\n };\n}\n\nfunction buildCliSpaceActionSuccessPayload(input: {\n basePayload: Pick<\n OpenMeldDaemonTaskResultPayload,\n \"agentId\" | \"attemptId\" | \"deduped\" | \"sourceEventId\" | \"taskId\"\n > &\n Partial<\n Pick<\n OpenMeldDaemonTaskResultPayload,\n | \"agentControllerConversation\"\n | \"agentControllerConversationId\"\n | \"agentControllerRef\"\n | \"bootstrapTemplateFacts\"\n | \"dispatchExecution\"\n | \"effectiveRuntimeWorkingDirectory\"\n | \"openClawBinding\"\n | \"openClawGatewayVisibility\"\n | \"promptTrace\"\n | \"runtimeWorkspaceFingerprint\"\n | \"telemetry\"\n | \"transportMode\"\n >\n >;\n record: DispatchSpaceActionRecord;\n}): Extract<OpenMeldDaemonTaskResultPayload, { status: \"success\" }> {\n const output = resolveStructuredActionOutputFallback({\n action: input.record.action,\n cleanedOutput: \"\",\n });\n return {\n agentId: input.basePayload.agentId,\n attemptId: input.basePayload.attemptId,\n deduped: input.basePayload.deduped,\n sourceEventId: input.basePayload.sourceEventId,\n taskId: input.basePayload.taskId,\n ...(input.basePayload.agentControllerConversation\n ? {\n agentControllerConversation:\n input.basePayload.agentControllerConversation,\n }\n : {}),\n ...(input.basePayload.agentControllerConversationId\n ? {\n agentControllerConversationId:\n input.basePayload.agentControllerConversationId,\n }\n : {}),\n ...(input.basePayload.agentControllerRef\n ? { agentControllerRef: input.basePayload.agentControllerRef }\n : {}),\n ...(input.basePayload.bootstrapTemplateFacts\n ? { bootstrapTemplateFacts: input.basePayload.bootstrapTemplateFacts }\n : {}),\n ...(input.basePayload.dispatchExecution\n ? { dispatchExecution: input.basePayload.dispatchExecution }\n : {}),\n ...(input.basePayload.effectiveRuntimeWorkingDirectory\n ? {\n effectiveRuntimeWorkingDirectory:\n input.basePayload.effectiveRuntimeWorkingDirectory,\n }\n : {}),\n ...(input.basePayload.openClawBinding\n ? { openClawBinding: input.basePayload.openClawBinding }\n : {}),\n ...(input.basePayload.openClawGatewayVisibility\n ? {\n openClawGatewayVisibility:\n input.basePayload.openClawGatewayVisibility,\n }\n : {}),\n ...(input.basePayload.promptTrace\n ? { promptTrace: input.basePayload.promptTrace }\n : {}),\n ...(input.basePayload.runtimeWorkspaceFingerprint\n ? {\n runtimeWorkspaceFingerprint:\n input.basePayload.runtimeWorkspaceFingerprint,\n }\n : {}),\n ...(input.basePayload.telemetry\n ? { telemetry: input.basePayload.telemetry }\n : {}),\n ...(input.basePayload.transportMode\n ? { transportMode: input.basePayload.transportMode }\n : {}),\n output,\n spaceAction: input.record.action,\n spaceActionProvenance: \"cli_action\",\n status: \"success\",\n };\n}\n\nasync function readCliSpaceActionRecordWithGrace(input: {\n dispatchSpaceActionContext: DispatchSpaceActionContext;\n graceMs: number;\n}): Promise<DispatchSpaceActionRecordReadResult> {\n const immediateRead = readDispatchSpaceActionRecord({\n context: input.dispatchSpaceActionContext,\n });\n if (immediateRead.status !== \"missing\" || input.graceMs <= 0) {\n return immediateRead;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), input.graceMs);\n try {\n const completion = await waitForCliSpaceActionRecord({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n signal: abortController.signal,\n });\n if (completion.kind === \"cli_space_action_recorded\") {\n return {\n record: completion.record,\n status: \"loaded\",\n };\n }\n if (completion.kind === \"cli_space_action_invalid\") {\n return {\n errorMessage: completion.errorMessage,\n status: \"invalid\",\n };\n }\n return { status: \"missing\" };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function resolveRuntimeResultStructuredSpaceAction(input: {\n onInteractionRequest?: Parameters<\n typeof runRuntimeTask\n >[0][\"onInteractionRequest\"];\n onNativeTurnStarted: () => Promise<void>;\n onNativeTurnCompleted: (result: RuntimeTaskResult) => void;\n onRuntimeEvent?: Parameters<typeof runRuntimeTask>[0][\"onRuntimeEvent\"];\n agentReplyObservationCursor?: string | null;\n allowConcurrentReplyReconsideration?: boolean;\n cliEntry?: string | null;\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n controllerTurnCompletion: Promise<void>;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n instructionPrompt?: AdapterInstructionPrompt;\n parsedTask: ParsedDispatchTask;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n presenter: Presenter;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n runtimeContext: ProviderDispatchRuntimeContext;\n runtimeEnvOverrides?: Record<string, string | undefined>;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): Promise<{\n runtimeResult: RuntimeTaskResult;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n resolvedSpaceActionProvenance: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n}> {\n let runtimeResult = input.runtimeResult;\n let structuredSpaceActionResolution =\n resolveStructuredSpaceActionFromRuntimePayload(runtimeResult);\n const runtimePayloadSpaceAction = runtimeResult.resultPayload.spaceAction;\n const publicationRequirement = resolveSpacePublicationRequirement(\n input.parsedTask.spaceContractSnapshot\n );\n const requiresStructuredSpaceAction =\n publicationRequirement.requiresExplicitPublicAction;\n let repairFailureDiagnostics: StructuredActionFailureDiagnostics | null =\n null;\n const initialStructuredActionFailure =\n resolveStructuredActionRequirementFailure({\n requiresStructuredSpaceAction,\n resolution: runtimePayloadSpaceAction\n ? { action: runtimePayloadSpaceAction, parseError: null }\n : structuredSpaceActionResolution,\n runtimeResult,\n });\n\n if (initialStructuredActionFailure?.kind === \"preserve_runtime_failure\") {\n return {\n runtimeResult,\n resolvedSpaceAction: undefined,\n resolvedSpaceActionProvenance: undefined,\n };\n }\n\n if (initialStructuredActionFailure?.kind === \"repair\") {\n const repairResult = await maybeRepairStructuredSpaceAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n runtimeResult,\n sendTargetReference: input.sendTargetReference,\n failureReason: initialStructuredActionFailure.failureReason,\n cliEntry: input.cliEntry,\n runControllerRepair: ({ prompt, runtimeResult }) => {\n const repairContinuation = resolveStructuredActionRepairContinuation({\n runtimeResult,\n agentControllerConversationOverride:\n input.agentControllerConversationOverride,\n });\n return runDispatchRuntimeExecution({\n onInteractionRequest: input.onInteractionRequest,\n onNativeTurnStarted: input.onNativeTurnStarted,\n onNativeTurnCompleted: input.onNativeTurnCompleted,\n onRuntimeEvent: input.onRuntimeEvent,\n computerFileAccessBoundary: input.computerFileAccessBoundary,\n contextId: repairContinuation.contextId,\n executionMode: \"repair\",\n io: input.ledgerIo,\n ledgerPaths: input.ledgerPaths,\n instructionPrompt: input.instructionPrompt\n ? {\n ...input.instructionPrompt,\n userPrompt: prompt,\n }\n : undefined,\n parsedTask: input.parsedTask,\n prompt,\n routeConfig: input.routeConfig,\n runtimeContext: input.runtimeContext,\n runtimeEnvOverrides: input.runtimeEnvOverrides,\n runtimeControllerSupport: input.runtimeControllerSupport,\n streamingModeOverride: \"final\",\n agentControllerConversationOverride:\n repairContinuation.agentControllerConversationOverride,\n });\n },\n });\n repairFailureDiagnostics = repairResult.finalFailureDiagnostics;\n if (repairResult.runtimeResult) {\n runtimeResult = repairResult.runtimeResult;\n structuredSpaceActionResolution =\n resolveStructuredSpaceActionFromRuntimePayload(runtimeResult);\n }\n }\n\n let resolvedSpaceAction =\n runtimeResult.resultPayload.spaceAction ??\n structuredSpaceActionResolution.action;\n const resolvedSpaceActionProvenance = resolveStructuredSpaceActionProvenance({\n runtimeResult,\n resolvedSpaceAction,\n });\n const normalizedAction = normalizeResolvedStructuredSpaceAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n resolvedSpaceAction,\n runtimeResult,\n sendTargetReference: input.sendTargetReference,\n structuredSpaceActionResolution,\n });\n resolvedSpaceAction = normalizedAction.resolvedSpaceAction;\n\n const finalStructuredActionFailure = normalizedAction.failureReason\n ? {\n failureReason: normalizedAction.failureReason,\n kind: \"repair\" as const,\n }\n : resolveStructuredActionRequirementFailure({\n requiresStructuredSpaceAction,\n resolution: {\n ...structuredSpaceActionResolution,\n action: resolvedSpaceAction,\n parseError: runtimeResult.resultPayload.spaceAction\n ? null\n : structuredSpaceActionResolution.parseError,\n },\n runtimeResult,\n });\n if (finalStructuredActionFailure?.kind === \"preserve_runtime_failure\") {\n return {\n runtimeResult,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n }\n if (finalStructuredActionFailure?.kind === \"repair\") {\n const diagnostics =\n repairFailureDiagnostics ??\n resolveStructuredActionFailureDiagnostics({\n carrierKind: structuredSpaceActionResolution.carrierKind,\n parseError: structuredSpaceActionResolution.parseError,\n publicFailureReason: finalStructuredActionFailure.failureReason,\n repairMode: \"required_check\",\n runtimeResult,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_required_failed\",\n text: `OpenMeld Space action requirement failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason: finalStructuredActionFailure.failureReason,\n ...diagnostics,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n runtimeResult: {\n ...runtimeResult,\n resultPayload: coerceRuntimeResultToStructuredActionFailure({\n diagnostics,\n failureReason: finalStructuredActionFailure.failureReason,\n runtimeResult,\n }),\n },\n resolvedSpaceAction: undefined,\n resolvedSpaceActionProvenance: undefined,\n };\n }\n\n if (\n runtimeResult.resultPayload.status !== \"success\" &&\n runtimeResult.resultPayload.status !== \"partial_success\"\n ) {\n return {\n runtimeResult,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n }\n\n if (\n input.allowConcurrentReplyReconsideration !== false &&\n resolvedSpaceAction?.type === \"post_message\"\n ) {\n return await coordinateConcurrentAgentReply({\n ...input,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n runtimeResult,\n });\n }\n\n const shouldPreserveCliActionOutput =\n runtimeResult.resultPayload.spaceActionProvenance === \"cli_action\";\n const shouldApplyStructuredActionResolution =\n runtimeResult.resultPayload.spaceAction !== resolvedSpaceAction ||\n runtimeResult.resultPayload.spaceActionProvenance !==\n resolvedSpaceActionProvenance ||\n (!shouldPreserveCliActionOutput &&\n typeof structuredSpaceActionResolution.cleanedOutput === \"string\" &&\n structuredSpaceActionResolution.cleanedOutput !==\n runtimeResult.resultPayload.output);\n if (!shouldApplyStructuredActionResolution) {\n return {\n runtimeResult,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n }\n\n return {\n runtimeResult: applyStructuredSpaceActionResolutionToRuntimePayload({\n runtimeResult,\n resolution: {\n ...structuredSpaceActionResolution,\n action: resolvedSpaceAction,\n spaceActionProvenance: resolvedSpaceActionProvenance,\n },\n }),\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n}\n\nasync function coordinateConcurrentAgentReply(input: {\n onInteractionRequest?: Parameters<\n typeof runRuntimeTask\n >[0][\"onInteractionRequest\"];\n onNativeTurnStarted: () => Promise<void>;\n onNativeTurnCompleted: (result: RuntimeTaskResult) => void;\n onRuntimeEvent?: Parameters<typeof runRuntimeTask>[0][\"onRuntimeEvent\"];\n agentReplyObservationCursor?: string | null;\n cliEntry?: string | null;\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n controllerTurnCompletion: Promise<void>;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n instructionPrompt?: AdapterInstructionPrompt;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n resolvedSpaceAction: Extract<\n NonNullable<OpenMeldDaemonTaskResultPayload[\"spaceAction\"]>,\n { type: \"post_message\" }\n >;\n resolvedSpaceActionProvenance: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeContext: ProviderDispatchRuntimeContext;\n runtimeEnvOverrides?: Record<string, string | undefined>;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): Promise<{\n runtimeResult: RuntimeTaskResult;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n resolvedSpaceActionProvenance: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n}> {\n const requestContext = buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n ownerUserId: input.profileOwnerUserId,\n profileKind: \"agent\",\n profileName:\n input.parsedTask.targetProfileName ??\n input.parsedTask.targetProfileMentionLabel ??\n input.parsedTask.targetProfileId,\n openMeldProfileId: input.parsedTask.targetProfileId,\n ...(input.profileOwnerName ? { ownerName: input.profileOwnerName } : {}),\n },\n });\n const readObservation = async (\n observedThroughSignalId: string\n ): Promise<DispatchAgentReplyObservation> => {\n try {\n return await readDispatchAgentReplyObservation({\n currentWakeTargetProfileIds:\n input.parsedTask.sourceMessageEnvelope?.activationTargets,\n requestContext,\n sourceSignalId: observedThroughSignalId,\n spaceId: input.parsedTask.spaceId,\n spacePassword: input.parsedTask.spacePassword,\n threadContext: input.parsedTask.threadContext,\n wakeSourceSignalId: input.parsedTask.sourceEventId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_reply_observation_unavailable\",\n text: `Agent reply observation unavailable for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n observedThroughSignalId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_observation.unavailable\",\n message: `OpenMeld could not read the Space context before publishing the Agent reply: ${toErrorMessage(error)}`,\n });\n }\n };\n let observation: DispatchAgentReplyObservation;\n try {\n observation = await readObservation(\n normalizeOptionalText(input.agentReplyObservationCursor) ??\n input.parsedTask.sourceEventId\n );\n } catch (error) {\n if (input.agentReplyObservationCursor) {\n throw error;\n }\n // Preserve the first proposal using only the context actually delivered\n // with the Wake. Space's atomic publication guard still checks this cursor\n // after durable replay and can require review before publishing anything.\n const action = attachAgentReplyObservation({\n action: input.resolvedSpaceAction,\n observedThroughSignalId: input.parsedTask.sourceEventId,\n });\n return {\n resolvedSpaceAction: action,\n resolvedSpaceActionProvenance: input.resolvedSpaceActionProvenance,\n runtimeResult: applyStructuredSpaceActionResolutionToRuntimePayload({\n resolution: {\n action,\n parseError: null,\n spaceActionProvenance: input.resolvedSpaceActionProvenance,\n },\n runtimeResult: input.runtimeResult,\n }),\n };\n }\n\n const coordinated = await coordinateDispatchAgentReply({\n action: input.resolvedSpaceAction,\n originalWake: {\n sourceSignalId: input.parsedTask.sourceEventId,\n targetProfileId: input.parsedTask.targetProfileId,\n text: input.parsedTask.prompt,\n },\n currentValue: {\n provenance: input.resolvedSpaceActionProvenance,\n runtimeResult: input.runtimeResult,\n },\n observation,\n reconsider: async (prompt, currentObservation) => {\n const reconsiderationStartedAtMs = Date.now();\n const recordReconsideration = (result: string) =>\n emitDaemonDispatchJournalEvent({\n type: \"dispatch.reply_reconsideration\",\n dispatchId: input.parsedTask.dispatchId,\n profileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n result,\n metadata: {\n reason: \"new_relevant_space_signal\",\n newerSignalCount: currentObservation.relevantSignals.length,\n observedThroughSignalId: currentObservation.observedThroughSignalId,\n triggeringSignalIds: currentObservation.relevantSignals.map(\n (signal) => signal.id\n ),\n startedAtMs: reconsiderationStartedAtMs,\n durationMs: Math.max(0, Date.now() - reconsiderationStartedAtMs),\n },\n });\n recordReconsideration(\"started\");\n try {\n const continuation = resolveStructuredActionRepairContinuation({\n agentControllerConversationOverride:\n input.agentControllerConversationOverride,\n runtimeResult: input.runtimeResult,\n });\n if (\n !(\n continuation.contextId ||\n continuation.agentControllerConversationOverride\n )\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_reconsideration.conversation_unavailable\",\n message:\n \"The Space changed, but the exact Agent conversation is unavailable for reply reconsideration.\",\n });\n }\n await input.controllerTurnCompletion;\n const activeTask = input.inflightTaskControlRegistry.getTask(\n input.parsedTask.taskId\n );\n if (\n activeTask?.dispatchId !== input.parsedTask.dispatchId ||\n activeTask.runtimeCoordinatorExecutionId !==\n input.parsedTask.runtimeCoordinatorExecutionId\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_reconsideration.execution_inactive\",\n message:\n \"The Wake stopped before the Agent could reconsider its reply.\",\n });\n }\n if (input.dispatchSpaceActionContext) {\n supersedeDispatchSpaceActionRecordForReconsideration({\n context: input.dispatchSpaceActionContext,\n });\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_reply_reconsideration_started\",\n text: `Agent reply reconsideration started for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n newerSignalCount: currentObservation.relevantSignals.length,\n observedThroughSignalId: currentObservation.observedThroughSignalId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n let runtimeResult = await runDispatchRuntimeExecution({\n onInteractionRequest: input.onInteractionRequest,\n onNativeTurnStarted: input.onNativeTurnStarted,\n onNativeTurnCompleted: input.onNativeTurnCompleted,\n onRuntimeEvent: input.onRuntimeEvent,\n agentControllerConversationOverride:\n continuation.agentControllerConversationOverride,\n computerFileAccessBoundary: input.computerFileAccessBoundary,\n contextId: continuation.contextId,\n executionMode: \"repair\",\n instructionPrompt: input.instructionPrompt\n ? {\n ...input.instructionPrompt,\n userPrompt: prompt,\n }\n : undefined,\n io: input.ledgerIo,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n prompt,\n routeConfig: input.routeConfig,\n runtimeContext: input.runtimeContext,\n runtimeEnvOverrides: input.runtimeEnvOverrides,\n runtimeControllerSupport: input.runtimeControllerSupport,\n streamingModeOverride: \"final\",\n });\n runtimeResult = await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult,\n });\n const reconsidered = await resolveRuntimeResultStructuredSpaceAction({\n ...input,\n agentControllerConversationOverride:\n continuation.agentControllerConversationOverride,\n allowConcurrentReplyReconsideration: false,\n runtimeResult,\n });\n if (!reconsidered.resolvedSpaceAction) {\n if (reconsidered.runtimeResult.resultPayload.status === \"failed\") {\n return {\n action: undefined,\n value: {\n provenance: undefined,\n runtimeResult: reconsidered.runtimeResult,\n },\n };\n }\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_reconsideration.action_missing\",\n message:\n \"The Agent did not return a valid Space action after reviewing newer messages.\",\n });\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_reply_reconsideration_completed\",\n text: `Agent reply reconsideration completed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n observedThroughSignalId: currentObservation.observedThroughSignalId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n action: reconsidered.resolvedSpaceAction,\n value: {\n provenance: \"controller_repair\" as const,\n runtimeResult: reconsidered.runtimeResult,\n },\n };\n } finally {\n recordReconsideration(\"finished\");\n }\n },\n refreshObservation: readObservation,\n spaceId: input.parsedTask.spaceId,\n });\n return {\n resolvedSpaceAction: coordinated.action,\n resolvedSpaceActionProvenance: coordinated.value.provenance,\n runtimeResult: applyStructuredSpaceActionResolutionToRuntimePayload({\n resolution: {\n action: coordinated.action,\n parseError: null,\n spaceActionProvenance: coordinated.value.provenance,\n },\n runtimeResult: coordinated.value.runtimeResult,\n }),\n };\n}\n\nfunction normalizeResolvedStructuredSpaceAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n structuredSpaceActionResolution: ReturnType<\n typeof resolveStructuredSpaceActionFromRuntimePayload\n >;\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const postMessageResult = normalizeResolvedPostMessageAction(input);\n if (postMessageResult.failureReason) {\n return postMessageResult;\n }\n const postStatusResult = normalizeResolvedPostStatusAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n resolvedSpaceAction: postMessageResult.resolvedSpaceAction,\n });\n if (postStatusResult.failureReason) {\n return postStatusResult;\n }\n\n return normalizeResolvedThreadAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n resolvedSpaceAction: postStatusResult.resolvedSpaceAction,\n });\n}\n\nfunction normalizeResolvedPostMessageAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n structuredSpaceActionResolution: ReturnType<\n typeof resolveStructuredSpaceActionFromRuntimePayload\n >;\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const action = input.resolvedSpaceAction;\n if (action?.type !== \"post_message\") {\n return { failureReason: null, resolvedSpaceAction: action };\n }\n\n try {\n const normalizedPostMessageAction = normalizeDispatchPostMessageAction({\n action,\n currentReplyToSignalId:\n input.parsedTask.replyToSnapshot?.signalId ?? null,\n inputKind: \"direct_payload\",\n sendTargetReference: input.sendTargetReference,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.post_message_normalized\",\n text: `post_message normalized for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n ...normalizedPostMessageAction.tracePayload,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n failureReason: null,\n resolvedSpaceAction: normalizedPostMessageAction.action,\n };\n } catch (error) {\n const failureReason = toErrorMessage(error);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.post_message_validation_rejected\",\n text: `post_message validation rejected for task ${input.parsedTask.taskId}`,\n payload: {\n activationTargetsCount: action.messageEnvelope.activationTargets.length,\n dispatchId: input.parsedTask.dispatchId,\n failureReason,\n inputKind: \"direct_payload\",\n memberDirectoryLoaded: input.sendTargetReference.status === \"loaded\",\n mentionTargetsCount: action.messageEnvelope.mentionTargets?.length ?? 0,\n referenceTargetsCount: action.messageEnvelope.referenceTargets.length,\n replyToSignalIdResolved: Boolean(\n action.messageEnvelope.replyToSignalId\n ),\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return { failureReason, resolvedSpaceAction: undefined };\n }\n}\n\nfunction normalizeResolvedPostStatusAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const action = input.resolvedSpaceAction;\n if (action?.type !== \"post_status\" || action.status !== \"working\") {\n return { failureReason: null, resolvedSpaceAction: action };\n }\n\n const failureReason =\n \"post_status working is not allowed for a final OpenMeld Space Action. Use done, blocked, needs_input, handoff, post_message, or stay_silent.\";\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.post_status_validation_rejected\",\n text: `post_status validation rejected for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason,\n status: action.status,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return { failureReason, resolvedSpaceAction: undefined };\n}\n\nfunction normalizeResolvedThreadAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const action = input.resolvedSpaceAction;\n if (!(action?.type === \"post_message\" || action?.type === \"post_status\")) {\n return { failureReason: null, resolvedSpaceAction: action };\n }\n\n try {\n return {\n failureReason: null,\n resolvedSpaceAction: normalizeDispatchThreadAction({\n action,\n threadContext: input.parsedTask.threadContext,\n }),\n };\n } catch (error) {\n const failureReason = toErrorMessage(error);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.thread_action_validation_rejected\",\n text: `thread action validation rejected for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n threadId: input.parsedTask.threadContext?.threadId ?? null,\n },\n });\n return { failureReason, resolvedSpaceAction: undefined };\n }\n}\n\nasync function maybeRepairStructuredSpaceAction(input: {\n cliEntry?: string | null;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n failureReason: string;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runControllerRepair?: (input: {\n prompt: string;\n runtimeResult: RuntimeTaskResult;\n }) => Promise<RuntimeTaskResult>;\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n}): Promise<StructuredActionRepairResult> {\n if (!input.failureReason) {\n return {\n finalFailureDiagnostics: null,\n runtimeResult: null,\n };\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_started\",\n text: `structured OpenMeld Space action repair started for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason: input.failureReason,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n const skillRepair = await ensureDispatchControllerOpenMeldSkill({\n agentControllerRef: input.parsedTask.agentControllerRef,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.dispatch_controller_skill_repair_checked\",\n text: `OpenMeld skill repair checked for task ${input.parsedTask.taskId}`,\n payload: {\n agentControllerRef: input.parsedTask.agentControllerRef,\n agentId: skillRepair.agentId,\n dispatchId: input.parsedTask.dispatchId,\n ...(skillRepair.reason ? { reason: skillRepair.reason } : {}),\n status: skillRepair.status,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n if (!input.runControllerRepair) {\n return {\n finalFailureDiagnostics: resolveStructuredActionFailureDiagnostics({\n carrierKind: \"none\",\n parseError: input.failureReason,\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult: input.runtimeResult,\n }),\n runtimeResult: null,\n };\n }\n\n let providerRepairRuntimeResult: RuntimeTaskResult;\n try {\n providerRepairRuntimeResult = await input.runControllerRepair({\n prompt: buildStructuredActionRepairPrompt({\n cliEntry: input.cliEntry,\n currentReplyToSignalId: input.parsedTask.replyToSnapshot?.signalId,\n parseError: input.failureReason,\n previousOutput: resolveStructuredActionRepairPreviousOutput(\n input.runtimeResult\n ),\n sendTargetReferenceLines: input.sendTargetReference.referenceLines,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n spaceId: input.parsedTask.spaceId,\n }),\n runtimeResult: input.runtimeResult,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_failed\",\n text: `structured OpenMeld Space action repair failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n ...resolveStructuredActionFailureDiagnostics({\n carrierKind: \"none\",\n parseError: toErrorMessage(error),\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult: input.runtimeResult,\n }),\n failureReason: input.failureReason,\n repairedRuntimeStatus: \"failed\",\n repairedStructuredActionPresent: false,\n repairMode: \"controller_roundtrip\",\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n finalFailureDiagnostics: resolveStructuredActionFailureDiagnostics({\n carrierKind: \"none\",\n parseError: toErrorMessage(error),\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult: input.runtimeResult,\n }),\n runtimeResult: null,\n };\n }\n\n providerRepairRuntimeResult = await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult: providerRepairRuntimeResult,\n });\n\n const providerRepairEvaluation = resolveStructuredActionRepairEvaluation({\n runtimeResult: providerRepairRuntimeResult,\n });\n if (\n !(\n providerRepairEvaluation.accepted &&\n providerRepairEvaluation.runtimeResult\n )\n ) {\n const providerFailureDiagnostics =\n resolveStructuredActionFailureDiagnostics({\n carrierKind: providerRepairEvaluation.carrierKind,\n parseError: providerRepairEvaluation.parseError,\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult:\n providerRepairEvaluation.runtimeResult ?? providerRepairRuntimeResult,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_failed\",\n text: `structured OpenMeld Space action repair failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n ...providerFailureDiagnostics,\n failureReason: input.failureReason,\n repairedRuntimeStatus: providerRepairEvaluation.repairedRuntimeStatus,\n repairedStructuredActionPresent:\n providerRepairEvaluation.repairedStructuredActionPresent,\n repairMode: \"controller_roundtrip\",\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n finalFailureDiagnostics: providerFailureDiagnostics,\n runtimeResult: null,\n };\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_completed\",\n text: `structured OpenMeld Space action repair completed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n repaired: true,\n repairMode: \"controller_roundtrip\",\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n finalFailureDiagnostics: null,\n runtimeResult: applyStructuredSpaceActionProvenanceToRuntimeResult({\n runtimeResult: providerRepairEvaluation.runtimeResult,\n provenance: \"controller_repair\",\n }),\n };\n}\n\nfunction resolveStructuredActionRepairEvaluation(input: {\n runtimeResult: RuntimeTaskResult;\n}): {\n accepted: boolean;\n carrierKind: StructuredActionFailureDiagnostics[\"carrierKind\"];\n parseError: string | null;\n repairedRuntimeStatus: RuntimeTaskResult[\"resultPayload\"][\"status\"];\n repairedStructuredActionPresent: boolean;\n runtimeResult: RuntimeTaskResult | null;\n} {\n const runtimeResult = input.runtimeResult;\n const repairedResolution =\n resolveStructuredSpaceActionFromRuntimePayload(runtimeResult);\n const repairedAction =\n runtimeResult.resultPayload.spaceAction ?? repairedResolution.action;\n const repairedRuntimeStatus = runtimeResult.resultPayload.status;\n const accepted =\n (repairedRuntimeStatus === \"success\" ||\n repairedRuntimeStatus === \"partial_success\") &&\n repairedResolution.parseError === null &&\n repairedAction !== undefined;\n\n return {\n accepted,\n carrierKind: repairedResolution.carrierKind,\n parseError: repairedResolution.parseError,\n repairedRuntimeStatus,\n repairedStructuredActionPresent: repairedAction !== undefined,\n runtimeResult,\n };\n}\n\nfunction resolveStructuredActionFailureDiagnostics(input: {\n carrierKind: StructuredActionFailureDiagnostics[\"carrierKind\"];\n parseError: string | null;\n publicFailureReason?: string | null;\n repairMode: StructuredActionFailureDiagnostics[\"repairMode\"];\n runtimeResult: RuntimeTaskResult;\n}): StructuredActionFailureDiagnostics {\n return {\n carrierKind: input.carrierKind,\n invalidOutputPreview: buildInvalidStructuredActionOutputPreview(\n input.runtimeResult\n ),\n publicFailureReason: normalizeOptionalText(input.publicFailureReason),\n repairMode: input.repairMode,\n spaceActionCandidatePresent: input.carrierKind !== \"none\",\n spaceActionParseError: normalizeOptionalText(input.parseError),\n };\n}\n\nfunction maybeRejectDispatchPreflight(input: {\n activeLeaseEpoch: number | undefined;\n correlation: DispatchCorrelation;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n parsedTask: ReturnType<typeof parseDispatchTask>;\n ledgerPaths: LedgerPaths;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n const staleLeaseResult = maybeRejectStaleLease({\n activeLeaseEpoch: input.activeLeaseEpoch,\n correlation: input.correlation,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n socket: input.socket,\n });\n if (staleLeaseResult) {\n return staleLeaseResult;\n }\n\n return maybeRejectInvalidDispatchTask({\n correlation: input.correlation,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n socket: input.socket,\n });\n}\n\nfunction resolveStructuredSpaceActionFromRuntimePayload(\n runtimeResult: RuntimeTaskResult\n): {\n action: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n carrierKind: StructuredActionFailureDiagnostics[\"carrierKind\"];\n cleanedOutput?: string;\n parseError: string | null;\n} {\n const payload = runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return {\n action: undefined,\n carrierKind: \"none\",\n cleanedOutput: undefined,\n parseError: null,\n };\n }\n\n return {\n action: payload.spaceAction,\n carrierKind: \"none\",\n cleanedOutput: undefined,\n parseError: null,\n };\n}\n\nfunction applyStructuredSpaceActionResolutionToRuntimePayload(input: {\n runtimeResult: RuntimeTaskResult;\n resolution: {\n action: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n cleanedOutput?: string;\n parseError: string | null;\n spaceActionProvenance?: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n };\n}): RuntimeTaskResult {\n const payload = input.runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return input.runtimeResult;\n }\n\n return {\n ...input.runtimeResult,\n resultPayload: {\n ...payload,\n output: input.resolution.cleanedOutput ?? payload.output,\n ...(input.resolution.action\n ? { spaceAction: input.resolution.action }\n : {}),\n ...(input.resolution.action && input.resolution.spaceActionProvenance\n ? { spaceActionProvenance: input.resolution.spaceActionProvenance }\n : {}),\n },\n };\n}\n\nfunction applyStructuredSpaceActionProvenanceToRuntimeResult(input: {\n runtimeResult: RuntimeTaskResult;\n provenance: NonNullable<\n OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"]\n >;\n}): RuntimeTaskResult {\n const payload = input.runtimeResult.resultPayload;\n if (\n (payload.status !== \"success\" && payload.status !== \"partial_success\") ||\n !payload.spaceAction\n ) {\n return input.runtimeResult;\n }\n\n return {\n ...input.runtimeResult,\n resultPayload: {\n ...payload,\n spaceActionProvenance: payload.spaceActionProvenance ?? input.provenance,\n },\n };\n}\n\nfunction resolveStructuredSpaceActionProvenance(input: {\n runtimeResult: RuntimeTaskResult;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n}): OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"] {\n if (!input.resolvedSpaceAction) {\n return undefined;\n }\n return input.runtimeResult.resultPayload.spaceActionProvenance ?? \"direct\";\n}\n\ntype DispatchRuntimeRoute = NonNullable<\n Parameters<typeof runRuntimeTask>[0][\"route\"]\n>;\ntype DispatchRuntimeTask = Parameters<typeof runRuntimeTask>[0][\"task\"];\n\nasync function runDispatchRuntimeExecution(input: {\n onNativeTurnStarted: () => Promise<void>;\n onNativeTurnCompleted: (result: RuntimeTaskResult) => void;\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n contextId: string | null;\n executionMode: AdapterDispatchExecutionMode;\n io: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n onInteractionRequest?: Parameters<\n typeof runRuntimeTask\n >[0][\"onInteractionRequest\"];\n onPreview?: Parameters<typeof runRuntimeTask>[0][\"onPreview\"];\n onRuntimeEvent?: Parameters<typeof runRuntimeTask>[0][\"onRuntimeEvent\"];\n parsedTask: ParsedDispatchTask;\n instructionPrompt?: AdapterInstructionPrompt;\n prompt: string;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeContext: ProviderDispatchRuntimeContext;\n runtimeEnvOverrides?: Record<string, string | undefined>;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n streamingModeOverride?: DispatchRuntimeRoute[\"streamingMode\"];\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): Promise<Awaited<ReturnType<typeof runRuntimeTask>>> {\n await input.onNativeTurnStarted();\n const result = await runRuntimeTask({\n // Admission/continuation already selected the conversation. An explicit\n // null means start fresh, not permission to restore a retained ledger ID.\n agentContextOverride: {\n agentControllerConversationId: input.contextId,\n agentControllerConversationOverride:\n input.agentControllerConversationOverride ?? null,\n },\n io: input.io,\n ...(input.onInteractionRequest\n ? { onInteractionRequest: input.onInteractionRequest }\n : {}),\n ...(input.onPreview ? { onPreview: input.onPreview } : {}),\n ...(input.onRuntimeEvent ? { onRuntimeEvent: input.onRuntimeEvent } : {}),\n paths: input.ledgerPaths,\n route: buildDispatchRuntimeRoute({\n contextId: input.contextId,\n envOverrides: input.runtimeEnvOverrides,\n parsedTask: input.parsedTask,\n routeConfig: input.routeConfig,\n runtimeControllerSupport: input.runtimeControllerSupport,\n streamingMode:\n input.streamingModeOverride ?? input.parsedTask.streamingMode,\n }),\n task: buildDispatchRuntimeTask({\n computerFileAccessBoundary: input.computerFileAccessBoundary,\n executionMode: input.executionMode,\n instructionPrompt: input.instructionPrompt,\n parsedTask: input.parsedTask,\n prompt: input.prompt,\n runtimeContext: input.runtimeContext,\n }),\n });\n input.onNativeTurnCompleted(result);\n return result;\n}\n\nfunction buildDispatchRuntimeRoute(input: {\n contextId: string | null;\n envOverrides?: Record<string, string | undefined>;\n parsedTask: ParsedDispatchTask;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n streamingMode: DispatchRuntimeRoute[\"streamingMode\"];\n}): DispatchRuntimeRoute {\n const runtimeEnv: Record<string, string | undefined> = input.contextId\n ? {\n [input.parsedTask.contextIdMappingSpec.sourceField]: input.contextId,\n ...(input.envOverrides ?? {}),\n }\n : (input.envOverrides ?? {});\n return {\n contextIdMappingSpec: input.parsedTask.contextIdMappingSpec,\n agentControllerRef: input.parsedTask.agentControllerRef,\n controllerRuntimeAvailable: true,\n env: buildDispatchOwnedRuntimeEnv({\n dispatchId: input.parsedTask.dispatchId,\n targetProfileId: input.parsedTask.targetProfileId,\n env: runtimeEnv,\n spaceActionContextPath:\n runtimeEnv[OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV] ?? null,\n }),\n serviceHealthy: true,\n serviceInstalled: true,\n ...(input.routeConfig?.agentControllerPermissionMode\n ? {\n agentControllerPermissionMode:\n input.routeConfig.agentControllerPermissionMode,\n }\n : {}),\n ...(input.routeConfig?.conversationPolicy\n ? { conversationPolicy: input.routeConfig.conversationPolicy }\n : {}),\n ...(input.routeConfig?.openCodePermission\n ? { openCodePermission: input.routeConfig.openCodePermission }\n : {}),\n targets: [\n ...buildRuntimeRouteTargets({\n agentControllerRef: input.parsedTask.agentControllerRef,\n launchContract: input.routeConfig?.launchContract ?? null,\n runtimeControllerSupport: input.runtimeControllerSupport,\n }),\n ],\n streamingMode: input.streamingMode,\n transportMode: input.parsedTask.transportMode,\n view: \"agent\",\n };\n}\n\nfunction buildDispatchRuntimeTask(input: {\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n executionMode: AdapterDispatchExecutionMode;\n instructionPrompt?: AdapterInstructionPrompt;\n parsedTask: ParsedDispatchTask;\n prompt: string;\n runtimeContext: ProviderDispatchRuntimeContext;\n}): DispatchRuntimeTask {\n return {\n executionContext: input.parsedTask.executionContext,\n agentId: input.parsedTask.targetProfileId,\n attemptId: input.parsedTask.attemptId,\n bindingKey: `${input.parsedTask.spaceId}|${input.parsedTask.targetProfileId}`,\n ...(input.computerFileAccessBoundary\n ? { computerFileAccessBoundary: input.computerFileAccessBoundary }\n : {}),\n dispatchId: input.parsedTask.dispatchId,\n deliveryRecoveryReason:\n input.parsedTask.deliveryRecoveryReason ?? undefined,\n executionMode: input.executionMode,\n ...(input.instructionPrompt\n ? { instructionPrompt: input.instructionPrompt }\n : {}),\n mentioned: true,\n newSessionTitle:\n input.executionMode === \"normal\" &&\n input.parsedTask.agentControllerRef === \"builtin:codex\"\n ? buildDispatchSessionTitle(input.parsedTask)\n : undefined,\n prompt: input.prompt,\n runtimeContext: input.runtimeContext,\n sequence: input.parsedTask.sequence,\n sourceEventId: input.parsedTask.sourceEventId,\n spaceId: input.parsedTask.spaceId,\n taskId: input.parsedTask.taskId,\n triggerMode: input.parsedTask.triggerMode,\n };\n}\n\nfunction maybeRejectStaleLease(input: {\n activeLeaseEpoch: number | undefined;\n correlation: DispatchCorrelation;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n parsedTask: ReturnType<typeof parseDispatchTask>;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n if (\n input.activeLeaseEpoch === undefined ||\n input.activeLeaseEpoch === input.deliverRequest.leaseEpoch\n ) {\n return null;\n }\n\n return sendDispatchRejectionResult({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n dispatchId: input.correlation.dispatchId,\n ledgerPaths: input.ledgerPaths,\n payload: {\n attemptId: input.correlation.attemptId,\n agentControllerRef: input.parsedTask?.agentControllerRef ?? null,\n errorCode: \"daemon.session.stale_lease\",\n errorMessage:\n \"daemon.session.stale_lease: local lease epoch does not match deliver frame\",\n errorType: \"config\",\n sourceEventId: input.correlation.sourceEventId,\n targetProfileId: input.correlation.targetProfileId,\n taskId: input.correlation.taskId,\n },\n presenter: input.presenter,\n });\n}\n\nfunction maybeRejectInvalidDispatchTask(input: {\n correlation: DispatchCorrelation;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n parsedTask: ReturnType<typeof parseDispatchTask>;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n if (input.parsedTask) {\n return null;\n }\n\n return sendDispatchRejectionResult({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n dispatchId: input.correlation.dispatchId,\n ledgerPaths: input.ledgerPaths,\n payload: {\n attemptId: input.correlation.attemptId,\n agentControllerRef: input.correlation.agentControllerRef,\n errorCode: \"schema.invalid\",\n errorMessage:\n \"schema.invalid: daemon dispatch payload is invalid or missing required fields\",\n errorType: \"config\",\n sourceEventId: input.correlation.sourceEventId,\n targetProfileId: input.correlation.targetProfileId,\n taskId: input.correlation.taskId,\n },\n presenter: input.presenter,\n });\n}\n\nfunction resolveValidatedDispatchDeliveryInput(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n}):\n | {\n result: LocalExecutionSlotTaskResult;\n status: \"rejected\";\n }\n | {\n parsedTask: ParsedDispatchTask;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeControllerSupport: ReturnType<\n typeof resolveLocalRuntimeControllerSupport\n >;\n status: \"ready\";\n } {\n const routeConfig =\n input.routeByProfileId.get(input.deliverRequest.profileId) ?? null;\n const parsedTask = parseDispatchTask({\n deliverRequest: input.deliverRequest,\n fallbackRouteConfig: routeConfig,\n });\n const correlation = buildDispatchCorrelation({\n deliverRequest: input.deliverRequest,\n parsedTask,\n });\n const activeLeaseEpoch = input.leasesByProfileId.get(\n input.deliverRequest.profileId\n );\n const preflightRejectionResult = maybeRejectDispatchPreflight({\n activeLeaseEpoch,\n correlation,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n presenter: input.presenter,\n socket: input.socket,\n });\n if (preflightRejectionResult) {\n return {\n result: preflightRejectionResult,\n status: \"rejected\",\n };\n }\n assertParsedDispatchTask(parsedTask);\n\n const runtimeControllerSupport = resolveLocalRuntimeControllerSupport({\n agentControllerRef: parsedTask.agentControllerRef,\n localAdapterContainer: input.localAdapterContainer,\n });\n\n return {\n parsedTask,\n routeConfig,\n runtimeControllerSupport,\n status: \"ready\",\n };\n}\n\nfunction assertParsedDispatchTask(\n parsedTask: ReturnType<typeof parseDispatchTask>\n): asserts parsedTask is ParsedDispatchTask {\n if (!parsedTask) {\n throw new Error(\"dispatch task unexpectedly missing after validation\");\n }\n}\n\nfunction assertSupportedRuntimeControllerSupport(\n runtimeControllerSupport: ReturnType<\n typeof resolveLocalRuntimeControllerSupport\n >\n): asserts runtimeControllerSupport is SupportedRuntimeControllerSupport {\n if (!runtimeControllerSupport.supported) {\n throw new Error(\n `runtime controller support unexpectedly missing after validation: ${runtimeControllerSupport.reasonDetail}`\n );\n }\n}\n\nfunction maybeRejectUnsupportedController(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeControllerSupport: ReturnType<\n typeof resolveLocalRuntimeControllerSupport\n >;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n if (input.runtimeControllerSupport.supported) {\n return null;\n }\n\n return sendDispatchRejectionResult({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n dispatchId: input.parsedTask.dispatchId,\n ledgerPaths: input.ledgerPaths,\n payload: {\n attemptId: input.parsedTask.attemptId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n errorCode: \"controller.kind.unsupported\",\n errorMessage: `controller.kind.unsupported: ${input.runtimeControllerSupport.reasonDetail}`,\n errorType: \"config\",\n sourceEventId: input.parsedTask.sourceEventId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n presenter: input.presenter,\n });\n}\n\nfunction sendDispatchRejectionResult(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n dispatchId: string;\n ledgerPaths: LedgerPaths;\n payload: DispatchRejectionPayloadInput;\n presenter: Presenter;\n}): LocalExecutionSlotTaskResult {\n const payload = buildFailedTaskResultPayload(input.payload);\n return sendResultAndSummarize({\n attemptId: input.payload.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionIdentityEcho: toRuntimeTransportResultIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: toRuntimeCoordinatorExecutionTokenEcho(\n input.deliverRequest\n ),\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n payload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId:\n input.deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: input.payload.taskId,\n }).resultSummary;\n}\n\nexport function buildDispatchExecution(input: {\n agentControllerConversationId: string | null;\n bootstrapPlan: BootstrapPlan;\n localRuntimeContextPlan: LocalRuntimeContextPlan;\n observedAgentControllerConversation: AgentControllerConversationRef | null;\n plannedAgentControllerConversation: AgentControllerConversationRef | null;\n}): DispatchExecution {\n const effectiveObservedAgentControllerConversation =\n input.observedAgentControllerConversation ??\n input.plannedAgentControllerConversation;\n let agentControllerConversationResume: DispatchExecution[\"agentControllerConversationResume\"];\n if (!normalizeOptionalContextId(input.agentControllerConversationId)) {\n agentControllerConversationResume = {\n status: \"not_bound\",\n };\n } else if (\n input.plannedAgentControllerConversation &&\n areSameAgentControllerConversationRef(\n input.plannedAgentControllerConversation,\n effectiveObservedAgentControllerConversation\n )\n ) {\n agentControllerConversationResume = {\n status: \"continued\",\n };\n } else {\n agentControllerConversationResume = {\n status: \"replaced_by_provider\",\n };\n }\n return {\n bootstrap: input.bootstrapPlan.shouldInject\n ? {\n reason: input.bootstrapPlan.reason ?? \"missing_bootstrap_state\",\n status: \"pending\",\n }\n : {\n reason: null,\n status: \"applied\",\n },\n localRuntimeContext: {\n reason: input.localRuntimeContextPlan.reason,\n status:\n input.localRuntimeContextPlan.status === \"reuse\"\n ? \"reused\"\n : \"recreated\",\n },\n agentControllerConversationResume,\n };\n}\n\nfunction sendResultAndSummarize(input: {\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n emitCompletedLifecycle?: boolean;\n executionIdentityEcho: RuntimeTransportResultIdentityEcho;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n ledgerPaths: LedgerPaths;\n leaseEpoch: number;\n payload: OpenMeldDaemonTaskResultPayload;\n presenter: Presenter;\n runtimeCoordinatorExecutionId: string | null;\n taskId: string;\n waitForSettlement?: boolean;\n}): {\n resultSummary: LocalExecutionSlotTaskResult;\n settlement: Promise<DispatchResultOutboxSettlement> | null;\n} {\n let settlement: Promise<DispatchResultOutboxSettlement> | null = null;\n try {\n if (input.emitCompletedLifecycle !== false) {\n emitDispatchLifecycleTransition({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n phase: \"completed_local\",\n presenter: input.presenter,\n executionTokenEcho: input.executionTokenEcho,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n taskId: input.taskId,\n });\n }\n settlement = enqueueDispatchResultOutboxRecord({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionIdentityEcho: input.executionIdentityEcho,\n executionTokenEcho: input.executionTokenEcho,\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: input.leaseEpoch,\n payload: input.payload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n taskId: input.taskId,\n waitForSettlement: input.waitForSettlement,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: buildResultDispatchJournalMetadata(input.payload),\n result: input.payload.status,\n taskId: input.taskId,\n type: \"dispatch.result.sent\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.result_queued\",\n text: `daemon result queued for dispatch ${input.dispatchId}`,\n payload: {\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n result: input.payload.status,\n taskId: input.taskId,\n },\n });\n } catch (error) {\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: {\n ...buildResultDispatchJournalMetadata(input.payload),\n errorMessage: toErrorMessage(error),\n },\n result: input.payload.status,\n taskId: input.taskId,\n type: \"dispatch.result.send_failed\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.result_send_failed\",\n text: `daemon result send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n result: input.payload.status,\n taskId: input.taskId,\n },\n });\n throw error;\n }\n return {\n resultSummary: summarizeTaskResultPayload(input.payload),\n settlement,\n };\n}\n\nfunction requireCompletedDispatchPlans(input: {\n bootstrapPlan: BootstrapPlan | null;\n ledgerIo: ReturnType<typeof createLedgerIo> | null;\n localRuntimeContextPlan: LocalRuntimeContextPlan | null;\n runtimePromptPlan: DispatchPromptPlan | null;\n}): {\n bootstrapPlan: BootstrapPlan;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n localRuntimeContextPlan: LocalRuntimeContextPlan;\n runtimePromptPlan: DispatchPromptPlan;\n} {\n if (\n !(\n input.bootstrapPlan &&\n input.ledgerIo &&\n input.localRuntimeContextPlan &&\n input.runtimePromptPlan\n )\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.runtime_context.incomplete\",\n message:\n \"OpenMeld could not settle the Agent reply because its runtime context is incomplete.\",\n });\n }\n return {\n bootstrapPlan: input.bootstrapPlan,\n ledgerIo: input.ledgerIo,\n localRuntimeContextPlan: input.localRuntimeContextPlan,\n runtimePromptPlan: input.runtimePromptPlan,\n };\n}\n\nasync function requestDispatchAgentInteraction(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n leasesByProfileId: Map<string, number>;\n parsedTask: ParsedDispatchTask;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n presenter: Presenter;\n request: AdapterInteractionRequest;\n}): Promise<Awaited<ReturnType<PendingAgentInteractionRegistry[\"register\"]>>> {\n const requestedAtMs = Date.now();\n const interactionCandidate: AgentInteractionRequest = {\n ...input.request,\n v: AGENT_INTERACTION_SCHEMA_VERSION,\n interactionId: randomUUID(),\n requestedAtMs,\n expiresAtMs: requestedAtMs + AGENT_INTERACTION_DEFAULT_TIMEOUT_MS,\n };\n const parsedInteraction =\n agentInteractionRequestSchema.safeParse(interactionCandidate);\n if (!parsedInteraction.success) {\n throw new DaemonServiceRunError({\n code: \"daemon.run.interaction_payload_invalid\",\n message: \"local agent produced an invalid interaction request\",\n });\n }\n\n const responsePromise = input.pendingAgentInteractionRegistry.register({\n authority: {\n attemptId: input.parsedTask.attemptId,\n dispatchId: input.parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: input.parsedTask.executionTokenEcho,\n runtimeCoordinatorExecutionId:\n input.parsedTask.runtimeCoordinatorExecutionId,\n targetProfileId: input.parsedTask.targetProfileId,\n },\n request: parsedInteraction.data,\n taskId: input.parsedTask.taskId,\n });\n try {\n sendDispatchInteractionRequestFrame({\n attemptId: input.parsedTask.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.deliverRequest.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: input.parsedTask.executionTokenEcho,\n interaction: parsedInteraction.data,\n leaseEpoch:\n input.leasesByProfileId.get(input.parsedTask.targetProfileId) ??\n input.deliverRequest.leaseEpoch,\n runtimeCoordinatorExecutionId:\n input.parsedTask.runtimeCoordinatorExecutionId,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.parsedTask.dispatchId),\n taskId: input.parsedTask.taskId,\n });\n } catch (error) {\n input.pendingAgentInteractionRegistry.reject(\n parsedInteraction.data.interactionId,\n error instanceof Error ? error : new Error(toErrorMessage(error))\n );\n throw error;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_requested\",\n text: `local agent is waiting for user input for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n expiresAtMs: parsedInteraction.data.expiresAtMs,\n interactionId: parsedInteraction.data.interactionId,\n interactionKind: parsedInteraction.data.kind,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return await responsePromise;\n}\n\nfunction emitDispatchPreviewFrame(input: {\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n leaseEpoch: number;\n presenter: Presenter;\n previewText: string;\n taskId: string;\n}): void {\n try {\n sendDispatchPreviewFrame({\n attemptId: input.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n previewText: input.previewText,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.dispatchId),\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.preview_send_failed\",\n text: `daemon preview send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n taskId: input.taskId,\n },\n });\n }\n}\n\nfunction emitDispatchAgentToolActivityFrame(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n event: AdapterToolActivityEvent;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n sequence: number;\n}): void {\n try {\n sendDispatchToolActivityFrame({\n attemptId: input.parsedTask.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.deliverRequest.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: input.parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n observedAtMs: input.event.tsMs,\n part: {\n type: \"tool\",\n toolCallId: input.event.toolCallId,\n toolName: input.event.toolName,\n state: input.event.state,\n ...(input.event.work ? { work: input.event.work } : {}),\n },\n runtimeCoordinatorExecutionId:\n input.parsedTask.runtimeCoordinatorExecutionId,\n sequence: input.sequence,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.parsedTask.dispatchId),\n sourceSignalId: input.parsedTask.sourceEventId,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.tool_activity_send_failed\",\n text: `daemon tool activity send failed for dispatch ${input.parsedTask.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.parsedTask.attemptId,\n dispatchId: input.parsedTask.dispatchId,\n sequence: input.sequence,\n state: input.event.state,\n toolName: input.event.toolName,\n taskId: input.parsedTask.taskId,\n },\n });\n }\n}\n\nfunction emitDispatchPreviewEndFrame(input: {\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n leaseEpoch: number;\n presenter: Presenter;\n taskId: string;\n}): void {\n try {\n sendDispatchPreviewEndFrame({\n attemptId: input.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.dispatchId),\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.preview_end_send_failed\",\n text: `daemon preview end send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n taskId: input.taskId,\n },\n });\n }\n}\n\nfunction emitDispatchRuntimeEvidenceTransition(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n durationMs?: number | null;\n errorName?: string | null;\n parsedTask?: ParsedDispatchTask | null;\n phase: RuntimeTransportDispatchRuntimeEvidencePhase;\n presenter: Presenter;\n reasonCode?: string | null;\n}): void {\n const identity = buildDispatchRuntimeEvidenceIdentity({\n deliverRequest: input.deliverRequest,\n parsedTask: input.parsedTask ?? null,\n });\n\n try {\n sendDispatchRuntimeEvidenceFrame({\n attemptId: identity.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.deliverRequest.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: identity.dispatchId,\n durationMs: input.durationMs ?? null,\n errorName: input.errorName ?? null,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: toRuntimeCoordinatorExecutionTokenEcho(\n input.deliverRequest\n ),\n leaseEpoch: input.deliverRequest.leaseEpoch,\n phase: input.phase,\n reasonCode: input.reasonCode ?? null,\n runtimeCoordinatorExecutionId:\n input.deliverRequest.payload.runtimeCoordinatorExecutionId,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(identity.dispatchId),\n sourceClientMessageId: identity.sourceClientMessageId,\n sourceSignalId: identity.sourceSignalId,\n spaceId: identity.spaceId,\n targetProfileId: identity.targetProfileId,\n taskId: identity.taskId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_evidence_send_failed\",\n text: `daemon runtime evidence ${input.phase} send failed for dispatch ${identity.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: identity.attemptId,\n dispatchId: identity.dispatchId,\n phase: input.phase,\n reasonCode: input.reasonCode ?? null,\n taskId: identity.taskId,\n },\n });\n }\n}\n\nfunction buildDispatchRuntimeEvidenceIdentity(input: {\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n parsedTask: ParsedDispatchTask | null;\n}): {\n attemptId: string;\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceSignalId: string;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n} {\n const payload = input.deliverRequest.payload;\n return {\n attemptId: input.parsedTask?.attemptId ?? input.deliverRequest.attemptId,\n dispatchId: input.parsedTask?.dispatchId ?? input.deliverRequest.dispatchId,\n sourceClientMessageId: payload.sourceClientMessageId ?? null,\n sourceSignalId: input.parsedTask?.sourceEventId ?? payload.sourceEventId,\n spaceId: input.parsedTask?.spaceId ?? payload.spaceId,\n targetProfileId:\n input.parsedTask?.targetProfileId ?? payload.targetProfileId,\n taskId: input.parsedTask?.taskId ?? payload.taskId,\n };\n}\n\nfunction toRuntimeTransportRuntimeEvidenceIdentityEcho(\n deliverRequest: RuntimeTransportDeliverDispatchRequest\n): RuntimeTransportRuntimeEvidenceIdentityEcho {\n return {\n echoSource: \"daemon_delivery_context\",\n core: deliverRequest.payload.executionIdentity.core,\n };\n}\n\nfunction toRuntimeTransportResultIdentityEcho(\n deliverRequest: RuntimeTransportDeliverDispatchRequest\n): RuntimeTransportResultIdentityEcho {\n return toRuntimeTransportResultIdentityEchoFromDeliveryIdentity(\n deliverRequest.payload.executionIdentity\n );\n}\n\nfunction toRuntimeCoordinatorExecutionTokenEcho(\n deliverRequest: RuntimeTransportDeliverDispatchRequest\n): RuntimeCoordinatorExecutionTokenEcho | null {\n const executionToken = deliverRequest.payload.executionToken;\n if (!executionToken) {\n return null;\n }\n return {\n executionToken: executionToken.executionToken,\n runId: executionToken.runId,\n runtimeCoordinatorExecutionId:\n executionToken.executionScope.runtimeCoordinatorExecutionId,\n tokenFingerprint: executionToken.tokenFingerprint,\n };\n}\n\nfunction resolveRuntimeCoordinatorExecutionTokenEchoFromRaw(\n value: unknown\n): RuntimeCoordinatorExecutionTokenEcho | null {\n const parsed =\n runtimeCoordinatorExecutionTokenEnvelopeSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n return {\n executionToken: parsed.data.executionToken,\n runId: parsed.data.runId,\n runtimeCoordinatorExecutionId:\n parsed.data.executionScope.runtimeCoordinatorExecutionId,\n tokenFingerprint: parsed.data.tokenFingerprint,\n };\n}\n\nfunction toRuntimeTransportResultIdentityEchoFromDeliveryIdentity(\n executionIdentity: RuntimeTransportDeliveryExecutionIdentity\n): RuntimeTransportResultIdentityEcho {\n return {\n echoSource: \"daemon_delivery_context\",\n core: executionIdentity.core,\n };\n}\n\nfunction resolveRuntimeEvidenceResultPhase(\n payload: OpenMeldDaemonTaskResultPayload\n): Extract<\n RuntimeTransportDispatchRuntimeEvidencePhase,\n \"completed\" | \"failed\"\n> {\n return payload.status === \"failed\" ? \"failed\" : \"completed\";\n}\n\nfunction resolveRuntimeEvidenceResultReasonCode(\n payload: OpenMeldDaemonTaskResultPayload\n): string | null {\n if (payload.status !== \"failed\") {\n return null;\n }\n return normalizeOptionalText(payload.errorCode) ?? null;\n}\n\nfunction toRuntimeTransportDispatchLocalQueueDiagnostics(\n input: LocalExecutionSlotDiagnostics\n): RuntimeTransportDispatchLocalQueueDiagnostics {\n return {\n activeForLane: input.activeForLane,\n activeGlobal: input.activeGlobal,\n globalConcurrency: input.limits.globalConcurrency,\n queueDepth: input.queueDepth,\n queueMax: input.limits.queueMax,\n queuePosition: input.queuePosition,\n status: input.status,\n waitReason: input.waitReason,\n };\n}\n\nfunction emitDispatchLifecycleTransition(input: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n localQueue?: RuntimeTransportDispatchLocalQueueDiagnostics | null;\n phase: DispatchLifecyclePhase;\n presenter: Presenter;\n runtimeCoordinatorExecutionId: string | null;\n taskId: string;\n}): void {\n try {\n sendCurrentDispatchLifecycleFrame({\n agentControllerConversationOccupancy:\n input.agentControllerConversationOccupancy ?? null,\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionTokenEcho: input.executionTokenEcho,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n });\n } catch (error) {\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: {\n errorMessage: toErrorMessage(error),\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n },\n result: \"failed\",\n taskId: input.taskId,\n type: \"dispatch.lifecycle.send_failed\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.lifecycle_send_failed\",\n text: `daemon lifecycle ${input.phase} send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n phase: input.phase,\n taskId: input.taskId,\n },\n });\n return;\n }\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: {\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n },\n result: \"sent\",\n taskId: input.taskId,\n type: \"dispatch.lifecycle.sent\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.lifecycle_sent\",\n text: `daemon lifecycle ${input.phase} sent for dispatch ${input.dispatchId}`,\n payload: {\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n taskId: input.taskId,\n },\n });\n}\n\nfunction resolveInitialDispatchLifecyclePhase(input: {\n providerAdmissionOwnsRunningLifecycle: boolean;\n}): Extract<DispatchLifecyclePhase, \"accepted_local\" | \"running\"> {\n return input.providerAdmissionOwnsRunningLifecycle\n ? \"accepted_local\"\n : \"running\";\n}\n\nfunction startDispatchLifecycleKeepalive(input: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n localQueue?: RuntimeTransportDispatchLocalQueueDiagnostics | null;\n phase: Extract<DispatchLifecyclePhase, \"accepted_local\" | \"running\">;\n presenter: Presenter;\n runtimeCoordinatorExecutionId: string | null;\n taskId: string;\n}): () => void {\n let intervalCount = 0;\n let lastOccupancyConnectionGeneration: number | null = null;\n const intervalId = setInterval(() => {\n try {\n const currentConnectionGeneration = resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n });\n const shouldReassertOccupancy = Boolean(\n input.agentControllerConversationOccupancy &&\n (intervalCount %\n AGENT_CONTROLLER_OCCUPANCY_KEEPALIVE_REASSERT_INTERVALS ===\n 0 ||\n lastOccupancyConnectionGeneration !== currentConnectionGeneration)\n );\n intervalCount += 1;\n if (shouldReassertOccupancy) {\n lastOccupancyConnectionGeneration = currentConnectionGeneration;\n }\n sendCurrentDispatchLifecycleFrame({\n agentControllerConversationOccupancy: shouldReassertOccupancy\n ? (input.agentControllerConversationOccupancy ?? null)\n : null,\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionTokenEcho: input.executionTokenEcho,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.lifecycle_keepalive_failed\",\n text: `daemon lifecycle keepalive failed for dispatch ${input.dispatchId}: ${error instanceof Error ? error.message : String(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n phase: input.phase,\n taskId: input.taskId,\n },\n });\n }\n }, DEFAULT_TASK_LIFECYCLE_HEARTBEAT_INTERVAL_MS);\n\n return () => {\n clearInterval(intervalId);\n };\n}\n\nfunction sendCurrentDispatchLifecycleFrame(input: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n localQueue?: RuntimeTransportDispatchLocalQueueDiagnostics | null;\n phase: DispatchLifecyclePhase;\n runtimeCoordinatorExecutionId: string | null;\n}): void {\n sendDispatchLifecycleFrame({\n agentControllerConversationOccupancy:\n input.agentControllerConversationOccupancy ?? null,\n attemptId: input.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n executionTokenEcho: input.executionTokenEcho,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.dispatchId),\n });\n}\n\nfunction resolveCurrentConnectionGeneration(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n fallbackConnectionGeneration: number;\n}): number {\n return (\n input.currentSocketRef.connectionGeneration ??\n input.fallbackConnectionGeneration\n );\n}\n\nfunction failMissingCurrentSocket(dispatchId: string): never {\n throw new DaemonServiceRunError({\n code: \"daemon.run.socket_unavailable\",\n message: `active daemon socket is unavailable for dispatch ${dispatchId}`,\n });\n}\n","import type {\n AdapterCancelResult,\n AdapterInterruptResult,\n AdapterLocalAttemptOutcome,\n} from \"@openmeld/adapter-core\";\nimport type {\n InflightTaskControlRecord,\n InflightTaskControlRegistry,\n LocalDaemonAdapterContainer,\n} from \"@openmeld/local-service\";\nimport {\n OPENMELD_DAEMON_CANCEL_STOP_REQUESTED_AFTER_START_REASON_CODE,\n OPENMELD_DAEMON_CANCEL_WITHDRAWN_BEFORE_START_REASON_CODE,\n} from \"@openmeld/schemas\";\nimport type {\n OpenMeldDaemonCancelRequestPayload,\n OpenMeldDaemonControlPlaneResponse,\n OpenMeldDaemonInterruptRequestPayload,\n} from \"@openmeld/schemas/types\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine } from \"../core/logger\";\n\ntype LocalControlCancelPayload = Extract<\n OpenMeldDaemonControlPlaneResponse,\n { code: \"service.cancel\" }\n>[\"payload\"];\ntype LocalControlInterruptPayload = Extract<\n OpenMeldDaemonControlPlaneResponse,\n { code: \"service.interrupt\" }\n>[\"payload\"];\n\nexport async function handleLocalControlPlaneCancel(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n registry: InflightTaskControlRegistry;\n}): Promise<LocalControlCancelPayload> {\n const resolution = input.registry.resolveTarget(input.payload.target);\n if (!resolution) {\n return (\n replayRecordedWithdrawal(input) ?? rejectMissingInflightTarget(input)\n );\n }\n\n if (\n input.payload.runtimeCoordinatorExecutionId &&\n resolution.record.runtimeCoordinatorExecutionId !==\n input.payload.runtimeCoordinatorExecutionId\n ) {\n return rejectRuntimeCoordinatorExecutionMismatch({\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const adapterEntry = input.localAdapterContainer.getAdapter(\n resolution.record.adapterId\n );\n const adapter = adapterEntry?.adapter ?? null;\n if (!adapter?.cancel) {\n return rejectMissingAdapterCancel({\n adapterPresent: Boolean(adapter),\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const result = await adapter.cancel({\n ...(input.payload.reason ? { reason: input.payload.reason } : {}),\n taskId: resolution.record.taskId,\n });\n if (result.accepted) {\n const currentRecord = input.registry.getTask(resolution.record.taskId);\n if (\n currentRecord?.dispatchId === resolution.record.dispatchId &&\n currentRecord.runtimeCoordinatorExecutionId ===\n resolution.record.runtimeCoordinatorExecutionId\n ) {\n if (result.localAttemptOutcome) {\n input.registry.settleWithdrawnTask({\n localAttemptOutcome: result.localAttemptOutcome,\n record: currentRecord,\n });\n }\n input.registry.removeTask(resolution.record.taskId);\n }\n }\n const reasonCode = result.accepted\n ? resolveAcceptedCancelReasonCode(result.localAttemptOutcome)\n : result.reasonCode;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel\",\n text: `local cancel ${result.accepted ? \"accepted\" : \"rejected\"} for dispatch ${resolution.record.dispatchId}`,\n payload: {\n accepted: result.accepted,\n adapterId: resolution.record.adapterId,\n deliveryPath: result.deliveryPath ?? null,\n dispatchId: resolution.record.dispatchId,\n reasonCode,\n signalDelivery: result.signalDelivery,\n target: input.payload.target,\n taskId: resolution.record.taskId,\n },\n });\n return {\n accepted: result.accepted,\n note: resolveAdapterCancelNote({ reasonCode, result }),\n reasonCode,\n resolvedDispatchId: resolution.record.dispatchId,\n ...(resolution.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n resolution.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: resolution.record.taskId,\n target: input.payload.target,\n };\n}\n\n/**\n * Names what an accepted cancellation established.\n *\n * The distinction rides the existing reason code rather than a new payload key:\n * these control payloads are strict objects, so a Service that emitted a new\n * key would have its whole frame rejected by a Core that predates it, and a\n * local component can reach a user before the matching Core deploy.\n */\nfunction resolveAcceptedCancelReasonCode(\n localAttemptOutcome: AdapterLocalAttemptOutcome | undefined\n): string {\n if (localAttemptOutcome === \"withdrawn_before_start\") {\n return OPENMELD_DAEMON_CANCEL_WITHDRAWN_BEFORE_START_REASON_CODE;\n }\n return localAttemptOutcome === \"stop_requested_after_start\"\n ? OPENMELD_DAEMON_CANCEL_STOP_REQUESTED_AFTER_START_REASON_CODE\n : \"adapter.cancel.accepted\";\n}\n\n/**\n * Answers a repeat request from what the withdrawal already established.\n *\n * Accepting a withdrawal removes the inflight record, so without this a repeat\n * could only answer \"no such task\". That is a weaker statement than what was\n * actually established and cannot be turned back into proof, which would leave\n * work that replaces this attempt blocked on evidence merely lost in transit.\n */\nfunction replayRecordedWithdrawal(input: {\n payload: OpenMeldDaemonCancelRequestPayload;\n registry: InflightTaskControlRegistry;\n}): LocalControlCancelPayload | null {\n const receipt = input.registry.readWithdrawnTaskReceipt(input.payload.target);\n if (\n !receipt ||\n (input.payload.runtimeCoordinatorExecutionId &&\n receipt.record.runtimeCoordinatorExecutionId !==\n input.payload.runtimeCoordinatorExecutionId)\n ) {\n return null;\n }\n return {\n accepted: true,\n note: \"Replayed the recorded withdrawal for this attempt.\",\n reasonCode: resolveAcceptedCancelReasonCode(receipt.localAttemptOutcome),\n resolvedDispatchId: receipt.record.dispatchId,\n ...(receipt.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n receipt.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: receipt.record.taskId,\n target: input.payload.target,\n };\n}\n\nexport async function handleLocalControlPlaneInterrupt(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n registry: InflightTaskControlRegistry;\n}): Promise<LocalControlInterruptPayload> {\n const resolution = input.registry.resolveTarget(input.payload.target);\n if (!resolution) {\n return rejectMissingInflightInterruptTarget(input);\n }\n\n if (\n input.payload.runtimeCoordinatorExecutionId &&\n resolution.record.runtimeCoordinatorExecutionId !==\n input.payload.runtimeCoordinatorExecutionId\n ) {\n return rejectInterruptRuntimeCoordinatorExecutionMismatch({\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const adapterEntry = input.localAdapterContainer.getAdapter(\n resolution.record.adapterId\n );\n const adapter = adapterEntry?.adapter ?? null;\n if (!adapter?.interrupt) {\n return rejectMissingAdapterInterrupt({\n adapterPresent: Boolean(adapter),\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const result = await adapter.interrupt({\n ...(input.payload.mode ? { mode: input.payload.mode } : {}),\n ...(input.payload.reason ? { reason: input.payload.reason } : {}),\n taskId: resolution.record.taskId,\n });\n const reasonCode = result.accepted\n ? \"adapter.interrupt.accepted\"\n : result.reasonCode;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt\",\n text: `local interrupt ${result.accepted ? \"accepted\" : \"rejected\"} for dispatch ${resolution.record.dispatchId}`,\n payload: {\n accepted: result.accepted,\n adapterId: resolution.record.adapterId,\n dispatchId: resolution.record.dispatchId,\n reasonCode,\n signalDelivery: result.signalDelivery,\n target: input.payload.target,\n taskId: resolution.record.taskId,\n },\n });\n return {\n accepted: result.accepted,\n note: resolveAdapterInterruptNote({ reasonCode, result }),\n reasonCode,\n resolvedDispatchId: resolution.record.dispatchId,\n ...(resolution.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n resolution.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: resolution.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingInflightTarget(input: {\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n}): LocalControlCancelPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_rejected\",\n text: \"local cancel rejected because the target is not inflight\",\n payload: {\n accepted: false,\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n },\n });\n return {\n accepted: false,\n note: \"task.not_found\",\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingInflightInterruptTarget(input: {\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n}): LocalControlInterruptPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_rejected\",\n text: \"local interrupt rejected because the target is not inflight\",\n payload: {\n accepted: false,\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n },\n });\n return {\n accepted: false,\n note: \"task.not_found\",\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n };\n}\n\nfunction rejectRuntimeCoordinatorExecutionMismatch(input: {\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlCancelPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_rejected\",\n text: `local cancel rejected because RuntimeCoordinator execution identity did not match dispatch ${input.record.dispatchId}`,\n payload: {\n accepted: false,\n dispatchId: input.record.dispatchId,\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n requestedRuntimeCoordinatorExecutionId:\n input.payload.runtimeCoordinatorExecutionId,\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: \"runtime_coordinator.execution_id_mismatch\",\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectInterruptRuntimeCoordinatorExecutionMismatch(input: {\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlInterruptPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_rejected\",\n text: `local interrupt rejected because RuntimeCoordinator execution identity did not match dispatch ${input.record.dispatchId}`,\n payload: {\n accepted: false,\n dispatchId: input.record.dispatchId,\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n requestedRuntimeCoordinatorExecutionId:\n input.payload.runtimeCoordinatorExecutionId,\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: \"runtime_coordinator.execution_id_mismatch\",\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingAdapterCancel(input: {\n adapterPresent: boolean;\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlCancelPayload {\n const reasonCode = input.adapterPresent\n ? \"adapter.unsupported\"\n : \"adapter.missing\";\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_rejected\",\n text: `local cancel rejected because adapter '${input.record.adapterId}' does not expose cancel control`,\n payload: {\n accepted: false,\n adapterId: input.record.adapterId,\n dispatchId: input.record.dispatchId,\n reasonCode,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: reasonCode,\n reasonCode,\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingAdapterInterrupt(input: {\n adapterPresent: boolean;\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlInterruptPayload {\n const reasonCode = input.adapterPresent\n ? \"adapter.unsupported\"\n : \"adapter.missing\";\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_rejected\",\n text: `local interrupt rejected because adapter '${input.record.adapterId}' does not expose interrupt control`,\n payload: {\n accepted: false,\n adapterId: input.record.adapterId,\n dispatchId: input.record.dispatchId,\n reasonCode,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: reasonCode,\n reasonCode,\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction resolveAdapterCancelNote(input: {\n reasonCode: string;\n result: AdapterCancelResult;\n}): string {\n if (input.result.accepted) {\n return input.result.deliveryPath ?? input.reasonCode;\n }\n if (input.result.reasonDetail) {\n return `${input.result.reasonCode}: ${input.result.reasonDetail}`;\n }\n return input.reasonCode;\n}\n\nfunction resolveAdapterInterruptNote(input: {\n reasonCode: string;\n result: AdapterInterruptResult;\n}): string {\n if (input.result.accepted) {\n return input.reasonCode;\n }\n if (input.result.reasonDetail) {\n return `${input.result.reasonCode}: ${input.result.reasonDetail}`;\n }\n return input.reasonCode;\n}\n","import type {\n InflightTaskControlRegistry,\n LocalDaemonAdapterContainer,\n LocalExecutionSlots,\n PendingAgentInteractionRegistry,\n} from \"@openmeld/local-service\";\nimport {\n localAgentReasoningPreferencesSchema,\n RUNTIME_TRANSPORT_SCHEMA_VERSION,\n runtimeTransportDispatchInteractionDeliveredRequestSchema,\n runtimeTransportDispatchInteractionResponseFramePayloadSchema,\n runtimeTransportLocalAgentControlCancelFramePayloadSchema,\n runtimeTransportLocalAgentControlInterruptFramePayloadSchema,\n} from \"@openmeld/schemas\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type {\n CurrentDaemonSocketRef,\n DaemonFrameSink,\n DaemonProfileRouteConfig,\n InflightDispatchMeta,\n LedgerPaths,\n ParsedDaemonFrame,\n PendingFrameWaiters,\n} from \"../core/types\";\nimport {\n acknowledgeDispatchResultOutboxRecord,\n flushDispatchResultOutbox,\n} from \"../dispatch/dispatch-result-outbox\";\nimport { enqueueDispatchDeliverFrame } from \"../dispatch/execute-dispatch-task\";\nimport {\n emitDaemonErrorFrame,\n resolveHeartbeatResponseFrame,\n resolveRegisterResponseFrame,\n sendDaemonFrame,\n} from \"./daemon-frame-transport\";\nimport {\n handleLocalControlPlaneCancel,\n handleLocalControlPlaneInterrupt,\n} from \"./local-control-handlers\";\n\nfunction handleDispatchInteractionResponse(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n leasesByProfileId: Map<string, number>;\n payload: Record<string, unknown>;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): void {\n const parsedResponse =\n runtimeTransportDispatchInteractionResponseFramePayloadSchema.safeParse(\n input.payload\n );\n if (!parsedResponse.success) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_invalid\",\n text: \"local agent interaction response was rejected because the payload is invalid\",\n });\n return;\n }\n const pendingInteraction = input.pendingAgentInteractionRegistry.get(\n parsedResponse.data.interactionId\n );\n if (!pendingInteraction) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_not_found\",\n text: `local agent interaction ${parsedResponse.data.interactionId} is no longer pending`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const authority = pendingInteraction.authority;\n if (\n authority.attemptId !== parsedResponse.data.attemptId ||\n authority.dispatchId !== parsedResponse.data.dispatchId ||\n authority.runtimeCoordinatorExecutionId !==\n parsedResponse.data.runtimeCoordinatorExecutionId\n ) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_authority_mismatch\",\n text: `local agent interaction ${parsedResponse.data.interactionId} did not match the active execution`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const resolution = input.pendingAgentInteractionRegistry.resolve({\n interactionId: parsedResponse.data.interactionId,\n response: parsedResponse.data.response,\n });\n if (!resolution || resolution.status === \"response_invalid\") {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_invalid\",\n text: `local agent interaction ${parsedResponse.data.interactionId} received an invalid answer`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const connectionGeneration = input.currentSocketRef.connectionGeneration;\n const leaseEpoch = input.leasesByProfileId.get(authority.targetProfileId);\n if (!(connectionGeneration && leaseEpoch)) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_delivery_deferred\",\n text: `local agent interaction ${parsedResponse.data.interactionId} resumed locally; delivery acknowledgement is waiting for the active lease`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const deliveredRequest =\n runtimeTransportDispatchInteractionDeliveredRequestSchema.parse({\n v: RUNTIME_TRANSPORT_SCHEMA_VERSION,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n executionTokenEcho: authority.executionTokenEcho,\n dispatchId: parsedResponse.data.dispatchId,\n attemptId: parsedResponse.data.attemptId,\n executionIdentityEcho: authority.executionIdentityEcho,\n daemonSessionId: input.daemonSessionId,\n connectionGeneration,\n leaseEpoch,\n interactionId: parsedResponse.data.interactionId,\n deliveredAtMs: Date.now(),\n });\n sendDaemonFrame(input.socket, {\n code: \"daemon.dispatch.interaction_delivered\",\n payload: deliveredRequest,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_resolved\",\n text: `local agent resumed after user input for interaction ${parsedResponse.data.interactionId}`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n resolutionStatus: resolution.status,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n}\n\nfunction applyReasoningPreference(\n ref: CurrentDaemonSocketRef,\n payload: unknown\n): void {\n const preference = localAgentReasoningPreferencesSchema.safeParse(payload);\n if (\n !preference.success ||\n ref.reasoningStreamEnabled === preference.data.enabled\n ) {\n return;\n }\n ref.reasoningStreamEnabled = preference.data.enabled;\n for (const listener of ref.reasoningPreferenceListeners ?? []) {\n listener();\n }\n}\n\nexport function handleDaemonSocketFrame(input: {\n computerFileAccessStorePath: string;\n contextStore: Map<string, string>;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n localExecutionSlots: LocalExecutionSlots;\n inflightDispatchMetaByTaskId: Map<string, InflightDispatchMeta>;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n parsedFrame: ParsedDaemonFrame;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n requestCurrentWorkingFolderFactRefresh?: () => void;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n waiters: PendingFrameWaiters;\n}): void {\n switch (input.parsedFrame.code) {\n case \"daemon.reasoning.preferences\": {\n applyReasoningPreference(\n input.currentSocketRef,\n input.parsedFrame.payload\n );\n return;\n }\n case \"daemon.session.register\":\n resolveRegisterResponseFrame({\n payload: input.parsedFrame.payload,\n presenter: input.presenter,\n waiters: input.waiters,\n });\n return;\n case \"daemon.session.heartbeat\":\n resolveHeartbeatResponseFrame({\n payload: input.parsedFrame.payload,\n presenter: input.presenter,\n waiters: input.waiters,\n });\n return;\n case \"daemon.dispatch.deliver\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.dispatch_deliver_received\",\n text: `deliver frame received for dispatch ${String(input.parsedFrame.payload.dispatchId ?? \"unknown\")}`,\n payload: {\n attemptId: input.parsedFrame.payload.attemptId ?? null,\n connectionGeneration: input.parsedFrame.payload.connectionGeneration,\n deliveryRecoveryReason:\n input.parsedFrame.payload.deliveryRecoveryReason ?? null,\n dispatchId: input.parsedFrame.payload.dispatchId ?? null,\n leaseEpoch: input.parsedFrame.payload.leaseEpoch ?? null,\n profileId: input.parsedFrame.payload.profileId ?? null,\n taskId: input.parsedFrame.payload.taskId ?? null,\n },\n });\n enqueueDispatchDeliverFrame({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n contextStore: input.contextStore,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n localExecutionSlots: input.localExecutionSlots,\n inflightDispatchMetaByTaskId: input.inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n pendingAgentInteractionRegistry: input.pendingAgentInteractionRegistry,\n ledgerPaths: input.ledgerPaths,\n leasesByProfileId: input.leasesByProfileId,\n localAdapterContainer: input.localAdapterContainer,\n payload: input.parsedFrame.payload,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n requestCurrentWorkingFolderFactRefresh:\n input.requestCurrentWorkingFolderFactRefresh,\n presenter: input.presenter,\n routeByProfileId: input.routeByProfileId,\n socket: input.socket,\n });\n return;\n case \"daemon.dispatch.accepted\":\n acknowledgeDispatchResultOutboxRecord({\n attemptId: normalizeOptionalFrameValue(\n input.parsedFrame.payload.attemptId\n ),\n dispatchId:\n normalizeOptionalFrameValue(input.parsedFrame.payload.dispatchId) ??\n \"unknown\",\n ledgerPaths: input.ledgerPaths,\n ok: input.parsedFrame.payload.ok === true,\n presenter: input.presenter,\n reasonCode: normalizeOptionalFrameValue(\n input.parsedFrame.payload.reasonCode\n ),\n status: normalizeResultAckStatus(input.parsedFrame.payload.status),\n });\n flushDispatchResultOutbox({\n currentSocketRef: input.currentSocketRef,\n ledgerPaths: input.ledgerPaths,\n presenter: input.presenter,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.result_acknowledged\",\n text: `daemon result acknowledged for dispatch ${String(input.parsedFrame.payload.dispatchId ?? \"unknown\")}`,\n payload: {\n attemptId: input.parsedFrame.payload.attemptId ?? null,\n dispatchId: input.parsedFrame.payload.dispatchId ?? null,\n ok: input.parsedFrame.payload.ok ?? null,\n reasonCode: input.parsedFrame.payload.reasonCode ?? null,\n status: input.parsedFrame.payload.status ?? null,\n },\n });\n return;\n case \"daemon.dispatch.interaction_response\":\n handleDispatchInteractionResponse({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n leasesByProfileId: input.leasesByProfileId,\n payload: input.parsedFrame.payload,\n pendingAgentInteractionRegistry: input.pendingAgentInteractionRegistry,\n presenter: input.presenter,\n socket: input.socket,\n });\n return;\n case \"daemon.local_agent_control.cancel\": {\n const parsedCancelFrame =\n runtimeTransportLocalAgentControlCancelFramePayloadSchema.safeParse(\n input.parsedFrame.payload\n );\n if (!parsedCancelFrame.success) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_frame_invalid\",\n text: \"local cancel frame rejected because the payload is invalid\",\n });\n return;\n }\n handleLocalControlPlaneCancel({\n localAdapterContainer: input.localAdapterContainer,\n payload: parsedCancelFrame.data.payload,\n presenter: input.presenter,\n registry: input.inflightTaskControlRegistry,\n })\n .then((payload) => {\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedCancelFrame.data.requestId,\n payload,\n },\n });\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_failed\",\n text: `local cancel handling failed: ${toErrorMessage(error)}`,\n payload: {\n requestId: parsedCancelFrame.data.requestId,\n target: parsedCancelFrame.data.payload.target,\n },\n });\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedCancelFrame.data.requestId,\n payload: {\n accepted: false,\n note: toErrorMessage(error),\n reasonCode: \"local_control.unhandled_error\",\n target: parsedCancelFrame.data.payload.target,\n },\n },\n });\n });\n return;\n }\n case \"daemon.local_agent_control.interrupt\": {\n const parsedInterruptFrame =\n runtimeTransportLocalAgentControlInterruptFramePayloadSchema.safeParse(\n input.parsedFrame.payload\n );\n if (!parsedInterruptFrame.success) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_frame_invalid\",\n text: \"local interrupt frame rejected because the payload is invalid\",\n });\n return;\n }\n handleLocalControlPlaneInterrupt({\n localAdapterContainer: input.localAdapterContainer,\n payload: parsedInterruptFrame.data.payload,\n presenter: input.presenter,\n registry: input.inflightTaskControlRegistry,\n })\n .then((payload) => {\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedInterruptFrame.data.requestId,\n payload,\n },\n });\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_failed\",\n text: `local interrupt handling failed: ${toErrorMessage(error)}`,\n payload: {\n requestId: parsedInterruptFrame.data.requestId,\n target: parsedInterruptFrame.data.payload.target,\n },\n });\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedInterruptFrame.data.requestId,\n payload: {\n accepted: false,\n note: toErrorMessage(error),\n reasonCode: \"local_control.unhandled_error\",\n target: parsedInterruptFrame.data.payload.target,\n },\n },\n });\n });\n return;\n }\n case \"daemon.error\":\n emitDaemonErrorFrame({\n payload: input.parsedFrame.payload,\n presenter: input.presenter,\n waiters: input.waiters,\n });\n return;\n case \"daemon.dispatch.result\":\n return;\n default:\n return;\n }\n}\n\nfunction normalizeOptionalFrameValue(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeResultAckStatus(\n value: unknown\n): \"accepted\" | \"rejected_terminal\" | \"review_required\" | \"retry_later\" | null {\n return value === \"accepted\" ||\n value === \"rejected_terminal\" ||\n value === \"review_required\" ||\n value === \"retry_later\"\n ? value\n : null;\n}\n\nexport function emitDispatchQueueError(input: {\n error: unknown;\n presenter: Presenter;\n}): void {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.dispatch_unhandled_error\",\n text: `dispatch handling failed: ${toErrorMessage(input.error)}`,\n });\n}\n","import { AGENT_PROFILE_WORK_CONCURRENCY_LIMIT } from \"@openmeld/agent-runtime\";\nimport {\n createLocalExecutionSlots,\n type LocalExecutionSlots,\n} from \"@openmeld/local-service\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine } from \"../core/logger\";\nimport type { DaemonDispatchLimits } from \"../core/types\";\n\nexport function createDaemonLocalExecutionSlots(input: {\n limits: DaemonDispatchLimits;\n presenter: Presenter;\n onChanged?: () => void;\n}): LocalExecutionSlots {\n return createLocalExecutionSlots({\n onChanged: input.onChanged,\n limits: {\n ...input.limits,\n contextConcurrency: AGENT_PROFILE_WORK_CONCURRENCY_LIMIT,\n },\n onTaskDropped: (event) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_dropped\",\n text: `local execution slot dropped pending task ${event.taskId} for ${event.targetLabel}: ${event.reason}`,\n payload: {\n adapterId: event.adapterId,\n activeForLane: event.activeForLane,\n activeGlobal: event.activeGlobal,\n controllerKey: event.controllerKey,\n dispatchId: event.dispatchId,\n globalConcurrency: event.limits.globalConcurrency,\n localExecutionLaneKey: event.localExecutionLaneKey,\n profileId: event.profileId,\n queueDepth: event.queueDepth,\n localQueueStatus: event.localQueue.status,\n localQueueWaitReason: event.localQueue.waitReason,\n queuePosition: event.localQueue.queuePosition,\n queueMax: event.limits.queueMax,\n reason: event.reason,\n spaceId: event.spaceId,\n step: \"dropped\",\n taskId: event.taskId,\n targetLabel: event.targetLabel,\n transportMode: event.transportMode,\n },\n });\n },\n onTaskStarted: (event) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_reserved\",\n text: `local execution slot reserved task ${event.taskId} for ${event.targetLabel}`,\n payload: {\n adapterId: event.adapterId,\n activeForLane: event.activeForLane,\n activeGlobal: event.activeGlobal,\n controllerKey: event.controllerKey,\n dispatchId: event.dispatchId,\n durationMs: null,\n errorCode: null,\n globalConcurrency: event.limits.globalConcurrency,\n localExecutionLaneKey: event.localExecutionLaneKey,\n profileId: event.profileId,\n queueDepth: event.queueDepth,\n localQueueStatus: event.localQueue.status,\n localQueueWaitReason: event.localQueue.waitReason,\n queuePosition: event.localQueue.queuePosition,\n queueMax: event.limits.queueMax,\n result: null,\n spaceId: event.spaceId,\n step: \"started\",\n taskId: event.taskId,\n targetLabel: event.targetLabel,\n transportMode: event.transportMode,\n },\n });\n },\n onTaskCompleted: (event) => {\n let completionText = `local execution slot failed task ${event.taskId} for ${event.targetLabel}`;\n if (event.result === \"success\") {\n completionText = `local execution slot completed task ${event.taskId} for ${event.targetLabel}`;\n } else if (event.result === \"partial_success\") {\n completionText = `local execution slot partially completed task ${event.taskId} for ${event.targetLabel}`;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_completed\",\n text: completionText,\n payload: {\n adapterId: event.adapterId,\n activeForLane: event.activeForLane,\n activeGlobal: event.activeGlobal,\n controllerKey: event.controllerKey,\n dispatchId: event.dispatchId,\n durationMs: event.durationMs,\n errorCode: event.errorCode,\n ...(event.errorMessage ? { errorMessage: event.errorMessage } : {}),\n globalConcurrency: event.limits.globalConcurrency,\n localExecutionLaneKey: event.localExecutionLaneKey,\n profileId: event.profileId,\n queueDepth: event.queueDepth,\n localQueueStatus: event.localQueue.status,\n localQueueWaitReason: event.localQueue.waitReason,\n queuePosition: event.localQueue.queuePosition,\n queueMax: event.limits.queueMax,\n result: event.result,\n spaceId: event.spaceId,\n step: \"completed\",\n taskId: event.taskId,\n targetLabel: event.targetLabel,\n transportMode: event.transportMode,\n },\n });\n },\n });\n}\n","import {\n resolveCodexTimeoutMs,\n verifyCodexAppServerThread,\n} from \"@openmeld/adapter-codex\";\nimport {\n buildAgentContextLookupKey,\n buildRuntimeWorkspaceFingerprint,\n loadLedgerState,\n} from \"@openmeld/local-execution\";\nimport {\n resolveCompatibleAgentContextMatch,\n resolveCompatibleConversationExecutionState,\n} from \"@openmeld/local-service\";\nimport {\n buildAgentControllerConversationRef,\n normalizeKnownBuiltinAgentControllerId,\n resolveBuiltinAgentControllerConversationKind,\n} from \"@openmeld/schemas\";\nimport type {\n ConversationExecutionState,\n OpenMeldDaemonConversationExecutionStatusPayload,\n OpenMeldDaemonConversationExecutionStatusRequestPayload,\n RuntimeAgentControllerLaunchContract,\n} from \"@openmeld/schemas/types\";\nimport { resolveProfileWorkspaceRuntime } from \"../../profile-workspace/runtime-resolution\";\nimport { normalizeOptionalText } from \"../core/logger\";\nimport {\n readLocalEnabledControllers,\n resolveLocalController,\n} from \"../routing/resolve-controller-support\";\nimport {\n buildLedgerPaths,\n ensureDaemonRuntimePaths,\n} from \"../state/daemon-device-id\";\nimport { createLedgerIo } from \"../state/ledger-io\";\n\nexport async function resolveLocalConversationExecutionStatus(\n input: OpenMeldDaemonConversationExecutionStatusRequestPayload\n): Promise<OpenMeldDaemonConversationExecutionStatusPayload> {\n const localControllers = await readLocalEnabledControllers();\n const localController = resolveLocalController({\n agentControllerRef: input.agentControllerRef,\n localControllers,\n });\n const workspaceResolution = await resolveProfileWorkspaceRuntime({\n openMeldProfileId: input.targetProfileId,\n mode: \"dispatch\",\n });\n const localLedgerStatus = await resolveLocalLedgerConversationExecution({\n agentControllerRef: input.agentControllerRef,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n transportMode: input.transportMode,\n workspaceResolution,\n });\n const providerConversationProof =\n input.validate === true\n ? await resolveLocalProviderConversationProof({\n boundAgentControllerRef: input.boundAgentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n launchContract: localController?.launchContract ?? null,\n profileAgentControllerRef: input.agentControllerRef,\n runtimeWorkingDirectory:\n workspaceResolution.status === \"ready\"\n ? workspaceResolution.effectiveRuntimeWorkingDirectory\n : null,\n transportMode: input.transportMode,\n })\n : buildProviderConversationProofNotRun(input.transportMode);\n\n return {\n agentContextLookupKey: localLedgerStatus.agentContextLookupKey,\n controllerLaunchStatus: resolveControllerLaunchStatus(localController),\n executionState: localLedgerStatus.executionState,\n localRuntimeContext: {\n agentContextLookupKey: localLedgerStatus.agentContextLookupKey,\n runtimeWorkspaceFingerprint:\n localLedgerStatus.runtimeWorkspaceFingerprint,\n status: resolveLocalRuntimeContextStatus({\n agentControllerConversationId: input.agentControllerConversationId,\n executionState: localLedgerStatus.executionState,\n previousAgentControllerConversationId:\n localLedgerStatus.previousAgentControllerConversationId ?? null,\n }),\n },\n providerConversationProof,\n runtimeWorkspace: normalizeRuntimeWorkspace(workspaceResolution),\n };\n}\n\nfunction resolveControllerLaunchStatus(\n localController: Awaited<\n ReturnType<typeof readLocalEnabledControllers>\n > extends Map<string, infer T>\n ? T | null\n : never\n): OpenMeldDaemonConversationExecutionStatusPayload[\"controllerLaunchStatus\"] {\n if (!localController) {\n return \"missing\";\n }\n if (localController.enabled !== true) {\n return \"disabled\";\n }\n if (!localController.launchContract) {\n return \"repair_required\";\n }\n return \"ready\";\n}\n\nfunction resolveLocalRuntimeContextStatus(input: {\n agentControllerConversationId: string | null;\n executionState: ConversationExecutionState | null;\n previousAgentControllerConversationId: string | null;\n}): OpenMeldDaemonConversationExecutionStatusPayload[\"localRuntimeContext\"][\"status\"] {\n if (!(input.executionState && input.previousAgentControllerConversationId)) {\n return \"missing\";\n }\n if (\n input.agentControllerConversationId &&\n input.previousAgentControllerConversationId !==\n input.agentControllerConversationId\n ) {\n return \"mismatch\";\n }\n return \"ready\";\n}\n\nfunction normalizeRuntimeWorkspace(\n input: Awaited<ReturnType<typeof resolveProfileWorkspaceRuntime>>\n): OpenMeldDaemonConversationExecutionStatusPayload[\"runtimeWorkspace\"] {\n switch (input.status) {\n case \"ready\":\n return {\n configPath: input.configPath,\n configuredWorkspacePath: input.configuredWorkspacePath,\n fingerprint: buildRuntimeWorkspaceFingerprint(\n input.effectiveRuntimeWorkingDirectory\n ),\n path: input.effectiveRuntimeWorkingDirectory,\n reasonCode: null,\n reasonText: null,\n runtimeContext: input.runtimeContext,\n status: \"ready\",\n workspaceMode: input.workspaceMode,\n };\n case \"missing\":\n return {\n configPath: input.configPath,\n configuredWorkspacePath: null,\n fingerprint: null,\n path: null,\n reasonCode: input.reasonCode,\n reasonText: input.reasonText,\n runtimeContext: null,\n status: \"missing\",\n workspaceMode: null,\n };\n case \"invalid\":\n return {\n configPath: input.configPath,\n configuredWorkspacePath: input.configuredWorkspacePath ?? null,\n fingerprint: null,\n path: null,\n reasonCode: input.reasonCode,\n reasonText: input.reasonText,\n runtimeContext: null,\n status: \"invalid\",\n workspaceMode: input.workspaceMode ?? null,\n };\n default:\n throw new Error(\"unsupported profile workspace runtime status\");\n }\n}\n\nfunction buildProviderConversationProofNotRun(\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"]\n): OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"] {\n return {\n agentControllerConversationId: null,\n checkedAt: null,\n errorCode: null,\n errorMessage: null,\n errorType: null,\n expiresAt: null,\n intrusive: false,\n method: null,\n provider: null,\n status: \"not_run\",\n transportMode,\n };\n}\n\nexport async function resolveLocalProviderConversationProof(input: {\n agentControllerConversationId: string | null;\n boundAgentControllerRef: string | null;\n launchContract: RuntimeAgentControllerLaunchContract | null;\n profileAgentControllerRef: string;\n runtimeWorkingDirectory: string | null;\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n}): Promise<\n OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"]\n> {\n const checkedAt = new Date().toISOString();\n const providerId = normalizeKnownBuiltinAgentControllerId(\n input.profileAgentControllerRef\n );\n const provider = resolveProviderConversationProofProvider(providerId);\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n const base = {\n agentControllerConversationId,\n checkedAt,\n errorCode: null,\n errorMessage: null,\n errorType: null,\n expiresAt: null,\n intrusive: false,\n method: resolveProviderConversationProofMethod({\n provider,\n transportMode: input.transportMode,\n }),\n provider,\n transportMode: input.transportMode,\n } satisfies Omit<\n OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"],\n \"status\"\n >;\n\n if (!agentControllerConversationId) {\n return {\n ...base,\n status: \"not_applicable\",\n };\n }\n\n if (!(provider === \"codex\" && input.transportMode === \"codex-app-server\")) {\n return {\n ...base,\n status: \"not_applicable\",\n };\n }\n\n if (!input.launchContract) {\n return {\n ...base,\n errorCode: \"controller.launch.needs_repair\",\n errorMessage:\n \"The current agent profile controller does not have an available local launch contract on this device.\",\n errorType: \"config\",\n status: \"failed\",\n };\n }\n\n if (!input.runtimeWorkingDirectory) {\n return {\n ...base,\n errorCode: \"workspace.missing\",\n errorMessage:\n \"The current agent profile workspace is unavailable for dispatch on this device.\",\n errorType: \"config\",\n status: \"failed\",\n };\n }\n\n if (\n input.boundAgentControllerRef &&\n input.boundAgentControllerRef !== input.profileAgentControllerRef\n ) {\n return {\n ...base,\n errorCode: \"controller_ref_mismatch\",\n errorMessage:\n \"The bound agent controller conversation controller does not match the current agent profile controller.\",\n errorType: \"config\",\n status: \"failed\",\n };\n }\n\n const agentControllerConversationKind = providerId\n ? resolveBuiltinAgentControllerConversationKind(\n input.profileAgentControllerRef\n )\n : null;\n if (!agentControllerConversationKind) {\n return {\n ...base,\n errorCode: \"provider_unsupported\",\n errorMessage: `Provider conversation proof is not available for ${input.profileAgentControllerRef}.`,\n errorType: \"config\",\n status: \"failed\",\n };\n }\n const agentControllerConversation = buildAgentControllerConversationRef({\n agentControllerRef: input.profileAgentControllerRef,\n agentControllerConversationId,\n agentControllerConversationKind,\n });\n\n try {\n await verifyCodexAppServerThread({\n codexTimeoutMs: resolveProviderConversationProofTimeoutMs(\n resolveCodexTimeoutMs()\n ),\n codexWorkdir: input.runtimeWorkingDirectory,\n launchContract: input.launchContract,\n threadId: agentControllerConversation.agentControllerConversationId,\n });\n\n return {\n ...base,\n expiresAt: new Date(\n Date.parse(checkedAt) + PROVIDER_CONVERSATION_PROOF_TTL_MS\n ).toISOString(),\n status: \"passed\",\n };\n } catch (error) {\n return {\n ...base,\n errorCode: readErrorCode(error),\n errorMessage: readErrorMessage(error),\n errorType: readErrorType(error),\n status: \"failed\",\n };\n }\n}\n\nfunction resolveProviderConversationProofProvider(\n value: string | null\n): OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"][\"provider\"] {\n if (value === \"codex\" || value === \"claude-code\" || value === \"openclaw\") {\n return value;\n }\n return null;\n}\n\nfunction resolveProviderConversationProofMethod(input: {\n provider: OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"][\"provider\"];\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n}): OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"][\"method\"] {\n if (\n input.provider === \"codex\" &&\n input.transportMode === \"codex-app-server\"\n ) {\n return \"codex_app_server_thread_resume\";\n }\n return null;\n}\n\nasync function resolveLocalLedgerConversationExecution(input: {\n agentControllerRef: string;\n spaceId: string;\n targetProfileId: string;\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n workspaceResolution: Awaited<\n ReturnType<typeof resolveProfileWorkspaceRuntime>\n >;\n}): Promise<{\n agentContextLookupKey: string;\n executionState: ConversationExecutionState | null;\n previousAgentControllerConversationId: string | null;\n runtimeWorkspaceFingerprint: string | null;\n}> {\n const io = createLedgerIo();\n const runtimePaths = await ensureDaemonRuntimePaths();\n const ledgerState = await loadLedgerState({\n invalidStateStrategy: \"backup_and_reset\",\n io,\n paths: buildLedgerPaths(runtimePaths.ledgerRootPath),\n });\n\n if (input.workspaceResolution.status !== \"ready\") {\n return {\n agentContextLookupKey: buildUnresolvedRuntimeWorkspaceLookupKey({\n agentControllerRef: input.agentControllerRef,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n transportMode: input.transportMode,\n }),\n executionState: null,\n previousAgentControllerConversationId: null,\n runtimeWorkspaceFingerprint: null,\n };\n }\n\n const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n input.workspaceResolution.effectiveRuntimeWorkingDirectory\n );\n const keyInput = {\n agentControllerRef: input.agentControllerRef,\n runtimeWorkspaceFingerprint,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n transportMode: input.transportMode,\n } as const;\n const agentContextLookupKey = buildAgentContextLookupKey(keyInput);\n const previousAgentContextMatch = resolveCompatibleAgentContextMatch({\n key: keyInput,\n state: ledgerState,\n });\n const executionState = resolveCompatibleConversationExecutionState({\n key: keyInput,\n preferredLookupKey:\n previousAgentContextMatch?.agentContextLookupKey ?? null,\n state: ledgerState,\n });\n\n return {\n agentContextLookupKey,\n executionState,\n previousAgentControllerConversationId:\n previousAgentContextMatch?.agentContext.agentControllerConversationId ??\n null,\n runtimeWorkspaceFingerprint,\n };\n}\n\nfunction buildUnresolvedRuntimeWorkspaceLookupKey(input: {\n agentControllerRef: string;\n spaceId: string;\n targetProfileId: string;\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n}): string {\n return [\n input.spaceId,\n input.targetProfileId,\n encodeURIComponent(input.agentControllerRef),\n input.transportMode,\n \"runtime-workspace-unresolved\",\n ].join(\"|\");\n}\n\nfunction readErrorCode(error: unknown): string | null {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\"\n ) {\n return error.code;\n }\n return null;\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\nfunction readErrorType(error: unknown): string | null {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"errorType\" in error &&\n typeof error.errorType === \"string\"\n ) {\n return error.errorType;\n }\n return null;\n}\n\nconst PROVIDER_CONVERSATION_PROOF_TIMEOUT_MS = 30_000;\nconst PROVIDER_CONVERSATION_PROOF_TTL_MS = 10 * 60_000;\n\nfunction resolveProviderConversationProofTimeoutMs(\n runtimeTimeoutMs: number | null\n) {\n if (runtimeTimeoutMs === null) {\n return PROVIDER_CONVERSATION_PROOF_TIMEOUT_MS;\n }\n return Math.min(runtimeTimeoutMs, PROVIDER_CONVERSATION_PROOF_TIMEOUT_MS);\n}\n","import type {\n OpenMeldDaemonProviderConversationProof,\n RuntimeAgentControllerLaunchContract,\n} from \"@openmeld/schemas/types\";\nimport { resolveLocalProviderConversationProof } from \"../control-plane/conversation-execution-status\";\nimport type { RouteCatalog } from \"../core/types\";\nimport {\n notifyRuntimeReportingAttemptObserver,\n type RuntimeProviderConversationProofInput,\n type RuntimeProviderConversationProofSubmission,\n type RuntimeReportingAttemptObserver,\n submitRuntimeProviderConversationProofs,\n} from \"./runtime-agent-controller-reporting-submission\";\n\nconst PROVIDER_CONVERSATION_PROOF_FALLBACK_TTL_MS = 10 * 60_000;\n\nexport type LocalServiceProviderConversationProofSyncResult =\n | {\n status: \"skipped\";\n reasonCodes: readonly string[];\n proofCount: 0;\n submittedCount: 0;\n failedCount: 0;\n }\n | {\n status: \"submitted\";\n reasonCodes: readonly string[];\n proofCount: number;\n submittedCount: number;\n failedCount: number;\n };\n\nexport async function syncLocalServiceProviderConversationProofs(input: {\n onAttempt?: RuntimeReportingAttemptObserver;\n routeCatalog: RouteCatalog;\n}): Promise<LocalServiceProviderConversationProofSyncResult> {\n let proofInputs: RuntimeProviderConversationProofInput[];\n try {\n proofInputs = (\n await Promise.all(\n [...input.routeCatalog.routeByProfileId.values()].map(async (route) => {\n if (!isCodexAppServerRouteWithConversation(route)) {\n return null;\n }\n const workspace = route.workingFolderRuntime;\n if (!workspace) {\n return null;\n }\n const proof = await resolveLocalProviderConversationProof({\n agentControllerConversationId: route.agentControllerConversationId,\n boundAgentControllerRef: route.agentControllerRef,\n launchContract: route.launchContract ?? null,\n profileAgentControllerRef: route.agentControllerRef,\n runtimeWorkingDirectory: workspace.effectiveRuntimeWorkingDirectory,\n transportMode: route.transportMode,\n });\n return toRuntimeProviderConversationProofInput({\n agentControllerConversationId: route.agentControllerConversationId,\n agentControllerRef: route.agentControllerRef,\n bindingId: route.bindingId,\n profileId: route.profileId,\n proof,\n });\n })\n )\n ).filter(\n (proof): proof is RuntimeProviderConversationProofInput => proof !== null\n );\n } catch (error) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"provider_conversation_proof\",\n message: \"Provider conversation proof collection failed.\",\n reasonCode: \"provider_conversation.runtime_reporting.collection_failed\",\n status: \"failed\",\n });\n throw error;\n }\n\n if (proofInputs.length === 0) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"provider_conversation_proof\",\n message: null,\n reasonCode: \"provider_conversation.proof.no_applicable_routes\",\n status: \"not_applicable\",\n });\n return {\n status: \"skipped\",\n reasonCodes: [\"provider_conversation.proof.no_applicable_routes\"],\n proofCount: 0,\n submittedCount: 0,\n failedCount: 0,\n };\n }\n\n const submissions = await submitRuntimeProviderConversationProofs({\n ...(input.onAttempt ? { onAttempt: input.onAttempt } : {}),\n proofs: proofInputs,\n });\n return summarizeSubmissions(submissions);\n}\n\nfunction isCodexAppServerRouteWithConversation(route: {\n agentControllerConversationId?: string | null;\n agentControllerRef: string;\n bindingId?: string;\n launchContract?: RuntimeAgentControllerLaunchContract | null;\n transportMode: string;\n}): route is typeof route & {\n agentControllerConversationId: string;\n bindingId: string;\n launchContract: RuntimeAgentControllerLaunchContract;\n transportMode: \"codex-app-server\";\n} {\n return (\n route.agentControllerRef === \"builtin:codex\" &&\n route.transportMode === \"codex-app-server\" &&\n Boolean(route.agentControllerConversationId?.trim()) &&\n Boolean(route.bindingId?.trim()) &&\n Boolean(route.launchContract)\n );\n}\n\nfunction toRuntimeProviderConversationProofInput(input: {\n agentControllerConversationId: string;\n agentControllerRef: string;\n bindingId: string;\n profileId: string;\n proof: OpenMeldDaemonProviderConversationProof;\n}): RuntimeProviderConversationProofInput | null {\n if (!(input.proof.status === \"passed\" || input.proof.status === \"failed\")) {\n return null;\n }\n if (\n !(\n input.proof.provider === \"codex\" &&\n input.proof.method === \"codex_app_server_thread_resume\" &&\n input.proof.transportMode === \"codex-app-server\" &&\n input.proof.intrusive === false\n )\n ) {\n return null;\n }\n\n const observedAtMs = Date.parse(input.proof.checkedAt ?? \"\");\n if (!(Number.isFinite(observedAtMs) && observedAtMs > 0)) {\n return null;\n }\n const parsedExpiresAtMs = Date.parse(input.proof.expiresAt ?? \"\");\n const expiresAtMs =\n Number.isFinite(parsedExpiresAtMs) && parsedExpiresAtMs > observedAtMs\n ? parsedExpiresAtMs\n : observedAtMs + PROVIDER_CONVERSATION_PROOF_FALLBACK_TTL_MS;\n\n return {\n agentProfileId: input.profileId,\n bindingId: input.bindingId,\n agentControllerRef: input.agentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n transportMode: \"codex-app-server\",\n provider: \"codex\",\n method: \"codex_app_server_thread_resume\",\n intrusive: false,\n observedAtMs,\n expiresAtMs,\n status: input.proof.status,\n ...(input.proof.errorCode ? { errorCode: input.proof.errorCode } : {}),\n ...(input.proof.errorMessage\n ? { errorMessage: input.proof.errorMessage }\n : {}),\n ...(input.proof.errorType ? { errorType: input.proof.errorType } : {}),\n };\n}\n\nfunction summarizeSubmissions(\n submissions: readonly RuntimeProviderConversationProofSubmission[]\n): LocalServiceProviderConversationProofSyncResult {\n const submittedCount = submissions.filter(\n (submission) =>\n submission.status === \"submitted\" &&\n submission.providerConversationProofStatus === \"accepted\"\n ).length;\n const failedCount = submissions.length - submittedCount;\n return {\n status: \"submitted\",\n reasonCodes: [\n ...new Set(\n submissions\n .flatMap((submission) => submission.reasonCodes)\n .filter((reasonCode) => reasonCode.trim())\n ),\n ],\n proofCount: submissions.length,\n submittedCount,\n failedCount,\n };\n}\n","import type { LocalDaemonAdapterContainer } from \"@openmeld/local-service\";\nimport { reconcileNewRunnableBuiltinAgentRegistrations } from \"../../agents/registry\";\nimport type { AgentControllerInterfaceProbePolicy } from \"../inventory/agent-controller-interface\";\nimport {\n collectLocalAgentControllerInventory,\n resolveLocalAgentControllerReportDecision,\n} from \"../inventory/agent-controller-inventory\";\nimport {\n notifyRuntimeReportingAttemptObserver,\n type RuntimeAgentControllerReportSubmission,\n type RuntimeReportingAttemptObserver,\n submitRuntimeAgentControllerReports,\n} from \"./runtime-agent-controller-reporting-submission\";\n\nexport type LocalServiceRuntimeAgentControllerReportSyncResult =\n | {\n status: \"skipped\";\n reasonCodes: readonly string[];\n reportCount: 0;\n submittedCount: 0;\n failedCount: 0;\n }\n | {\n status: \"submitted\";\n reasonCodes: readonly string[];\n reportCount: number;\n submittedCount: number;\n failedCount: number;\n };\n\nexport async function syncLocalServiceRuntimeAgentControllerReports(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n onAttempt?: RuntimeReportingAttemptObserver;\n probePolicy?: AgentControllerInterfaceProbePolicy;\n}): Promise<LocalServiceRuntimeAgentControllerReportSyncResult> {\n // OPENMELD_SERVICE_THIN_CORE: runtime Agent Controller report evidence.\n // This reports detected local controller capabilities for the current\n // service identity. It must remain evidence, not Binding truth or final Ready.\n let inventory: Awaited<\n ReturnType<typeof collectLocalAgentControllerInventory>\n >;\n try {\n // Discovery belongs to the existing background inventory pass, not route\n // registration. Slow unrelated install probes must not strand new Wakes.\n // Newly registered controllers notify the carrier through the normal\n // lane-local catalog-change signal; explicit disabled choices stay intact.\n await reconcileNewRunnableBuiltinAgentRegistrations();\n inventory = await collectLocalAgentControllerInventory({\n includeControllerInterface: true,\n localAdapterContainer: input.localAdapterContainer,\n probePolicy: input.probePolicy,\n });\n } catch (error) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"runtime_agent_controller\",\n message: \"Local agent inventory collection failed.\",\n reasonCode: \"runtime.reporting.inventory_failed\",\n status: \"failed\",\n });\n throw error;\n }\n const reports = inventory.capabilities\n .filter((capability) => capability.registered)\n .map((capability) => {\n if (!capability.agentControllerRef) {\n return null;\n }\n const reportDecision = resolveLocalAgentControllerReportDecision(\n capability,\n { requireEnabled: true }\n );\n return {\n agentControllerRef: capability.agentControllerRef,\n ...(capability.agentControllerInterface\n ? { agentControllerInterface: capability.agentControllerInterface }\n : {}),\n enabled: capability.enabled,\n localParticipationState: reportDecision.localParticipationState,\n reasonCodes: reportDecision.reasonCodes,\n };\n })\n .filter((report): report is NonNullable<typeof report> => report !== null);\n\n if (reports.length === 0) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"runtime_agent_controller\",\n message: \"No local controllers are installed on this computer.\",\n reasonCode: \"runtime.agent_controller_report.no_local_controllers\",\n status: \"not_applicable\",\n });\n return {\n status: \"skipped\",\n reasonCodes: [\"runtime.agent_controller_report.no_local_controllers\"],\n reportCount: 0,\n submittedCount: 0,\n failedCount: 0,\n };\n }\n\n const submissions = await submitRuntimeAgentControllerReports({\n ...(input.onAttempt ? { onAttempt: input.onAttempt } : {}),\n reports,\n });\n return summarizeSubmissions(submissions);\n}\n\nfunction summarizeSubmissions(\n submissions: readonly RuntimeAgentControllerReportSubmission[]\n): LocalServiceRuntimeAgentControllerReportSyncResult {\n const submittedCount = submissions.filter(\n (submission) =>\n submission.status === \"submitted\" &&\n submission.agentControllerReportStatus === \"accepted\"\n ).length;\n const failedCount = submissions.length - submittedCount;\n return {\n status: \"submitted\",\n reasonCodes: [\n ...new Set(\n submissions\n .flatMap((submission) => submission.reasonCodes)\n .filter((reasonCode) => reasonCode.trim())\n ),\n ],\n reportCount: submissions.length,\n submittedCount,\n failedCount,\n };\n}\n","import type { RuntimeReportingServiceIdentity } from \"@openmeld/schemas/types\";\nimport { toErrorMessage, warnDaemonEvent } from \"../core/logger\";\nimport {\n recordRuntimeReportingFailure,\n recordRuntimeReportingNotApplicable,\n recordRuntimeReportingSuccess,\n} from \"../state/runtime-reporting-health-state\";\nimport type {\n RuntimeReportingAttempt,\n RuntimeReportingAttemptObserver,\n} from \"./runtime-agent-controller-reporting-submission\";\nimport type { RuntimeReportingAuthenticationFailure } from \"./runtime-reporting-auth-recovery\";\n\nexport function createRuntimeReportingAttemptObserver(input: {\n serviceIdentity: RuntimeReportingServiceIdentity;\n onAuthenticationFailure?: (\n failure: RuntimeReportingAuthenticationFailure\n ) => Promise<void> | void;\n}): RuntimeReportingAttemptObserver {\n return async (attempt) => {\n await persistRuntimeReportingAttempt(attempt, input.serviceIdentity);\n if (\n attempt.status === \"failed\" &&\n attempt.authenticationRejected &&\n attempt.reasonCode &&\n attempt.message\n ) {\n await input.onAuthenticationFailure?.({\n ...(attempt.credentialFingerprint\n ? { credentialFingerprint: attempt.credentialFingerprint }\n : {}),\n message: attempt.message,\n reasonCode: attempt.reasonCode,\n });\n }\n };\n}\n\nasync function persistRuntimeReportingAttempt(\n attempt: RuntimeReportingAttempt,\n serviceIdentity: RuntimeReportingServiceIdentity\n): Promise<void> {\n const channel =\n attempt.family === \"runtime_agent_controller\"\n ? \"runtimeAgentController\"\n : \"providerConversationProof\";\n try {\n if (attempt.status === \"succeeded\") {\n await recordRuntimeReportingSuccess({ channel, serviceIdentity });\n return;\n }\n if (attempt.status === \"not_applicable\") {\n await recordRuntimeReportingNotApplicable({ channel, serviceIdentity });\n return;\n }\n await recordRuntimeReportingFailure({\n channel,\n message: attempt.message ?? \"Runtime reporting failed.\",\n reasonCode: attempt.reasonCode ?? \"runtime.reporting.failed\",\n serviceIdentity,\n });\n } catch (error) {\n warnDaemonEvent(\"[openmeld.runtime_reporting.health_write_failed]\", {\n error: toErrorMessage(error),\n event: \"cli.runtime_reporting.health_write_failed\",\n family: attempt.family,\n reasonCode: attempt.reasonCode,\n status: attempt.status,\n });\n }\n}\n","import type {\n InflightTaskControlRegistry,\n LocalDaemonAdapterContainer,\n} from \"@openmeld/local-service\";\nimport type { AgentControllerPermissionMode } from \"@openmeld/schemas/types\";\nimport type { MutableRouteCatalogState } from \"../core/types\";\n\nexport type ActivePermissionModeSyncOutcome = {\n adapterId: string;\n agentControllerPermissionMode: AgentControllerPermissionMode;\n errorMessage?: string;\n reasonCode?:\n | \"adapter.permission_mode_incompatible\"\n | \"adapter.permission_mode_update_unsupported\"\n | \"adapter.task_not_active\";\n status: \"applied\" | \"failed\" | \"not_applied\";\n targetProfileId: string;\n taskId: string;\n};\n\nexport async function syncActiveTaskPermissionModes(input: {\n catalogState: MutableRouteCatalogState;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n localAdapterContainer: LocalDaemonAdapterContainer;\n}): Promise<ActivePermissionModeSyncOutcome[]> {\n const outcomes: ActivePermissionModeSyncOutcome[] = [];\n\n for (const task of input.inflightTaskControlRegistry.listTasks()) {\n if (!task.targetProfileId) {\n continue;\n }\n const route = input.catalogState.routeByProfileId.get(task.targetProfileId);\n const nextPermissionMode = route?.agentControllerPermissionMode;\n if (\n !nextPermissionMode ||\n nextPermissionMode === task.agentControllerPermissionMode\n ) {\n continue;\n }\n\n const adapterEntry = input.localAdapterContainer.getAdapter(task.adapterId);\n const updatePermissionMode = adapterEntry?.adapter.updatePermissionMode;\n if (!updatePermissionMode) {\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n reasonCode: \"adapter.permission_mode_update_unsupported\",\n status: \"not_applied\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n continue;\n }\n\n try {\n const result = await updatePermissionMode({\n agentControllerPermissionMode: nextPermissionMode,\n taskId: task.taskId,\n });\n if (result.status === \"not_applied\") {\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n reasonCode: result.reasonCode,\n status: \"not_applied\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n continue;\n }\n\n input.inflightTaskControlRegistry.updateTaskPermissionMode({\n agentControllerPermissionMode: nextPermissionMode,\n taskId: task.taskId,\n });\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n status: \"applied\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n } catch (error) {\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n errorMessage: error instanceof Error ? error.message : String(error),\n status: \"failed\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n }\n }\n\n return outcomes;\n}\n","import { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirnamePath, normalizeOptionalText } from \"../core/logger\";\n\nexport async function loadContextStore(\n contextStorePath: string\n): Promise<Map<string, string>> {\n const raw = await readFile(contextStorePath, \"utf8\").catch(() => \"\");\n if (!raw) {\n return new Map();\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return new Map();\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return new Map();\n }\n const contextStore = new Map<string, string>();\n for (const [key, value] of Object.entries(parsed)) {\n const normalizedKey = normalizeOptionalText(key);\n const normalizedValue = normalizeOptionalText(value);\n if (!(normalizedKey && normalizedValue)) {\n continue;\n }\n contextStore.set(normalizedKey, normalizedValue);\n }\n return contextStore;\n}\n\nexport async function persistContextStore(input: {\n contextStore: Map<string, string>;\n contextStorePath: string;\n}): Promise<void> {\n const payload = Object.fromEntries(input.contextStore.entries());\n const tempPath = `${input.contextStorePath}.tmp-${Date.now()}-${process.pid}`;\n await mkdir(dirnamePath(input.contextStorePath), {\n recursive: true,\n });\n await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, input.contextStorePath).catch(async (error) => {\n await rm(tempPath, {\n force: true,\n }).catch(() => undefined);\n throw error;\n });\n}\n","import type { LocalDaemonAdapterContainer } from \"@openmeld/local-service\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type { RouteCatalog } from \"../core/types\";\nimport { emitDaemonLifecycleEvent } from \"../lifecycle/daemon-lifecycle-journal\";\nimport {\n loadDaemonRouteCatalog,\n type RouteCatalogLoadPhaseTimings,\n} from \"../routing/route-catalog\";\nimport {\n readDaemonRouteCatalogCache,\n writeDaemonRouteCatalogCache,\n} from \"../state/route-catalog-cache\";\n\ntype CatalogOwner = {\n lane: string;\n localAdapterContainer: LocalDaemonAdapterContainer;\n ownerUserId: string;\n presenter: Presenter;\n serviceBundleId: string | null;\n};\n\nexport async function loadExecutionHostCatalog(\n owner: CatalogOwner,\n initial: boolean\n): Promise<RouteCatalog> {\n if (!initial) {\n return await loadDaemonRouteCatalog({\n localAdapterContainer: owner.localAdapterContainer,\n ownerUserId: owner.ownerUserId,\n presenter: owner.presenter,\n allowEmpty: true,\n localReplyStateMode: \"check\",\n quiet: true,\n });\n }\n const startedAt = Date.now();\n const phaseTimings: RouteCatalogLoadPhaseTimings = {};\n await recordInitialLoad(\"started\", {});\n try {\n const catalog = await loadDaemonRouteCatalog({\n allowEmpty: true,\n localAdapterContainer: owner.localAdapterContainer,\n localReplyStateMode: \"check\",\n ownerUserId: owner.ownerUserId,\n phaseTimings,\n presenter: owner.presenter,\n });\n await recordInitialLoad(\"completed\", {\n durationMs: Date.now() - startedAt,\n phaseTimings,\n profileCount: catalog.profileIds.length,\n skippedProfileCount: catalog.skippedProfiles.length,\n });\n return catalog;\n } catch (error) {\n const cached = await readDaemonRouteCatalogCache({\n lane: owner.lane,\n ownerUserId: owner.ownerUserId,\n serviceBundleId: owner.serviceBundleId,\n });\n emitRunLine({\n presenter: owner.presenter,\n code: cached\n ? \"daemon.run.route_catalog_cache_recovered\"\n : \"daemon.run.route_catalog_initial_load_failed\",\n text: cached\n ? `using last known route catalog after initial catalog load failed: ${toErrorMessage(error)}`\n : `initial route catalog load failed; starting with an empty catalog and retrying via catalog sync: ${toErrorMessage(error)}`,\n payload: {\n reason: cached ? \"initial_load_failed\" : \"initial_load_failed_no_cache\",\n },\n });\n await recordInitialLoad(cached ? \"cache_recovered\" : \"failed_empty_start\", {\n durationMs: Date.now() - startedAt,\n errorMessage: toErrorMessage(error),\n phaseTimings,\n ...(cached ? { profileCount: cached.profileIds.length } : {}),\n });\n return (\n cached ?? {\n profileIds: [],\n routeByProfileId: new Map(),\n skippedProfiles: [],\n }\n );\n }\n}\n\nexport async function persistExecutionHostCatalog(\n owner: CatalogOwner,\n routeCatalog: RouteCatalog\n): Promise<void> {\n try {\n await writeDaemonRouteCatalogCache({\n lane: owner.lane,\n ownerUserId: owner.ownerUserId,\n serviceBundleId: owner.serviceBundleId,\n routeCatalog,\n });\n } catch (error) {\n emitRunLine({\n presenter: owner.presenter,\n code: \"daemon.run.route_catalog_cache_write_failed\",\n text: `route catalog cache write failed: ${toErrorMessage(error)}`,\n });\n }\n}\n\nasync function recordInitialLoad(\n result: string,\n metadata: Record<string, unknown>\n): Promise<void> {\n // Match the existing diagnostic contract: journaling never owns startup.\n await emitDaemonLifecycleEvent({\n type: \"route_catalog.initial_load\",\n result,\n metadata,\n }).catch(() => undefined);\n}\n","import type { AdapterComputerFileAccessBoundary } from \"@openmeld/adapter-core\";\nimport type { LocalDaemonAdapterContainer } from \"@openmeld/local-service\";\nimport {\n buildAgentControllerConversationRef,\n resolveBuiltinAgentControllerConversationKind,\n} from \"@openmeld/schemas\";\nimport type {\n RuntimeTransportResumeControllerConversationFramePayload,\n RuntimeTransportResumeControllerConversationResult,\n} from \"@openmeld/schemas/types\";\nimport type { DaemonProfileRouteConfig } from \"../core/types\";\nimport { assertComputerFileAccessWorkingDirectoryAllowed } from \"../file-access/computer-file-access-admission\";\nimport { COMPUTER_FILE_ACCESS_AWARENESS } from \"../file-access/computer-file-access-prompt\";\nimport { readComputerFileAccessPolicy } from \"../file-access/computer-file-access-store\";\nimport { resolveLocalRuntimeControllerSupport } from \"../routing/resolve-controller-support\";\n\ntype RecoveryRouteConfig = Pick<\n DaemonProfileRouteConfig,\n | \"agentControllerPermissionMode\"\n | \"agentControllerRef\"\n | \"launchContract\"\n | \"profileId\"\n | \"transportMode\"\n>;\n\nconst RECOVERY_PROMPT = [\n \"OpenMeld execution recovery.\",\n \"Continue this exact controller conversation.\",\n \"Do not redo the task, call tools, edit files, or perform external actions.\",\n \"Return the best faithful final answer you can recover from this conversation.\",\n \"Your answer is content only. OpenMeld decides recovery status from the typed provider outcome, never from words in your answer.\",\n].join(\" \");\n\nexport async function resumeExactControllerConversation(input: {\n computerFileAccessStorePath: string;\n localAdapterContainer: LocalDaemonAdapterContainer;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n routeConfig?: RecoveryRouteConfig | null;\n}): Promise<RuntimeTransportResumeControllerConversationResult> {\n const identity = input.request.identity;\n const controllerRef = identity.agentControllerRef;\n const conversationId = identity.agentControllerConversationId;\n if (!(controllerRef && conversationId)) {\n return rejected(input.request, \"execution_recovery.identity_incomplete\");\n }\n const support = resolveLocalRuntimeControllerSupport({\n agentControllerRef: controllerRef,\n localAdapterContainer: input.localAdapterContainer,\n });\n if (!support.supported) {\n return rejected(input.request, support.reasonCode, support.reasonDetail);\n }\n if (\n !support.localAdapterEntry.transportModes.includes(\n input.request.transportMode\n )\n ) {\n return rejected(\n input.request,\n \"execution_recovery.transport_mode_unsupported\"\n );\n }\n const conversationKind =\n resolveBuiltinAgentControllerConversationKind(controllerRef);\n if (!conversationKind) {\n return rejected(\n input.request,\n \"execution_recovery.controller_conversation_kind_unsupported\"\n );\n }\n const exactConversation = buildAgentControllerConversationRef({\n agentControllerConversationId: conversationId,\n agentControllerConversationKind: conversationKind,\n agentControllerRef: controllerRef,\n });\n const fileAccess = await resolveRecoveryComputerFileAccess({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n request: input.request,\n routeConfig: input.routeConfig ?? null,\n support,\n });\n if (fileAccess.status === \"rejected\") {\n return fileAccess.result;\n }\n const computerFileAccessBoundary = fileAccess.boundary;\n const result = await support.localAdapterEntry.adapter.dispatch({\n agentControllerConversation: exactConversation,\n agentControllerConversationId: conversationId,\n agentId: identity.targetProfileId,\n dispatchId: identity.dispatchId,\n executionMode: \"repair\",\n ...(computerFileAccessBoundary ? { computerFileAccessBoundary } : {}),\n prompt: computerFileAccessBoundary\n ? `${COMPUTER_FILE_ACCESS_AWARENESS} ${RECOVERY_PROMPT}`\n : RECOVERY_PROMPT,\n runtimeContext: {\n providerRuntimeWorkingDirectory:\n input.request.providerRuntimeWorkingDirectory,\n },\n sourceEventId: input.request.sourceEventId,\n spaceId: identity.spaceId,\n streamingMode: \"final\",\n taskId:\n identity.taskId ?? `execution-recovery:${input.request.operationId}`,\n transportMode: input.request.transportMode,\n });\n if (result.status !== \"success\") {\n return {\n destination: input.request.destination,\n identity,\n message: result.errorMessage,\n operationId: input.request.operationId,\n reasonCode:\n result.errorCode ?? \"execution_recovery.controller_resume_failed\",\n status: \"outcome_unknown\",\n };\n }\n const observedConversationId =\n result.contextDelta?.agentControllerConversationId ?? conversationId;\n if (observedConversationId !== conversationId) {\n return {\n destination: input.request.destination,\n identity,\n message:\n \"The controller returned a different conversation during recovery.\",\n operationId: input.request.operationId,\n reasonCode: \"execution_recovery.controller_conversation_mismatch\",\n status: \"outcome_unknown\",\n };\n }\n const output = result.output.trim();\n if (!output) {\n return {\n destination: input.request.destination,\n identity,\n message: \"The exact conversation did not contain a completed result.\",\n operationId: input.request.operationId,\n reasonCode: \"execution_recovery.completed_result_unavailable\",\n status: \"outcome_unknown\",\n };\n }\n return {\n agentControllerConversationId: conversationId,\n destination: input.request.destination,\n identity,\n operationId: input.request.operationId,\n output,\n status: \"completed\",\n };\n}\n\nasync function resolveRecoveryComputerFileAccess(input: {\n computerFileAccessStorePath: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n routeConfig: RecoveryRouteConfig | null;\n support: Extract<\n ReturnType<typeof resolveLocalRuntimeControllerSupport>,\n { supported: true }\n >;\n}): Promise<\n | {\n boundary: AdapterComputerFileAccessBoundary | null;\n status: \"ready\";\n }\n | {\n result: RuntimeTransportResumeControllerConversationResult;\n status: \"rejected\";\n }\n> {\n const policy = await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n );\n if (policy.mode === \"local_agent_settings\") {\n return { boundary: null, status: \"ready\" };\n }\n if (\n input.support.localAdapterEntry.adapterId !== \"codex\" ||\n (input.request.transportMode !== \"codex-app-server\" &&\n input.request.transportMode !== \"local-cli\")\n ) {\n return {\n result: rejected(\n input.request,\n \"execution_recovery.computer_file_access_unverified\",\n \"OpenMeld could not verify this Computer’s file access boundary for execution recovery.\"\n ),\n status: \"rejected\",\n };\n }\n try {\n await assertComputerFileAccessWorkingDirectoryAllowed({\n boundary: policy,\n providerRuntimeWorkingDirectory:\n input.request.providerRuntimeWorkingDirectory,\n });\n } catch {\n return {\n result: rejected(\n input.request,\n \"computer.file_access.working_directory_denied\",\n \"This recovery working folder is outside the Computer file access boundary.\"\n ),\n status: \"rejected\",\n };\n }\n\n const routeConfig = input.routeConfig;\n const verifyBoundary =\n input.support.localAdapterEntry.adapter.verifyComputerFileAccessBoundary;\n if (\n !(verifyBoundary && routeConfig) ||\n routeConfig.profileId !== input.request.identity.targetProfileId ||\n routeConfig.agentControllerRef !==\n input.request.identity.agentControllerRef ||\n routeConfig.transportMode !== input.request.transportMode\n ) {\n return unverifiedComputerFileAccess(input.request);\n }\n try {\n const verification = await verifyBoundary({\n agentControllerPermissionMode: routeConfig.agentControllerPermissionMode,\n boundary: policy,\n executionMode: \"repair\",\n launchContract: routeConfig.launchContract ?? null,\n transportMode: input.request.transportMode,\n workingDirectory: input.request.providerRuntimeWorkingDirectory,\n });\n if (!verification.supported) {\n return unverifiedComputerFileAccess(input.request);\n }\n } catch {\n return unverifiedComputerFileAccess(input.request);\n }\n return { boundary: policy, status: \"ready\" };\n}\n\nfunction unverifiedComputerFileAccess(\n request: RuntimeTransportResumeControllerConversationFramePayload\n): {\n result: RuntimeTransportResumeControllerConversationResult;\n status: \"rejected\";\n} {\n return {\n result: rejected(\n request,\n \"execution_recovery.computer_file_access_unverified\",\n \"OpenMeld could not verify this Computer’s file access boundary for execution recovery.\"\n ),\n status: \"rejected\",\n };\n}\n\nfunction rejected(\n request: RuntimeTransportResumeControllerConversationFramePayload,\n reasonCode: string,\n message = reasonCode\n): RuntimeTransportResumeControllerConversationResult {\n return {\n destination: request.destination,\n identity: request.identity,\n message,\n operationId: request.operationId,\n reasonCode,\n status: \"rejected\",\n };\n}\n","import { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type {\n RuntimeTransportResumeControllerConversationFramePayload,\n RuntimeTransportResumeControllerConversationResult,\n} from \"@openmeld/schemas/types\";\n\nconst STORE_SCHEMA =\n \"openmeld-daemon-execution-recovery-operation-store-v1\" as const;\nconst RECORD_SCHEMA =\n \"openmeld-daemon-execution-recovery-operation-record-v1\" as const;\nconst STORE_FILE_NAME = \"execution-recovery-operations.json\";\nconst STORE_TEMP_FILE_NAME = \"execution-recovery-operations.tmp\";\nconst MAX_RETAINED_RECORDS = 256;\n\ntype StoredResumeControllerConversationOperation = {\n operationId: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n requestFingerprint: string;\n result: RuntimeTransportResumeControllerConversationResult | null;\n schema: typeof RECORD_SCHEMA;\n status: \"completed\" | \"in_progress\" | \"outcome_unknown\";\n updatedAtMs: number;\n};\n\ntype OperationStoreFile = {\n records: StoredResumeControllerConversationOperation[];\n schema: typeof STORE_SCHEMA;\n updatedAtMs: number;\n v: 1;\n};\n\ntype ReadRecordsResult =\n | {\n ok: true;\n records: StoredResumeControllerConversationOperation[];\n }\n | {\n ok: false;\n reasonCode:\n | \"execution_recovery.operation_store_invalid\"\n | \"execution_recovery.operation_store_unavailable\"\n | \"execution_recovery.operation_store_update_required\";\n };\n\nconst storeTails = new Map<string, Promise<void>>();\n\nexport async function runResumeControllerConversationOperation(input: {\n execute: () => Promise<RuntimeTransportResumeControllerConversationResult>;\n ledgerRootPath: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n}): Promise<RuntimeTransportResumeControllerConversationResult> {\n const previous = storeTails.get(input.ledgerRootPath) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n storeTails.set(input.ledgerRootPath, tail);\n await previous;\n try {\n return await runSerializedResumeControllerConversationOperation(input);\n } finally {\n release();\n if (storeTails.get(input.ledgerRootPath) === tail) {\n storeTails.delete(input.ledgerRootPath);\n }\n }\n}\n\nasync function runSerializedResumeControllerConversationOperation(input: {\n execute: () => Promise<RuntimeTransportResumeControllerConversationResult>;\n ledgerRootPath: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n}): Promise<RuntimeTransportResumeControllerConversationResult> {\n const stored = readRecords(input.ledgerRootPath);\n if (!stored.ok) {\n return rejected(input.request, stored.reasonCode);\n }\n const records = stored.records;\n const requestFingerprint = stableJson(input.request);\n const existing = records.find(\n (record) => record.operationId === input.request.operationId\n );\n if (existing) {\n if (existing.requestFingerprint !== requestFingerprint) {\n return rejected(\n input.request,\n \"execution_recovery.operation_identity_conflict\"\n );\n }\n if (existing.result) {\n return existing.result;\n }\n return outcomeUnknown(\n input.request,\n \"The exact controller command started, but no authoritative result was recorded.\"\n );\n }\n\n const started: StoredResumeControllerConversationOperation = {\n operationId: input.request.operationId,\n request: input.request,\n requestFingerprint,\n result: null,\n schema: RECORD_SCHEMA,\n status: \"in_progress\",\n updatedAtMs: Date.now(),\n };\n writeRecords(input.ledgerRootPath, [...records, started]);\n\n let result: RuntimeTransportResumeControllerConversationResult;\n try {\n result = await input.execute();\n } catch (error) {\n result = outcomeUnknown(\n input.request,\n error instanceof Error ? error.message : String(error)\n );\n }\n const completed: StoredResumeControllerConversationOperation = {\n ...started,\n result,\n status:\n result.status === \"completed\" || result.status === \"rejected\"\n ? \"completed\"\n : \"outcome_unknown\",\n updatedAtMs: Date.now(),\n };\n writeRecords(input.ledgerRootPath, [...records, completed]);\n return result;\n}\n\nfunction outcomeUnknown(\n request: RuntimeTransportResumeControllerConversationFramePayload,\n message: string\n): RuntimeTransportResumeControllerConversationResult {\n return {\n destination: request.destination,\n identity: request.identity,\n message,\n operationId: request.operationId,\n reasonCode: \"execution_recovery.controller_outcome_unknown\",\n status: \"outcome_unknown\",\n };\n}\n\nfunction rejected(\n request: RuntimeTransportResumeControllerConversationFramePayload,\n reasonCode: string\n): RuntimeTransportResumeControllerConversationResult {\n return {\n destination: request.destination,\n identity: request.identity,\n message: reasonCode,\n operationId: request.operationId,\n reasonCode,\n status: \"rejected\",\n };\n}\n\nfunction readRecords(ledgerRootPath: string): ReadRecordsResult {\n const path = resolveStorePath(ledgerRootPath);\n let source: string;\n try {\n source = readFileSync(path, \"utf8\");\n } catch (error) {\n if (hasErrorCode(error, \"ENOENT\")) {\n return { ok: true, records: [] };\n }\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_unavailable\",\n };\n }\n let parsed: Partial<OperationStoreFile>;\n try {\n parsed = JSON.parse(source) as Partial<OperationStoreFile>;\n } catch {\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_invalid\",\n };\n }\n if (parsed.schema !== STORE_SCHEMA || parsed.v !== 1) {\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_update_required\",\n };\n }\n if (\n !(Array.isArray(parsed.records) && parsed.records.every(isStoredOperation))\n ) {\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_invalid\",\n };\n }\n return { ok: true, records: parsed.records };\n}\n\nfunction writeRecords(\n ledgerRootPath: string,\n records: StoredResumeControllerConversationOperation[]\n): void {\n const path = resolveStorePath(ledgerRootPath);\n const tempPath = join(ledgerRootPath, STORE_TEMP_FILE_NAME);\n mkdirSync(dirname(path), { recursive: true });\n const retained = [...records]\n .sort((left, right) => right.updatedAtMs - left.updatedAtMs)\n .slice(0, MAX_RETAINED_RECORDS);\n writeFileSync(\n tempPath,\n JSON.stringify(\n {\n records: retained,\n schema: STORE_SCHEMA,\n updatedAtMs: Date.now(),\n v: 1,\n } satisfies OperationStoreFile,\n null,\n 2\n ),\n { encoding: \"utf8\", mode: 0o600 }\n );\n renameSync(tempPath, path);\n}\n\nfunction resolveStorePath(ledgerRootPath: string): string {\n return join(ledgerRootPath, STORE_FILE_NAME);\n}\n\nfunction isStoredOperation(\n value: unknown\n): value is StoredResumeControllerConversationOperation {\n const candidate =\n value as Partial<StoredResumeControllerConversationOperation>;\n return (\n candidate.schema === RECORD_SCHEMA &&\n typeof candidate.operationId === \"string\" &&\n typeof candidate.requestFingerprint === \"string\" &&\n typeof candidate.request === \"object\" &&\n candidate.request !== null &&\n (candidate.result === null ||\n (typeof candidate.result === \"object\" && candidate.result !== null)) &&\n (candidate.status === \"completed\" ||\n candidate.status === \"in_progress\" ||\n candidate.status === \"outcome_unknown\") &&\n typeof candidate.updatedAtMs === \"number\"\n );\n}\n\nfunction hasErrorCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === code\n );\n}\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableJson).join(\",\")}]`;\n }\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n","import { forkSession as forkClaudeCodeSession } from \"@anthropic-ai/claude-agent-sdk\";\nimport {\n forkCodexAppServerThread,\n resolveInstalledCodexLaunchCandidates,\n} from \"@openmeld/adapter-codex\";\nimport {\n forkOpenCodeServerSession,\n resolveInstalledOpenCodeLaunchCandidates,\n} from \"@openmeld/adapter-opencode\";\nimport type { RuntimeTransportLocalAgentControlForkSessionFramePayload } from \"@openmeld/schemas/types\";\nimport { listProjectBindings } from \"../../agent-activity/project-bindings\";\nimport { recordOpenMeldCreatedLocalAgentSession } from \"../../agent-activity/session-inventory-origin-store\";\nimport { discoverLocalAgentSessionProviders } from \"../../agent-activity/session-inventory-provider-adapters\";\n\nconst PROVIDER_PROBE_TIMEOUT_MS = 5000;\nconst PROVIDER_FORK_TIMEOUT_MS = 30_000;\n\ntype ForkRequest =\n RuntimeTransportLocalAgentControlForkSessionFramePayload[\"request\"];\n\nexport async function forkAgentSession(input: {\n request: ForkRequest;\n rootDir?: string;\n}): Promise<{ childNativeSessionId: string }> {\n const source = await resolveSourceSession({\n request: input.request,\n rootDir: input.rootDir,\n });\n let childNativeSessionId: string;\n switch (input.request.agentControllerRef) {\n case \"builtin:codex\": {\n const launch = await resolveInstalledCodexLaunchCandidates({\n timeoutMs: PROVIDER_PROBE_TIMEOUT_MS,\n });\n if (!(launch.ok && launch.candidates[0])) {\n throw new AgentSessionForkError(\n \"agent_session_fork.local_agent_unavailable\",\n \"Codex is no longer available on this Computer.\"\n );\n }\n const result = await forkCodexAppServerThread({\n codexTimeoutMs: PROVIDER_FORK_TIMEOUT_MS,\n codexWorkdir: source.workingDirectory,\n // The user picked this Session in inventory and asked for a copy of it,\n // so copying its entire stored history is the requested operation. No\n // completed-turn cutoff is available or wanted here; the execution\n // context path is the one that must prove a boundary.\n forkFullHistory: true,\n launchContract: launch.candidates[0].launchContract,\n sourceThreadId: input.request.sourceNativeSessionId,\n title: buildForkedSessionTitle(input.request.profileName),\n });\n childNativeSessionId = result.threadId;\n break;\n }\n case \"builtin:claude-code\": {\n const result = await forkClaudeCodeSession(\n input.request.sourceNativeSessionId,\n {\n dir: source.workingDirectory,\n title: buildForkedSessionTitle(input.request.profileName),\n }\n );\n childNativeSessionId = result.sessionId;\n break;\n }\n case \"builtin:opencode\": {\n const launch = await resolveInstalledOpenCodeLaunchCandidates({\n timeoutMs: PROVIDER_PROBE_TIMEOUT_MS,\n });\n if (!(launch.ok && launch.candidates[0])) {\n throw new AgentSessionForkError(\n \"agent_session_fork.local_agent_unavailable\",\n \"OpenCode is no longer available on this Computer.\"\n );\n }\n const result = await forkOpenCodeServerSession({\n launchContract: launch.candidates[0].launchContract,\n openCodeTimeoutMs: PROVIDER_FORK_TIMEOUT_MS,\n openCodeWorkdir: source.workingDirectory,\n sourceSessionId: input.request.sourceNativeSessionId,\n title: buildForkedSessionTitle(input.request.profileName),\n });\n childNativeSessionId = result.sessionId;\n break;\n }\n default:\n throw new AgentSessionForkError(\n \"agent_session_fork.unsupported\",\n \"This local agent does not currently provide a verified native Fork operation.\"\n );\n }\n await recordOpenMeldCreatedLocalAgentSession({\n agentControllerRef: input.request.agentControllerRef,\n nativeSessionId: childNativeSessionId,\n rootDir: input.rootDir,\n });\n return { childNativeSessionId };\n}\n\nexport class AgentSessionForkError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AgentSessionForkError\";\n this.code = code;\n }\n}\n\nasync function resolveSourceSession(input: {\n request: ForkRequest;\n rootDir?: string;\n}): Promise<{ workingDirectory: string }> {\n const bindings = (\n await listProjectBindings({\n organizationId: input.request.organizationId,\n rootDir: input.rootDir,\n })\n ).filter((binding) => binding.projectId === input.request.projectId);\n if (bindings.length === 0) {\n throw new AgentSessionForkError(\n \"agent_session_fork.project_unavailable\",\n \"This Project is no longer connected on the selected Computer.\"\n );\n }\n const providers = await discoverLocalAgentSessionProviders({\n bindings,\n rootDir: input.rootDir,\n });\n const provider = providers.find(\n (item) => item.agentControllerRef === input.request.agentControllerRef\n );\n if (!provider || provider.result !== \"sessions\") {\n throw new AgentSessionForkError(\n \"agent_session_fork.inventory_unavailable\",\n \"OpenMeld could not read the selected local agent's current Sessions.\"\n );\n }\n const source = provider.sessions.find(\n (item) =>\n item.binding.projectId === input.request.projectId &&\n item.session.nativeSessionId === input.request.sourceNativeSessionId &&\n item.session.canFork\n );\n if (!source) {\n throw new AgentSessionForkError(\n \"agent_session_fork.source_unavailable\",\n \"The selected Session is no longer current or forkable.\"\n );\n }\n return { workingDirectory: source.binding.repositoryPath };\n}\n\nfunction buildForkedSessionTitle(profileName: string): string {\n return `OpenMeld · ${profileName}`;\n}\n","import type {\n LocalDaemonAdapterContainer,\n LocalExecutionSlots,\n} from \"@openmeld/local-service\";\nimport {\n runtimeTransportLocalAgentControlForkSessionFramePayloadSchema,\n runtimeTransportLocalAgentControlManageInstallationFramePayloadSchema,\n runtimeTransportLocalAgentControlSetEnabledFramePayloadSchema,\n runtimeTransportResumeControllerConversationFramePayloadSchema,\n runtimeTransportResumeControllerConversationResultFramePayloadSchema,\n} from \"@openmeld/schemas\";\nimport type {\n OpenMeldDaemonManageLocalAgentInstallationPayload,\n OpenMeldDaemonSetLocalAgentEnabledPayload,\n} from \"@openmeld/schemas/types\";\nimport {\n manageAgentRegistrationInstallation,\n setAgentRegistrationEnabled,\n} from \"../../agents/registry\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { sendDaemonFrame } from \"../carrier/daemon-frame-transport\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type {\n DaemonFrameSink,\n LedgerPaths,\n MutableRouteCatalogState,\n ParsedDaemonFrame,\n} from \"../core/types\";\nimport { resumeExactControllerConversation } from \"../execution-recovery/resume-controller-conversation\";\nimport { runResumeControllerConversationOperation } from \"../execution-recovery/resume-controller-conversation-operation-store\";\nimport type { LocalServiceRuntimeAgentControllerReportSyncResult } from \"../reporting/runtime-agent-controller-report-sync\";\nimport { forkAgentSession } from \"../session-control/fork-agent-session\";\nimport { runAgentSessionForkOperation } from \"../session-control/session-fork-operation-store\";\n\nexport function isExecutionHostControlFrame(frame: ParsedDaemonFrame): boolean {\n return (\n frame.code === \"daemon.local_agent_control.set_enabled\" ||\n frame.code === \"daemon.local_agent_control.manage_installation\" ||\n frame.code === \"daemon.local_agent_control.fork_session\" ||\n frame.code === \"daemon.execution_recovery.resume_controller_conversation\"\n );\n}\n\nexport function createExecutionHostControls(input: {\n computerFileAccessStorePath: string;\n ledgerPaths: LedgerPaths;\n localAdapterContainer: LocalDaemonAdapterContainer;\n localExecutionSlots: LocalExecutionSlots;\n presenter: Presenter;\n routeCatalogState: MutableRouteCatalogState;\n refreshReports(): Promise<LocalServiceRuntimeAgentControllerReportSyncResult>;\n invalidate(scope: \"activity\" | \"routes\"): void;\n}) {\n const log = (code: string, text: string) =>\n emitRunLine({ presenter: input.presenter, code, text });\n\n async function refreshReports(): Promise<\"failed\" | \"skipped\" | \"submitted\"> {\n try {\n const result = await input.refreshReports();\n if (result.failedCount > 0) {\n throw new Error(\n `OpenMeld could not submit ${result.failedCount} of ${result.reportCount} local agent reports.`\n );\n }\n return result.status;\n } catch (error) {\n log(\n \"daemon.run.local_agent_control_report_sync_failed\",\n `runtime agent controller report sync failed after local agent control: ${toErrorMessage(error)}`\n );\n return \"failed\";\n }\n }\n\n async function setEnabled(control: {\n agentId: string;\n enabled: boolean;\n }): Promise<OpenMeldDaemonSetLocalAgentEnabledPayload> {\n try {\n const result = await setAgentRegistrationEnabled(control);\n const reportSyncStatus = await refreshReports();\n if (result.changed) {\n input.invalidate(\"routes\");\n }\n log(\n \"daemon.run.local_agent_control_set_enabled\",\n `${result.displayName} is ${result.enabled ? \"enabled\" : \"disabled\"}.`\n );\n return {\n accepted: true,\n agentControllerRef: result.agentControllerRef,\n agentId: result.agentId,\n changed: result.changed,\n enabled: result.enabled,\n reportSyncStatus,\n status: result.status,\n };\n } catch (error) {\n const message = toErrorMessage(error);\n log(\n \"daemon.run.local_agent_control_set_enabled_rejected\",\n `local agent control rejected: ${message}`\n );\n return {\n accepted: false,\n agentId: control.agentId,\n enabled: control.enabled,\n changed: false,\n message,\n reasonCode: controlErrorCode(error),\n reportSyncStatus: \"failed\",\n status: \"rejected\",\n };\n }\n }\n\n async function manageInstallation(control: {\n agentId: string;\n installationId?: string;\n operation: \"list\" | \"select\";\n }): Promise<OpenMeldDaemonManageLocalAgentInstallationPayload> {\n try {\n let result: Awaited<\n ReturnType<typeof manageAgentRegistrationInstallation>\n >;\n if (control.operation === \"select\") {\n const guarded =\n await input.localExecutionSlots.runAdapterOperationIfIdle(\n control.agentId,\n () => manageAgentRegistrationInstallation(control)\n );\n if (!guarded.accepted) {\n throw new Error(\n guarded.status === \"operation_in_progress\"\n ? \"agents.installation_change_in_progress: this installation is already being changed; check again in a moment\"\n : \"agents.installation_change_blocked_by_work: this agent has work in progress; wait until it finishes before changing installations\"\n );\n }\n result = guarded.value;\n } else {\n result = await manageAgentRegistrationInstallation(control);\n }\n const selectionStatus =\n input.localExecutionSlots.getAdapterOperationStatus(control.agentId);\n const reportSyncStatus = result.changed\n ? await refreshReports()\n : \"skipped\";\n if (result.changed) {\n input.invalidate(\"routes\");\n }\n return {\n accepted: true,\n agentControllerRef: result.agentControllerRef,\n agentId: result.agentId,\n changed: result.changed,\n installations: result.installations,\n reportSyncStatus,\n selectionStatus,\n selectedInstallationId: result.selectedInstallationId,\n status: result.status,\n };\n } catch (error) {\n const message = toErrorMessage(error);\n log(\n \"daemon.run.local_agent_installation_rejected\",\n `local agent installation request rejected: ${message}`\n );\n return {\n accepted: false,\n agentId: control.agentId,\n changed: false,\n installations: [],\n message,\n reasonCode: controlErrorCode(error),\n reportSyncStatus: \"failed\",\n selectedInstallationId: null,\n status: \"rejected\",\n };\n }\n }\n\n async function handleFrame(\n frame: ParsedDaemonFrame,\n socket: DaemonFrameSink\n ): Promise<boolean> {\n if (frame.code === \"daemon.local_agent_control.set_enabled\") {\n const parsed =\n runtimeTransportLocalAgentControlSetEnabledFramePayloadSchema.parse(\n frame.payload\n );\n sendDaemonFrame(socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsed.requestId,\n payload: await setEnabled(parsed.payload),\n },\n });\n return true;\n }\n if (frame.code === \"daemon.local_agent_control.manage_installation\") {\n const parsed =\n runtimeTransportLocalAgentControlManageInstallationFramePayloadSchema.parse(\n frame.payload\n );\n sendDaemonFrame(socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsed.requestId,\n payload: await manageInstallation(parsed.payload),\n },\n });\n return true;\n }\n if (frame.code === \"daemon.local_agent_control.fork_session\") {\n const parsed =\n runtimeTransportLocalAgentControlForkSessionFramePayloadSchema.parse(\n frame.payload\n );\n const result = await runAgentSessionForkOperation({\n execute: () => forkAgentSession({ request: parsed.request }),\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n request: parsed.request,\n });\n sendDaemonFrame(socket, {\n code: \"daemon.local_agent_control.result\",\n payload: { requestId: parsed.requestId, payload: result },\n });\n log(\n result.status === \"completed\"\n ? \"daemon.run.agent_session_fork_completed\"\n : \"daemon.run.agent_session_fork_failed\",\n result.status === \"completed\"\n ? `forked ${result.agentControllerRef} Session ${result.sourceNativeSessionId}.`\n : `Agent Session Fork ${result.status}: ${result.reasonCode}.`\n );\n if (result.status === \"completed\") {\n input.invalidate(\"activity\");\n }\n return true;\n }\n if (\n frame.code === \"daemon.execution_recovery.resume_controller_conversation\"\n ) {\n const parsed =\n runtimeTransportResumeControllerConversationFramePayloadSchema.parse(\n frame.payload\n );\n const result = await runResumeControllerConversationOperation({\n execute: () =>\n resumeExactControllerConversation({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n localAdapterContainer: input.localAdapterContainer,\n request: parsed,\n routeConfig:\n input.routeCatalogState.routeByProfileId.get(\n parsed.identity.targetProfileId\n ) ?? null,\n }),\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n request: parsed,\n });\n sendDaemonFrame(socket, {\n code: \"daemon.execution_recovery.resume_controller_conversation_result\",\n payload:\n runtimeTransportResumeControllerConversationResultFramePayloadSchema.parse(\n { requestId: parsed.requestId, result }\n ),\n });\n return true;\n }\n return false;\n }\n\n return { handleFrame, setEnabled };\n}\n\nfunction controlErrorCode(error: unknown): string {\n const code =\n error instanceof Error ? error.message.split(\":\", 1)[0]?.trim() : null;\n return code?.includes(\".\") ? code : \"agents.unexpected_error\";\n}\n","import { randomUUID } from \"node:crypto\";\nimport { performance } from \"node:perf_hooks\";\nimport {\n RUNTIME_TRANSPORT_SCHEMA_VERSION,\n runtimeTransportDispatchLifecycleAcknowledgementSchema,\n runtimeTransportDispatchLifecycleRequestSchema,\n} from \"@openmeld/schemas\";\nimport type { RuntimeTransportDeliverDispatchRequest } from \"@openmeld/schemas/types\";\nimport type { CurrentDaemonSocketRef } from \"../core/types\";\nimport { ExecutionHostError } from \"./channel\";\n\ntype AdmissionRequest = Pick<\n RuntimeTransportDeliverDispatchRequest,\n \"dispatchId\" | \"attemptId\" | \"daemonSessionId\" | \"leaseEpoch\"\n> & {\n payload: Pick<\n RuntimeTransportDeliverDispatchRequest[\"payload\"],\n \"executionToken\" | \"runtimeCoordinatorExecutionId\"\n >;\n};\n\n// Response waiters only: the Coordinator remains the execution authority.\n// Missing observations never authorize starting a provider.\nexport function createExecutionAdmissionConfirmation(\n socketRef: CurrentDaemonSocketRef\n) {\n const pending = new Map<\n string,\n {\n request: AdmissionRequest;\n sentAt: number;\n resolve(): void;\n reject(error: Error): void;\n }\n >();\n const resend = () => {\n if (!socketRef.socket || socketRef.connectionGeneration === null) {\n return;\n }\n for (const [previousId, waiter] of [...pending]) {\n const acknowledgementId = randomUUID();\n pending.delete(previousId);\n pending.set(acknowledgementId, waiter);\n waiter.sentAt = performance.now();\n const request = waiter.request;\n const token = request.payload.executionToken;\n const payload = runtimeTransportDispatchLifecycleRequestSchema.parse({\n v: RUNTIME_TRANSPORT_SCHEMA_VERSION,\n acknowledgementId,\n dispatchId: request.dispatchId,\n attemptId: request.attemptId,\n daemonSessionId: request.daemonSessionId,\n connectionGeneration: socketRef.connectionGeneration,\n leaseEpoch: request.leaseEpoch,\n runtimeCoordinatorExecutionId:\n request.payload.runtimeCoordinatorExecutionId,\n executionTokenEcho: token\n ? {\n executionToken: token.executionToken,\n runId: token.runId,\n tokenFingerprint: token.tokenFingerprint,\n runtimeCoordinatorExecutionId:\n token.executionScope.runtimeCoordinatorExecutionId,\n }\n : undefined,\n phase: \"accepted_local\",\n lifecycleAtMs: Date.now(),\n });\n try {\n socketRef.socket.send(\n JSON.stringify({\n v: RUNTIME_TRANSPORT_SCHEMA_VERSION,\n code: \"daemon.dispatch.lifecycle\",\n payload,\n })\n );\n } catch {\n // Delivery is unconfirmed. Reconnection retries this read/confirmation,\n // never the provider execution, and a send failure cannot grant access.\n }\n }\n };\n return {\n confirm(request: AdmissionRequest): Promise<void> {\n return new Promise((resolve, reject) => {\n const id = randomUUID();\n pending.set(id, {\n request,\n resolve,\n reject,\n sentAt: performance.now(),\n });\n try {\n resend();\n } catch (error) {\n for (const [pendingId, waiter] of pending) {\n if (waiter.resolve === resolve) {\n pending.delete(pendingId);\n }\n }\n reject(error);\n }\n });\n },\n resend,\n receive(payload: unknown) {\n const parsed =\n runtimeTransportDispatchLifecycleAcknowledgementSchema.safeParse(\n payload\n );\n if (!parsed.success) {\n return;\n }\n const reply = parsed.data;\n const waiter = pending.get(reply.acknowledgementId);\n if (\n !waiter ||\n reply.connectionGeneration !== socketRef.connectionGeneration ||\n waiter.request.dispatchId !== reply.dispatchId ||\n waiter.request.attemptId !== reply.attemptId\n ) {\n return;\n }\n if (\n reply.accepted &&\n performance.now() - waiter.sentAt >= reply.validForMs\n ) {\n // A delayed positive reply is not fresh permission. Keep the same\n // execution waiting; heartbeat/reconnect retries only the confirmation.\n return;\n }\n pending.delete(reply.acknowledgementId);\n if (reply.accepted) {\n waiter.resolve();\n } else {\n waiter.reject(\n new ExecutionHostError(\n reply.reasonCode ?? \"host.execution_not_authorized\",\n \"RuntimeCoordinator did not authorize this execution; the provider was not started.\"\n )\n );\n }\n },\n };\n}\n","import {\n createInflightTaskControlRegistry,\n createLocalAdapterContainer,\n createLocalAdapterEntries,\n createLocalTaskInterruptSender,\n createPendingAgentInteractionRegistry,\n} from \"@openmeld/local-service\";\nimport {\n RUNTIME_TRANSPORT_SCHEMA_VERSION,\n SERVICE_EXECUTION_HOST_PROTOCOL,\n type ServiceExecutionHostCatalog,\n type ServiceExecutionHostIdentity,\n type ServiceExecutionHostMessage,\n type ServiceExecutionHostSnapshot,\n serviceExecutionHostCatalogSchema,\n} from \"@openmeld/schemas\";\nimport { createManagedAgentActivityIntegrationRefreshScheduler } from \"../../agent-activity/integration-refresh\";\nimport { startLocalAgentActivitySyncLoop } from \"../../agent-activity/local-sync\";\nimport { getConfiguredDaemonDispatchLimits } from \"../../config/runtime-config\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { parseDaemonFrame } from \"../carrier/daemon-frame-transport\";\nimport { handleDaemonSocketFrame } from \"../carrier/frame-router\";\nimport {\n handleLocalControlPlaneCancel,\n handleLocalControlPlaneInterrupt,\n} from \"../carrier/local-control-handlers\";\nimport { createDaemonLocalExecutionSlots } from \"../carrier/local-execution-slots\";\nimport { resolveLocalConversationExecutionStatus } from \"../control-plane/conversation-execution-status\";\nimport { CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS } from \"../core/constants\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type {\n CurrentDaemonSocketRef,\n DaemonFrameSink,\n DaemonRuntimePaths,\n InflightDispatchMeta,\n RouteCatalog,\n} from \"../core/types\";\nimport {\n flushDispatchResultOutbox,\n listDispatchResultOutboxPendingAcknowledgementKeys,\n waitForDispatchResultOutboxAcknowledgement,\n} from \"../dispatch/dispatch-result-outbox\";\nimport { sendDispatchInteractionRequestFrame } from \"../dispatch/send-dispatch-result\";\nimport { resolveComputerFileAccessStorePath } from \"../file-access/computer-file-access-store\";\nimport { consumeArmedAgentControllerInterfaceReprobe } from \"../inventory/agent-controller-interface-keeper\";\nimport { syncLocalServiceProviderConversationProofs } from \"../reporting/provider-conversation-proof-sync\";\nimport { syncLocalServiceRuntimeAgentControllerReports } from \"../reporting/runtime-agent-controller-report-sync\";\nimport { createRuntimeReportingAttemptObserver } from \"../reporting/runtime-reporting-attempt-observer\";\nimport { syncActiveTaskPermissionModes } from \"../routing/active-permission-mode-sync\";\nimport {\n createMutableRouteCatalogState,\n createRouteCatalogFromMutableState,\n} from \"../routing/route-catalog-state\";\nimport { loadContextStore } from \"../state/context-store\";\nimport { buildLedgerPaths } from \"../state/daemon-device-id\";\nimport {\n loadExecutionHostCatalog,\n persistExecutionHostCatalog,\n} from \"./catalog\";\nimport { ExecutionHostError, type ExecutionHostHandlers } from \"./channel\";\nimport {\n createExecutionHostControls,\n isExecutionHostControlFrame,\n} from \"./controls\";\nimport { createExecutionAdmissionConfirmation } from \"./execution-admission\";\n\ntype HostEvent = Exclude<ServiceExecutionHostMessage, { type: \"reply\" }>;\n\nexport async function createExecutionHostResources(input: {\n runtimePaths: DaemonRuntimePaths;\n presenter: Presenter;\n}) {\n const ledgerPaths = buildLedgerPaths(input.runtimePaths.ledgerRootPath);\n const contextStore = await loadContextStore(\n input.runtimePaths.contextStorePath\n );\n const inflightDispatchMetaByTaskId = new Map<string, InflightDispatchMeta>();\n const inflightTaskControlRegistry = createInflightTaskControlRegistry();\n const pendingAgentInteractionRegistry =\n createPendingAgentInteractionRegistry();\n const interrupt = createLocalTaskInterruptSender({\n registry: inflightTaskControlRegistry,\n });\n const localAdapterContainer = createLocalAdapterContainer(\n createLocalAdapterEntries({\n runtimeWorkdir: process.cwd(),\n sendInterrupt: async (signal) => {\n await interrupt(signal);\n },\n registerRuntimeProcess: (event) => {\n const processId =\n event.phase === \"process_exit\" ? null : event.processId;\n const updated = inflightTaskControlRegistry.updateTaskProcess({\n processId,\n signalTarget:\n event.phase === \"process_exit\" ? null : event.signalTarget,\n taskId: event.taskId,\n });\n if (updated) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_process_registered\",\n text: `control process ${event.phase === \"process_spawned\" ? \"registered\" : \"cleared\"} for task ${event.taskId}`,\n payload: {\n adapterId: updated.adapterId,\n dispatchId: updated.dispatchId,\n phase: event.phase,\n processId,\n taskId: event.taskId,\n signalTarget: event.signalTarget,\n },\n });\n }\n },\n })\n );\n const emptyCatalog: RouteCatalog = {\n profileIds: [],\n routeByProfileId: new Map(),\n skippedProfiles: [],\n };\n\n return {\n ledgerPaths,\n contextStore,\n inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry,\n pendingAgentInteractionRegistry,\n localAdapterContainer,\n initialCatalog: emptyCatalog,\n dispatchLimits: await getConfiguredDaemonDispatchLimits(),\n };\n}\nexport type ExecutionHostResources = Awaited<\n ReturnType<typeof createExecutionHostResources>\n>;\n\n// One Host owns these execution objects across all replacement cloud sockets.\n// No socket, reconnect loop, public listener or independent task scheduler lives\n// here. The original execution/approval/result domain owners remain in use.\nexport function createExecutionHostRuntime(input: {\n resources: ExecutionHostResources;\n hostInstanceId: string;\n identity: ServiceExecutionHostIdentity;\n runtimePaths: DaemonRuntimePaths;\n serviceBundleId: string | null;\n profileOwnerName: string | null;\n presenter: Presenter;\n emit(event: HostEvent): void;\n onWorkStateChange?(quiescent: boolean): void;\n}) {\n const identity = input.identity;\n const {\n ledgerPaths,\n contextStore,\n inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry,\n pendingAgentInteractionRegistry,\n localAdapterContainer,\n initialCatalog: emptyCatalog,\n } = input.resources;\n const localExecutionSlots = createDaemonLocalExecutionSlots({\n limits: input.resources.dispatchLimits,\n presenter: input.presenter,\n onChanged: () => {\n input.onWorkStateChange?.(snapshot().localQuiescent);\n invalidate(\"execution\");\n },\n });\n const routeCatalogState = createMutableRouteCatalogState(emptyCatalog);\n const currentSocketRef: CurrentDaemonSocketRef = {\n socket: null,\n connectionGeneration: null,\n };\n const executionAdmission =\n createExecutionAdmissionConfirmation(currentSocketRef);\n currentSocketRef.confirmExecutionAdmission = executionAdmission.confirm;\n const leasesByProfileId = new Map<string, number>();\n const catalogs = new Map<number, RouteCatalog>([[0, emptyCatalog]]);\n let catalogRevision = 0;\n let activeCatalogRevision = 0;\n let generation = 0;\n let draining = false;\n let disposed = false;\n let startupReplayPending = false;\n let connectionAbort: AbortController | null = null;\n let catalogLoad: Promise<ServiceExecutionHostCatalog> | null = null;\n let controllerReport: Promise<\n Awaited<ReturnType<typeof syncLocalServiceRuntimeAgentControllerReports>>\n > | null = null;\n let reportPolicy: \"background\" | \"fresh\" | null = null;\n const activeControls = new Set<Promise<unknown>>();\n const envelope = {\n protocol: SERVICE_EXECUTION_HOST_PROTOCOL,\n hostInstanceId: input.hostInstanceId,\n } as const;\n const computerFileAccessStorePath = resolveComputerFileAccessStorePath(\n input.runtimePaths.dataRootPath\n );\n const emit = (event: HostEvent): void => {\n if (!disposed) {\n input.emit(event);\n }\n };\n const invalidate = (scope: \"routes\" | \"activity\" | \"execution\") =>\n emit({ ...envelope, type: \"invalidate\", scope });\n const owner = {\n lane: identity.lane,\n ownerUserId: identity.ownerUserId,\n localAdapterContainer,\n presenter: input.presenter,\n serviceBundleId: input.serviceBundleId,\n };\n const reportingAttempt = () => {\n const connectionGeneration = currentSocketRef.connectionGeneration;\n return createRuntimeReportingAttemptObserver({\n serviceIdentity: {\n deviceId: identity.deviceId,\n contractGeneration: identity.serviceContractGeneration,\n },\n onAuthenticationFailure: (failure) =>\n emit({\n ...envelope,\n type: \"authentication_failure\",\n connectionGeneration,\n failure,\n }),\n });\n };\n\n function snapshot(): ServiceExecutionHostSnapshot {\n const state = localExecutionSlots.getDrainState();\n return {\n pid: process.pid,\n admission: draining ? \"draining\" : \"open\",\n activeCount: state.activeGlobal,\n pendingCount: state.pendingCount,\n localQuiescent:\n localExecutionSlots.isQuiescent() && activeControls.size === 0,\n unacknowledgedResultCount:\n listDispatchResultOutboxPendingAcknowledgementKeys({ ledgerPaths })\n .length,\n startupReplayPending,\n adapterIds: localAdapterContainer\n .listAdapters()\n .map((entry) => entry.adapterId),\n };\n }\n\n function assertConnection(expected: number): DaemonFrameSink {\n if (expected !== generation || !currentSocketRef.socket || disposed) {\n throw new ExecutionHostError(\n \"host.connection_replaced\",\n \"The operation belongs to a retired connector generation.\"\n );\n }\n return currentSocketRef.socket;\n }\n\n function replayInteractions(): void {\n const sink = currentSocketRef.socket;\n if (!sink) {\n return;\n }\n for (const pending of pendingAgentInteractionRegistry.list()) {\n const leaseEpoch = leasesByProfileId.get(\n pending.authority.targetProfileId\n );\n if (pending.response || !leaseEpoch) {\n continue;\n }\n sendDispatchInteractionRequestFrame({\n attemptId: pending.authority.attemptId,\n connectionGeneration: generation,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: pending.authority.dispatchId,\n executionIdentityEcho: pending.authority.executionIdentityEcho,\n executionTokenEcho: pending.authority.executionTokenEcho,\n interaction: pending.request,\n leaseEpoch,\n runtimeCoordinatorExecutionId:\n pending.authority.runtimeCoordinatorExecutionId,\n socket: sink,\n taskId: pending.taskId,\n });\n }\n }\n\n function startResultReplay(): void {\n const recordKeys = listDispatchResultOutboxPendingAcknowledgementKeys({\n ledgerPaths,\n });\n const expectedGeneration = generation;\n startupReplayPending = recordKeys.length > 0;\n if (startupReplayPending) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.startup_result_replay_started\",\n text: \"Replaying retained results before accepting new work.\",\n });\n }\n const replay = waitForDispatchResultOutboxAcknowledgement({\n abortSignal: connectionAbort?.signal,\n ledgerPaths,\n recordKeys,\n });\n flushDispatchResultOutbox({\n currentSocketRef,\n ledgerPaths,\n presenter: input.presenter,\n });\n replay\n .then((status) => {\n if (\n status === \"acknowledged\" &&\n generation === expectedGeneration &&\n currentSocketRef.socket &&\n !draining\n ) {\n startupReplayPending = false;\n if (recordKeys.length > 0) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.startup_result_replay_completed\",\n text: \"Retained results were acknowledged; new work may be admitted.\",\n });\n }\n invalidate(\"execution\");\n }\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.startup_result_replay_failed\",\n text: toErrorMessage(error),\n });\n });\n }\n\n async function reportControllers(policy: \"background\" | \"fresh\") {\n if (controllerReport) {\n const previous = controllerReport;\n if (policy !== \"fresh\" || reportPolicy === \"fresh\") {\n return await previous;\n }\n await previous;\n }\n const attempt = syncLocalServiceRuntimeAgentControllerReports({\n localAdapterContainer,\n onAttempt: reportingAttempt(),\n probePolicy: policy,\n });\n controllerReport = attempt;\n reportPolicy = policy;\n try {\n return await attempt;\n } finally {\n if (controllerReport === attempt) {\n controllerReport = null;\n reportPolicy = null;\n }\n }\n }\n\n const controls = createExecutionHostControls({\n computerFileAccessStorePath,\n ledgerPaths,\n localAdapterContainer,\n localExecutionSlots,\n presenter: input.presenter,\n routeCatalogState,\n refreshReports: () => reportControllers(\"fresh\"),\n invalidate,\n });\n const activity = startLocalAgentActivitySyncLoop({\n onError: (error) =>\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_activity_sync_failed\",\n text: toErrorMessage(error),\n }),\n onResult: (result) => {\n if (result.status === \"idle\") {\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code:\n result.status === \"submitted\"\n ? \"daemon.run.agent_activity_sync\"\n : \"daemon.run.agent_activity_sync_unavailable\",\n text:\n result.status === \"submitted\"\n ? `Local Agent reporting submitted ${result.submittedCount} activity event(s), ${result.controllerTaskEventSubmittedCount} task callback event(s), and ${result.sessionInventory.submittedSourceCount} Session Inventory source(s).`\n : `Agent Activity sync deferred: ${result.reason ?? \"unavailable\"}.`,\n payload: {\n ...result.health,\n controllerTaskEventSubmittedCount:\n result.controllerTaskEventSubmittedCount,\n controllerTaskHealth: result.controllerTaskHealth,\n observedCount: result.observedCount,\n reason: result.reason,\n sessionInventory: result.sessionInventory,\n status: result.status,\n submittedCount: result.submittedCount,\n },\n });\n },\n });\n const integrations = createManagedAgentActivityIntegrationRefreshScheduler({\n onError: (error) =>\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_activity_integration_refresh_failed\",\n text: toErrorMessage(error),\n }),\n onResult: (result) => {\n if (result.status === \"ready\") {\n activity.requestSync({ refreshContext: true });\n }\n },\n });\n // Inventory is independent of opening the inherited control endpoint.\n integrations.request();\n\n function beginDrain(): ServiceExecutionHostSnapshot {\n draining = true;\n localExecutionSlots.beginDrain();\n return snapshot();\n }\n\n async function drain(): Promise<ServiceExecutionHostSnapshot> {\n beginDrain();\n await localExecutionSlots.drain();\n await Promise.allSettled([...activeControls]);\n const drained = snapshot();\n input.onWorkStateChange?.(drained.localQuiescent);\n return drained;\n }\n\n function trackControl<T>(run: () => Promise<T>): Promise<T> {\n if (draining || disposed) {\n return Promise.reject(\n new ExecutionHostError(\n \"host.draining\",\n \"The execution host is draining; new operations are not admitted.\"\n )\n );\n }\n input.onWorkStateChange?.(false);\n const operation = Promise.resolve().then(run);\n activeControls.add(operation);\n return operation.finally(() => {\n activeControls.delete(operation);\n input.onWorkStateChange?.(snapshot().localQuiescent);\n invalidate(\"execution\");\n });\n }\n\n const handlers: Omit<ExecutionHostHandlers, \"initialize\"> = {\n health: snapshot,\n loadCatalog: async ({ initial }) => {\n if (!catalogLoad) {\n catalogLoad = loadExecutionHostCatalog(owner, initial)\n .then((catalog) => {\n const revision = ++catalogRevision;\n catalogs.set(revision, catalog);\n // Retain the active snapshot plus the latest two loads. Never resolve\n // a retired revision by substituting another set of routes.\n for (const key of catalogs.keys()) {\n if (key !== activeCatalogRevision && key < revision - 1) {\n catalogs.delete(key);\n }\n }\n return serviceExecutionHostCatalogSchema.parse({\n revision,\n expectedRoutesContractVersion:\n catalog.expectedRoutesContractVersion,\n profileIds: catalog.profileIds,\n routes: [...catalog.routeByProfileId.values()],\n skippedProfiles: catalog.skippedProfiles,\n workingFolderExpectedProfileIds:\n catalog.workingFolderExpectedProfileIds,\n workingFolderObservations: catalog.workingFolderObservations,\n });\n })\n .finally(() => {\n catalogLoad = null;\n });\n }\n return await catalogLoad;\n },\n configureConnection: async (request) => {\n if (request.executionAdmissionConfirmation !== true) {\n throw new ExecutionHostError(\n \"host.execution_admission_unsupported\",\n \"The connected server must support execution admission confirmation before this Host can run tasks.\"\n );\n }\n if (request.connectionGeneration < generation || disposed) {\n throw new ExecutionHostError(\n \"host.connection_replaced\",\n \"An older connector cannot replace the active connection.\"\n );\n }\n const catalog = catalogs.get(request.catalogRevision);\n if (!catalog || request.catalogRevision < activeCatalogRevision) {\n throw new ExecutionHostError(\n \"host.catalog_replaced\",\n \"The requested Host catalog is no longer available.\"\n );\n }\n connectionAbort?.abort();\n connectionAbort = new AbortController();\n generation = request.connectionGeneration;\n activeCatalogRevision = request.catalogRevision;\n Object.assign(routeCatalogState, createMutableRouteCatalogState(catalog));\n leasesByProfileId.clear();\n for (const lease of request.leases) {\n leasesByProfileId.set(lease.profileId, lease.leaseEpoch);\n }\n const sink: DaemonFrameSink = {\n send: (raw) => {\n if (\n generation !== request.connectionGeneration ||\n currentSocketRef.socket !== sink\n ) {\n throw new ExecutionHostError(\n \"host.connection_replaced\",\n \"This execution frame's connector has been retired.\"\n );\n }\n const frame = parseDaemonFrame(raw);\n if (!frame) {\n throw new ExecutionHostError(\n \"host.invalid_frame\",\n \"Execution produced an invalid transport frame.\"\n );\n }\n emit({\n ...envelope,\n type: \"frame\",\n connectionGeneration: generation,\n frame: { v: RUNTIME_TRANSPORT_SCHEMA_VERSION, ...frame },\n });\n },\n };\n currentSocketRef.socket = sink;\n currentSocketRef.connectionGeneration = generation;\n executionAdmission.resend();\n const outcomes = await syncActiveTaskPermissionModes({\n catalogState: routeCatalogState,\n inflightTaskControlRegistry,\n localAdapterContainer,\n });\n for (const outcome of outcomes) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.active_permission_mode_sync\",\n text: `active permission update ${outcome.status} for ${outcome.taskId}`,\n payload: outcome,\n });\n }\n assertConnection(request.connectionGeneration);\n replayInteractions();\n startResultReplay();\n return snapshot();\n },\n detachConnection: ({ connectionGeneration }) => {\n if (connectionGeneration === generation) {\n connectionAbort?.abort();\n currentSocketRef.socket = null;\n currentSocketRef.connectionGeneration = null;\n localExecutionSlots.dropPendingTasks({\n reason: \"daemon.session.unexpected_close\",\n });\n }\n return snapshot();\n },\n heartbeat: ({ connectionGeneration, staleProfileIds }) => {\n assertConnection(connectionGeneration);\n executionAdmission.resend();\n for (const profileId of staleProfileIds) {\n leasesByProfileId.delete(profileId);\n }\n flushDispatchResultOutbox({\n currentSocketRef,\n ledgerPaths,\n presenter: input.presenter,\n });\n replayInteractions();\n return snapshot();\n },\n handleFrame: async ({ connectionGeneration, frame }) => {\n const socket = assertConnection(connectionGeneration);\n if (frame.code === \"daemon.dispatch.lifecycle_acknowledged\") {\n executionAdmission.receive(frame.payload);\n return {};\n }\n if (isExecutionHostControlFrame(frame)) {\n await trackControl(() => controls.handleFrame(frame, socket));\n return {};\n }\n if (frame.code === \"daemon.dispatch.deliver\") {\n if (draining || startupReplayPending) {\n throw new ExecutionHostError(\n \"host.admission_closed\",\n \"Execution admission is closed; the existing Coordinator retains delivery ownership.\"\n );\n }\n input.onWorkStateChange?.(false);\n }\n handleDaemonSocketFrame({\n computerFileAccessStorePath,\n contextStore,\n currentSocketRef,\n daemonSessionId: identity.daemonSessionId,\n parsedFrame: frame,\n inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry,\n ledgerPaths,\n leasesByProfileId,\n localAdapterContainer,\n localExecutionSlots,\n pendingAgentInteractionRegistry,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: identity.ownerUserId,\n requestCurrentWorkingFolderFactRefresh: () => invalidate(\"routes\"),\n presenter: input.presenter,\n routeByProfileId: routeCatalogState.routeByProfileId,\n socket,\n waiters: {\n registerResolver: null,\n registerRejecter: null,\n heartbeatResolver: null,\n heartbeatRejecter: null,\n },\n });\n input.onWorkStateChange?.(snapshot().localQuiescent);\n invalidate(\"execution\");\n return {};\n },\n cancel: (payload) =>\n handleLocalControlPlaneCancel({\n localAdapterContainer,\n payload,\n presenter: input.presenter,\n registry: inflightTaskControlRegistry,\n }),\n interrupt: (payload) =>\n handleLocalControlPlaneInterrupt({\n localAdapterContainer,\n payload,\n presenter: input.presenter,\n registry: inflightTaskControlRegistry,\n }),\n conversationStatus: resolveLocalConversationExecutionStatus,\n setEnabled: (payload) => trackControl(() => controls.setEnabled(payload)),\n reportControllers: async ({ probePolicy }) => {\n const result = await reportControllers(probePolicy);\n return {\n ...result,\n reasonCodes: [...result.reasonCodes],\n hasArmedReprobe: consumeArmedAgentControllerInterfaceReprobe(),\n };\n },\n reportConversations: async () => {\n const result = await syncLocalServiceProviderConversationProofs({\n onAttempt: reportingAttempt(),\n routeCatalog: createRouteCatalogFromMutableState(routeCatalogState),\n });\n return { ...result, reasonCodes: [...result.reasonCodes] };\n },\n persistCatalog: async ({ revision }) => {\n const catalog = catalogs.get(revision);\n if (!catalog || revision !== activeCatalogRevision) {\n throw new ExecutionHostError(\n \"host.catalog_replaced\",\n \"Only the currently accepted catalog can be persisted.\"\n );\n }\n await persistExecutionHostCatalog(owner, catalog);\n return {};\n },\n syncActivity: ({ refreshIntegrations }) => {\n activity.requestSync({ reconcile: true, refreshContext: true });\n if (refreshIntegrations) {\n // Startup may have skipped installation because no Project was bound.\n // Reuse the Host's coalescing scheduler; never block connector control.\n integrations.request();\n }\n return {};\n },\n beginDrain,\n drain,\n settleResults: async () => {\n if (!snapshot().localQuiescent) {\n throw new ExecutionHostError(\n \"host.work_active\",\n \"Local work must drain before result settlement.\"\n );\n }\n if (!(currentSocketRef.socket && connectionAbort)) {\n return { status: \"connection_closed\" };\n }\n const abort = new AbortController();\n const onClose = () => abort.abort();\n const connectionSignal = connectionAbort.signal;\n connectionSignal.addEventListener(\"abort\", onClose, { once: true });\n const timer = setTimeout(\n () => abort.abort(),\n CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS\n );\n try {\n const recordKeys = listDispatchResultOutboxPendingAcknowledgementKeys({\n ledgerPaths,\n });\n const wait = waitForDispatchResultOutboxAcknowledgement({\n abortSignal: abort.signal,\n ledgerPaths,\n recordKeys,\n });\n flushDispatchResultOutbox({\n currentSocketRef,\n ledgerPaths,\n presenter: input.presenter,\n });\n const result = await wait;\n if (result === \"acknowledged\") {\n return { status: \"acknowledged\" };\n }\n return {\n status: connectionSignal.aborted ? \"connection_closed\" : \"timeout\",\n };\n } finally {\n clearTimeout(timer);\n connectionSignal.removeEventListener(\"abort\", onClose);\n }\n },\n stop: async () => {\n const result = await drain();\n await integrations.stop();\n await activity.stop();\n connectionAbort?.abort();\n currentSocketRef.socket = null;\n currentSocketRef.connectionGeneration = null;\n disposed = true;\n return result;\n },\n };\n\n return {\n handlers,\n snapshot,\n async closeAfterConnectorLoss() {\n if (!disposed) {\n handlers.detachConnection({ connectionGeneration: generation });\n await handlers.stop({});\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAM,sCAAsC;AAC5C,MAAM,mCAAmC;AACzC,SAAS,mCAAmC,OAAO;CAClD,IAAI,cAAc;CAClB,IAAI,MAAM,mBAAmB,WAAW,cAAc;MACjD,IAAI,MAAM,mBAAmB,cAAc,cAAc;CAC9D,OAAO;EACN,MAAM;EACN,OAAO;EACP;EACA,WAAW,CAAC;GACX,YAAY;GACZ,QAAQ;GACR,UAAU;GACV,YAAY;GACZ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GACxB,MAAM,SAAS,KAAK;GACpB,iBAAiB,MAAM;GACvB,iBAAiB,SAAS;GAC1B,iBAAiB,uBAAuB;GACxC,WAAW;GACX,OAAO;EACT;CACF;CAEA,OAAO;EACL;EACA;EACA,MAAM,0BAA0B;GAC9B,IAAI,CAAC,UAAU;IACb,SAAS,iBAAiB,EAAE,sBAAsB,WAAW,CAAC;IAC9D,MAAM,SAAS,KAAK,CAAC,CAAC;GACxB;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"runtime-DMYoB5_x.js","names":["toErrorMessage","normalizeOptionalText","normalizeOptionalText","failure","toErrorMessage","resolveBootstrapPlan","markBootstrapInjectedContext","reconcileBootstrapInjectedContextAfterDispatch","rollbackBootstrapExecutionStateAfterDispatchFailure","resolveStructuredActionRequirementFailure","buildStructuredActionRepairPrompt","normalizeOptionalText","resolveStructuredActionRepairContinuation","coerceRuntimeResultToStructuredActionFailure","STORE_SCHEMA","RECORD_SCHEMA","STORE_FILE_NAME","STORE_TEMP_FILE_NAME","MAX_RETAINED_RECORDS","storeTails","rejected","stableJson","outcomeUnknown","readRecords","writeRecords","readErrorCode","isStoredOperation","markBootstrapInjectedContextInternal","reconcileBootstrapInjectedContextAfterDispatchInternal","resolveBootstrapPlanInternal","rollbackBootstrapExecutionStateAfterDispatchFailureInternal","buildStructuredActionRepairPromptInternal","coerceRuntimeResultToStructuredActionFailureInternal","resolveStructuredActionRepairContinuationInternal","resolveStructuredActionRequirementFailureInternal","toErrorMessage","normalizeOptionalText","toTaskExecutionErrorInternal","mergeOpenClawGatewayVisibilityInternal","delay","toErrorMessage","normalizeOptionalText","summarizeSubmissions","toErrorMessage","normalizeOptionalText","toErrorMessage","rejected","forkClaudeCodeSession","toErrorMessage","toErrorMessage"],"sources":["../../../packages/schemas/dist/working-folder-recovery.js","../src/agent-activity/integration-refresh.ts","../src/local-service/execution/dispatch-runtime-preparation.ts","../src/local-service/execution/task-execution-error.ts","../src/provider-hosts/openclaw/agent-controller-conversation.ts","../src/provider-hosts/openclaw/continuation.ts","../src/local-service/continuation/provider-runtime-continuation.ts","../src/local-service/file-access/computer-file-access-admission.ts","../src/local-service/continuation/working-folder-recovery.ts","../src/local-service/file-access/computer-file-access-prompt.ts","../src/local-service/file-access/dispatch-work-handoff.ts","../src/local-service/dispatch/dispatch-agent-reply-observation.ts","../src/local-service/dispatch/dispatch-agent-reply-settlement.ts","../src/local-service/dispatch/dispatch-image-attachments.ts","../src/local-service/dispatch/ensure-dispatch-controller-openmeld-skill.ts","../src/local-service/dispatch/execute-dispatch-conversation.ts","../src/local-service/dispatch/execute-dispatch-bootstrap-plan.ts","../src/local-service/dispatch/execute-dispatch-conversation-state.ts","../src/local-service/dispatch/execute-dispatch-observation.ts","../src/local-service/dispatch/execute-dispatch-structured-action-repair.ts","../src/local-service/session-control/session-fork-operation-store.ts","../src/local-service/dispatch/execution-context-workspace.ts","../src/local-service/dispatch/execution-context-session.ts","../src/local-service/dispatch/prompt-trace.ts","../src/local-service/dispatch/reasoning-stream.ts","../src/local-service/dispatch/send-target-reference.ts","../src/local-service/dispatch/execute-dispatch-task.ts","../src/local-service/carrier/local-control-handlers.ts","../src/local-service/carrier/frame-router.ts","../src/local-service/carrier/local-execution-slots.ts","../src/local-service/control-plane/conversation-execution-status.ts","../src/local-service/reporting/provider-conversation-proof-sync.ts","../src/local-service/reporting/runtime-agent-controller-report-sync.ts","../src/local-service/reporting/runtime-reporting-attempt-observer.ts","../src/local-service/routing/active-permission-mode-sync.ts","../src/local-service/state/context-store.ts","../src/local-service/execution-host/catalog.ts","../src/local-service/execution-recovery/resume-controller-conversation.ts","../src/local-service/execution-recovery/resume-controller-conversation-operation-store.ts","../src/local-service/session-control/fork-agent-session.ts","../src/local-service/execution-host/controls.ts","../src/local-service/execution-host/execution-admission.ts","../src/local-service/execution-host/runtime.ts"],"sourcesContent":[" \n//#region src/working-folder-recovery.ts\nconst WORKING_FOLDER_RECOVERY_QUESTION_ID = \"working_folder_recovery\";\nconst WORKING_FOLDER_RECOVERY_DECLINED = \"context.workspace_recovery_declined\";\nfunction buildWorkingFolderRecoveryQuestion(input) {\n\tlet description = \"This conversation started in a different folder. The task has not started.\";\n\tif (input.previousFolder === \"missing\") description = \"The previous conversation’s folder is no longer available. The task has not started.\";\n\telse if (input.previousFolder === \"restricted\") description = \"The previous conversation’s folder is outside this Computer’s allowed folders. The task has not started.\";\n\treturn {\n\t\tkind: \"question\",\n\t\ttitle: \"Choose where to continue\",\n\t\tdescription,\n\t\tquestions: [{\n\t\t\tquestionId: WORKING_FOLDER_RECOVERY_QUESTION_ID,\n\t\t\tprompt: \"Which conversation should this task use?\",\n\t\t\tmultiple: false,\n\t\t\tallowOther: false,\n\t\t\toptions: [\n\t\t\t\t...input.previousFolder === \"available\" ? [{\n\t\t\t\t\toptionId: \"use_previous_folder\",\n\t\t\t\t\tlabel: \"Continue the previous conversation\",\n\t\t\t\t\tdescription: `Use ${input.previousFolderLabel} for this task. Keep its conversation history. The Agent’s default folder stays unchanged.`\n\t\t\t\t}] : [],\n\t\t\t\t{\n\t\t\t\t\toptionId: \"start_new_conversation\",\n\t\t\t\t\tlabel: \"Start a new conversation\",\n\t\t\t\t\tdescription: `Use ${input.selectedFolderLabel} with the same Agent. The previous conversation stays saved, but its history will not carry over.`\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\toptionId: \"leave_task\",\n\t\t\t\t\tlabel: \"Stop this task\",\n\t\t\t\t\tdescription: \"Keep the previous conversation and folder settings.\"\n\t\t\t\t}\n\t\t\t]\n\t\t}]\n\t};\n}\nfunction isWorkingFolderRecoveryQuestion(request) {\n\treturn request?.kind === \"question\" && request.questions?.length === 1 && request.questions[0]?.questionId === \"working_folder_recovery\";\n}\nfunction isWorkingFolderRecoveryDecline(response) {\n\treturn response.kind === \"question\" && response.answers.length === 1 && response.answers[0]?.questionId === \"working_folder_recovery\" && response.answers[0].values.length === 1 && response.answers[0].values[0] === \"leave_task\";\n}\n/** Only explicit local admission declines qualify; timeouts and lost waiters do not. */\nfunction resolveLocalExecutionOwnerCancellationReason(payload) {\n\tif (payload.status !== \"failed\") return null;\n\treturn payload.errorCode === \"context.workspace_recovery_declined\" || payload.errorCode === \"computer.file_access.owner_declined\" ? payload.errorCode : null;\n}\n//#endregion\nexport { WORKING_FOLDER_RECOVERY_DECLINED, WORKING_FOLDER_RECOVERY_QUESTION_ID, buildWorkingFolderRecoveryQuestion, isWorkingFolderRecoveryDecline, isWorkingFolderRecoveryQuestion, resolveLocalExecutionOwnerCancellationReason };\n\n//# sourceMappingURL=working-folder-recovery.js.map","import { homedir } from \"node:os\";\nimport { resolveOpenMeldRootDir } from \"../config/paths\";\nimport {\n defaultManagedIntegrationPaths,\n installAgentActivityIntegrations,\n} from \"./managed-integrations\";\nimport { listProjectBindings } from \"./project-bindings\";\nimport { registerAgentActivityRoute } from \"./route-registry\";\n\nexport type ManagedAgentActivityIntegrationRefreshResult =\n | {\n integrations: Awaited<\n ReturnType<typeof installAgentActivityIntegrations>\n >;\n status: \"ready\";\n }\n | {\n reason: \"no_project_bindings\";\n status: \"skipped\";\n };\n\nexport type ManagedAgentActivityIntegrationRefreshScheduler = {\n request: () => void;\n stop: () => Promise<void>;\n};\n\nexport async function refreshManagedAgentActivityIntegrations(input?: {\n homeDir?: string;\n install?: typeof installAgentActivityIntegrations;\n register?: typeof registerAgentActivityRoute;\n rootDir?: string;\n}): Promise<ManagedAgentActivityIntegrationRefreshResult> {\n const rootDir = input?.rootDir ?? resolveOpenMeldRootDir();\n const bindings = await listProjectBindings({ rootDir });\n if (bindings.length === 0) {\n return { reason: \"no_project_bindings\", status: \"skipped\" };\n }\n await (input?.register ?? registerAgentActivityRoute)({ rootDir });\n return {\n integrations: await (input?.install ?? installAgentActivityIntegrations)({\n paths: defaultManagedIntegrationPaths(input?.homeDir ?? homedir()),\n }),\n status: \"ready\",\n };\n}\n\nexport function createManagedAgentActivityIntegrationRefreshScheduler(input: {\n onError?: (error: unknown) => void;\n onResult?: (result: ManagedAgentActivityIntegrationRefreshResult) => void;\n refresh?: () => Promise<ManagedAgentActivityIntegrationRefreshResult>;\n}): ManagedAgentActivityIntegrationRefreshScheduler {\n let inFlight: Promise<void> | null = null;\n let pending = false;\n let scheduled = false;\n let stopped = false;\n const refresh = input.refresh ?? refreshManagedAgentActivityIntegrations;\n\n const schedule = () => {\n if (stopped || scheduled) {\n return;\n }\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n run();\n });\n };\n const run = () => {\n if (stopped || inFlight || !pending) {\n return;\n }\n pending = false;\n inFlight = refresh()\n .then((result) => input.onResult?.(result))\n .catch((error) => input.onError?.(error))\n .finally(() => {\n inFlight = null;\n if (pending) {\n schedule();\n }\n });\n };\n\n return {\n request: () => {\n if (stopped) {\n return;\n }\n pending = true;\n schedule();\n },\n stop: async () => {\n stopped = true;\n pending = false;\n await inFlight;\n },\n };\n}\n","import type { OpenClawGatewayVisibility } from \"@openmeld/local-service\";\nimport { providerDispatchRuntimeContextSchema } from \"@openmeld/schemas\";\nimport type {\n OpenMeldDaemonDispatchControllerSnapshot,\n ProviderDispatchRuntimeContext,\n RuntimeTransportDeliveryExecutionIdentity,\n} from \"@openmeld/schemas/types\";\nimport {\n resolveCurrentEffectiveProfileWorkingFolderRuntime,\n resolveEffectiveProfileWorkingFolderRuntime,\n} from \"../../profile-workspace/effective-runtime-resolution\";\nimport {\n type ProviderRuntimePreparationDetails,\n prepareProviderRuntime,\n} from \"../../provider-hosts/prepare-provider-runtime\";\nimport type { DaemonProfileRouteConfig } from \"../core/types\";\nimport { DaemonServiceRunError } from \"../core/types\";\n\n// A healthy session re-observes the route at most every 45 seconds. Keep the\n// compatibility launch fence aligned with the current route-lease freshness\n// window so a transient catalog read failure can preserve a genuinely current\n// route without allowing historical folder state to launch new work.\nexport const CURRENT_ROUTE_WORKING_FOLDER_FRESHNESS_MS = 200_000;\n\nexport type DispatchRuntimePreparation = {\n effectiveRuntimeContext: ProviderDispatchRuntimeContext;\n runtimePreparationDetails: ProviderRuntimePreparationDetails;\n runtimeEnvOverrides: Record<string, string | undefined> | undefined;\n runtimeOpenClawGatewayVisibility: OpenClawGatewayVisibility | null;\n};\n\nexport async function resolveDispatchRuntimeContext(input: {\n defaultProjectId?: string | null;\n openMeldProfileId: string;\n}): Promise<ProviderDispatchRuntimeContext> {\n const resolution = await resolveEffectiveProfileWorkingFolderRuntime({\n defaultProjectId: input.defaultProjectId,\n openMeldProfileId: input.openMeldProfileId,\n mode: \"dispatch\",\n });\n if (resolution.status === \"ready\") {\n return resolution.runtimeContext;\n }\n if (resolution.status === \"missing\") {\n if (\n \"workingFolderSource\" in resolution &&\n resolution.workingFolderSource === \"default_project\" &&\n resolution.defaultProjectId\n ) {\n const folderMissing =\n resolution.defaultProjectFailureReason === \"folder_missing\";\n throw new DaemonServiceRunError({\n code: folderMissing\n ? \"project.local_connection.folder_missing\"\n : \"project.local_connection.missing\",\n message: folderMissing\n ? \"project.local_connection.folder_missing\"\n : \"project.local_connection.missing\",\n projectFailureContext: {\n ...(resolution.defaultProjectBindingGeneration\n ? {\n bindingGeneration: resolution.defaultProjectBindingGeneration,\n }\n : {}),\n projectId: resolution.defaultProjectId,\n },\n });\n }\n throw new DaemonServiceRunError({\n code: \"profile.workspace.missing\",\n message: `profile.workspace.missing: ${resolution.reasonText}`,\n });\n }\n if (\n \"workingFolderSource\" in resolution &&\n resolution.workingFolderSource === \"default_project\" &&\n resolution.defaultProjectId\n ) {\n throw new DaemonServiceRunError({\n code: \"project.local_connection.invalid\",\n message: \"project.local_connection.invalid\",\n projectFailureContext: {\n ...(resolution.defaultProjectBindingGeneration\n ? {\n bindingGeneration: resolution.defaultProjectBindingGeneration,\n }\n : {}),\n projectId: resolution.defaultProjectId,\n },\n });\n }\n throw new DaemonServiceRunError({\n code: \"profile.workspace.invalid\",\n message: `profile.workspace.invalid: ${resolution.reasonText}`,\n });\n}\n\nexport async function resolveDispatchWorkingFolderRuntimeContext(input: {\n controllerSnapshot: OpenMeldDaemonDispatchControllerSnapshot;\n defaultProjectId: string | null;\n defaultProjectIdWasProvided: boolean;\n executionIdentity: RuntimeTransportDeliveryExecutionIdentity;\n nowMs?: number;\n onCurrentWorkingFolderFactRejected?: () => void;\n routeConfig: DaemonProfileRouteConfig | null;\n targetProfileId: string;\n}): Promise<ProviderDispatchRuntimeContext> {\n const route = input.routeConfig;\n const workingFolderRuntime = route?.workingFolderRuntime;\n if (!(route && workingFolderRuntime)) {\n rejectCurrentWorkingFolderFact(\n input,\n \"missing\",\n \"the current route has no working-folder observation\"\n );\n }\n if (\n input.defaultProjectIdWasProvided &&\n input.defaultProjectId !==\n workingFolderRuntime.workingFolderFact.defaultProjectId\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"identity_mismatch\",\n \"the delivered Default Project does not match the current route observation\"\n );\n }\n const identity = input.executionIdentity.core;\n const controllerSnapshot = input.controllerSnapshot;\n if (\n route.profileId !== input.targetProfileId ||\n identity.targetProfileId !== input.targetProfileId ||\n route.bindingId !== identity.bindingId ||\n controllerSnapshot.bindingId !== identity.bindingId ||\n typeof route.configurationRevision !== \"number\" ||\n typeof controllerSnapshot.configurationRevision !== \"number\" ||\n route.configurationRevision !== controllerSnapshot.configurationRevision ||\n route.agentControllerRef !== identity.agentControllerRef ||\n controllerSnapshot.agentControllerRef !== identity.agentControllerRef ||\n route.openMeldServiceRuntimeId !== identity.openMeldServiceRuntimeId.value\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"identity_mismatch\",\n \"the current route does not match the accepted dispatch identity\"\n );\n }\n const observedAtMs = workingFolderRuntime.workingFolderFact.observedAtMs;\n const nowMs = input.nowMs ?? Date.now();\n if (\n observedAtMs > nowMs ||\n nowMs - observedAtMs >= CURRENT_ROUTE_WORKING_FOLDER_FRESHNESS_MS\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"stale\",\n \"the current route working-folder observation has expired\"\n );\n }\n const currentWorkingFolder =\n await resolveCurrentEffectiveProfileWorkingFolderRuntime({\n defaultProjectId: workingFolderRuntime.workingFolderFact.defaultProjectId,\n mode: \"dispatch\",\n openMeldProfileId: input.targetProfileId,\n });\n const currentFact = currentWorkingFolder.workingFolderFact;\n if (\n currentWorkingFolder.status !== \"ready\" ||\n currentFact.source !== workingFolderRuntime.workingFolderFact.source ||\n currentFact.defaultProjectId !==\n workingFolderRuntime.workingFolderFact.defaultProjectId ||\n currentFact.localProjectBindingGeneration !==\n workingFolderRuntime.workingFolderFact.localProjectBindingGeneration ||\n currentWorkingFolder.runtimeContext.providerRuntimeWorkingDirectory !==\n workingFolderRuntime.runtimeContext.providerRuntimeWorkingDirectory\n ) {\n rejectCurrentWorkingFolderFact(\n input,\n \"changed\",\n \"the effective working folder changed after this route was observed\"\n );\n }\n return workingFolderRuntime.runtimeContext;\n}\n\nfunction rejectCurrentWorkingFolderFact(\n input: { onCurrentWorkingFolderFactRejected?: () => void },\n reason: \"changed\" | \"identity_mismatch\" | \"missing\" | \"stale\",\n detail: string\n): never {\n input.onCurrentWorkingFolderFactRejected?.();\n throwCurrentWorkingFolderFactError(reason, detail);\n}\n\nfunction throwCurrentWorkingFolderFactError(\n reason: \"changed\" | \"identity_mismatch\" | \"missing\" | \"stale\",\n detail: string\n): never {\n throw new DaemonServiceRunError({\n code: `profile.working_folder.current_fact_${reason}`,\n message: `profile.working_folder.current_fact_${reason}: ${detail}`,\n });\n}\n\nexport async function resolveDispatchRuntimeEnvOverrides(input: {\n daemonWorkingDirectory: string;\n parsedTask: {\n agentControllerRef: string;\n targetProfileId: string;\n };\n profileName: string | null;\n providerRuntimeWorkingDirectory?: string;\n}): Promise<Record<string, string | undefined> | undefined> {\n return (\n await prepareProviderRuntime({\n agentControllerRef: input.parsedTask.agentControllerRef,\n daemonWorkingDirectory: input.daemonWorkingDirectory,\n mode: \"dispatch\",\n profileName: input.profileName,\n runtimeContext: parseDispatchRuntimeContextOrThrow({\n providerRuntimeWorkingDirectory:\n input.providerRuntimeWorkingDirectory ?? input.daemonWorkingDirectory,\n source: `dispatch runtime env overrides for ${input.parsedTask.targetProfileId}`,\n }),\n targetProfileId: input.parsedTask.targetProfileId,\n })\n ).envOverrides;\n}\n\nexport async function prepareDispatchRuntimeExecution(input: {\n agentControllerRef: string;\n daemonWorkingDirectory: string;\n dispatchRuntimeContext: ProviderDispatchRuntimeContext;\n profileName: string | null;\n targetProfileId: string;\n}): Promise<DispatchRuntimePreparation> {\n const runtimePreparation = await prepareProviderRuntime({\n agentControllerRef: input.agentControllerRef,\n daemonWorkingDirectory: input.daemonWorkingDirectory,\n mode: \"dispatch\",\n profileName: input.profileName,\n runtimeContext: input.dispatchRuntimeContext,\n targetProfileId: input.targetProfileId,\n });\n const openClawPreparation =\n runtimePreparation.preparationDetails.kind === \"openclaw\"\n ? runtimePreparation.preparationDetails\n : null;\n\n return {\n effectiveRuntimeContext: runtimePreparation.runtimeContext,\n runtimePreparationDetails: runtimePreparation.preparationDetails,\n runtimeEnvOverrides: runtimePreparation.envOverrides,\n runtimeOpenClawGatewayVisibility:\n openClawPreparation?.openClawGatewayVisibility ?? null,\n };\n}\n\nfunction parseDispatchRuntimeContextOrThrow(input: {\n providerRuntimeWorkingDirectory: string;\n source: string;\n}): ProviderDispatchRuntimeContext {\n const parsed = providerDispatchRuntimeContextSchema.safeParse({\n providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,\n });\n if (parsed.success) {\n return parsed.data;\n }\n throw new DaemonServiceRunError({\n code: \"controller.runtime_context.invalid\",\n message: `controller.runtime_context.invalid: invalid provider runtime working directory from ${input.source}`,\n });\n}\n","import type { OpenMeldDaemonTaskResultPayload } from \"@openmeld/schemas/types\";\nimport { toErrorMessage } from \"../core/logger\";\nimport {\n DaemonServiceRunError,\n type OpenMeldDaemonTaskErrorType,\n} from \"../core/types\";\n\nconst EXECUTION_CONTEXT_ERROR_PATTERN = /^execution_context\\.[a-z_]+$/u;\n\nexport function toTaskExecutionError(error: unknown): {\n errorCode: string;\n errorType: OpenMeldDaemonTaskErrorType;\n message: string;\n openClawGatewayVisibility?: OpenMeldDaemonTaskResultPayload[\"openClawGatewayVisibility\"];\n projectFailureContext?: OpenMeldDaemonTaskResultPayload[\"projectFailureContext\"];\n} {\n if (error instanceof DaemonServiceRunError) {\n return {\n errorCode: error.code,\n errorType: \"config\",\n message: error.message,\n openClawGatewayVisibility: error.openClawGatewayVisibility,\n projectFailureContext: error.projectFailureContext,\n };\n }\n if (\n error instanceof Error &&\n EXECUTION_CONTEXT_ERROR_PATTERN.test(error.message)\n ) {\n return {\n errorCode: error.message,\n errorType: \"config\",\n message: error.message,\n };\n }\n return {\n errorCode: \"dispatch.execution_failed\",\n errorType: \"internal\",\n message: toErrorMessage(error),\n };\n}\n","import {\n normalizeOpenClawSpaceIdPrefix,\n slugifyOpenClawNamePart,\n} from \"./naming\";\n\nconst OPENCLAW_SPACE_SESSION_KEY_RE =\n /^agent:(?<agentId>[a-z0-9-]+):openmeld-space:(?<spaceSlug>[a-z0-9-]+)--(?<spaceIdPrefix>[a-z0-9]{8})$/u;\n\nexport type OpenClawAgentControllerConversationClassification =\n | \"missing\"\n | \"canonical_owned\"\n | \"legacy\"\n | \"foreign\";\n\nexport type ParsedOpenClawSpaceSessionKey = {\n agentId: string;\n spaceIdPrefix: string;\n spaceSlug: string;\n};\n\nexport function parseOpenClawSpaceSessionKey(\n value: string\n): ParsedOpenClawSpaceSessionKey | null {\n const match = OPENCLAW_SPACE_SESSION_KEY_RE.exec(String(value ?? \"\").trim());\n if (!match?.groups) {\n return null;\n }\n const agentId = normalizeOptionalText(match.groups.agentId);\n const spaceIdPrefix = normalizeOptionalText(match.groups.spaceIdPrefix);\n const spaceSlug = normalizeOptionalText(match.groups.spaceSlug);\n if (!(agentId && spaceIdPrefix && spaceSlug)) {\n return null;\n }\n return {\n agentId,\n spaceIdPrefix,\n spaceSlug,\n };\n}\n\nexport function matchesOwnedOpenClawSpaceSessionKey(input: {\n openClawBootstrapAgentId: string | null;\n sessionKey: string;\n spaceId: string;\n}): boolean {\n const parsed = parseOpenClawSpaceSessionKey(input.sessionKey);\n if (!parsed) {\n return false;\n }\n const normalizedAgentId = normalizeOptionalText(\n input.openClawBootstrapAgentId\n );\n if (!normalizedAgentId) {\n return false;\n }\n return (\n parsed.agentId === slugifyOpenClawNamePart(normalizedAgentId, \"agent\") &&\n parsed.spaceIdPrefix === normalizeOpenClawSpaceIdPrefix(input.spaceId)\n );\n}\n\nexport function classifyOpenClawAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n openClawBootstrapAgentId: string | null;\n spaceId: string;\n}): OpenClawAgentControllerConversationClassification {\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n if (!agentControllerConversationId) {\n return \"missing\";\n }\n return matchesOwnedOpenClawSpaceSessionKey({\n openClawBootstrapAgentId: input.openClawBootstrapAgentId,\n sessionKey: agentControllerConversationId,\n spaceId: input.spaceId,\n })\n ? \"canonical_owned\"\n : \"legacy\";\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { buildAgentControllerConversationRef } from \"@openmeld/schemas\";\nimport type {\n ProviderRuntimeContinuationResult,\n ProviderSpecificRuntimeContinuationRequest,\n} from \"../../local-service/continuation/types\";\nimport {\n classifyOpenClawAgentControllerConversation,\n type OpenClawAgentControllerConversationClassification,\n} from \"./agent-controller-conversation\";\nimport { buildOpenClawSpaceSessionKey } from \"./naming\";\n\nexport function resolveOpenClawProviderRuntimeContinuation(\n input: ProviderSpecificRuntimeContinuationRequest\n): ProviderRuntimeContinuationResult {\n const conversationClassification =\n classifyOpenClawAgentControllerConversation({\n agentControllerConversationId: input.agentControllerConversationId,\n openClawBootstrapAgentId: resolveOpenClawBootstrapAgentId(\n input.runtimePreparationDetails\n ),\n spaceId: input.spaceId,\n });\n\n return {\n localRuntimeContextPlan: input.standardLocalRuntimeContextPlan,\n taskResultProviderFacts: {\n openClawBinding: {\n classification: conversationClassification,\n },\n },\n agentControllerConversationResumePlan:\n input.standardAgentControllerConversationResumePlan,\n agentControllerConversationOverride:\n resolveOpenClawAgentControllerConversationOverride({\n conversationClassification,\n agentControllerConversationId: input.agentControllerConversationId,\n openClawBootstrapAgentId: resolveOpenClawBootstrapAgentId(\n input.runtimePreparationDetails\n ),\n spaceId: input.spaceId,\n spaceNameSnapshot: input.spaceNameSnapshot,\n }),\n };\n}\n\nfunction resolveOpenClawBootstrapAgentId(\n preparationDetails: ProviderSpecificRuntimeContinuationRequest[\"runtimePreparationDetails\"]\n): string | null {\n return preparationDetails.kind === \"openclaw\"\n ? preparationDetails.bootstrap.agentId\n : null;\n}\n\nfunction resolveOpenClawAgentControllerConversationOverride(input: {\n agentControllerConversationId: string | null;\n conversationClassification: OpenClawAgentControllerConversationClassification;\n openClawBootstrapAgentId: string | null;\n spaceId: string;\n spaceNameSnapshot: string | null;\n}): ProviderRuntimeContinuationResult[\"agentControllerConversationOverride\"] {\n if (\n input.conversationClassification === \"canonical_owned\" &&\n normalizeOptionalText(input.agentControllerConversationId)\n ) {\n return buildAgentControllerConversationRef({\n agentControllerRef: \"builtin:openclaw\",\n agentControllerConversationKind: \"session\",\n agentControllerConversationId: normalizeOptionalText(\n input.agentControllerConversationId\n ) as string,\n });\n }\n\n const openClawBootstrapAgentId = normalizeOptionalText(\n input.openClawBootstrapAgentId\n );\n if (!openClawBootstrapAgentId) {\n return null;\n }\n\n return buildAgentControllerConversationRef({\n agentControllerRef: \"builtin:openclaw\",\n agentControllerConversationKind: \"session\",\n agentControllerConversationId: buildOpenClawSpaceSessionKey({\n agentId: openClawBootstrapAgentId,\n spaceId: input.spaceId,\n spaceNameSnapshot: input.spaceNameSnapshot,\n }),\n });\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { buildRuntimeWorkspaceFingerprint } from \"@openmeld/local-execution\";\nimport type {\n AgentControllerConversationResumePlan,\n ConversationExecutionState,\n ConversationPolicy,\n LocalRuntimeContextPlan,\n ProviderDispatchRuntimeContext,\n RuntimeTransportMode,\n} from \"@openmeld/schemas/types\";\nimport {\n listBuiltinAgentsRegistryEntries,\n resolveRegistryRuntimeAdapterContractByAgentControllerRef,\n} from \"../../agents/registry-source\";\nimport { resolveOpenClawProviderRuntimeContinuation } from \"../../provider-hosts/openclaw/continuation\";\nimport type { ProviderRuntimePreparationDetails } from \"../../provider-hosts/prepare-provider-runtime\";\nimport type {\n ProviderRuntimeContinuationResult,\n ProviderSpecificRuntimeContinuationPolicy,\n} from \"./types\";\n\ntype ConversationCompatibilityRequest = {\n agentControllerConversationId: string | null;\n agentControllerRef: string;\n currentPolicy: ConversationPolicy;\n existingContextId: string | null;\n executionState: ConversationExecutionState | null;\n latestKnownRuntimeWorkspaceFingerprint?: string | null;\n runtimeContext: ProviderDispatchRuntimeContext;\n transportMode: RuntimeTransportMode;\n};\n\ntype ProviderRuntimeContinuationRequest = ConversationCompatibilityRequest & {\n runtimePreparationDetails: ProviderRuntimePreparationDetails;\n spaceId: string;\n spaceNameSnapshot: string | null;\n};\n\ntype ProviderSpecificRuntimeContinuationRegistry = Record<\n string,\n ProviderSpecificRuntimeContinuationPolicy\n>;\n\nconst DEFAULT_PROVIDER_SPECIFIC_CONTINUATION_POLICIES: ProviderSpecificRuntimeContinuationRegistry =\n {\n openclaw: resolveOpenClawProviderRuntimeContinuation,\n };\n\nexport function listRegisteredProviderSpecificContinuationAdapterIds(): string[] {\n return Object.keys(DEFAULT_PROVIDER_SPECIFIC_CONTINUATION_POLICIES).sort();\n}\n\nexport function resolveProviderRuntimeDispatchContinuation(\n input: ProviderRuntimeContinuationRequest,\n options: {\n policies?: ProviderSpecificRuntimeContinuationRegistry;\n resolveAdapterContract?: typeof resolveRegistryRuntimeAdapterContractByAgentControllerRef;\n } = {}\n): ProviderRuntimeContinuationResult {\n const standardAgentControllerConversationResumePlan =\n resolveAgentControllerConversationResumePlan(input);\n const standardLocalRuntimeContextPlan = resolveLocalRuntimeContextPlan(input);\n const runtimeAdapterContract = (\n options.resolveAdapterContract ??\n resolveRegistryRuntimeAdapterContractByAgentControllerRef\n )(input.agentControllerRef);\n\n if (\n !runtimeAdapterContract ||\n runtimeAdapterContract.capabilityDeclaration.continuationCapability ===\n \"standard\"\n ) {\n return {\n localRuntimeContextPlan: standardLocalRuntimeContextPlan,\n taskResultProviderFacts: {},\n agentControllerConversationResumePlan:\n standardAgentControllerConversationResumePlan,\n agentControllerConversationOverride: null,\n };\n }\n\n const policies: ProviderSpecificRuntimeContinuationRegistry =\n options.policies ?? DEFAULT_PROVIDER_SPECIFIC_CONTINUATION_POLICIES;\n const policy = policies[runtimeAdapterContract.adapterId];\n if (!policy) {\n throw new Error(\n `No runtime continuation implementation is registered for adapter '${runtimeAdapterContract.adapterId}'`\n );\n }\n\n return policy({\n ...input,\n standardLocalRuntimeContextPlan,\n standardAgentControllerConversationResumePlan,\n });\n}\n\nexport function resolveAgentControllerConversationResumePlan(\n input: Pick<\n ConversationCompatibilityRequest,\n \"agentControllerConversationId\" | \"existingContextId\"\n >\n): AgentControllerConversationResumePlan {\n const agentControllerConversationId =\n normalizeOptionalText(input.agentControllerConversationId) ??\n normalizeOptionalText(input.existingContextId);\n if (!agentControllerConversationId) {\n return {\n status: \"not_bound\",\n };\n }\n\n return {\n status: \"continue_existing\",\n };\n}\n\nexport function resolveLocalRuntimeContextPlan(\n input: ConversationCompatibilityRequest\n): LocalRuntimeContextPlan {\n if (input.executionState) {\n return {\n reason: null,\n status: \"reuse\",\n };\n }\n\n if (normalizeOptionalText(input.existingContextId)) {\n return {\n reason: \"execution_state_missing\",\n status: \"recreate\",\n };\n }\n\n if (hasWorkspaceChangedSinceLatestKnownRuntime(input)) {\n return {\n reason: \"workspace_changed\",\n status: \"recreate\",\n };\n }\n\n return {\n reason: \"first_local_runtime_context\",\n status: \"recreate\",\n };\n}\n\nfunction hasWorkspaceChangedSinceLatestKnownRuntime(\n input: ConversationCompatibilityRequest\n): boolean {\n const currentRuntimeWorkingDirectory = normalizeOptionalText(\n input.runtimeContext.providerRuntimeWorkingDirectory\n );\n if (!currentRuntimeWorkingDirectory) {\n return false;\n }\n\n const currentRuntimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n currentRuntimeWorkingDirectory\n );\n const latestKnownRuntimeWorkspaceFingerprint = normalizeOptionalText(\n input.latestKnownRuntimeWorkspaceFingerprint\n );\n if (!latestKnownRuntimeWorkspaceFingerprint) {\n return false;\n }\n return (\n currentRuntimeWorkspaceFingerprint !==\n latestKnownRuntimeWorkspaceFingerprint\n );\n}\n\nexport function listRegistryProviderSpecificContinuationAdapterIds(): string[] {\n return listBuiltinAgentsRegistryEntries()\n .filter((agent) => agent.runtime.supported)\n .flatMap((agent) =>\n agent.runtime.adapters\n .filter(\n (adapter) =>\n adapter.capabilityDeclaration.continuationCapability ===\n \"provider_specific\"\n )\n .map((adapter) => adapter.adapterId)\n )\n .sort();\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { realpath } from \"node:fs/promises\";\nimport type {\n AdapterComputerFileAccessBoundary,\n AdapterComputerFileAccessVerificationResult,\n AdapterInteractionCallback,\n AdapterTransportMode,\n AgentControllerPermissionMode,\n} from \"@openmeld/adapter-core\";\nimport { COMPUTER_FILE_ACCESS_OWNER_CANCELLED_REASON_CODE } from \"@openmeld/schemas\";\nimport type { ComputerFileAccessPolicy } from \"@openmeld/schemas/types\";\nimport { isSameOrDescendantPath } from \"../../lib/path-containment\";\nimport { DaemonServiceRunError } from \"../core/types\";\n\nconst RUN_ONCE_OPTION_ID = \"run_once_without_computer_file_access_boundary\";\nconst CANCEL_OPTION_ID = \"cancel_computer_file_access_run\";\n\nexport async function resolveComputerFileAccessAdmission(input: {\n agentControllerPermissionMode?: AgentControllerPermissionMode;\n agentControllerRef: string;\n onInteractionRequest: AdapterInteractionCallback;\n policy: ComputerFileAccessPolicy;\n providerRuntimeWorkingDirectory: string;\n transportMode: AdapterTransportMode;\n verifyBoundary?: (\n boundary: AdapterComputerFileAccessBoundary\n ) => Promise<AdapterComputerFileAccessVerificationResult>;\n}): Promise<{\n boundary: AdapterComputerFileAccessBoundary | null;\n bypassedForThisRun: boolean;\n}> {\n if (input.policy.mode === \"local_agent_settings\") {\n return { boundary: null, bypassedForThisRun: false };\n }\n\n await assertComputerFileAccessWorkingDirectoryAllowed({\n boundary: input.policy,\n providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,\n });\n\n const verification = await input.verifyBoundary?.(input.policy);\n if (verification?.supported) {\n return { boundary: input.policy, bypassedForThisRun: false };\n }\n\n const launchRejected =\n verification?.reasonCode === \"computer.file_access.launch_rejected\";\n const response = await input.onInteractionRequest({\n description: launchRejected\n ? \"The local agent could not start with the requested file access settings. Cancel and check the selected agent’s version and configuration. Running once without this boundary removes the Computer file access restriction for this Wake.\"\n : \"OpenMeld can’t verify that this local agent can enforce this computer’s file access boundary. Run this Wake once without the boundary, or cancel it.\",\n kind: \"permission\",\n options: [\n {\n intent: \"allow_once\",\n label: \"Run once without this boundary\",\n optionId: RUN_ONCE_OPTION_ID,\n },\n {\n intent: \"deny\",\n label: \"Cancel run\",\n optionId: CANCEL_OPTION_ID,\n },\n ],\n subject: {\n resource: \"Computer file access boundary\",\n type: \"additional_permissions\",\n },\n title: \"File access needs your decision\",\n });\n\n if (\n response.kind === \"permission\" &&\n response.optionId === RUN_ONCE_OPTION_ID\n ) {\n return { boundary: null, bypassedForThisRun: true };\n }\n\n if (\n response.kind !== \"permission\" ||\n response.optionId !== CANCEL_OPTION_ID\n ) {\n const code =\n response.kind === \"cancel\"\n ? \"computer.file_access.interaction_cancelled\"\n : \"computer.file_access.response_invalid\";\n throw new DaemonServiceRunError({\n code,\n message: `${code}: the file access decision did not authorize this run`,\n });\n }\n throw new DaemonServiceRunError({\n code: COMPUTER_FILE_ACCESS_OWNER_CANCELLED_REASON_CODE,\n message: `${COMPUTER_FILE_ACCESS_OWNER_CANCELLED_REASON_CODE}: the Computer owner declined running this Wake without the configured file access boundary`,\n });\n}\n\nexport async function assertComputerFileAccessWorkingDirectoryAllowed(input: {\n boundary: AdapterComputerFileAccessBoundary;\n providerRuntimeWorkingDirectory: string;\n}): Promise<void> {\n const workingDirectory = await realpath(\n input.providerRuntimeWorkingDirectory\n );\n const matchesConfiguredFolder = input.boundary.folders.some((folder) =>\n isSameOrDescendantPath(workingDirectory, folder)\n );\n const allowed =\n input.boundary.mode === \"only_selected_folders\"\n ? matchesConfiguredFolder\n : !matchesConfiguredFolder;\n if (allowed) {\n return;\n }\n\n throw new DaemonServiceRunError({\n code: \"computer.file_access.working_directory_denied\",\n message:\n \"computer.file_access.working_directory_denied: this Wake’s working folder is outside the Computer file access boundary\",\n });\n}\n","import { realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename } from \"node:path\";\nimport type { AdapterInteractionCallback } from \"@openmeld/adapter-core\";\nimport {\n buildWorkingFolderRecoveryQuestion,\n WORKING_FOLDER_RECOVERY_DECLINED,\n WORKING_FOLDER_RECOVERY_QUESTION_ID,\n} from \"@openmeld/schemas\";\nimport type {\n ComputerFileAccessPolicy,\n ConversationExecutionState,\n} from \"@openmeld/schemas/types\";\nimport {\n readOpenCodeSessionRows,\n resolveOpenCodeDatabasePath,\n} from \"../../agent-activity/opencode-storage\";\nimport { DaemonServiceRunError } from \"../core/types\";\nimport { assertComputerFileAccessWorkingDirectoryAllowed } from \"../file-access/computer-file-access-admission\";\n\ntype FolderChoice = { workingDirectory: string; startNewConversation: boolean };\n\n/** Admission asks the owner before any prompt, attachment, or bootstrap uses a folder. */\nexport async function resolveWorkingFolderRecovery(input: {\n agentControllerRef: string;\n nativeSessionId: string | null;\n workingDirectory: string;\n policy: ComputerFileAccessPolicy;\n onInteractionRequest: AdapterInteractionCallback;\n inspectSession?: (\n nativeSessionId: string\n ) => Promise<{ directory: string; sessionId: string }>;\n hasExecutionContext?: boolean;\n}): Promise<FolderChoice> {\n const unchanged = {\n workingDirectory: input.workingDirectory,\n startNewConversation: false,\n };\n if (\n input.hasExecutionContext ||\n input.agentControllerRef !== \"builtin:opencode\" ||\n !input.nativeSessionId\n ) {\n return unchanged;\n }\n const nativeSessionId = input.nativeSessionId;\n const inspect = () =>\n (input.inspectSession ?? inspectRetainedOpenCodeSession)(nativeSessionId);\n const session = await inspect();\n const selectedFolder = await realpath(input.workingDirectory);\n const previousFolder = await realpath(session.directory).catch(() => null);\n if (selectedFolder === previousFolder) {\n return unchanged;\n }\n let previousFolderAllowed = previousFolder !== null;\n if (previousFolder && input.policy.mode !== \"local_agent_settings\") {\n try {\n await assertComputerFileAccessWorkingDirectoryAllowed({\n boundary: input.policy,\n providerRuntimeWorkingDirectory: previousFolder,\n });\n } catch {\n previousFolderAllowed = false;\n }\n }\n const previousFolderStatus = previousFolder ? \"restricted\" : \"missing\";\n const response = await input.onInteractionRequest(\n buildWorkingFolderRecoveryQuestion({\n previousFolder: previousFolderAllowed\n ? \"available\"\n : previousFolderStatus,\n previousFolderLabel: basename(session.directory),\n selectedFolderLabel: basename(selectedFolder),\n })\n );\n const choice =\n response.kind === \"question\" &&\n response.answers.length === 1 &&\n response.answers[0]?.questionId === WORKING_FOLDER_RECOVERY_QUESTION_ID &&\n response.answers[0].values.length === 1\n ? response.answers[0].values[0]\n : null;\n if (choice === \"leave_task\") {\n throw failure(\n WORKING_FOLDER_RECOVERY_DECLINED,\n \"The Computer owner stopped this task before the Agent started. The previous conversation is saved.\"\n );\n }\n if (\n choice !== \"start_new_conversation\" &&\n !(choice === \"use_previous_folder\" && previousFolderAllowed)\n ) {\n throw failure(\n \"context.workspace_recovery_unanswered\",\n \"This task did not start because no folder choice was confirmed. Send it again when you’re ready.\"\n );\n }\n // The owner may be away for hours. Re-read the exact native association and\n // both filesystem identities; an old answer must not authorize a moved path.\n const latest = await inspect();\n if (\n latest.sessionId !== session.sessionId ||\n latest.directory !== session.directory ||\n (await realpath(input.workingDirectory).catch(() => null)) !==\n selectedFolder ||\n (previousFolder &&\n (await realpath(session.directory).catch(() => null)) !== previousFolder)\n ) {\n throw failure(\n \"context.workspace_recovery_changed\",\n \"The conversation or folder changed while waiting. Send this task again to review the current choices.\"\n );\n }\n return {\n workingDirectory:\n choice === \"use_previous_folder\" && previousFolder\n ? previousFolder\n : selectedFolder,\n startNewConversation: choice === \"start_new_conversation\",\n };\n}\n\nexport function resolveRecoveredLedgerConversation(input: {\n startNewConversation: boolean;\n bindingConversationId: string | null;\n existingContextId: string | null;\n currentExecutionState: ConversationExecutionState | null;\n}) {\n return input.startNewConversation\n ? {\n bindingConversationId: null,\n existingContextId: null,\n currentExecutionState: null,\n }\n : input;\n}\n\nfunction failure(\n code: string,\n message: string,\n cause?: unknown\n): DaemonServiceRunError {\n const error = new DaemonServiceRunError({ code, message });\n if (cause !== undefined) {\n error.cause = cause;\n }\n return error;\n}\n\nasync function inspectRetainedOpenCodeSession(\n nativeSessionId: string\n): Promise<{ directory: string; sessionId: string }> {\n try {\n const rows = await readOpenCodeSessionRows(\n resolveOpenCodeDatabasePath({ homeDir: homedir() }),\n nativeSessionId\n );\n const session = rows[0];\n if (\n rows.length === 1 &&\n session?.id === nativeSessionId &&\n typeof session.directory === \"string\" &&\n session.directory.trim()\n ) {\n return { directory: session.directory, sessionId: nativeSessionId };\n }\n } catch (cause) {\n // This is only a preflight read. Never repair or create the provider's store.\n throw failure(\n \"context.workspace_verification_unavailable\",\n \"OpenMeld could not read this conversation’s folder. Open the conversation in OpenCode, then try this task again.\",\n cause\n );\n }\n throw failure(\n \"context.workspace_verification_unavailable\",\n \"OpenMeld could not read this conversation’s folder. Open the conversation in OpenCode, then try this task again.\"\n );\n}\n","import { createHash } from \"node:crypto\";\nimport type { AdapterInstructionPrompt } from \"@openmeld/adapter-core\";\nimport type { ComputerFileAccessPolicy } from \"@openmeld/schemas/types\";\n\nexport const COMPUTER_FILE_ACCESS_AWARENESS =\n \"Stay within the file access available to this OpenMeld run. Treat denied paths as intentional and continue with the safest useful alternative. Only the Computer owner can change this boundary.\";\n\nexport function applyComputerFileAccessAwareness(input: {\n policy: ComputerFileAccessPolicy;\n promptPlan: AdapterInstructionPrompt & { fallbackPrompt: string };\n}): AdapterInstructionPrompt & { fallbackPrompt: string } {\n if (input.policy.mode === \"local_agent_settings\") {\n return input.promptPlan;\n }\n\n const developerInstructions = `${input.promptPlan.developerInstructions}\\n\\n${COMPUTER_FILE_ACCESS_AWARENESS}`;\n const fingerprint = createHash(\"sha256\")\n .update(developerInstructions, \"utf8\")\n .digest(\"hex\");\n const epochPrefix = input.promptPlan.instructionEpoch.split(\":\", 1)[0];\n return {\n ...input.promptPlan,\n developerInstructions,\n fallbackPrompt: `${COMPUTER_FILE_ACCESS_AWARENESS}\\n\\n${input.promptPlan.fallbackPrompt}`,\n instructionEpoch: `${epochPrefix}:${fingerprint}`,\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { lstat, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n createOrganizationSkillsApi,\n createSpaceApi,\n} from \"@openmeld/api-client\";\nimport { spaceWorkSelectionSchema } from \"@openmeld/schemas\";\nimport { getAuthSessionState } from \"../../config/auth-session\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../../config/openmeld-request-context\";\nimport { resolveOpenMeldRootDir } from \"../../config/paths\";\nimport { materializeOrganizationSkillRelease } from \"../../organization-skills/cache\";\nimport { createCliApiClientFoundation } from \"../../space/api-client-foundation\";\nimport { downloadWorkingCopyFile } from \"../../space/working-copy-download\";\nimport type { ParsedDispatchTask } from \"../core/types\";\nimport { createSpaceWorkingCopies } from \"./space-working-copy\";\n\n/** The admitted Service prepares inputs; no login state is copied into the workspace. */\nexport async function prepareDispatchWorkHandoff(input: {\n task: Pick<\n ParsedDispatchTask,\n | \"workHandoff\"\n | \"workingCopyId\"\n | \"executionContext\"\n | \"agentControllerRef\"\n | \"transportMode\"\n | \"targetProfileId\"\n | \"targetProfileName\"\n | \"spaceId\"\n | \"spacePassword\"\n | \"taskId\"\n | \"prompt\"\n >;\n ownerUserId: string;\n workingDirectory: string;\n}) {\n const { task } = input;\n if (!task.workHandoff) {\n return input.workingDirectory;\n }\n if (\n !task.executionContext ||\n task.executionContext.access !== \"space_context\" ||\n task.agentControllerRef !== \"builtin:codex\" ||\n task.transportMode !== \"codex-app-server\"\n ) {\n throw new Error(\n \"Selected-file handoffs require a new Space-only context on Codex App Server. This controller cannot enforce that boundary.\"\n );\n }\n const organizationId = task.executionContext.scope.organizationId;\n const baseUrl = await resolveBaseUrl();\n const laneRoot = resolveOpenMeldRootDir();\n const assertCurrentIdentity = async () => {\n const auth = await getAuthSessionState({ validateRemote: false });\n if (\n auth.session?.user?.id !== input.ownerUserId ||\n auth.session?.activeOrganization?.id !== organizationId\n ) {\n throw new Error(\n \"The account or Organization changed before handoff preparation.\"\n );\n }\n };\n await assertCurrentIdentity();\n const requestContext = buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n openMeldProfileId: task.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.ownerUserId,\n profileName: task.targetProfileName ?? task.targetProfileId,\n },\n });\n const foundation = createCliApiClientFoundation(baseUrl, {\n expectedOwnerUserId: input.ownerUserId,\n organizationId,\n });\n const api = createSpaceApi(foundation);\n const common = {\n spaceId: task.spaceId,\n requestContext,\n ...(task.spacePassword ? { spacePassword: task.spacePassword } : {}),\n };\n const copies = createSpaceWorkingCopies({\n laneRoot,\n scope: {\n accountId: input.ownerUserId,\n organizationId,\n spaceId: task.spaceId,\n profileId: task.targetProfileId,\n baseUrl,\n },\n assertCurrentIdentity,\n transport: {\n read: (fileId, revision) =>\n downloadWorkingCopyFile(api, { ...common, fileId, revision }),\n get: async (fileId) => (await api.getFile({ ...common, fileId })).file,\n write: async (write) =>\n await api.updateFileContent({ ...common, ...write }),\n },\n });\n const key = createHash(\"sha256\")\n .update(\n JSON.stringify([\n baseUrl,\n input.ownerUserId,\n organizationId,\n task.spaceId,\n task.targetProfileId,\n task.taskId,\n ])\n )\n .digest(\"hex\");\n const records = join(laneRoot, \"space-work-dispatches\");\n await mkdir(records, { recursive: true, mode: 0o700 });\n const recordPath = join(records, `${key}.json`);\n let copyId: string;\n let root: string;\n const stored = await readFile(recordPath, \"utf8\").catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n );\n if (stored) {\n const record = JSON.parse(stored) as {\n copyId: string;\n root: string;\n };\n copyId = record.copyId;\n const status = await copies.resume(copyId);\n root = status.root;\n if (\n root !== record.root ||\n root !== join(input.workingDirectory, `handoff-${copyId}`)\n ) {\n throw new Error(\"The handoff workspace identity changed.\");\n }\n } else {\n // The existing dispatch owner serializes execution. This private record is\n // published only after preparation; partial directories are never reused.\n copyId = randomUUID();\n root = join(input.workingDirectory, `handoff-${copyId}`);\n await copies.prepare(\n spaceWorkSelectionSchema.parse({\n schemaVersion: 1,\n files: task.workHandoff.files,\n }),\n root,\n copyId\n );\n await writeFile(recordPath, JSON.stringify({ copyId, root }), {\n flag: \"wx\",\n mode: 0o600,\n });\n }\n const skillsRoot = join(root, \".openmeld-skills\");\n if (task.workHandoff.skills.length) {\n await mkdir(skillsRoot, { recursive: true, mode: 0o700 });\n if ((await lstat(skillsRoot)).isSymbolicLink()) {\n throw new Error(\"The Skill directory was replaced by a symbolic link.\");\n }\n }\n const skills = createOrganizationSkillsApi(foundation);\n for (const [index, selected] of task.workHandoff.skills.entries()) {\n await assertCurrentIdentity();\n const result = await skills.get({ ...selected, requestContext });\n const release = result.selectedRelease;\n if (\n !release ||\n result.skill.organizationId !== organizationId ||\n !result.skill.enabled ||\n release.releaseId !== selected.releaseId ||\n release.digest !== selected.digest ||\n release.bundle.portable.name !== selected.name\n ) {\n throw new Error(\n \"The selected Skill release is unavailable or changed. No latest-version fallback is allowed.\"\n );\n }\n await materializeOrganizationSkillRelease({\n ...selected,\n organizationId,\n bundle: release.bundle,\n releaseDirectory: join(skillsRoot, String(index)),\n });\n }\n await assertCurrentIdentity();\n await copies.status(copyId);\n task.workingCopyId = copyId;\n task.prompt +=\n \"\\n\\nThe selected inputs are prepared in your working directory. Selected Skills (including resources) are in .openmeld-skills/<selection index>/SKILL.md. Use the working_copy tool to check, commit or reconcile your edits; it does not complete this Wake. Attach the exact saved file references with the reply tool when delivering results.\";\n return root;\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport type {\n OpenMeldRequestContext,\n OpenMeldSpaceEgressAction,\n SpaceThreadContext,\n} from \"@openmeld/schemas/types\";\nimport {\n buildSpaceRoundSignalPublication,\n isWakeClosingSystemNoticeType,\n} from \"@openmeld/space\";\nimport {\n SPACE_COLLABORATION_CONTEXT_RULE,\n SPACE_PERSONAL_CONTRIBUTION_RULE,\n} from \"@openmeld/space-mesh\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { createCliSpaceApi } from \"../../space/cli-space-api\";\nimport { fetchSpaceUpdates } from \"../../space/updates-api\";\n\nconst OBSERVATION_LIMIT = 20;\nconst SIGNAL_TEXT_LIMIT = 2000;\n\nexport type DispatchAgentReplyObservation = {\n observedThroughSignalId: string;\n relevantSignals: SignalEnvelope[];\n status: \"changed\" | \"current\";\n};\n\nexport async function readDispatchAgentReplyObservation(input: {\n currentWakeTargetProfileIds?: readonly string[];\n requestContext: OpenMeldRequestContext;\n sourceSignalId: string;\n spaceId: string;\n spacePassword: string | null;\n threadContext: SpaceThreadContext | null;\n wakeSourceSignalId: string;\n}): Promise<DispatchAgentReplyObservation> {\n const baseUrl = await resolveBaseUrl();\n const candidates = input.threadContext\n ? await readThreadSignalsAfterSource({\n baseUrl,\n requestContext: input.requestContext,\n sourceSignalId: input.sourceSignalId,\n spaceId: input.spaceId,\n spacePassword: input.spacePassword,\n threadId: input.threadContext.threadId,\n })\n : (\n await fetchSpaceUpdates({\n afterSignalId: input.sourceSignalId,\n baseUrl,\n limit: OBSERVATION_LIMIT,\n requestContext: input.requestContext,\n space: input.spaceId,\n ...(input.spacePassword ? { password: input.spacePassword } : {}),\n })\n ).signals;\n return resolveDispatchAgentReplyObservation({\n candidates,\n currentWakeTargetProfileIds: input.currentWakeTargetProfileIds,\n sourceSignalId: input.sourceSignalId,\n wakeSourceSignalId: input.wakeSourceSignalId,\n });\n}\n\nexport function resolveDispatchAgentReplyObservation(input: {\n candidates: readonly SignalEnvelope[];\n currentWakeTargetProfileIds?: readonly string[];\n sourceSignalId: string;\n wakeSourceSignalId?: string;\n}): DispatchAgentReplyObservation {\n const currentWakeTargetProfileIds = new Set(\n (input.currentWakeTargetProfileIds ?? []).map((profileId) =>\n profileId.trim()\n )\n );\n const relevantSignals = input.candidates\n .filter(\n (signal) =>\n isRelevantCollaborationSignal(signal) &&\n isSignalInCurrentWakeScope(\n signal,\n currentWakeTargetProfileIds,\n input.wakeSourceSignalId ?? input.sourceSignalId\n )\n )\n .slice(0, OBSERVATION_LIMIT);\n const observedThroughSignalId =\n input.candidates.at(-1)?.id ?? input.sourceSignalId;\n return {\n observedThroughSignalId,\n relevantSignals,\n status: relevantSignals.length > 0 ? \"changed\" : \"current\",\n };\n}\n\nexport function attachAgentReplyObservation(input: {\n action: OpenMeldSpaceEgressAction;\n observedThroughSignalId: string;\n}): OpenMeldSpaceEgressAction {\n if (input.action.type !== \"post_message\") {\n return input.action;\n }\n return {\n ...input.action,\n observedThroughSignalId: input.observedThroughSignalId,\n };\n}\n\nexport function buildAgentReplyReconsiderationPrompt(input: {\n action: OpenMeldSpaceEgressAction;\n originalWake: {\n sourceSignalId: string;\n targetProfileId: string;\n text: string;\n };\n relevantSignals: readonly SignalEnvelope[];\n omittedThroughSignalId?: string;\n spaceId: string;\n}): string {\n const updates = input.relevantSignals.map((signal) => ({\n actorProfileId: readCollaborationActorProfileId(signal),\n authorKind: signal.profile.kind,\n outcome: resolveCollaborationOutcome(signal),\n signalId: signal.id,\n text: readSignalText(signal).slice(0, SIGNAL_TEXT_LIMIT),\n truncated: readSignalText(signal).length > SIGNAL_TEXT_LIMIT,\n }));\n return [\n \"OpenMeld concurrent Space update review.\",\n `Space: ${input.spaceId}`,\n \"Continue the original Wake, not a new assignment: do not run activation-intent classification against the newer messages. Another Agent's reply does not turn you into a reference or candidate or transfer your assignment.\",\n `Original Wake (the assignment being completed): ${JSON.stringify(input.originalWake)}`,\n \"This bounded view includes earlier review facts as well as new public messages, in publication order. Prior review turns may not be present in this conversation.\",\n SPACE_COLLABORATION_CONTEXT_RULE,\n \"Your previous action is an unpublished proposal.\",\n \"An accepted action acknowledgement does not mean the Space published it. You still have one public reply available for this Wake.\",\n \"Do not redo completed work or repeat external side effects.\",\n \"A failed, stopped, or silent outcome is not a public contribution. Use it only as truthful availability and coordination context.\",\n \"Keep the user's full request as the goal. Reconsider only the final Space action in light of these newer messages.\",\n \"If a follow-up needs work that this review cannot perform, say what remains undone; do not imply that acknowledging it starts or queues that work.\",\n SPACE_PERSONAL_CONTRIBUTION_RULE,\n \"For dependent contributions, follow the user's shared constraints and confirmed contributions. In an ordered sequence, contribute only the next valid step, not a future step with unpublished prerequisites. A participant list or proposed division of work is not evidence that earlier steps happened. Avoid duplicating completed work, not requested personal answers.\",\n \"Call exactly one dispatch-scoped OpenMeld Space Action tool for the final action and inspect its acknowledgement. Discover the tool before concluding it is unavailable; use the provided CLI only if unavailable. Answer text never becomes an action.\",\n \"Record the final action even if you keep the same answer.\",\n ...(input.omittedThroughSignalId\n ? [\n `Earlier review messages through signal ${JSON.stringify(input.omittedThroughSignalId)} were omitted from this bounded view. Absence is not evidence that nothing happened. Read the originating Space or thread history if those facts affect your action.`,\n ]\n : []),\n \"A truncated message is an excerpt; read its original when omitted details affect your action.\",\n `Previous proposed action: ${JSON.stringify(input.action)}`,\n `Observed Space messages: ${JSON.stringify(updates)}`,\n ].join(\"\\n\");\n}\n\nexport async function coordinateDispatchAgentReply<T>(input: {\n action: OpenMeldSpaceEgressAction;\n originalWake: {\n sourceSignalId: string;\n targetProfileId: string;\n text: string;\n };\n currentValue: T;\n observation: DispatchAgentReplyObservation;\n reconsider: (\n prompt: string,\n observation: DispatchAgentReplyObservation\n ) => Promise<{\n action: OpenMeldSpaceEgressAction | undefined;\n value: T;\n }>;\n refreshObservation?: (\n observedThroughSignalId: string\n ) => Promise<DispatchAgentReplyObservation>;\n spaceId: string;\n}): Promise<{\n action: OpenMeldSpaceEgressAction | undefined;\n reconsiderationCount: number;\n reconsidered: boolean;\n value: T;\n}> {\n let action: OpenMeldSpaceEgressAction | undefined = input.action;\n let observation = input.observation;\n let reconsiderationCount = 0;\n let value = input.currentValue;\n // Repair forks preserve canonical identity, not the previous fork's memory.\n // Retain a bounded public view only for this coordination call, never a\n // private transcript or a second source of Space/execution truth.\n const observedSignals = new Map<string, SignalEnvelope>();\n let omittedThroughSignalId: string | undefined;\n\n while (observation.status === \"changed\") {\n for (const signal of observation.relevantSignals) {\n observedSignals.set(signal.id, signal);\n if (observedSignals.size > OBSERVATION_LIMIT) {\n const oldestId = observedSignals.keys().next().value;\n if (oldestId) {\n observedSignals.delete(oldestId);\n omittedThroughSignalId = oldestId;\n }\n }\n }\n const reconsidered = await input.reconsider(\n buildAgentReplyReconsiderationPrompt({\n action,\n originalWake: input.originalWake,\n relevantSignals: [...observedSignals.values()],\n omittedThroughSignalId,\n spaceId: input.spaceId,\n }),\n observation\n );\n action = reconsidered.action;\n value = reconsidered.value;\n reconsiderationCount += 1;\n if (\n !action ||\n action.type !== \"post_message\" ||\n !input.refreshObservation\n ) {\n break;\n }\n observation = await input.refreshObservation(\n observation.observedThroughSignalId\n );\n }\n\n return {\n action: action\n ? attachAgentReplyObservation({\n action,\n observedThroughSignalId: observation.observedThroughSignalId,\n })\n : undefined,\n reconsiderationCount,\n reconsidered: reconsiderationCount > 0,\n value,\n };\n}\n\nfunction isRelevantCollaborationSignal(signal: SignalEnvelope): boolean {\n if (signal.type === \"signal.system_notice\") {\n return isWakeClosingSystemNoticeType(signal.data.noticeType);\n }\n return (\n (signal.type === \"signal.text\" || signal.type === \"signal.status\") &&\n (signal.type !== \"signal.text\" || signal.data.meta?.transient !== true)\n );\n}\n\nfunction readSignalText(signal: SignalEnvelope): string {\n return signal.type === \"signal.text\" ||\n signal.type === \"signal.status\" ||\n signal.type === \"signal.system_notice\"\n ? signal.data.text\n : \"\";\n}\n\nfunction isSignalInCurrentWakeScope(\n signal: SignalEnvelope,\n currentWakeTargetProfileIds: ReadonlySet<string>,\n wakeSourceSignalId: string\n): boolean {\n if (signal.profile.kind === \"human\") {\n return !isNewHumanWake(signal);\n }\n if (currentWakeTargetProfileIds.size === 0) {\n return true;\n }\n const publication = buildSpaceRoundSignalPublication(signal);\n return Boolean(\n publication?.actorProfileId &&\n currentWakeTargetProfileIds.has(publication.actorProfileId) &&\n publication.replyToSignalId === wakeSourceSignalId\n );\n}\n\nfunction isNewHumanWake(signal: SignalEnvelope): boolean {\n return Boolean(\n signal.type === \"signal.text\" &&\n signal.data.messageEnvelope?.activationTargets.length\n );\n}\n\nfunction readCollaborationActorProfileId(\n signal: SignalEnvelope\n): string | null {\n return signal.profile.kind === \"human\"\n ? signal.profile.profileId\n : (buildSpaceRoundSignalPublication(signal)?.actorProfileId ?? null);\n}\n\nfunction resolveCollaborationOutcome(\n signal: SignalEnvelope\n): \"contribution\" | \"failed\" | \"silent\" | \"stopped\" | \"status\" {\n if (signal.type === \"signal.text\") {\n return \"contribution\";\n }\n if (signal.type === \"signal.status\") {\n return \"status\";\n }\n switch (signal.data.noticeType) {\n case \"stay_silent\":\n return \"silent\";\n case \"wake_stopped\":\n return \"stopped\";\n default:\n return \"failed\";\n }\n}\n\nasync function readThreadSignalsAfterSource(input: {\n baseUrl: string;\n requestContext: OpenMeldRequestContext;\n sourceSignalId: string;\n spaceId: string;\n spacePassword: string | null;\n threadId: string;\n}): Promise<SignalEnvelope[]> {\n const response = await createCliSpaceApi(input.baseUrl).listThreadSignals({\n afterSignalId: input.sourceSignalId,\n limit: OBSERVATION_LIMIT,\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n threadId: input.threadId,\n ...(input.spacePassword ? { spacePassword: input.spacePassword } : {}),\n });\n return response.signals;\n}\n","import type { LocalExecutionSlotTaskResult } from \"@openmeld/local-service\";\nimport type { OpenMeldDaemonTaskResultPayload } from \"@openmeld/schemas/types\";\nimport { DaemonServiceRunError } from \"../core/types\";\nimport type { DispatchResultOutboxSettlement } from \"./dispatch-result-outbox\";\n\nfunction requireDispatchResultOutboxSettlement(input: {\n settlement: Promise<DispatchResultOutboxSettlement> | null;\n}): Promise<DispatchResultOutboxSettlement> {\n if (!input.settlement) {\n throw new DaemonServiceRunError({\n code: \"dispatch.result_settlement.not_registered\",\n message:\n \"OpenMeld could not wait for the Agent reply because result settlement was not registered.\",\n });\n }\n return input.settlement;\n}\n\nfunction shouldAwaitAgentReplySettlement(\n payload: OpenMeldDaemonTaskResultPayload\n): boolean {\n return (\n (payload.status === \"success\" || payload.status === \"partial_success\") &&\n payload.spaceAction?.type === \"post_message\"\n );\n}\n\nexport async function settleAgentReplyProposals(input: {\n initialResultPayload: OpenMeldDaemonTaskResultPayload;\n reconsider: (\n agentReplyObservationCursor: string\n ) => Promise<OpenMeldDaemonTaskResultPayload>;\n submit: (payload: OpenMeldDaemonTaskResultPayload) => {\n resultSummary: LocalExecutionSlotTaskResult;\n settlement: Promise<DispatchResultOutboxSettlement> | null;\n };\n}): Promise<{\n resultPayload: OpenMeldDaemonTaskResultPayload;\n resultSummary: LocalExecutionSlotTaskResult | null;\n}> {\n let resultPayload = input.initialResultPayload;\n while (shouldAwaitAgentReplySettlement(resultPayload)) {\n const proposal = input.submit(resultPayload);\n const settlement = await requireDispatchResultOutboxSettlement(proposal);\n if (settlement.status === \"accepted\") {\n return {\n resultPayload,\n resultSummary: proposal.resultSummary,\n };\n }\n if (settlement.status === \"rejected_terminal\") {\n throw new DaemonServiceRunError({\n code: settlement.reasonCode,\n message: `OpenMeld rejected the Agent reply proposal: ${settlement.reasonCode}`,\n });\n }\n const previousCursor = readObservationCursor(resultPayload);\n resultPayload = await input.reconsider(previousCursor);\n if (\n shouldAwaitAgentReplySettlement(resultPayload) &&\n readObservationCursor(resultPayload) === previousCursor\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_observation.no_progress\",\n message:\n \"OpenMeld requested a reply review, but no newer Space context could be read. Open Diagnostics before waking the Agent again.\",\n });\n }\n }\n return { resultPayload, resultSummary: null };\n}\n\nfunction readObservationCursor(\n payload: OpenMeldDaemonTaskResultPayload\n): string {\n return (\n (payload.spaceAction?.type === \"post_message\"\n ? payload.spaceAction.observedThroughSignalId?.trim()\n : null) || payload.sourceEventId\n );\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { buildSpaceAttachmentDownloadPath } from \"@openmeld/api-client\";\nimport type { SpaceMessageAttachment } from \"@openmeld/schemas/types\";\nimport { resolveRegistryRuntimeAdapterContractByAgentControllerRef } from \"../../agents/registry-source\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldProfileIdentityRequestHeadersWithAuth } from \"../../config/request-headers\";\nimport { fetchSpaceRequestWithTimeout } from \"../../space/fetch-with-timeout\";\n\nconst SAFE_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;\n\nexport type DispatchImageAttachmentFailure = {\n attachment: SpaceMessageAttachment;\n errorCode:\n | \"controller_image_input_unsupported\"\n | \"download_failed\"\n | \"download_size_mismatch\"\n | \"download_type_mismatch\"\n | \"invalid_attachment_id\"\n | \"invalid_task_id\"\n | \"write_failed\";\n errorMessage: string;\n};\n\nexport type DispatchImageAttachmentDownload = (input: {\n attachmentId: string;\n spaceId: string;\n}) => Promise<Response>;\n\nexport type DispatchImageAttachmentPreparation = {\n failures: DispatchImageAttachmentFailure[];\n localPaths: string[];\n promptSection: string | null;\n};\n\nexport async function downloadDispatchImageAttachment(input: {\n attachmentId: string;\n ownerName: string | null;\n ownerUserId: string;\n spaceId: string;\n spacePassword: string | null;\n targetProfileId: string;\n targetProfileName: string | null;\n}): Promise<Response> {\n const baseUrl = await resolveBaseUrl();\n const requestUrl = new URL(\n buildSpaceAttachmentDownloadPath(input.spaceId, input.attachmentId),\n baseUrl\n ).toString();\n const headers = await buildOpenMeldProfileIdentityRequestHeadersWithAuth({\n profileIdentity: {\n openMeldProfileId: input.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.ownerUserId,\n ...(input.ownerName ? { ownerName: input.ownerName } : {}),\n profileName: input.targetProfileName ?? input.targetProfileId,\n },\n requestUrl,\n ...(input.spacePassword ? { spacePassword: input.spacePassword } : {}),\n });\n return await fetchSpaceRequestWithTimeout({\n url: requestUrl,\n operation: \"space.attachment.download\",\n init: { headers },\n });\n}\n\nexport async function materializeDispatchImageAttachments(input: {\n agentControllerRef: string;\n attachments: SpaceMessageAttachment[];\n downloadAttachment: DispatchImageAttachmentDownload;\n providerRuntimeWorkingDirectory: string;\n spaceId: string;\n taskId: string;\n}): Promise<DispatchImageAttachmentPreparation> {\n if (input.attachments.length === 0) {\n return { failures: [], localPaths: [], promptSection: null };\n }\n\n // TODO(models.dev): OpenCode currently declares local-file image input\n // statically. Resolve it per selected model once the catalog exposes a\n // stable vision-capability contract.\n const capability = resolveRegistryRuntimeAdapterContractByAgentControllerRef(\n input.agentControllerRef\n )?.capabilityDeclaration.imageInputCapability;\n if (capability !== \"local_file_path\") {\n return buildPreparationResult({\n failures: input.attachments.map((attachment) => ({\n attachment,\n errorCode: \"controller_image_input_unsupported\",\n errorMessage: `Agent Controller ${input.agentControllerRef} does not accept local image file paths.`,\n })),\n materialized: [],\n });\n }\n\n if (!isSafePathSegment(input.taskId)) {\n return buildPreparationResult({\n failures: input.attachments.map((attachment) => ({\n attachment,\n errorCode: \"invalid_task_id\",\n errorMessage: \"The dispatch task ID is not safe for a local path.\",\n })),\n materialized: [],\n });\n }\n\n const attachmentDirectory = join(\n input.providerRuntimeWorkingDirectory,\n \".openmeld\",\n \"attachments\",\n input.taskId\n );\n const failures: DispatchImageAttachmentFailure[] = [];\n const materialized: Array<{\n attachment: SpaceMessageAttachment;\n localPath: string;\n }> = [];\n\n for (const attachment of input.attachments) {\n if (!isSafePathSegment(attachment.id)) {\n failures.push({\n attachment,\n errorCode: \"invalid_attachment_id\",\n errorMessage: \"The attachment ID is not safe for a local path.\",\n });\n continue;\n }\n\n let response: Response;\n try {\n response = await input.downloadAttachment({\n attachmentId: attachment.id,\n spaceId: input.spaceId,\n });\n } catch (error) {\n failures.push({\n attachment,\n errorCode: \"download_failed\",\n errorMessage: toErrorMessage(error),\n });\n continue;\n }\n\n if (!response.ok) {\n failures.push({\n attachment,\n errorCode: \"download_failed\",\n errorMessage: `Attachment download returned HTTP ${response.status}.`,\n });\n continue;\n }\n const responseMimeType = normalizeMimeType(\n response.headers.get(\"content-type\")\n );\n if (responseMimeType !== attachment.mimeType) {\n failures.push({\n attachment,\n errorCode: \"download_type_mismatch\",\n errorMessage: `Attachment download returned ${responseMimeType ?? \"no content type\"}; expected ${attachment.mimeType}.`,\n });\n continue;\n }\n\n let bytes: Uint8Array;\n try {\n bytes = new Uint8Array(await response.arrayBuffer());\n } catch (error) {\n failures.push({\n attachment,\n errorCode: \"download_failed\",\n errorMessage: toErrorMessage(error),\n });\n continue;\n }\n if (bytes.byteLength !== attachment.sizeBytes) {\n failures.push({\n attachment,\n errorCode: \"download_size_mismatch\",\n errorMessage: `Attachment download returned ${bytes.byteLength} bytes; expected ${attachment.sizeBytes}.`,\n });\n continue;\n }\n\n const localPath = join(\n attachmentDirectory,\n `${attachment.id}${resolveImageExtension(attachment)}`\n );\n try {\n await mkdir(attachmentDirectory, { recursive: true });\n await writeFile(localPath, bytes);\n } catch (error) {\n failures.push({\n attachment,\n errorCode: \"write_failed\",\n errorMessage: toErrorMessage(error),\n });\n continue;\n }\n materialized.push({ attachment, localPath });\n }\n\n return buildPreparationResult({ failures, materialized });\n}\n\nfunction buildPreparationResult(input: {\n failures: DispatchImageAttachmentFailure[];\n materialized: Array<{\n attachment: SpaceMessageAttachment;\n localPath: string;\n }>;\n}): DispatchImageAttachmentPreparation {\n const sections: string[] = [];\n if (input.materialized.length > 0) {\n sections.push(\n [\n \"Attached images (local files):\",\n ...input.materialized.map(\n ({ attachment, localPath }) =>\n `- \\`${localPath}\\` — Space attachment ${formatAttachmentLabel(attachment)} (${attachment.mimeType}).`\n ),\n ].join(\"\\n\")\n );\n }\n if (input.failures.length > 0) {\n sections.push(\n [\n `The user attached ${input.failures.length} image(s) but they could not be retrieved.`,\n ...input.failures.map(\n ({ attachment }) =>\n `- Space attachment ${formatAttachmentLabel(attachment)} (${attachment.id}) was unavailable.`\n ),\n ].join(\"\\n\")\n );\n }\n return {\n failures: input.failures,\n localPaths: input.materialized.map(({ localPath }) => localPath),\n promptSection: sections.length > 0 ? sections.join(\"\\n\\n\") : null,\n };\n}\n\nfunction resolveImageExtension(attachment: SpaceMessageAttachment): string {\n const declaredExtension = extname(attachment.fileName ?? \"\").toLowerCase();\n if (attachment.mimeType === \"image/png\") {\n return declaredExtension === \".png\" ? declaredExtension : \".png\";\n }\n if (declaredExtension === \".jpg\" || declaredExtension === \".jpeg\") {\n return declaredExtension;\n }\n return \".jpg\";\n}\n\nfunction formatAttachmentLabel(attachment: SpaceMessageAttachment): string {\n return attachment.fileName\n ? JSON.stringify(attachment.fileName)\n : attachment.id;\n}\n\nfunction isSafePathSegment(value: string): boolean {\n return SAFE_PATH_SEGMENT_PATTERN.test(value);\n}\n\nfunction normalizeMimeType(value: string | null): string | null {\n const normalized = String(value ?? \"\")\n .split(\";\", 1)[0]\n ?.trim()\n .toLowerCase();\n return normalized ? normalized : null;\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { createHash } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { OFFICIAL_CLI_SKILL_URL } from \"@openmeld/schemas\";\nimport { getConfiguredSkillsConfig } from \"../../config/runtime-config\";\nimport {\n canManageRegistryAgentSkillTargets,\n resolveSkillsAgentRegistry,\n} from \"../../skills/agents\";\nimport {\n installSkillsToTargets,\n type SkillsInstallTarget,\n withSkillsInstallLock,\n} from \"../../skills/installer\";\nimport { resolveSkillInstallStateForTarget } from \"../../skills/state\";\nimport { ensureLocalSkills, type LocalSkill } from \"../../skills/store\";\nimport type { DispatchPromptPlan } from \"./parse-dispatch-task\";\n\nexport type DispatchControllerOpenMeldSkillRepairStatus =\n | \"blocked\"\n | \"failed\"\n | \"lane_isolated\"\n | \"not_needed\"\n | \"repaired\"\n | \"unsupported\";\n\nexport type DispatchControllerOpenMeldSkillRepairResult = {\n agentId: string | null;\n status: DispatchControllerOpenMeldSkillRepairStatus;\n reason?: string;\n skillPath?: string;\n};\n\nconst OPENMELD_CLI_SKILL_ID = \"openmeld-cli\";\n\n/**\n * Restores only OpenMeld's own collaboration skill for the Agent Controller\n * carrying the current dispatch. User-owned skill directories are never\n * overwritten, and isolated lanes cannot mutate published agent state unless\n * the target directory was explicitly configured for that lane.\n */\nexport async function ensureDispatchControllerOpenMeldSkill(input: {\n agentControllerRef: string | null | undefined;\n}): Promise<DispatchControllerOpenMeldSkillRepairResult> {\n const agentId = resolveBuiltinAgentId(input.agentControllerRef);\n if (!agentId) {\n return { agentId: null, status: \"unsupported\" };\n }\n\n try {\n const skillsConfig = await getConfiguredSkillsConfig();\n const registry = resolveSkillsAgentRegistry(skillsConfig);\n const agent = registry[agentId];\n if (!agent?.globalSkillsDir || agent.skillsInstallable !== true) {\n return { agentId, status: \"unsupported\" };\n }\n if (\n agent.globalSkillsDirSource === \"registry-default\" &&\n !canManageRegistryAgentSkillTargets()\n ) {\n return { agentId, status: \"lane_isolated\" };\n }\n\n const openMeldSkill = (await ensureLocalSkills()).find(\n (skill) => skill.id === OPENMELD_CLI_SKILL_ID\n );\n if (!openMeldSkill) {\n return {\n agentId,\n status: \"failed\",\n reason: \"the bundled openmeld-cli skill is unavailable\",\n };\n }\n\n const target: SkillsInstallTarget = {\n id: agentId,\n dir: agent.globalSkillsDir,\n type: \"agent\",\n };\n return await repairOpenMeldSkillTarget({\n agentId,\n openMeldSkill,\n target,\n });\n } catch (error) {\n return {\n agentId,\n status: \"failed\",\n reason: error instanceof Error ? error.message : \"skill repair failed\",\n };\n }\n}\n\nasync function repairOpenMeldSkillTarget(input: {\n agentId: string;\n openMeldSkill: LocalSkill;\n target: SkillsInstallTarget;\n}): Promise<DispatchControllerOpenMeldSkillRepairResult> {\n const currentResult = await resolveExistingSkillResult(input);\n if (currentResult) {\n return currentResult;\n }\n\n const [installResult] = await withSkillsInstallLock(() =>\n installSkillsToTargets({\n skills: [input.openMeldSkill],\n targets: [input.target],\n })\n );\n if (installResult?.status === \"installed\") {\n return {\n agentId: input.agentId,\n status: \"repaired\",\n skillPath: join(input.target.dir, OPENMELD_CLI_SKILL_ID, \"SKILL.md\"),\n };\n }\n if (installResult?.status === \"skipped\") {\n const reconciledResult = await resolveExistingSkillResult(input);\n if (reconciledResult) {\n return reconciledResult;\n }\n }\n return {\n agentId: input.agentId,\n status: \"failed\",\n ...(installResult?.reason ? { reason: installResult.reason } : {}),\n };\n}\n\nasync function resolveExistingSkillResult(input: {\n agentId: string;\n openMeldSkill: LocalSkill;\n target: SkillsInstallTarget;\n}): Promise<DispatchControllerOpenMeldSkillRepairResult | null> {\n const state = await resolveSkillInstallStateForTarget({\n skill: input.openMeldSkill,\n target: input.target,\n });\n if (state.state === \"up_to_date\") {\n return {\n agentId: input.agentId,\n status: \"not_needed\",\n skillPath: `${state.skillDir}/SKILL.md`,\n };\n }\n if (state.state === \"external_conflict\") {\n return {\n agentId: input.agentId,\n status: \"blocked\",\n ...(state.reason ? { reason: state.reason } : {}),\n };\n }\n return null;\n}\n\nfunction resolveBuiltinAgentId(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n if (!normalized.startsWith(\"builtin:\")) {\n return null;\n }\n const agentId = normalized.slice(\"builtin:\".length).trim();\n return agentId.length > 0 ? agentId : null;\n}\n\nexport function applyDispatchSkillInstructions(\n plan: DispatchPromptPlan,\n skill: DispatchControllerOpenMeldSkillRepairResult\n): DispatchPromptPlan {\n const instruction = [\n \"For OpenMeld operations, read the official openmeld-cli Skill entry, then only the topic needed.\",\n ...(skill.skillPath\n ? [`Local entry: ${JSON.stringify(skill.skillPath)}.`]\n : []),\n `If the local entry is unavailable, read ${OFFICIAL_CLI_SKILL_URL}. Follow its relative topic links; do not preload the full guide.`,\n \"The guide does not grant permissions or add CLI commands. Follow this dispatch's action instructions when publishing a reply.\",\n ].join(\"\\n\");\n const developerInstructions = `${plan.developerInstructions}\\n\\n${instruction}`;\n return {\n ...plan,\n developerInstructions,\n fallbackPrompt: `${instruction}\\n\\n${plan.fallbackPrompt}`,\n instructionEpoch: `${plan.instructionEpoch}:skill:${createHash(\"sha256\").update(instruction).digest(\"hex\")}`,\n };\n}\n","import type {\n AdapterAgentContextResolution,\n AdapterDispatchContextDelta,\n} from \"@openmeld/adapter-core\";\nimport type { runRuntimeTask } from \"@openmeld/local-execution\";\nimport {\n buildAgentControllerConversationRef,\n normalizeKnownBuiltinAgentControllerId,\n resolveBuiltinAgentControllerConversationKind,\n} from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n AgentControllerConversationResumePlan,\n ConversationPolicy,\n} from \"@openmeld/schemas/types\";\nimport type { DaemonProfileRouteConfig } from \"../core/types\";\n\nexport function resolveCurrentConversationPolicy(\n routeConfig: DaemonProfileRouteConfig | null\n): ConversationPolicy {\n return { ...(routeConfig?.conversationPolicy ?? {}) };\n}\n\nexport function resolveDispatchContextIdForAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n agentControllerConversationOverride: AgentControllerConversationRef | null;\n agentControllerConversationResumePlan: AgentControllerConversationResumePlan;\n}): string | null {\n if (\n input.agentControllerConversationResumePlan.status !== \"continue_existing\"\n ) {\n return null;\n }\n\n return normalizeOptionalContextId(\n input.agentControllerConversationOverride?.agentControllerConversationId ??\n input.agentControllerConversationId ??\n null\n );\n}\n\nexport function resolvePlannedAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n agentControllerRef: string;\n}): AgentControllerConversationRef | null {\n return buildAgentControllerConversationRefFromAgentControllerConversation(\n input\n );\n}\n\nexport function resolveObservedDispatchAgentControllerConversation(input: {\n contextDelta: AdapterDispatchContextDelta | null;\n contextResolution: AdapterAgentContextResolution | null;\n plannedAgentControllerConversation: AgentControllerConversationRef | null;\n agentControllerConversationOverride: AgentControllerConversationRef | null;\n}): AgentControllerConversationRef | null {\n return (\n input.contextDelta?.agentControllerConversation ??\n input.contextResolution?.agentControllerConversation ??\n input.agentControllerConversationOverride ??\n input.plannedAgentControllerConversation ??\n null\n );\n}\n\nexport function buildAgentControllerConversationRefFromAgentControllerConversation(input: {\n agentControllerConversationId: string | null;\n agentControllerRef: string;\n}): AgentControllerConversationRef | null {\n const conversationId = normalizeOptionalContextId(\n input.agentControllerConversationId\n );\n const agentControllerRef = normalizeOptionalContextId(\n input.agentControllerRef\n );\n if (!(conversationId && agentControllerRef)) {\n return null;\n }\n const builtinProviderId =\n normalizeKnownBuiltinAgentControllerId(agentControllerRef);\n if (builtinProviderId) {\n return buildAgentControllerConversationRef({\n agentControllerRef,\n agentControllerConversationKind:\n resolveBuiltinAgentControllerConversationKind(agentControllerRef) ??\n \"context\",\n agentControllerConversationId: conversationId,\n });\n }\n return buildAgentControllerConversationRef({\n agentControllerRef,\n agentControllerConversationKind: \"context\",\n agentControllerConversationId: conversationId,\n });\n}\n\nexport function areSameAgentControllerConversationRef(\n left: AgentControllerConversationRef,\n right: AgentControllerConversationRef | null\n): boolean {\n if (!right) {\n return false;\n }\n return (\n left.agentControllerRef === right.agentControllerRef &&\n left.agentControllerConversationKind ===\n right.agentControllerConversationKind &&\n left.agentControllerConversationId === right.agentControllerConversationId\n );\n}\n\nexport function normalizeOptionalContextId(\n contextId: string | null | undefined\n): string | null {\n if (typeof contextId !== \"string\") {\n return null;\n }\n const normalized = contextId.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function resolveDispatchContextDeltaFromRuntimeResult(\n dispatchResult: Awaited<ReturnType<typeof runRuntimeTask>>[\"dispatchResult\"]\n): AdapterDispatchContextDelta | null {\n if (!dispatchResult.dispatched) {\n return null;\n }\n if (dispatchResult.adapterResult.status !== \"success\") {\n return null;\n }\n return dispatchResult.adapterResult.contextDelta ?? null;\n}\n","import {\n buildRuntimeWorkspaceFingerprint,\n removeConversationExecutionState,\n upsertConversationExecutionState,\n} from \"@openmeld/local-execution\";\nimport type { DispatchContinuityObservation } from \"@openmeld/local-service\";\nimport type {\n AgentControllerConversationRef,\n BootstrapTemplateFacts,\n ConversationExecutionState,\n LocalRuntimeContextPlan,\n} from \"@openmeld/schemas/types\";\nimport { normalizeOptionalContextId } from \"./execute-dispatch-conversation\";\nimport type { BootstrapPlan } from \"./execute-dispatch-types\";\n\nconst BOOTSTRAP_IDLE_STALE_MS = 24 * 60 * 60 * 1000;\nconst BOOTSTRAP_DISPATCH_STALE_THRESHOLD = 8;\n\nconst isBootstrapExecutionStateMissing = (\n executionState: ConversationExecutionState\n): boolean =>\n !(\n executionState.bootstrapLastAppliedAt &&\n executionState.lastAppliedTemplateVersion &&\n executionState.lastAppliedContentFingerprint\n );\n\nconst isBootstrapIdleStale = (\n lastActivatedAt: string | undefined,\n nowMs: number\n): boolean => {\n if (!lastActivatedAt) {\n return false;\n }\n const lastActivatedMs = Date.parse(lastActivatedAt);\n if (!Number.isFinite(lastActivatedMs)) {\n return false;\n }\n return nowMs - lastActivatedMs >= BOOTSTRAP_IDLE_STALE_MS;\n};\n\nexport function resolveBootstrapPlan(input: {\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n executionState: ConversationExecutionState | null;\n localRuntimeContextPlan: LocalRuntimeContextPlan;\n nowMs: number;\n}): BootstrapPlan {\n if (input.localRuntimeContextPlan.status === \"recreate\") {\n return {\n reason: \"compatibility_recreate\",\n shouldInject: true,\n };\n }\n if (!input.executionState) {\n return {\n reason: \"missing_bootstrap_state\",\n shouldInject: true,\n };\n }\n if (input.executionState.pendingBootstrapReason === \"context_healed\") {\n return {\n reason: \"context_healed\",\n shouldInject: true,\n };\n }\n if (isBootstrapExecutionStateMissing(input.executionState)) {\n return {\n reason: \"missing_bootstrap_state\",\n shouldInject: true,\n };\n }\n if (\n input.executionState.lastAppliedTemplateVersion !==\n input.bootstrapTemplateFacts.templateVersion ||\n input.executionState.lastAppliedContentFingerprint !==\n input.bootstrapTemplateFacts.contentFingerprint\n ) {\n return {\n reason: \"template_changed\",\n shouldInject: true,\n };\n }\n if (\n isBootstrapIdleStale(\n input.executionState.bootstrapLastActivatedAt,\n input.nowMs\n )\n ) {\n return {\n reason: \"idle_stale\",\n shouldInject: true,\n };\n }\n if (\n input.executionState.dispatchesSinceBootstrapApplied >=\n BOOTSTRAP_DISPATCH_STALE_THRESHOLD\n ) {\n return {\n reason: \"dispatch_count_stale\",\n shouldInject: true,\n };\n }\n return {\n reason: null,\n shouldInject: false,\n };\n}\n\nexport function markBootstrapInjectedContext(input: {\n executionState: ConversationExecutionState | null;\n agentContextLookupKey: string;\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n existingContextId: string | null;\n effectiveRuntimeWorkingDirectory: string;\n nowIso: string;\n}): ConversationExecutionState {\n const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n input.effectiveRuntimeWorkingDirectory\n );\n return {\n agentContextLookupKey: input.agentContextLookupKey,\n activeContextId: normalizeOptionalContextId(input.existingContextId),\n dispatchesSinceBootstrapApplied: 0,\n bootstrapLastAppliedAt: input.nowIso,\n bootstrapLastActivatedAt: input.nowIso,\n lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,\n lastAppliedContentFingerprint:\n input.bootstrapTemplateFacts.contentFingerprint,\n lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,\n runtimeWorkspaceFingerprint,\n pendingBootstrapReason: undefined,\n updatedAt: input.nowIso,\n ...(input.executionState?.lastResolvedAgentControllerConversation\n ? {\n lastResolvedAgentControllerConversation: {\n ...input.executionState.lastResolvedAgentControllerConversation,\n },\n }\n : {}),\n };\n}\n\nexport function reconcileBootstrapInjectedContextAfterDispatch(input: {\n executionState: ConversationExecutionState | null;\n shouldInjectBootstrap: boolean;\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n continuityObservation: DispatchContinuityObservation | null;\n contextHealed: boolean;\n dispatchedContextId: string | null;\n effectiveRuntimeWorkingDirectory: string;\n nowIso: string;\n resolvedAgentControllerConversation: AgentControllerConversationRef | null;\n}): ConversationExecutionState | null {\n if (!input.executionState) {\n return null;\n }\n\n const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n input.effectiveRuntimeWorkingDirectory\n );\n const nextExecutionState: ConversationExecutionState = {\n ...input.executionState,\n bootstrapLastActivatedAt: input.nowIso,\n lastRuntimeWorkspacePath: input.effectiveRuntimeWorkingDirectory,\n runtimeWorkspaceFingerprint,\n updatedAt: input.nowIso,\n ...(input.resolvedAgentControllerConversation\n ? {\n lastResolvedAgentControllerConversation: {\n ...input.resolvedAgentControllerConversation,\n },\n }\n : {}),\n };\n\n if (input.shouldInjectBootstrap) {\n const dispatchedContextId = normalizeOptionalContextId(\n input.dispatchedContextId\n );\n return {\n ...nextExecutionState,\n activeContextId:\n dispatchedContextId ?? nextExecutionState.activeContextId,\n dispatchesSinceBootstrapApplied: 0,\n bootstrapLastAppliedAt:\n nextExecutionState.bootstrapLastAppliedAt ?? input.nowIso,\n bootstrapLastActivatedAt: input.nowIso,\n lastAppliedTemplateVersion: input.bootstrapTemplateFacts.templateVersion,\n lastAppliedContentFingerprint:\n input.bootstrapTemplateFacts.contentFingerprint,\n pendingBootstrapReason: undefined,\n };\n }\n\n if (input.contextHealed) {\n return {\n ...nextExecutionState,\n activeContextId:\n normalizeOptionalContextId(input.dispatchedContextId) ??\n nextExecutionState.activeContextId,\n dispatchesSinceBootstrapApplied: 0,\n bootstrapLastAppliedAt: undefined,\n lastAppliedTemplateVersion: undefined,\n lastAppliedContentFingerprint: undefined,\n pendingBootstrapReason: \"context_healed\",\n };\n }\n\n if (input.continuityObservation?.status === \"implicit_rotation\") {\n return {\n ...nextExecutionState,\n activeContextId:\n normalizeOptionalContextId(input.dispatchedContextId) ??\n nextExecutionState.activeContextId,\n dispatchesSinceBootstrapApplied:\n nextExecutionState.dispatchesSinceBootstrapApplied + 1,\n pendingBootstrapReason: undefined,\n };\n }\n\n return {\n ...nextExecutionState,\n dispatchesSinceBootstrapApplied:\n nextExecutionState.dispatchesSinceBootstrapApplied + 1,\n pendingBootstrapReason: undefined,\n };\n}\n\nexport function rollbackBootstrapExecutionStateAfterDispatchFailure(input: {\n agentContextLookupKey: string;\n executionStateBeforeDispatch: ConversationExecutionState | null;\n state: Parameters<typeof upsertConversationExecutionState>[0][\"state\"];\n}) {\n const stateWithoutCurrentLookupKey = removeConversationExecutionState({\n agentContextLookupKey: input.agentContextLookupKey,\n state: input.state,\n });\n if (input.executionStateBeforeDispatch) {\n return upsertConversationExecutionState({\n state: stateWithoutCurrentLookupKey,\n executionState: input.executionStateBeforeDispatch,\n });\n }\n return stateWithoutCurrentLookupKey;\n}\n","import {\n removeConversationExecutionState,\n upsertConversationExecutionState,\n} from \"@openmeld/local-execution\";\nimport type { ConversationExecutionState } from \"@openmeld/schemas/types\";\n\nexport function upsertConversationExecutionStateForLookupKey(input: {\n executionState: ConversationExecutionState;\n replacedLookupKey?: string | null;\n state: Parameters<typeof upsertConversationExecutionState>[0][\"state\"];\n targetLookupKey: string;\n}) {\n let nextState = input.state;\n const staleLookupKeys = new Set<string>();\n if (input.executionState.agentContextLookupKey !== input.targetLookupKey) {\n staleLookupKeys.add(input.executionState.agentContextLookupKey);\n }\n if (\n input.replacedLookupKey &&\n input.replacedLookupKey !== input.targetLookupKey\n ) {\n staleLookupKeys.add(input.replacedLookupKey);\n }\n for (const agentContextLookupKey of staleLookupKeys) {\n nextState = removeConversationExecutionState({\n agentContextLookupKey,\n state: nextState,\n });\n }\n return upsertConversationExecutionState({\n state: nextState,\n executionState: {\n ...input.executionState,\n agentContextLookupKey: input.targetLookupKey,\n },\n });\n}\n","import type {\n AdapterDispatchDiagnostics,\n AdapterDispatchTelemetry,\n AdapterRuntimeEvent,\n} from \"@openmeld/adapter-core\";\nimport type {\n RuntimeTaskResult,\n runRuntimeTask,\n} from \"@openmeld/local-execution\";\nimport type {\n DispatchContinuityObservation,\n LocalExecutionSlotTaskResult,\n} from \"@openmeld/local-service\";\nimport type {\n OpenMeldDaemonTaskResultPayload,\n RuntimeTransportDeliverDispatchRequest,\n} from \"@openmeld/schemas/types\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine } from \"../core/logger\";\nimport { emitDaemonDispatchJournalEvent } from \"./daemon-dispatch-journal\";\nimport type {\n DispatchLocalJournalPhase,\n ParsedDispatchTask,\n} from \"./execute-dispatch-types\";\nimport { buildDispatchCorrelation } from \"./parse-dispatch-task\";\n\nexport function resolveAdapterTelemetry(\n dispatchResult: Awaited<ReturnType<typeof runRuntimeTask>>[\"dispatchResult\"]\n): AdapterDispatchTelemetry | null {\n if (!dispatchResult.dispatched) {\n return null;\n }\n return dispatchResult.adapterResult.telemetry ?? null;\n}\n\nexport function resolveAdapterDiagnostics(\n dispatchResult: Awaited<ReturnType<typeof runRuntimeTask>>[\"dispatchResult\"]\n): AdapterDispatchDiagnostics | null {\n if (!dispatchResult.dispatched) {\n return null;\n }\n return dispatchResult.adapterResult.diagnostics ?? null;\n}\n\nexport function buildRuntimeObservationPayload(input: {\n continuityObservation: DispatchContinuityObservation | null;\n daemonWorkingDirectory: string;\n deliveryRecoveryReason: ParsedDispatchTask[\"deliveryRecoveryReason\"];\n dispatchId: string;\n providerRuntimeWorkingDirectory: string;\n resultPayload: OpenMeldDaemonTaskResultPayload;\n runtimeResult: Pick<\n Awaited<ReturnType<typeof runRuntimeTask>>,\n \"dispatchResult\" | \"resultPayload\"\n >;\n runtimeStartedAtMs: number;\n taskId: string;\n}): Record<string, unknown> {\n const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);\n const diagnostics = resolveAdapterDiagnostics(\n input.runtimeResult.dispatchResult\n );\n const runtimeCompletedAtMs = Date.now();\n const runtimeTelemetryPayload =\n telemetry === null ? {} : buildAdapterRuntimeObservationPayload(telemetry);\n\n return {\n attemptId: input.runtimeResult.resultPayload.attemptId,\n daemonWorkingDirectory: input.daemonWorkingDirectory,\n dispatchId: input.dispatchId,\n ...(\"errorCode\" in input.resultPayload && input.resultPayload.errorCode\n ? { errorCode: input.resultPayload.errorCode }\n : {}),\n ...(diagnostics?.modelNegotiation\n ? { modelNegotiation: diagnostics.modelNegotiation }\n : {}),\n providerRuntimeWorkingDirectory: input.providerRuntimeWorkingDirectory,\n result: input.resultPayload.status,\n runtimeDurationMs: runtimeCompletedAtMs - input.runtimeStartedAtMs,\n taskId: input.taskId,\n ...(input.deliveryRecoveryReason\n ? { deliveryRecoveryReason: input.deliveryRecoveryReason }\n : {}),\n ...runtimeTelemetryPayload,\n };\n}\n\nfunction buildAdapterRuntimeObservationPayload(\n telemetry: AdapterDispatchTelemetry\n): Record<string, number | string | boolean | null> {\n const timeToMetric = (tsMs: number | null | undefined): number | null => {\n return tsMs === undefined || tsMs === null\n ? null\n : tsMs - telemetry.invokedAtMs;\n };\n const adapterDurationMs = timeToMetric(telemetry.completedAtMs);\n const timeToFirstOutputMs = timeToMetric(telemetry.firstOutputAtMs);\n const timeToFirstStderrMs = timeToMetric(telemetry.firstStderrAtMs);\n const timeToFirstStdoutMs = timeToMetric(telemetry.firstStdoutAtMs);\n const timeToProcessSpawnMs = timeToMetric(telemetry.processSpawnedAtMs);\n const timeToStdinClosedMs = timeToMetric(telemetry.stdinClosedAtMs);\n\n return {\n ...(adapterDurationMs === null ? {} : { adapterDurationMs }),\n ...(telemetry.contextHealed === undefined\n ? {}\n : { contextHealed: telemetry.contextHealed }),\n ...(telemetry.contextCompactionObserved === undefined\n ? {}\n : {\n contextCompactionObserved: telemetry.contextCompactionObserved,\n }),\n ...(telemetry.tokenUsage\n ? {\n lastCachedInputTokens: telemetry.tokenUsage.last.cachedInputTokens,\n lastInputTokens: telemetry.tokenUsage.last.inputTokens,\n lastOutputTokens: telemetry.tokenUsage.last.outputTokens,\n lastReasoningOutputTokens:\n telemetry.tokenUsage.last.reasoningOutputTokens,\n lastTotalTokens: telemetry.tokenUsage.last.totalTokens,\n modelContextWindowTokens: telemetry.tokenUsage.modelContextWindow,\n totalCachedInputTokens: telemetry.tokenUsage.total.cachedInputTokens,\n totalInputTokens: telemetry.tokenUsage.total.inputTokens,\n totalOutputTokens: telemetry.tokenUsage.total.outputTokens,\n totalReasoningOutputTokens:\n telemetry.tokenUsage.total.reasoningOutputTokens,\n totalTokens: telemetry.tokenUsage.total.totalTokens,\n }\n : {}),\n resumedContext: telemetry.resumedContext,\n ...(timeToFirstOutputMs === null ? {} : { timeToFirstOutputMs }),\n ...(timeToFirstStderrMs === null ? {} : { timeToFirstStderrMs }),\n ...(timeToFirstStdoutMs === null ? {} : { timeToFirstStdoutMs }),\n ...(timeToProcessSpawnMs === null ? {} : { timeToProcessSpawnMs }),\n ...(telemetry.processId === undefined\n ? {}\n : { providerProcessId: telemetry.processId }),\n ...(timeToStdinClosedMs === null ? {} : { timeToStdinClosedMs }),\n ...(telemetry.timeoutTriggeredAtMs === undefined\n ? {}\n : { providerTimedOut: true }),\n ...(telemetry.exitCode === undefined\n ? {}\n : { providerExitCode: telemetry.exitCode }),\n ...(telemetry.exitSignal === undefined\n ? {}\n : { providerExitSignal: telemetry.exitSignal }),\n };\n}\n\nexport function emitProviderRuntimePhaseLine(input: {\n agentControllerRef: string;\n dispatchId: string;\n event: AdapterRuntimeEvent;\n presenter: Presenter;\n runtimeStartedAtMs: number;\n targetProfileId: string;\n taskId: string;\n}): void {\n const sinceRuntimeStartedMs = input.event.tsMs - input.runtimeStartedAtMs;\n const basePayload = {\n agentControllerRef: input.agentControllerRef,\n dispatchId: input.dispatchId,\n phase: input.event.phase,\n ...(input.event.phase === \"process_spawned\" && input.event.processLaunchKind\n ? { processLaunchKind: input.event.processLaunchKind }\n : {}),\n processId: \"processId\" in input.event ? input.event.processId : null,\n ...(input.event.phase === \"process_spawned\" &&\n input.event.processWorkingDirectoryKind\n ? {\n processWorkingDirectoryKind: input.event.processWorkingDirectoryKind,\n }\n : {}),\n sinceRuntimeStartedMs,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n };\n\n switch (input.event.phase) {\n case \"process_spawned\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_process_spawned\",\n text: `provider process spawned for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"stdin_closed\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_input_written\",\n text: `provider input written for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"first_stdout\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_first_stdout\",\n text: `provider first stdout observed for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"first_stderr\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_first_stderr\",\n text: `provider first stderr observed for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"timeout_triggered\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_timeout_triggered\",\n text: `provider timeout triggered for task ${input.taskId}`,\n payload: basePayload,\n });\n return;\n case \"process_exit\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_process_exit\",\n text: `provider process exited for task ${input.taskId}`,\n payload: {\n ...basePayload,\n exitCode: input.event.exitCode,\n exitSignal: input.event.signal,\n },\n });\n return;\n case \"provider_conversation_observed\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_conversation_observed\",\n text: `provider conversation observed for task ${input.taskId}`,\n payload: {\n ...basePayload,\n agentControllerConversationId:\n input.event.agentControllerConversationId,\n },\n });\n return;\n case \"provider_turn_accepted\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_turn_accepted\",\n text: `provider turn accepted for task ${input.taskId}`,\n payload: {\n ...basePayload,\n agentControllerConversationId:\n input.event.agentControllerConversationId,\n turnId: input.event.turnId,\n },\n });\n return;\n case \"provider_usage_limits_observed\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_usage_limits_observed\",\n text: `provider usage limits observed for task ${input.taskId}`,\n payload: {\n ...basePayload,\n observedLimitKeys: input.event.usageLimits.map((limit) => limit.key),\n },\n });\n return;\n default:\n return;\n }\n}\n\nexport function emitContinuityWarningIfNeeded(input: {\n continuityObservation: DispatchContinuityObservation | null;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n}): void {\n if (!input.continuityObservation?.shouldWarn) {\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.continuity_warning\",\n text: `implicit conversation rotation detected for task ${input.parsedTask.taskId}; OpenMeld adopted the new context id`,\n payload: {\n agentControllerRef: input.parsedTask.agentControllerRef,\n dispatchId: input.parsedTask.dispatchId,\n existingContextId: input.continuityObservation.existingContextId,\n resolvedContextId: input.continuityObservation.resolvedContextId,\n status: input.continuityObservation.status,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n}\n\nexport function emitRuntimeObservationSummaryLine(input: {\n agentControllerRef: string;\n dispatchId: string;\n presenter: Presenter;\n runtimeResult: RuntimeTaskResult;\n targetProfileId: string;\n taskId: string;\n}): void {\n const telemetry = resolveAdapterTelemetry(input.runtimeResult.dispatchResult);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_result_observed\",\n text: `runtime result observed for task ${input.taskId}`,\n payload: {\n agentControllerRef: input.agentControllerRef,\n dispatchId: input.dispatchId,\n hasTelemetry: telemetry !== null,\n ...(telemetry === null\n ? {}\n : {\n hasExitCode: telemetry.exitCode !== undefined,\n hasFirstOutputAtMs: telemetry.firstOutputAtMs !== undefined,\n hasFirstStderrAtMs: telemetry.firstStderrAtMs !== undefined,\n hasFirstStdoutAtMs: telemetry.firstStdoutAtMs !== undefined,\n hasInvokedAtMs: telemetry.invokedAtMs !== undefined,\n hasProcessId: telemetry.processId !== undefined,\n hasProcessSpawnedAtMs: telemetry.processSpawnedAtMs !== undefined,\n hasStdinClosedAtMs: telemetry.stdinClosedAtMs !== undefined,\n hasStreamingMode: telemetry.streamingMode !== undefined,\n resumedContext: telemetry.resumedContext,\n }),\n resultStatus: input.runtimeResult.resultPayload.status,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n },\n });\n}\n\nexport function summarizeTaskResultPayload(\n payload: OpenMeldDaemonTaskResultPayload\n): LocalExecutionSlotTaskResult {\n if (payload.status === \"failed\") {\n return {\n errorCode: payload.errorCode ?? null,\n errorMessage: payload.errorMessage ?? null,\n result: \"failed\",\n };\n }\n if (payload.status === \"partial_success\") {\n return {\n errorCode: payload.errorCode ?? null,\n errorMessage: payload.errorMessage ?? null,\n result: \"partial_success\",\n };\n }\n return {\n errorCode: null,\n errorMessage: null,\n result: \"success\",\n };\n}\n\nexport function emitDispatchLocalPhaseJournalEvent(input: {\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n metadata?: Record<string, unknown>;\n parsedTask: ParsedDispatchTask | null;\n phase: DispatchLocalJournalPhase;\n result: string;\n}): void {\n const correlation = buildDispatchCorrelation({\n deliverRequest: input.deliverRequest,\n parsedTask: input.parsedTask,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: correlation.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n daemonSessionId: input.deliverRequest.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n metadata: {\n phase: input.phase,\n ...(input.metadata ?? {}),\n },\n profileId: correlation.targetProfileId,\n result: input.result,\n taskId: correlation.taskId,\n type: \"dispatch.local.phase\",\n });\n}\n\nexport function buildResultDispatchJournalMetadata(\n payload: OpenMeldDaemonTaskResultPayload\n): Record<string, unknown> {\n const spaceAction = payload.spaceAction ?? null;\n const outputLength = \"output\" in payload ? payload.output.length : null;\n const errorCode = \"errorCode\" in payload ? (payload.errorCode ?? null) : null;\n const errorType = \"errorType\" in payload ? (payload.errorType ?? null) : null;\n const errorMessage =\n \"errorMessage\" in payload ? (payload.errorMessage ?? null) : null;\n\n return {\n agentId: payload.agentId,\n agentControllerRef: payload.agentControllerRef ?? null,\n errorCode,\n errorMessage,\n errorType,\n outputLength,\n sourceEventId: payload.sourceEventId,\n spaceActionProvenance: payload.spaceActionProvenance ?? null,\n spaceActionType: spaceAction?.type ?? null,\n suppressPublicOutcome: payload.suppressPublicOutcome ?? false,\n ...(spaceAction?.type === \"post_message\"\n ? {\n postMessageTextLength: spaceAction.messageEnvelope.text.length,\n }\n : {}),\n ...(spaceAction?.type === \"post_status\"\n ? {\n postStatus: spaceAction.status,\n postStatusTextLength: spaceAction.text.length,\n }\n : {}),\n ...(spaceAction?.type === \"stay_silent\"\n ? {\n staySilentReasonLength: spaceAction.reason.length,\n }\n : {}),\n };\n}\n","import type { RuntimeTaskResult } from \"@openmeld/local-execution\";\nimport {\n SPACE_ACTION_CONTEXT_GUIDANCE_LINES,\n SPACE_ACTION_TARGET_GUIDANCE_LINES,\n} from \"@openmeld/local-service\";\nimport { openMeldDaemonTaskResultPayloadSchema } from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n OpenMeldDaemonTaskResultPayload,\n} from \"@openmeld/schemas/types\";\nimport {\n resolvePublicAgentFailureReason,\n resolveSpacePublicationRequirement,\n} from \"@openmeld/space-mesh\";\nimport { DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND } from \"../../runtime/dispatch-runtime-env\";\nimport { normalizeOptionalText } from \"../core/logger\";\nimport {\n normalizeOptionalContextId,\n resolveDispatchContextDeltaFromRuntimeResult,\n} from \"./execute-dispatch-conversation\";\nimport type {\n ParsedDispatchTask,\n StructuredActionFailureDiagnostics,\n} from \"./execute-dispatch-types\";\n\nexport function resolveStructuredActionRequirementFailure(input: {\n requiresStructuredSpaceAction: boolean;\n resolution: {\n action: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n parseError: string | null;\n };\n runtimeResult: RuntimeTaskResult;\n}):\n | {\n failureReason: string;\n kind: \"preserve_runtime_failure\";\n }\n | {\n failureReason: string;\n kind: \"repair\";\n }\n | null {\n if (input.resolution.parseError) {\n return {\n failureReason: input.resolution.parseError,\n kind: \"repair\",\n };\n }\n if (!(input.requiresStructuredSpaceAction && !input.resolution.action)) {\n return null;\n }\n\n const payload = input.runtimeResult.resultPayload;\n if (payload.status === \"failed\") {\n return {\n failureReason:\n resolvePublicAgentFailureReason({\n defaultReason: \"The agent could not complete this reply right now.\",\n errorCode: payload.errorCode,\n errorMessage: payload.errorMessage,\n }) ?? \"The agent could not complete this reply right now.\",\n kind: \"preserve_runtime_failure\",\n };\n }\n\n return {\n failureReason:\n \"A valid OpenMeld Space action is required in collaboration mode.\",\n kind: \"repair\",\n };\n}\n\nexport function resolveStructuredActionOutputFallback(input: {\n action: NonNullable<OpenMeldDaemonTaskResultPayload[\"spaceAction\"]>;\n cleanedOutput: string;\n}): string {\n const cleanedOutput = input.cleanedOutput.trim();\n if (cleanedOutput.length > 0) {\n return cleanedOutput;\n }\n\n switch (input.action.type) {\n case \"post_message\":\n return input.action.messageEnvelope.text;\n case \"post_status\":\n return input.action.text.trim() || `status:${input.action.status}`;\n case \"stay_silent\":\n return input.action.reason.trim() || \"stay_silent\";\n default:\n return \"structured-action\";\n }\n}\n\nexport function buildStructuredActionRepairPrompt(input: {\n cliEntry?: string | null;\n currentReplyToSignalId?: string | null;\n parseError: string;\n sendTargetReferenceLines?: readonly string[] | null;\n spaceContractSnapshot?: ParsedDispatchTask[\"spaceContractSnapshot\"];\n spaceId?: string | null;\n previousOutput?: string | null;\n}): string {\n const previousOutput = buildBoundedRepairOutputPreview(input.previousOutput);\n const publicationRequirement = resolveSpacePublicationRequirement(\n input.spaceContractSnapshot\n );\n return [\n `OpenMeld delivery repair: ${input.parseError}`,\n ...(previousOutput\n ? [\"Your previous final answer was:\", \"```text\", previousOutput, \"```\"]\n : []),\n \"Do not redo the user's work or change the intended public outcome.\",\n \"Never publish a shell, CLI, MCP, or transport failure message as the user's normal Space reply.\",\n \"If the previous turn tried an action and that transport failed, retry the same intended action and message through the dispatch-scoped tool.\",\n ...SPACE_ACTION_CONTEXT_GUIDANCE_LINES,\n \"Your answer text never selects an OpenMeld Space action.\",\n \"Call exactly one dispatch-scoped OpenMeld Space Action tool now.\",\n publicationRequirement.repairRequirementLine,\n ...SPACE_ACTION_TARGET_GUIDANCE_LINES,\n ...(normalizeOptionalText(input.currentReplyToSignalId)\n ? [\n `post_message.messageEnvelope.replyToSignalId must match the current dispatch reply target: ${normalizeOptionalText(input.currentReplyToSignalId)}.`,\n ]\n : []),\n ...publicationRequirement.actionGuidanceLines,\n ...buildStructuredActionRepairSendTargetReferenceLines(\n input.sendTargetReferenceLines\n ),\n \"Use the official `openmeld-cli` skill for future OpenMeld work.\",\n ...buildStructuredActionRepairCompletionLines({\n publicationRequirement,\n }),\n ].join(\"\\n\");\n}\n\nfunction buildStructuredActionRepairCompletionLines(input: {\n publicationRequirement: ReturnType<typeof resolveSpacePublicationRequirement>;\n}): string[] {\n return [\n buildStructuredActionRepairPrimaryCommandLine(input),\n \"If neither the tool nor the fallback command can record the action, stop. Do not print JSON or prose as a substitute.\",\n \"Do not finish with an explanation of what you will do.\",\n ];\n}\n\nconst REPAIR_OUTPUT_PREVIEW_MAX_CHARS = 1200;\n\nfunction buildBoundedRepairOutputPreview(value: unknown): string | null {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n return null;\n }\n if (normalized.length <= REPAIR_OUTPUT_PREVIEW_MAX_CHARS) {\n return normalized;\n }\n return `${normalized.slice(0, REPAIR_OUTPUT_PREVIEW_MAX_CHARS).trimEnd()}\\n[truncated; reuse the complete answer already in this conversation]`;\n}\n\nfunction buildStructuredActionRepairPrimaryCommandLine(input: {\n publicationRequirement: ReturnType<typeof resolveSpacePublicationRequirement>;\n}): string {\n if (input.publicationRequirement.allowedActions.includes(\"post_message\")) {\n return `For a normal reply, call the dispatch-scoped OpenMeld Space Action \\`reply\\` tool with the corrected public message. If that tool is unavailable, run the fallback CLI command \\`${DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND} space action reply \"corrected public message\"\\` and wait for it to finish.`;\n }\n if (input.publicationRequirement.allowedActions.includes(\"post_status\")) {\n return `For a final status, call the dispatch-scoped OpenMeld Space Action \\`status\\` tool with a final-safe status and short update. If that tool is unavailable, run the fallback CLI command \\`${DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND} space action status done \"short completion update\"\\` and wait for it to finish.`;\n }\n if (input.publicationRequirement.allowedActions.includes(\"stay_silent\")) {\n return `If no public reply is needed, call the dispatch-scoped OpenMeld Space Action \\`stay_silent\\` tool with your reason. If that tool is unavailable, run the fallback CLI command \\`${DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND} space action silent --reason \"reason\"\\` and wait for it to finish.`;\n }\n return \"No permitted OpenMeld Space action is available. Do not invent one in answer text.\";\n}\n\nfunction buildStructuredActionRepairSendTargetReferenceLines(\n sendTargetReferenceLines: readonly string[] | null | undefined\n): string[] {\n if (!(sendTargetReferenceLines && sendTargetReferenceLines.length > 0)) {\n return [];\n }\n\n return [\n \"Current send target reference:\",\n ...sendTargetReferenceLines.map((line) => line),\n ];\n}\n\nexport function resolveStructuredActionRepairPreviousOutput(\n runtimeResult: RuntimeTaskResult\n): string | null {\n const payload = runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return null;\n }\n return normalizeOptionalText(payload.output);\n}\n\nexport function resolveStructuredActionRepairContinuation(input: {\n runtimeResult: RuntimeTaskResult;\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): {\n contextId: string | null;\n agentControllerConversationOverride: AgentControllerConversationRef | null;\n} {\n const contextDelta = resolveDispatchContextDeltaFromRuntimeResult(\n input.runtimeResult.dispatchResult\n );\n return {\n contextId:\n normalizeOptionalContextId(\n input.runtimeResult.contextResolution?.agentControllerConversationId ??\n contextDelta?.agentControllerConversationId ??\n null\n ) ?? null,\n agentControllerConversationOverride:\n input.runtimeResult.contextResolution?.agentControllerConversation ??\n contextDelta?.agentControllerConversation ??\n input.agentControllerConversationOverride ??\n null,\n };\n}\n\nexport function buildInvalidStructuredActionOutputPreview(\n runtimeResult: RuntimeTaskResult\n): string | null {\n const payload = runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return null;\n }\n const normalizedOutput = normalizeOptionalText(payload.output);\n if (!normalizedOutput) {\n return null;\n }\n if (normalizedOutput.length <= 180) {\n return normalizedOutput;\n }\n return `${normalizedOutput.slice(0, 177).trimEnd()}...`;\n}\n\nexport function coerceRuntimeResultToStructuredActionFailure(input: {\n diagnostics?: StructuredActionFailureDiagnostics | null;\n failureReason: string;\n runtimeResult: RuntimeTaskResult;\n}): OpenMeldDaemonTaskResultPayload {\n const payload = input.runtimeResult.resultPayload;\n const normalizedDiagnostics = input.diagnostics\n ? {\n ...input.diagnostics,\n publicFailureReason:\n input.diagnostics.publicFailureReason ??\n normalizeOptionalText(input.failureReason),\n }\n : null;\n const normalizedPayload = openMeldDaemonTaskResultPayloadSchema.safeParse({\n status: \"failed\",\n attemptId: payload.attemptId,\n taskId: payload.taskId,\n sourceEventId: payload.sourceEventId,\n agentId: payload.agentId,\n deduped: payload.deduped,\n ...(payload.agentControllerRef\n ? { agentControllerRef: payload.agentControllerRef }\n : {}),\n ...(payload.agentControllerConversationId\n ? { agentControllerConversationId: payload.agentControllerConversationId }\n : {}),\n ...(payload.telemetry ? { telemetry: payload.telemetry } : {}),\n ...(payload.agentControllerConversation\n ? { agentControllerConversation: payload.agentControllerConversation }\n : {}),\n ...(payload.bootstrapTemplateFacts\n ? { bootstrapTemplateFacts: payload.bootstrapTemplateFacts }\n : {}),\n ...(payload.dispatchExecution\n ? { dispatchExecution: payload.dispatchExecution }\n : {}),\n ...(normalizedDiagnostics\n ? { spaceActionFailureDiagnostics: normalizedDiagnostics }\n : {}),\n errorCode: \"openmeld.space_action.repair_failed\",\n errorMessage: input.failureReason,\n errorType: \"policy\",\n });\n if (normalizedPayload.success) {\n return normalizedPayload.data;\n }\n\n return {\n status: \"failed\",\n attemptId: payload.attemptId,\n taskId: payload.taskId,\n sourceEventId: payload.sourceEventId,\n agentId: payload.agentId,\n deduped: payload.deduped,\n ...(payload.agentControllerRef\n ? { agentControllerRef: payload.agentControllerRef }\n : {}),\n ...(normalizedDiagnostics\n ? { spaceActionFailureDiagnostics: normalizedDiagnostics }\n : {}),\n errorCode: \"openmeld.space_action.repair_failed\",\n errorMessage: input.failureReason,\n errorType: \"policy\",\n };\n}\n","import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { runtimeTransportForkAgentSessionResultSchema } from \"@openmeld/schemas\";\nimport type {\n RuntimeTransportForkAgentSessionResult,\n RuntimeTransportLocalAgentControlForkSessionFramePayload,\n} from \"@openmeld/schemas/types\";\nimport { z } from \"zod/v4\";\n\nconst STORE_SCHEMA = \"openmeld-agent-session-fork-operation-store-v2\" as const;\nconst LEGACY_STORE_SCHEMA = \"openmeld-agent-session-fork-operation-store-v1\";\nconst RECORD_SCHEMA =\n \"openmeld-agent-session-fork-operation-record-v1\" as const;\nconst STORE_FILE_NAME = \"agent-session-fork-operations.json\";\nconst STORE_TEMP_FILE_NAME = \"agent-session-fork-operations.tmp\";\nconst MAX_RETAINED_RECORDS = 256;\n\ntype ForkRequest =\n RuntimeTransportLocalAgentControlForkSessionFramePayload[\"request\"];\n\nconst contextForkRequestSchema = z.strictObject({\n kind: z.literal(\"execution_context\"),\n operationId: z.string().uuid(),\n sourceNativeSessionId: z.string().min(1),\n completedHistoryId: z.string().min(1),\n workingDirectory: z.string().min(1),\n});\nexport type ContextForkRequest = z.infer<typeof contextForkRequestSchema>;\nexport type ContextForkRequestInput = {\n kind: \"execution_context\";\n operationId: string;\n sourceNativeSessionId: string;\n completedHistoryId?: string;\n workingDirectory: string;\n};\nconst contextForkResultSchema = z.discriminatedUnion(\"status\", [\n contextForkRequestSchema.extend({\n status: z.literal(\"completed\"),\n childNativeSessionId: z.string().min(1),\n }),\n contextForkRequestSchema.extend({\n status: z.enum([\"rejected\", \"outcome_unknown\"]),\n reasonCode: z.string().min(1),\n message: z.string().min(1),\n }),\n]);\ntype ContextForkResult = z.infer<typeof contextForkResultSchema>;\ntype ForkOperationRequest = ForkRequest | ContextForkRequest;\ntype ForkOperationResult =\n | RuntimeTransportForkAgentSessionResult\n | ContextForkResult;\n\ntype StoredOperation = {\n completedHistoryId?: string;\n operationId: string;\n requestFingerprint: string;\n result: ForkOperationResult | null;\n schema: typeof RECORD_SCHEMA;\n sourceNativeSessionId?: string;\n updatedAtMs: number;\n};\n\ntype OperationStore = {\n records: StoredOperation[];\n schema: typeof STORE_SCHEMA;\n updatedAtMs: number;\n v: 2;\n};\n\ntype ReadRecordsResult =\n | { ok: true; records: StoredOperation[] }\n | {\n ok: false;\n reasonCode:\n | \"agent_session_fork.operation_store_invalid\"\n | \"agent_session_fork.operation_store_unavailable\"\n | \"agent_session_fork.operation_store_update_required\";\n };\n\nconst storeTails = new Map<string, Promise<void>>();\n\nexport async function runAgentSessionForkOperation(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ForkRequest;\n}): Promise<RuntimeTransportForkAgentSessionResult>;\nexport async function runAgentSessionForkOperation(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ContextForkRequestInput;\n resolveCompletedHistoryId?: () => Promise<string>;\n}): Promise<ContextForkResult>;\nexport async function runAgentSessionForkOperation(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ForkRequest | ContextForkRequestInput;\n resolveCompletedHistoryId?: () => Promise<string>;\n}): Promise<ForkOperationResult> {\n const previous = storeTails.get(input.ledgerRootPath) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n storeTails.set(input.ledgerRootPath, tail);\n await previous;\n try {\n return await runSerialized(input);\n } finally {\n release();\n if (storeTails.get(input.ledgerRootPath) === tail) {\n storeTails.delete(input.ledgerRootPath);\n }\n }\n}\n\nfunction handleExistingOperation(\n existing: StoredOperation,\n request: ForkRequest | ContextForkRequestInput\n): ForkOperationResult {\n let effectiveRequest: ForkOperationRequest;\n\n if (\"kind\" in request && request.kind === \"execution_context\") {\n const frozenCompletedHistoryId =\n existing.completedHistoryId ??\n (existing.result && \"completedHistoryId\" in existing.result\n ? existing.result.completedHistoryId\n : undefined);\n\n const requestedCompletedHistoryId = request.completedHistoryId;\n\n if (\n requestedCompletedHistoryId &&\n frozenCompletedHistoryId &&\n requestedCompletedHistoryId !== frozenCompletedHistoryId\n ) {\n return rejected(\n { ...request, completedHistoryId: requestedCompletedHistoryId },\n \"agent_session_fork.operation_identity_conflict\",\n \"This Fork operation id was already used for a different Session.\"\n );\n }\n\n effectiveRequest = {\n ...request,\n completedHistoryId:\n requestedCompletedHistoryId ?? frozenCompletedHistoryId ?? \"\",\n };\n } else {\n effectiveRequest = request as ForkRequest;\n }\n\n const fingerprint = stableJson(effectiveRequest);\n if (existing.requestFingerprint !== fingerprint) {\n return rejected(\n effectiveRequest,\n \"agent_session_fork.operation_identity_conflict\",\n \"This Fork operation id was already used for a different Session.\"\n );\n }\n return (\n existing.result ??\n outcomeUnknown(\n effectiveRequest,\n \"The provider Fork started, but no authoritative child Session id was recorded.\"\n )\n );\n}\n\nasync function resolveEffectiveCreationRequest(\n request: ForkRequest | ContextForkRequestInput,\n resolveCompletedHistoryId?: () => Promise<string>\n): Promise<ForkOperationRequest> {\n if (!(\"kind\" in request && request.kind === \"execution_context\")) {\n return request as ForkRequest;\n }\n let completedHistoryId = request.completedHistoryId;\n if (!completedHistoryId && resolveCompletedHistoryId) {\n completedHistoryId = await resolveCompletedHistoryId();\n }\n if (!completedHistoryId) {\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n }\n return {\n ...request,\n completedHistoryId,\n };\n}\n\nasync function runSerialized(input: {\n execute: (input?: {\n completedHistoryId: string;\n }) => Promise<{ childNativeSessionId: string }>;\n ledgerRootPath: string;\n request: ForkRequest | ContextForkRequestInput;\n resolveCompletedHistoryId?: () => Promise<string>;\n}): Promise<ForkOperationResult> {\n const stored = await readRecords(input.ledgerRootPath);\n if (!stored.ok) {\n return rejected(\n input.request as ForkOperationRequest,\n stored.reasonCode,\n stored.reasonCode\n );\n }\n const records = stored.records;\n const existing = records.find(\n (record) => record.operationId === input.request.operationId\n );\n if (existing) {\n return handleExistingOperation(existing, input.request);\n }\n\n const effectiveRequest = await resolveEffectiveCreationRequest(\n input.request,\n input.resolveCompletedHistoryId\n );\n const fingerprint = stableJson(effectiveRequest);\n if (\n records.filter(\n (record) =>\n record.result === null || record.result.status === \"outcome_unknown\"\n ).length >= MAX_RETAINED_RECORDS\n ) {\n return rejected(\n effectiveRequest,\n \"agent_session_fork.unresolved_operation_limit\",\n \"Resolve uncertain fork operations before starting another fork.\"\n );\n }\n const started: StoredOperation = {\n ...(\"completedHistoryId\" in effectiveRequest\n ? { completedHistoryId: effectiveRequest.completedHistoryId }\n : {}),\n ...(\"sourceNativeSessionId\" in effectiveRequest\n ? { sourceNativeSessionId: effectiveRequest.sourceNativeSessionId }\n : {}),\n operationId: effectiveRequest.operationId,\n requestFingerprint: fingerprint,\n result: null,\n schema: RECORD_SCHEMA,\n updatedAtMs: Date.now(),\n };\n try {\n await writeRecords(input.ledgerRootPath, [...records, started]);\n } catch (error) {\n return rejected(\n effectiveRequest,\n \"agent_session_fork.operation_store_unavailable\",\n toErrorMessage(error)\n );\n }\n let result: ForkOperationResult;\n try {\n const forked = await input.execute(\n \"completedHistoryId\" in effectiveRequest\n ? { completedHistoryId: effectiveRequest.completedHistoryId }\n : undefined\n );\n result = parseForkOperationResult({\n ...effectiveRequest,\n childNativeSessionId: forked.childNativeSessionId,\n status: \"completed\",\n });\n } catch (error) {\n const reasonCode = readErrorCode(error);\n result = reasonCode\n ? rejected(effectiveRequest, reasonCode, toErrorMessage(error))\n : outcomeUnknown(effectiveRequest, toErrorMessage(error));\n }\n try {\n await writeRecords(input.ledgerRootPath, [\n ...records,\n { ...started, result, updatedAtMs: Date.now() },\n ]);\n } catch (error) {\n return outcomeUnknown(\n effectiveRequest,\n `The provider Fork finished, but OpenMeld could not record its result: ${toErrorMessage(error)}`\n );\n }\n return result;\n}\n\nasync function readRecords(ledgerRootPath: string): Promise<ReadRecordsResult> {\n const path = join(ledgerRootPath, STORE_FILE_NAME);\n let source: string;\n try {\n source = await readFile(path, \"utf8\");\n } catch (error) {\n if (isNodeError(error, \"ENOENT\")) {\n return { ok: true, records: [] };\n }\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_unavailable\",\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_invalid\",\n };\n }\n if (!(parsed && typeof parsed === \"object\")) {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_invalid\",\n };\n }\n if (\n \"schema\" in parsed &&\n parsed.schema === LEGACY_STORE_SCHEMA &&\n \"v\" in parsed &&\n parsed.v === 1\n ) {\n parsed = { ...parsed, schema: STORE_SCHEMA, v: 2 };\n }\n const candidate = parsed as Partial<OperationStore>;\n if (candidate.schema !== STORE_SCHEMA || candidate.v !== 2) {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_update_required\",\n };\n }\n if (!isOperationStore(parsed)) {\n return {\n ok: false,\n reasonCode: \"agent_session_fork.operation_store_invalid\",\n };\n }\n return { ok: true, records: parsed.records };\n}\n\nasync function writeRecords(\n ledgerRootPath: string,\n records: StoredOperation[]\n): Promise<void> {\n const path = join(ledgerRootPath, STORE_FILE_NAME);\n const tempPath = join(ledgerRootPath, STORE_TEMP_FILE_NAME);\n await mkdir(dirname(path), { mode: 0o700, recursive: true });\n const ordered = [...records].sort(\n (left, right) => right.updatedAtMs - left.updatedAtMs\n );\n const unresolved = ordered.filter(\n (record) =>\n record.result === null || record.result.status === \"outcome_unknown\"\n );\n const retained = [\n ...unresolved,\n ...ordered\n .filter((record) => !unresolved.includes(record))\n .slice(0, Math.max(0, MAX_RETAINED_RECORDS - unresolved.length)),\n ];\n await writeFile(\n tempPath,\n `${JSON.stringify(\n {\n records: retained,\n schema: STORE_SCHEMA,\n updatedAtMs: Date.now(),\n v: 2,\n } satisfies OperationStore,\n null,\n 2\n )}\\n`,\n { encoding: \"utf8\", mode: 0o600 }\n );\n await rename(tempPath, path);\n}\n\nfunction isOperationStore(value: unknown): value is OperationStore {\n if (!(value && typeof value === \"object\")) {\n return false;\n }\n const candidate = value as Partial<OperationStore>;\n return (\n candidate.schema === STORE_SCHEMA &&\n candidate.v === 2 &&\n Array.isArray(candidate.records) &&\n candidate.records.every(isStoredOperation)\n );\n}\n\nfunction isStoredOperation(value: unknown): value is StoredOperation {\n if (!(value && typeof value === \"object\")) {\n return false;\n }\n const candidate = value as Partial<StoredOperation>;\n return (\n candidate.schema === RECORD_SCHEMA &&\n typeof candidate.operationId === \"string\" &&\n typeof candidate.requestFingerprint === \"string\" &&\n typeof candidate.updatedAtMs === \"number\" &&\n (candidate.result === null ||\n runtimeTransportForkAgentSessionResultSchema.safeParse(candidate.result)\n .success ||\n contextForkResultSchema.safeParse(candidate.result).success)\n );\n}\n\nfunction rejected(\n request: ForkOperationRequest,\n reasonCode: string,\n message: string\n): ForkOperationResult {\n return parseForkOperationResult({\n ...request,\n message,\n reasonCode,\n status: \"rejected\",\n });\n}\n\nfunction outcomeUnknown(\n request: ForkOperationRequest,\n message: string\n): ForkOperationResult {\n return parseForkOperationResult({\n ...request,\n message,\n reasonCode: \"agent_session_fork.provider_outcome_unknown\",\n status: \"outcome_unknown\",\n });\n}\n\nfunction readErrorCode(error: unknown): string | null {\n return error && typeof error === \"object\" && \"code\" in error\n ? String(error.code).trim() || null\n : null;\n}\n\nfunction parseForkOperationResult(\n value: Record<string, unknown>\n): ForkOperationResult {\n return value.kind === \"execution_context\"\n ? contextForkResultSchema.parse(value)\n : runtimeTransportForkAgentSessionResultSchema.parse(value);\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error instanceof Error && (error as NodeJS.ErrnoException).code === code\n );\n}\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableJson).join(\",\")}]`;\n }\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n","import { execFile } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n readFile,\n readlink,\n realpath,\n rename,\n rm,\n} from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { listAgentControllerSupervisedProcessIds } from \"@openmeld/adapter-core\";\nimport {\n executionContextAssignmentSchema,\n executionContextTaskSchema,\n} from \"@openmeld/schemas\";\nimport type {\n ComputerFileAccessPolicy,\n ExecutionContextTask,\n} from \"@openmeld/schemas/types\";\nimport { z } from \"zod/v4\";\nimport {\n acquireLock,\n type OpenMeldLock,\n releaseLock,\n runWithHeldLock,\n} from \"../../config/lock\";\nimport { createLedgerIo } from \"../state/ledger-io\";\n\nconst execFileAsync = promisify(execFile);\nconst syncDirectory = createLedgerIo().syncPath;\nconst COMMIT_PATTERN = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;\nconst manifestSchema = z\n .strictObject({\n version: z.union([z.literal(1), z.literal(2)]),\n identity: executionContextAssignmentSchema,\n sourceWorkingDirectory: z.string().nullable(),\n baseCommit: z.string().regex(COMMIT_PATTERN).nullable(),\n boundaryRoot: z.string(),\n workingDirectory: z.string(),\n status: z.enum([\n \"preparing\",\n \"restoring\",\n \"completed\",\n \"in_use\",\n \"retiring\",\n \"released\",\n ]),\n pristineFingerprint: z\n .string()\n .regex(/^[a-f0-9]{64}$/u)\n .optional(),\n copiedUncommittedFiles: z.literal(false),\n processSupervisionId: z.uuid().optional(),\n retirement: z\n .strictObject({\n path: z.string(),\n pristineFingerprint: z.string().regex(/^[a-f0-9]{64}$/u),\n })\n .optional(),\n })\n .refine(\n (manifest) =>\n manifest.version === 2 ||\n ((manifest.status === \"preparing\" || manifest.status === \"completed\") &&\n !manifest.pristineFingerprint &&\n !manifest.processSupervisionId &&\n !manifest.retirement)\n )\n .refine((manifest) =>\n manifest.identity.access === \"space_context\"\n ? manifest.sourceWorkingDirectory === null && manifest.baseCommit === null\n : manifest.sourceWorkingDirectory !== null &&\n isAbsolute(manifest.sourceWorkingDirectory) &&\n manifest.baseCommit !== null &&\n manifest.identity.workspace === \"isolated\"\n );\ntype Manifest = z.infer<typeof manifestSchema>;\nexport type ExecutionContextWorkspace = {\n workingDirectory: string;\n boundaryRoot: string;\n sourceWorkingDirectory?: string;\n baseCommit?: string;\n};\n\nexport async function prepareExecutionContextWorkspace(input: {\n context: ExecutionContextTask;\n ledgerRootPath: string;\n currentWorkingDirectory: string;\n policy: ComputerFileAccessPolicy;\n}): Promise<ExecutionContextWorkspace> {\n const parsed = executionContextTaskSchema.safeParse(input.context);\n if (!parsed.success) {\n throw failure(\"invalid_workspace_context\");\n }\n const { nativeConversationId, runtimeWorkspaceFingerprint } = parsed.data;\n const identity = executionContextAssignmentSchema.strip().parse(parsed.data);\n const isProject = identity.access !== \"space_context\";\n const source = isProject\n ? await canonicalDirectory(input.currentWorkingDirectory)\n : null;\n if (source) {\n assertSourceAllowed(source, input.policy);\n if (identity.workspace === \"current\") {\n return { workingDirectory: source, boundaryRoot: source };\n }\n }\n\n const ledgerRoot = await ensureDirectory(input.ledgerRootPath, true);\n const workspaceRoot = await ensureDirectory(\n join(ledgerRoot, \"execution-context-workspaces\")\n );\n const recordsRoot = await ensureDirectory(\n join(ledgerRoot, \"execution-context-workspace-records\")\n );\n const boundaryRoot = join(workspaceRoot, identity.id);\n const workingDirectory = source\n ? join(boundaryRoot, \"worktree\")\n : boundaryRoot;\n const recordPath = join(recordsRoot, `${identity.id}.json`);\n return await withWorkspaceLock(ledgerRoot, identity.id, async () => {\n const stored = await readManifest(recordPath);\n if (stored) {\n if (\n JSON.stringify(stored.identity) !== JSON.stringify(identity) ||\n stored.sourceWorkingDirectory !== source ||\n stored.boundaryRoot !== boundaryRoot ||\n stored.workingDirectory !== workingDirectory\n ) {\n throw failure(\"workspace_identity_mismatch\");\n }\n await reconcileRetainedWorkspace(\n stored,\n recordPath,\n Boolean(runtimeWorkspaceFingerprint || nativeConversationId),\n ledgerRoot\n );\n return await verifyRetainedWorkspace(stored);\n }\n if (runtimeWorkspaceFingerprint || nativeConversationId) {\n throw failure(\"workspace_record_missing\");\n }\n if (await inspectPath(boundaryRoot)) {\n throw failure(\"workspace_already_exists\");\n }\n const baseCommit = source ? await resolveSourceCommit(source) : null;\n const manifest: Manifest = {\n version: 2,\n identity,\n sourceWorkingDirectory: source,\n baseCommit,\n boundaryRoot,\n workingDirectory,\n status: \"preparing\",\n copiedUncommittedFiles: false,\n processSupervisionId: randomUUID(),\n };\n // Publish the frozen base before Git starts. The process-owned lock prevents\n // a retry from racing a live materialization; retries never replace task data.\n await writeManifest(recordPath, manifest, \"wx\");\n await finishWorkspacePreparation(manifest, recordPath, true);\n return workspaceResult(manifest);\n });\n}\n\nasync function reconcileRetainedWorkspace(\n record: Manifest,\n path: string,\n hasNativeIdentity: boolean,\n ledgerRoot: string\n) {\n if (record.status === \"retiring\") {\n await runWithHeldLock({\n lock: await acquireWorkspaceExecutionLock(ledgerRoot, record.identity.id),\n run: async () => {\n if (\n !record.processSupervisionId ||\n (\n await listAgentControllerSupervisedProcessIds({\n fresh: true,\n processId: null,\n supervisionId: record.processSupervisionId,\n })\n ).length > 0\n ) {\n throw failure(\"workspace_execution_quiescence_unconfirmed\");\n }\n const reconciled = await finishWorkspaceRetirement(record, path);\n if (reconciled.status === \"released\") {\n await restoreReleasedWorkspace(reconciled, path);\n }\n },\n });\n } else if (record.status === \"released\") {\n await restoreReleasedWorkspace(record, path);\n } else if (record.status === \"preparing\" || record.status === \"restoring\") {\n if (record.status === \"preparing\" && hasNativeIdentity) {\n throw failure(\"workspace_creation_incomplete\");\n }\n if (\n !record.processSupervisionId ||\n (\n await listAgentControllerSupervisedProcessIds({\n fresh: true,\n processId: null,\n supervisionId: record.processSupervisionId,\n })\n ).length > 0\n ) {\n throw failure(\"workspace_preparation_quiescence_unconfirmed\");\n }\n await finishWorkspacePreparation(record, path);\n } else if (record.status === \"in_use\") {\n await runWithHeldLock({\n lock: await acquireWorkspaceExecutionLock(ledgerRoot, record.identity.id),\n run: async () => {\n if (\n !record.processSupervisionId ||\n (\n await listAgentControllerSupervisedProcessIds({\n fresh: true,\n processId: null,\n supervisionId: record.processSupervisionId,\n })\n ).length > 0\n ) {\n throw failure(\"workspace_execution_quiescence_unconfirmed\");\n }\n await verifyRetainedWorkspace(record);\n await writeManifest(path, { ...record, status: \"completed\" }, \"r+\");\n },\n });\n }\n}\n\nasync function finishWorkspacePreparation(\n manifest: Manifest,\n recordPath: string,\n pristineCreation = false\n) {\n const {\n boundaryRoot,\n workingDirectory,\n sourceWorkingDirectory: source,\n baseCommit,\n } = manifest;\n await ensureDirectory(boundaryRoot);\n const repository = join(boundaryRoot, \"repository.git\");\n if (source && baseCommit) {\n if (!(await inspectPath(repository))) {\n if ((await readdir(boundaryRoot)).length > 0) {\n throw failure(\"workspace_creation_incomplete\");\n }\n await git(\n boundaryRoot,\n [\n \"init\",\n \"--bare\",\n \"--template=\",\n `--object-format=${baseCommit.length === 64 ? \"sha256\" : \"sha1\"}`,\n repository,\n ],\n manifest.processSupervisionId\n );\n }\n await canonicalDirectory(repository);\n await assertPrivateMetadata(repository);\n if (\n (await readdir(boundaryRoot)).some(\n (name) => name !== \"repository.git\" && name !== \"worktree\"\n )\n ) {\n throw failure(\"workspace_creation_incomplete\");\n }\n if (await inspectPath(join(repository, \"objects\", \"info\", \"alternates\"))) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n // A protocol fetch copies only committed objects, never local files,\n // alternates or hardlinks, and never writes the source worktree registry.\n if (!(await inspectPath(workingDirectory))) {\n await git(\n boundaryRoot,\n [\n `--git-dir=${repository}`,\n \"fetch\",\n \"--no-tags\",\n \"--no-recurse-submodules\",\n \"--depth=1\",\n \"--no-write-fetch-head\",\n source,\n `${baseCommit}:refs/openmeld/base`,\n ],\n manifest.processSupervisionId\n );\n await git(\n boundaryRoot,\n [\n `--git-dir=${repository}`,\n \"worktree\",\n \"add\",\n \"--detach\",\n workingDirectory,\n baseCommit,\n ],\n manifest.processSupervisionId\n );\n }\n await verifyOwnedRepository(manifest);\n await finishMissingCheckoutFiles(manifest);\n // A prepared checkout may have survived an interruption just before the\n // completed record. Reconcile it only if it has no possible task effects.\n if (!(await isUnchangedCheckout(manifest))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n } else if ((await readdir(boundaryRoot)).length > 0) {\n throw failure(\"workspace_creation_incomplete\");\n }\n await writeManifest(\n recordPath,\n {\n ...manifest,\n status: \"completed\",\n pristineFingerprint: pristineCreation\n ? await fingerprintDirectory(boundaryRoot)\n : undefined,\n },\n \"r+\"\n );\n}\n\nexport async function readExecutionContextWorkspace(input: {\n ledgerRootPath: string;\n contextId: string;\n}): Promise<ExecutionContextWorkspace | null> {\n if (\n !executionContextAssignmentSchema.shape.id.safeParse(input.contextId)\n .success\n ) {\n throw failure(\"invalid_workspace_context\");\n }\n if (!(await inspectPath(input.ledgerRootPath))) {\n return null;\n }\n const ledgerRoot = await canonicalDirectory(input.ledgerRootPath);\n const recordsRoot = join(ledgerRoot, \"execution-context-workspace-records\");\n if (!(await inspectPath(recordsRoot))) {\n return null;\n }\n await canonicalDirectory(recordsRoot);\n const manifest = await readManifest(\n join(recordsRoot, `${input.contextId}.json`)\n );\n if (!manifest) {\n return null;\n }\n const workspaceRoot = await canonicalDirectory(\n join(ledgerRoot, \"execution-context-workspaces\")\n );\n const boundaryRoot = join(workspaceRoot, input.contextId);\n const isProject = manifest.identity.access !== \"space_context\";\n const workingDirectory = isProject\n ? join(boundaryRoot, \"worktree\")\n : boundaryRoot;\n if (\n manifest.identity.id !== input.contextId ||\n manifest.boundaryRoot !== boundaryRoot ||\n manifest.workingDirectory !== workingDirectory\n ) {\n throw failure(\"workspace_identity_mismatch\");\n }\n if (manifest.status === \"released\" || manifest.status === \"retiring\") {\n // Fork reads need the frozen path association, not another live checkout.\n return workspaceResult(manifest);\n }\n if (manifest.status === \"preparing\" || manifest.status === \"restoring\") {\n throw failure(\"workspace_creation_incomplete\");\n }\n return await verifyRetainedWorkspace(manifest);\n}\n\nexport type ExecutionContextWorkspaceUse = {\n lock: OpenMeldLock;\n processSupervisionId: string;\n};\n\nexport async function markExecutionContextWorkspaceInUse(input: {\n ledgerRootPath: string;\n context?: ExecutionContextTask;\n}): Promise<ExecutionContextWorkspaceUse | null> {\n const context = input.context;\n if (\n !context ||\n context.workspace !== \"isolated\" ||\n context.access === \"space_context\"\n ) {\n return null;\n }\n const root = await canonicalDirectory(input.ledgerRootPath);\n const lock = await acquireWorkspaceExecutionLock(root, context.id);\n const processSupervisionId = randomUUID();\n try {\n await withWorkspaceLock(root, context.id, async () => {\n await readExecutionContextWorkspace({\n ledgerRootPath: root,\n contextId: context.id,\n });\n const path = join(\n root,\n \"execution-context-workspace-records\",\n `${context.id}.json`\n );\n const record = await readManifest(path);\n if (record?.status !== \"completed\") {\n throw failure(\"workspace_execution_quiescence_unconfirmed\");\n }\n await writeManifest(\n path,\n { ...record, status: \"in_use\", processSupervisionId },\n \"r+\"\n );\n });\n return { lock, processSupervisionId };\n } catch (error) {\n await releaseLock(lock);\n throw error;\n }\n}\n\nexport type ExecutionContextWorkspaceRelease =\n | { status: \"released\" }\n | {\n status: \"retained\";\n reason:\n | \"execution_quiescence_unconfirmed\"\n | \"workspace_changed\"\n | \"baseline_unverified\"\n | \"cleanup_incomplete\"\n | \"source_commit_unavailable\";\n };\n\nexport async function releaseExecutionContextWorkspace(input: {\n ledgerRootPath: string;\n context: ExecutionContextTask;\n ownedProcessesQuiescent: boolean;\n use?: ExecutionContextWorkspaceUse | null;\n}): Promise<ExecutionContextWorkspaceRelease> {\n const root = await canonicalDirectory(input.ledgerRootPath);\n try {\n return await withWorkspaceLock(root, input.context.id, async () => {\n await readExecutionContextWorkspace({\n ledgerRootPath: root,\n contextId: input.context.id,\n });\n const path = join(\n root,\n \"execution-context-workspace-records\",\n `${input.context.id}.json`\n );\n let record = await readManifest(path);\n if (!(record && [\"completed\", \"in_use\"].includes(record.status))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n if (!input.ownedProcessesQuiescent) {\n return {\n status: \"retained\",\n reason: \"execution_quiescence_unconfirmed\",\n };\n }\n const completed: Manifest = { ...record, status: \"completed\" };\n await writeManifest(path, completed, \"r+\");\n record = await removePristineRetirement(completed, path);\n if (record.retirement) {\n return { status: \"retained\", reason: \"cleanup_incomplete\" };\n }\n // Old records have no pre-execution baseline. Never infer one from a task's\n // current files, including apparently clean commits or ignored outputs.\n if (!record.pristineFingerprint) {\n return { status: \"retained\", reason: \"baseline_unverified\" };\n }\n await verifyRetainedWorkspace(record);\n if (\n (await fingerprintDirectory(record.boundaryRoot)) !==\n record.pristineFingerprint\n ) {\n return { status: \"retained\", reason: \"workspace_changed\" };\n }\n if (record.sourceWorkingDirectory && !(await sourceHasCommit(record))) {\n return { status: \"retained\", reason: \"source_commit_unavailable\" };\n }\n const retired = await retirePristineWorkspace(record, path);\n return retired.status === \"released\"\n ? { status: \"released\" }\n : { status: \"retained\", reason: \"workspace_changed\" };\n });\n } finally {\n if (input.use) {\n await releaseLock(input.use.lock);\n }\n }\n}\n\nasync function retirePristineWorkspace(\n record: Manifest,\n recordPath: string\n): Promise<Manifest> {\n if (\n !record.pristineFingerprint ||\n (await fingerprintDirectory(record.boundaryRoot)) !==\n record.pristineFingerprint\n ) {\n throw failure(\"workspace_release_incomplete\");\n }\n const retiring: Manifest = {\n ...record,\n status: \"retiring\",\n retirement: {\n path: `${recordPath}.retired-${randomUUID()}`,\n pristineFingerprint: record.pristineFingerprint,\n },\n };\n await writeManifest(recordPath, retiring, \"r+\");\n return await finishWorkspaceRetirement(retiring, recordPath);\n}\n\nasync function finishWorkspaceRetirement(\n record: Manifest,\n recordPath: string\n): Promise<Manifest> {\n const retirement = record.retirement;\n if (!retirement) {\n throw failure(\"workspace_release_incomplete\");\n }\n const live = await inspectPath(record.boundaryRoot);\n const retired = await inspectPath(retirement.path);\n if ((live && retired) || !(live || retired)) {\n throw failure(\"workspace_release_incomplete\");\n }\n if (live) {\n await moveWorkspace(record.boundaryRoot, retirement.path);\n }\n if (\n (await fingerprintDirectory(retirement.path)) !==\n retirement.pristineFingerprint\n ) {\n // The path fence caught an edit. Restore that exact copy, including its Git\n // metadata, so continuation sees the output rather than a fresh checkout.\n if (await inspectPath(record.boundaryRoot)) {\n throw failure(\"workspace_release_incomplete\");\n }\n await moveWorkspace(retirement.path, record.boundaryRoot);\n const retained: Manifest = {\n ...record,\n retirement: undefined,\n status: \"completed\",\n };\n await writeManifest(recordPath, retained, \"r+\");\n return retained;\n }\n const released: Manifest = { ...record, status: \"released\" };\n await writeManifest(recordPath, released, \"r+\");\n return await removePristineRetirement(released, recordPath);\n}\n\nasync function removePristineRetirement(\n record: Manifest,\n recordPath: string\n): Promise<Manifest> {\n const retirement = record.retirement;\n if (!retirement) {\n return record;\n }\n if (await inspectPath(retirement.path)) {\n if (\n (await fingerprintDirectory(retirement.path)) !==\n retirement.pristineFingerprint\n ) {\n return record;\n }\n await rm(retirement.path, { recursive: true });\n }\n const removed = { ...record, retirement: undefined };\n await writeManifest(recordPath, removed, \"r+\");\n return removed;\n}\n\nasync function restoreReleasedWorkspace(record: Manifest, recordPath: string) {\n if (record.sourceWorkingDirectory && !(await sourceHasCommit(record))) {\n throw failure(\"workspace_base_commit_unavailable\");\n }\n if (await inspectPath(record.boundaryRoot)) {\n throw failure(\"workspace_already_exists\");\n }\n const restoring: Manifest = {\n ...record,\n status: \"restoring\",\n processSupervisionId: randomUUID(),\n };\n await writeManifest(recordPath, restoring, \"r+\");\n await finishWorkspacePreparation(restoring, recordPath, true);\n}\n\nasync function sourceHasCommit(record: Manifest): Promise<boolean> {\n if (!(record.sourceWorkingDirectory && record.baseCommit)) {\n return false;\n }\n try {\n await git(record.sourceWorkingDirectory, [\n \"cat-file\",\n \"-e\",\n `${record.baseCommit}^{commit}`,\n ]);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function isUnchangedCheckout(record: Manifest): Promise<boolean> {\n return (\n (await git(record.workingDirectory, [\"rev-parse\", \"HEAD\"])) ===\n record.baseCommit &&\n (await git(record.workingDirectory, [\n \"status\",\n \"--porcelain\",\n \"--untracked-files=all\",\n \"--ignored\",\n ])) === \"\"\n );\n}\n\nasync function finishMissingCheckoutFiles(record: Manifest) {\n if (\n (await git(record.workingDirectory, [\"rev-parse\", \"HEAD\"])) !==\n record.baseCommit\n ) {\n throw failure(\"workspace_creation_incomplete\");\n }\n const flags = await git(record.workingDirectory, [\"ls-files\", \"-v\", \"-z\"]);\n if (flags.split(\"\\0\").some((entry) => entry && !entry.startsWith(\"H \"))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n const status = await git(record.workingDirectory, [\n \"status\",\n \"--porcelain\",\n \"-z\",\n \"--untracked-files=all\",\n \"--ignored\",\n ]);\n if (!status) {\n return;\n }\n const changes = status.split(\"\\0\").filter(Boolean);\n if (changes.some((entry) => !entry.startsWith(\" D \"))) {\n throw failure(\"workspace_creation_incomplete\");\n }\n // checkout-index without --force writes only absent files. Existing edits,\n // staged changes and extra files were rejected, never overwritten.\n const paths = changes.map((entry) => entry.slice(3));\n for (let offset = 0; offset < paths.length; offset += 100) {\n await git(\n record.workingDirectory,\n [\"checkout-index\", \"--\", ...paths.slice(offset, offset + 100)],\n record.processSupervisionId\n );\n }\n}\n\nasync function fingerprintDirectory(root: string): Promise<string> {\n const hash = createHash(\"sha256\");\n const visit = async (directory: string) => {\n for (const name of (await readdir(directory)).sort()) {\n const path = join(directory, name);\n const info = await lstat(path);\n hash.update(\n JSON.stringify([relative(root, path), info.mode, info.nlink])\n );\n if (info.isSymbolicLink()) {\n hash.update(JSON.stringify(await readlink(path)));\n } else if (info.isDirectory()) {\n await visit(path);\n } else if (info.isFile() && info.nlink === 1) {\n hash.update(String(info.size));\n hash.update(await fingerprintFile(path));\n } else {\n throw failure(\"workspace_git_metadata_changed\");\n }\n }\n };\n await visit(root);\n return hash.digest(\"hex\");\n}\n\nasync function fingerprintFile(path: string) {\n const hash = createHash(\"sha256\");\n const file = await open(path, \"r\");\n try {\n const buffer = Buffer.alloc(64 * 1024);\n for (;;) {\n const { bytesRead } = await file.read(buffer);\n if (!bytesRead) {\n break;\n }\n hash.update(buffer.subarray(0, bytesRead));\n }\n } finally {\n await file.close();\n }\n return hash.digest(\"hex\");\n}\n\nasync function withWorkspaceLock<T>(\n root: string,\n contextId: string,\n run: () => Promise<T>\n): Promise<T> {\n if (!executionContextAssignmentSchema.shape.id.safeParse(contextId).success) {\n throw failure(\"invalid_workspace_context\");\n }\n return await runWithHeldLock({\n lock: await acquireLock({\n openMeldProfileId: \"execution-context-workspaces\",\n key: contextId,\n pathResolution: { env: { OPENMELD_HOME: root } },\n }),\n run,\n });\n}\n\nasync function verifyRetainedWorkspace(\n manifest: Manifest\n): Promise<ExecutionContextWorkspace> {\n await canonicalDirectory(manifest.boundaryRoot);\n await canonicalDirectory(manifest.workingDirectory);\n if (manifest.sourceWorkingDirectory) {\n await verifyOwnedRepository(manifest);\n }\n return workspaceResult(manifest);\n}\n\nasync function acquireWorkspaceExecutionLock(root: string, contextId: string) {\n return await acquireLock({\n openMeldProfileId: \"execution-context-workspaces\",\n key: `${contextId}-execution`,\n pathResolution: { env: { OPENMELD_HOME: root } },\n });\n}\n\nfunction workspaceResult(manifest: Manifest): ExecutionContextWorkspace {\n return {\n workingDirectory: manifest.workingDirectory,\n boundaryRoot: manifest.boundaryRoot,\n ...(manifest.sourceWorkingDirectory\n ? { sourceWorkingDirectory: manifest.sourceWorkingDirectory }\n : {}),\n ...(manifest.baseCommit ? { baseCommit: manifest.baseCommit } : {}),\n };\n}\n\nfunction assertSourceAllowed(\n source: string,\n policy: ComputerFileAccessPolicy\n): void {\n if (\n policy.mode === \"only_selected_folders\" &&\n !policy.folders.some((folder) => within(source, folder))\n ) {\n throw failure(\"workspace_outside_computer_policy\");\n }\n if (\n policy.mode === \"block_selected_folders\" &&\n policy.folders.some(\n (folder) => within(source, folder) || within(folder, source)\n )\n ) {\n throw failure(\"workspace_overlaps_blocked_folder\");\n }\n}\n\nasync function resolveSourceCommit(source: string): Promise<string> {\n // Requiring a marker at the selected root prevents Git's upward discovery\n // from escalating a selected subdirectory into the surrounding repository.\n if (!(await inspectPath(join(source, \".git\")))) {\n throw failure(\"project_repository_required\");\n }\n const topLevel = await git(source, [\"rev-parse\", \"--show-toplevel\"]);\n if ((await realpath(topLevel)) !== source) {\n throw failure(\"project_repository_root_required\");\n }\n const commit = await git(source, [\n \"rev-parse\",\n \"--verify\",\n \"HEAD^{commit}\",\n ]).catch((cause: unknown) => {\n throw new Error(\"execution_context.project_commit_required\", { cause });\n });\n if (!COMMIT_PATTERN.test(commit)) {\n throw failure(\"project_commit_required\");\n }\n return commit;\n}\n\nasync function verifyOwnedRepository(manifest: Manifest): Promise<void> {\n const repository = join(manifest.boundaryRoot, \"repository.git\");\n await canonicalDirectory(repository);\n await assertPrivateMetadata(repository);\n if (await inspectPath(join(repository, \"objects\", \"info\", \"alternates\"))) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n const gitFile = join(manifest.workingDirectory, \".git\");\n const gitFileInfo = await inspectPath(gitFile);\n if (!gitFileInfo?.isFile() || gitFileInfo.size > 4096) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n const expectedGitDir = join(repository, \"worktrees\", \"worktree\");\n if (\n (await readFile(gitFile, \"utf8\")).trim() !== `gitdir: ${expectedGitDir}`\n ) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n if (\n (await realpath(\n join(\n expectedGitDir,\n (await readFile(join(expectedGitDir, \"commondir\"), \"utf8\")).trim()\n )\n )) !== repository\n ) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n const base = await git(manifest.boundaryRoot, [\n `--git-dir=${repository}`,\n \"rev-parse\",\n \"--verify\",\n \"refs/openmeld/base^{commit}\",\n ]);\n if (base !== manifest.baseCommit) {\n throw failure(\"workspace_base_commit_changed\");\n }\n}\n\nasync function assertPrivateMetadata(path: string): Promise<void> {\n for (const entry of await readdir(path, { withFileTypes: true })) {\n if (entry.isSymbolicLink()) {\n throw failure(\"workspace_is_symlink\");\n }\n if (entry.isDirectory()) {\n await assertPrivateMetadata(join(path, entry.name));\n } else if ((await lstat(join(path, entry.name))).nlink !== 1) {\n throw failure(\"workspace_git_metadata_changed\");\n }\n }\n}\n\nasync function readManifest(path: string): Promise<Manifest | null> {\n const info = await inspectPath(path);\n if (!info) {\n return null;\n }\n if (!info.isFile() || info.size > 32_768) {\n throw failure(\"workspace_record_invalid\");\n }\n let content: unknown;\n try {\n content = JSON.parse(await readFile(path, \"utf8\"));\n } catch {\n throw failure(\"workspace_record_invalid\");\n }\n const parsed = manifestSchema.safeParse(content);\n if (!parsed.success) {\n throw failure(\"workspace_record_invalid\");\n }\n const retirement = parsed.data.retirement;\n const prefix = `${path}.retired-`;\n if (\n (parsed.data.status === \"retiring\" && !retirement) ||\n (retirement &&\n !(\n retirement.path.startsWith(prefix) &&\n z.uuid().safeParse(retirement.path.slice(prefix.length)).success\n ))\n ) {\n throw failure(\"workspace_record_invalid\");\n }\n return parsed.data;\n}\n\nasync function writeManifest(\n path: string,\n manifest: Manifest,\n flags: \"wx\" | \"r+\"\n): Promise<void> {\n const temporaryPath = flags === \"wx\" ? path : `${path}.${randomUUID()}.tmp`;\n const file = await open(temporaryPath, \"wx\", 0o600);\n try {\n await file.writeFile(\n `${JSON.stringify({ ...manifest, version: 2 })}\\n`,\n \"utf8\"\n );\n await file.sync();\n } finally {\n await file.close();\n }\n if (flags !== \"wx\") {\n await rename(temporaryPath, path);\n }\n await syncDirectory(dirname(path));\n}\n\nasync function moveWorkspace(from: string, to: string) {\n await rename(from, to);\n await syncDirectory(dirname(from));\n await syncDirectory(dirname(to));\n}\n\nasync function inspectPath(path: string) {\n const info = await lstat(path).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n });\n if (info?.isSymbolicLink()) {\n throw failure(\"workspace_is_symlink\");\n }\n return info;\n}\n\nasync function canonicalDirectory(path: string): Promise<string> {\n if (!(await inspectPath(path))?.isDirectory()) {\n throw failure(\"workspace_directory_unavailable\");\n }\n return await realpath(path);\n}\n\nasync function ensureDirectory(\n path: string,\n recursive = false\n): Promise<string> {\n await inspectPath(path);\n await mkdir(path, { recursive, mode: 0o700 }).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"EEXIST\") {\n throw error;\n }\n }\n );\n return await canonicalDirectory(path);\n}\n\nfunction within(child: string, parent: string): boolean {\n const path = relative(resolve(parent), child);\n return (\n path === \"\" ||\n (path !== \"..\" && !path.startsWith(`..${sep}`) && !isAbsolute(path))\n );\n}\n\nconst GIT_SETTINGS = {\n \"core.hooksPath\": \"/dev/null\",\n \"core.attributesFile\": \"/dev/null\",\n \"core.fsmonitor\": \"false\",\n \"credential.helper\": \"\",\n \"protocol.allow\": \"never\",\n \"protocol.file.allow\": \"always\",\n \"fetch.recurseSubmodules\": \"false\",\n \"submodule.recurse\": \"false\",\n \"uploadpack.packObjectsHook\": \"\",\n \"gc.auto\": \"0\",\n \"maintenance.auto\": \"false\",\n};\n\nasync function git(\n cwd: string,\n args: string[],\n processSupervisionId?: string\n): Promise<string> {\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !key.startsWith(\"GIT_\"))\n );\n Object.assign(env, {\n ...(processSupervisionId\n ? { OPENMELD_PROCESS_SUPERVISION_ID: processSupervisionId }\n : {}),\n GIT_CONFIG_NOSYSTEM: \"1\",\n GIT_CONFIG_SYSTEM: \"/dev/null\",\n GIT_CONFIG_GLOBAL: \"/dev/null\",\n GIT_ATTR_NOSYSTEM: \"1\",\n GIT_NO_REPLACE_OBJECTS: \"1\",\n GIT_NO_LAZY_FETCH: \"1\",\n GIT_ALLOW_PROTOCOL: \"file\",\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_CONFIG_COUNT: String(Object.keys(GIT_SETTINGS).length),\n });\n for (const [index, [key, value]] of Object.entries(GIT_SETTINGS).entries()) {\n env[`GIT_CONFIG_KEY_${index}`] = key;\n env[`GIT_CONFIG_VALUE_${index}`] = value;\n }\n const result = await execFileAsync(\"git\", args, {\n cwd,\n env,\n encoding: \"utf8\",\n timeout: 30_000,\n maxBuffer: 1024 * 1024,\n });\n return result.stdout.trimEnd();\n}\n\nfunction failure(code: string): Error {\n return new Error(`execution_context.${code}`);\n}\n","import { lstat, mkdir, realpath } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n forkSession,\n getSessionInfo,\n getSessionMessages,\n} from \"@anthropic-ai/claude-agent-sdk\";\nimport {\n forkCodexAppServerThread,\n resolveCodexAppServerCompletedTurn,\n} from \"@openmeld/adapter-codex\";\nimport type {\n AdapterComputerFileAccessBoundary,\n AdapterRuntimeEventCallback,\n RuntimeAgentControllerLaunchContract,\n} from \"@openmeld/adapter-core\";\nimport { buildRuntimeWorkspaceFingerprint } from \"@openmeld/local-execution\";\nimport type {\n ComputerFileAccessPolicy,\n ExecutionContextCompletion,\n ExecutionContextTask,\n} from \"@openmeld/schemas/types\";\nimport { isSameOrDescendantPath } from \"../../lib/path-containment\";\nimport { runAgentSessionForkOperation } from \"../session-control/session-fork-operation-store\";\nimport {\n type ExecutionContextWorkspace,\n readExecutionContextWorkspace,\n} from \"./execution-context-workspace\";\n\nexport function executionContextLedgerPolicy(context?: ExecutionContextTask) {\n return context ? (\"throw\" as const) : (\"backup_and_reset\" as const);\n}\n\nexport function executionContextResourceScope(context?: ExecutionContextTask) {\n if (!context) {\n return undefined;\n }\n if (context.access === \"space_context\") {\n return \"none\" as const;\n }\n if (context.workspace === \"isolated\") {\n return context.access === \"workspace\"\n ? (\"isolated\" as const)\n : (\"isolated_read\" as const);\n }\n return context.access === \"workspace\"\n ? (\"exclusive\" as const)\n : (\"read_only\" as const);\n}\n\nexport function executionContextFileAccessBoundary(input: {\n context: ExecutionContextTask;\n workingDirectory: string;\n policy: ComputerFileAccessPolicy;\n taskWorkspace?: ExecutionContextWorkspace;\n workingCopyId?: string;\n}): AdapterComputerFileAccessBoundary {\n const within = isSameOrDescendantPath;\n const policy = input.policy;\n // Space-only work has no user-folder source. The native boundary still names\n // only its Service-owned scratch root, regardless of the user's folder policy.\n if (input.context.access !== \"space_context\") {\n const policySource =\n input.taskWorkspace?.sourceWorkingDirectory ?? input.workingDirectory;\n if (\n policy.mode === \"only_selected_folders\" &&\n !policy.folders.some((folder) => within(policySource, folder))\n ) {\n throw new Error(\"execution_context.workspace_outside_computer_policy\");\n }\n if (\n policy.mode === \"block_selected_folders\" &&\n policy.folders.some(\n (folder) => within(policySource, folder) || within(folder, policySource)\n )\n ) {\n throw new Error(\"execution_context.workspace_overlaps_blocked_folder\");\n }\n }\n return {\n mode: \"only_selected_folders\",\n folders: [\n input.context.access === \"space_context\" && input.workingCopyId\n ? input.workingDirectory\n : (input.taskWorkspace?.boundaryRoot ?? input.workingDirectory),\n ],\n revision: policy.revision,\n updatedAtMs: policy.updatedAtMs,\n executionContextAccess: input.context.access,\n ...(input.context.access === \"space_context\" && input.workingCopyId\n ? { workingCopyId: input.workingCopyId }\n : {}),\n };\n}\n\nexport async function executionContextWorkingDirectory(input: {\n context?: Pick<ExecutionContextTask, \"id\" | \"workspace\">;\n ledgerRootPath: string;\n currentWorkingDirectory: string;\n}): Promise<string> {\n if (!input.context) {\n return input.currentWorkingDirectory;\n }\n if (input.context.workspace === \"current\") {\n return await realpath(input.currentWorkingDirectory);\n }\n await mkdir(input.ledgerRootPath, { recursive: true, mode: 0o700 });\n const root = join(\n await realpath(input.ledgerRootPath),\n \"execution-context-workspaces\"\n );\n await mkdir(root, { recursive: true, mode: 0o700 });\n if ((await lstat(root)).isSymbolicLink()) {\n throw new Error(\"execution_context.workspace_is_symlink\");\n }\n const path = join(root, input.context.id);\n await mkdir(path, { recursive: true, mode: 0o700 });\n if ((await lstat(path)).isSymbolicLink()) {\n throw new Error(\"execution_context.workspace_is_symlink\");\n }\n return await realpath(path);\n}\n\nexport async function prepareExecutionContextConversation(input: {\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n context?: ExecutionContextTask;\n unscopedNativeConversationId: string | null;\n currentWorkingDirectory: string;\n workingDirectory: string;\n existingNativeConversationId: string | null;\n ledgerRootPath: string;\n agentControllerRef: string;\n launchContract?: RuntimeAgentControllerLaunchContract | null;\n onRuntimeEvent?: AdapterRuntimeEventCallback;\n processSupervisionId?: string;\n}): Promise<string | null> {\n if (!input.context) {\n return input.unscopedNativeConversationId;\n }\n const nativeId = input.context.nativeConversationId;\n if (\n input.context.runtimeWorkspaceFingerprint &&\n input.context.runtimeWorkspaceFingerprint !==\n buildRuntimeWorkspaceFingerprint(input.workingDirectory)\n ) {\n throw new Error(\"execution_context.workspace_changed\");\n }\n if (\n nativeId &&\n input.existingNativeConversationId &&\n nativeId !== input.existingNativeConversationId\n ) {\n throw new Error(\"execution_context.native_identity_mismatch\");\n }\n if (nativeId || input.existingNativeConversationId) {\n return nativeId ?? input.existingNativeConversationId;\n }\n const source = input.context.forkSource;\n if (!source) {\n return null;\n }\n const sourceWorkspace =\n source.workspace === \"isolated\"\n ? await readExecutionContextWorkspace({\n ledgerRootPath: input.ledgerRootPath,\n contextId: source.contextId,\n })\n : null;\n const sourceDirectory =\n sourceWorkspace?.workingDirectory ??\n (await realpath(\n source.workspace === \"current\"\n ? input.currentWorkingDirectory\n : (sourceWorkspace?.workingDirectory ??\n join(\n input.ledgerRootPath,\n \"execution-context-workspaces\",\n source.contextId\n ))\n ));\n if (\n buildRuntimeWorkspaceFingerprint(sourceDirectory) !==\n source.runtimeWorkspaceFingerprint\n ) {\n throw new Error(\"execution_context.fork_source_workspace_changed\");\n }\n // A frozen checkpoint is authoritative when Core assigned one. Otherwise the\n // boundary is resolved under the fork journal lock: the source may be a\n // thread OpenMeld never finished a turn on, and reading its settled turns\n // names a cutoff that is verified now rather than assumed. That read takes no\n // writer lock, so it works while another App Server holds the thread. The\n // journal records the exact boundary it forked at, so a lost response\n // or subsequent replay restores that recorded cutoff instead of re-reading\n // an advanced source history.\n const result = await runAgentSessionForkOperation({\n ledgerRootPath: input.ledgerRootPath,\n request: {\n kind: \"execution_context\",\n operationId: input.context.id,\n sourceNativeSessionId: source.nativeConversationId,\n ...(source.completedHistoryId\n ? { completedHistoryId: source.completedHistoryId }\n : {}),\n workingDirectory: input.workingDirectory,\n },\n resolveCompletedHistoryId: async () => {\n if (\n input.agentControllerRef === \"builtin:codex\" &&\n input.launchContract\n ) {\n const completed = await resolveCodexAppServerCompletedTurn({\n codexTimeoutMs: 30_000,\n codexWorkdir: sourceDirectory,\n launchContract: input.launchContract,\n threadId: source.nativeConversationId,\n });\n return completed.completedTurnId;\n }\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n },\n execute: async (forkInput) => {\n const completedHistoryId = forkInput?.completedHistoryId;\n if (!completedHistoryId) {\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n }\n if (input.agentControllerRef === \"builtin:claude-code\") {\n const messages = await readBoundedClaudeHistory(\n source.nativeConversationId\n );\n const boundary = messages.find(\n (message) =>\n message.uuid === completedHistoryId &&\n isCompletedAssistantMessage(message)\n );\n if (!boundary) {\n throw new Error(\"execution_context.fork_checkpoint_unavailable\");\n }\n const child = await forkSession(source.nativeConversationId, {\n upToMessageId: completedHistoryId,\n });\n return { childNativeSessionId: child.sessionId };\n }\n if (\n input.agentControllerRef === \"builtin:codex\" &&\n input.launchContract\n ) {\n const child = await forkCodexAppServerThread({\n computerFileAccessBoundary:\n input.computerFileAccessBoundary ?? undefined,\n codexTimeoutMs: 30_000,\n codexWorkdir: sourceDirectory,\n launchContract: input.launchContract,\n sourceThreadId: source.nativeConversationId,\n sourceCompletedTurnId: completedHistoryId,\n targetWorkingDirectory: input.workingDirectory,\n onRuntimeEvent: input.onRuntimeEvent,\n env: { OPENMELD_PROCESS_SUPERVISION_ID: input.processSupervisionId },\n });\n return { childNativeSessionId: child.threadId };\n }\n throw new Error(\"execution_context.fork_unsupported\");\n },\n });\n if (result.status !== \"completed\") {\n throw new Error(`${result.reasonCode}: ${result.message}`);\n }\n return result.childNativeSessionId;\n}\n\nexport async function captureExecutionContextCompletion(input: {\n context?: ExecutionContextTask;\n nativeConversationId: string | null;\n agentControllerRef: string;\n workingDirectory: string;\n completedTurnId: string | null;\n providerSucceeded: boolean;\n}): Promise<ExecutionContextCompletion | undefined> {\n if (!(input.context && input.nativeConversationId)) {\n return undefined;\n }\n const completion: ExecutionContextCompletion = {\n contextId: input.context.id,\n nativeConversationId: input.nativeConversationId,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n input.workingDirectory\n ),\n };\n if (!input.providerSucceeded) {\n return completion;\n }\n if (input.agentControllerRef === \"builtin:codex\") {\n return {\n ...completion,\n ...(input.completedTurnId\n ? { completedHistoryId: input.completedTurnId }\n : {}),\n };\n }\n if (input.agentControllerRef === \"builtin:claude-code\") {\n try {\n const messages = await readBoundedClaudeHistory(\n input.nativeConversationId\n );\n const completed = messages.findLast(isCompletedAssistantMessage);\n if (completed) {\n return { ...completion, completedHistoryId: completed.uuid };\n }\n } catch {\n // Native completion remains known; no unverified fork boundary is emitted.\n console.warn(\"[execution_context.checkpoint_unavailable]\", {\n contextId: input.context.id,\n });\n }\n }\n return completion;\n}\n\nasync function readBoundedClaudeHistory(sessionId: string) {\n // A fork may execute in a different folder from its native history file.\n // The SDK resolves this exact authorized ID; the Service does not scan sessions.\n const info = await getSessionInfo(sessionId);\n if (!info || info.fileSize === undefined || info.fileSize > 8 * 1024 * 1024) {\n throw new Error(\"execution_context.history_unavailable_or_too_large\");\n }\n return await getSessionMessages(sessionId);\n}\n\nfunction isCompletedAssistantMessage(\n value: Awaited<ReturnType<typeof getSessionMessages>>[number]\n): boolean {\n return (\n value.type === \"assistant\" &&\n typeof value.message === \"object\" &&\n value.message !== null &&\n \"stop_reason\" in value.message &&\n value.message.stop_reason === \"end_turn\"\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS } from \"@openmeld/schemas\";\nimport type { OpenMeldDaemonTaskResultPayload } from \"@openmeld/schemas/types\";\n\ntype DispatchPromptTrace = NonNullable<\n OpenMeldDaemonTaskResultPayload[\"promptTrace\"]\n>;\n\nconst OMITTED_ORGANIZATION_POLICY =\n \"[organization-protected information policy omitted]\";\n\nexport function buildDispatchPromptTrace(input: {\n prompt: string;\n protectedInformation?: string | null;\n}): DispatchPromptTrace | null {\n if (input.prompt.trim().length === 0) {\n return null;\n }\n const protectedInformation = input.protectedInformation?.trim();\n const traceSafePrompt = protectedInformation\n ? input.prompt.replaceAll(protectedInformation, OMITTED_ORGANIZATION_POLICY)\n : input.prompt;\n return {\n fingerprint: `sha256:${createHash(\"sha256\")\n .update(input.prompt)\n .digest(\"hex\")}`,\n length: input.prompt.length,\n preview:\n traceSafePrompt.length <= SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS\n ? traceSafePrompt\n : `${traceSafePrompt\n .slice(0, SPACE_DISPATCH_TRACE_PROMPT_PREVIEW_MAX_CHARS - 3)\n .trimEnd()}...`,\n };\n}\n","import type {\n AdapterReasoningEvent,\n AdapterRuntimeEvent,\n AdapterRuntimeEventCallback,\n} from \"@openmeld/adapter-core\";\nimport { LOCAL_AGENT_REASONING_MAX_CHARS } from \"@openmeld/schemas\";\n\n/** Keep private live content outside all lifecycle and journaling observers. */\nexport function routeReasoningEvents(\n reasoning: (event: AdapterReasoningEvent) => void,\n lifecycle: (\n event: Exclude<AdapterRuntimeEvent, AdapterReasoningEvent>\n ) => void\n): AdapterRuntimeEventCallback {\n return (event) => {\n if (event.phase === \"reasoning\") {\n reasoning(event);\n } else {\n lifecycle(event);\n }\n };\n}\n\n/** A disposable live tail, deliberately independent of the result journal. */\nexport function createReasoningStream(input: {\n enabled: () => boolean;\n send: (snapshot: string, observedAtMs: number) => void;\n}) {\n const blocks = new Map<string, string>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lastSentAt = Number.NEGATIVE_INFINITY;\n let observedAtMs = 0;\n let dirty = false;\n let disposed = false;\n const clear = () => {\n if (timer) {\n clearTimeout(timer);\n }\n timer = undefined;\n blocks.clear();\n dirty = false;\n };\n const flush = () => {\n if (timer) {\n clearTimeout(timer);\n }\n timer = undefined;\n if (disposed || !input.enabled()) {\n clear();\n return;\n }\n if (!dirty) {\n return;\n }\n dirty = false;\n lastSentAt = Date.now();\n input.send(\n [...blocks.values()].join(\"\\n\\n\").slice(-LOCAL_AGENT_REASONING_MAX_CHARS),\n observedAtMs\n );\n };\n return {\n clear,\n observe(event: AdapterReasoningEvent) {\n if (disposed || !input.enabled()) {\n clear();\n return;\n }\n if (!event.text) {\n return;\n }\n const previous = blocks.get(event.blockId) ?? \"\";\n const next = (\n event.mode === \"snapshot\" ? event.text : previous + event.text\n ).slice(-LOCAL_AGENT_REASONING_MAX_CHARS);\n if (next === previous) {\n return;\n }\n blocks.set(event.blockId, next);\n while (blocks.size > 8) {\n const oldest = blocks.keys().next().value;\n if (oldest !== undefined) {\n blocks.delete(oldest);\n }\n }\n dirty = true;\n observedAtMs = event.tsMs;\n const delay = Math.max(0, 100 - (Date.now() - lastSentAt));\n if (delay === 0) {\n flush();\n } else {\n timer ??= setTimeout(flush, delay);\n }\n },\n dispose() {\n disposed = true;\n clear();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport type { DispatchSendTargetProjectionEntry } from \"@openmeld/local-service\";\nimport type {\n OpenMeldRequestContext,\n SpaceMemberDirectory,\n} from \"@openmeld/schemas/types\";\nimport {\n createDispatchContinuationSpaceAccessContext,\n getSpaceAccessPassword,\n getSpaceAccessRequestContext,\n listSpaceMemberDirectorySendTargets,\n type SpaceMemberDirectorySendTargetEntry,\n} from \"@openmeld/space\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../../config/openmeld-request-context\";\nimport { createCliSpaceApi, type SpaceApi } from \"../../space/cli-space-api\";\n\nconst SEND_TARGET_REFERENCE_DIRECTORY_CACHE_TTL_MS = 20_000;\n\ntype CachedMemberDirectory = {\n directory: SpaceMemberDirectory;\n expiresAtMs: number;\n};\n\nconst memberDirectoryCache = new Map<string, CachedMemberDirectory>();\nconst inFlightMemberDirectoryLoads = new Map<\n string,\n Promise<SpaceMemberDirectory>\n>();\n\nexport type DispatchSendTargetReferenceLoadResult =\n | {\n status: \"loaded\";\n projection: SpaceMemberDirectorySendTargetEntry[];\n referenceLines: string[];\n }\n | {\n status: \"failed\";\n errorMessage: string;\n projection: null;\n referenceLines: [];\n };\n\nexport async function resolveDispatchSendTargetReference(input: {\n agentControllerRef: string;\n dispatchTask: {\n attemptId: string;\n dispatchId: string;\n sourceEventId: string;\n spaceId: string;\n spacePassword: string | null;\n targetProfileId: string;\n };\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n targetProfileName: string | null;\n}): Promise<DispatchSendTargetReferenceLoadResult> {\n try {\n const baseUrl = await resolveBaseUrl();\n const spaceApi = createCliSpaceApi(baseUrl);\n const requestContext = buildDispatchSendTargetRequestContext({\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n targetProfileId: input.dispatchTask.targetProfileId,\n targetProfileName: input.targetProfileName,\n });\n const spaceAccess = createDispatchContinuationSpaceAccessContext({\n attemptId: input.dispatchTask.attemptId,\n dispatchId: input.dispatchTask.dispatchId,\n password: input.dispatchTask.spacePassword,\n requestContext,\n sourceSignalId: input.dispatchTask.sourceEventId,\n spaceId: input.dispatchTask.spaceId,\n targetProfileId: input.dispatchTask.targetProfileId,\n });\n const accessRequestContext = getSpaceAccessRequestContext(spaceAccess);\n const spacePassword = getSpaceAccessPassword(spaceAccess) ?? null;\n const directory = await loadDispatchSendTargetMemberDirectory({\n baseUrl,\n profileOwnerUserId: input.profileOwnerUserId,\n requestContext: accessRequestContext ?? requestContext,\n spaceApi,\n spaceId: spaceAccess.spaceId,\n spacePassword,\n });\n const projection = listSpaceMemberDirectorySendTargets(directory).sort(\n (left, right) =>\n left.primaryMentionLabel.localeCompare(\n right.primaryMentionLabel,\n \"en\",\n {\n sensitivity: \"base\",\n }\n )\n );\n\n return {\n status: \"loaded\",\n projection,\n referenceLines: projection\n .filter(\n (target) => target.profileId !== input.dispatchTask.targetProfileId\n )\n .map((target) => formatDispatchSendTargetReferenceLine(target)),\n };\n } catch (error) {\n return {\n status: \"failed\",\n errorMessage:\n error instanceof Error\n ? error.message\n : \"Failed to load current Space member directory\",\n projection: null,\n referenceLines: [],\n };\n }\n}\n\nfunction loadDispatchSendTargetMemberDirectory(input: {\n baseUrl: string;\n profileOwnerUserId: string;\n requestContext: OpenMeldRequestContext;\n spaceApi: SpaceApi;\n spaceId: string;\n spacePassword: string | null;\n}): Promise<SpaceMemberDirectory> {\n const cacheKey = buildMemberDirectoryCacheKey(input);\n const nowMs = Date.now();\n const cached = memberDirectoryCache.get(cacheKey);\n if (cached && cached.expiresAtMs > nowMs) {\n return Promise.resolve(cached.directory);\n }\n if (cached) {\n memberDirectoryCache.delete(cacheKey);\n }\n\n const inFlight = inFlightMemberDirectoryLoads.get(cacheKey);\n if (inFlight) {\n return inFlight;\n }\n\n const loadPromise = input.spaceApi\n .getMemberDirectory({\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n ...(input.spacePassword ? { spacePassword: input.spacePassword } : {}),\n })\n .then((directory) => {\n memberDirectoryCache.set(cacheKey, {\n directory,\n expiresAtMs: Date.now() + SEND_TARGET_REFERENCE_DIRECTORY_CACHE_TTL_MS,\n });\n return directory;\n })\n .finally(() => {\n inFlightMemberDirectoryLoads.delete(cacheKey);\n });\n\n inFlightMemberDirectoryLoads.set(cacheKey, loadPromise);\n return loadPromise;\n}\n\nfunction buildMemberDirectoryCacheKey(input: {\n baseUrl: string;\n profileOwnerUserId: string;\n spaceId: string;\n spacePassword: string | null;\n}): string {\n return [\n `base:${input.baseUrl}`,\n `space:${input.spaceId}`,\n `owner:${input.profileOwnerUserId}`,\n `password:${hashCacheSecret(input.spacePassword)}`,\n ].join(\"|\");\n}\n\nfunction hashCacheSecret(value: string | null): string {\n if (!value) {\n return \"none\";\n }\n return createHash(\"sha256\").update(value).digest(\"base64url\");\n}\n\nexport function clearDispatchSendTargetReferenceCacheForTests(): void {\n memberDirectoryCache.clear();\n inFlightMemberDirectoryLoads.clear();\n}\n\nfunction buildDispatchSendTargetRequestContext(input: {\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n targetProfileId: string;\n targetProfileName: string | null;\n}): OpenMeldRequestContext {\n return buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n openMeldProfileId: input.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.profileOwnerUserId,\n ...(input.profileOwnerName ? { ownerName: input.profileOwnerName } : {}),\n profileName: normalizeTargetProfileName(input.targetProfileName),\n },\n });\n}\n\nfunction formatDispatchSendTargetReferenceLine(\n target: DispatchSendTargetProjectionEntry\n): string {\n return `${target.primaryMentionLabel} -> ${target.profileId} (${formatAllowedRelations(target)})`;\n}\n\nfunction formatAllowedRelations(\n target: DispatchSendTargetProjectionEntry\n): string {\n const relations: string[] = [];\n if (target.allowedRelations.wake) {\n relations.push(\"wake\");\n }\n if (target.allowedRelations.reference) {\n relations.push(\"reference\");\n }\n if (target.allowedRelations.mention) {\n relations.push(\"mention\");\n }\n return relations.join(\" | \");\n}\n\nfunction normalizeTargetProfileName(value: string | null): string {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : \"unknown\";\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type {\n AdapterComputerFileAccessBoundary,\n AdapterDispatchContextDelta,\n AdapterDispatchExecutionMode,\n AdapterInstructionPrompt,\n AdapterInteractionCallback,\n AdapterInteractionRequest,\n AdapterRuntimeEvent,\n AdapterToolActivityEvent,\n} from \"@openmeld/adapter-core\";\nimport type { RuntimeTaskResult } from \"@openmeld/local-execution\";\nimport {\n appendLedgerHistoryEntry,\n assertLegacyAgentContextAssociation,\n buildAgentContextLookupKey,\n buildRuntimeWorkspaceFingerprint,\n commitResolvedAgentContext,\n DEFAULT_TASK_LIFECYCLE_HEARTBEAT_INTERVAL_MS,\n loadLedgerState,\n resolveConversationExecutionStateByLookupKey,\n runRuntimeTask,\n seedLegacyAgentContext,\n settleInflightTask,\n withLedgerStateTransaction,\n} from \"@openmeld/local-execution\";\nimport {\n createSerialAgentInteractionCallback,\n type DispatchContinuityObservation,\n type InflightTaskControlRegistry,\n type LocalDaemonAdapterContainer,\n type LocalExecutionSlotDiagnostics,\n type LocalExecutionSlots,\n type LocalExecutionSlotTaskResult,\n mergeOpenClawGatewayVisibility as mergeOpenClawGatewayVisibilityInternal,\n normalizeDispatchPostMessageAction,\n normalizeDispatchThreadAction,\n type OpenClawGatewayVisibility,\n type PendingAgentInteractionRegistry,\n resolveCompatibleAgentContextMatch,\n resolveCompatibleConversationExecutionState,\n resolveDispatchContinuityObservation,\n resolveDispatchQueueLogMeta,\n resolveLatestScopedConversationExecutionState,\n syncRuntimeEventToInflightTaskControlRegistry,\n} from \"@openmeld/local-service\";\nimport {\n AGENT_INTERACTION_DEFAULT_TIMEOUT_MS,\n AGENT_INTERACTION_SCHEMA_VERSION,\n agentInteractionRequestSchema,\n runtimeCoordinatorExecutionTokenEnvelopeSchema,\n runtimeTransportDeliverDispatchRequestSchema,\n runtimeTransportDeliveryExecutionIdentitySchema,\n} from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n AgentControllerConversationResumePlan,\n AgentInteractionRequest,\n BootstrapTemplateFacts,\n ConversationExecutionState,\n DispatchExecution,\n ExecutionContextCompletion,\n LocalRuntimeContextPlan,\n OpenMeldDaemonTaskResultPayload,\n ProviderDispatchRuntimeContext,\n RuntimeCoordinatorExecutionTokenEcho,\n RuntimeTransportAgentControllerConversationOccupancy,\n RuntimeTransportDeliverDispatchRequest,\n RuntimeTransportDeliveryExecutionIdentity,\n RuntimeTransportDispatchLocalQueueDiagnostics,\n RuntimeTransportDispatchRuntimeEvidencePhase,\n RuntimeTransportResultIdentityEcho,\n RuntimeTransportRuntimeEvidenceIdentityEcho,\n} from \"@openmeld/schemas/types\";\nimport { resolveSpacePublicationRequirement } from \"@openmeld/space-mesh\";\nimport { recordOpenMeldCreatedLocalAgentSession } from \"../../agent-activity/session-inventory-origin-store\";\nimport { resolveBuiltinAgentControllerDefinition } from \"../../agents/builtin-agent-controller-definitions\";\nimport { resolveBaseUrl } from \"../../config/base-url\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../../config/openmeld-request-context\";\nimport { emitDaemonDispatchJournalEvent } from \"../../local-service/dispatch/daemon-dispatch-journal\";\nimport {\n type DispatchRuntimePreparation,\n prepareDispatchRuntimeExecution,\n resolveDispatchWorkingFolderRuntimeContext,\n} from \"../../local-service/execution/dispatch-runtime-preparation\";\nimport { toTaskExecutionError as toTaskExecutionErrorInternal } from \"../../local-service/execution/task-execution-error\";\nimport { buildDispatchOwnedRuntimeEnv } from \"../../runtime/dispatch-owned-runtime\";\nimport { DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND } from \"../../runtime/dispatch-runtime-env\";\nimport {\n createDispatchSpaceActionContext,\n type DispatchSpaceActionContext,\n type DispatchSpaceActionRecord,\n type DispatchSpaceActionRecordReadResult,\n OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV,\n readDispatchSpaceActionRecord,\n supersedeDispatchSpaceActionRecordForReconsideration,\n} from \"../../runtime/dispatch-space-action-context\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { fetchSpaceMeta } from \"../../space/meta-api\";\nimport { resolveProviderRuntimeDispatchContinuation } from \"../continuation/provider-runtime-continuation\";\nimport {\n resolveRecoveredLedgerConversation,\n resolveWorkingFolderRecovery,\n} from \"../continuation/working-folder-recovery\";\nimport {\n emitRunLine,\n normalizeOptionalText,\n toErrorMessage,\n} from \"../core/logger\";\nimport type {\n CurrentDaemonSocketRef,\n DaemonFrameSink,\n DaemonProfileRouteConfig,\n InflightDispatchMeta,\n LedgerPaths,\n} from \"../core/types\";\nimport { DaemonServiceRunError } from \"../core/types\";\nimport { resolveComputerFileAccessAdmission } from \"../file-access/computer-file-access-admission\";\nimport { applyComputerFileAccessAwareness } from \"../file-access/computer-file-access-prompt\";\nimport { readComputerFileAccessPolicy } from \"../file-access/computer-file-access-store\";\nimport { prepareDispatchWorkHandoff } from \"../file-access/dispatch-work-handoff\";\nimport { probeAgentControllerUsageObservationAuth } from \"../inventory/agent-controller-interface\";\nimport { recordRuntimeProviderUsageLimits } from \"../inventory/runtime-provider-usage-limits\";\nimport {\n buildRuntimeRouteTargets,\n resolveLocalRuntimeControllerSupport,\n} from \"../routing/resolve-controller-support\";\nimport { createLedgerIo } from \"../state/ledger-io\";\nimport {\n attachAgentReplyObservation,\n coordinateDispatchAgentReply,\n type DispatchAgentReplyObservation,\n readDispatchAgentReplyObservation,\n} from \"./dispatch-agent-reply-observation\";\nimport { settleAgentReplyProposals } from \"./dispatch-agent-reply-settlement\";\nimport {\n type DispatchImageAttachmentPreparation,\n downloadDispatchImageAttachment,\n materializeDispatchImageAttachments,\n} from \"./dispatch-image-attachments\";\nimport {\n type DispatchResultOutboxSettlement,\n enqueueDispatchResultOutboxRecord,\n} from \"./dispatch-result-outbox\";\nimport {\n applyDispatchSkillInstructions,\n ensureDispatchControllerOpenMeldSkill,\n} from \"./ensure-dispatch-controller-openmeld-skill\";\nimport {\n markBootstrapInjectedContext as markBootstrapInjectedContextInternal,\n reconcileBootstrapInjectedContextAfterDispatch as reconcileBootstrapInjectedContextAfterDispatchInternal,\n resolveBootstrapPlan as resolveBootstrapPlanInternal,\n rollbackBootstrapExecutionStateAfterDispatchFailure as rollbackBootstrapExecutionStateAfterDispatchFailureInternal,\n} from \"./execute-dispatch-bootstrap-plan\";\nimport {\n areSameAgentControllerConversationRef,\n buildAgentControllerConversationRefFromAgentControllerConversation,\n normalizeOptionalContextId,\n resolveCurrentConversationPolicy,\n resolveDispatchContextDeltaFromRuntimeResult,\n resolveDispatchContextIdForAgentControllerConversation,\n resolveObservedDispatchAgentControllerConversation,\n resolvePlannedAgentControllerConversation,\n} from \"./execute-dispatch-conversation\";\nimport { upsertConversationExecutionStateForLookupKey } from \"./execute-dispatch-conversation-state\";\nimport {\n buildResultDispatchJournalMetadata,\n buildRuntimeObservationPayload,\n emitContinuityWarningIfNeeded,\n emitDispatchLocalPhaseJournalEvent,\n emitProviderRuntimePhaseLine,\n emitRuntimeObservationSummaryLine,\n resolveAdapterTelemetry,\n summarizeTaskResultPayload,\n} from \"./execute-dispatch-observation\";\nimport {\n buildInvalidStructuredActionOutputPreview,\n buildStructuredActionRepairPrompt as buildStructuredActionRepairPromptInternal,\n coerceRuntimeResultToStructuredActionFailure as coerceRuntimeResultToStructuredActionFailureInternal,\n resolveStructuredActionOutputFallback,\n resolveStructuredActionRepairContinuation as resolveStructuredActionRepairContinuationInternal,\n resolveStructuredActionRepairPreviousOutput,\n resolveStructuredActionRequirementFailure as resolveStructuredActionRequirementFailureInternal,\n} from \"./execute-dispatch-structured-action-repair\";\nimport type {\n BootstrapPlan,\n DispatchBootstrapContextPhase,\n DispatchCorrelation,\n DispatchLifecyclePhase,\n DispatchPromptTrace,\n DispatchRejectionPayloadInput,\n DispatchRuntimeCompletion,\n DispatchSendTargetReferenceLoadResult,\n ParsedDispatchTask,\n StructuredActionFailureDiagnostics,\n StructuredActionRepairResult,\n SupportedRuntimeControllerSupport,\n} from \"./execute-dispatch-types\";\nimport {\n captureExecutionContextCompletion,\n executionContextFileAccessBoundary,\n executionContextLedgerPolicy,\n executionContextResourceScope,\n executionContextWorkingDirectory,\n prepareExecutionContextConversation,\n} from \"./execution-context-session\";\nimport {\n type ExecutionContextWorkspace,\n type ExecutionContextWorkspaceUse,\n markExecutionContextWorkspaceInUse,\n prepareExecutionContextWorkspace,\n releaseExecutionContextWorkspace,\n} from \"./execution-context-workspace\";\nimport {\n buildDispatchBootstrapTemplateFacts,\n buildDispatchCorrelation,\n buildDispatchPromptPlan,\n buildDispatchSessionTitle,\n type DispatchPromptPlan,\n parseDispatchTask,\n resolveBootstrapSpaceOwnerProfileId,\n resolveBootstrapTargetProfileContext,\n resolveDispatchMentionSourceContext,\n} from \"./parse-dispatch-task\";\nimport { buildDispatchPromptTrace } from \"./prompt-trace\";\nimport {\n createReasoningStream,\n routeReasoningEvents,\n} from \"./reasoning-stream\";\nimport {\n buildFailedTaskResultPayload,\n resolveDispatchResultPayload,\n sendDispatchInteractionRequestFrame,\n sendDispatchLifecycleFrame,\n sendDispatchPreviewEndFrame,\n sendDispatchPreviewFrame,\n sendDispatchReasoningFrame,\n sendDispatchRuntimeEvidenceFrame,\n sendDispatchToolActivityFrame,\n} from \"./send-dispatch-result\";\nimport { resolveDispatchSendTargetReference } from \"./send-target-reference\";\n\nexport const markBootstrapInjectedContext =\n markBootstrapInjectedContextInternal;\nexport const reconcileBootstrapInjectedContextAfterDispatch =\n reconcileBootstrapInjectedContextAfterDispatchInternal;\nexport const resolveBootstrapPlan = resolveBootstrapPlanInternal;\nexport const rollbackBootstrapExecutionStateAfterDispatchFailure =\n rollbackBootstrapExecutionStateAfterDispatchFailureInternal;\nexport const buildStructuredActionRepairPrompt =\n buildStructuredActionRepairPromptInternal;\nexport const coerceRuntimeResultToStructuredActionFailure =\n coerceRuntimeResultToStructuredActionFailureInternal;\nexport const resolveStructuredActionRepairContinuation =\n resolveStructuredActionRepairContinuationInternal;\nexport const resolveStructuredActionRequirementFailure =\n resolveStructuredActionRequirementFailureInternal;\n\nconst CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS = 25;\nconst CLI_SPACE_ACTION_RECORD_RUNTIME_COMPLETION_GRACE_MS = 1500;\nconst CLI_SPACE_ACTION_PROVIDER_CONVERSATION_GRACE_MS = 1500;\nconst AGENT_CONTROLLER_OCCUPANCY_KEEPALIVE_REASSERT_INTERVALS = 4;\n\n// OPENMELD_SERVICE_THIN_CORE: temporary dispatch execution shell.\n// Keep new local-service execution helpers outside this file. This file still\n// orchestrates delivery intake, runtime preparation, Space Action handling, and\n// result evidence until those slices are split one by one.\nexport function enqueueDispatchDeliverFrame(input: {\n computerFileAccessStorePath: string;\n contextStore: Map<string, string>;\n currentSocketRef?: CurrentDaemonSocketRef;\n daemonSessionId: string;\n localExecutionSlots: LocalExecutionSlots;\n inflightDispatchMetaByTaskId: Map<string, InflightDispatchMeta>;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n payload: Record<string, unknown>;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n requestCurrentWorkingFolderFactRefresh?: () => void;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n}): void {\n // OPENMELD_SERVICE_THIN_CORE: RuntimeCoordinator task intake.\n // The daemon may accept, queue, and execute a token-backed local task, then\n // report evidence. RuntimeCoordinator and Space still own final outcome.\n // OPENMELD_SETUP_TO_WAKE_PATH: HIGHEST_FACT local-service-execution\n // OpenMeld Service carries an accepted Wake to the bound local runtime. It is not\n // the owner of Space truth or final publication.\n const currentSocketRef = input.currentSocketRef ?? {\n connectionGeneration: normalizePositiveInteger(\n input.payload.connectionGeneration\n ),\n socket: input.socket,\n };\n const { pendingAgentInteractionRegistry } = input;\n const parsedDeliver = runtimeTransportDeliverDispatchRequestSchema.safeParse(\n input.payload\n );\n if (!parsedDeliver.success) {\n reportInvalidDeliverRequest({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n issues: parsedDeliver.error.issues,\n ledgerPaths: input.ledgerPaths,\n payload: input.payload,\n presenter: input.presenter,\n });\n return;\n }\n const deliverRequest = parsedDeliver.data;\n const correlation = buildDispatchCorrelation({\n deliverRequest,\n parsedTask: null,\n });\n const parsedQueueTask = parseDispatchTaskForQueue({\n deliverRequest,\n routeByProfileId: input.routeByProfileId,\n });\n const queueLogMeta = resolveDispatchQueueLogMeta({\n parsedTask: parsedQueueTask,\n profileId: deliverRequest.profileId,\n runtimeAdapterId: resolveQueueRuntimeAdapterId({\n localAdapterContainer: input.localAdapterContainer,\n parsedTask: parsedQueueTask,\n }),\n });\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest,\n phase: \"received\",\n presenter: input.presenter,\n });\n const enqueueResult = input.localExecutionSlots.request({\n resourceScope: executionContextResourceScope(\n deliverRequest.payload.executionContext\n ),\n adapterId: queueLogMeta.adapterId,\n attemptId: correlation.attemptId,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n executionTokenRunId: deliverRequest.payload.executionToken?.runId ?? null,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n onQueued: (event) => {\n const localQueue = toRuntimeTransportDispatchLocalQueueDiagnostics(\n event.localQueue\n );\n emitDispatchLifecycleTransition({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: deliverRequest.leaseEpoch,\n localQueue,\n phase: \"accepted_local\",\n presenter: input.presenter,\n executionTokenEcho:\n toRuntimeCoordinatorExecutionTokenEcho(deliverRequest),\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: correlation.taskId,\n });\n return startDispatchLifecycleKeepalive({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: deliverRequest.leaseEpoch,\n localQueue,\n phase: \"accepted_local\",\n presenter: input.presenter,\n executionTokenEcho:\n toRuntimeCoordinatorExecutionTokenEcho(deliverRequest),\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: correlation.taskId,\n });\n },\n profileId: deliverRequest.profileId,\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId ?? null,\n spaceId: queueLogMeta.spaceId,\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n run: async () => {\n return await handleDispatchDeliverFrame({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n contextStore: input.contextStore,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest,\n inflightDispatchMetaByTaskId: input.inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n pendingAgentInteractionRegistry,\n ledgerPaths: input.ledgerPaths,\n leasesByProfileId: input.leasesByProfileId,\n localAdapterContainer: input.localAdapterContainer,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n requestCurrentWorkingFolderFactRefresh:\n input.requestCurrentWorkingFolderFactRefresh,\n presenter: input.presenter,\n routeByProfileId: input.routeByProfileId,\n socket: input.socket,\n });\n },\n });\n function handleRejectedLocalExecutionSlot(\n rejected: Exclude<\n ReturnType<LocalExecutionSlots[\"request\"]>,\n { accepted: true }\n >\n ): void {\n if (rejected.reason === \"service.draining\") {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_deferred\",\n text: `deferred task ${correlation.taskId} because the local service is draining`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n activeForLane: rejected.snapshot.activeForLane,\n activeGlobal: rejected.snapshot.activeGlobal,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n durationMs: null,\n errorCode: \"daemon.service.draining\",\n globalConcurrency: rejected.snapshot.limits.globalConcurrency,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n profileId: deliverRequest.profileId,\n queueDepth: rejected.snapshot.queueDepth,\n queueMax: rejected.snapshot.limits.queueMax,\n result: \"deferred\",\n spaceId: queueLogMeta.spaceId,\n step: \"deferred\",\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n },\n });\n return;\n }\n const queueRejectErrorCode =\n rejected.reason === \"task.owner_conflict\"\n ? \"runtime.task.local_owner_conflict\"\n : \"queue.full\";\n const queueRejectMessage =\n rejected.reason === \"task.owner_conflict\"\n ? `${queueRejectErrorCode}: local task owner conflict for task ${correlation.taskId}; activeOwner=${rejected.activeOwner.dispatchId}/${rejected.activeOwner.attemptId}`\n : `queue.full: local execution slot queue is full (queueMax=${String(rejected.snapshot.limits.queueMax)}, pending=${String(rejected.snapshot.queueDepth)})`;\n const queueRejectPayload = buildFailedTaskResultPayload({\n attemptId: correlation.attemptId,\n agentControllerRef: correlation.agentControllerRef,\n errorCode: queueRejectErrorCode,\n errorMessage: queueRejectMessage,\n errorType:\n rejected.reason === \"task.owner_conflict\" ? \"internal\" : \"policy\",\n localOwnerConflict:\n rejected.reason === \"task.owner_conflict\"\n ? {\n activeAttemptId: rejected.activeOwner.attemptId,\n activeDispatchId: rejected.activeOwner.dispatchId,\n activeExecutionTokenRunId:\n rejected.activeOwner.executionTokenRunId,\n activeRuntimeCoordinatorExecutionId:\n rejected.activeOwner.runtimeCoordinatorExecutionId,\n activeTaskId: rejected.activeOwner.taskId,\n reason: \"task.owner_conflict\",\n rejectedAttemptId: correlation.attemptId,\n rejectedDispatchId: correlation.dispatchId,\n rejectedExecutionTokenRunId:\n deliverRequest.payload.executionToken?.runId ?? null,\n rejectedRuntimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId ?? null,\n rejectedTaskId: correlation.taskId,\n }\n : null,\n sourceEventId: correlation.sourceEventId,\n suppressPublicOutcome: rejected.reason === \"task.owner_conflict\",\n targetProfileId: correlation.targetProfileId,\n taskId: correlation.taskId,\n });\n enqueueDispatchResultOutboxRecord({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n executionIdentityEcho:\n toRuntimeTransportResultIdentityEcho(deliverRequest),\n executionTokenEcho:\n toRuntimeCoordinatorExecutionTokenEcho(deliverRequest),\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: deliverRequest.leaseEpoch,\n payload: queueRejectPayload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId:\n deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: correlation.taskId,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: correlation.attemptId,\n connectionGeneration: deliverRequest.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: correlation.dispatchId,\n leaseEpoch: deliverRequest.leaseEpoch,\n metadata: buildResultDispatchJournalMetadata(queueRejectPayload),\n profileId: deliverRequest.profileId,\n result: queueRejectPayload.status,\n taskId: correlation.taskId,\n type: \"dispatch.result.queued\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_rejected\",\n text: `local execution slot rejected task ${correlation.taskId} for ${queueLogMeta.targetLabel}: ${rejected.reason}`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n activeForLane: rejected.snapshot.activeForLane,\n activeGlobal: rejected.snapshot.activeGlobal,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n durationMs: null,\n errorCode: queueRejectErrorCode,\n globalConcurrency: rejected.snapshot.limits.globalConcurrency,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n profileId: deliverRequest.profileId,\n queueDepth: rejected.snapshot.queueDepth,\n queueMax: rejected.snapshot.limits.queueMax,\n result: \"failed\",\n spaceId: queueLogMeta.spaceId,\n step: \"rejected\",\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n ...(rejected.reason === \"task.owner_conflict\"\n ? {\n activeOwnerAttemptId: rejected.activeOwner.attemptId,\n activeOwnerDispatchId: rejected.activeOwner.dispatchId,\n }\n : {}),\n },\n });\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest,\n phase: \"failed\",\n presenter: input.presenter,\n reasonCode: queueRejectErrorCode,\n });\n }\n if (!enqueueResult.accepted) {\n handleRejectedLocalExecutionSlot(enqueueResult);\n return;\n }\n if (enqueueResult.deduped) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_deduped\",\n text: `local execution slot deduped attempt ${correlation.attemptId} for task ${correlation.taskId}`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n attemptId: correlation.attemptId,\n controllerKey: queueLogMeta.controllerKey,\n dispatchId: correlation.dispatchId,\n queueDepth: enqueueResult.snapshot.queueDepth,\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n },\n });\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_accepted\",\n text: `local execution slot accepted task ${correlation.taskId} for ${queueLogMeta.targetLabel}`,\n payload: {\n adapterId: queueLogMeta.adapterId,\n activeForLane: enqueueResult.snapshot.activeForLane,\n activeGlobal: enqueueResult.snapshot.activeGlobal,\n connectionGeneration: deliverRequest.connectionGeneration,\n controllerKey: queueLogMeta.controllerKey,\n deliveryRecoveryReason: deliverRequest.deliveryRecoveryReason ?? null,\n dispatchId: correlation.dispatchId,\n durationMs: null,\n errorCode: null,\n globalConcurrency: enqueueResult.snapshot.limits.globalConcurrency,\n localExecutionLaneKey: queueLogMeta.localExecutionLaneKey,\n profileId: deliverRequest.profileId,\n queueDepth: enqueueResult.snapshot.queueDepth,\n queueMax: enqueueResult.snapshot.limits.queueMax,\n result: null,\n spaceId: queueLogMeta.spaceId,\n step: \"enqueued\",\n taskId: correlation.taskId,\n targetLabel: queueLogMeta.targetLabel,\n transportMode: queueLogMeta.transportMode,\n },\n });\n}\n\nfunction parseDispatchTaskForQueue(input: {\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n}): ParsedDispatchTask | null {\n return parseDispatchTask({\n deliverRequest: input.deliverRequest,\n fallbackRouteConfig:\n input.routeByProfileId.get(input.deliverRequest.profileId) ?? null,\n });\n}\n\nfunction resolveQueueRuntimeAdapterId(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n parsedTask: ParsedDispatchTask | null;\n}): string | null {\n if (!input.parsedTask) {\n return null;\n }\n const support = resolveLocalRuntimeControllerSupport({\n agentControllerRef: input.parsedTask.agentControllerRef,\n localAdapterContainer: input.localAdapterContainer,\n });\n return support.supported === true\n ? support.runtimeAdapterMatch.adapterId\n : null;\n}\n\nfunction reportInvalidDeliverRequest(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n issues: readonly { message: string; path: readonly unknown[] }[];\n ledgerPaths: LedgerPaths;\n payload: Record<string, unknown>;\n presenter: Presenter;\n}): void {\n const identity = resolveInvalidDeliverRequestIdentity({\n fallbackDaemonSessionId: input.daemonSessionId,\n payload: input.payload,\n });\n const issues = summarizeDeliverParseIssues(input.issues);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.deliver_payload_invalid\",\n text: `deliver payload rejected before queueing for dispatch ${identity?.dispatchId ?? \"unknown\"}`,\n payload: {\n dispatchId: identity?.dispatchId ?? null,\n issues,\n result: \"failed\",\n taskId: identity?.taskId ?? null,\n },\n });\n\n if (!identity) {\n return;\n }\n\n const resultPayload = buildFailedTaskResultPayload({\n attemptId: identity.attemptId,\n agentControllerRef: identity.agentControllerRef,\n errorCode: \"schema.invalid\",\n errorMessage: buildInvalidDeliverRequestErrorMessage(issues),\n errorType: \"config\",\n sourceEventId: identity.sourceEventId,\n targetProfileId: identity.targetProfileId,\n taskId: identity.taskId,\n });\n try {\n enqueueDispatchResultOutboxRecord({\n attemptId: identity.attemptId,\n connectionGeneration: identity.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: identity.dispatchId,\n executionIdentityEcho: identity.executionIdentityEcho,\n executionTokenEcho: identity.executionTokenEcho,\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: identity.leaseEpoch,\n payload: resultPayload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId: identity.runtimeCoordinatorExecutionId,\n taskId: identity.taskId,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: identity.attemptId,\n connectionGeneration: identity.connectionGeneration,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: identity.dispatchId,\n leaseEpoch: identity.leaseEpoch,\n metadata: {\n ...buildResultDispatchJournalMetadata(resultPayload),\n parseIssues: issues,\n },\n profileId: identity.targetProfileId,\n result: resultPayload.status,\n taskId: identity.taskId,\n type: \"dispatch.result.queued\",\n });\n } catch (error) {\n emitDaemonDispatchJournalEvent({\n attemptId: identity.attemptId,\n connectionGeneration: identity.connectionGeneration,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: identity.dispatchId,\n leaseEpoch: identity.leaseEpoch,\n metadata: {\n ...buildResultDispatchJournalMetadata(resultPayload),\n errorMessage: toErrorMessage(error),\n parseIssues: issues,\n },\n profileId: identity.targetProfileId,\n result: resultPayload.status,\n taskId: identity.taskId,\n type: \"dispatch.result.send_failed\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.invalid_deliver_result_send_failed\",\n text: `failed to send invalid deliver result for dispatch ${identity.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n dispatchId: identity.dispatchId,\n errorMessage: toErrorMessage(error),\n result: \"failed\",\n taskId: identity.taskId,\n },\n });\n }\n}\n\nfunction resolveInvalidDeliverRequestIdentity(input: {\n fallbackDaemonSessionId: string;\n payload: Record<string, unknown>;\n}): {\n attemptId: string;\n connectionGeneration: number;\n agentControllerRef: string | null;\n daemonSessionId: string;\n dispatchId: string;\n executionIdentityEcho: RuntimeTransportResultIdentityEcho;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n runtimeCoordinatorExecutionId: string | null;\n sourceEventId: string;\n targetProfileId: string;\n taskId: string;\n} | null {\n const taskPayload = toRecord(input.payload.payload);\n const controllerSnapshot = toRecord(taskPayload?.controllerSnapshot);\n const executionIdentity =\n runtimeTransportDeliveryExecutionIdentitySchema.safeParse(\n taskPayload?.executionIdentity\n );\n const attemptId =\n normalizeOptionalText(input.payload.attemptId) ??\n normalizeOptionalText(taskPayload?.attemptId);\n const connectionGeneration = normalizePositiveInteger(\n input.payload.connectionGeneration\n );\n const daemonSessionId =\n normalizeOptionalText(input.payload.daemonSessionId) ??\n input.fallbackDaemonSessionId;\n const dispatchId =\n normalizeOptionalText(input.payload.dispatchId) ??\n normalizeOptionalText(taskPayload?.dispatchId);\n const leaseEpoch = normalizePositiveInteger(input.payload.leaseEpoch);\n const sourceEventId = normalizeOptionalText(taskPayload?.sourceEventId);\n const targetProfileId =\n normalizeOptionalText(taskPayload?.targetProfileId) ??\n normalizeOptionalText(input.payload.profileId);\n const taskId = normalizeOptionalText(taskPayload?.taskId);\n const runtimeCoordinatorExecutionId = normalizeOptionalText(\n taskPayload?.runtimeCoordinatorExecutionId\n );\n const executionTokenEcho = resolveRuntimeCoordinatorExecutionTokenEchoFromRaw(\n taskPayload?.executionToken\n );\n\n if (\n !(\n attemptId &&\n connectionGeneration &&\n daemonSessionId &&\n dispatchId &&\n executionIdentity.success &&\n leaseEpoch &&\n sourceEventId &&\n targetProfileId &&\n taskId\n )\n ) {\n return null;\n }\n\n return {\n attemptId,\n connectionGeneration,\n agentControllerRef:\n normalizeOptionalText(controllerSnapshot?.agentControllerRef) ?? null,\n daemonSessionId,\n dispatchId,\n executionIdentityEcho:\n toRuntimeTransportResultIdentityEchoFromDeliveryIdentity(\n executionIdentity.data\n ),\n executionTokenEcho,\n leaseEpoch,\n runtimeCoordinatorExecutionId,\n sourceEventId,\n targetProfileId,\n taskId,\n };\n}\n\nfunction summarizeDeliverParseIssues(\n issues: readonly { message: string; path: readonly unknown[] }[]\n): Array<{ message: string; path: string }> {\n return issues.slice(0, 8).map((issue) => ({\n message: issue.message,\n path: issue.path.map((part) => String(part)).join(\".\"),\n }));\n}\n\nfunction buildInvalidDeliverRequestErrorMessage(\n issues: readonly { message: string; path: string }[]\n): string {\n const firstIssue = issues[0];\n if (!firstIssue) {\n return \"schema.invalid: daemon deliver payload is invalid\";\n }\n const path = firstIssue.path || \"payload\";\n return `schema.invalid: daemon deliver payload is invalid at ${path}: ${firstIssue.message}`;\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\nfunction normalizePositiveInteger(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0\n ? value\n : null;\n}\n\nexport async function handleDispatchDeliverFrame(input: {\n computerFileAccessStorePath: string;\n contextStore: Map<string, string>;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n inflightDispatchMetaByTaskId: Map<string, InflightDispatchMeta>;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n requestCurrentWorkingFolderFactRefresh?: () => void;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n}): Promise<LocalExecutionSlotTaskResult> {\n const { currentSocketRef } = input;\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n source: \"local_execution_slot_task\",\n },\n parsedTask: null,\n phase: \"task_started\",\n result: \"started\",\n });\n const validatedDispatchInput = resolveValidatedDispatchDeliveryInput({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n leasesByProfileId: input.leasesByProfileId,\n localAdapterContainer: input.localAdapterContainer,\n presenter: input.presenter,\n routeByProfileId: input.routeByProfileId,\n socket: input.socket,\n });\n if (validatedDispatchInput.status === \"rejected\") {\n return validatedDispatchInput.result;\n }\n const { parsedTask, routeConfig, runtimeControllerSupport } =\n validatedDispatchInput;\n const unsupportedControllerResult = maybeRejectUnsupportedController({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n presenter: input.presenter,\n runtimeControllerSupport,\n socket: input.socket,\n });\n if (unsupportedControllerResult) {\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n parsedTask,\n phase: \"failed\",\n presenter: input.presenter,\n reasonCode: \"controller.kind.unsupported\",\n });\n return unsupportedControllerResult;\n }\n assertSupportedRuntimeControllerSupport(runtimeControllerSupport);\n const { pendingAgentInteractionRegistry } = input;\n const onInteractionRequest: AdapterInteractionCallback =\n createSerialAgentInteractionCallback(\n async (request) =>\n await requestDispatchAgentInteraction({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n parsedTask,\n pendingAgentInteractionRegistry,\n presenter: input.presenter,\n request,\n leasesByProfileId: input.leasesByProfileId,\n })\n );\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerRef: parsedTask.agentControllerRef,\n source: \"dispatch_preflight\",\n streamingMode: parsedTask.streamingMode,\n transportMode: parsedTask.transportMode,\n },\n parsedTask,\n phase: \"preflight_ready\",\n result: \"ready\",\n });\n\n let resultPayload: OpenMeldDaemonTaskResultPayload;\n let continuityObservation: DispatchContinuityObservation | null = null;\n let dispatchExecution: DispatchExecution | null = null;\n let resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n let resolvedSpaceActionProvenance:\n | OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"]\n | undefined;\n let contextLookupKey = \"\";\n let currentExecutionState: ConversationExecutionState | null = null;\n let existingContextId: string | null = null;\n let latestScopedExecutionState: ConversationExecutionState | null = null;\n let ledgerIo: ReturnType<typeof createLedgerIo> | null = null;\n const currentConversationPolicy =\n resolveCurrentConversationPolicy(routeConfig);\n const bootstrapContext = await resolveDispatchBootstrapContext({\n onPhase: (phase, metadata) => {\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata,\n parsedTask,\n phase,\n result: \"ready\",\n });\n },\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n parsedTask,\n });\n let localRuntimeContextPlan: LocalRuntimeContextPlan | null = null;\n let agentControllerConversationResumePlan: AgentControllerConversationResumePlan | null =\n null;\n let contextIdForDispatch: string | null = null;\n let effectiveAgentControllerConversationId: string | null = null;\n let bootstrapPlan: BootstrapPlan | null = null;\n let plannedAgentControllerConversation: AgentControllerConversationRef | null =\n null;\n let observedProviderConversationId: string | null = null;\n let observedProviderConversation: AgentControllerConversationRef | null =\n null;\n let runtimePromptPlan: DispatchPromptPlan | null = null;\n let runtimePromptTrace: DispatchPromptTrace | null = null;\n let settledResultSummary: LocalExecutionSlotTaskResult | null = null;\n const providerAdmissionOwnsRunningLifecycle =\n resolveBuiltinAgentControllerDefinition(\n runtimeControllerSupport.runtimeAdapterMatch.agentId\n )?.conversationOccupancy.mode ===\n \"official_atomic_admission_and_release_signal\";\n let runtimeLifecyclePhase: Extract<\n DispatchLifecyclePhase,\n \"accepted_local\" | \"running\"\n > = resolveInitialDispatchLifecyclePhase({\n providerAdmissionOwnsRunningLifecycle,\n });\n const lifecycleKeepalive = {\n stop: null as (() => void) | null,\n };\n let firstOutputEvidenceSent = false;\n input.inflightTaskControlRegistry.registerTask({\n adapterId: runtimeControllerSupport.runtimeAdapterMatch.adapterId,\n agentControllerPermissionMode:\n routeConfig?.agentControllerPermissionMode ?? null,\n dispatchId: parsedTask.dispatchId,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n const runtimeStartedAtMs = Date.now();\n let agentToolActivitySequence = 0;\n let firstReasoningMs: number | undefined;\n const sendReasoning = (\n thinkingSnapshot: string,\n observedAtMs: number,\n status: \"streaming\" | \"waiting\" | \"disabled\" = \"streaming\"\n ) => {\n const socket = currentSocketRef.socket;\n if (\n runtimeControllerSupport.runtimeAdapterMatch.adapterId === \"openclaw\" ||\n !socket ||\n currentSocketRef.reasoningStreamEnabled === undefined ||\n (status === \"streaming\" && (socket.bufferedAmount ?? 0) > 64 * 1024)\n ) {\n return;\n }\n try {\n sendDispatchReasoningFrame({\n socket,\n thinkingSnapshot,\n observedAtMs,\n reasoningState: {\n status,\n ...(firstReasoningMs !== undefined\n ? { firstOutputMs: firstReasoningMs }\n : {}),\n },\n sequence: ++agentToolActivitySequence,\n attemptId: parsedTask.attemptId,\n dispatchId: parsedTask.dispatchId,\n daemonSessionId: input.daemonSessionId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef,\n fallbackConnectionGeneration:\n input.deliverRequest.connectionGeneration,\n }),\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n sourceSignalId: parsedTask.sourceEventId,\n spaceId: parsedTask.spaceId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n } catch {\n // Live delivery is best effort; never log its content or fail the run.\n }\n };\n const reasoningStream = createReasoningStream({\n enabled: () =>\n currentSocketRef.reasoningStreamEnabled === true &&\n currentSocketRef.socket !== null,\n send: sendReasoning,\n });\n const clearReasoning = () => {\n reasoningStream.clear();\n sendReasoning(\n \"\",\n Date.now(),\n currentSocketRef.reasoningStreamEnabled ? \"waiting\" : \"disabled\"\n );\n };\n currentSocketRef.reasoningPreferenceListeners ??= new Set();\n currentSocketRef.reasoningPreferenceListeners.add(clearReasoning);\n const observeReasoning = (\n event: Extract<AdapterRuntimeEvent, { phase: \"reasoning\" }>\n ) => {\n if (firstReasoningMs === undefined && event.text.length > 0) {\n firstReasoningMs = Math.max(0, event.tsMs - runtimeStartedAtMs);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.reasoning_first_output\",\n text: \"Local Agent produced its first reasoning output.\",\n payload: {\n dispatchId: parsedTask.dispatchId,\n firstOutputMs: firstReasoningMs,\n },\n });\n }\n reasoningStream.observe(event);\n };\n const daemonWorkingDirectory = process.cwd();\n let dispatchRuntimeContext: ProviderDispatchRuntimeContext | null = null;\n let effectiveRuntimeContext: ProviderDispatchRuntimeContext | null = null;\n let runtimeEnvOverrides: Record<string, string | undefined> | undefined;\n let runtimeOpenClawGatewayVisibility: OpenClawGatewayVisibility | null = null;\n let computerFileAccessBoundary: AdapterComputerFileAccessBoundary | null =\n null;\n let runtimeOpenClawBinding:\n | OpenMeldDaemonTaskResultPayload[\"openClawBinding\"]\n | undefined;\n let agentControllerConversationOverride:\n | OpenMeldDaemonTaskResultPayload[\"agentControllerConversation\"]\n | null = null;\n let dispatchSpaceActionContext: DispatchSpaceActionContext | null = null;\n let nativeQuiescence: Promise<void> | undefined;\n let workspaceUse: ExecutionContextWorkspaceUse | null = null;\n const workspaceProcesses = new Map<number | null, boolean>();\n const observeWorkspaceProcess = (event: AdapterRuntimeEvent) =>\n observeExecutionContextWorkspaceProcess(workspaceProcesses, event);\n let completedTurnId: string | null = null;\n let completedTurnConversationId: string | null = null;\n let completedNativeResult: RuntimeTaskResult | null = null;\n let executionContextCompletion: ExecutionContextCompletion | undefined;\n const invalidStateStrategy = executionContextLedgerPolicy(\n parsedTask.executionContext\n );\n\n try {\n await currentSocketRef.confirmExecutionAdmission?.(input.deliverRequest);\n dispatchRuntimeContext = await resolveDispatchWorkingFolderRuntimeContext({\n controllerSnapshot: input.deliverRequest.payload.controllerSnapshot,\n defaultProjectId: parsedTask.defaultProjectId,\n defaultProjectIdWasProvided: Object.hasOwn(\n input.deliverRequest.payload,\n \"defaultProjectId\"\n ),\n executionIdentity: parsedTask.executionIdentity,\n onCurrentWorkingFolderFactRejected:\n input.requestCurrentWorkingFolderFactRefresh,\n routeConfig,\n targetProfileId: parsedTask.targetProfileId,\n });\n const folderRecovery = await resolveWorkingFolderRecovery({\n agentControllerRef: parsedTask.agentControllerRef,\n nativeSessionId: parsedTask.agentControllerConversationId,\n hasExecutionContext: Boolean(parsedTask.executionContext),\n workingDirectory: dispatchRuntimeContext.providerRuntimeWorkingDirectory,\n policy: await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n ),\n onInteractionRequest,\n });\n dispatchRuntimeContext = {\n providerRuntimeWorkingDirectory: folderRecovery.workingDirectory,\n };\n await currentSocketRef.confirmExecutionAdmission?.(input.deliverRequest);\n const skillPreflight = await ensureDispatchControllerOpenMeldSkill({\n agentControllerRef: parsedTask.agentControllerRef,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.skill_preflight\",\n text: \"OpenMeld Skill checked for this local agent\",\n payload: {\n agentId: skillPreflight.agentId,\n status: skillPreflight.status,\n reason: skillPreflight.reason,\n },\n });\n const runtimePreparation = await prepareDispatchRuntimeExecution({\n agentControllerRef: parsedTask.agentControllerRef,\n daemonWorkingDirectory,\n dispatchRuntimeContext,\n profileName: bootstrapContext.targetProfileName,\n targetProfileId: parsedTask.targetProfileId,\n });\n effectiveRuntimeContext = runtimePreparation.effectiveRuntimeContext;\n const originalWorkingDirectory =\n effectiveRuntimeContext.providerRuntimeWorkingDirectory;\n await verifyDispatchLegacyContextAssociation({\n parsedTask,\n ledgerPaths: input.ledgerPaths,\n originalWorkingDirectory,\n });\n const taskWorkspace = await prepareDispatchTaskWorkspace({\n parsedTask,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n currentWorkingDirectory: originalWorkingDirectory,\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n });\n const handoffWorkingDirectory = await prepareDispatchWorkHandoff({\n task: parsedTask,\n ownerUserId: input.profileOwnerUserId,\n workingDirectory: taskWorkspace.workingDirectory,\n });\n effectiveRuntimeContext = {\n providerRuntimeWorkingDirectory: handoffWorkingDirectory,\n };\n runtimePreparation.effectiveRuntimeContext = effectiveRuntimeContext;\n computerFileAccessBoundary = await resolveDispatchComputerFileAccess({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n onInteractionRequest,\n parsedTask,\n presenter: input.presenter,\n routeConfig,\n runtimeControllerSupport,\n runtimePreparation,\n taskWorkspace,\n });\n // First real consumer of the send target reference: the network load has\n // been running concurrently with the local runtime preparation above.\n const [sendTargetReference, imageAttachmentPreparation] = await Promise.all(\n [\n bootstrapContext.sendTargetReferencePromise,\n materializeDispatchImageAttachments({\n agentControllerRef: parsedTask.agentControllerRef,\n attachments: parsedTask.attachments,\n downloadAttachment: ({ attachmentId, spaceId }) =>\n downloadDispatchImageAttachment({\n attachmentId,\n ownerName: input.profileOwnerName,\n ownerUserId: input.profileOwnerUserId,\n spaceId,\n spacePassword: parsedTask.spacePassword,\n targetProfileId: parsedTask.targetProfileId,\n targetProfileName: bootstrapContext.targetProfileName,\n }),\n providerRuntimeWorkingDirectory:\n effectiveRuntimeContext.providerRuntimeWorkingDirectory,\n spaceId: parsedTask.spaceId,\n taskId: parsedTask.taskId,\n }),\n ]\n );\n emitSendTargetReferenceLoadFailureIfNeeded({\n parsedTask,\n presenter: input.presenter,\n sendTargetReference,\n });\n emitDispatchImageAttachmentPreparation({\n parsedTask,\n preparation: imageAttachmentPreparation,\n presenter: input.presenter,\n });\n const spaceActionRuntimeContext = createDispatchSpaceActionRuntimeContext({\n bootstrapContext,\n parsedTask,\n runtimePreparation,\n sendTargetReference,\n });\n dispatchSpaceActionContext =\n spaceActionRuntimeContext.dispatchSpaceActionContext;\n runtimeEnvOverrides = spaceActionRuntimeContext.runtimeEnvOverrides;\n runtimeOpenClawGatewayVisibility =\n runtimePreparation.runtimeOpenClawGatewayVisibility;\n const activeRuntimeContext = effectiveRuntimeContext;\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerRef: parsedTask.agentControllerRef,\n providerRuntimePreparationKind:\n runtimePreparation.runtimePreparationDetails.kind,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n source: \"dispatch_runtime_context\",\n },\n parsedTask,\n phase: \"runtime_context_ready\",\n result: \"ready\",\n });\n const dispatchLedgerContext = await loadDispatchLedgerContext({\n contextStore: input.contextStore,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n originalWorkingDirectory,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n });\n contextLookupKey = dispatchLedgerContext.contextLookupKey;\n const recoveredConversation = resolveRecoveredLedgerConversation({\n startNewConversation: folderRecovery.startNewConversation,\n bindingConversationId: parsedTask.agentControllerConversationId,\n currentExecutionState: dispatchLedgerContext.currentExecutionState,\n existingContextId: dispatchLedgerContext.existingContextId,\n });\n currentExecutionState = recoveredConversation.currentExecutionState;\n existingContextId = recoveredConversation.existingContextId;\n effectiveAgentControllerConversationId =\n resolveEffectiveAgentControllerConversationId({\n agentControllerConversationId:\n recoveredConversation.bindingConversationId,\n existingContextId,\n });\n workspaceUse = await markExecutionContextWorkspaceInUse({\n context: parsedTask.executionContext,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n });\n runtimeEnvOverrides = {\n ...runtimeEnvOverrides,\n OPENMELD_PROCESS_SUPERVISION_ID: workspaceUse?.processSupervisionId,\n };\n effectiveAgentControllerConversationId =\n await prepareExecutionContextConversation({\n computerFileAccessBoundary,\n unscopedNativeConversationId: effectiveAgentControllerConversationId,\n context: parsedTask.executionContext,\n currentWorkingDirectory: originalWorkingDirectory,\n workingDirectory: activeRuntimeContext.providerRuntimeWorkingDirectory,\n existingNativeConversationId: existingContextId,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n agentControllerRef: parsedTask.agentControllerRef,\n launchContract: routeConfig?.launchContract,\n onRuntimeEvent: observeWorkspaceProcess,\n processSupervisionId: workspaceUse?.processSupervisionId,\n });\n latestScopedExecutionState =\n dispatchLedgerContext.latestScopedExecutionState;\n ledgerIo = dispatchLedgerContext.ledgerIo;\n input.inflightDispatchMetaByTaskId.set(parsedTask.taskId, {\n agentContextLookupKey: contextLookupKey,\n });\n const runtimeContinuation = resolveProviderRuntimeDispatchContinuation({\n agentControllerConversationId: effectiveAgentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n currentPolicy: currentConversationPolicy,\n existingContextId,\n executionState: currentExecutionState,\n latestKnownRuntimeWorkspaceFingerprint:\n latestScopedExecutionState?.runtimeWorkspaceFingerprint ?? null,\n runtimeContext: activeRuntimeContext,\n runtimePreparationDetails: runtimePreparation.runtimePreparationDetails,\n spaceId: parsedTask.spaceId,\n spaceNameSnapshot: parsedTask.spaceNameSnapshot,\n transportMode: parsedTask.transportMode,\n });\n localRuntimeContextPlan = runtimeContinuation.localRuntimeContextPlan;\n agentControllerConversationResumePlan =\n runtimeContinuation.agentControllerConversationResumePlan;\n runtimeOpenClawBinding =\n runtimeContinuation.taskResultProviderFacts.openClawBinding;\n contextIdForDispatch =\n resolveDispatchContextIdForAgentControllerConversation({\n agentControllerConversationId: effectiveAgentControllerConversationId,\n agentControllerConversationOverride:\n runtimeContinuation.agentControllerConversationOverride,\n agentControllerConversationResumePlan,\n });\n plannedAgentControllerConversation =\n resolvePlannedAgentControllerConversation({\n agentControllerConversationId: contextIdForDispatch,\n agentControllerRef: parsedTask.agentControllerRef,\n });\n observedProviderConversationId = contextIdForDispatch;\n observedProviderConversation = plannedAgentControllerConversation;\n bootstrapPlan = resolveBootstrapPlan({\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n executionState: currentExecutionState,\n localRuntimeContextPlan,\n nowMs: Date.now(),\n });\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n bootstrapReason: bootstrapPlan.reason,\n bootstrapShouldInject: bootstrapPlan.shouldInject,\n existingContextPresent: existingContextId !== null,\n localRuntimeContextStatus: localRuntimeContextPlan.status,\n source: \"dispatch_ledger_context\",\n agentControllerConversationResumeStatus:\n agentControllerConversationResumePlan.status,\n },\n parsedTask,\n phase: \"ledger_context_ready\",\n result: \"ready\",\n });\n const baseRuntimePromptPlan = applyDispatchSkillInstructions(\n buildDispatchRuntimePrompt({\n bootstrapContext,\n imageAttachmentPreparation,\n parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n sendTargetReference,\n shouldInjectBootstrap: bootstrapPlan.shouldInject,\n taskWorkspace,\n }),\n skillPreflight\n );\n runtimePromptPlan = computerFileAccessBoundary\n ? applyComputerFileAccessAwareness({\n policy: computerFileAccessBoundary,\n promptPlan: baseRuntimePromptPlan,\n })\n : baseRuntimePromptPlan;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.bootstrap_context\",\n text: `bootstrap context prepared for ${parsedTask.spaceId}/${parsedTask.targetProfileId}`,\n payload: {\n activationTargetCount:\n parsedTask.sourceMessageEnvelope?.activationTargets.length ?? 0,\n dispatchId: parsedTask.dispatchId,\n dispatchTriggerSource: parsedTask.dispatchTriggerSource,\n messageEnvelopePresent: parsedTask.sourceMessageEnvelope !== null,\n referenceTargetCount:\n parsedTask.sourceMessageEnvelope?.referenceTargets.length ?? 0,\n sourceEventId: parsedTask.sourceEventId,\n targetProfileId: parsedTask.targetProfileId,\n },\n });\n runtimePromptTrace = buildDispatchPromptTrace({\n prompt: runtimePromptPlan.fallbackPrompt,\n protectedInformation: parsedTask.organizationProtectedInformation,\n });\n await prepareBootstrapExecutionStateIfNeeded({\n bootstrapPlan,\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n contextIdForDispatch,\n contextLookupKey,\n currentExecutionState,\n effectiveRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n presenter: input.presenter,\n });\n agentControllerConversationOverride =\n runtimeContinuation.agentControllerConversationOverride;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_started\",\n text: `runtime started for task ${parsedTask.taskId}`,\n payload: {\n attemptId: parsedTask.attemptId,\n agentControllerRef: parsedTask.agentControllerRef,\n deliveryRecoveryReason: parsedTask.deliveryRecoveryReason,\n dispatchId: parsedTask.dispatchId,\n existingContextId: contextIdForDispatch,\n localRuntimeContextReason: localRuntimeContextPlan.reason,\n localRuntimeContextStatus: localRuntimeContextPlan.status,\n daemonWorkingDirectory,\n providerRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n spaceId: parsedTask.spaceId,\n streamingMode: parsedTask.streamingMode,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n transportMode: parsedTask.transportMode,\n agentControllerConversationResumeStatus:\n agentControllerConversationResumePlan.status,\n ...(agentControllerConversationResumePlan.status === \"blocked\"\n ? {\n agentControllerConversationResumeReason:\n agentControllerConversationResumePlan.reason,\n }\n : {}),\n },\n });\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n parsedTask,\n phase: \"runtime_started\",\n presenter: input.presenter,\n });\n const transitionDispatchLifecycle = (inputLifecycle: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n phase: Extract<DispatchLifecyclePhase, \"accepted_local\" | \"running\">;\n }): void => {\n runtimeLifecyclePhase = inputLifecycle.phase;\n lifecycleKeepalive.stop?.();\n emitDispatchLifecycleTransition({\n agentControllerConversationOccupancy:\n inputLifecycle.agentControllerConversationOccupancy ?? null,\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n phase: runtimeLifecyclePhase,\n presenter: input.presenter,\n executionTokenEcho: parsedTask.executionTokenEcho,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n taskId: parsedTask.taskId,\n });\n lifecycleKeepalive.stop = startDispatchLifecycleKeepalive({\n agentControllerConversationOccupancy:\n inputLifecycle.agentControllerConversationOccupancy ?? null,\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n phase: runtimeLifecyclePhase,\n presenter: input.presenter,\n executionTokenEcho: parsedTask.executionTokenEcho,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n taskId: parsedTask.taskId,\n });\n };\n transitionDispatchLifecycle({ phase: runtimeLifecyclePhase });\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerRef: parsedTask.agentControllerRef,\n localRuntimeContextStatus: localRuntimeContextPlan.status,\n streamingMode: parsedTask.streamingMode,\n transportMode: parsedTask.transportMode,\n agentControllerConversationResumeStatus:\n agentControllerConversationResumePlan.status,\n },\n parsedTask,\n phase: \"runtime_invocation_started\",\n result: \"started\",\n });\n const providerConversationLedgerIo = ledgerIo;\n if (!providerConversationLedgerIo) {\n throw new DaemonServiceRunError({\n code: \"dispatch.ledger.unavailable\",\n message:\n \"dispatch.ledger.unavailable: dispatch ledger is not initialized\",\n });\n }\n let recordedOpenMeldCreatedSessionId: string | null = null;\n const recordProviderConversationObservation = (observation: {\n agentControllerConversationId: string | null | undefined;\n agentControllerConversation?: AgentControllerConversationRef | null;\n source: \"runtime_event\" | \"runtime_result\";\n }): string | null => {\n const agentControllerConversationId = normalizeOptionalContextId(\n observation.agentControllerConversationId\n );\n if (!agentControllerConversationId) {\n return null;\n }\n const agentControllerConversation =\n observation.agentControllerConversation ??\n buildAgentControllerConversationRefFromAgentControllerConversation({\n agentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n });\n observedProviderConversationId = agentControllerConversationId;\n observedProviderConversation = agentControllerConversation;\n if (\n contextIdForDispatch === null &&\n recordedOpenMeldCreatedSessionId !== agentControllerConversationId\n ) {\n recordedOpenMeldCreatedSessionId = agentControllerConversationId;\n recordOpenMeldCreatedLocalAgentSession({\n agentControllerRef: parsedTask.agentControllerRef,\n nativeSessionId: agentControllerConversationId,\n }).catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.session_inventory_origin_record_failed\",\n text: `Session Inventory origin could not be recorded for task ${parsedTask.taskId}`,\n payload: {\n dispatchId: parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n });\n }\n const persistProviderConversationObservation = withLedgerStateTransaction(\n {\n invalidStateStrategy,\n io: providerConversationLedgerIo,\n mutate: (state) => ({\n nextState: commitResolvedAgentContext({\n state,\n agentContextLookupKey: contextLookupKey,\n agentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n spaceId: parsedTask.spaceId,\n targetProfileId: parsedTask.targetProfileId,\n transportMode: parsedTask.transportMode,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n taskId: parsedTask.taskId,\n nowMs: Date.now(),\n }),\n value: undefined,\n }),\n paths: input.ledgerPaths,\n }\n );\n persistProviderConversationObservation.catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_conversation_observation_ignored\",\n text: `provider conversation observation could not be persisted for task ${parsedTask.taskId}`,\n payload: {\n dispatchId: parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n source: observation.source,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n });\n return agentControllerConversationId;\n };\n let usageObservationAuthPromise: ReturnType<\n typeof probeAgentControllerUsageObservationAuth\n > | null = null;\n const syncAgentControllerConversationOccupancyLifecycle = (\n event: AdapterRuntimeEvent\n ) => {\n if (\n event.phase !== \"agent_controller_conversation_available\" &&\n event.phase !== \"agent_controller_conversation_occupied\"\n ) {\n return;\n }\n const occupancy = {\n agentControllerConversationId: event.agentControllerConversationId,\n contractVersion: event.contractVersion,\n state:\n event.phase === \"agent_controller_conversation_occupied\"\n ? (\"occupied\" as const)\n : (\"available\" as const),\n } satisfies RuntimeTransportAgentControllerConversationOccupancy;\n transitionDispatchLifecycle({\n agentControllerConversationOccupancy: occupancy,\n phase: runtimeLifecyclePhase,\n });\n };\n const syncProviderTurnAcceptedLifecycle = (\n event: AdapterRuntimeEvent\n ): void => {\n if (event.phase !== \"provider_turn_accepted\") {\n return;\n }\n completedTurnId = event.turnId;\n completedTurnConversationId = event.agentControllerConversationId;\n if (\n providerAdmissionOwnsRunningLifecycle &&\n runtimeLifecyclePhase !== \"running\"\n ) {\n transitionDispatchLifecycle({ phase: \"running\" });\n }\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: {\n agentControllerConversationId: event.agentControllerConversationId,\n turnId: event.turnId,\n },\n parsedTask,\n phase: \"provider_turn_accepted\",\n result: \"accepted\",\n });\n };\n const onNativeTurnStarted = async () => {\n await currentSocketRef.confirmExecutionAdmission?.(input.deliverRequest);\n completedTurnId = null;\n completedTurnConversationId = null;\n executionContextCompletion = undefined;\n completedNativeResult = null;\n };\n const onNativeTurnCompleted = (result: RuntimeTaskResult) => {\n completedNativeResult = result;\n };\n const onRuntimeEvent = routeReasoningEvents(observeReasoning, (event) => {\n observeWorkspaceProcess(event);\n syncAgentControllerConversationOccupancyLifecycle(event);\n syncProviderTurnAcceptedLifecycle(event);\n if (event.phase === \"tool_activity\") {\n agentToolActivitySequence += 1;\n emitDispatchAgentToolActivityFrame({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n event,\n parsedTask,\n presenter: input.presenter,\n sequence: agentToolActivitySequence,\n });\n }\n if (event.phase === \"provider_conversation_observed\") {\n recordProviderConversationObservation({\n agentControllerConversation:\n event.agentControllerConversation ?? null,\n agentControllerConversationId: event.agentControllerConversationId,\n source: \"runtime_event\",\n });\n }\n if (\n event.phase === \"provider_usage_limits_observed\" &&\n routeConfig?.launchContract\n ) {\n const agentId = runtimeControllerSupport.runtimeAdapterMatch.adapterId;\n const launchContract = routeConfig.launchContract;\n usageObservationAuthPromise ??=\n probeAgentControllerUsageObservationAuth({\n agentId,\n launchContract,\n });\n const recordUsageLimits = usageObservationAuthPromise.then(\n (authSnapshot) =>\n recordRuntimeProviderUsageLimits({\n agentId,\n authSnapshot,\n launchContract,\n usageLimits: event.usageLimits,\n })\n );\n recordUsageLimits\n .then((retained) => {\n if (retained) {\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_usage_limits_observation_ignored\",\n text: `provider usage limit observation could not be retained for task ${parsedTask.taskId}`,\n payload: {\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n observedLimitKeys: event.usageLimits.map((limit) => limit.key),\n reasonCode: \"provider_account_unconfirmed\",\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.provider_usage_limits_observation_ignored\",\n text: `provider usage limit observation could not be retained for task ${parsedTask.taskId}`,\n payload: {\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n observedLimitKeys: event.usageLimits.map((limit) => limit.key),\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n });\n }\n if (\n !firstOutputEvidenceSent &&\n (event.phase === \"first_stdout\" || event.phase === \"first_stderr\")\n ) {\n firstOutputEvidenceSent = true;\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n durationMs: Math.max(0, event.tsMs - runtimeStartedAtMs),\n parsedTask,\n phase: \"first_output\",\n presenter: input.presenter,\n });\n }\n const controlRegistrySyncResult =\n syncRuntimeEventToInflightTaskControlRegistry({\n event,\n registry: input.inflightTaskControlRegistry,\n taskId: parsedTask.taskId,\n });\n if (controlRegistrySyncResult.updated) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_registry_synced\",\n text: `control registry synced for task ${parsedTask.taskId}`,\n payload: {\n dispatchId: parsedTask.dispatchId,\n phase: event.phase,\n processId: controlRegistrySyncResult.processId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n },\n });\n }\n if (event.phase === \"process_spawned\" || event.phase === \"process_exit\") {\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: buildProviderProcessJournalMetadata({\n agentControllerRef: parsedTask.agentControllerRef,\n event,\n runtimeStartedAtMs,\n }),\n parsedTask,\n phase: event.phase,\n result: event.phase === \"process_exit\" ? \"exited\" : \"spawned\",\n });\n }\n emitProviderRuntimePhaseLine({\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n event,\n presenter: input.presenter,\n runtimeStartedAtMs,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n });\n clearReasoning();\n const runtimeExecutionPromise = Promise.resolve(\n runDispatchRuntimeExecution({\n computerFileAccessBoundary,\n contextId: contextIdForDispatch,\n executionMode: \"normal\",\n io: ledgerIo,\n ledgerPaths: input.ledgerPaths,\n onInteractionRequest,\n onNativeTurnStarted,\n onNativeTurnCompleted,\n onRuntimeEvent,\n onPreview: (preview) => {\n emitDispatchPreviewFrame({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n presenter: input.presenter,\n previewText: preview.text,\n taskId: parsedTask.taskId,\n });\n },\n parsedTask,\n instructionPrompt: runtimePromptPlan,\n prompt: runtimePromptPlan.fallbackPrompt,\n routeConfig,\n runtimeContext: activeRuntimeContext,\n runtimeEnvOverrides,\n runtimeControllerSupport,\n agentControllerConversationOverride,\n })\n );\n const controllerTurnCompletion = runtimeExecutionPromise.then(\n () => undefined,\n () => undefined\n );\n nativeQuiescence = controllerTurnCompletion;\n let runtimeResult = await resolveRuntimeResultFromRuntimeOrCliSpaceAction({\n contextIdForDispatch,\n dispatchSpaceActionContext,\n getObservedAgentControllerConversation: () =>\n observedProviderConversation,\n getObservedAgentControllerConversationId: () =>\n observedProviderConversationId,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n onRuntimeResultAfterCliSpaceAction: (runtimeResult) => {\n const runtimeContextDelta =\n resolveDispatchContextDeltaFromRuntimeResult(\n runtimeResult.dispatchResult\n );\n recordProviderConversationObservation({\n agentControllerConversation:\n runtimeResult.contextResolution?.agentControllerConversation ??\n runtimeContextDelta?.agentControllerConversation ??\n null,\n agentControllerConversationId:\n runtimeResult.contextResolution?.agentControllerConversationId ??\n runtimeContextDelta?.agentControllerConversationId ??\n null,\n source: \"runtime_result\",\n });\n },\n parsedTask,\n presenter: input.presenter,\n runtimeExecutionPromise,\n });\n const structuredSpaceActionOutcome =\n await resolveRuntimeResultStructuredSpaceAction({\n onInteractionRequest,\n onNativeTurnStarted,\n onNativeTurnCompleted,\n onRuntimeEvent,\n computerFileAccessBoundary,\n controllerTurnCompletion,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n instructionPrompt: runtimePromptPlan,\n parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n presenter: input.presenter,\n routeConfig,\n cliEntry: bootstrapContext.cliEntry,\n dispatchSpaceActionContext,\n runtimeResult,\n sendTargetReference,\n runtimeContext: activeRuntimeContext,\n runtimeEnvOverrides,\n runtimeControllerSupport,\n agentControllerConversationOverride,\n });\n runtimeResult = structuredSpaceActionOutcome.runtimeResult;\n resolvedSpaceAction = structuredSpaceActionOutcome.resolvedSpaceAction;\n resolvedSpaceActionProvenance =\n structuredSpaceActionOutcome.resolvedSpaceActionProvenance;\n emitRuntimeObservationSummaryLine({\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchId: parsedTask.dispatchId,\n presenter: input.presenter,\n runtimeResult,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n });\n\n const contextDelta = resolveDispatchContextDeltaFromRuntimeResult(\n runtimeResult.dispatchResult\n );\n const contextHealed =\n contextDelta?.refreshed === true ||\n resolveAdapterTelemetry(runtimeResult.dispatchResult)?.contextHealed ===\n true;\n continuityObservation = resolveDispatchContinuityObservation({\n contextHealed,\n existingContextId: contextIdForDispatch,\n resolvedContextId:\n normalizeOptionalContextId(\n runtimeResult.contextResolution?.agentControllerConversationId ??\n contextDelta?.agentControllerConversationId ??\n null\n ) ?? null,\n });\n await withLedgerStateTransaction({\n invalidStateStrategy,\n io: ledgerIo,\n mutate: (state) => {\n let nextState = state;\n if (contextDelta?.agentControllerConversationId) {\n nextState = commitResolvedAgentContext({\n state: nextState,\n agentContextLookupKey: contextLookupKey,\n agentControllerConversationId:\n contextDelta.agentControllerConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n spaceId: parsedTask.spaceId,\n targetProfileId: parsedTask.targetProfileId,\n transportMode: parsedTask.transportMode,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n activeRuntimeContext.providerRuntimeWorkingDirectory\n ),\n taskId: parsedTask.taskId,\n nowMs: Date.now(),\n });\n }\n const nextExecutionState =\n reconcileBootstrapInjectedContextAfterDispatch({\n executionState:\n resolveConversationExecutionStateByLookupKey({\n agentContextLookupKey: contextLookupKey,\n state: nextState,\n }) ?? currentExecutionState,\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n continuityObservation,\n contextHealed,\n dispatchedContextId:\n contextDelta?.agentControllerConversationId ?? null,\n effectiveRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n nowIso: new Date().toISOString(),\n resolvedAgentControllerConversation:\n contextDelta?.agentControllerConversation ??\n runtimeResult.contextResolution?.agentControllerConversation ??\n null,\n shouldInjectBootstrap: bootstrapPlan?.shouldInject === true,\n });\n if (nextExecutionState) {\n nextState = upsertConversationExecutionStateForLookupKey({\n state: nextState,\n executionState: nextExecutionState,\n replacedLookupKey:\n currentExecutionState?.agentContextLookupKey ?? null,\n targetLookupKey: contextLookupKey,\n });\n }\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n\n emitContextHealedLineIfNeeded({\n contextDelta,\n parsedTask,\n presenter: input.presenter,\n });\n\n const {\n bootstrapPlan: completedBootstrapPlan,\n ledgerIo: completedLedgerIo,\n localRuntimeContextPlan: completedLocalRuntimeContextPlan,\n runtimePromptPlan: completedRuntimePromptPlan,\n } = requireCompletedDispatchPlans({\n bootstrapPlan,\n ledgerIo,\n localRuntimeContextPlan,\n runtimePromptPlan,\n });\n const completedAgentControllerConversationOverride =\n agentControllerConversationOverride ?? null;\n const buildCurrentResultPayload =\n async (): Promise<OpenMeldDaemonTaskResultPayload> => {\n if (parsedTask.executionContext) {\n await controllerTurnCompletion;\n }\n const currentContextDelta =\n resolveDispatchContextDeltaFromRuntimeResult(\n runtimeResult.dispatchResult\n );\n const observedAgentControllerConversation =\n resolveObservedDispatchAgentControllerConversation({\n plannedAgentControllerConversation,\n contextDelta: currentContextDelta,\n contextResolution: runtimeResult.contextResolution ?? null,\n agentControllerConversationOverride:\n completedAgentControllerConversationOverride,\n });\n const finalNativeResult =\n completedNativeResult as RuntimeTaskResult | null;\n const nativeConversationId =\n (finalNativeResult\n ? resolveDispatchContextDeltaFromRuntimeResult(\n finalNativeResult.dispatchResult\n )?.agentControllerConversationId\n : null) ??\n finalNativeResult?.contextResolution?.agentControllerConversationId ??\n currentContextDelta?.agentControllerConversationId ??\n runtimeResult.contextResolution?.agentControllerConversationId ??\n observedAgentControllerConversation?.agentControllerConversationId ??\n observedProviderConversationId;\n executionContextCompletion = await captureExecutionContextCompletion({\n context: parsedTask.executionContext,\n nativeConversationId,\n agentControllerRef: parsedTask.agentControllerRef,\n workingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n completedTurnId:\n completedTurnConversationId === nativeConversationId\n ? completedTurnId\n : null,\n providerSucceeded:\n finalNativeResult?.resultPayload.status === \"success\" ||\n finalNativeResult?.resultPayload.status === \"partial_success\",\n });\n dispatchExecution = buildDispatchExecution({\n bootstrapPlan: completedBootstrapPlan,\n agentControllerConversationId: effectiveAgentControllerConversationId,\n localRuntimeContextPlan: completedLocalRuntimeContextPlan,\n observedAgentControllerConversation,\n plannedAgentControllerConversation,\n });\n return {\n ...resolveDispatchResultPayload({\n attemptId: parsedTask.attemptId,\n contextDelta: currentContextDelta,\n contextResolution: runtimeResult.contextResolution ?? null,\n basePayload: runtimeResult.resultPayload,\n bootstrapTemplateFacts: bootstrapContext.bootstrapTemplateFacts,\n agentControllerRef: parsedTask.agentControllerRef,\n dispatchExecution,\n existingContextId: contextIdForDispatch,\n openClawBinding: runtimeOpenClawBinding,\n openClawGatewayVisibility: runtimeOpenClawGatewayVisibility,\n promptTrace: runtimePromptTrace,\n agentControllerConversationForDispatch:\n observedAgentControllerConversation ??\n plannedAgentControllerConversation,\n workingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n spaceAction: resolvedSpaceAction,\n spaceActionProvenance: resolvedSpaceActionProvenance,\n sourceEventId: parsedTask.sourceEventId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n }),\n executionContextId: parsedTask.executionContext?.id,\n executionContextCompletion,\n };\n };\n resultPayload = await buildCurrentResultPayload();\n const replySettlement = await settleAgentReplyProposals({\n initialResultPayload: resultPayload,\n reconsider: async (agentReplyObservationCursor) => {\n const reconsidered = await resolveRuntimeResultStructuredSpaceAction({\n onInteractionRequest,\n onNativeTurnStarted,\n onNativeTurnCompleted,\n onRuntimeEvent,\n agentReplyObservationCursor,\n computerFileAccessBoundary,\n controllerTurnCompletion,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n ledgerIo: completedLedgerIo,\n ledgerPaths: input.ledgerPaths,\n instructionPrompt: completedRuntimePromptPlan,\n parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n presenter: input.presenter,\n routeConfig,\n cliEntry: bootstrapContext.cliEntry,\n dispatchSpaceActionContext,\n runtimeResult,\n sendTargetReference,\n runtimeContext: activeRuntimeContext,\n runtimeEnvOverrides,\n runtimeControllerSupport,\n agentControllerConversationOverride,\n });\n runtimeResult = reconsidered.runtimeResult;\n resolvedSpaceAction = reconsidered.resolvedSpaceAction;\n resolvedSpaceActionProvenance =\n reconsidered.resolvedSpaceActionProvenance;\n return await buildCurrentResultPayload();\n },\n submit: (payload) =>\n sendResultAndSummarize({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n emitCompletedLifecycle: false,\n executionIdentityEcho: toRuntimeTransportResultIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n payload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId:\n parsedTask.runtimeCoordinatorExecutionId,\n ledgerPaths: input.ledgerPaths,\n taskId: parsedTask.taskId,\n waitForSettlement: true,\n }),\n });\n resultPayload = replySettlement.resultPayload;\n settledResultSummary = replySettlement.resultSummary;\n const runtimeObservationPayload = buildRuntimeObservationPayload({\n continuityObservation,\n dispatchId: parsedTask.dispatchId,\n daemonWorkingDirectory,\n deliveryRecoveryReason: parsedTask.deliveryRecoveryReason,\n providerRuntimeWorkingDirectory:\n activeRuntimeContext.providerRuntimeWorkingDirectory,\n resultPayload,\n runtimeResult,\n runtimeStartedAtMs,\n taskId: parsedTask.taskId,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_completed\",\n text: `runtime completed for task ${parsedTask.taskId}`,\n payload: runtimeObservationPayload,\n });\n emitDispatchLocalPhaseJournalEvent({\n deliverRequest: input.deliverRequest,\n metadata: runtimeObservationPayload,\n parsedTask,\n phase: \"runtime_completed\",\n result: resultPayload.status,\n });\n emitContinuityWarningIfNeeded({\n continuityObservation,\n parsedTask,\n presenter: input.presenter,\n });\n } catch (error) {\n await rollbackBootstrapExecutionStateAfterFailureIfNeeded({\n bootstrapPlan,\n contextLookupKey,\n currentExecutionState,\n ledgerIo,\n ledgerPaths: input.ledgerPaths,\n });\n const runtimeFailedAtMs = Date.now();\n const typedError = toTaskExecutionErrorInternal(error);\n resultPayload = buildFailedTaskResultPayload({\n attemptId: parsedTask.attemptId,\n agentControllerRef: parsedTask.agentControllerRef,\n errorCode: typedError.errorCode,\n errorMessage: `${typedError.errorCode}: ${typedError.message}`,\n errorType: typedError.errorType,\n openClawBinding: runtimeOpenClawBinding,\n openClawGatewayVisibility: mergeOpenClawGatewayVisibilityInternal({\n primary: typedError.openClawGatewayVisibility,\n fallback: runtimeOpenClawGatewayVisibility,\n }),\n projectFailureContext: typedError.projectFailureContext,\n promptTrace: runtimePromptTrace,\n sourceEventId: parsedTask.sourceEventId,\n targetProfileId: parsedTask.targetProfileId,\n taskId: parsedTask.taskId,\n agentControllerConversation: agentControllerConversationOverride,\n ...(effectiveRuntimeContext\n ? {\n effectiveRuntimeWorkingDirectory:\n effectiveRuntimeContext.providerRuntimeWorkingDirectory,\n }\n : {}),\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_completed\",\n text: `runtime failed for task ${parsedTask.taskId}`,\n payload: {\n attemptId: parsedTask.attemptId,\n daemonWorkingDirectory,\n dispatchId: parsedTask.dispatchId,\n deliveryRecoveryReason: parsedTask.deliveryRecoveryReason,\n errorCode: typedError.errorCode,\n projectFailureContext: typedError.projectFailureContext,\n ...(effectiveRuntimeContext\n ? {\n providerRuntimeWorkingDirectory:\n effectiveRuntimeContext.providerRuntimeWorkingDirectory,\n }\n : {}),\n result: resultPayload.status,\n runtimeDurationMs: runtimeFailedAtMs - runtimeStartedAtMs,\n taskId: parsedTask.taskId,\n },\n });\n } finally {\n await nativeQuiescence;\n await releaseDispatchTaskWorkspace({\n workspaceUse,\n parsedTask,\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n workspaceProcesses,\n presenter: input.presenter,\n });\n reasoningStream.dispose();\n currentSocketRef.reasoningPreferenceListeners?.delete(clearReasoning);\n lifecycleKeepalive.stop?.();\n lifecycleKeepalive.stop = null;\n input.inflightDispatchMetaByTaskId.delete(parsedTask.taskId);\n input.inflightTaskControlRegistry.removeTask(parsedTask.taskId);\n pendingAgentInteractionRegistry.removeTask(parsedTask.taskId);\n }\n\n resultPayload = {\n ...resultPayload,\n executionContextId: parsedTask.executionContext?.id,\n executionContextCompletion,\n };\n\n emitDispatchRuntimeEvidenceTransition({\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n durationMs: Math.max(0, Date.now() - runtimeStartedAtMs),\n parsedTask,\n phase: resolveRuntimeEvidenceResultPhase(resultPayload),\n presenter: input.presenter,\n reasonCode: resolveRuntimeEvidenceResultReasonCode(resultPayload),\n });\n\n const resultSummary =\n settledResultSummary ??\n sendResultAndSummarize({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportResultIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n payload: resultPayload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId: parsedTask.runtimeCoordinatorExecutionId,\n ledgerPaths: input.ledgerPaths,\n taskId: parsedTask.taskId,\n }).resultSummary;\n emitDispatchPreviewEndFrame({\n attemptId: parsedTask.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: parsedTask.dispatchId,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n presenter: input.presenter,\n taskId: parsedTask.taskId,\n });\n return resultSummary;\n}\n\ntype ProviderProcessLifecycleEvent = Extract<\n AdapterRuntimeEvent,\n { phase: \"process_exit\" | \"process_spawned\" }\n>;\n\nfunction buildProviderProcessJournalMetadata(input: {\n agentControllerRef: string;\n event: ProviderProcessLifecycleEvent;\n runtimeStartedAtMs: number;\n}): Record<string, unknown> {\n const lifecycleMetadata =\n input.event.phase === \"process_exit\"\n ? {\n exitCode: input.event.exitCode,\n exitSignal: input.event.signal,\n }\n : {\n ...(input.event.processLaunchKind\n ? { processLaunchKind: input.event.processLaunchKind }\n : {}),\n ...(input.event.processWorkingDirectoryKind\n ? {\n processWorkingDirectoryKind:\n input.event.processWorkingDirectoryKind,\n }\n : {}),\n };\n return {\n agentControllerRef: input.agentControllerRef,\n ...lifecycleMetadata,\n phaseTsMs: input.event.tsMs,\n processId: input.event.processId,\n signalTarget: input.event.signalTarget,\n sinceRuntimeStartedMs: Math.max(\n 0,\n input.event.tsMs - input.runtimeStartedAtMs\n ),\n };\n}\n\nfunction emitSendTargetReferenceLoadFailureIfNeeded(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n}): void {\n if (input.sendTargetReference.status !== \"failed\") {\n return;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.send_target_reference_load_failed\",\n text: `send target reference load failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: input.sendTargetReference.errorMessage,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n}\n\nfunction emitDispatchImageAttachmentPreparation(input: {\n parsedTask: ParsedDispatchTask;\n preparation: DispatchImageAttachmentPreparation;\n presenter: Presenter;\n}): void {\n for (const failure of input.preparation.failures) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.attachment_download_failed\",\n text: `image attachment unavailable for task ${input.parsedTask.taskId}`,\n payload: {\n attachmentId: failure.attachment.id,\n dispatchId: input.parsedTask.dispatchId,\n errorCode: failure.errorCode,\n errorMessage: failure.errorMessage,\n mimeType: failure.attachment.mimeType,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n }\n}\n\nasync function prepareBootstrapExecutionStateIfNeeded(input: {\n bootstrapPlan: BootstrapPlan;\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n contextIdForDispatch: string | null;\n contextLookupKey: string;\n currentExecutionState: ConversationExecutionState | null;\n effectiveRuntimeWorkingDirectory: string;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n}): Promise<void> {\n if (!input.bootstrapPlan.shouldInject) {\n return;\n }\n\n await withLedgerStateTransaction({\n invalidStateStrategy: \"backup_and_reset\",\n io: input.ledgerIo,\n mutate: (state) => {\n const latestExecutionState =\n resolveConversationExecutionStateByLookupKey({\n agentContextLookupKey: input.contextLookupKey,\n state,\n }) ?? input.currentExecutionState;\n const nextState = upsertConversationExecutionStateForLookupKey({\n state,\n executionState: markBootstrapInjectedContext({\n executionState: latestExecutionState,\n agentContextLookupKey: input.contextLookupKey,\n bootstrapTemplateFacts: input.bootstrapTemplateFacts,\n existingContextId: input.contextIdForDispatch,\n effectiveRuntimeWorkingDirectory:\n input.effectiveRuntimeWorkingDirectory,\n nowIso: new Date().toISOString(),\n }),\n replacedLookupKey: latestExecutionState?.agentContextLookupKey ?? null,\n targetLookupKey: input.contextLookupKey,\n });\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.bootstrap_injected\",\n text: `bootstrap injected for ${input.parsedTask.spaceId}/${input.parsedTask.targetProfileId}`,\n payload: {\n bootstrapReason: input.bootstrapPlan.reason,\n dispatchId: input.parsedTask.dispatchId,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n },\n });\n}\n\nfunction emitContextHealedLineIfNeeded(input: {\n contextDelta: AdapterDispatchContextDelta | null;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n}): void {\n if (input.contextDelta?.refreshed !== true) {\n return;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.context_healed\",\n text: `context healed once for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n taskId: input.parsedTask.taskId,\n targetProfileId: input.parsedTask.targetProfileId,\n },\n });\n}\n\nasync function rollbackBootstrapExecutionStateAfterFailureIfNeeded(input: {\n bootstrapPlan: BootstrapPlan | null;\n contextLookupKey: string;\n currentExecutionState: ConversationExecutionState | null;\n ledgerIo: ReturnType<typeof createLedgerIo> | null;\n ledgerPaths: LedgerPaths;\n}): Promise<void> {\n if (!(input.bootstrapPlan?.shouldInject && input.ledgerIo)) {\n return;\n }\n\n await withLedgerStateTransaction({\n invalidStateStrategy: \"backup_and_reset\",\n io: input.ledgerIo,\n mutate: (state) => {\n const nextState = rollbackBootstrapExecutionStateAfterDispatchFailure({\n agentContextLookupKey: input.contextLookupKey,\n executionStateBeforeDispatch: input.currentExecutionState,\n state,\n });\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n}\n\nasync function verifyDispatchLegacyContextAssociation(input: {\n parsedTask: ParsedDispatchTask;\n ledgerPaths: LedgerPaths;\n originalWorkingDirectory: string;\n}): Promise<void> {\n const association = input.parsedTask.executionContext?.legacyAssociation;\n if (!association) {\n return;\n }\n const state = await loadLedgerState({\n invalidStateStrategy: \"throw\",\n io: createLedgerIo(),\n paths: input.ledgerPaths,\n });\n assertLegacyAgentContextAssociation({\n state,\n legacyNativeConversationId: association.nativeConversationId,\n key: {\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n transportMode: input.parsedTask.transportMode,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n input.originalWorkingDirectory\n ),\n },\n });\n}\n\nasync function loadDispatchLedgerContext(input: {\n contextStore: Map<string, string>;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n runtimeWorkspaceFingerprint: string;\n originalWorkingDirectory: string;\n}): Promise<{\n contextLookupKey: string;\n currentExecutionState: ConversationExecutionState | null;\n existingContextId: string | null;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n latestScopedExecutionState: ConversationExecutionState | null;\n}> {\n const keyInput = {\n executionContextId: input.parsedTask.executionContext?.id,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n transportMode: input.parsedTask.transportMode,\n runtimeWorkspaceFingerprint: input.runtimeWorkspaceFingerprint,\n } as const;\n const contextLookupKey = buildAgentContextLookupKey(keyInput);\n const ledgerIo = createLedgerIo();\n const legacyContextId = input.contextStore.get(contextLookupKey) ?? null;\n const {\n currentExecutionState,\n existingContextId,\n latestScopedExecutionState,\n } = await withLedgerStateTransaction({\n invalidStateStrategy: executionContextLedgerPolicy(\n input.parsedTask.executionContext\n ),\n io: ledgerIo,\n mutate: (state) => {\n const scopeInput = {\n agentControllerRef: input.parsedTask.agentControllerRef,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n transportMode: input.parsedTask.transportMode,\n } as const;\n assertLegacyAgentContextAssociation({\n state,\n legacyNativeConversationId:\n input.parsedTask.executionContext?.legacyAssociation\n ?.nativeConversationId,\n key: {\n ...scopeInput,\n runtimeWorkspaceFingerprint: buildRuntimeWorkspaceFingerprint(\n input.originalWorkingDirectory\n ),\n },\n });\n const existingAgentContextMatch = resolveCompatibleAgentContextMatch({\n key: keyInput,\n state,\n });\n const seededLedgerState = existingAgentContextMatch\n ? state\n : seedLegacyAgentContext({\n state,\n agentContextLookupKey: contextLookupKey,\n legacyAgentControllerConversationId: legacyContextId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n transportMode: input.parsedTask.transportMode,\n runtimeWorkspaceFingerprint: input.runtimeWorkspaceFingerprint,\n taskId: input.parsedTask.taskId,\n nowMs: Date.now(),\n });\n const nextAgentContextMatch = resolveCompatibleAgentContextMatch({\n key: keyInput,\n state: seededLedgerState,\n });\n const existingContextId =\n nextAgentContextMatch?.agentContext.agentControllerConversationId ??\n null;\n const currentExecutionState = resolveCompatibleConversationExecutionState(\n {\n key: keyInput,\n preferredLookupKey:\n nextAgentContextMatch?.agentContextLookupKey ?? null,\n state: seededLedgerState,\n }\n );\n const latestScopedExecutionState = input.parsedTask.executionContext\n ? currentExecutionState\n : (resolveLatestScopedConversationExecutionState({\n scope: scopeInput,\n state: seededLedgerState,\n })?.executionState ?? null);\n return {\n nextState: seededLedgerState,\n value: {\n currentExecutionState,\n existingContextId,\n latestScopedExecutionState,\n },\n };\n },\n paths: input.ledgerPaths,\n });\n\n return {\n contextLookupKey,\n currentExecutionState,\n existingContextId,\n ledgerIo,\n latestScopedExecutionState,\n };\n}\n\ntype DispatchBootstrapContext = {\n bootstrapTemplateFacts: BootstrapTemplateFacts;\n cliEntry: string | null;\n mentionSourceMentionLabel: string | null;\n mentionSourceProfileName: string | null;\n sendTargetReferencePromise: Promise<DispatchSendTargetReferenceLoadResult>;\n spaceGuide: string | null;\n spaceName: string | null;\n spaceOwnerProfileId: string | null;\n spacePurpose: string | null;\n targetProfileMentionLabel: string | null;\n targetProfileName: string | null;\n targetProfileRole: string | null;\n};\n\ntype DispatchSpaceMetaLoadResult =\n | {\n status: \"loaded\";\n spaceGuide: string | null;\n spaceName: string | null;\n spacePurpose: string | null;\n }\n | {\n status: \"failed\";\n errorMessage: string;\n spaceGuide: null;\n spaceName: null;\n spacePurpose: null;\n };\n\nasync function resolveDispatchBootstrapContext(input: {\n onPhase?: (\n phase: DispatchBootstrapContextPhase,\n metadata: Record<string, unknown>\n ) => void;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n parsedTask: ParsedDispatchTask;\n}): Promise<DispatchBootstrapContext> {\n const [\n spaceOwnerProfileId,\n targetProfileContext,\n mentionSourceContext,\n spaceMetaContext,\n ] = await Promise.all([\n resolveBootstrapSpaceOwnerProfileId({\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n }),\n resolveBootstrapTargetProfileContext({\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n preferredMentionLabel: input.parsedTask.targetProfileMentionLabel,\n preferredProfileName: input.parsedTask.targetProfileName,\n }),\n resolveDispatchMentionSourceContext({\n spaceId: input.parsedTask.spaceId,\n mentionSourceProfileId: input.parsedTask.mentionSourceProfileId,\n preferredMentionLabel: input.parsedTask.mentionSourceProfileMentionLabel,\n }),\n resolveDispatchSpaceMetaContext({\n parsedTask: input.parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n }),\n ]);\n input.onPhase?.(\"bootstrap_context_ready\", {\n mentionSourceMentionLabelPresent:\n mentionSourceContext.mentionSourceMentionLabel !== null,\n mentionSourceProfileNamePresent:\n mentionSourceContext.mentionSourceProfileName !== null,\n source: \"dispatch_bootstrap_context\",\n spaceGuidePresent: spaceMetaContext.spaceGuide !== null,\n spaceMetaError:\n spaceMetaContext.status === \"failed\"\n ? spaceMetaContext.errorMessage\n : null,\n spaceMetaStatus: spaceMetaContext.status,\n spaceNamePresent: spaceMetaContext.spaceName !== null,\n spaceOwnerProfilePresent: spaceOwnerProfileId !== null,\n spacePurposePresent: spaceMetaContext.spacePurpose !== null,\n targetProfileMentionLabelPresent:\n targetProfileContext.targetProfileMentionLabel !== null,\n targetProfileNamePresent: targetProfileContext.targetProfileName !== null,\n targetProfileRolePresent: targetProfileContext.targetProfileRole !== null,\n });\n // Deliberately not awaited here: the member-directory load is a network\n // round trip that nothing in local runtime/ledger preparation depends on,\n // so it runs concurrently with that local work and is awaited at its first\n // real consumer. The phase event fires when the load actually resolves.\n // The loader never rejects (it returns a \"failed\" result), so this floating\n // promise cannot produce an unhandled rejection.\n const sendTargetReferencePromise = resolveDispatchSendTargetReference({\n agentControllerRef: input.parsedTask.agentControllerRef,\n dispatchTask: input.parsedTask,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n targetProfileName: targetProfileContext.targetProfileName,\n }).then((sendTargetReference) => {\n input.onPhase?.(\"send_target_reference_ready\", {\n sendTargetReferenceCount:\n sendTargetReference.status === \"loaded\"\n ? sendTargetReference.projection.length\n : null,\n sendTargetReferenceStatus: sendTargetReference.status,\n source: \"dispatch_send_target_reference\",\n });\n return sendTargetReference;\n });\n const cliEntry = DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND;\n const bootstrapTemplateFacts = buildDispatchBootstrapTemplateFacts({\n dispatchTriggerSource: input.parsedTask.dispatchTriggerSource,\n mentionSourceProfileId: input.parsedTask.mentionSourceProfileId,\n mentionSourceProfileKind: input.parsedTask.mentionSourceProfileKind,\n ...mentionSourceContext,\n spaceId: input.parsedTask.spaceId,\n spaceGuide: spaceMetaContext.spaceGuide,\n spaceName: spaceMetaContext.spaceName,\n spaceOwnerProfileId,\n spacePurpose: spaceMetaContext.spacePurpose,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n ...targetProfileContext,\n targetProfileId: input.parsedTask.targetProfileId,\n cliEntry,\n });\n\n return {\n bootstrapTemplateFacts,\n cliEntry,\n mentionSourceMentionLabel:\n mentionSourceContext.mentionSourceMentionLabel ?? null,\n mentionSourceProfileName: mentionSourceContext.mentionSourceProfileName,\n sendTargetReferencePromise,\n spaceGuide: spaceMetaContext.spaceGuide,\n spaceName: spaceMetaContext.spaceName,\n spaceOwnerProfileId,\n spacePurpose: spaceMetaContext.spacePurpose,\n targetProfileMentionLabel: targetProfileContext.targetProfileMentionLabel,\n targetProfileName: targetProfileContext.targetProfileName,\n targetProfileRole: targetProfileContext.targetProfileRole,\n };\n}\n\nasync function resolveDispatchSpaceMetaContext(input: {\n parsedTask: ParsedDispatchTask;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n}): Promise<DispatchSpaceMetaLoadResult> {\n try {\n const baseUrl = await resolveBaseUrl();\n const requestContext = buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n openMeldProfileId: input.parsedTask.targetProfileId,\n profileKind: \"agent\",\n ownerUserId: input.profileOwnerUserId,\n ...(input.profileOwnerName\n ? { ownerName: input.profileOwnerName }\n : {}),\n profileName:\n input.parsedTask.targetProfileName ??\n input.parsedTask.targetProfileMentionLabel ??\n input.parsedTask.targetProfileId,\n },\n });\n const meta = await fetchSpaceMeta({\n baseUrl,\n requestContext,\n space: input.parsedTask.spaceId,\n ...(input.parsedTask.spacePassword\n ? { password: input.parsedTask.spacePassword }\n : {}),\n });\n return {\n status: \"loaded\",\n spaceGuide: normalizeOptionalText(meta.guide),\n spaceName: normalizeOptionalText(meta.name),\n spacePurpose: normalizeOptionalText(meta.purpose),\n };\n } catch (error) {\n return {\n status: \"failed\",\n errorMessage: toErrorMessage(error),\n spaceGuide: null,\n spaceName: null,\n spacePurpose: null,\n };\n }\n}\n\nfunction buildDispatchRuntimePrompt(input: {\n bootstrapContext: DispatchBootstrapContext;\n imageAttachmentPreparation: DispatchImageAttachmentPreparation;\n parsedTask: ParsedDispatchTask;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n shouldInjectBootstrap: boolean;\n taskWorkspace?: ExecutionContextWorkspace;\n}): DispatchPromptPlan {\n return buildDispatchPromptPlan({\n callerContext: input.parsedTask.callerContext,\n shouldInjectBootstrap: input.shouldInjectBootstrap,\n shouldInjectCenterAgentRoleTemplate:\n input.parsedTask.targetProfileIsCenterAgent,\n dispatchTriggerSource: input.parsedTask.dispatchTriggerSource,\n imageAttachmentPromptSection:\n input.imageAttachmentPreparation.promptSection,\n spaceFiles: input.parsedTask.files,\n mentionSourceProfileId: input.parsedTask.mentionSourceProfileId,\n mentionSourceProfileKind: input.parsedTask.mentionSourceProfileKind,\n mentionSourceMentionLabel: input.bootstrapContext.mentionSourceMentionLabel,\n mentionSourceProfileName: input.bootstrapContext.mentionSourceProfileName,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n organizationProtectedInformation:\n input.parsedTask.organizationProtectedInformation,\n workingLanguage: input.parsedTask.workingLanguage,\n prompt: input.taskWorkspace?.baseCommit\n ? `${input.parsedTask.prompt}\\n\\nOpenMeld task workspace: ${JSON.stringify(\n {\n projectId: input.parsedTask.defaultProjectId,\n repositoryName: input.taskWorkspace.sourceWorkingDirectory\n ? basename(input.taskWorkspace.sourceWorkingDirectory)\n : null,\n workingDirectory: input.taskWorkspace.workingDirectory,\n baseCommit: input.taskWorkspace.baseCommit,\n }\n )}\\nThis task uses an independent Git worktree with private Git metadata. The starting commit is frozen. Uncommitted and ignored source files were not copied. Make changes in this task worktree; the original checkout is not the task's working directory. Refer to the task and commit in public replies without disclosing private local paths.`\n : input.parsedTask.prompt,\n recipientExplicitlyAddressedByActivationTargets:\n input.parsedTask.recipientExplicitlyAddressedByActivationTargets,\n sourceSignalId: input.parsedTask.sourceEventId,\n sourceMessageEnvelope: input.parsedTask.sourceMessageEnvelope,\n sendTargetReferenceLines: input.sendTargetReference.referenceLines,\n spaceId: input.parsedTask.spaceId,\n spaceGuide: input.bootstrapContext.spaceGuide,\n spaceName: input.bootstrapContext.spaceName,\n spaceOwnerProfileId: input.bootstrapContext.spaceOwnerProfileId,\n spacePurpose: input.bootstrapContext.spacePurpose,\n targetProfileMentionLabel: input.bootstrapContext.targetProfileMentionLabel,\n targetProfileName: input.bootstrapContext.targetProfileName,\n targetProfileRole: input.bootstrapContext.targetProfileRole,\n cliEntry: input.bootstrapContext.cliEntry,\n continuitySnapshot: input.parsedTask.continuitySnapshot,\n replyToSnapshot: input.parsedTask.replyToSnapshot,\n threadContext: input.parsedTask.threadContext,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n targetProfileId: input.parsedTask.targetProfileId,\n });\n}\n\nasync function prepareDispatchTaskWorkspace(input: {\n parsedTask: ParsedDispatchTask;\n ledgerRootPath: string;\n currentWorkingDirectory: string;\n computerFileAccessStorePath: string;\n}): Promise<ExecutionContextWorkspace> {\n const context = input.parsedTask.executionContext;\n if (context && context.access !== \"space_context\") {\n return await prepareExecutionContextWorkspace({\n context,\n ledgerRootPath: input.ledgerRootPath,\n currentWorkingDirectory: input.currentWorkingDirectory,\n policy: await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n ),\n });\n }\n const workingDirectory = await executionContextWorkingDirectory({\n context,\n ledgerRootPath: input.ledgerRootPath,\n currentWorkingDirectory: input.currentWorkingDirectory,\n });\n return { workingDirectory, boundaryRoot: workingDirectory };\n}\n\nasync function releaseDispatchTaskWorkspace(input: {\n workspaceUse: ExecutionContextWorkspaceUse | null;\n parsedTask: ParsedDispatchTask;\n ledgerRootPath: string;\n workspaceProcesses: Map<number | null, boolean>;\n presenter: Presenter;\n}): Promise<void> {\n const context = input.parsedTask.executionContext;\n if (!(input.workspaceUse && context)) {\n return;\n }\n try {\n const released = await releaseExecutionContextWorkspace({\n ledgerRootPath: input.ledgerRootPath,\n context,\n use: input.workspaceUse,\n // Codex reports process_spawned synchronously before native work. An\n // empty set after a settled preflight error means no process was started.\n ownedProcessesQuiescent: [...input.workspaceProcesses.values()].every(\n Boolean\n ),\n });\n emitRunLine({\n presenter: input.presenter,\n code: `daemon.run.workspace_${released.status}`,\n text:\n released.status === \"released\"\n ? \"Reclaimed the unchanged task workspace.\"\n : \"Retained the task workspace.\",\n payload: { contextId: context.id, ...released },\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.workspace_retained\",\n text: \"Task workspace cleanup needs reconciliation.\",\n payload: { contextId: context.id, errorMessage: toErrorMessage(error) },\n });\n }\n}\n\nfunction observeExecutionContextWorkspaceProcess(\n processes: Map<number | null, boolean>,\n event: AdapterRuntimeEvent\n): void {\n if (event.phase === \"process_spawned\") {\n processes.set(event.processId, false);\n } else if (event.phase === \"process_exit\") {\n processes.set(event.processId, event.ownedProcessesQuiescent === true);\n }\n}\n\nasync function resolveDispatchComputerFileAccess(input: {\n computerFileAccessStorePath: string;\n onInteractionRequest: AdapterInteractionCallback;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n runtimePreparation: DispatchRuntimePreparation;\n taskWorkspace?: ExecutionContextWorkspace;\n}): Promise<AdapterComputerFileAccessBoundary | null> {\n const policy = await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n );\n const verifier =\n input.runtimeControllerSupport.localAdapterEntry.adapter\n .verifyComputerFileAccessBoundary;\n if (input.parsedTask.executionContext) {\n const context = input.parsedTask.executionContext;\n if (\n input.parsedTask.agentControllerRef === \"builtin:claude-code\" &&\n context.access === \"space_context\"\n ) {\n return null;\n }\n if (\n input.parsedTask.agentControllerRef !== \"builtin:codex\" ||\n input.parsedTask.transportMode !== \"codex-app-server\" ||\n !verifier\n ) {\n throw new Error(\"execution_context.file_access_unsupported\");\n }\n const workingDirectory =\n input.runtimePreparation.effectiveRuntimeContext\n .providerRuntimeWorkingDirectory;\n const boundary = executionContextFileAccessBoundary({\n context,\n workingDirectory,\n policy,\n taskWorkspace: input.taskWorkspace,\n workingCopyId: input.parsedTask.workingCopyId,\n });\n const verification = await verifier({\n boundary,\n workingDirectory,\n executionMode: \"normal\",\n agentControllerPermissionMode:\n input.routeConfig?.agentControllerPermissionMode,\n launchContract: input.routeConfig?.launchContract ?? null,\n transportMode: input.parsedTask.transportMode,\n });\n if (!verification.supported) {\n throw new Error(\"execution_context.file_access_unverified\");\n }\n return boundary;\n }\n const admission = await resolveComputerFileAccessAdmission({\n agentControllerPermissionMode:\n input.routeConfig?.agentControllerPermissionMode,\n agentControllerRef: input.parsedTask.agentControllerRef,\n onInteractionRequest: input.onInteractionRequest,\n policy,\n providerRuntimeWorkingDirectory:\n input.runtimePreparation.effectiveRuntimeContext\n .providerRuntimeWorkingDirectory,\n transportMode: input.parsedTask.transportMode,\n ...(verifier\n ? {\n verifyBoundary: async (boundary) => {\n const verification = await verifier({\n agentControllerPermissionMode:\n input.routeConfig?.agentControllerPermissionMode,\n boundary,\n executionMode: \"normal\",\n launchContract: input.routeConfig?.launchContract ?? null,\n transportMode: input.parsedTask.transportMode,\n workingDirectory:\n input.runtimePreparation.effectiveRuntimeContext\n .providerRuntimeWorkingDirectory,\n });\n return verification;\n },\n }\n : {}),\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.computer_file_access_resolved\",\n text: `Computer file access resolved for task ${input.parsedTask.taskId}`,\n payload: {\n boundaryApplied: admission.boundary !== null,\n bypassedForThisRun: admission.bypassedForThisRun,\n dispatchId: input.parsedTask.dispatchId,\n mode: policy.mode,\n revision: policy.revision,\n taskId: input.parsedTask.taskId,\n },\n });\n return admission.boundary;\n}\n\nfunction createDispatchSpaceActionRuntimeContext(input: {\n bootstrapContext: DispatchBootstrapContext;\n parsedTask: ParsedDispatchTask;\n runtimePreparation: DispatchRuntimePreparation;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n}): {\n dispatchSpaceActionContext: DispatchSpaceActionContext;\n runtimeEnvOverrides: Record<string, string | undefined> | undefined;\n} {\n const contextResult = createDispatchSpaceActionContext({\n workingCopyId: input.parsedTask.workingCopyId,\n attemptId: input.parsedTask.attemptId,\n dispatchId: input.parsedTask.dispatchId,\n env: process.env,\n replyToSignalId: input.parsedTask.replyToSnapshot?.signalId ?? null,\n sendTargetReference: input.sendTargetReference,\n sourceEventId: input.parsedTask.sourceEventId,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n });\n\n return {\n dispatchSpaceActionContext: contextResult.context,\n runtimeEnvOverrides: {\n ...(input.runtimePreparation.runtimeEnvOverrides ?? {}),\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]: contextResult.contextPath,\n },\n };\n}\n\nexport async function resolveRuntimeResultFromRuntimeOrCliSpaceAction(input: {\n contextIdForDispatch: string | null;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n getObservedAgentControllerConversation?: () => AgentControllerConversationRef | null;\n getObservedAgentControllerConversationId?: () => string | null;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n onRuntimeResultAfterCliSpaceAction?: (\n runtimeResult: RuntimeTaskResult\n ) => Promise<void> | void;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): Promise<RuntimeTaskResult> {\n if (!input.dispatchSpaceActionContext) {\n return await input.runtimeExecutionPromise;\n }\n if (input.parsedTask.executionContext) {\n return await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult: await input.runtimeExecutionPromise,\n });\n }\n\n const cliSpaceActionAbortController = new AbortController();\n let completion: DispatchRuntimeCompletion;\n try {\n completion = await Promise.race([\n input.runtimeExecutionPromise.then(\n (runtimeResult): DispatchRuntimeCompletion => ({\n kind: \"runtime\",\n runtimeResult,\n })\n ),\n waitForCliSpaceActionRecord({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n signal: cliSpaceActionAbortController.signal,\n }),\n ]);\n } finally {\n cliSpaceActionAbortController.abort();\n }\n\n if (completion.kind === \"runtime\") {\n return await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult: completion.runtimeResult,\n });\n }\n\n if (completion.kind === \"cli_space_action_poll_aborted\") {\n return await input.runtimeExecutionPromise;\n }\n\n if (completion.kind === \"cli_space_action_invalid\") {\n throw new DaemonServiceRunError({\n code: \"dispatch.cli_space_action.invalid\",\n message: completion.errorMessage,\n });\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.cli_space_action_finalized\",\n text: `CLI OpenMeld Space Action finalized task ${input.parsedTask.taskId}`,\n payload: {\n command: completion.record.command,\n dispatchId: input.parsedTask.dispatchId,\n spaceActionType: completion.record.action.type,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n const completedRuntimeResult =\n await resolveAlreadyCompletedRuntimeResultAfterCliSpaceAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeExecutionPromise: input.runtimeExecutionPromise,\n });\n if (completedRuntimeResult) {\n return applyCliSpaceActionRecordToRuntimeResult({\n record: completion.record,\n runtimeResult: completedRuntimeResult,\n });\n }\n\n const postActionCompletion =\n await resolveRuntimeResultOrObservedProviderConversationAfterCliSpaceAction(\n {\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n runtimeExecutionPromise: input.runtimeExecutionPromise,\n }\n );\n if (postActionCompletion?.kind === \"runtime\") {\n return applyCliSpaceActionRecordToRuntimeResult({\n record: completion.record,\n runtimeResult: postActionCompletion.runtimeResult,\n });\n }\n\n observeRuntimeResultAfterCliSpaceAction({\n onRuntimeResultAfterCliSpaceAction:\n input.onRuntimeResultAfterCliSpaceAction,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeExecutionPromise: input.runtimeExecutionPromise,\n });\n const observedAgentControllerConversation =\n postActionCompletion?.kind === \"provider_conversation\"\n ? postActionCompletion.agentControllerConversation\n : resolveObservedProviderConversationForCliSpaceAction({\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n });\n\n return await buildCliSpaceActionRuntimeResult({\n agentControllerConversation: observedAgentControllerConversation,\n agentControllerConversationId:\n observedAgentControllerConversation?.agentControllerConversationId ??\n null,\n ledgerIo: input.ledgerIo,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n record: completion.record,\n });\n}\n\nexport function resolveEffectiveAgentControllerConversationId(input: {\n agentControllerConversationId: string | null;\n existingContextId: string | null;\n}): string | null {\n const bindingConversationId = normalizeOptionalContextId(\n input.agentControllerConversationId\n );\n if (bindingConversationId) {\n return bindingConversationId;\n }\n return normalizeOptionalContextId(input.existingContextId);\n}\n\ntype CliSpaceActionPostActionCompletion =\n | {\n kind: \"provider_conversation\";\n agentControllerConversation: AgentControllerConversationRef;\n }\n | {\n kind: \"runtime\";\n runtimeResult: RuntimeTaskResult;\n };\n\nasync function resolveRuntimeResultOrObservedProviderConversationAfterCliSpaceAction(input: {\n contextIdForDispatch: string | null;\n getObservedAgentControllerConversation?: () => AgentControllerConversationRef | null;\n getObservedAgentControllerConversationId?: () => string | null;\n parsedTask: ParsedDispatchTask;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): Promise<CliSpaceActionPostActionCompletion | null> {\n const existingConversation =\n resolveObservedProviderConversationForCliSpaceAction({\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n });\n if (existingConversation) {\n return {\n kind: \"provider_conversation\",\n agentControllerConversation: existingConversation,\n };\n }\n\n const deadlineMs =\n Date.now() + CLI_SPACE_ACTION_PROVIDER_CONVERSATION_GRACE_MS;\n const runtimeCompletion = input.runtimeExecutionPromise.then(\n (runtimeResult) => ({ runtimeResult, status: \"runtime\" as const }),\n (error) => ({ error, status: \"runtime_error\" as const })\n );\n\n while (Date.now() < deadlineMs) {\n const remainingMs = Math.max(0, deadlineMs - Date.now());\n const waitMs = Math.min(\n CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS,\n remainingMs\n );\n const result = await Promise.race([\n runtimeCompletion,\n delay(waitMs).then(() => ({ status: \"pending\" as const })),\n ]);\n\n if (result.status === \"runtime\") {\n return {\n kind: \"runtime\",\n runtimeResult: result.runtimeResult,\n };\n }\n if (result.status === \"runtime_error\") {\n return null;\n }\n\n const observedConversation =\n resolveObservedProviderConversationForCliSpaceAction({\n contextIdForDispatch: input.contextIdForDispatch,\n getObservedAgentControllerConversation:\n input.getObservedAgentControllerConversation,\n getObservedAgentControllerConversationId:\n input.getObservedAgentControllerConversationId,\n parsedTask: input.parsedTask,\n });\n if (observedConversation) {\n return {\n kind: \"provider_conversation\",\n agentControllerConversation: observedConversation,\n };\n }\n }\n\n return null;\n}\n\nfunction resolveObservedProviderConversationForCliSpaceAction(input: {\n contextIdForDispatch: string | null;\n getObservedAgentControllerConversation?: () => AgentControllerConversationRef | null;\n getObservedAgentControllerConversationId?: () => string | null;\n parsedTask: ParsedDispatchTask;\n}): AgentControllerConversationRef | null {\n const observedAgentControllerConversation =\n input.getObservedAgentControllerConversation?.() ?? null;\n if (observedAgentControllerConversation) {\n return observedAgentControllerConversation;\n }\n\n const observedAgentControllerConversationId =\n normalizeOptionalContextId(\n input.getObservedAgentControllerConversationId?.() ?? null\n ) ?? input.contextIdForDispatch;\n return buildAgentControllerConversationRefFromAgentControllerConversation({\n agentControllerConversationId: observedAgentControllerConversationId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n });\n}\n\nasync function waitForCliSpaceActionRecord(input: {\n dispatchSpaceActionContext: DispatchSpaceActionContext;\n signal: AbortSignal;\n}): Promise<DispatchRuntimeCompletion> {\n while (!input.signal.aborted) {\n const readResult = readDispatchSpaceActionRecord({\n context: input.dispatchSpaceActionContext,\n });\n if (readResult.status === \"loaded\") {\n return {\n kind: \"cli_space_action_recorded\",\n record: readResult.record,\n };\n }\n if (readResult.status === \"invalid\") {\n return {\n kind: \"cli_space_action_invalid\",\n errorMessage: readResult.errorMessage,\n };\n }\n try {\n await delay(CLI_SPACE_ACTION_RECORD_POLL_INTERVAL_MS, undefined, {\n signal: input.signal,\n });\n } catch (error) {\n if (input.signal.aborted) {\n return {\n kind: \"cli_space_action_poll_aborted\",\n };\n }\n throw error;\n }\n }\n\n return {\n kind: \"cli_space_action_poll_aborted\",\n };\n}\n\nasync function buildCliSpaceActionRuntimeResult(input: {\n agentControllerConversation: AgentControllerConversationRef | null;\n agentControllerConversationId: string | null;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n record: DispatchSpaceActionRecord;\n}): Promise<RuntimeTaskResult> {\n const resultPayload = buildCliSpaceActionSuccessPayload({\n basePayload: {\n agentId: input.parsedTask.targetProfileId,\n attemptId: input.parsedTask.attemptId,\n deduped: false,\n sourceEventId: input.parsedTask.sourceEventId,\n taskId: input.parsedTask.taskId,\n ...(input.agentControllerConversation\n ? {\n agentControllerConversation: input.agentControllerConversation,\n }\n : {}),\n ...(input.agentControllerConversationId\n ? {\n agentControllerConversationId: input.agentControllerConversationId,\n }\n : {}),\n ...(input.parsedTask.agentControllerRef\n ? { agentControllerRef: input.parsedTask.agentControllerRef }\n : {}),\n ...(input.parsedTask.transportMode\n ? { transportMode: input.parsedTask.transportMode }\n : {}),\n },\n record: input.record,\n });\n const state = await withLedgerStateTransaction({\n invalidStateStrategy: \"backup_and_reset\",\n io: input.ledgerIo,\n mutate: (state) => {\n const nextState = settleInflightTask({\n state,\n taskId: input.parsedTask.taskId,\n });\n return {\n nextState,\n value: nextState,\n };\n },\n paths: input.ledgerPaths,\n });\n await appendLedgerHistoryEntry({\n entry: {\n message: \"task finalized from CLI Space Action\",\n reasonCode: \"task.cli_space_action\",\n status: resultPayload.status,\n taskId: input.parsedTask.taskId,\n ts: new Date().toISOString(),\n },\n io: input.ledgerIo,\n paths: input.ledgerPaths,\n });\n\n return {\n agentContextLifecycleCounters: state.agentContextLifecycleCounters,\n deduped: false,\n dispatchResult: {\n adapterResult: {\n ...(input.agentControllerConversationId\n ? {\n contextDelta: {\n ...(input.agentControllerConversation\n ? {\n agentControllerConversation:\n input.agentControllerConversation,\n }\n : {}),\n agentControllerConversationId:\n input.agentControllerConversationId,\n },\n }\n : {}),\n output: resultPayload.output,\n status: \"success\",\n },\n dispatched: true,\n reason: \"dispatched\",\n },\n resultPayload,\n runtimeState: \"idle\",\n state,\n };\n}\n\nasync function applyCliSpaceActionRecordIfPresent(input: {\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeResult: RuntimeTaskResult;\n}): Promise<RuntimeTaskResult> {\n if (!input.dispatchSpaceActionContext) {\n return input.runtimeResult;\n }\n const readResult = await readCliSpaceActionRecordWithGrace({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n graceMs: CLI_SPACE_ACTION_RECORD_RUNTIME_COMPLETION_GRACE_MS,\n });\n if (readResult.status === \"missing\") {\n return input.runtimeResult;\n }\n if (readResult.status === \"invalid\") {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.cli_space_action_invalid\",\n text: `CLI OpenMeld Space Action record ignored for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: readResult.errorMessage,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return input.runtimeResult;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.cli_space_action_recorded\",\n text: `CLI OpenMeld Space Action recorded for task ${input.parsedTask.taskId}`,\n payload: {\n command: readResult.record.command,\n dispatchId: input.parsedTask.dispatchId,\n spaceActionType: readResult.record.action.type,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n return applyCliSpaceActionRecordToRuntimeResult({\n record: readResult.record,\n runtimeResult: input.runtimeResult,\n });\n}\n\nasync function resolveAlreadyCompletedRuntimeResultAfterCliSpaceAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): Promise<RuntimeTaskResult | null> {\n try {\n const result = await Promise.race([\n input.runtimeExecutionPromise.then((runtimeResult) => ({\n runtimeResult,\n status: \"runtime\" as const,\n })),\n delay(0).then(() => ({\n status: \"pending\" as const,\n })),\n ]);\n if (result.status === \"runtime\") {\n return result.runtimeResult;\n }\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_ignored_after_cli_space_action\",\n text: `runtime failed after CLI OpenMeld Space Action finalized task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n }\n return null;\n}\n\nfunction observeRuntimeResultAfterCliSpaceAction(input: {\n onRuntimeResultAfterCliSpaceAction?: (\n runtimeResult: RuntimeTaskResult\n ) => Promise<void> | void;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeExecutionPromise: Promise<RuntimeTaskResult>;\n}): void {\n input.runtimeExecutionPromise\n .then(async (runtimeResult) => {\n await input.onRuntimeResultAfterCliSpaceAction?.(runtimeResult);\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_ignored_after_cli_space_action\",\n text: `runtime failed after CLI OpenMeld Space Action finalized task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n });\n}\n\nfunction applyCliSpaceActionRecordToRuntimeResult(input: {\n record: DispatchSpaceActionRecord;\n runtimeResult: RuntimeTaskResult;\n}): RuntimeTaskResult {\n return {\n ...input.runtimeResult,\n resultPayload: buildCliSpaceActionSuccessPayload({\n basePayload: input.runtimeResult.resultPayload,\n record: input.record,\n }),\n };\n}\n\nfunction buildCliSpaceActionSuccessPayload(input: {\n basePayload: Pick<\n OpenMeldDaemonTaskResultPayload,\n \"agentId\" | \"attemptId\" | \"deduped\" | \"sourceEventId\" | \"taskId\"\n > &\n Partial<\n Pick<\n OpenMeldDaemonTaskResultPayload,\n | \"agentControllerConversation\"\n | \"agentControllerConversationId\"\n | \"agentControllerRef\"\n | \"bootstrapTemplateFacts\"\n | \"dispatchExecution\"\n | \"effectiveRuntimeWorkingDirectory\"\n | \"openClawBinding\"\n | \"openClawGatewayVisibility\"\n | \"promptTrace\"\n | \"runtimeWorkspaceFingerprint\"\n | \"telemetry\"\n | \"transportMode\"\n >\n >;\n record: DispatchSpaceActionRecord;\n}): Extract<OpenMeldDaemonTaskResultPayload, { status: \"success\" }> {\n const output = resolveStructuredActionOutputFallback({\n action: input.record.action,\n cleanedOutput: \"\",\n });\n return {\n agentId: input.basePayload.agentId,\n attemptId: input.basePayload.attemptId,\n deduped: input.basePayload.deduped,\n sourceEventId: input.basePayload.sourceEventId,\n taskId: input.basePayload.taskId,\n ...(input.basePayload.agentControllerConversation\n ? {\n agentControllerConversation:\n input.basePayload.agentControllerConversation,\n }\n : {}),\n ...(input.basePayload.agentControllerConversationId\n ? {\n agentControllerConversationId:\n input.basePayload.agentControllerConversationId,\n }\n : {}),\n ...(input.basePayload.agentControllerRef\n ? { agentControllerRef: input.basePayload.agentControllerRef }\n : {}),\n ...(input.basePayload.bootstrapTemplateFacts\n ? { bootstrapTemplateFacts: input.basePayload.bootstrapTemplateFacts }\n : {}),\n ...(input.basePayload.dispatchExecution\n ? { dispatchExecution: input.basePayload.dispatchExecution }\n : {}),\n ...(input.basePayload.effectiveRuntimeWorkingDirectory\n ? {\n effectiveRuntimeWorkingDirectory:\n input.basePayload.effectiveRuntimeWorkingDirectory,\n }\n : {}),\n ...(input.basePayload.openClawBinding\n ? { openClawBinding: input.basePayload.openClawBinding }\n : {}),\n ...(input.basePayload.openClawGatewayVisibility\n ? {\n openClawGatewayVisibility:\n input.basePayload.openClawGatewayVisibility,\n }\n : {}),\n ...(input.basePayload.promptTrace\n ? { promptTrace: input.basePayload.promptTrace }\n : {}),\n ...(input.basePayload.runtimeWorkspaceFingerprint\n ? {\n runtimeWorkspaceFingerprint:\n input.basePayload.runtimeWorkspaceFingerprint,\n }\n : {}),\n ...(input.basePayload.telemetry\n ? { telemetry: input.basePayload.telemetry }\n : {}),\n ...(input.basePayload.transportMode\n ? { transportMode: input.basePayload.transportMode }\n : {}),\n output,\n spaceAction: input.record.action,\n spaceActionProvenance: \"cli_action\",\n status: \"success\",\n };\n}\n\nasync function readCliSpaceActionRecordWithGrace(input: {\n dispatchSpaceActionContext: DispatchSpaceActionContext;\n graceMs: number;\n}): Promise<DispatchSpaceActionRecordReadResult> {\n const immediateRead = readDispatchSpaceActionRecord({\n context: input.dispatchSpaceActionContext,\n });\n if (immediateRead.status !== \"missing\" || input.graceMs <= 0) {\n return immediateRead;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), input.graceMs);\n try {\n const completion = await waitForCliSpaceActionRecord({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n signal: abortController.signal,\n });\n if (completion.kind === \"cli_space_action_recorded\") {\n return {\n record: completion.record,\n status: \"loaded\",\n };\n }\n if (completion.kind === \"cli_space_action_invalid\") {\n return {\n errorMessage: completion.errorMessage,\n status: \"invalid\",\n };\n }\n return { status: \"missing\" };\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function resolveRuntimeResultStructuredSpaceAction(input: {\n onInteractionRequest?: Parameters<\n typeof runRuntimeTask\n >[0][\"onInteractionRequest\"];\n onNativeTurnStarted: () => Promise<void>;\n onNativeTurnCompleted: (result: RuntimeTaskResult) => void;\n onRuntimeEvent?: Parameters<typeof runRuntimeTask>[0][\"onRuntimeEvent\"];\n agentReplyObservationCursor?: string | null;\n allowConcurrentReplyReconsideration?: boolean;\n cliEntry?: string | null;\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n controllerTurnCompletion: Promise<void>;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n instructionPrompt?: AdapterInstructionPrompt;\n parsedTask: ParsedDispatchTask;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n presenter: Presenter;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n runtimeContext: ProviderDispatchRuntimeContext;\n runtimeEnvOverrides?: Record<string, string | undefined>;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): Promise<{\n runtimeResult: RuntimeTaskResult;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n resolvedSpaceActionProvenance: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n}> {\n let runtimeResult = input.runtimeResult;\n let structuredSpaceActionResolution =\n resolveStructuredSpaceActionFromRuntimePayload(runtimeResult);\n const runtimePayloadSpaceAction = runtimeResult.resultPayload.spaceAction;\n const publicationRequirement = resolveSpacePublicationRequirement(\n input.parsedTask.spaceContractSnapshot\n );\n const requiresStructuredSpaceAction =\n publicationRequirement.requiresExplicitPublicAction;\n let repairFailureDiagnostics: StructuredActionFailureDiagnostics | null =\n null;\n const initialStructuredActionFailure =\n resolveStructuredActionRequirementFailure({\n requiresStructuredSpaceAction,\n resolution: runtimePayloadSpaceAction\n ? { action: runtimePayloadSpaceAction, parseError: null }\n : structuredSpaceActionResolution,\n runtimeResult,\n });\n\n if (initialStructuredActionFailure?.kind === \"preserve_runtime_failure\") {\n return {\n runtimeResult,\n resolvedSpaceAction: undefined,\n resolvedSpaceActionProvenance: undefined,\n };\n }\n\n if (initialStructuredActionFailure?.kind === \"repair\") {\n const repairResult = await maybeRepairStructuredSpaceAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n runtimeResult,\n sendTargetReference: input.sendTargetReference,\n failureReason: initialStructuredActionFailure.failureReason,\n cliEntry: input.cliEntry,\n runControllerRepair: ({ prompt, runtimeResult }) => {\n const repairContinuation = resolveStructuredActionRepairContinuation({\n runtimeResult,\n agentControllerConversationOverride:\n input.agentControllerConversationOverride,\n });\n return runDispatchRuntimeExecution({\n onInteractionRequest: input.onInteractionRequest,\n onNativeTurnStarted: input.onNativeTurnStarted,\n onNativeTurnCompleted: input.onNativeTurnCompleted,\n onRuntimeEvent: input.onRuntimeEvent,\n computerFileAccessBoundary: input.computerFileAccessBoundary,\n contextId: repairContinuation.contextId,\n executionMode: \"repair\",\n io: input.ledgerIo,\n ledgerPaths: input.ledgerPaths,\n instructionPrompt: input.instructionPrompt\n ? {\n ...input.instructionPrompt,\n userPrompt: prompt,\n }\n : undefined,\n parsedTask: input.parsedTask,\n prompt,\n routeConfig: input.routeConfig,\n runtimeContext: input.runtimeContext,\n runtimeEnvOverrides: input.runtimeEnvOverrides,\n runtimeControllerSupport: input.runtimeControllerSupport,\n streamingModeOverride: \"final\",\n agentControllerConversationOverride:\n repairContinuation.agentControllerConversationOverride,\n });\n },\n });\n repairFailureDiagnostics = repairResult.finalFailureDiagnostics;\n if (repairResult.runtimeResult) {\n runtimeResult = repairResult.runtimeResult;\n structuredSpaceActionResolution =\n resolveStructuredSpaceActionFromRuntimePayload(runtimeResult);\n }\n }\n\n let resolvedSpaceAction =\n runtimeResult.resultPayload.spaceAction ??\n structuredSpaceActionResolution.action;\n const resolvedSpaceActionProvenance = resolveStructuredSpaceActionProvenance({\n runtimeResult,\n resolvedSpaceAction,\n });\n const normalizedAction = normalizeResolvedStructuredSpaceAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n resolvedSpaceAction,\n runtimeResult,\n sendTargetReference: input.sendTargetReference,\n structuredSpaceActionResolution,\n });\n resolvedSpaceAction = normalizedAction.resolvedSpaceAction;\n\n const finalStructuredActionFailure = normalizedAction.failureReason\n ? {\n failureReason: normalizedAction.failureReason,\n kind: \"repair\" as const,\n }\n : resolveStructuredActionRequirementFailure({\n requiresStructuredSpaceAction,\n resolution: {\n ...structuredSpaceActionResolution,\n action: resolvedSpaceAction,\n parseError: runtimeResult.resultPayload.spaceAction\n ? null\n : structuredSpaceActionResolution.parseError,\n },\n runtimeResult,\n });\n if (finalStructuredActionFailure?.kind === \"preserve_runtime_failure\") {\n return {\n runtimeResult,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n }\n if (finalStructuredActionFailure?.kind === \"repair\") {\n const diagnostics =\n repairFailureDiagnostics ??\n resolveStructuredActionFailureDiagnostics({\n carrierKind: structuredSpaceActionResolution.carrierKind,\n parseError: structuredSpaceActionResolution.parseError,\n publicFailureReason: finalStructuredActionFailure.failureReason,\n repairMode: \"required_check\",\n runtimeResult,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_required_failed\",\n text: `OpenMeld Space action requirement failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason: finalStructuredActionFailure.failureReason,\n ...diagnostics,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n runtimeResult: {\n ...runtimeResult,\n resultPayload: coerceRuntimeResultToStructuredActionFailure({\n diagnostics,\n failureReason: finalStructuredActionFailure.failureReason,\n runtimeResult,\n }),\n },\n resolvedSpaceAction: undefined,\n resolvedSpaceActionProvenance: undefined,\n };\n }\n\n if (\n runtimeResult.resultPayload.status !== \"success\" &&\n runtimeResult.resultPayload.status !== \"partial_success\"\n ) {\n return {\n runtimeResult,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n }\n\n if (\n input.allowConcurrentReplyReconsideration !== false &&\n resolvedSpaceAction?.type === \"post_message\"\n ) {\n return await coordinateConcurrentAgentReply({\n ...input,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n runtimeResult,\n });\n }\n\n const shouldPreserveCliActionOutput =\n runtimeResult.resultPayload.spaceActionProvenance === \"cli_action\";\n const shouldApplyStructuredActionResolution =\n runtimeResult.resultPayload.spaceAction !== resolvedSpaceAction ||\n runtimeResult.resultPayload.spaceActionProvenance !==\n resolvedSpaceActionProvenance ||\n (!shouldPreserveCliActionOutput &&\n typeof structuredSpaceActionResolution.cleanedOutput === \"string\" &&\n structuredSpaceActionResolution.cleanedOutput !==\n runtimeResult.resultPayload.output);\n if (!shouldApplyStructuredActionResolution) {\n return {\n runtimeResult,\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n }\n\n return {\n runtimeResult: applyStructuredSpaceActionResolutionToRuntimePayload({\n runtimeResult,\n resolution: {\n ...structuredSpaceActionResolution,\n action: resolvedSpaceAction,\n spaceActionProvenance: resolvedSpaceActionProvenance,\n },\n }),\n resolvedSpaceAction,\n resolvedSpaceActionProvenance,\n };\n}\n\nasync function coordinateConcurrentAgentReply(input: {\n onInteractionRequest?: Parameters<\n typeof runRuntimeTask\n >[0][\"onInteractionRequest\"];\n onNativeTurnStarted: () => Promise<void>;\n onNativeTurnCompleted: (result: RuntimeTaskResult) => void;\n onRuntimeEvent?: Parameters<typeof runRuntimeTask>[0][\"onRuntimeEvent\"];\n agentReplyObservationCursor?: string | null;\n cliEntry?: string | null;\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n controllerTurnCompletion: Promise<void>;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n instructionPrompt?: AdapterInstructionPrompt;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n resolvedSpaceAction: Extract<\n NonNullable<OpenMeldDaemonTaskResultPayload[\"spaceAction\"]>,\n { type: \"post_message\" }\n >;\n resolvedSpaceActionProvenance: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeContext: ProviderDispatchRuntimeContext;\n runtimeEnvOverrides?: Record<string, string | undefined>;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): Promise<{\n runtimeResult: RuntimeTaskResult;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n resolvedSpaceActionProvenance: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n}> {\n const requestContext = buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: {\n ownerUserId: input.profileOwnerUserId,\n profileKind: \"agent\",\n profileName:\n input.parsedTask.targetProfileName ??\n input.parsedTask.targetProfileMentionLabel ??\n input.parsedTask.targetProfileId,\n openMeldProfileId: input.parsedTask.targetProfileId,\n ...(input.profileOwnerName ? { ownerName: input.profileOwnerName } : {}),\n },\n });\n const readObservation = async (\n observedThroughSignalId: string\n ): Promise<DispatchAgentReplyObservation> => {\n try {\n return await readDispatchAgentReplyObservation({\n currentWakeTargetProfileIds:\n input.parsedTask.sourceMessageEnvelope?.activationTargets,\n requestContext,\n sourceSignalId: observedThroughSignalId,\n spaceId: input.parsedTask.spaceId,\n spacePassword: input.parsedTask.spacePassword,\n threadContext: input.parsedTask.threadContext,\n wakeSourceSignalId: input.parsedTask.sourceEventId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_reply_observation_unavailable\",\n text: `Agent reply observation unavailable for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n errorMessage: toErrorMessage(error),\n observedThroughSignalId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_observation.unavailable\",\n message: `OpenMeld could not read the Space context before publishing the Agent reply: ${toErrorMessage(error)}`,\n });\n }\n };\n let observation: DispatchAgentReplyObservation;\n try {\n observation = await readObservation(\n normalizeOptionalText(input.agentReplyObservationCursor) ??\n input.parsedTask.sourceEventId\n );\n } catch (error) {\n if (input.agentReplyObservationCursor) {\n throw error;\n }\n // Preserve the first proposal using only the context actually delivered\n // with the Wake. Space's atomic publication guard still checks this cursor\n // after durable replay and can require review before publishing anything.\n const action = attachAgentReplyObservation({\n action: input.resolvedSpaceAction,\n observedThroughSignalId: input.parsedTask.sourceEventId,\n });\n return {\n resolvedSpaceAction: action,\n resolvedSpaceActionProvenance: input.resolvedSpaceActionProvenance,\n runtimeResult: applyStructuredSpaceActionResolutionToRuntimePayload({\n resolution: {\n action,\n parseError: null,\n spaceActionProvenance: input.resolvedSpaceActionProvenance,\n },\n runtimeResult: input.runtimeResult,\n }),\n };\n }\n\n const coordinated = await coordinateDispatchAgentReply({\n action: input.resolvedSpaceAction,\n originalWake: {\n sourceSignalId: input.parsedTask.sourceEventId,\n targetProfileId: input.parsedTask.targetProfileId,\n text: input.parsedTask.prompt,\n },\n currentValue: {\n provenance: input.resolvedSpaceActionProvenance,\n runtimeResult: input.runtimeResult,\n },\n observation,\n reconsider: async (prompt, currentObservation) => {\n const reconsiderationStartedAtMs = Date.now();\n const recordReconsideration = (result: string) =>\n emitDaemonDispatchJournalEvent({\n type: \"dispatch.reply_reconsideration\",\n dispatchId: input.parsedTask.dispatchId,\n profileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n result,\n metadata: {\n reason: \"new_relevant_space_signal\",\n newerSignalCount: currentObservation.relevantSignals.length,\n observedThroughSignalId: currentObservation.observedThroughSignalId,\n triggeringSignalIds: currentObservation.relevantSignals.map(\n (signal) => signal.id\n ),\n startedAtMs: reconsiderationStartedAtMs,\n durationMs: Math.max(0, Date.now() - reconsiderationStartedAtMs),\n },\n });\n recordReconsideration(\"started\");\n try {\n const continuation = resolveStructuredActionRepairContinuation({\n agentControllerConversationOverride:\n input.agentControllerConversationOverride,\n runtimeResult: input.runtimeResult,\n });\n if (\n !(\n continuation.contextId ||\n continuation.agentControllerConversationOverride\n )\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_reconsideration.conversation_unavailable\",\n message:\n \"The Space changed, but the exact Agent conversation is unavailable for reply reconsideration.\",\n });\n }\n await input.controllerTurnCompletion;\n const activeTask = input.inflightTaskControlRegistry.getTask(\n input.parsedTask.taskId\n );\n if (\n activeTask?.dispatchId !== input.parsedTask.dispatchId ||\n activeTask.runtimeCoordinatorExecutionId !==\n input.parsedTask.runtimeCoordinatorExecutionId\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_reconsideration.execution_inactive\",\n message:\n \"The Wake stopped before the Agent could reconsider its reply.\",\n });\n }\n if (input.dispatchSpaceActionContext) {\n supersedeDispatchSpaceActionRecordForReconsideration({\n context: input.dispatchSpaceActionContext,\n });\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_reply_reconsideration_started\",\n text: `Agent reply reconsideration started for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n newerSignalCount: currentObservation.relevantSignals.length,\n observedThroughSignalId: currentObservation.observedThroughSignalId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n let runtimeResult = await runDispatchRuntimeExecution({\n onInteractionRequest: input.onInteractionRequest,\n onNativeTurnStarted: input.onNativeTurnStarted,\n onNativeTurnCompleted: input.onNativeTurnCompleted,\n onRuntimeEvent: input.onRuntimeEvent,\n agentControllerConversationOverride:\n continuation.agentControllerConversationOverride,\n computerFileAccessBoundary: input.computerFileAccessBoundary,\n contextId: continuation.contextId,\n executionMode: \"repair\",\n instructionPrompt: input.instructionPrompt\n ? {\n ...input.instructionPrompt,\n userPrompt: prompt,\n }\n : undefined,\n io: input.ledgerIo,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n prompt,\n routeConfig: input.routeConfig,\n runtimeContext: input.runtimeContext,\n runtimeEnvOverrides: input.runtimeEnvOverrides,\n runtimeControllerSupport: input.runtimeControllerSupport,\n streamingModeOverride: \"final\",\n });\n runtimeResult = await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult,\n });\n const reconsidered = await resolveRuntimeResultStructuredSpaceAction({\n ...input,\n agentControllerConversationOverride:\n continuation.agentControllerConversationOverride,\n allowConcurrentReplyReconsideration: false,\n runtimeResult,\n });\n if (!reconsidered.resolvedSpaceAction) {\n if (reconsidered.runtimeResult.resultPayload.status === \"failed\") {\n return {\n action: undefined,\n value: {\n provenance: undefined,\n runtimeResult: reconsidered.runtimeResult,\n },\n };\n }\n throw new DaemonServiceRunError({\n code: \"dispatch.agent_reply_reconsideration.action_missing\",\n message:\n \"The Agent did not return a valid Space action after reviewing newer messages.\",\n });\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_reply_reconsideration_completed\",\n text: `Agent reply reconsideration completed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n observedThroughSignalId: currentObservation.observedThroughSignalId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n action: reconsidered.resolvedSpaceAction,\n value: {\n provenance: \"controller_repair\" as const,\n runtimeResult: reconsidered.runtimeResult,\n },\n };\n } finally {\n recordReconsideration(\"finished\");\n }\n },\n refreshObservation: readObservation,\n spaceId: input.parsedTask.spaceId,\n });\n return {\n resolvedSpaceAction: coordinated.action,\n resolvedSpaceActionProvenance: coordinated.value.provenance,\n runtimeResult: applyStructuredSpaceActionResolutionToRuntimePayload({\n resolution: {\n action: coordinated.action,\n parseError: null,\n spaceActionProvenance: coordinated.value.provenance,\n },\n runtimeResult: coordinated.value.runtimeResult,\n }),\n };\n}\n\nfunction normalizeResolvedStructuredSpaceAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n structuredSpaceActionResolution: ReturnType<\n typeof resolveStructuredSpaceActionFromRuntimePayload\n >;\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const postMessageResult = normalizeResolvedPostMessageAction(input);\n if (postMessageResult.failureReason) {\n return postMessageResult;\n }\n const postStatusResult = normalizeResolvedPostStatusAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n resolvedSpaceAction: postMessageResult.resolvedSpaceAction,\n });\n if (postStatusResult.failureReason) {\n return postStatusResult;\n }\n\n return normalizeResolvedThreadAction({\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n resolvedSpaceAction: postStatusResult.resolvedSpaceAction,\n });\n}\n\nfunction normalizeResolvedPostMessageAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n structuredSpaceActionResolution: ReturnType<\n typeof resolveStructuredSpaceActionFromRuntimePayload\n >;\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const action = input.resolvedSpaceAction;\n if (action?.type !== \"post_message\") {\n return { failureReason: null, resolvedSpaceAction: action };\n }\n\n try {\n const normalizedPostMessageAction = normalizeDispatchPostMessageAction({\n action,\n currentReplyToSignalId:\n input.parsedTask.replyToSnapshot?.signalId ?? null,\n inputKind: \"direct_payload\",\n sendTargetReference: input.sendTargetReference,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.post_message_normalized\",\n text: `post_message normalized for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n ...normalizedPostMessageAction.tracePayload,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n failureReason: null,\n resolvedSpaceAction: normalizedPostMessageAction.action,\n };\n } catch (error) {\n const failureReason = toErrorMessage(error);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.post_message_validation_rejected\",\n text: `post_message validation rejected for task ${input.parsedTask.taskId}`,\n payload: {\n activationTargetsCount: action.messageEnvelope.activationTargets.length,\n dispatchId: input.parsedTask.dispatchId,\n failureReason,\n inputKind: \"direct_payload\",\n memberDirectoryLoaded: input.sendTargetReference.status === \"loaded\",\n mentionTargetsCount: action.messageEnvelope.mentionTargets?.length ?? 0,\n referenceTargetsCount: action.messageEnvelope.referenceTargets.length,\n replyToSignalIdResolved: Boolean(\n action.messageEnvelope.replyToSignalId\n ),\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return { failureReason, resolvedSpaceAction: undefined };\n }\n}\n\nfunction normalizeResolvedPostStatusAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const action = input.resolvedSpaceAction;\n if (action?.type !== \"post_status\" || action.status !== \"working\") {\n return { failureReason: null, resolvedSpaceAction: action };\n }\n\n const failureReason =\n \"post_status working is not allowed for a final OpenMeld Space Action. Use done, blocked, needs_input, handoff, post_message, or stay_silent.\";\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.post_status_validation_rejected\",\n text: `post_status validation rejected for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason,\n status: action.status,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return { failureReason, resolvedSpaceAction: undefined };\n}\n\nfunction normalizeResolvedThreadAction(input: {\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n}): {\n failureReason: string | null;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n} {\n const action = input.resolvedSpaceAction;\n if (!(action?.type === \"post_message\" || action?.type === \"post_status\")) {\n return { failureReason: null, resolvedSpaceAction: action };\n }\n\n try {\n return {\n failureReason: null,\n resolvedSpaceAction: normalizeDispatchThreadAction({\n action,\n threadContext: input.parsedTask.threadContext,\n }),\n };\n } catch (error) {\n const failureReason = toErrorMessage(error);\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.thread_action_validation_rejected\",\n text: `thread action validation rejected for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n threadId: input.parsedTask.threadContext?.threadId ?? null,\n },\n });\n return { failureReason, resolvedSpaceAction: undefined };\n }\n}\n\nasync function maybeRepairStructuredSpaceAction(input: {\n cliEntry?: string | null;\n dispatchSpaceActionContext: DispatchSpaceActionContext | null;\n failureReason: string;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runControllerRepair?: (input: {\n prompt: string;\n runtimeResult: RuntimeTaskResult;\n }) => Promise<RuntimeTaskResult>;\n runtimeResult: RuntimeTaskResult;\n sendTargetReference: DispatchSendTargetReferenceLoadResult;\n}): Promise<StructuredActionRepairResult> {\n if (!input.failureReason) {\n return {\n finalFailureDiagnostics: null,\n runtimeResult: null,\n };\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_started\",\n text: `structured OpenMeld Space action repair started for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n failureReason: input.failureReason,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n const skillRepair = await ensureDispatchControllerOpenMeldSkill({\n agentControllerRef: input.parsedTask.agentControllerRef,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.dispatch_controller_skill_repair_checked\",\n text: `OpenMeld skill repair checked for task ${input.parsedTask.taskId}`,\n payload: {\n agentControllerRef: input.parsedTask.agentControllerRef,\n agentId: skillRepair.agentId,\n dispatchId: input.parsedTask.dispatchId,\n ...(skillRepair.reason ? { reason: skillRepair.reason } : {}),\n status: skillRepair.status,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n\n if (!input.runControllerRepair) {\n return {\n finalFailureDiagnostics: resolveStructuredActionFailureDiagnostics({\n carrierKind: \"none\",\n parseError: input.failureReason,\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult: input.runtimeResult,\n }),\n runtimeResult: null,\n };\n }\n\n let providerRepairRuntimeResult: RuntimeTaskResult;\n try {\n providerRepairRuntimeResult = await input.runControllerRepair({\n prompt: buildStructuredActionRepairPrompt({\n cliEntry: input.cliEntry,\n currentReplyToSignalId: input.parsedTask.replyToSnapshot?.signalId,\n parseError: input.failureReason,\n previousOutput: resolveStructuredActionRepairPreviousOutput(\n input.runtimeResult\n ),\n sendTargetReferenceLines: input.sendTargetReference.referenceLines,\n spaceContractSnapshot: input.parsedTask.spaceContractSnapshot,\n spaceId: input.parsedTask.spaceId,\n }),\n runtimeResult: input.runtimeResult,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_failed\",\n text: `structured OpenMeld Space action repair failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n ...resolveStructuredActionFailureDiagnostics({\n carrierKind: \"none\",\n parseError: toErrorMessage(error),\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult: input.runtimeResult,\n }),\n failureReason: input.failureReason,\n repairedRuntimeStatus: \"failed\",\n repairedStructuredActionPresent: false,\n repairMode: \"controller_roundtrip\",\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n finalFailureDiagnostics: resolveStructuredActionFailureDiagnostics({\n carrierKind: \"none\",\n parseError: toErrorMessage(error),\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult: input.runtimeResult,\n }),\n runtimeResult: null,\n };\n }\n\n providerRepairRuntimeResult = await applyCliSpaceActionRecordIfPresent({\n dispatchSpaceActionContext: input.dispatchSpaceActionContext,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n runtimeResult: providerRepairRuntimeResult,\n });\n\n const providerRepairEvaluation = resolveStructuredActionRepairEvaluation({\n runtimeResult: providerRepairRuntimeResult,\n });\n if (\n !(\n providerRepairEvaluation.accepted &&\n providerRepairEvaluation.runtimeResult\n )\n ) {\n const providerFailureDiagnostics =\n resolveStructuredActionFailureDiagnostics({\n carrierKind: providerRepairEvaluation.carrierKind,\n parseError: providerRepairEvaluation.parseError,\n publicFailureReason: input.failureReason,\n repairMode: \"controller_roundtrip\",\n runtimeResult:\n providerRepairEvaluation.runtimeResult ?? providerRepairRuntimeResult,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_failed\",\n text: `structured OpenMeld Space action repair failed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n ...providerFailureDiagnostics,\n failureReason: input.failureReason,\n repairedRuntimeStatus: providerRepairEvaluation.repairedRuntimeStatus,\n repairedStructuredActionPresent:\n providerRepairEvaluation.repairedStructuredActionPresent,\n repairMode: \"controller_roundtrip\",\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n finalFailureDiagnostics: providerFailureDiagnostics,\n runtimeResult: null,\n };\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.structured_action_repair_completed\",\n text: `structured OpenMeld Space action repair completed for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n repaired: true,\n repairMode: \"controller_roundtrip\",\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return {\n finalFailureDiagnostics: null,\n runtimeResult: applyStructuredSpaceActionProvenanceToRuntimeResult({\n runtimeResult: providerRepairEvaluation.runtimeResult,\n provenance: \"controller_repair\",\n }),\n };\n}\n\nfunction resolveStructuredActionRepairEvaluation(input: {\n runtimeResult: RuntimeTaskResult;\n}): {\n accepted: boolean;\n carrierKind: StructuredActionFailureDiagnostics[\"carrierKind\"];\n parseError: string | null;\n repairedRuntimeStatus: RuntimeTaskResult[\"resultPayload\"][\"status\"];\n repairedStructuredActionPresent: boolean;\n runtimeResult: RuntimeTaskResult | null;\n} {\n const runtimeResult = input.runtimeResult;\n const repairedResolution =\n resolveStructuredSpaceActionFromRuntimePayload(runtimeResult);\n const repairedAction =\n runtimeResult.resultPayload.spaceAction ?? repairedResolution.action;\n const repairedRuntimeStatus = runtimeResult.resultPayload.status;\n const accepted =\n (repairedRuntimeStatus === \"success\" ||\n repairedRuntimeStatus === \"partial_success\") &&\n repairedResolution.parseError === null &&\n repairedAction !== undefined;\n\n return {\n accepted,\n carrierKind: repairedResolution.carrierKind,\n parseError: repairedResolution.parseError,\n repairedRuntimeStatus,\n repairedStructuredActionPresent: repairedAction !== undefined,\n runtimeResult,\n };\n}\n\nfunction resolveStructuredActionFailureDiagnostics(input: {\n carrierKind: StructuredActionFailureDiagnostics[\"carrierKind\"];\n parseError: string | null;\n publicFailureReason?: string | null;\n repairMode: StructuredActionFailureDiagnostics[\"repairMode\"];\n runtimeResult: RuntimeTaskResult;\n}): StructuredActionFailureDiagnostics {\n return {\n carrierKind: input.carrierKind,\n invalidOutputPreview: buildInvalidStructuredActionOutputPreview(\n input.runtimeResult\n ),\n publicFailureReason: normalizeOptionalText(input.publicFailureReason),\n repairMode: input.repairMode,\n spaceActionCandidatePresent: input.carrierKind !== \"none\",\n spaceActionParseError: normalizeOptionalText(input.parseError),\n };\n}\n\nfunction maybeRejectDispatchPreflight(input: {\n activeLeaseEpoch: number | undefined;\n correlation: DispatchCorrelation;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n parsedTask: ReturnType<typeof parseDispatchTask>;\n ledgerPaths: LedgerPaths;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n const staleLeaseResult = maybeRejectStaleLease({\n activeLeaseEpoch: input.activeLeaseEpoch,\n correlation: input.correlation,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n socket: input.socket,\n });\n if (staleLeaseResult) {\n return staleLeaseResult;\n }\n\n return maybeRejectInvalidDispatchTask({\n correlation: input.correlation,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask: input.parsedTask,\n presenter: input.presenter,\n socket: input.socket,\n });\n}\n\nfunction resolveStructuredSpaceActionFromRuntimePayload(\n runtimeResult: RuntimeTaskResult\n): {\n action: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n carrierKind: StructuredActionFailureDiagnostics[\"carrierKind\"];\n cleanedOutput?: string;\n parseError: string | null;\n} {\n const payload = runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return {\n action: undefined,\n carrierKind: \"none\",\n cleanedOutput: undefined,\n parseError: null,\n };\n }\n\n return {\n action: payload.spaceAction,\n carrierKind: \"none\",\n cleanedOutput: undefined,\n parseError: null,\n };\n}\n\nfunction applyStructuredSpaceActionResolutionToRuntimePayload(input: {\n runtimeResult: RuntimeTaskResult;\n resolution: {\n action: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n cleanedOutput?: string;\n parseError: string | null;\n spaceActionProvenance?: OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"];\n };\n}): RuntimeTaskResult {\n const payload = input.runtimeResult.resultPayload;\n if (payload.status !== \"success\" && payload.status !== \"partial_success\") {\n return input.runtimeResult;\n }\n\n return {\n ...input.runtimeResult,\n resultPayload: {\n ...payload,\n output: input.resolution.cleanedOutput ?? payload.output,\n ...(input.resolution.action\n ? { spaceAction: input.resolution.action }\n : {}),\n ...(input.resolution.action && input.resolution.spaceActionProvenance\n ? { spaceActionProvenance: input.resolution.spaceActionProvenance }\n : {}),\n },\n };\n}\n\nfunction applyStructuredSpaceActionProvenanceToRuntimeResult(input: {\n runtimeResult: RuntimeTaskResult;\n provenance: NonNullable<\n OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"]\n >;\n}): RuntimeTaskResult {\n const payload = input.runtimeResult.resultPayload;\n if (\n (payload.status !== \"success\" && payload.status !== \"partial_success\") ||\n !payload.spaceAction\n ) {\n return input.runtimeResult;\n }\n\n return {\n ...input.runtimeResult,\n resultPayload: {\n ...payload,\n spaceActionProvenance: payload.spaceActionProvenance ?? input.provenance,\n },\n };\n}\n\nfunction resolveStructuredSpaceActionProvenance(input: {\n runtimeResult: RuntimeTaskResult;\n resolvedSpaceAction: OpenMeldDaemonTaskResultPayload[\"spaceAction\"];\n}): OpenMeldDaemonTaskResultPayload[\"spaceActionProvenance\"] {\n if (!input.resolvedSpaceAction) {\n return undefined;\n }\n return input.runtimeResult.resultPayload.spaceActionProvenance ?? \"direct\";\n}\n\ntype DispatchRuntimeRoute = NonNullable<\n Parameters<typeof runRuntimeTask>[0][\"route\"]\n>;\ntype DispatchRuntimeTask = Parameters<typeof runRuntimeTask>[0][\"task\"];\n\nasync function runDispatchRuntimeExecution(input: {\n onNativeTurnStarted: () => Promise<void>;\n onNativeTurnCompleted: (result: RuntimeTaskResult) => void;\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n contextId: string | null;\n executionMode: AdapterDispatchExecutionMode;\n io: ReturnType<typeof createLedgerIo>;\n ledgerPaths: LedgerPaths;\n onInteractionRequest?: Parameters<\n typeof runRuntimeTask\n >[0][\"onInteractionRequest\"];\n onPreview?: Parameters<typeof runRuntimeTask>[0][\"onPreview\"];\n onRuntimeEvent?: Parameters<typeof runRuntimeTask>[0][\"onRuntimeEvent\"];\n parsedTask: ParsedDispatchTask;\n instructionPrompt?: AdapterInstructionPrompt;\n prompt: string;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeContext: ProviderDispatchRuntimeContext;\n runtimeEnvOverrides?: Record<string, string | undefined>;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n streamingModeOverride?: DispatchRuntimeRoute[\"streamingMode\"];\n agentControllerConversationOverride?: AgentControllerConversationRef | null;\n}): Promise<Awaited<ReturnType<typeof runRuntimeTask>>> {\n await input.onNativeTurnStarted();\n const result = await runRuntimeTask({\n // Admission/continuation already selected the conversation. An explicit\n // null means start fresh, not permission to restore a retained ledger ID.\n agentContextOverride: {\n agentControllerConversationId: input.contextId,\n agentControllerConversationOverride:\n input.agentControllerConversationOverride ?? null,\n },\n io: input.io,\n ...(input.onInteractionRequest\n ? { onInteractionRequest: input.onInteractionRequest }\n : {}),\n ...(input.onPreview ? { onPreview: input.onPreview } : {}),\n ...(input.onRuntimeEvent ? { onRuntimeEvent: input.onRuntimeEvent } : {}),\n paths: input.ledgerPaths,\n route: buildDispatchRuntimeRoute({\n contextId: input.contextId,\n envOverrides: input.runtimeEnvOverrides,\n parsedTask: input.parsedTask,\n routeConfig: input.routeConfig,\n runtimeControllerSupport: input.runtimeControllerSupport,\n streamingMode:\n input.streamingModeOverride ?? input.parsedTask.streamingMode,\n }),\n task: buildDispatchRuntimeTask({\n computerFileAccessBoundary: input.computerFileAccessBoundary,\n executionMode: input.executionMode,\n instructionPrompt: input.instructionPrompt,\n parsedTask: input.parsedTask,\n prompt: input.prompt,\n runtimeContext: input.runtimeContext,\n }),\n });\n input.onNativeTurnCompleted(result);\n return result;\n}\n\nfunction buildDispatchRuntimeRoute(input: {\n contextId: string | null;\n envOverrides?: Record<string, string | undefined>;\n parsedTask: ParsedDispatchTask;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeControllerSupport: SupportedRuntimeControllerSupport;\n streamingMode: DispatchRuntimeRoute[\"streamingMode\"];\n}): DispatchRuntimeRoute {\n const runtimeEnv: Record<string, string | undefined> = input.contextId\n ? {\n [input.parsedTask.contextIdMappingSpec.sourceField]: input.contextId,\n ...(input.envOverrides ?? {}),\n }\n : (input.envOverrides ?? {});\n return {\n contextIdMappingSpec: input.parsedTask.contextIdMappingSpec,\n agentControllerRef: input.parsedTask.agentControllerRef,\n controllerRuntimeAvailable: true,\n env: buildDispatchOwnedRuntimeEnv({\n dispatchId: input.parsedTask.dispatchId,\n targetProfileId: input.parsedTask.targetProfileId,\n env: runtimeEnv,\n spaceActionContextPath:\n runtimeEnv[OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV] ?? null,\n }),\n serviceHealthy: true,\n serviceInstalled: true,\n ...(input.routeConfig?.agentControllerPermissionMode\n ? {\n agentControllerPermissionMode:\n input.routeConfig.agentControllerPermissionMode,\n }\n : {}),\n ...(input.routeConfig?.conversationPolicy\n ? { conversationPolicy: input.routeConfig.conversationPolicy }\n : {}),\n ...(input.routeConfig?.openCodePermission\n ? { openCodePermission: input.routeConfig.openCodePermission }\n : {}),\n targets: [\n ...buildRuntimeRouteTargets({\n agentControllerRef: input.parsedTask.agentControllerRef,\n launchContract: input.routeConfig?.launchContract ?? null,\n runtimeControllerSupport: input.runtimeControllerSupport,\n }),\n ],\n streamingMode: input.streamingMode,\n transportMode: input.parsedTask.transportMode,\n view: \"agent\",\n };\n}\n\nfunction buildDispatchRuntimeTask(input: {\n computerFileAccessBoundary?: AdapterComputerFileAccessBoundary | null;\n executionMode: AdapterDispatchExecutionMode;\n instructionPrompt?: AdapterInstructionPrompt;\n parsedTask: ParsedDispatchTask;\n prompt: string;\n runtimeContext: ProviderDispatchRuntimeContext;\n}): DispatchRuntimeTask {\n return {\n executionContext: input.parsedTask.executionContext,\n agentId: input.parsedTask.targetProfileId,\n attemptId: input.parsedTask.attemptId,\n bindingKey: `${input.parsedTask.spaceId}|${input.parsedTask.targetProfileId}`,\n ...(input.computerFileAccessBoundary\n ? { computerFileAccessBoundary: input.computerFileAccessBoundary }\n : {}),\n dispatchId: input.parsedTask.dispatchId,\n deliveryRecoveryReason:\n input.parsedTask.deliveryRecoveryReason ?? undefined,\n executionMode: input.executionMode,\n ...(input.instructionPrompt\n ? { instructionPrompt: input.instructionPrompt }\n : {}),\n mentioned: true,\n newSessionTitle:\n input.executionMode === \"normal\" &&\n input.parsedTask.agentControllerRef === \"builtin:codex\"\n ? buildDispatchSessionTitle(input.parsedTask)\n : undefined,\n prompt: input.prompt,\n runtimeContext: input.runtimeContext,\n sequence: input.parsedTask.sequence,\n sourceEventId: input.parsedTask.sourceEventId,\n spaceId: input.parsedTask.spaceId,\n taskId: input.parsedTask.taskId,\n triggerMode: input.parsedTask.triggerMode,\n };\n}\n\nfunction maybeRejectStaleLease(input: {\n activeLeaseEpoch: number | undefined;\n correlation: DispatchCorrelation;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n parsedTask: ReturnType<typeof parseDispatchTask>;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n if (\n input.activeLeaseEpoch === undefined ||\n input.activeLeaseEpoch === input.deliverRequest.leaseEpoch\n ) {\n return null;\n }\n\n return sendDispatchRejectionResult({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n dispatchId: input.correlation.dispatchId,\n ledgerPaths: input.ledgerPaths,\n payload: {\n attemptId: input.correlation.attemptId,\n agentControllerRef: input.parsedTask?.agentControllerRef ?? null,\n errorCode: \"daemon.session.stale_lease\",\n errorMessage:\n \"daemon.session.stale_lease: local lease epoch does not match deliver frame\",\n errorType: \"config\",\n sourceEventId: input.correlation.sourceEventId,\n targetProfileId: input.correlation.targetProfileId,\n taskId: input.correlation.taskId,\n },\n presenter: input.presenter,\n });\n}\n\nfunction maybeRejectInvalidDispatchTask(input: {\n correlation: DispatchCorrelation;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n parsedTask: ReturnType<typeof parseDispatchTask>;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n if (input.parsedTask) {\n return null;\n }\n\n return sendDispatchRejectionResult({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n dispatchId: input.correlation.dispatchId,\n ledgerPaths: input.ledgerPaths,\n payload: {\n attemptId: input.correlation.attemptId,\n agentControllerRef: input.correlation.agentControllerRef,\n errorCode: \"schema.invalid\",\n errorMessage:\n \"schema.invalid: daemon dispatch payload is invalid or missing required fields\",\n errorType: \"config\",\n sourceEventId: input.correlation.sourceEventId,\n targetProfileId: input.correlation.targetProfileId,\n taskId: input.correlation.taskId,\n },\n presenter: input.presenter,\n });\n}\n\nfunction resolveValidatedDispatchDeliveryInput(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n}):\n | {\n result: LocalExecutionSlotTaskResult;\n status: \"rejected\";\n }\n | {\n parsedTask: ParsedDispatchTask;\n routeConfig: DaemonProfileRouteConfig | null;\n runtimeControllerSupport: ReturnType<\n typeof resolveLocalRuntimeControllerSupport\n >;\n status: \"ready\";\n } {\n const routeConfig =\n input.routeByProfileId.get(input.deliverRequest.profileId) ?? null;\n const parsedTask = parseDispatchTask({\n deliverRequest: input.deliverRequest,\n fallbackRouteConfig: routeConfig,\n });\n const correlation = buildDispatchCorrelation({\n deliverRequest: input.deliverRequest,\n parsedTask,\n });\n const activeLeaseEpoch = input.leasesByProfileId.get(\n input.deliverRequest.profileId\n );\n const preflightRejectionResult = maybeRejectDispatchPreflight({\n activeLeaseEpoch,\n correlation,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n ledgerPaths: input.ledgerPaths,\n parsedTask,\n presenter: input.presenter,\n socket: input.socket,\n });\n if (preflightRejectionResult) {\n return {\n result: preflightRejectionResult,\n status: \"rejected\",\n };\n }\n assertParsedDispatchTask(parsedTask);\n\n const runtimeControllerSupport = resolveLocalRuntimeControllerSupport({\n agentControllerRef: parsedTask.agentControllerRef,\n localAdapterContainer: input.localAdapterContainer,\n });\n\n return {\n parsedTask,\n routeConfig,\n runtimeControllerSupport,\n status: \"ready\",\n };\n}\n\nfunction assertParsedDispatchTask(\n parsedTask: ReturnType<typeof parseDispatchTask>\n): asserts parsedTask is ParsedDispatchTask {\n if (!parsedTask) {\n throw new Error(\"dispatch task unexpectedly missing after validation\");\n }\n}\n\nfunction assertSupportedRuntimeControllerSupport(\n runtimeControllerSupport: ReturnType<\n typeof resolveLocalRuntimeControllerSupport\n >\n): asserts runtimeControllerSupport is SupportedRuntimeControllerSupport {\n if (!runtimeControllerSupport.supported) {\n throw new Error(\n `runtime controller support unexpectedly missing after validation: ${runtimeControllerSupport.reasonDetail}`\n );\n }\n}\n\nfunction maybeRejectUnsupportedController(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n ledgerPaths: LedgerPaths;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n runtimeControllerSupport: ReturnType<\n typeof resolveLocalRuntimeControllerSupport\n >;\n socket: DaemonFrameSink;\n}): LocalExecutionSlotTaskResult | null {\n if (input.runtimeControllerSupport.supported) {\n return null;\n }\n\n return sendDispatchRejectionResult({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n deliverRequest: input.deliverRequest,\n dispatchId: input.parsedTask.dispatchId,\n ledgerPaths: input.ledgerPaths,\n payload: {\n attemptId: input.parsedTask.attemptId,\n agentControllerRef: input.parsedTask.agentControllerRef,\n errorCode: \"controller.kind.unsupported\",\n errorMessage: `controller.kind.unsupported: ${input.runtimeControllerSupport.reasonDetail}`,\n errorType: \"config\",\n sourceEventId: input.parsedTask.sourceEventId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n presenter: input.presenter,\n });\n}\n\nfunction sendDispatchRejectionResult(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n dispatchId: string;\n ledgerPaths: LedgerPaths;\n payload: DispatchRejectionPayloadInput;\n presenter: Presenter;\n}): LocalExecutionSlotTaskResult {\n const payload = buildFailedTaskResultPayload(input.payload);\n return sendResultAndSummarize({\n attemptId: input.payload.attemptId,\n connectionGeneration: input.deliverRequest.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionIdentityEcho: toRuntimeTransportResultIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: toRuntimeCoordinatorExecutionTokenEcho(\n input.deliverRequest\n ),\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n payload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId:\n input.deliverRequest.payload.runtimeCoordinatorExecutionId,\n taskId: input.payload.taskId,\n }).resultSummary;\n}\n\nexport function buildDispatchExecution(input: {\n agentControllerConversationId: string | null;\n bootstrapPlan: BootstrapPlan;\n localRuntimeContextPlan: LocalRuntimeContextPlan;\n observedAgentControllerConversation: AgentControllerConversationRef | null;\n plannedAgentControllerConversation: AgentControllerConversationRef | null;\n}): DispatchExecution {\n const effectiveObservedAgentControllerConversation =\n input.observedAgentControllerConversation ??\n input.plannedAgentControllerConversation;\n let agentControllerConversationResume: DispatchExecution[\"agentControllerConversationResume\"];\n if (!normalizeOptionalContextId(input.agentControllerConversationId)) {\n agentControllerConversationResume = {\n status: \"not_bound\",\n };\n } else if (\n input.plannedAgentControllerConversation &&\n areSameAgentControllerConversationRef(\n input.plannedAgentControllerConversation,\n effectiveObservedAgentControllerConversation\n )\n ) {\n agentControllerConversationResume = {\n status: \"continued\",\n };\n } else {\n agentControllerConversationResume = {\n status: \"replaced_by_provider\",\n };\n }\n return {\n bootstrap: input.bootstrapPlan.shouldInject\n ? {\n reason: input.bootstrapPlan.reason ?? \"missing_bootstrap_state\",\n status: \"pending\",\n }\n : {\n reason: null,\n status: \"applied\",\n },\n localRuntimeContext: {\n reason: input.localRuntimeContextPlan.reason,\n status:\n input.localRuntimeContextPlan.status === \"reuse\"\n ? \"reused\"\n : \"recreated\",\n },\n agentControllerConversationResume,\n };\n}\n\nfunction sendResultAndSummarize(input: {\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n emitCompletedLifecycle?: boolean;\n executionIdentityEcho: RuntimeTransportResultIdentityEcho;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n ledgerPaths: LedgerPaths;\n leaseEpoch: number;\n payload: OpenMeldDaemonTaskResultPayload;\n presenter: Presenter;\n runtimeCoordinatorExecutionId: string | null;\n taskId: string;\n waitForSettlement?: boolean;\n}): {\n resultSummary: LocalExecutionSlotTaskResult;\n settlement: Promise<DispatchResultOutboxSettlement> | null;\n} {\n let settlement: Promise<DispatchResultOutboxSettlement> | null = null;\n try {\n if (input.emitCompletedLifecycle !== false) {\n emitDispatchLifecycleTransition({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n phase: \"completed_local\",\n presenter: input.presenter,\n executionTokenEcho: input.executionTokenEcho,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n taskId: input.taskId,\n });\n }\n settlement = enqueueDispatchResultOutboxRecord({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionIdentityEcho: input.executionIdentityEcho,\n executionTokenEcho: input.executionTokenEcho,\n ledgerPaths: input.ledgerPaths,\n leaseEpoch: input.leaseEpoch,\n payload: input.payload,\n presenter: input.presenter,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n taskId: input.taskId,\n waitForSettlement: input.waitForSettlement,\n });\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: buildResultDispatchJournalMetadata(input.payload),\n result: input.payload.status,\n taskId: input.taskId,\n type: \"dispatch.result.sent\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.result_queued\",\n text: `daemon result queued for dispatch ${input.dispatchId}`,\n payload: {\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n result: input.payload.status,\n taskId: input.taskId,\n },\n });\n } catch (error) {\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: {\n ...buildResultDispatchJournalMetadata(input.payload),\n errorMessage: toErrorMessage(error),\n },\n result: input.payload.status,\n taskId: input.taskId,\n type: \"dispatch.result.send_failed\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.result_send_failed\",\n text: `daemon result send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n result: input.payload.status,\n taskId: input.taskId,\n },\n });\n throw error;\n }\n return {\n resultSummary: summarizeTaskResultPayload(input.payload),\n settlement,\n };\n}\n\nfunction requireCompletedDispatchPlans(input: {\n bootstrapPlan: BootstrapPlan | null;\n ledgerIo: ReturnType<typeof createLedgerIo> | null;\n localRuntimeContextPlan: LocalRuntimeContextPlan | null;\n runtimePromptPlan: DispatchPromptPlan | null;\n}): {\n bootstrapPlan: BootstrapPlan;\n ledgerIo: ReturnType<typeof createLedgerIo>;\n localRuntimeContextPlan: LocalRuntimeContextPlan;\n runtimePromptPlan: DispatchPromptPlan;\n} {\n if (\n !(\n input.bootstrapPlan &&\n input.ledgerIo &&\n input.localRuntimeContextPlan &&\n input.runtimePromptPlan\n )\n ) {\n throw new DaemonServiceRunError({\n code: \"dispatch.runtime_context.incomplete\",\n message:\n \"OpenMeld could not settle the Agent reply because its runtime context is incomplete.\",\n });\n }\n return {\n bootstrapPlan: input.bootstrapPlan,\n ledgerIo: input.ledgerIo,\n localRuntimeContextPlan: input.localRuntimeContextPlan,\n runtimePromptPlan: input.runtimePromptPlan,\n };\n}\n\nasync function requestDispatchAgentInteraction(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n leasesByProfileId: Map<string, number>;\n parsedTask: ParsedDispatchTask;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n presenter: Presenter;\n request: AdapterInteractionRequest;\n}): Promise<Awaited<ReturnType<PendingAgentInteractionRegistry[\"register\"]>>> {\n const requestedAtMs = Date.now();\n const interactionCandidate: AgentInteractionRequest = {\n ...input.request,\n v: AGENT_INTERACTION_SCHEMA_VERSION,\n interactionId: randomUUID(),\n requestedAtMs,\n expiresAtMs: requestedAtMs + AGENT_INTERACTION_DEFAULT_TIMEOUT_MS,\n };\n const parsedInteraction =\n agentInteractionRequestSchema.safeParse(interactionCandidate);\n if (!parsedInteraction.success) {\n throw new DaemonServiceRunError({\n code: \"daemon.run.interaction_payload_invalid\",\n message: \"local agent produced an invalid interaction request\",\n });\n }\n\n const responsePromise = input.pendingAgentInteractionRegistry.register({\n authority: {\n attemptId: input.parsedTask.attemptId,\n dispatchId: input.parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: input.parsedTask.executionTokenEcho,\n runtimeCoordinatorExecutionId:\n input.parsedTask.runtimeCoordinatorExecutionId,\n targetProfileId: input.parsedTask.targetProfileId,\n },\n request: parsedInteraction.data,\n taskId: input.parsedTask.taskId,\n });\n try {\n sendDispatchInteractionRequestFrame({\n attemptId: input.parsedTask.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.deliverRequest.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: input.parsedTask.executionTokenEcho,\n interaction: parsedInteraction.data,\n leaseEpoch:\n input.leasesByProfileId.get(input.parsedTask.targetProfileId) ??\n input.deliverRequest.leaseEpoch,\n runtimeCoordinatorExecutionId:\n input.parsedTask.runtimeCoordinatorExecutionId,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.parsedTask.dispatchId),\n taskId: input.parsedTask.taskId,\n });\n } catch (error) {\n input.pendingAgentInteractionRegistry.reject(\n parsedInteraction.data.interactionId,\n error instanceof Error ? error : new Error(toErrorMessage(error))\n );\n throw error;\n }\n\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_requested\",\n text: `local agent is waiting for user input for task ${input.parsedTask.taskId}`,\n payload: {\n dispatchId: input.parsedTask.dispatchId,\n expiresAtMs: parsedInteraction.data.expiresAtMs,\n interactionId: parsedInteraction.data.interactionId,\n interactionKind: parsedInteraction.data.kind,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n },\n });\n return await responsePromise;\n}\n\nfunction emitDispatchPreviewFrame(input: {\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n leaseEpoch: number;\n presenter: Presenter;\n previewText: string;\n taskId: string;\n}): void {\n try {\n sendDispatchPreviewFrame({\n attemptId: input.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n previewText: input.previewText,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.dispatchId),\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.preview_send_failed\",\n text: `daemon preview send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n taskId: input.taskId,\n },\n });\n }\n}\n\nfunction emitDispatchAgentToolActivityFrame(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n event: AdapterToolActivityEvent;\n parsedTask: ParsedDispatchTask;\n presenter: Presenter;\n sequence: number;\n}): void {\n try {\n sendDispatchToolActivityFrame({\n attemptId: input.parsedTask.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.deliverRequest.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.parsedTask.dispatchId,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: input.parsedTask.executionTokenEcho,\n leaseEpoch: input.deliverRequest.leaseEpoch,\n observedAtMs: input.event.tsMs,\n part: {\n type: \"tool\",\n toolCallId: input.event.toolCallId,\n toolName: input.event.toolName,\n state: input.event.state,\n ...(input.event.work ? { work: input.event.work } : {}),\n },\n runtimeCoordinatorExecutionId:\n input.parsedTask.runtimeCoordinatorExecutionId,\n sequence: input.sequence,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.parsedTask.dispatchId),\n sourceSignalId: input.parsedTask.sourceEventId,\n spaceId: input.parsedTask.spaceId,\n targetProfileId: input.parsedTask.targetProfileId,\n taskId: input.parsedTask.taskId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.tool_activity_send_failed\",\n text: `daemon tool activity send failed for dispatch ${input.parsedTask.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.parsedTask.attemptId,\n dispatchId: input.parsedTask.dispatchId,\n sequence: input.sequence,\n state: input.event.state,\n toolName: input.event.toolName,\n taskId: input.parsedTask.taskId,\n },\n });\n }\n}\n\nfunction emitDispatchPreviewEndFrame(input: {\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n leaseEpoch: number;\n presenter: Presenter;\n taskId: string;\n}): void {\n try {\n sendDispatchPreviewEndFrame({\n attemptId: input.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.dispatchId),\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.preview_end_send_failed\",\n text: `daemon preview end send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n taskId: input.taskId,\n },\n });\n }\n}\n\nfunction emitDispatchRuntimeEvidenceTransition(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n durationMs?: number | null;\n errorName?: string | null;\n parsedTask?: ParsedDispatchTask | null;\n phase: RuntimeTransportDispatchRuntimeEvidencePhase;\n presenter: Presenter;\n reasonCode?: string | null;\n}): void {\n const identity = buildDispatchRuntimeEvidenceIdentity({\n deliverRequest: input.deliverRequest,\n parsedTask: input.parsedTask ?? null,\n });\n\n try {\n sendDispatchRuntimeEvidenceFrame({\n attemptId: identity.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.deliverRequest.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: identity.dispatchId,\n durationMs: input.durationMs ?? null,\n errorName: input.errorName ?? null,\n executionIdentityEcho: toRuntimeTransportRuntimeEvidenceIdentityEcho(\n input.deliverRequest\n ),\n executionTokenEcho: toRuntimeCoordinatorExecutionTokenEcho(\n input.deliverRequest\n ),\n leaseEpoch: input.deliverRequest.leaseEpoch,\n phase: input.phase,\n reasonCode: input.reasonCode ?? null,\n runtimeCoordinatorExecutionId:\n input.deliverRequest.payload.runtimeCoordinatorExecutionId,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(identity.dispatchId),\n sourceClientMessageId: identity.sourceClientMessageId,\n sourceSignalId: identity.sourceSignalId,\n spaceId: identity.spaceId,\n targetProfileId: identity.targetProfileId,\n taskId: identity.taskId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.runtime_evidence_send_failed\",\n text: `daemon runtime evidence ${input.phase} send failed for dispatch ${identity.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: identity.attemptId,\n dispatchId: identity.dispatchId,\n phase: input.phase,\n reasonCode: input.reasonCode ?? null,\n taskId: identity.taskId,\n },\n });\n }\n}\n\nfunction buildDispatchRuntimeEvidenceIdentity(input: {\n deliverRequest: RuntimeTransportDeliverDispatchRequest;\n parsedTask: ParsedDispatchTask | null;\n}): {\n attemptId: string;\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceSignalId: string;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n} {\n const payload = input.deliverRequest.payload;\n return {\n attemptId: input.parsedTask?.attemptId ?? input.deliverRequest.attemptId,\n dispatchId: input.parsedTask?.dispatchId ?? input.deliverRequest.dispatchId,\n sourceClientMessageId: payload.sourceClientMessageId ?? null,\n sourceSignalId: input.parsedTask?.sourceEventId ?? payload.sourceEventId,\n spaceId: input.parsedTask?.spaceId ?? payload.spaceId,\n targetProfileId:\n input.parsedTask?.targetProfileId ?? payload.targetProfileId,\n taskId: input.parsedTask?.taskId ?? payload.taskId,\n };\n}\n\nfunction toRuntimeTransportRuntimeEvidenceIdentityEcho(\n deliverRequest: RuntimeTransportDeliverDispatchRequest\n): RuntimeTransportRuntimeEvidenceIdentityEcho {\n return {\n echoSource: \"daemon_delivery_context\",\n core: deliverRequest.payload.executionIdentity.core,\n };\n}\n\nfunction toRuntimeTransportResultIdentityEcho(\n deliverRequest: RuntimeTransportDeliverDispatchRequest\n): RuntimeTransportResultIdentityEcho {\n return toRuntimeTransportResultIdentityEchoFromDeliveryIdentity(\n deliverRequest.payload.executionIdentity\n );\n}\n\nfunction toRuntimeCoordinatorExecutionTokenEcho(\n deliverRequest: RuntimeTransportDeliverDispatchRequest\n): RuntimeCoordinatorExecutionTokenEcho | null {\n const executionToken = deliverRequest.payload.executionToken;\n if (!executionToken) {\n return null;\n }\n return {\n executionToken: executionToken.executionToken,\n runId: executionToken.runId,\n runtimeCoordinatorExecutionId:\n executionToken.executionScope.runtimeCoordinatorExecutionId,\n tokenFingerprint: executionToken.tokenFingerprint,\n };\n}\n\nfunction resolveRuntimeCoordinatorExecutionTokenEchoFromRaw(\n value: unknown\n): RuntimeCoordinatorExecutionTokenEcho | null {\n const parsed =\n runtimeCoordinatorExecutionTokenEnvelopeSchema.safeParse(value);\n if (!parsed.success) {\n return null;\n }\n return {\n executionToken: parsed.data.executionToken,\n runId: parsed.data.runId,\n runtimeCoordinatorExecutionId:\n parsed.data.executionScope.runtimeCoordinatorExecutionId,\n tokenFingerprint: parsed.data.tokenFingerprint,\n };\n}\n\nfunction toRuntimeTransportResultIdentityEchoFromDeliveryIdentity(\n executionIdentity: RuntimeTransportDeliveryExecutionIdentity\n): RuntimeTransportResultIdentityEcho {\n return {\n echoSource: \"daemon_delivery_context\",\n core: executionIdentity.core,\n };\n}\n\nfunction resolveRuntimeEvidenceResultPhase(\n payload: OpenMeldDaemonTaskResultPayload\n): Extract<\n RuntimeTransportDispatchRuntimeEvidencePhase,\n \"completed\" | \"failed\"\n> {\n return payload.status === \"failed\" ? \"failed\" : \"completed\";\n}\n\nfunction resolveRuntimeEvidenceResultReasonCode(\n payload: OpenMeldDaemonTaskResultPayload\n): string | null {\n if (payload.status !== \"failed\") {\n return null;\n }\n return normalizeOptionalText(payload.errorCode) ?? null;\n}\n\nfunction toRuntimeTransportDispatchLocalQueueDiagnostics(\n input: LocalExecutionSlotDiagnostics\n): RuntimeTransportDispatchLocalQueueDiagnostics {\n return {\n activeForLane: input.activeForLane,\n activeGlobal: input.activeGlobal,\n globalConcurrency: input.limits.globalConcurrency,\n queueDepth: input.queueDepth,\n queueMax: input.limits.queueMax,\n queuePosition: input.queuePosition,\n status: input.status,\n waitReason: input.waitReason,\n };\n}\n\nfunction emitDispatchLifecycleTransition(input: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n localQueue?: RuntimeTransportDispatchLocalQueueDiagnostics | null;\n phase: DispatchLifecyclePhase;\n presenter: Presenter;\n runtimeCoordinatorExecutionId: string | null;\n taskId: string;\n}): void {\n try {\n sendCurrentDispatchLifecycleFrame({\n agentControllerConversationOccupancy:\n input.agentControllerConversationOccupancy ?? null,\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionTokenEcho: input.executionTokenEcho,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n });\n } catch (error) {\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: {\n errorMessage: toErrorMessage(error),\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n },\n result: \"failed\",\n taskId: input.taskId,\n type: \"dispatch.lifecycle.send_failed\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.lifecycle_send_failed\",\n text: `daemon lifecycle ${input.phase} send failed for dispatch ${input.dispatchId}: ${toErrorMessage(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n phase: input.phase,\n taskId: input.taskId,\n },\n });\n return;\n }\n emitDaemonDispatchJournalEvent({\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n metadata: {\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n },\n result: \"sent\",\n taskId: input.taskId,\n type: \"dispatch.lifecycle.sent\",\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.lifecycle_sent\",\n text: `daemon lifecycle ${input.phase} sent for dispatch ${input.dispatchId}`,\n payload: {\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n taskId: input.taskId,\n },\n });\n}\n\nfunction resolveInitialDispatchLifecyclePhase(input: {\n providerAdmissionOwnsRunningLifecycle: boolean;\n}): Extract<DispatchLifecyclePhase, \"accepted_local\" | \"running\"> {\n return input.providerAdmissionOwnsRunningLifecycle\n ? \"accepted_local\"\n : \"running\";\n}\n\nfunction startDispatchLifecycleKeepalive(input: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n localQueue?: RuntimeTransportDispatchLocalQueueDiagnostics | null;\n phase: Extract<DispatchLifecyclePhase, \"accepted_local\" | \"running\">;\n presenter: Presenter;\n runtimeCoordinatorExecutionId: string | null;\n taskId: string;\n}): () => void {\n let intervalCount = 0;\n let lastOccupancyConnectionGeneration: number | null = null;\n const intervalId = setInterval(() => {\n try {\n const currentConnectionGeneration = resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n });\n const shouldReassertOccupancy = Boolean(\n input.agentControllerConversationOccupancy &&\n (intervalCount %\n AGENT_CONTROLLER_OCCUPANCY_KEEPALIVE_REASSERT_INTERVALS ===\n 0 ||\n lastOccupancyConnectionGeneration !== currentConnectionGeneration)\n );\n intervalCount += 1;\n if (shouldReassertOccupancy) {\n lastOccupancyConnectionGeneration = currentConnectionGeneration;\n }\n sendCurrentDispatchLifecycleFrame({\n agentControllerConversationOccupancy: shouldReassertOccupancy\n ? (input.agentControllerConversationOccupancy ?? null)\n : null,\n attemptId: input.attemptId,\n connectionGeneration: input.connectionGeneration,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n executionTokenEcho: input.executionTokenEcho,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n });\n } catch (error) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.lifecycle_keepalive_failed\",\n text: `daemon lifecycle keepalive failed for dispatch ${input.dispatchId}: ${error instanceof Error ? error.message : String(error)}`,\n payload: {\n attemptId: input.attemptId,\n dispatchId: input.dispatchId,\n phase: input.phase,\n taskId: input.taskId,\n },\n });\n }\n }, DEFAULT_TASK_LIFECYCLE_HEARTBEAT_INTERVAL_MS);\n\n return () => {\n clearInterval(intervalId);\n };\n}\n\nfunction sendCurrentDispatchLifecycleFrame(input: {\n agentControllerConversationOccupancy?: RuntimeTransportAgentControllerConversationOccupancy | null;\n attemptId: string;\n connectionGeneration: number;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n dispatchId: string;\n executionTokenEcho: RuntimeCoordinatorExecutionTokenEcho | null;\n leaseEpoch: number;\n localQueue?: RuntimeTransportDispatchLocalQueueDiagnostics | null;\n phase: DispatchLifecyclePhase;\n runtimeCoordinatorExecutionId: string | null;\n}): void {\n sendDispatchLifecycleFrame({\n agentControllerConversationOccupancy:\n input.agentControllerConversationOccupancy ?? null,\n attemptId: input.attemptId,\n connectionGeneration: resolveCurrentConnectionGeneration({\n currentSocketRef: input.currentSocketRef,\n fallbackConnectionGeneration: input.connectionGeneration,\n }),\n daemonSessionId: input.daemonSessionId,\n dispatchId: input.dispatchId,\n leaseEpoch: input.leaseEpoch,\n localQueue: input.localQueue ?? null,\n phase: input.phase,\n executionTokenEcho: input.executionTokenEcho,\n runtimeCoordinatorExecutionId: input.runtimeCoordinatorExecutionId,\n socket:\n input.currentSocketRef.socket ??\n failMissingCurrentSocket(input.dispatchId),\n });\n}\n\nfunction resolveCurrentConnectionGeneration(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n fallbackConnectionGeneration: number;\n}): number {\n return (\n input.currentSocketRef.connectionGeneration ??\n input.fallbackConnectionGeneration\n );\n}\n\nfunction failMissingCurrentSocket(dispatchId: string): never {\n throw new DaemonServiceRunError({\n code: \"daemon.run.socket_unavailable\",\n message: `active daemon socket is unavailable for dispatch ${dispatchId}`,\n });\n}\n","import type {\n AdapterCancelResult,\n AdapterInterruptResult,\n AdapterLocalAttemptOutcome,\n} from \"@openmeld/adapter-core\";\nimport type {\n InflightTaskControlRecord,\n InflightTaskControlRegistry,\n LocalDaemonAdapterContainer,\n} from \"@openmeld/local-service\";\nimport {\n OPENMELD_DAEMON_CANCEL_STOP_REQUESTED_AFTER_START_REASON_CODE,\n OPENMELD_DAEMON_CANCEL_WITHDRAWN_BEFORE_START_REASON_CODE,\n} from \"@openmeld/schemas\";\nimport type {\n OpenMeldDaemonCancelRequestPayload,\n OpenMeldDaemonControlPlaneResponse,\n OpenMeldDaemonInterruptRequestPayload,\n} from \"@openmeld/schemas/types\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine } from \"../core/logger\";\n\ntype LocalControlCancelPayload = Extract<\n OpenMeldDaemonControlPlaneResponse,\n { code: \"service.cancel\" }\n>[\"payload\"];\ntype LocalControlInterruptPayload = Extract<\n OpenMeldDaemonControlPlaneResponse,\n { code: \"service.interrupt\" }\n>[\"payload\"];\n\nexport async function handleLocalControlPlaneCancel(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n registry: InflightTaskControlRegistry;\n}): Promise<LocalControlCancelPayload> {\n const resolution = input.registry.resolveTarget(input.payload.target);\n if (!resolution) {\n return (\n replayRecordedWithdrawal(input) ?? rejectMissingInflightTarget(input)\n );\n }\n\n if (\n input.payload.runtimeCoordinatorExecutionId &&\n resolution.record.runtimeCoordinatorExecutionId !==\n input.payload.runtimeCoordinatorExecutionId\n ) {\n return rejectRuntimeCoordinatorExecutionMismatch({\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const adapterEntry = input.localAdapterContainer.getAdapter(\n resolution.record.adapterId\n );\n const adapter = adapterEntry?.adapter ?? null;\n if (!adapter?.cancel) {\n return rejectMissingAdapterCancel({\n adapterPresent: Boolean(adapter),\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const result = await adapter.cancel({\n ...(input.payload.reason ? { reason: input.payload.reason } : {}),\n taskId: resolution.record.taskId,\n });\n if (result.accepted) {\n const currentRecord = input.registry.getTask(resolution.record.taskId);\n if (\n currentRecord?.dispatchId === resolution.record.dispatchId &&\n currentRecord.runtimeCoordinatorExecutionId ===\n resolution.record.runtimeCoordinatorExecutionId\n ) {\n if (result.localAttemptOutcome) {\n input.registry.settleWithdrawnTask({\n localAttemptOutcome: result.localAttemptOutcome,\n record: currentRecord,\n });\n }\n input.registry.removeTask(resolution.record.taskId);\n }\n }\n const reasonCode = result.accepted\n ? resolveAcceptedCancelReasonCode(result.localAttemptOutcome)\n : result.reasonCode;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel\",\n text: `local cancel ${result.accepted ? \"accepted\" : \"rejected\"} for dispatch ${resolution.record.dispatchId}`,\n payload: {\n accepted: result.accepted,\n adapterId: resolution.record.adapterId,\n deliveryPath: result.deliveryPath ?? null,\n dispatchId: resolution.record.dispatchId,\n reasonCode,\n signalDelivery: result.signalDelivery,\n target: input.payload.target,\n taskId: resolution.record.taskId,\n },\n });\n return {\n accepted: result.accepted,\n note: resolveAdapterCancelNote({ reasonCode, result }),\n reasonCode,\n resolvedDispatchId: resolution.record.dispatchId,\n ...(resolution.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n resolution.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: resolution.record.taskId,\n target: input.payload.target,\n };\n}\n\n/**\n * Names what an accepted cancellation established.\n *\n * The distinction rides the existing reason code rather than a new payload key:\n * these control payloads are strict objects, so a Service that emitted a new\n * key would have its whole frame rejected by a Core that predates it, and a\n * local component can reach a user before the matching Core deploy.\n */\nfunction resolveAcceptedCancelReasonCode(\n localAttemptOutcome: AdapterLocalAttemptOutcome | undefined\n): string {\n if (localAttemptOutcome === \"withdrawn_before_start\") {\n return OPENMELD_DAEMON_CANCEL_WITHDRAWN_BEFORE_START_REASON_CODE;\n }\n return localAttemptOutcome === \"stop_requested_after_start\"\n ? OPENMELD_DAEMON_CANCEL_STOP_REQUESTED_AFTER_START_REASON_CODE\n : \"adapter.cancel.accepted\";\n}\n\n/**\n * Answers a repeat request from what the withdrawal already established.\n *\n * Accepting a withdrawal removes the inflight record, so without this a repeat\n * could only answer \"no such task\". That is a weaker statement than what was\n * actually established and cannot be turned back into proof, which would leave\n * work that replaces this attempt blocked on evidence merely lost in transit.\n */\nfunction replayRecordedWithdrawal(input: {\n payload: OpenMeldDaemonCancelRequestPayload;\n registry: InflightTaskControlRegistry;\n}): LocalControlCancelPayload | null {\n const receipt = input.registry.readWithdrawnTaskReceipt(input.payload.target);\n if (\n !receipt ||\n (input.payload.runtimeCoordinatorExecutionId &&\n receipt.record.runtimeCoordinatorExecutionId !==\n input.payload.runtimeCoordinatorExecutionId)\n ) {\n return null;\n }\n return {\n accepted: true,\n note: \"Replayed the recorded withdrawal for this attempt.\",\n reasonCode: resolveAcceptedCancelReasonCode(receipt.localAttemptOutcome),\n resolvedDispatchId: receipt.record.dispatchId,\n ...(receipt.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n receipt.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: receipt.record.taskId,\n target: input.payload.target,\n };\n}\n\nexport async function handleLocalControlPlaneInterrupt(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n registry: InflightTaskControlRegistry;\n}): Promise<LocalControlInterruptPayload> {\n const resolution = input.registry.resolveTarget(input.payload.target);\n if (!resolution) {\n return rejectMissingInflightInterruptTarget(input);\n }\n\n if (\n input.payload.runtimeCoordinatorExecutionId &&\n resolution.record.runtimeCoordinatorExecutionId !==\n input.payload.runtimeCoordinatorExecutionId\n ) {\n return rejectInterruptRuntimeCoordinatorExecutionMismatch({\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const adapterEntry = input.localAdapterContainer.getAdapter(\n resolution.record.adapterId\n );\n const adapter = adapterEntry?.adapter ?? null;\n if (!adapter?.interrupt) {\n return rejectMissingAdapterInterrupt({\n adapterPresent: Boolean(adapter),\n payload: input.payload,\n presenter: input.presenter,\n record: resolution.record,\n });\n }\n\n const result = await adapter.interrupt({\n ...(input.payload.mode ? { mode: input.payload.mode } : {}),\n ...(input.payload.reason ? { reason: input.payload.reason } : {}),\n taskId: resolution.record.taskId,\n });\n const reasonCode = result.accepted\n ? \"adapter.interrupt.accepted\"\n : result.reasonCode;\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt\",\n text: `local interrupt ${result.accepted ? \"accepted\" : \"rejected\"} for dispatch ${resolution.record.dispatchId}`,\n payload: {\n accepted: result.accepted,\n adapterId: resolution.record.adapterId,\n dispatchId: resolution.record.dispatchId,\n reasonCode,\n signalDelivery: result.signalDelivery,\n target: input.payload.target,\n taskId: resolution.record.taskId,\n },\n });\n return {\n accepted: result.accepted,\n note: resolveAdapterInterruptNote({ reasonCode, result }),\n reasonCode,\n resolvedDispatchId: resolution.record.dispatchId,\n ...(resolution.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n resolution.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: resolution.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingInflightTarget(input: {\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n}): LocalControlCancelPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_rejected\",\n text: \"local cancel rejected because the target is not inflight\",\n payload: {\n accepted: false,\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n },\n });\n return {\n accepted: false,\n note: \"task.not_found\",\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingInflightInterruptTarget(input: {\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n}): LocalControlInterruptPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_rejected\",\n text: \"local interrupt rejected because the target is not inflight\",\n payload: {\n accepted: false,\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n },\n });\n return {\n accepted: false,\n note: \"task.not_found\",\n reasonCode: \"task.not_found\",\n target: input.payload.target,\n };\n}\n\nfunction rejectRuntimeCoordinatorExecutionMismatch(input: {\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlCancelPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_rejected\",\n text: `local cancel rejected because RuntimeCoordinator execution identity did not match dispatch ${input.record.dispatchId}`,\n payload: {\n accepted: false,\n dispatchId: input.record.dispatchId,\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n requestedRuntimeCoordinatorExecutionId:\n input.payload.runtimeCoordinatorExecutionId,\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: \"runtime_coordinator.execution_id_mismatch\",\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectInterruptRuntimeCoordinatorExecutionMismatch(input: {\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlInterruptPayload {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_rejected\",\n text: `local interrupt rejected because RuntimeCoordinator execution identity did not match dispatch ${input.record.dispatchId}`,\n payload: {\n accepted: false,\n dispatchId: input.record.dispatchId,\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n requestedRuntimeCoordinatorExecutionId:\n input.payload.runtimeCoordinatorExecutionId,\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: \"runtime_coordinator.execution_id_mismatch\",\n reasonCode: \"runtime_coordinator.execution_id_mismatch\",\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingAdapterCancel(input: {\n adapterPresent: boolean;\n payload: OpenMeldDaemonCancelRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlCancelPayload {\n const reasonCode = input.adapterPresent\n ? \"adapter.unsupported\"\n : \"adapter.missing\";\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_rejected\",\n text: `local cancel rejected because adapter '${input.record.adapterId}' does not expose cancel control`,\n payload: {\n accepted: false,\n adapterId: input.record.adapterId,\n dispatchId: input.record.dispatchId,\n reasonCode,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: reasonCode,\n reasonCode,\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction rejectMissingAdapterInterrupt(input: {\n adapterPresent: boolean;\n payload: OpenMeldDaemonInterruptRequestPayload;\n presenter: Presenter;\n record: InflightTaskControlRecord;\n}): LocalControlInterruptPayload {\n const reasonCode = input.adapterPresent\n ? \"adapter.unsupported\"\n : \"adapter.missing\";\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_rejected\",\n text: `local interrupt rejected because adapter '${input.record.adapterId}' does not expose interrupt control`,\n payload: {\n accepted: false,\n adapterId: input.record.adapterId,\n dispatchId: input.record.dispatchId,\n reasonCode,\n target: input.payload.target,\n taskId: input.record.taskId,\n },\n });\n return {\n accepted: false,\n note: reasonCode,\n reasonCode,\n resolvedDispatchId: input.record.dispatchId,\n ...(input.record.runtimeCoordinatorExecutionId\n ? {\n resolvedRuntimeCoordinatorExecutionId:\n input.record.runtimeCoordinatorExecutionId,\n }\n : {}),\n resolvedTaskId: input.record.taskId,\n target: input.payload.target,\n };\n}\n\nfunction resolveAdapterCancelNote(input: {\n reasonCode: string;\n result: AdapterCancelResult;\n}): string {\n if (input.result.accepted) {\n return input.result.deliveryPath ?? input.reasonCode;\n }\n if (input.result.reasonDetail) {\n return `${input.result.reasonCode}: ${input.result.reasonDetail}`;\n }\n return input.reasonCode;\n}\n\nfunction resolveAdapterInterruptNote(input: {\n reasonCode: string;\n result: AdapterInterruptResult;\n}): string {\n if (input.result.accepted) {\n return input.reasonCode;\n }\n if (input.result.reasonDetail) {\n return `${input.result.reasonCode}: ${input.result.reasonDetail}`;\n }\n return input.reasonCode;\n}\n","import type {\n InflightTaskControlRegistry,\n LocalDaemonAdapterContainer,\n LocalExecutionSlots,\n PendingAgentInteractionRegistry,\n} from \"@openmeld/local-service\";\nimport {\n localAgentReasoningPreferencesSchema,\n RUNTIME_TRANSPORT_SCHEMA_VERSION,\n runtimeTransportDispatchInteractionDeliveredRequestSchema,\n runtimeTransportDispatchInteractionResponseFramePayloadSchema,\n runtimeTransportLocalAgentControlCancelFramePayloadSchema,\n runtimeTransportLocalAgentControlInterruptFramePayloadSchema,\n} from \"@openmeld/schemas\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type {\n CurrentDaemonSocketRef,\n DaemonFrameSink,\n DaemonProfileRouteConfig,\n InflightDispatchMeta,\n LedgerPaths,\n ParsedDaemonFrame,\n PendingFrameWaiters,\n} from \"../core/types\";\nimport {\n acknowledgeDispatchResultOutboxRecord,\n flushDispatchResultOutbox,\n} from \"../dispatch/dispatch-result-outbox\";\nimport { enqueueDispatchDeliverFrame } from \"../dispatch/execute-dispatch-task\";\nimport {\n emitDaemonErrorFrame,\n resolveHeartbeatResponseFrame,\n resolveRegisterResponseFrame,\n sendDaemonFrame,\n} from \"./daemon-frame-transport\";\nimport {\n handleLocalControlPlaneCancel,\n handleLocalControlPlaneInterrupt,\n} from \"./local-control-handlers\";\n\nfunction handleDispatchInteractionResponse(input: {\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n leasesByProfileId: Map<string, number>;\n payload: Record<string, unknown>;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n presenter: Presenter;\n socket: DaemonFrameSink;\n}): void {\n const parsedResponse =\n runtimeTransportDispatchInteractionResponseFramePayloadSchema.safeParse(\n input.payload\n );\n if (!parsedResponse.success) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_invalid\",\n text: \"local agent interaction response was rejected because the payload is invalid\",\n });\n return;\n }\n const pendingInteraction = input.pendingAgentInteractionRegistry.get(\n parsedResponse.data.interactionId\n );\n if (!pendingInteraction) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_not_found\",\n text: `local agent interaction ${parsedResponse.data.interactionId} is no longer pending`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const authority = pendingInteraction.authority;\n if (\n authority.attemptId !== parsedResponse.data.attemptId ||\n authority.dispatchId !== parsedResponse.data.dispatchId ||\n authority.runtimeCoordinatorExecutionId !==\n parsedResponse.data.runtimeCoordinatorExecutionId\n ) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_authority_mismatch\",\n text: `local agent interaction ${parsedResponse.data.interactionId} did not match the active execution`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const resolution = input.pendingAgentInteractionRegistry.resolve({\n interactionId: parsedResponse.data.interactionId,\n response: parsedResponse.data.response,\n });\n if (!resolution || resolution.status === \"response_invalid\") {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_response_invalid\",\n text: `local agent interaction ${parsedResponse.data.interactionId} received an invalid answer`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const connectionGeneration = input.currentSocketRef.connectionGeneration;\n const leaseEpoch = input.leasesByProfileId.get(authority.targetProfileId);\n if (!(connectionGeneration && leaseEpoch)) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_delivery_deferred\",\n text: `local agent interaction ${parsedResponse.data.interactionId} resumed locally; delivery acknowledgement is waiting for the active lease`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n return;\n }\n const deliveredRequest =\n runtimeTransportDispatchInteractionDeliveredRequestSchema.parse({\n v: RUNTIME_TRANSPORT_SCHEMA_VERSION,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n executionTokenEcho: authority.executionTokenEcho,\n dispatchId: parsedResponse.data.dispatchId,\n attemptId: parsedResponse.data.attemptId,\n executionIdentityEcho: authority.executionIdentityEcho,\n daemonSessionId: input.daemonSessionId,\n connectionGeneration,\n leaseEpoch,\n interactionId: parsedResponse.data.interactionId,\n deliveredAtMs: Date.now(),\n });\n sendDaemonFrame(input.socket, {\n code: \"daemon.dispatch.interaction_delivered\",\n payload: deliveredRequest,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.interaction_resolved\",\n text: `local agent resumed after user input for interaction ${parsedResponse.data.interactionId}`,\n payload: {\n interactionId: parsedResponse.data.interactionId,\n resolutionStatus: resolution.status,\n runtimeCoordinatorExecutionId:\n parsedResponse.data.runtimeCoordinatorExecutionId,\n },\n });\n}\n\nfunction applyReasoningPreference(\n ref: CurrentDaemonSocketRef,\n payload: unknown\n): void {\n const preference = localAgentReasoningPreferencesSchema.safeParse(payload);\n if (\n !preference.success ||\n ref.reasoningStreamEnabled === preference.data.enabled\n ) {\n return;\n }\n ref.reasoningStreamEnabled = preference.data.enabled;\n for (const listener of ref.reasoningPreferenceListeners ?? []) {\n listener();\n }\n}\n\nexport function handleDaemonSocketFrame(input: {\n computerFileAccessStorePath: string;\n contextStore: Map<string, string>;\n currentSocketRef: CurrentDaemonSocketRef;\n daemonSessionId: string;\n localExecutionSlots: LocalExecutionSlots;\n inflightDispatchMetaByTaskId: Map<string, InflightDispatchMeta>;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n pendingAgentInteractionRegistry: PendingAgentInteractionRegistry;\n ledgerPaths: LedgerPaths;\n leasesByProfileId: Map<string, number>;\n localAdapterContainer: LocalDaemonAdapterContainer;\n parsedFrame: ParsedDaemonFrame;\n profileOwnerName: string | null;\n profileOwnerUserId: string;\n requestCurrentWorkingFolderFactRefresh?: () => void;\n presenter: Presenter;\n routeByProfileId: Map<string, DaemonProfileRouteConfig>;\n socket: DaemonFrameSink;\n waiters: PendingFrameWaiters;\n}): void {\n switch (input.parsedFrame.code) {\n case \"daemon.reasoning.preferences\": {\n applyReasoningPreference(\n input.currentSocketRef,\n input.parsedFrame.payload\n );\n return;\n }\n case \"daemon.session.register\":\n resolveRegisterResponseFrame({\n payload: input.parsedFrame.payload,\n presenter: input.presenter,\n waiters: input.waiters,\n });\n return;\n case \"daemon.session.heartbeat\":\n resolveHeartbeatResponseFrame({\n payload: input.parsedFrame.payload,\n presenter: input.presenter,\n waiters: input.waiters,\n });\n return;\n case \"daemon.dispatch.deliver\":\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.dispatch_deliver_received\",\n text: `deliver frame received for dispatch ${String(input.parsedFrame.payload.dispatchId ?? \"unknown\")}`,\n payload: {\n attemptId: input.parsedFrame.payload.attemptId ?? null,\n connectionGeneration: input.parsedFrame.payload.connectionGeneration,\n deliveryRecoveryReason:\n input.parsedFrame.payload.deliveryRecoveryReason ?? null,\n dispatchId: input.parsedFrame.payload.dispatchId ?? null,\n leaseEpoch: input.parsedFrame.payload.leaseEpoch ?? null,\n profileId: input.parsedFrame.payload.profileId ?? null,\n taskId: input.parsedFrame.payload.taskId ?? null,\n },\n });\n enqueueDispatchDeliverFrame({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n contextStore: input.contextStore,\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n localExecutionSlots: input.localExecutionSlots,\n inflightDispatchMetaByTaskId: input.inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry: input.inflightTaskControlRegistry,\n pendingAgentInteractionRegistry: input.pendingAgentInteractionRegistry,\n ledgerPaths: input.ledgerPaths,\n leasesByProfileId: input.leasesByProfileId,\n localAdapterContainer: input.localAdapterContainer,\n payload: input.parsedFrame.payload,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: input.profileOwnerUserId,\n requestCurrentWorkingFolderFactRefresh:\n input.requestCurrentWorkingFolderFactRefresh,\n presenter: input.presenter,\n routeByProfileId: input.routeByProfileId,\n socket: input.socket,\n });\n return;\n case \"daemon.dispatch.accepted\":\n acknowledgeDispatchResultOutboxRecord({\n attemptId: normalizeOptionalFrameValue(\n input.parsedFrame.payload.attemptId\n ),\n dispatchId:\n normalizeOptionalFrameValue(input.parsedFrame.payload.dispatchId) ??\n \"unknown\",\n ledgerPaths: input.ledgerPaths,\n ok: input.parsedFrame.payload.ok === true,\n presenter: input.presenter,\n reasonCode: normalizeOptionalFrameValue(\n input.parsedFrame.payload.reasonCode\n ),\n status: normalizeResultAckStatus(input.parsedFrame.payload.status),\n });\n flushDispatchResultOutbox({\n currentSocketRef: input.currentSocketRef,\n ledgerPaths: input.ledgerPaths,\n presenter: input.presenter,\n });\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.result_acknowledged\",\n text: `daemon result acknowledged for dispatch ${String(input.parsedFrame.payload.dispatchId ?? \"unknown\")}`,\n payload: {\n attemptId: input.parsedFrame.payload.attemptId ?? null,\n dispatchId: input.parsedFrame.payload.dispatchId ?? null,\n ok: input.parsedFrame.payload.ok ?? null,\n reasonCode: input.parsedFrame.payload.reasonCode ?? null,\n status: input.parsedFrame.payload.status ?? null,\n },\n });\n return;\n case \"daemon.dispatch.interaction_response\":\n handleDispatchInteractionResponse({\n currentSocketRef: input.currentSocketRef,\n daemonSessionId: input.daemonSessionId,\n leasesByProfileId: input.leasesByProfileId,\n payload: input.parsedFrame.payload,\n pendingAgentInteractionRegistry: input.pendingAgentInteractionRegistry,\n presenter: input.presenter,\n socket: input.socket,\n });\n return;\n case \"daemon.local_agent_control.cancel\": {\n const parsedCancelFrame =\n runtimeTransportLocalAgentControlCancelFramePayloadSchema.safeParse(\n input.parsedFrame.payload\n );\n if (!parsedCancelFrame.success) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_frame_invalid\",\n text: \"local cancel frame rejected because the payload is invalid\",\n });\n return;\n }\n handleLocalControlPlaneCancel({\n localAdapterContainer: input.localAdapterContainer,\n payload: parsedCancelFrame.data.payload,\n presenter: input.presenter,\n registry: input.inflightTaskControlRegistry,\n })\n .then((payload) => {\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedCancelFrame.data.requestId,\n payload,\n },\n });\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_cancel_failed\",\n text: `local cancel handling failed: ${toErrorMessage(error)}`,\n payload: {\n requestId: parsedCancelFrame.data.requestId,\n target: parsedCancelFrame.data.payload.target,\n },\n });\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedCancelFrame.data.requestId,\n payload: {\n accepted: false,\n note: toErrorMessage(error),\n reasonCode: \"local_control.unhandled_error\",\n target: parsedCancelFrame.data.payload.target,\n },\n },\n });\n });\n return;\n }\n case \"daemon.local_agent_control.interrupt\": {\n const parsedInterruptFrame =\n runtimeTransportLocalAgentControlInterruptFramePayloadSchema.safeParse(\n input.parsedFrame.payload\n );\n if (!parsedInterruptFrame.success) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_frame_invalid\",\n text: \"local interrupt frame rejected because the payload is invalid\",\n });\n return;\n }\n handleLocalControlPlaneInterrupt({\n localAdapterContainer: input.localAdapterContainer,\n payload: parsedInterruptFrame.data.payload,\n presenter: input.presenter,\n registry: input.inflightTaskControlRegistry,\n })\n .then((payload) => {\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedInterruptFrame.data.requestId,\n payload,\n },\n });\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_interrupt_failed\",\n text: `local interrupt handling failed: ${toErrorMessage(error)}`,\n payload: {\n requestId: parsedInterruptFrame.data.requestId,\n target: parsedInterruptFrame.data.payload.target,\n },\n });\n sendDaemonFrame(input.socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsedInterruptFrame.data.requestId,\n payload: {\n accepted: false,\n note: toErrorMessage(error),\n reasonCode: \"local_control.unhandled_error\",\n target: parsedInterruptFrame.data.payload.target,\n },\n },\n });\n });\n return;\n }\n case \"daemon.error\":\n emitDaemonErrorFrame({\n payload: input.parsedFrame.payload,\n presenter: input.presenter,\n waiters: input.waiters,\n });\n return;\n case \"daemon.dispatch.result\":\n return;\n default:\n return;\n }\n}\n\nfunction normalizeOptionalFrameValue(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeResultAckStatus(\n value: unknown\n): \"accepted\" | \"rejected_terminal\" | \"review_required\" | \"retry_later\" | null {\n return value === \"accepted\" ||\n value === \"rejected_terminal\" ||\n value === \"review_required\" ||\n value === \"retry_later\"\n ? value\n : null;\n}\n\nexport function emitDispatchQueueError(input: {\n error: unknown;\n presenter: Presenter;\n}): void {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.dispatch_unhandled_error\",\n text: `dispatch handling failed: ${toErrorMessage(input.error)}`,\n });\n}\n","import { AGENT_PROFILE_WORK_CONCURRENCY_LIMIT } from \"@openmeld/agent-runtime\";\nimport {\n createLocalExecutionSlots,\n type LocalExecutionSlots,\n} from \"@openmeld/local-service\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine } from \"../core/logger\";\nimport type { DaemonDispatchLimits } from \"../core/types\";\n\nexport function createDaemonLocalExecutionSlots(input: {\n limits: DaemonDispatchLimits;\n presenter: Presenter;\n onChanged?: () => void;\n}): LocalExecutionSlots {\n return createLocalExecutionSlots({\n onChanged: input.onChanged,\n limits: {\n ...input.limits,\n contextConcurrency: AGENT_PROFILE_WORK_CONCURRENCY_LIMIT,\n },\n onTaskDropped: (event) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_dropped\",\n text: `local execution slot dropped pending task ${event.taskId} for ${event.targetLabel}: ${event.reason}`,\n payload: {\n adapterId: event.adapterId,\n activeForLane: event.activeForLane,\n activeGlobal: event.activeGlobal,\n controllerKey: event.controllerKey,\n dispatchId: event.dispatchId,\n globalConcurrency: event.limits.globalConcurrency,\n localExecutionLaneKey: event.localExecutionLaneKey,\n profileId: event.profileId,\n queueDepth: event.queueDepth,\n localQueueStatus: event.localQueue.status,\n localQueueWaitReason: event.localQueue.waitReason,\n queuePosition: event.localQueue.queuePosition,\n queueMax: event.limits.queueMax,\n reason: event.reason,\n spaceId: event.spaceId,\n step: \"dropped\",\n taskId: event.taskId,\n targetLabel: event.targetLabel,\n transportMode: event.transportMode,\n },\n });\n },\n onTaskStarted: (event) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_reserved\",\n text: `local execution slot reserved task ${event.taskId} for ${event.targetLabel}`,\n payload: {\n adapterId: event.adapterId,\n activeForLane: event.activeForLane,\n activeGlobal: event.activeGlobal,\n controllerKey: event.controllerKey,\n dispatchId: event.dispatchId,\n durationMs: null,\n errorCode: null,\n globalConcurrency: event.limits.globalConcurrency,\n localExecutionLaneKey: event.localExecutionLaneKey,\n profileId: event.profileId,\n queueDepth: event.queueDepth,\n localQueueStatus: event.localQueue.status,\n localQueueWaitReason: event.localQueue.waitReason,\n queuePosition: event.localQueue.queuePosition,\n queueMax: event.limits.queueMax,\n result: null,\n spaceId: event.spaceId,\n step: \"started\",\n taskId: event.taskId,\n targetLabel: event.targetLabel,\n transportMode: event.transportMode,\n },\n });\n },\n onTaskCompleted: (event) => {\n let completionText = `local execution slot failed task ${event.taskId} for ${event.targetLabel}`;\n if (event.result === \"success\") {\n completionText = `local execution slot completed task ${event.taskId} for ${event.targetLabel}`;\n } else if (event.result === \"partial_success\") {\n completionText = `local execution slot partially completed task ${event.taskId} for ${event.targetLabel}`;\n }\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.local_execution_slot_completed\",\n text: completionText,\n payload: {\n adapterId: event.adapterId,\n activeForLane: event.activeForLane,\n activeGlobal: event.activeGlobal,\n controllerKey: event.controllerKey,\n dispatchId: event.dispatchId,\n durationMs: event.durationMs,\n errorCode: event.errorCode,\n ...(event.errorMessage ? { errorMessage: event.errorMessage } : {}),\n globalConcurrency: event.limits.globalConcurrency,\n localExecutionLaneKey: event.localExecutionLaneKey,\n profileId: event.profileId,\n queueDepth: event.queueDepth,\n localQueueStatus: event.localQueue.status,\n localQueueWaitReason: event.localQueue.waitReason,\n queuePosition: event.localQueue.queuePosition,\n queueMax: event.limits.queueMax,\n result: event.result,\n spaceId: event.spaceId,\n step: \"completed\",\n taskId: event.taskId,\n targetLabel: event.targetLabel,\n transportMode: event.transportMode,\n },\n });\n },\n });\n}\n","import {\n resolveCodexTimeoutMs,\n verifyCodexAppServerThread,\n} from \"@openmeld/adapter-codex\";\nimport {\n buildAgentContextLookupKey,\n buildRuntimeWorkspaceFingerprint,\n loadLedgerState,\n} from \"@openmeld/local-execution\";\nimport {\n resolveCompatibleAgentContextMatch,\n resolveCompatibleConversationExecutionState,\n} from \"@openmeld/local-service\";\nimport {\n buildAgentControllerConversationRef,\n normalizeKnownBuiltinAgentControllerId,\n resolveBuiltinAgentControllerConversationKind,\n} from \"@openmeld/schemas\";\nimport type {\n ConversationExecutionState,\n OpenMeldDaemonConversationExecutionStatusPayload,\n OpenMeldDaemonConversationExecutionStatusRequestPayload,\n RuntimeAgentControllerLaunchContract,\n} from \"@openmeld/schemas/types\";\nimport { resolveProfileWorkspaceRuntime } from \"../../profile-workspace/runtime-resolution\";\nimport { normalizeOptionalText } from \"../core/logger\";\nimport {\n readLocalEnabledControllers,\n resolveLocalController,\n} from \"../routing/resolve-controller-support\";\nimport {\n buildLedgerPaths,\n ensureDaemonRuntimePaths,\n} from \"../state/daemon-device-id\";\nimport { createLedgerIo } from \"../state/ledger-io\";\n\nexport async function resolveLocalConversationExecutionStatus(\n input: OpenMeldDaemonConversationExecutionStatusRequestPayload\n): Promise<OpenMeldDaemonConversationExecutionStatusPayload> {\n const localControllers = await readLocalEnabledControllers();\n const localController = resolveLocalController({\n agentControllerRef: input.agentControllerRef,\n localControllers,\n });\n const workspaceResolution = await resolveProfileWorkspaceRuntime({\n openMeldProfileId: input.targetProfileId,\n mode: \"dispatch\",\n });\n const localLedgerStatus = await resolveLocalLedgerConversationExecution({\n agentControllerRef: input.agentControllerRef,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n transportMode: input.transportMode,\n workspaceResolution,\n });\n const providerConversationProof =\n input.validate === true\n ? await resolveLocalProviderConversationProof({\n boundAgentControllerRef: input.boundAgentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n launchContract: localController?.launchContract ?? null,\n profileAgentControllerRef: input.agentControllerRef,\n runtimeWorkingDirectory:\n workspaceResolution.status === \"ready\"\n ? workspaceResolution.effectiveRuntimeWorkingDirectory\n : null,\n transportMode: input.transportMode,\n })\n : buildProviderConversationProofNotRun(input.transportMode);\n\n return {\n agentContextLookupKey: localLedgerStatus.agentContextLookupKey,\n controllerLaunchStatus: resolveControllerLaunchStatus(localController),\n executionState: localLedgerStatus.executionState,\n localRuntimeContext: {\n agentContextLookupKey: localLedgerStatus.agentContextLookupKey,\n runtimeWorkspaceFingerprint:\n localLedgerStatus.runtimeWorkspaceFingerprint,\n status: resolveLocalRuntimeContextStatus({\n agentControllerConversationId: input.agentControllerConversationId,\n executionState: localLedgerStatus.executionState,\n previousAgentControllerConversationId:\n localLedgerStatus.previousAgentControllerConversationId ?? null,\n }),\n },\n providerConversationProof,\n runtimeWorkspace: normalizeRuntimeWorkspace(workspaceResolution),\n };\n}\n\nfunction resolveControllerLaunchStatus(\n localController: Awaited<\n ReturnType<typeof readLocalEnabledControllers>\n > extends Map<string, infer T>\n ? T | null\n : never\n): OpenMeldDaemonConversationExecutionStatusPayload[\"controllerLaunchStatus\"] {\n if (!localController) {\n return \"missing\";\n }\n if (localController.enabled !== true) {\n return \"disabled\";\n }\n if (!localController.launchContract) {\n return \"repair_required\";\n }\n return \"ready\";\n}\n\nfunction resolveLocalRuntimeContextStatus(input: {\n agentControllerConversationId: string | null;\n executionState: ConversationExecutionState | null;\n previousAgentControllerConversationId: string | null;\n}): OpenMeldDaemonConversationExecutionStatusPayload[\"localRuntimeContext\"][\"status\"] {\n if (!(input.executionState && input.previousAgentControllerConversationId)) {\n return \"missing\";\n }\n if (\n input.agentControllerConversationId &&\n input.previousAgentControllerConversationId !==\n input.agentControllerConversationId\n ) {\n return \"mismatch\";\n }\n return \"ready\";\n}\n\nfunction normalizeRuntimeWorkspace(\n input: Awaited<ReturnType<typeof resolveProfileWorkspaceRuntime>>\n): OpenMeldDaemonConversationExecutionStatusPayload[\"runtimeWorkspace\"] {\n switch (input.status) {\n case \"ready\":\n return {\n configPath: input.configPath,\n configuredWorkspacePath: input.configuredWorkspacePath,\n fingerprint: buildRuntimeWorkspaceFingerprint(\n input.effectiveRuntimeWorkingDirectory\n ),\n path: input.effectiveRuntimeWorkingDirectory,\n reasonCode: null,\n reasonText: null,\n runtimeContext: input.runtimeContext,\n status: \"ready\",\n workspaceMode: input.workspaceMode,\n };\n case \"missing\":\n return {\n configPath: input.configPath,\n configuredWorkspacePath: null,\n fingerprint: null,\n path: null,\n reasonCode: input.reasonCode,\n reasonText: input.reasonText,\n runtimeContext: null,\n status: \"missing\",\n workspaceMode: null,\n };\n case \"invalid\":\n return {\n configPath: input.configPath,\n configuredWorkspacePath: input.configuredWorkspacePath ?? null,\n fingerprint: null,\n path: null,\n reasonCode: input.reasonCode,\n reasonText: input.reasonText,\n runtimeContext: null,\n status: \"invalid\",\n workspaceMode: input.workspaceMode ?? null,\n };\n default:\n throw new Error(\"unsupported profile workspace runtime status\");\n }\n}\n\nfunction buildProviderConversationProofNotRun(\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"]\n): OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"] {\n return {\n agentControllerConversationId: null,\n checkedAt: null,\n errorCode: null,\n errorMessage: null,\n errorType: null,\n expiresAt: null,\n intrusive: false,\n method: null,\n provider: null,\n status: \"not_run\",\n transportMode,\n };\n}\n\nexport async function resolveLocalProviderConversationProof(input: {\n agentControllerConversationId: string | null;\n boundAgentControllerRef: string | null;\n launchContract: RuntimeAgentControllerLaunchContract | null;\n profileAgentControllerRef: string;\n runtimeWorkingDirectory: string | null;\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n}): Promise<\n OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"]\n> {\n const checkedAt = new Date().toISOString();\n const providerId = normalizeKnownBuiltinAgentControllerId(\n input.profileAgentControllerRef\n );\n const provider = resolveProviderConversationProofProvider(providerId);\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n const base = {\n agentControllerConversationId,\n checkedAt,\n errorCode: null,\n errorMessage: null,\n errorType: null,\n expiresAt: null,\n intrusive: false,\n method: resolveProviderConversationProofMethod({\n provider,\n transportMode: input.transportMode,\n }),\n provider,\n transportMode: input.transportMode,\n } satisfies Omit<\n OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"],\n \"status\"\n >;\n\n if (!agentControllerConversationId) {\n return {\n ...base,\n status: \"not_applicable\",\n };\n }\n\n if (!(provider === \"codex\" && input.transportMode === \"codex-app-server\")) {\n return {\n ...base,\n status: \"not_applicable\",\n };\n }\n\n if (!input.launchContract) {\n return {\n ...base,\n errorCode: \"controller.launch.needs_repair\",\n errorMessage:\n \"The current agent profile controller does not have an available local launch contract on this device.\",\n errorType: \"config\",\n status: \"failed\",\n };\n }\n\n if (!input.runtimeWorkingDirectory) {\n return {\n ...base,\n errorCode: \"workspace.missing\",\n errorMessage:\n \"The current agent profile workspace is unavailable for dispatch on this device.\",\n errorType: \"config\",\n status: \"failed\",\n };\n }\n\n if (\n input.boundAgentControllerRef &&\n input.boundAgentControllerRef !== input.profileAgentControllerRef\n ) {\n return {\n ...base,\n errorCode: \"controller_ref_mismatch\",\n errorMessage:\n \"The bound agent controller conversation controller does not match the current agent profile controller.\",\n errorType: \"config\",\n status: \"failed\",\n };\n }\n\n const agentControllerConversationKind = providerId\n ? resolveBuiltinAgentControllerConversationKind(\n input.profileAgentControllerRef\n )\n : null;\n if (!agentControllerConversationKind) {\n return {\n ...base,\n errorCode: \"provider_unsupported\",\n errorMessage: `Provider conversation proof is not available for ${input.profileAgentControllerRef}.`,\n errorType: \"config\",\n status: \"failed\",\n };\n }\n const agentControllerConversation = buildAgentControllerConversationRef({\n agentControllerRef: input.profileAgentControllerRef,\n agentControllerConversationId,\n agentControllerConversationKind,\n });\n\n try {\n await verifyCodexAppServerThread({\n codexTimeoutMs: resolveProviderConversationProofTimeoutMs(\n resolveCodexTimeoutMs()\n ),\n codexWorkdir: input.runtimeWorkingDirectory,\n launchContract: input.launchContract,\n threadId: agentControllerConversation.agentControllerConversationId,\n });\n\n return {\n ...base,\n expiresAt: new Date(\n Date.parse(checkedAt) + PROVIDER_CONVERSATION_PROOF_TTL_MS\n ).toISOString(),\n status: \"passed\",\n };\n } catch (error) {\n return {\n ...base,\n errorCode: readErrorCode(error),\n errorMessage: readErrorMessage(error),\n errorType: readErrorType(error),\n status: \"failed\",\n };\n }\n}\n\nfunction resolveProviderConversationProofProvider(\n value: string | null\n): OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"][\"provider\"] {\n if (value === \"codex\" || value === \"claude-code\" || value === \"openclaw\") {\n return value;\n }\n return null;\n}\n\nfunction resolveProviderConversationProofMethod(input: {\n provider: OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"][\"provider\"];\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n}): OpenMeldDaemonConversationExecutionStatusPayload[\"providerConversationProof\"][\"method\"] {\n if (\n input.provider === \"codex\" &&\n input.transportMode === \"codex-app-server\"\n ) {\n return \"codex_app_server_thread_resume\";\n }\n return null;\n}\n\nasync function resolveLocalLedgerConversationExecution(input: {\n agentControllerRef: string;\n spaceId: string;\n targetProfileId: string;\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n workspaceResolution: Awaited<\n ReturnType<typeof resolveProfileWorkspaceRuntime>\n >;\n}): Promise<{\n agentContextLookupKey: string;\n executionState: ConversationExecutionState | null;\n previousAgentControllerConversationId: string | null;\n runtimeWorkspaceFingerprint: string | null;\n}> {\n const io = createLedgerIo();\n const runtimePaths = await ensureDaemonRuntimePaths();\n const ledgerState = await loadLedgerState({\n invalidStateStrategy: \"backup_and_reset\",\n io,\n paths: buildLedgerPaths(runtimePaths.ledgerRootPath),\n });\n\n if (input.workspaceResolution.status !== \"ready\") {\n return {\n agentContextLookupKey: buildUnresolvedRuntimeWorkspaceLookupKey({\n agentControllerRef: input.agentControllerRef,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n transportMode: input.transportMode,\n }),\n executionState: null,\n previousAgentControllerConversationId: null,\n runtimeWorkspaceFingerprint: null,\n };\n }\n\n const runtimeWorkspaceFingerprint = buildRuntimeWorkspaceFingerprint(\n input.workspaceResolution.effectiveRuntimeWorkingDirectory\n );\n const keyInput = {\n agentControllerRef: input.agentControllerRef,\n runtimeWorkspaceFingerprint,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n transportMode: input.transportMode,\n } as const;\n const agentContextLookupKey = buildAgentContextLookupKey(keyInput);\n const previousAgentContextMatch = resolveCompatibleAgentContextMatch({\n key: keyInput,\n state: ledgerState,\n });\n const executionState = resolveCompatibleConversationExecutionState({\n key: keyInput,\n preferredLookupKey:\n previousAgentContextMatch?.agentContextLookupKey ?? null,\n state: ledgerState,\n });\n\n return {\n agentContextLookupKey,\n executionState,\n previousAgentControllerConversationId:\n previousAgentContextMatch?.agentContext.agentControllerConversationId ??\n null,\n runtimeWorkspaceFingerprint,\n };\n}\n\nfunction buildUnresolvedRuntimeWorkspaceLookupKey(input: {\n agentControllerRef: string;\n spaceId: string;\n targetProfileId: string;\n transportMode: OpenMeldDaemonConversationExecutionStatusRequestPayload[\"transportMode\"];\n}): string {\n return [\n input.spaceId,\n input.targetProfileId,\n encodeURIComponent(input.agentControllerRef),\n input.transportMode,\n \"runtime-workspace-unresolved\",\n ].join(\"|\");\n}\n\nfunction readErrorCode(error: unknown): string | null {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof error.code === \"string\"\n ) {\n return error.code;\n }\n return null;\n}\n\nfunction readErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\nfunction readErrorType(error: unknown): string | null {\n if (\n typeof error === \"object\" &&\n error !== null &&\n \"errorType\" in error &&\n typeof error.errorType === \"string\"\n ) {\n return error.errorType;\n }\n return null;\n}\n\nconst PROVIDER_CONVERSATION_PROOF_TIMEOUT_MS = 30_000;\nconst PROVIDER_CONVERSATION_PROOF_TTL_MS = 10 * 60_000;\n\nfunction resolveProviderConversationProofTimeoutMs(\n runtimeTimeoutMs: number | null\n) {\n if (runtimeTimeoutMs === null) {\n return PROVIDER_CONVERSATION_PROOF_TIMEOUT_MS;\n }\n return Math.min(runtimeTimeoutMs, PROVIDER_CONVERSATION_PROOF_TIMEOUT_MS);\n}\n","import type {\n OpenMeldDaemonProviderConversationProof,\n RuntimeAgentControllerLaunchContract,\n} from \"@openmeld/schemas/types\";\nimport { resolveLocalProviderConversationProof } from \"../control-plane/conversation-execution-status\";\nimport type { RouteCatalog } from \"../core/types\";\nimport {\n notifyRuntimeReportingAttemptObserver,\n type RuntimeProviderConversationProofInput,\n type RuntimeProviderConversationProofSubmission,\n type RuntimeReportingAttemptObserver,\n submitRuntimeProviderConversationProofs,\n} from \"./runtime-agent-controller-reporting-submission\";\n\nconst PROVIDER_CONVERSATION_PROOF_FALLBACK_TTL_MS = 10 * 60_000;\n\nexport type LocalServiceProviderConversationProofSyncResult =\n | {\n status: \"skipped\";\n reasonCodes: readonly string[];\n proofCount: 0;\n submittedCount: 0;\n failedCount: 0;\n }\n | {\n status: \"submitted\";\n reasonCodes: readonly string[];\n proofCount: number;\n submittedCount: number;\n failedCount: number;\n };\n\nexport async function syncLocalServiceProviderConversationProofs(input: {\n onAttempt?: RuntimeReportingAttemptObserver;\n routeCatalog: RouteCatalog;\n}): Promise<LocalServiceProviderConversationProofSyncResult> {\n let proofInputs: RuntimeProviderConversationProofInput[];\n try {\n proofInputs = (\n await Promise.all(\n [...input.routeCatalog.routeByProfileId.values()].map(async (route) => {\n if (!isCodexAppServerRouteWithConversation(route)) {\n return null;\n }\n const workspace = route.workingFolderRuntime;\n if (!workspace) {\n return null;\n }\n const proof = await resolveLocalProviderConversationProof({\n agentControllerConversationId: route.agentControllerConversationId,\n boundAgentControllerRef: route.agentControllerRef,\n launchContract: route.launchContract ?? null,\n profileAgentControllerRef: route.agentControllerRef,\n runtimeWorkingDirectory: workspace.effectiveRuntimeWorkingDirectory,\n transportMode: route.transportMode,\n });\n return toRuntimeProviderConversationProofInput({\n agentControllerConversationId: route.agentControllerConversationId,\n agentControllerRef: route.agentControllerRef,\n bindingId: route.bindingId,\n profileId: route.profileId,\n proof,\n });\n })\n )\n ).filter(\n (proof): proof is RuntimeProviderConversationProofInput => proof !== null\n );\n } catch (error) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"provider_conversation_proof\",\n message: \"Provider conversation proof collection failed.\",\n reasonCode: \"provider_conversation.runtime_reporting.collection_failed\",\n status: \"failed\",\n });\n throw error;\n }\n\n if (proofInputs.length === 0) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"provider_conversation_proof\",\n message: null,\n reasonCode: \"provider_conversation.proof.no_applicable_routes\",\n status: \"not_applicable\",\n });\n return {\n status: \"skipped\",\n reasonCodes: [\"provider_conversation.proof.no_applicable_routes\"],\n proofCount: 0,\n submittedCount: 0,\n failedCount: 0,\n };\n }\n\n const submissions = await submitRuntimeProviderConversationProofs({\n ...(input.onAttempt ? { onAttempt: input.onAttempt } : {}),\n proofs: proofInputs,\n });\n return summarizeSubmissions(submissions);\n}\n\nfunction isCodexAppServerRouteWithConversation(route: {\n agentControllerConversationId?: string | null;\n agentControllerRef: string;\n bindingId?: string;\n launchContract?: RuntimeAgentControllerLaunchContract | null;\n transportMode: string;\n}): route is typeof route & {\n agentControllerConversationId: string;\n bindingId: string;\n launchContract: RuntimeAgentControllerLaunchContract;\n transportMode: \"codex-app-server\";\n} {\n return (\n route.agentControllerRef === \"builtin:codex\" &&\n route.transportMode === \"codex-app-server\" &&\n Boolean(route.agentControllerConversationId?.trim()) &&\n Boolean(route.bindingId?.trim()) &&\n Boolean(route.launchContract)\n );\n}\n\nfunction toRuntimeProviderConversationProofInput(input: {\n agentControllerConversationId: string;\n agentControllerRef: string;\n bindingId: string;\n profileId: string;\n proof: OpenMeldDaemonProviderConversationProof;\n}): RuntimeProviderConversationProofInput | null {\n if (!(input.proof.status === \"passed\" || input.proof.status === \"failed\")) {\n return null;\n }\n if (\n !(\n input.proof.provider === \"codex\" &&\n input.proof.method === \"codex_app_server_thread_resume\" &&\n input.proof.transportMode === \"codex-app-server\" &&\n input.proof.intrusive === false\n )\n ) {\n return null;\n }\n\n const observedAtMs = Date.parse(input.proof.checkedAt ?? \"\");\n if (!(Number.isFinite(observedAtMs) && observedAtMs > 0)) {\n return null;\n }\n const parsedExpiresAtMs = Date.parse(input.proof.expiresAt ?? \"\");\n const expiresAtMs =\n Number.isFinite(parsedExpiresAtMs) && parsedExpiresAtMs > observedAtMs\n ? parsedExpiresAtMs\n : observedAtMs + PROVIDER_CONVERSATION_PROOF_FALLBACK_TTL_MS;\n\n return {\n agentProfileId: input.profileId,\n bindingId: input.bindingId,\n agentControllerRef: input.agentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n transportMode: \"codex-app-server\",\n provider: \"codex\",\n method: \"codex_app_server_thread_resume\",\n intrusive: false,\n observedAtMs,\n expiresAtMs,\n status: input.proof.status,\n ...(input.proof.errorCode ? { errorCode: input.proof.errorCode } : {}),\n ...(input.proof.errorMessage\n ? { errorMessage: input.proof.errorMessage }\n : {}),\n ...(input.proof.errorType ? { errorType: input.proof.errorType } : {}),\n };\n}\n\nfunction summarizeSubmissions(\n submissions: readonly RuntimeProviderConversationProofSubmission[]\n): LocalServiceProviderConversationProofSyncResult {\n const submittedCount = submissions.filter(\n (submission) =>\n submission.status === \"submitted\" &&\n submission.providerConversationProofStatus === \"accepted\"\n ).length;\n const failedCount = submissions.length - submittedCount;\n return {\n status: \"submitted\",\n reasonCodes: [\n ...new Set(\n submissions\n .flatMap((submission) => submission.reasonCodes)\n .filter((reasonCode) => reasonCode.trim())\n ),\n ],\n proofCount: submissions.length,\n submittedCount,\n failedCount,\n };\n}\n","import type { LocalDaemonAdapterContainer } from \"@openmeld/local-service\";\nimport { reconcileNewRunnableBuiltinAgentRegistrations } from \"../../agents/registry\";\nimport type { AgentControllerInterfaceProbePolicy } from \"../inventory/agent-controller-interface\";\nimport {\n collectLocalAgentControllerInventory,\n resolveLocalAgentControllerReportDecision,\n} from \"../inventory/agent-controller-inventory\";\nimport {\n notifyRuntimeReportingAttemptObserver,\n type RuntimeAgentControllerReportSubmission,\n type RuntimeReportingAttemptObserver,\n submitRuntimeAgentControllerReports,\n} from \"./runtime-agent-controller-reporting-submission\";\n\nexport type LocalServiceRuntimeAgentControllerReportSyncResult =\n | {\n status: \"skipped\";\n reasonCodes: readonly string[];\n reportCount: 0;\n submittedCount: 0;\n failedCount: 0;\n }\n | {\n status: \"submitted\";\n reasonCodes: readonly string[];\n reportCount: number;\n submittedCount: number;\n failedCount: number;\n };\n\nexport async function syncLocalServiceRuntimeAgentControllerReports(input: {\n localAdapterContainer: LocalDaemonAdapterContainer;\n onAttempt?: RuntimeReportingAttemptObserver;\n probePolicy?: AgentControllerInterfaceProbePolicy;\n}): Promise<LocalServiceRuntimeAgentControllerReportSyncResult> {\n // OPENMELD_SERVICE_THIN_CORE: runtime Agent Controller report evidence.\n // This reports detected local controller capabilities for the current\n // service identity. It must remain evidence, not Binding truth or final Ready.\n let inventory: Awaited<\n ReturnType<typeof collectLocalAgentControllerInventory>\n >;\n try {\n // Discovery belongs to the existing background inventory pass, not route\n // registration. Slow unrelated install probes must not strand new Wakes.\n // Newly registered controllers notify the carrier through the normal\n // lane-local catalog-change signal; explicit disabled choices stay intact.\n await reconcileNewRunnableBuiltinAgentRegistrations();\n inventory = await collectLocalAgentControllerInventory({\n includeControllerInterface: true,\n localAdapterContainer: input.localAdapterContainer,\n probePolicy: input.probePolicy,\n });\n } catch (error) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"runtime_agent_controller\",\n message: \"Local agent inventory collection failed.\",\n reasonCode: \"runtime.reporting.inventory_failed\",\n status: \"failed\",\n });\n throw error;\n }\n const reports = inventory.capabilities\n .filter((capability) => capability.registered)\n .map((capability) => {\n if (!capability.agentControllerRef) {\n return null;\n }\n const reportDecision = resolveLocalAgentControllerReportDecision(\n capability,\n { requireEnabled: true }\n );\n return {\n agentControllerRef: capability.agentControllerRef,\n ...(capability.agentControllerInterface\n ? { agentControllerInterface: capability.agentControllerInterface }\n : {}),\n enabled: capability.enabled,\n localParticipationState: reportDecision.localParticipationState,\n reasonCodes: reportDecision.reasonCodes,\n };\n })\n .filter((report): report is NonNullable<typeof report> => report !== null);\n\n if (reports.length === 0) {\n await notifyRuntimeReportingAttemptObserver(input.onAttempt, {\n authenticationRejected: false,\n family: \"runtime_agent_controller\",\n message: \"No local controllers are installed on this computer.\",\n reasonCode: \"runtime.agent_controller_report.no_local_controllers\",\n status: \"not_applicable\",\n });\n return {\n status: \"skipped\",\n reasonCodes: [\"runtime.agent_controller_report.no_local_controllers\"],\n reportCount: 0,\n submittedCount: 0,\n failedCount: 0,\n };\n }\n\n const submissions = await submitRuntimeAgentControllerReports({\n ...(input.onAttempt ? { onAttempt: input.onAttempt } : {}),\n reports,\n });\n return summarizeSubmissions(submissions);\n}\n\nfunction summarizeSubmissions(\n submissions: readonly RuntimeAgentControllerReportSubmission[]\n): LocalServiceRuntimeAgentControllerReportSyncResult {\n const submittedCount = submissions.filter(\n (submission) =>\n submission.status === \"submitted\" &&\n submission.agentControllerReportStatus === \"accepted\"\n ).length;\n const failedCount = submissions.length - submittedCount;\n return {\n status: \"submitted\",\n reasonCodes: [\n ...new Set(\n submissions\n .flatMap((submission) => submission.reasonCodes)\n .filter((reasonCode) => reasonCode.trim())\n ),\n ],\n reportCount: submissions.length,\n submittedCount,\n failedCount,\n };\n}\n","import type { RuntimeReportingServiceIdentity } from \"@openmeld/schemas/types\";\nimport { toErrorMessage, warnDaemonEvent } from \"../core/logger\";\nimport {\n recordRuntimeReportingFailure,\n recordRuntimeReportingNotApplicable,\n recordRuntimeReportingSuccess,\n} from \"../state/runtime-reporting-health-state\";\nimport type {\n RuntimeReportingAttempt,\n RuntimeReportingAttemptObserver,\n} from \"./runtime-agent-controller-reporting-submission\";\nimport type { RuntimeReportingAuthenticationFailure } from \"./runtime-reporting-auth-recovery\";\n\nexport function createRuntimeReportingAttemptObserver(input: {\n serviceIdentity: RuntimeReportingServiceIdentity;\n onAuthenticationFailure?: (\n failure: RuntimeReportingAuthenticationFailure\n ) => Promise<void> | void;\n}): RuntimeReportingAttemptObserver {\n return async (attempt) => {\n await persistRuntimeReportingAttempt(attempt, input.serviceIdentity);\n if (\n attempt.status === \"failed\" &&\n attempt.authenticationRejected &&\n attempt.reasonCode &&\n attempt.message\n ) {\n await input.onAuthenticationFailure?.({\n ...(attempt.credentialFingerprint\n ? { credentialFingerprint: attempt.credentialFingerprint }\n : {}),\n message: attempt.message,\n reasonCode: attempt.reasonCode,\n });\n }\n };\n}\n\nasync function persistRuntimeReportingAttempt(\n attempt: RuntimeReportingAttempt,\n serviceIdentity: RuntimeReportingServiceIdentity\n): Promise<void> {\n const channel =\n attempt.family === \"runtime_agent_controller\"\n ? \"runtimeAgentController\"\n : \"providerConversationProof\";\n try {\n if (attempt.status === \"succeeded\") {\n await recordRuntimeReportingSuccess({ channel, serviceIdentity });\n return;\n }\n if (attempt.status === \"not_applicable\") {\n await recordRuntimeReportingNotApplicable({ channel, serviceIdentity });\n return;\n }\n await recordRuntimeReportingFailure({\n channel,\n message: attempt.message ?? \"Runtime reporting failed.\",\n reasonCode: attempt.reasonCode ?? \"runtime.reporting.failed\",\n serviceIdentity,\n });\n } catch (error) {\n warnDaemonEvent(\"[openmeld.runtime_reporting.health_write_failed]\", {\n error: toErrorMessage(error),\n event: \"cli.runtime_reporting.health_write_failed\",\n family: attempt.family,\n reasonCode: attempt.reasonCode,\n status: attempt.status,\n });\n }\n}\n","import type {\n InflightTaskControlRegistry,\n LocalDaemonAdapterContainer,\n} from \"@openmeld/local-service\";\nimport type { AgentControllerPermissionMode } from \"@openmeld/schemas/types\";\nimport type { MutableRouteCatalogState } from \"../core/types\";\n\nexport type ActivePermissionModeSyncOutcome = {\n adapterId: string;\n agentControllerPermissionMode: AgentControllerPermissionMode;\n errorMessage?: string;\n reasonCode?:\n | \"adapter.permission_mode_incompatible\"\n | \"adapter.permission_mode_update_unsupported\"\n | \"adapter.task_not_active\";\n status: \"applied\" | \"failed\" | \"not_applied\";\n targetProfileId: string;\n taskId: string;\n};\n\nexport async function syncActiveTaskPermissionModes(input: {\n catalogState: MutableRouteCatalogState;\n inflightTaskControlRegistry: InflightTaskControlRegistry;\n localAdapterContainer: LocalDaemonAdapterContainer;\n}): Promise<ActivePermissionModeSyncOutcome[]> {\n const outcomes: ActivePermissionModeSyncOutcome[] = [];\n\n for (const task of input.inflightTaskControlRegistry.listTasks()) {\n if (!task.targetProfileId) {\n continue;\n }\n const route = input.catalogState.routeByProfileId.get(task.targetProfileId);\n const nextPermissionMode = route?.agentControllerPermissionMode;\n if (\n !nextPermissionMode ||\n nextPermissionMode === task.agentControllerPermissionMode\n ) {\n continue;\n }\n\n const adapterEntry = input.localAdapterContainer.getAdapter(task.adapterId);\n const updatePermissionMode = adapterEntry?.adapter.updatePermissionMode;\n if (!updatePermissionMode) {\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n reasonCode: \"adapter.permission_mode_update_unsupported\",\n status: \"not_applied\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n continue;\n }\n\n try {\n const result = await updatePermissionMode({\n agentControllerPermissionMode: nextPermissionMode,\n taskId: task.taskId,\n });\n if (result.status === \"not_applied\") {\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n reasonCode: result.reasonCode,\n status: \"not_applied\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n continue;\n }\n\n input.inflightTaskControlRegistry.updateTaskPermissionMode({\n agentControllerPermissionMode: nextPermissionMode,\n taskId: task.taskId,\n });\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n status: \"applied\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n } catch (error) {\n outcomes.push({\n adapterId: task.adapterId,\n agentControllerPermissionMode: nextPermissionMode,\n errorMessage: error instanceof Error ? error.message : String(error),\n status: \"failed\",\n targetProfileId: task.targetProfileId,\n taskId: task.taskId,\n });\n }\n }\n\n return outcomes;\n}\n","import { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirnamePath, normalizeOptionalText } from \"../core/logger\";\n\nexport async function loadContextStore(\n contextStorePath: string\n): Promise<Map<string, string>> {\n const raw = await readFile(contextStorePath, \"utf8\").catch(() => \"\");\n if (!raw) {\n return new Map();\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return new Map();\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return new Map();\n }\n const contextStore = new Map<string, string>();\n for (const [key, value] of Object.entries(parsed)) {\n const normalizedKey = normalizeOptionalText(key);\n const normalizedValue = normalizeOptionalText(value);\n if (!(normalizedKey && normalizedValue)) {\n continue;\n }\n contextStore.set(normalizedKey, normalizedValue);\n }\n return contextStore;\n}\n\nexport async function persistContextStore(input: {\n contextStore: Map<string, string>;\n contextStorePath: string;\n}): Promise<void> {\n const payload = Object.fromEntries(input.contextStore.entries());\n const tempPath = `${input.contextStorePath}.tmp-${Date.now()}-${process.pid}`;\n await mkdir(dirnamePath(input.contextStorePath), {\n recursive: true,\n });\n await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, input.contextStorePath).catch(async (error) => {\n await rm(tempPath, {\n force: true,\n }).catch(() => undefined);\n throw error;\n });\n}\n","import type { LocalDaemonAdapterContainer } from \"@openmeld/local-service\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type { RouteCatalog } from \"../core/types\";\nimport { emitDaemonLifecycleEvent } from \"../lifecycle/daemon-lifecycle-journal\";\nimport {\n loadDaemonRouteCatalog,\n type RouteCatalogLoadPhaseTimings,\n} from \"../routing/route-catalog\";\nimport {\n readDaemonRouteCatalogCache,\n writeDaemonRouteCatalogCache,\n} from \"../state/route-catalog-cache\";\n\ntype CatalogOwner = {\n lane: string;\n localAdapterContainer: LocalDaemonAdapterContainer;\n ownerUserId: string;\n presenter: Presenter;\n serviceBundleId: string | null;\n};\n\nexport async function loadExecutionHostCatalog(\n owner: CatalogOwner,\n initial: boolean\n): Promise<RouteCatalog> {\n if (!initial) {\n return await loadDaemonRouteCatalog({\n localAdapterContainer: owner.localAdapterContainer,\n ownerUserId: owner.ownerUserId,\n presenter: owner.presenter,\n allowEmpty: true,\n localReplyStateMode: \"check\",\n quiet: true,\n });\n }\n const startedAt = Date.now();\n const phaseTimings: RouteCatalogLoadPhaseTimings = {};\n await recordInitialLoad(\"started\", {});\n try {\n const catalog = await loadDaemonRouteCatalog({\n allowEmpty: true,\n localAdapterContainer: owner.localAdapterContainer,\n localReplyStateMode: \"check\",\n ownerUserId: owner.ownerUserId,\n phaseTimings,\n presenter: owner.presenter,\n });\n await recordInitialLoad(\"completed\", {\n durationMs: Date.now() - startedAt,\n phaseTimings,\n profileCount: catalog.profileIds.length,\n skippedProfileCount: catalog.skippedProfiles.length,\n });\n return catalog;\n } catch (error) {\n const cached = await readDaemonRouteCatalogCache({\n lane: owner.lane,\n ownerUserId: owner.ownerUserId,\n serviceBundleId: owner.serviceBundleId,\n });\n emitRunLine({\n presenter: owner.presenter,\n code: cached\n ? \"daemon.run.route_catalog_cache_recovered\"\n : \"daemon.run.route_catalog_initial_load_failed\",\n text: cached\n ? `using last known route catalog after initial catalog load failed: ${toErrorMessage(error)}`\n : `initial route catalog load failed; starting with an empty catalog and retrying via catalog sync: ${toErrorMessage(error)}`,\n payload: {\n reason: cached ? \"initial_load_failed\" : \"initial_load_failed_no_cache\",\n },\n });\n await recordInitialLoad(cached ? \"cache_recovered\" : \"failed_empty_start\", {\n durationMs: Date.now() - startedAt,\n errorMessage: toErrorMessage(error),\n phaseTimings,\n ...(cached ? { profileCount: cached.profileIds.length } : {}),\n });\n return (\n cached ?? {\n profileIds: [],\n routeByProfileId: new Map(),\n skippedProfiles: [],\n }\n );\n }\n}\n\nexport async function persistExecutionHostCatalog(\n owner: CatalogOwner,\n routeCatalog: RouteCatalog\n): Promise<void> {\n try {\n await writeDaemonRouteCatalogCache({\n lane: owner.lane,\n ownerUserId: owner.ownerUserId,\n serviceBundleId: owner.serviceBundleId,\n routeCatalog,\n });\n } catch (error) {\n emitRunLine({\n presenter: owner.presenter,\n code: \"daemon.run.route_catalog_cache_write_failed\",\n text: `route catalog cache write failed: ${toErrorMessage(error)}`,\n });\n }\n}\n\nasync function recordInitialLoad(\n result: string,\n metadata: Record<string, unknown>\n): Promise<void> {\n // Match the existing diagnostic contract: journaling never owns startup.\n await emitDaemonLifecycleEvent({\n type: \"route_catalog.initial_load\",\n result,\n metadata,\n }).catch(() => undefined);\n}\n","import type { AdapterComputerFileAccessBoundary } from \"@openmeld/adapter-core\";\nimport type { LocalDaemonAdapterContainer } from \"@openmeld/local-service\";\nimport {\n buildAgentControllerConversationRef,\n resolveBuiltinAgentControllerConversationKind,\n} from \"@openmeld/schemas\";\nimport type {\n RuntimeTransportResumeControllerConversationFramePayload,\n RuntimeTransportResumeControllerConversationResult,\n} from \"@openmeld/schemas/types\";\nimport type { DaemonProfileRouteConfig } from \"../core/types\";\nimport { assertComputerFileAccessWorkingDirectoryAllowed } from \"../file-access/computer-file-access-admission\";\nimport { COMPUTER_FILE_ACCESS_AWARENESS } from \"../file-access/computer-file-access-prompt\";\nimport { readComputerFileAccessPolicy } from \"../file-access/computer-file-access-store\";\nimport { resolveLocalRuntimeControllerSupport } from \"../routing/resolve-controller-support\";\n\ntype RecoveryRouteConfig = Pick<\n DaemonProfileRouteConfig,\n | \"agentControllerPermissionMode\"\n | \"agentControllerRef\"\n | \"launchContract\"\n | \"profileId\"\n | \"transportMode\"\n>;\n\nconst RECOVERY_PROMPT = [\n \"OpenMeld execution recovery.\",\n \"Continue this exact controller conversation.\",\n \"Do not redo the task, call tools, edit files, or perform external actions.\",\n \"Return the best faithful final answer you can recover from this conversation.\",\n \"Your answer is content only. OpenMeld decides recovery status from the typed provider outcome, never from words in your answer.\",\n].join(\" \");\n\nexport async function resumeExactControllerConversation(input: {\n computerFileAccessStorePath: string;\n localAdapterContainer: LocalDaemonAdapterContainer;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n routeConfig?: RecoveryRouteConfig | null;\n}): Promise<RuntimeTransportResumeControllerConversationResult> {\n const identity = input.request.identity;\n const controllerRef = identity.agentControllerRef;\n const conversationId = identity.agentControllerConversationId;\n if (!(controllerRef && conversationId)) {\n return rejected(input.request, \"execution_recovery.identity_incomplete\");\n }\n const support = resolveLocalRuntimeControllerSupport({\n agentControllerRef: controllerRef,\n localAdapterContainer: input.localAdapterContainer,\n });\n if (!support.supported) {\n return rejected(input.request, support.reasonCode, support.reasonDetail);\n }\n if (\n !support.localAdapterEntry.transportModes.includes(\n input.request.transportMode\n )\n ) {\n return rejected(\n input.request,\n \"execution_recovery.transport_mode_unsupported\"\n );\n }\n const conversationKind =\n resolveBuiltinAgentControllerConversationKind(controllerRef);\n if (!conversationKind) {\n return rejected(\n input.request,\n \"execution_recovery.controller_conversation_kind_unsupported\"\n );\n }\n const exactConversation = buildAgentControllerConversationRef({\n agentControllerConversationId: conversationId,\n agentControllerConversationKind: conversationKind,\n agentControllerRef: controllerRef,\n });\n const fileAccess = await resolveRecoveryComputerFileAccess({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n request: input.request,\n routeConfig: input.routeConfig ?? null,\n support,\n });\n if (fileAccess.status === \"rejected\") {\n return fileAccess.result;\n }\n const computerFileAccessBoundary = fileAccess.boundary;\n const result = await support.localAdapterEntry.adapter.dispatch({\n agentControllerConversation: exactConversation,\n agentControllerConversationId: conversationId,\n agentId: identity.targetProfileId,\n dispatchId: identity.dispatchId,\n executionMode: \"repair\",\n ...(computerFileAccessBoundary ? { computerFileAccessBoundary } : {}),\n prompt: computerFileAccessBoundary\n ? `${COMPUTER_FILE_ACCESS_AWARENESS} ${RECOVERY_PROMPT}`\n : RECOVERY_PROMPT,\n runtimeContext: {\n providerRuntimeWorkingDirectory:\n input.request.providerRuntimeWorkingDirectory,\n },\n sourceEventId: input.request.sourceEventId,\n spaceId: identity.spaceId,\n streamingMode: \"final\",\n taskId:\n identity.taskId ?? `execution-recovery:${input.request.operationId}`,\n transportMode: input.request.transportMode,\n });\n if (result.status !== \"success\") {\n return {\n destination: input.request.destination,\n identity,\n message: result.errorMessage,\n operationId: input.request.operationId,\n reasonCode:\n result.errorCode ?? \"execution_recovery.controller_resume_failed\",\n status: \"outcome_unknown\",\n };\n }\n const observedConversationId =\n result.contextDelta?.agentControllerConversationId ?? conversationId;\n if (observedConversationId !== conversationId) {\n return {\n destination: input.request.destination,\n identity,\n message:\n \"The controller returned a different conversation during recovery.\",\n operationId: input.request.operationId,\n reasonCode: \"execution_recovery.controller_conversation_mismatch\",\n status: \"outcome_unknown\",\n };\n }\n const output = result.output.trim();\n if (!output) {\n return {\n destination: input.request.destination,\n identity,\n message: \"The exact conversation did not contain a completed result.\",\n operationId: input.request.operationId,\n reasonCode: \"execution_recovery.completed_result_unavailable\",\n status: \"outcome_unknown\",\n };\n }\n return {\n agentControllerConversationId: conversationId,\n destination: input.request.destination,\n identity,\n operationId: input.request.operationId,\n output,\n status: \"completed\",\n };\n}\n\nasync function resolveRecoveryComputerFileAccess(input: {\n computerFileAccessStorePath: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n routeConfig: RecoveryRouteConfig | null;\n support: Extract<\n ReturnType<typeof resolveLocalRuntimeControllerSupport>,\n { supported: true }\n >;\n}): Promise<\n | {\n boundary: AdapterComputerFileAccessBoundary | null;\n status: \"ready\";\n }\n | {\n result: RuntimeTransportResumeControllerConversationResult;\n status: \"rejected\";\n }\n> {\n const policy = await readComputerFileAccessPolicy(\n input.computerFileAccessStorePath\n );\n if (policy.mode === \"local_agent_settings\") {\n return { boundary: null, status: \"ready\" };\n }\n if (\n input.support.localAdapterEntry.adapterId !== \"codex\" ||\n (input.request.transportMode !== \"codex-app-server\" &&\n input.request.transportMode !== \"local-cli\")\n ) {\n return {\n result: rejected(\n input.request,\n \"execution_recovery.computer_file_access_unverified\",\n \"OpenMeld could not verify this Computer’s file access boundary for execution recovery.\"\n ),\n status: \"rejected\",\n };\n }\n try {\n await assertComputerFileAccessWorkingDirectoryAllowed({\n boundary: policy,\n providerRuntimeWorkingDirectory:\n input.request.providerRuntimeWorkingDirectory,\n });\n } catch {\n return {\n result: rejected(\n input.request,\n \"computer.file_access.working_directory_denied\",\n \"This recovery working folder is outside the Computer file access boundary.\"\n ),\n status: \"rejected\",\n };\n }\n\n const routeConfig = input.routeConfig;\n const verifyBoundary =\n input.support.localAdapterEntry.adapter.verifyComputerFileAccessBoundary;\n if (\n !(verifyBoundary && routeConfig) ||\n routeConfig.profileId !== input.request.identity.targetProfileId ||\n routeConfig.agentControllerRef !==\n input.request.identity.agentControllerRef ||\n routeConfig.transportMode !== input.request.transportMode\n ) {\n return unverifiedComputerFileAccess(input.request);\n }\n try {\n const verification = await verifyBoundary({\n agentControllerPermissionMode: routeConfig.agentControllerPermissionMode,\n boundary: policy,\n executionMode: \"repair\",\n launchContract: routeConfig.launchContract ?? null,\n transportMode: input.request.transportMode,\n workingDirectory: input.request.providerRuntimeWorkingDirectory,\n });\n if (!verification.supported) {\n return unverifiedComputerFileAccess(input.request);\n }\n } catch {\n return unverifiedComputerFileAccess(input.request);\n }\n return { boundary: policy, status: \"ready\" };\n}\n\nfunction unverifiedComputerFileAccess(\n request: RuntimeTransportResumeControllerConversationFramePayload\n): {\n result: RuntimeTransportResumeControllerConversationResult;\n status: \"rejected\";\n} {\n return {\n result: rejected(\n request,\n \"execution_recovery.computer_file_access_unverified\",\n \"OpenMeld could not verify this Computer’s file access boundary for execution recovery.\"\n ),\n status: \"rejected\",\n };\n}\n\nfunction rejected(\n request: RuntimeTransportResumeControllerConversationFramePayload,\n reasonCode: string,\n message = reasonCode\n): RuntimeTransportResumeControllerConversationResult {\n return {\n destination: request.destination,\n identity: request.identity,\n message,\n operationId: request.operationId,\n reasonCode,\n status: \"rejected\",\n };\n}\n","import { mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport type {\n RuntimeTransportResumeControllerConversationFramePayload,\n RuntimeTransportResumeControllerConversationResult,\n} from \"@openmeld/schemas/types\";\n\nconst STORE_SCHEMA =\n \"openmeld-daemon-execution-recovery-operation-store-v1\" as const;\nconst RECORD_SCHEMA =\n \"openmeld-daemon-execution-recovery-operation-record-v1\" as const;\nconst STORE_FILE_NAME = \"execution-recovery-operations.json\";\nconst STORE_TEMP_FILE_NAME = \"execution-recovery-operations.tmp\";\nconst MAX_RETAINED_RECORDS = 256;\n\ntype StoredResumeControllerConversationOperation = {\n operationId: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n requestFingerprint: string;\n result: RuntimeTransportResumeControllerConversationResult | null;\n schema: typeof RECORD_SCHEMA;\n status: \"completed\" | \"in_progress\" | \"outcome_unknown\";\n updatedAtMs: number;\n};\n\ntype OperationStoreFile = {\n records: StoredResumeControllerConversationOperation[];\n schema: typeof STORE_SCHEMA;\n updatedAtMs: number;\n v: 1;\n};\n\ntype ReadRecordsResult =\n | {\n ok: true;\n records: StoredResumeControllerConversationOperation[];\n }\n | {\n ok: false;\n reasonCode:\n | \"execution_recovery.operation_store_invalid\"\n | \"execution_recovery.operation_store_unavailable\"\n | \"execution_recovery.operation_store_update_required\";\n };\n\nconst storeTails = new Map<string, Promise<void>>();\n\nexport async function runResumeControllerConversationOperation(input: {\n execute: () => Promise<RuntimeTransportResumeControllerConversationResult>;\n ledgerRootPath: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n}): Promise<RuntimeTransportResumeControllerConversationResult> {\n const previous = storeTails.get(input.ledgerRootPath) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => current);\n storeTails.set(input.ledgerRootPath, tail);\n await previous;\n try {\n return await runSerializedResumeControllerConversationOperation(input);\n } finally {\n release();\n if (storeTails.get(input.ledgerRootPath) === tail) {\n storeTails.delete(input.ledgerRootPath);\n }\n }\n}\n\nasync function runSerializedResumeControllerConversationOperation(input: {\n execute: () => Promise<RuntimeTransportResumeControllerConversationResult>;\n ledgerRootPath: string;\n request: RuntimeTransportResumeControllerConversationFramePayload;\n}): Promise<RuntimeTransportResumeControllerConversationResult> {\n const stored = readRecords(input.ledgerRootPath);\n if (!stored.ok) {\n return rejected(input.request, stored.reasonCode);\n }\n const records = stored.records;\n const requestFingerprint = stableJson(input.request);\n const existing = records.find(\n (record) => record.operationId === input.request.operationId\n );\n if (existing) {\n if (existing.requestFingerprint !== requestFingerprint) {\n return rejected(\n input.request,\n \"execution_recovery.operation_identity_conflict\"\n );\n }\n if (existing.result) {\n return existing.result;\n }\n return outcomeUnknown(\n input.request,\n \"The exact controller command started, but no authoritative result was recorded.\"\n );\n }\n\n const started: StoredResumeControllerConversationOperation = {\n operationId: input.request.operationId,\n request: input.request,\n requestFingerprint,\n result: null,\n schema: RECORD_SCHEMA,\n status: \"in_progress\",\n updatedAtMs: Date.now(),\n };\n writeRecords(input.ledgerRootPath, [...records, started]);\n\n let result: RuntimeTransportResumeControllerConversationResult;\n try {\n result = await input.execute();\n } catch (error) {\n result = outcomeUnknown(\n input.request,\n error instanceof Error ? error.message : String(error)\n );\n }\n const completed: StoredResumeControllerConversationOperation = {\n ...started,\n result,\n status:\n result.status === \"completed\" || result.status === \"rejected\"\n ? \"completed\"\n : \"outcome_unknown\",\n updatedAtMs: Date.now(),\n };\n writeRecords(input.ledgerRootPath, [...records, completed]);\n return result;\n}\n\nfunction outcomeUnknown(\n request: RuntimeTransportResumeControllerConversationFramePayload,\n message: string\n): RuntimeTransportResumeControllerConversationResult {\n return {\n destination: request.destination,\n identity: request.identity,\n message,\n operationId: request.operationId,\n reasonCode: \"execution_recovery.controller_outcome_unknown\",\n status: \"outcome_unknown\",\n };\n}\n\nfunction rejected(\n request: RuntimeTransportResumeControllerConversationFramePayload,\n reasonCode: string\n): RuntimeTransportResumeControllerConversationResult {\n return {\n destination: request.destination,\n identity: request.identity,\n message: reasonCode,\n operationId: request.operationId,\n reasonCode,\n status: \"rejected\",\n };\n}\n\nfunction readRecords(ledgerRootPath: string): ReadRecordsResult {\n const path = resolveStorePath(ledgerRootPath);\n let source: string;\n try {\n source = readFileSync(path, \"utf8\");\n } catch (error) {\n if (hasErrorCode(error, \"ENOENT\")) {\n return { ok: true, records: [] };\n }\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_unavailable\",\n };\n }\n let parsed: Partial<OperationStoreFile>;\n try {\n parsed = JSON.parse(source) as Partial<OperationStoreFile>;\n } catch {\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_invalid\",\n };\n }\n if (parsed.schema !== STORE_SCHEMA || parsed.v !== 1) {\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_update_required\",\n };\n }\n if (\n !(Array.isArray(parsed.records) && parsed.records.every(isStoredOperation))\n ) {\n return {\n ok: false,\n reasonCode: \"execution_recovery.operation_store_invalid\",\n };\n }\n return { ok: true, records: parsed.records };\n}\n\nfunction writeRecords(\n ledgerRootPath: string,\n records: StoredResumeControllerConversationOperation[]\n): void {\n const path = resolveStorePath(ledgerRootPath);\n const tempPath = join(ledgerRootPath, STORE_TEMP_FILE_NAME);\n mkdirSync(dirname(path), { recursive: true });\n const retained = [...records]\n .sort((left, right) => right.updatedAtMs - left.updatedAtMs)\n .slice(0, MAX_RETAINED_RECORDS);\n writeFileSync(\n tempPath,\n JSON.stringify(\n {\n records: retained,\n schema: STORE_SCHEMA,\n updatedAtMs: Date.now(),\n v: 1,\n } satisfies OperationStoreFile,\n null,\n 2\n ),\n { encoding: \"utf8\", mode: 0o600 }\n );\n renameSync(tempPath, path);\n}\n\nfunction resolveStorePath(ledgerRootPath: string): string {\n return join(ledgerRootPath, STORE_FILE_NAME);\n}\n\nfunction isStoredOperation(\n value: unknown\n): value is StoredResumeControllerConversationOperation {\n const candidate =\n value as Partial<StoredResumeControllerConversationOperation>;\n return (\n candidate.schema === RECORD_SCHEMA &&\n typeof candidate.operationId === \"string\" &&\n typeof candidate.requestFingerprint === \"string\" &&\n typeof candidate.request === \"object\" &&\n candidate.request !== null &&\n (candidate.result === null ||\n (typeof candidate.result === \"object\" && candidate.result !== null)) &&\n (candidate.status === \"completed\" ||\n candidate.status === \"in_progress\" ||\n candidate.status === \"outcome_unknown\") &&\n typeof candidate.updatedAtMs === \"number\"\n );\n}\n\nfunction hasErrorCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === code\n );\n}\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableJson).join(\",\")}]`;\n }\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n","import { forkSession as forkClaudeCodeSession } from \"@anthropic-ai/claude-agent-sdk\";\nimport {\n forkCodexAppServerThread,\n resolveInstalledCodexLaunchCandidates,\n} from \"@openmeld/adapter-codex\";\nimport {\n forkOpenCodeServerSession,\n resolveInstalledOpenCodeLaunchCandidates,\n} from \"@openmeld/adapter-opencode\";\nimport type { RuntimeTransportLocalAgentControlForkSessionFramePayload } from \"@openmeld/schemas/types\";\nimport { listProjectBindings } from \"../../agent-activity/project-bindings\";\nimport { recordOpenMeldCreatedLocalAgentSession } from \"../../agent-activity/session-inventory-origin-store\";\nimport { discoverLocalAgentSessionProviders } from \"../../agent-activity/session-inventory-provider-adapters\";\n\nconst PROVIDER_PROBE_TIMEOUT_MS = 5000;\nconst PROVIDER_FORK_TIMEOUT_MS = 30_000;\n\ntype ForkRequest =\n RuntimeTransportLocalAgentControlForkSessionFramePayload[\"request\"];\n\nexport async function forkAgentSession(input: {\n request: ForkRequest;\n rootDir?: string;\n}): Promise<{ childNativeSessionId: string }> {\n const source = await resolveSourceSession({\n request: input.request,\n rootDir: input.rootDir,\n });\n let childNativeSessionId: string;\n switch (input.request.agentControllerRef) {\n case \"builtin:codex\": {\n const launch = await resolveInstalledCodexLaunchCandidates({\n timeoutMs: PROVIDER_PROBE_TIMEOUT_MS,\n });\n if (!(launch.ok && launch.candidates[0])) {\n throw new AgentSessionForkError(\n \"agent_session_fork.local_agent_unavailable\",\n \"Codex is no longer available on this Computer.\"\n );\n }\n const result = await forkCodexAppServerThread({\n codexTimeoutMs: PROVIDER_FORK_TIMEOUT_MS,\n codexWorkdir: source.workingDirectory,\n // The user picked this Session in inventory and asked for a copy of it,\n // so copying its entire stored history is the requested operation. No\n // completed-turn cutoff is available or wanted here; the execution\n // context path is the one that must prove a boundary.\n forkFullHistory: true,\n launchContract: launch.candidates[0].launchContract,\n sourceThreadId: input.request.sourceNativeSessionId,\n title: buildForkedSessionTitle(input.request.profileName),\n });\n childNativeSessionId = result.threadId;\n break;\n }\n case \"builtin:claude-code\": {\n const result = await forkClaudeCodeSession(\n input.request.sourceNativeSessionId,\n {\n dir: source.workingDirectory,\n title: buildForkedSessionTitle(input.request.profileName),\n }\n );\n childNativeSessionId = result.sessionId;\n break;\n }\n case \"builtin:opencode\": {\n const launch = await resolveInstalledOpenCodeLaunchCandidates({\n timeoutMs: PROVIDER_PROBE_TIMEOUT_MS,\n });\n if (!(launch.ok && launch.candidates[0])) {\n throw new AgentSessionForkError(\n \"agent_session_fork.local_agent_unavailable\",\n \"OpenCode is no longer available on this Computer.\"\n );\n }\n const result = await forkOpenCodeServerSession({\n launchContract: launch.candidates[0].launchContract,\n openCodeTimeoutMs: PROVIDER_FORK_TIMEOUT_MS,\n openCodeWorkdir: source.workingDirectory,\n sourceSessionId: input.request.sourceNativeSessionId,\n title: buildForkedSessionTitle(input.request.profileName),\n });\n childNativeSessionId = result.sessionId;\n break;\n }\n default:\n throw new AgentSessionForkError(\n \"agent_session_fork.unsupported\",\n \"This local agent does not currently provide a verified native Fork operation.\"\n );\n }\n await recordOpenMeldCreatedLocalAgentSession({\n agentControllerRef: input.request.agentControllerRef,\n nativeSessionId: childNativeSessionId,\n rootDir: input.rootDir,\n });\n return { childNativeSessionId };\n}\n\nexport class AgentSessionForkError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AgentSessionForkError\";\n this.code = code;\n }\n}\n\nasync function resolveSourceSession(input: {\n request: ForkRequest;\n rootDir?: string;\n}): Promise<{ workingDirectory: string }> {\n const bindings = (\n await listProjectBindings({\n organizationId: input.request.organizationId,\n rootDir: input.rootDir,\n })\n ).filter((binding) => binding.projectId === input.request.projectId);\n if (bindings.length === 0) {\n throw new AgentSessionForkError(\n \"agent_session_fork.project_unavailable\",\n \"This Project is no longer connected on the selected Computer.\"\n );\n }\n const providers = await discoverLocalAgentSessionProviders({\n bindings,\n rootDir: input.rootDir,\n });\n const provider = providers.find(\n (item) => item.agentControllerRef === input.request.agentControllerRef\n );\n if (!provider || provider.result !== \"sessions\") {\n throw new AgentSessionForkError(\n \"agent_session_fork.inventory_unavailable\",\n \"OpenMeld could not read the selected local agent's current Sessions.\"\n );\n }\n const source = provider.sessions.find(\n (item) =>\n item.binding.projectId === input.request.projectId &&\n item.session.nativeSessionId === input.request.sourceNativeSessionId &&\n item.session.canFork\n );\n if (!source) {\n throw new AgentSessionForkError(\n \"agent_session_fork.source_unavailable\",\n \"The selected Session is no longer current or forkable.\"\n );\n }\n return { workingDirectory: source.binding.repositoryPath };\n}\n\nfunction buildForkedSessionTitle(profileName: string): string {\n return `OpenMeld · ${profileName}`;\n}\n","import type {\n LocalDaemonAdapterContainer,\n LocalExecutionSlots,\n} from \"@openmeld/local-service\";\nimport {\n runtimeTransportLocalAgentControlForkSessionFramePayloadSchema,\n runtimeTransportLocalAgentControlManageInstallationFramePayloadSchema,\n runtimeTransportLocalAgentControlSetEnabledFramePayloadSchema,\n runtimeTransportResumeControllerConversationFramePayloadSchema,\n runtimeTransportResumeControllerConversationResultFramePayloadSchema,\n} from \"@openmeld/schemas\";\nimport type {\n OpenMeldDaemonManageLocalAgentInstallationPayload,\n OpenMeldDaemonSetLocalAgentEnabledPayload,\n} from \"@openmeld/schemas/types\";\nimport {\n manageAgentRegistrationInstallation,\n setAgentRegistrationEnabled,\n} from \"../../agents/registry\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { sendDaemonFrame } from \"../carrier/daemon-frame-transport\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type {\n DaemonFrameSink,\n LedgerPaths,\n MutableRouteCatalogState,\n ParsedDaemonFrame,\n} from \"../core/types\";\nimport { resumeExactControllerConversation } from \"../execution-recovery/resume-controller-conversation\";\nimport { runResumeControllerConversationOperation } from \"../execution-recovery/resume-controller-conversation-operation-store\";\nimport type { LocalServiceRuntimeAgentControllerReportSyncResult } from \"../reporting/runtime-agent-controller-report-sync\";\nimport { forkAgentSession } from \"../session-control/fork-agent-session\";\nimport { runAgentSessionForkOperation } from \"../session-control/session-fork-operation-store\";\n\nexport function isExecutionHostControlFrame(frame: ParsedDaemonFrame): boolean {\n return (\n frame.code === \"daemon.local_agent_control.set_enabled\" ||\n frame.code === \"daemon.local_agent_control.manage_installation\" ||\n frame.code === \"daemon.local_agent_control.fork_session\" ||\n frame.code === \"daemon.execution_recovery.resume_controller_conversation\"\n );\n}\n\nexport function createExecutionHostControls(input: {\n computerFileAccessStorePath: string;\n ledgerPaths: LedgerPaths;\n localAdapterContainer: LocalDaemonAdapterContainer;\n localExecutionSlots: LocalExecutionSlots;\n presenter: Presenter;\n routeCatalogState: MutableRouteCatalogState;\n refreshReports(): Promise<LocalServiceRuntimeAgentControllerReportSyncResult>;\n invalidate(scope: \"activity\" | \"routes\"): void;\n}) {\n const log = (code: string, text: string) =>\n emitRunLine({ presenter: input.presenter, code, text });\n\n async function refreshReports(): Promise<\"failed\" | \"skipped\" | \"submitted\"> {\n try {\n const result = await input.refreshReports();\n if (result.failedCount > 0) {\n throw new Error(\n `OpenMeld could not submit ${result.failedCount} of ${result.reportCount} local agent reports.`\n );\n }\n return result.status;\n } catch (error) {\n log(\n \"daemon.run.local_agent_control_report_sync_failed\",\n `runtime agent controller report sync failed after local agent control: ${toErrorMessage(error)}`\n );\n return \"failed\";\n }\n }\n\n async function setEnabled(control: {\n agentId: string;\n enabled: boolean;\n }): Promise<OpenMeldDaemonSetLocalAgentEnabledPayload> {\n try {\n const result = await setAgentRegistrationEnabled(control);\n const reportSyncStatus = await refreshReports();\n if (result.changed) {\n input.invalidate(\"routes\");\n }\n log(\n \"daemon.run.local_agent_control_set_enabled\",\n `${result.displayName} is ${result.enabled ? \"enabled\" : \"disabled\"}.`\n );\n return {\n accepted: true,\n agentControllerRef: result.agentControllerRef,\n agentId: result.agentId,\n changed: result.changed,\n enabled: result.enabled,\n reportSyncStatus,\n status: result.status,\n };\n } catch (error) {\n const message = toErrorMessage(error);\n log(\n \"daemon.run.local_agent_control_set_enabled_rejected\",\n `local agent control rejected: ${message}`\n );\n return {\n accepted: false,\n agentId: control.agentId,\n enabled: control.enabled,\n changed: false,\n message,\n reasonCode: controlErrorCode(error),\n reportSyncStatus: \"failed\",\n status: \"rejected\",\n };\n }\n }\n\n async function manageInstallation(control: {\n agentId: string;\n installationId?: string;\n operation: \"list\" | \"select\";\n }): Promise<OpenMeldDaemonManageLocalAgentInstallationPayload> {\n try {\n let result: Awaited<\n ReturnType<typeof manageAgentRegistrationInstallation>\n >;\n if (control.operation === \"select\") {\n const guarded =\n await input.localExecutionSlots.runAdapterOperationIfIdle(\n control.agentId,\n () => manageAgentRegistrationInstallation(control)\n );\n if (!guarded.accepted) {\n throw new Error(\n guarded.status === \"operation_in_progress\"\n ? \"agents.installation_change_in_progress: this installation is already being changed; check again in a moment\"\n : \"agents.installation_change_blocked_by_work: this agent has work in progress; wait until it finishes before changing installations\"\n );\n }\n result = guarded.value;\n } else {\n result = await manageAgentRegistrationInstallation(control);\n }\n const selectionStatus =\n input.localExecutionSlots.getAdapterOperationStatus(control.agentId);\n const reportSyncStatus = result.changed\n ? await refreshReports()\n : \"skipped\";\n if (result.changed) {\n input.invalidate(\"routes\");\n }\n return {\n accepted: true,\n agentControllerRef: result.agentControllerRef,\n agentId: result.agentId,\n changed: result.changed,\n installations: result.installations,\n reportSyncStatus,\n selectionStatus,\n selectedInstallationId: result.selectedInstallationId,\n status: result.status,\n };\n } catch (error) {\n const message = toErrorMessage(error);\n log(\n \"daemon.run.local_agent_installation_rejected\",\n `local agent installation request rejected: ${message}`\n );\n return {\n accepted: false,\n agentId: control.agentId,\n changed: false,\n installations: [],\n message,\n reasonCode: controlErrorCode(error),\n reportSyncStatus: \"failed\",\n selectedInstallationId: null,\n status: \"rejected\",\n };\n }\n }\n\n async function handleFrame(\n frame: ParsedDaemonFrame,\n socket: DaemonFrameSink\n ): Promise<boolean> {\n if (frame.code === \"daemon.local_agent_control.set_enabled\") {\n const parsed =\n runtimeTransportLocalAgentControlSetEnabledFramePayloadSchema.parse(\n frame.payload\n );\n sendDaemonFrame(socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsed.requestId,\n payload: await setEnabled(parsed.payload),\n },\n });\n return true;\n }\n if (frame.code === \"daemon.local_agent_control.manage_installation\") {\n const parsed =\n runtimeTransportLocalAgentControlManageInstallationFramePayloadSchema.parse(\n frame.payload\n );\n sendDaemonFrame(socket, {\n code: \"daemon.local_agent_control.result\",\n payload: {\n requestId: parsed.requestId,\n payload: await manageInstallation(parsed.payload),\n },\n });\n return true;\n }\n if (frame.code === \"daemon.local_agent_control.fork_session\") {\n const parsed =\n runtimeTransportLocalAgentControlForkSessionFramePayloadSchema.parse(\n frame.payload\n );\n const result = await runAgentSessionForkOperation({\n execute: () => forkAgentSession({ request: parsed.request }),\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n request: parsed.request,\n });\n sendDaemonFrame(socket, {\n code: \"daemon.local_agent_control.result\",\n payload: { requestId: parsed.requestId, payload: result },\n });\n log(\n result.status === \"completed\"\n ? \"daemon.run.agent_session_fork_completed\"\n : \"daemon.run.agent_session_fork_failed\",\n result.status === \"completed\"\n ? `forked ${result.agentControllerRef} Session ${result.sourceNativeSessionId}.`\n : `Agent Session Fork ${result.status}: ${result.reasonCode}.`\n );\n if (result.status === \"completed\") {\n input.invalidate(\"activity\");\n }\n return true;\n }\n if (\n frame.code === \"daemon.execution_recovery.resume_controller_conversation\"\n ) {\n const parsed =\n runtimeTransportResumeControllerConversationFramePayloadSchema.parse(\n frame.payload\n );\n const result = await runResumeControllerConversationOperation({\n execute: () =>\n resumeExactControllerConversation({\n computerFileAccessStorePath: input.computerFileAccessStorePath,\n localAdapterContainer: input.localAdapterContainer,\n request: parsed,\n routeConfig:\n input.routeCatalogState.routeByProfileId.get(\n parsed.identity.targetProfileId\n ) ?? null,\n }),\n ledgerRootPath: input.ledgerPaths.rootDirPath,\n request: parsed,\n });\n sendDaemonFrame(socket, {\n code: \"daemon.execution_recovery.resume_controller_conversation_result\",\n payload:\n runtimeTransportResumeControllerConversationResultFramePayloadSchema.parse(\n { requestId: parsed.requestId, result }\n ),\n });\n return true;\n }\n return false;\n }\n\n return { handleFrame, setEnabled };\n}\n\nfunction controlErrorCode(error: unknown): string {\n const code =\n error instanceof Error ? error.message.split(\":\", 1)[0]?.trim() : null;\n return code?.includes(\".\") ? code : \"agents.unexpected_error\";\n}\n","import { randomUUID } from \"node:crypto\";\nimport { performance } from \"node:perf_hooks\";\nimport {\n RUNTIME_TRANSPORT_SCHEMA_VERSION,\n runtimeTransportDispatchLifecycleAcknowledgementSchema,\n runtimeTransportDispatchLifecycleRequestSchema,\n} from \"@openmeld/schemas\";\nimport type { RuntimeTransportDeliverDispatchRequest } from \"@openmeld/schemas/types\";\nimport type { CurrentDaemonSocketRef } from \"../core/types\";\nimport { ExecutionHostError } from \"./channel\";\n\ntype AdmissionRequest = Pick<\n RuntimeTransportDeliverDispatchRequest,\n \"dispatchId\" | \"attemptId\" | \"daemonSessionId\" | \"leaseEpoch\"\n> & {\n payload: Pick<\n RuntimeTransportDeliverDispatchRequest[\"payload\"],\n \"executionToken\" | \"runtimeCoordinatorExecutionId\"\n >;\n};\n\n// Response waiters only: the Coordinator remains the execution authority.\n// Missing observations never authorize starting a provider.\nexport function createExecutionAdmissionConfirmation(\n socketRef: CurrentDaemonSocketRef\n) {\n const pending = new Map<\n string,\n {\n request: AdmissionRequest;\n sentAt: number;\n resolve(): void;\n reject(error: Error): void;\n }\n >();\n const resend = () => {\n if (!socketRef.socket || socketRef.connectionGeneration === null) {\n return;\n }\n for (const [previousId, waiter] of [...pending]) {\n const acknowledgementId = randomUUID();\n pending.delete(previousId);\n pending.set(acknowledgementId, waiter);\n waiter.sentAt = performance.now();\n const request = waiter.request;\n const token = request.payload.executionToken;\n const payload = runtimeTransportDispatchLifecycleRequestSchema.parse({\n v: RUNTIME_TRANSPORT_SCHEMA_VERSION,\n acknowledgementId,\n dispatchId: request.dispatchId,\n attemptId: request.attemptId,\n daemonSessionId: request.daemonSessionId,\n connectionGeneration: socketRef.connectionGeneration,\n leaseEpoch: request.leaseEpoch,\n runtimeCoordinatorExecutionId:\n request.payload.runtimeCoordinatorExecutionId,\n executionTokenEcho: token\n ? {\n executionToken: token.executionToken,\n runId: token.runId,\n tokenFingerprint: token.tokenFingerprint,\n runtimeCoordinatorExecutionId:\n token.executionScope.runtimeCoordinatorExecutionId,\n }\n : undefined,\n phase: \"accepted_local\",\n lifecycleAtMs: Date.now(),\n });\n try {\n socketRef.socket.send(\n JSON.stringify({\n v: RUNTIME_TRANSPORT_SCHEMA_VERSION,\n code: \"daemon.dispatch.lifecycle\",\n payload,\n })\n );\n } catch {\n // Delivery is unconfirmed. Reconnection retries this read/confirmation,\n // never the provider execution, and a send failure cannot grant access.\n }\n }\n };\n return {\n confirm(request: AdmissionRequest): Promise<void> {\n return new Promise((resolve, reject) => {\n const id = randomUUID();\n pending.set(id, {\n request,\n resolve,\n reject,\n sentAt: performance.now(),\n });\n try {\n resend();\n } catch (error) {\n for (const [pendingId, waiter] of pending) {\n if (waiter.resolve === resolve) {\n pending.delete(pendingId);\n }\n }\n reject(error);\n }\n });\n },\n resend,\n receive(payload: unknown) {\n const parsed =\n runtimeTransportDispatchLifecycleAcknowledgementSchema.safeParse(\n payload\n );\n if (!parsed.success) {\n return;\n }\n const reply = parsed.data;\n const waiter = pending.get(reply.acknowledgementId);\n if (\n !waiter ||\n reply.connectionGeneration !== socketRef.connectionGeneration ||\n waiter.request.dispatchId !== reply.dispatchId ||\n waiter.request.attemptId !== reply.attemptId\n ) {\n return;\n }\n if (\n reply.accepted &&\n performance.now() - waiter.sentAt >= reply.validForMs\n ) {\n // A delayed positive reply is not fresh permission. Keep the same\n // execution waiting; heartbeat/reconnect retries only the confirmation.\n return;\n }\n pending.delete(reply.acknowledgementId);\n if (reply.accepted) {\n waiter.resolve();\n } else {\n waiter.reject(\n new ExecutionHostError(\n reply.reasonCode ?? \"host.execution_not_authorized\",\n \"RuntimeCoordinator did not authorize this execution; the provider was not started.\"\n )\n );\n }\n },\n };\n}\n","import {\n createInflightTaskControlRegistry,\n createLocalAdapterContainer,\n createLocalAdapterEntries,\n createLocalTaskInterruptSender,\n createPendingAgentInteractionRegistry,\n} from \"@openmeld/local-service\";\nimport {\n RUNTIME_TRANSPORT_SCHEMA_VERSION,\n SERVICE_EXECUTION_HOST_PROTOCOL,\n type ServiceExecutionHostCatalog,\n type ServiceExecutionHostIdentity,\n type ServiceExecutionHostMessage,\n type ServiceExecutionHostSnapshot,\n serviceExecutionHostCatalogSchema,\n} from \"@openmeld/schemas\";\nimport { createManagedAgentActivityIntegrationRefreshScheduler } from \"../../agent-activity/integration-refresh\";\nimport { startLocalAgentActivitySyncLoop } from \"../../agent-activity/local-sync\";\nimport { getConfiguredDaemonDispatchLimits } from \"../../config/runtime-config\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport { parseDaemonFrame } from \"../carrier/daemon-frame-transport\";\nimport { handleDaemonSocketFrame } from \"../carrier/frame-router\";\nimport {\n handleLocalControlPlaneCancel,\n handleLocalControlPlaneInterrupt,\n} from \"../carrier/local-control-handlers\";\nimport { createDaemonLocalExecutionSlots } from \"../carrier/local-execution-slots\";\nimport { resolveLocalConversationExecutionStatus } from \"../control-plane/conversation-execution-status\";\nimport { CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS } from \"../core/constants\";\nimport { emitRunLine, toErrorMessage } from \"../core/logger\";\nimport type {\n CurrentDaemonSocketRef,\n DaemonFrameSink,\n DaemonRuntimePaths,\n InflightDispatchMeta,\n RouteCatalog,\n} from \"../core/types\";\nimport {\n flushDispatchResultOutbox,\n listDispatchResultOutboxPendingAcknowledgementKeys,\n waitForDispatchResultOutboxAcknowledgement,\n} from \"../dispatch/dispatch-result-outbox\";\nimport { sendDispatchInteractionRequestFrame } from \"../dispatch/send-dispatch-result\";\nimport { resolveComputerFileAccessStorePath } from \"../file-access/computer-file-access-store\";\nimport { consumeArmedAgentControllerInterfaceReprobe } from \"../inventory/agent-controller-interface-keeper\";\nimport { syncLocalServiceProviderConversationProofs } from \"../reporting/provider-conversation-proof-sync\";\nimport { syncLocalServiceRuntimeAgentControllerReports } from \"../reporting/runtime-agent-controller-report-sync\";\nimport { createRuntimeReportingAttemptObserver } from \"../reporting/runtime-reporting-attempt-observer\";\nimport { syncActiveTaskPermissionModes } from \"../routing/active-permission-mode-sync\";\nimport {\n createMutableRouteCatalogState,\n createRouteCatalogFromMutableState,\n} from \"../routing/route-catalog-state\";\nimport { loadContextStore } from \"../state/context-store\";\nimport { buildLedgerPaths } from \"../state/daemon-device-id\";\nimport {\n loadExecutionHostCatalog,\n persistExecutionHostCatalog,\n} from \"./catalog\";\nimport { ExecutionHostError, type ExecutionHostHandlers } from \"./channel\";\nimport {\n createExecutionHostControls,\n isExecutionHostControlFrame,\n} from \"./controls\";\nimport { createExecutionAdmissionConfirmation } from \"./execution-admission\";\n\ntype HostEvent = Exclude<ServiceExecutionHostMessage, { type: \"reply\" }>;\n\nexport async function createExecutionHostResources(input: {\n runtimePaths: DaemonRuntimePaths;\n presenter: Presenter;\n}) {\n const ledgerPaths = buildLedgerPaths(input.runtimePaths.ledgerRootPath);\n const contextStore = await loadContextStore(\n input.runtimePaths.contextStorePath\n );\n const inflightDispatchMetaByTaskId = new Map<string, InflightDispatchMeta>();\n const inflightTaskControlRegistry = createInflightTaskControlRegistry();\n const pendingAgentInteractionRegistry =\n createPendingAgentInteractionRegistry();\n const interrupt = createLocalTaskInterruptSender({\n registry: inflightTaskControlRegistry,\n });\n const localAdapterContainer = createLocalAdapterContainer(\n createLocalAdapterEntries({\n runtimeWorkdir: process.cwd(),\n sendInterrupt: async (signal) => {\n await interrupt(signal);\n },\n registerRuntimeProcess: (event) => {\n const processId =\n event.phase === \"process_exit\" ? null : event.processId;\n const updated = inflightTaskControlRegistry.updateTaskProcess({\n processId,\n signalTarget:\n event.phase === \"process_exit\" ? null : event.signalTarget,\n taskId: event.taskId,\n });\n if (updated) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.control_process_registered\",\n text: `control process ${event.phase === \"process_spawned\" ? \"registered\" : \"cleared\"} for task ${event.taskId}`,\n payload: {\n adapterId: updated.adapterId,\n dispatchId: updated.dispatchId,\n phase: event.phase,\n processId,\n taskId: event.taskId,\n signalTarget: event.signalTarget,\n },\n });\n }\n },\n })\n );\n const emptyCatalog: RouteCatalog = {\n profileIds: [],\n routeByProfileId: new Map(),\n skippedProfiles: [],\n };\n\n return {\n ledgerPaths,\n contextStore,\n inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry,\n pendingAgentInteractionRegistry,\n localAdapterContainer,\n initialCatalog: emptyCatalog,\n dispatchLimits: await getConfiguredDaemonDispatchLimits(),\n };\n}\nexport type ExecutionHostResources = Awaited<\n ReturnType<typeof createExecutionHostResources>\n>;\n\n// One Host owns these execution objects across all replacement cloud sockets.\n// No socket, reconnect loop, public listener or independent task scheduler lives\n// here. The original execution/approval/result domain owners remain in use.\nexport function createExecutionHostRuntime(input: {\n resources: ExecutionHostResources;\n hostInstanceId: string;\n identity: ServiceExecutionHostIdentity;\n runtimePaths: DaemonRuntimePaths;\n serviceBundleId: string | null;\n profileOwnerName: string | null;\n presenter: Presenter;\n emit(event: HostEvent): void;\n onWorkStateChange?(quiescent: boolean): void;\n}) {\n const identity = input.identity;\n const {\n ledgerPaths,\n contextStore,\n inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry,\n pendingAgentInteractionRegistry,\n localAdapterContainer,\n initialCatalog: emptyCatalog,\n } = input.resources;\n const localExecutionSlots = createDaemonLocalExecutionSlots({\n limits: input.resources.dispatchLimits,\n presenter: input.presenter,\n onChanged: () => {\n input.onWorkStateChange?.(snapshot().localQuiescent);\n invalidate(\"execution\");\n },\n });\n const routeCatalogState = createMutableRouteCatalogState(emptyCatalog);\n const currentSocketRef: CurrentDaemonSocketRef = {\n socket: null,\n connectionGeneration: null,\n };\n const executionAdmission =\n createExecutionAdmissionConfirmation(currentSocketRef);\n currentSocketRef.confirmExecutionAdmission = executionAdmission.confirm;\n const leasesByProfileId = new Map<string, number>();\n const catalogs = new Map<number, RouteCatalog>([[0, emptyCatalog]]);\n let catalogRevision = 0;\n let activeCatalogRevision = 0;\n let generation = 0;\n let draining = false;\n let disposed = false;\n let startupReplayPending = false;\n let connectionAbort: AbortController | null = null;\n let catalogLoad: Promise<ServiceExecutionHostCatalog> | null = null;\n let controllerReport: Promise<\n Awaited<ReturnType<typeof syncLocalServiceRuntimeAgentControllerReports>>\n > | null = null;\n let reportPolicy: \"background\" | \"fresh\" | null = null;\n const activeControls = new Set<Promise<unknown>>();\n const envelope = {\n protocol: SERVICE_EXECUTION_HOST_PROTOCOL,\n hostInstanceId: input.hostInstanceId,\n } as const;\n const computerFileAccessStorePath = resolveComputerFileAccessStorePath(\n input.runtimePaths.dataRootPath\n );\n const emit = (event: HostEvent): void => {\n if (!disposed) {\n input.emit(event);\n }\n };\n const invalidate = (scope: \"routes\" | \"activity\" | \"execution\") =>\n emit({ ...envelope, type: \"invalidate\", scope });\n const owner = {\n lane: identity.lane,\n ownerUserId: identity.ownerUserId,\n localAdapterContainer,\n presenter: input.presenter,\n serviceBundleId: input.serviceBundleId,\n };\n const reportingAttempt = () => {\n const connectionGeneration = currentSocketRef.connectionGeneration;\n return createRuntimeReportingAttemptObserver({\n serviceIdentity: {\n deviceId: identity.deviceId,\n contractGeneration: identity.serviceContractGeneration,\n },\n onAuthenticationFailure: (failure) =>\n emit({\n ...envelope,\n type: \"authentication_failure\",\n connectionGeneration,\n failure,\n }),\n });\n };\n\n function snapshot(): ServiceExecutionHostSnapshot {\n const state = localExecutionSlots.getDrainState();\n return {\n pid: process.pid,\n admission: draining ? \"draining\" : \"open\",\n activeCount: state.activeGlobal,\n pendingCount: state.pendingCount,\n localQuiescent:\n localExecutionSlots.isQuiescent() && activeControls.size === 0,\n unacknowledgedResultCount:\n listDispatchResultOutboxPendingAcknowledgementKeys({ ledgerPaths })\n .length,\n startupReplayPending,\n adapterIds: localAdapterContainer\n .listAdapters()\n .map((entry) => entry.adapterId),\n };\n }\n\n function assertConnection(expected: number): DaemonFrameSink {\n if (expected !== generation || !currentSocketRef.socket || disposed) {\n throw new ExecutionHostError(\n \"host.connection_replaced\",\n \"The operation belongs to a retired connector generation.\"\n );\n }\n return currentSocketRef.socket;\n }\n\n function replayInteractions(): void {\n const sink = currentSocketRef.socket;\n if (!sink) {\n return;\n }\n for (const pending of pendingAgentInteractionRegistry.list()) {\n const leaseEpoch = leasesByProfileId.get(\n pending.authority.targetProfileId\n );\n if (pending.response || !leaseEpoch) {\n continue;\n }\n sendDispatchInteractionRequestFrame({\n attemptId: pending.authority.attemptId,\n connectionGeneration: generation,\n daemonSessionId: identity.daemonSessionId,\n dispatchId: pending.authority.dispatchId,\n executionIdentityEcho: pending.authority.executionIdentityEcho,\n executionTokenEcho: pending.authority.executionTokenEcho,\n interaction: pending.request,\n leaseEpoch,\n runtimeCoordinatorExecutionId:\n pending.authority.runtimeCoordinatorExecutionId,\n socket: sink,\n taskId: pending.taskId,\n });\n }\n }\n\n function startResultReplay(): void {\n const recordKeys = listDispatchResultOutboxPendingAcknowledgementKeys({\n ledgerPaths,\n });\n const expectedGeneration = generation;\n startupReplayPending = recordKeys.length > 0;\n if (startupReplayPending) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.startup_result_replay_started\",\n text: \"Replaying retained results before accepting new work.\",\n });\n }\n const replay = waitForDispatchResultOutboxAcknowledgement({\n abortSignal: connectionAbort?.signal,\n ledgerPaths,\n recordKeys,\n });\n flushDispatchResultOutbox({\n currentSocketRef,\n ledgerPaths,\n presenter: input.presenter,\n });\n replay\n .then((status) => {\n if (\n status === \"acknowledged\" &&\n generation === expectedGeneration &&\n currentSocketRef.socket &&\n !draining\n ) {\n startupReplayPending = false;\n if (recordKeys.length > 0) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.startup_result_replay_completed\",\n text: \"Retained results were acknowledged; new work may be admitted.\",\n });\n }\n invalidate(\"execution\");\n }\n })\n .catch((error) => {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.startup_result_replay_failed\",\n text: toErrorMessage(error),\n });\n });\n }\n\n async function reportControllers(policy: \"background\" | \"fresh\") {\n if (controllerReport) {\n const previous = controllerReport;\n if (policy !== \"fresh\" || reportPolicy === \"fresh\") {\n return await previous;\n }\n await previous;\n }\n const attempt = syncLocalServiceRuntimeAgentControllerReports({\n localAdapterContainer,\n onAttempt: reportingAttempt(),\n probePolicy: policy,\n });\n controllerReport = attempt;\n reportPolicy = policy;\n try {\n return await attempt;\n } finally {\n if (controllerReport === attempt) {\n controllerReport = null;\n reportPolicy = null;\n }\n }\n }\n\n const controls = createExecutionHostControls({\n computerFileAccessStorePath,\n ledgerPaths,\n localAdapterContainer,\n localExecutionSlots,\n presenter: input.presenter,\n routeCatalogState,\n refreshReports: () => reportControllers(\"fresh\"),\n invalidate,\n });\n const activity = startLocalAgentActivitySyncLoop({\n onError: (error) =>\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_activity_sync_failed\",\n text: toErrorMessage(error),\n }),\n onResult: (result) => {\n if (result.status === \"idle\") {\n return;\n }\n emitRunLine({\n presenter: input.presenter,\n code:\n result.status === \"submitted\"\n ? \"daemon.run.agent_activity_sync\"\n : \"daemon.run.agent_activity_sync_unavailable\",\n text:\n result.status === \"submitted\"\n ? `Local Agent reporting submitted ${result.submittedCount} activity event(s), ${result.controllerTaskEventSubmittedCount} task callback event(s), and ${result.sessionInventory.submittedSourceCount} Session Inventory source(s).`\n : `Agent Activity sync deferred: ${result.reason ?? \"unavailable\"}.`,\n payload: {\n ...result.health,\n controllerTaskEventSubmittedCount:\n result.controllerTaskEventSubmittedCount,\n controllerTaskHealth: result.controllerTaskHealth,\n observedCount: result.observedCount,\n reason: result.reason,\n sessionInventory: result.sessionInventory,\n status: result.status,\n submittedCount: result.submittedCount,\n },\n });\n },\n });\n const integrations = createManagedAgentActivityIntegrationRefreshScheduler({\n onError: (error) =>\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.agent_activity_integration_refresh_failed\",\n text: toErrorMessage(error),\n }),\n onResult: (result) => {\n if (result.status === \"ready\") {\n activity.requestSync({ refreshContext: true });\n }\n },\n });\n // Inventory is independent of opening the inherited control endpoint.\n integrations.request();\n\n function beginDrain(): ServiceExecutionHostSnapshot {\n draining = true;\n localExecutionSlots.beginDrain();\n return snapshot();\n }\n\n async function drain(): Promise<ServiceExecutionHostSnapshot> {\n beginDrain();\n await localExecutionSlots.drain();\n await Promise.allSettled([...activeControls]);\n const drained = snapshot();\n input.onWorkStateChange?.(drained.localQuiescent);\n return drained;\n }\n\n function trackControl<T>(run: () => Promise<T>): Promise<T> {\n if (draining || disposed) {\n return Promise.reject(\n new ExecutionHostError(\n \"host.draining\",\n \"The execution host is draining; new operations are not admitted.\"\n )\n );\n }\n input.onWorkStateChange?.(false);\n const operation = Promise.resolve().then(run);\n activeControls.add(operation);\n return operation.finally(() => {\n activeControls.delete(operation);\n input.onWorkStateChange?.(snapshot().localQuiescent);\n invalidate(\"execution\");\n });\n }\n\n const handlers: Omit<ExecutionHostHandlers, \"initialize\"> = {\n health: snapshot,\n loadCatalog: async ({ initial }) => {\n if (!catalogLoad) {\n catalogLoad = loadExecutionHostCatalog(owner, initial)\n .then((catalog) => {\n const revision = ++catalogRevision;\n catalogs.set(revision, catalog);\n // Retain the active snapshot plus the latest two loads. Never resolve\n // a retired revision by substituting another set of routes.\n for (const key of catalogs.keys()) {\n if (key !== activeCatalogRevision && key < revision - 1) {\n catalogs.delete(key);\n }\n }\n return serviceExecutionHostCatalogSchema.parse({\n revision,\n expectedRoutesContractVersion:\n catalog.expectedRoutesContractVersion,\n profileIds: catalog.profileIds,\n routes: [...catalog.routeByProfileId.values()],\n skippedProfiles: catalog.skippedProfiles,\n workingFolderExpectedProfileIds:\n catalog.workingFolderExpectedProfileIds,\n workingFolderObservations: catalog.workingFolderObservations,\n });\n })\n .finally(() => {\n catalogLoad = null;\n });\n }\n return await catalogLoad;\n },\n configureConnection: async (request) => {\n if (request.executionAdmissionConfirmation !== true) {\n throw new ExecutionHostError(\n \"host.execution_admission_unsupported\",\n \"The connected server must support execution admission confirmation before this Host can run tasks.\"\n );\n }\n if (request.connectionGeneration < generation || disposed) {\n throw new ExecutionHostError(\n \"host.connection_replaced\",\n \"An older connector cannot replace the active connection.\"\n );\n }\n const catalog = catalogs.get(request.catalogRevision);\n if (!catalog || request.catalogRevision < activeCatalogRevision) {\n throw new ExecutionHostError(\n \"host.catalog_replaced\",\n \"The requested Host catalog is no longer available.\"\n );\n }\n connectionAbort?.abort();\n connectionAbort = new AbortController();\n generation = request.connectionGeneration;\n activeCatalogRevision = request.catalogRevision;\n Object.assign(routeCatalogState, createMutableRouteCatalogState(catalog));\n leasesByProfileId.clear();\n for (const lease of request.leases) {\n leasesByProfileId.set(lease.profileId, lease.leaseEpoch);\n }\n const sink: DaemonFrameSink = {\n send: (raw) => {\n if (\n generation !== request.connectionGeneration ||\n currentSocketRef.socket !== sink\n ) {\n throw new ExecutionHostError(\n \"host.connection_replaced\",\n \"This execution frame's connector has been retired.\"\n );\n }\n const frame = parseDaemonFrame(raw);\n if (!frame) {\n throw new ExecutionHostError(\n \"host.invalid_frame\",\n \"Execution produced an invalid transport frame.\"\n );\n }\n emit({\n ...envelope,\n type: \"frame\",\n connectionGeneration: generation,\n frame: { v: RUNTIME_TRANSPORT_SCHEMA_VERSION, ...frame },\n });\n },\n };\n currentSocketRef.socket = sink;\n currentSocketRef.connectionGeneration = generation;\n executionAdmission.resend();\n const outcomes = await syncActiveTaskPermissionModes({\n catalogState: routeCatalogState,\n inflightTaskControlRegistry,\n localAdapterContainer,\n });\n for (const outcome of outcomes) {\n emitRunLine({\n presenter: input.presenter,\n code: \"daemon.run.active_permission_mode_sync\",\n text: `active permission update ${outcome.status} for ${outcome.taskId}`,\n payload: outcome,\n });\n }\n assertConnection(request.connectionGeneration);\n replayInteractions();\n startResultReplay();\n return snapshot();\n },\n detachConnection: ({ connectionGeneration }) => {\n if (connectionGeneration === generation) {\n connectionAbort?.abort();\n currentSocketRef.socket = null;\n currentSocketRef.connectionGeneration = null;\n localExecutionSlots.dropPendingTasks({\n reason: \"daemon.session.unexpected_close\",\n });\n }\n return snapshot();\n },\n heartbeat: ({ connectionGeneration, staleProfileIds }) => {\n assertConnection(connectionGeneration);\n executionAdmission.resend();\n for (const profileId of staleProfileIds) {\n leasesByProfileId.delete(profileId);\n }\n flushDispatchResultOutbox({\n currentSocketRef,\n ledgerPaths,\n presenter: input.presenter,\n });\n replayInteractions();\n return snapshot();\n },\n handleFrame: async ({ connectionGeneration, frame }) => {\n const socket = assertConnection(connectionGeneration);\n if (frame.code === \"daemon.dispatch.lifecycle_acknowledged\") {\n executionAdmission.receive(frame.payload);\n return {};\n }\n if (isExecutionHostControlFrame(frame)) {\n await trackControl(() => controls.handleFrame(frame, socket));\n return {};\n }\n if (frame.code === \"daemon.dispatch.deliver\") {\n if (draining || startupReplayPending) {\n throw new ExecutionHostError(\n \"host.admission_closed\",\n \"Execution admission is closed; the existing Coordinator retains delivery ownership.\"\n );\n }\n input.onWorkStateChange?.(false);\n }\n handleDaemonSocketFrame({\n computerFileAccessStorePath,\n contextStore,\n currentSocketRef,\n daemonSessionId: identity.daemonSessionId,\n parsedFrame: frame,\n inflightDispatchMetaByTaskId,\n inflightTaskControlRegistry,\n ledgerPaths,\n leasesByProfileId,\n localAdapterContainer,\n localExecutionSlots,\n pendingAgentInteractionRegistry,\n profileOwnerName: input.profileOwnerName,\n profileOwnerUserId: identity.ownerUserId,\n requestCurrentWorkingFolderFactRefresh: () => invalidate(\"routes\"),\n presenter: input.presenter,\n routeByProfileId: routeCatalogState.routeByProfileId,\n socket,\n waiters: {\n registerResolver: null,\n registerRejecter: null,\n heartbeatResolver: null,\n heartbeatRejecter: null,\n },\n });\n input.onWorkStateChange?.(snapshot().localQuiescent);\n invalidate(\"execution\");\n return {};\n },\n cancel: (payload) =>\n handleLocalControlPlaneCancel({\n localAdapterContainer,\n payload,\n presenter: input.presenter,\n registry: inflightTaskControlRegistry,\n }),\n interrupt: (payload) =>\n handleLocalControlPlaneInterrupt({\n localAdapterContainer,\n payload,\n presenter: input.presenter,\n registry: inflightTaskControlRegistry,\n }),\n conversationStatus: resolveLocalConversationExecutionStatus,\n setEnabled: (payload) => trackControl(() => controls.setEnabled(payload)),\n reportControllers: async ({ probePolicy }) => {\n const result = await reportControllers(probePolicy);\n return {\n ...result,\n reasonCodes: [...result.reasonCodes],\n hasArmedReprobe: consumeArmedAgentControllerInterfaceReprobe(),\n };\n },\n reportConversations: async () => {\n const result = await syncLocalServiceProviderConversationProofs({\n onAttempt: reportingAttempt(),\n routeCatalog: createRouteCatalogFromMutableState(routeCatalogState),\n });\n return { ...result, reasonCodes: [...result.reasonCodes] };\n },\n persistCatalog: async ({ revision }) => {\n const catalog = catalogs.get(revision);\n if (!catalog || revision !== activeCatalogRevision) {\n throw new ExecutionHostError(\n \"host.catalog_replaced\",\n \"Only the currently accepted catalog can be persisted.\"\n );\n }\n await persistExecutionHostCatalog(owner, catalog);\n return {};\n },\n syncActivity: ({ refreshIntegrations }) => {\n activity.requestSync({ reconcile: true, refreshContext: true });\n if (refreshIntegrations) {\n // Startup may have skipped installation because no Project was bound.\n // Reuse the Host's coalescing scheduler; never block connector control.\n integrations.request();\n }\n return {};\n },\n beginDrain,\n drain,\n settleResults: async () => {\n if (!snapshot().localQuiescent) {\n throw new ExecutionHostError(\n \"host.work_active\",\n \"Local work must drain before result settlement.\"\n );\n }\n if (!(currentSocketRef.socket && connectionAbort)) {\n return { status: \"connection_closed\" };\n }\n const abort = new AbortController();\n const onClose = () => abort.abort();\n const connectionSignal = connectionAbort.signal;\n connectionSignal.addEventListener(\"abort\", onClose, { once: true });\n const timer = setTimeout(\n () => abort.abort(),\n CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS\n );\n try {\n const recordKeys = listDispatchResultOutboxPendingAcknowledgementKeys({\n ledgerPaths,\n });\n const wait = waitForDispatchResultOutboxAcknowledgement({\n abortSignal: abort.signal,\n ledgerPaths,\n recordKeys,\n });\n flushDispatchResultOutbox({\n currentSocketRef,\n ledgerPaths,\n presenter: input.presenter,\n });\n const result = await wait;\n if (result === \"acknowledged\") {\n return { status: \"acknowledged\" };\n }\n return {\n status: connectionSignal.aborted ? \"connection_closed\" : \"timeout\",\n };\n } finally {\n clearTimeout(timer);\n connectionSignal.removeEventListener(\"abort\", onClose);\n }\n },\n stop: async () => {\n const result = await drain();\n await integrations.stop();\n await activity.stop();\n connectionAbort?.abort();\n currentSocketRef.socket = null;\n currentSocketRef.connectionGeneration = null;\n disposed = true;\n return result;\n },\n };\n\n return {\n handlers,\n snapshot,\n async closeAfterConnectorLoss() {\n if (!disposed) {\n handlers.detachConnection({ connectionGeneration: generation });\n await handlers.stop({});\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAM,sCAAsC;AAC5C,MAAM,mCAAmC;AACzC,SAAS,mCAAmC,OAAO;CAClD,IAAI,cAAc;CAClB,IAAI,MAAM,mBAAmB,WAAW,cAAc;MACjD,IAAI,MAAM,mBAAmB,cAAc,cAAc;CAC9D,OAAO;EACN,MAAM;EACN,OAAO;EACP;EACA,WAAW,CAAC;GACX,YAAY;GACZ,QAAQ;GACR,UAAU;GACV,YAAY;GACZ,SAAS;IACR,GAAG,MAAM,mBAAmB,cAAc,CAAC;KAC1C,UAAU;KACV,OAAO;KACP,aAAa,OAAO,MAAM,oBAAoB;IAC/C,CAAC,IAAI,CAAC;IACN;KACC,UAAU;KACV,OAAO;KACP,aAAa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