@ref0/sdk 0.0.0-stage → 0.6.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,376 @@
1
- # Temporary Holding Version
1
+ # @ref0/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ What a repo's `.ref0/` code imports to run on ref0, the Git platform for agents, and ref0's HTTP client.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ cd .ref0
9
+ pnpm add @ref0/sdk zod@^4
10
+ ```
11
+
12
+ Its types are built on Effect's, which need `"lib": ["ESNext"]` in `tsconfig.json`, or `skipLibCheck`. Checks' params and called workflows' inputs use zod 4.
13
+
14
+ Each TypeScript block below is a whole file. The path on its first line is relative to the repo's root. Pip writes the files, and Mo is the person accountable for the thread in these examples.
15
+
16
+ ## 1. A gate reads what changed
17
+
18
+ `.ref0/gate.ts` says what a change needs before it merges. Pip's gate reads the root `package.json` on both sides of the change and asks for `dependencies` only when a dependency changed.
19
+
20
+ ```ts
21
+ // .ref0/gate.ts
22
+ import { approval, gate, local, passkey, review } from '@ref0/sdk';
23
+ import { z } from 'zod';
24
+ import e2e from './checks/e2e';
25
+ import unit from './checks/unit';
26
+
27
+ const manifest = z.object({
28
+ dependencies: z.record(z.string(), z.string()).default({}),
29
+ devDependencies: z.record(z.string(), z.string()).default({}),
30
+ optionalDependencies: z.record(z.string(), z.string()).default({}),
31
+ peerDependencies: z.record(z.string(), z.string()).default({}),
32
+ });
33
+
34
+ export default gate(async ({ change }) => {
35
+ const [before, after] = await Promise.all([
36
+ change.before.readJSON({ path: 'package.json' }),
37
+ change.after.readJSON({ path: 'package.json' }),
38
+ ]);
39
+ const was = manifest.parse(before ?? {});
40
+ const next = manifest.parse(after ?? {});
41
+ const moved = Object.entries(was).some(([field, dependencies]) => {
42
+ const current = next[field as keyof typeof next];
43
+
44
+ return Object.keys({ ...dependencies, ...current }).some(
45
+ (name) => dependencies[name] !== current[name],
46
+ );
47
+ });
48
+
49
+ return [
50
+ review(),
51
+ moved && approval('dependencies'),
52
+ change.touches('src/billing/**') && approval('billing'),
53
+ !change.only('**/*.md') && [local(unit()), passkey.check(local(e2e()))],
54
+ ];
55
+ });
56
+ ```
57
+
58
+ The comparison catches added, removed and changed versions in the four dependency fields. A change to scripts alone asks no dependency approval. A repo with other manifests or install configuration needs to cover those files too.
59
+
60
+ A gate returns needs. `review()` needs a review with no blocking finding, `approval('billing')` needs a holder of that permission, and `unit()` needs a successful run of that check. Story 5 explains the `local` and `passkey.check` wrappers. ref0 skips false, null and undefined items and flattens nested lists. Its floor adds needs the gate can't lower.
61
+
62
+ ref0 runs the gate in an isolate with no network, a fixed clock and seeded randomness. `change.before` is the base's tree, and `change.after` is the expected tree. Their reads are recorded with the version. A decision reads at most 200 objects, at most 1 MiB each and 8 MiB in all. A read past a bound fails the decision.
63
+
64
+ ## 2. A check decides who may start it
65
+
66
+ A check is a file in `.ref0/checks/`, named by its file. It judges a tree and returns a conclusion. Pip's e2e check limits each agent to ten new runs a day and three an hour, across both browsers.
67
+
68
+ ```ts
69
+ // .ref0/checks/e2e.ts
70
+ import { allow, check, oneOf, refuse, text } from '@ref0/sdk';
71
+ import { z } from 'zod';
72
+ import node from '../sandboxes/node';
73
+
74
+ export default check({
75
+ description: 'End-to-end tests for one browser',
76
+ params: z.object({ browser: oneOf(['chromium', 'webkit']) }),
77
+ on: ['change', 'tip'],
78
+ start: ({ actor, params, runs, now }) => {
79
+ const own = runs.filter((run) => run.actor.kind === actor.kind && run.actor.id === actor.id);
80
+ const recent = own.filter((run) => run.startedAt > now - 60 * 60 * 1000);
81
+
82
+ return [
83
+ actor.kind === 'agent' && own.length >= 10
84
+ ? refuse(
85
+ text`Ten e2e runs a day each. Reuse a result instead of starting ${params.browser}`,
86
+ )
87
+ : allow(),
88
+ actor.kind === 'agent' && recent.length >= 3
89
+ ? refuse(
90
+ text`Three e2e runs an hour each. Reuse a result instead of starting ${params.browser}`,
91
+ )
92
+ : allow(),
93
+ ];
94
+ },
95
+ run: async ({ params, step }) => {
96
+ const { exitCode } = await node.run(step, 'e2e', {}, (sb) =>
97
+ sb.exec(['pnpm', 'exec', 'playwright', 'test', '--project', params.browser]),
98
+ );
99
+
100
+ return { conclusion: exitCode === 0 ? 'success' : 'failure' };
101
+ },
102
+ });
103
+ ```
104
+
105
+ `oneOf` makes one check run for each value unless the start supplies that param. `now` and each run's `startedAt` are milliseconds since the epoch. `runs` covers the check's last day, including new runs admitted earlier in the same start. A run the starter can't read hides its details, but still counts.
106
+
107
+ A start rule returns a list. Any `refuse(text)` refuses with its words. Otherwise, `allow()` or an empty list allows. ref0's own starts for the gate and the queue's tip bypass the rule, as do starts answered by reuse or a run already going. `on` says when ref0 starts the check itself, here on a change and on the queue's tip. `on: []` leaves starts to people and code.
108
+
109
+ The sandbox is another whole file. Its setup installs the repo's dependencies before a session opens. The example assumes the repo has Playwright browser projects named `chromium` and `webkit`.
110
+
111
+ ```ts
112
+ // .ref0/sandboxes/node.ts
113
+ import { sandbox } from '@ref0/sdk';
114
+
115
+ export default sandbox({
116
+ image: 'node-24',
117
+ cache: { inputs: ['package.json', 'pnpm-lock.yaml'] },
118
+ setup: ['pnpm install --frozen-lockfile'],
119
+ egress: { setup: ['registry.npmjs.org'] },
120
+ });
121
+ ```
122
+
123
+ Here is the unit check that the gate needs. The repo supplies its `test:unit` script.
124
+
125
+ ```ts
126
+ // .ref0/checks/unit.ts
127
+ import { check } from '@ref0/sdk';
128
+ import node from '../sandboxes/node';
129
+
130
+ export default check({
131
+ description: 'Unit tests',
132
+ run: async ({ step }) => {
133
+ const { exitCode } = await node.run(step, 'unit tests', {}, (sb) =>
134
+ sb.exec(['pnpm', 'run', 'test:unit']),
135
+ );
136
+
137
+ return { conclusion: exitCode === 0 ? 'success' : 'failure' };
138
+ },
139
+ });
140
+ ```
141
+
142
+ A check reads the tree it judges through `repo.readFile`, `readText`, `readJSON` and `readTree`. It opens a sandbox through `run(step, name, options, work)`. ref0 reads `description`, `timeout`, `on` and `reuse` from their literals. `params`, `output`, `start` and `run` are code.
143
+
144
+ ## 3. A workflow waits for Mo
145
+
146
+ A called workflow has `input` and a `title`. This one asks Mo whether to spend on e2e, then asks for Mo's passkey yes to one statement. Mo is the run's accountable person, so both requests use `'accountable'`.
147
+
148
+ ```ts
149
+ // .ref0/workflows/approve-e2e.ts
150
+ import { allow, ask, passkey, refuse, text, workflow } from '@ref0/sdk';
151
+ import { z } from 'zod';
152
+
153
+ export default workflow({
154
+ input: z.object({ browser: z.string() }),
155
+ title: ({ input }) => text`Approve e2e on ${input.browser}`,
156
+ permissions: { ask: ['accountable'], budgets: { asks: 2 } },
157
+ run: async ({ input, step }) => {
158
+ const answer = await ask.run(step, {
159
+ to: 'accountable',
160
+ key: 'e2e-cost',
161
+ question: text`Run e2e on ${input.browser}?`,
162
+ answers: [
163
+ { key: 'run', title: text`Run it`, detail: text`About $4 and 12 minutes` },
164
+ { key: 'skip', title: text`Skip`, detail: text`Keep the current result` },
165
+ ],
166
+ lean: 'skip',
167
+ deadline: '30 minutes',
168
+ });
169
+ if (answer.key !== 'run') return refuse(text`Mo skipped this e2e run`);
170
+
171
+ const signed = await passkey.run(step, {
172
+ from: 'accountable',
173
+ statement: text`Spend about $4 on e2e (${input.browser})`,
174
+ deadline: '30 minutes',
175
+ });
176
+
177
+ return signed.approved ? allow() : refuse(text`No passkey approval for e2e`);
178
+ },
179
+ });
180
+ ```
181
+
182
+ `ask.run` is a step of its own. It waits for `{ key, by, via, at }`. At its deadline it returns the lean with `via: 'deadline'` and no `by`. It offers two to five answers, and a run uses each ask key once. A refused or withdrawn ask throws `AskRefused`.
183
+
184
+ `passkey.run` is also a step of its own. Only the person in their approving browser can answer yes with their passkey. The result has `approved`, `at` and, when someone answered, `by`. A deadline answers no. `from` can also name `{ person: 'mo' }` or `{ permission: 'deploy' }`, with `person` or `permission` in `permissions.ask`. Agents have no passkey.
185
+
186
+ Call both leaves outside `step.do` callbacks. Each request spends from the workflow's `asks` budget. Deadlines range from a minute to a day, bounded by the run's remaining day. A called workflow parses its input with one `z.object` and returns JSON to its caller.
187
+
188
+ ## 4. A start waits for that workflow
189
+
190
+ A second check can use the same sandbox command while its start waits for `approve-e2e`. An agent's start calls the workflow's handle with `{ browser }`.
191
+
192
+ ```ts
193
+ // .ref0/checks/approved-e2e.ts
194
+ import { allow, check, oneOf } from '@ref0/sdk';
195
+ import { z } from 'zod';
196
+ import node from '../sandboxes/node';
197
+ import approveE2e from '../workflows/approve-e2e';
198
+
199
+ export default check({
200
+ description: 'End-to-end tests with a person approving an agent start',
201
+ params: z.object({ browser: oneOf(['chromium', 'webkit']) }),
202
+ on: [],
203
+ start: ({ actor, params: { browser } }) => [
204
+ actor.kind === 'agent' ? approveE2e({ browser }) : allow(),
205
+ ],
206
+ run: async ({ params, step }) => {
207
+ const { exitCode } = await node.run(step, 'e2e', {}, (sb) =>
208
+ sb.exec(['pnpm', 'exec', 'playwright', 'test', '--project', params.browser]),
209
+ );
210
+
211
+ return { conclusion: exitCode === 0 ? 'success' : 'failure' };
212
+ },
213
+ });
214
+ ```
215
+
216
+ The start holds no check run while it waits. Every called workflow must return `allow()` before ref0 starts the check. A refusal, a failed run or any other output refuses the start. Another start of the same check, params and tree joins that wait.
217
+
218
+ From an agent session on Mo's thread, start one browser:
219
+
220
+ ```sh
221
+ ref0 run approved-e2e --thread pip/shop#3 --param browser=webkit
222
+ ```
223
+
224
+ After Mo answers the ask, while the passkey request is still open, the command shows a tree like this:
225
+
226
+ ```text
227
+ approved-e2e (webkit) · waiting, until 2026-10-23 10:00 UTC · startwait_01k6zt7m0yf8q2v3w4x5y6z7ab
228
+ └─ Approve e2e on `webkit` · going · approve-e2e.ts
229
+ ├─ ask · mo answered "Run it" · 2m ago
230
+ └─ passkey · waiting on mo · "Spend about $4 on e2e (`webkit`)" · 1m ago
231
+ ```
232
+
233
+ The command waits by default and prints the tree again when it changes. After nine minutes it exits with instructions to wait again or cancel. `--no-wait` returns while the start is waiting. Cancelling the start cancels its called runs.
234
+
235
+ ## 5. Run a check on Pip's machine
236
+
237
+ On an attached machine, in a clean checkout of a thread's expected tree:
238
+
239
+ ```sh
240
+ ref0 run unit --local --thread pip/shop#3
241
+ ```
242
+
243
+ The CLI runs the parts requested by the open version's gate, with their params and code from ref0. It runs the sandbox's setup in the checkout, then executes commands on the machine. It reports a local result with its signer and attachment. Outside an agent session, add `--agent pip/claude` to select the attachment and approve the read and reports. `exec` and `serve` work locally. A local check that calls `browse` or `push` refuses by name.
244
+
245
+ Local results appear beside ref0's runs. A plain check need still takes only ref0's own runs.
246
+
247
+ The gate in story 1 takes local results with `local(unit())` and `passkey.check(local(e2e()))`. A local run from the version's thread can meet a need that takes `local` when it has the same check-run identity. ref0 leaves those parts for the local run unless another need requires ref0's own run.
248
+
249
+ The newest finished local run counts unless a ref0 failure stands. A newer local run replaces an earlier one, and a newer ref0 pass counts instead. A ref0 failure stands until an admin overrides it, even if a later run passes.
250
+
251
+ `passkey.check` waits for the person behind the counted run to say yes over its result with their passkey. For a local run, that's the signer's person. For ref0's run, it's the version's accountable person. `{ from }` asks someone else, as in `passkey.check(local(e2e()), { from: { person: 'mo' } })`. The statement names the check-run identity, conclusion and outputs' hash. A newer counted run needs a new yes.
252
+
253
+ When ref0 runs the same check-run identity as a signed success and it fails twice, the signer stops answering that check. For `local`, ref0 revokes the attachment. For `passkey.check`, it revokes the person whose yes stood over the result. An admin restores the signer with `ref0 checks signers restore`, using `--person` for a person. The floor's needs and the queue's tip take only ref0's runs.
254
+
255
+ ## Event workflows and actions
256
+
257
+ An event workflow has `on` instead of `input`. ref0 runs it from `main` and checks each action against its declared `permissions`. This workflow comments when a change to contracts merges.
258
+
259
+ ```ts
260
+ // .ref0/workflows/docs.ts
261
+ import { text, workflow } from '@ref0/sdk';
262
+
263
+ export default workflow({
264
+ on: ['pull_request.merged'],
265
+ where: { 'pull_request.merged': { paths: ['packages/contracts/**'] } },
266
+ permissions: { comment: ['accountable'] },
267
+ run: async ({ event, step, ref0 }) => {
268
+ await step.do('tell the accountable person', () =>
269
+ ref0.comments.create({ to: 'accountable', text: text`Merged ${event.pullRequest}` }),
270
+ );
271
+ },
272
+ });
273
+ ```
274
+
275
+ ref0 reads `on`, `where` and `permissions` from their literals. Each piece of text is a `text` template ref0 has read in the source. A run fills in its values, never its words. Actions run inside `step.do`, and ref0 keeps their answers so replay doesn't act twice. Check an action's answer for a refusal before continuing.
276
+
277
+ A workflow calls a called workflow with `.run(step, input)`. That call runs outside `step.do`, starts a run of its own and waits for its output. `where` on a check run selects `main` or a thread's head, separately from a check's `on`. Here, `where: 'thread'` selects the head of the thread that became active.
278
+
279
+ ```ts
280
+ // .ref0/workflows/test-thread.ts
281
+ import { text, workflow } from '@ref0/sdk';
282
+ import e2e from '../checks/e2e';
283
+ import approveE2e from './approve-e2e';
284
+
285
+ export default workflow({
286
+ on: ['thread.stage.moved'],
287
+ where: { 'thread.stage.moved': { to: ['active'] } },
288
+ permissions: { checks: 'run', comment: ['accountable'] },
289
+ run: async ({ step, ref0 }) => {
290
+ const decision = await approveE2e.run(step, { browser: 'webkit' });
291
+ if (decision.kind !== 'allow') return;
292
+
293
+ const results = await e2e.run(step, { where: 'thread', params: { browser: 'webkit' } });
294
+ await step.do('report', () =>
295
+ ref0.comments.create({ to: 'accountable', text: text`E2e finished ${results.length} runs` }),
296
+ );
297
+ },
298
+ });
299
+ ```
300
+
301
+ A called workflow's permissions are its own. It ships in the caller's version and is approved with it. `.run` throws `CalledRunFailed` if ref0 refuses the call or the run fails. A replay finds the same child for the same call and input. A call with different input makes another child.
302
+
303
+ `ref0.pr.needs.add` adds a need to an open pull request. This called workflow takes its number as input and declares `needs: 'add'`.
304
+
305
+ ```ts
306
+ // .ref0/workflows/billing-review.ts
307
+ import { approval, text, workflow } from '@ref0/sdk';
308
+ import { z } from 'zod';
309
+
310
+ export default workflow({
311
+ input: z.object({ pullRequest: z.number().int().positive() }),
312
+ title: ({ input }) => text`Billing approval for pull request ${input.pullRequest}`,
313
+ permissions: { needs: 'add' },
314
+ run: async ({ input, step, ref0 }) => {
315
+ await step.do('ask for billing approval', () =>
316
+ ref0.pr.needs.add(input.pullRequest, approval('billing')),
317
+ );
318
+ },
319
+ });
320
+ ```
321
+
322
+ `ref0.pr.open` opens a pull request from a fork the workflow has pushed. This repo supplies an `update-docs` script. The workflow gets its own fork, changes it in a sandbox, pushes, then opens the pull request.
323
+
324
+ ```ts
325
+ // .ref0/workflows/update-docs.ts
326
+ import { text, workflow } from '@ref0/sdk';
327
+ import node from '../sandboxes/node';
328
+
329
+ export default workflow({
330
+ on: ['pull_request.merged'],
331
+ where: { 'pull_request.merged': { paths: ['packages/contracts/**'] } },
332
+ permissions: { code: 'write', budgets: { forks: 1, pushes: 1, threads: 1 } },
333
+ run: async ({ step, ref0 }) => {
334
+ const fork = await step.do('fork', () => ref0.forks.create());
335
+ if (fork.kind !== 'fork') return;
336
+
337
+ const pushed = await node.run(step, 'update docs', { tree: fork }, async (sb) => {
338
+ const result = await sb.exec(['pnpm', 'run', 'update-docs']);
339
+ if (result.exitCode !== 0) throw new Error(result.stderr);
340
+
341
+ return await sb.push({ message: 'Update the contracts docs' });
342
+ });
343
+ if (pushed.kind !== 'pushed') return;
344
+
345
+ await step.do('open pull request', () =>
346
+ ref0.pr.open({ fork, title: text`Update the contracts docs` }),
347
+ );
348
+ },
349
+ });
350
+ ```
351
+
352
+ ## Versions
353
+
354
+ The package a repo installs gives its editor the types. ref0 runs its own build of the same major version in its place.
355
+
356
+ ## A check that browses
357
+
358
+ A check that imports `@ref0/sdk/browser` borrows a browser with `sb.browse`. The published module holds only its types and an `expect` that throws. ref0 loads its own browser module in its place.
359
+
360
+ Its types are Playwright's, from the version ref0 pins, an optional peer. Install it beside the SDK, and resolve modules as a bundler does, which Playwright's types need:
361
+
362
+ ```sh
363
+ pnpm add -D @cloudflare/playwright@1.3.6
364
+ ```
365
+
366
+ ```json
367
+ { "compilerOptions": { "module": "preserve", "moduleResolution": "bundler" } }
368
+ ```
369
+
370
+ ## The client
371
+
372
+ `@ref0/sdk/client` is ref0's HTTP client, which ref0's web app and CLI use.
373
+
374
+ ## License
375
+
376
+ Apache 2.0