owenloop 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +98 -25
- package/bin/owenloop.mjs +2 -2
- package/dist/packages/work/src/agent/brief.d.ts +172 -0
- package/dist/packages/work/src/agent/brief.js +193 -0
- package/dist/packages/work/src/agent/loop.d.ts +135 -0
- package/dist/packages/work/src/agent/loop.js +542 -0
- package/dist/packages/work/src/agent/workdir.d.ts +210 -0
- package/dist/packages/work/src/agent/workdir.js +319 -0
- package/dist/packages/work/src/bundle/cache.d.ts +90 -0
- package/dist/packages/work/src/bundle/cache.js +324 -0
- package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
- package/dist/packages/work/src/bundle/fetch.js +325 -0
- package/dist/packages/work/src/bundle/types.d.ts +160 -0
- package/dist/packages/work/src/bundle/types.js +1 -0
- package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
- package/dist/packages/work/src/credentials/owenloop.js +28 -0
- package/dist/packages/work/src/credentials/reader.d.ts +36 -0
- package/dist/packages/work/src/credentials/reader.js +32 -0
- package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
- package/dist/packages/work/src/credentials/resolve.js +56 -0
- package/dist/packages/work/src/exec/loop.d.ts +29 -0
- package/dist/packages/work/src/exec/loop.js +215 -0
- package/dist/packages/work/src/exec/receipt.d.ts +38 -0
- package/dist/packages/work/src/exec/receipt.js +21 -0
- package/dist/packages/work/src/exec/runner.d.ts +65 -0
- package/dist/packages/work/src/exec/runner.js +185 -0
- package/dist/packages/work/src/harness/child-env.d.ts +100 -0
- package/dist/packages/work/src/harness/child-env.js +127 -0
- package/dist/packages/work/src/harness/claude.d.ts +128 -0
- package/dist/packages/work/src/harness/claude.js +635 -0
- package/dist/packages/work/src/harness/codex.d.ts +110 -0
- package/dist/packages/work/src/harness/codex.js +896 -0
- package/dist/packages/work/src/harness/contract.d.ts +283 -0
- package/dist/packages/work/src/harness/contract.js +32 -0
- package/dist/packages/work/src/harness/fake.d.ts +59 -0
- package/dist/packages/work/src/harness/fake.js +90 -0
- package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
- package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
- package/dist/packages/work/src/harness/permissions.d.ts +62 -0
- package/dist/packages/work/src/harness/permissions.js +93 -0
- package/dist/packages/work/src/harness/registry.d.ts +47 -0
- package/dist/packages/work/src/harness/registry.js +45 -0
- package/dist/packages/work/src/harness/session-store.d.ts +163 -0
- package/dist/packages/work/src/harness/session-store.js +319 -0
- package/dist/packages/work/src/harness/types.d.ts +29 -0
- package/dist/packages/work/src/harness/types.js +14 -0
- package/dist/packages/work/src/harnesses.d.ts +38 -0
- package/dist/packages/work/src/harnesses.js +38 -0
- package/dist/packages/work/src/hold/loop.d.ts +36 -0
- package/dist/packages/work/src/hold/loop.js +23 -0
- package/dist/packages/work/src/hold/mcp.d.ts +55 -0
- package/dist/packages/work/src/hold/mcp.js +149 -0
- package/dist/packages/work/src/hub/client.d.ts +22 -0
- package/dist/packages/work/src/hub/client.js +78 -0
- package/dist/packages/work/src/hub/types.d.ts +290 -0
- package/dist/packages/work/src/hub/types.js +28 -0
- package/dist/packages/work/src/lease/loop.d.ts +94 -0
- package/dist/packages/work/src/lease/loop.js +277 -0
- package/dist/packages/work/src/main.d.ts +1 -0
- package/dist/packages/work/src/main.js +48 -0
- package/dist/packages/work/src/mcp/server.d.ts +125 -0
- package/dist/packages/work/src/mcp/server.js +320 -0
- package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
- package/dist/packages/work/src/roles/agent-run.js +447 -0
- package/dist/packages/work/src/roles/exec.d.ts +40 -0
- package/dist/packages/work/src/roles/exec.js +203 -0
- package/dist/packages/work/src/roles/hold.d.ts +68 -0
- package/dist/packages/work/src/roles/hold.js +324 -0
- package/dist/packages/work/src/roles/join.d.ts +18 -0
- package/dist/packages/work/src/roles/join.js +204 -0
- package/dist/packages/work/src/roles/lint.d.ts +59 -0
- package/dist/packages/work/src/roles/lint.js +200 -0
- package/dist/packages/work/src/roles/prepare.d.ts +1 -0
- package/dist/packages/work/src/roles/prepare.js +249 -0
- package/dist/packages/work/src/roles/release.d.ts +48 -0
- package/dist/packages/work/src/roles/release.js +137 -0
- package/dist/packages/work/src/roles/sessions.d.ts +61 -0
- package/dist/packages/work/src/roles/sessions.js +180 -0
- package/dist/packages/work/src/roles/settings.d.ts +6 -0
- package/dist/packages/work/src/roles/settings.js +66 -0
- package/dist/packages/work/src/roles/shift.d.ts +12 -0
- package/dist/packages/work/src/roles/shift.js +228 -0
- package/dist/packages/work/src/roles/signals.d.ts +55 -0
- package/dist/packages/work/src/roles/signals.js +62 -0
- package/dist/packages/work/src/settings/provision.d.ts +21 -0
- package/dist/packages/work/src/settings/provision.js +47 -0
- package/dist/packages/work/src/settings/settings.d.ts +120 -0
- package/dist/packages/work/src/settings/settings.js +116 -0
- package/dist/packages/work/src/shift/client.d.ts +24 -0
- package/dist/packages/work/src/shift/client.js +124 -0
- package/dist/packages/work/src/shift/loop.d.ts +120 -0
- package/dist/packages/work/src/shift/loop.js +468 -0
- package/dist/packages/work/src/shift/protocol.d.ts +91 -0
- package/dist/packages/work/src/shift/protocol.js +24 -0
- package/dist/packages/work/src/shift/routing.d.ts +35 -0
- package/dist/packages/work/src/shift/routing.js +50 -0
- package/dist/packages/work/src/shift/runtime.d.ts +43 -0
- package/dist/packages/work/src/shift/runtime.js +274 -0
- package/dist/packages/work/src/shift/server.d.ts +23 -0
- package/dist/packages/work/src/shift/server.js +716 -0
- package/dist/packages/work/src/shift/spawn.d.ts +86 -0
- package/dist/packages/work/src/shift/spawn.js +100 -0
- package/dist/packages/work/src/shift/state.d.ts +77 -0
- package/dist/packages/work/src/shift/state.js +162 -0
- package/dist/packages/work/src/usage.d.ts +6 -0
- package/dist/packages/work/src/usage.js +175 -0
- package/dist/{add.d.ts → src/add.d.ts} +12 -40
- package/dist/{add.js → src/add.js} +11 -176
- package/dist/src/cli.d.ts +147 -0
- package/dist/{cli.js → src/cli.js} +1643 -353
- package/dist/src/credentials.d.ts +280 -0
- package/dist/src/credentials.js +697 -0
- package/dist/{defs.js → src/defs.js} +59 -36
- package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
- package/dist/{engine.js → src/engine.js} +29 -20
- package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
- package/dist/{hub.js → src/hub.js} +531 -1
- package/dist/{index.d.ts → src/index.d.ts} +3 -1
- package/dist/{index.js → src/index.js} +2 -1
- package/dist/src/lock.d.ts +80 -0
- package/dist/src/lock.js +217 -0
- package/dist/src/mcp/serve.d.ts +85 -0
- package/dist/src/mcp/serve.js +702 -0
- package/dist/src/mcp/server.d.ts +132 -0
- package/dist/src/mcp/server.js +327 -0
- package/dist/{model.d.ts → src/model.d.ts} +59 -4
- package/dist/{model.js → src/model.js} +149 -22
- package/dist/{types.d.ts → src/types.d.ts} +66 -24
- package/dist/{util.d.ts → src/util.d.ts} +25 -0
- package/dist/{util.js → src/util.js} +26 -0
- package/dist/src/work-settings.d.ts +57 -0
- package/dist/src/work-settings.js +84 -0
- package/docs/authoring.md +102 -53
- package/docs/cli.md +883 -29
- package/docs/design.md +119 -45
- package/docs/embedding.md +39 -14
- package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
- package/examples/workflows/compile-dev-playbook.yaml +338 -0
- package/examples/workflows/judges/gate-sharpness.md +39 -0
- package/examples/workflows/judges/security.md +34 -0
- package/package.json +17 -8
- package/dist/cli.d.ts +0 -83
- /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
- /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
- /package/dist/{factory.js → src/factory.js} +0 -0
- /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
- /package/dist/{paths.js → src/paths.js} +0 -0
- /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
- /package/dist/{schema.js → src/schema.js} +0 -0
- /package/dist/{store.d.ts → src/store.d.ts} +0 -0
- /package/dist/{store.js → src/store.js} +0 -0
- /package/dist/{types.js → src/types.js} +0 -0
- /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
- /package/dist/{untar.js → src/untar.js} +0 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lease-loop core — keeps ONE order's lease alive by heartbeating the hub
|
|
3
|
+
* on a safe cadence, and performs a bounded final-breath release on shutdown.
|
|
4
|
+
*
|
|
5
|
+
* Extracted from C4's `hold` loop (C5, plan decision 4) so the two self-leasing
|
|
6
|
+
* roles share ONE implementation of cadence/backoff/clock-jump/classification/
|
|
7
|
+
* final-breath rather than duplicating it:
|
|
8
|
+
* - `hold` (`src/hold/loop.ts`) wraps this with `role: 'hold'` — its observable
|
|
9
|
+
* behavior (outcomes, exit codes, every emitted message string) is unchanged;
|
|
10
|
+
* the hold tests pass unedited.
|
|
11
|
+
* - `exec` (`src/exec/loop.ts`) wraps this with `role: 'exec'` and an `onOrder`
|
|
12
|
+
* callback so it can read the first-contact order packet and run the command
|
|
13
|
+
* while this loop keeps the lease warm underneath it.
|
|
14
|
+
*
|
|
15
|
+
* Like C3's shift loop, every side effect is injected (hub client, sleep/clock,
|
|
16
|
+
* jitter, output sinks) so every test drives it with a fake hub, a scriptable
|
|
17
|
+
* clock, and no real timers.
|
|
18
|
+
*
|
|
19
|
+
* LIFECYCLE
|
|
20
|
+
* - First contact: `get_order({workflow, run, holder})`. This beats the lease,
|
|
21
|
+
* closes the B2 pickup window, tags the holder, and validates the
|
|
22
|
+
* (workflow, run) pairing. On a claimed lease it fires `onOrder(res)` (so the
|
|
23
|
+
* caller can read the packet from the SAME response — no second fetch) and
|
|
24
|
+
* returns `holding`. `lease.claimed:false` with an `outcome` ⇒ the order
|
|
25
|
+
* already finished (`completed`); with no outcome ⇒ nothing to hold
|
|
26
|
+
* (`lease-lost`). A 403 ⇒ `ownership-error`; other throws retry under the
|
|
27
|
+
* backoff policy before giving up `hub-unreachable`.
|
|
28
|
+
* - Tick: abortable `sleep(heartbeatIntervalMs)` → clock-jump check (a wall gap
|
|
29
|
+
* beyond interval + tolerance, e.g. a laptop sleeping, triggers a `get_order`
|
|
30
|
+
* lease check BEFORE the next beat so we fail fast on a dead lease) →
|
|
31
|
+
* `heartbeat({workflow, run, holder})`.
|
|
32
|
+
* - Heartbeat failure: 403 ⇒ `ownership-error` immediately; any other error
|
|
33
|
+
* (the engine's lease-gone 500 included) is classified via `get_order`
|
|
34
|
+
* (`outcome` ⇒ `completed`, unclaimed ⇒ `lease-lost`, still claimed / classify
|
|
35
|
+
* failed ⇒ transient). Transient failures back off (exponential + jitter,
|
|
36
|
+
* base 1s ×2 cap 30s) without ever sleeping past the failure window; once
|
|
37
|
+
* consecutive failures span `failureWindowMs`, one last classify then
|
|
38
|
+
* `hub-unreachable`.
|
|
39
|
+
* - `stop(reason, {release?})` flips a flag checked between awaits AND aborts
|
|
40
|
+
* the in-flight interval sleep (final breath fires ~immediately, not up to a
|
|
41
|
+
* full interval late), then — unless the order already `completed` or the
|
|
42
|
+
* caller passed `release:false` — a targeted `release` bounded at
|
|
43
|
+
* RELEASE_CAP_MS. `release:false` is exec's "the run just closed via submit,
|
|
44
|
+
* don't release" path (a release then would be a confusing no-op). Release is
|
|
45
|
+
* idempotent hub-side (`not-held` is a no-op, never a throw), so a normal
|
|
46
|
+
* completion or a reaper race both land as `released`; a throw/timeout is
|
|
47
|
+
* `release-failed`.
|
|
48
|
+
*
|
|
49
|
+
* OUTCOME → the role maps each to an exit code in one place (see the roles).
|
|
50
|
+
*/
|
|
51
|
+
import { type ContactHolder, type GetOrderResponse } from '../hub/types.ts';
|
|
52
|
+
import type { HubClient } from '../hub/client.ts';
|
|
53
|
+
/** Discriminated result of a lease run; the role maps these to exit codes. */
|
|
54
|
+
export type LeaseOutcome = 'completed' | 'released' | 'release-failed' | 'ownership-error' | 'lease-lost' | 'hub-unreachable' | 'stopped';
|
|
55
|
+
/** Options handed to `stop()`. */
|
|
56
|
+
export interface StopOptions {
|
|
57
|
+
/** Skip the final-breath release (default true = release). exec passes false
|
|
58
|
+
* after a successful submit — the run already closed, so releasing would be a
|
|
59
|
+
* confusing no-op in the logs. */
|
|
60
|
+
release?: boolean;
|
|
61
|
+
}
|
|
62
|
+
export interface LeaseLoopOptions {
|
|
63
|
+
hub: HubClient;
|
|
64
|
+
workflow: string;
|
|
65
|
+
run: string;
|
|
66
|
+
/** Message prefix `owenloop work ${role}: …`. hold passes `'hold'`, exec `'exec'`. */
|
|
67
|
+
role: string;
|
|
68
|
+
/** `{kind, id}` when the holder identity is known; else omitted. */
|
|
69
|
+
holder?: ContactHolder;
|
|
70
|
+
/** Fired once on a successful first contact, with the same get_order response
|
|
71
|
+
* that established the hold — the caller reads the order packet from it. */
|
|
72
|
+
onOrder?: (res: GetOrderResponse) => void;
|
|
73
|
+
/** Injected sleep — tests pass a scriptable stub (no real timers). */
|
|
74
|
+
sleep: (ms: number) => Promise<void>;
|
|
75
|
+
/** Injected clock. */
|
|
76
|
+
now: () => number;
|
|
77
|
+
/** Jitter seam (default `Math.random`). */
|
|
78
|
+
random?: () => number;
|
|
79
|
+
/** stdout sink (one line per call; newline appended by the caller). */
|
|
80
|
+
out: (line: string) => void;
|
|
81
|
+
/** stderr sink. */
|
|
82
|
+
err: (line: string) => void;
|
|
83
|
+
/** Heartbeat cadence (default 60_000). */
|
|
84
|
+
heartbeatIntervalMs?: number;
|
|
85
|
+
/** Wall-gap slack before a tick is treated as a clock jump (default 30_000). */
|
|
86
|
+
jumpToleranceMs?: number;
|
|
87
|
+
/** Consecutive-failure give-up horizon (default 180_000). */
|
|
88
|
+
failureWindowMs?: number;
|
|
89
|
+
}
|
|
90
|
+
export interface LeaseLoop {
|
|
91
|
+
run(): Promise<LeaseOutcome>;
|
|
92
|
+
stop(reason?: string, opts?: StopOptions): void;
|
|
93
|
+
}
|
|
94
|
+
export declare function createLeaseLoop(opts: LeaseLoopOptions): LeaseLoop;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lease-loop core — keeps ONE order's lease alive by heartbeating the hub
|
|
3
|
+
* on a safe cadence, and performs a bounded final-breath release on shutdown.
|
|
4
|
+
*
|
|
5
|
+
* Extracted from C4's `hold` loop (C5, plan decision 4) so the two self-leasing
|
|
6
|
+
* roles share ONE implementation of cadence/backoff/clock-jump/classification/
|
|
7
|
+
* final-breath rather than duplicating it:
|
|
8
|
+
* - `hold` (`src/hold/loop.ts`) wraps this with `role: 'hold'` — its observable
|
|
9
|
+
* behavior (outcomes, exit codes, every emitted message string) is unchanged;
|
|
10
|
+
* the hold tests pass unedited.
|
|
11
|
+
* - `exec` (`src/exec/loop.ts`) wraps this with `role: 'exec'` and an `onOrder`
|
|
12
|
+
* callback so it can read the first-contact order packet and run the command
|
|
13
|
+
* while this loop keeps the lease warm underneath it.
|
|
14
|
+
*
|
|
15
|
+
* Like C3's shift loop, every side effect is injected (hub client, sleep/clock,
|
|
16
|
+
* jitter, output sinks) so every test drives it with a fake hub, a scriptable
|
|
17
|
+
* clock, and no real timers.
|
|
18
|
+
*
|
|
19
|
+
* LIFECYCLE
|
|
20
|
+
* - First contact: `get_order({workflow, run, holder})`. This beats the lease,
|
|
21
|
+
* closes the B2 pickup window, tags the holder, and validates the
|
|
22
|
+
* (workflow, run) pairing. On a claimed lease it fires `onOrder(res)` (so the
|
|
23
|
+
* caller can read the packet from the SAME response — no second fetch) and
|
|
24
|
+
* returns `holding`. `lease.claimed:false` with an `outcome` ⇒ the order
|
|
25
|
+
* already finished (`completed`); with no outcome ⇒ nothing to hold
|
|
26
|
+
* (`lease-lost`). A 403 ⇒ `ownership-error`; other throws retry under the
|
|
27
|
+
* backoff policy before giving up `hub-unreachable`.
|
|
28
|
+
* - Tick: abortable `sleep(heartbeatIntervalMs)` → clock-jump check (a wall gap
|
|
29
|
+
* beyond interval + tolerance, e.g. a laptop sleeping, triggers a `get_order`
|
|
30
|
+
* lease check BEFORE the next beat so we fail fast on a dead lease) →
|
|
31
|
+
* `heartbeat({workflow, run, holder})`.
|
|
32
|
+
* - Heartbeat failure: 403 ⇒ `ownership-error` immediately; any other error
|
|
33
|
+
* (the engine's lease-gone 500 included) is classified via `get_order`
|
|
34
|
+
* (`outcome` ⇒ `completed`, unclaimed ⇒ `lease-lost`, still claimed / classify
|
|
35
|
+
* failed ⇒ transient). Transient failures back off (exponential + jitter,
|
|
36
|
+
* base 1s ×2 cap 30s) without ever sleeping past the failure window; once
|
|
37
|
+
* consecutive failures span `failureWindowMs`, one last classify then
|
|
38
|
+
* `hub-unreachable`.
|
|
39
|
+
* - `stop(reason, {release?})` flips a flag checked between awaits AND aborts
|
|
40
|
+
* the in-flight interval sleep (final breath fires ~immediately, not up to a
|
|
41
|
+
* full interval late), then — unless the order already `completed` or the
|
|
42
|
+
* caller passed `release:false` — a targeted `release` bounded at
|
|
43
|
+
* RELEASE_CAP_MS. `release:false` is exec's "the run just closed via submit,
|
|
44
|
+
* don't release" path (a release then would be a confusing no-op). Release is
|
|
45
|
+
* idempotent hub-side (`not-held` is a no-op, never a throw), so a normal
|
|
46
|
+
* completion or a reaper race both land as `released`; a throw/timeout is
|
|
47
|
+
* `release-failed`.
|
|
48
|
+
*
|
|
49
|
+
* OUTCOME → the role maps each to an exit code in one place (see the roles).
|
|
50
|
+
*/
|
|
51
|
+
import { HubError } from "../hub/types.js";
|
|
52
|
+
const DEFAULT_INTERVAL_MS = 60_000;
|
|
53
|
+
const DEFAULT_JUMP_TOLERANCE_MS = 30_000;
|
|
54
|
+
const DEFAULT_FAILURE_WINDOW_MS = 180_000;
|
|
55
|
+
const BACKOFF_BASE_MS = 1_000;
|
|
56
|
+
const BACKOFF_CAP_MS = 30_000;
|
|
57
|
+
const BACKOFF_JITTER = 0.2;
|
|
58
|
+
const RELEASE_CAP_MS = 5_000;
|
|
59
|
+
function errMsg(e) {
|
|
60
|
+
return e instanceof Error ? e.message : String(e);
|
|
61
|
+
}
|
|
62
|
+
function isForbidden(e) {
|
|
63
|
+
return e instanceof HubError && e.status === 403;
|
|
64
|
+
}
|
|
65
|
+
export function createLeaseLoop(opts) {
|
|
66
|
+
const interval = opts.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS;
|
|
67
|
+
const jumpTolerance = opts.jumpToleranceMs ?? DEFAULT_JUMP_TOLERANCE_MS;
|
|
68
|
+
const failureWindow = opts.failureWindowMs ?? DEFAULT_FAILURE_WINDOW_MS;
|
|
69
|
+
const random = opts.random ?? Math.random;
|
|
70
|
+
const { workflow, role } = opts;
|
|
71
|
+
const runId = opts.run;
|
|
72
|
+
const req = { workflow, run: runId, ...(opts.holder !== undefined ? { holder: opts.holder } : {}) };
|
|
73
|
+
let stopped = false;
|
|
74
|
+
let stopReason = '';
|
|
75
|
+
let releaseOnStop = true;
|
|
76
|
+
// A single stop promise, resolved once, so any in-flight (or later) abortable
|
|
77
|
+
// sleep returns immediately after stop().
|
|
78
|
+
let resolveStop;
|
|
79
|
+
const stopPromise = new Promise((r) => {
|
|
80
|
+
resolveStop = r;
|
|
81
|
+
});
|
|
82
|
+
// Shared consecutive-failure tracker (first contact + heartbeat both feed it).
|
|
83
|
+
let firstFailureAt;
|
|
84
|
+
let attempt = 0;
|
|
85
|
+
function recordFailure() {
|
|
86
|
+
if (firstFailureAt === undefined)
|
|
87
|
+
firstFailureAt = opts.now();
|
|
88
|
+
attempt++;
|
|
89
|
+
}
|
|
90
|
+
function resetFailures() {
|
|
91
|
+
firstFailureAt = undefined;
|
|
92
|
+
attempt = 0;
|
|
93
|
+
}
|
|
94
|
+
function failureWindowExceeded() {
|
|
95
|
+
return firstFailureAt !== undefined && opts.now() - firstFailureAt >= failureWindow;
|
|
96
|
+
}
|
|
97
|
+
/** Sleep that resolves early when stop() fires. */
|
|
98
|
+
async function abortableSleep(ms) {
|
|
99
|
+
if (stopped)
|
|
100
|
+
return;
|
|
101
|
+
await Promise.race([opts.sleep(ms), stopPromise]);
|
|
102
|
+
}
|
|
103
|
+
/** Backoff delay for the current `attempt`, jittered and window-bounded. */
|
|
104
|
+
function backoffDelay() {
|
|
105
|
+
const raw = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, attempt - 1));
|
|
106
|
+
const jittered = raw * (1 + (random() * 2 - 1) * BACKOFF_JITTER);
|
|
107
|
+
let delay = Math.max(0, Math.round(jittered));
|
|
108
|
+
// Never sleep past the failure window — leave room for the final classify.
|
|
109
|
+
if (firstFailureAt !== undefined) {
|
|
110
|
+
const remaining = failureWindow - (opts.now() - firstFailureAt);
|
|
111
|
+
if (remaining > 0)
|
|
112
|
+
delay = Math.min(delay, remaining);
|
|
113
|
+
}
|
|
114
|
+
return delay;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* A get_order lease probe used for the clock-jump check and for classifying a
|
|
118
|
+
* heartbeat failure. Any throw (including a 403, which on this path means the
|
|
119
|
+
* hub is being flaky rather than a fresh ownership loss the beat already
|
|
120
|
+
* surfaced) is reported as `transient` so the caller's backoff owns it.
|
|
121
|
+
*/
|
|
122
|
+
async function probe() {
|
|
123
|
+
try {
|
|
124
|
+
const res = await opts.hub.getOrder(req);
|
|
125
|
+
if (res.lease.claimed)
|
|
126
|
+
return 'holding';
|
|
127
|
+
return res.lease.outcome !== undefined ? 'completed' : 'lease-lost';
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return 'transient';
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Establish the hold. Returns `holding` once the lease is confirmed (after
|
|
135
|
+
* firing `onOrder`), a terminal outcome, or `stopped` if stop() arrived before
|
|
136
|
+
* we established it.
|
|
137
|
+
*/
|
|
138
|
+
async function firstContact() {
|
|
139
|
+
for (;;) {
|
|
140
|
+
if (stopped)
|
|
141
|
+
return 'stopped';
|
|
142
|
+
try {
|
|
143
|
+
const res = await opts.hub.getOrder(req);
|
|
144
|
+
resetFailures();
|
|
145
|
+
if (res.lease.claimed) {
|
|
146
|
+
opts.onOrder?.(res);
|
|
147
|
+
return 'holding';
|
|
148
|
+
}
|
|
149
|
+
return res.lease.outcome !== undefined ? 'completed' : 'lease-lost';
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
if (isForbidden(e)) {
|
|
153
|
+
opts.err(`owenloop work ${role}: ${workflow}/${runId} is not yours to hold (forbidden)`);
|
|
154
|
+
return 'ownership-error';
|
|
155
|
+
}
|
|
156
|
+
recordFailure();
|
|
157
|
+
opts.err(`owenloop work ${role}: first contact failed: ${errMsg(e)} (retrying)`);
|
|
158
|
+
if (failureWindowExceeded())
|
|
159
|
+
return 'hub-unreachable';
|
|
160
|
+
await abortableSleep(backoffDelay());
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** One heartbeat tick. Returns a terminal outcome, or `undefined` to continue. */
|
|
165
|
+
async function tick() {
|
|
166
|
+
const before = opts.now();
|
|
167
|
+
await abortableSleep(interval);
|
|
168
|
+
if (stopped)
|
|
169
|
+
return undefined; // final breath handled by the caller
|
|
170
|
+
// Clock-jump guard: a wall gap well beyond the interval (laptop sleep) means
|
|
171
|
+
// the lease may have lapsed while we were suspended — check before beating.
|
|
172
|
+
const gap = opts.now() - before;
|
|
173
|
+
if (gap > interval + jumpTolerance) {
|
|
174
|
+
opts.err(`owenloop work ${role}: clock jump detected (${gap}ms gap) — verifying lease before beat`);
|
|
175
|
+
const p = await probe();
|
|
176
|
+
if (p === 'completed')
|
|
177
|
+
return 'completed';
|
|
178
|
+
if (p === 'lease-lost')
|
|
179
|
+
return 'lease-lost';
|
|
180
|
+
// 'holding' → carry on and beat; 'transient' → fall through, the beat's
|
|
181
|
+
// own failure handling will pick up the unreachable hub.
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
await opts.hub.heartbeat(req);
|
|
185
|
+
resetFailures();
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
if (isForbidden(e)) {
|
|
190
|
+
opts.err(`owenloop work ${role}: heartbeat forbidden — the claim is no longer yours`);
|
|
191
|
+
return 'ownership-error';
|
|
192
|
+
}
|
|
193
|
+
// Classify the failure: did the order finish, or was the lease lost?
|
|
194
|
+
const p = await probe();
|
|
195
|
+
if (p === 'completed')
|
|
196
|
+
return 'completed';
|
|
197
|
+
if (p === 'lease-lost')
|
|
198
|
+
return 'lease-lost';
|
|
199
|
+
// Transient (still claimed, or the classify call itself failed): back off.
|
|
200
|
+
recordFailure();
|
|
201
|
+
opts.err(`owenloop work ${role}: heartbeat failed: ${errMsg(e)} (attempt ${attempt}, backing off)`);
|
|
202
|
+
if (failureWindowExceeded()) {
|
|
203
|
+
const last = await probe();
|
|
204
|
+
if (last === 'completed')
|
|
205
|
+
return 'completed';
|
|
206
|
+
if (last === 'lease-lost')
|
|
207
|
+
return 'lease-lost';
|
|
208
|
+
opts.err(`owenloop work ${role}: hub unreachable for ${failureWindow}ms — giving up`);
|
|
209
|
+
return 'hub-unreachable';
|
|
210
|
+
}
|
|
211
|
+
await abortableSleep(backoffDelay());
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The final breath: a targeted release, bounded at RELEASE_CAP_MS. Skipped
|
|
217
|
+
* when the order already completed (a completed order has no claim to hand
|
|
218
|
+
* back) or when stop() asked for `release:false`. Idempotent hub-side, so
|
|
219
|
+
* `not-held` is success.
|
|
220
|
+
*/
|
|
221
|
+
async function finalBreath(alreadyCompleted) {
|
|
222
|
+
if (alreadyCompleted)
|
|
223
|
+
return 'completed';
|
|
224
|
+
if (!releaseOnStop)
|
|
225
|
+
return 'stopped';
|
|
226
|
+
opts.out(`owenloop work ${role}: final breath (${stopReason || 'stop'}) — releasing ${workflow}/${runId}`);
|
|
227
|
+
try {
|
|
228
|
+
const raced = await Promise.race([
|
|
229
|
+
opts.hub.release({ workflow, run: runId }).then(() => 'ok'),
|
|
230
|
+
opts.sleep(RELEASE_CAP_MS).then(() => 'timeout'),
|
|
231
|
+
]);
|
|
232
|
+
if (raced === 'timeout') {
|
|
233
|
+
opts.err(`owenloop work ${role}: release timed out after ${RELEASE_CAP_MS}ms — order strands until its lease TTL`);
|
|
234
|
+
return 'release-failed';
|
|
235
|
+
}
|
|
236
|
+
opts.out(`owenloop work ${role}: released ${workflow}/${runId} — the order re-offers on the next tick`);
|
|
237
|
+
return 'released';
|
|
238
|
+
}
|
|
239
|
+
catch (e) {
|
|
240
|
+
opts.err(`owenloop work ${role}: release failed: ${errMsg(e)} — order strands until its lease TTL`);
|
|
241
|
+
return 'release-failed';
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async function run() {
|
|
245
|
+
const fc = await firstContact();
|
|
246
|
+
if (fc === 'stopped')
|
|
247
|
+
return 'stopped';
|
|
248
|
+
if (fc !== 'holding')
|
|
249
|
+
return fc;
|
|
250
|
+
opts.out(`owenloop work ${role}: holding ${workflow}/${runId}` +
|
|
251
|
+
(opts.holder !== undefined ? ` as ${opts.holder.kind} ${opts.holder.id}` : '') +
|
|
252
|
+
` (heartbeat every ${interval}ms)`);
|
|
253
|
+
for (;;) {
|
|
254
|
+
if (stopped)
|
|
255
|
+
break;
|
|
256
|
+
const outcome = await tick();
|
|
257
|
+
if (outcome === 'completed')
|
|
258
|
+
return 'completed';
|
|
259
|
+
if (outcome !== undefined)
|
|
260
|
+
return outcome;
|
|
261
|
+
if (stopped)
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
// Stopped while holding → hand off.
|
|
265
|
+
return finalBreath(false);
|
|
266
|
+
}
|
|
267
|
+
function stop(reason, stopOpts) {
|
|
268
|
+
if (stopped)
|
|
269
|
+
return;
|
|
270
|
+
stopped = true;
|
|
271
|
+
stopReason = reason ?? '';
|
|
272
|
+
if (stopOpts?.release === false)
|
|
273
|
+
releaseOnStop = false;
|
|
274
|
+
resolveStop();
|
|
275
|
+
}
|
|
276
|
+
return { run, stop };
|
|
277
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function mainAsync(argv: string[]): Promise<number>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `owenloop work` entry point: parse argv, dispatch one execution role, and map
|
|
3
|
+
* the role's returned code onto the process exit code.
|
|
4
|
+
*
|
|
5
|
+
* Exit-code contract (stable; roles and scripts depend on it):
|
|
6
|
+
* 0 success, or `--help` / `help` / `--version`
|
|
7
|
+
* 2 usage error — unknown or missing role, or a role's own arg validation
|
|
8
|
+
* failed (missing `--order`, missing `<order-id>`, …). Usage goes to stderr.
|
|
9
|
+
* 3 a role is a not-yet-implemented skeleton stub. Distinct from 0 so a
|
|
10
|
+
* script can never mistake a stub's "did nothing" for real success.
|
|
11
|
+
*
|
|
12
|
+
* The role table contains loaders rather than imported functions. This keeps
|
|
13
|
+
* `owenloop work settings` and `owenloop work lint` from evaluating unrelated
|
|
14
|
+
* worker or harness modules, and leaves the model SDK behind the adapter's own
|
|
15
|
+
* dynamic import boundary.
|
|
16
|
+
*/
|
|
17
|
+
import { USAGE } from "./usage.js";
|
|
18
|
+
const VERSION = '0.0.0';
|
|
19
|
+
const ROLES = {
|
|
20
|
+
hold: () => import("./roles/hold.js"),
|
|
21
|
+
exec: () => import("./roles/exec.js"),
|
|
22
|
+
'agent-run': () => import("./roles/agent-run.js"),
|
|
23
|
+
prepare: () => import("./roles/prepare.js"),
|
|
24
|
+
lint: () => import("./roles/lint.js"),
|
|
25
|
+
settings: () => import("./roles/settings.js"),
|
|
26
|
+
release: () => import("./roles/release.js"),
|
|
27
|
+
join: () => import("./roles/join.js"),
|
|
28
|
+
sessions: () => import("./roles/sessions.js"),
|
|
29
|
+
};
|
|
30
|
+
export async function mainAsync(argv) {
|
|
31
|
+
const [first, ...rest] = argv;
|
|
32
|
+
if (first === undefined || first === '--help' || first === '-h' || first === 'help') {
|
|
33
|
+
process.stdout.write(USAGE);
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
if (first === '--version') {
|
|
37
|
+
process.stdout.write(`${VERSION}\n`);
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
const loader = ROLES[first];
|
|
41
|
+
if (loader === undefined) {
|
|
42
|
+
process.stderr.write(`owenloop work: unknown command '${first}'\n\n`);
|
|
43
|
+
process.stderr.write(USAGE);
|
|
44
|
+
return 2;
|
|
45
|
+
}
|
|
46
|
+
const module = await loader();
|
|
47
|
+
return module.run(rest);
|
|
48
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
|
|
3
|
+
* over stdio, hand-rolled (plan decision 1).
|
|
4
|
+
*
|
|
5
|
+
* WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is one
|
|
6
|
+
* runtime dep (`yaml`). The SDK drags zod and a transport stack for a surface we
|
|
7
|
+
* need only a few hundred lines of. The hub side already proves interop against
|
|
8
|
+
* the official SDK client, and the `--mcp` e2e tests here drive a real
|
|
9
|
+
* client-side handshake, so drift is tested rather than assumed.
|
|
10
|
+
*
|
|
11
|
+
* The core is transport-agnostic and side-effect-injected: it exposes
|
|
12
|
+
* `handleLine(line)` (feed it one framed JSON-RPC line) and `close(reason)`
|
|
13
|
+
* (transport EOF), and it emits every outbound frame through the injected
|
|
14
|
+
* `write(msg)`. Unit tests feed lines and inspect writes with no child process;
|
|
15
|
+
* `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
|
|
16
|
+
*
|
|
17
|
+
* Supported methods (the subset the Shift + work-holder need):
|
|
18
|
+
* - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
|
|
19
|
+
* agreed protocolVersion (echo the client's when
|
|
20
|
+
* recognized, else answer with ours).
|
|
21
|
+
* - `notifications/initialized` → no-op (no response; it is a notification).
|
|
22
|
+
* - `ping` → `{}`.
|
|
23
|
+
* - `tools/list` → the registered tool defs.
|
|
24
|
+
* - `tools/call` → dispatch to the tool handler; the result is
|
|
25
|
+
* `{content:[{type:'text',text:<JSON>}], isError?}`.
|
|
26
|
+
* - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
|
|
27
|
+
* aborted call sends NO response frame.
|
|
28
|
+
* - outbound `notifications/progress` when a call carried
|
|
29
|
+
* `params._meta.progressToken` (via `ctx.sendProgress`).
|
|
30
|
+
*
|
|
31
|
+
* Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
|
|
32
|
+
* invalid params → -32602. A notification (no `id`) never gets a response, even
|
|
33
|
+
* on error. The process must never crash on a bad line.
|
|
34
|
+
*/
|
|
35
|
+
export declare const PARSE_ERROR = -32700;
|
|
36
|
+
export declare const INVALID_REQUEST = -32600;
|
|
37
|
+
export declare const METHOD_NOT_FOUND = -32601;
|
|
38
|
+
export declare const INVALID_PARAMS = -32602;
|
|
39
|
+
export declare const INTERNAL_ERROR = -32603;
|
|
40
|
+
/** A tool result as MCP serves it: text content blocks, optional error flag. */
|
|
41
|
+
export interface ToolResult {
|
|
42
|
+
content: Array<{
|
|
43
|
+
type: 'text';
|
|
44
|
+
text: string;
|
|
45
|
+
}>;
|
|
46
|
+
isError?: boolean;
|
|
47
|
+
}
|
|
48
|
+
/** Convenience: wrap a JSON-able value as a single text content block. */
|
|
49
|
+
export declare function textResult(value: unknown, isError?: boolean): ToolResult;
|
|
50
|
+
/** The per-call context handed to a tool handler. */
|
|
51
|
+
export interface ToolCallContext {
|
|
52
|
+
/** True once the caller cancelled this request (`notifications/cancelled`). */
|
|
53
|
+
readonly cancelled: boolean;
|
|
54
|
+
/** Register a callback fired when this request is cancelled. */
|
|
55
|
+
onCancel(cb: () => void): void;
|
|
56
|
+
/**
|
|
57
|
+
* Emit a `notifications/progress` frame for this call. A no-op when the caller
|
|
58
|
+
* supplied no `progressToken` (progress is meaningless without one).
|
|
59
|
+
*/
|
|
60
|
+
sendProgress(payload: {
|
|
61
|
+
progress?: number;
|
|
62
|
+
total?: number;
|
|
63
|
+
message?: string;
|
|
64
|
+
}): void;
|
|
65
|
+
}
|
|
66
|
+
export type ToolHandler = (args: Record<string, unknown>, ctx: ToolCallContext) => Promise<ToolResult> | ToolResult;
|
|
67
|
+
/** A registered tool: its advertised shape plus the handler that runs it. */
|
|
68
|
+
export interface ToolRegistration {
|
|
69
|
+
name: string;
|
|
70
|
+
description: string;
|
|
71
|
+
/** JSON-Schema for the tool's arguments (advertised via `tools/list`). */
|
|
72
|
+
inputSchema: Record<string, unknown>;
|
|
73
|
+
handler: ToolHandler;
|
|
74
|
+
}
|
|
75
|
+
export interface McpServerOptions {
|
|
76
|
+
name: string;
|
|
77
|
+
version: string;
|
|
78
|
+
tools: ToolRegistration[];
|
|
79
|
+
/** Outbound frame sink — the caller JSON-serializes + newline-terminates. */
|
|
80
|
+
write: (msg: unknown) => void;
|
|
81
|
+
/** Diagnostic sink (stderr); protocol frames never go here. */
|
|
82
|
+
err?: (line: string) => void;
|
|
83
|
+
}
|
|
84
|
+
export interface McpServer {
|
|
85
|
+
/** Feed one framed JSON-RPC line (no trailing newline required). */
|
|
86
|
+
handleLine(line: string): Promise<void>;
|
|
87
|
+
/**
|
|
88
|
+
* Transport EOF — cancels in-flight calls so parked handlers unblock. Their
|
|
89
|
+
* replies are still flushed (close-cancel ≠ client-cancel; see `InFlight`).
|
|
90
|
+
*/
|
|
91
|
+
close(reason?: string): void;
|
|
92
|
+
}
|
|
93
|
+
export declare function createMcpServer(opts: McpServerOptions): McpServer;
|
|
94
|
+
/** The slice of a readable stream `pumpStdin` needs — injectable for tests. */
|
|
95
|
+
export interface LineStream {
|
|
96
|
+
on(event: 'data', handler: (chunk: Buffer | string) => void): unknown;
|
|
97
|
+
on(event: 'end' | 'close', handler: () => void): unknown;
|
|
98
|
+
setEncoding?(enc: string): void;
|
|
99
|
+
resume?(): void;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Wire a real byte stream (`process.stdin`) into a server: buffer bytes, split
|
|
103
|
+
* on newlines, feed each complete line to `server.handleLine`, and call
|
|
104
|
+
* `server.close` + `onEof` once on EOF. A trailing partial line at EOF is
|
|
105
|
+
* flushed if non-empty.
|
|
106
|
+
*
|
|
107
|
+
* Every line is DISPATCHED THE MOMENT IT ARRIVES — never queued behind an
|
|
108
|
+
* in-flight `tools/call`. JSON-RPC over MCP is a concurrent protocol: while a
|
|
109
|
+
* long `whats_next` park is outstanding, `notifications/cancelled` must reach
|
|
110
|
+
* the server to abort it (D12 cancel-mid-park) and `ping` must still answer.
|
|
111
|
+
* Serializing the pump behind the in-flight call chain would deadlock exactly
|
|
112
|
+
* those frames on the real transport. Per-frame ordering still holds for the
|
|
113
|
+
* non-parking methods because `handleLine` runs synchronously up to the first
|
|
114
|
+
* tool-handler await, and responses are matched by id, not by order.
|
|
115
|
+
*
|
|
116
|
+
* EOF flushes the tail line, then calls `server.close` RIGHT AWAY — `close()`
|
|
117
|
+
* cancels any parked in-flight call, which is what lets a process waiting on
|
|
118
|
+
* this pump actually exit (chaining the close behind a parked call would
|
|
119
|
+
* deadlock EOF against the very call only the close can unpark). A close-cancel
|
|
120
|
+
* does NOT suppress the call's reply the way a client cancel does — every call
|
|
121
|
+
* received before EOF still answers. `onEof` fires only after every dispatched
|
|
122
|
+
* line has settled, so those reply frames are on the pipe before the caller
|
|
123
|
+
* acts on EOF (e.g. exits the process).
|
|
124
|
+
*/
|
|
125
|
+
export declare function pumpStdin(stream: LineStream, server: McpServer, onEof?: () => void): void;
|