@awebai/oats 0.69.12 → 0.69.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +216 -178
- package/bin/oats.mjs +176 -184
- package/docs/capabilities.md +4 -1
- package/docs/configuration.md +63 -5
- package/docs/container.md +246 -0
- package/docs/design/2026-09-23-workspace-module-contracts.md +2 -0
- package/docs/desktop-cli-api.md +376 -37
- package/docs/desktop-instance-start.md +4 -1
- package/docs/desktop.md +58 -12
- package/docs/execution-targets.md +69 -6
- package/docs/implementation.md +86 -29
- package/docs/integrations.md +3 -2
- package/docs/knowledge-and-learning.md +72 -0
- package/docs/oats-local.schema.json +11 -2
- package/docs/official-catalog.md +39 -5
- package/docs/packages.md +93 -14
- package/docs/release-lane.md +2 -1
- package/docs/release-notes/v0.69.13.md +767 -0
- package/docs/release-notes/v0.69.14.md +83 -0
- package/docs/schedules.md +26 -3
- package/docs/servers.md +181 -5
- package/docs/souls-and-instances.md +140 -11
- package/docs/tui.md +1 -1
- package/docs/upgrading.md +24 -5
- package/docs/workspaces.md +31 -5
- package/lib/claim.mjs +21 -5
- package/lib/command-flags.mjs +238 -0
- package/lib/core.mjs +791 -563
- package/lib/deployments.mjs +4 -3
- package/lib/dir-lock.mjs +126 -31
- package/lib/errors.mjs +1 -1
- package/lib/harness-token.mjs +110 -0
- package/lib/hot-reads.mjs +4 -3
- package/lib/instance-events.mjs +28 -6
- package/lib/instance-git.mjs +138 -13
- package/lib/instance-inspect.mjs +6 -1
- package/lib/instance-listing.mjs +80 -38
- package/lib/instance-resolution.mjs +56 -3
- package/lib/instance-upgrade.mjs +16 -20
- package/lib/launch-env-exec.sh +7 -0
- package/lib/launch-env.mjs +74 -0
- package/lib/launch-preference.mjs +19 -12
- package/lib/member-clone.mjs +7 -1
- package/lib/packages.mjs +74 -2
- package/lib/read-call.mjs +3 -0
- package/lib/reader.mjs +3 -2
- package/lib/refused-text.mjs +3 -2
- package/lib/remote.mjs +119 -27
- package/lib/retained-after-retire.mjs +2 -7
- package/lib/retire-git-forms.mjs +41 -0
- package/lib/retire-incomplete.mjs +96 -0
- package/lib/schedule.mjs +2 -1
- package/lib/servers.mjs +78 -23
- package/lib/session-resume.mjs +68 -53
- package/lib/session-seen.mjs +54 -5
- package/lib/start-env.mjs +13 -7
- package/lib/system-tools.mjs +1 -1
- package/lib/teams.mjs +11 -4
- package/lib/upgrade-state.mjs +13 -2
- package/lib/worktree.mjs +56 -7
- package/package-catalog.json +1 -1
- package/package.json +2 -1
- package/packages/client/instance-lifecycle.mjs +1 -1
- package/packages/client/lifecycle-contract.mjs +3 -1
- package/packages/client/session-resume-cli.mjs +2 -1
- package/packages/client/session-start.mjs +10 -7
- package/packages/client/workspace-cli.mjs +5 -1
- package/share/oats-login-receive +204 -0
- package/skills/oats-getting-started/SKILL.md +92 -25
- package/lib/tmux-config.mjs +0 -35
package/lib/core.mjs
CHANGED
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
* work (worktree|checkout|attached|workspace|directory), harness (pi|claude|codex), model (pi model pattern, optional)
|
|
28
28
|
* (attached as soul default is for service agents — spawn must supply workDir)
|
|
29
29
|
*/
|
|
30
|
+
import { isLaunchEnvReference, referenceSource, referenceValue, fileReferenceRemedy, launchEnvHandoff, LAUNCH_ENV_HANDOFF } from "./launch-env.mjs";
|
|
30
31
|
import { canonicalHomePath, realPathOrNearest } from "./real-path.mjs";
|
|
31
32
|
import { createLaunchPromptController, neverSettled } from "./launch-prompts.mjs";
|
|
32
33
|
import { retainLaunchPromptFrame } from "./launch-prompt-evidence.mjs";
|
|
@@ -43,16 +44,17 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
43
44
|
import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
|
|
44
45
|
import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
|
|
45
46
|
import { noteRuntimeName } from "./deprecation.mjs";
|
|
47
|
+
import { RETIRE_DELETE_BRANCH_REFUSED } from "./command-flags.mjs";
|
|
46
48
|
import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
|
|
47
49
|
import { AGENT_PANE_OPTION, inspectSessionTarget, inputSessionTarget, resolveAgentPane } from "./session-input.mjs";
|
|
48
|
-
import { appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
|
|
50
|
+
import { RETIRE_HOOK_WARNING_KIND, appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
|
|
49
51
|
import { killGroup } from "./process-group.mjs";
|
|
50
52
|
import { NAMING_CALLS, NAMING_TIMEOUT_MS, suggestInstanceName } from "./instance-naming.mjs";
|
|
51
53
|
import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
|
|
52
54
|
import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
|
|
53
55
|
import { captureLoginEnvironment } from "./login-environment.mjs";
|
|
54
56
|
import { kernelNode } from "./stable-node.mjs";
|
|
55
|
-
import { assertNoPartialUpgrade, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
|
|
57
|
+
import { assertNoPartialUpgrade, packageRespawnWarning, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
|
|
56
58
|
|
|
57
59
|
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";
|
|
58
60
|
import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
|
|
@@ -85,7 +87,8 @@ import { readPortableBytes } from "./bounded-read.mjs";
|
|
|
85
87
|
import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
|
|
86
88
|
import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
|
|
87
89
|
import { hashFile, readFilePieces, readFileUpTo } from "./file-pieces.mjs";
|
|
88
|
-
import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
|
|
90
|
+
import { assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
|
|
91
|
+
import { retireGitReadsNoWorkTreeFile, retireSubcommandAt } from "./retire-git-forms.mjs";
|
|
89
92
|
import { systemTool } from "./system-tools.mjs";
|
|
90
93
|
import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
|
|
91
94
|
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
@@ -93,7 +96,7 @@ import { readInstanceBackground, writeInstanceBackground } from "./instance-back
|
|
|
93
96
|
import { SAME_WORK_FILE, writeSameWork } from "./instance-same-work.mjs";
|
|
94
97
|
import { readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
|
|
95
98
|
import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
|
|
96
|
-
import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv,
|
|
99
|
+
import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
|
|
97
100
|
import { watchResumeConfirmation } from "./launch-prompt-resume.mjs";
|
|
98
101
|
import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
|
|
99
102
|
import { PKG_ROOT } from "./version.mjs";
|
|
@@ -348,6 +351,8 @@ export const LAUNCH_CONFIG_KEYS = new Set(["harness", "runtime", "executable", "
|
|
|
348
351
|
export const launchConfigHarness = (entry) => (Object.hasOwn(entry, "harness") ? entry.harness : entry.runtime);
|
|
349
352
|
const LAUNCH_CONFIG_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
350
353
|
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
354
|
+
const DIRECTORY_LAUNCH_ENV = new Set(["HOME", "PATH", ...Object.values(HARNESS_FOLDER_VAR), "PI_CODING_AGENT_SESSION_DIR"]);
|
|
355
|
+
const fileLocationMessage = (name) => `${name} is a directory location; give it as a literal or {fromEnv}. fromFile is for credential values.`;
|
|
351
356
|
export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
|
|
352
357
|
const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
|
|
353
358
|
export function validateLaunchConfig(name, entry, where) {
|
|
@@ -365,12 +370,13 @@ export function validateLaunchConfig(name, entry, where) {
|
|
|
365
370
|
for (const a of entry.args) if (typeof a !== "string" || a.includes("\0")) bad("args must be a list of strings");
|
|
366
371
|
}
|
|
367
372
|
if (entry.env !== undefined) {
|
|
368
|
-
if (!entry.env || typeof entry.env !== "object" || Array.isArray(entry.env)) bad("env must be a map of NAME to a string
|
|
373
|
+
if (!entry.env || typeof entry.env !== "object" || Array.isArray(entry.env)) bad("env must be a map of NAME to a string, {fromEnv: NAME}, or {fromFile: /absolute/path}");
|
|
369
374
|
for (const [n, v] of Object.entries(entry.env)) {
|
|
370
375
|
if (!ENV_NAME.test(n)) bad(`env name ${JSON.stringify(n)} is not a valid environment variable name`);
|
|
371
376
|
if (reservedLaunchEnv(n)) bad(`env ${n} is set by the kernel for every launch and cannot be overridden`);
|
|
372
377
|
if (typeof v === "string") { if (v.includes("\0")) bad(`env ${n} must be text`); continue; }
|
|
373
|
-
if (!
|
|
378
|
+
if (!isLaunchEnvReference(v)) bad(`env ${n} must be a string or {fromEnv: NAME} or {fromFile: /absolute/path}`);
|
|
379
|
+
if (v.fromFile !== undefined && DIRECTORY_LAUNCH_ENV.has(n)) bad(fileLocationMessage(n));
|
|
374
380
|
if (v && typeof v === "object" && v.fromEnv && v.fromEnv.startsWith(LAUNCH_REF_PREFIX)) bad(`env ${n} may not reference a ${LAUNCH_REF_PREFIX}* alias`);
|
|
375
381
|
}
|
|
376
382
|
}
|
|
@@ -2206,9 +2212,10 @@ export function launchEnvironment({ configEnv, configName, capabilities, removed
|
|
|
2206
2212
|
const of = (name) => {
|
|
2207
2213
|
const own = Object.hasOwn(configEnv || {}, name) ? configEnv[name] : undefined;
|
|
2208
2214
|
if (typeof own === "string") return selector(name, { value: own, source: `the ${name} of launch configuration ${configName}` });
|
|
2209
|
-
if (own && typeof own === "object" && own.fromEnv) {
|
|
2210
|
-
const
|
|
2211
|
-
|
|
2215
|
+
if (own && typeof own === "object" && (own.fromEnv || own.fromFile)) {
|
|
2216
|
+
const sourceName = referenceSource(own), value = referenceValue(own, env);
|
|
2217
|
+
const source = `the ${name} of launch configuration ${configName} (from ${sourceName})`;
|
|
2218
|
+
return value === undefined ? { source, problem: `${name} references ${sourceName}, not set on this host`, unresolved: true } : selector(name, { value, source });
|
|
2212
2219
|
}
|
|
2213
2220
|
if (capabilities?.env && Object.hasOwn(capabilities.env, name) && typeof capabilities.env[name] === "string") return selector(name, { value: capabilities.env[name], source: `the ${name} that ${capabilities.owner?.(name) || "a capability"} sets for this launch` });
|
|
2214
2221
|
// A selector the launch removes (a manifest may declare one under a namespace it names); PATH
|
|
@@ -2376,8 +2383,9 @@ function oatsTmuxWindows(session) {
|
|
|
2376
2383
|
/** The harness's window command: no COLORFGBG in the pane, none of the names only a hook is handed,
|
|
2377
2384
|
* and none of the names the launch removes (`removed`: removedLaunchEnv, each a portable name),
|
|
2378
2385
|
* whatever the server's global or the session's environment holds; the command's own prefix then sets what the launch sets. tmux runs
|
|
2379
|
-
* the command with
|
|
2380
|
-
*
|
|
2386
|
+
* the window command with its `default-shell -c`. A reference handoff then runs this pane
|
|
2387
|
+
* wrapper through /bin/sh; nativeRecordCommand already executes parsed harness argv through
|
|
2388
|
+
* /bin/sh for every launch. The fallback shell it execs inherits the result. Never persisted: the
|
|
2381
2389
|
* recorded command (meta.command) is the launch command alone. */
|
|
2382
2390
|
/** A launch's command followed by its exit marker (lib/session-end.mjs): the start id and the harness's
|
|
2383
2391
|
* exit status, written when the harness ends, by spawn's window and start's alike. */
|
|
@@ -2686,9 +2694,24 @@ export function checkLaunchExecutable(path) {
|
|
|
2686
2694
|
return null;
|
|
2687
2695
|
} catch (e) { return `${path} ${e.code === "ENOENT" ? "does not exist" : e.code === "EACCES" ? "is not executable" : e.message}`; }
|
|
2688
2696
|
}
|
|
2689
|
-
/** Source names of
|
|
2697
|
+
/** Source names of host references that cannot be resolved. Status recipes redact literals
|
|
2698
|
+
* as objects too; only reference-shaped entries have a source to resolve. */
|
|
2690
2699
|
export function missingLaunchEnvRefs(configEnv, env = process.env) {
|
|
2691
|
-
return Object.values(configEnv || {}).filter((v) => v &&
|
|
2700
|
+
return Object.values(configEnv || {}).filter((v) => isLaunchEnvReference(v) && referenceValue(v, env) === undefined).map(referenceSource).sort();
|
|
2701
|
+
}
|
|
2702
|
+
/** A /login credential belongs to the person's account. Only an OATS-set token selects
|
|
2703
|
+
* the token route: inherited pane values cannot make that decision for the operator. */
|
|
2704
|
+
function claudeLoginCredential({ harness, launch, configEnv = {}, hooksEnv = {} }) {
|
|
2705
|
+
if (harness !== "claude") return null;
|
|
2706
|
+
const selected = launch.of("CLAUDE_CONFIG_DIR");
|
|
2707
|
+
if (selected.problem || selected.unresolved) return null;
|
|
2708
|
+
const ownHome = selected.value ? null : launch.of("HOME");
|
|
2709
|
+
const dir = selected.value || (ownHome?.value ? join(ownHome.value, ".claude") : null);
|
|
2710
|
+
if (!dir || !existsSync(join(dir, ".credentials.json"))) return null;
|
|
2711
|
+
const token = Object.hasOwn(configEnv, "CLAUDE_CODE_OAUTH_TOKEN") || Object.hasOwn(hooksEnv, "CLAUDE_CODE_OAUTH_TOKEN");
|
|
2712
|
+
return token
|
|
2713
|
+
? { code: "E_CLAUDE_LOGIN_CREDENTIAL", message: `Claude has a /login credential at ${join(dir, ".credentials.json")} alongside the token OATS sets. Remove that /login credential before starting. Use oats harness token set claude to provision an inference-only token.` }
|
|
2714
|
+
: null;
|
|
2692
2715
|
}
|
|
2693
2716
|
/** The selection a start makes: which configuration (explicit name, "none",
|
|
2694
2717
|
* a frozen recipe's, or the soul's default), and from it the harness and
|
|
@@ -2837,10 +2860,16 @@ export function launchReportFor({ layers, launchConfigs = {}, contextDir }) {
|
|
|
2837
2860
|
* name: the command says NAME="$OATS_LAUNCH_REF_NAME", so no source
|
|
2838
2861
|
* variable is ever named in the command and no assignment in the same
|
|
2839
2862
|
* prefix can shadow it (zsh evaluates a prefix's assignments in order).
|
|
2840
|
-
* Each goes to the pane
|
|
2863
|
+
* Each goes to the pane through a private per-start handoff file. */
|
|
2841
2864
|
export function launchEnvRefs(recipe, env = process.env) {
|
|
2842
|
-
const out = [];
|
|
2843
|
-
for (const [name, v] of Object.entries(recipe.env || {})) if (v
|
|
2865
|
+
const out = [], values = new Map();
|
|
2866
|
+
for (const [name, v] of Object.entries(recipe.env || {})) if (isLaunchEnvReference(v)) {
|
|
2867
|
+
const source = referenceSource(v);
|
|
2868
|
+
if (!values.has(source)) values.set(source, referenceValue(v, env));
|
|
2869
|
+
const value = values.get(source);
|
|
2870
|
+
if (value === undefined) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage([referenceSource(v)], recipe.harness));
|
|
2871
|
+
out.push({ name: `${LAUNCH_REF_PREFIX}${name}`, value, target: name, source: referenceSource(v) });
|
|
2872
|
+
}
|
|
2844
2873
|
return out;
|
|
2845
2874
|
}
|
|
2846
2875
|
|
|
@@ -3050,7 +3079,7 @@ function nativeRecordCommand(command, home, harness, { start, scope } = {}) {
|
|
|
3050
3079
|
/** The agent's scope of the launch of `command` in a pane with `pane`'s environment (paneEnvironment)
|
|
3051
3080
|
* → agentScope's answer. The values the probe gets for SCOPE_ENV_NAMES are the ones systemd-run
|
|
3052
3081
|
* will run with: what the command's environment prefix sets (a literal, or a reference whose source
|
|
3053
|
-
* is one of `refs`, the
|
|
3082
|
+
* is one of `refs`, the private handoff's values, else the pane's own), else nothing for a name the launch
|
|
3054
3083
|
* removes (paneCommand's `unset`), else the pane's. `io` is a test's (agentScope). */
|
|
3055
3084
|
function agentScopeOn(command, { pane, removed = [], refs = [] }, io) {
|
|
3056
3085
|
return agentScope({ io, paneEnv: () => {
|
|
@@ -3086,7 +3115,10 @@ export function assertLaunchRecipe(recipe, what) {
|
|
|
3086
3115
|
if (typeof recipe.executable !== "string" || !recipe.executable) bad("no executable");
|
|
3087
3116
|
if (!Array.isArray(recipe.args) || recipe.args.some((a) => typeof a !== "string")) bad("args are not a list of strings");
|
|
3088
3117
|
if (!recipe.env || typeof recipe.env !== "object" || Array.isArray(recipe.env)) bad("env is not a map");
|
|
3089
|
-
for (const [n, v] of Object.entries(recipe.env))
|
|
3118
|
+
for (const [n, v] of Object.entries(recipe.env)) {
|
|
3119
|
+
if (!(typeof v === "string" || isLaunchEnvReference(v))) bad(`env ${n} is neither a string nor a reference`);
|
|
3120
|
+
if (v?.fromFile !== undefined && DIRECTORY_LAUNCH_ENV.has(n)) bad(fileLocationMessage(n));
|
|
3121
|
+
}
|
|
3090
3122
|
if (recipe.model !== null && recipe.model !== undefined && typeof recipe.model !== "string") bad("model is not text");
|
|
3091
3123
|
if (recipe.yolo !== undefined && typeof recipe.yolo !== "boolean") bad("yolo is not a boolean");
|
|
3092
3124
|
if (!recipe.hooks || typeof recipe.hooks !== "object") bad("no hooks record");
|
|
@@ -3203,8 +3235,10 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
|
|
|
3203
3235
|
fail("environment", "E_LAUNCH_ENV_CONFLICT", `${owned.map((n) => `${n} (set by ${owner(n)})`).join(", ")} cannot be overridden by launch configuration ${config?.name}; change the capability's setting instead`);
|
|
3204
3236
|
}
|
|
3205
3237
|
const missing = missingLaunchEnvRefs(configEnv, env);
|
|
3206
|
-
if (missing.length) fail("environment", "E_LAUNCH_ENV_MISSING", `launch configuration ${config?.name} references ${missing.join(", ")}, not set on this host; nothing was stopped or started`);
|
|
3238
|
+
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)}`);
|
|
3207
3239
|
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` });
|
|
3240
|
+
const login = claudeLoginCredential({ harness, configEnv, hooksEnv: hooks.env, launch: launchEnvironment({ configEnv, capabilities: { env: hooks.env }, removed: removedEnv, env, pane: launchEnv.pane, cwd: home }) });
|
|
3241
|
+
if (login?.code) fail("credentials", login.code, login.message);
|
|
3208
3242
|
problems.push({ check: "model", ok: true, detail: model ? `${model} (${modelSource})` : `native default (${modelSource})` });
|
|
3209
3243
|
// Harness package requirements: the captured providers' (bindings united
|
|
3210
3244
|
// with contributions, by id, current manifest, captured settings for
|
|
@@ -3285,7 +3319,7 @@ export function launchEffectiveEnv({ base = process.env, hooksEnv = {}, configEn
|
|
|
3285
3319
|
Object.assign(out, hooksEnv);
|
|
3286
3320
|
for (const [name, v] of Object.entries(configEnv || {})) {
|
|
3287
3321
|
if (typeof v === "string") out[name] = v;
|
|
3288
|
-
else if (v && typeof v === "object"
|
|
3322
|
+
else if (v && typeof v === "object") { const value = referenceValue(v, base); if (value !== undefined) out[name] = value; }
|
|
3289
3323
|
}
|
|
3290
3324
|
for (const name of PANE_ENV_NAMES) {
|
|
3291
3325
|
const answer = launch.of(name);
|
|
@@ -3924,7 +3958,12 @@ function* spawnBody(root, agent, o = {}) {
|
|
|
3924
3958
|
{ const bad = checkLaunchExecutable(executable.path); if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${launchConfig?.name || "(harness default)"}: ${bad}`); }
|
|
3925
3959
|
const bin = executable.path;
|
|
3926
3960
|
const missingRefs = missingLaunchEnvRefs(launchConfig?.env || {}, process.env);
|
|
3927
|
-
if (missingRefs.length) throw oatsError("E_LAUNCH_ENV_MISSING", `launch configuration ${launchConfig.name} references ${missingRefs.join(", ")}, not set in this environment; nothing was created`);
|
|
3961
|
+
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)}`);
|
|
3962
|
+
const preflightRemoved = removedLaunchEnv({ declared: declaredLaunchEnv(resolvedCfg.capabilities), configEnv: launchConfig?.env });
|
|
3963
|
+
// A hook-owned selector has no value until hooks run; its final check remains below.
|
|
3964
|
+
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));
|
|
3965
|
+
const loginPreflight = selectorPending ? null : claudeLoginCredential({ harness, configEnv: launchConfig?.env, launch: launchEnvOn(expectedEnv.pane, preflightRemoved) });
|
|
3966
|
+
if (loginPreflight?.code) throw oatsError(loginPreflight.code, loginPreflight.message);
|
|
3928
3967
|
// A configuration's executable answers the package probe (without one the
|
|
3929
3968
|
// context-selected name does, as before: its remedies name that command),
|
|
3930
3969
|
// under the environment the launch will have (launchEffectiveEnv: the
|
|
@@ -4860,6 +4899,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
|
|
|
4860
4899
|
// with whatever environment (a race lost to another creator, a session that overrides a name):
|
|
4861
4900
|
// one read of it answers the three checks below, each of which reads it only when it has to.
|
|
4862
4901
|
const pane = paneEnvironment(socket, session, undefined, home);
|
|
4902
|
+
const login = claudeLoginCredential({ harness, configEnv: recipe.env, hooksEnv: hookRes.env, launch: launchEnvironment({ configEnv: recipe.env, capabilities: { env: hookRes.env }, removed: removedEnv, env: process.env, pane, cwd: home }) });
|
|
4903
|
+
if (login?.code) throw oatsError(login.code, login.message);
|
|
4863
4904
|
const actualEnv = launchEnvOn(pane, removedEnv);
|
|
4864
4905
|
// The harness looked up again on that PATH. Not there: refused, and the spawn is compensated.
|
|
4865
4906
|
// Found elsewhere than the preflight found it: the launch runs that one.
|
|
@@ -4920,16 +4961,16 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
|
|
|
4920
4961
|
writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: true, tmux: meta.tmux });
|
|
4921
4962
|
clearSpawnInProgressMarker();
|
|
4922
4963
|
// The first start's launch environment (lib/start-env.mjs), after the baseline, as a start records its own.
|
|
4923
|
-
|
|
4964
|
+
const refs = launchEnvRefs(recipe, process.env);
|
|
4965
|
+
recordStartEnv(home, promptStartId, refs.map((r) => r.source), Object.fromEntries(refs.map((r) => [r.source, r.value])));
|
|
4924
4966
|
// Wrap the command so the window drops into an interactive shell when the
|
|
4925
4967
|
// agent exits (e.g. Ctrl-C) instead of tmux killing the window.
|
|
4926
|
-
const refs = launchEnvRefs(recipe, process.env);
|
|
4927
4968
|
// On the same pane, for the command it runs: whether the harness runs in a scope of its own.
|
|
4928
4969
|
const scope = agentScopeOn(cmdline, { pane, removed: removedEnv, refs });
|
|
4929
4970
|
if (scope.warning) spawnWarnings.push(unscoped = scope.warning);
|
|
4930
4971
|
// The exit marker records how this launch's harness ended (lib/session-end.mjs), as a start's does.
|
|
4931
4972
|
const windowCmd = paneCommand(exitMarked(nativeRecordCommand(cmdline, home, harness, { start: nativeStart, scope: scope.wrapper }), promptStartId, join(home, START_EXITED_FILE)), removedEnv);
|
|
4932
|
-
|
|
4973
|
+
|
|
4933
4974
|
const launchFailed = (step, refused, e) => oatsError("E_SPAWN_LAUNCH_FAILED", `tmux ${step} failed for ${instance} (${e.code === "ENOENT" ? "tmux unavailable" : refused}); the command line and tmux's output are withheld from this message because they can carry reference values; run tmux -S ${shellWord(socket)} list-windows -t ${shellWord(session)} to inspect`);
|
|
4934
4975
|
// Only a launch that engages the confirmation needs lineage committed before
|
|
4935
4976
|
// dispatch: its uncertain input outcome retains the new process and parent
|
|
@@ -4940,8 +4981,9 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
|
|
|
4940
4981
|
promptDispatched = !!controller;
|
|
4941
4982
|
let windowId;
|
|
4942
4983
|
|
|
4943
|
-
|
|
4944
|
-
|
|
4984
|
+
const envHandoff = launchEnvHandoff(home, promptStartId, refs);
|
|
4985
|
+
try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", controller ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, envHandoff.wrap(windowCmd), ...markAgentPane(instance)], undefined, oatsWindowEnvironment()).trim(); }
|
|
4986
|
+
catch (e) { envHandoff.remove(); throw launchFailed("new-window", "the window command was refused", e); }
|
|
4945
4987
|
if (controller) { promptTarget = { ...meta.tmux, ...launchPaneTarget(socket, windowId) }; windowId = promptTarget.windowId; }
|
|
4946
4988
|
try { prepareAgentWindow(socket, windowId); }
|
|
4947
4989
|
catch (e) { throw launchFailed("set-option", "the new window's options were refused", e); }
|
|
@@ -5351,9 +5393,31 @@ const GIT_MAX_BUFFER = 512 * 1024 * 1024;
|
|
|
5351
5393
|
* attempt to every existing instance's retire. These flags leave a status as
|
|
5352
5394
|
* it was. They are the operator's own; what the retire guards against is
|
|
5353
5395
|
* configuration the retired agent could write.
|
|
5354
|
-
*
|
|
5355
|
-
*
|
|
5356
|
-
*
|
|
5396
|
+
*
|
|
5397
|
+
* Filter drivers (`filter.<name>.clean`, `.process`, `.smudge`): Git runs
|
|
5398
|
+
* one when a command reads or writes a work-tree file that carries the
|
|
5399
|
+
* `filter` attribute, and it has no switch that turns filters off. A command
|
|
5400
|
+
* that can do so (every form outside lib/retire-git-forms.mjs's:
|
|
5401
|
+
* `status`, and the `checkout` of a recovery) is preceded by one read of the
|
|
5402
|
+
* repository's own configuration, and every driver that read names is
|
|
5403
|
+
* overridden to no command (lib/instance-git.mjs filterOverrides, which
|
|
5404
|
+
* says what the read covers). A file with such an attribute is then compared
|
|
5405
|
+
* as its bytes are in the work tree: a status reads it by its recorded size
|
|
5406
|
+
* and times first, as always, and by those bytes when they differ. A driver
|
|
5407
|
+
* whose name `-c` cannot carry is not overridden: Git is not run, and the
|
|
5408
|
+
* command fails (retireGitArgv). A driver that the operator's global or
|
|
5409
|
+
* system configuration defines runs as it does for the operator's own Git:
|
|
5410
|
+
* one that only it defines is left alone, and one the repository defines
|
|
5411
|
+
* under the same name is overridden with the operator's values, so the
|
|
5412
|
+
* repository's command for it never runs.
|
|
5413
|
+
* What this does not cover:
|
|
5414
|
+
* - a driver added to the configuration between that read and the command;
|
|
5415
|
+
* - a submodule's own configuration: a status runs Git inside each populated
|
|
5416
|
+
* submodule, and the overrides name this repository's drivers, not the
|
|
5417
|
+
* submodule's;
|
|
5418
|
+
* - `clone` (cloneRecovery), which has no repository to read yet: the
|
|
5419
|
+
* recovery it makes starts with no local configuration, so its checkout
|
|
5420
|
+
* runs only what the operator's own configuration defines. */
|
|
5357
5421
|
const RETIRE_GIT_FLAGS = ["--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external="];
|
|
5358
5422
|
const RETIRE_GIT_DROPPED_ENV = new Set(["GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_DEFAULT_REF_FORMAT", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY", "GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS", "GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR"]);
|
|
5359
5423
|
function retireGitEnv(env) {
|
|
@@ -5363,16 +5427,31 @@ function retireGitEnv(env) {
|
|
|
5363
5427
|
}
|
|
5364
5428
|
return { ...out, GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1", ...env };
|
|
5365
5429
|
}
|
|
5430
|
+
/** The arguments of one retire Git command in `repo` (null for none): the
|
|
5431
|
+
* flags, the overrides of the filter drivers `repo`'s configuration defines
|
|
5432
|
+
* when the subcommand can read or write a work-tree file, `-C`, then `args`
|
|
5433
|
+
* (the subcommand, after any `-c <setting>` of its own). Throws, and Git is
|
|
5434
|
+
* not run, when the drivers cannot be read or one cannot be overridden: a
|
|
5435
|
+
* status that was not run is a status that failed, never a clean one. */
|
|
5436
|
+
function retireGitArgv(repo, args) {
|
|
5437
|
+
const filters = repo === null || retireGitReadsNoWorkTreeFile(args) ? { ok: true, args: [] } : filterOverrides(["-C", repo], { operatorEnv: retireGitEnv() });
|
|
5438
|
+
if (!filters.ok) throw new Error(`git ${args[retireSubcommandAt(args)]} was not run in ${repo}: ${filters.err}`);
|
|
5439
|
+
return [...RETIRE_GIT_FLAGS, ...filters.args, ...(repo === null ? [] : ["-C", repo]), ...args];
|
|
5440
|
+
}
|
|
5366
5441
|
/** One retire Git command in `repo` (`-C`; null for none, as for a clone) →
|
|
5367
5442
|
* its stdout (a Buffer, or text with `encoding`); throws what execFileSync
|
|
5368
|
-
* throws. */
|
|
5443
|
+
* throws, or retireGitArgv's error. */
|
|
5369
5444
|
function retireGit(repo, args, { env, input, encoding } = {}) {
|
|
5370
|
-
return execFileSync("git",
|
|
5445
|
+
return execFileSync("git", retireGitArgv(repo, args),
|
|
5371
5446
|
{ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv(env) });
|
|
5372
5447
|
}
|
|
5373
|
-
/** retireGit that never throws → spawnSync's result, for a caller that reads the exit status
|
|
5448
|
+
/** retireGit that never throws → spawnSync's result, for a caller that reads the exit status;
|
|
5449
|
+
* a command retireGitArgv did not let run reads as one that could not be started (`error`). */
|
|
5374
5450
|
function retireGitProbe(repo, args, { encoding } = {}) {
|
|
5375
|
-
|
|
5451
|
+
let argv;
|
|
5452
|
+
try { argv = retireGitArgv(repo, args); }
|
|
5453
|
+
catch (error) { return { error, status: null, signal: null, stdout: "", stderr: error.message }; }
|
|
5454
|
+
return spawnSync("git", argv, { stdio: ["ignore", "pipe", "pipe"], encoding, maxBuffer: GIT_MAX_BUFFER, shell: false, env: retireGitEnv() });
|
|
5376
5455
|
}
|
|
5377
5456
|
|
|
5378
5457
|
/** Kernel-owned receipts the kernel itself appends to a home after the spawn
|
|
@@ -5395,7 +5474,7 @@ function retireGitProbe(repo, args, { encoding } = {}) {
|
|
|
5395
5474
|
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", SAME_WORK_FILE, START_EXITED_FILE, START_ENV_FILE, START_ENV_KEY_FILE]);
|
|
5396
5475
|
// `instance.json.tmp-<pid>` is what a process killed between the two steps of writeJsonAtomic leaves
|
|
5397
5476
|
// of the record: not a hidden name, so a capability cannot declare it (disposableHomeRootProblem).
|
|
5398
|
-
const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, /^instance\.json\.tmp-\d+$/, START_ENV_TMP];
|
|
5477
|
+
const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/, /^instance\.json\.tmp-\d+$/, START_ENV_TMP, LAUNCH_ENV_HANDOFF];
|
|
5399
5478
|
/** Harness project settings in the home are configuration, not work: the
|
|
5400
5479
|
* home's `.claude/` is harness layout the kernel already shapes (the skills
|
|
5401
5480
|
* alias), and capabilities keep their own entries current in its
|
|
@@ -6885,7 +6964,7 @@ function startSession(home, o) {
|
|
|
6885
6964
|
// spawned records no modules, and there is no scope configuration left to
|
|
6886
6965
|
// re-resolve it against. Retire still works on it.
|
|
6887
6966
|
if (!isWorkspaceHome(readMeta())) throw preWorkspaceHome(realHome, "nothing was started");
|
|
6888
|
-
let drift; // Read under the
|
|
6967
|
+
let drift; // Read under the home's claim, so an upgrade cannot swap modules between reads.
|
|
6889
6968
|
let cleanupWarnings = [];
|
|
6890
6969
|
// A missing socket file is a stopped server only when no process works in this home (#624): its
|
|
6891
6970
|
// check, for a recorded session and for the OATS server lookup. A failed read of a recorded session
|
|
@@ -6942,512 +7021,533 @@ function startSession(home, o) {
|
|
|
6942
7021
|
if (clearPending) { checkRoots(); rmSync(pendingPath, { force: true }); }
|
|
6943
7022
|
return { ...(drift.length ? { drift } : {}), instance: meta.instance, agent: meta.agent, home: realHome, harness: next.harness, backend: "tmux", model: model ?? null, launchConfig: next.launch?.launchConfig ?? null, yolo: next.yolo ?? null, target, startedAt, restartCount: next.restartCount, reused, warnings: cleanupWarnings, ...(launchPrompts ? { launchPrompts } : {}), ...(nativeRecordId ? { nativeRecordId } : {}), ...(stop ? { stop } : {}) };
|
|
6944
7023
|
};
|
|
6945
|
-
|
|
6946
|
-
|
|
6947
|
-
|
|
6948
|
-
|
|
6949
|
-
|
|
6950
|
-
|
|
7024
|
+
refuseStartMutex(realHome, lock);
|
|
7025
|
+
// An upgrade holds the home's claim while it applies, and this start holds it now: what an
|
|
7026
|
+
// upgrade left is read from here on.
|
|
7027
|
+
assertNoPartialUpgrade(realHome);
|
|
7028
|
+
cleanupWarnings = upgradeCleanupWarnings(realHome);
|
|
7029
|
+
// Compare the frozen package copies with the local deployment lock; starting never moves them.
|
|
7030
|
+
const driftDeployment = dirname(dirname(dirname(dirname(realHome))));
|
|
7031
|
+
let driftLock;
|
|
7032
|
+
try { driftLock = deploymentLock(driftDeployment); }
|
|
7033
|
+
catch (error) {
|
|
7034
|
+
// Drift is advisory; an unreadable deployment lock cannot invalidate a frozen home's launch.
|
|
7035
|
+
cleanupWarnings.push(`package module drift could not be read from ${join(driftDeployment, "oats-lock.json")}: ${error.message}`);
|
|
7036
|
+
}
|
|
7037
|
+
drift = driftLock === undefined ? [] : packageUpgradeDrift(readMeta(), { lock: driftLock });
|
|
7038
|
+
// The package modules an upgrade cannot move (gone from the lock): one line naming the respawn.
|
|
7039
|
+
const respawn = driftLock === undefined ? null : packageRespawnWarning(readMeta(), { lock: driftLock });
|
|
7040
|
+
if (respawn !== null) cleanupWarnings.push(respawn);
|
|
7041
|
+
if (existsSync(join(realHome, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${realHome} is a quarantined home whose cleanup is incomplete; finish its retirement (oats retire) before starting anything there`);
|
|
7042
|
+
// A self-retirement leaves this marker while its detached teardown runs:
|
|
7043
|
+
// the home is about to disappear, so nothing is relaunched into it.
|
|
7044
|
+
if (existsSync(retirePendingMarkerPath(realHome))) throw oatsError("E_INSTANCE_RETIRING", `${basename(realHome)} is being retired (${retirePendingMarkerPath(realHome)} is present); nothing was started`);
|
|
7045
|
+
// A start that leaves the server the home recorded says so: one line per move (see the docs'
|
|
7046
|
+
// "Existing instances"), in the answer and as a launch-warning event.
|
|
7047
|
+
const movedWarnings = [];
|
|
7048
|
+
// 1. Reconcile a pending receipt before the equality gate: it may be the
|
|
7049
|
+
// only record of a session an earlier start allocated.
|
|
7050
|
+
if (existsSync(pendingPath)) {
|
|
7051
|
+
let pending;
|
|
7052
|
+
try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = undefined; }
|
|
7053
|
+
const pt = pending?.target;
|
|
7054
|
+
const validTarget = pt?.backend === "tmux" && [pt.session, pt.window, pt.socket].every((v) => typeof v === "string" && v.length > 0) && isAbsolute(pt.socket);
|
|
7055
|
+
let validCommand = false;
|
|
7056
|
+
try { parseLaunchCommand(pending?.command); validCommand = true; } catch { /* preserve invalid receipt below */ }
|
|
7057
|
+
let validLaunch = true;
|
|
7058
|
+
if (pending?.launch !== undefined) { try { assertLaunchRecipe(pending.launch, "the pending start"); } catch { validLaunch = false; } }
|
|
7059
|
+
if (pending?.harness !== undefined && !LAUNCH_HARNESSES.includes(pending.harness)) validLaunch = false;
|
|
7060
|
+
if (pending?.yolo !== undefined && typeof pending.yolo !== "boolean") validLaunch = false;
|
|
7061
|
+
const validReceipt = validTarget && validCommand && validLaunch
|
|
7062
|
+
&& typeof pending.id === "string" && /^[a-zA-Z0-9-]{1,80}$/.test(pending.id)
|
|
7063
|
+
&& (pending.model === null || (typeof pending.model === "string" && !!pending.model.trim() && !pending.model.includes("\0")))
|
|
7064
|
+
&& typeof pending.startedAt === "string" && Number.isFinite(Date.parse(pending.startedAt));
|
|
7065
|
+
if (!validReceipt) throw oatsError("E_SESSION_UNKNOWN", `an earlier start left an unreadable or invalid receipt at ${pendingPath}; inspect it before retrying; nothing was started`);
|
|
7066
|
+
let st;
|
|
7067
|
+
checkRoots();
|
|
7068
|
+
try { st = inspectSessionTarget(pending.target, o.io); }
|
|
7069
|
+
catch (e) {
|
|
7070
|
+
const lost = lostServer(e);
|
|
7071
|
+
if (lost.stopped) st = { present: false, state: "stopped" };
|
|
7072
|
+
else throw oatsError("E_SESSION_UNKNOWN", `an earlier start of ${basename(realHome)} recorded a session (tmux ${pending.target.session}:${pending.target.window} on ${pending.target.socket}) that cannot be observed now: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}; the receipt ${pendingPath} is kept and nothing was started`);
|
|
6951
7073
|
}
|
|
6952
|
-
|
|
6953
|
-
|
|
6954
|
-
|
|
6955
|
-
|
|
6956
|
-
|
|
6957
|
-
|
|
6958
|
-
|
|
6959
|
-
const
|
|
6960
|
-
|
|
6961
|
-
|
|
6962
|
-
|
|
6963
|
-
|
|
6964
|
-
|
|
6965
|
-
|
|
6966
|
-
|
|
6967
|
-
|
|
6968
|
-
|
|
6969
|
-
|
|
6970
|
-
|
|
6971
|
-
|
|
6972
|
-
|
|
6973
|
-
|
|
6974
|
-
|
|
6975
|
-
// only record of a session an earlier start allocated.
|
|
6976
|
-
if (existsSync(pendingPath)) {
|
|
6977
|
-
let pending;
|
|
6978
|
-
try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = undefined; }
|
|
6979
|
-
const pt = pending?.target;
|
|
6980
|
-
const validTarget = pt?.backend === "tmux" && [pt.session, pt.window, pt.socket].every((v) => typeof v === "string" && v.length > 0) && isAbsolute(pt.socket);
|
|
6981
|
-
let validCommand = false;
|
|
6982
|
-
try { parseLaunchCommand(pending?.command); validCommand = true; } catch { /* preserve invalid receipt below */ }
|
|
6983
|
-
let validLaunch = true;
|
|
6984
|
-
if (pending?.launch !== undefined) { try { assertLaunchRecipe(pending.launch, "the pending start"); } catch { validLaunch = false; } }
|
|
6985
|
-
if (pending?.harness !== undefined && !LAUNCH_HARNESSES.includes(pending.harness)) validLaunch = false;
|
|
6986
|
-
if (pending?.yolo !== undefined && typeof pending.yolo !== "boolean") validLaunch = false;
|
|
6987
|
-
const validReceipt = validTarget && validCommand && validLaunch
|
|
6988
|
-
&& typeof pending.id === "string" && /^[a-zA-Z0-9-]{1,80}$/.test(pending.id)
|
|
6989
|
-
&& (pending.model === null || (typeof pending.model === "string" && !!pending.model.trim() && !pending.model.includes("\0")))
|
|
6990
|
-
&& typeof pending.startedAt === "string" && Number.isFinite(Date.parse(pending.startedAt));
|
|
6991
|
-
if (!validReceipt) throw oatsError("E_SESSION_UNKNOWN", `an earlier start left an unreadable or invalid receipt at ${pendingPath}; inspect it before retrying; nothing was started`);
|
|
6992
|
-
let st;
|
|
6993
|
-
checkRoots();
|
|
6994
|
-
try { st = inspectSessionTarget(pending.target, o.io); }
|
|
6995
|
-
catch (e) {
|
|
6996
|
-
const lost = lostServer(e);
|
|
6997
|
-
if (lost.stopped) st = { present: false, state: "stopped" };
|
|
6998
|
-
else throw oatsError("E_SESSION_UNKNOWN", `an earlier start of ${basename(realHome)} recorded a session (tmux ${pending.target.session}:${pending.target.window} on ${pending.target.socket}) that cannot be observed now: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}; the receipt ${pendingPath} is kept and nothing was started`);
|
|
6999
|
-
}
|
|
7000
|
-
// A launch may still consist entirely of shells (startup files, a
|
|
7001
|
-
// shell-script harness). Only its own completion marker proves this
|
|
7002
|
-
// is a fallback shell. Never respawn an accepted launch in that gap.
|
|
7003
|
-
if (st.present && st.state === "shell") {
|
|
7004
|
-
const exited = readStartExited(realHome)?.startId === pending.id;
|
|
7005
|
-
if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
|
|
7074
|
+
// A launch may still consist entirely of shells (startup files, a
|
|
7075
|
+
// shell-script harness). Only its own completion marker proves this
|
|
7076
|
+
// is a fallback shell. Never respawn an accepted launch in that gap.
|
|
7077
|
+
if (st.present && st.state === "shell") {
|
|
7078
|
+
const exited = readStartExited(realHome)?.startId === pending.id;
|
|
7079
|
+
if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
|
|
7080
|
+
}
|
|
7081
|
+
const meta = readMeta();
|
|
7082
|
+
// A completed start (#691): its receipt names the start instance.json already records, on the
|
|
7083
|
+
// target it records. The receipt is history then, never authority: nothing of it is recorded
|
|
7084
|
+
// again, so a newer launch recipe or provider metadata stays as it is.
|
|
7085
|
+
const rt = meta.tmux;
|
|
7086
|
+
const sameTarget = rt && rt.session === pt.session && rt.window === pt.window && typeof rt.socket === "string" && !!rt.socket && resolve(rt.socket) === resolve(pt.socket);
|
|
7087
|
+
const running = st.present && st.state !== "shell";
|
|
7088
|
+
// The same start on another target is ambiguous while that other target runs; a restart once it
|
|
7089
|
+
// no longer runs is the way out (the recorded target is instance.json's, the ordinary path's).
|
|
7090
|
+
if (meta.startId === pending.id && !sameTarget && (!o.restart || running)) {
|
|
7091
|
+
throw oatsError("E_SESSION_UNKNOWN", `the start ${pending.id} of ${meta.instance} is recorded on tmux ${rt?.session ?? "?"}:${rt?.window ?? "?"} on ${rt?.socket ?? "?"} (\`oats session inspect --home ${realHome}\` shows it), but its receipt ${pendingPath} names tmux ${pt.session}:${pt.window} on ${pt.socket}; the receipt is kept and nothing was started. If that other target is not this instance's session, stop it (\`tmux -S ${shq(pt.socket)} kill-window -t ${shq(`=${pt.session}:=${pt.window}`)}\`), then run \`oats session restart --home ${realHome}\``);
|
|
7092
|
+
}
|
|
7093
|
+
if (meta.startId === pending.id) {
|
|
7094
|
+
if (running && !o.restart) {
|
|
7095
|
+
const asked = (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), meta.harness) !== meta.model) || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined || o.reselectLaunch === true;
|
|
7096
|
+
throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running; nothing was started${asked ? "; the requested model, launch configuration, harness or yolo was not applied: use session restart" : ""}`);
|
|
7006
7097
|
}
|
|
7007
|
-
|
|
7008
|
-
//
|
|
7009
|
-
//
|
|
7010
|
-
//
|
|
7011
|
-
|
|
7012
|
-
|
|
7013
|
-
|
|
7014
|
-
// The
|
|
7015
|
-
//
|
|
7016
|
-
|
|
7017
|
-
|
|
7098
|
+
// A restart, or a target that is gone or a harness that exited: the ordinary start below
|
|
7099
|
+
// reads instance.json as it is, and its own receipt replaces this one when it launches. A
|
|
7100
|
+
// start refused before that leaves this receipt as it was. The completed start recorded its
|
|
7101
|
+
// own session boundary; it is not recorded again.
|
|
7102
|
+
} else {
|
|
7103
|
+
// Reconcile even an exited target: the independent baseline may
|
|
7104
|
+
// already name it while metadata still names the old allocation.
|
|
7105
|
+
// The adopted start's session boundary, at its launch time, completed
|
|
7106
|
+
// in whichever log the interrupted start did not record it. The receipt's
|
|
7107
|
+
// recipe names its configuration (null: the bare harness); only a receipt
|
|
7108
|
+
// without a recipe falls back to the recorded one.
|
|
7109
|
+
recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: (pending.launch ? pending.launch.launchConfig : meta.launch?.launchConfig) ?? null, phase: "recovered" });
|
|
7110
|
+
const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
|
|
7111
|
+
// The adopted target is on another server than the home recorded (the start that allocated it
|
|
7112
|
+
// could not record it): this adoption records it, and says so once, here.
|
|
7113
|
+
const recordedSocket = typeof meta.tmux?.socket === "string" && meta.tmux.socket ? resolve(meta.tmux.socket) : null;
|
|
7114
|
+
if (recordedSocket && recordedSocket !== resolve(pending.target.socket)) {
|
|
7115
|
+
const message = sessionMovedWarning(meta.instance, recordedSocket, resolve(pending.target.socket));
|
|
7116
|
+
appendEvent(realHome, { kind: "launch-warning", data: { message } });
|
|
7117
|
+
movedWarnings.push(message);
|
|
7018
7118
|
}
|
|
7019
|
-
if (
|
|
7020
|
-
if (
|
|
7021
|
-
|
|
7022
|
-
|
|
7023
|
-
|
|
7024
|
-
|
|
7025
|
-
|
|
7026
|
-
|
|
7027
|
-
// own session boundary; it is not recorded again.
|
|
7028
|
-
} else {
|
|
7029
|
-
// Reconcile even an exited target: the independent baseline may
|
|
7030
|
-
// already name it while metadata still names the old allocation.
|
|
7031
|
-
// The adopted start's session boundary, at its launch time, completed
|
|
7032
|
-
// in whichever log the interrupted start did not record it. The receipt's
|
|
7033
|
-
// recipe names its configuration (null: the bare harness); only a receipt
|
|
7034
|
-
// without a recipe falls back to the recorded one.
|
|
7035
|
-
recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: (pending.launch ? pending.launch.launchConfig : meta.launch?.launchConfig) ?? null, phase: "recovered" });
|
|
7036
|
-
const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
|
|
7037
|
-
// The adopted target is on another server than the home recorded (the start that allocated it
|
|
7038
|
-
// could not record it): this adoption records it, and says so once, here.
|
|
7039
|
-
const recordedSocket = typeof meta.tmux?.socket === "string" && meta.tmux.socket ? resolve(meta.tmux.socket) : null;
|
|
7040
|
-
if (recordedSocket && recordedSocket !== resolve(pending.target.socket)) {
|
|
7041
|
-
const message = sessionMovedWarning(meta.instance, recordedSocket, resolve(pending.target.socket));
|
|
7042
|
-
appendEvent(realHome, { kind: "launch-warning", data: { message } });
|
|
7043
|
-
movedWarnings.push(message);
|
|
7044
|
-
}
|
|
7045
|
-
if (st.present && st.state !== "shell") {
|
|
7046
|
-
if (o.restart) { rmSync(pendingPath, { force: true }); }
|
|
7047
|
-
else {
|
|
7048
|
-
// The recovered target runs what the receipt says; a choice made
|
|
7049
|
-
// now (model, configuration, harness, yolo) was not applied to it.
|
|
7050
|
-
if (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), done.harness || meta.harness) !== done.model) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running with its previously requested model; its target was recovered, but the new model was not applied`);
|
|
7051
|
-
if (o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running (its pending start was recovered); the requested launch configuration, harness or yolo was not applied; stop it, or use session restart`);
|
|
7052
|
-
return { ...done, warnings: [...done.warnings, ...movedWarnings] };
|
|
7053
|
-
}
|
|
7119
|
+
if (st.present && st.state !== "shell") {
|
|
7120
|
+
if (o.restart) { rmSync(pendingPath, { force: true }); }
|
|
7121
|
+
else {
|
|
7122
|
+
// The recovered target runs what the receipt says; a choice made
|
|
7123
|
+
// now (model, configuration, harness, yolo) was not applied to it.
|
|
7124
|
+
if (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), done.harness || meta.harness) !== done.model) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running with its previously requested model; its target was recovered, but the new model was not applied`);
|
|
7125
|
+
if (o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running (its pending start was recovered); the requested launch configuration, harness or yolo was not applied; stop it, or use session restart`);
|
|
7126
|
+
return { ...done, warnings: [...done.warnings, ...movedWarnings] };
|
|
7054
7127
|
}
|
|
7055
7128
|
}
|
|
7056
7129
|
}
|
|
7057
|
-
|
|
7058
|
-
|
|
7059
|
-
|
|
7060
|
-
|
|
7061
|
-
|
|
7062
|
-
|
|
7063
|
-
|
|
7064
|
-
|
|
7065
|
-
|
|
7066
|
-
|
|
7067
|
-
|
|
7068
|
-
|
|
7069
|
-
|
|
7070
|
-
|
|
7071
|
-
|
|
7072
|
-
|
|
7073
|
-
|
|
7074
|
-
|
|
7075
|
-
|
|
7076
|
-
|
|
7077
|
-
|
|
7078
|
-
|
|
7079
|
-
|
|
7080
|
-
|
|
7081
|
-
|
|
7082
|
-
|
|
7130
|
+
}
|
|
7131
|
+
// 2. The ordinary gate and observation, all under the home's claim.
|
|
7132
|
+
const receipt = instanceSessionTarget(realHome);
|
|
7133
|
+
const meta = readMeta();
|
|
7134
|
+
const harness = meta.harness;
|
|
7135
|
+
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`);
|
|
7136
|
+
let command = meta.command;
|
|
7137
|
+
let model = meta.model || undefined;
|
|
7138
|
+
// What this start launches: the frozen command (optionally with another
|
|
7139
|
+
// model, re-rendered in place), or, under a selection, the recipe
|
|
7140
|
+
// re-resolved against the home's current scoped configuration. Every
|
|
7141
|
+
// preflight happens here, before anything is observed or stopped.
|
|
7142
|
+
// --reselect-launch (feature launch-preference): apply the home's launch layers now (souls.launch,
|
|
7143
|
+
// the recorded soul's launch, the host default) instead of the frozen recipe.
|
|
7144
|
+
// `launchOffered`: the caller's read of the workspace's souls (homeSoulsOffered), which the layers need
|
|
7145
|
+
// to tell a key of souls.launch that names no soul. A selection the layers would decide never goes on
|
|
7146
|
+
// without it: a key that was not checked must not let the launch fall through.
|
|
7147
|
+
const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
|
|
7148
|
+
if (reselect?.needsOffered && o.launchConfig === undefined && o.harness === undefined) throw oatsError("E_BAD_ARGS", `--reselect-launch of ${meta.instance || realHome} 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)`);
|
|
7149
|
+
// The session this start opens its window in when it has to create one, and what its creation
|
|
7150
|
+
// needs (planOatsTmuxSession), read at most once: by the plan's lookup or by the creation's preflight.
|
|
7151
|
+
const planSession = receipt.target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
|
|
7152
|
+
let sessionPlanRead;
|
|
7153
|
+
const sessionPlan = () => {
|
|
7154
|
+
if (!sessionPlanRead) { try { sessionPlanRead = { plan: planOatsTmuxSession(planSession, o.io, { missingSocket }) }; } catch (e) { sessionPlanRead = { error: e }; } }
|
|
7155
|
+
if (sessionPlanRead.error) throw sessionPlanRead.error;
|
|
7156
|
+
return sessionPlanRead.plan;
|
|
7157
|
+
};
|
|
7158
|
+
// The recorded target, observed once: by the plan's lookup, which must know whether the pane will
|
|
7159
|
+
// be reused before it chooses where to look, or by the gate below. A lost server is a stopped one
|
|
7160
|
+
// (lostServer); any other failure is the gate's refusal (E_SESSION_UNKNOWN), and the lookup does
|
|
7161
|
+
// not decide it.
|
|
7162
|
+
let recordedRead;
|
|
7163
|
+
const recordedState = () => {
|
|
7164
|
+
if (!recordedRead) {
|
|
7165
|
+
try { recordedRead = { state: receipt.target ? inspectSessionTarget(receipt.target, o.io) : { present: false, state: "not-launched" } }; }
|
|
7166
|
+
catch (e) { const lost = lostServer(e); recordedRead = lost.stopped ? { state: { present: false, state: "stopped" } } : { error: lost.why ? new Error(lost.why) : e }; }
|
|
7167
|
+
}
|
|
7168
|
+
return recordedRead;
|
|
7169
|
+
};
|
|
7170
|
+
// A pane the start reuses where it is: one the recorded target shows, running or left as a shell.
|
|
7171
|
+
const reusable = (state) => !!(state?.paneId && (state.present || state.state === "stopped"));
|
|
7172
|
+
const selected = reselect !== null || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined;
|
|
7173
|
+
const hasRecipe = meta.launch && typeof meta.launch === "object";
|
|
7174
|
+
let launchPlan = null, launchHooksPass = null, handedExecutable, hookMeta, hookDialogClaims, explicitModelFrom = null, warnings = [];
|
|
7175
|
+
// --resume: only a home whose session was lost, read here, under the home's claim, before any launch hook
|
|
7176
|
+
// runs. Then the conversation it continues, or the reason it starts fresh (resumeConversation).
|
|
7177
|
+
let resume = null;
|
|
7178
|
+
if (o.resume === true) {
|
|
7179
|
+
if (!hasRecipe) throw oatsError("E_LAUNCH_LEGACY", `${meta.instance || realHome} records no launch recipe (an earlier kernel spawned it): re-spawn it from the deployment; nothing was changed`);
|
|
7180
|
+
const observed = recordedState();
|
|
7181
|
+
if (observed.error) { const e = observed.error; throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${meta.instance} is running, so nothing was started: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
|
|
7182
|
+
if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
|
|
7183
|
+
// A home whose retire runs, cannot be told, failed or was interrupted is owed it, never a
|
|
7184
|
+
// resume (read as its status row reads it, under the claim this resume holds).
|
|
7185
|
+
const owed = owedRetire(realHome);
|
|
7186
|
+
if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(meta.instance, owed.state)}; nothing was started`);
|
|
7187
|
+
const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
|
|
7188
|
+
if (end !== SESSION_END.LOST) throw oatsError("E_RESUME_NOT_LOST", `${meta.instance} did not lose its session (${end === "never-launched" ? "it was never launched" : `it ${end}`}); --resume brings back only a lost session; nothing was started (an ordinary session start opens a fresh conversation)`);
|
|
7189
|
+
resume = resumeConversation(realHome, meta);
|
|
7190
|
+
}
|
|
7191
|
+
if (selected || hasRecipe) {
|
|
7192
|
+
// Every start of a home with a recipe (ordinary, model-only, or under a
|
|
7193
|
+
// selection) goes through the one planner: recipe shape, the recorded
|
|
7194
|
+
// or selected executable, references, capability contributions under
|
|
7195
|
+
// the captured settings and current trust. A home without a recipe that
|
|
7196
|
+
// is asked for a selection is refused (E_LAUNCH_LEGACY).
|
|
7197
|
+
const context = meta.repo && existsSync(meta.repo) ? resolve(meta.repo) : dirname(dirname(dirname(dirname(realHome))));
|
|
7198
|
+
// o.teams / o.defaultTeam: the home's LIVE teams, computed by an async caller (liveTeams) —
|
|
7199
|
+
// the launch hook re-checks joined memberships against them.
|
|
7200
|
+
const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
|
|
7201
|
+
let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
|
|
7202
|
+
// The environment the plan's checks read for this launch's pane (the harness lookup by name,
|
|
7203
|
+
// the package probe, folder trust): a pane the start will reuse, on its own recorded session,
|
|
7204
|
+
// whatever the OATS server holds; otherwise the session's or the server's when a server runs;
|
|
7205
|
+
// when none does, the environment this start will create the server with (read once, here,
|
|
7206
|
+
// for the plan and for the creation below). For a creator that may not create the server no
|
|
7207
|
+
// pane's environment is established: the plan's checks read this process's, and the refusal
|
|
7208
|
+
// comes at the creation's own place, after the start's other preflights.
|
|
7209
|
+
const pane = () => {
|
|
7210
|
+
const recorded = recordedState();
|
|
7211
|
+
if (reusable(recorded.state)) return paneEnvironment(receipt.target.socket, receipt.target.session, o.io, realHome);
|
|
7212
|
+
if (recorded.error) return NO_PANE_READ; // the gate refuses below; no check decides it
|
|
7213
|
+
const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
|
|
7214
|
+
if (!preview || preview.server) return expectedPaneEnvironment(preview, planSession, o.io, realHome);
|
|
7215
|
+
try { return expectedPaneEnvironment(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return SESSION_REFUSED; throw e; }
|
|
7083
7216
|
};
|
|
7084
|
-
|
|
7085
|
-
|
|
7086
|
-
|
|
7087
|
-
|
|
7088
|
-
|
|
7089
|
-
|
|
7090
|
-
|
|
7091
|
-
|
|
7092
|
-
|
|
7217
|
+
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,
|
|
7218
|
+
pane });
|
|
7219
|
+
launchPlan = { recipe: plan.recipe, command: plan.command, declaredEnv: plan.declaredEnv, harness: plan.harness, model: plan.model, yolo: plan.yolo, executable: plan.executable, executablePaneSide: plan.executablePaneSide, config: plan.config, launchChoice: plan.launchChoice, trustHome: plan.trustHome, modelFrom: modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null }),
|
|
7220
|
+
...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at, launchDeclared: plan.launchChoice.declared } : {}) };
|
|
7221
|
+
// The plan ran preview-aware launch hooks as a preview: their real run, over the planned
|
|
7222
|
+
// contributions, waits for the rest of preflight.
|
|
7223
|
+
handedExecutable = harnessExecutableEnv(plan.executable.path, plan.executablePaneSide).OATS_HARNESS_EXECUTABLE;
|
|
7224
|
+
if (plan.previewedHooks.length) launchHooksPass = { frozen: { ...plan.frozen, hooks: plan.recipe.hooks }, harness: plan.harness, resolvedCfg, contextDir: context, previewed: plan.recipe.hooks, volatileEnv: plan.volatileEnv, trustHome: plan.trustHome };
|
|
7225
|
+
command = launchPlan.command; model = launchPlan.model;
|
|
7226
|
+
// The other launch hooks ran for real in the plan: their warnings are
|
|
7227
|
+
// events now, whatever the start does next, and the answer carries them.
|
|
7228
|
+
hookMeta = plan.hookMeta;
|
|
7229
|
+
hookDialogClaims = plan.hookDialogClaims;
|
|
7230
|
+
warnings = plan.warnings;
|
|
7231
|
+
for (const message of warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
|
|
7232
|
+
} else if (o.model !== undefined && o.model !== null && String(o.model).trim() !== "") {
|
|
7233
|
+
const resolved = resolveModelPreference(String(o.model), harness);
|
|
7234
|
+
if (!resolved) throw oatsError("E_MODEL_UNKNOWN", `model preference ${JSON.stringify(o.model)} has no entry usable by harness ${harness}; give a ${harness} model id`);
|
|
7235
|
+
command = withLaunchModel(command, resolved);
|
|
7236
|
+
model = resolved; explicitModelFrom = "start";
|
|
7237
|
+
} else parseLaunchCommand(command);
|
|
7238
|
+
// A recorded command starts, and is saved, with its harness's safe task prompt.
|
|
7239
|
+
if (!launchPlan) command = withSafeTaskPrompt(command, harness);
|
|
7240
|
+
// References recorded for this home must resolve on this host on every
|
|
7241
|
+
// start path, and the source variables go to the pane, not the command.
|
|
7242
|
+
const recipeForEnv = launchPlan?.recipe || (meta.launch && typeof meta.launch === "object" ? meta.launch : null);
|
|
7243
|
+
if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing, recipeForEnv.harness)); }
|
|
7244
|
+
// A resume starts only under the values the start it brings back recorded (lib/start-env.mjs): a
|
|
7245
|
+
// changed one refuses, after a missing one; a start with no record to check (an earlier kernel's,
|
|
7246
|
+
// or one that does not read) is resumed and says so once. Ordinary starts never compare.
|
|
7247
|
+
const paneEnv = recipeForEnv ? launchEnvRefs(recipeForEnv, o.env || process.env) : [];
|
|
7248
|
+
const referenceNames = paneEnv.map((r) => r.source), referenceValues = Object.fromEntries(paneEnv.map((r) => [r.source, r.value]));
|
|
7249
|
+
let envUnverified = null;
|
|
7250
|
+
if (resume && recipeForEnv) {
|
|
7251
|
+
const fit = checkStartEnv(realHome, meta.startId, referenceNames, referenceValues);
|
|
7252
|
+
if (fit.changed) throw oatsError("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
|
|
7253
|
+
if (fit.unverified) warnings.push(envUnverified = launchEnvUnverifiedWarning(meta.instance));
|
|
7254
|
+
}
|
|
7255
|
+
|
|
7256
|
+
checkRoots(); // preparation has run; no backend has been changed
|
|
7257
|
+
let target = receipt.target;
|
|
7258
|
+
const recorded = recordedState();
|
|
7259
|
+
if (recorded.error) { const e = recorded.error; throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${meta.instance} is running, so nothing was started: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
|
|
7260
|
+
let state = recorded.state;
|
|
7261
|
+
if (state.present && state.state !== "shell" && !o.restart) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${state.state}); nothing was started`);
|
|
7262
|
+
// A caller that will have to create the tmux session reads the environment for it here, unless
|
|
7263
|
+
// the plan's lookup read it already with no server running (an instance that cannot is refused
|
|
7264
|
+
// here either way): after the start's preflights and its planning,
|
|
7265
|
+
// so each of their refusals still answers first, and before the real run of preview-aware
|
|
7266
|
+
// launch hooks, a stop and any write of the home's launch state (record, receipt, pending
|
|
7267
|
+
// start). A launch hook that does not declare launchPreview has already run and its warnings
|
|
7268
|
+
// are already events (above), as before any other late refusal of a start (E_SESSION_RUNNING,
|
|
7269
|
+
// E_LAUNCH_ENV_MISSING); nothing undoes what it did, and the hook contract (above
|
|
7270
|
+
// prepareLaunchHooks) allows such a hook idempotent provider registration, which the next
|
|
7271
|
+
// start repeats. Only when this start will have to create a window: a retained pane is reused
|
|
7272
|
+
// where it is. A restart whose window goes away during its stop is decided at the creation.
|
|
7273
|
+
const retained = reusable(state);
|
|
7274
|
+
const tmuxSessionPlan = retained ? undefined : sessionPlan();
|
|
7275
|
+
// A harness the plan looked up by name is looked up again where its pane will look it up, before
|
|
7276
|
+
// anything is stopped: the retained pane's own session, or the session this start will create
|
|
7277
|
+
// its window in (as planned). Once more on the session ensureOatsTmuxSession returns (below).
|
|
7278
|
+
// Not there: refused. Found elsewhere: the launch runs that one, and records it. Every executable
|
|
7279
|
+
// named bare (the harness's name, a declared name) is looked up again, also one the plan could only
|
|
7280
|
+
// look up on this process's PATH; a recorded (frozen) or a declared path never is.
|
|
7281
|
+
const lookAgain = (pane) => {
|
|
7282
|
+
if (!launchPlan || launchPlan.config?.frozen || launchPlan.config?.executable?.includes("/")) return false;
|
|
7283
|
+
const { config, launchChoice } = launchPlan;
|
|
7284
|
+
const actual = resolveLaunchExecutable({ harness: launchPlan.harness, declared: config?.executable, declaringDir: config?.source, lookup: launchLookup(launchEnvironment({ configEnv: config?.env, configName: config?.name, env: o.env || process.env, pane, cwd: realHome })) });
|
|
7285
|
+
if (!actual.path) throw executableNotOnPanePath(actual, { harness: launchPlan.harness, config, from: launchChoice?.from, at: launchChoice?.at });
|
|
7286
|
+
const bad = checkLaunchExecutable(actual.path);
|
|
7287
|
+
if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${bad}; nothing was started`);
|
|
7288
|
+
launchPlan.executablePaneSide = !!actual.lookup;
|
|
7289
|
+
if (actual.path === launchPlan.recipe.executable) return false;
|
|
7290
|
+
launchPlan.recipe = { ...launchPlan.recipe, executable: actual.path };
|
|
7291
|
+
command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome });
|
|
7292
|
+
return true;
|
|
7293
|
+
};
|
|
7294
|
+
/** The launch runs another program than the hooks that have run were handed: said, and kept in the home. */
|
|
7295
|
+
const noteReplacedExecutable = () => {
|
|
7296
|
+
const replaced = replacedExecutableWarning(handedExecutable, launchPlan?.recipe.executable);
|
|
7297
|
+
if (!replaced) return;
|
|
7298
|
+
handedExecutable = undefined;
|
|
7299
|
+
hookDialogClaims = voidedDialogClaims(hookDialogClaims);
|
|
7300
|
+
warnings.push(replaced);
|
|
7301
|
+
appendEvent(realHome, { kind: "launch-warning", data: { message: replaced } });
|
|
7302
|
+
};
|
|
7303
|
+
lookAgain(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
|
|
7304
|
+
// Every preflight has passed: the preview-aware launch hooks run for real
|
|
7305
|
+
// (they may register the home with their provider), before a restart's
|
|
7306
|
+
// stop, and must contribute exactly what they contributed as a preview,
|
|
7307
|
+
// which is what the command was rendered and preflighted from, except the
|
|
7308
|
+
// values of the env their preview declared volatile: those come from this
|
|
7309
|
+
// run, and the command is rendered again with them.
|
|
7310
|
+
if (launchHooksPass) {
|
|
7311
|
+
const { previewed, volatileEnv, trustHome, ...pass } = launchHooksPass;
|
|
7312
|
+
// The looks above have settled what this start expects: that is what its real hooks are handed.
|
|
7313
|
+
const handed = harnessExecutableEnv(launchPlan.recipe.executable, launchPlan.executablePaneSide);
|
|
7314
|
+
// Hooks that ran for real in the plan were handed the plan's: their statements don't reach this one.
|
|
7315
|
+
if (handed.OATS_HARNESS_EXECUTABLE !== handedExecutable) hookDialogClaims = voidedDialogClaims(hookDialogClaims);
|
|
7316
|
+
handedExecutable = handed.OATS_HARNESS_EXECUTABLE;
|
|
7317
|
+
const real = prepareLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots, pass: "real" });
|
|
7318
|
+
const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
|
|
7319
|
+
const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
|
|
7320
|
+
if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
|
|
7321
|
+
// A provider's row names its env; the values are in the merged env.
|
|
7322
|
+
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]) }); };
|
|
7323
|
+
const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
|
|
7324
|
+
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`);
|
|
7325
|
+
}
|
|
7326
|
+
launchPlan.recipe = { ...launchPlan.recipe, hooks: { launch: real.launch, env: real.env, contributions: real.contributions } };
|
|
7327
|
+
command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome });
|
|
7328
|
+
if (real.meta) hookMeta = { ...(hookMeta || {}), ...real.meta };
|
|
7329
|
+
if (real.dialogClaims) hookDialogClaims = { ...(hookDialogClaims || {}), ...real.dialogClaims };
|
|
7330
|
+
// The real run's warnings are events now, whatever the start does next,
|
|
7331
|
+
// and the answer carries them.
|
|
7332
|
+
warnings = [...warnings, ...real.warnings];
|
|
7333
|
+
for (const message of real.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
|
|
7334
|
+
checkRoots();
|
|
7335
|
+
}
|
|
7336
|
+
// The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
|
|
7337
|
+
// A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
|
|
7338
|
+
const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
|
|
7339
|
+
// Check the final hook contributions against the environment actually handed to this start.
|
|
7340
|
+
// Reference values below are the same snapshot the private launcher will receive.
|
|
7341
|
+
const loginOn = (pane) => {
|
|
7342
|
+
const r = launchPlan?.recipe || recipeForEnv;
|
|
7343
|
+
if (!r) return;
|
|
7344
|
+
const configEnv = Object.fromEntries(Object.entries(r.env || {}).map(([name, value]) => [name, typeof value === "string" ? value : paneEnv.find((ref) => ref.target === name)?.value]));
|
|
7345
|
+
const login = claudeLoginCredential({ harness: launchPlan?.harness || harness, configEnv, hooksEnv: r.hooks?.env, launch: launchEnvironment({ configEnv, capabilities: { env: r.hooks?.env }, removed, env: o.env || process.env, pane, cwd: realHome }) });
|
|
7346
|
+
if (login?.code) throw oatsError(login.code, login.message);
|
|
7347
|
+
};
|
|
7348
|
+
loginOn(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
|
|
7349
|
+
noteReplacedExecutable();
|
|
7350
|
+
const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
|
|
7351
|
+
...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
|
|
7352
|
+
...(hookMeta ? { hookMeta } : {}), ...(hookDialogClaims ? { hookDialogClaims } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
|
|
7353
|
+
if (resume?.warning) { warnings.push(resume.warning); appendEvent(realHome, { kind: "launch-warning", data: { message: resume.warning } }); }
|
|
7354
|
+
warnings.push(...launchStartNotices(dirname(dirname(dirname(dirname(home)))), launchPlan?.harness || harness, command));
|
|
7355
|
+
if (kernelNode().warning) warnings.push(kernelNode().warning);
|
|
7356
|
+
const engaged = devChannelEngaged(launchPlan?.harness || harness, command);
|
|
7357
|
+
let stopReceipt = null;
|
|
7358
|
+
if (state.present && state.state !== "shell") {
|
|
7359
|
+
// Restart: every preflight above passed, so ask the running harness to
|
|
7360
|
+
// end and wait, bounded. A harness still there afterwards is reported
|
|
7361
|
+
// as running; nothing is escalated and nothing is launched.
|
|
7362
|
+
// The stop is recorded first, for the start instance.json still names (recordStop, as a
|
|
7363
|
+
// retire does), so a relaunch that fails, or a process that dies before it, leaves a home
|
|
7364
|
+
// that reads `stopped`, never `lost`: no resume brings back what was being restarted. The
|
|
7365
|
+
// relaunch records a new start, which the record does not name. A stop refused here leaves
|
|
7366
|
+
// the record with the harness running: should that harness die later, the home reads
|
|
7367
|
+
// `stopped`. A record that cannot be written (a full disk) does not block the restart.
|
|
7368
|
+
try { recordStop(realHome, null); } catch { /* see above */ }
|
|
7369
|
+
stopReceipt = stopHarness(target, { graceMs: o.stopGraceMs ?? 20000, io: o.io, kill: o.io?.kill, sleep: o.io?.sleep });
|
|
7370
|
+
writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe.launchConfig ?? null, model: model ?? null } }, 0o600);
|
|
7371
|
+
appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
|
|
7372
|
+
if (!stopReceipt.exited) throw oatsError("E_SESSION_STOP_FAILED", `${meta.instance} was asked to stop (${stopReceipt.signal} to ${stopReceipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")} at ${stopReceipt.sentAt}) and was still running after ${stopReceipt.waitedMs} ms (${stopReceipt.state}); nothing was escalated and nothing was started; stop it yourself, or retry with a longer --stop-grace. Receipt: ${join(realHome, ".oats-restart.json")}`);
|
|
7373
|
+
try { state = inspectSessionTarget(target, o.io); }
|
|
7374
|
+
catch (e) {
|
|
7375
|
+
const lost = lostServer(e);
|
|
7376
|
+
if (lost.stopped) state = { present: false, state: "stopped" };
|
|
7377
|
+
else throw oatsError("E_SESSION_UNKNOWN", `after the stop, cannot establish the state of ${meta.instance}, so nothing was started: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}`);
|
|
7378
|
+
}
|
|
7379
|
+
if (state.present && state.state !== "shell") throw oatsError("E_SESSION_UNKNOWN", `${meta.instance} read as stopped and then as ${state.state} again; nothing was started`);
|
|
7380
|
+
}
|
|
7381
|
+
// The kernel that launches the harness is the one the agent's plain `oats` runs.
|
|
7382
|
+
checkRoots();
|
|
7383
|
+
writeKernelShim(realHome);
|
|
7384
|
+
const startedAt = new Date().toISOString();
|
|
7385
|
+
const id = randomUUID();
|
|
7386
|
+
if (!engaged) planExtra.launchPrompts = notEngaged(id);
|
|
7387
|
+
// This start's launch environment, recorded just before its pane is made (best effort: never a
|
|
7388
|
+
// refusal). A home without a recipe renders none and records nothing.
|
|
7389
|
+
const recordEnv = () => { if (recipeForEnv) recordStartEnv(realHome, id, referenceNames, referenceValues); };
|
|
7390
|
+
const makeLaunchController = () => engaged ? promptController(realHome, id, command, o.io, originalHomeIdentity) : null;
|
|
7391
|
+
let launchController;
|
|
7392
|
+
let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
|
|
7393
|
+
// A resumed Claude session is watched for its resume-cost dialog once it runs (after the record):
|
|
7394
|
+
// the pane's identity is read at its creation, as the controller reads it.
|
|
7395
|
+
const watchResume = !!resume?.sessionId && launchPlan.harness === "claude";
|
|
7396
|
+
let resumeTarget = null;
|
|
7397
|
+
checkRoots();
|
|
7398
|
+
// The launch's one native start; every render of its window command reuses it.
|
|
7399
|
+
const nativeStart = prepareNativeStart(realHome, launchPlan?.harness || harness);
|
|
7400
|
+
// What the window runs: the planned command, or, for a resume that found its conversation, the same
|
|
7401
|
+
// recipe rendered with the harness's resume selector and the resume notice. Only the window carries
|
|
7402
|
+
// it: instance.json, the pending receipt and the recipe keep the ordinary launch, so a later start
|
|
7403
|
+
// opens a fresh conversation (and the native-record roots never see a recorded --session).
|
|
7404
|
+
const executedCommand = () => resume?.sessionId ? renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome, resume: { sessionId: resume.sessionId, prompt: RESUME_NOTICE } }) : command;
|
|
7405
|
+
const windowCommand = (scope) => paneCommand(exitMarked(nativeRecordCommand(executedCommand(), realHome, launchPlan?.harness || harness, { start: nativeStart, scope }), id, exitedPath), removed);
|
|
7406
|
+
// Whether the harness runs in a scope of its own (nativeRecordCommand), judged on the pane it
|
|
7407
|
+
// will run in for the command it runs; a warning is said, and is an event once the start is recorded.
|
|
7408
|
+
let unscoped = null;
|
|
7409
|
+
const scopeOn = (pane) => {
|
|
7410
|
+
// The caller's own io (a test's), not the guarded one every start runs with.
|
|
7411
|
+
const scope = agentScopeOn(command, { pane, removed, refs: paneEnv }, rawIo);
|
|
7412
|
+
if (scope.warning) warnings.push(unscoped = scope.warning);
|
|
7413
|
+
return scope.wrapper;
|
|
7414
|
+
};
|
|
7415
|
+
let envHandoff;
|
|
7416
|
+
const privateWindowCommand = (command) => { envHandoff = launchEnvHandoff(realHome, id, paneEnv); return envHandoff.wrap(command); };
|
|
7417
|
+
let reused = "new";
|
|
7418
|
+
const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
|
|
7419
|
+
const window = target?.window || meta.tmux?.window || meta.instance;
|
|
7420
|
+
let socket = target?.socket || meta.tmux?.socket;
|
|
7421
|
+
let windowCmd = windowCommand();
|
|
7422
|
+
let moved = null;
|
|
7423
|
+
// A fallback shell (no harness descendant) or a retained dead pane is
|
|
7424
|
+
// the agent's own pane (resolveAgentPane): the command runs there, on the
|
|
7425
|
+
// server the home recorded, no other window or pane touched and no option
|
|
7426
|
+
// set but that pane's mark.
|
|
7427
|
+
const inPlace = state.paneId && (state.present || state.state === "stopped");
|
|
7428
|
+
try {
|
|
7429
|
+
if (inPlace) {
|
|
7430
|
+
const pane = paneEnvironment(socket, session, o.io, realHome);
|
|
7431
|
+
loginOn(pane);
|
|
7432
|
+
const scope = scopeOn(pane);
|
|
7433
|
+
if (scope) windowCmd = windowCommand(scope);
|
|
7434
|
+
launchController = makeLaunchController();
|
|
7435
|
+
if (launchController) {
|
|
7436
|
+
try {
|
|
7437
|
+
const oldTarget = launchPromptTransport(o.io).identity(socket, state.paneId);
|
|
7438
|
+
beforeRespawn = launchController.captureBeforeRespawn(oldTarget);
|
|
7439
|
+
} catch { /* a missing prior capture can never authorize input */ }
|
|
7093
7440
|
}
|
|
7094
|
-
|
|
7095
|
-
|
|
7096
|
-
|
|
7097
|
-
|
|
7098
|
-
|
|
7099
|
-
|
|
7100
|
-
|
|
7101
|
-
|
|
7102
|
-
// runs. Then the conversation it continues, or the reason it starts fresh (resumeConversation).
|
|
7103
|
-
let resume = null;
|
|
7104
|
-
if (o.resume === true) {
|
|
7105
|
-
if (!hasRecipe) throw oatsError("E_LAUNCH_LEGACY", `${meta.instance || realHome} records no launch recipe (an earlier kernel spawned it): re-spawn it from the deployment; nothing was changed`);
|
|
7106
|
-
const observed = recordedState();
|
|
7107
|
-
if (observed.error) { const e = observed.error; throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${meta.instance} is running, so nothing was started: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
|
|
7108
|
-
if (observed.state.present && observed.state.state !== "shell") throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${observed.state.state}); nothing was started`);
|
|
7109
|
-
// A home whose retire runs, cannot be told, failed or was interrupted is owed it, never a
|
|
7110
|
-
// resume (read as its status row reads it, under the claim this resume holds).
|
|
7111
|
-
const owed = owedRetire(realHome);
|
|
7112
|
-
if (owed) throw oatsError("E_INSTANCE_RETIRING", `${owedRetireSaid(meta.instance, owed.state)}; nothing was started`);
|
|
7113
|
-
const end = meta.launched === true ? sessionEndOf(realHome, meta) : "never-launched";
|
|
7114
|
-
if (end !== SESSION_END.LOST) throw oatsError("E_RESUME_NOT_LOST", `${meta.instance} did not lose its session (${end === "never-launched" ? "it was never launched" : `it ${end}`}); --resume brings back only a lost session; nothing was started (an ordinary session start opens a fresh conversation)`);
|
|
7115
|
-
resume = resumeConversation(realHome, meta);
|
|
7116
|
-
}
|
|
7117
|
-
if (selected || hasRecipe) {
|
|
7118
|
-
// Every start of a home with a recipe (ordinary, model-only, or under a
|
|
7119
|
-
// selection) goes through the one planner: recipe shape, the recorded
|
|
7120
|
-
// or selected executable, references, capability contributions under
|
|
7121
|
-
// the captured settings and current trust. A home without a recipe that
|
|
7122
|
-
// is asked for a selection is refused (E_LAUNCH_LEGACY).
|
|
7123
|
-
const context = meta.repo && existsSync(meta.repo) ? resolve(meta.repo) : dirname(dirname(dirname(dirname(realHome))));
|
|
7124
|
-
// o.teams / o.defaultTeam: the home's LIVE teams, computed by an async caller (liveTeams) —
|
|
7125
|
-
// the launch hook re-checks joined memberships against them.
|
|
7126
|
-
const resolvedCfg = resolvedFromHome(realHome, meta, { teams: o.teams, defaultTeam: o.defaultTeam, teamsSource: o.teamsSource });
|
|
7127
|
-
let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
|
|
7128
|
-
// The environment the plan's checks read for this launch's pane (the harness lookup by name,
|
|
7129
|
-
// the package probe, folder trust): a pane the start will reuse, on its own recorded session,
|
|
7130
|
-
// whatever the OATS server holds; otherwise the session's or the server's when a server runs;
|
|
7131
|
-
// when none does, the environment this start will create the server with (read once, here,
|
|
7132
|
-
// for the plan and for the creation below). For a creator that may not create the server no
|
|
7133
|
-
// pane's environment is established: the plan's checks read this process's, and the refusal
|
|
7134
|
-
// comes at the creation's own place, after the start's other preflights.
|
|
7135
|
-
const pane = () => {
|
|
7136
|
-
const recorded = recordedState();
|
|
7137
|
-
if (reusable(recorded.state)) return paneEnvironment(receipt.target.socket, receipt.target.session, o.io, realHome);
|
|
7138
|
-
if (recorded.error) return NO_PANE_READ; // the gate refuses below; no check decides it
|
|
7139
|
-
const preview = planOatsTmuxSession(planSession, o.io, { preview: true, missingSocket });
|
|
7140
|
-
if (!preview || preview.server) return expectedPaneEnvironment(preview, planSession, o.io, realHome);
|
|
7141
|
-
try { return expectedPaneEnvironment(sessionPlan(), planSession, o.io, realHome); } catch (e) { if (isKernelCode(e?.code)) return SESSION_REFUSED; throw e; }
|
|
7142
|
-
};
|
|
7143
|
-
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,
|
|
7144
|
-
pane });
|
|
7145
|
-
launchPlan = { recipe: plan.recipe, command: plan.command, declaredEnv: plan.declaredEnv, harness: plan.harness, model: plan.model, yolo: plan.yolo, executable: plan.executable, executablePaneSide: plan.executablePaneSide, config: plan.config, launchChoice: plan.launchChoice, trustHome: plan.trustHome, modelFrom: modelFromOf(plan.modelSource, { at: "start", prior: meta.modelFrom ?? null }),
|
|
7146
|
-
...(plan.launchChoice ? { launchFrom: plan.launchChoice.from, launchAt: plan.launchChoice.at, launchDeclared: plan.launchChoice.declared } : {}) };
|
|
7147
|
-
// The plan ran preview-aware launch hooks as a preview: their real run, over the planned
|
|
7148
|
-
// contributions, waits for the rest of preflight.
|
|
7149
|
-
handedExecutable = harnessExecutableEnv(plan.executable.path, plan.executablePaneSide).OATS_HARNESS_EXECUTABLE;
|
|
7150
|
-
if (plan.previewedHooks.length) launchHooksPass = { frozen: { ...plan.frozen, hooks: plan.recipe.hooks }, harness: plan.harness, resolvedCfg, contextDir: context, previewed: plan.recipe.hooks, volatileEnv: plan.volatileEnv, trustHome: plan.trustHome };
|
|
7151
|
-
command = launchPlan.command; model = launchPlan.model;
|
|
7152
|
-
// The other launch hooks ran for real in the plan: their warnings are
|
|
7153
|
-
// events now, whatever the start does next, and the answer carries them.
|
|
7154
|
-
hookMeta = plan.hookMeta;
|
|
7155
|
-
hookDialogClaims = plan.hookDialogClaims;
|
|
7156
|
-
warnings = plan.warnings;
|
|
7157
|
-
for (const message of warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
|
|
7158
|
-
} else if (o.model !== undefined && o.model !== null && String(o.model).trim() !== "") {
|
|
7159
|
-
const resolved = resolveModelPreference(String(o.model), harness);
|
|
7160
|
-
if (!resolved) throw oatsError("E_MODEL_UNKNOWN", `model preference ${JSON.stringify(o.model)} has no entry usable by harness ${harness}; give a ${harness} model id`);
|
|
7161
|
-
command = withLaunchModel(command, resolved);
|
|
7162
|
-
model = resolved; explicitModelFrom = "start";
|
|
7163
|
-
} else parseLaunchCommand(command);
|
|
7164
|
-
// A recorded command starts, and is saved, with its harness's safe task prompt.
|
|
7165
|
-
if (!launchPlan) command = withSafeTaskPrompt(command, harness);
|
|
7166
|
-
// References recorded for this home must resolve on this host on every
|
|
7167
|
-
// start path, and the source variables go to the pane, not the command.
|
|
7168
|
-
const recipeForEnv = launchPlan?.recipe || (meta.launch && typeof meta.launch === "object" ? meta.launch : null);
|
|
7169
|
-
if (recipeForEnv) { const missing = missingLaunchEnvRefs(recipeForEnv.env, o.env || process.env); if (missing.length) throw oatsError("E_LAUNCH_ENV_MISSING", launchEnvMissingMessage(missing)); }
|
|
7170
|
-
// A resume starts only under the values the start it brings back recorded (lib/start-env.mjs): a
|
|
7171
|
-
// changed one refuses, after a missing one; a start with no record to check (an earlier kernel's,
|
|
7172
|
-
// or one that does not read) is resumed and says so once. Ordinary starts never compare.
|
|
7173
|
-
let envUnverified = null;
|
|
7174
|
-
if (resume && recipeForEnv) {
|
|
7175
|
-
const fit = checkStartEnv(realHome, meta.startId, fromEnvNames(recipeForEnv.env), o.env || process.env);
|
|
7176
|
-
if (fit.changed) throw oatsError("E_LAUNCH_ENV_CHANGED", launchEnvChangedMessage(fit.changed));
|
|
7177
|
-
if (fit.unverified) warnings.push(envUnverified = launchEnvUnverifiedWarning(meta.instance));
|
|
7178
|
-
}
|
|
7179
|
-
const paneEnv = recipeForEnv ? launchEnvRefs(recipeForEnv, o.env || process.env) : [];
|
|
7180
|
-
const paneEnvFlags = paneEnv.flatMap((r) => ["-e", `${r.name}=${r.value}`]);
|
|
7181
|
-
checkRoots(); // preparation has run; no backend has been changed
|
|
7182
|
-
let target = receipt.target;
|
|
7183
|
-
const recorded = recordedState();
|
|
7184
|
-
if (recorded.error) { const e = recorded.error; throw oatsError("E_SESSION_UNKNOWN", `cannot establish whether ${meta.instance} is running, so nothing was started: ${String(e.stderr ?? e.message ?? "").trim() || e.message}`); }
|
|
7185
|
-
let state = recorded.state;
|
|
7186
|
-
if (state.present && state.state !== "shell" && !o.restart) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is running (${state.state}); nothing was started`);
|
|
7187
|
-
// A caller that will have to create the tmux session reads the environment for it here, unless
|
|
7188
|
-
// the plan's lookup read it already with no server running (an instance that cannot is refused
|
|
7189
|
-
// here either way): after the start's preflights and its planning,
|
|
7190
|
-
// so each of their refusals still answers first, and before the real run of preview-aware
|
|
7191
|
-
// launch hooks, a stop and any write of the home's launch state (record, receipt, pending
|
|
7192
|
-
// start). A launch hook that does not declare launchPreview has already run and its warnings
|
|
7193
|
-
// are already events (above), as before any other late refusal of a start (E_SESSION_RUNNING,
|
|
7194
|
-
// E_LAUNCH_ENV_MISSING); nothing undoes what it did, and the hook contract (above
|
|
7195
|
-
// prepareLaunchHooks) allows such a hook idempotent provider registration, which the next
|
|
7196
|
-
// start repeats. Only when this start will have to create a window: a retained pane is reused
|
|
7197
|
-
// where it is. A restart whose window goes away during its stop is decided at the creation.
|
|
7198
|
-
const retained = reusable(state);
|
|
7199
|
-
const tmuxSessionPlan = retained ? undefined : sessionPlan();
|
|
7200
|
-
// A harness the plan looked up by name is looked up again where its pane will look it up, before
|
|
7201
|
-
// anything is stopped: the retained pane's own session, or the session this start will create
|
|
7202
|
-
// its window in (as planned). Once more on the session ensureOatsTmuxSession returns (below).
|
|
7203
|
-
// Not there: refused. Found elsewhere: the launch runs that one, and records it. Every executable
|
|
7204
|
-
// named bare (the harness's name, a declared name) is looked up again, also one the plan could only
|
|
7205
|
-
// look up on this process's PATH; a recorded (frozen) or a declared path never is.
|
|
7206
|
-
const lookAgain = (pane) => {
|
|
7207
|
-
if (!launchPlan || launchPlan.config?.frozen || launchPlan.config?.executable?.includes("/")) return false;
|
|
7208
|
-
const { config, launchChoice } = launchPlan;
|
|
7209
|
-
const actual = resolveLaunchExecutable({ harness: launchPlan.harness, declared: config?.executable, declaringDir: config?.source, lookup: launchLookup(launchEnvironment({ configEnv: config?.env, configName: config?.name, env: o.env || process.env, pane, cwd: realHome })) });
|
|
7210
|
-
if (!actual.path) throw executableNotOnPanePath(actual, { harness: launchPlan.harness, config, from: launchChoice?.from, at: launchChoice?.at });
|
|
7211
|
-
const bad = checkLaunchExecutable(actual.path);
|
|
7212
|
-
if (bad) throw oatsError("E_LAUNCH_EXECUTABLE", `launch configuration ${config?.name || "(harness default)"}: ${bad}; nothing was started`);
|
|
7213
|
-
launchPlan.executablePaneSide = !!actual.lookup;
|
|
7214
|
-
if (actual.path === launchPlan.recipe.executable) return false;
|
|
7215
|
-
launchPlan.recipe = { ...launchPlan.recipe, executable: actual.path };
|
|
7216
|
-
command = launchPlan.command = renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome });
|
|
7217
|
-
return true;
|
|
7218
|
-
};
|
|
7219
|
-
/** The launch runs another program than the hooks that have run were handed: said, and kept in the home. */
|
|
7220
|
-
const noteReplacedExecutable = () => {
|
|
7221
|
-
const replaced = replacedExecutableWarning(handedExecutable, launchPlan?.recipe.executable);
|
|
7222
|
-
if (!replaced) return;
|
|
7223
|
-
handedExecutable = undefined;
|
|
7224
|
-
hookDialogClaims = voidedDialogClaims(hookDialogClaims);
|
|
7225
|
-
warnings.push(replaced);
|
|
7226
|
-
appendEvent(realHome, { kind: "launch-warning", data: { message: replaced } });
|
|
7227
|
-
};
|
|
7228
|
-
lookAgain(retained ? () => paneEnvironment(target.socket, target.session, o.io, realHome) : () => expectedPaneEnvironment(tmuxSessionPlan, planSession, o.io, realHome));
|
|
7229
|
-
// Every preflight has passed: the preview-aware launch hooks run for real
|
|
7230
|
-
// (they may register the home with their provider), before a restart's
|
|
7231
|
-
// stop, and must contribute exactly what they contributed as a preview,
|
|
7232
|
-
// which is what the command was rendered and preflighted from, except the
|
|
7233
|
-
// values of the env their preview declared volatile: those come from this
|
|
7234
|
-
// run, and the command is rendered again with them.
|
|
7235
|
-
if (launchHooksPass) {
|
|
7236
|
-
const { previewed, volatileEnv, trustHome, ...pass } = launchHooksPass;
|
|
7237
|
-
// The looks above have settled what this start expects: that is what its real hooks are handed.
|
|
7238
|
-
const handed = harnessExecutableEnv(launchPlan.recipe.executable, launchPlan.executablePaneSide);
|
|
7239
|
-
// Hooks that ran for real in the plan were handed the plan's: their statements don't reach this one.
|
|
7240
|
-
if (handed.OATS_HARNESS_EXECUTABLE !== handedExecutable) hookDialogClaims = voidedDialogClaims(hookDialogClaims);
|
|
7241
|
-
handedExecutable = handed.OATS_HARNESS_EXECUTABLE;
|
|
7242
|
-
const real = prepareLaunchHooks({ ...pass, extraEnv: handed, home: realHome, meta, assertRoots: checkRoots, pass: "real" });
|
|
7243
|
-
const canon = (v) => canonicalJson(JSON.parse(JSON.stringify(v ?? null)));
|
|
7244
|
-
const stable = (h) => Object.fromEntries(Object.entries(h.env).filter(([n]) => !volatileEnv.includes(n)));
|
|
7245
|
-
if (canon({ launch: real.launch, env: stable(real), contributions: real.contributions }) !== canon({ launch: previewed.launch, env: stable(previewed), contributions: previewed.contributions })) {
|
|
7246
|
-
// A provider's row names its env; the values are in the merged env.
|
|
7247
|
-
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]) }); };
|
|
7248
|
-
const differing = [...new Set([...real.contributions, ...previewed.contributions].map((c) => c.capability))].filter((id) => rowOf(real, id) !== rowOf(previewed, id));
|
|
7249
|
-
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`);
|
|
7441
|
+
checkRoots();
|
|
7442
|
+
recordEnv();
|
|
7443
|
+
writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
|
|
7444
|
+
promptDispatched = !!launchController;
|
|
7445
|
+
try {
|
|
7446
|
+
const output = tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, privateWindowCommand(windowCmd), ...markAgentPane(window, state.paneId), ...(launchController || watchResume ? [";", "display-message", "-p", "-t", state.paneId, LAUNCH_PANE_FORMAT] : [])], o.io, oatsWindowEnvironment());
|
|
7447
|
+
if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
|
|
7448
|
+
if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
|
|
7250
7449
|
}
|
|
7251
|
-
|
|
7252
|
-
|
|
7253
|
-
|
|
7254
|
-
|
|
7255
|
-
|
|
7256
|
-
// and the answer carries them.
|
|
7257
|
-
warnings = [...warnings, ...real.warnings];
|
|
7258
|
-
for (const message of real.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
|
|
7450
|
+
catch (e) { envHandoff?.remove(); throw launchFailure(e); }
|
|
7451
|
+
reused = "pane";
|
|
7452
|
+
} else {
|
|
7453
|
+
const instancesRoot = dirname(realHome);
|
|
7454
|
+
const hq = existsSync(dirname(dirname(instancesRoot))) ? dirname(dirname(instancesRoot)) : realHome;
|
|
7259
7455
|
checkRoots();
|
|
7260
|
-
|
|
7261
|
-
|
|
7262
|
-
|
|
7263
|
-
|
|
7264
|
-
|
|
7265
|
-
|
|
7266
|
-
|
|
7267
|
-
|
|
7268
|
-
|
|
7269
|
-
|
|
7270
|
-
|
|
7271
|
-
|
|
7272
|
-
|
|
7273
|
-
|
|
7274
|
-
|
|
7275
|
-
// retire does), so a relaunch that fails, or a process that dies before it, leaves a home
|
|
7276
|
-
// that reads `stopped`, never `lost`: no resume brings back what was being restarted. The
|
|
7277
|
-
// relaunch records a new start, which the record does not name. A stop refused here leaves
|
|
7278
|
-
// the record with the harness running: should that harness die later, the home reads
|
|
7279
|
-
// `stopped`. A record that cannot be written (a full disk) does not block the restart.
|
|
7280
|
-
try { recordStop(realHome, null); } catch { /* see above */ }
|
|
7281
|
-
stopReceipt = stopHarness(target, { graceMs: o.stopGraceMs ?? 20000, io: o.io, kill: o.io?.kill, sleep: o.io?.sleep });
|
|
7282
|
-
writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe.launchConfig ?? null, model: model ?? null } }, 0o600);
|
|
7283
|
-
appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
|
|
7284
|
-
if (!stopReceipt.exited) throw oatsError("E_SESSION_STOP_FAILED", `${meta.instance} was asked to stop (${stopReceipt.signal} to ${stopReceipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")} at ${stopReceipt.sentAt}) and was still running after ${stopReceipt.waitedMs} ms (${stopReceipt.state}); nothing was escalated and nothing was started; stop it yourself, or retry with a longer --stop-grace. Receipt: ${join(realHome, ".oats-restart.json")}`);
|
|
7285
|
-
try { state = inspectSessionTarget(target, o.io); }
|
|
7456
|
+
// A replacement window (never launched, recorded window gone, recorded server gone) is created
|
|
7457
|
+
// on the OATS server, wherever the home was recorded: one socket from here to the record.
|
|
7458
|
+
const recordedSocket = socket ? resolve(socket) : null;
|
|
7459
|
+
socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
|
|
7460
|
+
// One read of the pane's environment answers both: the executable and the scope.
|
|
7461
|
+
const pane = paneEnvironment(socket, session, o.io, realHome);
|
|
7462
|
+
loginOn(pane);
|
|
7463
|
+
const looked = lookAgain(() => pane);
|
|
7464
|
+
if (looked) planExtra.launch = launchPlan.recipe;
|
|
7465
|
+
noteReplacedExecutable();
|
|
7466
|
+
if (hookDialogClaims) planExtra.hookDialogClaims = hookDialogClaims;
|
|
7467
|
+
const scope = scopeOn(pane);
|
|
7468
|
+
if (looked || scope) windowCmd = windowCommand(scope);
|
|
7469
|
+
let names;
|
|
7470
|
+
try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
|
|
7286
7471
|
catch (e) {
|
|
7287
|
-
|
|
7288
|
-
|
|
7289
|
-
else throw oatsError("E_SESSION_UNKNOWN", `after the stop, cannot establish the state of ${meta.instance}, so nothing was started: ${lost.why ?? (String(e.stderr ?? e.message ?? "").trim() || e.message)}`);
|
|
7472
|
+
if (isKernelCode(e?.code)) throw e;
|
|
7473
|
+
throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
|
|
7290
7474
|
}
|
|
7291
|
-
if (
|
|
7292
|
-
|
|
7293
|
-
|
|
7294
|
-
|
|
7295
|
-
|
|
7296
|
-
|
|
7297
|
-
|
|
7298
|
-
|
|
7299
|
-
|
|
7300
|
-
|
|
7301
|
-
|
|
7302
|
-
|
|
7303
|
-
let launchController;
|
|
7304
|
-
let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
|
|
7305
|
-
// A resumed Claude session is watched for its resume-cost dialog once it runs (after the record):
|
|
7306
|
-
// the pane's identity is read at its creation, as the controller reads it.
|
|
7307
|
-
const watchResume = !!resume?.sessionId && launchPlan.harness === "claude";
|
|
7308
|
-
let resumeTarget = null;
|
|
7309
|
-
checkRoots();
|
|
7310
|
-
// The names this launch removes, from the recipe it runs (a preview-aware hook's real run included).
|
|
7311
|
-
// A home without a recipe (an earlier kernel's) composes no providers at launch: nothing.
|
|
7312
|
-
const removed = launchPlan ? removedLaunchEnv({ declared: launchPlan.declaredEnv, hooksEnv: launchPlan.recipe.hooks?.env, configEnv: launchPlan.recipe.env }) : [];
|
|
7313
|
-
// The launch's one native start; every render of its window command reuses it.
|
|
7314
|
-
const nativeStart = prepareNativeStart(realHome, launchPlan?.harness || harness);
|
|
7315
|
-
// What the window runs: the planned command, or, for a resume that found its conversation, the same
|
|
7316
|
-
// recipe rendered with the harness's resume selector and the resume notice. Only the window carries
|
|
7317
|
-
// it: instance.json, the pending receipt and the recipe keep the ordinary launch, so a later start
|
|
7318
|
-
// opens a fresh conversation (and the native-record roots never see a recorded --session).
|
|
7319
|
-
const executedCommand = () => resume?.sessionId ? renderLaunchRecipe(launchPlan.recipe, { home: realHome, instance: meta.instance, trustHome: launchPlan.trustHome, resume: { sessionId: resume.sessionId, prompt: RESUME_NOTICE } }) : command;
|
|
7320
|
-
const windowCommand = (scope) => paneCommand(exitMarked(nativeRecordCommand(executedCommand(), realHome, launchPlan?.harness || harness, { start: nativeStart, scope }), id, exitedPath), removed);
|
|
7321
|
-
// Whether the harness runs in a scope of its own (nativeRecordCommand), judged on the pane it
|
|
7322
|
-
// will run in for the command it runs; a warning is said, and is an event once the start is recorded.
|
|
7323
|
-
let unscoped = null;
|
|
7324
|
-
const scopeOn = (pane) => {
|
|
7325
|
-
// The caller's own io (a test's), not the guarded one every start runs with.
|
|
7326
|
-
const scope = agentScopeOn(command, { pane, removed, refs: paneEnv }, rawIo);
|
|
7327
|
-
if (scope.warning) warnings.push(unscoped = scope.warning);
|
|
7328
|
-
return scope.wrapper;
|
|
7329
|
-
};
|
|
7330
|
-
let reused = "new";
|
|
7331
|
-
const session = target?.session || meta.tmux?.session || DEFAULT_TMUX_SESSION;
|
|
7332
|
-
const window = target?.window || meta.tmux?.window || meta.instance;
|
|
7333
|
-
let socket = target?.socket || meta.tmux?.socket;
|
|
7334
|
-
let windowCmd = windowCommand();
|
|
7335
|
-
let moved = null;
|
|
7336
|
-
// A fallback shell (no harness descendant) or a retained dead pane is
|
|
7337
|
-
// the agent's own pane (resolveAgentPane): the command runs there, on the
|
|
7338
|
-
// server the home recorded, no other window or pane touched and no option
|
|
7339
|
-
// set but that pane's mark.
|
|
7340
|
-
const inPlace = state.paneId && (state.present || state.state === "stopped");
|
|
7341
|
-
try {
|
|
7342
|
-
if (inPlace) {
|
|
7343
|
-
const scope = scopeOn(paneEnvironment(socket, session, o.io, realHome));
|
|
7344
|
-
if (scope) windowCmd = windowCommand(scope);
|
|
7345
|
-
launchController = makeLaunchController();
|
|
7346
|
-
if (launchController) {
|
|
7347
|
-
try {
|
|
7348
|
-
const oldTarget = launchPromptTransport(o.io).identity(socket, state.paneId);
|
|
7349
|
-
beforeRespawn = launchController.captureBeforeRespawn(oldTarget);
|
|
7350
|
-
} catch { /* a missing prior capture can never authorize input */ }
|
|
7351
|
-
}
|
|
7352
|
-
checkRoots();
|
|
7353
|
-
recordEnv();
|
|
7354
|
-
writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
|
|
7355
|
-
promptDispatched = !!launchController;
|
|
7356
|
-
try {
|
|
7357
|
-
const output = tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, ...paneEnvFlags, windowCmd, ...markAgentPane(window, state.paneId), ...(launchController || watchResume ? [";", "display-message", "-p", "-t", state.paneId, LAUNCH_PANE_FORMAT] : [])], o.io, oatsWindowEnvironment());
|
|
7358
|
-
if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
|
|
7359
|
-
if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
|
|
7360
|
-
}
|
|
7361
|
-
catch (e) { throw launchFailure(e); }
|
|
7362
|
-
reused = "pane";
|
|
7363
|
-
} else {
|
|
7364
|
-
const instancesRoot = dirname(realHome);
|
|
7365
|
-
const hq = existsSync(dirname(dirname(instancesRoot))) ? dirname(dirname(instancesRoot)) : realHome;
|
|
7366
|
-
checkRoots();
|
|
7367
|
-
// A replacement window (never launched, recorded window gone, recorded server gone) is created
|
|
7368
|
-
// on the OATS server, wherever the home was recorded: one socket from here to the record.
|
|
7369
|
-
const recordedSocket = socket ? resolve(socket) : null;
|
|
7370
|
-
socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan, missingSocket, warnings);
|
|
7371
|
-
// One read of the pane's environment answers both: the executable and the scope.
|
|
7372
|
-
const pane = paneEnvironment(socket, session, o.io, realHome);
|
|
7373
|
-
const looked = lookAgain(() => pane);
|
|
7374
|
-
if (looked) planExtra.launch = launchPlan.recipe;
|
|
7375
|
-
noteReplacedExecutable();
|
|
7376
|
-
if (hookDialogClaims) planExtra.hookDialogClaims = hookDialogClaims;
|
|
7377
|
-
const scope = scopeOn(pane);
|
|
7378
|
-
if (looked || scope) windowCmd = windowCommand(scope);
|
|
7379
|
-
let names;
|
|
7380
|
-
try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
|
|
7381
|
-
catch (e) {
|
|
7382
|
-
if (isKernelCode(e?.code)) throw e;
|
|
7383
|
-
throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
|
|
7384
|
-
}
|
|
7385
|
-
if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
|
|
7386
|
-
target = { backend: "tmux", session, window, socket };
|
|
7387
|
-
launchController = makeLaunchController();
|
|
7388
|
-
checkRoots();
|
|
7389
|
-
recordEnv();
|
|
7390
|
-
writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
|
|
7391
|
-
promptDispatched = !!launchController;
|
|
7392
|
-
try {
|
|
7393
|
-
const output = tmuxOn(socket, ["new-window", "-P", "-F", launchController || watchResume ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, ...paneEnvFlags, windowCmd, ...markAgentPane(window)], o.io, oatsWindowEnvironment()).trim();
|
|
7394
|
-
if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
|
|
7395
|
-
if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
|
|
7396
|
-
prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : watchResume ? output.split("\t")[0] : output, o.io);
|
|
7397
|
-
}
|
|
7398
|
-
catch (e) { throw launchFailure(e); }
|
|
7399
|
-
if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
|
|
7475
|
+
if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
|
|
7476
|
+
target = { backend: "tmux", session, window, socket };
|
|
7477
|
+
launchController = makeLaunchController();
|
|
7478
|
+
checkRoots();
|
|
7479
|
+
recordEnv();
|
|
7480
|
+
writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
|
|
7481
|
+
promptDispatched = !!launchController;
|
|
7482
|
+
try {
|
|
7483
|
+
const output = tmuxOn(socket, ["new-window", "-P", "-F", launchController || watchResume ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, privateWindowCommand(windowCmd), ...markAgentPane(window)], o.io, oatsWindowEnvironment()).trim();
|
|
7484
|
+
if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
|
|
7485
|
+
if (watchResume) resumeTarget = resumePaneTarget(target, socket, output);
|
|
7486
|
+
prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : watchResume ? output.split("\t")[0] : output, o.io);
|
|
7400
7487
|
}
|
|
7401
|
-
|
|
7402
|
-
if (
|
|
7403
|
-
}
|
|
7404
|
-
|
|
7405
|
-
|
|
7406
|
-
|
|
7407
|
-
|
|
7408
|
-
|
|
7409
|
-
|
|
7410
|
-
|
|
7411
|
-
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
|
|
7415
|
-
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
|
|
7420
|
-
|
|
7421
|
-
|
|
7422
|
-
|
|
7423
|
-
|
|
7424
|
-
|
|
7425
|
-
|
|
7426
|
-
|
|
7427
|
-
|
|
7428
|
-
|
|
7429
|
-
|
|
7430
|
-
|
|
7431
|
-
|
|
7432
|
-
if (
|
|
7433
|
-
|
|
7434
|
-
|
|
7435
|
-
|
|
7436
|
-
|
|
7437
|
-
|
|
7438
|
-
|
|
7439
|
-
|
|
7440
|
-
|
|
7441
|
-
|
|
7442
|
-
|
|
7443
|
-
}
|
|
7444
|
-
|
|
7445
|
-
|
|
7446
|
-
|
|
7447
|
-
|
|
7448
|
-
|
|
7449
|
-
|
|
7450
|
-
|
|
7488
|
+
catch (e) { envHandoff?.remove(); throw launchFailure(e); }
|
|
7489
|
+
if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
|
|
7490
|
+
}
|
|
7491
|
+
if (launchController) launchPrompts = inPlace ? launchController.observeRespawn(launchPromptTarget, beforeRespawn) : launchController.observeNew(launchPromptTarget);
|
|
7492
|
+
if (launchPrompts?.status === "flag-ignored") { launchPrompts = channelsUnavailable(id, launchPrompts); warnings = flagIgnoredWarnings(warnings); }
|
|
7493
|
+
} catch (error) {
|
|
7494
|
+
if (!promptDispatched) throw error;
|
|
7495
|
+
launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
|
|
7496
|
+
}
|
|
7497
|
+
target = { backend: "tmux", session, window, socket: resolve(socket) };
|
|
7498
|
+
if (launchPrompts) {
|
|
7499
|
+
try { assertLaunchHome(realHome, originalHomeIdentity); }
|
|
7500
|
+
catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch home identity changed; metadata retained at original home", launchPrompts, originalHomeIdentity)); }
|
|
7501
|
+
planExtra.launchPrompts = launchPrompts;
|
|
7502
|
+
planExtra.launchPromptTarget = launchPromptTarget ?? target;
|
|
7503
|
+
// Recovery retains evidence but never reconstructs this invocation's answer authority.
|
|
7504
|
+
try { writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600); }
|
|
7505
|
+
catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt pending receipt incomplete", launchPrompts, originalHomeIdentity)); }
|
|
7506
|
+
}
|
|
7507
|
+
// The session exists: its boundary (lib/instance-events.mjs) is recorded
|
|
7508
|
+
// now, before the metadata, so a start whose metadata write fails still
|
|
7509
|
+
// voids the claims of the session it replaced; its adoption only completes a log it missed.
|
|
7510
|
+
// The planned recipe names the configuration (null: the bare harness), never the recorded recipe's.
|
|
7511
|
+
recordStartBoundary(realHome, { startId: id, startedAt, harness: launchPlan?.harness || harness, backend: "tmux", launchConfig: launchPlan?.recipe.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
|
|
7512
|
+
// Keep launch evidence until the command exits or the target disappears.
|
|
7513
|
+
// A transient child (for example the native-start recorder) is not proof that startup
|
|
7514
|
+
// has finished. A later start reconciles the receipt without a watcher.
|
|
7515
|
+
let done;
|
|
7516
|
+
try { done = record(meta, { id, target, model, command, startedAt, reused, ...planExtra, ...(stopReceipt ? { stop: stopReceipt } : {}) }, false); }
|
|
7517
|
+
catch (e) {
|
|
7518
|
+
if (launchPrompts) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt metadata recording incomplete", launchPrompts, originalHomeIdentity));
|
|
7519
|
+
if (e.code && String(e.code).startsWith("E_")) throw e;
|
|
7520
|
+
throw oatsError("E_SESSION_START_INCOMPLETE", `${meta.instance} was started (tmux ${target.session}:${target.window} on ${target.socket}) but its metadata could not be recorded: ${e.message}; the actual target is kept in ${pendingPath} and the next start adopts it instead of allocating another`);
|
|
7521
|
+
}
|
|
7522
|
+
if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
|
|
7523
|
+
// As spawn says it once launched: a start refused before this point leaves no event.
|
|
7524
|
+
if (unscoped) appendEvent(realHome, { kind: "launch-warning", data: { message: unscoped } });
|
|
7525
|
+
if (envUnverified) appendEvent(realHome, { kind: "launch-warning", data: { message: envUnverified } });
|
|
7526
|
+
// Said once the new socket is recorded: a start that could not record leaves it to the adoption.
|
|
7527
|
+
if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
|
|
7528
|
+
// A resume answers what it continued. A resumed Claude session that stops at its resume-cost dialog
|
|
7529
|
+
// is a start that succeeded and waits for its human: reported (`waiting`), never answered.
|
|
7530
|
+
const waiting = resumeTarget && watchResumeConfirmation({ transport: launchPromptTransport(o.io), target: resumeTarget, notice: RESUME_NOTICE, ...(o.io?.now ? { now: o.io.now } : {}), ...(o.io?.sleep ? { sleep: o.io.sleep } : {}) }).waiting === RESUME_WAITING.RESUME_CONFIRMATION ? RESUME_WAITING.RESUME_CONFIRMATION : null;
|
|
7531
|
+
const resumed = resume ? { resume: resumeAnswer(resume, waiting) } : {};
|
|
7532
|
+
return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings], ...resumed };
|
|
7533
|
+
}
|
|
7534
|
+
/** What a start, holding the home's lifecycle claim (startClaimed), refuses at `lock`, the home's
|
|
7535
|
+
* `.oats-start.lock`. Two starts exclude each other through that claim, and a start makes
|
|
7536
|
+
* nothing at this path. An upgrade writes its regular file there and keeps it until its final
|
|
7537
|
+
* receipt is persisted (lib/instance-upgrade.mjs), so a file is an upgrade that has not finished,
|
|
7538
|
+
* answered with its retry and never removed here. A directory is the start lock of an earlier
|
|
7539
|
+
* OATS, which made one for each start: refused, named, and never removed. Anything else there is
|
|
7540
|
+
* refused and named. Every refusal is before any effect: E_SESSION_START_BUSY for the upgrade,
|
|
7541
|
+
* which its retry ends, and E_SESSION_START_LOCK_STUCK for the rest, which only a person can
|
|
7542
|
+
* end, so that an unattended caller (a scheduled start, the resume sweep) never waits it out as
|
|
7543
|
+
* a start that runs. */
|
|
7544
|
+
function refuseStartMutex(home, lock) {
|
|
7545
|
+
let entry;
|
|
7546
|
+
try { entry = lstatSync(lock); } catch (e) { if (e.code === "ENOENT") return; throw e; }
|
|
7547
|
+
const retry = entry.isFile() ? upgradeMutexRetry(home) : null;
|
|
7548
|
+
if (retry) throw oatsError("E_SESSION_START_BUSY", `a package upgrade of ${basename(home)} holds the start mutex (${lock}); nothing was stopped or started. Retry ${retry} to finish the upgrade before starting`);
|
|
7549
|
+
if (entry.isDirectory()) throw oatsError("E_SESSION_START_LOCK_STUCK", `${lock} is the start lock directory of an earlier OATS; nothing was stopped or started. Once no earlier oats is running, remove that directory and retry`);
|
|
7550
|
+
throw oatsError("E_SESSION_START_LOCK_STUCK", `${lock} is neither a package upgrade's file nor an earlier OATS's start lock directory; nothing was stopped or started. Remove it and retry`);
|
|
7451
7551
|
}
|
|
7452
7552
|
|
|
7453
7553
|
/** One Git call of a retirement inspection → its stdout, as bytes: a text
|
|
@@ -8689,7 +8789,7 @@ function copyRecoveryHome(observation, dest) {
|
|
|
8689
8789
|
// The launch environment's key and the digests made with it never leave the home
|
|
8690
8790
|
// (lib/start-env.mjs): a recovery copy leaves them, and any temporary file of theirs, out.
|
|
8691
8791
|
const excludeRoot = new Set(observation.homeExclude || ["work"]);
|
|
8692
|
-
for (const name of readdirSync(observation.home)) if (name === START_ENV_FILE || name === START_ENV_KEY_FILE || START_ENV_TMP.test(name)) excludeRoot.add(name);
|
|
8792
|
+
for (const name of readdirSync(observation.home)) if (name === START_ENV_FILE || name === START_ENV_KEY_FILE || START_ENV_TMP.test(name) || LAUNCH_ENV_HANDOFF.test(name)) excludeRoot.add(name);
|
|
8693
8793
|
copyRecoveryTree(observation.home, dest, { excludeRoot });
|
|
8694
8794
|
if (storedTreeDigest(observation.home, BASELINE_DIGEST_VERSION, { excludeRoot, instanceHome: true }) !== storedTreeDigest(dest, BASELINE_DIGEST_VERSION, { instanceHome: true })) {
|
|
8695
8795
|
throw new Error("home recovery verification disagreed with the source");
|
|
@@ -9144,7 +9244,8 @@ const COMPLETES_DEFERRED = Symbol("the completion of a deferred self-retire");
|
|
|
9144
9244
|
export const SCHEDULING_WAIT_MS = 10 * 60 * 1000;
|
|
9145
9245
|
/** How long a completion pauses between two looks at the claim its scheduling still holds. */
|
|
9146
9246
|
const SCHEDULING_PAUSE_MS = 50;
|
|
9147
|
-
|
|
9247
|
+
// The refusal of retire --delete-branch: the CLI's (lib/command-flags.mjs) and retireInstance's.
|
|
9248
|
+
export { RETIRE_DELETE_BRANCH_REFUSED };
|
|
9148
9249
|
|
|
9149
9250
|
/** Run by the detached child: wait for the caller's window to be gone, then
|
|
9150
9251
|
* retire the instance as an ordinary external operator. Returns true only
|
|
@@ -9159,7 +9260,11 @@ export const RETIRE_DELETE_BRANCH_REFUSED = "oats retire no longer deletes branc
|
|
|
9159
9260
|
* hooks ran, the usual quarantine stays too); otherwise it goes, and the instance is a stopped or
|
|
9160
9261
|
* running instance like any other, not one that reads RETIRING for a retire that is not happening.
|
|
9161
9262
|
* How far the retire got is read from what it answers (`details.reached`, retireFailure), never
|
|
9162
|
-
* from its code.
|
|
9263
|
+
* from its code.
|
|
9264
|
+
*
|
|
9265
|
+
* A retire whose cleanup is left incomplete by retire hooks alone is tried again first, up to three
|
|
9266
|
+
* times (RETIRE_RETRY_DELAYS_MS; awebai/oats#1747), before that outcome is written, and then the
|
|
9267
|
+
* outcome says how many attempts ran (`attempts`). An outcome after no retry is as it was. */
|
|
9163
9268
|
export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
|
|
9164
9269
|
let intent = intentOrMarkerPath;
|
|
9165
9270
|
if (typeof intentOrMarkerPath === "string") {
|
|
@@ -9244,40 +9349,110 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
|
|
|
9244
9349
|
if (!written.ok) console.error(`deferred retirement of ${intent.instance}: its retire-refused event could not be written: ${written.reason ?? (written.results ?? []).map((r) => `${r.path}: ${r.reason}`).join("; ")}`);
|
|
9245
9350
|
return false;
|
|
9246
9351
|
};
|
|
9247
|
-
|
|
9248
|
-
|
|
9249
|
-
|
|
9250
|
-
|
|
9251
|
-
|
|
9252
|
-
|
|
9253
|
-
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
9257
|
-
|
|
9258
|
-
|
|
9259
|
-
|
|
9260
|
-
|
|
9261
|
-
|
|
9262
|
-
|
|
9263
|
-
|
|
9264
|
-
|
|
9265
|
-
|
|
9266
|
-
|
|
9267
|
-
|
|
9268
|
-
|
|
9269
|
-
|
|
9270
|
-
|
|
9271
|
-
|
|
9272
|
-
|
|
9352
|
+
const retry = `oats retire ${intent.instance}${intent.options?.home ? ` --home ${intent.options.home}` : ""}`;
|
|
9353
|
+
const retireOnce = (underClaim) => retireInstance(intent.root, intent.instance, {
|
|
9354
|
+
home: intent.options?.home, keepDir: !!intent.options?.keepDir, tmuxSession: intent.options?.tmuxSession,
|
|
9355
|
+
...(Array.isArray(intent.options?.plannedExtraWorktrees) ? { plannedExtraWorktrees: intent.options.plannedExtraWorktrees } : {}),
|
|
9356
|
+
...(Array.isArray(intent.options?.children) ? { children: intent.options.children } : {}),
|
|
9357
|
+
...(obsoleteDeleteBranch ? { [OBSOLETE_DELETE_BRANCH]: true } : {}),
|
|
9358
|
+
// The retire that scheduled this completion was waited for above. Any other live holder of
|
|
9359
|
+
// the claim is waited for by the retire itself, for the time a completion's retire has
|
|
9360
|
+
// always waited, and then answers as for every retire.
|
|
9361
|
+
[COMPLETES_DEFERRED]: true,
|
|
9362
|
+
...(underClaim ? { [RETIRE_UNDER_CLAIM]: underClaim } : {}),
|
|
9363
|
+
});
|
|
9364
|
+
// A retire whose cleanup is incomplete with retire hooks alone owed (RETIRE_HOOK_DEBT_ONLY) is
|
|
9365
|
+
// tried again, after each delay of RETIRE_RETRY_DELAYS_MS (`opts.retryDelaysMs` for a test), as a
|
|
9366
|
+
// plain retire like the first: it takes the claim, and its quarantine retry clears only when the
|
|
9367
|
+
// hooks are shown to have run. Every attempt records its own `retired` row. The retries stop at the
|
|
9368
|
+
// first that answers an error or whose cleanup owes more than retire hooks, and before any retry
|
|
9369
|
+
// whose home is gone or whose pending marker is no longer this completion's (another `requestedAt`,
|
|
9370
|
+
// or none): that is checked after the wait, and again by the retry itself once it holds the home's
|
|
9371
|
+
// claim, before it reads or does anything. While it waits, the completion keeps its retry state at
|
|
9372
|
+
// retireRetryPath, which another retire's refusal reads (refusePendingCompletion); it removes that
|
|
9373
|
+
// file on every way out.
|
|
9374
|
+
const delays = (Array.isArray(opts.retryDelaysMs) ? opts.retryDelaysMs : RETIRE_RETRY_DELAYS_MS).map((ms) => Math.max(0, Number(ms) || 0));
|
|
9375
|
+
const attempts = 1 + delays.length;
|
|
9376
|
+
const retryPath = home ? retireRetryPath(home) : null;
|
|
9377
|
+
const dropRetryState = () => {
|
|
9378
|
+
if (!retryPath) return;
|
|
9379
|
+
try { rmSync(retryPath, { force: true }); } catch (e) { console.error(`deferred retirement: cannot remove ${retryPath}: ${e.message}`); }
|
|
9380
|
+
};
|
|
9381
|
+
/** Why the home may not be retried now, or null: it is there, and its pending marker is still the
|
|
9382
|
+
* one of this completion's scheduling. */
|
|
9383
|
+
const notOwed = () => {
|
|
9384
|
+
if (!home) return "its intent names no home";
|
|
9385
|
+
if (!existsSync(home)) return "its home is gone";
|
|
9386
|
+
const marker = readJsonOrUndefined(retirePendingMarkerPath(home));
|
|
9387
|
+
if (!isPlainObject(marker) || typeof intent.requestedAt !== "string" || marker.requestedAt !== intent.requestedAt) return "its pending marker is no longer this completion's";
|
|
9388
|
+
return null;
|
|
9389
|
+
};
|
|
9390
|
+
/** Why the retire whose attempt `attempt` left `result` is not tried again, or null when it is. */
|
|
9391
|
+
const notRetried = (attempt, result) => {
|
|
9392
|
+
if (!result[RETIRE_HOOK_DEBT_ONLY]) return "its cleanup owes more than retire hooks";
|
|
9393
|
+
if (attempt >= attempts) return "it was the last attempt";
|
|
9394
|
+
return notOwed();
|
|
9395
|
+
};
|
|
9396
|
+
const items = (result) => result.rollbackIncomplete.join("; ");
|
|
9397
|
+
/** The way out of a retire left incomplete after `run` attempts → false. `said` is the log's line
|
|
9398
|
+
* for it: none for a first attempt that owes more than hooks, which says what it said before. */
|
|
9399
|
+
const incomplete = (run, result, said) => {
|
|
9400
|
+
if (said) console.error(said);
|
|
9273
9401
|
// A result and not an error, so it has no code. The retire worked on the home and left it
|
|
9274
9402
|
// quarantined: the home is changed. The items are text of hooks and of Git, which the outcome
|
|
9275
9403
|
// and the log hold and the event does not.
|
|
9276
|
-
|
|
9404
|
+
dropRetryState();
|
|
9405
|
+
notCompleted({ ok: false, result, retry, ...(run > 1 ? { attempts: run } : {}) },
|
|
9277
9406
|
{ code: null, homeChanged: true, sentence: RETIRE_INCOMPLETE_SENTENCE(intent.instance) });
|
|
9278
9407
|
console.error(`deferred retirement of ${intent.instance} is INCOMPLETE; the home is retained:\n ${result.rollbackIncomplete.join("\n ")}`);
|
|
9279
9408
|
return false;
|
|
9280
|
-
}
|
|
9409
|
+
};
|
|
9410
|
+
/** What a retry throws under the home's claim when the home is no longer owed it: nothing was done.
|
|
9411
|
+
* Never answered as it is: the completion knows it by identity, and an answer code passes through
|
|
9412
|
+
* retireInstance unwrapped. */
|
|
9413
|
+
const cancelled = lifecycleBusy("none", `the retry of the retirement of ${intent.instance} was not started: its pending marker is no longer this completion's; nothing was done`,
|
|
9414
|
+
"nothing to do: the scheduling that marker names owns the retirement now", { instance: intent.instance, home });
|
|
9415
|
+
const ownStart = processStartToken(process.pid);
|
|
9416
|
+
let result;
|
|
9417
|
+
for (let attempt = 1; ; attempt++) {
|
|
9418
|
+
if (attempt > 1) {
|
|
9419
|
+
const why = notOwed();
|
|
9420
|
+
if (why) return incomplete(attempt - 1, result, `deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is not started: ${why}`);
|
|
9421
|
+
}
|
|
9422
|
+
const last = result;
|
|
9423
|
+
try {
|
|
9424
|
+
result = retireOnce(attempt > 1 ? () => { if (notOwed()) throw cancelled; } : undefined);
|
|
9425
|
+
} catch (e) {
|
|
9426
|
+
if (e === cancelled) return incomplete(attempt - 1, last, `deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is not started: ${notOwed() ?? "its pending marker was not this completion's under the home's claim"}`);
|
|
9427
|
+
const code = kernelCode(e, "E_LIFECYCLE_FAILED");
|
|
9428
|
+
// An answer without `reached` is one in which the retire of the home had not begun (retireInstance).
|
|
9429
|
+
// A retry's home was changed by the attempts before it: their hooks ran, and it is quarantined.
|
|
9430
|
+
const reached = e?.details?.reached;
|
|
9431
|
+
const homeChanged = attempt > 1 || (isPlainObject(reached) && (reached.hooksStarted === true || reached.home !== "kept"));
|
|
9432
|
+
dropRetryState();
|
|
9433
|
+
notCompleted({ ok: false, error: { code, message: e.message }, ...(e.details?.childrenStopped ? { childrenStopped: e.details.childrenStopped } : {}), ...(obsoleteDeleteBranch ? { warnings: [OBSOLETE_DELETE_BRANCH_SENTENCE] } : {}), retry, ...(attempt > 1 ? { attempts: attempt } : {}) },
|
|
9434
|
+
{ code, homeChanged, sentence: e.message });
|
|
9435
|
+
console.error(`deferred retirement of ${intent.instance} failed${attempt > 1 ? ` on attempt ${attempt} of ${attempts}` : ""}: ${e.message}`);
|
|
9436
|
+
// A defect's stack goes to the completion's log (lib/errors.mjs isDefect).
|
|
9437
|
+
reportDefect(e);
|
|
9438
|
+
return false;
|
|
9439
|
+
}
|
|
9440
|
+
if (obsoleteDeleteBranch && attempt === 1) console.log(OBSOLETE_DELETE_BRANCH_SENTENCE);
|
|
9441
|
+
if (!result.rollbackIncomplete) break;
|
|
9442
|
+
const why = notRetried(attempt, result);
|
|
9443
|
+
// The first attempt of a retire that owes more than hooks says what it said before this rule.
|
|
9444
|
+
if (why) return incomplete(attempt, result, attempt > 1 || result[RETIRE_HOOK_DEBT_ONLY] ? `deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is incomplete (${items(result)}); it is not tried again: ${why}` : null);
|
|
9445
|
+
// When the next attempt starts, and the earliest the last one can: each wait follows the end of
|
|
9446
|
+
// the attempt before it, whose length cannot be known here.
|
|
9447
|
+
const now = Date.now(), wait = delays[attempt - 1];
|
|
9448
|
+
const nextAt = new Date(now + wait).toISOString(), lastAt = new Date(now + delays.slice(attempt - 1).reduce((a, b) => a + b, 0)).toISOString();
|
|
9449
|
+
console.error(`deferred retirement of ${intent.instance}: attempt ${attempt} of ${attempts} is incomplete (${items(result)}); attempt ${attempt + 1} runs at ${nextAt}`);
|
|
9450
|
+
// Without its file the retry still runs; a refusal meanwhile only says less.
|
|
9451
|
+
try { writeFileSync(retryPath, JSON.stringify({ requestedAt: intent.requestedAt, completionPid: process.pid, completionStart: ownStart, attempt: attempt + 1, attempts, nextAt, lastAt }, null, 2) + "\n"); }
|
|
9452
|
+
catch (e) { console.error(`deferred retirement: cannot write ${retryPath}: ${e.message}; it retries without it`); }
|
|
9453
|
+
if (wait) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait);
|
|
9454
|
+
}
|
|
9455
|
+
dropRetryState();
|
|
9281
9456
|
if (intent.options?.keepDir) {
|
|
9282
9457
|
// The kept home is the one the intent names, never a same-named twin.
|
|
9283
9458
|
const retained = intent.options?.home ? { home: intent.options.home } : findInstanceHome(intent.root, intent.instance);
|
|
@@ -9295,6 +9470,21 @@ export function completeDeferredRetirement(intentOrMarkerPath, opts = {}) {
|
|
|
9295
9470
|
* (awebai/oats#693): the CLI cleans that home's wake schedules. A symbol, so
|
|
9296
9471
|
* the printed and JSON receipt, and a recorded one, do not carry it. */
|
|
9297
9472
|
export const RETIRE_SELECTED_HOME = Symbol("oats.retireSelectedHome");
|
|
9473
|
+
/** On retireInstance's result: true when its cleanup is incomplete and what it owes is retire hooks
|
|
9474
|
+
* and nothing else (no Git step, directory preservation, orphaned work directory, or item no rerun
|
|
9475
|
+
* of the hooks can clear). A deferred completion retries only such a retire
|
|
9476
|
+
* (completeDeferredRetirement). A symbol, so the printed and JSON receipts do not carry it. */
|
|
9477
|
+
const RETIRE_HOOK_DEBT_ONLY = Symbol("oats.retireHookDebtOnly");
|
|
9478
|
+
/** How long a deferred completion whose retire owes retire hooks alone waits after each failed
|
|
9479
|
+
* attempt before the next (completeDeferredRetirement): three retries, at about 1, 5 and 15 minutes. */
|
|
9480
|
+
export const RETIRE_RETRY_DELAYS_MS = Object.freeze([60 * 1000, 5 * 60 * 1000, 15 * 60 * 1000]);
|
|
9481
|
+
/** Where a deferred completion keeps its retry state while it waits between attempts, beside the
|
|
9482
|
+
* home: `{ requestedAt, completionPid, completionStart, attempt, attempts, nextAt, lastAt }`.
|
|
9483
|
+
* Kernel-internal. Read only by refusePendingCompletion, and only while the completion it names
|
|
9484
|
+
* is the live one the pending marker names; any retire that removes the home removes it too. */
|
|
9485
|
+
function retireRetryPath(home) {
|
|
9486
|
+
return join(dirname(home), `.oats-retire-retry-${basename(home)}.json`);
|
|
9487
|
+
}
|
|
9298
9488
|
/** An option of retireInstance: a function it calls once it holds the home's claim, has resolved
|
|
9299
9489
|
* the home again and has found no pending self-retire, before it reads anything else. What the
|
|
9300
9490
|
* function throws is the retire's answer, and nothing was done; what it returns, `{ children?,
|
|
@@ -9533,11 +9723,22 @@ function refusePendingCompletion(name, home) {
|
|
|
9533
9723
|
if (live.state === "gone") return;
|
|
9534
9724
|
const start = typeof pending.completionStart === "string" ? pending.completionStart : "none";
|
|
9535
9725
|
const details = { instance: name, home, lock: marker, pid, since: pending.requestedAt ?? null, action: "retire" };
|
|
9536
|
-
if (live.state === "alive") throw lifecycleBusy("running", `a retire of ${name} is already scheduled (its completion, pid ${pid}, requested at ${pending.requestedAt ?? "?"}); nothing was done`, "wait for it to finish", details);
|
|
9726
|
+
if (live.state === "alive") throw lifecycleBusy("running", `a retire of ${name} is already scheduled (its completion, pid ${pid}, requested at ${pending.requestedAt ?? "?"})${retryingSaid(home, pending)}; nothing was done`, "wait for it to finish", details);
|
|
9537
9727
|
throw lifecycleBusy("unknown", `whether the completion of the scheduled retire of ${name} that ${marker} names (pid ${pid}, recorded start ${start}) still runs cannot be read (${live.reason}); nothing was done`,
|
|
9538
9728
|
`check that pid by hand, and if it is not an oats retire, remove ${marker}, then retry`, { ...details, unknown: live.reason });
|
|
9539
9729
|
}
|
|
9540
9730
|
|
|
9731
|
+
/** What a refusal adds while the completion `pending` names waits to retry a cleanup that did not
|
|
9732
|
+
* finish: the clause of its retry state (retireRetryPath) when that file names the same scheduling
|
|
9733
|
+
* and the same completion, else "". Its numbers and times are checked before they are said. */
|
|
9734
|
+
function retryingSaid(home, pending) {
|
|
9735
|
+
const r = readJsonOrUndefined(retireRetryPath(home));
|
|
9736
|
+
if (!isPlainObject(r) || r.requestedAt !== pending.requestedAt || r.completionPid !== pending.completionPid || r.completionStart !== (pending.completionStart ?? null)) return "";
|
|
9737
|
+
if (![r.attempt, r.attempts].every((n) => Number.isSafeInteger(n) && n > 0) || r.attempt > r.attempts) return "";
|
|
9738
|
+
if (![r.nextAt, r.lastAt].every((t) => typeof t === "string" && !Number.isNaN(Date.parse(t)) && new Date(Date.parse(t)).toISOString() === t)) return "";
|
|
9739
|
+
return `; it is retrying cleanup that did not finish: attempt ${r.attempt} of ${r.attempts} runs at ${r.nextAt}, the last no earlier than ${r.lastAt}`;
|
|
9740
|
+
}
|
|
9741
|
+
|
|
9541
9742
|
/** Retire one instance. One retire of a home at a time (awebai/oats#863): the home's claim
|
|
9542
9743
|
* (retireClaimPath; lib/claim.mjs) is taken as soon as the home is resolved, before anything the
|
|
9543
9744
|
* retire acts on is read, and held until this returns or throws. Any other retire of that home
|
|
@@ -10028,6 +10229,10 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10028
10229
|
...(nonEmptyString(meta.soulId) ? { soulId: meta.soulId } : {}),
|
|
10029
10230
|
contextDir: meta.repo, workspaceDir: workspaceOf(root), rootDir: root, resolved, priorMeta: meta.capabilityMeta || {},
|
|
10030
10231
|
});
|
|
10232
|
+
// The hooks ran: their warnings are events now, whatever the retire does
|
|
10233
|
+
// next (a refusal, a quarantine), so an action a hook names outlives the
|
|
10234
|
+
// answer (#1749). Recorded as given, in the workspace log only.
|
|
10235
|
+
for (const message of hookResults.warnings || []) appendEvent(found.home, { kind: RETIRE_HOOK_WARNING_KIND, data: { message } }, { workspaceOnly: true });
|
|
10031
10236
|
}
|
|
10032
10237
|
at.phase = "after-hooks";
|
|
10033
10238
|
at.said = afterHooks;
|
|
@@ -10060,6 +10265,9 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10060
10265
|
// A quarantine retry's outcome apart from Git: what the hooks it reran left undone, and what they owed and
|
|
10061
10266
|
// did not run. Known before the worktree step, which waits for it.
|
|
10062
10267
|
const retryFailures = [];
|
|
10268
|
+
// How many of them no rerun of the retire hooks can clear: a capability with no retire hook, hooks
|
|
10269
|
+
// that cannot be rerun, an orphaned work directory. The rest are hook debt (retireHookDebtOnly).
|
|
10270
|
+
let retryNonHook = 0;
|
|
10063
10271
|
if (quarantine) {
|
|
10064
10272
|
for (const f of hookResults?.failures || []) retryFailures.push(`retire hook ${f.capability}: ${f.message}`);
|
|
10065
10273
|
for (const [capId, m] of Object.entries(hookResults?.meta || {})) {
|
|
@@ -10076,12 +10284,14 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10076
10284
|
for (const capId of quarantine.cleanup.outstanding?.hooks || []) {
|
|
10077
10285
|
if (ran.has(capId)) continue;
|
|
10078
10286
|
const cap = (meta.capabilityRuntime || []).find((c) => c.id === capId);
|
|
10079
|
-
|
|
10287
|
+
const noHook = !!cap && !cap.hooks?.retire;
|
|
10288
|
+
if (noHook) retryNonHook++;
|
|
10289
|
+
retryFailures.push(noHook
|
|
10080
10290
|
? `${capId}: declares no retire hook, so OATS cannot verify or undo what its failed spawn hook may have created — clean up by hand, then remove the home with \`oats retire ${name} --force\``
|
|
10081
10291
|
: `retire hook ${capId}: did not run on this retry, so the cleanup it owed is unverified`);
|
|
10082
10292
|
}
|
|
10083
|
-
if (!hookResults) retryFailures.push("retire hooks could not be rerun (cleanup descriptor lost its context repo)");
|
|
10084
|
-
if (orphanItem) retryFailures.push(orphanItem);
|
|
10293
|
+
if (!hookResults) { retryNonHook++; retryFailures.push("retire hooks could not be rerun (cleanup descriptor lost its context repo)"); }
|
|
10294
|
+
if (orphanItem) { retryNonHook++; retryFailures.push(orphanItem); }
|
|
10085
10295
|
}
|
|
10086
10296
|
|
|
10087
10297
|
// Hooks are allowed to mutate the inspected tree, so inspect again after
|
|
@@ -10382,6 +10592,10 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10382
10592
|
// Otherwise the home — and the credentials in it — must survive again, or the
|
|
10383
10593
|
// retry becomes the deletion the quarantine was preventing.
|
|
10384
10594
|
let stillIncomplete;
|
|
10595
|
+
// Whether what is still incomplete is retire hooks and nothing else (RETIRE_HOOK_DEBT_ONLY).
|
|
10596
|
+
// `keptForRetry` is not debt of its own: it is the worktree kept because of those items, and a
|
|
10597
|
+
// retry runs the worktree step once they clear.
|
|
10598
|
+
let hookDebtOnly = false;
|
|
10385
10599
|
// Ordinary path: quarantine instead of deleting, using the SAME writer the
|
|
10386
10600
|
// spawn rollback uses. Two copies of this logic is how a previous divergence
|
|
10387
10601
|
// happened (see quarantineInstanceHome), so there is still exactly one.
|
|
@@ -10392,6 +10606,9 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10392
10606
|
for (const [capId, m] of Object.entries(hookResults?.meta || {})) {
|
|
10393
10607
|
if (m && typeof m === "object" && m.retired === false && m.reason !== "nothing-to-delete") outstandingHooks.add(capId);
|
|
10394
10608
|
}
|
|
10609
|
+
// What the writer adds to the items is debt of its own: a descriptor kept outside the home, or
|
|
10610
|
+
// one that could not be stored, owes a restoration no rerun of the hooks makes.
|
|
10611
|
+
const itemsBeforeQuarantine = ordinaryIncomplete.length;
|
|
10395
10612
|
quarantineInstanceHome({
|
|
10396
10613
|
home: found.home, instance: name, agent: found.agent,
|
|
10397
10614
|
soulDir: instanceSoulDir(found.home, meta), soulId: nonEmptyString(meta.soulId) ? meta.soulId : undefined,
|
|
@@ -10404,11 +10621,14 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10404
10621
|
reason: outstandingHooks.size ? "retire hook reported incomplete cleanup" : "the work directory has no git admin entry",
|
|
10405
10622
|
});
|
|
10406
10623
|
stillIncomplete = ordinaryIncomplete;
|
|
10624
|
+
hookDebtOnly = outstandingHooks.size > 0 && !orphanItem && ordinaryIncomplete.length === itemsBeforeQuarantine;
|
|
10407
10625
|
}
|
|
10408
10626
|
let branchDeletedByRetry = false, branchKeptReason;
|
|
10409
10627
|
if (quarantine) {
|
|
10410
10628
|
const failures = [...retryFailures];
|
|
10411
10629
|
if (keptForRetry) failures.push(keptForRetry);
|
|
10630
|
+
// What the hooks left, before the Git verification below adds its own items.
|
|
10631
|
+
const hookItems = failures.length;
|
|
10412
10632
|
// The quarantine may exist BECAUSE Git cleanup failed, so a retry has to
|
|
10413
10633
|
// redo those steps and verify them — not just rerun hooks. No retire deletes a branch.
|
|
10414
10634
|
if (workMeta.work === "worktree" && workMeta.repo) {
|
|
@@ -10480,6 +10700,11 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10480
10700
|
}
|
|
10481
10701
|
if (failures.length) {
|
|
10482
10702
|
stillIncomplete = failures;
|
|
10703
|
+
// Hook debt alone: a retire hook is still owed, nothing no rerun can clear is, no Git step was
|
|
10704
|
+
// added by the verification above, and the marker owes no Git step, directory or orphaned work.
|
|
10705
|
+
const owed = quarantine.cleanup.outstanding;
|
|
10706
|
+
hookDebtOnly = retryFailures.length > 0 && retryNonHook === 0 && failures.length === hookItems
|
|
10707
|
+
&& !owed?.git?.length && owed?.directory !== true && owed?.orphanedWork !== true;
|
|
10483
10708
|
try {
|
|
10484
10709
|
writeFileSync(quarantinePath, JSON.stringify({ ...quarantine, incomplete: failures, lastRetryAt: new Date().toISOString() }, null, 2) + "\n");
|
|
10485
10710
|
} catch { /* the quarantine stands regardless */ }
|
|
@@ -10532,6 +10757,8 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10532
10757
|
rmSync(retirePendingMarkerPath(found.home), { force: true });
|
|
10533
10758
|
rmSync(deferredRetireResultPath(found.home), { force: true });
|
|
10534
10759
|
rmSync(deferredRetireResultPath(found.home).replace(/\.json$/, ".log"), { force: true });
|
|
10760
|
+
// And the retry state a completion that was killed while it waited may have left (retireRetryPath).
|
|
10761
|
+
rmSync(retireRetryPath(found.home), { force: true });
|
|
10535
10762
|
at.lead = null;
|
|
10536
10763
|
}
|
|
10537
10764
|
|
|
@@ -10552,6 +10779,7 @@ function retireSteps(root, name, o, found, at) {
|
|
|
10552
10779
|
return w.length ? w : undefined;
|
|
10553
10780
|
})() };
|
|
10554
10781
|
result[RETIRE_SELECTED_HOME] = found.home;
|
|
10782
|
+
result[RETIRE_HOOK_DEBT_ONLY] = !!stillIncomplete && !forced && hookDebtOnly;
|
|
10555
10783
|
if (self) {
|
|
10556
10784
|
// The caller is the instance: its process lives in the window we are about to
|
|
10557
10785
|
// kill. Detach the kill so this function can return and the caller can report
|