@kitman-sh/cli 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/{chunk-fjdp3rd6.js → chunk-1zb8h7gv.js} +45 -32
  2. package/dist/{chunk-r2kzvdrg.js → chunk-4qjfn1sa.js} +1 -1
  3. package/dist/{chunk-m1qp6swh.js → chunk-5kqt4bqp.js} +1 -1
  4. package/dist/{chunk-z59pvcbk.js → chunk-8fyfsajs.js} +179 -31
  5. package/dist/{chunk-vh2a72d1.js → chunk-9nbqzdqp.js} +60 -14
  6. package/dist/{chunk-emw9ragp.js → chunk-9tyv6211.js} +21 -21
  7. package/dist/{chunk-vwynec02.js → chunk-a9ncx2a8.js} +1 -1
  8. package/dist/{chunk-yjc2w86k.js → chunk-ak1qrm4q.js} +7 -7
  9. package/dist/{chunk-9vqkjkya.js → chunk-bnhb3cth.js} +2 -2
  10. package/dist/{chunk-2sazk478.js → chunk-gnq1ryhx.js} +8 -4
  11. package/dist/{chunk-y64ssczv.js → chunk-h2f26xbd.js} +40 -226
  12. package/dist/{chunk-s4r49vbj.js → chunk-hgxhpj6m.js} +4 -4
  13. package/dist/{chunk-qb11yda6.js → chunk-jrwpte6y.js} +41 -41
  14. package/dist/{chunk-qbrkeg49.js → chunk-mhx0tgm3.js} +7 -7
  15. package/dist/{chunk-5qrjf4xq.js → chunk-np5n54ky.js} +6 -6
  16. package/dist/{chunk-xxcxramy.js → chunk-nwbry6c8.js} +130 -124
  17. package/dist/{chunk-nndgeync.js → chunk-py3133q0.js} +6 -6
  18. package/dist/{chunk-nk0ew12p.js → chunk-racse7zf.js} +449 -37
  19. package/dist/chunk-s34am3kw.js +399 -0
  20. package/dist/{chunk-9a6wbk11.js → chunk-samxkpbz.js} +3 -3
  21. package/dist/{chunk-njgay1ed.js → chunk-sgkgwzvb.js} +6 -6
  22. package/dist/{chunk-pd3azxev.js → chunk-tsx0347c.js} +1 -1
  23. package/dist/{chunk-zy21drtv.js → chunk-vz38kngm.js} +2 -2
  24. package/dist/{chunk-qjxgew0k.js → chunk-x29m7k25.js} +2 -2
  25. package/dist/{chunk-9yvknsnj.js → chunk-xkkyx7bn.js} +3 -3
  26. package/dist/{chunk-38drrdzp.js → chunk-yveqd8ye.js} +4 -4
  27. package/dist/index.js +4 -4
  28. package/package.json +1 -1
  29. package/dist/chunk-kx8rpa62.js +0 -230
