@awebai/oats 0.69.22 → 0.69.24

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 (98) hide show
  1. package/bin/oats.mjs +185 -38
  2. package/docs/capabilities.md +365 -7
  3. package/docs/capability-manifest.schema.json +37 -1
  4. package/docs/configuration.md +27 -7
  5. package/docs/container.md +206 -228
  6. package/docs/design/2026-11-19-sandboxes.md +1352 -0
  7. package/docs/design/2026-11-20-provider-home-lifecycle.md +320 -0
  8. package/docs/design/README.md +7 -0
  9. package/docs/desktop-cli-api.md +673 -81
  10. package/docs/desktop.md +241 -65
  11. package/docs/execution-targets.md +186 -3
  12. package/docs/first-team.md +11 -0
  13. package/docs/implementation.md +6 -2
  14. package/docs/integrations.md +3 -3
  15. package/docs/knowledge-capability-authoring.md +10 -7
  16. package/docs/knowledge-reference/acceptance.md +21 -19
  17. package/docs/knowledge-reference/adoption.md +18 -4
  18. package/docs/knowledge-reference/model.md +11 -9
  19. package/docs/knowledge-reference/package-craft.md +2 -2
  20. package/docs/knowledge-reference/proposal.md +127 -0
  21. package/docs/knowledge-reference/provider-mapping.md +10 -10
  22. package/docs/knowledge-reference/reader-capture.md +26 -22
  23. package/docs/knowledge-theory.md +1 -1
  24. package/docs/knowledge.md +25 -16
  25. package/docs/official-catalog.md +4 -4
  26. package/docs/packages.md +13 -13
  27. package/docs/release-notes/v0.69.23.md +231 -0
  28. package/docs/release-notes/v0.69.24.md +264 -0
  29. package/docs/servers.md +10 -6
  30. package/docs/souls-and-instances.md +96 -22
  31. package/docs/tui.md +25 -4
  32. package/docs/upgrading.md +19 -5
  33. package/docs/workspaces.md +14 -6
  34. package/lib/argv.mjs +6 -2
  35. package/lib/capability-contract.mjs +2 -2
  36. package/lib/capability-show.mjs +11 -1
  37. package/lib/command-flags.mjs +40 -3
  38. package/lib/compile-cache.mjs +1 -1
  39. package/lib/core.mjs +1201 -195
  40. package/lib/errors.mjs +4 -1
  41. package/lib/hook-env.mjs +106 -0
  42. package/lib/host-run.mjs +11 -3
  43. package/lib/instance-board.mjs +337 -0
  44. package/lib/instance-events.mjs +48 -10
  45. package/lib/instance-inspect.mjs +44 -0
  46. package/lib/instance-lifecycle.mjs +34 -18
  47. package/lib/instance-listing.mjs +113 -16
  48. package/lib/instance-related-work.mjs +143 -0
  49. package/lib/kernel-features.mjs +13 -1
  50. package/lib/node-version.mjs +9 -0
  51. package/lib/provider-call-child.mjs +60 -0
  52. package/lib/provider-resume.mjs +83 -0
  53. package/lib/provider-test-seams.mjs +20 -0
  54. package/lib/read-call.mjs +2 -0
  55. package/lib/reserved-launch-env.mjs +8 -1
  56. package/lib/retire-admission.mjs +5 -1
  57. package/lib/schedule.mjs +14 -4
  58. package/lib/servers.mjs +151 -17
  59. package/lib/session-inspect.mjs +104 -13
  60. package/lib/session-providers.mjs +528 -0
  61. package/lib/session-resume.mjs +68 -15
  62. package/lib/stable-node.mjs +3 -0
  63. package/lib/triggers.mjs +3 -1
  64. package/package-catalog.json +3 -3
  65. package/package.json +2 -1
  66. package/packages/client/capability-list.mjs +21 -0
  67. package/packages/client/cli-adapter.mjs +19 -4
  68. package/packages/client/cli-locator.mjs +5 -1
  69. package/packages/client/deployment-data.mjs +27 -3
  70. package/packages/client/deployment-panel.mjs +27 -4
  71. package/packages/client/home-board.mjs +33 -19
  72. package/packages/client/inspect-boundary.mjs +18 -8
  73. package/packages/client/instance-acts.mjs +30 -3
  74. package/packages/client/instance-board.mjs +206 -0
  75. package/packages/client/instance-presentation.mjs +55 -0
  76. package/packages/client/instance-tree.mjs +34 -4
  77. package/packages/client/keymap.mjs +5 -0
  78. package/packages/client/liveness.mjs +15 -4
  79. package/packages/client/mail-contract.mjs +130 -0
  80. package/packages/client/own-codes.mjs +5 -1
  81. package/packages/client/panel-views.mjs +7 -7
  82. package/packages/client/related-work.mjs +84 -0
  83. package/packages/client/remote-roster.mjs +9 -3
  84. package/packages/client/session-backends.mjs +31 -0
  85. package/packages/client/session-start.mjs +18 -6
  86. package/packages/client/spawn-apply-cli.mjs +5 -3
  87. package/packages/client/spawn-apply-contract.mjs +25 -2
  88. package/packages/client/spawn-apply.mjs +5 -1
  89. package/packages/client/spawn-messages.mjs +3 -0
  90. package/packages/client/terminal-contract.mjs +4 -0
  91. package/packages/client/waiting-on-you.mjs +12 -2
  92. package/packages/client/workspace-cli.mjs +13 -2
  93. package/packages/tui/lib/model.mjs +14 -3
  94. package/packages/tui/lib/store.mjs +12 -3
  95. package/skills/oats-getting-started/SKILL.md +11 -8
  96. package/docs/knowledge-reference/harvester.md +0 -109
  97. package/lib/instance-same-work.mjs +0 -67
  98. package/packages/client/same-work.mjs +0 -49
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";
@@ -48,7 +48,7 @@ import { createHash, randomUUID } from "node:crypto";
48
48
  import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
49
49
  import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
50
50
  import { noteRuntimeName } from "./deprecation.mjs";
51
- import { RETIRE_DELETE_BRANCH_REFUSED } from "./command-flags.mjs";
51
+ import { RETIRE_DELETE_BRANCH_REFUSED, SAME_WORK_OPTION_RENAMED } from "./command-flags.mjs";
52
52
  import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
53
53
  import { AGENT_PANE_OPTION, inspectSessionTarget, inputSessionTarget, resolveAgentPane } from "./session-input.mjs";
54
54
  import { RETIRE_HOOK_WARNING_KIND, appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
@@ -58,11 +58,12 @@ 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";
61
62
  import { assertNoPartialUpgrade, packageRespawnWarning, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
62
63
 
63
64
  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";
65
+ 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";
66
+ import { envRows, recordedTeams } from "./teams.mjs";
66
67
  import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
67
68
  import { shq, shellWord } from "./shell-word.mjs";
68
69
  import { CONFIG_DIR_VAR, HARNESS_FOLDER_VAR, claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigFolder } from "./harness-trust.mjs";
@@ -99,8 +100,14 @@ import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPla
99
100
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
100
101
  import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
101
102
  import { PIN_FILE } from "./instance-pin.mjs";
102
- import { SAME_WORK_FILE, writeSameWork } from "./instance-same-work.mjs";
103
- import { HOST_STOP_REASON, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
103
+ import { dieAt } from "./provider-test-seams.mjs";
104
+ import { SESSION_PROVIDER_ANY, launchSentOf, unsettledLaunchSaid, sessionProviderTimeout, recordsSessionProvider, launchReadinessRefusal, homeSessionProvider, inputProviderSession, inputWasRefused, sameEndpoint, inspectProviderSession, launchProviderSession, providerRuntimeRecord, selectSessionBackend, stopProviderSession } from "./session-providers.mjs";
105
+ import { BOARD_FILE, BOARD_LOCK } from "./instance-board.mjs";
106
+ import { RELATED_WORK_FILE, SAME_WORK_FILE, relatedWorkBinding, writeRelatedWork } from "./instance-related-work.mjs";
107
+ import { HOST_STOP_REASON, lostReasonOf, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
108
+ import { PROVIDER_RESUME_NOTICE, RESUME_QUIET_WAIT_MS, countProviderResume, resumeCountLock, resumeQuietWait } from "./provider-resume.mjs";
109
+ import { withDirLock } from "./dir-lock.mjs";
110
+ import { waitingHold } from "./instance-events.mjs";
104
111
  import { thisBoot } from "./session-seen.mjs";
105
112
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
106
113
  import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
@@ -109,7 +116,8 @@ import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
109
116
  import { PKG_ROOT } from "./version.mjs";
110
117
  import { canonicalDeploymentPath } from "./deployment-path.mjs";
111
118
  import { INSTANCE_NAME_RE, RESERVED, capabilityAgentDirs, enclosingInstanceHome, findInstanceHomes, listAgents, logicalCwd, readSoul, soulOf, stripInternalAnnotations, withConfigFile, yamlKey } from "./soul-listing.mjs";
112
- import { RETIRE_BASELINE_VERSION, authorityMismatch, findRetirementBaseline, inspectInstanceSession, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, retirementBaselinePath, runtimeAuthorityOf, tmuxEndpointAgrees } from "./session-inspect.mjs";
119
+ import { endpointAgrees, providerHomeOf } from "./session-inspect.mjs";
120
+ import { RETIRE_BASELINE_VERSION, authorityMismatch, findRetirementBaseline, inspectInstanceSession, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, retirementBaselinePath, runtimeAuthorityOf } from "./session-inspect.mjs";
113
121
  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";
114
122
  import { LAYERS, PACKAGE_ID_RE } from "./package-catalog.mjs";
115
123
  import { RESERVED_LAUNCH_ENV } from "./reserved-launch-env.mjs";
@@ -122,6 +130,7 @@ export { RESERVED, assertSafeConfigKey, enclosingInstanceHome, findInstanceHomes
122
130
  export { canonicalAgentsRoot, ensureRoot, findRoot, workspaceOf } from "./agents-root.mjs";
123
131
  export { canonicalDeploymentPath } from "./deployment-path.mjs";
124
132
  export { OATS_VERSION, PKG_ROOT } from "./version.mjs";
133
+ export { instanceSoulDir, kernelBin, lifecycleHookEnv, stableSoulId, teamEnv } from "./hook-env.mjs";
125
134
  // Keep the existing public core surface; internal data helpers are not re-exported.
126
135
  export { oatsError } from "./errors.mjs";
127
136
  export { copyTreeSafe } from "./tree-copy.mjs";
@@ -1335,67 +1344,12 @@ function validateHookEnvironment(capabilityID, value, owners, declarations) {
1335
1344
  return accepted;
1336
1345
  }
1337
1346
 
1338
- /**
1339
- * A soul's STABLE identity for capability hooks (OATS_SOUL_ID): what a provider
1340
- * may key durable state on. Workspace soul: `<repo key>#<soul name>` — it does not
1341
- * change when the member commits (the per-commit soul directory does) or when the
1342
- * copy moves. Classic soul: the realpath of agents/<name>/soul, i.e. today's value,
1343
- * so 0.24 deployments are unchanged. Order: an explicit `soulId` (a prepared spawn),
1344
- * the home's recorded `instance.json.workspace.soul` (retire/launch of a workspace
1345
- * home), else the path.
1346
- */
1347
- export function stableSoulId({ soulId, home, soulDir, agentName } = {}) {
1348
- if (typeof soulId === "string" && soulId) return soulId;
1349
- if (home) {
1350
- try {
1351
- const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
1352
- const s = meta?.workspace?.soul;
1353
- if (typeof s?.id === "string" && s.id) return s.id;
1354
- if (typeof s?.repoKey === "string" && s.repoKey) return `${s.repoKey}#${meta.agent ?? agentName ?? ""}`;
1355
- } catch { /* not a workspace home */ }
1356
- }
1357
- if (soulDir) { try { return realpathSync(soulDir); } catch { return soulDir; } }
1358
- return "";
1359
- }
1360
1347
  export const workspaceSoulId = (repoKey, name) => `${repoKey}#${name}`;
1361
1348
  /** A triggered instance's event, inside its home's .oats/ (lib/triggers.mjs). */
1362
1349
  export const TRIGGER_EVENT_FILE = "trigger-event.json";
1363
1350
  /** A prepared soul entry's id: `<repoKey>#<name>` for a member or external soul, `package:<id>#<name>`
1364
1351
  * for a package soul (stable across the package's versions and independent of its repo). */
1365
1352
  export const preparedSoulIdOf = (entry) => workspaceSoulId(typeof entry.package === "string" ? `package:${entry.package}` : entry.repoKey, entry.name);
1366
- /** The soul directory an instance incarnates, as spawn recorded it (instance.json
1367
- * `soulDir`): a workspace soul's per-commit copy (agents/<soul>/souls/<commit12>) or
1368
- * the read-only soul inside a capability package. It is what every classic
1369
- * lifecycle hook and dispatched command sees as OATS_SOUL (captured hooks set
1370
- * none); instance homes carry no soul link. */
1371
- export function instanceSoulDir(home, meta = undefined) {
1372
- if (meta === undefined && home) { try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { meta = null; } }
1373
- return typeof meta?.soulDir === "string" && isAbsolute(meta.soulDir) ? meta.soulDir : undefined;
1374
- }
1375
-
1376
- /** The team and workspace facts a lifecycle hook, command or provider check receives (workspace
1377
- * model only, lead decision c3-7): OATS_TEAM_SCOPE is the deployment directory; OATS_WORKSPACE_NAME /
1378
- * _KEY the workspace's name and canonical key; OATS_TEAM_NAME (the 0.25 `team:` block's name) is always
1379
- * empty, so an ambient value never reaches a hook.
1380
- *
1381
- * Team model v2 (docs/desktop-cli-api.md, The provider environment): `resolved.teams` are the soul's
1382
- * TeamRows here and `resolved.defaultTeam` its DefaultTeam; teamsEnv sets OATS_DEFAULT_TEAM(_ID,_FROM),
1383
- * OATS_TEAMS (mapped rows only) and OATS_TEAMS_SOURCE (`live`: the workspace + oats-local.yaml read now,
1384
- * or a fresh resolution; `recorded`: the spawn-time record). A provider LEAVES a joined team only on a
1385
- * `live` list. Teams not known (`resolved.teams` not an array): every team name unset. */
1386
- export function teamEnv(resolved) {
1387
- const ws = resolved?.workspace && typeof resolved.workspace === "object" ? resolved.workspace : {};
1388
- const known = Array.isArray(resolved?.teams);
1389
- return {
1390
- OATS_TEAM_NAME: "", OATS_TEAM_SCOPE: typeof ws.deployment === "string" ? ws.deployment : "",
1391
- ...teamsEnv(known ? { teams: resolved.teams, defaultTeam: resolved.defaultTeam ?? null, source: resolved.teamsSource } : null),
1392
- OATS_WORKSPACE_NAME: typeof ws.name === "string" ? ws.name : "", OATS_WORKSPACE_KEY: typeof ws.key === "string" ? ws.key : "",
1393
- };
1394
- }
1395
- function withoutAmbientHookFacts(env) {
1396
- const { OATS_LAUNCH_PREVIEW: _ambient, OATS_HARNESS_EXECUTABLE: _inherited, OATS_SPAWNER_HOME: _spawner, ...rest } = env;
1397
- return rest;
1398
- }
1399
1353
  /** A hook's OATS_HARNESS_EXECUTABLE: what the kernel's pane-side selection found, as an absolute real
1400
1354
  * path, so a hook can ask the program its pane will run. `paneSide` says the path is such an answer:
1401
1355
  * a recorded recipe's, a declared one, or a lookup on the pane's PATH. A bare name this process's
@@ -1414,43 +1368,6 @@ function replacedExecutableWarning(handed, launched) {
1414
1368
  if (!handed || !now || handed === now) return null;
1415
1369
  return `the harness executable changed after the hooks ran: hooks were given ${handed}, this launch runs ${now}`;
1416
1370
  }
1417
- /** The environment one capability's lifecycle hook runs with: the invoker's own
1418
- * (inherited, as for every hook; the kernel adds no credentials), plus the
1419
- * standard OATS_* variables (docs/capabilities.md, Commands and hooks) and the
1420
- * caller's `extraEnv`. One builder for every event, so the `worktree` runner
1421
- * (lib/worktree-hooks.mjs) hands its hooks exactly what every other hook gets. */
1422
- export function lifecycleHookEnv(event, cap, { home, instance, agentName, soulDir, soulId, contextDir, workspaceDir, rootDir, resolved, priorMeta = {}, extraEnv = {} }) {
1423
- return {
1424
- // OATS_LAUNCH_PREVIEW is the kernel's to give (prepareLaunchHooks), never
1425
- // inherited: a real start's hook must not read an ambient one as a preview.
1426
- // Nor are OATS_HARNESS_EXECUTABLE and OATS_SPAWNER_HOME (spawn's
1427
- // callerSpawner): a hook started from inside an instance must not read its caller's.
1428
- ...withoutAmbientHookFacts(process.env),
1429
- // OATS_INSTANCE_HOME is the runtime-neutral contract name for the
1430
- // instance home (absolute). OATS_HOME predates it and stays as a
1431
- // compatibility alias: shipped capability hooks read it
1432
- // (the official oats.aweb and oats.okf packages) and are versioned
1433
- // independently of this kernel. Neither is OATS_HOME_DIR, which is
1434
- // the package STORE root — do not conflate them.
1435
- OATS_EVENT: event, OATS_INSTANCE: instance, OATS_INSTANCE_HOME: home, OATS_HOME: home, OATS_AGENT: agentName,
1436
- OATS_CAPABILITY: cap.id, OATS_LAYER: cap.layer || "", OATS_ROOT: rootDir || "",
1437
- OATS_SOUL: soulDir || "", OATS_SOUL_ID: stableSoulId({ soulId, home, soulDir, agentName }), OATS_CONTEXT: contextDir, OATS_WORKSPACE: workspaceDir || "", OATS_LEVEL: cap.level || "",
1438
- ...teamEnv(resolved),
1439
- ...extraEnv,
1440
- // Hooks also run through direct core callers (not only bin/oats).
1441
- // Author this from the running kernel, never PATH, ambient env or
1442
- // a caller's extraEnv: those may point at a different executable.
1443
- OATS_CLI_BIN: kernelBin(),
1444
- // The node a capability writes into anything that outlives its hook (lib/stable-node.mjs).
1445
- OATS_NODE_BIN: kernelNode().node,
1446
- OATS_SETTINGS: JSON.stringify(cap.settings || {}),
1447
- // Where each leaf of OATS_SETTINGS came from (JSON pointer → { kind, at }; kind is
1448
- // manifest-default | workspace | soul | host | spawn | anchor), so a provider can tell a
1449
- // soul-set value from a host-set one. {} when the home recorded none (spawned before 0.29).
1450
- OATS_SETTINGS_ORIGINS: JSON.stringify(cap.settingsOrigins || {}),
1451
- OATS_META: JSON.stringify(priorMeta[cap.id] || {}),
1452
- };
1453
- }
1454
1371
  /** What a spawn or launch hook may answer as `dialogClaims`: `reported`, this session's dialogs become
1455
1372
  * `permission` or `question` claims; `none`, this harness has no dialog an Enter can answer. */
1456
1373
  const DIALOG_CLAIMS = ["reported", "none"];
@@ -1866,7 +1783,7 @@ const INSTANCE_IDENTITY_ENV = ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME
1866
1783
  const KERNEL_ENV_NAMES = new Set([...RESERVED_LAUNCH_ENV, "COLORFGBG", "TMUX", "TMUX_PANE",
1867
1784
  "OATS_CAPABILITY", "OATS_LAYER", "OATS_LEVEL", "OATS_META", "OATS_DEPLOYMENT", "OATS_RESOLUTION", "OATS_OPERATION",
1868
1785
  "OATS_REPO", "OATS_BRANCH", "OATS_WORK", "OATS_KIND", "OATS_TASK", "OATS_HARNESS", "OATS_PREVIOUS_HARNESS", "OATS_RUNTIME", "OATS_PREVIOUS_RUNTIME",
1869
- "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1786
+ "OATS_BACKEND", "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1870
1787
  "OATS_TEAM_NAME", "OATS_TEAM_SCOPE", "OATS_TEAM_ID", "OATS_TEAM_LABEL", "OATS_TEAM_LABELS", "OATS_TEAMS", "OATS_TEAMS_SOURCE",
1871
1788
  "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_WORKSPACE_NAME", "OATS_WORKSPACE_KEY",
1872
1789
  // A worktree hook's tree (#796): never inherited by what such a hook starts.
@@ -2176,6 +2093,7 @@ const NO_PANE_READ = Object.freeze({ unestablished: ": this process could not re
2176
2093
  const NO_TMUX = Object.freeze({ unestablished: ": this process has no tmux on its PATH to read the OATS tmux server with" });
2177
2094
  const NO_LAUNCH = Object.freeze({ unestablished: ": this spawn launches nothing (--no-launch), and a start reads its own session's" });
2178
2095
  const SESSION_REFUSED = Object.freeze({ unestablished: ": the session this start would create was refused" });
2096
+ const NO_PANE = Object.freeze({ unestablished: ": a session provider runs this launch, which has no pane" });
2179
2097
  const HOME_SESSION_UNREAD = Object.freeze({ unestablished: ": this home's session record could not be read" });
2180
2098
  /** The environment a launch's pane is expected to have (paneEnvironment's shape), from a plan
2181
2099
  * (planOatsTmuxSession): the session's or the server's when a server runs, else the environment the
@@ -2280,7 +2198,12 @@ export function previewPaneEnvironment({ home = null, meta = null, deployment =
2280
2198
  let session = DEFAULT_TMUX_SESSION;
2281
2199
  if (home) {
2282
2200
  let target;
2283
- try { ({ target } = instanceSessionTarget(home)); } catch (e) { if (!isKernelCode(e?.code)) throw e; return HOME_SESSION_UNREAD; }
2201
+ try {
2202
+ const recorded = instanceSessionTarget(home);
2203
+ // A home on a session provider has no pane, now or at its next start.
2204
+ if (providerHomeOf(recorded)) return NO_PANE;
2205
+ target = recorded.target;
2206
+ } catch (e) { if (!isKernelCode(e?.code)) throw e; return HOME_SESSION_UNREAD; }
2284
2207
  if (target) {
2285
2208
  let state = null;
2286
2209
  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 */ }
@@ -2551,7 +2474,24 @@ export function requirementHarness(row) {
2551
2474
  if (!row || typeof row !== "object") return undefined;
2552
2475
  return Object.hasOwn(row, "harness") ? row.harness : row.runtime;
2553
2476
  }
2554
- function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {}) {
2477
+ /** Whether a `requires` row applies to a launch on `backend` (`tmux`, or a session provider's name).
2478
+ * A row may carry `backends`: `["tmux"]`, `["session-provider"]` (any session provider) or both;
2479
+ * without the key it applies to every backend. Never inside `when`, whose keys are the capability's
2480
+ * own settings. A `backends` that is not such a list applies (verifyHarnessPackages refuses it). */
2481
+ const REQUIREMENT_BACKENDS = ["tmux", SESSION_PROVIDER_ANY];
2482
+ 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));
2483
+ function requirementOnBackend(row, backend) {
2484
+ if (row.backends === undefined || !validRequirementBackends(row)) return true;
2485
+ return row.backends.includes(backend === "tmux" ? "tmux" : SESSION_PROVIDER_ANY);
2486
+ }
2487
+ /** Whether a `requires` row's `when` holds under the capability's effective settings: every named
2488
+ * setting has the given value. A row without `when` holds, and so does one whose `when` is no
2489
+ * object, as a malformed `backends` does: verifyHarnessPackages refuses it. */
2490
+ 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));
2491
+ /** Whether a `requires` row is a requirement of this launch: for its backend, AND its `when` holds.
2492
+ * The one predicate of the probe (verifyHarnessPackages) and of what it would probe (applicableRequirements). */
2493
+ const requirementApplies = (cap, row, backend) => requirementOnBackend(row, backend) && requirementWhenHolds(cap, row);
2494
+ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env, backend = "tmux" } = {}) {
2555
2495
  // The probe's environment is the launch's (launchEffectiveEnv: the pane's PATH, HOME and
2556
2496
  // selectors, never this process's in their place), given as it is or as a function called at the
2557
2497
  // first requirement that applies: a launch with none reads nothing of its pane, and one whose
@@ -2577,11 +2517,15 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
2577
2517
  if (!raw || typeof raw !== "object") continue;
2578
2518
  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; }
2579
2519
  if (requirementHarness(raw) !== harness) continue;
2520
+ // A requirement may name the backends it is for (`backends`): a row for another backend is
2521
+ // not a requirement of this launch at all.
2522
+ 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; }
2523
+ if (!requirementOnBackend(raw, backend)) continue;
2580
2524
  // A requirement may be conditional on the capability's effective
2581
2525
  // settings (`when: { delivery: "channel" }`): rows whose condition does
2582
2526
  // not hold are not requirements of this spawn at all.
2583
2527
  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; }
