@awebai/oats 0.69.23 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/bin/oats.mjs +112 -20
  2. package/docs/capabilities.md +697 -11
  3. package/docs/capability-manifest.schema.json +66 -0
  4. package/docs/configuration.md +27 -7
  5. package/docs/design/2026-11-19-sandboxes.md +595 -121
  6. package/docs/design/2026-11-20-provider-home-lifecycle.md +322 -0
  7. package/docs/design/README.md +7 -3
  8. package/docs/desktop-cli-api.md +330 -9
  9. package/docs/desktop.md +181 -48
  10. package/docs/execution-targets.md +210 -4
  11. package/docs/first-team.md +11 -0
  12. package/docs/implementation.md +24 -3
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge-capability-authoring.md +1 -1
  15. package/docs/knowledge-reference/proposal.md +10 -0
  16. package/docs/knowledge.md +20 -11
  17. package/docs/official-catalog.md +2 -2
  18. package/docs/packages.md +7 -7
  19. package/docs/release-notes/v0.69.24.md +264 -0
  20. package/docs/release-notes/v0.70.0.md +155 -0
  21. package/docs/souls-and-instances.md +57 -0
  22. package/docs/trust-model.md +8 -1
  23. package/docs/tui.md +21 -1
  24. package/docs/upgrading.md +19 -5
  25. package/docs/workspaces.md +13 -5
  26. package/lib/automation-scope.mjs +1 -1
  27. package/lib/capability-show.mjs +20 -1
  28. package/lib/command-flags.mjs +2 -2
  29. package/lib/compile-cache.mjs +1 -1
  30. package/lib/core.mjs +1455 -203
  31. package/lib/errors.mjs +4 -1
  32. package/lib/home-integrity.mjs +329 -0
  33. package/lib/hook-env.mjs +107 -0
  34. package/lib/host-run.mjs +11 -3
  35. package/lib/instance-events.mjs +32 -5
  36. package/lib/instance-git.mjs +9 -0
  37. package/lib/instance-inspect.mjs +107 -9
  38. package/lib/instance-lifecycle.mjs +15 -3
  39. package/lib/instance-listing.mjs +101 -8
  40. package/lib/instance-resolution.mjs +85 -2
  41. package/lib/instance-upgrade.mjs +170 -14
  42. package/lib/kernel-features.mjs +10 -1
  43. package/lib/node-version.mjs +9 -0
  44. package/lib/provider-call-child.mjs +60 -0
  45. package/lib/provider-resume.mjs +83 -0
  46. package/lib/provider-test-seams.mjs +20 -0
  47. package/lib/read-call.mjs +2 -0
  48. package/lib/remote.mjs +33 -1
  49. package/lib/reserved-launch-env.mjs +8 -1
  50. package/lib/retire-admission.mjs +12 -1
  51. package/lib/sandbox-allowances.mjs +329 -0
  52. package/lib/schedule.mjs +14 -4
  53. package/lib/servers.mjs +38 -5
  54. package/lib/session-inspect.mjs +123 -87
  55. package/lib/session-providers.mjs +575 -0
  56. package/lib/session-receipt.mjs +93 -0
  57. package/lib/session-resume.mjs +68 -15
  58. package/lib/stable-node.mjs +3 -0
  59. package/lib/triggers.mjs +3 -1
  60. package/lib/upgrade-state.mjs +6 -1
  61. package/lib/worktree-hooks.mjs +18 -2
  62. package/lib/worktree.mjs +21 -7
  63. package/package-catalog.json +2 -2
  64. package/package.json +2 -1
  65. package/packages/client/capability-list.mjs +21 -0
  66. package/packages/client/cli-adapter.mjs +19 -4
  67. package/packages/client/cli-locator.mjs +5 -1
  68. package/packages/client/deployment-data.mjs +23 -1
  69. package/packages/client/deployment-panel.mjs +25 -3
  70. package/packages/client/home-board.mjs +33 -19
  71. package/packages/client/inspect-boundary.mjs +18 -8
  72. package/packages/client/instance-acts.mjs +30 -3
  73. package/packages/client/instance-board.mjs +206 -0
  74. package/packages/client/instance-presentation.mjs +55 -0
  75. package/packages/client/liveness.mjs +15 -4
  76. package/packages/client/own-codes.mjs +5 -1
  77. package/packages/client/remote-roster.mjs +6 -1
  78. package/packages/client/session-backends.mjs +31 -0
  79. package/packages/client/session-start.mjs +18 -6
  80. package/packages/client/spawn-apply-cli.mjs +5 -3
  81. package/packages/client/spawn-apply-contract.mjs +25 -2
  82. package/packages/client/spawn-apply.mjs +5 -1
  83. package/packages/client/spawn-messages.mjs +3 -0
  84. package/packages/client/terminal-contract.mjs +4 -0
  85. package/packages/client/waiting-on-you.mjs +12 -2
  86. package/packages/tui/lib/model.mjs +14 -3
  87. package/packages/tui/lib/store.mjs +12 -3
  88. package/skills/oats-getting-started/SKILL.md +3 -3
package/lib/core.mjs CHANGED
@@ -39,7 +39,7 @@ import { launchPromptEngages, claudeVersionOf, CLAUDE_SESSION_HINT } from "./lau
39
39
  import { LAUNCH_PANE_FORMAT, launchPaneTarget, launchPromptTransport } from "./launch-prompt-transport.mjs";
40
40
  import { execFileSync, execSync, spawn as spawnProcess, spawnSync } from "node:child_process";
41
41
  import {
42
- chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, writeFileSync,
42
+ chmodSync, closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, writeFileSync,
43
43
  } from "node:fs";
44
44
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
45
45
  import { homedir } from "node:os";
@@ -58,11 +58,14 @@ import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, se
58
58
  import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, recordInClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
59
59
  import { captureLoginEnvironment } from "./login-environment.mjs";
60
60
  import { kernelNode } from "./stable-node.mjs";
