@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
@@ -81,6 +81,8 @@ import {
81
81
  fiberRunIn,
82
82
  makeLatchUnsafe,
83
83
  makeLatch,
84
+ ClockRef,
85
+ currentTimeMillis2,
84
86
  succeed3,
85
87
  failCause2,
86
88
  fail4,
@@ -203,7 +205,7 @@ import {
203
205
  String4,
204
206
  toCodecStringTree,
205
207
  encodeUnknownJsonStringSync
206
- } from "./chunk-h2f26xbd.js";
208
+ } from "./chunk-61dmxexa.js";
207
209
 
208
210
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/Iterable.js
209
211
  var headUnsafe = (self) => {
@@ -252,14 +254,9 @@ var makeEquivalence = (equivalence) => {
252
254
  return (self, that) => is(self, that) && is(that, self);
253
255
  };
254
256
 
255
- // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/BigInt.js
256
- var BigInt2 = globalThis.BigInt;
257
- var toNumber = (b) => {
258
- if (b > BigInt2(Number.MAX_SAFE_INTEGER) || b < BigInt2(Number.MIN_SAFE_INTEGER)) {
259
- return none();
260
- }
261
- return some(Number(b));
262
- };
257
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/Clock.js
258
+ var Clock = ClockRef;
259
+ var currentTimeMillis = currentTimeMillis2;
263
260
 
264
261
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/ByteSize.js
265
262
  var bigint0 = /* @__PURE__ */ BigInt(0);
@@ -1140,7 +1137,7 @@ var MutableRefProto = {
1140
1137
  };
1141
1138
  }
1142
1139
  };
