lobstah 0.1.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.
package/dist/runner.js ADDED
@@ -0,0 +1,1319 @@
1
+ // packages/runner/src/index.ts
2
+ import * as fs9 from "node:fs";
3
+ import * as path7 from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ // packages/core/dist/types.js
7
+ var VERBS = ["working", "needs-decision", "blocked", "paused", "done", "failed"];
8
+ var TERMINAL_VERBS = ["done", "failed"];
9
+
10
+ // packages/core/dist/paths.js
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+ function lobstahHome() {
14
+ return process.env.LOBSTAH_HOME ?? path.join(os.homedir(), ".lobstah");
15
+ }
16
+ function laneRoot(lane) {
17
+ return lane === "work" ? lobstahHome() : path.join(lobstahHome(), "chores");
18
+ }
19
+ function laneDirs(lane) {
20
+ const root = laneRoot(lane);
21
+ return {
22
+ queue: path.join(root, "queue"),
23
+ active: path.join(root, "active"),
24
+ done: path.join(root, "done"),
25
+ state: path.join(root, "state"),
26
+ inbox: path.join(root, "inbox")
27
+ };
28
+ }
29
+ function statusPath(id, lane) {
30
+ return path.join(laneDirs(lane).state, `${id}.status`);
31
+ }
32
+ function eventsPath(id, lane) {
33
+ return path.join(laneDirs(lane).state, `${id}.events`);
34
+ }
35
+ function evidencePath(id, lane) {
36
+ return path.join(laneDirs(lane).state, `${id}.evidence`);
37
+ }
38
+
39
+ // packages/core/dist/queue.js
40
+ import * as fs from "node:fs";
41
+ import * as path2 from "node:path";
42
+ function complete(id, lane) {
43
+ const dirs = laneDirs(lane);
44
+ fs.renameSync(path2.join(dirs.active, id), path2.join(dirs.done, id));
45
+ }
46
+ function cancelRequested(id, lane) {
47
+ return fs.existsSync(path2.join(laneDirs(lane).active, id, "cancel"));
48
+ }
49
+
50
+ // packages/core/dist/status.js
51
+ import * as fs2 from "node:fs";
52
+ function isVerb(v) {
53
+ return VERBS.includes(v);
54
+ }
55
+ function appendStatus(id, lane, verb, note) {
56
+ if (!isVerb(verb)) {
57
+ throw new Error(`invalid status verb "${verb}" \u2014 must be one of: ${VERBS.join(", ")}`);
58
+ }
59
+ const entry = { at: (/* @__PURE__ */ new Date()).toISOString(), verb, ...note ? { note } : {} };
60
+ fs2.appendFileSync(statusPath(id, lane), `${JSON.stringify(entry)}
61
+ `);
62
+ return entry;
63
+ }
64
+ function readStatusLog(id, lane) {
65
+ const file = statusPath(id, lane);
66
+ if (!fs2.existsSync(file))
67
+ return [];
68
+ return fs2.readFileSync(file, "utf8").split("\n").filter(Boolean).flatMap((line) => {
69
+ try {
70
+ const parsed = JSON.parse(line);
71
+ return isVerb(parsed.verb) ? [parsed] : [];
72
+ } catch {
73
+ return [];
74
+ }
75
+ });
76
+ }
77
+
78
+ // packages/core/dist/events.js
79
+ import * as fs3 from "node:fs";
80
+ function appendEvent(id, lane, ev) {
81
+ fs3.appendFileSync(eventsPath(id, lane), `${JSON.stringify(ev)}
82
+ `);
83
+ }
84
+
85
+ // packages/core/dist/evidence.js
86
+ import * as fs4 from "node:fs";
87
+ function readEvidence(id, lane) {
88
+ try {
89
+ return JSON.parse(fs4.readFileSync(evidencePath(id, lane), "utf8"));
90
+ } catch {
91
+ return {};
92
+ }
93
+ }
94
+ function mergeEvidence(id, lane, patch) {
95
+ const file = evidencePath(id, lane);
96
+ const tmp = `${file}.tmp-${process.pid}`;
97
+ fs4.writeFileSync(tmp, JSON.stringify({ ...readEvidence(id, lane), ...patch }, null, 2));
98
+ fs4.renameSync(tmp, file);
99
+ }
100
+
101
+ // packages/core/dist/inbox.js
102
+ import * as fs5 from "node:fs";
103
+ import * as path3 from "node:path";
104
+ function inboxDir(id, lane) {
105
+ return path3.join(laneDirs(lane).inbox, id);
106
+ }
107
+ function unhandled(id, lane) {
108
+ const dir = inboxDir(id, lane);
109
+ if (!fs5.existsSync(dir))
110
+ return [];
111
+ return fs5.readdirSync(dir).filter((f) => f.endsWith(".msg")).sort().map((f) => ({ file: f, text: fs5.readFileSync(path3.join(dir, f), "utf8") }));
112
+ }
113
+ function acknowledge(id, lane, file) {
114
+ const dir = inboxDir(id, lane);
115
+ fs5.mkdirSync(path3.join(dir, "handled"), { recursive: true });
116
+ fs5.renameSync(path3.join(dir, file), path3.join(dir, "handled", file));
117
+ }
118
+
119
+ // packages/core/dist/config.js
120
+ import * as fs6 from "node:fs";
121
+ import * as os2 from "node:os";
122
+ import * as path4 from "node:path";
123
+
124
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/date.js
125
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;
126
+ var TomlDate = class _TomlDate extends Date {
127
+ #hasDate = false;
128
+ #hasTime = false;
129
+ #offset = null;
130
+ constructor(date) {
131
+ let hasDate = true;
132
+ let hasTime = true;
133
+ let offset = "Z";
134
+ if (typeof date === "string") {
135
+ let match = date.match(DATE_TIME_RE);
136
+ if (match) {
137
+ if (!match[1]) {
138
+ hasDate = false;
139
+ date = `0000-01-01T${date}`;
140
+ }
141
+ hasTime = !!match[2];
142
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
143
+ if (match[2] && +match[2] > 23) {
144
+ date = "";
145
+ } else {
146
+ offset = match[3] || null;
147
+ date = date.toUpperCase();
148
+ if (!offset && hasTime)
149
+ date += "Z";
150
+ }
151
+ } else {
152
+ date = "";
153
+ }
154
+ }
155
+ super(date);
156
+ if (!isNaN(this.getTime())) {
157
+ this.#hasDate = hasDate;
158
+ this.#hasTime = hasTime;
159
+ this.#offset = offset;
160
+ }
161
+ }
162
+ isDateTime() {
163
+ return this.#hasDate && this.#hasTime;
164
+ }
165
+ isLocal() {
166
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
167
+ }
168
+ isDate() {
169
+ return this.#hasDate && !this.#hasTime;
170
+ }
171
+ isTime() {
172
+ return this.#hasTime && !this.#hasDate;
173
+ }
174
+ isValid() {
175
+ return this.#hasDate || this.#hasTime;
176
+ }
177
+ toISOString() {
178
+ let iso = super.toISOString();
179
+ if (this.isDate())
180
+ return iso.slice(0, 10);
181
+ if (this.isTime())
182
+ return iso.slice(11, 23);
183
+ if (this.#offset === null)
184
+ return iso.slice(0, -1);
185
+ if (this.#offset === "Z")
186
+ return iso;
187
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
188
+ offset = this.#offset[0] === "-" ? offset : -offset;
189
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
190
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
191
+ }
192
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
193
+ let date = new _TomlDate(jsDate);
194
+ date.#offset = offset;
195
+ return date;
196
+ }
197
+ static wrapAsLocalDateTime(jsDate) {
198
+ let date = new _TomlDate(jsDate);
199
+ date.#offset = null;
200
+ return date;
201
+ }
202
+ static wrapAsLocalDate(jsDate) {
203
+ let date = new _TomlDate(jsDate);
204
+ date.#hasTime = false;
205
+ date.#offset = null;
206
+ return date;
207
+ }
208
+ static wrapAsLocalTime(jsDate) {
209
+ let date = new _TomlDate(jsDate);
210
+ date.#hasDate = false;
211
+ date.#offset = null;
212
+ return date;
213
+ }
214
+ };
215
+
216
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/error.js
217
+ function getLineColFromPtr(string, ptr) {
218
+ let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
219
+ return [lines.length, lines.pop().length + 1];
220
+ }
221
+ function makeCodeBlock(string, line, column) {
222
+ let lines = string.split(/\r\n|\n|\r/g);
223
+ let codeblock = "";
224
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
225
+ for (let i = line - 1; i <= line + 1; i++) {
226
+ let l = lines[i - 1];
227
+ if (!l)
228
+ continue;
229
+ codeblock += i.toString().padEnd(numberLen, " ");
230
+ codeblock += ": ";
231
+ codeblock += l;
232
+ codeblock += "\n";
233
+ if (i === line) {
234
+ codeblock += " ".repeat(numberLen + column + 2);
235
+ codeblock += "^\n";
236
+ }
237
+ }
238
+ return codeblock;
239
+ }
240
+ var TomlError = class extends Error {
241
+ line;
242
+ column;
243
+ codeblock;
244
+ constructor(message, options) {
245
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
246
+ const codeblock = makeCodeBlock(options.toml, line, column);
247
+ super(`Invalid TOML document: ${message}
248
+
249
+ ${codeblock}`, options);
250
+ this.line = line;
251
+ this.column = column;
252
+ this.codeblock = codeblock;
253
+ }
254
+ };
255
+
256
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/util.js
257
+ function indexOfNewline(str, start = 0) {
258
+ let idx = str.indexOf("\n", start);
259
+ if (str.charCodeAt(idx - 1) === 13)
260
+ idx--;
261
+ return idx;
262
+ }
263
+ function skipComment(ctx) {
264
+ for (; ctx.p < ctx.s.length; ctx.p++) {
265
+ let c = ctx.s.charCodeAt(ctx.p);
266
+ if (c === 10)
267
+ break;
268
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
269
+ ctx.p++;
270
+ break;
271
+ }
272
+ if (c < 32 && c !== 9 || c === 127) {
273
+ throw new TomlError("control characters are not allowed in comments", {
274
+ toml: ctx.s,
275
+ ptr: ctx.p
276
+ });
277
+ }
278
+ }
279
+ }
280
+ function skipVoid(ctx, banNewLines, banComments) {
281
+ let c;
282
+ while (1) {
283
+ while ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10))
284
+ ctx.p++;
285
+ if (banComments || c !== 35)
286
+ break;
287
+ skipComment(ctx);
288
+ }
289
+ }
290
+ function skipUntil(ctx, sep, end) {
291
+ let ptr = ctx.p;
292
+ if (!end) {
293
+ ptr = indexOfNewline(ctx.s, ptr);
294
+ ctx.p = ptr < 0 ? ctx.s.length : ptr;
295
+ return;
296
+ }
297
+ for (; ctx.p < ctx.s.length; ctx.p++) {
298
+ let c = ctx.s.charCodeAt(ctx.p);
299
+ if (c === 35) {
300
+ skipComment(ctx);
301
+ } else if (c === end || c === sep) {
302
+ return;
303
+ }
304
+ }
305
+ throw new TomlError("cannot find end of structure", {
306
+ toml: ctx.s,
307
+ ptr
308
+ });
309
+ }
310
+
311
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/primitive.js
312
+ var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
313
+ var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
314
+ var LEADING_ZERO = /^[+-]?0[0-9_]/;
315
+ function parseString(ctx) {
316
+ let start = ctx.p;
317
+ let c = ctx.s.charCodeAt(ctx.p++);
318
+ let first = c;
319
+ let isLiteral = c === 39;
320
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
321
+ if (isMultiline) {
322
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
323
+ ctx.p++;
324
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
325
+ ctx.p += 2;
326
+ }
327
+ let parsed = "";
328
+ let sliceStart = ctx.p;
329
+ let state = 0;
330
+ for (; ctx.p < ctx.s.length; ctx.p++) {
331
+ c = ctx.s.charCodeAt(ctx.p);
332
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
333
+ state = state && 3;
334
+ } else if (c < 32 && c !== 9 || c === 127) {
335
+ throw new TomlError("control characters are not allowed in strings", {
336
+ toml: ctx.s,
337
+ ptr: ctx.p
338
+ });
339
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
340
+ if (isMultiline) {
341
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
342
+ ctx.p++;
343
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
344
+ ctx.p++;
345
+ }
346
+ if (!state)
347
+ parsed += ctx.s.slice(sliceStart, ctx.p);
348
+ ctx.p += isMultiline ? 3 : 1;
349
+ return parsed;
350
+ } else if (!state) {
351
+ if (!isLiteral && c === 92) {
352
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
353
+ state = 1;
354
+ }
355
+ } else if (state === 1) {
356
+ if (c === 120 || c === 117 || c === 85) {
357
+ let value = 0;
358
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
359
+ for (let j = 0; j < len; j++, ctx.p++) {
360
+ let hex = ctx.s.charCodeAt(ctx.p + 1);
361
+ let digit = (
362
+ /* 0-9 */
363
+ hex >= 48 && hex <= 57 ? hex - 48 : (
364
+ /* A-F */
365
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
366
+ /* a-f */
367
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
368
+ )
369
+ )
370
+ );
371
+ if (digit < 0)
372
+ throw new TomlError("invalid non-hex character in unicode escape", { toml: ctx.s, ptr: ctx.p + 1 });
373
+ value = value << 4 | digit;
374
+ }
375
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
376
+ throw new TomlError("invalid unicode escape", { toml: ctx.s, ptr: ctx.p });
377
+ }
378
+ parsed += String.fromCodePoint(value);
379
+ sliceStart = ctx.p + 1;
380
+ state = 0;
381
+ } else if (c === 32 || c === 9) {
382
+ state = 2;
383
+ } else {
384
+ if (c === 98)
385
+ parsed += "\b";
386
+ else if (c === 116)
387
+ parsed += " ";
388
+ else if (c === 110)
389
+ parsed += "\n";
390
+ else if (c === 102)
391
+ parsed += "\f";
392
+ else if (c === 114)
393
+ parsed += "\r";
394
+ else if (c === 101)
395
+ parsed += "\x1B";
396
+ else if (c === 34)
397
+ parsed += '"';
398
+ else if (c === 92)
399
+ parsed += "\\";
400
+ else
401
+ throw new TomlError("unrecognized escape sequence", { toml: ctx.s, ptr: ctx.p });
402
+ sliceStart = ctx.p + 1;
403
+ state = 0;
404
+ }
405
+ } else if (c !== 32 && c !== 9) {
406
+ if (state === 2) {
407
+ throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
408
+ toml: ctx.s,
409
+ ptr: sliceStart
410
+ });
411
+ }
412
+ state = !isLiteral && c === 92 ? 1 : 0;
413
+ sliceStart = ctx.p;
414
+ }
415
+ }
416
+ throw new TomlError("unfinished string", { toml: ctx.s, ptr: start });
417
+ }
418
+ function sliceAndTrimEndOf(ctx, start, end) {
419
+ let value = ctx.s.slice(start, end);
420
+ let commentIdx = value.indexOf("#");
421
+ if (commentIdx > 0) {
422
+ skipComment({ s: value, p: commentIdx, d: 0 });
423
+ value = value.slice(0, commentIdx);
424
+ }
425
+ return value.trimEnd();
426
+ }
427
+ function parseValue(ctx, integersAsBigInt, end) {
428
+ let ptr = ctx.p;
429
+ let err = { toml: ctx.s, ptr };
430
+ skipUntil(ctx, 44, end);
431
+ let value = sliceAndTrimEndOf(ctx, ptr, ctx.p);
432
+ if (!value)
433
+ throw new TomlError("incomplete declaration: value expected", err);
434
+ if (value === "-inf")
435
+ return -Infinity;
436
+ if (value === "inf" || value === "+inf")
437
+ return Infinity;
438
+ if (value === "nan" || value === "+nan" || value === "-nan")
439
+ return NaN;
440
+ if (value === "-0")
441
+ return integersAsBigInt ? 0n : 0;
442
+ let isInt = INT_REGEX.test(value);
443
+ if (isInt || FLOAT_REGEX.test(value)) {
444
+ if (LEADING_ZERO.test(value)) {
445
+ throw new TomlError("leading zeroes are not allowed", err);
446
+ }
447
+ value = value.replace(/_/g, "");
448
+ let numeric = +value;
449
+ if (isNaN(numeric)) {
450
+ throw new TomlError("invalid number", err);
451
+ }
452
+ if (isInt) {
453
+ if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
454
+ throw new TomlError("integer value cannot be represented losslessly", err);
455
+ }
456
+ if (isInt || integersAsBigInt === true)
457
+ numeric = BigInt(value);
458
+ }
459
+ return numeric;
460
+ }
461
+ const date = new TomlDate(value);
462
+ if (!date.isValid())
463
+ throw new TomlError("invalid value", err);
464
+ return date;
465
+ }
466
+
467
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/extract.js
468
+ function extractValue(ctx, end, integersAsBigInt) {
469
+ let ptr = ctx.p;
470
+ let c = ctx.s.charCodeAt(ptr);
471
+ if (c === 91 || c === 123) {
472
+ if (!ctx.d--) {
473
+ throw new TomlError("document contains excessively nested structures. aborting.", {
474
+ toml: ctx.s,
475
+ ptr
476
+ });
477
+ }
478
+ let value = c === 91 ? parseArray(ctx, integersAsBigInt) : parseInlineTable(ctx, integersAsBigInt);
479
+ ctx.d++;
480
+ return value;
481
+ }
482
+ if (c === 34 || c === 39) {
483
+ return parseString(ctx);
484
+ }
485
+ if (c === 116) {
486
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
487
+ throw new TomlError("invalid value", { toml: ctx.s, ptr });
488
+ ctx.p++;
489
+ return true;
490
+ }
491
+ if (c === 102) {
492
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
493
+ throw new TomlError("invalid value", { toml: ctx.s, ptr });
494
+ ctx.p++;
495
+ return false;
496
+ }
497
+ return parseValue(ctx, integersAsBigInt, end);
498
+ }
499
+
500
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/struct.js
501
+ var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
502
+ function parseKey(ctx, end = "=") {
503
+ let start = ctx.p;
504
+ let dot = start - 1;
505
+ let parsed = [];
506
+ let endPtr = ctx.s.indexOf(end, start);
507
+ if (endPtr < 0) {
508
+ throw new TomlError("incomplete key-value: cannot find end of key", {
509
+ toml: ctx.s,
510
+ ptr: start
511
+ });
512
+ }
513
+ do {
514
+ let c = ctx.s.charCodeAt(ctx.p = ++dot);
515
+ if (c !== 32 && c !== 9) {
516
+ if (c === 34 || c === 39) {
517
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2)) {
518
+ throw new TomlError("multiline strings are not allowed in keys", {
519
+ toml: ctx.s,
520
+ ptr: ctx.p
521
+ });
522
+ }
523
+ let part = parseString(ctx);
524
+ dot = ctx.s.indexOf(".", ctx.p);
525
+ let strEnd = ctx.s.slice(ctx.p, dot < 0 || dot > endPtr ? endPtr : dot);
526
+ let newLine = indexOfNewline(strEnd);
527
+ if (newLine > -1) {
528
+ throw new TomlError("newlines are not allowed in keys", {
529
+ toml: ctx.s,
530
+ ptr: newLine
531
+ });
532
+ }
533
+ if (strEnd.trimStart()) {
534
+ throw new TomlError("found extra tokens after the string part", {
535
+ toml: ctx.s,
536
+ ptr: ctx.p
537
+ });
538
+ }
539
+ if (endPtr < ctx.p) {
540
+ endPtr = ctx.s.indexOf(end, ctx.p);
541
+ if (endPtr < 0) {
542
+ throw new TomlError("incomplete key-value: cannot find end of key", {
543
+ toml: ctx.s,
544
+ ptr: start
545
+ });
546
+ }
547
+ }
548
+ parsed.push(part);
549
+ } else {
550
+ dot = ctx.s.indexOf(".", ctx.p);
551
+ let part = ctx.s.slice(ctx.p, dot < 0 || dot > endPtr ? endPtr : dot);
552
+ if (!KEY_PART_RE.test(part)) {
553
+ throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
554
+ toml: ctx.s,
555
+ ptr: ctx.p
556
+ });
557
+ }
558
+ parsed.push(part.trimEnd());
559
+ }
560
+ }
561
+ } while (dot + 1 && dot < endPtr);
562
+ ctx.p = endPtr + 1;
563
+ skipVoid(ctx, true, true);
564
+ return parsed;
565
+ }
566
+ function parseInlineTable(ctx, integersAsBigInt) {
567
+ let res = {};
568
+ let seen = /* @__PURE__ */ new Set();
569
+ let c;
570
+ ctx.p++;
571
+ while (ctx.p < ctx.s.length) {
572
+ skipVoid(ctx);
573
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
574
+ ctx.p++;
575
+ return res;
576
+ }
577
+ let k;
578
+ let t = res;
579
+ let hasOwn = false;
580
+ let p = ctx.p;
581
+ let key = parseKey(ctx);
582
+ for (let i = 0; i < key.length; i++) {
583
+ if (i)
584
+ t = hasOwn ? t[k] : t[k] = {};
585
+ k = key[i];
586
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
587
+ throw new TomlError("trying to redefine an already defined value", {
588
+ toml: ctx.s,
589
+ ptr: p
590
+ });
591
+ }
592
+ if (!hasOwn && k === "__proto__") {
593
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
594
+ }
595
+ }
596
+ if (hasOwn) {
597
+ throw new TomlError("trying to redefine an already defined value", {
598
+ toml: ctx.s,
599
+ ptr: ctx.p
600
+ });
601
+ }
602
+ let value = extractValue(ctx, 125, integersAsBigInt);
603
+ seen.add(t[k] = value);
604
+ skipVoid(ctx);
605
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
606
+ return res;
607
+ }
608
+ if (c !== 44) {
609
+ throw new TomlError("expected comma or end of structure", { toml: ctx.s, ptr: ctx.p - 1 });
610
+ }
611
+ }
612
+ throw new TomlError("unfinished table encountered", {
613
+ toml: ctx.s,
614
+ ptr: ctx.p
615
+ });
616
+ }
617
+ function parseArray(ctx, integersAsBigInt) {
618
+ let res = [];
619
+ let c;
620
+ ctx.p++;
621
+ while (ctx.p < ctx.s.length) {
622
+ skipVoid(ctx);
623
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
624
+ ctx.p++;
625
+ return res;
626
+ }
627
+ res.push(extractValue(ctx, 93, integersAsBigInt));
628
+ skipVoid(ctx);
629
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
630
+ return res;
631
+ }
632
+ if (c !== 44) {
633
+ throw new TomlError("expected comma or end of structure", { toml: ctx.s, ptr: ctx.p - 1 });
634
+ }
635
+ }
636
+ throw new TomlError("unfinished array encountered", {
637
+ toml: ctx.s,
638
+ ptr: ctx.p
639
+ });
640
+ }
641
+
642
+ // node_modules/.pnpm/smol-toml@1.8.0/node_modules/smol-toml/dist/parse.js
643
+ function peekTable(key, table, meta, type) {
644
+ let t = table;
645
+ let m = meta;
646
+ let k;
647
+ let hasOwn = false;
648
+ let state;
649
+ for (let i = 0; i < key.length; i++) {
650
+ if (i) {
651
+ t = hasOwn ? t[k] : t[k] = {};
652
+ m = (state = m[k]).c;
653
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
654
+ return null;
655
+ }
656
+ if (state.t === 2) {
657
+ let l = t.length - 1;
658
+ t = t[l];
659
+ m = m[l].c;
660
+ }
661
+ }
662
+ k = key[i];
663
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
664
+ return null;
665
+ }
666
+ if (!hasOwn) {
667
+ if (k === "__proto__") {
668
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
669
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
670
+ }
671
+ m[k] = {
672
+ t: i < key.length - 1 && type === 2 ? 3 : type,
673
+ d: false,
674
+ i: 0,
675
+ c: {}
676
+ };
677
+ }
678
+ }
679
+ state = m[k];
680
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
681
+ return null;
682
+ }
683
+ if (type === 2) {
684
+ if (!state.d) {
685
+ state.d = true;
686
+ t[k] = [];
687
+ }
688
+ t[k].push(t = {});
689
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
690
+ }
691
+ if (state.d) {
692
+ return null;
693
+ }
694
+ state.d = true;
695
+ if (type === 1) {
696
+ t = hasOwn ? t[k] : t[k] = {};
697
+ } else if (type === 0 && hasOwn) {
698
+ return null;
699
+ }
700
+ return [k, t, state.c];
701
+ }
702
+ function parse(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
703
+ let ctx = { s: toml, p: 0, d: maxDepth };
704
+ let res = {};
705
+ let meta = {};
706
+ let tmp;
707
+ let tbl = res;
708
+ let m = meta;
709
+ skipVoid(ctx);
710
+ while (ctx.p < toml.length) {
711
+ if (toml.charCodeAt(ctx.p) === 91) {
712
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
713
+ tmp = ctx.p += +isTableArray;
714
+ let k = parseKey(ctx, "]");
715
+ if (isTableArray) {
716
+ if (toml.charCodeAt(ctx.p - 1) !== 93) {
717
+ throw new TomlError("expected end of table declaration", {
718
+ toml,
719
+ ptr: ctx.p - 1
720
+ });
721
+ }
722
+ ctx.p++;
723
+ }
724
+ let p = peekTable(
725
+ k,
726
+ res,
727
+ meta,
728
+ isTableArray ? 2 : 1
729
+ /* Type.EXPLICIT */
730
+ );
731
+ if (!p) {
732
+ throw new TomlError("trying to redefine an already defined table or value", {
733
+ toml,
734
+ ptr: tmp
735
+ });
736
+ }
737
+ m = p[2];
738
+ tbl = p[1];
739
+ } else {
740
+ tmp = ctx.p;
741
+ let k = parseKey(ctx);
742
+ let p = peekTable(
743
+ k,
744
+ tbl,
745
+ m,
746
+ 0
747
+ /* Type.DOTTED */
748
+ );
749
+ if (!p) {
750
+ throw new TomlError("trying to redefine an already defined table or value", {
751
+ toml,
752
+ ptr: tmp
753
+ });
754
+ }
755
+ p[1][p[0]] = extractValue(ctx, void 0, integersAsBigInt);
756
+ }
757
+ skipVoid(ctx, true);
758
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && tmp !== 13) {
759
+ throw new TomlError("each key-value declaration must be followed by an end-of-line", {
760
+ toml,
761
+ ptr: ctx.p
762
+ });
763
+ }
764
+ skipVoid(ctx);
765
+ }
766
+ return res;
767
+ }
768
+
769
+ // packages/core/dist/config.js
770
+ var DEFAULT_LIMITS = {
771
+ maxConcurrent: 2,
772
+ choreConcurrent: 1,
773
+ wedgeThresholdSecs: 600,
774
+ maxRestartAttempts: 2,
775
+ wallClockSecs: 3600,
776
+ choreRetentionDays: 7
777
+ };
778
+ function configPath() {
779
+ return path4.join(lobstahHome(), "config.toml");
780
+ }
781
+ function expandHome(p) {
782
+ return p.startsWith("~/") ? path4.join(os2.homedir(), p.slice(2)) : p;
783
+ }
784
+ function loadConfig() {
785
+ const file = configPath();
786
+ const raw = fs6.existsSync(file) ? parse(fs6.readFileSync(file, "utf8")) : {};
787
+ const reposRaw = raw.repos ?? {};
788
+ const repos = {};
789
+ for (const [key, r] of Object.entries(reposRaw)) {
790
+ repos[key] = {
791
+ path: expandHome(String(r.path ?? "")),
792
+ origin: r.origin ? String(r.origin) : void 0,
793
+ trunk: String(r.trunk ?? "main"),
794
+ setup: Array.isArray(r.setup) ? r.setup.map(String) : void 0,
795
+ env: r.env ?? void 0,
796
+ harness: r.harness ?? void 0
797
+ };
798
+ }
799
+ return {
800
+ repos,
801
+ harness: raw.harness ?? {},
802
+ limits: { ...DEFAULT_LIMITS, ...raw.limits ?? {} },
803
+ notifyCommand: raw.notifyCommand ? String(raw.notifyCommand) : void 0,
804
+ notifyVerbs: Array.isArray(raw.notifyVerbs) ? raw.notifyVerbs.map(String) : void 0,
805
+ remindSecs: raw.remindSecs !== void 0 ? Number(raw.remindSecs) : void 0
806
+ };
807
+ }
808
+ function resolveDispatch(d, cfg) {
809
+ const repo = cfg.repos[d.repo];
810
+ if (!repo)
811
+ throw new Error(`unknown repo key "${d.repo}" \u2014 add it to ${configPath()}`);
812
+ const rh = repo.harness ?? {};
813
+ const gh = cfg.harness;
814
+ return {
815
+ harness: d.harness ?? rh.default ?? gh.default ?? "claude",
816
+ model: d.model ?? rh.model ?? gh.model,
817
+ effort: d.effort ?? rh.effort ?? gh.effort,
818
+ limits: {
819
+ wallClockSecs: cfg.limits.wallClockSecs,
820
+ ...d.limits ?? {}
821
+ },
822
+ env: { ...repo.env ?? {}, ...d.env ?? {} },
823
+ flags: d.flags ?? []
824
+ };
825
+ }
826
+
827
+ // packages/adapters/dist/types.js
828
+ var AsyncQueue = class {
829
+ buffer = [];
830
+ waiters = [];
831
+ closed = false;
832
+ push(item) {
833
+ if (this.closed)
834
+ return;
835
+ const w = this.waiters.shift();
836
+ if (w)
837
+ w({ value: item, done: false });
838
+ else
839
+ this.buffer.push(item);
840
+ }
841
+ close() {
842
+ this.closed = true;
843
+ for (const w of this.waiters.splice(0))
844
+ w({ value: void 0, done: true });
845
+ }
846
+ [Symbol.asyncIterator]() {
847
+ return {
848
+ next: () => {
849
+ const item = this.buffer.shift();
850
+ if (item !== void 0)
851
+ return Promise.resolve({ value: item, done: false });
852
+ if (this.closed)
853
+ return Promise.resolve({ value: void 0, done: true });
854
+ return new Promise((resolve2) => this.waiters.push(resolve2));
855
+ }
856
+ };
857
+ }
858
+ };
859
+ var InputGate = class {
860
+ queue = [];
861
+ waiter = null;
862
+ ended = false;
863
+ send(text) {
864
+ this.queue.push(text);
865
+ this.waiter?.();
866
+ }
867
+ end() {
868
+ this.ended = true;
869
+ this.waiter?.();
870
+ }
871
+ /** Resolves with the next message, or undefined once ended and drained. */
872
+ async next() {
873
+ while (true) {
874
+ const msg = this.queue.shift();
875
+ if (msg !== void 0)
876
+ return msg;
877
+ if (this.ended)
878
+ return void 0;
879
+ await new Promise((resolve2) => this.waiter = resolve2);
880
+ this.waiter = null;
881
+ }
882
+ }
883
+ };
884
+ function now() {
885
+ return (/* @__PURE__ */ new Date()).toISOString();
886
+ }
887
+
888
+ // packages/adapters/dist/claude.js
889
+ function flagsToExtraArgs(flags) {
890
+ const extra = {};
891
+ for (let i = 0; i < flags.length; i++) {
892
+ const f = flags[i];
893
+ if (!f?.startsWith("--"))
894
+ continue;
895
+ const next = flags[i + 1];
896
+ if (next !== void 0 && !next.startsWith("--")) {
897
+ extra[f.slice(2)] = next;
898
+ i++;
899
+ } else {
900
+ extra[f.slice(2)] = null;
901
+ }
902
+ }
903
+ return extra;
904
+ }
905
+ function createClaudeAdapter() {
906
+ return {
907
+ name: "claude",
908
+ async start(opts) {
909
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
910
+ const input = new InputGate();
911
+ async function* userMessages() {
912
+ yield {
913
+ type: "user",
914
+ message: { role: "user", content: opts.prompt },
915
+ parent_tool_use_id: null,
916
+ session_id: ""
917
+ };
918
+ while (true) {
919
+ const text = await input.next();
920
+ if (text === void 0)
921
+ return;
922
+ yield {
923
+ type: "user",
924
+ message: { role: "user", content: text },
925
+ parent_tool_use_id: null,
926
+ session_id: ""
927
+ };
928
+ }
929
+ }
930
+ const q = sdk.query({
931
+ prompt: userMessages(),
932
+ options: {
933
+ cwd: opts.cwd,
934
+ model: opts.model,
935
+ maxTurns: opts.limits.maxTurns,
936
+ resume: opts.resumeSession,
937
+ forkSession: opts.resumeSession ? true : void 0,
938
+ permissionMode: "bypassPermissions",
939
+ env: { ...process.env, ...opts.env },
940
+ extraArgs: flagsToExtraArgs(opts.flags)
941
+ }
942
+ });
943
+ const events = new AsyncQueue();
944
+ let sessionId;
945
+ const done = (async () => {
946
+ try {
947
+ for await (const msg of q) {
948
+ const at = now();
949
+ if (msg.type === "system" && msg.subtype === "init") {
950
+ sessionId = msg.session_id;
951
+ events.push({ at, type: "session", data: { sessionId } });
952
+ } else if (msg.type === "assistant") {
953
+ for (const block of msg.message?.content ?? []) {
954
+ if (block.type === "tool_use") {
955
+ events.push({ at, type: "tool-start", data: { name: block.name } });
956
+ } else if (block.type === "text" && block.text) {
957
+ events.push({ at, type: "text", data: { text: String(block.text).slice(0, 2e3) } });
958
+ }
959
+ }
960
+ } else if (msg.type === "user") {
961
+ const content = msg.message?.content;
962
+ if (Array.isArray(content)) {
963
+ for (const block of content) {
964
+ if (block.type === "tool_result")
965
+ events.push({ at, type: "tool-end", data: {} });
966
+ }
967
+ }
968
+ } else if (msg.type === "result") {
969
+ events.push({ at, type: "turn-end", data: { subtype: msg.subtype, costUsd: msg.total_cost_usd } });
970
+ }
971
+ }
972
+ return { sessionId };
973
+ } catch (err) {
974
+ const message = err instanceof Error ? err.message : String(err);
975
+ events.push({ at: now(), type: "error", data: { message } });
976
+ return { sessionId, error: message };
977
+ } finally {
978
+ events.close();
979
+ }
980
+ })();
981
+ return {
982
+ events,
983
+ send: (text) => input.send(text),
984
+ end: () => input.end(),
985
+ done,
986
+ kill: () => {
987
+ try {
988
+ q.interrupt?.();
989
+ } catch {
990
+ }
991
+ input.end();
992
+ }
993
+ };
994
+ }
995
+ };
996
+ }
997
+
998
+ // packages/adapters/dist/codex.js
999
+ import * as fs7 from "node:fs";
1000
+ import * as os3 from "node:os";
1001
+ import * as path5 from "node:path";
1002
+ function isolatedCodexHome() {
1003
+ const dir = path5.join(lobstahHome(), "codex-home");
1004
+ fs7.mkdirSync(dir, { recursive: true });
1005
+ const auth = path5.join(dir, "auth.json");
1006
+ const realAuth = path5.join(os3.homedir(), ".codex", "auth.json");
1007
+ if (!fs7.existsSync(auth) && fs7.existsSync(realAuth)) {
1008
+ try {
1009
+ fs7.symlinkSync(realAuth, auth);
1010
+ } catch {
1011
+ fs7.copyFileSync(realAuth, auth);
1012
+ }
1013
+ }
1014
+ const cfg = path5.join(dir, "config.toml");
1015
+ if (!fs7.existsSync(cfg)) {
1016
+ fs7.writeFileSync(cfg, "# lobstah-managed: auth inherited from ~/.codex, interactive config not\n");
1017
+ }
1018
+ return dir;
1019
+ }
1020
+ function createCodexAdapter() {
1021
+ return {
1022
+ name: "codex",
1023
+ async start(opts) {
1024
+ const mod = await import("@openai/codex-sdk");
1025
+ const codex = new mod.Codex({
1026
+ env: { ...process.env, ...opts.env, CODEX_HOME: isolatedCodexHome() }
1027
+ });
1028
+ const threadOptions = {
1029
+ workingDirectory: opts.cwd,
1030
+ skipGitRepoCheck: true,
1031
+ sandboxMode: "workspace-write",
1032
+ approvalPolicy: "never",
1033
+ ...opts.model ? { model: opts.model } : {},
1034
+ ...opts.effort ? { modelReasoningEffort: opts.effort } : {}
1035
+ };
1036
+ const thread = opts.resumeSession ? codex.resumeThread(opts.resumeSession, threadOptions) : codex.startThread(threadOptions);
1037
+ const input = new InputGate();
1038
+ const events = new AsyncQueue();
1039
+ let sessionId;
1040
+ let lastTurnError;
1041
+ const done = (async () => {
1042
+ try {
1043
+ let next = opts.prompt;
1044
+ while (next !== void 0) {
1045
+ const streamed = await thread.runStreamed(next);
1046
+ for await (const ev of streamed.events) {
1047
+ const at = now();
1048
+ if (ev.type === "thread.started") {
1049
+ sessionId = ev.thread_id;
1050
+ events.push({ at, type: "session", data: { sessionId } });
1051
+ } else if (ev.type === "turn.started") {
1052
+ events.push({ at, type: "turn-start", data: {} });
1053
+ } else if (ev.type === "item.started") {
1054
+ events.push({ at, type: "tool-start", data: { name: ev.item?.type } });
1055
+ } else if (ev.type === "item.completed") {
1056
+ if (ev.item?.type === "agent_message" && ev.item?.text) {
1057
+ events.push({ at, type: "text", data: { text: String(ev.item.text).slice(0, 2e3) } });
1058
+ } else {
1059
+ events.push({ at, type: "tool-end", data: { name: ev.item?.type } });
1060
+ }
1061
+ } else if (ev.type === "turn.failed") {
1062
+ lastTurnError = ev.error?.message ?? "turn failed";
1063
+ events.push({ at, type: "error", data: { message: lastTurnError } });
1064
+ }
1065
+ }
1066
+ events.push({ at: now(), type: "turn-end", data: {} });
1067
+ next = await input.next();
1068
+ }
1069
+ return { sessionId };
1070
+ } catch (err) {
1071
+ const message = lastTurnError ?? (err instanceof Error ? err.message : String(err));
1072
+ events.push({ at: now(), type: "error", data: { message } });
1073
+ return { sessionId, error: message };
1074
+ } finally {
1075
+ events.close();
1076
+ }
1077
+ })();
1078
+ return {
1079
+ events,
1080
+ send: (text) => input.send(text),
1081
+ end: () => input.end(),
1082
+ done,
1083
+ kill: () => input.end()
1084
+ };
1085
+ }
1086
+ };
1087
+ }
1088
+
1089
+ // packages/adapters/dist/index.js
1090
+ function loadAdapter(name) {
1091
+ switch (name) {
1092
+ case "claude":
1093
+ return createClaudeAdapter();
1094
+ case "codex":
1095
+ return createCodexAdapter();
1096
+ default:
1097
+ throw new Error(`unknown harness "${name}" \u2014 known: claude, codex`);
1098
+ }
1099
+ }
1100
+
1101
+ // packages/worktree/dist/index.js
1102
+ import * as fs8 from "node:fs";
1103
+ import * as path6 from "node:path";
1104
+ import { exec, execFile } from "node:child_process";
1105
+ import { promisify } from "node:util";
1106
+ var run = promisify(execFile);
1107
+ var shell = promisify(exec);
1108
+ function worktreePath(id) {
1109
+ return path6.join(lobstahHome(), "worktrees", id);
1110
+ }
1111
+ async function git(cwd, ...args) {
1112
+ const { stdout } = await run("git", args, { cwd, env: process.env });
1113
+ return stdout.trim();
1114
+ }
1115
+ async function allocate(repo, id) {
1116
+ const dir = worktreePath(id);
1117
+ if (fs8.existsSync(dir)) {
1118
+ throw new Error(`worktree for ${id} already exists at ${dir} \u2014 never allocate a second`);
1119
+ }
1120
+ if (!fs8.existsSync(repo.path)) {
1121
+ if (!repo.origin)
1122
+ throw new Error(`repo path ${repo.path} missing and no origin configured`);
1123
+ await run("git", ["clone", repo.origin, repo.path], { env: process.env });
1124
+ }
1125
+ await git(repo.path, "fetch", "origin", repo.trunk);
1126
+ await git(repo.path, "worktree", "add", dir, "-b", `lobstah/${id}`, `origin/${repo.trunk}`);
1127
+ for (const cmd of repo.setup ?? []) {
1128
+ await shell(cmd, { cwd: dir, env: { ...process.env, ...repo.env ?? {} } });
1129
+ }
1130
+ return dir;
1131
+ }
1132
+ async function collectEvidence(repo, id) {
1133
+ const dir = worktreePath(id);
1134
+ const branch = await git(dir, "rev-parse", "--abbrev-ref", "HEAD");
1135
+ const log = await git(dir, "log", "--oneline", `origin/${repo.trunk}..HEAD`);
1136
+ return { branch, commits: log ? log.split("\n") : [] };
1137
+ }
1138
+
1139
+ // packages/runner/src/contract.ts
1140
+ function buildPrompt(brief, opts) {
1141
+ const reporting = `Report status by running \`lobstah report ${opts.id} <verb> [note]\` (verbs: ${VERBS.join(", ")}). Attach a PR URL to your final report with \`--pr <url>\`. At natural checkpoints, check for operator messages with \`lobstah inbox ${opts.id}\` \u2014 messages also arrive automatically between your turns.`;
1142
+ const parts = [
1143
+ `You are a dispatched coding agent supervised by lobstah. Dispatch id: ${opts.id}.`,
1144
+ `Work only inside the current directory \u2014 it is an isolated git worktree allocated for this dispatch.`,
1145
+ reporting,
1146
+ `Use \`needs-decision\` when you are blocked on a question only a human can answer, then stop. New operator messages may arrive between your turns as user messages; treat them as instructions from the dispatcher.`,
1147
+ `Commit your work with clear messages. Do not merge anything.`,
1148
+ `--- BRIEF ---`,
1149
+ brief
1150
+ ];
1151
+ if (opts.nudge) parts.push(`--- SUPERVISOR NOTE ---`, opts.nudge);
1152
+ return parts.join("\n\n");
1153
+ }
1154
+
1155
+ // packages/runner/src/index.ts
1156
+ function followUpSession(followUp) {
1157
+ for (const lane of ["work", "chore"]) {
1158
+ const ev = readEvidence(followUp, lane);
1159
+ if (ev.sessionId) return ev.sessionId;
1160
+ }
1161
+ return void 0;
1162
+ }
1163
+ async function main(activeDir, lane) {
1164
+ const id = path7.basename(activeDir);
1165
+ const status = (verb, note) => appendStatus(id, lane, verb, note);
1166
+ const cfg = loadConfig();
1167
+ const descriptor = JSON.parse(fs9.readFileSync(path7.join(activeDir, "descriptor.json"), "utf8"));
1168
+ const resolved = resolveDispatch(descriptor, cfg);
1169
+ const repo = cfg.repos[descriptor.repo];
1170
+ const briefFile = path7.join(activeDir, "brief.md");
1171
+ if (!fs9.existsSync(briefFile)) fs9.writeFileSync(briefFile, descriptor.brief);
1172
+ const brief = fs9.readFileSync(briefFile, "utf8");
1173
+ const attempts = Number(process.env.LOBSTAH_ATTEMPTS ?? "1");
1174
+ const runnerInfo = {
1175
+ pid: process.pid,
1176
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1177
+ attempts
1178
+ };
1179
+ fs9.writeFileSync(path7.join(activeDir, "runner.json"), JSON.stringify(runnerInfo, null, 2));
1180
+ status("working", attempts > 1 ? `attempt ${attempts}` : void 0);
1181
+ appendEvent(id, lane, { at: (/* @__PURE__ */ new Date()).toISOString(), type: "runner", data: { pid: process.pid, attempts } });
1182
+ const wtFile = path7.join(activeDir, "worktree.json");
1183
+ let cwd;
1184
+ if (fs9.existsSync(wtFile)) {
1185
+ cwd = JSON.parse(fs9.readFileSync(wtFile, "utf8")).path;
1186
+ if (!fs9.existsSync(cwd)) throw new Error(`recorded worktree ${cwd} is gone`);
1187
+ } else if (fs9.existsSync(worktreePath(id))) {
1188
+ throw new Error(`unrecorded worktree already exists for ${id} \u2014 refusing to proceed`);
1189
+ } else {
1190
+ cwd = await allocate(repo, id);
1191
+ fs9.writeFileSync(wtFile, JSON.stringify({ path: cwd }, null, 2));
1192
+ }
1193
+ const resumeSession = process.env.LOBSTAH_RESUME ?? (descriptor.followUp ? followUpSession(descriptor.followUp) : void 0);
1194
+ const adapter = loadAdapter(resolved.harness);
1195
+ const prompt = buildPrompt(brief, { id, nudge: process.env.LOBSTAH_NUDGE });
1196
+ const binDir = path7.resolve(path7.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "bin");
1197
+ const workerPath = fs9.existsSync(path7.join(binDir, "lobstah")) ? `${binDir}${path7.delimiter}${process.env.PATH ?? ""}` : void 0;
1198
+ const run2 = await adapter.start({
1199
+ id,
1200
+ cwd,
1201
+ prompt,
1202
+ model: resolved.model,
1203
+ effort: resolved.effort,
1204
+ limits: resolved.limits,
1205
+ env: {
1206
+ ...resolved.env,
1207
+ LOBSTAH_HOME: lobstahHome(),
1208
+ ...workerPath ? { PATH: workerPath } : {}
1209
+ },
1210
+ flags: resolved.flags,
1211
+ resumeSession
1212
+ });
1213
+ let wallClockHit = false;
1214
+ const wallTimer = resolved.limits.wallClockSecs ? setTimeout(() => {
1215
+ wallClockHit = true;
1216
+ run2.kill();
1217
+ }, resolved.limits.wallClockSecs * 1e3) : void 0;
1218
+ let cancelled = false;
1219
+ for await (const ev of run2.events) {
1220
+ appendEvent(id, lane, ev);
1221
+ if (ev.type === "session" && ev.data?.sessionId) {
1222
+ mergeEvidence(id, lane, { sessionId: String(ev.data.sessionId) });
1223
+ }
1224
+ if (ev.type === "turn-end") {
1225
+ if (cancelRequested(id, lane)) {
1226
+ cancelled = true;
1227
+ run2.kill();
1228
+ continue;
1229
+ }
1230
+ const msgs = unhandled(id, lane);
1231
+ if (msgs.length > 0) {
1232
+ for (const m of msgs) {
1233
+ run2.send(m.text);
1234
+ acknowledge(id, lane, m.file);
1235
+ }
1236
+ } else {
1237
+ run2.end();
1238
+ }
1239
+ }
1240
+ }
1241
+ const result = await run2.done;
1242
+ if (wallTimer) clearTimeout(wallTimer);
1243
+ try {
1244
+ const gitEvidence = await collectEvidence(repo, id);
1245
+ console.log(`[runner] git evidence: ${JSON.stringify(gitEvidence)}`);
1246
+ mergeEvidence(id, lane, { ...gitEvidence, sessionId: result.sessionId ?? readEvidence(id, lane).sessionId });
1247
+ console.log(`[runner] evidence after merge: ${JSON.stringify(readEvidence(id, lane))}`);
1248
+ } catch (err) {
1249
+ mergeEvidence(id, lane, {
1250
+ note: `evidence collection failed: ${err instanceof Error ? err.message : String(err)}`.slice(0, 300)
1251
+ });
1252
+ }
1253
+ const lastVerb = readStatusLog(id, lane).at(-1)?.verb;
1254
+ if (cancelled) {
1255
+ status("failed", "cancelled by operator");
1256
+ } else if (wallClockHit) {
1257
+ status("failed", "wall-clock limit exceeded");
1258
+ } else if (result.error) {
1259
+ status("failed", result.error.slice(0, 500));
1260
+ } else if (!lastVerb || !TERMINAL_VERBS.includes(lastVerb)) {
1261
+ status("done");
1262
+ }
1263
+ complete(id, lane);
1264
+ }
1265
+ var [activeDirArg, laneArg] = process.argv.slice(2);
1266
+ if (activeDirArg) {
1267
+ const lane = laneArg === "chore" ? "chore" : "work";
1268
+ main(activeDirArg, lane).catch((err) => {
1269
+ const id = path7.basename(activeDirArg);
1270
+ try {
1271
+ appendStatus(id, lane, "failed", String(err instanceof Error ? err.message : err).slice(0, 500));
1272
+ fs9.renameSync(activeDirArg, path7.join(laneDirs(lane).done, id));
1273
+ } catch {
1274
+ }
1275
+ process.exitCode = 1;
1276
+ });
1277
+ }
1278
+ export {
1279
+ main
1280
+ };
1281
+ /*! Bundled license information:
1282
+
1283
+ smol-toml/dist/date.js:
1284
+ smol-toml/dist/error.js:
1285
+ smol-toml/dist/util.js:
1286
+ smol-toml/dist/primitive.js:
1287
+ smol-toml/dist/extract.js:
1288
+ smol-toml/dist/struct.js:
1289
+ smol-toml/dist/parse.js:
1290
+ smol-toml/dist/stringify.js:
1291
+ smol-toml/dist/index.js:
1292
+ (*!
1293
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1294
+ * SPDX-License-Identifier: BSD-3-Clause
1295
+ *
1296
+ * Redistribution and use in source and binary forms, with or without
1297
+ * modification, are permitted provided that the following conditions are met:
1298
+ *
1299
+ * 1. Redistributions of source code must retain the above copyright notice, this
1300
+ * list of conditions and the following disclaimer.
1301
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1302
+ * this list of conditions and the following disclaimer in the
1303
+ * documentation and/or other materials provided with the distribution.
1304
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1305
+ * may be used to endorse or promote products derived from this software without
1306
+ * specific prior written permission.
1307
+ *
1308
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1309
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1310
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1311
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1312
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1313
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1314
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1315
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1316
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1317
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1318
+ *)
1319
+ */