@parcha/agentrun-pi 0.1.0-beta.1

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.
Files changed (45) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +209 -0
  4. package/dist/admission.d.ts +6 -0
  5. package/dist/admission.js +51 -0
  6. package/dist/author.d.ts +21 -0
  7. package/dist/author.js +72 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +68 -0
  10. package/dist/demo-data.d.ts +361 -0
  11. package/dist/demo-data.js +386 -0
  12. package/dist/demo.d.ts +13 -0
  13. package/dist/demo.js +44 -0
  14. package/dist/extension-service.d.ts +110 -0
  15. package/dist/extension-service.js +477 -0
  16. package/dist/extension.d.ts +41 -0
  17. package/dist/extension.js +419 -0
  18. package/dist/host-session.d.ts +5 -0
  19. package/dist/host-session.js +80 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.js +6 -0
  22. package/dist/presentation.d.ts +4 -0
  23. package/dist/presentation.js +34 -0
  24. package/dist/runner.d.ts +12 -0
  25. package/dist/runner.js +256 -0
  26. package/dist/skill-bundle.d.ts +5 -0
  27. package/dist/skill-bundle.js +15 -0
  28. package/dist/tool-input-error.d.ts +10 -0
  29. package/dist/tool-input-error.js +40 -0
  30. package/dist/types.d.ts +119 -0
  31. package/dist/types.js +1 -0
  32. package/package.json +73 -0
  33. package/skills/author/SKILL.md +102 -0
  34. package/skills/author/examples/evidence-gate.input.json +6 -0
  35. package/skills/author/examples/evidence-gate.json +125 -0
  36. package/skills/author/examples/read-file.input.json +1 -0
  37. package/skills/author/examples/read-file.json +44 -0
  38. package/skills/author/examples/read-source-decision.input.json +4 -0
  39. package/skills/author/examples/read-source-decision.json +37 -0
  40. package/skills/author/examples/release-note.txt +10 -0
  41. package/skills/author/examples/review-release-notes.input.json +6 -0
  42. package/skills/author/examples/review-release-notes.json +123 -0
  43. package/skills/author/references/jev-decisions.md +112 -0
  44. package/skills/author/references/sdk-authoring.md +16 -0
  45. package/skills/author/references/workflow-format.md +145 -0
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/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ AgentRun
2
+ Copyright 2026 Parcha Labs, Inc.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # agent.run() + Pi
2
+
3
+ Describe a task in Pi. AgentRun turns it into a workflow you can inspect and runs its steps using your current Pi model. Requires Node 22.19+ and Pi 0.87.0.
4
+
5
+ ## Install from source
6
+
7
+ Build the extension and use the included Pi CLI. From a new terminal:
8
+
9
+ ```sh
10
+ git clone --branch main --single-branch https://github.com/Parcha-ai/agentrun.git
11
+ cd agentrun
12
+ npm ci --ignore-scripts
13
+ npm run build
14
+ ./node_modules/.bin/pi install ./packages/pi -l
15
+ ./node_modules/.bin/pi --offline
16
+ ```
17
+
18
+ `-l` writes project settings in `.pi/settings.json`. Omit it to install for all your Pi sessions. `--offline` skips startup downloads; it does not disable model calls.
19
+
20
+ On first launch, Pi asks whether you trust the project before loading its extension. Review the checkout before accepting.
21
+
22
+ Already built this checkout? Start at the `pi install` line. The included CLI is the tested Pi 0.87.0 version; a global Pi installation is unnecessary. If Pi 0.87.0 is already open, use `/reload`. Keep this checkout: Pi loads the extension and skill from it. Rebuild after source changes, then reload. `/reload` clears the current workflow definition; run the demo or describe your task again to create one.
23
+
24
+ For live tasks, configure model access in Pi first. AgentRun uses Pi's current model and authentication; it needs no separate model configuration. The scripted demo below works without provider access.
25
+
26
+ Try the bundled example inside Pi:
27
+
28
+ ```text
29
+ /agentrun demo
30
+ ```
31
+
32
+ The demo shows the workflow graph, progress, and a completed result with call counts. It uses scripted responses over fictional sources. It makes no model calls and does not test model quality. Run `/agentrun status` to check the loaded skill and Pi host version. The tested version is 0.87.0; status flags a different host without blocking it. Missing Pi or Jev access does not prevent the scripted demo. To repeat it, run `/agentrun run` or `/agentrun demo`. A scripted demo stays scripted on rerun, including its missing-evidence path. Use `/agentrun demo live` to switch to real Pi and Jev calls. Workflows authored by Pi use real adapters.
33
+
34
+ For an offline Pi startup, use `./node_modules/.bin/pi --offline`. Without that flag, Pi may download optional command-line tools on first launch. This is separate from the scripted demo, which makes no network calls.
35
+
36
+ ## Describe, inspect, run
37
+
38
+ ```text
39
+ /agentrun Find the main entry points in this repository and summarize how requests reach them.
40
+ ```
41
+
42
+ The command loads the packaged `agentrun-author` skill. Pi reads the available tools, builds a workflow, inspects its graph, then runs it with the task's input. You can also invoke `/skill:agentrun-author <task>` directly. Ask Pi to change a step or explain a result as you would in an ordinary conversation.
43
+
44
+ | Command | What happens |
45
+ | --- | --- |
46
+ | `/agentrun <task>` | Ask Pi to build, inspect, and run a workflow for the task. |
47
+ | `/agentrun help` | List commands and demo modes. |
48
+ | `/agentrun` | Show the current workflow, or help if there is none. |
49
+ | `/agentrun run` | Repeat the current workflow with its last supplied input. Scripted demos stay scripted; authored workflows use real adapters. |
50
+ | `/agentrun status` | Check skill discovery, active Pi selection, and Jev configuration without making provider calls. |
51
+ | `/agentrun stop` | Request cancellation of the running workflow. |
52
+
53
+ A progress widget shows active steps and the number finished. Results appear in Pi, with full output and events in the structured result.
54
+
55
+ Pi 0.87.0 cannot export a fresh session containing only slash-command results. To save an offline research receipt from the checkout, run `node examples/research-live.mjs --out research-result.json`. This runs the scripted example again and writes its result; it does not export the Pi session.
56
+
57
+ One workflow runs at a time. Definitions and run state belong to the current Pi session; switching sessions or closing Pi does not create a saved workflow library. Named saves and reuse across sessions are planned for V2. This extension does not support them.
58
+
59
+ ### Three demo modes
60
+
61
+ | Command | What it demonstrates |
62
+ | --- | --- |
63
+ | `/agentrun demo` | Scripted successful execution over the bundled fictional sources, without model calls. |
64
+ | `/agentrun demo empty` | Scripted insufficient-evidence path, without model calls. |
65
+ | `/agentrun demo live` | Real Pi agent steps and Jev system one decisions over the same fictional sources. |
66
+
67
+ Live mode uses your active Pi model and requires configured TypeSafe access for Jev. It still does not search the web or prove accuracy on real research. See the [Jev adapter configuration](../jev/README.md). Live calls can incur usage charges; scripted mode needs no provider access.
68
+
69
+ ## Tools and execution
70
+
71
+ By default, the extension exposes currently active Pi built-in `read`, `grep`, `find`, and `ls` tools. A workflow can narrow that set; it cannot enable a tool that the host has not supplied. The additional `search` tool reads only the bundled fictional demo sources.
72
+
73
+ The user must issue `/agentrun run --trusted` for each run that needs code nodes or active built-in `bash`, `edit`, or `write` tools. This permits local, unsandboxed execution; authorization does not carry into the next run. A model cannot grant itself that permission with a tool argument.
74
+
75
+ Native V1 does not supply SOP text. Workflows declaring `sopSection` stop before execution with a setup error; keep the required sections and use an SDK host that supplies the complete SOP.
76
+
77
+ Custom extension tools and the outer Pi session's permission hooks are **not inherited**, including in trusted runs. A configured host can explicitly supply its own tool definitions as described below. Shell/executor effect transports and artifact delivery are unavailable in this extension; declared tool effects must use an available tool.
78
+
79
+ A direct `call` to a Pi built-in returns a Pi tool result. Its `content` is an array of text/image blocks; `details` may be absent from the workflow's JSON result. Declare that result shape in the output schema. Custom `PiToolDefinition` implementations follow Pi's SDK contract and return a `details` field; use `details: undefined` when there is no extra data. Only the demo `search` tool returns `{sources}` directly. A tool-only workflow does not create an agent session. Jev is needed only for system one decisions.
80
+
81
+ Jev design guidance is bundled with the author skill and returned by `describe`
82
+ under `authoring.jev`, including for hosts without a file-reading tool. No separate
83
+ TypeSafe skill install is required for DSL authoring. The
84
+ [source-read example](skills/author/examples/read-source-decision.json) preserves
85
+ original tool evidence through a Jev decision and deterministic projection; its
86
+ fictional tests demonstrate wiring, not measured semantic accuracy. Explicit
87
+ `tools: []` disables tools for an agent node; omission inherits the host allowlist.
88
+
89
+ Inspection checks nonexecuting host admission as well as DSL structure; `describe`
90
+ also exposes structural limits. Runtime contract failures provide safe error codes,
91
+ stages and schema problems for repair. Unknown provider failures remain opaque;
92
+ provider bodies and arbitrary code exception text are not included in reports.
93
+ Recognized Jev response/transport failures use fixed `jev_*` categories, and a Pi
94
+ session response failure uses `model_response_failed`, with the failing node label.
95
+ Pi runner stops use `pi_timeout`, `pi_turn_limit`, `pi_submission_limit`,
96
+ `pi_no_submission`, or `pi_aborted`, with a fixed message explaining the next step.
97
+ Operator cancellation of the workflow still reports `cancelled`.
98
+ Jev reports may also include a fixed `error.reason` identifying the rejected
99
+ response invariant, or a numeric HTTP `error.status`. A recognized token-capacity
100
+ rejection reports `max_tokens_exceeded`; this is not a byte-to-token estimate or
101
+ permission to truncate evidence. Provider text remains private.
102
+ These diagnostics add no retry and do not infer an unobserved provider cause.
103
+
104
+ Use `/agentrun stop` to cancel a slash-command run; pressing Escape is not a guaranteed cancellation path. Stopping signals admitted tools, but already-started effects may still finish. Check their results before retrying; a stop does not undo a write.
105
+
106
+ Displayed workflow counts include direct tool calls, system one decisions, and model steps. They do not include tools called inside an agent step or measure tokens, requests, or spending. Hosts can count child tool attempts through `onToolAttempt`.
107
+
108
+ Agent steps capture the active Pi model when the run starts and keep that selection for the run. Request-count and deadline limits bound execution; they are not token or spending caps.
109
+
110
+ The native model-facing interface starts with `agentrun` and `action: "describe"` for available tool schemas and configuration presence, then `action: "inspect"` and a complete `workflow`, followed by `action: "run"` and `input`. There is no outer `submit` tool: `submit` belongs to the internal child runner and the SDK author described below.
111
+
112
+ ### Configure the native extension from a host
113
+
114
+ Hosts that own a restricted corpus, an approved Jev transport, or shared accounting can configure the same native extension:
115
+
116
+ ```js
117
+ import { createAgentRunExtension } from '@parcha/agentrun-pi/extension';
118
+
119
+ // These definitions and callbacks belong to the embedding host.
120
+ export default createAgentRunExtension({
121
+ hostTools: ctx => approvedToolsFor(ctx),
122
+ createJudge: ({ signal }) => makeHostJudge({ signal }),
123
+ onToolAttempt: () => sharedBudget.admit('tool'),
124
+ });
125
+ ```
126
+
127
+ All options are optional; the default export retains ordinary Pi setup. `hostTools` replaces the complete built-in and demo tool inventory, including during trusted runs. `describe` reports the supplied schemas. Direct calls to these tools return `{content, details?}` even if a supplied tool is named `search`. Definitions refresh from the execution context before each run. Tool names must be unique; `agentrun` and `submit` are reserved.
128
+
129
+ `createJudge` supplies the runner for workflow Jev nodes and is called only when the graph requires one. A failed factory never falls back to ambient configuration. The host receives cancellation signals and owns transport configuration and accounting. `onToolAttempt` is synchronous admission: it runs before each direct tool call and each native child tool attempt, including invalid arguments, unknown tools, and `submit`. Throwing prevents the attempted effect. Outer authoring calls are counted by their own host. `describe.limits` reports the configured workflow deadline, model-request, judge-call and tool-attempt ceilings, and per-node turn, submission, and timeout limits. The callback can impose a shared budget across authoring and execution.
130
+
131
+ Hosts may supply `runtimeLimits` to lower a finite limit or explicitly disable it with `null`: `deadlineMs`, `modelRequests`, `judgeCalls`, `toolAttempts`, `nodeMaxTurns`, `nodeMaxSubmissions`, and `nodeTimeoutMs`. Omitted values keep existing finite defaults. Disabling all seven removes extension inference/time admission caps while preserving operator cancellation, schema validation, graph structure, concurrency, and trace/data guards. This is host configuration; neither a workflow nor an author tool argument can change it. Tool-specific timeouts and provider limits are separate host/tool contracts.
132
+
133
+ Trace retention is **not an execution budget**. A run keeps recent sanitized events
134
+ within a bounded in-memory report and continues when that retention fills. The
135
+ report's `trace` counts received, retained, dropped and rejected events/bytes;
136
+ `traceTruncated` discloses incomplete retained history, not incomplete output.
137
+ Individual events still have plain-JSON, byte, depth and value-count safety guards.
138
+ The SDK service configures those separately with `maxTraceBytes` (retention) and
139
+ `maxEventBytes` (individual safety).
140
+
141
+ For complete host-owned observation, configure `onWorkflowEvent(frame)`. Each
142
+ frame has `workflowDigest`, a registration-local `runOrdinal`, a per-run `sequence`,
143
+ and an isolated sanitized `event`. Valid events arrive even after report retention
144
+ fills, including cancellation cleanup before run closure. This callback cannot
145
+ grant authority or change execution. It is not a durable-store guarantee: the host
146
+ must record write failures, drain asynchronous work, and check received sequences
147
+ against report counters before claiming a complete journal. Callback errors are
148
+ nonfatal to the workflow. Do not store source material without an appropriate
149
+ host-owned storage policy.
150
+
151
+ An operator may select a different active Pi model between inspection and execution; child agent steps capture that execution selection. The workflow cannot choose a replacement model or configure host callbacks. Code still requires the per-run trusted command and remains unsandboxed: a restricted tool inventory is not a sandbox for executable code. The host must review executable candidates before granting that authority.
152
+
153
+ ## SDK: embed the runner
154
+
155
+ The native extension handles configuration above. For another Pi extension that already has a context:
156
+
157
+ ```js
158
+ import { runWorkflow } from '@parcha/agentrun-dsl';
159
+ import { createPiHostRunner } from '@parcha/agentrun-pi';
160
+
161
+ const result = await runWorkflow(workflow, input, {
162
+ runNode: createPiHostRunner(ctx, { tools: allowedTools }),
163
+ // Supply runJudge separately for Jev nodes or semantic verification.
164
+ });
165
+ ```
166
+
167
+ `ctx` supplies the active model and public model registry. Tools are explicitly supplied and receive the original context; outer hooks are not copied. The captured active model remains fixed for the run. The host thinking level is inherited when provided, and a node can override it. The runner bounds turns, submissions, and time, and refuses an absent model instead of selecting a fallback. These limits do not impose token or spending caps.
168
+
169
+ For a standalone application, `createPiRunner(options)` accepts a configured SDK `ModelRuntime` and its selected `model`. Supply `tools` explicitly. It loads no ambient filesystem tools, workspace instructions, extensions, prompt templates, or skills. `createPiHostSessionFactory(ctx)` exposes the same native child session transport for integrations that own their own runner. Factories are unnecessary for ordinary extension use.
170
+
171
+ LLM `instructions` are literal text. Refer to "the text field in the JSON input" and declare `requires: ["text"]`; `{text}` inside instructions stays literal. An optional node `state` map scopes the JSON user message. Placeholder substitution applies to designated fields such as `state` and `call.args`.
172
+
173
+ The child model delivers `{value: result}` through its `submit` tool. Schema and review rejections return feedback to the same session. Exhausting a turn, submission, timeout, or cancellation limit throws `PiRunError`; a rejected draft is never returned as success. A host can explicitly pass `null` for runner `maxTurns`, `maxSubmissions`, or `timeoutMs` to disable that limit. Omission keeps the default; external cancellation still interrupts unlimited runs.
174
+
175
+ ## SDK: retain candidates and check fixed fixtures
176
+
177
+ The SDK author saves candidate files separately from the native extension's session-local workflow. Supply configured runner options and host-owned acceptance checks:
178
+
179
+ ```js
180
+ import { authorWorkflow } from '@parcha/agentrun-pi';
181
+
182
+ const candidate = await authorWorkflow({
183
+ request: 'Extract a numeric count from text',
184
+ outputDir: './candidates',
185
+ inputKeys: ['text'],
186
+ pi: options, // Your configured PiRunnerOptions.
187
+ maxCandidates: 4,
188
+ acceptance: workflow => checkAgainstYourFixtures(workflow),
189
+ });
190
+ console.log(candidate.path, candidate.checks);
191
+ ```
192
+
193
+ The host owns `checkAgainstYourFixtures`: return diagnostics, or `[]` to accept. Without that callback, acceptance is labeled `structural` and does not establish correct behavior. The author retains each submitted version and its feedback, never activates it, and cannot edit the host's acceptance checks.
194
+
195
+ With `rubricSections`, every supplied section must appear on every generated LLM node, including child workflows. The author conservatively rejects Jev nodes, semantic `ask` predicates, and `verify` clauses under that policy; those need a separately reviewed question contract. Schema properties named `node`, `verify`, or `predicate` remain ordinary data. Supply the authoritative rubric as `deps.sop` when executing the candidate.
196
+
197
+ The standalone CLI remains available as `node packages/pi/dist/cli.js --help` from source. It imports a trusted caller-owned `--config` module for `author` and `run`; importing that module executes its code. `validate` can evaluate code probes. Review executable workflows before using it.
198
+
199
+ ## Dependencies and retained data
200
+
201
+ Pi is optional for `@parcha/agentrun-dsl`. This package brings the Pi coding-agent SDK, its provider dependencies, and the Jev adapter; its dependency footprint is larger than the core. The release inventory records the locked versions.
202
+
203
+ The SDK dependencies remain pinned so standalone applications and the CLI have a complete runtime. When loaded as an extension, Pi resolves its core packages and TypeBox through the host loader. The tested host is Pi 0.87.0; installed SDK pins do not make an older or newer host compatible. The offline loader regression checks competing local dependencies, a native file read, and the scripted workflow. Pi's [package guidance](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/packages.md#dependencies) recommends peers for extension-only packages; this package also provides the standalone SDK.
204
+
205
+ Candidate directories retain request text, rubric text, workflow versions, and feedback. Native Pi messages can contain workflow inputs and results. Choose storage and tool access appropriate for that data. The accompanying `skills/author/SKILL.md` describes the native and SDK authoring paths for agents.
206
+
207
+ ## License
208
+
209
+ Apache-2.0. See the included LICENSE and NOTICE files.
@@ -0,0 +1,6 @@
1
+ export interface WorkflowAdmissionOptions {
2
+ rubricSections?: Record<string, string>;
3
+ allowExecutableCandidates?: boolean;
4
+ allowedEffectTools?: readonly string[];
5
+ }
6
+ export declare function workflowPolicyErrors(candidate: unknown, options: WorkflowAdmissionOptions): string[];
@@ -0,0 +1,51 @@
1
+ export function workflowPolicyErrors(candidate, options) {
2
+ const errors = [];
3
+ const sections = Object.keys(options.rubricSections ?? {});
4
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
5
+ const visit = (value) => {
6
+ const node = record(value);
7
+ if (!node)
8
+ return;
9
+ const kind = node.node;
10
+ if (!options.allowExecutableCandidates && ["code", "call", "artifact"].includes(String(kind)) && !(kind === "call" && node.via === "tool" && typeof node.tool === "string" && options.allowedEffectTools?.includes(node.tool)))
11
+ errors.push(`${kind} requires allowExecutableCandidates`);
12
+ if (sections.length && ["judge", "pick", "sift", "route"].includes(String(kind)))
13
+ errors.push(`${String(kind)} cannot carry supplied SOP sections; use an LLM node with sopSection`);
14
+ const llm = ["agent", "decide", "extract", "report"].includes(String(kind));
15
+ const predicate = kind === "loop" ? record(node.until) : kind === "escalate" ? record(node.when) : undefined;
16
+ if (sections.length && (predicate?.predicate === "ask" || (llm && node.verify !== undefined)))
17
+ errors.push("Semantic predicates and verify clauses require a separately reviewed question contract when rubric sections are supplied");
18
+ const proseArtifact = kind === "artifact" && (node.type === "markdown" || node.type === "report");
19
+ if (llm || proseArtifact) {
20
+ const included = Array.isArray(node.sopSection) ? node.sopSection : [node.sopSection];
21
+ for (const section of sections)
22
+ if (!included.includes(section))
23
+ errors.push(`${String(node.label)} must include rubric section ${section}`);
24
+ }
25
+ switch (kind) {
26
+ case "chain":
27
+ if (Array.isArray(node.steps))
28
+ node.steps.forEach(visit);
29
+ break;
30
+ case "parallel":
31
+ if (Array.isArray(node.branches))
32
+ node.branches.forEach(visit);
33
+ break;
34
+ case "map":
35
+ case "loop":
36
+ visit(node.body);
37
+ break;
38
+ case "route": {
39
+ const branches = record(node.branches);
40
+ if (branches)
41
+ Object.values(branches).forEach(branch => visit(record(branch)?.body));
42
+ break;
43
+ }
44
+ case "workflow":
45
+ visit(record(node.workflow)?.root);
46
+ break;
47
+ }
48
+ };
49
+ visit(record(candidate)?.root);
50
+ return errors;
51
+ }
@@ -0,0 +1,21 @@
1
+ import { type Workflow } from "@parcha/agentrun-dsl";
2
+ import { type PiRunnerOptions } from "./runner.js";
3
+ export declare const AUTHOR_CONTRACT = "You author AgentRun DSL v2 workflows as JSON data.\nDeliver with the submit tool, never prose or a filename. Make the smallest workflow satisfying the request.\nThe document has v:2, name, schemas (JSON Schema catalog), optional input:{schemaId}, output:{schemaId,path?}, root.\nEvery referenced schema must exist. Each LLM node has node:agent|decide|extract, label, instructions, out (schema id), as (state key), optional requires/tools/sopSection.\nA chain has node:chain, steps:[nodes]. A map has label, itemsPath, body, as, maxConcurrency. A loop has label, body, until, maxIters.\nA judge has label,state,out,as. Judge schemas use flat boolean/enum/integer properties; each property's description states its question. A route has label,state,instructions,branches:{name:{criteria,body}}, optional unsure:{branch,gte} and as.\nLLM instructions are literal text, never interpolated. The node receives workflow state as a JSON user message; refer to its keys in ordinary prose and declare required keys in requires. Use {stateKey} placeholders only in interpolated fields such as judge.state and call.args; whole placeholders preserve their value's type. Output.path selects a final state value validated by output.schemaId.\nOnly use tools named by the host. Never invent a tool, capability, evidence source or successful test.\nKeep the full rubric in its original source text. Every LLM node's sopSection must include ALL supplied rubric section names. Merged judgments inherit their parents' union. Do not paraphrase policy into instructions. If rubric sections are supplied, use LLM nodes for judgment; Jev nodes do not carry sopSection and require a separately reviewed question contract.\nKeep independent acceptance checks host-owned; never change their implementation, fixtures or thresholds to pass. A valid candidate is not automatically activated.\nCode, shell/effect calls and artifact delivery require explicit host authorization. Bound loops and parallelism; uncertainty should escalate or select an explicit fallback.\nExample: {\"v\":2,\"name\":\"summarize\",\"schemas\":{\"Result\":{\"type\":\"object\",\"properties\":{\"summary\":{\"type\":\"string\"}},\"required\":[\"summary\"],\"additionalProperties\":false}},\"output\":{\"schemaId\":\"Result\",\"path\":\"result\"},\"root\":{\"node\":\"extract\",\"label\":\"summarize\",\"instructions\":\"Summarize the text field from the JSON input faithfully.\",\"out\":\"Result\",\"as\":\"result\",\"requires\":[\"text\"]}}";
4
+ export interface AuthorWorkflowOptions {
5
+ request: string;
6
+ outputDir: string;
7
+ pi: PiRunnerOptions;
8
+ inputKeys?: string[];
9
+ rubricSections?: Record<string, string>;
10
+ allowExecutableCandidates?: boolean;
11
+ maxCandidates?: number;
12
+ acceptance?: (candidate: Workflow) => Promise<string[]> | string[];
13
+ }
14
+ export interface AuthoredWorkflow {
15
+ workflow: Workflow;
16
+ path: string;
17
+ directory: string;
18
+ candidates: number;
19
+ checks: "structural" | "structural-and-host";
20
+ }
21
+ export declare function authorWorkflow(options: AuthorWorkflowOptions): Promise<AuthoredWorkflow>;
package/dist/author.js ADDED
@@ -0,0 +1,72 @@
1
+ import { workflowPolicyErrors } from "./admission.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { resolve, join } from "node:path";
5
+ import { validateWorkflow } from "@parcha/agentrun-dsl";
6
+ import { createPiRunner } from "./runner.js";
7
+ export const AUTHOR_CONTRACT = `You author AgentRun DSL v2 workflows as JSON data.
8
+ Deliver with the submit tool, never prose or a filename. Make the smallest workflow satisfying the request.
9
+ The document has v:2, name, schemas (JSON Schema catalog), optional input:{schemaId}, output:{schemaId,path?}, root.
10
+ Every referenced schema must exist. Each LLM node has node:agent|decide|extract, label, instructions, out (schema id), as (state key), optional requires/tools/sopSection.
11
+ A chain has node:chain, steps:[nodes]. A map has label, itemsPath, body, as, maxConcurrency. A loop has label, body, until, maxIters.
12
+ A judge has label,state,out,as. Judge schemas use flat boolean/enum/integer properties; each property's description states its question. A route has label,state,instructions,branches:{name:{criteria,body}}, optional unsure:{branch,gte} and as.
13
+ LLM instructions are literal text, never interpolated. The node receives workflow state as a JSON user message; refer to its keys in ordinary prose and declare required keys in requires. Use {stateKey} placeholders only in interpolated fields such as judge.state and call.args; whole placeholders preserve their value's type. Output.path selects a final state value validated by output.schemaId.
14
+ Only use tools named by the host. Never invent a tool, capability, evidence source or successful test.
15
+ Keep the full rubric in its original source text. Every LLM node's sopSection must include ALL supplied rubric section names. Merged judgments inherit their parents' union. Do not paraphrase policy into instructions. If rubric sections are supplied, use LLM nodes for judgment; Jev nodes do not carry sopSection and require a separately reviewed question contract.
16
+ Keep independent acceptance checks host-owned; never change their implementation, fixtures or thresholds to pass. A valid candidate is not automatically activated.
17
+ Code, shell/effect calls and artifact delivery require explicit host authorization. Bound loops and parallelism; uncertainty should escalate or select an explicit fallback.
18
+ Example: {"v":2,"name":"summarize","schemas":{"Result":{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"],"additionalProperties":false}},"output":{"schemaId":"Result","path":"result"},"root":{"node":"extract","label":"summarize","instructions":"Summarize the text field from the JSON input faithfully.","out":"Result","as":"result","requires":["text"]}}`;
19
+ export async function authorWorkflow(options) {
20
+ if (!options.request.trim())
21
+ throw new Error("Workflow request is required");
22
+ const maxCandidates = options.maxCandidates ?? 4;
23
+ if (!Number.isSafeInteger(maxCandidates) || maxCandidates < 1)
24
+ throw new Error("maxCandidates must be a positive integer");
25
+ const directory = resolve(options.outputDir, `candidate-${randomUUID()}`);
26
+ await mkdir(directory, { recursive: true });
27
+ await writeFile(join(directory, "request.json"), JSON.stringify({ request: options.request, inputKeys: options.inputKeys ?? [], rubricSections: options.rubricSections ?? {}, allowExecutableCandidates: options.allowExecutableCandidates ?? false, maxCandidates }, null, 2), { flag: "wx" });
28
+ let candidates = 0;
29
+ let acceptedPath;
30
+ const runner = createPiRunner({ ...options.pi, tools: [], maxSubmissions: maxCandidates });
31
+ try {
32
+ const workflow = await runner({
33
+ kind: "agent", label: "author-workflow", tools: [],
34
+ system: [AUTHOR_CONTRACT, `Executable candidates authorized: ${options.allowExecutableCandidates ?? false}.`, `All supplied rubric sections (authoritative): ${JSON.stringify(options.rubricSections ?? {})}`],
35
+ user: `${options.request}\nAvailable input keys: ${JSON.stringify(options.inputKeys ?? [])}`,
36
+ schema: { type: "object", additionalProperties: true },
37
+ async review(value) {
38
+ candidates++;
39
+ if (candidates > maxCandidates)
40
+ throw new Error("Candidate limit exceeded");
41
+ const candidatePath = join(directory, `${String(candidates).padStart(3, "0")}.json`);
42
+ await writeFile(candidatePath, JSON.stringify(value, null, 2), { flag: "wx" });
43
+ const errors = workflowPolicyErrors(value, options);
44
+ if (!errors.length) {
45
+ try {
46
+ const verdict = validateWorkflow(value, { inputKeys: options.inputKeys });
47
+ if (!verdict.ok)
48
+ errors.push(...verdict.errors);
49
+ }
50
+ catch (error) {
51
+ errors.push(`Invalid workflow: ${error instanceof Error ? error.message : String(error)}`);
52
+ }
53
+ }
54
+ if (!errors.length && options.acceptance)
55
+ errors.push(...await options.acceptance(structuredClone(value)));
56
+ await writeFile(join(directory, `${String(candidates).padStart(3, "0")}.review.json`), JSON.stringify({ accepted: !errors.length, checks: options.acceptance ? "structural-and-host" : "structural", errors }, null, 2), { flag: "wx" });
57
+ if (errors.length)
58
+ return { accepted: false, message: errors.join("\n") };
59
+ acceptedPath = candidatePath;
60
+ return { accepted: true };
61
+ },
62
+ });
63
+ if (!acceptedPath)
64
+ throw new Error("Author returned without a retained accepted candidate");
65
+ await writeFile(join(directory, "result.json"), JSON.stringify({ status: "candidate", path: acceptedPath, candidates }, null, 2), { flag: "wx" });
66
+ return { workflow, path: acceptedPath, directory, candidates, checks: options.acceptance ? "structural-and-host" : "structural" };
67
+ }
68
+ catch (error) {
69
+ await writeFile(join(directory, "result.json"), JSON.stringify({ status: "failed", candidates, message: error instanceof Error ? error.message : String(error) }, null, 2), { flag: "wx" });
70
+ throw error;
71
+ }
72
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};