2584
- if (raw.when && !Object.entries(raw.when).every(([k, v]) => String(cap.settings?.[k] ?? "") === String(v))) continue;
2528
+ if (!requirementApplies(cap, raw, backend)) continue;
2585
2529
  const spec = raw.package;
2586
2530
  if (!safeHarnessPackageSpec(spec, harness)) { problems.push(`${cap.id}: ${harness} package spec is not a plain source token (${JSON.stringify(spec)})`); continue; }
2587
2531
  if (raw.marketplace !== undefined && !safeHarnessSourceRef(raw.marketplace)) { problems.push(`${cap.id}: marketplace is not a plain source reference (${JSON.stringify(raw.marketplace)})`); continue; }
@@ -2875,8 +2819,6 @@ export function launchEnvRefs(recipe, env = process.env) {
2875
2819
  return out;
2876
2820
  }
2877
2821
 
2878
- /** The canonical path of this kernel's CLI: what the home's shim points at, and OATS_CLI_BIN. */
2879
- export function kernelBin() { return realpathSync(join(PKG_ROOT, "bin", "oats.mjs")); }
2880
2822
  /** Where a home's `oats` lives: first on its harness's PATH, so plain `oats` inside an instance is
2881
2823
  * the kernel that launched it, whatever other `oats` the host's PATH finds first. */
2882
2824
  export const kernelShimDir = (home) => join(home, ".oats", "bin");
