@kitman-sh/cli 0.31.0 → 0.32.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-nndgeync.js → chunk-1an3xh3b.js} +6 -6
  2. package/dist/{chunk-pd3azxev.js → chunk-1hgsf81a.js} +1 -1
  3. package/dist/{chunk-qbrkeg49.js → chunk-3cneth9k.js} +4 -4
  4. package/dist/{chunk-9a6wbk11.js → chunk-4qrb09w4.js} +3 -3
  5. package/dist/{chunk-qb11yda6.js → chunk-4tzzmrz2.js} +9 -9
  6. package/dist/chunk-56gs4z53.js +399 -0
  7. package/dist/{chunk-emw9ragp.js → chunk-5hp8ams4.js} +20 -20
  8. package/dist/{chunk-y64ssczv.js → chunk-61dmxexa.js} +13 -157
  9. package/dist/{chunk-9vqkjkya.js → chunk-6e6t0f8y.js} +1 -1
  10. package/dist/{chunk-fjdp3rd6.js → chunk-a0bjjbhg.js} +20 -20
  11. package/dist/{chunk-9yvknsnj.js → chunk-abyssa8p.js} +3 -3
  12. package/dist/{chunk-njgay1ed.js → chunk-acmyagwp.js} +6 -6
  13. package/dist/{chunk-yjc2w86k.js → chunk-af8kftyw.js} +7 -7
  14. package/dist/{chunk-vwynec02.js → chunk-ah59jrtr.js} +1 -1
  15. package/dist/{chunk-s4r49vbj.js → chunk-awx0zevr.js} +4 -4
  16. package/dist/{chunk-2sazk478.js → chunk-c8eg05nh.js} +8 -4
  17. package/dist/{chunk-vh2a72d1.js → chunk-er0e8d8v.js} +2 -2
  18. package/dist/{chunk-xxcxramy.js → chunk-nb6h112w.js} +18 -13
  19. package/dist/{chunk-zy21drtv.js → chunk-q8e58p57.js} +2 -2
  20. package/dist/{chunk-qjxgew0k.js → chunk-qqb6djs7.js} +2 -2
  21. package/dist/{chunk-5qrjf4xq.js → chunk-r3mjxsmn.js} +4 -4
  22. package/dist/{chunk-r2kzvdrg.js → chunk-rbpn35g5.js} +1 -1
  23. package/dist/{chunk-38drrdzp.js → chunk-rnm5ybw4.js} +4 -4
  24. package/dist/{chunk-nk0ew12p.js → chunk-x4d4t28n.js} +108 -19
  25. package/dist/{chunk-z59pvcbk.js → chunk-z0gqrc8c.js} +169 -21
  26. package/dist/{chunk-m1qp6swh.js → chunk-znhjs0t6.js} +1 -1
  27. package/dist/index.js +4 -4
  28. package/package.json +1 -1
  29. package/dist/chunk-kx8rpa62.js +0 -230
@@ -4,12 +4,12 @@ import {
4
4
  runnerRpcUrl2,
5
5
  makeRunnerRpcClient2,
6
6
  makeProgramRpcClient2
7
- } from "./chunk-qbrkeg49.js";
8
- import"./chunk-5qrjf4xq.js";
9
- import"./chunk-xxcxramy.js";
10
- import"./chunk-r2kzvdrg.js";
11
- import"./chunk-z59pvcbk.js";
12
- import"./chunk-y64ssczv.js";
7
+ } from "./chunk-3cneth9k.js";
8
+ import"./chunk-r3mjxsmn.js";
9
+ import"./chunk-nb6h112w.js";
10
+ import"./chunk-rbpn35g5.js";
11
+ import"./chunk-z0gqrc8c.js";
12
+ import"./chunk-61dmxexa.js";
13
13
  export {
14
14
  makeProgramRpcClient2 as makeProgramRpcClient,
15
15
  makeRunnerRpcClient2 as makeRunnerRpcClient,
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  isString2
4
- } from "./chunk-y64ssczv.js";
4
+ } from "./chunk-61dmxexa.js";
5
5
 
6
6
  // packages/core/src/question-recommendation.ts
