@kitman-sh/cli 0.30.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-7j1kf6sa.js → chunk-1an3xh3b.js} +6 -6
  2. package/dist/{chunk-tsx0347c.js → chunk-1hgsf81a.js} +1 -1
  3. package/dist/{chunk-bv4gcq1h.js → chunk-3cneth9k.js} +7 -7
  4. package/dist/{chunk-samxkpbz.js → chunk-4qrb09w4.js} +3 -3
  5. package/dist/{chunk-wtea9nbk.js → chunk-4tzzmrz2.js} +25 -25
  6. package/dist/chunk-56gs4z53.js +399 -0
  7. package/dist/{chunk-39kjyh2y.js → chunk-5hp8ams4.js} +19 -19
  8. package/dist/{chunk-h2f26xbd.js → chunk-61dmxexa.js} +70 -28
  9. package/dist/{chunk-sw0dadq5.js → chunk-6e6t0f8y.js} +1 -1
  10. package/dist/{chunk-d4h1p51s.js → chunk-a0bjjbhg.js} +23 -23
  11. package/dist/{chunk-yr7np5eb.js → chunk-abyssa8p.js} +3 -3
  12. package/dist/{chunk-3xg9zbmy.js → chunk-acmyagwp.js} +10 -10
  13. package/dist/{chunk-tbmht2qb.js → chunk-af8kftyw.js} +10 -10
  14. package/dist/{chunk-r7m32p2j.js → chunk-ah59jrtr.js} +1 -1
  15. package/dist/{chunk-yaa3gkpx.js → chunk-awx0zevr.js} +9 -9
  16. package/dist/{chunk-js64y97w.js → chunk-c8eg05nh.js} +8 -4
  17. package/dist/{chunk-gap0vmj7.js → chunk-er0e8d8v.js} +14 -60
  18. package/dist/{chunk-0mg7k9b4.js → chunk-nb6h112w.js} +126 -122
  19. package/dist/{chunk-vz38kngm.js → chunk-q8e58p57.js} +2 -2
  20. package/dist/{chunk-1j38xtvp.js → chunk-qqb6djs7.js} +2 -2
  21. package/dist/{chunk-cehbrs1y.js → chunk-r3mjxsmn.js} +6 -6
  22. package/dist/{chunk-4qjfn1sa.js → chunk-rbpn35g5.js} +1 -1
  23. package/dist/{chunk-msn6rrx9.js → chunk-rnm5ybw4.js} +4 -4
  24. package/dist/{chunk-chxtmsns.js → chunk-x4d4t28n.js} +241 -109
  25. package/dist/{chunk-63cyj9dh.js → chunk-z0gqrc8c.js} +30 -25
  26. package/dist/{chunk-5kqt4bqp.js → chunk-znhjs0t6.js} +1 -1
  27. package/dist/index.js +4 -4
  28. package/package.json +1 -1
  29. package/dist/chunk-my92qn4x.js +0 -230
