UNPKG

@hasna/projects

Version:

High-level project management CLI, MCP server, SDK, and AI SDK agent loop for coding agents

24,038 lines • 913 kB
// @bun
var __defProp = Object.defineProperty;
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;

// ../../node_modules/.bun/solid-js@1.9.13/node_modules/solid-js/dist/server.js
function getContextId(count) {
  const num = String(count), len = num.length - 1;
  return sharedConfig.context.id + (len ? String.fromCharCode(96 + len) : "") + num;
}
function setHydrateContext(context) {
  sharedConfig.context = context;
}
function nextHydrateContext() {
  return {
    ...sharedConfig.context,
    id: sharedConfig.getNextContextId(),
    count: 0
  };
}
function createRoot(fn, detachedOwner) {
  const listener = Listener, owner = Owner, unowned = fn.length === 0, current = detachedOwner === undefined ? owner : detachedOwner, root = unowned ? UNOWNED : {
    owned: null,
    cleanups: null,
    context: current ? current.context : null,
    owner: current
  }, updateFn = unowned ? fn : () => fn(() => untrack(() => cleanNode(root)));
  Owner = root;
  Listener = null;
  try {
    return runUpdates(updateFn, true);
  } finally {
    Listener = listener;
    Owner = owner;
  }
}
function createSignal(value, options) {
  options = options ? Object.assign({}, signalOptions, options) : signalOptions;
  const s = {
    value,
    observers: null,
    observerSlots: null,
    comparator: options.equals || undefined
  };
  const setter = (value2) => {
    if (typeof value2 === "function") {
      if (Transition && Transition.running && Transition.sources.has(s))
        value2 = value2(s.tValue);
      else
        value2 = value2(s.value);
    }
    return writeSignal(s, value2);
  };
  return [readSignal.bind(s), setter];
}
function createRenderEffect(fn, value, options) {
  const c = createComputation(fn, value, false, STALE);
  if (Scheduler && Transition && Transition.running)
    Updates.push(c);
  else
    updateComputation(c);
}
function createEffect(fn, value, options) {
  runEffects = runUserEffects;
  const c = createComputation(fn, value, false, STALE), s = SuspenseContext && useContext(SuspenseContext);
  if (s)
    c.suspense = s;
  if (!options || !options.render)
    c.user = true;
  Effects ? Effects.push(c) : updateComputation(c);
}
function createMemo(fn, value, options) {
  options = options ? Object.assign({}, signalOptions, options) : signalOptions;
  const c = createComputation(fn, value, true, 0);
  c.observers = null;
  c.observerSlots = null;
  c.comparator = options.equals || undefined;
  if (Scheduler && Transition && Transition.running) {
    c.tState = STALE;
    Updates.push(c);
  } else
    updateComputation(c);
  return readSignal.bind(c);
}
function batch(fn) {
  return runUpdates(fn, false);
}
function untrack(fn) {
  if (!ExternalSourceConfig && Listener === null)
    return fn();
  const listener = Listener;
  Listener = null;
  try {
    if (ExternalSourceConfig)
      return ExternalSourceConfig.untrack(fn);
    return fn();
  } finally {
    Listener = listener;
  }
}
function on(deps, fn, options) {
  const isArray = Array.isArray(deps);
  let prevInput;
  let defer = options && options.defer;
  return (prevValue) => {
    let input;
    if (isArray) {
      input = Array(deps.length);
      for (let i = 0;i < deps.length; i++)
        input[i] = deps[i]();
    } else
      input = deps();
    if (defer) {
      defer = false;
      return prevValue;
    }
    const result = untrack(() => fn(input, prevInput, prevValue));
    prevInput = input;
    return result;
  };
}
function onMount(fn) {
  createEffect(() => untrack(fn));
}
function onCleanup(fn) {
  if (Owner === null)
    ;
  else if (Owner.cleanups === null)
    Owner.cleanups = [fn];
  else
    Owner.cleanups.push(fn);
  return fn;
}
function catchError(fn, handler) {
  ERROR || (ERROR = Symbol("error"));
  Owner = createComputation(undefined, undefined, true);
  Owner.context = {
    ...Owner.context,
    [ERROR]: [handler]
  };
  if (Transition && Transition.running)
    Transition.sources.add(Owner);
  try {
    return fn();
  } catch (err) {
    handleError(err);
  } finally {
    Owner = Owner.owner;
  }
}
function getListener() {
  return Listener;
}
function getOwner() {
  return Owner;
}
function runWithOwner(o, fn) {
  const prev = Owner;
  const prevListener = Listener;
  Owner = o;
  Listener = null;
  try {
    return runUpdates(fn, true);
  } catch (err) {
    handleError(err);
  } finally {
    Owner = prev;
    Listener = prevListener;
  }
}
function startTransition(fn) {
  if (Transition && Transition.running) {
    fn();
    return Transition.done;
  }
  const l = Listener;
  const o = Owner;
  return Promise.resolve().then(() => {
    Listener = l;
    Owner = o;
    let t;
    if (Scheduler || SuspenseContext) {
      t = Transition || (Transition = {
        sources: new Set,
        effects: [],
        promises: new Set,
        disposed: new Set,
        queue: new Set,
        running: true
      });
      t.done || (t.done = new Promise((res) => t.resolve = res));
      t.running = true;
    }
    runUpdates(fn, false);
    Listener = Owner = null;
    return t ? t.done : undefined;
  });
}
function createContext(defaultValue, options) {
  const id = Symbol("context");
  return {
    id,
    Provider: createProvider(id),
    defaultValue
  };
}
function useContext(context) {
  let value;
  return Owner && Owner.context && (value = Owner.context[context.id]) !== undefined ? value : context.defaultValue;
}
function children(fn) {
  const children2 = createMemo(fn);
  const memo = createMemo(() => resolveChildren(children2()));
  memo.toArray = () => {
    const c = memo();
    return Array.isArray(c) ? c : c != null ? [c] : [];
  };
  return memo;
}
function readSignal() {
  const runningTransition = Transition && Transition.running;
  if (this.sources && (runningTransition ? this.tState : this.state)) {
    if ((runningTransition ? this.tState : this.state) === STALE)
      updateComputation(this);
    else {
      const updates = Updates;
      Updates = null;
      runUpdates(() => lookUpstream(this), false);
      Updates = updates;
    }
  }
  if (Listener) {
    const observers = this.observers;
    if (!observers || observers[observers.length - 1] !== Listener) {
      const sSlot = observers ? observers.length : 0;
      if (!Listener.sources) {
        Listener.sources = [this];
        Listener.sourceSlots = [sSlot];
      } else {
        Listener.sources.push(this);
        Listener.sourceSlots.push(sSlot);
      }
      if (!observers) {
        this.observers = [Listener];
        this.observerSlots = [Listener.sources.length - 1];
      } else {
        observers.push(Listener);
        this.observerSlots.push(Listener.sources.length - 1);
      }
    }
  }
  if (runningTransition && Transition.sources.has(this))
    return this.tValue;
  return this.value;
}
function writeSignal(node, value, isComp) {
  let current = Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value;
  if (!node.comparator || !node.comparator(current, value)) {
    if (Transition) {
      const TransitionRunning = Transition.running;
      if (TransitionRunning || !isComp && Transition.sources.has(node)) {
        Transition.sources.add(node);
        node.tValue = value;
      }
      if (!TransitionRunning)
        node.value = value;
    } else
      node.value = value;
    if (node.observers && node.observers.length) {
      runUpdates(() => {
        for (let i = 0;i < node.observers.length; i += 1) {
          const o = node.observers[i];
          const TransitionRunning = Transition && Transition.running;
          if (TransitionRunning && Transition.disposed.has(o))
            continue;
          if (TransitionRunning ? !o.tState : !o.state) {
            if (o.pure)
              Updates.push(o);
            else
              Effects.push(o);
            if (o.observers)
              markDownstream(o);
          }
          if (!TransitionRunning)
            o.state = STALE;
          else
            o.tState = STALE;
        }
        if (Updates.length > 1e6) {
          Updates = [];
          if (IS_DEV)
            ;
          throw new Error;
        }
      }, false);
    }
  }
  return value;
}
function updateComputation(node) {
  if (!node.fn)
    return;
  cleanNode(node);
  const time = ExecCount;
  runComputation(node, Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value, time);
  if (Transition && !Transition.running && Transition.sources.has(node)) {
    queueMicrotask(() => {
      runUpdates(() => {
        Transition && (Transition.running = true);
        Listener = Owner = node;
        runComputation(node, node.tValue, time);
        Listener = Owner = null;
      }, false);
    });
  }
}
function runComputation(node, value, time) {
  let nextValue;
  const owner = Owner, listener = Listener;
  Listener = Owner = node;
  try {
    nextValue = node.fn(value);
  } catch (err) {
    if (node.pure) {
      if (Transition && Transition.running) {
        node.tState = STALE;
        node.tOwned && node.tOwned.forEach(cleanNode);
        node.tOwned = undefined;
      } else {
        node.state = STALE;
        node.owned && node.owned.forEach(cleanNode);
        node.owned = null;
      }
    }
    node.updatedAt = time + 1;
    return handleError(err);
  } finally {
    Listener = listener;
    Owner = owner;
  }
  if (!node.updatedAt || node.updatedAt <= time) {
    if (node.updatedAt != null && "observers" in node) {
      writeSignal(node, nextValue, true);
    } else if (Transition && Transition.running && node.pure) {
      if (!Transition.sources.has(node))
        node.value = nextValue;
      Transition.sources.add(node);
      node.tValue = nextValue;
    } else
      node.value = nextValue;
    node.updatedAt = time;
  }
}
function createComputation(fn, init, pure, state = STALE, options) {
  const c = {
    fn,
    state,
    updatedAt: null,
    owned: null,
    sources: null,
    sourceSlots: null,
    cleanups: null,
    value: init,
    owner: Owner,
    context: Owner ? Owner.context : null,
    pure
  };
  if (Transition && Transition.running) {
    c.state = 0;
    c.tState = state;
  }
  if (Owner === null)
    ;
  else if (Owner !== UNOWNED) {
    if (Transition && Transition.running && Owner.pure) {
      if (!Owner.tOwned)
        Owner.tOwned = [c];
      else
        Owner.tOwned.push(c);
    } else {
      if (!Owner.owned)
        Owner.owned = [c];
      else
        Owner.owned.push(c);
    }
  }
  if (ExternalSourceConfig && c.fn) {
    const sourceFn = c.fn;
    const [track, trigger] = createSignal(undefined, {
      equals: false
    });
    const ordinary = ExternalSourceConfig.factory(sourceFn, trigger);
    onCleanup(() => ordinary.dispose());
    let inTransition;
    const triggerInTransition = () => startTransition(trigger).then(() => {
      if (inTransition) {
        inTransition.dispose();
        inTransition = undefined;
      }
    });
    c.fn = (x) => {
      track();
      if (Transition && Transition.running) {
        if (!inTransition)
          inTransition = ExternalSourceConfig.factory(sourceFn, triggerInTransition);
        return inTransition.track(x);
      }
      return ordinary.track(x);
    };
  }
  return c;
}
function runTop(node) {
  const runningTransition = Transition && Transition.running;
  if ((runningTransition ? node.tState : node.state) === 0)
    return;
  if ((runningTransition ? node.tState : node.state) === PENDING)
    return lookUpstream(node);
  if (node.suspense && untrack(node.suspense.inFallback))
    return node.suspense.effects.push(node);
  const ancestors = [node];
  while ((node = node.owner) && (!node.updatedAt || node.updatedAt < ExecCount)) {
    if (runningTransition && Transition.disposed.has(node))
      return;
    if (runningTransition ? node.tState : node.state)
      ancestors.push(node);
  }
  for (let i = ancestors.length - 1;i >= 0; i--) {
    node = ancestors[i];
    if (runningTransition) {
      let top = node, prev = ancestors[i + 1];
      while ((top = top.owner) && top !== prev) {
        if (Transition.disposed.has(top))
          return;
      }
    }
    if ((runningTransition ? node.tState : node.state) === STALE) {
      updateComputation(node);
    } else if ((runningTransition ? node.tState : node.state) === PENDING) {
      const updates = Updates;
      Updates = null;
      runUpdates(() => lookUpstream(node, ancestors[0]), false);
      Updates = updates;
    }
  }
}
function runUpdates(fn, init) {
  if (Updates)
    return fn();
  let wait = false;
  if (!init)
    Updates = [];
  if (Effects)
    wait = true;
  else
    Effects = [];
  ExecCount++;
  try {
    const res = fn();
    completeUpdates(wait);
    return res;
  } catch (err) {
    if (!wait)
      Effects = null;
    Updates = null;
    handleError(err);
  }
}
function completeUpdates(wait) {
  if (Updates) {
    if (Scheduler && Transition && Transition.running)
      scheduleQueue(Updates);
    else
      runQueue(Updates);
    Updates = null;
  }
  if (wait)
    return;
  let res;
  if (Transition) {
    if (!Transition.promises.size && !Transition.queue.size) {
      const sources = Transition.sources;
      const disposed = Transition.disposed;
      Effects.push.apply(Effects, Transition.effects);
      res = Transition.resolve;
      for (const e2 of Effects) {
        "tState" in e2 && (e2.state = e2.tState);
        delete e2.tState;
      }
      Transition = null;
      runUpdates(() => {
        for (const d of disposed)
          cleanNode(d);
        for (const v of sources) {
          v.value = v.tValue;
          if (v.owned) {
            for (let i = 0, len = v.owned.length;i < len; i++)
              cleanNode(v.owned[i]);
          }
          if (v.tOwned)
            v.owned = v.tOwned;
          delete v.tValue;
          delete v.tOwned;
          v.tState = 0;
        }
        setTransPending(false);
      }, false);
    } else if (Transition.running) {
      Transition.running = false;
      Transition.effects.push.apply(Transition.effects, Effects);
      Effects = null;
      setTransPending(true);
      return;
    }
  }
  const e = Effects;
  Effects = null;
  if (e.length)
    runUpdates(() => runEffects(e), false);
  if (res)
    res();
}
function runQueue(queue) {
  for (let i = 0;i < queue.length; i++)
    runTop(queue[i]);
}
function scheduleQueue(queue) {
  for (let i = 0;i < queue.length; i++) {
    const item = queue[i];
    const tasks = Transition.queue;
    if (!tasks.has(item)) {
      tasks.add(item);
      Scheduler(() => {
        tasks.delete(item);
        runUpdates(() => {
          Transition.running = true;
          runTop(item);
        }, false);
        Transition && (Transition.running = false);
      });
    }
  }
}
function runUserEffects(queue) {
  let i, userLength = 0;
  for (i = 0;i < queue.length; i++) {
    const e = queue[i];
    if (!e.user)
      runTop(e);
    else
      queue[userLength++] = e;
  }
  if (sharedConfig.context) {
    if (sharedConfig.count) {
      sharedConfig.effects || (sharedConfig.effects = []);
      sharedConfig.effects.push(...queue.slice(0, userLength));
      return;
    }
    setHydrateContext();
  }
  if (sharedConfig.effects && (sharedConfig.done || !sharedConfig.count)) {
    queue = [...sharedConfig.effects, ...queue];
    userLength += sharedConfig.effects.length;
    delete sharedConfig.effects;
  }
  for (i = 0;i < userLength; i++)
    runTop(queue[i]);
}
function lookUpstream(node, ignore) {
  const runningTransition = Transition && Transition.running;
  if (runningTransition)
    node.tState = 0;
  else
    node.state = 0;
  for (let i = 0;i < node.sources.length; i += 1) {
    const source = node.sources[i];
    if (source.sources) {
      const state = runningTransition ? source.tState : source.state;
      if (state === STALE) {
        if (source !== ignore && (!source.updatedAt || source.updatedAt < ExecCount))
          runTop(source);
      } else if (state === PENDING)
        lookUpstream(source, ignore);
    }
  }
}
function markDownstream(node) {
  const runningTransition = Transition && Transition.running;
  for (let i = 0;i < node.observers.length; i += 1) {
    const o = node.observers[i];
    if (runningTransition ? !o.tState : !o.state) {
      if (runningTransition)
        o.tState = PENDING;
      else
        o.state = PENDING;
      if (o.pure)
        Updates.push(o);
      else
        Effects.push(o);
      o.observers && markDownstream(o);
    }
  }
}
function cleanNode(node) {
  let i;
  if (node.sources) {
    while (node.sources.length) {
      const source = node.sources.pop(), index = node.sourceSlots.pop(), obs = source.observers;
      if (obs && obs.length) {
        const n = obs.pop(), s = source.observerSlots.pop();
        if (index < obs.length) {
          n.sourceSlots[s] = index;
          obs[index] = n;
          source.observerSlots[index] = s;
        }
      }
    }
  }
  if (node.tOwned) {
    for (i = node.tOwned.length - 1;i >= 0; i--)
      cleanNode(node.tOwned[i]);
    delete node.tOwned;
  }
  if (Transition && Transition.running && node.pure) {
    reset(node, true);
  } else if (node.owned) {
    for (i = node.owned.length - 1;i >= 0; i--)
      cleanNode(node.owned[i]);
    node.owned = null;
  }
  if (node.cleanups) {
    for (i = node.cleanups.length - 1;i >= 0; i--)
      node.cleanups[i]();
    node.cleanups = null;
  }
  if (Transition && Transition.running)
    node.tState = 0;
  else
    node.state = 0;
}
function reset(node, top) {
  if (!top) {
    node.tState = 0;
    Transition.disposed.add(node);
  }
  if (node.owned) {
    for (let i = 0;i < node.owned.length; i++)
      reset(node.owned[i]);
  }
}
function castError(err) {
  if (err instanceof Error)
    return err;
  return new Error(typeof err === "string" ? err : "Unknown error", {
    cause: err
  });
}
function runErrors(err, fns, owner) {
  try {
    for (const f of fns)
      f(err);
  } catch (e) {
    handleError(e, owner && owner.owner || null);
  }
}
function handleError(err, owner = Owner) {
  const fns = ERROR && owner && owner.context && owner.context[ERROR];
  const error = castError(err);
  if (!fns)
    throw error;
  if (Effects)
    Effects.push({
      fn() {
        runErrors(error, fns, owner);
      },
      state: STALE
    });
  else
    runErrors(error, fns, owner);
}
function resolveChildren(children2) {
  if (typeof children2 === "function" && !children2.length)
    return resolveChildren(children2());
  if (Array.isArray(children2)) {
    const results = [];
    for (let i = 0;i < children2.length; i++) {
      const result = resolveChildren(children2[i]);
      if (Array.isArray(result)) {
        if (result.length < 32768)
          results.push.apply(results, result);
        else
          for (let j = 0;j < result.length; j++)
            results.push(result[j]);
      } else {
        results.push(result);
      }
    }
    return results;
  }
  return children2;
}
function createProvider(id, options) {
  return function provider(props) {
    let res;
    createRenderEffect(() => res = untrack(() => {
      Owner.context = {
        ...Owner.context,
        [id]: props.value
      };
      return children(() => props.children);
    }), undefined);
    return res;
  };
}
function dispose(d) {
  for (let i = 0;i < d.length; i++)
    d[i]();
}
function mapArray(list, mapFn, options = {}) {
  let items = [], mapped = [], disposers = [], len = 0, indexes = mapFn.length > 1 ? [] : null;
  onCleanup(() => dispose(disposers));
  return () => {
    let newItems = list() || [], newLen = newItems.length, i, j;
    newItems[$TRACK];
    return untrack(() => {
      let newIndices, newIndicesNext, temp, tempdisposers, tempIndexes, start, end, newEnd, item;
      if (newLen === 0) {
        if (len !== 0) {
          dispose(disposers);
          disposers = [];
          items = [];
          mapped = [];
          len = 0;
          indexes && (indexes = []);
        }
        if (options.fallback) {
          items = [FALLBACK];
          mapped[0] = createRoot((disposer) => {
            disposers[0] = disposer;
            return options.fallback();
          });
          len = 1;
        }
      } else if (len === 0) {
        mapped = new Array(newLen);
        for (j = 0;j < newLen; j++) {
          items[j] = newItems[j];
          mapped[j] = createRoot(mapper);
        }
        len = newLen;
      } else {
        temp = new Array(newLen);
        tempdisposers = new Array(newLen);
        indexes && (tempIndexes = new Array(newLen));
        for (start = 0, end = Math.min(len, newLen);start < end && items[start] === newItems[start]; start++)
          ;
        for (end = len - 1, newEnd = newLen - 1;end >= start && newEnd >= start && items[end] === newItems[newEnd]; end--, newEnd--) {
          temp[newEnd] = mapped[end];
          tempdisposers[newEnd] = disposers[end];
          indexes && (tempIndexes[newEnd] = indexes[end]);
        }
        newIndices = new Map;
        newIndicesNext = new Array(newEnd + 1);
        for (j = newEnd;j >= start; j--) {
          item = newItems[j];
          i = newIndices.get(item);
          newIndicesNext[j] = i === undefined ? -1 : i;
          newIndices.set(item, j);
        }
        for (i = start;i <= end; i++) {
          item = items[i];
          j = newIndices.get(item);
          if (j !== undefined && j !== -1) {
            temp[j] = mapped[i];
            tempdisposers[j] = disposers[i];
            indexes && (tempIndexes[j] = indexes[i]);
            j = newIndicesNext[j];
            newIndices.set(item, j);
          } else
            disposers[i]();
        }
        for (j = start;j < newLen; j++) {
          if (j in temp) {
            mapped[j] = temp[j];
            disposers[j] = tempdisposers[j];
            if (indexes) {
              indexes[j] = tempIndexes[j];
              indexes[j](j);
            }
          } else
            mapped[j] = createRoot(mapper);
        }
        mapped = mapped.slice(0, len = newLen);
        items = newItems.slice(0);
      }
      return mapped;
    });
    function mapper(disposer) {
      disposers[j] = disposer;
      if (indexes) {
        const [s, set] = createSignal(j);
        indexes[j] = set;
        return mapFn(newItems[j], s);
      }
      return mapFn(newItems[j]);
    }
  };
}
function createComponent(Comp, props) {
  if (hydrationEnabled) {
    if (sharedConfig.context) {
      const c = sharedConfig.context;
      setHydrateContext(nextHydrateContext());
      const r = untrack(() => Comp(props || {}));
      setHydrateContext(c);
      return r;
    }
  }
  return untrack(() => Comp(props || {}));
}
function trueFn() {
  return true;
}
function resolveSource(s) {
  return !(s = typeof s === "function" ? s() : s) ? {} : s;
}
function resolveSources() {
  for (let i = 0, length = this.length;i < length; ++i) {
    const v = this[i]();
    if (v !== undefined)
      return v;
  }
}
function mergeProps(...sources) {
  let proxy = false;
  for (let i = 0;i < sources.length; i++) {
    const s = sources[i];
    proxy = proxy || !!s && $PROXY in s;
    sources[i] = typeof s === "function" ? (proxy = true, createMemo(s)) : s;
  }
  if (SUPPORTS_PROXY && proxy) {
    return new Proxy({
      get(property) {
        for (let i = sources.length - 1;i >= 0; i--) {
          const v = resolveSource(sources[i])[property];
          if (v !== undefined)
            return v;
        }
      },
      has(property) {
        for (let i = sources.length - 1;i >= 0; i--) {
          if (property in resolveSource(sources[i]))
            return true;
        }
        return false;
      },
      keys() {
        const keys = [];
        for (let i = 0;i < sources.length; i++)
          keys.push(...Object.keys(resolveSource(sources[i])));
        return [...new Set(keys)];
      }
    }, propTraps);
  }
  const sourcesMap = {};
  const defined = Object.create(null);
  for (let i = sources.length - 1;i >= 0; i--) {
    const source = sources[i];
    if (!source)
      continue;
    const sourceKeys = Object.getOwnPropertyNames(source);
    for (let i2 = sourceKeys.length - 1;i2 >= 0; i2--) {
      const key = sourceKeys[i2];
      if (key === "__proto__" || key === "constructor")
        continue;
      const desc = Object.getOwnPropertyDescriptor(source, key);
      if (!defined[key]) {
        defined[key] = desc.get ? {
          enumerable: true,
          configurable: true,
          get: resolveSources.bind(sourcesMap[key] = [desc.get.bind(source)])
        } : desc.value !== undefined ? desc : undefined;
      } else {
        const sources2 = sourcesMap[key];
        if (sources2) {
          if (desc.get)
            sources2.push(desc.get.bind(source));
          else if (desc.value !== undefined)
            sources2.push(() => desc.value);
        }
      }
    }
  }
  const target = {};
  const definedKeys = Object.keys(defined);
  for (let i = definedKeys.length - 1;i >= 0; i--) {
    const key = definedKeys[i], desc = defined[key];
    if (desc && desc.get)
      Object.defineProperty(target, key, desc);
    else
      target[key] = desc ? desc.value : undefined;
  }
  return target;
}
function splitProps(props, ...keys) {
  const len = keys.length;
  if (SUPPORTS_PROXY && $PROXY in props) {
    const blocked = len > 1 ? keys.flat() : keys[0];
    const res = keys.map((k) => {
      return new Proxy({
        get(property) {
          return k.includes(property) ? props[property] : undefined;
        },
        has(property) {
          return k.includes(property) && property in props;
        },
        keys() {
          return k.filter((property) => (property in props));
        }
      }, propTraps);
    });
    res.push(new Proxy({
      get(property) {
        return blocked.includes(property) ? undefined : props[property];
      },
      has(property) {
        return blocked.includes(property) ? false : (property in props);
      },
      keys() {
        return Object.keys(props).filter((k) => !blocked.includes(k));
      }
    }, propTraps));
    return res;
  }
  const objects = [];
  for (let i = 0;i <= len; i++) {
    objects[i] = {};
  }
  for (const propName of Object.getOwnPropertyNames(props)) {
    let keyIndex = len;
    for (let i = 0;i < keys.length; i++) {
      if (keys[i].includes(propName)) {
        keyIndex = i;
        break;
      }
    }
    const desc = Object.getOwnPropertyDescriptor(props, propName);
    const isDefaultDesc = !desc.get && !desc.set && desc.enumerable && desc.writable && desc.configurable;
    isDefaultDesc ? objects[keyIndex][propName] = desc.value : Object.defineProperty(objects[keyIndex], propName, desc);
  }
  return objects;
}
function For(props) {
  const fallback = "fallback" in props && {
    fallback: () => props.fallback
  };
  return createMemo(mapArray(() => props.each, props.children, fallback || undefined));
}
function Show(props) {
  const keyed = props.keyed;
  const conditionValue = createMemo(() => props.when, undefined, undefined);
  const condition = keyed ? conditionValue : createMemo(conditionValue, undefined, {
    equals: (a, b) => !a === !b
  });
  return createMemo(() => {
    const c = condition();
    if (c) {
      const child = props.children;
      const fn = typeof child === "function" && child.length > 0;
      return fn ? untrack(() => child(keyed ? c : () => {
        if (!untrack(condition))
          throw narrowedError("Show");
        return conditionValue();
      })) : child;
    }
    return props.fallback;
  }, undefined, undefined);
}
function Switch(props) {
  const chs = children(() => props.children);
  const switchFunc = createMemo(() => {
    const ch = chs();
    const mps = Array.isArray(ch) ? ch : [ch];
    let func = () => {
      return;
    };
    for (let i = 0;i < mps.length; i++) {
      const index = i;
      const mp = mps[i];
      const prevFunc = func;
      const conditionValue = createMemo(() => prevFunc() ? undefined : mp.when, undefined, undefined);
      const condition = mp.keyed ? conditionValue : createMemo(conditionValue, undefined, {
        equals: (a, b) => !a === !b
      });
      func = () => prevFunc() || (condition() ? [index, conditionValue, mp] : undefined);
    }
    return func;
  });
  return createMemo(() => {
    const sel = switchFunc()();
    if (!sel)
      return props.fallback;
    const [index, conditionValue, mp] = sel;
    const child = mp.children;
    const fn = typeof child === "function" && child.length > 0;
    return fn ? untrack(() => child(mp.keyed ? conditionValue() : () => {
      if (untrack(switchFunc)()?.[0] !== index)
        throw narrowedError("Match");
      return conditionValue();
    })) : child;
  }, undefined, undefined);
}
function Match(props) {
  return props;
}
function ErrorBoundary(props) {
  let err;
  if (sharedConfig.context && sharedConfig.load)
    err = sharedConfig.load(sharedConfig.getContextId());
  const [errored, setErrored] = createSignal(err, undefined);
  Errors || (Errors = new Set);
  Errors.add(setErrored);
  onCleanup(() => Errors.delete(setErrored));
  return createMemo(() => {
    let e;
    if (e = errored()) {
      const f = props.fallback;
      return typeof f === "function" && f.length ? untrack(() => f(e, () => setErrored())) : f;
    }
    return catchError(() => props.children, setErrored);
  }, undefined, undefined);
}
var sharedConfig, IS_DEV = false, equalFn = (a, b) => a === b, $PROXY, SUPPORTS_PROXY, $TRACK, $DEVCOMP, signalOptions, ERROR = null, runEffects, STALE = 1, PENDING = 2, UNOWNED, Owner = null, Transition = null, Scheduler = null, ExternalSourceConfig = null, Listener = null, Updates = null, Effects = null, ExecCount = 0, transPending, setTransPending, SuspenseContext, FALLBACK, hydrationEnabled = false, propTraps, narrowedError = (name) => `Stale read from <${name}>.`, Errors;
var init_server = __esm(() => {
  sharedConfig = {
    context: undefined,
    registry: undefined,
    effects: undefined,
    done: false,
    getContextId() {
      return getContextId(this.context.count);
    },
    getNextContextId() {
      return getContextId(this.context.count++);
    }
  };
  $PROXY = Symbol("solid-proxy");
  SUPPORTS_PROXY = typeof Proxy === "function";
  $TRACK = Symbol("solid-track");
  $DEVCOMP = Symbol("solid-dev-component");
  signalOptions = {
    equals: equalFn
  };
  runEffects = runQueue;
  UNOWNED = {
    owned: null,
    cleanups: null,
    context: null,
    owner: null
  };
  [transPending, setTransPending] = /* @__PURE__ */ createSignal(false);
  FALLBACK = Symbol("fallback");
  propTraps = {
    get(_, property, receiver) {
      if (property === $PROXY)
        return receiver;
      return _.get(property);
    },
    has(_, property) {
      if (property === $PROXY)
        return true;
      return _.has(property);
    },
    set: trueFn,
    deleteProperty: trueFn,
    getOwnPropertyDescriptor(_, property) {
      return {
        configurable: true,
        enumerable: true,
        get() {
          return _.get(property);
        },
        set: trueFn,
        deleteProperty: trueFn
      };
    },
    ownKeys(_) {
      return _.keys();
    }
  };
});

// ../../node_modules/.bun/entities@7.0.1/node_modules/entities/dist/esm/decode-codepoint.js
function replaceCodePoint(codePoint) {
  var _a2;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== undefined ? _a2 : codePoint;
}
var _a, decodeMap, fromCodePoint;
var init_decode_codepoint = __esm(() => {
  decodeMap = new Map([
    [0, 65533],
    [128, 8364],
    [130, 8218],
    [131, 402],
    [132, 8222],
    [133, 8230],
    [134, 8224],
    [135, 8225],
    [136, 710],
    [137, 8240],
    [138, 352],
    [139, 8249],
    [140, 338],
    [142, 381],
    [145, 8216],
    [146, 8217],
    [147, 8220],
    [148, 8221],
    [149, 8226],
    [150, 8211],
    [151, 8212],
    [152, 732],
    [153, 8482],
    [154, 353],
    [155, 8250],
    [156, 339],
    [158, 382],
    [159, 376]
  ]);
  fromCodePoint = (_a = String.fromCodePoint) !== null && _a !== undefined ? _a : (codePoint) => {
    let output = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output += String.fromCharCode(codePoint);
    return output;
  };
});

// ../../node_modules/.bun/entities@7.0.1/node_modules/entities/dist/esm/internal/decode-shared.js
function decodeBase64(input) {
  const binary = typeof atob === "function" ? atob(input) : typeof Buffer.from === "function" ? Buffer.from(input, "base64").toString("binary") : new Buffer(input, "base64").toString("binary");
  const evenLength = binary.length & ~1;
  const out = new Uint16Array(evenLength / 2);
  for (let index = 0, outIndex = 0;index < evenLength; index += 2) {
    const lo = binary.charCodeAt(index);
    const hi = binary.charCodeAt(index + 1);
    out[outIndex++] = lo | hi << 8;
  }
  return out;
}

// ../../node_modules/.bun/entities@7.0.1/node_modules/entities/dist/esm/generated/decode-data-html.js
var htmlDecodeTree;
var init_decode_data_html = __esm(() => {
  htmlDecodeTree = /* @__PURE__ */ decodeBase64("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");
});

// ../../node_modules/.bun/entities@7.0.1/node_modules/entities/dist/esm/internal/bin-trie-flags.js
var BinTrieFlags;
var init_bin_trie_flags = __esm(() => {
  (function(BinTrieFlags2) {
    BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
    BinTrieFlags2[BinTrieFlags2["FLAG13"] = 8192] = "FLAG13";
    BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH";
    BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
  })(BinTrieFlags || (BinTrieFlags = {}));
});

// ../../node_modules/.bun/entities@7.0.1/node_modules/entities/dist/esm/decode.js
function isNumber(code) {
  return code >= CharCodes.ZERO && code <= CharCodes.NINE;
}
function isHexadecimalCharacter(code) {
  return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F;
}
function isAsciiAlphaNumeric(code) {
  return code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z || code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z || isNumber(code);
}
function isEntityInAttributeInvalidEnd(code) {
  return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
}

class EntityDecoder {
  constructor(decodeTree, emitCodePoint, errors) {
    this.decodeTree = decodeTree;
    this.emitCodePoint = emitCodePoint;
    this.errors = errors;
    this.state = EntityDecoderState.EntityStart;
    this.consumed = 1;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.decodeMode = DecodingMode.Strict;
    this.runConsumed = 0;
  }
  startEntity(decodeMode) {
    this.decodeMode = decodeMode;
    this.state = EntityDecoderState.EntityStart;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.consumed = 1;
    this.runConsumed = 0;
  }
  write(input, offset) {
    switch (this.state) {
      case EntityDecoderState.EntityStart: {
        if (input.charCodeAt(offset) === CharCodes.NUM) {
          this.state = EntityDecoderState.NumericStart;
          this.consumed += 1;
          return this.stateNumericStart(input, offset + 1);
        }
        this.state = EntityDecoderState.NamedEntity;
        return this.stateNamedEntity(input, offset);
      }
      case EntityDecoderState.NumericStart: {
        return this.stateNumericStart(input, offset);
      }
      case EntityDecoderState.NumericDecimal: {
        return this.stateNumericDecimal(input, offset);
      }
      case EntityDecoderState.NumericHex: {
        return this.stateNumericHex(input, offset);
      }
      case EntityDecoderState.NamedEntity: {
        return this.stateNamedEntity(input, offset);
      }
    }
  }
  stateNumericStart(input, offset) {
    if (offset >= input.length) {
      return -1;
    }
    if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
      this.state = EntityDecoderState.NumericHex;
      this.consumed += 1;
      return this.stateNumericHex(input, offset + 1);
    }
    this.state = EntityDecoderState.NumericDecimal;
    return this.stateNumericDecimal(input, offset);
  }
  stateNumericHex(input, offset) {
    while (offset < input.length) {
      const char = input.charCodeAt(offset);
      if (isNumber(char) || isHexadecimalCharacter(char)) {
        const digit = char <= CharCodes.NINE ? char - CharCodes.ZERO : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
        this.result = this.result * 16 + digit;
        this.consumed++;
        offset++;
      } else {
        return this.emitNumericEntity(char, 3);
      }
    }
    return -1;
  }
  stateNumericDecimal(input, offset) {
    while (offset < input.length) {
      const char = input.charCodeAt(offset);
      if (isNumber(char)) {
        this.result = this.result * 10 + (char - CharCodes.ZERO);
        this.consumed++;
        offset++;
      } else {
        return this.emitNumericEntity(char, 2);
      }
    }
    return -1;
  }
  emitNumericEntity(lastCp, expectedLength) {
    var _a2;
    if (this.consumed <= expectedLength) {
      (_a2 = this.errors) === null || _a2 === undefined || _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
      return 0;
    }
    if (lastCp === CharCodes.SEMI) {
      this.consumed += 1;
    } else if (this.decodeMode === DecodingMode.Strict) {
      return 0;
    }
    this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
    if (this.errors) {
      if (lastCp !== CharCodes.SEMI) {
        this.errors.missingSemicolonAfterCharacterReference();
      }
      this.errors.validateNumericCharacterReference(this.result);
    }
    return this.consumed;
  }
  stateNamedEntity(input, offset) {
    const { decodeTree } = this;
    let current = decodeTree[this.treeIndex];
    let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
    while (offset < input.length) {
      if (valueLength === 0 && (current & BinTrieFlags.FLAG13) !== 0) {
        const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
        if (this.runConsumed === 0) {
          const firstChar = current & BinTrieFlags.JUMP_TABLE;
          if (input.charCodeAt(offset) !== firstChar) {
            return this.result === 0 ? 0 : this.emitNotTerminatedNamedEntity();
          }
          offset++;
          this.excess++;
          this.runConsumed++;
        }
        while (this.runConsumed < runLength) {
          if (offset >= input.length) {
            return -1;
          }
          const charIndexInPacked = this.runConsumed - 1;
          const packedWord = decodeTree[this.treeIndex + 1 + (charIndexInPacked >> 1)];
          const expectedChar = charIndexInPacked % 2 === 0 ? packedWord & 255 : packedWord >> 8 & 255;
          if (input.charCodeAt(offset) !== expectedChar) {
            this.runConsumed = 0;
            return this.result === 0 ? 0 : this.emitNotTerminatedNamedEntity();
          }
          offset++;
          this.excess++;
          this.runConsumed++;
        }
        this.runConsumed = 0;
        this.treeIndex += 1 + (runLength >> 1);
        current = decodeTree[this.treeIndex];
        valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
      }
      if (offset >= input.length)
        break;
      const char = input.charCodeAt(offset);
      if (char === CharCodes.SEMI && valueLength !== 0 && (current & BinTrieFlags.FLAG13) !== 0) {
        return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
      }
      this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
      if (this.treeIndex < 0) {
        return this.result === 0 || this.decodeMode === DecodingMode.Attribute && (valueLength === 0 || isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
      }
      current = decodeTree[this.treeIndex];
      valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
      if (valueLength !== 0) {
        if (char === CharCodes.SEMI) {
          return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
        }
        if (this.decodeMode !== DecodingMode.Strict && (current & BinTrieFlags.FLAG13) === 0) {
          this.result = this.treeIndex;
          this.consumed += this.excess;
          this.excess = 0;
        }
      }
      offset++;
      this.excess++;
    }
    return -1;
  }
  emitNotTerminatedNamedEntity() {
    var _a2;
    const { result, decodeTree } = this;
    const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
    this.emitNamedEntityData(result, valueLength, this.consumed);
    (_a2 = this.errors) === null || _a2 === undefined || _a2.missingSemicolonAfterCharacterReference();
    return this.consumed;
  }
  emitNamedEntityData(result, valueLength, consumed) {
    const { decodeTree } = this;
    this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~(BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13) : decodeTree[result + 1], consumed);
    if (valueLength === 3) {
      this.emitCodePoint(decodeTree[result + 2], consumed);
    }
    return consumed;
  }
  end() {
    var _a2;
    switch (this.state) {
      case EntityDecoderState.NamedEntity: {
        return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
      }
      case EntityDecoderState.NumericDecimal: {
        return this.emitNumericEntity(0, 2);
      }
      case EntityDecoderState.NumericHex: {
        return this.emitNumericEntity(0, 3);
      }
      case EntityDecoderState.NumericStart: {
        (_a2 = this.errors) === null || _a2 === undefined || _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
        return 0;
      }
      case EntityDecoderState.EntityStart: {
        return 0;
      }
    }
  }
}
function getDecoder(decodeTree) {
  let returnValue = "";
  const decoder = new EntityDecoder(decodeTree, (data) => returnValue += fromCodePoint(data));
  return function decodeWithTrie(input, decodeMode) {
    let lastIndex = 0;
    let offset = 0;
    while ((offset = input.indexOf("&", offset)) >= 0) {
      returnValue += input.slice(lastIndex, offset);
      decoder.startEntity(decodeMode);
      const length = decoder.write(input, offset + 1);
      if (length < 0) {
        lastIndex = offset + decoder.end();
        break;
      }
      lastIndex = offset + length;
      offset = length === 0 ? lastIndex + 1 : lastIndex;
    }
    const result = returnValue + input.slice(lastIndex);
    returnValue = "";
    return result;
  };
}
function determineBranch(decodeTree, current, nodeIndex, char) {
  const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  if (branchCount === 0) {
    return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
  }
  if (jumpOffset) {
    const value = char - jumpOffset;
    return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIndex + value] - 1;
  }
  const packedKeySlots = branchCount + 1 >> 1;
  let lo = 0;
  let hi = branchCount - 1;
  while (lo <= hi) {
    const mid = lo + hi >>> 1;
    const slot = mid >> 1;
    const packed = decodeTree[nodeIndex + slot];
    const midKey = packed >> (mid & 1) * 8 & 255;
    if (midKey < char) {
      lo = mid + 1;
    } else if (midKey > char) {
      hi = mid - 1;
    } else {
      return decodeTree[nodeIndex + packedKeySlots + mid];
    }
  }
  return -1;
}
function decodeHTMLStrict(htmlString) {
  return htmlDecoder(htmlString, DecodingMode.Strict);
}
var CharCodes, TO_LOWER_BIT = 32, EntityDecoderState, DecodingMode, htmlDecoder;
var init_decode = __esm(() => {
  init_decode_codepoint();
  init_decode_data_html();
  init_bin_trie_flags();
  (function(CharCodes2) {
    CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
    CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
    CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
    CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
    CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
    CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
    CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
    CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
    CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
    CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
    CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
    CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
  })(CharCodes || (CharCodes = {}));
  (function(EntityDecoderState2) {
    EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
    EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
    EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
    EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
    EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
  })(EntityDecoderState || (EntityDecoderState = {}));
  (function(DecodingMode2) {
    DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
    DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
    DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
  })(DecodingMode || (DecodingMode = {}));
  htmlDecoder = /* @__PURE__ */ getDecoder(htmlDecodeTree);
});

// ../../node_modules/.bun/entities@7.0.1/node_modules/entities/dist/esm/index.js
var EntityLevel, EncodingMode;
var init_esm = __esm(() => {
  init_decode();
  (function(EntityLevel2) {
    EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
    EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
  })(EntityLevel || (EntityLevel = {}));
  (function(EncodingMode2) {
    EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
    EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
    EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
    EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
    EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
  })(EncodingMode || (EncodingMode = {}));
});

// ../../node_modules/.bun/@opentui+solid@0.5.10+4c2f59a89fdb89d2/node_modules/@opentui/solid/index.bun.js
var exports_index_bun = {};
__export(exports_index_bun, {
  writeSolidToScrollback: () => writeSolidToScrollback,
  useTimeline: () => useTimeline,
  useTerminalDimensions: () => useTerminalDimensions,
  useSelectionHandler: () => useSelectionHandler,
  useRenderer: () => useRenderer,
  usePaste: () => usePaste,
  useKeyboard: () => useKeyboard,
  useKeyHandler: () => useKeyHandler,
  use: () => use,
  textNodeKeys: () => textNodeKeys,
  testRender: () => testRender,
  spread: () => spread,
  setProp: () => setProp,
  render: () => render,
  onResize: () => onResize,
  onFocus: () => onFocus,
  onBlur: () => onBlur,
  mergeProps: () => mergeProps3,
  memo: () => memo2,
  insertNode: () => insertNode,
  insert: () => insert,
  getComponentCatalogue: () => getComponentCatalogue,
  extend: () => extend,
  effect: () => effect,
  createTextNode: () => createTextNode,
  createSolidSlotRegistry: () => createSolidSlotRegistry,
  createSlotNode: () => createSlotNode,
  createSlot: () => createSlot,
  createScrollbackWriter: () => createScrollbackWriter,
  createElement: () => createElement,
  createDynamic: () => createDynamic,
  createComponent: () => createComponent2,
  componentCatalogue: () => componentCatalogue,
  baseComponents: () => baseComponents,
  _render: () => _render,
  UnderlineSpanRenderable: () => UnderlineSpanRenderable,
  TimeToFirstDraw: () => TimeToFirstDraw,
  TextSlotRenderable: () => TextSlotRenderable,
  SlotRenderable: () => SlotRenderable,
  Slot: () => Slot,
  RendererContext: () => RendererContext,
  Portal: () => Portal,
  LinkRenderable: () => LinkRenderable,
  LineBreakRenderable: () => LineBreakRenderable,
  LayoutSlotRenderable: () => LayoutSlotRenderable,
  ItalicSpanRenderable: () => ItalicSpanRenderable,
  Dynamic: () => Dynamic,
  BoldSpanRenderable: () => BoldSpanRenderable
});
import { CliRenderer, createCliRenderer, engine as engine2 } from "@opentui/core";
import { createTestRenderer } from "@opentui/core/testing";
import {
  ASCIIFontRenderable,
  BoxRenderable,
  CodeRenderable,
  DiffRenderable,
  ImageRenderable,
  InputRenderable,
  LineNumberRenderable,
  MarkdownRenderable,
  ScrollBoxRenderable,
  SelectRenderable,
  TabSelectRenderable,
  TextareaRenderable,
  TextAttributes,
  TextNodeRenderable,
  TextRenderable
} from "@opentui/core";
import {
  engine,
  Timeline
} from "@opentui/core";
import {
  BaseRenderable,
  createTextAttributes,
  ImageRenderable as ImageRenderable2,
  InputRenderable as InputRenderable2,
  InputRenderableEvents,
  isTextNodeRenderable,
  isEditBufferRenderable,
  parseColor,
  Renderable,
  RootTextNodeRenderable,
  ScrollBoxRenderable as ScrollBoxRenderable2,
  SelectRenderable as SelectRenderable2,
  SelectRenderableEvents,
  TabSelectRenderable as TabSelectRenderable2,
  TabSelectRenderableEvents,
  TextNodeRenderable as TextNodeRenderable2,
  TextRenderable as TextRenderable2
} from "@opentui/core";
import { BaseRenderable as BaseRenderable2, isTextNodeRenderable as isTextNodeRenderable2, TextNodeRenderable as TextNodeRenderable3, TextRenderable as TextRenderable3, Yoga } from "@opentui/core";
import {
  BoxRenderable as BoxRenderable2,
  RootRenderable
} from "@opentui/core";
import { TimeToFirstDrawRenderable } from "@opentui/core";
import { createSlotRegistry } from "@opentui/core";
function extend(objects) {
  Object.assign(componentCatalogue, objects);
}
function getComponentCatalogue() {
  return componentCatalogue;
}
function createRenderer({
  createElement,
  createTextNode,
  createDynamicTextNode,
  createSlotNode,
  isTextNode,
  replaceText,
  insertNode,
  removeNode,
  setProperty,
  getParentNode,
  getFirstChild,
  getNextSibling
}) {
  function insert(parent, accessor, marker, initial) {
    if (marker !== undefined && !initial)
      initial = [];
    if (typeof accessor !== "function")
      return insertExpression(parent, accessor, initial, marker);
    createRenderEffect((current) => insertExpression(parent, accessor(), current, marker), initial);
  }
  function insertExpression(parent, value, current, marker, unwrapArray) {
    while (typeof current === "function")
      current = current();
    if (value === current)
      return current;
    const t = typeof value, multi = marker !== undefined;
    if (t === "string" || t === "number") {
      if (t === "number")
        value = value.toString();
      if (multi) {
        let node = current[0];
        if (node && isTextNode(node)) {
          replaceText(node, value);
        } else
          node = createDynamicTextNode(value);
        current = cleanChildren(parent, current, marker, node);
      } else {
        if (current !== "" && typeof current === "string") {
          replaceText(getFirstChild(parent), current = value);
        } else {
          cleanChildren(parent, current, marker, createDynamicTextNode(value));
          current = value;
        }
      }
    } else if (value == null || t === "boolean") {
      current = cleanChildren(parent, current, marker);
    } else if (t === "function") {
      createRenderEffect(() => {
        let v = value();
        while (typeof v === "function")
          v = v();
        current = insertExpression(parent, v, current, marker);
      });
      return () => current;
    } else if (Array.isArray(value)) {
      const array = [];
      if (normalizeIncomingArray(array, value, unwrapArray)) {
        createRenderEffect(() => current = insertExpression(parent, array, current, marker, true));
        return () => current;
      }
      if (array.length === 0) {
        const replacement = cleanChildren(parent, current, marker);
        if (multi)
          return current = replacement;
      } else {
        if (Array.isArray(current)) {
          if (current.length === 0) {
            appendNodes(parent, array, marker);
          } else
            reconcileArrays(parent, current, array);
        } else if (current == null || current === "") {
          appendNodes(parent, array);
        } else {
          reconcileArrays(parent, multi && current || [getFirstChild(parent)], array);
        }
      }
      current = array;
    } else {
      if (Array.isArray(current)) {
        if (multi)
          return current = cleanChildren(parent, current, marker, value);
        cleanChildren(parent, current, null, value);
      } else if (current == null || current === "" || !getFirstChild(parent)) {
        insertNode(parent, value);
      } else
        replaceNode(parent, value, getFirstChild(parent));
      current = value;
    }
    return current;
  }
  function normalizeIncomingArray(normalized, array, unwrap) {
    let dynamic = false;
    for (let i = 0, len = array.length;i < len; i++) {
      let item = array[i], t;
      if (item == null || item === true || item === false)
        ;
      else if (Array.isArray(item)) {
        dynamic = normalizeIncomingArray(normalized, item) || dynamic;
      } else if ((t = typeof item) === "string" || t === "number") {
        normalized.push(createDynamicTextNode(item));
      } else if (t === "function") {
        if (unwrap) {
          while (typeof item === "function")
            item = item();
          dynamic = normalizeIncomingArray(normalized, Array.isArray(item) ? item : [item]) || dynamic;
        } else {
          normalized.push(item);
          dynamic = true;
        }
      } else
        normalized.push(item);
    }
    return dynamic;
  }
  function reconcileArrays(parentNode, a, b) {
    let bLength = b.length, aEnd = a.length, bEnd = bLength, aStart = 0, bStart = 0, after = getNextSibling(a[aEnd - 1]), map = null;
    while (aStart < aEnd || bStart < bEnd) {
      if (a[aStart] === b[bStart]) {
        aStart++;
        bStart++;
        continue;
      }
      while (a[aEnd - 1] === b[bEnd - 1]) {
        aEnd--;
        bEnd--;
      }
      if (aEnd === aStart) {
        const node = bEnd < bLength ? bStart ? getNextSibling(b[bStart - 1]) : b[bEnd - bStart] : after;
        while (bStart < bEnd)
          insertNode(parentNode, b[bStart++], node);
      } else if (bEnd === bStart) {
        while (aStart < aEnd) {
          if (!map || !map.has(a[aStart]))
            removeNode(parentNode, a[aStart]);
          aStart++;
        }
      } else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
        const node = getNextSibling(a[--aEnd]);
        insertNode(parentNode, b[bStart++], getNextSibling(a[aStart++]));
        insertNode(parentNode, b[--bEnd], node);
        a[aEnd] = b[bEnd];
      } else {
        if (!map) {
          map = new Map;
          let i = bStart;
          while (i < bEnd)
            map.set(b[i], i++);
        }
        const index = map.get(a[aStart]);
        if (index != null) {
          if (bStart < index && index < bEnd) {
            let i = aStart, sequence = 1, t;
            while (++i < aEnd && i < bEnd) {
              if ((t = map.get(a[i])) == null || t !== index + sequence)
                break;
              sequence++;
            }
            if (sequence > index - bStart) {
              const node = a[aStart];
              while (bStart < index)
                insertNode(parentNode, b[bStart++], node);
            } else
              replaceNode(parentNode, b[bStart++], a[aStart++]);
          } else
            aStart++;
        } else
          removeNode(parentNode, a[aStart++]);
      }
    }
  }
  function cleanChildren(parent, current, marker, replacement) {
    if (marker === undefined) {
      let removed;
      while (removed = getFirstChild(parent))
        removeNode(parent, removed);
      replacement && insertNode(parent, replacement);
      return replacement ?? "";
    }
    const node = replacement || createSlotNode();
    if (current.length) {
      let inserted = false;
      for (let i = current.length - 1;i >= 0; i--) {
        const el = current[i];
        if (node !== el) {
          const isParent = getParentNode(el) === parent;
          if (!inserted && !i)
            isParent ? replaceNode(parent, node, el) : insertNode(parent, node, marker);
          else
            isParent && removeNode(parent, el);
        } else
          inserted = true;
      }
    } else
      insertNode(parent, node, marker);
    return [node];
  }
  function appendNodes(parent, array, marker) {
    for (let i = 0, len = array.length;i < len; i++)
      insertNode(parent, array[i], marker);
  }
  function replaceNode(parent, newNode, oldNode) {
    insertNode(parent, newNode, oldNode);
    removeNode(parent, oldNode);
  }
  function spreadExpression(node, props, prevProps = {}, skipChildren) {
    props || (props = {});
    if (!skipChildren) {
      createRenderEffect(() => prevProps.children = insertExpression(node, props.children, prevProps.children));
    }
    createRenderEffect(() => props.ref && props.ref(node));
    createRenderEffect(() => {
      for (const prop in props) {
        if (prop === "children" || prop === "ref")
          continue;
        const value = props[prop];
        if (value === prevProps[prop])
          continue;
        setProperty(node, prop, value, prevProps[prop]);
        prevProps[prop] = value;
      }
    });
    return prevProps;
  }
  return {
    render(code, element) {
      let disposer;
      createRoot((dispose2) => {
        disposer = dispose2;
        insert(element, code());
      });
      return disposer;
    },
    insert,
    spread(node, accessor, skipChildren) {
      if (typeof accessor === "function") {
        createRenderEffect((current) => spreadExpression(node, accessor(), current, skipChildren));
      } else
        spreadExpression(node, accessor, undefined, skipChildren);
    },
    createElement,
    createTextNode,
    insertNode,
    setProp(node, name, value, prev) {
      setProperty(node, name, value, prev);
      return value;
    },
    mergeProps,
    effect: createRenderEffect,
    memo,
    createComponent,
    use(fn, element, arg) {
      return untrack(() => fn(element, arg));
    }
  };
}
function createRenderer2(options) {
  const renderer = createRenderer(options);
  renderer.mergeProps = mergeProps;
  return renderer;
}
function getNextId(elementType) {
  if (!idCounter.has(elementType)) {
    idCounter.set(elementType, 0);
  }
  const value = idCounter.get(elementType) + 1;
  idCounter.set(elementType, value);
  return `${elementType}-${value}`;
}
function _insertNode(parent, node, anchor) {
  log("Inserting node:", logId(node), "into parent:", logId(parent), "with anchor:", logId(anchor), node instanceof TextNode);
  if (node instanceof SlotRenderable) {
    node.parent = parent;
    node = node.getSlotChild(parent);
  }
  if (anchor && anchor instanceof SlotRenderable) {
    anchor = anchor.getSlotChild(parent);
  }
  if (isTextNodeRenderable(node)) {
    if (!(parent instanceof TextRenderable2) && !isTextNodeRenderable(parent)) {
      throw new Error(`Orphan text error: "${node.toChunks().map((c) => c.text).join("")}" must have a <text> as a parent: ${parent.id} above ${node.id}`);
    }
  }
  if (!(parent instanceof BaseRenderable)) {
    console.error("[INSERT]", "Tried to mount a non base renderable");
    throw new Error("Tried to mount a non base renderable");
  }
  if (!anchor) {
    parent.add(node);
    return;
  }
  const children2 = getNodeChildren(parent);
  const anchorIndex = children2.indexOf(anchor);
  if (anchorIndex === -1) {
    log("[INSERT]", "Could not find anchor", logId(parent), logId(anchor), "[children]", ...children2.map((c) => c.id));
  }
  parent.add(node, anchorIndex);
}
function _removeNode(parent, node) {
  log("Removing node:", logId(node), "from parent:", logId(parent));
  let slotParent;
  if (node instanceof SlotRenderable) {
    slotParent = node;
    const slotChild = slotParent.getSlotChildForRemoval(parent);
    if (!slotChild) {
      if (slotParent.parent === parent) {
        slotParent.parent = null;
      }
      return;
    }
    node = slotChild;
  }
  parent.remove(node);
  slotParent?.didRemoveSlotChild(parent, node);
  process.nextTick(() => {
    if (node instanceof BaseRenderable && !node.parent) {
      node.destroyRecursively();
      return;
    }
  });
}
function _createTextNode(value, decodeEntities) {
  log("Creating text node:", value);
  const id = getNextId("text-node");
  if (typeof value === "number") {
    value = value.toString();
  }
  return TextNode.fromString(decodeEntities ? decodeHTMLStrict(value) : value, { id });
}
function createSlotNode() {
  const id = getNextId("slot-node");
  log("Creating slot node", id);
  return new SlotRenderable(id);
}
function _getParentNode(childNode) {
  log("Getting parent of node:", logId(childNode));
  let parent = childNode.parent ?? undefined;
  if (parent instanceof RootTextNodeRenderable) {
    parent = parent.textParent ?? undefined;
  }
  const scrollBoxCandidate = parent?.parent?.parent?.parent;
  if (scrollBoxCandidate instanceof ScrollBoxRenderable2 && scrollBoxCandidate.content === parent) {
    parent = scrollBoxCandidate;
  }
  return parent;
}
function Portal(props) {
  const renderer = useRenderer();
  const marker = createSlotNode(), mount = () => props.mount || renderer.root, owner = getOwner();
  let content;
  createEffect(() => {
    content || (content = runWithOwner(owner, () => createMemo(() => props.children)));
    const el = mount();
    const container = createElement("box"), renderRoot = container;
    Object.defineProperty(container, "_$host", {
      get() {
        return marker.parent;
      },
      configurable: true
    });
    insert(renderRoot, content);
    el.add(container);
    props.ref && props.ref(container);
    onCleanup(() => el.remove(container));
  }, undefined, { render: true });
  return marker;
}
function createDynamic(component, props) {
  const cached = createMemo(component);
  return createMemo(() => {
    const component2 = cached();
    switch (typeof component2) {
      case "function":
        return untrack(() => component2(props));
      case "string":
        const el = createElement(component2);
        spread(el, props);
        return el;
      default:
        break;
    }
  });
}
function Dynamic(props) {
  const [, others] = splitProps(props, ["component"]);
  return createDynamic(() => props.component, others);
}
function getLayoutNodeConstructor(parent) {
  const parentLayoutNode = parent?.getLayoutNode?.();
  return parentLayoutNode?.constructor;
}
function createLayoutSlotYogaNode(parentNodeConstructor) {
  return parentNodeConstructor?.create?.() ?? Yoga.default.Node.create();
}
function normalizeSnapshotDimension(value, axis) {
  if (value === undefined) {
    return;
  }
  if (!Number.isFinite(value)) {
    throw new Error(`createScrollbackWriter requires a finite ${axis}`);
  }
  return Math.max(1, Math.trunc(value));
}
function createSnapshotRendererValue(renderContext, root, width, height, firstLineOffset) {
  const [snapshotWidth] = createSignal(width);
  const [snapshotHeight, setSnapshotHeight] = createSignal(height);
  const renderer = Object.create(renderContext);
  let offset = firstLineOffset;
  Object.defineProperties(renderer, {
    root: {
      value: root,
      enumerable: true,
      configurable: true
    },
    width: {
      get: snapshotWidth,
      enumerable: true,
      configurable: true
    },
    height: {
      get: snapshotHeight,
      enumerable: true,
      configurable: true
    },
    claimFirstLineOffset: {
      value: () => {
        const out = offset;
        offset = 0;
        return out;
      },
      enumerable: true,
      configurable: true
    }
  });
  return {
    renderer,
    getHeight: snapshotHeight,
    setHeight(nextHeight) {
      setSnapshotHeight(nextHeight);
      renderer.emit("resize", snapshotWidth(), nextHeight);
    }
  };
}
function runLifecyclePasses(renderContext) {
  for (const renderable of renderContext.getLifecyclePasses()) {
    renderable.onLifecyclePass?.call(renderable);
  }
}
function clearLifecyclePasses(renderContext) {
  for (const renderable of [...renderContext.getLifecyclePasses()]) {
    renderContext.unregisterLifecyclePass(renderable);
  }
}
function measureSnapshotHeight(renderContext, root) {
  const measureRoot = new RootRenderable(renderContext);
  try {
    measureRoot.add(root);
    runLifecyclePasses(renderContext);
    measureRoot.calculateLayout();
    return Math.max(1, Math.trunc(root.getLayoutNode().getComputedLayout().height));
  } finally {
    if (root.parent === measureRoot) {
      measureRoot.remove(root);
    }
    measureRoot.destroyRecursively();
  }
}
function resolveSnapshotHeight(renderContext, root, snapshotRenderer) {
  for (let pass = 0;pass < MAX_AUTO_HEIGHT_PASSES; pass++) {
    const measuredHeight = measureSnapshotHeight(renderContext, root);
    if (measuredHeight === snapshotRenderer.getHeight()) {
      clearLifecyclePasses(renderContext);
      return measuredHeight;
    }
    snapshotRenderer.setHeight(measuredHeight);
  }
  return measureSnapshotHeight(renderContext, root);
}
function createScrollbackWriter(node, options = {}) {
  return (ctx) => {
    const width = normalizeSnapshotDimension(options.width, "width") ?? Math.max(1, Math.trunc(ctx.width));
    const height = normalizeSnapshotDimension(options.height, "height");
    const startOnNewLine = options.startOnNewLine ?? true;
    const firstLineWidth = !startOnNewLine && ctx.tailColumn > 0 && ctx.tailColumn < ctx.width ? Math.min(width, ctx.width - ctx.tailColumn) : width;
    const firstLineOffset = width - firstLineWidth;
    const root = new BoxRenderable2(ctx.renderContext, {
      id: `solid-scrollback-root-${solidScrollbackRootCounter++}`,
      position: "absolute",
      left: 0,
      top: 0,
      width,
      height: height ?? "auto",
      border: false,
      backgroundColor: "transparent",
      shouldFill: false,
      flexDirection: "column"
    });
    const snapshotRenderer = createSnapshotRendererValue(ctx.renderContext, root, width, height ?? Math.max(1, ctx.renderContext.height), firstLineOffset);
    let dispose2;
    let disposed = false;
    const teardown = () => {
      if (disposed) {
        return;
      }
      disposed = true;
      dispose2?.();
    };
    try {
      dispose2 = _render(() => createComponent2(RendererContext.Provider, {
        get value() {
          return snapshotRenderer.renderer;
        },
        get children() {
          return node(ctx);
        }
      }), root);
      return {
        root,
        width,
        height: height ?? resolveSnapshotHeight(ctx.renderContext, root, snapshotRenderer),
        rowColumns: options.rowColumns,
        startOnNewLine,
        trailingNewline: options.trailingNewline,
        teardown
      };
    } catch (error) {
      teardown();
      root.destroyRecursively();
      throw error;
    }
  };
}
function writeSolidToScrollback(renderer, node, options = {}) {
  renderer.writeToScrollback(createScrollbackWriter(node, options));
}
function createSolidSlotRegistry(renderer, context, options = {}) {
  return createSlotRegistry(renderer, "solid:slot-registry", context, options);
}
function createSlot(registry, options = {}) {
  return function BoundSlot(props) {
    return createComponent2(Slot, mergeProps3(props, {
      registry,
      get pluginFailurePlaceholder() {
        return options.pluginFailurePlaceholder;
      }
    }));
  };
}
function Slot(props) {
  const [local, slotProps] = splitProps(props, ["registry", "name", "mode", "children", "pluginFailurePlaceholder"]);
  const registry = () => local.registry;
  const pluginFailurePlaceholder = () => local.pluginFailurePlaceholder;
  const [version, setVersion] = createSignal(0);
  let queued = false;
  let disposed = false;
  const unsubscribe = registry().subscribe(() => {
    if (queued)
      return;
    queued = true;
    setVersion((current) => current + 1);
    queueMicrotask(() => {
      queued = false;
      if (disposed)
        return;
    });
  });
  onCleanup(() => {
    disposed = true;
    unsubscribe();
  });
  const entries = createMemo((previousEntries = []) => {
    version();
    const resolvedEntries = registry().resolveEntries(local.name);
    if (resolvedEntries.length === 0) {
      if (previousEntries.length === 0)
        return previousEntries;
      return [];
    }
    const previousById = new Map(previousEntries.map((entry) => [entry.id, entry]));
    const nextEntries = resolvedEntries.map((entry) => {
      const previousEntry = previousById.get(entry.id);
      if (previousEntry && previousEntry.renderer === entry.renderer) {
        return previousEntry;
      }
      return entry;
    });
    const unchanged = nextEntries.length === previousEntries.length && nextEntries.every((entry, index) => entry === previousEntries[index]);
    if (unchanged)
      return previousEntries;
    return nextEntries;
  });
  const entryIds = createMemo(() => entries().map((entry) => entry.id));
  const entriesById = createMemo(() => new Map(entries().map((entry) => [entry.id, entry])));
  const slotName = () => String(local.name);
  const renderFallback = () => {
    const value = children(() => local.children)();
    return value ?? null;
  };
  const resolveFallback = (fallbackValue) => fallbackValue?.() ?? null;
  const renderPluginFailurePlaceholder = (failure, fallbackValue) => {
    if (!pluginFailurePlaceholder()) {
      return resolveFallback(fallbackValue);
    }
    try {
      return pluginFailurePlaceholder()(failure);
    } catch (error) {
      registry().reportPluginError({
        pluginId: failure.pluginId,
        slot: failure.slot ?? slotName(),
        phase: "error_placeholder",
        source: "solid",
        error
      });
      return resolveFallback(fallbackValue);
    }
  };
  const renderEntry = (entry, fallbackOnError) => {
    let initialRender;
    try {
      initialRender = entry.renderer(registry().context, slotProps);
    } catch (error) {
      const failure = registry().reportPluginError({
        pluginId: entry.id,
        slot: slotName(),
        phase: "render",
        source: "solid",
        error
      });
      return renderPluginFailurePlaceholder(failure, fallbackOnError);
    }
    const resolvedInitialRender = children(() => initialRender);
    const hasInitialOutput = resolvedInitialRender.toArray().some((node) => node !== null && node !== undefined && node !== false);
    if (!hasInitialOutput) {
      return resolveFallback(fallbackOnError);
    }
    return createComponent2(ErrorBoundary, {
      fallback: (error) => {
        const failure = registry().reportPluginError({
          pluginId: entry.id,
          slot: slotName(),
          phase: "render",
          source: "solid",
          error
        });
        return renderPluginFailurePlaceholder(failure, fallbackOnError);
      },
      get children() {
        return resolvedInitialRender();
      }
    });
  };
  const AppendEntry = (appendProps) => {
    const entry = createMemo(() => entriesById().get(appendProps.entryId));
    return memo2(() => {
      const resolvedEntry = entry();
      if (!resolvedEntry) {
        return null;
      }
      return renderEntry(resolvedEntry);
    });
  };
  const appendEntryIds = createMemo(() => {
    const mode = local.mode ?? "append";
    if (mode !== "append") {
      return EMPTY_ENTRY_IDS;
    }
    return entryIds();
  });
  const appendView = [renderFallback, createComponent2(For, {
    get each() {
      return appendEntryIds();
    },
    children: (entryId) => createComponent2(AppendEntry, {
      entryId
    })
  })];
  return memo2(() => {
    const resolvedEntries = entries();
    const mode = local.mode ?? "append";
    if (resolvedEntries.length === 0) {
      return renderFallback();
    }
    if (mode === "single_winner") {
      const winner = resolvedEntries[0];
      if (!winner) {
        return renderFallback();
      }
      return renderEntry(winner, renderFallback);
    }
    if (mode === "replace") {
      const renderedEntries = resolvedEntries.map((entry) => renderEntry(entry));
      const hasPluginOutput = renderedEntries.some((entry) => entry !== null && entry !== undefined && entry !== false);
      if (!hasPluginOutput) {
        return renderFallback();
      }
      return renderedEntries;
    }
    return appendView;
  });
}
var SpanRenderable, textNodeKeys, TextModifierRenderable, BoldSpanRenderable, ItalicSpanRenderable, UnderlineSpanRenderable, LineBreakRenderable, LinkRenderable, baseComponents, componentCatalogue, RendererContext, useRenderer = () => {
  const renderer = useContext(RendererContext);
  if (!renderer) {
    throw new Error("No renderer found");
  }
  return renderer;
}, onResize = (callback) => {
  const renderer = useRenderer();
  onMount(() => {
    renderer.on("resize", callback);
  });
  onCleanup(() => {
    renderer.off("resize", callback);
  });
}, useTerminalDimensions = () => {
  const renderer = useRenderer();
  const [terminalDimensions, setTerminalDimensions] = createSignal({ width: renderer.width, height: renderer.height });
  const callback = (width, height) => {
    setTerminalDimensions({ width, height });
  };
  onResize(callback);
  return terminalDimensions;
}, useKeyboard = (callback, options) => {
  const renderer = useRenderer();
  const keyHandler = renderer.keyInput;
  onMount(() => {
    keyHandler.on("keypress", callback);
    if (options?.release) {
      keyHandler.on("keyrelease", callback);
    }
  });
  onCleanup(() => {
    keyHandler.off("keypress", callback);
    if (options?.release) {
      keyHandler.off("keyrelease", callback);
    }
  });
}, usePaste = (callback) => {
  const renderer = useRenderer();
  const keyHandler = renderer.keyInput;
  onMount(() => {
    keyHandler.on("paste", callback);
  });
  onCleanup(() => {
    keyHandler.off("paste", callback);
  });
}, useKeyHandler, onFocus = (callback) => {
  const renderer = useRenderer();
  onMount(() => {
    renderer.on("focus", callback);
  });
  onCleanup(() => {
    renderer.off("focus", callback);
  });
}, onBlur = (callback) => {
  const renderer = useRenderer();
  onMount(() => {
    renderer.on("blur", callback);
  });
  onCleanup(() => {
    renderer.off("blur", callback);
  });
}, useSelectionHandler = (callback) => {
  const renderer = useRenderer();
  onMount(() => {
    renderer.on("selection", callback);
  });
  onCleanup(() => {
    renderer.off("selection", callback);
  });
}, useTimeline = (options = {}) => {
  const timeline = new Timeline(options);
  onMount(() => {
    if (options.autoplay !== false) {
      timeline.play();
    }
    engine.register(timeline);
  });
  onCleanup(() => {
    timeline.pause();
    engine.unregister(timeline);
  });
  return timeline;
}, memo = (fn) => createMemo(() => fn()), idCounter, log = (...args) => {
  if (process.env.DEBUG) {
    console.log("[Reconciler]", ...args);
  }
}, TextNode, logId = (node) => {
  if (!node)
    return;
  return node.id;
}, getNodeChildren = (node) => {
  let children2;
  if (node instanceof TextRenderable2) {
    children2 = node.getTextChildren();
  } else {
    children2 = node.getChildren();
  }
  return children2;
}, _render, effect, memo2, createComponent2, createElement, createTextNode, insertNode, insert, spread, setProp, mergeProps3, use, SlotBaseRenderable, TextSlotRenderable, LayoutSlotRenderable, SlotRenderable, solidScrollbackRootCounter = 0, MAX_AUTO_HEIGHT_PASSES = 4, TimeToFirstDraw = (props) => {
  return (() => {
    var _el$ = createElement("time_to_first_draw");
    spread(_el$, props, false);
    return _el$;
  })();
}, EMPTY_ENTRY_IDS, mountSolidRoot = (renderer, node) => {
  let dispose2;
  let disposeRequested = false;
  let disposed = false;
  let mounting = true;
  let destroyRequested = false;
  const originalDestroy = renderer.destroy.bind(renderer);
  const runDispose = () => {
    if (disposed) {
      return;
    }
    if (!dispose2) {
      disposeRequested = true;
      return;
    }
    disposed = true;
    dispose2();
  };
  renderer.once("destroy", runDispose);
  renderer.destroy = () => {
    if (mounting) {
      destroyRequested = true;
      return;
    }
    originalDestroy();
  };
  try {
    dispose2 = _render(() => createComponent2(RendererContext.Provider, {
      get value() {
        return renderer;
      },
      get children() {
        return createComponent2(node, {});
      }
    }), renderer.root);
  } finally {
    mounting = false;
    renderer.destroy = originalDestroy;
  }
  if (disposeRequested) {
    runDispose();
  }
  if (destroyRequested) {
    originalDestroy();
  }
}, render = async (node, rendererOrConfig = {}) => {
  const renderer = rendererOrConfig instanceof CliRenderer ? rendererOrConfig : await createCliRenderer({
    ...rendererOrConfig,
    onDestroy: () => {
      rendererOrConfig.onDestroy?.();
    }
  });
  engine2.attach(renderer);
  mountSolidRoot(renderer, node);
}, testRender = async (node, renderConfig = {}) => {
  const testSetup = await createTestRenderer({
    ...renderConfig,
    onDestroy: () => {
      renderConfig.onDestroy?.();
    }
  });
  engine2.attach(testSetup.renderer);
  mountSolidRoot(testSetup.renderer, node);
  return testSetup;
};
var init_index_bun = __esm(() => {
  init_server();
  init_server();
  init_esm();
  init_server();
  init_server();
  init_server();
  init_server();
  init_server();
  SpanRenderable = class SpanRenderable extends TextNodeRenderable {
    _ctx;
    constructor(_ctx, options) {
      super(options);
      this._ctx = _ctx;
    }
  };
  textNodeKeys = ["span", "b", "strong", "i", "em", "u", "a"];
  TextModifierRenderable = class TextModifierRenderable extends SpanRenderable {
    constructor(options, modifier) {
      super(null, options);
      if (modifier === "b" || modifier === "strong") {
        this.attributes = (this.attributes || 0) | TextAttributes.BOLD;
      } else if (modifier === "i" || modifier === "em") {
        this.attributes = (this.attributes || 0) | TextAttributes.ITALIC;
      } else if (modifier === "u") {
        this.attributes = (this.attributes || 0) | TextAttributes.UNDERLINE;
      }
    }
  };
  BoldSpanRenderable = class BoldSpanRenderable extends TextModifierRenderable {
    constructor(options) {
      super(options, "b");
    }
  };
  ItalicSpanRenderable = class ItalicSpanRenderable extends TextModifierRenderable {
    constructor(options) {
      super(options, "i");
    }
  };
  UnderlineSpanRenderable = class UnderlineSpanRenderable extends TextModifierRenderable {
    constructor(options) {
      super(options, "u");
    }
  };
  LineBreakRenderable = class LineBreakRenderable extends SpanRenderable {
    constructor(_ctx, options) {
      super(null, options);
      this.add();
    }
    add() {
      return super.add(`
`);
    }
  };
  LinkRenderable = class LinkRenderable extends SpanRenderable {
    constructor(_ctx, options) {
      const linkOptions = {
        ...options,
        link: { url: options.href }
      };
      super(null, linkOptions);
    }
  };
  baseComponents = {
    box: BoxRenderable,
    text: TextRenderable,
    input: InputRenderable,
    select: SelectRenderable,
    textarea: TextareaRenderable,
    ascii_font: ASCIIFontRenderable,
    tab_select: TabSelectRenderable,
    scrollbox: ScrollBoxRenderable,
    code: CodeRenderable,
    diff: DiffRenderable,
    line_number: LineNumberRenderable,
    markdown: MarkdownRenderable,
    image: ImageRenderable,
    span: SpanRenderable,
    strong: BoldSpanRenderable,
    b: BoldSpanRenderable,
    em: ItalicSpanRenderable,
    i: ItalicSpanRenderable,
    u: UnderlineSpanRenderable,
    br: LineBreakRenderable,
    a: LinkRenderable
  };
  componentCatalogue = { ...baseComponents };
  RendererContext = createContext();
  useKeyHandler = useKeyboard;
  idCounter = new Map;
  TextNode = class TextNode extends TextNodeRenderable2 {
    static fromString(text, options = {}) {
      const node = new TextNode(options);
      node.add(text);
      return node;
    }
  };
  ({
    render: _render,
    effect,
    memo: memo2,
    createComponent: createComponent2,
    createElement,
    createTextNode,
    insertNode,
    insert,
    spread,
    setProp,
    mergeProps: mergeProps3,
    use
  } = createRenderer2({
    createElement(tagName) {
      log("Creating element:", tagName);
      const id = getNextId(tagName);
      const solidRenderer = useContext(RendererContext);
      if (!solidRenderer) {
        throw new Error("No renderer found");
      }
      const elements = getComponentCatalogue();
      if (!elements[tagName]) {
        throw new Error(`[Reconciler] Unknown component type: ${tagName}`);
      }
      const element = new elements[tagName](solidRenderer, { id });
      if (element instanceof ImageRenderable2) {
        onCleanup(() => {
          element.source = undefined;
        });
      }
      log("Element created with id:", id);
      return element;
    },
    createTextNode: (value) => _createTextNode(value, true),
    createDynamicTextNode: (value) => _createTextNode(value, false),
    createSlotNode,
    replaceText(textNode, value) {
      log("Replacing text:", value, "in node:", logId(textNode));
      if (!(textNode instanceof TextNode))
        return;
      textNode.replace(value, 0);
    },
    setProperty(node, name, value, prev) {
      if (name.startsWith("on:")) {
        const eventName = name.slice(3);
        if (value) {
          node.on(eventName, value);
        }
        if (prev) {
          node.off(eventName, prev);
        }
        return;
      }
      if (isTextNodeRenderable(node)) {
        if (name === "href") {
          node.link = { url: value };
          return;
        }
        if (name === "style") {
          node.attributes |= createTextAttributes(value);
          node.fg = value.fg ? parseColor(value.fg) : node.fg;
          node.bg = value.bg ? parseColor(value.bg) : node.bg;
          return;
        }
        return;
      }
      switch (name) {
        case "id":
          log("Id mapped", node.id, "=", value);
          node[name] = value;
          break;
        case "focused":
          if (!(node instanceof Renderable))
            return;
          if (value) {
            node.focus();
          } else {
            node.blur();
          }
          break;
        case "onChange":
          let event = undefined;
          if (node instanceof SelectRenderable2) {
            event = SelectRenderableEvents.SELECTION_CHANGED;
          } else if (node instanceof TabSelectRenderable2) {
            event = TabSelectRenderableEvents.SELECTION_CHANGED;
          } else if (node instanceof InputRenderable2) {
            event = InputRenderableEvents.CHANGE;
          }
          if (!event)
            break;
          if (value) {
            node.on(event, value);
          }
          if (prev) {
            node.off(event, prev);
          }
          break;
        case "onInput":
          if (node instanceof InputRenderable2) {
            if (value) {
              node.on(InputRenderableEvents.INPUT, value);
            }
            if (prev) {
              node.off(InputRenderableEvents.INPUT, prev);
            }
          }
          break;
        case "onSubmit":
          if (node instanceof InputRenderable2) {
            if (value) {
              node.on(InputRenderableEvents.ENTER, value);
            }
            if (prev) {
              node.off(InputRenderableEvents.ENTER, prev);
            }
          } else {
            node[name] = value;
          }
          break;
        case "onSelect":
          if (node instanceof SelectRenderable2) {
            if (value) {
              node.on(SelectRenderableEvents.ITEM_SELECTED, value);
            }
            if (prev) {
              node.off(SelectRenderableEvents.ITEM_SELECTED, prev);
            }
          } else if (node instanceof TabSelectRenderable2) {
            if (value) {
              node.on(TabSelectRenderableEvents.ITEM_SELECTED, value);
            }
            if (prev) {
              node.off(TabSelectRenderableEvents.ITEM_SELECTED, prev);
            }
          }
          break;
        case "style":
          const nextStyle = value ?? {};
          const previousStyle = prev ?? {};
          if (isEditBufferRenderable(node) && previousStyle.selectionOccupancy && !nextStyle.selectionOccupancy) {
            node.selectionOccupancy = undefined;
          }
          if (node instanceof ImageRenderable2) {
            for (const prop in previousStyle) {
              if (Object.prototype.hasOwnProperty.call(nextStyle, prop))
                continue;
              if (prop !== "fit" && prop !== "protocol")
                continue;
              node[prop] = undefined;
            }
          }
          for (const prop in nextStyle) {
            const propVal = nextStyle[prop];
            if (propVal === previousStyle[prop])
              continue;
            node[prop] = propVal;
          }
          break;
        case "text":
        case "content": {
          const textValue = typeof value === "string" ? value : Array.isArray(value) ? value.join("") : `${value}`;
          node[name] = textValue;
          break;
        }
        default:
          node[name] = value;
      }
    },
    isTextNode(node) {
      return node instanceof TextNode;
    },
    insertNode: _insertNode,
    removeNode: _removeNode,
    getParentNode: _getParentNode,
    getFirstChild(node) {
      log("Getting first child of node:", logId(node));
      const firstChild = getNodeChildren(node)[0];
      if (!firstChild) {
        log("No first child found for node:", logId(node));
        return;
      }
      log("First child found:", logId(firstChild), "for node:", logId(node));
      return firstChild;
    },
    getNextSibling(node) {
      log("Getting next sibling of node:", logId(node));
      const parent = _getParentNode(node);
      if (!parent) {
        log("No parent found for node:", logId(node));
        return;
      }
      if (node instanceof SlotRenderable) {
        const layoutSlotNode = node.getSlotChildForRemoval(parent);
        if (layoutSlotNode) {
          node = layoutSlotNode;
        }
      }
      const siblings = getNodeChildren(parent);
      const index = siblings.indexOf(node);
      if (index === -1 || index === siblings.length - 1) {
        log("No next sibling found for node:", logId(node));
        return;
      }
      const nextSibling = siblings[index + 1];
      if (!nextSibling) {
        log("Next sibling is null for node:", logId(node));
        return;
      }
      log("Next sibling found:", logId(nextSibling), "for node:", logId(node));
      return nextSibling;
    }
  }));
  SlotBaseRenderable = class SlotBaseRenderable extends BaseRenderable2 {
    constructor(id) {
      super({
        id
      });
    }
    add(obj, index) {
      throw new Error("Can't add children on an Slot renderable");
    }
    getChildren() {
      return [];
    }
    remove(child) {}
    insertBefore(obj, anchor) {
      throw new Error("Can't add children on an Slot renderable");
    }
    getRenderable(id) {
      return;
    }
    getChildrenCount() {
      return 0;
    }
    requestRender() {}
    findDescendantById(id) {
      return;
    }
  };
  TextSlotRenderable = class TextSlotRenderable extends TextNodeRenderable3 {
    slotParent;
    destroyed = false;
    constructor(id, parent) {
      super({ id });
      this._visible = false;
      this.slotParent = parent;
    }
    detachFromSlot() {
      this.slotParent = undefined;
    }
    disposeWithoutSlotCascade() {
      if (this.destroyed) {
        return;
      }
      this.destroyed = true;
      this.detachFromSlot();
    }
    destroy() {
      if (this.destroyed) {
        return;
      }
      this.destroyed = true;
      const slotParent = this.slotParent;
      this.slotParent = undefined;
      slotParent?.destroy();
      super.destroy();
    }
  };
  LayoutSlotRenderable = class LayoutSlotRenderable extends SlotBaseRenderable {
    yogaNode;
    slotParent;
    destroyed = false;
    yogaNodeConstructor;
    yogaNodeFreed = false;
    constructor(id, parent, layoutParent) {
      super(id);
      this._visible = false;
      this.slotParent = parent;
      this.yogaNodeConstructor = getLayoutNodeConstructor(layoutParent);
      this.yogaNode = createLayoutSlotYogaNode(this.yogaNodeConstructor);
      this.yogaNode.setDisplay(Yoga.Display.None);
    }
    getLayoutNode() {
      return this.yogaNode;
    }
    updateFromLayout() {}
    updateLayout() {}
    onRemove() {}
    isCompatibleWith(layoutParent) {
      return this.yogaNodeConstructor === getLayoutNodeConstructor(layoutParent);
    }
    detachFromSlot() {
      this.slotParent = undefined;
    }
    freeYogaNode() {
      if (this.yogaNodeFreed) {
        return;
      }
      this.yogaNodeFreed = true;
      try {
        this.yogaNode.free();
      } catch {}
    }
    disposeWithoutSlotCascade() {
      if (this.destroyed) {
        return;
      }
      this.destroyed = true;
      this.detachFromSlot();
      this.freeYogaNode();
    }
    destroy() {
      if (this.destroyed) {
        return;
      }
      this.destroyed = true;
      const slotParent = this.slotParent;
      this.slotParent = undefined;
      this.freeYogaNode();
      slotParent?.destroy();
    }
  };
  SlotRenderable = class SlotRenderable extends SlotBaseRenderable {
    destroyed = false;
    layoutNodesByParent = new Map;
    textNodesByParent = new Map;
    layoutNodeCount = 0;
    textNodeCount = 0;
    constructor(id) {
      super(id);
      this._visible = false;
    }
    get layoutNode() {
      return this.getCurrentSlotChild(this.layoutNodesByParent);
    }
    get textNode() {
      return this.getCurrentSlotChild(this.textNodesByParent);
    }
    isTextSlotParent(parent) {
      return isTextNodeRenderable2(parent) || parent instanceof TextRenderable3;
    }
    getCurrentSlotChild(nodesByParent) {
      for (const node of nodesByParent.values()) {
        if (node.parent) {
          return node;
        }
      }
      return nodesByParent.values().next().value;
    }
    getTextNodeForParent(parent) {
      const mappedNode = this.textNodesByParent.get(parent);
      if (mappedNode) {
        return mappedNode;
      }
      for (const [mappedParent, textNode] of this.textNodesByParent) {
        if (textNode.parent !== parent) {
          continue;
        }
        this.textNodesByParent.delete(mappedParent);
        this.textNodesByParent.set(parent, textNode);
        return textNode;
      }
    }
    getLayoutNodeForParent(parent) {
      const mappedNode = this.layoutNodesByParent.get(parent);
      if (mappedNode) {
        return mappedNode;
      }
      for (const [mappedParent, layoutNode] of this.layoutNodesByParent) {
        if (layoutNode.parent !== parent) {
          continue;
        }
        this.layoutNodesByParent.delete(mappedParent);
        this.layoutNodesByParent.set(parent, layoutNode);
        return layoutNode;
      }
    }
    takeReusableTextNode(parent) {
      for (const [mappedParent, textNode] of this.textNodesByParent) {
        if (textNode.parent) {
          continue;
        }
        this.textNodesByParent.delete(mappedParent);
        this.textNodesByParent.set(parent, textNode);
        return textNode;
      }
    }
    takeReusableLayoutNode(parent) {
      for (const [mappedParent, layoutNode] of this.layoutNodesByParent) {
        if (layoutNode.parent) {
          continue;
        }
        if (!layoutNode.isCompatibleWith(parent)) {
          continue;
        }
        this.layoutNodesByParent.delete(mappedParent);
        this.layoutNodesByParent.set(parent, layoutNode);
        return layoutNode;
      }
    }
    disposeDetachedTextNodes() {
      for (const [parent, textNode] of this.textNodesByParent) {
        if (textNode.parent) {
          continue;
        }
        this.textNodesByParent.delete(parent);
        textNode.disposeWithoutSlotCascade();
      }
    }
    disposeDetachedIncompatibleLayoutNodes(parent) {
      for (const [mappedParent, layoutNode] of this.layoutNodesByParent) {
        if (layoutNode.parent || layoutNode.isCompatibleWith(parent)) {
          continue;
        }
        this.layoutNodesByParent.delete(mappedParent);
        layoutNode.disposeWithoutSlotCascade();
      }
    }
    getAttachedSlotParent(excludedNode) {
      for (const textNode of this.textNodesByParent.values()) {
        if (textNode !== excludedNode && textNode.parent) {
          return textNode.parent;
        }
      }
      for (const layoutNode of this.layoutNodesByParent.values()) {
        if (layoutNode !== excludedNode && layoutNode.parent) {
          return layoutNode.parent;
        }
      }
      return null;
    }
    hasOtherAttachedSlotChildren(excludedNode) {
      return this.getAttachedSlotParent(excludedNode) !== null;
    }
    getSlotChild(parent) {
      if (this.isTextSlotParent(parent)) {
        const existingTextNode = this.getTextNodeForParent(parent);
        if (existingTextNode) {
          return existingTextNode;
        }
        const reusableTextNode = this.takeReusableTextNode(parent);
        if (reusableTextNode) {
          return reusableTextNode;
        }
        this.disposeDetachedIncompatibleLayoutNodes(parent);
        const textNode = new TextSlotRenderable(`slot-text-${this.id}-${++this.textNodeCount}`, this);
        this.textNodesByParent.set(parent, textNode);
        return textNode;
      }
      const existingLayoutNode = this.getLayoutNodeForParent(parent);
      if (existingLayoutNode) {
        return existingLayoutNode;
      }
      const reusableLayoutNode = this.takeReusableLayoutNode(parent);
      if (reusableLayoutNode) {
        return reusableLayoutNode;
      }
      this.disposeDetachedTextNodes();
      this.disposeDetachedIncompatibleLayoutNodes(parent);
      const layoutNode = new LayoutSlotRenderable(`slot-layout-${this.id}-${++this.layoutNodeCount}`, this, parent);
      this.layoutNodesByParent.set(parent, layoutNode);
      return layoutNode;
    }
    getSlotChildForRemoval(parent) {
      if (this.isTextSlotParent(parent)) {
        return this.getTextNodeForParent(parent);
      }
      return this.getLayoutNodeForParent(parent);
    }
    didRemoveSlotChild(parent, child) {
      const hasOtherAttachedSlotChildren = this.hasOtherAttachedSlotChildren(child);
      if (hasOtherAttachedSlotChildren && child instanceof TextSlotRenderable && this.getTextNodeForParent(parent) === child) {
        this.textNodesByParent.delete(parent);
        child.disposeWithoutSlotCascade();
      }
      if (hasOtherAttachedSlotChildren && child instanceof LayoutSlotRenderable && this.getLayoutNodeForParent(parent) === child) {
        this.layoutNodesByParent.delete(parent);
        child.disposeWithoutSlotCascade();
      }
      if (this.parent === parent) {
        this.parent = this.getAttachedSlotParent(child);
      }
    }
    destroy() {
      if (this.destroyed) {
        return;
      }
      this.destroyed = true;
      const layoutNodes = new Set(this.layoutNodesByParent.values());
      this.layoutNodesByParent.clear();
      for (const layoutNode of layoutNodes) {
        layoutNode.destroy();
      }
      const textNodes = new Set(this.textNodesByParent.values());
      this.textNodesByParent.clear();
      for (const textNode of textNodes) {
        textNode.destroy();
      }
    }
  };
  extend({
    time_to_first_draw: TimeToFirstDrawRenderable
  });
  EMPTY_ENTRY_IDS = [];
});

// ../../node_modules/.bun/@opentui+keymap@0.5.10+4b5b8a304ce90f81/node_modules/@opentui/keymap/chunks/index-p35cyhc4.js
var init_index_p35cyhc4 = () => {};

// ../../node_modules/.bun/@opentui+keymap@0.5.10+4b5b8a304ce90f81/node_modules/@opentui/keymap/chunks/index-frk6sdcd.js
function normalizeBindingTokenName(token) {
  const normalized = token.trim().toLowerCase();
  if (!normalized) {
    throw new Error("Invalid keymap token: token cannot be empty");
  }
  return normalized;
}
function normalizeKeyName(name) {
  const normalized = name.trim().toLowerCase();
  if (!normalized) {
    throw new Error("Invalid key name: key name cannot be empty");
  }
  return normalized;
}
function normalizeKeyStroke(input) {
  return {
    name: normalizeKeyName(input.name),
    ctrl: input.ctrl ?? false,
    shift: input.shift ?? false,
    meta: input.meta ?? false,
    super: input.super ?? false,
    hyper: input.hyper || undefined
  };
}
function cloneKeyStroke(stroke) {
  return {
    name: stroke.name,
    ctrl: stroke.ctrl,
    shift: stroke.shift,
    meta: stroke.meta,
    super: stroke.super,
    hyper: stroke.hyper || undefined
  };
}
function createKeySequencePart(input, options) {
  const stroke = cloneKeyStroke(normalizeKeyStroke(input));
  return {
    stroke,
    display: options?.display ?? stringifyCanonicalStroke(stroke),
    match: options?.match ?? createKeyMatch(stroke),
    tokenName: options?.tokenName ? normalizeBindingTokenName(options.tokenName) : undefined
  };
}
function cloneKeySequencePart(part) {
  return {
    stroke: cloneKeyStroke(part.stroke),
    display: part.display,
    match: part.match,
    tokenName: part.tokenName,
    patternName: part.patternName,
    payloadKey: part.payloadKey
  };
}
function cloneKeySequence(parts) {
  return parts.map((part) => cloneKeySequencePart(part));
}
function resolveKeyMatch(input) {
  if ("match" in input) {
    return input.match;
  }
  if ("stroke" in input) {
    return createKeyMatch(input.stroke);
  }
  return createKeyMatch(input);
}
function createKeyMatch(input) {
  return `key:${buildKeyMatchId(normalizeKeyStroke(input))}`;
}
function createTextKeyMatch(id) {
  const normalized = id.trim();
  if (!normalized) {
    throw new Error("Invalid keymap match id: id cannot be empty");
  }
  return `text:${normalized}`;
}
function stringifyKeyStroke(input, options) {
  if ("stroke" in input) {
    if (options?.preferDisplay && input.display) {
      return input.display;
    }
    return stringifyCanonicalStroke(input.stroke);
  }
  return stringifyCanonicalStroke(normalizeKeyStroke(input));
}
function stringifyKeySequence(input, options) {
  return input.map((part) => stringifyKeyStroke(part, options)).join(options?.separator ?? "");
}
function stringifyCanonicalStroke(stroke) {
  const parts = [];
  if (stroke.ctrl) {
    parts.push("ctrl");
  }
  if (stroke.shift) {
    parts.push("shift");
  }
  if (stroke.meta) {
    parts.push("meta");
  }
  if (stroke.super) {
    parts.push("super");
  }
  if (stroke.hyper) {
    parts.push("hyper");
  }
  parts.push(stroke.name === "return" ? "enter" : stroke.name);
  return parts.join("+");
}
function buildKeyMatchId(stroke) {
  return `${stroke.name}:${stroke.ctrl ? 1 : 0}:${stroke.shift ? 1 : 0}:${stroke.meta ? 1 : 0}:${stroke.super ? 1 : 0}:${stroke.hyper ? 1 : 0}`;
}
function getFocusedTargetIfAvailable(host) {
  if (host.isDestroyed) {
    return null;
  }
  return host.getFocusedTarget();
}
function forEachActivationTarget(host, focused, visit) {
  let current = focused ?? host.rootTarget;
  let isFocusedTarget = focused !== null;
  while (current) {
    const shouldContinue = visit(current, isFocusedTarget);
    if (shouldContinue === false) {
      return;
    }
    current = host.getParentTarget(current);
    isFocusedTarget = false;
  }
}
function getActivationPath(host, focused) {
  const path = new Set;
  forEachActivationTarget(host, focused, (current) => {
    path.add(current);
  });
  return path;
}
function getActiveLayersForFocused(layers, host, focused) {
  const activeLayers = [];
  const activationPath = getActivationPath(host, focused);
  const sortedLayers = Array.isArray(layers) ? layers : getSortedLayers(layers);
  for (const layer of sortedLayers) {
    if (isLayerActiveForFocused(host, layer, focused, activationPath)) {
      activeLayers.push(layer);
    }
  }
  return activeLayers;
}
function getSortedLayers(layers) {
  return [...layers].sort((left, right) => {
    const priorityDiff = right.priority - left.priority;
    return priorityDiff || right.order - left.order;
  });
}
function isLayerActiveForFocused(host, layer, focused, activationPath = getActivationPath(host, focused)) {
  const target = layer.target;
  if (!target) {
    return true;
  }
  if (host.isTargetDestroyed(target)) {
    return false;
  }
  if (layer.targetMode === "focus") {
    return target === focused;
  }
  return activationPath.has(target);
}
function patternCaptureCount(capture) {
  const part = capture.binding.sequence[capture.index];
  if (!part?.patternName) {
    return 0;
  }
  const captured = capture.patterns?.at(-1);
  return captured?.name === part.patternName ? captured.values.length : 0;
}
function captureHasMinimum(capture, patterns, missingPatternResult = true) {
  const part = capture.binding.sequence[capture.index];
  if (!part?.patternName) {
    return true;
  }
  const pattern = patterns.get(part.patternName);
  return pattern ? patternCaptureCount(capture) >= pattern.min : missingPatternResult;
}
function captureHasContinuations(capture, patterns, missingPatternMinimum = true) {
  const part = capture.binding.sequence[capture.index];
  if (part?.patternName) {
    const pattern = patterns.get(part.patternName);
    if (pattern && patternCaptureCount(capture) < pattern.max) {
      return true;
    }
  }
  return captureHasMinimum(capture, patterns, missingPatternMinimum) && capture.index + 1 < capture.binding.sequence.length;
}
function captureIsExact(capture, patterns) {
  return capture.index === capture.binding.sequence.length - 1 && captureHasMinimum(capture, patterns, false);
}
function createSequenceNode(parent, stroke, match, pattern) {
  return {
    parent,
    depth: parent ? parent.depth + 1 : 0,
    stroke,
    match,
    pattern,
    children: new Map,
    patternChildren: [],
    bindings: [],
    reachableBindings: []
  };
}
function buildSequenceTree(bindings, patterns) {
  const root = createSequenceNode(null, null, null);
  for (const binding of bindings) {
    if (binding.event !== "press") {
      continue;
    }
    let node = root;
    for (const part of binding.sequence) {
      let child;
      if (part.patternName) {
        const pattern = patterns.get(part.patternName);
        child = node.patternChildren.find((candidate) => candidate.pattern?.name === part.patternName);
        if (!child) {
          child = createSequenceNode(node, part.stroke, part.match, pattern);
          node.patternChildren.push(child);
        }
      } else {
        child = node.children.get(part.match);
        if (!child) {
          child = createSequenceNode(node, part.stroke, part.match);
          node.children.set(part.match, child);
        }
      }
      child.reachableBindings.push(binding);
      node = child;
    }
    node.bindings.push(binding);
  }
  return root;
}
function activeOptionsForCaptures(captures, patterns) {
  const options = [];
  for (const capture of captures) {
    if (!captureHasMinimum(capture, patterns)) {
      continue;
    }
    const index = capture.index + 1;
    const part = capture.binding.sequence[index];
    if (part) {
      options.push({
        part,
        binding: capture.binding,
        index,
        exact: index === capture.binding.sequence.length - 1,
        continues: index < capture.binding.sequence.length - 1
      });
    }
  }
  return options;
}
function appendPatternCapture(capture, index, part, value) {
  const patternName = part.patternName;
  if (!patternName) {
    return { ...capture, index };
  }
  const patterns = [...capture.patterns ?? []];
  const last = patterns.at(-1);
  if (last?.name === patternName) {
    patterns[patterns.length - 1] = {
      ...last,
      values: [...last.values, value],
      parts: [...last.parts, part]
    };
  } else {
    patterns.push({
      name: patternName,
      payloadKey: part.payloadKey ?? patternName,
      values: [value],
      parts: [part]
    });
  }
  return {
    layer: capture.layer,
    binding: capture.binding,
    index,
    parts: [...capture.parts, part],
    patterns
  };
}
function capturePriority(capture, matchKeys) {
  const part = capture.parts.at(-1);
  if (!part || part.patternName) {
    return matchKeys.length;
  }
  const index = matchKeys.indexOf(part.match);
  return index === -1 ? matchKeys.length : index;
}
function advanceSequenceBinding(layer, binding, index, parts, patterns, matchKeys, event, matchPattern, createPatternPart) {
  const part = binding.sequence[index];
  if (!part) {
    return;
  }
  if (part.patternName) {
    const patternMatch = matchPattern(part.patternName, event);
    if (!patternMatch) {
      return;
    }
    const eventPart = createPatternPart(event, part.patternName, patternMatch);
    return appendPatternCapture({ layer, binding, index, parts, patterns }, index, eventPart, patternMatch.value ?? event.name);
  }
  if (!matchKeys.includes(part.match)) {
    return;
  }
  return { layer, binding, index, parts: [...parts, part], patterns };
}
function advanceSequenceCapture(capture, matchKeys, event, patterns, matchPattern, createPatternPart) {
  const currentPart = capture.binding.sequence[capture.index];
  if (currentPart?.patternName) {
    const pattern = patterns.get(currentPart.patternName);
    if (pattern && patternCaptureCount(capture) < pattern.max) {
      const patternMatch = matchPattern(pattern.name, event);
      if (patternMatch) {
        const part = createPatternPart(event, pattern.name, patternMatch);
        return appendPatternCapture(capture, capture.index, part, patternMatch.value ?? event.name);
      }
    }
    if (!captureHasMinimum(capture, patterns, false)) {
      return;
    }
    return advanceSequenceBinding(capture.layer, capture.binding, capture.index + 1, capture.parts, capture.patterns, matchKeys, event, matchPattern, createPatternPart);
  }
  return advanceSequenceBinding(capture.layer, capture.binding, capture.index + 1, capture.parts, capture.patterns, matchKeys, event, matchPattern, createPatternPart);
}
function collectRootSequenceCaptures(layer, matchKeys, event, matchPattern, createPatternPart) {
  const captures = [];
  let bestPriority = Number.POSITIVE_INFINITY;
  for (const binding of layer.bindings) {
    if (binding.event !== "press") {
      continue;
    }
    const capture = advanceSequenceBinding(layer, binding, 0, [], undefined, matchKeys, event, matchPattern, createPatternPart);
    if (!capture) {
      continue;
    }
    const priority = capturePriority(capture, matchKeys);
    if (priority < bestPriority) {
      bestPriority = priority;
      captures.length = 0;
    }
    if (priority === bestPriority) {
      captures.push(capture);
    }
  }
  return captures;
}
var KEYMAP_EXTENSION_CONTEXT;
var init_index_frk6sdcd = __esm(() => {
  KEYMAP_EXTENSION_CONTEXT = Symbol("keymap-extension-context");
});

// ../../node_modules/.bun/@opentui+keymap@0.5.10+4b5b8a304ce90f81/node_modules/@opentui/keymap/src/index.js
function createRuntimeEmitter(onError) {
  let listeners = Object.create(null);
  const off = (name, listener) => {
    const current = listeners[name];
    if (!current)
      return;
    const next = current.filter((candidate) => candidate !== listener);
    if (next.length === 0)
      delete listeners[name];
    else if (next.length !== current.length)
      listeners[name] = next;
  };
  return {
    hook(name, listener) {
      listeners[name] = [...listeners[name] ?? [], listener];
      return () => off(name, listener);
    },
    has(name) {
      return (listeners[name]?.length ?? 0) > 0;
    },
    emit(name, ...args) {
      const current = listeners[name];
      if (!current)
        return;
      for (const listener of current) {
        try {
          if (args.length === 0)
            listener();
          else
            listener(args[0]);
        } catch (error) {
          onError(name, error);
        }
      }
    }
  };
}
function createItems() {
  let items = [];
  return {
    get: () => items,
    set: (next) => {
      items = next;
    },
    remove(value) {
      items = items.filter((candidate) => candidate !== value);
    },
    has: () => items.length > 0,
    clear: () => {
      items = [];
    }
  };
}
function createRuntimeOrderedRegistry() {
  const items = createItems();
  return {
    append(value) {
      items.set([...items.get(), value]);
      return () => items.remove(value);
    },
    prepend(value) {
      items.set([value, ...items.get()]);
      return () => items.remove(value);
    },
    values: items.get,
    has: items.has,
    clear: items.clear
  };
}
function createRuntimePriorityRegistry() {
  const items = createItems();
  let order = 0;
  return {
    register(listener, options) {
      const registered = { ...options, listener, order: order++ };
      items.set([...items.get(), registered].sort((left, right) => {
        const priorityDiff = right.priority - left.priority;
        return priorityDiff || left.order - right.order;
      }));
      return () => items.remove(registered);
    },
    entries: items.get,
    has: items.has,
    clear: items.clear
  };
}
function isKeyLike(value) {
  return typeof value === "string" || !!value && typeof value === "object" && !Array.isArray(value);
}
function validateBindings(bindings) {
  if (!Array.isArray(bindings)) {
    return { ok: false, reason: "Invalid keymap bindings: expected an array of binding objects" };
  }
  for (const [index, binding] of bindings.entries()) {
    if (!binding || typeof binding !== "object" || Array.isArray(binding)) {
      return { ok: false, reason: `Invalid keymap binding at index ${index}: expected a binding object` };
    }
    if (!isKeyLike(binding.key)) {
      return {
        ok: false,
        reason: `Invalid keymap binding at index ${index}: expected "key" to be a string or keystroke object`
      };
    }
  }
  return { ok: true };
}
function snapshotBindings(bindings) {
  const validation = validateBindings(bindings);
  if (!validation.ok) {
    throw new Error(validation.reason);
  }
  return bindings.map((binding) => ({
    ...binding,
    key: typeof binding.key === "string" ? binding.key : { ...binding.key }
  }));
}
function snapshotParsedBinding(binding) {
  return {
    ...binding,
    sequence: cloneKeySequence(binding.sequence)
  };
}
function createLayerDiagnostics(notify, commands) {
  const analyzers = createRuntimeOrderedRegistry();
  return {
    prependLayerAnalyzer(analyzer) {
      return analyzers.prepend(analyzer);
    },
    appendLayerAnalyzer(analyzer) {
      return analyzers.append(analyzer);
    },
    clearLayerAnalyzers() {
      analyzers.clear();
    },
    analyzeLayer(options) {
      const registeredAnalyzers = analyzers.values();
      if (registeredAnalyzers.length === 0)
        return;
      const bindings = buildLayerBindingAnalyses(options.bindings);
      const ctx = {
        target: options.target,
        order: options.order,
        sourceBindings: options.sourceBindings,
        bindings,
        hasTokenBindings: options.hasTokenBindings,
        checkCommandResolution(command) {
          return commands.getCommandResolutionStatus(command, options.commands);
        },
        warn(code, warning, message) {
          notify.emitWarning(code, warning, message);
        },
        warnOnce(key, code, warning, message) {
          notify.warnOnce(key, code, warning, message);
        },
        error(code, error, message) {
          notify.emitError(code, error, message);
        }
      };
      for (const analyzer of registeredAnalyzers) {
        try {
          analyzer(ctx);
        } catch (error) {
          notify.emitError("layer-analyzer-error", error, "[Keymap] Error in layer analyzer:");
        }
      }
    }
  };
}
function buildLayerBindingAnalyses(bindings) {
  return bindings.map((binding) => ({
    sequence: cloneKeySequence(binding.sequence),
    command: binding.command,
    attrs: binding.attrs,
    event: binding.event,
    preventDefault: binding.preventDefault,
    fallthrough: binding.fallthrough,
    parsedBinding: snapshotParsedBinding(binding.parsedBinding),
    sourceTarget: binding.sourceTarget,
    sourceLayerOrder: binding.sourceLayerOrder,
    bindingIndex: binding.bindingIndex,
    hasCommandAtSequence: bindings.some((candidate) => {
      return candidate.event === "press" && candidate.command !== undefined && sameSequence(candidate, binding);
    }),
    hasContinuations: bindings.some((candidate) => {
      return candidate.event === "press" && isPrefix(binding, candidate);
    })
  }));
}
function sameSequence(left, right) {
  return left.sequence.length === right.sequence.length && left.sequence.every((part, index) => part.match === right.sequence[index]?.match);
}
function isPrefix(left, right) {
  return left.sequence.length < right.sequence.length && left.sequence.every((part, index) => part.match === right.sequence[index]?.match);
}
function createActiveKeysCache() {
  return {
    version: -1,
    notifyVersion: -1,
    focused: undefined,
    value: [],
    targets: new WeakMap
  };
}
function createActiveKeysCaches() {
  return {
    plain: createActiveKeysCache(),
    bindings: createActiveKeysCache(),
    metadata: createActiveKeysCache(),
    bindingsAndMetadata: createActiveKeysCache()
  };
}
function getActiveKeysCache(caches, options) {
  if (options === undefined) {
    return caches.plain;
  }
  const includeBindings = options.includeBindings === true;
  const includeMetadata = options.includeMetadata === true;
  return includeBindings ? includeMetadata ? caches.bindingsAndMetadata : caches.bindings : includeMetadata ? caches.metadata : caches.plain;
}
function getFocusedActiveKeysCache(cache, cacheVersion, focused) {
  const cached = focused ? cache.targets.get(focused) : cache.nullTarget;
  return cached?.version === cacheVersion ? cached : undefined;
}
function setFocusedActiveKeysCache(cache, cacheVersion, focused, value) {
  const cached = { version: cacheVersion, value };
  if (focused) {
    cache.targets.set(focused, cached);
  } else {
    cache.nullTarget = cached;
  }
}
function isSamePendingSequence(current, next) {
  if (current === next) {
    return true;
  }
  if (!current || !next) {
    return false;
  }
  if (current.captures.length !== next.captures.length) {
    return false;
  }
  for (let index = 0;index < current.captures.length; index += 1) {
    const left = current.captures[index];
    const right = next.captures[index];
    if (!left || !right || left.layer !== right.layer || left.binding !== right.binding || left.index !== right.index || left.parts.length !== right.parts.length) {
      return false;
    }
    for (let partIndex = 0;partIndex < left.parts.length; partIndex += 1) {
      if (left.parts[partIndex]?.match !== right.parts[partIndex]?.match) {
        return false;
      }
    }
    const leftPatterns = left.patterns ?? [];
    const rightPatterns = right.patterns ?? [];
    if (leftPatterns.length !== rightPatterns.length) {
      return false;
    }
    for (let patternIndex = 0;patternIndex < leftPatterns.length; patternIndex += 1) {
      const leftPattern = leftPatterns[patternIndex];
      const rightPattern = rightPatterns[patternIndex];
      if (!leftPattern || !rightPattern || leftPattern.name !== rightPattern.name) {
        return false;
      }
      if (leftPattern.values.length !== rightPattern.values.length) {
        return false;
      }
      for (let valueIndex = 0;valueIndex < leftPattern.values.length; valueIndex += 1) {
        if (!Object.is(leftPattern.values[valueIndex], rightPattern.values[valueIndex])) {
          return false;
        }
      }
    }
  }
  return true;
}
function popCapture(capture) {
  const lastPart = capture.parts.at(-1);
  if (!lastPart || capture.parts.length <= 1) {
    return;
  }
  let index = capture.index - 1;
  let patterns = capture.patterns;
  if (lastPart.patternName) {
    const lastPattern = patterns?.at(-1);
    if (lastPattern?.name === lastPart.patternName) {
      if (lastPattern.values.length > 1) {
        index = capture.index;
        patterns = [
          ...(patterns ?? []).slice(0, -1),
          {
            ...lastPattern,
            values: lastPattern.values.slice(0, -1),
            parts: lastPattern.parts.slice(0, -1)
          }
        ];
      } else {
        patterns = (patterns ?? []).slice(0, -1);
      }
    }
  }
  return {
    layer: capture.layer,
    binding: capture.binding,
    index,
    parts: capture.parts.slice(0, -1),
    patterns
  };
}
function collectSequencePartsFromPending(pending) {
  const firstCapture = pending.captures[0];
  if (!firstCapture || firstCapture.parts.length === 0) {
    return [];
  }
  const parts = [];
  for (let index = 0;index < firstCapture.parts.length; index += 1) {
    const firstPart = firstCapture.parts[index];
    if (!firstPart)
      continue;
    let display;
    let tokenName;
    let hasDisplayConflict = false;
    let hasTokenConflict = false;
    for (const capture of pending.captures) {
      const part = capture.parts[index];
      if (!part) {
        continue;
      }
      if (display === undefined) {
        display = part.display;
        tokenName = part.tokenName;
        continue;
      }
      if (!hasDisplayConflict && display !== part.display) {
        hasDisplayConflict = true;
      }
      if (!hasTokenConflict && tokenName !== part.tokenName) {
        hasTokenConflict = true;
      }
    }
    if (display === undefined || hasDisplayConflict) {
      display = stringifyKeyStroke(firstPart.stroke);
    }
    if (hasTokenConflict) {
      tokenName = undefined;
    }
    parts.push(createKeySequencePart(firstPart.stroke, {
      display,
      match: firstPart.match,
      tokenName
    }));
  }
  return parts;
}
function getLiveHost(host) {
  if (host.isDestroyed) {
    throw new Error("Cannot use a keymap after its host was destroyed");
  }
  return host;
}
function createActivationService(state, host, hooks, notify, conditions, catalog, options = {}) {
  const activeKeysCaches = createActiveKeysCaches();
  let pendingSequenceCacheVersion = -1;
  let pendingSequenceCache = [];
  const getFocusedTarget = () => {
    return getLiveHost(host).getFocusedTarget();
  };
  const getFocusedTargetIfAvailable2 = () => {
    return getFocusedTargetIfAvailable(host);
  };
  const setPendingSequence = (next) => {
    const previous = state.pending;
    if (isSamePendingSequence(previous, next)) {
      return;
    }
    state.pending = next;
    options.onPendingSequenceChanged?.(previous, next);
    notifyPendingSequenceChange();
    notify.queueStateChange();
  };
  const ensureValidPendingSequence = () => {
    const pending = state.pending;
    if (!pending) {
      return;
    }
    const focused = getFocusedTarget();
    const activeView = catalog.getActiveCommandView(focused);
    const captures = pending.captures.filter((capture) => {
      return state.layers.has(capture.layer) && isActiveLayerForFocused(capture.layer, focused) && conditions.matchesConditions(capture.layer) && bindingMatchesRuntimeState(capture.binding, focused, activeView) && captureHasContinuations(capture, state.patterns);
    });
    if (captures.length === 0) {
      setPendingSequence(null);
      return;
    }
    if (captures.length !== pending.captures.length) {
      setPendingSequence({ captures });
    }
    return state.pending ?? undefined;
  };
  const revalidatePendingSequenceIfNeeded = () => {
    if (host.isDestroyed || !state.pending) {
      return;
    }
    ensureValidPendingSequence();
  };
  const hasPendingSequenceState = () => {
    return !host.isDestroyed && state.pending !== null;
  };
  const getPendingSequence = () => {
    if (pendingSequenceCacheVersion === state.cacheVersion) {
      return pendingSequenceCache;
    }
    const pending = ensureValidPendingSequence();
    const sequence = pending ? collectSequencePartsFromPending(pending) : [];
    if (!pending || allRegisteredLayersCanCacheActiveKeys()) {
      pendingSequenceCacheVersion = state.cacheVersion;
      pendingSequenceCache = sequence;
    }
    return sequence;
  };
  const popPendingSequence = () => {
    const pending = ensureValidPendingSequence();
    if (!pending) {
      return false;
    }
    const firstCapture = pending.captures[0];
    if (!firstCapture || firstCapture.parts.length <= 1) {
      setPendingSequence(null);
      return true;
    }
    const nextCaptures = [];
    for (const capture of pending.captures) {
      const nextCapture = popCapture(capture);
      if (!nextCapture) {
        continue;
      }
      nextCaptures.push(nextCapture);
    }
    if (nextCaptures.length === 0) {
      setPendingSequence(null);
      return true;
    }
    setPendingSequence({ captures: nextCaptures });
    return true;
  };
  const getActiveKeys = (options2) => {
    const includeBindings = options2?.includeBindings === true;
    const includeMetadata = options2?.includeMetadata === true;
    const cache = getActiveKeysCache(activeKeysCaches, options2);
    if (cache.notifyVersion === state.derivedVersion) {
      return cache.value;
    }
    return collectActiveKeysForCache(cache, includeBindings, includeMetadata);
  };
  const collectActiveKeysForCache = (cache, includeBindings, includeMetadata) => {
    if (host.isDestroyed) {
      getLiveHost(host);
    }
    const focused = getFocusedTarget();
    const cached = getFocusedActiveKeysCache(cache, state.cacheVersion, focused);
    if (cached) {
      cache.notifyVersion = state.derivedVersion;
      cache.version = state.cacheVersion;
      cache.focused = focused;
      cache.value = cached.value;
      return cached.value;
    }
    const activeView = catalog.getActiveCommandView(focused);
    const pending = ensureValidPendingSequence();
    const activeLayers = pending ? [] : getActiveLayers(focused);
    const activeKeys = pending ? collectActiveKeysFromPending(pending.captures, includeBindings, includeMetadata, focused, activeView) : collectActiveKeysAtRoot(activeLayers, includeBindings, includeMetadata, focused, activeView);
    const canUseCache = pending ? allRegisteredLayersCanCacheActiveKeys() : activeLayersCanCacheActiveKeys(activeLayers);
    if (canUseCache) {
      cache.version = state.cacheVersion;
      cache.notifyVersion = state.derivedVersion;
      cache.focused = focused;
      cache.value = activeKeys;
      setFocusedActiveKeysCache(cache, state.cacheVersion, focused, activeKeys);
    }
    return activeKeys;
  };
  const getActiveKeysForCaptures = (captures, options2) => {
    const includeBindings = options2?.includeBindings === true;
    const includeMetadata = options2?.includeMetadata === true;
    const focused = getFocusedTarget();
    const activeView = catalog.getActiveCommandView(focused);
    return collectActiveKeysFromPending(captures, includeBindings, includeMetadata, focused, activeView);
  };
  const getActiveKeysForFocused = (focused, options2) => {
    const includeBindings = options2?.includeBindings === true;
    const includeMetadata = options2?.includeMetadata === true;
    const currentFocused = getFocusedTargetIfAvailable2();
    const pending = focused === currentFocused ? ensureValidPendingSequence() : undefined;
    const activeView = catalog.getActiveCommandView(focused);
    if (pending) {
      return collectActiveKeysFromPending(pending.captures, includeBindings, includeMetadata, focused, activeView);
    }
    return collectActiveKeysAtRoot(getActiveLayers(focused), includeBindings, includeMetadata, focused, activeView);
  };
  const getActiveLayers = (focused) => {
    if (state.activeLayersCacheVersion === state.cacheVersion && state.activeLayersCacheFocused === focused) {
      return state.activeLayersCache;
    }
    state.activeLayersCacheVersion = state.cacheVersion;
    state.activeLayersCacheFocused = focused;
    state.activeLayersCache = getActiveLayersForFocused(state.sortedLayers, host, focused);
    return state.activeLayersCache;
  };
  const isActiveLayerForFocused = (layer, focused) => {
    return isLayerActiveForFocused(host, layer, focused);
  };
  const activeLayersCanCacheActiveKeys = (activeLayers) => {
    return !state.commandResolvers.has() && state.activeKeyCacheBlockers === 0;
  };
  const allRegisteredLayersCanCacheActiveKeys = () => {
    return !state.commandResolvers.has() && state.activeKeyCacheBlockers === 0;
  };
  const collectMatchingBindings = (bindings, focused, activeView) => {
    const matches = [];
    for (const binding of bindings) {
      if (conditions.matchesConditions(binding) && catalog.isBindingVisible(binding, focused, activeView)) {
        matches.push(binding);
      }
    }
    return matches;
  };
  const bindingMatchesRuntimeState = (binding, focused, activeView) => {
    return conditions.matchesConditions(binding) && catalog.isBindingVisible(binding, focused, activeView);
  };
  const getPartPresentation = (bindings, partIndex) => {
    let display;
    let tokenName;
    let hasDisplayConflict = false;
    let hasTokenConflict = false;
    for (const binding of bindings) {
      const part = binding.sequence[partIndex];
      if (!part) {
        continue;
      }
      if (display === undefined) {
        display = part.display;
        tokenName = part.tokenName;
        continue;
      }
      if (!hasDisplayConflict && display !== part.display) {
        hasDisplayConflict = true;
      }
      if (!hasTokenConflict && tokenName !== part.tokenName) {
        hasTokenConflict = true;
      }
    }
    if (display === undefined || hasDisplayConflict) {
      const stroke = bindings[0]?.sequence[partIndex]?.stroke;
      display = stroke ? stringifyKeyStroke(stroke) : "";
    }
    if (hasTokenConflict) {
      tokenName = undefined;
    }
    return {
      display,
      tokenName
    };
  };
  const toActiveBinding = (binding, focused, activeView) => {
    return {
      sequence: binding.sequence,
      command: binding.command,
      commandAttrs: catalog.getBindingCommandAttrs(binding, focused, activeView),
      attrs: binding.attrs,
      event: binding.event,
      preventDefault: binding.preventDefault,
      fallthrough: binding.fallthrough
    };
  };
  const collectActiveBindings = (bindings, focused, activeView) => {
    return bindings.map((binding) => toActiveBinding(binding, focused, activeView));
  };
  const collectActiveKeysAtRoot = (activeLayers, includeBindings, includeMetadata, focused, activeView) => {
    const activeKeys = new Map;
    const stopped = new Set;
    for (const layer of activeLayers) {
      if (layer.root.children.size === 0 && layer.root.patternChildren.length === 0 || !conditions.matchesConditions(layer)) {
        continue;
      }
      collectActiveKeyNodes(layer.root.children.values(), activeKeys, stopped, includeBindings, focused, activeView);
      collectActiveKeyNodes(layer.root.patternChildren, activeKeys, stopped, includeBindings, focused, activeView);
    }
    return materializeActiveKeys(activeKeys, includeBindings, includeMetadata, focused, activeView);
  };
  const collectActiveKeyNodes = (nodes, activeKeys, stopped, includeBindings, focused, activeView) => {
    for (const node of nodes) {
      const bindingKey = node.match;
      if (!bindingKey || stopped.has(bindingKey) || !node.stroke) {
        continue;
      }
      const selection = selectActiveKeyNode(node, includeBindings, focused, activeView);
      if (!selection) {
        continue;
      }
      const existing = activeKeys.get(bindingKey);
      if (!existing) {
        activeKeys.set(bindingKey, createActiveKeyState(node.stroke, selection, includeBindings));
      } else {
        updateActiveKeyState(existing, selection, includeBindings);
      }
      if (selection.stop) {
        stopped.add(bindingKey);
      }
    }
  };
  const selectActiveKeyNode = (node, includeBindings, focused, activeView) => {
    const continues = node.children.size > 0 || node.patternChildren.length > 0;
    if (!continues) {
      const selected2 = selectActiveBindings(nodeExactBindingsNeedPrefilter(node) ? collectMatchingBindings(node.bindings, focused, activeView) : node.bindings, focused, activeView);
      if (!selected2) {
        return;
      }
      const presentation2 = getPartPresentation(selected2.bindings, node.depth - 1);
      return {
        display: presentation2.display,
        tokenName: presentation2.tokenName,
        continues: false,
        firstBinding: selected2.bindings[0],
        commandBinding: selected2.commandBinding,
        bindings: includeBindings ? [...selected2.bindings] : undefined,
        stop: selected2.stop
      };
    }
    const reachableBindings = collectMatchingBindings(node.reachableBindings, focused, activeView);
    if (reachableBindings.length === 0) {
      return;
    }
    const selected = selectActiveBindings(node.bindings, focused, activeView);
    const presentation = getPartPresentation(reachableBindings, node.depth - 1);
    return {
      display: presentation.display,
      tokenName: presentation.tokenName,
      continues: true,
      firstBinding: selected?.bindings[0],
      commandBinding: selected?.commandBinding,
      bindings: includeBindings && selected ? [...selected.bindings] : undefined,
      stop: true
    };
  };
  const nodeExactBindingsNeedPrefilter = (node) => {
    if (state.commandResolvers.has()) {
      return true;
    }
    for (const binding of node.bindings) {
      if (binding.matchers.length > 0) {
        return true;
      }
    }
    return false;
  };
  const collectActiveKeysFromPending = (captures, includeBindings, includeMetadata, focused, activeView) => {
    const activeKeys = new Map;
    const stopped = new Set;
    collectActiveKeyOptions(activeOptionsForCaptures(captures, state.patterns), activeKeys, stopped, includeBindings, focused, activeView);
    return materializeActiveKeys(activeKeys, includeBindings, includeMetadata, focused, activeView);
  };
  const collectActiveKeyOptions = (options2, activeKeys, stopped, includeBindings, focused, activeView) => {
    const seen = new Set;
    for (const option of options2) {
      if (seen.has(option.part.match)) {
        continue;
      }
      seen.add(option.part.match);
      collectActiveKeyOption(option, options2, activeKeys, stopped, includeBindings, focused, activeView);
    }
  };
  const collectActiveKeyOption = (option, siblingOptions, activeKeys, stopped, includeBindings, focused, activeView) => {
    const bindingKey = option.part.match;
    if (stopped.has(bindingKey)) {
      return;
    }
    const selection = selectActiveKeyOption(option, siblingOptions, includeBindings, focused, activeView);
    if (!selection) {
      return;
    }
    const existing = activeKeys.get(bindingKey);
    if (!existing) {
      activeKeys.set(bindingKey, createActiveKeyState(option.part.stroke, selection, includeBindings));
    } else {
      updateActiveKeyState(existing, selection, includeBindings);
    }
    if (selection.stop) {
      stopped.add(bindingKey);
    }
  };
  const materializeActiveKeys = (activeKeys, includeBindings, includeMetadata, focused, activeView) => {
    const materialized = [];
    for (const state2 of activeKeys.values()) {
      const activeKey = materializeActiveKey(state2, includeBindings, includeMetadata, focused, activeView);
      if (activeKey) {
        materialized.push(activeKey);
      }
    }
    return materialized;
  };
  const selectActiveKeyOption = (option, siblingOptions, includeBindings, focused, activeView) => {
    const matchingOptions = siblingOptions.filter((candidate) => candidate.part.match === option.part.match);
    const exactBindings = matchingOptions.filter((candidate) => candidate.exact).map((candidate) => candidate.binding);
    const selected = selectActiveBindings(exactBindings, focused, activeView);
    const continues = matchingOptions.some((candidate) => candidate.continues);
    if (!continues && !selected) {
      return;
    }
    const presentation = getOptionPresentation(matchingOptions);
    return {
      display: presentation.display,
      tokenName: presentation.tokenName,
      continues,
      firstBinding: selected?.bindings[0],
      commandBinding: selected?.commandBinding,
      bindings: includeBindings && selected ? [...selected.bindings] : undefined,
      stop: continues || selected?.stop === true
    };
  };
  const getOptionPresentation = (options2) => {
    let display;
    let tokenName;
    let hasDisplayConflict = false;
    let hasTokenConflict = false;
    for (const option of options2) {
      const part = option.part;
      if (display === undefined) {
        display = part.display;
        tokenName = part.tokenName;
        continue;
      }
      if (!hasDisplayConflict && display !== part.display) {
        hasDisplayConflict = true;
      }
      if (!hasTokenConflict && tokenName !== part.tokenName) {
        hasTokenConflict = true;
      }
    }
    const firstPart = options2[0]?.part;
    if (display === undefined || hasDisplayConflict) {
      display = firstPart ? stringifyKeyStroke(firstPart.stroke) : "";
    }
    if (hasTokenConflict) {
      tokenName = undefined;
    }
    return { display, tokenName };
  };
  const selectActiveBindings = (bindings, focused, activeView) => {
    const selected = [];
    let commandBinding;
    for (const binding of bindings) {
      if (!conditions.matchesConditions(binding) || !catalog.isBindingVisible(binding, focused, activeView)) {
        continue;
      }
      selected.push(binding);
      if (binding.command === undefined) {
        continue;
      }
      commandBinding ??= binding;
      if (!binding.fallthrough) {
        return { bindings: selected, commandBinding, stop: true };
      }
    }
    if (selected.length === 0) {
      return;
    }
    return { bindings: selected, commandBinding, stop: false };
  };
  const createActiveKeyState = (stroke, selection, includeBindings) => {
    return {
      stroke,
      display: selection.display,
      tokenName: selection.tokenName,
      continues: selection.continues,
      firstBinding: selection.firstBinding,
      commandBinding: selection.commandBinding,
      bindings: includeBindings && selection.bindings ? [...selection.bindings] : undefined
    };
  };
  const updateActiveKeyState = (state2, selection, includeBindings) => {
    if (!state2.firstBinding && selection.firstBinding) {
      state2.firstBinding = selection.firstBinding;
    }
    if (!state2.commandBinding && selection.commandBinding) {
      state2.commandBinding = selection.commandBinding;
    }
    if (selection.continues) {
      state2.continues = true;
    }
    if (!includeBindings || !selection.bindings || selection.bindings.length === 0) {
      return;
    }
    if (!state2.bindings) {
      state2.bindings = [...selection.bindings];
      return;
    }
    state2.bindings.push(...selection.bindings);
  };
  const materializeActiveKey = (state2, includeBindings, includeMetadata, focused, activeView) => {
    if (!state2.commandBinding && !state2.continues) {
      return;
    }
    const activeKey = {
      stroke: cloneKeyStroke(state2.stroke),
      display: state2.display,
      continues: state2.continues
    };
    if (state2.tokenName) {
      activeKey.tokenName = state2.tokenName;
    }
    if (state2.commandBinding) {
      activeKey.command = state2.commandBinding.command;
    }
    if (includeBindings && state2.bindings && state2.bindings.length > 0) {
      activeKey.bindings = state2.bindings.length === 1 ? [toActiveBinding(state2.bindings[0], focused, activeView)] : collectActiveBindings(state2.bindings, focused, activeView);
    }
    if (includeMetadata) {
      if (state2.firstBinding?.attrs) {
        activeKey.bindingAttrs = state2.firstBinding.attrs;
      }
      const commandAttrs = state2.commandBinding ? catalog.getBindingCommandAttrs(state2.commandBinding, focused, activeView) : undefined;
      if (commandAttrs) {
        activeKey.commandAttrs = commandAttrs;
      }
    }
    return activeKey;
  };
  const notifyPendingSequenceChange = () => {
    if (!hooks.has("pendingSequence")) {
      return;
    }
    hooks.emit("pendingSequence", state.pending ? collectSequencePartsFromPending(state.pending) : []);
  };
  return {
    getFocusedTarget,
    getFocusedTargetIfAvailable: getFocusedTargetIfAvailable2,
    setPendingSequence,
    ensureValidPendingSequence,
    revalidatePendingSequenceIfNeeded,
    hasPendingSequenceState,
    getPendingSequence,
    popPendingSequence,
    getActiveKeys,
    getActiveKeysForCaptures,
    getActiveKeysForFocused,
    getActiveLayers,
    isLayerActiveForFocused: isActiveLayerForFocused,
    collectSequencePartsFromPending,
    collectMatchingBindings,
    collectActiveBindings
  };
}
function normalizeBindingCommand(command) {
  if (command === undefined || typeof command === "function") {
    return command;
  }
  const trimmed = command.trim();
  if (!trimmed) {
    throw new Error("Invalid keymap command: command cannot be empty");
  }
  return trimmed;
}
function normalizeCommandName(name) {
  const trimmed = name.trim();
  if (!trimmed) {
    throw new Error("Invalid keymap command name: name cannot be empty");
  }
  if (/\s/.test(trimmed)) {
    throw new Error(`Invalid keymap command name "${name}": command names cannot contain whitespace`);
  }
  return trimmed;
}
function pushCommandEntry(target, name, entry) {
  const existing = target.get(name);
  if (existing)
    existing.push(entry);
  else
    target.set(name, [entry]);
}
function getRegisteredCommandView(state) {
  const entries = [];
  const chainsByName = new Map;
  for (const layer of state.layers) {
    for (const commandState of layer.commands) {
      const entry = { layer, commandState };
      entries.push(entry);
      pushCommandEntry(chainsByName, commandState.command.name, entry);
    }
  }
  return { entries, chainsByName };
}
function collectActiveCommands(layers, conditions, checkLayerConditions) {
  const entries = [];
  const reachable = [];
  const reachableByName = new Map;
  const chainsByName = new Map;
  for (const layer of layers) {
    if (layer.commands.length === 0)
      continue;
    if (checkLayerConditions && !conditions.matchesConditions(layer))
      continue;
    for (const commandState of layer.commands) {
      if (!conditions.matchesConditions(commandState))
        continue;
      const entry = { layer, commandState };
      entries.push(entry);
      pushCommandEntry(chainsByName, commandState.command.name, entry);
      if (!reachableByName.has(commandState.command.name)) {
        reachableByName.set(commandState.command.name, entry);
        reachable.push(entry);
      }
    }
  }
  return { layers, entries, reachable, reachableByName, chainsByName };
}
function getActiveCommandView(state, host, conditions, focused) {
  if (state.activeLayersCacheVersion !== state.cacheVersion || state.activeLayersCacheFocused !== focused) {
    state.activeLayersCacheVersion = state.cacheVersion;
    state.activeLayersCacheFocused = focused;
    state.activeLayersCache = getActiveLayersForFocused(state.sortedLayers, host, focused);
  }
  return collectActiveCommands(state.activeLayersCache, conditions, true);
}
function mergeRequirement(target, name, value, source) {
  if (Object.prototype.hasOwnProperty.call(target, name) && !Object.is(target[name], value)) {
    throw new Error(`Conflicting keymap requirement for "${name}" from ${source}`);
  }
  target[name] = value;
}
function mergeAttribute(target, name, value, source) {
  if (Object.prototype.hasOwnProperty.call(target, name) && !Object.is(target[name], value)) {
    throw new Error(`Conflicting keymap attribute for "${name}" from ${source}`);
  }
  target[name] = value;
}
function createFieldCompilerContext(options) {
  const source = `field ${options.fieldName}`;
  return {
    require(name, value) {
      mergeRequirement(options.requirements, name, value, source);
    },
    attr(name, value) {
      if (!options.attrs) {
        throw new Error(`Keymap ${source} cannot publish attrs`);
      }
      mergeAttribute(options.attrs, name, value, source);
    },
    activeWhen(matcher) {
      options.matchers.push(options.conditions.buildRuntimeMatcher(matcher, source));
    }
  };
}
function isPlainObject(value) {
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}
function getErrorMessage(error, fallback) {
  if (error instanceof Error && error.message) {
    return error.message;
  }
  return fallback;
}
function isPromiseLike(value) {
  if (!value) {
    return false;
  }
  if (typeof value !== "object" && typeof value !== "function") {
    return false;
  }
  return typeof value.then === "function";
}
function snapshotDataValue(value, options) {
  const deep = options?.deep === true;
  const freeze = options?.freeze === true;
  const preserveNonPlainObjects = options?.preserveNonPlainObjects === true;
  if (Array.isArray(value)) {
    const cloned = deep ? value.map((entry) => snapshotDataValue(entry, options)) : [...value];
    return freeze ? Object.freeze(cloned) : cloned;
  }
  if (value && typeof value === "object") {
    if (preserveNonPlainObjects && !isPlainObject(value)) {
      return value;
    }
    const cloned = {};
    for (const [key, entry] of Object.entries(value)) {
      cloned[key] = deep ? snapshotDataValue(entry, options) : entry;
    }
    return freeze ? Object.freeze(cloned) : cloned;
  }
  return value;
}
function createCommandCatalogService(state, host, notify, conditions, options) {
  let registeredViewVersion = -1;
  let registeredView;
  let activeViewVersion = -1;
  let activeViewFocused;
  let activeView;
  let registeredBindingsCacheVersion = -1;
  let registeredBindingsCacheCommands;
  let registeredBindingsCache;
  let registeredBindingsByCommandVersion = -1;
  let registeredBindingsByCommand;
  let registeredResolvedCacheVersion = -1;
  let registeredResolvedCache = new Map;
  const normalizeLayerCommands = (commands) => {
    return normalizeCommands({
      commands,
      commandFields: state.commandFields,
      conditions,
      onError: (code, error, message) => {
        notify.emitError(code, error, message);
      }
    });
  };
  const prependCommandResolver = (resolver) => {
    return mutateCommandResolvers(() => state.commandResolvers.prepend(resolver), resolver);
  };
  const appendCommandResolver = (resolver) => {
    return mutateCommandResolvers(() => state.commandResolvers.append(resolver), resolver);
  };
  const clearCommandResolvers = () => {
    if (!state.commandResolvers.has()) {
      return;
    }
    notify.runWithStateChangeBatch(() => {
      state.commandResolvers.clear();
      options.onCommandResolversChanged();
      notify.queueStateChange();
    });
  };
  const getCommands = (query) => {
    return getFilteredCommandEntries(query).map((entry) => getCommand(entry.commandState));
  };
  const getCommandEntries = (query) => {
    const context = getCommandQueryContext(query);
    const filteredEntries = getFilteredCommandEntries(query, context);
    if (filteredEntries.length === 0) {
      return [];
    }
    const grouped = filteredEntries.map((entry) => ({
      entry,
      command: getCommand(entry.commandState),
      commandAttrs: entry.commandState.attrs,
      bindings: []
    }));
    const indexesByName = new Map;
    for (const [index, item] of grouped.entries()) {
      const existing = indexesByName.get(item.command.name);
      if (existing) {
        existing.push(index);
      } else {
        indexesByName.set(item.command.name, [index]);
      }
    }
    if (indexesByName.size > 0) {
      collectCommandEntryBindings(grouped, indexesByName, context);
    }
    return grouped.map((item) => ({
      command: item.command,
      bindings: item.bindings
    }));
  };
  const getCommandBindings = (query) => {
    if (query.visibility === "registered" && registeredBindingsCacheVersion === state.derivedVersion && registeredBindingsCacheCommands === query.commands && registeredBindingsCache) {
      return registeredBindingsCache;
    }
    const bindingsByCommand = new Map;
    for (const command of query.commands) {
      if (!bindingsByCommand.has(command)) {
        bindingsByCommand.set(command, []);
      }
    }
    if (bindingsByCommand.size === 0) {
      return bindingsByCommand;
    }
    collectCommandBindings(bindingsByCommand, getCommandQueryContext(query));
    if (query.visibility === "registered") {
      registeredBindingsCacheVersion = state.derivedVersion;
      registeredBindingsCacheCommands = query.commands;
      registeredBindingsCache = bindingsByCommand;
    }
    return bindingsByCommand;
  };
  const getResolvedCommandChain = (command, focused, execution) => {
    const view = getActiveCommandView2(focused);
    if (execution) {
      const resolved2 = [];
      const chain = view.chainsByName.get(command);
      if (chain) {
        for (const entry of chain) {
          resolved2.push({
            target: entry.layer.target,
            command: entry.commandState.command,
            attrs: entry.commandState.attrs,
            payload: execution.payload
          });
        }
      }
      const fallback2 = resolveCommandWithResolversForMode(command, focused, { mode: "active", execution });
      if (fallback2.resolved) {
        resolved2.push(fallback2.resolved);
      }
      return { entries: resolved2.length > 0 ? resolved2 : undefined, hadError: fallback2.hadError };
    }
    const resolved = [];
    for (const entry of view.chainsByName.get(command) ?? []) {
      resolved.push({
        target: entry.layer.target,
        command: entry.commandState.command,
        attrs: entry.commandState.attrs
      });
    }
    const fallback = resolveCommandWithResolversForMode(command, focused, { mode: "active" });
    if (fallback.resolved) {
      resolved.push(fallback.resolved);
    }
    return { entries: resolved.length > 0 ? resolved : undefined, hadError: fallback.hadError };
  };
  const getRegisteredResolvedEntries = (command) => {
    if (registeredResolvedCacheVersion !== state.derivedVersion) {
      registeredResolvedCacheVersion = state.derivedVersion;
      registeredResolvedCache = new Map;
    }
    if (registeredResolvedCache.has(command)) {
      return registeredResolvedCache.get(command) ?? undefined;
    }
    const resolved = resolveRegisteredEntries(getRegisteredCommandChain(command));
    registeredResolvedCache.set(command, resolved ?? null);
    return resolved;
  };
  const getActiveRegisteredResolvedEntries = (command, focused) => {
    return resolveRegisteredEntries(getActiveCommandView2(focused).chainsByName.get(command));
  };
  const resolveRegisteredResolverFallback = (command, execution) => {
    return resolveCommandWithResolversForMode(command, null, { mode: "registered", execution });
  };
  const resolveActiveResolverFallback = (command, focused, execution) => {
    return resolveCommandWithResolversForMode(command, focused, { mode: "active", execution });
  };
  const getTopCommand = (command, focused) => {
    const top = getTopResolvedCommand(command, focused);
    return top?.command;
  };
  const getCommandByName = (command) => {
    const top = getCommandEntry(command);
    return top?.commandState.command;
  };
  const getDispatchUnavailableCommandState = (command, focused, includeCommand) => {
    const view = getCommandView();
    const chain = view.chainsByName.get(command);
    if (!chain || chain.length === 0) {
      return;
    }
    let inactiveEntry;
    let disabledEntry;
    for (const entry of chain) {
      if (!isLayerActiveForFocused(host, entry.layer, focused)) {
        inactiveEntry ??= entry;
        continue;
      }
      if (!conditions.matchesConditions(entry.layer) || !conditions.matchesConditions(entry.commandState)) {
        disabledEntry ??= entry;
      }
    }
    const unavailableEntry = disabledEntry ?? inactiveEntry;
    if (!unavailableEntry) {
      return;
    }
    return {
      reason: disabledEntry ? "disabled" : "inactive",
      command: includeCommand ? unavailableEntry.commandState.command : undefined
    };
  };
  const getActiveCommandView2 = (focused) => {
    if (activeViewVersion === state.derivedVersion && activeViewFocused === focused && activeView) {
      return activeView;
    }
    const view = getActiveCommandView(state, host, conditions, focused);
    if (activeCommandViewCanCache()) {
      activeViewVersion = state.derivedVersion;
      activeViewFocused = focused;
      activeView = view;
    }
    return view;
  };
  const getCommandView = () => {
    if (registeredViewVersion === state.derivedVersion && registeredView) {
      return registeredView;
    }
    registeredViewVersion = state.derivedVersion;
    registeredView = getRegisteredCommandView(state);
    return registeredView;
  };
  const activeCommandViewCanCache = () => {
    return state.activeCommandViewCacheBlockers === 0;
  };
  const isBindingVisible = (binding, focused, activeView2) => {
    if (binding.command === undefined || binding.run) {
      return true;
    }
    if (typeof binding.command !== "string") {
      return false;
    }
    if (activeView2.reachableByName.has(binding.command)) {
      return true;
    }
    return getFallbackResolvedCommand(binding.command, focused, "active") !== undefined;
  };
  const getBindingCommandAttrs = (binding, focused, activeView2) => {
    if (typeof binding.command !== "string") {
      return;
    }
    const active = activeView2.reachableByName.get(binding.command);
    if (active) {
      return active.commandState.attrs;
    }
    const fallback = getFallbackResolvedCommand(binding.command, focused, "active");
    return fallback?.attrs;
  };
  const getCommandResolutionStatus = (command, layerCommands) => {
    if (layerCommands?.some((state2) => state2.command.name === command) || getCommandView().chainsByName.has(command)) {
      return "resolved";
    }
    const lookup = resolveCommandWithResolversForMode(command, getFocusedTargetIfAvailable(host));
    if (lookup.resolved || lookup.hadError) {
      return lookup.resolved ? "resolved" : "error";
    }
    return "unresolved";
  };
  const mutateCommandResolvers = (register, resolver) => {
    return notify.runWithStateChangeBatch(() => {
      const off = register();
      options.onCommandResolversChanged();
      notify.queueStateChange();
      return () => {
        notify.runWithStateChangeBatch(() => {
          off();
          if (state.commandResolvers.values().includes(resolver)) {
            return;
          }
          options.onCommandResolversChanged();
          notify.queueStateChange();
        });
      };
    });
  };
  const getTopResolvedCommand = (command, focused) => {
    const activeView2 = getActiveCommandView2(focused);
    const active = activeView2.reachableByName.get(command);
    if (active) {
      return {
        target: active.layer.target,
        command: active.commandState.command,
        attrs: active.commandState.attrs
      };
    }
    return getFallbackResolvedCommand(command, focused, "active");
  };
  const getCommandEntry = (command) => {
    return getRegisteredCommandChain(command)?.[0];
  };
  const getRegisteredCommandChain = (command) => {
    const entries = [];
    for (const layer of state.sortedLayers) {
      for (const commandState of layer.commands) {
        if (commandState.command.name === command) {
          entries.push({ layer, commandState });
        }
      }
    }
    return entries.length > 0 ? entries : undefined;
  };
  const resolveRegisteredEntries = (chain) => {
    if (!chain?.length) {
      return;
    }
    return chain.map((entry) => ({
      target: entry.layer.target,
      command: entry.commandState.command,
      attrs: entry.commandState.attrs
    }));
  };
  const getFallbackResolvedCommand = (command, focused, mode) => {
    const lookup = resolveCommandWithResolversForMode(command, focused, { mode });
    return lookup.resolved;
  };
  const getRegisteredLayerCommandEntries = () => {
    return getCommandView().entries;
  };
  const getRegisteredBindingsByCommand = () => {
    if (registeredBindingsByCommandVersion === state.derivedVersion && registeredBindingsByCommand) {
      return registeredBindingsByCommand;
    }
    const bindingsByCommand = new Map;
    for (const layer of state.layers) {
      for (const binding of layer.bindings) {
        if (typeof binding.command !== "string") {
          continue;
        }
        const bindings = bindingsByCommand.get(binding.command);
        if (bindings) {
          bindings.push(binding);
        } else {
          bindingsByCommand.set(binding.command, [binding]);
        }
      }
    }
    registeredBindingsByCommandVersion = state.derivedVersion;
    registeredBindingsByCommand = bindingsByCommand;
    return bindingsByCommand;
  };
  const getCommandQueryContext = (query) => {
    const visibility = query?.visibility ?? "reachable";
    const focused = query && Object.prototype.hasOwnProperty.call(query, "focused") ? query.focused ?? null : getFocusedTargetIfAvailable(host);
    if (visibility === "registered") {
      return { visibility, focused };
    }
    return {
      visibility,
      focused,
      activeView: getActiveCommandView2(focused)
    };
  };
  const getFilteredCommandEntries = (query, context = getCommandQueryContext(query)) => {
    let entries;
    if (context.visibility === "registered") {
      entries = getRegisteredLayerCommandEntries();
    } else if (context.visibility === "active") {
      entries = context.activeView?.entries ?? [];
    } else {
      entries = context.activeView?.reachable ?? [];
    }
    return queryLayerCommandEntries({
      entries,
      query,
      getCommand: (command) => getCommand(command),
      onFilterError: (error) => {
        notify.emitError("command-query-filter-error", error, "[Keymap] Error in command query filter:");
      }
    });
  };
  const collectCommandEntryBindings = (grouped, indexesByName, context) => {
    visitCommandQueryBindings(context, (binding) => {
      collectBindingForCommandEntries(grouped, indexesByName, binding);
    });
  };
  const collectCommandBindings = (bindingsByCommand, context) => {
    if (context.visibility === "registered") {
      const registeredBindings = getRegisteredBindingsByCommand();
      for (const [command, bindings] of bindingsByCommand) {
        const commandAttrs = getCommandView().chainsByName.get(command)?.[0]?.commandState.attrs;
        for (const binding of registeredBindings.get(command) ?? []) {
          bindings.push(createActiveBinding(binding, commandAttrs));
        }
      }
      return;
    }
    visitCommandQueryBindings(context, (binding) => {
      collectBindingForCommandBindings(bindingsByCommand, binding, context);
    });
  };
  const visitCommandQueryBindings = (context, visit) => {
    if (context.visibility === "registered") {
      for (const layer of state.layers) {
        for (const binding of layer.bindings)
          visit(binding);
      }
      return;
    }
    const activeView2 = context.activeView;
    if (!activeView2) {
      return;
    }
    for (const layer of activeView2.layers) {
      if (layer.bindings.length === 0 || !conditions.matchesConditions(layer)) {
        continue;
      }
      for (const binding of layer.bindings) {
        if (conditions.matchesConditions(binding) && isBindingVisible(binding, context.focused, activeView2)) {
          visit(binding);
        }
      }
    }
  };
  const collectBindingForCommandEntries = (grouped, indexesByName, binding) => {
    if (typeof binding.command !== "string") {
      return;
    }
    const indexes = indexesByName.get(binding.command);
    if (!indexes || indexes.length === 0) {
      return;
    }
    for (const index of indexes) {
      const item = grouped[index];
      if (!item) {
        continue;
      }
      item.bindings.push(createActiveBinding(binding, item.commandAttrs));
    }
  };
  const collectBindingForCommandBindings = (bindingsByCommand, binding, context) => {
    if (typeof binding.command !== "string") {
      return;
    }
    const bindings = bindingsByCommand.get(binding.command);
    if (!bindings) {
      return;
    }
    bindings.push(createActiveBinding(binding, getCommandBindingAttrsForQuery(binding, context)));
  };
  const createActiveBinding = (binding, commandAttrs) => {
    return {
      sequence: binding.sequence,
      command: binding.command,
      commandAttrs,
      attrs: binding.attrs,
      event: binding.event,
      preventDefault: binding.preventDefault,
      fallthrough: binding.fallthrough
    };
  };
  const getCommandBindingAttrsForQuery = (binding, context) => {
    if (typeof binding.command !== "string") {
      return;
    }
    if (context.visibility === "registered") {
      return getCommandView().chainsByName.get(binding.command)?.[0]?.commandState.attrs;
    }
    const activeView2 = context.activeView;
    if (!activeView2) {
      return;
    }
    return getBindingCommandAttrs(binding, context.focused, activeView2);
  };
  const resolveCommandWithResolversForMode = (command, focused, options2) => {
    const mode = options2?.mode ?? "active";
    const execution = options2?.execution ?? { input: command };
    const lookup = resolveCommandWithResolvers(command, state.commandResolvers.values(), () => createCommandResolverContext(focused, mode, execution), (error) => {
      notify.emitError("command-resolver-error", error, `[Keymap] Error in command resolver for "${command}":`);
    });
    let resolved = lookup.resolved;
    if (resolved) {
      const entry = getCommandEntryForMode(resolved.command.name, focused, mode);
      if (entry?.commandState.command === resolved.command && resolved.target === undefined) {
        resolved = { ...resolved, target: entry.layer.target };
        lookup.resolved = resolved;
      }
    }
    if (resolved && !resolved.attrs) {
      const attrs = getCommandStateAttrs(resolved.command.name, focused, mode) ?? getResolverCommandAttrs(resolved.command);
      if (attrs) {
        lookup.resolved = { ...resolved, attrs };
      }
    }
    return lookup;
  };
  const getCommandStateAttrs = (command, focused, mode) => {
    if (mode === "registered") {
      return getCommandEntry(command)?.commandState.attrs;
    }
    return getActiveCommandView2(focused).reachableByName.get(command)?.commandState.attrs;
  };
  const getCommandEntryForMode = (command, focused, mode) => {
    if (mode === "registered") {
      return getCommandEntry(command);
    }
    return getActiveCommandView2(focused).reachableByName.get(command);
  };
  const createCommandResolverContext = (focused, mode, execution) => {
    let input = execution.input;
    let payload = execution.payload;
    return {
      context: {
        get input() {
          return input;
        },
        get payload() {
          return payload;
        },
        setInput(nextInput) {
          input = nextInput;
        },
        setPayload(nextPayload) {
          payload = nextPayload;
        },
        getCommand: (name) => {
          if (mode === "registered") {
            return getCommandByName(name);
          }
          return getTopCommand(name, focused);
        }
      },
      getExecutionFields() {
        return { input, payload };
      }
    };
  };
  return {
    normalizeCommands: normalizeLayerCommands,
    prependCommandResolver,
    appendCommandResolver,
    clearCommandResolvers,
    getCommands,
    getCommandEntries,
    getCommandBindings,
    getResolvedCommandChain,
    getRegisteredResolvedEntries,
    getActiveRegisteredResolvedEntries,
    resolveRegisteredResolverFallback,
    resolveActiveResolverFallback,
    getTopCommand,
    getDispatchUnavailableCommandState,
    getActiveCommandView: getActiveCommandView2,
    isBindingVisible,
    getBindingCommandAttrs,
    getCommandResolutionStatus
  };
}
function getCommand(state) {
  return state.command;
}
function normalizeCommands(options) {
  const normalizedCommands = [];
  const seen = new Set;
  for (const command of options.commands) {
    try {
      const mergedRequires = {};
      const matchers = [];
      const normalizedName = normalizeCommandName(command.name);
      const fields = getCommandFields(command);
      const attrs = {};
      if (seen.has(normalizedName)) {
        options.onError("duplicate-command", { command: normalizedName }, `Duplicate keymap command "${normalizedName}" in the same layer`);
        continue;
      }
      command.name = normalizedName;
      for (const [fieldName, value] of Object.entries(fields)) {
        if (value === undefined) {
          continue;
        }
        const compiler = options.commandFields.get(fieldName);
        if (!compiler) {
          continue;
        }
        compiler(value, createFieldCompilerContext({
          fieldName,
          conditions: options.conditions,
          requirements: mergedRequires,
          matchers,
          attrs
        }));
      }
      const commandState = {
        command,
        fields,
        attrs: Object.keys(attrs).length === 0 ? undefined : attrs,
        requires: Object.entries(mergedRequires),
        matchers
      };
      seen.add(commandState.command.name);
      normalizedCommands.push(commandState);
    } catch (error) {
      options.onError("register-command-failed", error, getErrorMessage(error, `Failed to register keymap command "${String(command.name)}"`));
      continue;
    }
  }
  return normalizedCommands;
}
function resolveCommandWithResolvers(command, resolvers, createContext2, onResolverError) {
  if (resolvers.length === 0) {
    return { hadError: false };
  }
  let hadError = false;
  for (const resolver of resolvers) {
    let resolvedCommand;
    const attempt = createContext2();
    try {
      resolvedCommand = resolver(command, attempt.context);
    } catch (error) {
      hadError = true;
      onResolverError(error);
      continue;
    }
    if (resolvedCommand) {
      return { hadError, resolved: getResolverCommandEntry(resolvedCommand, attempt.getExecutionFields()) };
    }
  }
  return { hadError };
}
function getCommandFields(command) {
  const fields = {};
  for (const [name, value] of Object.entries(command)) {
    if (!RESERVED_COMMAND_FIELDS.has(name) && value !== undefined) {
      fields[name] = value;
    }
  }
  return Object.keys(fields).length === 0 ? EMPTY_COMMAND_FIELDS : fields;
}
function getResolverCommandEntry(command, execution) {
  return {
    command,
    input: execution.input,
    payload: execution.payload
  };
}
function getResolverCommandAttrs(command) {
  const fields = getCommandFields(command);
  return fields === EMPTY_COMMAND_FIELDS ? undefined : fields;
}
function queryLayerCommandEntries(options) {
  const namespace = options.query?.namespace;
  const limit = normalizeQueryLimit(options.query?.limit);
  if (limit === 0) {
    return [];
  }
  const normalizedSearch = options.query?.search?.trim().toLowerCase() ?? "";
  let searchKeys = DEFAULT_COMMAND_SEARCH_FIELDS;
  if (options.query?.searchIn && options.query.searchIn.length > 0) {
    searchKeys = options.query.searchIn;
  }
  const filter = options.query?.filter;
  let filterEntries;
  let filterPredicate;
  let exactNameFilter;
  if (typeof filter === "function") {
    filterPredicate = filter;
  } else if (filter) {
    const entries = Object.entries(filter);
    const remainingEntries = [];
    for (const [key, matcher] of entries) {
      if (key === "name") {
        if (typeof matcher === "string") {
          exactNameFilter = new Set([matcher]);
          continue;
        }
        if (Array.isArray(matcher)) {
          const names = new Set;
          for (const value of matcher) {
            if (typeof value === "string") {
              names.add(value);
            }
          }
          exactNameFilter = names;
          continue;
        }
      }
      remainingEntries.push([key, matcher]);
    }
    filterEntries = remainingEntries.length > 0 ? remainingEntries : undefined;
  }
  const results = [];
  for (const entry of options.entries) {
    const commandState = entry.commandState;
    if (!commandMatchesNamespace(commandState, namespace)) {
      continue;
    }
    if (!commandMatchesSearch(commandState, normalizedSearch, searchKeys)) {
      continue;
    }
    if (exactNameFilter && !exactNameFilter.has(commandState.command.name)) {
      continue;
    }
    if (!commandMatchesFilters(commandState, filterEntries, options)) {
      continue;
    }
    if (filterPredicate) {
      let matches = false;
      try {
        matches = filterPredicate(options.getCommand(commandState));
      } catch (error) {
        options.onFilterError(error);
        continue;
      }
      if (!matches) {
        continue;
      }
    }
    results.push(entry);
    if (limit !== undefined && results.length >= limit) {
      break;
    }
  }
  return results;
}
function normalizeQueryLimit(value) {
  if (value === undefined) {
    return;
  }
  const limit = Math.floor(Number(value));
  if (!Number.isFinite(limit) || limit <= 0) {
    return 0;
  }
  return limit;
}
function commandMatchesSearch(commandState, search, searchKeys) {
  if (!search) {
    return true;
  }
  for (const key of searchKeys) {
    if (commandKeyMatchesSearch(commandState, key, search)) {
      return true;
    }
  }
  return false;
}
function commandMatchesNamespace(commandState, namespace) {
  if (namespace === undefined) {
    return true;
  }
  const fields = commandState.fields;
  if (!Object.prototype.hasOwnProperty.call(fields, "namespace")) {
    return false;
  }
  return valueMatchesFilter(fields.namespace, namespace);
}
function commandMatchesFilters(commandState, filters, options) {
  if (!filters) {
    return true;
  }
  for (const [key, matcher] of filters) {
    if (!commandKeyMatchesQuery(commandState, key, matcher, options)) {
      return false;
    }
  }
  return true;
}
function commandKeyMatchesSearch(commandState, key, search) {
  return getCommandSearchText(commandState, key)?.includes(search) === true;
}
function getCommandSearchText(commandState, key) {
  let cache = commandSearchCache.get(commandState);
  if (!cache) {
    cache = new Map;
    commandSearchCache.set(commandState, cache);
  }
  if (cache.has(key)) {
    return cache.get(key);
  }
  const fields = commandState.fields;
  const attrs = commandState.attrs;
  let value;
  if (key === "name") {
    value = commandState.command.name;
  } else if (Object.prototype.hasOwnProperty.call(fields, key)) {
    value = fields[key];
  } else if (attrs && Object.prototype.hasOwnProperty.call(attrs, key)) {
    value = attrs[key];
  }
  const text = toSearchText(value);
  cache.set(key, text);
  return text;
}
function toSearchText(value) {
  if (Array.isArray(value)) {
    const parts = [];
    for (const entry of value) {
      const text = toSearchText(entry);
      if (text !== undefined) {
        parts.push(text);
      }
    }
    return parts.length > 0 ? parts.join("\x00") : undefined;
  }
  if (typeof value === "string") {
    return value.toLowerCase();
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return String(value).toLowerCase();
  }
  return;
}
function runCommandQueryPredicate(matcher, value, command, onFilterError) {
  try {
    return matcher(value, command);
  } catch (error) {
    onFilterError(error);
    return false;
  }
}
function commandKeyMatchesQuery(commandState, key, matcher, options) {
  if (typeof matcher === "function") {
    return commandKeyMatchesPredicate(commandState, key, matcher, options);
  }
  return commandKeyMatchesExact(commandState, key, matcher);
}
function commandKeyMatchesPredicate(commandState, key, matcher, options) {
  const command = commandState.command;
  const fields = commandState.fields;
  const attrs = commandState.attrs;
  let commandView;
  let foundValue = false;
  const getCommandView = () => commandView ??= options.getCommand(commandState);
  if (key === "name") {
    foundValue = true;
    if (runCommandQueryPredicate(matcher, command.name, getCommandView(), options.onFilterError)) {
      return true;
    }
  }
  if (Object.prototype.hasOwnProperty.call(fields, key)) {
    foundValue = true;
    if (runCommandQueryPredicate(matcher, fields[key], getCommandView(), options.onFilterError)) {
      return true;
    }
  }
  if (attrs && Object.prototype.hasOwnProperty.call(attrs, key)) {
    foundValue = true;
    if (runCommandQueryPredicate(matcher, attrs[key], getCommandView(), options.onFilterError)) {
      return true;
    }
  }
  return !foundValue && runCommandQueryPredicate(matcher, undefined, getCommandView(), options.onFilterError);
}
function commandKeyMatchesExact(commandState, key, matcher) {
  const command = commandState.command;
  const fields = commandState.fields;
  const attrs = commandState.attrs;
  if (key === "name" && valueMatchesFilter(command.name, matcher)) {
    return true;
  }
  if (Object.prototype.hasOwnProperty.call(fields, key) && valueMatchesFilter(fields[key], matcher)) {
    return true;
  }
  return !!attrs && Object.prototype.hasOwnProperty.call(attrs, key) && valueMatchesFilter(attrs[key], matcher);
}
function valueMatchesFilter(value, matcher) {
  if (Array.isArray(matcher)) {
    return matcher.some((expected) => valueMatchesExact(value, expected));
  }
  return valueMatchesExact(value, matcher);
}
function valueMatchesExact(value, expected) {
  if (Array.isArray(value)) {
    return value.some((entry) => valueMatchesExact(entry, expected));
  }
  return Object.is(value, expected);
}
function createCommandExecutorService(notify, runtime, activation, catalog, options) {
  const createCommandContext = (event, focused, target, data, input, payload) => {
    return {
      keymap: options.keymap,
      event,
      focused,
      target,
      data,
      input,
      payload
    };
  };
  const executeResolvedCommand = (commandName, command, context, includeCommand) => {
    const commandView = typeof command === "function" ? undefined : command;
    const run = typeof command === "function" ? command : command.run;
    const resultCommand = includeCommand ? commandView : undefined;
    let result;
    try {
      result = run(commandView ? { ...context, command: commandView } : context);
    } catch (error) {
      notify.emitError("command-execution-error", error, `[Keymap] Error running command "${commandName}":`);
      return {
        status: "error",
        result: resultCommand ? { ok: false, reason: "error", command: resultCommand } : { ok: false, reason: "error" }
      };
    }
    if (isPromiseLike(result)) {
      result.catch((error) => {
        notify.emitError("async-command-error", error, `[Keymap] Async error in command "${commandName}":`);
      });
      return {
        status: "handled",
        result: resultCommand ? { ok: true, command: resultCommand } : { ok: true }
      };
    }
    if (isRunCommandResult(result)) {
      let commandResult = result;
      if (!result.ok && result.reason !== "not-found" && includeCommand && commandView && !result.command) {
        commandResult = { ...result, command: commandView };
      } else if (result.ok && includeCommand && commandView && !result.command) {
        commandResult = { ...result, command: commandView };
      }
      return {
        status: result.ok ? "handled" : "rejected",
        result: commandResult
      };
    }
    if (result === false) {
      return {
        status: "rejected",
        result: resultCommand ? { ok: false, reason: "rejected", command: resultCommand } : { ok: false, reason: "rejected" }
      };
    }
    return {
      status: "handled",
      result: resultCommand ? { ok: true, command: resultCommand } : { ok: true }
    };
  };
  const executeCommandChain = (commandName, chain, event, focused, target, data, payload, includeCommand) => {
    let rejected;
    for (const entry of chain ?? []) {
      const executed = executeResolvedCommand(commandName, entry.command, createCommandContext(event, focused, target ?? entry.target ?? null, data, commandName, payload), includeCommand);
      if (executed.status === "handled" || executed.status === "error") {
        return [executed.result, rejected];
      }
      rejected = executed.result;
    }
    return [undefined, rejected];
  };
  const executeProgrammaticCommand = (cmd, commandOptions, mode) => {
    let normalized;
    try {
      normalized = normalizeBindingCommand(cmd);
    } catch {
      return { ok: false, reason: "invalid-args" };
    }
    if (typeof normalized !== "string") {
      return { ok: false, reason: "not-found" };
    }
    const includeCommand = commandOptions?.includeCommand === true;
    const focused = commandOptions?.focused ?? activation.getFocusedTargetIfAvailable();
    const event = commandOptions?.event ?? options.createCommandEvent();
    const data = runtime.getReadonlyData();
    const payload = commandOptions?.payload;
    const chain = mode === "registered" ? catalog.getRegisteredResolvedEntries(normalized) : catalog.getActiveRegisteredResolvedEntries(normalized, focused);
    const [done, rejected] = executeCommandChain(normalized, chain, event, focused, commandOptions?.target, data, payload, includeCommand);
    if (done) {
      return done;
    }
    let rejectedResult = rejected;
    const fallback = mode === "registered" ? catalog.resolveRegisteredResolverFallback(normalized, { input: normalized, payload }) : catalog.resolveActiveResolverFallback(normalized, focused, { input: normalized, payload });
    if (fallback.resolved) {
      const result = executeResolvedCommand(normalized, fallback.resolved.command, createCommandContext(event, focused, commandOptions?.target ?? fallback.resolved.target ?? null, data, fallback.resolved.input ?? normalized, fallback.resolved.payload), includeCommand);
      if (result.status === "handled" || result.status === "error") {
        return result.result;
      }
      rejectedResult = result.result;
    }
    if (fallback.hadError) {
      return { ok: false, reason: "error" };
    }
    if (mode === "active") {
      const unavailable = catalog.getDispatchUnavailableCommandState(normalized, focused, includeCommand);
      if (unavailable) {
        return unavailable.command ? { ok: false, reason: unavailable.reason, command: unavailable.command } : { ok: false, reason: unavailable.reason };
      }
    }
    return rejectedResult ?? { ok: false, reason: "not-found" };
  };
  return {
    runCommand(cmd, commandOptions) {
      return executeProgrammaticCommand(cmd, commandOptions, "registered");
    },
    dispatchCommand(cmd, commandOptions) {
      return executeProgrammaticCommand(cmd, commandOptions, "active");
    },
    runBinding(bindingLayer, binding, event, focused, payload) {
      const data = runtime.getReadonlyData();
      if (binding.run) {
        const result = executeResolvedCommand(typeof binding.command === "string" ? binding.command : "<function>", binding.run, createCommandContext(event, focused, bindingLayer.target ?? null, data, typeof binding.command === "string" ? binding.command : "<function>", payload), false);
        if (result.status === "rejected") {
          return false;
        }
        applyBindingEventEffects(binding, event);
        return true;
      }
      if (typeof binding.command !== "string") {
        return false;
      }
      const chain = catalog.getResolvedCommandChain(binding.command, focused, payload === undefined ? undefined : { input: binding.command, payload }).entries;
      for (const entry of chain ?? []) {
        const result = executeResolvedCommand(binding.command, entry.command, createCommandContext(event, focused, entry.target ?? bindingLayer.target ?? null, data, entry.input ?? binding.command, entry.payload), false);
        if (result.status === "rejected") {
          continue;
        }
        applyBindingEventEffects(binding, event);
        return true;
      }
      return false;
    }
  };
}
function isRunCommandResult(value) {
  return typeof value === "object" && value !== null && "ok" in value;
}
function applyBindingEventEffects(binding, event) {
  if (!binding.preventDefault) {
    return;
  }
  event.preventDefault();
  event.stopPropagation();
}
function snapshotAttributes(attrs) {
  if (Object.keys(attrs).length === 0) {
    return;
  }
  return snapshotDataValue(attrs, { freeze: true });
}
function createCompilerService(state, notify, conditions, options) {
  const parseTokenKey = (key) => {
    return parseSingleKeyPartWithParsers(key, state.bindingParsers.values(), {
      tokens: state.tokens,
      patterns: state.patterns,
      layer: EMPTY_COMPILE_FIELDS,
      parseObjectKey: (value, options2) => parseObjectKeyPart(value, options2)
    });
  };
  const parseKeySequence = (key) => {
    if (typeof key !== "string") {
      return [parseObjectKeyPart(key)];
    }
    const parsed = parseBindingSequenceWithParsers(key, state.bindingParsers.values(), {
      tokens: state.tokens,
      patterns: state.patterns,
      layer: EMPTY_COMPILE_FIELDS,
      parseObjectKey: (value, options2) => parseObjectKeyPart(value, options2)
    });
    for (const tokenName of parsed.unknownTokens) {
      options.warnUnknownToken(tokenName, key);
    }
    if (parsed.unknownTokens.length > 0) {
      return [];
    }
    return parsed.parts;
  };
  const formatKey = (key, options2) => {
    return stringifyKeySequence(parseKeySequence(key), options2);
  };
  const compileBindings = (bindings, tokens, sourceTarget, sourceLayerOrder, compileFields) => {
    const bindingStates = [];
    let hasTokenBindings = false;
    const bindingExpanders = state.bindingExpanders.values();
    const bindingParsers = state.bindingParsers.values();
    const bindingFieldCompilers = state.bindingFields;
    const allowExactPrefixAmbiguity = state.disambiguationResolvers.has();
    const warnUnknownField = options.warnUnknownField;
    const warnUnknownToken = options.warnUnknownToken;
    for (const [bindingIndex, binding] of bindings.entries()) {
      let expandedBindingKeys;
      try {
        expandedBindingKeys = expandBindingKeyWithExpanders(binding.key, bindingExpanders, {
          layer: compileFields
        });
      } catch (error) {
        notify.emitError("binding-expand-error", error, getErrorMessage(error, "Failed to expand keymap binding"));
        continue;
      }
      for (const expandedBindingKey of expandedBindingKeys) {
        const expandedKey = expandedBindingKey.key;
        let parsed;
        try {
          parsed = typeof expandedKey === "string" ? parseBindingSequenceWithParsers(expandedKey, bindingParsers, {
            tokens,
            patterns: state.patterns,
            layer: compileFields,
            parseObjectKey: (value, options2) => parseObjectKeyPart(value, options2)
          }) : {
            parts: [parseObjectKeyPart(expandedKey)],
            usedTokens: [],
            unknownTokens: [],
            hasTokenBindings: false
          };
          parsed = applyExpansionDisplays(parsed, expandedBindingKey);
        } catch (error) {
          notify.emitError("binding-parse-error", error, getErrorMessage(error, "Failed to parse keymap binding"));
          continue;
        }
        const sequence = parsed.parts;
        hasTokenBindings ||= parsed.hasTokenBindings;
        for (const tokenName of parsed.unknownTokens) {
          warnUnknownToken(tokenName, typeof expandedKey === "string" ? expandedKey : String(expandedKey.name));
        }
        if (parsed.unknownTokens.length > 0) {
          continue;
        }
        for (const compiledInput of applyBindingTransformers(binding, sequence, tokens, bindingParsers, compileFields)) {
          try {
            const event = normalizeBindingEvent(compiledInput.event);
            const compiledSequence = compiledInput.sequence;
            const mergedRequires = {};
            const mergedAttrs = {};
            const matchers = [];
            for (const fieldName in compiledInput) {
              if (fieldName === "sequence") {
                continue;
              }
              if (RESERVED_BINDING_FIELDS.has(fieldName)) {
                continue;
              }
              const value = compiledInput[fieldName];
              if (value === undefined) {
                continue;
              }
              const compiler = bindingFieldCompilers.get(fieldName);
              if (!compiler) {
                warnUnknownField("binding", fieldName);
                continue;
              }
              compiler(value, createFieldCompilerContext({
                fieldName,
                conditions,
                requirements: mergedRequires,
                matchers,
                attrs: mergedAttrs
              }));
            }
            const attrs = Object.keys(mergedAttrs).length > 0 ? snapshotAttributes(mergedAttrs) : undefined;
            const command = normalizeBindingCommand(compiledInput.cmd);
            const compiledBinding = {
              binding,
              sequence: compiledSequence,
              command,
              event,
              parsedBinding: snapshotParsedBinding(compiledInput),
              sourceTarget,
              sourceLayerOrder,
              bindingIndex,
              requires: Object.keys(mergedRequires).length > 0 ? Object.entries(mergedRequires) : EMPTY_REQUIRES,
              matchers: matchers.length > 0 ? matchers : EMPTY_MATCHERS,
              preventDefault: compiledInput.preventDefault !== false,
              fallthrough: compiledInput.fallthrough ?? false
            };
            if (attrs) {
              compiledBinding.attrs = attrs;
            }
            if (typeof command === "function") {
              compiledBinding.run = command;
            }
            if (compiledSequence.length === 0) {
              continue;
            }
            if (event === "release" && compiledSequence.length > 1) {
              throw new Error("Keymap release bindings only support a single key stroke");
            }
            const terminalPattern = compiledSequence.at(-1);
            if (terminalPattern?.patternName) {
              const pattern = state.patterns.get(terminalPattern.patternName);
              if (pattern && pattern.max !== pattern.min) {
                throw new Error("Keymap unbounded sequence patterns must be followed by a concrete continuation");
              }
            }
            if (event === "press" && !allowExactPrefixAmbiguity) {
              validateExactPrefixAmbiguity(bindingStates, compiledBinding);
            }
            bindingStates.push(compiledBinding);
          } catch (error) {
            notify.emitError("binding-compile-error", error, getErrorMessage(error, "Failed to compile keymap binding"));
          }
        }
      }
    }
    return {
      bindings: bindingStates,
      hasTokenBindings
    };
  };
  const parseObjectKeyPart = (key, options2) => {
    return createKeySequencePart(key, options2);
  };
  const normalizeBindingEvent = (event) => {
    if (event === undefined || event === "press") {
      return "press";
    }
    if (event === "release") {
      return "release";
    }
    throw new Error(`Invalid keymap binding event "${String(event)}": expected "press" or "release"`);
  };
  const applyBindingTransformers = (binding, sequence, tokens, bindingParsers, compileFields) => {
    const bindingTransformers = state.bindingTransformers.values();
    if (bindingTransformers.length === 0) {
      return [{ ...binding, sequence: cloneKeySequence(sequence) }];
    }
    const parsedBinding = {
      ...binding,
      sequence: cloneKeySequence(sequence)
    };
    const extraBindings = [];
    let keepOriginal = true;
    const layer = compileFields ?? EMPTY_COMPILE_FIELDS;
    for (const transformer of bindingTransformers) {
      try {
        transformer(parsedBinding, {
          layer,
          parseKey: (key) => {
            return parseSingleKeyPartWithParsers(key, bindingParsers, {
              tokens,
              patterns: state.patterns,
              layer,
              parseObjectKey: (value, options2) => parseObjectKeyPart(value, options2)
            });
          },
          add: (nextBinding) => {
            extraBindings.push(snapshotParsedBinding(nextBinding));
          },
          skipOriginal: () => {
            keepOriginal = false;
          }
        });
      } catch (error) {
        notify.emitError("binding-transformer-error", error, "[Keymap] Error in binding transformer:");
      }
    }
    if (!keepOriginal) {
      return extraBindings;
    }
    if (extraBindings.length === 0) {
      return [parsedBinding];
    }
    return [parsedBinding, ...extraBindings];
  };
  return { parseTokenKey, parseKeySequence, formatKey, compileBindings };
}
function sequenceMatchesPrefix(left, right) {
  if (left.length >= right.length) {
    return false;
  }
  for (let index = 0;index < left.length; index += 1) {
    if (left[index]?.match !== right[index]?.match) {
      return false;
    }
  }
  return true;
}
function validateExactPrefixAmbiguity(bindings, next) {
  for (const existing of bindings) {
    if (existing.event !== "press") {
      continue;
    }
    if (existing.command !== undefined && sequenceMatchesPrefix(existing.sequence, next.sequence) || next.command !== undefined && sequenceMatchesPrefix(next.sequence, existing.sequence)) {
      throw new Error("Keymap bindings cannot use the same sequence as both an exact match and a prefix in the same layer");
    }
  }
}
function expandBindingKeyWithExpanders(key, expanders, options) {
  if (typeof key !== "string" || expanders.length === 0) {
    return [{ key }];
  }
  const layer = options?.layer ?? EMPTY_COMPILE_FIELDS;
  let candidates = [{ key }];
  for (const expander of expanders) {
    const nextCandidates = [];
    for (const candidate of candidates) {
      const result = expander({
        input: candidate.key,
        displays: candidate.displays,
        layer
      });
      if (!result) {
        nextCandidates.push(candidate);
        continue;
      }
      if (result.length === 0) {
        throw new Error(`Keymap binding expander must return at least one key sequence for "${candidate.key}"`);
      }
      for (const expanded of result) {
        if (!expanded || typeof expanded !== "object" || Array.isArray(expanded) || typeof expanded.key !== "string") {
          throw new Error(`Keymap binding expander must return expansion objects with string keys for "${candidate.key}"`);
        }
        if (expanded.displays !== undefined) {
          if (!Array.isArray(expanded.displays)) {
            throw new Error(`Keymap binding expander displays must be an array of strings for "${candidate.key}"`);
          }
          for (const display of expanded.displays) {
            if (typeof display !== "string") {
              throw new Error(`Keymap binding expander displays must be an array of strings for "${candidate.key}"`);
            }
          }
        }
        nextCandidates.push(expanded);
      }
    }
    candidates = nextCandidates;
  }
  return candidates;
}
function applyExpansionDisplays(parsed, expansion) {
  if (!expansion.displays) {
    return parsed;
  }
  if (expansion.displays.length !== parsed.parts.length) {
    throw new Error(`Keymap binding expansion displays length must match parsed sequence length for "${String(expansion.key)}"`);
  }
  return {
    ...parsed,
    parts: parsed.parts.map((part, index) => ({
      ...part,
      display: expansion.displays[index]
    }))
  };
}
function parseBindingSequenceWithParsers(key, parsers, options) {
  if (key.length === 0) {
    throw new Error("Invalid key sequence: sequence cannot be empty");
  }
  if (parsers.length === 0) {
    throw new Error("No keymap binding parsers are registered");
  }
  const tokens = options.tokens ?? new Map;
  const patterns = options.patterns ?? new Map;
  const layer = options.layer ?? EMPTY_COMPILE_FIELDS;
  const parseObjectKey = options.parseObjectKey;
  const parts = [];
  const usedTokens = new Set;
  const unknownTokens = new Set;
  let index = 0;
  while (index < key.length) {
    let matched = false;
    for (const parser of parsers) {
      const result = parser({
        input: key,
        index,
        layer,
        tokens,
        patterns,
        normalizeTokenName: normalizeBindingTokenName,
        createMatch: createTextKeyMatch,
        parseObjectKey
      });
      if (!result) {
        continue;
      }
      if (result.nextIndex <= index || result.nextIndex > key.length) {
        throw new Error(`Keymap binding parser must advance the input for "${key}" at index ${index}`);
      }
      parts.push(...result.parts);
      for (const tokenName of result.usedTokens ?? []) {
        usedTokens.add(tokenName);
      }
      for (const tokenName of result.unknownTokens ?? []) {
        unknownTokens.add(tokenName);
      }
      index = result.nextIndex;
      matched = true;
      break;
    }
    if (!matched) {
      throw new Error(`No keymap binding parser handled input at index ${index} in "${key}"`);
    }
  }
  return {
    parts,
    usedTokens: [...usedTokens],
    unknownTokens: [...unknownTokens],
    hasTokenBindings: usedTokens.size > 0 || unknownTokens.size > 0
  };
}
function parseSingleKeyPartWithParsers(key, parsers, options) {
  if (typeof key !== "string") {
    return options.parseObjectKey(key);
  }
  const { parts } = parseBindingSequenceWithParsers(key, parsers, options);
  const [part] = parts;
  if (!part || parts.length !== 1) {
    throw new Error(`Invalid key "${String(key)}": expected a single key stroke`);
  }
  return part;
}
function isReactiveMatcher(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  const candidate = value;
  return typeof candidate.get === "function" && typeof candidate.subscribe === "function";
}
function createConditionService(state, notify) {
  const hasNoConditions = (target) => {
    return target.requires.length === 0 && target.matchers.length === 0;
  };
  const matchesRuntimeMatcher = (matcher) => {
    try {
      return matcher.match();
    } catch (error) {
      notify.emitError("runtime-matcher-error", error, `[Keymap] Error evaluating runtime matcher from ${matcher.source}:`);
      return false;
    }
  };
  const matchesRuntimeMatchers = (target) => {
    if (target.matchers.length === 0) {
      return true;
    }
    if (target.matchers.length === 1) {
      const [matcher] = target.matchers;
      return matcher ? matchesRuntimeMatcher(matcher) : true;
    }
    for (const matcher of target.matchers) {
      if (!matchesRuntimeMatcher(matcher)) {
        return false;
      }
    }
    return true;
  };
  const matchRequirements = (requires) => {
    if (requires.length === 0) {
      return true;
    }
    for (const [name, value] of requires) {
      if (!Object.is(state.data[name], value)) {
        return false;
      }
    }
    return true;
  };
  const matchesConditions = (target) => {
    return hasNoConditions(target) || matchRequirements(target.requires) && matchesRuntimeMatchers(target);
  };
  return {
    buildRuntimeMatcher(matcher, source) {
      if (typeof matcher === "function") {
        return { source, match: matcher };
      }
      if (isReactiveMatcher(matcher)) {
        return {
          source,
          match: () => matcher.get(),
          subscribe: (onChange) => matcher.subscribe(onChange)
        };
      }
      throw new Error(`Keymap ${source} expected a function or a reactive matcher`);
    },
    matchesConditions
  };
}
function createSyncDecision(action, handler) {
  return {
    [KEY_DISAMBIGUATION_DECISION]: true,
    action,
    handler
  };
}
function createDeferredDecision(action) {
  return {
    [KEY_DEFERRED_DISAMBIGUATION_DECISION]: true,
    action
  };
}
function isSyncDecision(value) {
  return !!value && typeof value === "object" && value[KEY_DISAMBIGUATION_DECISION] === true;
}
function isDeferredDecision(value) {
  return !!value && typeof value === "object" && value[KEY_DEFERRED_DISAMBIGUATION_DECISION] === true;
}
function sleepWithSignal(ms, signal) {
  if (signal.aborted) {
    return Promise.resolve(false);
  }
  return new Promise((resolve) => {
    const timeout = setTimeout(() => {
      signal.removeEventListener("abort", onAbort);
      resolve(true);
    }, Math.max(0, ms));
    const onAbort = () => {
      clearTimeout(timeout);
      signal.removeEventListener("abort", onAbort);
      resolve(false);
    };
    signal.addEventListener("abort", onAbort, { once: true });
  });
}
function matchSequencePattern(patterns, notify, patternName, event) {
  const pattern = patterns.get(patternName);
  if (!pattern) {
    return;
  }
  try {
    return pattern.matcher(event);
  } catch (error) {
    notify.emitError("sequence-pattern-match-error", error, `[Keymap] Error matching sequence pattern "${pattern.name}":`);
    return;
  }
}
function createPatternEventPart(patterns, event, patternName, match) {
  const pattern = patterns.get(patternName);
  const payloadKey = pattern?.payloadKey ?? patternName;
  const part = createKeySequencePart({
    name: event.name,
    ctrl: event.ctrl,
    shift: event.shift,
    meta: event.meta,
    super: event.super ?? false,
    hyper: event.hyper || undefined
  }, { display: match.display ?? String(match.value ?? event.name) });
  return { ...part, patternName, payloadKey };
}
function createSequencePayload(patterns, notify, capture) {
  if (!capture?.patterns || capture.patterns.length === 0) {
    return;
  }
  const payload = {};
  let hasPayload = false;
  for (const captured of capture.patterns) {
    const pattern = patterns.get(captured.name);
    let value;
    try {
      value = pattern?.finalize ? pattern.finalize(captured.values) : captured.values.length === 1 ? captured.values[0] : [...captured.values];
    } catch (error) {
      notify.emitError("sequence-pattern-finalize-error", error, `[Keymap] Error finalizing sequence pattern "${captured.name}":`);
      continue;
    }
    const existing = payload[captured.payloadKey];
    if (existing === undefined) {
      payload[captured.payloadKey] = value;
      hasPayload = true;
    } else if (Array.isArray(existing)) {
      existing.push(value);
    } else {
      payload[captured.payloadKey] = [existing, value];
    }
  }
  return hasPayload ? payload : undefined;
}
function createDispatchService(state, notify, runtime, activation, conditions, executor, compiler, catalog, layers, hooks) {
  const eventMatchResolverContext = {
    resolveKey: (key) => compiler.parseTokenKey(key).match
  };
  let pendingDisambiguation = null;
  let nextPendingDisambiguationId = 0;
  function intercept(name, fn, options) {
    if (name === "key") {
      const keyOptions = options;
      return state.keyHooks.register(fn, {
        priority: keyOptions?.priority ?? 0,
        release: keyOptions?.release ?? false
      });
    }
    if (name === "key:after") {
      const keyOptions = options;
      return state.keyAfterHooks.register(fn, {
        priority: keyOptions?.priority ?? 0,
        release: keyOptions?.release ?? false
      });
    }
    const rawOptions = options;
    return state.rawHooks.register(fn, {
      priority: rawOptions?.priority ?? 0
    });
  }
  function prependEventMatchResolver(resolver) {
    return state.eventMatchResolvers.prepend(resolver);
  }
  function appendEventMatchResolver(resolver) {
    return state.eventMatchResolvers.append(resolver);
  }
  function clearEventMatchResolvers() {
    state.eventMatchResolvers.clear();
  }
  function prependDisambiguationResolver(resolver) {
    return mutateDisambiguationResolvers(() => state.disambiguationResolvers.prepend(resolver), resolver);
  }
  function appendDisambiguationResolver(resolver) {
    return mutateDisambiguationResolvers(() => state.disambiguationResolvers.append(resolver), resolver);
  }
  function clearDisambiguationResolvers() {
    if (!state.disambiguationResolvers.has()) {
      return;
    }
    notify.runWithStateChangeBatch(() => {
      state.disambiguationResolvers.clear();
      layers.recompileBindings();
    });
  }
  function handlePendingSequenceChange(_previous, _next) {
    if (!pendingDisambiguation) {
      return;
    }
    cancelPendingDisambiguation();
  }
  function handleRawSequence(sequence) {
    const hooks2 = state.rawHooks.entries();
    if (hooks2.length === 0) {
      return false;
    }
    let stopped = false;
    const context = {
      sequence,
      stop() {
        stopped = true;
      }
    };
    for (const hook of hooks2) {
      try {
        hook.listener(context);
      } catch (error) {
        notify.emitError("raw-intercept-error", error, "[Keymap] Error in raw intercept listener:");
      }
      if (stopped) {
        return true;
      }
    }
    return false;
  }
  function createDispatchBinding(binding, focused) {
    return {
      sequence: cloneKeySequence(binding.sequence),
      command: binding.command,
      commandAttrs: catalog.getBindingCommandAttrs(binding, focused, catalog.getActiveCommandView(focused)),
      attrs: binding.attrs,
      event: binding.event,
      preventDefault: binding.preventDefault,
      fallthrough: binding.fallthrough,
      sourceLayerOrder: binding.sourceLayerOrder,
      bindingIndex: binding.bindingIndex
    };
  }
  function emitDispatchEvent(event) {
    if (!hooks.has("dispatch")) {
      return;
    }
    hooks.emit("dispatch", event);
  }
  function emitBindingDispatch(phase, layer, binding, focused) {
    if (!hooks.has("dispatch")) {
      return;
    }
    emitDispatchEvent({
      phase,
      event: binding.event,
      focused,
      layer: {
        order: layer.order,
        priority: layer.priority,
        target: layer.target,
        targetMode: layer.targetMode
      },
      binding: createDispatchBinding(binding, focused),
      sequence: cloneKeySequence(binding.sequence),
      command: binding.command
    });
  }
  function emitSequenceDispatch(phase, captures, focused) {
    if (!hooks.has("dispatch")) {
      return;
    }
    const first = captures[0];
    const sequence = captures.length > 0 ? activation.collectSequencePartsFromPending({ captures }) : [];
    emitDispatchEvent({
      phase,
      event: "press",
      focused,
      layer: first ? {
        order: first.layer.order,
        priority: first.layer.priority,
        target: first.layer.target,
        targetMode: first.layer.targetMode
      } : undefined,
      sequence
    });
  }
  function getKeyAfterHooks(release) {
    const hooks2 = state.keyAfterHooks.entries();
    for (const hook of hooks2) {
      if (hook.release === release) {
        return hooks2;
      }
    }
    return;
  }
  function getOutcomeSequence(outcome) {
    if (outcome.sequence) {
      return cloneKeySequence(outcome.sequence);
    }
    if (outcome.captures) {
      return activation.collectSequencePartsFromPending({ captures: outcome.captures });
    }
    return [];
  }
  function createSequenceOutcome(reason, captures) {
    return {
      handled: reason !== "sequence-miss",
      reason,
      captures
    };
  }
  function createBindingOutcome(binding, handled) {
    return {
      handled,
      reason: handled ? "binding-handled" : "binding-rejected",
      sequence: binding.sequence
    };
  }
  function preferDispatchOutcome(current, next) {
    if (next.handled || current.reason === "no-match") {
      return next;
    }
    return current;
  }
  function emitKeyAfter(hooks2, event, release, focused, outcome) {
    const context = {
      event,
      eventType: release ? "release" : "press",
      focused,
      handled: outcome.handled,
      reason: outcome.reason,
      sequence: getOutcomeSequence(outcome),
      pendingSequence: activation.getPendingSequence(),
      setData: (name, value) => {
        runtime.setData(name, value);
      },
      getData: (name) => {
        return runtime.getData(name);
      },
      consume: (options) => {
        const shouldPreventDefault = options?.preventDefault ?? true;
        const shouldStopPropagation = options?.stopPropagation ?? true;
        if (shouldPreventDefault) {
          event.preventDefault();
        }
        if (shouldStopPropagation) {
          event.stopPropagation();
        }
      }
    };
    for (const hook of hooks2) {
      if (hook.release !== release) {
        continue;
      }
      try {
        hook.listener(context);
      } catch (error) {
        notify.emitError("key-after-intercept-error", error, "[Keymap] Error in key:after intercept listener:");
      }
    }
  }
  function noMatchOutcome() {
    return { handled: false, reason: "no-match" };
  }
  function consumeSequenceEvent(event) {
    event.preventDefault();
    event.stopPropagation();
  }
  function holdSequence(phase, captures, focused, event) {
    activation.setPendingSequence({ captures });
    const outcome = createSequenceOutcome("sequence-pending", captures);
    emitSequenceDispatch(phase, captures, focused);
    consumeSequenceEvent(event);
    return outcome;
  }
  function clearSequence(reason, captures, focused, event) {
    const outcome = createSequenceOutcome(reason, captures);
    emitSequenceDispatch("sequence-clear", captures, focused);
    activation.setPendingSequence(null);
    consumeSequenceEvent(event);
    return outcome;
  }
  function handleKeyEvent(event, release) {
    if (!release) {
      cancelPendingDisambiguation();
    }
    const afterHooks = getKeyAfterHooks(release);
    const afterFocused = afterHooks ? activation.getFocusedTarget() : null;
    const hooks2 = state.keyHooks.entries();
    const context = {
      event,
      setData: (name, value) => {
        runtime.setData(name, value);
      },
      getData: (name) => {
        return runtime.getData(name);
      },
      consume: (options) => {
        const shouldPreventDefault = options?.preventDefault ?? true;
        const shouldStopPropagation = options?.stopPropagation ?? true;
        if (shouldPreventDefault) {
          event.preventDefault();
        }
        if (shouldStopPropagation) {
          event.stopPropagation();
        }
      }
    };
    for (const hook of hooks2) {
      if (hook.release !== release) {
        continue;
      }
      try {
        hook.listener(context);
      } catch (error) {
        notify.emitError("key-intercept-error", error, "[Keymap] Error in key intercept listener:");
      }
      if (event.propagationStopped) {
        if (afterHooks) {
          emitKeyAfter(afterHooks, event, release, afterFocused, {
            handled: true,
            reason: "intercept-consumed",
            sequence: []
          });
        }
        return;
      }
    }
    if (release) {
      const outcome2 = dispatchReleaseLayers(event);
      if (afterHooks) {
        emitKeyAfter(afterHooks, event, release, afterFocused, outcome2);
      }
      return;
    }
    const outcome = dispatchLayers(event);
    if (afterHooks) {
      emitKeyAfter(afterHooks, event, release, afterFocused, outcome);
    }
  }
  function mutateDisambiguationResolvers(register, resolver) {
    return notify.runWithStateChangeBatch(() => {
      const hadResolvers = state.disambiguationResolvers.has();
      const off = register();
      if (!hadResolvers && state.disambiguationResolvers.has()) {
        layers.recompileBindings();
      }
      return () => {
        notify.runWithStateChangeBatch(() => {
          const hadBeforeRemoval = state.disambiguationResolvers.has();
          off();
          if (state.disambiguationResolvers.values().includes(resolver)) {
            return;
          }
          if (hadBeforeRemoval && !state.disambiguationResolvers.has()) {
            layers.recompileBindings();
          }
        });
      };
    });
  }
  function dispatchReleaseLayers(event) {
    const focused = activation.getFocusedTarget();
    const activeLayers = activation.getActiveLayers(focused);
    const matchKeys = resolveEventMatchKeys(event);
    let outcome = noMatchOutcome();
    for (const strokeKey of matchKeys) {
      layerLoop:
        for (const layer of activeLayers) {
          if (layer.bindings.length === 0) {
            continue;
          }
          if (!conditions.matchesConditions(layer)) {
            continue;
          }
          const result = runReleaseBindings(layer, strokeKey, event, focused);
          outcome = preferDispatchOutcome(outcome, result.outcome);
          if (!result.handled) {
            continue;
          }
          if (result.stop) {
            return outcome;
          }
          continue layerLoop;
        }
    }
    return outcome;
  }
  function dispatchLayers(event) {
    const focused = activation.getFocusedTarget();
    const pending = activation.ensureValidPendingSequence();
    const matchKeys = resolveEventMatchKeys(event);
    if (pending) {
      return dispatchPendingSequence(pending, matchKeys, event, focused);
    }
    const activeLayers = activation.getActiveLayers(focused);
    let outcome = noMatchOutcome();
    for (const matchKey of matchKeys) {
      const result = dispatchFromRoot(activeLayers, [matchKey], event, focused);
      outcome = preferDispatchOutcome(outcome, result);
      if (result.handled) {
        return outcome;
      }
    }
    return outcome;
  }
  function dispatchPendingSequence(pending, matchKeys, event, focused) {
    const activeView = catalog.getActiveCommandView(focused);
    const advancedCaptures = [];
    for (const capture of pending.captures) {
      const advanced = advanceSequenceCapture(capture, matchKeys, event, state.patterns, matchPattern, createPatternEventPart2);
      if (!advanced) {
        continue;
      }
      advancedCaptures.push(advanced);
    }
    const bestPriority = advancedCaptures.reduce((best, capture) => Math.min(best, capturePriority(capture, matchKeys)), Number.POSITIVE_INFINITY);
    const prioritizedCaptures = advancedCaptures.filter((capture) => capturePriority(capture, matchKeys) === bestPriority);
    if (prioritizedCaptures.length === 0 || !prioritizedCaptures.some((capture) => captureIsReachable(capture, focused, activeView))) {
      const outcome = createSequenceOutcome("sequence-miss", pending.captures);
      emitSequenceDispatch("sequence-clear", pending.captures, focused);
      activation.setPendingSequence(null);
      return outcome;
    }
    return dispatchPendingCapturesFromIndex(prioritizedCaptures, 0, false, event, focused);
  }
  function dispatchPendingCapturesFromIndex(advancedCaptures, startIndex, handledExact, event, focused) {
    let hasHandledExact = handledExact;
    let outcome = noMatchOutcome();
    const processedExact = new Set;
    for (let index = startIndex;index < advancedCaptures.length; index += 1) {
      const capture = advancedCaptures[index];
      if (!capture || processedExact.has(capture)) {
        continue;
      }
      const continuationCapturesForPrefix = collectContinuationCapturesForPrefix(advancedCaptures, index, capture);
      if (continuationCapturesForPrefix.length > 0) {
        if (hasHandledExact) {
          continue;
        }
        const exactCaptures2 = collectExactCapturesForPrefix(advancedCaptures, capture);
        const resolvedOutcome = tryResolvePendingAmbiguity(advancedCaptures, index, continuationCapturesForPrefix, exactCaptures2, event, focused, hasHandledExact);
        if (resolvedOutcome) {
          return resolvedOutcome;
        }
        return holdSequence("sequence-advance", continuationCapturesForPrefix, focused, event);
      }
      if (!captureIsExact(capture, state.patterns)) {
        continue;
      }
      const exactCaptures = collectExactCapturesForPrefix(advancedCaptures, capture);
      for (const exact of exactCaptures)
        processedExact.add(exact);
      const result = runCaptureBindings(capture.layer, exactCaptures, event, focused);
      outcome = preferDispatchOutcome(outcome, result.outcome);
      if (!result.handled) {
        continue;
      }
      hasHandledExact = true;
      if (result.stop) {
        emitSequenceDispatch("sequence-clear", advancedCaptures, focused);
        activation.setPendingSequence(null);
        return outcome;
      }
    }
    emitSequenceDispatch("sequence-clear", advancedCaptures, focused);
    activation.setPendingSequence(null);
    return outcome;
  }
  function dispatchFromRoot(activeLayers, matchKeys, event, focused) {
    return dispatchFromRootAtIndex(activeLayers, 0, matchKeys, event, focused);
  }
  function dispatchFromRootAtIndex(activeLayers, startIndex, matchKeys, event, focused) {
    const activeView = catalog.getActiveCommandView(focused);
    let outcome = noMatchOutcome();
    for (let index = startIndex;index < activeLayers.length; index += 1) {
      const layer = activeLayers[index];
      if (!layer) {
        continue;
      }
      if (!conditions.matchesConditions(layer)) {
        continue;
      }
      const captures = collectRootCaptures(layer, matchKeys, event, focused, activeView);
      if (captures.length === 0) {
        continue;
      }
      const layerContinuationCaptures = captures.filter((capture) => captureHasContinuations(capture, state.patterns, false));
      if (layerContinuationCaptures.length > 0) {
        const exactCaptures2 = captures.filter((capture) => captureIsExact(capture, state.patterns));
        const continuationCaptures = collectPendingCapturesFromRoot(activeLayers, index, matchKeys, event, focused);
        const resolvedOutcome = tryResolveRootAmbiguity(activeLayers, index, matchKeys, continuationCaptures, exactCaptures2, event, focused);
        if (resolvedOutcome) {
          return resolvedOutcome;
        }
        return holdSequence("sequence-start", continuationCaptures, focused, event);
      }
      const exactCaptures = captures.filter((capture) => captureIsExact(capture, state.patterns));
      const result = runCaptureBindings(layer, exactCaptures, event, focused);
      outcome = preferDispatchOutcome(outcome, result.outcome);
      if (!result.handled) {
        continue;
      }
      if (result.stop) {
        return outcome;
      }
    }
    return outcome;
  }
  function tryResolveRootAmbiguity(activeLayers, layerIndex, matchKeys, continuationCaptures, exactCaptures, event, focused) {
    const applyExact = () => {
      activation.setPendingSequence(null);
      const layer = exactCaptures[0]?.layer;
      if (!layer)
        return noMatchOutcome();
      const result = runCaptureBindings(layer, exactCaptures, event, focused);
      if (!result.stop) {
        return preferDispatchOutcome(result.outcome, dispatchFromRootAtIndex(activeLayers, layerIndex + 1, matchKeys, event, focused));
      }
      return result.outcome;
    };
    return tryResolveAmbiguity({
      event,
      focused,
      continuationCaptures,
      exactBindingsSource: exactCaptures.map((capture) => capture.binding),
      sequencePhase: "sequence-start",
      runExact: applyExact
    });
  }
  function tryResolvePendingAmbiguity(advancedCaptures, captureIndex, continuationCaptures, exactCaptures, event, focused, handledExact) {
    const applyExact = () => {
      activation.setPendingSequence(null);
      const layer = exactCaptures[0]?.layer;
      if (!layer)
        return noMatchOutcome();
      const result = runCaptureBindings(layer, exactCaptures, event, focused);
      if (result.stop) {
        return result.outcome;
      }
      return preferDispatchOutcome(result.outcome, dispatchPendingCapturesFromIndex(advancedCaptures, captureIndex + 1, handledExact || result.handled, event, focused));
    };
    return tryResolveAmbiguity({
      event,
      focused,
      continuationCaptures,
      exactBindingsSource: exactCaptures.map((capture) => capture.binding),
      sequencePhase: "sequence-advance",
      runExact: applyExact
    });
  }
  function tryResolveAmbiguity(options) {
    const { event, focused, continuationCaptures, exactBindingsSource, sequencePhase, runExact } = options;
    if (!state.disambiguationResolvers.has() || continuationCaptures.length === 0) {
      return;
    }
    const activeView = catalog.getActiveCommandView(focused);
    const exactBindings = activation.collectMatchingBindings(exactBindingsSource, focused, activeView);
    if (!exactBindings.some((binding) => binding.command !== undefined)) {
      return;
    }
    const continueSequence = () => {
      return holdSequence(sequencePhase, continuationCaptures, focused, event);
    };
    const clear = () => {
      return clearSequence("sequence-cleared", continuationCaptures, focused, event);
    };
    let sequence;
    const getSequence = () => {
      sequence ??= activation.collectSequencePartsFromPending({ captures: continuationCaptures });
      return sequence;
    };
    const decision = resolveDisambiguation({
      event,
      focused,
      getSequence,
      exactBindings,
      continuationCaptures,
      activeView
    });
    if (!decision) {
      warnUnresolvedAmbiguity(getSequence());
      return continueSequence();
    }
    return applySyncDecision(decision, continuationCaptures, runExact, continueSequence, clear, focused, getSequence);
  }
  function applySyncDecision(decision, continuationCaptures, runExact, continueSequence, clear, focused, getSequence) {
    if (decision.action === "run-exact") {
      return runExact();
    }
    if (decision.action === "continue-sequence") {
      return continueSequence();
    }
    if (decision.action === "clear") {
      return clear();
    }
    const outcome = continueSequence();
    scheduleDeferredDisambiguation(continuationCaptures, decision.handler, focused, getSequence(), (nextDecision) => {
      if (!nextDecision) {
        return;
      }
      if (nextDecision.action === "run-exact") {
        runExact();
        return;
      }
      if (nextDecision.action === "continue-sequence") {
        continueSequence();
        return;
      }
      clear();
    });
    return outcome;
  }
  function resolveDisambiguation(options) {
    let sequence;
    let exact;
    let continuations;
    let strokePart;
    const ctx = {
      event: options.event,
      focused: options.focused,
      get sequence() {
        sequence ??= cloneKeySequence(options.getSequence());
        return sequence;
      },
      get stroke() {
        const stroke = options.getSequence().at(-1);
        if (!stroke) {
          throw new Error("Disambiguation context expected a non-empty sequence");
        }
        strokePart ??= {
          ...stroke,
          stroke: cloneKeyStroke(stroke.stroke)
        };
        return strokePart;
      },
      get exact() {
        exact ??= activation.collectActiveBindings(options.exactBindings, options.focused, options.activeView).map((binding) => ({
          ...binding,
          sequence: cloneKeySequence(binding.sequence)
        }));
        return exact;
      },
      get continuations() {
        continuations ??= activation.getActiveKeysForCaptures(options.continuationCaptures, {
          includeBindings: true,
          includeMetadata: true
        });
        return continuations;
      },
      getData: (name) => {
        return runtime.getData(name);
      },
      setData: (name, value) => {
        runtime.setData(name, value);
      },
      runExact: () => createSyncDecision("run-exact"),
      continueSequence: () => createSyncDecision("continue-sequence"),
      clear: () => createSyncDecision("clear"),
      defer: (run) => createSyncDecision("defer", run)
    };
    for (const resolver of state.disambiguationResolvers.values()) {
      let result;
      try {
        result = resolver(ctx);
      } catch (error) {
        notify.emitError("disambiguation-resolver-error", error, "[Keymap] Error in disambiguation resolver:");
        continue;
      }
      if (result === undefined) {
        continue;
      }
      if (isPromiseLike(result)) {
        notify.emitError("invalid-disambiguation-resolver-return", result, "[Keymap] Disambiguation resolvers must return synchronously; use ctx.defer(...) for async handling");
        continue;
      }
      if (!isSyncDecision(result)) {
        notify.emitError("invalid-disambiguation-decision", result, "[Keymap] Invalid disambiguation decision returned by resolver:");
        continue;
      }
      return result;
    }
    return;
  }
  function scheduleDeferredDisambiguation(captures, handler, focused, sequence, apply) {
    cancelPendingDisambiguation();
    const controller = new AbortController;
    const pending = {
      id: nextPendingDisambiguationId++,
      controller,
      captures,
      apply
    };
    pendingDisambiguation = pending;
    queueMicrotask(() => {
      executeDeferredDisambiguation(pending, handler, focused, sequence);
    });
  }
  function executeDeferredDisambiguation(pending, handler, focused, sequence) {
    if (!isPendingDisambiguationCurrent(pending)) {
      return;
    }
    const ctx = {
      signal: pending.controller.signal,
      sequence: cloneKeySequence(sequence),
      focused,
      sleep: (ms) => {
        return sleepWithSignal(ms, pending.controller.signal);
      },
      runExact: () => createDeferredDecision("run-exact"),
      continueSequence: () => createDeferredDecision("continue-sequence"),
      clear: () => createDeferredDecision("clear")
    };
    let result;
    try {
      result = handler(ctx);
    } catch (error) {
      if (isPendingDisambiguationCurrent(pending)) {
        notify.emitError("deferred-disambiguation-error", error, "[Keymap] Error in deferred disambiguation handler:");
        finishPendingDisambiguation(pending);
      }
      return;
    }
    if (isPromiseLike(result)) {
      result.then((resolved) => {
        applyDeferredDisambiguationResult(pending, resolved);
      }).catch((error) => {
        if (!isPendingDisambiguationCurrent(pending)) {
          return;
        }
        notify.emitError("deferred-disambiguation-error", error, "[Keymap] Error in deferred disambiguation handler:");
        finishPendingDisambiguation(pending);
      });
      return;
    }
    applyDeferredDisambiguationResult(pending, result);
  }
  function applyDeferredDisambiguationResult(pending, result) {
    if (!isPendingDisambiguationCurrent(pending)) {
      return;
    }
    if (result !== undefined && !isDeferredDecision(result)) {
      notify.emitError("invalid-deferred-disambiguation-decision", result, "[Keymap] Invalid deferred disambiguation decision returned by handler:");
      finishPendingDisambiguation(pending);
      return;
    }
    finishPendingDisambiguation(pending);
    pending.apply(result);
  }
  function finishPendingDisambiguation(pending) {
    if (!isPendingDisambiguationCurrent(pending)) {
      return;
    }
    pendingDisambiguation = null;
  }
  function cancelPendingDisambiguation() {
    const pending = pendingDisambiguation;
    if (!pending) {
      return;
    }
    pendingDisambiguation = null;
    pending.controller.abort();
  }
  function isPendingDisambiguationCurrent(pending) {
    return pendingDisambiguation === pending;
  }
  function warnUnresolvedAmbiguity(sequence) {
    const display = stringifyKeySequence(sequence, { preferDisplay: true });
    notify.warnOnce(`unresolved-disambiguation:${display}`, "unresolved-disambiguation", { sequence: display }, `[Keymap] Ambiguous exact/prefix sequence "${display}" fell back to prefix handling because no disambiguation resolver resolved it`);
  }
  function collectPendingCapturesFromRoot(activeLayers, startIndex, matchKeys, event, focused) {
    const captures = [];
    const activeView = catalog.getActiveCommandView(focused);
    for (let index = startIndex;index < activeLayers.length; index += 1) {
      const layer = activeLayers[index];
      if (!layer) {
        continue;
      }
      if (!conditions.matchesConditions(layer)) {
        continue;
      }
      for (const capture of collectRootCaptures(layer, matchKeys, event, focused, activeView)) {
        if (captureHasContinuations(capture, state.patterns, false)) {
          captures.push(capture);
        }
      }
    }
    return captures;
  }
  function collectContinuationCapturesForPrefix(captures, startIndex, prefix) {
    return captures.filter((candidate, candidateIndex) => {
      return candidateIndex >= startIndex && captureHasContinuations(candidate, state.patterns, false) && sameParts(candidate.parts, prefix.parts);
    });
  }
  function collectExactCapturesForPrefix(captures, prefix) {
    return captures.filter((capture) => {
      return capture.layer === prefix.layer && captureIsExact(capture, state.patterns) && sameParts(capture.parts, prefix.parts);
    });
  }
  function resolveEventMatchKeys(event) {
    const resolvers = state.eventMatchResolvers.values();
    if (resolvers.length === 0) {
      return [];
    }
    if (resolvers.length === 1) {
      return resolveSingleEventMatchKeys(resolvers[0], event, eventMatchResolverContext, notify);
    }
    const keys = [];
    const seen = new Set;
    for (const resolver of resolvers) {
      let resolved;
      try {
        resolved = resolver(event, eventMatchResolverContext);
      } catch (error) {
        notify.emitError("event-match-resolver-error", error, "[Keymap] Error in event match resolver:");
        continue;
      }
      if (!resolved || resolved.length === 0) {
        continue;
      }
      for (const candidate of resolved) {
        if (typeof candidate !== "string") {
          notify.emitError("invalid-event-match-resolver-candidate", candidate, "[Keymap] Invalid event match resolver candidate:");
          continue;
        }
        if (seen.has(candidate)) {
          continue;
        }
        seen.add(candidate);
        keys.push(candidate);
      }
    }
    return keys;
  }
  function runReleaseBindings(layer, strokeKey, event, focused) {
    let handled = false;
    let outcome = noMatchOutcome();
    for (const binding of layer.bindings) {
      if (binding.event !== "release") {
        continue;
      }
      const firstPart = binding.sequence[0];
      if (!firstPart || firstPart.match !== strokeKey) {
        continue;
      }
      if (!conditions.matchesConditions(binding)) {
        continue;
      }
      const bindingHandled = executor.runBinding(layer, binding, event, focused);
      outcome = preferDispatchOutcome(outcome, createBindingOutcome(binding, bindingHandled));
      if (!bindingHandled) {
        emitBindingDispatch("binding-reject", layer, binding, focused);
        continue;
      }
      emitBindingDispatch("binding-execute", layer, binding, focused);
      handled = true;
      if (!binding.fallthrough) {
        return { handled: true, stop: true, outcome };
      }
    }
    return { handled, stop: false, outcome };
  }
  function matchPattern(patternName, event) {
    return matchSequencePattern(state.patterns, notify, patternName, event);
  }
  function createPatternEventPart2(event, patternName, match) {
    return createPatternEventPart(state.patterns, event, patternName, match);
  }
  function collectRootCaptures(layer, matchKeys, event, focused, activeView) {
    const captures = collectRootSequenceCaptures(layer, matchKeys, event, matchPattern, createPatternEventPart2);
    return captures.some((capture) => captureIsReachable(capture, focused, activeView)) ? captures : [];
  }
  function createSequencePayload2(capture) {
    return createSequencePayload(state.patterns, notify, capture);
  }
  function bindingMatchesRuntimeState(binding, focused, activeView) {
    return conditions.matchesConditions(binding) && catalog.isBindingVisible(binding, focused, activeView);
  }
  function captureIsReachable(capture, focused, activeView) {
    return bindingMatchesRuntimeState(capture.binding, focused, activeView);
  }
  function runCaptureBindings(layer, captures, event, focused) {
    let handled = false;
    let outcome = noMatchOutcome();
    for (const capture of captures) {
      const binding = capture.binding;
      if (!conditions.matchesConditions(binding)) {
        continue;
      }
      const bindingHandled = executor.runBinding(layer, binding, event, focused, createSequencePayload2(capture));
      outcome = preferDispatchOutcome(outcome, createBindingOutcome(binding, bindingHandled));
      if (!bindingHandled) {
        emitBindingDispatch("binding-reject", layer, binding, focused);
        continue;
      }
      emitBindingDispatch("binding-execute", layer, binding, focused);
      handled = true;
      if (!binding.fallthrough) {
        return { handled: true, stop: true, outcome };
      }
    }
    return { handled, stop: false, outcome };
  }
  return {
    intercept,
    prependEventMatchResolver,
    appendEventMatchResolver,
    clearEventMatchResolvers,
    prependDisambiguationResolver,
    appendDisambiguationResolver,
    clearDisambiguationResolvers,
    handlePendingSequenceChange,
    handleRawSequence,
    handleKeyEvent
  };
}
function resolveSingleEventMatchKeys(resolver, event, ctx, notify) {
  let resolved;
  try {
    resolved = resolver(event, ctx);
  } catch (error) {
    notify.emitError("event-match-resolver-error", error, "[Keymap] Error in event match resolver:");
    return [];
  }
  if (!resolved || resolved.length === 0) {
    return [];
  }
  if (resolved.length === 1) {
    const [candidate] = resolved;
    if (typeof candidate !== "string") {
      notify.emitError("invalid-event-match-resolver-candidate", candidate, "[Keymap] Invalid event match resolver candidate:");
      return [];
    }
    return [candidate];
  }
  const keys = [];
  const seen = new Set;
  for (const candidate of resolved) {
    if (typeof candidate !== "string") {
      notify.emitError("invalid-event-match-resolver-candidate", candidate, "[Keymap] Invalid event match resolver candidate:");
      continue;
    }
    if (seen.has(candidate)) {
      continue;
    }
    seen.add(candidate);
    keys.push(candidate);
  }
  return keys;
}
function sameParts(left, right) {
  if (left.length !== right.length) {
    return false;
  }
  for (let index = 0;index < left.length; index += 1) {
    if (left[index]?.match !== right[index]?.match) {
      return false;
    }
  }
  return true;
}
function normalizePatternLimit(name, field, value, fallback) {
  if (value === undefined) {
    return fallback;
  }
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
    throw new Error(`Keymap sequence pattern "${name}" ${field} must be a non-negative integer`);
  }
  return value;
}
function registerFieldCompilers(fields, options) {
  const { kind, reservedFields, registeredFields, emitError } = options;
  const entries = Object.entries(fields);
  const registered = [];
  for (const [name, compiler] of entries) {
    if (reservedFields.has(name)) {
      emitError(`reserved-${kind}-field`, { field: name, kind }, `Keymap ${kind} field "${name}" is reserved`);
      continue;
    }
    if (registeredFields.has(name)) {
      emitError(`duplicate-${kind}-field`, { field: name, kind }, `Keymap ${kind} field "${name}" is already registered`);
      continue;
    }
    registeredFields.set(name, compiler);
    registered.push([name, compiler]);
  }
  return () => {
    for (const [name, compiler] of registered) {
      const current = registeredFields.get(name);
      if (current === compiler) {
        registeredFields.delete(name);
      }
    }
  };
}
function registerToken(state, notify, compiler, layers, token) {
  let normalizedToken;
  try {
    normalizedToken = normalizeBindingTokenName(token.name);
  } catch (error) {
    notify.emitError("token-name-normalize-error", error, getErrorMessage(error, "Failed to register keymap token"));
    return NOOP;
  }
  if (state.tokens.has(normalizedToken) || state.patterns.has(normalizedToken)) {
    notify.emitError("duplicate-token", { token: normalizedToken }, `Keymap token "${normalizedToken}" is already registered`);
    return NOOP;
  }
  let parsedToken;
  try {
    parsedToken = compiler.parseTokenKey(token.key);
    if (parsedToken.patternName) {
      throw new Error(`Invalid key "${String(token.key)}": expected a concrete key stroke`);
    }
  } catch (error) {
    notify.emitError("token-parse-error", error, getErrorMessage(error, `Failed to register keymap token "${normalizedToken}"`));
    return NOOP;
  }
  const registeredToken = {
    stroke: parsedToken.stroke,
    match: parsedToken.match
  };
  const nextTokens = new Map(state.tokens);
  nextTokens.set(normalizedToken, registeredToken);
  try {
    layers.applyTokenState(nextTokens);
  } catch (error) {
    notify.emitError("token-register-error", error, getErrorMessage(error, `Failed to register keymap token "${normalizedToken}"`));
    return NOOP;
  }
  return () => {
    const current = state.tokens.get(normalizedToken);
    if (current !== registeredToken) {
      return;
    }
    const nextTokens2 = new Map(state.tokens);
    nextTokens2.delete(normalizedToken);
    try {
      layers.applyTokenState(nextTokens2);
    } catch (error) {
      notify.emitError("token-unregister-error", error, getErrorMessage(error, `Failed to unregister keymap token "${normalizedToken}"`));
    }
  };
}
function registerSequencePattern(state, notify, layers, pattern) {
  let normalizedName;
  let resolvedPattern;
  try {
    normalizedName = normalizeBindingTokenName(pattern.name);
    const min = normalizePatternLimit(normalizedName, "min", pattern.min, 1);
    const max = normalizePatternLimit(normalizedName, "max", pattern.max, Number.MAX_SAFE_INTEGER);
    if (max < min) {
      throw new Error(`Keymap sequence pattern "${normalizedName}" max must be greater than or equal to min`);
    }
    resolvedPattern = {
      name: normalizedName,
      display: pattern.display,
      payloadKey: pattern.payloadKey ?? normalizedName,
      match: createTextKeyMatch(`pattern:${normalizedName}`),
      min,
      max,
      matcher: (event) => pattern.match(event),
      finalize: pattern.finalize
    };
  } catch (error) {
    notify.emitError("sequence-pattern-register-error", error, getErrorMessage(error, "Failed to register keymap sequence pattern"));
    return NOOP;
  }
  if (state.tokens.has(normalizedName) || state.patterns.has(normalizedName)) {
    notify.emitError("duplicate-sequence-pattern", { pattern: normalizedName }, `Keymap sequence pattern "${normalizedName}" is already registered`);
    return NOOP;
  }
  state.patterns.set(normalizedName, resolvedPattern);
  layers.recompileBindings();
  return () => {
    const current = state.patterns.get(normalizedName);
    if (current !== resolvedPattern) {
      return;
    }
    state.patterns.delete(normalizedName);
    layers.recompileBindings();
  };
}
function registerFields(state, notify, kind, fields) {
  const reservedFields = kind === "layer" ? RESERVED_LAYER_FIELDS : kind === "binding" ? RESERVED_BINDING_FIELDS : RESERVED_COMMAND_FIELDS;
  const registeredFields = kind === "layer" ? state.layerFields : kind === "binding" ? state.bindingFields : state.commandFields;
  return registerFieldCompilers(fields, {
    kind,
    reservedFields,
    registeredFields,
    emitError: (code, error, message) => notify.emitError(code, error, message)
  });
}
function compareLayers(left, right) {
  const priorityDiff = right.priority - left.priority;
  return priorityDiff || right.order - left.order;
}
function layerBlocksActiveKeyCache(layer) {
  if (layer.matchers.length > 0)
    return true;
  for (const command of layer.commands)
    if (command.matchers.length > 0)
      return true;
  for (const binding of layer.bindings)
    if (binding.matchers.length > 0)
      return true;
  return false;
}
function layerBlocksActiveCommandViewCache(layer) {
  if (layer.commands.length === 0)
    return false;
  if (layer.matchers.length > 0)
    return true;
  for (const command of layer.commands)
    if (command.matchers.length > 0)
      return true;
  return false;
}
function createLayerService(state, notify, conditions, activation, options) {
  const registerLayer = (layer) => {
    return notify.runWithStateChangeBatch(() => {
      const target = layer.target;
      if (target && options.host.isTargetDestroyed(target)) {
        notify.emitError("destroyed-layer-target", { target }, "Cannot register a keymap layer for a destroyed keymap target");
        return NOOP2;
      }
      let sourceBindings;
      let requires;
      let matchers;
      let fields;
      let attrs;
      let commands;
      let targetMode;
      try {
        targetMode = normalizeTargetMode(layer);
        sourceBindings = applyLayerBindingsTransformers(snapshotBindings(layer.bindings ?? []), layer);
        const sourceCommands = applyCommandTransformers(layer.commands ?? [], layer);
        commands = sourceCommands.length === 0 ? [] : options.commands.normalizeCommands(sourceCommands);
        ({ requires, matchers, fields, attrs } = compileLayerRuntimeState(layer));
      } catch (error) {
        notify.emitError("register-layer-failed", error, getErrorMessage(error, "Failed to register keymap layer"));
        return NOOP2;
      }
      const order = state.order++;
      const bindingStates = options.compiler.compileBindings(sourceBindings, state.tokens, target, order, fields);
      if (bindingStates.bindings.length === 0 && !bindingStates.hasTokenBindings && commands.length === 0) {
        return NOOP2;
      }
      options.diagnostics?.analyzeLayer({
        target,
        order,
        commands,
        sourceBindings,
        bindings: bindingStates.bindings,
        hasTokenBindings: bindingStates.hasTokenBindings
      });
      const registeredLayer = {
        order,
        target,
        targetMode,
        priority: layer.priority ?? 0,
        requires,
        matchers,
        fields,
        attrs,
        commands,
        sourceBindings,
        bindings: bindingStates.bindings,
        root: buildSequenceTree(bindingStates.bindings, state.patterns),
        hasTokenBindings: bindingStates.hasTokenBindings,
        activeKeyCacheBlocked: false,
        activeCommandViewCacheBlocked: false
      };
      updateCacheBlockers(registeredLayer);
      state.layers.add(registeredLayer);
      state.sortedLayers = [...state.sortedLayers, registeredLayer].sort(compareLayers);
      attachReactiveMatchers(registeredLayer);
      for (const command of registeredLayer.commands) {
        attachReactiveMatchers(command);
      }
      for (const binding of registeredLayer.bindings) {
        attachReactiveMatchers(binding);
      }
      if (target) {
        const onTargetDestroy = () => {
          unregisterLayer(registeredLayer);
        };
        registeredLayer.offTargetDestroy = options.host.onTargetDestroy(target, onTargetDestroy);
      }
      if (registeredLayer.commands.length > 0) {
        activation.ensureValidPendingSequence();
      }
      notify.queueStateChange();
      return () => {
        unregisterLayer(registeredLayer);
      };
    });
  };
  const applyTokenState = (nextTokens) => {
    notify.runWithStateChangeBatch(() => {
      const nextCompilations = new Map;
      for (const layer of state.layers) {
        if (!layer.hasTokenBindings) {
          continue;
        }
        nextCompilations.set(layer, compileLayerBindings(layer, nextTokens));
      }
      state.tokens = nextTokens;
      let shouldClearPending = false;
      for (const [layer, compilation] of nextCompilations) {
        if (applyBindingStates(layer, compilation)) {
          shouldClearPending = true;
        }
      }
      if (shouldClearPending) {
        activation.setPendingSequence(null);
      }
      if (nextCompilations.size > 0) {
        notify.queueStateChange();
      }
    });
  };
  const recompileBindings = () => {
    notify.runWithStateChangeBatch(() => {
      let recompiledLayers = 0;
      let shouldClearPending = false;
      for (const layer of state.layers) {
        if (layer.sourceBindings.length === 0) {
          continue;
        }
        const compilation = compileLayerBindings(layer, state.tokens);
        if (applyBindingStates(layer, compilation)) {
          shouldClearPending = true;
        }
        recompiledLayers += 1;
      }
      if (shouldClearPending) {
        activation.setPendingSequence(null);
      }
      if (recompiledLayers > 0) {
        notify.queueStateChange();
      }
    });
  };
  const cleanup = () => {
    for (const layer of state.layers) {
      detachReactiveMatchers(layer);
      for (const command of layer.commands) {
        detachReactiveMatchers(command);
      }
      for (const binding of layer.bindings) {
        detachReactiveMatchers(binding);
      }
      layer.offTargetDestroy?.();
      layer.offTargetDestroy = undefined;
    }
  };
  const normalizeTargetMode = (layer) => {
    if (layer.targetMode) {
      if (!layer.target) {
        throw new Error(`Keymap targetMode "${layer.targetMode}" requires a target`);
      }
      return layer.targetMode;
    }
    return layer.target ? "focus-within" : undefined;
  };
  const applyLayerBindingsTransformers = (bindings, layer) => {
    const transformers = state.layerBindingsTransformers.values();
    if (transformers.length === 0) {
      return bindings;
    }
    let current = bindings;
    for (const transformer of transformers) {
      const next = transformer(current, {
        layer,
        validateBindings: (bindings2) => validateBindings(bindings2)
      });
      if (!next) {
        continue;
      }
      current = snapshotBindings(next);
    }
    return current;
  };
  const applyCommandTransformers = (commands, layer) => {
    const transformers = state.commandTransformers.values();
    if (commands.length === 0 || transformers.length === 0) {
      return commands;
    }
    const transformedCommands = [];
    for (const command of commands) {
      const transformedCommand = { ...command };
      const extraCommands = [];
      let keepOriginal = true;
      for (const transformer of transformers) {
        try {
          transformer(transformedCommand, {
            layer,
            add(nextCommand) {
              extraCommands.push({ ...nextCommand });
            },
            skipOriginal() {
              keepOriginal = false;
            }
          });
        } catch (error) {
          notify.emitError("command-transformer-error", error, "[Keymap] Error in command transformer:");
        }
      }
      if (keepOriginal) {
        transformedCommands.push(transformedCommand);
      }
      transformedCommands.push(...extraCommands);
    }
    return transformedCommands;
  };
  const compileLayerRuntimeState = (layer) => {
    const mergedRequires = {};
    const matchers = [];
    const fields = Object.create(null);
    const attrs = {};
    for (const [fieldName, value] of Object.entries(layer)) {
      if (RESERVED_LAYER_FIELDS.has(fieldName)) {
        continue;
      }
      if (value === undefined) {
        continue;
      }
      fields[fieldName] = snapshotDataValue(value);
      const compiler = state.layerFields.get(fieldName);
      if (!compiler) {
        options.warnUnknownField("layer", fieldName);
        continue;
      }
      compiler(value, createFieldCompilerContext({
        fieldName,
        conditions,
        requirements: mergedRequires,
        matchers,
        attrs
      }));
    }
    return {
      requires: Object.entries(mergedRequires),
      matchers,
      fields: Object.keys(fields).length > 0 ? Object.freeze(fields) : undefined,
      attrs: Object.keys(attrs).length > 0 ? snapshotDataValue(attrs, { freeze: true }) : undefined
    };
  };
  const compileLayerBindings = (layer, tokens) => {
    return options.compiler.compileBindings(layer.sourceBindings, tokens, layer.target, layer.order, layer.fields);
  };
  const applyBindingStates = (layer, compilation) => {
    options.diagnostics?.analyzeLayer({
      target: layer.target,
      order: layer.order,
      commands: layer.commands,
      sourceBindings: layer.sourceBindings,
      bindings: compilation.bindings,
      hasTokenBindings: compilation.hasTokenBindings
    });
    untrackCacheBlockers(layer);
    for (const binding of layer.bindings) {
      detachReactiveMatchers(binding);
    }
    layer.bindings = compilation.bindings;
    layer.root = buildSequenceTree(compilation.bindings, state.patterns);
    layer.hasTokenBindings = compilation.hasTokenBindings;
    updateCacheBlockers(layer);
    for (const binding of layer.bindings) {
      attachReactiveMatchers(binding);
    }
    return state.pending?.captures.some((capture) => capture.layer === layer) ?? false;
  };
  const unregisterLayer = (layer) => {
    notify.runWithStateChangeBatch(() => {
      if (!state.layers.delete(layer)) {
        return;
      }
      state.sortedLayers = state.sortedLayers.filter((candidate) => candidate !== layer);
      untrackCacheBlockers(layer);
      detachReactiveMatchers(layer);
      for (const command of layer.commands) {
        detachReactiveMatchers(command);
      }
      for (const binding of layer.bindings) {
        detachReactiveMatchers(binding);
      }
      layer.offTargetDestroy?.();
      layer.offTargetDestroy = undefined;
      if (state.pending?.captures.some((capture) => capture.layer === layer)) {
        activation.setPendingSequence(null);
      } else if (layer.commands.length > 0 && !options.host.isDestroyed) {
        activation.ensureValidPendingSequence();
      }
      notify.queueStateChange();
    });
  };
  const attachReactiveMatchers = (target) => {
    for (const matcher of target.matchers) {
      if (!matcher.subscribe) {
        continue;
      }
      try {
        matcher.dispose = matcher.subscribe(() => {
          if (!activation.hasPendingSequenceState()) {
            notify.queueStateChange();
            return;
          }
          notify.runWithStateChangeBatch(() => {
            activation.revalidatePendingSequenceIfNeeded();
            notify.queueStateChange();
          });
        });
      } catch (error) {
        notify.emitError("reactive-matcher-subscribe-error", error, getErrorMessage(error, `Failed to subscribe to reactive matcher from ${matcher.source}`));
      }
    }
  };
  const updateCacheBlockers = (layer) => {
    const activeKeyBlocked = layerBlocksActiveKeyCache(layer);
    const activeCommandViewBlocked = layerBlocksActiveCommandViewCache(layer);
    layer.activeKeyCacheBlocked = activeKeyBlocked;
    layer.activeCommandViewCacheBlocked = activeCommandViewBlocked;
    if (activeKeyBlocked)
      state.activeKeyCacheBlockers += 1;
    if (activeCommandViewBlocked)
      state.activeCommandViewCacheBlockers += 1;
  };
  const untrackCacheBlockers = (layer) => {
    if (layer.activeKeyCacheBlocked) {
      state.activeKeyCacheBlockers -= 1;
      layer.activeKeyCacheBlocked = false;
    }
    if (layer.activeCommandViewCacheBlocked) {
      state.activeCommandViewCacheBlockers -= 1;
      layer.activeCommandViewCacheBlocked = false;
    }
  };
  const detachReactiveMatchers = (target) => {
    for (const matcher of target.matchers) {
      if (!matcher.dispose) {
        continue;
      }
      try {
        matcher.dispose();
      } catch (error) {
        notify.emitError("reactive-matcher-dispose-error", error, getErrorMessage(error, `Failed to dispose reactive matcher from ${matcher.source}`));
      }
      matcher.dispose = undefined;
    }
  };
  return { registerLayer, applyTokenState, recompileBindings, cleanup };
}
function createNotificationService(state, events, hooks) {
  const emitWarning = (code, warning, message) => {
    if (!events.has("warning")) {
      const consoleMessage = `[${code}] ${message}`;
      if (warning instanceof Error) {
        console.warn(consoleMessage, warning);
      } else {
        console.warn(consoleMessage);
      }
      return;
    }
    events.emit("warning", { code, message, warning });
  };
  const emitError = (code, error, message) => {
    if (!events.has("error")) {
      const consoleMessage = `[${code}] ${message}`;
      if (error instanceof Error) {
        console.error(consoleMessage, error);
      } else {
        console.error(consoleMessage);
      }
      return;
    }
    events.emit("error", { code, message, error });
  };
  const flushStateChange = () => {
    if (!state.stateChangePending || state.stateChangeDepth > 0 || state.flushingStateChange) {
      return;
    }
    state.flushingStateChange = true;
    try {
      let iterations = 0;
      while (state.stateChangePending && state.stateChangeDepth === 0) {
        if (iterations >= MAX_STATE_CHANGE_FLUSH_ITERATIONS) {
          state.stateChangePending = false;
          emitError("state-change-feedback-loop", { iterations: MAX_STATE_CHANGE_FLUSH_ITERATIONS }, `[Keymap] Possible infinite state listener feedback loop detected after ${MAX_STATE_CHANGE_FLUSH_ITERATIONS} iterations; pending state notifications were dropped`);
          break;
        }
        iterations += 1;
        state.stateChangePending = false;
        hooks.emit("state");
      }
    } finally {
      state.flushingStateChange = false;
    }
  };
  return {
    runWithStateChangeBatch(fn) {
      state.stateChangeDepth += 1;
      try {
        return fn();
      } finally {
        state.stateChangeDepth -= 1;
        if (state.stateChangeDepth === 0) {
          flushStateChange();
        }
      }
    },
    queueStateChange(options) {
      state.derivedVersion += 1;
      if (options?.invalidateCaches !== false) {
        state.cacheVersion += 1;
      }
      if (!hooks.has("state")) {
        return;
      }
      state.stateChangePending = true;
      if (state.stateChangeDepth === 0 && !state.flushingStateChange) {
        flushStateChange();
      }
    },
    emitWarning,
    emitError,
    reportListenerError(name, error) {
      if (name === "state") {
        emitError("state-listener-error", error, "[Keymap] Error in state listener:");
        return;
      }
      if (name === "pendingSequence") {
        emitError("pending-sequence-listener-error", error, "[Keymap] Error in pending sequence listener:");
        return;
      }
      if (name === "dispatch") {
        emitError("dispatch-listener-error", error, "[Keymap] Error in dispatch listener:");
      }
    },
    warnOnce(key, code, warning, message) {
      if (state.usedWarningKeys.has(key)) {
        return;
      }
      state.usedWarningKeys.add(key);
      emitWarning(code, warning, message);
    }
  };
}
function createRuntimeService(state, notify, activation) {
  return {
    getData(name) {
      return state.data[name];
    },
    setData(name, value) {
      notify.runWithStateChangeBatch(() => {
        if (value === undefined) {
          if (!(name in state.data)) {
            return;
          }
          delete state.data[name];
          state.dataVersion += 1;
          activation.ensureValidPendingSequence();
          notify.queueStateChange();
          return;
        }
        if (Object.is(state.data[name], value)) {
          return;
        }
        state.data[name] = value;
        state.dataVersion += 1;
        activation.ensureValidPendingSequence();
        notify.queueStateChange();
      });
    },
    getReadonlyData() {
      if (state.readonlyDataVersion === state.dataVersion) {
        return state.readonlyData;
      }
      state.readonlyData = Object.freeze({ ...state.data });
      state.readonlyDataVersion = state.dataVersion;
      return state.readonlyData;
    }
  };
}
function createKeymapState() {
  return {
    order: 0,
    tokens: new Map,
    patterns: new Map,
    layerFields: new Map,
    layerBindingsTransformers: createRuntimeOrderedRegistry(),
    bindingExpanders: createRuntimeOrderedRegistry(),
    bindingParsers: createRuntimeOrderedRegistry(),
    bindingTransformers: createRuntimeOrderedRegistry(),
    bindingFields: new Map,
    commandTransformers: createRuntimeOrderedRegistry(),
    commandFields: new Map,
    eventMatchResolvers: createRuntimeOrderedRegistry(),
    disambiguationResolvers: createRuntimeOrderedRegistry(),
    keyHooks: createRuntimePriorityRegistry(),
    keyAfterHooks: createRuntimePriorityRegistry(),
    rawHooks: createRuntimePriorityRegistry(),
    layers: new Set,
    sortedLayers: [],
    activeLayersCacheVersion: -1,
    activeLayersCacheFocused: undefined,
    activeLayersCache: [],
    activeKeyCacheBlockers: 0,
    activeCommandViewCacheBlockers: 0,
    commandResolvers: createRuntimeOrderedRegistry(),
    pending: null,
    data: {},
    dataVersion: 0,
    readonlyDataVersion: -1,
    readonlyData: EMPTY_DATA,
    cacheVersion: 0,
    derivedVersion: 0,
    stateChangeDepth: 0,
    stateChangePending: false,
    flushingStateChange: false,
    usedWarningKeys: new Set
  };
}
function getKeyMatchKey(input) {
  return resolveKeyMatch(input);
}
var RESERVED_COMMAND_FIELDS, RESERVED_BINDING_FIELDS, RESERVED_LAYER_FIELDS, DEFAULT_COMMAND_SEARCH_FIELDS, EMPTY_COMMAND_FIELDS, commandSearchCache, EMPTY_COMPILE_FIELDS, EMPTY_REQUIRES, EMPTY_MATCHERS, KEY_DISAMBIGUATION_DECISION, KEY_DEFERRED_DISAMBIGUATION_DECISION, NOOP = () => {}, NOOP2 = () => {}, MAX_STATE_CHANGE_FLUSH_ITERATIONS = 1000, EMPTY_DATA, Keymap;
var init_src = __esm(() => {
  init_index_frk6sdcd();
  init_index_p35cyhc4();
  RESERVED_COMMAND_FIELDS = new Set(["name", "run", "fields", "attrs", "rejectedResult"]);
  RESERVED_BINDING_FIELDS = new Set(["key", "cmd", "event", "preventDefault", "fallthrough"]);
  RESERVED_LAYER_FIELDS = new Set(["target", "targetMode", "priority", "bindings", "commands"]);
  DEFAULT_COMMAND_SEARCH_FIELDS = ["name"];
  EMPTY_COMMAND_FIELDS = Object.freeze({});
  commandSearchCache = new WeakMap;
  EMPTY_COMPILE_FIELDS = Object.freeze({});
  EMPTY_REQUIRES = [];
  EMPTY_MATCHERS = [];
  KEY_DISAMBIGUATION_DECISION = Symbol("keymap-disambiguation-decision");
  KEY_DEFERRED_DISAMBIGUATION_DECISION = Symbol("keymap-deferred-disambiguation-decision");
  EMPTY_DATA = Object.freeze({});
  Keymap = class Keymap {
    #state = createKeymapState();
    #cleanedUp = false;
    #resources = new Map;
    #cleanupListeners = [];
    #events = createRuntimeEmitter(() => {});
    #hooks;
    #notify;
    #activation;
    #runtime;
    #conditions;
    #catalog;
    #executor;
    #compiler;
    #dispatch;
    #layers;
    #layerDiagnostics;
    #keypressListener;
    #keyreleaseListener;
    #rawListener;
    #focusedTargetListener;
    #host;
    getPendingSequence;
    getActiveKeys;
    constructor(host) {
      this.#host = host;
      if (host.isDestroyed) {
        throw new Error("Cannot create a keymap for a destroyed host");
      }
      this.#hooks = createRuntimeEmitter((name, error) => {
        this.#notify.reportListenerError(name, error);
      });
      this.#notify = createNotificationService(this.#state, this.#events, this.#hooks);
      this.#conditions = createConditionService(this.#state, this.#notify);
      this.#catalog = createCommandCatalogService(this.#state, this.#host, this.#notify, this.#conditions, {
        onCommandResolversChanged: () => {
          this.#activation.ensureValidPendingSequence();
        }
      });
      this.#activation = createActivationService(this.#state, this.#host, this.#hooks, this.#notify, this.#conditions, this.#catalog, {
        onPendingSequenceChanged: (previous, next) => {
          this.#dispatch?.handlePendingSequenceChange(previous, next);
        }
      });
      this.#runtime = createRuntimeService(this.#state, this.#notify, this.#activation);
      this.#executor = createCommandExecutorService(this.#notify, this.#runtime, this.#activation, this.#catalog, {
        keymap: this,
        createCommandEvent: () => this.#host.createCommandEvent()
      });
      this.#compiler = createCompilerService(this.#state, this.#notify, this.#conditions, {
        warnUnknownField: (kind, fieldName) => {
          this.#warnUnknownField(kind, fieldName);
        },
        warnUnknownToken: (token, sequence) => {
          this.#warnUnknownToken(token, sequence);
        }
      });
      this.#layerDiagnostics = createLayerDiagnostics(this.#notify, this.#catalog);
      this.#layers = createLayerService(this.#state, this.#notify, this.#conditions, this.#activation, {
        compiler: this.#compiler,
        commands: this.#catalog,
        host: this.#host,
        diagnostics: this.#layerDiagnostics,
        warnUnknownField: (kind, fieldName) => {
          this.#warnUnknownField(kind, fieldName);
        }
      });
      this.#dispatch = createDispatchService(this.#state, this.#notify, this.#runtime, this.#activation, this.#conditions, this.#executor, this.#compiler, this.#catalog, this.#layers, this.#hooks);
      this.getPendingSequence = this.#activation.getPendingSequence;
      this.getActiveKeys = this.#activation.getActiveKeys;
      this.#keypressListener = (event) => {
        this.#dispatch.handleKeyEvent(event, false);
      };
      this.#keyreleaseListener = (event) => {
        this.#dispatch.handleKeyEvent(event, true);
      };
      this.#rawListener = (sequence) => {
        return this.#dispatch.handleRawSequence(sequence);
      };
      this.#focusedTargetListener = (focused) => {
        this.#handleFocusedTargetChange(focused);
      };
      this.#cleanupListeners.push(this.#host.onKeyPress(this.#keypressListener));
      this.#cleanupListeners.push(this.#host.onKeyRelease(this.#keyreleaseListener));
      if (this.#host.onRawInput) {
        this.#cleanupListeners.push(this.#host.onRawInput(this.#rawListener));
      }
      this.#cleanupListeners.push(this.#host.onFocusChange(this.#focusedTargetListener));
      if (this.#host.onDestroy) {
        this.#cleanupListeners.push(this.#host.onDestroy(() => {
          this.#cleanup();
        }));
      }
    }
    [KEYMAP_EXTENSION_CONTEXT]() {
      return {
        state: this.#state,
        host: this.#host,
        conditions: this.#conditions,
        catalog: this.#catalog,
        activation: this.#activation
      };
    }
    #cleanup() {
      if (this.#cleanedUp) {
        return;
      }
      this.#cleanedUp = true;
      this.#activation.setPendingSequence(null);
      for (const resource of this.#resources.values()) {
        resource.dispose();
      }
      this.#resources.clear();
      this.#layers.cleanup();
      for (const cleanupListener of this.#cleanupListeners.splice(0)) {
        cleanupListener();
      }
    }
    setData(name, value) {
      this.#runtime.setData(name, value);
    }
    getData(name) {
      return this.#runtime.getData(name);
    }
    getHostMetadata() {
      return this.#host.metadata;
    }
    hasPendingSequence() {
      return this.#activation.ensureValidPendingSequence() !== undefined;
    }
    createKeyMatcher(key) {
      const match = this.#compiler.parseTokenKey(key).match;
      return (input) => {
        if (!input) {
          return false;
        }
        return getKeyMatchKey(input) === match;
      };
    }
    parseKeySequence(key) {
      return this.#compiler.parseKeySequence(key);
    }
    formatKey(key, options) {
      return this.#compiler.formatKey(key, options);
    }
    clearPendingSequence() {
      this.#activation.setPendingSequence(null);
    }
    popPendingSequence() {
      return this.#activation.popPendingSequence();
    }
    getCommands(query) {
      return this.#catalog.getCommands(query);
    }
    getCommandEntries(query) {
      return this.#catalog.getCommandEntries(query);
    }
    getCommandBindings(query) {
      return this.#catalog.getCommandBindings(query);
    }
    acquireResource(key, setup) {
      if (this.#cleanedUp || this.#host.isDestroyed) {
        throw new Error("Cannot use a keymap after its host was destroyed");
      }
      const existing = this.#resources.get(key);
      if (existing) {
        existing.count += 1;
        return () => {
          this.#releaseResource(key, existing);
        };
      }
      const dispose2 = setup();
      const resource = { count: 1, dispose: dispose2 };
      this.#resources.set(key, resource);
      return () => {
        this.#releaseResource(key, resource);
      };
    }
    runCommand(cmd, options) {
      return this.#executor.runCommand(cmd, options);
    }
    dispatchCommand(cmd, options) {
      return this.#executor.dispatchCommand(cmd, options);
    }
    on(name, fn) {
      if (name === "warning") {
        return this.#events.hook(name, fn);
      }
      if (name === "error") {
        return this.#events.hook(name, fn);
      }
      return this.#hooks.hook(name, fn);
    }
    intercept(name, fn, options) {
      if (name === "key") {
        return this.#dispatch.intercept(name, fn, options);
      }
      if (name === "key:after") {
        return this.#dispatch.intercept(name, fn, options);
      }
      return this.#dispatch.intercept(name, fn, options);
    }
    registerLayer(layer) {
      return this.#layers.registerLayer(layer);
    }
    registerLayerFields(fields) {
      return registerFields(this.#state, this.#notify, "layer", fields);
    }
    prependLayerBindingsTransformer(transformer) {
      return this.#state.layerBindingsTransformers.prepend(transformer);
    }
    appendLayerBindingsTransformer(transformer) {
      return this.#state.layerBindingsTransformers.append(transformer);
    }
    clearLayerBindingsTransformers() {
      this.#state.layerBindingsTransformers.clear();
    }
    prependBindingTransformer(transformer) {
      return this.#state.bindingTransformers.prepend(transformer);
    }
    appendBindingTransformer(transformer) {
      return this.#state.bindingTransformers.append(transformer);
    }
    clearBindingTransformers() {
      this.#state.bindingTransformers.clear();
    }
    prependCommandTransformer(transformer) {
      return this.#state.commandTransformers.prepend(transformer);
    }
    appendCommandTransformer(transformer) {
      return this.#state.commandTransformers.append(transformer);
    }
    clearCommandTransformers() {
      this.#state.commandTransformers.clear();
    }
    prependBindingParser(parser) {
      return this.#state.bindingParsers.prepend(parser);
    }
    appendBindingParser(parser) {
      return this.#state.bindingParsers.append(parser);
    }
    clearBindingParsers() {
      this.#state.bindingParsers.clear();
    }
    registerToken(token) {
      return registerToken(this.#state, this.#notify, this.#compiler, this.#layers, token);
    }
    registerSequencePattern(pattern) {
      return registerSequencePattern(this.#state, this.#notify, this.#layers, pattern);
    }
    prependBindingExpander(expander) {
      return this.#state.bindingExpanders.prepend(expander);
    }
    appendBindingExpander(expander) {
      return this.#state.bindingExpanders.append(expander);
    }
    clearBindingExpanders() {
      this.#state.bindingExpanders.clear();
    }
    registerBindingFields(fields) {
      return registerFields(this.#state, this.#notify, "binding", fields);
    }
    registerCommandFields(fields) {
      return registerFields(this.#state, this.#notify, "command", fields);
    }
    prependCommandResolver(resolver) {
      return this.#catalog.prependCommandResolver(resolver);
    }
    appendCommandResolver(resolver) {
      return this.#catalog.appendCommandResolver(resolver);
    }
    clearCommandResolvers() {
      this.#catalog.clearCommandResolvers();
    }
    prependLayerAnalyzer(analyzer) {
      return this.#layerDiagnostics.prependLayerAnalyzer(analyzer);
    }
    appendLayerAnalyzer(analyzer) {
      return this.#layerDiagnostics.appendLayerAnalyzer(analyzer);
    }
    clearLayerAnalyzers() {
      this.#layerDiagnostics.clearLayerAnalyzers();
    }
    prependEventMatchResolver(resolver) {
      return this.#dispatch.prependEventMatchResolver(resolver);
    }
    appendEventMatchResolver(resolver) {
      return this.#dispatch.appendEventMatchResolver(resolver);
    }
    clearEventMatchResolvers() {
      this.#dispatch.clearEventMatchResolvers();
    }
    prependDisambiguationResolver(resolver) {
      return this.#dispatch.prependDisambiguationResolver(resolver);
    }
    appendDisambiguationResolver(resolver) {
      return this.#dispatch.appendDisambiguationResolver(resolver);
    }
    clearDisambiguationResolvers() {
      this.#dispatch.clearDisambiguationResolvers();
    }
    #handleFocusedTargetChange(_focused) {
      this.#notify.runWithStateChangeBatch(() => {
        this.#activation.setPendingSequence(null);
        this.#notify.queueStateChange({ invalidateCaches: false });
      });
    }
    #warnUnknownField(kind, fieldName) {
      this.#notify.warnOnce(`${kind}:${fieldName}`, `unknown-${kind}-field`, { field: fieldName, kind }, `[Keymap] Unknown ${kind} field "${fieldName}" was ignored`);
    }
    #warnUnknownToken(token, sequence) {
      this.#notify.warnOnce(`token:${token}`, "unknown-token", { token, sequence }, `[Keymap] Unknown token "${token}" in key sequence "${sequence}"; binding was skipped until the token is registered`);
    }
    #releaseResource(key, resource) {
      const current = this.#resources.get(key);
      if (current !== resource) {
        return;
      }
      resource.count -= 1;
      if (resource.count > 0) {
        return;
      }
      resource.dispose();
      this.#resources.delete(key);
    }
  };
});

// ../../node_modules/.bun/@opentui+keymap@0.5.10+4b5b8a304ce90f81/node_modules/@opentui/keymap/src/addons/index.js
function createPrefixBuckets(values) {
  const buckets = new Map;
  for (const value of values) {
    const first = value.charCodeAt(0);
    if (Number.isNaN(first)) {
      continue;
    }
    let bucket = buckets.get(first);
    if (!bucket) {
      bucket = [];
      buckets.set(first, bucket);
    }
    bucket.push(value);
  }
  for (const bucket of buckets.values()) {
    bucket.sort((left, right) => right.length - left.length);
  }
  return buckets;
}
function toLowerAsciiCode(code) {
  return code >= 65 && code <= 90 ? code + 32 : code;
}
function isDigitCode(code) {
  return code >= 48 && code <= 57;
}
function startsWithAsciiInsensitive(input, prefix, index) {
  if (input.startsWith(prefix, index)) {
    return true;
  }
  if (index + prefix.length > input.length) {
    return false;
  }
  for (let offset = 0;offset < prefix.length; offset += 1) {
    if (toLowerAsciiCode(input.charCodeAt(index + offset)) !== prefix.charCodeAt(offset)) {
      return false;
    }
  }
  return true;
}
function findBucketedPrefixMatch(buckets, input, index) {
  const first = input.charCodeAt(index);
  if (Number.isNaN(first)) {
    return;
  }
  const candidates = buckets.get(toLowerAsciiCode(first));
  if (!candidates) {
    return;
  }
  for (const candidate of candidates) {
    if (startsWithAsciiInsensitive(input, candidate, index)) {
      return candidate;
    }
  }
  return;
}
function parseObjectKeyInput(ctx, key, display, match, tokenName) {
  return ctx.parseObjectKey(key, {
    display,
    match,
    tokenName
  });
}
function parseStringKeyPart(input, ctx) {
  if (input === " ") {
    return ctx.parseObjectKey({ name: "space" }, { display: "space" });
  }
  if (input === "+") {
    return ctx.parseObjectKey({ name: "+" }, { display: "+" });
  }
  const parts = input.split("+");
  let name = "";
  let displayName = "";
  let ctrl = false;
  let shift = false;
  let meta = false;
  let superKey = false;
  let hyper = false;
  for (const rawPart of parts) {
    const part = rawPart.trim();
    if (!part) {
      continue;
    }
    const lowered = part.toLowerCase();
    if (lowered === "ctrl" || lowered === "control") {
      ctrl = true;
      continue;
    }
    if (lowered === "shift") {
      shift = true;
      continue;
    }
    if (lowered === "meta" || lowered === "alt" || lowered === "option") {
      meta = true;
      continue;
    }
    if (lowered === "super") {
      superKey = true;
      continue;
    }
    if (lowered === "hyper") {
      hyper = true;
      continue;
    }
    if (name) {
      throw new Error(`Invalid key "${input}": multiple key names are not supported`);
    }
    name = part;
    displayName = lowered;
  }
  if (!name) {
    throw new Error(`Invalid key "${input}": missing key name`);
  }
  const displayParts = [];
  if (ctrl)
    displayParts.push("ctrl");
  if (shift)
    displayParts.push("shift");
  if (meta)
    displayParts.push("meta");
  if (superKey)
    displayParts.push("super");
  if (hyper)
    displayParts.push("hyper");
  displayParts.push(displayName);
  return ctx.parseObjectKey({
    name,
    ctrl,
    shift,
    meta,
    super: superKey,
    hyper: hyper || undefined
  }, {
    display: displayParts.join("+")
  });
}
function parseNamedKeyPart(name, ctx) {
  const normalized = name.trim().toLowerCase();
  return ctx.parseObjectKey({ name: normalized }, { display: normalized });
}
function findNamedSingleStrokeKey(input, index) {
  const namedKey = findBucketedPrefixMatch(namedSingleStrokeKeyPrefixes, input, index);
  if (namedKey) {
    return namedKey;
  }
  if (toLowerAsciiCode(input.charCodeAt(index)) !== 102 || !isDigitCode(input.charCodeAt(index + 1))) {
    return;
  }
  const end = isDigitCode(input.charCodeAt(index + 2)) ? index + 3 : index + 2;
  return input.slice(index, end).toLowerCase();
}
function findModifierKey(input, index) {
  return findBucketedPrefixMatch(modifierKeyPrefixes, input, index);
}
function parseModifiedKeyPart(input, index, ctx) {
  let cursor = index;
  let ctrl = false;
  let shift = false;
  let meta = false;
  let superKey = false;
  let hyper = false;
  while (cursor < input.length) {
    const modifier = findModifierKey(input, cursor);
    if (!modifier) {
      break;
    }
    const plusIndex = cursor + modifier.length;
    if (input[plusIndex] !== "+") {
      break;
    }
    if (modifier === "ctrl" || modifier === "control") {
      ctrl = true;
    } else if (modifier === "shift") {
      shift = true;
    } else if (modifier === "meta" || modifier === "alt" || modifier === "option") {
      meta = true;
    } else if (modifier === "super") {
      superKey = true;
    } else if (modifier === "hyper") {
      hyper = true;
    }
    cursor = plusIndex + 1;
  }
  if (cursor === index) {
    return;
  }
  const char = input[cursor];
  if (char === undefined) {
    throw new Error(`Invalid key "${input.slice(index)}": missing key name`);
  }
  const name = findNamedSingleStrokeKey(input, cursor) ?? char;
  const displayName = name === " " ? "space" : name === "+" ? "+" : name.toLowerCase();
  const displayParts = [];
  if (ctrl)
    displayParts.push("ctrl");
  if (shift)
    displayParts.push("shift");
  if (meta)
    displayParts.push("meta");
  if (superKey)
    displayParts.push("super");
  if (hyper)
    displayParts.push("hyper");
  displayParts.push(displayName);
  return {
    part: ctx.parseObjectKey({
      name: name === " " ? "space" : name,
      ctrl,
      shift,
      meta,
      super: superKey,
      hyper: hyper || undefined
    }, {
      display: displayParts.join("+")
    }),
    nextIndex: cursor + name.length
  };
}
function registerDefaultBindingParser(keymap) {
  return keymap.appendBindingParser((ctx) => defaultBindingParser(ctx));
}
function registerDefaultEventMatchResolver(keymap) {
  return keymap.appendEventMatchResolver((event, ctx) => defaultEventMatchResolver(event, ctx));
}
function registerDefaultKeys(keymap) {
  const offParser = registerDefaultBindingParser(keymap);
  const offResolver = registerDefaultEventMatchResolver(keymap);
  return () => {
    offResolver();
    offParser();
  };
}
function isReactiveMatcher2(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  const candidate = value;
  return typeof candidate.get === "function" && typeof candidate.subscribe === "function";
}
function normalizeEnabledValue(fieldName, value) {
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value === "function") {
    return value;
  }
  if (isReactiveMatcher2(value)) {
    return value;
  }
  throw new Error(`Keymap enabled field "${fieldName}" must be a boolean, a function, or a reactive matcher`);
}
function registerEnabledFields(keymap) {
  return keymap.acquireResource(ENABLED_FIELDS_RESOURCE, () => {
    const offLayerFields = keymap.registerLayerFields({
      enabled(value, ctx) {
        const normalized = normalizeEnabledValue("enabled", value);
        if (normalized === true) {
          return;
        }
        if (normalized === false) {
          ctx.activeWhen(() => false);
          return;
        }
        ctx.activeWhen(normalized);
      }
    });
    const offCommandFields = keymap.registerCommandFields({
      enabled(value, ctx) {
        const normalized = normalizeEnabledValue("enabled", value);
        if (normalized === true) {
          return;
        }
        if (normalized === false) {
          ctx.activeWhen(() => false);
          return;
        }
        ctx.activeWhen(normalized);
      }
    });
    return () => {
      offCommandFields();
      offLayerFields();
    };
  });
}
function normalizeMetadataText(fieldName, value) {
  if (typeof value !== "string") {
    throw new Error(`Keymap metadata field "${fieldName}" must be a string`);
  }
  const trimmed = value.trim();
  if (!trimmed) {
    throw new Error(`Keymap metadata field "${fieldName}" cannot be empty`);
  }
  return trimmed;
}
function registerMetadataFields(keymap) {
  return keymap.acquireResource(METADATA_FIELDS_RESOURCE, () => {
    const offBindingFields = keymap.registerBindingFields({
      desc(value, ctx) {
        ctx.attr("desc", normalizeMetadataText("desc", value));
      },
      group(value, ctx) {
        ctx.attr("group", normalizeMetadataText("group", value));
      }
    });
    const offCommandFields = keymap.registerCommandFields({
      desc(value, ctx) {
        ctx.attr("desc", normalizeMetadataText("desc", value));
      },
      title(value, ctx) {
        ctx.attr("title", normalizeMetadataText("title", value));
      },
      category(value, ctx) {
        ctx.attr("category", normalizeMetadataText("category", value));
      }
    });
    return () => {
      offCommandFields();
      offBindingFields();
    };
  });
}
var namedSingleStrokeKeys, modifierKeyNames, namedSingleStrokeKeyPrefixes, modifierKeyPrefixes, defaultBindingParser = (ctx) => {
  const { input, index, tokens, normalizeTokenName } = ctx;
  if (index === 0 && input.includes("+") && /\s/.test(input)) {
    return {
      parts: [parseStringKeyPart(input, ctx)],
      nextIndex: input.length
    };
  }
  const char = input[index];
  if (char === undefined) {
    return;
  }
  if (char === "<") {
    const end = input.indexOf(">", index);
    if (end === -1) {
      return {
        parts: [parseStringKeyPart(char, ctx)],
        nextIndex: index + 1
      };
    }
    const tokenName = normalizeTokenName(input.slice(index + 1, end));
    const token = tokens.get(tokenName);
    if (!token) {
      return {
        parts: [],
        nextIndex: end + 1,
        unknownTokens: [tokenName]
      };
    }
    return {
      parts: [parseObjectKeyInput(ctx, token.stroke, `<${tokenName}>`, token.match, tokenName)],
      nextIndex: end + 1,
      usedTokens: [tokenName]
    };
  }
  if (char === "{") {
    const end = input.indexOf("}", index);
    if (end === -1) {
      return {
        parts: [parseStringKeyPart(char, ctx)],
        nextIndex: index + 1
      };
    }
    const patternName = normalizeTokenName(input.slice(index + 1, end));
    const pattern = ctx.patterns.get(patternName);
    if (!pattern) {
      return {
        parts: [],
        nextIndex: end + 1,
        unknownTokens: [patternName]
      };
    }
    const part = ctx.parseObjectKey({ name: patternName, ctrl: false, shift: false, meta: false, super: false }, { display: pattern.display ?? `{${patternName}}`, match: pattern.match });
    return {
      parts: [{ ...part, patternName: pattern.name, payloadKey: pattern.payloadKey }],
      nextIndex: end + 1,
      usedTokens: [patternName]
    };
  }
  const modified = parseModifiedKeyPart(input, index, ctx);
  if (modified) {
    return {
      parts: [modified.part],
      nextIndex: modified.nextIndex
    };
  }
  const namedKey = findNamedSingleStrokeKey(input, index);
  if (namedKey) {
    return {
      parts: [parseNamedKeyPart(namedKey, ctx)],
      nextIndex: index + namedKey.length
    };
  }
  return {
    parts: [parseStringKeyPart(char, ctx)],
    nextIndex: index + 1
  };
}, defaultEventMatchResolver = (event, ctx) => {
  return [
    ctx.resolveKey({
      name: event.name,
      ctrl: event.ctrl,
      shift: event.shift,
      meta: event.meta,
      super: event.super ?? false,
      hyper: event.hyper || undefined
    })
  ];
}, BINDING_OVERRIDES_RESOURCE, ALIASES_FIELD_RESOURCE, COMMA_BINDINGS_RESOURCE, DEAD_BINDING_WARNINGS_RESOURCE, ENABLED_FIELDS_RESOURCE, EMACS_BINDINGS_RESOURCE, EX_COMMANDS_RESOURCE, METADATA_FIELDS_RESOURCE, MOD_BINDINGS_RESOURCE, UNRESOLVED_COMMAND_WARNINGS_RESOURCE;
var init_addons = __esm(() => {
  init_index_p35cyhc4();
  init_src();
  init_src();
  namedSingleStrokeKeys = new Set([
    "up",
    "down",
    "left",
    "right",
    "clear",
    "escape",
    "return",
    "linefeed",
    "enter",
    "tab",
    "backspace",
    "delete",
    "insert",
    "home",
    "end",
    "pageup",
    "pagedown",
    "space",
    "lt",
    "gt",
    "plus",
    "minus",
    "equal",
    "comma",
    "period",
    "slash",
    "backslash",
    "semicolon",
    "quote",
    "backquote",
    "leftbracket",
    "rightbracket",
    "capslock",
    "numlock",
    "scrolllock",
    "printscreen",
    "pause",
    "menu",
    "apps",
    "kp0",
    "kp1",
    "kp2",
    "kp3",
    "kp4",
    "kp5",
    "kp6",
    "kp7",
    "kp8",
    "kp9",
    "kpdecimal",
    "kpdivide",
    "kpmultiply",
    "kpminus",
    "kpplus",
    "kpenter",
    "kpequal",
    "kpseparator",
    "kpleft",
    "kpright",
    "kpup",
    "kpdown",
    "kppageup",
    "kppagedown",
    "kphome",
    "kpend",
    "kpinsert",
    "kpdelete",
    "mediaplay",
    "mediapause",
    "mediaplaypause",
    "mediareverse",
    "mediastop",
    "mediafastforward",
    "mediarewind",
    "medianext",
    "mediaprev",
    "mediarecord",
    "volumedown",
    "volumeup",
    "mute",
    "leftshift",
    "leftctrl",
    "leftalt",
    "leftsuper",
    "lefthyper",
    "leftmeta",
    "rightshift",
    "rightctrl",
    "rightalt",
    "rightsuper",
    "righthyper",
    "rightmeta",
    "iso_level3_shift",
    "iso_level5_shift",
    "option",
    "alt",
    "meta",
    "super",
    "hyper",
    "control",
    "ctrl",
    "shift"
  ]);
  modifierKeyNames = new Set(["ctrl", "control", "shift", "meta", "alt", "option", "super", "hyper"]);
  namedSingleStrokeKeyPrefixes = createPrefixBuckets(namedSingleStrokeKeys);
  modifierKeyPrefixes = createPrefixBuckets(modifierKeyNames);
  BINDING_OVERRIDES_RESOURCE = Symbol("keymap:binding-overrides");
  ALIASES_FIELD_RESOURCE = Symbol("keymap:aliases-field");
  COMMA_BINDINGS_RESOURCE = Symbol("keymap:comma-bindings");
  DEAD_BINDING_WARNINGS_RESOURCE = Symbol("keymap:dead-binding-warnings");
  ENABLED_FIELDS_RESOURCE = Symbol("keymap:enabled-fields");
  EMACS_BINDINGS_RESOURCE = Symbol("keymap:emacs-bindings");
  EX_COMMANDS_RESOURCE = Symbol("keymap:ex-commands");
  METADATA_FIELDS_RESOURCE = Symbol("keymap:metadata-fields");
  MOD_BINDINGS_RESOURCE = Symbol("keymap:mod-bindings");
  UNRESOLVED_COMMAND_WARNINGS_RESOURCE = Symbol("keymap:unresolved-command-warnings");
});

// ../../node_modules/.bun/@opentui+keymap@0.5.10+4b5b8a304ce90f81/node_modules/@opentui/keymap/src/opentui.js
import { CliRenderEvents, KeyEvent, RenderableEvents } from "@opentui/core";
function createSyntheticCommandEvent() {
  return new KeyEvent({
    name: "command",
    ctrl: false,
    meta: false,
    shift: false,
    option: false,
    sequence: "",
    number: false,
    raw: "",
    eventType: "press",
    source: "raw"
  });
}
function normalizeRuntimePlatform(platform) {
  if (platform === "darwin") {
    return "macos";
  }
  if (platform === "win32") {
    return "windows";
  }
  if (platform === "linux") {
    return "linux";
  }
  return "unknown";
}
function createOpenTuiHostMetadata(renderer) {
  const platform = normalizeRuntimePlatform(process.platform);
  const hasKittyKeyboard = renderer.capabilities?.kitty_keyboard === true;
  return {
    platform,
    primaryModifier: platform === "macos" ? "super" : platform === "unknown" ? "unknown" : "ctrl",
    modifiers: {
      ctrl: "supported",
      shift: "supported",
      meta: "supported",
      super: hasKittyKeyboard ? "supported" : "unknown",
      hyper: hasKittyKeyboard ? "supported" : "unknown"
    }
  };
}
function createOpenTuiKeymapHost(renderer) {
  return {
    get metadata() {
      return createOpenTuiHostMetadata(renderer);
    },
    rootTarget: renderer.root,
    get isDestroyed() {
      return renderer.isDestroyed;
    },
    getFocusedTarget() {
      const focused = renderer.currentFocusedRenderable;
      if (!focused || focused.isDestroyed || !focused.focused) {
        return null;
      }
      return focused;
    },
    getParentTarget(target) {
      return target.parent;
    },
    isTargetDestroyed(target) {
      return target.isDestroyed;
    },
    onKeyPress(listener) {
      renderer.keyInput.prependListener("keypress", listener);
      return () => {
        renderer.keyInput.off("keypress", listener);
      };
    },
    onKeyRelease(listener) {
      renderer.keyInput.prependListener("keyrelease", listener);
      return () => {
        renderer.keyInput.off("keyrelease", listener);
      };
    },
    onFocusChange(listener) {
      renderer.on(CliRenderEvents.FOCUSED_RENDERABLE, listener);
      return () => {
        renderer.off(CliRenderEvents.FOCUSED_RENDERABLE, listener);
      };
    },
    onDestroy(listener) {
      renderer.once(CliRenderEvents.DESTROY, listener);
      return () => {
        renderer.off(CliRenderEvents.DESTROY, listener);
      };
    },
    onTargetDestroy(target, listener) {
      target.once(RenderableEvents.DESTROYED, listener);
      return () => {
        target.off(RenderableEvents.DESTROYED, listener);
      };
    },
    onRawInput(listener) {
      renderer.prependInputHandler(listener);
      return () => {
        renderer.removeInputHandler(listener);
      };
    },
    createCommandEvent() {
      return createSyntheticCommandEvent();
    }
  };
}
function createDefaultOpenTuiKeymap(renderer) {
  if (renderer.isDestroyed) {
    throw new Error("Cannot create a keymap for a destroyed renderer");
  }
  const keymap = new Keymap(createOpenTuiKeymapHost(renderer));
  registerDefaultKeys(keymap);
  registerEnabledFields(keymap);
  registerMetadataFields(keymap);
  return keymap;
}
var init_opentui = __esm(() => {
  init_index_p35cyhc4();
  init_src();
  init_addons();
});

// src/cli/tui-solid/keymap-input.ts
var exports_keymap_input = {};
__export(exports_keymap_input, {
  createProjectsKeymap: () => createProjectsKeymap
});
function createProjectsKeymap(renderer) {
  const keymap = createDefaultOpenTuiKeymap(renderer);
  keymap.clearEventMatchResolvers();
  keymap.appendEventMatchResolver((event, context) => event.name.trim() ? defaultEventMatchResolver(event, context) : []);
  return keymap;
}
var init_keymap_input = __esm(() => {
  init_opentui();
  init_addons();
});

// ../../node_modules/.bun/@opentui+keymap@0.5.10+4b5b8a304ce90f81/node_modules/@opentui/keymap/src/solid/index.js
var exports_solid = {};
__export(exports_solid, {
  useKeymapSelector: () => useKeymapSelector,
  useKeymap: () => useKeymap,
  useBindings: () => useBindings,
  reactiveMatcherFromSignal: () => reactiveMatcherFromSignal,
  KeymapProvider: () => KeymapProvider
});
function KeymapProvider(props) {
  return createComponent(KeymapContext.Provider, {
    get value() {
      return props.keymap;
    },
    get children() {
      return props.children;
    }
  });
}
function resolveBindingsTarget(target) {
  return target?.() ?? undefined;
}
function useKeymapStateVersion(keymap) {
  const [version, setVersion] = createSignal(0);
  let dispose2;
  onMount(() => {
    dispose2 = keymap.on("state", () => {
      setVersion((value) => value + 1);
    });
    setVersion((value) => value + 1);
  });
  onCleanup(() => {
    dispose2?.();
  });
  return version;
}
function useBindings(createLayer) {
  const keymap = useKeymap();
  createEffect(() => {
    const layer = createLayer();
    const hasExplicitTarget = layer.target !== undefined;
    const explicitTarget = resolveBindingsTarget(layer.target);
    const nextTargetMode = layer.targetMode ?? (hasExplicitTarget ? "focus-within" : undefined);
    const { target: _target, targetMode: _targetMode, ...baseLayer } = layer;
    if (!nextTargetMode) {
      const dispose22 = keymap.registerLayer({
        ...baseLayer
      });
      onCleanup(() => {
        dispose22();
      });
      return;
    }
    if (!hasExplicitTarget) {
      throw new Error("useBindings local bindings need a target accessor");
    }
    if (!explicitTarget) {
      return;
    }
    const dispose2 = keymap.registerLayer({
      ...baseLayer,
      target: explicitTarget,
      targetMode: nextTargetMode
    });
    onCleanup(() => {
      dispose2();
    });
  });
}
function reactiveMatcherFromSignal(accessor, predicate) {
  return {
    get() {
      return predicate ? predicate(accessor()) : Boolean(accessor());
    },
    subscribe(onChange) {
      return createRoot((dispose2) => {
        createEffect(on(accessor, () => onChange(), { defer: true }));
        return dispose2;
      });
    }
  };
}
var KeymapContext, useKeymap = () => {
  const keymap = useContext(KeymapContext);
  if (!keymap) {
    throw new Error("Keymap not found. Wrap the tree in <KeymapProvider>.");
  }
  return keymap;
}, useKeymapSelector = (selector) => {
  const keymap = useKeymap();
  const version = useKeymapStateVersion(keymap);
  return createMemo((previous) => {
    version();
    try {
      return selector(keymap);
    } catch (error) {
      if (previous !== undefined && error instanceof Error && error.message === "Cannot use a keymap after its host was destroyed") {
        return previous;
      }
      throw error;
    }
  });
};
var init_solid = __esm(() => {
  init_index_p35cyhc4();
  init_server();
  KeymapContext = createContext();
});

// src/cli/tui/theme.ts
function normalizeThemeMode(value) {
  const raw = String(value ?? "").trim().toLowerCase();
  if (raw === "light" || raw === "dark" || raw === "auto")
    return raw;
  return "auto";
}
function themeFromColorFgBg(value) {
  if (!value)
    return null;
  const parts = value.split(";").map((p) => Number.parseInt(p, 10)).filter((n) => Number.isFinite(n));
  const bg = parts.at(-1);
  if (bg === undefined)
    return null;
  if (bg === 7 || bg === 15)
    return "light";
  if (bg >= 0 && bg <= 6 || bg === 8)
    return "dark";
  return null;
}
function detectSystemTheme(env = process.env) {
  const forced = normalizeThemeMode(env["PROJECTS_TUI_THEME"] ?? env["HASNA_PROJECTS_TUI_THEME"] ?? env["TUI_THEME"] ?? env["TERMINAL_THEME"]);
  if (forced === "light" || forced === "dark")
    return forced;
  const colorFgBg = themeFromColorFgBg(env["COLORFGBG"]);
  if (colorFgBg)
    return colorFgBg;
  const joined = [
    env["APPLE_INTERFACE_STYLE"],
    env["OS_APPEARANCE"],
    env["TERM_BACKGROUND"],
    env["GTK_THEME"],
    env["KDE_COLOR_SCHEME"],
    env["ITERM_PROFILE"]
  ].filter(Boolean).join(" ").toLowerCase();
  if (/\b(dark|night|black)\b/.test(joined))
    return "dark";
  if (/\b(light|day|white)\b/.test(joined))
    return "light";
  return "light";
}
var init_theme = () => {};

// src/cli/tui-solid/context/theme.tsx
function resolveSolidTheme(mode = "auto", env = process.env) {
  const normalized = normalizeThemeMode(mode);
  const resolved = normalized === "auto" ? detectSystemTheme(env) : normalized;
  return resolved === "light" ? LIGHT : DARK;
}
function hexToRgb(hex) {
  const raw = hex.replace("#", "").slice(0, 6);
  if (raw.length !== 6)
    return null;
  const value = Number.parseInt(raw, 16);
  if (!Number.isFinite(value))
    return null;
  return {
    r: value >> 16 & 255,
    g: value >> 8 & 255,
    b: value & 255
  };
}
function selectedForeground(theme, bg) {
  if (theme.selectedListItemText)
    return theme.selectedListItemText;
  if (typeof bg === "string") {
    const rgb = hexToRgb(bg);
    if (rgb) {
      const luminance = 0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b;
      return luminance > 150 ? "#0a0a0a" : "#ffffff";
    }
  } else if (bg) {
    const luminance = 0.299 * bg.r + 0.587 * bg.g + 0.114 * bg.b;
    return luminance > 150 ? "#0a0a0a" : "#ffffff";
  }
  return theme.mode === "dark" ? theme.background : theme.text;
}
function ThemeProvider(props) {
  const theme = createMemo(() => resolveSolidTheme(props.mode ?? "auto"));
  const value = new Proxy({}, {
    get: (_, key) => typeof key === "string" ? theme()[key] : undefined
  });
  return createComponent2(ThemeContext.Provider, {
    value,
    get children() {
      return props.children;
    }
  });
}
function useTheme() {
  const theme = useContext(ThemeContext);
  if (!theme)
    throw new Error("useTheme must be used within ThemeProvider");
  return theme;
}
function labelColor(theme, label) {
  let hash = 0;
  for (const ch of label)
    hash = hash * 31 + ch.charCodeAt(0) | 0;
  return theme.labelPalette[Math.abs(hash) % theme.labelPalette.length] ?? (typeof theme.primary === "string" ? theme.primary : "#fab283");
}
var DARK, LIGHT, ThemeContext;
var init_theme2 = __esm(() => {
  init_index_bun();
  init_server();
  init_theme();
  DARK = {
    mode: "dark",
    primary: "#fab283",
    secondary: "#5c9cf5",
    accent: "#9d7cd8",
    error: "#e06c75",
    warning: "#f5a742",
    success: "#7fd88f",
    info: "#56b6c2",
    text: "#eeeeee",
    textMuted: "#808080",
    textFaint: "#606060",
    selectedListItemText: "#0a0a0a",
    background: "#0a0a0a",
    backgroundPanel: "#141414",
    backgroundElement: "#1e1e1e",
    backgroundMenu: "#1e1e1e",
    backgroundActive: "#282828",
    backgroundHover: "#323232",
    backgroundPressed: "#3c3c3c",
    border: "#484848",
    borderActive: "#606060",
    borderSubtle: "#3c3c3c",
    markdownText: "#eeeeee",
    markdownHeading: "#9d7cd8",
    markdownLink: "#fab283",
    markdownLinkText: "#56b6c2",
    markdownCode: "#7fd88f",
    markdownBlockQuote: "#e5c07b",
    markdownEmph: "#e5c07b",
    markdownStrong: "#f5a742",
    markdownHorizontalRule: "#808080",
    markdownListItem: "#fab283",
    markdownListEnumeration: "#56b6c2",
    markdownImage: "#fab283",
    markdownImageText: "#56b6c2",
    markdownCodeBlock: "#eeeeee",
    labelPalette: ["#fab283", "#5c9cf5", "#9d7cd8", "#7fd88f", "#56b6c2", "#e06c75", "#e5c07b"]
  };
  LIGHT = {
    mode: "light",
    primary: "#1e66f5",
    secondary: "#209fb5",
    accent: "#8839ef",
    error: "#d20f39",
    warning: "#df8e1d",
    success: "#40a02b",
    info: "#04a5e5",
    text: "#4c4f69",
    textMuted: "#6c6f85",
    textFaint: "#9ca0b0",
    selectedListItemText: "#ffffff",
    background: "#ffffff",
    backgroundPanel: "#fafbfc",
    backgroundElement: "#f4f5f7",
    backgroundMenu: "#f4f5f7",
    backgroundActive: "#e8eefc",
    backgroundHover: "#eef0f4",
    backgroundPressed: "#dfe3ea",
    border: "#dce0e8",
    borderActive: "#bcc0cc",
    borderSubtle: "#eceef1",
    markdownText: "#4c4f69",
    markdownHeading: "#8839ef",
    markdownLink: "#1e66f5",
    markdownLinkText: "#209fb5",
    markdownCode: "#40a02b",
    markdownBlockQuote: "#df8e1d",
    markdownEmph: "#df8e1d",
    markdownStrong: "#fe640b",
    markdownHorizontalRule: "#9ca0b0",
    markdownListItem: "#1e66f5",
    markdownListEnumeration: "#209fb5",
    markdownImage: "#1e66f5",
    markdownImageText: "#209fb5",
    markdownCodeBlock: "#4c4f69",
    labelPalette: ["#1e66f5", "#8839ef", "#fe640b", "#40a02b", "#179299", "#d20f39", "#df8e1d"]
  };
  ThemeContext = createContext();
});

// ../../node_modules/.bun/solid-js@1.9.13/node_modules/solid-js/store/dist/server.js
function wrap$1(value) {
  let p = value[$PROXY];
  if (!p) {
    Object.defineProperty(value, $PROXY, {
      value: p = new Proxy(value, proxyTraps$1)
    });
    if (!Array.isArray(value)) {
      const keys = Object.keys(value), desc = Object.getOwnPropertyDescriptors(value), proto = Object.getPrototypeOf(value);
      const isClass = proto !== null && value !== null && typeof value === "object" && !Array.isArray(value) && proto !== Object.prototype;
      if (isClass) {
        const descriptors = Object.getOwnPropertyDescriptors(proto);
        keys.push(...Object.keys(descriptors));
        Object.assign(desc, descriptors);
      }
      for (let i = 0, l = keys.length;i < l; i++) {
        const prop = keys[i];
        if (isClass && prop === "constructor")
          continue;
        if (desc[prop].get) {
          Object.defineProperty(value, prop, {
            configurable: true,
            enumerable: desc[prop].enumerable,
            get: desc[prop].get.bind(p)
          });
        }
      }
    }
  }
  return p;
}
function isWrappable(obj) {
  let proto;
  return obj != null && typeof obj === "object" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));
}
function unwrap(item, set = new Set) {
  let result, unwrapped, v, prop;
  if (result = item != null && item[$RAW])
    return result;
  if (!isWrappable(item) || set.has(item))
    return item;
  if (Array.isArray(item)) {
    if (Object.isFrozen(item))
      item = item.slice(0);
    else
      set.add(item);
    for (let i = 0, l = item.length;i < l; i++) {
      v = item[i];
      if ((unwrapped = unwrap(v, set)) !== v)
        item[i] = unwrapped;
    }
  } else {
    if (Object.isFrozen(item))
      item = Object.assign({}, item);
    else
      set.add(item);
    const keys = Object.keys(item), desc = Object.getOwnPropertyDescriptors(item);
    for (let i = 0, l = keys.length;i < l; i++) {
      prop = keys[i];
      if (desc[prop].get)
        continue;
      v = item[prop];
      if ((unwrapped = unwrap(v, set)) !== v)
        item[prop] = unwrapped;
    }
  }
  return item;
}
function getNodes(target, symbol) {
  let nodes = target[symbol];
  if (!nodes)
    Object.defineProperty(target, symbol, {
      value: nodes = Object.create(null)
    });
  return nodes;
}
function getNode(nodes, property, value) {
  if (nodes[property])
    return nodes[property];
  const [s, set] = createSignal(value, {
    equals: false,
    internal: true
  });
  s.$ = set;
  return nodes[property] = s;
}
function proxyDescriptor$1(target, property) {
  const desc = Reflect.getOwnPropertyDescriptor(target, property);
  if (!desc || desc.get || !desc.configurable || property === $PROXY || property === $NODE)
    return desc;
  delete desc.value;
  delete desc.writable;
  desc.get = () => target[$PROXY][property];
  return desc;
}
function trackSelf(target) {
  getListener() && getNode(getNodes(target, $NODE), $SELF)();
}
function ownKeys(target) {
  trackSelf(target);
  return Reflect.ownKeys(target);
}
function setProperty(state, property, value, deleting = false) {
  if (property === "__proto__") {
    return;
  }
  if (!deleting && state[property] === value)
    return;
  const prev = state[property], len = state.length;
  if (value === undefined) {
    delete state[property];
    if (state[$HAS] && state[$HAS][property] && prev !== undefined)
      state[$HAS][property].$();
  } else {
    state[property] = value;
    if (state[$HAS] && state[$HAS][property] && prev === undefined)
      state[$HAS][property].$();
  }
  let nodes = getNodes(state, $NODE), node;
  if (node = getNode(nodes, property, prev))
    node.$(() => value);
  if (Array.isArray(state) && state.length !== len) {
    for (let i = state.length;i < len; i++)
      (node = nodes[i]) && node.$();
    (node = getNode(nodes, "length", len)) && node.$(state.length);
  }
  (node = nodes[$SELF]) && node.$();
}
function mergeStoreNode(state, value) {
  const keys = Object.keys(value);
  for (let i = 0;i < keys.length; i += 1) {
    const key = keys[i];
    if (isUnsafeKey$1(key))
      continue;
    setProperty(state, key, value[key]);
  }
}
function isUnsafeKey$1(property) {
  return property === "__proto__" || property === "constructor" || property === "prototype";
}
function updateArray(current, next) {
  if (typeof next === "function")
    next = next(current);
  next = unwrap(next);
  if (Array.isArray(next)) {
    if (current === next)
      return;
    let i = 0, len = next.length;
    for (;i < len; i++) {
      const value = next[i];
      if (current[i] !== value)
        setProperty(current, i, value);
    }
    setProperty(current, "length", len);
  } else
    mergeStoreNode(current, next);
}
function updatePath(current, path, traversed = []) {
  let part, prev = current;
  if (path.length > 1) {
    part = path.shift();
    const partType = typeof part, isArray = Array.isArray(current);
    if (partType === "string" && (part === "__proto__" || path.length > 1 && isUnsafeKey$1(part))) {
      return;
    }
    if (Array.isArray(part)) {
      for (let i = 0;i < part.length; i++) {
        updatePath(current, [part[i]].concat(path), traversed);
      }
      return;
    } else if (isArray && partType === "function") {
      for (let i = 0;i < current.length; i++) {
        if (part(current[i], i))
          updatePath(current, [i].concat(path), traversed);
      }
      return;
    } else if (isArray && partType === "object") {
      const {
        from = 0,
        to = current.length - 1,
        by = 1
      } = part;
      for (let i = from;i <= to; i += by) {
        updatePath(current, [i].concat(path), traversed);
      }
      return;
    } else if (path.length > 1) {
      updatePath(current[part], path, [part].concat(traversed));
      return;
    }
    prev = current[part];
    traversed = [part].concat(traversed);
  }
  let value = path[0];
  if (typeof value === "function") {
    value = value(prev, traversed);
    if (value === prev)
      return;
  }
  if (part === undefined && value == undefined)
    return;
  value = unwrap(value);
  if (part === undefined || isWrappable(prev) && isWrappable(value) && !Array.isArray(value)) {
    mergeStoreNode(prev, value);
  } else
    setProperty(current, part, value);
}
function createStore(...[store, options]) {
  const unwrappedStore = unwrap(store || {});
  const isArray = Array.isArray(unwrappedStore);
  const wrappedStore = wrap$1(unwrappedStore);
  function setStore(...args) {
    batch(() => {
      isArray && args.length === 1 ? updateArray(unwrappedStore, args[0]) : updatePath(unwrappedStore, args);
    });
  }
  return [wrappedStore, setStore];
}
var $RAW, $NODE, $HAS, $SELF, proxyTraps$1, $ROOT, producers;
var init_server2 = __esm(() => {
  init_server();
  $RAW = Symbol("store-raw");
  $NODE = Symbol("store-node");
  $HAS = Symbol("store-has");
  $SELF = Symbol("store-self");
  proxyTraps$1 = {
    get(target, property, receiver) {
      if (property === $RAW)
        return target;
      if (property === $PROXY)
        return receiver;
      if (property === $TRACK) {
        trackSelf(target);
        return receiver;
      }
      const nodes = getNodes(target, $NODE);
      const tracked = nodes[property];
      let value = tracked ? tracked() : target[property];
      if (property === $NODE || property === $HAS || property === "__proto__")
        return value;
      if (!tracked) {
        const desc = Object.getOwnPropertyDescriptor(target, property);
        if (getListener() && (typeof value !== "function" || target.hasOwnProperty(property)) && !(desc && desc.get))
          value = getNode(nodes, property, value)();
      }
      return isWrappable(value) ? wrap$1(value) : value;
    },
    has(target, property) {
      if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === $HAS || property === "__proto__")
        return true;
      getListener() && getNode(getNodes(target, $HAS), property)();
      return property in target;
    },
    set() {
      return true;
    },
    deleteProperty() {
      return true;
    },
    ownKeys,
    getOwnPropertyDescriptor: proxyDescriptor$1
  };
  $ROOT = Symbol("store-root");
  producers = new WeakMap;
});

// src/db/schema.ts
function runMigrations(db) {
  db.run(`
    CREATE TABLE IF NOT EXISTS _migrations (
      id INTEGER PRIMARY KEY,
      applied_at TEXT NOT NULL DEFAULT (datetime('now'))
    )
  `);
  for (let i = 0;i < MIGRATIONS.length; i++) {
    const migrationId = i + 1;
    const exists = db.query("SELECT id FROM _migrations WHERE id = ?").get(migrationId);
    if (!exists) {
      db.run(MIGRATIONS[i]);
    }
  }
}
var MIGRATIONS;
var init_schema = __esm(() => {
  MIGRATIONS = [
    `
  INSERT OR IGNORE INTO _migrations (id) VALUES (1);
  `,
    `
  INSERT OR IGNORE INTO _migrations (id) VALUES (2);
  `,
    `
  INSERT OR IGNORE INTO _migrations (id) VALUES (3);
  `,
    `
  INSERT OR IGNORE INTO _migrations (id) VALUES (4);
  `,
    `
  CREATE TABLE IF NOT EXISTS roots (
    id TEXT PRIMARY KEY,
    slug TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    base_path TEXT NOT NULL,
    tags TEXT NOT NULL DEFAULT '[]',
    default_kind TEXT,
    default_recipe_id TEXT,
    default_tmux_profile_id TEXT,
    github_org TEXT,
    repo_visibility TEXT CHECK(repo_visibility IS NULL OR repo_visibility IN ('public', 'private')),
    path_template TEXT,
    name_template TEXT,
    allowed_recipes TEXT NOT NULL DEFAULT '[]',
    allowed_agents TEXT NOT NULL DEFAULT '[]',
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS recipes (
    id TEXT PRIMARY KEY,
    slug TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    description TEXT,
    kind TEXT,
    version INTEGER NOT NULL DEFAULT 1,
    steps TEXT NOT NULL DEFAULT '[]',
    variables TEXT NOT NULL DEFAULT '{}',
    default_tags TEXT NOT NULL DEFAULT '[]',
    default_tmux_profile_id TEXT,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS agents (
    id TEXT PRIMARY KEY,
    slug TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    kind TEXT NOT NULL CHECK(kind IN ('human', 'ai', 'service', 'cli')),
    provider TEXT,
    model TEXT,
    role TEXT,
    permissions TEXT NOT NULL DEFAULT '[]',
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS workspaces (
    id TEXT PRIMARY KEY,
    slug TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    description TEXT,
    kind TEXT NOT NULL DEFAULT 'generic',
    status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'archived', 'deleted')),
    root_id TEXT REFERENCES roots(id) ON DELETE SET NULL,
    recipe_id TEXT REFERENCES recipes(id) ON DELETE SET NULL,
    primary_path TEXT UNIQUE,
    git_remote TEXT,
    s3_bucket TEXT,
    s3_prefix TEXT,
    tags TEXT NOT NULL DEFAULT '[]',
    integrations TEXT NOT NULL DEFAULT '{}',
    metadata TEXT NOT NULL DEFAULT '{}',
    last_opened_at TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    synced_at TEXT
  );

  CREATE TABLE IF NOT EXISTS workspace_locations (
    id TEXT PRIMARY KEY,
    workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    path TEXT NOT NULL,
    machine_id TEXT NOT NULL,
    label TEXT NOT NULL DEFAULT 'main',
    kind TEXT NOT NULL DEFAULT 'local',
    is_primary INTEGER NOT NULL DEFAULT 0,
    exists_at_create INTEGER NOT NULL DEFAULT 0,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(workspace_id, path, machine_id)
  );

  CREATE TABLE IF NOT EXISTS workspace_agents (
    id TEXT PRIMARY KEY,
    workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    agent_id TEXT NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
    role TEXT NOT NULL DEFAULT 'contributor',
    assigned_by TEXT REFERENCES agents(id) ON DELETE SET NULL,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(workspace_id, agent_id, role)
  );

  CREATE TABLE IF NOT EXISTS workspace_events (
    id TEXT PRIMARY KEY,
    workspace_id TEXT REFERENCES workspaces(id) ON DELETE SET NULL,
    agent_id TEXT REFERENCES agents(id) ON DELETE SET NULL,
    event_type TEXT NOT NULL,
    source TEXT NOT NULL CHECK(source IN ('cli', 'mcp', 'agent', 'migration', 'system')),
    prompt TEXT,
    command TEXT,
    before_json TEXT,
    after_json TEXT,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS agent_runs (
    id TEXT PRIMARY KEY,
    agent_id TEXT REFERENCES agents(id) ON DELETE SET NULL,
    workspace_id TEXT REFERENCES workspaces(id) ON DELETE SET NULL,
    provider TEXT,
    model TEXT,
    prompt TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'planned' CHECK(status IN ('planned', 'running', 'completed', 'failed')),
    plan_json TEXT,
    tool_calls_json TEXT NOT NULL DEFAULT '[]',
    result_json TEXT,
    error TEXT,
    metadata TEXT NOT NULL DEFAULT '{}',
    started_at TEXT NOT NULL DEFAULT (datetime('now')),
    completed_at TEXT
  );

  CREATE TABLE IF NOT EXISTS project_budgets (
    id TEXT PRIMARY KEY,
    scope_type TEXT NOT NULL CHECK(scope_type IN ('project', 'run')),
    scope_id TEXT NOT NULL,
    window TEXT NOT NULL CHECK(window IN ('daily', 'monthly', 'lifetime')),
    mode TEXT NOT NULL DEFAULT 'hard' CHECK(mode IN ('hard', 'soft')),
    max_usd REAL,
    max_input_tokens INTEGER,
    max_output_tokens INTEGER,
    max_total_tokens INTEGER,
    warning_threshold REAL,
    reset_at TEXT,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS project_budget_spend (
    id TEXT PRIMARY KEY,
    workspace_id TEXT REFERENCES workspaces(id) ON DELETE SET NULL,
    run_id TEXT,
    provider TEXT,
    model TEXT,
    usd REAL NOT NULL DEFAULT 0,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    total_tokens INTEGER NOT NULL DEFAULT 0,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS tmux_profiles (
    id TEXT PRIMARY KEY,
    slug TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    description TEXT,
    session_template TEXT NOT NULL DEFAULT '{slug}',
    attach INTEGER NOT NULL DEFAULT 0,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS tmux_profile_windows (
    id TEXT PRIMARY KEY,
    profile_id TEXT NOT NULL REFERENCES tmux_profiles(id) ON DELETE CASCADE,
    window_name_template TEXT NOT NULL,
    path_template TEXT,
    command TEXT,
    window_index INTEGER,
    detached INTEGER NOT NULL DEFAULT 1,
    env TEXT NOT NULL DEFAULT '{}',
    revive INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(profile_id, window_name_template)
  );

  CREATE TABLE IF NOT EXISTS workspace_tmux_sessions (
    id TEXT PRIMARY KEY,
    workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    profile_id TEXT REFERENCES tmux_profiles(id) ON DELETE SET NULL,
    session_name TEXT NOT NULL,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(workspace_id, session_name)
  );

  CREATE TABLE IF NOT EXISTS workspace_locks (
    id TEXT PRIMARY KEY,
    lock_key TEXT UNIQUE NOT NULL,
    workspace_id TEXT REFERENCES workspaces(id) ON DELETE CASCADE,
    agent_id TEXT REFERENCES agents(id) ON DELETE SET NULL,
    reason TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    expires_at TEXT
  );

  CREATE TABLE IF NOT EXISTS workspace_migration_map (
    old_project_id TEXT PRIMARY KEY,
    workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    migrated_at TEXT NOT NULL DEFAULT (datetime('now')),
    metadata TEXT NOT NULL DEFAULT '{}'
  );

  CREATE INDEX IF NOT EXISTS idx_roots_slug ON roots(slug);
  CREATE INDEX IF NOT EXISTS idx_roots_base_path ON roots(base_path);
  CREATE INDEX IF NOT EXISTS idx_recipes_slug ON recipes(slug);
  CREATE INDEX IF NOT EXISTS idx_agents_slug ON agents(slug);
  CREATE INDEX IF NOT EXISTS idx_workspaces_slug ON workspaces(slug);
  CREATE INDEX IF NOT EXISTS idx_workspaces_kind ON workspaces(kind);
  CREATE INDEX IF NOT EXISTS idx_workspaces_status ON workspaces(status);
  CREATE INDEX IF NOT EXISTS idx_workspaces_root ON workspaces(root_id);
  CREATE INDEX IF NOT EXISTS idx_workspaces_primary_path ON workspaces(primary_path);
  CREATE INDEX IF NOT EXISTS idx_workspace_locations_workspace ON workspace_locations(workspace_id);
  CREATE INDEX IF NOT EXISTS idx_workspace_locations_machine ON workspace_locations(machine_id);
  CREATE INDEX IF NOT EXISTS idx_workspace_events_workspace ON workspace_events(workspace_id);
  CREATE INDEX IF NOT EXISTS idx_workspace_events_agent ON workspace_events(agent_id);
  CREATE INDEX IF NOT EXISTS idx_workspace_events_type ON workspace_events(event_type);
  CREATE INDEX IF NOT EXISTS idx_agent_runs_agent ON agent_runs(agent_id);
  CREATE INDEX IF NOT EXISTS idx_agent_runs_workspace ON agent_runs(workspace_id);
  CREATE INDEX IF NOT EXISTS idx_agent_runs_status ON agent_runs(status);
  CREATE INDEX IF NOT EXISTS idx_project_budgets_scope ON project_budgets(scope_type, scope_id);
  CREATE INDEX IF NOT EXISTS idx_project_budget_spend_workspace ON project_budget_spend(workspace_id);
  CREATE INDEX IF NOT EXISTS idx_project_budget_spend_run ON project_budget_spend(run_id);
  CREATE INDEX IF NOT EXISTS idx_tmux_profiles_slug ON tmux_profiles(slug);

  INSERT OR IGNORE INTO _migrations (id) VALUES (5);
  `,
    `
  CREATE TABLE IF NOT EXISTS project_budgets (
    id TEXT PRIMARY KEY,
    scope_type TEXT NOT NULL CHECK(scope_type IN ('project', 'run')),
    scope_id TEXT NOT NULL,
    window TEXT NOT NULL CHECK(window IN ('daily', 'monthly', 'lifetime')),
    mode TEXT NOT NULL DEFAULT 'hard' CHECK(mode IN ('hard', 'soft')),
    max_usd REAL,
    max_input_tokens INTEGER,
    max_output_tokens INTEGER,
    max_total_tokens INTEGER,
    warning_threshold REAL,
    reset_at TEXT,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS project_budget_spend (
    id TEXT PRIMARY KEY,
    workspace_id TEXT REFERENCES workspaces(id) ON DELETE SET NULL,
    run_id TEXT,
    provider TEXT,
    model TEXT,
    usd REAL NOT NULL DEFAULT 0,
    input_tokens INTEGER NOT NULL DEFAULT 0,
    output_tokens INTEGER NOT NULL DEFAULT 0,
    total_tokens INTEGER NOT NULL DEFAULT 0,
    metadata TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE INDEX IF NOT EXISTS idx_project_budgets_scope ON project_budgets(scope_type, scope_id);
  CREATE INDEX IF NOT EXISTS idx_project_budget_spend_workspace ON project_budget_spend(workspace_id);
  CREATE INDEX IF NOT EXISTS idx_project_budget_spend_run ON project_budget_spend(run_id);

  INSERT OR IGNORE INTO _migrations (id) VALUES (6);
  `,
    `
  ALTER TABLE workspaces ADD COLUMN canonical_machine TEXT NULL;

  CREATE TABLE IF NOT EXISTS machines (
    slug TEXT PRIMARY KEY,
    status TEXT NOT NULL DEFAULT 'active',
    role TEXT NOT NULL CHECK(role IN ('mirror-hub', 'assignable', 'avoid'))
  );

  INSERT OR IGNORE INTO machines (slug, status, role) VALUES
    ('spark01', 'active', 'mirror-hub'),
    ('spark02', 'active', 'mirror-hub'),
    ('apple01', 'active', 'assignable'),
    ('apple03', 'active', 'assignable'),
    ('apple06', 'active', 'avoid'),
    ('machine001', 'active', 'assignable'),
    ('machine002', 'active', 'assignable'),
    ('machine003', 'active', 'assignable'),
    ('machine004', 'active', 'assignable'),
    ('machine005', 'active', 'assignable'),
    ('machine006', 'active', 'assignable'),
    ('machine007', 'active', 'assignable'),
    ('machine008', 'active', 'assignable'),
    ('machine009', 'active', 'assignable'),
    ('machine010', 'active', 'assignable'),
    ('machine011', 'active', 'assignable');

  UPDATE workspaces
  SET canonical_machine = NULLIF(trim(json_extract(metadata, '$.canonical_machine')), '')
  WHERE canonical_machine IS NULL
    AND json_valid(metadata)
    AND json_type(metadata, '$.canonical_machine') = 'text';

  UPDATE workspaces
  SET metadata = json_remove(metadata, '$.canonical_machine')
  WHERE json_valid(metadata)
    AND json_type(metadata, '$.canonical_machine') IS NOT NULL;

  CREATE INDEX IF NOT EXISTS idx_workspaces_canonical_machine ON workspaces(canonical_machine);

  INSERT OR IGNORE INTO _migrations (id) VALUES (7);
  `,
    `
  CREATE TABLE IF NOT EXISTS guarded_project_mutation_receipts (
    receipt_id TEXT PRIMARY KEY,
    operation_id TEXT NOT NULL,
    step_id TEXT NOT NULL,
    direction TEXT NOT NULL CHECK(direction IN ('forward', 'inverse')),
    idempotency_key TEXT NOT NULL,
    target_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    request_digest TEXT NOT NULL,
    precondition_digest TEXT NOT NULL,
    expected_revision TEXT NOT NULL,
    outcome TEXT NOT NULL CHECK(outcome IN ('accepted', 'duplicate_of_accepted', 'terminal_nonacceptance')),
    reason TEXT,
    result_project_id TEXT,
    duplicate_of_receipt_id TEXT,
    before_json TEXT,
    after_json TEXT,
    post_revision TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE INDEX IF NOT EXISTS idx_guarded_project_mutation_receipts_lookup
    ON guarded_project_mutation_receipts(operation_id, step_id, direction, idempotency_key, target_id);
  CREATE INDEX IF NOT EXISTS idx_guarded_project_mutation_receipts_target
    ON guarded_project_mutation_receipts(target_id, created_at);

  INSERT OR IGNORE INTO _migrations (id) VALUES (8);
  `,
    `
  CREATE TABLE IF NOT EXISTS project_registration_manifests (
    operation_id TEXT PRIMARY KEY,
    route TEXT NOT NULL,
    request_digest TEXT NOT NULL,
    project_id TEXT NOT NULL,
    project_slug TEXT NOT NULL,
    plan_json TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT (datetime('now'))
  );

  CREATE TABLE IF NOT EXISTS project_registration_receipts (
    receipt_id TEXT PRIMARY KEY,
    operation_id TEXT NOT NULL REFERENCES project_registration_manifests(operation_id),
    sequence INTEGER NOT NULL,
    step_id TEXT NOT NULL,
    authority TEXT NOT NULL,
    resource_kind TEXT NOT NULL,
    direction TEXT NOT NULL CHECK(direction IN ('forward', 'inverse')),
    idempotency_key TEXT NOT NULL,
    target_id TEXT,
    request_digest TEXT NOT NULL,
    precondition_digest TEXT NOT NULL,
    outcome TEXT NOT NULL CHECK(outcome IN ('accepted', 'duplicate_of_accepted', 'terminal_nonacceptance')),
    reason TEXT,
    result_revision TEXT,
    result_digest TEXT,
    duplicate_of_receipt_id TEXT,
    authority_receipt_json TEXT,
    artifacts_json TEXT NOT NULL DEFAULT '[]',
    preconditions_json TEXT NOT NULL DEFAULT '[]',
    rollback_json TEXT NOT NULL DEFAULT '[]',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(operation_id, sequence)
  );

  CREATE INDEX IF NOT EXISTS idx_project_registration_receipts_lookup
    ON project_registration_receipts(operation_id, step_id, direction, idempotency_key);
  CREATE INDEX IF NOT EXISTS idx_project_registration_receipts_target
    ON project_registration_receipts(authority, resource_kind, target_id, created_at);

  CREATE TRIGGER IF NOT EXISTS project_registration_manifests_no_update
  BEFORE UPDATE ON project_registration_manifests
  BEGIN
    SELECT RAISE(ABORT, 'project registration manifests are immutable');
  END;

  CREATE TRIGGER IF NOT EXISTS project_registration_manifests_no_delete
  BEFORE DELETE ON project_registration_manifests
  BEGIN
    SELECT RAISE(ABORT, 'project registration manifests are immutable');
  END;

  CREATE TRIGGER IF NOT EXISTS project_registration_receipts_no_update
  BEFORE UPDATE ON project_registration_receipts
  BEGIN
    SELECT RAISE(ABORT, 'project registration receipts are immutable');
  END;

  CREATE TRIGGER IF NOT EXISTS project_registration_receipts_no_delete
  BEFORE DELETE ON project_registration_receipts
  BEGIN
    SELECT RAISE(ABORT, 'project registration receipts are immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (9);
  `,
    `
  CREATE TABLE IF NOT EXISTS project_resource_links (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    authority TEXT NOT NULL CHECK(authority IN ('todos', 'conversations', 'knowledge', 'mementos')),
    service_instance TEXT NOT NULL,
    source_package TEXT NOT NULL CHECK(source_package IN ('@hasna/todos', '@hasna/conversations', '@hasna/knowledge', '@hasna/mementos')),
    target_kind TEXT NOT NULL CHECK(target_kind IN ('project', 'task_list', 'plan', 'channel', 'collection', 'item')),
    locator_kind TEXT NOT NULL CHECK(locator_kind IN ('external_uuid', 'canonical_uri')),
    locator_value TEXT NOT NULL,
    scope TEXT NOT NULL CHECK(scope IN ('resource', 'collection')),
    labels_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value)
  );

  CREATE INDEX IF NOT EXISTS idx_project_resource_links_project
    ON project_resource_links(project_id, authority, target_kind, id);

  CREATE TRIGGER IF NOT EXISTS project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value, scope
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (10);
  `,
    `
  DROP TRIGGER IF EXISTS project_resource_links_identity_immutable;
  DROP INDEX IF EXISTS idx_project_resource_links_project;

  ALTER TABLE project_resource_links RENAME TO project_resource_links_v10;

  CREATE TABLE project_resource_links (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    authority TEXT NOT NULL CHECK(authority IN ('todos', 'conversations', 'knowledge', 'mementos')),
    service_instance TEXT NOT NULL,
    source_package TEXT NOT NULL CHECK(source_package IN ('@hasna/todos', '@hasna/conversations', '@hasna/knowledge', '@hasna/mementos')),
    target_kind TEXT NOT NULL CHECK(target_kind IN ('project', 'task_list', 'plan', 'channel', 'collection', 'item')),
    locator_kind TEXT NOT NULL CHECK(locator_kind IN ('external_uuid', 'canonical_uri', 'conversations_channel_id')),
    locator_value TEXT NOT NULL,
    scope TEXT NOT NULL CHECK(scope IN ('resource', 'collection')),
    labels_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value)
  );

  INSERT INTO project_resource_links (
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  )
  SELECT
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  FROM project_resource_links_v10;

  DROP TABLE project_resource_links_v10;

  CREATE INDEX idx_project_resource_links_project
    ON project_resource_links(project_id, authority, target_kind, id);

  CREATE TRIGGER project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value, scope
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (11);
  `,
    `
  DROP TRIGGER IF EXISTS project_resource_links_identity_immutable;
  DROP INDEX IF EXISTS idx_project_resource_links_project;

  ALTER TABLE project_resource_links RENAME TO project_resource_links_v11;

  CREATE TABLE project_resource_links (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    authority TEXT NOT NULL CHECK(authority IN ('todos', 'conversations', 'knowledge', 'mementos', 'orgs')),
    service_instance TEXT NOT NULL,
    source_package TEXT NOT NULL CHECK(source_package IN ('@hasna/todos', '@hasna/conversations', '@hasna/knowledge', '@hasna/mementos', '@hasna/orgs')),
    target_kind TEXT NOT NULL CHECK(target_kind IN ('org', 'project', 'task_list', 'plan', 'channel', 'collection', 'item')),
    locator_kind TEXT NOT NULL CHECK(locator_kind IN ('external_uuid', 'canonical_uri', 'conversations_channel_id')),
    locator_value TEXT NOT NULL,
    scope TEXT NOT NULL CHECK(scope IN ('resource', 'collection')),
    labels_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value)
  );

  INSERT INTO project_resource_links (
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  )
  SELECT
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  FROM project_resource_links_v11;

  DROP TABLE project_resource_links_v11;

  CREATE INDEX idx_project_resource_links_project
    ON project_resource_links(project_id, authority, target_kind, id);

  CREATE TRIGGER project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value, scope
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (12);
  `,
    `
  DROP TRIGGER IF EXISTS project_resource_links_identity_immutable;
  DROP INDEX IF EXISTS idx_project_resource_links_project;

  ALTER TABLE project_resource_links RENAME TO project_resource_links_v12;

  CREATE TABLE project_resource_links (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    authority TEXT NOT NULL CHECK(authority IN ('todos', 'conversations', 'knowledge', 'mementos', 'orgs', 'contacts')),
    service_instance TEXT NOT NULL,
    source_package TEXT NOT NULL CHECK(source_package IN ('@hasna/todos', '@hasna/conversations', '@hasna/knowledge', '@hasna/mementos', '@hasna/orgs', '@hasna/contacts')),
    target_kind TEXT NOT NULL CHECK(target_kind IN ('contact', 'org', 'project', 'task_list', 'plan', 'channel', 'collection', 'item')),
    locator_kind TEXT NOT NULL CHECK(locator_kind IN ('external_uuid', 'canonical_uri', 'conversations_channel_id')),
    locator_value TEXT NOT NULL,
    scope TEXT NOT NULL CHECK(scope IN ('resource', 'collection')),
    labels_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value)
  );

  INSERT INTO project_resource_links (
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  )
  SELECT
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  FROM project_resource_links_v12;

  DROP TABLE project_resource_links_v12;

  CREATE INDEX idx_project_resource_links_project
    ON project_resource_links(project_id, authority, target_kind, id);

  CREATE TRIGGER project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value, scope
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (13);
  `,
    `
  DROP TRIGGER IF EXISTS project_resource_links_identity_immutable;
  DROP INDEX IF EXISTS idx_project_resource_links_project;

  ALTER TABLE project_resource_links RENAME TO project_resource_links_v13;

  CREATE TABLE project_resource_links (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    authority TEXT NOT NULL CHECK(authority IN ('todos', 'conversations', 'knowledge', 'mementos', 'orgs', 'contacts')),
    service_instance TEXT NOT NULL,
    source_package TEXT NOT NULL CHECK(source_package IN ('@hasna/todos', '@hasna/conversations', '@hasna/knowledge', '@hasna/mementos', '@hasna/orgs', '@hasna/contacts')),
    target_kind TEXT NOT NULL CHECK(target_kind IN ('contact', 'org', 'project', 'task', 'task_list', 'plan', 'channel', 'collection', 'item')),
    locator_kind TEXT NOT NULL CHECK(locator_kind IN ('external_uuid', 'canonical_uri', 'conversations_channel_id')),
    locator_value TEXT NOT NULL,
    scope TEXT NOT NULL CHECK(scope IN ('resource', 'collection')),
    labels_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value)
  );

  INSERT INTO project_resource_links (
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  )
  SELECT
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  FROM project_resource_links_v13;

  DROP TABLE project_resource_links_v13;

  CREATE INDEX idx_project_resource_links_project
    ON project_resource_links(project_id, authority, target_kind, id);

  CREATE TRIGGER project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value, scope
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (14);
  `,
    `
  DROP TRIGGER IF EXISTS project_resource_links_identity_immutable;

  CREATE TRIGGER project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  CREATE TABLE IF NOT EXISTS project_resource_link_migration_manifests (
    manifest_id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    operation_id TEXT NOT NULL,
    step_id TEXT NOT NULL,
    state TEXT NOT NULL CHECK(state IN (
      'planned', 'producer_applied', 'projects_applied', 'verified',
      'rollback_in_progress', 'rolled_back', 'retained_target', 'failed_reconcilable'
    )),
    expected_project_revision TEXT NOT NULL,
    desired_collection_digest TEXT NOT NULL,
    links_json TEXT NOT NULL,
    projects_forward_receipt_id TEXT,
    projects_inverse_receipt_id TEXT,
    projects_reference_proof_json TEXT,
    last_verified_projects_revision TEXT,
    last_verified_projects_digest TEXT,
    transition_version INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, operation_id, step_id)
  );

  CREATE TABLE IF NOT EXISTS project_resource_link_migration_events (
    event_id TEXT PRIMARY KEY,
    manifest_id TEXT NOT NULL REFERENCES project_resource_link_migration_manifests(manifest_id) ON DELETE CASCADE,
    transition_version INTEGER NOT NULL,
    from_state TEXT,
    to_state TEXT NOT NULL,
    request_digest TEXT NOT NULL,
    precondition_digest TEXT NOT NULL,
    evidence_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(manifest_id, transition_version)
  );

  CREATE INDEX IF NOT EXISTS idx_project_resource_link_migrations_project
    ON project_resource_link_migration_manifests(project_id, state, updated_at);
  CREATE INDEX IF NOT EXISTS idx_project_resource_link_migration_events_manifest
    ON project_resource_link_migration_events(manifest_id, transition_version);

  CREATE TRIGGER IF NOT EXISTS project_resource_link_migration_events_no_update
  BEFORE UPDATE ON project_resource_link_migration_events
  BEGIN
    SELECT RAISE(ABORT, 'project resource link migration events are append-only');
  END;

  CREATE TRIGGER IF NOT EXISTS project_resource_link_migration_events_no_delete
  BEFORE DELETE ON project_resource_link_migration_events
  BEGIN
    SELECT RAISE(ABORT, 'project resource link migration events are append-only');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (15);
  `,
    `
  INSERT OR IGNORE INTO machines (slug, status, role) VALUES
    ('station01', 'active', 'mirror-hub'),
    ('station02', 'active', 'mirror-hub'),
    ('station03', 'active', 'assignable'),
    ('station04', 'active', 'assignable'),
    ('station05', 'active', 'avoid'),
    ('station06', 'active', 'assignable'),
    ('station07', 'active', 'assignable'),
    ('station08', 'active', 'assignable'),
    ('station09', 'active', 'assignable'),
    ('station10', 'active', 'assignable'),
    ('station11', 'active', 'assignable'),
    ('station12', 'active', 'assignable'),
    ('station13', 'active', 'assignable'),
    ('station14', 'active', 'assignable'),
    ('station15', 'active', 'assignable'),
    ('station16', 'active', 'assignable');

  INSERT OR IGNORE INTO _migrations (id) VALUES (16);
  `,
    `
  DROP TRIGGER IF EXISTS project_resource_links_identity_immutable;
  DROP INDEX IF EXISTS idx_project_resource_links_project;

  ALTER TABLE project_resource_links RENAME TO project_resource_links_v16;

  CREATE TABLE project_resource_links (
    id TEXT PRIMARY KEY,
    project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    authority TEXT NOT NULL CHECK(authority IN ('todos', 'conversations', 'knowledge', 'mementos', 'orgs', 'contacts', 'files')),
    service_instance TEXT NOT NULL,
    source_package TEXT NOT NULL CHECK(source_package IN ('@hasna/todos', '@hasna/conversations', '@hasna/knowledge', '@hasna/mementos', '@hasna/orgs', '@hasna/contacts', '@hasna/files')),
    target_kind TEXT NOT NULL CHECK(target_kind IN ('contact', 'org', 'project', 'task', 'task_list', 'plan', 'channel', 'collection', 'item')),
    locator_kind TEXT NOT NULL CHECK(locator_kind IN ('external_uuid', 'canonical_uri', 'conversations_channel_id')),
    locator_value TEXT NOT NULL,
    scope TEXT NOT NULL CHECK(scope IN ('resource', 'collection')),
    labels_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now')),
    UNIQUE(project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value)
  );

  INSERT INTO project_resource_links (
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  )
  SELECT
    id, project_id, authority, service_instance, source_package, target_kind,
    locator_kind, locator_value, scope, labels_json, created_at, updated_at
  FROM project_resource_links_v16;

  DROP TABLE project_resource_links_v16;

  CREATE INDEX idx_project_resource_links_project
    ON project_resource_links(project_id, authority, target_kind, id);

  CREATE TRIGGER project_resource_links_identity_immutable
  BEFORE UPDATE OF project_id, authority, service_instance, source_package, target_kind, locator_kind, locator_value
  ON project_resource_links
  BEGIN
    SELECT RAISE(ABORT, 'project resource link identity is immutable');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (17);
  `,
    `
  CREATE TABLE IF NOT EXISTS project_relations (
    relation_id TEXT NOT NULL,
    version INTEGER NOT NULL,
    from_project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    to_project_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
    relation TEXT NOT NULL CHECK(relation IN ('parent_of', 'depends_on', 'related_to')),
    superseded_by INTEGER,
    superseded_at TEXT,
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    PRIMARY KEY (relation_id, version),
    UNIQUE (from_project_id, to_project_id, version),
    CHECK (length(relation_id) > 0),
    CHECK (version > 0),
    CHECK (from_project_id <> to_project_id),
    CHECK (superseded_by IS NULL OR superseded_by > version),
    CHECK ((superseded_by IS NULL) = (superseded_at IS NULL))
  );

  CREATE UNIQUE INDEX IF NOT EXISTS idx_project_relations_head
    ON project_relations(relation_id) WHERE superseded_by IS NULL;

  CREATE INDEX IF NOT EXISTS idx_project_relations_from
    ON project_relations(from_project_id, relation, relation_id);

  CREATE INDEX IF NOT EXISTS idx_project_relations_to
    ON project_relations(to_project_id, relation, relation_id);

  CREATE TRIGGER IF NOT EXISTS project_relations_history_immutable
  BEFORE UPDATE OF relation_id, version, from_project_id, to_project_id, relation, created_at
  ON project_relations
  BEGIN
    SELECT RAISE(ABORT, 'project relation history is immutable');
  END;

  CREATE TRIGGER IF NOT EXISTS project_relations_supersede_once
  BEFORE UPDATE OF superseded_by, superseded_at
  ON project_relations
  WHEN OLD.superseded_by IS NOT NULL OR NEW.superseded_by IS NULL
  BEGIN
    SELECT RAISE(ABORT, 'project relation rows are superseded at most once and never un-superseded');
  END;

  INSERT OR IGNORE INTO _migrations (id) VALUES (18);
  `
  ];
});

// src/lib/project-store-paths.ts
import { existsSync } from "fs";
import { homedir } from "os";
import { join, resolve } from "path";
import { homedir as pathsResolverHomedir } from "os";
import { join as pathsResolverJoin } from "path";
function pathsResolverAssertApp(app) {
  if (typeof app !== "string" || app.length === 0) {
    throw new TypeError("paths: app must be a non-empty string");
  }
  if (!PATHS_RESOLVER_APP_SLUG_RE.test(app)) {
    throw new TypeError(`paths: invalid app slug "${app}" \u2014 expected lowercase kebab-case ([a-z0-9]+(-[a-z0-9]+)*)`);
  }
}
function pathsResolverAssertKind(kind) {
  if (!Object.keys(PATHS_RESOLVER_KIND_ENV).includes(kind)) {
    throw new TypeError(`paths: invalid path kind "${kind}" \u2014 expected one of ${Object.keys(PATHS_RESOLVER_KIND_ENV).join(", ")}`);
  }
}
function pathsResolverBaseDir(kind, options) {
  pathsResolverAssertKind(kind);
  const env = options.env ?? process.env;
  const override = env[PATHS_RESOLVER_KIND_ENV[kind]];
  if (typeof override === "string" && override.length > 0)
    return override;
  const home = options.home ?? pathsResolverHomedir();
  const platform = options.platform ?? process.platform;
  if (platform === "darwin") {
    switch (kind) {
      case "config":
      case "data":
        return pathsResolverJoin(home, "Library", "Application Support", "Hasna");
      case "cache":
        return pathsResolverJoin(home, "Library", "Caches", "Hasna");
      case "state":
        return pathsResolverJoin(home, "Library", "Logs", "Hasna");
    }
  }
  switch (kind) {
    case "config":
      return pathsResolverJoin(home, ".config", "hasna");
    case "data":
      return pathsResolverJoin(home, ".local", "share", "hasna");
    case "state":
      return pathsResolverJoin(home, ".local", "state", "hasna");
    case "cache":
      return pathsResolverJoin(home, ".cache", "hasna");
  }
}
function pathsResolverResolve(kind, options) {
  pathsResolverAssertApp(options.app);
  const appSegment = options.internal === true ? pathsResolverJoin("internal", options.app) : options.app;
  return pathsResolverJoin(pathsResolverBaseDir(kind, options), appSegment);
}
function dataDir(options) {
  return pathsResolverResolve("data", options);
}
function assertProjectWorkspaceId(workspaceId) {
  if (!PROJECT_WORKSPACE_ID_PATTERN.test(workspaceId)) {
    throw new Error(`Invalid workspace id for project store path: ${workspaceId}`);
  }
  return workspaceId;
}
function effectiveHome() {
  return process.env["HOME"] || process.env["USERPROFILE"] || homedir();
}
function legacyHomeDir() {
  return resolve(join(effectiveHome(), ".hasna", "projects"));
}
function resolverHome() {
  return dataDir({ app: "projects", home: process.env["HOME"] || process.env["USERPROFILE"] || undefined });
}
function adoptResolverHome(resolved, env = process.env) {
  const dataOverride = env.HASNA_DATA_HOME;
  if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
    return true;
  return existsSync(join(resolved, "projects.db"));
}
function getProjectsHome() {
  const configured = process.env[PROJECTS_HOME_ENV]?.trim();
  if (configured)
    return resolve(configured);
  const resolved = resolverHome();
  return adoptResolverHome(resolved) ? resolve(resolved) : legacyHomeDir();
}
function projectWorkspaceStorePath(workspaceId) {
  return resolve(join(getProjectsHome(), "workspaces", assertProjectWorkspaceId(workspaceId)));
}
function projectDataStorePath(workspaceId) {
  return resolve(join(getProjectsHome(), "data", assertProjectWorkspaceId(workspaceId)));
}
function isProjectWorkspaceStorePath(workspaceId, path) {
  return Boolean(path && resolve(path) === projectWorkspaceStorePath(workspaceId));
}
var PATHS_RESOLVER_KIND_ENV, PATHS_RESOLVER_APP_SLUG_RE, PROJECTS_HOME_ENV = "HASNA_PROJECTS_HOME", PROJECT_WORKSPACE_ID_PATTERN;
var init_project_store_paths = __esm(() => {
  PATHS_RESOLVER_KIND_ENV = {
    config: "HASNA_CONFIG_HOME",
    data: "HASNA_DATA_HOME",
    state: "HASNA_STATE_HOME",
    cache: "HASNA_CACHE_HOME"
  };
  PATHS_RESOLVER_APP_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
  PROJECT_WORKSPACE_ID_PATTERN = /^wks_[A-Za-z0-9_-]{1,80}$/;
});

// src/db/database.ts
import { Database } from "bun:sqlite";
import { existsSync as existsSync2, mkdirSync } from "fs";
import { dirname, join as join2, resolve as resolve2 } from "path";
function getDbPath() {
  if (process.env[PROJECTS_DB_PATH_ENV]) {
    return process.env[PROJECTS_DB_PATH_ENV];
  }
  if (process.env[LEGACY_WORKSPACES_DB_PATH_ENV]) {
    return process.env[LEGACY_WORKSPACES_DB_PATH_ENV];
  }
  return join2(getProjectsHome(), "projects.db");
}
function ensureDir(filePath) {
  if (filePath === ":memory:")
    return;
  const dir = dirname(resolve2(filePath));
  if (!existsSync2(dir)) {
    mkdirSync(dir, { recursive: true });
  }
}
function refuseLocalStore(message) {
  localStoreRefusal = message;
}
function assertLocalStoreAllowed() {
  if (localStoreRefusal !== null)
    throw new LocalStoreRefusedError(localStoreRefusal);
}
function getDatabase(path) {
  if (path !== ":memory:")
    assertLocalStoreAllowed();
  if (path) {
    ensureDir(path);
    const db = new Database(path);
    db.run("PRAGMA journal_mode=WAL");
    db.run("PRAGMA busy_timeout=5000");
    db.run("PRAGMA foreign_keys=ON");
    runMigrations(db);
    return db;
  }
  const dbPath = getDbPath();
  if (!_db || _dbPath !== dbPath) {
    if (_db)
      _db.close();
    ensureDir(dbPath);
    _db = new Database(dbPath);
    _dbPath = dbPath;
    _db.run("PRAGMA journal_mode=WAL");
    _db.run("PRAGMA busy_timeout=5000");
    _db.run("PRAGMA foreign_keys=ON");
    runMigrations(_db);
  }
  return _db;
}
function now() {
  return new Date().toISOString().replace("T", " ").replace("Z", "");
}
function uuid() {
  return crypto.randomUUID();
}
var PROJECTS_DB_PATH_ENV = "HASNA_PROJECTS_DB_PATH", LEGACY_WORKSPACES_DB_PATH_ENV = "HASNA_WORKSPACES_DB_PATH", _db = null, _dbPath = null, localStoreRefusal = null, LocalStoreRefusedError;
var init_database = __esm(() => {
  init_schema();
  init_project_store_paths();
  LocalStoreRefusedError = class LocalStoreRefusedError extends Error {
    code = "REMOTE_COMMAND_UNSUPPORTED";
    constructor(message) {
      super(message);
      this.name = "LocalStoreRefusedError";
    }
  };
});

// src/lib/project-management.ts
import { existsSync as existsSync3 } from "fs";
function metadataHasOwn(metadata, key) {
  return Object.prototype.hasOwnProperty.call(metadata, key);
}
function normalizedLowerToken(value) {
  if (typeof value !== "string")
    return null;
  const normalized = value.trim().toLowerCase().replace(/[_\s]+/g, "-");
  return normalized || null;
}
function hasFinanceProjectMetadataIntent(metadata) {
  return normalizedLowerToken(metadata["business_area"]) === "finance";
}
function requiredFinanceMetadataString(metadata, field) {
  const value = metadata[field];
  if (typeof value !== "string" || !value.trim()) {
    throw new Error(`Finance project metadata ${field} must be a non-empty string`);
  }
  const normalized = value.trim();
  if (normalized.length > FINANCE_METADATA_TEXT_MAX_LENGTH) {
    throw new Error(`Finance project metadata ${field} must be at most ${FINANCE_METADATA_TEXT_MAX_LENGTH} characters`);
  }
  return normalized;
}
function normalizeFinanceLegalEntities(value) {
  if (!Array.isArray(value) || value.length === 0) {
    throw new Error("Finance project metadata legal_entities must be a non-empty array of strings");
  }
  if (value.length > FINANCE_LEGAL_ENTITY_MAX_ITEMS) {
    throw new Error(`Finance project metadata legal_entities must contain at most ${FINANCE_LEGAL_ENTITY_MAX_ITEMS} items`);
  }
  const entities = [];
  const seen = new Set;
  for (const item of value) {
    if (typeof item !== "string" || !item.trim()) {
      throw new Error("Finance project metadata legal_entities must be a non-empty array of strings");
    }
    const entity = item.trim();
    if (entity.length > FINANCE_LEGAL_ENTITY_MAX_LENGTH) {
      throw new Error(`Finance project metadata legal_entities entries must be at most ${FINANCE_LEGAL_ENTITY_MAX_LENGTH} characters`);
    }
    if (seen.has(entity))
      continue;
    seen.add(entity);
    entities.push(entity);
  }
  if (entities.length === 0) {
    throw new Error("Finance project metadata legal_entities must be a non-empty array of strings");
  }
  return entities;
}
function normalizeProjectMetadata(metadata, existingMetadata) {
  const next = { ...metadata ?? {} };
  const explicitlyClearsFinance = metadataHasOwn(next, "business_area") && next["business_area"] === null;
  const isFinance = hasFinanceProjectMetadataIntent(next) || (!explicitlyClearsFinance && existingMetadata ? hasFinanceProjectMetadataIntent(existingMetadata) : false);
  if (!isFinance) {
    if (explicitlyClearsFinance)
      delete next["business_area"];
    return next;
  }
  const missing = FINANCE_PROJECT_METADATA_FIELDS.filter((field) => !metadataHasOwn(next, field));
  if (missing.length > 0) {
    throw new Error(`Finance project metadata is missing required fields: ${missing.join(", ")}`);
  }
  const businessArea = normalizedLowerToken(next["business_area"]);
  if (businessArea !== "finance") {
    throw new Error('Finance project metadata business_area must be "finance"');
  }
  const jurisdiction = requiredFinanceMetadataString(next, "jurisdiction").toUpperCase();
  if (!FINANCE_JURISDICTION_PATTERN.test(jurisdiction)) {
    throw new Error("Finance project metadata jurisdiction must be a stable 2-64 character identifier");
  }
  const fiscalCycle = normalizedLowerToken(next["fiscal_cycle"]);
  if (!fiscalCycle || !FINANCE_FISCAL_CYCLES.includes(fiscalCycle)) {
    throw new Error(`Finance project metadata fiscal_cycle must be one of: ${FINANCE_FISCAL_CYCLES.join(", ")}`);
  }
  const classification = normalizedLowerToken(next["data_classification"]);
  if (!classification || !FINANCE_DATA_CLASSIFICATIONS.includes(classification)) {
    throw new Error(`Finance project metadata data_classification must be one of: ${FINANCE_DATA_CLASSIFICATIONS.join(", ")}`);
  }
  const profile = {
    schema: FINANCE_PROJECT_METADATA_SCHEMA,
    business_area: "finance",
    jurisdiction,
    legal_entities: normalizeFinanceLegalEntities(next["legal_entities"]),
    fiscal_cycle: fiscalCycle,
    data_classification: classification,
    retention_policy: requiredFinanceMetadataString(next, "retention_policy"),
    ledger_authority: requiredFinanceMetadataString(next, "ledger_authority"),
    evidence_store: requiredFinanceMetadataString(next, "evidence_store"),
    approver: requiredFinanceMetadataString(next, "approver"),
    external_recipient_policy: requiredFinanceMetadataString(next, "external_recipient_policy")
  };
  const profileBytes = Buffer.byteLength(JSON.stringify(profile), "utf8");
  if (profileBytes > FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES) {
    throw new Error(`Finance project metadata exceeds ${FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES}-byte context budget`);
  }
  const { schema: _schema, ...storedProfile } = profile;
  return {
    ...next,
    ...storedProfile
  };
}
function stringValue(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function startWindowsValue(value) {
  if (!Array.isArray(value))
    return [];
  return value.flatMap((item) => {
    if (!item || typeof item !== "object")
      return [];
    const window = item;
    const name = typeof window.name === "string" ? window.name.trim() : "";
    if (!name)
      return [];
    return [{
      name,
      path: typeof window.path === "string" && window.path.trim() ? window.path.trim() : undefined,
      command: typeof window.command === "string" && window.command.trim() ? window.command.trim() : undefined,
      index: typeof window.index === "number" ? window.index : undefined,
      detached: typeof window.detached === "boolean" ? window.detached : undefined
    }];
  });
}
function projectManagementSummary(project) {
  return {
    stage: stringValue(project.metadata.stage),
    priority: stringValue(project.metadata.priority),
    owner: stringValue(project.metadata.owner),
    launch_profile: stringValue(project.metadata.launch_profile),
    start_agent: stringValue(project.metadata.start_agent),
    start_command: stringValue(project.metadata.start_command),
    start_session_policy: stringValue(project.metadata.start_session_policy),
    start_windows: startWindowsValue(project.metadata.start_windows),
    todos_project_id: project.integrations.todos_project_id ?? null,
    todos_task_list_id: project.integrations.todos_task_list_id ?? null,
    brief_id: project.integrations.brief_id ?? null,
    brief_path: project.integrations.brief_path ?? null,
    canvases_project_id: project.integrations.canvases_project_id ?? null,
    canvases_default_canvas_id: project.integrations.canvases_default_canvas_id ?? null
  };
}
function projectExternalLinksSummary(project) {
  const todosProjectId = project.integrations.todos_project_id ?? null;
  const todosTaskListId = project.integrations.todos_task_list_id ?? null;
  const briefId = project.integrations.brief_id ?? null;
  const briefPath = project.integrations.brief_path ?? null;
  const briefLinked = Boolean(briefId || briefPath);
  const canvasesProjectId = project.integrations.canvases_project_id ?? null;
  const canvasesDefaultCanvasId = project.integrations.canvases_default_canvas_id ?? null;
  return {
    todos: {
      linked: Boolean(todosProjectId || todosTaskListId),
      status: todosProjectId || todosTaskListId ? "linked" : "unlinked",
      project_id: todosProjectId,
      task_list_id: todosTaskListId
    },
    brief: {
      linked: briefLinked,
      status: briefLinked ? "linked" : "unlinked",
      id: briefId,
      path: briefPath,
      path_exists: briefPath ? existsSync3(briefPath) : null
    },
    canvases: {
      linked: Boolean(canvasesProjectId || canvasesDefaultCanvasId),
      status: canvasesProjectId || canvasesDefaultCanvasId ? "linked" : "unlinked",
      project_id: canvasesProjectId,
      default_canvas_id: canvasesDefaultCanvasId
    }
  };
}
function projectPathHealth(project) {
  if (!project.primary_path) {
    return {
      status: project.kind === "remote-only" ? "remote-only" : "unknown",
      path: null,
      exists: null
    };
  }
  const exists = existsSync3(project.primary_path);
  return {
    status: exists ? "ok" : "missing",
    path: project.primary_path,
    exists
  };
}
function projectDashboardSummary(project) {
  const management = projectManagementSummary(project);
  return {
    management,
    external_links: projectExternalLinksSummary(project),
    path_health: projectPathHealth(project),
    launch: {
      default_agent: management.start_agent,
      default_command: management.start_command,
      default_profile: management.launch_profile,
      default_session_policy: management.start_session_policy,
      default_windows: management.start_windows,
      last_opened_at: project.last_opened_at
    }
  };
}
var PROJECT_STAGES, PROJECT_PRIORITIES, FINANCE_PROJECT_METADATA_SCHEMA = "hasna.projects.finance_project_metadata.v1", FINANCE_PROJECT_METADATA_FIELDS, FINANCE_FISCAL_CYCLES, FINANCE_DATA_CLASSIFICATIONS, FINANCE_JURISDICTION_PATTERN, FINANCE_METADATA_TEXT_MAX_LENGTH = 512, FINANCE_LEGAL_ENTITY_MAX_LENGTH = 256, FINANCE_LEGAL_ENTITY_MAX_ITEMS = 100, FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES;
var init_project_management = __esm(() => {
  PROJECT_STAGES = ["idea", "planned", "active", "paused", "shipped", "maintenance"];
  PROJECT_PRIORITIES = ["low", "medium", "high", "critical"];
  FINANCE_PROJECT_METADATA_FIELDS = [
    "business_area",
    "jurisdiction",
    "legal_entities",
    "fiscal_cycle",
    "data_classification",
    "retention_policy",
    "ledger_authority",
    "evidence_store",
    "approver",
    "external_recipient_policy"
  ];
  FINANCE_FISCAL_CYCLES = ["monthly", "quarterly", "annual", "event-driven"];
  FINANCE_DATA_CLASSIFICATIONS = ["public", "internal", "confidential", "restricted"];
  FINANCE_JURISDICTION_PATTERN = /^[A-Z0-9][A-Z0-9._:-]{1,63}$/;
  FINANCE_PROJECT_METADATA_CONTEXT_MAX_BYTES = 4 * 1024;
});

// src/lib/redaction.ts
function isSensitiveProjectKey(key) {
  return SENSITIVE_KEY_PATTERN.test(key.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase());
}
function redactProjectText(value) {
  if (!MAYBE_SECRET_TEXT_PATTERN.test(value))
    return value;
  return value.replace(PRIVATE_KEY_PATTERN, PROJECT_REDACTED_VALUE).replace(URL_CREDENTIAL_PATTERN, `$1${PROJECT_REDACTED_VALUE}@`).replace(AUTH_HEADER_PATTERN, `$1 ${PROJECT_REDACTED_VALUE}`).replace(CLI_SECRET_FLAG_PATTERN, `$1${PROJECT_REDACTED_VALUE}`).replace(KNOWN_SECRET_VALUE_PATTERN, PROJECT_REDACTED_VALUE).replace(ENV_ASSIGNMENT_PATTERN, `$1$2=${PROJECT_REDACTED_VALUE}`);
}
function redactProjectValue(value) {
  return redactUnknown(value, undefined, new WeakSet);
}
function redactUnknown(value, key, seen) {
  if (key && isSensitiveProjectKey(key))
    return PROJECT_REDACTED_VALUE;
  if (typeof value === "string")
    return redactProjectText(value);
  if (value === null || value === undefined)
    return value;
  if (typeof value !== "object")
    return value;
  if (seen.has(value))
    return "[Circular]";
  seen.add(value);
  if (Array.isArray(value)) {
    const redactedArray = value.map((item) => redactUnknown(item, key, seen));
    seen.delete(value);
    return redactedArray;
  }
  const redacted = {};
  for (const [childKey, childValue] of Object.entries(value)) {
    redacted[childKey] = redactUnknown(childValue, childKey, seen);
  }
  seen.delete(value);
  return redacted;
}
var PROJECT_REDACTED_VALUE = "[REDACTED]", SENSITIVE_KEY_PATTERN, URL_CREDENTIAL_PATTERN, AUTH_HEADER_PATTERN, CLI_SECRET_FLAG_PATTERN, PRIVATE_KEY_PATTERN, KNOWN_SECRET_VALUE_PATTERN, ENV_ASSIGNMENT_PATTERN, MAYBE_SECRET_TEXT_PATTERN;
var init_redaction = __esm(() => {
  SENSITIVE_KEY_PATTERN = /(^|[^a-z0-9])(password|passwd|pwd|secret|token|api[-_]?key|apikey|access[-_]?key|private[-_]?key|client[-_]?secret|credential|credentials|authorization|auth[-_]?header|cookie|session[-_]?token|npmrc|database[-_]?url|connection[-_]?string|dsn)([^a-z0-9]|$)/i;
  URL_CREDENTIAL_PATTERN = /\b([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s@]+)@/gi;
  AUTH_HEADER_PATTERN = /\b(Bearer|Basic)\s+[A-Za-z0-9+/_=:.~\-]+/gi;
  CLI_SECRET_FLAG_PATTERN = /((?:^|[\s,;])--?(?:password|passwd|pwd|secret|token|api[-_]?key|apikey|access[-_]?key|private[-_]?key|client[-_]?secret|credential|credentials|authorization|auth[-_]?header|cookie|session[-_]?token|npmrc|database[-_]?url|connection[-_]?string|dsn)(?:=|\s+))([^\s"'`,;]+)/gi;
  PRIVATE_KEY_PATTERN = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g;
  KNOWN_SECRET_VALUE_PATTERN = /\b(sk-[A-Za-z0-9_-]{16,}|ghp\x5f[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9_]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})\b/g;
  ENV_ASSIGNMENT_PATTERN = /(^|[\s,;])([A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY|ACCESS_KEY|PRIVATE_KEY|CLIENT_SECRET|COOKIE|DSN|DATABASE_URL|CONNECTION_STRING)[A-Za-z0-9_]*)=([^\s"'`,;]+)/g;
  MAYBE_SECRET_TEXT_PATTERN = /:\/\/|PRIVATE KEY|Bearer\s|Basic\s|TOKEN|SECRET|PASSWORD|API_KEY|ACCESS_KEY|PRIVATE_KEY|CLIENT_SECRET|COOKIE|DSN|DATABASE_URL|CONNECTION_STRING|sk-|ghp\x5f|github_pat_|npm_|xox[baprs]-|AKIA/i;
});

// src/lib/guarded-project-mutation.ts
import { createHash } from "crypto";
function assertCompleteStableProjectId(value) {
  if (!COMPLETE_STABLE_PROJECT_ID_RE.test(value)) {
    throw new Error("guarded project mutation requires a complete stable project id beginning with wks_; slugs, paths, names, and partial ids are refused");
  }
}
function assertPositiveBounds(bounds) {
  if (!Number.isInteger(bounds.response_byte_limit) || bounds.response_byte_limit <= 0) {
    throw new Error("response_byte_limit must be a positive integer");
  }
  if (!Number.isInteger(bounds.time_budget_ms) || bounds.time_budget_ms <= 0) {
    throw new Error("time_budget_ms must be a positive integer");
  }
}
function canonicalJson(value) {
  return JSON.stringify(canonicalize(value));
}
function canonicalize(value) {
  if (Array.isArray(value))
    return value.map((item) => canonicalize(item));
  if (!value || typeof value !== "object")
    return value;
  const out = {};
  for (const key of Object.keys(value).sort()) {
    const next = value[key];
    if (next !== undefined)
      out[key] = canonicalize(next);
  }
  return out;
}
function sha256(value) {
  return createHash("sha256").update(value).digest("hex");
}
function requestDigest(patch) {
  return sha256(canonicalJson(normalizePatch(patch)));
}
function preconditionDigest(input) {
  return sha256(canonicalJson({ project_id: input.project_id, revision: input.expected_revision }));
}
function deriveGuardedIdempotencyKey(input) {
  return `gpm_${sha256(canonicalJson({
    route: GUARDED_PROJECT_MUTATION_ROUTE,
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: input.direction,
    target_id: input.target_id,
    request_digest: input.request_digest,
    precondition_digest: input.precondition_digest
  })).slice(0, 48)}`;
}
function normalizePatch(patch) {
  const allowed = {};
  const keys = [
    "name",
    "slug",
    "description",
    "kind",
    "status",
    "root_id",
    "recipe_id",
    "canonical_machine",
    "primary_path",
    "git_remote",
    "s3_bucket",
    "s3_prefix",
    "tags",
    "integrations",
    "metadata",
    "last_opened_at",
    "agent_id",
    "source",
    "prompt",
    "command"
  ];
  for (const key of keys) {
    if (patch[key] !== undefined) {
      allowed[key] = patch[key];
    }
  }
  return canonicalize(allowed);
}
function workspaceRevision(workspace) {
  if (!workspace.updated_at)
    throw new Error(`project ${workspace.id} has no authority revision`);
  return workspace.updated_at;
}
function workspaceSnapshot(workspace) {
  return canonicalize(workspace);
}
function rowToGuardedReceipt(row) {
  return {
    receipt_id: row.receipt_id,
    operation_id: row.operation_id,
    step_id: row.step_id,
    direction: row.direction,
    idempotency_key: row.idempotency_key,
    target_id: row.target_id,
    request_digest: row.request_digest,
    precondition_digest: row.precondition_digest,
    expected_revision: row.expected_revision,
    outcome: row.outcome,
    reason: row.reason,
    result_project_id: row.result_project_id,
    duplicate_of_receipt_id: row.duplicate_of_receipt_id,
    before: parseJson(row.before_json),
    after: parseJson(row.after_json),
    post_revision: row.post_revision,
    created_at: row.created_at
  };
}
function parseJson(raw) {
  if (!raw)
    return null;
  return JSON.parse(raw);
}
function timedOut(startedAtMs, timeBudgetMs) {
  return Date.now() - startedAtMs > timeBudgetMs;
}
function responseControl(payload, bounds, startedAtMs, operation = "guarded mutation", completeness = {
  complete: true,
  truncated: false
}) {
  assertPositiveBounds(bounds);
  const bytes = Buffer.byteLength(JSON.stringify(payload), "utf8");
  const elapsed = Math.max(Date.now() - startedAtMs, 0);
  if (bytes > bounds.response_byte_limit) {
    throw new Error(`${operation} response byte budget exceeded: ${bytes} > ${bounds.response_byte_limit}`);
  }
  if (elapsed > bounds.time_budget_ms) {
    throw new Error(`${operation} time budget exceeded: ${elapsed} > ${bounds.time_budget_ms}`);
  }
  return {
    response_byte_limit: bounds.response_byte_limit,
    time_budget_ms: bounds.time_budget_ms,
    response_bytes: bytes,
    elapsed_ms: elapsed,
    ...completeness
  };
}
function withResponseControl(payload, bounds, startedAtMs, operation = "guarded mutation", completeness = {
  complete: true,
  truncated: false
}) {
  const envelope = {
    ...payload,
    response_control: {
      response_byte_limit: bounds.response_byte_limit,
      time_budget_ms: bounds.time_budget_ms,
      response_bytes: 0,
      elapsed_ms: 0,
      ...completeness
    }
  };
  envelope.response_control = responseControl(envelope, bounds, startedAtMs, operation, completeness);
  envelope.response_control = responseControl(envelope, bounds, startedAtMs, operation, completeness);
  return envelope;
}
function buildGuardedProjectReadResult(project, input, startedAtMs, resourceLinks = { links: [], max_items: 1000, collection_digest: sha256("[]") }) {
  assertCompleteStableProjectId(input.project_id);
  assertPositiveBounds(input);
  if (project.id !== input.project_id) {
    throw new Error(`guarded project read target mismatch: requested ${input.project_id}, received ${project.id}`);
  }
  return withResponseControl({
    ok: true,
    project_id: project.id,
    project,
    current_revision: workspaceRevision(project),
    resource_links: resourceLinks.links,
    resource_link_count: resourceLinks.links.length,
    resource_link_max_items: resourceLinks.max_items,
    resource_link_collection_digest: resourceLinks.collection_digest
  }, input, startedAtMs, "guarded project read");
}
function buildReceiptId(input) {
  return `gpmr_${sha256(canonicalJson(input)).slice(0, 32)}`;
}
var GUARDED_PROJECT_MUTATION_ROUTE = "projects.guarded-metadata-mutation.v1", COMPLETE_STABLE_PROJECT_ID_PATTERN = "^wks_[A-Za-z0-9_-]{12,}$", COMPLETE_STABLE_PROJECT_ID_RE;
var init_guarded_project_mutation = __esm(() => {
  COMPLETE_STABLE_PROJECT_ID_RE = new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN);
});

// src/lib/env.ts
var alias = (...keys) => {
  for (const key of keys) {
    const value = process.env[key];
    if (value)
      return value;
  }
  return;
}, env;
var init_env = __esm(() => {
  env = {
    json: () => alias("HASNA_PROJECTS_JSON", "PROJECTS_JSON"),
    reportsToken: () => alias("HASNA_PROJECTS_REPORTS_TOKEN", "PROJECTS_REPORTS_TOKEN"),
    conversationsBin: () => alias("HASNA_PROJECTS_CONVERSATIONS_BIN", "PROJECTS_CONVERSATIONS_BIN"),
    agentModel: () => alias("HASNA_PROJECTS_AGENT_MODEL", "PROJECTS_AGENT_MODEL"),
    agentContextLimit: () => alias("HASNA_PROJECTS_AGENT_CONTEXT_LIMIT", "PROJECTS_AGENT_CONTEXT_LIMIT"),
    openrouterApiKey: () => alias("HASNA_PROJECTS_OPENROUTER_API_KEY", "OPENROUTER_API_KEY", "PROJECTS_OPENROUTER_API_KEY"),
    openrouterSecretKey: () => alias("HASNA_PROJECTS_OPENROUTER_SECRET_KEY", "PROJECTS_OPENROUTER_SECRET_KEY"),
    useSecrets: () => alias("HASNA_PROJECTS_USE_SECRETS", "PROJECTS_USE_SECRETS"),
    modelPricingJson: () => alias("HASNA_PROJECTS_MODEL_PRICING_JSON", "PROJECTS_MODEL_PRICING_JSON")
  };
});

// src/lib/project-channel-guard.ts
function normalizeProjectChannelName(value) {
  return value.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/[^a-z0-9.-]/g, "").replace(/-{2,}/g, "-").replace(/^[-.]+|[-.]+$/g, "");
}
function conversationsCliRunner(binary) {
  const executable = binary?.trim() || env.conversationsBin()?.trim() || "conversations";
  return (args) => {
    try {
      const result = Bun.spawnSync({
        cmd: [executable, ...args],
        stdout: "pipe",
        stderr: "pipe",
        stdin: "ignore",
        timeout: CONVERSATIONS_CLI_TIMEOUT_MS
      });
      return {
        ok: result.exitCode === 0,
        stdout: Buffer.from(result.stdout).toString("utf-8"),
        stderr: Buffer.from(result.stderr).toString("utf-8")
      };
    } catch (err) {
      return { ok: false, stdout: "", stderr: err instanceof Error ? err.message : String(err) };
    }
  };
}
function conversationsChannelListResult(result) {
  if (!result.ok) {
    return { ok: false, detail: result.stderr.trim() || result.stdout.trim() || "conversations channel list failed" };
  }
  let rows;
  try {
    rows = JSON.parse(result.stdout);
  } catch {
    return { ok: false, detail: "could not parse conversations channel list JSON output" };
  }
  if (!Array.isArray(rows)) {
    return { ok: false, detail: "conversations channel list JSON output was not an array" };
  }
  const names = rows.map((row) => row && typeof row === "object" && typeof row.name === "string" ? row.name : "").filter((name) => name.length > 0);
  return { ok: true, names };
}
function conversationsChannelExistence(names, channel) {
  const target = normalizeProjectChannelName(channel);
  const exists = names.some((name) => normalizeProjectChannelName(name) === target);
  return exists ? { verdict: "exists" } : { verdict: "missing" };
}
function conversationsCliChannelProbe(binary) {
  const executable = binary?.trim() || env.conversationsBin()?.trim() || "conversations";
  return (channel) => {
    if (!channelNameListCache.has(executable)) {
      channelNameListCache.set(executable, conversationsChannelListResult(conversationsCliRunner(executable)(["channel", "list", "-j"])));
    }
    const cached = channelNameListCache.get(executable);
    if (!cached.ok)
      return { verdict: "unknown", detail: cached.detail };
    return conversationsChannelExistence(cached.names, channel);
  };
}
function shouldProbeConversationsChannel(envValue = process.env) {
  const flag = (envValue["HASNA_PROJECTS_CHANNEL_VERIFY"] ?? envValue["PROJECTS_CHANNEL_VERIFY"])?.trim().toLowerCase();
  if (flag) {
    if (["1", "true", "on", "yes"].includes(flag))
      return true;
    if (["0", "false", "off", "no"].includes(flag))
      return false;
  }
  if (envValue["NODE_ENV"] === "test")
    return false;
  return true;
}
function projectChannelWriteProbe(envValue = process.env) {
  return shouldProbeConversationsChannel(envValue) ? conversationsCliChannelProbe() : undefined;
}
function changedProjectChannel(next, previous) {
  const normalized = (value) => {
    const trimmed = value?.trim();
    return trimmed ? normalizeProjectChannelName(trimmed) : null;
  };
  const nextChannel = normalized(next?.[PROJECT_CHANNEL_INTEGRATION_KEY]);
  const previousChannel = normalized(previous?.[PROJECT_CHANNEL_INTEGRATION_KEY]);
  if (!nextChannel || nextChannel === previousChannel)
    return null;
  return nextChannel;
}
function assertProjectChannelWritable(channel, options = {}) {
  const target = channel?.trim();
  if (!target)
    return;
  const probe = options.probe;
  if (!probe)
    return;
  const result = probe(target);
  if (result.verdict !== "missing")
    return;
  throw new Error(`Refusing to pin integrations.${PROJECT_CHANNEL_INTEGRATION_KEY} "${target}": the conversations app has no channel with that name, ` + `so a project-channel post would fail closed (HTTP 400 "Channel \\"${target}\\" does not exist, so this message was not sent.") ` + `or land in an agent DM of the same name instead of in a channel. ` + `Create the channel first (conversations channel create ${target}) or point the project at a channel that exists ` + `(conversations channel list -j). Set HASNA_PROJECTS_CHANNEL_VERIFY=0 to skip this check.`);
}
function assertProjectChannelIntegrationWritable(next, previous, options = {}) {
  const channel = changedProjectChannel(next, previous);
  if (!channel)
    return;
  const probe = options.probe ?? projectChannelWriteProbe(options.env);
  assertProjectChannelWritable(channel, { probe });
}
var PROJECT_CHANNEL_INTEGRATION_KEY = "conversations_channel", CONVERSATIONS_CLI_TIMEOUT_MS = 15000, channelNameListCache;
var init_project_channel_guard = __esm(() => {
  init_env();
  channelNameListCache = new Map;
});

// src/types/workspace.ts
var WORKSPACE_KINDS, AGENT_KINDS, PROJECT_RESOURCE_AUTHORITIES, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS = 1000, PROJECT_RELATIONS, PROJECT_RELATION_ACYCLIC_KINDS, PROJECT_RELATION_DEFAULT_MAX_ITEMS = 1000;
var init_workspace = __esm(() => {
  WORKSPACE_KINDS = [
    "open-source",
    "internal-app",
    "platform",
    "company-website",
    "scaffold",
    "community",
    "project",
    "experiment",
    "docs",
    "remote-only",
    "generic"
  ];
  AGENT_KINDS = ["human", "ai", "service", "cli"];
  PROJECT_RESOURCE_AUTHORITIES = ["todos", "conversations", "knowledge", "mementos", "orgs", "contacts", "files"];
  PROJECT_RELATIONS = ["parent_of", "depends_on", "related_to"];
  PROJECT_RELATION_ACYCLIC_KINDS = ["parent_of", "depends_on"];
});

// src/lib/project-resource-links.ts
import {
  ProjectResourceLinkCollectionV1Schema,
  ProjectResourceLinkInputSchema,
  ProjectResourceLinkSchema
} from "@hasna/contracts/schemas";
function projectResourceLinkConversationsChannelLocatorKind(value) {
  if (UUID_RE.test(value))
    return "external_uuid";
  if (CONVERSATIONS_CHANNEL_ID_RE.test(value))
    return "conversations_channel_id";
  return null;
}
function assertClosedObject(value, allowed, label) {
  for (const key of Object.keys(value)) {
    if (!allowed.has(key))
      throw new Error(`${label} contains unknown field '${key}'`);
  }
}
function requiredString(value, label) {
  if (typeof value !== "string" || !value.trim())
    throw new Error(`${label} must be a non-empty string`);
  return value.trim();
}
function canonicalProjectResourceLinkUri(value, label) {
  if (URN_RE.test(value))
    return value;
  let url;
  try {
    url = new URL(value);
  } catch {
    throw new Error(`${label} must be a canonical https URI or URN`);
  }
  if (url.protocol !== "https:" || url.username || url.password) {
    throw new Error(`${label} must be a non-secret canonical https URI or URN`);
  }
  if (url.search || url.hash)
    throw new Error(`${label} must not contain query or fragment components`);
  return url.toString();
}
function assertProjectResourceLinkServiceInstanceWritable(authority, serviceInstance) {
  const canonical = canonicalProjectResourceLinkUri(serviceInstance, "resource link service_instance");
  if (!URN_SERVICE_INSTANCE_AUTHORITIES.includes(authority))
    return canonical;
  const segments = canonical.split(":");
  if (segments[0] === "urn") {
    if (segments[1] === "hasna" && segments[2] === authority && segments[3] === "service" && segments[4]) {
      return canonical;
    }
    throw new Error(`resource link service_instance urn must be authority-qualified as urn:hasna:${authority}:service:...; got '${canonical}'`);
  }
  throw new Error(`resource link service_instance must be the authority-qualified urn form ${PROJECT_RESOURCE_SERVICE_INSTANCE_URN_FORM}, not a bare service URL; got '${canonical}'`);
}
function assertProjectResourceLinksWritable(links) {
  for (const link of links) {
    assertProjectResourceLinkServiceInstanceWritable(link.authority, link.service_instance);
  }
}
function normalizeLabels(value) {
  if (value === undefined)
    return {};
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error("resource link labels must be an object");
  }
  assertClosedObject(value, LABEL_FIELDS, "resource link labels");
  const raw = value;
  const labels = {};
  if (raw["name"] !== undefined)
    labels.name = requiredString(raw["name"], "resource link labels.name");
  if (raw["channel_name"] !== undefined)
    labels.channel_name = requiredString(raw["channel_name"], "resource link labels.channel_name");
  if (raw["path"] !== undefined)
    labels.path = requiredString(raw["path"], "resource link labels.path");
  if (raw["tags"] !== undefined) {
    if (!Array.isArray(raw["tags"]) || raw["tags"].some((tag) => typeof tag !== "string")) {
      throw new Error("resource link labels.tags must be an array of strings");
    }
    labels.tags = [...new Set(raw["tags"].map((tag) => tag.trim()).filter(Boolean))].sort();
  }
  return labels;
}
function normalizeProjectResourceLink(input) {
  if (!input || typeof input !== "object" || Array.isArray(input))
    throw new Error("resource link must be an object");
  assertClosedObject(input, LINK_FIELDS, "resource link");
  if (!PROJECT_RESOURCE_AUTHORITIES.includes(input.authority)) {
    throw new Error("resource link authority is unsupported");
  }
  const authority = input.authority;
  const serviceInstance = canonicalProjectResourceLinkUri(requiredString(input.service_instance, "resource link service_instance"), "resource link service_instance");
  const expectedPackage = SOURCE_PACKAGE_BY_AUTHORITY[authority];
  if (input.source_package !== expectedPackage) {
    throw new Error(`resource link source_package for ${authority} must be ${expectedPackage}`);
  }
  if (!TARGET_KINDS_BY_AUTHORITY[authority].includes(input.target_kind)) {
    throw new Error(`resource link target_kind '${input.target_kind}' is not valid for ${authority}`);
  }
  if (!input.locator || typeof input.locator !== "object" || Array.isArray(input.locator)) {
    throw new Error("resource link locator must be an object");
  }
  assertClosedObject(input.locator, LOCATOR_FIELDS, "resource link locator");
  const locatorValue = requiredString(input.locator.value, "resource link locator.value");
  let normalizedLocatorValue;
  if (input.locator.kind === "external_uuid") {
    if (projectResourceLinkConversationsChannelLocatorKind(locatorValue) !== "external_uuid") {
      throw new Error("resource link external_uuid must be a complete UUID");
    }
    normalizedLocatorValue = locatorValue.toLowerCase();
  } else if (input.locator.kind === "canonical_uri") {
    normalizedLocatorValue = canonicalProjectResourceLinkUri(locatorValue, "resource link canonical_uri");
  } else if (input.locator.kind === "conversations_channel_id") {
    if (projectResourceLinkConversationsChannelLocatorKind(locatorValue) !== "conversations_channel_id") {
      throw new Error("resource link conversations channel ID must match chn_<32hex>");
    }
    normalizedLocatorValue = locatorValue.toLowerCase();
  } else {
    throw new Error("resource link locator.kind must be external_uuid, canonical_uri, or conversations_channel_id");
  }
  const locator = {
    kind: input.locator.kind,
    value: normalizedLocatorValue
  };
  if (input.scope !== "resource" && input.scope !== "collection") {
    throw new Error("resource link scope must be resource or collection");
  }
  const labels = normalizeLabels(input.labels);
  if (locator.kind === "conversations_channel_id" && !(authority === "conversations" && input.target_kind === "channel")) {
    throw new Error("resource link conversations_channel_id is only valid for Conversations channel links");
  }
  if (input.authority === "todos" && input.target_kind === "task") {
    if (locator.kind !== "external_uuid") {
      throw new Error("Todos task links require a complete external_uuid task ID");
    }
    const taskLocator = { kind: "external_uuid", value: locator.value };
    return ProjectResourceLinkInputSchema.parse({
      ...input,
      service_instance: serviceInstance,
      locator: taskLocator,
      labels
    });
  }
  if (authority === "conversations" && input.target_kind === "channel") {
    if (locator.kind !== "external_uuid" && locator.kind !== "conversations_channel_id") {
      throw new Error("conversations channel links require an immutable external_uuid or conversations_channel_id");
    }
    if (!labels.channel_name) {
      throw new Error("conversations channel links require labels.channel_name as mutable compatibility data");
    }
  }
  if (authority === "contacts" && input.target_kind === "contact") {
    if (locator.kind !== "external_uuid") {
      throw new Error("contacts contact links require an immutable external_uuid");
    }
    const contactLocator = { kind: "external_uuid", value: locator.value };
    return ProjectResourceLinkInputSchema.parse({
      ...input,
      service_instance: serviceInstance,
      locator: contactLocator,
      labels
    });
  }
  if (authority === "files" && input.target_kind === "project") {
    if (input.scope !== "collection") {
      throw new Error("files project links require scope collection");
    }
    if (locator.kind !== "canonical_uri") {
      throw new Error(`files project links require a canonical_uri locator of the form ${PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX}<prj_id>`);
    }
    if (!FILES_PROJECT_LOCATOR_RE.test(locator.value)) {
      throw new Error(`files project links require a locator value of the form ${PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX}<prj_id>`);
    }
  }
  return ProjectResourceLinkInputSchema.parse({
    ...input,
    service_instance: serviceInstance,
    locator,
    labels
  });
}
function projectResourceLinkIdentity(input) {
  const link = normalizeProjectResourceLink({
    authority: input.authority,
    service_instance: input.service_instance,
    source_package: input.source_package,
    target_kind: input.target_kind,
    locator: input.locator,
    scope: input.scope,
    labels: input.labels
  });
  return {
    authority: link.authority,
    service_instance: link.service_instance,
    source_package: link.source_package,
    target_kind: link.target_kind,
    locator_kind: link.locator.kind,
    locator_value: link.locator.value
  };
}
function projectResourceLinkId(projectId, input) {
  return `prl_${sha256(canonicalJson({ project_id: projectId, ...projectResourceLinkIdentity(input) })).slice(0, 36)}`;
}
function normalizeProjectResourceLinks(inputs) {
  if (!Array.isArray(inputs))
    throw new Error("resource links must be an array");
  const normalized = inputs.map(normalizeProjectResourceLink);
  const seen = new Set;
  for (const link of normalized) {
    const key = canonicalJson(projectResourceLinkIdentity(link));
    if (seen.has(key))
      throw new Error(`duplicate resource link identity in request: ${key}`);
    seen.add(key);
  }
  return normalized.sort((a, b) => canonicalJson(projectResourceLinkIdentity(a)).localeCompare(canonicalJson(projectResourceLinkIdentity(b))));
}
function rowToProjectResourceLink(row) {
  const input = normalizeProjectResourceLink({
    authority: row.authority,
    service_instance: row.service_instance,
    source_package: row.source_package,
    target_kind: row.target_kind,
    locator: {
      kind: row.locator_kind,
      value: row.locator_value
    },
    scope: row.scope,
    labels: JSON.parse(row.labels_json)
  });
  const timestamp = (value) => {
    if (value.includes("T"))
      return new Date(value).toISOString();
    return new Date(`${value.replace(" ", "T")}Z`).toISOString();
  };
  return ProjectResourceLinkSchema.parse({
    ...input,
    id: row.id,
    project_id: row.project_id,
    labels: input.labels ?? {},
    created_at: timestamp(row.created_at),
    updated_at: timestamp(row.updated_at)
  });
}
function projectResourceLinksDigest(links) {
  const ordered = [...links].sort((a, b) => canonicalJson(projectResourceLinkIdentity(a)).localeCompare(canonicalJson(projectResourceLinkIdentity(b))));
  return sha256(canonicalJson(ordered.map((link) => ({
    id: link.id,
    project_id: link.project_id,
    ...projectResourceLinkIdentity(link),
    scope: link.scope,
    labels: link.labels
  }))));
}
function projectionValue(link) {
  if (link.authority === "conversations" && link.target_kind === "channel") {
    return link.labels.channel_name ?? null;
  }
  return link.locator.value;
}
function projectResourceLinkIntegrationProjection(integrations, beforeLinks, afterLinks) {
  const projected = { ...integrations };
  for (const projection of PROJECTIONS) {
    const before = beforeLinks.filter(projection.match);
    const after = afterLinks.filter(projection.match);
    if (after.length === 1) {
      const value = projectionValue(after[0]);
      if (value)
        projected[projection.key] = value;
      else
        delete projected[projection.key];
    } else if (after.length > 1) {
      const existingValue = projected[projection.key];
      const matches = typeof existingValue === "string" ? after.filter((link) => projectionValue(link) === existingValue) : [];
      if (matches.length !== 1)
        delete projected[projection.key];
    } else if (before.length > 0) {
      delete projected[projection.key];
    }
  }
  return projected;
}
function normalizeProjectResourceLinkIntegrations(value) {
  if (value === undefined)
    return;
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error("resource link integrations must be an object");
  }
  const integrations = {};
  for (const [key, item] of Object.entries(value)) {
    if (!key.trim() || typeof item !== "string" || !item.trim()) {
      throw new Error("resource link integration keys and values must be non-empty strings");
    }
    integrations[key] = item;
  }
  return integrations;
}
function assertProjectResourceLinkIntegrationMutation(beforeIntegrations, proposedIntegrations, links) {
  const canonical = projectResourceLinkIntegrationProjection({}, [], links);
  for (const key of PROJECT_RESOURCE_LINK_INTEGRATION_KEYS) {
    if (beforeIntegrations[key] === proposedIntegrations[key])
      continue;
    const authoritative = canonical[key];
    if (authoritative !== undefined && authoritative !== proposedIntegrations[key]) {
      throw new Error(`integration '${key}' is a typed resource-link compatibility projection and conflicts with the existing resource link ('${authoritative}'); change it through resource-links`);
    }
  }
}
function projectResourceLinkSnapshot(project, links) {
  return {
    project,
    links,
    collection_digest: projectResourceLinksDigest(links)
  };
}
function projectResourceLinkCollection(projectId, currentRevision, links, maxItems) {
  return ProjectResourceLinkCollectionV1Schema.parse({
    schema: "hasna.project_resource_link_collection.v1",
    project_id: projectId,
    current_revision: currentRevision,
    links,
    link_count: links.length,
    max_items: maxItems,
    collection_digest: projectResourceLinksDigest(links),
    complete: true,
    truncated: false
  });
}
function assertProjectResourceLinkReadContractEquality(read) {
  const flat = {
    project_id: read.project_id,
    current_revision: read.current_revision,
    links: read.links,
    link_count: read.link_count,
    max_items: read.max_items,
    collection_digest: read.collection_digest,
    complete: read.complete,
    truncated: read.truncated
  };
  const { schema: _schema, ...contract } = ProjectResourceLinkCollectionV1Schema.parse(read.contract);
  if (canonicalJson(flat) !== canonicalJson(contract)) {
    throw new Error("project resource link contract and compatibility fields are not byte-equivalent");
  }
}
var SOURCE_PACKAGE_BY_AUTHORITY, TARGET_KINDS_BY_AUTHORITY, LINK_FIELDS, LOCATOR_FIELDS, LABEL_FIELDS, COMPLETE_EXTERNAL_UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$", UUID_RE, CONVERSATIONS_CHANNEL_ID_RE, URN_RE, PROJECT_RESOURCE_SERVICE_INSTANCE_URN_FORM = "urn:hasna:<authority>:service:<authority_id>:tenant:<tenant_id>:corpus:<corpus_id>", URN_SERVICE_INSTANCE_AUTHORITIES, PROJECT_RESOURCE_FILES_PROJECT_URN_PREFIX = "urn:hasna:files:project:", FILES_PROJECT_LOCATOR_RE, PROJECTIONS, PROJECT_RESOURCE_LINK_INTEGRATION_KEYS;
var init_project_resource_links = __esm(() => {
  init_workspace();
  init_guarded_project_mutation();
  init_workspace();
  SOURCE_PACKAGE_BY_AUTHORITY = {
    todos: "@hasna/todos",
    conversations: "@hasna/conversations",
    knowledge: "@hasna/knowledge",
    mementos: "@hasna/mementos",
    orgs: "@hasna/orgs",
    contacts: "@hasna/contacts",
    files: "@hasna/files"
  };
  TARGET_KINDS_BY_AUTHORITY = {
    todos: ["project", "task", "task_list", "plan"],
    conversations: ["project", "channel"],
    knowledge: ["collection", "item"],
    mementos: ["project", "item"],
    orgs: ["org", "project"],
    contacts: ["contact"],
    files: ["project"]
  };
  LINK_FIELDS = new Set([
    "authority",
    "service_instance",
    "source_package",
    "target_kind",
    "locator",
    "scope",
    "labels"
  ]);
  LOCATOR_FIELDS = new Set(["kind", "value"]);
  LABEL_FIELDS = new Set(["name", "channel_name", "path", "tags"]);
  UUID_RE = new RegExp(COMPLETE_EXTERNAL_UUID_PATTERN);
  CONVERSATIONS_CHANNEL_ID_RE = /^chn_[0-9a-f]{32}$/;
  URN_RE = /^urn:[a-z0-9][a-z0-9-]{0,31}:[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%-]+$/;
  URN_SERVICE_INSTANCE_AUTHORITIES = [
    "todos",
    "conversations",
    "knowledge",
    "mementos",
    "orgs",
    "files"
  ];
  FILES_PROJECT_LOCATOR_RE = /^urn:hasna:files:project:prj_[A-Za-z0-9_-]+$/;
  PROJECTIONS = [
    { key: "todos_project_id", match: (link) => link.authority === "todos" && link.target_kind === "project" },
    { key: "todos_task_list_id", match: (link) => link.authority === "todos" && link.target_kind === "task_list" },
    { key: "mementos_project_id", match: (link) => link.authority === "mementos" && link.target_kind === "project" },
    { key: "orgs_org_id", match: (link) => link.authority === "orgs" && link.target_kind === "org" },
    { key: "orgs_project_id", match: (link) => link.authority === "orgs" && link.target_kind === "project" },
    { key: "conversations_channel", match: (link) => link.authority === "conversations" && link.target_kind === "channel" }
  ];
  PROJECT_RESOURCE_LINK_INTEGRATION_KEYS = PROJECTIONS.map((projection) => projection.key);
});

// src/lib/tmux.ts
var init_tmux = () => {};

// src/lib/workspace-runtime.ts
var PROJECT_MARKER_FILENAME = ".project.json", LEGACY_WORKSPACE_MARKER_FILENAME = ".workspace.json";
var init_workspace_runtime = __esm(() => {
  init_tmux();
  init_workspaces();
  init_project_store_paths();
});

// src/lib/project-resolver.ts
import { existsSync as existsSync4, readFileSync, statSync } from "fs";
import { homedir as homedir2 } from "os";
import { join as join3, resolve as resolve3 } from "path";
function normalizeProjectPath(target) {
  if (target === "~")
    return homedir2();
  if (target.startsWith("~/"))
    return join3(homedir2(), target.slice(2));
  return resolve3(target);
}
function isProjectDirectory(path) {
  try {
    return existsSync4(path) && statSync(path).isDirectory();
  } catch {
    return false;
  }
}
function isProjectPathLike(target) {
  return target === "." || target === ".." || target === "~" || target.startsWith("~/") || target.startsWith("/") || target.startsWith("./") || target.startsWith("../") || target.includes("/");
}
function readProjectMarker(path) {
  const markerPath = [join3(path, PROJECT_MARKER_FILENAME), join3(path, LEGACY_WORKSPACE_MARKER_FILENAME)].find((candidate) => existsSync4(candidate));
  if (!markerPath)
    return null;
  try {
    const marker = JSON.parse(readFileSync(markerPath, "utf-8"));
    return {
      id: typeof marker.id === "string" && marker.id.trim() ? marker.id.trim() : undefined,
      slug: typeof marker.slug === "string" && marker.slug.trim() ? marker.slug.trim() : undefined,
      path: markerPath,
      legacy: markerPath.endsWith(LEGACY_WORKSPACE_MARKER_FILENAME)
    };
  } catch (err) {
    throw new Error(`Project marker is malformed: ${markerPath}: ${err instanceof Error ? err.message : String(err)}`);
  }
}
function isResolvableProject(workspace, options) {
  return options.includeDeleted === true || workspace.status !== "deleted";
}
function exactNameMatches(target, options) {
  const lower = target.toLowerCase();
  return listWorkspaces({ query: target, limit: 200 }, options.db).filter((workspace) => isResolvableProject(workspace, options)).filter((workspace) => workspace.name.toLowerCase() === lower);
}
function workspaceFromMarker(path, options) {
  const marker = readProjectMarker(path);
  if (!marker)
    return null;
  for (const idOrSlug of [marker.id, marker.slug]) {
    if (!idOrSlug)
      continue;
    const workspace = resolveWorkspace(idOrSlug, options.db);
    if (workspace && isResolvableProject(workspace, options))
      return { project: workspace, marker };
  }
  throw new Error(`Project marker references an unknown project: ${marker.path ?? join3(path, PROJECT_MARKER_FILENAME)}`);
}
function resolveRegisteredProjectTarget(target, options = {}) {
  const normalizedTarget = target?.trim() || ".";
  const byIdOrSlug = resolveWorkspace(normalizedTarget, options.db);
  if (byIdOrSlug && isResolvableProject(byIdOrSlug, options)) {
    return {
      target: normalizedTarget,
      source: "id-or-slug",
      registered: true,
      project: byIdOrSlug
    };
  }
  const matches = exactNameMatches(normalizedTarget, options);
  if (matches.length === 1) {
    return {
      target: normalizedTarget,
      source: "name",
      registered: true,
      project: matches[0]
    };
  }
  if (matches.length > 1) {
    throw new Error(`Project name is ambiguous: ${normalizedTarget}`);
  }
  if (options.allowPath === false)
    return null;
  const path = normalizeProjectPath(normalizedTarget);
  if (!isProjectPathLike(normalizedTarget) && !isProjectDirectory(path))
    return null;
  if (!isProjectDirectory(path))
    throw new Error(`Project path does not exist or is not a directory: ${path}`);
  const pathMatches = listWorkspacesByPath(path, options.db).filter((workspace) => isResolvableProject(workspace, options));
  if (pathMatches.length > 1) {
    throw new Error(`Project path is ambiguous: ${path} matches ${pathMatches.map((workspace) => workspace.slug).join(", ")}`);
  }
  if (pathMatches[0]) {
    return {
      target: normalizedTarget,
      source: "path",
      registered: true,
      project: pathMatches[0],
      path
    };
  }
  if (options.allowMarker === false)
    return null;
  const markerMatch = workspaceFromMarker(path, options);
  if (markerMatch) {
    return {
      target: normalizedTarget,
      source: "marker",
      registered: true,
      project: markerMatch.project,
      path,
      marker: markerMatch.marker
    };
  }
  return null;
}
function resolveRegisteredProjectTargetOrThrow(target, options = {}) {
  const resolution = resolveRegisteredProjectTarget(target, options);
  if (!resolution)
    throw new Error(`Project not found: ${target?.trim() || "."}`);
  return resolution;
}
var init_project_resolver = __esm(() => {
  init_workspaces();
  init_workspace_runtime();
});

// src/lib/project-channel.ts
function resolveProjectChannelClass(project) {
  return resolveProjectChannelClassDetailed(project).channel_class;
}
function resolveProjectChannelClassDetailed(project) {
  const fromKind = WORKSPACE_KIND_CHANNEL_CLASSES[project.kind] ?? null;
  const explicit = project.integrations?.[PROJECT_CHANNEL_CLASS_INTEGRATION_KEY]?.trim().toLowerCase();
  if (!explicit)
    return { channel_class: fromKind };
  const known = PROJECT_CHANNEL_CLASSES.find((value) => value === explicit);
  if (known)
    return { channel_class: known };
  return {
    channel_class: fromKind,
    warning: `Ignoring unknown ${PROJECT_CHANNEL_CLASS_INTEGRATION_KEY} "${explicit}" on the project record (known: ${PROJECT_CHANNEL_CLASSES.join(", ")}); using ${fromKind ?? "no class"} from kind "${project.kind}" instead.`
  };
}
function deriveProjectChannel(project) {
  const channel_class = resolveProjectChannelClass(project);
  const linked = project.integrations?.[PROJECT_CHANNEL_INTEGRATION_KEY]?.trim();
  if (linked) {
    const channel2 = normalizeProjectChannelName(linked);
    if (!channel2)
      throw new Error(`Linked conversations channel is not a valid channel name: ${linked}`);
    return { channel: channel2, channel_class, source: "integration" };
  }
  const channel = normalizeProjectChannelName(project.slug);
  if (!channel)
    throw new Error(`Project slug does not produce a valid channel name: ${project.slug}`);
  return { channel, channel_class, source: "derived" };
}
function projectChannelDescription(project, channelClass) {
  const label = project.name.trim() || project.slug;
  const classPart = channelClass ? ` \u2014 class ${channelClass}` : "";
  return `Project channel for ${label} (${project.slug})${classPart}; auto-created by @hasna/projects.`;
}
function projectChannelTopic(project, channelClass) {
  const label = project.name.trim() || project.slug;
  return `${label} (${project.slug}) \u2014 ${channelClass ? `${channelClass} channel` : "project channel"}`;
}
function errorText(err) {
  return err instanceof Error ? err.message : String(err);
}
function buildChannelCreateArgs(project, derivation, options = {}) {
  const args = [
    "channel",
    "create",
    derivation.channel,
    "--description",
    projectChannelDescription(project, derivation.channel_class)
  ];
  if (options.withMetadata !== false) {
    if (derivation.channel_class)
      args.push("--class", derivation.channel_class);
    args.push("--topic", projectChannelTopic(project, derivation.channel_class));
  }
  args.push("-j");
  if (options.from?.trim())
    args.push("--from", options.from.trim());
  return args;
}
function isUnsupportedOptionFailure(result) {
  const output = `${result.stderr} ${result.stdout}`.toLowerCase();
  return /unknown option|unrecognized option|unknown argument|invalid option|unknown flag/.test(output);
}
function createConversationsChannel(runner, project, derivation, from) {
  let result = runner(buildChannelCreateArgs(project, derivation, { from }));
  if (!result.ok && isUnsupportedOptionFailure(result)) {
    result = runner(buildChannelCreateArgs(project, derivation, { from, withMetadata: false }));
  }
  if (result.ok)
    return { status: "created" };
  const output = `${result.stderr} ${result.stdout}`.toLowerCase();
  if (output.includes("exist"))
    return { status: "exists" };
  return {
    status: "error",
    message: result.stderr.trim() || result.stdout.trim() || "conversations channel create failed"
  };
}
function derivationErrorResult(project, message) {
  return {
    channel: "",
    channel_class: null,
    source: "derived",
    status: "error",
    created: false,
    linked: false,
    message,
    warnings: [],
    side_effects: { ...NO_SIDE_EFFECTS },
    project
  };
}
function plannedResult(project, derivation, alreadyLinked) {
  return {
    ...derivation,
    status: "planned",
    created: false,
    linked: alreadyLinked,
    warnings: [],
    side_effects: { ...NO_SIDE_EFFECTS, integration_linked: alreadyLinked },
    project,
    message: `Would ensure conversations channel ${derivation.channel}${derivation.channel_class ? ` (${derivation.channel_class})` : ""}.`
  };
}
async function ensureProjectChannelViaStore(store, project, options = {}) {
  let derivation;
  try {
    derivation = deriveProjectChannel(project);
  } catch (err) {
    return derivationErrorResult(project, errorText(err));
  }
  const alreadyLinked = Boolean(project.integrations[PROJECT_CHANNEL_INTEGRATION_KEY]?.trim());
  if (options.dryRun) {
    return plannedResult(project, derivation, alreadyLinked);
  }
  const runner = options.runner ?? conversationsCliRunner();
  const create = createConversationsChannel(runner, project, derivation, options.from);
  let status = create.status;
  const messages = create.message ? [create.message] : [];
  const warnings = [];
  const classWarning = resolveProjectChannelClassDetailed(project).warning;
  if (classWarning)
    warnings.push(classWarning);
  let eventRecorded = false;
  const updated = project;
  {
    try {
      await store.recordEvent(project.id, {
        event_type: "channel_ensured",
        source: options.source ?? "cli",
        agentId: options.agentId,
        command: options.command,
        after: {
          channel: derivation.channel,
          channel_class: derivation.channel_class,
          status,
          created: status === "created",
          message: messages[0] ?? null
        }
      });
      eventRecorded = true;
    } catch (err) {
      warnings.push(`Channel ensure audit event was not recorded: ${errorText(err)}`);
    }
  }
  const linked = Boolean(updated.integrations[PROJECT_CHANNEL_INTEGRATION_KEY]?.trim());
  return {
    ...derivation,
    status,
    created: create.status === "created",
    linked,
    message: messages.length ? messages.join("; ") : undefined,
    warnings,
    side_effects: {
      channel_created: create.status === "created",
      channel_present: create.status === "created" || create.status === "exists",
      integration_linked: linked,
      event_recorded: eventRecorded
    },
    project: updated
  };
}
var PROJECT_CHANNEL_CLASSES, PROJECT_CHANNEL_CLASS_INTEGRATION_KEY = "conversations_channel_class", WORKSPACE_KIND_CHANNEL_CLASSES, NO_SIDE_EFFECTS;
var init_project_channel = __esm(() => {
  init_workspaces();
  init_project_resolver();
  init_project_channel_guard();
  PROJECT_CHANNEL_CLASSES = ["package", "product", "work-project", "initiative", "loop-lane"];
  WORKSPACE_KIND_CHANNEL_CLASSES = {
    "open-source": "package",
    "internal-app": "product",
    platform: "product",
    "company-website": "product",
    community: "product",
    project: "work-project",
    experiment: null,
    scaffold: null,
    docs: null,
    "remote-only": null,
    generic: null
  };
  NO_SIDE_EFFECTS = {
    channel_created: false,
    channel_present: false,
    integration_linked: false,
    event_recorded: false
  };
});

// src/lib/project-resource-link-migrations.ts
function projectResourceLinkProducerProjectSubject(project) {
  return {
    id: project.id,
    slug: project.slug,
    name: project.name,
    kind: project.kind,
    conversations_channel: deriveProjectChannel(project).channel
  };
}
function projectResourceLinkProducerEvidenceDigest(manifest, phase, producerEvidence) {
  return sha256(canonicalJson({
    manifest_id: manifest.manifest_id,
    phase,
    producer_context: manifest.links.map((item) => ({
      link_id: item.link_id,
      producer_resource_kind: item.producer_resource_kind,
      producer_binding: item.producer_binding
    })),
    producer_evidence: producerEvidence
  }));
}
function projectResourceLinkProducerAttestationId(manifestId, phase, evidenceDigest) {
  return `prlpa_${sha256(canonicalJson({
    manifest_id: manifestId,
    phase,
    evidence_digest: evidenceDigest
  })).slice(0, 36)}`;
}
function assertProjectResourceLinkProducerAttestation(manifest, phase, producerEvidence, attestation) {
  if (!attestation) {
    throw new Error(`project resource link migration ${phase} requires trusted producer receipt/readback attestation`);
  }
  const evidenceDigest = projectResourceLinkProducerEvidenceDigest(manifest, phase, producerEvidence);
  const attestationId = projectResourceLinkProducerAttestationId(manifest.manifest_id, phase, evidenceDigest);
  if (attestation.attestation_id !== attestationId || attestation.manifest_id !== manifest.manifest_id || attestation.phase !== phase || attestation.evidence_digest !== evidenceDigest) {
    throw new Error("producer attestation does not bind the exact manifest, phase, and producer evidence");
  }
  requireNonemptyProofValue(attestation.verifier, "producer attestation verifier");
  requireNonemptyProofValue(attestation.verified_at, "producer attestation verified_at");
  if (!Number.isFinite(Date.parse(attestation.verified_at))) {
    throw new Error("producer attestation verified_at must be an ISO-8601 timestamp");
  }
  return { ...attestation };
}
function migrationEvidenceWithProducerAttestation(evidence, attestation) {
  return {
    ...evidence,
    producer_attestation: { ...attestation }
  };
}
function requireNonemptyProofValue(value, label) {
  if (!value?.trim())
    throw new Error(`${label} must be a nonempty producer proof value`);
  return value;
}
function assertProducerBinding(item) {
  if (item.producer_binding.authority_id !== item.link.authority) {
    throw new Error("producer binding authority_id must match the resource-link authority");
  }
  requireNonemptyProofValue(item.producer_resource_kind, "producer resource_kind");
  requireNonemptyProofValue(item.producer_binding.tenant_id, "producer binding tenant_id");
  requireNonemptyProofValue(item.producer_binding.capability_digest, "producer binding capability_digest");
}
function assertUniqueReceiptIds(receiptIds, label) {
  for (const receiptId of receiptIds)
    requireNonemptyProofValue(receiptId, label);
  if (new Set(receiptIds).size !== receiptIds.length) {
    throw new Error(`${label} must not contain duplicate producer receipts`);
  }
}
function reconcileProjectResourceLinkProducerProof(manifest, evidence, phase, terminalOutcome) {
  if (!evidence || evidence.length !== manifest.links.length) {
    const label = phase === "inverse" ? "producer inverse proof" : `producer ${phase} proof`;
    throw new Error(`${label} requires exact evidence for every manifest link`);
  }
  let retainedTargetCount = 0;
  const reconciled = evidence.map((candidate, index) => {
    const item = manifest.links[index];
    const persisted = item.producer_evidence;
    assertProducerBinding(item);
    requireNonemptyProofValue(candidate.forward_receipt_id, "producer forward receipt");
    requireNonemptyProofValue(candidate.target_revision, "producer target revision");
    requireNonemptyProofValue(candidate.target_digest, "producer target digest");
    assertUniqueReceiptIds(candidate.child_link_receipt_ids, "producer child-link receipt");
    if (phase !== "forward") {
      if (!persisted)
        throw new Error(`producer ${phase} proof has no persisted forward proof`);
      if (candidate.created_by_operation !== persisted.created_by_operation || candidate.forward_receipt_id !== persisted.forward_receipt_id || canonicalJson(candidate.child_link_receipt_ids) !== canonicalJson(persisted.child_link_receipt_ids)) {
        throw new Error(`producer ${phase} proof does not match the persisted producer receipt identity`);
      }
    }
    if (phase === "forward" || phase === "readback") {
      if (candidate.inverse_verified !== null || candidate.inverse_outcome !== null) {
        throw new Error(`producer ${phase} proof must not claim an inverse outcome`);
      }
    } else {
      if (candidate.inverse_verified !== true) {
        throw new Error("producer inverse proof requires inverse_verified=true for every manifest link");
      }
      const inverseOutcome = requireNonemptyProofValue(candidate.inverse_outcome, "producer inverse outcome");
      if (terminalOutcome === "complete" && candidate.created_by_operation && inverseOutcome !== "complete") {
        throw new Error("producer inverse proof for a created target must record inverse_outcome=complete");
      }
      if (terminalOutcome === "retained_target" && inverseOutcome === "retained_target") {
        retainedTargetCount += 1;
      }
    }
    return { ...candidate };
  });
  if (phase === "inverse" && terminalOutcome === "retained_target" && retainedTargetCount === 0) {
    throw new Error("producer inverse proof for retained_target must record a retained_target outcome");
  }
  return reconciled;
}
function projectResourceLinkMigrationManifestId(projectId, operationId, stepId, desiredCollectionDigest) {
  return `prlm_${sha256(canonicalJson({
    project_id: projectId,
    operation_id: operationId,
    step_id: stepId,
    desired_collection_digest: desiredCollectionDigest
  })).slice(0, 36)}`;
}
function projectResourceLinkMigrationEventId(manifestId, transitionVersion, toState) {
  return `prlme_${sha256(canonicalJson({
    manifest_id: manifestId,
    transition_version: transitionVersion,
    to_state: toState
  })).slice(0, 36)}`;
}
function buildProjectResourceLinkMigrationPlan(input, createdAt) {
  const normalizedInInputOrder = input.links.map((item) => normalizeProjectResourceLinks([item.link])[0]);
  const normalized = normalizeProjectResourceLinks(normalizedInInputOrder);
  if (normalized.length !== input.links.length) {
    throw new Error("project resource link migration plan lost link cardinality");
  }
  const items = input.links.map((item, index) => {
    const link = normalizedInInputOrder[index];
    if (!link)
      throw new Error("project resource link migration plan contains an ambiguous normalized identity");
    return {
      ...item,
      link,
      link_id: projectResourceLinkId(input.project_id, link),
      producer_evidence: null
    };
  });
  for (const item of items)
    assertProducerBinding(item);
  const desiredCollectionDigest = projectResourceLinksDigest(items.map((item) => ({
    ...item.link,
    id: item.link_id,
    project_id: input.project_id,
    labels: item.link.labels ?? {},
    created_at: createdAt,
    updated_at: createdAt
  })));
  return {
    schema: "projects.project_resource_link_migration_manifest.v1",
    manifest_id: projectResourceLinkMigrationManifestId(input.project_id, input.operation_id, input.step_id, desiredCollectionDigest),
    project_id: input.project_id,
    operation_id: input.operation_id,
    step_id: input.step_id,
    state: "planned",
    expected_project_revision: input.expected_project_revision,
    desired_collection_digest: desiredCollectionDigest,
    links: items,
    projects_forward_receipt_id: null,
    projects_inverse_receipt_id: null,
    projects_reference_proof: null,
    last_verified_projects_revision: null,
    last_verified_projects_digest: null,
    transition_version: 1,
    created_at: createdAt,
    updated_at: createdAt
  };
}
function assertProjectResourceLinkMigrationTransition(from, to) {
  if (!TRANSITIONS[from].includes(to)) {
    throw new Error(`project resource link migration transition ${from} -> ${to} is not allowed`);
  }
}
function applyProjectResourceLinkMigrationTransition(manifest, toState, updatedAt, updates = {}) {
  assertProjectResourceLinkMigrationTransition(manifest.state, toState);
  if (updates.producer_evidence && updates.producer_evidence.length !== manifest.links.length) {
    throw new Error("producer evidence cardinality must equal manifest links cardinality");
  }
  return {
    ...manifest,
    state: toState,
    links: updates.producer_evidence ? manifest.links.map((item, index) => ({
      ...item,
      producer_evidence: updates.producer_evidence[index]
    })) : manifest.links,
    projects_forward_receipt_id: updates.projects_forward_receipt_id === undefined ? manifest.projects_forward_receipt_id : updates.projects_forward_receipt_id,
    projects_inverse_receipt_id: updates.projects_inverse_receipt_id === undefined ? manifest.projects_inverse_receipt_id : updates.projects_inverse_receipt_id,
    projects_reference_proof: updates.projects_reference_proof === undefined ? manifest.projects_reference_proof : updates.projects_reference_proof,
    last_verified_projects_revision: updates.last_verified_projects_revision === undefined ? manifest.last_verified_projects_revision : updates.last_verified_projects_revision,
    last_verified_projects_digest: updates.last_verified_projects_digest === undefined ? manifest.last_verified_projects_digest : updates.last_verified_projects_digest,
    transition_version: manifest.transition_version + 1,
    updated_at: updatedAt
  };
}
function rowToProjectResourceLinkMigrationManifest(row) {
  return {
    schema: "projects.project_resource_link_migration_manifest.v1",
    manifest_id: row.manifest_id,
    project_id: row.project_id,
    operation_id: row.operation_id,
    step_id: row.step_id,
    state: row.state,
    expected_project_revision: row.expected_project_revision,
    desired_collection_digest: row.desired_collection_digest,
    links: JSON.parse(row.links_json),
    projects_forward_receipt_id: row.projects_forward_receipt_id,
    projects_inverse_receipt_id: row.projects_inverse_receipt_id,
    projects_reference_proof: row.projects_reference_proof_json ? JSON.parse(row.projects_reference_proof_json) : null,
    last_verified_projects_revision: row.last_verified_projects_revision,
    last_verified_projects_digest: row.last_verified_projects_digest,
    transition_version: Number(row.transition_version),
    created_at: row.created_at,
    updated_at: row.updated_at
  };
}
function migrationEvent(manifestId, transitionVersion, fromState, toState, requestDigest2, preconditionDigest2, evidence, createdAt) {
  return {
    event_id: projectResourceLinkMigrationEventId(manifestId, transitionVersion, toState),
    manifest_id: manifestId,
    transition_version: transitionVersion,
    from_state: fromState,
    to_state: toState,
    request_digest: requestDigest2,
    precondition_digest: preconditionDigest2,
    evidence,
    created_at: createdAt
  };
}
var TRANSITIONS;
var init_project_resource_link_migrations = __esm(() => {
  init_guarded_project_mutation();
  init_project_channel();
  init_project_resource_links();
  TRANSITIONS = {
    planned: ["producer_applied", "rollback_in_progress", "rolled_back", "failed_reconcilable"],
    producer_applied: ["projects_applied", "rollback_in_progress", "rolled_back", "retained_target", "failed_reconcilable"],
    projects_applied: ["verified", "rollback_in_progress", "failed_reconcilable"],
    verified: ["rollback_in_progress", "failed_reconcilable"],
    rollback_in_progress: ["rolled_back", "retained_target", "failed_reconcilable"],
    rolled_back: [],
    retained_target: [],
    failed_reconcilable: ["rollback_in_progress"]
  };
});

// src/lib/project-quarantine.ts
function workspaceLocationsDigest(locations) {
  return sha256(canonicalJson([...locations].sort((a, b) => a.id.localeCompare(b.id))));
}
function projectDigest(project, locations = []) {
  return sha256(canonicalJson({
    project: workspaceSnapshot(project),
    workspace_locations: [...locations].sort((a, b) => a.id.localeCompare(b.id))
  }));
}
function projectQuarantineSnapshot(project, resourceLinks, workspaceLocations) {
  return {
    project,
    project_digest: projectDigest(project, workspaceLocations),
    resource_links: resourceLinks,
    resource_link_collection_digest: projectResourceLinksDigest(resourceLinks),
    workspace_locations: workspaceLocations,
    workspace_location_collection_digest: workspaceLocationsDigest(workspaceLocations)
  };
}
function projectQuarantineSnapshotJson(snapshot) {
  return snapshot;
}
function parseProjectQuarantineSnapshot(value, label) {
  const snapshot = value;
  if (!snapshot?.project?.id || !Array.isArray(snapshot.resource_links) || !Array.isArray(snapshot.workspace_locations) || typeof snapshot.project_digest !== "string" || typeof snapshot.resource_link_collection_digest !== "string" || typeof snapshot.workspace_location_collection_digest !== "string") {
    throw new Error(`${label} quarantine receipt snapshot is incomplete`);
  }
  if (projectDigest(snapshot.project, snapshot.workspace_locations) !== snapshot.project_digest) {
    throw new Error(`${label} quarantine receipt project digest mismatch`);
  }
  if (projectResourceLinksDigest(snapshot.resource_links) !== snapshot.resource_link_collection_digest) {
    throw new Error(`${label} quarantine receipt resource-link digest mismatch`);
  }
  if (workspaceLocationsDigest(snapshot.workspace_locations) !== snapshot.workspace_location_collection_digest) {
    throw new Error(`${label} quarantine receipt workspace-location digest mismatch`);
  }
  return snapshot;
}
function normalizedExpectedResourceLinkIds(input) {
  const ids = input.expected_resource_link_ids.map((value) => value.trim()).sort();
  if (ids.some((value) => !value)) {
    throw new Error("project quarantine expected_resource_link_ids must be non-empty strings");
  }
  if (new Set(ids).size !== ids.length) {
    throw new Error("project quarantine expected_resource_link_ids must be unique");
  }
  if (ids.length > input.resource_link_max_items) {
    throw new Error("project quarantine expected link set exceeds resource_link_max_items");
  }
  return ids;
}
function normalizedExpectedWorkspaceLocationIds(input) {
  const ids = input.expected_workspace_location_ids.map((value) => value.trim()).sort();
  if (ids.some((value) => !value)) {
    throw new Error("project quarantine expected_workspace_location_ids must be non-empty strings");
  }
  if (new Set(ids).size !== ids.length) {
    throw new Error("project quarantine expected_workspace_location_ids must be unique");
  }
  if (ids.length > input.workspace_location_max_items) {
    throw new Error("project quarantine expected workspace-location set exceeds workspace_location_max_items");
  }
  return ids;
}
function projectQuarantineRequestDigest(input) {
  return sha256(canonicalJson({
    route: PROJECT_QUARANTINE_ROUTE,
    quarantine_name: input.quarantine_name.trim(),
    quarantine_slug: input.quarantine_slug.trim()
  }));
}
function projectQuarantinePreconditionDigest(input, expectedIds = normalizedExpectedResourceLinkIds(input), expectedLocationIds = normalizedExpectedWorkspaceLocationIds(input)) {
  return sha256(canonicalJson({
    route: PROJECT_QUARANTINE_ROUTE,
    project_id: input.project_id,
    expected_revision: input.expected_revision,
    expected_project_digest: input.expected_project_digest,
    expected_resource_link_collection_digest: input.expected_resource_link_collection_digest,
    expected_resource_link_ids: expectedIds,
    resource_link_max_items: input.resource_link_max_items,
    expected_workspace_location_collection_digest: input.expected_workspace_location_collection_digest,
    expected_workspace_location_ids: expectedLocationIds,
    workspace_location_max_items: input.workspace_location_max_items
  }));
}
function projectQuarantinePatch(input, before) {
  const quarantineName = input.quarantine_name.trim();
  const quarantineSlug = input.quarantine_slug.trim();
  if (!quarantineName)
    throw new Error("project quarantine requires a non-empty quarantine_name");
  if (!quarantineSlug)
    throw new Error("project quarantine requires a non-empty quarantine_slug");
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(quarantineSlug)) {
    throw new Error("project quarantine requires an already-canonical quarantine_slug");
  }
  return {
    name: quarantineName,
    slug: quarantineSlug,
    status: "archived",
    root_id: null,
    recipe_id: null,
    canonical_machine: null,
    primary_path: null,
    git_remote: null,
    s3_bucket: null,
    s3_prefix: null,
    integrations: {},
    tags: [...new Set([...before.project.tags, "duplicate-quarantine", "provenance-only"])].sort(),
    metadata: {
      ...before.project.metadata,
      [PROJECT_QUARANTINE_METADATA_KEY]: {
        schema: "hasna.projects.duplicate-quarantine.v1",
        operation_id: input.operation_id,
        step_id: input.step_id,
        original_project_digest: before.project_digest,
        original_resource_link_collection_digest: before.resource_link_collection_digest,
        original_resource_link_ids: before.resource_links.map((link) => link.id).sort(),
        original_workspace_location_collection_digest: before.workspace_location_collection_digest,
        original_workspace_location_ids: before.workspace_locations.map((location) => location.id).sort()
      }
    },
    last_opened_at: null
  };
}
function assertProjectQuarantinePreconditions(input, before) {
  const expectedIds = normalizedExpectedResourceLinkIds(input);
  const expectedLocationIds = normalizedExpectedWorkspaceLocationIds(input);
  const actualIds = before.resource_links.map((link) => link.id).sort();
  const actualLocationIds = before.workspace_locations.map((location) => location.id).sort();
  if (before.project.updated_at !== input.expected_revision)
    return "stale_revision";
  if (before.project_digest !== input.expected_project_digest)
    return "project_digest_mismatch";
  if (canonicalJson(actualIds) !== canonicalJson(expectedIds))
    return "resource_link_target_set_mismatch";
  if (before.resource_link_collection_digest !== input.expected_resource_link_collection_digest) {
    return "resource_link_collection_digest_mismatch";
  }
  if (canonicalJson(actualLocationIds) !== canonicalJson(expectedLocationIds)) {
    return "workspace_location_target_set_mismatch";
  }
  if (before.workspace_location_collection_digest !== input.expected_workspace_location_collection_digest) {
    return "workspace_location_collection_digest_mismatch";
  }
  return null;
}
function assertProjectQuarantinePostimage(input, before, after) {
  const marker = after.project.metadata[PROJECT_QUARANTINE_METADATA_KEY];
  if (after.project.status !== "archived" || after.project.name !== input.quarantine_name.trim() || after.project.slug !== input.quarantine_slug.trim() || after.project.root_id !== null || after.project.recipe_id !== null || after.project.canonical_machine !== null || after.project.primary_path !== null || after.project.git_remote !== null || after.project.s3_bucket !== null || after.project.s3_prefix !== null || Object.keys(after.project.integrations).length !== 0 || after.resource_links.length !== 0 || after.workspace_locations.length !== 0 || marker?.original_project_digest !== before.project_digest || marker?.original_resource_link_collection_digest !== before.resource_link_collection_digest || canonicalJson(marker?.original_resource_link_ids) !== canonicalJson(before.resource_links.map((link) => link.id).sort()) || marker?.original_workspace_location_collection_digest !== before.workspace_location_collection_digest || canonicalJson(marker?.original_workspace_location_ids) !== canonicalJson(before.workspace_locations.map((location) => location.id).sort())) {
    throw new Error("project quarantine exact post-write readback mismatch");
  }
}
function restoreProjectPatch(snapshot) {
  const before = snapshot.project;
  return {
    name: before.name,
    slug: before.slug,
    description: before.description,
    kind: before.kind,
    status: before.status,
    root_id: before.root_id,
    recipe_id: before.recipe_id,
    canonical_machine: before.canonical_machine,
    primary_path: before.primary_path,
    git_remote: before.git_remote,
    s3_bucket: before.s3_bucket,
    s3_prefix: before.s3_prefix,
    tags: before.tags,
    integrations: before.integrations,
    metadata: before.metadata,
    last_opened_at: before.last_opened_at
  };
}
var PROJECT_QUARANTINE_ROUTE = "projects.duplicate-quarantine.v1", PROJECT_QUARANTINE_EVENT = "duplicate_project_quarantined", PROJECT_QUARANTINE_ROLLBACK_EVENT = "duplicate_project_quarantine_rolled_back", PROJECT_QUARANTINE_METADATA_KEY = "projects_duplicate_quarantine";
var init_project_quarantine = __esm(() => {
  init_guarded_project_mutation();
  init_project_resource_links();
});

// src/db/workspaces.ts
import { customAlphabet } from "nanoid";
import { existsSync as existsSync5 } from "fs";
import { hostname } from "os";
import { dirname as dirname2, isAbsolute, join as join4, resolve as resolve4 } from "path";
function generateWorkspaceId() {
  return `wks_${nanoid()}`;
}
function generateRootId() {
  return `root_${nanoid()}`;
}
function generateRecipeId() {
  return `rcp_${nanoid()}`;
}
function generateAgentId() {
  return `agt_${nanoid()}`;
}
function generateWorkspaceEventId() {
  return `evt_${nanoid()}`;
}
function generateLocationId() {
  return `loc_${nanoid()}`;
}
function generateTmuxProfileId() {
  return `tmp_${nanoid()}`;
}
function generateTmuxProfileWindowId() {
  return `tmw_${nanoid()}`;
}
function generateWorkspaceLockId() {
  return `lock_${nanoid()}`;
}
function workspaceSlugify(name) {
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
function parseJson2(raw, fallback) {
  if (!raw)
    return fallback;
  try {
    return JSON.parse(raw);
  } catch {
    return fallback;
  }
}
function json(value) {
  return JSON.stringify(value ?? null);
}
function normalizeList(values) {
  return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
function ensureUniqueSlug(table, base, db, excludeId) {
  const safeBase = base || "workspace";
  let candidate = safeBase;
  let suffix = 1;
  while (true) {
    const row = db.query(`SELECT id FROM ${table} WHERE slug = ?`).get(candidate);
    if (!row || row.id === excludeId)
      return candidate;
    suffix++;
    candidate = `${safeBase}-${suffix}`;
  }
}
function rowToRoot(row) {
  return {
    ...row,
    tags: parseJson2(row.tags, []),
    default_kind: row.default_kind,
    repo_visibility: row.repo_visibility,
    allowed_recipes: parseJson2(row.allowed_recipes, []),
    allowed_agents: parseJson2(row.allowed_agents, []),
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToAgent(row) {
  return {
    ...row,
    kind: row.kind,
    permissions: parseJson2(row.permissions, []),
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToMachine(row) {
  return {
    ...row,
    role: row.role
  };
}
function rowToRecipe(row) {
  return {
    ...row,
    kind: row.kind,
    steps: redactProjectValue(parseJson2(row.steps, [])),
    variables: redactProjectValue(parseJson2(row.variables, {})),
    default_tags: parseJson2(row.default_tags, []),
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToWorkspace(row) {
  return {
    ...row,
    kind: row.kind,
    status: row.status,
    tags: parseJson2(row.tags, []),
    integrations: redactProjectValue(parseJson2(row.integrations, {})),
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToLocation(row) {
  return {
    ...row,
    is_primary: row.is_primary === 1,
    exists_at_create: row.exists_at_create === 1,
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToWorkspaceAgentAssignment(row, db) {
  return {
    ...row,
    metadata: redactProjectValue(parseJson2(row.metadata, {})),
    agent: getAgent(row.agent_id, db)
  };
}
function rowToEvent(row) {
  return {
    ...row,
    source: row.source,
    prompt: row.prompt ? redactProjectText(row.prompt) : null,
    command: row.command ? redactProjectText(row.command) : null,
    before_json: redactProjectValue(parseJson2(row.before_json, null)),
    after_json: redactProjectValue(parseJson2(row.after_json, null)),
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToAgentRun(row) {
  return {
    ...row,
    status: row.status,
    prompt: redactProjectText(row.prompt),
    plan_json: redactProjectValue(parseJson2(row.plan_json, null)),
    tool_calls_json: redactProjectValue(parseJson2(row.tool_calls_json, [])),
    result_json: redactProjectValue(parseJson2(row.result_json, null)),
    error: row.error ? redactProjectText(row.error) : null,
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToTmuxProfile(row) {
  return {
    ...row,
    attach: row.attach === 1,
    metadata: redactProjectValue(parseJson2(row.metadata, {}))
  };
}
function rowToTmuxProfileWindow(row) {
  return {
    ...row,
    detached: row.detached === 1,
    env: redactProjectValue(parseJson2(row.env, {})),
    revive: row.revive === 1
  };
}
function rowToWorkspaceLock(row) {
  return row;
}
function parseWorkspaceRevision(revision) {
  return Date.parse(revision.replace(" ", "T") + "Z");
}
function workspaceRevisionFromMs(ms) {
  return new Date(ms).toISOString().replace("T", " ").replace("Z", "");
}
function nextWorkspaceRevision(current) {
  const nowRevision = now();
  const currentMs = parseWorkspaceRevision(current);
  const nowMs = parseWorkspaceRevision(nowRevision);
  if (Number.isFinite(currentMs) && Number.isFinite(nowMs) && nowMs <= currentMs) {
    return workspaceRevisionFromMs(currentMs + 1);
  }
  if (nowRevision !== current)
    return nowRevision;
  if (Number.isFinite(currentMs))
    return workspaceRevisionFromMs(currentMs + 1);
  return `${current}.1`;
}
function renderTemplate(template, values) {
  return template.replace(/\{([a-zA-Z0-9_]+)\}/g, (_match, key) => values[key] ?? "");
}
function createRoot2(input, db) {
  const d = db || getDatabase();
  const id = generateRootId();
  const ts = now();
  const slug = ensureUniqueSlug("roots", input.slug ?? workspaceSlugify(input.name), d);
  const basePath = resolve4(input.base_path);
  d.run(`INSERT INTO roots (
      id, slug, name, base_path, tags, default_kind, default_recipe_id,
      default_tmux_profile_id, github_org, repo_visibility, path_template,
      name_template, allowed_recipes, allowed_agents, metadata, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    slug,
    input.name,
    basePath,
    json(normalizeList(input.tags)),
    input.default_kind ?? null,
    input.default_recipe_id ?? null,
    input.default_tmux_profile_id ?? null,
    input.github_org ?? null,
    input.repo_visibility ?? null,
    input.path_template ?? null,
    input.name_template ?? null,
    json(normalizeList(input.allowed_recipes)),
    json(normalizeList(input.allowed_agents)),
    json(input.metadata ?? {}),
    ts,
    ts
  ]);
  return getRoot(id, d);
}
function getRoot(id, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM roots WHERE id = ?").get(id);
  return row ? rowToRoot(row) : null;
}
function getRootBySlug(slug, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM roots WHERE slug = ?").get(slug);
  return row ? rowToRoot(row) : null;
}
function listRoots(db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM roots ORDER BY slug ASC").all().map(rowToRoot);
}
function updateRoot(id, input, db) {
  const d = db || getDatabase();
  const before = getRoot(id, d);
  if (!before)
    throw new Error(`Root not found: ${id}`);
  const updates = [];
  const params = [];
  const set = (column, value) => {
    updates.push(`${column} = ?`);
    params.push(value);
  };
  if (input.slug !== undefined)
    set("slug", ensureUniqueSlug("roots", workspaceSlugify(input.slug), d, id));
  if (input.name !== undefined)
    set("name", input.name);
  if (input.base_path !== undefined)
    set("base_path", resolve4(input.base_path));
  if (input.tags !== undefined)
    set("tags", json(normalizeList(input.tags)));
  if (input.default_kind !== undefined)
    set("default_kind", input.default_kind);
  if (input.default_recipe_id !== undefined)
    set("default_recipe_id", input.default_recipe_id);
  if (input.default_tmux_profile_id !== undefined)
    set("default_tmux_profile_id", input.default_tmux_profile_id);
  if (input.github_org !== undefined)
    set("github_org", input.github_org);
  if (input.repo_visibility !== undefined)
    set("repo_visibility", input.repo_visibility);
  if (input.path_template !== undefined)
    set("path_template", input.path_template);
  if (input.name_template !== undefined)
    set("name_template", input.name_template);
  if (input.allowed_recipes !== undefined)
    set("allowed_recipes", json(normalizeList(input.allowed_recipes)));
  if (input.allowed_agents !== undefined)
    set("allowed_agents", json(normalizeList(input.allowed_agents)));
  if (input.metadata !== undefined)
    set("metadata", json(input.metadata));
  if (!updates.length)
    return before;
  set("updated_at", now());
  params.push(id);
  d.run(`UPDATE roots SET ${updates.join(", ")} WHERE id = ?`, params);
  return getRoot(id, d);
}
function deleteRoot(id, options = {}, db) {
  const d = db || getDatabase();
  const root = getRoot(id, d);
  if (!root)
    throw new Error(`Root not found: ${id}`);
  const count = d.query("SELECT COUNT(*) as n FROM workspaces WHERE root_id = ?").get(id).n;
  if (count > 0 && !options.detachWorkspaces) {
    throw new Error(`Root ${root.slug} is used by ${count} workspace(s); pass detachWorkspaces to clear those references before deletion.`);
  }
  if (count > 0) {
    d.run("UPDATE workspaces SET root_id = NULL, updated_at = ? WHERE root_id = ?", [now(), id]);
  }
  d.run("DELETE FROM roots WHERE id = ?", [id]);
  return { root, detached_workspaces: count };
}
function rankRoots(roots, input = {}) {
  const absPath = input.path ? resolve4(input.path) : undefined;
  const tags = new Set(input.tags ?? []);
  return roots.map((root) => {
    let score = 0;
    const reasons = [];
    if (absPath && (absPath === root.base_path || absPath.startsWith(`${root.base_path}/`))) {
      score += 1000 + root.base_path.length;
      reasons.push("path-prefix");
    }
    if (input.kind && root.default_kind === input.kind) {
      score += 50;
      reasons.push("kind");
    }
    if (input.github_org && root.github_org === input.github_org) {
      score += 40;
      reasons.push("github-org");
    }
    const tagMatches = root.tags.filter((tag) => tags.has(tag));
    if (tagMatches.length > 0) {
      score += tagMatches.length * 10;
      reasons.push(`tags:${tagMatches.join(",")}`);
    }
    return { root, score, reasons };
  }).filter((item) => item.score > 0).sort((a, b) => b.score - a.score || a.root.slug.localeCompare(b.root.slug));
}
function scoreRoots(input = {}, db) {
  const absPath = input.path ? resolve4(input.path) : undefined;
  const tags = new Set(input.tags ?? []);
  return listRoots(db).map((root) => {
    let score = 0;
    const reasons = [];
    if (absPath && (absPath === root.base_path || absPath.startsWith(`${root.base_path}/`))) {
      score += 1000 + root.base_path.length;
      reasons.push("path-prefix");
    }
    if (input.kind && root.default_kind === input.kind) {
      score += 50;
      reasons.push("kind");
    }
    if (input.github_org && root.github_org === input.github_org) {
      score += 40;
      reasons.push("github-org");
    }
    const tagMatches = root.tags.filter((tag) => tags.has(tag));
    if (tagMatches.length > 0) {
      score += tagMatches.length * 10;
      reasons.push(`tags:${tagMatches.join(",")}`);
    }
    return { root, score, reasons };
  }).filter((item) => item.score > 0).sort((a, b) => b.score - a.score || a.root.slug.localeCompare(b.root.slug));
}
function createAgent(input, db) {
  const d = db || getDatabase();
  const id = generateAgentId();
  const ts = now();
  const slug = ensureUniqueSlug("agents", input.slug ?? workspaceSlugify(input.name), d);
  d.run(`INSERT INTO agents (
      id, slug, name, kind, provider, model, role, permissions, metadata, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    slug,
    input.name,
    input.kind,
    input.provider ?? null,
    input.model ?? null,
    input.role ?? null,
    json(normalizeList(input.permissions)),
    json(input.metadata ?? {}),
    ts,
    ts
  ]);
  return getAgent(id, d);
}
function getAgent(id, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM agents WHERE id = ?").get(id);
  return row ? rowToAgent(row) : null;
}
function getAgentBySlug(slug, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM agents WHERE slug = ?").get(slug);
  return row ? rowToAgent(row) : null;
}
function listAgents(db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM agents ORDER BY slug ASC").all().map(rowToAgent);
}
function getMachine(slug, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM machines WHERE slug = ?").get(slug);
  return row ? rowToMachine(row) : null;
}
function listMachines(db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM machines ORDER BY slug ASC").all().map(rowToMachine);
}
function assertAgentPermission(agentId, permission, db) {
  if (!agentId)
    return;
  const agent = getAgent(agentId, db);
  if (!agent || agent.permissions.length === 0)
    return;
  if (agent.permissions.includes("*") || agent.permissions.includes(permission))
    return;
  throw new Error(`Agent ${agent.slug} does not have permission ${permission}`);
}
function isAllowedReference(allowed, id, slug) {
  if (allowed.length === 0)
    return true;
  return Boolean(id && allowed.includes(id) || slug && allowed.includes(slug));
}
function assertRootWorkspacePolicy(root, recipe, agentId, db) {
  if (!root)
    return;
  if (!isAllowedReference(root.allowed_recipes, recipe?.id, recipe?.slug)) {
    throw new Error(`Root ${root.slug} does not allow recipe ${recipe?.slug ?? "none"}`);
  }
  if (root.allowed_agents.length > 0) {
    const agent = agentId ? getAgent(agentId, db) : null;
    if (!isAllowedReference(root.allowed_agents, agent?.id, agent?.slug)) {
      throw new Error(`Root ${root.slug} does not allow agent ${agent?.slug ?? agentId ?? "unknown"}`);
    }
  }
}
function createRecipe(input, db) {
  const d = db || getDatabase();
  const id = generateRecipeId();
  const ts = now();
  const slug = ensureUniqueSlug("recipes", input.slug ?? workspaceSlugify(input.name), d);
  d.run(`INSERT INTO recipes (
      id, slug, name, description, kind, version, steps, variables, default_tags,
      default_tmux_profile_id, metadata, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    slug,
    input.name,
    input.description ?? null,
    input.kind ?? null,
    input.version ?? 1,
    json(input.steps ?? []),
    json(input.variables ?? {}),
    json(normalizeList(input.default_tags)),
    input.default_tmux_profile_id ?? null,
    json(input.metadata ?? {}),
    ts,
    ts
  ]);
  return getRecipe(id, d);
}
function getRecipe(id, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM recipes WHERE id = ?").get(id);
  return row ? rowToRecipe(row) : null;
}
function getRecipeBySlug(slug, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM recipes WHERE slug = ?").get(slug);
  return row ? rowToRecipe(row) : null;
}
function listRecipes(db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM recipes ORDER BY slug ASC").all().map(rowToRecipe);
}
function createTmuxProfile(input, db) {
  const d = db || getDatabase();
  const id = generateTmuxProfileId();
  const ts = now();
  const slug = ensureUniqueSlug("tmux_profiles", input.slug ?? workspaceSlugify(input.name), d);
  d.run(`INSERT INTO tmux_profiles (
      id, slug, name, description, session_template, attach, metadata, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    slug,
    input.name,
    input.description ?? null,
    input.session_template ?? "{slug}",
    input.attach ? 1 : 0,
    json(input.metadata ?? {}),
    ts,
    ts
  ]);
  for (const window of input.windows ?? []) {
    addTmuxProfileWindow({ ...window, profile_id: id }, d);
  }
  return getTmuxProfile(id, d);
}
function getTmuxProfile(id, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM tmux_profiles WHERE id = ?").get(id);
  return row ? rowToTmuxProfile(row) : null;
}
function getTmuxProfileBySlug(slug, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM tmux_profiles WHERE slug = ?").get(slug);
  return row ? rowToTmuxProfile(row) : null;
}
function resolveTmuxProfile(idOrSlug, db) {
  const d = db || getDatabase();
  return getTmuxProfile(idOrSlug, d) ?? getTmuxProfileBySlug(idOrSlug, d);
}
function listTmuxProfiles(db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM tmux_profiles ORDER BY slug ASC").all().map(rowToTmuxProfile);
}
function addTmuxProfileWindow(input, db) {
  const d = db || getDatabase();
  const profile = getTmuxProfile(input.profile_id, d);
  if (!profile)
    throw new Error(`Tmux profile not found: ${input.profile_id}`);
  const id = generateTmuxProfileWindowId();
  d.run(`INSERT INTO tmux_profile_windows (
      id, profile_id, window_name_template, path_template, command, window_index,
      detached, env, revive, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON CONFLICT(profile_id, window_name_template) DO UPDATE SET
      path_template = excluded.path_template,
      command = excluded.command,
      window_index = excluded.window_index,
      detached = excluded.detached,
      env = excluded.env,
      revive = excluded.revive`, [
    id,
    input.profile_id,
    input.window_name_template,
    input.path_template ?? null,
    input.command ?? null,
    input.window_index ?? null,
    input.detached === false ? 0 : 1,
    json(input.env ?? {}),
    input.revive === false ? 0 : 1,
    now()
  ]);
  const row = d.query("SELECT * FROM tmux_profile_windows WHERE profile_id = ? AND window_name_template = ?").get(input.profile_id, input.window_name_template);
  if (!row)
    throw new Error(`Tmux profile window was not written: ${input.window_name_template}`);
  return rowToTmuxProfileWindow(row);
}
function listTmuxProfileWindows(profileId, db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM tmux_profile_windows WHERE profile_id = ? ORDER BY COALESCE(window_index, 9999), window_name_template ASC").all(profileId).map(rowToTmuxProfileWindow);
}
function machineId() {
  return hostname();
}
function hasOwn(metadata, key) {
  return Object.prototype.hasOwnProperty.call(metadata, key);
}
function canonicalMachineFromMetadata(metadata) {
  if (!hasOwn(metadata, "canonical_machine"))
    return;
  const value = metadata["canonical_machine"];
  if (value === null)
    return null;
  if (typeof value !== "string") {
    throw new Error("canonical_machine metadata must be a machine slug string");
  }
  return value.trim() || null;
}
function withoutCanonicalMachineMetadata(metadata) {
  const copy = { ...metadata };
  delete copy["canonical_machine"];
  return copy;
}
function deriveWorkspacePath(input, root, slug, id, kind) {
  if (input.primary_path)
    return resolve4(input.primary_path);
  if (!root && kind !== "remote-only")
    return projectWorkspaceStorePath(id);
  if (!root)
    return null;
  const rendered = renderTemplate(root.path_template || root.name_template || "{slug}", {
    slug,
    name: input.name,
    kind,
    root: root.slug,
    org: root.github_org
  });
  return isAbsolute(rendered) ? resolve4(rendered) : resolve4(join4(root.base_path, rendered));
}
function createWorkspace(input, db) {
  const d = db || getDatabase();
  const id = input.id ? assertProjectWorkspaceId(input.id) : generateWorkspaceId();
  const ts = now();
  const requestedSlug = input.slug ?? workspaceSlugify(input.name);
  const slugBase = input.require_exact_identity ? workspaceSlugify(requestedSlug) : requestedSlug;
  const slug = input.require_exact_identity ? slugBase : ensureUniqueSlug("workspaces", slugBase, d);
  const root = input.root_id ? getRoot(input.root_id, d) : null;
  if (input.root_id && !root)
    throw new Error(`Root not found: ${input.root_id}`);
  const recipe = input.recipe_id ? getRecipe(input.recipe_id, d) : null;
  if (input.recipe_id && !recipe)
    throw new Error(`Recipe not found: ${input.recipe_id}`);
  assertAgentPermission(input.agent_id, "workspace:create", d);
  assertRootWorkspacePolicy(root, recipe, input.agent_id, d);
  const kind = input.kind ?? recipe?.kind ?? root?.default_kind ?? "generic";
  const primaryPath = deriveWorkspacePath(input, root, slug, id, kind);
  const tags = normalizeList([
    ...root?.tags ?? [],
    ...recipe?.default_tags ?? [],
    ...input.tags ?? []
  ]);
  const metadata = normalizeProjectMetadata(input.metadata);
  d.run(`INSERT INTO workspaces (
      id, slug, name, description, kind, status, root_id, recipe_id, primary_path,
      git_remote, s3_bucket, s3_prefix, tags, integrations, metadata, created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    slug,
    input.name,
    input.description ?? null,
    kind,
    root?.id ?? null,
    recipe?.id ?? null,
    primaryPath,
    input.git_remote ?? null,
    input.s3_bucket ?? null,
    input.s3_prefix ?? null,
    json(tags),
    json(input.integrations ?? {}),
    json(metadata),
    ts,
    ts
  ]);
  if (primaryPath) {
    addWorkspaceLocation({
      workspace_id: id,
      path: primaryPath,
      label: "main",
      kind: input.git_remote && !existsSync5(primaryPath) ? "remote-intended" : "local",
      is_primary: true,
      metadata: {}
    }, d);
  }
  if (input.agent_id) {
    assignAgentToWorkspace(id, input.agent_id, "creator", input.agent_id, { source: input.source ?? "cli" }, d);
  }
  const workspace = getWorkspace(id, d);
  recordWorkspaceEvent({
    workspace_id: id,
    agent_id: input.agent_id,
    event_type: "created",
    source: input.source ?? "cli",
    prompt: input.prompt,
    command: input.command,
    after: workspace,
    metadata: { root_slug: root?.slug, recipe_slug: recipe?.slug }
  }, d);
  return workspace;
}
function getWorkspace(id, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM workspaces WHERE id = ?").get(id);
  return row ? rowToWorkspace(row) : null;
}
function getWorkspaceBySlug(slug, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM workspaces WHERE slug = ?").get(slug);
  return row ? rowToWorkspace(row) : null;
}
function listWorkspacesByPath(path, db) {
  const d = db || getDatabase();
  const absPath = resolve4(path);
  const rows = d.query(`
      SELECT DISTINCT w.*
      FROM workspaces w
      LEFT JOIN workspace_locations loc ON loc.workspace_id = w.id
      WHERE w.primary_path = ? OR loc.path = ?
      ORDER BY
        CASE WHEN w.primary_path = ? THEN 0 ELSE 1 END,
        w.name ASC
    `).all(absPath, absPath, absPath);
  return rows.map(rowToWorkspace);
}
function workspaceFilterSql(filter) {
  const conditions = [];
  const params = [];
  if (filter.status) {
    conditions.push("status = ?");
    params.push(filter.status);
  }
  if (filter.kind) {
    conditions.push("kind = ?");
    params.push(filter.kind);
  }
  if (filter.root_id) {
    conditions.push("root_id = ?");
    params.push(filter.root_id);
  }
  if (filter.query) {
    const scope = filter.query_scope;
    const normalizedQuery = filter.query.toLowerCase();
    const q = `%${scope === undefined ? normalizedQuery : normalizedQuery.replace(/[\\%_]/g, "\\$&")}%`;
    const columns = scope === undefined ? ["name", "slug", "COALESCE(description, '')", "COALESCE(primary_path, '')", "COALESCE(tags, '')", "COALESCE(integrations, '')", "COALESCE(metadata, '')"] : scope === "identity" ? ["name", "slug"] : scope === "discovery" ? ["name", "slug", "COALESCE(description, '')", "COALESCE(tags, '')"] : scope === "structured" ? ["name", "slug", "COALESCE(description, '')", "COALESCE(tags, '')", "COALESCE(integrations, '')", "COALESCE(metadata, '')"] : ["name", "slug", "COALESCE(description, '')", "COALESCE(primary_path, '')", "COALESCE(tags, '')", "COALESCE(integrations, '')", "COALESCE(metadata, '')"];
    const escape = scope === undefined ? "" : " ESCAPE '\\'";
    conditions.push(`(${columns.map((column) => `lower(${column}) LIKE ?${escape}`).join(" OR ")})`);
    params.push(...columns.map(() => q));
  }
  if (filter.tags && filter.tags.length > 0) {
    for (const tag of filter.tags) {
      conditions.push("EXISTS (SELECT 1 FROM json_each(workspaces.tags) WHERE json_each.value = ?)");
      params.push(tag);
    }
  }
  if (filter.exclude_eval_artifacts) {
    conditions.push(`NOT (
      substr(slug, 1, 5) = 'eval-'
      OR substr(name, 1, 5) = 'Eval '
      OR EXISTS (
        SELECT 1 FROM json_each(workspaces.tags)
        WHERE json_each.value = 'eval' OR substr(json_each.value, 1, 5) = 'eval-'
      )
      OR COALESCE(json_type(metadata, '$.eval_fixture') = 'true', 0)
      OR COALESCE(json_type(metadata, '$.agent_eval_fixture') = 'true', 0)
    )`);
  }
  if (filter.exclude_registry_fixtures) {
    conditions.push(`NOT EXISTS (
      SELECT 1 FROM json_each(workspaces.tags)
      WHERE json_each.value = 'registry-fixture'
    )`);
  }
  return { where: conditions.length ? `WHERE ${conditions.join(" AND ")}` : "", params };
}
function listWorkspaces(filter = {}, db) {
  const d = db || getDatabase();
  const { where, params } = workspaceFilterSql(filter);
  const rows = d.query(`SELECT * FROM workspaces ${where} ORDER BY name ASC, id ASC LIMIT ? OFFSET ?`).all(...params, filter.limit ?? -1, filter.offset ?? 0);
  return rows.map(rowToWorkspace);
}
function countWorkspaces(filter = {}, db) {
  const d = db || getDatabase();
  const { where, params } = workspaceFilterSql(filter);
  const row = d.query(`SELECT COUNT(*) AS n FROM workspaces ${where}`).get(...params);
  return row?.n ?? 0;
}
function resolveWorkspace(idOrSlug, db) {
  const d = db || getDatabase();
  return getWorkspace(idOrSlug, d) ?? getWorkspaceBySlug(idOrSlug, d);
}
function updateWorkspace(id, input, db) {
  const d = db || getDatabase();
  const before = getWorkspace(id, d);
  if (!before)
    throw new Error(`Workspace not found: ${id}`);
  assertAgentPermission(input.agent_id, input.status === "deleted" ? "workspace:delete" : "workspace:update", d);
  const root = input.root_id === undefined || input.root_id === null ? null : getRoot(input.root_id, d);
  if (input.root_id && !root)
    throw new Error(`Root not found: ${input.root_id}`);
  const recipe = input.recipe_id === undefined || input.recipe_id === null ? null : getRecipe(input.recipe_id, d);
  if (input.recipe_id && !recipe)
    throw new Error(`Recipe not found: ${input.recipe_id}`);
  const inputMetadataMachine = input.metadata === undefined ? undefined : canonicalMachineFromMetadata(input.metadata);
  const existingMetadataMachine = canonicalMachineFromMetadata(before.metadata);
  let canonicalMachine = input.canonical_machine;
  if (canonicalMachine === undefined && inputMetadataMachine !== undefined) {
    canonicalMachine = inputMetadataMachine;
  } else if (canonicalMachine === undefined && before.canonical_machine === null && existingMetadataMachine !== undefined) {
    canonicalMachine = existingMetadataMachine;
  }
  if (typeof canonicalMachine === "string") {
    canonicalMachine = canonicalMachine.trim();
    if (!canonicalMachine)
      throw new Error("Canonical machine must not be empty");
    if (!getMachine(canonicalMachine, d))
      throw new Error(`Machine not found: ${canonicalMachine}`);
  }
  let metadata = input.metadata;
  if (metadata !== undefined && inputMetadataMachine !== undefined) {
    metadata = withoutCanonicalMachineMetadata(metadata);
  } else if (metadata === undefined && existingMetadataMachine !== undefined) {
    metadata = withoutCanonicalMachineMetadata(before.metadata);
  }
  if (metadata !== undefined) {
    metadata = normalizeProjectMetadata(metadata, before.metadata);
  }
  if (input.integrations !== undefined) {
    assertProjectResourceLinkIntegrationMutation(before.integrations, input.integrations, listProjectResourceLinks(id, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, d));
  }
  const updates = [];
  const params = [];
  const set = (column, value) => {
    updates.push(`${column} = ?`);
    params.push(value);
  };
  if (input.name !== undefined)
    set("name", input.name);
  if (input.slug !== undefined)
    set("slug", ensureUniqueSlug("workspaces", workspaceSlugify(input.slug), d, id));
  if (input.description !== undefined)
    set("description", input.description);
  if (input.kind !== undefined)
    set("kind", input.kind);
  if (input.status !== undefined)
    set("status", input.status);
  if (input.root_id !== undefined)
    set("root_id", input.root_id);
  if (input.recipe_id !== undefined)
    set("recipe_id", input.recipe_id);
  if (canonicalMachine !== undefined)
    set("canonical_machine", canonicalMachine);
  if (input.primary_path !== undefined)
    set("primary_path", input.primary_path ? resolve4(input.primary_path) : null);
  if (input.git_remote !== undefined)
    set("git_remote", input.git_remote);
  if (input.s3_bucket !== undefined)
    set("s3_bucket", input.s3_bucket);
  if (input.s3_prefix !== undefined)
    set("s3_prefix", input.s3_prefix);
  if (input.tags !== undefined)
    set("tags", json(normalizeList(input.tags)));
  if (input.integrations !== undefined)
    set("integrations", json(input.integrations));
  if (metadata !== undefined)
    set("metadata", json(metadata));
  if (input.last_opened_at !== undefined)
    set("last_opened_at", input.last_opened_at);
  if (updates.length > 0) {
    updates.push("updated_at = ?");
    params.push(nextWorkspaceRevision(before.updated_at));
    params.push(id);
    d.run(`UPDATE workspaces SET ${updates.join(", ")} WHERE id = ?`, params);
  }
  let after = getWorkspace(id, d);
  if (input.primary_path !== undefined) {
    if (input.primary_path) {
      addWorkspaceLocation({
        workspace_id: id,
        path: input.primary_path,
        label: "main",
        kind: after.git_remote && !existsSync5(resolve4(input.primary_path)) ? "remote-intended" : "local",
        is_primary: true,
        metadata: {}
      }, d);
    } else {
      d.run("UPDATE workspace_locations SET is_primary = 0 WHERE workspace_id = ?", [id]);
    }
    after = getWorkspace(id, d);
  }
  recordWorkspaceEvent({
    workspace_id: id,
    agent_id: input.agent_id,
    event_type: "updated",
    source: input.source ?? "cli",
    prompt: input.prompt,
    command: input.command,
    before,
    after
  }, d);
  return after;
}
function assertGuardedReceiptTargetExists(targetId, db) {
  const target = db.query("SELECT id FROM workspaces WHERE id = ?").get(targetId);
  if (!target)
    throw new Error(`guarded project mutation receipt target not found: ${targetId}`);
}
function insertGuardedProjectMutationReceipt(input, db) {
  const inserted = db.run(`INSERT INTO guarded_project_mutation_receipts (
      receipt_id, operation_id, step_id, direction, idempotency_key, target_id,
      request_digest, precondition_digest, expected_revision, outcome, reason,
      result_project_id, duplicate_of_receipt_id, before_json, after_json,
      post_revision
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON CONFLICT (receipt_id) DO NOTHING`, [
    input.receipt_id,
    input.operation_id,
    input.step_id,
    input.direction,
    input.idempotency_key,
    input.target_id,
    input.request_digest,
    input.precondition_digest,
    input.expected_revision,
    input.outcome,
    input.reason,
    input.result_project_id,
    input.duplicate_of_receipt_id,
    input.before === null ? null : json(redactProjectValue(input.before)),
    input.after === null ? null : json(redactProjectValue(input.after)),
    input.post_revision
  ]);
  const row = db.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(input.receipt_id);
  if (!row)
    throw new Error(`guarded project mutation receipt readback failed: ${input.receipt_id}`);
  if (inserted.changes === 0)
    assertGuardedReceiptTargetExists(input.target_id, db);
  return rowToGuardedReceipt(row);
}
function findGuardedAcceptedReceipt(input, db) {
  const row = db.query(`SELECT * FROM guarded_project_mutation_receipts
     WHERE operation_id = ? AND step_id = ? AND direction = ? AND idempotency_key = ?
       AND target_id = ? AND outcome = 'accepted'
     ORDER BY created_at ASC, receipt_id ASC`).get(input.operation_id, input.step_id, input.direction, input.idempotency_key, input.target_id);
  return row ? rowToGuardedReceipt(row) : null;
}
function findGuardedAcceptedByStep(input, db) {
  const row = db.query(`SELECT * FROM guarded_project_mutation_receipts
     WHERE operation_id = ? AND step_id = ? AND direction = ? AND target_id = ?
       AND outcome = 'accepted'
     ORDER BY created_at ASC, receipt_id ASC`).get(input.operation_id, input.step_id, input.direction, input.target_id);
  return row ? rowToGuardedReceipt(row) : null;
}
function requireForwardProjectResourceLinkReceipt(receiptId, projectId, db) {
  const row = db.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(receiptId);
  if (!row)
    throw new Error(`accepted receipt not found: ${receiptId}`);
  const accepted = rowToGuardedReceipt(row);
  if (accepted.outcome !== "accepted" || accepted.direction !== "forward" || accepted.target_id !== projectId) {
    throw new Error("resource link rollback requires a forward accepted receipt for the same project id");
  }
  if (!accepted.post_revision) {
    throw new Error("resource link rollback accepted receipt has no post_revision");
  }
  return accepted;
}
function terminalNonacceptanceReceipt(input, db) {
  return insertGuardedProjectMutationReceipt({
    receipt_id: buildReceiptId({ ...input, outcome: "terminal_nonacceptance", suffix: input.reason }),
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: input.direction,
    idempotency_key: input.idempotency_key,
    target_id: input.target_id,
    request_digest: input.request_digest,
    precondition_digest: input.precondition_digest,
    expected_revision: input.expected_revision,
    outcome: "terminal_nonacceptance",
    reason: input.reason,
    result_project_id: null,
    duplicate_of_receipt_id: null,
    before: input.before_snapshot ?? (input.before ? workspaceSnapshot(input.before) : null),
    after: null,
    post_revision: null
  }, db);
}
function duplicateOfAcceptedReceipt(accepted, before, db, beforeSnapshot) {
  const receiptId = buildReceiptId({
    operation_id: accepted.operation_id,
    step_id: accepted.step_id,
    direction: accepted.direction,
    idempotency_key: accepted.idempotency_key,
    outcome: "duplicate_of_accepted",
    target_id: accepted.target_id,
    suffix: accepted.receipt_id
  });
  const existing = db.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(receiptId);
  if (existing)
    return rowToGuardedReceipt(existing);
  return insertGuardedProjectMutationReceipt({
    receipt_id: receiptId,
    operation_id: accepted.operation_id,
    step_id: accepted.step_id,
    direction: accepted.direction,
    idempotency_key: accepted.idempotency_key,
    target_id: accepted.target_id,
    request_digest: accepted.request_digest,
    precondition_digest: accepted.precondition_digest,
    expected_revision: accepted.expected_revision,
    outcome: "duplicate_of_accepted",
    reason: null,
    result_project_id: accepted.result_project_id,
    duplicate_of_receipt_id: accepted.receipt_id,
    before: beforeSnapshot ?? workspaceSnapshot(before),
    after: accepted.after,
    post_revision: accepted.post_revision
  }, db);
}
function assertProjectResourceLinkMaxItems(maxItems) {
  if (!Number.isInteger(maxItems) || maxItems <= 0) {
    throw new Error("project resource link max_items must be a positive integer");
  }
}
function listProjectResourceLinkRows(projectId, maxItems, db) {
  assertProjectResourceLinkMaxItems(maxItems);
  const rows = db.query(`SELECT * FROM project_resource_links
     WHERE project_id = ?
     ORDER BY authority, service_instance, source_package, target_kind, locator_kind, locator_value, id
     LIMIT ?`).all(projectId, maxItems + 1);
  if (rows.length > maxItems) {
    throw new Error(`project resource link collection exceeds max_items: more than ${maxItems}`);
  }
  return rows;
}
function listProjectResourceLinks(projectId, maxItems = PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, db) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(projectId);
  return listProjectResourceLinkRows(projectId, maxItems, d).map(rowToProjectResourceLink);
}
function readProjectResourceLinks(input, db, startedAt = Date.now()) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(input.project_id);
  assertProjectResourceLinkMaxItems(input.max_items);
  const project = getWorkspace(input.project_id, d);
  if (!project)
    throw new Error(`Workspace not found: ${input.project_id}`);
  const links = listProjectResourceLinks(input.project_id, input.max_items, d);
  const read = {
    ok: true,
    project_id: project.id,
    project,
    current_revision: workspaceRevision(project),
    links,
    link_count: links.length,
    max_items: input.max_items,
    collection_digest: projectResourceLinksDigest(links),
    complete: true,
    truncated: false,
    contract: projectResourceLinkCollection(project.id, workspaceRevision(project), links, input.max_items)
  };
  assertProjectResourceLinkReadContractEquality(read);
  return withResponseControl(read, input, startedAt, "project resource link read");
}
function projectResourceLinkInputFromStored(link) {
  const { id: _id, project_id: _projectId, created_at: _createdAt, updated_at: _updatedAt, ...input } = link;
  return input;
}
function desiredProjectResourceLinks(projectId, mode, requested, before, preserve) {
  const normalized = normalizeProjectResourceLinks(requested);
  const beforeById = new Map(before.map((link) => [link.id, link]));
  const preserveById = new Map((preserve ?? []).map((link) => [link.id, link]));
  const requestedLinks = normalized.map((input) => {
    const id = projectResourceLinkId(projectId, input);
    const existing = beforeById.get(id);
    const restored = preserveById.get(id);
    const timestamp = restored?.created_at ?? existing?.created_at ?? now();
    return {
      id,
      project_id: projectId,
      ...input,
      labels: input.labels ?? {},
      created_at: timestamp,
      updated_at: restored?.updated_at ?? (existing && existing.scope === input.scope && canonicalJson(existing.labels) === canonicalJson(input.labels ?? {}) ? existing.updated_at : now())
    };
  });
  const combined = mode === "add" ? [...before, ...requestedLinks.filter((link) => !beforeById.has(link.id))] : requestedLinks;
  return combined.sort((a, b) => canonicalJson({
    authority: a.authority,
    service_instance: a.service_instance,
    source_package: a.source_package,
    target_kind: a.target_kind,
    locator_kind: a.locator.kind,
    locator_value: a.locator.value
  }).localeCompare(canonicalJson({
    authority: b.authority,
    service_instance: b.service_instance,
    source_package: b.source_package,
    target_kind: b.target_kind,
    locator_kind: b.locator.kind,
    locator_value: b.locator.value
  })));
}
function replaceProjectResourceLinks(projectId, links, db) {
  const desiredIds = new Set(links.map((link) => link.id));
  for (const existing of listProjectResourceLinks(projectId, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, db)) {
    if (!desiredIds.has(existing.id))
      db.run("DELETE FROM project_resource_links WHERE id = ?", [existing.id]);
  }
  for (const link of links) {
    const existing = db.query("SELECT * FROM project_resource_links WHERE id = ?").get(link.id);
    if (existing) {
      const current = rowToProjectResourceLink(existing);
      if (current.scope !== link.scope || canonicalJson(current.labels) !== canonicalJson(link.labels)) {
        db.run("UPDATE project_resource_links SET scope = ?, labels_json = ?, updated_at = ? WHERE id = ?", [link.scope, canonicalJson(link.labels), link.updated_at, link.id]);
      }
      continue;
    }
    db.run(`INSERT INTO project_resource_links (
        id, project_id, authority, service_instance, source_package, target_kind,
        locator_kind, locator_value, scope, labels_json, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
      link.id,
      link.project_id,
      link.authority,
      link.service_instance,
      link.source_package,
      link.target_kind,
      link.locator.kind,
      link.locator.value,
      link.scope,
      canonicalJson(link.labels),
      link.created_at,
      link.updated_at
    ]);
  }
}
function listWorkspaceLocationsBounded(workspaceId, maxItems, db) {
  if (!Number.isInteger(maxItems) || maxItems <= 0) {
    throw new Error("project quarantine workspace_location_max_items must be a positive integer");
  }
  const rows = db.query(`SELECT * FROM workspace_locations
     WHERE workspace_id = ?
     ORDER BY is_primary DESC, created_at ASC, id ASC
     LIMIT ?`).all(workspaceId, maxItems + 1);
  if (rows.length > maxItems) {
    throw new Error(`project quarantine workspace-location collection exceeds max_items: more than ${maxItems}`);
  }
  return rows.map(rowToLocation);
}
function replaceWorkspaceLocations(workspaceId, locations, db) {
  db.run("DELETE FROM workspace_locations WHERE workspace_id = ?", [workspaceId]);
  for (const location of locations) {
    db.run(`INSERT INTO workspace_locations (
        id, workspace_id, path, machine_id, label, kind, is_primary,
        exists_at_create, metadata, created_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
      location.id,
      workspaceId,
      location.path,
      location.machine_id,
      location.label,
      location.kind,
      location.is_primary ? 1 : 0,
      location.exists_at_create ? 1 : 0,
      json(location.metadata),
      location.created_at
    ]);
  }
}
function applyProjectQuarantineWorkspacePatch(projectId, patch, expectedRevision, db) {
  const before = getWorkspace(projectId, db);
  if (!before)
    throw new Error(`Workspace not found: ${projectId}`);
  if (before.updated_at !== expectedRevision) {
    throw new Error("project quarantine conditional update lost");
  }
  const after = previewWorkspacePatch(before, patch);
  const nextRevision = nextWorkspaceRevision(expectedRevision);
  const result = db.run(`UPDATE workspaces SET
      name = ?, slug = ?, description = ?, kind = ?, status = ?, root_id = ?, recipe_id = ?,
      canonical_machine = ?, primary_path = ?, git_remote = ?, s3_bucket = ?, s3_prefix = ?,
      tags = ?, integrations = ?, metadata = ?, last_opened_at = ?, updated_at = ?
     WHERE id = ? AND updated_at = ?`, [
    after.name,
    after.slug,
    after.description,
    after.kind,
    after.status,
    after.root_id,
    after.recipe_id,
    after.canonical_machine,
    after.primary_path,
    after.git_remote,
    after.s3_bucket,
    after.s3_prefix,
    json(after.tags),
    json(after.integrations),
    json(after.metadata),
    after.last_opened_at,
    nextRevision,
    projectId,
    expectedRevision
  ]);
  if (result.changes !== 1)
    throw new Error("project quarantine conditional update lost");
  return getWorkspace(projectId, db);
}
function snapshotJson(snapshot) {
  return snapshot;
}
function parseResourceLinkSnapshot(value, label) {
  const snapshot = value;
  if (!snapshot?.project?.id || !Array.isArray(snapshot.links) || typeof snapshot.collection_digest !== "string") {
    throw new Error(`${label} receipt snapshot is incomplete`);
  }
  return snapshot;
}
function mutateProjectResourceLinksInternal(input, db, options = {}) {
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  const maxItems = input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS;
  assertProjectResourceLinkMaxItems(maxItems);
  const direction = options.direction ?? "forward";
  const normalized = normalizeProjectResourceLinks(input.links);
  if (direction === "forward")
    assertProjectResourceLinksWritable(normalized);
  const forcedIntegrations = normalizeProjectResourceLinkIntegrations(options.forced_integrations ?? input.integrations);
  if (normalized.length > maxItems) {
    throw new Error(`project resource link request exceeds max_items: ${normalized.length} > ${maxItems}`);
  }
  const reqDigest = sha256(canonicalJson({
    mode: input.mode,
    links: normalized,
    integrations: forcedIntegrations ?? null
  }));
  const preDigest = preconditionDigest({ project_id: input.project_id, expected_revision: input.expected_revision });
  const idempotencyKey = deriveGuardedIdempotencyKey({
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction,
    target_id: input.project_id,
    request_digest: reqDigest,
    precondition_digest: preDigest
  });
  return db.transaction(() => {
    const beforeProject = getWorkspace(input.project_id, db);
    if (!beforeProject)
      throw new Error(`Workspace not found: ${input.project_id}`);
    const beforeLinks = listProjectResourceLinks(input.project_id, maxItems, db);
    const before = projectResourceLinkSnapshot(beforeProject, beforeLinks);
    const currentRevision = workspaceRevision(beforeProject);
    const duplicate = findGuardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    }, db);
    if (duplicate) {
      const duplicateReceipt = duplicateOfAcceptedReceipt(duplicate, beforeProject, db, snapshotJson(before));
      return withResponseControl({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: parseResourceLinkSnapshot(duplicate.after, "accepted"),
        receipt: duplicateReceipt
      }, input, started, "project resource link mutation");
    }
    const priorAccepted = findGuardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      target_id: input.project_id
    }, db);
    if (priorAccepted) {
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "changed_request_or_precondition_for_step",
        before_snapshot: snapshotJson(before)
      }, db);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: null,
        receipt: receipt2
      }, input, started, "project resource link mutation");
    }
    if (currentRevision !== input.expected_revision) {
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "stale_revision",
        before_snapshot: snapshotJson(before)
      }, db);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: null,
        receipt: receipt2
      }, input, started, "project resource link mutation");
    }
    const desired = desiredProjectResourceLinks(input.project_id, input.mode, normalized, beforeLinks, options.preserve_links);
    if (desired.length > maxItems) {
      throw new Error(`project resource link collection exceeds max_items: ${desired.length} > ${maxItems}`);
    }
    const integrations = forcedIntegrations ?? projectResourceLinkIntegrationProjection(beforeProject.integrations, beforeLinks, desired);
    assertProjectChannelIntegrationWritable(integrations, beforeProject.integrations);
    const previewProject = { ...beforeProject, integrations };
    const preview = projectResourceLinkSnapshot(previewProject, desired);
    if (input.dry_run) {
      return withResponseControl({
        ok: true,
        dry_run: true,
        outcome: "planned",
        mode: input.mode,
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: preview,
        receipt: null
      }, input, started, "project resource link mutation");
    }
    if (timedOut(started, input.time_budget_ms))
      throw new Error("project resource link mutation time budget exceeded before write");
    const changed = canonicalJson(before.links) !== canonicalJson(desired) || canonicalJson(beforeProject.integrations) !== canonicalJson(integrations);
    let afterProject = beforeProject;
    if (changed) {
      replaceProjectResourceLinks(input.project_id, desired, db);
      const nextRevision = nextWorkspaceRevision(currentRevision);
      const update = db.run("UPDATE workspaces SET integrations = ?, updated_at = ? WHERE id = ? AND updated_at = ?", [canonicalJson(integrations), nextRevision, input.project_id, currentRevision]);
      if (update.changes !== 1)
        throw new Error("project resource link conditional update lost");
      afterProject = getWorkspace(input.project_id, db);
    }
    const afterLinks = listProjectResourceLinks(input.project_id, maxItems, db);
    const after = projectResourceLinkSnapshot(afterProject, afterLinks);
    if (after.collection_digest !== projectResourceLinksDigest(desired)) {
      throw new Error("project resource link exact readback mismatch");
    }
    const receipt = insertGuardedProjectMutationReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: afterProject.id,
      duplicate_of_receipt_id: null,
      before: snapshotJson(before),
      after: snapshotJson(after),
      post_revision: workspaceRevision(afterProject)
    }, db);
    recordWorkspaceEvent({
      workspace_id: afterProject.id,
      agent_id: input.agent_id,
      event_type: direction === "inverse" ? "project_resource_links_rollback" : `project_resource_links_${input.mode}`,
      source: input.source ?? "cli",
      command: input.command,
      before: snapshotJson(before),
      after: snapshotJson(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id,
        idempotency_key: idempotencyKey,
        collection_digest: after.collection_digest
      }
    }, db);
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      mode: input.mode,
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: currentRevision,
      before,
      after,
      receipt
    }, input, started, "project resource link mutation");
  })();
}
function mutateProjectResourceLinks(input, db) {
  return mutateProjectResourceLinksInternal(input, db || getDatabase());
}
function mutateProjectResourceLinksForRegistration(input, integrations, db) {
  return mutateProjectResourceLinksInternal(input, db || getDatabase(), {
    forced_integrations: integrations
  });
}
function rollbackProjectResourceLinks(input, db) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(input.project_id);
  const accepted = requireForwardProjectResourceLinkReceipt(input.accepted_receipt_id, input.project_id, d);
  if (accepted.post_revision !== input.expected_current_revision) {
    throw new Error("resource link rollback expected_current_revision must equal the accepted receipt post_revision");
  }
  const before = parseResourceLinkSnapshot(accepted.before, "accepted before");
  const after = parseResourceLinkSnapshot(accepted.after, "accepted after");
  const current = readProjectResourceLinks({
    project_id: input.project_id,
    max_items: input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  }, d);
  const priorInverse = findGuardedAcceptedByStep({
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: "inverse",
    target_id: input.project_id
  }, d);
  if (priorInverse) {
    const inverseBefore = parseResourceLinkSnapshot(priorInverse.before, "accepted inverse before");
    const inverseAfter = parseResourceLinkSnapshot(priorInverse.after, "accepted inverse after");
    if (priorInverse.expected_revision !== input.expected_current_revision || inverseBefore.collection_digest !== after.collection_digest || canonicalJson(inverseBefore.project.integrations) !== canonicalJson(after.project.integrations) || inverseAfter.collection_digest !== before.collection_digest || canonicalJson(inverseAfter.project.integrations) !== canonicalJson(before.project.integrations)) {
      throw new Error("accepted resource link inverse receipt does not match the forward receipt");
    }
    if (!priorInverse.post_revision || current.current_revision !== priorInverse.post_revision || current.collection_digest !== inverseAfter.collection_digest || canonicalJson(current.project.integrations) !== canonicalJson(inverseAfter.project.integrations)) {
      throw new Error("resource link rollback retry refuses drift after the accepted inverse");
    }
  } else if (current.current_revision !== input.expected_current_revision || current.collection_digest !== after.collection_digest) {
    throw new Error("resource link rollback refuses current revision or collection digest drift");
  }
  return mutateProjectResourceLinksInternal({
    project_id: input.project_id,
    operation_id: input.operation_id,
    step_id: input.step_id,
    mode: "reconcile",
    expected_revision: input.expected_current_revision,
    links: before.links.map(projectResourceLinkInputFromStored),
    max_items: input.max_items,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms,
    agent_id: input.agent_id,
    source: input.source,
    command: input.command
  }, d, {
    direction: "inverse",
    forced_integrations: before.project.integrations,
    preserve_links: before.links
  });
}
function readDuplicateProjectQuarantinePreimage(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  assertProjectResourceLinkMaxItems(input.resource_link_max_items);
  const project = getWorkspace(input.project_id, d);
  if (!project)
    throw new Error(`Workspace not found: ${input.project_id}`);
  const links = listProjectResourceLinks(input.project_id, input.resource_link_max_items, d);
  const locations = listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items, d);
  const snapshot = projectQuarantineSnapshot(project, links, locations);
  return withResponseControl({
    ok: true,
    project_id: project.id,
    current_revision: project.updated_at,
    snapshot,
    resource_link_count: links.length,
    workspace_location_count: locations.length,
    complete: true,
    truncated: false
  }, input, started, "project quarantine preimage read");
}
function quarantineDuplicateProject(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  assertProjectResourceLinkMaxItems(input.resource_link_max_items);
  if (!Number.isInteger(input.workspace_location_max_items) || input.workspace_location_max_items <= 0) {
    throw new Error("project quarantine workspace_location_max_items must be a positive integer");
  }
  const expectedIds = normalizedExpectedResourceLinkIds(input);
  const reqDigest = projectQuarantineRequestDigest(input);
  const preDigest = projectQuarantinePreconditionDigest(input, expectedIds);
  const idempotencyKey = deriveGuardedIdempotencyKey({
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: "forward",
    target_id: input.project_id,
    request_digest: reqDigest,
    precondition_digest: preDigest
  });
  return d.transaction(() => {
    const beforeProject = getWorkspace(input.project_id, d);
    if (!beforeProject)
      throw new Error(`Workspace not found: ${input.project_id}`);
    const beforeLinks = listProjectResourceLinks(input.project_id, input.resource_link_max_items, d);
    const beforeLocations = listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items, d);
    const before = projectQuarantineSnapshot(beforeProject, beforeLinks, beforeLocations);
    const duplicate = findGuardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    }, d);
    if (duplicate) {
      const acceptedAfter = parseProjectQuarantineSnapshot(duplicate.after, "accepted after");
      if (before.project.updated_at !== duplicate.post_revision || before.project_digest !== acceptedAfter.project_digest || before.resource_link_collection_digest !== acceptedAfter.resource_link_collection_digest || before.workspace_location_collection_digest !== acceptedAfter.workspace_location_collection_digest) {
        throw new Error("project quarantine retry refuses drift after the accepted receipt");
      }
      if (input.dry_run) {
        return withResponseControl({
          ok: true,
          dry_run: true,
          outcome: "duplicate_of_accepted",
          idempotency_key: idempotencyKey,
          request_digest: reqDigest,
          precondition_digest: preDigest,
          project_id: input.project_id,
          expected_revision: input.expected_revision,
          current_revision: beforeProject.updated_at,
          before,
          after: acceptedAfter,
          receipt: null,
          rollback: {
            accepted_receipt_id: duplicate.receipt_id,
            expected_current_revision: duplicate.post_revision
          }
        }, input, started, "project quarantine");
      }
      const receipt2 = duplicateOfAcceptedReceipt(duplicate, beforeProject, d, projectQuarantineSnapshotJson(before));
      return withResponseControl({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: acceptedAfter,
        receipt: receipt2,
        rollback: {
          accepted_receipt_id: duplicate.receipt_id,
          expected_current_revision: duplicate.post_revision
        }
      }, input, started, "project quarantine");
    }
    const priorAccepted = findGuardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id
    }, d);
    if (priorAccepted) {
      if (input.dry_run) {
        return withResponseControl({
          ok: false,
          dry_run: true,
          outcome: "terminal_nonacceptance",
          idempotency_key: idempotencyKey,
          request_digest: reqDigest,
          precondition_digest: preDigest,
          project_id: input.project_id,
          expected_revision: input.expected_revision,
          current_revision: beforeProject.updated_at,
          before,
          after: null,
          receipt: null,
          rollback: null
        }, input, started, "project quarantine");
      }
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "changed_request_or_precondition_for_step",
        before_snapshot: projectQuarantineSnapshotJson(before)
      }, d);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine");
    }
    const refusal = assertProjectQuarantinePreconditions(input, before);
    if (refusal) {
      if (input.dry_run) {
        return withResponseControl({
          ok: false,
          dry_run: true,
          outcome: "terminal_nonacceptance",
          idempotency_key: idempotencyKey,
          request_digest: reqDigest,
          precondition_digest: preDigest,
          project_id: input.project_id,
          expected_revision: input.expected_revision,
          current_revision: beforeProject.updated_at,
          before,
          after: null,
          receipt: null,
          rollback: null
        }, input, started, "project quarantine");
      }
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: refusal,
        before_snapshot: projectQuarantineSnapshotJson(before)
      }, d);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine");
    }
    const conflictingSlug = d.query("SELECT id FROM workspaces WHERE slug = ? AND id <> ?").get(workspaceSlugify(input.quarantine_slug), input.project_id);
    if (conflictingSlug)
      throw new Error("project quarantine slug is already owned by another project");
    const patch = projectQuarantinePatch(input, before);
    const previewProject = previewWorkspacePatch(beforeProject, patch);
    const preview = projectQuarantineSnapshot(previewProject, [], []);
    assertProjectQuarantinePostimage(input, before, preview);
    if (input.dry_run) {
      return withResponseControl({
        ok: true,
        dry_run: true,
        outcome: "planned",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: beforeProject.updated_at,
        before,
        after: preview,
        receipt: null,
        rollback: null
      }, input, started, "project quarantine");
    }
    if (timedOut(started, input.time_budget_ms))
      throw new Error("project quarantine time budget exceeded before write");
    replaceProjectResourceLinks(input.project_id, [], d);
    replaceWorkspaceLocations(input.project_id, [], d);
    const afterProject = applyProjectQuarantineWorkspacePatch(input.project_id, patch, input.expected_revision, d);
    const after = projectQuarantineSnapshot(afterProject, listProjectResourceLinks(input.project_id, input.resource_link_max_items, d), listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items, d));
    assertProjectQuarantinePostimage(input, before, after);
    const receipt = insertGuardedProjectMutationReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: afterProject.id,
      duplicate_of_receipt_id: null,
      before: projectQuarantineSnapshotJson(before),
      after: projectQuarantineSnapshotJson(after),
      post_revision: afterProject.updated_at
    }, d);
    recordWorkspaceEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: PROJECT_QUARANTINE_EVENT,
      source: input.source ?? "cli",
      command: input.command,
      before: projectQuarantineSnapshotJson(before),
      after: projectQuarantineSnapshotJson(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id
      }
    }, d);
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: beforeProject.updated_at,
      before,
      after,
      receipt,
      rollback: {
        accepted_receipt_id: receipt.receipt_id,
        expected_current_revision: afterProject.updated_at
      }
    }, input, started, "project quarantine");
  })();
}
function rollbackDuplicateProjectQuarantine(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  assertProjectResourceLinkMaxItems(input.resource_link_max_items);
  if (!Number.isInteger(input.workspace_location_max_items) || input.workspace_location_max_items <= 0) {
    throw new Error("project quarantine workspace_location_max_items must be a positive integer");
  }
  return d.transaction(() => {
    const row = d.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(input.accepted_receipt_id);
    if (!row)
      throw new Error(`accepted quarantine receipt not found: ${input.accepted_receipt_id}`);
    const accepted = rowToGuardedReceipt(row);
    if (accepted.outcome !== "accepted" || accepted.direction !== "forward" || accepted.target_id !== input.project_id) {
      throw new Error("quarantine rollback requires a forward accepted receipt for the same project id");
    }
    if (accepted.post_revision !== input.expected_current_revision) {
      throw new Error("quarantine rollback expected_current_revision must equal the accepted receipt post_revision");
    }
    const acceptedBefore = parseProjectQuarantineSnapshot(accepted.before, "accepted before");
    const acceptedAfter = parseProjectQuarantineSnapshot(accepted.after, "accepted after");
    const currentProject = getWorkspace(input.project_id, d);
    if (!currentProject)
      throw new Error(`Workspace not found: ${input.project_id}`);
    const current = projectQuarantineSnapshot(currentProject, listProjectResourceLinks(input.project_id, input.resource_link_max_items, d), listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items, d));
    const reqDigest = sha256(canonicalJson({
      route: "projects.duplicate-quarantine.rollback.v1",
      accepted_receipt_id: accepted.receipt_id,
      restore_project_digest: acceptedBefore.project_digest,
      restore_resource_link_collection_digest: acceptedBefore.resource_link_collection_digest,
      restore_workspace_location_collection_digest: acceptedBefore.workspace_location_collection_digest
    }));
    const preDigest = preconditionDigest({
      project_id: input.project_id,
      expected_revision: input.expected_current_revision
    });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest
    });
    const duplicate = findGuardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    }, d);
    if (duplicate) {
      const acceptedInverseAfter = parseProjectQuarantineSnapshot(duplicate.after, "accepted inverse after");
      if (currentProject.updated_at !== duplicate.post_revision || current.project_digest !== acceptedInverseAfter.project_digest || current.resource_link_collection_digest !== acceptedInverseAfter.resource_link_collection_digest || current.workspace_location_collection_digest !== acceptedInverseAfter.workspace_location_collection_digest) {
        throw new Error("quarantine rollback retry refuses drift after the accepted inverse");
      }
      const receipt2 = duplicateOfAcceptedReceipt(duplicate, currentProject, d, projectQuarantineSnapshotJson(current));
      return withResponseControl({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_current_revision,
        current_revision: currentProject.updated_at,
        before: current,
        after: acceptedInverseAfter,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine rollback");
    }
    const priorInverse = findGuardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      target_id: input.project_id
    }, d);
    if (priorInverse) {
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "inverse",
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_current_revision,
        reason: "changed_request_or_precondition_for_step",
        before_snapshot: projectQuarantineSnapshotJson(current)
      }, d);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_current_revision,
        current_revision: currentProject.updated_at,
        before: current,
        after: null,
        receipt: receipt2,
        rollback: null
      }, input, started, "project quarantine rollback");
    }
    if (currentProject.updated_at !== input.expected_current_revision || current.project_digest !== acceptedAfter.project_digest || current.resource_link_collection_digest !== acceptedAfter.resource_link_collection_digest || current.workspace_location_collection_digest !== acceptedAfter.workspace_location_collection_digest) {
      throw new Error("quarantine rollback refuses current project, resource-link, or path-selector drift");
    }
    replaceProjectResourceLinks(input.project_id, acceptedBefore.resource_links, d);
    replaceWorkspaceLocations(input.project_id, acceptedBefore.workspace_locations, d);
    const afterProject = applyProjectQuarantineWorkspacePatch(input.project_id, restoreProjectPatch(acceptedBefore), input.expected_current_revision, d);
    const after = projectQuarantineSnapshot(afterProject, listProjectResourceLinks(input.project_id, input.resource_link_max_items, d), listWorkspaceLocationsBounded(input.project_id, input.workspace_location_max_items, d));
    const restoredProject = { ...after.project, updated_at: acceptedBefore.project.updated_at };
    if (projectDigest(restoredProject, after.workspace_locations) !== acceptedBefore.project_digest || after.resource_link_collection_digest !== acceptedBefore.resource_link_collection_digest || after.workspace_location_collection_digest !== acceptedBefore.workspace_location_collection_digest) {
      throw new Error("quarantine rollback exact inverse readback mismatch");
    }
    const receipt = insertGuardedProjectMutationReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "inverse",
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "inverse",
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_current_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: afterProject.id,
      duplicate_of_receipt_id: null,
      before: projectQuarantineSnapshotJson(current),
      after: projectQuarantineSnapshotJson(after),
      post_revision: afterProject.updated_at
    }, d);
    recordWorkspaceEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: PROJECT_QUARANTINE_ROLLBACK_EVENT,
      source: input.source ?? "cli",
      command: input.command,
      before: projectQuarantineSnapshotJson(current),
      after: projectQuarantineSnapshotJson(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        accepted_receipt_id: accepted.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id
      }
    }, d);
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_current_revision,
      current_revision: currentProject.updated_at,
      before: current,
      after,
      receipt,
      rollback: null
    }, input, started, "project quarantine rollback");
  })();
}
function getProjectResourceLinkMigrationManifest(projectId, manifestId, db) {
  const row = db.query(`SELECT * FROM project_resource_link_migration_manifests
     WHERE manifest_id = ? AND project_id = ?`).get(manifestId, projectId);
  if (!row)
    throw new Error(`project resource link migration manifest not found: ${manifestId}`);
  return rowToProjectResourceLinkMigrationManifest(row);
}
function listProjectResourceLinkMigrationEvents(manifestId, db) {
  return readBoundedProjectResourceLinkMigrationEvents(manifestId, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, db).events;
}
function readBoundedProjectResourceLinkMigrationEvents(manifestId, maxItems, db) {
  if (!Number.isInteger(maxItems) || maxItems <= 0) {
    throw new Error("project resource link migration event max_items must be a positive integer");
  }
  const rows = db.query(`SELECT event_id, manifest_id, transition_version, from_state, to_state,
            request_digest, precondition_digest, evidence_json, created_at
     FROM project_resource_link_migration_events
     WHERE manifest_id = ?
     ORDER BY transition_version ASC
     LIMIT ?`).all(manifestId, maxItems + 1);
  const truncated = rows.length > maxItems;
  return {
    events: rows.slice(0, maxItems).map((row) => ({
      event_id: String(row["event_id"]),
      manifest_id: String(row["manifest_id"]),
      transition_version: Number(row["transition_version"]),
      from_state: row["from_state"] === null ? null : row["from_state"],
      to_state: row["to_state"],
      request_digest: String(row["request_digest"]),
      precondition_digest: String(row["precondition_digest"]),
      evidence: JSON.parse(String(row["evidence_json"])),
      created_at: String(row["created_at"])
    })),
    complete: !truncated,
    truncated
  };
}
function insertProjectResourceLinkMigrationEvent(event, db) {
  db.run(`INSERT INTO project_resource_link_migration_events (
      event_id, manifest_id, transition_version, from_state, to_state,
      request_digest, precondition_digest, evidence_json, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    event.event_id,
    event.manifest_id,
    event.transition_version,
    event.from_state,
    event.to_state,
    event.request_digest,
    event.precondition_digest,
    canonicalJson(event.evidence),
    event.created_at
  ]);
}
function persistProjectResourceLinkMigrationTransition(before, after, evidence, db) {
  const update = db.run(`UPDATE project_resource_link_migration_manifests
     SET state = ?, links_json = ?, projects_forward_receipt_id = ?,
         projects_inverse_receipt_id = ?, projects_reference_proof_json = ?,
         last_verified_projects_revision = ?, last_verified_projects_digest = ?,
         transition_version = ?, updated_at = ?
     WHERE manifest_id = ? AND project_id = ? AND transition_version = ?`, [
    after.state,
    canonicalJson(after.links),
    after.projects_forward_receipt_id,
    after.projects_inverse_receipt_id,
    after.projects_reference_proof === null ? null : canonicalJson(after.projects_reference_proof),
    after.last_verified_projects_revision,
    after.last_verified_projects_digest,
    after.transition_version,
    after.updated_at,
    after.manifest_id,
    after.project_id,
    before.transition_version
  ]);
  if (update.changes !== 1)
    throw new Error("project resource link migration transition CAS lost");
  insertProjectResourceLinkMigrationEvent(migrationEvent(after.manifest_id, after.transition_version, before.state, after.state, sha256(canonicalJson(evidence)), sha256(canonicalJson({
    manifest_id: before.manifest_id,
    transition_version: before.transition_version,
    state: before.state
  })), evidence, after.updated_at), db);
}
function planProjectResourceLinkMigration(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  const project = getWorkspace(input.project_id, d);
  if (!project)
    throw new Error(`Workspace not found: ${input.project_id}`);
  if (workspaceRevision(project) !== input.expected_project_revision) {
    throw new Error("project resource link migration plan refuses a stale project revision");
  }
  const maxItems = input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS;
  if (input.links.length > maxItems)
    throw new Error("project resource link migration plan exceeds max_items");
  const ts = now();
  const candidate = buildProjectResourceLinkMigrationPlan(input, ts);
  const existingRow = d.query(`SELECT * FROM project_resource_link_migration_manifests
     WHERE project_id = ? AND operation_id = ? AND step_id = ?`).get(input.project_id, input.operation_id, input.step_id);
  if (existingRow) {
    const existing = rowToProjectResourceLinkMigrationManifest(existingRow);
    if (existing.manifest_id !== candidate.manifest_id) {
      throw new Error("project resource link migration step already has a different accepted manifest");
    }
    return withResponseControl({
      ok: true,
      outcome: "duplicate_of_accepted",
      manifest: existing,
      events: listProjectResourceLinkMigrationEvents(existing.manifest_id, d)
    }, input, started, "project resource link migration plan");
  }
  d.transaction(() => {
    d.run(`INSERT INTO project_resource_link_migration_manifests (
        manifest_id, project_id, operation_id, step_id, state,
        expected_project_revision, desired_collection_digest, links_json,
        projects_forward_receipt_id, projects_inverse_receipt_id,
        projects_reference_proof_json, last_verified_projects_revision,
        last_verified_projects_digest, transition_version, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)`, [
      candidate.manifest_id,
      candidate.project_id,
      candidate.operation_id,
      candidate.step_id,
      candidate.state,
      candidate.expected_project_revision,
      candidate.desired_collection_digest,
      canonicalJson(candidate.links),
      candidate.transition_version,
      candidate.created_at,
      candidate.updated_at
    ]);
    insertProjectResourceLinkMigrationEvent(migrationEvent(candidate.manifest_id, candidate.transition_version, null, "planned", sha256(canonicalJson(input.links)), sha256(canonicalJson({
      project_id: input.project_id,
      expected_project_revision: input.expected_project_revision
    })), { link_ids: candidate.links.map((item) => item.link_id) }, ts), d);
  })();
  return withResponseControl({
    ok: true,
    outcome: "accepted",
    manifest: candidate,
    events: listProjectResourceLinkMigrationEvents(candidate.manifest_id, d)
  }, input, started, "project resource link migration plan");
}
function readProjectResourceLinkMigration(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  const manifest = getProjectResourceLinkMigrationManifest(input.project_id, input.manifest_id, d);
  const boundedEvents = readBoundedProjectResourceLinkMigrationEvents(manifest.manifest_id, input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, d);
  return withResponseControl({
    ok: true,
    outcome: "accepted",
    manifest,
    events: boundedEvents.events
  }, input, started, "project resource link migration read", boundedEvents);
}
function advanceProjectResourceLinkMigration(input, db, producerEvidenceVerifier) {
  const d = db || getDatabase();
  const started = Date.now();
  const before = getProjectResourceLinkMigrationManifest(input.project_id, input.manifest_id, d);
  if (before.transition_version !== input.expected_transition_version) {
    throw new Error("project resource link migration advance transition_version is stale");
  }
  if (before.state === input.next_state) {
    return withResponseControl({
      ok: true,
      outcome: "duplicate_of_accepted",
      manifest: before,
      events: listProjectResourceLinkMigrationEvents(before.manifest_id, d)
    }, input, started, "project resource link migration advance");
  }
  let producerEvidence = input.producer_evidence;
  let producerAttestation;
  if (input.next_state === "producer_applied") {
    producerEvidence = reconcileProjectResourceLinkProducerProof(before, input.producer_evidence, "forward");
  }
  if (input.next_state === "projects_applied") {
    if (!input.projects_forward_receipt_id)
      throw new Error("projects_applied requires a Projects forward receipt");
    const row = d.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(input.projects_forward_receipt_id);
    if (!row)
      throw new Error("Projects forward receipt not found");
    const receipt = rowToGuardedReceipt(row);
    const snapshot = parseResourceLinkSnapshot(receipt.after, "Projects forward");
    const snapshotIds = new Set(snapshot.links.map((link) => link.id));
    if (receipt.outcome !== "accepted" || receipt.direction !== "forward" || receipt.target_id !== input.project_id || snapshot.collection_digest !== before.desired_collection_digest || before.links.some((item) => !snapshotIds.has(item.link_id))) {
      throw new Error("Projects forward receipt does not prove the manifest collection");
    }
  }
  if (input.next_state === "verified") {
    producerEvidence = reconcileProjectResourceLinkProducerProof(before, input.producer_evidence, "readback");
    const trustedProject = getWorkspace(input.project_id, d);
    if (!trustedProject)
      throw new Error(`Project not found: ${input.project_id}`);
    producerAttestation = assertProjectResourceLinkProducerAttestation(before, "readback", producerEvidence, producerEvidenceVerifier?.({
      manifest: before,
      trusted_project: projectResourceLinkProducerProjectSubject(trustedProject),
      phase: "readback",
      producer_evidence: producerEvidence,
      transition_evidence: input.evidence,
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms
    }));
    const read = readProjectResourceLinks({
      project_id: input.project_id,
      max_items: Math.max(PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, before.links.length),
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms
    }, d);
    if (read.collection_digest !== before.desired_collection_digest || input.last_verified_projects_revision !== read.current_revision || input.last_verified_projects_digest !== read.collection_digest) {
      throw new Error("verified transition requires a current complete Projects readback");
    }
  }
  const after = applyProjectResourceLinkMigrationTransition(before, input.next_state, now(), {
    producer_evidence: producerEvidence,
    projects_forward_receipt_id: input.projects_forward_receipt_id,
    last_verified_projects_revision: input.last_verified_projects_revision,
    last_verified_projects_digest: input.last_verified_projects_digest
  });
  const transitionEvidence = producerAttestation ? migrationEvidenceWithProducerAttestation(input.evidence, producerAttestation) : input.evidence;
  d.transaction(() => persistProjectResourceLinkMigrationTransition(before, after, transitionEvidence, d))();
  return withResponseControl({
    ok: true,
    outcome: "accepted",
    manifest: after,
    events: listProjectResourceLinkMigrationEvents(after.manifest_id, d)
  }, input, started, "project resource link migration advance");
}
function rollbackProjectResourceLinkMigration(input, db, producerEvidenceVerifier) {
  const d = db || getDatabase();
  const started = Date.now();
  let before = getProjectResourceLinkMigrationManifest(input.project_id, input.manifest_id, d);
  if (["rolled_back", "retained_target"].includes(before.state)) {
    return withResponseControl({
      ok: true,
      outcome: "duplicate_of_accepted",
      manifest: before,
      events: listProjectResourceLinkMigrationEvents(before.manifest_id, d)
    }, input, started, "project resource link migration rollback");
  }
  if (before.transition_version !== input.expected_transition_version) {
    throw new Error("project resource link migration rollback transition_version is stale");
  }
  let proof = before.projects_reference_proof;
  let inverseReceiptId = before.projects_inverse_receipt_id;
  const establishingProjectsReferenceProof = proof === null;
  if (establishingProjectsReferenceProof && input.producer_outcome !== "pending") {
    throw new Error("first migration rollback call must use producer_outcome=pending so Projects reference proof is persisted before producer compensation");
  }
  if (!proof) {
    const linkIds = before.links.map((item) => item.link_id);
    if (before.projects_forward_receipt_id) {
      const forwardReceipt = requireForwardProjectResourceLinkReceipt(before.projects_forward_receipt_id, input.project_id, d);
      const inverse = rollbackProjectResourceLinks({
        project_id: input.project_id,
        operation_id: `${before.operation_id}:migration-rollback`,
        step_id: `${before.step_id}:projects-reference`,
        accepted_receipt_id: before.projects_forward_receipt_id,
        expected_current_revision: forwardReceipt.post_revision,
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms,
        agent_id: input.agent_id,
        source: input.source,
        command: input.command
      }, d);
      const verified = readProjectResourceLinks({
        project_id: input.project_id,
        max_items: input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      }, d);
      if (verified.links.some((link) => linkIds.includes(link.id))) {
        throw new Error("Projects inverse did not remove every manifest reference");
      }
      if (!["accepted", "duplicate_of_accepted"].includes(inverse.outcome)) {
        throw new Error("Projects inverse was not accepted");
      }
      inverseReceiptId = inverse.receipt?.duplicate_of_receipt_id ?? inverse.receipt?.receipt_id ?? null;
      if (!inverseReceiptId)
        throw new Error("Projects inverse did not return an accepted receipt");
      proof = {
        kind: "accepted_inverse",
        forward_receipt_id: before.projects_forward_receipt_id,
        inverse_receipt_id: inverseReceiptId,
        verified_revision: verified.current_revision,
        collection_digest: verified.collection_digest,
        link_ids_checked: linkIds,
        complete: true,
        truncated: false,
        request_digest: inverse.request_digest,
        precondition_digest: inverse.precondition_digest
      };
    } else {
      const current = readProjectResourceLinks({
        project_id: input.project_id,
        max_items: input.max_items ?? PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      }, d);
      if (current.links.some((link) => linkIds.includes(link.id))) {
        throw new Error("ambiguous Projects state: manifest links exist without a matching accepted forward receipt");
      }
      proof = {
        kind: "no_projects_write",
        verified_revision: current.current_revision,
        collection_digest: current.collection_digest,
        link_ids_checked: linkIds,
        complete: true,
        truncated: false,
        request_digest: sha256(canonicalJson({ manifest_id: before.manifest_id, link_ids: linkIds })),
        precondition_digest: sha256(canonicalJson({
          revision: current.current_revision,
          collection_digest: current.collection_digest
        }))
      };
    }
  }
  if (before.state !== "rollback_in_progress") {
    const inProgress = applyProjectResourceLinkMigrationTransition(before, "rollback_in_progress", now(), {
      projects_inverse_receipt_id: inverseReceiptId,
      projects_reference_proof: proof,
      last_verified_projects_revision: proof.verified_revision,
      last_verified_projects_digest: proof.collection_digest
    });
    d.transaction(() => persistProjectResourceLinkMigrationTransition(before, inProgress, input.evidence, d))();
    before = inProgress;
  }
  if (input.producer_outcome === "pending") {
    return withResponseControl({
      ok: true,
      outcome: "accepted",
      manifest: before,
      events: listProjectResourceLinkMigrationEvents(before.manifest_id, d)
    }, input, started, "project resource link migration rollback");
  }
  const nextState = input.producer_outcome === "complete" ? "rolled_back" : input.producer_outcome === "retained_target" ? "retained_target" : "failed_reconcilable";
  const terminalProducerEvidence = nextState === "rolled_back" || nextState === "retained_target" ? reconcileProjectResourceLinkProducerProof(before, input.producer_evidence, "inverse", nextState === "rolled_back" ? "complete" : "retained_target") : undefined;
  const producerAttestation = terminalProducerEvidence ? (() => {
    const trustedProject = getWorkspace(input.project_id, d);
    if (!trustedProject)
      throw new Error(`Project not found: ${input.project_id}`);
    const phase = nextState === "rolled_back" ? "inverse_complete" : "inverse_retained_target";
    return assertProjectResourceLinkProducerAttestation(before, phase, terminalProducerEvidence, producerEvidenceVerifier?.({
      manifest: before,
      trusted_project: projectResourceLinkProducerProjectSubject(trustedProject),
      phase,
      producer_evidence: terminalProducerEvidence,
      transition_evidence: input.evidence,
      response_byte_limit: input.response_byte_limit,
      time_budget_ms: input.time_budget_ms
    }));
  })() : undefined;
  const after = applyProjectResourceLinkMigrationTransition(before, nextState, now(), {
    producer_evidence: terminalProducerEvidence,
    projects_inverse_receipt_id: inverseReceiptId,
    projects_reference_proof: proof,
    last_verified_projects_revision: proof.verified_revision,
    last_verified_projects_digest: proof.collection_digest
  });
  const transitionEvidence = producerAttestation ? migrationEvidenceWithProducerAttestation(input.evidence, producerAttestation) : input.evidence;
  d.transaction(() => persistProjectResourceLinkMigrationTransition(before, after, transitionEvidence, d))();
  before = after;
  return withResponseControl({
    ok: true,
    outcome: "accepted",
    manifest: before,
    events: listProjectResourceLinkMigrationEvents(before.manifest_id, d)
  }, input, started, "project resource link migration rollback");
}
function previewWorkspacePatch(before, patch) {
  return {
    ...before,
    ...patch.name !== undefined ? { name: patch.name } : {},
    ...patch.slug !== undefined ? { slug: workspaceSlugify(patch.slug) } : {},
    ...patch.description !== undefined ? { description: patch.description } : {},
    ...patch.kind !== undefined ? { kind: patch.kind } : {},
    ...patch.status !== undefined ? { status: patch.status } : {},
    ...patch.root_id !== undefined ? { root_id: patch.root_id } : {},
    ...patch.recipe_id !== undefined ? { recipe_id: patch.recipe_id } : {},
    ...patch.canonical_machine !== undefined ? { canonical_machine: patch.canonical_machine } : {},
    ...patch.primary_path !== undefined ? { primary_path: patch.primary_path } : {},
    ...patch.git_remote !== undefined ? { git_remote: patch.git_remote } : {},
    ...patch.s3_bucket !== undefined ? { s3_bucket: patch.s3_bucket } : {},
    ...patch.s3_prefix !== undefined ? { s3_prefix: patch.s3_prefix } : {},
    ...patch.tags !== undefined ? { tags: patch.tags } : {},
    ...patch.integrations !== undefined ? { integrations: patch.integrations } : {},
    ...patch.metadata !== undefined ? { metadata: normalizeProjectMetadata(patch.metadata, before.metadata) } : {},
    ...patch.last_opened_at !== undefined ? { last_opened_at: patch.last_opened_at } : {}
  };
}
function guardedUpdateWorkspace(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  const direction = input.direction ?? "forward";
  const reqDigest = requestDigest(input.patch);
  const preDigest = preconditionDigest({ project_id: input.project_id, expected_revision: input.expected_revision });
  const idempotencyKey = deriveGuardedIdempotencyKey({
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction,
    target_id: input.project_id,
    request_digest: reqDigest,
    precondition_digest: preDigest
  });
  return d.transaction(() => {
    const before = getWorkspace(input.project_id, d);
    if (!before)
      throw new Error(`Workspace not found: ${input.project_id}`);
    if (input.patch.integrations !== undefined) {
      assertProjectResourceLinkIntegrationMutation(before.integrations, input.patch.integrations, listProjectResourceLinks(input.project_id, PROJECT_RESOURCE_LINK_DEFAULT_MAX_ITEMS, d));
    }
    const currentRevision = workspaceRevision(before);
    const duplicate = findGuardedAcceptedReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    }, d);
    if (duplicate) {
      const duplicateReceipt = duplicateOfAcceptedReceipt(duplicate, before, d);
      const result = {
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: duplicate.after,
        receipt: duplicateReceipt
      };
      return withResponseControl(result, input, started);
    }
    const priorAccepted = findGuardedAcceptedByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      target_id: input.project_id
    }, d);
    if (priorAccepted) {
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "changed_request_or_precondition_for_step",
        before
      }, d);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: null,
        receipt: receipt2
      }, input, started);
    }
    if (currentRevision !== input.expected_revision) {
      const receipt2 = terminalNonacceptanceReceipt({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason: "stale_revision",
        before
      }, d);
      return withResponseControl({
        ok: false,
        dry_run: false,
        outcome: "terminal_nonacceptance",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: null,
        receipt: receipt2
      }, input, started);
    }
    if (input.dry_run) {
      return withResponseControl({
        ok: true,
        dry_run: true,
        outcome: "planned",
        idempotency_key: idempotencyKey,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        project_id: input.project_id,
        expected_revision: input.expected_revision,
        current_revision: currentRevision,
        before,
        after: previewWorkspacePatch(before, input.patch),
        receipt: null
      }, input, started);
    }
    if (timedOut(started, input.time_budget_ms))
      throw new Error("guarded mutation time budget exceeded before write");
    const after = updateWorkspace(input.project_id, {
      ...input.patch,
      agent_id: input.agent_id ?? input.patch.agent_id,
      source: input.source ?? input.patch.source ?? "cli",
      command: input.command ?? input.patch.command
    }, d);
    const receipt = insertGuardedProjectMutationReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction,
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction,
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: after.id,
      duplicate_of_receipt_id: null,
      before: workspaceSnapshot(before),
      after: workspaceSnapshot(after),
      post_revision: workspaceRevision(after)
    }, d);
    recordWorkspaceEvent({
      workspace_id: after.id,
      agent_id: input.agent_id,
      event_type: "guarded_metadata_mutation",
      source: input.source ?? "cli",
      command: input.command,
      before,
      after,
      metadata: { receipt_id: receipt.receipt_id, operation_id: input.operation_id, step_id: input.step_id, idempotency_key: idempotencyKey }
    }, d);
    return withResponseControl({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: currentRevision,
      before,
      after,
      receipt
    }, input, started);
  })();
}
function lookupGuardedWorkspaceMutationReceipt(input, db) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(input.project_id);
  if (input.max_items !== 1)
    throw new Error("guarded receipt lookup max_items must be exactly 1");
  const rows = d.query(`SELECT * FROM guarded_project_mutation_receipts
     WHERE operation_id = ? AND step_id = ? AND direction = ? AND idempotency_key = ? AND target_id = ?
     ORDER BY created_at ASC, receipt_id ASC
     LIMIT 2`).all(input.operation_id, input.step_id, input.direction, input.idempotency_key, input.project_id);
  if (rows.length === 0)
    throw new Error("guarded receipt lookup expected exactly one terminal receipt, found 0");
  const receipts = rows.map(rowToGuardedReceipt);
  const accepted = receipts.find((receipt2) => receipt2.outcome === "accepted");
  const duplicates = receipts.filter((receipt2) => receipt2.outcome === "duplicate_of_accepted");
  if (receipts.length > 1) {
    if (!accepted || duplicates.length !== receipts.length - 1 || duplicates.some((receipt2) => receipt2.duplicate_of_receipt_id !== accepted.receipt_id)) {
      throw new Error(`guarded receipt lookup expected exactly one terminal result, found ${receipts.length}`);
    }
  }
  const receipt = duplicates.at(-1) ?? accepted ?? receipts[0];
  if (!["accepted", "duplicate_of_accepted", "terminal_nonacceptance"].includes(receipt.outcome)) {
    throw new Error(`guarded receipt lookup found nonterminal outcome: ${receipt.outcome}`);
  }
  return receipt;
}
function restorePatchFromReceipt(receipt) {
  const before = receipt.before;
  if (!before)
    throw new Error("accepted receipt has no before snapshot");
  return {
    name: before.name,
    slug: before.slug,
    description: before.description,
    kind: before.kind,
    status: before.status,
    root_id: before.root_id,
    recipe_id: before.recipe_id,
    canonical_machine: before.canonical_machine,
    primary_path: before.primary_path,
    git_remote: before.git_remote,
    s3_bucket: before.s3_bucket,
    s3_prefix: before.s3_prefix,
    tags: before.tags,
    integrations: before.integrations,
    metadata: before.metadata,
    last_opened_at: before.last_opened_at
  };
}
function rollbackGuardedWorkspaceMutation(input, db) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(input.project_id);
  const acceptedRow = d.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(input.accepted_receipt_id);
  if (!acceptedRow)
    throw new Error(`accepted receipt not found: ${input.accepted_receipt_id}`);
  const accepted = rowToGuardedReceipt(acceptedRow);
  if (accepted.outcome !== "accepted" || accepted.direction !== "forward" || accepted.target_id !== input.project_id) {
    throw new Error("rollback requires a forward accepted receipt for the same project id");
  }
  if (accepted.post_revision !== input.expected_current_revision) {
    throw new Error("rollback expected_current_revision must equal the accepted receipt post_revision");
  }
  const patch = restorePatchFromReceipt(accepted);
  const reqDigest = requestDigest(patch);
  const preDigest = preconditionDigest({ project_id: input.project_id, expected_revision: input.expected_current_revision });
  const idempotencyKey = deriveGuardedIdempotencyKey({
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: "inverse",
    target_id: input.project_id,
    request_digest: reqDigest,
    precondition_digest: preDigest
  });
  const result = guardedUpdateWorkspace({
    project_id: input.project_id,
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: "inverse",
    expected_revision: input.expected_current_revision,
    patch,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms,
    agent_id: input.agent_id,
    source: input.source ?? "cli",
    command: input.command
  }, d);
  if (result.receipt?.outcome === "accepted") {
    recordWorkspaceEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: "guarded_metadata_mutation_rollback",
      source: input.source ?? "cli",
      command: input.command,
      metadata: {
        receipt_id: result.receipt.receipt_id,
        accepted_receipt_id: accepted.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id
      }
    }, d);
  }
  return result;
}
function archiveWorkspace(id, input = {}, db) {
  return updateWorkspace(id, { ...input, status: "archived" }, db);
}
function unarchiveWorkspace(id, input = {}, db) {
  return updateWorkspace(id, { ...input, status: "active" }, db);
}
function deleteWorkspace(id, input = {}, db) {
  const d = db || getDatabase();
  const before = getWorkspace(id, d);
  if (!before)
    throw new Error(`Workspace not found: ${id}`);
  const { hard, recordEvent, ...updateInput } = input;
  if (!hard) {
    const workspace = updateWorkspace(id, { ...updateInput, status: "deleted" }, d);
    return { workspace, hard: false };
  }
  if (recordEvent !== false) {
    recordWorkspaceEvent({
      workspace_id: id,
      agent_id: updateInput.agent_id,
      event_type: "deleted",
      source: updateInput.source ?? "cli",
      prompt: updateInput.prompt,
      command: updateInput.command,
      before,
      metadata: { hard: true }
    }, d);
  }
  d.run("DELETE FROM workspaces WHERE id = ?", [id]);
  return { workspace: before, hard: true };
}
function addWorkspaceLocation(input, db) {
  const d = db || getDatabase();
  const workspace = getWorkspace(input.workspace_id, d);
  if (!workspace)
    throw new Error(`Workspace not found: ${input.workspace_id}`);
  if (input.is_primary) {
    d.run("UPDATE workspace_locations SET is_primary = 0 WHERE workspace_id = ?", [input.workspace_id]);
  }
  const id = generateLocationId();
  const path = resolve4(input.path);
  const localMachine = machineId();
  const machine = input.machine_id === undefined ? localMachine : input.machine_id.trim();
  if (!machine)
    throw new Error("Location machine must not be empty");
  const ts = now();
  d.run(`INSERT INTO workspace_locations (
      id, workspace_id, path, machine_id, label, kind, is_primary, exists_at_create, metadata, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ON CONFLICT(workspace_id, path, machine_id) DO UPDATE SET
      label = excluded.label,
      kind = excluded.kind,
      is_primary = excluded.is_primary,
      metadata = excluded.metadata`, [
    id,
    input.workspace_id,
    path,
    machine,
    input.label ?? "main",
    input.kind ?? "local",
    input.is_primary ? 1 : 0,
    machine === localMachine && existsSync5(path) ? 1 : 0,
    json(input.metadata ?? {}),
    ts
  ]);
  if (input.is_primary) {
    d.run("UPDATE workspaces SET primary_path = ?, updated_at = ? WHERE id = ?", [
      path,
      nextWorkspaceRevision(workspace.updated_at),
      input.workspace_id
    ]);
  }
  const row = d.query("SELECT * FROM workspace_locations WHERE workspace_id = ? AND path = ? AND machine_id = ?").get(input.workspace_id, path, machine);
  if (!row)
    throw new Error(`Workspace location was not written: ${path}`);
  const location = rowToLocation(row);
  if (input.source || input.agent_id || input.prompt || input.command) {
    recordWorkspaceEvent({
      workspace_id: input.workspace_id,
      agent_id: input.agent_id,
      event_type: "location_added",
      source: input.source ?? "system",
      prompt: input.prompt,
      command: input.command,
      after: location,
      metadata: { primary: location.is_primary }
    }, d);
  }
  return location;
}
function listWorkspaceLocations(workspaceId, db) {
  const d = db || getDatabase();
  const rows = d.query("SELECT * FROM workspace_locations WHERE workspace_id = ? ORDER BY is_primary DESC, created_at ASC").all(workspaceId);
  return rows.map(rowToLocation);
}
function assignAgentToWorkspace(workspaceId, agentId, role = "contributor", assignedBy, metadata, db) {
  const d = db || getDatabase();
  if (!getWorkspace(workspaceId, d))
    throw new Error(`Workspace not found: ${workspaceId}`);
  if (!getAgent(agentId, d))
    throw new Error(`Agent not found: ${agentId}`);
  d.run(`INSERT INTO workspace_agents (id, workspace_id, agent_id, role, assigned_by, metadata, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)
     ON CONFLICT(workspace_id, agent_id, role) DO NOTHING`, [uuid(), workspaceId, agentId, role, assignedBy ?? null, json(metadata ?? {}), now()]);
  const row = d.query("SELECT * FROM workspace_agents WHERE workspace_id = ? AND agent_id = ? AND role = ?").get(workspaceId, agentId, role);
  if (!row)
    throw new Error(`Workspace agent assignment was not written: ${workspaceId}/${agentId}/${role}`);
  return rowToWorkspaceAgentAssignment(row, d);
}
function listWorkspaceAgents(workspaceId, db) {
  const d = db || getDatabase();
  const rows = d.query("SELECT * FROM workspace_agents WHERE workspace_id = ? ORDER BY role ASC, created_at ASC").all(workspaceId);
  return rows.map((row) => rowToWorkspaceAgentAssignment(row, d));
}
function recordWorkspaceEvent(input, db) {
  const d = db || getDatabase();
  const id = generateWorkspaceEventId();
  d.run(`INSERT INTO workspace_events (
      id, workspace_id, agent_id, event_type, source, prompt, command,
      before_json, after_json, metadata, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    input.workspace_id ?? null,
    input.agent_id ?? null,
    input.event_type,
    input.source,
    input.prompt ? redactProjectText(input.prompt) : null,
    input.command ? redactProjectText(input.command) : null,
    input.before === undefined ? null : json(redactProjectValue(input.before)),
    input.after === undefined ? null : json(redactProjectValue(input.after)),
    json(redactProjectValue(input.metadata ?? {})),
    now()
  ]);
  const row = d.query("SELECT * FROM workspace_events WHERE id = ?").get(id);
  return rowToEvent(row);
}
function listWorkspaceEvents(workspaceId, db) {
  const d = db || getDatabase();
  return d.query("SELECT * FROM workspace_events WHERE workspace_id = ? ORDER BY created_at ASC").all(workspaceId).map(rowToEvent);
}
function listAgentRuns(filter = {}, db) {
  const d = db || getDatabase();
  const conditions = [];
  const params = [];
  if (filter.workspace_id) {
    conditions.push("workspace_id = ?");
    params.push(filter.workspace_id);
  }
  if (filter.agent_id) {
    conditions.push("agent_id = ?");
    params.push(filter.agent_id);
  }
  if (filter.status) {
    conditions.push("status = ?");
    params.push(filter.status);
  }
  const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
  return d.query(`SELECT * FROM agent_runs ${where} ORDER BY started_at DESC LIMIT ?`).all(...params, filter.limit ?? 100).map(rowToAgentRun);
}
function clearExpiredLocks(db) {
  db.run("DELETE FROM workspace_locks WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')");
}
function acquireWorkspaceLock(input, db) {
  const d = db || getDatabase();
  clearExpiredLocks(d);
  const existing = d.query("SELECT * FROM workspace_locks WHERE lock_key = ?").get(input.lock_key);
  if (existing) {
    throw new Error(`Workspace lock already held: ${input.lock_key}`);
  }
  const id = generateWorkspaceLockId();
  const expiresAt = input.ttl_seconds ? new Date(Date.now() + input.ttl_seconds * 1000).toISOString().replace("T", " ").replace("Z", "") : null;
  d.run(`INSERT INTO workspace_locks (id, lock_key, workspace_id, agent_id, reason, created_at, expires_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)`, [id, input.lock_key, input.workspace_id ?? null, input.agent_id ?? null, input.reason ?? null, now(), expiresAt]);
  const row = d.query("SELECT * FROM workspace_locks WHERE id = ?").get(id);
  return rowToWorkspaceLock(row);
}
function releaseWorkspaceLock(lockKey, lockId, db) {
  const d = db || getDatabase();
  const result = d.run("DELETE FROM workspace_locks WHERE lock_key = ? AND id = ?", [lockKey, lockId]);
  return result.changes > 0;
}
function forceReleaseWorkspaceLock(lockKey, db) {
  const d = db || getDatabase();
  const result = d.run("DELETE FROM workspace_locks WHERE lock_key = ?", [lockKey]);
  return result.changes > 0;
}
function listWorkspaceLocks(db) {
  const d = db || getDatabase();
  clearExpiredLocks(d);
  return d.query("SELECT * FROM workspace_locks ORDER BY created_at ASC").all().map(rowToWorkspaceLock);
}
var nanoid;
var init_workspaces = __esm(() => {
  init_database();
  init_project_store_paths();
  init_project_management();
  init_redaction();
  init_guarded_project_mutation();
  init_project_channel_guard();
  init_project_resource_links();
  init_project_resource_link_migrations();
  init_project_quarantine();
  nanoid = customAlphabet(`0123456789${"abcdefghijklmnopqrstuvwxyz"}`, 12);
});

// src/lib/local-opt-in.ts
import {
  clientTransportEnvKeys,
  credentialOverrideEnvKey,
  credentialPointerEnvKey,
  CREDENTIAL_PROFILE_ENV_KEY
} from "@hasna/contracts/client";
function isProjectsLocalOptIn(env2 = process.env) {
  return PROJECTS_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env2[key] ?? "").trim() !== "");
}
function projectsAuthorityEnvKeys() {
  const keys = clientTransportEnvKeys("projects");
  return [
    ...keys.apiUrlKeys,
    ...keys.apiKeyKeys,
    credentialOverrideEnvKey("projects"),
    credentialPointerEnvKey("projects"),
    CREDENTIAL_PROFILE_ENV_KEY
  ];
}
function hasProjectsEnvAuthorityIntent(env2 = process.env) {
  return projectsAuthorityEnvKeys().some((key) => (env2[key] ?? "").trim() !== "");
}
function selectsProjectsLocalStore(env2 = process.env) {
  return !hasProjectsEnvAuthorityIntent(env2) && isProjectsLocalOptIn(env2);
}
var PROJECTS_LOCAL_OPT_IN_ENV_KEYS;
var init_local_opt_in = __esm(() => {
  PROJECTS_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_PROJECTS_LOCAL", "PROJECTS_LOCAL"];
});

// src/store/paginate.ts
async function collectPages(fetchPage, identify, options = {}) {
  const want = options.want;
  if (want !== undefined && want <= 0)
    return [];
  const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
  const requestSize = options.pageSize ?? DEFAULT_PAGE_REQUEST;
  let offset = options.offset ?? 0;
  const collected = [];
  const seen = new Set;
  let stride = null;
  for (let page = 0;page < maxPages; page++) {
    const remaining = want === undefined ? undefined : want - collected.length;
    if (remaining !== undefined && remaining <= 0)
      break;
    const ask = remaining === undefined ? stride ?? requestSize : Math.min(remaining, stride ?? requestSize);
    const rows = await fetchPage({ limit: ask, offset });
    if (rows.length === 0)
      break;
    let fresh = 0;
    for (const row of rows) {
      const id = identify(row);
      if (id !== undefined) {
        if (seen.has(id)) {
          throw new PaginationError(`Projects list pagination returned duplicate row "${id}" at offset ${offset}; refusing to deduplicate a possibly missing page.`);
        }
        seen.add(id);
      }
      collected.push(row);
      fresh++;
      if (want !== undefined && collected.length >= want)
        break;
    }
    if (fresh === 0) {
      throw new PaginationError(`Projects list pagination stalled at offset ${offset}: the server returned ${rows.length} row(s) that were all already seen, which means it is ignoring the offset parameter. Refusing to return a silently truncated list.`);
    }
    if (want !== undefined && collected.length >= want)
      break;
    if (stride === null)
      stride = rows.length;
    if (rows.length < (stride ?? rows.length))
      break;
    offset += rows.length;
  }
  return collected;
}
async function collectCompletePages(fetchPage, identify, options = {}) {
  const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
  const requestSize = options.pageSize ?? DEFAULT_PAGE_REQUEST;
  const collected = [];
  const seen = new Set;
  let offset = 0;
  let expectedTotal;
  let pages = 0;
  for (;pages < maxPages; pages++) {
    const page = await fetchPage({ limit: requestSize, offset });
    if (!Number.isInteger(page.total) || page.total < 0) {
      throw new PaginationError(`Complete project traversal requires a non-negative integer producer total at offset ${offset}.`);
    }
    if (!Number.isInteger(page.offset) || page.offset !== offset) {
      throw new PaginationError(`Projects list producer returned offset ${page.offset} for requested offset ${offset}; refusing traversal.`);
    }
    if (!Number.isInteger(page.limit) || page.limit <= 0) {
      throw new PaginationError(`Projects list producer returned invalid page limit ${page.limit} at offset ${offset}.`);
    }
    if (page.rows.length > page.limit) {
      throw new PaginationError(`Projects list producer returned ${page.rows.length} rows for limit ${page.limit}; refusing traversal.`);
    }
    if (expectedTotal === undefined)
      expectedTotal = page.total;
    if (page.total !== expectedTotal) {
      throw new PaginationError(`Projects list producer total changed during traversal (${expectedTotal} -> ${page.total} at offset ${offset}); refusing a moving population.`);
    }
    const expectedHasMore = offset + page.rows.length < expectedTotal;
    if (page.has_more !== expectedHasMore) {
      throw new PaginationError(`Projects list producer has_more=${page.has_more} disagrees with total=${expectedTotal} and rows through ${offset + page.rows.length}.`);
    }
    if (page.rows.length === 0) {
      if (expectedTotal !== 0 || page.has_more) {
        throw new PaginationError(`Projects list producer returned an empty non-terminal page at offset ${offset}; refusing missing-page traversal.`);
      }
      return { rows: collected, total: expectedTotal, pages: pages + 1, complete: true };
    }
    for (const row of page.rows) {
      const id = identify(row);
      if (!id)
        throw new PaginationError(`Projects list producer returned a row without a stable identity at offset ${offset}.`);
      if (seen.has(id)) {
        throw new PaginationError(`Projects list producer returned duplicate row "${id}" at offset ${offset}; refusing traversal.`);
      }
      seen.add(id);
      collected.push(row);
    }
    if (!page.has_more) {
      if (collected.length !== expectedTotal) {
        throw new PaginationError(`Projects list terminal invariant failed: collected ${collected.length} unique rows, producer total is ${expectedTotal}.`);
      }
      return { rows: collected, total: expectedTotal, pages: pages + 1, complete: true };
    }
    offset += page.rows.length;
  }
  throw new PaginationError(`Projects list exceeded the ${maxPages}-page safety bound before reaching a terminal invariant.`);
}
var DEFAULT_PAGE_REQUEST = 5000, DEFAULT_MAX_PAGES = 1000, PaginationError;
var init_paginate = __esm(() => {
  PaginationError = class PaginationError extends Error {
    constructor(message) {
      super(message);
      this.name = "PaginationError";
    }
  };
});

// src/db/store-adoption.ts
import { Database as Database2 } from "bun:sqlite";
import {
  closeSync,
  copyFileSync,
  existsSync as existsSync6,
  mkdtempSync,
  openSync,
  readSync,
  realpathSync,
  rmSync
} from "fs";
import { tmpdir } from "os";
import { join as join5 } from "path";
function isInternalTable(name) {
  return SQLITE_INTERNAL_TABLES.has(name);
}
function classifyStoreTables(tableNames) {
  const tables = tableNames.filter((name) => !isInternalTable(name));
  if (tables.includes(PROJECTS_MIGRATION_LEDGER)) {
    return tables.every((name) => PROJECT_STORE_KNOWN_OBJECTS.has(name)) ? "ours" : "foreign";
  }
  return tables.length === 0 ? "new" : "foreign";
}
function storeTableNames(db) {
  const rows = db.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'view')").all();
  return rows.map((row) => row.name).filter((name) => !isInternalTable(name)).sort();
}
function storeTriggerNames(db) {
  const rows = db.query("SELECT name FROM sqlite_master WHERE type = 'trigger'").all();
  return rows.map((row) => row.name).sort();
}
function storeViewNames(db) {
  const rows = db.query("SELECT name FROM sqlite_master WHERE type = 'view'").all();
  return rows.map((row) => row.name).sort();
}
function storeForeignTypeRows(db) {
  return db.query("SELECT type, name FROM sqlite_master " + "WHERE type NOT IN ('table', 'index', 'view', 'trigger') ORDER BY type, name").all();
}
function declaresWalFormat(dbPath) {
  const header = Buffer.alloc(20);
  let fd;
  try {
    fd = openSync(dbPath, "r");
    const read = readSync(fd, header, 0, header.length, 0);
    return read === header.length && header[18] === 2 && header[19] === 2;
  } catch {
    return false;
  } finally {
    if (fd !== undefined)
      closeSync(fd);
  }
}
function readOnlyMode(dbPath) {
  let probe = dbPath;
  try {
    probe = realpathSync(dbPath);
  } catch {}
  if (existsSync6(`${probe}-wal`) || !declaresWalFormat(probe))
    return "plain";
  return "snapshot";
}
function openExistingStoreReadOnly(dbPath) {
  if (readOnlyMode(dbPath) === "snapshot")
    return openSnapshotOfStore(dbPath);
  const db = new Database2(dbPath, { readonly: true });
  try {
    db.run("PRAGMA busy_timeout=5000");
    return db;
  } catch (error) {
    db.close();
    throw error;
  }
}
function openSnapshotOfStore(dbPath) {
  const dir = mkdtempSync(join5(tmpdir(), "hasna-store-snapshot-"));
  let db;
  try {
    const copyPath = join5(dir, "project.db");
    copyFileSync(dbPath, copyPath);
    db = new Database2(copyPath);
    db.run("PRAGMA busy_timeout=5000");
    db.run("PRAGMA query_only=1");
  } catch (error) {
    try {
      db?.close();
    } catch {}
    rmSync(dir, { recursive: true, force: true });
    throw error;
  }
  const closeSnapshot = db.close.bind(db);
  let closed = false;
  db.close = () => {
    if (closed)
      return;
    closed = true;
    try {
      closeSnapshot();
    } finally {
      rmSync(dir, { recursive: true, force: true });
    }
  };
  return db;
}
function quoteForeignText(text) {
  const clipped = text.length > MAX_NAME_CHARS ? `${text.slice(0, MAX_NAME_CHARS)}\u2026` : text;
  return JSON.stringify(clipped);
}
function quoteObjectName(name) {
  return quoteForeignText(name);
}
function describeBounded(rendered) {
  const listed = [];
  let used = 0;
  for (const text of rendered) {
    if (listed.length >= MAX_NAMED_TABLES)
      break;
    if (used + text.length + 2 > MAX_NAMED_CHARS)
      break;
    listed.push(text);
    used += text.length + 2;
  }
  const remaining = rendered.length - listed.length;
  if (listed.length === 0)
    return `${remaining} objects (names too long to print)`;
  return remaining > 0 ? `${listed.join(", ")}, and ${remaining} more` : listed.join(", ");
}
function describeObjects(objects) {
  return describeBounded(objects.map(quoteObjectName));
}
function describeForeignTypes(rows) {
  return describeBounded(rows.map((row) => quoteForeignText(`${row.type} ${row.name}`)));
}
function ledgerShapeProblem(db) {
  const columns = db.query(`PRAGMA table_info(${PROJECTS_MIGRATION_LEDGER})`).all();
  if (columns.length === 0) {
    return `its ${PROJECTS_MIGRATION_LEDGER} table cannot be read`;
  }
  const shapeMatches = columns.length === LEDGER_COLUMNS.length && LEDGER_COLUMNS.every((want, index) => {
    const found = columns[index];
    return found.name === want.name && String(found.type).toUpperCase() === want.type && found.pk === 1 === want.pk;
  });
  if (!shapeMatches) {
    const shown = columns.slice(0, MAX_NAMED_TABLES).map((column) => quoteObjectName(String(column.name))).join(", ");
    return `its ${PROJECTS_MIGRATION_LEDGER} table has different columns (${shown})`;
  }
  const summary = db.query(`SELECT COALESCE(SUM(CASE WHEN id IN (1, 2, 3) THEN 0 ELSE 1 END), 0) AS unexpected,
            MAX(CASE WHEN id IN (1, 2, 3) THEN id END) AS highest
       FROM ${PROJECTS_MIGRATION_LEDGER}`).get();
  if (!summary) {
    return `its ${PROJECTS_MIGRATION_LEDGER} table cannot be read`;
  }
  if (summary.unexpected > 0) {
    return `its ${PROJECTS_MIGRATION_LEDGER} table records migration ids this app never writes`;
  }
  if (summary.highest !== null && summary.highest >= 2) {
    const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
    const missing = TABLES_CREATED_BY_MIGRATION_2.filter((name) => !tables.has(name));
    if (missing.length > 0) {
      return `its ${PROJECTS_MIGRATION_LEDGER} table records migration ${summary.highest} ` + `without the tables that migration creates: ${describeObjects(missing)}`;
    }
  }
  return null;
}
function assertStoreAdoptable(db, dbPath) {
  const tableNames = storeTableNames(db);
  const verdict = classifyStoreTables(tableNames);
  const foreignTypes = storeForeignTypeRows(db);
  if (foreignTypes.length > 0) {
    throw storeRefused(dbPath, "it carries objects with a type SQLite never writes: " + describeForeignTypes(foreignTypes));
  }
  const triggers = storeTriggerNames(db);
  if (triggers.length > 0) {
    throw storeRefused(dbPath, `it carries a trigger this app never creates: ${describeObjects(triggers)}`);
  }
  const views = storeViewNames(db);
  if (views.length > 0) {
    throw storeRefused(dbPath, `it carries a view this app never creates: ${describeObjects(views)}`);
  }
  if (verdict === "new")
    return;
  if (verdict === "ours") {
    const problem = ledgerShapeProblem(db);
    if (problem === null)
      return;
    throw storeRefused(dbPath, `${problem}. It is not this app's ledger`);
  }
  const objects = tableNames.filter((name) => !isInternalTable(name)).sort();
  const reason = objects.includes(PROJECTS_MIGRATION_LEDGER) ? `it carries the ${PROJECTS_MIGRATION_LEDGER} ledger beside objects this app does not create` : `it is missing the ${PROJECTS_MIGRATION_LEDGER} ledger`;
  throw storeRefused(dbPath, `${reason}; found: ${describeObjects(objects)}`);
}
function storeRefused(dbPath, reason) {
  return new Error(`Project store refused: ${dbPath} already holds a database that is not a Projects store ` + `(${reason}). ` + `Nothing was written to the database itself. Opening a WAL-mode store creates its ` + `-shm side file beside it, whether the open is read-only or read-write, and this check ` + `opens the file both ways: the read-only probe first, then the re-check on the ` + `connection that would have done the writing. Where the store is WAL format with no ` + `-wal beside it, the probe reads a disposable copy in a temporary directory instead. ` + `Move that file out of the canonical store path, or point the project at a directory ` + `of its own.`);
}
var PROJECTS_MIGRATION_LEDGER = "project_store_migrations", PROJECT_STORE_TABLES, LEGACY_PROJECT_CANVAS_TABLE = "project_canvases", PROJECT_STORE_KNOWN_OBJECTS, TABLES_CREATED_BY_MIGRATION_2, SQLITE_INTERNAL_TABLES, MAX_NAMED_TABLES = 8, MAX_NAME_CHARS = 64, MAX_NAMED_CHARS = 1024, PROJECT_STORE_MIGRATION_IDS, LEDGER_COLUMNS;
var init_store_adoption = __esm(() => {
  PROJECT_STORE_TABLES = [
    "project_meta",
    "project_store_migrations",
    "project_data_models",
    "project_data_records",
    "project_loop_links"
  ];
  PROJECT_STORE_KNOWN_OBJECTS = new Set([
    ...PROJECT_STORE_TABLES,
    LEGACY_PROJECT_CANVAS_TABLE
  ]);
  TABLES_CREATED_BY_MIGRATION_2 = PROJECT_STORE_TABLES.filter((name) => name !== PROJECTS_MIGRATION_LEDGER);
  SQLITE_INTERNAL_TABLES = new Set([
    "sqlite_sequence",
    "sqlite_stat1",
    "sqlite_stat2",
    "sqlite_stat3",
    "sqlite_stat4"
  ]);
  PROJECT_STORE_MIGRATION_IDS = new Set([1, 2, 3]);
  LEDGER_COLUMNS = [
    { name: "id", type: "INTEGER", pk: true },
    { name: "applied_at", type: "TEXT", pk: false }
  ];
});

// src/db/project-store.ts
import { Database as Database3 } from "bun:sqlite";
import { customAlphabet as customAlphabet2 } from "nanoid";
import { existsSync as existsSync7, mkdirSync as mkdirSync2, realpathSync as realpathSync2 } from "fs";
import { join as join6 } from "path";
function now2() {
  return new Date().toISOString();
}
function projectIdOf(project) {
  const projectId = typeof project === "string" ? project : project.id;
  try {
    return assertProjectWorkspaceId(projectId);
  } catch {
    throw new Error(`Invalid project id for project store path: ${projectId}`);
  }
}
function slugify(value) {
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "item";
}
function parseJson3(raw, fallback) {
  if (!raw)
    return fallback;
  try {
    return JSON.parse(raw);
  } catch {
    return fallback;
  }
}
function json2(value) {
  return JSON.stringify(value ?? null);
}
function uniqueSlug(table, base, db) {
  let candidate = slugify(base);
  let suffix = 1;
  while (true) {
    const row = db.query(`SELECT id FROM ${table} WHERE slug = ?`).get(candidate);
    if (!row)
      return candidate;
    suffix++;
    candidate = `${slugify(base)}-${suffix}`;
  }
}
function rowToDataModel(row) {
  return {
    id: row.id,
    slug: row.slug,
    name: row.name,
    description: row.description,
    schema: parseJson3(row.schema_json, {}),
    ui_schema: parseJson3(row.ui_schema_json, {}),
    render_spec: parseJson3(row.render_spec_json, null),
    metadata: parseJson3(row.metadata_json, {}),
    created_at: row.created_at,
    updated_at: row.updated_at
  };
}
function rowToDataRecord(row) {
  return {
    id: row.id,
    model_id: row.model_id,
    key: row.key,
    title: row.title,
    data: parseJson3(row.data_json, {}),
    render_spec: parseJson3(row.render_spec_json, null),
    metadata: parseJson3(row.metadata_json, {}),
    created_at: row.created_at,
    updated_at: row.updated_at
  };
}
function rowToLoopLink(row) {
  return {
    id: row.id,
    loop_id: row.loop_id,
    loop_name: row.loop_name,
    role: row.role,
    metadata: parseJson3(row.metadata_json, {}),
    created_at: row.created_at,
    updated_at: row.updated_at
  };
}
function closeIfOwned(db, owned) {
  if (owned)
    db.close();
}
function openDbForProject(project, db) {
  if (db)
    return { db, owned: false };
  return { db: getProjectDatabase(project), owned: true };
}
function getProjectsHome2() {
  return getProjectsHome();
}
function getProjectStorePaths(project) {
  const projectId = projectIdOf(project);
  const homeDir = getProjectsHome2();
  const projectDir = projectDataStorePath(projectId);
  return {
    project_id: projectId,
    home_dir: homeDir,
    project_dir: projectDir,
    db_path: join6(projectDir, "project.db"),
    assets_dir: join6(projectDir, "assets")
  };
}
function ensureProjectStoreDirs(project) {
  const paths = getProjectStorePaths(project);
  mkdirSync2(paths.project_dir, { recursive: true, mode: 448 });
  mkdirSync2(paths.assets_dir, { recursive: true, mode: 448 });
  return paths;
}
function runProjectStoreMigrations(db) {
  db.exec(`
    PRAGMA foreign_keys=ON;

    CREATE TABLE IF NOT EXISTS project_store_migrations (
      id INTEGER PRIMARY KEY,
      applied_at TEXT NOT NULL DEFAULT (datetime('now'))
    );
  `);
  const migratedV2 = db.query("SELECT id FROM project_store_migrations WHERE id = 2").get();
  if (!migratedV2)
    db.exec(`
    CREATE TABLE IF NOT EXISTS project_meta (
      key TEXT PRIMARY KEY,
      value_json TEXT NOT NULL,
      updated_at TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS project_data_models (
      id TEXT PRIMARY KEY,
      slug TEXT UNIQUE NOT NULL,
      name TEXT NOT NULL,
      description TEXT,
      schema_json TEXT NOT NULL DEFAULT '{}',
      ui_schema_json TEXT NOT NULL DEFAULT '{}',
      render_spec_json TEXT,
      metadata_json TEXT NOT NULL DEFAULT '{}',
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS project_data_records (
      id TEXT PRIMARY KEY,
      model_id TEXT NOT NULL REFERENCES project_data_models(id) ON DELETE CASCADE,
      key TEXT NOT NULL,
      title TEXT,
      data_json TEXT NOT NULL DEFAULT '{}',
      render_spec_json TEXT,
      metadata_json TEXT NOT NULL DEFAULT '{}',
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      UNIQUE(model_id, key)
    );
    CREATE INDEX IF NOT EXISTS idx_project_data_records_model ON project_data_records(model_id);

    CREATE TABLE IF NOT EXISTS project_loop_links (
      id TEXT PRIMARY KEY,
      loop_id TEXT NOT NULL UNIQUE,
      loop_name TEXT,
      role TEXT NOT NULL DEFAULT 'project-loop',
      metadata_json TEXT NOT NULL DEFAULT '{}',
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL
    );
    CREATE INDEX IF NOT EXISTS idx_project_loop_links_role ON project_loop_links(role);

    INSERT OR REPLACE INTO project_meta (key, value_json, updated_at)
      VALUES ('schema_version', '2', datetime('now'));
    INSERT OR IGNORE INTO project_store_migrations (id) VALUES (2);
  `);
  const migratedV3 = db.query("SELECT id FROM project_store_migrations WHERE id = 3").get();
  if (!migratedV3)
    db.exec(`
    INSERT OR REPLACE INTO project_meta (key, value_json, updated_at)
      VALUES ('schema_version', '3', datetime('now'));
    INSERT OR IGNORE INTO project_store_migrations (id) VALUES (3);
  `);
}
function projectStoreOwner(db) {
  const table = db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'project_meta'").get();
  if (!table)
    return null;
  const row = db.query("SELECT value_json FROM project_meta WHERE key = ?").get(PROJECT_STORE_OWNER_META_KEY);
  if (!row)
    return null;
  const value = parseJson3(row.value_json, null);
  return typeof value === "string" ? value : null;
}
function bindProjectStoreOwner(db, projectId) {
  const owner = projectStoreOwner(db);
  if (owner && owner !== projectId) {
    throw new Error(`Project store collision: canonical app store belongs to project ${owner}, not ${projectId}`);
  }
  if (!owner) {
    db.run("INSERT INTO project_meta (key, value_json, updated_at) VALUES (?, ?, ?)", [PROJECT_STORE_OWNER_META_KEY, json2(projectId), now2()]);
  }
}
function probeExistingStore(dbPath) {
  const probe = openExistingStoreReadOnly(dbPath);
  try {
    assertStoreAdoptable(probe, dbPath);
  } finally {
    probe.close();
  }
}
function closeWithoutCheckpointing(dbPath, db) {
  let guard = null;
  try {
    guard = new Database3(dbPath, { readonly: true });
    guard.query("SELECT 1").get();
  } catch {
    guard = null;
  }
  try {
    db.close();
  } finally {
    try {
      guard?.close();
    } catch {}
  }
}
function getProjectDatabase(project) {
  assertLocalStoreAllowed();
  const projectId = projectIdOf(project);
  const paths = ensureProjectStoreDirs(projectId);
  if (existsSync7(paths.db_path)) {
    probeExistingStore(paths.db_path);
  }
  const db = new Database3(paths.db_path);
  if (existsSync7(`${paths.db_path}-journal`)) {
    db.close();
    throw new Error(`Project store refused: a rollback journal is present beside ${paths.db_path} ` + `(project.db-journal), so the database is mid-transaction and any read on it ` + `completes that transaction. Neither file was touched. Let the writer finish, ` + `or \u2014 if a tool crashed \u2014 open the database once with sqlite3 so it rolls its own ` + `journal back, then try again.`);
  }
  db.run("PRAGMA busy_timeout=5000");
  try {
    assertStoreAdoptable(db, paths.db_path);
  } catch (error) {
    closeWithoutCheckpointing(paths.db_path, db);
    throw error;
  }
  db.run("PRAGMA journal_mode=WAL");
  db.run("PRAGMA foreign_keys=ON");
  runProjectStoreMigrations(db);
  bindProjectStoreOwner(db, projectId);
  return db;
}
function createProjectDataModel(project, input, db) {
  const opened = openDbForProject(project, db);
  try {
    const id = `pdm_${nanoid2()}`;
    const ts = now2();
    const slug = uniqueSlug("project_data_models", input.slug ?? input.name, opened.db);
    opened.db.run(`INSERT INTO project_data_models (
        id, slug, name, description, schema_json, ui_schema_json,
        render_spec_json, metadata_json, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
      id,
      slug,
      input.name,
      input.description ?? null,
      json2(input.schema ?? {}),
      json2(input.ui_schema ?? {}),
      input.render_spec ? json2(input.render_spec) : null,
      json2(input.metadata ?? {}),
      ts,
      ts
    ]);
    return getProjectDataModel(project, id, opened.db);
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function listProjectDataModels(project, db) {
  const opened = openDbForProject(project, db);
  try {
    const rows = opened.db.query("SELECT * FROM project_data_models ORDER BY updated_at DESC").all();
    return rows.map(rowToDataModel);
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function getProjectDataModel(project, idOrSlug, db) {
  const opened = openDbForProject(project, db);
  try {
    const row = opened.db.query("SELECT * FROM project_data_models WHERE id = ? OR slug = ? LIMIT 1").get(idOrSlug, idOrSlug);
    return row ? rowToDataModel(row) : null;
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function createProjectDataRecord(project, input, db) {
  const opened = openDbForProject(project, db);
  try {
    const id = `pdr_${nanoid2()}`;
    const ts = now2();
    const key = input.key ?? id;
    opened.db.run(`INSERT INTO project_data_records (
        id, model_id, key, title, data_json, render_spec_json,
        metadata_json, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
      id,
      input.model_id,
      key,
      input.title ?? null,
      json2(input.data ?? {}),
      input.render_spec ? json2(input.render_spec) : null,
      json2(input.metadata ?? {}),
      ts,
      ts
    ]);
    return getProjectDataRecord(project, input.model_id, key, opened.db);
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function listProjectDataRecords(project, modelId, db) {
  const opened = openDbForProject(project, db);
  try {
    const rows = opened.db.query("SELECT * FROM project_data_records WHERE model_id = ? ORDER BY updated_at DESC").all(modelId);
    return rows.map(rowToDataRecord);
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function getProjectDataRecord(project, modelId, keyOrId, db) {
  const opened = openDbForProject(project, db);
  try {
    const row = opened.db.query("SELECT * FROM project_data_records WHERE model_id = ? AND (id = ? OR key = ?) LIMIT 1").get(modelId, keyOrId, keyOrId);
    return row ? rowToDataRecord(row) : null;
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function linkProjectLoop(project, input, db) {
  const opened = openDbForProject(project, db);
  try {
    const existing = opened.db.query("SELECT * FROM project_loop_links WHERE loop_id = ? LIMIT 1").get(input.loop_id);
    const ts = now2();
    if (existing) {
      opened.db.run(`UPDATE project_loop_links
         SET loop_name = ?, role = ?, metadata_json = ?, updated_at = ?
         WHERE id = ?`, [
        input.loop_name ?? existing.loop_name,
        input.role ?? existing.role,
        json2({ ...parseJson3(existing.metadata_json, {}), ...input.metadata ?? {} }),
        ts,
        existing.id
      ]);
      return getProjectLoopLink(project, input.loop_id, opened.db);
    }
    const id = `plp_${nanoid2()}`;
    opened.db.run(`INSERT INTO project_loop_links (
        id, loop_id, loop_name, role, metadata_json, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?)`, [
      id,
      input.loop_id,
      input.loop_name ?? null,
      input.role ?? "project-loop",
      json2(input.metadata ?? {}),
      ts,
      ts
    ]);
    return getProjectLoopLink(project, input.loop_id, opened.db);
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function getProjectLoopLink(project, loopId, db) {
  const opened = openDbForProject(project, db);
  try {
    const row = opened.db.query("SELECT * FROM project_loop_links WHERE loop_id = ? OR loop_name = ? LIMIT 1").get(loopId, loopId);
    return row ? rowToLoopLink(row) : null;
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function listProjectLoopLinks(project, db) {
  const opened = openDbForProject(project, db);
  try {
    const rows = opened.db.query("SELECT * FROM project_loop_links ORDER BY role ASC, updated_at DESC").all();
    return rows.map(rowToLoopLink);
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function listProjectLoopSummaries(project, options = {}) {
  const links = listProjectLoopLinks(project, options.db);
  return withLoopsClient(options.loopsClient, async (client) => {
    const summaries = [];
    for (const link of links) {
      try {
        const loop = await client.get(link.loop_id) ?? (link.loop_name ? await client.get(link.loop_name) : undefined);
        const runs = options.includeRuns ? client.runs(stringField(loop, "id")).slice(0, options.runLimit ?? 5).map(loopRunSummary) : [];
        summaries.push({
          link,
          status: "linked",
          loop: loopSummary(loop),
          runs
        });
      } catch (err) {
        summaries.push({
          link,
          status: "missing",
          loop: null,
          runs: [],
          error: err instanceof Error ? err.message : String(err)
        });
      }
    }
    return summaries;
  }).catch((err) => {
    return links.map((link) => ({
      link,
      status: "unavailable",
      loop: null,
      runs: [],
      error: err instanceof Error ? err.message : String(err)
    }));
  });
}
async function withLoopsClient(provided, fn) {
  if (provided)
    return fn(provided);
  const sdk = await import(LOOPS_SDK_SPECIFIER);
  if (typeof sdk.loops !== "function")
    throw new Error("@hasna/loops/sdk does not export loops()");
  const client = sdk.loops();
  try {
    return await fn(client);
  } finally {
    client.close?.();
  }
}
function objectValue(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
}
function stringField(value, key) {
  const object = objectValue(value);
  const field = object[key];
  return typeof field === "string" ? field : "";
}
function numberField(value, key) {
  const object = objectValue(value);
  const field = object[key];
  return typeof field === "number" ? field : undefined;
}
function loopSummary(loop) {
  const object = objectValue(loop);
  return {
    id: stringField(object, "id"),
    name: stringField(object, "name"),
    description: stringField(object, "description") || undefined,
    status: stringField(object, "status"),
    schedule: object.schedule,
    target_type: objectValue(object.target).type,
    next_run_at: stringField(object, "nextRunAt") || undefined,
    retry_scheduled_for: stringField(object, "retryScheduledFor") || undefined,
    expires_at: stringField(object, "expiresAt") || undefined,
    updated_at: stringField(object, "updatedAt")
  };
}
function loopRunSummary(run) {
  return {
    id: stringField(run, "id"),
    scheduled_for: stringField(run, "scheduledFor"),
    attempt: numberField(run, "attempt") ?? 0,
    status: stringField(run, "status"),
    started_at: stringField(run, "startedAt") || undefined,
    finished_at: stringField(run, "finishedAt") || undefined,
    exit_code: numberField(run, "exitCode"),
    duration_ms: numberField(run, "durationMs"),
    error: stringField(run, "error") || undefined
  };
}
function inspectProjectStore(project, options = {}) {
  const paths = getProjectStorePaths(project);
  const exists = existsSync7(paths.db_path);
  if (!exists) {
    return {
      project_id: paths.project_id,
      paths,
      exists: false,
      schema_version: null,
      counts: { data_models: 0, data_records: 0, loop_links: 0 },
      legacy_canvas_storage: inspectLegacyProjectCanvasStorage(project)
    };
  }
  const opened = openDbForProject(project, options.db);
  try {
    const schemaVersion = opened.db.query("SELECT value_json FROM project_meta WHERE key = 'schema_version'").get();
    const counts = {
      data_models: tableCount(opened.db, "project_data_models"),
      data_records: tableCount(opened.db, "project_data_records"),
      loop_links: tableCount(opened.db, "project_loop_links")
    };
    return {
      project_id: paths.project_id,
      paths,
      exists,
      schema_version: schemaVersion ? Number.parseInt(schemaVersion.value_json, 10) : null,
      counts,
      legacy_canvas_storage: inspectLegacyProjectCanvasStorage(project, opened.db)
    };
  } finally {
    closeIfOwned(opened.db, opened.owned);
  }
}
function inspectLegacyProjectCanvasStorage(project, db) {
  const paths = getProjectStorePaths(project);
  const filesPath = join6(paths.project_dir, "canvases");
  const tableExists = db ? hasTable(db, LEGACY_PROJECT_CANVAS_TABLE) : legacyCanvasTableExists(paths.db_path);
  const recordCount = tableExists ? db ? tableCount(db, LEGACY_PROJECT_CANVAS_TABLE) : legacyCanvasRecordCount(paths.db_path) : 0;
  const filesPathExists = existsSync7(filesPath);
  return {
    state: tableExists || filesPathExists ? "present" : "absent",
    read_only: true,
    table: LEGACY_PROJECT_CANVAS_TABLE,
    table_exists: tableExists,
    record_count: recordCount,
    db_path: paths.db_path,
    files_path: filesPath,
    files_path_exists: filesPathExists,
    export_schema: LEGACY_PROJECT_CANVAS_EXPORT_SCHEMA
  };
}
async function inspectProjectStoreWithLoops(project, options = {}) {
  const summary = inspectProjectStore(project, { db: options.db });
  return {
    ...summary,
    loops: await listProjectLoopSummaries(project, {
      db: options.db,
      loopsClient: options.loopsClient,
      includeRuns: options.includeRuns
    })
  };
}
function tableCount(db, table) {
  const row = db.query(`SELECT COUNT(*) AS count FROM ${table}`).get();
  return row?.count ?? 0;
}
function hasTable(db, table) {
  return Boolean(db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1").get(table));
}
function legacyCanvasTableExists(dbPath) {
  if (!existsSync7(dbPath))
    return false;
  assertLocalStoreAllowed();
  const db = openExistingStoreReadOnly(dbPath);
  try {
    return hasTable(db, LEGACY_PROJECT_CANVAS_TABLE);
  } finally {
    db.close();
  }
}
function legacyCanvasRecordCount(dbPath) {
  assertLocalStoreAllowed();
  const db = openExistingStoreReadOnly(dbPath);
  try {
    return tableCount(db, LEGACY_PROJECT_CANVAS_TABLE);
  } finally {
    db.close();
  }
}
var PROJECT_STORE_OWNER_META_KEY = "owner_project_id", LEGACY_PROJECT_CANVAS_EXPORT_SCHEMA = "hasna.projects_legacy_canvas_export.v1", LOOPS_SDK_SPECIFIER = "@hasna/loops/sdk", nanoid2;
var init_project_store = __esm(() => {
  init_database();
  init_store_adoption();
  init_project_store_paths();
  init_project_store_paths();
  nanoid2 = customAlphabet2(`0123456789${"abcdefghijklmnopqrstuvwxyz"}`, 12);
});

// src/lib/budget.ts
import { customAlphabet as customAlphabet3 } from "nanoid";
function json3(value) {
  return JSON.stringify(value ?? null);
}
function parseJson4(value, fallback) {
  if (!value)
    return fallback;
  try {
    return JSON.parse(value);
  } catch {
    return fallback;
  }
}
function rowToBudget(row) {
  return {
    ...row,
    scope_type: row.scope_type,
    window: row.window,
    mode: row.mode,
    metadata: parseJson4(row.metadata, {})
  };
}
function rowToSpend(row) {
  return {
    ...row,
    metadata: parseJson4(row.metadata, {})
  };
}
function roundMoney(value) {
  return Number(value.toFixed(12));
}
function assertLimit(value, label) {
  if (value === undefined)
    return;
  if (!Number.isFinite(value) || value < 0)
    throw new Error(`${label} must be a non-negative number`);
}
function assertBudgetHasLimit(input) {
  if (input.max_usd === undefined && input.max_input_tokens === undefined && input.max_output_tokens === undefined && input.max_total_tokens === undefined) {
    throw new Error("Budget must define at least one money or token limit");
  }
}
function createProjectBudget(input, db) {
  assertBudgetHasLimit(input);
  assertLimit(input.max_usd, "max_usd");
  assertLimit(input.max_input_tokens, "max_input_tokens");
  assertLimit(input.max_output_tokens, "max_output_tokens");
  assertLimit(input.max_total_tokens, "max_total_tokens");
  const d = db || getDatabase();
  const id = input.id ?? `bud_${nanoid3()}`;
  const ts = now();
  d.run(`INSERT INTO project_budgets (
      id, scope_type, scope_id, window, mode, max_usd, max_input_tokens,
      max_output_tokens, max_total_tokens, warning_threshold, reset_at, metadata,
      created_at, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)
    ON CONFLICT(id) DO UPDATE SET
      scope_type = excluded.scope_type,
      scope_id = excluded.scope_id,
      window = excluded.window,
      mode = excluded.mode,
      max_usd = excluded.max_usd,
      max_input_tokens = excluded.max_input_tokens,
      max_output_tokens = excluded.max_output_tokens,
      max_total_tokens = excluded.max_total_tokens,
      warning_threshold = excluded.warning_threshold,
      metadata = excluded.metadata,
      updated_at = excluded.updated_at`, [
    id,
    input.scope_type,
    input.scope_id,
    input.window ?? "lifetime",
    input.mode ?? "hard",
    input.max_usd ?? null,
    input.max_input_tokens ?? null,
    input.max_output_tokens ?? null,
    input.max_total_tokens ?? null,
    input.warning_threshold ?? null,
    json3(input.metadata ?? {}),
    ts,
    ts
  ]);
  return getProjectBudget(id, d);
}
function getProjectBudget(id, db) {
  const d = db || getDatabase();
  const row = d.query("SELECT * FROM project_budgets WHERE id = ?").get(id);
  return row ? rowToBudget(row) : null;
}
function listProjectBudgets(filter = {}, db) {
  const d = db || getDatabase();
  if (filter.budget_id) {
    return d.query("SELECT * FROM project_budgets WHERE id = ? ORDER BY created_at ASC").all(filter.budget_id).map(rowToBudget);
  }
  if (filter.workspace_id && filter.run_id) {
    return d.query("SELECT * FROM project_budgets WHERE (scope_type = 'project' AND scope_id = ?) OR (scope_type = 'run' AND scope_id = ?) ORDER BY created_at ASC").all(filter.workspace_id, filter.run_id).map(rowToBudget);
  }
  if (filter.workspace_id) {
    return d.query("SELECT * FROM project_budgets WHERE scope_type = 'project' AND scope_id = ? ORDER BY created_at ASC").all(filter.workspace_id).map(rowToBudget);
  }
  if (filter.run_id) {
    return d.query("SELECT * FROM project_budgets WHERE scope_type = 'run' AND scope_id = ? ORDER BY created_at ASC").all(filter.run_id).map(rowToBudget);
  }
  return d.query("SELECT * FROM project_budgets ORDER BY created_at ASC").all().map(rowToBudget);
}
function resetProjectBudget(id, db) {
  const d = db || getDatabase();
  d.run("UPDATE project_budgets SET reset_at = ?, updated_at = ? WHERE id = ?", [now(), now(), id]);
  const budget = getProjectBudget(id, d);
  if (!budget)
    throw new Error(`Budget not found: ${id}`);
  return budget;
}
function recordProjectSpend(input, db) {
  const d = db || getDatabase();
  const id = `spend_${nanoid3()}`;
  const totalTokens = input.total_tokens ?? (input.input_tokens ?? 0) + (input.output_tokens ?? 0);
  const costUnknown = input.cost_unknown ?? (input.usd === undefined && totalTokens > 0);
  const metadata = {
    ...input.metadata ?? {},
    ...costUnknown ? { cost_unknown: true } : {}
  };
  d.run(`INSERT INTO project_budget_spend (
      id, workspace_id, run_id, provider, model, usd, input_tokens,
      output_tokens, total_tokens, metadata, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    id,
    input.workspace_id ?? null,
    input.run_id ?? null,
    input.provider ?? null,
    input.model ?? null,
    input.usd ?? 0,
    input.input_tokens ?? 0,
    input.output_tokens ?? 0,
    totalTokens,
    json3(metadata),
    now()
  ]);
  const row = d.query("SELECT * FROM project_budget_spend WHERE id = ?").get(id);
  const spend = rowToSpend(row);
  if (input.workspace_id) {
    recordWorkspaceEvent({
      workspace_id: input.workspace_id,
      event_type: "budget_spend",
      source: "system",
      after: spend,
      metadata: { run_id: input.run_id ?? null }
    }, d);
  }
  return spend;
}
function windowStartFor(budget) {
  const current = new Date;
  let start = null;
  if (budget.window === "daily") {
    start = new Date(Date.UTC(current.getUTCFullYear(), current.getUTCMonth(), current.getUTCDate()));
  } else if (budget.window === "monthly") {
    start = new Date(Date.UTC(current.getUTCFullYear(), current.getUTCMonth(), 1));
  }
  const resetAt = budget.reset_at ? new Date(budget.reset_at.replace(" ", "T") + "Z") : null;
  if (resetAt && (!start || resetAt > start))
    return resetAt.toISOString();
  return start?.toISOString() ?? null;
}
function totalsForBudget(budget, db) {
  const start = windowStartFor(budget);
  const startParam = start?.replace("T", " ").replace("Z", "");
  const projectTotalsSql = `
    SELECT
      COALESCE(SUM(usd), 0) as usd,
      COALESCE(SUM(input_tokens), 0) as input_tokens,
      COALESCE(SUM(output_tokens), 0) as output_tokens,
      COALESCE(SUM(total_tokens), 0) as total_tokens,
      COALESCE(SUM(CASE WHEN json_extract(metadata, '$.cost_unknown') = 1 THEN 1 ELSE 0 END), 0) as unknown_cost_events
    FROM project_budget_spend
    WHERE workspace_id = ?
  `;
  const projectTotalsWindowSql = `
    SELECT
      COALESCE(SUM(usd), 0) as usd,
      COALESCE(SUM(input_tokens), 0) as input_tokens,
      COALESCE(SUM(output_tokens), 0) as output_tokens,
      COALESCE(SUM(total_tokens), 0) as total_tokens,
      COALESCE(SUM(CASE WHEN json_extract(metadata, '$.cost_unknown') = 1 THEN 1 ELSE 0 END), 0) as unknown_cost_events
    FROM project_budget_spend
    WHERE workspace_id = ? AND created_at >= ?
  `;
  const runTotalsSql = `
    SELECT
      COALESCE(SUM(usd), 0) as usd,
      COALESCE(SUM(input_tokens), 0) as input_tokens,
      COALESCE(SUM(output_tokens), 0) as output_tokens,
      COALESCE(SUM(total_tokens), 0) as total_tokens,
      COALESCE(SUM(CASE WHEN json_extract(metadata, '$.cost_unknown') = 1 THEN 1 ELSE 0 END), 0) as unknown_cost_events
    FROM project_budget_spend
    WHERE run_id = ?
  `;
  const runTotalsWindowSql = `
    SELECT
      COALESCE(SUM(usd), 0) as usd,
      COALESCE(SUM(input_tokens), 0) as input_tokens,
      COALESCE(SUM(output_tokens), 0) as output_tokens,
      COALESCE(SUM(total_tokens), 0) as total_tokens,
      COALESCE(SUM(CASE WHEN json_extract(metadata, '$.cost_unknown') = 1 THEN 1 ELSE 0 END), 0) as unknown_cost_events
    FROM project_budget_spend
    WHERE run_id = ? AND created_at >= ?
  `;
  const row = budget.scope_type === "project" ? startParam ? db.query(projectTotalsWindowSql).get(budget.scope_id, startParam) : db.query(projectTotalsSql).get(budget.scope_id) : startParam ? db.query(runTotalsWindowSql).get(budget.scope_id, startParam) : db.query(runTotalsSql).get(budget.scope_id);
  return {
    usd: roundMoney(row.usd),
    input_tokens: row.input_tokens,
    output_tokens: row.output_tokens,
    total_tokens: row.total_tokens,
    unknown_cost_events: row.unknown_cost_events
  };
}
function remainingNumber(limit, spent) {
  return limit === null ? undefined : Math.max(0, roundMoney(limit - spent));
}
function remainingTokens(limit, spent) {
  return limit === null ? undefined : Math.max(0, limit - spent);
}
function exceeded(limit, spent) {
  return limit !== null && spent > limit;
}
function exhausted(limit, spent) {
  return limit !== null && spent >= limit;
}
function warningsFor(budget, spent) {
  const threshold = budget.warning_threshold ?? (budget.mode === "soft" ? 0.8 : null);
  const warnings = [];
  if (budget.max_usd !== null && spent.unknown_cost_events > 0) {
    warnings.push("USD budget cannot be verified because model pricing is missing");
  }
  const check = (label, limit, value) => {
    if (limit === null)
      return;
    if (value > limit)
      warnings.push(`${label} budget exceeded`);
    else if (threshold !== null && limit > 0 && value >= limit * threshold) {
      warnings.push(`${label} budget at or above ${Math.round(threshold * 100)}%`);
    }
  };
  check("USD", budget.max_usd, spent.usd);
  check("input token", budget.max_input_tokens, spent.input_tokens);
  check("output token", budget.max_output_tokens, spent.output_tokens);
  check("total token", budget.max_total_tokens, spent.total_tokens);
  return warnings;
}
function statusForBudget(budget, db) {
  const spent = totalsForBudget(budget, db);
  const unknownCostBlocksUsdBudget = budget.max_usd !== null && spent.unknown_cost_events > 0;
  return {
    budget,
    spent,
    remaining: {
      ...budget.max_usd === null ? {} : { usd: unknownCostBlocksUsdBudget ? 0 : remainingNumber(budget.max_usd, spent.usd) },
      ...budget.max_input_tokens === null ? {} : { input_tokens: remainingTokens(budget.max_input_tokens, spent.input_tokens) },
      ...budget.max_output_tokens === null ? {} : { output_tokens: remainingTokens(budget.max_output_tokens, spent.output_tokens) },
      ...budget.max_total_tokens === null ? {} : { total_tokens: remainingTokens(budget.max_total_tokens, spent.total_tokens) }
    },
    window_start: windowStartFor(budget),
    exhausted: unknownCostBlocksUsdBudget || exhausted(budget.max_usd, spent.usd) || exhausted(budget.max_input_tokens, spent.input_tokens) || exhausted(budget.max_output_tokens, spent.output_tokens) || exhausted(budget.max_total_tokens, spent.total_tokens),
    exceeded: unknownCostBlocksUsdBudget || exceeded(budget.max_usd, spent.usd) || exceeded(budget.max_input_tokens, spent.input_tokens) || exceeded(budget.max_output_tokens, spent.output_tokens) || exceeded(budget.max_total_tokens, spent.total_tokens),
    warnings: warningsFor(budget, spent)
  };
}
function getProjectBudgetStatuses(context = {}, db) {
  const d = db || getDatabase();
  return listProjectBudgets(context, d).map((budget) => statusForBudget(budget, d));
}
var nanoid3;
var init_budget = __esm(() => {
  init_database();
  init_workspaces();
  init_env();
  nanoid3 = customAlphabet3(`0123456789${"abcdefghijklmnopqrstuvwxyz"}`, 12);
});

// src/lib/project-relations.ts
function projectRelationId(fromProjectId, toProjectId) {
  assertProjectRelationEndpointId(fromProjectId, "from_project_id");
  assertProjectRelationEndpointId(toProjectId, "to_project_id");
  return `${PROJECT_RELATION_ID_PREFIX}${sha256(canonicalJson({
    from_project_id: fromProjectId,
    to_project_id: toProjectId
  })).slice(0, 36)}`;
}
function assertProjectRelationEndpointId(value, label) {
  const candidate = typeof value === "string" ? value.trim() : "";
  if (!candidate)
    throw new Error(`project relation ${label} must be a non-empty string`);
  if (!COMPLETE_STABLE_PROJECT_ID_RE2.test(candidate)) {
    const detail = FILES_PROJECT_REFERENCE_RE.test(candidate) ? `; '${candidate}' is a Files prj_ project reference, not a Projects identity` : "";
    throw new Error(`project relation ${label} must be a complete stable Projects identity of the form` + ` ${COMPLETE_STABLE_PROJECT_ID_PATTERN} (got '${candidate}')${detail}`);
  }
  assertCompleteStableProjectId(candidate);
  return candidate;
}
function normalizeProjectRelationKind(value, label = "relation") {
  if (typeof value !== "string" || !PROJECT_RELATIONS.includes(value)) {
    throw new Error(`project relation ${label} must be one of ${PROJECT_RELATIONS.join(", ")} (got '${String(value)}')`);
  }
  return value;
}
function projectRelationIsAcyclicKind(relation) {
  return PROJECT_RELATION_ACYCLIC_KINDS.includes(relation);
}
function assertProjectRelationNotSelf(fromProjectId, toProjectId) {
  if (fromProjectId === toProjectId) {
    throw new Error(`project relation refuses a self-link: from_project_id and to_project_id are both '${fromProjectId}'`);
  }
}
function assertProjectRelationEndpointActive(workspace, label, projectId) {
  if (!workspace) {
    throw new Error(`project relation ${label} '${projectId}' does not resolve in this tenant: no Projects identity with that id exists here`);
  }
  if (workspace.status !== "active") {
    throw new Error(`project relation ${label} '${projectId}' is ${workspace.status}: both endpoints of a relation must be active`);
  }
  return workspace;
}
function rowToProjectRelation(row) {
  return {
    relation_id: row.relation_id,
    version: Number(row.version),
    from_project_id: row.from_project_id,
    to_project_id: row.to_project_id,
    relation: normalizeProjectRelationKind(row.relation),
    superseded_by: row.superseded_by === null ? null : Number(row.superseded_by),
    superseded_at: row.superseded_at,
    created_at: row.created_at
  };
}
function projectRelationViews(relations, selfProjectId, counterparts = new Map) {
  assertCompleteStableProjectId(selfProjectId);
  const views = relations.map((relation) => {
    const outbound = relation.from_project_id === selfProjectId;
    const counterpartId = outbound ? relation.to_project_id : relation.from_project_id;
    const counterpart = counterparts.get(counterpartId);
    return {
      relation_id: relation.relation_id,
      version: relation.version,
      relation: relation.relation,
      direction: outbound ? "outbound" : "inbound",
      self_project_id: selfProjectId,
      counterpart_project_id: counterpartId,
      counterpart_slug: counterpart?.slug ?? null,
      counterpart_name: counterpart?.name ?? null,
      counterpart_status: counterpart?.status ?? null,
      created_at: relation.created_at
    };
  });
  return views.sort((a, b) => projectRelationViewKey(a).localeCompare(projectRelationViewKey(b)));
}
function projectRelationViewKey(view) {
  return canonicalJson({
    direction: view.direction,
    counterpart_project_id: view.counterpart_project_id,
    relation: view.relation,
    relation_id: view.relation_id,
    version: view.version
  });
}
function projectRelationsDigest(views) {
  const ordered = [...views].sort((a, b) => projectRelationViewKey(a).localeCompare(projectRelationViewKey(b)));
  return sha256(canonicalJson(ordered.map((view) => ({
    relation_id: view.relation_id,
    version: view.version,
    relation: view.relation,
    direction: view.direction,
    self_project_id: view.self_project_id,
    counterpart_project_id: view.counterpart_project_id,
    created_at: view.created_at
  }))));
}
function projectRelationSnapshot(project, relations) {
  return {
    project,
    relations,
    collection_digest: projectRelationsDigest(relations)
  };
}
function assertProjectRelationAcyclic(existing, candidate) {
  if (!projectRelationIsAcyclicKind(candidate.relation))
    return;
  const adjacency = new Map;
  for (const edge of existing) {
    if (!projectRelationIsAcyclicKind(edge.relation))
      continue;
    const next = adjacency.get(edge.from_project_id);
    if (next)
      next.push(edge.to_project_id);
    else
      adjacency.set(edge.from_project_id, [edge.to_project_id]);
  }
  const path = findProjectRelationPath(adjacency, candidate.to_project_id, candidate.from_project_id);
  if (path) {
    throw new Error(`project relation refuses a ${candidate.relation} cycle in the hierarchy:` + ` ${[candidate.from_project_id, ...path].join(" -> ")} closes back on '${candidate.from_project_id}'`);
  }
}
function findProjectRelationPath(adjacency, start, target) {
  if (start === target)
    return [start];
  const visited = new Set([start]);
  const queue = [{ node: start, path: [start] }];
  while (queue.length > 0) {
    const current = queue.shift();
    for (const next of adjacency.get(current.node) ?? []) {
      if (next === target)
        return [...current.path, next];
      if (visited.has(next))
        continue;
      visited.add(next);
      queue.push({ node: next, path: [...current.path, next] });
    }
  }
  return null;
}
var PROJECT_RELATION_ID_PREFIX = "prr_", FILES_PROJECT_REFERENCE_RE, COMPLETE_STABLE_PROJECT_ID_RE2;
var init_project_relations = __esm(() => {
  init_guarded_project_mutation();
  init_workspace();
  init_workspace();
  FILES_PROJECT_REFERENCE_RE = /^prj_[A-Za-z0-9_-]+$/;
  COMPLETE_STABLE_PROJECT_ID_RE2 = new RegExp(COMPLETE_STABLE_PROJECT_ID_PATTERN);
});

// src/db/project-relations.ts
function assertProjectRelationMaxItems(maxItems) {
  if (!Number.isInteger(maxItems) || maxItems <= 0) {
    throw new Error("project relation max_items must be a positive integer");
  }
}
function snapshotJson2(snapshot) {
  return snapshot;
}
function parseRelationSnapshot(value, label) {
  const snapshot = value;
  if (!snapshot?.project?.id || !Array.isArray(snapshot.relations) || typeof snapshot.collection_digest !== "string") {
    throw new Error(`${label} relation receipt snapshot is incomplete`);
  }
  return snapshot;
}
function listProjectRelationHeads(projectId, maxItems = PROJECT_RELATION_DEFAULT_MAX_ITEMS, db) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(projectId);
  assertProjectRelationMaxItems(maxItems);
  const rows = d.query(`SELECT ${RELATION_COLUMNS} FROM project_relations
     WHERE superseded_by IS NULL AND (from_project_id = ? OR to_project_id = ?)
     ORDER BY relation, relation_id
     LIMIT ?`).all(projectId, projectId, maxItems + 1);
  if (rows.length > maxItems) {
    throw new Error(`project relation collection exceeds max_items: more than ${maxItems}`);
  }
  return rows.map(rowToProjectRelation);
}
function counterpartIndex(relations, selfProjectId, db) {
  const ids = new Set;
  for (const relation of relations) {
    ids.add(relation.from_project_id === selfProjectId ? relation.to_project_id : relation.from_project_id);
  }
  const index = new Map;
  if (ids.size === 0)
    return index;
  const list = [...ids].sort();
  const placeholders = list.map(() => "?").join(", ");
  const rows = db.query(`SELECT id, slug, name, status FROM workspaces WHERE id IN (${placeholders})`).all(...list);
  for (const row of rows) {
    index.set(row.id, { slug: row.slug, name: row.name, status: row.status });
  }
  return index;
}
function relationViewsFor(relations, selfProjectId, db) {
  return projectRelationViews(relations, selfProjectId, counterpartIndex(relations, selfProjectId, db));
}
function relationSnapshotFor(project, maxItems, db) {
  const relations = listProjectRelationHeads(project.id, maxItems, db);
  return projectRelationSnapshot(project, relationViewsFor(relations, project.id, db));
}
function readProjectRelations(input, db, startedAt = Date.now()) {
  const d = db || getDatabase();
  assertCompleteStableProjectId(input.project_id);
  assertProjectRelationMaxItems(input.max_items);
  const project = getWorkspace(input.project_id, d);
  if (!project)
    throw new Error(`Workspace not found: ${input.project_id}`);
  const snapshot = relationSnapshotFor(project, input.max_items, d);
  const outbound = snapshot.relations.filter((relation) => relation.direction === "outbound").length;
  return withResponseControl({
    ok: true,
    project_id: project.id,
    project,
    current_revision: workspaceRevision(project),
    relations: snapshot.relations,
    outbound_count: outbound,
    inbound_count: snapshot.relations.length - outbound,
    relation_count: snapshot.relations.length,
    max_items: input.max_items,
    collection_digest: snapshot.collection_digest,
    complete: true,
    truncated: false
  }, input, startedAt, "project relation read");
}
function listProjectRelationAcyclicEdges(db) {
  const rows = db.query(`SELECT from_project_id, to_project_id, relation FROM project_relations
     WHERE superseded_by IS NULL AND relation IN ('parent_of', 'depends_on')`).all();
  return rows.map((row) => ({
    from_project_id: row.from_project_id,
    to_project_id: row.to_project_id,
    relation: normalizeProjectRelationKind(row.relation)
  }));
}
function findHeadRelation(relationId, db) {
  const row = db.query(`SELECT ${RELATION_COLUMNS} FROM project_relations
     WHERE relation_id = ? AND superseded_by IS NULL`).get(relationId);
  return row ? rowToProjectRelation(row) : null;
}
function findGuardedAcceptedRelationReceipt(input, db) {
  const row = db.query(`SELECT * FROM guarded_project_mutation_receipts
     WHERE operation_id = ? AND step_id = ? AND direction = 'forward' AND idempotency_key = ?
       AND target_id = ? AND outcome = 'accepted'
     ORDER BY created_at ASC, receipt_id ASC`).get(input.operation_id, input.step_id, input.idempotency_key, input.target_id);
  return row ? rowToGuardedReceipt(row) : null;
}
function findGuardedAcceptedRelationByStep(input, db) {
  const row = db.query(`SELECT * FROM guarded_project_mutation_receipts
     WHERE operation_id = ? AND step_id = ? AND direction = 'forward' AND target_id = ?
       AND outcome = 'accepted'
     ORDER BY created_at ASC, receipt_id ASC`).get(input.operation_id, input.step_id, input.target_id);
  return row ? rowToGuardedReceipt(row) : null;
}
function relationTerminalNonacceptance(input, db) {
  return insertGuardedProjectMutationReceipt({
    receipt_id: buildReceiptId({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: input.idempotency_key,
      outcome: "terminal_nonacceptance",
      target_id: input.target_id,
      suffix: input.reason
    }),
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: "forward",
    idempotency_key: input.idempotency_key,
    target_id: input.target_id,
    request_digest: input.request_digest,
    precondition_digest: input.precondition_digest,
    expected_revision: input.expected_revision,
    outcome: "terminal_nonacceptance",
    reason: input.reason,
    result_project_id: null,
    duplicate_of_receipt_id: null,
    before: input.before_snapshot,
    after: null,
    post_revision: null
  }, db);
}
function relationDuplicateOfAccepted(accepted, before, db) {
  const receiptId = buildReceiptId({
    operation_id: accepted.operation_id,
    step_id: accepted.step_id,
    direction: accepted.direction,
    idempotency_key: accepted.idempotency_key,
    outcome: "duplicate_of_accepted",
    target_id: accepted.target_id,
    suffix: accepted.receipt_id
  });
  const existing = db.query("SELECT * FROM guarded_project_mutation_receipts WHERE receipt_id = ?").get(receiptId);
  if (existing)
    return rowToGuardedReceipt(existing);
  return insertGuardedProjectMutationReceipt({
    receipt_id: receiptId,
    operation_id: accepted.operation_id,
    step_id: accepted.step_id,
    direction: accepted.direction,
    idempotency_key: accepted.idempotency_key,
    target_id: accepted.target_id,
    request_digest: accepted.request_digest,
    precondition_digest: accepted.precondition_digest,
    expected_revision: accepted.expected_revision,
    outcome: "duplicate_of_accepted",
    reason: null,
    result_project_id: accepted.result_project_id,
    duplicate_of_receipt_id: accepted.receipt_id,
    before: snapshotJson2(before),
    after: accepted.after,
    post_revision: accepted.post_revision
  }, db);
}
function assertProjectRelationMode(mode) {
  if (mode !== "add" && mode !== "supersede") {
    throw new Error(`project relation mode must be add or supersede (got '${String(mode)}')`);
  }
  return mode;
}
function mutateProjectRelation(input, db) {
  const d = db || getDatabase();
  const started = Date.now();
  assertCompleteStableProjectId(input.project_id);
  const toProjectId = assertProjectRelationEndpointId(input.to_project_id, "to_project_id");
  const relation = normalizeProjectRelationKind(input.relation);
  assertProjectRelationNotSelf(input.project_id, toProjectId);
  const mode = assertProjectRelationMode(input.mode);
  const maxItems = PROJECT_RELATION_DEFAULT_MAX_ITEMS;
  const relationId = projectRelationId(input.project_id, toProjectId);
  const reqDigest = sha256(canonicalJson({
    mode,
    relation,
    from_project_id: input.project_id,
    to_project_id: toProjectId
  }));
  const preDigest = preconditionDigest({
    project_id: input.project_id,
    expected_revision: input.expected_revision,
    ...input.expected_relation_version === undefined ? {} : { expected_relation_version: input.expected_relation_version }
  });
  const idempotencyKey = deriveGuardedIdempotencyKey({
    operation_id: input.operation_id,
    step_id: input.step_id,
    direction: "forward",
    target_id: input.project_id,
    request_digest: reqDigest,
    precondition_digest: preDigest
  });
  return d.transaction(() => {
    const fromProject = getWorkspace(input.project_id, d);
    if (!fromProject)
      throw new Error(`Workspace not found: ${input.project_id}`);
    const before = relationSnapshotFor(fromProject, maxItems, d);
    const currentRevision = workspaceRevision(fromProject);
    const envelope = (fields) => withResponseControl({
      mode,
      idempotency_key: idempotencyKey,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      project_id: input.project_id,
      expected_revision: input.expected_revision,
      current_revision: currentRevision,
      relation_id: relationId,
      ...fields
    }, input, started, "project relation mutation");
    const duplicate = findGuardedAcceptedRelationReceipt({
      operation_id: input.operation_id,
      step_id: input.step_id,
      idempotency_key: idempotencyKey,
      target_id: input.project_id
    }, d);
    if (duplicate) {
      return envelope({
        ok: true,
        dry_run: false,
        outcome: "duplicate_of_accepted",
        before,
        after: parseRelationSnapshot(duplicate.after, "accepted"),
        receipt: relationDuplicateOfAccepted(duplicate, before, d)
      });
    }
    const reject = (reason) => envelope({
      ok: false,
      dry_run: false,
      outcome: "terminal_nonacceptance",
      before,
      after: null,
      receipt: relationTerminalNonacceptance({
        operation_id: input.operation_id,
        step_id: input.step_id,
        idempotency_key: idempotencyKey,
        target_id: input.project_id,
        request_digest: reqDigest,
        precondition_digest: preDigest,
        expected_revision: input.expected_revision,
        reason,
        before_snapshot: snapshotJson2(before)
      }, d)
    });
    const priorAccepted = findGuardedAcceptedRelationByStep({
      operation_id: input.operation_id,
      step_id: input.step_id,
      target_id: input.project_id
    }, d);
    if (priorAccepted)
      return reject("changed_request_or_precondition_for_step");
    if (currentRevision !== input.expected_revision)
      return reject("stale_revision");
    const toProject = assertProjectRelationEndpointActive(getWorkspace(toProjectId, d), "to_project_id", toProjectId);
    assertProjectRelationEndpointActive(fromProject, "project_id", input.project_id);
    const head = findHeadRelation(relationId, d);
    if (mode === "add" && head)
      return reject("duplicate_relation_identity");
    if (mode === "supersede" && !head)
      return reject("relation_not_found");
    if (head && head.relation === relation)
      return reject("relation_unchanged");
    if (mode === "supersede") {
      if (input.expected_relation_version === undefined) {
        return reject("relation_state_precondition_required");
      }
      if (head && input.expected_relation_version !== head.version) {
        return reject("stale_relation_state");
      }
    }
    assertProjectRelationAcyclic(listProjectRelationAcyclicEdges(d), { from_project_id: input.project_id, to_project_id: toProjectId, relation });
    const timestamp = now();
    const nextVersion = (head?.version ?? 0) + 1;
    const proposedHeads = [
      ...listProjectRelationHeads(input.project_id, maxItems, d).filter((item) => item.relation_id !== relationId),
      {
        relation_id: relationId,
        version: nextVersion,
        from_project_id: input.project_id,
        to_project_id: toProjectId,
        relation,
        superseded_by: null,
        superseded_at: null,
        created_at: timestamp
      }
    ];
    const preview = projectRelationSnapshot(fromProject, relationViewsFor(proposedHeads, input.project_id, d));
    if (input.dry_run) {
      return envelope({
        ok: true,
        dry_run: true,
        outcome: "planned",
        before,
        after: preview,
        receipt: null
      });
    }
    if (timedOut(started, input.time_budget_ms)) {
      throw new Error("project relation mutation time budget exceeded before write");
    }
    if (head) {
      const superseded = d.run(`UPDATE project_relations SET superseded_by = ?, superseded_at = ?
         WHERE relation_id = ? AND version = ? AND superseded_by IS NULL`, [nextVersion, timestamp, relationId, head.version]);
      if (superseded.changes !== 1)
        throw new Error("project relation supersede conditional update lost");
    }
    d.run(`INSERT INTO project_relations (
        relation_id, version, from_project_id, to_project_id, relation,
        superseded_by, superseded_at, created_at
      ) VALUES (?, ?, ?, ?, ?, NULL, NULL, ?)`, [relationId, nextVersion, input.project_id, toProjectId, relation, timestamp]);
    const after = relationSnapshotFor(fromProject, maxItems, d);
    if (after.collection_digest !== preview.collection_digest) {
      throw new Error("project relation exact readback mismatch");
    }
    const receipt = insertGuardedProjectMutationReceipt({
      receipt_id: buildReceiptId({
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: "forward",
        idempotency_key: idempotencyKey,
        outcome: "accepted",
        target_id: input.project_id
      }),
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      idempotency_key: idempotencyKey,
      target_id: input.project_id,
      request_digest: reqDigest,
      precondition_digest: preDigest,
      expected_revision: input.expected_revision,
      outcome: "accepted",
      reason: null,
      result_project_id: input.project_id,
      duplicate_of_receipt_id: null,
      before: snapshotJson2(before),
      after: snapshotJson2(after),
      post_revision: currentRevision
    }, d);
    recordWorkspaceEvent({
      workspace_id: input.project_id,
      agent_id: input.agent_id,
      event_type: mode === "add" ? "project_relation_add" : "project_relation_supersede",
      source: input.source ?? "cli",
      command: input.command,
      before: snapshotJson2(before),
      after: snapshotJson2(after),
      metadata: {
        receipt_id: receipt.receipt_id,
        operation_id: input.operation_id,
        step_id: input.step_id,
        idempotency_key: idempotencyKey,
        relation_id: relationId,
        relation,
        version: nextVersion,
        from_project_id: input.project_id,
        to_project_id: toProjectId,
        counterpart_slug: toProject.slug,
        collection_digest: after.collection_digest
      }
    }, d);
    return envelope({
      ok: true,
      dry_run: false,
      outcome: "accepted",
      before,
      after,
      receipt
    });
  })();
}
var RELATION_COLUMNS = "relation_id, version, from_project_id, to_project_id, relation, superseded_by, superseded_at, created_at";
var init_project_relations2 = __esm(() => {
  init_database();
  init_workspaces();
  init_guarded_project_mutation();
  init_project_relations();
  init_workspace();
});

// src/lib/workspace-plan.ts
var init_workspace_plan = __esm(() => {
  init_workspaces();
  init_database();
  init_project_channel();
  init_project_management();
  init_workspace_runtime();
  init_project_store_paths();
});

// src/lib/project-registration.ts
import { join as join7, resolve as resolve5 } from "path";

class ProjectRegistrationPathHandle {
  #absolutePath;
  #pathDigest;
  constructor(path) {
    this.#absolutePath = resolve5(path);
    this.#pathDigest = sha256(this.#absolutePath);
  }
  static fromPath(path) {
    if (!path?.trim())
      throw new Error("project registration requires a non-empty target path");
    return new ProjectRegistrationPathHandle(path);
  }
  get digest() {
    return this.#pathDigest;
  }
  withOwnedPath(consumer) {
    return consumer(this.#absolutePath);
  }
}
function controlledResult(payload, bounds, startedAtMs) {
  const envelope = {
    ...payload,
    response_control: {
      response_byte_limit: bounds.response_byte_limit,
      time_budget_ms: bounds.time_budget_ms,
      response_bytes: 0,
      elapsed_ms: 0,
      complete: true,
      truncated: false
    }
  };
  envelope.response_control = responseControl(envelope, bounds, startedAtMs, "project registration");
  envelope.response_control = responseControl(envelope, bounds, startedAtMs, "project registration");
  return envelope;
}
function parseJsonObjectArray(raw) {
  const parsed = JSON.parse(raw);
  if (!Array.isArray(parsed))
    throw new Error("project registration receipt array is malformed");
  return parsed;
}
function parseAuthorityReceipt(raw) {
  return raw ? JSON.parse(raw) : null;
}
function rowToReceipt(row) {
  return {
    receipt_id: row.receipt_id,
    operation_id: row.operation_id,
    sequence: row.sequence,
    step_id: row.step_id,
    authority: row.authority,
    resource_kind: row.resource_kind,
    direction: row.direction,
    idempotency_key: row.idempotency_key,
    target_id: row.target_id,
    request_digest: row.request_digest,
    precondition_digest: row.precondition_digest,
    outcome: row.outcome,
    reason: row.reason,
    result_revision: row.result_revision,
    result_digest: row.result_digest,
    duplicate_of_receipt_id: row.duplicate_of_receipt_id,
    authority_receipt: parseAuthorityReceipt(row.authority_receipt_json),
    artifacts: parseJsonObjectArray(row.artifacts_json),
    preconditions: parseJsonObjectArray(row.preconditions_json),
    rollback: parseJsonObjectArray(row.rollback_json),
    created_at: row.created_at
  };
}
function safeAuthorityReceipt(receipt) {
  if (!("resource_kind" in receipt)) {
    return {
      receipt_id: receipt.receipt_id,
      authority: receipt.authority,
      route: receipt.route,
      package_version: receipt.package_version,
      authority_id: receipt.authority_id,
      tenant_id: receipt.tenant_id,
      corpus_id: receipt.corpus_id,
      operation_id: receipt.operation_id,
      step_id: receipt.step_id,
      direction: receipt.direction,
      idempotency_key: receipt.idempotency_key,
      request_digest: receipt.request_digest,
      outcome: receipt.outcome,
      target_id: receipt.target_id,
      expected_revision: receipt.expected_revision,
      result_revision: receipt.result_revision,
      result_digest: receipt.result_digest,
      accepted_receipt_id: receipt.accepted_receipt_id,
      created_at: receipt.created_at
    };
  }
  return {
    receipt_id: receipt.receipt_id,
    authority: receipt.authority,
    route: receipt.route,
    package_version: receipt.package_version,
    authority_id: receipt.authority_id,
    tenant_id: receipt.tenant_id,
    corpus_id: receipt.corpus_id,
    operation_id: receipt.operation_id,
    step_id: receipt.step_id,
    resource_kind: receipt.resource_kind,
    direction: receipt.direction,
    idempotency_key: receipt.idempotency_key,
    request_digest: receipt.request_digest,
    precondition_digest: receipt.precondition_digest,
    outcome: receipt.outcome,
    reason: receipt.reason,
    target_id: receipt.target_id,
    result_revision: receipt.result_revision,
    result_digest: receipt.result_digest,
    duplicate_of_receipt_id: receipt.duplicate_of_receipt_id,
    accepted_receipt_id: receipt.accepted_receipt_id,
    created_by_operation: receipt.created_by_operation,
    created_at: receipt.created_at
  };
}
function receiptLogicalPayload(input) {
  return {
    operation_id: input.operation_id,
    step_id: input.step_id,
    authority: input.authority,
    resource_kind: input.resource_kind,
    direction: input.direction,
    idempotency_key: input.idempotency_key,
    target_id: input.target_id ?? null,
    request_digest: input.request_digest,
    precondition_digest: input.precondition_digest,
    outcome: input.outcome,
    reason: input.reason ?? null,
    result_revision: input.result_revision ?? null,
    result_digest: input.result_digest ?? null,
    duplicate_of_receipt_id: input.duplicate_of_receipt_id ?? null,
    authority_receipt: input.authority_receipt ? safeAuthorityReceipt(input.authority_receipt) : null,
    artifacts: input.artifacts ?? [],
    preconditions: input.preconditions ?? [],
    rollback: input.rollback ?? []
  };
}
function buildReceiptId2(input) {
  return `prr_${sha256(canonicalJson(receiptLogicalPayload(input))).slice(0, 36)}`;
}
function deriveProjectRegistrationIdempotencyKey(input) {
  return `prk_${sha256(canonicalJson({
    route: PROJECT_REGISTRATION_ROUTE,
    ...input
  })).slice(0, 48)}`;
}
function appendRegistrationReceiptInTransaction(input, db) {
  const receiptId = buildReceiptId2(input);
  const existing = db.query("SELECT * FROM project_registration_receipts WHERE receipt_id = ?").get(receiptId);
  if (existing)
    return rowToReceipt(existing);
  if (input.outcome === "accepted") {
    const prior = db.query(`SELECT * FROM project_registration_receipts
       WHERE operation_id = ? AND step_id = ? AND authority = ? AND resource_kind = ?
         AND direction = ? AND outcome = 'accepted'
       ORDER BY sequence ASC LIMIT 1`).get(input.operation_id, input.step_id, input.authority, input.resource_kind, input.direction);
    if (prior && prior.idempotency_key !== input.idempotency_key) {
      throw new Error(`project registration step already accepted with different semantics: ${input.step_id}`);
    }
  }
  const sequenceRow = db.query("SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence FROM project_registration_receipts WHERE operation_id = ?").get(input.operation_id);
  const sequence = Number(sequenceRow.next_sequence);
  const logical = receiptLogicalPayload(input);
  db.run(`INSERT INTO project_registration_receipts (
      receipt_id, operation_id, sequence, step_id, authority, resource_kind,
      direction, idempotency_key, target_id, request_digest,
      precondition_digest, outcome, reason, result_revision, result_digest,
      duplicate_of_receipt_id, authority_receipt_json, artifacts_json,
      preconditions_json, rollback_json, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
    receiptId,
    input.operation_id,
    sequence,
    input.step_id,
    input.authority,
    input.resource_kind,
    input.direction,
    input.idempotency_key,
    input.target_id ?? null,
    input.request_digest,
    input.precondition_digest,
    input.outcome,
    input.reason ?? null,
    input.result_revision ?? null,
    input.result_digest ?? null,
    input.duplicate_of_receipt_id ?? null,
    input.authority_receipt ? canonicalJson(safeAuthorityReceipt(input.authority_receipt)) : null,
    canonicalJson(logical.artifacts ?? []),
    canonicalJson(logical.preconditions ?? []),
    canonicalJson(logical.rollback ?? []),
    now()
  ]);
  return rowToReceipt(db.query("SELECT * FROM project_registration_receipts WHERE receipt_id = ?").get(receiptId));
}
function appendRegistrationReceipt(input, db) {
  return db.transaction(() => appendRegistrationReceiptInTransaction(input, db))();
}
function lookupProjectRegistrationReceipt(input, db) {
  const d = db ?? getDatabase();
  const startedAt = Date.now();
  if (input.max_items !== 1)
    throw new Error("project registration receipt lookup max_items must be exactly 1");
  const rows = d.query(`SELECT * FROM project_registration_receipts
     WHERE operation_id = ? AND step_id = ? AND direction = ? AND idempotency_key = ?
     ORDER BY sequence ASC LIMIT 2`).all(input.operation_id, input.step_id, input.direction, input.idempotency_key);
  if (rows.length === 0) {
    throw new Error("project registration receipt lookup expected exactly one terminal receipt, found 0");
  }
  const receipts = rows.map(rowToReceipt);
  const accepted = receipts.find((receipt2) => receipt2.outcome === "accepted");
  const duplicates = receipts.filter((receipt2) => receipt2.outcome === "duplicate_of_accepted");
  if (receipts.length > 1) {
    if (!accepted || duplicates.length !== receipts.length - 1 || duplicates.some((receipt2) => receipt2.duplicate_of_receipt_id !== accepted.receipt_id)) {
      throw new Error(`project registration receipt lookup expected exactly one terminal result, found ${receipts.length}`);
    }
  }
  const receipt = duplicates.at(-1) ?? accepted ?? receipts[0];
  return controlledResult({ receipt }, input, startedAt);
}
function listProjectRegistrationReceipts(operationId, db) {
  const d = db ?? getDatabase();
  const rows = d.query(`SELECT * FROM project_registration_receipts
     WHERE operation_id = ? ORDER BY sequence ASC LIMIT ?`).all(operationId, PROJECT_REGISTRATION_MAX_RECEIPTS + 1);
  if (rows.length > PROJECT_REGISTRATION_MAX_RECEIPTS) {
    throw new Error(`project registration receipt population exceeds ${PROJECT_REGISTRATION_MAX_RECEIPTS}`);
  }
  return rows.map(rowToReceipt);
}
function projectRegistrationManifestFromRow(row) {
  return {
    operation_id: row.operation_id,
    route: row.route,
    request_digest: row.request_digest,
    project_id: row.project_id,
    project_slug: row.project_slug,
    plan: JSON.parse(row.plan_json),
    created_at: row.created_at
  };
}
function localProjectRegistrationLedger(db) {
  const handle = () => db ?? getDatabase();
  return {
    async ensureManifest(input) {
      const result = createOrReadManifest({
        operation_id: input.operation_id,
        request_digest: input.request_digest,
        project_id: input.project_id,
        project_slug: input.project_slug,
        plan: input.plan
      }, handle());
      return { manifest: projectRegistrationManifestFromRow(result.manifest), created: result.created };
    },
    async readManifest(operationId) {
      const row = handle().query("SELECT * FROM project_registration_manifests WHERE operation_id = ?").get(operationId);
      return row ? projectRegistrationManifestFromRow(row) : null;
    },
    async appendReceipt(input) {
      return appendRegistrationReceipt(input, handle());
    },
    async lookupReceipt(input) {
      return lookupProjectRegistrationReceipt(input, handle());
    },
    async listReceipts(operationId) {
      return listProjectRegistrationReceipts(operationId, handle());
    },
    async findAcceptedReceipts(input) {
      const rows = handle().query(`SELECT * FROM project_registration_receipts
         WHERE operation_id = ? AND step_id = ? AND direction = ? AND outcome = 'accepted'
         ORDER BY sequence ASC LIMIT ?`).all(input.operation_id, input.step_id, input.direction, input.limit);
      return rows.map(rowToReceipt);
    }
  };
}
function registrationPlanMatches(stored, requestedCanonical) {
  if (stored === requestedCanonical)
    return true;
  try {
    return canonicalJson(JSON.parse(stored)) === requestedCanonical;
  } catch {
    return false;
  }
}
function createOrReadManifest(input, db) {
  const planJson = canonicalJson(input.plan);
  return db.transaction(() => {
    const inserted = db.run(`INSERT OR IGNORE INTO project_registration_manifests (
        operation_id, route, request_digest, project_id, project_slug, plan_json, created_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?)`, [
      input.operation_id,
      PROJECT_REGISTRATION_ROUTE,
      input.request_digest,
      input.project_id,
      input.project_slug,
      planJson,
      now()
    ]);
    const existing = db.query("SELECT * FROM project_registration_manifests WHERE operation_id = ?").get(input.operation_id);
    if (!existing) {
      throw new ProjectRegistrationStepError("registration_manifest", "manifest_insert_missing");
    }
    if (existing.route !== PROJECT_REGISTRATION_ROUTE || existing.request_digest !== input.request_digest || existing.project_id !== input.project_id || existing.project_slug !== input.project_slug || !registrationPlanMatches(existing.plan_json, planJson)) {
      throw new ProjectRegistrationStepError("registration_manifest", "operation_semantics_conflict");
    }
    return { manifest: existing, created: inserted.changes === 1 };
  })();
}
var PROJECT_REGISTRATION_ROUTE = "projects.full-registration.v1", PROJECT_REGISTRATION_MAX_RECEIPTS = 32, ProjectRegistrationStepError;
var init_project_registration = __esm(() => {
  init_workspaces();
  init_database();
  init_guarded_project_mutation();
  init_project_channel();
  init_project_resource_links();
  init_project_management();
  init_project_store_paths();
  init_workspace_plan();
  init_workspace_runtime();
  ProjectRegistrationStepError = class ProjectRegistrationStepError extends Error {
    stepId;
    code;
    splitState;
    constructor(stepId, code, splitState = false) {
      super(`${stepId}:${code}`);
      this.stepId = stepId;
      this.code = code;
      this.splitState = splitState;
      this.name = "ProjectRegistrationStepError";
    }
  };
});

// src/lib/production-project-registration-authorities.ts
function firstConfigured(env2, keys) {
  for (const key of keys) {
    const value = env2[key]?.trim();
    if (value)
      return { key, value };
  }
  return null;
}
function authorityRoot(raw, sourceKey) {
  let url;
  try {
    url = new URL(raw);
  } catch {
    throw new Error(`${sourceKey} must be an absolute http(s) URL`);
  }
  if (!["http:", "https:"].includes(url.protocol)) {
    throw new Error(`${sourceKey} must be an absolute http(s) URL`);
  }
  if (url.username || url.password || url.search || url.hash) {
    throw new Error(`${sourceKey} must not contain userinfo, query, or fragment data`);
  }
  const pathname = url.pathname.replace(/\/+$/, "");
  const prefix = pathname === "/v1" ? "" : pathname.replace(/\/v1$/, "");
  return `${url.origin}${prefix}`;
}
function authorityHttpConfig(config, env2) {
  const localDatabase = firstConfigured(env2, config.dbPathKeys);
  if (localDatabase)
    return null;
  const url = firstConfigured(env2, config.apiUrlKeys);
  const key = firstConfigured(env2, config.apiKeyKeys);
  if (!url && !key) {
    throw new Error(`${config.authority} project registration requires ${config.apiUrlKeys[0]} ` + `or an explicit ${config.dbPathKeys[0]}`);
  }
  if (!url) {
    throw new Error(`${config.apiUrlKeys[0]} is required when ${key.key} is configured`);
  }
  if (!key) {
    throw new Error(`${config.apiKeyKeys[0]} is required when ${url.key} is configured`);
  }
  return {
    baseUrl: authorityRoot(url.value, url.key),
    apiKey: key.value
  };
}
function moduleObject(value, packageName) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${packageName} did not load as an ES module`);
  }
  return value;
}
function responseObject(authority, value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${authority} project registration returned a non-object response`);
  }
  return value;
}
function selectedResponse(authority, value, key) {
  const body = responseObject(authority, value);
  return key && key in body ? body[key] : body;
}
function withoutTarget(request) {
  const { target: _target, ...serializable } = request;
  return serializable;
}
function withTargetDigest(request) {
  return {
    ...withoutTarget(request),
    target_digest: request.target.digest
  };
}
function assertAdapter(authority, value) {
  if (!value || typeof value !== "object" || value.authority !== authority) {
    throw new Error(`${authority} package did not return its project registration authority`);
  }
  return value;
}

class ConversationsSdkAuthority {
  client;
  authority = "conversations";
  constructor(client) {
    this.client = client;
  }
  async capability() {
    return selectedResponse(this.authority, await this.client.getProjectChannelRegistrationCapability());
  }
  async create(request) {
    if (request.operation_intent === "adopt_existing") {
      if (!this.client.adoptExistingProjectChannel) {
        throw new Error("Conversations SDK does not expose adoptExistingProjectChannel");
      }
      return selectedResponse(this.authority, await this.client.adoptExistingProjectChannel(withTargetDigest(request)));
    }
    return selectedResponse(this.authority, await this.client.registerProjectChannel(withTargetDigest(request)));
  }
  async readExact(request) {
    return selectedResponse(this.authority, await this.client.readProjectChannelRegistrationExact(request.target_id, {
      resource_kind: request.resource_kind,
      target_digest: request.target.digest,
      response_byte_limit: request.response_byte_limit,
      time_budget_ms: request.time_budget_ms,
      call_limit: 1
    }));
  }
  async lookupReceipt(request) {
    return selectedResponse(this.authority, await this.client.lookupProjectChannelRegistrationReceipt({
      ...request,
      call_limit: 1
    }));
  }
  async validateExistingAdoption(request, receipt) {
    if (request.resource_kind !== "channel" || typeof request.desired.channel !== "string")
      return false;
    const response = await this.client.getChannel(request.desired.channel);
    if (!response)
      return false;
    const nestedChannel = response.channel;
    const channel = nestedChannel && typeof nestedChannel === "object" && !Array.isArray(nestedChannel) ? nestedChannel : response;
    return channel.id === receipt.target_id && channel.name === request.desired.channel && (channel.project_id === null || channel.project_id === request.project_id);
  }
  async compensate(request) {
    return selectedResponse(this.authority, await this.client.compensateProjectChannelRegistration(withTargetDigest(request)));
  }
  async verifyInverse(request) {
    return selectedResponse(this.authority, await this.client.verifyProjectChannelRegistrationInverse(withTargetDigest(request)));
  }
}
async function loadHttpAuthority(authority, http, fetchImpl, importModule) {
  if (authority === "todos") {
    const specifier2 = "@hasna/todos/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createClient = module2.createTodosProjectRegistrationHttpClient;
    if (typeof createClient !== "function") {
      throw new Error(`${specifier2} does not expose createTodosProjectRegistrationHttpClient`);
    }
    return assertAdapter(authority, createClient({
      baseUrl: http.baseUrl,
      apiKey: http.apiKey,
      fetch: fetchImpl
    }));
  }
  if (authority === "mementos") {
    const specifier2 = "@hasna/mementos/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createClient = module2.createMementosProjectRegistrationHttpClient;
    if (typeof createClient !== "function") {
      throw new Error(`${specifier2} does not expose createMementosProjectRegistrationHttpClient`);
    }
    return assertAdapter(authority, createClient({
      baseUrl: http.baseUrl,
      apiKey: http.apiKey,
      fetch: fetchImpl
    }));
  }
  if (authority === "files") {
    const specifier2 = "@hasna/files/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createClient = module2.createFilesProjectRegistrationHttpClient;
    if (typeof createClient !== "function") {
      throw new Error(`${specifier2} does not expose createFilesProjectRegistrationHttpClient`);
    }
    return assertAdapter(authority, createClient({
      baseUrl: http.baseUrl,
      apiKey: http.apiKey,
      fetch: fetchImpl
    }));
  }
  const specifier = "@hasna/conversations/sdk";
  const module = moduleObject(await importModule(specifier), specifier);
  const ConversationsClient = module.ConversationsClient;
  if (typeof ConversationsClient !== "function") {
    throw new Error(`${specifier} does not expose ConversationsClient`);
  }
  const client = new ConversationsClient({
    baseUrl: http.baseUrl,
    apiKey: http.apiKey,
    fetch: fetchImpl
  });
  return new ConversationsSdkAuthority(client);
}
function announceLocalAuthority(authority, localDatabaseKey, notify) {
  notify(`projects: local mode \u2014 ${localDatabaseKey} is set, so the ${authority} project registration ` + (authority === "files" ? "capability reports the on-box files instance instead of the hosted files service." : `authority reads and writes the on-box ${authority} SQLite instead of the hosted ${authority} service.`));
}
async function loadLocalAuthority(authority, importModule, localDatabaseKey, notify = (line) => console.error(line)) {
  announceLocalAuthority(authority, localDatabaseKey, notify);
  if (authority === "todos") {
    const specifier2 = "@hasna/todos";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const getDatabase2 = module2.getDatabase;
    const createAuthority2 = module2.createLocalTodosProjectRegistrationAuthority;
    if (typeof getDatabase2 !== "function" || typeof createAuthority2 !== "function") {
      throw new Error(`${specifier2} does not expose the shipped local project registration authority`);
    }
    return assertAdapter(authority, createAuthority2(getDatabase2()));
  }
  if (authority === "mementos") {
    const specifier2 = "@hasna/mementos";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const getDatabase2 = module2.getDatabase;
    const createAuthority2 = module2.createLocalMementosProjectRegistrationAuthority;
    if (typeof getDatabase2 !== "function" || typeof createAuthority2 !== "function") {
      throw new Error(`${specifier2} does not expose the shipped local project registration authority`);
    }
    return assertAdapter(authority, createAuthority2(getDatabase2()));
  }
  if (authority === "files") {
    const specifier2 = "@hasna/files/project-registration";
    const module2 = moduleObject(await importModule(specifier2), specifier2);
    const createAuthority2 = module2.createLocalFilesProjectRegistrationAuthority;
    if (typeof createAuthority2 !== "function") {
      throw new Error(`${specifier2} does not expose the shipped local project registration authority`);
    }
    return assertAdapter(authority, createAuthority2());
  }
  const specifier = "@hasna/conversations";
  const module = moduleObject(await importModule(specifier), specifier);
  const createAuthority = module.createProjectChannelRegistrationAuthority;
  if (typeof createAuthority !== "function") {
    throw new Error(`${specifier} does not expose the shipped project channel registration authority`);
  }
  return assertAdapter(authority, createAuthority());
}

class LazyProjectRegistrationAuthority {
  load;
  authority;
  transport;
  delegate = null;
  constructor(authority, transport, load) {
    this.load = load;
    this.authority = authority;
    this.transport = transport;
  }
  resolve() {
    this.delegate ??= this.load();
    return this.delegate;
  }
  async capability() {
    return (await this.resolve()).capability();
  }
  async create(request) {
    return (await this.resolve()).create(request);
  }
  async readExact(request) {
    return (await this.resolve()).readExact(request);
  }
  async lookupReceipt(request) {
    return (await this.resolve()).lookupReceipt(request);
  }
  async validateExistingAdoption(request, receipt) {
    const delegate = await this.resolve();
    return delegate.validateExistingAdoption?.(request, receipt) ?? false;
  }
  async validatePriorRegistrationAdoption(sourceRequest, sourceReceipt, currentRecord) {
    const delegate = await this.resolve();
    return delegate.validatePriorRegistrationAdoption?.(sourceRequest, sourceReceipt, currentRecord) ?? false;
  }
  async compensate(request) {
    return (await this.resolve()).compensate(request);
  }
  async verifyInverse(request) {
    return (await this.resolve()).verifyInverse(request);
  }
  async guardedUpdateProject(targetId, request) {
    const delegate = await this.resolve();
    if (!delegate.guardedUpdateProject) {
      throw new Error(`${this.authority} package does not expose guardedUpdateProject`);
    }
    return delegate.guardedUpdateProject(targetId, request);
  }
  async getGuardedProjectUpdateReceipt(targetId, receiptId, request) {
    const delegate = await this.resolve();
    if (!delegate.getGuardedProjectUpdateReceipt) {
      throw new Error(`${this.authority} package does not expose getGuardedProjectUpdateReceipt`);
    }
    return delegate.getGuardedProjectUpdateReceipt(targetId, receiptId, request);
  }
  async rollbackGuardedProjectUpdate(targetId, request) {
    const delegate = await this.resolve();
    if (!delegate.rollbackGuardedProjectUpdate) {
      throw new Error(`${this.authority} package does not expose rollbackGuardedProjectUpdate`);
    }
    return delegate.rollbackGuardedProjectUpdate(targetId, request);
  }
}
function configuredAuthority(authority, options) {
  const config = AUTHORITY_ENDPOINTS[authority];
  const localDatabase = firstConfigured(options.env, config.dbPathKeys);
  const transport = localDatabase ? "local" : firstConfigured(options.env, [...config.apiUrlKeys, ...config.apiKeyKeys]) ? "api" : undefined;
  return new LazyProjectRegistrationAuthority(authority, transport, async () => {
    const http = authorityHttpConfig(config, options.env);
    return http ? loadHttpAuthority(authority, http, options.fetch, options.importModule) : loadLocalAuthority(authority, options.importModule, localDatabase?.key ?? config.dbPathKeys[0]);
  });
}
function productionProjectRegistrationAuthorities(options = {}) {
  const resolved = {
    env: options.env ?? process.env,
    fetch: options.fetch ?? globalThis.fetch,
    importModule: options.importModule ?? ((specifier) => import(specifier))
  };
  return {
    todos: configuredAuthority("todos", resolved),
    mementos: configuredAuthority("mementos", resolved),
    conversations: configuredAuthority("conversations", resolved),
    files: configuredAuthority("files", resolved)
  };
}
var AUTHORITY_ENDPOINTS;
var init_production_project_registration_authorities = __esm(() => {
  AUTHORITY_ENDPOINTS = {
    todos: {
      authority: "todos",
      apiUrlKeys: ["HASNA_TODOS_API_URL", "TODOS_API_URL"],
      apiKeyKeys: ["HASNA_TODOS_API_KEY", "TODOS_API_KEY"],
      dbPathKeys: ["HASNA_TODOS_DB_PATH", "TODOS_DB_PATH"]
    },
    mementos: {
      authority: "mementos",
      apiUrlKeys: ["HASNA_MEMENTOS_API_URL", "MEMENTOS_API_URL"],
      apiKeyKeys: ["HASNA_MEMENTOS_API_KEY", "MEMENTOS_API_KEY"],
      dbPathKeys: ["HASNA_MEMENTOS_DB_PATH", "MEMENTOS_DB_PATH"]
    },
    conversations: {
      authority: "conversations",
      apiUrlKeys: ["HASNA_CONVERSATIONS_API_URL", "CONVERSATIONS_API_URL"],
      apiKeyKeys: ["HASNA_CONVERSATIONS_API_KEY", "CONVERSATIONS_API_KEY"],
      dbPathKeys: ["HASNA_CONVERSATIONS_DB_PATH", "CONVERSATIONS_DB_PATH"]
    },
    files: {
      authority: "files",
      apiUrlKeys: ["HASNA_FILES_API_URL", "FILES_API_URL"],
      apiKeyKeys: ["HASNA_FILES_API_KEY", "FILES_API_KEY"],
      dbPathKeys: ["HASNA_FILES_DB_PATH", "FILES_DB_PATH"]
    }
  };
});

// src/lib/project-resource-link-producer-verifier.ts
function objectValue2(value, label) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${label} must be an object`);
  }
  return value;
}
function stringValue2(value, label) {
  if (typeof value !== "string" || !value.trim()) {
    throw new Error(`${label} must be a nonempty string`);
  }
  return value;
}
function nullableStringValue(value, label) {
  return value === null ? null : stringValue2(value, label);
}
function booleanValue(value, label) {
  if (typeof value !== "boolean")
    throw new Error(`${label} must be a boolean`);
  return value;
}
function receiptValue(value, label) {
  const receipt = objectValue2(value, label);
  const authority = stringValue2(receipt.authority, `${label}.authority`);
  const resourceKind = stringValue2(receipt.resource_kind, `${label}.resource_kind`);
  const direction = stringValue2(receipt.direction, `${label}.direction`);
  const outcome = stringValue2(receipt.outcome, `${label}.outcome`);
  if (!["todos", "mementos", "conversations"].includes(authority)) {
    throw new Error(`${label}.authority is not a supported project-registration authority`);
  }
  if (!["project", "task_list", "channel"].includes(resourceKind)) {
    throw new Error(`${label}.resource_kind is unsupported`);
  }
  if (!["forward", "inverse"].includes(direction)) {
    throw new Error(`${label}.direction is unsupported`);
  }
  if (!["accepted", "duplicate_of_accepted", "terminal_nonacceptance"].includes(outcome)) {
    throw new Error(`${label}.outcome is unsupported`);
  }
  return {
    receipt_id: stringValue2(receipt.receipt_id, `${label}.receipt_id`),
    authority,
    route: stringValue2(receipt.route, `${label}.route`),
    package_version: stringValue2(receipt.package_version, `${label}.package_version`),
    authority_id: stringValue2(receipt.authority_id, `${label}.authority_id`),
    tenant_id: stringValue2(receipt.tenant_id, `${label}.tenant_id`),
    corpus_id: stringValue2(receipt.corpus_id, `${label}.corpus_id`),
    operation_id: stringValue2(receipt.operation_id, `${label}.operation_id`),
    step_id: stringValue2(receipt.step_id, `${label}.step_id`),
    resource_kind: resourceKind,
    direction,
    idempotency_key: stringValue2(receipt.idempotency_key, `${label}.idempotency_key`),
    request_digest: stringValue2(receipt.request_digest, `${label}.request_digest`),
    precondition_digest: stringValue2(receipt.precondition_digest, `${label}.precondition_digest`),
    outcome,
    reason: nullableStringValue(receipt.reason, `${label}.reason`),
    target_id: nullableStringValue(receipt.target_id, `${label}.target_id`),
    result_revision: nullableStringValue(receipt.result_revision, `${label}.result_revision`),
    result_digest: nullableStringValue(receipt.result_digest, `${label}.result_digest`),
    duplicate_of_receipt_id: nullableStringValue(receipt.duplicate_of_receipt_id, `${label}.duplicate_of_receipt_id`),
    accepted_receipt_id: nullableStringValue(receipt.accepted_receipt_id, `${label}.accepted_receipt_id`),
    created_by_operation: booleanValue(receipt.created_by_operation, `${label}.created_by_operation`),
    created_at: stringValue2(receipt.created_at, `${label}.created_at`)
  };
}
function envelopeValue(evidence) {
  const raw = objectValue2(evidence.producer_verification, "producer verification evidence");
  if (raw.schema !== PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA) {
    throw new Error(`producer verification evidence schema must be ${PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA}`);
  }
  if (!Array.isArray(raw.links)) {
    throw new Error("producer verification evidence links must be an array");
  }
  const links = raw.links.map((value, index) => {
    const link = objectValue2(value, `producer verification link ${index}`);
    const inverseRequest = link.inverse_request === undefined ? undefined : objectValue2(link.inverse_request, `producer verification link ${index}.inverse_request`);
    return {
      link_id: stringValue2(link.link_id, `producer verification link ${index}.link_id`),
      target_context_digest: stringValue2(link.target_context_digest, `producer verification link ${index}.target_context_digest`),
      target_selector: stringValue2(link.target_selector, `producer verification link ${index}.target_selector`),
      forward_receipt: receiptValue(link.forward_receipt, `producer verification link ${index}.forward_receipt`),
      ...link.inverse_receipt === undefined ? {} : {
        inverse_receipt: receiptValue(link.inverse_receipt, `producer verification link ${index}.inverse_receipt`)
      },
      ...inverseRequest ? {
        inverse_request: {
          project_slug: stringValue2(inverseRequest.project_slug, `producer verification link ${index}.inverse_request.project_slug`),
          project_name: stringValue2(inverseRequest.project_name, `producer verification link ${index}.inverse_request.project_name`),
          desired: objectValue2(inverseRequest.desired, `producer verification link ${index}.inverse_request.desired`)
        }
      } : {}
    };
  });
  if (new Set(links.map((link) => link.link_id)).size !== links.length) {
    throw new Error("producer verification evidence contains duplicate link ids");
  }
  return {
    schema: PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA,
    links
  };
}
function authorityName(item) {
  const authority = item.link.authority;
  if (!["todos", "mementos", "conversations"].includes(authority)) {
    throw new Error(`producer authority ${authority} is not configured for trusted readback`);
  }
  return authority;
}
function resourceKind(item) {
  const targetKind = item.link.target_kind;
  if (!["project", "task_list", "channel"].includes(targetKind)) {
    throw new Error(`producer target kind ${targetKind} is not supported for trusted readback`);
  }
  return targetKind;
}
function expectedTargetId(item) {
  const { kind, value } = item.link.locator;
  if (kind === "canonical_uri") {
    const parts = value.split(/[:/]/).filter(Boolean);
    const targetId = parts.at(-1);
    if (!targetId)
      throw new Error("producer canonical locator does not contain a target id");
    return targetId;
  }
  if (kind === "external_uuid" || kind.endsWith("_id"))
    return value;
  throw new Error(`producer locator kind ${kind} is not supported for trusted readback`);
}
function assertCapability(item, capability, expectedAuthority, expectedResourceKind) {
  const binding = item.producer_binding;
  if (capability.authority !== expectedAuthority || capability.authority_id !== binding.authority_id || capability.tenant_id !== binding.tenant_id || capability.corpus_id !== binding.corpus_id) {
    throw new Error("producer capability does not match the manifest authority, tenant, and corpus binding");
  }
  if (sha256(canonicalJson(capability)) !== binding.capability_digest) {
    throw new Error("producer capability digest does not match the manifest binding");
  }
  if (!capability.immutable_receipts || !capability.exact_terminal_lookup || !capability.exact_readback || !capability.supported_resources.includes(expectedResourceKind)) {
    throw new Error("producer capability does not support immutable exact receipt/readback verification");
  }
}
function assertReceiptContext(receipt, manifest, item, capability, expectedDirection, expectedResourceKind) {
  const binding = item.producer_binding;
  if (receipt.authority !== capability.authority || receipt.route !== capability.route || receipt.package_version !== capability.package_version || receipt.authority_id !== binding.authority_id || receipt.tenant_id !== binding.tenant_id || receipt.corpus_id !== binding.corpus_id || receipt.operation_id !== manifest.operation_id || receipt.step_id !== manifest.step_id || receipt.resource_kind !== expectedResourceKind || receipt.direction !== expectedDirection) {
    throw new Error("producer receipt does not bind the manifest operation and authority context");
  }
}
function trustedConversationsForwardRequest(manifest, item, input) {
  const project = input.trusted_project;
  if (manifest.project_id !== project.id) {
    throw new Error("producer manifest does not match the trusted project subject");
  }
  if (item.link.authority !== "conversations" || item.link.target_kind !== "channel") {
    throw new Error(`producer request reconstruction is not configured for ${item.link.authority}/${item.link.target_kind}`);
  }
  const targetSelector = project.conversations_channel;
  if (item.link.labels?.channel_name !== undefined && item.link.labels.channel_name !== targetSelector) {
    throw new Error("producer manifest channel label does not match the trusted project subject");
  }
  const desired = {
    channel: targetSelector,
    project_id: project.id,
    project_slug: project.slug,
    project_kind: project.kind
  };
  const requestDigest2 = sha256(canonicalJson(desired));
  const preconditionDigest2 = sha256(canonicalJson({
    target_selector: targetSelector,
    expected: "absent"
  }));
  return {
    target_selector: targetSelector,
    idempotency_key: deriveProjectRegistrationIdempotencyKey({
      operation_id: manifest.operation_id,
      step_id: manifest.step_id,
      direction: "forward",
      target_selector: targetSelector,
      request_digest: requestDigest2,
      precondition_digest: preconditionDigest2
    }),
    request_digest: requestDigest2,
    precondition_digest: preconditionDigest2,
    project_id: project.id,
    project_slug: project.slug,
    project_name: project.name,
    desired
  };
}
function trustedInverseRequest(manifest, forwardReceipt, input) {
  const project = input.trusted_project;
  if (manifest.project_id !== project.id) {
    throw new Error("producer manifest does not match the trusted project subject");
  }
  if (!forwardReceipt.target_id) {
    throw new Error("producer forward receipt does not identify an inverse target");
  }
  const desired = {
    accepted_receipt_id: forwardReceipt.receipt_id,
    target_id: forwardReceipt.target_id
  };
  const requestDigest2 = sha256(canonicalJson(desired));
  const preconditionDigest2 = sha256(canonicalJson({
    target_id: forwardReceipt.target_id,
    expected_revision: forwardReceipt.result_revision,
    expected_digest: forwardReceipt.result_digest
  }));
  return {
    target_selector: forwardReceipt.target_id,
    idempotency_key: deriveProjectRegistrationIdempotencyKey({
      operation_id: manifest.operation_id,
      step_id: manifest.step_id,
      direction: "inverse",
      target_selector: forwardReceipt.target_id,
      request_digest: requestDigest2,
      precondition_digest: preconditionDigest2
    }),
    request_digest: requestDigest2,
    precondition_digest: preconditionDigest2,
    project_id: project.id,
    project_slug: project.slug,
    project_name: project.name,
    desired
  };
}
function assertLookupControl(result, input) {
  const control = result.response_control;
  if (control.complete !== true || control.truncated !== false || control.response_bytes > input.response_byte_limit || control.elapsed_ms > input.time_budget_ms) {
    throw new Error("producer receipt lookup did not return one complete bounded result");
  }
}
async function lookupStoredReceipt(authority, receipt, request, input) {
  const result = await authority.lookupReceipt({
    operation_id: receipt.operation_id,
    step_id: receipt.step_id,
    resource_kind: receipt.resource_kind,
    direction: receipt.direction,
    authority: receipt.authority,
    authority_route: receipt.route,
    package_version: receipt.package_version,
    authority_id: receipt.authority_id,
    tenant_id: receipt.tenant_id,
    corpus_id: receipt.corpus_id,
    target_selector: request.target_selector,
    idempotency_key: request.idempotency_key,
    request_digest: request.request_digest,
    precondition_digest: request.precondition_digest,
    ...receipt.target_id ? { target_id: receipt.target_id } : {},
    max_items: 1,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  });
  assertLookupControl(result, input);
  const stored = receiptValue(result.receipt, "lookup.receipt");
  if (canonicalJson(stored) !== canonicalJson(receipt)) {
    throw new Error("stored producer receipt does not match the supplied verification envelope");
  }
  return stored;
}
function opaqueTargetHandle(digest) {
  return {
    digest,
    withOwnedPath() {
      throw new Error("producer authority requires an owned path, but migration verification only carries an opaque target context");
    }
  };
}
function assertForwardReceipt(receipt, manifest, item, producerEvidence, capability, expectedResourceKind, request) {
  assertReceiptContext(receipt, manifest, item, capability, "forward", expectedResourceKind);
  const persisted = item.producer_evidence;
  if (!persisted)
    throw new Error("producer verification has no persisted forward evidence");
  if (receipt.outcome !== "accepted" || receipt.receipt_id !== producerEvidence.forward_receipt_id || receipt.receipt_id !== persisted.forward_receipt_id || receipt.created_by_operation !== persisted.created_by_operation || receipt.target_id !== expectedTargetId(item) || receipt.idempotency_key !== request.idempotency_key || receipt.request_digest !== request.request_digest || receipt.precondition_digest !== request.precondition_digest) {
    throw new Error("producer forward receipt does not bind the trusted project subject and manifest target");
  }
  if (producerEvidence.child_link_receipt_ids.length > 0) {
    throw new Error("producer child-link receipt verification is not configured; refusing terminal transition");
  }
}
async function assertCurrentReadback(authority, receipt, proof, producerEvidence, input) {
  if (!receipt.target_id)
    throw new Error("producer forward receipt does not identify a target");
  const record = await authority.readExact({
    resource_kind: receipt.resource_kind,
    target_id: receipt.target_id,
    target: opaqueTargetHandle(proof.target_context_digest),
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  });
  if (record.target_id !== receipt.target_id || record.revision !== producerEvidence.target_revision || record.digest !== producerEvidence.target_digest) {
    throw new Error("producer exact readback does not match the terminal migration evidence");
  }
}
function assertInverseReceipt(receipt, forwardReceipt, manifest, item, producerEvidence, capability, expectedResourceKind, phase, request) {
  assertReceiptContext(receipt, manifest, item, capability, "inverse", expectedResourceKind);
  const expectedOutcome = phase === "inverse_complete" ? ["accepted", "duplicate_of_accepted"] : ["terminal_nonacceptance"];
  if (!expectedOutcome.includes(receipt.outcome) || receipt.accepted_receipt_id !== forwardReceipt.receipt_id || receipt.target_id !== forwardReceipt.target_id || receipt.result_revision !== producerEvidence.target_revision || receipt.result_digest !== producerEvidence.target_digest || receipt.idempotency_key !== request.idempotency_key || receipt.request_digest !== request.request_digest || receipt.precondition_digest !== request.precondition_digest) {
    throw new Error("producer inverse receipt does not prove the requested terminal outcome");
  }
}
async function assertInverseComplete(authority, forwardReceipt, inverseReceipt, inverseRequest, proof, request, input) {
  if (!forwardReceipt.target_id)
    throw new Error("producer forward receipt does not identify a target");
  if (inverseRequest.project_slug !== request.project_slug || inverseRequest.project_name !== request.project_name || canonicalJson(inverseRequest.desired) !== canonicalJson(request.desired)) {
    throw new Error("producer inverse request evidence does not match the trusted project subject");
  }
  const verification = await authority.verifyInverse({
    operation_id: inverseReceipt.operation_id,
    step_id: inverseReceipt.step_id,
    resource_kind: inverseReceipt.resource_kind,
    direction: "inverse",
    authority_route: inverseReceipt.route,
    package_version: inverseReceipt.package_version,
    authority_id: inverseReceipt.authority_id,
    tenant_id: inverseReceipt.tenant_id,
    corpus_id: inverseReceipt.corpus_id,
    target_selector: request.target_selector,
    idempotency_key: request.idempotency_key,
    request_digest: request.request_digest,
    precondition_digest: request.precondition_digest,
    project_id: request.project_id,
    project_slug: request.project_slug,
    project_name: request.project_name,
    desired: request.desired,
    target: opaqueTargetHandle(proof.target_context_digest),
    accepted_receipt: forwardReceipt,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  });
  if (verification.absent !== true || verification.target_id !== forwardReceipt.target_id || verification.accepted_receipt_id !== forwardReceipt.receipt_id || !verification.digest?.trim()) {
    throw new Error("producer inverse verification did not prove exact target absence");
  }
}
async function verifyLink(authority, capability, manifest, item, proof, producerEvidence, input) {
  const expectedAuthority = authorityName(item);
  const expectedResourceKind = resourceKind(item);
  const forwardRequest = trustedConversationsForwardRequest(manifest, item, input);
  assertCapability(item, capability, expectedAuthority, expectedResourceKind);
  if (proof.target_selector !== forwardRequest.target_selector) {
    throw new Error("producer verification target selector does not match the trusted project subject");
  }
  assertForwardReceipt(proof.forward_receipt, manifest, item, producerEvidence, capability, expectedResourceKind, forwardRequest);
  const storedForward = await lookupStoredReceipt(authority, proof.forward_receipt, forwardRequest, input);
  if (input.phase === "readback") {
    await assertCurrentReadback(authority, storedForward, proof, producerEvidence, input);
    return;
  }
  if (!capability.conditional_inverse) {
    throw new Error("producer capability does not support conditional inverse verification");
  }
  if (!proof.inverse_receipt || !proof.inverse_request) {
    throw new Error("producer inverse verification requires an exact inverse receipt and request context");
  }
  const inverseRequest = trustedInverseRequest(manifest, storedForward, input);
  assertInverseReceipt(proof.inverse_receipt, storedForward, manifest, item, producerEvidence, capability, expectedResourceKind, input.phase, inverseRequest);
  const storedInverse = await lookupStoredReceipt(authority, proof.inverse_receipt, inverseRequest, input);
  if (input.phase === "inverse_complete") {
    await assertInverseComplete(authority, storedForward, storedInverse, proof.inverse_request, proof, inverseRequest, input);
    return;
  }
  await assertCurrentReadback(authority, storedForward, proof, producerEvidence, input);
}
function createProductionProjectResourceLinkProducerEvidenceVerifier(options = {}) {
  const authorities = options.authorities ?? productionProjectRegistrationAuthorities();
  const now3 = options.now ?? (() => new Date().toISOString());
  return async (input) => {
    const envelope = envelopeValue(input.transition_evidence);
    if (envelope.links.length !== input.manifest.links.length) {
      throw new Error("producer verification evidence requires exact proof for every manifest link");
    }
    const proofByLink = new Map(envelope.links.map((proof) => [proof.link_id, proof]));
    const capabilityByAuthority = new Map;
    for (let index = 0;index < input.manifest.links.length; index += 1) {
      const item = input.manifest.links[index];
      const proof = proofByLink.get(item.link_id);
      if (!proof)
        throw new Error(`producer verification evidence is missing link ${item.link_id}`);
      const name = authorityName(item);
      const authority = authorities[name];
      if (!authority)
        throw new Error(`producer authority ${name} is not configured for trusted readback`);
      let capability = capabilityByAuthority.get(name);
      if (!capability) {
        capability = await authority.capability();
        capabilityByAuthority.set(name, capability);
      }
      await verifyLink(authority, capability, input.manifest, item, proof, input.producer_evidence[index], input);
    }
    const evidenceDigest = projectResourceLinkProducerEvidenceDigest(input.manifest, input.phase, input.producer_evidence);
    return {
      attestation_id: projectResourceLinkProducerAttestationId(input.manifest.manifest_id, input.phase, evidenceDigest),
      manifest_id: input.manifest.manifest_id,
      phase: input.phase,
      evidence_digest: evidenceDigest,
      verifier: PROJECT_RESOURCE_LINK_PRODUCER_VERIFIER,
      verified_at: now3()
    };
  };
}
var PROJECT_RESOURCE_LINK_PRODUCER_VERIFICATION_SCHEMA = "projects.project_resource_link_producer_verification.v1", PROJECT_RESOURCE_LINK_PRODUCER_VERIFIER = "projects.production-producer-authority-readback.v1";
var init_project_resource_link_producer_verifier = __esm(() => {
  init_guarded_project_mutation();
  init_project_resource_link_migrations();
  init_project_registration();
  init_production_project_registration_authorities();
});

// src/lib/project-list-output.ts
var PROJECT_QUERY_SCOPES, PROJECT_LIST_FIELDS, DEFAULT_PROJECT_LIST_MAX_BYTES, MAX_PROJECT_LIST_MAX_BYTES, PROJECT_LIST_V2_CONTRACT = "projects.list.v2", PROJECT_LIST_FIELD_SET, PROJECT_QUERY_SCOPE_SET;
var init_project_list_output = __esm(() => {
  PROJECT_QUERY_SCOPES = ["identity", "discovery", "structured", "all"];
  PROJECT_LIST_FIELDS = [
    "id",
    "slug",
    "name",
    "status",
    "kind",
    "path",
    "canonical_machine",
    "root_id",
    "recipe_id",
    "git_remote",
    "updated_at"
  ];
  DEFAULT_PROJECT_LIST_MAX_BYTES = 32 * 1024;
  MAX_PROJECT_LIST_MAX_BYTES = 256 * 1024;
  PROJECT_LIST_FIELD_SET = new Set(PROJECT_LIST_FIELDS);
  PROJECT_QUERY_SCOPE_SET = new Set(PROJECT_QUERY_SCOPES);
});

// src/store/project-store.ts
import {
  createHasnaStorageClient,
  resolveStorageClient
} from "@hasna/contracts/client/storage";
import {
  clientTransportEnvKeys as clientTransportEnvKeys2,
  credentialDiskSources
} from "@hasna/contracts/client";
import { basename } from "path";
function withLock(workspaceId, ctx, reason, fn) {
  const key = `workspace:${workspaceId}`;
  const hasLocalWorkspaceRow = getWorkspace(workspaceId) !== null;
  let lock;
  try {
    lock = acquireWorkspaceLock({
      lock_key: key,
      workspace_id: hasLocalWorkspaceRow ? workspaceId : undefined,
      agent_id: ctx?.agentId,
      reason,
      ttl_seconds: 600
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    if (message.startsWith("Workspace lock already held:")) {
      throw new Error(message.replace("Workspace lock", "Project lock"));
    }
    throw err;
  }
  try {
    return fn();
  } finally {
    releaseWorkspaceLock(key, lock.id);
  }
}
function mutationFields(ctx) {
  return {
    agent_id: ctx?.agentId,
    source: ctx?.source ?? "cli",
    command: ctx?.command,
    prompt: ctx?.prompt
  };
}
async function prepareLocalProducerEvidenceVerifier(verifier, input, phase) {
  const manifest = readProjectResourceLinkMigration({
    project_id: input.project_id,
    manifest_id: input.manifest_id,
    max_items: 1,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  }).manifest;
  const trustedProject = getWorkspace(input.project_id);
  if (!trustedProject) {
    throw new Error(`Project not found: ${input.project_id}`);
  }
  const producerEvidence = phase === "readback" ? reconcileProjectResourceLinkProducerProof(manifest, input.producer_evidence, "readback") : reconcileProjectResourceLinkProducerProof(manifest, input.producer_evidence, "inverse", phase === "inverse_complete" ? "complete" : "retained_target");
  const verificationInput = {
    manifest,
    trusted_project: projectResourceLinkProducerProjectSubject(trustedProject),
    phase,
    producer_evidence: producerEvidence,
    transition_evidence: input.evidence,
    response_byte_limit: input.response_byte_limit,
    time_budget_ms: input.time_budget_ms
  };
  const attestation = await verifier(verificationInput);
  const expectedInput = canonicalJson(verificationInput);
  return (actualInput) => {
    if (canonicalJson(actualInput) !== expectedInput) {
      throw new Error("local producer attestation does not match the transition under lock");
    }
    return attestation;
  };
}

class LocalProjectStore {
  producerEvidenceVerifier;
  transport = "local";
  baseUrl = null;
  constructor(producerEvidenceVerifier) {
    this.producerEvidenceVerifier = producerEvidenceVerifier;
  }
  async listProjects(filter) {
    if (filter?.limit === undefined && filter?.offset === undefined) {
      return (await this.listProjectsComplete(filter)).projects;
    }
    return listWorkspaces(filter ?? {});
  }
  async listProjectsComplete(filter) {
    const f = filter ?? {};
    const projects = listWorkspaces(f);
    const total = countWorkspaces(f);
    const ids = new Set(projects.map((project) => project.id));
    if (ids.size !== projects.length || projects.length !== total) {
      throw new Error(`Projects list terminal invariant failed: local producer returned ${projects.length} unique rows for total ${total}.`);
    }
    return { projects, total, pages: 1, complete: true };
  }
  async listProjectsPage(filter) {
    const f = filter ?? {};
    return buildProjectListPage(listWorkspaces(f), f, countWorkspaces(f));
  }
  async getProject(idOrSlug) {
    return resolveWorkspace(idOrSlug);
  }
  async resolveTarget(target, options) {
    return resolveRegisteredProjectTargetOrThrow(target, options).project;
  }
  async createProject(input) {
    return createWorkspace(input);
  }
  async updateProject(id, patch) {
    return withLock(id, { agentId: patch.agent_id, source: patch.source, command: patch.command }, "project update", () => updateWorkspace(id, patch));
  }
  async guardedReadProject(input) {
    const started = Date.now();
    assertCompleteStableProjectId(input.project_id);
    assertPositiveBounds(input);
    const project = getWorkspace(input.project_id);
    if (!project)
      throw new Error(`Project not found: ${input.project_id}`);
    const maxItems = input.resource_link_max_items ?? 1000;
    const links = listProjectResourceLinks(input.project_id, maxItems);
    return buildGuardedProjectReadResult(project, input, started, {
      links,
      max_items: maxItems,
      collection_digest: readProjectResourceLinks({
        project_id: input.project_id,
        max_items: maxItems,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      }).collection_digest
    });
  }
  async readProjectResourceLinks(input) {
    return readProjectResourceLinks(input);
  }
  async mutateProjectResourceLinks(input) {
    return withLock(input.project_id, { agentId: input.agent_id, source: input.source, command: input.command }, "project resource links mutation", () => input.integrations ? mutateProjectResourceLinksForRegistration(input, input.integrations) : mutateProjectResourceLinks(input));
  }
  async rollbackProjectResourceLinks(input) {
    return withLock(input.project_id, { agentId: input.agent_id, source: input.source, command: input.command }, "project resource links rollback", () => rollbackProjectResourceLinks(input));
  }
  async readProjectRelations(input) {
    return readProjectRelations(input);
  }
  async mutateProjectRelation(input) {
    const ctx = { agentId: input.agent_id, source: input.source, command: input.command };
    const [first, second] = [input.project_id, input.to_project_id].sort();
    const run = () => mutateProjectRelation(input);
    return second && second !== first ? withLock(first, ctx, "project relation mutation", () => withLock(second, ctx, "project relation mutation", run)) : withLock(first, ctx, "project relation mutation", run);
  }
  async createProjectRegistrationManifest(input) {
    return localProjectRegistrationLedger().ensureManifest(input);
  }
  async readProjectRegistrationManifest(operationId) {
    return localProjectRegistrationLedger().readManifest(operationId);
  }
  async appendProjectRegistrationReceipt(input) {
    return localProjectRegistrationLedger().appendReceipt(input);
  }
  async lookupProjectRegistrationReceipt(input) {
    return localProjectRegistrationLedger().lookupReceipt(input);
  }
  async listProjectRegistrationReceipts(operationId) {
    return localProjectRegistrationLedger().listReceipts(operationId);
  }
  async findProjectRegistrationReceipts(input) {
    return localProjectRegistrationLedger().findAcceptedReceipts(input);
  }
  async readDuplicateProjectQuarantinePreimage(input) {
    return readDuplicateProjectQuarantinePreimage(input);
  }
  async quarantineDuplicateProject(input) {
    return withLock(input.project_id, { agentId: input.agent_id, source: input.source, command: input.command }, "duplicate project quarantine", () => quarantineDuplicateProject(input));
  }
  async rollbackDuplicateProjectQuarantine(input) {
    return withLock(input.project_id, { agentId: input.agent_id, source: input.source, command: input.command }, "duplicate project quarantine rollback", () => rollbackDuplicateProjectQuarantine(input));
  }
  async planProjectResourceLinkMigration(input) {
    return withLock(input.project_id, undefined, "project resource link migration plan", () => planProjectResourceLinkMigration(input));
  }
  async readProjectResourceLinkMigration(input) {
    return readProjectResourceLinkMigration(input);
  }
  async advanceProjectResourceLinkMigration(input) {
    const verifier = input.next_state === "verified" ? await prepareLocalProducerEvidenceVerifier(this.producerEvidenceVerifier, input, "readback") : undefined;
    return withLock(input.project_id, undefined, "project resource link migration advance", () => advanceProjectResourceLinkMigration(input, undefined, verifier));
  }
  async rollbackProjectResourceLinkMigration(input) {
    const phase = input.producer_outcome === "complete" ? "inverse_complete" : input.producer_outcome === "retained_target" ? "inverse_retained_target" : undefined;
    const verifier = phase ? await prepareLocalProducerEvidenceVerifier(this.producerEvidenceVerifier, input, phase) : undefined;
    return withLock(input.project_id, undefined, "project resource link migration rollback", () => rollbackProjectResourceLinkMigration(input, undefined, verifier));
  }
  async guardedUpdateProject(input) {
    return withLock(input.project_id, { agentId: input.agent_id, source: input.source, command: input.command }, "guarded project update", () => guardedUpdateWorkspace(input));
  }
  async lookupGuardedProjectMutationReceipt(input) {
    const started = Date.now();
    const receipt = lookupGuardedWorkspaceMutationReceipt(input);
    return withResponseControl({ receipt }, input, started);
  }
  async rollbackGuardedProjectMutation(input) {
    return withLock(input.project_id, { agentId: input.agent_id, source: input.source, command: input.command }, "guarded project rollback", () => rollbackGuardedWorkspaceMutation(input));
  }
  async archiveProject(id, ctx) {
    return withLock(id, ctx, "project archive", () => archiveWorkspace(id, mutationFields(ctx)));
  }
  async unarchiveProject(id, ctx) {
    return withLock(id, ctx, "project unarchive", () => unarchiveWorkspace(id, mutationFields(ctx)));
  }
  async deleteProject(id, opts, ctx) {
    const res = withLock(id, ctx, "project delete", () => deleteWorkspace(id, { ...mutationFields(ctx), hard: opts.hard }));
    return { workspace: res.workspace, hard: res.hard, id: res.workspace.id };
  }
  async listEvents(idOrSlug, limit) {
    const project = resolveWorkspace(idOrSlug);
    if (!project)
      throw new Error(`Project not found: ${idOrSlug}`);
    const events = listWorkspaceEvents(project.id);
    return limit && limit > 0 ? events.slice(-limit).reverse() : events;
  }
  async recordEvent(idOrSlug, input) {
    const project = resolveWorkspace(idOrSlug);
    if (!project)
      throw new Error(`Project not found: ${idOrSlug}`);
    return recordWorkspaceEvent({
      workspace_id: project.id,
      agent_id: input.agentId,
      event_type: input.event_type,
      source: input.source,
      prompt: input.prompt,
      command: input.command,
      before: input.before,
      after: input.after,
      metadata: input.metadata
    });
  }
  async getProjectAgents(id) {
    return listWorkspaceAgents(id);
  }
  async assignAgent(idOrSlug, input) {
    const project = resolveWorkspace(idOrSlug);
    if (!project)
      throw new Error(`Project not found: ${idOrSlug}`);
    const role = input.role ?? "contributor";
    return withLock(project.id, { agentId: input.assignedBy, source: input.source, command: input.command }, "project agent assign", () => {
      const assignment = assignAgentToWorkspace(project.id, input.agentId, role, input.assignedBy, input.metadata);
      recordWorkspaceEvent({
        workspace_id: project.id,
        agent_id: input.assignedBy,
        event_type: "agent_assigned",
        source: input.source ?? "cli",
        command: input.command,
        after: {
          agent_id: input.agentId,
          role: assignment.role,
          assignment_id: assignment.id
        }
      });
      return assignment;
    });
  }
  async getProjectLocations(id) {
    return listWorkspaceLocations(id);
  }
  async listMachines() {
    return listMachines();
  }
  async addLocation(idOrSlug, input) {
    const project = resolveWorkspace(idOrSlug);
    if (!project)
      throw new Error(`Project not found: ${idOrSlug}`);
    return withLock(project.id, { agentId: input.agentId, source: input.source, command: input.command }, "project location add", () => {
      const location = addWorkspaceLocation({
        workspace_id: project.id,
        path: input.path,
        machine_id: input.machineId,
        label: input.label,
        kind: input.kind,
        is_primary: input.isPrimary,
        metadata: input.metadata,
        agent_id: input.agentId,
        source: input.source ?? "cli",
        command: input.command
      });
      const updated = resolveWorkspace(project.id) ?? project;
      return { project: updated, location };
    });
  }
  async listLocks() {
    return listWorkspaceLocks();
  }
  async acquireLock(input) {
    return acquireWorkspaceLock({
      lock_key: input.key,
      workspace_id: input.workspaceId,
      agent_id: input.agentId,
      reason: input.reason,
      ttl_seconds: input.ttlSeconds
    });
  }
  async releaseLock(key, lockId) {
    return releaseWorkspaceLock(key, lockId);
  }
  async forceReleaseLock(key) {
    return forceReleaseWorkspaceLock(key);
  }
  async listRoots() {
    return listRoots();
  }
  async getRoot(idOrSlug) {
    return getRoot(idOrSlug) ?? getRootBySlug(idOrSlug);
  }
  async createRoot(input) {
    return createRoot2(input);
  }
  async updateRoot(idOrSlug, patch) {
    const root = await this.getRoot(idOrSlug);
    if (!root)
      throw new Error(`Root not found: ${idOrSlug}`);
    return updateRoot(root.id, patch);
  }
  async deleteRoot(idOrSlug, opts) {
    const root = await this.getRoot(idOrSlug);
    if (!root)
      throw new Error(`Root not found: ${idOrSlug}`);
    return deleteRoot(root.id, { detachWorkspaces: opts?.detachProjects });
  }
  async matchRoots(input) {
    return scoreRoots(input);
  }
  async listAgents() {
    return listAgents();
  }
  async getAgent(idOrSlug) {
    return getAgent(idOrSlug) ?? getAgentBySlug(idOrSlug);
  }
  async createAgent(input) {
    return createAgent(input);
  }
  async listRecipes() {
    return listRecipes();
  }
  async getRecipe(idOrSlug) {
    return getRecipe(idOrSlug) ?? getRecipeBySlug(idOrSlug);
  }
  async createRecipe(input) {
    return createRecipe(input);
  }
  async listAgentRuns(filter) {
    return listAgentRuns(filter ?? {});
  }
  listDataModels = machineLocalAppStore.listDataModels;
  createDataModel = machineLocalAppStore.createDataModel;
  listDataRecords = machineLocalAppStore.listDataRecords;
  createDataRecord = machineLocalAppStore.createDataRecord;
  listLoopLinks = machineLocalAppStore.listLoopLinks;
  linkLoop = machineLocalAppStore.linkLoop;
  listLoopSummaries = machineLocalAppStore.listLoopSummaries;
  inspectAppStore = machineLocalAppStore.inspectAppStore;
  inspectAppStoreWithLoops = machineLocalAppStore.inspectAppStoreWithLoops;
  async createBudget(input) {
    return createProjectBudget(input);
  }
  async listBudgets(context) {
    return listProjectBudgets(context);
  }
  async getBudgetStatuses(context) {
    return getProjectBudgetStatuses(context);
  }
  async resetBudget(id) {
    return resetProjectBudget(id);
  }
  async recordSpend(input) {
    return recordProjectSpend(input);
  }
  listTmuxProfiles = machineLocalTmuxProfiles.listTmuxProfiles;
  getTmuxProfile = machineLocalTmuxProfiles.getTmuxProfile;
  createTmuxProfile = machineLocalTmuxProfiles.createTmuxProfile;
  addTmuxProfileWindow = machineLocalTmuxProfiles.addTmuxProfileWindow;
  listTmuxProfileWindows = machineLocalTmuxProfiles.listTmuxProfileWindows;
  async ensureChannel(project, options) {
    return ensureProjectChannelViaStore(this, project, options);
  }
}
function buildProjectListPage(projects, filter, total) {
  const offset = filter.offset ?? 0;
  const limit = filter.limit ?? null;
  const has_more = offset + projects.length < total;
  return {
    projects,
    count: projects.length,
    total,
    offset,
    limit,
    has_more,
    complete: offset === 0 && !has_more
  };
}
function listQuery(filter) {
  if (!filter)
    return {};
  return {
    kind: filter.kind,
    status: filter.status,
    query: filter.query,
    query_scope: filter.query_scope,
    root_id: filter.root_id,
    tag: filter.tags && filter.tags.length > 0 ? filter.tags[0] : undefined,
    tags: filter.require_list_v2_contract && filter.tags && filter.tags.length > 1 ? filter.tags.slice(1) : undefined,
    ...filter.exclude_registry_fixtures === false ? { include_fixtures: "true" } : {},
    ...filter.exclude_eval_artifacts === true ? { exclude_evals: "true" } : {},
    limit: filter.limit,
    offset: filter.offset
  };
}
function isHostedRegistryResolvableId(idOrSlug) {
  const target = idOrSlug.trim();
  if (!target)
    return false;
  if (target === "." || target === "..")
    return false;
  if (target.startsWith("~"))
    return false;
  if (target.startsWith("/") || target.startsWith("./") || target.startsWith("../"))
    return false;
  if (target.includes("/") || target.includes("\\"))
    return false;
  if (/^[a-zA-Z]:[\\/]/.test(target))
    return false;
  return true;
}
function canonicalProjectIdFromExistingPath(target) {
  const path = normalizeProjectPath(target);
  if (!isProjectDirectory(path))
    return null;
  const projectId = basename(path);
  if (!PROJECT_WORKSPACE_ID_PATTERN.test(projectId))
    return null;
  return isProjectWorkspaceStorePath(projectId, path) ? projectId : null;
}
function normalizeApiWorkspace(raw) {
  if (!raw || typeof raw !== "object")
    return null;
  const ws = raw;
  if (typeof ws.id !== "string" || typeof ws.slug !== "string")
    return null;
  return {
    ...ws,
    tags: Array.isArray(ws.tags) ? ws.tags : [],
    integrations: ws.integrations ?? {},
    metadata: ws.metadata ?? {}
  };
}
function normalizeApiAgent(raw, requestedIdOrSlug) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
    throw new Error(`Projects agent lookup returned a malformed response for ${requestedIdOrSlug}.`);
  }
  const value = raw;
  const validOptionalNullableString = (candidate) => candidate === undefined || candidate === null || typeof candidate === "string";
  const metadata = value.metadata;
  const permissions = value.permissions;
  if (typeof value.id !== "string" || value.id.trim().length === 0 || typeof value.slug !== "string" || value.slug.trim().length === 0 || typeof value.name !== "string" || value.name.trim().length === 0 || typeof value.kind !== "string" || !AGENT_KINDS.includes(value.kind) || !validOptionalNullableString(value.provider) || !validOptionalNullableString(value.model) || !validOptionalNullableString(value.role) || permissions !== undefined && (!Array.isArray(permissions) || permissions.some((permission) => typeof permission !== "string")) || metadata !== undefined && (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) || value.created_at !== undefined && typeof value.created_at !== "string" || value.updated_at !== undefined && typeof value.updated_at !== "string") {
    throw new Error(`Projects agent lookup returned a malformed response for ${requestedIdOrSlug}.`);
  }
  if (value.id !== requestedIdOrSlug && value.slug !== requestedIdOrSlug) {
    throw new Error(`Projects agent lookup response did not match ${requestedIdOrSlug}.`);
  }
  return {
    ...value,
    provider: value.provider ?? null,
    model: value.model ?? null,
    role: value.role ?? null,
    permissions: permissions ?? [],
    metadata: metadata ?? {},
    created_at: typeof value.created_at === "string" ? value.created_at : "",
    updated_at: typeof value.updated_at === "string" ? value.updated_at : ""
  };
}
function seamErrorReason(error) {
  if (!(error instanceof Error))
    return null;
  const body = error.body;
  if (!body || typeof body !== "object" || Array.isArray(body))
    return null;
  const reason = body.reason;
  return typeof reason === "string" ? reason : null;
}
function registrationManifestRefusal(error) {
  const reason = seamErrorReason(error);
  if (reason === "operation_semantics_conflict" || reason === "manifest_insert_missing") {
    return new ProjectRegistrationStepError("registration_manifest", reason);
  }
  return error;
}

class ApiProjectStore {
  transport = "http";
  baseUrl;
  client;
  constructor(client) {
    this.client = client;
    this.baseUrl = client.baseUrl;
  }
  async fetchProjectPage(filter, params) {
    const raw = await this.client.transport.get("/projects", {
      query: { ...listQuery(filter), limit: params.limit, offset: params.offset }
    });
    const rows = (raw.workspaces ?? raw.projects ?? []).map((row) => normalizeApiWorkspace(row) ?? row);
    if (typeof raw.offset === "number" && raw.offset !== params.offset) {
      throw new PaginationError(`Projects list producer returned offset ${raw.offset} for requested offset ${params.offset}; refusing a mislabeled page.`);
    }
    if (filter?.require_list_v2_contract) {
      const expectedFilters = {
        query_scope: filter.query_scope ?? "legacy",
        tags: [...new Set(filter.tags ?? [])],
        exclude_evals: filter.exclude_eval_artifacts === true,
        exclude_registry_fixtures: filter.exclude_registry_fixtures === true
      };
      if (raw.filter_contract !== PROJECT_LIST_V2_CONTRACT) {
        throw new PaginationError(`Projects list requires the ${PROJECT_LIST_V2_CONTRACT} filter contract; update projects-serve before using compact search.`);
      }
      const applied = raw.applied_filters;
      if (!applied || applied.query_scope !== expectedFilters.query_scope || JSON.stringify(applied.tags ?? []) !== JSON.stringify(expectedFilters.tags) || applied.exclude_evals !== expectedFilters.exclude_evals || applied.exclude_registry_fixtures !== expectedFilters.exclude_registry_fixtures) {
        throw new PaginationError("Projects list producer did not attest the exact query/tag/eval/fixture filters; refusing a mislabeled compact page.");
      }
    }
    return {
      rows,
      total: typeof raw.total === "number" ? raw.total : null,
      offset: typeof raw.offset === "number" ? raw.offset : null,
      limit: typeof raw.limit === "number" ? raw.limit : null,
      has_more: typeof raw.has_more === "boolean" ? raw.has_more : null
    };
  }
  async listProjects(filter) {
    if (filter?.limit === undefined && filter?.offset === undefined) {
      return (await this.listProjectsComplete(filter)).projects;
    }
    return collectPages(async (params) => (await this.fetchProjectPage(filter, params)).rows, (row) => row?.id, {
      ...filter?.limit !== undefined ? { want: filter.limit } : {},
      ...filter?.offset !== undefined ? { offset: filter.offset } : {}
    });
  }
  async listProjectsComplete(filter) {
    const f = filter ?? {};
    const population = await collectCompletePages(async (params) => {
      const page = await this.fetchProjectPage(f, params);
      if (page.total === null || page.offset === null || page.limit === null || page.has_more === null) {
        throw new Error("Projects producer did not return the complete population contract (total/offset/limit/has_more).");
      }
      return {
        rows: page.rows,
        total: page.total,
        offset: page.offset,
        limit: page.limit,
        has_more: page.has_more
      };
    }, (row) => row?.id);
    return { projects: population.rows, total: population.total, pages: population.pages, complete: true };
  }
  async listProjectsPage(filter) {
    const f = filter ?? {};
    if (f.limit === undefined && f.offset === undefined) {
      const population = await this.listProjectsComplete(f);
      return buildProjectListPage(population.projects, f, population.total);
    }
    let serverTotal = null;
    const projects = await collectPages(async (params) => {
      const page = await this.fetchProjectPage(f, params);
      if (page.total !== null) {
        if (serverTotal !== null && page.total !== serverTotal) {
          throw new PaginationError(`Projects list producer total changed during bounded traversal (${serverTotal} -> ${page.total}); refusing a moving population.`);
        }
        serverTotal = page.total;
      }
      return page.rows;
    }, (row) => row?.id, {
      ...f.limit !== undefined ? { want: f.limit } : {},
      ...f.offset !== undefined ? { offset: f.offset } : {}
    });
    const total = serverTotal ?? await this.probeTotal(f, projects.length);
    return buildProjectListPage(projects, f, total);
  }
  async probeTotal(filter, returned) {
    const offset = filter.offset ?? 0;
    if (filter.limit === undefined)
      return offset + returned;
    const rest = await collectPages(async (params) => (await this.fetchProjectPage(filter, params)).rows, (row) => row?.id, { offset: offset + returned });
    return offset + returned + rest.length;
  }
  async getProject(idOrSlug) {
    if (!isHostedRegistryResolvableId(idOrSlug))
      return null;
    return normalizeApiWorkspace(await this.client.get(RESOURCE, idOrSlug));
  }
  async resolveTarget(target, options) {
    const idOrSlug = target?.trim();
    if (!idOrSlug)
      throw new Error("Project not found: (no target provided)");
    const canonicalProjectId = options?.allowPath === false ? null : canonicalProjectIdFromExistingPath(idOrSlug);
    if (canonicalProjectId) {
      const project2 = await this.getProject(canonicalProjectId);
      if (project2?.id === canonicalProjectId && isProjectWorkspaceStorePath(canonicalProjectId, project2.primary_path)) {
        return project2;
      }
      throw new Error(`Project not found: ${idOrSlug}`);
    }
    const project = await this.getProject(idOrSlug);
    if (!project)
      throw new Error(`Project not found: ${idOrSlug}`);
    return project;
  }
  async createProject(input) {
    const metadata = normalizeProjectMetadata(input.metadata);
    const created = await this.client.create(RESOURCE, {
      ...input,
      metadata: Object.keys(metadata).length > 0 ? metadata : undefined
    });
    return normalizeApiWorkspace(created) ?? created;
  }
  async updateProject(id, patch) {
    const updated = await this.client.update(RESOURCE, id, {
      ...patch,
      ...patch.metadata !== undefined ? { metadata: normalizeProjectMetadata(patch.metadata) } : {}
    });
    return normalizeApiWorkspace(updated) ?? updated;
  }
  async guardedReadProject(input) {
    assertCompleteStableProjectId(input.project_id);
    assertPositiveBounds(input);
    return this.client.transport.get(`/projects/${encodeURIComponent(input.project_id)}/guarded-metadata`, {
      query: {
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms,
        resource_link_max_items: input.resource_link_max_items
      },
      timeoutMs: input.time_budget_ms
    });
  }
  async readProjectResourceLinks(input) {
    const result = await this.client.transport.get(`/projects/${encodeURIComponent(input.project_id)}/resource-links`, {
      query: {
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      },
      timeoutMs: input.time_budget_ms
    });
    assertProjectResourceLinkReadContractEquality(result);
    return result;
  }
  async mutateProjectResourceLinks(input) {
    const normalized = normalizeProjectResourceLinks(input.links);
    assertProjectResourceLinksWritable(normalized);
    const integrations = normalizeProjectResourceLinkIntegrations(input.integrations);
    const requestHash = sha256(canonicalJson({
      mode: input.mode,
      links: normalized,
      integrations: integrations ?? null
    }));
    const preconditionHash = preconditionDigest({
      project_id: input.project_id,
      expected_revision: input.expected_revision
    });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id,
      request_digest: requestHash,
      precondition_digest: preconditionHash
    });
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/resource-links/${input.mode}`, input, {
      idempotencyKey,
      timeoutMs: input.time_budget_ms
    });
  }
  async rollbackProjectResourceLinks(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/resource-links/rollback`, input, { timeoutMs: input.time_budget_ms });
  }
  async readProjectRelations(input) {
    return this.client.transport.get(`/projects/${encodeURIComponent(input.project_id)}/relations`, {
      query: {
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      },
      timeoutMs: input.time_budget_ms
    });
  }
  async mutateProjectRelation(input) {
    const toProjectId = assertProjectRelationEndpointId(input.to_project_id, "to_project_id");
    const relation = normalizeProjectRelationKind(input.relation);
    assertProjectRelationNotSelf(input.project_id, toProjectId);
    const requestHash = sha256(canonicalJson({
      mode: input.mode,
      relation,
      from_project_id: input.project_id,
      to_project_id: toProjectId
    }));
    const preconditionHash = preconditionDigest({
      project_id: input.project_id,
      expected_revision: input.expected_revision
    });
    const idempotencyKey = deriveGuardedIdempotencyKey({
      operation_id: input.operation_id,
      step_id: input.step_id,
      direction: "forward",
      target_id: input.project_id,
      request_digest: requestHash,
      precondition_digest: preconditionHash
    });
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/relations/${input.mode}`, input, {
      idempotencyKey,
      timeoutMs: input.time_budget_ms
    });
  }
  async createProjectRegistrationManifest(input) {
    try {
      return await this.client.transport.post("/project-registration/manifests", input);
    } catch (error) {
      throw registrationManifestRefusal(error);
    }
  }
  async readProjectRegistrationManifest(operationId) {
    const result = await this.client.transport.get(`/project-registration/manifests/${encodeURIComponent(operationId)}`);
    return result.manifest ?? null;
  }
  async appendProjectRegistrationReceipt(input) {
    const result = await this.client.transport.post("/project-registration/receipts", input);
    return result.receipt;
  }
  async lookupProjectRegistrationReceipt(input) {
    return this.client.transport.get("/project-registration/receipts", {
      query: {
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: input.direction,
        idempotency_key: input.idempotency_key,
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      },
      timeoutMs: input.time_budget_ms
    });
  }
  async listProjectRegistrationReceipts(operationId) {
    const result = await this.client.transport.get(`/project-registration/operations/${encodeURIComponent(operationId)}/receipts`);
    return result.receipts;
  }
  async findProjectRegistrationReceipts(input) {
    const result = await this.client.transport.get(`/project-registration/operations/${encodeURIComponent(input.operation_id)}/receipts`, {
      query: {
        step_id: input.step_id,
        direction: input.direction,
        outcome: "accepted",
        limit: input.limit
      }
    });
    return result.receipts;
  }
  async readDuplicateProjectQuarantinePreimage(input) {
    return this.client.transport.get(`/projects/${encodeURIComponent(input.project_id)}/duplicate-quarantine`, {
      query: {
        resource_link_max_items: input.resource_link_max_items,
        workspace_location_max_items: input.workspace_location_max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      },
      timeoutMs: input.time_budget_ms
    });
  }
  async quarantineDuplicateProject(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/duplicate-quarantine`, input, { timeoutMs: input.time_budget_ms });
  }
  async rollbackDuplicateProjectQuarantine(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/duplicate-quarantine/rollback`, input, { timeoutMs: input.time_budget_ms });
  }
  async planProjectResourceLinkMigration(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/resource-link-migrations/plan`, input, { timeoutMs: input.time_budget_ms });
  }
  async readProjectResourceLinkMigration(input) {
    return this.client.transport.get(`/projects/${encodeURIComponent(input.project_id)}/resource-link-migrations/${encodeURIComponent(input.manifest_id)}`, {
      query: {
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      },
      timeoutMs: input.time_budget_ms
    });
  }
  async advanceProjectResourceLinkMigration(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/resource-link-migrations/${encodeURIComponent(input.manifest_id)}/advance`, input, { timeoutMs: input.time_budget_ms });
  }
  async rollbackProjectResourceLinkMigration(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/resource-link-migrations/${encodeURIComponent(input.manifest_id)}/rollback`, input, { timeoutMs: input.time_budget_ms });
  }
  async guardedUpdateProject(input) {
    const res = await this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/guarded-metadata`, input, { timeoutMs: input.time_budget_ms });
    return res;
  }
  async lookupGuardedProjectMutationReceipt(input) {
    return this.client.transport.get(`/projects/${encodeURIComponent(input.project_id)}/guarded-metadata/receipts`, {
      query: {
        operation_id: input.operation_id,
        step_id: input.step_id,
        direction: input.direction,
        idempotency_key: input.idempotency_key,
        max_items: input.max_items,
        response_byte_limit: input.response_byte_limit,
        time_budget_ms: input.time_budget_ms
      },
      timeoutMs: input.time_budget_ms
    });
  }
  async rollbackGuardedProjectMutation(input) {
    return this.client.transport.post(`/projects/${encodeURIComponent(input.project_id)}/guarded-metadata/rollback`, input, { timeoutMs: input.time_budget_ms });
  }
  async archiveProject(id) {
    const ws = await this.client.transport.post(`/projects/${encodeURIComponent(id)}/archive`);
    return normalizeApiWorkspace(ws) ?? ws;
  }
  async unarchiveProject(id) {
    const ws = await this.client.transport.post(`/projects/${encodeURIComponent(id)}/unarchive`);
    return normalizeApiWorkspace(ws) ?? ws;
  }
  async deleteProject(id, opts) {
    const q = opts.hard ? "?hard=true" : "";
    const res = await this.client.transport.del(`/projects/${encodeURIComponent(id)}${q}`);
    const workspace = normalizeApiWorkspace(res?.workspace ?? res?.project);
    return { workspace, hard: Boolean(res?.hard), id: res?.id ?? workspace?.id ?? id };
  }
  async listEvents(idOrSlug, limit) {
    const raw = await this.client.transport.get(`/projects/${encodeURIComponent(idOrSlug)}/events`, { query: limit ? { limit } : {} });
    return raw.events ?? [];
  }
  async recordEvent(idOrSlug, input) {
    const raw = await this.client.transport.post(`/projects/${encodeURIComponent(idOrSlug)}/events`, {
      event_type: input.event_type,
      source: input.source,
      agent_id: input.agentId,
      prompt: input.prompt,
      command: input.command,
      before: input.before,
      after: input.after,
      metadata: input.metadata
    });
    return raw.event ?? raw;
  }
  async getProjectAgents(id) {
    const raw = await this.client.transport.get(`/projects/${encodeURIComponent(id)}/agents`);
    return raw.assignments ?? [];
  }
  async assignAgent(idOrSlug, input) {
    const raw = await this.client.transport.post(`/projects/${encodeURIComponent(idOrSlug)}/agents`, {
      agent_id: input.agentId,
      role: input.role,
      assigned_by: input.assignedBy,
      metadata: input.metadata
    });
    const assignment = raw.assignment ?? raw;
    if (!assignment)
      throw new Error(`Agent assignment was not recorded for ${idOrSlug}`);
    return assignment;
  }
  async getProjectLocations(id) {
    const raw = await this.client.transport.get(`/projects/${encodeURIComponent(id)}/locations`);
    return raw.locations ?? [];
  }
  async listMachines() {
    const raw = await this.client.transport.get("/machines");
    return raw.machines ?? [];
  }
  async addLocation(idOrSlug, input) {
    const raw = await this.client.transport.post(`/projects/${encodeURIComponent(idOrSlug)}/locations`, {
      path: input.path,
      machine_id: input.machineId,
      label: input.label,
      kind: input.kind,
      is_primary: input.isPrimary,
      metadata: input.metadata
    });
    const location = raw.location ?? raw.location;
    const project = raw.project ?? raw.project;
    if (!location || !project)
      throw new Error(`Project location was not recorded for ${idOrSlug}`);
    return { project, location };
  }
  async listLocks() {
    const raw = await this.client.transport.get("/locks");
    return raw.locks ?? [];
  }
  async acquireLock(input) {
    const raw = await this.client.transport.post("/locks", {
      lock_key: input.key,
      workspace_id: input.workspaceId,
      agent_id: input.agentId,
      reason: input.reason,
      ttl_seconds: input.ttlSeconds
    });
    const lock = raw.lock ?? raw;
    if (!lock)
      throw new Error(`Project lock was not acquired: ${input.key}`);
    return lock;
  }
  async releaseLock(key, lockId) {
    const raw = await this.client.transport.del(`/locks/${encodeURIComponent(key)}`, undefined, { query: { lock_id: lockId } });
    return Boolean(raw?.released);
  }
  async forceReleaseLock(key) {
    const raw = await this.client.transport.del(`/locks/${encodeURIComponent(key)}`);
    return Boolean(raw?.released);
  }
  async listRoots() {
    const raw = await this.client.transport.get("/roots");
    return raw.roots ?? [];
  }
  async getRoot(idOrSlug) {
    return this.client.get("roots", idOrSlug);
  }
  async createRoot(input) {
    return this.client.create("roots", input);
  }
  async updateRoot(idOrSlug, patch) {
    return this.client.update("roots", idOrSlug, patch);
  }
  async deleteRoot(idOrSlug, opts) {
    const root = await this.getRoot(idOrSlug);
    if (!root)
      throw new Error(`Root not found: ${idOrSlug}`);
    const q = opts?.detachProjects ? "?detach=true" : "";
    const res = await this.client.transport.del(`/roots/${encodeURIComponent(root.id)}${q}`);
    return { root, detached_workspaces: res?.detached_workspaces ?? 0 };
  }
  async matchRoots(input) {
    return rankRoots(await this.listRoots(), input);
  }
  async listAgents() {
    const raw = await this.client.transport.get("/agents");
    return raw.agents ?? [];
  }
  async getAgent(idOrSlug) {
    const raw = await this.client.get("agents", idOrSlug);
    return raw === null ? null : normalizeApiAgent(raw, idOrSlug);
  }
  async createAgent(input) {
    return this.client.create("agents", input);
  }
  async listRecipes() {
    const raw = await this.client.transport.get("/recipes");
    return raw.recipes ?? [];
  }
  async getRecipe(idOrSlug) {
    return this.client.get("recipes", idOrSlug);
  }
  async createRecipe(input) {
    return this.client.create("recipes", input);
  }
  async listAgentRuns() {
    return [];
  }
  async listDataModels() {
    throw new LocalOnlyOperationError("list project data models");
  }
  async createDataModel() {
    throw new LocalOnlyOperationError("create project data model");
  }
  async listDataRecords() {
    throw new LocalOnlyOperationError("list project data records");
  }
  async createDataRecord() {
    throw new LocalOnlyOperationError("create project data record");
  }
  async listLoopLinks() {
    throw new LocalOnlyOperationError("list project loop links");
  }
  async linkLoop() {
    throw new LocalOnlyOperationError("link a loop to a project");
  }
  async listLoopSummaries() {
    throw new LocalOnlyOperationError("list project loop summaries");
  }
  async inspectAppStore() {
    throw new LocalOnlyOperationError("inspect the project app store");
  }
  async inspectAppStoreWithLoops() {
    throw new LocalOnlyOperationError("inspect the project app store");
  }
  async createBudget() {
    throw new LocalOnlyOperationError("create project budget");
  }
  async listBudgets() {
    throw new LocalOnlyOperationError("list project budgets");
  }
  async getBudgetStatuses() {
    throw new LocalOnlyOperationError("read project budget statuses");
  }
  async resetBudget() {
    throw new LocalOnlyOperationError("reset project budget");
  }
  async recordSpend() {
    throw new LocalOnlyOperationError("record project spend");
  }
  async listTmuxProfiles() {
    throw new LocalOnlyOperationError("list tmux profiles");
  }
  async getTmuxProfile() {
    throw new LocalOnlyOperationError("read a tmux profile");
  }
  async createTmuxProfile() {
    throw new LocalOnlyOperationError("create a tmux profile");
  }
  async addTmuxProfileWindow() {
    throw new LocalOnlyOperationError("add a tmux profile window");
  }
  async listTmuxProfileWindows() {
    throw new LocalOnlyOperationError("list tmux profile windows");
  }
  async ensureChannel(project, options) {
    return ensureProjectChannelViaStore(this, project, options);
  }
}
function enrichSeamTransport(transport) {
  const withDetail = (error) => {
    if (!(error instanceof Error) || error.name !== "HasnaHttpError")
      return error;
    const body = error.body;
    const detail = body !== null && typeof body === "object" && !Array.isArray(body) ? body.error : undefined;
    if (typeof detail !== "string" || detail.length === 0 || error.message.includes(detail)) {
      return error;
    }
    const bounded = detail.length <= 500 ? detail : `${detail.slice(0, 497)}...`;
    return Object.assign(new Error(`${error.message}: ${bounded}`), {
      name: error.name,
      status: error.status,
      method: error.method,
      path: error.path,
      body
    });
  };
  const guard = (promise) => promise.catch((error) => {
    throw withDetail(error);
  });
  return {
    ...transport,
    request: (method, path, body, opts) => guard(transport.request(method, path, body, opts)),
    get: (path, opts) => guard(transport.get(path, opts)),
    post: (path, body, opts) => guard(transport.post(path, body, opts)),
    put: (path, body, opts) => guard(transport.put(path, body, opts)),
    patch: (path, body, opts) => guard(transport.patch(path, body, opts)),
    del: (path, body, opts) => guard(transport.del(path, body, opts))
  };
}
function announceLocalMode(env2, notify) {
  if (announcedLocalMode)
    return;
  announcedLocalMode = true;
  const keys = clientTransportEnvKeys2(APP);
  const diskPaths = credentialDiskSources(APP, env2);
  const disk = diskPaths.length > 0 ? diskPaths.join(" or ") : "no credentials file (no HOME)";
  notify(`projects: local mode \u2014 HASNA_PROJECTS_LOCAL is set, so this run reads and writes the on-box ` + `SQLite registry at ${getDbPath()} instead of the hosted fleet. Unset it and provide a ` + `credential (${keys.apiKeyKeys[0]}, the Keychain item hasna.credentials.${APP}.api-key, or ${disk}) to run hosted.`);
}
function resolveProjectStore(env2 = process.env, fetchImpl, options = {}) {
  const cacheable = env2 === process.env && options.producerAuthorityOptions === undefined && options.producerVerifierNow === undefined && options.credentials === undefined && options.notify === undefined;
  if (cacheable && cached)
    return cached;
  if (selectsProjectsLocalStore(env2)) {
    const localStore = new LocalProjectStore(createProductionProjectResourceLinkProducerEvidenceVerifier({
      authorities: productionProjectRegistrationAuthorities({
        ...options.producerAuthorityOptions,
        env: options.producerAuthorityOptions?.env ?? env2,
        fetch: options.producerAuthorityOptions?.fetch ?? fetchImpl
      }),
      now: options.producerVerifierNow
    }));
    if (cacheable)
      cached = localStore;
    announceLocalMode(env2, options.notify ?? ((line) => console.error(line)));
    return localStore;
  }
  const resolved = resolveStorageClient(APP, env2, {
    fetchImpl,
    ...options.credentials ? { credentials: options.credentials } : {}
  });
  const httpStore = new ApiProjectStore(createHasnaStorageClient(resolved.client.name, enrichSeamTransport(resolved.client.transport)));
  if (env2 === process.env) {
    refuseLocalStore(hostedLocalStoreRefusal(env2, resolved.client.baseUrl));
  }
  if (cacheable)
    cached = httpStore;
  return httpStore;
}
function hostedLocalStoreRefusal(env2, authority) {
  const keys = clientTransportEnvKeys2(APP);
  const diskPaths = credentialDiskSources(APP, env2);
  const disk = diskPaths.length > 0 ? diskPaths.join(" or ") : "the credentials file";
  return `REMOTE_COMMAND_UNSUPPORTED: projects refuses to open the on-box SQLite store because this run resolved a ` + `hosted Projects authority (${authority}) from ${keys.apiKeyKeys[0]}, the Keychain item ` + `hasna.credentials.${APP}.api-key or ${disk}. This command (or part of it) is local-only and has no hosted ` + `/v1 route. To use the machine-local store deliberately, run with ${PROJECTS_LOCAL_OPT_IN_ENV_KEYS[0]}=1 ` + `(alias ${PROJECTS_LOCAL_OPT_IN_ENV_KEYS[1]}=1) and no Projects credential in the environment.`;
}
var APP = "projects", RESOURCE = "projects", LocalOnlyOperationError, machineLocalAppStore, machineLocalTmuxProfiles, cached = null, announcedLocalMode = false;
var init_project_store2 = __esm(() => {
  init_workspaces();
  init_local_opt_in();
  init_database();
  init_project_resolver();
  init_project_store_paths();
  init_paginate();
  init_project_store();
  init_budget();
  init_project_channel();
  init_guarded_project_mutation();
  init_project_resource_links();
  init_project_relations();
  init_project_relations2();
  init_project_resource_link_migrations();
  init_project_resource_link_producer_verifier();
  init_production_project_registration_authorities();
  init_project_management();
  init_project_list_output();
  init_project_registration();
  init_workspace();
  LocalOnlyOperationError = class LocalOnlyOperationError extends Error {
    code = "REMOTE_COMMAND_UNSUPPORTED";
    constructor(operation) {
      super(`REMOTE_COMMAND_UNSUPPORTED: ${operation} is a local-only operation and is not available in the hosted backend. ` + "It reads or writes the on-box SQLite store, which this run refuses because a hosted Projects authority " + "is configured, and hosted Projects models no /v1 route for it. To use the machine-local store deliberately, " + `run with ${PROJECTS_LOCAL_OPT_IN_ENV_KEYS[0]}=1 (alias ${PROJECTS_LOCAL_OPT_IN_ENV_KEYS[1]}=1) and no Projects ` + "credential in the environment.");
      this.name = "LocalOnlyOperationError";
    }
  };
  machineLocalAppStore = {
    listDataModels: async (project) => listProjectDataModels(project),
    createDataModel: async (project, input, ctx) => withLock(project.id, ctx, "project data model create", () => createProjectDataModel(project, input)),
    listDataRecords: async (project, modelId) => listProjectDataRecords(project, modelId),
    createDataRecord: async (project, input, ctx) => withLock(project.id, ctx, "project data record create", () => createProjectDataRecord(project, input)),
    listLoopLinks: async (project) => listProjectLoopLinks(project),
    linkLoop: async (project, input, ctx) => withLock(project.id, ctx, "project OpenLoops link", () => linkProjectLoop(project, input)),
    listLoopSummaries: async (project, options) => listProjectLoopSummaries(project, options),
    inspectAppStore: async (project) => inspectProjectStore(project),
    inspectAppStoreWithLoops: async (project, options) => inspectProjectStoreWithLoops(project, options)
  };
  machineLocalTmuxProfiles = {
    listTmuxProfiles: async () => listTmuxProfiles(),
    getTmuxProfile: async (idOrSlug) => resolveTmuxProfile(idOrSlug),
    createTmuxProfile: async (input) => createTmuxProfile(input),
    addTmuxProfileWindow: async (input) => addTmuxProfileWindow(input),
    listTmuxProfileWindows: async (profileId) => listTmuxProfileWindows(profileId)
  };
});

// src/cli/tui/data.ts
function resolveStore() {
  try {
    return resolveProjectStore();
  } catch (err) {
    const detail = err instanceof Error ? err.message : String(err);
    throw new Error("Projects TUI cannot reach a projects registry: nothing is configured. " + "Configure hosted credentials (HASNA_PROJECTS_API_KEY, the macOS Keychain item " + "hasna.credentials.projects.api-key, or ~/.hasna/projects/config/credentials), " + `or opt in to the on-box registry with HASNA_PROJECTS_LOCAL=1.

` + detail);
  }
}
function store() {
  return resolveStore();
}
function transport() {
  return store().transport;
}
function authority() {
  const baseUrl = store().baseUrl;
  if (!baseUrl)
    return null;
  try {
    return new URL(baseUrl).host;
  } catch {
    return baseUrl.replace(/^[a-z][a-z\d+\-.]*:\/\//i, "").split("/")[0] || null;
  }
}
function toWorkspaceFilter(filter) {
  return {
    status: filter?.status,
    kind: filter?.kind,
    query: filter?.query,
    tags: filter?.tags,
    limit: filter?.limit,
    exclude_eval_artifacts: true,
    exclude_registry_fixtures: true
  };
}
async function listProjects(filter) {
  return store().listProjects(toWorkspaceFilter(filter));
}
async function getProject(idOrSlug) {
  const project = await store().getProject(idOrSlug);
  if (!project)
    throw new Error(`Project not found: ${idOrSlug}`);
  return project;
}
async function createProject(input) {
  return store().createProject(input);
}
async function updateProject(id, patch) {
  return store().updateProject(id, patch);
}
async function archiveProject(id) {
  return store().archiveProject(id);
}
async function unarchiveProject(id) {
  return store().unarchiveProject(id);
}
async function deleteProject(id, hard) {
  const result = await store().deleteProject(id, { hard });
  return { deleted: true, hard: result.hard, id: result.id };
}
async function listRoots2() {
  return store().listRoots();
}
async function listRecipes2() {
  return store().listRecipes();
}
async function listAgents2() {
  return store().listAgents();
}
async function listProjectEvents(idOrSlug, limit) {
  return store().listEvents(idOrSlug, limit);
}
async function listProjectLocations(idOrSlug) {
  return store().getProjectLocations(idOrSlug);
}
async function listProjectAgents(idOrSlug) {
  return store().getProjectAgents(idOrSlug);
}
function healthFromPathStatus(status) {
  switch (status) {
    case "ok":
      return "ok";
    case "missing":
      return "missing";
    case "remote-only":
      return "untracked";
    default:
      return "unknown";
  }
}
function managementView(project) {
  const management = projectManagementSummary(project);
  const dashboard = projectDashboardSummary(project);
  return {
    stage: management.stage ?? undefined,
    priority: management.priority ?? undefined,
    owner: management.owner ?? undefined,
    health: healthFromPathStatus(dashboard.path_health.status),
    lastOpenedAt: dashboard.launch.last_opened_at
  };
}
var init_data = __esm(() => {
  init_project_store2();
  init_project_management();
});

// src/cli/tui-solid/context/projects-state.tsx
function errorMessage(error) {
  if (error instanceof Error)
    return error.message;
  return String(error);
}
function createProjectsStore() {
  const [state, setState] = createStore({
    route: {
      name: "projects"
    },
    projects: [],
    loading: false,
    error: null,
    filter: {
      status: "all",
      kind: "all",
      query: ""
    },
    selected: null,
    selectedLoading: false,
    events: [],
    locations: [],
    assignments: [],
    roots: [],
    recipes: [],
    agents: [],
    transport: null,
    authority: null,
    dialog: null,
    mutating: false
  });
  const dataFilter = () => ({
    status: state.filter.status === "all" ? undefined : state.filter.status,
    kind: state.filter.kind === "all" ? undefined : state.filter.kind,
    query: state.filter.query.trim() || undefined
  });
  const loadSelected = async (idOrSlug) => {
    setState("selectedLoading", true);
    try {
      const [project, events, locations, assignments] = await Promise.all([getProject(idOrSlug), listProjectEvents(idOrSlug, SELECTED_EVENT_LIMIT), listProjectLocations(idOrSlug), listProjectAgents(idOrSlug)]);
      setState({
        selected: project,
        events,
        locations,
        assignments,
        error: null
      });
    } catch (error) {
      setState("error", errorMessage(error));
    } finally {
      setState("selectedLoading", false);
    }
  };
  const refreshIfOpen = (idOrSlug) => {
    if (state.route.name !== "project")
      return;
    if (state.selected?.id === idOrSlug || state.route.projectId === idOrSlug) {
      loadSelected(idOrSlug);
    }
  };
  const actions = {
    async load() {
      setState("loading", true);
      setState("error", null);
      let resolvedTransport;
      try {
        resolvedTransport = transport();
      } catch (error) {
        setState("error", errorMessage(error));
        setState("loading", false);
        return;
      }
      try {
        setState("transport", resolvedTransport);
        setState("authority", authority());
        const [projects, roots, recipes, agents] = await Promise.all([listProjects(dataFilter()), listRoots2(), listRecipes2(), listAgents2()]);
        setState({
          projects,
          roots,
          recipes,
          agents,
          error: null
        });
      } catch (error) {
        setState("error", errorMessage(error));
      } finally {
        setState("loading", false);
      }
    },
    async reloadProjects() {
      setState("loading", true);
      try {
        const projects = await listProjects(dataFilter());
        setState({
          projects,
          error: null
        });
      } catch (error) {
        setState("error", errorMessage(error));
      } finally {
        setState("loading", false);
      }
    },
    setFilter(partial) {
      setState("filter", {
        ...state.filter,
        ...partial
      });
      actions.reloadProjects();
    },
    async navigate(route) {
      setState("route", route);
    },
    async openProject(idOrSlug) {
      setState("route", {
        name: "project",
        projectId: idOrSlug
      });
      await loadSelected(idOrSlug);
    },
    async refreshSelected() {
      if (state.route.name !== "project")
        return;
      await loadSelected(state.route.projectId);
    },
    openDialog(dialog) {
      setState("dialog", dialog);
    },
    closeDialog() {
      setState("dialog", null);
    },
    async createProject(input) {
      setState("mutating", true);
      try {
        const created = await createProject(input);
        setState("error", null);
        await actions.reloadProjects();
        return created;
      } catch (error) {
        setState("error", errorMessage(error));
        return null;
      } finally {
        setState("mutating", false);
      }
    },
    async updateProject(id, patch) {
      setState("mutating", true);
      try {
        const updated = await updateProject(id, patch);
        setState("error", null);
        await actions.reloadProjects();
        refreshIfOpen(id);
        return updated;
      } catch (error) {
        setState("error", errorMessage(error));
        return null;
      } finally {
        setState("mutating", false);
      }
    },
    async archiveProject(id) {
      setState("mutating", true);
      try {
        await archiveProject(id);
        setState("error", null);
        await actions.reloadProjects();
        refreshIfOpen(id);
        return true;
      } catch (error) {
        setState("error", errorMessage(error));
        return false;
      } finally {
        setState("mutating", false);
      }
    },
    async unarchiveProject(id) {
      setState("mutating", true);
      try {
        await unarchiveProject(id);
        setState("error", null);
        await actions.reloadProjects();
        refreshIfOpen(id);
        return true;
      } catch (error) {
        setState("error", errorMessage(error));
        return false;
      } finally {
        setState("mutating", false);
      }
    },
    async deleteProject(id, hard) {
      setState("mutating", true);
      try {
        const result = await deleteProject(id, hard);
        setState("error", null);
        if (state.route.name === "project" && (state.selected?.id === id || state.route.projectId === id)) {
          setState({
            selected: null,
            events: [],
            locations: [],
            assignments: [],
            route: {
              name: "projects"
            }
          });
        }
        await actions.reloadProjects();
        return result.deleted;
      } catch (error) {
        setState("error", errorMessage(error));
        return false;
      } finally {
        setState("mutating", false);
      }
    }
  };
  return {
    state,
    actions
  };
}
function ProjectsProvider(props) {
  const store2 = createProjectsStore();
  return createComponent2(ProjectsContext.Provider, {
    value: store2,
    get children() {
      return props.children;
    }
  });
}
function useProjects() {
  const store2 = useContext(ProjectsContext);
  if (!store2)
    throw new Error("useProjects must be used within ProjectsProvider");
  return store2;
}
var SELECTED_EVENT_LIMIT = 25, ProjectsContext;
var init_projects_state = __esm(() => {
  init_index_bun();
  init_server();
  init_server2();
  init_data();
  ProjectsContext = createContext();
});

// src/cli/tui-solid/ui/border.tsx
var EmptyBorder, SplitBorder;
var init_border = __esm(() => {
  EmptyBorder = {
    topLeft: "",
    bottomLeft: "",
    vertical: "",
    topRight: "",
    bottomRight: "",
    horizontal: " ",
    bottomT: "",
    topT: "",
    cross: "",
    leftT: "",
    rightT: ""
  };
  SplitBorder = {
    border: ["left", "right"],
    customBorderChars: {
      ...EmptyBorder,
      vertical: "\u2503"
    }
  };
});

// src/cli/tui-solid/context/toast.tsx
import { TextAttributes as TextAttributes2 } from "@opentui/core";
function createToastStore() {
  const [state, setState] = createStore({
    current: null
  });
  let timer = null;
  const clear = () => {
    if (timer)
      clearTimeout(timer);
    timer = null;
    setState("current", null);
  };
  onCleanup(clear);
  return {
    get current() {
      return state.current;
    },
    show(input) {
      if (timer)
        clearTimeout(timer);
      setState("current", {
        ...input,
        id: Date.now(),
        tone: input.tone ?? "info"
      });
      timer = setTimeout(clear, input.duration ?? 5200);
      timer.unref?.();
    },
    clear
  };
}
function ToastProvider(props) {
  const toast = createToastStore();
  return createComponent2(ToastContext.Provider, {
    value: toast,
    get children() {
      return props.children;
    }
  });
}
function useToast() {
  const toast = useContext(ToastContext);
  if (!toast)
    throw new Error("useToast must be used within ToastProvider");
  return toast;
}
function ToastViewport() {
  const toast = useToast();
  const theme = useTheme();
  const dimensions = useTerminalDimensions();
  const toneColor = () => {
    const current = toast.current;
    if (!current)
      return theme.info;
    if (current.tone === "success")
      return theme.success;
    if (current.tone === "warning")
      return theme.warning;
    if (current.tone === "error")
      return theme.error;
    return theme.info;
  };
  return createComponent2(Show, {
    get when() {
      return toast.current;
    },
    children: (current) => (() => {
      var _el$ = createElement("box"), _el$2 = createElement("text");
      insertNode(_el$, _el$2);
      setProp(_el$, "position", "absolute");
      setProp(_el$, "top", 1);
      setProp(_el$, "right", 2);
      setProp(_el$, "zIndex", 4000);
      setProp(_el$, "paddingLeft", 2);
      setProp(_el$, "paddingRight", 2);
      setProp(_el$, "paddingTop", 1);
      setProp(_el$, "paddingBottom", 1);
      setProp(_el$, "flexDirection", "column");
      setProp(_el$, "rowGap", 1);
      insert(_el$, (() => {
        var _c$ = memo2(() => !!current().title);
        return () => _c$() ? (() => {
          var _el$3 = createElement("text");
          insert(_el$3, () => current().title);
          effect((_p$) => {
            var _v$7 = theme.text, _v$8 = TextAttributes2.BOLD;
            _v$7 !== _p$.e && (_p$.e = setProp(_el$3, "fg", _v$7, _p$.e));
            _v$8 !== _p$.t && (_p$.t = setProp(_el$3, "attributes", _v$8, _p$.t));
            return _p$;
          }, {
            e: undefined,
            t: undefined
          });
          return _el$3;
        })() : null;
      })(), _el$2);
      setProp(_el$2, "wrapMode", "word");
      setProp(_el$2, "width", "100%");
      insert(_el$2, () => current().message);
      effect((_p$) => {
        var _v$ = Math.min(60, Math.max(20, dimensions().width - 6)), _v$2 = theme.backgroundMenu, _v$3 = toneColor(), _v$4 = SplitBorder.border, _v$5 = SplitBorder.customBorderChars, _v$6 = theme.text;
        _v$ !== _p$.e && (_p$.e = setProp(_el$, "width", _v$, _p$.e));
        _v$2 !== _p$.t && (_p$.t = setProp(_el$, "backgroundColor", _v$2, _p$.t));
        _v$3 !== _p$.a && (_p$.a = setProp(_el$, "borderColor", _v$3, _p$.a));
        _v$4 !== _p$.o && (_p$.o = setProp(_el$, "border", _v$4, _p$.o));
        _v$5 !== _p$.i && (_p$.i = setProp(_el$, "customBorderChars", _v$5, _p$.i));
        _v$6 !== _p$.n && (_p$.n = setProp(_el$2, "fg", _v$6, _p$.n));
        return _p$;
      }, {
        e: undefined,
        t: undefined,
        a: undefined,
        o: undefined,
        i: undefined,
        n: undefined
      });
      return _el$;
    })()
  });
}
var ToastContext;
var init_toast = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_server2();
  init_index_bun();
  init_theme2();
  init_border();
  ToastContext = createContext();
});

// src/cli/tui-solid/context/keymap.tsx
function useStaticBindings(createLayer) {
  const keymap = useKeymap();
  let dispose2;
  onMount(() => {
    const layer = createLayer();
    dispose2 = keymap.registerLayer({
      ...layer,
      bindings: layer.bindings?.map((binding) => ({
        ...binding,
        preventDefault: false
      }))
    });
  });
  onCleanup(() => dispose2?.());
}
var init_keymap = __esm(() => {
  init_server();
  init_solid();
});

// src/cli/tui-solid/context/dialog.tsx
import { RGBA } from "@opentui/core";
function createDialogStore() {
  const [stack, setStack] = createSignal([]);
  let nextId = 1;
  return {
    stack,
    get current() {
      return stack().at(-1) ?? null;
    },
    push(element, options) {
      setStack((items) => [...items, {
        id: nextId++,
        element,
        size: options?.size ?? "medium",
        onClose: options?.onClose
      }]);
    },
    replace(element, options) {
      for (const item of stack())
        item.onClose?.();
      setStack([{
        id: nextId++,
        element,
        size: options?.size ?? "medium",
        onClose: options?.onClose
      }]);
    },
    pop() {
      const current = stack().at(-1);
      current?.onClose?.();
      setStack((items) => items.slice(0, -1));
      return !!current;
    },
    clear() {
      for (const item of stack())
        item.onClose?.();
      setStack([]);
    }
  };
}
function DialogProvider(props) {
  const dialog = createDialogStore();
  return createComponent2(DialogContext.Provider, {
    value: dialog,
    get children() {
      return props.children;
    }
  });
}
function useDialog() {
  const dialog = useContext(DialogContext);
  if (!dialog)
    throw new Error("useDialog must be used within DialogProvider");
  return dialog;
}
function widthFor(size, terminalWidth) {
  const target = size === "xlarge" ? 116 : size === "large" ? 88 : 60;
  return Math.max(36, Math.min(target, terminalWidth - 2));
}
function DialogViewport() {
  const dialog = useDialog();
  const theme = useTheme();
  const renderer = useRenderer();
  const dimensions = useTerminalDimensions();
  let selectionDrag = false;
  useStaticBindings(() => ({
    priority: 300,
    bindings: [{
      key: "escape",
      desc: "Close dialog",
      group: "Dialog",
      cmd: () => {
        if (dialog.stack().length === 0)
          return;
        if (renderer.getSelection())
          renderer.clearSelection();
        else
          dialog.pop();
      }
    }]
  }));
  const current = () => dialog.current;
  return createComponent2(Show, {
    get when() {
      return current();
    },
    children: (entry) => (() => {
      var _el$ = createElement("box"), _el$2 = createElement("box");
      insertNode(_el$, _el$2);
      setProp(_el$, "position", "absolute");
      setProp(_el$, "zIndex", 3000);
      setProp(_el$, "left", 0);
      setProp(_el$, "top", 0);
      setProp(_el$, "alignItems", "center");
      setProp(_el$, "justifyContent", "center");
      setProp(_el$, "onMouseDown", () => {
        selectionDrag = !!renderer.getSelection();
      });
      setProp(_el$, "onMouseUp", () => {
        if (selectionDrag) {
          selectionDrag = false;
          return;
        }
        dialog.pop();
      });
      setProp(_el$2, "paddingTop", 1);
      setProp(_el$2, "paddingBottom", 1);
      setProp(_el$2, "paddingLeft", 2);
      setProp(_el$2, "paddingRight", 2);
      setProp(_el$2, "onMouseUp", (event) => {
        selectionDrag = false;
        event.stopPropagation();
      });
      insert(_el$2, () => entry().element());
      effect((_p$) => {
        var _v$ = dimensions().width, _v$2 = dimensions().height, _v$3 = RGBA.fromInts(0, 0, 0, 150), _v$4 = widthFor(entry().size, dimensions().width), _v$5 = Math.max(8, dimensions().height - 4), _v$6 = theme.backgroundMenu;
        _v$ !== _p$.e && (_p$.e = setProp(_el$, "width", _v$, _p$.e));
        _v$2 !== _p$.t && (_p$.t = setProp(_el$, "height", _v$2, _p$.t));
        _v$3 !== _p$.a && (_p$.a = setProp(_el$, "backgroundColor", _v$3, _p$.a));
        _v$4 !== _p$.o && (_p$.o = setProp(_el$2, "width", _v$4, _p$.o));
        _v$5 !== _p$.i && (_p$.i = setProp(_el$2, "maxHeight", _v$5, _p$.i));
        _v$6 !== _p$.n && (_p$.n = setProp(_el$2, "backgroundColor", _v$6, _p$.n));
        return _p$;
      }, {
        e: undefined,
        t: undefined,
        a: undefined,
        o: undefined,
        i: undefined,
        n: undefined
      });
      return _el$;
    })()
  });
}
var DialogContext;
var init_dialog = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_theme2();
  init_keymap();
  DialogContext = createContext();
});

// src/cli/tui-solid/context/commands.tsx
function createCommands() {
  const projects = useProjects();
  const toast = useToast();
  return createMemo(() => [{
    id: "projects.open",
    title: "Projects",
    category: "View",
    run: () => void projects.actions.navigate({
      name: "projects"
    })
  }, {
    id: "roots.open",
    title: "Roots",
    category: "View",
    run: () => void projects.actions.navigate({
      name: "roots"
    })
  }, {
    id: "recipes.open",
    title: "Recipes",
    category: "View",
    run: () => void projects.actions.navigate({
      name: "recipes"
    })
  }, {
    id: "agents.open",
    title: "Agents",
    category: "View",
    run: () => void projects.actions.navigate({
      name: "agents"
    })
  }, {
    id: "settings.open",
    title: "Settings",
    category: "View",
    run: () => void projects.actions.navigate({
      name: "settings"
    })
  }, {
    id: "project.new",
    title: "Create Project",
    category: "Project",
    run: () => projects.actions.openDialog({
      kind: "create"
    })
  }, {
    id: "project.edit",
    title: "Edit Project",
    category: "Project",
    enabled: () => !!projects.state.selected,
    run: () => {
      const project = projects.state.selected;
      if (project)
        projects.actions.openDialog({
          kind: "edit",
          project
        });
    }
  }, {
    id: "shortcuts.open",
    title: "Keyboard Shortcuts",
    category: "Help",
    run: () => projects.actions.openDialog({
      kind: "shortcuts"
    })
  }, {
    id: "refresh",
    title: "Refresh",
    category: "View",
    run: async () => {
      await projects.actions.reloadProjects();
      toast.show(projects.state.error ? {
        title: "Couldn't refresh",
        message: "Check your connection and try again.",
        tone: "error"
      } : {
        title: "Refreshed",
        message: "Projects are up to date.",
        tone: "success"
      });
    }
  }]);
}
function CommandProvider(props) {
  const commands = createCommands();
  const projects = useProjects();
  const renderer = useRenderer();
  const value = {
    commands,
    visibleCommands: createMemo(() => commands().filter((command) => !command.hidden && (command.enabled?.() ?? true))),
    async runCommand(id) {
      const command = commands().find((item) => item.id === id);
      if (!command || command.enabled?.() === false)
        return false;
      await command.run();
      return true;
    }
  };
  useStaticBindings(() => ({
    priority: 50,
    bindings: [{
      key: "ctrl+p",
      desc: "Open shortcuts",
      group: "Commands",
      cmd: () => projects.state.dialog === null && projects.actions.openDialog({
        kind: "shortcuts"
      })
    }, {
      key: "ctrl+r",
      desc: "Refresh",
      group: "Commands",
      cmd: () => projects.state.dialog === null && value.runCommand("refresh")
    }, {
      key: "escape",
      desc: "Back",
      group: "Navigation",
      cmd: () => {
        if (projects.state.dialog)
          return;
        projects.state.route.name === "project" ? projects.actions.navigate({
          name: "projects"
        }) : renderer.destroy();
      }
    }]
  }));
  const handleKey = (key) => {
    if (projects.state.dialog)
      return;
    const consume = () => {
      key.preventDefault();
      key.stopPropagation();
    };
    if (key.ctrl && key.name === "p") {
      projects.actions.openDialog({
        kind: "shortcuts"
      });
      consume();
      return;
    }
    if (key.ctrl && key.name === "r") {
      value.runCommand("refresh");
      consume();
      return;
    }
    if (key.name === "escape") {
      projects.state.route.name === "project" ? projects.actions.navigate({
        name: "projects"
      }) : renderer.destroy();
      consume();
      return;
    }
  };
  const handleRawInput = (sequence) => {
    if (projects.state.dialog)
      return false;
    const rawCommands = {
      "\x10": () => projects.actions.openDialog({
        kind: "shortcuts"
      }),
      "\x1B[112;5u": () => projects.actions.openDialog({
        kind: "shortcuts"
      }),
      "\x12": () => void value.runCommand("refresh"),
      "\x1B[114;5u": () => void value.runCommand("refresh")
    };
    const run = rawCommands[sequence];
    if (!run)
      return false;
    run();
    return true;
  };
  let registered = false;
  onMount(() => {
    queueMicrotask(() => {
      renderer.prependInputHandler(handleRawInput);
      renderer.keyInput.prependListener("keypress", handleKey);
      registered = true;
    });
  });
  onCleanup(() => {
    if (!registered)
      return;
    renderer.removeInputHandler(handleRawInput);
    renderer.keyInput.off("keypress", handleKey);
  });
  return createComponent2(CommandContext.Provider, {
    value,
    get children() {
      return props.children;
    }
  });
}
var CommandContext;
var init_commands = __esm(() => {
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_toast();
  init_keymap();
  CommandContext = createContext();
});

// src/cli/tui/clipboard.ts
import { readFileSync as readFileSync2 } from "fs";
function defaultRuntime() {
  return {
    env: process.env,
    platform: process.platform,
    stdoutIsTTY: process.stdout.isTTY,
    writeStdout: (value) => {
      process.stdout.write(value);
    },
    spawnSync: (options) => Bun.spawnSync(options),
    spawnAsync: async (options) => {
      const proc = Bun.spawn({
        cmd: options.cmd,
        stdin: options.stdin ? "pipe" : "ignore",
        stdout: options.stdout,
        stderr: options.stderr
      });
      if (options.stdin && proc.stdin) {
        proc.stdin.write(options.stdin);
        proc.stdin.end();
      }
      let timedOut2 = false;
      const timeout = options.timeoutMs ? setTimeout(() => {
        timedOut2 = true;
        proc.kill("SIGKILL");
      }, options.timeoutMs) : null;
      try {
        const [exitCode, stdout] = await Promise.all([
          proc.exited.catch(() => null),
          options.stdout === "pipe" && proc.stdout ? new Response(proc.stdout).arrayBuffer().then((buffer) => new Uint8Array(buffer)).catch(() => {
            return;
          }) : Promise.resolve(undefined)
        ]);
        return { exitCode: timedOut2 ? null : exitCode, stdout };
      } finally {
        if (timeout)
          clearTimeout(timeout);
      }
    },
    readFile: (path) => {
      try {
        return readFileSync2(path);
      } catch {
        return null;
      }
    }
  };
}
function clippedForOsc52(text) {
  const bytes = new TextEncoder().encode(text);
  if (bytes.length <= OSC52_MAX_BYTES)
    return text;
  return new TextDecoder().decode(bytes.slice(0, OSC52_MAX_BYTES));
}
function copyWithOsc52(text, runtime) {
  if (!runtime.stdoutIsTTY)
    return null;
  const encoded = Buffer.from(clippedForOsc52(text)).toString("base64");
  if (runtime.env["TMUX"]) {
    runtime.writeStdout(`\x1BPtmux;\x1B\x1B]52;c;${encoded}\x07\x1B\\`);
    return { ok: true, method: "osc52-tmux" };
  }
  runtime.writeStdout(`\x1B]52;c;${encoded}\x07`);
  return { ok: true, method: "osc52" };
}
function runClipboardCommand(runtime, cmd, text) {
  try {
    const result = runtime.spawnSync({
      cmd,
      stdin: new TextEncoder().encode(text),
      stdout: "ignore",
      stderr: "ignore"
    });
    return result.exitCode === 0;
  } catch {
    return false;
  }
}
function clipboardCommandTimeoutMs(runtime) {
  const raw = runtime.env["PROJECTS_TUI_CLIPBOARD_COMMAND_TIMEOUT_MS"];
  const parsed = raw ? Number.parseInt(raw, 10) : DEFAULT_COMMAND_TIMEOUT_MS;
  return Number.isFinite(parsed) ? Math.max(250, parsed) : DEFAULT_COMMAND_TIMEOUT_MS;
}
async function runClipboardCommandAsync(runtime, cmd, text) {
  if (!runtime.spawnAsync)
    return runClipboardCommand(runtime, cmd, text);
  try {
    const result = await runtime.spawnAsync({
      cmd,
      stdin: new TextEncoder().encode(text),
      stdout: "ignore",
      stderr: "ignore",
      timeoutMs: clipboardCommandTimeoutMs(runtime)
    });
    return result.exitCode === 0;
  } catch {
    return false;
  }
}
function commandOutput(runtime, cmd) {
  try {
    const result = runtime.spawnSync({ cmd, stdout: "pipe", stderr: "ignore" });
    if (result.exitCode !== 0 || !result.stdout)
      return "";
    return typeof result.stdout === "string" ? result.stdout : Buffer.from(result.stdout).toString("utf8");
  } catch {
    return "";
  }
}
function readFileText(runtime, path) {
  try {
    const content = runtime.readFile?.(path);
    if (!content)
      return "";
    return typeof content === "string" ? content : Buffer.from(content).toString("utf8");
  } catch {
    return "";
  }
}
function splitHostList(value) {
  return (value ?? "").split(/[,\s]+/).map((item) => item.trim()).filter(Boolean);
}
function firstEnvWord(value) {
  return value?.split(/\s+/)[0];
}
function parseEnvironmentText(text) {
  const env2 = {};
  for (const rawLine of text.split(/\0|\n/)) {
    const line = rawLine.trim();
    const separator = line.indexOf("=");
    if (separator <= 0)
      continue;
    env2[line.slice(0, separator)] = line.slice(separator + 1);
  }
  return env2;
}
function tmuxClientPids(runtime) {
  const active = commandOutput(runtime, ["tmux", "display-message", "-p", "#{client_pid}"]);
  const listed = commandOutput(runtime, ["tmux", "list-clients", "-F", "#{client_pid}"]);
  return [...new Set(`${active}
${listed}`.split(/\s+/).filter((pid) => /^\d+$/.test(pid)))];
}
function tmuxEnvironmentHosts(runtime) {
  if (!runtime.env["TMUX"])
    return [];
  const envParts = [
    commandOutput(runtime, ["tmux", "show-environment", "-g", "SSH_CLIENT"]),
    commandOutput(runtime, ["tmux", "show-environment", "-g", "SSH_CONNECTION"]),
    commandOutput(runtime, ["tmux", "show-environment", "-g", "MOSH_IP"]),
    commandOutput(runtime, ["tmux", "show-environment", "-g", "MOSH_CLIENT_IP"])
  ];
  for (const pid of tmuxClientPids(runtime)) {
    envParts.push(readFileText(runtime, `/proc/${pid}/environ`));
  }
  return sshClipboardHosts(parseEnvironmentText(envParts.join(`
`)));
}
function sshClipboardHosts(env2 = process.env, discoveredHosts = []) {
  const explicitHosts = [
    ...splitHostList(env2["PROJECTS_TUI_CLIPBOARD_HOST"]),
    ...splitHostList(env2["PROJECTS_TUI_CLIPBOARD_SSH_HOSTS"])
  ];
  const hosts = [
    ...explicitHosts,
    ...discoveredHosts,
    firstEnvWord(env2["SSH_CLIENT"]),
    firstEnvWord(env2["SSH_CONNECTION"]),
    firstEnvWord(env2["MOSH_IP"]),
    firstEnvWord(env2["MOSH_CLIENT_IP"]),
    firstEnvWord(env2["MOSH_CLIENT_HOST"])
  ].filter((host) => !!host);
  return [...new Set(hosts)];
}
function sshClipboardCommands(env2, discoveredHosts = []) {
  const timeout = env2["PROJECTS_TUI_CLIPBOARD_SSH_TIMEOUT"] || DEFAULT_SSH_TIMEOUT_SECONDS;
  return sshClipboardHosts(env2, discoveredHosts).map((host) => [
    "ssh",
    "-o",
    "BatchMode=yes",
    "-o",
    `ConnectTimeout=${timeout}`,
    "-o",
    "LogLevel=ERROR",
    host,
    "pbcopy"
  ]);
}
function clipboardCommands(platform = process.platform, env2 = process.env, discoveredHosts = []) {
  const commands = [];
  const configured = env2["PROJECTS_TUI_CLIPBOARD_COMMAND"]?.trim();
  if (configured)
    commands.push(configured.split(/\s+/));
  if (platform === "darwin")
    commands.push(["pbcopy"]);
  commands.push(...sshClipboardCommands(env2, discoveredHosts));
  if (platform !== "darwin")
    commands.push(["pbcopy"]);
  if (platform === "win32")
    commands.push(["clip.exe"]);
  commands.push(["tmux-clipboard-copy"]);
  return [
    ...commands,
    ["wl-copy"],
    ["xclip", "-selection", "clipboard"],
    ["xsel", "--clipboard", "--input"],
    ["termux-clipboard-set"]
  ];
}
function commandMethod(cmd) {
  if (cmd[0] === "ssh")
    return `ssh-pbcopy:${cmd.at(-2) ?? "host"}`;
  return cmd[0] ?? "command";
}
async function copyToTmuxBufferAsync(text, runtime) {
  if (!runtime.env["TMUX"])
    return null;
  if (await runClipboardCommandAsync(runtime, ["tmux", "load-buffer", "-"], text))
    return { ok: true, method: "tmux-buffer" };
  return null;
}
function osc52Preference(env2) {
  const raw = (env2["PROJECTS_TUI_CLIPBOARD_OSC52"] ?? "").trim().toLowerCase();
  if (raw === "always" || raw === "1" || raw === "true" || raw === "force")
    return "always";
  if (raw === "never" || raw === "0" || raw === "false" || raw === "off")
    return "never";
  return "auto";
}
function hasConfiguredCommand(env2) {
  return !!env2["PROJECTS_TUI_CLIPBOARD_COMMAND"]?.trim();
}
function isRemoteSession(env2 = process.env, discoveredHosts = []) {
  if (env2["SSH_TTY"] || env2["SSH_CONNECTION"] || env2["SSH_CLIENT"])
    return true;
  if (env2["MOSH_CONNECTION"] || env2["MOSH_CLIENT_IP"] || env2["MOSH_IP"])
    return true;
  if (env2["TMUX"] && discoveredHosts.length > 0)
    return true;
  return false;
}
function shouldPreferOsc52(runtime, discoveredHosts) {
  const mode = osc52Preference(runtime.env);
  if (mode === "never")
    return false;
  if (!runtime.stdoutIsTTY)
    return false;
  if (mode === "always")
    return true;
  return isRemoteSession(runtime.env, discoveredHosts) && !hasConfiguredCommand(runtime.env);
}
async function copyTextToClipboardAsync(text, runtime = defaultRuntime()) {
  if (!text.trim())
    return { ok: false, error: "nothing to copy" };
  if (runtime.env["PROJECTS_TUI_CLIPBOARD_DRY_RUN"] === "1")
    return { ok: true, method: "dry-run" };
  const discovered = tmuxEnvironmentHosts(runtime);
  if (shouldPreferOsc52(runtime, discovered)) {
    const osc52 = copyWithOsc52(text, runtime);
    if (osc52)
      return osc52;
  }
  const commands = clipboardCommands(runtime.platform, runtime.env, discovered);
  for (const cmd of commands) {
    if (await runClipboardCommandAsync(runtime, cmd, text))
      return { ok: true, method: commandMethod(cmd) };
  }
  const tmux = await copyToTmuxBufferAsync(text, runtime);
  if (tmux)
    return tmux;
  if (osc52Preference(runtime.env) !== "never") {
    const osc52 = copyWithOsc52(text, runtime);
    if (osc52)
      return osc52;
  }
  return { ok: false, error: "no supported clipboard route found" };
}
var OSC52_MAX_BYTES = 90000, DEFAULT_SSH_TIMEOUT_SECONDS = "1", DEFAULT_COMMAND_TIMEOUT_MS = 1500;
var init_clipboard = () => {};

// src/cli/tui/watchdog.ts
function startEventLoopWatchdog(options = {}) {
  const intervalMs = Math.max(100, options.intervalMs ?? 2000);
  const thresholdMs = Math.max(intervalMs, options.thresholdMs ?? 5000);
  const onLag = options.onLag ?? ((lagMs) => {
    process.stderr.write(`[projects ui] event loop lag ${Math.round(lagMs)}ms
`);
  });
  let expected = Date.now() + intervalMs;
  const timer = setInterval(() => {
    const now3 = Date.now();
    const lag = now3 - expected;
    if (lag > thresholdMs)
      onLag(lag);
    expected = now3 + intervalMs;
  }, intervalMs);
  timer.unref?.();
  return () => clearInterval(timer);
}

// src/cli/tui-solid/ui/primitives.tsx
import { TextAttributes as TextAttributes3 } from "@opentui/core";
function Button(props) {
  const theme = useTheme();
  const bg = () => {
    if (props.active)
      return theme.primary;
    if (props.tone === "primary")
      return theme.primary;
    if (props.tone === "danger")
      return theme.error;
    if (props.tone === "warning")
      return theme.warning;
    return theme.backgroundElement;
  };
  const foreground = () => {
    if (props.active || props.tone === "primary" || props.tone === "danger" || props.tone === "warning") {
      return selectedForeground(theme, bg());
    }
    return theme.text;
  };
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("text");
    insertNode(_el$, _el$2);
    setProp(_el$, "height", 1);
    setProp(_el$, "paddingLeft", 1);
    setProp(_el$, "paddingRight", 1);
    setProp(_el$, "onMouseUp", (event) => {
      if (event.button !== 0)
        return;
      event.stopPropagation();
      props.onPress?.();
    });
    insert(_el$2, () => props.label);
    effect((_p$) => {
      var _v$ = props.width, _v$2 = bg(), _v$3 = foreground();
      _v$ !== _p$.e && (_p$.e = setProp(_el$, "width", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$, "backgroundColor", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$2, "fg", _v$3, _p$.a));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined
    });
    return _el$;
  })();
}
function SectionHeader(props) {
  const theme = useTheme();
  return (() => {
    var _el$3 = createElement("box"), _el$4 = createElement("text");
    insertNode(_el$3, _el$4);
    setProp(_el$3, "height", 1);
    setProp(_el$3, "paddingLeft", 1);
    setProp(_el$3, "marginTop", 1);
    setProp(_el$3, "marginBottom", 0);
    setProp(_el$3, "onMouseUp", (event) => {
      if (event.button !== 0)
        return;
      event.stopPropagation();
      props.onPress?.();
    });
    insert(_el$4, () => props.label, null);
    insert(_el$4, (() => {
      var _c$ = memo2(() => !!props.muted);
      return () => _c$() ? `  ${props.muted}` : "";
    })(), null);
    effect((_p$) => {
      var _v$4 = theme.textMuted, _v$5 = TextAttributes3.BOLD;
      _v$4 !== _p$.e && (_p$.e = setProp(_el$4, "fg", _v$4, _p$.e));
      _v$5 !== _p$.t && (_p$.t = setProp(_el$4, "attributes", _v$5, _p$.t));
      return _p$;
    }, {
      e: undefined,
      t: undefined
    });
    return _el$3;
  })();
}
function Row(props) {
  const theme = useTheme();
  return (() => {
    var _el$5 = createElement("box");
    setProp(_el$5, "width", "100%");
    setProp(_el$5, "paddingLeft", 1);
    setProp(_el$5, "paddingRight", 1);
    setProp(_el$5, "onMouseUp", (event) => {
      if (event.button !== 0)
        return;
      event.stopPropagation();
      props.onPress?.();
    });
    insert(_el$5, () => props.children);
    effect((_p$) => {
      var _v$6 = props.height ?? 1, _v$7 = props.active ? theme.primary : undefined;
      _v$6 !== _p$.e && (_p$.e = setProp(_el$5, "height", _v$6, _p$.e));
      _v$7 !== _p$.t && (_p$.t = setProp(_el$5, "backgroundColor", _v$7, _p$.t));
      return _p$;
    }, {
      e: undefined,
      t: undefined
    });
    return _el$5;
  })();
}
function EmptyState(props) {
  const theme = useTheme();
  return (() => {
    var _el$6 = createElement("box"), _el$7 = createElement("text");
    insertNode(_el$6, _el$7);
    setProp(_el$6, "flexDirection", "column");
    setProp(_el$6, "width", "100%");
    setProp(_el$6, "minHeight", 0);
    setProp(_el$6, "padding", 2);
    setProp(_el$6, "rowGap", 1);
    insert(_el$6, (() => {
      var _c$2 = memo2(() => !!props.icon);
      return () => _c$2() ? (() => {
        var _el$8 = createElement("text");
        insert(_el$8, () => props.icon);
        effect((_$p) => setProp(_el$8, "fg", theme.primary, _$p));
        return _el$8;
      })() : null;
    })(), _el$7);
    setProp(_el$7, "wrapMode", "word");
    insert(_el$7, () => props.title);
    insert(_el$6, (() => {
      var _c$3 = memo2(() => !!props.detail);
      return () => _c$3() ? (() => {
        var _el$9 = createElement("text");
        setProp(_el$9, "wrapMode", "word");
        insert(_el$9, () => props.detail);
        effect((_$p) => setProp(_el$9, "fg", theme.textMuted, _$p));
        return _el$9;
      })() : null;
    })(), null);
    insert(_el$6, () => props.children, null);
    effect((_p$) => {
      var _v$8 = props.fill ? 1 : 0, _v$9 = props.fill ? "center" : undefined, _v$0 = props.fill ? "center" : undefined, _v$1 = theme.text, _v$10 = TextAttributes3.BOLD;
      _v$8 !== _p$.e && (_p$.e = setProp(_el$6, "flexGrow", _v$8, _p$.e));
      _v$9 !== _p$.t && (_p$.t = setProp(_el$6, "justifyContent", _v$9, _p$.t));
      _v$0 !== _p$.a && (_p$.a = setProp(_el$6, "alignItems", _v$0, _p$.a));
      _v$1 !== _p$.o && (_p$.o = setProp(_el$7, "fg", _v$1, _p$.o));
      _v$10 !== _p$.i && (_p$.i = setProp(_el$7, "attributes", _v$10, _p$.i));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined
    });
    return _el$6;
  })();
}
var init_primitives = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_theme2();
});

// src/cli/tui-solid/ui/select-dialog.tsx
import { TextAttributes as TextAttributes4 } from "@opentui/core";
function filterItems(items, query) {
  const q = query.trim().toLowerCase();
  if (!q)
    return items;
  const parts = q.split(/\s+/).filter(Boolean);
  return items.filter((item) => {
    const haystack = `${item.title} ${item.detail ?? ""} ${item.category ?? ""}`.toLowerCase();
    return parts.every((part) => haystack.includes(part));
  });
}
function SelectDialog(props) {
  const theme = useTheme();
  const [active, setActive] = createSignal(Math.max(0, props.items.findIndex((item) => item.id === props.selectedId)));
  const visible = createMemo(() => filterItems(props.items, props.query));
  let list;
  createEffect(() => {
    const index = Math.min(active(), Math.max(0, visible().length - 1));
    if (index !== active())
      setActive(index);
    if (!list)
      return;
    if (index < list.scrollTop)
      list.scrollTo(index);
    else if (index >= list.scrollTop + list.viewport.height)
      list.scrollTo(index - list.viewport.height + 1);
  });
  const selectActive = () => {
    const item = visible()[active()];
    if (item && !item.disabled)
      props.onSelect(item);
  };
  useKeyboard((key) => {
    if (key.name === "up") {
      key.preventDefault();
      key.stopPropagation();
      setActive((value) => Math.max(0, value - 1));
      return;
    }
    if (key.name === "down") {
      key.preventDefault();
      key.stopPropagation();
      setActive((value) => Math.min(Math.max(0, visible().length - 1), value + 1));
      return;
    }
    if (key.name === "enter" || key.name === "return") {
      key.preventDefault();
      key.stopPropagation();
      selectActive();
      return;
    }
    if (key.name === "escape") {
      key.preventDefault();
      key.stopPropagation();
      props.onClose();
    }
  });
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$4 = createElement("input"), _el$5 = createElement("scrollbox");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$4);
    insertNode(_el$, _el$5);
    setProp(_el$, "flexDirection", "column");
    setProp(_el$, "width", "100%");
    setProp(_el$, "rowGap", 1);
    insertNode(_el$2, _el$3);
    setProp(_el$2, "height", 1);
    setProp(_el$2, "flexDirection", "row");
    setProp(_el$2, "justifyContent", "space-between");
    insert(_el$3, () => props.title);
    insert(_el$2, createComponent2(Button, {
      label: "Close",
      get onPress() {
        return props.onClose;
      }
    }), null);
    setProp(_el$4, "focused", true);
    setProp(_el$4, "width", "100%");
    setProp(_el$4, "onInput", (value) => {
      props.onQuery(value);
      setActive(0);
    });
    use((value) => {
      list = value;
    }, _el$5);
    setProp(_el$5, "width", "100%");
    setProp(_el$5, "scrollX", false);
    insert(_el$5, createComponent2(For, {
      get each() {
        return visible();
      },
      children: (item, index) => {
        const isActive = () => index() === active();
        return createComponent2(Row, {
          get active() {
            return isActive();
          },
          onPress: () => {
            if (!item.disabled)
              props.onSelect(item);
          },
          get children() {
            var _el$6 = createElement("box"), _el$7 = createElement("text"), _el$8 = createElement("box"), _el$9 = createElement("text");
            insertNode(_el$6, _el$7);
            insertNode(_el$6, _el$8);
            setProp(_el$6, "flexDirection", "row");
            setProp(_el$6, "width", "100%");
            setProp(_el$6, "columnGap", 1);
            insert(_el$7, () => item.marker ?? " ");
            insertNode(_el$8, _el$9);
            setProp(_el$8, "flexGrow", 1);
            setProp(_el$8, "flexShrink", 1);
            insert(_el$9, () => item.title);
            insert(_el$6, (() => {
              var _c$3 = memo2(() => !!item.detail);
              return () => _c$3() ? (() => {
                var _el$0 = createElement("box"), _el$1 = createElement("text");
                insertNode(_el$0, _el$1);
                setProp(_el$0, "flexShrink", 0);
                insert(_el$1, () => item.detail);
                effect((_$p) => setProp(_el$1, "fg", isActive() ? selectedForeground(theme, theme.primary) : theme.textMuted, _$p));
                return _el$0;
              })() : null;
            })(), null);
            effect((_p$) => {
              var _v$10 = isActive() ? theme.primary : undefined, _v$11 = isActive() ? selectedForeground(theme, theme.primary) : item.markerColor ?? theme.textMuted, _v$12 = isActive() ? selectedForeground(theme, theme.primary) : item.disabled ? theme.textFaint : theme.text, _v$13 = isActive() ? TextAttributes4.BOLD : 0;
              _v$10 !== _p$.e && (_p$.e = setProp(_el$6, "backgroundColor", _v$10, _p$.e));
              _v$11 !== _p$.t && (_p$.t = setProp(_el$7, "fg", _v$11, _p$.t));
              _v$12 !== _p$.a && (_p$.a = setProp(_el$9, "fg", _v$12, _p$.a));
              _v$13 !== _p$.o && (_p$.o = setProp(_el$9, "attributes", _v$13, _p$.o));
              return _p$;
            }, {
              e: undefined,
              t: undefined,
              a: undefined,
              o: undefined
            });
            return _el$6;
          }
        });
      }
    }), null);
    insert(_el$5, (() => {
      var _c$ = memo2(() => visible().length === 0);
      return () => _c$() ? (() => {
        var _el$10 = createElement("text");
        insertNode(_el$10, createTextNode(`No matches`));
        effect((_$p) => setProp(_el$10, "fg", theme.textMuted, _$p));
        return _el$10;
      })() : null;
    })(), null);
    insert(_el$, (() => {
      var _c$2 = memo2(() => !!props.footer);
      return () => _c$2() ? (() => {
        var _el$12 = createElement("text");
        insert(_el$12, () => props.footer);
        effect((_$p) => setProp(_el$12, "fg", theme.textMuted, _$p));
        return _el$12;
      })() : null;
    })(), null);
    effect((_p$) => {
      var _v$ = theme.text, _v$2 = TextAttributes4.BOLD, _v$3 = props.query, _v$4 = props.placeholder ?? "Filter", _v$5 = theme.text, _v$6 = theme.backgroundElement, _v$7 = theme.text, _v$8 = theme.backgroundActive, _v$9 = theme.textMuted, _v$0 = theme.text, _v$1 = Math.min(16, Math.max(5, visible().length + 1));
      _v$ !== _p$.e && (_p$.e = setProp(_el$3, "fg", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "attributes", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$4, "value", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$4, "placeholder", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$4, "textColor", _v$5, _p$.i));
      _v$6 !== _p$.n && (_p$.n = setProp(_el$4, "backgroundColor", _v$6, _p$.n));
      _v$7 !== _p$.s && (_p$.s = setProp(_el$4, "focusedTextColor", _v$7, _p$.s));
      _v$8 !== _p$.h && (_p$.h = setProp(_el$4, "focusedBackgroundColor", _v$8, _p$.h));
      _v$9 !== _p$.r && (_p$.r = setProp(_el$4, "placeholderColor", _v$9, _p$.r));
      _v$0 !== _p$.d && (_p$.d = setProp(_el$4, "cursorColor", _v$0, _p$.d));
      _v$1 !== _p$.l && (_p$.l = setProp(_el$5, "height", _v$1, _p$.l));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined,
      s: undefined,
      h: undefined,
      r: undefined,
      d: undefined,
      l: undefined
    });
    return _el$;
  })();
}
var init_select_dialog = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_theme2();
  init_primitives();
});

// src/cli/tui/format.ts
function truncate(text, max) {
  if (max <= 1)
    return text.slice(0, Math.max(0, max));
  return text.length > max ? text.slice(0, max - 1) + "\u2026" : text;
}
function formatRelativeTime(iso, now3 = Date.now()) {
  if (!iso)
    return "";
  const time = new Date(iso).getTime();
  if (!Number.isFinite(time))
    return "";
  const diff = Math.max(0, now3 - time);
  const seconds = Math.floor(diff / 1000);
  if (seconds < 60)
    return `${seconds}s ago`;
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60)
    return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24)
    return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 7)
    return `${days}d ago`;
  return iso.slice(0, 10);
}
function formatDateTime(iso, now3) {
  if (!iso)
    return "";
  const date = new Date(iso);
  if (Number.isNaN(date.getTime()))
    return "";
  const pad = (n) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + `${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function kindLabel(kind) {
  if (!kind)
    return "";
  return kind.charAt(0).toUpperCase() + kind.slice(1);
}
function statusLabel(status) {
  return status;
}
function capitalize(value) {
  return value ? value.charAt(0).toUpperCase() + value.slice(1) : value;
}
function stageLabel(stage) {
  if (!stage)
    return "";
  if (PROJECT_STAGES.includes(stage)) {
    return STAGE_LABELS[stage];
  }
  return capitalize(stage);
}
function priorityLabel(priority) {
  if (!priority)
    return "";
  if (PROJECT_PRIORITIES.includes(priority)) {
    return PRIORITY_LABELS[priority];
  }
  return capitalize(priority);
}
function transportLabel(transport2) {
  if (transport2 === "http")
    return "hosted";
  if (transport2 === "local")
    return "local";
  return transport2;
}
var STAGE_LABELS, PRIORITY_LABELS;
var init_format = __esm(() => {
  init_project_management();
  STAGE_LABELS = {
    idea: "Idea",
    planned: "Planned",
    active: "Active",
    paused: "Paused",
    shipped: "Shipped",
    maintenance: "Maintenance"
  };
  PRIORITY_LABELS = {
    low: "Low",
    medium: "Medium",
    high: "High",
    critical: "Critical"
  };
});

// src/cli/tui/types.ts
var init_types = __esm(() => {
  init_workspace();
});

// src/cli/tui-solid/component/sidebar.tsx
import { TextAttributes as TextAttributes5 } from "@opentui/core";
function sidebarWidth(terminalWidth) {
  return terminalWidth >= 92 ? SIDEBAR_WIDE : Math.min(SIDEBAR_WIDE, Math.max(24, Math.floor(terminalWidth * 0.42)));
}
function Sidebar() {
  const projects = useProjects();
  const {
    state,
    actions
  } = projects;
  const theme = useTheme();
  const dimensions = useTerminalDimensions();
  const transportLine = () => {
    const transport2 = state.transport;
    if (!transport2)
      return "Resolving registry\u2026";
    const label = transportLabel(transport2);
    return transport2 === "http" && state.authority ? `${label} \xB7 ${state.authority}` : label;
  };
  const projectRowActive = (status) => state.route.name === "projects" && state.filter.status === status;
  const goProjectFilter = (status) => {
    actions.setFilter({
      status
    });
    actions.navigate({
      name: "projects"
    });
  };
  const errorWidth = () => Math.max(18, sidebarWidth(dimensions().width) - 3);
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$5 = createElement("text"), _el$6 = createElement("box"), _el$7 = createElement("scrollbox"), _el$8 = createElement("box"), _el$9 = createElement("box"), _el$10 = createElement("box"), _el$11 = createElement("text");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$6);
    insertNode(_el$, _el$7);
    insertNode(_el$, _el$10);
    setProp(_el$, "width", "100%");
    setProp(_el$, "height", "100%");
    setProp(_el$, "flexDirection", "column");
    setProp(_el$, "paddingTop", 1);
    setProp(_el$, "paddingLeft", 1);
    setProp(_el$, "paddingRight", 1);
    insertNode(_el$2, _el$3);
    insertNode(_el$2, _el$5);
    setProp(_el$2, "height", 2);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$2, "flexDirection", "column");
    setProp(_el$2, "paddingLeft", 1);
    insertNode(_el$3, createTextNode(`Projects`));
    setProp(_el$3, "wrapMode", "none");
    setProp(_el$5, "wrapMode", "none");
    insert(_el$5, transportLine);
    setProp(_el$6, "width", "100%");
    setProp(_el$6, "marginTop", 1);
    setProp(_el$6, "flexShrink", 0);
    insert(_el$6, createComponent2(Button, {
      label: "+ New project",
      tone: "primary",
      onPress: () => actions.openDialog({
        kind: "create"
      })
    }));
    insertNode(_el$7, _el$8);
    insertNode(_el$7, _el$9);
    setProp(_el$7, "flexGrow", 1);
    setProp(_el$7, "minHeight", 0);
    setProp(_el$7, "width", "100%");
    setProp(_el$7, "scrollX", false);
    insert(_el$7, createComponent2(SectionHeader, {
      label: "Projects"
    }), _el$8);
    insert(_el$7, createComponent2(For, {
      each: PROJECT_NAV,
      children: (item) => {
        const active = () => projectRowActive(item.status);
        const fg = () => active() ? selectedForeground(theme, theme.primary) : theme.text;
        return createComponent2(Row, {
          get active() {
            return active();
          },
          onPress: () => goProjectFilter(item.status),
          get children() {
            var _el$12 = createElement("box"), _el$13 = createElement("text");
            insertNode(_el$12, _el$13);
            setProp(_el$12, "width", "100%");
            setProp(_el$12, "flexDirection", "row");
            setProp(_el$12, "columnGap", 1);
            setProp(_el$13, "flexShrink", 1);
            setProp(_el$13, "minWidth", 0);
            setProp(_el$13, "wrapMode", "none");
            insert(_el$13, () => item.label);
            effect((_$p) => setProp(_el$13, "fg", fg(), _$p));
            return _el$12;
          }
        });
      }
    }), _el$8);
    setProp(_el$8, "height", 1);
    setProp(_el$8, "flexShrink", 0);
    setProp(_el$8, "border", ["bottom"]);
    insert(_el$7, createComponent2(For, {
      each: REGISTRY_NAV,
      children: (item) => {
        const active = () => state.route.name === item.route;
        const fg = () => active() ? selectedForeground(theme, theme.primary) : theme.text;
        return createComponent2(Row, {
          get active() {
            return active();
          },
          onPress: () => void actions.navigate({
            name: item.route
          }),
          get children() {
            var _el$14 = createElement("text");
            setProp(_el$14, "wrapMode", "none");
            insert(_el$14, () => item.label);
            effect((_$p) => setProp(_el$14, "fg", fg(), _$p));
            return _el$14;
          }
        });
      }
    }), _el$9);
    setProp(_el$9, "height", 1);
    setProp(_el$9, "flexShrink", 0);
    setProp(_el$9, "border", ["bottom"]);
    insert(_el$7, createComponent2(Row, {
      get active() {
        return state.dialog?.kind === "shortcuts";
      },
      onPress: () => actions.openDialog({
        kind: "shortcuts"
      }),
      get children() {
        var _el$0 = createElement("text");
        insertNode(_el$0, createTextNode(`Shortcuts`));
        setProp(_el$0, "wrapMode", "none");
        effect((_$p) => setProp(_el$0, "fg", state.dialog?.kind === "shortcuts" ? selectedForeground(theme, theme.primary) : theme.text, _$p));
        return _el$0;
      }
    }), null);
    insertNode(_el$10, _el$11);
    setProp(_el$10, "height", 1);
    setProp(_el$10, "flexShrink", 0);
    setProp(_el$10, "paddingLeft", 1);
    insert(_el$11, () => state.loading ? "Loading" : "Ready");
    insert(_el$, createComponent2(Show, {
      get when() {
        return state.error;
      },
      children: (message) => (() => {
        var _el$15 = createElement("box"), _el$16 = createElement("text");
        insertNode(_el$15, _el$16);
        setProp(_el$15, "height", 1);
        setProp(_el$15, "flexShrink", 0);
        setProp(_el$15, "paddingLeft", 1);
        setProp(_el$15, "width", "100%");
        setProp(_el$16, "wrapMode", "none");
        insert(_el$16, () => truncate(message(), errorWidth()));
        effect((_$p) => setProp(_el$16, "fg", theme.error, _$p));
        return _el$15;
      })()
    }), null);
    effect((_p$) => {
      var { backgroundPanel: _v$, text: _v$2 } = theme, _v$3 = TextAttributes5.BOLD, _v$4 = theme.textMuted, _v$5 = {
        trackOptions: {
          backgroundColor: theme.backgroundElement,
          foregroundColor: theme.borderActive
        }
      }, _v$6 = theme.borderSubtle, _v$7 = theme.borderSubtle, _v$8 = state.loading ? theme.textMuted : theme.text;
      _v$ !== _p$.e && (_p$.e = setProp(_el$, "backgroundColor", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "fg", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$3, "attributes", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$5, "fg", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$7, "verticalScrollbarOptions", _v$5, _p$.i));
      _v$6 !== _p$.n && (_p$.n = setProp(_el$8, "borderColor", _v$6, _p$.n));
      _v$7 !== _p$.s && (_p$.s = setProp(_el$9, "borderColor", _v$7, _p$.s));
      _v$8 !== _p$.h && (_p$.h = setProp(_el$11, "fg", _v$8, _p$.h));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined,
      s: undefined,
      h: undefined
    });
    return _el$;
  })();
}
var SIDEBAR_WIDE = 30, PROJECT_NAV, REGISTRY_NAV;
var init_sidebar = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_primitives();
  init_format();
  PROJECT_NAV = [{
    label: "Projects",
    status: "all"
  }, {
    label: "Active",
    status: "active"
  }, {
    label: "Archived",
    status: "archived"
  }];
  REGISTRY_NAV = [{
    label: "Roots",
    route: "roots"
  }, {
    label: "Recipes",
    route: "recipes"
  }, {
    label: "Agents",
    route: "agents"
  }, {
    label: "Settings",
    route: "settings"
  }];
});

// src/cli/tui-solid/component/projects-list.tsx
import { TextAttributes as TextAttributes6 } from "@opentui/core";
function statusFg(theme, status) {
  if (status === "active")
    return theme.success;
  if (status === "archived")
    return theme.textMuted;
  return theme.error;
}
function healthGlyph(health) {
  switch (health) {
    case "ok":
      return ".";
    case "untracked":
      return "!";
    case "missing":
      return "x";
    case "unknown":
      return "?";
  }
}
function healthFg(theme, health) {
  switch (health) {
    case "ok":
      return theme.success;
    case "untracked":
      return theme.warning;
    case "missing":
      return theme.error;
    case "unknown":
      return theme.textMuted;
  }
}
function ProjectRow(props) {
  const theme = useTheme();
  const project = () => props.project;
  const rowBg = () => props.selected ? theme.primary : undefined;
  const rowFg = () => props.selected ? selectedForeground(theme, rowBg()) : theme.text;
  const mgmt = () => managementView(project());
  const cols = () => props.columns;
  return createComponent2(Row, {
    get active() {
      return props.selected;
    },
    get onPress() {
      return props.onPress;
    },
    get children() {
      var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$4 = createElement("box"), _el$5 = createElement("text"), _el$6 = createElement("box"), _el$7 = createElement("text"), _el$8 = createElement("box"), _el$9 = createElement("text"), _el$0 = createElement("box"), _el$1 = createElement("text");
      insertNode(_el$, _el$2);
      insertNode(_el$, _el$4);
      insertNode(_el$, _el$6);
      insertNode(_el$, _el$8);
      insertNode(_el$, _el$0);
      setProp(_el$, "flexDirection", "row");
      setProp(_el$, "width", "100%");
      setProp(_el$, "columnGap", 1);
      insertNode(_el$2, _el$3);
      setProp(_el$2, "flexShrink", 0);
      setProp(_el$3, "wrapMode", "none");
      insert(_el$3, () => truncate(project().slug, cols().slug));
      insertNode(_el$4, _el$5);
      setProp(_el$4, "flexShrink", 0);
      setProp(_el$5, "wrapMode", "none");
      insert(_el$5, () => truncate(statusLabel(project().status), cols().status));
      insertNode(_el$6, _el$7);
      setProp(_el$6, "flexShrink", 0);
      setProp(_el$7, "wrapMode", "none");
      insert(_el$7, () => truncate(mgmt().stage ?? "-", cols().stage));
      insertNode(_el$8, _el$9);
      setProp(_el$8, "flexShrink", 0);
      setProp(_el$9, "wrapMode", "none");
      insert(_el$9, () => healthGlyph(mgmt().health));
      insertNode(_el$0, _el$1);
      setProp(_el$0, "flexShrink", 0);
      setProp(_el$1, "wrapMode", "none");
      insert(_el$1, () => truncate(project().primary_path ?? "-", cols().path));
      effect((_p$) => {
        var _v$ = rowBg(), _v$2 = cols().slug, _v$3 = rowFg(), _v$4 = TextAttributes6.BOLD, _v$5 = cols().status, _v$6 = props.selected ? rowFg() : statusFg(theme, project().status), _v$7 = cols().stage, _v$8 = props.selected ? rowFg() : theme.textMuted, _v$9 = cols().health, _v$0 = props.selected ? rowFg() : healthFg(theme, mgmt().health), _v$1 = cols().path, _v$10 = props.selected ? rowFg() : theme.textMuted;
        _v$ !== _p$.e && (_p$.e = setProp(_el$, "backgroundColor", _v$, _p$.e));
        _v$2 !== _p$.t && (_p$.t = setProp(_el$2, "width", _v$2, _p$.t));
        _v$3 !== _p$.a && (_p$.a = setProp(_el$3, "fg", _v$3, _p$.a));
        _v$4 !== _p$.o && (_p$.o = setProp(_el$3, "attributes", _v$4, _p$.o));
        _v$5 !== _p$.i && (_p$.i = setProp(_el$4, "width", _v$5, _p$.i));
        _v$6 !== _p$.n && (_p$.n = setProp(_el$5, "fg", _v$6, _p$.n));
        _v$7 !== _p$.s && (_p$.s = setProp(_el$6, "width", _v$7, _p$.s));
        _v$8 !== _p$.h && (_p$.h = setProp(_el$7, "fg", _v$8, _p$.h));
        _v$9 !== _p$.r && (_p$.r = setProp(_el$8, "width", _v$9, _p$.r));
        _v$0 !== _p$.d && (_p$.d = setProp(_el$9, "fg", _v$0, _p$.d));
        _v$1 !== _p$.l && (_p$.l = setProp(_el$0, "width", _v$1, _p$.l));
        _v$10 !== _p$.u && (_p$.u = setProp(_el$1, "fg", _v$10, _p$.u));
        return _p$;
      }, {
        e: undefined,
        t: undefined,
        a: undefined,
        o: undefined,
        i: undefined,
        n: undefined,
        s: undefined,
        h: undefined,
        r: undefined,
        d: undefined,
        l: undefined,
        u: undefined
      });
      return _el$;
    }
  });
}
function ProjectsListRoute() {
  const projects = useProjects();
  const {
    state,
    actions
  } = projects;
  const theme = useTheme();
  const dialog = useDialog();
  const renderer = useRenderer();
  const dimensions = useTerminalDimensions();
  const [selected, setSelected] = createSignal(0);
  const [searchActive, setSearchActive] = createSignal(false);
  const [kindQuery, setKindQuery] = createSignal("");
  const contentWidth = () => Math.max(24, dimensions().width - sidebarWidth(dimensions().width) - 6);
  const sorted = createMemo(() => [...state.projects].sort((a, b) => b.updated_at.localeCompare(a.updated_at)).slice(0, 200));
  createEffect(() => {
    const count = sorted().length;
    if (count === 0)
      setSelected(0);
    else if (selected() >= count)
      setSelected(count - 1);
  });
  onMount(() => {
    if (!state.loading && state.projects.length === 0 && !state.error)
      actions.load();
  });
  const columns = () => {
    const width = contentWidth();
    const health = 1;
    const status = 9;
    const stage = width < 74 ? 8 : 12;
    const slug = Math.max(8, Math.min(22, Math.floor(width * 0.2)));
    const path = Math.max(6, width - health - status - stage - slug - 4);
    return {
      slug,
      status,
      stage,
      health,
      path
    };
  };
  const hasFilters = () => state.filter.status !== "all" || state.filter.kind !== "all" || state.filter.query.trim().length > 0;
  const emptyTitle = () => {
    if (state.loading)
      return "Loading projects\u2026";
    if (state.error)
      return "Couldn't load projects";
    if (hasFilters())
      return "No matching projects";
    return "No projects";
  };
  const emptyDetail = () => {
    if (state.loading)
      return "Fetching the project registry\u2026";
    if (state.error)
      return "Check your connection and try again.";
    if (hasFilters())
      return "Try a different search or clear your filters.";
    return "Create a project to get started.";
  };
  const countCaption = () => {
    const total = sorted().length;
    const parts = [`${total} project${total === 1 ? "" : "s"}`];
    if (state.filter.status !== "all")
      parts.push(statusLabel(state.filter.status));
    if (state.filter.kind !== "all")
      parts.push(`kind: ${kindLabel(state.filter.kind)}`);
    if (state.filter.query.trim())
      parts.push(`search "${state.filter.query.trim()}"`);
    return parts.join(" \xB7 ");
  };
  const openProject = (id) => () => void actions.openProject(id);
  const openKindPicker = () => {
    const items = [{
      id: "all",
      title: "All kinds",
      marker: state.filter.kind === "all" ? "\u25CF" : " "
    }, ...WORKSPACE_KINDS.map((kind) => ({
      id: kind,
      title: kindLabel(kind),
      marker: state.filter.kind === kind ? "\u25CF" : " ",
      markerColor: theme.primary
    }))];
    dialog.replace(() => createComponent2(SelectDialog, {
      title: "Filter by kind",
      placeholder: "Search kinds",
      items,
      get selectedId() {
        return state.filter.kind;
      },
      get query() {
        return kindQuery();
      },
      onQuery: setKindQuery,
      onSelect: (item) => {
        actions.setFilter({
          kind: item.id
        });
        dialog.clear();
      },
      onClose: () => dialog.clear(),
      footer: "Choose a project kind to filter the list."
    }), {
      size: "large",
      onClose: () => dialog.clear()
    });
  };
  const newProject = () => actions.openDialog({
    kind: "create"
  });
  useKeyboard((key) => {
    if (state.dialog || dialog.stack().length > 0)
      return;
    if (searchActive()) {
      if (key.name === "enter" || key.name === "return") {
        key.preventDefault();
        key.stopPropagation();
        setSearchActive(false);
      }
      return;
    }
    if (key.name === "up") {
      key.preventDefault();
      key.stopPropagation();
      setSelected((value) => Math.max(0, value - 1));
      return;
    }
    if (key.name === "down") {
      key.preventDefault();
      key.stopPropagation();
      setSelected((value) => Math.min(Math.max(0, sorted().length - 1), value + 1));
      return;
    }
    if (key.name === "enter" || key.name === "return") {
      key.preventDefault();
      key.stopPropagation();
      const project = sorted()[selected()];
      if (project)
        actions.openProject(project.id);
      return;
    }
    if (key.name === "/") {
      key.preventDefault();
      key.stopPropagation();
      setSearchActive(true);
      return;
    }
    if (key.ctrl && key.name === "f") {
      key.preventDefault();
      key.stopPropagation();
      setSearchActive(true);
      return;
    }
    if (key.name === "n" || key.ctrl && key.name === "n") {
      key.preventDefault();
      key.stopPropagation();
      newProject();
      return;
    }
  });
  const onGlobalEscape = (key) => {
    if (state.dialog)
      return;
    if (key.name !== "escape")
      return;
    if (dialog.stack().length > 0) {
      key.preventDefault();
      key.stopPropagation();
      dialog.clear();
      return;
    }
    if (state.route.name === "projects" && searchActive()) {
      key.preventDefault();
      key.stopPropagation();
      actions.setFilter({
        query: ""
      });
      setSearchActive(false);
    }
  };
  onMount(() => renderer.keyInput.prependListener("keypress", onGlobalEscape));
  onCleanup(() => renderer.keyInput.off("keypress", onGlobalEscape));
  return (() => {
    var _el$10 = createElement("box"), _el$11 = createElement("box"), _el$12 = createElement("box"), _el$13 = createElement("input"), _el$14 = createElement("box");
    insertNode(_el$10, _el$11);
    insertNode(_el$10, _el$14);
    setProp(_el$10, "width", "100%");
    setProp(_el$10, "height", "100%");
    setProp(_el$10, "flexDirection", "column");
    setProp(_el$10, "paddingTop", 1);
    setProp(_el$10, "paddingLeft", 2);
    setProp(_el$10, "paddingRight", 2);
    insertNode(_el$11, _el$12);
    setProp(_el$11, "width", "100%");
    setProp(_el$11, "height", 1);
    setProp(_el$11, "flexShrink", 0);
    setProp(_el$11, "flexDirection", "row");
    setProp(_el$11, "columnGap", 1);
    insertNode(_el$12, _el$13);
    setProp(_el$12, "flexGrow", 1);
    setProp(_el$12, "flexShrink", 1);
    setProp(_el$12, "minWidth", 0);
    setProp(_el$12, "height", 1);
    setProp(_el$12, "onMouseUp", (event) => {
      if (event.button !== 0)
        return;
      event.stopPropagation();
      setSearchActive(true);
    });
    setProp(_el$13, "placeholder", "Search projects  (Ctrl+F)");
    setProp(_el$13, "width", "100%");
    setProp(_el$13, "onInput", (value) => actions.setFilter({
      query: value
    }));
    insert(_el$11, createComponent2(Button, {
      label: "New project",
      tone: "primary",
      onPress: newProject
    }), null);
    setProp(_el$14, "width", "100%");
    setProp(_el$14, "flexDirection", "row");
    setProp(_el$14, "flexWrap", "wrap");
    setProp(_el$14, "flexShrink", 0);
    setProp(_el$14, "columnGap", 1);
    setProp(_el$14, "rowGap", 1);
    setProp(_el$14, "marginTop", 1);
    setProp(_el$14, "marginBottom", 1);
    insert(_el$14, createComponent2(Button, {
      label: "All",
      get active() {
        return state.filter.status === "all";
      },
      onPress: () => actions.setFilter({
        status: "all"
      })
    }), null);
    insert(_el$14, createComponent2(Button, {
      label: "Active",
      get active() {
        return state.filter.status === "active";
      },
      onPress: () => actions.setFilter({
        status: "active"
      })
    }), null);
    insert(_el$14, createComponent2(Button, {
      label: "Archived",
      get active() {
        return state.filter.status === "archived";
      },
      onPress: () => actions.setFilter({
        status: "archived"
      })
    }), null);
    insert(_el$14, createComponent2(Button, {
      get label() {
        return memo2(() => state.filter.kind === "all")() ? "All kinds" : kindLabel(state.filter.kind);
      },
      get active() {
        return state.filter.kind !== "all";
      },
      onPress: openKindPicker
    }), null);
    insert(_el$10, createComponent2(Show, {
      get when() {
        return sorted().length > 0;
      },
      get children() {
        return [(() => {
          var _el$15 = createElement("text");
          setProp(_el$15, "flexShrink", 0);
          insert(_el$15, countCaption);
          effect((_$p) => setProp(_el$15, "fg", theme.textMuted, _$p));
          return _el$15;
        })(), (() => {
          var _el$16 = createElement("box"), _el$17 = createElement("box"), _el$18 = createElement("text"), _el$20 = createElement("box"), _el$21 = createElement("text"), _el$23 = createElement("box"), _el$24 = createElement("text"), _el$26 = createElement("box"), _el$27 = createElement("text"), _el$29 = createElement("box"), _el$30 = createElement("text");
          insertNode(_el$16, _el$17);
          insertNode(_el$16, _el$20);
          insertNode(_el$16, _el$23);
          insertNode(_el$16, _el$26);
          insertNode(_el$16, _el$29);
          setProp(_el$16, "height", 1);
          setProp(_el$16, "flexDirection", "row");
          setProp(_el$16, "columnGap", 1);
          setProp(_el$16, "paddingLeft", 1);
          setProp(_el$16, "marginTop", 1);
          insertNode(_el$17, _el$18);
          setProp(_el$17, "flexShrink", 0);
          insertNode(_el$18, createTextNode(`Slug`));
          insertNode(_el$20, _el$21);
          setProp(_el$20, "flexShrink", 0);
          insertNode(_el$21, createTextNode(`Status`));
          insertNode(_el$23, _el$24);
          setProp(_el$23, "flexShrink", 0);
          insertNode(_el$24, createTextNode(`Stage`));
          insertNode(_el$26, _el$27);
          setProp(_el$26, "flexShrink", 0);
          insertNode(_el$27, createTextNode(`H`));
          insertNode(_el$29, _el$30);
          setProp(_el$29, "flexShrink", 0);
          insertNode(_el$30, createTextNode(`Path`));
          effect((_p$) => {
            var _v$11 = columns().slug, _v$12 = theme.textMuted, _v$13 = columns().status, _v$14 = theme.textMuted, _v$15 = columns().stage, _v$16 = theme.textMuted, _v$17 = columns().health, _v$18 = theme.textMuted, _v$19 = columns().path, _v$20 = theme.textMuted;
            _v$11 !== _p$.e && (_p$.e = setProp(_el$17, "width", _v$11, _p$.e));
            _v$12 !== _p$.t && (_p$.t = setProp(_el$18, "fg", _v$12, _p$.t));
            _v$13 !== _p$.a && (_p$.a = setProp(_el$20, "width", _v$13, _p$.a));
            _v$14 !== _p$.o && (_p$.o = setProp(_el$21, "fg", _v$14, _p$.o));
            _v$15 !== _p$.i && (_p$.i = setProp(_el$23, "width", _v$15, _p$.i));
            _v$16 !== _p$.n && (_p$.n = setProp(_el$24, "fg", _v$16, _p$.n));
            _v$17 !== _p$.s && (_p$.s = setProp(_el$26, "width", _v$17, _p$.s));
            _v$18 !== _p$.h && (_p$.h = setProp(_el$27, "fg", _v$18, _p$.h));
            _v$19 !== _p$.r && (_p$.r = setProp(_el$29, "width", _v$19, _p$.r));
            _v$20 !== _p$.d && (_p$.d = setProp(_el$30, "fg", _v$20, _p$.d));
            return _p$;
          }, {
            e: undefined,
            t: undefined,
            a: undefined,
            o: undefined,
            i: undefined,
            n: undefined,
            s: undefined,
            h: undefined,
            r: undefined,
            d: undefined
          });
          return _el$16;
        })()];
      }
    }), null);
    insert(_el$10, createComponent2(Show, {
      get when() {
        return sorted().length === 0;
      },
      get fallback() {
        return (() => {
          var _el$34 = createElement("scrollbox");
          setProp(_el$34, "flexGrow", 1);
          setProp(_el$34, "minHeight", 0);
          setProp(_el$34, "width", "100%");
          setProp(_el$34, "scrollX", false);
          insert(_el$34, createComponent2(For, {
            get each() {
              return sorted();
            },
            children: (project, index) => createComponent2(ProjectRow, {
              project,
              get selected() {
                return selected() === index();
              },
              get columns() {
                return columns();
              },
              get onPress() {
                return openProject(project.id);
              }
            })
          }));
          effect((_$p) => setProp(_el$34, "verticalScrollbarOptions", {
            trackOptions: {
              backgroundColor: theme.backgroundElement,
              foregroundColor: theme.borderActive
            }
          }, _$p));
          return _el$34;
        })();
      },
      get children() {
        return createComponent2(EmptyState, {
          fill: true,
          get icon() {
            return state.error ? "!" : "\u25CE";
          },
          get title() {
            return emptyTitle();
          },
          get detail() {
            return emptyDetail();
          },
          get children() {
            return createComponent2(Show, {
              get when() {
                return !state.loading;
              },
              get children() {
                var _el$32 = createElement("box");
                setProp(_el$32, "flexDirection", "row");
                setProp(_el$32, "flexWrap", "wrap");
                setProp(_el$32, "justifyContent", "center");
                setProp(_el$32, "columnGap", 1);
                setProp(_el$32, "rowGap", 1);
                insert(_el$32, createComponent2(Show, {
                  get when() {
                    return state.error;
                  },
                  get children() {
                    return createComponent2(Button, {
                      label: "Try again",
                      tone: "primary",
                      onPress: () => void actions.load()
                    });
                  }
                }), null);
                insert(_el$32, createComponent2(Show, {
                  get when() {
                    return memo2(() => !!!state.error)() && hasFilters();
                  },
                  get children() {
                    return createComponent2(Button, {
                      label: "Clear filters",
                      onPress: () => actions.setFilter({
                        status: "all",
                        kind: "all",
                        query: ""
                      })
                    });
                  }
                }), null);
                insert(_el$32, createComponent2(Show, {
                  get when() {
                    return memo2(() => !!!state.error)() && !hasFilters();
                  },
                  get children() {
                    return createComponent2(Button, {
                      label: "New project",
                      tone: "primary",
                      onPress: newProject
                    });
                  }
                }), null);
                return _el$32;
              }
            });
          }
        });
      }
    }), null);
    insert(_el$10, createComponent2(Show, {
      get when() {
        return memo2(() => !!state.error)() && sorted().length > 0;
      },
      get children() {
        var _el$33 = createElement("text");
        setProp(_el$33, "flexShrink", 0);
        setProp(_el$33, "wrapMode", "none");
        insert(_el$33, () => state.error);
        effect((_$p) => setProp(_el$33, "fg", theme.error, _$p));
        return _el$33;
      }
    }), null);
    effect((_p$) => {
      var _v$21 = theme.background, _v$22 = searchActive(), _v$23 = state.filter.query, _v$24 = theme.text, _v$25 = searchActive() ? theme.backgroundActive : theme.backgroundElement, _v$26 = theme.text, _v$27 = theme.backgroundActive, _v$28 = theme.textMuted, _v$29 = theme.text;
      _v$21 !== _p$.e && (_p$.e = setProp(_el$10, "backgroundColor", _v$21, _p$.e));
      _v$22 !== _p$.t && (_p$.t = setProp(_el$13, "focused", _v$22, _p$.t));
      _v$23 !== _p$.a && (_p$.a = setProp(_el$13, "value", _v$23, _p$.a));
      _v$24 !== _p$.o && (_p$.o = setProp(_el$13, "textColor", _v$24, _p$.o));
      _v$25 !== _p$.i && (_p$.i = setProp(_el$13, "backgroundColor", _v$25, _p$.i));
      _v$26 !== _p$.n && (_p$.n = setProp(_el$13, "focusedTextColor", _v$26, _p$.n));
      _v$27 !== _p$.s && (_p$.s = setProp(_el$13, "focusedBackgroundColor", _v$27, _p$.s));
      _v$28 !== _p$.h && (_p$.h = setProp(_el$13, "placeholderColor", _v$28, _p$.h));
      _v$29 !== _p$.r && (_p$.r = setProp(_el$13, "cursorColor", _v$29, _p$.r));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined,
      s: undefined,
      h: undefined,
      r: undefined
    });
    return _el$10;
  })();
}
var init_projects_list = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_dialog();
  init_primitives();
  init_select_dialog();
  init_format();
  init_data();
  init_types();
  init_sidebar();
});

// src/cli/tui-solid/component/project-detail.tsx
import { TextAttributes as TextAttributes7 } from "@opentui/core";
function statusFg2(theme, status) {
  if (status === "active")
    return theme.success;
  if (status === "archived")
    return theme.textMuted;
  return theme.error;
}
function DetailLine(props) {
  const theme = useTheme();
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$4 = createElement("box"), _el$5 = createElement("text");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$4);
    setProp(_el$, "width", "100%");
    setProp(_el$, "flexDirection", "row");
    setProp(_el$, "columnGap", 1);
    setProp(_el$, "flexShrink", 0);
    insertNode(_el$2, _el$3);
    setProp(_el$2, "width", 14);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$3, "wrapMode", "none");
    insert(_el$3, () => props.label);
    insertNode(_el$4, _el$5);
    setProp(_el$4, "flexGrow", 1);
    setProp(_el$4, "flexShrink", 1);
    setProp(_el$4, "minWidth", 0);
    setProp(_el$5, "wrapMode", "word");
    insert(_el$5, () => props.value);
    effect((_p$) => {
      var _v$ = theme.textMuted, _v$2 = props.valueFg ? props.valueFg(theme) : theme.text;
      _v$ !== _p$.e && (_p$.e = setProp(_el$3, "fg", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$5, "fg", _v$2, _p$.t));
      return _p$;
    }, {
      e: undefined,
      t: undefined
    });
    return _el$;
  })();
}
function ProjectDetailRoute() {
  const projects = useProjects();
  const {
    state,
    actions
  } = projects;
  const theme = useTheme();
  const dialog = useDialog();
  const dimensions = useTerminalDimensions();
  const contentWidth = () => Math.max(24, dimensions().width - sidebarWidth(dimensions().width) - 6);
  const project = () => state.selected;
  const mgmt = createMemo(() => project() ? managementView(project()) : null);
  onMount(() => {
    if (!state.loading && !state.error && state.roots.length === 0)
      actions.load();
  });
  const rootName = (rootId) => {
    if (!rootId)
      return "-";
    return state.roots.find((root) => root.id === rootId)?.name ?? rootId;
  };
  const recipeName = (recipeId) => {
    if (!recipeId)
      return "-";
    return state.recipes.find((recipe) => recipe.id === recipeId)?.name ?? recipeId;
  };
  const sortedEvents = createMemo(() => [...state.events].sort((a, b) => b.created_at.localeCompare(a.created_at)).slice(0, 25));
  const integrations = createMemo(() => {
    const sel = project();
    if (!sel)
      return [];
    return Object.entries(sel.integrations).filter((entry) => typeof entry[1] === "string" && entry[1].length > 0);
  });
  const confirmArchive = (sel) => () => actions.openDialog({
    kind: sel.status === "archived" ? "confirm-unarchive" : "confirm-archive",
    project: sel
  });
  const confirmDelete = (sel) => () => actions.openDialog({
    kind: "confirm-delete",
    project: sel
  });
  useKeyboard((key) => {
    if (state.dialog || dialog.stack().length > 0)
      return;
    if (key.name === "escape" || key.name === "backspace") {
      key.preventDefault();
      key.stopPropagation();
      actions.navigate({
        name: "projects"
      });
      return;
    }
    if (key.name === "r") {
      key.preventDefault();
      key.stopPropagation();
      actions.refreshSelected();
      return;
    }
    const sel = project();
    if (!sel)
      return;
    if (key.name === "e") {
      key.preventDefault();
      key.stopPropagation();
      actions.openDialog({
        kind: "edit",
        project: sel
      });
      return;
    }
    if (key.name === "a") {
      key.preventDefault();
      key.stopPropagation();
      actions.openDialog({
        kind: sel.status === "archived" ? "confirm-unarchive" : "confirm-archive",
        project: sel
      });
      return;
    }
    if (key.name === "d" || key.name === "delete") {
      key.preventDefault();
      key.stopPropagation();
      actions.openDialog({
        kind: "confirm-delete",
        project: sel
      });
    }
  });
  return (() => {
    var _el$6 = createElement("box");
    setProp(_el$6, "width", "100%");
    setProp(_el$6, "height", "100%");
    setProp(_el$6, "flexDirection", "column");
    setProp(_el$6, "paddingTop", 1);
    setProp(_el$6, "paddingLeft", 2);
    setProp(_el$6, "paddingRight", 2);
    insert(_el$6, createComponent2(Show, {
      get when() {
        return project();
      },
      get fallback() {
        return createComponent2(EmptyState, {
          fill: true,
          get title() {
            return memo2(() => !!state.selectedLoading)() ? "Loading project\u2026" : state.error ? "Couldn't load project" : "No project selected";
          },
          get detail() {
            return memo2(() => !!state.selectedLoading)() ? "Fetching project details\u2026" : state.error ?? "Open a project from the list.";
          },
          get children() {
            return createComponent2(Show, {
              get when() {
                return !state.selectedLoading;
              },
              get children() {
                return createComponent2(Button, {
                  label: "\u2190 Back",
                  onPress: () => void actions.navigate({
                    name: "projects"
                  })
                });
              }
            });
          }
        });
      },
      children: (sel) => [(() => {
        var _el$7 = createElement("box"), _el$8 = createElement("box"), _el$9 = createElement("text"), _el$0 = createElement("box"), _el$1 = createElement("text"), _el$10 = createElement("box"), _el$11 = createElement("text");
        insertNode(_el$7, _el$8);
        insertNode(_el$7, _el$0);
        insertNode(_el$7, _el$10);
        setProp(_el$7, "width", "100%");
        setProp(_el$7, "height", 1);
        setProp(_el$7, "flexShrink", 0);
        setProp(_el$7, "flexDirection", "row");
        setProp(_el$7, "columnGap", 1);
        insert(_el$7, createComponent2(Button, {
          label: "\u2190 Back",
          onPress: () => void actions.navigate({
            name: "projects"
          })
        }), _el$8);
        insertNode(_el$8, _el$9);
        setProp(_el$8, "flexShrink", 1);
        setProp(_el$8, "minWidth", 0);
        setProp(_el$8, "flexGrow", 1);
        setProp(_el$9, "wrapMode", "none");
        insert(_el$9, () => truncate(sel().name, Math.max(12, Math.floor(contentWidth() * 0.5))));
        insertNode(_el$0, _el$1);
        setProp(_el$0, "flexShrink", 0);
        setProp(_el$1, "wrapMode", "none");
        insert(_el$1, () => sel().slug);
        insertNode(_el$10, _el$11);
        setProp(_el$10, "flexShrink", 0);
        setProp(_el$11, "wrapMode", "none");
        insert(_el$11, () => statusLabel(sel().status));
        effect((_p$) => {
          var _v$3 = theme.text, _v$4 = TextAttributes7.BOLD, _v$5 = theme.textMuted, _v$6 = statusFg2(theme, sel().status);
          _v$3 !== _p$.e && (_p$.e = setProp(_el$9, "fg", _v$3, _p$.e));
          _v$4 !== _p$.t && (_p$.t = setProp(_el$9, "attributes", _v$4, _p$.t));
          _v$5 !== _p$.a && (_p$.a = setProp(_el$1, "fg", _v$5, _p$.a));
          _v$6 !== _p$.o && (_p$.o = setProp(_el$11, "fg", _v$6, _p$.o));
          return _p$;
        }, {
          e: undefined,
          t: undefined,
          a: undefined,
          o: undefined
        });
        return _el$7;
      })(), (() => {
        var _el$12 = createElement("box");
        setProp(_el$12, "width", "100%");
        setProp(_el$12, "flexDirection", "row");
        setProp(_el$12, "flexWrap", "wrap");
        setProp(_el$12, "flexShrink", 0);
        setProp(_el$12, "columnGap", 1);
        setProp(_el$12, "rowGap", 1);
        setProp(_el$12, "marginTop", 1);
        insert(_el$12, createComponent2(Button, {
          label: "Edit",
          onPress: () => actions.openDialog({
            kind: "edit",
            project: sel()
          })
        }), null);
        insert(_el$12, createComponent2(Button, {
          get label() {
            return sel().status === "archived" ? "Unarchive" : "Archive";
          },
          get onPress() {
            return confirmArchive(sel());
          }
        }), null);
        insert(_el$12, createComponent2(Button, {
          label: "Delete",
          tone: "danger",
          get onPress() {
            return confirmDelete(sel());
          }
        }), null);
        insert(_el$12, createComponent2(Show, {
          get when() {
            return state.selectedLoading;
          },
          get children() {
            var _el$13 = createElement("text");
            insertNode(_el$13, createTextNode(`Refreshing\u2026`));
            effect((_$p) => setProp(_el$13, "fg", theme.textMuted, _$p));
            return _el$13;
          }
        }), null);
        return _el$12;
      })(), (() => {
        var _el$15 = createElement("scrollbox"), _el$16 = createElement("text");
        insertNode(_el$15, _el$16);
        setProp(_el$15, "flexGrow", 1);
        setProp(_el$15, "minHeight", 0);
        setProp(_el$15, "width", "100%");
        setProp(_el$15, "scrollX", false);
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Description"
        }), _el$16);
        setProp(_el$16, "wrapMode", "word");
        setProp(_el$16, "width", "100%");
        insert(_el$16, () => sel().description || "\u2014");
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Management"
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Stage",
          get value() {
            return memo2(() => !!mgmt()?.stage)() ? stageLabel(mgmt().stage) ?? mgmt().stage : "-";
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Priority",
          get value() {
            return memo2(() => !!mgmt()?.priority)() ? priorityLabel(mgmt().priority) ?? mgmt().priority : "-";
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Owner",
          get value() {
            return mgmt()?.owner ?? "-";
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Health",
          get value() {
            return mgmt()?.health ?? "unknown";
          },
          valueFg: (t) => mgmt()?.health === "ok" ? t.success : mgmt()?.health === "missing" ? t.error : mgmt()?.health === "untracked" ? t.warning : t.textMuted
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Created",
          get value() {
            return formatDateTime(sel().created_at);
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Updated",
          get value() {
            return `${formatDateTime(sel().updated_at)} (${formatRelativeTime(sel().updated_at)})`;
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Last opened",
          get value() {
            return memo2(() => !!mgmt()?.lastOpenedAt)() ? `${formatDateTime(mgmt().lastOpenedAt)} (${formatRelativeTime(mgmt().lastOpenedAt)})` : "never";
          }
        }), null);
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Kind & Registry"
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Kind",
          get value() {
            return kindLabel(sel().kind);
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Root",
          get value() {
            return rootName(sel().root_id);
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Recipe",
          get value() {
            return recipeName(sel().recipe_id);
          }
        }), null);
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Path & Remote"
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Primary path",
          get value() {
            return sel().primary_path ?? "\u2014";
          }
        }), null);
        insert(_el$15, createComponent2(DetailLine, {
          label: "Git remote",
          get value() {
            return sel().git_remote ?? "\u2014";
          }
        }), null);
        insert(_el$15, createComponent2(Show, {
          get when() {
            return sel().tags.length > 0;
          },
          get children() {
            return [createComponent2(SectionHeader, {
              label: "Tags"
            }), (() => {
              var _el$17 = createElement("box");
              setProp(_el$17, "width", "100%");
              setProp(_el$17, "flexDirection", "row");
              setProp(_el$17, "flexWrap", "wrap");
              setProp(_el$17, "columnGap", 1);
              setProp(_el$17, "rowGap", 1);
              insert(_el$17, createComponent2(For, {
                get each() {
                  return sel().tags;
                },
                children: (tag) => (() => {
                  var _el$18 = createElement("text");
                  insert(_el$18, tag);
                  effect((_$p) => setProp(_el$18, "fg", labelColor(theme, tag), _$p));
                  return _el$18;
                })()
              }));
              return _el$17;
            })()];
          }
        }), null);
        insert(_el$15, createComponent2(Show, {
          get when() {
            return integrations().length > 0;
          },
          get children() {
            return [createComponent2(SectionHeader, {
              label: "Integrations"
            }), createComponent2(For, {
              get each() {
                return integrations();
              },
              children: (entry) => (() => {
                var _el$19 = createElement("text"), _el$20 = createTextNode(`: `);
                insertNode(_el$19, _el$20);
                setProp(_el$19, "wrapMode", "none");
                setProp(_el$19, "width", "100%");
                insert(_el$19, () => entry[0], _el$20);
                insert(_el$19, () => truncate(entry[1], Math.max(8, contentWidth() - 20)), null);
                effect((_$p) => setProp(_el$19, "fg", theme.textMuted, _$p));
                return _el$19;
              })()
            })];
          }
        }), null);
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Locations"
        }), null);
        insert(_el$15, createComponent2(Show, {
          get when() {
            return state.locations.length > 0;
          },
          get fallback() {
            return (() => {
              var _el$21 = createElement("text");
              insertNode(_el$21, createTextNode(`No registered locations.`));
              effect((_$p) => setProp(_el$21, "fg", theme.textMuted, _$p));
              return _el$21;
            })();
          },
          get children() {
            return createComponent2(For, {
              get each() {
                return state.locations;
              },
              children: (location) => (() => {
                var _el$23 = createElement("box"), _el$24 = createElement("box"), _el$25 = createElement("text"), _el$26 = createElement("box"), _el$27 = createElement("text");
                insertNode(_el$23, _el$24);
                insertNode(_el$23, _el$26);
                setProp(_el$23, "width", "100%");
                setProp(_el$23, "flexDirection", "row");
                setProp(_el$23, "columnGap", 1);
                setProp(_el$23, "flexShrink", 0);
                insertNode(_el$24, _el$25);
                setProp(_el$24, "flexShrink", 1);
                setProp(_el$24, "minWidth", 0);
                setProp(_el$24, "flexGrow", 1);
                setProp(_el$25, "wrapMode", "none");
                insert(_el$25, () => truncate(location.path, Math.max(8, Math.floor(contentWidth() * 0.6))));
                insertNode(_el$26, _el$27);
                setProp(_el$26, "flexShrink", 0);
                setProp(_el$27, "wrapMode", "none");
                insert(_el$27, () => location.machine_id);
                insert(_el$23, createComponent2(Show, {
                  get when() {
                    return location.is_primary;
                  },
                  get children() {
                    var _el$28 = createElement("box"), _el$29 = createElement("text");
                    insertNode(_el$28, _el$29);
                    setProp(_el$28, "flexShrink", 0);
                    insertNode(_el$29, createTextNode(`\u2605 primary`));
                    effect((_$p) => setProp(_el$29, "fg", theme.primary, _$p));
                    return _el$28;
                  }
                }), null);
                effect((_p$) => {
                  var { text: _v$9, textMuted: _v$0 } = theme;
                  _v$9 !== _p$.e && (_p$.e = setProp(_el$25, "fg", _v$9, _p$.e));
                  _v$0 !== _p$.t && (_p$.t = setProp(_el$27, "fg", _v$0, _p$.t));
                  return _p$;
                }, {
                  e: undefined,
                  t: undefined
                });
                return _el$23;
              })()
            });
          }
        }), null);
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Agents"
        }), null);
        insert(_el$15, createComponent2(Show, {
          get when() {
            return state.assignments.length > 0;
          },
          get fallback() {
            return (() => {
              var _el$31 = createElement("text");
              insertNode(_el$31, createTextNode(`No agents assigned.`));
              effect((_$p) => setProp(_el$31, "fg", theme.textMuted, _$p));
              return _el$31;
            })();
          },
          get children() {
            return createComponent2(For, {
              get each() {
                return state.assignments;
              },
              children: (assignment) => (() => {
                var _el$33 = createElement("box"), _el$34 = createElement("box"), _el$35 = createElement("text"), _el$36 = createElement("box"), _el$37 = createElement("text");
                insertNode(_el$33, _el$34);
                insertNode(_el$33, _el$36);
                setProp(_el$33, "width", "100%");
                setProp(_el$33, "flexDirection", "row");
                setProp(_el$33, "columnGap", 1);
                setProp(_el$33, "flexShrink", 0);
                insertNode(_el$34, _el$35);
                setProp(_el$34, "flexShrink", 1);
                setProp(_el$34, "minWidth", 0);
                setProp(_el$34, "flexGrow", 1);
                setProp(_el$35, "wrapMode", "none");
                insert(_el$35, () => truncate(assignment.agent?.name ?? assignment.agent_id, 40));
                insertNode(_el$36, _el$37);
                setProp(_el$36, "flexShrink", 0);
                setProp(_el$37, "wrapMode", "none");
                insert(_el$37, () => assignment.role);
                effect((_p$) => {
                  var { text: _v$1, textMuted: _v$10 } = theme;
                  _v$1 !== _p$.e && (_p$.e = setProp(_el$35, "fg", _v$1, _p$.e));
                  _v$10 !== _p$.t && (_p$.t = setProp(_el$37, "fg", _v$10, _p$.t));
                  return _p$;
                }, {
                  e: undefined,
                  t: undefined
                });
                return _el$33;
              })()
            });
          }
        }), null);
        insert(_el$15, createComponent2(SectionHeader, {
          label: "Events"
        }), null);
        insert(_el$15, createComponent2(Show, {
          get when() {
            return sortedEvents().length > 0;
          },
          get fallback() {
            return (() => {
              var _el$38 = createElement("text");
              insertNode(_el$38, createTextNode(`No recorded events.`));
              effect((_$p) => setProp(_el$38, "fg", theme.textMuted, _$p));
              return _el$38;
            })();
          },
          get children() {
            return createComponent2(For, {
              get each() {
                return sortedEvents();
              },
              children: (event) => (() => {
                var _el$40 = createElement("box"), _el$41 = createElement("box"), _el$42 = createElement("text"), _el$43 = createElement("box"), _el$44 = createElement("text"), _el$45 = createElement("box"), _el$46 = createElement("text");
                insertNode(_el$40, _el$41);
                insertNode(_el$40, _el$43);
                insertNode(_el$40, _el$45);
                setProp(_el$40, "width", "100%");
                setProp(_el$40, "flexDirection", "row");
                setProp(_el$40, "columnGap", 1);
                setProp(_el$40, "flexShrink", 0);
                insertNode(_el$41, _el$42);
                setProp(_el$41, "width", 14);
                setProp(_el$41, "flexShrink", 0);
                setProp(_el$42, "wrapMode", "none");
                insert(_el$42, () => truncate(formatRelativeTime(event.created_at), 14));
                insertNode(_el$43, _el$44);
                setProp(_el$43, "flexShrink", 1);
                setProp(_el$43, "minWidth", 0);
                setProp(_el$43, "flexGrow", 1);
                setProp(_el$44, "wrapMode", "none");
                insert(_el$44, () => truncate(event.event_type, 48));
                insertNode(_el$45, _el$46);
                setProp(_el$45, "flexShrink", 0);
                setProp(_el$46, "wrapMode", "none");
                insert(_el$46, () => event.source);
                effect((_p$) => {
                  var { textMuted: _v$11, text: _v$12, textMuted: _v$13 } = theme;
                  _v$11 !== _p$.e && (_p$.e = setProp(_el$42, "fg", _v$11, _p$.e));
                  _v$12 !== _p$.t && (_p$.t = setProp(_el$44, "fg", _v$12, _p$.t));
                  _v$13 !== _p$.a && (_p$.a = setProp(_el$46, "fg", _v$13, _p$.a));
                  return _p$;
                }, {
                  e: undefined,
                  t: undefined,
                  a: undefined
                });
                return _el$40;
              })()
            });
          }
        }), null);
        effect((_p$) => {
          var _v$7 = {
            trackOptions: {
              backgroundColor: theme.backgroundElement,
              foregroundColor: theme.borderActive
            }
          }, _v$8 = theme.text;
          _v$7 !== _p$.e && (_p$.e = setProp(_el$15, "verticalScrollbarOptions", _v$7, _p$.e));
          _v$8 !== _p$.t && (_p$.t = setProp(_el$16, "fg", _v$8, _p$.t));
          return _p$;
        }, {
          e: undefined,
          t: undefined
        });
        return _el$15;
      })()]
    }));
    effect((_$p) => setProp(_el$6, "backgroundColor", theme.background, _$p));
    return _el$6;
  })();
}
var init_project_detail = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_dialog();
  init_primitives();
  init_format();
  init_data();
  init_sidebar();
});

// src/cli/tui-solid/component/roots.tsx
import { TextAttributes as TextAttributes8 } from "@opentui/core";
function RootsRoute() {
  const projects = useProjects();
  const {
    state
  } = projects;
  const theme = useTheme();
  const toast = useToast();
  const dimensions = useTerminalDimensions();
  const [name, setName] = createSignal("");
  const [basePath, setBasePath] = createSignal("");
  const [field, setField] = createSignal("name");
  const contentWidth = () => Math.max(24, dimensions().width - sidebarWidth(dimensions().width) - 6);
  useKeyboard((key) => {
    if (state.dialog)
      return;
    if (key.name !== "tab")
      return;
    key.preventDefault();
    key.stopPropagation();
    setField((current) => current === "name" ? "basePath" : "name");
  });
  const addRoot = () => {
    const value = name().trim();
    if (!value) {
      toast.show({
        title: "Name required",
        message: "Enter a root name before adding.",
        tone: "error"
      });
      return;
    }
    toast.show({
      title: "Roots are managed via the CLI",
      message: `Run: projects roots add --name "${value}" --path "${basePath().trim() || "<base-path>"}"`,
      tone: "info"
    });
  };
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$5 = createElement("text"), _el$6 = createTextNode(` registered`), _el$7 = createElement("box"), _el$8 = createElement("text"), _el$0 = createElement("box"), _el$1 = createElement("box"), _el$10 = createElement("text"), _el$12 = createElement("box"), _el$13 = createElement("input"), _el$14 = createElement("box"), _el$15 = createElement("box"), _el$16 = createElement("text"), _el$18 = createElement("box"), _el$19 = createElement("input"), _el$20 = createElement("box"), _el$22 = createElement("text");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$7);
    insertNode(_el$, _el$22);
    setProp(_el$, "width", "100%");
    setProp(_el$, "height", "100%");
    setProp(_el$, "flexDirection", "column");
    setProp(_el$, "paddingTop", 1);
    setProp(_el$, "paddingLeft", 2);
    setProp(_el$, "paddingRight", 2);
    insertNode(_el$2, _el$3);
    insertNode(_el$2, _el$5);
    setProp(_el$2, "width", "100%");
    setProp(_el$2, "height", 1);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$2, "flexDirection", "row");
    setProp(_el$2, "justifyContent", "space-between");
    setProp(_el$2, "columnGap", 1);
    insertNode(_el$3, createTextNode(`Roots`));
    insertNode(_el$5, _el$6);
    insert(_el$5, () => state.roots.length, _el$6);
    insertNode(_el$7, _el$8);
    insertNode(_el$7, _el$0);
    insertNode(_el$7, _el$14);
    insertNode(_el$7, _el$20);
    setProp(_el$7, "width", "100%");
    setProp(_el$7, "flexDirection", "column");
    setProp(_el$7, "flexShrink", 0);
    setProp(_el$7, "rowGap", 1);
    setProp(_el$7, "marginTop", 1);
    setProp(_el$7, "paddingTop", 1);
    setProp(_el$7, "paddingBottom", 1);
    setProp(_el$7, "paddingLeft", 1);
    setProp(_el$7, "paddingRight", 1);
    insertNode(_el$8, createTextNode(`Add a root (name + base path)`));
    insertNode(_el$0, _el$1);
    insertNode(_el$0, _el$12);
    setProp(_el$0, "width", "100%");
    setProp(_el$0, "height", 1);
    setProp(_el$0, "flexDirection", "row");
    setProp(_el$0, "columnGap", 1);
    insertNode(_el$1, _el$10);
    setProp(_el$1, "width", 14);
    setProp(_el$1, "flexShrink", 0);
    insertNode(_el$10, createTextNode(`Name`));
    insertNode(_el$12, _el$13);
    setProp(_el$12, "flexGrow", 1);
    setProp(_el$12, "flexShrink", 1);
    setProp(_el$12, "minWidth", 0);
    setProp(_el$13, "placeholder", "Root name");
    setProp(_el$13, "width", "100%");
    setProp(_el$13, "onInput", setName);
    insertNode(_el$14, _el$15);
    insertNode(_el$14, _el$18);
    setProp(_el$14, "width", "100%");
    setProp(_el$14, "height", 1);
    setProp(_el$14, "flexDirection", "row");
    setProp(_el$14, "columnGap", 1);
    insertNode(_el$15, _el$16);
    setProp(_el$15, "width", 14);
    setProp(_el$15, "flexShrink", 0);
    insertNode(_el$16, createTextNode(`Base path`));
    insertNode(_el$18, _el$19);
    setProp(_el$18, "flexGrow", 1);
    setProp(_el$18, "flexShrink", 1);
    setProp(_el$18, "minWidth", 0);
    setProp(_el$19, "placeholder", "/Users/you/code");
    setProp(_el$19, "width", "100%");
    setProp(_el$19, "onInput", setBasePath);
    setProp(_el$19, "onSubmit", addRoot);
    setProp(_el$20, "height", 1);
    setProp(_el$20, "flexDirection", "row");
    setProp(_el$20, "columnGap", 1);
    insert(_el$20, createComponent2(Button, {
      label: "Add root",
      tone: "primary",
      onPress: addRoot
    }), null);
    insert(_el$20, createComponent2(Button, {
      label: "CLI: projects roots add",
      onPress: () => toast.show({
        title: "CLI management",
        message: "Run `projects roots add --help` for full options.",
        tone: "info"
      })
    }), null);
    insert(_el$, createComponent2(Show, {
      get when() {
        return state.roots.length > 0;
      },
      get fallback() {
        return createComponent2(EmptyState, {
          fill: true,
          title: "No roots",
          detail: "Add a root to register where project repositories live."
        });
      },
      get children() {
        return [createComponent2(SectionHeader, {
          label: "Registered roots",
          get muted() {
            return `${state.roots.length} total`;
          }
        }), (() => {
          var _el$21 = createElement("scrollbox");
          setProp(_el$21, "flexGrow", 1);
          setProp(_el$21, "minHeight", 0);
          setProp(_el$21, "width", "100%");
          setProp(_el$21, "scrollX", false);
          insert(_el$21, createComponent2(For, {
            get each() {
              return state.roots;
            },
            children: (root) => createComponent2(Row, {
              get children() {
                var _el$24 = createElement("box"), _el$25 = createElement("box"), _el$26 = createElement("text"), _el$27 = createElement("box"), _el$28 = createElement("text"), _el$29 = createElement("box"), _el$30 = createElement("text"), _el$31 = createElement("box"), _el$32 = createElement("text");
                insertNode(_el$24, _el$25);
                insertNode(_el$24, _el$27);
                insertNode(_el$24, _el$29);
                insertNode(_el$24, _el$31);
                setProp(_el$24, "width", "100%");
                setProp(_el$24, "flexDirection", "row");
                setProp(_el$24, "columnGap", 1);
                insertNode(_el$25, _el$26);
                setProp(_el$25, "flexShrink", 0);
                setProp(_el$26, "wrapMode", "none");
                insert(_el$26, () => truncate(root.name, Math.max(12, Math.min(24, Math.floor(contentWidth() * 0.25)))));
                insertNode(_el$27, _el$28);
                setProp(_el$27, "width", 18);
                setProp(_el$27, "flexShrink", 0);
                setProp(_el$28, "wrapMode", "none");
                insert(_el$28, () => truncate(root.slug, 18));
                insertNode(_el$29, _el$30);
                setProp(_el$29, "flexGrow", 1);
                setProp(_el$29, "flexShrink", 1);
                setProp(_el$29, "minWidth", 0);
                setProp(_el$30, "wrapMode", "none");
                insert(_el$30, () => truncate(root.base_path, Math.max(8, Math.floor(contentWidth() * 0.35))));
                insertNode(_el$31, _el$32);
                setProp(_el$31, "flexShrink", 0);
                setProp(_el$32, "wrapMode", "none");
                insert(_el$32, (() => {
                  var _c$ = memo2(() => !!root.default_kind);
                  return () => _c$() ? kindLabel(root.default_kind) : "no default kind";
                })());
                effect((_p$) => {
                  var _v$24 = Math.max(12, Math.min(24, Math.floor(contentWidth() * 0.25))), _v$25 = theme.text, _v$26 = TextAttributes8.BOLD, _v$27 = theme.textMuted, _v$28 = theme.textMuted, _v$29 = root.default_kind ? labelColor(theme, root.default_kind) : theme.textFaint;
                  _v$24 !== _p$.e && (_p$.e = setProp(_el$25, "width", _v$24, _p$.e));
                  _v$25 !== _p$.t && (_p$.t = setProp(_el$26, "fg", _v$25, _p$.t));
                  _v$26 !== _p$.a && (_p$.a = setProp(_el$26, "attributes", _v$26, _p$.a));
                  _v$27 !== _p$.o && (_p$.o = setProp(_el$28, "fg", _v$27, _p$.o));
                  _v$28 !== _p$.i && (_p$.i = setProp(_el$30, "fg", _v$28, _p$.i));
                  _v$29 !== _p$.n && (_p$.n = setProp(_el$32, "fg", _v$29, _p$.n));
                  return _p$;
                }, {
                  e: undefined,
                  t: undefined,
                  a: undefined,
                  o: undefined,
                  i: undefined,
                  n: undefined
                });
                return _el$24;
              }
            })
          }));
          effect((_$p) => setProp(_el$21, "verticalScrollbarOptions", {
            trackOptions: {
              backgroundColor: theme.backgroundElement,
              foregroundColor: theme.borderActive
            }
          }, _$p));
          return _el$21;
        })()];
      }
    }), _el$22);
    insertNode(_el$22, createTextNode(`Full management: \`projects roots add\` \xB7 read + add only in the TUI`));
    setProp(_el$22, "flexShrink", 0);
    setProp(_el$22, "marginTop", 1);
    effect((_p$) => {
      var { background: _v$, text: _v$2 } = theme, _v$3 = TextAttributes8.BOLD, _v$4 = theme.textMuted, _v$5 = theme.backgroundElement, _v$6 = theme.textMuted, _v$7 = theme.textMuted, _v$8 = field() === "name", _v$9 = name(), _v$0 = theme.text, _v$1 = field() === "name" ? theme.backgroundActive : theme.backgroundMenu, _v$10 = theme.text, _v$11 = theme.backgroundActive, _v$12 = theme.textMuted, _v$13 = theme.text, _v$14 = theme.textMuted, _v$15 = field() === "basePath", _v$16 = basePath(), _v$17 = theme.text, _v$18 = field() === "basePath" ? theme.backgroundActive : theme.backgroundMenu, _v$19 = theme.text, _v$20 = theme.backgroundActive, _v$21 = theme.textMuted, _v$22 = theme.text, _v$23 = theme.textMuted;
      _v$ !== _p$.e && (_p$.e = setProp(_el$, "backgroundColor", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "fg", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$3, "attributes", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$5, "fg", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$7, "backgroundColor", _v$5, _p$.i));
      _v$6 !== _p$.n && (_p$.n = setProp(_el$8, "fg", _v$6, _p$.n));
      _v$7 !== _p$.s && (_p$.s = setProp(_el$10, "fg", _v$7, _p$.s));
      _v$8 !== _p$.h && (_p$.h = setProp(_el$13, "focused", _v$8, _p$.h));
      _v$9 !== _p$.r && (_p$.r = setProp(_el$13, "value", _v$9, _p$.r));
      _v$0 !== _p$.d && (_p$.d = setProp(_el$13, "textColor", _v$0, _p$.d));
      _v$1 !== _p$.l && (_p$.l = setProp(_el$13, "backgroundColor", _v$1, _p$.l));
      _v$10 !== _p$.u && (_p$.u = setProp(_el$13, "focusedTextColor", _v$10, _p$.u));
      _v$11 !== _p$.c && (_p$.c = setProp(_el$13, "focusedBackgroundColor", _v$11, _p$.c));
      _v$12 !== _p$.w && (_p$.w = setProp(_el$13, "placeholderColor", _v$12, _p$.w));
      _v$13 !== _p$.m && (_p$.m = setProp(_el$13, "cursorColor", _v$13, _p$.m));
      _v$14 !== _p$.f && (_p$.f = setProp(_el$16, "fg", _v$14, _p$.f));
      _v$15 !== _p$.y && (_p$.y = setProp(_el$19, "focused", _v$15, _p$.y));
      _v$16 !== _p$.g && (_p$.g = setProp(_el$19, "value", _v$16, _p$.g));
      _v$17 !== _p$.p && (_p$.p = setProp(_el$19, "textColor", _v$17, _p$.p));
      _v$18 !== _p$.b && (_p$.b = setProp(_el$19, "backgroundColor", _v$18, _p$.b));
      _v$19 !== _p$.T && (_p$.T = setProp(_el$19, "focusedTextColor", _v$19, _p$.T));
      _v$20 !== _p$.A && (_p$.A = setProp(_el$19, "focusedBackgroundColor", _v$20, _p$.A));
      _v$21 !== _p$.O && (_p$.O = setProp(_el$19, "placeholderColor", _v$21, _p$.O));
      _v$22 !== _p$.I && (_p$.I = setProp(_el$19, "cursorColor", _v$22, _p$.I));
      _v$23 !== _p$.S && (_p$.S = setProp(_el$22, "fg", _v$23, _p$.S));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined,
      s: undefined,
      h: undefined,
      r: undefined,
      d: undefined,
      l: undefined,
      u: undefined,
      c: undefined,
      w: undefined,
      m: undefined,
      f: undefined,
      y: undefined,
      g: undefined,
      p: undefined,
      b: undefined,
      T: undefined,
      A: undefined,
      O: undefined,
      I: undefined,
      S: undefined
    });
    return _el$;
  })();
}
var init_roots = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_toast();
  init_primitives();
  init_format();
  init_sidebar();
});

// src/cli/tui-solid/component/recipes.tsx
import { TextAttributes as TextAttributes9 } from "@opentui/core";
function RecipesRoute() {
  const projects = useProjects();
  const {
    state
  } = projects;
  const theme = useTheme();
  const dimensions = useTerminalDimensions();
  const contentWidth = () => Math.max(24, dimensions().width - sidebarWidth(dimensions().width) - 6);
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$5 = createElement("text"), _el$6 = createTextNode(` registered`), _el$8 = createElement("text");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$8);
    setProp(_el$, "width", "100%");
    setProp(_el$, "height", "100%");
    setProp(_el$, "flexDirection", "column");
    setProp(_el$, "paddingTop", 1);
    setProp(_el$, "paddingLeft", 2);
    setProp(_el$, "paddingRight", 2);
    insertNode(_el$2, _el$3);
    insertNode(_el$2, _el$5);
    setProp(_el$2, "width", "100%");
    setProp(_el$2, "height", 1);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$2, "flexDirection", "row");
    setProp(_el$2, "justifyContent", "space-between");
    setProp(_el$2, "columnGap", 1);
    insertNode(_el$3, createTextNode(`Recipes`));
    insertNode(_el$5, _el$6);
    insert(_el$5, () => state.recipes.length, _el$6);
    insert(_el$, createComponent2(Show, {
      get when() {
        return state.recipes.length > 0;
      },
      get fallback() {
        return createComponent2(EmptyState, {
          fill: true,
          title: "No recipes",
          detail: "Recipes let project creation apply a standard scaffold."
        });
      },
      get children() {
        return [createComponent2(SectionHeader, {
          label: "Registered recipes",
          get muted() {
            return `${state.recipes.length} total`;
          }
        }), (() => {
          var _el$7 = createElement("scrollbox");
          setProp(_el$7, "flexGrow", 1);
          setProp(_el$7, "minHeight", 0);
          setProp(_el$7, "width", "100%");
          setProp(_el$7, "scrollX", false);
          insert(_el$7, createComponent2(For, {
            get each() {
              return state.recipes;
            },
            children: (recipe) => createComponent2(Row, {
              get children() {
                var _el$0 = createElement("box"), _el$1 = createElement("box"), _el$10 = createElement("text"), _el$11 = createElement("box"), _el$12 = createElement("text"), _el$13 = createElement("box"), _el$14 = createElement("text"), _el$15 = createElement("box"), _el$16 = createElement("text"), _el$17 = createElement("box"), _el$18 = createElement("text"), _el$19 = createTextNode(`v`);
                insertNode(_el$0, _el$1);
                insertNode(_el$0, _el$11);
                insertNode(_el$0, _el$13);
                insertNode(_el$0, _el$15);
                insertNode(_el$0, _el$17);
                setProp(_el$0, "width", "100%");
                setProp(_el$0, "flexDirection", "row");
                setProp(_el$0, "columnGap", 1);
                insertNode(_el$1, _el$10);
                setProp(_el$1, "flexShrink", 0);
                setProp(_el$10, "wrapMode", "none");
                insert(_el$10, () => truncate(recipe.name, Math.max(12, Math.min(22, Math.floor(contentWidth() * 0.22)))));
                insertNode(_el$11, _el$12);
                setProp(_el$11, "width", 18);
                setProp(_el$11, "flexShrink", 0);
                setProp(_el$12, "wrapMode", "none");
                insert(_el$12, () => truncate(recipe.slug, 18));
                insertNode(_el$13, _el$14);
                setProp(_el$13, "width", 12);
                setProp(_el$13, "flexShrink", 0);
                setProp(_el$14, "wrapMode", "none");
                insert(_el$14, (() => {
                  var _c$ = memo2(() => !!recipe.kind);
                  return () => _c$() ? kindLabel(recipe.kind) : "\u2014";
                })());
                insertNode(_el$15, _el$16);
                setProp(_el$15, "flexGrow", 1);
                setProp(_el$15, "flexShrink", 1);
                setProp(_el$15, "minWidth", 0);
                setProp(_el$16, "wrapMode", "none");
                insert(_el$16, () => truncate(recipe.description ?? "\u2014", Math.max(8, Math.floor(contentWidth() * 0.35))));
                insertNode(_el$17, _el$18);
                setProp(_el$17, "flexShrink", 0);
                insertNode(_el$18, _el$19);
                setProp(_el$18, "wrapMode", "none");
                insert(_el$18, () => recipe.version, null);
                effect((_p$) => {
                  var _v$6 = Math.max(12, Math.min(22, Math.floor(contentWidth() * 0.22))), _v$7 = theme.text, _v$8 = TextAttributes9.BOLD, _v$9 = theme.textMuted, _v$0 = recipe.kind ? theme.secondary : theme.textFaint, _v$1 = theme.textMuted, _v$10 = theme.textFaint;
                  _v$6 !== _p$.e && (_p$.e = setProp(_el$1, "width", _v$6, _p$.e));
                  _v$7 !== _p$.t && (_p$.t = setProp(_el$10, "fg", _v$7, _p$.t));
                  _v$8 !== _p$.a && (_p$.a = setProp(_el$10, "attributes", _v$8, _p$.a));
                  _v$9 !== _p$.o && (_p$.o = setProp(_el$12, "fg", _v$9, _p$.o));
                  _v$0 !== _p$.i && (_p$.i = setProp(_el$14, "fg", _v$0, _p$.i));
                  _v$1 !== _p$.n && (_p$.n = setProp(_el$16, "fg", _v$1, _p$.n));
                  _v$10 !== _p$.s && (_p$.s = setProp(_el$18, "fg", _v$10, _p$.s));
                  return _p$;
                }, {
                  e: undefined,
                  t: undefined,
                  a: undefined,
                  o: undefined,
                  i: undefined,
                  n: undefined,
                  s: undefined
                });
                return _el$0;
              }
            })
          }));
          effect((_$p) => setProp(_el$7, "verticalScrollbarOptions", {
            trackOptions: {
              backgroundColor: theme.backgroundElement,
              foregroundColor: theme.borderActive
            }
          }, _$p));
          return _el$7;
        })()];
      }
    }), _el$8);
    insertNode(_el$8, createTextNode(`Recipes are managed via the Projects CLI: \`projects recipes\` \xB7 read-only here`));
    setProp(_el$8, "flexShrink", 0);
    setProp(_el$8, "marginTop", 1);
    effect((_p$) => {
      var { background: _v$, text: _v$2 } = theme, _v$3 = TextAttributes9.BOLD, _v$4 = theme.textMuted, _v$5 = theme.textMuted;
      _v$ !== _p$.e && (_p$.e = setProp(_el$, "backgroundColor", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "fg", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$3, "attributes", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$5, "fg", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$8, "fg", _v$5, _p$.i));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined
    });
    return _el$;
  })();
}
var init_recipes = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_primitives();
  init_format();
  init_sidebar();
});

// src/cli/tui-solid/component/agents.tsx
import { TextAttributes as TextAttributes10 } from "@opentui/core";
function AgentsRoute() {
  const projects = useProjects();
  const {
    state
  } = projects;
  const theme = useTheme();
  const dimensions = useTerminalDimensions();
  const contentWidth = () => Math.max(24, dimensions().width - sidebarWidth(dimensions().width) - 6);
  const agentKind = (kind) => kind.charAt(0).toUpperCase() + kind.slice(1);
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$5 = createElement("text"), _el$6 = createTextNode(` registered`), _el$8 = createElement("text");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$8);
    setProp(_el$, "width", "100%");
    setProp(_el$, "height", "100%");
    setProp(_el$, "flexDirection", "column");
    setProp(_el$, "paddingTop", 1);
    setProp(_el$, "paddingLeft", 2);
    setProp(_el$, "paddingRight", 2);
    insertNode(_el$2, _el$3);
    insertNode(_el$2, _el$5);
    setProp(_el$2, "width", "100%");
    setProp(_el$2, "height", 1);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$2, "flexDirection", "row");
    setProp(_el$2, "justifyContent", "space-between");
    setProp(_el$2, "columnGap", 1);
    insertNode(_el$3, createTextNode(`Agents`));
    insertNode(_el$5, _el$6);
    insert(_el$5, () => state.agents.length, _el$6);
    insert(_el$, createComponent2(Show, {
      get when() {
        return state.agents.length > 0;
      },
      get fallback() {
        return createComponent2(EmptyState, {
          fill: true,
          title: "No agents",
          detail: "Agents are registered in the project registry and assigned to projects."
        });
      },
      get children() {
        return [createComponent2(SectionHeader, {
          label: "Registered agents",
          get muted() {
            return `${state.agents.length} total`;
          }
        }), (() => {
          var _el$7 = createElement("scrollbox");
          setProp(_el$7, "flexGrow", 1);
          setProp(_el$7, "minHeight", 0);
          setProp(_el$7, "width", "100%");
          setProp(_el$7, "scrollX", false);
          insert(_el$7, createComponent2(For, {
            get each() {
              return state.agents;
            },
            children: (agent) => createComponent2(Row, {
              get children() {
                var _el$0 = createElement("box"), _el$1 = createElement("box"), _el$10 = createElement("text"), _el$11 = createElement("box"), _el$12 = createElement("text"), _el$13 = createElement("box"), _el$14 = createElement("text"), _el$15 = createElement("box"), _el$16 = createElement("text"), _el$17 = createElement("box"), _el$18 = createElement("text");
                insertNode(_el$0, _el$1);
                insertNode(_el$0, _el$11);
                insertNode(_el$0, _el$13);
                insertNode(_el$0, _el$15);
                insertNode(_el$0, _el$17);
                setProp(_el$0, "width", "100%");
                setProp(_el$0, "flexDirection", "row");
                setProp(_el$0, "columnGap", 1);
                insertNode(_el$1, _el$10);
                setProp(_el$1, "flexShrink", 0);
                setProp(_el$10, "wrapMode", "none");
                insert(_el$10, () => truncate(agent.name, Math.max(12, Math.min(22, Math.floor(contentWidth() * 0.22)))));
                insertNode(_el$11, _el$12);
                setProp(_el$11, "width", 18);
                setProp(_el$11, "flexShrink", 0);
                setProp(_el$12, "wrapMode", "none");
                insert(_el$12, () => truncate(agent.slug, 18));
                insertNode(_el$13, _el$14);
                setProp(_el$13, "width", 12);
                setProp(_el$13, "flexShrink", 0);
                setProp(_el$14, "wrapMode", "none");
                insert(_el$14, () => agentKind(agent.kind));
                insertNode(_el$15, _el$16);
                setProp(_el$15, "flexGrow", 1);
                setProp(_el$15, "flexShrink", 1);
                setProp(_el$15, "minWidth", 0);
                setProp(_el$16, "wrapMode", "none");
                insert(_el$16, () => [agent.provider, agent.model].filter(Boolean).join(" / ") || "\u2014");
                insertNode(_el$17, _el$18);
                setProp(_el$17, "flexShrink", 0);
                setProp(_el$18, "wrapMode", "none");
                insert(_el$18, () => truncate(agent.role ?? "", 16));
                effect((_p$) => {
                  var _v$6 = Math.max(12, Math.min(22, Math.floor(contentWidth() * 0.22))), _v$7 = theme.text, _v$8 = TextAttributes10.BOLD, _v$9 = theme.textMuted, _v$0 = theme.secondary, _v$1 = theme.textMuted, _v$10 = theme.textFaint;
                  _v$6 !== _p$.e && (_p$.e = setProp(_el$1, "width", _v$6, _p$.e));
                  _v$7 !== _p$.t && (_p$.t = setProp(_el$10, "fg", _v$7, _p$.t));
                  _v$8 !== _p$.a && (_p$.a = setProp(_el$10, "attributes", _v$8, _p$.a));
                  _v$9 !== _p$.o && (_p$.o = setProp(_el$12, "fg", _v$9, _p$.o));
                  _v$0 !== _p$.i && (_p$.i = setProp(_el$14, "fg", _v$0, _p$.i));
                  _v$1 !== _p$.n && (_p$.n = setProp(_el$16, "fg", _v$1, _p$.n));
                  _v$10 !== _p$.s && (_p$.s = setProp(_el$18, "fg", _v$10, _p$.s));
                  return _p$;
                }, {
                  e: undefined,
                  t: undefined,
                  a: undefined,
                  o: undefined,
                  i: undefined,
                  n: undefined,
                  s: undefined
                });
                return _el$0;
              }
            })
          }));
          effect((_$p) => setProp(_el$7, "verticalScrollbarOptions", {
            trackOptions: {
              backgroundColor: theme.backgroundElement,
              foregroundColor: theme.borderActive
            }
          }, _$p));
          return _el$7;
        })()];
      }
    }), _el$8);
    insertNode(_el$8, createTextNode(`Agents are managed via the Projects CLI: \`projects agents\` \xB7 read-only here`));
    setProp(_el$8, "flexShrink", 0);
    setProp(_el$8, "marginTop", 1);
    effect((_p$) => {
      var { background: _v$, text: _v$2 } = theme, _v$3 = TextAttributes10.BOLD, _v$4 = theme.textMuted, _v$5 = theme.textMuted;
      _v$ !== _p$.e && (_p$.e = setProp(_el$, "backgroundColor", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "fg", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$3, "attributes", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$5, "fg", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$8, "fg", _v$5, _p$.i));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined
    });
    return _el$;
  })();
}
var init_agents = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_primitives();
  init_format();
  init_sidebar();
});

// src/cli/tui-solid/component/settings.tsx
import { TextAttributes as TextAttributes11 } from "@opentui/core";
function InfoRow(props) {
  const theme = useTheme();
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$4 = createElement("box"), _el$5 = createElement("text");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$4);
    setProp(_el$, "width", "100%");
    setProp(_el$, "flexDirection", "row");
    setProp(_el$, "columnGap", 1);
    setProp(_el$, "flexShrink", 0);
    insertNode(_el$2, _el$3);
    setProp(_el$2, "width", 16);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$3, "wrapMode", "none");
    insert(_el$3, () => props.label);
    insertNode(_el$4, _el$5);
    setProp(_el$4, "flexGrow", 1);
    setProp(_el$4, "flexShrink", 1);
    setProp(_el$4, "minWidth", 0);
    setProp(_el$5, "wrapMode", "word");
    insert(_el$5, () => props.value);
    effect((_p$) => {
      var { textMuted: _v$, text: _v$2 } = theme;
      _v$ !== _p$.e && (_p$.e = setProp(_el$3, "fg", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$5, "fg", _v$2, _p$.t));
      return _p$;
    }, {
      e: undefined,
      t: undefined
    });
    return _el$;
  })();
}
function SettingsContent() {
  const projects = useProjects();
  const {
    state
  } = projects;
  const theme = useTheme();
  const transportLine = () => {
    const transport2 = state.transport;
    if (!transport2)
      return "Resolving registry\u2026";
    const label = transportLabel(transport2);
    return transport2 === "http" && state.authority ? `${label} \xB7 ${state.authority}` : label;
  };
  return (() => {
    var _el$6 = createElement("box"), _el$9 = createElement("text");
    insertNode(_el$6, _el$9);
    setProp(_el$6, "width", "100%");
    setProp(_el$6, "flexDirection", "column");
    setProp(_el$6, "flexShrink", 0);
    insert(_el$6, createComponent2(SectionHeader, {
      label: "Session"
    }), _el$9);
    insert(_el$6, createComponent2(InfoRow, {
      label: "Transport",
      get value() {
        return transportLine();
      }
    }), _el$9);
    insert(_el$6, createComponent2(InfoRow, {
      label: "Registry",
      get value() {
        return state.transport === "http" ? "Hosted Projects API" : "Local SQLite registry";
      }
    }), _el$9);
    insert(_el$6, createComponent2(SectionHeader, {
      label: "Data access"
    }), _el$9);
    insert(_el$6, createComponent2(Show, {
      get when() {
        return state.transport === "http";
      },
      get fallback() {
        return (() => {
          var _el$1 = createElement("text");
          insertNode(_el$1, createTextNode(`Local mode is on (HASNA_PROJECTS_LOCAL=1). The registry lives on this machine at HASNA_PROJECTS_DB_PATH, defaulting to ~/.hasna/projects/projects.db.`));
          setProp(_el$1, "wrapMode", "word");
          setProp(_el$1, "width", "100%");
          effect((_$p) => setProp(_el$1, "fg", theme.textMuted, _$p));
          return _el$1;
        })();
      },
      get children() {
        var _el$7 = createElement("text");
        insertNode(_el$7, createTextNode(`Hosted mode resolves a credential from the standard tiers: argument, environment pointer, macOS Keychain (hasna.credentials.projects.api-key), the credentials file (~/.hasna/projects/config/credentials), then HASNA_PROJECTS_API_KEY. Nothing configured fails closed.`));
        setProp(_el$7, "wrapMode", "word");
        setProp(_el$7, "width", "100%");
        effect((_$p) => setProp(_el$7, "fg", theme.textMuted, _$p));
        return _el$7;
      }
    }), _el$9);
    insert(_el$6, createComponent2(SectionHeader, {
      label: "Appearance"
    }), _el$9);
    insertNode(_el$9, createTextNode(`Theme follows the terminal; force it with PROJECTS_TUI_THEME=light or PROJECTS_TUI_THEME=dark.`));
    setProp(_el$9, "wrapMode", "word");
    setProp(_el$9, "width", "100%");
    insert(_el$6, createComponent2(SectionHeader, {
      label: "Shortcuts"
    }), null);
    insert(_el$6, createComponent2(For, {
      each: PROJECTS_SHORTCUTS,
      children: (shortcut) => (() => {
        var _el$11 = createElement("box"), _el$12 = createElement("text"), _el$13 = createElement("text");
        insertNode(_el$11, _el$12);
        insertNode(_el$11, _el$13);
        setProp(_el$11, "width", "100%");
        setProp(_el$11, "flexDirection", "row");
        setProp(_el$11, "flexShrink", 0);
        setProp(_el$11, "columnGap", 1);
        setProp(_el$11, "paddingLeft", 1);
        setProp(_el$11, "paddingRight", 1);
        setProp(_el$12, "flexGrow", 1);
        setProp(_el$12, "flexShrink", 1);
        setProp(_el$12, "wrapMode", "none");
        insert(_el$12, () => shortcut[0]);
        setProp(_el$13, "flexShrink", 0);
        setProp(_el$13, "wrapMode", "none");
        insert(_el$13, () => shortcut[1]);
        effect((_p$) => {
          var { text: _v$3, textMuted: _v$4 } = theme;
          _v$3 !== _p$.e && (_p$.e = setProp(_el$12, "fg", _v$3, _p$.e));
          _v$4 !== _p$.t && (_p$.t = setProp(_el$13, "fg", _v$4, _p$.t));
          return _p$;
        }, {
          e: undefined,
          t: undefined
        });
        return _el$11;
      })()
    }), null);
    effect((_$p) => setProp(_el$9, "fg", theme.textMuted, _$p));
    return _el$6;
  })();
}
function SettingsRoute() {
  const theme = useTheme();
  return (() => {
    var _el$14 = createElement("box"), _el$15 = createElement("box"), _el$16 = createElement("text"), _el$18 = createElement("scrollbox");
    insertNode(_el$14, _el$15);
    insertNode(_el$14, _el$18);
    setProp(_el$14, "width", "100%");
    setProp(_el$14, "height", "100%");
    setProp(_el$14, "flexDirection", "column");
    setProp(_el$14, "paddingTop", 1);
    setProp(_el$14, "paddingLeft", 2);
    setProp(_el$14, "paddingRight", 2);
    insertNode(_el$15, _el$16);
    setProp(_el$15, "width", "100%");
    setProp(_el$15, "height", 1);
    setProp(_el$15, "flexShrink", 0);
    insertNode(_el$16, createTextNode(`Settings`));
    setProp(_el$18, "flexGrow", 1);
    setProp(_el$18, "minHeight", 0);
    setProp(_el$18, "width", "100%");
    setProp(_el$18, "scrollX", false);
    insert(_el$18, createComponent2(SettingsContent, {}));
    effect((_p$) => {
      var { background: _v$5, text: _v$6 } = theme, _v$7 = TextAttributes11.BOLD, _v$8 = {
        trackOptions: {
          backgroundColor: theme.backgroundElement,
          foregroundColor: theme.borderActive
        }
      };
      _v$5 !== _p$.e && (_p$.e = setProp(_el$14, "backgroundColor", _v$5, _p$.e));
      _v$6 !== _p$.t && (_p$.t = setProp(_el$16, "fg", _v$6, _p$.t));
      _v$7 !== _p$.a && (_p$.a = setProp(_el$16, "attributes", _v$7, _p$.a));
      _v$8 !== _p$.o && (_p$.o = setProp(_el$18, "verticalScrollbarOptions", _v$8, _p$.o));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined
    });
    return _el$14;
  })();
}
var PROJECTS_SHORTCUTS;
var init_settings = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_projects_state();
  init_theme2();
  init_primitives();
  init_format();
  PROJECTS_SHORTCUTS = [["Move selection", "\u2191 / \u2193"], ["Open project", "Enter"], ["Search projects", "/ or Ctrl+F"], ["New project", "N or Ctrl+N"], ["Clear search / close", "Esc"], ["Back to projects (detail)", "Esc or Backspace"], ["Edit project (detail)", "E"], ["Archive / Unarchive (detail)", "A"], ["Delete project (detail)", "D or Delete"], ["Refresh project (detail)", "R"], ["Shortcuts", "Ctrl+P"], ["Refresh list", "Ctrl+R"]];
});

// src/cli/tui/project-form-values.ts
function projectFormMetadata(previous, fields) {
  const metadata = { ...previous };
  for (const key of ["stage", "priority", "owner"]) {
    const value = fields[key].trim();
    if (value)
      metadata[key] = value;
    else
      delete metadata[key];
  }
  return metadata;
}
function projectFormPatch(project, fields) {
  return {
    name: fields.name.trim(),
    slug: fields.slug.trim(),
    description: fields.description.trim() || null,
    kind: fields.kind,
    root_id: fields.rootId === "none" ? null : fields.rootId,
    recipe_id: fields.recipeId === "none" ? null : fields.recipeId,
    primary_path: fields.primaryPath.trim() || null,
    git_remote: fields.gitRemote.trim() || null,
    tags: fields.tags,
    metadata: projectFormMetadata(project.metadata, fields)
  };
}

// src/cli/tui-solid/component/project-form.tsx
import { TextAttributes as TextAttributes12 } from "@opentui/core";
function parseTags(value) {
  return value.split(",").map((tag) => tag.trim()).filter(Boolean);
}
function TextField(props) {
  const theme = useTheme();
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$4 = createElement("box"), _el$5 = createElement("input");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$4);
    setProp(_el$, "width", "100%");
    setProp(_el$, "height", 1);
    setProp(_el$, "flexDirection", "row");
    setProp(_el$, "columnGap", 1);
    setProp(_el$, "flexShrink", 0);
    insertNode(_el$2, _el$3);
    setProp(_el$2, "width", 16);
    setProp(_el$2, "flexShrink", 0);
    setProp(_el$3, "wrapMode", "none");
    insert(_el$3, () => props.label);
    insertNode(_el$4, _el$5);
    setProp(_el$4, "flexGrow", 1);
    setProp(_el$4, "flexShrink", 1);
    setProp(_el$4, "minWidth", 0);
    setProp(_el$5, "width", "100%");
    effect((_p$) => {
      var _v$ = props.focused ? theme.primary : theme.textMuted, _v$2 = props.focused, _v$3 = props.value, _v$4 = props.placeholder, _v$5 = theme.text, _v$6 = props.focused ? theme.backgroundActive : theme.backgroundElement, _v$7 = theme.text, _v$8 = theme.backgroundActive, _v$9 = theme.textMuted, _v$0 = theme.text, _v$1 = props.onChange, _v$10 = props.onSubmit;
      _v$ !== _p$.e && (_p$.e = setProp(_el$3, "fg", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$5, "focused", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$5, "value", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$5, "placeholder", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$5, "textColor", _v$5, _p$.i));
      _v$6 !== _p$.n && (_p$.n = setProp(_el$5, "backgroundColor", _v$6, _p$.n));
      _v$7 !== _p$.s && (_p$.s = setProp(_el$5, "focusedTextColor", _v$7, _p$.s));
      _v$8 !== _p$.h && (_p$.h = setProp(_el$5, "focusedBackgroundColor", _v$8, _p$.h));
      _v$9 !== _p$.r && (_p$.r = setProp(_el$5, "placeholderColor", _v$9, _p$.r));
      _v$0 !== _p$.d && (_p$.d = setProp(_el$5, "cursorColor", _v$0, _p$.d));
      _v$1 !== _p$.l && (_p$.l = setProp(_el$5, "onInput", _v$1, _p$.l));
      _v$10 !== _p$.u && (_p$.u = setProp(_el$5, "onSubmit", _v$10, _p$.u));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined,
      s: undefined,
      h: undefined,
      r: undefined,
      d: undefined,
      l: undefined,
      u: undefined
    });
    return _el$;
  })();
}
function SelectField(props) {
  const theme = useTheme();
  return (() => {
    var _el$6 = createElement("box"), _el$7 = createElement("box"), _el$8 = createElement("text"), _el$9 = createElement("box"), _el$0 = createElement("text");
    insertNode(_el$6, _el$7);
    insertNode(_el$6, _el$9);
    setProp(_el$6, "width", "100%");
    setProp(_el$6, "height", 1);
    setProp(_el$6, "flexDirection", "row");
    setProp(_el$6, "columnGap", 1);
    setProp(_el$6, "flexShrink", 0);
    insertNode(_el$7, _el$8);
    setProp(_el$7, "width", 16);
    setProp(_el$7, "flexShrink", 0);
    setProp(_el$8, "wrapMode", "none");
    insert(_el$8, () => props.label);
    insertNode(_el$9, _el$0);
    setProp(_el$9, "flexGrow", 1);
    setProp(_el$9, "flexShrink", 1);
    setProp(_el$9, "minWidth", 0);
    setProp(_el$9, "height", 1);
    setProp(_el$9, "paddingLeft", 1);
    setProp(_el$9, "onMouseUp", (event) => {
      if (event.button !== 0)
        return;
      event.stopPropagation();
      props.onPick();
    });
    setProp(_el$0, "wrapMode", "none");
    insert(_el$0, () => truncate(props.value, 48));
    effect((_p$) => {
      var _v$11 = props.focused ? theme.primary : theme.textMuted, _v$12 = props.focused ? theme.backgroundActive : theme.backgroundElement, _v$13 = theme.text;
      _v$11 !== _p$.e && (_p$.e = setProp(_el$8, "fg", _v$11, _p$.e));
      _v$12 !== _p$.t && (_p$.t = setProp(_el$9, "backgroundColor", _v$12, _p$.t));
      _v$13 !== _p$.a && (_p$.a = setProp(_el$0, "fg", _v$13, _p$.a));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined
    });
    return _el$6;
  })();
}
function FieldPicker(props) {
  const theme = useTheme();
  const [active, setActive] = createSignal(Math.max(0, props.items.findIndex((item) => item.id === props.selectedId)));
  const visible = createMemo(() => {
    const q = props.query.trim().toLowerCase();
    if (!q)
      return props.items;
    return props.items.filter((item) => `${item.title} ${item.detail ?? ""}`.toLowerCase().includes(q));
  });
  useKeyboard((key) => {
    if (key.name === "up") {
      key.preventDefault();
      key.stopPropagation();
      setActive((value) => Math.max(0, value - 1));
      return;
    }
    if (key.name === "down") {
      key.preventDefault();
      key.stopPropagation();
      setActive((value) => Math.min(Math.max(0, visible().length - 1), value + 1));
      return;
    }
    if (key.name === "enter" || key.name === "return") {
      key.preventDefault();
      key.stopPropagation();
      const item = visible()[active()];
      if (item)
        props.onSelect(item.id);
      return;
    }
  });
  return (() => {
    var _el$1 = createElement("box"), _el$10 = createElement("box"), _el$11 = createElement("text"), _el$12 = createElement("input"), _el$13 = createElement("scrollbox");
    insertNode(_el$1, _el$10);
    insertNode(_el$1, _el$12);
    insertNode(_el$1, _el$13);
    setProp(_el$1, "flexDirection", "column");
    setProp(_el$1, "width", "100%");
    setProp(_el$1, "rowGap", 1);
    insertNode(_el$10, _el$11);
    setProp(_el$10, "height", 1);
    setProp(_el$10, "flexDirection", "row");
    setProp(_el$10, "justifyContent", "space-between");
    insert(_el$11, () => props.title);
    insert(_el$10, createComponent2(Button, {
      label: "Close",
      get onPress() {
        return props.onCancel;
      }
    }), null);
    setProp(_el$12, "focused", true);
    setProp(_el$12, "placeholder", "Filter");
    setProp(_el$12, "width", "100%");
    setProp(_el$12, "onInput", (value) => {
      props.onQuery(value);
      setActive(0);
    });
    setProp(_el$13, "width", "100%");
    setProp(_el$13, "scrollX", false);
    insert(_el$13, createComponent2(For, {
      get each() {
        return visible();
      },
      children: (item, index) => {
        const isActive = () => index() === active();
        return createComponent2(Row, {
          get active() {
            return isActive();
          },
          onPress: () => props.onSelect(item.id),
          get children() {
            var _el$14 = createElement("box"), _el$15 = createElement("box"), _el$16 = createElement("text");
            insertNode(_el$14, _el$15);
            setProp(_el$14, "flexDirection", "row");
            setProp(_el$14, "width", "100%");
            setProp(_el$14, "columnGap", 1);
            insertNode(_el$15, _el$16);
            setProp(_el$15, "flexGrow", 1);
            setProp(_el$15, "flexShrink", 1);
            setProp(_el$15, "minWidth", 0);
            setProp(_el$16, "wrapMode", "none");
            insert(_el$16, () => truncate(item.title, 40));
            insert(_el$14, (() => {
              var _c$2 = memo2(() => !!item.detail);
              return () => _c$2() ? (() => {
                var _el$17 = createElement("box"), _el$18 = createElement("text");
                insertNode(_el$17, _el$18);
                setProp(_el$17, "flexShrink", 0);
                setProp(_el$18, "wrapMode", "none");
                insert(_el$18, () => truncate(item.detail, 24));
                effect((_$p) => setProp(_el$18, "fg", isActive() ? selectedForeground(theme, theme.primary) : theme.textMuted, _$p));
                return _el$17;
              })() : null;
            })(), null);
            effect((_p$) => {
              var _v$24 = isActive() ? theme.primary : undefined, _v$25 = isActive() ? selectedForeground(theme, theme.primary) : theme.text, _v$26 = isActive() ? TextAttributes12.BOLD : 0;
              _v$24 !== _p$.e && (_p$.e = setProp(_el$14, "backgroundColor", _v$24, _p$.e));
              _v$25 !== _p$.t && (_p$.t = setProp(_el$16, "fg", _v$25, _p$.t));
              _v$26 !== _p$.a && (_p$.a = setProp(_el$16, "attributes", _v$26, _p$.a));
              return _p$;
            }, {
              e: undefined,
              t: undefined,
              a: undefined
            });
            return _el$14;
          }
        });
      }
    }), null);
    insert(_el$13, (() => {
      var _c$ = memo2(() => visible().length === 0);
      return () => _c$() ? (() => {
        var _el$19 = createElement("text");
        insertNode(_el$19, createTextNode(`No matches`));
        effect((_$p) => setProp(_el$19, "fg", theme.textMuted, _$p));
        return _el$19;
      })() : null;
    })(), null);
    effect((_p$) => {
      var _v$14 = theme.text, _v$15 = TextAttributes12.BOLD, _v$16 = props.query, _v$17 = theme.text, _v$18 = theme.backgroundElement, _v$19 = theme.text, _v$20 = theme.backgroundActive, _v$21 = theme.textMuted, _v$22 = theme.text, _v$23 = Math.min(12, Math.max(4, visible().length + 1));
      _v$14 !== _p$.e && (_p$.e = setProp(_el$11, "fg", _v$14, _p$.e));
      _v$15 !== _p$.t && (_p$.t = setProp(_el$11, "attributes", _v$15, _p$.t));
      _v$16 !== _p$.a && (_p$.a = setProp(_el$12, "value", _v$16, _p$.a));
      _v$17 !== _p$.o && (_p$.o = setProp(_el$12, "textColor", _v$17, _p$.o));
      _v$18 !== _p$.i && (_p$.i = setProp(_el$12, "backgroundColor", _v$18, _p$.i));
      _v$19 !== _p$.n && (_p$.n = setProp(_el$12, "focusedTextColor", _v$19, _p$.n));
      _v$20 !== _p$.s && (_p$.s = setProp(_el$12, "focusedBackgroundColor", _v$20, _p$.s));
      _v$21 !== _p$.h && (_p$.h = setProp(_el$12, "placeholderColor", _v$21, _p$.h));
      _v$22 !== _p$.r && (_p$.r = setProp(_el$12, "cursorColor", _v$22, _p$.r));
      _v$23 !== _p$.d && (_p$.d = setProp(_el$13, "height", _v$23, _p$.d));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined,
      s: undefined,
      h: undefined,
      r: undefined,
      d: undefined
    });
    return _el$1;
  })();
}
function ProjectFormDialog(props) {
  const projects = useProjects();
  const {
    state,
    actions
  } = projects;
  const theme = useTheme();
  const toast = useToast();
  const dimensions = useTerminalDimensions();
  const [name, setName] = createSignal(props.project?.name ?? "");
  const [slug, setSlug] = createSignal(props.project?.slug ?? "");
  const [description, setDescription] = createSignal(props.project?.description ?? "");
  const [primaryPath, setPrimaryPath] = createSignal(props.project?.primary_path ?? "");
  const [gitRemote, setGitRemote] = createSignal(props.project?.git_remote ?? "");
  const [tagsInput, setTagsInput] = createSignal((props.project?.tags ?? []).join(", "));
  const [kind, setKind] = createSignal(props.project?.kind ?? "generic");
  const [rootId, setRootId] = createSignal(props.project?.root_id ?? "none");
  const [recipeId, setRecipeId] = createSignal(props.project?.recipe_id ?? "none");
  const [stage, setStage] = createSignal(typeof props.project?.metadata?.stage === "string" ? props.project.metadata.stage : "");
  const [priority, setPriority] = createSignal(typeof props.project?.metadata?.priority === "string" ? props.project.metadata.priority : "");
  const [owner, setOwner] = createSignal(typeof props.project?.metadata?.owner === "string" ? props.project.metadata.owner : "");
  const [field, setField] = createSignal("name");
  const [picking, setPicking] = createSignal(null);
  const [pickerQuery, setPickerQuery] = createSignal("");
  const [saving, setSaving] = createSignal(false);
  const isEdit = () => !!props.project;
  const busy = () => saving() || state.mutating;
  const managementFields = () => ({
    stage: stage(),
    priority: priority(),
    owner: owner()
  });
  const buildInput = () => {
    const input = {
      name: name().trim()
    };
    const slugValue = slug().trim();
    if (slugValue)
      input.slug = slugValue;
    const desc = description().trim();
    if (desc)
      input.description = desc;
    if (kind() !== "generic")
      input.kind = kind();
    if (rootId() !== "none")
      input.root_id = rootId();
    if (recipeId() !== "none")
      input.recipe_id = recipeId();
    const pathValue = primaryPath().trim();
    if (pathValue)
      input.primary_path = pathValue;
    const remote = gitRemote().trim();
    if (remote)
      input.git_remote = remote;
    const tags = parseTags(tagsInput());
    if (tags.length)
      input.tags = tags;
    const meta = projectFormMetadata({}, managementFields());
    if (Object.keys(meta).length)
      input.metadata = meta;
    return input;
  };
  const buildPatch = () => projectFormPatch(props.project, {
    name: name(),
    slug: slug(),
    description: description(),
    kind: kind(),
    rootId: rootId(),
    recipeId: recipeId(),
    primaryPath: primaryPath(),
    gitRemote: gitRemote(),
    tags: parseTags(tagsInput()),
    ...managementFields()
  });
  const save = async () => {
    if (busy())
      return;
    if (!name().trim()) {
      toast.show({
        title: "Name required",
        message: "A project needs a name.",
        tone: "error"
      });
      return;
    }
    if (isEdit() && !slug().trim()) {
      toast.show({
        title: "Slug required",
        message: "An existing project needs a slug.",
        tone: "error"
      });
      return;
    }
    setSaving(true);
    try {
      const result = props.project ? await actions.updateProject(props.project.id, buildPatch()) : await actions.createProject(buildInput());
      if (result) {
        props.onDone(result);
      } else {
        toast.show({
          title: "Save failed",
          message: state.error ?? "Could not save the project.",
          tone: "error"
        });
        props.onDone(null);
      }
    } finally {
      setSaving(false);
    }
  };
  const cycleField = (delta) => {
    const index = FORM_FIELDS.indexOf(field());
    setField(FORM_FIELDS[(index + delta + FORM_FIELDS.length) % FORM_FIELDS.length]);
  };
  const advanceTextField = (current) => {
    const index = TEXT_FIELDS.indexOf(current);
    setField(TEXT_FIELDS[(index + 1) % TEXT_FIELDS.length]);
  };
  const openPicker = (which) => {
    setPickerQuery("");
    setPicking(which);
  };
  useKeyboard((key) => {
    if (key.name === "escape") {
      key.preventDefault();
      key.stopPropagation();
      props.onDone(null);
      return;
    }
    if (picking())
      return;
    if (key.name === "tab") {
      key.preventDefault();
      key.stopPropagation();
      cycleField(key.shift ? -1 : 1);
      return;
    }
    if (key.name === "enter" || key.name === "return") {
      const current = field();
      if (current === "kind" || current === "root" || current === "recipe") {
        key.preventDefault();
        key.stopPropagation();
        openPicker(current);
      }
    }
  });
  const kindItems = () => WORKSPACE_KINDS.map((value) => ({
    id: value,
    title: kindLabel(value)
  }));
  const rootItems = () => state.roots.map((root) => ({
    id: root.id,
    title: root.name,
    detail: root.slug
  }));
  const recipeItems = () => state.recipes.map((recipe) => ({
    id: recipe.id,
    title: recipe.name,
    detail: recipe.slug
  }));
  const rootDisplay = () => {
    if (rootId() === "none")
      return "None";
    return state.roots.find((root) => root.id === rootId())?.name ?? rootId();
  };
  const recipeDisplay = () => {
    if (recipeId() === "none")
      return "None";
    return state.recipes.find((recipe) => recipe.id === recipeId())?.name ?? recipeId();
  };
  const pickField = (which) => which === "kind" ? createComponent2(FieldPicker, {
    title: "Project kind",
    get items() {
      return kindItems();
    },
    get selectedId() {
      return kind();
    },
    get query() {
      return pickerQuery();
    },
    onQuery: setPickerQuery,
    onSelect: (id) => {
      setKind(id);
      setPicking(null);
    },
    onCancel: () => setPicking(null)
  }) : which === "root" ? createComponent2(FieldPicker, {
    title: "Root",
    get items() {
      return rootItems();
    },
    get selectedId() {
      return rootId();
    },
    get query() {
      return pickerQuery();
    },
    onQuery: setPickerQuery,
    onSelect: (id) => {
      setRootId(id);
      setPicking(null);
    },
    onCancel: () => setPicking(null)
  }) : createComponent2(FieldPicker, {
    title: "Recipe",
    get items() {
      return recipeItems();
    },
    get selectedId() {
      return recipeId();
    },
    get query() {
      return pickerQuery();
    },
    onQuery: setPickerQuery,
    onSelect: (id) => {
      setRecipeId(id);
      setPicking(null);
    },
    onCancel: () => setPicking(null)
  });
  const fieldsHeight = () => Math.max(8, Math.min(16, dimensions().height - 8));
  return (() => {
    var _el$21 = createElement("box"), _el$22 = createElement("box"), _el$23 = createElement("text");
    insertNode(_el$21, _el$22);
    setProp(_el$21, "width", "100%");
    setProp(_el$21, "flexDirection", "column");
    setProp(_el$21, "rowGap", 1);
    insertNode(_el$22, _el$23);
    setProp(_el$22, "height", 1);
    setProp(_el$22, "flexDirection", "row");
    setProp(_el$22, "justifyContent", "space-between");
    insert(_el$23, (() => {
      var _c$3 = memo2(() => !!isEdit());
      return () => _c$3() ? `Edit project \xB7 ${props.project.slug}` : "New project";
    })());
    insert(_el$22, createComponent2(Button, {
      label: "Close",
      onPress: () => props.onDone(null)
    }), null);
    insert(_el$21, createComponent2(Show, {
      get when() {
        return picking();
      },
      get fallback() {
        return [(() => {
          var _el$24 = createElement("scrollbox");
          setProp(_el$24, "width", "100%");
          setProp(_el$24, "scrollX", false);
          setProp(_el$24, "flexShrink", 0);
          insert(_el$24, createComponent2(TextField, {
            label: "Name*",
            get value() {
              return name();
            },
            placeholder: "Project name",
            get focused() {
              return field() === "name";
            },
            onChange: setName,
            onSubmit: () => advanceTextField("name")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Slug",
            get value() {
              return slug();
            },
            placeholder: "project-slug",
            get focused() {
              return field() === "slug";
            },
            onChange: setSlug,
            onSubmit: () => advanceTextField("slug")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Description",
            get value() {
              return description();
            },
            placeholder: "What is this project?",
            get focused() {
              return field() === "description";
            },
            onChange: setDescription,
            onSubmit: () => advanceTextField("description")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Primary path",
            get value() {
              return primaryPath();
            },
            placeholder: "/Users/you/code/project",
            get focused() {
              return field() === "primaryPath";
            },
            onChange: setPrimaryPath,
            onSubmit: () => advanceTextField("primaryPath")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Git remote",
            get value() {
              return gitRemote();
            },
            placeholder: "git@github.com:org/project.git",
            get focused() {
              return field() === "gitRemote";
            },
            onChange: setGitRemote,
            onSubmit: () => advanceTextField("gitRemote")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Tags",
            get value() {
              return tagsInput();
            },
            placeholder: "comma, separated",
            get focused() {
              return field() === "tags";
            },
            onChange: setTagsInput,
            onSubmit: () => advanceTextField("tags")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Stage",
            get value() {
              return stage();
            },
            placeholder: "idea / active / shipped",
            get focused() {
              return field() === "stage";
            },
            onChange: setStage,
            onSubmit: () => advanceTextField("stage")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Priority",
            get value() {
              return priority();
            },
            placeholder: "p1 / p2 / low",
            get focused() {
              return field() === "priority";
            },
            onChange: setPriority,
            onSubmit: () => advanceTextField("priority")
          }), null);
          insert(_el$24, createComponent2(TextField, {
            label: "Owner",
            get value() {
              return owner();
            },
            placeholder: "owner slug or email",
            get focused() {
              return field() === "owner";
            },
            onChange: setOwner,
            onSubmit: () => advanceTextField("owner")
          }), null);
          insert(_el$24, createComponent2(SelectField, {
            label: "Kind",
            get value() {
              return kindLabel(kind());
            },
            get focused() {
              return field() === "kind";
            },
            onPick: () => openPicker("kind")
          }), null);
          insert(_el$24, createComponent2(SelectField, {
            label: "Root",
            get value() {
              return rootDisplay();
            },
            get focused() {
              return field() === "root";
            },
            onPick: () => openPicker("root")
          }), null);
          insert(_el$24, createComponent2(SelectField, {
            label: "Recipe",
            get value() {
              return recipeDisplay();
            },
            get focused() {
              return field() === "recipe";
            },
            onPick: () => openPicker("recipe")
          }), null);
          effect((_$p) => setProp(_el$24, "height", fieldsHeight(), _$p));
          return _el$24;
        })(), (() => {
          var _el$25 = createElement("box"), _el$26 = createElement("text");
          insertNode(_el$25, _el$26);
          setProp(_el$25, "height", 1);
          setProp(_el$25, "flexDirection", "row");
          setProp(_el$25, "columnGap", 1);
          insert(_el$25, createComponent2(Button, {
            get label() {
              return memo2(() => !!busy())() ? "Saving\u2026" : isEdit() ? "Save changes" : "Create project";
            },
            tone: "primary",
            onPress: () => void save()
          }), _el$26);
          insert(_el$25, createComponent2(Button, {
            label: "Cancel",
            onPress: () => props.onDone(null)
          }), _el$26);
          insertNode(_el$26, createTextNode(`Tab next \xB7 Enter picks on select rows`));
          setProp(_el$26, "wrapMode", "none");
          effect((_$p) => setProp(_el$26, "fg", theme.textMuted, _$p));
          return _el$25;
        })()];
      },
      children: (which) => pickField(which())
    }), null);
    effect((_p$) => {
      var _v$27 = theme.text, _v$28 = TextAttributes12.BOLD;
      _v$27 !== _p$.e && (_p$.e = setProp(_el$23, "fg", _v$27, _p$.e));
      _v$28 !== _p$.t && (_p$.t = setProp(_el$23, "attributes", _v$28, _p$.t));
      return _p$;
    }, {
      e: undefined,
      t: undefined
    });
    return _el$21;
  })();
}
var TEXT_FIELDS, SELECT_FIELDS, FORM_FIELDS;
var init_project_form = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_toast();
  init_primitives();
  init_format();
  init_types();
  TEXT_FIELDS = ["name", "slug", "description", "primaryPath", "gitRemote", "tags", "stage", "priority", "owner"];
  SELECT_FIELDS = ["kind", "root", "recipe"];
  FORM_FIELDS = [...TEXT_FIELDS, ...SELECT_FIELDS];
});

// src/cli/tui-solid/component/dialogs.tsx
import { TextAttributes as TextAttributes13 } from "@opentui/core";
function ConfirmDialog(props) {
  const theme = useTheme();
  useKeyboard((key) => {
    if (key.name === "escape")
      props.close();
  });
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("text"), _el$4 = createElement("text"), _el$5 = createElement("box");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$4);
    insertNode(_el$, _el$5);
    setProp(_el$, "flexDirection", "column");
    setProp(_el$, "width", "100%");
    setProp(_el$, "rowGap", 1);
    insertNode(_el$2, _el$3);
    setProp(_el$2, "height", 1);
    setProp(_el$2, "flexDirection", "row");
    setProp(_el$2, "justifyContent", "space-between");
    insert(_el$3, () => props.title);
    insert(_el$2, createComponent2(Button, {
      label: "Close",
      get onPress() {
        return props.close;
      }
    }), null);
    setProp(_el$4, "wrapMode", "word");
    setProp(_el$4, "width", "100%");
    insert(_el$4, () => props.message);
    setProp(_el$5, "height", 1);
    setProp(_el$5, "flexDirection", "row");
    setProp(_el$5, "columnGap", 1);
    insert(_el$5, createComponent2(Button, {
      get label() {
        return memo2(() => !!props.busy)() ? "Working\u2026" : props.confirmLabel;
      },
      get tone() {
        return props.danger ? "danger" : "primary";
      },
      onPress: () => void props.onConfirm()
    }), null);
    insert(_el$5, createComponent2(Button, {
      label: "Cancel",
      get onPress() {
        return props.close;
      }
    }), null);
    effect((_p$) => {
      var _v$ = theme.text, _v$2 = TextAttributes13.BOLD, _v$3 = theme.text;
      _v$ !== _p$.e && (_p$.e = setProp(_el$3, "fg", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$3, "attributes", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$4, "fg", _v$3, _p$.a));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined
    });
    return _el$;
  })();
}
function ShortcutsDialog(props) {
  const theme = useTheme();
  useKeyboard((key) => {
    if (key.name === "escape")
      props.close();
  });
  return (() => {
    var _el$6 = createElement("box"), _el$7 = createElement("box"), _el$8 = createElement("text"), _el$0 = createElement("text");
    insertNode(_el$6, _el$7);
    insertNode(_el$6, _el$0);
    setProp(_el$6, "flexDirection", "column");
    setProp(_el$6, "width", "100%");
    setProp(_el$6, "rowGap", 1);
    insertNode(_el$7, _el$8);
    setProp(_el$7, "height", 1);
    setProp(_el$7, "flexDirection", "row");
    setProp(_el$7, "justifyContent", "space-between");
    insertNode(_el$8, createTextNode(`Keyboard shortcuts`));
    insert(_el$7, createComponent2(Button, {
      label: "Close",
      get onPress() {
        return props.close;
      }
    }), null);
    insert(_el$6, createComponent2(For, {
      each: PROJECTS_SHORTCUTS,
      children: (shortcut) => (() => {
        var _el$10 = createElement("box"), _el$11 = createElement("text"), _el$12 = createElement("text");
        insertNode(_el$10, _el$11);
        insertNode(_el$10, _el$12);
        setProp(_el$10, "width", "100%");
        setProp(_el$10, "flexDirection", "row");
        setProp(_el$10, "flexShrink", 0);
        setProp(_el$10, "columnGap", 1);
        setProp(_el$10, "paddingLeft", 1);
        setProp(_el$10, "paddingRight", 1);
        setProp(_el$10, "border", ["bottom"]);
        setProp(_el$11, "flexGrow", 1);
        setProp(_el$11, "flexShrink", 1);
        setProp(_el$11, "wrapMode", "none");
        insert(_el$11, () => shortcut[0]);
        setProp(_el$12, "flexShrink", 0);
        setProp(_el$12, "wrapMode", "none");
        insert(_el$12, () => shortcut[1]);
        effect((_p$) => {
          var { borderSubtle: _v$7, text: _v$8, textMuted: _v$9 } = theme;
          _v$7 !== _p$.e && (_p$.e = setProp(_el$10, "borderColor", _v$7, _p$.e));
          _v$8 !== _p$.t && (_p$.t = setProp(_el$11, "fg", _v$8, _p$.t));
          _v$9 !== _p$.a && (_p$.a = setProp(_el$12, "fg", _v$9, _p$.a));
          return _p$;
        }, {
          e: undefined,
          t: undefined,
          a: undefined
        });
        return _el$10;
      })()
    }), _el$0);
    insertNode(_el$0, createTextNode(`Single-letter shortcuts are disabled while a dialog is open.`));
    effect((_p$) => {
      var _v$4 = theme.text, _v$5 = TextAttributes13.BOLD, _v$6 = theme.textMuted;
      _v$4 !== _p$.e && (_p$.e = setProp(_el$8, "fg", _v$4, _p$.e));
      _v$5 !== _p$.t && (_p$.t = setProp(_el$8, "attributes", _v$5, _p$.t));
      _v$6 !== _p$.a && (_p$.a = setProp(_el$0, "fg", _v$6, _p$.a));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined
    });
    return _el$6;
  })();
}
function SettingsDialog(props) {
  const theme = useTheme();
  const dimensions = useTerminalDimensions();
  useKeyboard((key) => {
    if (key.name === "escape")
      props.close();
  });
  return (() => {
    var _el$13 = createElement("box"), _el$14 = createElement("box"), _el$15 = createElement("text"), _el$17 = createElement("scrollbox");
    insertNode(_el$13, _el$14);
    insertNode(_el$13, _el$17);
    setProp(_el$13, "flexDirection", "column");
    setProp(_el$13, "width", "100%");
    setProp(_el$13, "rowGap", 1);
    insertNode(_el$14, _el$15);
    setProp(_el$14, "height", 1);
    setProp(_el$14, "flexDirection", "row");
    setProp(_el$14, "justifyContent", "space-between");
    insertNode(_el$15, createTextNode(`Settings`));
    insert(_el$14, createComponent2(Button, {
      label: "Close",
      get onPress() {
        return props.close;
      }
    }), null);
    setProp(_el$17, "width", "100%");
    setProp(_el$17, "scrollX", false);
    insert(_el$17, createComponent2(SettingsContent, {}));
    effect((_p$) => {
      var _v$0 = theme.text, _v$1 = TextAttributes13.BOLD, _v$10 = Math.max(10, Math.min(22, dimensions().height - 8));
      _v$0 !== _p$.e && (_p$.e = setProp(_el$15, "fg", _v$0, _p$.e));
      _v$1 !== _p$.t && (_p$.t = setProp(_el$15, "attributes", _v$1, _p$.t));
      _v$10 !== _p$.a && (_p$.a = setProp(_el$17, "height", _v$10, _p$.a));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined
    });
    return _el$13;
  })();
}
function ProjectsDialogs() {
  const projects = useProjects();
  const {
    state,
    actions
  } = projects;
  const dialog = useDialog();
  const theme = useTheme();
  const toast = useToast();
  const close = () => {
    actions.closeDialog();
    dialog.clear();
  };
  createEffect(() => {
    const kind = state.dialog;
    untrack(() => {
      if (kind === null) {
        dialog.clear();
        return;
      }
      if (kind.kind === "create") {
        dialog.replace(() => createComponent2(ProjectFormDialog, {
          onDone: (result) => {
            actions.closeDialog();
            dialog.clear();
            if (result) {
              toast.show({
                title: "Project created",
                message: result.slug,
                tone: "success"
              });
              actions.openProject(result.id);
            }
          }
        }), {
          size: "large",
          onClose: actions.closeDialog
        });
        return;
      }
      if (kind.kind === "edit") {
        const project = kind.project;
        dialog.replace(() => createComponent2(ProjectFormDialog, {
          project,
          onDone: (result) => {
            actions.closeDialog();
            dialog.clear();
            if (result) {
              toast.show({
                title: "Project updated",
                message: result.slug,
                tone: "success"
              });
            }
          }
        }), {
          size: "large",
          onClose: actions.closeDialog
        });
        return;
      }
      if (kind.kind === "confirm-archive") {
        const project = kind.project;
        dialog.replace(() => createComponent2(ConfirmDialog, {
          title: "Archive project",
          get message() {
            return `Archive "${project.name}" (${project.slug})? Archived projects stay in the registry and can be unarchived later.`;
          },
          confirmLabel: "Archive",
          get busy() {
            return state.mutating;
          },
          onConfirm: async () => {
            const ok = await actions.archiveProject(project.id);
            toast.show(ok ? {
              title: "Archived",
              message: project.slug,
              tone: "success"
            } : {
              title: "Archive failed",
              message: state.error ?? "Could not archive the project.",
              tone: "error"
            });
            close();
          },
          close
        }), {
          size: "medium",
          onClose: actions.closeDialog
        });
        return;
      }
      if (kind.kind === "confirm-unarchive") {
        const project = kind.project;
        dialog.replace(() => createComponent2(ConfirmDialog, {
          title: "Unarchive project",
          get message() {
            return `Unarchive "${project.name}" (${project.slug})?`;
          },
          confirmLabel: "Unarchive",
          get busy() {
            return state.mutating;
          },
          onConfirm: async () => {
            const ok = await actions.unarchiveProject(project.id);
            toast.show(ok ? {
              title: "Unarchived",
              message: project.slug,
              tone: "success"
            } : {
              title: "Unarchive failed",
              message: state.error ?? "Could not unarchive the project.",
              tone: "error"
            });
            close();
          },
          close
        }), {
          size: "medium",
          onClose: actions.closeDialog
        });
        return;
      }
      if (kind.kind === "confirm-delete") {
        const project = kind.project;
        dialog.replace(() => createComponent2(ConfirmDialog, {
          title: "Delete project",
          get message() {
            return `Delete "${project.name}" (${project.slug})? The project can be restored later.`;
          },
          confirmLabel: "Delete",
          danger: true,
          get busy() {
            return state.mutating;
          },
          onConfirm: async () => {
            const ok = await actions.deleteProject(project.id, kind.hard);
            toast.show(ok ? {
              title: "Deleted",
              message: project.slug,
              tone: "success"
            } : {
              title: "Delete failed",
              message: state.error ?? "Could not delete the project.",
              tone: "error"
            });
            close();
          },
          close
        }), {
          size: "medium",
          onClose: actions.closeDialog
        });
        return;
      }
      if (kind.kind === "shortcuts") {
        dialog.replace(() => createComponent2(ShortcutsDialog, {
          close
        }), {
          size: "large",
          onClose: actions.closeDialog
        });
        return;
      }
      if (kind.kind === "settings") {
        dialog.replace(() => createComponent2(SettingsDialog, {
          close
        }), {
          size: "xlarge",
          onClose: actions.closeDialog
        });
        return;
      }
    });
  });
  return null;
}
var init_dialogs = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_projects_state();
  init_theme2();
  init_dialog();
  init_toast();
  init_primitives();
  init_project_form();
  init_settings();
});

// src/cli/tui-solid/App.tsx
var exports_App = {};
__export(exports_App, {
  App: () => App
});
function RuntimeWatchdog() {
  onMount(() => {
    const stop = startEventLoopWatchdog();
    onCleanup(stop);
  });
  return null;
}
function RoutedContent() {
  const projects = useProjects();
  return createComponent2(Switch, {
    get fallback() {
      return createComponent2(ProjectsListRoute, {});
    },
    get children() {
      return [createComponent2(Match, {
        get when() {
          return projects.state.route.name === "projects";
        },
        get children() {
          return createComponent2(ProjectsListRoute, {});
        }
      }), createComponent2(Match, {
        get when() {
          return projects.state.route.name === "project";
        },
        get children() {
          return createComponent2(ProjectDetailRoute, {});
        }
      }), createComponent2(Match, {
        get when() {
          return projects.state.route.name === "roots";
        },
        get children() {
          return createComponent2(RootsRoute, {});
        }
      }), createComponent2(Match, {
        get when() {
          return projects.state.route.name === "recipes";
        },
        get children() {
          return createComponent2(RecipesRoute, {});
        }
      }), createComponent2(Match, {
        get when() {
          return projects.state.route.name === "agents";
        },
        get children() {
          return createComponent2(AgentsRoute, {});
        }
      }), createComponent2(Match, {
        get when() {
          return projects.state.route.name === "settings";
        },
        get children() {
          return createComponent2(SettingsRoute, {});
        }
      })];
    }
  });
}
function AppShell(props) {
  const renderer = useRenderer();
  const projects = useProjects();
  const dialog = useDialog();
  const dimensions = useTerminalDimensions();
  const theme = useTheme();
  const toast = useToast();
  onMount(() => {
    if (props.initialProject)
      projects.actions.openProject(props.initialProject);
  });
  useSelectionHandler((selection) => {
    const text = selection.getSelectedText().trim();
    if (!text)
      return;
    copyTextToClipboardAsync(text).then((result) => {
      if (!result.ok)
        return;
      toast.show({
        title: "Copied",
        message: `Selection copied via ${result.method ?? "clipboard"}.`,
        tone: "success"
      });
    });
  });
  useKeyboard((key) => {
    if (!key.ctrl || key.name !== "c")
      return;
    key.preventDefault();
    key.stopPropagation();
    if (renderer.getSelection()?.getSelectedText())
      renderer.clearSelection();
    else if (dialog.stack().length)
      dialog.pop();
    else
      renderer.destroy();
  });
  const sidebarW = () => sidebarWidth(dimensions().width);
  return (() => {
    var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("box");
    insertNode(_el$, _el$2);
    insertNode(_el$, _el$3);
    setProp(_el$, "flexDirection", "row");
    setProp(_el$2, "height", "100%");
    insert(_el$2, createComponent2(Sidebar, {}));
    setProp(_el$3, "flexGrow", 1);
    setProp(_el$3, "height", "100%");
    insert(_el$3, createComponent2(RoutedContent, {}));
    insert(_el$, createComponent2(ProjectsDialogs, {}), null);
    insert(_el$, createComponent2(DialogViewport, {}), null);
    insert(_el$, createComponent2(ToastViewport, {}), null);
    effect((_p$) => {
      var _v$ = dimensions().width, _v$2 = dimensions().height, _v$3 = theme.background, _v$4 = sidebarW(), _v$5 = theme.backgroundPanel, _v$6 = theme.background;
      _v$ !== _p$.e && (_p$.e = setProp(_el$, "width", _v$, _p$.e));
      _v$2 !== _p$.t && (_p$.t = setProp(_el$, "height", _v$2, _p$.t));
      _v$3 !== _p$.a && (_p$.a = setProp(_el$, "backgroundColor", _v$3, _p$.a));
      _v$4 !== _p$.o && (_p$.o = setProp(_el$2, "width", _v$4, _p$.o));
      _v$5 !== _p$.i && (_p$.i = setProp(_el$2, "backgroundColor", _v$5, _p$.i));
      _v$6 !== _p$.n && (_p$.n = setProp(_el$3, "backgroundColor", _v$6, _p$.n));
      return _p$;
    }, {
      e: undefined,
      t: undefined,
      a: undefined,
      o: undefined,
      i: undefined,
      n: undefined
    });
    return _el$;
  })();
}
function ThemedApp(props) {
  return createComponent2(ThemeProvider, {
    mode: "auto",
    get children() {
      return props.children;
    }
  });
}
function App(props) {
  return createComponent2(ProjectsProvider, {
    get children() {
      return createComponent2(ThemedApp, {
        get children() {
          return createComponent2(ToastProvider, {
            get children() {
              return createComponent2(DialogProvider, {
                get children() {
                  return createComponent2(CommandProvider, {
                    get children() {
                      return [createComponent2(RuntimeWatchdog, {}), createComponent2(AppShell, {
                        get initialProject() {
                          return props.initialProject;
                        }
                      })];
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
  });
}
var init_App = __esm(() => {
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_index_bun();
  init_server();
  init_index_bun();
  init_theme2();
  init_projects_state();
  init_toast();
  init_dialog();
  init_commands();
  init_clipboard();
  init_projects_list();
  init_project_detail();
  init_roots();
  init_recipes();
  init_agents();
  init_settings();
  init_sidebar();
  init_dialogs();
});

// src/cli/tui-solid/runtime.tsx
var exports_runtime = {};
__export(exports_runtime, {
  runSolidOpenTuiApp: () => runSolidOpenTuiApp
});
async function runSolidOpenTuiApp(initialProject) {
  const previousAlternateScreen = process.env["OTUI_USE_ALTERNATE_SCREEN"];
  process.env["OTUI_USE_ALTERNATE_SCREEN"] = "true";
  let renderer = null;
  const signalExitCodes = {
    SIGINT: 130,
    SIGTERM: 143
  };
  const signalHandlers = [];
  const restoreAlternateScreenEnv = () => {
    if (previousAlternateScreen === undefined)
      delete process.env["OTUI_USE_ALTERNATE_SCREEN"];
    else
      process.env["OTUI_USE_ALTERNATE_SCREEN"] = previousAlternateScreen;
  };
  const [{
    createCliRenderer: createCliRenderer2
  }, {
    render: render2
  }, {
    createProjectsKeymap: createProjectsKeymap2
  }, {
    KeymapProvider: KeymapProvider2
  }, {
    App: App2
  }] = await Promise.all([import("@opentui/core"), Promise.resolve().then(() => (init_index_bun(), exports_index_bun)), Promise.resolve().then(() => (init_keymap_input(), exports_keymap_input)), Promise.resolve().then(() => (init_solid(), exports_solid)), Promise.resolve().then(() => (init_App(), exports_App))]);
  try {
    renderer = await createCliRenderer2({
      exitOnCtrlC: false,
      screenMode: "alternate-screen",
      clearOnShutdown: true,
      targetFps: 60,
      consoleMode: "disabled",
      openConsoleOnError: false,
      useKittyKeyboard: {},
      useMouse: true,
      enableMouseMovement: true,
      backgroundColor: "#0a0a0a"
    });
    const keymap = createProjectsKeymap2(renderer);
    for (const signal of ["SIGINT", "SIGTERM"]) {
      const handler = () => {
        process.exitCode = signalExitCodes[signal] ?? 1;
        renderer?.destroy();
      };
      signalHandlers.push([signal, handler]);
      process.once(signal, handler);
    }
    renderer.setTerminalTitle("Projects");
    const destroyed = new Promise((resolve6) => renderer.on("destroy", () => resolve6()));
    await render2(() => createComponent2(KeymapProvider2, {
      keymap,
      get children() {
        return createComponent2(App2, {
          initialProject
        });
      }
    }), renderer);
    await destroyed;
  } finally {
    for (const [signal, handler] of signalHandlers)
      process.removeListener(signal, handler);
    renderer?.destroy();
    restoreAlternateScreenEnv();
  }
}
var init_runtime = __esm(() => {
  init_index_bun();
});

// src/cli/tui/runtime.tsx
async function runOpenTuiApp(initialProject) {
  const {
    runSolidOpenTuiApp: runSolidOpenTuiApp2
  } = await Promise.resolve().then(() => (init_runtime(), exports_runtime));
  await runSolidOpenTuiApp2(initialProject);
}
export {
  runOpenTuiApp
};