7
7
  var optionValue = (option) => isString2(option) ? option : option.value;
@@ -6,10 +6,10 @@ import {
6
6
  gen,
7
7
  flatMap3,
8
8
  provideContext2
9
- } from "./chunk-y64ssczv.js";
9
+ } from "./chunk-61dmxexa.js";
10
10
  import {
11
11
  runForEach
12
- } from "./chunk-z59pvcbk.js";
12
+ } from "./chunk-z0gqrc8c.js";
13
13
  import {
14
14
  WebSocketConstructor,
15
15
  layerWebSocketConstructorGlobal,
@@ -19,13 +19,13 @@ import {
19
19
  RunnerReplicaRpcs,
20
20
  RunnerRunFileRpcs,
21
21
  ProgramRpcs
22
- } from "./chunk-xxcxramy.js";
22
+ } from "./chunk-nb6h112w.js";
23
23
  import {
24
24
  layerJson,
25
25
  make3,
26
26
  withHeaders,
27
27
  layerProtocolSocket
28
- } from "./chunk-5qrjf4xq.js";
28
+ } from "./chunk-r3mjxsmn.js";
29
29
 
30
30
  // packages/live/src/rpc/runner-client.ts
31
31
  var proxiedWebSocket = (proxy) => succeed5(WebSocketConstructor)((target) => {
@@ -4,9 +4,9 @@ import {
4
4
  opaqueTunnelRefusal2,
5
5
  isOpaqueConnectReason2,
6
6
  runSrtStep2
7
- } from "./chunk-zy21drtv.js";
8
- import"./chunk-r2kzvdrg.js";
9
- import"./chunk-y64ssczv.js";
7
+ } from "./chunk-q8e58p57.js";
8
+ import"./chunk-rbpn35g5.js";
9
+ import"./chunk-61dmxexa.js";
10
10
  export {
11
11
  isOpaqueConnectReason2 as isOpaqueConnectReason,
12
12
  opaqueTunnelRefusal2 as opaqueTunnelRefusal,
@@ -118,9 +118,8 @@ import {
118
118
  decodeJsonStringOption,
119
119
  encodeJsonStringSync,
120
120
  encodePrettyJsonString
121
- } from "./chunk-y64ssczv.js";
121
+ } from "./chunk-61dmxexa.js";
122
122
  import {
123
- currentTimeMillis,
124
123
  SecureRandom,
125
124
  makeUnsafe,
126
125
  formatIso,
@@ -170,8 +169,9 @@ import {
170
169
  runMcpEffect,
171
170
  createAgentAuthSignedFetch,
172
171
  setupMcpAgentCredential
173
- } from "./chunk-xxcxramy.js";
172
+ } from "./chunk-nb6h112w.js";
174
173
  import {
174
+ currentTimeMillis,
175
175
  join,
176
176
  interrupt,
177
177
  empty2,
@@ -187,30 +187,30 @@ import {
187
187
  withDefault,
188
188
  option,
189
189
  String2
190
- } from "./chunk-z59pvcbk.js";
190
+ } from "./chunk-z0gqrc8c.js";
191
191
  import {
192
192
  searchDocs2,
193
193
  readDoc2
194
- } from "./chunk-9vqkjkya.js";
194
+ } from "./chunk-6e6t0f8y.js";
195
195
  import {
196
196
  nextInt
197
- } from "./chunk-m1qp6swh.js";
197
+ } from "./chunk-znhjs0t6.js";
198
198
  import {
199
199
  recommendationProblem
200
- } from "./chunk-pd3azxev.js";
200
+ } from "./chunk-1hgsf81a.js";
201
201
  import {
202
202
  layerJson,
203
203
  make3,
204
204
  withHeaders,
205
205
  layerProtocolSocket,
206
206
  ConnectionHooks
207
- } from "./chunk-5qrjf4xq.js";
207
+ } from "./chunk-r3mjxsmn.js";
208
208
  import {
209
209
  guard,
210
210
  Id,
211
211
  Timestamp,
212
212
  ActorType
213
- } from "./chunk-r2kzvdrg.js";
213
+ } from "./chunk-rbpn35g5.js";
214
214
 
