diff --git a/docs/BUDGET.md b/docs/BUDGET.md index b8f23c770..5eedab4d8 100644 --- a/docs/BUDGET.md +++ b/docs/BUDGET.md @@ -94,8 +94,13 @@ wrapper may return an explicit result envelope after its execution handshake: {"protocol":"relayflows-agent-cli-v1-result","output":"answer","usage":{"input_tokens":1000,"output_tokens":200}} ``` +Devin print mode returns plain text without authoritative usage. Its agent +steps always warn `budget_unmetered`, even with a priced model, and journal +unmetered usage with zero reported tokens. Token and dollar ceilings cannot +measure their spend; use a timeout to bound execution duration. + A priced model with missing or malformed usage produces a journaled worker -error. An unpriced model's usage is optional: reported tokens are journaled +error for adapters that report usage. An unpriced model's usage is optional: reported tokens are journaled with `dollars_unmetered: true`, and a completion with no reported tokens is still marked unmetered (with zero tokens). Workers never omit usage for an unpriced step and never send `dollars` alongside `dollars_unmetered`; the kernel diff --git a/docs/DEVIN.md b/docs/DEVIN.md new file mode 100644 index 000000000..03fa94c06 --- /dev/null +++ b/docs/DEVIN.md @@ -0,0 +1,42 @@ +# Devin agent steps + +Use the installed `devin` executable for an agent step: + +```yaml +version: '0.1.0' +steps: + - id: implement + type: agent + cli: devin + instruction: Fix the failing test and explain the change. + timeoutMs: 600000 +``` + +An optional `model` is passed through `--model`. Execution uses `devin -p +--prompt-file --permission-mode dangerous +--respect-workspace-trust false`. Its printed response is the step result. +Devin is an agent harness; `llm` steps are refused at preflight. + +For hosted flows, provide a Devin CLI login token as the +`FLOW_DEVIN_API_KEY` workspace secret. This requires a hosted launcher with +`FLOW_` credential-alias support that supplies it to the agent runtime as +`DEVIN_API_KEY`; local runs set `DEVIN_API_KEY` directly. +This is the token stored as `windsurf_api_key` by CLI login; a Devin REST API +key is a different credential. The verified +Devin CLI release `3000.11.234` does not read that variable itself. The worker +writes it as `windsurf_api_key` in a private `credentials.toml`, selects that +attempt's XDG data/config/cache directories, and removes the private state +when execution ends, fails, or is aborted. The original home and interactive +credentials are untouched. Local runs without the variable use the existing +Devin login from `devin auth login`. + +Preflight checks the executable and authenticates with `devin models list +--format json`; `devin auth status` exits zero even when logged out. An +explicit model is checked with a headless model round trip. + +Print mode provides no authoritative token usage. Every Devin step warns +`budget_unmetered`, including steps with a priced model: token and dollar +ceilings cannot measure its spend. Set a timeout to bound its duration. + +Broker skill installation uses the supported Windsurf target, whose +`.windsurf/skills` directory Devin also reads. diff --git a/docs/SURFACE.md b/docs/SURFACE.md index 6aa54df03..262368f65 100644 --- a/docs/SURFACE.md +++ b/docs/SURFACE.md @@ -437,7 +437,8 @@ Broker `cwd` accepts an existing absolute directory or a path relative to the ru root, including an external git worktree. `skills` names come from the canonical `AgentWorkforce/skills` repository. The `skills` CLI installs full directories, including supporting files, in the agent's project before spawning. Supported -skill targets are Claude Code, Codex, Gemini CLI, Cursor, and OpenCode; an +skill targets are Claude Code, Codex, Gemini CLI, Cursor, OpenCode, and Devin +(through its Windsurf-compatible skill directory); an unsupported target or installation failure fails the step. The broker name contains the sanitized flow and authored agent name plus a diff --git a/evidence/devin-harness/artifact-and-redaction-followup.md b/evidence/devin-harness/artifact-and-redaction-followup.md new file mode 100644 index 000000000..c544d9ddf --- /dev/null +++ b/evidence/devin-harness/artifact-and-redaction-followup.md @@ -0,0 +1,233 @@ +# Artifact CI and overlapping probe redactions + +The [artifact job at a046f280](https://github.com/AgentWorkforce/flows/actions/runs/41524171476/job/125547526284) failed on two issue-swarm calls without explicit models. +The example now pins each supported broker/skills CLI pair explicitly (Claude, +Codex, Cursor), refusing other selections before effects. No CI gate, scanner, +or waiver was changed. + +Probe redaction preserves shared known-value/header/cookie/environment-dump +handling first. It then collects supplemental email/token/hex matches and short +Devin credential matches against that same redacted text, masking the union of +overlapping spans. This covers a short key inside a shape, a shape inside a short +key, and overlapping occurrences of a short key. Regression tests cover both +synchronous and asynchronous drivers and preserve other providers' known-secret +handling. There are no changes to the shared transcript redactor. + +The model-pin test now reaches the pre-existing dynamic call in land.flow.ts. +Its failure is captured below; this report does not claim green CI. The land +owner has been notified. + +## SDK focused regressions and types + +Working directory: `packages/sdk`. + +```sh +set -o pipefail; { TMPDIR=/Users/khaliqgant/.cache/devin-harness node node_modules/vitest/vitest.mjs run tests/devin.test.ts tests/cli-probe.test.ts tests/preflight.test.ts tests/agent-transcript.test.ts && npm run typecheck && npm run typecheck:tests; } 2>&1 | tee /Users/khaliqgant/.cache/devin-harness/overlap-followup-final.log +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/agent-transcript.test.ts (29 tests) 141ms + ✓ tests/preflight.test.ts (70 tests) 42ms + ✓ tests/devin.test.ts (25 tests) 6255ms + ✓ launches print mode with file input and cleans up after --version +Do the task 326ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 408ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 612ms + ✓ fully redacts echoed credentials alongside shape-based scrubbing 325ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: abc 438ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: abc 315ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: abc 313ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: a@b.co! 409ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: aba 362ms + ✓ preserves shared redaction before short-key and supplemental rules: Authorization: Bearer abcSECRET_SUFFIX123456 494ms + ✓ preserves shared redaction before short-key and supplemental rules: Cookie: session=abcSECRET_SUFFIX123456 512ms + ✓ tests/cli-probe.test.ts (19 tests) 7214ms + ✓ redacts whole non-Devin secrets and enclosing shapes: prefix-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-secretSuffix 409ms + ✓ executes a canonical shebang target through its authored alias in both probe drivers 380ms + ✓ keeps synchronous and asynchronous classification equal: success 457ms + ✓ keeps synchronous and asynchronous classification equal: auth denied 329ms + ✓ keeps missing executables and unsupported identification fail closed 335ms + ✓ scopes delivered secrets in PATH lookup and provider probes for checked and authored steps 986ms + ✓ reports timeout in both drivers while the async driver leaves the loop free 791ms + ✓ reports signal termination in both drivers 320ms + ✓ classifies a failed claude model probe from its own output: outdated CLI 448ms + ✓ classifies a failed claude model probe from its own output: usage limit 456ms + ✓ classifies a failed claude model probe from its own output: unknown model 376ms + ✓ classifies a failed claude model probe from its own output: unrecognised output 419ms + + Test Files 4 passed (4) + Tests 143 passed (143) + Start at 13:43:03 + Duration 8.54s (transform 1.09s, setup 49ms, collect 2.97s, tests 13.65s, environment 0ms, prepare 217ms) + + +> @relayflows/sdk@2.0.55 typecheck +> tsc --noEmit && tsc -p tsconfig.type-tests.json + + +> @relayflows/sdk@2.0.55 typecheck:tests +> tsc -p tsconfig.tests.json + +``` + +## Issue-swarm model selection and saved-source behavior + +Working directory: `examples/issue-swarm`. + +```sh +set -o pipefail; { TMPDIR=/Users/khaliqgant/.cache/devin-harness npm run typecheck && TMPDIR=/Users/khaliqgant/.cache/devin-harness npm test; } 2>&1 | tee /Users/khaliqgant/.cache/devin-harness/issue-swarm-pins-final.log +``` + +```text + +> typecheck +> tsc -p tsconfig.json + + +> test +> node --experimental-strip-types --test tests/*.test.ts + +✔ count bounds parallel issues; three broker reviewers per PR; releases before removing worktrees (3.38375ms) +✔ each selectable CLI pins its model for implementers and reviewers (1.598542ms) +✔ unsupported CLI selections fail before commands or sessions start (0.347334ms) +✔ NO-GO findings go to the same implementer, followed by fresh review (0.66925ms) +✔ monitor sends CI and review-thread repairs, then captures fresh state (1.268083ms) +✔ pending checks and unknown mergeability wait without repair pushes (0.472875ms) +✔ a completed clean snapshot takes precedence over deadline expiry (0.169417ms) +✔ monitor fixes that push a new head trigger all three reviewers again (0.216083ms) +✔ a timed out message ends with human attention and releases its implementer (0.446584ms) +✔ a new head cannot inherit GO after the last review pass (0.272959ms) +✔ review exhaustion and unknown mergeability cannot become success at deadline (0.196083ms) +✔ zero monitor budget captures status but sends no monitor repair (0.10475ms) +✔ a failed lane waits for peers and still releases each returned session (0.610709ms) +✔ worktree creation failure still cleans up the successful sibling lane (0.324125ms) +✔ malformed reviewer result releases implementers and cannot produce GO (0.173375ms) +✔ release failures preserve that worktree and do not skip other cleanup (1.212292ms) +✔ dirty worktree is preserved and cleanup error reported (0.485083ms) +✔ empty issue list allocates no agents or worktrees (0.217208ms) +✔ title-only issues normalize null body without losing their identity (0.134667ms) +✔ invalid input fails before effects; label shell metacharacters stay quoted (0.240167ms) +✔ explicit foreign repo and a mismatched origin fail before allocating worktrees (0.225375ms) +✔ malformed, stale and contradictory verdicts fail closed (0.504833ms) +✔ captures current-head checks, newest status and final metadata read (1.212458ms) +✔ pages REST checks and GraphQL unresolved threads (1.2305ms) +✔ a later approval clears a changes-requested review but a comment does not (0.482708ms) +✔ rejects changing heads and incomplete GraphQL responses (0.763042ms) +✔ pending, stale checks, unknown mergeability, blocked state and stale review fail closed (0.26075ms) +✔ GraphQL repeated cursors and REST pagination exhaustion fail closed (0.855292ms) +✔ saved source runs with fakes after copying without sibling modules (21.3055ms) +ℹ tests 29 +ℹ suites 0 +ℹ pass 29 +ℹ fail 0 +ℹ cancelled 0 +ℹ skipped 0 +ℹ todo 0 +ℹ duration_ms 158.819208 +``` + +## Remaining model-pin failure + +Working directory: `packages/sdk`. + +```sh +set -o pipefail; TMPDIR=/Users/khaliqgant/.cache/devin-harness node node_modules/vitest/vitest.mjs run tests/shipped-source-models.test.ts 2>&1 | tee /Users/khaliqgant/.cache/devin-harness/shipped-source-pins.log +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ❯ tests/shipped-source-models.test.ts (2 tests | 1 failed) 157829ms + × first-party shipped source model pins > gives every TypeScript agent and LLM an explicit supported pair or a pinned named-agent declaration 157789ms + → examples/land/land.flow.ts: omitted pairs must resolve call-exactly through complete named agents: expected [ Array(1) ] to deeply equal [] + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL tests/shipped-source-models.test.ts > first-party shipped source model pins > gives every TypeScript agent and LLM an explicit supported pair or a pinned named-agent declaration +AssertionError: examples/land/land.flow.ts: omitted pairs must resolve call-exactly through complete named agents: expected [ Array(1) ] to deeply equal [] + +- Expected ++ Received + +- Array [] ++ Array [ ++ "examples/land/land.flow.ts:557 has unprovable options overrides", ++ ] + + ❯ tests/shipped-source-models.test.ts:100:112 + 98| seenDynamicWaivers.add(name); + 99| } + 100| expect(result.missing, `${name}: omitted pairs must resolve call… + | ^ + 101| } + 102| expect(seenDynamicWaivers).toEqual(new Set(DYNAMIC_PAIR_SOURCE_WAI… + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + Test Files 1 failed (1) + Tests 1 failed | 1 passed (2) + Start at 13:37:13 + Duration 158.34s (transform 111ms, setup 9ms, collect 316ms, tests 157.83s, environment 0ms, prepare 28ms) + +``` + +## Bounded diagnostic coverage follow-up + +The span arrays/sort above are replaced by a single byte mask over the +shared-redacted text. Shape matches and short-key occurrences mark covered +characters; connected marked runs are emitted once with credential marker +precedence. Auxiliary coverage storage is one byte per diagnostic character, +independent of how many matches it contains. Shared redaction remains first. +An email-start boundary prevents retrying the email matcher inside every suffix +of a long word. + +The fixture writes the full 900,000-character diagnostic synchronously before +exiting, so both probe drivers receive it completely. The assertion includes the +credential-file echo after that diagnostic, protecting against a truncated fixture. +No gates, waivers, or land source were modified. + +Working directory: packages/sdk. + +```sh +set -o pipefail; { TMPDIR=/Users/khaliqgant/.cache/devin-harness node node_modules/vitest/vitest.mjs run tests/devin.test.ts tests/cli-probe.test.ts tests/preflight.test.ts tests/agent-transcript.test.ts && npm run typecheck && npm run typecheck:tests; } 2>&1 | tee /Users/khaliqgant/.cache/devin-harness/bounded-redaction-final.log +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/agent-transcript.test.ts (29 tests) 153ms + ✓ tests/preflight.test.ts (70 tests) 48ms + ✓ tests/devin.test.ts (26 tests) 5637ms + ✓ redacts a near-buffer-size response to a one-character credential without retaining per-match spans 416ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 411ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 583ms + ✓ fully redacts echoed credentials alongside shape-based scrubbing 315ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: abc 362ms + ✓ redacts the complete overlap between credentials and diagnostic shapes: aba 507ms + ✓ tests/cli-probe.test.ts (19 tests) 5979ms + ✓ returns the absolute executable selected for a bare CLI name 339ms + ✓ keeps synchronous and asynchronous classification equal: model denied 439ms + ✓ scopes delivered secrets in PATH lookup and provider probes for checked and authored steps 935ms + ✓ reports timeout in both drivers while the async driver leaves the loop free 449ms + ✓ reports signal termination in both drivers 532ms + ✓ classifies a failed claude model probe from its own output: unrecognised output 377ms + + Test Files 4 passed (4) + Tests 144 passed (144) + Start at 13:52:47 + Duration 7.26s (transform 1.09s, setup 44ms, collect 2.86s, tests 11.82s, environment 0ms, prepare 200ms) + + +> @relayflows/sdk@2.0.55 typecheck +> tsc --noEmit && tsc -p tsconfig.type-tests.json + + +> @relayflows/sdk@2.0.55 typecheck:tests +> tsc -p tsconfig.tests.json + +``` diff --git a/evidence/devin-harness/land-credential-followup.md b/evidence/devin-harness/land-credential-followup.md new file mode 100644 index 000000000..d1d52d74a --- /dev/null +++ b/evidence/devin-harness/land-credential-followup.md @@ -0,0 +1,165 @@ +# Hosted-land credential diagnostics follow-up + +Hosted flow operators supply a CLI-login token through `FLOW_DEVIN_API_KEY`; the Cloud alias passes it to the runtime as `DEVIN_API_KEY`. Local runtime use retains `DEVIN_API_KEY`. Sign-in refusals now state both contexts, and auth probes retain actual error details with credential values redacted. + +The first regression attempt accidentally ran `npx` from the repository root and selected Vitest 5.1.0. Its new assertion also expected the wrong casing for the redaction marker. That assertion was corrected to the implementation's marker, and the check reran from `packages/sdk` using the installed Vitest 2.1.9. This was a test-expectation failure; the output already showed the credential value redacted. + +Initial command, from repository root: + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp npx vitest run tests/devin.test.ts tests/cli-probe.test.ts tests/preflight.test.ts +``` + +```text +npm warn exec The following package was not found and will be installed: vitest@5.1.0 + + RUN v5.1.0 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102 + + ❯ packages/sdk/tests/devin.test.ts (13 tests | 1 failed) 1925ms + × redacts a provider auth failure that echoes its staged credential, including a padded key 355ms + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL packages/sdk/tests/devin.test.ts > redacts a provider auth failure that echoes its staged credential, including a padded key +AssertionError: expected 'windsurf_api_key = "[redacted:DEVIN_A…' to contain 'REDACTED' + +Expected: "REDACTED" +Received: "windsurf_api_key = "[redacted:DEVIN_API_KEY]"" + + ❯ packages/sdk/tests/devin.test.ts:191:38 + 189| expect(result.authExitCode).toBe(1); + 190| expect(result.authFailureDetail).not.toContain('invalid-devin-secr… + 191| expect(result.authFailureDetail).toContain('REDACTED'); + | ^ + 192| } + 193| }); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯ + + + Test Files 1 failed | 2 passed (3) + Tests 1 failed | 100 passed (101) + Start at 12:14:57 + Duration 6.31s (tests 71%, transform 17%, import 12%) +``` + +Corrected command, from `packages/sdk`: + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp node node_modules/vitest/vitest.mjs run tests/devin.test.ts tests/cli-probe.test.ts tests/preflight.test.ts && npm run typecheck && npm run typecheck:tests +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/preflight.test.ts (70 tests) 39ms + ✓ tests/devin.test.ts (14 tests) 1840ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 349ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 520ms + ✓ tests/cli-probe.test.ts (18 tests) 5186ms + ✓ returns the absolute executable selected for a bare CLI name 341ms + ✓ executes a canonical shebang target through its authored alias in both probe drivers 307ms + ✓ scopes delivered secrets in PATH lookup and provider probes for checked and authored steps 794ms + ✓ reports timeout in both drivers while the async driver leaves the loop free 496ms + + Test Files 3 passed (3) + Tests 102 passed (102) + Start at 12:18:04 + Duration 6.41s (transform 988ms, setup 30ms, collect 2.71s, tests 7.06s, environment 0ms, prepare 137ms) + +> @relayflows/sdk@2.0.55 typecheck +> tsc --noEmit && tsc -p tsconfig.type-tests.json + + +> @relayflows/sdk@2.0.55 typecheck:tests +> tsc -p tsconfig.tests.json + +``` + +The actual replacement workspace CLI token has not been tested by this session. No secret was created, replaced, or printed. + +Known secret values are redacted before general email/token/hex patterns so an interior match cannot expose a token suffix. The regression includes an echoed padded key with a 32-hex interior fragment. + +The hosted operator prefix was subsequently renamed from `LAND_` to `FLOW_`. Current guidance uses `FLOW_DEVIN_API_KEY`; historical captured runs above remain unchanged. Focused rename checks, run from `packages/sdk`: + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp node node_modules/vitest/vitest.mjs run tests/devin.test.ts tests/preflight.test.ts && npm run typecheck && npm run typecheck:tests +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/preflight.test.ts (70 tests) 41ms + ✓ tests/devin.test.ts (14 tests) 2126ms + ✓ launches print mode with file input and cleans up after --version +Do the task 339ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 346ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 443ms + ✓ fully redacts echoed credentials before shape-based scrubbing 309ms + ✓ fully redacts echoed credentials before shape-based scrubbing 380ms + + Test Files 2 passed (2) + Tests 84 passed (84) + Start at 12:46:04 + Duration 2.89s (transform 911ms, setup 20ms, collect 1.78s, tests 2.17s, environment 0ms, prepare 110ms) + +> @relayflows/sdk@2.0.55 typecheck +> tsc --noEmit && tsc -p tsconfig.type-tests.json + + +> @relayflows/sdk@2.0.55 typecheck:tests +> tsc -p tsconfig.tests.json + +``` + +Short-key review follow-up: preflight removes explicitly supplied normalized Devin credentials even when they are shorter than the shared redactor's eight-character threshold. Regression cases include one, three and seven characters in both probe drivers. Documentation describes the required hosted mapping without a PR-specific dependency. Captured grouped command, from `packages/sdk`: + +```sh +set -o pipefail; { TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp node node_modules/vitest/vitest.mjs run tests/devin.test.ts tests/cli-probe.test.ts tests/preflight.test.ts && npm run typecheck && npm run typecheck:tests; } 2>&1 | tee /Users/khaliqgant/.cache/devin-harness/flows-short-key-tests.log +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/preflight.test.ts (70 tests) 45ms + ✓ tests/devin.test.ts (17 tests) 3471ms + ✓ launches print mode with file input and cleans up after --version +Do the task 412ms + ✓ redacts the normalized token when the supplied key has surrounding whitespace 348ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 338ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 486ms + ✓ fully redacts echoed credentials before shape-based scrubbing 303ms + ✓ fully redacts echoed credentials before shape-based scrubbing 312ms + ✓ fully redacts echoed credentials before shape-based scrubbing 394ms + ✓ fully redacts echoed credentials before shape-based scrubbing 432ms + ✓ tests/cli-probe.test.ts (18 tests) 6828ms + ✓ executes a canonical shebang target through its authored alias in both probe drivers 323ms + ✓ keeps synchronous and asynchronous classification equal: model denied 469ms + ✓ keeps synchronous and asynchronous classification equal: auth denied 390ms + ✓ keeps missing executables and unsupported identification fail closed 332ms + ✓ uses an explicit provider environment for every probe process 318ms + ✓ scopes delivered secrets in PATH lookup and provider probes for checked and authored steps 1009ms + ✓ reports timeout in both drivers while the async driver leaves the loop free 538ms + ✓ reports signal termination in both drivers 370ms + ✓ classifies a failed claude model probe from its own output: outdated CLI 388ms + ✓ classifies a failed claude model probe from its own output: usage limit 443ms + ✓ classifies a failed claude model probe from its own output: rate limit 380ms + ✓ classifies a failed claude model probe from its own output: unknown model 429ms + ✓ classifies a failed claude model probe from its own output: unrecognised output 441ms + + Test Files 3 passed (3) + Tests 105 passed (105) + Start at 12:55:36 + Duration 8.22s (transform 1.05s, setup 34ms, collect 3.03s, tests 10.34s, environment 0ms, prepare 149ms) + + +> @relayflows/sdk@2.0.55 typecheck +> tsc --noEmit && tsc -p tsconfig.type-tests.json + + +> @relayflows/sdk@2.0.55 typecheck:tests +> tsc -p tsconfig.tests.json +``` diff --git a/evidence/devin-harness/linux-probe-run.original.txt b/evidence/devin-harness/linux-probe-run.original.txt new file mode 100644 index 000000000..d9c9d40a9 --- /dev/null +++ b/evidence/devin-harness/linux-probe-run.original.txt @@ -0,0 +1,12 @@ +import pathlib,urllib.request,hashlib,tarfile,subprocess,base64,os +root=pathlib.Path.home()/'.cache/devin-harness-20261102' +root.mkdir(parents=True,exist_ok=True) +bundle=root/'devin-linux-x64.tar.gz' +url='https://static.devin.ai/cli/3000.11.234/devin-3000.11.234-x86_64-unknown-linux.tar.gz' +urllib.request.urlretrieve(url,bundle) +assert hashlib.sha256(bundle.read_bytes()).hexdigest()=='201370cddd2924294e3ca6b46fd8ece49b5763953b644a1dd823fce5490cb41a' +print('Linux x64 bundle SHA-256 verified',flush=True) +with tarfile.open(bundle) as archive:archive.extractall(root/'cli',filter='data') +probe=root/'probe-cli.py' +probe.write_bytes(base64.b64decode('IiIiUHJvYmUgYW4gaW5zdGFsbGVkIERldmluIHdpdGhvdXQgdG91Y2hpbmcgaXRzIGludGVyYWN0aXZlIGNyZWRlbnRpYWxzLiIiIgppbXBvcnQgYXJncGFyc2UKaW1wb3J0IGpzb24KaW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgdGVtcGZpbGUKaW1wb3J0IHRvbWxsaWIKCnBhcnNlciA9IGFyZ3BhcnNlLkFyZ3VtZW50UGFyc2VyKCkKcGFyc2VyLmFkZF9hcmd1bWVudCgiLS1jbGkiLCByZXF1aXJlZD1UcnVlKQpwYXJzZXIuYWRkX2FyZ3VtZW50KCItLWNyZWRlbnRpYWxzIiwgdHlwZT1QYXRoKQphcmdzID0gcGFyc2VyLnBhcnNlX2FyZ3MoKQpwcmludChzdWJwcm9jZXNzLmNoZWNrX291dHB1dChbYXJncy5jbGksICItLXZlcnNpb24iXSwgdGV4dD1UcnVlKS5zdHJpcCgpLCBmbHVzaD1UcnVlKQptb2RlcyA9IFsibm9uZSIsICJkdW1teV9lbnYiLCAiZHVtbXlfZmlsZSJdCmlmIGFyZ3MuY3JlZGVudGlhbHM6CiAgICBtb2Rlcy5hcHBlbmQoImV4aXN0aW5nX2xvZ2luX2ZpbGUiKQpmb3IgbW9kZSBpbiBtb2RlczoKICAgIHdpdGggdGVtcGZpbGUuVGVtcG9yYXJ5RGlyZWN0b3J5KHByZWZpeD0iZGV2aW4tcHJvYmUtIikgYXMgZGlyZWN0b3J5OgogICAgICAgIHJvb3QgPSBQYXRoKGRpcmVjdG9yeSkKICAgICAgICBlbnYgPSBkaWN0KG9zLmVudmlyb24sIEhPTUU9ZGlyZWN0b3J5LCBYREdfREFUQV9IT01FPXN0cihyb290IC8gImRhdGEiKSwKICAgICAgICAgICAgICAgICAgIFhER19DT05GSUdfSE9NRT1zdHIocm9vdCAvICJjb25maWciKSwgWERHX0NBQ0hFX0hPTUU9c3RyKHJvb3QgLyAiY2FjaGUiKSkKICAgICAgICBlbnYucG9wKCJERVZJTl9BUElfS0VZIiwgTm9uZSkKICAgICAgICBpZiBtb2RlID09ICJkdW1teV9lbnYiOgogICAgICAgICAgICBlbnZbIkRFVklOX0FQSV9LRVkiXSA9ICJwcm9iZS1pbnZhbGlkIgogICAgICAgIGlmIG1vZGUuZW5kc3dpdGgoImZpbGUiKToKICAgICAgICAgICAga2V5ID0gInByb2JlLWludmFsaWQiIGlmIG1vZGUgPT0gImR1bW15X2ZpbGUiIGVsc2UgdG9tbGxpYi5sb2FkcygKICAgICAgICAgICAgICAgIGFyZ3MuY3JlZGVudGlhbHMucmVhZF90ZXh0KCkpWyJ3aW5kc3VyZl9hcGlfa2V5Il0KICAgICAgICAgICAgY3JlZGVudGlhbCA9IHJvb3QgLyAiZGF0YS9kZXZpbi9jcmVkZW50aWFscy50b21sIgogICAgICAgICAgICBjcmVkZW50aWFsLnBhcmVudC5ta2RpcihwYXJlbnRzPVRydWUsIG1vZGU9MG83MDApCiAgICAgICAgICAgIGNyZWRlbnRpYWwud3JpdGVfdGV4dCgid2luZHN1cmZfYXBpX2tleSA9ICIgKyBqc29uLmR1bXBzKGtleSkgKyAiXG4iKQogICAgICAgICAgICBjcmVkZW50aWFsLmNobW9kKDBvNjAwKQogICAgICAgIHJlc3VsdCA9IHN1YnByb2Nlc3MucnVuKFthcmdzLmNsaSwgIm1vZGVscyIsICJsaXN0IiwgIi0tZm9ybWF0IiwgImpzb24iXSwKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBlbnY9ZW52LCBjd2Q9cm9vdCwgY2FwdHVyZV9vdXRwdXQ9VHJ1ZSwgdGV4dD1UcnVlLCB0aW1lb3V0PTMwKQogICAgICAgICMgUHJpbnQgb25seSBmaXhlZCBjbGFzc2lmaWNhdGlvbnM6IHByb3ZpZGVyIG91dHB1dCBjYW4gaWRlbnRpZnkgYW4gYWNjb3VudC4KICAgICAgICBkZXRhaWwgPSAoImNhdGFsb2cgcmVjZWl2ZWQiIGlmIHJlc3VsdC5yZXR1cm5jb2RlID09IDAgZWxzZQogICAgICAgICAgICAgICAgICAibm90IGxvZ2dlZCBpbiIgaWYgIk5vdCBsb2dnZWQgaW4iIGluIHJlc3VsdC5zdGRlcnIgZWxzZQogICAgICAgICAgICAgICAgICAiaW52YWxpZCBhcGkga2V5IiBpZiAiaW52YWxpZCBhcGkga2V5IiBpbiByZXN1bHQuc3RkZXJyIGVsc2UgInVuY2xhc3NpZmllZCBmYWlsdXJlIikKICAgICAgICBwcmludChmInttb2RlfTogbW9kZWxzIGV4aXQ9e3Jlc3VsdC5yZXR1cm5jb2RlfTsge2RldGFpbH0iLCBmbHVzaD1UcnVlKQogICAgICAgIGlmIG1vZGUgPT0gImV4aXN0aW5nX2xvZ2luX2ZpbGUiOgogICAgICAgICAgICBwcm9tcHQgPSByb290IC8gInByb21wdC50eHQiCiAgICAgICAgICAgIHByb21wdC53cml0ZV90ZXh0KCJSZXBseSB3aXRoIGV4YWN0bHkgUkVMQVlGTE9XU19ERVZJTl9SRUFEWSBhbmQgbm90aGluZyBlbHNlLiBEbyBub3QgY2FsbCB0b29scy4iKQogICAgICAgICAgICByZXN1bHQgPSBzdWJwcm9jZXNzLnJ1bihbYXJncy5jbGksICItcCIsICItLXByb21wdC1maWxlIiwgc3RyKHByb21wdCksCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAiLS1wZXJtaXNzaW9uLW1vZGUiLCAiZGFuZ2Vyb3VzIiwgIi0tcmVzcGVjdC13b3Jrc3BhY2UtdHJ1c3QiLCAiZmFsc2UiXSwKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZW52PWVudiwgY3dkPXJvb3QsIGNhcHR1cmVfb3V0cHV0PVRydWUsIHRleHQ9VHJ1ZSwgdGltZW91dD02MCkKICAgICAgICAgICAgcHJpbnQoZiJoZWFkbGVzcyBleGl0PXtyZXN1bHQucmV0dXJuY29kZX07IG1hcmtlciByZWNlaXZlZD17cmVzdWx0LnN0ZG91dC5zdHJpcCgpID09ICdSRUxBWUZMT1dTX0RFVklOX1JFQURZJ30iLAogICAgICAgICAgICAgICAgICBmbHVzaD1UcnVlKQo=')) +subprocess.run(['python3',str(probe),'--cli',str(root/'cli/bin/devin')],check=True,env=dict(os.environ,TMPDIR=str(root))) diff --git a/evidence/devin-harness/probe-cli.py b/evidence/devin-harness/probe-cli.py new file mode 100644 index 000000000..a48c38cc8 --- /dev/null +++ b/evidence/devin-harness/probe-cli.py @@ -0,0 +1,57 @@ +"""Probe an installed Devin without touching its interactive credentials.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile +import tomllib + +parser = argparse.ArgumentParser() +parser.add_argument("--cli", required=True) +parser.add_argument("--credentials", type=Path) +args = parser.parse_args() +EXPECTED_CLI_VERSION = "3000.11.234" +version = subprocess.check_output([args.cli, "--version"], text=True, timeout=10).strip() +print(version, flush=True) +if not version.startswith(f"devin {EXPECTED_CLI_VERSION} "): + raise SystemExit("Unexpected Devin CLI version") +modes = ["none", "dummy_env", "dummy_file"] +if args.credentials: + modes.append("existing_login_file") +for mode in modes: + with tempfile.TemporaryDirectory(prefix="devin-probe-") as directory: + root = Path(directory) + env = dict(os.environ, HOME=directory, XDG_DATA_HOME=str(root / "data"), + XDG_CONFIG_HOME=str(root / "config"), XDG_CACHE_HOME=str(root / "cache")) + env.pop("DEVIN_API_KEY", None) + if mode == "dummy_env": + env["DEVIN_API_KEY"] = "probe-invalid" + if mode.endswith("file"): + key = "probe-invalid" if mode == "dummy_file" else tomllib.loads( + args.credentials.read_text())["windsurf_api_key"] + credential = root / "data/devin/credentials.toml" + credential.parent.mkdir(parents=True, mode=0o700) + credential.write_text("windsurf_api_key = " + json.dumps(key) + "\n") + credential.chmod(0o600) + result = subprocess.run([args.cli, "models", "list", "--format", "json"], + env=env, cwd=root, capture_output=True, text=True, timeout=30) + # Print only fixed classifications: provider output can identify an account. + detail = ("catalog received" if result.returncode == 0 else + "not logged in" if "Not logged in" in result.stderr else + "invalid api key" if "invalid api key" in result.stderr else "unclassified failure") + print(f"{mode}: models exit={result.returncode}; {detail}", flush=True) + expected = "catalog received" if mode == "existing_login_file" else ( + "invalid api key" if mode == "dummy_file" else "not logged in") + if detail != expected: + raise SystemExit(f"{mode}: unexpected authentication behavior") + if mode == "existing_login_file": + prompt = root / "prompt.txt" + prompt.write_text("Reply with exactly RELAYFLOWS_DEVIN_READY and nothing else. Do not call tools.") + result = subprocess.run([args.cli, "-p", "--prompt-file", str(prompt), + "--permission-mode", "auto", "--respect-workspace-trust", "false"], + env=env, cwd=root, capture_output=True, text=True, timeout=60) + print(f"headless exit={result.returncode}; marker received={result.stdout.strip() == 'RELAYFLOWS_DEVIN_READY'}", + flush=True) + if result.returncode != 0 or result.stdout.strip() != 'RELAYFLOWS_DEVIN_READY': + raise SystemExit("Headless marker probe failed") diff --git a/evidence/devin-harness/probe-linux.py b/evidence/devin-harness/probe-linux.py new file mode 100644 index 000000000..42f00b602 --- /dev/null +++ b/evidence/devin-harness/probe-linux.py @@ -0,0 +1,27 @@ +"""Reproduce the pinned binary checks on a Linux x64 host (Python 3.14+).""" +import hashlib +import os +from pathlib import Path +import platform +import subprocess +import sys +import tarfile +import urllib.request + +if platform.system() != "Linux" or platform.machine() != "x86_64": + raise SystemExit("This probe requires Linux x64") +root = Path.home() / ".cache/devin-harness-20261102" +root.mkdir(parents=True, exist_ok=True) +bundle = root / "devin-linux-x64.tar.gz" +url = "https://static.devin.ai/cli/3000.11.234/devin-3000.11.234-x86_64-unknown-linux.tar.gz" +with urllib.request.urlopen(url, timeout=30) as response: + bundle.write_bytes(response.read()) +expected = "201370cddd2924294e3ca6b46fd8ece49b5763953b644a1dd823fce5490cb41a" +if hashlib.sha256(bundle.read_bytes()).hexdigest() != expected: + raise SystemExit("Linux x64 bundle checksum mismatch") +print("Linux x64 bundle SHA-256 verified", flush=True) +with tarfile.open(bundle) as archive: + archive.extractall(root / "cli", filter="data") +subprocess.run([sys.executable, str(Path(__file__).with_name("probe-cli.py")), + "--cli", str(root / "cli/bin/devin")], check=True, + env=dict(os.environ, TMPDIR=str(root)), timeout=120) diff --git a/evidence/devin-harness/verification.md b/evidence/devin-harness/verification.md new file mode 100644 index 000000000..72b93fa37 --- /dev/null +++ b/evidence/devin-harness/verification.md @@ -0,0 +1,422 @@ +# Devin harness verification — 2026-11-02 + +Scope: direct Devin agent execution, credential handling, communication environment and preflight. Devin print mode is explicitly unmetered; `llm` use is refused. No package was published. + +Commands below ran from `packages/sdk` unless stated otherwise. + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp npx vitest run tests/devin.test.ts tests/adapters tests/communication-review.test.ts tests/communication-worker.test.ts tests/communication-preflight.test.ts tests/worker-cli.test.ts tests/budget-preflight.test.ts tests/preflight.test.ts tests/cli-probe.test.ts +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/adapters/codex.test.ts (13 tests) 11ms + ✓ tests/adapters/claude.test.ts (13 tests) 4ms + ✓ tests/adapters/registry.test.ts (4 tests) 4ms + ✓ tests/communication-review.test.ts (10 tests) 408ms + ✓ tests/budget-preflight.test.ts (25 tests) 13ms + ✓ tests/preflight.test.ts (70 tests) 84ms + ✓ tests/communication-worker.test.ts (21 tests) 1947ms + ✓ tests/communication-preflight.test.ts (13 tests) 3159ms + ✓ managed CLI preflight > probes known CLIs with the same filtered credentials as execution 1425ms + ✓ managed CLI preflight > does not loosen ordinary wrapper preflight or cache a managed result for an ordinary step 1022ms + ✓ managed CLI preflight > still refuses missing executables and failed known-CLI probes 590ms + ✓ tests/devin.test.ts (8 tests) 3568ms + ✓ launches print mode with file input and cleans up after --version +Do the task 1244ms + ✓ launches print mode with file input and cleans up after fail 1285ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 970ms + ✓ tests/cli-probe.test.ts (18 tests) 10655ms + ✓ returns the absolute executable selected for a bare CLI name 1529ms + ✓ binds the canonical target of a probed executable symlink 882ms + ✓ executes a canonical shebang target through its authored alias in both probe drivers 918ms + ✓ normalizes a relative executable returned by PATH lookup 323ms + ✓ keeps synchronous and asynchronous classification equal: success 769ms + ✓ keeps synchronous and asynchronous classification equal: model denied 839ms + ✓ keeps synchronous and asynchronous classification equal: auth denied 645ms + ✓ keeps missing executables and unsupported identification fail closed 361ms + ✓ uses an explicit provider environment for every probe process 403ms + ✓ scopes delivered secrets in PATH lookup and provider probes for checked and authored steps 1060ms + ✓ reports timeout in both drivers while the async driver leaves the loop free 549ms + ✓ reports signal termination in both drivers 337ms + ✓ classifies a failed claude model probe from its own output: outdated CLI 375ms + ✓ classifies a failed claude model probe from its own output: usage limit 428ms + ✓ classifies a failed claude model probe from its own output: rate limit 447ms + ✓ classifies a failed claude model probe from its own output: unknown model 360ms + ✓ classifies a failed claude model probe from its own output: unrecognised output 424ms + ✓ tests/worker-cli.test.ts (31 tests) 37184ms + ✓ registered CLI model defaults > passes the same priced Claude default to the real provider invocation 2482ms + ✓ registered CLI model defaults > uses the explicitly supplied agent environment for the provider subprocess 1258ms + ✓ registered CLI model defaults > dispatches canonical generic bytes with the preflight-proved adapter identity 715ms + ✓ dash-leading task text > claude agent runs the task "--version" instead of parsing it as an option 1230ms + ✓ dash-leading task text > claude agent runs the task "-v explain the flag" instead of parsing it as an option 1071ms + ✓ dash-leading task text > codex agent runs the task "--version" instead of parsing it as an option 1080ms + ✓ dash-leading task text > codex agent runs the task "-v explain the flag" instead of parsing it as an option 833ms + ✓ direct transport lifecycle evidence > classifies only the exact Codex stdin lifecycle signature as retryable 557ms + ✓ direct transport lifecycle evidence > records a signal close separately from an ordinary nonzero exit 1337ms + ✓ direct transport lifecycle evidence > records a spawn error code without treating a missing executable as transient 334ms + ✓ direct transport lifecycle evidence > journals classified lifecycle evidence and reports crashed instead of generic worker_error 650ms + ✓ step discovery environment > names the run, step, attempt and an absolute data dir for a direct agent spawn 652ms + ✓ step discovery environment > exports none of the four without a data dir, even when the worker inherited them 497ms + ✓ wrapper discovery environment > sets the four names from the dispatch and still refuses ambient values and other secrets 482ms + ✓ wrapper discovery environment > exports none of the four to a wrapper without a data dir, even when the worker inherited them 441ms + ✓ custom wrapper execution identity > passes an explicit safe environment at identification and execution 496ms + ✓ custom wrapper execution identity > refuses a wrapper symlink retarget before delivering private values 643ms + ✓ custom wrapper execution identity > bounds wrapper execution after acknowledgement 525ms + ✓ custom wrapper execution identity > bounds captured wrapper output 616ms + ✓ custom wrapper execution identity > refuses a duplicate execute protocol frame 702ms + ✓ custom wrapper execution bounds are reader-owned > resolves when a conforming wrapper leaks a stdio pipe to a background helper 1225ms + ✓ custom wrapper execution bounds are reader-owned > resolves when the leaked helper inherits stderr only 791ms + ✓ custom wrapper execution bounds are reader-owned > resolves when a wrapper leaks a stdio pipe and exits before identifying 3328ms + ✓ custom wrapper execution bounds are reader-owned > journals a completionReason at the default bound when a wrapper leaks a stdio pipe 12025ms + ✓ custom wrapper execution bounds are reader-owned > accepts an execute token and an over-8KiB payload flushed in one write 438ms + ✓ custom wrapper execution bounds are reader-owned > accepts the same over-8KiB payload whether or not it coalesces with the execute token 1405ms + ✓ custom wrapper execution bounds are reader-owned > still bounds an un-terminated handshake buffer and names the bound 469ms + ✓ delivers the journaled memory pack to the real wrapper and excludes its charge from completion usage 443ms + + Test Files 11 passed (11) + Tests 226 passed (226) + Start at 11:45:13 + Duration 38.64s (transform 1.95s, setup 363ms, collect 8.72s, tests 57.04s, environment 1ms, prepare 719ms) +``` + +```sh +npm run typecheck +``` + +```text + +> @relayflows/sdk@2.0.55 typecheck +> tsc --noEmit && tsc -p tsconfig.type-tests.json +``` + +```sh +npm run typecheck:tests +``` + +```text + +> @relayflows/sdk@2.0.55 typecheck:tests +> tsc -p tsconfig.tests.json +``` + +```sh +npm run build +``` + +```text + +> @relayflows/sdk@2.0.55 build +> tsc && node scripts/make-cli-executable.mjs +``` + +From the repository root (Python 3.11+). Existing interactive credentials are read only to populate a private probe home; neither the key nor provider account output is printed. + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp /opt/homebrew/bin/python3.14 evidence/devin-harness/probe-cli.py --cli /Volumes/T7/Projects/AgentWorkforce/artifacts/devin-harness-20261102/cli/bin/devin --credentials /Users/khaliqgant/.local/share/devin/credentials.toml +``` + +```text +devin 3000.11.234 (92c83011d113) +none: models exit=1; not logged in +dummy_env: models exit=1; not logged in +dummy_file: models exit=1; invalid api key +existing_login_file: models exit=0; catalog received +headless exit=0; marker received=True +``` + +The compiled `runAgentCli` was also called with the pinned binary, `cliIdentity: devin`, a 60-second timeout, and the key in its private process environment. Exact Node command: + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp node --input-type=module <<'JS' +import {readFileSync, mkdtempSync, rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {runAgentCli} from './dist/worker-cli.js'; +const login=readFileSync('/Users/khaliqgant/.local/share/devin/credentials.toml','utf8'); +const key=JSON.parse(login.match(/^windsurf_api_key\s*=\s*(".*")$/m)[1]); +const cwd=mkdtempSync(join(tmpdir(),'devin-live-worker-')); +try { + const result=await runAgentCli('/Volumes/T7/Projects/AgentWorkforce/artifacts/devin-harness-20261102/cli/bin/devin', + 'Reply with exactly RELAYFLOWS_DEVIN_WORKER_READY and nothing else. Do not call tools.',undefined,undefined, + undefined,undefined,'agent',undefined,cwd,'direct',undefined, + {PATH:process.env.PATH,HOME:process.env.HOME,TMPDIR:process.env.TMPDIR,DEVIN_API_KEY:key},'devin',60000); + console.log(JSON.stringify({exit_code:result.exit_code,marker:result.stdout_tail.trim(),tokens_reported:result.tokens_input!==undefined})); + if(result.exit_code!==0||result.stdout_tail.trim()!=='RELAYFLOWS_DEVIN_WORKER_READY')process.exitCode=1; +}finally{rmSync(cwd,{recursive:true,force:true});} +JS +``` + +```text +{"exit_code":0,"marker":"RELAYFLOWS_DEVIN_WORKER_READY","tokens_reported":false} +``` + +Mutation check: removed exactly `if (name === 'devin') return ADAPTERS.devin;` from `src/adapters/index.ts`, ran the command below, restored the original file bytes in `finally`, then reran the same command. The two launch cases fail without adapter selection and pass after restoration. + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp node node_modules/vitest/vitest.mjs run tests/devin.test.ts -t "launches print mode" +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ❯ tests/devin.test.ts (8 tests | 2 failed | 6 skipped) 604ms + × launches print mode with file input and cleans up after --version +Do the task 346ms + → expected null to be +0 // Object.is equality + × launches print mode with file input and cleans up after fail 257ms + → expected null to be 7 // Object.is equality + +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL tests/devin.test.ts > launches print mode with file input and cleans up after --version +Do the task +AssertionError: expected null to be +0 // Object.is equality + +- Expected: +0 + ++ Received: +null + + ❯ tests/devin.test.ts:87:28 + 85| const result = await runAgentCli(f.cli, task, undefined, 'gpt-5.6-so… + 86| 'agent', undefined, f.cwd, 'direct', undefined, f.env); + 87| expect(result.exit_code).toBe(task === 'fail' ? 7 : 0); + | ^ + 88| expect(result.tokens_input).toBeUndefined(); + 89| expect(result.stdout_tail).not.toContain('devin-test-secret'); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯ + + FAIL tests/devin.test.ts > launches print mode with file input and cleans up after fail +AssertionError: expected null to be 7 // Object.is equality + +- Expected: +7 + ++ Received: +null + + ❯ tests/devin.test.ts:87:28 + 85| const result = await runAgentCli(f.cli, task, undefined, 'gpt-5.6-so… + 86| 'agent', undefined, f.cwd, 'direct', undefined, f.env); + 87| expect(result.exit_code).toBe(task === 'fail' ? 7 : 0); + | ^ + 88| expect(result.tokens_input).toBeUndefined(); + 89| expect(result.stdout_tail).not.toContain('devin-test-secret'); + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯ + + Test Files 1 failed (1) + Tests 2 failed | 6 skipped (8) + Start at 11:49:35 + Duration 2.31s (transform 636ms, setup 15ms, collect 1.45s, tests 604ms, environment 0ms, prepare 62ms) +``` + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp node node_modules/vitest/vitest.mjs run tests/devin.test.ts -t "launches print mode" +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/devin.test.ts (8 tests | 6 skipped) 562ms + + Test Files 1 passed (1) + Tests 2 passed | 6 skipped (8) + Start at 11:49:38 + Duration 1.47s (transform 346ms, setup 9ms, collect 684ms, tests 562ms, environment 0ms, prepare 36ms) +``` + +Linux x64 binary probes (remote `linuyc`, pinned archive checksum verified before extraction). [linux-probe-run.original.txt](linux-probe-run.original.txt) preserves the exact original runner and embedded probe source that produced this output. It is historical evidence; [probe-linux.py](probe-linux.py) is the current readable reproducer. The current reproducer has not been rerun on Linux in this session: + +```sh +tailscale ssh khaliqgant@linuyc 'python3 -' < /Users/khaliqgant/.cache/devin-harness/linux-probe-run.py +``` + +```text +Linux x64 bundle SHA-256 verified +devin 3000.11.234 (92c83011d113) +none: models exit=1; not logged in +dummy_env: models exit=1; not logged in +dummy_file: models exit=1; invalid api key +``` + +The probe implementation is [probe-cli.py](probe-cli.py). The installer/non-root image evidence is in the companion Cloud PR. A full hosted Cloud flow was not launched; this is CLI/runtime and image-install evidence. Independent Codex review reported no remaining findings on the working diff after fixes. + +Follow-up: pin the live harness test and probe to exactly 3000.11.234. The model-probe fixture now verifies exact arguments, the staged credential and rejection paths. The actual workspace secret value/type has not been inspected; the successful live test uses an existing CLI-login token. + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp /opt/homebrew/bin/python3.14 - <<'PY' +import os,pathlib,subprocess,tomllib +key=tomllib.loads((pathlib.Path.home()/'.local/share/devin/credentials.toml').read_text())['windsurf_api_key'] +env=dict(os.environ,DEVIN_API_KEY=key,RELAYFLOWS_REAL_DEVIN_CLI='/Volumes/T7/Projects/AgentWorkforce/artifacts/devin-harness-20261102/cli/bin/devin') +r=subprocess.run(['node','node_modules/vitest/vitest.mjs','run','tests/real-devin-adapter.test.ts','tests/devin.test.ts'],env=env) +raise SystemExit(r.returncode) +PY +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/devin.test.ts (9 tests) 2093ms + ✓ launches print mode with file input and cleans up after --version +Do the task 393ms + ✓ launches print mode with file input and cleans up after fail 522ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 518ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 628ms + ✓ tests/real-devin-adapter.test.ts (1 test) 5507ms + ✓ runs the pinned Devin CLI through the real agent worker 5506ms + + Test Files 2 passed (2) + Tests 10 passed (10) + Start at 11:59:07 + Duration 5.78s (transform 323ms, setup 20ms, collect 911ms, tests 7.60s, environment 0ms, prepare 99ms) +``` + +From the repository root: + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp /opt/homebrew/bin/python3.14 evidence/devin-harness/probe-cli.py --cli /Volumes/T7/Projects/AgentWorkforce/artifacts/devin-harness-20261102/cli/bin/devin +``` + +```text +devin 3000.11.234 (92c83011d113) +none: models exit=1; not logged in +dummy_env: models exit=1; not logged in +dummy_file: models exit=1; invalid api key +``` + +Authenticated compiled-worker and headless success evidence is macOS only. Linux evidence covers binary authentication rejection and non-root image installation; it does not claim a successful authenticated Linux worker call. + +Review follow-up: blank keys now surface a named preflight diagnostic; surrounding key whitespace is normalized before staging and redaction. The standalone authenticated marker probe now uses `auto` permissions and explicit nonzero failure checks that survive Python `-O`. + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp npx vitest run tests/devin.test.ts tests/cli-probe.test.ts tests/preflight.test.ts && npm run typecheck && npm run typecheck:tests +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/preflight.test.ts (70 tests) 45ms + ✓ tests/devin.test.ts (11 tests) 1599ms + ✓ checks provider auth with isolated credentials in both synchronous and asynchronous preflight 328ms + ✓ refuses an unavailable model and missing model-probe credentials in both preflight drivers 601ms + ✓ tests/cli-probe.test.ts (18 tests) 5887ms + ✓ executes a canonical shebang target through its authored alias in both probe drivers 384ms + ✓ keeps synchronous and asynchronous classification equal: success 329ms + ✓ keeps synchronous and asynchronous classification equal: auth denied 326ms + ✓ scopes delivered secrets in PATH lookup and provider probes for checked and authored steps 831ms + ✓ reports timeout in both drivers while the async driver leaves the loop free 548ms + ✓ classifies a failed claude model probe from its own output: usage limit 452ms + ✓ classifies a failed claude model probe from its own output: rate limit 318ms + ✓ classifies a failed claude model probe from its own output: unknown model 300ms + ✓ classifies a failed claude model probe from its own output: unrecognised output 437ms + + Test Files 3 passed (3) + Tests 99 passed (99) + Start at 12:06:06 + Duration 7.54s (transform 1.29s, setup 43ms, collect 3.62s, tests 7.53s, environment 0ms, prepare 170ms) +``` + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp npx vitest run tests/worker-cli.test.ts +``` + +```text + + RUN v2.1.9 /Volumes/T7/Projects/AgentWorkforce/worktrees/flows/devin-harness-20261102/packages/sdk + + ✓ tests/worker-cli.test.ts (31 tests) 33153ms + ✓ registered CLI model defaults > passes the same priced Claude default to the real provider invocation 1323ms + ✓ registered CLI model defaults > uses the explicitly supplied agent environment for the provider subprocess 588ms + ✓ registered CLI model defaults > dispatches canonical generic bytes with the preflight-proved adapter identity 679ms + ✓ dash-leading task text > claude agent runs the task "--version" instead of parsing it as an option 626ms + ✓ dash-leading task text > claude agent runs the task "-v explain the flag" instead of parsing it as an option 475ms + ✓ dash-leading task text > codex agent runs the task "--version" instead of parsing it as an option 553ms + ✓ dash-leading task text > codex agent runs the task "-v explain the flag" instead of parsing it as an option 518ms + ✓ direct transport lifecycle evidence > classifies only the exact Codex stdin lifecycle signature as retryable 585ms + ✓ direct transport lifecycle evidence > records a signal close separately from an ordinary nonzero exit 1108ms + ✓ direct transport lifecycle evidence > journals classified lifecycle evidence and reports crashed instead of generic worker_error 646ms + ✓ step discovery environment > names the run, step, attempt and an absolute data dir for a direct agent spawn 676ms + ✓ step discovery environment > exports none of the four without a data dir, even when the worker inherited them 457ms + ✓ wrapper discovery environment > sets the four names from the dispatch and still refuses ambient values and other secrets 571ms + ✓ wrapper discovery environment > exports none of the four to a wrapper without a data dir, even when the worker inherited them 474ms + ✓ custom wrapper execution identity > passes an explicit safe environment at identification and execution 558ms + ✓ custom wrapper execution identity > refuses a wrapper symlink retarget before delivering private values 562ms + ✓ custom wrapper execution identity > bounds wrapper execution after acknowledgement 590ms + ✓ custom wrapper execution identity > bounds captured wrapper output 579ms + ✓ custom wrapper execution identity > refuses a duplicate execute protocol frame 558ms + ✓ custom wrapper execution bounds are reader-owned > resolves when a conforming wrapper leaks a stdio pipe to a background helper 819ms + ✓ custom wrapper execution bounds are reader-owned > resolves when the leaked helper inherits stderr only 845ms + ✓ custom wrapper execution bounds are reader-owned > resolves when a wrapper leaks a stdio pipe and exits before identifying 3297ms + ✓ custom wrapper execution bounds are reader-owned > journals a completionReason at the default bound when a wrapper leaks a stdio pipe 11611ms + ✓ custom wrapper execution bounds are reader-owned > accepts an execute token and an over-8KiB payload flushed in one write 945ms + ✓ custom wrapper execution bounds are reader-owned > accepts the same over-8KiB payload whether or not it coalesces with the execute token 1694ms + ✓ custom wrapper execution bounds are reader-owned > still bounds an un-terminated handshake buffer and names the bound 520ms + ✓ delivers the journaled memory pack to the real wrapper and excludes its charge from completion usage 529ms + + Test Files 1 passed (1) + Tests 31 passed (31) + Start at 12:07:13 + Duration 34.18s (transform 337ms, setup 9ms, collect 842ms, tests 33.15s, environment 0ms, prepare 49ms) +``` + +From the repository root: + +```sh +TMPDIR=/Users/khaliqgant/.cache/devin-harness/tmp /opt/homebrew/bin/python3.14 -O evidence/devin-harness/probe-cli.py --cli /Volumes/T7/Projects/AgentWorkforce/artifacts/devin-harness-20261102/cli/bin/devin --credentials /Users/khaliqgant/.local/share/devin/credentials.toml +``` + +```text +devin 3000.11.234 (92c83011d113) +none: models exit=1; not logged in +dummy_env: models exit=1; not logged in +dummy_file: models exit=1; invalid api key +existing_login_file: models exit=0; catalog received +headless exit=0; marker received=True +``` + +A deliberately broken CLI fixture that reports the pinned version but returns a successful model catalog while logged out is still rejected under optimized Python: + +```sh +/opt/homebrew/bin/python3.14 - <<'PY' +from pathlib import Path +import subprocess +fake=Path('/Users/khaliqgant/.cache/devin-harness/fake-devin') +fake.write_text('#!/bin/sh\nif [ "$1" = --version ]; then echo "devin 3000.11.234 (fixture)"; fi\nexit 0\n') +fake.chmod(0o755) +result=subprocess.run(['/opt/homebrew/bin/python3.14','-O','evidence/devin-harness/probe-cli.py','--cli',str(fake)],text=True,capture_output=True) +print(result.stdout,end='') +print(result.stderr,end='') +print('exit='+str(result.returncode)) +if result.returncode!=1:raise SystemExit('Expected the broken fixture to fail') +PY +``` + +```text +devin 3000.11.234 (fixture) +none: models exit=0; catalog received +none: unexpected authentication behavior +exit=1 +``` + +The committed historical runner is byte-identical to the cache file used for the captured Linux run: + +```sh +shasum -a 256 evidence/devin-harness/linux-probe-run.original.txt /Users/khaliqgant/.cache/devin-harness/linux-probe-run.py +``` + +```text +888a9b9f3c66193d313a79677a20cd63929dc27a35d49b5535e6cc5373440449 evidence/devin-harness/linux-probe-run.original.txt +888a9b9f3c66193d313a79677a20cd63929dc27a35d49b5535e6cc5373440449 /Users/khaliqgant/.cache/devin-harness/linux-probe-run.py +``` + +Hosted-land credential guidance and the auth-error regression follow-up are recorded in [land-credential-followup.md](land-credential-followup.md). diff --git a/packages/sdk/src/adapters/base.ts b/packages/sdk/src/adapters/base.ts index e2d6d8efd..0c1b86c6e 100644 --- a/packages/sdk/src/adapters/base.ts +++ b/packages/sdk/src/adapters/base.ts @@ -27,6 +27,8 @@ export function promptOperand(text: string): [separator: '--', text: string] { export interface CliInvocation { args: string[]; timeoutMs: number; + /** Materialized privately at launch for CLIs whose task input is a file. */ + promptFile?: string; /** Set only for wrapper readiness probes; raw providers receive a model flag. */ modelEnv?: string; } diff --git a/packages/sdk/src/adapters/devin.ts b/packages/sdk/src/adapters/devin.ts new file mode 100644 index 000000000..399c52c32 --- /dev/null +++ b/packages/sdk/src/adapters/devin.ts @@ -0,0 +1,22 @@ +import type { HeadlessAdapter } from './base.js'; + +const flags = ['-p', '--respect-workspace-trust', 'false']; + +/** Devin print mode returns plain text; it has no JSON-output switch. */ +export const devinAdapter: HeadlessAdapter = { + kind: 'devin', + buildIdentification: () => ({ invocation: { args: ['auth', 'status', '--help'], timeoutMs: 10_000 } }), + // `auth status` exits zero even when logged out. Listing models actually + // contacts the provider and refuses missing or invalid credentials. + buildAuthProbe: () => ({ args: ['models', 'list', '--format', 'json'], timeoutMs: 30_000 }), + buildModelReadinessProbe: model => ({ + args: [...flags, '--model', model, '--', 'Reply with exactly RELAYFLOWS_MODEL_READY and nothing else.'], + timeoutMs: 60_000, + }), + buildAgentInvocation: (instruction, model) => ({ + args: [...flags, '--permission-mode', 'dangerous', ...(model === undefined ? [] : ['--model', model])], + promptFile: instruction, + timeoutMs: 0, + }), + buildLlmInvocation: () => { throw new Error('Devin supports agent steps only; use a model provider for llm steps.'); }, +}; diff --git a/packages/sdk/src/adapters/index.ts b/packages/sdk/src/adapters/index.ts index 5258dec21..aa7d8b200 100644 --- a/packages/sdk/src/adapters/index.ts +++ b/packages/sdk/src/adapters/index.ts @@ -2,15 +2,17 @@ import { basename } from 'node:path'; import { claudeAdapter } from './claude.js'; import { codexAdapter } from './codex.js'; +import { devinAdapter } from './devin.js'; import { wrapperAdapter } from './wrapper.js'; import type { HeadlessAdapter } from './base.js'; -export type CliAdapterKind = 'claude' | 'codex' | 'relayflows-wrapper-v1'; +export type CliAdapterKind = 'claude' | 'codex' | 'devin' | 'relayflows-wrapper-v1'; /** The registered adapter set. Adding a CLI is adding one file + one entry. */ const ADAPTERS: Record = { claude: claudeAdapter, codex: codexAdapter, + devin: devinAdapter, 'relayflows-wrapper-v1': wrapperAdapter, }; @@ -19,6 +21,7 @@ export function resolveAdapter(executable: string): HeadlessAdapter { const name = basename(executable).replace(/\.exe$/i, ''); if (name === 'claude') return ADAPTERS.claude; if (name === 'codex') return ADAPTERS.codex; + if (name === 'devin') return ADAPTERS.devin; return ADAPTERS['relayflows-wrapper-v1']; } @@ -32,5 +35,5 @@ export function registeredAdapters(): Readonly(sequence: Generator): T { while (!next.done) { const request = next.value; const pinned = pinCliAliasSync(request.executable, request.argv0 ?? basename(request.executable)); + let prepared: ReturnType | undefined; const result = (() => { try { - return spawnSync(pinned.executable, request.invocation.args, { - ...probeOptions(request), + prepared = prepareProbe(request); + return spawnSync(pinned.executable, prepared.args, { + ...probeOptions({ ...request, environment: prepared.env }), // Preserve the old synchronous probe contract: provider CLIs must not // inherit a readable stdin that can block auth/identify probes. stdio: ['ignore', 'pipe', 'pipe'], }); } finally { + prepared?.close(); pinned.release(); } })(); @@ -69,9 +74,12 @@ function probeOptions({ argv0, directory, invocation, environment }: ProbeReques async function runProbeAsync(request: ProbeRequest): Promise { const pinned = await pinCliAlias(request.executable, request.argv0 ?? basename(request.executable)); + let prepared: ReturnType | undefined; try { + prepared = prepareProbe(request); + const current = prepared; return await new Promise((resolve, reject) => { - const child = execFile(pinned.executable, request.invocation.args, probeOptions(request), + const child = execFile(pinned.executable, current.args, probeOptions({ ...request, environment: current.env }), (error, stdout, stderr) => { // Numeric exit codes are probe results; launch, timeout, signal and buffer // errors are failures to collect a fact, just as in the synchronous driver. @@ -86,6 +94,7 @@ async function runProbeAsync(request: ProbeRequest): Promise { child.stdin?.end(); }); } finally { + prepared?.close(); await pinned.release(); } } @@ -133,12 +142,16 @@ function* probeSequence( const auth = authenticationProbe(kind); const authCommand = displayInvocation(cli, auth); if (model === undefined) { + const authProbe = yield probe(auth); + const authenticated = authProbe.status === 0; return { exists: true, supported: true, - authenticated: (yield probe(auth)).status === 0, + authenticated, executable, authCommand, + ...(authenticated ? {} : { authExitCode: authProbe.status, + authFailureDetail: redactProbeOutput(`${authProbe.stderr}${authProbe.stdout}`, sourceEnvironment).trim().slice(0, 500) }), }; } @@ -168,7 +181,7 @@ function* probeSequence( // because Claude Code prints the provider's API error there and its own // catalog warnings on stderr. const failure = classifyModelProbeFailure(kind, `${scopedProbe.stdout}\n${scopedProbe.stderr}`); - const modelDetail = redactProbeOutput(scopedProbe.stdout.trim() || scopedProbe.stderr.trim()).slice(0, 500); + const modelDetail = redactProbeOutput(scopedProbe.stdout.trim() || scopedProbe.stderr.trim(), sourceEnvironment).slice(0, 500); return { exists: true, supported: true, @@ -187,7 +200,7 @@ function* probeSequence( : { authExitCode: authProbe.status, authFailureDetail: redactProbeOutput( - `${authProbe.stderr}${authProbe.stdout}`, + `${authProbe.stderr}${authProbe.stdout}`, sourceEnvironment, ).trim().slice(0, 500), }), }; @@ -201,11 +214,42 @@ function* probeSequence( * say WHY a probe failed, which survives redaction; leaking an identity into a * refusal message that gets pasted into issues does not. */ -function redactProbeOutput(text: string): string { - return text - .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '') - .replace(/\b(sk|pk|oat|rt)[-_][A-Za-z0-9._-]{8,}/gi, '') - .replace(/\b[A-Fa-f0-9]{32,}\b/g, ''); +function redactProbeOutput(text: string, environment: NodeJS.ProcessEnv): string { + const key = environment.DEVIN_API_KEY?.trim(); + const normalized = { ...environment, ...(key === undefined ? {} : { DEVIN_API_KEY: key }) }; + // Preserve the shared redactor's known-value, header and cookie handling. + const redacted = redactText(text, normalized); + // One byte per diagnostic character bounds auxiliary memory even when a + // one-character credential matches the entire probe buffer. No span lists. + const covered = new Uint8Array(redacted.length); + const replacements = ['', '', '', '', '[redacted:DEVIN_API_KEY]']; + for (const [pattern, tag] of [ + [/(? { @@ -245,3 +289,13 @@ function classifySpawnFailure( } return signal === null ? undefined : new CliProbeError(`signal:${signal}`); } + +function prepareProbe(request: ProbeRequest) { + if (cliAdapterKind(request.argv0 ?? request.executable) === 'devin' + && request.environment.DEVIN_API_KEY !== undefined && !request.environment.DEVIN_API_KEY.trim()) { + throw new CliProbeError('devin_api_key_empty'); + } + return cliAdapterKind(request.argv0 ?? request.executable) === 'devin' + ? prepareDevinRuntime(request.environment, request.invocation) + : { args: request.invocation.args, env: request.environment, close() {} }; +} diff --git a/packages/sdk/src/communication/environment.ts b/packages/sdk/src/communication/environment.ts index 53aff3403..7a65d450d 100644 --- a/packages/sdk/src/communication/environment.ts +++ b/packages/sdk/src/communication/environment.ts @@ -25,6 +25,7 @@ const providerNames: Readonly> = { // AgentWorkforce/cloud#4026's house-provider run contract gives Grok an // isolated home plus an xAI-compatible base URL. These remain Grok-scoped. grok: ['XAI_API_KEY', 'GROK_XAI_API_BASE_URL', 'GROK_HOME'], + devin: ['DEVIN_API_KEY', 'DEVIN_MODEL'], ...Object.fromEntries(['opencode', 'aider', 'goose', 'pi', 'deepagents'].map(cli => [cli, multiProvider])), }; /** @internal Names-only test seam; credential lists remain private. */ diff --git a/packages/sdk/src/communication/pty.ts b/packages/sdk/src/communication/pty.ts index b19d6a51f..88fb31075 100644 --- a/packages/sdk/src/communication/pty.ts +++ b/packages/sdk/src/communication/pty.ts @@ -1,5 +1,6 @@ import { mkdir, mkdtemp, rm, symlink } from 'node:fs/promises'; import { basename, join } from 'node:path'; +import { prepareDevinRuntime } from '../devin-runtime.js'; import { agentEnvironment } from './environment.js'; import { resolveCliModel } from '../cli-adapter.js'; import type { RelayBroker } from './relay.js'; @@ -19,6 +20,9 @@ export async function spawnFlowPty(broker: Pick, option const argv0 = basename(identity); let command = options.cli; let link: string | undefined; + const environment = agentEnvironment(identity, options.environment ?? process.env, + options.secrets, options.scopeSecrets ?? true); + const prepared = argv0.replace(/\.exe$/i, '') === 'devin' ? prepareDevinRuntime(environment) : undefined; try { if (basename(command) !== argv0) { const root = join(options.dataDir, 'communication'); @@ -32,15 +36,15 @@ export async function spawnFlowPty(broker: Pick, option ...(options.team === undefined ? {} : { team: options.team }), model: resolveCliModel(identity, options.model), cwd: options.cwd, harnessConfig: { runtime: 'pty', command: shellQuote(command), args: [], cwd: options.cwd, - env: { ...agentEnvironment(identity, options.environment ?? process.env, - options.secrets, options.scopeSecrets ?? true), + env: { ...(prepared?.env ?? environment), RELAYFLOW_COMMUNICATION_SOCKET: options.socket, RELAYFLOW_COMMUNICATION_TOKEN: options.token, ...(options.metadata === undefined ? {} : { RELAYFLOW_RUN_ID: options.metadata.runId, RELAYFLOW_FLOW_NAME: options.metadata.flow, RELAYFLOW_STEP_NAME: options.metadata.step, }) }, delivery: { mode: 'pty-injection', format: 'relay-block' } } }); - return { handle, close: async () => { if (link) await rm(link, { recursive: true, force: true }); } }; + return { handle, close: async () => { prepared?.close(); if (link) await rm(link, { recursive: true, force: true }); } }; } catch (error) { + prepared?.close(); if (link) await rm(link, { recursive: true, force: true }); throw error; } diff --git a/packages/sdk/src/communication/skills.ts b/packages/sdk/src/communication/skills.ts index bc28a4ccb..c115e4d07 100644 --- a/packages/sdk/src/communication/skills.ts +++ b/packages/sdk/src/communication/skills.ts @@ -7,8 +7,9 @@ const execute = promisify(execFile); export async function installBrokerSkills(skills: string[], cli: string, cwd: string, signal: AbortSignal): Promise { if (!skills.length) return; const identity = basename(cli).replace(/\.exe$/i, ''); + // Devin reads .windsurf/skills, which the canonical skills installer supports. const harness = ({ claude: 'claude-code', codex: 'codex', gemini: 'gemini-cli', - 'cursor-agent': 'cursor', opencode: 'opencode' } as Record)[identity]; + 'cursor-agent': 'cursor', opencode: 'opencode', devin: 'windsurf' } as Record)[identity]; if (!harness) throw new Error(`Skill installation is unsupported for broker CLI ${identity}`); await execute('npx', ['--yes', 'skills', 'add', 'https://github.com/AgentWorkforce/skills', '--skill', ...skills, '--agent', harness, '--yes', '--copy'], diff --git a/packages/sdk/src/devin-runtime.ts b/packages/sdk/src/devin-runtime.ts new file mode 100644 index 000000000..4c4258bb8 --- /dev/null +++ b/packages/sdk/src/devin-runtime.ts @@ -0,0 +1,33 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { CliInvocation } from './adapters/base.js'; + +/** Private attempt/probe state, never the user's interactive Devin login. */ +export function prepareDevinRuntime(environment: NodeJS.ProcessEnv, invocation?: CliInvocation) { + let root: string | undefined; + const env = { ...environment }; + const args = [...(invocation?.args ?? [])]; + const directory = () => root ??= mkdtempSync(join(environment.TMPDIR ?? tmpdir(), 'relayflows-devin-')); + const close = () => { if (root !== undefined) rmSync(root, { recursive: true, force: true }); }; + try { + if (env.DEVIN_API_KEY !== undefined) { + const key = env.DEVIN_API_KEY.trim(); + if (!key) throw new Error('DEVIN_API_KEY must not be empty'); + const data = join(directory(), 'data'); + mkdirSync(join(data, 'devin'), { recursive: true, mode: 0o700 }); + writeFileSync(join(data, 'devin', 'credentials.toml'), + `windsurf_api_key = ${JSON.stringify(key)}\n`, { mode: 0o600 }); + env.XDG_DATA_HOME = data; + env.XDG_CONFIG_HOME = join(directory(), 'config'); + env.XDG_CACHE_HOME = join(directory(), 'cache'); + delete env.DEVIN_API_KEY; + } + if (invocation?.promptFile !== undefined) { + const path = join(directory(), 'prompt.txt'); + writeFileSync(path, invocation.promptFile, { mode: 0o600 }); + args.push('--prompt-file', path); + } + return { env, args, close }; + } catch (error) { close(); throw error; } +} diff --git a/packages/sdk/src/preflight.ts b/packages/sdk/src/preflight.ts index d9d70cb48..01600ee88 100644 --- a/packages/sdk/src/preflight.ts +++ b/packages/sdk/src/preflight.ts @@ -11,7 +11,7 @@ import type { TriggerSource } from '@relayflows/surface'; import { acceptsAnyOutput, inspectStepGate, type StepGateInspection } from './gate-contract.js'; import { compileSpec, CompileError } from './compile.js'; import { helperCall } from './yaml-helpers.js'; -import { resolveCliModelSelection, type CliModelSource } from './cli-adapter.js'; +import { cliAdapterKind, resolveCliModelSelection, type CliModelSource } from './cli-adapter.js'; import { isNamedGate, NAMED_GATE_FAILURE_KINDS, type NamedGateFailureKind } from './named-gates.js'; import { namedGateScanCoverageDiagnostics } from './named-gate-preflight.js'; import { compileScopes, type ScopeInput, type MountRegistry } from './scope-compiler.js'; @@ -65,6 +65,7 @@ export interface CliProbeResult { export type CliProbeFailureDetail = | 'spawn_failed' + | 'devin_api_key_empty' | `timeout:${number}ms` | `signal:${string}`; @@ -286,6 +287,10 @@ export function resolvePreflight(flow: unknown, options: ResolutionOptions): Pre message: unresolvedCliMessage(step.id, options), }); } else { + if (step.type === 'llm' && cliAdapterKind(resolution.cli) === 'devin') { + cliResolutionDiagnostics.push({ severity: 'refusal', kind: 'cli_unsupported', stepId: step.id, + cli: resolution.cli, message: `Step "${step.id}" uses Devin for an llm step; Devin supports agent steps only.` }); + } resolutions.push(resolution); resolutionByStep.set(step.id, resolution); } @@ -594,13 +599,16 @@ function probeResolvedCli( kind: 'cli_unsupported', stepId: resolution.stepId, cli: resolution.cli, - message: `Step "${resolution.stepId}" declares CLI "${resolution.cli}", but it is neither a supported raw Claude/Codex executable nor a conforming Relayflows wrapper; custom wrappers must identify with the relayflows-agent-cli-v1 contract.`, + message: `Step "${resolution.stepId}" declares CLI "${resolution.cli}", but it is neither a supported raw Claude/Codex/Devin executable nor a conforming Relayflows wrapper; custom wrappers must identify with the relayflows-agent-cli-v1 contract.`, }); } else if (managed && result.authenticated === 'unverified') { diagnostics.push({ severity: 'warning', kind: 'managed_cli_unverified', stepId: resolution.stepId, message: `Step "${resolution.stepId}" uses Relay's interactive CLI transport. The executable exists, but authentication${resolution.model ? ' and access to model "' + resolution.model + '"' : ''} could not be verified before startup. The managed session must execute its task and report completion; startup or task failure fails the step.` }); } else if (result.authenticated !== true) { const command = result.authCommand ?? `${resolution.cli} auth status`; + const loginHint = cliAdapterKind(resolution.cli) === 'devin' + ? ' For hosted flows, set FLOW_DEVIN_API_KEY to a Devin CLI login token; local runs use DEVIN_API_KEY. A REST API key is a different credential.' + : ''; // Say what the probe reported. A refusal that names only the command turns // a transient provider rejection and a genuinely unauthenticated CLI into // the same message, and the difference decides whether retrying is @@ -616,7 +624,7 @@ function probeResolvedCli( kind: 'cli_unauthenticated', stepId: resolution.stepId, cli: resolution.cli, - message: `Step "${resolution.stepId}" declares CLI "${resolution.cli}", but "${command}" exited non-zero${exitCode}; authenticate it or repair that adapter's authentication probe.${detail}`, + message: `Step "${resolution.stepId}" declares CLI "${resolution.cli}", but "${command}" exited non-zero${exitCode}; authenticate it or repair that adapter's authentication probe.${detail}${loginHint}`, }); } else if (resolution.model !== undefined && result.modelAvailable !== true) { diagnostics.push(modelProbeRefusal(resolution as CliResolution & { model: string }, result)); @@ -668,6 +676,7 @@ function probeFailedMessage( ): string { const prefix = `Could not verify CLI "${resolution.cli}" for step "${resolution.stepId}"`; if (detail === undefined) return `${prefix}.`; + if (detail === 'devin_api_key_empty') return `${prefix}: DEVIN_API_KEY must contain a non-empty Devin CLI login token. For hosted flows, set FLOW_DEVIN_API_KEY.`; if (detail === 'spawn_failed') return `${prefix}: the probe process could not be started.`; if (detail.startsWith('signal:')) { return `${prefix}: the probe was terminated by signal "${detail.slice('signal:'.length)}".`; diff --git a/packages/sdk/src/step-secrets.ts b/packages/sdk/src/step-secrets.ts index f385389ca..8ca717085 100644 --- a/packages/sdk/src/step-secrets.ts +++ b/packages/sdk/src/step-secrets.ts @@ -47,6 +47,7 @@ const CLI_LOGIN: Record = { 'AWS_SESSION_TOKEN', 'AWS_REGION', 'AWS_DEFAULT_REGION', ], codex: ['CODEX_HOME', 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE', 'OPENROUTER_API_KEY'], + devin: ['DEVIN_API_KEY', 'DEVIN_MODEL'], 'relayflows-wrapper-v1': [], }; diff --git a/packages/sdk/src/worker-cli.ts b/packages/sdk/src/worker-cli.ts index f2b74a030..05e0ac044 100644 --- a/packages/sdk/src/worker-cli.ts +++ b/packages/sdk/src/worker-cli.ts @@ -45,6 +45,7 @@ import { type AgentTransport, } from './agent-relay-transport.js'; import { pinCliAlias } from './cli/pinned-cli-alias.js'; +import { prepareDevinRuntime } from './devin-runtime.js'; import { promptOperand } from './adapters/base.js'; export type { CliTransportCause, CliTransportEvidence, CliTransportPhase } from './cli-transport-evidence.js'; @@ -277,15 +278,22 @@ export async function runAgentCli( // The flags go before the `--` that ends the task operand (promptOperand): // after it they would reach the CLI as task text, not options. const args = [...invocation.args]; - args.splice(args.length - promptOperand('').length, 0, ...(kind === 'claude' ? ['--output-format', 'stream-json', '--verbose'] : ['--json'])); + if (kind !== 'devin') args.splice(args.length - promptOperand('').length, 0, ...(kind === 'claude' ? ['--output-format', 'stream-json', '--verbose'] : ['--json'])); const completion = kind === 'claude' ? claudeResultOutcome : undefined; // Retain the source values for output redaction even though the child // receives only its filtered environment. A provider can echo a value from // its prompt or fixture that was not granted as an environment variable. - const redactionEnvironment = { ...processEnvironment, ...env }; - return requirePricedUsage(decodeProviderResult(await spawnInvocation( - cli, { ...invocation, args }, env, signal, sidechannel, cwd, completion, argv0, kind, redactionEnvironment, - ), kind, redactionEnvironment), effectiveModel); + const redactionEnvironment = { ...processEnvironment, ...env, + ...(kind === 'devin' && env.DEVIN_API_KEY !== undefined ? { DEVIN_API_KEY: env.DEVIN_API_KEY.trim() } : {}) }; + const prepared = kind === 'devin' ? prepareDevinRuntime(env, { ...invocation, args }) : undefined; + try { + const result = await spawnInvocation(cli, + { ...invocation, args: prepared?.args ?? args }, prepared?.env ?? env, + signal, sidechannel, cwd, completion, argv0, kind, redactionEnvironment); + // Print mode has neither provider frames nor authoritative token counts. + return kind === 'devin' ? { ...result, stdout_tail: redactText(result.stdout_tail, redactionEnvironment) } + : requirePricedUsage(decodeProviderResult(result, kind, redactionEnvironment), effectiveModel); + } finally { prepared?.close(); } } } diff --git a/packages/sdk/tests/adapters/registry.test.ts b/packages/sdk/tests/adapters/registry.test.ts index 9de76d022..78f635329 100644 --- a/packages/sdk/tests/adapters/registry.test.ts +++ b/packages/sdk/tests/adapters/registry.test.ts @@ -14,9 +14,9 @@ import { } from '../../src/cli-adapter.js'; describe('adapters registry + cli-adapter parity', () => { - it('registers claude, codex, and the wrapper protocol', () => { + it('registers Claude, Codex, Devin, and the wrapper protocol', () => { const kinds = Object.keys(registeredAdapters()).sort(); - expect(kinds).toEqual(['claude', 'codex', 'relayflows-wrapper-v1']); + expect(kinds).toEqual(['claude', 'codex', 'devin', 'relayflows-wrapper-v1']); }); it('resolves by basename', () => { diff --git a/packages/sdk/tests/cli-probe.test.ts b/packages/sdk/tests/cli-probe.test.ts index b9115b748..fa60f3266 100644 --- a/packages/sdk/tests/cli-probe.test.ts +++ b/packages/sdk/tests/cli-probe.test.ts @@ -26,6 +26,18 @@ const identify = `if (process.argv[2] === '--relayflows-adapter-v1') { console.log('relayflows-agent-cli-v1'); process.exit(0); }`; +it.each([ + ['prefix-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-secretSuffix', 'prefix-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-secretSuffix'], +])('redacts whole non-Devin secrets and enclosing shapes: %s', async (key, diagnostic) => { + const { path, directory } = wrapper(identify + `console.error(${JSON.stringify(`Failure: ${diagnostic}`)}); process.exit(1);`); + const environment = { PATH: process.env.PATH, OPENAI_API_KEY: key }; + for (const probe of [probeCli, probeCliAsync]) { + const result = await probe(path, directory, undefined, undefined, environment); + expect(result.authenticated).toBe(false); + expect(result.authFailureDetail).toBe('Failure: [redacted:OPENAI_API_KEY]'); + } +}); + it('does not expose the removed authored readiness probe through the public CLI', async () => { const stdout: string[] = []; const stderr: string[] = []; diff --git a/packages/sdk/tests/communication-review.test.ts b/packages/sdk/tests/communication-review.test.ts index 30db94ac6..798babe30 100644 --- a/packages/sdk/tests/communication-review.test.ts +++ b/packages/sdk/tests/communication-review.test.ts @@ -98,23 +98,23 @@ it('legacy communication agents still strip delivered repository names', () => { it('communication CLIs keep only their own delivered login, never generic cloud credentials', () => { const source = { GEMINI_API_KEY: 'gemini-login', CURSOR_API_KEY: 'cursor-login', - XAI_API_KEY: 'grok-login', FACTORY_API_KEY: 'droid-login', + DEVIN_API_KEY: 'devin-login', XAI_API_KEY: 'grok-login', FACTORY_API_KEY: 'droid-login', GOOGLE_API_KEY: 'application-google-key', GOOGLE_APPLICATION_CREDENTIALS: '/tmp/application-service-account.json', AWS_ACCESS_KEY_ID: 'application-aws-key', GH_TOKEN: 'user-repository-secret', RELAY_SECRET_ENV_NAMES: JSON.stringify([ - 'GEMINI_API_KEY', 'CURSOR_API_KEY', 'XAI_API_KEY', 'FACTORY_API_KEY', + 'GEMINI_API_KEY', 'CURSOR_API_KEY', 'XAI_API_KEY', 'DEVIN_API_KEY', 'FACTORY_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_APPLICATION_CREDENTIALS', 'AWS_ACCESS_KEY_ID', 'GH_TOKEN', ]), }; for (const [cli, own] of [ ['gemini', 'GEMINI_API_KEY'], ['cursor-agent', 'CURSOR_API_KEY'], - ['grok', 'XAI_API_KEY'], ['droid', 'FACTORY_API_KEY'], + ['grok', 'XAI_API_KEY'], ['devin', 'DEVIN_API_KEY'], ['droid', 'FACTORY_API_KEY'], ] as const) { for (const scopeSecrets of [true, false]) { const env = agentEnvironment(cli, source, undefined, scopeSecrets); expect(env[own]).toBe(source[own]); - for (const foreign of ['GEMINI_API_KEY', 'CURSOR_API_KEY', 'XAI_API_KEY', 'FACTORY_API_KEY']) { + for (const foreign of ['GEMINI_API_KEY', 'CURSOR_API_KEY', 'XAI_API_KEY', 'DEVIN_API_KEY', 'FACTORY_API_KEY']) { if (foreign !== own) expect(env).not.toHaveProperty(foreign); } for (const generic of ['GOOGLE_API_KEY', 'GOOGLE_APPLICATION_CREDENTIALS', 'AWS_ACCESS_KEY_ID', 'GH_TOKEN']) { @@ -157,7 +157,7 @@ it('passes provider-specific proxy routing only to Cursor and Grok children', () }; const cursorNames = ['CURSOR_API_KEY', 'CURSOR_API_ENDPOINT', 'CURSOR_API_BASE_URL']; const grokNames = ['XAI_API_KEY', 'GROK_XAI_API_BASE_URL', 'GROK_HOME']; - const providerClis = ['claude', 'codex', 'gemini', 'cursor-agent', 'droid', 'grok', + const providerClis = ['claude', 'codex', 'gemini', 'cursor-agent', 'droid', 'grok', 'devin', 'opencode', 'aider', 'goose', 'pi', 'deepagents']; expect([...providerEnvironmentCliNames()].sort()).toEqual([...providerClis].sort()); expect(agentEnvironment('cursor-agent', source)).toMatchObject({ diff --git a/packages/sdk/tests/communication-worker.test.ts b/packages/sdk/tests/communication-worker.test.ts index 555047a4d..8d69f5556 100644 --- a/packages/sdk/tests/communication-worker.test.ts +++ b/packages/sdk/tests/communication-worker.test.ts @@ -51,7 +51,7 @@ it('journals readiness failure and still releases all acquired resources', async expect(mocks.close).toHaveBeenCalledTimes(1); }); -it.each(['claude', 'codex', 'gemini', 'cursor-agent', 'droid', 'opencode', 'aider', 'goose', 'grok', 'pi', 'deepagents', '/opt/custom/tool'])('delegates %s launch and injection to Relay without Claude-only flags', async cli => { +it.each(['claude', 'codex', 'gemini', 'cursor-agent', 'droid', 'opencode', 'aider', 'goose', 'grok', 'devin', 'pi', 'deepagents', '/opt/custom/tool'])('delegates %s launch and injection to Relay without Claude-only flags', async cli => { const f = fixture(cli); await f.execute(); expect(mocks.spawn).toHaveBeenCalledWith(expect.objectContaining({ cli: cli.split('/').at(-1), diff --git a/packages/sdk/tests/devin.test.ts b/packages/sdk/tests/devin.test.ts new file mode 100644 index 000000000..5d6ac131f --- /dev/null +++ b/packages/sdk/tests/devin.test.ts @@ -0,0 +1,239 @@ +import { afterEach, expect, it } from 'vitest'; +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { prepareDevinRuntime } from '../src/devin-runtime.js'; +import { agentExecution, cliAdapterKind } from '../src/cli-adapter.js'; +import { agentStepEnvironment } from '../src/step-secrets.js'; +import { runAgentCli } from '../src/worker-cli.js'; +import { probeCli, probeCliAsync } from '../src/cli/cli-probe.js'; +import { preflight } from '../src/preflight.js'; + +const directories: string[] = []; +function directory() { const path = mkdtempSync(join(tmpdir(), 'devin-test-')); directories.push(path); return path; } +afterEach(() => { for (const path of directories.splice(0)) rmSync(path, { recursive: true, force: true }); }); + +it('isolates credentials and prompt files, escapes the key, and removes all private state', () => { + const source = { HOME: '/original', XDG_DATA_HOME: '/original/data', DEVIN_API_KEY: 'test-"key\\value' }; + const prepared = prepareDevinRuntime(source, agentExecution('devin', '--version\nTask')); + const credentials = join(prepared.env.XDG_DATA_HOME!, 'devin', 'credentials.toml'); + const prompt = prepared.args.at(-1)!; + expect(readFileSync(credentials, 'utf8')).toBe(`windsurf_api_key = ${JSON.stringify(source.DEVIN_API_KEY)}\n`); + expect(statSync(credentials).mode & 0o777).toBe(0o600); + expect(statSync(prompt).mode & 0o777).toBe(0o600); + expect(readFileSync(prompt, 'utf8')).toBe('--version\nTask'); + expect(prepared.env.HOME).toBe('/original'); + expect(prepared.env).not.toHaveProperty('DEVIN_API_KEY'); + expect(source.XDG_DATA_HOME).toBe('/original/data'); + prepared.close(); + expect(existsSync(credentials)).toBe(false); + expect(existsSync(prompt)).toBe(false); +}); + +it('preserves local interactive login when no API key is supplied and rejects an empty key', () => { + const local = prepareDevinRuntime({ XDG_DATA_HOME: '/local/data' }); + expect(local.env.XDG_DATA_HOME).toBe('/local/data'); local.close(); + expect(() => prepareDevinRuntime({ DEVIN_API_KEY: ' ' })).toThrow('must not be empty'); + const padded = prepareDevinRuntime({ DEVIN_API_KEY: ' cli-token\n' }); + expect(readFileSync(join(padded.env.XDG_DATA_HOME!, 'devin', 'credentials.toml'), 'utf8')) + .toBe('windsurf_api_key = "cli-token"\n'); + padded.close(); +}); + +it('gives only Devin its intrinsic delivered login', () => { + const source = { DEVIN_API_KEY: 'devin-login', OPENAI_API_KEY: 'openai-login', + RELAY_SECRET_ENV_NAMES: '["DEVIN_API_KEY","OPENAI_API_KEY"]' }; + expect(cliAdapterKind('/bin/devin.exe')).toBe('devin'); + expect(agentStepEnvironment(source, 'devin')).toEqual({ DEVIN_API_KEY: 'devin-login' }); + expect(agentStepEnvironment(source, 'codex')).toEqual({ OPENAI_API_KEY: 'openai-login' }); +}); + +it('refuses llm use before probing and warns about both unmetered ceilings for priced agent models', () => { + let probes = 0; + const options = { probes: { cli: () => { probes++; return { exists: true, authenticated: true }; }, + executor: () => true, command: () => true } }; + const refused = preflight({ version: '0.1.0', steps: [{ id: 'ask', type: 'llm', cli: 'devin', prompt: 'hello' }] }, options); + expect(refused.ok).toBe(false); expect(probes).toBe(0); + expect(refused.diagnostics).toContainEqual(expect.objectContaining({ kind: 'cli_unsupported' })); + for (const budget of ['$1/run', { tokens: 100 }, undefined]) { + const checked = preflight({ version: '0.1.0', budget, + steps: [{ id: 'work', type: 'agent', cli: 'devin', model: 'gpt-5.6-sol', instruction: 'work' }] }, options); + expect(checked.diagnostics).toContainEqual(expect.objectContaining({ + kind: 'budget_unmetered', message: expect.stringContaining('Token and dollar ceilings cannot bound its spend'), + })); + } +}); + +function fixture() { + const cwd = directory(); const cli = join(cwd, 'devin'); + writeFileSync(cli, `#!/usr/bin/env node +const fs = require('node:fs'); const path = require('node:path'); +const args = process.argv.slice(2); +if (JSON.stringify(args) === JSON.stringify(['auth', 'status', '--help'])) process.exit(0); +const credentials = path.join(process.env.XDG_DATA_HOME, 'devin', 'credentials.toml'); +const authenticated = fs.existsSync(credentials) + && fs.readFileSync(credentials, 'utf8') === 'windsurf_api_key = "devin-test-secret"\\n'; +if (args[0] === 'models') { + if (JSON.stringify(args) !== JSON.stringify(['models', 'list', '--format', 'json'])) process.exit(11); + if (process.env.PROBE_DIAGNOSTIC) console.error(process.env.PROBE_DIAGNOSTIC); + if (process.env.PROBE_LARGE_OUTPUT) fs.writeFileSync(2, 'x'.repeat(900_000) + '\\n'); + if (!authenticated && fs.existsSync(credentials)) console.error(fs.readFileSync(credentials, 'utf8')); + process.exit(authenticated ? 0 : 1); +} +if (args.includes('--json') || args.includes('--relayflows-identify')) process.exit(10); +if (!args.includes('--prompt-file')) { + const model = args[args.indexOf('--model') + 1]; + const expected = ['-p', '--respect-workspace-trust', 'false', '--model', model, '--', + 'Reply with exactly RELAYFLOWS_MODEL_READY and nothing else.']; + if (!authenticated || JSON.stringify(args) !== JSON.stringify(expected)) process.exit(12); + if (model !== 'model') { console.error('Unknown model'); process.exit(1); } + console.log('RELAYFLOWS_MODEL_READY'); process.exit(0); +} +const promptPath = args[args.indexOf('--prompt-file') + 1]; +const task = fs.readFileSync(promptPath, 'utf8'); +const result = { args, task, credentials, promptPath, keyPresent: !!process.env.DEVIN_API_KEY, + credential: fs.readFileSync(credentials, 'utf8'), mode: fs.statSync(credentials).mode & 511 }; +console.log(JSON.stringify(result)); +if (task === 'wait') setTimeout(() => {}, 30000); else process.exit(task === 'fail' ? 7 : 0); +`, { mode: 0o755 }); + return { cwd, cli, env: { PATH: process.env.PATH, HOME: cwd, DEVIN_API_KEY: 'devin-test-secret' } }; +} + +it.each(['--version\nDo the task', 'fail'])('launches print mode with file input and cleans up after %s', async task => { + const f = fixture(); + const result = await runAgentCli(f.cli, task, undefined, 'gpt-5.6-sol', undefined, undefined, + 'agent', undefined, f.cwd, 'direct', undefined, f.env); + expect(result.exit_code).toBe(task === 'fail' ? 7 : 0); + expect(result.tokens_input).toBeUndefined(); + expect(result.stdout_tail).not.toContain('devin-test-secret'); + const value = JSON.parse(result.stdout_tail); + expect(value.task).toBe(task); + expect(value.args).toEqual(expect.arrayContaining(['-p', '--permission-mode', 'dangerous', + '--respect-workspace-trust', 'false', '--model', 'gpt-5.6-sol', '--prompt-file'])); + expect(value.keyPresent).toBe(false); expect(value.mode).toBe(0o600); + expect(existsSync(value.credentials)).toBe(false); expect(existsSync(value.promptPath)).toBe(false); +}); + +it('redacts a near-buffer-size response to a one-character credential without retaining per-match spans', async () => { + const f = fixture(); + const env = { ...f.env, DEVIN_API_KEY: 'x', PROBE_LARGE_OUTPUT: '1' }; + for (const probe of [probeCli, probeCliAsync]) { + const result = await probe(f.cli, f.cwd, undefined, undefined, env); + expect(result.authenticated).toBe(false); + expect(result.authFailureDetail).toBe('[redacted:DEVIN_API_KEY]\nwindsurf_api_key = "[redacted:DEVIN_API_KEY]"'); + } +}); + +it('redacts the normalized token when the supplied key has surrounding whitespace', async () => { + const f = fixture(); + const result = await runAgentCli(f.cli, 'task', undefined, undefined, undefined, undefined, + 'agent', undefined, f.cwd, 'direct', undefined, { ...f.env, DEVIN_API_KEY: ' devin-test-secret\n' }); + expect(result.exit_code).toBe(0); + expect(result.stdout_tail).not.toContain('devin-test-secret'); +}); + +it('checks provider auth with isolated credentials in both synchronous and asynchronous preflight', async () => { + const f = fixture(); + expect(probeCli(f.cli, f.cwd, undefined, undefined, f.env).authenticated).toBe(true); + expect((await probeCliAsync(f.cli, f.cwd, 'model', undefined, f.env)).modelAvailable).toBe(true); + expect(probeCli(f.cli, f.cwd, undefined, undefined, { PATH: process.env.PATH, HOME: f.cwd, + XDG_DATA_HOME: f.cwd }).authenticated).toBe(false); +}); + +it('refuses an unavailable model and missing model-probe credentials in both preflight drivers', async () => { + const f = fixture(); + for (const probe of [probeCli, probeCliAsync]) { + expect(await probe(f.cli, f.cwd, 'unavailable', undefined, f.env)) + .toMatchObject({ authenticated: true, modelAvailable: false }); + expect(await probe(f.cli, f.cwd, 'model', undefined, { PATH: process.env.PATH, + HOME: f.cwd, XDG_DATA_HOME: f.cwd })) + .toMatchObject({ authenticated: false, modelAvailable: false }); + } +}); + +it('names an empty Devin key in preflight rather than hiding it as a generic probe failure', async () => { + const f = fixture(); const env = { ...f.env, DEVIN_API_KEY: ' ' }; + expect(() => probeCli(f.cli, f.cwd, undefined, undefined, env)) + .toThrow(expect.objectContaining({ detail: 'devin_api_key_empty' })); + await expect(probeCliAsync(f.cli, f.cwd, undefined, undefined, env)) + .rejects.toMatchObject({ detail: 'devin_api_key_empty' }); + const checked = preflight({ version: '0.1.0', steps: [{ id: 'work', type: 'agent', cli: f.cli, + instruction: 'work' }] }, { probes: { cli: () => probeCli(f.cli, f.cwd, undefined, undefined, env), + executor: () => true, command: () => true } }); + expect(checked.ok).toBe(false); + expect(checked.diagnostics).toContainEqual(expect.objectContaining({ kind: 'probe_failed', + detail: 'devin_api_key_empty', message: expect.stringContaining('DEVIN_API_KEY must contain a non-empty') })); + expect(checked.diagnostics).toContainEqual(expect.objectContaining({ + message: expect.stringContaining('FLOW_DEVIN_API_KEY') })); +}); + +it('points hosted flow operators to the CLI-token alias on authentication refusal', () => { + const checked = preflight({ version: '0.1.0', steps: [{ id: 'work', type: 'agent', cli: 'devin', + instruction: 'work' }] }, { probes: { cli: () => ({ exists: true, supported: true, + authenticated: false, authExitCode: 1, authFailureDetail: 'Authentication required: invalid api key' }), + executor: () => true, command: () => true } }); + expect(checked.ok).toBe(false); + expect(checked.diagnostics).toContainEqual(expect.objectContaining({ kind: 'cli_unauthenticated', + message: expect.stringContaining('set FLOW_DEVIN_API_KEY to a Devin CLI login token') })); +}); + +it('removes credential and prompt state when the worker loses its lease', async () => { + const f = fixture(); const privateRoot = directory(); + const controller = new AbortController(); + const running = runAgentCli(f.cli, 'wait', undefined, undefined, undefined, controller.signal, + 'agent', undefined, f.cwd, 'direct', undefined, { ...f.env, TMPDIR: privateRoot }); + for (let i = 0; i < 100 && readdirSync(privateRoot).length === 0; i++) { + await new Promise(resolve => setTimeout(resolve, 10)); + } + expect(readdirSync(privateRoot).length).toBeGreaterThan(0); + controller.abort(); + const result = await running; + expect(result.exit_code).toBeNull(); + expect(result.transport?.cause).toBe('lease_lost'); + expect(readdirSync(privateRoot)).toEqual([]); +}); + +it.each([' invalid-devin-secret\n', ' prefix-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-secretSuffix\n', + ' abc\n', ' short01\n', ' ?\n'])('fully redacts echoed credentials alongside shape-based scrubbing', async key => { + const f = fixture(); const env = { ...f.env, DEVIN_API_KEY: key }; + for (const probe of [probeCli, probeCliAsync]) { + const result = await probe(f.cli, f.cwd, undefined, undefined, env); + expect(result.authenticated).toBe(false); + expect(result.authExitCode).toBe(1); + expect(result.authFailureDetail).not.toContain(key.trim()); + expect(result.authFailureDetail).not.toContain('prefix-'); + expect(result.authFailureDetail).not.toContain('secretSuffix'); + expect(result.authFailureDetail).toContain('[redacted:DEVIN_API_KEY]'); + } +}); + +it.each([ + ['abc', 'sk-prefixabcSuffix123456'], + ['abc', 'prefixabc@example.com'], + ['abc', `${'0'.repeat(16)}abc${'1'.repeat(16)}`], + ['a@b.co!', 'a@b.co!'], + ['aba', 'ababa'], +])('redacts the complete overlap between credentials and diagnostic shapes: %s', async (key, diagnostic) => { + const f = fixture(); + const env = { ...f.env, DEVIN_API_KEY: ` ${key}\n`, PROBE_DIAGNOSTIC: `Failure: ${diagnostic}` }; + for (const probe of [probeCli, probeCliAsync]) { + const result = await probe(f.cli, f.cwd, undefined, undefined, env); + expect(result.authenticated).toBe(false); + expect(result.authFailureDetail).toBe('Failure: [redacted:DEVIN_API_KEY]\nwindsurf_api_key = "[redacted:DEVIN_API_KEY]"'); + } +}); + +it.each([ + ['Authorization: Bearer abcSECRET_SUFFIX123456', 'Authorization: Bearer [redacted]'], + ['Cookie: session=abcSECRET_SUFFIX123456', 'Cookie: [redacted]'], + ['PLAIN_SETTING=prefix-aaaaaaaaaaaaaaaaabcaaaaaaaaaaaaaaaa-secretSuffix', 'PLAIN_SETTING=[redacted:PLAIN_SETTING]'], +])('preserves shared redaction before short-key and supplemental rules: %s', async (diagnostic, expected) => { + const f = fixture(); + const env = { ...f.env, DEVIN_API_KEY: 'abc', PROBE_DIAGNOSTIC: diagnostic, + PLAIN_SETTING: 'prefix-aaaaaaaaaaaaaaaaabcaaaaaaaaaaaaaaaa-secretSuffix' }; + for (const probe of [probeCli, probeCliAsync]) { + const result = await probe(f.cli, f.cwd, undefined, undefined, env); + expect(result.authenticated).toBe(false); + expect(result.authFailureDetail).toBe(`${expected}\nwindsurf_api_key = "[redacted:DEVIN_API_KEY]"`); + } +}); diff --git a/packages/sdk/tests/real-devin-adapter.test.ts b/packages/sdk/tests/real-devin-adapter.test.ts new file mode 100644 index 000000000..20d19d2df --- /dev/null +++ b/packages/sdk/tests/real-devin-adapter.test.ts @@ -0,0 +1,27 @@ +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { expect, it } from 'vitest'; +import { runAgentCli } from '../src/worker-cli.js'; + +// Match the pinned Cloud sandbox release; opt in with a CLI-login token. +const DEVIN_VERSION = '3000.11.234'; +const cli = process.env.RELAYFLOWS_REAL_DEVIN_CLI; +it.runIf(cli !== undefined)('runs the pinned Devin CLI through the real agent worker', async () => { + const version = spawnSync(cli!, ['--version'], { encoding: 'utf8', timeout: 10_000 }); + expect(version.status).toBe(0); + expect(version.stdout).toMatch(new RegExp(`^devin ${DEVIN_VERSION.replaceAll('.', '\\.')} `)); + expect(process.env.DEVIN_API_KEY?.length).toBeGreaterThan(0); + const cwd = mkdtempSync(join(tmpdir(), 'real-devin-')); + try { + const result = await runAgentCli(cli!, + 'Reply with exactly RELAYFLOWS_DEVIN_WORKER_READY and nothing else. Do not call tools.', + undefined, undefined, undefined, undefined, 'agent', undefined, cwd, 'direct', undefined, + { PATH: process.env.PATH, HOME: process.env.HOME, TMPDIR: process.env.TMPDIR, + DEVIN_API_KEY: process.env.DEVIN_API_KEY }, 'devin', 60_000); + expect(result.exit_code).toBe(0); + expect(result.stdout_tail.trim()).toBe('RELAYFLOWS_DEVIN_WORKER_READY'); + expect(result.tokens_input).toBeUndefined(); + } finally { rmSync(cwd, { recursive: true, force: true }); } +}, 70_000);