@ours.network/fleet 0.10.0-nightly.4 → 0.10.1

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 (53) hide show
  1. package/README.md +138 -21
  2. package/dist/atomic-file.d.ts +30 -0
  3. package/dist/atomic-file.js +86 -0
  4. package/dist/briefing.d.ts +6 -0
  5. package/dist/briefing.js +43 -13
  6. package/dist/cli.js +98 -22
  7. package/dist/config.d.ts +24 -3
  8. package/dist/config.js +84 -11
  9. package/dist/creation.d.ts +179 -0
  10. package/dist/creation.js +254 -0
  11. package/dist/docs.d.ts +28 -1
  12. package/dist/docs.js +155 -8
  13. package/dist/doctor.js +75 -17
  14. package/dist/harness/claude-code.d.ts +39 -3
  15. package/dist/harness/claude-code.js +128 -26
  16. package/dist/harness/codex.d.ts +7 -1
  17. package/dist/harness/codex.js +58 -11
  18. package/dist/harness/registry.d.ts +2 -0
  19. package/dist/harness/registry.js +19 -0
  20. package/dist/harness/types.d.ts +51 -4
  21. package/dist/isolation/bubblewrap.js +7 -1
  22. package/dist/isolation/policy.d.ts +34 -5
  23. package/dist/isolation/policy.js +114 -7
  24. package/dist/isolation/resources.d.ts +6 -3
  25. package/dist/isolation/resources.js +6 -3
  26. package/dist/isolation/types.d.ts +19 -1
  27. package/dist/monitor.d.ts +44 -7
  28. package/dist/monitor.js +157 -35
  29. package/dist/ops.d.ts +15 -2
  30. package/dist/ops.js +32 -9
  31. package/dist/permissions.d.ts +70 -0
  32. package/dist/permissions.js +97 -0
  33. package/dist/runner.d.ts +72 -2
  34. package/dist/runner.js +291 -28
  35. package/dist/session/acp.d.ts +25 -2
  36. package/dist/session/acp.js +143 -26
  37. package/dist/session/control.d.ts +49 -1
  38. package/dist/session/control.js +116 -12
  39. package/dist/session/tmux.d.ts +9 -2
  40. package/dist/session/tmux.js +36 -4
  41. package/dist/session/types.d.ts +99 -2
  42. package/dist/session/types.js +42 -1
  43. package/dist/spawn.d.ts +27 -2
  44. package/dist/spawn.js +153 -15
  45. package/dist/supervisor/launchd.d.ts +50 -0
  46. package/dist/supervisor/launchd.js +121 -4
  47. package/dist/supervisor/none.js +22 -4
  48. package/dist/supervisor/systemd.d.ts +8 -1
  49. package/dist/supervisor/systemd.js +94 -4
  50. package/dist/supervisor/types.d.ts +36 -3
  51. package/dist/tmux.d.ts +34 -2
  52. package/dist/tmux.js +48 -11
  53. package/package.json +1 -1
package/dist/ops.d.ts CHANGED
@@ -1,18 +1,31 @@
1
1
  import type { FleetConfig, ResolvedRole } from './config.js';
2
- import type { SupervisorBackend } from './supervisor/types.js';
2
+ import type { InstallOutcome as BackendInstallOutcome, SupervisorBackend } from './supervisor/types.js';
3
+ /** An install outcome tagged with the role it belongs to. */
4
+ export interface InstallOutcome extends BackendInstallOutcome {
5
+ role: string;
6
+ }
3
7
  export interface OpsDeps {
4
8
  backend: SupervisorBackend;
5
9
  binPath: string;
6
10
  log(line: string): void;
11
+ /**
12
+ * Called the INSTANT a registration is created, before anything else can
13
+ * fail. A creation transaction that learns about registrations only from
14
+ * `up()`'s return value learns nothing when `up()` throws — and the service
15
+ * it just registered is then invisible to rollback (6.2). Optional: plain
16
+ * `ours-fleet up` has no transaction to tell.
17
+ */
18
+ onInstalled?(outcome: InstallOutcome): void;
7
19
  }
8
20
  /** Materialize a role's state dir from config: briefing + markers. Returns the dir. */
