runtime.ts 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. import { DeferredRuntimeConversation } from "@mavis/conversation-contract";
  2. import {
  3. LocalQuestionnaireService,
  4. createDeferredLocalAgentRuntimePort,
  5. createLocalRuntimeHost as createLocalRuntimeHostV1,
  6. ensureCurrentLocalRuntimeDataMigratedToV2OrThrow,
  7. isLocalRuntimeStartupExecutionEnabled,
  8. resolveAgentBashEnvPolicy,
  9. type DeferredLocalAgentRuntimePort,
  10. type CreatedLocalRuntimeHost as V1CreatedLocalRuntimeHost,
  11. } from "@mavis/local-runtime";
  12. import { logger } from "@mavis/shared/local-runtime-logging";
  13. import {
  14. createBackgroundRuntime,
  15. type BackgroundRuntime,
  16. } from "./background-runtime.js";
  17. import {
  18. cleanupFailedV1Startup,
  19. createDeferredAgentRuntimeTelemetry,
  20. createV1RuntimeCompatibility,
  21. withAgentStorageLock,
  22. type V1RuntimeCompatibility,
  23. } from "./compat/v1/runtime.js";
  24. import { createV2AgentRuntimeManagementPort } from "./local/agent-runtime-port.js";
  25. import { DatabaseClient } from "./infra/db/client.js";
  26. import {
  27. initializeDatabase,
  28. type DatabaseInitializationResult,
  29. } from "./infra/db/initialize.js";
  30. import { createCliService } from "./local/app.js";
  31. import type {
  32. CreateLocalRuntimeHostOptions,
  33. CreatedLocalRuntimeHost,
  34. LocalRuntimeProductHostOptions,
  35. } from "./local/host-contract.js";
  36. import {
  37. createDeferredLocalSandboxBashOperationsFactory,
  38. createRuntimeAgentComposition,
  39. createRuntimeServices,
  40. prepareRuntimeServices,
  41. type AgentCutoverLogEvent,
  42. type AgentRuntimeOwner,
  43. type CreateRuntimeServicesOptions,
  44. type DeferredLocalSandboxBashOperationsFactory,
  45. type LegacyCustomAgentMaterializationEvent,
  46. type LegacyIdentityDetachEvent,
  47. type PreparedRuntimeServices,
  48. type RuntimeServices,
  49. type RuntimeServicesTestOverrides,
  50. } from "./services.js";
  51. const V2_LAYOUT_MIGRATION_RECEIPT_CARRIER = Symbol.for(
  52. "mavis.local-runtime.v2-layout-migration-receipt",
  53. );
  54. /** @internal Component-scoped overrides used by runtime tests and parity probes. */
  55. export interface LocalRuntimeV2TestOverrides {
  56. readonly database?: {
  57. readonly sqlite3ModulePath?: string;
  58. };
  59. readonly services?: RuntimeServicesTestOverrides;
  60. }
  61. interface InitializedOwnerRuntime {
  62. readonly database: DatabaseClient;
  63. readonly background: BackgroundRuntime;
  64. readonly services: RuntimeServices;
  65. readonly disabledLegacyScheduleCount: number;
  66. }
  67. /** Creates a fully initialized local runtime. The returned compatibility `ready` is resolved. */
  68. export function createLocalRuntimeHostV2(
  69. options: LocalRuntimeProductHostOptions,
  70. ): Promise<CreatedLocalRuntimeHost> {
  71. return createLocalRuntimeHostV2Internal(options, {});
  72. }
  73. /** @internal Direct-module test seam; intentionally absent from the package facade. */
  74. export function createLocalRuntimeHostV2ForTest(
  75. options: LocalRuntimeProductHostOptions,
  76. overrides: LocalRuntimeV2TestOverrides = {},
  77. ): Promise<CreatedLocalRuntimeHost> {
  78. return createLocalRuntimeHostV2Internal(options, overrides);
  79. }
  80. function bindAskUserSuppressionProbe(
  81. apiHost: V1CreatedLocalRuntimeHost["apiHost"],
  82. turnSystem: InitializedOwnerRuntime["services"]["turnSystem"] | undefined,
  83. ): void {
  84. const turnInspection = turnSystem?.inspection;
  85. if (!turnInspection?.hasPendingUserSteering) return;
  86. const hasPendingUserSteering =
  87. turnInspection.hasPendingUserSteering.bind(turnInspection);
  88. apiHost.hasPendingUserSteeringProbe = (sessionId) =>
  89. hasPendingUserSteering(sessionId);
  90. }
  91. function bindV2AgentRuntimeManagementPort(
  92. agentRuntimePort: DeferredLocalAgentRuntimePort,
  93. ownerRuntime: InitializedOwnerRuntime,
  94. agentOwner: AgentRuntimeOwner,
  95. ): void {
  96. agentRuntimePort.bindManagement(
  97. createV2AgentRuntimeManagementPort({
  98. application: ownerRuntime.services.agent,
  99. service: agentOwner.service,
  100. readSessionAgentRouting: (sessionId) =>
  101. ownerRuntime.services.sessionSystem.sessions.records.readSessionAgentRouting(
  102. sessionId,
  103. ),
  104. resolveSessionProjectIdentity: (sessionId) =>
  105. ownerRuntime.services.sessionSystem.projects.service.resolveSessionProjectIdentity(
  106. sessionId,
  107. ),
  108. }),
  109. );
  110. }
  111. async function createLocalRuntimeHostV2Internal(
  112. options: LocalRuntimeProductHostOptions,
  113. overrides: LocalRuntimeV2TestOverrides,
  114. ): Promise<CreatedLocalRuntimeHost> {
  115. const compatibility = createV1Compatibility(isV2RuntimeOwner(options));
  116. let agentOwner: AgentRuntimeOwner | undefined;
  117. let v1: V1CreatedLocalRuntimeHost | undefined;
  118. let legacyClose: (() => Promise<void>) | undefined;
  119. let ownerRuntime: InitializedOwnerRuntime | undefined;
  120. const agentRuntimePort: DeferredLocalAgentRuntimePort =
  121. createDeferredLocalAgentRuntimePort();
  122. const sandboxOperationsFactory =
  123. createDeferredLocalSandboxBashOperationsFactory(
  124. () => options.configGetter?.().sandbox?.enabled ?? false,
  125. resolveAgentBashEnvPolicy(options.dataDir),
  126. );
  127. const agentTelemetry = createDeferredAgentRuntimeTelemetry();
  128. let database: DatabaseClient | undefined;
  129. let preparedServices: PreparedRuntimeServices | undefined;
  130. const startupStartedAtMs = Date.now();
  131. const stageTimings: Record<string, number> = {};
  132. const measureStage = <T>(stage: string, run: () => T): T => {
  133. const stageStartedAtMs = Date.now();
  134. try {
  135. return run();
  136. } finally {
  137. stageTimings[stage] = Math.max(0, Date.now() - stageStartedAtMs);
  138. }
  139. };
  140. const measureStageAsync = async <T>(
  141. stage: string,
  142. run: () => Promise<T>,
  143. ): Promise<T> => {
  144. const stageStartedAtMs = Date.now();
  145. try {
  146. return await run();
  147. } finally {
  148. stageTimings[stage] = Math.max(0, Date.now() - stageStartedAtMs);
  149. }
  150. };
  151. try {
  152. // 2026-09-03: the startup generation checkpoint (whole-dataDir copy +
  153. // fingerprint verification for the manual `generation rollback` CLI) was
  154. // removed from the boot path entirely. Layout migration is additive and
  155. // schema migration keeps its own SQLite backup, so the extra whole-tree
  156. // snapshot bought nothing while costing large IO on every cold start
  157. // (a 17G dataDir starved the 600s bootstrap watchdog six times in a row).
  158. // The rootless-v2-generation module remains for the CLI, which acquires
  159. // its own operation fence.
  160. // Layout migration must complete before the authoritative V2 target is
  161. // opened. The services composition below gates all legacy access on the
  162. // target Agent row count.
  163. const completedLayoutMigration = measureStage("layout_migration_ms", () =>
  164. ensureCurrentLocalRuntimeDataMigratedToV2OrThrow(
  165. () => options.dataDir,
  166. options.nowMs,
  167. ),
  168. );
  169. database = measureStage(
  170. "db_open_ms",
  171. () =>
  172. new DatabaseClient({
  173. dataDir: options.dataDir,
  174. ...(overrides.database?.sqlite3ModulePath
  175. ? { sqlite3ModulePath: overrides.database.sqlite3ModulePath }
  176. : {}),
  177. }),
  178. );
  179. const resolvedDatabase = database;
  180. const initialization = await measureStageAsync("db_initialize_ms", () =>
  181. initializeDatabase({
  182. database: resolvedDatabase,
  183. dataDir: options.dataDir,
  184. onMigration: options.onDatabaseMigration,
  185. }),
  186. );
  187. reportLegacySessionRecovery({
  188. recoveredLegacySessionCount: initialization.recoveredLegacySessionCount,
  189. degradedLegacySessionCount: initialization.degradedLegacySessionCount,
  190. });
  191. reportProjectMigrationRecovery({
  192. recoveredProjectPreferenceCount:
  193. initialization.recoveredProjectPreferenceCount,
  194. skippedSessionProjectRepairCount:
  195. initialization.skippedSessionProjectRepairCount,
  196. });
  197. agentOwner = await measureStageAsync("agent_composition_ms", () =>
  198. createRuntimeAgentComposition({
  199. db: resolvedDatabase.db,
  200. dataDir: options.dataDir,
  201. ...(options.promptMode
  202. ? {
  203. promptMode: options.promptMode,
  204. promptVersion: options.appVersion,
  205. }
  206. : {}),
  207. ...(options.nowMs ? { nowMs: options.nowMs } : {}),
  208. withAgentStorageLock: (operation) =>
  209. withAgentStorageLock(options.dataDir, operation),
  210. reportCutover: reportAgentCutover,
  211. reportIdentityDetach: reportAgentIdentityDetach,
  212. reportLegacyCustomMaterialization:
  213. reportLegacyCustomAgentMaterialization,
  214. facts: agentTelemetry.facts,
  215. }),
  216. );
  217. agentRuntimePort.bindResolver(agentOwner.service);
  218. preparedServices = compatibility
  219. ? prepareRuntimeServices({
  220. db: database.db,
  221. runtimeOwnerKind: options.runtimeOwnerKind,
  222. })
  223. : undefined;
  224. const configuredOptions = configureV1HostOptions(
  225. options,
  226. compatibility,
  227. agentRuntimePort,
  228. {
  229. sandboxOperationsFactory,
  230. prepared: preparedServices,
  231. },
  232. );
  233. Object.defineProperty(
  234. configuredOptions,
  235. V2_LAYOUT_MIGRATION_RECEIPT_CARRIER,
  236. {
  237. value: completedLayoutMigration,
  238. enumerable: false,
  239. configurable: false,
  240. writable: false,
  241. },
  242. );
  243. v1 = createLocalRuntimeHostV1(configuredOptions);
  244. const resolvedV1 = v1;
  245. agentTelemetry.bind({
  246. metricsClient: resolvedV1.metricsClient,
  247. emitBusEvent: (type, payload) =>
  248. resolvedV1.apiHost.emitBusEvent(type, payload),
  249. });
  250. legacyClose = v1.apiHost.close.bind(v1.apiHost);
  251. await measureStageAsync("v1_host_ready_ms", async () => resolvedV1.ready);
  252. if (compatibility) {
  253. if (!preparedServices)
  254. throw new Error("V2 owner services were not prepared");
  255. const resolvedPreparedServices = preparedServices;
  256. const resolvedAgentOwner = agentOwner;
  257. ownerRuntime = await measureStageAsync("owner_runtime_ms", () =>
  258. initializeOwnerRuntime({
  259. v1: resolvedV1,
  260. compatibility,
  261. agentOwner: resolvedAgentOwner,
  262. database: resolvedDatabase,
  263. sandboxOperationsFactory,
  264. prepared: resolvedPreparedServices,
  265. disabledLegacyScheduleCount:
  266. initialization.disabledLegacyScheduleCount,
  267. options,
  268. overrides,
  269. }),
  270. );
  271. ownerRuntime.background.registerMaintenance(
  272. "migration-backup-retention",
  273. async () => initialization.pruneBackups?.(),
  274. );
  275. bindV2AgentRuntimeManagementPort(
  276. agentRuntimePort,
  277. ownerRuntime,
  278. agentOwner,
  279. );
  280. bindV2AgentLifecycle(v1.apiHost, ownerRuntime.services.agent);
  281. // Decision v3: late-bind the ask_user suppression probe now that the
  282. // V2 Turn system exists. V1-only hosts (and partial test graphs) keep
  283. // the probe unset, which means never suppress.
  284. bindAskUserSuppressionProbe(v1.apiHost, ownerRuntime.services.turnSystem);
  285. }
  286. const cliService = ownerRuntime
  287. ? createCliService(ownerRuntime.services)
  288. : undefined;
  289. const close = createSharedClose({
  290. ownerRuntime,
  291. closeV1: legacyClose,
  292. agentOwner,
  293. agentTelemetry,
  294. v1,
  295. database,
  296. });
  297. const ownerCompromiseGuard = createRuntimeOwnerCompromiseGuard(
  298. ownerRuntime,
  299. close,
  300. );
  301. ownerCompromiseGuard.assertHealthy();
  302. v1.apiHost.close = close;
  303. // A fresh profile has no primary Agent row until the detached builtin recovery
  304. // completes. Gate owner channels on that milestone without making either
  305. // builtin or Channel recovery part of core Runtime readiness.
  306. const channelStartupStartedAtMs = Date.now();
  307. const channelStartup = startChannelSubsystemAfterOwnerAgentDefinitions(
  308. ownerRuntime,
  309. resolvedV1.apiHost,
  310. ownerRuntime
  311. ? () =>
  312. reportDetachedOwnerChannelStartupTiming(
  313. startupStartedAtMs,
  314. channelStartupStartedAtMs,
  315. stageTimings,
  316. initialization,
  317. )
  318. : undefined,
  319. );
  320. if (!ownerRuntime) {
  321. // Legacy/non-owner hosts retain their established fail-closed startup contract.
  322. try {
  323. await measureStageAsync("channel_startup_ms", () => channelStartup);
  324. } catch (error) {
  325. reportStartupTimings({
  326. totalMs: Math.max(0, Date.now() - startupStartedAtMs),
  327. stages: stageTimings,
  328. initialization,
  329. outcome: "failed",
  330. });
  331. throw error;
  332. }
  333. reportStartupTimings({
  334. totalMs: Math.max(0, Date.now() - startupStartedAtMs),
  335. stages: stageTimings,
  336. initialization,
  337. outcome: "ready",
  338. });
  339. }
  340. ownerCompromiseGuard.publish();
  341. ownerRuntime?.background.startMaintenance();
  342. return createStartedHost(v1, ownerRuntime, cliService, v1.ready);
  343. } catch (error) {
  344. compatibility?.failConversation(error);
  345. await cleanupFailedStartup({
  346. ownerRuntime,
  347. v1,
  348. closeV1: legacyClose,
  349. agentOwner,
  350. agentTelemetry,
  351. database,
  352. });
  353. throw error;
  354. }
  355. }
  356. function createV1Compatibility(
  357. ownsV2Runtime: boolean,
  358. ): V1RuntimeCompatibility | undefined {
  359. if (!ownsV2Runtime) return undefined;
  360. return createV1RuntimeCompatibility(new DeferredRuntimeConversation(), {
  361. createQuestionnaireService: (host) =>
  362. new LocalQuestionnaireService(host.apiHost.questionnaireServiceDeps()),
  363. });
  364. }
  365. async function startChannelSubsystemAfterOwnerAgentDefinitions(
  366. ownerRuntime: InitializedOwnerRuntime | undefined,
  367. apiHost: V1CreatedLocalRuntimeHost["apiHost"],
  368. onOwnerChannelStartupSettled?: () => void,
  369. ): Promise<void> {
  370. try {
  371. if (
  372. ownerRuntime &&
  373. !(await ownerRuntime.services.builtinAgentDefinitionsReady)
  374. )
  375. return;
  376. await apiHost.startChannelSubsystem();
  377. } catch (error) {
  378. if (!ownerRuntime) throw error;
  379. try {
  380. logger.error(
  381. {
  382. event: "rootless_im_startup_detached_rejected",
  383. error_code: runtimeOwnerErrorCode(error),
  384. },
  385. "Detached Rootless IM startup rejected after core Runtime became ready",
  386. );
  387. } catch {
  388. // Channel-only diagnostics cannot compromise an otherwise ready Runtime.
  389. }
  390. } finally {
  391. if (ownerRuntime) onOwnerChannelStartupSettled?.();
  392. }
  393. }
  394. function reportDetachedOwnerChannelStartupTiming(
  395. startupStartedAtMs: number,
  396. channelStartupStartedAtMs: number,
  397. stageTimings: Record<string, number>,
  398. initialization: DatabaseInitializationResult,
  399. ): void {
  400. stageTimings.channel_startup_ms = Math.max(
  401. 0,
  402. Date.now() - channelStartupStartedAtMs,
  403. );
  404. reportStartupTimings({
  405. totalMs: Math.max(0, Date.now() - startupStartedAtMs),
  406. stages: stageTimings,
  407. initialization,
  408. outcome: "ready",
  409. });
  410. }
  411. function createStartedHost(
  412. v1: V1CreatedLocalRuntimeHost,
  413. ownerRuntime: InitializedOwnerRuntime | undefined,
  414. cliService: ReturnType<typeof createCliService> | undefined,
  415. ready: Promise<void>,
  416. ): CreatedLocalRuntimeHost {
  417. return {
  418. ...v1,
  419. ...(ownerRuntime ? { application: ownerRuntime.services.application } : {}),
  420. ...(cliService ? { cliService } : {}),
  421. apiHost: v1.apiHost,
  422. ready,
  423. ...(ownerRuntime
  424. ? {
  425. notifyAuthContextChanged: (authState) =>
  426. ownerRuntime.services.notifyAuthContextChanged(authState),
  427. }
  428. : {}),
  429. };
  430. }
  431. interface RuntimeOwnerCompromiseGuard {
  432. assertHealthy(): void;
  433. publish(): void;
  434. }
  435. function createRuntimeOwnerCompromiseGuard(
  436. ownerRuntime: InitializedOwnerRuntime | undefined,
  437. close: () => Promise<void>,
  438. ): RuntimeOwnerCompromiseGuard {
  439. const identity = ownerRuntime?.background.clients.runtimeOwnerIdentity;
  440. if (!identity)
  441. return { assertHealthy: () => undefined, publish: () => undefined };
  442. let published = false;
  443. let startupFailure: Error | undefined;
  444. let compromiseClose: Promise<void> | undefined;
  445. const unsubscribe = identity.onCompromised((error) => {
  446. if (!published) {
  447. startupFailure ??= error;
  448. return;
  449. }
  450. compromiseClose ??= closeCompromisedRuntime(
  451. identity.instanceId,
  452. error,
  453. close,
  454. );
  455. });
  456. const assertHealthy = (): void => {
  457. if (!startupFailure) return;
  458. unsubscribe();
  459. throw startupFailure;
  460. };
  461. return {
  462. assertHealthy,
  463. publish: () => {
  464. assertHealthy();
  465. published = true;
  466. },
  467. };
  468. }
  469. async function closeCompromisedRuntime(
  470. instanceId: string,
  471. error: Error,
  472. close: () => Promise<void>,
  473. ): Promise<void> {
  474. logger.error(
  475. {
  476. event: "runtime_owner_lease_compromised",
  477. instance_id: instanceId,
  478. error_code: runtimeOwnerErrorCode(error),
  479. },
  480. "V2 Runtime owner lease compromised; closing Runtime",
  481. );
  482. try {
  483. await close();
  484. } catch (closeError: unknown) {
  485. logger.error(
  486. {
  487. event: "runtime_owner_compromise_close_failed",
  488. instance_id: instanceId,
  489. error_code: runtimeOwnerErrorCode(closeError),
  490. },
  491. "V2 Runtime failed to close after owner lease compromise",
  492. );
  493. }
  494. }
  495. function runtimeOwnerErrorCode(error: unknown): string {
  496. if (!error || typeof error !== "object" || !("code" in error))
  497. return "UNKNOWN";
  498. const code = error.code;
  499. return typeof code === "string" && code.length > 0 ? code : "UNKNOWN";
  500. }
  501. function isV2RuntimeOwner(options: CreateLocalRuntimeHostOptions): boolean {
  502. return (
  503. (options.runtimeOwnerKind === "electron" &&
  504. options.capabilities?.electronHost === true) ||
  505. ((options.runtimeOwnerKind === "cli" ||
  506. options.runtimeOwnerKind === "tui") &&
  507. options.capabilities?.cliEmbedded === true)
  508. );
  509. }
  510. export { createLocalRuntimeHostV2 as createLocalRuntimeHost };
  511. /**
  512. * Emits one structured line accounting for every blocking startup stage.
  513. *
  514. * Restart latency after an update install is dominated by this path, and until
  515. * now the only local evidence was the gap between unrelated log lines. The line
  516. * is always emitted — including the fast no-migration case — so a slow start can
  517. * be compared against a normal one instead of only being visible when it hurts.
  518. *
  519. * `outcome` distinguishes a runtime that actually reached readiness from one
  520. * that died during channel startup, so a failed restart is never mistaken for a
  521. * fast one.
  522. */
  523. function reportStartupTimings(input: {
  524. readonly totalMs: number;
  525. readonly stages: Readonly<Record<string, number>>;
  526. readonly initialization: DatabaseInitializationResult;
  527. readonly outcome: "ready" | "failed";
  528. }): void {
  529. const { backup, pendingVersions, timings } = input.initialization;
  530. try {
  531. logger.info(
  532. {
  533. outcome: input.outcome,
  534. total_ms: input.totalMs,
  535. ...input.stages,
  536. ...(timings
  537. ? {
  538. db_initialize_backup_ms: timings.backupMs,
  539. db_initialize_migrations_ms: timings.migrationsMs,
  540. db_initialize_schema_check_ms: timings.schemaCheckMs,
  541. }
  542. : {}),
  543. pending_migration_count: pendingVersions?.length ?? 0,
  544. ...(pendingVersions && pendingVersions.length > 0
  545. ? { pending_migration_versions: pendingVersions }
  546. : {}),
  547. backup_created: backup?.created === true,
  548. ...(backup?.created
  549. ? {
  550. backup_copy_ms: backup.backupMs,
  551. backup_integrity_ms: backup.integrityMs,
  552. ...(backup.sizeBytes === undefined
  553. ? {}
  554. : { backup_size_bytes: backup.sizeBytes }),
  555. }
  556. : {}),
  557. },
  558. "local-runtime-v2 startup timings",
  559. );
  560. } catch {
  561. // Startup diagnostics are strictly observational: never let a malformed or
  562. // partially populated initialization result prevent the runtime from
  563. // starting.
  564. }
  565. }
  566. function reportLegacySessionRecovery(result: {
  567. readonly recoveredLegacySessionCount: number;
  568. readonly degradedLegacySessionCount: number;
  569. }): void {
  570. if (
  571. result.recoveredLegacySessionCount <= 0 &&
  572. result.degradedLegacySessionCount <= 0
  573. )
  574. return;
  575. logger.warn(
  576. result,
  577. "local-runtime-v2 recovered or degraded malformed Session records before migration",
  578. );
  579. }
  580. function reportProjectMigrationRecovery(result: {
  581. readonly recoveredProjectPreferenceCount: number;
  582. readonly skippedSessionProjectRepairCount: number;
  583. }): void {
  584. if (
  585. result.recoveredProjectPreferenceCount <= 0 &&
  586. result.skippedSessionProjectRepairCount <= 0
  587. ) {
  588. return;
  589. }
  590. logger.warn(
  591. result,
  592. "local-runtime-v2 skipped malformed Project migration data",
  593. );
  594. }
  595. function reportAgentCutover(event: AgentCutoverLogEvent): void {
  596. const fields = {
  597. migration_id: event.migrationId,
  598. ...(event.collisionMigrationId
  599. ? { collision_migration_id: event.collisionMigrationId }
  600. : {}),
  601. phase: event.phase,
  602. status: event.status,
  603. source_kind: event.sourceKind,
  604. target_kind: event.targetKind,
  605. conflict_count: event.conflictCount,
  606. mapping: event.mapping,
  607. reference_counts: event.referenceCounts,
  608. source_row_count: event.sourceRowCount,
  609. imported_row_count: event.importedRowCount,
  610. recovered_timestamp_count: event.recoveredTimestampCount,
  611. recoveries: event.recoveries,
  612. target_row_count: event.targetRowCount,
  613. duration_ms: event.durationMs,
  614. ...(event.failureStep ? { failure_step: event.failureStep } : {}),
  615. ...(event.secondaryFailureStep
  616. ? { secondary_failure_step: event.secondaryFailureStep }
  617. : {}),
  618. ...(event.skipCode ? { skip_code: event.skipCode } : {}),
  619. ...(event.errorCode ? { error_code: event.errorCode } : {}),
  620. };
  621. if (event.status === "failed") {
  622. logger.error(fields, "V2 Agent cutover failed");
  623. return;
  624. }
  625. logger.info(fields, "V2 Agent cutover");
  626. }
  627. /**
  628. * Startup-only detached-identity record. The fields are deliberately bounded:
  629. * no Persona, Prompt, Memory, credential, avatar URL, or error text reaches
  630. * runtime logs.
  631. */
  632. function reportAgentIdentityDetach(event: LegacyIdentityDetachEvent): void {
  633. const fields = {
  634. event: "legacy_builtin_identity_detach",
  635. agent_name: event.agentName,
  636. phase: event.phase,
  637. outcome: event.outcome,
  638. ...(event.asset ? { asset: event.asset } : {}),
  639. ...(event.action ? { action: event.action } : {}),
  640. ...(event.avatarDecision ? { avatar_decision: event.avatarDecision } : {}),
  641. };
  642. if (event.outcome === "failed") {
  643. logger.error(fields, "V2 Agent identity detach failed");
  644. return;
  645. }
  646. logger.info(fields, "V2 Agent identity detach");
  647. }
  648. function reportLegacyCustomAgentMaterialization(
  649. event: LegacyCustomAgentMaterializationEvent,
  650. ): void {
  651. if (event.kind === "summary") {
  652. reportLegacyCustomAgentMaterializationSummary(event);
  653. return;
  654. }
  655. reportLegacyCustomAgentMaterializationAgent(event);
  656. }
  657. function reportLegacyCustomAgentMaterializationSummary(
  658. event: Extract<
  659. LegacyCustomAgentMaterializationEvent,
  660. { readonly kind: "summary" }
  661. >,
  662. ): void {
  663. const fields = {
  664. event: "legacy_custom_agent_materialization_summary",
  665. materialized: event.materialized,
  666. canonical_identity_reconciled: event.canonicalIdentityReconciled,
  667. already_canonical: event.alreadyCanonical,
  668. not_legacy: event.notLegacy,
  669. invalid: event.invalid,
  670. failed: event.failed,
  671. receipt_completed: event.receiptCompleted,
  672. };
  673. if (event.invalid > 0 || event.failed > 0) {
  674. logger.warn(fields, "V2 legacy Custom Agent materialization incomplete");
  675. return;
  676. }
  677. logger.info(fields, "V2 legacy Custom Agent materialization summary");
  678. }
  679. function reportLegacyCustomAgentMaterializationAgent(
  680. event: Extract<
  681. LegacyCustomAgentMaterializationEvent,
  682. { readonly kind: "agent" }
  683. >,
  684. ): void {
  685. const deferred = event.outcome === "invalid" || event.outcome === "failed";
  686. const fields = {
  687. event: deferred
  688. ? "legacy_custom_agent_materialization_deferred"
  689. : "legacy_custom_agent_materialization",
  690. agent_name: event.agentName,
  691. outcome: event.outcome,
  692. identity_source: event.identitySource,
  693. recovered_fields: event.recoveredFields,
  694. ...(event.errorCode ? { error_code: event.errorCode } : {}),
  695. ...(event.stage ? { stage: event.stage } : {}),
  696. ...(event.reason ? { reason: event.reason } : {}),
  697. };
  698. if (deferred) {
  699. logger.warn(fields, "V2 legacy Custom Agent materialization deferred");
  700. return;
  701. }
  702. logger.info(fields, "V2 legacy Custom Agent materialization");
  703. }
  704. function configureV1HostOptions(
  705. options: LocalRuntimeProductHostOptions,
  706. compatibility: V1RuntimeCompatibility | undefined,
  707. agentRuntimePort: DeferredLocalAgentRuntimePort,
  708. owners: {
  709. readonly sandboxOperationsFactory: DeferredLocalSandboxBashOperationsFactory;
  710. readonly prepared: PreparedRuntimeServices | undefined;
  711. },
  712. ): CreateLocalRuntimeHostOptions {
  713. const { sandboxOperationsFactory, prepared } = owners;
  714. const {
  715. browserAdapter,
  716. browserToolExposure,
  717. promptConfigKey,
  718. promptMode,
  719. ...v1Options
  720. } = options;
  721. void browserAdapter;
  722. void browserToolExposure;
  723. void promptConfigKey;
  724. void promptMode;
  725. // V2 owns the channel startup point: the V1 shell must build stores, APIs,
  726. // runner and registries without restoring a single transport.
  727. if (compatibility) {
  728. if (!prepared)
  729. throw new Error(
  730. "V2 owner services were not prepared before V1 construction",
  731. );
  732. return {
  733. ...compatibility.configureHostOptions(
  734. { ...v1Options, agentRuntimePort, sandboxOperationsFactory },
  735. agentRuntimePort,
  736. prepared.v1,
  737. ),
  738. deferChannelStartup: true,
  739. };
  740. }
  741. return {
  742. ...v1Options,
  743. agentResolver: agentRuntimePort,
  744. agentRuntimePort,
  745. sandboxOperationsFactory,
  746. deferChannelStartup: true,
  747. };
  748. }
  749. function bindV2AgentLifecycle(
  750. apiHost: V1CreatedLocalRuntimeHost["apiHost"],
  751. agent: RuntimeServices["agent"],
  752. ): void {
  753. apiHost.ensureBuiltinAgents = async () => {
  754. await agent.ensureBuiltinDefinitionsForPhase2();
  755. };
  756. apiHost.retryBuiltinGreetings = () => Promise.resolve();
  757. }
  758. function createBrowserUseServiceOptions(
  759. options: CreateLocalRuntimeHostOptions,
  760. ): NonNullable<CreateRuntimeServicesOptions["browserUse"]> {
  761. return {
  762. ...(options.browserAdapter ? { adapter: options.browserAdapter } : {}),
  763. ...(options.browserToolExposure
  764. ? { toolExposure: options.browserToolExposure }
  765. : {}),
  766. };
  767. }
  768. async function initializeOwnerRuntime(input: {
  769. readonly v1: V1CreatedLocalRuntimeHost;
  770. readonly compatibility: V1RuntimeCompatibility;
  771. readonly agentOwner: AgentRuntimeOwner;
  772. readonly database: DatabaseClient;
  773. readonly prepared: PreparedRuntimeServices;
  774. readonly disabledLegacyScheduleCount: number;
  775. readonly options: CreateLocalRuntimeHostOptions;
  776. readonly overrides: LocalRuntimeV2TestOverrides;
  777. readonly sandboxOperationsFactory: DeferredLocalSandboxBashOperationsFactory;
  778. }): Promise<InitializedOwnerRuntime> {
  779. const {
  780. v1,
  781. compatibility,
  782. agentOwner,
  783. database,
  784. prepared,
  785. options,
  786. overrides,
  787. sandboxOperationsFactory,
  788. } = input;
  789. let background: BackgroundRuntime | undefined;
  790. let services: RuntimeServices | undefined;
  791. try {
  792. const startupExecutionEnabled = isLocalRuntimeStartupExecutionEnabled(
  793. options.startupExecutionPolicy,
  794. );
  795. const electronOwner = options.runtimeOwnerKind === "electron";
  796. background = await createBackgroundRuntime({
  797. db: database.db,
  798. dataDir: v1.dataDir,
  799. logger,
  800. metrics: v1.metricsClient,
  801. ...(options.nowMs ? { nowMs: options.nowMs } : {}),
  802. restorePersistedJobExecution: startupExecutionEnabled,
  803. enableScheduler: electronOwner,
  804. });
  805. services = await createRuntimeServices({
  806. db: database.db,
  807. dataDir: v1.dataDir,
  808. logger,
  809. ...(background.clients.scheduler
  810. ? { scheduler: background.clients.scheduler }
  811. : {}),
  812. metrics: v1.metricsClient,
  813. eventBus: background.clients.eventBus,
  814. forkWorktree: background.clients.forkWorktree,
  815. compatibility: {
  816. create: () => compatibility.createServiceCompatibility(v1, options),
  817. },
  818. prepared,
  819. agentService: agentOwner.service,
  820. promptFileReader: agentOwner.promptFileReader,
  821. ...(options.configSource ? { configSource: options.configSource } : {}),
  822. ...(options.nowMs ? { nowMs: options.nowMs } : {}),
  823. recoverPersistedState: startupExecutionEnabled,
  824. greetingEnabled: electronOwner && startupExecutionEnabled,
  825. runtimeOwnerKind: options.runtimeOwnerKind,
  826. browserUse: createBrowserUseServiceOptions(options),
  827. ...(options.promptConfigKey
  828. ? { promptConfigKey: options.promptConfigKey }
  829. : {}),
  830. capabilityProfile: options.capabilityProfile,
  831. getRunawayGuardConfig: options.getRunawayGuardConfig,
  832. ...(options.getToolResultCompactionConfig
  833. ? {
  834. getToolResultCompactionConfig:
  835. options.getToolResultCompactionConfig,
  836. }
  837. : {}),
  838. runtimeOwnerIdentity: background.clients.runtimeOwnerIdentity,
  839. sandboxOperationsFactory,
  840. ...sandboxRuntimeOptions(options),
  841. ...(overrides.services ? { overrides: overrides.services } : {}),
  842. });
  843. const ownedServices = services;
  844. background.registerMaintenance("turn-diff-retention", () =>
  845. ownedServices.sessionSystem.runStorageMaintenance(),
  846. );
  847. await background.start();
  848. await services.ready();
  849. return {
  850. database,
  851. background,
  852. services,
  853. disabledLegacyScheduleCount: input.disabledLegacyScheduleCount,
  854. };
  855. } catch (error) {
  856. await closeOwnerResources(background, services, "startup cleanup");
  857. throw error;
  858. }
  859. }
  860. function sandboxRuntimeOptions(
  861. options: CreateLocalRuntimeHostOptions,
  862. ): Pick<Parameters<typeof createRuntimeServices>[0], "sandboxConfig"> {
  863. const sandboxConfig = options.configGetter?.().sandbox;
  864. return sandboxConfig ? { sandboxConfig } : {};
  865. }
  866. interface RuntimeResourceState {
  867. readonly ownerRuntime: InitializedOwnerRuntime | undefined;
  868. readonly closeV1: (() => Promise<void>) | undefined;
  869. readonly agentOwner: AgentRuntimeOwner | undefined;
  870. readonly agentTelemetry: { close(): void };
  871. readonly v1: V1CreatedLocalRuntimeHost | undefined;
  872. readonly database: DatabaseClient | undefined;
  873. }
  874. function createSharedClose(state: RuntimeResourceState): () => Promise<void> {
  875. let closePromise: Promise<void> | undefined;
  876. return () => {
  877. if (!closePromise) {
  878. state.v1?.apiHost.beginShutdown();
  879. closePromise = closeRuntime(state);
  880. }
  881. return closePromise;
  882. };
  883. }
  884. async function closeRuntime({
  885. ownerRuntime,
  886. closeV1,
  887. agentOwner,
  888. agentTelemetry,
  889. v1,
  890. database,
  891. }: RuntimeResourceState): Promise<void> {
  892. let firstError: unknown;
  893. await stopV1Producers(v1, (error) => {
  894. firstError ??= error;
  895. });
  896. await closeOwnerResources(
  897. ownerRuntime?.background,
  898. ownerRuntime?.services,
  899. "close",
  900. (error) => {
  901. firstError ??= error;
  902. },
  903. );
  904. try {
  905. agentTelemetry.close();
  906. } catch (error) {
  907. firstError ??= error;
  908. }
  909. try {
  910. agentOwner?.close();
  911. } catch (error) {
  912. firstError ??= error;
  913. }
  914. try {
  915. await closeV1?.();
  916. } catch (error) {
  917. firstError ??= error;
  918. }
  919. try {
  920. database?.close();
  921. } catch (error) {
  922. firstError ??= error;
  923. }
  924. if (firstError !== undefined) throw firstError;
  925. }
  926. async function closeOwnerResources(
  927. background: BackgroundRuntime | undefined,
  928. services: RuntimeServices | undefined,
  929. operation: "startup cleanup" | "close",
  930. recordError?: (error: unknown) => void,
  931. ): Promise<void> {
  932. const steps: Array<[string, () => void | Promise<void>]> = [
  933. ["stop_background", () => background?.stop()],
  934. ["close_services", () => services?.close()],
  935. ["close_background", () => background?.close()],
  936. ];
  937. for (const [cleanupStep, step] of steps) {
  938. try {
  939. await step();
  940. } catch (err) {
  941. recordError?.(err);
  942. try {
  943. logger.warn(
  944. { cleanupStep, err },
  945. `local-runtime-v2 ${operation} failed`,
  946. );
  947. } catch {
  948. // Resource cleanup and the original runtime failure remain primary.
  949. }
  950. }
  951. }
  952. }
  953. async function cleanupFailedStartup({
  954. ownerRuntime,
  955. v1,
  956. closeV1,
  957. agentOwner,
  958. agentTelemetry,
  959. database,
  960. }: RuntimeResourceState): Promise<void> {
  961. await stopV1Producers(v1, (error) => {
  962. try {
  963. logger.warn(
  964. { cleanupStep: "stop_v1_producers", err: error },
  965. "local-runtime-v2 startup cleanup failed",
  966. );
  967. } catch {
  968. // Continue cleanup.
  969. }
  970. });
  971. await closeOwnerResources(
  972. ownerRuntime?.background,
  973. ownerRuntime?.services,
  974. "startup cleanup",
  975. );
  976. try {
  977. agentTelemetry.close();
  978. } catch (error) {
  979. try {
  980. logger.warn(
  981. { cleanupStep: "close_agent_telemetry", err: error },
  982. "local-runtime-v2 startup cleanup failed",
  983. );
  984. } catch {
  985. // Continue cleanup.
  986. }
  987. }
  988. try {
  989. agentOwner?.close();
  990. } catch (error) {
  991. try {
  992. logger.warn(
  993. { cleanupStep: "close_agent_owner", err: error },
  994. "local-runtime-v2 startup cleanup failed",
  995. );
  996. } catch {
  997. // Keep running cleanup even when reporting the owner failure fails.
  998. }
  999. }
  1000. await cleanupFailedV1Startup(v1, closeV1, (cleanupStep, err) => {
  1001. try {
  1002. logger.warn(
  1003. { cleanupStep, err },
  1004. "local-runtime-v2 startup cleanup failed",
  1005. );
  1006. } catch {
  1007. // Continue cleanup even when reporting itself fails.
  1008. }
  1009. });
  1010. try {
  1011. database?.close();
  1012. } catch (error) {
  1013. try {
  1014. logger.warn(
  1015. { cleanupStep: "close_database", err: error },
  1016. "local-runtime-v2 startup cleanup failed",
  1017. );
  1018. } catch {
  1019. // Continue cleanup.
  1020. }
  1021. }
  1022. }
  1023. async function stopV1Producers(
  1024. v1: V1CreatedLocalRuntimeHost | undefined,
  1025. recordError: (error: unknown) => void,
  1026. ): Promise<void> {
  1027. const steps: Array<() => void | Promise<void>> = [
  1028. () => v1?.apiHost.cronRuntime.stop(),
  1029. () => v1?.apiHost.shutdownChannelSubsystem(),
  1030. ];
  1031. for (const step of steps) {
  1032. try {
  1033. await step();
  1034. } catch (error) {
  1035. recordError(error);
  1036. }
  1037. }
  1038. }