@@ -3108,13 +3050,14 @@ function agentScopeOn(command, { pane, removed = [], refs = [] }, io) {
3108
3050
 
3109
3051
  /** A recorded recipe this kernel understands, or a refusal before anything
3110
3052
  * is observed or stopped. */
3111
- export function assertLaunchRecipe(recipe, what) {
3053
+ export function assertLaunchRecipe(recipe, what, { sessionProvider = false } = {}) {
3112
3054
  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`); };
3113
3055
  if (!recipe || typeof recipe !== "object") bad("not an object");
3114
3056
  recipe = upgradeLaunchRecipe(recipe);
3115
3057
  if (recipe.version !== LAUNCH_RECIPE_VERSION) bad(`version ${JSON.stringify(recipe.version)}, expected ${LAUNCH_RECIPE_VERSION}`);
3116
3058
  if (!LAUNCH_HARNESSES.includes(recipe.harness)) bad(`harness ${JSON.stringify(recipe.harness)}`);
3117
- if (typeof recipe.executable !== "string" || !recipe.executable) bad("no executable");
3059
+ // A home on a session provider records no executable: the provider runs the harness itself.
3060
+ if (sessionProvider ? recipe.executable !== null : typeof recipe.executable !== "string" || !recipe.executable) bad(sessionProvider ? "an executable, on a session provider" : "no executable");
3118
3061
  if (!Array.isArray(recipe.args) || recipe.args.some((a) => typeof a !== "string")) bad("args are not a list of strings");
3119
3062
  if (!recipe.env || typeof recipe.env !== "object" || Array.isArray(recipe.env)) bad("env is not a map");
3120
3063
  for (const [n, v] of Object.entries(recipe.env)) {
@@ -3129,14 +3072,13 @@ export function assertLaunchRecipe(recipe, what) {
3129
3072
  /** The harness-package requirements that apply: declared for this harness
3130
3073
  * and, for a conditional row, holding under the provider's (captured)
3131
3074
  * settings. Nothing else is probed or restricted. */
3132
- export function applicableRequirements(harness, providers) {
3133
- 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)));
3075
+ export function applicableRequirements(harness, providers, backend = "tmux") {
3134
3076
  const out = [];
3135
- 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 });
3077
+ 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 });
3136
3078
  return out;
3137
3079
  }
3138
- function requirementsWithArgsMessage(harness, providers, config) {
3139
- const rows = applicableRequirements(harness, providers);
3080
+ function requirementsWithArgsMessage(harness, providers, config, backend = "tmux") {
3081
+ const rows = applicableRequirements(harness, providers, backend);
3140
3082
  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`;
3141
3083
  }
3142
3084
  /** ONE planner for what a start would run, used by preview and by starts of
@@ -3158,7 +3100,10 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3158
3100
  // A recorded recipe is validated before anything is observed. A home without
3159
3101
  // one predates recipes: there is nothing this kernel plans from.
3160
3102
  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`);
3161
- const frozen = meta ? assertLaunchRecipe(meta.launch, meta.instance || home) : null;
3103
+ // A home on a session provider (lib/session-providers.mjs): the provider runs the harness itself,
3104
+ // so nothing of a pane or an executable is planned or checked, and no command line is rendered.
3105
+ const sessionProvider = meta && homeBackendOf(meta) !== "tmux" ? { backend: meta.backend, capability: meta.session.provider } : null;
3106
+ const frozen = meta ? assertLaunchRecipe(meta.launch, meta.instance || home, { sessionProvider: !!sessionProvider }) : null;
3162
3107
  // The home's deployment declares the launch configurations (its oats-local.yaml,
3163
3108
  // found walking up from the home) — never the context directory, which may be a
3164
3109
  // member clone outside the deployment.
@@ -3182,7 +3127,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3182
3127
  // A frozen recipe keeps its recorded path. Otherwise a bare name is looked up where the pane will
3183
3128
  // look it up (launchLookup: the configuration's PATH, else the pane's, the start's expected
3184
3129
  // session or server PATH; a start looks again on the session it gets).
3185
- const executable = config?.frozen
3130
+ const executable = sessionProvider ? { path: null, declared: null, resolvedFrom: `session provider ${sessionProvider.backend}` } : config?.frozen
3186
3131
  ? { path: config.executablePath, declared: frozen.executableDeclared ?? null, resolvedFrom: frozen.executableResolvedFrom || "recorded", missing: existsSync(config.executablePath) ? undefined : `${config.executablePath} (recorded) does not exist` }
3187
3132
  : resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir, lookup: config?.executable?.includes("/") ? undefined : launchLookup(launchEnv) });
3188
3133
  // What the hooks are handed: the pane-side answer, not one this process's PATH gave.
@@ -3190,7 +3135,18 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3190
3135
  // A bare name looked up on this process's PATH because the pane's is not established: said.
3191
3136
  const lookupNote = !config?.frozen && !config?.executable?.includes("/") && !executable.lookup ? unestablishedNote(launchEnv, ["PATH"]) : null;
3192
3137
  const notOnPane = !executable.path && executable.lookup ? executableNotOnPanePath(executable, { harness, config, from: launchChoice?.from, at: launchChoice?.at }) : null;
3193
- if (notOnPane) {
3138
+ if (sessionProvider) {
3139
+ // The provider's own rules for this launch: the harness is one it runs, and no executable is named.
3140
+ // The home's modules as they are now, under the spawn's own selection: one name has one
3141
+ // meaning (E_BACKEND_AMBIGUOUS), and the harness is one the provider runs (E_BACKEND_HARNESS).
3142
+ const bound = homeSessionProvider(home, meta, sessionProvider.capability, sessionProvider.backend);
3143
+ let refusal = null;
3144
+ 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; } }
3145
+ 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`);
3146
+ else if (refusal) { if (!preview) throw refusal; problems.push({ check: "backend", ok: false, detail: refusal.message, code: refusal.code }); }
3147
+ 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`);
3148
+ 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` });
3149
+ } else if (notOnPane) {
3194
3150
  if (!preview) throw notOnPane;
3195
3151
  problems.push({ check: "executable", ok: false, detail: notOnPane.message, code: notOnPane.code });
3196
3152
  } else if (!executable.path && !config?.executable && launchChoice) {
@@ -3199,7 +3155,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3199
3155
  problems.push({ check: "executable", ok: false, detail: e.message, code: e.code });
3200
3156
  }
3201
3157
  const exeProblem = executable.path ? checkLaunchExecutable(executable.path) : notOnPane || (!config?.executable && launchChoice) ? null : executable.missing;
3202
- 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}` : ""}` });
3158
+ 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}` : ""}` });
3203
3159
  // Capability contributions: recorded at spawn with provenance; a harness
3204
3160
  // switch needs the new harness's launch args from the same capabilities.
3205
3161
  let hooks = { launch: {}, env: {}, contributions: [], pending: true };
@@ -3239,7 +3195,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3239
3195
  const missing = missingLaunchEnvRefs(configEnv, env);
3240
3196
  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)}`);
3241
3197
  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` });
3242
- const login = claudeLoginCredential({ harness, configEnv, hooksEnv: hooks.env, launch: launchEnvironment({ configEnv, capabilities: { env: hooks.env }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) });
3198
+ 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 }) });
3243
3199
  if (login?.code) fail("credentials", login.code, login.message);
3244
3200
  problems.push({ check: "model", ok: true, detail: model ? `${model} (${modelSource})` : `native default (${modelSource})` });
3245
3201
  // Harness package requirements: the captured providers' (bindings united
@@ -3251,16 +3207,20 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3251
3207
  // package probe (it must never start a conversation), which is stated. A pane
3252
3208
  // whose environment cannot be read is refused with its own code, and one that
3253
3209
  // is not established is probed with what the item names.
3254
- if (executable.path && !missing.length && !owned.length) {
3210
+ // A session provider's launch has no pane and no executable of its own: a requirement that
3211
+ // applies to it (a row without `backends`, or one that names `session-provider`) is probed on
3212
+ // this host with the harness found on this process's PATH, the conservative reading.
3213
+ const requirementsBackend = sessionProvider ? sessionProvider.backend : "tmux";
3214
+ if ((executable.path || sessionProvider) && !missing.length && !owned.length) {
3255
3215
  const providers = frozen
3256
3216
  ? 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)
3257
3217
  : (resolvedCfg?.capabilities || []);
3258
- const declared = applicableRequirements(harness, providers).length > 0;
3218
+ const declared = applicableRequirements(harness, providers, requirementsBackend).length > 0;
3259
3219
  if (declared && (config?.args || []).length) {
3260
3220
  // The controlled probe cannot carry configuration arguments, so with
3261
3221
  // an applicable requirement a launch under such arguments cannot be
3262
3222
  // reported verified: refused, truthfully, with the way out.
3263
- fail("harness-packages", "E_LAUNCH_PROBE_UNSUPPORTED", requirementsWithArgsMessage(harness, providers, config));
3223
+ fail("harness-packages", "E_LAUNCH_PROBE_UNSUPPORTED", requirementsWithArgsMessage(harness, providers, config, requirementsBackend));
3264
3224
  } else if (declared) {
3265
3225
  // The check fails with the code the gate refused with, never another name for it (#1047):
3266
3226
  // E_HARNESS_RESOURCE_MISSING, or E_RUNTIME_ENDPOINT_UNKNOWN for a pane whose environment it
@@ -3269,26 +3229,25 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3269
3229
  try {
3270
3230
  // The probe's answer also holds what the capabilities set, over the same read of the pane.
3271
3231
  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 });
3272
- 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) });
3232
+ 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) });
3273
3233
  const probeNote = unestablishedNote(probeLaunch, probeNames(harness));
3274
- 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}` : ""}` });
3234
+ 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}` : ""}` });
3275
3235
  } catch (e) { if (!["E_HARNESS_RESOURCE_MISSING", "E_RUNTIME_ENDPOINT_UNKNOWN"].includes(e?.code)) throw e; fail("harness-packages", e.code, e.message); }
3276
3236
  } else problems.push({ check: "harness-packages", ok: true, detail: "no harness package requirement declared for this harness; nothing probed" });
3277
3237
  }
3278
3238
  const recipe = {
3279
3239
  version: LAUNCH_RECIPE_VERSION, harness, launchConfig: config?.name || null, launchConfigSource: config?.source || null, ...(config?.harnessDefault ? { launchConfigDefault: true } : {}),
3280
- executable: executable.path || executable.declared || harness, executableDeclared: executable.declared ?? null, executableResolvedFrom: executable.resolvedFrom,
3240
+ executable: sessionProvider ? null : executable.path || executable.declared || harness, executableDeclared: executable.declared ?? null, executableResolvedFrom: executable.resolvedFrom,
3281
3241
  args: [...(config?.args || [])], env: { ...configEnv }, model: model || null, ...(yolo !== undefined ? { yolo } : {}),
3282
3242
  hooks: frozen ? { launch: hooks.launch, env: hooks.env, contributions: hooks.contributions } : hooks, prompt: LAUNCH_PROMPT, kernelBin: kernelBin(),
3283
3243
  ...(frozen?.legacy ? { legacy: { ...frozen.legacy, ...(hooks.refreshed?.length ? { replacedBy: hooks.refreshed } : {}) } } : {}),
3284
3244
  };
3285
- const inst = instance || meta?.instance || basename(home);
3286
3245
  const trustLaunch = removedEnv.length ? launchEnvironment({ configEnv: config?.env, configName: config?.name, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) : launchEnv;
3287
- const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3288
- const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3246
+ const { trustHome } = sessionProvider ? { trustHome: false } : launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3247
+ const command = sessionProvider ? undefined : renderLaunchRecipe(recipe, { home, instance: instance || meta?.instance || basename(home), trustHome });
3289
3248
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3290
3249
  // A preview states what the start will do; the start states it in its own output.
3291
- const previewNotices = preview ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3250
+ const previewNotices = preview && !sessionProvider ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3292
3251
  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 } : {}) };
3293
3252
  }
3294
3253
  /** The names a package probe of `harness` depends on: where its program is found and runs, the
@@ -3369,6 +3328,227 @@ export function describeLaunchCommand(command) {
3369
3328
  const argv = tokens.slice(binary + 1).map((t) => t.kind === "sep" ? "--" : t.kind === "prompt" ? t.text : t.value);
3370
3329
  return { executable: tokens[binary].value, argv, environment };
3371
3330
  }
3331
+ // ------------------------------------------------------------ session providers (lib/session-providers.mjs)
3332
+
3333
+ /** What a session provider's `launch` is handed (docs/capabilities.md "Session providers"): the
3334
+ * launch a tmux window would run, as data. `env`: every variable the launch sets, in the order a
3335
+ * window's command sets them, each with its `source`, so a provider can refuse one it cannot carry
3336
+ * safely: `kernel` (the instance's identity, a trigger's event file), `capability` (a hook's, with
3337
+ * the `capability` that owns it), `launch-config` (a configuration's literal) or
3338
+ * `launch-config-reference` (a configuration's fromEnv/fromFile: a secret source, `secret: true`,
3339
+ * its value read on this host as a window's would be). `unset`: the names the launch removes.
3340
+ * `pathPrepend`: the home's kernel shim directory, first on a window's PATH, so the agent's plain
3341
+ * `oats` is this kernel. `args`: the configuration's arguments, then the capabilities' launch
3342
+ * arguments for the harness; never the kernel's own flags, which are `model`, `yolo` and the
3343
+ * prompt (`promptFile`, the home's TASK.md). `previous`: the endpoint of the session this launch
3344
+ * replaces (a start, a restart), null for a home's first launch. */
3345
+ function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [], previous = null }) {
3346
+ const env = [{ name: "OATS_INSTANCE", value: instance, source: "kernel" }, { name: "OATS_INSTANCE_HOME", value: home, source: "kernel" }];
3347
+ const hookEnv = recipe.hooks?.env || {};
3348
+ const owner = (name) => (recipe.hooks?.contributions || []).find((c) => (c.env || []).includes(name))?.capability ?? null;
3349
+ for (const name of Object.keys(hookEnv).sort()) env.push({ name, value: hookEnv[name], source: "capability", capability: owner(name) });
3350
+ for (const name of Object.keys(recipe.env || {}).sort()) {
3351
+ const value = recipe.env[name];
3352
+ if (typeof value === "string") env.push({ name, value, source: name.startsWith("OATS_") ? "kernel" : "launch-config" });
3353
+ else {
3354
+ const resolved = referenceValue(value, hostEnv);
3355
+ if (resolved === undefined) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage([referenceSource(value)], recipe.harness));
3356
+ env.push({ name, value: resolved, source: "launch-config-reference", secret: true });
3357
+ }
3358
+ }
3359
+ // A capability's launch arguments are a string in the grammar a launch command is written in:
3360
+ // read as the words a window's shell would hand the harness (the stand-in binary is never sent).
3361
+ const hookArgs = recipe.hooks?.launch?.[recipe.harness] || "";
3362
+ let hookWords = [];
3363
+ if (hookArgs.trim()) {
3364
+ try { hookWords = parseLaunchCommand(`${shq("harness")} ${hookArgs}`).tokens.slice(1).map((t) => t.value ?? t.text); } catch (e) {
3365
+ const owners = (recipe.hooks?.contributions || []).filter((c) => c.launch?.[recipe.harness]).map((c) => c.capability);
3366
+ 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 } });
3367
+ }
3368
+ }
3369
+ return {
3370
+ home, instance, harness: recipe.harness, model: recipe.model ?? null, yolo: recipe.yolo ?? null,
3371
+ env, unset: [...removed], pathPrepend: [kernelShimDir(home)],
3372
+ args: [...(recipe.args || []), ...hookWords], promptFile: join(home, "TASK.md"), previous,
3373
+ };
3374
+ }
3375
+ /** A home's independent session receipt, read to be written again with another `runtime` → `{ path,
3376
+ * baseline }`. Refused as every writer of it refuses: E_RUNTIME_ENDPOINT_UNKNOWN for a receipt that
3377
+ * is missing, unreadable, of another home, or that authorises nothing. */
3378
+ function readSessionReceipt(home) {
3379
+ const path = findRetirementBaseline(home);
3380
+ let baseline;
3381
+ try { baseline = JSON.parse(readFileSync(path, "utf8")); } catch (e) {
3382
+ if (e.code === "ENOENT") throw missingSessionReceipt(home);
3383
+ throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or unreadable for ${home}: ${e.message}`);
3384
+ }
3385
+ 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}`);
3386
+ return { path, baseline };
3387
+ }
3388
+ /** Record a provider home's runtime in its independent receipt: `session` is `{ backend, provider,
3389
+ * endpoint, stoppedAt? }`. The one writer after the spawn's own baseline: a launch's
3390
+ * endpoint, a stop's `stoppedAt`, a start's clearing of it. Only `runtime` changes. */
3391
+ function writeProviderRuntime(home, session) {
3392
+ const { path, baseline } = readSessionReceipt(home);
3393
+ // A launch that was sent and has no recorded outcome stays marked through every write of the
3394
+ // runtime (a stop's `stoppedAt`, the launch's own endpoint): only clearLaunchSent and
3395
+ // recordLaunchSettled take the mark away, as the last write of what they end.
3396
+ baseline.runtime = providerRuntimeRecord({ ...session, launchSent: launchSentOf(baseline.runtime) ?? null });
3397
+ writeJsonAtomic(path, baseline, 0o600);
3398
+ }
3399
+ function setRecordLaunched(home, launched) {
3400
+ const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
3401
+ if (meta.launched !== launched) writeHomeRecord(home, { ...meta, launched });
3402
+ }
3403
+ /** Record, in the home's receipt, that a launch is being sent to its provider (launchSentOf), right
3404
+ * before the provider is called → the instant recorded. It is taken away once the launch is
3405
+ * known to have started nothing (clearLaunchSent), once what it started is known to be stopped
3406
+ * (recordLaunchSettled), or once its outcome is recorded (recordLaunchOutcome).
3407
+ *
3408
+ * A home that was never launched has no endpoint to keep. Meanwhile its runtime reads `{ launched:
3409
+ * true, backend, provider, launchSent }` and its record (instance.json) `launched: true`, with no
3410
+ * endpoint in either: to a kernel from before session providers that is a launch it cannot
3411
+ * address, which it refuses for every verb, a retire included, where "never launched" would read
3412
+ * as a home it may remove. Both go back to not launched when the launch is settled. The receipt
3413
+ * is written first and cleared last, and this kernel takes either value of the record's
3414
+ * `launched` beside it (lib/session-inspect.mjs launchStateAgrees). */
3415
+ function markLaunchSent(home) {
3416
+ const { path, baseline } = readSessionReceipt(home);
3417
+ const launchSent = new Date().toISOString();
3418
+ const launchedBefore = baseline.runtime.launched === true && baseline.runtime.endpoint !== undefined;
3419
+ baseline.runtime = launchedBefore ? { ...baseline.runtime, launchSent } : { launched: true, backend: baseline.runtime.backend, provider: baseline.runtime.provider, launchSent };
3420
+ writeJsonAtomic(path, baseline, 0o600);
3421
+ dieAt("mark:receipt-written");
3422
+ if (!launchedBefore) setRecordLaunched(home, true);
3423
+ return launchSent;
3424
+ }
3425
+ /** Whether the home's receipt (outside the home) names a session provider; false when it has none
3426
+ * or it cannot be read. */
3427
+ function receiptNamesProvider(home) {
3428
+ try { return typeof readSessionReceipt(home).baseline.runtime?.provider === "string"; } catch { return false; }
3429
+ }
3430
+ /** A launch's outcome, for a spawn's first launch and for a start alike, in three writes: the
3431
+ * receipt's endpoint with the launch still marked as sent, the record, then the mark removed.
3432
+ * Killed between any two, the home is unsettled, never one whose record contradicts its receipt.
3433
+ * A failure of the first write recorded nothing; one after it is in `outcomeRecordFailures` (the
3434
+ * receipt names the session by then, still marked as sent: the home is unsettled). */
3435
+ const outcomeRecordFailures = new WeakSet();
3436
+ function recordLaunchOutcome(home, runtime, record, { keepMark = false } = {}) {
3437
+ writeProviderRuntime(home, runtime);
3438
+ dieAt("outcome:receipt-written");
3439
+ try {
3440
+ writeHomeRecord(home, record);
3441
+ dieAt("outcome:record-written");
3442
+ // (`keepMark`: a spawn, which has writes of its own to make yet, and removes the mark after
3443
+ // the last: until then the home is unsettled, so no input is admitted to a home whose spawn
3444
+ // may still be undone.)
3445
+ if (!keepMark) clearLaunchSent(home);
3446
+ } catch (e) { if (e && typeof e === "object") outcomeRecordFailures.add(e); throw e; }
3447
+ }
3448
+ /** Unmark a launch that is known to have started nothing (the provider refused it): the home is
3449
+ * as it was before the mark. The record first, then the receipt. */
3450
+ function clearLaunchSent(home) {
3451
+ const { path, baseline } = readSessionReceipt(home);
3452
+ if (baseline.runtime?.launchSent === undefined) return;
3453
+ const { launchSent: _settled, ...runtime } = baseline.runtime;
3454
+ if (runtime.endpoint === undefined) setRecordLaunched(home, false);
3455
+ dieAt("unmark:record-written");
3456
+ baseline.runtime = runtime.endpoint === undefined ? { launched: false, backend: runtime.backend, provider: runtime.provider } : runtime;
3457
+ writeJsonAtomic(path, baseline, 0o600);
3458
+ }
3459
+ /** The records of a home whose spawn failed after its launch was sent, once the provider confirmed
3460
+ * that nothing runs for it, and which the spawn keeps for another debt: PLANNED, the record
3461
+ * first, then the receipt (where there is one). `planned`: `{ backend, provider }`. */
3462
+ function recordProviderPlanned(home, planned) {
3463
+ const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
3464
+ writeHomeRecord(home, { ...meta, launched: false, backend: planned.backend, session: { ...(isPlainObject(meta.session) ? meta.session : {}), provider: planned.provider, endpoint: null } });
3465
+ // (Killed here, the receipt still says the launch was sent: unsettled, and the record is not
3466
+ // compared; the next verb settles the home.)
3467
+ dieAt("rollback:record-written");
3468
+ if (!existsSync(retirementBaselinePath(home))) return;
3469
+ const { path, baseline } = readSessionReceipt(home);
3470
+ baseline.runtime = { launched: false, backend: planned.backend, provider: planned.provider };
3471
+ writeJsonAtomic(path, baseline, 0o600);
3472
+ }
3473
+ /** The records of a home whose sent launch the provider has confirmed stopped: no session of that
3474
+ * launch runs, and the one before it was stopped before the launch was marked, so nothing does.
3475
+ * A home with no endpoint is PLANNED again; one with an endpoint is STOPPED (`stoppedAt` set
3476
+ * when it was not; the stop is an operator's, unless the home's stop receipt already says the
3477
+ * host's). The record is rewritten to agree first (it was not compared while the launch was
3478
+ * unsettled), then the receipt, which is what ends the unsettled state. */
3479
+ function recordLaunchSettled(home) {
3480
+ const { path, baseline } = readSessionReceipt(home);
3481
+ const { launchSent, ...runtime } = baseline.runtime;
3482
+ if (launchSent === undefined) return;
3483
+ const meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
3484
+ const session = { ...(isPlainObject(meta.session) ? meta.session : {}), provider: runtime.provider };
3485
+ if (runtime.endpoint === undefined) {
3486
+ writeHomeRecord(home, { ...meta, launched: false, backend: runtime.backend, session: { ...session, endpoint: null } });
3487
+ baseline.runtime = { launched: false, backend: runtime.backend, provider: runtime.provider };
3488
+ } else {
3489
+ const agreed = { ...meta, launched: true, backend: runtime.backend, session: { ...session, endpoint: runtime.endpoint } };
3490
+ writeHomeRecord(home, agreed);
3491
+ // The host's stop only when the home was stopped before this launch: a stop receipt beside a
3492
+ // home that was running is an earlier stop's, left by a resume that died.
3493
+ if (runtime.stoppedAt == null || lostReasonOf(home, agreed) !== HOST_STOP_REASON) { try { recordStop(home, null); } catch { /* the receipt below is the authority */ } }
3494
+ baseline.runtime = { ...runtime, stoppedAt: runtime.stoppedAt ?? new Date().toISOString() };
3495
+ }
3496
+ dieAt("settle:record-written");
3497
+ writeJsonAtomic(path, baseline, 0o600);
3498
+ }
3499
+ /** Ask a provider home's backend to stop a session, giving it `graceMs`, never escalated → null
3500
+ * when it confirmed, else why not, in one sentence: the provider failed or refused, or its
3501
+ * capability is no longer among the home's modules. `recorded`: the receipt's `{ backend,
3502
+ * provider }`. `endpoint`: the recorded one, or null for whatever session is rooted at the home
3503
+ * (with `launchSent`, the instant of the launch that may have started it). Its stop is
3504
+ * idempotent, so every OATS act that needs the session gone asks: a stop, a restart, a start
3505
+ * after a stop, a retire, a settle. */
3506
+ function providerStopUnconfirmed(home, meta, recorded, endpoint, graceMs = 20000, io, launchSent = null, { outlasted } = {}) {
3507
+ // First, the provider calls recorded for this home (drainProviderCalls): a command of the
3508
+ // provider that still runs, or runs later, could start a session after the stop asked for here.
3509
+ // Every caller has written its fence by now (`stoppedAt`, or a launch's mark), so no new input
3510
+ // is admitted meanwhile.
3511
+ const left = drainProviderCalls(home, { outlasted });
3512
+ if (left) return left;
3513
+ const found = homeSessionProvider(home, meta, recorded.provider, recorded.backend);
3514
+ if (found.problem) return found.problem;
3515
+ return trackedProviderStop(home, found.binding, endpoint, Math.max(1, Math.ceil(graceMs / 1000)), { io, launchSent }).failed ?? null;
3516
+ }
3517
+ /** The provider's stop, as EVERY stop the kernel sends is sent: recorded as a call while it runs
3518
+ * (markProviderCall). A stop is a call like another: one whose kernel ends during it would run
3519
+ * late, and stop a session launched or resumed since (a stop of what is rooted at the home stops
3520
+ * whatever was created after its `launchSent`). Recorded, it is ended before a launch, an input
3521
+ * or a resume is sent to the home, and by the drain of the next stop (endProviderCalls,
3522
+ * drainProviderCalls). The policy (fence, drain) is the caller's. → stopProviderSession's answer. */
3523
+ function trackedProviderStop(home, binding, endpoint, graceSeconds, { io, launchSent = null } = {}) {
3524
+ let call;
3525
+ try { call = markProviderCall(home, "stop"); }
3526
+ catch (e) { return { failed: `the stop could not be recorded as a call (${e?.code ?? e?.message ?? e}); the session backend was not asked` }; }
3527
+ try { return stopProviderSession(binding, endpoint, graceSeconds, { io, launchSent, groupFile: call.groupFile }); }
3528
+ finally { call.done(); }
3529
+ }
3530
+ /** Settle a launch that was sent to a home's provider and never recorded (`unsettled`:
3531
+ * instanceSessionTarget's, `{ backend, provider, launchSent }`, or null): the provider is asked to
3532
+ * stop whatever session is rooted at the home (`stop` with `endpoint: null` and that instant)
3533
+ * → null when there was none to settle or the provider confirmed (the record is then taken
3534
+ * away), else why not, in one sentence; the record then stays, and the next verb asks again.
3535
+ * The one place a home is settled: a stop's, a start's, a retire's. */
3536
+ function settleSentLaunch(home, meta, unsettled, graceMs = 20000, io, { recordedStopped = false } = {}) {
3537
+ if (!unsettled?.launchSent) return null;
3538
+ // A home launched before: its recorded session first. The stop of what the sent launch started
3539
+ // does not reach a session older than that launch, and a settle records the home stopped: it
3540
+ // is never done over a session at the recorded endpoint that was not confirmed stopped.
3541
+ // (`recordedStopped`: the caller has just had that confirmed, under this same claim.)
3542
+ if (!recordedStopped) {
3543
+ const endpoint = readSessionReceipt(home).baseline.runtime.endpoint;
3544
+ const old = endpoint === undefined ? null : providerStopUnconfirmed(home, meta, unsettled, endpoint, graceMs, io);
3545
+ if (old) return old;
3546
+ }
3547
+ const why = providerStopUnconfirmed(home, meta, unsettled, null, graceMs, io, unsettled.launchSent);
3548
+ if (why === null) recordLaunchSettled(home);
3549
+ return why;
3550
+ }
3551
+
3372
3552
  /** Spawn. With `o.prepared` (workspace model: a resolution prepared by
3373
3553
  * instance-resolution.mjs) this is ASYNC — capabilities are fetched and copied
3374
3554
  * into the home. Without it (classic soul-directory spawn: schedules, tests,
@@ -3512,6 +3692,8 @@ export async function spawnInstanceAsync(root, agent, o = {}) {
3512
3692
  /** The command a spawn's answer gives to attach to its instance: the tmux session of its window when
3513
3693
  * it was launched (`meta.tmux` then names the socket), else the session surface by home. */