9
21
  export declare function applyRole(role: ResolvedRole, opts?: {
10
22
  fresh?: boolean;
11
23
  temp?: boolean;
12
24
  configPath?: string;
25
+ identityGuarantee?: 'verified' | 'created' | 'unverified';
13
26
  }): string;
14
27
  /** Create/start roles declaratively. Idempotent; active roles keep their context. */
15
- export declare function up(cfg: FleetConfig, names: string[], deps: OpsDeps, configPath?: string): Promise<void>;
28
+ export declare function up(cfg: FleetConfig, names: string[], deps: OpsDeps, configPath?: string, identityGuarantee?: 'verified' | 'created' | 'unverified'): Promise<InstallOutcome[]>;
16
29
  export declare function down(cfg: FleetConfig, names: string[], deps: OpsDeps): Promise<void>;
17
30
  /** Re-sync from config + bounce. mode 'keep' resumes context; 'fresh' wipes it. */
18
31
  export declare function restartRoles(cfg: FleetConfig, names: string[], deps: OpsDeps, mode: 'keep' | 'fresh', configPath?: string): Promise<void>;
package/dist/ops.js CHANGED
@@ -5,6 +5,7 @@ import { agentDir, fleetDDir } from './paths.js';
5
5
  import { findRole } from './config.js';
6
6
  import { getAdapter } from './harness/registry.js';
7
7
  import { generateBriefing } from './briefing.js';
8
+ import { resetRestartLedger } from './runner.js';
8
9
  // Launch staggering now lives at the harness-launch point (the runner's start
9
10
  // gate, driven by `start_stagger_ms`), so it covers systemd host-boot too — not
10
11
  // just the `up`/`restart` command loop below. The old in-loop FLEET_START_STAGGER
