@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.
Files changed (70) hide show
  1. package/README.md +216 -178
  2. package/bin/oats.mjs +176 -184
  3. package/docs/capabilities.md +4 -1
  4. package/docs/configuration.md +63 -5
  5. package/docs/container.md +246 -0
  6. package/docs/design/2026-09-23-workspace-module-contracts.md +2 -0
  7. package/docs/desktop-cli-api.md +376 -37
  8. package/docs/desktop-instance-start.md +4 -1
  9. package/docs/desktop.md +58 -12
  10. package/docs/execution-targets.md +69 -6
  11. package/docs/implementation.md +86 -29
  12. package/docs/integrations.md +3 -2
  13. package/docs/knowledge-and-learning.md +72 -0
  14. package/docs/oats-local.schema.json +11 -2
  15. package/docs/official-catalog.md +39 -5
  16. package/docs/packages.md +93 -14
  17. package/docs/release-lane.md +2 -1
  18. package/docs/release-notes/v0.69.13.md +767 -0
  19. package/docs/release-notes/v0.69.14.md +83 -0
  20. package/docs/schedules.md +26 -3
  21. package/docs/servers.md +181 -5
  22. package/docs/souls-and-instances.md +140 -11
  23. package/docs/tui.md +1 -1
  24. package/docs/upgrading.md +24 -5
  25. package/docs/workspaces.md +31 -5
  26. package/lib/claim.mjs +21 -5
  27. package/lib/command-flags.mjs +238 -0
  28. package/lib/core.mjs +791 -563
  29. package/lib/deployments.mjs +4 -3
  30. package/lib/dir-lock.mjs +126 -31
  31. package/lib/errors.mjs +1 -1
  32. package/lib/harness-token.mjs +110 -0
  33. package/lib/hot-reads.mjs +4 -3
  34. package/lib/instance-events.mjs +28 -6
  35. package/lib/instance-git.mjs +138 -13
  36. package/lib/instance-inspect.mjs +6 -1
  37. package/lib/instance-listing.mjs +80 -38
  38. package/lib/instance-resolution.mjs +56 -3
  39. package/lib/instance-upgrade.mjs +16 -20
  40. package/lib/launch-env-exec.sh +7 -0
  41. package/lib/launch-env.mjs +74 -0
  42. package/lib/launch-preference.mjs +19 -12
  43. package/lib/member-clone.mjs +7 -1
  44. package/lib/packages.mjs +74 -2
  45. package/lib/read-call.mjs +3 -0
  46. package/lib/reader.mjs +3 -2
  47. package/lib/refused-text.mjs +3 -2
  48. package/lib/remote.mjs +119 -27
  49. package/lib/retained-after-retire.mjs +2 -7
  50. package/lib/retire-git-forms.mjs +41 -0
  51. package/lib/retire-incomplete.mjs +96 -0
  52. package/lib/schedule.mjs +2 -1
  53. package/lib/servers.mjs +78 -23
  54. package/lib/session-resume.mjs +68 -53
  55. package/lib/session-seen.mjs +54 -5
  56. package/lib/start-env.mjs +13 -7
  57. package/lib/system-tools.mjs +1 -1
  58. package/lib/teams.mjs +11 -4
  59. package/lib/upgrade-state.mjs +13 -2
  60. package/lib/worktree.mjs +56 -7
  61. package/package-catalog.json +1 -1
  62. package/package.json +2 -1
  63. package/packages/client/instance-lifecycle.mjs +1 -1
  64. package/packages/client/lifecycle-contract.mjs +3 -1
  65. package/packages/client/session-resume-cli.mjs +2 -1
  66. package/packages/client/session-start.mjs +10 -7
  67. package/packages/client/workspace-cli.mjs +5 -1
  68. package/share/oats-login-receive +204 -0
  69. package/skills/oats-getting-started/SKILL.md +92 -25
  70. package/lib/tmux-config.mjs +0 -35