3514
3694
  function spawnAttach(meta, launched) {
3695
+ // A session provider's session has no terminal to attach to: inspect's `open` is what a client shows.
3696
+ if (meta.session) return null;
3515
3697
  return launched ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(meta.tmux.session)}` : `oats session attach --home ${shellWord(meta.home)}`;
3516
3698
  }
3517
3699
  /** The producer sets this only when dispatched effects or their compensation
@@ -3537,7 +3719,7 @@ function* spawnBody(root, agent, o = {}) {
3537
3719
  const backend = o.backend || "tmux";
3538
3720
  if (backend === "herdr") throw herdrSettingRemoved("backend herdr was given");
3539
3721
  if (o.herdrSocket !== undefined) throw herdrSettingRemoved("herdrSocket was given");
3540
- if (backend !== "tmux") throw new Error(`unknown session backend "${backend}" (tmux)`);
3722
+ if (typeof backend !== "string") throw oatsError("E_BAD_ARGS", "backend must be a session backend's name");
3541
3723
  const launch = o.launch !== false;
3542
3724
  // Workspace model (`o.prepared`) + work: workspace: ./work is the deployment
3543
3725
  // boundary — the directory holding oats-local.yaml (`prepared.deployment`), which
@@ -3575,6 +3757,18 @@ function* spawnBody(root, agent, o = {}) {
3575
3757
  const launchConfig = launchSelection.config;
3576
3758
  const harness = launchSelection.harness;
3577
3759
  const model = launchSelection.model;
3760
+ // The session backend: tmux, the kernel's own, or a session provider one of this instance's
3761
+ // capabilities declares (lib/session-providers.mjs), decided for the harness this launch selected
3762
+ // and refused before anything is created: E_BACKEND_UNKNOWN, E_BACKEND_AMBIGUOUS, E_BACKEND_HARNESS.
3763
+ // `provider` is null for tmux, else `{ backend, capability, provider }`. A provider runs the
3764
+ // harness itself, so nothing of a pane is planned or checked for it, and no verb carries a
3765
+ // configuration's own executable.
3766
+ let provider;
3767
+ try {
3768
+ const selected = selectSessionBackend(backend, (o.prepared.resolution?.modules || []).map((m) => ({ id: m.name, manifest: m.manifest })), harness);
3769
+ provider = selected.backend === "tmux" ? null : selected;
3770
+ 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" } });
3771
+ } catch (e) { previewPreflightBudget = null; throw e; }
3578
3772
  // Instance homes belong in the soul-owning repo's PRIMARY checkout, never in a
3579
3773
  // linked worktree (see canonicalDeploymentPath). The CLI resolves this through
3580
3774
  // ensureRoot, but the kernel is its own validation boundary — the desktop
@@ -3659,7 +3853,7 @@ function* spawnBody(root, agent, o = {}) {
3659
3853
  // any scaffold, work tree, identity or hook, so that an instance that cannot is refused with
3660
3854
  // nothing left behind; the harness is first looked up on the PATH this plan expects (below). A
3661
3855
  // preview reads only what exists.
3662
- const tmuxSessionPlan = launch ? planOatsTmuxSession(session, undefined, { preview: o.preview === true }) : undefined;
3856
+ const tmuxSessionPlan = launch && !provider ? planOatsTmuxSession(session, undefined, { preview: o.preview === true }) : undefined;
3663
3857
 
3664
3858
  // Forward-only lineage: EXPLICIT only. Relations (child|sibling|parent|unrelated)
3665
3859
  // anchor the new instance to an EXISTING instance (o.relativeTo). o.parent
@@ -3683,7 +3877,13 @@ function* spawnBody(root, agent, o = {}) {
3683
3877
  if (relation === "unrelated" && relativeTo) throw new Error(`relation "unrelated" takes no relativeTo`);
3684
3878
  if (relation && relation !== "unrelated" && !relativeTo) throw new Error(`relation "${relation}" needs a relative-to instance`);
3685
3879
  if (typeof o.relativeRoot === "string" && o.relativeRoot.trim() && !relativeTo && !legacyParent) throw new Error(`relativeRoot only qualifies relativeTo/parent`);
3880
+ if (o.relatedWork !== undefined && typeof o.relatedWork !== "boolean") throw oatsError("E_BAD_ARGS", "relatedWork must be true or false");
3881
+ // `sameWork`, the option's old name, is an alias (the related-work compatibility layer): either sets the flag.
3882
+ // Its use is said once per call as Node's DeprecationWarning (stderr, never an answer); the CLI passes
3883
+ // `relatedWork`, its own alias having said so already (lib/command-flags.mjs SAME_WORK_ALIASES).
3686
3884
  if (o.sameWork !== undefined && typeof o.sameWork !== "boolean") throw oatsError("E_BAD_ARGS", "sameWork must be true or false");
3885
+ if (o.sameWork !== undefined) process.emitWarning(SAME_WORK_OPTION_RENAMED, { type: "DeprecationWarning", code: "OATS_SAME_WORK" });
3886
+ const relatedWorkAsked = o.relatedWork === true || o.sameWork === true;
3687
3887
  if (!relation && legacyParent) { relation = "child"; relativeTo = legacyParent; }
3688
3888
  if (relation === "unrelated") { relation = undefined; relativeTo = undefined; }
3689
3889
 
@@ -3814,11 +4014,12 @@ function* spawnBody(root, agent, o = {}) {
3814
4014
  if (anchorMeta?.siblingInstance) siblingInstance = anchorMeta.siblingInstance;
3815
4015
  }
3816
4016
  if (!relation && attachedOwner && attachedOwner !== instance) parentInstance = attachedOwner;
3817
- // Feature instance-same-work: the flag binds the parent the new home records, whichever relation gave
3818
- // it (child, a sibling of a non-root, --relation parent under a parented anchor, attached). None: refused
3819
- // here, before any home, worktree or hook, a preview's included.
3820
- if (o.sameWork === true && !(parentInstance && parentInstance !== instance)) {
3821
- throw oatsError("E_BAD_ARGS", `--same-work needs a parent: ${instance} would record no parent instance${relation ? ` (relation ${relation}${relativeTo ? ` to ${relativeTo}` : ""})` : ""}; spawn it with --parent <instance>, or without --same-work; nothing was spawned`);
4017
+ // Feature instance-related-work: the flag binds the parent the new home records, whichever relation gave
4018
+ // it (child, a sibling of a non-root, --relation parent under a parented anchor, attached), else the
4019
+ // sibling it records (a sibling of a root or of a root's sibling, --relation parent over an anchor with a
4020
+ // sibling link). Neither: refused here, before any home, worktree or hook, a preview's included.
4021
+ if (relatedWorkAsked && !relatedWorkBinding({ parentInstance: parentInstance !== instance ? parentInstance : undefined, siblingInstance: siblingInstance !== instance ? siblingInstance : undefined })) {
4022
+ throw oatsError("E_BAD_ARGS", `--related-work needs a parent or a sibling: ${instance} would record no parent or sibling instance${relation ? ` (relation ${relation}${relativeTo ? ` to ${relativeTo}` : ""})` : ""}; spawn it with --parent <instance> or --relation sibling --relative-to <instance>, or without --related-work; nothing was spawned`);
3822
4023
  }
3823
4024
  // K5 §4 — child-spawn permission is ENFORCED here, by the spawn route. The
3824
4025
  // parent's recorded policy (instance.json policy.childSpawns) says whether
@@ -3952,25 +4153,29 @@ function* spawnBody(root, agent, o = {}) {
3952
4153
  // and the naming call runs that same executable.
3953
4154
  let paneCwd = suggesting ? join(agent._dir, "instances", ".oats-suggest-name") : home;
3954
4155
  const launchEnvOn = (pane, removed = []) => launchEnvironment({ configEnv: launchConfig?.env, configName: launchConfig?.name, removed, env: process.env, pane, cwd: paneCwd });
3955
- const expectedEnv = launchEnvOn(launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, paneCwd) : NO_LAUNCH);
4156
+ const expectedEnv = launchEnvOn(provider ? NO_PANE : launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, paneCwd) : NO_LAUNCH);
3956
4157
  // A launched harness is looked up where its pane will look it up (launchLookup): this is the
3957
4158
  // preflight against the expected PATH; the launch looks again on the session it gets. Without a
3958
4159
  // launch (or a known destination) the lookup is this process's PATH, as before.
3959
4160
  const lookupFor = (launchEnv) => launch && !launchConfig?.executable?.includes("/") ? launchLookup(launchEnv) : undefined;
3960
- const executable = resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(expectedEnv) });
3961
- if (!executable.path && executable.lookup) { previewPreflightBudget = null; throw executableNotOnPanePath(executable, { harness, config: launchConfig, from: launchChoice.from, at: launchChoice.at }); }
4161
+ // A session provider runs the harness itself: no executable is looked up, checked or recorded, and
4162
+ // the checks that run or read one (the login credential, the harness package probe, folder trust)
4163
+ // have nothing to judge.
4164
+ const executable = provider ? { path: null, declared: null, resolvedFrom: `session provider ${backend}` }
4165
+ : resolveLaunchExecutable({ harness, declared: launchConfig?.executable, declaringDir: launchConfig?.source, contextDir: repoAbs, lookup: lookupFor(expectedEnv) });
4166
+ 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 }); }
3962
4167
  // No executable for the chosen harness (none declared by a configuration): E_HARNESS_UNAVAILABLE names the
3963
4168
  // layer that chose it and the fix. Never a fallback to another harness.
3964
- if (!executable.path && !launchConfig?.executable) { previewPreflightBudget = null; throw harnessUnavailable({ harness, from: launchChoice.from, at: launchChoice.at, why: executable.missing }); }
3965
- if (!executable.path) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig.name}: ${executable.missing}`);
3966
- { const bad = checkLaunchExecutable(executable.path); if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`); }
4169
+ else if (!executable.path && !launchConfig?.executable) { previewPreflightBudget = null; throw harnessUnavailable({ harness, from: launchChoice.from, at: launchChoice.at, why: executable.missing }); }
4170
+ else if (!executable.path) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig.name}: ${executable.missing}`);
4171
+ else { const bad = checkLaunchExecutable(executable.path); if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`); }
3967
4172
  const bin = executable.path;
3968
4173
  const missingRefs = missingLaunchEnvRefs(launchConfig?.env || {}, process.env);
3969
4174
  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)}`);
3970
4175
  const preflightRemoved = removedLaunchEnv({ declared: declaredLaunchEnv(resolvedCfg.capabilities), configEnv: launchConfig?.env });
3971
4176
  // A hook-owned selector has no value until hooks run; its final check remains below.
3972
4177
  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));
3973
- const loginPreflight = selectorPending ? null : claudeLoginCredential({ harness, configEnv: launchConfig?.env, launch: launchEnvOn(expectedEnv.pane, preflightRemoved) });
4178
+ const loginPreflight = selectorPending || provider ? null : claudeLoginCredential({ harness, configEnv: launchConfig?.env, launch: launchEnvOn(expectedEnv.pane, preflightRemoved) });
3974
4179
  if (loginPreflight?.code) throw oatsError(loginPreflight.code, loginPreflight.message);
3975
4180
  // A configuration's executable answers the package probe (without one the
3976
4181
  // context-selected name does, as before: its remedies name that command),
@@ -3981,11 +4186,14 @@ function* spawnBody(root, agent, o = {}) {
3981
4186
  // (awebai/oats#1041). `probed` keeps what the gate judged (null: no
3982
4187
  // requirement applied, so nothing was probed and nothing of the pane was
3983
4188
  // read), to compare with the pane the spawn actually gets.
3984
- if ((launchConfig?.args || []).length && applicableRequirements(harness, resolvedCfg.capabilities).length) throw oatsError("E_LAUNCH_PROBE_UNSUPPORTED", `${requirementsWithArgsMessage(harness, resolvedCfg.capabilities, launchConfig)}; nothing was created`);
4189
+ 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`);
3985
4190
  let probed = null;
3986
4191
  const recordedHarnessPackages = (found) => found.map((x) => ({ capability: x.capability, harness: x.harness, package: x.package, dir: x.dir, filtered: x.filtered, loadedBy: "harness-discovery" }));
3987
4192
  const probeEnvOn = (launchEnv, selected = bin) => probeEnvironment(() => (probed = launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: launchEnv, harness })), launchEnv, harness, selected);
3988
- const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { ...(launchConfig?.executable ? { bin } : {}), env: probeEnvOn(expectedEnv) });
4193
+ // A requirement applies to the launch's backend (requirementOnBackend). On a session provider,
4194
+ // which has no pane and no executable of its own, a row that applies is probed on this host,
4195
+ // with the harness found on this process's PATH.
4196
+ const harnessPackages = verifyHarnessPackages(harness, resolvedCfg, repoAbs, { backend, ...(launchConfig?.executable ? { bin } : {}), env: probeEnvOn(expectedEnv) });
3989
4197
  // What a preview of a launch says when no pane's environment is established (no server runs, or
3990
4198
  // it could not be read): the checks that read this process's values in its place, in one line
3991
4199
  // that names every name read that way, PATH among them: the lookup of a bare name and the package
@@ -3993,7 +4201,7 @@ function* spawnBody(root, agent, o = {}) {
3993
4201
  // a start checks again on its own session, and it says whose values it read only where it already
3994
4202
  // says something (the folder-trust warning, a refusal of the package gate).
3995
4203
  const previewReadWarning = () => {
3996
- if (!launch) return null;
4204
+ if (!launch || provider) return null;
3997
4205
  const checks = [...(!launchConfig?.executable?.includes("/") && !executable.lookup ? [["the harness lookup", ["PATH"]]] : []), ...(probed ? [["the harness package check", probeNames(harness)]] : [])];
3998
4206
  const note = unestablishedNote(expectedEnv, [...new Set(checks.flatMap(([, names]) => names))]);
3999
4207
  return note ? `${checks.map(([what]) => what).join(", ")}: ${note}` : null;
@@ -4010,7 +4218,9 @@ function* spawnBody(root, agent, o = {}) {
4010
4218
  const left = o.preview === true ? preflightStarted + preflightBudgetMs - Date.now() : own, souls = deploymentSoulNames(root, o.prepared), homes = deploymentInstanceHomes(root);
4011
4219
  let windows;
4012
4220
  const suggestion = yield () => suggestInstanceName({
4013
- harness, bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4221
+ // A session provider's launch has no executable of its own: the naming call runs the
4222
+ // harness found on this host's PATH, as the `requires` probe of such a launch does.
4223
+ harness, bin: provider ? harness : bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4014
4224
  env: () => launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: expectedEnv, harness }),
4015
4225
  taken: (n) => homes.has(n) || souls.has(n) || (windows ??= oatsTmuxWindows(session)).includes(n),
4016
4226
  });
@@ -4109,7 +4319,9 @@ function* spawnBody(root, agent, o = {}) {
4109
4319
  spawnPreviewApi: 2, preview: true, ...(previewWarnings.length ? { warnings: previewWarnings } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
4110
4320
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
4111
4321
  decision, preflight,
4112
- backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
4322
+ // A session provider is one of the instance's own modules: there to launch. Whether its
4323
+ // service is ready is its readiness check's answer (`oats readiness`), not this field's.
4324
+ backendStatus: launch ? { name: backend, installed: provider ? true : !!which(backend), started: false } : null,
4113
4325
  harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4114
4326
  background, ...(backgroundFrom ? { backgroundFrom } : {}),
4115
4327
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
@@ -4136,7 +4348,7 @@ function* spawnBody(root, agent, o = {}) {
4136
4348
  // Backend PRESENCE is a prerequisite, checked before anything is placed (M1):
4137
4349
  // an absent tmux binary must fail with nothing created, never after a
4138
4350
  // populated home exists.
4139
- if (launch && !which(backend)) throw new Error(`${backend} not installed (brew install tmux); nothing was created`);
4351
+ if (launch && !provider && !which(backend)) throw new Error(`${backend} not installed (brew install tmux); nothing was created`);
4140
4352
  // Exclusive placement reservation: the parent may be created, the home
4141
4353
  // itself never with `recursive` — EEXIST means another spawn (a concurrent
4142
4354
  // apply of the same decision, or anything else) got here first, and this one
@@ -4469,7 +4681,9 @@ function* spawnBody(root, agent, o = {}) {
4469
4681
  // A hook may replace either path; it must never mint authority for that target.
4470
4682
  if (work === "directory") {
4471
4683
  assertDirectoryRoots(home, homeReal);
4472
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false });
4684
+ // (A provider home's names its provider from the first: a spawn killed after its planned record
4685
+ // then leaves a receipt that agrees with it.)
4686
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: { backend, provider: provider.capability } } : { launched: false });
4473
4687
  }
4474
4688
 
4475
4689
  // Capability lifecycle hooks (spawn) — the knowledge integration scaffolds instance
@@ -4506,6 +4720,8 @@ function* spawnBody(root, agent, o = {}) {
4506
4720
  const treeHooks = work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities) : [];
4507
4721
  let worktreeRun = null, treeGuard = null, inProgressMarker = false;
4508
4722
  let hookRes = null;
4723
+ // A home on a session provider: what its receipt records before the first launch gives an endpoint.
4724
+ const plannedSession = provider ? { backend, provider: provider.capability } : null;
4509
4725
  const inProgressStartedAt = new Date().toISOString();
4510
4726
  /** `event`: the hooks the spawn is about to run, or runs, when it writes the marker ("spawn",
4511
4727
  * "worktree"). Until the spawn hooks have answered, each capability with a spawn hook may have
@@ -4544,7 +4760,9 @@ function* spawnBody(root, agent, o = {}) {
4544
4760
  hookRes = runLifecycleHooks("spawn", {
4545
4761
  home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs,
4546
4762
  workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg,
4547
- 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 } : {}) },
4763
+ // OATS_BACKEND: the session backend this instance launches on (`tmux`, or a session provider's
4764
+ // name), also for a spawn that launches nothing: it is what a later start launches on.
4765
+ 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 } : {}) },
4548
4766
  });
4549
4767
  // The spawn hooks' receipt (their `meta`), on disk as soon as there is one: a retire after a kill
4550
4768
  // from here on hands it to the retire hooks.
@@ -4583,6 +4801,21 @@ function* spawnBody(root, agent, o = {}) {
4583
4801
  let promptDispatched = false, promptTarget, promptResult, promptStartId;
4584
4802
  let windowMayExist = false;
4585
4803
  let spawnTmux;
4804
+ // A session provider's launch was sent: `{ binding, endpoint }`, the endpoint null until it answered.
4805
+ let providerSession = null;
4806
+ // The lifecycle claim a provider spawn holds over its home from before the home reads as an
4807
+ // ordinary never-launched one until its launch has been recorded or undone: a stop, a start or
4808
+ // a retire that arrives while the provider launches is busy, as beside any other lifecycle verb,
4809
+ // and never answers that there is nothing to stop while a session is being started.
4810
+ let providerLaunchClaim = null;
4811
+ // A provider home has its receipt BEFORE its record is published, as planned and not launched
4812
+ // (a directory home's and a worktree hook run's are written earlier still), and again after it,
4813
+ // for the digest of the home as the record leaves it. So a spawn that ends between the record
4814
+ // and that last receipt leaves a planned home, record and receipt agreed, never a record
4815
+ // without a receipt; and a spawn that reuses the name of a retired home, whose receipt a retire
4816
+ // keeps by its path, is never paired with that one.
4817
+ const writeEarlyProviderReceipt = () => { if (work !== "directory" && !treeHooks.length) writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: plannedSession }); };
4818
+ const releaseProviderLaunchClaim = () => { if (providerLaunchClaim) { const held = providerLaunchClaim; providerLaunchClaim = null; releaseHomeClaim(held); } };
4586
4819
  const ancillaryCleanup = [];
4587
4820
  // One compensation owner, from the first hook result through launch and
4588
4821
  // the final lineage write. Preserve the original failure and retain any
@@ -4600,6 +4833,38 @@ function* spawnBody(root, agent, o = {}) {
4600
4833
  // Retain cleanup owners so a retry must actually discharge their debt.
4601
4834
  const outstandingHooks = new Set();
4602
4835
  const outstandingGit = new Set();
4836
+ // A session provider's launch that was sent may have started a session, also when its answer
4837
+ // was lost: the provider stops it (by its endpoint, or, without one, whatever live session is
4838
+ // rooted at this home) before credentials or work its harness may be using are removed. A stop
4839
+ // that cannot be confirmed retains the home, as a window that cannot be seen gone does.
4840
+ if (providerSession) {
4841
+ // The fence: the launch is still marked as sent (a spawn keeps the mark until its last
4842
+ // write but one), or is marked again here, so no new input is admitted; one already in
4843
+ // flight is waited for or ended first (drainProviderCalls).
4844
+ let left = null;
4845
+ try { if (readSessionReceipt(home).baseline.runtime?.launchSent === undefined) markLaunchSent(home); }
4846
+ catch (e) { left = `that the session of ${instance} is being stopped could not be recorded (${e?.code ?? e?.message ?? e})`; }
4847
+ left ??= drainProviderCalls(home);
4848
+ const stopped = left ? { failed: left } : trackedProviderStop(home, providerSession.binding, providerSession.endpoint, 20, { launchSent: providerSession.launchSent });
4849
+ if (stopped.failed) {
4850
+ 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`);
4851
+ for (const cap of resolvedCfg.capabilities) if (cap.hooks?.retire) outstandingHooks.add(cap.id);
4852
+ if (work === "worktree") {
4853
+ outstandingGit.add("worktree");
4854
+ if (branch) outstandingGit.add("branch");
4855
+ }
4856
+ return { unconfirmed: true, note: quarantineInstanceHome({
4857
+ home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete, failed, outstandingHooks, outstandingGit,
4858
+ repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {},
4859
+ launched: false, directoryHome: homeReal,
4860
+ }) };
4861
+ }
4862
+ // Stopped: nothing runs for this home. One that is kept all the same (a hook's cleanup is
4863
+ // owed) is left PLANNED, in its record and its receipt alike, so its retire finds them agreed.
4864
+ try { recordProviderPlanned(home, plannedSession); }
4865
+ catch (e) { incomplete.push(`session records of ${instance}: ${e?.message ?? e}`); }
4866
+ providerSession = null;
4867
+ }
4603
4868
  // A failed new-window command may still have created its window. Verify