@@ -36,6 +37,7 @@ export function applyRole(role, opts = {}) {
36
37
  writeFileSync(join(dir, 'briefing.md'), generateBriefing(role, adapter.vocabulary, {
37
38
  stateDir: dir, worklogPath: join(dir, 'WORKLOG.md'),
38
39
  routinesPath: join(dir, 'ROUTINES.md'), briefingBody,
40
+ identityGuarantee: opts.identityGuarantee,
39
41
  }));
40
42
  if (opts.fresh)
41
43
  for (const f of ['.booted', '.session-id', '.exit-status'])
@@ -46,32 +48,53 @@ function selectRoles(cfg, names) {
46
48
  return names.length ? names.map(n => findRole(cfg, n)) : cfg.roles;
47
49
  }
48
50
  /** Create/start roles declaratively. Idempotent; active roles keep their context. */
49
- export async function up(cfg, names, deps, configPath) {
51
+ export async function up(cfg, names, deps, configPath, identityGuarantee) {
52
+ const outcomes = [];
50
53
  for (const role of selectRoles(cfg, names)) {
51
- const dir = applyRole(role, { configPath });
52
- // If the role isn't running, boot fresh so it reads the briefing we just wrote.
53
- const status = await deps.backend.status(role.name).catch(() => '');
54
- if (!/running|active \(/.test(status))
54
+ const dir = applyRole(role, { configPath, identityGuarantee });
55
+ // Only a *definite* stop boots fresh so the role reads the briefing we just
56
+ // wrote. A running, restarting, or unprobeable role keeps its context —
57
+ // guessing "stopped" from an unanswered probe silently discards a live
58
+ // conversation.
59
+ // An explicit operator `up` is the sanctioned way to release a held-down
60
+ // role: the still-alive runner polls this file and resumes (3.2).
61
+ resetRestartLedger(dir);
62
+ const live = await deps.backend.liveness(role.name)
63
+ .catch(e => ({ state: 'unknown', detail: e instanceof Error ? e.message : String(e) }));
64
+ if (live.state === 'stopped')
55
65
  rmSync(join(dir, '.booted'), { force: true });
56
- await deps.backend.install(role.name, deps.binPath);
66
+ else if (live.state === 'unknown')
67
+ deps.log(` ! ${role.name}: liveness unknown, keeping session context — ${live.detail}`);
68
+ // Report what each install actually did, so a creation transaction can undo
69
+ // only the registrations IT made (6.2). Announced immediately as well as
70
+ // returned: a later role in this same loop can throw, and the registrations
71
+ // already made must still be undoable.
72
+ const outcome = { ...await deps.backend.install(role.name, deps.binPath), role: role.name };
73
+ if (outcome.created)
74
+ deps.onInstalled?.(outcome);
75
+ outcomes.push(outcome);
57
76
  deps.log(`↑ up: ${role.name} (harness: ${role.harness}, identity: ${role.identity}${role.cwd ? `, cwd: ${role.cwd}` : ''})`);
58
77
  }
78
+ return outcomes;
59
79
  }
60
80
  export async function down(cfg, names, deps) {
61
81
  for (const role of selectRoles(cfg, names)) {
82
+ // Never swallow the backend's reason. "maybe not running" hid real stop
83
+ // failures — a wedged unit, an unreachable user bus — behind a guess.
62
84
  try {
63
85
  await deps.backend.stop(role.name);
64
86
  deps.log(`■ stopped ${role.name}`);
65
87
  }
66
- catch {
67
- deps.log(` (could not stop ${role.name} maybe not running)`);
88
+ catch (e) {
89
+ deps.log(` ! could not stop ${role.name}: ${e instanceof Error ? e.message : String(e)}`);
68
90
  }
69
91
  }
70
92
  }
71
93
  /** Re-sync from config + bounce. mode 'keep' resumes context; 'fresh' wipes it. */
72
94
  export async function restartRoles(cfg, names, deps, mode, configPath) {
73
95
  for (const role of selectRoles(cfg, names)) {
74
- applyRole(role, { fresh: mode === 'fresh', configPath });
96
+ const dir = applyRole(role, { fresh: mode === 'fresh', configPath });
97
+ resetRestartLedger(dir); // explicit restart closes the circuit
75
98
  await deps.backend.restart(role.name);
76
99
  deps.log(mode === 'fresh'
77
100
  ? `↻ ${role.name} — force-restarted (FRESH — context cleared, briefing reloaded)`
@@ -0,0 +1,70 @@
1
+ import type { CommonPermissions, ResolvedRole } from './config.js';
2
+ import type { UnattendedCapability } from './harness/types.js';
3
+ /**
4
+ * The capability floor every unattended role must clear. These are not
5
+ * nice-to-haves: an agent that cannot read its briefing, append its worklog,
6
+ * bind its identity, arm its monitor, edit its workspace, or run the status
7
+ * commands its briefing prescribes cannot carry out the job it was spawned for
8
+ * — and, being unattended, will report no error while failing to.
9
+ */
10
+ export declare const UNATTENDED_FLOOR: readonly UnattendedCapability[];
11
+ export interface FloorResult {
12
+ meets: boolean;
13
+ missing: UnattendedCapability[];
14
+ }
15
+ /** Which floor capabilities a set of granted capabilities fails to cover. */
16
+ export declare function checkUnattendedFloor(granted: readonly UnattendedCapability[]): FloorResult;
17
+ /**
18
+ * One role's neutral permissions, resolved through its harness adapter.
19
+ *
20
+ * Both `ours-fleet config` and `ours-fleet doctor` render this same object, so
21
+ * the two commands cannot disagree about what a configuration actually means.
22
+ * Before this existed, `translatePermissions()` was implemented by every
23
+ * adapter and called by nobody: the warnings it produced — including "this
24
+ * combination is not represented exactly" — were unreachable.
25
+ */
26
+ export interface RolePermissionAnalysis {
27
+ role: string;
28
+ harness: string;
29
+ permissions: CommonPermissions;
30
+ /** Whether the harness can express neutral permissions at all. */
31
+ supported: boolean;
32
+ /** The harness's own settings, when it can. */
33
+ native?: Record<string, unknown>;
34
+ /** Whether those settings represent the neutral intent exactly. */
35
+ exact?: boolean;
36
+ /** What the native settings actually permit an unattended agent to do. */
37
+ capabilities?: UnattendedCapability[];
38
+ /** Whether those capabilities clear the unattended floor. */
39
+ floor?: FloorResult;
40
+ /**
41
+ * How hard a floor shortfall is. A role that auto-denies (`unattended: deny`)
42
+ * silently does less than asked, so that is a failure; one that waits can at
43
+ * least be rescued by a human attaching a console, so that is a warning.
44
+ */
45
+ floorSeverity?: 'fail' | 'warn';
46
+ /** Native settings that contradict the neutral block; empty when they agree. */
47
+ conflicts?: PermissionConflict[];
48
+ /** A role-named line when the floor is not met; absent when it is. */
49
+ floorWarning?: string;
50
+ /** Role-named translation warnings, ready to print verbatim by any command. */
51
+ warnings: string[];
52
+ }
53
+ export interface PermissionConflict {
54
+ /** The native setting both sources speak to, e.g. `permission_mode`. */
55
+ key: string;
56
+ /** What the neutral `permissions:` block translates to. */
57
+ fromNeutral: string;
58
+ /** What `harness_options` states directly. */
59
+ fromNative: string;
60
+ /** The role-named line commands print. */
61
+ warning: string;
62
+ }
63
+ /** Resolve one role's permissions through its adapter. Never throws. */
64
+ export declare function analyzeRolePermissions(role: ResolvedRole): RolePermissionAnalysis;
65
+ /** Every line a command should show for a role: translation, conflicts, floor. */
66
+ export declare function allWarnings(a: RolePermissionAnalysis): string[];
67
+ /** Resolve every role's permissions, in config order. */
68
+ export declare function analyzeFleetPermissions(roles: ResolvedRole[]): RolePermissionAnalysis[];
69
+ /** Render an analysis's native settings compactly, for one-line reporting. */
70
+ export declare function formatNative(native: Record<string, unknown> | undefined): string;
@@ -0,0 +1,97 @@
1
+ import { getAdapter } from './harness/registry.js';
2
+ /**
3
+ * The capability floor every unattended role must clear. These are not
4
+ * nice-to-haves: an agent that cannot read its briefing, append its worklog,
5
+ * bind its identity, arm its monitor, edit its workspace, or run the status
6
+ * commands its briefing prescribes cannot carry out the job it was spawned for
7
+ * — and, being unattended, will report no error while failing to.
8
+ */
9
+ export const UNATTENDED_FLOOR = [
10
+ 'read-state', 'write-state', 'messaging', 'monitor', 'workspace-edit', 'status-commands',
11
+ ];
12
+ /** Which floor capabilities a set of granted capabilities fails to cover. */
13
+ export function checkUnattendedFloor(granted) {
14
+ const missing = UNATTENDED_FLOOR.filter(c => !granted.includes(c));
15
+ return { meets: missing.length === 0, missing };
16
+ }
17
+ /**
18
+ * Find native settings that contradict the neutral block. Only fires when the
19
+ * operator wrote BOTH — a role that states its intent once, neutrally or
20
+ * natively, has nothing to contradict and stays quiet. `harness_options` wins
21
+ * at launch, which is precisely why a silent disagreement is dangerous: the
22
+ * neutral block reads like the source of truth and is not.
23
+ */
24
+ function findConflicts(role, fromNeutral, fromNative) {
25
+ if (!role.permissionsDeclared)
26
+ return [];
27
+ const conflicts = [];
28
+ for (const [key, nativeValue] of Object.entries(fromNative)) {
29
+ const neutralValue = fromNeutral[key];
30
+ if (neutralValue === undefined || String(neutralValue) === String(nativeValue))
31
+ continue;
32
+ conflicts.push({
33
+ key,
34
+ fromNeutral: String(neutralValue),
35
+ fromNative: String(nativeValue),
36
+ warning: `role '${role.name}': harness_options.${key}=${String(nativeValue)} contradicts the `
37
+ + `permissions block, which translates to ${key}=${String(neutralValue)} — `
38
+ + `harness_options.${key}=${String(nativeValue)} wins`,
39
+ });
40
+ }
41
+ return conflicts;
42
+ }
43
+ /** Resolve one role's permissions through its adapter. Never throws. */
44
+ export function analyzeRolePermissions(role) {
45
+ const base = { role: role.name, harness: role.harness, permissions: role.permissions };
46
+ let adapter;
47
+ try {
48
+ adapter = getAdapter(role.harness);
49
+ }
50
+ catch (e) {
51
+ return { ...base, supported: false, warnings: [`role '${role.name}': ${e.message}`] };
52
+ }
53
+ const translation = adapter.translatePermissions(role.permissions);
54
+ if (!translation.supported) {
55
+ return {
56
+ ...base, supported: false,
57
+ warnings: [`role '${role.name}': harness '${role.harness}' cannot express neutral ` +
58
+ `permissions — ${translation.reason}`],
59
+ };
60
+ }
61
+ const conflicts = findConflicts(role, translation.native, adapter.nativePermissionOverrides(role.harness_options));
62
+ const floor = checkUnattendedFloor(translation.capabilities);
63
+ const floorSeverity = role.permissions.unattended === 'deny' ? 'fail' : 'warn';
64
+ return {
65
+ ...base,
66
+ supported: true,
67
+ native: translation.native,
68
+ exact: translation.exact,
69
+ capabilities: translation.capabilities,
70
+ floor,
71
+ floorSeverity,
72
+ conflicts,
73
+ floorWarning: floor.meets ? undefined : (`role '${role.name}': resolved ${role.harness} permissions do not meet the unattended ` +
74
+ `capability floor — missing ${floor.missing.join(', ')} ` +
75
+ `(${formatNative(translation.native)}; unattended=${role.permissions.unattended} means these ` +
76
+ `requests will ${role.permissions.unattended === 'deny' ? 'be denied silently' : 'block the turn'})`),
77
+ warnings: translation.warnings.map(w => `role '${role.name}': ${w}`),
78
+ };
79
+ }
80
+ /** Every line a command should show for a role: translation, conflicts, floor. */
81
+ export function allWarnings(a) {
82
+ return [
83
+ ...a.warnings,
84
+ ...(a.conflicts ?? []).map(c => c.warning),
85
+ ...(a.floorWarning ? [a.floorWarning] : []),
86
+ ];
87
+ }
88
+ /** Resolve every role's permissions, in config order. */
89
+ export function analyzeFleetPermissions(roles) {
90
+ return roles.map(analyzeRolePermissions);
91
+ }
92
+ /** Render an analysis's native settings compactly, for one-line reporting. */
93
+ export function formatNative(native) {
94
+ if (!native || !Object.keys(native).length)
95
+ return '(none)';
96
+ return Object.entries(native).map(([k, v]) => `${k}=${String(v)}`).join(' ');
97
+ }
package/dist/runner.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { Launch } from './harness/types.js';
3
3
  import { Tmux } from './tmux.js';
4
4
  import { type MonitorHandle, type MonitorOpts, type FetchLike } from './monitor.js';
5
5
  import { type Exec } from './exec.js';
6
+ import type { ExitRecord } from './session/types.js';
6
7
  export interface RunnerDeps {
7
8
  tmux: Tmux;
8
9
  exec: Exec;
@@ -15,7 +16,16 @@ export interface RunnerDeps {
15
16
  fetch: FetchLike;
16
17
  /** Construct the supervisor mail monitor (injectable so tests stub it out). */
17
18
  createMonitor(opts: MonitorOpts): MonitorHandle;
19
+ /** Lets a test (or a shutdown path) end the supervised restart loop. */
20
+ shouldStop?(): boolean;
18
21
  }
22
+ /**
23
+ * Record who owns wake delivery for this run. Returning true means a fleet
24
+ * monitor is taking ownership back from a native harness and must start at the
25
+ * current stream tip rather than replay notifications the native owner was
26
+ * responsible for.
27
+ */
28
+ export declare function recordMonitorOwner(dir: string, owner: 'fleet' | 'native'): boolean;
19
29
  /**
20
30
  * Compose the tmux pane shell command: env prefix + argv + exit-status capture.
21
31
  * `paneArgv` defaults to `launch.argv`; when isolation is active the caller passes
@@ -24,6 +34,41 @@ export interface RunnerDeps {
24
34
  * still sees the real exit code.
25
35
  */
26
36
  export declare function buildPaneCommand(launch: Launch, roleEnv: Record<string, string> | undefined, exitStatusPath: string, paneArgv?: string[]): string;
37
+ /**
38
+ * Read the pane's `.exit-status`. Three shapes are accepted: the structured
39
+ * record written above, a bare number left by a pre-upgrade pane (so an
40
+ * in-place upgrade does not misread a real exit), and anything else — which is
41
+ * `unknown`, never an invented failure. A missing file returns null so the
42
+ * caller can distinguish "no record" from "a record saying unknown".
43
+ */
44
+ export declare function readExitRecord(path: string): ExitRecord | null;
45
+ export declare const RESTART_LEDGER_FILE = ".restart-ledger.json";
46
+ /** Consecutive immediate failures tolerated before the agent is held down. */
47
+ export declare const RESTART_FAIL_THRESHOLD = 5;
48
+ export interface RestartLedger {
49
+ version: 1;
50
+ consecutiveImmediateFailures: number;
51
+ lastReason: string;
52
+ nextDelayMs: number;
53
+ /** Whether this failure sequence has already thrown away resume state. */
54
+ resumeDiscarded: boolean;
55
+ circuit: 'closed' | 'open';
56
+ updatedAt: string;
57
+ /** When the circuit opened, for the held-down status line. */
58
+ openedAt?: string;
59
+ }
60
+ /** Bounded exponential backoff for the nth consecutive immediate failure. */
61
+ export declare function backoffFor(consecutiveFailures: number): number;
62
+ /** Read a role's restart ledger; a missing or corrupt one starts clean. */
63
+ export declare function readRestartLedger(dir: string): RestartLedger;
64
+ export declare function writeRestartLedger(dir: string, ledger: RestartLedger): void;
65
+ /**
66
+ * Close the circuit and forget the failure streak. Called by an explicit
67
+ * operator `up`/`restart`, which is the only thing that may release a held-down
68
+ * role — a held-down runner polls this file, so a role can be released without
69
+ * bouncing its unit.
70
+ */
71
+ export declare function resetRestartLedger(dir: string): void;
27
72
  /** Filename spawnTemp writes into a temp agent dir to carry the fleet start-stagger. */
28
73
  export declare const START_STAGGER_FILE = ".start-stagger-ms";
29
74
  /**
@@ -37,10 +82,35 @@ export declare const START_STAGGER_FILE = ".start-stagger-ms";
37
82
  export declare function reserveLaunchSlot(root: string, staggerMs: number, deps: Pick<RunnerDeps, 'now' | 'sleep' | 'log'>): Promise<number>;
38
83
  /** Read a temp role's config snapshot written by spawnTemp. */
39
84
  export declare function loadTempRole(name: string): ResolvedRole;
40
- /** One supervised session lifecycle. The supervisor re-invokes us after we return. */
85
+ /** What one child session did, so the supervising loop can decide what follows. */
86
+ export interface AttemptResult {
87
+ elapsedSecs: number;
88
+ exit: ExitRecord;
89
+ /** Whether this attempt threw away resume state to start fresh. */
90
+ rotated: boolean;
91
+ mode: 'fresh' | 'resume';
92
+ }
93
+ /** One session lifecycle. `runSupervised` (or a one-shot caller) drives it. */
41
94
  export declare function runOnce(name: string, opts?: {
42
95
  temp?: boolean;
43
96
  configPath?: string;
44
- }, partialDeps?: Partial<RunnerDeps>): Promise<void>;
97
+ allowResumeRotation?: boolean;
98
+ }, partialDeps?: Partial<RunnerDeps>): Promise<AttemptResult>;
99
+ /**
100
+ * The persistent supervisor for one permanent role: run child sessions in a
101
+ * loop, count consecutive immediate failures across them, back off between
102
+ * attempts, and after `RESTART_FAIL_THRESHOLD` hold the agent down while
103
+ * staying alive — so the service manager has nothing to restart and cannot
104
+ * resume the two-second loop behind our back.
105
+ *
106
+ * `attempt` is injectable so the policy can be tested against a fake clock and
107
+ * fake child instead of real sessions.
108
+ */
109
+ export declare function runSupervised(name: string, opts?: {
110
+ configPath?: string;
111
+ }, partialDeps?: Partial<RunnerDeps>, attempt?: (n: string, o: {
112
+ configPath?: string;
113
+ allowResumeRotation?: boolean;
114
+ }, d: Partial<RunnerDeps>) => Promise<AttemptResult>): Promise<RestartLedger>;
45
115
  /** Temp-agent entrypoint: run one session, then remove the temp dir. */
46
116
  export declare function runTemp(name: string, deps?: Partial<RunnerDeps>): Promise<void>;