61
+ import { instanceSoulDir, kernelBin, lifecycleHookEnv, stableSoulId, teamEnv } from "./hook-env.mjs";
62
+ import { capabilityRuntimeOf, compositionOf, homeModulesProblem, kernelModuleDir, moduleCopyProblem, moduleCopyReport, providerHomeTrust, removeModulesStore, trustedCapability, trustedRecord } from "./home-integrity.mjs";
63
+ import { homeReceipt, legacyRetirementBaselinePath } from "./session-receipt.mjs";
61
64
  import { assertNoPartialUpgrade, packageRespawnWarning, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
62
65
 
63
66
  import { refuseHomeOfAnotherUser } from "./home-owner.mjs";
64
- import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
65
- import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
67
+ import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isDefect, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
68
+ import { envRows, recordedTeams } from "./teams.mjs";
66
69
  import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
67
70
  import { shq, shellWord } from "./shell-word.mjs";
68
71
  import { CONFIG_DIR_VAR, HARNESS_FOLDER_VAR, claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigFolder } from "./harness-trust.mjs";
@@ -92,16 +95,22 @@ import { readPortableBytes } from "./bounded-read.mjs";
92
95
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
93
96
  import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
94
97
  import { hashFile, readFilePieces, readFileUpTo } from "./file-pieces.mjs";
95
- import { assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
98
+ import { PROVIDER_TREE_GIT, assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
96
99
  import { retireGitReadsNoWorkTreeFile, retireSubcommandAt } from "./retire-git-forms.mjs";
97
100
  import { systemTool } from "./system-tools.mjs";
98
101
  import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
99
102
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
100
103
  import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
101
104
  import { PIN_FILE } from "./instance-pin.mjs";
105
+ import { SESSION_PROVIDER_ANY, launchSentOf, unsettledLaunchSaid, sessionProviderTimeout, recordsSessionProvider, launchReadinessRefusal, homeSessionProvider, inputProviderSession, inputWasRefused, sameEndpoint, inspectProviderSession, launchProviderSession, providerRuntimeRecord, selectSessionBackend, stopProviderSession, wireRefusal } from "./session-providers.mjs";
106
+ import { dieAt } from "./provider-test-seams.mjs";
102
107
  import { BOARD_FILE, BOARD_LOCK } from "./instance-board.mjs";
103
108
  import { RELATED_WORK_FILE, SAME_WORK_FILE, relatedWorkBinding, writeRelatedWork } from "./instance-related-work.mjs";
104
- import { HOST_STOP_REASON, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
109
+ import { HOST_STOP_REASON, lostReasonOf, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
110
+ import { PROVIDER_RESUME_NOTICE, RESUME_QUIET_WAIT_MS, countProviderResume, resumeCountLock, resumeQuietWait } from "./provider-resume.mjs";
111
+ import { withDirLock } from "./dir-lock.mjs";
112
+ import { waitingHold } from "./instance-events.mjs";
113
+ import { ensureSandboxWritePaths, homeSandboxAllowances, sandboxAllowances, sandboxEventsDir, sandboxLaunchInput, sandboxWritePathsRefusal } from "./sandbox-allowances.mjs";
105
114
  import { thisBoot } from "./session-seen.mjs";
106
115
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
107
116
  import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
@@ -110,7 +119,8 @@ import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
110
119
  import { PKG_ROOT } from "./version.mjs";
111
120
  import { canonicalDeploymentPath } from "./deployment-path.mjs";
112
121
  import { INSTANCE_NAME_RE, RESERVED, capabilityAgentDirs, enclosingInstanceHome, findInstanceHomes, listAgents, logicalCwd, readSoul, soulOf, stripInternalAnnotations, withConfigFile, yamlKey } from "./soul-listing.mjs";
113
- import { RETIRE_BASELINE_VERSION, authorityMismatch, findRetirementBaseline, inspectInstanceSession, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, retirementBaselinePath, runtimeAuthorityOf, tmuxEndpointAgrees } from "./session-inspect.mjs";
122
+ import { endpointAgrees, providerHomeOf } from "./session-inspect.mjs";
123
+ import { RETIRE_BASELINE_VERSION, authorityMismatch, findRetirementBaseline, inspectInstanceSession, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, retirementBaselinePath, runtimeAuthorityOf } from "./session-inspect.mjs";
114
124
  import { CLAIM_VERBS, DEFAULT_TMUX_SESSION, LAUNCH_RECIPE_VERSION, claimAction, completionLiveness, defaultTmuxWindows, deferredRetireResultPath, directoryRollbackPath, hostProcesses, isCapturedHome, lookupOnPath, missingSocketUnestablished, namedProcesses, parseLaunchCommand, procReadable, processesWorkingIn, readHomeRecord, readRetirePending, redactLaunchCommand, redactLaunchRecipe, retireCarried, retireClaimPath, retirePendingMarkerPath, retireStateOf, subdirs, tmuxFailure, tmuxOn, tmuxServerAbsence, upgradeHomeMeta, upgradeLaunchRecipe } from "./instance-listing.mjs";
115
125
  import { LAYERS, PACKAGE_ID_RE } from "./package-catalog.mjs";
116
126
  import { RESERVED_LAUNCH_ENV } from "./reserved-launch-env.mjs";
@@ -123,6 +133,7 @@ export { RESERVED, assertSafeConfigKey, enclosingInstanceHome, findInstanceHomes
123
133
  export { canonicalAgentsRoot, ensureRoot, findRoot, workspaceOf } from "./agents-root.mjs";
124
134
  export { canonicalDeploymentPath } from "./deployment-path.mjs";
125
135
  export { OATS_VERSION, PKG_ROOT } from "./version.mjs";
136
+ export { instanceSoulDir, kernelBin, lifecycleHookEnv, stableSoulId, teamEnv } from "./hook-env.mjs";
126
137
  // Keep the existing public core surface; internal data helpers are not re-exported.
127
138
  export { oatsError } from "./errors.mjs";
128
139
  export { copyTreeSafe } from "./tree-copy.mjs";
@@ -688,6 +699,20 @@ export function capabilityManifests(startDir) {
688
699
  if (m) add(m);
689
700
  return out;
690
701
  }
702
+ // A provider home's modules are the ones its receipt records, read from the KERNEL's copies of
703
+ // them, outside the home (lib/home-integrity.mjs): what the home's own record or its own copies
704
+ // say is not read (nor needed: a home whose `.oats/modules` or whose record of them is gone is
705
+ // read the same), and a module its record adds is no capability of it.
706
+ const providerHome = enclosingHome(startDir);
707
+ const trust = providerHome ? providerHomeTrust(providerHome) : null;
708
+ if (trust) {
709
+ for (const [name, rec] of Object.entries(trust.composition?.modules ?? {})) {
710
+ if (!PACKAGE_ID_RE.test(name) || name === "__proto__") continue;
711
+ const m = loadManifestAt(kernelModuleDir(providerHome, name, trust), `module:${providerHome}`);
712
+ if (m) { m._module = rec; add(m); }
713
+ }
714
+ return out;
715
+ }
691
716
  const modulesOf = instanceModulesRoot(startDir);
692
717
  if (modulesOf) {
693
718
  for (const [name, rec] of Object.entries(modulesOf.modules)) {
@@ -699,6 +724,19 @@ export function capabilityManifests(startDir) {
699
724
  }
700
725
  return out;
701
726
  }
727
+ /** The instance home `dir` is, or is inside: the nearest directory, `dir` included, that holds
728
+ * an instance.json (as instanceModulesRoot walks); null when there is none. */
729
+ function enclosingHome(dir) {
730
+ if (!dir) return null;
731
+ let cur = resolve(dir);
732
+ for (let i = 0; i < 6; i++) {
733
+ if (existsSync(join(cur, "instance.json"))) return cur;
734
+ const parent = dirname(cur);
735
+ if (parent === cur) break;
736
+ cur = parent;
737
+ }
738
+ return null;
739
+ }
702
740
  export function capabilityManifest(name, startDir) {
703
741
  return capabilityManifests(startDir)[name];
704
742
  }
@@ -903,7 +941,8 @@ export function resolvedFromHome(home, meta, { teams, defaultTeam, teamsSource }
903
941
  const messaging = (Array.isArray(meta?.capabilities) ? meta.capabilities : []).find((c) => c?.layer === "messaging")?.id ?? null;
904
942
  const t = Array.isArray(teams) ? { teams, defaultTeam: defaultTeam ?? null, teamsSource: teamsSource === "live" ? "live" : "recorded" } : { ...recordedTeams(meta), teamsSource: "recorded" };
905
943
  return {
906
- capabilities: Array.isArray(meta?.capabilityRuntime) ? meta.capabilityRuntime : [],
944
+ // (A provider home's rows are its receipt's: lib/home-integrity.mjs.)
945
+ capabilities: capabilityRuntimeOf(home, meta),
907
946
  workspace: ws ? { ...ws, slots: { messaging } } : null,
908
947
  payloads: meta?.providers ?? {},
909
948
  ...t,
@@ -1336,67 +1375,12 @@ function validateHookEnvironment(capabilityID, value, owners, declarations) {
1336
1375
  return accepted;
1337
1376
  }
1338
1377
 
1339
- /**
1340
- * A soul's STABLE identity for capability hooks (OATS_SOUL_ID): what a provider
1341
- * may key durable state on. Workspace soul: `<repo key>#<soul name>` — it does not
1342
- * change when the member commits (the per-commit soul directory does) or when the
1343
- * copy moves. Classic soul: the realpath of agents/<name>/soul, i.e. today's value,
1344
- * so 0.24 deployments are unchanged. Order: an explicit `soulId` (a prepared spawn),
1345
- * the home's recorded `instance.json.workspace.soul` (retire/launch of a workspace
1346
- * home), else the path.
1347
- */
1348
- export function stableSoulId({ soulId, home, soulDir, agentName } = {}) {
1349
- if (typeof soulId === "string" && soulId) return soulId;
1350
- if (home) {
1351
- try {
1352
- const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
1353
- const s = meta?.workspace?.soul;
1354
- if (typeof s?.id === "string" && s.id) return s.id;
1355
- if (typeof s?.repoKey === "string" && s.repoKey) return `${s.repoKey}#${meta.agent ?? agentName ?? ""}`;
1356
- } catch { /* not a workspace home */ }
1357
- }
1358
- if (soulDir) { try { return realpathSync(soulDir); } catch { return soulDir; } }
1359
- return "";
1360
- }
1361
1378
  export const workspaceSoulId = (repoKey, name) => `${repoKey}#${name}`;
1362
1379
  /** A triggered instance's event, inside its home's .oats/ (lib/triggers.mjs). */
1363
1380
  export const TRIGGER_EVENT_FILE = "trigger-event.json";
1364
1381
  /** A prepared soul entry's id: `<repoKey>#<name>` for a member or external soul, `package:<id>#<name>`
1365
1382
  * for a package soul (stable across the package's versions and independent of its repo). */
1366
1383
  export const preparedSoulIdOf = (entry) => workspaceSoulId(typeof entry.package === "string" ? `package:${entry.package}` : entry.repoKey, entry.name);
1367
- /** The soul directory an instance incarnates, as spawn recorded it (instance.json
1368
- * `soulDir`): a workspace soul's per-commit copy (agents/<soul>/souls/<commit12>) or
1369
- * the read-only soul inside a capability package. It is what every classic
1370
- * lifecycle hook and dispatched command sees as OATS_SOUL (captured hooks set
1371
- * none); instance homes carry no soul link. */
1372
- export function instanceSoulDir(home, meta = undefined) {
1373
- if (meta === undefined && home) { try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { meta = null; } }
1374
- return typeof meta?.soulDir === "string" && isAbsolute(meta.soulDir) ? meta.soulDir : undefined;
1375
- }
1376
-
1377
- /** The team and workspace facts a lifecycle hook, command or provider check receives (workspace
1378
- * model only, lead decision c3-7): OATS_TEAM_SCOPE is the deployment directory; OATS_WORKSPACE_NAME /
1379
- * _KEY the workspace's name and canonical key; OATS_TEAM_NAME (the 0.25 `team:` block's name) is always
1380
- * empty, so an ambient value never reaches a hook.
1381
- *
1382
- * Team model v2 (docs/desktop-cli-api.md, The provider environment): `resolved.teams` are the soul's
1383
- * TeamRows here and `resolved.defaultTeam` its DefaultTeam; teamsEnv sets OATS_DEFAULT_TEAM(_ID,_FROM),
1384
- * OATS_TEAMS (mapped rows only) and OATS_TEAMS_SOURCE (`live`: the workspace + oats-local.yaml read now,
1385
- * or a fresh resolution; `recorded`: the spawn-time record). A provider LEAVES a joined team only on a
1386
- * `live` list. Teams not known (`resolved.teams` not an array): every team name unset. */
1387
- export function teamEnv(resolved) {
1388
- const ws = resolved?.workspace && typeof resolved.workspace === "object" ? resolved.workspace : {};
1389
- const known = Array.isArray(resolved?.teams);
1390
- return {
1391
- OATS_TEAM_NAME: "", OATS_TEAM_SCOPE: typeof ws.deployment === "string" ? ws.deployment : "",
1392
- ...teamsEnv(known ? { teams: resolved.teams, defaultTeam: resolved.defaultTeam ?? null, source: resolved.teamsSource } : null),
1393
- OATS_WORKSPACE_NAME: typeof ws.name === "string" ? ws.name : "", OATS_WORKSPACE_KEY: typeof ws.key === "string" ? ws.key : "",
1394
- };
1395
- }
1396
- function withoutAmbientHookFacts(env) {
1397
- const { OATS_LAUNCH_PREVIEW: _ambient, OATS_HARNESS_EXECUTABLE: _inherited, OATS_SPAWNER_HOME: _spawner, ...rest } = env;
1398
- return rest;
1399
- }
1400
1384
  /** A hook's OATS_HARNESS_EXECUTABLE: what the kernel's pane-side selection found, as an absolute real
1401
1385
  * path, so a hook can ask the program its pane will run. `paneSide` says the path is such an answer:
1402
1386
  * a recorded recipe's, a declared one, or a lookup on the pane's PATH. A bare name this process's
@@ -1415,43 +1399,6 @@ function replacedExecutableWarning(handed, launched) {
1415
1399
  if (!handed || !now || handed === now) return null;
1416
1400
  return `the harness executable changed after the hooks ran: hooks were given ${handed}, this launch runs ${now}`;
1417
1401
  }
1418
- /** The environment one capability's lifecycle hook runs with: the invoker's own
1419
- * (inherited, as for every hook; the kernel adds no credentials), plus the
1420
- * standard OATS_* variables (docs/capabilities.md, Commands and hooks) and the
1421
- * caller's `extraEnv`. One builder for every event, so the `worktree` runner
1422
- * (lib/worktree-hooks.mjs) hands its hooks exactly what every other hook gets. */
1423
- export function lifecycleHookEnv(event, cap, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {} }) {
1424
- return {
1425
- // OATS_LAUNCH_PREVIEW is the kernel's to give (prepareLaunchHooks), never
1426
- // inherited: a real start's hook must not read an ambient one as a preview.
1427
- // Nor are OATS_HARNESS_EXECUTABLE and OATS_SPAWNER_HOME (spawn's
1428
- // callerSpawner): a hook started from inside an instance must not read its caller's.
1429
- ...withoutAmbientHookFacts(process.env),
1430
- // OATS_INSTANCE_HOME is the runtime-neutral contract name for the
1431
- // instance home (absolute). OATS_HOME predates it and stays as a
1432
- // compatibility alias: shipped capability hooks read it
1433
- // (the official oats.aweb and oats.okf packages) and are versioned
1434
- // independently of this kernel. Neither is OATS_HOME_DIR, which is
1435
- // the package STORE root — do not conflate them.
1436
- OATS_EVENT: event, OATS_INSTANCE: instance, OATS_INSTANCE_HOME: home, OATS_HOME: home, OATS_AGENT: agentName,
1437
- OATS_CAPABILITY: cap.id, OATS_LAYER: cap.layer || "", OATS_ROOT: rootDir || "",
1438
- OATS_SOUL: soulDir || "", OATS_SOUL_ID: stableSoulId({ soulId, home, soulDir, agentName }), OATS_CONTEXT: contextDir, OATS_WORKSPACE: workspaceDir || "", OATS_LEVEL: cap.level || "",
1439
- ...teamEnv(resolved),
1440
- ...extraEnv,
1441
- // Hooks also run through direct core callers (not only bin/oats).
1442
- // Author this from the running kernel, never PATH, ambient env or
1443
- // a caller's extraEnv: those may point at a different executable.
1444
- OATS_CLI_BIN: kernelBin(),
1445
- // The node a capability writes into anything that outlives its hook (lib/stable-node.mjs).
1446
- OATS_NODE_BIN: kernelNode().node,
1447
- OATS_SETTINGS: JSON.stringify(cap.settings || {}),
1448
- // Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
1449
- // manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
1450
- // soul-set value from a host-set one. {} when the home recorded none (spawned before 0.29).
1451
- OATS_SETTINGS_ORIGINS: JSON.stringify(cap.settingsOrigins || {}),
1452
- OATS_META: JSON.stringify(priorMeta[cap.id] || {}),
1453
- };
1454
- }
1455
1402
  /** What a spawn or launch hook may answer as `dialogClaims`: `reported`, this session's dialogs become
1456
1403
  * `permission` or `question` claims; `none`, this harness has no dialog an Enter can answer. */
1457
1404
  const DIALOG_CLAIMS = ["reported", "none"];
@@ -1477,10 +1424,17 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1477
1424
  // retire) gets the directory the home's spawn recorded.
1478
1425
  if (!soulDir && home) soulDir = instanceSoulDir(home);
1479
1426
  const envOwners = new Map();
1480
- const envDeclarations = new Map((resolved.capabilities || []).map((cap) => [cap.id, { names: new Set(cap.environment || []), namespaces: [...(cap.environmentNamespaces || [])] }]));
1481
- const caps = [...(resolved.capabilities || [])];
1427
+ // A provider home (lib/home-integrity.mjs): whatever rows the caller holds, each capability's
1428
+ // settings, hook commands and declarations are its receipt's, and the commands name the
1429
+ // kernel's own copy of the module, never the home's. A capability the receipt does not record,
1430
+ // or whose kernel copy is gone, is a failed required hook, which names the module: a launch is
1431
+ // refused, a retire goes on to the other capabilities' hooks and reports this one as not run.
1432
+ const trust = home ? providerHomeTrust(home) : null;
1433
+ const trusted = (resolved.capabilities || []).map((cap) => trustedCapability(home, cap, trust));
1434
+ const envDeclarations = new Map(trusted.map(({ cap }) => [cap.id, { names: new Set(cap.environment || []), namespaces: [...(cap.environmentNamespaces || [])] }]));
1435
+ const caps = [...trusted];
1482
1436
  if (event === "retire") caps.reverse();
1483
- for (const cap of caps) {
1437
+ for (const { cap, problem } of caps) {
1484
1438
  for (const miss of cap.missingRequires || []) {
1485
1439
  results.warnings.push(`${cap.id}${cap.layer ? ` (${cap.layer})` : ""}: required command "${miss.command}" not on PATH — ${miss.why || "needed by this capability"}${miss.install ? ` (install: ${miss.install})` : ""}`);
1486
1440
  }
@@ -1494,6 +1448,13 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1494
1448
  if (finished.get(cap.id) !== undefined) results.meta[cap.id] = finished.get(cap.id);
1495
1449
  continue;
1496
1450
  }
1451
+ const untrusted = trust ? problem ?? moduleCopyProblem(home, cap.id, trust) : null;
1452
+ if (untrusted) {
1453
+ results.warnings.push(`${cap.id} ${event} hook was NOT run: ${untrusted}`);
1454
+ results.failures.push({ capability: cap.id, event, message: untrusted, required: true, integrity: true });
1455
+ if (event === "spawn") return results;
1456
+ continue;
1457
+ }
1497
1458
  assertRoots?.();
1498
1459
  results.order.push(cap.id);
1499
1460
  if (event === "spawn" || event === "launch") results.dialogClaims[cap.id] = null;
@@ -1867,7 +1828,7 @@ const INSTANCE_IDENTITY_ENV = ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME
1867
1828
  const KERNEL_ENV_NAMES = new Set([...RESERVED_LAUNCH_ENV, "COLORFGBG", "TMUX", "TMUX_PANE",
1868
1829
  "OATS_CAPABILITY", "OATS_LAYER", "OATS_LEVEL", "OATS_META", "OATS_DEPLOYMENT", "OATS_RESOLUTION", "OATS_OPERATION",
1869
1830
  "OATS_REPO", "OATS_BRANCH", "OATS_WORK", "OATS_KIND", "OATS_TASK", "OATS_HARNESS", "OATS_PREVIOUS_HARNESS", "OATS_RUNTIME", "OATS_PREVIOUS_RUNTIME",
1870
- "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1831
+ "OATS_BACKEND", "OATS_PREVIOUS_BACKEND", "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1871
1832
  "OATS_TEAM_NAME", "OATS_TEAM_SCOPE", "OATS_TEAM_ID", "OATS_TEAM_LABEL", "OATS_TEAM_LABELS", "OATS_TEAMS", "OATS_TEAMS_SOURCE",
1872
1833
  "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_WORKSPACE_NAME", "OATS_WORKSPACE_KEY",
1873
1834
  // A worktree hook's tree (#796): never inherited by what such a hook starts.
@@ -2177,6 +2138,7 @@ const NO_PANE_READ = Object.freeze({ unestablished: ": this process could not re
2177
2138
  const NO_TMUX = Object.freeze({ unestablished: ": this process has no tmux on its PATH to read the OATS tmux server with" });
2178
2139
  const NO_LAUNCH = Object.freeze({ unestablished: ": this spawn launches nothing (--no-launch), and a start reads its own session's" });
2179
2140
  const SESSION_REFUSED = Object.freeze({ unestablished: ": the session this start would create was refused" });
2141
+ const NO_PANE = Object.freeze({ unestablished: ": a session provider runs this launch, which has no pane" });
2180
2142
  const HOME_SESSION_UNREAD = Object.freeze({ unestablished: ": this home's session record could not be read" });
2181
2143
  /** The environment a launch's pane is expected to have (paneEnvironment's shape), from a plan
2182
2144
  * (planOatsTmuxSession): the session's or the server's when a server runs, else the environment the
@@ -2281,7 +2243,12 @@ export function previewPaneEnvironment({ home = null, meta = null, deployment =
2281
2243
  let session = DEFAULT_TMUX_SESSION;
2282
2244
  if (home) {
2283
2245
  let target;
2284
- try { ({ target } = instanceSessionTarget(home)); } catch (e) { if (!isKernelCode(e?.code)) throw e; return HOME_SESSION_UNREAD; }
2246
+ try {
2247
+ const recorded = instanceSessionTarget(home);
2248
+ // A home on a session provider has no pane, now or at its next start.
2249
+ if (providerHomeOf(recorded)) return NO_PANE;
2250
+ target = recorded.target;
2251
+ } catch (e) { if (!isKernelCode(e?.code)) throw e; return HOME_SESSION_UNREAD; }
2285
2252
  if (target) {
2286
2253
  let state = null;
2287
2254
  try { state = inspectSessionTarget(target, io); } catch (e) { if (isKernelCode(e?.code)) return HOME_SESSION_UNREAD; /* a server that has gone has no pane to reuse */ }
@@ -2552,7 +2519,24 @@ export function requirementHarness(row) {
2552
2519
  if (!row || typeof row !== "object") return undefined;
2553
2520
  return Object.hasOwn(row, "harness") ? row.harness : row.runtime;
2554
2521
  }
2555
- function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {}) {
2522
+ /** Whether a `requires` row applies to a launch on `backend` (`tmux`, or a session provider's name).
2523
+ * A row may carry `backends`: `["tmux"]`, `["session-provider"]` (any session provider) or both;
2524
+ * without the key it applies to every backend. Never inside `when`, whose keys are the capability's
2525
+ * own settings. A `backends` that is not such a list applies (verifyHarnessPackages refuses it). */
2526
+ const REQUIREMENT_BACKENDS = ["tmux", SESSION_PROVIDER_ANY];
2527
+ const validRequirementBackends = (row) => row.backends === undefined || (Array.isArray(row.backends) && row.backends.length > 0 && row.backends.every((b, i) => REQUIREMENT_BACKENDS.includes(b) && row.backends.indexOf(b) === i));
2528
+ function requirementOnBackend(row, backend) {
2529
+ if (row.backends === undefined || !validRequirementBackends(row)) return true;
2530
+ return row.backends.includes(backend === "tmux" ? "tmux" : SESSION_PROVIDER_ANY);
2531
+ }
2532
+ /** Whether a `requires` row's `when` holds under the capability's effective settings: every named
2533
+ * setting has the given value. A row without `when` holds, and so does one whose `when` is no
2534
+ * object, as a malformed `backends` does: verifyHarnessPackages refuses it. */
2535
+ const requirementWhenHolds = (cap, row) => !row.when || typeof row.when !== "object" || Array.isArray(row.when) || Object.entries(row.when).every(([k, v]) => String(cap.settings?.[k] ?? "") === String(v));
2536
+ /** Whether a `requires` row is a requirement of this launch: for its backend, AND its `when` holds.
2537
+ * The one predicate of the probe (verifyHarnessPackages) and of what it would probe (applicableRequirements). */
2538
+ const requirementApplies = (cap, row, backend) => requirementOnBackend(row, backend) && requirementWhenHolds(cap, row);
2539
+ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env, backend = "tmux" } = {}) {
2556
2540
  // The probe's environment is the launch's (launchEffectiveEnv: the pane's PATH, HOME and
2557
2541
  // selectors, never this process's in their place), given as it is or as a function called at the
2558
2542
  // first requirement that applies: a launch with none reads nothing of its pane, and one whose
@@ -2578,11 +2562,15 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
2578
2562
  if (!raw || typeof raw !== "object") continue;
2579
2563
  if (Object.hasOwn(raw, "harness") && Object.hasOwn(raw, "runtime")) { problems.push(`${cap.id}: a requirement declares both \`harness\` and \`runtime\` (its pre-0.27 name); keep one`); continue; }
2580
2564
  if (requirementHarness(raw) !== harness) continue;
2565
+ // A requirement may name the backends it is for (`backends`): a row for another backend is
2566
+ // not a requirement of this launch at all.
2567
+ if (!validRequirementBackends(raw)) { problems.push(`${cap.id}: a requirement's \`backends\` must be a list of ${REQUIREMENT_BACKENDS.join(" and ")} (${SESSION_PROVIDER_ANY}: any session provider), each at most once`); continue; }
2568
+ if (!requirementOnBackend(raw, backend)) continue;
2581
2569
  // A requirement may be conditional on the capability's effective
2582
2570
  // settings (`when: { delivery: "channel" }`): rows whose condition does
2583
2571
  // not hold are not requirements of this spawn at all.
2584
2572
  if (raw.when !== undefined && (!raw.when || typeof raw.when !== "object" || Array.isArray(raw.when))) { problems.push(`${cap.id}: a requirement's \`when\` must be an object of setting names to values`); continue; }
2585
- if (raw.when && !Object.entries(raw.when).every(([k, v]) => String(cap.settings?.[k] ?? "") === String(v))) continue;
2573
+ if (!requirementApplies(cap, raw, backend)) continue;
2586
2574
  const spec = raw.package;
2587
2575
  if (!safeHarnessPackageSpec(spec, harness)) { problems.push(`${cap.id}: ${harness} package spec is not a plain source token (${JSON.stringify(spec)})`); continue; }
2588
2576
  if (raw.marketplace !== undefined && !safeHarnessSourceRef(raw.marketplace)) { problems.push(`${cap.id}: marketplace is not a plain source reference (${JSON.stringify(raw.marketplace)})`); continue; }
@@ -2876,8 +2864,6 @@ export function launchEnvRefs(recipe, env = process.env) {
2876
2864
  return out;
2877
2865
  }
2878
2866
 
2879
- /** The canonical path of this kernel's CLI: what the home's shim points at, and OATS_CLI_BIN. */
2880
- export function kernelBin() { return realpathSync(join(PKG_ROOT, "bin", "oats.mjs")); }
2881
2867
  /** Where a home's `oats` lives: first on its harness's PATH, so plain `oats` inside an instance is
2882
2868
  * the kernel that launched it, whatever other `oats` the host's PATH finds first. */
2883
2869
  export const kernelShimDir = (home) => join(home, ".oats", "bin");
@@ -3109,13 +3095,14 @@ function agentScopeOn(command, { pane, removed = [], refs = [] }, io) {
3109
3095
 
3110
3096
  /** A recorded recipe this kernel understands, or a refusal before anything
3111
3097
  * is observed or stopped. */
3112
- export function assertLaunchRecipe(recipe, what) {
3098
+ export function assertLaunchRecipe(recipe, what, { sessionProvider = false } = {}) {
3113
3099
  const bad = (why) => { throw oatsError("E_LAUNCH_RECIPE_UNSUPPORTED", `${what} records a launch recipe this kernel cannot start from (${why}); inspect launch in its instance.json`); };
3114
3100
  if (!recipe || typeof recipe !== "object") bad("not an object");
3115
3101
  recipe = upgradeLaunchRecipe(recipe);
3116
3102
  if (recipe.version !== LAUNCH_RECIPE_VERSION) bad(`version ${JSON.stringify(recipe.version)}, expected ${LAUNCH_RECIPE_VERSION}`);
3117
3103
  if (!LAUNCH_HARNESSES.includes(recipe.harness)) bad(`harness ${JSON.stringify(recipe.harness)}`);
3118
- if (typeof recipe.executable !== "string" || !recipe.executable) bad("no executable");
3104
+ // A home on a session provider records no executable: the provider runs the harness itself.
3105
+ if (sessionProvider ? recipe.executable !== null : typeof recipe.executable !== "string" || !recipe.executable) bad(sessionProvider ? "an executable, on a session provider" : "no executable");
3119
3106
  if (!Array.isArray(recipe.args) || recipe.args.some((a) => typeof a !== "string")) bad("args are not a list of strings");
3120
3107
  if (!recipe.env || typeof recipe.env !== "object" || Array.isArray(recipe.env)) bad("env is not a map");
3121
3108
  for (const [n, v] of Object.entries(recipe.env)) {
@@ -3130,14 +3117,13 @@ export function assertLaunchRecipe(recipe, what) {
3130
3117
  /** The harness-package requirements that apply: declared for this harness
3131
3118
  * and, for a conditional row, holding under the provider's (captured)
3132
3119
  * settings. Nothing else is probed or restricted. */
3133
- export function applicableRequirements(harness, providers) {
3134
- const holds = (cap, r) => !r.when || (r.when && typeof r.when === "object" && !Array.isArray(r.when) && Object.entries(r.when).every(([k, v]) => String(cap.settings?.[k] ?? "") === String(v)));
3120
+ export function applicableRequirements(harness, providers, backend = "tmux") {
3135
3121
  const out = [];
3136
- for (const cap of providers || []) for (const r of cap.manifest?.requires || []) if (r && typeof r === "object" && requirementHarness(r) === harness && holds(cap, r)) out.push({ capability: cap.id, package: r.package });
3122
+ for (const cap of providers || []) for (const r of cap.manifest?.requires || []) if (r && typeof r === "object" && requirementHarness(r) === harness && requirementApplies(cap, r, backend)) out.push({ capability: cap.id, package: r.package });
3137
3123
  return out;
3138
3124
  }
3139
- function requirementsWithArgsMessage(harness, providers, config) {
3140
- const rows = applicableRequirements(harness, providers);
3125
+ function requirementsWithArgsMessage(harness, providers, config, backend = "tmux") {
3126
+ const rows = applicableRequirements(harness, providers, backend);
3141
3127
  return `launch configuration ${config?.name || "(recorded)"} passes arguments (${config.args.map((a) => JSON.stringify(a)).join(", ")}) that the ${harness} package probe cannot carry, so ${rows.map((r) => `${r.capability}'s requirement ${r.package}`).join(", ")} cannot be verified for that launch; native configuration a required package must see belongs in a wrapper executable or the environment (env / fromEnv), not in args`;
3142
3128
  }
3143
3129
  /** ONE planner for what a start would run, used by preview and by starts of
@@ -3146,20 +3132,25 @@ function requirementsWithArgsMessage(harness, providers, config) {
3146
3132
  * collects every failed check into `preflight` instead of throwing. Launch
3147
3133
  * hooks of capabilities declaring `launchPreview` run here only as a preview
3148
3134
  * (OATS_LAUNCH_PREVIEW=1); the others run here for real when a start plans,
3149
- * and not at all for a preview. A home
3135
+ * and not at all for a preview. `noHooks` (with `preview`): no launch hook runs at all, the
3136
+ * recorded contributions stand for every capability: what a start asks its session provider's
3137
+ * readiness with, before any hook (the selection: harness, yolo, the configuration's arguments). A home
3150
3138
  * that records no launch recipe (an earlier kernel spawned it) is not planned:
3151
3139
  * E_LAUNCH_LEGACY, re-spawn it from the deployment. `pane`: the environment the launch's pane is
3152
3140
  * expected to have (paneEnvironment's shape, or a function giving it, called only when a check
3153
3141
  * needs a name the launch itself does not set); every check here reads it through the one answer
3154
3142
  * (launchEnvironment), and says so when it is not established. */
3155
- export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, assertRoots, reselect = null, pane }) {
3143
+ export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, noHooks = false, assertRoots, reselect = null, pane }) {
3156
3144
  assertRoots?.();
3157
3145
  const problems = [];
3158
3146
  const fail = (check, code, detail) => { if (!preview) throw oatsError(code, detail); problems.push({ check, ok: false, detail, code }); };
3159
3147
  // A recorded recipe is validated before anything is observed. A home without
3160
3148
  // one predates recipes: there is nothing this kernel plans from.
3161
3149
  if (meta && !(meta.launch && typeof meta.launch === "object")) throw oatsError("E_LAUNCH_LEGACY", `${meta.instance || home} records no launch recipe (an earlier kernel spawned it): re-spawn it from the deployment; nothing was changed`);
3162
- const frozen = meta ? assertLaunchRecipe(meta.launch, meta.instance || home) : null;
3150
+ // A home on a session provider (lib/session-providers.mjs): the provider runs the harness itself,
3151
+ // so nothing of a pane or an executable is planned or checked, and no command line is rendered.
3152
+ const sessionProvider = meta && homeBackendOf(meta) !== "tmux" ? { backend: meta.backend, capability: meta.session.provider } : null;
3153
+ const frozen = meta ? assertLaunchRecipe(meta.launch, meta.instance || home, { sessionProvider: !!sessionProvider }) : null;
3163
3154
  // The home's deployment declares the launch configurations (its oats-local.yaml,
3164
3155
  // found walking up from the home) — never the context directory, which may be a
3165
3156
  // member clone outside the deployment.
@@ -3183,7 +3174,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3183
3174
  // A frozen recipe keeps its recorded path. Otherwise a bare name is looked up where the pane will
3184
3175
  // look it up (launchLookup: the configuration's PATH, else the pane's, the start's expected
3185
3176
  // session or server PATH; a start looks again on the session it gets).
3186
- const executable = config?.frozen
3177
+ const executable = sessionProvider ? { path: null, declared: null, resolvedFrom: `session provider ${sessionProvider.backend}` } : config?.frozen
3187
3178
  ? { path: config.executablePath, declared: frozen.executableDeclared ?? null, resolvedFrom: frozen.executableResolvedFrom || "recorded", missing: existsSync(config.executablePath) ? undefined : `${config.executablePath} (recorded) does not exist` }
3188
3179
  : resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir, lookup: config?.executable?.includes("/") ? undefined : launchLookup(launchEnv) });
3189
3180
  // What the hooks are handed: the pane-side answer, not one this process's PATH gave.
@@ -3191,7 +3182,18 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3191
3182
  // A bare name looked up on this process's PATH because the pane's is not established: said.
3192
3183
  const lookupNote = !config?.frozen && !config?.executable?.includes("/") && !executable.lookup ? unestablishedNote(launchEnv, ["PATH"]) : null;
3193
3184
  const notOnPane = !executable.path && executable.lookup ? executableNotOnPanePath(executable, { harness, config, from: launchChoice?.from, at: launchChoice?.at }) : null;
3194
- if (notOnPane) {
3185
+ if (sessionProvider) {
3186
+ // The provider's own rules for this launch: the harness is one it runs, and no executable is named.
3187
+ // The home's modules as they are now, under the spawn's own selection: one name has one
3188
+ // meaning (E_BACKEND_AMBIGUOUS), and the harness is one the provider runs (E_BACKEND_HARNESS).
3189
+ const bound = homeSessionProvider(home, meta, sessionProvider.capability, sessionProvider.backend);
3190
+ let refusal = null;
3191
+ if (!bound.problem) { try { selectSessionBackend(sessionProvider.backend, Object.values(capabilityManifests(home)).map((m) => ({ id: m.capability, manifest: m })), harness, "nothing was stopped or started"); } catch (e) { if (!isKernelCode(e?.code)) throw e; refusal = e; } }
3192
+ if (bound.problem) fail("backend", "E_SESSION_START_FAILED", `${meta?.instance || instance || basename(home)} cannot be launched on session backend ${sessionProvider.backend}: ${bound.problem}; nothing was stopped or started`);
3193
+ else if (refusal) { if (!preview) throw refusal; problems.push({ check: "backend", ok: false, detail: refusal.message, code: refusal.code }); }
3194
+ else if (config?.executable && !config.frozen) fail("backend", "E_BACKEND_LAUNCH_ARG", `launch configuration ${config.name} declares an executable (${config.executable}), and session backend ${sessionProvider.backend} runs the harness itself: no executable can be handed to it; nothing was stopped or started`);
3195
+ else problems.push({ check: "backend", ok: true, detail: `session backend ${sessionProvider.backend} (${sessionProvider.capability}) runs the harness: no executable, harness package or folder trust is checked here` });
3196
+ } else if (notOnPane) {
3195
3197
  if (!preview) throw notOnPane;
3196
3198
  problems.push({ check: "executable", ok: false, detail: notOnPane.message, code: notOnPane.code });
3197
3199
  } else if (!executable.path && !config?.executable && launchChoice) {
@@ -3200,7 +3202,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3200
3202
  problems.push({ check: "executable", ok: false, detail: e.message, code: e.code });
3201
3203
  }
3202
3204
  const exeProblem = executable.path ? checkLaunchExecutable(executable.path) : notOnPane || (!config?.executable && launchChoice) ? null : executable.missing;
3203
- if (exeProblem) fail("executable", "E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${exeProblem}`); else if (!notOnPane) problems.push({ check: "executable", ok: true, detail: `${executable.path} (${executable.resolvedFrom})${lookupNote ? `; ${lookupNote}` : ""}` });
3205
+ if (sessionProvider) { /* a session provider's launch was judged above: it has no executable */ } else if (exeProblem) fail("executable", "E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${exeProblem}`); else if (!notOnPane) problems.push({ check: "executable", ok: true, detail: `${executable.path} (${executable.resolvedFrom})${lookupNote ? `; ${lookupNote}` : ""}` });
3204
3206
  // Capability contributions: recorded at spawn with provenance; a harness
3205
3207
  // switch needs the new harness's launch args from the same capabilities.
3206
3208
  let hooks = { launch: {}, env: {}, contributions: [], pending: true };
@@ -3213,7 +3215,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3213
3215
  // too (it runs them for real once its preflight passed); the others run
3214
3216
  // here for real on a start, and not at all for a preview.
3215
3217
  try {
3216
- hooks = prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, contextDir, extraEnv: harnessExecutableEnv(executable.path, executablePaneSide), assertRoots, pass: preview ? "preview" : "plan" });
3218
+ hooks = prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, contextDir, extraEnv: harnessExecutableEnv(executable.path, executablePaneSide), assertRoots, pass: noHooks ? "none" : preview ? "preview" : "plan" });
3217
3219
  const current = new Map((resolvedCfg?.capabilities || []).map((c) => [c.id, c]));
3218
3220
  const untrusted = hooks.contributions.filter((c) => c.capability && current.has(c.capability) && !current.get(c.capability).trust?.trusted).map((c) => c.capability);
3219
3221
  const inactive = hooks.contributions.filter((c) => c.capability && !current.has(c.capability)).map((c) => c.capability);
@@ -3240,7 +3242,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3240
3242
  const missing = missingLaunchEnvRefs(configEnv, env);
3241
3243
  if (missing.length) fail("environment", "E_LAUNCH_ENV_MISSING", missing.some((name) => name.startsWith("file:")) ? launchEnvMissingMessage(missing, harness) : `launch configuration ${config?.name} references ${missing.join(", ")}, not set on this host; nothing was stopped or started${fileReferenceRemedy(missing, harness)}`);
3242
3244
  else if (!owned.length) problems.push({ check: "environment", ok: true, detail: `${Object.keys(configEnv).length} value(s), references resolved on the execution host at start` });
3243
- const login = claudeLoginCredential({ harness, configEnv, hooksEnv: hooks.env, launch: launchEnvironment({ configEnv, capabilities: { env: hooks.env }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) });
3245
+ const login = sessionProvider ? null : claudeLoginCredential({ harness, configEnv, hooksEnv: hooks.env, launch: launchEnvironment({ configEnv, capabilities: { env: hooks.env }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) });
3244
3246
  if (login?.code) fail("credentials", login.code, login.message);
3245
3247
  problems.push({ check: "model", ok: true, detail: model ? `${model} (${modelSource})` : `native default (${modelSource})` });
3246
3248
  // Harness package requirements: the captured providers' (bindings united
@@ -3252,16 +3254,20 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3252
3254
  // package probe (it must never start a conversation), which is stated. A pane
3253
3255
  // whose environment cannot be read is refused with its own code, and one that
3254
3256
  // is not established is probed with what the item names.
3255
- if (executable.path && !missing.length && !owned.length) {
3257
+ // A session provider's launch has no pane and no executable of its own: a requirement that
3258
+ // applies to it (a row without `backends`, or one that names `session-provider`) is probed on
3259
+ // this host with the harness found on this process's PATH, the conservative reading.
3260
+ const requirementsBackend = sessionProvider ? sessionProvider.backend : "tmux";
3261
+ if ((executable.path || sessionProvider) && !missing.length && !owned.length) {
3256
3262
  const providers = frozen
3257
3263
  ? capturedProviders(meta, frozen).map((p) => { const dir = launchManifestDir(home, meta); const manifest = dir ? capabilityManifest(p.id, dir) : undefined; return manifest ? { id: p.id, manifest, settings: p.settings } : null; }).filter(Boolean)
3258
3264
  : (resolvedCfg?.capabilities || []);
3259
- const declared = applicableRequirements(harness, providers).length > 0;
3265
+ const declared = applicableRequirements(harness, providers, requirementsBackend).length > 0;
3260
3266
  if (declared && (config?.args || []).length) {
3261
3267
  // The controlled probe cannot carry configuration arguments, so with
3262
3268
  // an applicable requirement a launch under such arguments cannot be
3263
3269
  // reported verified: refused, truthfully, with the way out.
3264
- fail("harness-packages", "E_LAUNCH_PROBE_UNSUPPORTED", requirementsWithArgsMessage(harness, providers, config));
3270
+ fail("harness-packages", "E_LAUNCH_PROBE_UNSUPPORTED", requirementsWithArgsMessage(harness, providers, config, requirementsBackend));
3265
3271
  } else if (declared) {
3266
3272
  // The check fails with the code the gate refused with, never another name for it (#1047):
3267
3273
  // E_HARNESS_RESOURCE_MISSING, or E_RUNTIME_ENDPOINT_UNKNOWN for a pane whose environment it
@@ -3270,26 +3276,25 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3270
3276
  try {
3271
3277
  // The probe's answer also holds what the capabilities set, over the same read of the pane.
3272
3278
  const probeLaunch = launchEnvironment({ configEnv, configName: config?.name, capabilities: { env: hooks.env, owner: (name) => hooks.contributions.find((c) => (c.env || []).includes(name))?.capability }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home });
3273
- verifyHarnessPackages(harness, { capabilities: providers }, contextDir, { ...(config?.executable || config?.frozen ? { bin: executable.path } : {}), env: probeEnvironment(() => launchEffectiveEnv({ base: env, hooksEnv: hooks.env, configEnv, launch: probeLaunch, harness }), probeLaunch, harness, executable.path) });
3279
+ verifyHarnessPackages(harness, { capabilities: providers }, contextDir, { backend: requirementsBackend, ...(!sessionProvider && (config?.executable || config?.frozen) ? { bin: executable.path } : {}), env: probeEnvironment(() => launchEffectiveEnv({ base: env, hooksEnv: hooks.env, configEnv, launch: probeLaunch, harness }), probeLaunch, harness, executable.path) });
3274
3280
  const probeNote = unestablishedNote(probeLaunch, probeNames(harness));
3275
- problems.push({ check: "harness-packages", ok: true, detail: `verified with ${executable.path}${(config?.args || []).length ? "; configuration arguments are not applied to the probe: native configuration the packages must see belongs in a wrapper or the environment" : ""}${probeNote ? `; ${probeNote}` : ""}` });
3281
+ problems.push({ check: "harness-packages", ok: true, detail: `verified with ${executable.path ?? `${harness} on this host`}${(config?.args || []).length ? "; configuration arguments are not applied to the probe: native configuration the packages must see belongs in a wrapper or the environment" : ""}${probeNote ? `; ${probeNote}` : ""}` });
3276
3282
  } catch (e) { if (!["E_HARNESS_RESOURCE_MISSING", "E_RUNTIME_ENDPOINT_UNKNOWN"].includes(e?.code)) throw e; fail("harness-packages", e.code, e.message); }
3277
3283
  } else problems.push({ check: "harness-packages", ok: true, detail: "no harness package requirement declared for this harness; nothing probed" });
3278
3284
  }
3279
3285
  const recipe = {
3280
3286
  version: LAUNCH_RECIPE_VERSION, harness, launchConfig: config?.name || null, launchConfigSource: config?.source || null, ...(config?.harnessDefault ? { launchConfigDefault: true } : {}),
3281
- executable: executable.path || executable.declared || harness, executableDeclared: executable.declared ?? null, executableResolvedFrom: executable.resolvedFrom,
3287
+ executable: sessionProvider ? null : executable.path || executable.declared || harness, executableDeclared: executable.declared ?? null, executableResolvedFrom: executable.resolvedFrom,
3282
3288
  args: [...(config?.args || [])], env: { ...configEnv }, model: model || null, ...(yolo !== undefined ? { yolo } : {}),
3283
3289
  hooks: frozen ? { launch: hooks.launch, env: hooks.env, contributions: hooks.contributions } : hooks, prompt: LAUNCH_PROMPT, kernelBin: kernelBin(),
3284
3290
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3285
3291
  };
3286
- const inst = instance || meta?.instance || basename(home);
3287
3292
  const trustLaunch = removedEnv.length ? launchEnvironment({ configEnv: config?.env, configName: config?.name, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) : launchEnv;
3288
- const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3289
- const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3293
+ const { trustHome } = sessionProvider ? { trustHome: false } : launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3294
+ const command = sessionProvider ? undefined : renderLaunchRecipe(recipe, { home, instance: instance || meta?.instance || basename(home), trustHome });
3290
3295
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3291
3296
  // A preview states what the start will do; the start states it in its own output.
3292
- const previewNotices = preview ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3297
+ const previewNotices = preview && !sessionProvider ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3293
3298
  return { recipe, command, trustHome, declaredEnv, removedEnv, harness, model: model || undefined, modelSource, yolo, config, executable, executablePaneSide, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...previewNotices], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}), ...(hooks.dialogClaims ? { hookDialogClaims: hooks.dialogClaims } : {}) };
3294
3299
  }
3295
3300
  /** The names a package probe of `harness` depends on: where its program is found and runs, the
@@ -3370,6 +3375,272 @@ export function describeLaunchCommand(command) {
3370
3375
  const argv = tokens.slice(binary + 1).map((t) => t.kind === "sep" ? "--" : t.kind === "prompt" ? t.text : t.value);
3371
3376
  return { executable: tokens[binary].value, argv, environment };
3372
3377
  }
3378
+ // ------------------------------------------------------------ session providers (lib/session-providers.mjs)
3379
+
3380
+ /** What a session provider's `launch` is handed (docs/capabilities.md "Session providers"): the
3381
+ * launch a tmux window would run, as data. `env`: every variable the launch sets, in the order a
3382
+ * window's command sets them, each with its `source`, so a provider can refuse one it cannot carry
3383
+ * safely: `kernel` (the instance's identity, a trigger's event file), `capability` (a hook's, with
3384
+ * the `capability` that owns it), `launch-config` (a configuration's literal) or
3385
+ * `launch-config-reference` (a configuration's fromEnv/fromFile: a secret source, `secret: true`,
3386
+ * its value read on this host as a window's would be). `unset`: the names the launch removes.
3387
+ * `pathPrepend`: the home's kernel shim directory, first on a window's PATH, so the agent's plain
3388
+ * `oats` is this kernel. `args`: the configuration's arguments, then the capabilities' launch
3389
+ * arguments for the harness; never the kernel's own flags, which are `model`, `yolo` and the
3390
+ * prompt (`promptFile`, the home's TASK.md). `previous`: the endpoint of the session this launch
3391
+ * replaces (a start, a restart), null for a home's first launch. */
3392
+ /** The trees of a home, as a provider's launch (and its check) is handed them: `<home>/work`,
3393
+ * always and first, then every extra tree of the home by its name. An extra tree is what Git
3394
+ * itself says is one (extraWorktreesOf: a `.work-*` directory that is a registered linked
3395
+ * worktree of a repository outside the home), read with the kernel's hardened Git; nothing of
3396
+ * the home's own record (instance.json) names a tree. Absolute paths.
3397
+ *
3398
+ * A provider that sandboxes its harness keeps each tree's Git pointer, configuration and hooks
3399
+ * unwritable. A limit, for such a provider to know: the list of a repository's worktrees is in
3400
+ * its common Git directory, which a session that can write there can shorten; a tree taken off
3401
+ * that list is no longer sent. `<home>/work` always is. */
3402
+ function homeTrees(home) {
3403
+ return [join(home, "work"), ...extraWorktreesOf(home).map((tree) => tree.path)];
3404
+ }
3405
+ /** The kernel's own state for a home, as a provider's launch (and its check) is handed it:
3406
+ * directories a sandboxed agent must never write, and that a provider must not block reading or
3407
+ * executing. One entry: `<instances>/.oats-retirement/`, which holds the kernel's copies of the
3408
+ * home's modules (lib/home-integrity.mjs: what the kernel runs, and where the home's hooks point
3409
+ * the harness), the receipts, the claims and the provider calls in flight. Each is made here
3410
+ * when it is missing (a deployment's first home), so that a provider that refuses a launch for
3411
+ * a missing one refuses a fault and never a first launch. Never derived from the home's record. */
3412
+ function homeProtected(home) {
3413
+ const paths = [instancesRetirementRoot(dirname(canonicalHomePath(home)))];
3414
+ for (const path of paths) mkdirSync(path, { recursive: true, mode: 0o700 });
3415
+ return paths;
3416
+ }
3417
+ function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [], previous = null, sandbox }) {
3418
+ const env = [{ name: "OATS_INSTANCE", value: instance, source: "kernel" }, { name: "OATS_INSTANCE_HOME", value: home, source: "kernel" }];
3419
+ const hookEnv = recipe.hooks?.env || {};
3420
+ const owner = (name) => (recipe.hooks?.contributions || []).find((c) => (c.env || []).includes(name))?.capability ?? null;
3421
+ for (const name of Object.keys(hookEnv).sort()) env.push({ name, value: hookEnv[name], source: "capability", capability: owner(name) });
3422
+ for (const name of Object.keys(recipe.env || {}).sort()) {
3423
+ const value = recipe.env[name];
3424
+ if (typeof value === "string") env.push({ name, value, source: name.startsWith("OATS_") ? "kernel" : "launch-config" });
3425
+ else {
3426
+ const resolved = referenceValue(value, hostEnv);
3427
+ if (resolved === undefined) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage([referenceSource(value)], recipe.harness));
3428
+ env.push({ name, value: resolved, source: "launch-config-reference", secret: true });
3429
+ }
3430
+ }
3431
+ // A capability's launch arguments are a string in the grammar a launch command is written in:
3432
+ // read as the words a window's shell would hand the harness (the stand-in binary is never sent).
3433
+ const hookArgs = recipe.hooks?.launch?.[recipe.harness] || "";
3434
+ let hookWords = [];
3435
+ if (hookArgs.trim()) {
3436
+ try { hookWords = parseLaunchCommand(`${shq("harness")} ${hookArgs}`).tokens.slice(1).map((t) => t.value ?? t.text); } catch (e) {
3437
+ const owners = (recipe.hooks?.contributions || []).filter((c) => c.launch?.[recipe.harness]).map((c) => c.capability);
3438
+ throw Object.assign(oatsError("E_BACKEND_LAUNCH_ARG", `${instance} cannot be launched on a session provider: the ${recipe.harness} launch arguments of ${owners.length ? owners.join(", ") : "a capability"} (${JSON.stringify(hookArgs)}) cannot be read as words (${e?.message ?? e}); nothing was launched`), { details: { field: "args", capabilities: owners } });
3439
+ }
3440
+ }
3441
+ return {
3442
+ home, instance, harness: recipe.harness, model: recipe.model ?? null, yolo: recipe.yolo ?? null,
3443
+ env, unset: [...removed], pathPrepend: [kernelShimDir(home)],
3444
+ args: [...(recipe.args || []), ...hookWords], promptFile: join(home, "TASK.md"), previous,
3445
+ // What the provider may widen its harness's sandbox by, and nothing else (lib/sandbox-allowances.mjs).
3446
+ ...(sandbox ? { sandbox } : {}),
3447
+ // The home's trees (homeTrees): what a provider that sandboxes protects the Git files of.
3448
+ trees: homeTrees(home),
3449
+ // The kernel's own state (homeProtected): never written by a sandboxed agent.
3450
+ protected: homeProtected(home),
3451
+ };
3452
+ }
3453
+ /** A home's record of its capabilities' runtime (`capabilityRuntime`), one row per capability of
3454
+ * the spawn's resolution. */
3455
+ const capabilityRuntimeRows = (resolvedCfg) => resolvedCfg.capabilities.map((cap) => ({
3456
+ id: cap.id, layer: cap.layer, level: cap.level, settings: cap.settings, settingsOrigins: cap.settingsOrigins ?? {},
3457
+ hooks: cap.hooks, requiredHooks: cap.requiredHooks, environment: cap.environment, environmentNamespaces: cap.environmentNamespaces,
3458
+ missingRequires: cap.missingRequires, trust: cap.trust,
3459
+ executable: cap.executable,
3460
+ }));
3461
+ /** The launch that is planned, as a provider's `check` is handed it BEFORE any hook runs:
3462
+ * `{ harness, yolo, args, sandbox, trees, protected }`. `args` are the launch configuration's own: the
3463
+ * arguments a capability's hooks contribute are not known yet, and reach the launch input only.
3464
+ * `trees` and `protected` are the launch input's (homeTrees, homeProtected): a provider that
3465
+ * would refuse a launch for either refuses it here, before a restart stops anything. */
3466
+ const plannedLaunch = ({ home, harness, yolo, args, sandbox }) => ({ harness, yolo: yolo ?? null, args: [...(args || [])], ...(sandbox ? { sandbox } : {}), trees: homeTrees(home), protected: homeProtected(home) });
3467
+ /** A home's independent session receipt, read to be written again with another `runtime` → `{ path,
3468
+ * baseline }`. Refused as every writer of it refuses: E_RUNTIME_ENDPOINT_UNKNOWN for a receipt that
3469
+ * is missing, unreadable, of another home, or that authorises nothing. */
3470
+ function readSessionReceipt(home) {
3471
+ const path = findRetirementBaseline(home);
3472
+ let baseline;
3473
+ try { baseline = JSON.parse(readFileSync(path, "utf8")); } catch (e) {
3474
+ if (e.code === "ENOENT") throw missingSessionReceipt(home);
3475
+ throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or unreadable for ${home}: ${e.message}`);
3476
+ }
3477
+ if (baseline.version !== RETIRE_BASELINE_VERSION || !receiptRecordsHome(baseline, canonicalHomePath(home)) || !runtimeAuthorityOf(baseline)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is invalid for ${home}`);
3478
+ return { path, baseline };
3479
+ }
3480
+ /** Record a provider home's runtime in its independent receipt: `session` is `{ backend, provider,
3481
+ * endpoint, stoppedAt? }`. The one writer after the spawn's own baseline: a launch's
3482
+ * endpoint, a stop's `stoppedAt`, a start's clearing of it. Only `runtime` changes. */
3483
+ function writeProviderRuntime(home, session) {
3484
+ const { path, baseline } = readSessionReceipt(home);
3485
+ // A launch that was sent and has no recorded outcome stays marked through every write of the
3486
+ // runtime (a stop's `stoppedAt`, the launch's own endpoint): only clearLaunchSent and
3487
+ // recordLaunchSettled take the mark away, as the last write of what they end.
3488
+ baseline.runtime = providerRuntimeRecord({ ...session, launchSent: launchSentOf(baseline.runtime) ?? null });
3489
+ writeJsonAtomic(path, baseline, 0o600);
3490
+ }
3491
+ function setRecordLaunched(home, launched) {
3492
+ const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
3493
+ if (meta.launched !== launched) writeHomeRecord(home, { ...meta, launched });
3494
+ }
3495
+ /** Record, in the home's receipt, that a launch is being sent to its provider (launchSentOf), right
3496
+ * before the provider is called → the instant recorded. It is taken away once the launch is
3497
+ * known to have started nothing (clearLaunchSent), once what it started is known to be stopped
3498
+ * (recordLaunchSettled), or once its outcome is recorded (recordLaunchOutcome).
3499
+ *
3500
+ * A home that was never launched has no endpoint to keep. Meanwhile its runtime reads `{ launched:
3501
+ * true, backend, provider, launchSent }` and its record (instance.json) `launched: true`, with no
3502
+ * endpoint in either: to a kernel from before session providers that is a launch it cannot
3503
+ * address, which it refuses for every verb, a retire included, where "never launched" would read
3504
+ * as a home it may remove. Both go back to not launched when the launch is settled. The receipt
3505
+ * is written first and cleared last, and this kernel takes either value of the record's
3506
+ * `launched` beside it (lib/session-inspect.mjs launchStateAgrees). */
3507
+ function markLaunchSent(home) {
3508
+ const { path, baseline } = readSessionReceipt(home);
3509
+ const launchSent = new Date().toISOString();
3510
+ const launchedBefore = baseline.runtime.launched === true && baseline.runtime.endpoint !== undefined;
3511
+ baseline.runtime = launchedBefore ? { ...baseline.runtime, launchSent } : { launched: true, backend: baseline.runtime.backend, provider: baseline.runtime.provider, launchSent };
3512
+ writeJsonAtomic(path, baseline, 0o600);
3513
+ dieAt("mark:receipt-written");
3514
+ if (!launchedBefore) setRecordLaunched(home, true);
3515
+ return launchSent;
3516
+ }
3517
+ /** Whether the home's receipt (outside the home) names a session provider; false when it has none
3518
+ * or it cannot be read. */
3519
+ function receiptNamesProvider(home) {
3520
+ try { return typeof readSessionReceipt(home).baseline.runtime?.provider === "string"; } catch { return false; }
3521
+ }
3522
+ /** A launch's outcome, for a spawn's first launch and for a start alike, in three writes: the
3523
+ * receipt's endpoint with the launch still marked as sent, the record, then the mark removed.
3524
+ * Killed between any two, the home is unsettled, never one whose record contradicts its receipt.
3525
+ * A failure of the first write recorded nothing; one after it is in `outcomeRecordFailures` (the
3526
+ * receipt names the session by then, still marked as sent: the home is unsettled). */
3527
+ const outcomeRecordFailures = new WeakSet();
3528
+ function recordLaunchOutcome(home, runtime, record, { keepMark = false } = {}) {
3529
+ writeProviderRuntime(home, runtime);
3530
+ dieAt("outcome:receipt-written");
3531
+ try {
3532
+ writeHomeRecord(home, record);
3533
+ dieAt("outcome:record-written");
3534
+ // (`keepMark`: a spawn, which has writes of its own to make yet, and removes the mark after
3535
+ // the last: until then the home is unsettled, so no input is admitted to a home whose spawn
3536
+ // may still be undone.)
3537
+ if (!keepMark) clearLaunchSent(home);
3538
+ } catch (e) { if (e && typeof e === "object") outcomeRecordFailures.add(e); throw e; }
3539
+ }
3540
+ /** Unmark a launch that is known to have started nothing (the provider refused it): the home is
3541
+ * as it was before the mark. The record first, then the receipt. */
3542
+ function clearLaunchSent(home) {
3543
+ const { path, baseline } = readSessionReceipt(home);
3544
+ if (baseline.runtime?.launchSent === undefined) return;
3545
+ const { launchSent: _settled, ...runtime } = baseline.runtime;
3546
+ if (runtime.endpoint === undefined) setRecordLaunched(home, false);
3547
+ dieAt("unmark:record-written");
3548
+ baseline.runtime = runtime.endpoint === undefined ? { launched: false, backend: runtime.backend, provider: runtime.provider } : runtime;
3549
+ writeJsonAtomic(path, baseline, 0o600);
3550
+ }
3551
+ /** The records of a home whose spawn failed after its launch was sent, once the provider confirmed
3552
+ * that nothing runs for it, and which the spawn keeps for another debt: PLANNED, the record
3553
+ * first, then the receipt (where there is one). `planned`: `{ backend, provider }`. */
3554
+ function recordProviderPlanned(home, planned) {
3555
+ const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
3556
+ writeHomeRecord(home, { ...meta, launched: false, backend: planned.backend, session: { ...(isPlainObject(meta.session) ? meta.session : {}), provider: planned.provider, endpoint: null } });
3557
+ // (Killed here, the receipt still says the launch was sent: unsettled, and the record is not
3558
+ // compared; the next verb settles the home.)
3559
+ dieAt("rollback:record-written");
3560
+ if (!existsSync(retirementBaselinePath(home))) return;
3561
+ const { path, baseline } = readSessionReceipt(home);
3562
+ baseline.runtime = { launched: false, backend: planned.backend, provider: planned.provider };
3563
+ writeJsonAtomic(path, baseline, 0o600);
3564
+ }
3565
+ /** The records of a home whose sent launch the provider has confirmed stopped: no session of that
3566
+ * launch runs, and the one before it was stopped before the launch was marked, so nothing does.
3567
+ * A home with no endpoint is PLANNED again; one with an endpoint is STOPPED (`stoppedAt` set
3568
+ * when it was not; the stop is an operator's, unless the home's stop receipt already says the
3569
+ * host's). The record is rewritten to agree first (it was not compared while the launch was
3570
+ * unsettled), then the receipt, which is what ends the unsettled state. */
3571
+ function recordLaunchSettled(home) {
3572
+ const { path, baseline } = readSessionReceipt(home);
3573
+ const { launchSent, ...runtime } = baseline.runtime;
3574
+ if (launchSent === undefined) return;
3575
+ const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
3576
+ const session = { ...(isPlainObject(meta.session) ? meta.session : {}), provider: runtime.provider };
3577
+ if (runtime.endpoint === undefined) {
3578
+ writeHomeRecord(home, { ...meta, launched: false, backend: runtime.backend, session: { ...session, endpoint: null } });
3579
+ baseline.runtime = { launched: false, backend: runtime.backend, provider: runtime.provider };
3580
+ } else {
3581
+ const agreed = { ...meta, launched: true, backend: runtime.backend, session: { ...session, endpoint: runtime.endpoint } };
3582
+ writeHomeRecord(home, agreed);
3583
+ // The host's stop only when the home was stopped before this launch: a stop receipt beside a
3584
+ // home that was running is an earlier stop's, left by a resume that died.
3585
+ if (runtime.stoppedAt == null || lostReasonOf(home, agreed) !== HOST_STOP_REASON) { try { recordStop(home, null); } catch { /* the receipt below is the authority */ } }
3586
+ baseline.runtime = { ...runtime, stoppedAt: runtime.stoppedAt ?? new Date().toISOString() };
3587
+ }
3588
+ dieAt("settle:record-written");
3589
+ writeJsonAtomic(path, baseline, 0o600);
3590
+ }
3591
+ /** Ask a provider home's backend to stop a session, giving it `graceMs`, never escalated → null
3592
+ * when it confirmed, else why not, in one sentence: the provider failed or refused, or its
3593
+ * capability is no longer among the home's modules. `recorded`: the receipt's `{ backend,
3594
+ * provider }`. `endpoint`: the recorded one, or null for whatever session is rooted at the home
3595
+ * (with `launchSent`, the instant of the launch that may have started it). Its stop is
3596
+ * idempotent, so every OATS act that needs the session gone asks: a stop, a restart, a start
3597
+ * after a stop, a retire, a settle. */
3598
+ function providerStopUnconfirmed(home, meta, recorded, endpoint, graceMs = 20000, io, launchSent = null, { outlasted } = {}) {
3599
+ // First, the provider calls recorded for this home (drainProviderCalls): a command of the
3600
+ // provider that still runs, or runs later, could start a session after the stop asked for here.
3601
+ // Every caller has written its fence by now (`stoppedAt`, or a launch's mark), so no new input
3602
+ // is admitted meanwhile.
3603
+ const left = drainProviderCalls(home, { outlasted });
3604
+ if (left) return left;
3605
+ const found = homeSessionProvider(home, meta, recorded.provider, recorded.backend);
3606
+ if (found.problem) return found.problem;
3607
+ return trackedProviderStop(home, found.binding, endpoint, Math.max(1, Math.ceil(graceMs / 1000)), { io, launchSent }).failed ?? null;
3608
+ }
3609
+ /** The provider's stop, as EVERY stop the kernel sends is sent: recorded as a call while it runs
3610
+ * (markProviderCall). A stop is a call like another: one whose kernel ends during it would run
3611
+ * late, and stop a session launched or resumed since (a stop of what is rooted at the home stops
3612
+ * whatever was created after its `launchSent`). Recorded, it is ended before a launch, an input
3613
+ * or a resume is sent to the home, and by the drain of the next stop (endProviderCalls,
3614
+ * drainProviderCalls). The policy (fence, drain) is the caller's. → stopProviderSession's answer. */
3615
+ function trackedProviderStop(home, binding, endpoint, graceSeconds, { io, launchSent = null } = {}) {
3616
+ let call;
3617
+ try { call = markProviderCall(home, "stop"); }
3618
+ catch (e) { return { failed: `the stop could not be recorded as a call (${e?.code ?? e?.message ?? e}); the session backend was not asked` }; }
3619
+ try { return stopProviderSession(binding, endpoint, graceSeconds, { io, launchSent, groupFile: call.groupFile }); }
3620
+ finally { call.done(); }
3621
+ }
3622
+ /** Settle a launch that was sent to a home's provider and never recorded (`unsettled`:
3623
+ * instanceSessionTarget's, `{ backend, provider, launchSent }`, or null): the provider is asked to
3624
+ * stop whatever session is rooted at the home (`stop` with `endpoint: null` and that instant)
3625
+ * → null when there was none to settle or the provider confirmed (the record is then taken
3626
+ * away), else why not, in one sentence; the record then stays, and the next verb asks again.
3627
+ * The one place a home is settled: a stop's, a start's, a retire's. */
3628
+ function settleSentLaunch(home, meta, unsettled, graceMs = 20000, io, { recordedStopped = false } = {}) {
3629
+ if (!unsettled?.launchSent) return null;
3630
+ // A home launched before: its recorded session first. The stop of what the sent launch started
3631
+ // does not reach a session older than that launch, and a settle records the home stopped: it
3632
+ // is never done over a session at the recorded endpoint that was not confirmed stopped.
3633
+ // (`recordedStopped`: the caller has just had that confirmed, under this same claim.)
3634
+ if (!recordedStopped) {
3635
+ const endpoint = readSessionReceipt(home).baseline.runtime.endpoint;
3636
+ const old = endpoint === undefined ? null : providerStopUnconfirmed(home, meta, unsettled, endpoint, graceMs, io);
3637
+ if (old) return old;
3638
+ }
3639
+ const why = providerStopUnconfirmed(home, meta, unsettled, null, graceMs, io, unsettled.launchSent);
3640
+ if (why === null) recordLaunchSettled(home);
3641
+ return why;
3642
+ }
3643
+
3373
3644
  /** Spawn. With `o.prepared` (workspace model: a resolution prepared by
3374
3645
  * instance-resolution.mjs) this is ASYNC — capabilities are fetched and copied
3375
3646
  * into the home. Without it (classic soul-directory spawn: schedules, tests,
@@ -3513,6 +3784,8 @@ export async function spawnInstanceAsync(root, agent, o = {}) {
3513
3784
  /** The command a spawn's answer gives to attach to its instance: the tmux session of its window when
3514
3785
  * it was launched (`meta.tmux` then names the socket), else the session surface by home. */
3515
3786
  function spawnAttach(meta, launched) {
3787
+ // A session provider's session has no terminal to attach to: inspect's `open` is what a client shows.
3788
+ if (meta.session) return null;
3516
3789
  return launched ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(meta.tmux.session)}` : `oats session attach --home ${shellWord(meta.home)}`;
3517
3790
  }
3518
3791
  /** The producer sets this only when dispatched effects or their compensation
@@ -3538,7 +3811,7 @@ function* spawnBody(root, agent, o = {}) {
3538
3811
  const backend = o.backend || "tmux";
3539
3812
  if (backend === "herdr") throw herdrSettingRemoved("backend herdr was given");
3540
3813
  if (o.herdrSocket !== undefined) throw herdrSettingRemoved("herdrSocket was given");
3541
- if (backend !== "tmux") throw new Error(`unknown session backend "${backend}" (tmux)`);
3814
+ if (typeof backend !== "string") throw oatsError("E_BAD_ARGS", "backend must be a session backend's name");
3542
3815
  const launch = o.launch !== false;
3543
3816
  // Workspace model (`o.prepared`) + work: workspace: ./work is the deployment
3544
3817
  // boundary — the directory holding oats-local.yaml (`prepared.deployment`), which
@@ -3576,6 +3849,41 @@ function* spawnBody(root, agent, o = {}) {
3576
3849
  const launchConfig = launchSelection.config;
3577
3850
  const harness = launchSelection.harness;
3578
3851
  const model = launchSelection.model;
3852
+ // The session backend: tmux, the kernel's own, or a session provider one of this instance's
3853
+ // capabilities declares (lib/session-providers.mjs), decided for the harness this launch selected
3854
+ // and refused before anything is created: E_BACKEND_UNKNOWN, E_BACKEND_AMBIGUOUS, E_BACKEND_HARNESS.
3855
+ // `provider` is null for tmux, else `{ backend, capability, provider }`. A provider runs the
3856
+ // harness itself, so nothing of a pane is planned or checked for it, and no verb carries a
3857
+ // configuration's own executable.
3858
+ let provider;
3859
+ try {
3860
+ const selected = selectSessionBackend(backend, (o.prepared.resolution?.modules || []).map((m) => ({ id: m.name, manifest: m.manifest })), harness);
3861
+ provider = selected.backend === "tmux" ? null : selected;
3862
+ if (provider && launchConfig?.executable) throw Object.assign(oatsError("E_BACKEND_LAUNCH_ARG", `launch configuration ${launchConfig.name} declares an executable (${launchConfig.executable}), and session backend ${backend} runs the harness itself: no executable can be handed to it; use a configuration without one; nothing was created`), { details: { backend, launchConfig: launchConfig.name, field: "executable" } });
3863
+ } catch (e) { previewPreflightBudget = null; throw e; }
3864
+ // The Git settings of this spawn's own tree: for a home on a session provider, no hook and no
3865
+ // file monitor of the repository (lib/instance-git.mjs PROVIDER_TREE_GIT); none for a tmux home.
3866
+ const treeGit = provider ? PROVIDER_TREE_GIT : [];
3867
+ // What the provider may widen its harness's sandbox by (lib/sandbox-allowances.mjs), from the
3868
+ // deployment's own resolution: refused here, before anything is created, when a capability
3869
+ // asks for a host it may not ask for. A tmux launch has none.
3870
+ let sandbox = null;
3871
+ if (provider) {
3872
+ try {
3873
+ const deployment = o.prepared.deployment || workspaceOf(root), eventsDir = sandboxEventsDir(deployment);
3874
+ sandbox = sandboxAllowances({
3875
+ modules: (o.prepared.resolution?.modules || []).map((m) => ({ name: m.name, manifest: m.manifest })),
3876
+ slots: o.prepared.resolution?.slots ?? {}, payloads: o.prepared.resolution?.payloads ?? {}, origins: o.prepared.resolution?.payloadOrigins ?? {},
3877
+ teams: (o.prepared.resolution?.teams ?? []).map((row) => row.team).filter((team) => typeof team === "string"),
3878
+ defaultTeam: typeof o.prepared.resolution?.defaultTeam?.team === "string" ? o.prepared.resolution.defaultTeam.team : null,
3879
+ eventsDir, deployment, outside: [root, eventsDir],
3880
+ });
3881
+ // The paths it names exist, and are what they must be, before anything of the spawn is
3882
+ // created. A preview creates nothing, and refuses what the apply would refuse of them.
3883
+ if (o.preview !== true) ensureSandboxWritePaths(sandbox.write);
3884
+ else { const refused = sandboxWritePathsRefusal(sandbox.write); if (refused) throw refused; }
3885
+ } catch (e) { previewPreflightBudget = null; throw e; }
3886
+ }
3579
3887
  // Instance homes belong in the soul-owning repo's PRIMARY checkout, never in a
3580
3888
  // linked worktree (see canonicalDeploymentPath). The CLI resolves this through
3581
3889
  // ensureRoot, but the kernel is its own validation boundary — the desktop
@@ -3660,7 +3968,7 @@ function* spawnBody(root, agent, o = {}) {
3660
3968
  // any scaffold, work tree, identity or hook, so that an instance that cannot is refused with
3661
3969
  // nothing left behind; the harness is first looked up on the PATH this plan expects (below). A
3662
3970
  // preview reads only what exists.
3663
- const tmuxSessionPlan = launch ? planOatsTmuxSession(session, undefined, { preview: o.preview === true }) : undefined;
3971
+ const tmuxSessionPlan = launch && !provider ? planOatsTmuxSession(session, undefined, { preview: o.preview === true }) : undefined;
3664
3972
 
3665
3973
  // Forward-only lineage: EXPLICIT only. Relations (child|sibling|parent|unrelated)
3666
3974
  // anchor the new instance to an EXISTING instance (o.relativeTo). o.parent
@@ -3960,25 +4268,29 @@ function* spawnBody(root, agent, o = {}) {
3960
4268
  // and the naming call runs that same executable.
3961
4269
  let paneCwd = suggesting ? join(agent._dir, "instances", ".oats-suggest-name") : home;
3962
4270
  const launchEnvOn = (pane, removed = []) => launchEnvironment({ configEnv: launchConfig?.env, configName: launchConfig?.name, removed, env: process.env, pane, cwd: paneCwd });
3963
- const expectedEnv = launchEnvOn(launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, paneCwd) : NO_LAUNCH);
4271
+ const expectedEnv = launchEnvOn(provider ? NO_PANE : launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, paneCwd) : NO_LAUNCH);
3964
4272
  // A launched harness is looked up where its pane will look it up (launchLookup): this is the
3965
4273
  // preflight against the expected PATH; the launch looks again on the session it gets. Without a
3966
4274
  // launch (or a known destination) the lookup is this process's PATH, as before.
3967
4275
  const lookupFor = (launchEnv) => launch && !launchConfig?.executable?.includes("/") ? launchLookup(launchEnv) : undefined;
3968
- const executable = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(expectedEnv) });
3969
- if (!executable.path && executable.lookup) { previewPreflightBudget = null; throw executableNotOnPanePath(executable, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at }); }
4276
+ // A session provider runs the harness itself: no executable is looked up, checked or recorded, and
4277
+ // the checks that run or read one (the login credential, the harness package probe, folder trust)
4278
+ // have nothing to judge.
4279
+ const executable = provider ? { path: null, declared: null, resolvedFrom: `session provider ${backend}` }
4280
+ : resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(expectedEnv) });
4281
+ if (provider) { /* nothing to find */ } else if (!executable.path && executable.lookup) { previewPreflightBudget = null; throw executableNotOnPanePath(executable, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at }); }
3970
4282
  // No executable for the chosen harness (none declared by a configuration): E_HARNESS_UNAVAILABLE names the
3971
4283
  // layer that chose it and the fix. Never a fallback to another harness.
3972
- if (!executable.path && !launchConfig?.executable) { previewPreflightBudget = null; throw harnessUnavailable({ harness, from: launchChoice.from, at: launchChoice.at, why: executable.missing }); }
3973
- if (!executable.path) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig.name}: ${executable.missing}`);
3974
- { const bad = checkLaunchExecutable(executable.path); if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`); }
4284
+ else if (!executable.path && !launchConfig?.executable) { previewPreflightBudget = null; throw harnessUnavailable({ harness, from: launchChoice.from, at: launchChoice.at, why: executable.missing }); }
4285
+ else if (!executable.path) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig.name}: ${executable.missing}`);
4286
+ else { const bad = checkLaunchExecutable(executable.path); if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`); }
3975
4287
  const bin = executable.path;
3976
4288
  const missingRefs = missingLaunchEnvRefs(launchConfig?.env || {}, process.env);
3977
4289
  if (missingRefs.length) throw oatsError("E_LAUNCH_ENV_MISSING", missingRefs.some((name) => name.startsWith("file:")) ? launchEnvMissingMessage(missingRefs, harness) : `launch configuration ${launchConfig.name} references ${missingRefs.join(", ")}, not set in this environment; nothing was created${fileReferenceRemedy(missingRefs, harness)}`);
3978
4290
  const preflightRemoved = removedLaunchEnv({ declared: declaredLaunchEnv(resolvedCfg.capabilities), configEnv: launchConfig?.env });
3979
4291
  // A hook-owned selector has no value until hooks run; its final check remains below.
3980
4292
  const selectorPending = !Object.hasOwn(launchConfig?.env || {}, "CLAUDE_CONFIG_DIR") && resolvedCfg.capabilities.some((cap) => cap.environment?.includes("CLAUDE_CONFIG_DIR") && (cap.hooks?.spawn || cap.hooks?.launch));
3981
- const loginPreflight = selectorPending ? null : claudeLoginCredential({ harness, configEnv: launchConfig?.env, launch: launchEnvOn(expectedEnv.pane, preflightRemoved) });
4293
+ const loginPreflight = selectorPending || provider ? null : claudeLoginCredential({ harness, configEnv: launchConfig?.env, launch: launchEnvOn(expectedEnv.pane, preflightRemoved) });
3982
4294
  if (loginPreflight?.code) throw oatsError(loginPreflight.code, loginPreflight.message);
3983
4295
  // A configuration's executable answers the package probe (without one the
3984
4296
  // context-selected name does, as before: its remedies name that command),
@@ -3989,11 +4301,14 @@ function* spawnBody(root, agent, o = {}) {
3989
4301
  // (awebai/oats#1041). `probed` keeps what the gate judged (null: no
3990
4302
  // requirement applied, so nothing was probed and nothing of the pane was
3991
4303
  // read), to compare with the pane the spawn actually gets.
3992
- if ((launchConfig?.args || []).length && applicableRequirements(harness, resolvedCfg.capabilities).length) throw oatsError("E_LAUNCH_PROBE_UNSUPPORTED", `${requirementsWithArgsMessage(harness, resolvedCfg.capabilities, launchConfig)}; nothing was created`);
4304
+ if ((launchConfig?.args || []).length && applicableRequirements(harness, resolvedCfg.capabilities, backend).length) throw oatsError("E_LAUNCH_PROBE_UNSUPPORTED", `${requirementsWithArgsMessage(harness, resolvedCfg.capabilities, launchConfig, backend)}; nothing was created`);
3993
4305
  let probed = null;
3994
4306
  const recordedHarnessPackages = (found) => found.map((x) => ({ capability: x.capability, harness: x.harness, package: x.package, dir: x.dir, filtered: x.filtered, loadedBy: "harness-discovery" }));
3995
4307
  const probeEnvOn = (launchEnv, selected = bin) => probeEnvironment(() => (probed = launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: launchEnv, harness })), launchEnv, harness, selected);
3996
- const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin } : {}), env: probeEnvOn(expectedEnv) });
4308
+ // A requirement applies to the launch's backend (requirementOnBackend). On a session provider,
4309
+ // which has no pane and no executable of its own, a row that applies is probed on this host,
4310
+ // with the harness found on this process's PATH.
4311
+ const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { backend, ...(launchConfig?.executable ? { bin } : {}), env: probeEnvOn(expectedEnv) });
3997
4312
  // What a preview of a launch says when no pane's environment is established (no server runs, or
3998
4313
  // it could not be read): the checks that read this process's values in its place, in one line
3999
4314
  // that names every name read that way, PATH among them: the lookup of a bare name and the package
@@ -4001,7 +4316,7 @@ function* spawnBody(root, agent, o = {}) {
4001
4316
  // a start checks again on its own session, and it says whose values it read only where it already
4002
4317
  // says something (the folder-trust warning, a refusal of the package gate).
4003
4318
  const previewReadWarning = () => {
4004
- if (!launch) return null;
4319
+ if (!launch || provider) return null;
4005
4320
  const checks = [...(!launchConfig?.executable?.includes("/") && !executable.lookup ? [["the harness lookup", ["PATH"]]] : []), ...(probed ? [["the harness package check", probeNames(harness)]] : [])];
4006
4321
  const note = unestablishedNote(expectedEnv, [...new Set(checks.flatMap(([, names]) => names))]);
4007
4322
  return note ? `${checks.map(([what]) => what).join(", ")}: ${note}` : null;
@@ -4018,7 +4333,9 @@ function* spawnBody(root, agent, o = {}) {
4018
4333
  const left = o.preview === true ? preflightStarted + preflightBudgetMs - Date.now() : own, souls = deploymentSoulNames(root, o.prepared), homes = deploymentInstanceHomes(root);
4019
4334
  let windows;
4020
4335
  const suggestion = yield () => suggestInstanceName({
4021
- harness, bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4336
+ // A session provider's launch has no executable of its own: the naming call runs the
4337
+ // harness found on this host's PATH, as the `requires` probe of such a launch does.
4338
+ harness, bin: provider ? harness : bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4022
4339
  env: () => launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: expectedEnv, harness }),
4023
4340
  taken: (n) => homes.has(n) || souls.has(n) || (windows ??= oatsTmuxWindows(session)).includes(n),
4024
4341
  });
@@ -4117,7 +4434,12 @@ function* spawnBody(root, agent, o = {}) {
4117
4434
  spawnPreviewApi: 2, preview: true, ...(previewWarnings.length ? { warnings: previewWarnings } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
4118
4435
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
4119
4436
  decision, preflight,
4120
- backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
4437
+ // A session provider is one of the instance's own modules: there to launch. Whether its
4438
+ // service is ready is its readiness check's answer (`oats readiness`), not this field's.
4439
+ backendStatus: launch ? { name: backend, installed: provider ? true : !!which(backend), started: false } : null,
4440
+ // What a session provider may widen its harness's sandbox by: each host with the capability
4441
+ // and the setting that asked for it, each path with its reason. Absent for tmux.
4442
+ ...(sandbox ? { sandbox } : {}),
4121
4443
  harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4122
4444
  background, ...(backgroundFrom ? { backgroundFrom } : {}),
4123
4445
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
@@ -4144,7 +4466,7 @@ function* spawnBody(root, agent, o = {}) {
4144
4466
  // Backend PRESENCE is a prerequisite, checked before anything is placed (M1):
4145
4467
  // an absent tmux binary must fail with nothing created, never after a
4146
4468
  // populated home exists.
4147
- if (launch && !which(backend)) throw new Error(`${backend} not installed (brew install tmux); nothing was created`);
4469
+ if (launch && !provider && !which(backend)) throw new Error(`${backend} not installed (brew install tmux); nothing was created`);
4148
4470
  // Exclusive placement reservation: the parent may be created, the home
4149
4471
  // itself never with `recursive` — EEXIST means another spawn (a concurrent
4150
4472
  // apply of the same decision, or anything else) got here first, and this one
@@ -4157,6 +4479,7 @@ function* spawnBody(root, agent, o = {}) {
4157
4479
  if (e?.code === "EEXIST") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${instance} already exists at ${home} (a concurrent spawn won the placement); nothing was created by this call`), { instance, home });
4158
4480
  throw e;
4159
4481
  }
4482
+ removeStaleReceipt(home);
4160
4483
  const createdHomeIdentity = directoryIdentity(home);
4161
4484
  // Names are deployment-wide, but the reservation above is per soul: a concurrent
4162
4485
  // spawn of ANOTHER soul under the same name reserves its own directory. Re-check
@@ -4408,7 +4731,8 @@ function* spawnBody(root, agent, o = {}) {
4408
4731
  }
4409
4732
  let added = false;
4410
4733
  try {
4411
- execFileSync("git", [...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4734
+ // (A provider home's tree: no hook of the repository runs, here or in the rollback: PROVIDER_TREE_GIT.)
4735
+ execFileSync("git", [...treeGit, ...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4412
4736
  { stdio: ["ignore", "pipe", "pipe"] });
4413
4737
  added = true;
4414
4738
  // Git registers a canonical path. Retain it now: compensation hooks can
@@ -4422,7 +4746,7 @@ function* spawnBody(root, agent, o = {}) {
4422
4746
  // Capture every failure and verify Git effects; because canonical
4423
4747
  // identity was unavailable, never claim confirmed worktree absence.
4424
4748
  const run = (argv) => {
4425
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4749
+ try { return { ok: true, out: execFileSync(argv[0], [...treeGit, ...argv.slice(1)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4426
4750
  // With encoding:"utf8" a silent command yields stderr === "" — FALSY — so
4427
4751
  // `e2.stderr || e2.message` fell through to "Command failed: …" and made
4428
4752
  // every clean probe look like a failed one. `git rev-parse --verify
@@ -4440,7 +4764,7 @@ function* spawnBody(root, agent, o = {}) {
4440
4764
  else incomplete.push(`git worktree ${wt}: could not verify removal (canonical path unavailable after add)`);
4441
4765
  incomplete.push(...deleteBranchAsCreated(run, repoAbs, branch, plannedBase.oid));
4442
4766
  }
4443
- try { rmSync(home, { recursive: true, force: true }); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4767
+ try { rmSync(home, { recursive: true, force: true }); removeModulesStore(home); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4444
4768
  const note = incomplete.length ? ` — rollback INCOMPLETE — clean up manually: ${incomplete.join("; ")}` : "";
4445
4769
  const error = new Error(`git worktree add/canonicalization failed: ${original}${note}`);
4446
4770
  throw incomplete.length ? unconfirmedSpawn(error) : error;
@@ -4477,7 +4801,16 @@ function* spawnBody(root, agent, o = {}) {
4477
4801
  // A hook may replace either path; it must never mint authority for that target.
4478
4802
  if (work === "directory") {
4479
4803
  assertDirectoryRoots(home, homeReal);
4480
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false });
4804
+ // (A provider home's names its provider from the first: a spawn killed after its planned record
4805
+ // then leaves a receipt that agrees with it.)
4806
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: { backend, provider: provider.capability } } : { launched: false });
4807
+ } else if (provider) {
4808
+ // A provider home, in every other work mode too: its receipt, and with it the kernel's own
4809
+ // copies of its modules (lib/home-integrity.mjs), are made HERE, before the provider's check
4810
+ // and before any hook of the spawn. So the spawn's own hooks run from the kernel's copies as
4811
+ // every later hook does, and a path one of them hands the harness is the kernel's. (The
4812
+ // spawn writes the receipt again later, with what it then knows; the composition is kept.)
4813
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: { backend, provider: provider.capability } });
4481
4814
  }
4482
4815
 
4483
4816
  // Capability lifecycle hooks (spawn) — the knowledge integration scaffolds instance
@@ -4514,6 +4847,8 @@ function* spawnBody(root, agent, o = {}) {
4514
4847
  const treeHooks = work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities) : [];
4515
4848
  let worktreeRun = null, treeGuard = null, inProgressMarker = false;
4516
4849
  let hookRes = null;
4850
+ // A home on a session provider: what its receipt records before the first launch gives an endpoint.
4851
+ const plannedSession = provider ? { backend, provider: provider.capability } : null;
4517
4852
  const inProgressStartedAt = new Date().toISOString();
4518
4853
  /** `event`: the hooks the spawn is about to run, or runs, when it writes the marker ("spawn",
4519
4854
  * "worktree"). Until the spawn hooks have answered, each capability with a spawn hook may have
@@ -4542,6 +4877,28 @@ function* spawnBody(root, agent, o = {}) {
4542
4877
  rmSync(join(home, ".oats-rollback-incomplete.json"), { force: true });
4543
4878
  inProgressMarker = false;
4544
4879
  };
4880
+ // The provider's own readiness, with the launch that is planned, BEFORE any hook runs: a launch a
4881
+ // backend says it cannot take (one it would sandbox, without what it needs) is refused with no
4882
+ // hook run, so nothing a hook registers outside the home has to be undone. It needs nothing a
4883
+ // hook produces: the harness, yolo and the allowances are the plan's, and the arguments are the
4884
+ // launch configuration's own (a hook's reach the launch input, not this).
4885
+ let refusedBeforeHooks = null;
4886
+ if (launch && provider) {
4887
+ // (The record is not written yet: the binding is made from what it will hold of the soul, the
4888
+ // capabilities' rows and the workspace, so this call has the environment every later one has.)
4889
+ const planned = { agent: agent.name, instance, home, soulDir: homeSoulTarget, harness, capabilityRuntime: capabilityRuntimeRows(resolvedCfg), ...workspaceRecord };
4890
+ const bound = homeSessionProvider(home, planned, provider.capability, backend);
4891
+ if (bound.binding) bound.binding.soulId = preparedSoulId;
4892
+ const notReady = bound.problem ? null : launchReadinessRefusal(bound.binding, { launch: plannedLaunch({ home, harness, yolo, args: launchConfig?.args, sandbox: sandboxLaunchInput(sandbox) }) });
4893
+ if (bound.problem) refusedBeforeHooks = oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${bound.problem}`);
4894
+ else if (notReady) refusedBeforeHooks = Object.assign(oatsError(notReady.code, `${instance} was not launched: ${notReady.message}`), { details: { backend, capability: provider.capability } });
4895
+ }
4896
+ dieAt("spawn:hooks");
4897
+ if (refusedBeforeHooks) {
4898
+ // No hook runs for a spawn its backend refused: the spawn is undone below as one whose hooks
4899
+ // never ran (the home and its work are removed; nothing was registered outside them).
4900
+ hookRes = { meta: {}, briefs: [], warnings: [], order: [], launch: {}, env: {}, failures: [], contributions: [], volatileEnv: {}, dialogClaims: {} };
4901
+ } else {
4545
4902
  // Write-ahead: what a retire needs to run the retire hooks (the repository they come from, the
4546
4903
  // capabilities, the soul) is on disk before the first spawn hook runs. Until the final record
4547
4904
  // is written, instance.json is the stub lib/materialize.mjs wrote, which names none of it: a
@@ -4552,8 +4909,11 @@ function* spawnBody(root, agent, o = {}) {
4552
4909
  hookRes = runLifecycleHooks("spawn", {
4553
4910
  home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs,
4554
4911
  workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg,
4555
- extraEnv: { OATS_TASK: task, OATS_REPO: repoAbs, OATS_BRANCH: branch || "", OATS_WORK: work, OATS_HARNESS: harness, ...harnessExecutableHanded, OATS_RUNTIME: harness, OATS_KIND: agent.kind || "persistent", ...(triggerEventFile ? { OATS_TRIGGER_EVENT_FILE: triggerEventFile } : {}), ...(spawnedBy ? { OATS_SPAWNER_HOME: spawnedBy.home } : {}) },
4912
+ // OATS_BACKEND: the session backend this instance launches on (`tmux`, or a session provider's
4913
+ // name), also for a spawn that launches nothing: it is what a later start launches on.
4914
+ extraEnv: { OATS_TASK: task, OATS_REPO: repoAbs, OATS_BRANCH: branch || "", OATS_WORK: work, OATS_HARNESS: harness, OATS_BACKEND: backend, ...harnessExecutableHanded, OATS_RUNTIME: harness, OATS_KIND: agent.kind || "persistent", ...(triggerEventFile ? { OATS_TRIGGER_EVENT_FILE: triggerEventFile } : {}), ...(spawnedBy ? { OATS_SPAWNER_HOME: spawnedBy.home } : {}) },
4556
4915
  });
4916
+ }
4557
4917
  // The spawn hooks' receipt (their `meta`), on disk as soon as there is one: a retire after a kill
4558
4918
  // from here on hands it to the retire hooks.
4559
4919
  if (inProgressMarker) {
@@ -4591,6 +4951,21 @@ function* spawnBody(root, agent, o = {}) {
4591
4951
  let promptDispatched = false, promptTarget, promptResult, promptStartId;
4592
4952
  let windowMayExist = false;
4593
4953
  let spawnTmux;
4954
+ // A session provider's launch was sent: `{ binding, endpoint }`, the endpoint null until it answered.
4955
+ let providerSession = null;
4956
+ // The lifecycle claim a provider spawn holds over its home from before the home reads as an
4957
+ // ordinary never-launched one until its launch has been recorded or undone: a stop, a start or
4958
+ // a retire that arrives while the provider launches is busy, as beside any other lifecycle verb,
4959
+ // and never answers that there is nothing to stop while a session is being started.
4960
+ let providerLaunchClaim = null;
4961
+ // A provider home has its receipt BEFORE its record is published, as planned and not launched
4962
+ // (a directory home's and a worktree hook run's are written earlier still), and again after it,
4963
+ // for the digest of the home as the record leaves it. So a spawn that ends between the record
4964
+ // and that last receipt leaves a planned home, record and receipt agreed, never a record
4965
+ // without a receipt; and a spawn that reuses the name of a retired home, whose receipt a retire
4966
+ // keeps by its path, is never paired with that one.
4967
+ const writeEarlyProviderReceipt = () => { if (work !== "directory" && !treeHooks.length) writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: plannedSession }); };
4968
+ const releaseProviderLaunchClaim = () => { if (providerLaunchClaim) { const held = providerLaunchClaim; providerLaunchClaim = null; releaseHomeClaim(held); } };
4594
4969
  const ancillaryCleanup = [];
4595
4970
  // One compensation owner, from the first hook result through launch and
4596
4971
  // the final lineage write. Preserve the original failure and retain any
@@ -4601,13 +4976,45 @@ function* spawnBody(root, agent, o = {}) {
4601
4976
  : [{ capability: "oats.kernel", event: "spawn" }];
4602
4977
  const incomplete = [...ancillaryCleanup];
4603
4978
  const probe = (argv) => {
4604
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4979
+ try { return { ok: true, out: execFileSync(argv[0], [...(argv[0] === "git" ? treeGit : []), ...argv.slice(1)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4605
4980
  // An absent ref exits 1 with empty stderr; preserve that distinction.
4606
4981
  catch (e2) { return { ok: false, status: e2.status, err: String(e2.stderr ?? e2.message ?? "").trim() }; }
4607
4982
  };
4608
4983
  // Retain cleanup owners so a retry must actually discharge their debt.
4609
4984
  const outstandingHooks = new Set();
4610
4985
  const outstandingGit = new Set();
4986
+ // A session provider's launch that was sent may have started a session, also when its answer
4987
+ // was lost: the provider stops it (by its endpoint, or, without one, whatever live session is
4988
+ // rooted at this home) before credentials or work its harness may be using are removed. A stop
4989
+ // that cannot be confirmed retains the home, as a window that cannot be seen gone does.
4990
+ if (providerSession) {
4991
+ // The fence: the launch is still marked as sent (a spawn keeps the mark until its last
4992
+ // write but one), or is marked again here, so no new input is admitted; one already in
4993
+ // flight is waited for or ended first (drainProviderCalls).
4994
+ let left = null;
4995
+ try { if (readSessionReceipt(home).baseline.runtime?.launchSent === undefined) markLaunchSent(home); }
4996
+ catch (e) { left = `that the session of ${instance} is being stopped could not be recorded (${e?.code ?? e?.message ?? e})`; }
4997
+ left ??= drainProviderCalls(home);
4998
+ const stopped = left ? { failed: left } : trackedProviderStop(home, providerSession.binding, providerSession.endpoint, 20, { launchSent: providerSession.launchSent });
4999
+ if (stopped.failed) {
5000
+ incomplete.push(`session backend ${backend}: the session it may have started for ${instance} could not be stopped (${stopped.failed}); stop or archive it with ${provider.capability}'s own tooling`);
5001
+ for (const cap of resolvedCfg.capabilities) if (cap.hooks?.retire) outstandingHooks.add(cap.id);
5002
+ if (work === "worktree") {
5003
+ outstandingGit.add("worktree");
5004
+ if (branch) outstandingGit.add("branch");
5005
+ }
5006
+ return { unconfirmed: true, note: quarantineInstanceHome({
5007
+ home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete, failed, outstandingHooks, outstandingGit,
5008
+ repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {},
5009
+ launched: false, directoryHome: homeReal,
5010
+ }) };
5011
+ }
5012
+ // Stopped: nothing runs for this home. One that is kept all the same (a hook's cleanup is
5013
+ // owed) is left PLANNED, in its record and its receipt alike, so its retire finds them agreed.
5014
+ try { recordProviderPlanned(home, plannedSession); }
5015
+ catch (e) { incomplete.push(`session records of ${instance}: ${e?.message ?? e}`); }
5016
+ providerSession = null;
5017
+ }
4611
5018
  // A failed new-window command may still have created its window. Verify
4612
5019
  // quiescence before removing credentials or work that harness may be using.
4613
5020
  // On the socket recorded for this spawn: windowMayExist is only set once it is.
@@ -4649,6 +5056,8 @@ function* spawnBody(root, agent, o = {}) {
4649
5056
  home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete, failed, outstandingHooks, outstandingGit,
4650
5057
  repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {}, compensationMeta,
4651
5058
  launched: false, directoryPreservation: true, directoryHome: homeReal,
5059
+ // (A provider home stays one in its receipt: its composition is what its cleanup runs by.)
5060
+ ...(provider ? { session: { backend, provider: provider.capability } } : {}),
4652
5061
  recordRetirementBaseline: true,
4653
5062
  });
4654
5063
  return { unconfirmed: true, note: `${note}${directoryRecoveries.length ? `; prior work recovery: ${directoryRecoveries.join(", ")}` : ""}` };
@@ -4667,7 +5076,8 @@ function* spawnBody(root, agent, o = {}) {
4667
5076
  try { preserveDirectory(); }
4668
5077
  catch (e) { return retainDirectory(e); }
4669
5078
  try {
4670
- const comp = runLifecycleHooks("retire", {
5079
+ // (A spawn refused before any of its hooks ran has nothing for a retire hook to undo.)
5080
+ const comp = refusedBeforeHooks ? { failures: [], meta: {} } : runLifecycleHooks("retire", {
4671
5081
  home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs,
4672
5082
  workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg,
4673
5083
  priorMeta: hookRes.meta || {},
@@ -4727,11 +5137,11 @@ function* spawnBody(root, agent, o = {}) {
4727
5137
  home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete,
4728
5138
  failed,
4729
5139
  outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg,
4730
- hookMeta: hookRes.meta || {}, compensationMeta, launched: false,
5140
+ hookMeta: hookRes.meta || {}, compensationMeta, launched: false, session: plannedSession,
4731
5141
  directoryHome: homeReal, recordRetirementBaseline: true,
4732
5142
  });
4733
5143
  } else {
4734
- try { rmSync(home, { recursive: true, force: true }); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
5144
+ try { rmSync(home, { recursive: true, force: true }); removeModulesStore(home); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4735
5145
  if (existsSync(home) && !incomplete.some((m) => m.startsWith("instance home"))) incomplete.push(`instance home ${home}: still present`);
4736
5146
  note = incomplete.length ? ` — rollback INCOMPLETE, clean up manually: ${incomplete.join("; ")}` : " — spawn rolled back";
4737
5147
  }
@@ -4739,6 +5149,7 @@ function* spawnBody(root, agent, o = {}) {
4739
5149
  };
4740
5150
 
4741
5151
  try {
5152
+ if (refusedBeforeHooks) throw refusedBeforeHooks;
4742
5153
  if (requiredFailures.length) {
4743
5154
  const detail = requiredFailures.map((f) => ` ${f.capability} ${f.event} ${f.contract === "environment" ? "environment contract" : "hook (declared required)"}: ${f.message}`).join("\n");
4744
5155
  const code = requiredFailures.some((f) => f.contract === "environment") ? "E_HOOK_ENVIRONMENT_CONTRACT" : "E_REQUIRED_HOOK_FAILED";
@@ -4761,7 +5172,7 @@ function* spawnBody(root, agent, o = {}) {
4761
5172
  // apart from a dead one after a kill, so the spawn does not run its worktree hooks without it.
4762
5173
  if (!processStartToken(process.pid)) throw oatsError("E_SPAWN_FAILED", `this process's start time cannot be read, so a spawn killed while its worktree hooks ran could not be recovered safely; no worktree hook ran`);
4763
5174
  writeSpawnInProgressMarker("worktree", {});
4764
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: { session, window: instance } });
5175
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: plannedSession } : { launched: false, tmux: { session, window: instance } });
4765
5176
  treeGuard = signalGuard();
4766
5177
  const treeEnv = {
4767
5178
  OATS_TREE: tree, OATS_TREE_CLONE: cloneReal, OATS_TREE_REMOTE: originRemoteOf(cloneReal),
@@ -4853,9 +5264,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4853
5264
  // reads it again on the session it gets, and warns from that (below); a spawn that launches
4854
5265
  // nothing warns from this, and the warning says whose values were read.
4855
5266
  const folderTrustOn = (launchEnv) => launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, launch: launchEnv, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4856
- let folderTrust = folderTrustOn(launchEnvOn(expectedEnv.pane, removedEnv));
5267
+ // A session provider runs the harness in its own place, with its own trust of the folder, and is
5268
+ // handed the launch as data (providerLaunchInput): no command line is rendered or recorded.
5269
+ let folderTrust = provider ? { trustHome: false } : folderTrustOn(launchEnvOn(expectedEnv.pane, removedEnv));
4857
5270
  if (!launch && folderTrust.warning) warnings.push(folderTrust.warning);
4858
- let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
5271
+ let cmdline = provider ? undefined : renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4859
5272
 
4860
5273
  // Module skills as materialize landed them (flat, .agents/skills/<skill>/),
4861
5274
  // beside the soul's own: per-skill provenance `module:<cap>` (lead decision c3),
@@ -4931,14 +5344,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4931
5344
  skillAlias: { path: join(home, ".claude", "skills"), target: join("..", ".agents", "skills") },
4932
5345
  },
4933
5346
  },
4934
- capabilityRuntime: resolvedCfg.capabilities.map((cap) => ({
4935
- id: cap.id, layer: cap.layer, level: cap.level, settings: cap.settings, settingsOrigins: cap.settingsOrigins ?? {},
4936
- hooks: cap.hooks, requiredHooks: cap.requiredHooks, environment: cap.environment, environmentNamespaces: cap.environmentNamespaces,
4937
- missingRequires: cap.missingRequires, trust: cap.trust,
4938
- executable: cap.executable,
4939
- })),
4940
- tmux: { session, window: instance },
4941
- launch: recipe, command: cmdline, createdAt: new Date().toISOString(),
5347
+ capabilityRuntime: capabilityRuntimeRows(resolvedCfg),
5348
+ // The session's endpoint, as the receipt authorises it: tmux's planned names, or a session
5349
+ // provider's backend and capability (its endpoint is the provider's answer to the launch).
5350
+ ...(provider ? { backend, session: { provider: provider.capability, endpoint: null } } : { tmux: { session, window: instance } }),
5351
+ launch: recipe, ...(provider ? {} : { command: cmdline }), createdAt: new Date().toISOString(),
4942
5352
  };
4943
5353
  // Workspace model: materialize recorded modules/providers (and the module
4944
5354
  // digests) in instance.json before this metadata is assembled — carry them.
@@ -4955,9 +5365,52 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4955
5365
  spawnTmux = meta.tmux;
4956
5366
  if (work === "directory") assertDirectoryRoots(home, homeReal);
4957
5367
  // The launch's one native start, prepared before anything is created; every render below reuses it.
4958
- const nativeStart = launch ? prepareNativeStart(home, harness) : null;
5368
+ const nativeStart = launch && !provider ? prepareNativeStart(home, harness) : null;
4959
5369
  let unscoped = null; // the harness's agent-scope warning, an event once the launch is recorded
4960
- if (launch) {
5370
+ if (launch && provider) {
5371
+ // The record and the independent receipt first, as planned and not launched: the receipt's
5372
+ // digest of the home is taken before the provider's harness can write there. The endpoint is
5373
+ // the provider's answer; it is recorded in both, the receipt first, as soon as it is given.
5374
+ // Under the home's lifecycle claim (the launch is its first start), taken before the record
5375
+ // and the receipt make it a home another verb could act on (providerLaunchClaim).
5376
+ providerLaunchClaim = claimHomeFor("start", instance, canonicalHomePath(home));
5377
+ meta.launched = false;
5378
+ writeEarlyProviderReceipt();
5379
+ writeHomeRecord(home, meta);
5380
+ clearSpawnInProgressMarker();
5381
+ // Killed here, the home is planned: its record, and the receipt written before it.
5382
+ dieAt("spawn:record-written");
5383
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: plannedSession });
5384
+ const found = homeSessionProvider(home, meta, provider.capability, backend);
5385
+ if (found.problem) throw oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${found.problem}`);
5386
+ // (The provider's readiness was asked before the spawn's hooks ran.)
5387
+ const input = providerLaunchInput({ home, instance, recipe, env: process.env, removed: removedEnv, previous: null, sandbox: sandboxLaunchInput(sandbox) });
5388
+ assertHostRunAdmission();
5389
+ // From here a session may exist: the spawn's compensation stops it before anything is removed.
5390
+ // And a spawn that ends here without doing so (killed, its host stopped) leaves its word in
5391
+ // the receipt, outside the home: a launch was sent (launchSentOf).
5392
+ const orphaned = endProviderCalls(home); // of a home of this name that is gone
5393
+ if (orphaned) throw oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${orphaned}`);
5394
+ const launchSent = markLaunchSent(home);
5395
+ providerSession = { binding: found.binding, endpoint: null, launchSent };
5396
+ const call = markProviderCall(home, "launch");
5397
+ let answered;
5398
+ try { answered = launchProviderSession(found.binding, input, { groupFile: call.groupFile }); } finally { call.done(); }
5399
+ if (answered.refused) { providerSession = null; clearLaunchSent(home); throw Object.assign(oatsError(answered.refused.code, `session backend ${backend} refused to launch ${instance}: ${answered.refused.message}`), { details: { backend, capability: provider.capability } }); }
5400
+ if (answered.failed) {
5401
+ if (!answered.uncertain) { providerSession = null; clearLaunchSent(home); }
5402
+ throw oatsError("E_SESSION_START_FAILED", `session backend ${backend} did not launch ${instance}: ${answered.failed}`);
5403
+ }
5404
+ providerSession.endpoint = answered.endpoint;
5405
+ promptStartId = randomUUID();
5406
+ meta.startId = promptStartId;
5407
+ meta.session = { provider: provider.capability, endpoint: answered.endpoint };
5408
+ meta.launched = true;
5409
+ meta.launchPrompts = notEngaged(promptStartId);
5410
+ recordLaunchOutcome(home, { backend, provider: provider.capability, endpoint: answered.endpoint }, meta, { keepMark: true });
5411
+ // (The claim is kept to the spawn's last write of the record, below: a restart admitted
5412
+ // before it would have its record overwritten by this spawn's.)
5413
+ } else if (launch) {
4961
5414
  // The session on the OATS server, then everything on the one socket that answered: the collision
4962
5415
  // check, the records, the window and (in compensateSpawn) its removal.
4963
5416
  const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan, undefined, spawnWarnings);
@@ -5066,10 +5519,15 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5066
5519
  if (!meta.launched) throw retainedPromptError(home, instance, promptTarget, parentLineageCommitted, promptResult);
5067
5520
  }
5068
5521
  } else {
5522
+ // (3) A provider home's spawn holds the home's claim from before its record, launched or
5523
+ // not: a start admitted between that record and the spawn's last receipt write would have its
5524
+ // receipt overwritten as never launched.
5525
+ if (provider) { providerLaunchClaim = claimHomeFor("start", instance, canonicalHomePath(home)); writeEarlyProviderReceipt(); }
5069
5526
  meta.launched = false;
5070
5527
  writeHomeRecord(home, meta);
5071
5528
  clearSpawnInProgressMarker();
5072
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: meta.tmux });
5529
+ if (provider) dieAt("spawn:record-written");
5530
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: plannedSession } : { launched: false, tmux: meta.tmux });
5073
5531
  }
5074
5532
 
5075
5533
  // Ordinary launches and scaffolds commit here; launches that engage the
@@ -5080,12 +5538,20 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5080
5538
  appendEvent(home, { kind: "spawned", data: { agent: agent.name, work, branch: branch ?? null, harness, model: model || null, parentInstance: meta.parentInstance ?? null, relation: relation ?? null, spawnedBy, launched: launch, hooks: hookReceipt(hookRes), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}) } });
5081
5539
  if (launch) appendEvent(home, { kind: "launched", data: { harness, backend, launchConfig: launchConfig?.name ?? null } });
5082
5540
  if (unscoped) appendEvent(home, { kind: "launch-warning", data: { message: unscoped } });
5541
+ if (providerLaunchClaim) {
5542
+ // The launch's mark goes (kept since the launch's outcome), BEFORE the record says the spawn
5543
+ // completed: a same-key retry never replays, as finished, a home that is still unsettled.
5544
+ dieAt("spawn:recorded");
5545
+ clearLaunchSent(home);
5546
+ }
5083
5547
  if (o.idempotencyKey !== undefined) {
5084
5548
  // Only now is the spawn a finished receipt a same-key retry may replay.
5085
5549
  meta.spawnCompleted = true;
5086
5550
  writeHomeRecord(home, meta); // a kernel-owned field: the baseline fingerprint ignores it
5087
5551
  }
5088
- return deliver({ ...meta, background, ...(backgroundFrom ? { backgroundFrom } : {}), ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: spawnAttach(meta, launch), warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
5552
+ if (providerLaunchClaim) dieAt("spawn:published");
5553
+ releaseProviderLaunchClaim();
5554
+ return deliver({ ...meta, background, ...(backgroundFrom ? { backgroundFrom } : {}), ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), launch: redactLaunchRecipe(recipe), ...(provider ? {} : { command: redactLaunchCommand(cmdline) }), attach: spawnAttach(meta, launch), warnings: spawnWarnings.length ? spawnWarnings : undefined, ...(naming ? { naming } : {}) });
5089
5555
  } catch (error) {
5090
5556
  if (promptDispatched) {
5091
5557
  // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
@@ -5125,6 +5591,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5125
5591
  } finally {
5126
5592
  // Interrupts were held through the rollback of a spawn that ran worktree hooks (#796).
5127
5593
  treeGuard?.restore();
5594
+ // Held until the launch is undone: nothing acts on the home while its session is stopped and it is removed.
5595
+ releaseProviderLaunchClaim();
5128
5596
  }
5129
5597
  // #796: the worktree hooks' logs are in the home. A rollback that removed it removed them: no
5130
5598
  // answer names a path that is gone (each entry's `log` is null); a retained home keeps them.
@@ -5327,7 +5795,7 @@ function buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, f
5327
5795
  function writeQuarantineMarker(home, marker, extra = {}, mode) {
5328
5796
  writeJsonAtomic(join(home, ".oats-rollback-incomplete.json"), { ...marker, ...extra }, mode);
5329
5797
  }
5330
- function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, recordRetirementBaseline = false, reason, directoryPreservation = false, orphanedWork = false, directoryHome = realPathOrNearest(home) }) {
5798
+ function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, session = null, recordRetirementBaseline = false, reason, directoryPreservation = false, orphanedWork = false, directoryHome = realPathOrNearest(home) }) {
5331
5799
  const marker = buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, reason, directoryPreservation, orphanedWork });
5332
5800
  try {
5333
5801
  if (work === "directory") {
@@ -5350,7 +5818,8 @@ function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomp
5350
5818
  if (recordRetirementBaseline) {
5351
5819
  try {
5352
5820
  if (work === "directory") assertDirectoryRoots(home, directoryHome);
5353
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities || [], { launched: launched === true, tmux });
5821
+ // (`session`: a home on a session provider keeps its backend and provider in the receipt.)
5822
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities || [], session ? { launched: false, session } : { launched: launched === true, tmux });
5354
5823
  } catch (e) {
5355
5824
  incomplete.push(`independent retirement authority: ${e.message}`);
5356
5825
  }
@@ -5936,6 +6405,7 @@ function retirementDisposableRoots(work, capabilities) {
5936
6405
  * is still recovered at retire. (Replaces a whole-home re-stamp that could
5937
6406
  * bless authored bytes written in the launch→completion interval.) */
5938
6407
  const KERNEL_POST_SPAWN_FIELDS = ["spawnCompleted", "wake", "launchPrompts", "launchPromptTarget", "parentLineageCommitted"];
6408
+ const PROVIDER_POST_SPAWN_FIELDS = ["session", "launched", "startId"];
5939
6409
  // What a digest holds of a home instance.json to take its neutral form (#617); a larger one is hashed raw, in pieces.
5940
6410
  const NEUTRAL_INSTANCE_JSON_BYTES = 16 * 1024 * 1024;
5941
6411
  function kernelNeutralInstanceJson(bytes) {
@@ -5949,6 +6419,10 @@ function kernelNeutralInstanceJson(bytes) {
5949
6419
  const m = JSON.parse(text);
5950
6420
  if (!m || typeof m !== "object" || Array.isArray(m)) return bytes;
5951
6421
  for (const k of KERNEL_POST_SPAWN_FIELDS) delete m[k];
6422
+ // A home on a session provider (it records `session`): its endpoint is the provider's answer
6423
+ // to the launch, so the kernel writes the launch's outcome after the baseline is taken, where
6424
+ // a tmux home's is written before its window exists. The receipt is their authority.
6425
+ if (m.session !== undefined && typeof m.backend === "string") for (const k of PROVIDER_POST_SPAWN_FIELDS) delete m[k];
5952
6426
  return Buffer.from(JSON.stringify(m));
5953
6427
  } catch { return bytes; }
5954
6428
  }
@@ -6275,9 +6749,29 @@ export function rebaseUpgradeRetirementBaseline(home, { homeChangedSinceSpawn }
6275
6749
  writeJsonAtomic(path, { ...baseline, homeFingerprint }, 0o600);
6276
6750
  }
6277
6751
 
6752
+ /** A spawn's first act on the home it has just made: take away the receipt an earlier home left
6753
+ * at this path. A retire keeps a home's receipt, by the home's path, and a spawn writes its own
6754
+ * only later (in most work modes after its spawn hooks), so until then every reader of "this
6755
+ * home's receipt" would read the retired home's: its backend, and for a provider home its
6756
+ * composition, by which this spawn's hooks would be run. The home was made by this spawn a
6757
+ * moment ago (an exclusive mkdir), so whatever receipt is at its path is not its own. */
6758
+ function removeStaleReceipt(home) {
6759
+ for (const path of new Set([retirementBaselinePath(home), legacyRetirementBaselinePath(home)])) rmSync(path, { force: true });
6760
+ // (And the kernel's copies of that home's modules, by the same key.)
6761
+ removeModulesStore(home);
6762
+ }
6763
+
6278
6764
  /** Project transaction-owned temporary files out of this baseline only. Later
6279
6765
  * fingerprints still hold them: a stale mutex is work to preserve, not invisible state. */
6280
6766
  export function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding, transientHomePaths = [] } = {}) {
6767
+ // A receipt that names a session provider is never rewritten as one that names none: a caller
6768
+ // that hands no session (a rollback that knows only that nothing is launched) keeps the home's
6769
+ // backend and provider, and with them its composition. Without them the home would read as a
6770
+ // tmux home, whose own copies and own record the kernel runs.
6771
+ const standing = homeReceipt(home)?.runtime;
6772
+ if (!runtime?.session && isPlainObject(standing) && typeof standing.provider === "string" && typeof standing.backend === "string") {
6773
+ runtime = { launched: false, session: { backend: standing.backend, provider: standing.provider } };
6774
+ }
6281
6775
  const transientFiles = retirementTransientFiles(home, transientHomePaths);
6282
6776
  if (mode === "directory") assertDirectoryRoots(home);
6283
6777
  const isWorktree = mode === "worktree";
@@ -6294,10 +6788,23 @@ export function writeRetirementBaseline(home, work, mode, capabilities, runtime,
6294
6788
  disposableReceipts,
6295
6789
  disposableHome,
6296
6790
  generatedWorkFingerprint: isWorktree ? generatedWorkDigest(work, statusBytes, disposableReceipts.map((r) => r.root)) : undefined,
6297
- runtime: {
6298
- launched: runtime?.launched === true,
6299
- ...(runtime?.tmux ? { tmux: { session: runtime.tmux.session, window: runtime.tmux.window, ...(runtime.tmux.socket ? { socket: resolve(runtime.tmux.socket) } : {}) } } : {}),
6300
- },
6791
+ // A provider home's composition (lib/home-integrity.mjs): the store that holds the kernel's
6792
+ // own copies of the home's modules, made here from the copies this spawn materialised, and
6793
+ // the capability rows it resolved from the deployment. For such a home the kernel runs its
6794
+ // own copy of a module, and reads a capability's settings and hook commands from this record,
6795
+ // never from the home. A kernel from before it ignores the key.
6796
+ // Taken ONCE: a receipt that holds one keeps it (a spawn's later writes, its rollback's, a
6797
+ // retire's quarantine), so nothing is copied again from a home its agent could have written. The spawn removed any receipt an earlier home left at this path
6798
+ // (removeStaleReceipt), so the one found here is this home's own.
6799
+ ...(runtime?.session ? { composition: providerHomeTrust(home)?.composition ?? compositionOf(home, capabilityRuntimeRows({ capabilities })) } : {}),
6800
+ // `runtime.session`: a home on a session provider (lib/session-providers.mjs): its backend and the
6801
+ // capability that supplies it, and once launched the endpoint and whether OATS stopped it.
6802
+ runtime: runtime?.session
6803
+ ? (runtime.launched === true ? providerRuntimeRecord(runtime.session) : { launched: false, backend: runtime.session.backend, provider: runtime.session.provider })
6804
+ : {
6805
+ launched: runtime?.launched === true,
6806
+ ...(runtime?.tmux ? { tmux: { session: runtime.tmux.session, window: runtime.tmux.window, ...(runtime.tmux.socket ? { socket: resolve(runtime.tmux.socket) } : {}) } } : {}),
6807
+ },
6301
6808
  };
6302
6809
  assertRetirementTransientsUnchanged(transientFiles);
6303
6810
  const path = retirementBaselinePath(home);
@@ -6410,6 +6917,9 @@ export function observeSessionWithoutReceipt(home, meta, io) {
6410
6917
  }
6411
6918
  function recordedSessionAbsence(home, meta, io) {
6412
6919
  const tmux = meta?.tmux;
6920
+ // A home whose record names a session provider is never one from before session receipts: without
6921
+ // a receipt that can be used, whether its provider runs a session for it is not known.
6922
+ if (recordsSessionProvider(meta)) return { absent: false, backend: meta.backend, note: "instance.json records a session provider, and the home's session receipt cannot be used" };
6413
6923
  // A --no-launch home keeps its planned tmux names with `launched: false`: nothing was started there.
6414
6924
  if (meta?.launched !== true) return { absent: true, backend: null, note: "no session receipt (a home from before 0.25.9); instance.json records no launch" };
6415
6925
  if (!tmux) return { absent: false, backend: null, note: "instance.json records a launch but no session endpoint" };
@@ -6494,7 +7004,29 @@ function stopSessionClaimed(home, o) {
6494
7004
  try {
6495
7005
  if (retireCarried(realHome)) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6496
7006
  const s = instanceSessionTarget(realHome);
6497
- if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
7007
+ // A launch that was sent to the home's provider and never recorded: the provider stops whatever
7008
+ // it started before anything else is answered. Never "not launched" while that is not known.
7009
+ const sent = s.unsettled;
7010
+ if (sent) refuseOtherWire(realHome, s.meta, sent, "stopped", "nothing was stopped");
7011
+ if (sent && s.session) {
7012
+ // A home launched before: the one stop rule first (stopProviderHome: `stoppedAt` and the stop
7013
+ // receipt before the provider is called, the recorded session stopped, a host's stop
7014
+ // withdrawn by an operator's), then the launch that was sent.
7015
+ // (Not confirmed: E_SESSION_STOP_FAILED, and the home stays unsettled. The host's stop of a
7016
+ // home that is stopped already asks nothing: the settle then asks for the recorded session.)
7017
+ const stopped = stopProviderHome(realHome, s, o);
7018
+ const unsettled = settleSentLaunch(realHome, s.meta, sent, o.graceMs, o.io, { recordedStopped: !(o.withHost === true && s.session.stoppedAt !== null) });
7019
+ if (unsettled) throw oatsError("E_SESSION_STOP_FAILED", `${basename(realHome)} is recorded as stopped by OATS, but a launch of it was sent to session backend ${sent.backend} and never recorded, and the backend did not confirm that it stopped what that launch started (${unsettled}); stop it again, or stop or archive that session with ${sent.provider}'s own tooling`);
7020
+ return { ...stopped, stopped: true, alreadyIdle: false };
7021
+ }
7022
+ if (sent) {
7023
+ const unsettled = settleSentLaunch(realHome, s.meta, sent, o.graceMs, o.io);
7024
+ if (unsettled) throw oatsError("E_SESSION_STOP_FAILED", `a launch of ${basename(realHome)} was sent to session backend ${sent.backend} and never recorded, and the backend did not confirm that it stopped what that launch started (${unsettled}); stop it again, or stop or archive that session with ${sent.provider}'s own tooling`);
7025
+ appendEvent(realHome, { kind: "stopped", data: { signal: null, waitedMs: 0, stillRunning: [], state: "stopped" } });
7026
+ return { home: s.home, backend: sent.backend, stopped: true, alreadyIdle: false, state: "stopped", receipt: null };
7027
+ }
7028
+ if (s.session) return stopProviderHome(realHome, s, o);
7029
+ if (!s.target) return { home: s.home, backend: s.planned?.backend ?? null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6498
7030
  let before;
6499
7031
  try { before = inspectSessionTarget(s.target); }
6500
7032
  catch (e) {
@@ -6534,6 +7066,68 @@ function stopSessionClaimed(home, o) {
6534
7066
  throw failure;
6535
7067
  }
6536
7068
  }
7069
+ /** An OATS stop of a provider home's session, the kernel-owned rule in one place (a stop's, a
7070
+ * restart's): `stoppedAt` in the receipt first, then the home's stop receipt (`withHost`: the
7071
+ * host's shutdown wrote it, which a resume brings back), then the provider's stop → `{ unconfirmed,
7072
+ * waitedMs }`: `unconfirmed` null when the provider confirmed, else why not. The home stays
7073
+ * recorded as stopped either way. */
7074
+ function stopProviderSessionRecorded(home, meta, session, { withHost = false, graceMs, io, outlasted } = {}) {
7075
+ const started = Date.now();
7076
+ // An earlier stop's receipt goes first (one a resume that died left behind names this same
7077
+ // start): this stop is an operator's until its own receipt says otherwise.
7078
+ rmSync(join(home, STOP_RECEIPT_FILE), { force: true });
7079
+ writeProviderRuntime(home, { backend: session.backend, provider: session.provider, endpoint: session.endpoint, stoppedAt: new Date(started).toISOString() });
7080
+ dieAt("stop:stoppedAt-written");
7081
+ // The stop receipt: a record that cannot be written leaves the home stopped as by an operator,
7082
+ // which no resume brings back.
7083
+ try { recordStop(home, null, { withHost }); } catch { /* see above */ }
7084
+ dieAt("stop:receipt-written");
7085
+ const unconfirmed = providerStopUnconfirmed(home, meta, session, session.endpoint, graceMs, io, null, { outlasted });
7086
+ return { unconfirmed, waitedMs: Date.now() - started };
7087
+ }
7088
+ /** A home whose provider speaks another wire than this kernel is refused by name, E_BACKEND_WIRE,
7089
+ * before a verb records or asks anything: a start, a stop (the host's too) and an input. Its
7090
+ * sessions read unavailable and are never recorded as stopped by a provider that was not asked.
7091
+ * (A retire keeps its own rule: it cannot ask that provider, and goes on when no process works in
7092
+ * the home, with the warning that names the provider's own tooling.) `recorded`: `{ backend,
7093
+ * provider }`; `what`: the verb's participle; `nothing`: what did not happen. */
7094
+ function refuseOtherWire(home, meta, recorded, what, nothing) {
7095
+ const found = homeSessionProvider(home, meta, recorded.provider, recorded.backend);
7096
+ const wire = found.problem ? null : wireRefusal(recorded.provider, found.binding.provider);
7097
+ if (wire) throw Object.assign(oatsError(wire.code, `${meta.instance || basename(home)} was not ${what}: ${wire.message}; ${nothing}`), { details: wire.details });
7098
+ }
7099
+ /** The stop of a home on a session provider (lib/session-providers.mjs), under the home's claim.
7100
+ * Kernel-owned: the receipt records `stoppedAt` BEFORE the provider is called, so from that
7101
+ * instant inspect answers stopped and input is refused, whatever the provider then does; a start
7102
+ * clears it. Which stop it was is the home's stop receipt's to say, as for a tmux home
7103
+ * (recordStop): an operator's stop is the intent that keeps the home down; a stop with the host
7104
+ * (`withHost`: `oats host run`'s shutdown) is a loss, which a resume brings back. The provider's
7105
+ * stop comes second, given the stop's grace and never escalated: one that fails or cannot be
7106
+ * confirmed is E_SESSION_STOP_FAILED, and the home stays recorded as stopped. A home OATS already
7107
+ * stopped is idle, and an operator's stop of it asks the provider once more (its stop is
7108
+ * idempotent): that is how a stop the provider did not confirm is finished. It also rewrites the
7109
+ * stop receipt of a home stopped with the host, which withdraws the resume. */
7110
+ function stopProviderHome(realHome, s, o) {
7111
+ const { backend, stoppedAt } = s.session;
7112
+ const withHost = o.withHost === true;
7113
+ const idle = { home: s.home, backend, stopped: false, alreadyIdle: true, state: "stopped", receipt: null };
7114
+ // (The host's shutdown asks nothing of a home that is stopped already: it has no provider to refuse.)
7115
+ if (!(stoppedAt !== null && withHost)) refuseOtherWire(realHome, s.meta, s.session, "stopped", "nothing was stopped");
7116
+ if (stoppedAt !== null) {
7117
+ // The host's shutdown changes nothing of a home that is stopped already.
7118
+ if (withHost) return idle;
7119
+ if (lostReasonOf(realHome, s.meta) === HOST_STOP_REASON) recordStop(realHome, null);
7120
+ // An operator's stop asks the provider again: an earlier stop may not have been confirmed
7121
+ // (E_SESSION_STOP_FAILED leaves the home recorded as stopped), and this is how it is finished.
7122
+ const again = providerStopUnconfirmed(realHome, s.meta, s.session, s.session.endpoint, o.graceMs);
7123
+ if (again) throw oatsError("E_SESSION_STOP_FAILED", `${basename(realHome)} is recorded as stopped by OATS (inspect answers stopped and input to it is refused until it is started), but session backend ${backend} did not confirm that its session stopped: ${again}`);
7124
+ return idle;
7125
+ }
7126
+ const { unconfirmed, waitedMs } = stopProviderSessionRecorded(realHome, s.meta, s.session, { withHost, graceMs: o.graceMs });
7127
+ appendEvent(realHome, { kind: unconfirmed ? "stop-refused" : "stopped", data: { signal: null, waitedMs, stillRunning: [], state: unconfirmed ? "unknown" : "stopped" } });
7128
+ if (unconfirmed) throw oatsError("E_SESSION_STOP_FAILED", `${basename(realHome)} is recorded as stopped by OATS (inspect answers stopped and input to it is refused until it is started), but session backend ${backend} did not confirm that its session stopped: ${unconfirmed}`);
7129
+ return { home: s.home, backend, stopped: true, alreadyIdle: false, state: "stopped", receipt: null };
7130
+ }
6537
7131
  /** What a failed stop (an error of stopInstanceSession) established of the processes it signalled,
6538
7132
  * for its row of results: [] only when its receipt says the harness exited; the pids its receipt
6539
7133
  * names as still alive; and null when nothing is established. That is a stop without a receipt,
@@ -6583,17 +7177,278 @@ function stopRecordedChildren(children, signalled) {
6583
7177
  export async function attachInstanceSession(home, { detachKey, statusLine, onSwept } = {}) {
6584
7178
  if (detachKey !== undefined) requireDetachKey(detachKey);
6585
7179
  const s = instanceSessionTarget(home);
7180
+ if (s.session) throw sessionNoTerminal(s);
6586
7181
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
6587
7182
  return attachSessionTarget(s.target, { detachKey, statusLine, onSwept });
6588
7183
  }
7184
+ /** E_SESSION_NO_TERMINAL: a session provider's session has no terminal to attach to. Its message
7185
+ * and `details.open` carry what the provider offers instead (inspect's `open`), when it says. */
7186
+ function sessionNoTerminal(s) {
7187
+ let open = null;
7188
+ try { open = inspectInstanceSession(s.home).open ?? null; } catch (e) { if (!isKernelCode(e?.code)) throw e; /* the refusal stands without the link */ }
7189
+ return Object.assign(oatsError("E_SESSION_NO_TERMINAL", `${basename(s.home)} runs on session backend ${s.session.backend}, which has no terminal to attach to${open ? `; open it there: ${open.label} (${open.url})` : ""}`), { details: { backend: s.session.backend, open } });
7190
+ }
6589
7191
 
6590
7192
  export function inputInstanceSession(home, text) {
6591
7193
  if (typeof text !== "string" || !text.trim() || text.includes("\0") || Buffer.byteLength(text) > 256 * 1024) throw oatsError("E_BAD_ARGS", "session input must be nonempty text without NUL, at most 256 KiB");
6592
7194
  const s = instanceSessionTarget(home);
7195
+ if (s.session) return inputProviderHome(s, text);
6593
7196
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
6594
7197
  try { return { home: s.home, ...inputSessionTarget(s.target, text) }; }
6595
7198
  catch (e) { throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${e.message}`); }
6596
7199
  }
7200
+ /** Input to a home on a session provider.
7201
+ * - Kernel-owned: a home OATS stopped refuses E_SESSION_NOT_RUNNING before any provider call, for
7202
+ * every caller (a person's `session input`, a scheduled wake, a client, the messaging broker): a
7203
+ * provider would otherwise restart the session on the next input.
7204
+ * - A session that is gone and that OATS did not stop is a lost one, and an input to it is a
7205
+ * RESUME (the provider restarts it on that input): counted against the home's resume cap before
7206
+ * the provider's input is called (lib/provider-resume.mjs), refused E_SESSION_NOT_RUNNING at the
7207
+ * cap, and refused while a process of its last run still works in the home (resumeLostSession).
7208
+ * So the session is read first: one that cannot be read is E_SESSION_INPUT_FAILED, never sent to.
7209
+ * - Otherwise the provider's answer: `submitted: true` only when the input was dispatched;
7210
+ * E_SESSION_PROMPT_OPEN and E_SESSION_INPUT_QUEUED as it gives them (nothing was sent); anything
7211
+ * else E_SESSION_INPUT_FAILED. */
7212
+ function inputProviderHome(s, text) {
7213
+ const { backend, provider, endpoint, stoppedAt } = s.session;
7214
+ const name = basename(s.home);
7215
+ if (stoppedAt !== null) throw oatsError("E_SESSION_NOT_RUNNING", `${name} was stopped by OATS; nothing was sent. Start it first: oats session start --home ${s.home}`);
7216
+ // A launch that was sent and never recorded: the session it may have started is not the one at
7217
+ // the recorded endpoint, and an input there would have the provider start a second one.
7218
+ if (s.unsettled) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${unsettledLaunchSaid(name, backend, s.unsettled.launchSent)}; nothing was sent`);
7219
+ const found = homeSessionProvider(s.home, s.meta, provider, backend);
7220
+ if (found.problem) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${found.problem}`);
7221
+ // A provider that speaks another wire is never called: refused by name (refuseOtherWire's rule).
7222
+ const wire = wireRefusal(provider, found.binding.provider);
7223
+ if (wire) throw Object.assign(oatsError(wire.code, `${name} was not sent the input: ${wire.message}; nothing was sent`), { details: wire.details });
7224
+ const inspected = inspectProviderSession(found.binding, endpoint);
7225
+ if (inspected.unavailable) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: whether ${name}'s session is there could not be established (${inspected.unavailable}); nothing was sent`);
7226
+ const resume = inspected.observed.present ? null : resumeLostSession(s.home, name, { waitMs: 0 });
7227
+ // An input holds no claim, and a provider restarts a session on it: a stop, a restart or a
7228
+ // retire that lands while this input runs must still win. So the receipt is read again right
7229
+ // before the input (the inspect above may have taken seconds), and once more after it.
7230
+ // What crossed, if anything, from one read of the home → `{ what, sameLocator }`, or null: `what`
7231
+ // is `stopped` (the home is stopped, or its session is no longer recorded) or `restarted` (it
7232
+ // runs again: another start, by its id, or another endpoint). The start's id is compared as
7233
+ // well as the endpoint: a provider may hand a restart the same locator again (`sameLocator`).
7234
+ const startId = s.meta?.startId ?? null;
7235
+ const crossed = () => {
7236
+ try {
7237
+ const now = instanceSessionTarget(s.home);
7238
+ if (!now.session || now.session.stoppedAt !== null) return { what: "stopped", sameLocator: false };
7239
+ // A start that is launching (its launch is sent, not yet recorded): the session at this
7240
+ // endpoint is the one it replaces, whatever locator the new one gets.
7241
+ if (now.unsettled) return { what: "restarted", sameLocator: false };
7242
+ const sameLocator = sameEndpoint(now.session.endpoint, endpoint);
7243
+ return (now.meta?.startId ?? null) !== startId || !sameLocator ? { what: "restarted", sameLocator } : null;
7244
+ } catch { return { what: "stopped", sameLocator: false }; }
7245
+ };
7246
+ // In flight from here to the answer: a record outside the home says so to a retire, which waits
7247
+ // for it before its last stop (markProviderCall). Written BEFORE the read below, so an input
7248
+ // either sees the retire's stop there, or is seen by the retire.
7249
+ let call;
7250
+ try {
7251
+ // (A call a killed kernel left behind for this home, a stop that would run late, is ended first.)
7252
+ const orphaned = endProviderCalls(s.home);
7253
+ if (orphaned) throw new Error(orphaned);
7254
+ call = markProviderCall(s.home, "input");
7255
+ }
7256
+ catch (e) { resume?.undo(); throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: that it is in flight could not be recorded (${e?.code ?? e?.message ?? e}); nothing was sent`); }
7257
+ try {
7258
+ if (crossed()) { resume?.undo(); throw oatsError("E_SESSION_NOT_RUNNING", `${name} was stopped or restarted by OATS while this input was prepared; nothing was sent`); }
7259
+ let sent, failure;
7260
+ try { sent = inputProviderSession(found.binding, endpoint, text, { groupFile: call.groupFile }); }
7261
+ catch (e) {
7262
+ // The count is taken back only when the provider itself refused: nothing was sent. An input
7263
+ // whose call failed may have restarted the session: it stays counted, so no failing provider
7264
+ // lets input past the cap.
7265
+ if (inputWasRefused(e)) resume?.undo();
7266
+ failure = e;
7267
+ }
7268
+ // A stop (a restart's, a retire's) that landed while the input was being sent, whatever the
7269
+ // provider answered, a refusal included: it may have restarted the session it had just stopped,
7270
+ // at an endpoint OATS records as stopped or no longer records. It is asked to stop that session
7271
+ // again, and the input is not delivered: a mail then stays unread and comes again, to the
7272
+ // session that is there by then. After a RESTART the session at the endpoint this input used is
7273
+ // stopped again only when the home now runs at another one: the same locator is the new
7274
+ // session's, which no input's cleanup may stop.
7275
+ const crossing = crossed();
7276
+ if (crossing) {
7277
+ // (Recorded as a call, as every stop is; no drain: an input does not wait for another.)
7278
+ const again = crossing.sameLocator ? null : trackedProviderStop(s.home, found.binding, endpoint, 20);
7279
+ throw oatsError("E_SESSION_NOT_RUNNING", `${name} was ${crossing.what} by OATS while this input was being sent${again ? `; its ${backend} session was asked to stop again${again.failed ? `, which it did not confirm (${again.failed}): stop it in the stop's two steps (oats instance stop ${name} --plan, then --apply --plan-revision <rev> --idempotency-key <key>, which the plan prints)` : ""}` : ""}, and the input is not delivered`);
7280
+ }
7281
+ if (failure) throw failure;
7282
+ // No endpoint here: it is on inspect, spawn and start answers only.
7283
+ return { home: s.home, backend, ...sent };
7284
+ } finally { call.done(); }
7285
+ }
7286
+ /** The provider calls in flight for a home (docs/design/2026-11-20-provider-home-lifecycle.md, "A
7287
+ * provider's command outlives the kernel that ran it" and "A retire and an input in flight").
7288
+ *
7289
+ * A launch and an input can start a session, and the kernel that sent one can be killed while
7290
+ * it waits: the provider's command lives on, and a session it starts later would have no record.
7291
+ * So each such call has a record outside the home, beside the claims
7292
+ * (`<instances>/.oats-retirement/provider-calls/<name>/<verb>-<pid>-<id>.json`): the kernel that
7293
+ * makes the call (pid and start time, as a claim names its holder), and, in `<record>.group`, the
7294
+ * leader of the process group the provider's command runs in, written by that leader before the
7295
+ * provider runs (lib/provider-call-child.mjs). The record is removed when the call returns.
7296
+ *
7297
+ * A record left by a kernel that is gone is a call that may still act. Before the kernel relies
7298
+ * on a provider's stop (providerStopUnconfirmed), it ends each: the group is killed and seen
7299
+ * empty; a call whose group never recorded itself is made void (the `.group` file is created
7300
+ * here, so that leader, if it comes, runs nothing). A retire also waits for the inputs of LIVE
7301
+ * kernels (an input holds no claim), and ends those that outlast its wait. */
7302
+ const providerCallsDir = (home) => join(dirname(dirname(retireClaimPath(home))), "provider-calls", basename(home));
7303
+ /** The markers' directory lasts as long as a marker: none is left behind per home. */
7304
+ function removeIfEmpty(dir) {
7305
+ try { rmdirSync(dir); } catch (e) { if (!["ENOTEMPTY", "EEXIST", "ENOENT"].includes(e?.code)) throw e; }
7306
+ }
7307
+ /** Record that this process makes a `verb` call for `home` → `{ groupFile, done }`: where the
7308
+ * call's group records itself (callSessionProvider's `groupFile`: one call), and what takes the
7309
+ * record away. */
7310
+ /** Publish a small record whole, and only if none is there: written to a file of its own, then
7311
+ * linked to its name (EEXIST when the name is taken). A reader never finds it half written,
7312
+ * wherever its writer ends (the leader of a provider command's group publishes its own so:
7313
+ * lib/provider-call-child.mjs). */
7314
+ function publishExclusive(path, content) {
7315
+ const own = `${path}.${process.pid}.tmp`;
7316
+ try { writeFileSync(own, content, { mode: 0o600, flag: "wx" }); linkSync(own, path); }
7317
+ finally { rmSync(own, { force: true }); }
7318
+ }
7319
+ function markProviderCall(home, verb) {
7320
+ const dir = providerCallsDir(canonicalHomePath(home));
7321
+ const path = join(dir, `${verb}-${process.pid}-${randomUUID()}.json`);
7322
+ const write = () => { mkdirSync(dir, { recursive: true, mode: 0o700 }); publishExclusive(path, `${JSON.stringify({ verb, ...selfIdentity(), startedAt: new Date().toISOString() })}\n`); };
7323
+ // (Once more when another call's end took the directory away between the two steps.)
7324
+ try { write(); } catch (e) { if (e?.code !== "ENOENT") throw e; write(); }
7325
+ return { groupFile: `${path}.group`, done: () => { rmSync(path, { force: true }); rmSync(`${path}.group`, { force: true }); removeIfEmpty(dir); } };
7326
+ }
7327
+ /** The calls recorded for `home`, but this process's own → `[{ path, verb, pid, kernelGone }]`. */
7328
+ function providerCalls(home) {
7329
+ const dir = providerCallsDir(canonicalHomePath(home));
7330
+ let names;
7331
+ try { names = readdirSync(dir); } catch { return []; }
7332
+ const calls = [];
7333
+ for (const name of names) {
7334
+ const path = join(dir, name);
7335
+ // (A writer that ended before its link left its own file: nothing reads it, and it goes after a minute.)
7336
+ if (name.endsWith(".tmp")) { try { if (Date.now() - statSync(path).mtimeMs > 60_000) rmSync(path, { force: true }); } catch { /* gone meanwhile */ } continue; }
7337
+ if (!name.endsWith(".json")) continue;
7338
+ let record;
7339
+ try { record = JSON.parse(readFileSync(path, "utf8")); } catch { continue; } // just removed
7340
+ // This process's own (by its pid AND its start: a pid a gone kernel had is not this one).
7341
+ if (record.pid === process.pid && record.processStart === processStartToken(process.pid)) continue;
7342
+ calls.push({ path, verb: typeof record.verb === "string" ? record.verb : "call", pid: record.pid, kernelGone: processLiveness(record).state === "gone" });
7343
+ }
7344
+ if (!names.length) removeIfEmpty(dir);
7345
+ return calls;
7346
+ }
7347
+ /** Whether a process group has a member that can still act (one that is not a zombie) → true,
7348
+ * false, or null where that cannot be told (no /proc). */
7349
+ function groupCanAct(pgid) {
7350
+ let names;
7351
+ try { names = readdirSync("/proc"); } catch { return null; }
7352
+ for (const name of names) {
7353
+ if (!/^\d+$/.test(name)) continue;
7354
+ let stat;
7355
+ try { stat = readFileSync(`/proc/${name}/stat`, "utf8"); } catch { continue; } // gone meanwhile
7356
+ // "<pid> (<comm>) <state> <ppid> <pgrp> …": the command may hold spaces and parentheses.
7357
+ const [state, , pgrp] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
7358
+ if (Number(pgrp) === pgid && state !== "Z" && state !== "X") return true;
7359
+ }
7360
+ return false;
7361
+ }
7362
+ /** End one recorded call: nothing of its provider command runs after this → null, and its record
7363
+ * is removed; else why not, in one sentence, and the record stays. */
7364
+ function endProviderCall(call) {
7365
+ const groupFile = `${call.path}.group`;
7366
+ const said = `the ${call.verb} command that pid ${call.pid} ran for it`;
7367
+ let group;
7368
+ try { publishExclusive(groupFile, `${JSON.stringify({ void: true })}\n`); group = { void: true }; }
7369
+ catch (e) {
7370
+ if (e?.code !== "EEXIST") return `${said} could not be ended (${e?.code ?? e?.message ?? e})`;
7371
+ // Its group recorded itself, or an earlier kernel made the call void: either is published whole.
7372
+ try { group = JSON.parse(readFileSync(groupFile, "utf8")); }
7373
+ catch (read) { return `${said} could not be ended (its process group's record cannot be read: ${read?.code ?? read?.message ?? read})`; }
7374
+ }
7375
+ if (group.void !== true) {
7376
+ // "foreign": the leader's pid is another process's now, so that group is gone.
7377
+ const ended = terminateRecordedGroup({ hookPgid: group.pid, hookStart: group.processStart }, 0);
7378
+ // (Members that are all zombies can act no more: they wait for a parent that does not reap
7379
+ // them, as under a container whose first process is no init.)
7380
+ if (!["none", "terminated", "killed", "foreign"].includes(ended) && groupCanAct(group.pid) !== false) return `${said} could not be ended (process group ${group.pid}: ${ended}); end its processes yourself`;
7381
+ }
7382
+ rmSync(call.path, { force: true });
7383
+ rmSync(groupFile, { force: true });
7384
+ removeIfEmpty(dirname(call.path));
7385
+ return null;
7386
+ }
7387
+ /** End the calls recorded for `home` whose kernel is gone → null when none is left, else why
7388
+ * not. Before a launch, an input or a resume is sent: a stop a killed kernel left behind would
7389
+ * run late, and stop what they start. */
7390
+ function endProviderCalls(home) {
7391
+ return providerCalls(home).filter((call) => call.kernelGone).map(endProviderCall).filter(Boolean).join("; ") || null;
7392
+ }
7393
+ /** Drain the provider calls recorded for `home`, before a provider's stop is relied on → null
7394
+ * when none is left, else why not. The caller has written its fence (`stoppedAt`, a launch's
7395
+ * mark), so no new input is admitted. A call whose kernel is gone is ended at once; one of a
7396
+ * live kernel (an input holds no claim) is waited for, at most an input's timeout and a margin,
7397
+ * and ended if it outlasts that, or if its kernel dies meanwhile. `outlasted`: an array that
7398
+ * takes the pids of the kernels whose call was ended at the bound. */
7399
+ function drainProviderCalls(home, { outlasted, boundMs = sessionProviderTimeout("input") + INPUT_IN_FLIGHT_MARGIN_MS } = {}) {
7400
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
7401
+ const deadline = Date.now() + boundMs;
7402
+ for (;;) {
7403
+ const calls = providerCalls(home);
7404
+ const gone = calls.filter((call) => call.kernelGone).map(endProviderCall).filter(Boolean);
7405
+ if (gone.length) return gone.join("; ");
7406
+ const live = calls.filter((call) => !call.kernelGone);
7407
+ if (!live.length) return null;
7408
+ if (Date.now() >= deadline) {
7409
+ outlasted?.push(...live.map((call) => call.pid));
7410
+ return live.map(endProviderCall).filter(Boolean).join("; ") || null;
7411
+ }
7412
+ sleep(100);
7413
+ }
7414
+ }
7415
+ /** How long a provider's stop waits for the inputs in flight (drainProviderCalls): an input's own timeout, and a margin. */
7416
+ const INPUT_IN_FLIGHT_MARGIN_MS = 5000;
7417
+ /** How long a resume of a lost provider session waits for the processes of its last run to leave
7418
+ * the home, and how often it looks. */
7419
+ const RESUME_QUIET_POLL_MS = 1000;
7420
+ /** The kernel's resume primitive for a LOST session of a provider home (its session is gone, and
7421
+ * OATS did not stop it), before the provider's input is called → `{ undo }` (the count, to take
7422
+ * back when the input is then refused).
7423
+ * 1. No process of the old run works in the home (the kernel's process scan): a provider's
7424
+ * harness can outlive its server's crash for a while, and a resume beside it would run two.
7425
+ * The resume waits up to `waitMs` (default 150 s; an input waits not at all), then refuses,
7426
+ * naming the processes, as a retire does, and never kills them: E_SESSION_UNKNOWN for a start
7427
+ * (the sweep tries again, and counts nothing), E_SESSION_NOT_RUNNING for an input.
7428
+ * 2. The resume is counted against the home's cap, or refused at it (countProviderResume). */
7429
+ function resumeLostSession(home, name, { waitMs = RESUME_QUIET_WAIT_MS } = {}) {
7430
+ const budget = resumeQuietWait(waitMs);
7431
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
7432
+ const deadline = Date.now() + budget;
7433
+ for (;;) {
7434
+ // The host's own scan, never a start's guarded seam: a process is looked for as a retire does.
7435
+ const scan = processesInHome(home);
7436
+ const still = !scan.ok ? `whether a process of its last run still works in its home could not be established (${scan.error})` : scan.processes.length ? `a process of its last run still works in its home (${namedProcesses(scan.processes)})` : null;
7437
+ if (!still) break;
7438
+ if (Date.now() >= deadline) throw oatsError(waitMs > 0 ? "E_SESSION_UNKNOWN" : "E_SESSION_NOT_RUNNING", `${name} lost its session, and ${still}${waitMs > 0 ? ` after ${Math.round(budget / 1000)} s` : ""}; it is not resumed beside it, nothing was sent and nothing was killed`);
7439
+ sleep(Math.min(RESUME_QUIET_POLL_MS, Math.max(1, deadline - Date.now())));
7440
+ }
7441
+ // Counted under the count's lock, and taken back under it: inputs that run at the same time
7442
+ // each read the count the others wrote, so none passes the cap beside another.
7443
+ const uncounted = (why) => oatsError("E_SESSION_NOT_RUNNING", `${name} lost its session, and its resume could not be counted (${why}); nothing was sent`);
7444
+ const locked = (fn) => withDirLock(resumeCountLock(home), `counting a resume of ${name}`, fn, { retryMs: 5000, busy: uncounted });
7445
+ let counted;
7446
+ try { counted = locked(() => countProviderResume(home, name)); } catch (e) {
7447
+ // A lock the system would not make (its directory, its file) is a count that cannot be written.
7448
+ throw isKernelCode(e?.code) || isDefect(e) ? e : uncounted(e?.code ?? e?.message ?? e);
7449
+ }
7450
+ return { undo() { try { locked(() => counted.undo()); } catch { /* the count stands: a resume too many is counted, never one too few */ } } };
7451
+ }
6597
7452
 
6598
7453
  // ---------------------------------------------------------------- session start
6599
7454
 
@@ -6730,6 +7585,19 @@ export function capturedProviders(meta, frozen) {
6730
7585
  return { id, contribution, binding, settings: contribution?.settings ?? binding?.settings ?? {}, settingsOrigins };
6731
7586
  });
6732
7587
  }
7588
+ /** The session backend a home launches on, as its record says: a session provider's name, else tmux.
7589
+ * A launch hook's OATS_BACKEND (a spawn hook's is the spawn's own choice). */
7590
+ const homeBackendOf = (meta) => (recordsSessionProvider(meta) ? meta.backend : "tmux");
7591
+ /** The backend a home was last launched on, as the kernel recorded it OUTSIDE the home (its session
7592
+ * receipt): a session provider's name, or `tmux`; undefined for a home that was never launched,
7593
+ * and for one whose receipt is missing or says nothing this kernel reads. Never the home's own
7594
+ * record (instance.json), which the home's agent can write. A launch hook's OATS_PREVIOUS_BACKEND:
7595
+ * a capability that wrote files of its own for one backend reads here whether they are its to
7596
+ * remove, and removes nothing when the variable is absent. */
7597
+ function previousBackendOf(home) {
7598
+ const authority = runtimeAuthorityOf(homeReceipt(home));
7599
+ return authority?.session ? authority.session.backend : authority?.tmux ? "tmux" : undefined;
7600
+ }
6733
7601
  /** Capability contributions for a start of an existing home: the recorded
6734
7602
  * ones, refreshed by any capability that declares a `launch` hook (asked
6735
7603
  * for the target harness; spawn hooks are never re-run). A harness change
@@ -6775,13 +7643,15 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
6775
7643
  }
6776
7644
  const aware = withLaunchHook.filter((c) => c.manifest.launchPreview === true);
6777
7645
  const unaware = withLaunchHook.filter((c) => c.manifest.launchPreview !== true);
6778
- const runs = (pass === "real" ? [[aware, false]] : pass === "preview" ? [[aware, true]] : [[unaware, false], [aware, true]]).filter(([caps]) => caps.length);
6779
- const notRun = pass === "preview" ? unaware.map((c) => c.id) : [];
7646
+ // (`none`: no hook runs, whether it previews or not; every recorded contribution stands.)
7647
+ const runs = (pass === "none" ? [] : pass === "real" ? [[aware, false]] : pass === "preview" ? [[aware, true]] : [[unaware, false], [aware, true]]).filter(([caps]) => caps.length);
7648
+ const notRun = pass === "none" ? withLaunchHook.map((c) => c.id) : pass === "preview" ? unaware.map((c) => c.id) : [];
6780
7649
  const previewed = runs.filter(([, asPreview]) => asPreview).flatMap(([caps]) => caps.map((c) => c.id));
6781
7650
  const volatileEnv = [];
6782
7651
  let hookDialogClaims;
6783
7652
  if (runs.length) {
6784
- const results = runs.map(([caps, asPreview]) => ({ asPreview, res: runLifecycleHooks("launch", { assertRoots, home, instance: meta.instance, agentName: meta.agent, soulDir: instanceSoulDir(home, meta), contextDir: ctx, rootDir: dirname(dirname(dirname(home))), resolved: { ...(resolvedCfg || {}), capabilities: caps }, priorMeta: meta.capabilityMeta || {}, extraEnv: { OATS_HARNESS: harness, OATS_PREVIOUS_HARNESS: frozen.harness || "", OATS_RUNTIME: harness, OATS_PREVIOUS_RUNTIME: frozen.harness || "", ...(asPreview ? { OATS_LAUNCH_PREVIEW: "1" } : {}), ...extraEnv } }) }));
7653
+ const previousBackend = previousBackendOf(home);
7654
+ const results = runs.map(([caps, asPreview]) => ({ asPreview, res: runLifecycleHooks("launch", { assertRoots, home, instance: meta.instance, agentName: meta.agent, soulDir: instanceSoulDir(home, meta), contextDir: ctx, rootDir: dirname(dirname(dirname(home))), resolved: { ...(resolvedCfg || {}), capabilities: caps }, priorMeta: meta.capabilityMeta || {}, extraEnv: { OATS_HARNESS: harness, OATS_PREVIOUS_HARNESS: frozen.harness || "", OATS_RUNTIME: harness, OATS_PREVIOUS_RUNTIME: frozen.harness || "", OATS_BACKEND: homeBackendOf(meta), ...(previousBackend ? { OATS_PREVIOUS_BACKEND: previousBackend } : {}), ...(asPreview ? { OATS_LAUNCH_PREVIEW: "1" } : {}), ...extraEnv } }) }));
6785
7655
  const failed = results.flatMap(({ res }) => res.failures || []).map((f) => `${f.capability}: ${f.message}`);
6786
7656
  if (failed.length) throw oatsError("E_LAUNCH_PREPARATION", `a capability could not prepare the ${harness} launch:\n ${failed.join("\n ")}`);
6787
7657
  const fresh = results.flatMap(({ res }) => res.contributions || []);
@@ -7017,13 +7887,7 @@ function startSession(home, o) {
7017
7887
  // pending receipt exists for.
7018
7888
  const record = (meta, { id, target, model, command, startedAt, reused, launch, harness: newHarness, yolo: newYolo, stop, nativeRecordId, hookMeta, hookDialogClaims, modelFrom, launchFrom, launchAt, launchDeclared, launchPrompts, launchPromptTarget }, clearPending = true) => {
7019
7889
  checkRoots();
7020
- const baselinePath = findRetirementBaseline(realHome);
7021
- let baseline;
7022
- try { baseline = JSON.parse(readFileSync(baselinePath, "utf8")); } catch (e) {
7023
- if (e.code === "ENOENT") throw missingSessionReceipt(realHome);
7024
- throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or unreadable for ${realHome}: ${e.message}`);
7025
- }
7026
- if (baseline.version !== RETIRE_BASELINE_VERSION || !receiptRecordsHome(baseline, canonicalHomePath(realHome)) || !runtimeAuthorityOf(baseline)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is invalid for ${realHome}`);
7890
+ const { path: baselinePath, baseline } = readSessionReceipt(realHome);
7027
7891
  baseline.runtime = { launched: true, tmux: { session: target.session, window: target.window, socket: resolve(target.socket) } };
7028
7892
  writeJsonAtomic(baselinePath, baseline, 0o600);
7029
7893
  if (o.io?.failBeforeMetadataWrite && reused !== "adopted") throw new Error("injected metadata write failure"); // the write after THIS start's allocation
@@ -7084,7 +7948,10 @@ function startSession(home, o) {
7084
7948
  const movedWarnings = [];
7085
7949
  // 1. Reconcile a pending receipt before the equality gate: it may be the
7086
7950
  // only record of a session an earlier start allocated.
7087
- if (existsSync(pendingPath)) {
7951
+ // A tmux home's only: a home whose receipt names a session provider has none, and a file of
7952
+ // that name in it (the home is its agent's to write) is not read, or it would move the home's
7953
+ // session authority to a tmux target.
7954
+ if (existsSync(pendingPath) && !receiptNamesProvider(realHome)) {
7088
7955
  let pending;
7089
7956
  try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = undefined; }
7090
7957
  const pt = pending?.target;
@@ -7168,6 +8035,9 @@ function startSession(home, o) {
7168
8035
  // 2. The ordinary gate and observation, all under the home's claim.
7169
8036
  const receipt = instanceSessionTarget(realHome);
7170
8037
  const meta = readMeta();
8038
+ // A home on a session provider has no window, pane or pending receipt: its start is its own.
8039
+ // (Its capability rows are its receipt's, never its own record's: lib/home-integrity.mjs.)
8040
+ if (providerHomeOf(receipt)) return startProviderSession(realHome, o, { receipt, meta: trustedRecord(meta, providerHomeTrust(realHome)), checkRoots, drift, cleanupWarnings });
7171
8041
  const harness = meta.harness;
7172
8042
  if (!["pi", "claude", "codex"].includes(harness)) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `instance ${meta.instance || realHome} records harness ${JSON.stringify(harness)}, which this kernel cannot relaunch`);
7173
8043
  let command = meta.command;
@@ -7351,15 +8221,7 @@ function startSession(home, o) {
7351
8221
  // Hooks that ran for real in the plan were handed the plan's: their statements don't reach this one.
7352
8222
  if (handed.OATS_HARNESS_EXECUTABLE !== handedExecutable) hookDialogClaims = voidedDialogClaims(hookDialogClaims);
7353
8223
  handedExecutable = handed.OATS_HARNESS_EXECUTABLE;
7354
- const real = prepareLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots, pass: "real" });
7355
- const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
7356
- const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
7357
- if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
7358
- // A provider's row names its env; the values are in the merged env.
7359
- const rowOf = (h, id) => { const row = h.contributions.find((c) => c.capability === id); return canon({ row, values: (row?.env || []).map((n) => volatileEnv.includes(n) ? null : h.env[n]) }); };
7360
- const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
7361
- throw oatsError("E_LAUNCH_PREPARATION", `the launch hook of ${differing.join(", ") || "a capability"} returned a contribution that differs from its preview contribution (a launch hook returns the same contribution under OATS_LAUNCH_PREVIEW, apart from the values of its volatileEnv); nothing was stopped or started`);
7362
- }
8224
+ const real = realLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots }, previewed, volatileEnv);
7363
8225
  launchPlan.recipe = { ...launchPlan.recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
7364
8226
  command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome });
7365
8227
  if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
@@ -7570,6 +8432,315 @@ function startSession(home, o) {
7570
8432
  const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
7571
8433
  return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
7572
8434
  }
8435
+ /** The real run of a start's preview-aware launch hooks (prepareLaunchHooks, pass "real"), once its
8436
+ * preflight passed, over the contributions they gave as a preview (`previewed`). They may register
8437
+ * the home with their provider now, and must contribute exactly what they contributed as a
8438
+ * preview, which is what the launch was planned and preflighted from, apart from the values of
8439
+ * the env their preview declared volatile (`volatileEnv`). → the real run's answer;
8440
+ * E_LAUNCH_PREPARATION, naming the capabilities that differ, otherwise. One rule for a start on
8441
+ * tmux and on a session provider. */
8442
+ function realLaunchHooks(pass, previewed, volatileEnv) {
8443
+ const real = prepareLaunchHooks({ ...pass, pass: "real" });
8444
+ const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
8445
+ const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
8446
+ if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
8447
+ // A provider's row names its env; the values are in the merged env.
8448
+ const rowOf = (h, id) => { const row = h.contributions.find((c) => c.capability === id); return canon({ row, values: (row?.env || []).map((n) => volatileEnv.includes(n) ? null : h.env[n]) }); };
8449
+ const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
8450
+ throw oatsError("E_LAUNCH_PREPARATION", `the launch hook of ${differing.join(", ") || "a capability"} returned a contribution that differs from its preview contribution (a launch hook returns the same contribution under OATS_LAUNCH_PREVIEW, apart from the values of its volatileEnv); nothing was stopped or started`);
8451
+ }
8452
+ return real;
8453
+ }
8454
+ /** The start, restart and `--resume` of a home on a session provider (lib/session-providers.mjs),
8455
+ * under the home's claim (startClaimed), its refusals and guards already passed (startSession).
8456
+ * `receipt`: instanceSessionTarget's answer, whose `session` (launched before) or `planned` (never
8457
+ * launched) names the backend and the capability that supplies it.
8458
+ *
8459
+ * - start: a home OATS stopped, one never launched, and one whose session is gone, are launched: a
8460
+ * fresh conversation on TASK.md, as for tmux. A session that is there and that OATS did not stop
8461
+ * is never launched over: E_SESSION_RUNNING when it reads `running: true`, else
8462
+ * E_SESSION_UNKNOWN (the provider cannot tell a live idle session from a settled one); so is one
8463
+ * that cannot be inspected.
8464
+ * - restart: stop (recorded first, as every OATS stop: stopProviderHome's rule), then the launch,
8465
+ * under the one claim. A stop that is not confirmed launches nothing: E_SESSION_STOP_FAILED.
8466
+ * - The plan is planLaunch's, with no pane: the recipe or the selection, the launch hooks (which
8467
+ * run before the provider's launch exactly as before a window's), the environment rules.
8468
+ * - The provider's launch answers the endpoint, recorded in the receipt (which clears `stoppedAt`)
8469
+ * and then in instance.json. Its own refusal (E_BACKEND_*) is relayed; a launch that fails is
8470
+ * E_SESSION_START_FAILED, and when its answer was lost the provider is asked to stop whatever
8471
+ * it started. Either way the home stays as it was: stopped, or never launched.
8472
+ * - `--resume` (resumeProviderSession) never launches: it continues the session where it is.
8473
+ * - A home whose modules now hold two capabilities that declare its backend's name is refused
8474
+ * E_BACKEND_AMBIGUOUS before anything is stopped or started (planLaunch). */
8475
+ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, cleanupWarnings }) {
8476
+ const { backend, provider } = providerHomeOf(receipt);
8477
+ const session = receipt.session ?? null;
8478
+ const name = meta.instance || basename(realHome);
8479
+ if (!LAUNCH_HARNESSES.includes(meta.harness)) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `instance ${name} records harness ${JSON.stringify(meta.harness)}, which this kernel cannot relaunch`);
8480
+ // 0. A provider that speaks another wire than this kernel is never called: refused by name,
8481
+ // before its session is read, resumed, stopped or launched.
8482
+ refuseOtherWire(realHome, meta, { backend, provider }, "started", "nothing was stopped or started");
8483
+ if (o.resume === true) {
8484
+ // A launch that was sent and never recorded, on a home launched before or not: unknown, nothing is resumed.
8485
+ if (receipt.unsettled) throw oatsError("E_SESSION_UNKNOWN", `${unsettledLaunchSaid(name, backend, receipt.unsettled.launchSent)}; nothing was resumed`);
8486
+ return resumeProviderSession(realHome, o, { session, meta, backend, provider, drift, cleanupWarnings });
8487
+ }
8488
+ const answerBase = () => ({ ...(drift.length ? { drift } : {}), instance: meta.instance, agent: meta.agent, home: realHome });
8489
+ // 1. The gate: what is there now, when OATS did not stop it. Not asked of an unsettled home
8490
+ // (a launch was sent and never recorded): it is settled below, which leaves it stopped.
8491
+ let bound = null, replaced = false;
8492
+ if (session && session.stoppedAt === null && !receipt.unsettled) {
8493
+ const found = homeSessionProvider(realHome, meta, provider, backend);
8494
+ const inspected = found.problem ? { unavailable: found.problem } : inspectProviderSession(found.binding, session.endpoint, { io: o.io });
8495
+ if (inspected.unavailable) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${name} is running, so nothing was started: ${inspected.unavailable}`);
8496
+ bound = found.binding;
8497
+ if (inspected.observed.present) {
8498
+ if (!o.restart) {
8499
+ if (inspected.observed.running === true) throw oatsError("E_SESSION_RUNNING", `${name} is running (${inspected.observed.state}); nothing was started`);
8500
+ throw oatsError("E_SESSION_UNKNOWN", `${name} has a session on ${backend} that OATS did not stop, and whether it runs cannot be told (${inspected.observed.state}); nothing was started. Stop it first, in the stop's two steps (oats instance stop ${name} --plan, then --apply --plan-revision <rev> --idempotency-key <key>, which the plan prints), or use oats session restart --home ${realHome}`);
8501
+ }
8502
+ replaced = true;
8503
+ }
8504
+ }
8505
+ // 2. The plan: every preflight, and the launch hooks, before anything is stopped.
8506
+ const context = meta.repo && existsSync(meta.repo) ? resolve(meta.repo) : dirname(dirname(dirname(dirname(realHome))));
8507
+ const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
8508
+ let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
8509
+ const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
8510
+ if (reselect?.needsOffered && o.launchConfig === undefined && o.harness === undefined) throw oatsError("E_BAD_ARGS", `--reselect-launch of ${name} needs a read of the workspace's souls: oats-local.yaml souls.launch holds a key besides "*" and this home's soul has no entry of its own (the caller passes that read as launchOffered: lib/instance-resolution.mjs homeSoulsOffered)`);
8511
+ // 1a. The provider's own readiness, with the launch that is planned, BEFORE any launch hook runs
8512
+ // and before anything is stopped: a restart never trades a session that runs for a backend that
8513
+ // says it cannot launch one, and a refused start runs no hook. What it is asked with is the
8514
+ // SELECTION, which needs no hook: the harness, yolo and the launch configuration's own
8515
+ // arguments (a hook's arguments reach the launch input, not this), taken from a plan made with no
8516
+ // hook run at all. It is asked whatever else that plan says (its preflight reads the recorded
8517
+ // contributions, which the real plan refreshes), and, should that plan give no selection, right
8518
+ // after the real one: a launch is never sent, nor a session stopped, with the check not asked.
8519
+ const planOf = (how = {}) => planLaunch({ home: realHome, instance: meta.instance, meta, contextDir: context, agentLike: agent || { harness: meta.harness, model: meta.model, yolo: meta.yolo }, selection: { launchConfig: o.launchConfig, harness: o.harness, model: o.model, yolo: o.yolo }, reselect, resolvedCfg, env: o.env || process.env, assertRoots: checkRoots, pane: NO_PANE, ...how });
8520
+ // The kernel holds its copy of every module of the home (lib/home-integrity.mjs), before any of
8521
+ // their manifests is read for the plan: a launch is made of all of them.
8522
+ const untrusted = homeModulesProblem(realHome);
8523
+ if (untrusted) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${untrusted}; nothing was stopped or started`);
8524
+ const bound0 = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8525
+ if (bound0.problem) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${bound0.problem}`);
8526
+ // What the provider may widen its harness's sandbox by (lib/sandbox-allowances.mjs), from the
8527
+ // deployment's configuration as it is now, which an async caller resolved (`o.sandboxSource`:
8528
+ // lib/instance-resolution.mjs homeSandboxSource, which takes the deployment and the soul from
8529
+ // where this home is, never from what is in it). Only for capabilities that are also this
8530
+ // home's modules: the rest are named, and add nothing. Refused here (E_BACKEND_SANDBOX_HOST),
8531
+ // before any hook runs and before anything is stopped.
8532
+ let sandbox, sandboxAnswer;
8533
+ const sandboxWarnings = [];
8534
+ if (!o.sandboxSource || o.sandboxSource.unavailable) sandbox = { unavailable: o.sandboxSource?.unavailable ?? "this start did not resolve the deployment's configuration" };
8535
+ else {
8536
+ const allowed = homeSandboxAllowances({ source: o.sandboxSource, home: realHome, moduleNames: Object.keys(isPlainObject(meta.modules) ? meta.modules : {}) });
8537
+ sandboxAnswer = allowed;
8538
+ for (const { capability, reason } of allowed.skipped ?? []) sandboxWarnings.push(`sandbox allowances: ${capability} adds no host: ${reason}`);
8539
+ sandbox = sandboxLaunchInput(allowed);
8540
+ // The paths it names exist, and are what they must be, before anything is stopped.
8541
+ ensureSandboxWritePaths(sandbox.write);
8542
+ }
8543
+ let checkAsked = false;
8544
+ const askCheck = (planned) => {
8545
+ checkAsked = true;
8546
+ const notReady = launchReadinessRefusal(bound0.binding, { io: o.io, launch: plannedLaunch({ home: realHome, harness: planned.harness, yolo: planned.recipe.yolo, args: planned.recipe.args, sandbox }) });
8547
+ if (notReady) throw Object.assign(oatsError(notReady.code, `${name} was not started: ${notReady.message}; nothing was stopped or started`), { details: { backend, capability: provider } });
8548
+ };
8549
+ {
8550
+ let selected = null;
8551
+ try { selected = planOf({ preview: true, noHooks: true }); } catch { /* the real plan, below, says what this could not plan */ }
8552
+ if (selected?.recipe) askCheck(selected);
8553
+ }
8554
+ const plan = planOf();
8555
+ if (!checkAsked) askCheck(plan);
8556
+ let recipe = plan.recipe, hookMeta = plan.hookMeta, hookDialogClaims = plan.hookDialogClaims;
8557
+ let warnings = [...plan.warnings];
8558
+ for (const message of plan.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
8559
+ // The preview-aware launch hooks run for real now, over the planned contributions, and must
8560
+ // contribute what they contributed as a preview (apart from the values of their volatile env).
8561
+ if (plan.previewedHooks.length) {
8562
+ const previewed = plan.recipe.hooks;
8563
+ const real = realLaunchHooks({ frozen: { ...plan.frozen, hooks: previewed }, harness: plan.harness, resolvedCfg, contextDir: context, home: realHome, meta, assertRoots: checkRoots }, previewed, plan.volatileEnv);
8564
+ recipe = { ...recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
8565
+ if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
8566
+ if (real.dialogClaims) hookDialogClaims = { ...(hookDialogClaims || {}), ...real.dialogClaims };
8567
+ warnings = [...warnings, ...real.warnings];
8568
+ for (const message of real.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
8569
+ }
8570
+ const removed = removedLaunchEnv({ declared: plan.declaredEnv, hooksEnv: recipe.hooks?.env, configEnv: recipe.env });
8571
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
8572
+ // (The binding after the launch hooks: what they left of the home's module copy is what launches.)
8573
+ const found = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8574
+ if (found.problem) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${found.problem}`);
8575
+ for (const message of sandboxWarnings) { warnings.push(message); appendEvent(realHome, { kind: "launch-warning", data: { message } }); }
8576
+ const input = providerLaunchInput({ home: realHome, instance: meta.instance, recipe, env: o.env || process.env, removed, previous: session?.endpoint ?? null, sandbox });
8577
+ checkRoots();
8578
+ // 2. A launch that an earlier spawn or start sent and never recorded (launchSentOf): settled
8579
+ // first. The provider stops whatever that launch started, and the home is then planned, or
8580
+ // stopped; or nothing is launched beside it.
8581
+ // (A home launched before has its recorded session stopped first, by the settle.)
8582
+ const unsettled = settleSentLaunch(realHome, meta, receipt.unsettled, o.stopGraceMs, o.io);
8583
+ if (unsettled) throw oatsError("E_SESSION_STOP_FAILED", `a launch of ${name} was sent to session backend ${backend} before and never recorded, and the backend did not confirm that the session recorded before it, and what that launch started, are stopped (${unsettled}); nothing was started`);
8584
+ // 3. The session at the recorded endpoint. A restart's stop: recorded first, then the provider's.
8585
+ let stop = null;
8586
+ if (replaced) {
8587
+ const { unconfirmed, waitedMs } = stopProviderSessionRecorded(realHome, meta, session, { graceMs: o.stopGraceMs, io: o.io });
8588
+ appendEvent(realHome, { kind: unconfirmed ? "stop-refused" : "restarted", data: { phase: "restart-stop", signal: null, waitedMs, stillRunning: [] } });
8589
+ if (unconfirmed) throw oatsError("E_SESSION_STOP_FAILED", `${name} is recorded as stopped by OATS, but session backend ${backend} did not confirm that its session stopped (${unconfirmed}); nothing was started. Start it once its session is gone: oats session start --home ${realHome}`);
8590
+ stop = { stopped: true, waitedMs };
8591
+ } else if (session && session.stoppedAt !== null && !receipt.unsettled) {
8592
+ // A home OATS stopped: its last stop may not have been confirmed (E_SESSION_STOP_FAILED leaves
8593
+ // it recorded as stopped). The launch replaces the endpoint, after which OATS could no longer
8594
+ // address a session still running there: the provider is asked once more first.
8595
+ const unconfirmed = providerStopUnconfirmed(realHome, meta, session, session.endpoint, o.stopGraceMs, o.io);
8596
+ if (unconfirmed) throw oatsError("E_SESSION_STOP_FAILED", `${name} is recorded as stopped by OATS, but session backend ${backend} did not confirm that its last session stopped (${unconfirmed}); nothing was started`);
8597
+ }
8598
+ // 4. The launch.
8599
+ checkRoots();
8600
+ writeKernelShim(realHome);
8601
+ const startedAt = new Date().toISOString(), id = randomUUID();
8602
+ assertHostRunAdmission();
8603
+ // A call a killed kernel left for this home (a stop that would run late, and stop the session
8604
+ // launched here) is ended first.
8605
+ const orphaned = endProviderCalls(realHome);
8606
+ if (orphaned) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${orphaned}; nothing was sent to session backend ${backend}`);
8607
+ // From here a session may exist that no record names yet: the receipt says a launch was sent,
8608
+ // until its outcome is recorded.
8609
+ const launchSent = markLaunchSent(realHome);
8610
+ // A home launched before whose session OATS did not stop (it is gone, by the gate): the provider
8611
+ // is asked to stop it all the same (its stop is idempotent). An input that reached it since the
8612
+ // gate had the provider restart it, and the launch replaces its endpoint, after which OATS
8613
+ // could not address it. AFTER the mark: an input that read the home before the mark has ended
8614
+ // its provider call by now, and one that reads it after the mark stops that session itself, so
8615
+ // no input restarts it behind this stop. Not confirmed: nothing was sent, the mark is taken back.
8616
+ if (session && !replaced && session.stoppedAt === null && !receipt.unsettled) {
8617
+ const stale = providerStopUnconfirmed(realHome, meta, session, session.endpoint, o.stopGraceMs, o.io);
8618
+ if (stale) { clearLaunchSent(realHome); throw oatsError("E_SESSION_STOP_FAILED", `session backend ${backend} did not confirm that the last session of ${name} is stopped (${stale}); nothing was started`); }
8619
+ }
8620
+ const call = markProviderCall(realHome, "launch");
8621
+ let answered;
8622
+ try { answered = launchProviderSession(found.binding, input, { io: o.io, groupFile: call.groupFile }); } finally { call.done(); }
8623
+ if (answered.refused) { clearLaunchSent(realHome); throw Object.assign(oatsError(answered.refused.code, `session backend ${backend} refused to launch ${name}: ${answered.refused.message}`), { details: { backend, capability: provider } }); }
8624
+ if (answered.failed) {
8625
+ // A launch whose answer was lost may have started a session: the provider stops what is rooted
8626
+ // at this home. The home's record is unchanged either way; one it could not stop stays
8627
+ // recorded as sent, and the next stop or start asks again.
8628
+ // (A launch that failed for certain started nothing: unmarked, the home is as it was.)
8629
+ // (The session recorded before this launch was stopped in step 3, or after the mark.)
8630
+ const unstopped = answered.uncertain ? settleSentLaunch(realHome, meta, { backend, provider, launchSent }, 20000, o.io, { recordedStopped: true }) : (clearLaunchSent(realHome), null);
8631
+ const compensated = unstopped ? { failed: unstopped } : null;
8632
+ throw oatsError("E_SESSION_START_FAILED", `session backend ${backend} did not launch ${name}: ${answered.failed}${compensated?.failed ? `; a session it may have started could not be stopped (${compensated.failed}): check ${provider}'s own tooling before retrying` : ""}`);
8633
+ }
8634
+ // 5. The records, in the launch's three writes: the session boundary and the receipt's endpoint
8635
+ // (which clears `stoppedAt`) with the launch still marked as sent, then the record, then the
8636
+ // mark removed. Killed or failed between any two, the home is unsettled, and the next verb
8637
+ // settles it: never a record that contradicts its receipt.
8638
+ const unrecorded = (e) => {
8639
+ // (The launch is still marked as sent: the fence. Then the drain, then the stop.)
8640
+ const left = drainProviderCalls(realHome);
8641
+ const stopped = left ? { failed: left } : trackedProviderStop(realHome, found.binding, answered.endpoint, 20, { io: o.io });
8642
+ if (!stopped.failed) { try { recordLaunchSettled(realHome); } catch { /* the launch stays marked: the next stop or start asks the provider again */ } }
8643
+ return asKernelError(e, "E_SESSION_START_FAILED", `${name} was launched on ${backend}, but its session could not be recorded (${e?.message ?? e}); the session was asked to stop${stopped.failed ? `, which it did not confirm (${stopped.failed}): check ${provider}'s own tooling` : ""}, and the home is as it was`);
8644
+ };
8645
+ try {
8646
+ recordStartBoundary(realHome, { startId: id, startedAt, harness: plan.harness, backend, launchConfig: recipe.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
8647
+ checkRoots();
8648
+ } catch (e) { throw unrecorded(e); }
8649
+ const restarts = (Array.isArray(meta.restarts) ? meta.restarts : []).slice(-19);
8650
+ restarts.push({ startedAt, model: plan.model ?? null, reused: "new" });
8651
+ const modelFrom = modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null });
8652
+ const next = { ...meta, model: plan.model, launched: true, startId: id, restarts, restartCount: (meta.restartCount || 0) + 1, ...(modelFrom ? { modelFrom } : {}),
8653
+ launch: recipe, harness: plan.harness, ...(plan.yolo !== undefined ? { yolo: plan.yolo } : {}),
8654
+ ...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at ?? null, launchDeclared: plan.launchChoice.declared ?? null } : {}),
8655
+ ...(hookMeta ? { capabilityMeta: { ...(meta.capabilityMeta || {}), ...hookMeta } } : {}),
8656
+ backend, session: { provider, endpoint: answered.endpoint }, launchPrompts: notEngaged(id) };
8657
+ if (hookDialogClaims) { next.dialogClaims = replacedDialogClaims(meta.dialogClaims, hookDialogClaims); if (!next.dialogClaims) delete next.dialogClaims; }
8658
+ delete next.launchPromptTarget;
8659
+ try { recordLaunchOutcome(realHome, { backend, provider, endpoint: answered.endpoint }, next); }
8660
+ catch (e) {
8661
+ if (!outcomeRecordFailures.has(e)) throw unrecorded(e);
8662
+ throw oatsError("E_SESSION_START_INCOMPLETE", `${name} was started on ${backend} and its receipt records the session, but the rest of its outcome could not be recorded: ${e.message}; its launch stays marked as sent, so the home reads as unknown: a stop or a start settles it (the backend is asked to stop that session first)`); }
8663
+ // `target` is a tmux session's: null here, so a reader of a start's answer finds every key it knows.
8664
+ // (`moduleCopy`, as the home's status row carries it: which copy of its modules ran, and whether
8665
+ // the home's own record of them is the receipt's. The home's record is read as a row reads it
8666
+ // (readHomeRecord: a regular file only), since the session that could exchange it now runs.)
8667
+ let startedModuleCopy;
8668
+ try { startedModuleCopy = moduleCopyReport(readHomeRecord(realHome).meta, providerHomeTrust(realHome)); } catch { startedModuleCopy = undefined; }
8669
+ return { ...answerBase(), harness: next.harness, backend, model: plan.model ?? null, launchConfig: recipe.launchConfig ?? null, yolo: next.yolo ?? null, target: null, sandbox: sandboxAnswer ?? sandbox, ...(startedModuleCopy ? { moduleCopy: startedModuleCopy } : {}), session: { provider, endpoint: answered.endpoint }, startedAt, restartCount: next.restartCount, reused: "new", warnings: [...cleanupWarnings, ...warnings], ...(stop ? { stop } : {}) };
8670
+ }
8671
+ /** `session start --resume` of a home on a session provider, and what the machine sweep runs for it
8672
+ * (lib/session-resume.mjs): the session continues in its own conversation, through the provider's
8673
+ * input; nothing is launched. Two homes are resumed, and no other:
8674
+ * - one **stopped with the host** (`stoppedAt`, and the stop receipt says `oats host run`'s
8675
+ * shutdown wrote it): the notice is sent, then the stop cleared, then its receipt removed
8676
+ * (died between, the home is still to resume, or running). Not counted: the host's shutdown
8677
+ * is no crash.
8678
+ * - one whose session is **lost** (gone, and OATS did not stop it; a provider reads a session in
8679
+ * error so): the kernel's resume primitive first (resumeLostSession: no process of the last run
8680
+ * in the home, then the count against the home's cap), then the notice.
8681
+ * The notice is input: a claim that holds a scheduled wake holds it too (a permission prompt, a
8682
+ * question: E_SESSION_PROMPT_OPEN, nothing sent), and the provider's refusals are its refusals
8683
+ * (E_SESSION_PROMPT_OPEN, E_SESSION_INPUT_QUEUED: a queued notice is no resume). A notice that
8684
+ * was not sent leaves the home as it was (still stopped with the host; the count taken back), so
8685
+ * a later sweep tries again. A notice whose call failed keeps its count: it may have been sent,
8686
+ * and a home stopped with the host, which stays so, has the provider asked to stop it again.
8687
+ * Anything else was not lost: a home an operator stopped (E_RESUME_NOT_LOST: an ordinary start
8688
+ * opens a fresh conversation), a session that runs (E_SESSION_RUNNING) or is there
8689
+ * (E_RESUME_NOT_LOST), one that cannot be inspected (E_SESSION_UNKNOWN). */
8690
+ function resumeProviderSession(realHome, o, { session, meta, backend, provider, drift, cleanupWarnings }) {
8691
+ const name = meta.instance || basename(realHome);
8692
+ const notLost = (why) => oatsError("E_RESUME_NOT_LOST", `${name} did not lose its session (${why}); --resume brings back only a lost session; nothing was started (an ordinary session start opens a fresh conversation)`);
8693
+ if (!session) throw notLost("it was never launched");
8694
+ const owed = owedRetire(realHome);
8695
+ if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(name, owed.state)}; nothing was started`);
8696
+ const hostStopped = session.stoppedAt !== null && lostReasonOf(realHome, meta) === HOST_STOP_REASON;
8697
+ if (session.stoppedAt !== null && !hostStopped) throw notLost("it stopped");
8698
+ const found = homeSessionProvider(realHome, meta, provider, backend);
8699
+ if (found.problem) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${name} is running, so nothing was started: ${found.problem}`);
8700
+ if (!hostStopped) {
8701
+ const inspected = inspectProviderSession(found.binding, session.endpoint, { io: o.io });
8702
+ if (inspected.unavailable) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${name} is running, so nothing was started: ${inspected.unavailable}`);
8703
+ if (inspected.observed.present) {
8704
+ if (inspected.observed.running === true) throw oatsError("E_SESSION_RUNNING", `${name} is running (${inspected.observed.state}); nothing was started`);
8705
+ throw notLost("its session is there");
8706
+ }
8707
+ }
8708
+ // The notice holds on claims, as a scheduled wake does: it must not answer a dialog.
8709
+ let held;
8710
+ try { held = waitingHold(realHome); } catch { held = { claimReason: null, unreadable: "the claims could not be read" }; }
8711
+ if (held) throw oatsError("E_SESSION_PROMPT_OPEN", `${name} has a ${held.claimReason ?? "waiting"} claim open${held.unreadable ? ` (${held.unreadable})` : ""}: its session waits on its person, and the resume notice was not sent`);
8712
+ const counted = hostStopped ? null : resumeLostSession(realHome, name);
8713
+ // A home stopped with the host stays recorded as stopped until its notice has been sent: the
8714
+ // notice first, then `stoppedAt` cleared, then the stop receipt removed. Died after the notice,
8715
+ // the home is still stopped with the host, and its session may run again: the next sweep sends
8716
+ // the notice once more, and a stop or a start asks the provider to stop it, as of any stopped home.
8717
+ // (A stop a killed kernel left behind, the host's own included, would run late and stop the
8718
+ // session this resumes: it is ended first.)
8719
+ const orphaned = endProviderCalls(realHome);
8720
+ if (orphaned) { counted?.undo(); throw oatsError("E_SESSION_INPUT_FAILED", `${name} was not resumed: ${orphaned}; nothing was sent`); }
8721
+ const notice = markProviderCall(realHome, "input");
8722
+ try { inputProviderSession(found.binding, session.endpoint, PROVIDER_RESUME_NOTICE, { io: o.io, groupFile: notice.groupFile }); }
8723
+ catch (e) {
8724
+ notice.done();
8725
+ // The provider refused the notice: nothing was sent, so the count is taken back. A call that
8726
+ // failed may have restarted the session: it stays counted, and a home stopped with the host,
8727
+ // which stays stopped and still to resume, has it asked to stop again (a stopped home has
8728
+ // no session).
8729
+ if (inputWasRefused(e)) counted?.undo();
8730
+ else if (hostStopped) providerStopUnconfirmed(realHome, meta, session, session.endpoint, 20000, o.io);
8731
+ throw e;
8732
+ }
8733
+ notice.done();
8734
+ dieAt("resume:notice-sent");
8735
+ if (hostStopped) {
8736
+ writeProviderRuntime(realHome, { backend, provider, endpoint: session.endpoint });
8737
+ dieAt("resume:stop-cleared");
8738
+ // The stop is over: its receipt goes, so that a later loss of this same start is not read as
8739
+ // another stop with the host.
8740
+ rmSync(join(realHome, STOP_RECEIPT_FILE), { force: true });
8741
+ }
8742
+ return { ...(drift.length ? { drift } : {}), instance: meta.instance, agent: meta.agent, home: realHome, harness: meta.harness, backend, model: meta.model ?? null, launchConfig: meta.launch?.launchConfig ?? null, yolo: meta.yolo ?? null, target: null, session: { provider, endpoint: session.endpoint }, startedAt: null, restartCount: meta.restartCount || 0, reused: "session", warnings: [...cleanupWarnings], resume: { resumed: true, harness: meta.harness } };
8743
+ }
7573
8744
  /** What a start, holding the home's lifecycle claim (startClaimed), refuses at `lock`, the home's
7574
8745
  * `.oats-start.lock`. Two starts exclude each other through that claim, and a start makes
7575
8746
  * nothing at this path. An upgrade writes its regular file there and keeps it until its final
@@ -10092,7 +11263,7 @@ function retireSteps(root, name, o, found, at) {
10092
11263
  }
10093
11264
  }
10094
11265
  if (runtimeAuthority) {
10095
- const metaAgrees = launchStateAgrees(meta, runtimeAuthority) && (!runtimeAuthority.launched || tmuxEndpointAgrees(meta, runtimeAuthority));
11266
+ const metaAgrees = launchStateAgrees(meta, runtimeAuthority) && endpointAgrees(meta, runtimeAuthority);
10096
11267
  if (!metaAgrees) {
10097
11268
  throw authorityMismatch(`cannot quiesce ${name}: mutable instance metadata disagrees with independent runtime endpoint authority`, meta, runtimeAuthority);
10098
11269
  }
@@ -10128,7 +11299,79 @@ function retireSteps(root, name, o, found, at) {
10128
11299
  // `=` forces exact matching: tmux targets otherwise PREFIX-match window names.
10129
11300
  // A no-launch instance is already quiesced. A launched one must have exact
10130
11301
  // window absence established before recovery copying begins.
10131
- if (!self && runtimeAuthority?.launched) {
11302
+ // What the retire says of a session provider's session it could not stop through the provider.
11303
+ let providerStopWarning = null;
11304
+ // What it says of an input that outlasted its wait (waitForInputsInFlight).
11305
+ let inputInFlightWarning = null;
11306
+ // A launch that was sent to the home's provider and never recorded (launchSentOf): the provider
11307
+ // stops whatever it started first, for a home that was never launched as for a launched one.
11308
+ const sentLaunch = !self ? [runtimeAuthority?.session, runtimeAuthority?.planned].find((recorded) => recorded?.launchSent) ?? null : null;
11309
+ if (sentLaunch && !runtimeAuthority?.session) {
11310
+ const unsettledLaunch = settleSentLaunch(found.home, meta, sentLaunch);
11311
+ // Never launched by any record, and a session may run: the provider's stop, then no process
11312
+ // may work in the home, as below.
11313
+ const { backend, provider } = sentLaunch;
11314
+ at.sessionTouched = true;
11315
+ ownSession = "unverified";
11316
+ const unquiet = (why) => oatsError("E_RUNTIME_QUIESCE_FAILED", unsettledLaunch ? `could not establish that the ${backend} session a launch of ${name} may have started is stopped: ${unsettledLaunch}; ${why}` : `session backend ${backend} stopped what a launch of ${name} had started, ${why}`);
11317
+ const scan = processesInHome(found.home);
11318
+ if (!scan.ok) throw unquiet(`and whether a process still works in its home could not be established (${scan.error})`);
11319
+ if (scan.processes.length) throw unquiet(`${unsettledLaunch ? "" : "and "}a process works in its home (${namedProcesses(scan.processes)}); stop it, then retire again. A shell named here may be your own: one whose working directory is in the home counts, and leaving the home's directory clears it`);
11320
+ if (unsettledLaunch) providerStopWarning = `a launch of ${name} was sent to session backend ${backend} and never recorded, and the session it may have started was not stopped through the backend (${unsettledLaunch}); no process works in its home, so the retire went on: archive or remove that session with ${provider}'s own tooling`;
11321
+ ownSession = "stopped";
11322
+ }
11323
+ if (!self && runtimeAuthority?.session) {
11324
+ // A home on a session provider: `stoppedAt` first, so that from here its session reads stopped
11325
+ // and input to it is refused; then the provider's stop; then no process may work in the home,
11326
+ // whatever the provider answered: a stop it confirms can still leave one (a harness that
11327
+ // outlives its server), and OATS sees no window whose absence would say otherwise. Stricter
11328
+ // than a tmux home's retire, which takes its window's absence: a shell left in the home counts,
11329
+ // the operator's own included, and the refusal says so.
11330
+ // A stop that cannot be confirmed (the provider fails, or its capability is no longer among
11331
+ // the home's modules) does not strand the home: the retire goes on when no process works in
11332
+ // the home, and says that the provider's session was not stopped through it.
11333
+ const { backend, provider, endpoint, stoppedAt } = runtimeAuthority.session;
11334
+ at.sessionTouched = true;
11335
+ ownSession = "unverified";
11336
+ // The recorded session by the stop rule (stopProviderSessionRecorded: `stoppedAt`, the stop
11337
+ // receipt, then the provider); a home already stopped has the provider asked again, and its
11338
+ // stop becomes the operator's. Then the inputs that were in flight when `stoppedAt` was
11339
+ // recorded (a new one is refused from then on): the provider restarts a session on an input,
11340
+ // and once the home is removed no input can ask it to stop again, so the retire waits for
11341
+ // them, a bounded time, and asks once more. Then a launch that was sent and never recorded.
11342
+ let recordedStop;
11343
+ const outlasted = [];
11344
+ if (stoppedAt === null) {
11345
+ try { recordedStop = stopProviderSessionRecorded(found.home, meta, runtimeAuthority.session, { outlasted }).unconfirmed; }
11346
+ catch (e) {
11347
+ // The fence could not be written. Without it an input is still admitted, and one that
11348
+ // acts after the provider's stop restarts a session under a home that is then removed: the
11349
+ // provider is not asked, and nothing is retired. (A home whose launch is marked as sent has
11350
+ // that mark for a fence: its stop goes on, below.)
11351
+ if (!sentLaunch) throw oatsError("E_RUNTIME_QUIESCE_FAILED", `cannot retire ${name}: that its ${backend} session is being stopped could not be recorded (${e?.code ?? e?.message ?? e}), so input to it would still be admitted; the session was not asked to stop and nothing was retired`);
11352
+ }
11353
+ } else {
11354
+ try { recordStop(found.home, null); } catch { /* as above */ }
11355
+ }
11356
+ if (recordedStop === undefined) recordedStop = providerStopUnconfirmed(found.home, meta, runtimeAuthority.session, runtimeAuthority.session.endpoint, 20000, undefined, null, { outlasted });
11357
+ if (outlasted.length) inputInFlightWarning = `an input to ${name} was still being sent when the retire went on (pid ${outlasted.join(", ")}): its command was ended before the ${backend} session was asked to stop`;
11358
+ // The launch that was sent is settled only once the recorded session is confirmed stopped.
11359
+ // One that is not: the provider is asked to stop what that launch started all the same (the home
11360
+ // is about to be removed), and nothing is recorded of it.
11361
+ const sentStop = !sentLaunch ? null : recordedStop
11362
+ ? providerStopUnconfirmed(found.home, meta, sentLaunch, null, 20000, undefined, sentLaunch.launchSent)
11363
+ : settleSentLaunch(found.home, meta, sentLaunch, 20000, undefined, { recordedStopped: true });
11364
+ const unconfirmed = [recordedStop, sentStop].filter(Boolean).join("; ") || null;
11365
+ const unquiet = (why) => oatsError("E_RUNTIME_QUIESCE_FAILED", unconfirmed ? `could not establish that the ${backend} session of ${name} stopped: ${unconfirmed}; ${why}` : `the ${backend} session of ${name} stopped, ${why}`);
11366
+ const scan = processesInHome(found.home);
11367
+ if (!scan.ok) throw unquiet(`and whether a process still works in its home could not be established (${scan.error})`);
11368
+ if (scan.processes.length) throw unquiet(`${unconfirmed ? "" : "and "}a process works in its home (${namedProcesses(scan.processes)}); stop it, then retire again. A shell named here may be your own: one whose working directory is in the home counts, and leaving the home's directory clears it`);
11369
+ if (unconfirmed) {
11370
+ providerStopWarning = `the ${backend} session of ${name} was not stopped through its session backend (${unconfirmed}); no process works in its home, so the retire went on: archive or remove that session with ${provider}'s own tooling`;
11371
+ }
11372
+ ownSession = "stopped";
11373
+ }
11374
+ if (!self && runtimeAuthority?.tmux) {
10132
11375
  const runtimeSession = runtimeAuthority.tmux.session;
10133
11376
  const runtimeWindow = runtimeAuthority.tmux.window;
10134
11377
  const runtimeSocket = runtimeAuthority.tmux.socket;
@@ -10752,6 +11995,8 @@ function retireSteps(root, name, o, found, at) {
10752
11995
  at.lead = () => `${name}: the directory at ${found.home} could not be removed`;
10753
11996
  rmSync(found.home, { recursive: true, force: true });
10754
11997
  at.lead = () => `${name}: its home was removed, and a file the retire leaves beside it could not be`;
11998
+ // (The kernel's own copies of a provider home's modules go with the home.)
11999
+ removeModulesStore(found.home);
10755
12000
  rmSync(directoryFallbackPath, { force: true });
10756
12001
  // The owed retirement is paid: clear the pending marker, and the failed
10757
12002
  // outcome an earlier deferred attempt may have left beside the home; a
@@ -10765,7 +12010,7 @@ function retireSteps(root, name, o, found, at) {
10765
12010
  }
10766
12011
 
10767
12012
  const result = { retired: name, agent: found.agent.name, workRecovery, retention, extraWorktrees, worktreeRemoved: isWorktree && !!retention && retention.worktree !== "retained", branchDeleted: false, ...(branchDeletedByRetry || branchKeptReason ? { spawnCompensation: { branch: meta.branch, branchDeleted: branchDeletedByRetry, ...(branchKeptReason ? { reason: branchKeptReason } : {}) } } : {}), removedDir: !o.keepDir && (!stillIncomplete || forced), rollbackIncomplete: forced ? undefined : stillIncomplete, forcedIncomplete: forced ? stillIncomplete : undefined, retainedHome: stillIncomplete && !forced ? found.home : undefined, relinked: relinked.length ? relinked : undefined, childrenStopped, capabilityMeta: hookResults?.meta, warnings: (() => {
10768
- const w = [...spawnGroupWarnings, ...(hookResults?.warnings || []), ...relinkWarnings];
12013
+ const w = [...spawnGroupWarnings, ...(providerStopWarning ? [providerStopWarning] : []), ...(inputInFlightWarning ? [inputInFlightWarning] : []), ...(hookResults?.warnings || []), ...relinkWarnings];
10769
12014
  // What the retire read from Git about work/ where the record did not say it (#962).
10770
12015
  if (repoFromGit) w.push(`the record names no repository for the work tree at ${workPath}: the retire used the one Git names for it, ${repoFromGit}; the record was not changed`);
10771
12016
  if (homeDirectory && workIs.tree && !o.keepDir && (!stillIncomplete || forced)) w.push(`${workPath} was a registered worktree of ${workIs.tree.repo} and not this instance's own tree: it was copied to recovery and removed with the home as a directory of the home. Its entry stays in that repository until a prune (git -C ${shq(workIs.tree.repo)} worktree prune); its branch and commits are untouched`);
@@ -10802,7 +12047,14 @@ function retireSteps(root, name, o, found, at) {
10802
12047
  // The home `--keep-dir` keeps reads `stopped` once its window is gone, never `lost` (recordStop,
10803
12048
  // as above). A record that cannot be written stops nothing: the home then reads lost, as before.
10804
12049
  if (o.keepDir) { try { recordStop(found.home, null); } catch { /* see above */ } }
10805
- if (typeof killSocket === "string" && killSocket) {
12050
+ if (runtimeAuthority?.session) {
12051
+ // A session provider's session has no window to kill: it is stopped as any OATS stop does
12052
+ // (stopProviderHome), by a detached process, after the caller's last words.
12053
+ try {
12054
+ const child = spawnProcess(process.execPath, ["--input-type=module", "-e", `import { stopInstanceSession } from ${JSON.stringify(import.meta.url)};\nsetTimeout(() => { try { stopInstanceSession(${JSON.stringify(found.home)}, {}); } catch { process.exitCode = 1; } }, ${(o.selfKillDelaySec ?? 8) * 1000});`], { detached: true, stdio: "ignore", cwd: dirname(found.home), env: withoutKernelEnvironment(process.env) });
12055
+ child.unref();
12056
+ } catch { /* the home keeps its session: \`oats instance stop\` ends it */ }
12057
+ } else if (typeof killSocket === "string" && killSocket) {
10806
12058
  const kill = `sleep ${o.selfKillDelaySec ?? 8}; tmux -u -S ${shq(killSocket)} kill-window -t ${killTarget} 2>/dev/null || true`;
10807
12059
  shTry(`tmux -u -S ${shq(killSocket)} run-shell -b ${shq(kill.replace(/#/g, "##"))}`);
10808
12060
  } else shTry(`tmux run-shell -b 'sleep ${o.selfKillDelaySec ?? 8}; tmux kill-window -t ${killTarget} 2>/dev/null || true'`);