215
215
  // apps/cli/src/mcp.ts
216
216
  import { tmpdir as tmpdir2 } from "os";
@@ -0,0 +1,399 @@
1
+ // @bun
2
+ import {
3
+ isSome,
4
+ getOrElse,
5
+ getOrUndefined,
6
+ liftThrowable,
7
+ flatMap,
8
+ TaggedError,
9
+ catchDone,
10
+ all3,
11
+ forEach,
12
+ suspend3,
13
+ void_3,
14
+ undefined_,
15
+ gen,
16
+ fail7,
17
+ try_2,
18
+ option2,
19
+ mapError2,
20
+ timeoutOrElse,
21
+ sleep,
22
+ scoped,
23
+ declare,
24
+ decodeEffect,
25
+ Literal,
26
+ String4,
27
+ Boolean2,
28
+ Struct,
29
+ ArraySchema,
30
+ Union,
31
+ Literals,
32
+ NullOr,
33
+ Finite,
34
+ isNumber2,
35
+ isJsonObject,
36
+ isString2,
37
+ encodeUnknownJsonStringSync
38
+ } from "./chunk-61dmxexa.js";
39
+ import {
40
+ currentTimeMillis,
41
+ make10,
42
+ runForEach,
43
+ toPull,
44
+ FileSystem,
45
+ compiled2
46
+ } from "./chunk-z0gqrc8c.js";
47
+ import {
48
+ ChildProcessSpawner,
49
+ make2
50
+ } from "./chunk-er0e8d8v.js";
51
+
52
+ // packages/agent-runtime/src/opencode-store.ts
53
+ import { lstatSync, readFileSync, realpathSync, writeSync } from "fs";
54
+ import { DatabaseSync } from "node:sqlite";
55
+ import { fileURLToPath } from "url";
56
+ class OpencodeReadFailed extends TaggedError("OpencodeReadFailed") {
57
+ get message() {
58
+ return `OpenCode's session could not be read: ${this.reason}`;
59
+ }
60
+ }
61
+ var sliceBytes2 = 1024 * 1024;
62
+ var maxLineBytes2 = 8 * 1024 * 1024;
63
+ var linesPerTurn2 = 1024;
64
+ var decodedOption2 = liftThrowable((text) => JSON.parse(text));
65
+ var decoded2 = (text) => getOrUndefined(decodedOption2(text));
66
+ var Parsed = declare((_value) => true);
67
+ var OpencodeV2PartSchema = Struct({ ordinal: Finite, part: Parsed });
68
+ var OpencodeV2MessageSchema = Struct({
69
+ id: String4,
70
+ seq: Finite,
71
+ closed: Boolean2,
72
+ parts: NullOr(ArraySchema(OpencodeV2PartSchema))
73
+ });
74
+ var PartSchema = Struct({
75
+ id: String4,
76
+ position: Finite,
77
+ role: NullOr(String4),
78
+ part: Parsed
79
+ });
80
+ var maxRoleChars = 64;
81
+ var maxPartsPerMessage = 4096;
82
+ var bytesOf = (column) => `length(cast(${column} as blob))`;
83
+ var unlessLong = (column) => `case when ${bytesOf(column)} <= ${maxLineBytes2} then ${column} end`;
84
+ var decodedParts = (db, ids) => {
85
+ 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 = ?`);
86
+ const parts = [];
87
+ let bytes = 0;
88
+ let reached = 0;
89
+ while (reached < ids.length && bytes < sliceBytes2) {
90
+ const id = ids[reached++];
91
+ const row = id === undefined ? undefined : statement.get(id);
92
+ if (id !== undefined && isNumber2(row?.position)) {
93
+ const message = isString2(row.message) ? decoded2(row.message) : undefined;
94
+ const part = isString2(row.part) ? decoded2(row.part) : undefined;
95
+ bytes += isString2(row.part) ? row.part.length : 0;
96
+ const role = isJsonObject(message) ? message.role : undefined;
97
+ const shortRole = isString2(role) && role.length <= maxRoleChars ? role : null;
98
+ parts.push({ id, position: row.position, role: shortRole, part: part ?? null });
99
+ }
100
+ }
101
+ return { parts, rest: ids.slice(reached) };
102
+ };
103
+ var partsPast = "from part join message on message.id = part.message_id where part.session_id = ? and part.rowid > ?";
104
+ var opencodeV2Parts = (db, hasPartTable, id, data) => {
105
+ const rows = hasPartTable ? db.prepare("select ordinal, data from session_part where message_id = ? order by ordinal").all(id) : [];
106
+ if (rows.length > 0)
107
+ return rows.flatMap((row) => isNumber2(row.ordinal) && isString2(row.data) ? [{ ordinal: row.ordinal, part: decoded2(row.data) ?? null }] : []);
108
+ const content = isJsonObject(data) ? data.content : undefined;
109
+ return Array.isArray(content) ? content.map((part, ordinal) => ({ ordinal, part })) : [];
110
+ };
111
+ var opencodeSessionTables = [
112
+ { table: "session_v2", kind: "opencode_v2" },
113
+ { table: "session", kind: "opencode" }
114
+ ];
115
+ var newestSessionOf = (db, worktree, startedAt) => {
116
+ const present = new Set(db.prepare("select name from sqlite_master where type = 'table'").all().map((row) => row.name));
117
+ const newest = opencodeSessionTables.filter(({ table }) => present.has(table)).flatMap(({ table, kind }) => {
118
+ 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);
119
+ return isString2(row?.id) && isNumber2(row.time_created) ? [{ kind, id: row.id, createdAt: row.time_created }] : [];
120
+ });
121
+ return newest.reduce((best, session) => best === null || session.createdAt > best.createdAt ? session : best, null);
122
+ };
123
+ var messagesPastOf = (db, seq, sessionId) => {
124
+ const hasPartTable = db.prepare("select 1 from sqlite_master where name = 'session_part'").get() !== undefined;
125
+ const size = hasPartTable ? `${bytesOf("data")} + coalesce((select sum(${bytesOf("data")}) from session_part where message_id = session_message.id), 0)` : bytesOf("data");
126
+ 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);
127
+ const read = db.prepare("select data from session_message where id = ?");
128
+ const messages = [];
129
+ let bytes = 0;
130
+ let reached = 0;
131
+ let next;
132
+ for (const [index, row] of found.slice(0, linesPerTurn2).entries()) {
133
+ if (bytes >= sliceBytes2)
134
+ break;
135
+ reached = index + 1;
136
+ if (!isString2(row.id) || !isNumber2(row.seq) || !isNumber2(row.size))
137
+ continue;
138
+ next = row.seq;
139
+ const closed = row.completed === 1 || index < found.length - 1;
140
+ if (row.size > maxLineBytes2) {
141
+ messages.push({ id: row.id, seq: row.seq, closed, parts: null });
142
+ continue;
143
+ }
144
+ const data = read.get(row.id)?.data;
145
+ bytes += row.size;
146
+ const parts = opencodeV2Parts(db, hasPartTable, row.id, isString2(data) ? decoded2(data) : undefined);
147
+ messages.push({ id: row.id, seq: row.seq, closed, parts: parts.length > maxPartsPerMessage ? null : parts });
148
+ }
149
+ return { messages, next: reached < found.length ? next : undefined };
150
+ };
151
+ var partsPastOf = (db, position, sessionId) => {
152
+ const found = db.prepare(`select part.rowid as position, part.id as id ${partsPast} order by part.rowid limit ?`).all(sessionId, position, linesPerTurn2 + 1);
153
+ const rows = found.slice(0, linesPerTurn2);
154
+ const listed = rows.flatMap((row) => isString2(row.id) && isNumber2(row.position) ? [{ id: row.id, position: row.position }] : []);
155
+ const { parts, rest } = decodedParts(db, listed.map(({ id }) => id));
156
+ const last = rest.length > 0 ? listed[listed.length - rest.length - 1] : rows.at(-1);
157
+ const more = rest.length > 0 || found.length > rows.length;
158
+ return { parts, next: more && isNumber2(last?.position) ? last.position : undefined };
159
+ };
160
+ var lastErrorOf = (db, v2, sessionId) => {
161
+ const error = unlessLong("json_extract(data, '$.error')");
162
+ 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);
163
+ return isString2(row?.error) ? decoded2(row.error) ?? null : null;
164
+ };
165
+ var lastModelOf = (db, v2, sessionId) => {
166
+ 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`;
167
+ 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);
168
+ return isString2(row?.model) ? row.model : null;
169
+ };
170
+ var extentOf = (db, 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)
171
+ select coalesce(max(time_updated), 0) as extent from session_message where session_id in sessions`).get(sessionId)?.extent);
172
+ var reading = (output, read) => ({
173
+ output,
174
+ read
175
+ });
176
+ var readings = {
177
+ newestSession: reading(NullOr(Struct({ kind: Literals(["opencode", "opencode_v2"]), id: String4, createdAt: Finite })), (db, { worktree, startedAt }) => newestSessionOf(db, worktree, startedAt)),
178
+ parts: reading(Struct({ parts: ArraySchema(PartSchema), rest: ArraySchema(String4) }), (db, { ids }) => decodedParts(db, ids)),
179
+ partsPast: reading(ArraySchema(PartSchema), (db, { position }, sessionId) => {
180
+ const rows = db.prepare(`select part.id as id ${partsPast} order by part.rowid limit ?`).all(sessionId, position, linesPerTurn2);
181
+ return decodedParts(db, rows.flatMap((row) => isString2(row.id) ? [row.id] : [])).parts;
182
+ }),
183
+ partsPastCount: reading(Finite, (db, { position }, sessionId) => Number(db.prepare(`select count(*) as parts ${partsPast}`).get(sessionId, position)?.parts)),
184
+ messagesPast: reading(ArraySchema(OpencodeV2MessageSchema), (db, { seq }, sessionId) => messagesPastOf(db, seq, sessionId).messages),
185
+ lastError: reading(Parsed, (db, { v2 }, sessionId) => lastErrorOf(db, v2, sessionId)),
186
+ lastModel: reading(NullOr(String4), (db, { v2 }, sessionId) => lastModelOf(db, v2, sessionId)),
187
+ extent: reading(Finite, (db, _input, sessionId) => extentOf(db, sessionId))
188
+ };
189
+ var SessionKindSchema = Literals(["opencode", "opencode_v2"]);
190
+ var FrameSchema = Union([
191
+ Struct({
192
+ kind: Literal("found"),
193
+ session: NullOr(Struct({ kind: SessionKindSchema, id: String4 }))
194
+ }),
195
+ Struct({ kind: Literal("extent"), extent: Finite }),
196
+ Struct({ kind: Literal("error"), error: Parsed }),
197
+ Struct({ kind: Literal("model"), model: NullOr(String4) }),
198
+ Struct({ kind: Literal("unsaid"), reason: String4 }),
199
+ Struct({ kind: Literal("messages"), messages: ArraySchema(OpencodeV2MessageSchema) }),
200
+ Struct({ kind: Literal("open"), parts: ArraySchema(PartSchema) }),
201
+ Struct({ kind: Literal("past"), parts: ArraySchema(PartSchema) })
202
+ ]);
203
+ var decodedFrame = decodeEffect(FrameSchema);
204
+ var unlessFailed = (frame) => {
205
+ try {
206
+ return frame();
207
+ } catch (error) {
208
+ return { kind: "unsaid", reason: String(error).slice(0, 500) };
209
+ }
210
+ };
211
+ function* saidOf(db, v2, sessionId) {
212
+ yield unlessFailed(() => ({ kind: "error", error: lastErrorOf(db, v2, sessionId) }));
213
+ yield unlessFailed(() => ({ kind: "model", model: lastModelOf(db, v2, sessionId) }));
214
+ }
215
+ function* framesOf(db, look, sessionId) {
216
+ let session = look.kind === undefined ? undefined : { kind: look.kind, id: sessionId };
217
+ if (look.find !== undefined) {
218
+ const found = newestSessionOf(db, look.find.worktree, look.find.startedAt);
219
+ session = found === null ? undefined : { kind: found.kind, id: found.id };
220
+ yield { kind: "found", session: session ?? null };
221
+ }
222
+ if (session === undefined)
223
+ return;
224
+ const { id } = session;
225
+ if (session.kind === "opencode_v2") {
226
+ const extent = extentOf(db, id);
227
+ yield { kind: "extent", extent };
228
+ if (extent !== look.saidAt)
229
+ yield* saidOf(db, true, id);
230
+ for (let seq = look.closedTo;seq !== undefined; ) {
231
+ const { messages, next } = messagesPastOf(db, seq, id);
232
+ if (messages.length > 0)
233
+ yield { kind: "messages", messages };
234
+ seq = next !== undefined && next > seq ? next : undefined;
235
+ }
236
+ return;
237
+ }
238
+ yield* saidOf(db, false, id);
239
+ for (let ids = look.open;ids.length > 0; ) {
240
+ const { parts, rest } = decodedParts(db, ids);
241
+ yield { kind: "open", parts };
242
+ ids = rest;
243
+ }
244
+ for (let position = look.recordedTo;position !== undefined; ) {
245
+ const { parts, next } = partsPastOf(db, position, id);
246
+ if (parts.length > 0)
247
+ yield { kind: "past", parts };
248
+ position = next !== undefined && next > position ? next : undefined;
249
+ }
250
+ }
251
+ var maxReaderHeapBytes = 256 * 1024 * 1024;
252
+ var inDatabase = (database, hostile, use) => {
253
+ const db = new DatabaseSync(database, { readOnly: true });
254
+ try {
255
+ if (hostile)
256
+ db.exec(`pragma trusted_schema = off; pragma query_only = on; pragma hard_heap_limit = ${maxReaderHeapBytes};`);
257
+ return use(db);
258
+ } finally {
259
+ db.close();
260
+ }
261
+ };
262
+ var maxAnswerBytes = 16 * 1024 * 1024;
263
+ var answerTimeout = "3 seconds";
264
+ var opencodeReaderCommand = () => compiled2 ? [process.execPath, "opencode-read"] : [process.execPath, fileURLToPath(import.meta.resolve("./opencode-reader.main.ts"))];
265
+ var spawnReader = (request) => gen(function* () {
266
+ const spawner = yield* ChildProcessSpawner;
267
+ const [command, ...args] = opencodeReaderCommand();
268
+ return yield* spawner.spawn(make2(command, args, {
269
+ stdin: make10(new TextEncoder().encode(request)),
270
+ stderr: "ignore",
271
+ extendEnv: false,
272
+ env: {},
273
+ killSignal: "SIGKILL"
274
+ }));
275
+ });
276
+ var readFailed = (error) => error instanceof OpencodeReadFailed ? error : new OpencodeReadFailed({ reason: error.message });
277
+ var notAnswered = () => fail7(new OpencodeReadFailed({ reason: "the reader did not answer in time" }));
278
+ var isolatedRead = (store, name, input) => gen(function* () {
279
+ const handle = yield* spawnReader(encodeUnknownJsonStringSync({ store, name, input }));
280
+ const chunks = [];
281
+ let bytes = 0;
282
+ const [, exitCode] = yield* all3([
283
+ runForEach(handle.stdout, (chunk) => suspend3(() => {
284
+ bytes += chunk.length;
285
+ chunks.push(chunk);
286
+ return bytes > maxAnswerBytes ? fail7(new OpencodeReadFailed({ reason: "the reader said too much" })) : void_3;
287
+ })),
288
+ handle.exitCode
289
+ ], { concurrency: 2 });
290
+ if (exitCode !== 0)
291
+ return yield* new OpencodeReadFailed({ reason: `the reader exited with ${exitCode}` });
292
+ const answer = decoded2(new TextDecoder().decode(Buffer.concat(chunks)));
293
+ return yield* decodeEffect(readings[name].output)(answer);
294
+ }).pipe(scoped, mapError2(readFailed), timeoutOrElse({ duration: answerTimeout, orElse: notAnswered }));
295
+ var newline = 10;
296
+ var lookAtOpencode2 = (store, look, onFrame) => gen(function* () {
297
+ const handle = yield* spawnReader(encodeUnknownJsonStringSync({ store, look }));
298
+ const pull = yield* toPull(handle.stdout);
299
+ const nextChunks = pull.pipe(catchDone(() => undefined_), timeoutOrElse({ duration: answerTimeout, orElse: notAnswered }));
300
+ let line = [];
301
+ let lineBytes = 0;
302
+ for (let chunks = yield* nextChunks;chunks !== undefined; chunks = yield* nextChunks)
303
+ for (const chunk of chunks)
304
+ for (let start = 0;start < chunk.length; ) {
305
+ const end = chunk.indexOf(newline, start);
306
+ const piece = chunk.subarray(start, end < 0 ? chunk.length : end);
307
+ lineBytes += piece.length;
308
+ if (lineBytes > maxAnswerBytes)
309
+ return yield* new OpencodeReadFailed({ reason: "the reader said too much" });
310
+ line.push(piece);
311
+ if (end < 0)
312
+ break;
313
+ start = end + 1;
314
+ const frame = decoded2(new TextDecoder().decode(Buffer.concat(line)));
315
+ line = [];
316
+ lineBytes = 0;
317
+ if (!(yield* onFrame(yield* decodedFrame(frame))))
318
+ return false;
319
+ }
320
+ const exitCode = yield* handle.exitCode.pipe(timeoutOrElse({ duration: answerTimeout, orElse: notAnswered }));
321
+ if (exitCode !== 0)
322
+ return yield* new OpencodeReadFailed({ reason: `the reader exited with ${exitCode}` });
323
+ if (lineBytes > 0)
324
+ return yield* new OpencodeReadFailed({ reason: "the reader stopped mid-line" });
325
+ return true;
326
+ }).pipe(scoped, mapError2(readFailed));
327
+ var readOpencode2 = (store, name, input) => store.confinedTo === undefined ? try_2({
328
+ try: () => answerFrom(store, name, input, false),
329
+ catch: (error) => new OpencodeReadFailed({ reason: String(error) })
330
+ }) : isolatedRead(store, name, input);
331
+ var racyMillis = 100;
332
+ var filesStamp = (database) => gen(function* () {
333
+ const fs = yield* FileSystem;
334
+ const files = yield* forEach([database, `${database}-wal`], (file) => option2(fs.lstat(file)));
335
+ const times = files.map((info) => getOrElse(flatMap(info, ({ mtime }) => mtime), () => {
336
+ return;
337
+ }));
338
+ return {
339
+ stamp: files.map((info, index) => isSome(info) ? `${times[index]?.getTime()}:${info.value.size}` : "").join("|"),
340
+ writtenAt: Math.max(0, ...times.map((time) => time?.getTime() ?? 0))
341
+ };
342
+ });
343
+ var settleTries = 3;
344
+ var databaseStamp2 = (database) => gen(function* () {
345
+ for (let tries = 1;; tries++) {
346
+ const { stamp, writtenAt } = yield* filesStamp(database);
347
+ const wait = writtenAt + racyMillis - (yield* currentTimeMillis);
348
+ if (wait < 0 || tries === settleTries)
349
+ return { stamp, settled: wait < 0 };
350
+ yield* sleep(Math.min(wait, racyMillis) + 1);
351
+ }
352
+ });
353
+ var answerFrom = (store, name, input, hostile) => inDatabase(store.database, hostile, (db) => readings[name].read(db, input, store.sessionId ?? ""));
354
+ var assertConfined = (database, root) => {
355
+ for (const file of [database, `${database}-wal`, `${database}-shm`, `${database}-journal`]) {
356
+ const stat = lstatSync(file, { throwIfNoEntry: false });
357
+ if (file === database && stat === undefined)
358
+ throw new Error("No database");
359
+ if (stat !== undefined && (!stat.isFile() || stat.nlink !== 1))
360
+ throw new Error("Not a plain file");
361
+ }
362
+ if (!realpathSync(database).startsWith(`${realpathSync(root)}/`))
363
+ throw new Error("Outside its directory");
364
+ };
365
+ var written = (bytes) => {
366
+ const pause = new Int32Array(new SharedArrayBuffer(4));
367
+ for (let at = 0;at < bytes.length; )
368
+ try {
369
+ at += writeSync(1, bytes, at);
370
+ } catch (error) {
371
+ if (!(error instanceof Error && ("code" in error) && error.code === "EAGAIN"))
372
+ throw error;
373
+ Atomics.wait(pause, 0, 0, 1);
374
+ }
375
+ };
376
+ var runOpencodeReader2 = () => {
377
+ const request = decoded2(readFileSync(0, "utf8"));
378
+ if (!isJsonObject(request) || !isJsonObject(request.store))
379
+ throw new Error("No request");
380
+ const { database, sessionId, confinedTo } = request.store;
381
+ if (!isString2(database) || !isString2(confinedTo))
382
+ throw new Error("No confined database");
383
+ assertConfined(database, confinedTo);
384
+ const store = { database, confinedTo, ...isString2(sessionId) ? { sessionId } : undefined };
385
+ if (isJsonObject(request.look)) {
386
+ const look = request.look;
387
+ const encoder = new TextEncoder;
388
+ return inDatabase(database, true, (db) => {
389
+ for (const frame of framesOf(db, look, store.sessionId ?? ""))
390
+ written(encoder.encode(`${encodeUnknownJsonStringSync(frame)}
391
+ `));
392
+ });
393
+ }
394
+ const reading = request.name;
395
+ const input = request.input;
396
+ process.stdout.write(encodeUnknownJsonStringSync(answerFrom(store, reading, input, true)));
397
+ };
398
+
399
+ export { sliceBytes2, maxLineBytes2, linesPerTurn2, decodedOption2, decoded2, lookAtOpencode2, readOpencode2, databaseStamp2, runOpencodeReader2 };
@@ -35,7 +35,15 @@ import {
35
35
  toCodecJson,
36
36
  Json,
37
37
  encodePrettyJsonString
38
- } from "./chunk-y64ssczv.js";
38
+ } from "./chunk-61dmxexa.js";
39
+ import {
40
+ decodeText,
41
+ mkString,
42
+ FileSystem,
43
+ Path,
44
+ withDefault,
45
+ String2
46
+ } from "./chunk-z0gqrc8c.js";
39
47
  import {
40
48
  SecureRandom,
41
49
  layerWebCrypto,
@@ -52,34 +60,26 @@ import {
52
60
  KitDeclarations,
53
61
  kitmanMcpServer,
54
62
  RunnerRpcProtocolVersion
55
- } from "./chunk-xxcxramy.js";
56
- import {
57
- decodeText,
58
- mkString,
59
- FileSystem,
60
- Path,
61
- withDefault,
62
- String2
63
- } from "./chunk-z59pvcbk.js";
63
+ } from "./chunk-nb6h112w.js";
64
64
  import {
65
65
  Packument,
66
66
  tarballMatches
67
- } from "./chunk-9yvknsnj.js";
68
- import {
69
- ChildProcessSpawner,
70
- make2
71
- } from "./chunk-vh2a72d1.js";
67
+ } from "./chunk-abyssa8p.js";
72
68
  import {
73
69
  stepDefinedTwice,
74
70
  hostSteps,
75
71
  exports_activities,
76
72
  describeFlag,
77
73
  Described
78
- } from "./chunk-njgay1ed.js";
79
- import"./chunk-qbrkeg49.js";
80
- import"./chunk-pd3azxev.js";
81
- import"./chunk-5qrjf4xq.js";
82
- import"./chunk-r2kzvdrg.js";
74
+ } from "./chunk-acmyagwp.js";
75
+ import"./chunk-3cneth9k.js";
76
+ import"./chunk-1hgsf81a.js";
77
+ import {
78
+ ChildProcessSpawner,
79
+ make2
80
+ } from "./chunk-er0e8d8v.js";
81
+ import"./chunk-r3mjxsmn.js";
82
+ import"./chunk-rbpn35g5.js";
83
83
 
84
84
  // packages/sdk/src/build/outline/graph.ts
85
85
  import {