@codeworksh/harness 0.7.0 → 0.8.0-canary.125.1.gb9ae8bf0

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/effect.mjs CHANGED
@@ -199,9 +199,14 @@ const IDFromDb$1 = Schema.String.pipe(Schema.brand("Session.ID"));
199
199
  /**
200
200
  * Why an execution stopped. Supplied by whoever asked for the interruption --
201
201
  * a stop the user asked for and a stop the process imposed on shutdown are
202
- * different facts, and inspecting the cause cannot tell them apart.
202
+ * different facts, and inspecting the cause cannot tell them apart. `crash` is
203
+ * the startup sweep's: the process that ran the execution died without ending it.
203
204
  */
204
- const InterruptReason = Schema.Literals(["user", "shutdown"]);
205
+ const InterruptReason = Schema.Literals([
206
+ "user",
207
+ "shutdown",
208
+ "crash"
209
+ ]);
205
210
  const JsonObject = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
206
211
  const MessageEnvelopeIdentity = Schema.fromJsonString(Schema.Struct({ messageId: Schema.String }));
207
212
  const CompactionData = Schema.fromJsonString(Schema.Struct({
@@ -244,6 +249,83 @@ const Usage = Schema.Struct({
244
249
  });
245
250
  const AssistantEnvelopeUsage = Schema.fromJsonString(Schema.Struct({ usage: Usage }));
246
251
  //#endregion
252
+ //#region src/session/failure.ts
253
+ /**
254
+ * The public description of a failed execution.
255
+ *
256
+ * Open by design: `type` is a kebab-case category ending in `-error`, not a closed union.
257
+ * A client older than the server degrades to the message instead of failing to
258
+ * decode, and a new category is an additive change. The typed cause stays
259
+ * server-side -- this is what crosses the wire.
260
+ */
261
+ const Error$1 = Schema.Struct({
262
+ type: Schema.String,
263
+ message: Schema.String,
264
+ /** Provider HTTP status, when the failure came from one. */
265
+ status: (0, schema_exports$9.optional)(Schema.Int)
266
+ });
267
+ const providerCategory = (tag) => {
268
+ switch (tag) {
269
+ case "Runner.ProviderAuthenticationError": return "provider-authentication-error";
270
+ case "Runner.ProviderAuthorizationError": return "provider-authorization-error";
271
+ case "Runner.ProviderConfigurationError": return "provider-configuration-error";
272
+ case "Runner.ProviderModelUnavailableError": return "provider-model-unavailable-error";
273
+ case "Runner.ProviderRateLimitError": return "provider-rate-limit-error";
274
+ case "Runner.ProviderQuotaError": return "provider-quota-error";
275
+ case "Runner.ProviderInvalidRequestError": return "provider-invalid-request-error";
276
+ case "Runner.ProviderContentPolicyError": return "provider-content-filter-error";
277
+ case "Runner.ProviderTimeoutError": return "provider-timeout-error";
278
+ case "Runner.ProviderTransportError": return "provider-transport-error";
279
+ case "Runner.ProviderUnavailableError": return "provider-unavailable-error";
280
+ case "Runner.ProviderInvalidResponseError": return "provider-invalid-response-error";
281
+ default: return "provider-unknown-error";
282
+ }
283
+ };
284
+ const category = (tag) => {
285
+ switch (tag) {
286
+ case "Runner.ModelCatalogError": return "model-catalog-error";
287
+ case "Runner.ModelNotFoundError": return "model-not-found-error";
288
+ case "Runner.LLMStreamError": return "llm-stream-error";
289
+ case "ContextDecodeError": return "context-decode-error";
290
+ case "ContextEncodeError": return "context-encode-error";
291
+ case "SessionNotFoundError": return "session-not-found-error";
292
+ case "SessionLinkedSpaceNotFoundError": return "session-space-not-found-error";
293
+ case "SettingsError": return "settings-error";
294
+ case "State.SnapshotError": return "state-snapshot-error";
295
+ case "Runner.SandboxDirectoryNotFoundError": return "sandbox-directory-not-found-error";
296
+ case "SandboxFileSystemError": return "sandbox-filesystem-error";
297
+ case "SandboxNotFoundError":
298
+ case "SandboxDriverNotRegisteredError":
299
+ case "SandboxUnavailError":
300
+ case "SandboxRemovedError":
301
+ case "SandboxProviderError": return "sandbox-mount-error";
302
+ default: return "unknown-error";
303
+ }
304
+ };
305
+ const message$1 = (cause) => cause instanceof globalThis.Error ? cause.message : typeof cause === "string" ? cause : "Session execution failed";
306
+ /** Projects a typed drain failure onto the category vocabulary clients see. */
307
+ const fromCause = (cause) => {
308
+ const tag = Predicate.hasProperty(cause, "_tag") && typeof cause._tag === "string" ? cause._tag : void 0;
309
+ if (tag === void 0) return {
310
+ type: "unknown-error",
311
+ message: message$1(cause)
312
+ };
313
+ if (tag === "Runner.ProviderError") {
314
+ const reason = Predicate.hasProperty(cause, "reason") ? cause.reason : void 0;
315
+ const reasonTag = Predicate.hasProperty(reason, "_tag") && typeof reason._tag === "string" ? reason._tag : "";
316
+ const status = Predicate.hasProperty(reason, "status") && typeof reason.status === "number" ? reason.status : void 0;
317
+ return {
318
+ type: providerCategory(reasonTag),
319
+ message: message$1(cause),
320
+ ...status === void 0 ? {} : { status }
321
+ };
322
+ }
323
+ return {
324
+ type: category(tag),
325
+ message: message$1(cause)
326
+ };
327
+ };
328
+ //#endregion
247
329
  //#region src/thread/schema.ts
248
330
  var schema_exports$2 = /* @__PURE__ */ __exportAll({
249
331
  Execution: () => Execution,
@@ -251,6 +333,10 @@ var schema_exports$2 = /* @__PURE__ */ __exportAll({
251
333
  IDFromDb: () => IDFromDb,
252
334
  MAIN: () => MAIN,
253
335
  OriginKind: () => OriginKind,
336
+ RunError: () => RunError,
337
+ RunFailedReason: () => RunFailedReason,
338
+ RunOutcome: () => RunOutcome,
339
+ RunState: () => RunState,
254
340
  TITLE_MAX_LENGTH: () => 48,
255
341
  ThreadSchema: () => schema_exports$2,
256
342
  titleFrom: () => titleFrom
@@ -268,6 +354,35 @@ const OriginKind = Schema.Literals([
268
354
  * ended any other way leaves none.
269
355
  */
270
356
  const Execution = Schema.Literals(["running", "closed"]);
357
+ /**
358
+ * Where the thread's run is, projected from its lifecycle events: `starting` from
359
+ * `execution.started` until the first `llm.started`, `running` after it, `idle` once it ended.
360
+ */
361
+ const RunState = Schema.Literals([
362
+ "idle",
363
+ "starting",
364
+ "running"
365
+ ]);
366
+ const RunOutcome = Schema.Literals([
367
+ "succeeded",
368
+ "failed",
369
+ "interrupted"
370
+ ]);
371
+ /** Why a run ended without its answer and is not resumed; see `session.run.failed`. */
372
+ const RunFailedReason = Schema.Literals([
373
+ "crashloop",
374
+ "interrupted",
375
+ "truncated"
376
+ ]);
377
+ /** Why the last run did not succeed; stored as `thread.run_error` JSON. */
378
+ const RunError = Schema.Union([
379
+ Schema.TaggedStruct("failed", { error: Error$1 }),
380
+ Schema.TaggedStruct("runFailed", {
381
+ reason: RunFailedReason,
382
+ message: Schema.String
383
+ }),
384
+ Schema.TaggedStruct("interrupted", { reason: InterruptReason })
385
+ ]);
271
386
  /** `main` names a session's main thread wherever a thread id is accepted from a person. */
272
387
  const MAIN = "main";
273
388
  /**
@@ -293,6 +408,7 @@ const Timestamps = {
293
408
  updatedAt: Model.DateTimeUpdateFromNumber
294
409
  };
295
410
  const Metadata = Schema.Record(Schema.String, Schema.String);
411
+ const Rev = schema_exports$9.NonNegativeInt;
296
412
  const entryTypes = [
297
413
  "user",
298
414
  "assistant",
@@ -345,7 +461,8 @@ var ProjectRow = class extends Model.Class("ProjectRow")({
345
461
  id: Schema.String,
346
462
  name: Schema.String,
347
463
  status: schema_exports$10.ProjectSchema.Status,
348
- ...Timestamps
464
+ ...Timestamps,
465
+ rev: Rev
349
466
  }) {};
350
467
  /**
351
468
  * A durable filesystem namespace. The row is the whole durable model — reference
@@ -380,7 +497,8 @@ var SpaceRow = class extends Model.Class("SpaceRow")({
380
497
  kind: schema_exports$7.SpaceSchema.Kind,
381
498
  env: Model.FieldOption(instance_exports.SandboxInstance.ID),
382
499
  status: schema_exports$7.SpaceSchema.Status,
383
- ...Timestamps
500
+ ...Timestamps,
501
+ rev: Rev
384
502
  }) {};
385
503
  var SessionRow = class extends Model.Class("SessionRow")({
386
504
  id: IDFromDb$1,
@@ -390,7 +508,8 @@ var SessionRow = class extends Model.Class("SessionRow")({
390
508
  hostDir: Model.FieldOption(schema_exports$9.AbsolutePath),
391
509
  tag: Model.FieldOption(Schema.String),
392
510
  metadata: Model.FieldOption(Model.JsonFromString(Metadata)),
393
- ...Timestamps
511
+ ...Timestamps,
512
+ rev: Rev
394
513
  }) {};
395
514
  var ThreadRow = class extends Model.Class("ThreadRow")({
396
515
  id: IDFromDb,
@@ -401,6 +520,12 @@ var ThreadRow = class extends Model.Class("ThreadRow")({
401
520
  originCallId: Model.FieldOption(Schema.String),
402
521
  title: Model.FieldOption(Schema.String),
403
522
  execution: Model.FieldOption(Execution),
523
+ runState: Model.GeneratedByDb(RunState),
524
+ runStateAt: Model.GeneratedByDb(Schema.OptionFromNullOr(Schema.DateTimeUtcFromMillis)),
525
+ runStartedAt: Model.GeneratedByDb(Schema.OptionFromNullOr(Schema.DateTimeUtcFromMillis)),
526
+ runEndedAt: Model.GeneratedByDb(Schema.OptionFromNullOr(Schema.DateTimeUtcFromMillis)),
527
+ runOutcome: Model.GeneratedByDb(Schema.OptionFromNullOr(RunOutcome)),
528
+ runError: Model.GeneratedByDb(Schema.OptionFromNullOr(Schema.fromJsonString(RunError))),
404
529
  restarts: Model.GeneratedByDb(Schema.Int),
405
530
  attempt: Model.FieldOption(Schema.Int),
406
531
  cost: Model.GeneratedByDb(Schema.Finite),
@@ -409,7 +534,8 @@ var ThreadRow = class extends Model.Class("ThreadRow")({
409
534
  tokensCacheRead: Model.GeneratedByDb(Schema.Int),
410
535
  tokensCacheWrite: Model.GeneratedByDb(Schema.Int),
411
536
  createdSeq: schema_exports$9.NonNegativeInt,
412
- ...Timestamps
537
+ ...Timestamps,
538
+ rev: Rev
413
539
  }) {};
414
540
  var InboxRow = class extends Model.Class("InboxRow")({
415
541
  id: Schema.String,
@@ -421,7 +547,8 @@ var InboxRow = class extends Model.Class("InboxRow")({
421
547
  admittedSeq: Schema.Int,
422
548
  promotedSeq: Model.FieldOption(Schema.Int),
423
549
  cancelledSeq: Model.FieldOption(Schema.Int),
424
- createdAt: Model.DateTimeInsertFromNumber
550
+ createdAt: Model.DateTimeInsertFromNumber,
551
+ rev: Rev
425
552
  }) {};
426
553
  var EntryRow = class extends Model.Class("EntryRow")({
427
554
  id: Schema.String,
@@ -434,7 +561,8 @@ var EntryRow = class extends Model.Class("EntryRow")({
434
561
  data: Schema.String,
435
562
  label: Model.FieldOption(Schema.String),
436
563
  metadata: Model.FieldOption(Model.JsonFromString(Metadata)),
437
- ...Timestamps
564
+ ...Timestamps,
565
+ rev: Rev
438
566
  }) {};
439
567
  var EntryPartRow = class extends Model.Class("EntryPartRow")({
440
568
  id: Schema.String,
@@ -465,12 +593,61 @@ var DocumentRevisionRow = class extends Model.Class("DocumentRevisionRow")({
465
593
  value: Model.JsonFromString(Schema.Record(Schema.String, Schema.Json))
466
594
  }) {};
467
595
  //#endregion
596
+ //#region src/db/store.ts
597
+ var store_exports = /* @__PURE__ */ __exportAll({
598
+ Service: () => Service$22,
599
+ Store: () => store_exports,
600
+ layer: () => layer$32
601
+ });
602
+ var Service$22 = class extends Context.Service()("@codeworksh/harness/db/store/Service") {};
603
+ const Taken = Context.Reference("@codeworksh/harness/db/store/Taken", { defaultValue: () => void 0 });
604
+ const layer$32 = Layer.effect(Service$22, Effect.gen(function* () {
605
+ const sql = yield* SqlClient.SqlClient;
606
+ const wakes = /* @__PURE__ */ new Set();
607
+ const ring = Effect.forEach(wakes, (wake) => PubSub.publish(wake, void 0), { discard: true });
608
+ const write = (effect) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
609
+ if ((yield* Taken) !== void 0) return yield* restore(effect);
610
+ const taken = { rev: void 0 };
611
+ const result = yield* sql.withTransaction(restore(Effect.provideService(effect, Taken, taken)));
612
+ if (taken.rev !== void 0) yield* ring;
613
+ return result;
614
+ }));
615
+ const rev = Effect.gen(function* () {
616
+ const taken = yield* Taken;
617
+ if (taken === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("Store.rev outside Store.write"));
618
+ if (taken.rev === void 0) {
619
+ const [row] = yield* sql`UPDATE store SET rev = rev + 1 RETURNING rev`;
620
+ if (row === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("store row is missing"));
621
+ taken.rev = row.rev;
622
+ }
623
+ return taken.rev;
624
+ }).pipe(Effect.orDie);
625
+ const head = Effect.gen(function* () {
626
+ const [row] = yield* sql`SELECT id, rev FROM store`;
627
+ if (row === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("store row is missing"));
628
+ return row;
629
+ }).pipe(Effect.orDie);
630
+ const wake = Effect.gen(function* () {
631
+ const pubsub = yield* PubSub.sliding(1);
632
+ const subscription = yield* PubSub.subscribe(pubsub);
633
+ yield* Effect.acquireRelease(Effect.sync(() => wakes.add(pubsub)), () => Effect.sync(() => wakes.delete(pubsub)).pipe(Effect.andThen(PubSub.shutdown(pubsub))));
634
+ return subscription;
635
+ });
636
+ return Service$22.of({
637
+ write,
638
+ rev,
639
+ head,
640
+ wake
641
+ });
642
+ }));
643
+ //#endregion
468
644
  //#region src/document/document.ts
469
645
  var Service$21 = class extends Context.Service()("@codeworksh/harness/document/document/Service") {};
470
646
  const decodeAgent = Schema.decodeUnknownEffect(Agent);
471
647
  const encodeAgent = Schema.encodeEffect(Agent);
472
648
  const layer$31 = Layer.effect(Service$21, Effect.gen(function* () {
473
649
  const sql = yield* SqlClient.SqlClient;
650
+ const store = yield* Service$22;
474
651
  const insertDocument = SqlSchema.void({
475
652
  Request: DocumentRow.insert,
476
653
  execute: (row) => sql`INSERT INTO document ${sql.insert(row)}`
@@ -522,8 +699,14 @@ const layer$31 = Layer.effect(Service$21, Effect.gen(function* () {
522
699
  ...revision
523
700
  });
524
701
  const document = yield* findById(documentId);
525
- if (Option.isSome(document) && Option.getOrUndefined(document.value.history) === "latest") yield* sql`DELETE FROM revision WHERE document_id = ${documentId} AND seq < ${revision.seq}`;
526
- }, Effect.orDie);
702
+ if (Option.isNone(document)) return yield* Effect.die(`document ${documentId} not found`);
703
+ if (Option.getOrUndefined(document.value.history) === "latest") yield* sql`DELETE FROM revision WHERE document_id = ${documentId} AND seq < ${revision.seq}`;
704
+ const rev = yield* store.rev;
705
+ yield* Option.match(document.value.threadId, {
706
+ onNone: () => sql`UPDATE thread SET rev = ${rev} WHERE session_id = ${document.value.sessionId}`,
707
+ onSome: (threadId) => sql`UPDATE thread SET rev = ${rev} WHERE id = ${threadId}`
708
+ });
709
+ }, store.write, Effect.orDie);
527
710
  const create = Effect.fn("Document.create")(function* (input) {
528
711
  const { definition } = input;
529
712
  const row = DocumentRow.insert.make({
@@ -543,7 +726,7 @@ const layer$31 = Layer.effect(Service$21, Effect.gen(function* () {
543
726
  value: input.value
544
727
  });
545
728
  return new DocumentRow(row);
546
- }, Effect.orDie);
729
+ }, store.write, Effect.orDie);
547
730
  const find = Effect.fn("Document.find")(function* (threadId, kind) {
548
731
  return yield* findLive({
549
732
  threadId,
@@ -578,7 +761,7 @@ const layer$31 = Layer.effect(Service$21, Effect.gen(function* () {
578
761
  version: agent.version,
579
762
  value: yield* encodeAgent(next).pipe(Effect.orDie)
580
763
  });
581
- });
764
+ }, store.write, Effect.orDie);
582
765
  return Service$21.of({
583
766
  create,
584
767
  find,
@@ -592,83 +775,6 @@ const layer$31 = Layer.effect(Service$21, Effect.gen(function* () {
592
775
  });
593
776
  }));
594
777
  //#endregion
595
- //#region src/session/failure.ts
596
- /**
597
- * The public description of a failed execution.
598
- *
599
- * Open by design: `type` is a kebab-case category ending in `-error`, not a closed union.
600
- * A client older than the server degrades to the message instead of failing to
601
- * decode, and a new category is an additive change. The typed cause stays
602
- * server-side -- this is what crosses the wire.
603
- */
604
- const Error$1 = Schema.Struct({
605
- type: Schema.String,
606
- message: Schema.String,
607
- /** Provider HTTP status, when the failure came from one. */
608
- status: (0, schema_exports$9.optional)(Schema.Int)
609
- });
610
- const providerCategory = (tag) => {
611
- switch (tag) {
612
- case "Runner.ProviderAuthenticationError": return "provider-authentication-error";
613
- case "Runner.ProviderAuthorizationError": return "provider-authorization-error";
614
- case "Runner.ProviderConfigurationError": return "provider-configuration-error";
615
- case "Runner.ProviderModelUnavailableError": return "provider-model-unavailable-error";
616
- case "Runner.ProviderRateLimitError": return "provider-rate-limit-error";
617
- case "Runner.ProviderQuotaError": return "provider-quota-error";
618
- case "Runner.ProviderInvalidRequestError": return "provider-invalid-request-error";
619
- case "Runner.ProviderContentPolicyError": return "provider-content-filter-error";
620
- case "Runner.ProviderTimeoutError": return "provider-timeout-error";
621
- case "Runner.ProviderTransportError": return "provider-transport-error";
622
- case "Runner.ProviderUnavailableError": return "provider-unavailable-error";
623
- case "Runner.ProviderInvalidResponseError": return "provider-invalid-response-error";
624
- default: return "provider-unknown-error";
625
- }
626
- };
627
- const category = (tag) => {
628
- switch (tag) {
629
- case "Runner.ModelCatalogError": return "model-catalog-error";
630
- case "Runner.ModelNotFoundError": return "model-not-found-error";
631
- case "Runner.LLMStreamError": return "llm-stream-error";
632
- case "ContextDecodeError": return "context-decode-error";
633
- case "ContextEncodeError": return "context-encode-error";
634
- case "SessionNotFoundError": return "session-not-found-error";
635
- case "SessionLinkedSpaceNotFoundError": return "session-space-not-found-error";
636
- case "SettingsError": return "settings-error";
637
- case "State.SnapshotError": return "state-snapshot-error";
638
- case "Runner.SandboxDirectoryNotFoundError": return "sandbox-directory-not-found-error";
639
- case "SandboxFileSystemError": return "sandbox-filesystem-error";
640
- case "SandboxNotFoundError":
641
- case "SandboxDriverNotRegisteredError":
642
- case "SandboxUnavailError":
643
- case "SandboxRemovedError":
644
- case "SandboxProviderError": return "sandbox-mount-error";
645
- default: return "unknown-error";
646
- }
647
- };
648
- const message$1 = (cause) => cause instanceof globalThis.Error ? cause.message : typeof cause === "string" ? cause : "Session execution failed";
649
- /** Projects a typed drain failure onto the category vocabulary clients see. */
650
- const fromCause = (cause) => {
651
- const tag = Predicate.hasProperty(cause, "_tag") && typeof cause._tag === "string" ? cause._tag : void 0;
652
- if (tag === void 0) return {
653
- type: "unknown-error",
654
- message: message$1(cause)
655
- };
656
- if (tag === "Runner.ProviderError") {
657
- const reason = Predicate.hasProperty(cause, "reason") ? cause.reason : void 0;
658
- const reasonTag = Predicate.hasProperty(reason, "_tag") && typeof reason._tag === "string" ? reason._tag : "";
659
- const status = Predicate.hasProperty(reason, "status") && typeof reason.status === "number" ? reason.status : void 0;
660
- return {
661
- type: providerCategory(reasonTag),
662
- message: message$1(cause),
663
- ...status === void 0 ? {} : { status }
664
- };
665
- }
666
- return {
667
- type: category(tag),
668
- message: message$1(cause)
669
- };
670
- };
671
- //#endregion
672
778
  //#region src/session/message/schema.ts
673
779
  var schema_exports$6 = /* @__PURE__ */ __exportAll({
674
780
  ID: () => ID,
@@ -863,6 +969,7 @@ const TurnAborted = schema_exports$11.EventSchema.define({
863
969
  */
864
970
  const RetryScheduled = schema_exports$11.EventSchema.define({
865
971
  type: "session.retry.scheduled",
972
+ ...durableOptions,
866
973
  schema: {
867
974
  ...baseOptions,
868
975
  attempt: schema_exports$9.NonNegativeInt,
@@ -894,12 +1001,18 @@ const LLMTextStart = schema_exports$11.EventSchema.define({
894
1001
  type: "session.llm.text.start",
895
1002
  schema: LLMPartFields
896
1003
  });
1004
+ /**
1005
+ * `offset` is the part's text length before this delta, in JS string length (UTF-16 code units),
1006
+ * so a client compares it with its draft's `text.length`. A delta at 0 starts its part.
1007
+ */
1008
+ const LLMDeltaFields = {
1009
+ ...LLMPartFields,
1010
+ offset: schema_exports$9.NonNegativeInt,
1011
+ delta: Schema.String
1012
+ };
897
1013
  const LLMTextDelta = schema_exports$11.EventSchema.define({
898
1014
  type: "session.llm.text.delta",
899
- schema: {
900
- ...LLMPartFields,
901
- delta: Schema.String
902
- }
1015
+ schema: LLMDeltaFields
903
1016
  });
904
1017
  const LLMTextEnd = schema_exports$11.EventSchema.define({
905
1018
  type: "session.llm.text.end",
@@ -914,10 +1027,7 @@ const LLMThinkingStart = schema_exports$11.EventSchema.define({
914
1027
  });
915
1028
  const LLMThinkingDelta = schema_exports$11.EventSchema.define({
916
1029
  type: "session.llm.thinking.delta",
917
- schema: {
918
- ...LLMPartFields,
919
- delta: Schema.String
920
- }
1030
+ schema: LLMDeltaFields
921
1031
  });
922
1032
  const LLMThinkingEnd = schema_exports$11.EventSchema.define({
923
1033
  type: "session.llm.thinking.end",
@@ -1013,14 +1123,21 @@ const ToolSettled = schema_exports$11.EventSchema.define({
1013
1123
  */
1014
1124
  const ExecutionStarted = schema_exports$11.EventSchema.define({
1015
1125
  type: "session.execution.started",
1016
- schema: baseOptions
1126
+ ...durableOptions,
1127
+ /** `resumed`: recovery started it after a restart, for a run the last process left unfinished. */
1128
+ schema: {
1129
+ ...baseOptions,
1130
+ resumed: Schema.Boolean
1131
+ }
1017
1132
  });
1018
1133
  const ExecutionSucceeded = schema_exports$11.EventSchema.define({
1019
1134
  type: "session.execution.succeeded",
1135
+ ...durableOptions,
1020
1136
  schema: baseOptions
1021
1137
  });
1022
1138
  const ExecutionFailed = schema_exports$11.EventSchema.define({
1023
1139
  type: "session.execution.failed",
1140
+ ...durableOptions,
1024
1141
  schema: {
1025
1142
  ...baseOptions,
1026
1143
  error: Error$1
@@ -1028,6 +1145,7 @@ const ExecutionFailed = schema_exports$11.EventSchema.define({
1028
1145
  });
1029
1146
  const ExecutionInterrupted = schema_exports$11.EventSchema.define({
1030
1147
  type: "session.execution.interrupted",
1148
+ ...durableOptions,
1031
1149
  schema: {
1032
1150
  ...baseOptions,
1033
1151
  reason: InterruptReason
@@ -1043,11 +1161,7 @@ const RunFailed = schema_exports$11.EventSchema.define({
1043
1161
  ...durableOptions,
1044
1162
  schema: {
1045
1163
  ...baseOptions,
1046
- reason: Schema.Literals([
1047
- "crashloop",
1048
- "interrupted",
1049
- "truncated"
1050
- ]),
1164
+ reason: RunFailedReason,
1051
1165
  message: Schema.String
1052
1166
  }
1053
1167
  });
@@ -1139,7 +1253,7 @@ const Definitions = schema_exports$11.EventSchema.inventory(ExecutionStarted, Ex
1139
1253
  * itself a decision to publish it.
1140
1254
  */
1141
1255
  const PublicDefinitions = Definitions;
1142
- const DurableDefinitions = schema_exports$11.EventSchema.inventory(PromptAdmitted, Prompted, PromptCancelled, PromptUpdated, SessionCreated, ThreadForked, ThreadConfigured, SystemChanged, TurnEnded, LLMStarted, LLMProgress, LLMEnded, LLMFailed, RunFailed, ToolSettled);
1256
+ const DurableDefinitions = schema_exports$11.EventSchema.inventory(ExecutionStarted, ExecutionSucceeded, ExecutionFailed, ExecutionInterrupted, PromptAdmitted, Prompted, PromptCancelled, PromptUpdated, SessionCreated, ThreadForked, ThreadConfigured, SystemChanged, TurnEnded, RetryScheduled, LLMStarted, LLMProgress, LLMEnded, LLMFailed, RunFailed, ToolSettled);
1143
1257
  const Manifest$2 = {
1144
1258
  definitions: schema_exports$11.EventSchema.durable([...DurableDefinitions]),
1145
1259
  schema: Schema.Union([...DurableDefinitions], { mode: "oneOf" }).pipe(Schema.toTaggedUnion("type"))
@@ -1163,6 +1277,7 @@ var SubscriptionOverflowError = class extends Schema.TaggedError()("Subscription
1163
1277
  var Service$20 = class extends Context.Service()("@codeworksh/harness/event/event/Service") {};
1164
1278
  const layer$30 = Layer.effect(Service$20, Effect.gen(function* () {
1165
1279
  const sql = yield* SqlClient.SqlClient;
1280
+ const store = yield* Service$22;
1166
1281
  const pubsub = { durable: /* @__PURE__ */ new Map() };
1167
1282
  const subscriptions = /* @__PURE__ */ new Set();
1168
1283
  const projectors = /* @__PURE__ */ new Map();
@@ -1338,7 +1453,7 @@ const layer$30 = Layer.effect(Service$20, Effect.gen(function* () {
1338
1453
  message: `Expected string aggregate field ${durable.aggregate}`
1339
1454
  }));
1340
1455
  const encoded = yield* Schema.encodeUnknownEffect(definition.data)(event.data);
1341
- const committed = yield* sql.withTransaction(Effect.gen(function* () {
1456
+ const committed = yield* store.write(Effect.gen(function* () {
1342
1457
  const { seq } = yield* bumpSequence(aggregateId);
1343
1458
  const existing = yield* findEventById(event.id);
1344
1459
  if (Option.isSome(existing)) return yield* Effect.die(new InvalidDurableEventError({
@@ -1521,17 +1636,23 @@ var ForkError = class extends Schema.TaggedError()("ForkError", {
1521
1636
  };
1522
1637
  var Service$19 = class extends Context.Service()("@codeworksh/harness/thread/thread/Service") {};
1523
1638
  const messageTypes = new Set(messageEntryTypes);
1639
+ const SizedEntryRow = Schema.Struct({
1640
+ ...EntryRow.fields,
1641
+ size: schema_exports$9.NonNegativeInt
1642
+ });
1524
1643
  const decodeEnvelopeUsage = Schema.decodeUnknownEffect(AssistantEnvelopeUsage);
1525
1644
  const decodeMessageEnvelopeIdentity = Schema.decodeUnknownEffect(MessageEnvelopeIdentity);
1526
1645
  const decodeCompactionData$1 = Schema.decodeUnknownEffect(CompactionData);
1527
1646
  const decodeJsonObject$1 = Schema.decodeUnknownEffect(JsonObject);
1528
1647
  const encodeJsonObject$1 = Schema.encodeEffect(JsonObject);
1648
+ const encodeRunError = Schema.encodeEffect(Schema.fromJsonString(RunError));
1529
1649
  const decodeUserText = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({
1530
1650
  type: Schema.Literal("text"),
1531
1651
  text: Schema.String
1532
1652
  })));
1533
1653
  const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1534
1654
  const sql = yield* SqlClient.SqlClient;
1655
+ const store = yield* Service$22;
1535
1656
  const events = yield* Service$20;
1536
1657
  const documents = yield* Service$21;
1537
1658
  const findThread = SqlSchema.findOneOption({
@@ -1563,15 +1684,29 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1563
1684
  Result: EntryRow,
1564
1685
  execute: (id) => sql`SELECT * FROM entry WHERE id = ${id}`
1565
1686
  });
1687
+ const sized = sql`e.*, (SELECT coalesce(sum(length(CAST(p.data AS BLOB))), 0) FROM part p WHERE p.entry_id = e.id) AS size`;
1688
+ const findSized = SqlSchema.findOneOption({
1689
+ Request: Schema.String,
1690
+ Result: SizedEntryRow,
1691
+ execute: (id) => sql`SELECT ${sized} FROM entry e WHERE e.id = ${id}`
1692
+ });
1693
+ const findCut = SqlSchema.findOneOption({
1694
+ Request: Schema.String,
1695
+ Result: Schema.Struct({ cut: schema_exports$9.NonNegativeInt }),
1696
+ execute: (threadId) => sql`
1697
+ SELECT e.committed_seq AS cut FROM thread t JOIN entry e ON e.id = t.origin_entry_id
1698
+ WHERE t.id = ${threadId} AND e.committed_seq IS NOT NULL
1699
+ `
1700
+ });
1566
1701
  const insertEntry = SqlSchema.findAll({
1567
1702
  Request: EntryRow.insert,
1568
1703
  Result: Schema.Struct({ id: Schema.String }),
1569
1704
  execute: (row) => sql`
1570
- INSERT INTO entry (id, session_id, thread_id, seq, committed_seq, type, state, data, label, metadata, created_at, updated_at)
1705
+ INSERT INTO entry (id, session_id, thread_id, seq, committed_seq, type, state, data, label, metadata, created_at, updated_at, rev)
1571
1706
  SELECT
1572
1707
  ${row.id}, ${row.sessionId}, ${row.threadId}, ${row.seq}, ${row.committedSeq ?? null},
1573
1708
  ${row.type}, ${row.state}, ${row.data}, ${row.label ?? null}, ${row.metadata ?? null},
1574
- ${row.createdAt}, ${row.updatedAt}
1709
+ ${row.createdAt}, ${row.updatedAt}, ${row.rev}
1575
1710
  WHERE NOT EXISTS (
1576
1711
  SELECT 1 FROM entry WHERE thread_id = ${row.threadId} AND seq >= ${row.seq}
1577
1712
  )
@@ -1582,28 +1717,51 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1582
1717
  Request: EntryPartRow.insert,
1583
1718
  execute: (row) => sql`INSERT INTO part ${sql.insert(row)}`
1584
1719
  });
1720
+ const lineOf = (threadId, where) => sql`
1721
+ WITH RECURSIVE line(thread_id, upto) AS (
1722
+ SELECT id, NULL FROM thread WHERE id = ${threadId}
1723
+ UNION ALL
1724
+ SELECT t.origin_thread_id, e.committed_seq
1725
+ FROM line l
1726
+ JOIN thread t ON t.id = l.thread_id
1727
+ JOIN entry e ON e.id = t.origin_entry_id
1728
+ )
1729
+ SELECT ${sized}
1730
+ FROM line l
1731
+ JOIN entry e ON e.thread_id = l.thread_id AND (l.upto IS NULL OR e.seq <= l.upto)
1732
+ WHERE ${sql.and(where)}
1733
+ `;
1585
1734
  const selectLine = SqlSchema.findAll({
1586
1735
  Request: Schema.String,
1587
- Result: EntryRow,
1588
- execute: (threadId) => sql`
1589
- WITH RECURSIVE line(thread_id, upto) AS (
1590
- SELECT id, NULL FROM thread WHERE id = ${threadId}
1591
- UNION ALL
1592
- SELECT t.origin_thread_id, e.committed_seq
1593
- FROM line l
1594
- JOIN thread t ON t.id = l.thread_id
1595
- JOIN entry e ON e.id = t.origin_entry_id
1736
+ Result: SizedEntryRow,
1737
+ execute: (threadId) => sql`${lineOf(threadId, [])} ORDER BY e.seq`
1738
+ });
1739
+ const selectLinePage = SqlSchema.findAll({
1740
+ Request: Schema.Struct({
1741
+ threadId: Schema.String,
1742
+ before: Schema.optional(Schema.Int),
1743
+ budget: Schema.Int,
1744
+ limit: Schema.Int
1745
+ }),
1746
+ Result: SizedEntryRow,
1747
+ execute: ({ threadId, before, budget, limit }) => sql`
1748
+ SELECT * FROM (
1749
+ SELECT *, sum(size) OVER newest AS total, row_number() OVER newest AS n
1750
+ FROM (
1751
+ ${lineOf(threadId, [sql`e.type IN ('user', 'assistant')`, ...before === void 0 ? [] : [sql`e.seq < ${before}`]])}
1752
+ ORDER BY e.seq DESC
1753
+ LIMIT ${limit}
1754
+ )
1755
+ WINDOW newest AS (ORDER BY seq DESC)
1596
1756
  )
1597
- SELECT e.*
1598
- FROM line l
1599
- JOIN entry e ON e.thread_id = l.thread_id AND (l.upto IS NULL OR e.seq <= l.upto)
1600
- ORDER BY e.seq
1757
+ WHERE n = 1 OR total <= ${budget}
1758
+ ORDER BY seq DESC
1601
1759
  `
1602
1760
  });
1603
1761
  const selectDraft = SqlSchema.findOneOption({
1604
1762
  Request: Schema.String,
1605
- Result: EntryRow,
1606
- execute: (threadId) => sql`SELECT * FROM entry WHERE thread_id = ${threadId} AND state = 'draft'`
1763
+ Result: SizedEntryRow,
1764
+ execute: (threadId) => sql`SELECT ${sized} FROM entry e WHERE e.thread_id = ${threadId} AND e.state = 'draft'`
1607
1765
  });
1608
1766
  const selectPartsForEntries = SqlSchema.findAll({
1609
1767
  Request: Schema.Array(Schema.String),
@@ -1631,9 +1789,10 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1631
1789
  if (bucket) bucket.push(part);
1632
1790
  else byEntry.set(part.entryId, [part]);
1633
1791
  }
1634
- return entries.map((entry) => ({
1792
+ return entries.map(({ size, ...entry }) => ({
1635
1793
  entry,
1636
- parts: byEntry.get(entry.id) ?? []
1794
+ parts: byEntry.get(entry.id) ?? [],
1795
+ size
1637
1796
  }));
1638
1797
  };
1639
1798
  const partsFor = Effect.fnUntraced(function* (entries) {
@@ -1651,15 +1810,22 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1651
1810
  return yield* (sessionId === void 0 ? selectAll() : selectBySession(sessionId)).pipe(Effect.orDie);
1652
1811
  });
1653
1812
  const entry = Effect.fn("Thread.entry")(function* (entryId) {
1654
- const found = yield* findEntry(entryId).pipe(Effect.orDie);
1813
+ const found = yield* findSized(entryId).pipe(Effect.orDie);
1655
1814
  if (Option.isNone(found)) return Option.none();
1656
1815
  const parts = yield* partsFor([found.value]);
1657
1816
  return Option.some(hydrate([found.value], parts)[0]);
1658
1817
  });
1818
+ const cut = Effect.fn("Thread.cut")(function* (threadId) {
1819
+ return Option.map(yield* findCut(threadId).pipe(Effect.orDie), (row) => row.cut);
1820
+ });
1659
1821
  const line = Effect.fn("Thread.line")(function* (threadId) {
1660
1822
  const entries = yield* selectLine(threadId).pipe(Effect.orDie);
1661
1823
  return hydrate(entries, yield* partsFor(entries));
1662
1824
  });
1825
+ const linePage = Effect.fn("Thread.linePage")(function* (input) {
1826
+ const entries = yield* selectLinePage(input).pipe(Effect.orDie);
1827
+ return hydrate(entries, yield* partsFor(entries));
1828
+ });
1663
1829
  const draft = Effect.fn("Thread.draft")(function* (threadId) {
1664
1830
  const found = yield* selectDraft(threadId).pipe(Effect.orDie);
1665
1831
  if (Option.isNone(found)) return Option.none();
@@ -1680,10 +1846,11 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1680
1846
  title: Option.fromUndefinedOr(input.title),
1681
1847
  execution: Option.none(),
1682
1848
  attempt: Option.none(),
1683
- createdSeq: input.seq
1849
+ createdSeq: input.seq,
1850
+ rev: yield* store.rev
1684
1851
  });
1685
1852
  yield* insertThread(row);
1686
- }, Effect.orDie);
1853
+ }, store.write, Effect.orDie);
1687
1854
  const writePart = Effect.fnUntraced(function* (entryId, threadId, partIndex, part) {
1688
1855
  const partRow = yield* EntryPartRow.insert.makeEffect({
1689
1856
  id: part.id ?? uuidv7(),
@@ -1703,8 +1870,10 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1703
1870
  });
1704
1871
  const touch = Effect.fnUntraced(function* (thread, delta) {
1705
1872
  const now = yield* epochNow;
1873
+ const rev = yield* store.rev;
1706
1874
  yield* sql`
1707
1875
  UPDATE thread SET
1876
+ rev = ${rev},
1708
1877
  updated_at = ${now},
1709
1878
  cost = cost + ${delta?.cost ?? 0},
1710
1879
  tokens_input = tokens_input + ${delta?.input ?? 0},
@@ -1713,7 +1882,7 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1713
1882
  tokens_cache_write = tokens_cache_write + ${delta?.cacheWrite ?? 0}
1714
1883
  WHERE id = ${thread.id}
1715
1884
  `;
1716
- yield* sql`UPDATE session SET updated_at = ${now} WHERE id = ${thread.sessionId}`;
1885
+ yield* sql`UPDATE session SET updated_at = ${now}, rev = ${rev} WHERE id = ${thread.sessionId}`;
1717
1886
  });
1718
1887
  const append = Effect.fn("Thread.append")(function* (input) {
1719
1888
  const parts = input.parts ?? [];
@@ -1730,7 +1899,7 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1730
1899
  if (envelopeIdentity !== void 0 && envelopeIdentity.messageId !== input.id) return yield* invalid(`messageId "${envelopeIdentity.messageId}" does not match entry id`);
1731
1900
  const compaction = input.type === "compaction" ? yield* decodeCompactionData$1(input.data).pipe(Effect.mapError((error) => invalid(error.message))) : void 0;
1732
1901
  const usage = input.type === "assistant" ? yield* decodeEnvelopeUsage(input.data).pipe(Effect.map((envelope) => envelope.usage), Effect.mapError((error) => invalid(error.message))) : void 0;
1733
- const result = yield* sql.withTransaction(Effect.gen(function* () {
1902
+ const result = yield* store.write(Effect.gen(function* () {
1734
1903
  const thread = yield* findThread(input.threadId);
1735
1904
  if (Option.isNone(thread)) return { _tag: "threadNotFound" };
1736
1905
  if (compaction !== void 0 && compaction.firstKeptEntryId !== null) {
@@ -1749,7 +1918,8 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1749
1918
  state,
1750
1919
  data: input.data,
1751
1920
  label: Option.none(),
1752
- metadata: Option.fromUndefinedOr(input.metadata)
1921
+ metadata: Option.fromUndefinedOr(input.metadata),
1922
+ rev: yield* store.rev
1753
1923
  });
1754
1924
  if ((yield* insertEntry(entryRow)).length === 0) return {
1755
1925
  _tag: "invalidData",
@@ -1798,21 +1968,21 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1798
1968
  };
1799
1969
  });
1800
1970
  const replaceAssistant = Effect.fn("Thread.replaceAssistant")(function* (input) {
1801
- yield* sql.withTransaction(Effect.gen(function* () {
1971
+ yield* store.write(Effect.gen(function* () {
1802
1972
  const { entry, thread } = yield* requireDraft(input.id, input.threadId, "replaceAssistant");
1803
1973
  const delta = yield* usageDelta(entry.data, input.data);
1804
1974
  const now = yield* epochNow;
1805
1975
  yield* sql`DELETE FROM part WHERE entry_id = ${input.id}`;
1806
1976
  yield* writeParts(input.id, input.threadId, input.parts);
1807
1977
  yield* sql`
1808
- UPDATE entry SET data = ${input.data}, updated_at = ${now}
1978
+ UPDATE entry SET data = ${input.data}, updated_at = ${now}, rev = ${yield* store.rev}
1809
1979
  WHERE id = ${input.id} AND state = 'draft'
1810
1980
  `;
1811
1981
  yield* touch(thread, delta);
1812
1982
  }));
1813
1983
  }, Effect.orDie);
1814
1984
  const progress = Effect.fn("Thread.progress")(function* (input) {
1815
- yield* sql.withTransaction(Effect.gen(function* () {
1985
+ yield* store.write(Effect.gen(function* () {
1816
1986
  yield* requireDraft(input.id, input.threadId, "progress");
1817
1987
  const now = yield* epochNow;
1818
1988
  for (const change of input.changes) {
@@ -1837,7 +2007,7 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1837
2007
  WHERE entry_id = ${input.id} AND part_index = ${change.partIndex}
1838
2008
  `;
1839
2009
  }
1840
- yield* sql`UPDATE entry SET updated_at = ${now} WHERE id = ${input.id}`;
2010
+ yield* sql`UPDATE entry SET updated_at = ${now}, rev = ${yield* store.rev} WHERE id = ${input.id}`;
1841
2011
  }));
1842
2012
  }, Effect.orDie);
1843
2013
  const settleToolCall = Effect.fn("Thread.settleToolCall")(function* (input) {
@@ -1854,11 +2024,12 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1854
2024
  AND EXISTS (SELECT 1 FROM entry WHERE id = ${input.entryId} AND state = 'draft')
1855
2025
  RETURNING id
1856
2026
  `).length !== 1) return yield* Effect.die(`settleToolCall requires one unsettled call ${input.entryId}/${input.callId}`);
1857
- }, Effect.orDie);
2027
+ yield* sql`UPDATE entry SET updated_at = ${now}, rev = ${yield* store.rev} WHERE id = ${input.entryId}`;
2028
+ }, store.write, Effect.orDie);
1858
2029
  const commit = Effect.fn("Thread.commit")(function* (input) {
1859
2030
  const now = yield* epochNow;
1860
2031
  if ((yield* sql`
1861
- UPDATE entry SET state = 'committed', committed_seq = ${input.seq}, updated_at = ${now}
2032
+ UPDATE entry SET state = 'committed', committed_seq = ${input.seq}, updated_at = ${now}, rev = ${yield* store.rev}
1862
2033
  WHERE id = ${input.id}
1863
2034
  AND thread_id = ${input.threadId}
1864
2035
  AND type = 'assistant'
@@ -1868,10 +2039,10 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1868
2039
  )
1869
2040
  RETURNING id
1870
2041
  `).length !== 1) return yield* Effect.die(`commit requires a fully-settled draft ${input.id}`);
1871
- yield* sql`UPDATE thread SET updated_at = ${now} WHERE id = ${input.threadId}`;
1872
- }, Effect.orDie);
2042
+ yield* sql`UPDATE thread SET updated_at = ${now}, rev = ${yield* store.rev} WHERE id = ${input.threadId}`;
2043
+ }, store.write, Effect.orDie);
1873
2044
  const abort = Effect.fn("Thread.abort")(function* (input) {
1874
- yield* sql.withTransaction(Effect.gen(function* () {
2045
+ yield* store.write(Effect.gen(function* () {
1875
2046
  const { entry, thread } = yield* requireDraft(input.id, input.threadId, "abort");
1876
2047
  const delta = yield* usageDelta(entry.data, input.data);
1877
2048
  const now = yield* epochNow;
@@ -1879,7 +2050,8 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1879
2050
  yield* writeParts(input.id, input.threadId, input.parts);
1880
2051
  yield* sql`
1881
2052
  UPDATE entry
1882
- SET state = 'aborted', committed_seq = ${input.seq}, data = ${input.data}, updated_at = ${now}
2053
+ SET state = 'aborted', committed_seq = ${input.seq}, data = ${input.data}, updated_at = ${now},
2054
+ rev = ${yield* store.rev}
1883
2055
  WHERE id = ${input.id} AND state = 'draft'
1884
2056
  `;
1885
2057
  yield* touch(thread, delta);
@@ -1977,49 +2149,53 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
1977
2149
  value: {},
1978
2150
  seq
1979
2151
  });
1980
- });
2152
+ }, store.write, Effect.orDie);
1981
2153
  const retitle = Effect.fn("Thread.retitle")(function* (threadId, title) {
1982
2154
  return (yield* sql`
1983
- UPDATE thread SET title = ${title} WHERE id = ${threadId} AND title IS NULL RETURNING id
1984
- `.pipe(Effect.orDie)).length > 0;
1985
- });
2155
+ UPDATE thread SET title = ${title}, rev = ${yield* store.rev} WHERE id = ${threadId} AND title IS NULL RETURNING id
2156
+ `).length > 0;
2157
+ }, store.write, Effect.orDie);
1986
2158
  const markRunning = Effect.fn("Thread.markRunning")(function* (threadId) {
1987
- yield* sql`UPDATE thread SET execution = 'running' WHERE id = ${threadId}`;
1988
- }, Effect.orDie);
2159
+ yield* sql`UPDATE thread SET execution = 'running', rev = ${yield* store.rev} WHERE id = ${threadId}`;
2160
+ }, store.write, Effect.orDie);
1989
2161
  const endExecution = Effect.fn("Thread.endExecution")(function* (threadId, end, stoppedAt) {
2162
+ const rev = yield* store.rev;
1990
2163
  if (end === "closed") {
1991
- yield* sql`UPDATE thread SET execution = 'closed', attempt = NULL WHERE id = ${threadId}`;
2164
+ yield* sql`UPDATE thread SET execution = 'closed', attempt = NULL, rev = ${rev} WHERE id = ${threadId}`;
1992
2165
  return;
1993
2166
  }
1994
- yield* sql`UPDATE thread SET attempt = NULL WHERE id = ${threadId}`;
2167
+ yield* sql`UPDATE thread SET attempt = NULL, rev = ${rev} WHERE id = ${threadId}`;
1995
2168
  const after = end === "stopped" ? stoppedAt ?? Number.MAX_SAFE_INTEGER : -1;
1996
2169
  yield* sql`
1997
- UPDATE thread SET execution = NULL, restarts = 0
2170
+ UPDATE thread SET execution = NULL, restarts = 0, rev = ${rev}
1998
2171
  WHERE id = ${threadId} AND NOT EXISTS (
1999
2172
  SELECT 1 FROM inbox
2000
2173
  WHERE thread_id = ${threadId} AND promoted_seq IS NULL AND cancelled_seq IS NULL
2001
2174
  AND admitted_seq > ${after}
2002
2175
  )
2003
2176
  `;
2004
- }, Effect.orDie);
2177
+ }, store.write, Effect.orDie);
2005
2178
  const claimRestart = Effect.fn("Thread.claimRestart")(function* (threadId) {
2006
2179
  const rows = yield* sql`
2007
2180
  UPDATE thread
2008
- SET restarts = restarts + (CASE WHEN execution = 'running' THEN 1 ELSE 0 END), execution = 'running'
2181
+ SET restarts = restarts + (CASE WHEN execution = 'running' THEN 1 ELSE 0 END), execution = 'running',
2182
+ rev = ${yield* store.rev}
2009
2183
  WHERE id = ${threadId} AND execution IS NOT NULL
2010
2184
  RETURNING restarts
2011
2185
  `;
2012
2186
  return Option.fromUndefinedOr(rows[0]?.restarts);
2013
- }, Effect.orDie);
2187
+ }, store.write, Effect.orDie);
2014
2188
  const resetRestarts = Effect.fn("Thread.resetRestarts")(function* (threadId) {
2015
- yield* sql`UPDATE thread SET restarts = 0 WHERE id = ${threadId} AND restarts > 0`;
2016
- }, Effect.orDie);
2189
+ yield* sql`UPDATE thread SET restarts = 0, rev = ${yield* store.rev} WHERE id = ${threadId} AND restarts > 0`;
2190
+ }, store.write, Effect.orDie);
2017
2191
  const setAttempt = Effect.fn("Thread.setAttempt")(function* (threadId, attempt) {
2018
- yield* sql`UPDATE thread SET attempt = ${attempt} WHERE id = ${threadId}`;
2019
- }, Effect.orDie);
2192
+ yield* sql`UPDATE thread SET attempt = ${attempt}, rev = ${yield* store.rev} WHERE id = ${threadId}`;
2193
+ }, store.write, Effect.orDie);
2020
2194
  const idle = Effect.fn("Thread.idle")(function* (threadId) {
2021
- yield* sql`UPDATE thread SET execution = NULL, restarts = 0, attempt = NULL WHERE id = ${threadId}`;
2022
- }, Effect.orDie);
2195
+ yield* sql`
2196
+ UPDATE thread SET execution = NULL, restarts = 0, attempt = NULL, rev = ${yield* store.rev} WHERE id = ${threadId}
2197
+ `;
2198
+ }, store.write, Effect.orDie);
2023
2199
  const unfinished = SqlSchema.findAll({
2024
2200
  Request: Schema.Void,
2025
2201
  Result: ThreadRow,
@@ -2027,13 +2203,46 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
2027
2203
  SELECT * FROM thread WHERE execution IS NOT NULL AND origin_kind <> 'subagent' ORDER BY updated_at
2028
2204
  `
2029
2205
  })(void 0).pipe(Effect.orDie, Effect.withSpan("Thread.unfinished"));
2206
+ const projectRun = Effect.fn("Thread.projectRun")(function* (threadId, at, change) {
2207
+ const time = DateTime.toEpochMillis(at);
2208
+ const rev = yield* store.rev;
2209
+ const state = change._tag === "started" ? "starting" : change._tag === "running" ? "running" : "idle";
2210
+ const stateAt = sql`CASE WHEN run_state = ${state} THEN run_state_at ELSE ${time} END`;
2211
+ if (change._tag === "running") {
2212
+ yield* sql`UPDATE thread SET run_state_at = ${stateAt}, run_state = ${state}, rev = ${rev} WHERE id = ${threadId}`;
2213
+ return;
2214
+ }
2215
+ if (change._tag === "started") {
2216
+ yield* sql`
2217
+ UPDATE thread SET
2218
+ run_state_at = ${stateAt}, run_state = ${state}, run_started_at = ${time},
2219
+ run_ended_at = NULL, run_outcome = NULL, run_error = NULL, rev = ${rev}
2220
+ WHERE id = ${threadId}
2221
+ `;
2222
+ return;
2223
+ }
2224
+ const error = change.error === void 0 ? null : yield* encodeRunError(change.error);
2225
+ yield* sql`
2226
+ UPDATE thread SET
2227
+ run_state_at = ${stateAt}, run_state = ${state}, run_ended_at = ${time},
2228
+ run_outcome = ${change.outcome}, run_error = ${error}, rev = ${rev}
2229
+ WHERE id = ${threadId}
2230
+ `;
2231
+ }, Effect.orDie);
2232
+ const open = SqlSchema.findAll({
2233
+ Request: Schema.Void,
2234
+ Result: ThreadRow,
2235
+ execute: () => sql`SELECT * FROM thread WHERE run_state <> 'idle' ORDER BY updated_at`
2236
+ })(void 0).pipe(Effect.orDie, Effect.withSpan("Thread.open"));
2030
2237
  const setLabel = Effect.fn("Thread.setLabel")(function* (input) {
2031
- const now = yield* epochNow;
2032
- if ((yield* sql`
2033
- UPDATE entry SET label = ${input.label}, updated_at = ${now}
2034
- WHERE id = ${input.entryId} AND thread_id = ${input.threadId}
2035
- RETURNING id
2036
- `.pipe(Effect.orDie)).length === 0) return yield* new EntryNotFoundError({
2238
+ if ((yield* Effect.gen(function* () {
2239
+ const now = yield* epochNow;
2240
+ return yield* sql`
2241
+ UPDATE entry SET label = ${input.label}, updated_at = ${now}, rev = ${yield* store.rev}
2242
+ WHERE id = ${input.entryId} AND thread_id = ${input.threadId}
2243
+ RETURNING id
2244
+ `;
2245
+ }).pipe(store.write, Effect.orDie)).length === 0) return yield* new EntryNotFoundError({
2037
2246
  threadId: input.threadId,
2038
2247
  entryId: input.entryId
2039
2248
  });
@@ -2043,7 +2252,9 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
2043
2252
  main,
2044
2253
  list,
2045
2254
  entry,
2255
+ cut,
2046
2256
  line,
2257
+ linePage,
2047
2258
  draft,
2048
2259
  unsettled,
2049
2260
  insert,
@@ -2063,6 +2274,8 @@ const layer$29 = Layer.effect(Service$19, Effect.gen(function* () {
2063
2274
  setAttempt,
2064
2275
  idle,
2065
2276
  unfinished,
2277
+ projectRun,
2278
+ open,
2066
2279
  setLabel
2067
2280
  });
2068
2281
  }));
@@ -2462,6 +2675,7 @@ const equivalent = (input, expected) => input.delivery === expected.delivery &&
2462
2675
  const matchesProjection = (input, expected) => equivalent(input, expected) && DateTime.toEpochMillis(input.timeCreated) === DateTime.toEpochMillis(expected.timeCreated);
2463
2676
  const make$23 = Effect.gen(function* () {
2464
2677
  const sql = yield* SqlClient.SqlClient;
2678
+ const store = yield* Service$22;
2465
2679
  const events = yield* Service$20;
2466
2680
  const findRow = SqlSchema.findOneOption({
2467
2681
  Request: Schema.String,
@@ -2482,11 +2696,12 @@ const make$23 = Effect.gen(function* () {
2482
2696
  id: Schema.String,
2483
2697
  threadId: Schema.String,
2484
2698
  data: Schema.NullOr(Schema.fromJsonString(Prompt)),
2485
- delivery: Schema.NullOr(Delivery)
2699
+ delivery: Schema.NullOr(Delivery),
2700
+ rev: Schema.Int
2486
2701
  }),
2487
2702
  Result: Schema.Struct({ id: Schema.String }),
2488
- execute: ({ id, threadId, data, delivery }) => sql`
2489
- UPDATE inbox SET data = COALESCE(${data}, data), delivery = COALESCE(${delivery}, delivery)
2703
+ execute: ({ id, threadId, data, delivery, rev }) => sql`
2704
+ UPDATE inbox SET data = COALESCE(${data}, data), delivery = COALESCE(${delivery}, delivery), rev = ${rev}
2490
2705
  WHERE id = ${id} AND thread_id = ${threadId} AND promoted_seq IS NULL AND cancelled_seq IS NULL
2491
2706
  RETURNING id
2492
2707
  `
@@ -2498,13 +2713,14 @@ const make$23 = Effect.gen(function* () {
2498
2713
  data: Schema.fromJsonString(Prompt),
2499
2714
  delivery: Delivery,
2500
2715
  admittedSeq: Schema.Int,
2501
- createdAt: schema_exports$9.DateTimeUtcFromMillis
2716
+ createdAt: schema_exports$9.DateTimeUtcFromMillis,
2717
+ rev: Schema.Int
2502
2718
  }),
2503
2719
  Result: Schema.Struct({ id: Schema.String }),
2504
- execute: ({ id, threadId, data, delivery, admittedSeq, createdAt }) => sql`
2720
+ execute: ({ id, threadId, data, delivery, admittedSeq, createdAt, rev }) => sql`
2505
2721
  UPDATE inbox
2506
2722
  SET data = ${data}, delivery = ${delivery}, admitted_seq = ${admittedSeq}, created_at = ${createdAt},
2507
- cancelled_seq = NULL
2723
+ cancelled_seq = NULL, rev = ${rev}
2508
2724
  WHERE id = ${id} AND thread_id = ${threadId} AND promoted_seq IS NULL AND cancelled_seq IS NOT NULL
2509
2725
  RETURNING id
2510
2726
  `
@@ -2513,11 +2729,12 @@ const make$23 = Effect.gen(function* () {
2513
2729
  Request: Schema.Struct({
2514
2730
  id: Schema.String,
2515
2731
  threadId: Schema.String,
2516
- promotedSeq: Schema.Int
2732
+ promotedSeq: Schema.Int,
2733
+ rev: Schema.Int
2517
2734
  }),
2518
2735
  Result: InboxRow,
2519
- execute: ({ id, threadId, promotedSeq }) => sql`
2520
- UPDATE inbox SET promoted_seq = ${promotedSeq}
2736
+ execute: ({ id, threadId, promotedSeq, rev }) => sql`
2737
+ UPDATE inbox SET promoted_seq = ${promotedSeq}, rev = ${rev}
2521
2738
  WHERE id = ${id} AND thread_id = ${threadId} AND promoted_seq IS NULL AND cancelled_seq IS NULL
2522
2739
  RETURNING *
2523
2740
  `
@@ -2526,11 +2743,12 @@ const make$23 = Effect.gen(function* () {
2526
2743
  Request: Schema.Struct({
2527
2744
  id: Schema.String,
2528
2745
  threadId: Schema.String,
2529
- cancelledSeq: Schema.Int
2746
+ cancelledSeq: Schema.Int,
2747
+ rev: Schema.Int
2530
2748
  }),
2531
2749
  Result: Schema.Struct({ id: Schema.String }),
2532
- execute: ({ id, threadId, cancelledSeq }) => sql`
2533
- UPDATE inbox SET cancelled_seq = ${cancelledSeq}
2750
+ execute: ({ id, threadId, cancelledSeq, rev }) => sql`
2751
+ UPDATE inbox SET cancelled_seq = ${cancelledSeq}, rev = ${rev}
2534
2752
  WHERE id = ${id} AND thread_id = ${threadId} AND promoted_seq IS NULL AND cancelled_seq IS NULL
2535
2753
  RETURNING id
2536
2754
  `
@@ -2623,7 +2841,8 @@ const make$23 = Effect.gen(function* () {
2623
2841
  admittedSeq: input.admittedSeq,
2624
2842
  promotedSeq: Option.none(),
2625
2843
  cancelledSeq: Option.none(),
2626
- createdAt: VariantSchema.Override(input.timeCreated)
2844
+ createdAt: VariantSchema.Override(input.timeCreated),
2845
+ rev: yield* store.rev
2627
2846
  })).length > 0) return;
2628
2847
  if ((yield* reviveRow({
2629
2848
  id: input.id,
@@ -2631,14 +2850,16 @@ const make$23 = Effect.gen(function* () {
2631
2850
  data: input.prompt,
2632
2851
  delivery: input.delivery,
2633
2852
  admittedSeq: input.admittedSeq,
2634
- createdAt: input.timeCreated
2853
+ createdAt: input.timeCreated,
2854
+ rev: yield* store.rev
2635
2855
  })).length === 0) return yield* Effect.die(new LifecycleConflict({ id: input.id }));
2636
- }, Effect.orDie);
2856
+ }, store.write, Effect.orDie);
2637
2857
  const projectPrompted = Effect.fn("Inbox.projectPrompted")(function* (input) {
2638
2858
  const promoted = (yield* promoteRow({
2639
2859
  id: input.id,
2640
2860
  threadId: input.threadId,
2641
- promotedSeq: input.promotedSeq
2861
+ promotedSeq: input.promotedSeq,
2862
+ rev: yield* store.rev
2642
2863
  }))[0];
2643
2864
  if (promoted) {
2644
2865
  if (!matchesProjection(fromRow$1(promoted), input)) return yield* Effect.die(new LifecycleConflict({ id: input.id }));
@@ -2659,24 +2880,29 @@ const make$23 = Effect.gen(function* () {
2659
2880
  admittedSeq: input.promotedSeq,
2660
2881
  promotedSeq: Option.some(input.promotedSeq),
2661
2882
  cancelledSeq: Option.none(),
2662
- createdAt: VariantSchema.Override(input.timeCreated)
2883
+ createdAt: VariantSchema.Override(input.timeCreated),
2884
+ rev: yield* store.rev
2663
2885
  });
2664
- }, Effect.orDie);
2886
+ }, store.write, Effect.orDie);
2665
2887
  const projectCancelled = Effect.fn("Inbox.projectCancelled")(function* (input) {
2666
- if ((yield* cancelRow(input)).length > 0) return;
2888
+ if ((yield* cancelRow({
2889
+ ...input,
2890
+ rev: yield* store.rev
2891
+ })).length > 0) return;
2667
2892
  const stored = yield* find(input.id);
2668
2893
  if (Option.isSome(stored) && stored.value.cancelledSeq === input.cancelledSeq) return;
2669
2894
  return yield* Effect.die(new LifecycleConflict({ id: input.id }));
2670
- }, Effect.orDie);
2895
+ }, store.write, Effect.orDie);
2671
2896
  const projectUpdated = Effect.fn("Inbox.projectUpdated")(function* (input) {
2672
2897
  if ((yield* updateRow({
2673
2898
  id: input.id,
2674
2899
  threadId: input.threadId,
2675
2900
  data: input.prompt ?? null,
2676
- delivery: input.delivery ?? null
2901
+ delivery: input.delivery ?? null,
2902
+ rev: yield* store.rev
2677
2903
  })).length > 0) return;
2678
2904
  return yield* Effect.die(new LifecycleConflict({ id: input.id }));
2679
- }, Effect.orDie);
2905
+ }, store.write, Effect.orDie);
2680
2906
  const pendingOf = (threadId, id) => find(id).pipe(Effect.map(Option.filter((stored) => stored.threadId === threadId && stored.promotedSeq === void 0 && stored.cancelledSeq === void 0)));
2681
2907
  const update = Effect.fn("Inbox.update")(function* (threadId, id, patch) {
2682
2908
  const stored = yield* pendingOf(threadId, id);
@@ -5585,6 +5811,22 @@ const render$1 = (servers) => {
5585
5811
  //#region src/db/migrations.ts
5586
5812
  const migrations = { "202610290001_init": Effect.gen(function* () {
5587
5813
  const sql = yield* SqlClient.SqlClient;
5814
+ yield* sql`
5815
+ CREATE TABLE store (
5816
+ id TEXT NOT NULL,
5817
+ rev INTEGER NOT NULL
5818
+ )
5819
+ `;
5820
+ yield* sql`INSERT INTO store (id, rev) VALUES (${uuidv7()}, 0)`;
5821
+ yield* sql`
5822
+ CREATE TABLE removed (
5823
+ kind TEXT NOT NULL,
5824
+ id TEXT NOT NULL,
5825
+ rev INTEGER NOT NULL,
5826
+ PRIMARY KEY (kind, id)
5827
+ )
5828
+ `;
5829
+ yield* sql`CREATE INDEX removed_rev_idx ON removed (rev)`;
5588
5830
  yield* sql`
5589
5831
  CREATE TABLE sequence (
5590
5832
  aggregate_id TEXT PRIMARY KEY,
@@ -5634,7 +5876,8 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5634
5876
  name TEXT NOT NULL,
5635
5877
  status TEXT NOT NULL,
5636
5878
  created_at INTEGER NOT NULL,
5637
- updated_at INTEGER NOT NULL
5879
+ updated_at INTEGER NOT NULL,
5880
+ rev INTEGER NOT NULL
5638
5881
  )
5639
5882
  `;
5640
5883
  yield* sql`
@@ -5646,7 +5889,8 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5646
5889
  env TEXT REFERENCES sandbox(id) ON DELETE RESTRICT CHECK (env IS NULL OR env <> 'local'),
5647
5890
  status TEXT NOT NULL,
5648
5891
  created_at INTEGER NOT NULL,
5649
- updated_at INTEGER NOT NULL
5892
+ updated_at INTEGER NOT NULL,
5893
+ rev INTEGER NOT NULL
5650
5894
  )
5651
5895
  `;
5652
5896
  yield* sql`CREATE UNIQUE INDEX space_location_idx ON space (coalesce(env, 'local'), location)`;
@@ -5664,7 +5908,8 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5664
5908
  tag TEXT,
5665
5909
  metadata TEXT,
5666
5910
  created_at INTEGER NOT NULL,
5667
- updated_at INTEGER NOT NULL
5911
+ updated_at INTEGER NOT NULL,
5912
+ rev INTEGER NOT NULL
5668
5913
  )
5669
5914
  `;
5670
5915
  yield* sql`CREATE UNIQUE INDEX session_slug_idx ON session (slug)`;
@@ -5680,6 +5925,13 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5680
5925
  origin_call_id TEXT,
5681
5926
  title TEXT,
5682
5927
  execution TEXT,
5928
+ -- the run lifecycle, projected from the execution.* events; times are the events'
5929
+ run_state TEXT NOT NULL DEFAULT 'idle',
5930
+ run_state_at INTEGER,
5931
+ run_started_at INTEGER,
5932
+ run_ended_at INTEGER,
5933
+ run_outcome TEXT,
5934
+ run_error TEXT,
5683
5935
  restarts INTEGER NOT NULL DEFAULT 0,
5684
5936
  attempt INTEGER,
5685
5937
  cost REAL NOT NULL DEFAULT 0,
@@ -5690,6 +5942,7 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5690
5942
  created_seq INTEGER NOT NULL,
5691
5943
  created_at INTEGER NOT NULL,
5692
5944
  updated_at INTEGER NOT NULL,
5945
+ rev INTEGER NOT NULL,
5693
5946
  UNIQUE (session_id, id),
5694
5947
  -- the source thread lives in the same session
5695
5948
  FOREIGN KEY (session_id, origin_thread_id) REFERENCES thread(session_id, id),
@@ -5724,6 +5977,7 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5724
5977
  metadata TEXT,
5725
5978
  created_at INTEGER NOT NULL,
5726
5979
  updated_at INTEGER NOT NULL,
5980
+ rev INTEGER NOT NULL,
5727
5981
  UNIQUE (thread_id, id),
5728
5982
  FOREIGN KEY (session_id, thread_id) REFERENCES thread(session_id, id) ON DELETE CASCADE,
5729
5983
  -- the fork cut reads committed_seq: set exactly when the entry stops changing
@@ -5770,6 +6024,7 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5770
6024
  promoted_seq INTEGER,
5771
6025
  cancelled_seq INTEGER,
5772
6026
  created_at INTEGER NOT NULL,
6027
+ rev INTEGER NOT NULL,
5773
6028
  FOREIGN KEY (session_id, thread_id) REFERENCES thread(session_id, id) ON DELETE CASCADE
5774
6029
  )
5775
6030
  `;
@@ -5802,6 +6057,24 @@ const migrations = { "202610290001_init": Effect.gen(function* () {
5802
6057
  PRIMARY KEY (document_id, seq)
5803
6058
  )
5804
6059
  `;
6060
+ yield* sql`CREATE INDEX project_rev_idx ON project (rev)`;
6061
+ yield* sql`CREATE INDEX space_rev_idx ON space (rev)`;
6062
+ yield* sql`CREATE INDEX session_rev_idx ON session (rev)`;
6063
+ yield* sql`CREATE INDEX thread_rev_idx ON thread (rev)`;
6064
+ yield* sql`CREATE INDEX entry_thread_rev_idx ON entry (thread_id, rev)`;
6065
+ yield* sql`CREATE INDEX inbox_thread_rev_idx ON inbox (thread_id, rev)`;
6066
+ for (const table of [
6067
+ "project",
6068
+ "space",
6069
+ "session",
6070
+ "thread",
6071
+ "entry",
6072
+ "inbox"
6073
+ ]) for (const event of ["insert", "update"]) yield* sql.unsafe(`
6074
+ CREATE TRIGGER ${table}_rev_${event} BEFORE ${event.toUpperCase()} ON ${table}
6075
+ WHEN NEW.rev <> (SELECT rev FROM store)
6076
+ BEGIN SELECT RAISE(ABORT, 'rev is not the current revision'); END
6077
+ `);
5805
6078
  }) };
5806
6079
  //#endregion
5807
6080
  //#region src/db/db.ts
@@ -5832,7 +6105,7 @@ function layer$26(location) {
5832
6105
  transformQueryNames: String$1.camelToSnake,
5833
6106
  transformResultNames: String$1.snakeToCamel
5834
6107
  });
5835
- })).pipe(Layer.tap((context) => setup.pipe(Effect.provide(context))), Layer.orDie);
6108
+ })).pipe(Layer.tap((context) => setup.pipe(Effect.provide(context))), Layer.orDie, (sqlite) => Layer.provideMerge(layer$32, sqlite));
5836
6109
  }
5837
6110
  const locationConfig = Config.String("CODEWORK_DB").pipe(Config.withDefault("codework.db"));
5838
6111
  function resolveDatabaseLocation(configured, data) {
@@ -5860,18 +6133,20 @@ const fromRow = (row) => new schema_exports$7.SpaceSchema.Info({
5860
6133
  });
5861
6134
  /**
5862
6135
  * Archive every space of an env, then every touched project left without an
5863
- * active space in any env (§5.5). Requires only `SqlClient` so the sandbox
5864
- * controller can run it inside its destroy tombstone transaction (D-ENV).
6136
+ * active space in any env (§5.5). Requires only `SqlClient` and `Store` so the
6137
+ * sandbox controller can run it inside its destroy tombstone transaction (D-ENV).
5865
6138
  * Write-first so a DEFERRED transaction takes the write lock immediately.
5866
6139
  */
5867
6140
  const archiveEnv = Effect.fn("Space.archiveEnv")(function* (env) {
5868
6141
  const sql = yield* SqlClient.SqlClient;
6142
+ const store = yield* Service$22;
5869
6143
  const column = instance_exports.SandboxInstance.toColumn(env);
5870
6144
  const now = yield* Clock.currentTimeMillis;
5871
- yield* sql.withTransaction(Effect.gen(function* () {
5872
- yield* sql`UPDATE space SET status = 'archived', updated_at = ${now} WHERE env IS ${column}`;
6145
+ yield* store.write(Effect.gen(function* () {
6146
+ const rev = yield* store.rev;
6147
+ yield* sql`UPDATE space SET status = 'archived', updated_at = ${now}, rev = ${rev} WHERE env IS ${column}`;
5873
6148
  yield* sql`
5874
- UPDATE project SET status = 'archived', updated_at = ${now}
6149
+ UPDATE project SET status = 'archived', updated_at = ${now}, rev = ${rev}
5875
6150
  WHERE id IN (SELECT project_id FROM space WHERE env IS ${column})
5876
6151
  AND NOT EXISTS (SELECT 1 FROM space WHERE space.project_id = project.id AND status = 'active')
5877
6152
  `;
@@ -5879,6 +6154,7 @@ const archiveEnv = Effect.fn("Space.archiveEnv")(function* (env) {
5879
6154
  });
5880
6155
  const layer$25 = Layer.effect(Service$16, Effect.gen(function* () {
5881
6156
  const sql = yield* SqlClient.SqlClient;
6157
+ const store = yield* Service$22;
5882
6158
  const fs = yield* io_exports.SandboxIO.FileSystem;
5883
6159
  const { id: env } = yield* io_exports.SandboxIO.Current;
5884
6160
  const envColumn = instance_exports.SandboxInstance.toColumn(env);
@@ -5903,11 +6179,12 @@ const layer$25 = Layer.effect(Service$16, Effect.gen(function* () {
5903
6179
  project_id = excluded.project_id,
5904
6180
  kind = excluded.kind,
5905
6181
  status = 'active',
5906
- updated_at = excluded.updated_at
6182
+ updated_at = excluded.updated_at,
6183
+ rev = excluded.rev
5907
6184
  `
5908
6185
  });
5909
- const archiveOrphanProjects = (projectIds, now) => Effect.forEach(projectIds, (projectId) => sql`
5910
- UPDATE project SET status = 'archived', updated_at = ${now}
6186
+ const archiveOrphanProjects = (projectIds, now, rev) => Effect.forEach(projectIds, (projectId) => sql`
6187
+ UPDATE project SET status = 'archived', updated_at = ${now}, rev = ${rev}
5911
6188
  WHERE id = ${projectId}
5912
6189
  AND NOT EXISTS (SELECT 1 FROM space WHERE project_id = ${projectId} AND status = 'active')
5913
6190
  `, { discard: true });
@@ -5935,19 +6212,20 @@ const layer$25 = Layer.effect(Service$16, Effect.gen(function* () {
5935
6212
  const gone = probed.filter((entry) => entry.gone).map((entry) => entry.row.id);
5936
6213
  const returned = probed.filter((entry) => !entry.gone && entry.row.status === "archived").map((entry) => entry.row.id);
5937
6214
  const now = yield* Clock.currentTimeMillis;
5938
- yield* sql.withTransaction(Effect.gen(function* () {
5939
- if (gone.length > 0) yield* sql`UPDATE space SET status = 'archived', updated_at = ${now} WHERE ${sql.in("id", gone)}`;
5940
- if (returned.length > 0) yield* sql`UPDATE space SET status = 'active', updated_at = ${now} WHERE ${sql.in("id", returned)}`;
6215
+ yield* store.write(Effect.gen(function* () {
6216
+ const rev = yield* store.rev;
6217
+ if (gone.length > 0) yield* sql`UPDATE space SET status = 'archived', updated_at = ${now}, rev = ${rev} WHERE ${sql.in("id", gone)}`;
6218
+ if (returned.length > 0) yield* sql`UPDATE space SET status = 'active', updated_at = ${now}, rev = ${rev} WHERE ${sql.in("id", returned)}`;
5941
6219
  if ((yield* sql`
5942
6220
  SELECT id FROM space
5943
6221
  WHERE project_id = ${projectId} AND env IS ${envColumn} AND kind = 'primary' AND status = 'active'
5944
6222
  `).length === 0) {
5945
6223
  yield* sql`
5946
- UPDATE space SET kind = 'copy', updated_at = ${now}
6224
+ UPDATE space SET kind = 'copy', updated_at = ${now}, rev = ${rev}
5947
6225
  WHERE project_id = ${projectId} AND env IS ${envColumn} AND kind = 'primary'
5948
6226
  `;
5949
6227
  yield* sql`
5950
- UPDATE space SET kind = 'primary', updated_at = ${now}
6228
+ UPDATE space SET kind = 'primary', updated_at = ${now}, rev = ${rev}
5951
6229
  WHERE id = (
5952
6230
  SELECT id FROM space
5953
6231
  WHERE project_id = ${projectId} AND env IS ${envColumn} AND status = 'active' AND kind = 'copy'
@@ -5955,30 +6233,33 @@ const layer$25 = Layer.effect(Service$16, Effect.gen(function* () {
5955
6233
  )
5956
6234
  `;
5957
6235
  }
5958
- yield* archiveOrphanProjects([projectId], now);
6236
+ yield* archiveOrphanProjects([projectId], now, rev);
5959
6237
  })).pipe(Effect.orDie);
5960
6238
  return yield* list(projectId);
5961
6239
  });
5962
6240
  const rehome = Effect.fn("Space.rehome")(function* (input) {
6241
+ const rev = yield* store.rev;
5963
6242
  const write = (kind) => SpaceRow.insert.makeEffect({
5964
6243
  id: input.id,
5965
6244
  projectId: input.projectId,
5966
6245
  location: input.location,
5967
6246
  kind,
5968
6247
  env: instance_exports.SandboxInstance.toField(input.env),
5969
- status: "active"
6248
+ status: "active",
6249
+ rev
5970
6250
  }).pipe(Effect.flatMap(insertSpace));
5971
6251
  yield* write(input.kind).pipe(Effect.catchIf((error) => input.kind === "primary" && SqlError.isSqlError(error) && error.reason._tag === "UniqueViolation" && error.reason.constraint.includes("space_primary_idx"), () => write("copy")), Effect.orDie);
5972
- });
6252
+ }, store.write, Effect.orDie);
5973
6253
  const absorb = Effect.fn("Space.absorb")(function* (input) {
5974
- yield* sql`UPDATE session SET space_id = ${input.into} WHERE space_id = ${input.strayId}`;
6254
+ const rev = yield* store.rev;
6255
+ yield* sql`UPDATE session SET space_id = ${input.into}, rev = ${rev} WHERE space_id = ${input.strayId}`;
5975
6256
  yield* sql`DELETE FROM space WHERE id = ${input.strayId}`;
5976
- }, Effect.orDie);
6257
+ }, store.write, Effect.orDie);
5977
6258
  return Service$16.of({
5978
6259
  get,
5979
6260
  list,
5980
6261
  refresh,
5981
- archiveEnv: (target) => archiveEnv(target).pipe(Effect.provideService(SqlClient.SqlClient, sql)),
6262
+ archiveEnv: (target) => archiveEnv(target).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.provideService(Service$22, store)),
5982
6263
  rehome,
5983
6264
  absorb
5984
6265
  });
@@ -6475,6 +6756,7 @@ const timedShell = (shell, driver) => {
6475
6756
  };
6476
6757
  const make$14 = Effect.fn("Sandbox.Controller.make")(function* (options) {
6477
6758
  const sql = yield* SqlClient.SqlClient;
6759
+ const db = yield* Service$22;
6478
6760
  const registry = yield* Registry;
6479
6761
  const store = yield* make$15;
6480
6762
  const gate = yield* Semaphore.make(1);
@@ -7040,7 +7322,7 @@ const make$14 = Effect.fn("Sandbox.Controller.make")(function* (options) {
7040
7322
  const attached = yield* runtime(current, "destroy");
7041
7323
  yield* attached.driver.destroy(attached.input).pipe(Effect.catch((error) => (0, errors_exports.providerErrorIsNotFound)(error) ? Effect.void : persistProviderFailure(id, claim.restoreStatus, error)));
7042
7324
  const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
7043
- yield* sql.withTransaction(Effect.gen(function* () {
7325
+ yield* db.write(Effect.gen(function* () {
7044
7326
  yield* sql`
7045
7327
  UPDATE sandbox
7046
7328
  SET
@@ -7052,7 +7334,7 @@ const make$14 = Effect.fn("Sandbox.Controller.make")(function* (options) {
7052
7334
  WHERE id = ${id}
7053
7335
  `;
7054
7336
  yield* archiveEnv(id);
7055
- })).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.orDie);
7337
+ })).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.provideService(Service$22, db), Effect.orDie);
7056
7338
  });
7057
7339
  const createAndMount = (input, mountOptions) => {
7058
7340
  const id = input.instanceId ?? instance_exports.SandboxInstance.ID.create();
@@ -8010,6 +8292,7 @@ const provisional = (env, location) => schema_exports$10.ProjectSchema.ID.make(f
8010
8292
  var Service$12 = class extends Context.Service()("@codeworksh/harness/project/project/Service") {};
8011
8293
  const layer$15 = Layer.effect(Service$12, Effect.gen(function* () {
8012
8294
  const sql = yield* SqlClient.SqlClient;
8295
+ const store = yield* Service$22;
8013
8296
  const fs = yield* io_exports.SandboxIO.FileSystem;
8014
8297
  const repos = yield* Service$14;
8015
8298
  const worktrees = yield* Service$13;
@@ -8031,7 +8314,7 @@ const layer$15 = Layer.effect(Service$12, Effect.gen(function* () {
8031
8314
  Request: ProjectRow.insert,
8032
8315
  execute: (row) => sql`
8033
8316
  INSERT INTO project ${sql.insert(row)}
8034
- ON CONFLICT(id) DO UPDATE SET status = 'active', updated_at = excluded.updated_at
8317
+ ON CONFLICT(id) DO UPDATE SET status = 'active', updated_at = excluded.updated_at, rev = excluded.rev
8035
8318
  `
8036
8319
  });
8037
8320
  const toInfo = (row, vcs) => new schema_exports$10.ProjectSchema.Info({
@@ -8095,11 +8378,12 @@ const layer$15 = Layer.effect(Service$12, Effect.gen(function* () {
8095
8378
  return true;
8096
8379
  };
8097
8380
  const worktreeSpaceId = id(env, worktree);
8098
- yield* sql.withTransaction(Effect.gen(function* () {
8381
+ yield* store.write(Effect.gen(function* () {
8099
8382
  const row = yield* ProjectRow.insert.makeEffect({
8100
8383
  id: projectId,
8101
8384
  name,
8102
- status: "active"
8385
+ status: "active",
8386
+ rev: yield* store.rev
8103
8387
  });
8104
8388
  yield* upsertProject(row);
8105
8389
  for (const member of members) {
@@ -8144,18 +8428,24 @@ var ProjectNotFoundError = class extends Schema.TaggedError()("ProjectNotFoundEr
8144
8428
  /** Renames a project. Needs only the database, not a mount: a name is the same in every env. */
8145
8429
  const rename = Effect.fn("Project.rename")(function* (input) {
8146
8430
  const sql = yield* SqlClient.SqlClient;
8431
+ const store = yield* Service$22;
8147
8432
  const now = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
8148
- const row = yield* SqlSchema.findOneOption({
8433
+ const update = SqlSchema.findOneOption({
8149
8434
  Request: Schema.Struct({
8150
8435
  id: Schema.String,
8151
- name: Schema.String
8436
+ name: Schema.String,
8437
+ rev: Schema.Int
8152
8438
  }),
8153
8439
  Result: ProjectRow,
8154
- execute: ({ id, name }) => sql`UPDATE project SET name = ${name}, updated_at = ${now} WHERE id = ${id} RETURNING *`
8155
- })({
8156
- id: input.projectId,
8157
- name: input.name
8158
- }).pipe(Effect.orDie);
8440
+ execute: ({ id, name, rev }) => sql`UPDATE project SET name = ${name}, updated_at = ${now}, rev = ${rev} WHERE id = ${id} RETURNING *`
8441
+ });
8442
+ const row = yield* Effect.gen(function* () {
8443
+ return yield* update({
8444
+ id: input.projectId,
8445
+ name: input.name,
8446
+ rev: yield* store.rev
8447
+ });
8448
+ }).pipe(store.write, Effect.orDie);
8159
8449
  if (Option.isNone(row)) return yield* new ProjectNotFoundError({ projectId: input.projectId });
8160
8450
  return new schema_exports$10.ProjectSchema.Info({
8161
8451
  id: schema_exports$10.ProjectSchema.ID.make(row.value.id),
@@ -9731,6 +10021,7 @@ var SessionNotLinkedError = class extends Schema.TaggedError()("SessionNotLinked
9731
10021
  var Service$6 = class extends Context.Service()("@codeworksh/harness/session/session/Service") {};
9732
10022
  const layer$10 = Layer.effect(Service$6, Effect.gen(function* () {
9733
10023
  const sql = yield* SqlClient.SqlClient;
10024
+ const store = yield* Service$22;
9734
10025
  const events = yield* Service$20;
9735
10026
  const threads = yield* Service$19;
9736
10027
  const documents = yield* Service$21;
@@ -9794,7 +10085,8 @@ const layer$10 = Layer.effect(Service$6, Effect.gen(function* () {
9794
10085
  directory: data.directory,
9795
10086
  hostDir: Option.fromUndefinedOr(data.hostDir),
9796
10087
  tag: Option.fromUndefinedOr(data.tag),
9797
- metadata: Option.fromUndefinedOr(data.metadata)
10088
+ metadata: Option.fromUndefinedOr(data.metadata),
10089
+ rev: yield* store.rev
9798
10090
  });
9799
10091
  yield* insertSession(row);
9800
10092
  yield* threads.insert({
@@ -9811,7 +10103,7 @@ const layer$10 = Layer.effect(Service$6, Effect.gen(function* () {
9811
10103
  value: yield* Schema.encodeEffect(Agent)(data.agent),
9812
10104
  seq
9813
10105
  });
9814
- }, Effect.orDie);
10106
+ }, store.write, Effect.orDie);
9815
10107
  const create = Effect.fn("Session.create")(function* (input) {
9816
10108
  const id = input.id ?? ID$2.create();
9817
10109
  const threadId = input.mainThreadId ?? ID$1.create();
@@ -9882,10 +10174,12 @@ const layer$10 = Layer.effect(Service$6, Effect.gen(function* () {
9882
10174
  const session = yield* findSession(input.sessionId).pipe(Effect.orDie);
9883
10175
  if (Option.isNone(session)) return yield* new SessionNotFoundError({ sessionId: input.sessionId });
9884
10176
  const now = yield* epochNow;
9885
- yield* sql`
9886
- UPDATE session SET host_dir = ${input.hostDir}, updated_at = ${now}
9887
- WHERE id = ${input.sessionId}
9888
- `.pipe(Effect.orDie);
10177
+ yield* Effect.gen(function* () {
10178
+ yield* sql`
10179
+ UPDATE session SET host_dir = ${input.hostDir}, updated_at = ${now}, rev = ${yield* store.rev}
10180
+ WHERE id = ${input.sessionId}
10181
+ `;
10182
+ }).pipe(store.write, Effect.orDie);
9889
10183
  const updated = yield* findSession(input.sessionId).pipe(Effect.orDie);
9890
10184
  if (Option.isNone(updated)) return yield* Effect.die(/* @__PURE__ */ new Error("session link did not persist"));
9891
10185
  return updated.value;
@@ -9915,10 +10209,13 @@ const layer$10 = Layer.effect(Service$6, Effect.gen(function* () {
9915
10209
  if (!directoryWithin(target.value.location, directory)) return yield* reject("directory_outside_space");
9916
10210
  if (input.threadId === void 0) {
9917
10211
  const now = yield* epochNow;
9918
- yield* sql`
9919
- UPDATE session SET space_id = ${input.spaceId}, directory = ${directory}, updated_at = ${now}
9920
- WHERE id = ${input.sessionId}
9921
- `.pipe(Effect.orDie);
10212
+ yield* Effect.gen(function* () {
10213
+ yield* sql`
10214
+ UPDATE session SET space_id = ${input.spaceId}, directory = ${directory}, updated_at = ${now},
10215
+ rev = ${yield* store.rev}
10216
+ WHERE id = ${input.sessionId}
10217
+ `;
10218
+ }).pipe(store.write, Effect.orDie);
9922
10219
  } else yield* events.publish(ThreadConfigured, {
9923
10220
  timestamp: yield* DateTime.now,
9924
10221
  sessionId: input.sessionId,
@@ -9933,10 +10230,15 @@ const layer$10 = Layer.effect(Service$6, Effect.gen(function* () {
9933
10230
  return updated.value;
9934
10231
  });
9935
10232
  const remove = Effect.fn("Session.delete")(function* (sessionId) {
9936
- return yield* sql.withTransaction(Effect.gen(function* () {
10233
+ return yield* store.write(Effect.gen(function* () {
9937
10234
  const deleted = yield* sql`DELETE FROM session WHERE id = ${sessionId} RETURNING id`;
9938
10235
  yield* sql`DELETE FROM sequence WHERE aggregate_id = ${sessionId}`;
9939
- return deleted.length > 0;
10236
+ if (deleted.length === 0) return false;
10237
+ yield* sql`
10238
+ INSERT INTO removed (kind, id, rev) VALUES ('session', ${sessionId}, ${yield* store.rev})
10239
+ ON CONFLICT (kind, id) DO UPDATE SET rev = excluded.rev
10240
+ `;
10241
+ return true;
9940
10242
  })).pipe(Effect.orDie);
9941
10243
  });
9942
10244
  return Service$6.of({
@@ -9980,6 +10282,7 @@ const layer$9 = Layer.effect(Service$5, Effect.gen(function* () {
9980
10282
  const inputs = yield* make$23;
9981
10283
  const execution = yield* Service$7;
9982
10284
  const mcp = yield* Service$8;
10285
+ const events = yield* Service$20;
9983
10286
  const isLifecycleConflict = Schema.is(LifecycleConflict);
9984
10287
  const wake = (threadId) => threads.markRunning(threadId).pipe(Effect.andThen(execution.wake(threadId)));
9985
10288
  const resolve = Effect.fn("Control.resolve")(function* (ref) {
@@ -10086,6 +10389,17 @@ const layer$9 = Layer.effect(Service$5, Effect.gen(function* () {
10086
10389
  discard: true
10087
10390
  });
10088
10391
  }).pipe(Effect.withSpan("Control.resumeUnfinished"));
10392
+ const sweep = Effect.gen(function* () {
10393
+ for (const row of yield* threads.open) {
10394
+ const execution = Option.getOrUndefined(row.execution);
10395
+ yield* events.publish(ExecutionInterrupted, {
10396
+ timestamp: yield* DateTime.now,
10397
+ sessionId: ID$2.make(row.sessionId),
10398
+ threadId: ID$1.make(row.id),
10399
+ reason: execution === "closed" ? "shutdown" : "crash"
10400
+ });
10401
+ }
10402
+ }).pipe(Effect.withSpan("Control.sweep"));
10089
10403
  return Service$5.of({
10090
10404
  resolve,
10091
10405
  prompt,
@@ -10097,6 +10411,7 @@ const layer$9 = Layer.effect(Service$5, Effect.gen(function* () {
10097
10411
  deleteSession,
10098
10412
  active: execution.active,
10099
10413
  resumeUnfinished,
10414
+ sweep,
10100
10415
  pending: inputs.pending,
10101
10416
  cancel: inputs.cancel,
10102
10417
  update
@@ -13794,20 +14109,12 @@ const layer$7 = Layer.effect(Service$7, Effect.gen(function* () {
13794
14109
  const threads = yield* Service$19;
13795
14110
  const sandbox = yield* Controller;
13796
14111
  const sql = yield* SqlClient.SqlClient;
14112
+ const store = yield* Service$22;
13797
14113
  const runner = yield* Service$10;
13798
14114
  const events = yield* Service$20;
13799
14115
  const mcp = yield* Service$8;
13800
14116
  const reportLifecycle = (threadId, publish) => publish.pipe(Effect.tapCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.logError("Failed to publish session execution lifecycle", cause).pipe(Effect.annotateLogs({ threadId }))), Effect.ignore);
13801
- const owners = /* @__PURE__ */ new Map();
13802
- const sessionOf = (threadId) => Effect.gen(function* () {
13803
- const known = owners.get(threadId);
13804
- if (known !== void 0) return Option.some(known);
13805
- const thread = yield* threads.get(threadId);
13806
- if (Option.isNone(thread)) return Option.none();
13807
- const sessionId = ID$2.make(thread.value.sessionId);
13808
- owners.set(threadId, sessionId);
13809
- return Option.some(sessionId);
13810
- });
14117
+ const sessionOf = (threadId) => threads.get(threadId).pipe(Effect.map(Option.map((thread) => ID$2.make(thread.sessionId))));
13811
14118
  const publishLifecycle = (threadId, publish) => Effect.gen(function* () {
13812
14119
  const sessionId = yield* sessionOf(threadId);
13813
14120
  if (Option.isNone(sessionId)) return;
@@ -13820,13 +14127,21 @@ const layer$7 = Layer.effect(Service$7, Effect.gen(function* () {
13820
14127
  const recovering = /* @__PURE__ */ new Set();
13821
14128
  const abandoning = /* @__PURE__ */ new Map();
13822
14129
  const stoppedAt = /* @__PURE__ */ new Map();
14130
+ const ended = /* @__PURE__ */ new Set();
13823
14131
  const coordinator = yield* make$8({
13824
- started: (threadId) => reportLifecycle(threadId, (recovering.has(threadId) ? Effect.void : threads.markRunning(threadId)).pipe(Effect.andThen(publishLifecycle(threadId, (base) => events.publish(ExecutionStarted, base))))),
14132
+ started: (threadId) => Effect.suspend(() => {
14133
+ const resumed = recovering.has(threadId);
14134
+ return reportLifecycle(threadId, (resumed ? Effect.void : threads.markRunning(threadId)).pipe(Effect.andThen(publishLifecycle(threadId, (base) => events.publish(ExecutionStarted, {
14135
+ ...base,
14136
+ resumed
14137
+ })))));
14138
+ }),
13825
14139
  settled: (threadId, exit, reason) => reportLifecycle(threadId, Effect.gen(function* () {
13826
14140
  const interrupted = Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause);
13827
14141
  const stop = stoppedAt.get(threadId);
13828
14142
  stoppedAt.delete(threadId);
13829
14143
  yield* threads.endExecution(threadId, !interrupted ? "finished" : reason === "user" ? "stopped" : "closed", stop);
14144
+ if (ended.delete(threadId) && Exit.isSuccess(exit)) return;
13830
14145
  const sessionId = yield* sessionOf(threadId);
13831
14146
  if (Option.isNone(sessionId)) return;
13832
14147
  const base = {
@@ -13845,6 +14160,10 @@ const layer$7 = Layer.effect(Service$7, Effect.gen(function* () {
13845
14160
  });
13846
14161
  })),
13847
14162
  drain: Effect.fnUntraced(function* (threadId, force) {
14163
+ ended.delete(threadId);
14164
+ const record = (outcome) => Effect.sync(() => {
14165
+ if (outcome === "ended") ended.add(threadId);
14166
+ });
13848
14167
  const thread = yield* threads.get(threadId);
13849
14168
  if (Option.isNone(thread)) return;
13850
14169
  const sessionId = thread.value.sessionId;
@@ -13854,7 +14173,7 @@ const layer$7 = Layer.effect(Service$7, Effect.gen(function* () {
13854
14173
  if (abandoned !== void 0) return yield* runner.abandon({
13855
14174
  threadId,
13856
14175
  message: abandoned
13857
- });
14176
+ }).pipe(Effect.flatMap(record));
13858
14177
  const placement = yield* sessions.placement(threadId);
13859
14178
  if (Option.isNone(placement)) return yield* new SessionLinkedSpaceNotFoundError({
13860
14179
  sessionId,
@@ -13870,7 +14189,7 @@ const layer$7 = Layer.effect(Service$7, Effect.gen(function* () {
13870
14189
  sandboxInstanceId: instanceId,
13871
14190
  directory: current.cwd
13872
14191
  });
13873
- const location = layerMounted().pipe(Layer.provide(Layer.succeedContext(mountContext)), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)));
14192
+ const location = layerMounted().pipe(Layer.provide(Layer.succeedContext(mountContext)), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), Layer.provide(Layer.succeed(Service$22, store)));
13874
14193
  const locationContext = yield* Layer.build(location).pipe(Effect.catchTag(["Location.DirectoryNotFoundError", "Location.NotDirectoryError"], (error) => new SandboxDirectoryNotFoundError({
13875
14194
  threadId,
13876
14195
  sandboxInstanceId: error.sandboxInstanceId,
@@ -13884,7 +14203,7 @@ const layer$7 = Layer.effect(Service$7, Effect.gen(function* () {
13884
14203
  threadId,
13885
14204
  force,
13886
14205
  recovered
13887
- }).pipe(Effect.provideContext(Context.merge(locationContext, mountContext)));
14206
+ }).pipe(Effect.provideContext(Context.merge(locationContext, mountContext)), Effect.flatMap(record));
13888
14207
  }).pipe(Effect.scoped, Effect.tapCause((cause) => Cause.hasDies(cause) ? Effect.logError("defect", cause).pipe(Effect.annotateLogs({ threadId })) : Effect.void));
13889
14208
  })
13890
14209
  });
@@ -14086,6 +14405,12 @@ const make$7 = Effect.fn("LLMEventPublisher.make")(function* (input) {
14086
14405
  let dirty = false;
14087
14406
  let stopped = false;
14088
14407
  let ticker;
14408
+ const lengths = /* @__PURE__ */ new Map();
14409
+ const advance = (partIndex, delta) => {
14410
+ const offset = lengths.get(partIndex) ?? 0;
14411
+ lengths.set(partIndex, offset + delta.length);
14412
+ return offset;
14413
+ };
14089
14414
  const checkpoint = Effect.gen(function* () {
14090
14415
  dirty = false;
14091
14416
  if (latest === void 0 || startedMessageId === void 0) return;
@@ -14186,6 +14511,7 @@ const make$7 = Effect.fn("LLMEventPublisher.make")(function* (input) {
14186
14511
  ...base,
14187
14512
  messageId: yield* identify(event.partial.messageId),
14188
14513
  partIndex: event.partIndex,
14514
+ offset: advance(event.partIndex, event.delta),
14189
14515
  delta: event.delta
14190
14516
  });
14191
14517
  return;
@@ -14209,6 +14535,7 @@ const make$7 = Effect.fn("LLMEventPublisher.make")(function* (input) {
14209
14535
  ...base,
14210
14536
  messageId: yield* identify(event.partial.messageId),
14211
14537
  partIndex: event.partIndex,
14538
+ offset: advance(event.partIndex, event.delta),
14212
14539
  delta: event.delta
14213
14540
  });
14214
14541
  return;
@@ -14374,7 +14701,7 @@ const openWith = (options = {}) => Effect.fn("LLM.open")(function* (input, signa
14374
14701
  catch: (cause) => providerErrorFromUnknown(input, cause)
14375
14702
  });
14376
14703
  });
14377
- const open = openWith();
14704
+ const open$1 = openWith();
14378
14705
  const isProviderError = Schema.is(ProviderError);
14379
14706
  /** `error.type` for a request: the provider's failure reason, so a terminal and a thrown failure agree. */
14380
14707
  const requestErrorType = (input, exit) => {
@@ -14486,7 +14813,7 @@ const make$6 = (openStream) => {
14486
14813
  });
14487
14814
  return (input) => request(input).pipe(Effect.catchTag("LLM.FailedTerminal", (failed) => Effect.succeed(failed.terminal)), Effect.scoped);
14488
14815
  };
14489
- const run$1 = make$6(open);
14816
+ const run$1 = make$6(open$1);
14490
14817
  //#endregion
14491
14818
  //#region src/runner/hooks.ts
14492
14819
  var Service$3 = class extends Context.Service()("@codeworksh/harness/runner/hooks/Service") {};
@@ -15747,6 +16074,7 @@ const layer$3 = (options = {}) => Layer.effect(Service$10, Effect.gen(function*
15747
16074
  });
15748
16075
  yield* threads.idle(threadId);
15749
16076
  }));
16077
+ return "ended";
15750
16078
  });
15751
16079
  const settleTools = Effect.fn("Loop.settleTools", { level: "Info" })(function* (snapshot, message, reason, markCommitted) {
15752
16080
  const pending = message.parts.filter((part) => part.type === "toolCall" && part.status === "pending");
@@ -15985,7 +16313,7 @@ const layer$3 = (options = {}) => Layer.effect(Service$10, Effect.gen(function*
15985
16313
  yield* healDraft(input.threadId, carried?.message);
15986
16314
  const hasSteer = yield* inputs.hasPending(input.threadId, "steer");
15987
16315
  const hasFollowUp = hasSteer ? false : yield* inputs.hasPending(input.threadId, "followUp");
15988
- if (!input.force && !hasSteer && !hasFollowUp) return;
16316
+ if (!input.force && !hasSteer && !hasFollowUp) return "drained";
15989
16317
  yield* Effect.annotateCurrentSpan({
15990
16318
  "gen_ai.operation.name": "invoke_agent",
15991
16319
  "gen_ai.agent.name": "codework",
@@ -16022,24 +16350,24 @@ const layer$3 = (options = {}) => Layer.effect(Service$10, Effect.gen(function*
16022
16350
  pending: yield* peekPending(input.threadId)
16023
16351
  };
16024
16352
  const decision = completed === void 0 ? void 0 : yield* hooks.finishTurn(completed);
16025
- if (decision === "end") return;
16353
+ if (decision === "end") return "drained";
16026
16354
  if (truncations >= TRUNCATION_LIMIT) return yield* endRun(snapshot.sessionId, input.threadId, "truncated", `The response hit the output token limit with tool calls ${truncations} times in a row; the run is ended`);
16027
16355
  continuing = toolUse || decision === "continue";
16028
16356
  const steer = yield* inputs.hasPending(input.threadId, "steer");
16029
16357
  const followUp = !toolUse && !steer && (yield* inputs.hasPending(input.threadId, "followUp"));
16030
- if (!continuing && !steer && !followUp) return;
16358
+ if (!continuing && !steer && !followUp) return "drained";
16031
16359
  promotion = followUp ? "followUp" : "steer";
16032
16360
  const next = holdServers(start, yield* state.snapshot(input.threadId));
16033
16361
  snapshot = completed === void 0 ? next : yield* hooks.prepareNextTurn(completed, next);
16034
16362
  }
16035
16363
  });
16036
- yield* timed(drain, (seconds, exit) => record$1(agentDuration, seconds, withError({}, exit)));
16364
+ return yield* timed(drain, (seconds, exit) => record$1(agentDuration, seconds, withError({}, exit)));
16037
16365
  });
16038
16366
  const abandon = Effect.fn("Loop.abandon")(function* (input) {
16039
16367
  const thread = yield* threads.get(input.threadId);
16040
- if (Option.isNone(thread)) return;
16368
+ if (Option.isNone(thread)) return "drained";
16041
16369
  yield* healDraft(input.threadId, Option.isSome(thread.value.attempt) ? input.message : void 0);
16042
- yield* endRun(ID$2.make(thread.value.sessionId), input.threadId, "crashloop", input.message);
16370
+ return yield* endRun(ID$2.make(thread.value.sessionId), input.threadId, "crashloop", input.message);
16043
16371
  });
16044
16372
  return Service$10.of({
16045
16373
  run,
@@ -16209,7 +16537,38 @@ const layer$2 = Layer.effectDiscard(Effect.gen(function* () {
16209
16537
  const title = titleFrom(Prompt.text(event.data.prompt));
16210
16538
  if (title !== void 0) yield* threads.retitle(event.data.threadId, title);
16211
16539
  }));
16540
+ yield* events.project(ExecutionStarted, ({ data }) => threads.projectRun(data.threadId, data.timestamp, { _tag: "started" }));
16541
+ yield* events.project(ExecutionSucceeded, ({ data }) => threads.projectRun(data.threadId, data.timestamp, {
16542
+ _tag: "ended",
16543
+ outcome: "succeeded"
16544
+ }));
16545
+ yield* events.project(ExecutionFailed, ({ data }) => threads.projectRun(data.threadId, data.timestamp, {
16546
+ _tag: "ended",
16547
+ outcome: "failed",
16548
+ error: {
16549
+ _tag: "failed",
16550
+ error: data.error
16551
+ }
16552
+ }));
16553
+ yield* events.project(ExecutionInterrupted, ({ data }) => threads.projectRun(data.threadId, data.timestamp, {
16554
+ _tag: "ended",
16555
+ outcome: "interrupted",
16556
+ error: {
16557
+ _tag: "interrupted",
16558
+ reason: data.reason
16559
+ }
16560
+ }));
16561
+ yield* events.project(RunFailed, ({ data }) => threads.projectRun(data.threadId, data.timestamp, {
16562
+ _tag: "ended",
16563
+ outcome: "failed",
16564
+ error: {
16565
+ _tag: "runFailed",
16566
+ reason: data.reason,
16567
+ message: data.message
16568
+ }
16569
+ }));
16212
16570
  yield* events.project(LLMStarted, (event) => Effect.gen(function* () {
16571
+ yield* threads.projectRun(event.data.threadId, event.data.timestamp, { _tag: "running" });
16213
16572
  const encoded = yield* encodeAssistant(event.data);
16214
16573
  yield* threads.append({
16215
16574
  id: event.data.messageId,
@@ -16524,7 +16883,8 @@ var session_exports = /* @__PURE__ */ __exportAll({
16524
16883
  link: () => link,
16525
16884
  relink: () => relink,
16526
16885
  remove: () => remove,
16527
- threadInfo: () => threadInfo
16886
+ threadInfo: () => threadInfo,
16887
+ threadSummary: () => threadSummary
16528
16888
  });
16529
16889
  /** What stays in this process. The model and thinking level are the thread's {@link chosen} `agent`. */
16530
16890
  const runtimeBindings = (input) => ({
@@ -16582,8 +16942,12 @@ const info = Effect.fn("Session.info")(function* (id) {
16582
16942
  const sandbox = space === void 0 || space.env === instance_exports.SandboxInstance.ID.local ? void 0 : Option.getOrUndefined(yield* sandboxes.get(space.env));
16583
16943
  const hostDir = Option.getOrUndefined(row.hostDir);
16584
16944
  const project = Option.getOrUndefined(yield* sessions.project(id));
16945
+ const tag = Option.getOrUndefined(row.tag);
16946
+ const metadata = Option.getOrUndefined(row.metadata);
16585
16947
  return {
16586
16948
  id,
16949
+ spaceId: row.spaceId,
16950
+ slug: row.slug,
16587
16951
  directory: row.directory,
16588
16952
  ...hostDir === void 0 ? {} : { hostDir },
16589
16953
  hasHostLink: hostDir !== void 0,
@@ -16592,28 +16956,33 @@ const info = Effect.fn("Session.info")(function* (id) {
16592
16956
  id: project.id,
16593
16957
  name: project.name
16594
16958
  } },
16959
+ ...tag === void 0 ? {} : { tag },
16960
+ ...metadata === void 0 ? {} : { metadata },
16961
+ createdAt: DateTime.toEpochMillis(row.createdAt),
16595
16962
  updatedAt: DateTime.toEpochMillis(row.updatedAt),
16596
16963
  mainThreadId: ID$1.make(main.value.id)
16597
16964
  };
16598
16965
  });
16599
- const originOf = (row) => {
16966
+ const originOf = (row, cut) => {
16600
16967
  const threadId = Option.getOrUndefined(row.originThreadId);
16601
16968
  const entryId = Option.getOrUndefined(row.originEntryId);
16602
16969
  const callId = Option.getOrUndefined(row.originCallId);
16603
- if (row.originKind === "fork" && threadId !== void 0 && entryId !== void 0) return {
16970
+ if (row.originKind === "fork" && threadId !== void 0 && entryId !== void 0 && cut !== void 0) return {
16604
16971
  kind: "fork",
16605
16972
  threadId,
16606
- entryId
16973
+ entryId,
16974
+ cut
16607
16975
  };
16608
16976
  if (row.originKind === "subagent" && threadId !== void 0 && callId !== void 0) return {
16609
16977
  kind: "subagent",
16610
16978
  threadId,
16611
16979
  callId,
16612
- ...entryId === void 0 ? {} : { entryId }
16980
+ ...entryId === void 0 ? {} : { entryId },
16981
+ ...cut === void 0 ? {} : { cut }
16613
16982
  };
16614
16983
  return { kind: "main" };
16615
16984
  };
16616
- const threadInfo = Effect.fn("Session.threadInfo")(function* (id) {
16985
+ const threadSummary = Effect.fn("Session.threadSummary")(function* (id) {
16617
16986
  const threads = yield* Service$19;
16618
16987
  const documents = yield* Service$21;
16619
16988
  const found = yield* threads.get(id);
@@ -16621,10 +16990,17 @@ const threadInfo = Effect.fn("Session.threadInfo")(function* (id) {
16621
16990
  const row = found.value;
16622
16991
  const agent = yield* documents.agent(id);
16623
16992
  const title = Option.getOrUndefined(row.title);
16993
+ const millis = (time) => Option.getOrUndefined(Option.map(time, DateTime.toEpochMillis));
16994
+ const runStateAt = millis(row.runStateAt);
16995
+ const startedAt = millis(row.runStartedAt);
16996
+ const endedAt = millis(row.runEndedAt);
16997
+ const outcome = Option.getOrUndefined(row.runOutcome);
16998
+ const error = Option.getOrUndefined(row.runError);
16999
+ const attempt = Option.getOrUndefined(row.attempt);
16624
17000
  return {
16625
17001
  id,
16626
17002
  sessionId: ID$2.make(row.sessionId),
16627
- origin: originOf(row),
17003
+ origin: originOf(row, Option.isSome(row.originEntryId) ? Option.getOrUndefined(yield* threads.cut(id)) : void 0),
16628
17004
  ...title === void 0 ? {} : { title },
16629
17005
  updatedAt: DateTime.toEpochMillis(row.updatedAt),
16630
17006
  ...agent.model === void 0 ? {} : { model: agent.model },
@@ -16638,7 +17014,25 @@ const threadInfo = Effect.fn("Session.threadInfo")(function* (id) {
16638
17014
  cacheRead: row.tokensCacheRead,
16639
17015
  cacheWrite: row.tokensCacheWrite
16640
17016
  },
16641
- session: yield* info(ID$2.make(row.sessionId))
17017
+ runState: row.runState,
17018
+ ...runStateAt === void 0 ? {} : { runStateAt },
17019
+ ...startedAt === void 0 ? {} : { lastRun: {
17020
+ startedAt,
17021
+ ...endedAt === void 0 ? {} : { endedAt },
17022
+ ...outcome === void 0 ? {} : { outcome },
17023
+ ...error === void 0 ? {} : { error }
17024
+ } },
17025
+ restarts: row.restarts,
17026
+ ...attempt === void 0 ? {} : { attempt },
17027
+ createdSeq: row.createdSeq,
17028
+ createdAt: DateTime.toEpochMillis(row.createdAt)
17029
+ };
17030
+ });
17031
+ const threadInfo = Effect.fn("Session.threadInfo")(function* (id) {
17032
+ const summary = yield* threadSummary(id);
17033
+ return {
17034
+ ...summary,
17035
+ session: yield* info(summary.sessionId)
16642
17036
  };
16643
17037
  });
16644
17038
  const makeThread = Effect.fn("Session.makeThread")(function* (sessionId, id) {
@@ -16812,6 +17206,210 @@ const configuration = Effect.fn("Session.configuration")(function* (threadId) {
16812
17206
  return yield* Service$1.use((state) => state.configuration(threadId));
16813
17207
  });
16814
17208
  //#endregion
17209
+ //#region src/effect/sync.ts
17210
+ var sync_exports = /* @__PURE__ */ __exportAll({
17211
+ Sync: () => sync_exports,
17212
+ index: () => index,
17213
+ open: () => open,
17214
+ page: () => page,
17215
+ thread: () => thread
17216
+ });
17217
+ const Row = Schema.Struct({
17218
+ kind: Schema.String,
17219
+ id: Schema.String,
17220
+ rev: Schema.Int
17221
+ });
17222
+ const decodeRows = Schema.decodeUnknownEffect(Schema.Array(Row));
17223
+ /**
17224
+ * One page of the rows `select` names, as `kind`, `id` and `rev`, past `from` and up to revision
17225
+ * `upto`, in `(rev, kind, id)` order. `select` filters each table on the revision range it is given,
17226
+ * so every table reads through its `rev` index. Rows of one revision can span pages.
17227
+ */
17228
+ const page = Effect.fn("Sync.page")(function* (select, from, upto, limit) {
17229
+ const sql = yield* SqlClient.SqlClient;
17230
+ const after = from.key === void 0 ? sql`rev > ${from.rev}` : sql`(rev, kind, id) > (${from.rev}, ${from.key.kind}, ${from.key.id})`;
17231
+ const rows = yield* sql`
17232
+ SELECT kind, id, rev FROM (${select(sql`rev >= ${from.rev} AND rev <= ${upto}`)})
17233
+ WHERE ${after}
17234
+ ORDER BY rev, kind, id
17235
+ LIMIT ${limit}
17236
+ `.pipe(Effect.flatMap(decodeRows), Effect.orDie);
17237
+ const last = rows.at(-1);
17238
+ return {
17239
+ items: rows,
17240
+ ...last === void 0 || rows.length < limit ? {} : { next: {
17241
+ rev: last.rev,
17242
+ key: {
17243
+ kind: last.kind,
17244
+ id: last.id
17245
+ }
17246
+ } }
17247
+ };
17248
+ });
17249
+ /**
17250
+ * One page of the index rows past `from`, up to revision `upto`, read as one snapshot so every row
17251
+ * the page names is still there to read.
17252
+ */
17253
+ const index = Effect.fn("Sync.index")(function* (from, upto, limit) {
17254
+ const sql = yield* SqlClient.SqlClient;
17255
+ const findProject = SqlSchema.findOne({
17256
+ Request: Schema.String,
17257
+ Result: ProjectRow,
17258
+ execute: (id) => sql`SELECT * FROM project WHERE id = ${id}`
17259
+ });
17260
+ const findSpace = SqlSchema.findOne({
17261
+ Request: Schema.String,
17262
+ Result: SpaceRow,
17263
+ execute: (id) => sql`SELECT * FROM space WHERE id = ${id}`
17264
+ });
17265
+ const select = (range) => sql`
17266
+ SELECT 'project' AS kind, id, rev FROM project WHERE ${range}
17267
+ UNION ALL SELECT 'space', id, rev FROM space WHERE ${range}
17268
+ UNION ALL SELECT 'session', id, rev FROM session WHERE ${range}
17269
+ UNION ALL SELECT 'thread', id, rev FROM thread WHERE ${range}
17270
+ UNION ALL SELECT 'removed', id, rev FROM removed WHERE kind = 'session' AND ${range}
17271
+ `;
17272
+ const change = Effect.fnUntraced(function* ({ kind, id, rev }) {
17273
+ switch (kind) {
17274
+ case "project": {
17275
+ const row = yield* findProject(id);
17276
+ return {
17277
+ _tag: "Project",
17278
+ project: {
17279
+ id: row.id,
17280
+ name: row.name,
17281
+ status: row.status,
17282
+ createdAt: DateTime.toEpochMillis(row.createdAt),
17283
+ updatedAt: DateTime.toEpochMillis(row.updatedAt)
17284
+ },
17285
+ rev
17286
+ };
17287
+ }
17288
+ case "space": {
17289
+ const row = yield* findSpace(id);
17290
+ const env = Option.getOrUndefined(row.env);
17291
+ return {
17292
+ _tag: "Space",
17293
+ space: {
17294
+ id: row.id,
17295
+ projectId: row.projectId,
17296
+ location: row.location,
17297
+ kind: row.kind,
17298
+ ...env === void 0 ? {} : { env },
17299
+ status: row.status,
17300
+ createdAt: DateTime.toEpochMillis(row.createdAt),
17301
+ updatedAt: DateTime.toEpochMillis(row.updatedAt)
17302
+ },
17303
+ rev
17304
+ };
17305
+ }
17306
+ case "session": return {
17307
+ _tag: "Session",
17308
+ session: yield* info(ID$2.make(id)),
17309
+ rev
17310
+ };
17311
+ case "thread": return {
17312
+ _tag: "Thread",
17313
+ thread: yield* threadSummary(ID$1.make(id)),
17314
+ rev
17315
+ };
17316
+ default: return {
17317
+ _tag: "Removed",
17318
+ kind: "session",
17319
+ id,
17320
+ rev
17321
+ };
17322
+ }
17323
+ });
17324
+ return yield* sql.withTransaction(Effect.gen(function* () {
17325
+ const { items, next } = yield* page(select, from, upto, limit);
17326
+ return {
17327
+ items: yield* Effect.forEach(items, change),
17328
+ ...next === void 0 ? {} : { next }
17329
+ };
17330
+ })).pipe(Effect.orDie);
17331
+ });
17332
+ const toInbox = (row) => {
17333
+ const prompt = fromRow$1(row);
17334
+ return {
17335
+ _tag: "Inbox",
17336
+ prompt,
17337
+ state: prompt.promotedSeq !== void 0 ? "promoted" : prompt.cancelledSeq !== void 0 ? "cancelled" : "pending",
17338
+ rev: row.rev
17339
+ };
17340
+ };
17341
+ /**
17342
+ * One page of a thread's own user and assistant entries and inbox rows past `from`, up to revision
17343
+ * `upto`, read as one snapshot. Inherited entries never change after the fork's cut, so a resume
17344
+ * does not read them.
17345
+ */
17346
+ const thread = Effect.fn("Sync.thread")(function* (threadId, from, upto, limit) {
17347
+ const sql = yield* SqlClient.SqlClient;
17348
+ const threads = yield* Service$19;
17349
+ const findInbox = SqlSchema.findOne({
17350
+ Request: Schema.String,
17351
+ Result: InboxRow,
17352
+ execute: (id) => sql`SELECT * FROM inbox WHERE id = ${id}`
17353
+ });
17354
+ const select = (range) => sql`
17355
+ SELECT 'entry' AS kind, id, rev FROM entry
17356
+ WHERE thread_id = ${threadId} AND type IN ('user', 'assistant') AND ${range}
17357
+ UNION ALL SELECT 'inbox', id, rev FROM inbox WHERE thread_id = ${threadId} AND ${range}
17358
+ `;
17359
+ const change = Effect.fnUntraced(function* ({ kind, id, rev }) {
17360
+ if (kind === "inbox") return toInbox(yield* findInbox(id));
17361
+ const entry = yield* threads.entry(id);
17362
+ if (Option.isNone(entry)) return yield* Effect.die(/* @__PURE__ */ new Error(`entry ${id} is missing`));
17363
+ return {
17364
+ _tag: "Entry",
17365
+ entry: entry.value,
17366
+ rev
17367
+ };
17368
+ });
17369
+ return yield* sql.withTransaction(Effect.gen(function* () {
17370
+ const { items, next } = yield* page(select, from, upto, limit);
17371
+ return {
17372
+ items: yield* Effect.forEach(items, change),
17373
+ ...next === void 0 ? {} : { next }
17374
+ };
17375
+ })).pipe(Effect.orDie);
17376
+ });
17377
+ /**
17378
+ * A thread's first page, read as one snapshot: the newest entries of its line within `budget`
17379
+ * bytes and `limit` entries (`Thread.linePage`), oldest first, then its pending inbox in admission
17380
+ * order. `floor` is the oldest entry's seq.
17381
+ */
17382
+ const open = Effect.fn("Sync.open")(function* (threadId, budget, limit) {
17383
+ const sql = yield* SqlClient.SqlClient;
17384
+ const threads = yield* Service$19;
17385
+ const selectPending = SqlSchema.findAll({
17386
+ Request: Schema.String,
17387
+ Result: InboxRow,
17388
+ execute: (id) => sql`
17389
+ SELECT * FROM inbox
17390
+ WHERE thread_id = ${id} AND promoted_seq IS NULL AND cancelled_seq IS NULL
17391
+ ORDER BY admitted_seq
17392
+ `
17393
+ });
17394
+ return yield* sql.withTransaction(Effect.gen(function* () {
17395
+ const entries = (yield* threads.linePage({
17396
+ threadId,
17397
+ budget,
17398
+ limit
17399
+ })).toReversed();
17400
+ const pending = yield* selectPending(threadId);
17401
+ const floor = entries[0]?.entry.seq;
17402
+ return {
17403
+ items: [...entries.map((entry) => ({
17404
+ _tag: "Entry",
17405
+ entry,
17406
+ rev: entry.entry.rev
17407
+ })), ...pending.map(toInbox)],
17408
+ ...floor === void 0 ? {} : { floor }
17409
+ };
17410
+ })).pipe(Effect.orDie);
17411
+ });
17412
+ //#endregion
16815
17413
  //#region src/plugin/prompt/schema.ts
16816
17414
  var schema_exports$3 = /* @__PURE__ */ __exportAll({});
16817
17415
  import * as import__codeworksh_plugin_plugin_prompt from "@codeworksh/plugin/plugin/prompt";
@@ -16849,6 +17447,6 @@ var DateTimeUtcFromMillis = schema_exports$9.DateTimeUtcFromMillis;
16849
17447
  var EventSchema = schema_exports$11.EventSchema;
16850
17448
  var SandboxError = errors_exports.SandboxError;
16851
17449
  var optional = schema_exports$9.optional;
16852
- export { control_exports as Control, db_exports as Database, DateTimeUtcFromMillis, schema_exports as DocumentSchema, event_exports as Event, list_exports as EventList, registry_exports as EventRegistry, EventSchema, git_exports as Git, global_exports as Global, harness_exports as Harness, location_exports as Location, mcp_exports as Mcp, config_exports as McpConfig, error_exports as McpError, oauth_exports as McpOAuth, catalog_exports as ModelCatalog, plugin_exports as Plugin, project_exports as Project, schema_exports$1 as PromptSchema, run_exports as Runner, sandbox_exports as Sandbox, SandboxError, session_exports as Session, session_exports$1 as SessionStore, settings_exports as Settings, state_exports as State, schema_exports$2 as ThreadSchema, thread_exports as ThreadStore, tool_exports as Tool, expandTilde, optional };
17450
+ export { control_exports as Control, db_exports as Database, DateTimeUtcFromMillis, schema_exports as DocumentSchema, event_exports as Event, list_exports as EventList, registry_exports as EventRegistry, EventSchema, git_exports as Git, global_exports as Global, harness_exports as Harness, location_exports as Location, mcp_exports as Mcp, config_exports as McpConfig, error_exports as McpError, oauth_exports as McpOAuth, catalog_exports as ModelCatalog, plugin_exports as Plugin, project_exports as Project, schema_exports$1 as PromptSchema, run_exports as Runner, sandbox_exports as Sandbox, SandboxError, session_exports as Session, session_exports$1 as SessionStore, settings_exports as Settings, state_exports as State, store_exports as Store, sync_exports as Sync, schema_exports$2 as ThreadSchema, thread_exports as ThreadStore, tool_exports as Tool, expandTilde, optional };
16853
17451
 
16854
17452
  //# sourceMappingURL=effect.mjs.map