@@ -4,12 +4,12 @@ import {
4
4
  runnerRpcUrl2,
5
5
  makeRunnerRpcClient2,
6
6
  makeProgramRpcClient2
7
- } from "./chunk-bv4gcq1h.js";
8
- import"./chunk-cehbrs1y.js";
9
- import"./chunk-0mg7k9b4.js";
10
- import"./chunk-4qjfn1sa.js";
11
- import"./chunk-63cyj9dh.js";
12
- import"./chunk-h2f26xbd.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-h2f26xbd.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-h2f26xbd.js";
9
+ } from "./chunk-61dmxexa.js";
10
10
  import {
11
11
  runForEach
12
- } from "./chunk-63cyj9dh.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-0mg7k9b4.js";
22
+ } from "./chunk-nb6h112w.js";
23
23
  import {
24
24
  layerJson,
25
- make4,
25
+ make3,
26
26
  withHeaders,
27
27
  layerProtocolSocket
28
- } from "./chunk-cehbrs1y.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) => {
@@ -46,7 +46,7 @@ var authorizer = (options) => (call) => flatMap3(options.bearer, (token) => with
46
46
  var RunnerProcessRpcs = RunnerReplicaRpcs.merge(RunnerRunFileRpcs);
47
47
  var makeRunnerRpcClient2 = (options) => gen(function* () {
48
48
  const protocol = yield* build(options.protocol);
49
- const client = yield* make4(RunnerProcessRpcs).pipe(provideContext2(protocol));
49
+ const client = yield* make3(RunnerProcessRpcs).pipe(provideContext2(protocol));
50
50
  const authorized = authorizer(options);
51
51
  return {
52
52
  claim: (input) => authorized(client.Claim(input)),
@@ -74,7 +74,7 @@ var makeRunnerRpcClient2 = (options) => gen(function* () {
74
74
  });
75
75
  var makeProgramRpcClient2 = (options) => gen(function* () {
76
76
  const protocol = yield* build(options.protocol);
77
- const client = yield* make4(ProgramRpcs).pipe(provideContext2(protocol));
77
+ const client = yield* make3(ProgramRpcs).pipe(provideContext2(protocol));
78
78
  const authorized = authorizer(options);
79
79
  return {
80
80
  recordActivity: (input) => authorized(client.RecordActivity(input)),
@@ -4,9 +4,9 @@ import {
4
4
  opaqueTunnelRefusal2,
5
5
  isOpaqueConnectReason2,
6
6
  runSrtStep2
7
- } from "./chunk-vz38kngm.js";
8
- import"./chunk-4qjfn1sa.js";
9
- import"./chunk-h2f26xbd.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-h2f26xbd.js";
121
+ } from "./chunk-61dmxexa.js";
122
122
  import {
123
- currentTimeMillis,
124
123
  SecureRandom,
125
124
  makeUnsafe,
126
125
  formatIso,
@@ -158,8 +157,8 @@ import {
158
157
  sessionForApi,
159
158
  readAuthStore,
160
159
  agentCredentialForApi,
160
+ make5,
161
161
  make6,
162
- make7,
163
162
  Service,
164
163
  shouldRefresh,
165
164
  refreshSession,
@@ -170,8 +169,9 @@ import {
170
169
  runMcpEffect,
171
170
  createAgentAuthSignedFetch,
172
171
  setupMcpAgentCredential
173
- } from "./chunk-0mg7k9b4.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-63cyj9dh.js";
190
+ } from "./chunk-z0gqrc8c.js";
191
191
  import {
192
192
  searchDocs2,
193
193
  readDoc2
194
- } from "./chunk-sw0dadq5.js";
194
+ } from "./chunk-6e6t0f8y.js";
195
195
  import {
196
196
  nextInt
197
- } from "./chunk-5kqt4bqp.js";
197
+ } from "./chunk-znhjs0t6.js";
198
198
  import {
199
199
  recommendationProblem
200
- } from "./chunk-tsx0347c.js";
200
+ } from "./chunk-1hgsf81a.js";
201
201
  import {
202
202
  layerJson,
203
- make4,
203
+ make3,
204
204
  withHeaders,
205
205
  layerProtocolSocket,
206
206
  ConnectionHooks
207
- } from "./chunk-cehbrs1y.js";
207
+ } from "./chunk-r3mjxsmn.js";
208
208
  import {
209
209
  guard,
210
210
  Id,
211
211
  Timestamp,
212
212
  ActorType
213
- } from "./chunk-4qjfn1sa.js";
213
+ } from "./chunk-rbpn35g5.js";
214
214
 
215
215
  // apps/cli/src/mcp.ts
216
216
  import { tmpdir as tmpdir2 } from "os";
@@ -1947,56 +1947,56 @@ var LivePresenceSubscriptionMessage = Union([
1947
1947
  LivePresenceSubscriptionUpdate
1948
1948
  ]);
1949
1949
 
1950
- class LiveRpcs extends make7(make6("Session", {
1950
+ class LiveRpcs extends make6(make5("Session", {
1951
1951
  success: Struct({ workspaceId: String4, clientKind: String4 }),
1952
1952
  error: LiveRpcError
1953
- }), make6("Subscribe", {
1953
+ }), make5("Subscribe", {
1954
1954
  payload: LiveSubscribeInput,
1955
1955
  success: LiveSubscriptionMessage,
1956
1956
  error: LiveRpcError,
1957
1957
  stream: true
1958
- }), make6("Replay", {
1958
+ }), make5("Replay", {
1959
1959
  payload: LiveReplayInput,
1960
1960
  success: ArraySchema(LiveEvent),
1961
1961
  error: LiveRpcError
1962
- }), make6("Ack", {
1962
+ }), make5("Ack", {
1963
1963
  payload: LiveAckInput,
1964
1964
  success: LiveAckResult,
1965
1965
  error: LiveRpcError
1966
- }), make6("SubscribeWeb", {
1966
+ }), make5("SubscribeWeb", {
1967
1967
  payload: LiveWebSubscribeInput,
1968
1968
  success: LiveWebSubscriptionMessage,
1969
1969
  error: LiveRpcError,
1970
1970
  stream: true
1971
- }), make6("SubscriptionStatus", {
1971
+ }), make5("SubscriptionStatus", {
1972
1972
  payload: { subscriptionId: String4 },
1973
1973
  success: LiveSubscriptionStatus,
1974
1974
  error: LiveRpcError
1975
- }), make6("ReplayWeb", {
1975
+ }), make5("ReplayWeb", {
1976
1976
  payload: LiveWebReplayInput,
1977
1977
  success: LiveWebReplayResult,
1978
1978
  error: LiveRpcError
1979
- }), make6("AckWeb", {
1979
+ }), make5("AckWeb", {
1980
1980
  payload: LiveWebAckInput,
1981
1981
  success: LiveWebAckResult,
1982
1982
  error: LiveRpcError
1983
- }), make6("PublishPresence", {
1983
+ }), make5("PublishPresence", {
1984
1984
  payload: LivePresencePublishInput,
1985
1985
  success: LivePresenceEntry,
1986
1986
  error: LiveRpcError
1987
- }), make6("SubscribePresence", {
1987
+ }), make5("SubscribePresence", {
1988
1988
  payload: LivePresenceSubscribeInput,
1989
1989
  success: LivePresenceSubscriptionMessage,
1990
1990
  error: LiveRpcError,
1991
1991
  stream: true
1992
- }), make6("ClearPresence", {
1992
+ }), make5("ClearPresence", {
1993
1993
  payload: { scope: optional(LiveScope) },
1994
1994
  error: LiveRpcError
1995
- }), make6("RecordSessionUpdate", {
1995
+ }), make5("RecordSessionUpdate", {
1996
1996
  payload: { sessionId: String4, input: SessionUpdateCreate },
1997
1997
  success: SessionUpdate,
1998
1998
  error: LiveRpcError
1999
- }), make6("EndSession", {
1999
+ }), make5("EndSession", {
2000
2000
  payload: { sessionId: String4, input: SessionEnd },
2001
2001
  success: Session,
2002
2002
  error: LiveRpcError
@@ -2048,7 +2048,7 @@ function connectKitmanLiveRoot(protocol) {
2048
2048
  })
2049
2049
  });
2050
2050
  const layer = (isString2(protocol) ? liveWebSocketProtocol(protocol) : protocol()).pipe(provideMerge(hooks));
2051
- const client = await runPromise(buildWithScope(layer, scope).pipe(flatMap3((context) => make4(LiveRpcs).pipe(provideContext2(context))), provide(scope)));
2051
+ const client = await runPromise(buildWithScope(layer, scope).pipe(flatMap3((context) => make3(LiveRpcs).pipe(provideContext2(context))), provide(scope)));
2052
2052
  let abandon = () => {};
2053
2053
  const abandoned = new Promise((_resolve, reject) => {
2054
2054
  abandon = reject;
@@ -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 };