@cronch/kernel 0.0.0-stage → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/cbor.js ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Deterministic CBOR (RFC 8949 section 4.2.1): the one representation of every object Cronch stores, exchanges or hashes.
3
+ * The same rules as the kernel's (`crates/kernel/src/cbor.rs`), so both produce the same bytes for the same value.
4
+ *
5
+ * Integers take their shortest form, map keys are sorted by their encoded bytes, and a number with no fractional part
6
+ * is encoded as an integer. Other numbers are float64. The data model is JSON's; map entries whose value is
7
+ * `undefined` are omitted, as absent. Decoding accepts only the deterministic encoding of what it decodes to.
8
+ */
9
+
10
+ /** Thrown when encoding something outside the data model: a non-finite number, a function, a symbol. */
11
+ export class EncodeError extends Error {
12
+ name = "EncodeError";
13
+
14
+ /** @param {string} found */
15
+ constructor(found) {
16
+ super(`Not encodable as CBOR: ${found}`);
17
+ this.found = found;
18
+ }
19
+ }
20
+
21
+ const MAX_DEPTH = 256;
22
+ const utf8 = new TextEncoder();
23
+ // `ignoreBOM` keeps a leading BOM as text, rather than silently dropping it from the decoded value.
24
+ const fromUtf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
25
+
26
+ /** @param {number[]} out @param {number} major @param {bigint} n */
27
+ const head = (out, major, n) => {
28
+ const m = major << 5;
29
+ if (n < 24n) out.push(m | Number(n));
30
+ else if (n <= 0xffn) out.push(m | 24, Number(n));
31
+ else if (n <= 0xffffn) out.push(m | 25, Number(n >> 8n), Number(n & 0xffn));
32
+ else {
33
+ const width = n <= 0xffffffffn ? 4 : 8;
34
+ out.push(m | (width === 4 ? 26 : 27));
35
+ for (let i = width - 1; i >= 0; i--) out.push(Number((n >> BigInt(i * 8)) & 0xffn));
36
+ }
37
+ };
38
+
39
+ /** @param {Uint8Array} a @param {Uint8Array} b */
40
+ const compareBytes = (a, b) => {
41
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
42
+ if (a[i] !== b[i]) return a[i] - b[i];
43
+ }
44
+ return a.length - b.length;
45
+ };
46
+
47
+ /** @param {number[]} out @param {unknown} value */
48
+ const write = (out, value) => {
49
+ if (value === null) out.push(0xf6);
50
+ else if (value === false) out.push(0xf4);
51
+ else if (value === true) out.push(0xf5);
52
+ else if (typeof value === "number") {
53
+ if (!Number.isFinite(value)) throw new EncodeError(String(value));
54
+ if (Number.isInteger(value) && Math.abs(value) < 9.2e18) {
55
+ const n = BigInt(value);
56
+ if (n >= 0n) head(out, 0, n);
57
+ else head(out, 1, -1n - n);
58
+ } else {
59
+ const view = new DataView(new ArrayBuffer(8));
60
+ view.setFloat64(0, value);
61
+ out.push(0xfb, ...new Uint8Array(view.buffer));
62
+ }
63
+ } else if (typeof value === "string") {
64
+ const bytes = utf8.encode(value);
65
+ head(out, 3, BigInt(bytes.length));
66
+ for (const b of bytes) out.push(b);
67
+ } else if (Array.isArray(value)) {
68
+ head(out, 4, BigInt(value.length));
69
+ for (const item of value) write(out, item);
70
+ } else if (typeof value === "object") {
71
+ const entries = Object.entries(value)
72
+ .filter(([, v]) => v !== undefined)
73
+ .map(([k, v]) => [encode(k), v])
74
+ .sort((a, b) => compareBytes(a[0], b[0]));
75
+ head(out, 5, BigInt(entries.length));
76
+ for (const [k, v] of entries) {
77
+ for (const b of k) out.push(b);
78
+ write(out, v);
79
+ }
80
+ } else throw new EncodeError(typeof value);
81
+ };
82
+
83
+ /** Encode any JSON-shaped value. @param {unknown} value @returns {Uint8Array} */
84
+ export const encode = (value) => {
85
+ const out = [];
86
+ write(out, value);
87
+ return Uint8Array.from(out);
88
+ };
89
+
90
+ class Failure {
91
+ constructor(error) {
92
+ this.error = error;
93
+ }
94
+ }
95
+
96
+ /** @param {Uint8Array} bytes */
97
+ export const decode = (bytes) => {
98
+ let offset = 0;
99
+ const fail = (error) => {
100
+ throw new Failure(error);
101
+ };
102
+ const take = (n) => {
103
+ if (offset + n > bytes.length) fail({ kind: "truncated", offset });
104
+ const slice = bytes.subarray(offset, offset + n);
105
+ offset += n;
106
+ return slice;
107
+ };
108
+ const argument = (info, at) => {
109
+ if (info < 24) return BigInt(info);
110
+ const width = { 24: 1, 25: 2, 26: 4, 27: 8 }[info];
111
+ if (width === undefined) return fail({ kind: "unsupported", offset: at, initial: bytes[at] });
112
+ return take(width).reduce((n, b) => (n << 8n) | BigInt(b), 0n);
113
+ };
114
+ const safe = (n, at) =>
115
+ n > BigInt(Number.MAX_SAFE_INTEGER) ? fail({ kind: "outOfRange", offset: at }) : Number(n);
116
+
117
+ const value = (depth) => {
118
+ const at = offset;
119
+ if (depth > MAX_DEPTH) fail({ kind: "tooDeep", offset: at });
120
+ const initial = take(1)[0];
121
+ const major = initial >> 5;
122
+ const info = initial & 0x1f;
123
+ switch (major) {
124
+ case 0:
125
+ return safe(argument(info, at), at);
126
+ case 1:
127
+ return -1 - safe(argument(info, at), at);
128
+ case 3: {
129
+ const raw = take(safe(argument(info, at), at));
130
+ try {
131
+ return fromUtf8.decode(raw);
132
+ } catch {
133
+ return fail({ kind: "invalidUtf8", offset: at });
134
+ }
135
+ }
136
+ case 4: {
137
+ const length = safe(argument(info, at), at);
138
+ return Array.from({ length }, () => value(depth + 1));
139
+ }
140
+ case 5: {
141
+ const length = safe(argument(info, at), at);
142
+ const map = {};
143
+ for (let i = 0; i < length; i++) {
144
+ const keyAt = offset;
145
+ const key = value(depth + 1);
146
+ if (typeof key !== "string") fail({ kind: "nonTextKey", offset: keyAt });
147
+ if (Object.hasOwn(map, key)) fail({ kind: "duplicateKey", offset: keyAt });
148
+ map[key] = value(depth + 1);
149
+ }
150
+ return map;
151
+ }
152
+ case 7:
153
+ if (info === 20) return false;
154
+ if (info === 21) return true;
155
+ if (info === 22) return null;
156
+ if (info === 27) {
157
+ const f = new DataView(take(8).slice().buffer).getFloat64(0);
158
+ return Number.isFinite(f) ? f : fail({ kind: "notFinite", offset: at });
159
+ }
160
+ return fail({ kind: "unsupported", offset: at, initial });
161
+ default:
162
+ return fail({ kind: "unsupported", offset: at, initial });
163
+ }
164
+ };
165
+
166
+ try {
167
+ const decoded = value(0);
168
+ if (offset !== bytes.length) return { ok: false, error: { kind: "trailingBytes", offset } };
169
+ if (compareBytes(encode(decoded), bytes) !== 0) {
170
+ return { ok: false, error: { kind: "nonCanonical" } };
171
+ }
172
+ return { ok: true, value: decoded };
173
+ } catch (error) {
174
+ if (error instanceof Failure) return { ok: false, error: error.error };
175
+ throw error;
176
+ }
177
+ };
package/cli.js ADDED
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pata run [dir]`: runs the harness in `dir` on this machine, with the local host (`run.js`), and answers each ask
4
+ * at the terminal. `dir` holds one `.pata` harness and its capabilities' contracts, one `<name>.json` each, as
5
+ * `examples/claude-code` does. Without `dir`, it runs that example, which the package ships.
6
+ *
7
+ * The host's implementations: `net.ask` asks you, `net.fetch` is Node's `fetch`, and `fs` reads and writes under
8
+ * `--root`. `shell` is refused, since nothing here keeps a command off the network. The model, `brain.choose`, is a
9
+ * module you pass with `--model`, or the scripted demo: it fetches the first URL in the task and answers.
10
+ */
11
+
12
+ import { existsSync } from "node:fs";
13
+ import { readdir, readFile, writeFile } from "node:fs/promises";
14
+ import { isAbsolute, join, relative, resolve } from "node:path";
15
+ import { createInterface } from "node:readline";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import { parseArgs } from "node:util";
18
+ import { run } from "./run.js";
19
+
20
+ const USAGE = `usage: pata run [dir] [--input <task>] [--root <dir>] [--model <module.js>]
21
+
22
+ dir a harness and its contracts (default: T1's example, examples/claude-code)
23
+ --input the task the run starts with (default: a demo task)
24
+ --root the directory fs reads and writes under (default: the current one)
25
+ --model a module whose default export answers brain.choose (default: a scripted demo)`;
26
+
27
+ const DEMO_TASK = "Fetch https://example.com/ and tell me its title.";
28
+
29
+ /** T1's example: in the package, where `prepack` copies it, or in the repo. */
30
+ const EXAMPLE = ["./examples/claude-code", "../examples/claude-code"]
31
+ .map((path) => fileURLToPath(new URL(path, import.meta.url)))
32
+ .find((path) => existsSync(path));
33
+
34
+ /** Lines read from standard input, one per ask, whether it's a terminal or a pipe. */
35
+ function lines() {
36
+ const rl = createInterface({ input: process.stdin, terminal: false });
37
+ const heard = [];
38
+ const waiting = [];
39
+ let ended = false;
40
+ rl.on("line", (line) => (waiting.length > 0 ? waiting.shift()(line) : heard.push(line)));
41
+ rl.on("close", () => {
42
+ ended = true;
43
+ for (const w of waiting.splice(0)) w(null);
44
+ });
45
+ return {
46
+ next: () =>
47
+ heard.length > 0
48
+ ? Promise.resolve(heard.shift())
49
+ : ended
50
+ ? Promise.resolve(null)
51
+ : new Promise((r) => waiting.push(r)),
52
+ close: () => rl.close(),
53
+ };
54
+ }
55
+
56
+ /** The scripted demo model: fetch the first URL in the task, then answer from what came back. */
57
+ async function demoModel({ messages }) {
58
+ const task = messages[0]?.content ?? "";
59
+ const last = messages.at(-1);
60
+ if (messages.length === 1) {
61
+ const url = task.match(/https?:\/\/[^\s"'<>]+[^\s"'<>.,;:!?)]/)?.[0];
62
+ return url
63
+ ? { kind: "net.fetch", url }
64
+ : { kind: "answer", text: "There's no URL in the task." };
65
+ }
66
+ const title = last.content.match(/<title>([^<]*)<\/title>/i)?.[1]?.trim();
67
+ if (last.content === "denied")
68
+ return { kind: "answer", text: "You didn't allow it, so I didn't fetch it." };
69
+ return {
70
+ kind: "answer",
71
+ text: title ? `Its title is "${title}".` : `It answered: ${last.content.slice(0, 200)}`,
72
+ };
73
+ }
74
+
75
+ /** `path` under `root`, or a throw if it would leave it. */
76
+ function under(root, path) {
77
+ const full = resolve(root, path);
78
+ const rel = relative(root, full);
79
+ if (rel.startsWith("..") || isAbsolute(rel)) throw new Error(`${path} is outside ${root}`);
80
+ return full;
81
+ }
82
+
83
+ /** The host's handlers, each printing what it does to standard error, and why it failed if it did. */
84
+ function handlers(given) {
85
+ const said = {};
86
+ for (const [op, handle] of Object.entries(hosted(given))) {
87
+ said[op] = (args, context) =>
88
+ handle(args, context).catch((error) => {
89
+ process.stderr.write(`${op}: failed: ${error?.message ?? error}\n`);
90
+ throw error;
91
+ });
92
+ }
93
+ return said;
94
+ }
95
+
96
+ function hosted({ root, model, ask }) {
97
+ const say = (text) => process.stderr.write(`${text}\n`);
98
+ const refused = (op) => async () => {
99
+ throw new Error(
100
+ `${op} isn't available: the local runner has no sandbox to keep a command off the network`,
101
+ );
102
+ };
103
+ return {
104
+ "brain.choose": async (args) => {
105
+ const choice = await model(args);
106
+ say(`model: ${choice.kind === "answer" ? "answers" : `chooses ${choice.kind}`}`);
107
+ return choice;
108
+ },
109
+ "net.ask": async ({ url }) => {
110
+ process.stderr.write(`ask: allow ${url}? [y/N] `);
111
+ const line = await ask();
112
+ const answer = /^\s*y(es)?\s*$/i.test(line ?? "") ? "allow" : "deny";
113
+ // A terminal shows what was typed; a pipe doesn't.
114
+ if (!process.stdin.isTTY) say(line ?? "");
115
+ say(`ask: ${answer === "allow" ? "allowed" : "denied"}`);
116
+ return answer;
117
+ },
118
+ "net.fetch": async ({ url }, { signal }) => {
119
+ say(`net.fetch: ${url}`);
120
+ const response = await fetch(url, { signal });
121
+ return await response.text();
122
+ },
123
+ "fs.read": async ({ path }) => {
124
+ say(`fs.read: ${path}`);
125
+ return await readFile(under(root, path), "utf8");
126
+ },
127
+ "fs.write": async ({ path, text }) => {
128
+ say(`fs.write: ${path}`);
129
+ await writeFile(under(root, path), text);
130
+ return "written";
131
+ },
132
+ "shell.run": refused("shell.run"),
133
+ "shell.online": refused("shell.online"),
134
+ };
135
+ }
136
+
137
+ /** The harness and contracts in `dir`. */
138
+ async function load(dir) {
139
+ const names = await readdir(dir);
140
+ const harnesses = names.filter((n) => n.endsWith(".pata"));
141
+ if (harnesses.length !== 1)
142
+ throw new Error(`${dir} needs exactly one .pata harness, not ${harnesses.length}`);
143
+ const capabilities = {};
144
+ for (const name of names.filter((n) => n.endsWith(".json"))) {
145
+ capabilities[name.slice(0, -".json".length)] = JSON.parse(
146
+ await readFile(join(dir, name), "utf8"),
147
+ );
148
+ }
149
+ return { source: await readFile(join(dir, harnesses[0]), "utf8"), capabilities };
150
+ }
151
+
152
+ async function main(argv) {
153
+ const { values, positionals } = parseArgs({
154
+ args: argv,
155
+ allowPositionals: true,
156
+ options: {
157
+ input: { type: "string" },
158
+ root: { type: "string" },
159
+ model: { type: "string" },
160
+ help: { type: "boolean", short: "h" },
161
+ },
162
+ });
163
+ if (values.help || positionals[0] !== "run" || positionals.length > 2) {
164
+ console.error(USAGE);
165
+ return values.help ? 0 : 2;
166
+ }
167
+ const { source, capabilities } = await load(positionals[1] ?? EXAMPLE);
168
+ const model = values.model
169
+ ? (await import(pathToFileURL(resolve(values.model)).href)).default
170
+ : demoModel;
171
+ if (typeof model !== "function")
172
+ throw new Error(`${values.model} has no default export to answer brain.choose`);
173
+
174
+ const input = values.input ?? DEMO_TASK;
175
+ process.stderr.write(`task: ${input}\n`);
176
+ const stdin = lines();
177
+ try {
178
+ const { outcome } = await run(
179
+ source,
180
+ capabilities,
181
+ handlers({ root: resolve(values.root ?? "."), model, ask: stdin.next }),
182
+ { input },
183
+ );
184
+ console.log(JSON.stringify(outcome));
185
+ return outcome?.kind === "halted" ? 0 : 1;
186
+ } finally {
187
+ stdin.close();
188
+ }
189
+ }
190
+
191
+ main(process.argv.slice(2)).then(
192
+ (code) => process.exit(code),
193
+ (error) => {
194
+ console.error(`pata: ${error?.message ?? error}`);
195
+ process.exit(1);
196
+ },
197
+ );
@@ -0,0 +1,31 @@
1
+ harness claude_code(task: String) -> String
2
+
3
+ uses brain, fs, shell, net, session
4
+
5
+ type Message = {role: String, content: String}
6
+
7
+ carry history: List[Message] = [{role: "user", content: task}]
8
+ carry turns: Int = 0
9
+
10
+ stop = receive said from session.user when said == "stop"
11
+ reply = brain.choose(messages: history) until stop
12
+ choice = reply
13
+ url = match choice { net.fetch(c) => c.url, shell.online(c) => c.url, _ => "" }
14
+ asked = net.ask(url: url) when url != "" until stop
15
+ result = perform choice when (match asked { ok(a) => a == "allow", skipped => true, _ => false }) until stop
16
+
17
+ answer = match choice { answer(a) => a.text, _ => "" }
18
+ seen = match result {
19
+ ok(v) => v
20
+ failed(e) => concat("failed: ", e)
21
+ refused => "not allowed"
22
+ skipped => "denied"
23
+ }
24
+ heard = match stop { ok(s) => true, skipped => false }
25
+
26
+ next history = append(append(history, {role: "assistant", content: str(choice)}), {role: "tool", content: seen})
27
+ next turns = turns + 1
28
+
29
+ return (if heard then "interrupted" else answer) when heard or answer != "" or turns >= 20
30
+
31
+ otherwise return "interrupted"
@@ -0,0 +1,25 @@
1
+ {
2
+ "operations": {
3
+ "choose": {
4
+ "input": {
5
+ "Record": {
6
+ "messages": { "List": { "Record": { "role": "String", "content": "String" } } }
7
+ }
8
+ },
9
+ "output": {
10
+ "Variant": {
11
+ "tag": "kind",
12
+ "cases": {
13
+ "answer": { "Record": { "text": "String" } },
14
+ "fs.read": { "Record": { "path": "String" } },
15
+ "fs.write": { "Record": { "path": "String", "text": "String" } },
16
+ "shell.run": { "Record": { "command": "String" } },
17
+ "shell.online": { "Record": { "command": "String", "url": "String" } },
18
+ "net.fetch": { "Record": { "url": "String" } }
19
+ }
20
+ }
21
+ },
22
+ "ret": { "e": "list", "items": [{ "e": "lit", "v": "model" }] }
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "operations": {
3
+ "read": { "input": { "Record": { "path": "String" } }, "output": "String" },
4
+ "write": {
5
+ "input": { "Record": { "path": "String", "text": "String" } },
6
+ "output": "String",
7
+ "effect": true
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "operations": {
3
+ "call": {
4
+ "input": { "Record": { "server": "String", "tool": "String", "input": "String" } },
5
+ "output": "String",
6
+ "effect": true,
7
+ "pre": {
8
+ "e": "op",
9
+ "op": "contains",
10
+ "args": [
11
+ { "e": "get", "of": { "e": "var", "name": "grant" }, "field": "netAllow" },
12
+ { "e": "get", "of": { "e": "var", "name": "args" }, "field": "server" }
13
+ ]
14
+ },
15
+ "ret": { "e": "list", "items": [{ "e": "lit", "v": "web" }] },
16
+ "footprint": {
17
+ "e": "record",
18
+ "fields": {
19
+ "reaches": { "e": "get", "of": { "e": "var", "name": "args" }, "field": "server" }
20
+ }
21
+ }
22
+ }
23
+ },
24
+ "grant": { "Record": { "netAllow": { "List": "String" } } }
25
+ }