clanka 0.24.3 → 0.24.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/Agent.d.ts.map +1 -1
  2. package/dist/Agent.js +24 -11
  3. package/dist/Agent.js.map +1 -1
  4. package/dist/Agent.test.js +137 -0
  5. package/dist/Agent.test.js.map +1 -1
  6. package/dist/AgentTools.d.ts +88 -88
  7. package/dist/AgentTools.d.ts.map +1 -1
  8. package/dist/OutputFormatter.d.ts +1 -1
  9. package/dist/OutputFormatter.d.ts.map +1 -1
  10. package/dist/OutputFormatter.js +42 -2
  11. package/dist/OutputFormatter.js.map +1 -1
  12. package/dist/OutputFormatter.test.d.ts +2 -0
  13. package/dist/OutputFormatter.test.d.ts.map +1 -0
  14. package/dist/OutputFormatter.test.js +93 -0
  15. package/dist/OutputFormatter.test.js.map +1 -0
  16. package/dist/bin/{Stream-C51usiew.mjs → AiError-CsvdOsKR.mjs} +533 -74
  17. package/dist/bin/Latch-B3e9629m.mjs +5 -0
  18. package/dist/bin/{McpClient-DoPNaNzW.mjs → McpClient-BCxZZgnA.mjs} +2 -3
  19. package/dist/bin/{OutputFormatter-U02YKTfy.mjs → OutputFormatter-ByMjyBhe.mjs} +40 -4
  20. package/dist/bin/{Schema-Box_9VZG.mjs → Schema-BfUmMefy.mjs} +5602 -360
  21. package/dist/bin/{SemanticSearch-CH125AHH.mjs → SemanticSearch-DMzIsoZb.mjs} +80 -68
  22. package/dist/bin/cli.mjs +849 -1163
  23. package/dist/bin/{helpers-CljL9OKa.mjs → helpers-Bb68A2Sv.mjs} +2 -2
  24. package/dist/bin/{index.min-ClUfQ5ji.mjs → index.min-CuA3AuA-.mjs} +1448 -1348
  25. package/dist/bin/{rolldown-runtime-5zChB7MF.mjs → rolldown-runtime-CXhmmSW5.mjs} +4 -4
  26. package/dist/bin/{server-HlLriZxF.mjs → server-D4nrvZHH.mjs} +2 -2
  27. package/dist/bin/{turndown.cjs-C2WBxeA-.mjs → turndown.cjs-CwE2EFNQ.mjs} +15 -10
  28. package/dist/bin/{types-LcwjLVkt.mjs → types-N9Z-HYP0.mjs} +1 -1
  29. package/dist/bin/{upgrade-HMRGSqq8.mjs → upgrade-t590zYhO.mjs} +5 -6
  30. package/package.json +15 -15
  31. package/src/Agent.test.ts +198 -0
  32. package/src/Agent.ts +28 -11
  33. package/src/OutputFormatter.test.ts +158 -0
  34. package/src/OutputFormatter.ts +56 -1
  35. package/dist/bin/Effect-5XYMLOiB.mjs +0 -5183
  36. package/dist/bin/Latch-BnrpWMd1.mjs +0 -5