@@ -1,230 +0,0 @@
1
- // @bun
2
- import {
3
- getOrUndefined,
4
- liftThrowable,
5
- TaggedError,
6
- all3,
7
- suspend3,
8
- void_3,
9
- gen,
10
- fail7,
11
- try_2,
12
- mapError2,
13
- timeoutOrElse,
14
- scoped,
15
- declare,
16
- decodeEffect,
17
- String4,
18
- Boolean2,
19
- Struct,
20
- ArraySchema,
21
- Literals,
22
- NullOr,
23
- Finite,
24
- isNumber2,
25
- isJsonObject,
26
- isString2,
27
- encodeUnknownJsonStringSync
28
- } from "./chunk-y64ssczv.js";
29
- import {
30
- make10,
31
- runForEach,
32
- compiled2
33
- } from "./chunk-z59pvcbk.js";
34
- import {
35
- ChildProcessSpawner,
36
- make2
37
- } from "./chunk-vh2a72d1.js";
38
-
39
- // packages/agent-runtime/src/opencode-store.ts
40
- import { lstatSync, readFileSync, realpathSync } from "fs";
41
- import { DatabaseSync } from "node:sqlite";
42
- import { fileURLToPath } from "url";
43
- class OpencodeReadFailed extends TaggedError("OpencodeReadFailed") {
44
- get message() {
45
- return `OpenCode's session could not be read: ${this.reason}`;
46
- }
47
- }
48
- var sliceBytes2 = 1024 * 1024;
49
- var maxLineBytes2 = 8 * 1024 * 1024;
50
- var linesPerTurn2 = 1024;
51
- var decodedOption2 = liftThrowable((text) => JSON.parse(text));
52
- var decoded2 = (text) => getOrUndefined(decodedOption2(text));
53
- var Parsed = declare((_value) => true);
54
- var OpencodeV2PartSchema = Struct({ ordinal: Finite, part: Parsed });
55
- var OpencodeV2MessageSchema = Struct({
56
- id: String4,
57
- seq: Finite,
58
- closed: Boolean2,
59
- parts: NullOr(ArraySchema(OpencodeV2PartSchema))
60
- });
61
- var PartSchema = Struct({
62
- id: String4,
63
- position: Finite,
64
- role: NullOr(String4),
65
- part: Parsed
66
- });
67
- var maxRoleChars = 64;
68
- var maxPartsPerMessage = 4096;
69
- var bytesOf = (column) => `length(cast(${column} as blob))`;
70
- var unlessLong = (column) => `case when ${bytesOf(column)} <= ${maxLineBytes2} then ${column} end`;
71
- var decodedParts = (db, ids) => {
72
- const statement = db.prepare(`select part.rowid as position, ${unlessLong("message.data")} as message, ${unlessLong("part.data")} as part from part join message on message.id = part.message_id where part.id = ?`);
73
- const parts = [];
74
- let bytes = 0;
75
- let reached = 0;
76
- while (reached < ids.length && bytes < sliceBytes2) {
77
- const id = ids[reached++];
78
- const row = id === undefined ? undefined : statement.get(id);
79
- if (id !== undefined && isNumber2(row?.position)) {
80
- const message = isString2(row.message) ? decoded2(row.message) : undefined;
81
- const part = isString2(row.part) ? decoded2(row.part) : undefined;
82
- bytes += isString2(row.part) ? row.part.length : 0;
83
- const role = isJsonObject(message) ? message.role : undefined;
84
- const shortRole = isString2(role) && role.length <= maxRoleChars ? role : null;
85
- parts.push({ id, position: row.position, role: shortRole, part: part ?? null });
86
- }
87
- }
88
- return { parts, rest: ids.slice(reached) };
89
- };
90
- var partsPast = "from part join message on message.id = part.message_id where part.session_id = ? and part.rowid > ?";
91
- var opencodeV2Parts = (db, hasPartTable, id, data) => {
92
- const rows = hasPartTable ? db.prepare("select ordinal, data from session_part where message_id = ? order by ordinal").all(id) : [];
93
- if (rows.length > 0)
94
- return rows.flatMap((row) => isNumber2(row.ordinal) && isString2(row.data) ? [{ ordinal: row.ordinal, part: decoded2(row.data) ?? null }] : []);
95
- const content = isJsonObject(data) ? data.content : undefined;
96
- return Array.isArray(content) ? content.map((part, ordinal) => ({ ordinal, part })) : [];
97
- };
98
- var opencodeSessionTables = [
99
- { table: "session_v2", kind: "opencode_v2" },
100
- { table: "session", kind: "opencode" }
101
- ];
102
- var reading = (output, read) => ({
103
- output,
104
- read
105
- });
106
- var readings = {
107
- newestSession: reading(NullOr(Struct({ kind: Literals(["opencode", "opencode_v2"]), id: String4, createdAt: Finite })), (db, { worktree, startedAt }) => {
108
- const present = new Set(db.prepare("select name from sqlite_master where type = 'table'").all().map((row) => row.name));
109
- const newest = opencodeSessionTables.filter(({ table }) => present.has(table)).flatMap(({ table, kind }) => {
110
- const row = db.prepare(`select id, time_created from ${table} where directory = ? and parent_id is null and time_created >= ? order by time_created desc limit 1`).get(worktree, startedAt);
111
- return isString2(row?.id) && isNumber2(row.time_created) ? [{ kind, id: row.id, createdAt: row.time_created }] : [];
112
- });
113
- return newest.reduce((best, session) => best === null || session.createdAt > best.createdAt ? session : best, null);
114
- }),
115
- parts: reading(Struct({ parts: ArraySchema(PartSchema), rest: ArraySchema(String4) }), (db, { ids }) => decodedParts(db, ids)),
116
- partsPast: reading(ArraySchema(PartSchema), (db, { position }, sessionId) => {
117
- const rows = db.prepare(`select part.id as id ${partsPast} order by part.rowid limit ?`).all(sessionId, position, linesPerTurn2);
118
- return decodedParts(db, rows.flatMap((row) => isString2(row.id) ? [row.id] : [])).parts;
119
- }),
120
- partsPastCount: reading(Finite, (db, { position }, sessionId) => Number(db.prepare(`select count(*) as parts ${partsPast}`).get(sessionId, position)?.parts)),
121
- messagesPast: reading(ArraySchema(OpencodeV2MessageSchema), (db, { seq }, sessionId) => {
122
- const hasPartTable = db.prepare("select 1 from sqlite_master where name = 'session_part'").get() !== undefined;
123
- const size = hasPartTable ? `${bytesOf("data")} + coalesce((select sum(${bytesOf("data")}) from session_part where message_id = session_message.id), 0)` : bytesOf("data");
124
- const found = db.prepare(`select id, seq, ${size} as size, json_extract(data, '$.time.completed') is not null as completed from session_message where session_id = ? and type = 'assistant' and seq > ? order by seq limit ?`).all(sessionId, seq, linesPerTurn2 + 1);
125
- const read = db.prepare("select data from session_message where id = ?");
126
- const messages = [];
127
- let bytes = 0;
128
- for (const [index, row] of found.slice(0, linesPerTurn2).entries()) {
129
- if (bytes >= sliceBytes2)
130
- break;
131
- if (!isString2(row.id) || !isNumber2(row.seq) || !isNumber2(row.size))
132
- continue;
133
- const closed = row.completed === 1 || index < found.length - 1;
134
- if (row.size > maxLineBytes2) {
135
- messages.push({ id: row.id, seq: row.seq, closed, parts: null });
136
- continue;
137
- }
138
- const data = read.get(row.id)?.data;
139
- bytes += row.size;
140
- const parts = opencodeV2Parts(db, hasPartTable, row.id, isString2(data) ? decoded2(data) : undefined);
141
- messages.push({ id: row.id, seq: row.seq, closed, parts: parts.length > maxPartsPerMessage ? null : parts });
142
- }
143
- return messages;
144
- }),
145
- lastError: reading(Parsed, (db, { v2 }, sessionId) => {
146
- const error = unlessLong("json_extract(data, '$.error')");
147
- const row = v2 ? db.prepare(`select ${error} as error from session_message where session_id = ? and type = 'assistant' order by seq desc limit 1`).get(sessionId) : db.prepare(`select ${error} as error from message where session_id = ? and json_extract(data, '$.role') = 'assistant' order by time_created desc, rowid desc limit 1`).get(sessionId);
148
- return isString2(row?.error) ? decoded2(row.error) ?? null : null;
149
- }),
150
- lastModel: reading(NullOr(String4), (db, { v2 }, sessionId) => {
151
- const named = (provider, model) => `case when length(cast(${model} as blob)) <= 200 and length(cast(coalesce(${provider}, '') as blob)) <= 200 then case when ${provider} is null then ${model} else ${provider} || '/' || ${model} end end`;
152
- const row = v2 ? db.prepare(`select ${named("json_extract(data, '$.model.providerID')", "json_extract(data, '$.model.id')")} as model from session_message where session_id = ? and type = 'assistant' and json_type(data, '$.model.id') = 'text' order by seq desc limit 1`).get(sessionId) : db.prepare(`select ${named("json_extract(data, '$.providerID')", "json_extract(data, '$.modelID')")} as model from message where session_id = ? and json_extract(data, '$.role') = 'assistant' and json_type(data, '$.modelID') = 'text' order by time_created desc, rowid desc limit 1`).get(sessionId);
153
- return isString2(row?.model) ? row.model : null;
154
- }),
155
- extent: reading(Finite, (db, _input, sessionId) => Number(db.prepare(`with recursive sessions(id) as (select ? union select session_v2.id from session_v2 join sessions on session_v2.parent_id = sessions.id)
156
- select coalesce(max(time_updated), 0) as extent from session_message where session_id in sessions`).get(sessionId)?.extent))
157
- };
158
- var maxReaderHeapBytes = 256 * 1024 * 1024;
159
- var inDatabase = (database, hostile, use) => {
160
- const db = new DatabaseSync(database, { readOnly: true });
161
- try {
162
- if (hostile)
163
- db.exec(`pragma trusted_schema = off; pragma query_only = on; pragma hard_heap_limit = ${maxReaderHeapBytes};`);
164
- return use(db);
165
- } finally {
166
- db.close();
167
- }
168
- };
169
- var maxAnswerBytes = 16 * 1024 * 1024;
170
- var answerTimeout = "3 seconds";
171
- var opencodeReaderCommand = () => compiled2 ? [process.execPath, "opencode-read"] : [process.execPath, fileURLToPath(import.meta.resolve("./opencode-reader.main.ts"))];
172
- var isolatedRead = (store, name, input) => gen(function* () {
173
- const spawner = yield* ChildProcessSpawner;
174
- const [command, ...args] = opencodeReaderCommand();
175
- const handle = yield* spawner.spawn(make2(command, args, {
176
- stdin: make10(new TextEncoder().encode(encodeUnknownJsonStringSync({ store, name, input }))),
177
- stderr: "ignore",
178
- extendEnv: false,
179
- env: {},
180
- killSignal: "SIGKILL"
181
- }));
182
- const chunks = [];
183
- let bytes = 0;
184
- const [, exitCode] = yield* all3([
185
- runForEach(handle.stdout, (chunk) => suspend3(() => {
186
- bytes += chunk.length;
187
- chunks.push(chunk);
188
- return bytes > maxAnswerBytes ? fail7(new OpencodeReadFailed({ reason: "the reader said too much" })) : void_3;
189
- })),
190
- handle.exitCode
191
- ], { concurrency: 2 });
192
- if (exitCode !== 0)
193
- return yield* new OpencodeReadFailed({ reason: `the reader exited with ${exitCode}` });
194
- const answer = decoded2(new TextDecoder().decode(Buffer.concat(chunks)));
195
- return yield* decodeEffect(readings[name].output)(answer);
196
- }).pipe(scoped, mapError2((error) => error instanceof OpencodeReadFailed ? error : new OpencodeReadFailed({ reason: error.message })), timeoutOrElse({
197
- duration: answerTimeout,
198
- orElse: () => fail7(new OpencodeReadFailed({ reason: "the reader did not answer in time" }))
199
- }));
200
- var readOpencode2 = (store, name, input) => store.confinedTo === undefined ? try_2({
201
- try: () => answerFrom(store, name, input, false),
202
- catch: (error) => new OpencodeReadFailed({ reason: String(error) })
203
- }) : isolatedRead(store, name, input);
204
- var answerFrom = (store, name, input, hostile) => inDatabase(store.database, hostile, (db) => readings[name].read(db, input, store.sessionId ?? ""));
205
- var assertConfined = (database, root) => {
206
- for (const file of [database, `${database}-wal`, `${database}-shm`, `${database}-journal`]) {
207
- const stat = lstatSync(file, { throwIfNoEntry: false });
208
- if (file === database && stat === undefined)
209
- throw new Error("No database");
210
- if (stat !== undefined && (!stat.isFile() || stat.nlink !== 1))
211
- throw new Error("Not a plain file");
212
- }
213
- if (!realpathSync(database).startsWith(`${realpathSync(root)}/`))
214
- throw new Error("Outside its directory");
215
- };
216
- var runOpencodeReader2 = () => {
217
- const request = decoded2(readFileSync(0, "utf8"));
218
- if (!isJsonObject(request) || !isJsonObject(request.store))
219
- throw new Error("No request");
220
- const { database, sessionId, confinedTo } = request.store;
221
- if (!isString2(database) || !isString2(confinedTo))
222
- throw new Error("No confined database");
223
- assertConfined(database, confinedTo);
224
- const store = { database, confinedTo, ...isString2(sessionId) ? { sessionId } : undefined };
225
- const reading = request.name;
226
- const input = request.input;
227
- process.stdout.write(encodeUnknownJsonStringSync(answerFrom(store, reading, input, true)));
228
- };
229
-
230
- export { sliceBytes2, maxLineBytes2, linesPerTurn2, decodedOption2, decoded2, readOpencode2, runOpencodeReader2 };