An open-source, faster Devin alternative
TypeScript
computer: rebind runners found after a model proxy + host restart; fail turns that end on an API error (#1083)
opencomputer-app[bot]58190c45608d
diff --git a/computer/src/host/api-host.test.ts b/computer/src/host/api-host.test.tsindex 583701f9..f0446550 100644--- a/computer/src/host/api-host.test.ts+++ b/computer/src/host/api-host.test.ts@@ -197,6 +197,32 @@ describe('apiHost', () => {await t.a.stop();});+ it("binds the session's model before a call reaches its live runner: an opc turn after a host and model proxy restart (model-access.ts `called`)", async () => {+ let bound = () => {};+ const routed: string[] = [];+ const t = setup({ routed: (id) => (routed.push(id), new Promise<void>((r) => (bound = r))) });+ t.a.onGateway(welcome(4, { wire: { key: 'k' } }));+ await t.a.mint(spec, 'beef');+ t.a.up('beef'); // found running after the restart: no delivery, no start+ let where: unknown = 'pending';+ void Promise.resolve(t.a.hooks.where(S)).then((w) => (where = w));+ await tick(5);+ expect(routed).toEqual(['beef']);+ expect(where).toBe('pending'); // the client is not handed the runner until its bind is answered+ bound();+ await tick(5);+ expect(where).toMatchObject({ writer: 'runner' });+ t.a.onGateway(api('a1', 'turns.send', { session: spec }));+ await tick(5);+ expect(t.runner.calls).toEqual([]); // a gateway `api` call waits for it too+ bound();+ await tick(5);+ expect(routed).toEqual(['beef', 'beef']);+ expect(t.runner.calls).toEqual(['turns.send']);+ expect(results(t.sent)).toHaveLength(1);+ await t.a.stop();+ });+it('journals the relay\'s terminal and upload events through the session\'s writer, with their actor', async () => {const t = setup();t.a.onGateway(welcome(4));diff --git a/computer/src/host/api-host.ts b/computer/src/host/api-host.tsindex 6f58f9ab..5124b134 100644--- a/computer/src/host/api-host.ts+++ b/computer/src/host/api-host.ts@@ -84,6 +84,11 @@ export interface ApiHostDeps {retire?(runnerId: string): Promise<unknown>;/** Start the session's runner (or find it running), then deliver `msg`; resolves with its status. */start(spec: SessionSpec, o: StartOptions): Promise<SessionStatus | undefined>;+ /**+ * A call is about to reach runner `runnerId` without a delivery (the session API, opc): bind it as `deliver` would, so a runner+ * found after a restart of the host and the model proxy gets its credential again (model-access.ts `called`); settles once bound.+ */+ routed?(runnerId: string): Promise<unknown>;/** The fork of the session's runner, if it reported one. */forkPath?(key: string): string | undefined;/** Present where sessions run in containers (work 103): the session's sandbox, undefined when it has none yet. Its terminal and files are reached only there. */@@ -184,6 +189,7 @@ export function apiHost(d: ApiHostDeps) {await adopting.get(sessionId);await pending.get(sessionId)?.done;const r = live.get(sessionId);+ if (r && open) await d.routed?.(r.runnerId); // a call (not the mirror following it): its runner has its model firstif (r) return r.port;const h = hostWriters.get(sessionId) ?? (open ? openHost(sessionId) : undefined);return h && localPort(await h.w);@@ -256,6 +262,7 @@ export function apiHost(d: ApiHostDeps) {await pending.get(sessionId)?.done;const r = live.get(sessionId);const epochStartSeq = () => readJournalFile(journalPath(d.dataDir, sessionId), Number.MAX_SAFE_INTEGER, 0).startSeq || undefined;+ if (r) await d.routed?.(r.runnerId);if (r) return { socket: r.api.socket, token: r.api.token, writer: 'runner', epoch: r.api.epoch, epochStartSeq: epochStartSeq() };const h = hostWriters.get(sessionId) ?? openHost(sessionId);if (!h) return undefined;diff --git a/computer/src/host/main.ts b/computer/src/host/main.tsindex 40b3a74c..b879d7da 100644--- a/computer/src/host/main.ts+++ b/computer/src/host/main.ts@@ -289,6 +289,7 @@ const api = apiHost({ dataDir: HOST_DATA, stateDir: path.join(HOST_DATA, 'host-asend: (m) => link.open && (link.send(m), true), buffered: () => link.buffered, start: startSession, retire: retireRunner,dial: LAUNCH === 'podman' ? checkedDial({ uid: runnerUser(env)?.uid }) : undefined, // a container's sockets are its user's (checked-socket.ts)forkPath: (key) => runners.get(key)?.report?.forkPath,+ routed: async (id) => { const r = [...runners.values()].find((x) => x.id === id); if (r) await subs.called(r.key); }, // model-access.ts `called`wire: wireFor({ launch: LAUNCH, user: runnerUser(env), systemdRun: env.SP_SYSTEMD_RUN || undefined, path: env.SP_RUNNER_PATH,stateDir: path.join(HOST_DATA, 'state', 'uploads'), files: sandbox?.files, terminal: sandbox?.terminal }), sandbox: sandbox?.place, telemetry: tm });setInterval(() => {diff --git a/computer/src/host/model-access.test.ts b/computer/src/host/model-access.test.tsindex c367bb7b..06d5c600 100644--- a/computer/src/host/model-access.test.ts+++ b/computer/src/host/model-access.test.ts@@ -44,11 +44,12 @@ let bin: string;let proxy: ChildProcess | undefined;let cleanup: (() => unknown)[] = [];-async function startProxy() {+/** `bindingsFile`: the table a restart restores, every entry known and not credentialed (computer/modelproxy/persist.go). */+async function startProxy(bindingsFile = '') {const control = path.join(dir, 'control.sock');rmSync(control, { force: true });proxy = spawn(bin, ['-profiles', path.join(dir, 'profiles'), '-api-socket', path.join(dir, 'api.sock'), '-control-socket', control,- '-bindings-file', '', '-hold-timeout', '1s', '-drain-timeout', '1s'], { stdio: 'ignore' });+ '-bindings-file', bindingsFile, '-hold-timeout', '1s', '-drain-timeout', '1s'], { stdio: 'ignore' });await vi.waitFor(() => expect(existsSync(control)).toBe(true), { timeout: 5000 });}async function stopProxy() {@@ -268,6 +269,43 @@ describe.skipIf(!GO)('host model access against the real model proxy', () => {expect(await held('r5')).toMatchObject({ profile: 'claude-b' });});+ it('a proxy and host restart (a release switch): a found runner on `models` is bound again at once, one on its own route at its first API call', async () => {+ const file = path.join(dir, 'bindings.json');+ await stopProxy();+ await startProxy(file);+ const t = setup();+ await t.up();+ t.a.onGateway(welcome({ claude: route('claude-a') }));+ await t.register('s8', 'r8');+ t.a.onGateway({ t: 'model', sessionKey: 'api', model: route('claude-a', 'sk-own', 'own-key') });+ await t.register('api', 'r9');+ await vi.waitFor(() => expect(readFileSync(file, 'utf8')).toContain('own-key'));+ t.a.stop();+ await stopProxy();+ await startProxy(file); // its bindings come back from disk, without their variables++ const u = setup();+ const runners = [['s8', fakeRunner('r8')], ['api', fakeRunner('r9')]] as const;+ for (const [k, r] of runners) u.runners.set(k, r), u.a.registered(k, r.id, 'claude', true); // found before the proxy and the gateway say hello+ await u.up();+ expect(u.out).toEqual([]);+ u.a.onGateway(welcome({ claude: route('claude-a') }));+ await u.a.ready('s8');+ expect(u.out).toEqual([{ t: 'model-bound', sessionKey: 's8', mode: 'profile', profile: 'claude-a', key: 'claude-a-key' }]);+ expect(u.a.forRunner('s8', creds)?.model).toMatchObject({ profile: 'claude-a' });+ expect(u.a.forRunner('api', creds)?.model).toBeUndefined(); // on another credential: kept until its own route comes++ // An opc turn reaches its runner over the session API, with no delivery (api-host.ts `routed`): it is bound before the call goes on.+ await u.a.called('api');+ expect(u.out.at(-1)).toEqual({ t: 'model-bound', sessionKey: 'api', mode: 'profile', profile: 'claude-a', key: 'claude-a-key' });+ expect(u.a.forRunner('api', creds)?.model).toMatchObject({ profile: 'claude-a' });+ const n = u.out.length;+ await u.a.called('api'); // a runner already settled: nothing again+ expect(u.out.length).toBe(n);+ await stopProxy();+ rmSync(file, { force: true });+ }, 30_000);+it('re-hello: a proxy that restarts empty gets every held bind again; while down the host advertises no profiles', async () => {const t = setup();await t.up();diff --git a/computer/src/host/model-access.ts b/computer/src/host/model-access.tsindex 62482ab1..5891a116 100644--- a/computer/src/host/model-access.ts+++ b/computer/src/host/model-access.ts@@ -14,7 +14,13 @@// carried, else `models[harness]` from the last `welcome` or `credentials`,// else none, which is bound as a refusal. Nothing is persisted: a runner// found again after a host restart keeps the binding the proxy holds until-// its session's route arrives with a delivery or a `model` frame.+// its session's route arrives with a delivery, a `model` frame or a call of+// the session API (`called`, which settles it on `models` as a delivery+// without a route does). One the proxy lists on `models[harness]`'s+// credential, or not at all, is settled on `models` as soon as both are+// known: when the proxy restarted with the host, its binding came back from+// disk without the variables, and only a bind restores them (else every+// model request of the session is held, then 503, until the runner exits).// - A bind the proxy refuses is bound again as a refusal naming the code; a// refusal is never retried, so this cannot loop. A bind with no answer in// 5 s drops the control connection, and the next hello re-sends every bind.@@ -39,7 +45,7 @@ import type { Telemetry } from '../telemetry/emitter.js';import { send } from '../ipc.js';import { log } from '../log.js';import { spareKind } from '../model-key.js';-import { type ModelProxy, modelProxy, type ProxyBind, type ProxyEvent, type ProxyOptions } from './model-proxy.js';+import { type ModelProxy, modelProxy, type ProxyBind, type ProxyHello, type ProxyEvent, type ProxyOptions } from './model-proxy.js';export const NO_MODEL_CREDENTIAL = 'No model credential is configured for this computer.';export const PROXY_DOWN = "This computer's model proxy is not running.";@@ -199,6 +205,26 @@ export function hostModelAccess(o: HostModelAccessDeps) {} else if (route) update([key], () => own.set(key, route));}+ /** The proxy's binding `b` is on `route`'s credential (a refusal is any refusal). */+ const on = (b: ProxyHello['bindings'][number], route: ModelRoute | undefined) =>+ route?.mode === b.mode && (route.mode === 'refuse' || (route.profile === b.profile && route.key === b.key));++ /**+ * Settle the found runners in `keys` on `models`, once the proxy and `models` are both known, unless the proxy holds+ * their caller for this session on another credential (their own route's: kept until it arrives). The same bind+ * again changes nothing at a proxy that kept its variables, and restores them at one that restarted.+ */+ function settleFound(keys: Iterable<string> = unknown) {+ if (!proxy.up || !models) return;+ const at = new Map(proxy.hello!.bindings.map((b) => [b.caller, b]));+ for (const key of [...keys]) {+ const r = o.runner(key);+ const b = r && at.get(callerOf(r.id));+ if (!r || (b && (b.sessionKey !== key || !on(b, models[r.harness ?? 'claude'])))) continue;+ routed(key, undefined);+ }+ }+function forRunner(key: string, c: HostCredentials | undefined, harness = o.runner(key)?.harness ?? 'claude'): HostCredentials | undefined {if (!c) return undefined;const slack = slackOnly(c);@@ -245,6 +271,7 @@ export function hostModelAccess(o: HostModelAccessDeps) {h.refused = undefined;void bind(caller);}+ settleFound();for (const b of hello.bindings) {if (held.has(b.caller)) continue;void o.unitExists(b.caller).then((exists) => exists || held.has(b.caller) || proxy.release(b.caller));@@ -281,7 +308,7 @@ export function hostModelAccess(o: HostModelAccessDeps) {profiles,/** Runner `id`, on `harness`, now serves `key`: bind it, unless it was found after a restart (its route comes later). */registered(key: string, id: string, harness: HarnessName = 'claude', found = false) {- if (found) return void unknown.add(key);+ if (found) return void (unknown.add(key), settleFound([key]));const caller = callerOf(id);const h = held.get(caller);if (h?.sessionKey !== key || h.harness !== harness) void hold(caller, key, harness);@@ -304,6 +331,11 @@ export function hostModelAccess(o: HostModelAccessDeps) {await live(key)?.h.pending;return forRunner(key, c, harness);},+ /** A call of the session API is about to reach `key`'s live runner, with no delivery: settle a found runner as a delivery without a route would; settles once its bind was answered. */+ async called(key: string) {+ routed(key, undefined);+ await live(key)?.h.pending;+ },/** Credentials as `key`'s runner (on `harness`, else its live runner's; '' for a spare) gets them: Slack's, plus C4. */forRunner,/** The spare kind `key` on `harness` may take (model-key.ts), if its route has one. */@@ -332,6 +364,7 @@ export function hostModelAccess(o: HostModelAccessDeps) {const before = models?.claude;const keys = [...held.values()].map((h) => h.sessionKey).filter((k) => !k.startsWith(SPARE) && !own.has(k));update(keys, () => (models = m.models));+ settleFound();if (!isDeepStrictEqual(before, models?.claude)) for (const [caller, h] of held) if (h.sessionKey.startsWith(SPARE)) void bind(caller);return false;}diff --git a/computer/src/runner/harness/claude/translate.test.ts b/computer/src/runner/harness/claude/translate.test.tsindex 58d64fb1..813a4705 100644--- a/computer/src/runner/harness/claude/translate.test.ts+++ b/computer/src/runner/harness/claude/translate.test.ts@@ -115,6 +115,27 @@ describe('Translator', () => {expect(tr({ type: 'result', subtype: 'error_max_turns' })[0]).toMatchObject({ reason: 'error', detail: 'error_max_turns' });});+ it('a turn that ended on an API error fails: `is_error`, or the main thread ending on an `error`, with the error as detail', () => {+ const t = new Translator();+ const end = (m: Record<string, unknown> = {}) => t.translate({ type: 'result', subtype: 'success', ...m } as unknown as SDKMessage)[0];+ // The model proxy's 503 for a session it holds no credential for, as Claude Code ends the turn after its retries.+ t.translate(assistant('API Error: 503 model credential for this session is not ready', { error: 'server_error' }));+ expect(end({ is_error: true })).toMatchObject({ t: 'turn_ended', reason: 'error', detail: 'server_error' });+ expect(end({ is_error: true })).toMatchObject({ reason: 'error', detail: 'api_error' });+ t.translate(assistant('API Error: 500', { error: 'unknown' }));+ expect(end()).toMatchObject({ reason: 'error', detail: 'unknown' });+ // A message that recovered, a subagent's error, credits and a denied model end it `done`: the last two say why themselves.+ t.translate(assistant('', { error: 'max_output_tokens' }));+ t.translate(assistant('continued'));+ expect(end()).toEqual(expect.objectContaining({ reason: 'done' }));+ t.translate(assistant('API Error: 500', { error: 'server_error', parent_tool_use_id: 'task1' }));+ expect(end()).not.toHaveProperty('detail');+ t.translate(assistant('API Error: 402 requires more credits', { error: 'billing_error' }));+ expect(end({ is_error: true })).toMatchObject({ reason: 'done' });+ t.translate(assistant('model not allowed', { error: 'model_not_found' }));+ expect(end({ is_error: true })).toMatchObject({ reason: 'done' });+ });+it('system messages: init, requesting, compaction start and end', () => {expect(tr(diff --git a/computer/src/runner/harness/claude/translate.ts b/computer/src/runner/harness/claude/translate.tsindex 7d6069ef..e6d1e9c5 100644--- a/computer/src/runner/harness/claude/translate.ts+++ b/computer/src/runner/harness/claude/translate.ts@@ -7,7 +7,11 @@// calls and messages arrive with `parent`, its lifecycle as `task` records;// - a message's text is shown from its deltas; one that never streamed (some// SDK failures arrive only as a final assistant message) arrives as a whole-// `text` record, unless it is a refusal for credits, which is a `limit`.+// `text` record, unless it is a refusal for credits, which is a `limit`;+// - a turn that ended on an API error (`is_error` on a `success` result, or+// the main thread's last message carrying an `error`) ends `error`, so it+// is failed, not completed; unless it was a refusal for credits or a denied+// model, which their own records already report.import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';import { resultText } from '../../format.js';@@ -21,6 +25,7 @@ interface Fields {status?: unknown;parent_tool_use_id?: string | null;error?: string;+ is_error?: boolean;event?: {type?: string;index?: number;@@ -80,6 +85,8 @@ export class Translator {private streamed = false;/** Records a hook produced (hooks.ts), out with the next message so the stream keeps its order. */private held: HarnessEvent[] = [];+ /** The main thread's last message's `error` this turn; null: one its own record reports (credits, a denied model). */+ private apiError?: string | null;/** The PostCompact hook: the compaction's summary is written, `chars` long. */summarized(chars: number) {@@ -113,18 +120,22 @@ export class Translator {return this.assistant(m, e);case 'user':return e.parent_tool_use_id ? [] : results(e.message?.content);- case 'result':+ case 'result': {+ const apiError = this.apiError;+ this.apiError = undefined;+ // `error_during_execution` is a stopped turn or a failed one: Session and TurnEvents know which.+ const detail = e.subtype !== 'success' ? e.subtype : apiError === null ? undefined : (apiError ?? (e.is_error ? 'api_error' : undefined));return [{t: 'turn_ended',- // `error_during_execution` is a stopped turn or a failed one: Session and TurnEvents know which.- reason: e.subtype === 'success' ? 'done' : 'error',- ...(e.subtype !== 'success' ? { detail: e.subtype } : {}),+ reason: detail ? 'error' : 'done',+ ...(detail ? { detail } : {}),usage: usage(e.usage),...(e.duration_api_ms !== undefined ? { apiMs: e.duration_api_ms } : {}),...(e.total_cost_usd !== undefined ? { costTotalUsd: e.total_cost_usd } : {}),},];+ }}return [];}@@ -194,7 +205,9 @@ export class Translator {const out: HarnessEvent[] = [{ t: 'message', ...(parent ? { parent } : {}) }];const credits = isOutOfCredits(m);if (credits) out.push({ t: 'limit', kind: 'credits' });- if (isModelDenied(m)) out.push({ t: 'error', kind: 'model', code: 'model_not_found', message: textOf(content) });+ const denied = isModelDenied(m);+ if (denied) out.push({ t: 'error', kind: 'model', code: 'model_not_found', message: textOf(content) });+ if (!parent) this.apiError = credits || denied ? null : e.error;if (!parent && !this.streamed && !credits) {const text = textOf(content);if (text) out.push({ t: 'text', delta: text });