@@ -1,16 +1,17 @@
1
- import { $ as ignoreCause, $i as onExitUnsafe, $r as TracerTimingEnabled, Ai as endSpan, An as size, Ao as merge, As as assignProperty, B as fn, Ba as sort, Bc as pipeArguments, C as catchTags, Cn as empty$1, Co as get$1, Cr as reasonAnnotations, D as delay, Di as contextWith$1, Dn as make$8, Do as getUnsafe, Dr as effect, E as contextWith, Ea as fromIterable, En as isEmpty, Ft as runFork, Go as isNone, Gr as close, Hr as Scope, I as filterOrFail, Ia as map$1, Ii as fiberInterrupt, Ir as provide$1, It as runForkWith, J as forkScoped, Jr as make$7, Js as symbol, Ks as byReferenceUnsafe, Kt as succeed, L as flatMap, Lc as pipe, Ln as spaced, Lo as flatten, Lr as provideMerge, M as fail, Mc as dual, Mt as request$1, N as failCause$1, Nc as flow, O as die, On as remove, Oo as make$9, Or as effectContext, Os as withFiber$1, Ot as provideContext, Pc as identity, Po as filter, Pt as retry, Q as ignore, Qt as tapCause, S as catchTag, T as context, Ta as flatMapNullishOr, Tn as get$2, To as getOrUndefined, Tt as orElseSucceed, U as forEach, Ui as forkUnsafe, Ur as addFinalizer, V as fnUntraced, Vt as scoped, W as forever, Wt as serviceOption, Xo as match, Xr as provide, Xt as sync, Yi as makeSpanUnsafe, Yo as map$2, Yt as suspend, Z as gen, Zn as NoSuchElementError, Zo as none, Zs as hash, Zt as tap, _i as isFailure, _n as withSpan, a as andThen, ac as hasProperty, b as catchNoSuchElement, ba as empty, bi as void_$3, bo as Service, bt as onExit, c as as, ca as updateContext, ci as makeUnsafe$2, co as isFinite, cr as fromReasons, ct as makeSpanScoped, da as ParentSpan, dn as void_$1, do as millis, es as some, et as interrupt, fc as isNotNull, fi as fail$1, fo as minutes, ft as mapError, g as catchDefect, go as toMillis, gt as matchCauseEffect, ha as toPredicate, hn as withLogSpan, ho as seconds, hr as isFailReason, hs as Prototype, ht as matchCauseEager, i as all, ic as symbol$1, ii as into, in as try_, io as fromInputUnsafe, is as Number$1, ji as exitHasInterrupts, jo as omit, ka as isArrayNonEmpty, kc as constUndefined, kn as set, kr as effectDiscard, kt as provideService, la as void_$2, lo as isZero, lt as map, m as catchCause, ma as has, mn as withFiber, n as acquireUseRelease, nr as combine, nt as isEffect, o as annotateCurrentSpan, oo as infinity, or as filterInterruptors, ot as logInfo, pa as compose, pi as failCause, qo as isSome, qs as equals, ra as succeed$1, rn as tryPromise, rt as logDebug, s as annotateLogs, sn as uninterruptibleMask, t as acquireRelease, ti as doneUnsafe, u as asVoid, un as useSpan, ur as hasInterruptsOnly, us as make$10, vi as isSuccess, vo as zero, vr as makeDieReason, vs as PipeInspectableProto, w as catch_, wn as forEach$1, wo as getOption, wt as orDie, xi as ClockRef, xn as Class$1, xo as add, xt as onExitPrimitive, y as catchIf, yi as succeed$2, yo as Reference, yt as onError, zi as fiberJoin, zo as fromNullishOr } from "./Effect-5XYMLOiB.mjs";
2
- import { B as String$1, Cn as evolve, E as Natural, H as Struct$2, Jr as now, K as TaggedError, Kr as formatIsoDate, M as Number$2, N as Option, P as OptionFromNullOr, Yr as removeTime, _r as transform, a as BooleanFromBit, bn as withConstructorDefault, ci as TaggedError$1, d as DateTimeUtcFromMillis, dn as optional, dt as decodeTo, f as DateTimeUtcFromString, fn as optionalKey, fr as transformOptional, ft as decodeUnknownEffect, ht as encodeEffect, i as Boolean, ii as monotonicTimeNanos, j as NullOr, l as DateTimeUtc, mr as map$3, n as ArraySchema, ni as Clock, ot as brand, p as Defect, pr as dateTimeUtcFromInput, rt as Union$2, s as Class$2, tn as isSchema, u as DateTimeUtcFromDate, un as mutable, ur as transform$1, yn as toType, yt as instanceOf } from "./Schema-Box_9VZG.mjs";
3
- import { C as ChildProcessSpawner, E as FileSystem, S as make$11, T as Path, a as makeGrouped, d as maybeRemoveFile, f as maybeUpdateFile, i as batchN, n as EmbeddingModel, o as setDelay, p as map$4, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, u as SemanticSearch, w as Console } from "./cli.mjs";
4
- import { A as fromQueue, C as fromArray, Ct as failCauseUnsafe, G as provideService$1, Ht as interruptAllAs, J as runDrain, Ot as offerUnsafe, Ut as join$1, Wt as runIn, _t as makeUnsafe$3, dt as unwrap, gt as make$13, q as runCollect, st as tap$1, u as die$1, w as fromArrayEffect, wt as make$12, y as flatMap$1 } from "./Stream-C51usiew.mjs";
1
+ import { $i as ignore, $l as fromInputUnsafe, $o as NoSuchElementError, $s as TracerTimingEnabled$1, Ai as delay, Ao as size, B as String$1, Bd as identity, Ci as catchNoSuchElement, Cn as evolve, Co as empty$1, Cs as reasonAnnotations, Dc as contextWith$1, Di as catch_, Do as make$8, Ds as effect, E as Natural, Ei as catchTags, Eo as isEmpty, Fa as retry, Fd as constUndefined, Fi as fail, Fl as sort, Fu as isNone, Gc as makeSpanUnsafe, Gi as forever, Gs as close, H as Struct$2, Hd as pipe, Hi as fn, Hs as Scope, Hu as some, Ia as runFork, Ii as failCause$1, Is as provide$1, Iu as isSome, Jo as Clock, Jr as now, Js as make$7, Ju as Prototype, K as TaggedError, Ka as succeed, Kr as formatIsoDate, Ku as make$10, La as runForkWith, Lc as fiberJoin, Lo as spaced, Ls as provideMerge, Lu as map$3, M as Number$1, N as Option, Na as request$1, Oa as provideContext, Oc as endSpan, Oi as context, Oo as remove, Os as effectContext, Ou as flatten, P as OptionFromNullOr, Pc as fiberInterrupt, Qa as tapCause, Qi as gen, Rd as dual, Ri as filterOrFail, Ru as match, Sd as isNotNull, Si as catchIf, Sl as fromIterable, Su as omit, Ta as orElseSucceed, Ti as catchTag, Tl as isArrayNonEmpty, To as get$2, Tu as filter, Ud as pipeArguments, Ui as fnUntraced, Us as addFinalizer, Va as scoped, Vc as forkUnsafe, Wa as serviceOption, Wi as forEach, Wu as Number$2, Xa as sync, Xc as succeed$1, Xo as monotonicTimeNanos, Xs as provide, Xu as PipeInspectableProto, Ya as suspend, Yi as forkScoped, Yr as removeTime, Za as tap, _c as isFailure, _d as symbol, _i as catchCause, _o as withSpan, _r as transform, _s as isFailReason, a as BooleanFromBit, ad as withFiber$1, ai as acquireUseRelease, al as ParentSpan, au as millis, ba as onExit, bc as void_$3, bd as hasProperty, bn as withConstructorDefault, cc as makeUnsafe$2, ci as andThen, cs as filterInterruptors, cu as toMillis, d as DateTimeUtcFromMillis, di as as, dl as compose, dn as optional, do as void_$1, dt as decodeTo, du as Service, ea as ignoreCause, f as DateTimeUtcFromString, fc as fail$1, fl as has, fn as optionalKey, fr as transformOptional, fs as hasInterruptsOnly, ft as decodeUnknownEffect, fu as add, ga as matchCauseEffect, gd as equals, gl as empty, gu as getOrUndefined, ha as matchCauseEager, hd as byReferenceUnsafe, ho as withLogSpan, ht as encodeEffect, hu as getOption, i as Boolean, ia as logDebug, ic as into, ii as acquireRelease, io as try_, is as combine, j as NullOr, ji as die, jl as map$2, ka as provideService, kc as exitHasInterrupts, ki as contextWith, ko as set, ks as effectDiscard, ku as fromNullishOr, l as DateTimeUtc, la as makeSpanScoped, li as annotateCurrentSpan, ll as TaggedError$1, lu as zero, mo as withFiber, mr as map$1, mu as get$1, n as ArraySchema, nl as void_$2, nu as isFinite, od as assignProperty, oo as uninterruptible, ot as brand, ou as minutes, p as Defect, pa as mapError, pc as failCause, pi as asVoid, pl as toPredicate, pr as dateTimeUtcFromInput, qc as onExitUnsafe, ra as isEffect, rl as TracerTimingEnabled, ro as tryPromise, rt as Union$2, ru as isZero, s as Class$1, sa as logInfo, si as all, so as uninterruptibleMask, su as seconds, ta as interrupt, tc as doneUnsafe, tl as updateContext, tn as isSchema, tu as infinity, u as DateTimeUtcFromDate, ua as map, ui as annotateLogs, un as mutable, uo as useSpan, ur as transform$1, us as fromReasons, uu as Reference, vc as isSuccess, vd as hash, vu as getUnsafe, wa as orDie, wo as forEach$1, xa as onExitPrimitive, xc as ClockRef, xl as flatMapNullishOr, xo as Class$2, xu as merge, ya as onError, yc as succeed$2, yd as symbol$1, yi as catchDefect, yn as toType, ys as makeDieReason, yt as instanceOf, yu as make$9, zd as flow, zi as flatMap, zu as none } from "./Schema-BfUmMefy.mjs";
2
+ import { D as Path, E as Console, O as FileSystem, T as ChildProcessSpawner, a as makeGrouped, f as SemanticSearch, h as map$4, i as batchN, m as maybeUpdateFile, n as EmbeddingModel, o as setDelay, p as maybeRemoveFile, r as EmbeddingRequest, s as withSpan$1, t as Dimensions, w as make$11 } from "./cli.mjs";
3
+ import { $t as offerUnsafe, Ht as makeUnsafe$3, It as unwrap, J as fromArrayEffect, Jt as failCauseUnsafe, Mt as tap$1, P as die$1, U as flatMap$1, Vt as make$13, Yt as make$12, gt as provideService$1, hn as runIn, mn as join$1, pn as interruptAllAs, q as fromArray, tt as fromQueue, vt as runCollect, yt as runDrain } from "./AiError-CsvdOsKR.mjs";
5
4
  import { createHash } from "node:crypto";
