orizu 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/README.md +22 -13
- package/dist/artifact-archive.js +152 -0
- package/dist/connectors-cli.js +80 -0
- package/dist/credentials.js +4 -1
- package/dist/daytona-slice-rehearsal.js +255 -0
- package/dist/daytona-slice.js +441 -0
- package/dist/egress-allowlist-cli.js +132 -0
- package/dist/egress-policy.js +159 -0
- package/dist/git-credential.js +131 -0
- package/dist/github-setup.js +226 -0
- package/dist/help.js +276 -21
- package/dist/hosted-bootstrap-rehearsal.js +235 -0
- package/dist/hosted-bootstrap.js +365 -0
- package/dist/hosted-broker-server.js +220 -0
- package/dist/hosted-git-http-server.js +136 -0
- package/dist/hosted-harness-claude.js +493 -0
- package/dist/hosted-harness-opencode.js +729 -0
- package/dist/hosted-harness.js +60 -0
- package/dist/hosted-loop.js +477 -0
- package/dist/hosted-run-event-sink.js +499 -0
- package/dist/hosted-runtime-assets.js +216 -0
- package/dist/hosted-session-cli.js +642 -0
- package/dist/index.js +945 -258
- package/dist/kill-switch-cli.js +89 -0
- package/dist/manifests-cli.js +143 -0
- package/dist/preview-runtime.js +4 -1
- package/dist/sandbox-provider.js +238 -0
- package/dist/secret-redaction.js +112 -0
- package/dist/session-timeline.js +103 -0
- package/dist/setup-prompt.js +4 -2
- package/dist/skill-installer.js +9 -1
- package/dist/smoke.js +250 -0
- package/dist/task-assignment-manifest.js +96 -0
- package/dist/vercel-sandbox-provider.js +260 -0
- package/dist/workbench-cli.js +493 -0
- package/dist/workspace-sync.js +924 -0
- package/dist/workspace.js +868 -57
- package/package.json +4 -1
- package/src/artifact-archive.ts +182 -0
- package/src/connectors-cli.ts +115 -0
- package/src/credentials.ts +6 -2
- package/src/daytona-slice-rehearsal.ts +320 -0
- package/src/daytona-slice.ts +598 -0
- package/src/egress-allowlist-cli.ts +147 -0
- package/src/egress-policy.ts +188 -0
- package/src/git-credential.ts +155 -0
- package/src/github-setup.ts +366 -0
- package/src/help.ts +277 -21
- package/src/hosted-bootstrap-rehearsal.ts +312 -0
- package/src/hosted-bootstrap.ts +571 -0
- package/src/hosted-broker-server.ts +278 -0
- package/src/hosted-git-http-server.ts +164 -0
- package/src/hosted-harness-claude.ts +621 -0
- package/src/hosted-harness-opencode.ts +823 -0
- package/src/hosted-harness.ts +124 -0
- package/src/hosted-loop.ts +680 -0
- package/src/hosted-run-event-sink.ts +632 -0
- package/src/hosted-runtime-assets.ts +272 -0
- package/src/hosted-session-cli.ts +844 -0
- package/src/index.ts +1102 -317
- package/src/kill-switch-cli.ts +113 -0
- package/src/manifests-cli.ts +168 -0
- package/src/preview-runtime.ts +14 -9
- package/src/sandbox-provider.ts +440 -0
- package/src/secret-redaction.ts +124 -0
- package/src/session-timeline.ts +152 -0
- package/src/setup-prompt.ts +4 -2
- package/src/skill-installer.ts +13 -1
- package/src/smoke.ts +342 -0
- package/src/task-assignment-manifest.ts +164 -0
- package/src/vercel-sandbox-provider.ts +388 -0
- package/src/workbench-cli.ts +701 -0
- package/src/workspace-sync.ts +1148 -0
- package/src/workspace.ts +1051 -64
- package/vendor/skills/orizu-cli/SKILL.md +8 -4
- package/vendor/skills/orizu-cli/references/cli-reference.md +12 -4
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentHarness seam (ALI-926 / P3.4, interface 1 of ADR-005's swappability
|
|
3
|
+
* contract; sketch in audit §4a).
|
|
4
|
+
*
|
|
5
|
+
* `AgentHarness` abstracts "what starts and steps the agent" so the OpenCode
|
|
6
|
+
* driver (`hosted-harness-opencode.ts`) can be swapped for a Claude-Agent-SDK
|
|
7
|
+
* loop (ALI-929) WITHOUT touching the event bridge (`hosted-run-event-sink.ts`)
|
|
8
|
+
* or the RunAPI. The interface therefore carries ZERO OpenCode types: it speaks
|
|
9
|
+
* only in normalized `HarnessEvent`s whose `kind` is the audit §4b left column.
|
|
10
|
+
*
|
|
11
|
+
* Shape ported (in DESIGN, not code) from OpenInspect's `bridge.py`:
|
|
12
|
+
* create session → send prompt → stream parts → detect idle → stop.
|
|
13
|
+
* The OpenCode-specific SSE part schema, message-id correlation, and localhost
|
|
14
|
+
* HTTP driving live entirely behind this seam.
|
|
15
|
+
*
|
|
16
|
+
* Terminal semantics: `execution_complete` and `error` are emitted as ordinary
|
|
17
|
+
* stream events with `critical: true`. The bridge (§4b) routes those to the
|
|
18
|
+
* RunAPI terminal PATCH — they are NEVER appended as raw run events. The harness
|
|
19
|
+
* does not know about run status; "Orizu records win" (the disagreement rule) is
|
|
20
|
+
* enforced by the sink, not here.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* The normalized event vocabulary — the audit §4b left column. The bridge maps
|
|
24
|
+
* each kind onto a `workbench_run_events.event_type` (or drops it). Kept as a
|
|
25
|
+
* const map (no enums, per project guidelines).
|
|
26
|
+
*
|
|
27
|
+
* `push_complete` / `push_error` are deliberately OMITTED: they belong to the
|
|
28
|
+
* finish-branch / manifest push flow deferred to P3.5. `heartbeat` and
|
|
29
|
+
* `user_message` are not modeled at all — the harness never emits liveness or
|
|
30
|
+
* prompt-echo events (§4b drops both).
|
|
31
|
+
*/
|
|
32
|
+
export const HARNESS_EVENT_KINDS = {
|
|
33
|
+
ready: 'ready',
|
|
34
|
+
token: 'token',
|
|
35
|
+
tool_call: 'tool_call',
|
|
36
|
+
tool_result: 'tool_result',
|
|
37
|
+
step_start: 'step_start',
|
|
38
|
+
step_finish: 'step_finish',
|
|
39
|
+
git_sync: 'git_sync',
|
|
40
|
+
artifact: 'artifact',
|
|
41
|
+
session_title: 'session_title',
|
|
42
|
+
// Egress-canary results (G5 / ALI-1006). NOT produced by a harness — the
|
|
43
|
+
// in-sandbox loop emits these through the SAME single-writer run-event sink
|
|
44
|
+
// right after bootstrap (the startup canary that proves the firewall is live).
|
|
45
|
+
// They are part of the §4b run-event vocabulary (G6 lists "egress attempt")
|
|
46
|
+
// and never terminal, so they append like any structural event.
|
|
47
|
+
egress_blocked: 'egress_blocked',
|
|
48
|
+
egress_allowed: 'egress_allowed',
|
|
49
|
+
error: 'error',
|
|
50
|
+
execution_complete: 'execution_complete',
|
|
51
|
+
};
|
|
52
|
+
/** The two kinds that must NEVER be appended as raw events — they drive the
|
|
53
|
+
* terminal PATCH instead (§4b mapping rule). */
|
|
54
|
+
export const HARNESS_TERMINAL_KINDS = {
|
|
55
|
+
execution_complete: 'execution_complete',
|
|
56
|
+
error: 'error',
|
|
57
|
+
};
|
|
58
|
+
export function isHarnessTerminalKind(kind) {
|
|
59
|
+
return kind in HARNESS_TERMINAL_KINDS;
|
|
60
|
+
}
|
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-sandbox hosted agent loop (ALI-928 / P3.5, per ADR-005).
|
|
3
|
+
*
|
|
4
|
+
* Runs INSIDE the sandbox (installed by the bootstrap CLI step, launched
|
|
5
|
+
* DETACHED by `orizu session start --hosted`). It composes the ALI-926 pieces:
|
|
6
|
+
*
|
|
7
|
+
* 1. resolve the loop boot context (a run-scoped JSON file written by the host
|
|
8
|
+
* orchestrator) + read the agent bearer from its 0600 file (G3);
|
|
9
|
+
* 2. install `opencode` pinned to OPENCODE_PINNED_VERSION (non-fatal-RECORDED;
|
|
10
|
+
* if it is unavailable the spawn/connect below fails and the run finishes
|
|
11
|
+
* 'failed' cleanly — the run never dangles);
|
|
12
|
+
* 3. build a RESUME-AWARE RunEventSink (continues the server's sequence after
|
|
13
|
+
* the run-start + bootstrap events — so a reconnect loses nothing);
|
|
14
|
+
* 4. provision the `AgentHarness` SELECTED by `context.harness` (default
|
|
15
|
+
* 'opencode': install+spawn `opencode serve` then connect the OpenCode
|
|
16
|
+
* driver; 'claude-agent-sdk': construct the in-process Claude-Agent-SDK
|
|
17
|
+
* driver — no server to install or spawn), then drive the SINGLE task prompt
|
|
18
|
+
* (v0: no queue) through `drainHarnessToSink`;
|
|
19
|
+
* 5. the terminal event decides the run's final status via the sink's PATCH.
|
|
20
|
+
*
|
|
21
|
+
* SWAPPABILITY (ALI-929 / P3.6): harness SELECTION is the ONLY thing that differs
|
|
22
|
+
* between the two drivers — `start()` → `runPrompt()` → `drainHarnessToSink()` →
|
|
23
|
+
* `shutdown()` is byte-identical for both, and the sink, event vocabulary, and
|
|
24
|
+
* terminal-PATCH flow are unchanged. That is the proof: a second harness drops in
|
|
25
|
+
* behind the seam with no change to any consumer beyond the selector.
|
|
26
|
+
*
|
|
27
|
+
* The redaction list carries the agent bearer (added automatically by the sink)
|
|
28
|
+
* plus any model key present in the process env (defense in depth for the G3
|
|
29
|
+
* per-exec fallback — with firewall brokering the real key never reaches here).
|
|
30
|
+
*
|
|
31
|
+
* TESTABILITY: `runHostedLoop` takes injected `fetchImpl`, `spawnOpenCode`,
|
|
32
|
+
* `installOpenCode`, and `createHarness`, so the whole loop runs in-process
|
|
33
|
+
* against a fake broker + fake OpenCode server with no real binary.
|
|
34
|
+
*/
|
|
35
|
+
import { spawnSync, spawn as nodeSpawn } from 'child_process';
|
|
36
|
+
import { existsSync, readFileSync } from 'fs';
|
|
37
|
+
import { join } from 'path';
|
|
38
|
+
import { PREBAKED_MARKER_PATH, SETUP_HOOK_RELATIVE_PATH, parsePrebakedMarker, } from './hosted-runtime-assets.js';
|
|
39
|
+
import { OPENCODE_PINNED_VERSION, createOpenCodeHarness, spawnOpenCode, } from './hosted-harness-opencode.js';
|
|
40
|
+
import { createClaudeAgentHarness } from './hosted-harness-claude.js';
|
|
41
|
+
import { drainHarnessToSink, resumeRunEventSink, } from './hosted-run-event-sink.js';
|
|
42
|
+
/** Default egress-canary probe host (a known non-allowlisted destination). */
|
|
43
|
+
export const DEFAULT_EGRESS_CANARY_HOST = 'example.com';
|
|
44
|
+
/** Bound (ms) on the canary probe — a live firewall resets/times out fast; a
|
|
45
|
+
* reachable host answers well within this. */
|
|
46
|
+
const EGRESS_CANARY_TIMEOUT_MS = 5000;
|
|
47
|
+
/**
|
|
48
|
+
* Default probe: attempt a bounded HTTPS GET to `host`. A live default-deny
|
|
49
|
+
* firewall makes this THROW for a DENIED host (connection reset / timeout / DNS
|
|
50
|
+
* failure) → `reachable: false`. Any response at all — even an error status —
|
|
51
|
+
* proves the host was reachable → `reachable: true`. Used for BOTH the allowed
|
|
52
|
+
* (positive-control) and denied probes.
|
|
53
|
+
*/
|
|
54
|
+
async function defaultProbeEgress(host) {
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const timer = setTimeout(() => controller.abort(), EGRESS_CANARY_TIMEOUT_MS);
|
|
57
|
+
try {
|
|
58
|
+
const response = await fetch(`https://${host}/`, {
|
|
59
|
+
method: 'GET',
|
|
60
|
+
redirect: 'manual',
|
|
61
|
+
signal: controller.signal,
|
|
62
|
+
});
|
|
63
|
+
return { reachable: true, detail: `reachable (HTTP ${response.status})` };
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
return { reachable: false, detail: `blocked (${error instanceof Error ? error.name : 'error'})` };
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Run the startup egress canary as a POSITIVE CONTROL and emit the proof event
|
|
74
|
+
* through the (single-writer) sink. Probes BOTH a known-allowed host and the
|
|
75
|
+
* known-denied host, then decides:
|
|
76
|
+
*
|
|
77
|
+
* - allowed REACHABLE and denied BLOCKED → the firewall is live AND the network
|
|
78
|
+
* works → emit `egress_blocked` and PROCEED (the ONLY healthy outcome);
|
|
79
|
+
* - denied REACHABLE → egress is NOT enforced → emit `egress_allowed`, FAIL
|
|
80
|
+
* CLOSED;
|
|
81
|
+
* - allowed ALSO UNREACHABLE (denied blocked but the positive control failed) →
|
|
82
|
+
* we cannot tell policy-blocking from a total network outage → emit
|
|
83
|
+
* `egress_allowed`, FAIL CLOSED.
|
|
84
|
+
*
|
|
85
|
+
* The `egress_blocked` kind therefore means EXACTLY "proceeded, positive control
|
|
86
|
+
* passed"; `egress_allowed` means "failed closed" (the payload `result` field
|
|
87
|
+
* distinguishes an unexpectedly-reachable denied host from an unreachable
|
|
88
|
+
* positive control). Old behavior — treating ANY denied-host throw (incl. a
|
|
89
|
+
* timeout under a total outage) as "blocked → proceed" — failed OPEN; this now
|
|
90
|
+
* fails closed on that ambiguity.
|
|
91
|
+
*/
|
|
92
|
+
export async function runEgressCanary(targets, sink, probe, now = () => Date.now()) {
|
|
93
|
+
const [allowed, denied] = await Promise.all([probe(targets.allowedHost), probe(targets.deniedHost)]);
|
|
94
|
+
const checkedAt = new Date(now()).toISOString();
|
|
95
|
+
const positiveControl = {
|
|
96
|
+
host: targets.allowedHost,
|
|
97
|
+
reachable: allowed.reachable,
|
|
98
|
+
detail: allowed.detail,
|
|
99
|
+
};
|
|
100
|
+
// FAIL CLOSED: a denied host answered — the policy is not enforcing egress.
|
|
101
|
+
if (denied.reachable) {
|
|
102
|
+
await sink.append({
|
|
103
|
+
kind: 'egress_allowed',
|
|
104
|
+
critical: true,
|
|
105
|
+
payload: {
|
|
106
|
+
host: targets.deniedHost,
|
|
107
|
+
result: 'unexpectedly_reachable',
|
|
108
|
+
detail: denied.detail,
|
|
109
|
+
positiveControl,
|
|
110
|
+
checkedAt,
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
return {
|
|
114
|
+
proceed: false,
|
|
115
|
+
reason: `denied host ${targets.deniedHost} was reachable (${denied.detail}) — egress is not enforced`,
|
|
116
|
+
allowed,
|
|
117
|
+
denied,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
// FAIL CLOSED: the denied host was blocked, but the positive control ALSO did
|
|
121
|
+
// not answer — the environment/network is broken and we cannot distinguish a
|
|
122
|
+
// policy block from a total outage. This is the case the old code got wrong.
|
|
123
|
+
if (!allowed.reachable) {
|
|
124
|
+
await sink.append({
|
|
125
|
+
kind: 'egress_allowed',
|
|
126
|
+
critical: true,
|
|
127
|
+
payload: {
|
|
128
|
+
host: targets.deniedHost,
|
|
129
|
+
result: 'positive_control_unreachable',
|
|
130
|
+
detail: denied.detail,
|
|
131
|
+
positiveControl,
|
|
132
|
+
checkedAt,
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
proceed: false,
|
|
137
|
+
reason: `positive control ${targets.allowedHost} was unreachable (${allowed.detail}) — cannot distinguish egress enforcement from a network outage`,
|
|
138
|
+
allowed,
|
|
139
|
+
denied,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
// HEALTHY: allowed reachable AND denied blocked → the firewall is live.
|
|
143
|
+
await sink.append({
|
|
144
|
+
kind: 'egress_blocked',
|
|
145
|
+
critical: true,
|
|
146
|
+
payload: {
|
|
147
|
+
host: targets.deniedHost,
|
|
148
|
+
result: 'blocked',
|
|
149
|
+
detail: denied.detail,
|
|
150
|
+
positiveControl,
|
|
151
|
+
checkedAt,
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
return { proceed: true, reason: null, allowed, denied };
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Derive the known-ALLOWED positive-control host from the run's Orizu API base —
|
|
158
|
+
* always allowlisted (it is the agent's control-plane path) and ours, so it is
|
|
159
|
+
* the safest "must be reachable" signal. Falls back to a lenient host parse if
|
|
160
|
+
* the base is not a well-formed URL.
|
|
161
|
+
*/
|
|
162
|
+
export function egressCanaryAllowedHost(apiBaseUrl) {
|
|
163
|
+
try {
|
|
164
|
+
return new URL(apiBaseUrl).hostname;
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return apiBaseUrl.replace(/^[a-z]+:\/\//i, '').split('/')[0].split(':')[0];
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Default deferred-setup-hook runner (in-sandbox): run `bash .orizu/setup.sh` in
|
|
172
|
+
* the workspace if present. Non-fatal — a missing hook or a non-zero exit is
|
|
173
|
+
* recorded and the loop proceeds, matching the bootstrap's inline behavior.
|
|
174
|
+
*/
|
|
175
|
+
function defaultRunSetupHook({ workspaceDir }) {
|
|
176
|
+
const hookPath = join(workspaceDir, SETUP_HOOK_RELATIVE_PATH);
|
|
177
|
+
if (!existsSync(hookPath))
|
|
178
|
+
return { ran: false, ok: true, detail: 'no .orizu/setup.sh' };
|
|
179
|
+
const res = spawnSync('bash', [SETUP_HOOK_RELATIVE_PATH], { cwd: workspaceDir, encoding: 'utf8' });
|
|
180
|
+
const ok = (res.status ?? 1) === 0;
|
|
181
|
+
return { ran: true, ok, detail: ok ? 'setup.sh ok' : `setup.sh exit ${res.status ?? 'unknown'}` };
|
|
182
|
+
}
|
|
183
|
+
/** Model-key env vars whose value must be scrubbed from every run event. */
|
|
184
|
+
const MODEL_KEY_ENV_VARS = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'];
|
|
185
|
+
function redactionListFromEnv() {
|
|
186
|
+
const secrets = [];
|
|
187
|
+
for (const key of MODEL_KEY_ENV_VARS) {
|
|
188
|
+
const value = process.env[key];
|
|
189
|
+
if (value)
|
|
190
|
+
secrets.push(value);
|
|
191
|
+
}
|
|
192
|
+
return secrets;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Decide whether the loop is running the PRE-BAKED runtime image (ALI-1017).
|
|
196
|
+
* Prefers the explicit boot-context flag (the host KNOWS the image it passed);
|
|
197
|
+
* falls back to a belt read of the `/opt/orizu/prebaked.json` marker (validated
|
|
198
|
+
* via `parsePrebakedMarker`, so a stray file cannot trigger a skip). Either → true.
|
|
199
|
+
*/
|
|
200
|
+
function detectLoopPrebaked(flag) {
|
|
201
|
+
if (flag)
|
|
202
|
+
return true;
|
|
203
|
+
try {
|
|
204
|
+
return parsePrebakedMarker(readFileSync(PREBAKED_MARKER_PATH, 'utf8')) !== null;
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** Best-effort global install of the pinned opencode. Non-fatal: a failure is
|
|
211
|
+
* recorded and the run finishes cleanly when the subsequent connect fails. */
|
|
212
|
+
function installOpenCodePinned(version) {
|
|
213
|
+
const command = `bun add -g opencode-ai@${version} >/dev/null 2>&1 || ` +
|
|
214
|
+
`npm install -g opencode-ai@${version} >/dev/null 2>&1`;
|
|
215
|
+
const res = spawnSync('bash', ['-c', command], { encoding: 'utf8' });
|
|
216
|
+
const ok = (res.status ?? 1) === 0;
|
|
217
|
+
return { ok, detail: ok ? `installed opencode-ai@${version}` : `install exit ${res.status ?? 'unknown'}` };
|
|
218
|
+
}
|
|
219
|
+
/** Node child_process spawner for `opencode serve` (the sandbox runtime is
|
|
220
|
+
* node24 — Bun.spawn is not guaranteed present, so spawnOpenCode is given this
|
|
221
|
+
* runtime-agnostic spawner). */
|
|
222
|
+
function nodeChildSpawner(cmd, opts) {
|
|
223
|
+
const child = nodeSpawn(cmd[0], cmd.slice(1), {
|
|
224
|
+
cwd: opts.cwd,
|
|
225
|
+
env: { ...process.env, ...opts.env },
|
|
226
|
+
stdio: 'ignore',
|
|
227
|
+
});
|
|
228
|
+
return { kill: () => child.kill() };
|
|
229
|
+
}
|
|
230
|
+
export async function runHostedLoop(opts) {
|
|
231
|
+
const { context, taskPrompt } = opts;
|
|
232
|
+
const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
|
|
233
|
+
const signal = opts.signal ?? new AbortController().signal;
|
|
234
|
+
const pinnedVersion = context.opencodePinnedVersion ?? OPENCODE_PINNED_VERSION;
|
|
235
|
+
// Resolve the bearer per request. Precedence: an explicit provider, then a
|
|
236
|
+
// fixed string, else read the rotated 0600 bearer file every time (production
|
|
237
|
+
// + rotation path — a host-side rotation overwrites this file and the sink's
|
|
238
|
+
// next resolve picks it up).
|
|
239
|
+
const fixedBearer = opts.bearer;
|
|
240
|
+
const bearerProvider = opts.bearerProvider ??
|
|
241
|
+
(fixedBearer !== undefined
|
|
242
|
+
? () => fixedBearer
|
|
243
|
+
: () => readFileSync(context.bearerFile, 'utf8').trim());
|
|
244
|
+
// Build the resume-aware sink FIRST: even if the opencode install/spawn fails,
|
|
245
|
+
// we can record a terminal transition so the run is never left non-terminal.
|
|
246
|
+
const sink = await resumeRunEventSink({
|
|
247
|
+
apiBaseUrl: context.apiBaseUrl,
|
|
248
|
+
runId: context.runId,
|
|
249
|
+
bearer: bearerProvider,
|
|
250
|
+
fetchImpl,
|
|
251
|
+
now: opts.now,
|
|
252
|
+
redactSecretsList: [...(opts.redactSecretsList ?? []), ...redactionListFromEnv()],
|
|
253
|
+
});
|
|
254
|
+
// G5 startup canary (fail-closed, POSITIVE CONTROL): when the host applied an
|
|
255
|
+
// enforced egress policy it sets `egressCanaryHost`; probe BOTH the denied host
|
|
256
|
+
// AND a known-allowed host (the Orizu API base) BEFORE any agent work. Proceed
|
|
257
|
+
// ONLY IF the allowed host is reachable and the denied host is blocked; any
|
|
258
|
+
// other outcome (denied reachable → firewall not enforcing; allowed ALSO
|
|
259
|
+
// unreachable → network broken / indistinguishable from a block) emits
|
|
260
|
+
// `egress_allowed` and finishes the run FAILED rather than touch real customer
|
|
261
|
+
// data. A canary whose own event append fails is likewise fail-closed.
|
|
262
|
+
if (context.egressCanaryHost) {
|
|
263
|
+
const probe = opts.probeEgress ?? defaultProbeEgress;
|
|
264
|
+
const targets = {
|
|
265
|
+
allowedHost: egressCanaryAllowedHost(context.apiBaseUrl),
|
|
266
|
+
deniedHost: context.egressCanaryHost,
|
|
267
|
+
};
|
|
268
|
+
let canary;
|
|
269
|
+
try {
|
|
270
|
+
canary = await runEgressCanary(targets, sink, probe, opts.now);
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
// The canary's own event append failed — treat as fail-closed: we cannot
|
|
274
|
+
// prove the firewall is live, so do not proceed.
|
|
275
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
276
|
+
if (!sink.sealed) {
|
|
277
|
+
try {
|
|
278
|
+
await sink.finish('failed', { summary: { error: `egress canary error: ${message}` } });
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
// best-effort terminal
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { status: 'failed', agentSessionId: null, installOk: false, error: `egress canary error: ${message}` };
|
|
285
|
+
}
|
|
286
|
+
if (!canary.proceed) {
|
|
287
|
+
const error = `egress canary FAILED: ${canary.reason} — refusing to proceed`;
|
|
288
|
+
if (!sink.sealed) {
|
|
289
|
+
try {
|
|
290
|
+
await sink.finish('failed', {
|
|
291
|
+
summary: {
|
|
292
|
+
error,
|
|
293
|
+
egressCanary: {
|
|
294
|
+
deniedHost: targets.deniedHost,
|
|
295
|
+
deniedReachable: canary.denied.reachable,
|
|
296
|
+
deniedDetail: canary.denied.detail,
|
|
297
|
+
allowedHost: targets.allowedHost,
|
|
298
|
+
allowedReachable: canary.allowed.reachable,
|
|
299
|
+
allowedDetail: canary.allowed.detail,
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
// best-effort terminal
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return { status: 'failed', agentSessionId: null, installOk: false, error };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
// P3-a: run the DEFERRED customer setup hook now — AFTER the canary proved the
|
|
312
|
+
// firewall is live, BEFORE any harness/network work. bootstrap deferred it (for
|
|
313
|
+
// enforced-egress providers) precisely so its network access could not precede
|
|
314
|
+
// the canary. Non-fatal, single-writer (this loop sink owns the run now).
|
|
315
|
+
if (context.runSetupHook) {
|
|
316
|
+
try {
|
|
317
|
+
const runHook = opts.runSetupHook ?? defaultRunSetupHook;
|
|
318
|
+
const outcome = await runHook({ workspaceDir: context.workspaceDir });
|
|
319
|
+
await sink.append({
|
|
320
|
+
kind: 'artifact',
|
|
321
|
+
payload: {
|
|
322
|
+
step: outcome.ran ? 'setup_hook_completed' : 'setup_hook_skipped',
|
|
323
|
+
ok: outcome.ok,
|
|
324
|
+
detail: outcome.detail,
|
|
325
|
+
deferred: true,
|
|
326
|
+
},
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
// The hook run/record is best-effort — never block the run on it.
|
|
331
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
332
|
+
if (!sink.sealed) {
|
|
333
|
+
try {
|
|
334
|
+
await sink.append({
|
|
335
|
+
kind: 'artifact',
|
|
336
|
+
payload: { step: 'setup_hook_error', ok: false, detail: message, deferred: true },
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
catch {
|
|
340
|
+
// best-effort
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
let spawned = null;
|
|
346
|
+
let agentSessionId = null;
|
|
347
|
+
let installOk = false;
|
|
348
|
+
const harnessKind = context.harness ?? 'opencode';
|
|
349
|
+
try {
|
|
350
|
+
// --- Harness PROVISIONING: the ONLY thing that differs between the two
|
|
351
|
+
// drivers (ALI-929). Everything after `harness` is constructed is identical.
|
|
352
|
+
let harness;
|
|
353
|
+
if (harnessKind === 'claude-agent-sdk') {
|
|
354
|
+
// In-process agent loop: no server to install or spawn. Record an
|
|
355
|
+
// analogous setup artifact so the event stream shape is unchanged.
|
|
356
|
+
installOk = true;
|
|
357
|
+
await sink.append({
|
|
358
|
+
kind: 'artifact',
|
|
359
|
+
payload: { step: 'harness_select', harness: harnessKind, inProcess: true },
|
|
360
|
+
});
|
|
361
|
+
// G3 parity with the OpenCode path: hand the in-process SDK client the SAME
|
|
362
|
+
// non-secret dummy key (firewall brokers the real key on egress).
|
|
363
|
+
harness = (opts.createClaudeHarness ??
|
|
364
|
+
(() => createClaudeAgentHarness({ anthropicDummyKey: context.anthropicDummyKey })))();
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
// PRE-BAKED (ALI-1017): the pinned `opencode` is already on PATH, so SKIP the
|
|
368
|
+
// install (npm is blocked under G5 default-deny egress) and record
|
|
369
|
+
// `opencode_prebaked`. FROM-SCRATCH (local-sim / fallback): install as before.
|
|
370
|
+
const prebaked = detectLoopPrebaked(context.prebaked);
|
|
371
|
+
if (prebaked) {
|
|
372
|
+
installOk = true;
|
|
373
|
+
await sink.append({
|
|
374
|
+
kind: 'artifact',
|
|
375
|
+
payload: { step: 'opencode_prebaked', ok: true, detail: `opencode-ai@${pinnedVersion} pre-baked in the runtime image` },
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
else {
|
|
379
|
+
const install = opts.installOpenCode
|
|
380
|
+
? await opts.installOpenCode()
|
|
381
|
+
: installOpenCodePinned(pinnedVersion);
|
|
382
|
+
installOk = install.ok;
|
|
383
|
+
await sink.append({
|
|
384
|
+
kind: 'artifact',
|
|
385
|
+
payload: { step: 'opencode_install', ok: install.ok, detail: install.detail },
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
const spawnImpl = opts.spawnOpenCode ?? spawnOpenCode;
|
|
389
|
+
spawned = spawnImpl({
|
|
390
|
+
model: context.model,
|
|
391
|
+
cwd: context.workspaceDir,
|
|
392
|
+
port: context.opencodePort,
|
|
393
|
+
env: context.anthropicDummyKey ? { ANTHROPIC_API_KEY: context.anthropicDummyKey } : undefined,
|
|
394
|
+
spawn: nodeChildSpawner,
|
|
395
|
+
});
|
|
396
|
+
harness = (opts.createHarness ?? ((baseUrl) => createOpenCodeHarness({ baseUrl })))(spawned.baseUrl);
|
|
397
|
+
}
|
|
398
|
+
const started = await harness.start({
|
|
399
|
+
workspaceDir: context.workspaceDir,
|
|
400
|
+
model: context.model,
|
|
401
|
+
reasoningEffort: context.reasoningEffort,
|
|
402
|
+
resumeAgentSessionId: context.resumeAgentSessionId,
|
|
403
|
+
});
|
|
404
|
+
agentSessionId = started.agentSessionId;
|
|
405
|
+
const prompt = {
|
|
406
|
+
runId: context.runId,
|
|
407
|
+
messageId: context.messageId,
|
|
408
|
+
content: taskPrompt,
|
|
409
|
+
author: context.author,
|
|
410
|
+
};
|
|
411
|
+
const status = await drainHarnessToSink(harness.runPrompt(prompt, signal), sink, {
|
|
412
|
+
summary: { agentSessionId },
|
|
413
|
+
});
|
|
414
|
+
await harness.shutdown();
|
|
415
|
+
return { status, agentSessionId, installOk, error: null };
|
|
416
|
+
}
|
|
417
|
+
catch (error) {
|
|
418
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
419
|
+
// Fail closed: never leave the run non-terminal. finish() is idempotent and
|
|
420
|
+
// no-ops when the drain already sealed the sink.
|
|
421
|
+
if (!sink.sealed) {
|
|
422
|
+
try {
|
|
423
|
+
await sink.finish('failed', { summary: { error: message } });
|
|
424
|
+
}
|
|
425
|
+
catch {
|
|
426
|
+
// best-effort — the terminal write itself may be impossible (bearer gone)
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return { status: 'failed', agentSessionId, installOk, error: message };
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
if (spawned) {
|
|
433
|
+
try {
|
|
434
|
+
spawned.stop();
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
// ignore teardown failure
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
function argValue(args, flag) {
|
|
443
|
+
const index = args.indexOf(flag);
|
|
444
|
+
if (index === -1 || index + 1 >= args.length)
|
|
445
|
+
return null;
|
|
446
|
+
const value = args[index + 1];
|
|
447
|
+
return value.startsWith('--') ? null : value;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Read the loop context + bearer + task from disk and run the loop. Invoked
|
|
451
|
+
* in-sandbox as a hidden command; the run's terminal status is recorded
|
|
452
|
+
* server-side regardless of this process's exit code.
|
|
453
|
+
*/
|
|
454
|
+
export async function hostedLoopCommand(args, io) {
|
|
455
|
+
const contextPath = argValue(args, '--context');
|
|
456
|
+
if (!contextPath) {
|
|
457
|
+
io.printErr?.('Usage: orizu internal hosted-loop --context <path>');
|
|
458
|
+
return 1;
|
|
459
|
+
}
|
|
460
|
+
let context;
|
|
461
|
+
try {
|
|
462
|
+
context = JSON.parse(readFileSync(contextPath, 'utf8'));
|
|
463
|
+
}
|
|
464
|
+
catch (error) {
|
|
465
|
+
io.printErr?.(`unreadable loop context: ${error instanceof Error ? error.message : String(error)}`);
|
|
466
|
+
return 1;
|
|
467
|
+
}
|
|
468
|
+
// Read the bearer per request (via the provider) so a host-side rotation that
|
|
469
|
+
// overwrites the 0600 file is picked up without restarting the loop.
|
|
470
|
+
const bearerProvider = () => readFileSync(context.bearerFile, 'utf8').trim();
|
|
471
|
+
const taskPrompt = readFileSync(context.taskFile, 'utf8');
|
|
472
|
+
const result = await runHostedLoop({ context, bearerProvider, taskPrompt });
|
|
473
|
+
io.print(io.json
|
|
474
|
+
? JSON.stringify({ status: result.status, agentSessionId: result.agentSessionId, error: result.error })
|
|
475
|
+
: `hosted-loop finished: ${result.status}${result.error ? ` (${result.error})` : ''}`);
|
|
476
|
+
return result.error ? 1 : 0;
|
|
477
|
+
}
|