@parcha/agentrun-import 0.1.0-beta.57 → 0.1.0-beta.59

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.
@@ -0,0 +1,224 @@
1
+ // GitHub Copilot CLI: $COPILOT_HOME (~/.copilot)/session-state/<session id>/events.jsonl, one session event a line
2
+ // ({type, data, id, parentId, timestamp, agentId?, checkpoint?}); an older CLI wrote session-state/<session id>.jsonl.
3
+ // Sources: github/copilot-cli changelog.md (0.0.342: sessions in ~/.copilot/session-state; 0.0.422: "Session usage
4
+ // metrics (requests, tokens, code changes) are now persisted to events.jsonl after each session ends"); github/copilot-sdk
5
+ // at 5378d2d47d nodejs/src/generated/session-events.ts (the event schema), docs/features/session-persistence.md (the
6
+ // folder, events.N.jsonl archives and checkpoint records), docs/features/streaming-events.md (which events are persisted)
7
+ // and docs/features/usage-and-billing.md (inputTokens holds the cache read and write); @github/copilot 1.0.40 and
8
+ // 1.0.63 app.js (the config folder is --config-dir, else COPILOT_HOME, else ~/.copilot; a usage tracker made new for
9
+ // each process, fed only by live assistant.usage events).
10
+ //
11
+ // Tokens: assistant.usage, the one per-request record, is ephemeral: never written to disk. What is written is the
12
+ // session.shutdown each process writes as it exits: each model's tokens (modelMetrics), its subagents' with them. A CLI
13
+ // that keeps its accounting across processes (session.usage_checkpoint, the shutdown's usageAccountingWatermarks)
14
+ // writes the session's whole total there, so only what a shutdown adds to the totals read before it counts; an older
15
+ // CLI's shutdown counts its own process alone. A model's tokens go on the last request of that model since the process
16
+ // started (since session.start or session.resume), or on a request of their own when it has none there (a compaction's
17
+ // model); that model's other requests in the process are folded into it (`folded`: zeros, known). A session with no
18
+ // shutdown (still running, or killed) has its requests at unknown tokens. The CLI writes no price in dollars (it bills
19
+ // premium requests and AI credits), so the cost is the catalog's: the carriers' tokens at list price, unknown (null)
20
+ // when a request is at unknown tokens.
21
+ //
22
+ // Each persisted event counts once ("u:" its id), each message once ("m:" its messageId). A model call is one request:
23
+ // a response split into chunks (each chunk a message of its own, chunkIndex > 0 after the first) joins the request of
24
+ // its first chunk, its apiCallId the same. A shutdown read already in another file (a copied session) adds no tokens,
25
+ // but moves what this file has counted, so its next whole total adds only its own. A record marked checkpoint (a
26
+ // rotated journal's copy of its archive) is a copy: read for the session's id, folder and model alone. Each turn keeps
27
+ // the ids it was read by (`uuids` its events', a request's `keys` its later chunks' messageIds, a shutdown's on the
28
+ // requests it fed), so that a later import of a copy, handed them as seen, counts the copy as one import of both would.
29
+ // events.N.jsonl archives, which a CLI writes only when COPILOT_SESSION_EVENT_LOG_ROTATION_BYTES is set, are not read;
30
+ // history-session-state, the format before 0.0.342, neither.
31
+ import { basename, dirname, join } from "node:path";
32
+ import { lineReader } from "../lines.js";
33
+ import { entries } from "../reader.js";
34
+ import { argsOf, effortOf, isObject, str } from "../text.js";
35
+ import { normalizeUsage } from "../usage.js";
36
+ /** A Copilot model id as "provider/model": github-copilot's, unless it names its provider. */
37
+ const modelOf = (model) => (model.includes("/") ? model : `github-copilot/${model}`);
38
+ const BUCKETS = ["input", "output", "cacheRead", "cacheWrite"];
39
+ const combine = (a, b, op) => {
40
+ const out = Object.fromEntries(BUCKETS.map((k) => [k, op(a[k], b?.[k] ?? 0)]));
41
+ if (a.reasoning !== undefined || b?.reasoning !== undefined)
42
+ out.reasoning = Math.min(out.output, op(a.reasoning ?? 0, b?.reasoning ?? 0));
43
+ return out;
44
+ };
45
+ const plus = (a, b) => combine(a, b, (x, y) => x + y);
46
+ const none = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
47
+ const less = (a, b) => combine(a, b, (x, y) => Math.max(0, x - y));
48
+ const most = (a, b) => combine(a, b, Math.max);
49
+ /** `turn` read by the event `id` too (Turn.uuids). */
50
+ const mark = (turn, id) => {
51
+ if (id && !turn.uuids?.includes(id))
52
+ turn.uuids = [...(turn.uuids ?? []), id];
53
+ };
54
+ /** Whether a user message is the person's: not a subagent's prompt, nor one the CLI or an agent wrote in the user role
55
+ * (autopilot's continuation, a skill's injection, an inter-agent prompt). */
56
+ const persons = (value, data) => value.agentId === undefined && data.isAutopilotContinuation !== true && data.agentAuthored !== true && !/^(?:agent|skill)-/.test(str(data.source) ?? "");
57
+ /** A shutdown's tokens, on its process's requests, each request it fed read by its event `id` too. A `copy` (its event
58
+ * read already, in another file) adds none: it only moves what this file has counted, so that a later shutdown holding
59
+ * the whole total adds only its own. One that fed none adds nothing when read again (its zeros, or no more than this
60
+ * file has counted): its id is kept nowhere. */
61
+ function shutdown(data, at, id, { state, add }, copy = false) {
62
+ const { own } = state;
63
+ if (data.shutdownType === "error" && !copy)
64
+ state.session.state = "failed";
65
+ // The session's whole total, where the CLI kept its accounting across processes; else this process's alone.
66
+ const whole = own.durable || "usageAccountingWatermarks" in data || "accountingSnapshot" in data || "providerModelMetrics" in data;
67
+ const metrics = isObject(data.modelMetrics) ? data.modelMetrics : {};
68
+ for (const [name, entry] of Object.entries(metrics)) {
69
+ const total = isObject(entry) ? normalizeUsage("copilot", entry.usage) : undefined;
70
+ if (!total || !name)
71
+ continue;
72
+ const before = own.counted.get(name);
73
+ const usage = whole ? less(total, before) : total;
74
+ own.counted.set(name, whole ? most(total, before) : plus(total, before));
75
+ if (copy || BUCKETS.every((k) => usage[k] === 0))
76
+ continue;
77
+ const model = modelOf(name);
78
+ let index = own.segment.findLast((i) => state.answers[i].model === model);
79
+ if (index === undefined) {
80
+ add({ role: "assistant", text: "", calls: [], at, model });
81
+ own.segment.push((index = state.answers.length - 1));
82
+ }
83
+ const turn = state.answers[index];
84
+ turn.usage = turn.usage ? plus(turn.usage, usage) : usage;
85
+ delete turn.folded;
86
+ mark(turn, id);
87
+ // The model's other requests in this process: their tokens are in the carrier's, so theirs are known zeros.
88
+ for (const i of own.segment) {
89
+ const other = state.answers[i];
90
+ if (i !== index && other.model === model && !other.usage)
91
+ Object.assign(other, { usage: none(), folded: true });
92
+ }
93
+ }
94
+ }
95
+ function record(value, at, context) {
96
+ const { state, seen, keep, add } = context;
97
+ const { session, names, own } = state;
98
+ const data = isObject(value.data) ? value.data : {};
99
+ const type = value.type;
100
+ // What the session is, from any record, a checkpoint's copy too.
101
+ if (type === "session.start" || type === "session.resume") {
102
+ if (type === "session.start" && str(data.sessionId))
103
+ session.id = data.sessionId;
104
+ const cwd = isObject(data.context) ? str(data.context.cwd) : undefined;
105
+ if (cwd && !session.cwd)
106
+ session.cwd = cwd;
107
+ if (str(data.selectedModel))
108
+ session.model = modelOf(data.selectedModel);
109
+ state.effort = effortOf(data.reasoningEffort) ?? state.effort;
110
+ // A run the CLI started on another session's exit: its usage is that session's.
111
+ const parent = type === "session.start" ? str(data.detachedFromSpawningParentSessionId) : undefined;
112
+ if (parent)
113
+ Object.assign(session, { child: true, parent });
114
+ }
115
+ else if (type === "session.model_change") {
116
+ if (str(data.newModel))
117
+ session.model = modelOf(data.newModel);
118
+ if (data.reasoningEffort !== undefined)
119
+ state.effort = effortOf(data.reasoningEffort);
120
+ }
121
+ else if (type === "session.usage_checkpoint")
122
+ own.durable = true;
123
+ if (value.checkpoint === true)
124
+ return false;
125
+ const id = str(value.id);
126
+ if (id) {
127
+ if (seen.has(`u:${id}`)) {
128
+ if (type === "session.shutdown")
129
+ shutdown(data, at, id, context, true);
130
+ return false;
131
+ }
132
+ seen.add(`u:${id}`);
133
+ }
134
+ if (type === "session.start" || type === "session.resume") {
135
+ own.segment = [];
136
+ own.open = own.call = undefined;
137
+ }
138
+ else if (type === "user.message") {
139
+ const text = typeof data.content === "string" ? data.content : "";
140
+ const ids = id ? { uuids: [id] } : {};
141
+ if (persons(value, data))
142
+ add({ role: "user", text, at, ...ids });
143
+ else if (keep)
144
+ add({ role: "note", author: "copilot", text, at, ...ids });
145
+ }
146
+ else if (type === "assistant.message") {
147
+ const requests = Array.isArray(data.toolRequests) ? data.toolRequests.filter(isObject) : [];
148
+ const calls = requests.map((call) => {
149
+ const callId = String(call.toolCallId ?? "");
150
+ names.set(callId, String(call.name ?? ""));
151
+ return { type: "toolCall", id: callId, name: String(call.name ?? ""), arguments: keep ? argsOf(call.arguments) : {} };
152
+ });
153
+ const text = keep && typeof data.content === "string" ? data.content : "";
154
+ // Each message once, a chunk of a split response too (each chunk is a message with its own messageId).
155
+ const key = str(data.messageId);
156
+ if (key) {
157
+ if (seen.has(`m:${key}`))
158
+ return false;
159
+ seen.add(`m:${key}`);
160
+ }
161
+ // A later chunk of one model call's response (the same apiCallId, where it names one): the same request.
162
+ const apiCall = str(data.apiCallId);
163
+ const chunk = typeof data.chunkIndex === "number" && data.chunkIndex > 0;
164
+ const joined = chunk && own.open !== undefined && (!apiCall || !own.call || apiCall === own.call) ? state.answers[own.open] : undefined;
165
+ if (joined) {
166
+ if (text)
167
+ joined.text = [joined.text, text].filter(Boolean).join("\n");
168
+ joined.calls.push(...calls);
169
+ mark(joined, id);
170
+ if (key)
171
+ joined.keys = [...(joined.keys ?? []), key];
172
+ return;
173
+ }
174
+ const model = str(data.model) ? modelOf(data.model) : session.model;
175
+ // The session's model is its main agent's: a subagent's runs under it.
176
+ if (model && value.agentId === undefined)
177
+ session.model = model;
178
+ session.state = "completed";
179
+ const turn = { role: "assistant", text, calls, at, ...(id ? { uuids: [id] } : {}), ...(key ? { key } : {}), ...(model ? { model } : {}), ...(state.effort ? { effort: state.effort } : {}) };
180
+ add(turn);
181
+ own.open = state.answers.length - 1;
182
+ own.call = apiCall;
183
+ own.segment.push(own.open);
184
+ }
185
+ else if (type === "tool.execution_start") {
186
+ if (str(data.toolCallId) && str(data.toolName))
187
+ names.set(data.toolCallId, data.toolName);
188
+ }
189
+ else if (type === "tool.execution_complete") {
190
+ const callId = String(data.toolCallId ?? "");
191
+ const output = isObject(data.result) && typeof data.result.content === "string" ? data.result.content : isObject(data.error) ? (str(data.error.message) ?? "") : "";
192
+ // Without turns, no output text: the result is kept for whether it failed, in the result and the cursor alike.
193
+ add({ role: "toolResult", callId, name: names.get(callId) ?? "", text: keep ? output : "", isError: data.success === false, at, ...(id ? { uuids: [id] } : {}) });
194
+ }
195
+ else if (type === "abort")
196
+ session.state = "stopped";
197
+ else if (type === "session.error")
198
+ session.state = "failed";
199
+ else if (type === "session.shutdown")
200
+ shutdown(data, at, id, context);
201
+ }
202
+ /** A Copilot session file's id from its path: its folder's name (session-state/<id>/events.jsonl), else the older
203
+ * flat file's name (session-state/<id>.jsonl). A session.start's sessionId, where there is one, wins over it. */
204
+ export const copilotSessionId = (file) => (basename(file) === "events.jsonl" ? basename(dirname(file)) : basename(file, ".jsonl"));
205
+ const spec = {
206
+ source: "copilot",
207
+ name: "Copilot CLI",
208
+ harness: "pi",
209
+ async files(home, env) {
210
+ const root = join(env?.COPILOT_HOME || join(home, ".copilot"), "session-state");
211
+ const out = [];
212
+ for (const entry of await entries(root)) {
213
+ if (entry.isDirectory())
214
+ out.push(join(root, entry.name, "events.jsonl"));
215
+ else if (entry.isFile() && entry.name.endsWith(".jsonl"))
216
+ out.push(join(root, entry.name));
217
+ }
218
+ return out;
219
+ },
220
+ start: () => ({ segment: [], counted: new Map(), durable: false }),
221
+ record,
222
+ idOf: copilotSessionId,
223
+ };
224
+ export const copilot = lineReader(spec);
@@ -3,6 +3,8 @@ export declare const READERS: {
3
3
  readonly "claude-code": Reader<"claude-code", import("../lines.js").FileCursor>;
4
4
  readonly codex: Reader<"codex", import("../lines.js").FileCursor>;
5
5
  readonly pi: Reader<"pi", import("../lines.js").FileCursor>;
6
+ readonly opencode: Reader<"opencode", import("./opencode.js").OpenCodeCursor>;
7
+ readonly copilot: Reader<"copilot", import("../lines.js").FileCursor>;
6
8
  };
