@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
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/CHANGELOG.md +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +74 -0
- package/dist/errors.js +69 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +24 -0
- package/dist/turn-end.js +15 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +189 -0
- package/dist/webhooks.js +503 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/import.js
ADDED
|
@@ -0,0 +1,1222 @@
|
|
|
1
|
+
// `agentrun-serve import`: the Claude Code, Codex and pi sessions under a person's own home, into this server's agent
|
|
2
|
+
// store, once, when asked. Each project directory is one agent; each harness seen in it one revision of that agent, its
|
|
3
|
+
// instructions the project's CLAUDE.md or AGENTS.md and its skills the project's skill folders; each session one run,
|
|
4
|
+
// ended as it ended, its transcript the run's timeline. An imported run is history: it takes no message, stop or cancel.
|
|
5
|
+
// Nothing leaves the machine, every string written has the environment's key values cut out, and every file written is
|
|
6
|
+
// the owner's only. Read again, it imports only the sessions it has not.
|
|
7
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
8
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
9
|
+
import { chmod, lstat, mkdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
10
|
+
import { homedir, tmpdir } from "node:os";
|
|
11
|
+
import { basename, dirname, join, sep } from "node:path";
|
|
12
|
+
import { parseArgs } from "node:util";
|
|
13
|
+
import { BACKGROUND_CONTEXT as ctx } from "@earendil-works/chord/context";
|
|
14
|
+
import { AssistantEntry, createRegistry, Harness, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
|
|
15
|
+
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
|
|
16
|
+
import { openStore, openStoreReader, STORE_FILE } from "@parcha/pi-durable-agent";
|
|
17
|
+
import { REQUEST_COST, runMetricsOf } from "@parcha/pi-durable-agent/timeline";
|
|
18
|
+
import { DOOR_TOKEN_FILE, defaultData, readJson, RUN_META, TOKEN_FILE } from "./files.js";
|
|
19
|
+
import { childFiles, HARNESS_OF, mostEffortOf, readSession, SOURCES, sessionFiles } from "./import-sources.js";
|
|
20
|
+
import { foundIn, hoursOf, summaryLines } from "./import-summary.js";
|
|
21
|
+
import { catalogPrices } from "./model.js";
|
|
22
|
+
import { SESSION_SECRET_FILE } from "./owner.js";
|
|
23
|
+
import { logLine } from "./print.js";
|
|
24
|
+
import { DEFAULT_PORT } from "./server.js";
|
|
25
|
+
import { REDACTED, secretCut, secretsIn } from "./secret-cut.js";
|
|
26
|
+
import { SECRET_NAMES, withSecrets } from "./secrets.js";
|
|
27
|
+
import { SEAL_KEY_ENV, ToolKeys } from "./tool-keys.js";
|
|
28
|
+
import { WEBHOOK_FILE, webhookSecretIn } from "./webhooks.js";
|
|
29
|
+
import { triggerSecretsIn } from "./trigger-secrets.js";
|
|
30
|
+
import { readWorkBytes, WorkRefused, walkWork } from "./workspace.js";
|
|
31
|
+
/** In the data directory while an import the owner asked for at setup has not ended: the server's next start goes on with it. */
|
|
32
|
+
export const IMPORT_ASKED = ".import-at-setup";
|
|
33
|
+
/** A session file written to this recently may still be running: it is left for a later import. */
|
|
34
|
+
export const LIVE_MS = 10 * 60_000;
|
|
35
|
+
/** The most of one session file read. */
|
|
36
|
+
export const MAX_SESSION_BYTES = 256 * 1024 * 1024;
|
|
37
|
+
/** The most of one instructions or skill file read, and of one agent's skill files together. */
|
|
38
|
+
export const MAX_FILE_BYTES = 256 * 1024;
|
|
39
|
+
export const MAX_SKILL_BYTES = 1024 * 1024;
|
|
40
|
+
/** The project's skill folders, each `<dir>/<name>/` with its SKILL.md, by where each harness keeps them. */
|
|
41
|
+
export const SKILL_DIRS = [".agents/skills", ".claude/skills", ".codex/skills", ".pi/skills"];
|
|
42
|
+
const INSTRUCTIONS = {
|
|
43
|
+
"claude-agent": ["CLAUDE.md", "AGENTS.md"],
|
|
44
|
+
codex: ["AGENTS.md", "CLAUDE.md"],
|
|
45
|
+
pi: ["AGENTS.md", "CLAUDE.md"],
|
|
46
|
+
};
|
|
47
|
+
const hash = (text) => createHash("sha256").update(text).digest("hex");
|
|
48
|
+
/** A session's id as an import keeps it: as it is, unless it holds one of the keys the import cuts, the environment's or
|
|
49
|
+
* one saved on the server (a session named after its file can), then `redacted-` and a hash of it, the same each time
|
|
50
|
+
* and different for each id, so two such sessions stay two runs and a later import finds each one's. The plan and the
|
|
51
|
+
* import keep it from the same keys, or a later import would not find the run an earlier one made. */
|
|
52
|
+
const redactedId = (id) => `redacted-${hash(id).slice(0, 16)}`;
|
|
53
|
+
/** A file's size and time, as an import read it: the same after means the same content was read. */
|
|
54
|
+
const stampOf = (stats) => `${stats.size}:${stats.mtimeMs}`;
|
|
55
|
+
const keptId = (envs, own = []) => {
|
|
56
|
+
const { text, add } = secretCut(envs, SECRET_NAMES);
|
|
57
|
+
add(own);
|
|
58
|
+
// A key secretlint finds in the id itself (a session named after its file); a count, whose ids are kept by no run, asks
|
|
59
|
+
// no scan.
|
|
60
|
+
return async (id, scan = true) => (text(id) === id && !(scan && (await secretsIn(id)).length) ? id : redactedId(id));
|
|
61
|
+
};
|
|
62
|
+
/** The keys secretlint finds in what a run's import writes: its sessions as read (each file once, its path, every
|
|
63
|
+
* record's strings), in one pass, right before they are cut, so a key a session still being written added after the
|
|
64
|
+
* plan is found as well. */
|
|
65
|
+
async function keysInSessions(sessions) {
|
|
66
|
+
if (!sessions.length)
|
|
67
|
+
return [];
|
|
68
|
+
const strings = [];
|
|
69
|
+
const seen = new Set();
|
|
70
|
+
const collect = (value) => {
|
|
71
|
+
if (typeof value === "string")
|
|
72
|
+
strings.push(value);
|
|
73
|
+
else if (value !== null && typeof value === "object" && !seen.has(value)) {
|
|
74
|
+
seen.add(value);
|
|
75
|
+
if (Array.isArray(value))
|
|
76
|
+
value.forEach(collect);
|
|
77
|
+
else if (value instanceof Map)
|
|
78
|
+
for (const [name, inner] of value)
|
|
79
|
+
(collect(name), collect(inner));
|
|
80
|
+
else
|
|
81
|
+
for (const [name, inner] of Object.entries(value))
|
|
82
|
+
(strings.push(name), collect(inner));
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
sessions.forEach(collect);
|
|
86
|
+
return secretsIn(strings.join("\n"));
|
|
87
|
+
}
|
|
88
|
+
/** Every key an import would cut, found before anything of it is written, across every project: each project's own text,
|
|
89
|
+
* and each run the import would write (its sessions, then its subagents, which the reader holds to MAX_SESSION_BYTES),
|
|
90
|
+
* read through secretlint once, findings only, into `add`. Each file's size and time as read, and each project's text
|
|
91
|
+
* as read, are kept: a write reads a run (or a project's text) through secretlint again only if it changed since. */
|
|
92
|
+
async function findKeys(plan, add, cut, held, signal) {
|
|
93
|
+
const stamps = new Map();
|
|
94
|
+
const texts = new Map();
|
|
95
|
+
for (const project of plan.projects) {
|
|
96
|
+
if (signal?.aborted)
|
|
97
|
+
break;
|
|
98
|
+
const own = projectText(project.cwd, await projectFiles(project.cwd, []));
|
|
99
|
+
texts.set(project.agentId, hash(own));
|
|
100
|
+
add(await secretsIn(own));
|
|
101
|
+
}
|
|
102
|
+
for (const project of plan.projects) {
|
|
103
|
+
for (const files of byRun(project.sessions)) {
|
|
104
|
+
if (signal?.aborted)
|
|
105
|
+
break;
|
|
106
|
+
const listed = files[0];
|
|
107
|
+
if (held(listed))
|
|
108
|
+
continue;
|
|
109
|
+
// Its own count of records seen: the import's, shared across its files, is the write's to keep.
|
|
110
|
+
const seen = new Set();
|
|
111
|
+
const parts = [];
|
|
112
|
+
for (const { file } of files) {
|
|
113
|
+
const stats = await stat(file).catch(() => null);
|
|
114
|
+
const part = stats ? await readSession(file, listed.source, { seen }).catch(() => undefined) : undefined;
|
|
115
|
+
if (!part || !stats)
|
|
116
|
+
continue;
|
|
117
|
+
stamps.set(file, stampOf(stats));
|
|
118
|
+
parts.push(part);
|
|
119
|
+
}
|
|
120
|
+
if (!parts.length)
|
|
121
|
+
continue;
|
|
122
|
+
add(await keysInSessions(parts));
|
|
123
|
+
const session = merged(parts);
|
|
124
|
+
const subagents = await readChildren(plan, { ...session, id: cut(session.id) === session.id ? session.id : redactedId(session.id) }, parts, seen);
|
|
125
|
+
for (const child of subagents) {
|
|
126
|
+
const stats = await stat(child.file).catch(() => null);
|
|
127
|
+
if (stats)
|
|
128
|
+
stamps.set(child.file, stampOf(stats));
|
|
129
|
+
}
|
|
130
|
+
add(await keysInSessions(subagents));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { stamps, texts };
|
|
134
|
+
}
|
|
135
|
+
/** A project's own text for secretlint: its path, its instructions, and its skills' paths and text. */
|
|
136
|
+
const projectText = (cwd, files) => [cwd, ...Object.values(files.instructions), ...Object.entries(files.skills).flat()].join("\n");
|
|
137
|
+
export const agentIdOf = (cwd) => `imp-${hash(`dir:${cwd}`).slice(0, 32)}`;
|
|
138
|
+
/** The sessions the store holds already, as `source:session`, to their run's id. */
|
|
139
|
+
const importedIn = (store) => new Map(store.listRuns().flatMap((run) => (run.importedFrom ? [[`${run.importedFrom.source}:${run.importedFrom.session}`, run.id]] : [])));
|
|
140
|
+
const sameFile = (seen, stats) => seen !== undefined && seen.size === stats.size && seen.mtime_ms === stats.mtimeMs;
|
|
141
|
+
/** The session files the store's imports read whole, by their path's sha256, with their run: each from a run whose
|
|
142
|
+
* transcript is there. */
|
|
143
|
+
async function filesIn(store) {
|
|
144
|
+
const out = new Map();
|
|
145
|
+
for (const run of store.listRuns()) {
|
|
146
|
+
if (!run.importedFrom || !existsSync(store.runStorePath(run.id)))
|
|
147
|
+
continue;
|
|
148
|
+
const meta = (await readJson(join(store.dir, "runs", run.id, RUN_META)));
|
|
149
|
+
const seen = meta?.source_file;
|
|
150
|
+
if (seen && typeof seen.path_sha256 === "string" && typeof seen.size === "number" && typeof seen.mtime_ms === "number")
|
|
151
|
+
out.set(seen.path_sha256, { ...seen, run: run.id });
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
const unread = (file, error) => ({ what: file, why: `not read (${error.code ?? error.message})`, kind: "unread" });
|
|
156
|
+
const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
157
|
+
/** What an import would take: the sessions under `home`, by project, with what it leaves out and why. Keeps no turns
|
|
158
|
+
* (with `measure`, only until each session is measured), and reads no file `store`'s imports already read whole and
|
|
159
|
+
* that has not changed since. */
|
|
160
|
+
export async function planImport({ home, sources = SOURCES, all = false, deleted = false, now = Date.now(), temp: tempDir = tmpdir(), measure = false, env, stored, own = [], signal, keys: scan = true, onKeys }, store) {
|
|
161
|
+
// A session's id that holds a key (one named after its file can) is kept as a hash of it: every lookup of an earlier
|
|
162
|
+
// import's run then goes by the id as kept.
|
|
163
|
+
const idOf = keptId([env, stored ?? {}], own);
|
|
164
|
+
const skipped = [];
|
|
165
|
+
const seen = store ? await filesIn(store) : new Map();
|
|
166
|
+
let already = 0;
|
|
167
|
+
const held = [];
|
|
168
|
+
const found = [];
|
|
169
|
+
const children = new Map();
|
|
170
|
+
const child = (owner, file) => void children.set(owner, [...(children.get(owner) ?? []), file]);
|
|
171
|
+
const untied = [];
|
|
172
|
+
const projects = new Map();
|
|
173
|
+
// Each listed session's place in the import's order (inOrder).
|
|
174
|
+
const rank = new Map();
|
|
175
|
+
const temps = [...new Set([tempDir, await realpath(tempDir).catch(() => tempDir)])];
|
|
176
|
+
for (const source of sources) {
|
|
177
|
+
for (const { file, stats } of await inOrder(await sessionFiles(home, source), source)) {
|
|
178
|
+
if (signal?.aborted)
|
|
179
|
+
break;
|
|
180
|
+
const known = seen.get(hash(file));
|
|
181
|
+
if (sameFile(known, stats)) {
|
|
182
|
+
already += 1;
|
|
183
|
+
held.push(known.run);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (now - stats.mtimeMs < LIVE_MS) {
|
|
187
|
+
skipped.push({
|
|
188
|
+
what: file,
|
|
189
|
+
why: "written in the last 10 minutes: it may still be running",
|
|
190
|
+
kind: "live",
|
|
191
|
+
});
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (stats.size > MAX_SESSION_BYTES) {
|
|
195
|
+
skipped.push({ what: file, why: `over ${MAX_SESSION_BYTES} bytes`, kind: "large" });
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
// One file this user cannot read, or one gone since its stat, is named and passed over: the rest still import.
|
|
199
|
+
const session = await readSession(file, source, { turns: false }).catch((error) => void skipped.push(unread(file, error)));
|
|
200
|
+
if (!session)
|
|
201
|
+
continue;
|
|
202
|
+
session.id = await idOf(session.id, scan);
|
|
203
|
+
if (session.parent)
|
|
204
|
+
session.parent = await idOf(session.parent, scan);
|
|
205
|
+
// A subagent's session is no run of its own: its usage is its parent's, when its file names the parent (a Codex
|
|
206
|
+
// thread's, whichever of its files); else it counts in the totals alone, where its project would.
|
|
207
|
+
if (session.child && session.parent) {
|
|
208
|
+
child(`${source}:${session.parent}`, file);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (!session.cwd) {
|
|
212
|
+
skipped.push({ what: file, why: "no project directory in it", kind: "no-project" });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (!all && session.users === 0 && !session.child) {
|
|
216
|
+
skipped.push({ what: file, why: "no message of the person's", kind: "no-words", session: `${source}:${session.id}` });
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const cwd = session.cwd;
|
|
220
|
+
if (!all) {
|
|
221
|
+
// A temp folder first, gone or not: only --all brings it in, as the left-out line says.
|
|
222
|
+
if (temps.some((temp) => cwd === temp || cwd.startsWith(temp + sep))) {
|
|
223
|
+
skipped.push({
|
|
224
|
+
what: file,
|
|
225
|
+
why: `its project ${cwd} is a temp directory`,
|
|
226
|
+
kind: "temp",
|
|
227
|
+
session: `${source}:${session.id}`,
|
|
228
|
+
});
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const there = await lstat(cwd).catch(() => null);
|
|
232
|
+
if (!there?.isDirectory() && !deleted) {
|
|
233
|
+
skipped.push({ what: file, why: `its project ${cwd} is gone`, kind: "gone", session: `${source}:${session.id}` });
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (session.child) {
|
|
238
|
+
untied.push({ file, source });
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
let project = projects.get(cwd);
|
|
242
|
+
if (!project)
|
|
243
|
+
projects.set(cwd, (project = {
|
|
244
|
+
cwd,
|
|
245
|
+
agentId: agentIdOf(cwd),
|
|
246
|
+
name: basename(cwd) || cwd,
|
|
247
|
+
sessions: [],
|
|
248
|
+
}));
|
|
249
|
+
rank.set(session, rank.size);
|
|
250
|
+
project.sessions.push(session);
|
|
251
|
+
}
|
|
252
|
+
if (source === "claude-code")
|
|
253
|
+
for (const { file, of } of await childFiles(home))
|
|
254
|
+
child(of, file);
|
|
255
|
+
}
|
|
256
|
+
ownRuns(projects, rank);
|
|
257
|
+
const plan = { projects: [...projects.values()].sort((a, b) => a.cwd.localeCompare(b.cwd)), skipped, already, held, children, untied };
|
|
258
|
+
if (!measure)
|
|
259
|
+
return plan;
|
|
260
|
+
const counting = secretCut(env, SECRET_NAMES);
|
|
261
|
+
// Every key the import would cut, found first, as the import finds it before it writes anything: then the counts.
|
|
262
|
+
const heldBy = store ? importedIn(store) : undefined;
|
|
263
|
+
const foundKeys = (keys) => (counting.add(keys), onKeys?.(keys));
|
|
264
|
+
// This server's own secrets first, as the import takes them.
|
|
265
|
+
foundKeys(own);
|
|
266
|
+
await findKeys(plan, foundKeys, counting.text, (listed) => heldBy?.get(`${listed.source}:${listed.id}`) !== undefined, signal);
|
|
267
|
+
// Measured in the import's own order, a record or response counted once across files, each session with its
|
|
268
|
+
// subagents; a session the store holds already from its run, as the import counts it, not from its file now.
|
|
269
|
+
for (const project of plan.projects) {
|
|
270
|
+
const seen = await seenIn(store, project.agentId);
|
|
271
|
+
for (const files of byRun(project.sessions)) {
|
|
272
|
+
const run = heldBy?.get(`${files[0].source}:${files[0].id}`);
|
|
273
|
+
if (run !== undefined) {
|
|
274
|
+
held.push(run);
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
// Each of its files read; those holding only copies add no records to it, but their subagents' folders are its
|
|
278
|
+
// too, read through the same count (readChildren).
|
|
279
|
+
const read = [];
|
|
280
|
+
for (const listed of files) {
|
|
281
|
+
const part = await readSession(listed.file, listed.source, { seen: seen(listed.source) }).catch(() => undefined);
|
|
282
|
+
if (part)
|
|
283
|
+
read.push(part);
|
|
284
|
+
}
|
|
285
|
+
const parts = read.filter((part) => !ownless(part));
|
|
286
|
+
if (!parts.length)
|
|
287
|
+
continue;
|
|
288
|
+
const session = merged(parts);
|
|
289
|
+
// What the import's cut would take out of it (its turns, its first message): the dry run's count.
|
|
290
|
+
counting.json(session.turns);
|
|
291
|
+
if (session.firstPrompt)
|
|
292
|
+
counting.text(session.firstPrompt);
|
|
293
|
+
const subagents = await readChildren(plan, session, read, seen(session.source));
|
|
294
|
+
found.push({ source: session.source, agent: project.agentId, ...measured(session, subagents) });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// Each project's files read as the import reads them, held agent or new: each file it leaves out (a link, one over its
|
|
298
|
+
// cap) is among what the dry run says it leaves out. A new agent's own text (its name, its path, its instructions and
|
|
299
|
+
// skills) is the import's to cut too: counted here, after every key is known, as the import cuts it.
|
|
300
|
+
for (const project of plan.projects) {
|
|
301
|
+
const files = await projectFiles(project.cwd, skipped);
|
|
302
|
+
if (store?.readAgent(project.agentId))
|
|
303
|
+
continue;
|
|
304
|
+
counting.text(project.name);
|
|
305
|
+
counting.text(project.cwd);
|
|
306
|
+
for (const text of Object.values(files.instructions))
|
|
307
|
+
counting.text(text);
|
|
308
|
+
for (const [path, text] of Object.entries(files.skills))
|
|
309
|
+
(counting.text(path), counting.text(text));
|
|
310
|
+
}
|
|
311
|
+
return { ...plan, found, secretsFound: counting.text.removed };
|
|
312
|
+
}
|
|
313
|
+
/** The subagents tied to no session: each one's tokens and tool calls, for a summary's totals, each response once. */
|
|
314
|
+
export async function untiedFound(plan) {
|
|
315
|
+
const seen = new Map();
|
|
316
|
+
const counted = (source) => seen.get(source) ?? seen.set(source, new Set()).get(source);
|
|
317
|
+
// A thread resumed in a second file of the same id is one: its own subagents, which name it, count once with it.
|
|
318
|
+
const threads = new Map();
|
|
319
|
+
for (const { file, source } of plan.untied) {
|
|
320
|
+
const stats = await stat(file).catch(() => null);
|
|
321
|
+
if (!stats || stats.size > MAX_SESSION_BYTES)
|
|
322
|
+
continue;
|
|
323
|
+
const session = await readSession(file, source, { seen: counted(source) }).catch(() => undefined);
|
|
324
|
+
if (session)
|
|
325
|
+
threads.set(`${source}:${session.id}`, [...(threads.get(`${source}:${session.id}`) ?? []), session]);
|
|
326
|
+
}
|
|
327
|
+
const found = [];
|
|
328
|
+
for (const parts of threads.values()) {
|
|
329
|
+
const session = merged(parts);
|
|
330
|
+
found.push({ source: session.source, agent: "", untied: true, metrics: metricsOf(session, await readChildren(plan, session, parts, counted(session.source))) });
|
|
331
|
+
}
|
|
332
|
+
return found;
|
|
333
|
+
}
|
|
334
|
+
/** Each session's files in the project of its first file by start (the earliest-named of a tie), whichever project the
|
|
335
|
+
* others' records name: one run, in one agent, on every import. Each project's files in the import's order (`rank`); a
|
|
336
|
+
* project left with none is none. */
|
|
337
|
+
function ownRuns(projects, rank) {
|
|
338
|
+
const files = new Map();
|
|
339
|
+
for (const project of projects.values())
|
|
340
|
+
for (const session of project.sessions)
|
|
341
|
+
files.set(`${session.source}:${session.id}`, [...(files.get(`${session.source}:${session.id}`) ?? []), { session, project }]);
|
|
342
|
+
const first = (a, b) => (a.startedAt ?? "").localeCompare(b.startedAt ?? "") || a.file.localeCompare(b.file);
|
|
343
|
+
for (const run of files.values()) {
|
|
344
|
+
if (run.length < 2)
|
|
345
|
+
continue;
|
|
346
|
+
const owner = run.reduce((one, other) => (first(other.session, one.session) < 0 ? other : one)).project;
|
|
347
|
+
for (const { session, project } of run)
|
|
348
|
+
if (project !== owner)
|
|
349
|
+
(project.sessions.splice(project.sessions.indexOf(session), 1), owner.sessions.push(session));
|
|
350
|
+
}
|
|
351
|
+
for (const [cwd, project] of projects) {
|
|
352
|
+
if (project.sessions.length)
|
|
353
|
+
project.sessions.sort((a, b) => rank.get(a) - rank.get(b));
|
|
354
|
+
else
|
|
355
|
+
projects.delete(cwd);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/** A project's session files by the session they write, each session's in order, the sessions in their first files'
|
|
359
|
+
* order: a Codex thread resumed later writes a new file of the same id, and a Claude Code session resumed in another
|
|
360
|
+
* directory is copied into that project's folder under its id, then carried on. The store keeps one run of a session. */
|
|
361
|
+
function byRun(sessions) {
|
|
362
|
+
const runs = new Map();
|
|
363
|
+
for (const session of sessions)
|
|
364
|
+
runs.set(`${session.source}:${session.id}`, [...(runs.get(`${session.source}:${session.id}`) ?? []), session]);
|
|
365
|
+
return [...runs.values()];
|
|
366
|
+
}
|
|
367
|
+
/** The sessions `files` write, as the import takes them: one per source and session id, however many files write it
|
|
368
|
+
* (`byRun`), with its cost known when each of its files' is (as `merged` prices it). What a dry run counts. */
|
|
369
|
+
export const sessionsOf = (files) => byRun(files).map((parts) => ({ source: parts[0].source, key: `${parts[0].source}:${parts[0].id}`, priced: parts.every((s) => s.costUsd !== undefined) }));
|
|
370
|
+
/** A session's files, read in the import's order with its `seen` (which file keeps a copied record), as the one run the
|
|
371
|
+
* store keeps of it: their turns in the order they ran (each file's by its start; each answer with its own file's model
|
|
372
|
+
* when it names none), its state and model the file's that ended last. Its cost, when each file's is known: Claude Code
|
|
373
|
+
* writes the session's running total (a moved session's copy goes on from the original's), so the highest total
|
|
374
|
+
* written; another source's file prices its own requests, so their sum. */
|
|
375
|
+
function merged(parts) {
|
|
376
|
+
if (parts.length === 1)
|
|
377
|
+
return parts[0];
|
|
378
|
+
const ordered = [...parts].sort((a, b) => (a.startedAt ?? "").localeCompare(b.startedAt ?? "") || a.file.localeCompare(b.file));
|
|
379
|
+
const [first, last] = [ordered[0], ordered.reduce((one, other) => ((other.endedAt ?? "") >= (one.endedAt ?? "") ? other : one))];
|
|
380
|
+
const turns = ordered.flatMap((part) => part.turns.map((turn) => (turn.role === "assistant" && !turn.model && part.model ? { ...turn, model: part.model } : turn)));
|
|
381
|
+
const sum = (key) => parts.reduce((n, part) => n + part[key], 0);
|
|
382
|
+
const effort = mostEffortOf(turns);
|
|
383
|
+
const starts = parts.flatMap((part) => (part.startedAt ? [part.startedAt] : [])).sort();
|
|
384
|
+
const priced = parts.flatMap((part) => (part.costUsd !== undefined ? [part.costUsd] : []));
|
|
385
|
+
// Known only when each file's is: a file whose spending is unknown (an unpriced model, no cost written) leaves the
|
|
386
|
+
// session's unknown, never a part of it stored as the whole.
|
|
387
|
+
const costUsd = priced.length < parts.length ? undefined : first.source === "claude-code" ? Math.max(...priced) : priced.reduce((n, cost) => n + cost, 0);
|
|
388
|
+
const { model: _model, startedAt: _start, endedAt: _end, costUsd: _cost, firstPrompt: _prompt, effort: _effort, ...rest } = first;
|
|
389
|
+
const model = last.model ?? first.model;
|
|
390
|
+
const firstPrompt = ordered.find((part) => part.firstPrompt !== undefined)?.firstPrompt;
|
|
391
|
+
return {
|
|
392
|
+
...rest,
|
|
393
|
+
...(model ? { model } : {}),
|
|
394
|
+
...(starts[0] ? { startedAt: starts[0] } : {}),
|
|
395
|
+
...(last.endedAt ? { endedAt: last.endedAt } : {}),
|
|
396
|
+
state: last.state,
|
|
397
|
+
...(costUsd !== undefined ? { costUsd } : {}),
|
|
398
|
+
...(firstPrompt !== undefined ? { firstPrompt } : {}),
|
|
399
|
+
turns,
|
|
400
|
+
users: sum("users"),
|
|
401
|
+
activeMs: sum("activeMs"),
|
|
402
|
+
copies: sum("copies"),
|
|
403
|
+
...(effort ? { effort } : {}),
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
/** The files of `source`, each with its stats (one gone since it was listed is passed over), in the import's order:
|
|
407
|
+
* Claude Code's by project folder, oldest written first (the first file holding a copied record keeps it); Codex's and
|
|
408
|
+
* pi's as their dated names sort. */
|
|
409
|
+
async function inOrder(files, source) {
|
|
410
|
+
const out = [];
|
|
411
|
+
for (const file of files) {
|
|
412
|
+
const stats = await stat(file).catch(() => null);
|
|
413
|
+
if (stats)
|
|
414
|
+
out.push({ file, stats });
|
|
415
|
+
}
|
|
416
|
+
if (source === "claude-code")
|
|
417
|
+
out.sort((a, b) => dirname(a.file).localeCompare(dirname(b.file)) || a.stats.mtimeMs - b.stats.mtimeMs || a.file.localeCompare(b.file));
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
/** A session that holds only records an earlier file of the import holds (a resumed session's copy of them). */
|
|
421
|
+
const ownless = (session) => session.copies > 0 && !session.turns.some((turn) => turn.role !== "note");
|
|
422
|
+
/** The records and responses an import has counted, by source, for one project: first those its runs in `store` hold
|
|
423
|
+
* already (each answer's response id and each entry's record ids, as its transcript keeps them), then each file's as it
|
|
424
|
+
* is read. */
|
|
425
|
+
async function seenIn(store, agentId) {
|
|
426
|
+
const bySource = new Map();
|
|
427
|
+
const seen = (source) => bySource.get(source) ?? bySource.set(source, new Set()).get(source);
|
|
428
|
+
if (!store?.readAgent(agentId))
|
|
429
|
+
return seen;
|
|
430
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
431
|
+
for (const run of store.listRuns({ agent: agentId })) {
|
|
432
|
+
if (run.importedFrom?.source !== "claude-code" || !existsSync(store.runStorePath(run.id)))
|
|
433
|
+
continue;
|
|
434
|
+
const db = new DatabaseSync(store.runStorePath(run.id), { readOnly: true });
|
|
435
|
+
try {
|
|
436
|
+
const rows = db.prepare("SELECT json_extract(record, '$.model[0].responseId') AS id, json_extract(record, '$.data.record_uuids') AS uuids FROM entries").all();
|
|
437
|
+
for (const { id, uuids } of rows) {
|
|
438
|
+
if (typeof id === "string" && id)
|
|
439
|
+
seen("claude-code").add(`m:${id}`);
|
|
440
|
+
if (typeof uuids === "string")
|
|
441
|
+
for (const uuid of JSON.parse(uuids))
|
|
442
|
+
if (typeof uuid === "string")
|
|
443
|
+
seen("claude-code").add(`u:${uuid}`);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
finally {
|
|
447
|
+
db.close();
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return seen;
|
|
451
|
+
}
|
|
452
|
+
/** A run's subagents, theirs, and so on down, each file once, read with the import's `seen`: those beside each of its
|
|
453
|
+
* files (Claude Code's), and those naming its thread (Codex's, whichever of its files they ran under). Each within the cap
|
|
454
|
+
* and readable; another is passed over. */
|
|
455
|
+
async function readChildren(plan, session, parts, seen) {
|
|
456
|
+
const out = [];
|
|
457
|
+
const visited = new Set();
|
|
458
|
+
const under = async (owner) => {
|
|
459
|
+
for (const file of plan.children.get(owner) ?? []) {
|
|
460
|
+
if (visited.has(file))
|
|
461
|
+
continue;
|
|
462
|
+
visited.add(file);
|
|
463
|
+
const stats = await stat(file).catch(() => null);
|
|
464
|
+
if (!stats || stats.size > MAX_SESSION_BYTES)
|
|
465
|
+
continue;
|
|
466
|
+
const child = await readSession(file, session.source, { seen }).catch(() => undefined);
|
|
467
|
+
if (!child)
|
|
468
|
+
continue;
|
|
469
|
+
out.push(child);
|
|
470
|
+
// A subagent's own subagents (Codex names each one's parent thread) are the run's too.
|
|
471
|
+
await under(`${session.source}:${child.id}`);
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
for (const part of parts)
|
|
475
|
+
await under(part.file);
|
|
476
|
+
await under(`${session.source}:${session.id}`);
|
|
477
|
+
return out;
|
|
478
|
+
}
|
|
479
|
+
/** A subagent's requests in its session's transcript: each one a request with no answer of its own there, its usage and
|
|
480
|
+
* its cost (none known: null), as a request's cost is written with no answer (REQUEST_COST). The timeline shows none of
|
|
481
|
+
* them, and its usage row, the run's cost and runMetricsOf all count each one. */
|
|
482
|
+
const subagentMarks = (children) => children.flatMap((child) => child.turns.flatMap((turn) => {
|
|
483
|
+
if (turn.role !== "assistant")
|
|
484
|
+
return [];
|
|
485
|
+
const { input, output, cacheRead, cacheWrite } = turn.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
486
|
+
// A failed request's counts are its own, zeros included, as its answer's are (entryOf).
|
|
487
|
+
return [{ kind: REQUEST_COST, data: { request: "subagent", usd: turn.costUsd ?? null, usage: { input, output, cacheRead, cacheWrite }, ...(turn.error !== undefined ? { failed: true } : {}) } }];
|
|
488
|
+
}));
|
|
489
|
+
/** A session's entries as its transcript holds them, its subagents' requests with them (subagentMarks). */
|
|
490
|
+
const runEntries = (session, children) => [...entriesOf(session), ...subagentMarks(children)];
|
|
491
|
+
/** What a session used, its subagents' requests with it: runMetricsOf of its entries, and its subagents' models and tool
|
|
492
|
+
* calls, which their marks do not carry. */
|
|
493
|
+
function metricsOf(session, children) {
|
|
494
|
+
return withChildren(runMetricsOf(runEntries(session, children)), children.map((child) => runMetricsOf(entriesOf(child))));
|
|
495
|
+
}
|
|
496
|
+
/** A run's metrics with its subagents' models and tool calls in them (their requests and tokens are in its entries). The
|
|
497
|
+
* run's model stays its own. */
|
|
498
|
+
function withChildren(own, children) {
|
|
499
|
+
const sum = { ...own, models: { ...own.models }, tools: Object.fromEntries(Object.entries(own.tools).map(([name, tool]) => [name, { ...tool }])) };
|
|
500
|
+
for (const child of children) {
|
|
501
|
+
for (const [name, n] of Object.entries(child.models))
|
|
502
|
+
sum.models[name] = (sum.models[name] ?? 0) + n;
|
|
503
|
+
for (const [name, tool] of Object.entries(child.tools)) {
|
|
504
|
+
const into = (sum.tools[name] ??= { calls: 0, errors: 0 });
|
|
505
|
+
into.calls += tool.calls;
|
|
506
|
+
into.errors += tool.errors;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (sum.model === undefined) {
|
|
510
|
+
for (const [name, n] of Object.entries(sum.models))
|
|
511
|
+
if (sum.model === undefined || n > sum.models[sum.model])
|
|
512
|
+
sum.model = name;
|
|
513
|
+
}
|
|
514
|
+
return sum;
|
|
515
|
+
}
|
|
516
|
+
/** A project's instructions file and skill folders, read through no link and within their caps. Each file left out is
|
|
517
|
+
* in `skipped`, named, with why: a link, not text, over its cap, or a folder with no SKILL.md. */
|
|
518
|
+
export async function projectFiles(cwd, skipped) {
|
|
519
|
+
const instructions = {};
|
|
520
|
+
const skills = {};
|
|
521
|
+
// A project kept by --all or --include-deleted whose directory is gone has neither.
|
|
522
|
+
if (!(await lstat(cwd).catch(() => null))?.isDirectory())
|
|
523
|
+
return { instructions, skills };
|
|
524
|
+
const why = (reason) => (reason === "over_cap" ? `over ${MAX_FILE_BYTES} bytes` : reason === "link" ? "a link: not followed" : reason.replace("_", " "));
|
|
525
|
+
const text = async (rel) => {
|
|
526
|
+
try {
|
|
527
|
+
const bytes = await readWorkBytes(cwd, rel, { maxBytes: MAX_FILE_BYTES });
|
|
528
|
+
const decoded = bytes.includes(0)
|
|
529
|
+
? undefined
|
|
530
|
+
: (() => {
|
|
531
|
+
try {
|
|
532
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
533
|
+
}
|
|
534
|
+
catch {
|
|
535
|
+
return undefined;
|
|
536
|
+
}
|
|
537
|
+
})();
|
|
538
|
+
if (decoded === undefined)
|
|
539
|
+
skipped.push({ what: join(cwd, rel), why: "not text", kind: "file" });
|
|
540
|
+
return decoded;
|
|
541
|
+
}
|
|
542
|
+
catch (error) {
|
|
543
|
+
if (!(error instanceof WorkRefused))
|
|
544
|
+
throw error;
|
|
545
|
+
if (error.reason !== "missing")
|
|
546
|
+
skipped.push({ what: join(cwd, rel), why: why(error.reason), kind: "file" });
|
|
547
|
+
return undefined;
|
|
548
|
+
}
|
|
549
|
+
};
|
|
550
|
+
for (const name of ["CLAUDE.md", "AGENTS.md"]) {
|
|
551
|
+
const found = await text(name);
|
|
552
|
+
if (found !== undefined)
|
|
553
|
+
instructions[name] = found;
|
|
554
|
+
}
|
|
555
|
+
let total = 0;
|
|
556
|
+
for (const dir of SKILL_DIRS) {
|
|
557
|
+
// The folder itself is reached through no link: each component is a directory, not a link to one.
|
|
558
|
+
const parts = dir.split("/");
|
|
559
|
+
let reachable = true;
|
|
560
|
+
for (let i = 1; i <= parts.length && reachable; i++) {
|
|
561
|
+
const at = await lstat(join(cwd, ...parts.slice(0, i))).catch(() => null);
|
|
562
|
+
if (!at)
|
|
563
|
+
reachable = false;
|
|
564
|
+
else if (!at.isDirectory()) {
|
|
565
|
+
skipped.push({
|
|
566
|
+
what: join(cwd, ...parts.slice(0, i)),
|
|
567
|
+
why: at.isSymbolicLink() ? "a link: not followed" : "not a directory",
|
|
568
|
+
kind: "file",
|
|
569
|
+
});
|
|
570
|
+
reachable = false;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (!reachable)
|
|
574
|
+
continue;
|
|
575
|
+
const files = new Map();
|
|
576
|
+
try {
|
|
577
|
+
await walkWork(join(cwd, dir), (path, stats) => {
|
|
578
|
+
if (stats.isFile()) {
|
|
579
|
+
const name = path.split("/")[0];
|
|
580
|
+
if (path.includes("/"))
|
|
581
|
+
files.set(name, [...(files.get(name) ?? []), path]);
|
|
582
|
+
}
|
|
583
|
+
}, {
|
|
584
|
+
depth: 8,
|
|
585
|
+
refused: (path, reason) => skipped.push({ what: join(cwd, dir, path), why: why(reason), kind: "file" }),
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
catch (error) {
|
|
589
|
+
// The folder itself is not read (unreadable to this user): named, and the project's other folders still are.
|
|
590
|
+
if (!(error instanceof WorkRefused))
|
|
591
|
+
throw error;
|
|
592
|
+
skipped.push({ what: join(cwd, dir), why: why(error.reason), kind: "file" });
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
for (const [name, paths] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
|
|
596
|
+
if (!paths.includes(`${name}/SKILL.md`)) {
|
|
597
|
+
skipped.push({
|
|
598
|
+
what: join(cwd, dir, name),
|
|
599
|
+
why: "no SKILL.md: not a skill",
|
|
600
|
+
kind: "file",
|
|
601
|
+
});
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
if (Object.keys(skills).some((path) => path.startsWith(`${name}/`))) {
|
|
605
|
+
skipped.push({
|
|
606
|
+
what: join(cwd, dir, name),
|
|
607
|
+
why: "a skill of this name was already taken from another folder",
|
|
608
|
+
kind: "file",
|
|
609
|
+
});
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
// Every file is read again through the project, so a link anywhere on its way is refused, not followed.
|
|
613
|
+
const held = {};
|
|
614
|
+
for (const path of paths.sort()) {
|
|
615
|
+
const found = await text(`${dir}/${path}`);
|
|
616
|
+
if (found === undefined)
|
|
617
|
+
continue;
|
|
618
|
+
total += Buffer.byteLength(found);
|
|
619
|
+
if (total > MAX_SKILL_BYTES) {
|
|
620
|
+
skipped.push({
|
|
621
|
+
what: join(cwd, dir, path),
|
|
622
|
+
why: `the project's skill files are over ${MAX_SKILL_BYTES} bytes together`,
|
|
623
|
+
kind: "file",
|
|
624
|
+
});
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
held[path] = found;
|
|
628
|
+
}
|
|
629
|
+
if (held[`${name}/SKILL.md`] === undefined) {
|
|
630
|
+
skipped.push({
|
|
631
|
+
what: join(cwd, dir, name),
|
|
632
|
+
why: "its SKILL.md was not read: not a skill",
|
|
633
|
+
kind: "file",
|
|
634
|
+
});
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
Object.assign(skills, held);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return { instructions, skills };
|
|
641
|
+
}
|
|
642
|
+
/** A turn's transcript entry, with the source's ids of the records it was read from (`record_uuids`): a later import counts
|
|
643
|
+
* a copy of them once. */
|
|
644
|
+
const message = (turn, model) => {
|
|
645
|
+
const written = entryOf(turn, model);
|
|
646
|
+
return turn.uuids?.length ? { ...written, data: { ...written.data, record_uuids: turn.uuids } } : written;
|
|
647
|
+
};
|
|
648
|
+
const entryOf = (turn, model) => {
|
|
649
|
+
if (turn.role === "user")
|
|
650
|
+
return {
|
|
651
|
+
entry: UserEntry,
|
|
652
|
+
model: {
|
|
653
|
+
role: "user",
|
|
654
|
+
content: [{ type: "text", text: turn.text }],
|
|
655
|
+
timestamp: turn.at,
|
|
656
|
+
},
|
|
657
|
+
};
|
|
658
|
+
// The harness's own line, as an interrupt is written: a user's entry, by its author, so no request.
|
|
659
|
+
if (turn.role === "note")
|
|
660
|
+
return {
|
|
661
|
+
entry: UserEntry,
|
|
662
|
+
model: { role: "user", content: [{ type: "text", text: turn.text }], timestamp: turn.at },
|
|
663
|
+
data: { author: turn.author },
|
|
664
|
+
};
|
|
665
|
+
if (turn.role === "toolResult")
|
|
666
|
+
return {
|
|
667
|
+
entry: ToolResultEntry,
|
|
668
|
+
model: {
|
|
669
|
+
role: "toolResult",
|
|
670
|
+
toolCallId: turn.callId,
|
|
671
|
+
toolName: turn.name,
|
|
672
|
+
content: [{ type: "text", text: turn.text }],
|
|
673
|
+
isError: turn.isError,
|
|
674
|
+
timestamp: turn.at,
|
|
675
|
+
},
|
|
676
|
+
data: { diagnostics: [] },
|
|
677
|
+
};
|
|
678
|
+
const [provider, ...id] = (turn.model ?? model ?? "imported/unknown").split("/");
|
|
679
|
+
const cost = turn.costUsd;
|
|
680
|
+
// A request the source gave no counts for keeps zeros, which a run's metrics read as unmetered, never as 0 tokens.
|
|
681
|
+
const { input, output, cacheRead, cacheWrite, cacheWrite1h } = turn.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
682
|
+
return {
|
|
683
|
+
entry: AssistantEntry,
|
|
684
|
+
model: {
|
|
685
|
+
role: "assistant",
|
|
686
|
+
content: turn.error !== undefined ? [] : [...(turn.text ? [{ type: "text", text: turn.text }] : []), ...turn.calls],
|
|
687
|
+
api: "imported",
|
|
688
|
+
provider,
|
|
689
|
+
model: id.join("/") || provider,
|
|
690
|
+
// The source's own id for the response: a later import counts it once, whichever file holds it.
|
|
691
|
+
...(turn.key ? { responseId: turn.key } : {}),
|
|
692
|
+
// No total when the source did not price the request: the timeline's sum is then unknown, never this request at 0.
|
|
693
|
+
usage: {
|
|
694
|
+
input,
|
|
695
|
+
output,
|
|
696
|
+
cacheRead,
|
|
697
|
+
cacheWrite,
|
|
698
|
+
...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}),
|
|
699
|
+
totalTokens: input + output + cacheRead + cacheWrite,
|
|
700
|
+
cost: cost === undefined ? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: cost },
|
|
701
|
+
},
|
|
702
|
+
// A failed request's zero counts are its counts, as a live run's failed request's are.
|
|
703
|
+
...(turn.error !== undefined ? { stopReason: "error", errorMessage: turn.error } : { stopReason: turn.calls.length ? "toolUse" : "stop" }),
|
|
704
|
+
timestamp: turn.at,
|
|
705
|
+
},
|
|
706
|
+
};
|
|
707
|
+
};
|
|
708
|
+
/** The entries `message` makes of a session's turns, as a transcript holds them. */
|
|
709
|
+
const entriesOf = (session) => session.turns.map((turn) => {
|
|
710
|
+
const { entry, model, data } = message(turn, session.model);
|
|
711
|
+
return { kind: entry.kind, model: [model], ...(data ? { data } : {}) };
|
|
712
|
+
});
|
|
713
|
+
/** What a session read whole used, its subagents' requests with it, and when it asked: its metrics and time at work,
|
|
714
|
+
* and its own requests by hour. */
|
|
715
|
+
function measured(session, children = []) {
|
|
716
|
+
return {
|
|
717
|
+
metrics: { ...metricsOf(session, children), activeMs: session.activeMs },
|
|
718
|
+
hours: hoursOf(session.turns.flatMap((turn) => (turn.role === "assistant" ? [turn.at] : []))),
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
/** The run's transcript, into a store file at `storePath`, each string with the environment's key values cut out, its
|
|
722
|
+
* subagents' requests after its own turns (subagentMarks); the entries written, read back as the run's own timeline
|
|
723
|
+
* reads them. */
|
|
724
|
+
async function writeTimeline(storePath, session, cut, children = []) {
|
|
725
|
+
const { createModels } = await import("@earendil-works/pi-ai/models");
|
|
726
|
+
const storage = await openNodeSqliteStorage(storePath);
|
|
727
|
+
// No model is asked anything: the catalog is only what opening a Harness takes.
|
|
728
|
+
const harness = await Harness.open(storage, { registry: createRegistry(), models: createModels() }, ctx);
|
|
729
|
+
try {
|
|
730
|
+
await harness.root(ctx);
|
|
731
|
+
await harness.commit(async (tx) => {
|
|
732
|
+
for (const turn of session.turns) {
|
|
733
|
+
const { entry, model, data } = message(turn, session.model);
|
|
734
|
+
await tx.appendEntry(entry, ROOT_CONVERSATION_ID, {
|
|
735
|
+
model: [cut(model)],
|
|
736
|
+
...(data ? { data: data } : {}),
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
for (const { kind, data } of subagentMarks(children))
|
|
740
|
+
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data: cut(data) });
|
|
741
|
+
}, ctx);
|
|
742
|
+
}
|
|
743
|
+
finally {
|
|
744
|
+
await harness.close(ctx);
|
|
745
|
+
}
|
|
746
|
+
// A rollback journal, not WAL: the transcript never changes again, and a reader of a WAL file leaves -wal and -shm
|
|
747
|
+
// beside it, where nothing else may move.
|
|
748
|
+
const { DatabaseSync } = await import("node:sqlite");
|
|
749
|
+
const db = new DatabaseSync(storePath);
|
|
750
|
+
let entries;
|
|
751
|
+
try {
|
|
752
|
+
db.exec("PRAGMA journal_mode = DELETE");
|
|
753
|
+
entries = db.prepare("SELECT record FROM entries ORDER BY id").all().map((row) => JSON.parse(row.record));
|
|
754
|
+
}
|
|
755
|
+
finally {
|
|
756
|
+
db.close();
|
|
757
|
+
}
|
|
758
|
+
// The owner's only, whatever the umask made it.
|
|
759
|
+
for (const file of [storePath, `${storePath}-wal`, `${storePath}-shm`])
|
|
760
|
+
await chmod(file, 0o600).catch((error) => {
|
|
761
|
+
if (error.code !== "ENOENT")
|
|
762
|
+
throw error;
|
|
763
|
+
});
|
|
764
|
+
return entries;
|
|
765
|
+
}
|
|
766
|
+
/** What a run's requests cost at the catalog's list prices, each at its own provider's entry for its model: undefined when
|
|
767
|
+
* one request's tokens are unknown or its provider does not list its model (the request was served at a price no one
|
|
768
|
+
* lists here). A provider's $0 entry is $0. A request of no tokens costs nothing at any price. */
|
|
769
|
+
async function estimateOf(entries, catalog) {
|
|
770
|
+
// Unknown when one answer priced here has unknown tokens (a failed one's counts are its own, as runMetricsOf reads them).
|
|
771
|
+
if (runMetricsOf(entries.filter((entry) => entry.kind === "pi.assistant")).unmetered > 0)
|
|
772
|
+
return undefined;
|
|
773
|
+
const { calculateCost } = await import("@earendil-works/pi-ai");
|
|
774
|
+
let total = 0;
|
|
775
|
+
for (const entry of entries) {
|
|
776
|
+
const answer = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
|
|
777
|
+
if (!answer?.usage)
|
|
778
|
+
continue;
|
|
779
|
+
const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0, cacheWrite1h } = answer.usage;
|
|
780
|
+
if (input + output + cacheRead + cacheWrite === 0)
|
|
781
|
+
continue;
|
|
782
|
+
const cost = answer.provider && answer.model ? (await catalog()).get(answer.model)?.find((entry) => entry.provider === answer.provider)?.cost : undefined;
|
|
783
|
+
if (!cost)
|
|
784
|
+
return undefined;
|
|
785
|
+
const usage = { input, output, cacheRead, cacheWrite, ...(cacheWrite1h !== undefined ? { cacheWrite1h } : {}), totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
|
|
786
|
+
total += calculateCost({ cost }, usage).total;
|
|
787
|
+
}
|
|
788
|
+
return Math.round(total * 1e6) / 1e6;
|
|
789
|
+
}
|
|
790
|
+
/** The revision of `harness` an earlier import made for the agent, else a new one (current when the agent is new). */
|
|
791
|
+
async function revisionFor(store, agentId, source, files, model, cut, current) {
|
|
792
|
+
const note = `imported from ${source}`;
|
|
793
|
+
const held = store.readAgent(agentId)?.revisions.find((r) => r.note === note);
|
|
794
|
+
if (held)
|
|
795
|
+
return held;
|
|
796
|
+
const harness = HARNESS_OF[source];
|
|
797
|
+
const instructions = INSTRUCTIONS[harness].map((name) => files.instructions[name]).find((text) => text !== undefined) ?? "";
|
|
798
|
+
const revision = {
|
|
799
|
+
kind: "agentic",
|
|
800
|
+
instructions: cut(instructions),
|
|
801
|
+
skills: keptSkills(files.skills, cut),
|
|
802
|
+
tools: [],
|
|
803
|
+
...(model ? { model } : {}),
|
|
804
|
+
...(harness !== "pi" ? { harness } : {}),
|
|
805
|
+
note,
|
|
806
|
+
};
|
|
807
|
+
return store.commitRevision(agentId, revision, { setCurrent: current });
|
|
808
|
+
}
|
|
809
|
+
/** A run's serve.json: its title and input, and the session file it was read from, as read. */
|
|
810
|
+
async function writeMeta(dir, session, read, json) {
|
|
811
|
+
const meta = json({
|
|
812
|
+
// Cut before it is clipped: a key the clip cut short would match no rule.
|
|
813
|
+
title: clip(json(session.firstPrompt ?? `${session.source} session`), 120),
|
|
814
|
+
created_at: session.startedAt ?? new Date(0).toISOString(),
|
|
815
|
+
input: { content: session.firstPrompt ?? "" },
|
|
816
|
+
});
|
|
817
|
+
const metaPath = join(dir, RUN_META);
|
|
818
|
+
await writeFile(metaPath, `${JSON.stringify({ ...meta, source_file: read })}\n`, { mode: 0o600 });
|
|
819
|
+
await chmod(metaPath, 0o600);
|
|
820
|
+
}
|
|
821
|
+
/** The secrets this server made and keeps in data directory `data`, by value: its API token (`ar_local_...`) and its
|
|
822
|
+
* door token (server.ts), its sign-in sessions' secret (owner.ts), its webhook's signing secret (`whsec_...`;
|
|
823
|
+
* webhooks.ts) and each webhook trigger's (trigger-secrets.ts), opened with the seal key of `env`, so left out when that key is not there. One pasted into a session is
|
|
824
|
+
* this server's own, so an import cuts it wherever it is, as it cuts the environment's keys. Not among them: a run's own
|
|
825
|
+
* door token (one file a run; not read at each import), and a key-shaped value this server did not make (a `whsec_`
|
|
826
|
+
* from elsewhere). A webhook secret that does not open is said to `say`, as ToolKeys says a saved key that does not:
|
|
827
|
+
* the import goes on, and does not cut it. */
|
|
828
|
+
export function ownSecrets(data, env, say = () => { }) {
|
|
829
|
+
const read = (name) => {
|
|
830
|
+
try {
|
|
831
|
+
return readFileSync(join(data, name), "utf8").trim();
|
|
832
|
+
}
|
|
833
|
+
catch {
|
|
834
|
+
return "";
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
const webhook = webhookSecretIn(data, env);
|
|
838
|
+
if (webhook && "signing" in webhook)
|
|
839
|
+
say({ condition: webhook.signing, name: SEAL_KEY_ENV, file: join(data, WEBHOOK_FILE), effect: "this server's webhook secret cannot be read, so the import does not cut it" });
|
|
840
|
+
const values = [read(TOKEN_FILE), read(DOOR_TOKEN_FILE), read(SESSION_SECRET_FILE), webhook && "secret" in webhook ? webhook.secret : "", ...triggerSecretsIn(data, env)];
|
|
841
|
+
return [...new Set(values)].filter((value) => value.length >= 8 && !/\s/.test(value));
|
|
842
|
+
}
|
|
843
|
+
/** The plan, into `store`: the agents it does not hold, and the runs it does not. A run an earlier import made whose
|
|
844
|
+
* transcript never landed (the process stopped between the two) has it written now. */
|
|
845
|
+
export async function runImport(store, plan, options) {
|
|
846
|
+
const cut = secretCut([options.env, options.stored ?? {}], SECRET_NAMES);
|
|
847
|
+
const { text, json } = cut;
|
|
848
|
+
// Each key found is the import's to cut, and the CLI's to cut out of what it prints.
|
|
849
|
+
const add = (keys) => (cut.add(keys), options.onKeys?.(keys));
|
|
850
|
+
// This server's own secrets, then every key the import finds.
|
|
851
|
+
add(options.own ?? []);
|
|
852
|
+
const report = { agents: [], skipped: [...plan.skipped], already: plan.already };
|
|
853
|
+
let prices;
|
|
854
|
+
const catalog = () => (prices ??= catalogPrices());
|
|
855
|
+
const held = importedIn(store);
|
|
856
|
+
// Every key of the import is known before anything of it is written.
|
|
857
|
+
const known = await findKeys(plan, add, text, (listed) => {
|
|
858
|
+
const run = held.get(`${listed.source}:${listed.id}`);
|
|
859
|
+
return run !== undefined && existsSync(store.runStorePath(run));
|
|
860
|
+
}, options.signal);
|
|
861
|
+
const scannedAs = known.stamps;
|
|
862
|
+
for (const project of plan.projects) {
|
|
863
|
+
if (options.signal?.aborted)
|
|
864
|
+
break;
|
|
865
|
+
const created = !store.readAgent(project.agentId);
|
|
866
|
+
const files = await projectFiles(project.cwd, report.skipped);
|
|
867
|
+
// Its own text read through secretlint again only if it changed since the pass above.
|
|
868
|
+
const textNow = projectText(project.cwd, files);
|
|
869
|
+
if (hash(textNow) !== known.texts.get(project.agentId))
|
|
870
|
+
add(await secretsIn(textNow));
|
|
871
|
+
if (created)
|
|
872
|
+
store.createAgent({
|
|
873
|
+
id: project.agentId,
|
|
874
|
+
name: keptName(project, text),
|
|
875
|
+
description: text(project.cwd),
|
|
876
|
+
});
|
|
877
|
+
const byStart = [...project.sessions].sort((a, b) => (a.startedAt ?? "").localeCompare(b.startedAt ?? ""));
|
|
878
|
+
const latest = byStart.at(-1);
|
|
879
|
+
// The latest session's harness is the agent's current revision; its model, each harness's latest.
|
|
880
|
+
const revisions = new Map();
|
|
881
|
+
const order = [...new Set(project.sessions.map((s) => s.source))].sort((a, b) => (a === latest.source ? 1 : 0) - (b === latest.source ? 1 : 0));
|
|
882
|
+
for (const source of order)
|
|
883
|
+
revisions.set(source, await revisionFor(store, project.agentId, source, files, byStart.findLast((s) => s.source === source && s.model)?.model, text, created && source === latest.source));
|
|
884
|
+
const line = { id: project.agentId, name: project.name, cwd: project.cwd, created, runs: 0, already: 0, finished: 0 };
|
|
885
|
+
// A record or response counted once across the import's files, those its runs here hold already included.
|
|
886
|
+
const seen = await seenIn(store, project.agentId);
|
|
887
|
+
for (const files of byRun(project.sessions)) {
|
|
888
|
+
if (options.signal?.aborted)
|
|
889
|
+
break;
|
|
890
|
+
const listed = files[0];
|
|
891
|
+
const heldRun = held.get(`${listed.source}:${listed.id}`);
|
|
892
|
+
if (heldRun !== undefined && existsSync(store.runStorePath(heldRun))) {
|
|
893
|
+
line.already += 1;
|
|
894
|
+
continue;
|
|
895
|
+
}
|
|
896
|
+
// Each of its files, in order. The first's size and time before its read: a file that changes during it is read
|
|
897
|
+
// again next time.
|
|
898
|
+
const parts = [];
|
|
899
|
+
// Every file of it read: one holding only copies adds no records, but its subagents' folder is read with the rest.
|
|
900
|
+
const searched = [];
|
|
901
|
+
let read;
|
|
902
|
+
let changed = false;
|
|
903
|
+
for (const { file } of files) {
|
|
904
|
+
const stats = await stat(file).catch(() => null);
|
|
905
|
+
const part = stats ? await readSession(file, listed.source, { seen: seen(listed.source) }).catch((error) => void report.skipped.push(unread(file, error))) : void report.skipped.push({ what: file, why: "gone since it was listed", kind: "vanished" });
|
|
906
|
+
if (!part || !stats)
|
|
907
|
+
continue;
|
|
908
|
+
searched.push(part);
|
|
909
|
+
// A file of it holding only copies adds nothing to it.
|
|
910
|
+
if (heldRun === undefined && ownless(part)) {
|
|
911
|
+
report.skipped.push({ what: file, why: "holds only records of sessions imported already", kind: "copies" });
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
read ??= { path_sha256: hash(file), size: stats.size, mtime_ms: stats.mtimeMs };
|
|
915
|
+
parts.push(part);
|
|
916
|
+
if (scannedAs.get(file) !== stampOf(stats))
|
|
917
|
+
changed = true;
|
|
918
|
+
}
|
|
919
|
+
if (!read)
|
|
920
|
+
continue;
|
|
921
|
+
const session = merged(parts);
|
|
922
|
+
// A file of it changed since the scan above (a session still being written): what it holds now, read through
|
|
923
|
+
// secretlint again before any of it is cut.
|
|
924
|
+
if (changed)
|
|
925
|
+
add(await keysInSessions(parts));
|
|
926
|
+
// Its id as the plan keeps it (a key in it is one secretlint finds in what was read, the id among it); one
|
|
927
|
+
// holding a key counts among the keys removed.
|
|
928
|
+
const keptAs = text(session.id) === session.id ? session.id : redactedId(session.id);
|
|
929
|
+
session.id = keptAs;
|
|
930
|
+
const subagents = await readChildren(plan, session, searched, seen(listed.source));
|
|
931
|
+
const moved = await Promise.all(subagents.map(async (child) => scannedAs.get(child.file) !== stampOf((await stat(child.file).catch(() => null)) ?? { size: -1, mtimeMs: -1 })));
|
|
932
|
+
if (moved.some(Boolean))
|
|
933
|
+
add(await keysInSessions(subagents));
|
|
934
|
+
// The transcript is whole before its run is: written beside the store, then moved into the run's directory.
|
|
935
|
+
const pending = join(store.dir, `.import-${randomUUID()}.sqlite`);
|
|
936
|
+
let started;
|
|
937
|
+
try {
|
|
938
|
+
// Its subagents' requests are the run's too: marked in its transcript, so its timeline's usage row counts what its
|
|
939
|
+
// metrics do, one number for the run.
|
|
940
|
+
const entries = await writeTimeline(pending, session, json, subagents);
|
|
941
|
+
const metrics = { ...withChildren(runMetricsOf(entries), subagents.map((child) => runMetricsOf(entriesOf(child)))), activeMs: session.activeMs, ...(session.effort ? { effort: session.effort } : {}) };
|
|
942
|
+
// A session its source did not price: the catalog's estimate, beside its cost (unknown), never written as it.
|
|
943
|
+
const estimate = session.costUsd === undefined ? await estimateOf([...entries, ...subagents.flatMap(entriesOf)], catalog) : undefined;
|
|
944
|
+
if (estimate !== undefined)
|
|
945
|
+
Object.assign(metrics, { costUsdEst: estimate, costBasis: "catalog" });
|
|
946
|
+
if (heldRun !== undefined) {
|
|
947
|
+
started = { runId: heldRun, dir: join(store.dir, "runs", heldRun), storePath: store.runStorePath(heldRun) };
|
|
948
|
+
if ((await mkdir(dirname(started.storePath), { recursive: true })) !== undefined)
|
|
949
|
+
for (const made of [started.dir, dirname(started.storePath)])
|
|
950
|
+
await chmod(made, 0o700);
|
|
951
|
+
}
|
|
952
|
+
else {
|
|
953
|
+
const answer = session.turns.findLast((t) => t.role === "assistant" && t.text)?.text;
|
|
954
|
+
started = await store.importRun({
|
|
955
|
+
agent: project.agentId,
|
|
956
|
+
revision: revisions.get(session.source).id,
|
|
957
|
+
state: session.state,
|
|
958
|
+
startedAt: session.startedAt ?? new Date(0).toISOString(),
|
|
959
|
+
endedAt: session.endedAt ?? session.startedAt ?? new Date(0).toISOString(),
|
|
960
|
+
...(session.costUsd !== undefined ? { costUsd: session.costUsd } : {}),
|
|
961
|
+
...((answer ?? session.firstPrompt) ? { summary: text(answer ?? session.firstPrompt) } : {}),
|
|
962
|
+
source: session.source,
|
|
963
|
+
session: session.id,
|
|
964
|
+
metrics,
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
if (started)
|
|
968
|
+
await rename(pending, started.storePath);
|
|
969
|
+
}
|
|
970
|
+
finally {
|
|
971
|
+
await rm(pending, { force: true });
|
|
972
|
+
}
|
|
973
|
+
if (!started) {
|
|
974
|
+
line.already += 1;
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
await writeMeta(started.dir, session, read, json);
|
|
978
|
+
if (heldRun !== undefined)
|
|
979
|
+
line.finished += 1;
|
|
980
|
+
else
|
|
981
|
+
line.runs += 1;
|
|
982
|
+
}
|
|
983
|
+
report.agents.push(line);
|
|
984
|
+
}
|
|
985
|
+
report.secretsRemoved = text.removed;
|
|
986
|
+
return report;
|
|
987
|
+
}
|
|
988
|
+
const counted = (n, one, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
|
|
989
|
+
// What each kind of left-out file is, counted: sessions first by how many, a project's files apart.
|
|
990
|
+
const LEFT_OUT = {
|
|
991
|
+
gone: (n) => `${counted(n, "session")} from folders that no longer exist`,
|
|
992
|
+
temp: (n) => `${counted(n, "session")} from temp folders`,
|
|
993
|
+
live: (n) => `${counted(n, "session")} still being written: ${n === 1 ? "it comes" : "they come"} in next time`,
|
|
994
|
+
"no-words": (n) => `${counted(n, "session")} with no message of yours`,
|
|
995
|
+
"no-project": (n) => `${counted(n, "file")} that ${n === 1 ? "is not a session" : "are not sessions"} (no project folder in ${n === 1 ? "it" : "them"})`,
|
|
996
|
+
large: (n) => `${counted(n, "session")} over ${MAX_SESSION_BYTES / 1024 / 1024} MB`,
|
|
997
|
+
unread: (n) => `${counted(n, "session file")} that could not be read`,
|
|
998
|
+
vanished: (n) => `${counted(n, "session file")} gone since ${n === 1 ? "it was" : "they were"} counted`,
|
|
999
|
+
copies: (n) => `${counted(n, "file")} holding only copies of sessions imported already`,
|
|
1000
|
+
file: (n) => `${counted(n, "project file")} not copied (a link, not text, over its size cap, or a folder with no SKILL.md)`,
|
|
1001
|
+
};
|
|
1002
|
+
/** What an import left out, by why: one group per kind, the most first (a project's files last), each counted in words
|
|
1003
|
+
* ("84 sessions from folders that no longer exist"): a session by its id where the file was read, so one of two files
|
|
1004
|
+
* counts once, else each file. */
|
|
1005
|
+
export function leftOutOf(skipped) {
|
|
1006
|
+
const seen = new Map();
|
|
1007
|
+
for (const { kind, what, session } of skipped)
|
|
1008
|
+
seen.set(kind, (seen.get(kind) ?? new Set()).add(session ?? `file:${what}`));
|
|
1009
|
+
const by = new Map([...seen].map(([kind, ids]) => [kind, ids.size]));
|
|
1010
|
+
const order = Object.keys(LEFT_OUT);
|
|
1011
|
+
return [...by]
|
|
1012
|
+
.sort(([a, x], [b, y]) => Number(a === "file") - Number(b === "file") || y - x || order.indexOf(a) - order.indexOf(b))
|
|
1013
|
+
.map(([kind, count]) => ({ kind, count, label: LEFT_OUT[kind](count) }));
|
|
1014
|
+
}
|
|
1015
|
+
// How the CLI brings a kind in, when one of its flags does.
|
|
1016
|
+
const BRING_IN = { gone: "--include-deleted", temp: "--all", "no-words": "--all" };
|
|
1017
|
+
/** The CLI's left-out lines: each group (leftOutOf), with the flag that imports it too. */
|
|
1018
|
+
const leftOutLines = (skipped) => leftOutOf(skipped).map(({ kind, count, label }) => `left out: ${label}${BRING_IN[kind] ? ` (${BRING_IN[kind]} imports ${count === 1 ? "it" : "them"} too)` : ""}`);
|
|
1019
|
+
/** The plan as a person reads it: one line per project, its sessions counted as the import takes them, then (`verbose`)
|
|
1020
|
+
* each file left out and why. */
|
|
1021
|
+
export function describePlan(plan, store, { verbose = false } = {}) {
|
|
1022
|
+
const held = store ? importedIn(store) : undefined;
|
|
1023
|
+
const lines = plan.projects.map((project) => {
|
|
1024
|
+
const sessions = sessionsOf(project.sessions);
|
|
1025
|
+
const by = new Map();
|
|
1026
|
+
for (const s of sessions)
|
|
1027
|
+
by.set(s.source, (by.get(s.source) ?? 0) + 1);
|
|
1028
|
+
const already = held ? sessions.filter((s) => held.has(s.key)).length : 0;
|
|
1029
|
+
const priced = sessions.filter((s) => s.priced).length;
|
|
1030
|
+
return `${project.cwd} ${[...by].map(([source, n]) => `${source} ${n}`).join(", ")} cost known ${priced}/${sessions.length}${already ? ` already imported ${already}` : ""}`;
|
|
1031
|
+
});
|
|
1032
|
+
return [...lines, ...(plan.already ? [`already imported, unchanged: ${plan.already} session files`] : []), ...(verbose ? plan.skipped.map((s) => `skipped ${s.what}: ${s.why}`) : [])];
|
|
1033
|
+
}
|
|
1034
|
+
/** `agentrun-serve import ARGS`: its exit code. */
|
|
1035
|
+
export async function importCommand(args, usage, { home = homedir(),
|
|
1036
|
+
// The folder whose projects are left out as temporary (the OS's temp directory).
|
|
1037
|
+
temp = tmpdir(),
|
|
1038
|
+
// The server's own keys, which its start moved out of process.env (secrets.ts), read back in: the import cuts them
|
|
1039
|
+
// out of what it keeps, as it cuts every other key in the environment.
|
|
1040
|
+
env = withSecrets(process.env), out = console.log, } = {}) {
|
|
1041
|
+
// What it prints goes through the cut what it keeps does, with the keys secretlint finds in the lines themselves: a
|
|
1042
|
+
// file or project named after a key is printed cut. The lines are held until the end, then scanned and printed.
|
|
1043
|
+
const printed = secretCut(env, SECRET_NAMES);
|
|
1044
|
+
const print = out;
|
|
1045
|
+
const lines = [];
|
|
1046
|
+
out = (line) => void lines.push(line);
|
|
1047
|
+
// What it says on stderr (a key or a secret that does not open here, its file named) is held and cut the same way, and
|
|
1048
|
+
// printed first.
|
|
1049
|
+
const warnings = [];
|
|
1050
|
+
const say = (event) => (fields) => void warnings.push(`agentrun-serve import: ${logLine(event, fields)}`);
|
|
1051
|
+
const flush = async () => {
|
|
1052
|
+
printed.add(await secretsIn([...warnings, ...lines].join("\n")));
|
|
1053
|
+
for (const line of warnings.splice(0))
|
|
1054
|
+
console.error(printed.text(line));
|
|
1055
|
+
for (const line of lines.splice(0))
|
|
1056
|
+
print(printed.text(line));
|
|
1057
|
+
};
|
|
1058
|
+
try {
|
|
1059
|
+
let values;
|
|
1060
|
+
try {
|
|
1061
|
+
({ values } = parseArgs({
|
|
1062
|
+
args,
|
|
1063
|
+
options: {
|
|
1064
|
+
data: { type: "string" },
|
|
1065
|
+
from: { type: "string" },
|
|
1066
|
+
"dry-run": { type: "boolean" },
|
|
1067
|
+
all: { type: "boolean" },
|
|
1068
|
+
"include-deleted": { type: "boolean" },
|
|
1069
|
+
verbose: { type: "boolean" },
|
|
1070
|
+
port: { type: "string" },
|
|
1071
|
+
},
|
|
1072
|
+
}));
|
|
1073
|
+
}
|
|
1074
|
+
catch (error) {
|
|
1075
|
+
console.error(`${error.message}\n\n${usage}`);
|
|
1076
|
+
return 2;
|
|
1077
|
+
}
|
|
1078
|
+
const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
|
|
1079
|
+
if (!Number.isInteger(port) || port < 0 || port > 65_535) {
|
|
1080
|
+
console.error(`--port takes a port number\n\n${usage}`);
|
|
1081
|
+
return 2;
|
|
1082
|
+
}
|
|
1083
|
+
const open = openAt(env, port);
|
|
1084
|
+
const sources = values.from === undefined ? SOURCES : values.from.split(",").map((s) => s.trim());
|
|
1085
|
+
const unknown = sources.filter((s) => !SOURCES.includes(s));
|
|
1086
|
+
if (unknown.length) {
|
|
1087
|
+
console.error(`--from takes ${SOURCES.join(", ")}: not ${unknown.join(", ")}\n\n${usage}`);
|
|
1088
|
+
return 2;
|
|
1089
|
+
}
|
|
1090
|
+
const dir = values.data ?? defaultData({ ...env, HOME: home });
|
|
1091
|
+
// The tool keys the server keeps in this directory, opened here on the host with the seal key this process was handed:
|
|
1092
|
+
// an imported transcript keeps none of them. One that does not open is not known here, so not cut: said, as the
|
|
1093
|
+
// server says it at its start.
|
|
1094
|
+
const keys = new ToolKeys(dir, env, say("tool_keys"));
|
|
1095
|
+
keys.view();
|
|
1096
|
+
const options = {
|
|
1097
|
+
home,
|
|
1098
|
+
sources: sources,
|
|
1099
|
+
all: values.all === true,
|
|
1100
|
+
deleted: values["include-deleted"] === true,
|
|
1101
|
+
temp,
|
|
1102
|
+
env,
|
|
1103
|
+
stored: keys.values(),
|
|
1104
|
+
own: ownSecrets(dir, env, say("webhook_secret")),
|
|
1105
|
+
};
|
|
1106
|
+
// What it prints is cut with the saved keys too, and with every key the import (or the dry run) finds, as what it
|
|
1107
|
+
// keeps is.
|
|
1108
|
+
printed.add(Object.values(options.stored ?? {}));
|
|
1109
|
+
options.onKeys = (keys) => printed.add(keys);
|
|
1110
|
+
if (values["dry-run"]) {
|
|
1111
|
+
// A dry run writes nothing, not even a store: one there already is only read.
|
|
1112
|
+
const reader = existsSync(join(dir, STORE_FILE)) ? openStoreReader(dir) : undefined;
|
|
1113
|
+
let plan;
|
|
1114
|
+
let found;
|
|
1115
|
+
try {
|
|
1116
|
+
plan = await planImport({ ...options, measure: true }, reader);
|
|
1117
|
+
for (const line of describePlan(plan, reader, { verbose: values.verbose === true }))
|
|
1118
|
+
out(line);
|
|
1119
|
+
found = [...plan.found, ...(reader ? await foundAll(reader, plan.held) : []), ...(await untiedFound(plan))];
|
|
1120
|
+
}
|
|
1121
|
+
finally {
|
|
1122
|
+
reader?.close();
|
|
1123
|
+
}
|
|
1124
|
+
out(`${plan.projects.length} projects, ${sessionsOf(plan.projects.flatMap((p) => p.sessions)).length} sessions; nothing was written (dry run)`);
|
|
1125
|
+
if (plan.secretsFound !== undefined)
|
|
1126
|
+
out(`${plan.secretsFound} secret${plan.secretsFound === 1 ? "" : "s"} would be removed`);
|
|
1127
|
+
for (const line of leftOutLines(plan.skipped))
|
|
1128
|
+
out(line);
|
|
1129
|
+
for (const line of summaryLines(found, open, { dryRun: true }))
|
|
1130
|
+
out(line);
|
|
1131
|
+
return 0;
|
|
1132
|
+
}
|
|
1133
|
+
const store = openStore(dir);
|
|
1134
|
+
try {
|
|
1135
|
+
const plan = await planImport(options, store);
|
|
1136
|
+
const report = await runImport(store, plan, options);
|
|
1137
|
+
for (const agent of report.agents)
|
|
1138
|
+
out(`${agent.cwd} ${agent.created ? "new agent" : "agent held"} ${agent.id} imported ${agent.runs}${agent.finished ? `, finished ${agent.finished}` : ""}${agent.already ? `, already imported ${agent.already}` : ""}`);
|
|
1139
|
+
if (report.already)
|
|
1140
|
+
out(`already imported, unchanged: ${report.already} session files (not read again)`);
|
|
1141
|
+
if (values.verbose)
|
|
1142
|
+
for (const s of report.skipped)
|
|
1143
|
+
out(`skipped ${s.what}: ${s.why}`);
|
|
1144
|
+
out(`${report.agents.length} agents, ${report.agents.reduce((n, a) => n + a.runs, 0)} runs imported into ${dir}`);
|
|
1145
|
+
out(`${report.secretsRemoved ?? 0} secret${report.secretsRemoved === 1 ? "" : "s"} removed`);
|
|
1146
|
+
for (const line of leftOutLines(report.skipped))
|
|
1147
|
+
out(line);
|
|
1148
|
+
// Every session found: those imported now, those held before, and those whose file an earlier import read whole.
|
|
1149
|
+
const held = importedIn(store);
|
|
1150
|
+
const runs = [...plan.projects.flatMap((p) => p.sessions.flatMap((s) => held.get(`${s.source}:${s.id}`) ?? [])), ...plan.held];
|
|
1151
|
+
for (const line of summaryLines([...(await foundAll(store, runs)), ...(await untiedFound(plan))], open))
|
|
1152
|
+
out(line);
|
|
1153
|
+
return 0;
|
|
1154
|
+
}
|
|
1155
|
+
finally {
|
|
1156
|
+
store.close();
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
finally {
|
|
1160
|
+
await flush();
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
/** The imported runs `runIds` of `store`, each once, as found. */
|
|
1164
|
+
async function foundAll(store, runIds) {
|
|
1165
|
+
const found = [];
|
|
1166
|
+
for (const id of new Set(runIds)) {
|
|
1167
|
+
const run = await foundIn(store, id);
|
|
1168
|
+
if (run)
|
|
1169
|
+
found.push(run);
|
|
1170
|
+
}
|
|
1171
|
+
return found;
|
|
1172
|
+
}
|
|
1173
|
+
/** The address the summary's Open line names on this machine: the one a local server listens on by default. */
|
|
1174
|
+
const LOCAL = "127.0.0.1"; // key-gate: loopback-rule the default address a server on this machine listens on; a hint printed, the line dials nothing
|
|
1175
|
+
/** Where a person opens the console: the server's public address when one is set (as the server takes it), else this
|
|
1176
|
+
* machine's at `port`. A hint after an import, not a server setting. */
|
|
1177
|
+
function openAt(env, port) {
|
|
1178
|
+
const given = env.AGENTRUN_PUBLIC_URL || env.RENDER_EXTERNAL_URL;
|
|
1179
|
+
const parsed = given && URL.canParse(given) ? new URL(given) : undefined;
|
|
1180
|
+
if (parsed && /^https?:$/.test(parsed.protocol))
|
|
1181
|
+
return parsed.href.replace(/\/+$/, "");
|
|
1182
|
+
return `http://${LOCAL}:${port === 0 ? "<the port the server picks>" : port}`;
|
|
1183
|
+
}
|
|
1184
|
+
/** The "/"-segments of `path` a key touches (by their index): each whose blanking takes a key out of the path. Blanked
|
|
1185
|
+
* with spaces, which end every shape and are in no environment's key; the blanked paths are never kept, so they go
|
|
1186
|
+
* through the cut's probe, which counts nothing (a shorter value a blank leaves is no key removed). */
|
|
1187
|
+
function touchedSegments(path, cut) {
|
|
1188
|
+
const out = cut(path);
|
|
1189
|
+
if (out === path)
|
|
1190
|
+
return [];
|
|
1191
|
+
const probe = cut.probe ?? cut;
|
|
1192
|
+
const keys = (text) => probe(text).split(REDACTED).length;
|
|
1193
|
+
const held = out.split(REDACTED).length;
|
|
1194
|
+
const parts = path.split("/");
|
|
1195
|
+
return parts.flatMap((segment, at) => (keys([...parts.slice(0, at), " ".repeat(segment.length), ...parts.slice(at + 1)].join("/")) < held ? [at] : []));
|
|
1196
|
+
}
|
|
1197
|
+
/** A project's skills as an import keeps them: each file's text cut, and its path as it is when it holds no key. Else
|
|
1198
|
+
* every segment a key touches (one, or several when an environment's value holds "/") is kept as `redacted-` and a hash
|
|
1199
|
+
* of it (as `keptId` keeps a session's id), so two folders named after two keys stay two and no part of a key is left.
|
|
1200
|
+
* A folder kept so is kept so for every file under it, so a skill's files stay one skill. */
|
|
1201
|
+
function keptSkills(skills, cut) {
|
|
1202
|
+
const redacted = (segment) => `redacted-${hash(segment).slice(0, 12)}`;
|
|
1203
|
+
// The folders (and files) a key touches, by their path from the skills' root.
|
|
1204
|
+
const touched = new Set();
|
|
1205
|
+
for (const path of Object.keys(skills)) {
|
|
1206
|
+
const parts = path.split("/");
|
|
1207
|
+
for (const at of touchedSegments(path, cut))
|
|
1208
|
+
touched.add(parts.slice(0, at + 1).join("/"));
|
|
1209
|
+
}
|
|
1210
|
+
return Object.fromEntries(Object.entries(skills).map(([path, text]) => {
|
|
1211
|
+
const parts = path.split("/");
|
|
1212
|
+
const kept = parts.map((segment, at) => (touched.has(parts.slice(0, at + 1).join("/")) ? redacted(segment) : segment)).join("/");
|
|
1213
|
+
return [cut(kept) === kept ? kept : redacted(path), cut(text)];
|
|
1214
|
+
}));
|
|
1215
|
+
}
|
|
1216
|
+
/** A project's name as an import keeps it (its folder's name): cut, or kept as `redacted-` and a hash of it when a key
|
|
1217
|
+
* touches it, one across the project's path ending in it among them, so no part of the key is left in the name. */
|
|
1218
|
+
function keptName(project, cut) {
|
|
1219
|
+
const parts = project.cwd.split("/");
|
|
1220
|
+
const last = parts.length - 1;
|
|
1221
|
+
return parts[last] === project.name && touchedSegments(project.cwd, cut).includes(last) ? `redacted-${hash(project.name).slice(0, 12)}` : cut(project.name);
|
|
1222
|
+
}
|