1143
- var make8 = (value) => {
1140
+ var make7 = (value) => {
1144
1141
  const ref = Object.create(MutableRefProto);
1145
1142
  ref.current = value;
1146
1143
  return ref;
@@ -1301,7 +1298,7 @@ var remove = (self, value) => filter2(self, (v) => v !== value);
1301
1298
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/PubSub.js
1302
1299
  var TypeId3 = "~effect/PubSub";
1303
1300
  var SubscriptionTypeId = "~effect/PubSub/Subscription";
1304
- var make5 = (options) => sync2(() => makePubSubUnsafe(options.atomicPubSub(), new Map, makeUnsafe6(), makeUnsafe2(false), make8(false), options.strategy(), make8(none())));
1301
+ var make5 = (options) => sync2(() => makePubSubUnsafe(options.atomicPubSub(), new Map, makeUnsafe6(), makeUnsafe2(false), make7(false), options.strategy(), make7(none())));
1305
1302
  var unbounded = (options) => make5({
1306
1303
  atomicPubSub: () => makeAtomicUnbounded(options),
1307
1304
  strategy: () => new DroppingStrategy
@@ -1396,7 +1393,7 @@ var removeSubscribers = (subscribers, subscription, pollers) => {
1396
1393
  subscribers.delete(subscription);
1397
1394
  }
1398
1395
  };
1399
- var makeSubscriptionUnsafe = (pubsub, subscribers, strategy, ended) => new SubscriptionImpl(pubsub, subscribers, pubsub.subscribe(), make4(), makeUnsafe2(false), make8(false), strategy, pubsub.replayWindow(), ended);
1396
+ var makeSubscriptionUnsafe = (pubsub, subscribers, strategy, ended) => new SubscriptionImpl(pubsub, subscribers, pubsub.subscribe(), make4(), makeUnsafe2(false), make7(false), strategy, pubsub.replayWindow(), ended);
1400
1397
  class UnboundedPubSub {
1401
1398
  publisherHead = {
1402
1399
  value: AbsentValue,
@@ -1813,7 +1810,7 @@ var QueueProto = {
1813
1810
  };
1814
1811
  }
1815
1812
  };
1816
- var make9 = (options) => withFiber((fiber) => {
1813
+ var make8 = (options) => withFiber((fiber) => {
1817
1814
  const self = Object.create(QueueProto);
1818
1815
  self.dispatcher = fiber.currentDispatcher;
1819
1816
  self.capacity = options?.capacity ?? Number.POSITIVE_INFINITY;
@@ -1828,14 +1825,14 @@ var make9 = (options) => withFiber((fiber) => {
1828
1825
  };
1829
1826
  return succeed2(self);
1830
1827
  });
1831
- var bounded = (capacity) => make9({
1828
+ var bounded = (capacity) => make8({
1832
1829
  capacity
1833
1830
  });
1834
- var sliding = (capacity) => make9({
1831
+ var sliding = (capacity) => make8({
1835
1832
  capacity,
1836
1833
  strategy: "sliding"
1837
1834
  });
1838
- var unbounded2 = () => make9();
1835
+ var unbounded2 = () => make8();
1839
1836
  var offer = /* @__PURE__ */ dual(2, (self, message) => suspend2(() => offerUnsafe(self, message) ? exitTrue : self.state._tag === "Open" && self.strategy === "suspend" ? offerOrWait(self, message) : exitFalse));
1840
1837
  var offerUnsafe = (self, message) => {
1841
1838
  if (self.state._tag !== "Open") {
@@ -2261,7 +2258,7 @@ var fromTransformBracket = (f) => fromTransform(fnUntraced(function* (upstream,
2261
2258
  return onError(pull, onCause);
2262
2259
  }));
2263
2260
  var toTransform = (channel) => channel.transform;
2264
- var asyncQueue = (scope, f, options) => make9({
2261
+ var asyncQueue = (scope, f, options) => make8({
2265
2262
  capacity: options?.bufferSize,
2266
2263
  strategy: options?.strategy
2267
2264
  }).pipe(tap2((queue) => addFinalizer(scope, shutdown(queue))), tap2((queue) => provide(f(queue), scope).pipe(catchCause2((cause) => failCause(queue, cause)), forkIn(scope, {
@@ -2302,7 +2299,7 @@ var fromReadableStream2 = (options) => fromTransform((_, scope) => readableStrea
2302
2299
  }));
2303
2300
  var readableStreamToPullUnsafe = (options) => {
2304
2301
  const reader = options.readable.getReader();
2305
- const exit = options.exit ?? make8(undefined);
2302
+ const exit = options.exit ?? make7(undefined);
2306
2303
  const pull = suspend3(() => {
2307
2304
  if (exit.current)
2308
2305
  return exit.current;
@@ -2760,6 +2757,13 @@ var runFold2 = /* @__PURE__ */ dual(3, (self, initial, f) => suspend3(() => {
2760
2757
  }
2761
2758
  }), () => succeed6(state));
2762
2759
  }));
2760
+ var toPull2 = /* @__PURE__ */ fnUntraced(function* (self) {
2761
+ const semaphore = makeUnsafe3(1);
2762
+ const context2 = yield* context();
2763
+ const scope = get4(context2, Scope);
2764
+ const pull = yield* toTransform(self)(done(), scope);
2765
+ return pull.pipe(provideContext2(context2), semaphore.withPermits(1));
2766
+ }, /* @__PURE__ */ catchCause2((cause) => succeed6(failCause3(cause))));
2763
2767
  var toPullScoped = (self, scope) => toTransform(self)(done(), scope);
2764
2768
 
2765
2769
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/internal/stream.js
@@ -2956,7 +2960,7 @@ var release = (self, state) => {
2956
2960
  };
2957
2961
 
2958
2962
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/RcRef.js
2959
- var make10 = make6;
2963
+ var make9 = make6;
2960
2964
  var get3 = get2;
2961
2965
 
2962
2966
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/Stream.js
@@ -2968,7 +2972,7 @@ var transformPull2 = (self, f) => fromChannel2(fromTransform((_, scope) => flatM
2968
2972
  var toChannel2 = (stream) => stream.channel;
2969
2973
  var callback = (f, options) => fromChannel2(callbackArray(f, options));
2970
2974
  var empty2 = /* @__PURE__ */ fromChannel2(empty);
2971
- var make11 = (...values) => fromArray2(values);
2975
+ var make10 = (...values) => fromArray2(values);
2972
2976
  var suspend = (stream) => {
2973
2977
  const suspended = fromChannel2(suspend4(() => stream().channel));
2974
2978
  suspendedStreams.set(suspended, stream);
@@ -3111,6 +3115,7 @@ var runForEach = /* @__PURE__ */ dual(2, (self, f) => runForEach2(self.channel,
3111
3115
  });
3112
3116
  }));
3113
3117
  var runDrain = (self) => runDrain2(self.channel);
3118
+ var toPull = (self) => toPull2(self.channel);
3114
3119
  var mkString = (self) => runFold2(self.channel, () => "", (acc, chunk) => acc + chunk.join(""));
3115
3120
  var mkArrayBuffer = (self) => map9(mkUint8Array(self.channel), (bytes) => bytes.buffer);
3116
3121
  var toReadableStreamWith = /* @__PURE__ */ dual((args) => isStream(args[0]), (self, context, options) => {
@@ -3168,7 +3173,7 @@ var toReadableStreamEffect = /* @__PURE__ */ dual((args) => isStream(args[0]), (
3168
3173
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/FileSystem.js
3169
3174
  var TypeId10 = "~effect/FileSystem";
3170
3175
  var FileSystem = /* @__PURE__ */ Service2("effect/FileSystem");
3171
- var make12 = (impl) => FileSystem.of({
3176
+ var make11 = (impl) => FileSystem.of({
3172
3177
  ...impl,
3173
3178
  [TypeId10]: TypeId10,
3174
3179
  glob: make2(impl),
@@ -3228,7 +3233,7 @@ class WatchBackend extends (/* @__PURE__ */ Service2()("effect/FileSystem/WatchB
3228
3233
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/Path.js
3229
3234
  var TypeId11 = "~effect/Path";
3230
3235
  var Path = /* @__PURE__ */ Service2("effect/Path");
3231
- var make13 = (impl) => Path.of({
3236
+ var make12 = (impl) => Path.of({
3232
3237
  ...impl,
3233
3238
  [TypeId11]: TypeId11,
3234
3239
  resolveWithin(root, input) {
@@ -3303,7 +3308,7 @@ function makeProvider(load, mapInput) {
3303
3308
  function makeSource(get, transform) {
3304
3309
  return makeProvider((path) => get(transform(path)), (f) => makeSource(get, (path) => f(transform(path))));
3305
3310
  }
3306
- function make7(get) {
3311
+ function make13(get) {
3307
3312
  return makeSource(get, identityPath);
3308
3313
  }
3309
3314
  function emptyStringAsMissing(value, preserveEmptyStrings) {
@@ -3312,7 +3317,7 @@ function emptyStringAsMissing(value, preserveEmptyStrings) {
3312
3317
  function fromEnvRecord(env, options) {
3313
3318
  const preserveEmptyStrings = options?.preserveEmptyStrings === true;
3314
3319
  const trie = buildEnvTrie(env);
3315
- return make7((path) => succeed6(nodeAtEnv(trie, env, path, preserveEmptyStrings)));
3320
+ return make13((path) => succeed6(nodeAtEnv(trie, env, path, preserveEmptyStrings)));
3316
3321
  }
3317
3322
  function fromEnv(options) {
3318
3323
  const env = options?.env ?? {
@@ -3644,4 +3649,4 @@ var srtArgv2 = (srtCommand, settingsFile, argv) => [
3644
3649
  ...argv
3645
3650
  ];
3646
3651
 
3647
- export { map, makeEquivalence, toNumber, bytes, join, interrupt, getCurrent, BadArgument, systemError, badArgument, makeUnsafe2, make8, unbounded, publishUnsafe, make9, bounded, sliding, unbounded2, offer, offerUnsafe, offerAll, fail, failCause, failCauseUnsafe, end, endUnsafe, shutdownUnsafe, take, poll, makeUnsafe3, fromTransform, mapDone, isSink, fromChannel, drain, make10, get3, isStream, fromChannel2, callback, empty2, make11, suspend, fail2, fromQueue, fromPubSub, fromReadableStream, unwrap, map2, tap, drainFork, concat, merge2, filter, catchCause, tapError, mapError, take2, mapAccum, transduce, decodeText, encodeText, splitLines, interruptWhen, ensuring, provideContext, run, runCollect, runFold, runHead, runForEach, runDrain, mkString, mkArrayBuffer, toReadableStreamEffect, FileSystem, make12, FileTypeId, WatchBackend, Path, make13, embeddedFile, extractEmbeddedFile, map3, all, withDefault, option, String2, optionalEnv, operatorConfigHome, tempDirectoryScoped, harnessesUnsupportedInSrt2, harnessesUnsupportedInDocker2, compiled2, pinnedSrtCommand2, pinnedSrtStepCommand2, runSrtCli2, kitmanCacheDirectory2, srtSettings2, srtCacheEnvironment2, srtInheritedEnv2, inheritedEnvironment2, withOnlyEnvironment2, writeSrtSettings2, srtStepArgv2, srtArgv2 };
3652
+ export { map, makeEquivalence, Clock, currentTimeMillis, bytes, join, interrupt, getCurrent, BadArgument, systemError, badArgument, makeUnsafe2, make7, unbounded, publishUnsafe, make8, bounded, sliding, unbounded2, offer, offerUnsafe, offerAll, fail, failCause, failCauseUnsafe, end, endUnsafe, shutdownUnsafe, take, poll, makeUnsafe3, fromTransform, mapDone, isSink, fromChannel, drain, make9, get3, isStream, fromChannel2, callback, empty2, make10, suspend, fail2, fromQueue, fromPubSub, fromReadableStream, unwrap, map2, tap, drainFork, concat, merge2, filter, catchCause, tapError, mapError, take2, mapAccum, transduce, decodeText, encodeText, splitLines, interruptWhen, ensuring, provideContext, run, runCollect, runFold, runHead, runForEach, runDrain, toPull, mkString, mkArrayBuffer, toReadableStreamEffect, FileSystem, make11, FileTypeId, WatchBackend, Path, make12, embeddedFile, extractEmbeddedFile, map3, all, withDefault, option, String2, optionalEnv, operatorConfigHome, tempDirectoryScoped, harnessesUnsupportedInSrt2, harnessesUnsupportedInDocker2, compiled2, pinnedSrtCommand2, pinnedSrtStepCommand2, runSrtCli2, kitmanCacheDirectory2, srtSettings2, srtCacheEnvironment2, srtInheritedEnv2, inheritedEnvironment2, withOnlyEnvironment2, writeSrtSettings2, srtStepArgv2, srtArgv2 };
@@ -3,7 +3,7 @@ import {
3
3
  Random,
4
4
  succeed6,
5
5
  withFiber2
6
- } from "./chunk-h2f26xbd.js";
6
+ } from "./chunk-61dmxexa.js";
7
7
 
8
8
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/Random.js
9
9
  var Random2 = Random;
package/dist/index.js CHANGED
@@ -5,15 +5,15 @@
5
5
  var args = process.argv.slice(2);
6
6
  if (args[0] === "srt") {
7
7
  process.argv.splice(2, 1);
8
- const { runSrtCli } = await import("./chunk-1j38xtvp.js");
8
+ const { runSrtCli } = await import("./chunk-qqb6djs7.js");
9
9
  await runSrtCli();
10
10
  } else if (args[0] === "srt-step") {
11
- const { runSrtStep } = await import("./chunk-samxkpbz.js");
11
+ const { runSrtStep } = await import("./chunk-4qrb09w4.js");
12
12
  await runSrtStep(args.slice(1));
13
13
  } else if (args[0] === "opencode-read") {
14
- const { runOpencodeReader } = await import("./chunk-js64y97w.js");
14
+ const { runOpencodeReader } = await import("./chunk-c8eg05nh.js");
15
15
  runOpencodeReader();
16
16
  } else {
17
- const { runCli } = await import("./chunk-d4h1p51s.js");
17
+ const { runCli } = await import("./chunk-a0bjjbhg.js");
18
18
  runCli(args);
19
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitman-sh/cli",
3
- "version": "0.30.0",
3
+ "version": "0.32.0",
4
4
  "type": "module",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "bin": {
@@ -1,230 +0,0 @@
1
- // @bun
2
- import {
3
- make11,
4
- runForEach,
5
- compiled2
6
- } from "./chunk-63cyj9dh.js";
7
- import {
8
- getOrUndefined,
9
- liftThrowable,
10
- TaggedError,
11
- all3,
12
- suspend3,
13
- void_3,
14
- gen,
15
- fail7,
16
- try_2,
17
- mapError2,
18
- timeoutOrElse,
19
- scoped,
20
- declare,
21
- decodeEffect,
22
- String4,
23
- Boolean2,
24
- Struct,
25
- ArraySchema,
26
- Literals,
27
- NullOr,
28
- Finite,
29
- isNumber2,
30
- isJsonObject,
31
- isString2,
32
- encodeUnknownJsonStringSync
33
- } from "./chunk-h2f26xbd.js";
34
- import {
35
- ChildProcessSpawner,
36
- make3
37
- } from "./chunk-gap0vmj7.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(make3(command, args, {
176
- stdin: make11(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 };