@parcha/agentrun 0.2.1 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,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 CHANGED
@@ -1,199 +1,28 @@
1
- # AgentRun TypeScript SDK
1
+ # @parcha/agentrun
2
2
 
3
- Create agents, run them on your inputs, and collect the results. Typed, promise-based, no runtime dependencies. Node 20.9 or newer, or any runtime with `fetch`.
3
+ Start AgentRun on your machine with one command:
4
4
 
5
5
  ```sh
6
- npm install @parcha/agentrun
6
+ npx @parcha/agentrun
7
7
  ```
8
8
 
9
- ## Quick start
9
+ It starts [AgentRun Server](https://github.com/Parcha-ai/agentrun/tree/main/packages/serve) on the first free port from
10
+ 7340 on this machine's loopback, keeps its data in `~/.agentrun`, prints the address the server says to open and opens
11
+ it in your browser (`--no-open`, a CI run or a machine with no display skips that). The server,
12
+ `@parcha/agentrun-serve`, is this package's one dependency, at its exact version, so `npx` installs the two together and
13
+ each version of this command runs the server it was released with. Node.js 22.19 or newer on 22, or 24.2 or newer, on
14
+ macOS or Linux.
10
15
 
11
- Set `AGENTRUN_API_KEY` in your environment, then:
16
+ pi runs every agent out of the box. The Claude Code and Codex harnesses need their own packages beside the server; when
17
+ one is missing, AgentRun says so with the one command to paste: `npx` with this package, the server and that harness's
18
+ package at their versions, with `--data` naming the same store.
12
19
 
13
- ```ts
14
- import { Agent } from "@parcha/agentrun";
20
+ With no `AGENT_MODEL`, the server runs a current model of the first provider it has a key for, Anthropic, then OpenAI,
21
+ then OpenRouter: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` or `OPENROUTER_API_KEY` in your environment, or a key saved in
22
+ the console's Settings → Model keys, which counts from the save on. Other commands are the server's:
23
+ `npx @parcha/agentrun import` brings in your local Claude Code, Codex and pi sessions, and
24
+ `npx @parcha/agentrun reset-password` clears the console's password. `--data DIR` and `--port N` change where it keeps
25
+ its data and the port it takes.
15
26
 
16
- const agent = new Agent({
17
- name: "Company verifier",
18
- instructions: "Verify the company and cite primary sources.",
19
- });
20
- const run = await agent.run("Verify acme.example");
21
- const result = await agent.wait(run.id);
22
-
23
- console.log(result.status); // "completed", "failed", "cancelled", or "blocked"
24
- console.log(result.report?.markdown); // the report, or undefined
25
- ```
26
-
27
- `Agent` saves itself on the first call that needs it. Save `agent.id` and pass `new Agent({ id })` next time to reuse it. Two things to know about `wait`. It returns for every terminal status, so check `result.status` before using the report. It gives up after 10 minutes by default and throws `PollTimeoutError`, but the run keeps going on the server. Call `agent.getRun(run.id)` later to fetch it.
28
-
29
- Outside Node, or to avoid environment variables, pass `apiKey` to the constructor.
30
-
31
- ## Build an agent from a description
32
-
33
- ```ts
34
- const agent = await Agent.create("Research companies and cite sources.");
35
- // Save agent.buildId if this process might stop.
36
- await agent.waitUntilReady(); // builds can take a few minutes
37
- const run = await agent.run("Research acme.example");
38
- ```
39
-
40
- Resume an unfinished build with `new Agent({ buildId })`. Any run method waits for the build first. A build that fails throws `BuildError`; read `error.build.error` for the reason.
41
-
42
- ## Structured output
43
-
44
- Pass a JSON schema, or any object with a `toJSONSchema()` method, as `outputSchema`. The result's `structured_output` is the parsed object.
45
-
46
- ```ts
47
- const run = await agent.run("Verify acme.example", {
48
- outputSchema: { type: "object", properties: { verified: { type: "boolean" } } },
49
- });
50
- const { structured_output } = await agent.wait(run.id);
51
- ```
52
-
53
- ## Batches
54
-
55
- Run up to 100 inputs at once. The SDK checks the limits before sending anything.
56
-
57
- ```ts
58
- const batch = await agent.batch(["Verify acme.example", "Verify beta.example"], {
59
- name: "Q3 checks",
60
- maxConcurrent: 5,
61
- idempotencyKey: "q3-checks-001",
62
- });
63
- const done = await agent.waitBatch(batch.id);
64
- for (const row of (await agent.getBatchResults(batch.id)).results) {
65
- console.log(row.row_number, row.status, row.run_id, row.headline);
66
- }
67
- ```
68
-
69
- Result rows carry each run's outcome: `headline`, `excerpt`, `report_link`, and `structured_output`. The inputs are on the batch itself: `(await agent.getBatch(batch.id)).rows` gives each row's `question` and `row_data`.
70
-
71
- A CSV works too. Name the column that holds each input. The other columns come back as `row_data` on `getBatch(id).rows`.
72
-
73
- ```ts
74
- const batch = await agent.batch({ csv: csvText, inputColumn: "website" });
75
- for (const row of (await agent.getBatch(batch.id)).rows) {
76
- console.log(row.question, row.row_data);
77
- }
78
- ```
79
-
80
- `csv` may be a string or a `Blob`, up to 1 MB. `waitBatch` returns when the batch completes, fails, is cancelled, or pauses for attention; check `batch.paused_reason`. `cancelBatch` stops new rows; rows already running finish. `retryBatch` re-runs failed rows and spends credits. `getBatch(id, { includeRows: false })` skips per-row data on large batches.
81
-
82
- ## Loops
83
-
84
- A loop is a batch that repeats on a schedule. The first run starts immediately.
85
-
86
- ```ts
87
- const loop = await agent.loop(
88
- "Check acme.example for new filings",
89
- { frequency: "weekly", schedule_config: { hour: 9, minute: 0, day_of_week: 0 }, timezone: "America/New_York" },
90
- { name: "Weekly filings", maxCredits: 20 },
91
- );
92
- const history = await agent.getLoop(loop.id);
93
- await agent.pauseLoop(loop.id);
94
- await agent.deleteLoop(loop.id, { cancelActive: true });
95
- ```
96
-
97
- `frequency` is `daily`, `weekly`, or `monthly`. Weekly uses `day_of_week` with 0 as Monday. Monthly uses `day_of_month` from 1 to 28. `maxCredits` caps each occurrence, not the lifetime total. Inputs are frozen at creation; `updateLoop` changes only the name and cadence.
98
-
99
- ## Campaigns
100
-
101
- A campaign is a multi-stage plan. Save it as a draft, review it, then approve it with the digest of the plan you reviewed.
102
-
103
- ```ts
104
- const draft = await agent.createCampaign(plan);
105
- // read draft.stages and draft.deliverables
106
- const started = await agent.approveCampaign(draft.id, draft.review_digest!);
107
- const final = await agent.waitCampaign(started.id);
108
- const artifact = await agent.downloadCampaignArtifact(final.id, "companies");
109
- await writeFile(artifact.filename ?? "companies.xlsx", await artifact.bytes());
110
- ```
111
-
112
- `downloadCampaignArtifact` returns a `Blob` with an extra `filename`, so `arrayBuffer()`, `bytes()`, `text()`, and `type` all work. An agent configured with `run_mode: "campaign"` and a `campaign_plan` can start its template directly with `agent.campaign({ goal: "..." })`. That call starts work immediately. Approving with a stale digest throws `ConflictError`.
113
-
114
- ## Skills and integrations
115
-
116
- ```ts
117
- import { AgentRun } from "@parcha/agentrun";
118
-
119
- const client = new AgentRun();
120
- const skills = await client.listSkills({ query: "company" });
121
- const tools = await client.listIntegrations({ query: "company" });
122
-
123
- const agent = new Agent({
124
- name: "Company verifier",
125
- instructions: "Verify the company and cite evidence.",
126
- skills: skills.skills.map((s) => s.name),
127
- tools: tools.tools.filter((t) => !t.always_on).map((t) => t.name),
128
- });
129
- ```
130
-
131
- Save your own Markdown as a skill with `client.createSkill({ name, description, content })`. Creating a skill with an existing name updates it; the response has `created: false`.
132
-
133
- ## Statuses
134
-
135
- The API reports progress in its own vocabulary. The SDK maps it to a short list so your code stays simple. The original value is always in `raw_status`.
136
-
137
- | `run.status` | Means | Done |
138
- | --- | --- | --- |
139
- | `queued` | Accepted, not started. | no |
140
- | `moderation` | Content check in progress. | no |
141
- | `running` | Working. | no |
142
- | `blocked` | Needs your input, or content was rejected. | yes |
143
- | `completed` | Report is ready. | yes |
144
- | `failed` | Ran and failed, or never ran. | yes |
145
- | `cancelled` | Cancelled, deleted, or superseded. | yes |
146
-
147
- Batches use `queued`, `running`, `completed`, `completed_with_errors`, `failed`, and `cancelled`. Batch rows use `queued`, `running`, `completed`, and `failed`. A status the SDK does not recognise passes through unchanged.
148
-
149
- ## Errors
150
-
151
- Every method returns a promise, and every failure is a rejection with an error that extends `AgentRunError`.
152
-
153
- | Error | When |
154
- | --- | --- |
155
- | `AuthenticationError` | 401. Bad or missing API key. |
156
- | `PermissionDeniedError` | 403. The key lacks a scope or does not own the resource. |
157
- | `NotFoundError` | 404. |
158
- | `ConflictError` | 409. Stale review digest, or a loop already running. |
159
- | `UnprocessableEntityError` | 422. `error.body.detail` lists the bad fields. |
160
- | `RateLimitError` | 429. |
161
- | `ServiceUnavailableError` | 503. Down, or the feature is not enabled for your account. |
162
- | `APIConnectionError` | No HTTP response at all. `APITimeoutError` for a slow one. |
163
- | `InvalidResponseError` | 2xx but not the JSON the SDK expects. Usually a wrong `baseURL`. |
164
- | `BuildError` | An agent build failed. |
165
- | `PollTimeoutError` | A `wait*` call hit its local deadline. |
166
-
167
- `APIError` subclasses carry `statusCode`, `body`, and `requestId`. Include the request ID when you report a problem. The SDK checks the limits the API enforces before sending anything, such as skill content of at least 50 characters or `maxCostUsd` between 0.5 and 1000, and rejects with a plain `Error`. The SDK never retries a request on its own. Pass the same `idempotencyKey` to `run`, `batch`, `loop`, or `createCampaign` when you retry, so the server does not start the work twice.
168
-
169
- Every method accepts `{ signal }` to cancel a request or a wait from your side. Aborting stops local waiting only; it never cancels remote work. Use `cancelRun`, `cancelBatch`, or `cancelCampaign` for that.
170
-
171
- ## Configuration
172
-
173
- | Setting | Option | Environment variable | Default |
174
- | --- | --- | --- | --- |
175
- | API key | `apiKey` | `AGENTRUN_API_KEY` | required |
176
- | API root | `baseURL` | `AGENTRUN_BASE_URL` | `https://api.grep.ai/api/v2` |
177
- | Per-request timeout | `timeoutMs` | | 30000 |
178
- | Fetch implementation | `fetch` | | `globalThis.fetch` |
179
-
180
- `baseURL` must use HTTPS. Plain HTTP is allowed only for localhost. Redirects are never followed. Environment variables are read only where `process.env` exists.
181
-
182
- ## Types
183
-
184
- The package ships ESM and CommonJS builds with declarations. Responses are plain objects typed as interfaces, so `run.status` and `batch.rows` have the types your editor shows. Records keep any field the server adds later, reachable as a property. `id` is always the record's ID, whatever the API calls it. Agent records from `getAgent` and `listAgents` expose `instructions`, `skills`, and `tools`, the names `new Agent()` takes; the API's `system_prompt`, `skill_names`, and `mcp_tool_names` hold the same values.
185
-
186
- ## Development
187
-
188
- ```sh
189
- npm ci
190
- npm run typecheck
191
- npm run build
192
- npm test
193
- npm pack --dry-run
194
- ```
195
-
196
- Tests run against a fake API behind a `fetch` function. Two tests tie the SDK to the backend:
197
-
198
- - `tests/contract.test.ts` validates every request the SDK sends, and every canned response, against `tests/fixtures/public-v2.json`, the backend's generated OpenAPI document. Refresh it with `python scripts/update_contract.py <path-or-url>` when the API changes.
199
- - `tests/packaged.test.ts` starts a real local HTTP server and runs the same script the backend uses to verify packaged SDKs, against the built `dist/`.
27
+ The TypeScript SDK for the hosted AgentRun API is published as `@parcha/agentrun` 0.2.x, from its own repository; this
28
+ package starts with 0.3.0, so a dependency on `^0.2` keeps the SDK.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // npx @parcha/agentrun: AgentRun Server on this machine with one command. Node first, in syntax any Node reads, so an old one
3
+ // gets one plain line rather than a parse error; the repository's own rule (scripts/check-node.mjs).
4
+ const [major, minor] = process.versions.node.split(".").map(Number);
5
+ if (major < 22 || (major === 22 && minor < 19) || major === 23 || (major === 24 && minor < 2)) {
6
+ console.error(`AgentRun needs Node.js 22.19 or newer on 22, or 24.2 or newer; you have v${process.versions.node}.`);
7
+ process.exit(1);
8
+ }
9
+ import("../lib/start.mjs").then(({ main }) => main(process.argv.slice(2))).then((code) => { process.exitCode = code; });
package/lib/start.mjs ADDED
@@ -0,0 +1,145 @@
1
+ // `npx @parcha/agentrun`: AgentRun Server on this machine. The server is this package's dependency at its exact version, so
2
+ // npx installs the two together and this command always runs the server it was released with. The server's own CLI picks
3
+ // the port and whether to open the browser; this command passes its arguments through.
4
+ import { execFileSync, spawn } from "node:child_process";
5
+ import { readFileSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import { homedir } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+
10
+ export const SERVE_PACKAGE = "@parcha/agentrun-serve";
11
+ /** This command's package at its version, handed to the server it starts (AGENTRUN_NPX_PACKAGE), so the server's hints
12
+ * name this command. */
13
+ export const OWN_SPEC = `@parcha/agentrun@${JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version}`;
14
+ /** Where the server listens and the console is opened: this machine only. */
15
+ export const HOST = "127.0.0.1"; // key-gate: loopback-rule the server this starts listens on this machine only
16
+
17
+ /** The URL an "Open " line names: its first word after "Open ", when that is an http(s) URL on `HOST`, where the server
18
+ * this command starts listens; any text after it (what the link does) is not part of it. Undefined for any other line. */
19
+ export function openLineUrl(line) {
20
+ const word = /^Open (\S+)/.exec(line)?.[1];
21
+ if (word === undefined || !URL.canParse(word)) return undefined;
22
+ const url = new URL(word);
23
+ return (url.protocol === "http:" || url.protocol === "https:") && url.hostname === HOST ? word : undefined;
24
+ }
25
+
26
+ /** The address a person opens first, as the server says it: the URL of the first "Open " line of its output that names
27
+ * one (openLineUrl). That line is the server's interface for it (the plain address today, a single-use sign-in link
28
+ * once the server prints one), so this command never builds the address itself. Resolves undefined when the output ends
29
+ * without one; the rest of the output is read and dropped, so the server never blocks on a full pipe. */
30
+ export function openUrl(stdout) {
31
+ return new Promise((resolve) => {
32
+ let pending = "";
33
+ let found;
34
+ stdout.setEncoding("utf8");
35
+ stdout.on("data", (chunk) => {
36
+ if (found !== undefined) return;
37
+ pending += chunk;
38
+ for (let end = pending.indexOf("\n"); end >= 0 && found === undefined; end = pending.indexOf("\n")) {
39
+ const line = pending.slice(0, end).replace(/\r$/, "");
40
+ pending = pending.slice(end + 1);
41
+ const url = openLineUrl(line);
42
+ if (url !== undefined) resolve((found = url));
43
+ }
44
+ });
45
+ stdout.on("end", () => resolve(found));
46
+ });
47
+ }
48
+
49
+ /** A process's command line, or undefined once it is gone: from /proc on Linux, else from ps. */
50
+ export function commandOf(pid) {
51
+ try {
52
+ if (process.platform === "linux") return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").join(" ").trim() || undefined;
53
+ return execFileSync("ps", ["-o", "args=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || undefined;
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ }
58
+
59
+ /** A process's parent, or undefined once it is gone. */
60
+ export function parentOf(pid) {
61
+ try {
62
+ if (process.platform === "linux") return Number(readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[1]);
63
+ const out = execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
64
+ return out ? Number(out) : undefined;
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ const isNpm = (command) => /^npm(?:\s|$)/.test(command ?? "");
71
+
72
+ /** The npm that runs this command, when `npm exec` (npx) started it: npm says so in the environment (`npm_command` is
73
+ * exec, in npm 10 and 11) and names its own process `npm exec …`, two steps up (npm, its `sh -c`, this). Undefined for
74
+ * a command started any other way, which watches nothing. */
75
+ export function npmExecOf(env, from = process.ppid) {
76
+ if (env.npm_command !== "exec") return undefined;
77
+ for (let pid = from, step = 0; pid > 1 && step < 3; step++, pid = parentOf(pid)) if (isNpm(commandOf(pid))) return pid;
78
+ return undefined;
79
+ }
80
+
81
+ export const USAGE = "Usage: npx @parcha/agentrun [--port N] [--data DIR] [--no-open], or a server command: import, reset-password";
82
+
83
+ /** The server's launcher, installed with this package (its dependency), or undefined. */
84
+ export function installedServer(resolve = createRequire(import.meta.url).resolve) {
85
+ try {
86
+ return join(dirname(resolve(`${SERVE_PACKAGE}/package.json`)), "launcher", "agentrun-serve");
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ }
91
+
92
+ /** The server's arguments: this command's own, with the browser opened unless --no-open says not to (the server's
93
+ * --open, which itself skips a CI run and a machine with no display). */
94
+ export const serverArgs = (argv) => (argv.includes("--no-open") ? argv.filter((arg) => arg !== "--no-open") : ["--open", ...argv]);
95
+
96
+ export async function main(argv, env = process.env) {
97
+ if (argv.includes("--help") || argv.includes("-h")) return console.log(USAGE), 0;
98
+ if (process.platform === "win32") return console.error("AgentRun's server runs on macOS and Linux; on Windows, use WSL or its container."), 1;
99
+ const launcher = installedServer();
100
+ if (launcher === undefined) return console.error(`AgentRun's server (${SERVE_PACKAGE}) is not installed beside this command; run it as npx ${OWN_SPEC}.`), 1;
101
+ const childEnv = { AGENTRUN_LOG: "quiet", ...env, AGENTRUN_NPX_PACKAGE: OWN_SPEC };
102
+ // Started by npx, this runs under npm exec and its `sh -c`. A signal to npm alone (a process manager's SIGTERM or
103
+ // SIGKILL) ends npm and leaves this, and the server, with nobody to stop them: this finds that npm now, at its start,
104
+ // and stops the server when it goes. Started any other way, it watches nothing, so a shell's own rules apply (`&`,
105
+ // nohup).
106
+ const npm = npmExecOf(env);
107
+ const npmGone = () => npm !== undefined && !isNpm(commandOf(npm));
108
+ // The data directory is ~/.agentrun unless --data names one, handed to the server and its subcommands (import,
109
+ // reset-password) as --data (the server's own default is another directory). The server's hints name it too, so each
110
+ // opens this same store.
111
+ const at = argv.indexOf("--data");
112
+ const data = ["--data", at >= 0 ? argv[at + 1] : join(homedir(), ".agentrun")];
113
+ const rest = at >= 0 ? [...argv.slice(0, at), ...argv.slice(at + 2)] : argv;
114
+ if (rest[0] && !rest[0].startsWith("-")) {
115
+ return new Promise((resolve) => spawn(launcher, [rest[0], ...data, ...rest.slice(1)], { stdio: "inherit", env: childEnv }).on("exit", (code) => resolve(code ?? 1)));
116
+ }
117
+ // The server's banner and request lines stay out of this terminal: one line here says where to go, the URL of the
118
+ // server's own "Open " line. What it prints on stderr (why it did not start) comes through as it is.
119
+ const child = spawn(launcher, serverArgs([...data, ...rest]), { stdio: ["ignore", "pipe", "inherit"], env: childEnv });
120
+ const exited = new Promise((resolve) => child.on("exit", (code) => resolve(code ?? 1)));
121
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => child.kill(signal));
122
+ // A SIGHUP to this command alone (not the terminal's, which reaches the server too) asks the server to stop as a SIGTERM
123
+ // does.
124
+ process.on("SIGHUP", () => child.kill("SIGTERM"));
125
+ // When that npm goes, the server stops, as on a SIGTERM, and this ends.
126
+ if (npm !== undefined) {
127
+ const watch = setInterval(() => {
128
+ if (!npmGone()) return;
129
+ clearInterval(watch);
130
+ child.kill("SIGTERM");
131
+ }, 1000);
132
+ watch.unref();
133
+ child.on("exit", () => clearInterval(watch));
134
+ }
135
+ let timer;
136
+ const url = await Promise.race([openUrl(child.stdout), new Promise((resolve) => { timer = setTimeout(resolve, 60_000); })]);
137
+ clearTimeout(timer);
138
+ if (url === undefined) {
139
+ child.kill("SIGTERM");
140
+ console.error("AgentRun did not start; the server's lines above say why.");
141
+ return (await exited) || 1;
142
+ }
143
+ console.log(`AgentRun is running at ${url}`);
144
+ return exited;
145
+ }