@defrex/autobuild 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -18
- package/SPEC.md +499 -238
- package/bin/ab-dispatch-generation.ts +11 -2
- package/docs/accounts.md +119 -0
- package/docs/agent-runtimes.md +4 -4
- package/docs/answering-blocked-builds.md +2 -2
- package/docs/architecture.md +262 -53
- package/docs/assets/headline-wide.png +0 -0
- package/docs/build-store.md +3 -41
- package/docs/builds.md +4 -4
- package/docs/cli.md +18 -4
- package/docs/configuration-overview.md +115 -4
- package/docs/configuration.md +488 -334
- package/docs/dispatcher-hosting.md +19 -34
- package/docs/dispatcher.md +1 -1
- package/docs/forges.md +5 -5
- package/docs/getting-started.md +2 -2
- package/docs/glossary.md +6 -6
- package/docs/intake.md +2 -0
- package/docs/integration-overview.md +15 -15
- package/docs/integration-tree.md +45 -38
- package/docs/integration.md +6 -6
- package/{skills/guide/references/landing-policy.md → docs/merge-policy.md} +40 -24
- package/docs/migration-1.0.md +17 -13
- package/docs/operating.md +41 -19
- package/docs/operator-api.md +180 -51
- package/docs/operator-surfaces.md +5 -18
- package/docs/overview.md +3 -3
- package/docs/plugin-authoring.md +21 -0
- package/docs/remote-store-protocol.md +242 -68
- package/docs/remote-ticket-protocol.md +30 -50
- package/docs/restacking.md +54 -15
- package/docs/seams.md +8 -8
- package/docs/setup.md +59 -119
- package/docs/skills.md +1 -1
- package/docs/spec-standard.md +6 -6
- package/docs/ticket-dependencies.md +7 -7
- package/docs/ticket-sources.md +18 -0
- package/docs/tickets.md +8 -2
- package/docs/troubleshooting.md +8 -12
- package/docs/upgrading.md +9 -4
- package/docs/verification.md +60 -14
- package/docs/workspaces.md +4 -4
- package/package.json +17 -6
- package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
- package/packages/core/src/accounts/chatgpt-state.ts +41 -0
- package/packages/core/src/accounts/local-credentials.ts +194 -0
- package/packages/core/src/accounts/local-inference.ts +106 -0
- package/packages/core/src/accounts/local-owner.ts +123 -0
- package/packages/core/src/accounts/sensitive.ts +2 -0
- package/packages/core/src/cli/accounts.ts +147 -0
- package/packages/core/src/cli/binary-direct.ts +13 -1
- package/packages/core/src/cli/binary-lifecycle.ts +65 -2
- package/packages/core/src/cli/binary.ts +3 -1
- package/packages/core/src/cli/build-control.ts +83 -28
- package/packages/core/src/cli/connect.ts +3 -3
- package/packages/core/src/cli/context.ts +81 -38
- package/packages/core/src/cli/dashboard/facts.ts +2 -1
- package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
- package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
- package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
- package/packages/core/src/cli/dashboard/model.ts +56 -33
- package/packages/core/src/cli/dashboard/poll.ts +9 -3
- package/packages/core/src/cli/dashboard/render.ts +59 -37
- package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
- package/packages/core/src/cli/dashboard/tree.ts +3 -2
- package/packages/core/src/cli/dispatch-args.ts +1 -1
- package/packages/core/src/cli/dispatch-frontend.ts +6 -3
- package/packages/core/src/cli/dispatch-handoff.ts +125 -44
- package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
- package/packages/core/src/cli/dispatch-launcher.ts +54 -21
- package/packages/core/src/cli/dispatch-preflight.ts +6 -1
- package/packages/core/src/cli/dispatch.ts +106 -11
- package/packages/core/src/cli/env.ts +4 -0
- package/packages/core/src/cli/help.ts +46 -23
- package/packages/core/src/cli/init-readiness-remote.ts +22 -1
- package/packages/core/src/cli/init-readiness-shared.ts +5 -1
- package/packages/core/src/cli/init-validation.ts +160 -18
- package/packages/core/src/cli/main.ts +68 -8
- package/packages/core/src/cli/node-verification-provenance.ts +1 -97
- package/packages/core/src/cli/publication-settlement.ts +47 -21
- package/packages/core/src/cli/repository-status.ts +20 -9
- package/packages/core/src/cli/secrets.ts +173 -0
- package/packages/core/src/cli/status.ts +42 -5
- package/packages/core/src/cli/store-opening.ts +17 -2
- package/packages/core/src/cli/terminal.ts +22 -1
- package/packages/core/src/cli/terminals.ts +14 -10
- package/packages/core/src/cli/upgrade-agent.ts +9 -1
- package/packages/core/src/cli/upgrade-landing.ts +70 -30
- package/packages/core/src/cli/upgrade.ts +3 -1
- package/packages/core/src/cli/wait.ts +15 -7
- package/packages/core/src/cli/watch-lifetime.ts +111 -0
- package/packages/core/src/cli/watch.ts +635 -510
- package/packages/core/src/config/accounts.ts +101 -0
- package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
- package/packages/core/src/config/effective-artifact.ts +13 -0
- package/packages/core/src/config/landing.ts +1 -1
- package/packages/core/src/config/live.ts +14 -1
- package/packages/core/src/config/load.ts +21 -1
- package/packages/core/src/config/pipeline-source.ts +28 -0
- package/packages/core/src/config/reference-metadata.ts +2 -0
- package/packages/core/src/config/reference.ts +22 -7
- package/packages/core/src/config/roles.ts +54 -3
- package/packages/core/src/config/schema.ts +146 -162
- package/packages/core/src/context-directory.ts +26 -0
- package/packages/core/src/distribution-packaging.ts +26 -5
- package/packages/core/src/events/catalog.ts +10 -2
- package/packages/core/src/events/compatibility.ts +2 -1
- package/packages/core/src/events/globs.ts +1 -1
- package/packages/core/src/events/payloads.ts +73 -1
- package/packages/core/src/events/policy.ts +7 -0
- package/packages/core/src/events/repository.ts +4 -4
- package/packages/core/src/events/sessions.ts +6 -6
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +574 -0
- package/packages/core/src/kernel/auto-merge.ts +2 -2
- package/packages/core/src/kernel/engine.ts +255 -26
- package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
- package/packages/core/src/kernel/integration-landing.ts +3 -3
- package/packages/core/src/kernel/integration-state.ts +27 -4
- package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
- package/packages/core/src/kernel/log-index.ts +13 -1
- package/packages/core/src/kernel/node-landing.ts +8 -8
- package/packages/core/src/kernel/node-parent.ts +2 -2
- package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
- package/packages/core/src/kernel/node-verification-context.ts +216 -0
- package/packages/core/src/kernel/phases.ts +1 -1
- package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
- package/packages/core/src/kernel/publication-retry.ts +168 -0
- package/packages/core/src/kernel/reconcile-restack.ts +29 -1
- package/packages/core/src/kernel/reducer.ts +85 -5
- package/packages/core/src/kernel/target-distance.ts +45 -0
- package/packages/core/src/kernel/terminal-guard.ts +10 -1
- package/packages/core/src/kernel/verify-stage-state.ts +123 -0
- package/packages/core/src/kernel/verify-stages.ts +39 -0
- package/packages/core/src/ontology.ts +1 -0
- package/packages/core/src/operator/annotations.ts +6 -0
- package/packages/core/src/operator/control.ts +1 -1
- package/packages/core/src/operator/index.ts +3 -7
- package/packages/core/src/operator/landings.ts +5 -1
- package/packages/core/src/operator/presentation.ts +6 -1
- package/packages/core/src/operator/protocol.ts +6 -0
- package/packages/core/src/operator/query.ts +14 -18
- package/packages/core/src/operator/registry.ts +39 -7
- package/packages/core/src/operator/sandbox-host.ts +64 -40
- package/packages/core/src/operator/sandbox.ts +3 -0
- package/packages/core/src/operator/ticket-source-backend.ts +3 -12
- package/packages/core/src/operator/tickets.ts +25 -4
- package/packages/core/src/plugins/manifest.ts +2 -1
- package/packages/core/src/ports/forge/contract.ts +2 -2
- package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
- package/packages/core/src/ports/forge/github-readiness.ts +2 -2
- package/packages/core/src/ports/forge/github.ts +26 -7
- package/packages/core/src/ports/forge/local-git.ts +4 -4
- package/packages/core/src/ports/forge/readiness.ts +1 -1
- package/packages/core/src/ports/forge-failure.ts +24 -0
- package/packages/core/src/ports/runner/account-env.ts +88 -0
- package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
- package/packages/core/src/ports/runner/claude.ts +26 -2
- package/packages/core/src/ports/runner/codex.ts +63 -31
- package/packages/core/src/ports/runner/one-shot.ts +2 -0
- package/packages/core/src/ports/runner/provider-error.ts +5 -0
- package/packages/core/src/ports/runner/routing.ts +35 -4
- package/packages/core/src/ports/tickets/contract.ts +58 -0
- package/packages/core/src/ports/tickets/tree.ts +1 -1
- package/packages/core/src/ports/types.ts +28 -7
- package/packages/core/src/ports/workspace/account-policy.ts +72 -0
- package/packages/core/src/ports/workspace/build-execution.ts +9 -2
- package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
- package/packages/core/src/ports/workspace/create.ts +2 -0
- package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
- package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
- package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
- package/packages/core/src/ports/workspace/vercel-sandbox.ts +182 -72
- package/packages/core/src/processes/build-child.ts +6 -8
- package/packages/core/src/processes/build-execution-state.ts +8 -5
- package/packages/core/src/processes/build-runner.ts +554 -99
- package/packages/core/src/processes/dispatcher.ts +209 -101
- package/packages/core/src/processes/execution-no-progress.ts +8 -1
- package/packages/core/src/processes/execution-settlement.ts +21 -3
- package/packages/core/src/processes/harvest-runner.ts +68 -8
- package/packages/core/src/processes/phase-failure-budget.ts +1 -0
- package/packages/core/src/processes/publication-loss.ts +8 -2
- package/packages/core/src/processes/publication-state.ts +42 -4
- package/packages/core/src/processes/repo-view.ts +14 -0
- package/packages/core/src/processes/verify-cycle-config.ts +96 -0
- package/packages/core/src/project-secrets.ts +105 -0
- package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
- package/packages/core/src/secret-name.ts +41 -0
- package/packages/core/src/store/account-redaction.ts +156 -0
- package/packages/core/src/store/adapter.ts +1 -0
- package/packages/core/src/store/build-scope.ts +9 -0
- package/packages/core/src/store/contract.ts +116 -2
- package/packages/core/src/store/local/schema.ts +13 -0
- package/packages/core/src/store/local/store.ts +42 -0
- package/packages/core/src/store/memory.ts +47 -0
- package/packages/core/src/store/operator-presence.ts +21 -0
- package/packages/core/src/store/phase-session.ts +10 -0
- package/packages/core/src/store/reducer-value-shapes.json +5185 -4156
- package/packages/core/src/store/remote/client.ts +89 -48
- package/packages/core/src/store/remote/compatibility.ts +20 -0
- package/packages/core/src/store/remote/protocol.ts +4 -0
- package/packages/core/src/store/remote/version.ts +3 -1
- package/packages/core/src/store/retention.ts +2 -3
- package/packages/core/src/store/session-handle.ts +9 -0
- package/packages/core/src/store/streams/session-writer.ts +1 -1
- package/packages/core/src/store/types.ts +12 -2
- package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
- package/packages/core/src/testing/index.ts +12 -1
- package/packages/core/src/testing/reduced-read-budget.ts +47 -0
- package/packages/core/src/testing/temp-directories.ts +58 -0
- package/skills/code-review/SKILL.md +23 -9
- package/skills/finalize/SKILL.md +15 -7
- package/skills/guide/SKILL.md +373 -148
- package/skills/guide/references/accounts.md +119 -0
- package/skills/guide/references/integration-tree.md +45 -38
- package/{docs/landing-policy.md → skills/guide/references/merge-policy.md} +40 -24
- package/skills/guide/references/migration-1.0.md +17 -13
- package/skills/guide/references/operator-api.md +180 -51
- package/skills/guide/references/plugin-authoring.md +21 -0
- package/skills/guide/references/remote-store-protocol.md +242 -68
- package/skills/guide/references/remote-ticket-protocol.md +30 -50
- package/skills/guide/references/restacking.md +54 -15
- package/skills/guide/references/setup.md +59 -119
- package/skills/guide/references/spec-standard.md +6 -6
- package/skills/guide/references/ticket-dependencies.md +7 -7
- package/skills/harvest/SKILL.md +3 -1
- package/skills/harvest-review/SKILL.md +3 -1
- package/skills/implement/SKILL.md +43 -17
- package/skills/operate/SKILL.md +118 -118
- package/skills/plan/SKILL.md +39 -13
- package/skills/plan-review/SKILL.md +15 -10
- package/skills/reconcile/SKILL.md +22 -3
- package/skills/spec/SKILL.md +20 -20
- package/skills/tickets/SKILL.md +12 -9
- package/templates/autobuild.toml +1 -1
- package/templates/hosted-service/package.json +2 -2
- package/docs/hosted-dispatcher-cutover-validation.md +0 -178
- package/docs/hosted-dispatcher.md +0 -275
- package/docs/hosted-service.md +0 -293
- package/docs/mcp.md +0 -149
- package/packages/core/src/orchestrator/approvals.ts +0 -115
- package/packages/core/src/orchestrator/conversation.ts +0 -167
- package/packages/core/src/orchestrator/model.ts +0 -86
- package/packages/core/src/orchestrator/prompt.ts +0 -63
- package/packages/core/src/orchestrator/tools.ts +0 -117
- package/packages/core/src/orchestrator/turn-runner.ts +0 -457
- package/packages/core/src/processes/orchestrator-tick.ts +0 -360
package/docs/upgrading.md
CHANGED
|
@@ -9,6 +9,11 @@ description: "Update the pinned installation, preserve customization, and resume
|
|
|
9
9
|
|
|
10
10
|
Autobuild is an exact pinned development dependency. Pin the release you intend and review manifest and lockfile together.
|
|
11
11
|
|
|
12
|
+
Build sessions now hydrate inputs under `.ab/<phase>/` (or `.ab/verify-<step>/`
|
|
13
|
+
and `.ab/finalize-<step>/`). Repository-authored skills must replace hardcoded
|
|
14
|
+
hydrated `.ab/<file>` paths with `$AB_CONTEXT_DIR/<file>`. Custom output scratch
|
|
15
|
+
may still live elsewhere under `.ab/`.
|
|
16
|
+
|
|
12
17
|
## Update the installation
|
|
13
18
|
|
|
14
19
|
Stop the dispatcher cleanly first and let its sessions drain or suspend. Your operator agent diagnoses the need; you manage the process.
|
|
@@ -29,8 +34,8 @@ Check what upgrade committed, then review and commit the version bump.
|
|
|
29
34
|
|
|
30
35
|
Upgrade keeps your `autobuild.toml`; supported migrations may amend it.
|
|
31
36
|
|
|
32
|
-
- **Explicit
|
|
33
|
-
- **Absent
|
|
37
|
+
- **Explicit merge policy:** a valid `merge` array stays byte-for-byte unchanged. A deprecated `landing` array is renamed to `merge`, preserving rule values, order and comments without reading the legacy journal. Declaring both keys is an error.
|
|
38
|
+
- **Absent merge policy:** upgrade reads the target repository's journal. Legacy ON becomes leaf auto; OFF or no fact becomes leaf consent; nodes get consent either way. If the journal is unavailable, restore access or configure policy deliberately, then retry.
|
|
34
39
|
|
|
35
40
|
Skills [merge three ways](skills.md#how-upgrades-preserve-customization), with validated agent resolutions for overlapping edits. An unresolved conflict leaves that file untouched while others advance. Read the [upgrade report](skills.md#how-upgrades-preserve-customization) and diff even after exit zero: content conflicts don't fail the command. A conflict-free upgrade makes a narrowly scoped local commit. With `--no-commit`, conflicts or unsafe Git state, edits stay uncommitted with an explanation; resolve the reported files and commit.
|
|
36
41
|
|
|
@@ -45,6 +50,6 @@ bun ab dispatch
|
|
|
45
50
|
- **One writer.** Don't run old and new dispatchers at once.
|
|
46
51
|
- **Durable resume.** Work resumes from durable state after a clean stop. Restart doesn't answer escalations.
|
|
47
52
|
- **Old behavior.** Drain old work before switching if it must keep the old execution behavior; no claim-version switch preserves it.
|
|
48
|
-
- **
|
|
53
|
+
- **Remote clients.** Check the instance’s `/health` compatibility window before upgrading connected projects.
|
|
49
54
|
|
|
50
|
-
Read [Infrastructure seams](seams.md) and [Repository configuration](configuration-overview.md) before changing infrastructure or
|
|
55
|
+
Read [Infrastructure seams](seams.md) and [Repository configuration](configuration-overview.md) before changing infrastructure or merge policy.
|
package/docs/verification.md
CHANGED
|
@@ -18,16 +18,49 @@ Every repository needs an **acceptance check**: an agent verify step that runs t
|
|
|
18
18
|
|
|
19
19
|
## Steps and outcomes
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
Verification uses ordered stages. A string in `[verify].steps` is a singleton
|
|
22
|
+
stage; a nonempty array groups members that start together. Empty stages and
|
|
23
|
+
repeated names are errors. Plain string lists retain serial event sequences.
|
|
24
|
+
Every member resolves post-reconcile policy, approved selection/`always`, then
|
|
25
|
+
path applicability at stage entry. Only pass or skip satisfies a member. The
|
|
26
|
+
next stage, or finalize after the last, waits for every member to pass or skip.
|
|
27
|
+
|
|
28
|
+
By default a failure lets all siblings finish; the settled stage routes once
|
|
29
|
+
with every failed report, and no later stage runs. `failFast = true` on either
|
|
30
|
+
step kind instead cancels members without outcomes, preserving existing
|
|
31
|
+
outcomes. The kernel records `verify.cancelled {step, attempt, cause: {step}}`.
|
|
32
|
+
Cancellation is neither a pass nor a failure. It ends the entire build execution
|
|
33
|
+
through its existing process-group or environment supervisor; a replacement
|
|
34
|
+
execution resumes before implement can start. This opt-in teardown/relaunch cost
|
|
35
|
+
avoids per-member process groups and ensures cancelled descendants cannot keep
|
|
36
|
+
writing to the shared workspace, including after a crash.
|
|
37
|
+
|
|
38
|
+
An agent escalation holds its own member while siblings continue. The barrier
|
|
39
|
+
waits for the answer and that member's rerun, unless fail-fast cancels it.
|
|
40
|
+
Cancellation supersedes only that exact verifier occurrence's agent escalations,
|
|
41
|
+
including late raises and answers. They stay in history but no longer block,
|
|
42
|
+
route guidance, reset budgets, revise the spec or request abort. Answer commands
|
|
43
|
+
reject a superseded escalation as stale. Unrelated escalations retain authority.
|
|
44
|
+
|
|
45
|
+
All members of a cycle share one monotonic attempt. A failed cycle spends one
|
|
46
|
+
`maxVerifyAttempts` unit regardless of its failure count. Restart preserves
|
|
47
|
+
outcomes and reruns members without outcomes at that same attempt, with
|
|
48
|
+
independent agent contexts under `$AB_CONTEXT_DIR` in the shared workspace.
|
|
49
|
+
Integration nodes use the same barriers with exact head, parent and restack
|
|
50
|
+
identity; their failed-cycle attention is published only after settlement.
|
|
51
|
+
|
|
52
|
+
Each step has its own `[verify.<step>]` table.
|
|
53
|
+
|
|
54
|
+
For example: `steps = ["types", ["unit", "integration"], ["acceptance", "docs"]]`.
|
|
22
55
|
|
|
23
56
|
| Kind | Runs | Outcome |
|
|
24
57
|
|---|---|---|
|
|
25
58
|
| `check` | a named `command` from `[commands]`, no agent | exit 0 passes; nonzero fails, keeping the output |
|
|
26
59
|
| `agent` | the exact `skill` you configure ([repository-local](skills.md#add-a-repository-local-skill), no prefix inferred) | `ab verdict` records pass, fail or skip |
|
|
27
60
|
|
|
28
|
-
- **Pass**
|
|
29
|
-
- **Fail
|
|
30
|
-
- **Skip**
|
|
61
|
+
- **Pass** satisfies the member; the next stage waits for its siblings.
|
|
62
|
+
- **Fail**, after its stage settles, sends all failed reports back through implement and code review, then verification, up to `[policy].maxVerifyAttempts`; then the build escalates.
|
|
63
|
+
- **Skip** satisfies its member without counting as a pass or spending retries. Plan exclusions and path misses skip deterministically. An agent may skip only when the whole step doesn't apply, with a reason; an applicable behavior it can't exercise is a failure.
|
|
31
64
|
|
|
32
65
|
## Select what a build needs
|
|
33
66
|
|
|
@@ -134,13 +167,26 @@ Autobuild's own chain: this repository's choices, not defaults.
|
|
|
134
167
|
|---|---|---|---|
|
|
135
168
|
| 1 | lint | check | formatting and lint; mandatory |
|
|
136
169
|
| 2 | types | check | TypeScript type checking |
|
|
137
|
-
| 3 | unit | check | the test suite |
|
|
138
|
-
| 4 |
|
|
139
|
-
| 5 |
|
|
140
|
-
| 6 |
|
|
141
|
-
| 7 |
|
|
142
|
-
| 8 |
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
170
|
+
| 3 | unit | check | the test suite, minus database-backed integration tests |
|
|
171
|
+
| 4 | build | check | packs every publishable package and checks its contents, imports and bins; mandatory |
|
|
172
|
+
| 5 | integration | check | database-backed store, service and migration suites, plus a packed hosted-service deploy rehearsal |
|
|
173
|
+
| 6 | ui-tui | agent | captures terminal-dashboard frames and judges them |
|
|
174
|
+
| 7 | ui-app | agent | captures operator web-app frames and judges them against the design |
|
|
175
|
+
| 8 | ui-website | agent | captures site and docs frames at desktop and phone widths, compared with approved references |
|
|
176
|
+
| 9 | docs | agent | fails when a `docs/` passage no longer matches the build's user-facing changes |
|
|
177
|
+
|
|
178
|
+
Steps 5 to 9 are optional and path-scoped. Integration covers core, the Postgres store and the hosted packages; the others run through repository skills `verify-ui-tui`, `verify-ui-app`, `verify-ui-website` and `verify-docs`. The docs step applies to product source, skills, templates, `SPEC.md`, `README.md` and `docs/`.
|
|
179
|
+
|
|
180
|
+
A plan for a docs change like this page selects lint, types, unit, build, ui-website and docs; both of the last two pass their path checks because they cover `docs/`. The untouched ui-tui and ui-app steps aren't selected.
|
|
181
|
+
|
|
182
|
+
Grouped failures retain the legacy `feedback.verify` object for the first report
|
|
183
|
+
in configured order. A decisive `verify.stage-failed` receipt carries the full
|
|
184
|
+
ordered reports and cancelled members; `implement.started.verifyStageFailure`
|
|
185
|
+
references it. `ab context` materializes all reports and lists cancelled members
|
|
186
|
+
as not run, including when guidance is the immediate feedback. Older readers
|
|
187
|
+
defer on the decisive new event rather than misreading the stage's outcome.
|
|
188
|
+
|
|
189
|
+
Implement cancellation feedback is scoped to its referenced failed-stage receipt,
|
|
190
|
+
including guidance rounds. Later implement rounds without that receipt have no
|
|
191
|
+
`cancelledVerify` list. Finalize receives historical reports but omits that list;
|
|
192
|
+
its current verification gates have passed or been skipped.
|
package/docs/workspaces.md
CHANGED
|
@@ -47,7 +47,7 @@ Run `bun ab init`, install and authenticate your runtime, then run `bun ab init
|
|
|
47
47
|
|
|
48
48
|
Runs build-runners, agents and checks on remote machines. Install `@defrex/autobuild-vercel-sandbox`, register it in `plugins`, and commit your setup and configuration so remote clones see them. Requires:
|
|
49
49
|
|
|
50
|
-
-
|
|
50
|
+
- a remote store that speaks the remote BuildStore protocol over HTTPS
|
|
51
51
|
- an HTTPS `github.com/owner/repository` origin and `forge = "github"`
|
|
52
52
|
- a push-capable `GITHUB_TOKEN` or `GH_TOKEN` on the dispatcher (a `gh` login isn't enough)
|
|
53
53
|
- `VERCEL_TOKEN`, `VERCEL_TEAM_ID` and `VERCEL_PROJECT_ID` on the dispatcher host
|
|
@@ -110,9 +110,9 @@ Sandbox preparation order:
|
|
|
110
110
|
4. `runtimeProvisioning.<runtime>` installs
|
|
111
111
|
5. `commands.setup`
|
|
112
112
|
|
|
113
|
-
- **Runtimes.** Every primary and alternate runtime needs a pinned install and exact-version preflight, and gets only the credentials named in `environmentVariables
|
|
113
|
+
- **Runtimes.** Every primary and alternate runtime needs a pinned install and exact-version preflight, and gets only the credentials named in `environmentVariables`, except declared [accounts](configuration-overview.md#accounts), whose credentials remain on the host and are brokered by egress policy using guest placeholders.
|
|
114
114
|
- **Repetition.** New sandboxes repeat provisioning and preflights rerun before each build-runner; keep setup idempotent.
|
|
115
|
-
- **Validation.** `bun ab init --validate` runs named provisioning, setup, runtime and Store checks in a disposable environment, deletes it even on failure, and starts no build or agent.
|
|
115
|
+
- **Validation.** `bun ab init --validate` runs named provisioning, setup, runtime and Store checks in a disposable environment, deletes it even on failure, and starts no build. For every declared account, including unused accounts, it runs a tool-free model probe through the account's runtime (Claude Code for Claude/Kimi, Codex for ChatGPT); these probes create no ordinary build phase or persistent agent session. Hosted ChatGPT project secrets report readiness from write-only status metadata instead; the first hosted build is the live check.
|
|
116
116
|
- **Lifetime.** `timeoutSeconds` bounds a sandbox; provider operations have their own timeouts. An intact sandbox resumes; an expired or lost one is rebuilt from durable workspace and publication evidence, losing unpublished work that lived only on it.
|
|
117
117
|
|
|
118
118
|
### Private repositories
|
|
@@ -126,7 +126,7 @@ export AB_GIT_READ_TOKEN='<read-only repository token>'
|
|
|
126
126
|
|
|
127
127
|
- Use a repository-scoped read token, separate from the push identity. For a public clone, remove `gitUsernameEnv` and `gitPasswordEnv`.
|
|
128
128
|
- Autobuild passes these as the authenticated Git source for [Vercel private-repository cloning](https://vercel.com/kb/guide/sandbox-private-github-repositories); don't embed credentials in the origin URL.
|
|
129
|
-
- `environmentVariables`
|
|
129
|
+
- `environmentVariables` forwards legacy runtime API credentials; declared account credentials become placeholders even when listed here. Never forward `AB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, Vercel tokens or the clone token; Autobuild supplies scoped Store authority, keeps clone secrets out of guest commands, and publishes from the host.
|
|
130
130
|
|
|
131
131
|
## Writing your own
|
|
132
132
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@defrex/autobuild",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Agent-driven software delivery from groomed ticket to merged PR",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -90,6 +90,14 @@
|
|
|
90
90
|
"./connection": {
|
|
91
91
|
"types": "./packages/core/src/connection.ts",
|
|
92
92
|
"import": "./packages/core/src/connection.ts"
|
|
93
|
+
},
|
|
94
|
+
"./project-secrets": {
|
|
95
|
+
"types": "./packages/core/src/project-secrets.ts",
|
|
96
|
+
"import": "./packages/core/src/project-secrets.ts"
|
|
97
|
+
},
|
|
98
|
+
"./secret-name": {
|
|
99
|
+
"types": "./packages/core/src/secret-name.ts",
|
|
100
|
+
"import": "./packages/core/src/secret-name.ts"
|
|
93
101
|
}
|
|
94
102
|
},
|
|
95
103
|
"files": [
|
|
@@ -127,11 +135,13 @@
|
|
|
127
135
|
"release": "bun tools/release.ts",
|
|
128
136
|
"postgres:migrate": "bun packages/postgres-store/src/bin.ts migrate",
|
|
129
137
|
"docs:configuration": "bun tools/configuration-reference.ts --write",
|
|
130
|
-
"check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/
|
|
138
|
+
"check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
|
|
139
|
+
"check:build": "bun tools/workspace-manifest-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
|
|
131
140
|
"format:staged": "git-format-staged --formatter './node_modules/.bin/biome format --stdin-file-path {}' '*.js' '*.jsx' '*.ts' '*.tsx' '*.json' '*.jsonc' '*.css' '*.graphql' '*.gql'",
|
|
132
141
|
"prepare": "husky",
|
|
133
|
-
"test": "bun
|
|
134
|
-
"
|
|
142
|
+
"test": "bun tools/test-temp-leaks.ts unit",
|
|
143
|
+
"test:integration": "bun tools/test-temp-leaks.ts integration",
|
|
144
|
+
"typecheck": "node --max-old-space-size=4096 ./node_modules/typescript/bin/tsc --noEmit"
|
|
135
145
|
},
|
|
136
146
|
"dependencies": {
|
|
137
147
|
"@ai-sdk/gateway": "4.0.82",
|
|
@@ -139,14 +149,15 @@
|
|
|
139
149
|
"@vercel/sandbox": "^3.1.0",
|
|
140
150
|
"ai": "^7.0.101",
|
|
141
151
|
"drizzle-orm": "^0.45.2",
|
|
152
|
+
"jose": "^6.2.13",
|
|
142
153
|
"semver": "^7.7.4",
|
|
143
154
|
"smol-toml": "^1.7.0",
|
|
144
155
|
"zod": "^4.4.3"
|
|
145
156
|
},
|
|
146
157
|
"devDependencies": {
|
|
147
158
|
"@biomejs/biome": "2.5.5",
|
|
148
|
-
"@defrex/autobuild-postgres-store": "1.0
|
|
149
|
-
"@defrex/autobuild-vercel-sandbox": "1.0
|
|
159
|
+
"@defrex/autobuild-postgres-store": "1.2.0",
|
|
160
|
+
"@defrex/autobuild-vercel-sandbox": "1.2.0",
|
|
150
161
|
"@resvg/resvg-js": "2.6.2",
|
|
151
162
|
"@types/bun": "^1.3.14",
|
|
152
163
|
"@types/node": "^24.0.0",
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
2
|
+
import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'
|
|
3
|
+
import { chatgptStateSchema, earliestRefreshAt, type ChatGPTState } from './chatgpt-state'
|
|
4
|
+
|
|
5
|
+
const issuer = 'https://auth.openai.com'
|
|
6
|
+
export const CHATGPT_RESOURCE = 'https://api.openai.com/v1'
|
|
7
|
+
const tokenEndpoint = `${issuer}/api/accounts/oauth/token`
|
|
8
|
+
const scopes = 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct'
|
|
9
|
+
const failure = () => new Error('ChatGPT authorization failed; sign in again')
|
|
10
|
+
type Fetch = typeof globalThis.fetch
|
|
11
|
+
export interface OAuthTransaction {
|
|
12
|
+
state: string
|
|
13
|
+
nonce: string
|
|
14
|
+
verifier: string
|
|
15
|
+
redirectUri: string
|
|
16
|
+
hostId: string
|
|
17
|
+
previous?: ChatGPTState
|
|
18
|
+
}
|
|
19
|
+
export function transaction(
|
|
20
|
+
redirectUri: string,
|
|
21
|
+
hostId: string,
|
|
22
|
+
previous?: ChatGPTState,
|
|
23
|
+
): OAuthTransaction {
|
|
24
|
+
const random = () => randomBytes(32).toString('base64url')
|
|
25
|
+
return {
|
|
26
|
+
state: random(),
|
|
27
|
+
nonce: random(),
|
|
28
|
+
verifier: random(),
|
|
29
|
+
redirectUri,
|
|
30
|
+
hostId,
|
|
31
|
+
...(previous ? { previous } : {}),
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function authorizationUrl(t: OAuthTransaction): string {
|
|
35
|
+
const url = new URL(`${issuer}/api/accounts/authorize`)
|
|
36
|
+
url.search = new URLSearchParams({
|
|
37
|
+
client_id: t.previous?.clientId ?? 'dynamic_agent_client',
|
|
38
|
+
...(t.previous ? { id_token_hint: t.previous.idToken } : { agent_name_hint: 'autobuild' }),
|
|
39
|
+
ext_agent_host_id: t.hostId,
|
|
40
|
+
response_type: 'code',
|
|
41
|
+
redirect_uri: t.redirectUri,
|
|
42
|
+
resource: CHATGPT_RESOURCE,
|
|
43
|
+
scope: scopes,
|
|
44
|
+
state: t.state,
|
|
45
|
+
nonce: t.nonce,
|
|
46
|
+
code_challenge_method: 'S256',
|
|
47
|
+
code_challenge: createHash('sha256').update(t.verifier).digest('base64url'),
|
|
48
|
+
}).toString()
|
|
49
|
+
return url.href
|
|
50
|
+
}
|
|
51
|
+
export function callback(t: OAuthTransaction, url: URL): { code: string; clientId: string } {
|
|
52
|
+
if (
|
|
53
|
+
url.pathname !== '/auth/callback' ||
|
|
54
|
+
url.searchParams.getAll('state').length !== 1 ||
|
|
55
|
+
url.searchParams.get('state') !== t.state ||
|
|
56
|
+
url.searchParams.has('error')
|
|
57
|
+
)
|
|
58
|
+
throw failure()
|
|
59
|
+
const clientId = url.searchParams.get('client_id') ?? t.previous?.clientId
|
|
60
|
+
const code = url.searchParams.get('code')
|
|
61
|
+
if (
|
|
62
|
+
!code ||
|
|
63
|
+
!clientId ||
|
|
64
|
+
clientId === 'dynamic_agent_client' ||
|
|
65
|
+
(t.previous && clientId !== t.previous.clientId) ||
|
|
66
|
+
url.searchParams.getAll('code').length !== 1 ||
|
|
67
|
+
url.searchParams.getAll('client_id').length > 1
|
|
68
|
+
)
|
|
69
|
+
throw failure()
|
|
70
|
+
return { code, clientId }
|
|
71
|
+
}
|
|
72
|
+
const jwks = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), {
|
|
73
|
+
timeoutDuration: 15000,
|
|
74
|
+
})
|
|
75
|
+
export async function verifyIdentity(
|
|
76
|
+
idToken: string,
|
|
77
|
+
clientId: string,
|
|
78
|
+
nonce?: string,
|
|
79
|
+
keys: JWTVerifyGetKey = jwks,
|
|
80
|
+
): Promise<string> {
|
|
81
|
+
const { payload } = await jwtVerify(idToken, keys, {
|
|
82
|
+
issuer,
|
|
83
|
+
audience: clientId,
|
|
84
|
+
requiredClaims: ['exp', 'sub', ...(nonce ? ['nonce'] : [])],
|
|
85
|
+
algorithms: ['RS256'],
|
|
86
|
+
clockTolerance: 5,
|
|
87
|
+
})
|
|
88
|
+
if (!payload.sub || (nonce !== undefined && payload.nonce !== nonce)) throw failure()
|
|
89
|
+
return payload.sub
|
|
90
|
+
}
|
|
91
|
+
async function request(
|
|
92
|
+
body: URLSearchParams,
|
|
93
|
+
signal: AbortSignal,
|
|
94
|
+
fetcher: Fetch,
|
|
95
|
+
): Promise<Record<string, unknown>> {
|
|
96
|
+
try {
|
|
97
|
+
const response = await fetcher(tokenEndpoint, {
|
|
98
|
+
method: 'POST',
|
|
99
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
100
|
+
body,
|
|
101
|
+
signal,
|
|
102
|
+
redirect: 'error',
|
|
103
|
+
})
|
|
104
|
+
if (!response.ok) throw failure()
|
|
105
|
+
const text = await response.text()
|
|
106
|
+
if (text.length > 300000) throw failure()
|
|
107
|
+
const value: unknown = JSON.parse(text)
|
|
108
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw failure()
|
|
109
|
+
return value as Record<string, unknown>
|
|
110
|
+
} catch {
|
|
111
|
+
throw failure()
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export async function parseTokens(
|
|
115
|
+
raw: Record<string, unknown>,
|
|
116
|
+
registration: {
|
|
117
|
+
hostId: string
|
|
118
|
+
clientId: string
|
|
119
|
+
subject?: string
|
|
120
|
+
nonce?: string
|
|
121
|
+
previous?: ChatGPTState
|
|
122
|
+
},
|
|
123
|
+
verify = verifyIdentity,
|
|
124
|
+
now = Date.now(),
|
|
125
|
+
): Promise<ChatGPTState> {
|
|
126
|
+
try {
|
|
127
|
+
if (
|
|
128
|
+
typeof raw.access_token !== 'string' ||
|
|
129
|
+
typeof raw.refresh_token !== 'string' ||
|
|
130
|
+
typeof raw.expires_in !== 'number' ||
|
|
131
|
+
!Number.isFinite(raw.expires_in) ||
|
|
132
|
+
raw.expires_in <= 30 ||
|
|
133
|
+
typeof raw.token_type !== 'string' ||
|
|
134
|
+
raw.token_type.toLowerCase() !== 'bearer'
|
|
135
|
+
)
|
|
136
|
+
throw failure()
|
|
137
|
+
const idToken = raw.id_token === undefined ? registration.previous?.idToken : raw.id_token
|
|
138
|
+
if (typeof idToken !== 'string') throw failure()
|
|
139
|
+
const subject =
|
|
140
|
+
raw.id_token === undefined && registration.previous
|
|
141
|
+
? registration.previous.subject
|
|
142
|
+
: await verify(idToken, registration.clientId, registration.nonce)
|
|
143
|
+
if (registration.subject !== undefined && registration.subject !== subject) throw failure()
|
|
144
|
+
const granted =
|
|
145
|
+
raw.scope === undefined && registration.previous
|
|
146
|
+
? registration.previous.scopes
|
|
147
|
+
: typeof raw.scope === 'string'
|
|
148
|
+
? raw.scope.split(/\s+/)
|
|
149
|
+
: []
|
|
150
|
+
const earliest = earliestRefreshAt(raw.earliest_refresh_at)
|
|
151
|
+
return chatgptStateSchema.parse({
|
|
152
|
+
version: 1,
|
|
153
|
+
hostId: registration.hostId,
|
|
154
|
+
clientId: registration.clientId,
|
|
155
|
+
subject,
|
|
156
|
+
scopes: granted,
|
|
157
|
+
accessToken: raw.access_token,
|
|
158
|
+
refreshToken: raw.refresh_token,
|
|
159
|
+
idToken,
|
|
160
|
+
expiresAt: now + raw.expires_in * 1000 - 5000,
|
|
161
|
+
...(earliest === undefined ? {} : { earliestRefreshAt: earliest }),
|
|
162
|
+
})
|
|
163
|
+
} catch {
|
|
164
|
+
throw failure()
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
export async function exchangeCode(
|
|
168
|
+
t: OAuthTransaction,
|
|
169
|
+
url: URL,
|
|
170
|
+
signal: AbortSignal,
|
|
171
|
+
fetcher: Fetch = fetch,
|
|
172
|
+
): Promise<ChatGPTState> {
|
|
173
|
+
const { code, clientId } = callback(t, url)
|
|
174
|
+
const raw = await request(
|
|
175
|
+
new URLSearchParams({
|
|
176
|
+
grant_type: 'authorization_code',
|
|
177
|
+
client_id: clientId,
|
|
178
|
+
code,
|
|
179
|
+
code_verifier: t.verifier,
|
|
180
|
+
redirect_uri: t.redirectUri,
|
|
181
|
+
resource: CHATGPT_RESOURCE,
|
|
182
|
+
}),
|
|
183
|
+
signal,
|
|
184
|
+
fetcher,
|
|
185
|
+
)
|
|
186
|
+
return parseTokens(raw, {
|
|
187
|
+
hostId: t.hostId,
|
|
188
|
+
clientId,
|
|
189
|
+
nonce: t.nonce,
|
|
190
|
+
subject: t.previous?.subject,
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
export async function refreshChatGPT(
|
|
194
|
+
state: ChatGPTState,
|
|
195
|
+
signal: AbortSignal,
|
|
196
|
+
fetcher: Fetch = fetch,
|
|
197
|
+
): Promise<ChatGPTState> {
|
|
198
|
+
chatgptStateSchema.parse(state)
|
|
199
|
+
if ((state.earliestRefreshAt ?? 0) > Date.now()) throw failure()
|
|
200
|
+
const raw = await request(
|
|
201
|
+
new URLSearchParams({
|
|
202
|
+
grant_type: 'refresh_token',
|
|
203
|
+
client_id: state.clientId,
|
|
204
|
+
refresh_token: state.refreshToken,
|
|
205
|
+
resource: CHATGPT_RESOURCE,
|
|
206
|
+
}),
|
|
207
|
+
signal,
|
|
208
|
+
fetcher,
|
|
209
|
+
)
|
|
210
|
+
return parseTokens(raw, {
|
|
211
|
+
hostId: state.hostId,
|
|
212
|
+
clientId: state.clientId,
|
|
213
|
+
subject: state.subject,
|
|
214
|
+
previous: state,
|
|
215
|
+
})
|
|
216
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { sensitiveAccountValues } from './sensitive'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
const token = z
|
|
5
|
+
.string()
|
|
6
|
+
.min(1)
|
|
7
|
+
.max(65536)
|
|
8
|
+
.refine((s) => !s.includes('\0'))
|
|
9
|
+
export const chatgptStateSchema = z.strictObject({
|
|
10
|
+
version: z.literal(1),
|
|
11
|
+
hostId: z
|
|
12
|
+
.string()
|
|
13
|
+
.regex(/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),
|
|
14
|
+
clientId: z
|
|
15
|
+
.string()
|
|
16
|
+
.min(1)
|
|
17
|
+
.refine((s) => s !== 'dynamic_agent_client'),
|
|
18
|
+
subject: z.string().min(1),
|
|
19
|
+
scopes: z
|
|
20
|
+
.array(z.string())
|
|
21
|
+
.refine((s) => s.includes('chatgpt.tokens.use.direct') && s.includes('offline_access')),
|
|
22
|
+
accessToken: token,
|
|
23
|
+
refreshToken: token,
|
|
24
|
+
idToken: token,
|
|
25
|
+
expiresAt: z.number().finite(),
|
|
26
|
+
earliestRefreshAt: z.number().finite().optional(),
|
|
27
|
+
})
|
|
28
|
+
export type ChatGPTState = z.infer<typeof chatgptStateSchema>
|
|
29
|
+
export function credentialValues(state: ChatGPTState): string[] {
|
|
30
|
+
const values = [state.accessToken, state.refreshToken, state.idToken]
|
|
31
|
+
values.forEach((v) => {
|
|
32
|
+
sensitiveAccountValues.add(v)
|
|
33
|
+
})
|
|
34
|
+
return values
|
|
35
|
+
}
|
|
36
|
+
/** Provider uses absolute Unix seconds for numbers and absolute dates for strings. */
|
|
37
|
+
export function earliestRefreshAt(value: unknown): number | undefined {
|
|
38
|
+
const n =
|
|
39
|
+
typeof value === 'number' ? value * 1000 : typeof value === 'string' ? Date.parse(value) : NaN
|
|
40
|
+
return Number.isFinite(n) ? n : undefined
|
|
41
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { sensitiveAccountValues } from './sensitive'
|
|
3
|
+
import {
|
|
4
|
+
constants,
|
|
5
|
+
closeSync,
|
|
6
|
+
fstatSync,
|
|
7
|
+
fsyncSync,
|
|
8
|
+
lstatSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
openSync,
|
|
11
|
+
readFileSync,
|
|
12
|
+
renameSync,
|
|
13
|
+
unlinkSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from 'node:fs'
|
|
16
|
+
import { dirname, join } from 'node:path'
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
|
+
import type { Account } from '../config/accounts'
|
|
19
|
+
import { chatgptStateSchema, credentialValues, type ChatGPTState } from './chatgpt-state'
|
|
20
|
+
|
|
21
|
+
export interface LocalCredential {
|
|
22
|
+
version: 1
|
|
23
|
+
generation: string
|
|
24
|
+
descriptor: Account
|
|
25
|
+
state: ChatGPTState
|
|
26
|
+
status: 'ready' | 'refreshing' | 'failed'
|
|
27
|
+
owner?: string
|
|
28
|
+
ownerPid?: number
|
|
29
|
+
}
|
|
30
|
+
const error = () =>
|
|
31
|
+
new Error('ChatGPT credential storage unavailable; check permissions and sign in again')
|
|
32
|
+
/** Shared main-checkout state. All operations fail closed on unsafe existing files. */
|
|
33
|
+
export class LocalCredentials {
|
|
34
|
+
readonly directory: string
|
|
35
|
+
readonly sensitive = new Set<string>()
|
|
36
|
+
constructor(stateRoot: string) {
|
|
37
|
+
this.directory = join(stateRoot, 'accounts')
|
|
38
|
+
}
|
|
39
|
+
private prepare() {
|
|
40
|
+
mkdirSync(dirname(this.directory), { recursive: true, mode: 0o700 })
|
|
41
|
+
const parent = lstatSync(dirname(this.directory))
|
|
42
|
+
if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.())
|
|
43
|
+
throw error()
|
|
44
|
+
mkdirSync(this.directory, { mode: 0o700, recursive: true })
|
|
45
|
+
const info = lstatSync(this.directory)
|
|
46
|
+
if (
|
|
47
|
+
!info.isDirectory() ||
|
|
48
|
+
info.isSymbolicLink() ||
|
|
49
|
+
(info.mode & 0o777) !== 0o700 ||
|
|
50
|
+
info.uid !== process.getuid?.()
|
|
51
|
+
)
|
|
52
|
+
throw error()
|
|
53
|
+
}
|
|
54
|
+
private path(name: string) {
|
|
55
|
+
return join(this.directory, `${Buffer.from(name).toString('hex')}.json`)
|
|
56
|
+
}
|
|
57
|
+
private read<T>(path: string): T | undefined {
|
|
58
|
+
this.prepare()
|
|
59
|
+
let fd: number
|
|
60
|
+
try {
|
|
61
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW)
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if ((e as NodeJS.ErrnoException).code === 'ENOENT') return undefined
|
|
64
|
+
throw error()
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
const info = fstatSync(fd)
|
|
68
|
+
if (
|
|
69
|
+
!info.isFile() ||
|
|
70
|
+
(info.mode & 0o777) !== 0o600 ||
|
|
71
|
+
info.uid !== process.getuid?.() ||
|
|
72
|
+
info.size > 300000
|
|
73
|
+
)
|
|
74
|
+
throw error()
|
|
75
|
+
return JSON.parse(readFileSync(fd, 'utf8')) as T
|
|
76
|
+
} catch {
|
|
77
|
+
throw error()
|
|
78
|
+
} finally {
|
|
79
|
+
closeSync(fd)
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
private write(path: string, value: unknown) {
|
|
83
|
+
this.prepare()
|
|
84
|
+
this.read(path)
|
|
85
|
+
const temporary = `${path}.${randomUUID()}`
|
|
86
|
+
const fd = openSync(temporary, 'wx', 0o600)
|
|
87
|
+
try {
|
|
88
|
+
writeFileSync(fd, JSON.stringify(value))
|
|
89
|
+
fsyncSync(fd)
|
|
90
|
+
} finally {
|
|
91
|
+
closeSync(fd)
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
renameSync(temporary, path)
|
|
95
|
+
} finally {
|
|
96
|
+
try {
|
|
97
|
+
unlinkSync(temporary)
|
|
98
|
+
} catch {
|
|
99
|
+
/* moved */
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const directory = openSync(this.directory, constants.O_RDONLY)
|
|
103
|
+
try {
|
|
104
|
+
fsyncSync(directory)
|
|
105
|
+
} finally {
|
|
106
|
+
closeSync(directory)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** SQLite's filesystem lock is released by the OS on process death.
|
|
110
|
+
* Only locking lives here; the protected atomic records remain authoritative. */
|
|
111
|
+
locked<T>(_name: string, operation: () => T): T {
|
|
112
|
+
this.prepare()
|
|
113
|
+
const path = join(this.directory, 'locks.sqlite')
|
|
114
|
+
try {
|
|
115
|
+
const fd = openSync(path, 'wx', 0o600)
|
|
116
|
+
closeSync(fd)
|
|
117
|
+
} catch (e) {
|
|
118
|
+
if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw error()
|
|
119
|
+
}
|
|
120
|
+
const info = lstatSync(path)
|
|
121
|
+
if (
|
|
122
|
+
!info.isFile() ||
|
|
123
|
+
info.isSymbolicLink() ||
|
|
124
|
+
(info.mode & 0o777) !== 0o600 ||
|
|
125
|
+
info.uid !== process.getuid?.()
|
|
126
|
+
)
|
|
127
|
+
throw error()
|
|
128
|
+
const db = new Database(path)
|
|
129
|
+
try {
|
|
130
|
+
db.exec('PRAGMA busy_timeout=1000')
|
|
131
|
+
db.exec('BEGIN IMMEDIATE')
|
|
132
|
+
try {
|
|
133
|
+
const result = operation()
|
|
134
|
+
db.exec('COMMIT')
|
|
135
|
+
return result
|
|
136
|
+
} catch (e) {
|
|
137
|
+
db.exec('ROLLBACK')
|
|
138
|
+
throw e
|
|
139
|
+
}
|
|
140
|
+
} finally {
|
|
141
|
+
db.close()
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
hostId(): string {
|
|
145
|
+
return this.locked('__host', () => {
|
|
146
|
+
const path = join(this.directory, 'host.json')
|
|
147
|
+
const old = this.read<{ id: string }>(path)
|
|
148
|
+
if (old) {
|
|
149
|
+
if (!/^urn:uuid:[0-9a-f-]{36}$/.test(old.id)) throw error()
|
|
150
|
+
return old.id
|
|
151
|
+
}
|
|
152
|
+
const id = `urn:uuid:${randomUUID()}`
|
|
153
|
+
this.write(path, { id })
|
|
154
|
+
return id
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
load(name: string): LocalCredential | undefined {
|
|
158
|
+
const record = this.read<LocalCredential>(this.path(name))
|
|
159
|
+
if (!record) return undefined
|
|
160
|
+
if (
|
|
161
|
+
record.version !== 1 ||
|
|
162
|
+
typeof record.generation !== 'string' ||
|
|
163
|
+
!['ready', 'refreshing', 'failed'].includes(record.status) ||
|
|
164
|
+
record.descriptor.kind !== 'chatgpt-subscription'
|
|
165
|
+
)
|
|
166
|
+
throw error()
|
|
167
|
+
record.state = chatgptStateSchema.parse(record.state)
|
|
168
|
+
credentialValues(record.state).forEach((v) => {
|
|
169
|
+
this.sensitive.add(v)
|
|
170
|
+
sensitiveAccountValues.add(v)
|
|
171
|
+
})
|
|
172
|
+
return record
|
|
173
|
+
}
|
|
174
|
+
save(name: string, record: LocalCredential): void {
|
|
175
|
+
credentialValues(record.state).forEach((v) => {
|
|
176
|
+
this.sensitive.add(v)
|
|
177
|
+
sensitiveAccountValues.add(v)
|
|
178
|
+
})
|
|
179
|
+
this.write(this.path(name), record)
|
|
180
|
+
}
|
|
181
|
+
install(name: string, descriptor: Account, state: ChatGPTState): void {
|
|
182
|
+
this.locked(name, () => {
|
|
183
|
+
const old = this.load(name)
|
|
184
|
+
this.save(name, {
|
|
185
|
+
version: 1,
|
|
186
|
+
generation: randomUUID(),
|
|
187
|
+
descriptor,
|
|
188
|
+
state,
|
|
189
|
+
status: 'ready',
|
|
190
|
+
...(old?.owner ? { owner: old.owner, ownerPid: old.ownerPid } : {}),
|
|
191
|
+
})
|
|
192
|
+
})
|
|
193
|
+
}
|
|
194
|
+
}
|