4604
4869
  // quiescence before removing credentials or work that harness may be using.
4605
4870
  // On the socket recorded for this spawn: windowMayExist is only set once it is.
@@ -4719,7 +4984,7 @@ function* spawnBody(root, agent, o = {}) {
4719
4984
  home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete,
4720
4985
  failed,
4721
4986
  outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg,
4722
- hookMeta: hookRes.meta || {}, compensationMeta, launched: false,
4987
+ hookMeta: hookRes.meta || {}, compensationMeta, launched: false, session: plannedSession,
4723
4988
  directoryHome: homeReal, recordRetirementBaseline: true,
4724
4989
  });
4725
4990
  } else {
@@ -4753,7 +5018,7 @@ function* spawnBody(root, agent, o = {}) {
4753
5018
  // apart from a dead one after a kill, so the spawn does not run its worktree hooks without it.
4754
5019
  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`);
4755
5020
  writeSpawnInProgressMarker("worktree", {});
4756
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: { session, window: instance } });
5021
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: plannedSession } : { launched: false, tmux: { session, window: instance } });
4757
5022
  treeGuard = signalGuard();
4758
5023
  const treeEnv = {
4759
5024
  OATS_TREE: tree, OATS_TREE_CLONE: cloneReal, OATS_TREE_REMOTE: originRemoteOf(cloneReal),
@@ -4845,9 +5110,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4845
5110
  // reads it again on the session it gets, and warns from that (below); a spawn that launches
4846
5111
  // nothing warns from this, and the warning says whose values were read.
4847
5112
  const folderTrustOn = (launchEnv) => launchFolderTrust({ harness, home, meta: { workspace: { deployment: o.prepared?.deployment } }, yolo, launch: launchEnv, configEnv: launchConfig?.env, launchConfig: launchConfig?.name });
4848
- let folderTrust = folderTrustOn(launchEnvOn(expectedEnv.pane, removedEnv));
5113
+ // A session provider runs the harness in its own place, with its own trust of the folder, and is
5114
+ // handed the launch as data (providerLaunchInput): no command line is rendered or recorded.
5115
+ let folderTrust = provider ? { trustHome: false } : folderTrustOn(launchEnvOn(expectedEnv.pane, removedEnv));
4849
5116
  if (!launch && folderTrust.warning) warnings.push(folderTrust.warning);
4850
- let cmdline = renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
5117
+ let cmdline = provider ? undefined : renderLaunchRecipe(recipe, { home, instance, trustHome: folderTrust.trustHome });
4851
5118
 
4852
5119
  // Module skills as materialize landed them (flat, .agents/skills/<skill>/),
4853
5120
  // beside the soul's own: per-skill provenance `module:<cap>` (lead decision c3),
@@ -4929,8 +5196,10 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4929
5196
  missingRequires: cap.missingRequires, trust: cap.trust,
4930
5197
  executable: cap.executable,
4931
5198
  })),
4932
- tmux: { session, window: instance },
4933
- launch: recipe, command: cmdline, createdAt: new Date().toISOString(),
5199
+ // The session's endpoint, as the receipt authorises it: tmux's planned names, or a session
5200
+ // provider's backend and capability (its endpoint is the provider's answer to the launch).
5201
+ ...(provider ? { backend, session: { provider: provider.capability, endpoint: null } } : { tmux: { session, window: instance } }),
5202
+ launch: recipe, ...(provider ? {} : { command: cmdline }), createdAt: new Date().toISOString(),
4934
5203
  };
4935
5204
  // Workspace model: materialize recorded modules/providers (and the module
4936
5205
  // digests) in instance.json before this metadata is assembled — carry them.
@@ -4939,16 +5208,63 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4939
5208
  Object.assign(meta, workspaceRecord);
4940
5209
  }
4941
5210
  const spawnWarnings = warnings;
4942
- // Feature instance-same-work: bound to the parent the home records, written before the launch so that
4943
- // the instance's first status shows it; the home's removal on a rollback takes it with the rest.
4944
- if (o.sameWork === true && meta.parentInstance) writeSameWork(home, meta.parentInstance);
5211
+ // Feature instance-related-work: bound to the parent the home records, else to its sibling (the one
5212
+ // choice, relatedWorkBinding), written before the launch so that the instance's first status shows it;
5213
+ // the home's removal on a rollback takes it with the rest.
5214
+ if (relatedWorkAsked && relatedWorkBinding(meta)) writeRelatedWork(home, relatedWorkBinding(meta));
4945
5215
 
4946
5216
  spawnTmux = meta.tmux;
4947
5217
  if (work === "directory") assertDirectoryRoots(home, homeReal);
4948
5218
  // The launch's one native start, prepared before anything is created; every render below reuses it.
4949
- const nativeStart = launch ? prepareNativeStart(home, harness) : null;
5219
+ const nativeStart = launch && !provider ? prepareNativeStart(home, harness) : null;
4950
5220
  let unscoped = null; // the harness's agent-scope warning, an event once the launch is recorded
4951
- if (launch) {
5221
+ if (launch && provider) {
5222
+ // The record and the independent receipt first, as planned and not launched: the receipt's
5223
+ // digest of the home is taken before the provider's harness can write there. The endpoint is
5224
+ // the provider's answer; it is recorded in both, the receipt first, as soon as it is given.
5225
+ // Under the home's lifecycle claim (the launch is its first start), taken before the record
5226
+ // and the receipt make it a home another verb could act on (providerLaunchClaim).
5227
+ providerLaunchClaim = claimHomeFor("start", instance, canonicalHomePath(home));
5228
+ meta.launched = false;
5229
+ writeEarlyProviderReceipt();
5230
+ writeHomeRecord(home, meta);
5231
+ clearSpawnInProgressMarker();
5232
+ // Killed here, the home is planned: its record, and the receipt written before it.
5233
+ dieAt("spawn:record-written");
5234
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: plannedSession });
5235
+ const found = homeSessionProvider(home, meta, provider.capability, backend);
5236
+ if (found.problem) throw oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${found.problem}`);
5237
+ const input = providerLaunchInput({ home, instance, recipe, env: process.env, removed: removedEnv, previous: null });
5238
+ // The provider's own readiness first, where it declares one: a launch is never sent to a
5239
+ // backend that says it cannot take it.
5240
+ const notReady = launchReadinessRefusal(found.binding);
5241
+ if (notReady) throw Object.assign(oatsError(notReady.code, `${instance} was not launched: ${notReady.message}`), { details: { backend, capability: provider.capability } });
5242
+ assertHostRunAdmission();
5243
+ // From here a session may exist: the spawn's compensation stops it before anything is removed.
5244
+ // And a spawn that ends here without doing so (killed, its host stopped) leaves its word in
5245
+ // the receipt, outside the home: a launch was sent (launchSentOf).
5246
+ const orphaned = endProviderCalls(home); // of a home of this name that is gone
5247
+ if (orphaned) throw oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${orphaned}`);
5248
+ const launchSent = markLaunchSent(home);
5249
+ providerSession = { binding: found.binding, endpoint: null, launchSent };
5250
+ const call = markProviderCall(home, "launch");
5251
+ let answered;
5252
+ try { answered = launchProviderSession(found.binding, input, { groupFile: call.groupFile }); } finally { call.done(); }
5253
+ 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 } }); }
5254
+ if (answered.failed) {
5255
+ if (!answered.uncertain) { providerSession = null; clearLaunchSent(home); }
5256
+ throw oatsError("E_SESSION_START_FAILED", `session backend ${backend} did not launch ${instance}: ${answered.failed}`);
5257
+ }
5258
+ providerSession.endpoint = answered.endpoint;
5259
+ promptStartId = randomUUID();
5260
+ meta.startId = promptStartId;
5261
+ meta.session = { provider: provider.capability, endpoint: answered.endpoint };
5262
+ meta.launched = true;
5263
+ meta.launchPrompts = notEngaged(promptStartId);
5264
+ recordLaunchOutcome(home, { backend, provider: provider.capability, endpoint: answered.endpoint }, meta, { keepMark: true });
5265
+ // (The claim is kept to the spawn's last write of the record, below: a restart admitted
5266
+ // before it would have its record overwritten by this spawn's.)
5267
+ } else if (launch) {
4952
5268
  // The session on the OATS server, then everything on the one socket that answered: the collision
4953
5269
  // check, the records, the window and (in compensateSpawn) its removal.
4954
5270
  const socket = ensureOatsTmuxSession(session, existsSync(root) ? root : workspaceOf(root), undefined, tmuxSessionPlan, undefined, spawnWarnings);
@@ -5057,10 +5373,15 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5057
5373
  if (!meta.launched) throw retainedPromptError(home, instance, promptTarget, parentLineageCommitted, promptResult);
5058
5374
  }
5059
5375
  } else {
5376
+ // (3) A provider home's spawn holds the home's claim from before its record, launched or
5377
+ // not: a start admitted between that record and the spawn's last receipt write would have its
5378
+ // receipt overwritten as never launched.
5379
+ if (provider) { providerLaunchClaim = claimHomeFor("start", instance, canonicalHomePath(home)); writeEarlyProviderReceipt(); }
5060
5380
  meta.launched = false;
5061
5381
  writeHomeRecord(home, meta);
5062
5382
  clearSpawnInProgressMarker();
5063
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: meta.tmux });
5383
+ if (provider) dieAt("spawn:record-written");
5384
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: plannedSession } : { launched: false, tmux: meta.tmux });
5064
5385
  }
5065
5386
 
5066
5387
  // Ordinary launches and scaffolds commit here; launches that engage the
@@ -5071,12 +5392,20 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5071
5392
  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 } : {}) } });
5072
5393
  if (launch) appendEvent(home, { kind: "launched", data: { harness, backend, launchConfig: launchConfig?.name ?? null } });
5073
5394
  if (unscoped) appendEvent(home, { kind: "launch-warning", data: { message: unscoped } });
5395
+ if (providerLaunchClaim) {
5396
+ // The launch's mark goes (kept since the launch's outcome), BEFORE the record says the spawn
5397
+ // completed: a same-key retry never replays, as finished, a home that is still unsettled.
5398
+ dieAt("spawn:recorded");
5399
+ clearLaunchSent(home);
5400
+ }
5074
5401
  if (o.idempotencyKey !== undefined) {
5075
5402
  // Only now is the spawn a finished receipt a same-key retry may replay.
5076
5403
  meta.spawnCompleted = true;
5077
5404
  writeHomeRecord(home, meta); // a kernel-owned field: the baseline fingerprint ignores it
5078
5405
  }
5079
- 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 } : {}) });
5406
+ if (providerLaunchClaim) dieAt("spawn:published");
5407
+ releaseProviderLaunchClaim();
5408
+ 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 } : {}) });
5080
5409
  } catch (error) {
5081
5410
  if (promptDispatched) {
5082
5411
  // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
@@ -5116,6 +5445,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5116
5445
  } finally {
5117
5446
  // Interrupts were held through the rollback of a spawn that ran worktree hooks (#796).
5118
5447
  treeGuard?.restore();
5448
+ // Held until the launch is undone: nothing acts on the home while its session is stopped and it is removed.
5449
+ releaseProviderLaunchClaim();
5119
5450
  }
5120
5451
  // #796: the worktree hooks' logs are in the home. A rollback that removed it removed them: no
5121
5452
  // answer names a path that is gone (each entry's `log` is null); a retained home keeps them.
@@ -5318,7 +5649,7 @@ function buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, f
5318
5649
  function writeQuarantineMarker(home, marker, extra = {}, mode) {
5319
5650
  writeJsonAtomic(join(home, ".oats-rollback-incomplete.json"), { ...marker, ...extra }, mode);
5320
5651
  }
5321
- 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) }) {
5652
+ 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) }) {
5322
5653
  const marker = buildQuarantineMarker({ instance, agent, soulDir, soulId, incomplete, failed, outstandingHooks, outstandingGit, repoAbs, work, branch, resolvedCfg, hookMeta, compensationMeta, launched, tmux, reason, directoryPreservation, orphanedWork });
5323
5654
  try {
5324
5655
  if (work === "directory") {
@@ -5341,7 +5672,8 @@ function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomp
5341
5672
  if (recordRetirementBaseline) {
5342
5673
  try {
5343
5674
  if (work === "directory") assertDirectoryRoots(home, directoryHome);
5344
- writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities || [], { launched: launched === true, tmux });
5675
+ // (`session`: a home on a session provider keeps its backend and provider in the receipt.)
5676
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities || [], session ? { launched: false, session } : { launched: launched === true, tmux });
5345
5677
  } catch (e) {
5346
5678
  incomplete.push(`independent retirement authority: ${e.message}`);
5347
5679
  }
@@ -5476,13 +5808,15 @@ function retireGitProbe(repo, args, { encoding } = {}) {
5476
5808
  * KERNEL_HOME_NAME_PREFIXES in lib/capability-contract.mjs, and the schema). */
5477
5809
  // `.oats-color.json` (feature instance-color) and `.oats-background.json` (feature instance-background) are
5478
5810
  // presentation anyone may change at any time: never work. `.oats-pinned.json` (feature instance-pin) is
5479
- // presentation of the same kind.
5480
- // `.oats-same-work.json` (feature instance-same-work) is kernel presentation of the same kind.
5811
+ // presentation of the same kind. `.oats-board.json` (feature instance-board) is the agent's own display, and
5812
+ // `.oats-board.lock` what a write killed while it held the lock leaves: never work.
5813
+ // `.oats-related-work.json` (feature instance-related-work) is kernel presentation of the same kind, and so is
5814
+ // `.oats-same-work.json`, the file of the flag it replaced: read while the new one is absent, never written.
5481
5815
  // `.oats-start-exited` (lib/session-end.mjs) is the window's record of how the harness ended: every
5482
5816
  // launched home whose harness ever ended holds it.
5483
5817
  // `.oats-start-env.json` and its key (lib/start-env.mjs) are written at every start that renders a
5484
5818
  // recipe, after the spawn's baseline: every launched home holds them.
5485
- const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", ".oats-background.json", PIN_FILE, SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
5819
+ const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json", ".oats-background.json", PIN_FILE, BOARD_FILE, BOARD_LOCK, RELATED_WORK_FILE, SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
5486
5820
  // `instance.json.tmp-<pid>` is what a process killed between the two steps of writeJsonAtomic leaves
5487
5821
  // of the record: not a hidden name, so a capability cannot declare it (disposableHomeRootProblem).
5488
5822
  const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, /^instance\.json\.tmp-\d+$/, START_ENV_TMP, LAUNCH_ENV_HANDOFF];
@@ -5925,6 +6259,7 @@ function retirementDisposableRoots(work, capabilities) {
5925
6259
  * is still recovered at retire. (Replaces a whole-home re-stamp that could
5926
6260
  * bless authored bytes written in the launch→completion interval.) */
5927
6261
  const KERNEL_POST_SPAWN_FIELDS = ["spawnCompleted", "wake", "launchPrompts", "launchPromptTarget", "parentLineageCommitted"];
6262
+ const PROVIDER_POST_SPAWN_FIELDS = ["session", "launched", "startId"];
5928
6263
  // What a digest holds of a home instance.json to take its neutral form (#617); a larger one is hashed raw, in pieces.
5929
6264
  const NEUTRAL_INSTANCE_JSON_BYTES = 16 * 1024 * 1024;
5930
6265
  function kernelNeutralInstanceJson(bytes) {
@@ -5938,6 +6273,10 @@ function kernelNeutralInstanceJson(bytes) {
5938
6273
  const m = JSON.parse(text);
5939
6274
  if (!m || typeof m !== "object" || Array.isArray(m)) return bytes;
5940
6275
  for (const k of KERNEL_POST_SPAWN_FIELDS) delete m[k];
6276
+ // A home on a session provider (it records `session`): its endpoint is the provider's answer
6277
+ // to the launch, so the kernel writes the launch's outcome after the baseline is taken, where
6278
+ // a tmux home's is written before its window exists. The receipt is their authority.
6279
+ if (m.session !== undefined && typeof m.backend === "string") for (const k of PROVIDER_POST_SPAWN_FIELDS) delete m[k];
5941
6280
  return Buffer.from(JSON.stringify(m));
5942
6281
  } catch { return bytes; }
5943
6282
  }
@@ -6283,10 +6622,14 @@ export function writeRetirementBaseline(home, work, mode, capabilities, runtime,
6283
6622
  disposableReceipts,
6284
6623
  disposableHome,
6285
6624
  generatedWorkFingerprint: isWorktree ? generatedWorkDigest(work, statusBytes, disposableReceipts.map((r) => r.root)) : undefined,
6286
- runtime: {
6287
- launched: runtime?.launched === true,
6288
- ...(runtime?.tmux ? { tmux: { session: runtime.tmux.session, window: runtime.tmux.window, ...(runtime.tmux.socket ? { socket: resolve(runtime.tmux.socket) } : {}) } } : {}),
6289
- },
6625
+ // `runtime.session`: a home on a session provider (lib/session-providers.mjs): its backend and the
6626
+ // capability that supplies it, and once launched the endpoint and whether OATS stopped it.
6627
+ runtime: runtime?.session
6628
+ ? (runtime.launched === true ? providerRuntimeRecord(runtime.session) : { launched: false, backend: runtime.session.backend, provider: runtime.session.provider })
6629
+ : {
6630
+ launched: runtime?.launched === true,
6631
+ ...(runtime?.tmux ? { tmux: { session: runtime.tmux.session, window: runtime.tmux.window, ...(runtime.tmux.socket ? { socket: resolve(runtime.tmux.socket) } : {}) } } : {}),
6632
+ },
6290
6633
  };
6291
6634
  assertRetirementTransientsUnchanged(transientFiles);
6292
6635
  const path = retirementBaselinePath(home);
@@ -6399,6 +6742,9 @@ export function observeSessionWithoutReceipt(home, meta, io) {
6399
6742
  }
6400
6743
  function recordedSessionAbsence(home, meta, io) {
6401
6744
  const tmux = meta?.tmux;
6745
+ // A home whose record names a session provider is never one from before session receipts: without
6746
+ // a receipt that can be used, whether its provider runs a session for it is not known.
6747
+ 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" };
6402
6748
  // A --no-launch home keeps its planned tmux names with `launched: false`: nothing was started there.
6403
6749
  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" };
6404
6750
  if (!tmux) return { absent: false, backend: null, note: "instance.json records a launch but no session endpoint" };
@@ -6483,7 +6829,28 @@ function stopSessionClaimed(home, o) {
6483
6829
  try {
6484
6830
  if (retireCarried(realHome)) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired; nothing was stopped`);
6485
6831
  const s = instanceSessionTarget(realHome);
