"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  try {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  } catch (e) {
    throw mod = 0, e;
  }
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// ../../node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.cjs.js
var require_index_cjs = __commonJS({
  "../../node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.cjs.js"(exports2) {
    "use strict";
    var defaultErrorConfig = {
      withStackTrace: false
    };
    var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
      const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
      const maybeStack = config.withStackTrace ? new Error().stack : void 0;
      return {
        data,
        message,
        stack: maybeStack
      };
    };
    function __awaiter(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    }
    function __values(o) {
      var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
      if (m) return m.call(o);
      if (o && typeof o.length === "number") return {
        next: function() {
          if (o && i >= o.length) o = void 0;
          return { value: o && o[i++], done: !o };
        }
      };
      throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __await(v) {
      return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
      var g = generator.apply(thisArg, _arguments || []), i, q = [];
      return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
        return this;
      }, i;
      function awaitReturn(f) {
        return function(v) {
          return Promise.resolve(v).then(f, reject);
        };
      }
      function verb(n, f) {
        if (g[n]) {
          i[n] = function(v) {
            return new Promise(function(a, b) {
              q.push([n, v, a, b]) > 1 || resume(n, v);
            });
          };
          if (f) i[n] = f(i[n]);
        }
      }
      function resume(n, v) {
        try {
          step(g[n](v));
        } catch (e) {
          settle(q[0][3], e);
        }
      }
      function step(r) {
        r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
      }
      function fulfill(value) {
        resume("next", value);
      }
      function reject(value) {
        resume("throw", value);
      }
      function settle(f, v) {
        if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
      }
    }
    function __asyncDelegator(o) {
      var i, p;
      return i = {}, verb("next"), verb("throw", function(e) {
        throw e;
      }), verb("return"), i[Symbol.iterator] = function() {
        return this;
      }, i;
      function verb(n, f) {
        i[n] = o[n] ? function(v) {
          return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
        } : f;
      }
    }
    function __asyncValues(o) {
      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
      var m = o[Symbol.asyncIterator], i;
      return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
        return this;
      }, i);
      function verb(n) {
        i[n] = o[n] && function(v) {
          return new Promise(function(resolve, reject) {
            v = o[n](v), settle(resolve, reject, v.done, v.value);
          });
        };
      }
      function settle(resolve, reject, d, v) {
        Promise.resolve(v).then(function(v2) {
          resolve({ value: v2, done: d });
        }, reject);
      }
    }
    var ResultAsync2 = class _ResultAsync {
      constructor(res) {
        this._promise = res;
      }
      static fromSafePromise(promise) {
        const newPromise = promise.then((value) => new Ok(value));
        return new _ResultAsync(newPromise);
      }
      static fromPromise(promise, errorFn) {
        const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
        return new _ResultAsync(newPromise);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      static fromThrowable(fn, errorFn) {
        return (...args) => {
          return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
            try {
              return new Ok(yield fn(...args));
            } catch (error) {
              return new Err(errorFn ? errorFn(error) : error);
            }
          }))());
        };
      }
      static combine(asyncResultList) {
        return combineResultAsyncList(asyncResultList);
      }
      static combineWithAllErrors(asyncResultList) {
        return combineResultAsyncListWithAllErrors(asyncResultList);
      }
      map(f) {
        return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
          if (res.isErr()) {
            return new Err(res.error);
          }
          return new Ok(yield f(res.value));
        })));
      }
      andThrough(f) {
        return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
          if (res.isErr()) {
            return new Err(res.error);
          }
          const newRes = yield f(res.value);
          if (newRes.isErr()) {
            return new Err(newRes.error);
          }
          return new Ok(res.value);
        })));
      }
      andTee(f) {
        return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
          if (res.isErr()) {
            return new Err(res.error);
          }
          try {
            yield f(res.value);
          } catch (e) {
          }
          return new Ok(res.value);
        })));
      }
      orTee(f) {
        return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
          if (res.isOk()) {
            return new Ok(res.value);
          }
          try {
            yield f(res.error);
          } catch (e) {
          }
          return new Err(res.error);
        })));
      }
      mapErr(f) {
        return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
          if (res.isOk()) {
            return new Ok(res.value);
          }
          return new Err(yield f(res.error));
        })));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      andThen(f) {
        return new _ResultAsync(this._promise.then((res) => {
          if (res.isErr()) {
            return new Err(res.error);
          }
          const newValue = f(res.value);
          return newValue instanceof _ResultAsync ? newValue._promise : newValue;
        }));
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      orElse(f) {
        return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
          if (res.isErr()) {
            return f(res.error);
          }
          return new Ok(res.value);
        })));
      }
      match(ok2, _err) {
        return this._promise.then((res) => res.match(ok2, _err));
      }
      unwrapOr(t) {
        return this._promise.then((res) => res.unwrapOr(t));
      }
      /**
       * @deprecated will be removed in 9.0.0.
       *
       * You can use `safeTry` without this method.
       * @example
       * ```typescript
       * safeTry(async function* () {
       *   const okValue = yield* yourResult
       * })
       * ```
       * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
       */
      safeUnwrap() {
        return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
          return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
        });
      }
      // Makes ResultAsync implement PromiseLike<Result>
      then(successCallback, failureCallback) {
        return this._promise.then(successCallback, failureCallback);
      }
      [Symbol.asyncIterator]() {
        return __asyncGenerator(this, arguments, function* _a() {
          const result = yield __await(this._promise);
          if (result.isErr()) {
            yield yield __await(errAsync(result.error));
          }
          return yield __await(result.value);
        });
      }
    };
    function okAsync(value) {
      return new ResultAsync2(Promise.resolve(new Ok(value)));
    }
    function errAsync(err2) {
      return new ResultAsync2(Promise.resolve(new Err(err2)));
    }
    var fromPromise = ResultAsync2.fromPromise;
    var fromSafePromise = ResultAsync2.fromSafePromise;
    var fromAsyncThrowable = ResultAsync2.fromThrowable;
    var combineResultList = (resultList) => {
      let acc = ok([]);
      for (const result of resultList) {
        if (result.isErr()) {
          acc = err(result.error);
          break;
        } else {
          acc.map((list) => list.push(result.value));
        }
      }
      return acc;
    };
    var combineResultAsyncList = (asyncResultList) => ResultAsync2.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
    var combineResultListWithAllErrors = (resultList) => {
      let acc = ok([]);
      for (const result of resultList) {
        if (result.isErr() && acc.isErr()) {
          acc.error.push(result.error);
        } else if (result.isErr() && acc.isOk()) {
          acc = err([result.error]);
        } else if (result.isOk() && acc.isOk()) {
          acc.value.push(result.value);
        }
      }
      return acc;
    };
    var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync2.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
    exports2.Result = void 0;
    (function(Result) {
      function fromThrowable3(fn, errorFn) {
        return (...args) => {
          try {
            const result = fn(...args);
            return ok(result);
          } catch (e) {
            return err(errorFn ? errorFn(e) : e);
          }
        };
      }
      Result.fromThrowable = fromThrowable3;
      function combine(resultList) {
        return combineResultList(resultList);
      }
      Result.combine = combine;
      function combineWithAllErrors(resultList) {
        return combineResultListWithAllErrors(resultList);
      }
      Result.combineWithAllErrors = combineWithAllErrors;
    })(exports2.Result || (exports2.Result = {}));
    function ok(value) {
      return new Ok(value);
    }
    function err(err2) {
      return new Err(err2);
    }
    function safeTry(body) {
      const n = body().next();
      if (n instanceof Promise) {
        return new ResultAsync2(n.then((r) => r.value));
      }
      return n.value;
    }
    var Ok = class {
      constructor(value) {
        this.value = value;
      }
      isOk() {
        return true;
      }
      isErr() {
        return !this.isOk();
      }
      map(f) {
        return ok(f(this.value));
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      mapErr(_f) {
        return ok(this.value);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      andThen(f) {
        return f(this.value);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      andThrough(f) {
        return f(this.value).map((_value) => this.value);
      }
      andTee(f) {
        try {
          f(this.value);
        } catch (e) {
        }
        return ok(this.value);
      }
      orTee(_f) {
        return ok(this.value);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      orElse(_f) {
        return ok(this.value);
      }
      asyncAndThen(f) {
        return f(this.value);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      asyncAndThrough(f) {
        return f(this.value).map(() => this.value);
      }
      asyncMap(f) {
        return ResultAsync2.fromSafePromise(f(this.value));
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      unwrapOr(_v) {
        return this.value;
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      match(ok2, _err) {
        return ok2(this.value);
      }
      safeUnwrap() {
        const value = this.value;
        return (function* () {
          return value;
        })();
      }
      _unsafeUnwrap(_) {
        return this.value;
      }
      _unsafeUnwrapErr(config) {
        throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
      }
      // eslint-disable-next-line @typescript-eslint/no-this-alias, require-yield
      *[Symbol.iterator]() {
        return this.value;
      }
    };
    var Err = class {
      constructor(error) {
        this.error = error;
      }
      isOk() {
        return false;
      }
      isErr() {
        return !this.isOk();
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      map(_f) {
        return err(this.error);
      }
      mapErr(f) {
        return err(f(this.error));
      }
      andThrough(_f) {
        return err(this.error);
      }
      andTee(_f) {
        return err(this.error);
      }
      orTee(f) {
        try {
          f(this.error);
        } catch (e) {
        }
        return err(this.error);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      andThen(_f) {
        return err(this.error);
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
      orElse(f) {
        return f(this.error);
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      asyncAndThen(_f) {
        return errAsync(this.error);
      }
      asyncAndThrough(_f) {
        return errAsync(this.error);
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      asyncMap(_f) {
        return errAsync(this.error);
      }
      unwrapOr(v) {
        return v;
      }
      match(_ok, err2) {
        return err2(this.error);
      }
      safeUnwrap() {
        const error = this.error;
        return (function* () {
          yield err(error);
          throw new Error("Do not use this generator out of `safeTry`");
        })();
      }
      _unsafeUnwrap(config) {
        throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
      }
      _unsafeUnwrapErr(_) {
        return this.error;
      }
      *[Symbol.iterator]() {
        const self = this;
        yield self;
        return self;
      }
    };
    var fromThrowable2 = exports2.Result.fromThrowable;
    exports2.Err = Err;
    exports2.Ok = Ok;
    exports2.ResultAsync = ResultAsync2;
    exports2.err = err;
    exports2.errAsync = errAsync;
    exports2.fromAsyncThrowable = fromAsyncThrowable;
    exports2.fromPromise = fromPromise;
    exports2.fromSafePromise = fromSafePromise;
    exports2.fromThrowable = fromThrowable2;
    exports2.ok = ok;
    exports2.okAsync = okAsync;
    exports2.safeTry = safeTry;
  }
});

// src/provisioner.ts
var provisioner_exports = {};
__export(provisioner_exports, {
  setup: () => setup,
  teardown: () => teardown
});
module.exports = __toCommonJS(provisioner_exports);

// ../../packages/prompt-kit/dist/core/render.js
var ROLE_NODE_TYPES = /* @__PURE__ */ new Set(["system-message", "user-message", "assistant-message"]);
function nodeToRole(nodeType) {
  switch (nodeType) {
    case "system-message": {
      return "system";
    }
    case "user-message": {
      return "user";
    }
    case "assistant-message": {
      return "assistant";
    }
  }
  return "user";
}
function flushMessage(state) {
  const content = state.currentLines.join("\n").trim();
  if (content.length === 0) {
    return state.messages;
  }
  return [...state.messages, { role: state.currentRole, content }];
}
function renderChild(child) {
  if (child === null || child === void 0 || typeof child === "boolean") {
    return "";
  }
  if (typeof child === "string") {
    return child;
  }
  return renderNodeToText(child);
}
function renderChildren(children) {
  return children.map((child) => renderChild(child)).join("");
}
function renderListItem(text) {
  const indented = text.trim().replaceAll("\n", "\n  ");
  return `- ${indented}`;
}
function renderList(node) {
  const items = node.children.map((child) => renderChild(child)).filter((text) => text.trim().length > 0).map((text) => renderListItem(text)).join("\n");
  return `
${items}`;
}
var DEFAULT_HEADER_LEVEL = 2;
function renderHeader(node) {
  const level = node.props.level ?? DEFAULT_HEADER_LEVEL;
  const hashes = "#".repeat(level);
  return `

${hashes} ${renderChildren(node.children).trim()}`;
}
function renderText(node) {
  return `

${renderChildren(node.children)}`;
}
function childrenText(node) {
  return renderChildren(node.children);
}
function childrenTrimmed(node) {
  return renderChildren(node.children).trim();
}
function renderOrderedList(node) {
  const items = node.children.map((child) => renderChild(child)).filter((text) => text.trim().length > 0).map((text, index) => `${String(index + 1)}. ${text.trim()}`).join("\n");
  return `

${items}`;
}
function renderCodeBlock(node) {
  const language = typeof node.props.language === "string" ? node.props.language : "";
  const content = renderChildren(node.children);
  return `

\`\`\`${language}
${content}
\`\`\``;
}
var NODE_RENDERERS = {
  list: renderList,
  "ordered-list": renderOrderedList,
  "code-block": renderCodeBlock,
  header: renderHeader,
  text: renderText,
  paragraph: childrenTrimmed,
  item: childrenTrimmed,
  bold: (node) => `**${childrenTrimmed(node)}**`,
  br: () => "\n",
  raw: childrenText,
  fragment: childrenText,
  "system-message": childrenText,
  "user-message": childrenText,
  "assistant-message": childrenText
};
function renderNodeToText(node) {
  return NODE_RENDERERS[node.nodeType](node);
}
function processFragmentChild(child, state) {
  if (child === null || child === void 0 || typeof child === "boolean") {
    return state;
  }
  if (typeof child === "string") {
    return { ...state, currentLines: [...state.currentLines, child] };
  }
  if (ROLE_NODE_TYPES.has(child.nodeType)) {
    return collectMessages(child, state);
  }
  const text = renderNodeToText(child).trim();
  if (text.length === 0) {
    return state;
  }
  return { ...state, currentLines: [...state.currentLines, text] };
}
function processFragment(node, state) {
  let current = state;
  for (const child of node.children) {
    current = processFragmentChild(child, current);
  }
  return current;
}
function collectMessages(node, state) {
  if (ROLE_NODE_TYPES.has(node.nodeType)) {
    const flushed = flushMessage(state);
    const role = nodeToRole(node.nodeType);
    const innerText = renderNodeToText(node).trim();
    return {
      messages: [...flushed, { role, content: innerText }],
      currentRole: role,
      currentLines: []
    };
  }
  if (node.nodeType === "fragment") {
    return processFragment(node, state);
  }
  const text = renderNodeToText(node).trim();
  if (text.length === 0) {
    return state;
  }
  return { ...state, currentLines: [...state.currentLines, text] };
}
function render(node) {
  const initial = {
    messages: [],
    currentRole: "user",
    currentLines: []
  };
  const finalState = collectMessages(node, initial);
  return flushMessage(finalState);
}

// ../../packages/prompt-kit/dist/core/format.js
var SEPARATOR_WIDTH = 40;
var SEPARATOR = "=".repeat(SEPARATOR_WIDTH);

// ../../packages/prompt-kit/dist/jsx-runtime.js
function jsx(type, props) {
  if (typeof type === "function") {
    return type(props);
  }
  if (type === Fragment) {
    const children2 = flattenChildren(props.children);
    return { nodeType: "fragment", props: {}, children: children2 };
  }
  const { children: rawChildren, ...restProps } = props;
  const children = flattenChildren(rawChildren);
  return { nodeType: type, props: restProps, children };
}
function jsxs(type, props) {
  return jsx(type, props);
}
var Fragment = /* @__PURE__ */ Symbol("Fragment");
function flattenChildren(raw) {
  if (raw === void 0) {
    return [];
  }
  if (Array.isArray(raw)) {
    return raw.flat(Number.POSITIVE_INFINITY);
  }
  return [raw];
}

// ../../packages/prompt-kit/dist/components/messages.js
function SystemMessage(props) {
  return jsx("system-message", { children: props.children });
}
function UserMessage(props) {
  return jsx("user-message", { children: props.children });
}

// ../../packages/prompt-kit/dist/components/structure.js
function Header(props) {
  return jsx("header", { level: props.level, children: props.children });
}
function Text(props) {
  return jsx("text", { children: props.children });
}
function List(props) {
  return jsx("list", { children: props.children });
}
function Item(props) {
  return jsx("item", { children: props.children });
}
function OrderedList(props) {
  return jsx("ordered-list", { children: props.children });
}

// ../../packages/prompt-kit/dist/sdk/to-sdk-input.js
function toSdkInput(messages) {
  const systemParts = messages.filter((message) => message.role === "system").map((message) => message.content);
  const userParts = messages.filter((message) => message.role === "user").map((message) => message.content);
  return {
    systemPrompt: systemParts.join("\n\n"),
    userContent: userParts.join("\n\n")
  };
}

// ../../agents/provisioner/dist/index.js
var import_claude_agent_sdk = require("@anthropic-ai/claude-agent-sdk");
var import_neverthrow = __toESM(require_index_cjs(), 1);
var import_node_child_process = require("node:child_process");
var SATISFIED_RULE = "Done when the objective is satisfied and you have verified it with read-only tools.";
var HANDOFF_RULE = "Once verified, stop immediately. Do not run the test or do the work the objective is preparing for \u2014 hand off to the next agent.";
var ABORT_RULE = "If you hit a hard, non-retryable failure, stop and report what failed and why, citing the tool result that proves it. Do not keep retrying.";
var DONE_WHEN_RULES = [SATISFIED_RULE, HANDOFF_RULE, ABORT_RULE];
function CompletionSection() {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Header, { children: "Done when" }),
    /* @__PURE__ */ jsx(List, { children: DONE_WHEN_RULES.map((rule) => /* @__PURE__ */ jsx(Item, { children: rule })) })
  ] });
}
var SURVEY_STEP = "Survey the current state with the read-only tools available to you, so you know what already exists before you change anything.";
var ACT_STEP = "Act: call the tools needed to move the current state toward the objective. Make a concrete step toward it every turn.";
var VERIFY_STEP = "Verify with read-only tools that the objective is satisfied. Confirm from live tool results, not from assumption.";
var STOP_STEP = "Stop and hand off. Do NOT run the test or do the work the objective is preparing for \u2014 the next agent takes over once setup is verified.";
var SETUP_STEPS = [SURVEY_STEP, ACT_STEP, VERIFY_STEP, STOP_STEP];
function LifecycleSection() {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Header, { children: "Setup procedure" }),
    /* @__PURE__ */ jsx(OrderedList, { children: SETUP_STEPS.map((step) => /* @__PURE__ */ jsx(Item, { children: step })) })
  ] });
}
var READ_THE_ERROR_RULE = "Read the tool result. Diagnose what the error says before deciding what to do \u2014 never react blindly.";
var ADAPT_RULE = "If the error suggests a recoverable cause (a missing prerequisite, a transient failure, a value the tool wants changed), adapt: take the corrective step the result points to, then retry once.";
var STOP_AND_REPORT_RULE = "If the error is a hard, non-retryable failure, or a retry does not clear it, stop and report what failed and why, citing the tool result that proves it. Hand off for manual intervention.";
var NO_LOOP_RULE = "Never loop on the same failing call. Either the adaptation makes progress or you stop \u2014 do not repeat an identical call expecting a different result.";
var RECOVERY_RULES = [
  READ_THE_ERROR_RULE,
  ADAPT_RULE,
  STOP_AND_REPORT_RULE,
  NO_LOOP_RULE
];
function RecoverySection() {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Header, { children: "Error recovery" }),
    /* @__PURE__ */ jsx(Text, { children: `When a tool fails, diagnose from its result and either adapt or stop:` }),
    /* @__PURE__ */ jsx(List, { children: RECOVERY_RULES.map((rule) => /* @__PURE__ */ jsx(Item, { children: rule })) })
  ] });
}
var ORCHESTRATE_RULE = "You orchestrate the provided tools to satisfy the objective. You decide WHICH tool to call and WHETHER to retry \u2014 nothing more. You never run the test or do the work yourself.";
var READ_DESCRIPTIONS_RULE = "You are not told in advance what the tools are or what they do. Read each provided tool's own description before calling it, and pick tools by what their descriptions say they do.";
var NO_FABRICATION_RULE = "Never fabricate values, amounts, identifiers, or addresses \u2014 those belong to the tools. Reason only from the objective and live tool results, never from assumptions about the domain.";
var ROLE_RULES = [
  ORCHESTRATE_RULE,
  READ_DESCRIPTIONS_RULE,
  NO_FABRICATION_RULE
];
function RoleIntroSection() {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Text, { children: `You are the Provisioner. Your job is to prepare the conditions described by the
objective so that another agent can take over once setup is verified. You do this
by calling the provided tools \u2014 you do not do the work yourself.` }),
    /* @__PURE__ */ jsx(Header, { children: "Your role" }),
    /* @__PURE__ */ jsx(List, { children: ROLE_RULES.map((rule) => /* @__PURE__ */ jsx(Item, { children: rule })) })
  ] });
}
var NO_FABRICATION_RULE2 = "CRITICAL: never compute or invent values, amounts, identifiers, or addresses yourself. The tools own all of those. Pass only what the objective and prior tool results give you.";
var NO_RETRY_LARGER_RULE = "CRITICAL: if a tool refuses an input or caps it, do NOT blindly retry with a larger value and do NOT try to exceed the cap. Read the error, then adapt or stop and report.";
var REASON_FROM_TOOLS_RULE = "Reason from the objective and live tool results, not from hardcoded domain knowledge. What is available, valid, or possible is whatever the tools report \u2014 never assume.";
var SCOPE_RULE = "Only do what the objective calls for. Do not call tools or change state beyond what is needed to satisfy it.";
var PROGRESS_RULE = "Make a concrete step toward the objective every turn. You have a bounded turn budget \u2014 do not loop on read-only calls without acting.";
var SAFETY_RULES = [
  NO_FABRICATION_RULE2,
  NO_RETRY_LARGER_RULE,
  REASON_FROM_TOOLS_RULE,
  SCOPE_RULE,
  PROGRESS_RULE
];
function SafetySection() {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Header, { children: "Guardrails" }),
    /* @__PURE__ */ jsx(List, { children: SAFETY_RULES.map((rule) => /* @__PURE__ */ jsx(Item, { children: rule })) })
  ] });
}
var SURVEY_STEP2 = "Survey what currently exists with the read-only tools, so you know what setup left behind before you undo it.";
var UNDO_STEP = "Use the provided tools to undo and clean up everything setup created. Let the tools decide ordering and amounts \u2014 do not direct them.";
var VERIFY_STEP2 = "Verify with read-only tools that the cleanup is complete, then stop.";
var FAIL_STEP = "On a failure mid-cleanup, retry the tool once. If it still fails, report what remains and stop \u2014 do not improvise manual steps the tools did not perform.";
var TEARDOWN_STEPS = [SURVEY_STEP2, UNDO_STEP, VERIFY_STEP2, FAIL_STEP];
function TeardownSection() {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Header, { children: "Teardown" }),
    /* @__PURE__ */ jsx(Text, { children: `When asked to tear down, undo and clean up everything setup created, regardless of
what the test left behind:` }),
    /* @__PURE__ */ jsx(OrderedList, { children: TEARDOWN_STEPS.map((step) => /* @__PURE__ */ jsx(Item, { children: step })) })
  ] });
}
function PhaseBehavior({ phase }) {
  switch (phase) {
    case "setup": {
      return /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(LifecycleSection, {}),
        /* @__PURE__ */ jsx(CompletionSection, {})
      ] });
    }
    case "teardown": {
      return /* @__PURE__ */ jsx(TeardownSection, {});
    }
  }
}
function ProvisionerPrompt(props) {
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(SystemMessage, { children: [
      /* @__PURE__ */ jsx(RoleIntroSection, {}),
      /* @__PURE__ */ jsx(SafetySection, {}),
      /* @__PURE__ */ jsx(PhaseBehavior, { phase: props.phase }),
      /* @__PURE__ */ jsx(RecoverySection, {})
    ] }),
    /* @__PURE__ */ jsxs(UserMessage, { children: [
      /* @__PURE__ */ jsx(Header, { children: "Objective" }),
      /* @__PURE__ */ jsx(Text, { children: props.objective })
    ] })
  ] });
}
function renderProvisionerPrompt(phase, objective) {
  return toSdkInput(render(ProvisionerPrompt({ phase, objective })));
}
var PROVISIONER_AGENT_NAME = "provisioner";
function isStringRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readContentArray(message) {
  if (message.type !== "assistant") {
    return void 0;
  }
  const inner = message.message;
  if (!isStringRecord(inner)) {
    return void 0;
  }
  const { content } = inner;
  if (!Array.isArray(content)) {
    return void 0;
  }
  return content;
}
function readThoughtText(block) {
  if (block.type === "text" && typeof block.text === "string") {
    return block.text;
  }
  if (block.type === "thinking" && typeof block.thinking === "string") {
    return block.thinking;
  }
  return void 0;
}
function emitThought(onEvent, block) {
  if (!isStringRecord(block)) {
    return;
  }
  const text = readThoughtText(block);
  if (text === void 0 || text.trim().length === 0) {
    return;
  }
  onEvent({ type: "THOUGHT", agent: PROVISIONER_AGENT_NAME, text });
}
function emitAssistantThoughts(onEvent, message) {
  if (!isStringRecord(message)) {
    return;
  }
  const content = readContentArray(message);
  if (content === void 0) {
    return;
  }
  for (const block of content) {
    emitThought(onEvent, block);
  }
}
function spawnDetached(options) {
  const child = (0, import_node_child_process.spawn)(options.command, options.args, {
    cwd: options.cwd,
    env: options.env,
    stdio: ["pipe", "pipe", "pipe"],
    detached: true,
    signal: options.signal
  });
  child.stderr.pipe(process.stderr);
  return {
    stdin: child.stdin,
    stdout: child.stdout,
    get killed() {
      return child.killed;
    },
    get exitCode() {
      return child.exitCode;
    },
    kill: child.kill.bind(child),
    on: child.on.bind(child),
    once: child.once.bind(child),
    off: child.off.bind(child)
  };
}
var DEFAULT_MAX_TURNS = 40;
var DEFAULT_TIMEOUT_MS = 3e5;
function buildAbortController(timeoutMs, signal) {
  const controller = new AbortController();
  const timer = setTimeout(() => {
    controller.abort();
  }, timeoutMs);
  if (signal !== void 0) {
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      controller.abort();
    });
  }
  controller.signal.addEventListener("abort", () => {
    clearTimeout(timer);
  });
  return controller;
}
function buildQueryOptions(params) {
  const { input, config, controller } = params;
  const baseOptions = {
    allowedTools: [...config.allowedTools],
    mcpServers: { ...config.mcpServers },
    maxTurns: config.maxTurns ?? DEFAULT_MAX_TURNS,
    spawnClaudeCodeProcess: spawnDetached,
    thinking: { type: "adaptive" },
    abortController: controller,
    systemPrompt: input.systemPrompt
  };
  if (config.model === void 0) {
    return baseOptions;
  }
  return { ...baseOptions, model: config.model };
}
function buildQueryRunner(params) {
  const { input, config } = params;
  const safeLaunch = (0, import_neverthrow.fromThrowable)(
    config.queryRunner ?? import_claude_agent_sdk.query,
    (cause) => ({ type: "AI_CALL_FAILED", cause })
  );
  return safeLaunch({
    prompt: input.userContent,
    options: buildQueryOptions(params)
  });
}
async function drainStream(params) {
  const { stream, onEvent } = params;
  for await (const message of stream) {
    if (onEvent !== void 0) {
      emitAssistantThoughts(onEvent, message);
    }
  }
}
function drainQuery(params) {
  return import_neverthrow.ResultAsync.fromThrowable(
    drainStream,
    (cause) => ({
      type: "AI_CALL_FAILED",
      cause
    })
  )(params);
}
function runPhase(input, config) {
  const controller = buildAbortController(config.timeoutMs ?? DEFAULT_TIMEOUT_MS, config.signal);
  return buildQueryRunner({ input, config, controller }).asyncAndThen(
    (stream) => drainQuery({ stream, onEvent: config.onEvent })
  );
}
function setup(objective, config) {
  return runPhase(renderProvisionerPrompt("setup", objective), config).map(() => ({ objective }));
}
function teardown(objective, config) {
  return runPhase(renderProvisionerPrompt("teardown", objective), config).map(() => ({
    objective
  }));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  setup,
  teardown
});
