@motiontic/basal 0.0.0-stage → 0.3.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/README.md +36 -2
- package/dist/basal.mjs +1111 -0
- package/package.json +40 -4
package/README.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Basal CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Basal records your coding-agent sessions, finds the moments where the agent got it wrong, and turns them into tasks with hidden tests. Names, keys and secrets are masked on your machine before anything is sent.
|
|
4
|
+
|
|
5
|
+
Needs Node 20 or newer. No other dependencies.
|
|
6
|
+
|
|
7
|
+
## Connect a machine
|
|
8
|
+
|
|
9
|
+
1. Sign in at https://basal.motiontic.com/app.
|
|
10
|
+
2. Open **Agents → Connect a machine** and create a device key.
|
|
11
|
+
3. Run the command it shows:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npx @motiontic/basal connect --key <device key>
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
This saves your key to `~/.basal/config.json` (readable only by you) and adds a Claude Code hook, so each finished session is masked and uploaded. To stop recording, pause the agent under **Agents** in the app, or revoke the key.
|
|
18
|
+
|
|
19
|
+
To use plain `basal` instead of `npx @motiontic/basal`:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install -g @motiontic/basal
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Commands
|
|
26
|
+
|
|
27
|
+
| Command | What it does |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `connect --key <key>` | Save your key and install hooks for Claude Code (Codex gets a one-line config) |
|
|
30
|
+
| `import --agent claude-code --days 14` | Upload past sessions |
|
|
31
|
+
| `preview <file.jsonl>` | Show exactly what would be stored, after masking, without sending anything |
|
|
32
|
+
| `push --agent <agent> --transcript <file>` | Upload one transcript |
|
|
33
|
+
| `wrap -- <command>` | Record any agent that talks over stdin/stdout |
|
|
34
|
+
| `run <task> --agent <name> --tries N --cmd "<agent command>"` | Try an agent on a task; graded on Basal, so the tests stay hidden |
|
|
35
|
+
| `gates <task>` | Show a task's gate results |
|
|
36
|
+
|
|
37
|
+
Running a self-hosted Basal? Add `--server https://your-basal.example.com` to `connect`, or set `BASAL_SERVER`.
|
package/dist/basal.mjs
ADDED
|
@@ -0,0 +1,1111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/main.ts
|
|
4
|
+
import { execFileSync, spawn as spawn2 } from "node:child_process";
|
|
5
|
+
import { appendFileSync, copyFileSync as copyFileSync2, existsSync as existsSync3, mkdirSync as mkdirSync3, readdirSync, readFileSync as readFileSync3, statSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
6
|
+
import { basename, join as join4, resolve as resolvePath } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
|
|
9
|
+
// ../core/src/types.ts
|
|
10
|
+
var AGENTS = ["claude-code", "codex", "cursor", "gemini-cli", "sdk"];
|
|
11
|
+
|
|
12
|
+
// ../core/src/passrate.ts
|
|
13
|
+
var SWEET_LOW = 2;
|
|
14
|
+
var SWEET_HIGH = 30;
|
|
15
|
+
var RETIRE_AT = 70;
|
|
16
|
+
function passRate(passes, tries) {
|
|
17
|
+
if (tries <= 0) return { tries: 0, passes: 0, rate: 0, pm: 0, band: "too_hard" };
|
|
18
|
+
const p = passes / tries;
|
|
19
|
+
const rate = Math.round(p * 100);
|
|
20
|
+
const pm = Math.round(Math.sqrt(p * (1 - p) / tries) * 100);
|
|
21
|
+
const band = rate < SWEET_LOW ? "too_hard" : rate <= SWEET_HIGH ? "sweet" : rate < RETIRE_AT ? "warm" : "saturated";
|
|
22
|
+
return { tries, passes, rate, pm, band };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ../core/src/scrub.ts
|
|
26
|
+
var SECRET_DETECTORS = [
|
|
27
|
+
{ kind: "secret", label: "stripe_key", re: /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9…]{8,}\b/g },
|
|
28
|
+
{ kind: "secret", label: "anthropic_key", re: /\bsk-ant-[A-Za-z0-9_\-]{10,}\b/g },
|
|
29
|
+
{ kind: "secret", label: "openai_key", re: /\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}\b/g },
|
|
30
|
+
{ kind: "secret", label: "github_token", re: /\b(?:ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}\b/g },
|
|
31
|
+
{ kind: "secret", label: "aws_key", re: /\bAKIA[0-9A-Z]{16}\b/g },
|
|
32
|
+
{ kind: "secret", label: "slack_token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g },
|
|
33
|
+
{ kind: "secret", label: "jwt", re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g },
|
|
34
|
+
{ kind: "secret", label: "private_key", re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g },
|
|
35
|
+
{ kind: "secret", label: "db_url", re: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis):\/\/[^\s'"`]+/g },
|
|
36
|
+
{
|
|
37
|
+
kind: "secret",
|
|
38
|
+
label: "assigned_secret",
|
|
39
|
+
// KEY=value where the key name says it's a secret. The key must not be part of a mask
|
|
40
|
+
// ("‹SECRET:stripe_key›" is not "SECRET: value") and an already-masked value is left alone.
|
|
41
|
+
re: /(?<=(?<![‹\w])[A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY)[A-Z0-9_]*\s*[=:]\s*["']?)(?!‹)[^\s"'`]{6,}/g,
|
|
42
|
+
// Belt and braces: never re-mask anything that touches a mask.
|
|
43
|
+
keep: (m) => !/[‹›]/.test(m)
|
|
44
|
+
}
|
|
45
|
+
];
|
|
46
|
+
var PERSONAL_DETECTORS = [
|
|
47
|
+
{ kind: "personal", label: "EMAIL", re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, keep: (m) => !/@(?:example|users\.noreply\.github)\./i.test(m) && !/\.test$/i.test(m) },
|
|
48
|
+
{ kind: "personal", label: "CARD", re: /\b\d(?:[ -]?\d){12,15}\b/g, keep: luhn },
|
|
49
|
+
{ kind: "personal", label: "PHONE", re: /(?<![\w.])\+?\d{1,3}[\s.-]?\(?\d{2,4}\)?[\s.-]?\d{3,4}[\s.-]?\d{3,4}(?![\w.])/g, keep: (m) => m.replace(/\D/g, "").length >= 10 },
|
|
50
|
+
{ kind: "personal", label: "IP", re: /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g, keep: (m) => !/^(?:127\.|0\.|10\.0\.0\.|255\.)/.test(m) },
|
|
51
|
+
{ kind: "personal", label: "SSN", re: /\b\d{3}-\d{2}-\d{4}\b/g }
|
|
52
|
+
];
|
|
53
|
+
var BUSINESS_IDS = [
|
|
54
|
+
// IBANs, written solid or in groups of four ("FR14 2004 1010 0505 0001 3M02 606").
|
|
55
|
+
{ kind: "business", label: "IBAN", re: /\b[A-Z]{2}\d{2}(?:[A-Z0-9]{11,30}|(?: [A-Z0-9]{4}){2,7}(?: [A-Z0-9]{1,4})?)\b/g },
|
|
56
|
+
{ kind: "business", label: "INVOICE", re: /\b(?:INV|inv)[-_]?\d{4,}\b/g },
|
|
57
|
+
{ kind: "business", label: "ACCOUNT", re: /\b(?:acct|cus|org|tenant|ten)_[A-Za-z0-9]{6,}\b/g }
|
|
58
|
+
];
|
|
59
|
+
var BUSINESS_NAMES = [
|
|
60
|
+
{
|
|
61
|
+
kind: "business",
|
|
62
|
+
label: "DOMAIN",
|
|
63
|
+
re: /\b(?:[a-z0-9-]+\.)+(?:internal|corp|local|lan|intranet)\b/gi
|
|
64
|
+
}
|
|
65
|
+
];
|
|
66
|
+
var BUSINESS_DETECTORS = [...BUSINESS_IDS, ...BUSINESS_NAMES];
|
|
67
|
+
function luhn(m) {
|
|
68
|
+
const d = m.replace(/\D/g, "");
|
|
69
|
+
if (d.length < 13 || d.length > 19) return false;
|
|
70
|
+
let sum = 0;
|
|
71
|
+
for (let i = 0; i < d.length; i++) {
|
|
72
|
+
let n = Number(d[d.length - 1 - i]);
|
|
73
|
+
if (i % 2) {
|
|
74
|
+
n *= 2;
|
|
75
|
+
if (n > 9) n -= 9;
|
|
76
|
+
}
|
|
77
|
+
sum += n;
|
|
78
|
+
}
|
|
79
|
+
return sum % 10 === 0;
|
|
80
|
+
}
|
|
81
|
+
function isDroppedFile(path) {
|
|
82
|
+
const base = path.split(/[\\/]/).pop() ?? path;
|
|
83
|
+
return /^\.env(?:\..+)?$/.test(base) && base !== ".env.example" || /\.(?:pem|key|p12|pfx|keystore|jks)$/i.test(base) || /^id_(?:rsa|ed25519|ecdsa|dsa)$/.test(base) || /^(?:credentials|\.npmrc|\.pypirc|\.netrc)$/.test(base);
|
|
84
|
+
}
|
|
85
|
+
var Scrubber = class {
|
|
86
|
+
#byValue = /* @__PURE__ */ new Map();
|
|
87
|
+
/** mask -> the value as first seen (case kept, so table() gives back the real value). */
|
|
88
|
+
#original = /* @__PURE__ */ new Map();
|
|
89
|
+
#next = {};
|
|
90
|
+
#counts = { personal: 0, business: 0, secrets: 0 };
|
|
91
|
+
#terms;
|
|
92
|
+
constructor(opts = {}) {
|
|
93
|
+
const terms = [...opts.hiddenTerms ?? [], ...opts.knownOrgs ?? []].map((t) => t.trim()).filter((t) => t.length >= 2).sort((a, b) => b.length - a.length);
|
|
94
|
+
this.#terms = terms.length ? new RegExp(`\\b(?:${terms.map(escapeRe).join("|")})\\b`, "gi") : null;
|
|
95
|
+
}
|
|
96
|
+
#mask(kind, label, value) {
|
|
97
|
+
const key = `${kind}:${value.toLowerCase()}`;
|
|
98
|
+
const have = this.#byValue.get(key);
|
|
99
|
+
if (have) return have;
|
|
100
|
+
const n = this.#next[label] = (this.#next[label] ?? 0) + 1;
|
|
101
|
+
const mask = kind === "secret" ? `\u2039SECRET:${label}${n > 1 ? `_${n}` : ""}\u203A` : `\u2039${label}_${n}\u203A`;
|
|
102
|
+
this.#byValue.set(key, mask);
|
|
103
|
+
this.#original.set(mask, value);
|
|
104
|
+
if (kind === "personal") this.#counts.personal++;
|
|
105
|
+
else if (kind === "business") this.#counts.business++;
|
|
106
|
+
else this.#counts.secrets++;
|
|
107
|
+
return mask;
|
|
108
|
+
}
|
|
109
|
+
scrub(input) {
|
|
110
|
+
let text = input;
|
|
111
|
+
const run2 = (ds) => {
|
|
112
|
+
for (const d of ds) text = text.replace(d.re, (m) => d.keep && !d.keep(m) ? m : this.#mask(d.kind, d.label, m));
|
|
113
|
+
};
|
|
114
|
+
run2(SECRET_DETECTORS);
|
|
115
|
+
run2(BUSINESS_IDS);
|
|
116
|
+
run2(PERSONAL_DETECTORS);
|
|
117
|
+
if (this.#terms) text = text.replace(this.#terms, (m) => this.#mask("business", "CUSTOMER", m));
|
|
118
|
+
run2(BUSINESS_NAMES);
|
|
119
|
+
return text;
|
|
120
|
+
}
|
|
121
|
+
/** Masks the org part of a repo path or git remote: github.com/acme/billing -> ‹ORG_1›/billing. */
|
|
122
|
+
scrubRepo(repo) {
|
|
123
|
+
const m = /^(?:https?:\/\/|git@)?(?:[^/:]+[/:])?([^/]+)\/([^/]+?)(?:\.git)?$/.exec(repo.trim());
|
|
124
|
+
if (!m) return this.scrub(repo);
|
|
125
|
+
return `${this.#mask("business", "ORG", m[1])}/${m[2]}`;
|
|
126
|
+
}
|
|
127
|
+
counts() {
|
|
128
|
+
return { ...this.#counts };
|
|
129
|
+
}
|
|
130
|
+
/** mask -> original. LAPTOP ONLY. Never upload this. */
|
|
131
|
+
table() {
|
|
132
|
+
return Object.fromEntries(this.#original);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
function findLeaks(text, opts = {}) {
|
|
136
|
+
const leaks = [];
|
|
137
|
+
const all = [...SECRET_DETECTORS, ...BUSINESS_DETECTORS, ...PERSONAL_DETECTORS];
|
|
138
|
+
for (const d of all) {
|
|
139
|
+
d.re.lastIndex = 0;
|
|
140
|
+
for (const m of text.matchAll(new RegExp(d.re.source, d.re.flags))) {
|
|
141
|
+
if (d.keep && !d.keep(m[0])) continue;
|
|
142
|
+
leaks.push({ kind: d.kind, label: d.label });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const terms = [...opts.hiddenTerms ?? [], ...opts.knownOrgs ?? []].filter((t) => t.length >= 2);
|
|
146
|
+
for (const t of terms) if (new RegExp(`\\b${escapeRe(t)}\\b`, "i").test(text)) leaks.push({ kind: "business", label: "CUSTOMER" });
|
|
147
|
+
return leaks;
|
|
148
|
+
}
|
|
149
|
+
function escapeRe(s) {
|
|
150
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/config.ts
|
|
154
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
155
|
+
import { homedir } from "node:os";
|
|
156
|
+
import { join } from "node:path";
|
|
157
|
+
var home = () => process.env.HOME || homedir();
|
|
158
|
+
var configDir = () => process.env.BASAL_DIR || join(home(), ".basal");
|
|
159
|
+
var configPath = () => join(configDir(), "config.json");
|
|
160
|
+
function readConfig() {
|
|
161
|
+
try {
|
|
162
|
+
return JSON.parse(readFileSync(configPath(), "utf8"));
|
|
163
|
+
} catch {
|
|
164
|
+
return {};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function writeConfig(c) {
|
|
168
|
+
mkdirSync(configDir(), { recursive: true, mode: 448 });
|
|
169
|
+
writeFileSync(configPath(), `${JSON.stringify(c, null, 2)}
|
|
170
|
+
`, { mode: 384 });
|
|
171
|
+
chmodSync(configPath(), 384);
|
|
172
|
+
}
|
|
173
|
+
var DEFAULT_SERVER = "https://basal.motiontic.com";
|
|
174
|
+
function resolve(flags) {
|
|
175
|
+
const saved = readConfig();
|
|
176
|
+
const server = (str(flags.server) ?? process.env.BASAL_SERVER ?? saved.server ?? DEFAULT_SERVER).replace(/\/+$/, "");
|
|
177
|
+
const key = str(flags.key) ?? process.env.BASAL_KEY ?? saved.key;
|
|
178
|
+
return { server, key };
|
|
179
|
+
}
|
|
180
|
+
function str(v) {
|
|
181
|
+
return typeof v === "string" && v ? v : void 0;
|
|
182
|
+
}
|
|
183
|
+
var PACKAGE = "@motiontic/basal";
|
|
184
|
+
function invokedAs(script = process.argv[1] ?? "") {
|
|
185
|
+
if (/[\\/]_npx[\\/]/.test(script)) return `npx ${PACKAGE}`;
|
|
186
|
+
if (/\.mjs$/.test(script)) return "node basal.mjs";
|
|
187
|
+
return "basal";
|
|
188
|
+
}
|
|
189
|
+
var CliError = class extends Error {
|
|
190
|
+
};
|
|
191
|
+
async function call(server, key, method, path, body) {
|
|
192
|
+
let r;
|
|
193
|
+
try {
|
|
194
|
+
r = await fetch(`${server}${path}`, {
|
|
195
|
+
method,
|
|
196
|
+
headers: { authorization: `Bearer ${key}`, ...body === void 0 ? {} : { "content-type": "application/json" } },
|
|
197
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
198
|
+
});
|
|
199
|
+
} catch (e) {
|
|
200
|
+
throw new CliError(`Couldn't reach ${server} (${e.message}).`);
|
|
201
|
+
}
|
|
202
|
+
const data = await r.json().catch(() => ({}));
|
|
203
|
+
if (!r.ok) {
|
|
204
|
+
const msg = data?.error?.message ?? `Request failed (${r.status}).`;
|
|
205
|
+
throw new CliError(`${msg}${data?.error?.next ? `
|
|
206
|
+
${data.error.next}` : ""}`);
|
|
207
|
+
}
|
|
208
|
+
return data;
|
|
209
|
+
}
|
|
210
|
+
function need(c) {
|
|
211
|
+
if (!c.server || !c.key) throw new CliError(`Not connected. Run: ${invokedAs()} connect --key <device key>
|
|
212
|
+
(create a key in the app under Agents \u2192 Connect a machine)`);
|
|
213
|
+
return { server: c.server, key: c.key };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/hooks.ts
|
|
217
|
+
import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
218
|
+
import { dirname, join as join2 } from "node:path";
|
|
219
|
+
var HOOK_MARK = /(?:basal|tracebox)\.mjs"?\s+push\s+--agent\s+claude-code/;
|
|
220
|
+
function claudeHookCommand(cliPath2) {
|
|
221
|
+
return `node "${cliPath2}" push --agent claude-code --from-hook`;
|
|
222
|
+
}
|
|
223
|
+
function mergeClaudeSettings(current, command) {
|
|
224
|
+
const next = current && typeof current === "object" && !Array.isArray(current) ? structuredClone(current) : {};
|
|
225
|
+
next.hooks ??= {};
|
|
226
|
+
const stop = Array.isArray(next.hooks.Stop) ? next.hooks.Stop : [];
|
|
227
|
+
next.hooks.Stop = stop;
|
|
228
|
+
for (const group of stop) {
|
|
229
|
+
for (const h of group?.hooks ?? []) {
|
|
230
|
+
if (typeof h?.command === "string" && HOOK_MARK.test(h.command)) {
|
|
231
|
+
if (h.command === command) return { next: current, changed: false };
|
|
232
|
+
h.command = command;
|
|
233
|
+
return { next, changed: true };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
stop.push({ matcher: "", hooks: [{ type: "command", command, timeout: 60 }] });
|
|
238
|
+
return { next, changed: true };
|
|
239
|
+
}
|
|
240
|
+
function installClaudeCode(cliPath2, dryRun) {
|
|
241
|
+
const file = join2(home(), ".claude", "settings.json");
|
|
242
|
+
let current = {};
|
|
243
|
+
if (existsSync2(file)) {
|
|
244
|
+
try {
|
|
245
|
+
current = JSON.parse(readFileSync2(file, "utf8"));
|
|
246
|
+
} catch {
|
|
247
|
+
return { agent: "Claude Code", lines: [`${file} isn't valid JSON, so it was left alone. Fix it and run connect again.`] };
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const cmd = claudeHookCommand(cliPath2);
|
|
251
|
+
const { next, changed } = mergeClaudeSettings(current, cmd);
|
|
252
|
+
if (!changed) return { agent: "Claude Code", lines: [`Stop hook already installed in ${file}.`] };
|
|
253
|
+
if (dryRun) return { agent: "Claude Code", lines: [`Would add a Stop hook to ${file}:`, ` ${cmd}`, "Your other hooks and settings stay as they are."] };
|
|
254
|
+
mkdirSync2(dirname(file), { recursive: true });
|
|
255
|
+
const lines2 = [];
|
|
256
|
+
if (existsSync2(file)) {
|
|
257
|
+
const backup = `${file}.basal-backup-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
|
|
258
|
+
copyFileSync(file, backup);
|
|
259
|
+
lines2.push(`Backed up ${file} to ${backup}.`);
|
|
260
|
+
}
|
|
261
|
+
writeFileSync2(file, `${JSON.stringify(next, null, 2)}
|
|
262
|
+
`);
|
|
263
|
+
lines2.push(`Added a Stop hook to ${file}: each finished Claude Code reply pushes the session (masked on this machine first).`);
|
|
264
|
+
return { agent: "Claude Code", lines: lines2 };
|
|
265
|
+
}
|
|
266
|
+
function codexInstructions(cliPath2) {
|
|
267
|
+
return {
|
|
268
|
+
agent: "Codex",
|
|
269
|
+
lines: [
|
|
270
|
+
"Codex: add this line to ~/.codex/config.toml (top level) so each finished turn is pushed:",
|
|
271
|
+
` notify = ["node", "${cliPath2}", "push", "--agent", "codex", "--from-hook"]`,
|
|
272
|
+
`Past sessions: ${invokedAs()} import --agent codex --days 14`
|
|
273
|
+
]
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function comingSoon(name) {
|
|
277
|
+
return { agent: name, lines: [`${name}: a native adapter is coming. Until then: ${invokedAs()} wrap -- <your ${name} command>`] };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/mask.ts
|
|
281
|
+
import { createHash } from "node:crypto";
|
|
282
|
+
function globRe(glob) {
|
|
283
|
+
let re = "";
|
|
284
|
+
const g = glob.trim().replace(/^\.\//, "");
|
|
285
|
+
for (let i = 0; i < g.length; i++) {
|
|
286
|
+
const ch = g[i];
|
|
287
|
+
if (ch === "*") {
|
|
288
|
+
if (g[i + 1] === "*") {
|
|
289
|
+
re += ".*";
|
|
290
|
+
i++;
|
|
291
|
+
if (g[i + 1] === "/") i++;
|
|
292
|
+
} else re += "[^/]*";
|
|
293
|
+
} else if (ch === "?") re += "[^/]";
|
|
294
|
+
else re += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
295
|
+
}
|
|
296
|
+
return new RegExp(`(?:^|/)${re}$`);
|
|
297
|
+
}
|
|
298
|
+
function isNeverPath(path, neverPaths) {
|
|
299
|
+
const p = path.replace(/\\/g, "/");
|
|
300
|
+
return neverPaths.some((g) => globRe(g).test(p));
|
|
301
|
+
}
|
|
302
|
+
function touchedPaths(t) {
|
|
303
|
+
if (t.who !== "tool" || !t.input) return [];
|
|
304
|
+
if (t.tool === "bash" || t.tool === "test") return t.input.split(/[\s"'`;|&<>()=]+/).filter((w) => w && !w.startsWith("-"));
|
|
305
|
+
return t.input.split(/,\s*/).filter(Boolean);
|
|
306
|
+
}
|
|
307
|
+
function hashId(s) {
|
|
308
|
+
return createHash("sha256").update(`tracebox:${s}`).digest("hex").slice(0, 32);
|
|
309
|
+
}
|
|
310
|
+
function maskSession(raw, opts = {}) {
|
|
311
|
+
const hiddenTerms = opts.hiddenTerms ?? [];
|
|
312
|
+
const neverPaths = opts.neverPaths ?? [];
|
|
313
|
+
const sc = new Scrubber({ hiddenTerms, knownOrgs: opts.knownOrgs });
|
|
314
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
315
|
+
const turns = raw.turns.map((t) => {
|
|
316
|
+
const hits = touchedPaths(t).filter((p) => isDroppedFile(p) || isNeverPath(p, neverPaths));
|
|
317
|
+
const out2 = { who: t.who, text: "" };
|
|
318
|
+
if (t.tool) out2.tool = sc.scrub(t.tool);
|
|
319
|
+
if (t.input !== void 0) out2.input = sc.scrub(t.input);
|
|
320
|
+
if (t.exit !== void 0) out2.exit = t.exit;
|
|
321
|
+
if (t.at) out2.at = t.at;
|
|
322
|
+
if (hits.length) {
|
|
323
|
+
for (const h of hits) dropped.add(sc.scrub(h));
|
|
324
|
+
out2.text = `[dropped: ${hits.map((h) => sc.scrub(h)).join(", ")} is never uploaded]`;
|
|
325
|
+
} else {
|
|
326
|
+
out2.text = sc.scrub(t.text);
|
|
327
|
+
}
|
|
328
|
+
return out2;
|
|
329
|
+
});
|
|
330
|
+
const repoRaw = raw.repo || (raw.cwd ? raw.cwd.split(/[\\/]/).filter(Boolean).pop() : "") || "unknown";
|
|
331
|
+
const repo = repoRaw.includes("/") ? sc.scrub(sc.scrubRepo(repoRaw)) : sc.scrub(repoRaw);
|
|
332
|
+
const payload = {
|
|
333
|
+
agent: raw.agent,
|
|
334
|
+
agentVersion: raw.agentVersion,
|
|
335
|
+
title: sc.scrub(raw.title),
|
|
336
|
+
startedAt: raw.startedAt,
|
|
337
|
+
repo,
|
|
338
|
+
startCommit: raw.startCommit && /^[0-9a-f]{4,40}$/i.test(raw.startCommit) ? raw.startCommit : void 0,
|
|
339
|
+
sourceId: raw.sessionId ? hashId(`${raw.agent}:${raw.sessionId}`) : void 0,
|
|
340
|
+
turns,
|
|
341
|
+
droppedFiles: [...dropped],
|
|
342
|
+
masked: sc.counts()
|
|
343
|
+
};
|
|
344
|
+
return { payload, table: sc.table(), leaks: leakCheck(payload, hiddenTerms) };
|
|
345
|
+
}
|
|
346
|
+
function leakCheck(p, hiddenTerms) {
|
|
347
|
+
const fields = [p.title, p.repo, ...p.droppedFiles, ...p.turns.flatMap((t) => [t.text, t.input ?? "", t.tool ?? ""])];
|
|
348
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
349
|
+
for (const f of fields) for (const l of findLeaks(f, { hiddenTerms })) kinds.add(`${l.kind}:${l.label}`);
|
|
350
|
+
return [...kinds];
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// src/sdk.ts
|
|
354
|
+
import { spawn } from "node:child_process";
|
|
355
|
+
import { mkdtemp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
356
|
+
import { tmpdir } from "node:os";
|
|
357
|
+
import { dirname as dirname2, join as join3, normalize, relative, sep } from "node:path";
|
|
358
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".basal"]);
|
|
359
|
+
function safeJoin(root, p) {
|
|
360
|
+
const n = normalize(p);
|
|
361
|
+
if (n.startsWith("/") || n.split(/[\\/]/).includes("..")) throw new Error(`unsafe path in task bundle: ${p}`);
|
|
362
|
+
return join3(root, n);
|
|
363
|
+
}
|
|
364
|
+
async function writeTree(root, files) {
|
|
365
|
+
for (const [p, c] of Object.entries(files)) {
|
|
366
|
+
const full = safeJoin(root, p);
|
|
367
|
+
await mkdir(dirname2(full), { recursive: true });
|
|
368
|
+
await writeFile(full, c);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async function changedFiles(root, start) {
|
|
372
|
+
const out2 = {};
|
|
373
|
+
async function walk(dir) {
|
|
374
|
+
for (const e of await readdir(dir, { withFileTypes: true })) {
|
|
375
|
+
const full = join3(dir, e.name);
|
|
376
|
+
if (e.isDirectory()) {
|
|
377
|
+
if (!SKIP_DIRS.has(e.name)) await walk(full);
|
|
378
|
+
} else if (e.isFile()) {
|
|
379
|
+
if ((await stat(full)).size > 1e6) continue;
|
|
380
|
+
const rel = relative(root, full).split(sep).join("/");
|
|
381
|
+
const c = await readFile(full, "utf8");
|
|
382
|
+
if (start[rel] !== c) out2[rel] = c;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
await walk(root);
|
|
387
|
+
return out2;
|
|
388
|
+
}
|
|
389
|
+
function runShell(cmd, cwd, env, timeoutMs) {
|
|
390
|
+
return new Promise((resolve2) => {
|
|
391
|
+
const child = spawn(process.env.SHELL || "/bin/sh", ["-c", cmd], { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "inherit", "inherit"] });
|
|
392
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
|
|
393
|
+
child.on("close", (code) => (clearTimeout(timer), resolve2(code)));
|
|
394
|
+
child.on("error", () => (clearTimeout(timer), resolve2(-1)));
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
function rateLine(agent, passes, tries) {
|
|
398
|
+
const r = passRate(passes, tries);
|
|
399
|
+
return `${agent} ${passes} of ${tries} (${r.rate}% \xB1 ${r.pm})`;
|
|
400
|
+
}
|
|
401
|
+
async function runTask(o) {
|
|
402
|
+
const bundle = await o.call("GET", `/api/tasks/${encodeURIComponent(o.task)}/bundle`);
|
|
403
|
+
o.log(`Task ${bundle.slug}: ${o.tries} tr${o.tries === 1 ? "y" : "ies"} with ${o.agent}. Hidden tests stay on the server.`);
|
|
404
|
+
let passes = 0;
|
|
405
|
+
for (let i = 1; i <= o.tries; i++) {
|
|
406
|
+
const dir = await mkdtemp(join3(tmpdir(), "basal-try-"));
|
|
407
|
+
try {
|
|
408
|
+
await writeTree(dir, bundle.startFiles);
|
|
409
|
+
await writeFile(join3(dir, ".basal-instruction.md"), `${bundle.instruction}
|
|
410
|
+
`);
|
|
411
|
+
const exit = await runShell(o.cmd, dir, { BASAL_INSTRUCTION: bundle.instruction, BASAL_TASK: bundle.slug, BASAL_TRY: String(i) }, o.timeoutSec * 1e3);
|
|
412
|
+
const files = await changedFiles(dir, { ...bundle.startFiles, ".basal-instruction.md": `${bundle.instruction}
|
|
413
|
+
` });
|
|
414
|
+
delete files[".basal-instruction.md"];
|
|
415
|
+
const g = await o.call("POST", `/api/tasks/${encodeURIComponent(bundle.id)}/grade`, { agent: o.agent, files });
|
|
416
|
+
if (g.pass) passes++;
|
|
417
|
+
o.log(` try ${i}: ${g.pass ? "pass" : "fail"} (${g.verdict}${exit !== 0 ? `, agent exited ${exit}` : ""}, ${Object.keys(files).length} file${Object.keys(files).length === 1 ? "" : "s"} changed)`);
|
|
418
|
+
} finally {
|
|
419
|
+
await rm(dir, { recursive: true, force: true });
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return { passes, tries: o.tries, line: rateLine(o.agent, passes, o.tries) };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// src/transcripts.ts
|
|
426
|
+
var TEST_CMD_RE = /\b(?:npm (?:run )?test|pnpm (?:run )?test|yarn test|npx (?:vitest|jest)|vitest|jest|pytest|go test|cargo test|node --test|mocha|rspec|make test|bun test|deno test)\b/i;
|
|
427
|
+
var OUT_MAX = 2e3;
|
|
428
|
+
function tail(s, n = OUT_MAX) {
|
|
429
|
+
const t = s.replace(/\r/g, "").trim();
|
|
430
|
+
return t.length > n ? `\u2026${t.slice(-n)}` : t;
|
|
431
|
+
}
|
|
432
|
+
function lines(s) {
|
|
433
|
+
return typeof s === "string" && s.length ? s.split("\n").length : 0;
|
|
434
|
+
}
|
|
435
|
+
function titleFrom(turns) {
|
|
436
|
+
const first = turns.find((t2) => t2.who === "user" && t2.text.trim());
|
|
437
|
+
const t = (first?.text ?? "").replace(/\s+/g, " ").trim();
|
|
438
|
+
return t.length > 80 ? `${t.slice(0, 79)}\u2026` : t || "Untitled session";
|
|
439
|
+
}
|
|
440
|
+
function parseJsonl(text) {
|
|
441
|
+
const out2 = [];
|
|
442
|
+
for (const line of text.split("\n")) {
|
|
443
|
+
const l = line.trim();
|
|
444
|
+
if (!l) continue;
|
|
445
|
+
try {
|
|
446
|
+
out2.push(JSON.parse(l));
|
|
447
|
+
} catch {
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return out2;
|
|
451
|
+
}
|
|
452
|
+
function shellTurn(cmd, output, exit, at) {
|
|
453
|
+
const isTest = TEST_CMD_RE.test(cmd);
|
|
454
|
+
const out2 = tail(output);
|
|
455
|
+
const t = isTest ? { who: "tool", tool: "test", input: cmd, text: `${cmd} \u2192 ${out2}` } : { who: "tool", tool: "bash", input: cmd, text: out2 };
|
|
456
|
+
if (exit !== void 0) t.exit = exit;
|
|
457
|
+
if (at) t.at = at;
|
|
458
|
+
return t;
|
|
459
|
+
}
|
|
460
|
+
function blockText(c) {
|
|
461
|
+
if (typeof c === "string") return c;
|
|
462
|
+
if (Array.isArray(c)) return c.map((b) => typeof b === "string" ? b : b?.type === "text" ? String(b.text ?? "") : "").filter(Boolean).join("\n");
|
|
463
|
+
return "";
|
|
464
|
+
}
|
|
465
|
+
function cleanUserText(s) {
|
|
466
|
+
return s.replace(/<command-(?:name|message|args)>([\s\S]*?)<\/command-(?:name|message|args)>/g, "$1 ").replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>/g, "").replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "").replace(/\s+\n/g, "\n").trim();
|
|
467
|
+
}
|
|
468
|
+
function claudeToolTurn(name, input) {
|
|
469
|
+
const n = name.toLowerCase();
|
|
470
|
+
if (["edit", "multiedit", "write", "notebookedit"].includes(n)) {
|
|
471
|
+
const path = String(input?.file_path ?? input?.notebook_path ?? "");
|
|
472
|
+
let add = 0;
|
|
473
|
+
let del = 0;
|
|
474
|
+
if (n === "write") add = lines(input?.content);
|
|
475
|
+
else if (n === "multiedit") for (const e of input?.edits ?? []) add += lines(e?.new_string), del += lines(e?.old_string);
|
|
476
|
+
else if (n === "notebookedit") add = lines(input?.new_source);
|
|
477
|
+
else add = lines(input?.new_string), del = lines(input?.old_string);
|
|
478
|
+
return { who: "tool", tool: "edit", input: path, text: `${path} +${add}${del ? ` \u2212${del}` : ""}` };
|
|
479
|
+
}
|
|
480
|
+
if (n === "bash") return { who: "tool", tool: "bash", input: String(input?.command ?? ""), text: "" };
|
|
481
|
+
const target = input?.file_path ?? input?.path ?? input?.pattern ?? input?.url ?? input?.query ?? input?.description ?? "";
|
|
482
|
+
return { who: "tool", tool: n, input: String(target).slice(0, 300), text: `${name} ${String(target).slice(0, 200)}`.trim() };
|
|
483
|
+
}
|
|
484
|
+
function parseClaudeCode(text) {
|
|
485
|
+
const rows = parseJsonl(text);
|
|
486
|
+
const turns = [];
|
|
487
|
+
const pending = /* @__PURE__ */ new Map();
|
|
488
|
+
let sessionId;
|
|
489
|
+
let cwd;
|
|
490
|
+
let version;
|
|
491
|
+
let startedAt;
|
|
492
|
+
for (const r of rows) {
|
|
493
|
+
if (r?.type !== "user" && r?.type !== "assistant") continue;
|
|
494
|
+
if (r.isSidechain || r.isMeta) continue;
|
|
495
|
+
sessionId ??= r.sessionId;
|
|
496
|
+
cwd ??= r.cwd;
|
|
497
|
+
version ??= r.version;
|
|
498
|
+
startedAt ??= r.timestamp;
|
|
499
|
+
const at = typeof r.timestamp === "string" ? r.timestamp : void 0;
|
|
500
|
+
const content = r.message?.content;
|
|
501
|
+
if (r.type === "user") {
|
|
502
|
+
if (typeof content === "string") {
|
|
503
|
+
const t2 = cleanUserText(content);
|
|
504
|
+
if (t2) turns.push({ who: "user", text: t2, ...at ? { at } : {} });
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
if (!Array.isArray(content)) continue;
|
|
508
|
+
const texts = [];
|
|
509
|
+
for (const b of content) {
|
|
510
|
+
if (b?.type === "tool_result") {
|
|
511
|
+
const idx = pending.get(b.tool_use_id);
|
|
512
|
+
if (idx === void 0) continue;
|
|
513
|
+
pending.delete(b.tool_use_id);
|
|
514
|
+
const t2 = turns[idx];
|
|
515
|
+
const output = blockText(b.content);
|
|
516
|
+
if (t2.tool === "bash") {
|
|
517
|
+
const m = /^Exit code (\d+)/m.exec(output);
|
|
518
|
+
const exit = m ? Number(m[1]) : b.is_error ? 1 : 0;
|
|
519
|
+
turns[idx] = shellTurn(t2.input ?? "", output.replace(/^Exit code \d+\n?/m, ""), exit, t2.at);
|
|
520
|
+
} else if (b.is_error) {
|
|
521
|
+
t2.text = `${t2.text} (failed: ${tail(output, 300)})`;
|
|
522
|
+
}
|
|
523
|
+
} else if (b?.type === "text") {
|
|
524
|
+
texts.push(String(b.text ?? ""));
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
const t = cleanUserText(texts.join("\n"));
|
|
528
|
+
if (t) turns.push({ who: "user", text: t, ...at ? { at } : {} });
|
|
529
|
+
} else {
|
|
530
|
+
const blocks = Array.isArray(content) ? content : typeof content === "string" ? [{ type: "text", text: content }] : [];
|
|
531
|
+
for (const b of blocks) {
|
|
532
|
+
if (b?.type === "text" && String(b.text ?? "").trim()) {
|
|
533
|
+
const prev = turns[turns.length - 1];
|
|
534
|
+
if (prev?.who === "agent") prev.text += `
|
|
535
|
+
${String(b.text).trim()}`;
|
|
536
|
+
else turns.push({ who: "agent", text: String(b.text).trim(), ...at ? { at } : {} });
|
|
537
|
+
} else if (b?.type === "tool_use") {
|
|
538
|
+
const t = claudeToolTurn(String(b.name ?? "tool"), b.input);
|
|
539
|
+
if (at) t.at = at;
|
|
540
|
+
turns.push(t);
|
|
541
|
+
if (b.id) pending.set(b.id, turns.length - 1);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
for (const idx of pending.values()) {
|
|
547
|
+
const t = turns[idx];
|
|
548
|
+
if (t.tool === "bash") turns[idx] = shellTurn(t.input ?? "", "", void 0, t.at);
|
|
549
|
+
}
|
|
550
|
+
return { agent: "claude-code", agentVersion: version, sessionId, title: titleFrom(turns), startedAt: startedAt ?? (/* @__PURE__ */ new Date()).toISOString(), cwd, turns };
|
|
551
|
+
}
|
|
552
|
+
function patchTurn(patch) {
|
|
553
|
+
const files = [...patch.matchAll(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/gm)].map((m) => m[1].trim());
|
|
554
|
+
let add = 0;
|
|
555
|
+
let del = 0;
|
|
556
|
+
for (const l of patch.split("\n")) {
|
|
557
|
+
if (l.startsWith("+") && !l.startsWith("+++")) add++;
|
|
558
|
+
else if (l.startsWith("-") && !l.startsWith("---")) del++;
|
|
559
|
+
}
|
|
560
|
+
const input = files.join(", ");
|
|
561
|
+
return { who: "tool", tool: "edit", input, text: `${input} +${add}${del ? ` \u2212${del}` : ""}` };
|
|
562
|
+
}
|
|
563
|
+
function codexCommand(args) {
|
|
564
|
+
const cmd = args?.command ?? args?.cmd;
|
|
565
|
+
if (Array.isArray(cmd)) {
|
|
566
|
+
if (cmd.length >= 3 && /(?:^|\/)(?:ba|z)?sh$/.test(cmd[0]) && /^-l?c$/.test(cmd[1])) return String(cmd.slice(2).join(" "));
|
|
567
|
+
return cmd.map(String).join(" ");
|
|
568
|
+
}
|
|
569
|
+
return typeof cmd === "string" ? cmd : "";
|
|
570
|
+
}
|
|
571
|
+
function codexOutput(raw) {
|
|
572
|
+
if (typeof raw !== "string") return { output: blockText(raw) };
|
|
573
|
+
try {
|
|
574
|
+
const j = JSON.parse(raw);
|
|
575
|
+
if (j && typeof j === "object" && "output" in j) return { output: String(j.output ?? ""), exit: typeof j.metadata?.exit_code === "number" ? j.metadata.exit_code : void 0 };
|
|
576
|
+
} catch {
|
|
577
|
+
}
|
|
578
|
+
const m = /^Exit code:\s*(\d+)/m.exec(raw);
|
|
579
|
+
const body = /\nOutput:\n([\s\S]*)$/.exec(raw)?.[1] ?? raw;
|
|
580
|
+
return { output: body, exit: m ? Number(m[1]) : void 0 };
|
|
581
|
+
}
|
|
582
|
+
var CODEX_SKIP_USER = /^\s*(?:<environment_context>|<user_instructions>|<permissions|# AGENTS\.md instructions|<INSTRUCTIONS>)/;
|
|
583
|
+
function parseCodex(text) {
|
|
584
|
+
const rows = parseJsonl(text);
|
|
585
|
+
const turns = [];
|
|
586
|
+
const pending = /* @__PURE__ */ new Map();
|
|
587
|
+
let sessionId;
|
|
588
|
+
let cwd;
|
|
589
|
+
let version;
|
|
590
|
+
let startedAt;
|
|
591
|
+
let repo;
|
|
592
|
+
let startCommit;
|
|
593
|
+
for (const r of rows) {
|
|
594
|
+
const at = typeof r?.timestamp === "string" ? r.timestamp : void 0;
|
|
595
|
+
startedAt ??= at;
|
|
596
|
+
if (r?.type === "session_meta" || !r?.type && r?.id && r?.timestamp) {
|
|
597
|
+
const p = r.payload ?? r;
|
|
598
|
+
sessionId ??= p.id;
|
|
599
|
+
cwd ??= p.cwd;
|
|
600
|
+
version ??= p.cli_version;
|
|
601
|
+
startedAt ??= p.timestamp;
|
|
602
|
+
repo ??= p.git?.repository_url;
|
|
603
|
+
startCommit ??= p.git?.commit_hash;
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (r?.type === "turn_context") {
|
|
607
|
+
cwd ??= r.payload?.cwd;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
const it = r?.type === "response_item" ? r.payload : r;
|
|
611
|
+
if (!it || typeof it !== "object") continue;
|
|
612
|
+
if (it.type === "message") {
|
|
613
|
+
const txt = Array.isArray(it.content) ? it.content.map((c) => c?.text ?? "").join("\n").trim() : String(it.content ?? "").trim();
|
|
614
|
+
if (!txt) continue;
|
|
615
|
+
if (it.role === "user") {
|
|
616
|
+
if (CODEX_SKIP_USER.test(txt)) continue;
|
|
617
|
+
turns.push({ who: "user", text: txt, ...at ? { at } : {} });
|
|
618
|
+
} else if (it.role === "assistant") {
|
|
619
|
+
turns.push({ who: "agent", text: txt, ...at ? { at } : {} });
|
|
620
|
+
}
|
|
621
|
+
} else if (it.type === "function_call" || it.type === "custom_tool_call" || it.type === "local_shell_call") {
|
|
622
|
+
let args = it.arguments ?? it.input ?? it.action;
|
|
623
|
+
if (typeof args === "string") {
|
|
624
|
+
try {
|
|
625
|
+
args = JSON.parse(args);
|
|
626
|
+
} catch {
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const name = String(it.name ?? (it.type === "local_shell_call" ? "shell" : "tool"));
|
|
630
|
+
let t;
|
|
631
|
+
if (name === "apply_patch") t = patchTurn(typeof args === "string" ? args : String(args?.input ?? args?.patch ?? ""));
|
|
632
|
+
else if (name === "shell" || name === "exec_command" || name === "container.exec" || it.type === "local_shell_call") {
|
|
633
|
+
const cmd = codexCommand(args);
|
|
634
|
+
t = /^apply_patch\b/.test(cmd) ? patchTurn(cmd) : { who: "tool", tool: "bash", input: cmd, text: "" };
|
|
635
|
+
} else t = { who: "tool", tool: name.toLowerCase(), input: "", text: name };
|
|
636
|
+
if (at) t.at = at;
|
|
637
|
+
turns.push(t);
|
|
638
|
+
const cid = it.call_id ?? it.id;
|
|
639
|
+
if (cid) pending.set(cid, turns.length - 1);
|
|
640
|
+
} else if (it.type === "function_call_output" || it.type === "custom_tool_call_output" || it.type === "local_shell_call_output") {
|
|
641
|
+
const idx = pending.get(it.call_id);
|
|
642
|
+
if (idx === void 0) continue;
|
|
643
|
+
pending.delete(it.call_id);
|
|
644
|
+
const t = turns[idx];
|
|
645
|
+
const { output, exit } = codexOutput(it.output);
|
|
646
|
+
if (t.tool === "bash") turns[idx] = shellTurn(t.input ?? "", output, exit, t.at);
|
|
647
|
+
else if (exit !== void 0 && exit !== 0) t.text = `${t.text} (failed: ${tail(output, 300)})`;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
return { agent: "codex", agentVersion: version, sessionId, title: titleFrom(turns), startedAt: startedAt ?? (/* @__PURE__ */ new Date()).toISOString(), cwd, repo, startCommit, turns };
|
|
651
|
+
}
|
|
652
|
+
function detectAgent(text) {
|
|
653
|
+
const head = text.slice(0, 4e3);
|
|
654
|
+
return /"type"\s*:\s*"(?:session_meta|response_item|turn_context)"/.test(head) || /"instructions"/.test(head) ? "codex" : "claude-code";
|
|
655
|
+
}
|
|
656
|
+
function parseTranscript(agent, text) {
|
|
657
|
+
if (agent === "codex") return parseCodex(text);
|
|
658
|
+
if (agent === "claude-code") return parseClaudeCode(text);
|
|
659
|
+
throw new Error(`No transcript reader for ${agent} yet. Use \`basal wrap -- <command>\` for now.`);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// src/main.ts
|
|
663
|
+
var VERSION = "0.3.0";
|
|
664
|
+
var BOOL = /* @__PURE__ */ new Set(["dry-run", "from-hook", "help", "json", "force"]);
|
|
665
|
+
function parseArgs(argv) {
|
|
666
|
+
const dd = argv.indexOf("--");
|
|
667
|
+
const head = dd >= 0 ? argv.slice(0, dd) : argv;
|
|
668
|
+
const rest = dd >= 0 ? argv.slice(dd + 1) : [];
|
|
669
|
+
const pos = [];
|
|
670
|
+
const flags = {};
|
|
671
|
+
for (let i = 0; i < head.length; i++) {
|
|
672
|
+
const a = head[i];
|
|
673
|
+
if (a.startsWith("--")) {
|
|
674
|
+
const [k, v] = a.slice(2).split(/=(.*)/s, 2);
|
|
675
|
+
if (v !== void 0) flags[k] = v;
|
|
676
|
+
else if (BOOL.has(k) || i + 1 >= head.length || head[i + 1].startsWith("--")) flags[k] = true;
|
|
677
|
+
else flags[k] = head[++i];
|
|
678
|
+
} else if (a === "-h") flags.help = true;
|
|
679
|
+
else pos.push(a);
|
|
680
|
+
}
|
|
681
|
+
return { cmd: pos.shift() ?? "help", pos, flags, rest };
|
|
682
|
+
}
|
|
683
|
+
var out = (s = "") => process.stdout.write(`${s}
|
|
684
|
+
`);
|
|
685
|
+
var flagStr = (f, k) => typeof f[k] === "string" ? f[k] : void 0;
|
|
686
|
+
function cliPath() {
|
|
687
|
+
try {
|
|
688
|
+
return fileURLToPath(import.meta.url);
|
|
689
|
+
} catch {
|
|
690
|
+
return resolvePath(process.argv[1] ?? "basal.mjs");
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
function git(cwd, args) {
|
|
694
|
+
try {
|
|
695
|
+
return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim() || void 0;
|
|
696
|
+
} catch {
|
|
697
|
+
return void 0;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
function remoteOwner(remote) {
|
|
701
|
+
const m = remote && /^(?:https?:\/\/|ssh:\/\/)?(?:[^@/]+@)?[^/:]+[/:]([^/]+)\/[^/]+?(?:\.git)?\/?$/.exec(remote.trim());
|
|
702
|
+
return m?.[1];
|
|
703
|
+
}
|
|
704
|
+
function withGit(raw) {
|
|
705
|
+
const cwd = raw.cwd && existsSync3(raw.cwd) ? raw.cwd : void 0;
|
|
706
|
+
if (!cwd) return raw;
|
|
707
|
+
const repo = raw.repo ?? git(cwd, ["remote", "get-url", "origin"]) ?? basename(git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd);
|
|
708
|
+
const startCommit = raw.startCommit ?? git(cwd, ["rev-list", "-1", `--before=${raw.startedAt}`, "HEAD"]);
|
|
709
|
+
return { ...raw, repo, startCommit };
|
|
710
|
+
}
|
|
711
|
+
async function workspace(flags, optional = false) {
|
|
712
|
+
const c = resolve(flags);
|
|
713
|
+
if (!c.server || !c.key) {
|
|
714
|
+
if (optional) return { ws: { hidden_terms: [], never_paths: [] } };
|
|
715
|
+
need(c);
|
|
716
|
+
}
|
|
717
|
+
const conn = { server: c.server, key: c.key };
|
|
718
|
+
const ws = await call(conn.server, conn.key, "GET", "/api/cli/config");
|
|
719
|
+
return { conn, ws };
|
|
720
|
+
}
|
|
721
|
+
function prepare(raw, ws) {
|
|
722
|
+
const r = withGit(raw);
|
|
723
|
+
const owner = remoteOwner(r.repo);
|
|
724
|
+
return maskSession(r, { hiddenTerms: ws.hidden_terms, neverPaths: ws.never_paths, knownOrgs: owner ? [owner] : [] });
|
|
725
|
+
}
|
|
726
|
+
function pausedReason(agent, ws) {
|
|
727
|
+
if (ws.record === false) return "your role can't record sessions in this workspace";
|
|
728
|
+
const a = ws.agents?.find((x) => x.kind === agent);
|
|
729
|
+
return a && !a.enabled ? `recording ${agent} is paused for this workspace` : null;
|
|
730
|
+
}
|
|
731
|
+
var pushedPath = () => join4(configDir(), "pushed.json");
|
|
732
|
+
function pushedState() {
|
|
733
|
+
try {
|
|
734
|
+
return JSON.parse(readFileSync3(pushedPath(), "utf8"));
|
|
735
|
+
} catch {
|
|
736
|
+
return {};
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
function markPushed(sourceId, turns) {
|
|
740
|
+
if (!sourceId) return;
|
|
741
|
+
const s = pushedState();
|
|
742
|
+
s[sourceId] = turns;
|
|
743
|
+
mkdirSync3(configDir(), { recursive: true, mode: 448 });
|
|
744
|
+
writeFileSync3(pushedPath(), JSON.stringify(s), { mode: 384 });
|
|
745
|
+
}
|
|
746
|
+
async function upload(conn, p, leaks) {
|
|
747
|
+
if (leaks.length) throw new CliError(`Not uploaded: something still looked unmasked after masking (${leaks.join(", ")}). Nothing left this machine.`);
|
|
748
|
+
const r = await call(conn.server, conn.key, "POST", "/api/ingest", p);
|
|
749
|
+
markPushed(p.sourceId, p.turns.length);
|
|
750
|
+
return r;
|
|
751
|
+
}
|
|
752
|
+
function countsLine(p) {
|
|
753
|
+
const m = p.masked;
|
|
754
|
+
return `masked ${m.personal} personal, ${m.business} business, ${m.secrets} secret${m.secrets === 1 ? "" : "s"}${p.droppedFiles.length ? ` \xB7 dropped ${p.droppedFiles.join(", ")}` : ""}`;
|
|
755
|
+
}
|
|
756
|
+
function asAgent(v, fallback) {
|
|
757
|
+
const a = typeof v === "string" ? v : fallback;
|
|
758
|
+
if (!a || !AGENTS.includes(a)) throw new CliError(`--agent must be one of: ${AGENTS.join(", ")}`);
|
|
759
|
+
return a;
|
|
760
|
+
}
|
|
761
|
+
function walkJsonl(dir, depth, acc = []) {
|
|
762
|
+
if (!existsSync3(dir)) return acc;
|
|
763
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
764
|
+
const p = join4(dir, e.name);
|
|
765
|
+
if (e.isDirectory() && depth > 0) walkJsonl(p, depth - 1, acc);
|
|
766
|
+
else if (e.isFile() && e.name.endsWith(".jsonl")) acc.push(p);
|
|
767
|
+
}
|
|
768
|
+
return acc;
|
|
769
|
+
}
|
|
770
|
+
function transcriptFiles(agent, days) {
|
|
771
|
+
const since = Date.now() - days * 864e5;
|
|
772
|
+
const files = agent === "claude-code" ? walkJsonl(join4(home(), ".claude", "projects"), 1) : walkJsonl(join4(home(), ".codex", "sessions"), 4);
|
|
773
|
+
return files.map((f) => ({ f, m: statSync(f).mtimeMs })).filter((x) => x.m >= since).sort((a, b) => a.m - b.m).map((x) => x.f);
|
|
774
|
+
}
|
|
775
|
+
function readRaw(file, agent) {
|
|
776
|
+
if (!existsSync3(file)) throw new CliError(`No such transcript: ${file}`);
|
|
777
|
+
const text = readFileSync3(file, "utf8");
|
|
778
|
+
return parseTranscript(agent ?? detectAgent(text), text);
|
|
779
|
+
}
|
|
780
|
+
async function connect(a) {
|
|
781
|
+
const dry = !!a.flags["dry-run"];
|
|
782
|
+
const c = resolve(a.flags);
|
|
783
|
+
if (!c.server) throw new CliError("Pass --server <url> (the address of your Basal).");
|
|
784
|
+
if (!c.key) throw new CliError(`Almost there: this needs a device key.
|
|
785
|
+
1. Sign in at ${c.server}/app and open Agents \u2192 Connect a machine.
|
|
786
|
+
2. Run the command it shows you (it includes your key).`);
|
|
787
|
+
if (!/^https?:\/\//.test(c.server)) throw new CliError("--server must start with http:// or https://");
|
|
788
|
+
const which = typeof a.flags.agent === "string" ? a.flags.agent : "all";
|
|
789
|
+
const agents = which === "all" ? ["claude-code", "codex", "cursor", "gemini-cli"] : [which];
|
|
790
|
+
for (const x of agents) asAgent(x);
|
|
791
|
+
if (!dry) {
|
|
792
|
+
const ws = await call(c.server, c.key, "GET", "/api/cli/config");
|
|
793
|
+
out(`Connected to ${c.server} as ${ws.user ?? "you"}. ${ws.hidden_terms.length} hidden word${ws.hidden_terms.length === 1 ? "" : "s"} will be masked on this machine.`);
|
|
794
|
+
writeConfig({ ...readConfig(), server: c.server, key: c.key });
|
|
795
|
+
out(`Saved ${join4(configDir(), "config.json")} (readable only by you).`);
|
|
796
|
+
} else out(`Would save the server and key to ${join4(configDir(), "config.json")} (mode 600).`);
|
|
797
|
+
const stable = join4(configDir(), "basal.mjs");
|
|
798
|
+
const self = cliPath();
|
|
799
|
+
if (!dry && resolvePath(self) !== resolvePath(stable) && self.endsWith(".mjs")) {
|
|
800
|
+
mkdirSync3(configDir(), { recursive: true, mode: 448 });
|
|
801
|
+
copyFileSync2(self, stable);
|
|
802
|
+
}
|
|
803
|
+
const target = self.endsWith(".mjs") ? stable : self;
|
|
804
|
+
for (const ag of agents) {
|
|
805
|
+
const r = ag === "claude-code" ? installClaudeCode(target, dry) : ag === "codex" ? codexInstructions(target) : comingSoon(ag === "cursor" ? "Cursor" : "Gemini CLI");
|
|
806
|
+
out("");
|
|
807
|
+
for (const l of r.lines) out(l);
|
|
808
|
+
}
|
|
809
|
+
out("");
|
|
810
|
+
out(dry ? "Dry run: nothing was changed." : `Done. Check what would be stored for any transcript with: ${invokedAs()} preview <file>`);
|
|
811
|
+
}
|
|
812
|
+
async function readStdin() {
|
|
813
|
+
if (process.stdin.isTTY) return "";
|
|
814
|
+
const chunks = [];
|
|
815
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
816
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
817
|
+
}
|
|
818
|
+
function newestCodex(threadId) {
|
|
819
|
+
const files = transcriptFiles("codex", 30);
|
|
820
|
+
if (threadId) {
|
|
821
|
+
const hit = files.filter((f) => f.includes(threadId));
|
|
822
|
+
if (hit.length) return hit[hit.length - 1];
|
|
823
|
+
}
|
|
824
|
+
return files[files.length - 1];
|
|
825
|
+
}
|
|
826
|
+
async function push(a) {
|
|
827
|
+
const hook = !!a.flags["from-hook"];
|
|
828
|
+
try {
|
|
829
|
+
const agent = asAgent(a.flags.agent, "claude-code");
|
|
830
|
+
let file = flagStr(a.flags, "transcript");
|
|
831
|
+
if (!file && hook) {
|
|
832
|
+
if (agent === "codex") {
|
|
833
|
+
let note = {};
|
|
834
|
+
try {
|
|
835
|
+
note = JSON.parse(a.pos[a.pos.length - 1] ?? "{}");
|
|
836
|
+
} catch {
|
|
837
|
+
}
|
|
838
|
+
file = newestCodex(note["thread-id"] ?? note.thread_id);
|
|
839
|
+
} else {
|
|
840
|
+
const input = await readStdin();
|
|
841
|
+
try {
|
|
842
|
+
file = JSON.parse(input || "{}").transcript_path;
|
|
843
|
+
} catch {
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (!file && agent === "codex") file = newestCodex();
|
|
848
|
+
if (!file) throw new CliError("Pass --transcript <file> (or run from an agent hook).");
|
|
849
|
+
const raw = readRaw(file, agent);
|
|
850
|
+
if (!raw.turns.some((t) => t.who === "user")) {
|
|
851
|
+
if (!hook) out("Nothing to upload yet: the transcript has no messages from you.");
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
const { conn, ws } = await workspace(a.flags);
|
|
855
|
+
const paused = pausedReason(agent, ws);
|
|
856
|
+
if (paused) {
|
|
857
|
+
out(`Not uploaded: ${paused}.`);
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
const m = prepare(raw, ws);
|
|
861
|
+
if (hook && m.payload.sourceId && pushedState()[m.payload.sourceId] === m.payload.turns.length) return;
|
|
862
|
+
const r = await upload(conn, m.payload, m.leaks);
|
|
863
|
+
out(`Uploaded \u201C${m.payload.title}\u201D: ${r.outcome} (${countsLine(m.payload)})`);
|
|
864
|
+
out(` ${conn.server}${r.url}`);
|
|
865
|
+
} catch (e) {
|
|
866
|
+
if (!hook) throw e;
|
|
867
|
+
try {
|
|
868
|
+
mkdirSync3(configDir(), { recursive: true, mode: 448 });
|
|
869
|
+
appendFileSync(join4(configDir(), "push.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${e.message.split("\n")[0]}
|
|
870
|
+
`, { mode: 384 });
|
|
871
|
+
} catch {
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
async function preview(a) {
|
|
876
|
+
const file = a.pos[0] ?? flagStr(a.flags, "transcript");
|
|
877
|
+
if (!file) throw new CliError(`Usage: ${invokedAs()} preview <transcript.jsonl> [--agent claude-code|codex]`);
|
|
878
|
+
const raw = readRaw(file, a.flags.agent ? asAgent(a.flags.agent) : void 0);
|
|
879
|
+
let ws = { hidden_terms: [], never_paths: [] };
|
|
880
|
+
let note = "";
|
|
881
|
+
try {
|
|
882
|
+
ws = (await workspace(a.flags, true)).ws;
|
|
883
|
+
if (!resolve(a.flags).key) note = "Not connected, so your workspace's hidden words weren't loaded. Run connect first for an exact preview.";
|
|
884
|
+
} catch (e) {
|
|
885
|
+
note = `Couldn't load your workspace's hidden words (${e.message.split("\n")[0]}). Showing built-in masking only.`;
|
|
886
|
+
}
|
|
887
|
+
const m = prepare(raw, ws);
|
|
888
|
+
out(JSON.stringify(m.payload, null, 2));
|
|
889
|
+
out("");
|
|
890
|
+
out(`This is exactly what would be stored: ${m.payload.turns.length} turns, ${countsLine(m.payload)}.`);
|
|
891
|
+
out(`The mask table (${Object.keys(m.table).length} entr${Object.keys(m.table).length === 1 ? "y" : "ies"}) stays on this machine and is never uploaded.`);
|
|
892
|
+
if (m.leaks.length) out(`Warning: still looks unmasked: ${m.leaks.join(", ")}. This would not be uploaded.`);
|
|
893
|
+
if (note) out(note);
|
|
894
|
+
}
|
|
895
|
+
async function importCmd(a) {
|
|
896
|
+
const agent = asAgent(a.flags.agent);
|
|
897
|
+
if (agent !== "claude-code" && agent !== "codex") throw new CliError(`import reads Claude Code and Codex transcripts. For ${agent}, use wrap for now.`);
|
|
898
|
+
const days = Math.max(1, Math.min(365, Number(flagStr(a.flags, "days") ?? 14) || 14));
|
|
899
|
+
const dry = !!a.flags["dry-run"];
|
|
900
|
+
const files = transcriptFiles(agent, days);
|
|
901
|
+
if (!files.length) {
|
|
902
|
+
out(`No ${agent} transcripts from the last ${days} days.`);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
const { conn, ws } = await workspace(a.flags, dry);
|
|
906
|
+
const paused = pausedReason(agent, ws);
|
|
907
|
+
if (paused && !dry) throw new CliError(`Not importing: ${paused}.`);
|
|
908
|
+
let sent = 0;
|
|
909
|
+
let skipped = 0;
|
|
910
|
+
const tally = {};
|
|
911
|
+
for (const f of files) {
|
|
912
|
+
let raw;
|
|
913
|
+
try {
|
|
914
|
+
raw = readRaw(f, agent);
|
|
915
|
+
} catch {
|
|
916
|
+
skipped++;
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
if (!raw.turns.some((t) => t.who === "user") || raw.turns.length < 2) {
|
|
920
|
+
skipped++;
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const m = prepare(raw, ws);
|
|
924
|
+
if (dry) {
|
|
925
|
+
out(`would upload ${m.payload.startedAt.slice(0, 10)} ${m.payload.title} (${m.payload.turns.length} turns, ${countsLine(m.payload)})`);
|
|
926
|
+
sent++;
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
if (m.payload.sourceId && pushedState()[m.payload.sourceId] === m.payload.turns.length) {
|
|
930
|
+
skipped++;
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
try {
|
|
934
|
+
const r = await upload(conn, m.payload, m.leaks);
|
|
935
|
+
tally[r.outcome] = (tally[r.outcome] ?? 0) + 1;
|
|
936
|
+
out(`${r.outcome.padEnd(8)} ${m.payload.title}`);
|
|
937
|
+
sent++;
|
|
938
|
+
} catch (e) {
|
|
939
|
+
out(`skipped ${m.payload.title}: ${e.message.split("\n")[0]}`);
|
|
940
|
+
skipped++;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
out("");
|
|
944
|
+
out(dry ? `Dry run: ${sent} session${sent === 1 ? "" : "s"} would be uploaded, ${skipped} skipped. Nothing was sent.` : `Uploaded ${sent} (${Object.entries(tally).map(([k, v]) => `${v} ${k}`).join(", ") || "none"}), skipped ${skipped}.`);
|
|
945
|
+
}
|
|
946
|
+
async function wrap(a) {
|
|
947
|
+
if (!a.rest.length) throw new CliError(`Usage: ${invokedAs()} wrap [--agent sdk] -- <agent command\u2026>`);
|
|
948
|
+
const agent = asAgent(a.flags.agent, "sdk");
|
|
949
|
+
const turns = [];
|
|
950
|
+
const add = (who, line) => {
|
|
951
|
+
const last = turns[turns.length - 1];
|
|
952
|
+
if (last?.who === who) last.text += `
|
|
953
|
+
${line}`;
|
|
954
|
+
else turns.push({ who, text: line, at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
955
|
+
};
|
|
956
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
957
|
+
const child = spawn2(a.rest[0], a.rest.slice(1), { stdio: ["pipe", "pipe", "inherit"] });
|
|
958
|
+
let inBuf = "";
|
|
959
|
+
let outBuf = "";
|
|
960
|
+
const onIn = (b) => {
|
|
961
|
+
child.stdin.write(b);
|
|
962
|
+
inBuf += b.toString();
|
|
963
|
+
let i;
|
|
964
|
+
while ((i = inBuf.indexOf("\n")) >= 0) add("user", inBuf.slice(0, i)), inBuf = inBuf.slice(i + 1);
|
|
965
|
+
};
|
|
966
|
+
process.stdin.on("data", onIn);
|
|
967
|
+
process.stdin.on("end", () => child.stdin.end());
|
|
968
|
+
child.stdout.on("data", (b) => {
|
|
969
|
+
process.stdout.write(b);
|
|
970
|
+
outBuf += b.toString();
|
|
971
|
+
let i;
|
|
972
|
+
while ((i = outBuf.indexOf("\n")) >= 0) add("agent", outBuf.slice(0, i)), outBuf = outBuf.slice(i + 1);
|
|
973
|
+
});
|
|
974
|
+
const code = await new Promise((res) => {
|
|
975
|
+
child.on("close", (c) => res(c ?? 1));
|
|
976
|
+
child.on("error", (e) => {
|
|
977
|
+
process.stderr.write(`Couldn't start ${a.rest[0]}: ${e.message}
|
|
978
|
+
`);
|
|
979
|
+
res(127);
|
|
980
|
+
});
|
|
981
|
+
});
|
|
982
|
+
process.stdin.off("data", onIn);
|
|
983
|
+
process.stdin.pause();
|
|
984
|
+
if (inBuf) add("user", inBuf);
|
|
985
|
+
if (outBuf) add("agent", outBuf);
|
|
986
|
+
turns.push({ who: "tool", tool: "bash", input: a.rest.join(" "), text: `exited with code ${code}`, exit: code });
|
|
987
|
+
const raw = { agent, title: titleFrom(turns) === "Untitled session" ? a.rest.join(" ").slice(0, 80) : titleFrom(turns), startedAt, cwd: process.cwd(), turns };
|
|
988
|
+
try {
|
|
989
|
+
if (a.flags["dry-run"]) {
|
|
990
|
+
const m = prepare(raw, (await workspace(a.flags, true)).ws);
|
|
991
|
+
process.stderr.write(`
|
|
992
|
+
[basal] dry run: would upload \u201C${m.payload.title}\u201D (${m.payload.turns.length} turns, ${countsLine(m.payload)})
|
|
993
|
+
`);
|
|
994
|
+
} else {
|
|
995
|
+
const { conn, ws } = await workspace(a.flags);
|
|
996
|
+
const paused = pausedReason(agent, ws);
|
|
997
|
+
if (paused) process.stderr.write(`
|
|
998
|
+
[basal] not uploaded: ${paused}
|
|
999
|
+
`);
|
|
1000
|
+
else {
|
|
1001
|
+
const m = prepare(raw, ws);
|
|
1002
|
+
const r = await upload(conn, m.payload, m.leaks);
|
|
1003
|
+
process.stderr.write(`
|
|
1004
|
+
[basal] uploaded: ${r.outcome} \xB7 ${conn.server}${r.url}
|
|
1005
|
+
`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
} catch (e) {
|
|
1009
|
+
process.stderr.write(`
|
|
1010
|
+
[basal] not uploaded: ${e.message}
|
|
1011
|
+
`);
|
|
1012
|
+
}
|
|
1013
|
+
process.exitCode = code;
|
|
1014
|
+
}
|
|
1015
|
+
async function run(a) {
|
|
1016
|
+
const task = a.pos[0];
|
|
1017
|
+
const cmd = flagStr(a.flags, "cmd");
|
|
1018
|
+
if (!task || !cmd) throw new CliError(`Usage: ${invokedAs()} run <task> --agent <name> --tries N --cmd "<agent command>"`);
|
|
1019
|
+
const tries = Math.max(1, Math.min(200, Number(flagStr(a.flags, "tries") ?? 1) || 1));
|
|
1020
|
+
const agent = flagStr(a.flags, "agent") ?? "sdk";
|
|
1021
|
+
const conn = need(resolve(a.flags));
|
|
1022
|
+
const r = await runTask({ task, agent, tries, cmd, timeoutSec: Number(flagStr(a.flags, "timeout") ?? 600) || 600, call: (m, p, b) => call(conn.server, conn.key, m, p, b), log: out });
|
|
1023
|
+
out(r.line);
|
|
1024
|
+
}
|
|
1025
|
+
async function gates(a) {
|
|
1026
|
+
const task = a.pos[0];
|
|
1027
|
+
if (!task) throw new CliError(`Usage: ${invokedAs()} gates <task>`);
|
|
1028
|
+
out("Gates for tasks built from your own environment run where the repo is: on this machine, against your checkout.");
|
|
1029
|
+
out("For tasks Basal can run itself, the six gates run on the server when you open the task in the app.");
|
|
1030
|
+
const c = resolve(a.flags);
|
|
1031
|
+
if (!c.server || !c.key) return;
|
|
1032
|
+
try {
|
|
1033
|
+
const t = await call(c.server, c.key, "GET", `/api/tasks/${encodeURIComponent(task)}`);
|
|
1034
|
+
const g = t.gates ?? [];
|
|
1035
|
+
out(`
|
|
1036
|
+
${t.task?.slug ?? task}`);
|
|
1037
|
+
for (const x of g) out(`${x.result ? x.result.pass ? "pass " : "FAIL " : "not run"} ${String(x.label ?? x.key)}${x.result?.detail ? ` \xB7 ${x.result.detail}` : ""}`);
|
|
1038
|
+
} catch (e) {
|
|
1039
|
+
out(`
|
|
1040
|
+
${e.message.split("\n")[0]}`);
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
function help() {
|
|
1044
|
+
out(`basal ${VERSION} \u2014 records coding-agent sessions, masked on this machine first.
|
|
1045
|
+
Usage: ${invokedAs()} <command>
|
|
1046
|
+
|
|
1047
|
+
connect --key <device key> [--server <url>] [--agent claude-code|codex|cursor|gemini-cli|all] [--dry-run]
|
|
1048
|
+
import --agent claude-code|codex [--days 14] [--dry-run]
|
|
1049
|
+
push --agent <agent> --transcript <file.jsonl>
|
|
1050
|
+
preview <file.jsonl> [--agent claude-code|codex] show exactly what would be stored
|
|
1051
|
+
wrap [--agent sdk] -- <agent command\u2026> record any agent's stdin/stdout
|
|
1052
|
+
|
|
1053
|
+
SDK
|
|
1054
|
+
run <task> --agent <name> --tries N --cmd "<agent command>" graded on the server, tests stay hidden
|
|
1055
|
+
gates <task>
|
|
1056
|
+
|
|
1057
|
+
Settings live in ~/.basal/config.json. BASAL_SERVER and BASAL_KEY override it.`);
|
|
1058
|
+
}
|
|
1059
|
+
async function main(argv) {
|
|
1060
|
+
const a = parseArgs(argv);
|
|
1061
|
+
if (a.flags.help && a.cmd !== "wrap") a.cmd = "help";
|
|
1062
|
+
try {
|
|
1063
|
+
switch (a.cmd) {
|
|
1064
|
+
case "connect":
|
|
1065
|
+
await connect(a);
|
|
1066
|
+
break;
|
|
1067
|
+
case "import":
|
|
1068
|
+
await importCmd(a);
|
|
1069
|
+
break;
|
|
1070
|
+
case "push":
|
|
1071
|
+
await push(a);
|
|
1072
|
+
break;
|
|
1073
|
+
case "preview":
|
|
1074
|
+
await preview(a);
|
|
1075
|
+
break;
|
|
1076
|
+
case "wrap":
|
|
1077
|
+
await wrap(a);
|
|
1078
|
+
break;
|
|
1079
|
+
case "run":
|
|
1080
|
+
await run(a);
|
|
1081
|
+
break;
|
|
1082
|
+
case "gates":
|
|
1083
|
+
await gates(a);
|
|
1084
|
+
break;
|
|
1085
|
+
case "version":
|
|
1086
|
+
case "--version":
|
|
1087
|
+
out(VERSION);
|
|
1088
|
+
break;
|
|
1089
|
+
case "help":
|
|
1090
|
+
help();
|
|
1091
|
+
break;
|
|
1092
|
+
default:
|
|
1093
|
+
process.stderr.write(`Unknown command: ${a.cmd}
|
|
1094
|
+
|
|
1095
|
+
`);
|
|
1096
|
+
help();
|
|
1097
|
+
return 2;
|
|
1098
|
+
}
|
|
1099
|
+
return typeof process.exitCode === "number" ? process.exitCode : 0;
|
|
1100
|
+
} catch (e) {
|
|
1101
|
+
process.stderr.write(`${e instanceof CliError ? e.message : `Unexpected error: ${e.message}`}
|
|
1102
|
+
`);
|
|
1103
|
+
return 1;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// src/cli.ts
|
|
1108
|
+
main(process.argv.slice(2)).then((code) => {
|
|
1109
|
+
process.exitCode = code;
|
|
1110
|
+
process.stdin.unref?.();
|
|
1111
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@motiontic/basal",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Basal CLI: record Claude Code, Codex and other coding-agent sessions (masked on your machine) and turn their mistakes into checked RL tasks.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"basal": "dist/basal.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist/basal.mjs",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://basal.motiontic.com",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Motiontic/tracebox.git",
|
|
20
|
+
"directory": "packages/cli"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"claude-code",
|
|
24
|
+
"codex",
|
|
25
|
+
"coding-agents",
|
|
26
|
+
"reinforcement-learning",
|
|
27
|
+
"evals",
|
|
28
|
+
"basal"
|
|
29
|
+
],
|
|
30
|
+
"license": "UNLICENSED",
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "node build.mjs",
|
|
36
|
+
"prepublishOnly": "node build.mjs && npm test",
|
|
37
|
+
"test": "node --test --experimental-strip-types --no-warnings test/*.test.ts"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"esbuild": "0.25.2"
|
|
41
|
+
}
|
|
42
|
+
}
|