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,896 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `codexAdapter` — the `HarnessAdapter` for OpenAI's `codex app-server`
|
|
3
|
+
* (pinned to `codex-cli 0.146.0`, the `"codex"` key in `harness-versions.json`).
|
|
4
|
+
*
|
|
5
|
+
* THIS IS THE ONLY FILE UNDER `src/harness/` ALLOWED TO KNOW THE NAME `codex`.
|
|
6
|
+
* `test/harness-isolation.test.ts` allowlists `src/harness/codex.ts` by exact
|
|
7
|
+
* path; every other module in the layer, including `./jsonrpc-stdio.ts`, is
|
|
8
|
+
* checked against `/claude|codex|anthropic|openai/i` over its full text,
|
|
9
|
+
* comments included. Keep vendor knowledge — argv, method names, param shapes,
|
|
10
|
+
* notification names — inside this file.
|
|
11
|
+
*
|
|
12
|
+
* Attribution: the JSON-RPC client in `./jsonrpc-stdio.ts` was adapted from the
|
|
13
|
+
* kanna project (`github.com/jakemor/kanna`), specifically the knowledge in its
|
|
14
|
+
* `src/server/codex-app-server.ts` and `src/server/codex-app-server-protocol.ts`
|
|
15
|
+
* — knowledge only, no source, and kanna is not a dependency. Copyright (c) 2025
|
|
16
|
+
* Jake Mor. Its LICENSE is the MIT text with the grant narrowed to "any person
|
|
17
|
+
* other than Jacob Eiting and RevenueCat, Inc." (which is why GitHub reports
|
|
18
|
+
* NOASSERTION rather than MIT). That carve-out does not name typicalday, so the
|
|
19
|
+
* port is permitted; the permission notice requires the copyright line be
|
|
20
|
+
* reproduced, which it is here and in `./jsonrpc-stdio.ts`.
|
|
21
|
+
*
|
|
22
|
+
* PROTOCOL FACTS THIS FILE IS BUILT ON (all probed against the pinned binary on
|
|
23
|
+
* 2026-07-30; the full account is `docs/agent-runner.md`, "Phase 2B"):
|
|
24
|
+
* - `thread/start` does NOT carry the brief. The brief rides a separate
|
|
25
|
+
* `turn/start`.
|
|
26
|
+
* - There is a mandatory `initialize` request followed by an `initialized`
|
|
27
|
+
* notification. Both are in the DEFAULT (non-experimental) method set.
|
|
28
|
+
* - Inbound frames omit the `jsonrpc` member entirely.
|
|
29
|
+
* - An unknown method sent as a REQUEST (one carrying an `id`) IS answered, but
|
|
30
|
+
* with `-32600 Invalid request: unknown variant '<method>', expected one of
|
|
31
|
+
* ...` — NOT the `-32601 Method not found` the JSON-RPC spec reserves for it.
|
|
32
|
+
* Sent as a NOTIFICATION (no `id`) it is silently dropped, which is correct.
|
|
33
|
+
* Malformed params on a KNOWN method also come back as `-32600`
|
|
34
|
+
* (`Invalid request: missing field 'threadId'`). So `-32600` is this server's
|
|
35
|
+
* catch-all for "I could not make sense of your request" — see below.
|
|
36
|
+
* - An unknown thread id on `thread/resume` returns `-32600` with the message
|
|
37
|
+
* `no rollout found for thread id <id>`. Because `-32600` is the catch-all
|
|
38
|
+
* above, the resume-unavailable test matches the code AND the message.
|
|
39
|
+
* - `turn/start`'s RESPONSE is an ACK: it came back in 5 ms carrying the created
|
|
40
|
+
* `Turn` with `status:'inProgress'`, while the turn actually ended 7.4 s later
|
|
41
|
+
* with a `turn/completed` notification. Resolving `start`/`deliver` on the
|
|
42
|
+
* response would report a finished turn that had barely begun. Both recorded
|
|
43
|
+
* timings are visible in `test/fixtures/codex-app-server-session.jsonl`.
|
|
44
|
+
* - The owenloop MCP mount is `config.mcp_servers.<name>`, a PER-THREAD option
|
|
45
|
+
* that MERGES with `~/.codex/config.toml` rather than replacing it.
|
|
46
|
+
* - An MCP server child does NOT inherit this process's environment. codex hands
|
|
47
|
+
* it only `HOME, LOGNAME, PATH, SHELL, TMPDIR, USER, __CF_USER_TEXT_ENCODING`
|
|
48
|
+
* plus `mcp_servers.<name>.env`. See `mountEnv` — without it the owenloop
|
|
49
|
+
* mount dies before its MCP `initialize` reply and the step agent has no
|
|
50
|
+
* `submit` tool.
|
|
51
|
+
*
|
|
52
|
+
* ENVIRONMENT IS INHERITED UNTOUCHED — a decision, not an omission. `codex`
|
|
53
|
+
* reads its own `~/.codex/auth.json` or the OS keyring, and there is no API-key
|
|
54
|
+
* environment variable on this side that silently shadows subscription auth and
|
|
55
|
+
* bills API credits. The Claude adapter strips its child environment for exactly
|
|
56
|
+
* that reason; copying the strip here would be cargo-culted protection against a
|
|
57
|
+
* failure mode that does not exist. So: no `env` on the spawn, no strip list, no
|
|
58
|
+
* billing opt-out flag.
|
|
59
|
+
*
|
|
60
|
+
* Failure stance: every diagnostic leaves as `{kind:'progress'}` through
|
|
61
|
+
* `onEvent` — nothing under `src/` prints. A resume against a token the provider
|
|
62
|
+
* has forgotten rejects with `ResumeUnavailableError`; every other failure emits
|
|
63
|
+
* `{kind:'exited'}` and rejects with the underlying error.
|
|
64
|
+
*/
|
|
65
|
+
import { existsSync } from 'node:fs';
|
|
66
|
+
import { ResumeUnavailableError } from "./contract.js";
|
|
67
|
+
import { register } from "./registry.js";
|
|
68
|
+
import { ADMITTED_OWENLOOP_KEYS, filterOwenloopEnv } from "./child-env.js";
|
|
69
|
+
import { JsonRpcError, startStdioRpc } from "./jsonrpc-stdio.js";
|
|
70
|
+
/** The adapter id. Matches the `"codex"` key in `harness-versions.json`, so the
|
|
71
|
+
* worker can use one string for both the version pin and the adapter lookup. */
|
|
72
|
+
export const HARNESS_ID = 'codex';
|
|
73
|
+
/** The MCP server name the step agent's `get_order` / `submit` tools live under. */
|
|
74
|
+
const OWENLOOP_MCP_NAME = 'owenloop';
|
|
75
|
+
/** `codex app-server` — the subcommand that speaks JSON-RPC over stdio. */
|
|
76
|
+
const APP_SERVER_ARGS = ['app-server'];
|
|
77
|
+
/** Client identity sent on `initialize`. Version is informational only. */
|
|
78
|
+
const CLIENT_INFO = { name: 'owenloop', version: '0.1.0' };
|
|
79
|
+
/** Handshake and thread setup are fast; a long budget would only mask a hang. */
|
|
80
|
+
const SETUP_TIMEOUT_MS = 30_000;
|
|
81
|
+
/**
|
|
82
|
+
* Budget for the `turn/start` ACK only — measured at 5 ms, so this is enormous
|
|
83
|
+
* slack, deliberately. It costs nothing: the gate settles on `turn/completed`
|
|
84
|
+
* independently, so a generous ack budget can never delay a finished turn, while
|
|
85
|
+
* a tight one could fail a healthy turn on a slow machine.
|
|
86
|
+
*/
|
|
87
|
+
const TURN_START_TIMEOUT_MS = 15 * 60_000;
|
|
88
|
+
/** `turn/interrupt` is best-effort during teardown; never block on it. */
|
|
89
|
+
const INTERRUPT_TIMEOUT_MS = 5_000;
|
|
90
|
+
/**
|
|
91
|
+
* How long teardown waits, AFTER an accepted `turn/interrupt`, for the server to
|
|
92
|
+
* emit the `turn/completed` that carries `status:'interrupted'`.
|
|
93
|
+
*
|
|
94
|
+
* Without this wait, teardown would kill the child while the in-flight
|
|
95
|
+
* `start`/`deliver` promise is still parked on the gate; the child's death then
|
|
96
|
+
* REJECTS that promise through `onExit`, and a caller who asked for an orderly
|
|
97
|
+
* stop gets a process-death error instead of an interrupted turn. Bounded, so a
|
|
98
|
+
* server that never answers cannot stall teardown.
|
|
99
|
+
*/
|
|
100
|
+
const INTERRUPT_SETTLE_MS = 5_000;
|
|
101
|
+
/** `item/commandExecution/outputDelta` can be enormous; cap what reaches the log. */
|
|
102
|
+
const PROGRESS_TEXT_CAP = 2_000;
|
|
103
|
+
/**
|
|
104
|
+
* The resume-failure signature, in ONE place.
|
|
105
|
+
*
|
|
106
|
+
* Observed verbatim on 0.146.0: `no rollout found for thread id <uuid>` with
|
|
107
|
+
* code `-32600`. The `thread not found` alternative is defensive against a
|
|
108
|
+
* wording change.
|
|
109
|
+
*
|
|
110
|
+
* Matching `-32600` ALONE would be actively wrong, and that is measured, not
|
|
111
|
+
* assumed: the same code and no other comes back for an unknown method name
|
|
112
|
+
* (`unknown variant '<method>'`) and for a missing required param
|
|
113
|
+
* (`missing field 'threadId'`). A client that read bare `-32600` as
|
|
114
|
+
* "thread is gone" would answer a typo in a method name by throwing away a live
|
|
115
|
+
* thread and cold-replaying the entire step.
|
|
116
|
+
*/
|
|
117
|
+
export const RESUME_UNAVAILABLE_MESSAGE_RE = /no rollout found|thread not found/i;
|
|
118
|
+
/** The JSON-RPC code the resume failure rides. Never sufficient on its own. */
|
|
119
|
+
export const RESUME_UNAVAILABLE_CODE = -32600;
|
|
120
|
+
/** True only when BOTH the code and the message say "I do not know this thread". */
|
|
121
|
+
export function isResumeMiss(err) {
|
|
122
|
+
if (!(err instanceof JsonRpcError))
|
|
123
|
+
return false;
|
|
124
|
+
return err.code === RESUME_UNAVAILABLE_CODE && RESUME_UNAVAILABLE_MESSAGE_RE.test(err.message);
|
|
125
|
+
}
|
|
126
|
+
/** The three legal `SandboxMode` values in 0.146.0. */
|
|
127
|
+
const SANDBOX_MODES = new Set(['read-only', 'workspace-write', 'danger-full-access']);
|
|
128
|
+
/**
|
|
129
|
+
* Default sandbox. A delivery-line step agent must be able to edit its own
|
|
130
|
+
* worktree, so `read-only` would fail every builder step; `danger-full-access`
|
|
131
|
+
* is available when a step asks for it, but granting it silently is not this
|
|
132
|
+
* adapter's call.
|
|
133
|
+
*/
|
|
134
|
+
const DEFAULT_SANDBOX = 'workspace-write';
|
|
135
|
+
/**
|
|
136
|
+
* `AskForApproval` values this adapter passes through untouched (the server's
|
|
137
|
+
* own vocabulary). Anything else maps to `'never'`.
|
|
138
|
+
*/
|
|
139
|
+
const NATIVE_APPROVAL_POLICIES = new Set(['untrusted', 'on-request', 'never']);
|
|
140
|
+
/**
|
|
141
|
+
* `permissionMode` → `approvalPolicy`.
|
|
142
|
+
*
|
|
143
|
+
* `'never'` is the default for everything unrecognized, and that is a decision:
|
|
144
|
+
* this runs headless with no human on the other end, so any policy that can
|
|
145
|
+
* raise a `requestApproval` server request converts a stalled approval into an
|
|
146
|
+
* order that hangs past the worker's lease. The adapter still answers those
|
|
147
|
+
* requests defensively (see `handleServerRequest`) — belt and braces, because
|
|
148
|
+
* `approvalPolicy` does not govern every request kind.
|
|
149
|
+
*/
|
|
150
|
+
function toApprovalPolicy(mode) {
|
|
151
|
+
if (mode === undefined)
|
|
152
|
+
return 'never';
|
|
153
|
+
if (NATIVE_APPROVAL_POLICIES.has(mode))
|
|
154
|
+
return mode;
|
|
155
|
+
return 'never';
|
|
156
|
+
}
|
|
157
|
+
function isPlainMap(v) {
|
|
158
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Non-`OWENLOOP_*` variables the owenloop CLI reads and the mount must carry.
|
|
162
|
+
* `HOME` is already in codex's own core set; re-supplying it costs nothing and
|
|
163
|
+
* keeps this list a complete statement of what the child needs.
|
|
164
|
+
*/
|
|
165
|
+
const MOUNT_ENV_KEEP = ['HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME'];
|
|
166
|
+
/**
|
|
167
|
+
* The environment for the owenloop mount, forwarded from THIS process.
|
|
168
|
+
*
|
|
169
|
+
* MEASURED, not assumed: `codex app-server` 0.146.0 does NOT give an MCP server
|
|
170
|
+
* child its own environment. It hands the child exactly
|
|
171
|
+
* `HOME, LOGNAME, PATH, SHELL, TMPDIR, USER, __CF_USER_TEXT_ENCODING`
|
|
172
|
+
* plus whatever `mcp_servers.<name>.env` supplies. So `OWENLOOP_TOKEN` never
|
|
173
|
+
* arrives on its own, `owenloop work hold --mcp` exits 2 before answering
|
|
174
|
+
* `initialize`, and codex reports the mount as
|
|
175
|
+
* `status:'failed'` / `handshaking with MCP server failed: connection closed:
|
|
176
|
+
* initialize response`. The agent then has no `submit` tool and the order can
|
|
177
|
+
* never complete. The Claude adapter never needed this because Claude Code
|
|
178
|
+
* passes its own environment to MCP children.
|
|
179
|
+
*
|
|
180
|
+
* PHASE 6 NARROWED THE `OWENLOOP_*` HALF FROM A PREFIX TO AN ALLOWLIST. It used
|
|
181
|
+
* to forward the whole `OWENLOOP_*` prefix so a new variable could not silently
|
|
182
|
+
* stop reaching the mount. That default is now inverted: `ADMITTED_OWENLOOP_KEYS`
|
|
183
|
+
* (`src/harness/child-env.ts`) enumerates the names a harness child may see, and
|
|
184
|
+
* a new `OWENLOOP_*` variable does NOT reach the mount until somebody adds it
|
|
185
|
+
* there with a named consumer. The reason is the same fact that made the prefix
|
|
186
|
+
* rule better than `{...process.env}`: `thread/start` params are persisted in
|
|
187
|
+
* codex's rollout file, so anything that reaches this mount has a path to disk —
|
|
188
|
+
* and the hub bearer override in particular must not take it.
|
|
189
|
+
*
|
|
190
|
+
* `MOUNT_ENV_KEEP` is unchanged. Note that the mount's environment is exactly
|
|
191
|
+
* what this function returns, so an ambient variable that is neither admitted
|
|
192
|
+
* nor in `MOUNT_ENV_KEEP` reaches the mount only through codex's own core set.
|
|
193
|
+
*
|
|
194
|
+
* This does not contradict "environment inherited untouched": that was about the
|
|
195
|
+
* `codex app-server` SPAWN, which now applies the same namespace filter and
|
|
196
|
+
* nothing else. This function restores what codex strips back off one specific
|
|
197
|
+
* child — the unified owenloop binary's work-holder command.
|
|
198
|
+
*/
|
|
199
|
+
function mountEnv() {
|
|
200
|
+
const out = {};
|
|
201
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
202
|
+
if (value === undefined)
|
|
203
|
+
continue;
|
|
204
|
+
if (ADMITTED_OWENLOOP_KEYS.has(key) || MOUNT_ENV_KEEP.includes(key)) {
|
|
205
|
+
out[key] = value;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
/** The mount for owenloop's own work-holder MCP surface, verbatim from the worker. */
|
|
211
|
+
function owenloopMount(mcp) {
|
|
212
|
+
return { command: mcp.command, args: [...mcp.args], env: mountEnv() };
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Build the `thread/start` params. PURE — exported for tests.
|
|
216
|
+
*
|
|
217
|
+
* Takes `DeliverArgs`, not `StartArgs`, because it never reads `brief` and Phase
|
|
218
|
+
* 4's `deliver` needs the identical mapping (`StartArgs` is assignable to
|
|
219
|
+
* `DeliverArgs`, so every `start` call site is unaffected).
|
|
220
|
+
*
|
|
221
|
+
* Deliberately unmapped, so a reader sees intent rather than oversight:
|
|
222
|
+
* - `permissions.tools` / `permissions.disallowedTools`: 0.146.0 has no
|
|
223
|
+
* per-thread built-in-tool allow-list; the sandbox and the approval policy
|
|
224
|
+
* are the levers it does have.
|
|
225
|
+
* - `permissions.maxTurns`: no `thread/start` or `turn/start` equivalent.
|
|
226
|
+
* - `permissions.effort`: not a `ThreadStartParams` field — it is a
|
|
227
|
+
* `turn/start` param, so it lands in `buildTurnStartParams`.
|
|
228
|
+
* - every `extensions` key other than `mcpServers`, `codexConfig` and
|
|
229
|
+
* `sandbox`: those are the other harness's frontmatter concepts (`hooks`,
|
|
230
|
+
* `memory`, `skills`, `background`, `isolation`, `color`, `initialPrompt`).
|
|
231
|
+
* Unknown keys are ignored silently; `owenloop work lint` is where an unknown key
|
|
232
|
+
* gets warned about.
|
|
233
|
+
*/
|
|
234
|
+
export function buildThreadStartParams(args, onEvent) {
|
|
235
|
+
const ext = args.permissions.extensions;
|
|
236
|
+
// The escape hatch: any other config key, without re-opening the contract.
|
|
237
|
+
// `mcp_servers` is merged in AFTER it, so the owenloop mount always wins.
|
|
238
|
+
const extraConfig = isPlainMap(ext['codexConfig']) ? { ...ext['codexConfig'] } : {};
|
|
239
|
+
const bagServers = isPlainMap(ext['mcpServers']) ? ext['mcpServers'] : {};
|
|
240
|
+
const configuredServers = isPlainMap(extraConfig['mcp_servers']) ? extraConfig['mcp_servers'] : {};
|
|
241
|
+
const mcpServers = {
|
|
242
|
+
...configuredServers,
|
|
243
|
+
...bagServers,
|
|
244
|
+
// The owenloop mount wins on a key clash, mirroring how the legacy
|
|
245
|
+
// frontmatter builder overwrites an author's own `owenloop` entry. Without
|
|
246
|
+
// it the agent has no `submit` tool and the order can never complete.
|
|
247
|
+
[OWENLOOP_MCP_NAME]: owenloopMount(args.owenloopMcp),
|
|
248
|
+
};
|
|
249
|
+
const config = { ...extraConfig, mcp_servers: mcpServers };
|
|
250
|
+
const params = {
|
|
251
|
+
cwd: args.cwd,
|
|
252
|
+
config,
|
|
253
|
+
approvalPolicy: toApprovalPolicy(args.permissions.permissionMode),
|
|
254
|
+
sandbox: resolveSandbox(ext['sandbox'], onEvent),
|
|
255
|
+
};
|
|
256
|
+
if (args.permissions.permissionMode !== undefined &&
|
|
257
|
+
!NATIVE_APPROVAL_POLICIES.has(args.permissions.permissionMode)) {
|
|
258
|
+
onEvent?.({
|
|
259
|
+
kind: 'progress',
|
|
260
|
+
text: `permissionMode '${args.permissions.permissionMode}' has no approval-policy equivalent; using 'never'`,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
// Phase 1's precedence rule, verbatim: the per-start override beats the
|
|
264
|
+
// normalized step-def value. Omit the KEY entirely when neither is set —
|
|
265
|
+
// sending `model: null` would pin the thread to a null model rather than
|
|
266
|
+
// letting the server pick its default.
|
|
267
|
+
const model = args.model ?? args.permissions.model;
|
|
268
|
+
if (model !== undefined)
|
|
269
|
+
params['model'] = model;
|
|
270
|
+
return params;
|
|
271
|
+
}
|
|
272
|
+
/** Validate an `extensions.sandbox` override, dropping anything illegal loudly. */
|
|
273
|
+
function resolveSandbox(raw, onEvent) {
|
|
274
|
+
if (raw === undefined)
|
|
275
|
+
return DEFAULT_SANDBOX;
|
|
276
|
+
if (typeof raw === 'string' && SANDBOX_MODES.has(raw))
|
|
277
|
+
return raw;
|
|
278
|
+
onEvent?.({
|
|
279
|
+
kind: 'progress',
|
|
280
|
+
text: `ignoring unrecognized sandbox '${String(raw)}'; using '${DEFAULT_SANDBOX}'`,
|
|
281
|
+
});
|
|
282
|
+
return DEFAULT_SANDBOX;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Build the `turn/start` params. PURE — exported for tests.
|
|
286
|
+
*
|
|
287
|
+
* `input` is an ARRAY of `UserInput`; the text variant is `{type:'text', text}`.
|
|
288
|
+
* A bare string is the natural wrong guess and the server rejects it.
|
|
289
|
+
*/
|
|
290
|
+
export function buildTurnStartParams(threadId, text, effort) {
|
|
291
|
+
const params = {
|
|
292
|
+
threadId,
|
|
293
|
+
input: [{ type: 'text', text }],
|
|
294
|
+
};
|
|
295
|
+
// `ReasoningEffort` is `{"type":"string","minLength":1}` — an OPEN string, not
|
|
296
|
+
// a closed union, so a non-empty value passes through unnarrowed.
|
|
297
|
+
if (effort !== undefined && effort !== '')
|
|
298
|
+
params['effort'] = effort;
|
|
299
|
+
return params;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Build the `thread/resume` params. PURE — exported for tests.
|
|
303
|
+
*
|
|
304
|
+
* `base` is the resolved `thread/start` params from the session map when this
|
|
305
|
+
* process started the thread. `ThreadResumeParams` accepts `approvalPolicy`,
|
|
306
|
+
* `sandbox`, `model` and `config`, and a resumed thread that does not re-supply
|
|
307
|
+
* them reverts to the server's defaults.
|
|
308
|
+
*
|
|
309
|
+
* PHASE 4 CLOSED CONTRACT OBSERVATION 1. `deliver`'s third argument used to carry
|
|
310
|
+
* only `cwd` and `owenloopMcp`, so a resume in a different process from the start
|
|
311
|
+
* (the normal case for a re-offered step) had nothing to rebuild `approvalPolicy`
|
|
312
|
+
* / `sandbox` / `model` from and silently reverted to server defaults. It now
|
|
313
|
+
* carries the normalized `StepPermissions`, so this function derives the SAME
|
|
314
|
+
* params `buildThreadStartParams` would, and `args` WINS over `base` on every
|
|
315
|
+
* key — `base` only fills in what a `DeliverArgs` cannot express.
|
|
316
|
+
*
|
|
317
|
+
* The owenloop mount is ALWAYS re-supplied. Without it the resumed agent has no
|
|
318
|
+
* `submit` tool — a silent, total failure.
|
|
319
|
+
*/
|
|
320
|
+
export function buildThreadResumeParams(threadId, args, base, onEvent) {
|
|
321
|
+
const fromArgs = buildThreadStartParams(args, onEvent);
|
|
322
|
+
const baseConfig = base !== undefined && isPlainMap(base['config']) ? base['config'] : {};
|
|
323
|
+
const argsConfig = isPlainMap(fromArgs['config']) ? fromArgs['config'] : {};
|
|
324
|
+
const baseServers = isPlainMap(baseConfig['mcp_servers']) ? baseConfig['mcp_servers'] : {};
|
|
325
|
+
const argsServers = isPlainMap(argsConfig['mcp_servers']) ? argsConfig['mcp_servers'] : {};
|
|
326
|
+
const params = {
|
|
327
|
+
...(base ?? {}),
|
|
328
|
+
...fromArgs,
|
|
329
|
+
threadId,
|
|
330
|
+
config: {
|
|
331
|
+
...baseConfig,
|
|
332
|
+
...argsConfig,
|
|
333
|
+
// `argsServers` already carries the owenloop mount and is spread last, so
|
|
334
|
+
// the mount still wins over anything `base` held under the same name.
|
|
335
|
+
mcp_servers: { ...baseServers, ...argsServers },
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
return params;
|
|
339
|
+
}
|
|
340
|
+
// ---- notification mapping ---------------------------------------------------
|
|
341
|
+
/** Trim a progress line to something a log can hold. */
|
|
342
|
+
function cap(text) {
|
|
343
|
+
return text.length > PROGRESS_TEXT_CAP ? `${text.slice(0, PROGRESS_TEXT_CAP)}…` : text;
|
|
344
|
+
}
|
|
345
|
+
function str(v) {
|
|
346
|
+
return typeof v === 'string' && v !== '' ? v : undefined;
|
|
347
|
+
}
|
|
348
|
+
function asMap(v) {
|
|
349
|
+
return isPlainMap(v) ? v : {};
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Read a `turn/completed` frame's outcome. PURE — exported for tests.
|
|
353
|
+
* Returns `undefined` for anything that is not a `turn/completed`.
|
|
354
|
+
*/
|
|
355
|
+
export function readTurnCompleted(method, params) {
|
|
356
|
+
if (method !== 'turn/completed')
|
|
357
|
+
return undefined;
|
|
358
|
+
const turn = asMap(asMap(params)['turn']);
|
|
359
|
+
const err = asMap(turn['error']);
|
|
360
|
+
const message = str(err['message']);
|
|
361
|
+
const details = str(err['additionalDetails']);
|
|
362
|
+
return {
|
|
363
|
+
status: str(turn['status']) ?? 'completed',
|
|
364
|
+
turnId: str(turn['id']),
|
|
365
|
+
error: message === undefined
|
|
366
|
+
? undefined
|
|
367
|
+
: details === undefined
|
|
368
|
+
? message
|
|
369
|
+
: `${message} (${details})`,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Map one server→client notification to an `AgentEvent`.
|
|
374
|
+
*
|
|
375
|
+
* PURE and TOTAL — this is the function the recorded fixture replays through, so
|
|
376
|
+
* it must never throw on a shape it has not seen. `undefined` means "not worth
|
|
377
|
+
* surfacing"; nothing may depend on any particular progress line existing.
|
|
378
|
+
*
|
|
379
|
+
* `thread/started` maps to nothing on purpose: `start` emits `{kind:'started'}`
|
|
380
|
+
* itself from the `thread/start` RESPONSE, so the token is captured even if the
|
|
381
|
+
* notification ordering changes.
|
|
382
|
+
*/
|
|
383
|
+
export function mapNotification(method, params) {
|
|
384
|
+
const p = asMap(params);
|
|
385
|
+
switch (method) {
|
|
386
|
+
case 'thread/started':
|
|
387
|
+
return undefined;
|
|
388
|
+
case 'turn/started': {
|
|
389
|
+
const id = str(asMap(p['turn'])['id']) ?? '(unknown)';
|
|
390
|
+
return { kind: 'progress', text: `turn ${id} started` };
|
|
391
|
+
}
|
|
392
|
+
case 'turn/completed': {
|
|
393
|
+
const outcome = readTurnCompleted(method, params);
|
|
394
|
+
if (outcome === undefined)
|
|
395
|
+
return undefined;
|
|
396
|
+
return { kind: 'progress', text: `turn ${outcome.turnId ?? '(unknown)'} ${outcome.status}` };
|
|
397
|
+
}
|
|
398
|
+
case 'item/agentMessage/delta': {
|
|
399
|
+
const delta = str(p['delta']) ?? str(p['text']);
|
|
400
|
+
return delta === undefined ? undefined : { kind: 'progress', text: cap(delta) };
|
|
401
|
+
}
|
|
402
|
+
case 'item/started':
|
|
403
|
+
case 'item/completed': {
|
|
404
|
+
const item = asMap(p['item']);
|
|
405
|
+
const kind = str(item['type']) ?? str(item['itemType']) ?? 'item';
|
|
406
|
+
const id = str(item['id']) ?? '(unknown)';
|
|
407
|
+
return { kind: 'progress', text: `${method} ${kind} ${id}` };
|
|
408
|
+
}
|
|
409
|
+
case 'item/commandExecution/outputDelta': {
|
|
410
|
+
const chunk = str(p['chunk']) ?? str(p['delta']) ?? str(p['output']);
|
|
411
|
+
return chunk === undefined ? undefined : { kind: 'progress', text: cap(chunk) };
|
|
412
|
+
}
|
|
413
|
+
case 'item/reasoning/textDelta':
|
|
414
|
+
case 'item/reasoning/summaryTextDelta':
|
|
415
|
+
case 'item/plan/delta': {
|
|
416
|
+
const delta = str(p['delta']) ?? str(p['text']);
|
|
417
|
+
return delta === undefined ? undefined : { kind: 'progress', text: cap(delta) };
|
|
418
|
+
}
|
|
419
|
+
case 'turn/plan/updated':
|
|
420
|
+
case 'turn/diff/updated':
|
|
421
|
+
return { kind: 'progress', text: method };
|
|
422
|
+
case 'mcpServer/startupStatus/updated': {
|
|
423
|
+
const name = str(p['name']) ?? '(unnamed)';
|
|
424
|
+
const status = str(p['status']) ?? '(unknown)';
|
|
425
|
+
const err = str(p['error']);
|
|
426
|
+
return {
|
|
427
|
+
kind: 'progress',
|
|
428
|
+
text: cap(`MCP server '${name}' status ${status}${err === undefined ? '' : `: ${err}`}`),
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
case 'error': {
|
|
432
|
+
// The top-level error notification carries a `TurnError`.
|
|
433
|
+
const message = str(asMap(p['error'])['message']) ?? 'unspecified error';
|
|
434
|
+
return { kind: 'exited', exitCode: null, error: message };
|
|
435
|
+
}
|
|
436
|
+
default:
|
|
437
|
+
return undefined;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Read an `mcpServer/startupStatus/updated` frame for the owenloop mount's
|
|
442
|
+
* FAILURE only. PURE — exported for tests.
|
|
443
|
+
*
|
|
444
|
+
* Gates on an explicit `'failed'`, never on the absence of a `'ready'`: absence
|
|
445
|
+
* of a notification is not proof of failure, and gating on ever seeing `'ready'`
|
|
446
|
+
* would deadlock the moment the notification is renamed.
|
|
447
|
+
*/
|
|
448
|
+
export function readOwenloopMountFailure(method, params) {
|
|
449
|
+
if (method !== 'mcpServer/startupStatus/updated')
|
|
450
|
+
return undefined;
|
|
451
|
+
const p = asMap(params);
|
|
452
|
+
if (str(p['name']) !== OWENLOOP_MCP_NAME)
|
|
453
|
+
return undefined;
|
|
454
|
+
if (str(p['status']) !== 'failed')
|
|
455
|
+
return undefined;
|
|
456
|
+
const err = str(p['error']) ?? str(p['failureReason']) ?? 'no reason reported';
|
|
457
|
+
return `owenloop MCP server failed to start: ${err}`;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Module-level, process-wide. `stop` on a token this process did not start is a
|
|
461
|
+
* documented no-op — `HarnessSessionRef` carries no pid, so cross-process
|
|
462
|
+
* teardown is impossible under the current contract (observation 2).
|
|
463
|
+
*/
|
|
464
|
+
const SESSIONS = new Map();
|
|
465
|
+
/** The binary. `OWENLOOP_CODEX_BIN` overrides; otherwise `PATH` resolves `codex`. */
|
|
466
|
+
function resolveBin() {
|
|
467
|
+
return process.env['OWENLOOP_CODEX_BIN'] ?? 'codex';
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Wire one turn's settle semantics.
|
|
471
|
+
*
|
|
472
|
+
* TURN END, NOT PROCESS END. `turn/completed` settles the promise:
|
|
473
|
+
* - `completed` → emit `turn_ended`, resolve.
|
|
474
|
+
* - `failed` → emit `exited` carrying the error FIRST, then `turn_ended`,
|
|
475
|
+
* then resolve. The contract says everything except a resume
|
|
476
|
+
* failure surfaces as an `exited` event; resolving after it is
|
|
477
|
+
* the shape both adapters picked, and they must not diverge.
|
|
478
|
+
* - `interrupted` → emit `turn_ended`, resolve. `stop()` caused it.
|
|
479
|
+
* - `inProgress` → ignore; the turn is not over.
|
|
480
|
+
*
|
|
481
|
+
* If the child dies before any `turn/completed`, the promise REJECTS with that
|
|
482
|
+
* error and no `turn_ended` is synthesized — a dead process did not finish a turn.
|
|
483
|
+
*/
|
|
484
|
+
function createTurnGate(onEvent) {
|
|
485
|
+
let settle;
|
|
486
|
+
let turnId;
|
|
487
|
+
let settled = false;
|
|
488
|
+
const promise = new Promise((resolve, reject) => {
|
|
489
|
+
settle = (err) => {
|
|
490
|
+
if (settled)
|
|
491
|
+
return;
|
|
492
|
+
settled = true;
|
|
493
|
+
if (err !== undefined)
|
|
494
|
+
reject(err);
|
|
495
|
+
else
|
|
496
|
+
resolve();
|
|
497
|
+
};
|
|
498
|
+
});
|
|
499
|
+
// The gate can reject with NOBODY awaiting it. Both setup failure paths do
|
|
500
|
+
// exactly that: `thread/start` or `thread/resume` throws, the handler calls
|
|
501
|
+
// `dispose()`, disposal kills the child, `onExit` fires, and `gate.fail(...)`
|
|
502
|
+
// rejects a promise `runTurn` was never reached to await. Node then raises an
|
|
503
|
+
// unhandledRejection and takes the process down — turning a clean, correctly
|
|
504
|
+
// reported ResumeUnavailableError into a crash. (Caught by the live smoke,
|
|
505
|
+
// not by any unit test; the ordering only happens against a real child.)
|
|
506
|
+
//
|
|
507
|
+
// A no-op handler marks the ORIGINAL promise handled. It does not swallow the
|
|
508
|
+
// rejection for real awaiters: `promise.catch(noop)` returns a new promise,
|
|
509
|
+
// and a later `await promise` in `runTurn` still rejects exactly as before.
|
|
510
|
+
promise.catch(() => { });
|
|
511
|
+
// The executor above runs synchronously, so `settle` is assigned by here.
|
|
512
|
+
const done = settle;
|
|
513
|
+
return {
|
|
514
|
+
promise,
|
|
515
|
+
currentTurnId: () => turnId,
|
|
516
|
+
fail: (err) => done(err),
|
|
517
|
+
onNotification(method, params) {
|
|
518
|
+
if (method === 'turn/started') {
|
|
519
|
+
turnId = str(asMap(asMap(params)['turn'])['id']);
|
|
520
|
+
}
|
|
521
|
+
const mounted = readOwenloopMountFailure(method, params);
|
|
522
|
+
const event = mapNotification(method, params);
|
|
523
|
+
if (event !== undefined)
|
|
524
|
+
onEvent(event);
|
|
525
|
+
if (mounted !== undefined) {
|
|
526
|
+
// A silent dead order otherwise: with no `submit` tool the agent can
|
|
527
|
+
// never complete the order, so burning the turn's tokens is pointless.
|
|
528
|
+
onEvent({ kind: 'exited', exitCode: null, error: mounted });
|
|
529
|
+
done(new Error(mounted));
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const outcome = readTurnCompleted(method, params);
|
|
533
|
+
if (outcome === undefined)
|
|
534
|
+
return;
|
|
535
|
+
if (outcome.status === 'inProgress')
|
|
536
|
+
return;
|
|
537
|
+
if (outcome.status === 'failed') {
|
|
538
|
+
onEvent({ kind: 'exited', exitCode: null, error: outcome.error ?? 'turn failed' });
|
|
539
|
+
}
|
|
540
|
+
onEvent({ kind: 'turn_ended' });
|
|
541
|
+
done();
|
|
542
|
+
},
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Answer every server→client request. An unanswered one hangs the turn past the
|
|
547
|
+
* worker's lease, which is the single worst outcome available in this file.
|
|
548
|
+
*
|
|
549
|
+
* Exactly ONE thing is auto-approved — a tool call on owenloop's own MCP mount,
|
|
550
|
+
* see the `mcpServer/elicitation/request` case. Everything else is refused:
|
|
551
|
+
* under `approvalPolicy:'never'` a command/file approval request should not
|
|
552
|
+
* arrive at all; if one does, throwing (which the client turns into a JSON-RPC
|
|
553
|
+
* error reply) is a loud, non-hanging failure, whereas inventing an approval the
|
|
554
|
+
* policy said would never be asked for is a security decision this adapter is
|
|
555
|
+
* not authorized to make.
|
|
556
|
+
*
|
|
557
|
+
* `item/tool/requestUserInput` and every non-owenloop elicitation emit
|
|
558
|
+
* `needs_input` and then throw: the Phase 1 contract deliberately has no reply
|
|
559
|
+
* channel, so replying `{answers:{}}` would be fabricating a user's answer. The
|
|
560
|
+
* error reply surfaces to the model as a failed tool call — the least-wrong
|
|
561
|
+
* behavior available (contract observation 3).
|
|
562
|
+
*/
|
|
563
|
+
function handleServerRequest(onEvent) {
|
|
564
|
+
return async (method, params) => {
|
|
565
|
+
switch (method) {
|
|
566
|
+
case 'item/tool/requestUserInput': {
|
|
567
|
+
const questions = asMap(params)['questions'];
|
|
568
|
+
const asked = Array.isArray(questions)
|
|
569
|
+
? questions.map((q) => str(asMap(q)['question']) ?? str(asMap(q)['header']) ?? '').filter((q) => q !== '')
|
|
570
|
+
: [];
|
|
571
|
+
const question = asked.length > 0 ? asked.join(' / ') : 'the harness asked for user input';
|
|
572
|
+
onEvent({ kind: 'needs_input', question: cap(question) });
|
|
573
|
+
throw new Error('owenloop hosts this session headlessly and cannot answer user input');
|
|
574
|
+
}
|
|
575
|
+
case 'mcpServer/elicitation/request': {
|
|
576
|
+
const p = asMap(params);
|
|
577
|
+
// MEASURED: `approvalPolicy:'never'` does NOT cover MCP tool calls in
|
|
578
|
+
// 0.146.0. Every single call to an MCP tool arrives here first as an
|
|
579
|
+
// elicitation carrying `_meta.codex_approval_kind:'mcp_tool_call'`, and
|
|
580
|
+
// an error reply is recorded as `user rejected MCP tool call`. Refusing
|
|
581
|
+
// therefore does not fail safe — it makes `submit` impossible, so the
|
|
582
|
+
// agent can never green its artifact and every codex order dies owing.
|
|
583
|
+
//
|
|
584
|
+
// This grants exactly one thing: a call to a tool on owenloop's OWN
|
|
585
|
+
// mount. That mount is not third-party code — this adapter wrote it into
|
|
586
|
+
// `thread/start` itself, and `buildThreadStartParams` lets the owenloop
|
|
587
|
+
// entry win any key clash, so `serverName === 'owenloop'` cannot be some
|
|
588
|
+
// other server wearing the name. Any other server, and any elicitation
|
|
589
|
+
// that is not a tool-call approval, still gets `needs_input` + a throw.
|
|
590
|
+
if (str(p['serverName']) === OWENLOOP_MCP_NAME &&
|
|
591
|
+
str(asMap(p['_meta'])['codex_approval_kind']) === 'mcp_tool_call') {
|
|
592
|
+
return { action: 'accept', content: {} };
|
|
593
|
+
}
|
|
594
|
+
const message = str(p['message']) ?? 'an MCP server asked for user input';
|
|
595
|
+
onEvent({ kind: 'needs_input', question: cap(message) });
|
|
596
|
+
throw new Error('owenloop hosts this session headlessly and cannot answer an elicitation');
|
|
597
|
+
}
|
|
598
|
+
case 'item/commandExecution/requestApproval':
|
|
599
|
+
case 'item/fileChange/requestApproval':
|
|
600
|
+
case 'item/permissions/requestApproval':
|
|
601
|
+
case 'applyPatchApproval':
|
|
602
|
+
case 'execCommandApproval': {
|
|
603
|
+
onEvent({
|
|
604
|
+
kind: 'progress',
|
|
605
|
+
text: `refusing '${method}': owenloop runs with approvalPolicy 'never' and does not grant approvals`,
|
|
606
|
+
});
|
|
607
|
+
throw new Error(`'${method}' is not answerable by a headless host`);
|
|
608
|
+
}
|
|
609
|
+
default: {
|
|
610
|
+
onEvent({ kind: 'progress', text: `refusing unsupported server request '${method}'` });
|
|
611
|
+
throw new Error(`'${method}' is not supported by this host`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
/** Spawn one app-server, complete the handshake, and return the wired client. */
|
|
617
|
+
async function openClient(cwd, onEvent, gate) {
|
|
618
|
+
let exitReported = false;
|
|
619
|
+
const reportExit = (exitCode, error) => {
|
|
620
|
+
if (exitReported)
|
|
621
|
+
return;
|
|
622
|
+
exitReported = true;
|
|
623
|
+
onEvent({ kind: 'exited', exitCode, ...(error !== undefined ? { error } : {}) });
|
|
624
|
+
};
|
|
625
|
+
const client = startStdioRpc({
|
|
626
|
+
command: resolveBin(),
|
|
627
|
+
args: [...APP_SERVER_ARGS],
|
|
628
|
+
cwd,
|
|
629
|
+
// PHASE 6 ITEM 5 — the `OWENLOOP_*` namespace filter, and ONLY that.
|
|
630
|
+
//
|
|
631
|
+
// This is NOT the other adapter's vendor API-key strip, and it must not
|
|
632
|
+
// drift into one: `ANTHROPIC_*` and `OPENAI_*` continue to reach this
|
|
633
|
+
// app-server untouched, which is the recorded decision in
|
|
634
|
+
// `docs/agent-runner.md`. What changes is that owenloop's own variables with
|
|
635
|
+
// no consumer inside this process tree — the hub bearer override above all —
|
|
636
|
+
// stop arriving, because this server persists `thread/start` params under
|
|
637
|
+
// `~/.codex/sessions/` and an inherited secret therefore reaches disk.
|
|
638
|
+
//
|
|
639
|
+
// The value is a FULL environment (`process.env` minus the denied names),
|
|
640
|
+
// because supplying `env` to the transport replaces the child's environment
|
|
641
|
+
// rather than merging into it.
|
|
642
|
+
env: filterOwenloopEnv(process.env),
|
|
643
|
+
// Every unknown notification lands here and is ignored by `mapNotification`
|
|
644
|
+
// — unsolicited traffic arrives before any request completes, and throwing
|
|
645
|
+
// on one would kill a healthy session.
|
|
646
|
+
onNotification: (method, params) => gate.onNotification(method, params),
|
|
647
|
+
onServerRequest: handleServerRequest(onEvent),
|
|
648
|
+
onStderr: (line) => onEvent({ kind: 'progress', text: cap(line) }),
|
|
649
|
+
onExit: (code, signal) => {
|
|
650
|
+
reportExit(code, signal === null ? undefined : `killed by ${signal}`);
|
|
651
|
+
// Resolve-on-turn-end means a death BEFORE `turn/completed` is a failure,
|
|
652
|
+
// not a finished turn. If the turn already ended this is a no-op.
|
|
653
|
+
gate.fail(new Error(`app-server exited (code=${String(code)}, signal=${String(signal)})`));
|
|
654
|
+
},
|
|
655
|
+
});
|
|
656
|
+
try {
|
|
657
|
+
const init = await client.request('initialize', { clientInfo: CLIENT_INFO }, SETUP_TIMEOUT_MS);
|
|
658
|
+
client.notify('initialized', {});
|
|
659
|
+
// The only place the running binary's own version is observable, and the
|
|
660
|
+
// intended input to a `harness-versions.json` mismatch WARNING that is still
|
|
661
|
+
// NOT BUILT as of Phase 6 — see the "known gap" entry in
|
|
662
|
+
// `docs/agent-runner.md`. This line only surfaces the value; nothing reads
|
|
663
|
+
// it back. `test/harness-contract-fixtures.test.ts` pins the line's shape so
|
|
664
|
+
// a future consumer has something stable to parse.
|
|
665
|
+
onEvent({
|
|
666
|
+
kind: 'progress',
|
|
667
|
+
text: `app-server ready: userAgent=${str(init['userAgent']) ?? '(unknown)'}`,
|
|
668
|
+
});
|
|
669
|
+
return { client, reportExit };
|
|
670
|
+
}
|
|
671
|
+
catch (err) {
|
|
672
|
+
// THE HANDSHAKE IS INSIDE THE TRY FOR A REASON. It is spawn-adjacent, so it
|
|
673
|
+
// is tempting to treat it as part of "starting up" and leave the failure to
|
|
674
|
+
// the caller — but the child is ALREADY SPAWNED and, being `detached`, it is
|
|
675
|
+
// the leader of its own process group. A wedged binary, a wrong
|
|
676
|
+
// `OWENLOOP_CODEX_BIN`, or an `initialize` that times out would otherwise
|
|
677
|
+
// leave that group running with nobody holding a handle to it, and the caller
|
|
678
|
+
// would see a rejection with no `exited` event to explain it.
|
|
679
|
+
reportExit(null, describe(err));
|
|
680
|
+
await client.dispose();
|
|
681
|
+
throw err;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/** The message text for an `exited` event or a progress line. */
|
|
685
|
+
function describe(err) {
|
|
686
|
+
return err instanceof Error ? err.message : String(err);
|
|
687
|
+
}
|
|
688
|
+
/** A timer that cannot by itself hold the event loop — or a test runner — open. */
|
|
689
|
+
function sleepUnref(ms) {
|
|
690
|
+
return new Promise((resolve) => {
|
|
691
|
+
const t = setTimeout(resolve, ms);
|
|
692
|
+
t.unref();
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Tear one session's child down: interrupt the live turn if there is one, wait
|
|
697
|
+
* briefly for the interruption to land, then dispose.
|
|
698
|
+
*
|
|
699
|
+
* Shared by `stop` and by the failure path of a turn that never ended, because
|
|
700
|
+
* both need the same thing and the failure path is the easier one to get wrong:
|
|
701
|
+
* a turn whose gate rejected (an owenloop mount failure is the case that
|
|
702
|
+
* matters) is still RUNNING on the server, and leaving it alone burns tokens on
|
|
703
|
+
* an answer nobody will ever read.
|
|
704
|
+
*
|
|
705
|
+
* Never throws. Every step is best-effort: an already-finished turn, a dead
|
|
706
|
+
* child, and a timeout all mean the same thing at teardown — the child is going
|
|
707
|
+
* away — and none of them is a failure of `stop`.
|
|
708
|
+
*/
|
|
709
|
+
async function teardownSession(token, session) {
|
|
710
|
+
const turnId = session.gate?.currentTurnId() ?? session.turnId;
|
|
711
|
+
if (turnId !== undefined) {
|
|
712
|
+
try {
|
|
713
|
+
await session.client.request('turn/interrupt', { threadId: token, turnId }, INTERRUPT_TIMEOUT_MS);
|
|
714
|
+
// The interrupt was accepted; give the server its beat to emit
|
|
715
|
+
// `turn/completed{status:'interrupted'}` so a caller parked on the gate
|
|
716
|
+
// sees an interrupted turn rather than the child's death.
|
|
717
|
+
const gate = session.gate;
|
|
718
|
+
if (gate !== undefined) {
|
|
719
|
+
await Promise.race([gate.promise.then(noop, noop), sleepUnref(INTERRUPT_SETTLE_MS)]);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
catch {
|
|
723
|
+
// Best effort — see the doc comment.
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
try {
|
|
727
|
+
await session.client.dispose();
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
// Disposal of an already-exited child is exactly the case the contract
|
|
731
|
+
// calls not-an-error.
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
function noop() {
|
|
735
|
+
/* a settled gate is information, not an outcome, at teardown */
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* A turn that rejected did NOT end — drop the session and tear the child down.
|
|
739
|
+
*
|
|
740
|
+
* The case this exists for is the owenloop mount failure: the gate rejects the
|
|
741
|
+
* instant `mcpServer/startupStatus/updated` reports `failed`, but the SERVER is
|
|
742
|
+
* still happily running the turn, and an agent with no `submit` tool can only
|
|
743
|
+
* spend tokens on an order it cannot possibly complete. A child death or a
|
|
744
|
+
* `turn/start` ACK timeout land here too, and the same answer fits: nothing more
|
|
745
|
+
* will come of this turn, so nothing should still be running for it.
|
|
746
|
+
*
|
|
747
|
+
* The resume token stays valid — the rollout on disk outlives the child, so a
|
|
748
|
+
* later `deliver` can still resume the thread with a fresh app-server.
|
|
749
|
+
*/
|
|
750
|
+
async function abandonTurn(token, session) {
|
|
751
|
+
if (SESSIONS.get(token) === session)
|
|
752
|
+
SESSIONS.delete(token);
|
|
753
|
+
await teardownSession(token, session);
|
|
754
|
+
}
|
|
755
|
+
async function runTurn(client, gate, params) {
|
|
756
|
+
// The RESPONSE acknowledges the turn's creation; it is NOT turn end. Awaiting
|
|
757
|
+
// both means a server that answers late still cannot make us miss the
|
|
758
|
+
// `turn/completed` that already settled the gate.
|
|
759
|
+
await Promise.all([client.request('turn/start', params, TURN_START_TIMEOUT_MS), gate.promise]);
|
|
760
|
+
}
|
|
761
|
+
export const codexAdapter = {
|
|
762
|
+
id: HARNESS_ID,
|
|
763
|
+
resumeTier: 'native-token',
|
|
764
|
+
/**
|
|
765
|
+
* The command a human runs to re-open this thread in an interactive terminal.
|
|
766
|
+
*
|
|
767
|
+
* It goes through `resolveBin`, the SAME resolution the app-server spawn uses,
|
|
768
|
+
* so an operator who set `OWENLOOP_CODEX_BIN` is handed a command that runs on
|
|
769
|
+
* their machine rather than a bare name their shell cannot find. The token in
|
|
770
|
+
* `HarnessSessionRef` is the thread id, which is exactly what the CLI's
|
|
771
|
+
* `resume` subcommand takes.
|
|
772
|
+
*/
|
|
773
|
+
resumeCommand(ref) {
|
|
774
|
+
return { command: resolveBin(), args: ['resume', ref.token] };
|
|
775
|
+
},
|
|
776
|
+
async start(args, onEvent) {
|
|
777
|
+
const gate = createTurnGate(onEvent);
|
|
778
|
+
const startParams = buildThreadStartParams(args, onEvent);
|
|
779
|
+
// Handshake failure disposes the child inside `openClient` — see the catch
|
|
780
|
+
// there. Nothing is spawned and unowned by the time this rejects.
|
|
781
|
+
const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
|
|
782
|
+
let threadId;
|
|
783
|
+
try {
|
|
784
|
+
const res = await client.request('thread/start', startParams, SETUP_TIMEOUT_MS);
|
|
785
|
+
const id = str(asMap(res['thread'])['id']);
|
|
786
|
+
if (id === undefined)
|
|
787
|
+
throw new Error('thread/start returned no thread id');
|
|
788
|
+
threadId = id;
|
|
789
|
+
}
|
|
790
|
+
catch (err) {
|
|
791
|
+
// No token exists yet, so there is nothing to hand back and nothing to
|
|
792
|
+
// invent. Report, tear down, reject.
|
|
793
|
+
reportExit(null, describe(err));
|
|
794
|
+
await client.dispose();
|
|
795
|
+
throw err;
|
|
796
|
+
}
|
|
797
|
+
const ref = { harness: HARNESS_ID, token: threadId };
|
|
798
|
+
// The gate goes on the session BEFORE the turn is started, so a `stop` that
|
|
799
|
+
// lands mid-turn can read the live turn id off it and interrupt.
|
|
800
|
+
const session = { client, startParams, gate };
|
|
801
|
+
SESSIONS.set(threadId, session);
|
|
802
|
+
// BEFORE the turn runs and before resolving: the caller persists the token
|
|
803
|
+
// on this event, so a mid-turn crash still leaves a resumable record.
|
|
804
|
+
onEvent({ kind: 'started', ref });
|
|
805
|
+
try {
|
|
806
|
+
await runTurn(client, gate, buildTurnStartParams(threadId, args.brief, args.effort ?? args.permissions.effort));
|
|
807
|
+
}
|
|
808
|
+
catch (err) {
|
|
809
|
+
await abandonTurn(threadId, session);
|
|
810
|
+
throw err;
|
|
811
|
+
}
|
|
812
|
+
finally {
|
|
813
|
+
session.turnId = gate.currentTurnId();
|
|
814
|
+
delete session.gate;
|
|
815
|
+
}
|
|
816
|
+
return ref;
|
|
817
|
+
},
|
|
818
|
+
async deliver(ref, message, args, onEvent) {
|
|
819
|
+
// A rollout records its cwd; a vanished worktree cannot host the resumed
|
|
820
|
+
// turn, and finding that out from the server takes a spawn plus a handshake.
|
|
821
|
+
if (!existsSync(args.cwd)) {
|
|
822
|
+
throw new ResumeUnavailableError(`resume cwd no longer exists: ${args.cwd}`);
|
|
823
|
+
}
|
|
824
|
+
const gate = createTurnGate(onEvent);
|
|
825
|
+
const previous = SESSIONS.get(ref.token);
|
|
826
|
+
// PHASE 4: the map is no longer the source of truth for thread configuration.
|
|
827
|
+
// `args.permissions` is, and `buildThreadResumeParams` maps it. `startParams`
|
|
828
|
+
// survives only as a filler for keys a `DeliverArgs` cannot express, and a
|
|
829
|
+
// miss is now an ordinary cross-process resume rather than a degraded one —
|
|
830
|
+
// which is why the "minimal thread configuration" warning is gone.
|
|
831
|
+
const startParams = previous?.startParams;
|
|
832
|
+
if (previous !== undefined) {
|
|
833
|
+
// ALWAYS a fresh app-server, even when this process still holds a live one.
|
|
834
|
+
// A live client's notifications are bound to the gate it was opened with,
|
|
835
|
+
// and the client exposes no rewire; reusing it would route this turn's
|
|
836
|
+
// `turn/completed` to the PREVIOUS turn's already-settled gate and hang
|
|
837
|
+
// this one forever. Resume is cheap; a hung order is not.
|
|
838
|
+
SESSIONS.delete(ref.token);
|
|
839
|
+
await previous.client.dispose();
|
|
840
|
+
}
|
|
841
|
+
const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
|
|
842
|
+
const resumeParams = buildThreadResumeParams(ref.token, args, startParams, onEvent);
|
|
843
|
+
try {
|
|
844
|
+
await client.request('thread/resume', resumeParams, SETUP_TIMEOUT_MS);
|
|
845
|
+
}
|
|
846
|
+
catch (err) {
|
|
847
|
+
if (isResumeMiss(err)) {
|
|
848
|
+
// The ONLY failure that rejects with ResumeUnavailableError. The caller
|
|
849
|
+
// owns the cold-replay fallback; this adapter only reports. The `exited`
|
|
850
|
+
// event for the disposed child comes from `onExit`, unchanged — a
|
|
851
|
+
// forgotten thread is reported by the rejection, not by a second
|
|
852
|
+
// synthesized failure message.
|
|
853
|
+
await client.dispose();
|
|
854
|
+
throw new ResumeUnavailableError(`provider no longer knows thread ${ref.token}: ${describe(err)}`);
|
|
855
|
+
}
|
|
856
|
+
reportExit(null, describe(err));
|
|
857
|
+
await client.dispose();
|
|
858
|
+
throw err;
|
|
859
|
+
}
|
|
860
|
+
const session = {
|
|
861
|
+
client,
|
|
862
|
+
gate,
|
|
863
|
+
...(startParams !== undefined ? { startParams } : {}),
|
|
864
|
+
};
|
|
865
|
+
SESSIONS.set(ref.token, session);
|
|
866
|
+
try {
|
|
867
|
+
// NEVER re-emits `started` — the contract forbids it on a resume.
|
|
868
|
+
await runTurn(client, gate,
|
|
869
|
+
// Phase 4: effort is a `turn/start` param, so a resumed turn has to
|
|
870
|
+
// re-supply it exactly as `start` does — same precedence rule.
|
|
871
|
+
buildTurnStartParams(ref.token, message, args.effort ?? args.permissions.effort));
|
|
872
|
+
}
|
|
873
|
+
catch (err) {
|
|
874
|
+
await abandonTurn(ref.token, session);
|
|
875
|
+
throw err;
|
|
876
|
+
}
|
|
877
|
+
finally {
|
|
878
|
+
session.turnId = gate.currentTurnId();
|
|
879
|
+
delete session.gate;
|
|
880
|
+
}
|
|
881
|
+
},
|
|
882
|
+
async stop(ref) {
|
|
883
|
+
const session = SESSIONS.get(ref.token);
|
|
884
|
+
// A miss is NOT an error: the contract requires idempotence, an already-dead
|
|
885
|
+
// session is fine, and a session started by another process is simply not
|
|
886
|
+
// reachable from here.
|
|
887
|
+
if (session === undefined)
|
|
888
|
+
return;
|
|
889
|
+
SESSIONS.delete(ref.token);
|
|
890
|
+
await teardownSession(ref.token, session);
|
|
891
|
+
},
|
|
892
|
+
};
|
|
893
|
+
// Adapters self-register at IMPORT time; whoever imports this module is what
|
|
894
|
+
// puts it in the runtime registry. Phase 3's worker owns that import — this
|
|
895
|
+
// phase only makes the import sufficient.
|
|
896
|
+
register(codexAdapter);
|