autocode-skill 0.0.0-stage → 0.1.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/INSTALL.md +57 -0
- package/LICENSE +202 -0
- package/README.md +43 -2
- package/SKILL.md +20 -0
- package/USAGE.md +58 -0
- package/agents/openai.yaml +4 -0
- package/assets/templates/mixed-provider.js +10 -0
- package/assets/templates/parallel-scout.js +6 -0
- package/assets/templates/review-and-verify.js +15 -0
- package/package.json +43 -4
- package/references/authoring.md +30 -0
- package/scripts/autocode.mjs +56 -0
- package/scripts/claude-adapter.mjs +39 -0
- package/scripts/codex-adapter.mjs +28 -0
- package/scripts/runtime.mjs +243 -0
package/INSTALL.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Install Autocode
|
|
2
|
+
|
|
3
|
+
Autocode needs Node.js 20 or newer and authentication for whichever provider you use.
|
|
4
|
+
|
|
5
|
+
## Install the npm package
|
|
6
|
+
|
|
7
|
+
After the stable `v0.1.0` npm release, install the package globally, then link its skill files into both hosts:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -g autocode-skill
|
|
11
|
+
AUTOCODE_DIR="$(npm root -g)/autocode-skill"
|
|
12
|
+
mkdir -p ~/.codex/skills ~/.claude/skills
|
|
13
|
+
ln -s "$AUTOCODE_DIR" ~/.codex/skills/autocode
|
|
14
|
+
ln -s "$AUTOCODE_DIR" ~/.claude/skills/autocode
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The npm install provides the `autocode` command and both native SDK dependencies. The links make `SKILL.md` discoverable to Codex and Claude. If either skill path already exists, inspect it and move or replace it deliberately before creating the link; keep backups outside the `skills` directories so they are not discovered as duplicate skills.
|
|
18
|
+
|
|
19
|
+
## Install from a checkout
|
|
20
|
+
|
|
21
|
+
The GitHub repository currently requires access and an authorized SSH key. The pinned SDK dependencies are in `package-lock.json`.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
git clone git@github.com:postfix/autocode.git ~/.local/share/autocode
|
|
25
|
+
cd ~/.local/share/autocode
|
|
26
|
+
npm ci
|
|
27
|
+
npm test
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Point both hosts at the same checkout:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
mkdir -p ~/.codex/skills ~/.claude/skills
|
|
34
|
+
ln -s ~/.local/share/autocode ~/.codex/skills/autocode
|
|
35
|
+
ln -s ~/.local/share/autocode ~/.claude/skills/autocode
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Start a new Codex or Claude session to load the skill. In Codex, invoke it with `$autocode` followed by your task; in Claude, ask it to use the `autocode` skill. Codex and Claude can each author a workflow; `--provider` and per-call `provider` choose who executes its agent tasks.
|
|
39
|
+
|
|
40
|
+
## Check the installation
|
|
41
|
+
|
|
42
|
+
For a checkout, run `npm test` in the checkout. For an npm installation, run `command -v autocode` and confirm both `~/.codex/skills/autocode/SKILL.md` and `~/.claude/skills/autocode/SKILL.md` exist.
|
|
43
|
+
|
|
44
|
+
Then ask Codex to exercise the installed skill:
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
$autocode Create and run a read-only workflow that asks one Codex agent to return exactly OK, then report its result and failures.
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
That live check consumes tokens. To check the runner directly from a checkout, use:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
node scripts/autocode.mjs run assets/templates/parallel-scout.js \
|
|
54
|
+
--provider codex --args '{"questions":["Return exactly OK"]}'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
For a test without a provider call, the checkout's `npm test` runs the local suite with SDK fakes.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Autocode
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Autocode is a skill for Codex and Claude that writes and runs JavaScript workflows to coordinate agents. A workflow can fan out tasks, run pipelines, call child workflows, report progress, enforce a soft output-token budget, and resume completed agent calls from its journal. The runner uses the native `@openai/codex-sdk` and `@anthropic-ai/claude-agent-sdk` packages.
|
|
4
|
+
|
|
5
|
+
The agent authoring a workflow can use a capable model and high effort. Each delegated `agent()` call can then choose a smaller model, lower effort, or a different provider.
|
|
6
|
+
|
|
7
|
+
## Quick start
|
|
8
|
+
|
|
9
|
+
Follow [INSTALL.md](INSTALL.md) to install the skill from npm or a checkout. Then ask Codex:
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
$autocode Review the changes in this repository with parallel agents, independently verify each finding, and report the evidence.
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
In Claude, ask it to use the `autocode` skill with the same request. The skill writes a workflow for the task, runs it through the local SDK adapters, and reports the results and failures. Ask for a specific provider, model, or effort level when you want to control delegated calls; the authoring agent can use higher effort than the agents that execute the workflow.
|
|
16
|
+
|
|
17
|
+
## Run a workflow directly
|
|
18
|
+
|
|
19
|
+
To run a bundled template from a checkout with dependencies installed:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
node scripts/autocode.mjs run assets/templates/parallel-scout.js \
|
|
23
|
+
--provider codex \
|
|
24
|
+
--args '{"questions":["Find likely bugs in src/","Check the README examples"]}'
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The command prints progress to stderr and a JSON result to stdout. [USAGE.md](USAGE.md) explains skill use, the workflow API, mixed-provider calls, resume, limits, and permission modes. The [mixed-provider template](assets/templates/mixed-provider.js) demonstrates provider, model, and effort selection per task.
|
|
28
|
+
|
|
29
|
+
The npm package is named `autocode-skill` because `autocode` is already occupied on npm. The package installs an `autocode` command and includes the skill files; [release instructions](RELEASING.md) cover the initial MFA bootstrap and subsequent GitHub Trusted Publishing.
|
|
30
|
+
|
|
31
|
+
## What has been tested
|
|
32
|
+
|
|
33
|
+
The package has **47 named test cases across nine passing test files**, including three property tests with 140 generated cases. A clean `npm ci` install and the local suite passed. The tests cover the runner, adapters through native SDK API fakes, command routing, templates, resume, release validation, and npm tarball contents. A local install of the tarball ran the packaged `autocode` command and returned `PACKAGED_OK`. One live read-only Codex SDK call returned `CODEX_NATIVE_OK`, and a live two-agent parallel release review completed through the SDK.
|
|
34
|
+
Invoking the skill from a fresh Codex or Claude session has not yet been verified end to end.
|
|
35
|
+
|
|
36
|
+
**Still untested live on the current Codex SDK path:** structured output, resume after a Codex SDK call, workspace-write behavior, and model switching. Those paths have local tests using SDK fakes or runner fakes, which do not establish live Codex behavior. The mixed live run started Claude through its SDK, but the account returned a weekly usage-limit error; no successful live Claude SDK result has been verified.
|
|
37
|
+
|
|
38
|
+
The project does not claim complete Ultracode parity or 100% branch coverage. `npm run coverage` measured **100% lines, 78.88% branches, and 97.78% functions** in this package.
|
|
39
|
+
|
|
40
|
+
## Scope and provenance
|
|
41
|
+
|
|
42
|
+
Autocode is an independent implementation of local workflow orchestration, released under [Apache-2.0](LICENSE). This repository contains its own code, templates, tests, and authored guidance. Extracted third-party bundle modules and verbatim prompt assets are not included.
|
|
43
|
+
|
|
44
|
+
Run only workflow scripts you trust. Node's VM provides workflow globals but is not a security boundary. The SDKs may start their own local runtimes internally; Autocode calls their programmatic APIs rather than constructing `codex exec` or `claude -p` commands.
|
package/SKILL.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: autocode
|
|
3
|
+
description: Use Autocode when the user asks for a JavaScript multi-agent workflow, mixed Codex and Claude providers, fan-out verification, or a saved orchestration script.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Autocode
|
|
7
|
+
|
|
8
|
+
Author a bounded JavaScript workflow, then run it with Codex, Claude, or both. Use a workflow when the user requests multi-agent orchestration or invokes this skill; agent calls can spend substantial tokens. Plan the task list and expected result before launching. The host agent that writes the workflow can use high effort for design; each `agent()` call can specify a smaller model and lower effort for execution.
|
|
9
|
+
|
|
10
|
+
Read [authoring.md](references/authoring.md) when writing a script. Start from [review-and-verify.js](assets/templates/review-and-verify.js) for independent reviews followed by verification, [parallel-scout.js](assets/templates/parallel-scout.js) for a one-stage sweep, or [mixed-provider.js](assets/templates/mixed-provider.js) to choose provider and model per task. Save the workflow in the project where it will run.
|
|
11
|
+
|
|
12
|
+
From that project directory, run the script with:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
node "$HOME/.codex/skills/autocode/scripts/autocode.mjs" run workflow.js --provider codex --args '{"files":["src/a.js"]}'
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Use `--provider claude` when Claude should execute calls by default. A script can override the provider, model, and effort for each call with `agent(prompt, { provider: 'claude', model: 'haiku', effort: 'low' })`; other calls can use Codex. Both adapters use their native JavaScript SDKs. The command streams progress to stderr, then returns JSON with `result`, `failures`, `logs`, `agentCount`, `outputTokens`, `runId`, and `runDir` on stdout. Pass `--run-dir <dir>` to choose the journal location. Resume with the same directory and `--resume <runId>`; completed calls with unchanged inputs replay from the journal. Use `--budget <tokens>` for a soft output-token target. Both providers default to read-only tools; add `--sandbox workspace-write` only for authorized edits. Inspect failures and results before reporting success.
|
|
19
|
+
|
|
20
|
+
The runner needs Node.js 20+ and authentication for the selected provider. An npm installation includes dependencies and the `autocode` command. For a source checkout, install dependencies with `npm ci --prefix "$HOME/.codex/skills/autocode"`, then run `npm test --prefix "$HOME/.codex/skills/autocode"`. The property tests use `fast-check` and print a replayable seed and shrunk counterexample on failure.
|
package/USAGE.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Using Autocode
|
|
2
|
+
|
|
3
|
+
## Ask the skill to run a task
|
|
4
|
+
|
|
5
|
+
After [installing the skill](INSTALL.md), ask Codex:
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
$autocode Investigate the failing tests in this project in parallel, verify the likely cause, and summarize the evidence.
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
In Claude, ask it to use the `autocode` skill with the same request. The skill authors the JavaScript workflow and runs it. You can ask for Codex, Claude, or both as delegated providers, and specify the model or effort for individual tasks. The authoring agent can use higher effort than the delegated agents. Review the reported `failures` alongside the result.
|
|
12
|
+
|
|
13
|
+
## Write a workflow yourself
|
|
14
|
+
|
|
15
|
+
Start with literal metadata. The remaining JavaScript runs as an async body with `args`, `agent`, `parallel`, `pipeline`, `workflow`, `phase`, `log`, and `budget` available:
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
export const meta = { name: 'inspect', description: 'Inspect two questions' };
|
|
19
|
+
phase('Inspect');
|
|
20
|
+
return await parallel([
|
|
21
|
+
() => agent('Find likely bugs', { provider: 'codex', effort: 'low', label: 'bugs' }),
|
|
22
|
+
() => agent('Check documentation', { provider: 'claude', model: 'haiku', effort: 'low', label: 'docs' }),
|
|
23
|
+
]);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Save the file as `inspect.js`. The host agent can spend more effort designing this workflow; the `model` and `effort` options control each delegated call. Omitting `model` lets the selected SDK choose its configured default.
|
|
27
|
+
|
|
28
|
+
## Run and resume
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
autocode run inspect.js \
|
|
32
|
+
--provider codex --run-dir .codex/autocode-runs/inspect
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The `autocode` command is installed by `npm install -g autocode-skill`. From a source checkout, run `node "$HOME/.codex/skills/autocode/scripts/autocode.mjs"` with the same arguments.
|
|
36
|
+
|
|
37
|
+
`--provider` selects the default for calls without `opts.provider`. Use `--provider claude` to change it. Use `--args '{"target":"src"}'` to supply a JSON value; omitted `args` is `undefined`. `--cwd <directory>` selects the project directory for both SDKs. `--budget <tokens>` sets a soft output-token target: calls already running can make the final total exceed it.
|
|
38
|
+
|
|
39
|
+
The command returns JSON with `result`, `failures`, `logs`, `agentCount`, `outputTokens`, `runId`, and `runDir`. Progress appears on stderr. To resume, run the same script with the same `--run-dir` and `--resume <runId>`. Successful calls whose inputs and branch history match are reused from `journal.jsonl`.
|
|
40
|
+
|
|
41
|
+
## Workflow operations
|
|
42
|
+
|
|
43
|
+
| Operation | Behavior |
|
|
44
|
+
| --- | --- |
|
|
45
|
+
| `agent(prompt, opts?)` | Runs a Codex or Claude SDK agent. `opts` can set `provider`, `model`, `effort`, `schema`, `label`, and `phase`. A root-object JSON Schema requests structured output. |
|
|
46
|
+
| `parallel([() => task, ...])` | Runs branches concurrently and preserves input order. A failing branch yields `null` and appears in `failures`. |
|
|
47
|
+
| `pipeline(items, ...stages)` | Advances each item independently through stages. A `null` or failed item skips later stages. |
|
|
48
|
+
| `workflow(nameOrRef, childArgs?)` | Runs a saved `.codex/workflows/<name>.js` file or `{scriptPath: 'child.js'}`. Children share the queue, budget, and journal; nesting is limited to one level. |
|
|
49
|
+
| `phase(title)`, `log(message)` | Streams progress and records logs. `opts.phase` and `opts.label` identify individual agent calls. |
|
|
50
|
+
| `budget` | Exposes `total`, `spent()`, and `remaining()`. |
|
|
51
|
+
|
|
52
|
+
The runner allows up to 16 concurrent agents, 1,000 agent calls per workflow, and 4,096 items in one `parallel` or `pipeline` call. `agentType` and `isolation: 'worktree'` currently raise explicit errors.
|
|
53
|
+
|
|
54
|
+
## Permissions and templates
|
|
55
|
+
|
|
56
|
+
Both providers default to read-only operation. Pass `--sandbox workspace-write` only when edits are authorized. Codex uses its SDK thread sandbox; Claude receives limited file tools and SDK sandboxing. Inspect the returned `failures` before treating a workflow as successful.
|
|
57
|
+
|
|
58
|
+
Start from [parallel scout](assets/templates/parallel-scout.js), [review and verify](assets/templates/review-and-verify.js), or [mixed provider](assets/templates/mixed-provider.js). The detailed [authoring reference](references/authoring.md) covers deterministic resume and the workflow globals.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const meta = { name: 'mixed-provider', description: 'Ask each specialist with its selected model and provider' };
|
|
2
|
+
phase('Delegate');
|
|
3
|
+
const results = await parallel(args.tasks.map(task => () => agent(task.question, {
|
|
4
|
+
provider: task.provider,
|
|
5
|
+
model: task.model,
|
|
6
|
+
effort: task.effort,
|
|
7
|
+
phase: 'Delegate',
|
|
8
|
+
label: task.label ?? task.question,
|
|
9
|
+
})));
|
|
10
|
+
return args.tasks.map((task, index) => ({ label: task.label ?? task.question, result: results[index] }));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export const meta = { name: 'parallel-scout', description: 'Inspect independent questions in parallel' };
|
|
2
|
+
phase('Scout');
|
|
3
|
+
const findings = await parallel(args.questions.map(question => () =>
|
|
4
|
+
agent(question, { phase: 'Scout' })
|
|
5
|
+
));
|
|
6
|
+
return args.questions.map((question, index) => ({ question, finding: findings[index] }));
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const meta = { name: 'review-and-verify', description: 'Review independent topics and verify each finding' };
|
|
2
|
+
phase('Review');
|
|
3
|
+
const checked = await pipeline(
|
|
4
|
+
args.topics,
|
|
5
|
+
topic => agent(`Review ${topic} and return findings as JSON`, {
|
|
6
|
+
schema: { type: 'object', properties: { findings: { type: 'array', items: { type: 'string' } } }, required: ['findings'] },
|
|
7
|
+
phase: 'Review',
|
|
8
|
+
}),
|
|
9
|
+
review => parallel(review.findings.map(finding => () =>
|
|
10
|
+
agent(`Independently verify this finding: ${finding}`, { phase: 'Verify' })
|
|
11
|
+
.then(verdict => ({ finding, verdict }))
|
|
12
|
+
)),
|
|
13
|
+
);
|
|
14
|
+
log(`Reviewed ${args.topics.length} topics`);
|
|
15
|
+
return checked.flat().filter(Boolean);
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "autocode-skill",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "JavaScript workflow skill for Codex and Claude agents",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/postfix/autocode.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"bin": {
|
|
12
|
+
"autocode": "scripts/autocode.mjs"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"SKILL.md",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"README.md",
|
|
18
|
+
"INSTALL.md",
|
|
19
|
+
"USAGE.md",
|
|
20
|
+
"agents/openai.yaml",
|
|
21
|
+
"references/authoring.md",
|
|
22
|
+
"assets/templates/*.js",
|
|
23
|
+
"scripts/autocode.mjs",
|
|
24
|
+
"scripts/claude-adapter.mjs",
|
|
25
|
+
"scripts/codex-adapter.mjs",
|
|
26
|
+
"scripts/runtime.mjs"
|
|
27
|
+
],
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=20"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"test": "node --test tests/*.test.mjs",
|
|
36
|
+
"coverage": "node --test --experimental-test-coverage tests/*.test.mjs"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"fast-check": "4.8.0"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@anthropic-ai/claude-agent-sdk": "0.3.310",
|
|
43
|
+
"@openai/codex-sdk": "0.164.0"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Autocode workflow authoring
|
|
2
|
+
|
|
3
|
+
Begin each `.js` script with literal metadata:
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
export const meta = { name: 'review-changes', description: 'Review and verify changed files' };
|
|
7
|
+
phase('Review');
|
|
8
|
+
const results = await pipeline(args.files, file => agent(`Review ${file}`));
|
|
9
|
+
return results;
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The script body is an async function. It receives `args`, `agent`, `parallel`, `pipeline`, `workflow`, `phase`, `log`, and `budget`. Omitted `args` is `undefined`; a supplied JSON `null` remains `null`. Return a JSON-serializable result. The runner writes `run.json` and `journal.jsonl` inside the run directory. The earlier `/* autocode {"name":"...","description":"..."} */` header still works. Use trusted scripts: Node's VM is a convenience for workflow globals, not a security boundary.
|
|
13
|
+
|
|
14
|
+
## Calls
|
|
15
|
+
|
|
16
|
+
- `agent(prompt, opts?)` asks a Codex or Claude agent through its JavaScript SDK. It returns final text, or a JSON object if `opts.schema` is a root object JSON Schema. Supported options: `provider: 'codex' | 'claude'`, `schema`, `model`, `effort`, `label`, `phase`. The command's `--provider` sets the default, while `opts.provider` selects one call. Both SDKs support `low`, `medium`, `high`, `xhigh`, and `max` effort; choose a supported model for each provider.
|
|
17
|
+
- `agentType` and `isolation: 'worktree'` currently raise explicit errors in the SDK adapters.
|
|
18
|
+
- `parallel([() => promise, ...])` runs independent tasks and returns results in input order. A failed branch becomes `null`; inspect the top-level `failures` list.
|
|
19
|
+
- `pipeline(items, stage1, stage2, ...)` runs each item through its stages as soon as the prior stage finishes. Each stage receives `(previousResult, originalItem, index)`. A thrown error or `null` result ends that item and yields `null`. Use this for review then verification without a barrier.
|
|
20
|
+
- `phase(title)` and `log(message)` stream progress to CLI stderr as the workflow runs; logs are also returned in the final JSON. Agent starts, completions and failures stream with `opts.label` and `opts.phase` when supplied.
|
|
21
|
+
- `workflow(nameOrRef, childArgs?)` runs a saved `.codex/workflows/<name>.js` script or an explicit `{scriptPath: 'path/to/script.js'}`. Relative script paths resolve from the CLI working directory. Children share the same agent queue, budget and journal, and are limited to one level.
|
|
22
|
+
- `budget.total`, `budget.spent()`, `budget.remaining()` expose the output-token target. It stops additional calls once usage reaches the target. Concurrent calls can exceed it.
|
|
23
|
+
|
|
24
|
+
At most 16 agents run simultaneously across both providers. Each `parallel` or `pipeline` accepts at most 4096 items, and a workflow can make at most 1000 agent calls. A failing agent call rejects inside its branch; `parallel` and `pipeline` turn that branch into `null` and report the error.
|
|
25
|
+
|
|
26
|
+
Use unique prompts and JSON args for reproducible resume. The journal caches successful agent results. A resumed script reuses a completed call when its branch history, prompt, and relevant options match; edits beyond that point run live. After a run, check `failures` and inspect `journal.jsonl` when output looks incomplete.
|
|
27
|
+
|
|
28
|
+
`Date.now()`, `new Date()` without arguments, and `Math.random()` throw inside workflows because they would make replay depend on when the run was resumed. Pass a timestamp or seed in `args` when needed.
|
|
29
|
+
|
|
30
|
+
Autocode reimplements observed local workflow behavior through native Codex and Claude SDK adapters. This public package contains the runnable implementation and authored templates.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { runWorkflow } from './runtime.mjs';
|
|
8
|
+
import { codexAgent } from './codex-adapter.mjs';
|
|
9
|
+
import { claudeAgent } from './claude-adapter.mjs';
|
|
10
|
+
|
|
11
|
+
export async function runAutocode(argv, adapters = { codex: codexAgent, claude: claudeAgent }) {
|
|
12
|
+
if (argv[0] !== 'run' || !argv[1] || argv[1].startsWith('--'))
|
|
13
|
+
throw new Error('usage: autocode run <script.js> [--provider codex|claude] [options]');
|
|
14
|
+
const scriptPath = resolve(argv[1]);
|
|
15
|
+
const flags = {};
|
|
16
|
+
for (let i = 2; i < argv.length; i += 2) {
|
|
17
|
+
if (!argv[i]?.startsWith('--') || argv[i + 1] === undefined) throw new Error(`invalid option: ${argv[i]}`);
|
|
18
|
+
flags[argv[i].slice(2)] = argv[i + 1];
|
|
19
|
+
}
|
|
20
|
+
for (const name of Object.keys(flags))
|
|
21
|
+
if (!['args', 'run-dir', 'resume', 'budget', 'sandbox', 'codex', 'claude', 'provider', 'cwd'].includes(name))
|
|
22
|
+
throw new Error(`unknown option: --${name}`);
|
|
23
|
+
const provider = flags.provider ?? 'codex';
|
|
24
|
+
if (!['codex', 'claude'].includes(provider)) throw new Error(`unknown provider: ${provider}`);
|
|
25
|
+
const cwd = resolve(flags.cwd ?? process.cwd());
|
|
26
|
+
const runDir = resolve(flags['run-dir'] ?? `.codex/autocode-runs/${flags.resume ?? randomUUID()}`);
|
|
27
|
+
const args = flags.args === undefined ? undefined : JSON.parse(flags.args);
|
|
28
|
+
const budget = flags.budget === undefined ? null : Number(flags.budget);
|
|
29
|
+
const sandbox = flags.sandbox ?? 'read-only';
|
|
30
|
+
const result = await runWorkflow({
|
|
31
|
+
script: await readFile(scriptPath, 'utf8'), args, runDir, budget,
|
|
32
|
+
resumeFromRunId: flags.resume,
|
|
33
|
+
onProgress: (event) => process.stderr.write(event.type === 'phase' ?
|
|
34
|
+
`${event.title}\n` : event.type === 'log' ? `${event.message}\n` :
|
|
35
|
+
`${event.phase ? `[${event.phase}] ` : ''}${event.label}: ${event.type.slice(6)}\n`),
|
|
36
|
+
resolveWorkflow: (reference) => readFile(typeof reference === 'string' ?
|
|
37
|
+
join(cwd, '.codex', 'workflows', `${reference}.js`) : resolve(cwd, reference.scriptPath), 'utf8'),
|
|
38
|
+
agent: (prompt, opts, context) => {
|
|
39
|
+
const selected = opts.provider ?? provider;
|
|
40
|
+
if (!['codex', 'claude'].includes(selected)) throw new Error(`unknown provider: ${selected}`);
|
|
41
|
+
return adapters[selected](prompt, { ...opts, sandbox }, {
|
|
42
|
+
...context, cwd, executable: selected === 'codex' ? flags.codex : flags.claude,
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
return { ...result, runDir };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (process.argv[1] && existsSync(process.argv[1]) &&
|
|
50
|
+
realpathSync(process.argv[1]) === fileURLToPath(import.meta.url))
|
|
51
|
+
runAutocode(process.argv.slice(2)).then((result) => {
|
|
52
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
53
|
+
}).catch((error) => {
|
|
54
|
+
process.stderr.write(`autocode: ${error.message}\n`);
|
|
55
|
+
process.exitCode = 1;
|
|
56
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { query } from '@anthropic-ai/claude-agent-sdk';
|
|
2
|
+
|
|
3
|
+
const SUBAGENT_INSTRUCTIONS = 'You are a subagent spawned by an Autocode workflow. Your final response is the return value to the calling script. Complete only the assigned task within existing permissions. Return the requested result directly, without a status confirmation or Markdown fence. Follow the supplied output schema when present.';
|
|
4
|
+
|
|
5
|
+
export async function claudeAgent(prompt, opts = {}, context = {}) {
|
|
6
|
+
if (typeof prompt !== 'string' || !prompt.trim()) throw new TypeError('agent prompt must be non-empty');
|
|
7
|
+
const { query: runQuery = query, executable, cwd = process.cwd(), runDir, signal } = context;
|
|
8
|
+
if (!runDir) throw new TypeError('runDir is required');
|
|
9
|
+
if (opts.agentType !== undefined) throw new TypeError('agentType is unavailable in cross-agent Autocode');
|
|
10
|
+
if (opts.isolation !== undefined) throw new TypeError('Claude SDK adapter does not support worktree isolation');
|
|
11
|
+
const sandbox = opts.sandbox ?? 'read-only';
|
|
12
|
+
if (!['read-only', 'workspace-write'].includes(sandbox)) throw new RangeError('unsupported sandbox mode');
|
|
13
|
+
if (opts.effort !== undefined && !['low', 'medium', 'high', 'xhigh', 'max'].includes(opts.effort))
|
|
14
|
+
throw new RangeError('unsupported effort');
|
|
15
|
+
if (opts.schema && (opts.schema.type !== 'object' || !opts.schema.properties ||
|
|
16
|
+
!Array.isArray(opts.schema.required ?? []))) throw new TypeError('schema must be a JSON object schema');
|
|
17
|
+
const controller = new AbortController();
|
|
18
|
+
if (signal?.aborted) controller.abort(signal.reason);
|
|
19
|
+
signal?.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
|
|
20
|
+
const options = { cwd, model: opts.model, effort: opts.effort,
|
|
21
|
+
permissionMode: sandbox === 'read-only' ? 'dontAsk' : 'acceptEdits',
|
|
22
|
+
permissionPrompts: 'none',
|
|
23
|
+
tools: sandbox === 'read-only' ? ['Read', 'Grep', 'Glob'] : ['Read', 'Grep', 'Glob', 'Edit', 'Write'],
|
|
24
|
+
sandbox: { enabled: true }, settingSources: [], strictMcpConfig: true,
|
|
25
|
+
abortController: controller,
|
|
26
|
+
...(executable ? { pathToClaudeCodeExecutable: executable } : {}),
|
|
27
|
+
...(opts.schema ? { outputFormat: { type: 'json_schema', schema: opts.schema } } : {}),
|
|
28
|
+
};
|
|
29
|
+
let completed;
|
|
30
|
+
for await (const message of runQuery({ prompt: `${SUBAGENT_INSTRUCTIONS}\n\nTask:\n${prompt}`, options }))
|
|
31
|
+
if (message.type === 'result') completed = message;
|
|
32
|
+
if (!completed || completed.subtype !== 'success' || completed.is_error)
|
|
33
|
+
throw new Error(`Claude SDK failed: ${completed?.subtype ?? 'no result'}`);
|
|
34
|
+
const result = opts.schema ? completed.structured_output : completed.result;
|
|
35
|
+
if (opts.schema && (typeof result !== 'object' || result === null || Array.isArray(result)))
|
|
36
|
+
throw new TypeError('Claude returned a non-object structured result');
|
|
37
|
+
const usage = completed.usage?.output_tokens ?? 0;
|
|
38
|
+
return { result, outputTokens: Number.isSafeInteger(usage) && usage >= 0 ? usage : 0 };
|
|
39
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Codex } from '@openai/codex-sdk';
|
|
2
|
+
|
|
3
|
+
const SUBAGENT_INSTRUCTIONS = 'You are a subagent spawned by an Autocode workflow. Your final response is the return value to the calling script. Complete only the assigned task within existing permissions. Return the requested result directly, without a status confirmation or Markdown fence. Follow the supplied output schema when present.';
|
|
4
|
+
|
|
5
|
+
export async function codexAgent(prompt, opts = {}, context = {}) {
|
|
6
|
+
if (typeof prompt !== 'string' || !prompt.trim()) throw new TypeError('agent prompt must be non-empty');
|
|
7
|
+
const { Codex: CodexClass = Codex, executable, cwd = process.cwd(), runDir, signal } = context;
|
|
8
|
+
if (!runDir) throw new TypeError('runDir is required');
|
|
9
|
+
if (opts.agentType !== undefined) throw new TypeError('agentType is unavailable in Codex Autocode');
|
|
10
|
+
if (opts.isolation !== undefined) throw new TypeError('Codex SDK adapter does not support worktree isolation');
|
|
11
|
+
const sandbox = opts.sandbox ?? 'read-only';
|
|
12
|
+
if (!['read-only', 'workspace-write'].includes(sandbox)) throw new RangeError('unsupported sandbox mode');
|
|
13
|
+
if (opts.effort !== undefined && !['low', 'medium', 'high', 'xhigh', 'max'].includes(opts.effort))
|
|
14
|
+
throw new RangeError('unsupported effort');
|
|
15
|
+
if (opts.schema && (opts.schema.type !== 'object' || !opts.schema.properties ||
|
|
16
|
+
!Array.isArray(opts.schema.required ?? []))) throw new TypeError('schema must be a JSON object schema');
|
|
17
|
+
const client = new CodexClass(executable ? { codexPathOverride: executable } : undefined);
|
|
18
|
+
const thread = client.startThread({ workingDirectory: cwd, sandboxMode: sandbox,
|
|
19
|
+
model: opts.model, modelReasoningEffort: opts.effort,
|
|
20
|
+
skipGitRepoCheck: true, approvalPolicy: 'never' });
|
|
21
|
+
const turn = await thread.run(`${SUBAGENT_INSTRUCTIONS}\n\nTask:\n${prompt}`,
|
|
22
|
+
{ outputSchema: opts.schema, signal });
|
|
23
|
+
const result = opts.schema ? JSON.parse(turn.finalResponse) : turn.finalResponse.trimEnd();
|
|
24
|
+
if (opts.schema && (typeof result !== 'object' || result === null || Array.isArray(result)))
|
|
25
|
+
throw new TypeError('Codex returned a non-object structured result');
|
|
26
|
+
const usage = turn.usage?.output_tokens ?? 0;
|
|
27
|
+
return { result, outputTokens: Number.isSafeInteger(usage) && usage >= 0 ? usage : 0 };
|
|
28
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { availableParallelism } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { Script, createContext } from 'node:vm';
|
|
7
|
+
|
|
8
|
+
function parseHeader(source) {
|
|
9
|
+
const comment = /^\/\* autocode ([^\n]*?) \*\/[\r\n]+/.exec(source);
|
|
10
|
+
if (comment) return { meta: JSON.parse(comment[1]), body: source.slice(comment[0].length) };
|
|
11
|
+
const exported = /^export\s+const\s+meta\s*=\s*\{/.exec(source);
|
|
12
|
+
if (!exported) throw new SyntaxError('workflow must start with JSON autocode metadata or export const meta');
|
|
13
|
+
let depth = 0, quote = null, escaped = false, end = -1;
|
|
14
|
+
for (let i = exported[0].length - 1; i < source.length && i < 65536; i++) {
|
|
15
|
+
const ch = source[i];
|
|
16
|
+
if (quote) {
|
|
17
|
+
if (escaped) escaped = false;
|
|
18
|
+
else if (ch === '\\') escaped = true;
|
|
19
|
+
else if (ch === quote) quote = null;
|
|
20
|
+
} else if (ch === '"' || ch === "'") quote = ch;
|
|
21
|
+
else if (ch === '{') depth++;
|
|
22
|
+
else if (ch === '}' && --depth === 0) { end = i + 1; break; }
|
|
23
|
+
}
|
|
24
|
+
if (end < 0) throw new SyntaxError('unterminated workflow metadata');
|
|
25
|
+
const literal = source.slice(exported[0].length - 1, end);
|
|
26
|
+
const meta = new Script(`(${literal})`).runInContext(createContext({},
|
|
27
|
+
{ codeGeneration: { strings: false, wasm: false } }), { timeout: 1000 });
|
|
28
|
+
if (!meta || typeof meta !== 'object' || Array.isArray(meta))
|
|
29
|
+
throw new TypeError('workflow metadata must be an object');
|
|
30
|
+
return { meta, body: source.slice(end).replace(/^\s*;?/, '') };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function runWorkflow({ script, args, runDir, agent, budget = null, signal,
|
|
34
|
+
concurrency = Math.min(16, Math.max(2, availableParallelism() - 2)), resumeFromRunId,
|
|
35
|
+
resolveWorkflow, onProgress }) {
|
|
36
|
+
if (typeof script !== 'string') throw new TypeError('script must be a string');
|
|
37
|
+
const { meta } = parseHeader(script);
|
|
38
|
+
if (typeof meta.name !== 'string' || !meta.name.trim() ||
|
|
39
|
+
typeof meta.description !== 'string' || !meta.description.trim())
|
|
40
|
+
throw new TypeError('meta.name and meta.description must be non-empty strings');
|
|
41
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 16)
|
|
42
|
+
throw new RangeError('concurrency must be an integer from 1 to 16');
|
|
43
|
+
if (budget !== null && (!Number.isSafeInteger(budget) || budget < 0))
|
|
44
|
+
throw new RangeError('budget must be a non-negative integer or null');
|
|
45
|
+
if (typeof runDir !== 'string' || !runDir) throw new TypeError('runDir must be a directory path');
|
|
46
|
+
await mkdir(runDir, { recursive: true });
|
|
47
|
+
const runFile = join(runDir, 'run.json');
|
|
48
|
+
const journalFile = join(runDir, 'journal.jsonl');
|
|
49
|
+
let runId;
|
|
50
|
+
const cached = new Map();
|
|
51
|
+
if (resumeFromRunId) {
|
|
52
|
+
const saved = JSON.parse(await readFile(runFile, 'utf8'));
|
|
53
|
+
if (saved.runId !== resumeFromRunId) throw new Error('resume run ID does not match this directory');
|
|
54
|
+
runId = saved.runId;
|
|
55
|
+
const previous = await readFile(journalFile, 'utf8').catch((error) => {
|
|
56
|
+
if (error.code === 'ENOENT') return '';
|
|
57
|
+
throw error;
|
|
58
|
+
});
|
|
59
|
+
for (const line of previous.split('\n')) {
|
|
60
|
+
if (!line) continue;
|
|
61
|
+
const event = JSON.parse(line);
|
|
62
|
+
if (event.type === 'result') cached.set(event.key, event.result);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
runId = `wf_${randomUUID()}`;
|
|
66
|
+
await writeFile(runFile, JSON.stringify({ runId, name: meta.name, script, args }), { flag: 'wx' });
|
|
67
|
+
}
|
|
68
|
+
let journalQueue = Promise.resolve();
|
|
69
|
+
const record = (event) => journalQueue = journalQueue.then(() =>
|
|
70
|
+
appendFile(journalFile, `${JSON.stringify(event)}\n`));
|
|
71
|
+
const canonical = (value) => {
|
|
72
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
73
|
+
if (value && typeof value === 'object')
|
|
74
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]));
|
|
75
|
+
return value;
|
|
76
|
+
};
|
|
77
|
+
const seed = createHash('sha256').update(args === undefined ? 'undefined' : JSON.stringify(canonical(args))).digest('hex');
|
|
78
|
+
const branches = new AsyncLocalStorage();
|
|
79
|
+
const root = { previousKey: seed };
|
|
80
|
+
let agentCount = 0;
|
|
81
|
+
let outputTokens = 0;
|
|
82
|
+
let currentPhase = null;
|
|
83
|
+
const logs = [];
|
|
84
|
+
let active = 0;
|
|
85
|
+
const waiting = [];
|
|
86
|
+
const failures = [];
|
|
87
|
+
const contexts = new AsyncLocalStorage();
|
|
88
|
+
const realmValue = (value) => {
|
|
89
|
+
const json = JSON.stringify(value);
|
|
90
|
+
if (json === undefined) throw new TypeError('workflow values must be JSON-serializable');
|
|
91
|
+
const context = contexts.getStore();
|
|
92
|
+
context.__autocodeJson = json;
|
|
93
|
+
try { return new Script('JSON.parse(__autocodeJson)').runInContext(context); }
|
|
94
|
+
finally { delete context.__autocodeJson; }
|
|
95
|
+
};
|
|
96
|
+
const inSlot = async (fn) => {
|
|
97
|
+
if (active < concurrency) active++;
|
|
98
|
+
else await new Promise((resolve) => waiting.push(resolve));
|
|
99
|
+
try { return await fn(); }
|
|
100
|
+
finally {
|
|
101
|
+
const next = waiting.shift();
|
|
102
|
+
if (next) next();
|
|
103
|
+
else active--;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const invokeAgent = async (prompt, opts = {}) => {
|
|
107
|
+
if (typeof prompt !== 'string' || !prompt.trim()) throw new TypeError('agent prompt must be a non-empty string');
|
|
108
|
+
if (agentCount >= 1000) throw Error('Autocode agent call cap reached (1000)');
|
|
109
|
+
agentCount++;
|
|
110
|
+
const cacheOpts = Object.fromEntries(Object.entries(opts).filter(([key]) =>
|
|
111
|
+
!['label', 'phase'].includes(key)));
|
|
112
|
+
const branch = branches.getStore() ?? root;
|
|
113
|
+
const key = createHash('sha256').update(`v1\0${branch.previousKey}\0${prompt}\0${JSON.stringify(canonical(cacheOpts))}`).digest('hex');
|
|
114
|
+
branch.previousKey = key;
|
|
115
|
+
if (cached.has(key)) return realmValue(cached.get(key));
|
|
116
|
+
return inSlot(async () => {
|
|
117
|
+
if (budget !== null && outputTokens >= budget) throw Error('Autocode token budget exceeded');
|
|
118
|
+
const progress = { label: opts.label ?? prompt, phase: opts.phase ?? currentPhase };
|
|
119
|
+
await record({ type: 'started', key });
|
|
120
|
+
onProgress?.({ type: 'agent-started', ...progress });
|
|
121
|
+
try {
|
|
122
|
+
const response = await agent(prompt, opts, { signal, runDir });
|
|
123
|
+
if (!response || !Number.isSafeInteger(response.outputTokens) || response.outputTokens < 0)
|
|
124
|
+
throw new TypeError('agent adapter must return a non-negative outputTokens count');
|
|
125
|
+
outputTokens += response.outputTokens;
|
|
126
|
+
const result = structuredClone(response.result);
|
|
127
|
+
await record({ type: 'result', key, result });
|
|
128
|
+
onProgress?.({ type: 'agent-completed', ...progress });
|
|
129
|
+
return realmValue(result);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
await record({ type: 'failed', key, message: String(error?.message ?? error) });
|
|
132
|
+
onProgress?.({ type: 'agent-failed', ...progress });
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
};
|
|
137
|
+
const parallel = async (thunks) => {
|
|
138
|
+
if (!Array.isArray(thunks) || thunks.length > 4096 || thunks.some((fn) => typeof fn !== 'function'))
|
|
139
|
+
throw new TypeError('parallel expects at most 4096 functions');
|
|
140
|
+
const parent = branches.getStore() ?? root;
|
|
141
|
+
const settled = await Promise.allSettled(thunks.map((fn, index) =>
|
|
142
|
+
branches.run({ previousKey: `${parent.previousKey}:parallel:${index}` }, () => Promise.resolve().then(fn))));
|
|
143
|
+
return realmValue(settled.map((item, index) => {
|
|
144
|
+
if (item.status === 'fulfilled') return item.value;
|
|
145
|
+
failures.push(`parallel[${index}]: ${item.reason?.message ?? String(item.reason)}`);
|
|
146
|
+
return null;
|
|
147
|
+
}));
|
|
148
|
+
};
|
|
149
|
+
const pipeline = async (items, ...stages) => {
|
|
150
|
+
if (!Array.isArray(items) || items.length > 4096 || stages.some((fn) => typeof fn !== 'function'))
|
|
151
|
+
throw new TypeError('pipeline expects at most 4096 items and function stages');
|
|
152
|
+
const parent = branches.getStore() ?? root;
|
|
153
|
+
const settled = await Promise.allSettled(items.map((item, index) => branches.run(
|
|
154
|
+
{ previousKey: `${parent.previousKey}:pipeline:${index}` }, async () => {
|
|
155
|
+
let value = item;
|
|
156
|
+
for (const stage of stages) {
|
|
157
|
+
if (value === null) break;
|
|
158
|
+
value = await stage(value, item, index);
|
|
159
|
+
}
|
|
160
|
+
return value;
|
|
161
|
+
})));
|
|
162
|
+
return realmValue(settled.map((entry, index) => {
|
|
163
|
+
if (entry.status === 'fulfilled') return entry.value;
|
|
164
|
+
failures.push(`pipeline[${index}]: ${entry.reason?.message ?? String(entry.reason)}`);
|
|
165
|
+
return null;
|
|
166
|
+
}));
|
|
167
|
+
};
|
|
168
|
+
const phase = (title) => {
|
|
169
|
+
if (typeof title !== 'string' || !title.trim()) throw new TypeError('phase title must be non-empty');
|
|
170
|
+
currentPhase = title;
|
|
171
|
+
record({ type: 'phase', title });
|
|
172
|
+
onProgress?.({ type: 'phase', title });
|
|
173
|
+
};
|
|
174
|
+
const log = (message) => {
|
|
175
|
+
if (logs.length < 1000) {
|
|
176
|
+
const entry = { phase: currentPhase, message: String(message) };
|
|
177
|
+
logs.push(entry);
|
|
178
|
+
record({ type: 'log', ...entry });
|
|
179
|
+
onProgress?.({ type: 'log', ...entry });
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
const budgetView = Object.freeze(Object.assign(Object.create(null), {
|
|
183
|
+
total: budget,
|
|
184
|
+
spent: () => outputTokens,
|
|
185
|
+
remaining: () => budget === null ? Infinity : Math.max(0, budget - outputTokens),
|
|
186
|
+
}));
|
|
187
|
+
const timers = new Map();
|
|
188
|
+
let timerId = 0;
|
|
189
|
+
const timer = (fn, delay) => {
|
|
190
|
+
const id = ++timerId;
|
|
191
|
+
timers.set(id, setTimeout(() => { timers.delete(id); fn(); }, delay));
|
|
192
|
+
return id;
|
|
193
|
+
};
|
|
194
|
+
const cancelTimer = (id) => { clearTimeout(timers.get(id)); timers.delete(id); };
|
|
195
|
+
for (const fn of [invokeAgent, parallel, pipeline, phase, log, timer, cancelTimer,
|
|
196
|
+
budgetView.spent, budgetView.remaining]) Object.setPrototypeOf(fn, null);
|
|
197
|
+
const execute = async (source, inputArgs, depth) => {
|
|
198
|
+
const { meta: childMeta, body } = parseHeader(source);
|
|
199
|
+
if (typeof childMeta.name !== 'string' || typeof childMeta.description !== 'string')
|
|
200
|
+
throw new TypeError('child workflow needs name and description');
|
|
201
|
+
const workflow = async (reference, childArgs) => {
|
|
202
|
+
if (depth >= 1) throw new Error('child workflow depth limit reached');
|
|
203
|
+
if (typeof reference === 'string' ? !/^[a-zA-Z0-9_-]+$/.test(reference) :
|
|
204
|
+
!reference || typeof reference !== 'object' ||
|
|
205
|
+
typeof reference.scriptPath !== 'string' || !reference.scriptPath.trim() ||
|
|
206
|
+
Object.keys(reference).length !== 1)
|
|
207
|
+
throw new TypeError('workflow reference must be a saved name or {scriptPath}');
|
|
208
|
+
if (typeof resolveWorkflow !== 'function') throw new Error('named workflow resolver is unavailable');
|
|
209
|
+
const childSource = await resolveWorkflow(reference);
|
|
210
|
+
const parent = branches.getStore() ?? root;
|
|
211
|
+
const child = { previousKey: `${parent.previousKey}:workflow:${JSON.stringify(canonical(reference))}:${JSON.stringify(canonical(childArgs))}` };
|
|
212
|
+
const result = await branches.run(child, () => execute(childSource, childArgs, depth + 1));
|
|
213
|
+
parent.previousKey = child.previousKey;
|
|
214
|
+
return realmValue(result);
|
|
215
|
+
};
|
|
216
|
+
Object.setPrototypeOf(workflow, null);
|
|
217
|
+
const context = createContext({ argsJson: inputArgs === undefined ? undefined : JSON.stringify(inputArgs),
|
|
218
|
+
__autocodeHost: { agent: invokeAgent, parallel, pipeline, workflow },
|
|
219
|
+
phase, log, budget: budgetView, setTimeout: timer, clearTimeout: cancelTimer },
|
|
220
|
+
{ codeGeneration: { strings: false, wasm: false } });
|
|
221
|
+
new Script(`(function(){
|
|
222
|
+
const host=globalThis.__autocodeHost;
|
|
223
|
+
delete globalThis.__autocodeHost;
|
|
224
|
+
globalThis.agent=(...xs)=>Promise.resolve(host.agent(...xs));
|
|
225
|
+
globalThis.parallel=(...xs)=>Promise.resolve(host.parallel(...xs));
|
|
226
|
+
globalThis.pipeline=(...xs)=>Promise.resolve(host.pipeline(...xs));
|
|
227
|
+
globalThis.workflow=(...xs)=>Promise.resolve(host.workflow(...xs));
|
|
228
|
+
const NativeDate=Date;
|
|
229
|
+
globalThis.Date=class extends NativeDate {
|
|
230
|
+
constructor(...xs){if(xs.length===0)throw Error('Date.now and new Date() are unavailable in Autocode workflows');super(...xs)}
|
|
231
|
+
static now(){throw Error('Date.now is unavailable in Autocode workflows')}
|
|
232
|
+
};
|
|
233
|
+
Math.random=()=>{throw Error('Math.random is unavailable in Autocode workflows')};
|
|
234
|
+
})()`).runInContext(context);
|
|
235
|
+
const code = new Script(`(async()=>{'use strict';const args=argsJson===undefined?undefined:JSON.parse(argsJson);\n${body}\n})()`, {
|
|
236
|
+
filename: `${childMeta.name}.js`,
|
|
237
|
+
});
|
|
238
|
+
return contexts.run(context, () => code.runInContext(context, { timeout: 30_000 }));
|
|
239
|
+
};
|
|
240
|
+
const result = await execute(script, args, 0);
|
|
241
|
+
await journalQueue;
|
|
242
|
+
return { result: structuredClone(result), agentCount, outputTokens, failures, logs, runId };
|
|
243
|
+
}
|