6486
- if (!s.target) return { home: s.home, backend: null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6832
+ // A launch that was sent to the home's provider and never recorded: the provider stops whatever
6833
+ // it started before anything else is answered. Never "not launched" while that is not known.
6834
+ const sent = s.unsettled;
6835
+ if (sent && s.session) {
6836
+ // A home launched before: the one stop rule first (stopProviderHome: `stoppedAt` and the stop
6837
+ // receipt before the provider is called, the recorded session stopped, a host's stop
6838
+ // withdrawn by an operator's), then the launch that was sent.
6839
+ // (Not confirmed: E_SESSION_STOP_FAILED, and the home stays unsettled. The host's stop of a
6840
+ // home that is stopped already asks nothing: the settle then asks for the recorded session.)
6841
+ const stopped = stopProviderHome(realHome, s, o);
6842
+ const unsettled = settleSentLaunch(realHome, s.meta, sent, o.graceMs, o.io, { recordedStopped: !(o.withHost === true && s.session.stoppedAt !== null) });
6843
+ 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`);
6844
+ return { ...stopped, stopped: true, alreadyIdle: false };
6845
+ }
6846
+ if (sent) {
6847
+ const unsettled = settleSentLaunch(realHome, s.meta, sent, o.graceMs, o.io);
6848
+ 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`);
6849
+ appendEvent(realHome, { kind: "stopped", data: { signal: null, waitedMs: 0, stillRunning: [], state: "stopped" } });
6850
+ return { home: s.home, backend: sent.backend, stopped: true, alreadyIdle: false, state: "stopped", receipt: null };
6851
+ }
6852
+ if (s.session) return stopProviderHome(realHome, s, o);
6853
+ if (!s.target) return { home: s.home, backend: s.planned?.backend ?? null, stopped: false, alreadyIdle: true, state: "not-launched", receipt: null };
6487
6854
  let before;
6488
6855
  try { before = inspectSessionTarget(s.target); }
6489
6856
  catch (e) {
@@ -6523,6 +6890,55 @@ function stopSessionClaimed(home, o) {
6523
6890
  throw failure;
6524
6891
  }
6525
6892
  }
6893
+ /** An OATS stop of a provider home's session, the kernel-owned rule in one place (a stop's, a
6894
+ * restart's): `stoppedAt` in the receipt first, then the home's stop receipt (`withHost`: the
6895
+ * host's shutdown wrote it, which a resume brings back), then the provider's stop → `{ unconfirmed,
6896
+ * waitedMs }`: `unconfirmed` null when the provider confirmed, else why not. The home stays
6897
+ * recorded as stopped either way. */
6898
+ function stopProviderSessionRecorded(home, meta, session, { withHost = false, graceMs, io, outlasted } = {}) {
6899
+ const started = Date.now();
6900
+ // An earlier stop's receipt goes first (one a resume that died left behind names this same
6901
+ // start): this stop is an operator's until its own receipt says otherwise.
6902
+ rmSync(join(home, STOP_RECEIPT_FILE), { force: true });
6903
+ writeProviderRuntime(home, { backend: session.backend, provider: session.provider, endpoint: session.endpoint, stoppedAt: new Date(started).toISOString() });
6904
+ dieAt("stop:stoppedAt-written");
6905
+ // The stop receipt: a record that cannot be written leaves the home stopped as by an operator,
6906
+ // which no resume brings back.
6907
+ try { recordStop(home, null, { withHost }); } catch { /* see above */ }
6908
+ dieAt("stop:receipt-written");
6909
+ const unconfirmed = providerStopUnconfirmed(home, meta, session, session.endpoint, graceMs, io, null, { outlasted });
6910
+ return { unconfirmed, waitedMs: Date.now() - started };
6911
+ }
6912
+ /** The stop of a home on a session provider (lib/session-providers.mjs), under the home's claim.
6913
+ * Kernel-owned: the receipt records `stoppedAt` BEFORE the provider is called, so from that
6914
+ * instant inspect answers stopped and input is refused, whatever the provider then does; a start
6915
+ * clears it. Which stop it was is the home's stop receipt's to say, as for a tmux home
6916
+ * (recordStop): an operator's stop is the intent that keeps the home down; a stop with the host
6917
+ * (`withHost`: `oats host run`'s shutdown) is a loss, which a resume brings back. The provider's
6918
+ * stop comes second, given the stop's grace and never escalated: one that fails or cannot be
6919
+ * confirmed is E_SESSION_STOP_FAILED, and the home stays recorded as stopped. A home OATS already
6920
+ * stopped is idle, and an operator's stop of it asks the provider once more (its stop is
6921
+ * idempotent): that is how a stop the provider did not confirm is finished. It also rewrites the
6922
+ * stop receipt of a home stopped with the host, which withdraws the resume. */
6923
+ function stopProviderHome(realHome, s, o) {
6924
+ const { backend, stoppedAt } = s.session;
6925
+ const withHost = o.withHost === true;
6926
+ const idle = { home: s.home, backend, stopped: false, alreadyIdle: true, state: "stopped", receipt: null };
6927
+ if (stoppedAt !== null) {
6928
+ // The host's shutdown changes nothing of a home that is stopped already.
6929
+ if (withHost) return idle;
6930
+ if (lostReasonOf(realHome, s.meta) === HOST_STOP_REASON) recordStop(realHome, null);
6931
+ // An operator's stop asks the provider again: an earlier stop may not have been confirmed
6932
+ // (E_SESSION_STOP_FAILED leaves the home recorded as stopped), and this is how it is finished.
6933
+ const again = providerStopUnconfirmed(realHome, s.meta, s.session, s.session.endpoint, o.graceMs);
6934
+ 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}`);
6935
+ return idle;
6936
+ }
6937
+ const { unconfirmed, waitedMs } = stopProviderSessionRecorded(realHome, s.meta, s.session, { withHost, graceMs: o.graceMs });
6938
+ appendEvent(realHome, { kind: unconfirmed ? "stop-refused" : "stopped", data: { signal: null, waitedMs, stillRunning: [], state: unconfirmed ? "unknown" : "stopped" } });
6939
+ 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}`);
6940
+ return { home: s.home, backend, stopped: true, alreadyIdle: false, state: "stopped", receipt: null };
6941
+ }
6526
6942
  /** What a failed stop (an error of stopInstanceSession) established of the processes it signalled,
6527
6943
  * for its row of results: [] only when its receipt says the harness exited; the pids its receipt
6528
6944
  * names as still alive; and null when nothing is established. That is a stop without a receipt,
@@ -6572,17 +6988,275 @@ function stopRecordedChildren(children, signalled) {
6572
6988
  export async function attachInstanceSession(home, { detachKey, statusLine, onSwept } = {}) {
6573
6989
  if (detachKey !== undefined) requireDetachKey(detachKey);
6574
6990
  const s = instanceSessionTarget(home);
6991
+ if (s.session) throw sessionNoTerminal(s);
6575
6992
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
6576
6993
  return attachSessionTarget(s.target, { detachKey, statusLine, onSwept });
6577
6994
  }
6995
+ /** E_SESSION_NO_TERMINAL: a session provider's session has no terminal to attach to. Its message
6996
+ * and `details.open` carry what the provider offers instead (inspect's `open`), when it says. */
6997
+ function sessionNoTerminal(s) {
6998
+ let open = null;
6999
+ try { open = inspectInstanceSession(s.home).open ?? null; } catch (e) { if (!isKernelCode(e?.code)) throw e; /* the refusal stands without the link */ }
7000
+ 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 } });
7001
+ }
6578
7002
 
6579
7003
  export function inputInstanceSession(home, text) {
6580
7004
  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");
6581
7005
  const s = instanceSessionTarget(home);
7006
+ if (s.session) return inputProviderHome(s, text);
6582
7007
  if (!s.target) throw oatsError("E_SESSION_NOT_RUNNING", "instance was not launched");
6583
7008
  try { return { home: s.home, ...inputSessionTarget(s.target, text) }; }
6584
7009
  catch (e) { throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${e.message}`); }
6585
7010
  }
7011
+ /** Input to a home on a session provider.
7012
+ * - Kernel-owned: a home OATS stopped refuses E_SESSION_NOT_RUNNING before any provider call, for
7013
+ * every caller (a person's `session input`, a scheduled wake, a client, the messaging broker): a
7014
+ * provider would otherwise restart the session on the next input.
7015
+ * - A session that is gone and that OATS did not stop is a lost one, and an input to it is a
7016
+ * RESUME (the provider restarts it on that input): counted against the home's resume cap before
7017
+ * the provider's input is called (lib/provider-resume.mjs), refused E_SESSION_NOT_RUNNING at the
7018
+ * cap, and refused while a process of its last run still works in the home (resumeLostSession).
7019
+ * So the session is read first: one that cannot be read is E_SESSION_INPUT_FAILED, never sent to.
7020
+ * - Otherwise the provider's answer: `submitted: true` only when the input was dispatched;
7021
+ * E_SESSION_PROMPT_OPEN and E_SESSION_INPUT_QUEUED as it gives them (nothing was sent); anything
7022
+ * else E_SESSION_INPUT_FAILED. */
7023
+ function inputProviderHome(s, text) {
7024
+ const { backend, provider, endpoint, stoppedAt } = s.session;
7025
+ const name = basename(s.home);
7026
+ 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}`);
7027
+ // A launch that was sent and never recorded: the session it may have started is not the one at
7028
+ // the recorded endpoint, and an input there would have the provider start a second one.
7029
+ if (s.unsettled) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${unsettledLaunchSaid(name, backend, s.unsettled.launchSent)}; nothing was sent`);
7030
+ const found = homeSessionProvider(s.home, s.meta, provider, backend);
7031
+ if (found.problem) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${found.problem}`);
7032
+ const inspected = inspectProviderSession(found.binding, endpoint);
7033
+ 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`);
7034
+ const resume = inspected.observed.present ? null : resumeLostSession(s.home, name, { waitMs: 0 });
7035
+ // An input holds no claim, and a provider restarts a session on it: a stop, a restart or a
7036
+ // retire that lands while this input runs must still win. So the receipt is read again right
7037
+ // before the input (the inspect above may have taken seconds), and once more after it.
7038
+ // What crossed, if anything, from one read of the home → `{ what, sameLocator }`, or null: `what`
7039
+ // is `stopped` (the home is stopped, or its session is no longer recorded) or `restarted` (it
7040
+ // runs again: another start, by its id, or another endpoint). The start's id is compared as
7041
+ // well as the endpoint: a provider may hand a restart the same locator again (`sameLocator`).
7042
+ const startId = s.meta?.startId ?? null;
7043
+ const crossed = () => {
7044
+ try {
7045
+ const now = instanceSessionTarget(s.home);
7046
+ if (!now.session || now.session.stoppedAt !== null) return { what: "stopped", sameLocator: false };
7047
+ // A start that is launching (its launch is sent, not yet recorded): the session at this
7048
+ // endpoint is the one it replaces, whatever locator the new one gets.
7049
+ if (now.unsettled) return { what: "restarted", sameLocator: false };
7050
+ const sameLocator = sameEndpoint(now.session.endpoint, endpoint);
7051
+ return (now.meta?.startId ?? null) !== startId || !sameLocator ? { what: "restarted", sameLocator } : null;
7052
+ } catch { return { what: "stopped", sameLocator: false }; }
7053
+ };
7054
+ // In flight from here to the answer: a record outside the home says so to a retire, which waits
7055
+ // for it before its last stop (markProviderCall). Written BEFORE the read below, so an input
7056
+ // either sees the retire's stop there, or is seen by the retire.
7057
+ let call;
7058
+ try {
7059
+ // (A call a killed kernel left behind for this home, a stop that would run late, is ended first.)
7060
+ const orphaned = endProviderCalls(s.home);
7061
+ if (orphaned) throw new Error(orphaned);
7062
+ call = markProviderCall(s.home, "input");
7063
+ }
7064
+ 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`); }
7065
+ try {
7066
+ 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`); }
7067
+ let sent, failure;
7068
+ try { sent = inputProviderSession(found.binding, endpoint, text, { groupFile: call.groupFile }); }
7069
+ catch (e) {
7070
+ // The count is taken back only when the provider itself refused: nothing was sent. An input
7071
+ // whose call failed may have restarted the session: it stays counted, so no failing provider
7072
+ // lets input past the cap.
7073
+ if (inputWasRefused(e)) resume?.undo();
7074
+ failure = e;
7075
+ }
7076
+ // A stop (a restart's, a retire's) that landed while the input was being sent, whatever the
7077
+ // provider answered, a refusal included: it may have restarted the session it had just stopped,
7078
+ // at an endpoint OATS records as stopped or no longer records. It is asked to stop that session
7079
+ // again, and the input is not delivered: a mail then stays unread and comes again, to the
7080
+ // session that is there by then. After a RESTART the session at the endpoint this input used is
7081
+ // stopped again only when the home now runs at another one: the same locator is the new
7082
+ // session's, which no input's cleanup may stop.
7083
+ const crossing = crossed();
7084
+ if (crossing) {
7085
+ // (Recorded as a call, as every stop is; no drain: an input does not wait for another.)
7086
+ const again = crossing.sameLocator ? null : trackedProviderStop(s.home, found.binding, endpoint, 20);
7087
+ 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 with oats instance stop ${name}` : ""}` : ""}, and the input is not delivered`);
7088
+ }
7089
+ if (failure) throw failure;
7090
+ // No endpoint here: it is on inspect, spawn and start answers only.
7091
+ return { home: s.home, backend, ...sent };
7092
+ } finally { call.done(); }
7093
+ }
7094
+ /** The provider calls in flight for a home (docs/design/2026-11-20-provider-home-lifecycle.md, "A
7095
+ * provider's command outlives the kernel that ran it" and "A retire and an input in flight").
7096
+ *
7097
+ * A launch and an input can start a session, and the kernel that sent one can be killed while
7098
+ * it waits: the provider's command lives on, and a session it starts later would have no record.
7099
+ * So each such call has a record outside the home, beside the claims
7100
+ * (`<instances>/.oats-retirement/provider-calls/<name>/<verb>-<pid>-<id>.json`): the kernel that
7101
+ * makes the call (pid and start time, as a claim names its holder), and, in `<record>.group`, the
7102
+ * leader of the process group the provider's command runs in, written by that leader before the
7103
+ * provider runs (lib/provider-call-child.mjs). The record is removed when the call returns.
7104
+ *
7105
+ * A record left by a kernel that is gone is a call that may still act. Before the kernel relies
7106
+ * on a provider's stop (providerStopUnconfirmed), it ends each: the group is killed and seen
7107
+ * empty; a call whose group never recorded itself is made void (the `.group` file is created
7108
+ * here, so that leader, if it comes, runs nothing). A retire also waits for the inputs of LIVE
7109
+ * kernels (an input holds no claim), and ends those that outlast its wait. */
7110
+ const providerCallsDir = (home) => join(dirname(dirname(retireClaimPath(home))), "provider-calls", basename(home));
7111
+ /** The markers' directory lasts as long as a marker: none is left behind per home. */
7112
+ function removeIfEmpty(dir) {
7113
+ try { rmdirSync(dir); } catch (e) { if (!["ENOTEMPTY", "EEXIST", "ENOENT"].includes(e?.code)) throw e; }
7114
+ }
7115
+ /** Record that this process makes a `verb` call for `home` → `{ groupFile, done }`: where the
7116
+ * call's group records itself (callSessionProvider's `groupFile`: one call), and what takes the
7117
+ * record away. */
7118
+ /** Publish a small record whole, and only if none is there: written to a file of its own, then
7119
+ * linked to its name (EEXIST when the name is taken). A reader never finds it half written,
7120
+ * wherever its writer ends (the leader of a provider command's group publishes its own so:
7121
+ * lib/provider-call-child.mjs). */
7122
+ function publishExclusive(path, content) {
7123
+ const own = `${path}.${process.pid}.tmp`;
7124
+ try { writeFileSync(own, content, { mode: 0o600, flag: "wx" }); linkSync(own, path); }
7125
+ finally { rmSync(own, { force: true }); }
7126
+ }
7127
+ function markProviderCall(home, verb) {
7128
+ const dir = providerCallsDir(canonicalHomePath(home));
7129
+ const path = join(dir, `${verb}-${process.pid}-${randomUUID()}.json`);
7130
+ const write = () => { mkdirSync(dir, { recursive: true, mode: 0o700 }); publishExclusive(path, `${JSON.stringify({ verb, ...selfIdentity(), startedAt: new Date().toISOString() })}\n`); };
7131
+ // (Once more when another call's end took the directory away between the two steps.)
7132
+ try { write(); } catch (e) { if (e?.code !== "ENOENT") throw e; write(); }
7133
+ return { groupFile: `${path}.group`, done: () => { rmSync(path, { force: true }); rmSync(`${path}.group`, { force: true }); removeIfEmpty(dir); } };
7134
+ }
7135
+ /** The calls recorded for `home`, but this process's own → `[{ path, verb, pid, kernelGone }]`. */
7136
+ function providerCalls(home) {
7137
+ const dir = providerCallsDir(canonicalHomePath(home));
7138
+ let names;
7139
+ try { names = readdirSync(dir); } catch { return []; }
7140
+ const calls = [];
7141
+ for (const name of names) {
7142
+ const path = join(dir, name);
7143
+ // (A writer that ended before its link left its own file: nothing reads it, and it goes after a minute.)
7144
+ if (name.endsWith(".tmp")) { try { if (Date.now() - statSync(path).mtimeMs > 60_000) rmSync(path, { force: true }); } catch { /* gone meanwhile */ } continue; }
7145
+ if (!name.endsWith(".json")) continue;
7146
+ let record;
7147
+ try { record = JSON.parse(readFileSync(path, "utf8")); } catch { continue; } // just removed
7148
+ // This process's own (by its pid AND its start: a pid a gone kernel had is not this one).
7149
+ if (record.pid === process.pid && record.processStart === processStartToken(process.pid)) continue;
7150
+ calls.push({ path, verb: typeof record.verb === "string" ? record.verb : "call", pid: record.pid, kernelGone: processLiveness(record).state === "gone" });
7151
+ }
7152
+ if (!names.length) removeIfEmpty(dir);
7153
+ return calls;
7154
+ }
7155
+ /** Whether a process group has a member that can still act (one that is not a zombie) → true,
7156
+ * false, or null where that cannot be told (no /proc). */
7157
+ function groupCanAct(pgid) {
7158
+ let names;
7159
+ try { names = readdirSync("/proc"); } catch { return null; }
7160
+ for (const name of names) {
7161
+ if (!/^\d+$/.test(name)) continue;
7162
+ let stat;
7163
+ try { stat = readFileSync(`/proc/${name}/stat`, "utf8"); } catch { continue; } // gone meanwhile
7164
+ // "<pid> (<comm>) <state> <ppid> <pgrp> …": the command may hold spaces and parentheses.
7165
+ const [state, , pgrp] = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
7166
+ if (Number(pgrp) === pgid && state !== "Z" && state !== "X") return true;
7167
+ }
7168
+ return false;
7169
+ }
7170
+ /** End one recorded call: nothing of its provider command runs after this → null, and its record
7171
+ * is removed; else why not, in one sentence, and the record stays. */
7172
+ function endProviderCall(call) {
7173
+ const groupFile = `${call.path}.group`;
7174
+ const said = `the ${call.verb} command that pid ${call.pid} ran for it`;
7175
+ let group;
7176
+ try { publishExclusive(groupFile, `${JSON.stringify({ void: true })}\n`); group = { void: true }; }
7177
+ catch (e) {
7178
+ if (e?.code !== "EEXIST") return `${said} could not be ended (${e?.code ?? e?.message ?? e})`;
7179
+ // Its group recorded itself, or an earlier kernel made the call void: either is published whole.
7180
+ try { group = JSON.parse(readFileSync(groupFile, "utf8")); }
7181
+ catch (read) { return `${said} could not be ended (its process group's record cannot be read: ${read?.code ?? read?.message ?? read})`; }
7182
+ }
7183
+ if (group.void !== true) {
7184
+ // "foreign": the leader's pid is another process's now, so that group is gone.
7185
+ const ended = terminateRecordedGroup({ hookPgid: group.pid, hookStart: group.processStart }, 0);
7186
+ // (Members that are all zombies can act no more: they wait for a parent that does not reap
7187
+ // them, as under a container whose first process is no init.)
7188
+ 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`;
7189
+ }
7190
+ rmSync(call.path, { force: true });
7191
+ rmSync(groupFile, { force: true });
7192
+ removeIfEmpty(dirname(call.path));
7193
+ return null;
7194
+ }
7195
+ /** End the calls recorded for `home` whose kernel is gone → null when none is left, else why
7196
+ * not. Before a launch, an input or a resume is sent: a stop a killed kernel left behind would
7197
+ * run late, and stop what they start. */
7198
+ function endProviderCalls(home) {
7199
+ return providerCalls(home).filter((call) => call.kernelGone).map(endProviderCall).filter(Boolean).join("; ") || null;
7200
+ }
7201
+ /** Drain the provider calls recorded for `home`, before a provider's stop is relied on → null
7202
+ * when none is left, else why not. The caller has written its fence (`stoppedAt`, a launch's
7203
+ * mark), so no new input is admitted. A call whose kernel is gone is ended at once; one of a
7204
+ * live kernel (an input holds no claim) is waited for, at most an input's timeout and a margin,
7205
+ * and ended if it outlasts that, or if its kernel dies meanwhile. `outlasted`: an array that
7206
+ * takes the pids of the kernels whose call was ended at the bound. */
7207
+ function drainProviderCalls(home, { outlasted, boundMs = sessionProviderTimeout("input") + INPUT_IN_FLIGHT_MARGIN_MS } = {}) {
7208
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
7209
+ const deadline = Date.now() + boundMs;
7210
+ for (;;) {
7211
+ const calls = providerCalls(home);
7212
+ const gone = calls.filter((call) => call.kernelGone).map(endProviderCall).filter(Boolean);
7213
+ if (gone.length) return gone.join("; ");
7214
+ const live = calls.filter((call) => !call.kernelGone);
7215
+ if (!live.length) return null;
7216
+ if (Date.now() >= deadline) {
7217
+ outlasted?.push(...live.map((call) => call.pid));
7218
+ return live.map(endProviderCall).filter(Boolean).join("; ") || null;
7219
+ }
7220
+ sleep(100);
7221
+ }
7222
+ }
7223
+ /** How long a provider's stop waits for the inputs in flight (drainProviderCalls): an input's own timeout, and a margin. */
7224
+ const INPUT_IN_FLIGHT_MARGIN_MS = 5000;
7225
+ /** How long a resume of a lost provider session waits for the processes of its last run to leave
7226
+ * the home, and how often it looks. */
7227
+ const RESUME_QUIET_POLL_MS = 1000;
7228
+ /** The kernel's resume primitive for a LOST session of a provider home (its session is gone, and
7229
+ * OATS did not stop it), before the provider's input is called → `{ undo }` (the count, to take
7230
+ * back when the input is then refused).
7231
+ * 1. No process of the old run works in the home (the kernel's process scan): a provider's
7232
+ * harness can outlive its server's crash for a while, and a resume beside it would run two.
7233
+ * The resume waits up to `waitMs` (default 150 s; an input waits not at all), then refuses,
7234
+ * naming the processes, as a retire does, and never kills them: E_SESSION_UNKNOWN for a start
7235
+ * (the sweep tries again, and counts nothing), E_SESSION_NOT_RUNNING for an input.
7236
+ * 2. The resume is counted against the home's cap, or refused at it (countProviderResume). */
7237
+ function resumeLostSession(home, name, { waitMs = RESUME_QUIET_WAIT_MS } = {}) {
7238
+ const budget = resumeQuietWait(waitMs);
7239
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
7240
+ const deadline = Date.now() + budget;
7241
+ for (;;) {
7242
+ // The host's own scan, never a start's guarded seam: a process is looked for as a retire does.
7243
+ const scan = processesInHome(home);
7244
+ 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;
7245
+ if (!still) break;
7246
+ 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`);
7247
+ sleep(Math.min(RESUME_QUIET_POLL_MS, Math.max(1, deadline - Date.now())));
7248
+ }
7249
+ // Counted under the count's lock, and taken back under it: inputs that run at the same time
7250
+ // each read the count the others wrote, so none passes the cap beside another.
7251
+ const uncounted = (why) => oatsError("E_SESSION_NOT_RUNNING", `${name} lost its session, and its resume could not be counted (${why}); nothing was sent`);
7252
+ const locked = (fn) => withDirLock(resumeCountLock(home), `counting a resume of ${name}`, fn, { retryMs: 5000, busy: uncounted });
7253
+ let counted;
7254
+ try { counted = locked(() => countProviderResume(home, name)); } catch (e) {
7255
+ // A lock the system would not make (its directory, its file) is a count that cannot be written.
7256
+ throw isKernelCode(e?.code) || isDefect(e) ? e : uncounted(e?.code ?? e?.message ?? e);
7257
+ }
7258
+ return { undo() { try { locked(() => counted.undo()); } catch { /* the count stands: a resume too many is counted, never one too few */ } } };
7259
+ }
6586
7260
 