7
9
  export type Source = keyof typeof READERS;
8
10
  export declare const SOURCES: Source[];
@@ -1,10 +1,14 @@
1
1
  import { claudeCode } from "./claude-code.js";
2
2
  import { codex } from "./codex.js";
3
+ import { opencode } from "./opencode.js";
4
+ import { copilot } from "./copilot.js";
3
5
  import { pi } from "./pi.js";
4
6
  export const READERS = {
5
7
  "claude-code": claudeCode,
6
8
  codex,
7
9
  pi,
10
+ opencode,
11
+ copilot,
8
12
  };
9
13
  export const SOURCES = Object.keys(READERS);
10
14
  /** The harness of serve that runs what each source ran. */
@@ -0,0 +1,42 @@
1
+ import { type Env, type Reader, type SessionRead } from "../reader.js";
2
+ import { FAILED } from "../text.js";
3
+ export { FAILED };
4
+ type Row = Record<string, unknown>;
5
+ type Found = SessionRead<"opencode">;
6
+ /** Where a read of one locator stopped: plain data, so structuredClone or v8.serialize keeps it whole. */
7
+ export type OpenCodeCursor = {
8
+ source: "opencode";
9
+ dev: number;
10
+ ino: number;
11
+ keep: boolean;
12
+ /** The rows (or files) the read was of, as counts and times: one that differs has changed since. */
13
+ stamp: string;
14
+ sessions: Found[];
15
+ /** The fingerprints the read added to `seen` (hashes, no text): a changed session read again whole finds its own
16
+ * there, which are no copies. */
17
+ owned: string[];
18
+ };
19
+ /** An open database, read-only; `read` the bytes of the `data` the queries have returned so far; `exec` a statement
20
+ * that returns no rows (BEGIN, COMMIT). */
21
+ type Db = {
22
+ all(sql: string, ...params: (string | number)[]): Row[];
23
+ exec(sql: string): void;
24
+ close(): void;
25
+ read(): number;
26
+ };
27
+ /** `use` of `file` open (openDb), then closed, every query of it in one read transaction: with OpenCode writing to it
28
+ * (its -wal there), each one reads the database as the first one did, never a message without the parts OpenCode wrote
29
+ * with it. Opened immutable, the read assumed nothing changed: one OpenCode opened or wrote meanwhile (its -wal or -shm
30
+ * there now, or the file's size, time or inode another) fails, never a clean read: the import names it and reads it
31
+ * again next time. */
32
+ export declare function withDb<T>(file: string, use: (db: Db) => T): Promise<T>;
33
+ /** OpenCode's databases and JSON storage under `home`, as OpenCode finds them in `env`: its data folder
34
+ * $XDG_DATA_HOME/opencode (~/.local/share/opencode without it), opencode.db and each channel's opencode-<channel>.db in
35
+ * it; and first the database OPENCODE_DB names, a path as given or one relative to the data folder. OpenCode opens
36
+ * only that one; the ones it wrote before are still the person's history. Never through a link; a database's -wal and
37
+ * -shm files are its own. No env is none: the home's folder. */
38
+ export declare function openCodeFiles(home: string, env?: Env): Promise<{
39
+ dbs: string[];
40
+ storage?: string;
41
+ }>;
42
+ export declare const opencode: Reader<"opencode", OpenCodeCursor>;