package/lib/worktree.mjs CHANGED
@@ -26,12 +26,14 @@ import { checkHolderByHand, ifItDoesNotEnd, lifecycleBusy, nothingAfter, oatsErr
26
26
  import { appendEvent } from "./instance-events.mjs";
27
27
  import { attachedToTree } from "./instance-lifecycle.mjs";
28
28
  import { recordedTeams } from "./teams.mjs";
29
- import { canonicalCloneKey, memberCloneOf } from "./instance-resolution.mjs";
29
+ import { canonicalCloneKey, conventionCloneDir, memberCloneOf, parsedCloneKey } from "./member-clone.mjs";
30
+ import { shellWord } from "./shell-word.mjs";
30
31
  import { loadLocal } from "./workspace.mjs";
31
32
  import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
32
33
  import { terminateGroup, watchGroup } from "./process-group.mjs";
33
34
  import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, recordInClaim, releaseClaim, shownHolder } from "./claim.mjs";
34
35
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
36
+ import { filterOverrides } from "./instance-git.mjs";
35
37
  import {
36
38
  cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
37
39
  refuseBesideRetire, retirePendingMarkerPath, stableSoulId, workspaceOf,
@@ -190,12 +192,16 @@ export function resolveTreeClone(meta, repo) {
190
192
  } else if (isAbsolute(repo) || repo.startsWith(".") || repo.startsWith("~")) {
191
193
  path = repo.startsWith("~") ? join(process.env.HOME ?? "", repo.slice(1)) : resolve(repo);
192
194
  } else {
193
- const key = canonicalCloneKey(repo);
195
+ const parsed = parsedCloneKey(repo);
196
+ const key = parsed ?? canonicalCloneKey(repo);
194
197
  const deployment = meta.workspace?.deployment;
195
198
  if (typeof deployment !== "string" || !deployment) throw oatsError("E_CLONE_MISSING", `--repo ${repo}: this home records no deployment to look its clone up in; pass a clone path instead`);
196
199
  let local = {};
197
200
  try { local = loadLocal(deployment)?.local ?? {}; } catch (e) { throw Object.assign(oatsError(e.code || "E_CONFIG_BROKEN", e.message), { details: e.details }); }
198
- const found = memberCloneOf(deployment, local, key);
201
+ let found;
202
+ try { found = memberCloneOf(deployment, local, key); }
203
+ catch (e) { if (parsed === null && e?.code === "E_CLONE_MISMATCH") throw notAKeyMismatch(repo, key, e); throw e; }
204
+ if (!found.path && parsed === null) throw Object.assign(oatsError("E_CLONE_MISSING", `--repo ${repo}: ${key} is not a repository key, and names no clone on this machine (nothing at its convention path ${conventionCloneDir(deployment, key)}); ${NOT_A_KEY_REMEDY}`), { details: { repoKey: key, deployment } });
199
205
  if (!found.path) throw Object.assign(oatsError("E_CLONE_MISSING", `--repo ${repo}: this machine has no clone of ${key} — clone it to <deployment>/<member name> or name it in oats-local.yaml clones: { ${key}: <abs path> }; or pass a clone path`), { details: { repoKey: key, deployment } });
200
206
  path = found.path;
201
207
  member = key;
@@ -217,6 +223,29 @@ export function resolveTreeClone(meta, repo) {
217
223
  if (!origin.ok || !origin.out.trim()) throw Object.assign(oatsError("E_CLONE_MISMATCH", `${clone} has no "origin" remote; a tree starts from origin's branch`), { details: { path: clone } });
218
224
  return { clone, member, remote: scrubRemoteUrl(origin.out.trim()) };
219
225
  }
226
+
227
+ const NOT_A_KEY_REMEDY = "pass a member's key (<host>/<org>/<repo>) or a clone path";
228
+
229
+ /** E_CLONE_MISMATCH for a `--repo` that is not a repository key (a member's name, `org/name`;
230
+ * oats-project/oats#1781), with the code and details memberCloneOf gave it. Such a string matches no
231
+ * remote, so the Git remedy that refusal ends with would repoint a good clone at a URL that does not
232
+ * exist. Instead: the clone's remotes whose key is `name` or ends in `/<name>` (`.git` aside) are the
233
+ * key to pass, and the clone's path is the other spelling that works. */
234
+ function notAKeyMismatch(repo, written, e) {
235
+ const { path, via, found } = e.details ?? {};
236
+ const bare = (k) => k.replace(/\.git$/i, "");
237
+ const name = bare(written);
238
+ const matches = [...new Set((Array.isArray(found) ? found : []).filter((k) => !k.startsWith("?/") && (bare(k) === name || bare(k).endsWith(`/${name}`))))];
239
+ const head = `--repo ${repo}: ${written} is not a repository key`;
240
+ let message;
241
+ if (matches.length) {
242
+ message = `${head}; the clone at ${path} (${via}) has ${matches.length > 1 ? "remotes" : "a remote"} ${matches.join(", ")}: pass ${matches.map((k) => `--repo ${shellWord(k)}`).join(" or ")}, or its path, --repo ${shellWord(path)}`;
243
+ } else {
244
+ const seen = !Array.isArray(found) ? e.message : `${via}: ${path} ${found.length ? `has remotes ${found.join(", ")}` : "has no remotes"}, none of them ${written}`;
245
+ message = `${head}, and matches no clone (${seen}); ${NOT_A_KEY_REMEDY}`;
246
+ }
247
+ return Object.assign(oatsError("E_CLONE_MISMATCH", message, e.provenance), { details: e.details });
248
+ }
220
249
  const realpathOr = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
221
250
 
222
251
  // ---------- the record ----------
@@ -343,7 +372,7 @@ const worktreeFields = (out, field) => out.split("\0").filter((f) => f.startsWit
343
372
  * and a recovery never acts on a tree made after it read. A live adder's own record is left to it
344
373
  * (others refuse it as busy), so the claim is not held while hooks run.
345
374
  *
346
- * Unlike lib/dir-lock.mjs, a claim left by a process that died (SIGKILL in the middle of a
375
+ * A claim left by a process that died (SIGKILL in the middle of a
347
376
  * recovery) is taken over, so a killed command can always be run again: the owner is named by
348
377
  * pid AND start time (processLiveness), never by a pid alone, and a holder whose start cannot be
349
378
  * read is never taken for gone. A claim held by a live process is
@@ -610,6 +639,19 @@ export async function worktreeAdd(homeArg, o = {}) {
610
639
 
611
640
  const manualResidueRemedy = (tree, purpose) => `save any work and remove ${tree} by hand, then run \`oats worktree remove --purpose ${purpose}\` to drop its record`;
612
641
 
642
+ /** The `-c` arguments that keep a removal's Git from running a filter driver
643
+ * (`filter.<name>.clean`, `.process`) of the repository at `where` (`-C <dir>`), whose
644
+ * configuration whoever works in a tree can write: Git runs one when it compares a tree's file
645
+ * that carries the `filter` attribute, and the removal reads the tree's files as their bytes are
646
+ * (lib/instance-git.mjs filterOverrides, which says what its read covers and what it does not).
647
+ * Throws `refused(why)` when the drivers cannot be read or one cannot be overridden: the caller
648
+ * then runs no Git on the tree, and never takes it for a clean one. */
649
+ function removalFilterOverrides(where, refused) {
650
+ const filters = filterOverrides(where, { operatorEnv: gitEnv() });
651
+ if (!filters.ok) throw refused(filters.err);
652
+ return filters.args;
653
+ }
654
+
613
655
  /** Git removes its admin entry even when deleting ignored output fails. A later remove
614
656
  * has no index to ask: compare the surviving files with the recorded branch in a private
615
657
  * index, never the clone's index. Missing files are expected after partial deletion. */
@@ -627,10 +669,13 @@ function checkRemovalResidue(clone, tree, rec, refuse) {
627
669
  } catch (e) { throw refuse(`the unregistered tree's .git file could not be checked (${e.message}); ${manualResidueRemedy(tree, rec.purpose)}`); }
628
670
  if (!missingGitdir) throw refuse(`the unregistered tree has no .git file pointing at a missing gitdir; ${manualResidueRemedy(tree, rec.purpose)}`);
629
671
 
672
+ // The refresh and diff-files below read the surviving files: no filter driver the clone's
673
+ // configuration defines runs in them (removalFilterOverrides).
674
+ const filters = removalFilterOverrides(["-C", clone], (err) => refuse(`the surviving files could not be checked (${err})`));
630
675
  const scratch = mkdtempSync(join(tmpdir(), "oats-worktree-remove-"));
631
676
  try {
632
677
  const env = { GIT_INDEX_FILE: join(scratch, "index") };
633
- const args = ["-C", clone, "--work-tree", tree];
678
+ const args = [...filters, "-C", clone, "--work-tree", tree];
634
679
  const read = git([...args, "read-tree", `refs/heads/${rec.branch}`], { env });
635
680
  if (!read.ok) throw refuse(`the recorded branch ${rec.branch} could not be read (${firstLine(read.err)})`);
636
681
  // read-tree has no stat cache. Refresh it before diff-files so identical survivors
@@ -731,9 +776,13 @@ export async function worktreeRemove(homeArg, o = {}) {
731
776
  if (!registered()) {
732
777
  checkRemovalResidue(clone, tree, rec, refuse);
733
778
  } else {
734
- const status = git(["-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
779
+ // The status, and the clean check inside `git worktree remove` (a `git status` Git starts
780
+ // in the tree, which the `-c` settings reach), compare the tree's files: no filter driver
781
+ // the tree's configuration defines runs in either (removalFilterOverrides).
782
+ const filters = removalFilterOverrides(["-C", tree], (err) => refuse(`whether the tree is clean could not be read (${err})`));
783
+ const status = git([...filters, "-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
735
784
  started = true;
736
- const r = await trackedGit(["-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
785
+ const r = await trackedGit([...filters, "-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
737
786
  if (!r.ok && registered()) {
738
787
  if (status.ok && status.out.trim()) throw Object.assign(oatsError("E_WORKTREE_DIRTY", `git refused to remove ${tree}: ${firstLine(r.err)}; commit and push its changes, or discard them, then retry (the record is kept)`), { details: { purpose, path: tree, git: r.err } });
739
788
  throw refuse(`git could not finish removing the tree (${firstLine(r.err)})`, r.err);
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "oats.framework": {
50
50
  "url": "https://github.com/awebai/oats.git",
51
- "ref": "oats-framework/v1.22.1",
51
+ "ref": "oats-framework/v1.23.0",
52
52
  "path": "oats-package"
53
53
  }
54
54
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.69.12",
3
+ "version": "0.69.14",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -30,6 +30,7 @@
30
30
  "files": [
31
31
  "bin/",
32
32
  "lib/",
33
+ "share/oats-login-receive",
33
34
  "skills/",
34
35
  "injects/",
35
36
  "docs/",
@@ -37,7 +37,7 @@ export function supportsLifecycle(cli, operation, apply = false) {
37
37
  * E_REMOTE_INCOMPATIBLE, E_AMBIGUOUS and E_SNAPSHOT_UNKNOWN before sending, and the host's own resolution
38
38
  * refuses them (and E_HOME_MISMATCH) before any effect. E_PLAN_STALE is not here: it is read by its own branch
39
39
  * (interpret), by the shape of the answer, never by this set. */
40
- export const BEFORE_EFFECT_CODES = Object.freeze(['E_BAD_ARGS', 'E_INSTANCE_RETIRING', 'E_LIFECYCLE_BUSY',
40
+ export const BEFORE_EFFECT_CODES = Object.freeze(['E_BAD_ARGS', 'E_USAGE', 'E_INSTANCE_RETIRING', 'E_LIFECYCLE_BUSY',
41
41
  'E_HOME_MISMATCH', 'E_SESSION_UNKNOWN', 'E_AMBIGUOUS_INSTANCE', 'E_UNIDENTIFIED_INSTANCE_HOME', 'E_REMOTE_INCOMPATIBLE', 'E_AMBIGUOUS', 'E_SNAPSHOT_UNKNOWN']);
42
42
  /** The installed CLI printed this error envelope: the kernel answered. Said by the adapter where it builds
43
43
  * the envelope (`origin`), never inferred from the envelope's shape: the adapter's own failures and this
@@ -17,7 +17,9 @@ export const planReference = v => typeof v === 'string' && /^[a-f0-9]{64}$/.test
17
17
  const at = v => typeof v === 'string' && Number.isFinite(Date.parse(v));
18
18
  const strings = v => Array.isArray(v) && v.length <= 64 && v.every(n => text(n));
19
19
  const messages = {
20
- E_BAD_ARGS: 'Invalid lifecycle request.', E_WORKSPACE_UNKNOWN: 'Choose an advertised workspace.',
20
+ E_BAD_ARGS: 'Invalid lifecycle request.',
21
+ // The kernel's, for a stop or a retire missing its argument (the usage line is its message). Answered only before any effect.
22
+ E_USAGE: 'Invalid lifecycle request.', E_WORKSPACE_UNKNOWN: 'Choose an advertised workspace.',
21
23
  E_SESSION_UNKNOWN: 'This instance is no longer in the current roster.', E_AMBIGUOUS_INSTANCE: 'Select an exact instance home.',
22
24
  E_HOME_MISMATCH: 'The instance home no longer matches this selection.',
23
25
  // The kernel's, for a home it cannot work from: a record that is there and cannot be read, a rollback
@@ -39,7 +39,8 @@ function refusal(error) {
39
39
  * signal it: the sweep outlives the client that started it (the TUI passes its `changeExec`). No `timeout` is
40
40
  * given. `io.env` replaces process.env as the environment cleaned.
41
41
  * Never rejects. Resolves the parsed `{ schemaVersion: 1, ok: true, result }` (exit 0 only); the kernel's refusal
42
- * `{ schemaVersion: 1, ok: false, error: { code, message } }` whatever the exit (E_RESUME_BUSY exits 1); or
42
+ * `{ schemaVersion: 1, ok: false, error: { code, message } }` whatever the exit (E_RESUME_BUSY and
43
+ * E_RESUME_LOCK_STUCK exit 1); or
43
44
  * `{ schemaVersion: 1, ok: false, error: { code } }`: E_CLI_UNAVAILABLE, E_RESUME_FEATURE (nothing ran),
44
45
  * E_CLI_OUTPUT_LIMIT (over SESSION_RESUME_MAX_BUFFER), E_CLI_PROTOCOL (no envelope, or a refusal without a valid
45
46
  * code), E_CLI_FAILED (a nonzero exit with no refusal, or an exec that threw).
@@ -25,12 +25,14 @@ import { requireTerms } from './client-terms.mjs';
25
25
  /** The gate is page-safe and lives apart (start-gate.mjs); a client takes it from here, with the rest of the rule. */
26
26
  export { startGate };
27
27
 
28
- /** The kernel's codes for a start that started nothing: the home's start lock is held, or an earlier start's
29
- * pane is still a shell without its completion marker (E_SESSION_START_BUSY); the instance was seen running,
30
- * or its window appeared during the start (E_SESSION_RUNNING). Some places that raise E_SESSION_RUNNING come
28
+ /** The kernel's codes for a start that started nothing: another start holds the home, an upgrade has not
29
+ * finished, or an earlier start's pane is still a shell without its completion marker (E_SESSION_START_BUSY);
30
+ * an earlier kernel's start lock, or anything else that is no upgrade's file, is at the home's
31
+ * `.oats-start.lock` (E_SESSION_START_LOCK_STUCK); the instance was seen running, or its window appeared
32
+ * during the start (E_SESSION_RUNNING). Some places that raise E_SESSION_RUNNING come
31
33
  * after the kernel has written the start's pending receipt, or after a restart's stop: nothing was started,
32
34
  * not nothing happened. A code joins only when every place the kernel raises it in a start launches nothing. */
33
- export const STARTED_NOTHING_CODES = Object.freeze(['E_SESSION_START_BUSY', 'E_SESSION_RUNNING']);
35
+ export const STARTED_NOTHING_CODES = Object.freeze(['E_SESSION_START_BUSY', 'E_SESSION_START_LOCK_STUCK', 'E_SESSION_RUNNING']);
34
36
 
35
37
  /** The kernel feature from which a start or a restart holds the home's lifecycle claim (#1602). */
36
38
  const CLAIM_START_FEATURE = 'lifecycle-claim-start';
@@ -42,11 +44,12 @@ const CLAIM_START_FEATURE = 'lifecycle-claim-start';
42
44
  * (lifecycle-contract.mjs answeringFeatures), never this computer's for a server's row. */
43
45
  export const CLAIM_STARTED_NOTHING_CODES = Object.freeze(['E_LIFECYCLE_BUSY', 'E_INSTANCE_RETIRING']);
44
46
 
45
- /** The two kernel codes' own sentences, for a client that words by code. The kernel's message is the
46
- * answer's `detail`, through the display filter. E_SESSION_START_BUSY says no more than busy: the kernel answers
47
- * it for a start lock that is there, which a start that ended without removing it leaves behind too. */
47
+ /** The kernel codes' own sentences, for a client that words by code. The kernel's message is the answer's
48
+ * `detail`, through the display filter. E_SESSION_START_BUSY says no more than busy. E_SESSION_START_LOCK_STUCK
49
+ * is what only a person ends: the kernel's message names the path to remove. */
48
50
  const STARTED_NOTHING = Object.freeze({
49
51
  E_SESSION_START_BUSY: 'OATS refused this start as busy. Nothing was started.',
52
+ E_SESSION_START_LOCK_STUCK: 'Something in this instance\'s home blocks starting, usually a start lock an earlier OATS left; OATS\'s message names it. Nothing was started. Remove it once no earlier OATS is running: waiting will not clear it.',
50
53
  E_SESSION_RUNNING: 'This instance is already running. Nothing was started.',
51
54
  });
52
55
  /** A CLAIM_STARTED_NOTHING_CODES refusal's sentence. E_LIFECYCLE_BUSY reads by who holds the claim (`holder`,
@@ -1,7 +1,7 @@
1
1
  /** Workspace model v2 verbs the Desktop drives: fixed argv, bounded output,
2
2
  * scrubbed instance environment. Only the kernel's JSON crosses back; a
3
3
  * refusal is its bounded error envelope (code + message, plus onboarding's
4
- * rolledBack flag), never stderr, argv, stacks or details objects.
4
+ * rolledBack flag and sync's `why` slug), never stderr, argv, stacks or details objects.
5
5
  * capabilities → `oats capabilities --dir D [--max-age S] --json` (capabilitiesApi 1)
6
6
  * souls → `oats souls --dir D [--max-age S] --json` (soulsApi 1, the spawn catalog)
7
7
  * capability-show → `oats capabilities show NAME (--member KEY | --package ID) [--file PATH]
@@ -27,6 +27,8 @@ export const WORKSPACE_MAX_BUFFER = 4 * 1024 * 1024;
27
27
  export const WORKSPACE_ACTIONS = Object.freeze(['capabilities', 'souls', 'sync', 'onboard', 'capability-show']);
28
28
  /** The read-only verbs: the ones `--max-age` may reach. */
29
29
  const READS = ['capabilities', 'souls', 'capability-show'];
30
+ /** A refusal's `details.why`, as a client may carry it: a short lower-case slug. */
31
+ const WHY_RE = /^[a-z][a-z0-9-]{0,31}$/;
30
32
  /** The kernel line this Desktop drives: workspace model v2 without package approval. */
31
33
  export const WORKSPACE_FEATURES = Object.freeze(['workspace-v2', 'packages-no-approval']);
32
34
  const absolute = path => typeof path === 'string' && !path.includes('\0') && isAbsolute(path) && resolve(path) === path;
@@ -132,6 +134,8 @@ export function cliWorkspace(cli, options, terms, io = {}) {
132
134
  if (!error) return fail('E_CLI_PROTOCOL');
133
135
  const out = { code: reason.code, message: reason.message };
134
136
  if (options.action === 'onboard' && reason.details?.rolledBack === true) out.rolledBack = true;
137
+ // Which case of a shared code (E_PACKAGE_INTEGRITY's branch, package-id, …): data a client words, never prose.
138
+ if (options.action === 'sync' && typeof reason.details?.why === 'string' && WHY_RE.test(reason.details.why)) out.why = reason.details.why;
135
139
  return done({ ok: false, reason: out });
136
140
  }
137
141
  if (error) return fail('E_CLI_FAILED'); // success is exit 0 only
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/python3 -I
2
+ """oats-login-receive: forced-command receiver for harness credentials (oats-project/oats#1786, OATS 9b1ed301).
3
+
4
+ Installed root-owned 0755 at /usr/local/sbin/oats-login-receive and reached ONLY through a dedicated key in root's
5
+ authorized_keys: restrict,command="/usr/local/sbin/oats-login-receive" <key>
6
+ SSH_ORIGINAL_COMMAND is "install|remove|status <harness> <name>"; for install the credential comes on stdin.
7
+ Answers one JSON line {ok, harness, name, fingerprint, replacedAt} (plus "error" when ok is false).
8
+ Never prints, logs or echoes the credential; the fingerprint is a sha256 prefix.
9
+
10
+ The destination comes from the root-owned config (/etc/oats-login/receiver.json), never from the caller:
11
+ {"teams": {"<name>": {"group": "<group that may read>", "harnesses": ["claude", ...],
12
+ "path": "/srv/oats-team/{name}/login/{harness}-token"}}} (path optional; that is the default)
13
+ The file is root:<group> 0440, written atomically; its parent directories are created root-owned (0750 for the login dir).
14
+ """
15
+ import datetime, grp, hashlib, json, os, re, stat, sys, syslog
16
+
17
+ CONFIG = "/etc/oats-login/receiver.json"
18
+ DEFAULT_PATH = "/srv/oats-team/{name}/login/{harness}-token"
19
+ HARNESSES = {"claude", "codex", "pi", "opencode"}
20
+ NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$")
21
+ MAX_BYTES = 65536
22
+
23
+
24
+ class Refused(Exception):
25
+ pass
26
+
27
+
28
+ def now():
29
+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
30
+
31
+
32
+ def fingerprint(data):
33
+ return "sha256:" + hashlib.sha256(data).hexdigest()[:16]
34
+
35
+
36
+ def root_owned_not_writable(path, want_dir):
37
+ st = os.lstat(path)
38
+ if stat.S_ISLNK(st.st_mode):
39
+ raise Refused(f"{path} is a symlink")
40
+ if want_dir and not stat.S_ISDIR(st.st_mode) or not want_dir and not stat.S_ISREG(st.st_mode):
41
+ raise Refused(f"{path} has the wrong type")
42
+ if st.st_uid != 0 or st.st_mode & 0o022:
43
+ raise Refused(f"{path} is not root-owned or is group/other-writable")
44
+
45
+
46
+ def load_config(path=CONFIG):
47
+ try:
48
+ root_owned_not_writable(path, want_dir=False)
49
+ root_owned_not_writable(os.path.dirname(path), want_dir=True)
50
+ with open(path) as f:
51
+ cfg = json.load(f)
52
+ except FileNotFoundError:
53
+ raise Refused("receiver config absent")
54
+ except (ValueError, OSError) as e:
55
+ raise Refused(f"receiver config unreadable: {type(e).__name__}")
56
+ if not isinstance(cfg.get("teams"), dict):
57
+ raise Refused("receiver config has no teams")
58
+ return cfg
59
+
60
+
61
+ def parse_command(raw):
62
+ parts = (raw or "").split()
63
+ if len(parts) != 3:
64
+ raise Refused("usage: install|remove|status <harness> <name>")
65
+ action, harness, name = parts
66
+ if action not in ("install", "remove", "status"):
67
+ raise Refused("unknown action")
68
+ if harness not in HARNESSES:
69
+ raise Refused("unknown harness")
70
+ if not NAME_RE.match(name):
71
+ raise Refused("bad name")
72
+ return action, harness, name
73
+
74
+
75
+ def destination(cfg, harness, name):
76
+ team = cfg["teams"].get(name)
77
+ if not isinstance(team, dict):
78
+ raise Refused("name not configured on this host")
79
+ hs = team.get("harnesses")
80
+ if not isinstance(hs, list) or harness not in hs:
81
+ raise Refused("harness not enabled for this name")
82
+ try:
83
+ gid = grp.getgrnam(team["group"]).gr_gid
84
+ except (KeyError, TypeError):
85
+ raise Refused("configured group absent")
86
+ path = (team.get("path") or DEFAULT_PATH).format(name=name, harness=harness)
87
+ if not os.path.isabs(path) or ".." in path.split("/"):
88
+ raise Refused("configured path is not absolute and normalized")
89
+ return path, gid
90
+
91
+
92
+ def ensure_parents(path, gid):
93
+ """Create missing parents root-owned; the login dir itself root:<group> 0750. Existing ones must be root-owned, not writable by others, no symlinks."""
94
+ login_dir = os.path.dirname(path)
95
+ parts = login_dir.strip("/").split("/")
96
+ cur = "/"
97
+ for i, p in enumerate(parts):
98
+ cur = os.path.join(cur, p)
99
+ last = i == len(parts) - 1
100
+ if not os.path.lexists(cur):
101
+ os.mkdir(cur, 0o750 if last else 0o755)
102
+ os.chown(cur, 0, gid if last else 0)
103
+ os.chmod(cur, 0o750 if last else 0o755)
104
+ root_owned_not_writable(cur, want_dir=True)
105
+ return login_dir
106
+
107
+
108
+ def read_credential(stream):
109
+ data = stream.read(MAX_BYTES + 1)
110
+ if len(data) > MAX_BYTES:
111
+ raise Refused("credential too large")
112
+ data = data.strip()
113
+ if not data:
114
+ raise Refused("empty credential")
115
+ if b"\0" in data:
116
+ raise Refused("credential contains NUL")
117
+ return data
118
+
119
+
120
+ def check_shape(harness, data):
121
+ # Shape only, never the value. Claude setup-token tokens are one line with the sk-ant-oat prefix.
122
+ if harness == "claude" and (not data.startswith(b"sk-ant-oat") or b"\n" in data or len(data) > 512):
123
+ raise Refused("not a claude setup-token")
124
+
125
+
126
+ def install(path, gid, data):
127
+ login_dir = ensure_parents(path, gid)
128
+ if os.path.lexists(path):
129
+ root_owned_not_writable(path, want_dir=False)
130
+ tmp = os.path.join(login_dir, f".{os.path.basename(path)}.{os.getpid()}.new")
131
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o400)
132
+ try:
133
+ try:
134
+ os.fchown(fd, 0, gid)
135
+ os.fchmod(fd, 0o440)
136
+ os.write(fd, data + b"\n")
137
+ os.fsync(fd)
138
+ finally:
139
+ os.close(fd)
140
+ os.rename(tmp, path)
141
+ except BaseException:
142
+ try:
143
+ os.unlink(tmp)
144
+ except OSError:
145
+ pass
146
+ raise
147
+ dfd = os.open(login_dir, os.O_RDONLY | os.O_DIRECTORY)
148
+ try:
149
+ os.fsync(dfd)
150
+ finally:
151
+ os.close(dfd)
152
+
153
+
154
+ def run(raw_command, stdin, config_path=CONFIG):
155
+ out = {"ok": False, "harness": None, "name": None, "fingerprint": None, "replacedAt": None}
156
+ try:
157
+ action, harness, name = parse_command(raw_command)
158
+ out.update(harness=harness, name=name)
159
+ path, gid = destination(load_config(config_path), harness, name)
160
+ if action == "install":
161
+ data = read_credential(stdin)
162
+ check_shape(harness, data)
163
+ install(path, gid, data)
164
+ out.update(ok=True, fingerprint=fingerprint(data), replacedAt=now())
165
+ elif action == "remove":
166
+ if os.path.lexists(path):
167
+ root_owned_not_writable(path, want_dir=False)
168
+ os.unlink(path)
169
+ out.update(ok=True, replacedAt=now())
170
+ else: # status
171
+ if not os.path.lexists(path):
172
+ raise Refused("no credential installed")
173
+ root_owned_not_writable(path, want_dir=False)
174
+ with open(path, "rb") as f:
175
+ data = f.read().strip()
176
+ st = os.lstat(path)
177
+ out.update(ok=True, fingerprint=fingerprint(data),
178
+ replacedAt=datetime.datetime.fromtimestamp(st.st_mtime, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))
179
+ except Refused as e:
180
+ out["error"] = str(e)
181
+ except OSError as e:
182
+ out["error"] = f"io error: {type(e).__name__}"
183
+ except Exception as e: # never leave the caller without a JSON line and a syslog record
184
+ out["error"] = f"internal error: {type(e).__name__}"
185
+ return out
186
+
187
+
188
+ def main():
189
+ os.umask(0o077)
190
+ out = run(os.environ.get("SSH_ORIGINAL_COMMAND", ""), sys.stdin.buffer)
191
+ syslog.openlog("oats-login-receive", 0, syslog.LOG_AUTH)
192
+ # Log only the VALIDATED action (never the raw first token: a client that puts the credential in the command
193
+ # line must not write it into the auth log).
194
+ first = (os.environ.get("SSH_ORIGINAL_COMMAND", "").split() or ["-"])[0]
195
+ action = first if first in ("install", "remove", "status") else "-"
196
+ syslog.syslog(syslog.LOG_NOTICE, "ok=%s action=%s harness=%s name=%s fingerprint=%s client=%s" % (
197
+ out["ok"], action, out["harness"], out["name"],
198
+ out["fingerprint"], (os.environ.get("SSH_CLIENT", "-").split() or ["-"])[0]))
199
+ print(json.dumps(out))
200
+ return 0 if out["ok"] else 1
201
+
202
+
203
+ if __name__ == "__main__":
204
+ sys.exit(main())