6587
7261
  // ---------------------------------------------------------------- session start
6588
7262
 
@@ -6719,6 +7393,9 @@ export function capturedProviders(meta, frozen) {
6719
7393
  return { id, contribution, binding, settings: contribution?.settings ?? binding?.settings ?? {}, settingsOrigins };
6720
7394
  });
6721
7395
  }
7396
+ /** The session backend a home launches on, as its record says: a session provider's name, else tmux.
7397
+ * A launch hook's OATS_BACKEND (a spawn hook's is the spawn's own choice). */
7398
+ const homeBackendOf = (meta) => (recordsSessionProvider(meta) ? meta.backend : "tmux");
6722
7399
  /** Capability contributions for a start of an existing home: the recorded
6723
7400
  * ones, refreshed by any capability that declares a `launch` hook (asked
6724
7401
  * for the target harness; spawn hooks are never re-run). A harness change
@@ -6770,7 +7447,7 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
6770
7447
  const volatileEnv = [];
6771
7448
  let hookDialogClaims;
6772
7449
  if (runs.length) {
6773
- 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 } }) }));
7450
+ 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), ...(asPreview ? { OATS_LAUNCH_PREVIEW: "1" } : {}), ...extraEnv } }) }));
6774
7451
  const failed = results.flatMap(({ res }) => res.failures || []).map((f) => `${f.capability}: ${f.message}`);
6775
7452
  if (failed.length) throw oatsError("E_LAUNCH_PREPARATION", `a capability could not prepare the ${harness} launch:\n ${failed.join("\n ")}`);
6776
7453
  const fresh = results.flatMap(({ res }) => res.contributions || []);
@@ -7006,13 +7683,7 @@ function startSession(home, o) {
7006
7683
  // pending receipt exists for.
7007
7684
  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) => {
7008
7685
  checkRoots();
7009
- const baselinePath = findRetirementBaseline(realHome);
7010
- let baseline;
7011
- try { baseline = JSON.parse(readFileSync(baselinePath, "utf8")); } catch (e) {
7012
- if (e.code === "ENOENT") throw missingSessionReceipt(realHome);
7013
- throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or unreadable for ${realHome}: ${e.message}`);
7014
- }
7015
- 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}`);
7686
+ const { path: baselinePath, baseline } = readSessionReceipt(realHome);
7016
7687
  baseline.runtime = { launched: true, tmux: { session: target.session, window: target.window, socket: resolve(target.socket) } };
7017
7688
  writeJsonAtomic(baselinePath, baseline, 0o600);
7018
7689
  if (o.io?.failBeforeMetadataWrite && reused !== "adopted") throw new Error("injected metadata write failure"); // the write after THIS start's allocation
@@ -7073,7 +7744,10 @@ function startSession(home, o) {
7073
7744
  const movedWarnings = [];
7074
7745
  // 1. Reconcile a pending receipt before the equality gate: it may be the
7075
7746
  // only record of a session an earlier start allocated.
7076
- if (existsSync(pendingPath)) {
7747
+ // A tmux home's only: a home whose receipt names a session provider has none, and a file of
7748
+ // that name in it (the home is its agent's to write) is not read, or it would move the home's
7749
+ // session authority to a tmux target.
7750
+ if (existsSync(pendingPath) && !receiptNamesProvider(realHome)) {
7077
7751
  let pending;
7078
7752
  try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = undefined; }
7079
7753
  const pt = pending?.target;
@@ -7157,6 +7831,8 @@ function startSession(home, o) {
7157
7831
  // 2. The ordinary gate and observation, all under the home's claim.
7158
7832
  const receipt = instanceSessionTarget(realHome);
7159
7833
  const meta = readMeta();
7834
+ // A home on a session provider has no window, pane or pending receipt: its start is its own.
7835
+ if (providerHomeOf(receipt)) return startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, cleanupWarnings });
7160
7836
  const harness = meta.harness;
7161
7837
  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`);
7162
7838
  let command = meta.command;
@@ -7340,15 +8016,7 @@ function startSession(home, o) {
7340
8016
  // Hooks that ran for real in the plan were handed the plan's: their statements don't reach this one.
7341
8017
  if (handed.OATS_HARNESS_EXECUTABLE !== handedExecutable) hookDialogClaims = voidedDialogClaims(hookDialogClaims);
7342
8018
  handedExecutable = handed.OATS_HARNESS_EXECUTABLE;
7343
- const real = prepareLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots, pass: "real" });
7344
- const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
7345
- const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
7346
- if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
7347
- // A provider's row names its env; the values are in the merged env.
7348
- 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]) }); };
7349
- const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
7350
- 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`);
7351
- }
8019
+ const real = realLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots }, previewed, volatileEnv);
7352
8020
  launchPlan.recipe = { ...launchPlan.recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
7353
8021
  command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome });
7354
8022
  if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
@@ -7559,6 +8227,265 @@ function startSession(home, o) {
7559
8227
  const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
7560
8228
  return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
7561
8229
  }
8230
+ /** The real run of a start's preview-aware launch hooks (prepareLaunchHooks, pass "real"), once its
8231
+ * preflight passed, over the contributions they gave as a preview (`previewed`). They may register
8232
+ * the home with their provider now, and must contribute exactly what they contributed as a
8233
+ * preview, which is what the launch was planned and preflighted from, apart from the values of
8234
+ * the env their preview declared volatile (`volatileEnv`). → the real run's answer;
8235
+ * E_LAUNCH_PREPARATION, naming the capabilities that differ, otherwise. One rule for a start on
8236
+ * tmux and on a session provider. */
8237
+ function realLaunchHooks(pass, previewed, volatileEnv) {
8238
+ const real = prepareLaunchHooks({ ...pass, pass: "real" });
8239
+ const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
8240
+ const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
8241
+ if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
8242
+ // A provider's row names its env; the values are in the merged env.
8243
+ 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]) }); };
8244
+ const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
8245
+ 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`);
8246
+ }
8247
+ return real;
8248
+ }
8249
+ /** The start, restart and `--resume` of a home on a session provider (lib/session-providers.mjs),
8250
+ * under the home's claim (startClaimed), its refusals and guards already passed (startSession).
8251
+ * `receipt`: instanceSessionTarget's answer, whose `session` (launched before) or `planned` (never
8252
+ * launched) names the backend and the capability that supplies it.
8253
+ *
8254
+ * - start: a home OATS stopped, one never launched, and one whose session is gone, are launched: a
8255
+ * fresh conversation on TASK.md, as for tmux. A session that is there and that OATS did not stop
8256
+ * is never launched over: E_SESSION_RUNNING when it reads `running: true`, else
8257
+ * E_SESSION_UNKNOWN (the provider cannot tell a live idle session from a settled one); so is one
8258
+ * that cannot be inspected.
8259
+ * - restart: stop (recorded first, as every OATS stop: stopProviderHome's rule), then the launch,
8260
+ * under the one claim. A stop that is not confirmed launches nothing: E_SESSION_STOP_FAILED.
8261
+ * - The plan is planLaunch's, with no pane: the recipe or the selection, the launch hooks (which
8262
+ * run before the provider's launch exactly as before a window's), the environment rules.
8263
+ * - The provider's launch answers the endpoint, recorded in the receipt (which clears `stoppedAt`)
8264
+ * and then in instance.json. Its own refusal (E_BACKEND_*) is relayed; a launch that fails is
8265
+ * E_SESSION_START_FAILED, and when its answer was lost the provider is asked to stop whatever
8266
+ * it started. Either way the home stays as it was: stopped, or never launched.
8267
+ * - `--resume` (resumeProviderSession) never launches: it continues the session where it is.
8268
+ * - A home whose modules now hold two capabilities that declare its backend's name is refused
8269
+ * E_BACKEND_AMBIGUOUS before anything is stopped or started (planLaunch). */
8270
+ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, cleanupWarnings }) {
8271
+ const { backend, provider } = providerHomeOf(receipt);
8272
+ const session = receipt.session ?? null;
8273
+ const name = meta.instance || basename(realHome);
8274
+ 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`);
8275
+ if (o.resume === true) {
8276
+ // A launch that was sent and never recorded, on a home launched before or not: unknown, nothing is resumed.
8277
+ if (receipt.unsettled) throw oatsError("E_SESSION_UNKNOWN", `${unsettledLaunchSaid(name, backend, receipt.unsettled.launchSent)}; nothing was resumed`);
8278
+ return resumeProviderSession(realHome, o, { session, meta, backend, provider, drift, cleanupWarnings });
8279
+ }
8280
+ const answerBase = () => ({ ...(drift.length ? { drift } : {}), instance: meta.instance, agent: meta.agent, home: realHome });
8281
+ // 1. The gate: what is there now, when OATS did not stop it. Not asked of an unsettled home
8282
+ // (a launch was sent and never recorded): it is settled below, which leaves it stopped.
8283
+ let bound = null, replaced = false;
8284
+ if (session && session.stoppedAt === null && !receipt.unsettled) {
8285
+ const found = homeSessionProvider(realHome, meta, provider, backend);
8286
+ const inspected = found.problem ? { unavailable: found.problem } : inspectProviderSession(found.binding, session.endpoint, { io: o.io });
8287
+ if (inspected.unavailable) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${name} is running, so nothing was started: ${inspected.unavailable}`);
8288
+ bound = found.binding;
8289
+ if (inspected.observed.present) {
8290
+ if (!o.restart) {
8291
+ if (inspected.observed.running === true) throw oatsError("E_SESSION_RUNNING", `${name} is running (${inspected.observed.state}); nothing was started`);
8292
+ 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 (oats instance stop ${name}), or use oats session restart --home ${realHome}`);
8293
+ }
8294
+ replaced = true;
8295
+ }
8296
+ }
8297
+ // 2. The plan: every preflight, and the launch hooks, before anything is stopped.
8298
+ const context = meta.repo && existsSync(meta.repo) ? resolve(meta.repo) : dirname(dirname(dirname(dirname(realHome))));
8299
+ const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
8300
+ let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
8301
+ const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
8302
+ 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)`);
8303
+ const plan = 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 });
8304
+ let recipe = plan.recipe, hookMeta = plan.hookMeta, hookDialogClaims = plan.hookDialogClaims;
8305
+ let warnings = [...plan.warnings];
8306
+ for (const message of plan.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
8307
+ // The preview-aware launch hooks run for real now, over the planned contributions, and must
8308
+ // contribute what they contributed as a preview (apart from the values of their volatile env).
8309
+ if (plan.previewedHooks.length) {
8310
+ const previewed = plan.recipe.hooks;
8311
+ const real = realLaunchHooks({ frozen: { ...plan.frozen, hooks: previewed }, harness: plan.harness, resolvedCfg, contextDir: context, home: realHome, meta, assertRoots: checkRoots }, previewed, plan.volatileEnv);
8312
+ recipe = { ...recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
8313
+ if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
8314
+ if (real.dialogClaims) hookDialogClaims = { ...(hookDialogClaims || {}), ...real.dialogClaims };
8315
+ warnings = [...warnings, ...real.warnings];
8316
+ for (const message of real.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
8317
+ }
8318
+ const removed = removedLaunchEnv({ declared: plan.declaredEnv, hooksEnv: recipe.hooks?.env, configEnv: recipe.env });
8319
+ if (kernelNode().warning) warnings.push(kernelNode().warning);
8320
+ const found = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8321
+ if (found.problem) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${found.problem}`);
8322
+ const input = providerLaunchInput({ home: realHome, instance: meta.instance, recipe, env: o.env || process.env, removed, previous: session?.endpoint ?? null });
8323
+ // The provider's own readiness, before anything is stopped: a restart never trades a session
8324
+ // that runs for a backend that says it cannot launch one.
8325
+ const notReady = launchReadinessRefusal(found.binding, { io: o.io });
8326
+ if (notReady) throw Object.assign(oatsError(notReady.code, `${name} was not started: ${notReady.message}; nothing was stopped or started`), { details: { backend, capability: provider } });
8327
+ checkRoots();
8328
+ // 2. A launch that an earlier spawn or start sent and never recorded (launchSentOf): settled
8329
+ // first. The provider stops whatever that launch started, and the home is then planned, or
8330
+ // stopped; or nothing is launched beside it.
8331
+ // (A home launched before has its recorded session stopped first, by the settle.)
8332
+ const unsettled = settleSentLaunch(realHome, meta, receipt.unsettled, o.stopGraceMs, o.io);
8333
+ 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`);
8334
+ // 3. The session at the recorded endpoint. A restart's stop: recorded first, then the provider's.
8335
+ let stop = null;
8336
+ if (replaced) {
8337
+ const { unconfirmed, waitedMs } = stopProviderSessionRecorded(realHome, meta, session, { graceMs: o.stopGraceMs, io: o.io });
8338
+ appendEvent(realHome, { kind: unconfirmed ? "stop-refused" : "restarted", data: { phase: "restart-stop", signal: null, waitedMs, stillRunning: [] } });
8339
+ 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}`);
8340
+ stop = { stopped: true, waitedMs };
8341
+ } else if (session && session.stoppedAt !== null && !receipt.unsettled) {
8342
+ // A home OATS stopped: its last stop may not have been confirmed (E_SESSION_STOP_FAILED leaves
8343
+ // it recorded as stopped). The launch replaces the endpoint, after which OATS could no longer
8344
+ // address a session still running there: the provider is asked once more first.
8345
+ const unconfirmed = providerStopUnconfirmed(realHome, meta, session, session.endpoint, o.stopGraceMs, o.io);
8346
+ 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`);
8347
+ }
8348
+ // 4. The launch.
8349
+ checkRoots();
8350
+ writeKernelShim(realHome);
8351
+ const startedAt = new Date().toISOString(), id = randomUUID();
8352
+ assertHostRunAdmission();
8353
+ // A call a killed kernel left for this home (a stop that would run late, and stop the session
8354
+ // launched here) is ended first.
8355
+ const orphaned = endProviderCalls(realHome);
8356
+ if (orphaned) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${orphaned}; nothing was sent to session backend ${backend}`);
8357
+ // From here a session may exist that no record names yet: the receipt says a launch was sent,
8358
+ // until its outcome is recorded.
8359
+ const launchSent = markLaunchSent(realHome);
8360
+ // A home launched before whose session OATS did not stop (it is gone, by the gate): the provider
8361
+ // is asked to stop it all the same (its stop is idempotent). An input that reached it since the
8362
+ // gate had the provider restart it, and the launch replaces its endpoint, after which OATS
8363
+ // could not address it. AFTER the mark: an input that read the home before the mark has ended
8364
+ // its provider call by now, and one that reads it after the mark stops that session itself, so
8365
+ // no input restarts it behind this stop. Not confirmed: nothing was sent, the mark is taken back.
8366
+ if (session && !replaced && session.stoppedAt === null && !receipt.unsettled) {
8367
+ const stale = providerStopUnconfirmed(realHome, meta, session, session.endpoint, o.stopGraceMs, o.io);
8368
+ 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`); }
8369
+ }
8370
+ const call = markProviderCall(realHome, "launch");
8371
+ let answered;
8372
+ try { answered = launchProviderSession(found.binding, input, { io: o.io, groupFile: call.groupFile }); } finally { call.done(); }
8373
+ 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 } }); }
8374
+ if (answered.failed) {
8375
+ // A launch whose answer was lost may have started a session: the provider stops what is rooted
8376
+ // at this home. The home's record is unchanged either way; one it could not stop stays
8377
+ // recorded as sent, and the next stop or start asks again.
8378
+ // (A launch that failed for certain started nothing: unmarked, the home is as it was.)
8379
+ // (The session recorded before this launch was stopped in step 3, or after the mark.)
8380
+ const unstopped = answered.uncertain ? settleSentLaunch(realHome, meta, { backend, provider, launchSent }, 20000, o.io, { recordedStopped: true }) : (clearLaunchSent(realHome), null);
8381
+ const compensated = unstopped ? { failed: unstopped } : null;
8382
+ 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` : ""}`);
8383
+ }
8384
+ // 5. The records, in the launch's three writes: the session boundary and the receipt's endpoint
8385
+ // (which clears `stoppedAt`) with the launch still marked as sent, then the record, then the
8386
+ // mark removed. Killed or failed between any two, the home is unsettled, and the next verb
8387
+ // settles it: never a record that contradicts its receipt.
8388
+ const unrecorded = (e) => {
8389
+ // (The launch is still marked as sent: the fence. Then the drain, then the stop.)
8390
+ const left = drainProviderCalls(realHome);
8391
+ const stopped = left ? { failed: left } : trackedProviderStop(realHome, found.binding, answered.endpoint, 20, { io: o.io });
8392
+ if (!stopped.failed) { try { recordLaunchSettled(realHome); } catch { /* the launch stays marked: the next stop or start asks the provider again */ } }
8393
+ 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`);
8394
+ };
8395
+ try {
8396
+ recordStartBoundary(realHome, { startId: id, startedAt, harness: plan.harness, backend, launchConfig: recipe.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
8397
+ checkRoots();
8398
+ } catch (e) { throw unrecorded(e); }
8399
+ const restarts = (Array.isArray(meta.restarts) ? meta.restarts : []).slice(-19);
8400
+ restarts.push({ startedAt, model: plan.model ?? null, reused: "new" });
8401
+ const modelFrom = modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null });
8402
+ const next = { ...meta, model: plan.model, launched: true, startId: id, restarts, restartCount: (meta.restartCount || 0) + 1, ...(modelFrom ? { modelFrom } : {}),
8403
+ launch: recipe, harness: plan.harness, ...(plan.yolo !== undefined ? { yolo: plan.yolo } : {}),
8404
+ ...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at ?? null, launchDeclared: plan.launchChoice.declared ?? null } : {}),
8405
+ ...(hookMeta ? { capabilityMeta: { ...(meta.capabilityMeta || {}), ...hookMeta } } : {}),
8406
+ backend, session: { provider, endpoint: answered.endpoint }, launchPrompts: notEngaged(id) };
8407
+ if (hookDialogClaims) { next.dialogClaims = replacedDialogClaims(meta.dialogClaims, hookDialogClaims); if (!next.dialogClaims) delete next.dialogClaims; }
8408
+ delete next.launchPromptTarget;
8409
+ try { recordLaunchOutcome(realHome, { backend, provider, endpoint: answered.endpoint }, next); }
8410
+ catch (e) {
8411
+ if (!outcomeRecordFailures.has(e)) throw unrecorded(e);
8412
+ 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)`); }
8413
+ // `target` is a tmux session's: null here, so a reader of a start's answer finds every key it knows.
8414
+ return { ...answerBase(), harness: next.harness, backend, model: plan.model ?? null, launchConfig: recipe.launchConfig ?? null, yolo: next.yolo ?? null, target: null, session: { provider, endpoint: answered.endpoint }, startedAt, restartCount: next.restartCount, reused: "new", warnings: [...cleanupWarnings, ...warnings], ...(stop ? { stop } : {}) };
8415
+ }
8416
+ /** `session start --resume` of a home on a session provider, and what the machine sweep runs for it
8417
+ * (lib/session-resume.mjs): the session continues in its own conversation, through the provider's
8418
+ * input; nothing is launched. Two homes are resumed, and no other:
8419
+ * - one **stopped with the host** (`stoppedAt`, and the stop receipt says `oats host run`'s
8420
+ * shutdown wrote it): the notice is sent, then the stop cleared, then its receipt removed
8421
+ * (died between, the home is still to resume, or running). Not counted: the host's shutdown
8422
+ * is no crash.
8423
+ * - one whose session is **lost** (gone, and OATS did not stop it; a provider reads a session in
8424
+ * error so): the kernel's resume primitive first (resumeLostSession: no process of the last run
8425
+ * in the home, then the count against the home's cap), then the notice.
8426
+ * The notice is input: a claim that holds a scheduled wake holds it too (a permission prompt, a
8427
+ * question: E_SESSION_PROMPT_OPEN, nothing sent), and the provider's refusals are its refusals
8428
+ * (E_SESSION_PROMPT_OPEN, E_SESSION_INPUT_QUEUED: a queued notice is no resume). A notice that
8429
+ * was not sent leaves the home as it was (still stopped with the host; the count taken back), so
8430
+ * a later sweep tries again. A notice whose call failed keeps its count: it may have been sent,
8431
+ * and a home stopped with the host, which stays so, has the provider asked to stop it again.
8432
+ * Anything else was not lost: a home an operator stopped (E_RESUME_NOT_LOST: an ordinary start
8433
+ * opens a fresh conversation), a session that runs (E_SESSION_RUNNING) or is there
8434
+ * (E_RESUME_NOT_LOST), one that cannot be inspected (E_SESSION_UNKNOWN). */
8435
+ function resumeProviderSession(realHome, o, { session, meta, backend, provider, drift, cleanupWarnings }) {
8436
+ const name = meta.instance || basename(realHome);
8437
+ 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)`);
8438
+ if (!session) throw notLost("it was never launched");
8439
+ const owed = owedRetire(realHome);
8440
+ if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(name, owed.state)}; nothing was started`);
8441
+ const hostStopped = session.stoppedAt !== null && lostReasonOf(realHome, meta) === HOST_STOP_REASON;
8442
+ if (session.stoppedAt !== null && !hostStopped) throw notLost("it stopped");
8443
+ const found = homeSessionProvider(realHome, meta, provider, backend);
8444
+ if (found.problem) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${name} is running, so nothing was started: ${found.problem}`);
8445
+ if (!hostStopped) {
8446
+ const inspected = inspectProviderSession(found.binding, session.endpoint, { io: o.io });
8447
+ if (inspected.unavailable) throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${name} is running, so nothing was started: ${inspected.unavailable}`);
8448
+ if (inspected.observed.present) {
8449
+ if (inspected.observed.running === true) throw oatsError("E_SESSION_RUNNING", `${name} is running (${inspected.observed.state}); nothing was started`);
8450
+ throw notLost("its session is there");
8451
+ }
8452
+ }
8453
+ // The notice holds on claims, as a scheduled wake does: it must not answer a dialog.
8454
+ let held;
8455
+ try { held = waitingHold(realHome); } catch { held = { claimReason: null, unreadable: "the claims could not be read" }; }
8456
+ 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`);
8457
+ const counted = hostStopped ? null : resumeLostSession(realHome, name);
8458
+ // A home stopped with the host stays recorded as stopped until its notice has been sent: the
8459
+ // notice first, then `stoppedAt` cleared, then the stop receipt removed. Died after the notice,
8460
+ // the home is still stopped with the host, and its session may run again: the next sweep sends
8461
+ // the notice once more, and a stop or a start asks the provider to stop it, as of any stopped home.
8462
+ // (A stop a killed kernel left behind, the host's own included, would run late and stop the
8463
+ // session this resumes: it is ended first.)
8464
+ const orphaned = endProviderCalls(realHome);
8465
+ if (orphaned) { counted?.undo(); throw oatsError("E_SESSION_INPUT_FAILED", `${name} was not resumed: ${orphaned}; nothing was sent`); }
8466
+ const notice = markProviderCall(realHome, "input");
8467
+ try { inputProviderSession(found.binding, session.endpoint, PROVIDER_RESUME_NOTICE, { io: o.io, groupFile: notice.groupFile }); }
8468
+ catch (e) {
8469
+ notice.done();
8470
+ // The provider refused the notice: nothing was sent, so the count is taken back. A call that
8471
+ // failed may have restarted the session: it stays counted, and a home stopped with the host,
8472
+ // which stays stopped and still to resume, has it asked to stop again (a stopped home has
8473
+ // no session).
8474
+ if (inputWasRefused(e)) counted?.undo();
8475
+ else if (hostStopped) providerStopUnconfirmed(realHome, meta, session, session.endpoint, 20000, o.io);
8476
+ throw e;
8477
+ }
8478
+ notice.done();
8479
+ dieAt("resume:notice-sent");
8480
+ if (hostStopped) {
8481
+ writeProviderRuntime(realHome, { backend, provider, endpoint: session.endpoint });
8482
+ dieAt("resume:stop-cleared");
8483
+ // The stop is over: its receipt goes, so that a later loss of this same start is not read as
8484
+ // another stop with the host.
8485
+ rmSync(join(realHome, STOP_RECEIPT_FILE), { force: true });
8486
+ }
8487
+ 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 } };
8488
+ }
7562
8489
  /** What a start, holding the home's lifecycle claim (startClaimed), refuses at `lock`, the home's
7563
8490
  * `.oats-start.lock`. Two starts exclude each other through that claim, and a start makes
7564
8491
  * nothing at this path. An upgrade writes its regular file there and keeps it until its final
@@ -9559,7 +10486,7 @@ const claimCommand = (action) => action === "resume" ? "oats session start --res
9559
10486
  /** What each verb that meets a held claim says it did not do: the words its refusals end with,
9560
10487
  * before any effect. After a takeover ended a dead holder's step, every verb says the same
9561
10488
  * (lib/errors.mjs nothingAfter). */