6
5
  import { DatabaseSync, backup } from "node:sqlite";
7
6
  import TreeSitter from "tree-sitter";
8
7
  import TreeSitterJavaScript from "tree-sitter-javascript";
9
8
  import TreeSitterTypeScript from "tree-sitter-typescript";
10
9
  import { getLoadablePath } from "sqlite-vec";
11
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/internal/sql.js
10
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/internal/sql.js
12
11
  const CurrentTransactionService = Reference("effect/sql/CurrentTransactionService", { defaultValue: () => void 0 });
13
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/reactivity/Reactivity.js
12
+ const waitClock = (fiber) => fiber.getRef(TracerTimingEnabled) ? fiber.getRef(Clock) : void 0;
13
+ const recordConnectionWait = (span, clock) => span.attribute("db.client.connection.wait_time_ms", Number(clock.currentTimeNanosUnsafe() - span.status.startTime) / 1e6);
14
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/reactivity/Reactivity.js
14
15
  const TypeId$6 = "~effect/reactivity/Reactivity";
15
16
  const Reactivity = Service("effect/reactivity/Reactivity");
16
17
  const make$6 = sync(() => {
@@ -131,7 +132,7 @@ const keysToHashes = (keys, f) => {
131
132
  for (let i = 0; i < ids.length; i++) f(`${key}:${stringOrHash(ids[i])}`);
132
133
  }
133
134
  };
134
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlError.js
135
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlError.js
135
136
  const TypeId$5 = "~effect/sql/SqlError";
136
137
  const ReasonTypeId = "~effect/sql/SqlError/Reason";
137
138
  const ReasonFields = {
@@ -304,7 +305,7 @@ var ResultLengthMismatch = class extends TaggedError("effect/sql/ResultLengthMis
304
305
  return `Expected ${this.expected} results but got ${this.actual}`;
305
306
  }
306
307
  };
307
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/Statement.js
308
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/Statement.js
308
309
  const FragmentTypeId = Symbol.for("~effect/sql/Statement/Fragment");
309
310
  const SegmentTypeId = Symbol.for("~effect/sql/Statement/Segment");
310
311
  const fragment = (segments) => ({
@@ -367,15 +368,13 @@ const recordUpdateHelperSingle = (value, omit) => Object.assign(Object.create(Re
367
368
  returningIdentifier: void 0
368
369
  });
369
370
  const make$5 = (acquirer, compiler, spanAttributes, transformRows, borrower) => {
370
- const cache = transformRows === void 0 ? constructorCache.noTransforms : constructorCache.transforms;
371
- if (cache.has(acquirer)) return cache.get(acquirer);
372
371
  const self = Object.assign(function sql(strings, ...args) {
373
372
  if (typeof strings === "string") return identifier(strings);
374
- else if (Array.isArray(strings) && "raw" in strings) return statement(acquirer, compiler, strings, args, spanAttributes, transformRows, borrower);
373
+ else if (Array.isArray(strings) && "raw" in strings) return makeUnsafe$1(templateSegments(strings, args), acquirer, compiler, spanAttributes, transformRows, borrower, self);
375
374
  throw "absurd";
376
375
  }, {
377
376
  unsafe(sql, params) {
378
- return makeUnsafe$1([literal(sql, params)], acquirer, compiler, spanAttributes, transformRows, borrower);
377
+ return makeUnsafe$1([literal(sql, params)], acquirer, compiler, spanAttributes, transformRows, borrower, self);
379
378
  },
380
379
  literal(sql) {
381
380
  return fragment([literal(sql)]);
@@ -401,14 +400,9 @@ const make$5 = (acquirer, compiler, spanAttributes, transformRows, borrower) =>
401
400
  return options[compiler.dialect] !== void 0 ? options[compiler.dialect]() : options.orElse();
402
401
  }
403
402
  });
404
- cache.set(acquirer, self);
405
403
  return self;
406
404
  };
407
- const constructorCache = {
408
- transforms: new WeakMap(),
409
- noTransforms: new WeakMap()
410
- };
411
- const statement = (acquirer, compiler, strings, args, spanAttributes, transformRows, borrower) => {
405
+ const templateSegments = (strings, args) => {
412
406
  const segments = strings[0].length > 0 ? [literal(strings[0])] : [];
413
407
  for (let i = 0; i < args.length; i++) {
414
408
  const arg = args[i];
@@ -417,7 +411,7 @@ const statement = (acquirer, compiler, strings, args, spanAttributes, transformR
417
411
  else segments.push(parameter(arg));
418
412
  if (strings[i + 1].length > 0) segments.push(literal(strings[i + 1]));
419
413
  }
420
- return makeUnsafe$1(segments, acquirer, compiler, spanAttributes, transformRows, borrower);
414
+ return segments;
421
415
  };
422
416
  function join(lit, addParens = true, fallback = "") {
423
417
  const literalStatement = literal(lit);
@@ -691,13 +685,12 @@ const spanName = (spanAttributes) => {
691
685
  return isNonEmptyString(system) ? system : "sql.execute";
692
686
  };
693
687
  const ATTR_DB_QUERY_TEXT = "db.query.text";
694
- const ATTR_DB_CLIENT_CONNECTION_WAIT_TIME = "db.client.connection.wait_time_ms";
695
688
  const ATTR_SQL_METHOD = "effect.sql.method";
696
689
  const spanAttribute = (spanAttributes, key) => {
697
690
  for (let i = spanAttributes.length - 1; i >= 0; i--) if (spanAttributes[i][0] === key) return spanAttributes[i][1];
698
691
  };
699
692
  const isNonEmptyString = (u) => typeof u === "string" && u.length > 0;
700
- const makeUnsafe$1 = (segments, acquirer, compiler, spanAttributes, transformRows, borrower) => {
693
+ const makeUnsafe$1 = (segments, acquirer, compiler, spanAttributes, transformRows, borrower, sql) => {
701
694
  const self = Object.create(StatementProto);
702
695
  self.segments = segments;
703
696
  self.acquirer = acquirer;
@@ -705,6 +698,7 @@ const makeUnsafe$1 = (segments, acquirer, compiler, spanAttributes, transformRow
705
698
  self.spanAttributes = spanAttributes;
706
699
  self.transformRows = transformRows;
707
700
  self.borrower = borrower;
701
+ self.sql = sql;
708
702
  return self;
709
703
  };
710
704
  const StatementProto = {
@@ -765,7 +759,7 @@ const StatementProto = {
765
759
  evaluate(fiber) {
766
760
  const span = makeSpanUnsafe(fiber, spanName(this.spanAttributes), { kind: "client" });
767
761
  const clock = fiber.getRef(Clock);
768
- const timingEnabled = fiber.getRef(TracerTimingEnabled);
762
+ const timingEnabled = fiber.getRef(TracerTimingEnabled$1);
769
763
  return onExit(this.withConnectionSpan("execute", (connection, sql, params) => connection.execute(sql, params, this.transformRows), false, span), (exit) => endSpan(span, exit, clock, timingEnabled));
770
764
  }
771
765
  }),
@@ -782,12 +776,10 @@ const StatementProto = {
782
776
  };
783
777
  }
784
778
  };
785
- const waitClock = (fiber) => fiber.getRef(TracerTimingEnabled) ? fiber.getRef(Clock) : void 0;
786
- const recordConnectionWait = (span, clock) => span.attribute(ATTR_DB_CLIENT_CONNECTION_WAIT_TIME, Number(clock.currentTimeNanosUnsafe() - span.status.startTime) / 1e6);
787
779
  const withStatement = (self, span, f) => withFiber((fiber) => {
788
780
  const transform = fiber.getRef(CurrentTransformer);
789
781
  if (transform === void 0) return f(self, fiber);
790
- return flatMap(transform(self, make$5(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), fiber, span), (statement) => f(statement, fiber));
782
+ return flatMap(transform(self, self.sql ?? make$5(self.acquirer, self.compiler, self.spanAttributes, self.transformRows, self.borrower), fiber, span), (statement) => f(statement, fiber));
791
783
  });
792
784
  const isSegment = (u) => hasProperty(u, SegmentTypeId);
793
785
  function convertLiteralOrFragment(clause) {
@@ -830,16 +822,17 @@ function in_() {
830
822
  const neverFragment = fragment([literal("1=0")]);
831
823
  const emptyInKeyword = /\b(NOT\s+)?IN\s*$/i;
832
824
  const isInLineComment = (sql, index) => sql.lastIndexOf("--", index) > sql.lastIndexOf("\n", index);
833
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlClient.js
825
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlClient.js
834
826
  const TypeId$4 = "~effect/sql/SqlClient";
835
827
  const SqlClient = Service("effect/sql/SqlClient");
836
828
  let clientIdCounter = 0;
837
829
  let transactionSemaphoreIdCounter = 0;
830
+ const ATTR_DB_OPERATION_NAME = "db.operation.name";
838
831
  const make$4 = fnUntraced(function* (options) {
839
832
  const transactionService = options.transactionService ?? TransactionConnection(clientIdCounter++);
840
833
  const getConnection = flatMap(serviceOption(transactionService), match({
841
834
  onNone: () => options.acquirer,
842
- onSome: ([conn]) => succeed(conn)
835
+ onSome: activeTransactionConnection
843
836
  }));
844
837
  const beginTransaction = options.beginTransaction ?? "BEGIN";
845
838
  const commit = options.commit ?? "COMMIT";
@@ -856,7 +849,7 @@ const make$4 = fnUntraced(function* (options) {
856
849
  transactionService,
857
850
  spanAttributes: options.spanAttributes,
858
851
  acquireConnection: (restore) => restore(transactionAcquirer),
859
- begin: (conn, statement) => statement === void 0 ? control(conn, beginTransaction) : unprepared(conn, statement),
852
+ begin: options.begin ?? ((conn, statement) => statement === void 0 ? control(conn, beginTransaction) : unprepared(conn, statement)),
860
853
  savepoint: (conn, id) => control(conn, savepoint(`effect_sql_${id}`)),
861
854
  releaseSavepoint: releaseSavepoint ? (conn, id) => cleanup(conn, releaseSavepoint(`effect_sql_${id}`)) : void 0,
862
855
  commit: typeof commit === "string" ? (conn) => control(conn, commit) : commit,
@@ -868,7 +861,7 @@ const make$4 = fnUntraced(function* (options) {
868
861
  const reactivity = yield* Reactivity;
869
862
  const borrower = options.borrower === void 0 ? void 0 : (f) => flatMap(serviceOption(transactionService), match({
870
863
  onNone: () => options.borrower(f),
871
- onSome: ([conn]) => f(conn)
864
+ onSome: (transaction) => flatMap(activeTransactionConnection(transaction), f)
872
865
  }));
873
866
  const client = Object.assign(make$5(getConnection, options.compiler, options.spanAttributes, options.transformRows, borrower), {
874
867
  [TypeId$4]: TypeId$4,
@@ -879,7 +872,6 @@ const make$4 = fnUntraced(function* (options) {
879
872
  reserve: transactionAcquirer,
880
873
  driver: options.driver,
881
874
  withoutTransforms() {
882
- if (options.transformRows === void 0) return this;
883
875
  const statement = make$5(getConnection, options.compiler.withoutTransform, options.spanAttributes, void 0, borrower);
884
876
  const client = Object.assign(statement, {
885
877
  ...this,
@@ -933,6 +925,15 @@ const isNoTransactionError = (error) => {
933
925
  };
934
926
  const failuresToDefects = (cause) => fromReasons(cause.reasons.map((reason) => isFailReason(reason) ? makeDieReason(reason.error).annotate(reasonAnnotations(reason)) : reason));
935
927
  const afterCommitBuffers = new WeakMap();
928
+ const hasEnded = (buffer) => {
929
+ for (; buffer !== void 0; buffer = buffer.parent) if (!buffer.open) return true;
930
+ return false;
931
+ };
932
+ const transactionEnded = suspend(() => fail(new SqlError({ reason: new UnknownError({
933
+ cause: void 0,
934
+ message: "SqlClient: the transaction has already ended"
935
+ }) })));
936
+ const activeTransactionConnection = (transaction) => hasEnded(afterCommitBuffers.get(transaction)) ? transactionEnded : succeed(transaction[0]);
936
937
  const runAfterCommit = (effect) => ignoreCause(effect, {
937
938
  log: "Unhandled",
938
939
  message: "Unhandled error in SqlClient.afterCommit callback"
@@ -941,13 +942,14 @@ const makeAfterCommit = (transactionService) => (effect) => withFiber((fiber) =>
941
942
  const transaction = getOrUndefined(fiber.context, transactionService);
942
943
  const buffer = transaction && afterCommitBuffers.get(transaction);
943
944
  if (buffer === void 0) return runAfterCommit(effect);
944
- for (let current = buffer; current !== void 0; current = current.parent) if (!current.open) return die(new Error("SqlClient.afterCommit: the transaction has already ended"));
945
+ if (hasEnded(buffer)) return die(new Error("SqlClient.afterCommit: the transaction has already ended"));
945
946
  buffer.callbacks.push(provideContext(effect, omit(transactionService)(fiber.context)));
946
947
  return void_$1;
947
948
  });
948
949
  const makeWithTransaction = (options) => {
949
950
  const transactionSemaphore = Service(`effect/sql/SqlClient/TransactionSemaphore/${transactionSemaphoreIdCounter++}`);
950
951
  const afterCommit = makeAfterCommit(options.transactionService);
952
+ const target = spanTarget(options.spanAttributes);
951
953
  const deferInvalidations = (reactivity) => {
952
954
  const invalidate = (keys) => afterCommit(sync(() => reactivity.invalidateUnsafe(keys)));
953
955
  return {
@@ -960,9 +962,20 @@ const makeWithTransaction = (options) => {
960
962
  for (const [key, value] of options.spanAttributes) span.attribute(key, value);
961
963
  const services = fiber.context;
962
964
  const reactivity = getOrUndefined(services, Reactivity);
963
- const clock = fiber.getRef(Clock);
965
+ const waitedClock = fiber.cache.tracerEnabled && fiber.getRef(SpanPropagationEnabled) ? waitClock(fiber) : void 0;
966
+ const control = (operation, effect) => useSpan(target === void 0 ? operation : `${operation} ${target}`, {
967
+ kind: "client",
968
+ parent: span
969
+ }, (controlSpan) => {
970
+ for (const [key, value] of options.spanAttributes) controlSpan.attribute(key, value);
971
+ controlSpan.attribute(ATTR_DB_OPERATION_NAME, operation);
972
+ return effect;
973
+ });
964
974
  const connOption = getOption(services, options.transactionService);
965
- const conn = connOption._tag === "Some" ? succeed([void 0, connOption.value[0]]) : flatMap(make$7(), (scope) => provide(options.acquireConnection(restore), scope).pipe(map((conn) => [scope, conn]), onError((cause) => close(scope, failCause(cause)))));
975
+ const conn = connOption._tag === "Some" ? map(suspend(() => activeTransactionConnection(connOption.value)), (conn) => [void 0, conn]) : flatMap(make$7(), (scope) => provide(options.acquireConnection(restore), scope).pipe(provideService(ParentSpan, span), map((conn) => {
976
+ if (waitedClock !== void 0) recordConnectionWait(span, waitedClock);
977
+ return [scope, conn];
978
+ }), onError((cause) => close(scope, failCause(cause)))));
966
979
  const id = connOption._tag === "Some" ? connOption.value[1] + 1 : 0;
967
980
  const buffer = {
968
981
  callbacks: [],
@@ -970,28 +983,28 @@ const makeWithTransaction = (options) => {
970
983
  open: true
971
984
  };
972
985
  let committed = false;
973
- const transaction = flatMap(conn, ([scope, conn]) => (id === 0 ? options.begin(conn, fiber.getRef(BeginTransaction)) : options.savepoint(conn, id)).pipe(flatMap(() => {
986
+ const start = (conn) => id === 0 ? control("BEGIN", options.begin(conn, fiber.getRef(BeginTransaction))) : control("SAVEPOINT", options.savepoint(conn, id));
987
+ const transaction = flatMap(conn, ([scope, conn]) => start(conn).pipe(flatMap(() => {
974
988
  const level = [conn, id];
975
989
  afterCommitBuffers.set(level, buffer);
976
990
  return onExitPrimitive(provideContext(restore(effect), services.pipe(add(options.transactionService, level), add(CurrentTransactionService, options.transactionService), reactivity ? add(Reactivity, deferInvalidations(reactivity)) : identity, add(transactionSemaphore, makeUnsafe$3(1)), add(ParentSpan, span))), (exit) => {
991
+ buffer.open = false;
992
+ if (hasEnded(buffer.parent)) return isSuccess(exit) ? transactionEnded : exit;
977
993
  let effect;
978
994
  if (isSuccess(exit)) {
979
995
  if (id === 0) {
980
- span.event("effect.sql.transaction.commit", clock.currentTimeNanosUnsafe());
981
996
  const onCommitFailure = options.onCommitFailure;
982
- effect = onCommitFailure ? catchCause(options.commit(conn), (commitCause) => matchCauseEffect(onCommitFailure(conn), {
997
+ const commit = control("COMMIT", options.commit(conn));
998
+ effect = onCommitFailure ? catchCause(commit, (commitCause) => matchCauseEffect(control("ROLLBACK", onCommitFailure(conn)), {
983
999
  onFailure: (cleanupCause) => failCause$1(failuresToDefects(combine(commitCause, cleanupCause))),
984
1000
  onSuccess: () => failCause$1(commitCause)
985
- })) : options.commit(conn);
986
- } else {
987
- span.event("effect.sql.transaction.savepoint", clock.currentTimeNanosUnsafe());
988
- effect = void_$1;
989
- }
990
- } else {
991
- span.event("effect.sql.transaction.rollback", clock.currentTimeNanosUnsafe());
992
- effect = orDie(id > 0 ? options.rollbackSavepoint(conn, id) : options.rollback(conn));
1001
+ })) : commit;
1002
+ } else effect = void_$1;
1003
+ } else effect = orDie(id > 0 ? control("ROLLBACK TO SAVEPOINT", options.rollbackSavepoint(conn, id)) : control("ROLLBACK", options.rollback(conn)));
1004
+ if (id > 0 && options.releaseSavepoint) {
1005
+ const release = orDie(control("RELEASE SAVEPOINT", options.releaseSavepoint(conn, id)));
1006
+ effect = flatMap(effect, () => hasEnded(buffer.parent) ? void_$1 : release);
993
1007
  }
994
- if (id > 0 && options.releaseSavepoint) effect = andThen(effect, orDie(options.releaseSavepoint(conn, id)));
995
1008
  return flatMap(effect, () => {
996
1009
  committed = isSuccess(exit);
997
1010
  return exit;
@@ -999,7 +1012,6 @@ const makeWithTransaction = (options) => {
999
1012
  }, true);
1000
1013
  }), scope ? (eff) => onExitPrimitive(eff, (exit) => close(scope, exit), true) : identity));
1001
1014
  const settled = onExitPrimitive(transaction, () => {
1002
- buffer.open = false;
1003
1015
  if (!committed || buffer.callbacks.length === 0) return;
1004
1016
  if (buffer.parent !== void 0) {
1005
1017
  buffer.parent.callbacks.push(...buffer.callbacks);
@@ -1007,13 +1019,13 @@ const makeWithTransaction = (options) => {
1007
1019
  }
1008
1020
  return forEach(buffer.callbacks, runAfterCommit, { discard: true });
1009
1021
  }, true);
1010
- return id === 0 ? settled : getUnsafe(services, transactionSemaphore).withPermit(settled);
1022
+ return id === 0 ? settled : restore(getUnsafe(services, transactionSemaphore).withPermit(uninterruptible(settled)));
1011
1023
  })));
1012
1024
  };
1013
1025
  const TransactionConnection = (clientId) => Service(`effect/sql/SqlClient/TransactionConnection/${clientId}`);
1014
1026
  const SafeIntegers = Reference("effect/sql/SqlClient/SafeIntegers", { defaultValue: () => false });
1015
1027
  const BeginTransaction = Reference("effect/sql/SqlClient/BeginTransaction", { defaultValue: () => void 0 });
1016
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/Cache.js
1028
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/Cache.js
1017
1029
  const TypeId$3 = "~effect/Cache";
1018
1030
  const makeWith = (lookup, options) => contextWith$1((context) => {
1019
1031
  const self = Object.create(Proto$1);
@@ -1105,7 +1117,7 @@ const checkCapacity = (self) => {
1105
1117
  if (diff === 0) return;
1106
1118
  }
1107
1119
  };
1108
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/schema/VariantSchema.js
1120
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/schema/VariantSchema.js
1109
1121
  const TypeId$2 = "~effect/schema/VariantSchema";
1110
1122
  const cacheSymbol = Symbol.for(`${TypeId$2}/cache`);
1111
1123
  const defaultCacheSymbol = Symbol.for(`${TypeId$2}/defaultCache`);
@@ -1138,7 +1150,7 @@ const extract$1 = dual((args) => isStruct(args[0]), (self, variant, options) =>
1138
1150
  const make$3 = (options) => {
1139
1151
  function Class(identifier) {
1140
1152
  return function(fields, annotations) {
1141
- return makeClass(fields, (defaultFields) => Class$2(identifier)(defaultFields, annotations));
1153
+ return makeClass(fields, (defaultFields) => Class$1(identifier)(defaultFields, annotations));
1142
1154
  };
1143
1155
  }
1144
1156
  function makeClass(fields, makeSchemaClass) {
@@ -1222,7 +1234,7 @@ const Union$1 = (members, defaultVariant, variants) => {
1222
1234
  for (const variant of variants) Object.defineProperty(VariantUnion, variant, { value: Union$2(members.map((member) => extract$1(member, variant))) });
1223
1235
  return VariantUnion;
1224
1236
  };
1225
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/schema/Model.js
1237
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/schema/Model.js
1226
1238
  const { Class, Field, FieldExcept, FieldOnly, Struct, Union, extract, fieldEvolve } = make$3({
1227
1239
  variants: [
1228
1240
  "select",
@@ -1255,7 +1267,7 @@ const BooleanSqlite = Field({
1255
1267
  jsonUpdate: Boolean
1256
1268
  });
1257
1269
  const Date$1 = String$1.pipe(decodeTo(DateTimeUtc, {
1258
- decode: map$3(dateTimeUtcFromInput(), removeTime),
1270
+ decode: map$1(dateTimeUtcFromInput(), removeTime),
1259
1271
  encode: transform(formatIsoDate)
1260
1272
  }));
1261
1273
  const DateWithNow = Overrideable(Date$1, { defaultValue: map(now, removeTime) });
@@ -1295,9 +1307,9 @@ const DateTimeUpdateFromNumber = Field({
1295
1307
  update: DateTimeFromNumberWithNow,
1296
1308
  json: DateTimeUtcFromMillis
1297
1309
  });
1298
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlResolver.js
1310
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlResolver.js
1299
1311
  const SqlRequestProto = {
1300
- ...Class$1.prototype,
1312
+ ...Class$2.prototype,
1301
1313
  [symbol](that) {
1302
1314
  return equals(this.payload, that.payload);
1303
1315
  },
@@ -1427,13 +1439,13 @@ function transactionKey(entry) {
1427
1439
  if (currentTransaction === void 0) return byReferenceUnsafe(clientTransaction);
1428
1440
  return [byReferenceUnsafe(clientTransaction), byReferenceUnsafe(currentTransaction)];
1429
1441
  }
1430
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlSchema.js
1442
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlSchema.js
1431
1443
  const findAll = (options) => {
1432
1444
  const encodeRequest = encodeEffect(options.Request);
1433
1445
  const decode = decodeUnknownEffect(mutable(ArraySchema(options.Result)));
1434
1446
  return (request) => flatMap(flatMap(encodeRequest(request), options.execute), decode);
1435
1447
  };
1436
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/SqlModel.js
1448
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/SqlModel.js
1437
1449
  const makeResolvers = (Model, options) => gen(function* () {
1438
1450
  const sql = yield* SqlClient;
1439
1451
  const idSchema = Model.fields[options.idColumn];
@@ -1470,10 +1482,10 @@ select * from ${sql(options.tableName)} where ${withSoftDeleteFilter(sql`${sql(i
1470
1482
  };
1471
1483
  });
1472
1484
  // src/ChunkRepo.ts
1473
- const ChunkId = Number$2.pipe(brand("ChunkRepo/ChunkId"));
1485
+ const ChunkId = Number$1.pipe(brand("ChunkRepo/ChunkId"));
1474
1486
  const SyncId = String$1.pipe(brand("ChunkRepo/SyncId"));
1475
1487
  const Float32ArraySchema = instanceOf(Float32Array);
1476
- const Float32ArrayFromArray = ArraySchema(Number$2).pipe(decodeTo(Float32ArraySchema, transform$1({
1488
+ const Float32ArrayFromArray = ArraySchema(Number$1).pipe(decodeTo(Float32ArraySchema, transform$1({
1477
1489
  decode: (arr) => new Float32Array(arr),
1478
1490
  encode: (array) => Array.from(array)
1479
1491
  })));
@@ -1533,7 +1545,7 @@ const layer$4 = effect(ChunkRepo, gen(function* () {
1533
1545
  const search = findAll({
1534
1546
  Request: Struct$2({
1535
1547
  vector: Float32ArraySchema,
1536
- limit: Number$2
1548
+ limit: Number$1
1537
1549
  }),
1538
1550
  Result: Chunk,
1539
1551
  execute: ({ vector, limit }) => sql`
@@ -2044,7 +2056,7 @@ const layer$3 = effect(CodeChunker, gen(function* () {
2044
2056
  chunkCodebase
2045
2057
  });
2046
2058
  }));
2047
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/FiberHandle.js
2059
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/FiberHandle.js
2048
2060
  const TypeId$1 = "~effect/FiberHandle";
2049
2061
  const isFiberHandle = (u) => hasProperty(u, TypeId$1);
2050
2062
  const Proto = {
@@ -2119,7 +2131,7 @@ const runImpl = (self, effect, options) => withFiber((parent) => {
2119
2131
  setUnsafe(self, fiber, options);
2120
2132
  return succeed(fiber);
2121
2133
  });
2122
- // node_modules/.pnpm/@effect+sql-sqlite-node@4.1.1_effect@4.1.1/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
2134
+ // node_modules/.pnpm/@effect+sql-sqlite-node@4.1.3_effect@4.1.3/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
2123
2135
  const ATTR_DB_SYSTEM_NAME = "db.system.name";
2124
2136
  const MAX_BUSY_TIMEOUT = 2147483647;
2125
2137
  const NANOS_PER_MILLI = BigInt(1e6);
@@ -2288,7 +2300,7 @@ const sqliteCauseWithErrno = (cause) => {
2288
2300
  const setLoadExtensionEnabled = (db, enabled) => {
2289
2301
  if (typeof db.enableLoadExtension === "function") db.enableLoadExtension(enabled);
2290
2302
  };
2291
- // node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/sql/Migrator.js
2303
+ // node_modules/.pnpm/effect@4.1.3/node_modules/effect/dist/sql/Migrator.js
2292
2304
  var MigrationError = class extends TaggedError$1("MigrationError") {};
2293
2305
  const make = ({ transformWrites = identity, dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, table = "effect_sql_migrations" }) => gen(function* () {
2294
2306
  const sql = yield* SqlClient;
@@ -2326,11 +2338,11 @@ ORDER BY migration_id`,
2326
2338
  pg: () => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : asVoid(createMigrationsTable).pipe(catch_((error) => flatMap(migrationsTableExists(sql, table), (exists) => exists ? void_$1 : fail(error))))),
2327
2339
  orElse: () => createMigrationsTable
2328
2340
  });
2329
- const insertMigrations = (rows) => transformWrites(sql`INSERT INTO ${sql(table)} ${sql.insert(map$1(rows, ([migration_id, name]) => ({
2341
+ const insertMigrations = (rows) => transformWrites(sql`INSERT INTO ${sql(table)} ${sql.insert(map$2(rows, ([migration_id, name]) => ({
2330
2342
  migration_id,
2331
2343
  name
2332
2344
  })))}`.withoutTransform);
2333
- const latestMigration = map(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$2(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
2345
+ const latestMigration = map(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$3(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
2334
2346
  id: migration_id,
2335
2347
  name,
2336
2348
  createdAt: created_at
@@ -2377,7 +2389,7 @@ ORDER BY migration_id`,
2377
2389
  yield* loadMigration(resolved)
2378
2390
  ]);
2379
2391
  }
2380
- if (transactional && isArrayNonEmpty(required)) yield* pipe(insertMigrations(map$1(required, ([id, name]) => [id, name])), mapError((error) => isConstraintConflict(error) ? new MigrationError({
2392
+ if (transactional && isArrayNonEmpty(required)) yield* pipe(insertMigrations(map$2(required, ([id, name]) => [id, name])), mapError((error) => isConstraintConflict(error) ? new MigrationError({
2381
2393
  kind: "Locked",
2382
2394
  message: "Migrations already running"
2383
2395
  }) : error));
@@ -2397,14 +2409,14 @@ const migrationsTableExists = (sql, table) => {
2397
2409
  const quotedTable = sql`${sql(table)}`.compile(true)[0];
2398
2410
  return map(sql`SELECT 1 AS found WHERE to_regclass(${quotedTable}) IS NOT NULL`.withoutTransform, (rows) => rows.length > 0);
2399
2411
  };
2400
- const migrationOrder = make$10(([a], [b]) => Number$1(a, b));
2412
+ const migrationOrder = make$10(([a], [b]) => Number$2(a, b));
2401
2413
  const isConstraintConflict = (error) => error.reason._tag === "ConstraintError" || error.reason._tag === "UniqueViolation";
2402
- const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$1(([key, id, name]) => [
2414
+ const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$2(([key, id, name]) => [
2403
2415
  Number(id),
2404
2416
  name,
2405
2417
  succeed(migrations[key])
2406
2418
  ]), sort(migrationOrder), succeed);
2407
- // node_modules/.pnpm/@effect+sql-sqlite-node@4.1.1_effect@4.1.1/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
2419
+ // node_modules/.pnpm/@effect+sql-sqlite-node@4.1.3_effect@4.1.3/node_modules/@effect/sql-sqlite-node/dist/SqliteMigrator.js
2408
2420
  const run = make({});
2409
2421
  const layer$1 = (options) => effectDiscard(run(options));
2410
2422
  // src/Sqlite.ts