9562
- const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", resume: "nothing was started", start: "nothing was started", "worktree add": "no tree was made", "instance color": "the colour was not changed", "instance same-work": "the flag was not changed", "instance background": "the background was not changed", "instance pin": "the pin was not changed" };
10489
+ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", resume: "nothing was started", start: "nothing was started", "worktree add": "no tree was made", "instance color": "the colour was not changed", "instance related-work": "the flag was not changed", "instance background": "the background was not changed", "instance pin": "the pin was not changed" };
9563
10490
 
9564
10491
  /** The refusals of `arriving` ("retire", "stop", "upgrade", "resume", "start", or "worktree add", which
9565
10492
  * reads the claim and does not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
@@ -10081,7 +11008,7 @@ function retireSteps(root, name, o, found, at) {
10081
11008
  }
10082
11009
  }
10083
11010
  if (runtimeAuthority) {
10084
- const metaAgrees = launchStateAgrees(meta, runtimeAuthority) && (!runtimeAuthority.launched || tmuxEndpointAgrees(meta, runtimeAuthority));
11011
+ const metaAgrees = launchStateAgrees(meta, runtimeAuthority) && endpointAgrees(meta, runtimeAuthority);
10085
11012
  if (!metaAgrees) {
10086
11013
  throw authorityMismatch(`cannot quiesce ${name}: mutable instance metadata disagrees with independent runtime endpoint authority`, meta, runtimeAuthority);
10087
11014
  }
@@ -10117,7 +11044,79 @@ function retireSteps(root, name, o, found, at) {
10117
11044
  // `=` forces exact matching: tmux targets otherwise PREFIX-match window names.
10118
11045
  // A no-launch instance is already quiesced. A launched one must have exact
10119
11046
  // window absence established before recovery copying begins.
10120
- if (!self && runtimeAuthority?.launched) {
11047
+ // What the retire says of a session provider's session it could not stop through the provider.
11048
+ let providerStopWarning = null;
11049
+ // What it says of an input that outlasted its wait (waitForInputsInFlight).
11050
+ let inputInFlightWarning = null;
11051
+ // A launch that was sent to the home's provider and never recorded (launchSentOf): the provider
11052
+ // stops whatever it started first, for a home that was never launched as for a launched one.
11053
+ const sentLaunch = !self ? [runtimeAuthority?.session, runtimeAuthority?.planned].find((recorded) => recorded?.launchSent) ?? null : null;
11054
+ if (sentLaunch && !runtimeAuthority?.session) {
11055
+ const unsettledLaunch = settleSentLaunch(found.home, meta, sentLaunch);
11056
+ // Never launched by any record, and a session may run: the provider's stop, then no process
11057
+ // may work in the home, as below.
11058
+ const { backend, provider } = sentLaunch;
11059
+ at.sessionTouched = true;
11060
+ ownSession = "unverified";
11061
+ 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}`);
11062
+ const scan = processesInHome(found.home);
11063
+ if (!scan.ok) throw unquiet(`and whether a process still works in its home could not be established (${scan.error})`);
11064
+ 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`);
11065
+ 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`;
11066
+ ownSession = "stopped";
11067
+ }
11068
+ if (!self && runtimeAuthority?.session) {
11069
+ // A home on a session provider: `stoppedAt` first, so that from here its session reads stopped
11070
+ // and input to it is refused; then the provider's stop; then no process may work in the home,
11071
+ // whatever the provider answered: a stop it confirms can still leave one (a harness that
11072
+ // outlives its server), and OATS sees no window whose absence would say otherwise. Stricter
11073
+ // than a tmux home's retire, which takes its window's absence: a shell left in the home counts,
11074
+ // the operator's own included, and the refusal says so.
11075
+ // A stop that cannot be confirmed (the provider fails, or its capability is no longer among
11076
+ // the home's modules) does not strand the home: the retire goes on when no process works in
11077
+ // the home, and says that the provider's session was not stopped through it.
11078
+ const { backend, provider, endpoint, stoppedAt } = runtimeAuthority.session;
11079
+ at.sessionTouched = true;
11080
+ ownSession = "unverified";
11081
+ // The recorded session by the stop rule (stopProviderSessionRecorded: `stoppedAt`, the stop
11082
+ // receipt, then the provider); a home already stopped has the provider asked again, and its
11083
+ // stop becomes the operator's. Then the inputs that were in flight when `stoppedAt` was
11084
+ // recorded (a new one is refused from then on): the provider restarts a session on an input,
11085
+ // and once the home is removed no input can ask it to stop again, so the retire waits for
11086
+ // them, a bounded time, and asks once more. Then a launch that was sent and never recorded.
11087
+ let recordedStop;
11088
+ const outlasted = [];
11089
+ if (stoppedAt === null) {
11090
+ try { recordedStop = stopProviderSessionRecorded(found.home, meta, runtimeAuthority.session, { outlasted }).unconfirmed; }
11091
+ catch (e) {
11092
+ // The fence could not be written. Without it an input is still admitted, and one that
11093
+ // acts after the provider's stop restarts a session under a home that is then removed: the
11094
+ // provider is not asked, and nothing is retired. (A home whose launch is marked as sent has
11095
+ // that mark for a fence: its stop goes on, below.)
11096
+ 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`);
11097
+ }
11098
+ } else {
11099
+ try { recordStop(found.home, null); } catch { /* as above */ }
11100
+ }
11101
+ if (recordedStop === undefined) recordedStop = providerStopUnconfirmed(found.home, meta, runtimeAuthority.session, runtimeAuthority.session.endpoint, 20000, undefined, null, { outlasted });
11102
+ 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`;
11103
+ // The launch that was sent is settled only once the recorded session is confirmed stopped.
11104
+ // One that is not: the provider is asked to stop what that launch started all the same (the home
11105
+ // is about to be removed), and nothing is recorded of it.
11106
+ const sentStop = !sentLaunch ? null : recordedStop
11107
+ ? providerStopUnconfirmed(found.home, meta, sentLaunch, null, 20000, undefined, sentLaunch.launchSent)
11108
+ : settleSentLaunch(found.home, meta, sentLaunch, 20000, undefined, { recordedStopped: true });
11109
+ const unconfirmed = [recordedStop, sentStop].filter(Boolean).join("; ") || null;
11110
+ 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}`);
11111
+ const scan = processesInHome(found.home);
11112
+ if (!scan.ok) throw unquiet(`and whether a process still works in its home could not be established (${scan.error})`);
11113
+ 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`);
11114
+ if (unconfirmed) {
11115
+ 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`;
11116
+ }
11117
+ ownSession = "stopped";
11118
+ }
11119
+ if (!self && runtimeAuthority?.tmux) {
10121
11120
  const runtimeSession = runtimeAuthority.tmux.session;
10122
11121
  const runtimeWindow = runtimeAuthority.tmux.window;
10123
11122
  const runtimeSocket = runtimeAuthority.tmux.socket;
@@ -10754,7 +11753,7 @@ function retireSteps(root, name, o, found, at) {
10754
11753
  }
10755
11754
 
10756
11755
  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: (() => {
10757
- const w = [...spawnGroupWarnings, ...(hookResults?.warnings || []), ...relinkWarnings];
11756
+ const w = [...spawnGroupWarnings, ...(providerStopWarning ? [providerStopWarning] : []), ...(inputInFlightWarning ? [inputInFlightWarning] : []), ...(hookResults?.warnings || []), ...relinkWarnings];
10758
11757
  // What the retire read from Git about work/ where the record did not say it (#962).
10759
11758
  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`);
10760
11759
  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`);
@@ -10791,7 +11790,14 @@ function retireSteps(root, name, o, found, at) {
10791
11790
  // The home `--keep-dir` keeps reads `stopped` once its window is gone, never `lost` (recordStop,
10792
11791
  // as above). A record that cannot be written stops nothing: the home then reads lost, as before.
10793
11792
  if (o.keepDir) { try { recordStop(found.home, null); } catch { /* see above */ } }
10794
- if (typeof killSocket === "string" && killSocket) {
11793
+ if (runtimeAuthority?.session) {
11794
+ // A session provider's session has no window to kill: it is stopped as any OATS stop does
11795
+ // (stopProviderHome), by a detached process, after the caller's last words.
11796
+ try {
11797
+ 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) });
11798
+ child.unref();
11799
+ } catch { /* the home keeps its session: \`oats instance stop\` ends it */ }
11800
+ } else if (typeof killSocket === "string" && killSocket) {
10795
11801
  const kill = `sleep ${o.selfKillDelaySec ?? 8}; tmux -u -S ${shq(killSocket)} kill-window -t ${killTarget} 2>/dev/null || true`;
10796
11802
  shTry(`tmux -u -S ${shq(killSocket)} run-shell -b ${shq(kill.replace(/#/g, "##"))}`);
10797
11803
  } else shTry(`tmux run-shell -b 'sleep ${o.selfKillDelaySec ?? 8}; tmux kill-window -t ${killTarget} 2>/dev/null || true'`);