// ../toolcraft/src/index.ts
import { fileURLToPath as fileURLToPath2 } from "node:url";

// ../toolcraft/src/user-error.ts
var UserError = class extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = "UserError";
  }
};

// ../toolcraft/src/human-in-loop/config.ts
function validateHumanInLoopOnDefine(config) {
  const label = Array.isArray(config.children) ? "group" : "command";
  if (config.confirm === true && config.humanInLoop !== void 0 && config.humanInLoop !== null) {
    throw new Error(`${label} '${config.name}': use either confirm or humanInLoop, not both`);
  }
  if (config.humanInLoop === void 0 || config.humanInLoop === null) {
    return;
  }
  if (config.humanInLoop.mode !== "sync" && config.humanInLoop.mode !== "async") {
    throw new Error(`${label} '${config.name}': humanInLoop.mode must be "sync" or "async"`);
  }
  if (typeof config.humanInLoop.message !== "function") {
    throw new Error(`${label} '${config.name}': humanInLoop.message must be a function`);
  }
}
function mergeHumanInLoopFromGroup(groupHumanInLoop, childHumanInLoop) {
  if (childHumanInLoop !== void 0) {
    return childHumanInLoop;
  }
  return groupHumanInLoop;
}

// ../toolcraft-schema/src/json.ts
function Json() {
  return {
    kind: "json"
  };
}

// ../toolcraft-schema/src/oneof.ts
function assertValidBranches(branches, discriminator) {
  if (Object.keys(branches).length === 0) {
    throw new Error("OneOf schema requires at least one branch");
  }
  for (const [branchName, branch] of Object.entries(branches)) {
    if (Object.prototype.hasOwnProperty.call(branch.shape, discriminator)) {
      throw new Error(
        `OneOf branch "${branchName}" must not declare discriminator field "${discriminator}".`
      );
    }
  }
}
function OneOf(config) {
  assertValidBranches(config.branches, config.discriminator);
  return {
    kind: "oneOf",
    discriminator: config.discriminator,
    branches: config.branches
  };
}

// ../toolcraft-schema/src/record.ts
function Record(value) {
  return {
    kind: "record",
    value
  };
}

// ../toolcraft-schema/src/union.ts
function isOptionalSchema(schema) {
  return schema.kind === "optional";
}
function getRequiredKeys(schema) {
  return Object.keys(schema.shape).filter((key) => !isOptionalSchema(schema.shape[key])).sort();
}
function getRequiredKeyFingerprint(schema) {
  return getRequiredKeys(schema).join("+");
}
function assertUniqueRequiredKeyFingerprints(branches) {
  const fingerprints = /* @__PURE__ */ new Map();
  branches.forEach((branch, index) => {
    const requiredKeys = getRequiredKeys(branch);
    const fingerprint = JSON.stringify(requiredKeys);
    const existing = fingerprints.get(fingerprint);
    if (existing === void 0) {
      fingerprints.set(fingerprint, {
        display: requiredKeys.join("+"),
        indices: [index]
      });
      return;
    }
    existing.indices.push(index);
  });
  for (const { display, indices } of fingerprints.values()) {
    if (indices.length > 1) {
      throw new Error(
        `Union branches [${indices.join(", ")}] share required-key fingerprint "${display}". Each branch must require a distinct set of keys.`
      );
    }
  }
}
function assertValidBranches2(branches) {
  if (branches.length === 0) {
    throw new Error("Union schema requires at least one branch");
  }
  assertUniqueRequiredKeyFingerprints(branches);
}
function Union(branches) {
  assertValidBranches2(branches);
  return {
    kind: "union",
    branches
  };
}

// ../toolcraft-schema/src/validate.ts
var missingValue = /* @__PURE__ */ Symbol("missingValue");
function validate(schema, value) {
  const state = { issues: [] };
  const result = walkSchema(schema, value, [], state);
  if (state.issues.length > 0) {
    return { ok: false, issues: state.issues };
  }
  return { ok: true, value: result.present ? result.value : void 0 };
}
function walkSchema(schema, value, path2, state) {
  if (schema.kind === "optional") {
    return walkOptional(schema, value, path2, state);
  }
  if (value === missingValue) {
    addIssue(
      state,
      path2,
      expectedFor(schema),
      "missing",
      `Expected ${expectedFor(schema)} at ${formatPath(path2)}`
    );
    return { present: false };
  }
  if (value === null && schema.nullable === true) {
    return { present: true, value };
  }
  switch (schema.kind) {
    case "string":
      return walkString(schema, value, path2, state);
    case "number":
      return walkNumber(schema, value, path2, state);
    case "boolean":
      return walkBoolean(value, path2, state);
    case "enum":
      return walkEnum(schema, value, path2, state);
    case "array":
      return walkArray(schema, value, path2, state);
    case "object":
      return walkObject(schema, value, path2, state);
    case "oneOf":
      return walkOneOf(schema, value, path2, state);
    case "union":
      return walkUnion(schema, value, path2, state);
    case "record":
      return walkRecord(schema, value, path2, state);
    case "json":
      return walkJson(value, path2, state);
  }
}
function walkOptional(schema, value, path2, state) {
  if (value === missingValue || value === void 0) {
    const defaultValue = getDefault(schema.inner);
    if (defaultValue.present) {
      return walkSchema(schema.inner, cloneDefault(defaultValue.value), path2, state);
    }
    return { present: false };
  }
  return walkSchema(schema.inner, value, path2, state);
}
function walkString(schema, value, path2, state) {
  if (typeof value !== "string") {
    addExpectedIssue(state, path2, "string", value);
    return { present: true, value };
  }
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
    const expected = `string with length at least ${schema.minLength}`;
    addIssue(
      state,
      path2,
      expected,
      `string with length ${value.length}`,
      `Expected ${expected} at ${formatPath(path2)}`
    );
  }
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
    const expected = `string with length at most ${schema.maxLength}`;
    addIssue(
      state,
      path2,
      expected,
      `string with length ${value.length}`,
      `Expected ${expected} at ${formatPath(path2)}`
    );
  }
  if (schema.pattern !== void 0) {
    const pattern = compilePattern(schema.pattern);
    if (pattern === void 0 || !pattern.test(value)) {
      const expected = `string matching pattern ${schema.pattern}`;
      addIssue(state, path2, expected, value, `Expected ${expected} at ${formatPath(path2)}`);
    }
  }
  return { present: true, value };
}
function walkNumber(schema, value, path2, state) {
  if (typeof value !== "number" || !Number.isFinite(value)) {
    addExpectedIssue(state, path2, schema.jsonType === "integer" ? "integer" : "number", value);
    return { present: true, value };
  }
  if (schema.jsonType === "integer" && !Number.isInteger(value)) {
    addExpectedIssue(state, path2, "integer", value);
  }
  if (schema.minimum !== void 0 && value < schema.minimum) {
    const expected = `number greater than or equal to ${schema.minimum}`;
    addIssue(state, path2, expected, String(value), `Expected ${expected} at ${formatPath(path2)}`);
  }
  if (schema.maximum !== void 0 && value > schema.maximum) {
    const expected = `number less than or equal to ${schema.maximum}`;
    addIssue(state, path2, expected, String(value), `Expected ${expected} at ${formatPath(path2)}`);
  }
  return { present: true, value };
}
function walkBoolean(value, path2, state) {
  if (typeof value !== "boolean") {
    addExpectedIssue(state, path2, "boolean", value);
  }
  return { present: true, value };
}
function walkEnum(schema, value, path2, state) {
  if (!schema.values.includes(value)) {
    const expected = `one of ${schema.values.join(", ")}`;
    addIssue(
      state,
      path2,
      expected,
      receivedValue(value),
      `Expected ${expected} at ${formatPath(path2)}`
    );
  }
  return { present: true, value };
}
function walkArray(schema, value, path2, state) {
  if (!Array.isArray(value)) {
    addExpectedIssue(state, path2, "array", value);
    return { present: true, value };
  }
  if (schema.minItems !== void 0 && value.length < schema.minItems) {
    const expected = `array with at least ${schema.minItems} items`;
    addIssue(
      state,
      path2,
      expected,
      `array with ${value.length} items`,
      `Expected ${expected} at ${formatPath(path2)}`
    );
  }
  if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
    const expected = `array with at most ${schema.maxItems} items`;
    addIssue(
      state,
      path2,
      expected,
      `array with ${value.length} items`,
      `Expected ${expected} at ${formatPath(path2)}`
    );
  }
  const nextValue = value.map((item, index) => {
    const result = walkSchema(schema.item, item, [...path2, String(index)], state);
    return result.present ? result.value : item;
  });
  return { present: true, value: nextValue };
}
function walkObject(schema, value, path2, state, injectedProperties = {}) {
  if (!isPlainRecord(value)) {
    addExpectedIssue(state, path2, "object", value);
    return { present: true, value };
  }
  const nextValue = {};
  const allowedKeys = /* @__PURE__ */ new Set([...Object.keys(schema.shape), ...Object.keys(injectedProperties)]);
  for (const [key, propertySchema] of Object.entries(schema.shape)) {
    const propertyValue = Object.hasOwn(value, key) ? value[key] : missingValue;
    const result = walkSchema(propertySchema, propertyValue, [...path2, key], state);
    if (result.present) {
      setOwnValue(nextValue, key, result.value);
    }
  }
  for (const [key, injectedValue] of Object.entries(injectedProperties)) {
    if (Object.hasOwn(value, key)) {
      setOwnValue(nextValue, key, value[key]);
    } else {
      setOwnValue(nextValue, key, injectedValue);
    }
  }
  for (const [key, propertyValue] of Object.entries(value)) {
    if (allowedKeys.has(key)) {
      continue;
    }
    if (schema.additionalProperties === true) {
      setOwnValue(nextValue, key, propertyValue);
    } else {
      addUnexpectedPropertyIssue(state, [...path2, key]);
    }
  }
  return { present: true, value: nextValue };
}
function walkOneOf(schema, value, path2, state) {
  if (!isPlainRecord(value)) {
    addExpectedIssue(state, path2, "object", value);
    return { present: true, value };
  }
  const discriminatorValue = value[schema.discriminator];
  const discriminatorPath = [...path2, schema.discriminator];
  const branchValues = Object.keys(schema.branches);
  const expected = `one of ${branchValues.join(", ")}`;
  if (!Object.hasOwn(value, schema.discriminator)) {
    addIssueWithMessage(
      state,
      discriminatorPath,
      expected,
      "missing",
      `Missing discriminator "${schema.discriminator}" at ${formatPath(path2)}. Expected one of: ${branchValues.join(", ")}.`
    );
    return { present: true, value };
  }
  if (typeof discriminatorValue !== "string" || !Object.hasOwn(schema.branches, discriminatorValue)) {
    addIssueWithMessage(
      state,
      discriminatorPath,
      expected,
      receivedValue(discriminatorValue),
      `Expected ${expected} at ${formatPath(discriminatorPath)}, got ${formatReceivedDiscriminator(discriminatorValue)}`
    );
    return { present: true, value };
  }
  return walkObject(schema.branches[discriminatorValue], value, path2, state, {
    [schema.discriminator]: discriminatorValue
  });
}
function walkUnion(schema, value, path2, state) {
  if (isPlainRecord(value)) {
    const candidateBranches = schema.branches.filter((branch) => hasRequiredKeys(branch, value));
    if (candidateBranches.length === 1) {
      return walkObject(candidateBranches[0], value, path2, state);
    }
  }
  const matches = [];
  for (const branch of schema.branches) {
    const branchState = { issues: [] };
    const result = walkObject(branch, value, path2, branchState);
    if (branchState.issues.length === 0 && result.present) {
      matches.push({ fingerprint: getRequiredKeyFingerprint(branch), value: result.value });
    }
  }
  if (matches.length === 1) {
    return { present: true, value: matches[0].value };
  }
  if (matches.length === 0) {
    const branchDescriptions = schema.branches.map((branch) => getRequiredKeyFingerprint(branch));
    addIssueWithMessage(
      state,
      path2,
      "exactly one union branch",
      "0 matching branches",
      `No union branch matched at ${formatPath(path2)}. Tried ${schema.branches.length} branches. Expected one of: ${branchDescriptions.join(" | ")}.`
    );
    return { present: true, value };
  }
  addIssueWithMessage(
    state,
    path2,
    "exactly one union branch",
    `${matches.length} matching branches`,
    `Expected exactly one union branch at ${formatPath(path2)}, but matched more than one branch: ${matches.map((match) => match.fingerprint).join(" | ")}`
  );
  return { present: true, value };
}
function hasRequiredKeys(schema, value) {
  for (const [key, propertySchema] of Object.entries(schema.shape)) {
    if (propertySchema.kind !== "optional" && !Object.hasOwn(value, key)) {
      return false;
    }
  }
  return true;
}
function walkRecord(schema, value, path2, state) {
  if (!isPlainRecord(value)) {
    addExpectedIssue(state, path2, "object", value);
    return { present: true, value };
  }
  const nextValue = {};
  for (const [key, propertyValue] of Object.entries(value)) {
    const result = walkSchema(schema.value, propertyValue, [...path2, key], state);
    if (result.present) {
      setOwnValue(nextValue, key, result.value);
    }
  }
  return { present: true, value: nextValue };
}
function walkJson(value, path2, state) {
  if (isJsonValue(value)) {
    return { present: true, value };
  }
  addExpectedIssue(state, path2, "JSON value", value);
  return { present: true, value };
}
function getDefault(schema) {
  if (schema.default !== void 0) {
    return { present: true, value: schema.default };
  }
  if (schema.kind === "optional") {
    return getDefault(schema.inner);
  }
  return { present: false };
}
function isPlainRecord(value) {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    return false;
  }
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}
function isJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    return typeof value !== "number" || Number.isFinite(value);
  }
  if (Array.isArray(value)) {
    if (ancestors.has(value)) {
      return false;
    }
    ancestors.add(value);
    const result = value.every((item) => isJsonValue(item, ancestors));
    ancestors.delete(value);
    return result;
  }
  if (isPlainRecord(value)) {
    if (ancestors.has(value)) {
      return false;
    }
    ancestors.add(value);
    const result = Object.values(value).every((item) => isJsonValue(item, ancestors));
    ancestors.delete(value);
    return result;
  }
  return false;
}
function cloneDefault(value) {
  return structuredClone(value);
}
function setOwnValue(target, key, value) {
  Object.defineProperty(target, key, {
    configurable: true,
    enumerable: true,
    writable: true,
    value
  });
}
function expectedFor(schema) {
  switch (schema.kind) {
    case "string":
      return "string";
    case "number":
      return schema.jsonType === "integer" ? "integer" : "number";
    case "boolean":
      return "boolean";
    case "enum":
      return `one of ${schema.values.join(", ")}`;
    case "array":
      return "array";
    case "object":
    case "oneOf":
    case "record":
      return "object";
    case "union":
      return "exactly one union branch";
    case "json":
      return "JSON value";
    case "optional":
      return expectedFor(schema.inner);
  }
}
function addExpectedIssue(state, path2, expected, value) {
  addIssue(
    state,
    path2,
    expected,
    receivedType(value),
    `Expected ${expected} at ${formatPath(path2)}`
  );
}
function addUnexpectedPropertyIssue(state, path2) {
  addIssue(
    state,
    path2,
    "no additional properties",
    "unknown property",
    `Unexpected property ${formatPath(path2)}`
  );
}
function addIssue(state, path2, expected, received, _message) {
  state.issues.push({
    path: path2,
    expected,
    received,
    message: formatIssueMessage(expected, path2, received)
  });
}
function addIssueWithMessage(state, path2, expected, received, message) {
  state.issues.push({
    path: path2,
    expected,
    received,
    message
  });
}
function formatIssueMessage(expected, path2, received) {
  return `Expected ${expected} at ${formatPath(path2)}, got ${received}`;
}
function formatPath(path2) {
  return path2.length === 0 ? "value" : path2.join(".");
}
function compilePattern(pattern) {
  try {
    return new RegExp(pattern);
  } catch {
    return void 0;
  }
}
function receivedType(value) {
  if (value === null) {
    return "null";
  }
  if (Array.isArray(value)) {
    return "array";
  }
  if (typeof value === "number" && Number.isInteger(value)) {
    return "integer";
  }
  return typeof value;
}
function receivedValue(value) {
  if (typeof value === "string") {
    return value;
  }
  if (value === void 0) {
    return "undefined";
  }
  return String(value);
}
function formatReceivedDiscriminator(value) {
  if (typeof value === "string") {
    return JSON.stringify(value);
  }
  return receivedValue(value);
}

// ../toolcraft-schema/src/index.ts
function assertValidEnumValues(values) {
  if (values.length === 0) {
    throw new Error("Enum schema requires at least one value");
  }
  const uniqueValues = new Set(values);
  if (uniqueValues.size !== values.length) {
    throw new Error("Enum schema values must be unique");
  }
  if (values.some((value) => typeof value === "number" && !Number.isFinite(value))) {
    throw new Error("Enum schema numeric values must be finite");
  }
}
function assertNonNegativeInteger(value, name) {
  if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
    throw new Error(`${name} must be a non-negative integer`);
  }
}
function assertFiniteNumber(value, name) {
  if (value !== void 0 && !Number.isFinite(value)) {
    throw new Error(`${name} must be finite`);
  }
}
function assertMinMaxOrder(minimum, maximum, minimumName, maximumName) {
  if (minimum !== void 0 && maximum !== void 0 && minimum > maximum) {
    throw new Error(`${minimumName} must be less than or equal to ${maximumName}`);
  }
}
function assertValidDefault(schema) {
  if (schema.default === void 0) {
    return;
  }
  const result = validate(schema, schema.default);
  if (!result.ok) {
    throw new Error(
      `default must satisfy schema: ${result.issues[0]?.message ?? "invalid default"}`
    );
  }
}
function assertPattern(pattern) {
  if (pattern === void 0) {
    return;
  }
  try {
    new RegExp(pattern);
  } catch {
    throw new Error("pattern must be a valid regular expression");
  }
}
var S = {
  String(options = {}) {
    assertNonNegativeInteger(options.minLength, "minLength");
    assertNonNegativeInteger(options.maxLength, "maxLength");
    assertMinMaxOrder(options.minLength, options.maxLength, "minLength", "maxLength");
    assertPattern(options.pattern);
    const schema = {
      kind: "string",
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Number(options = {}) {
    assertFiniteNumber(options.minimum, "minimum");
    assertFiniteNumber(options.maximum, "maximum");
    assertMinMaxOrder(options.minimum, options.maximum, "minimum", "maximum");
    assertFiniteNumber(options.default, "default");
    if (options.jsonType === "integer" && options.default !== void 0 && !Number.isInteger(options.default)) {
      throw new Error("default must be an integer");
    }
    const schema = {
      kind: "number",
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Boolean(options = {}) {
    const schema = {
      kind: "boolean",
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Enum(values, options = {}) {
    assertValidEnumValues(values);
    if (options.jsonType === "integer" && values.some((value) => typeof value !== "number" || !Number.isInteger(value))) {
      throw new Error("Integer enum values must be integers");
    }
    const schema = {
      kind: "enum",
      values,
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Array(item, options = {}) {
    assertNonNegativeInteger(options.minItems, "minItems");
    assertNonNegativeInteger(options.maxItems, "maxItems");
    assertMinMaxOrder(options.minItems, options.maxItems, "minItems", "maxItems");
    const schema = {
      kind: "array",
      item,
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Object(shape, options = {}) {
    const schema = {
      kind: "object",
      shape,
      ...options
    };
    assertValidDefault(schema);
    return schema;
  },
  Optional(inner) {
    return {
      kind: "optional",
      inner
    };
  },
  OneOf,
  Union,
  Record,
  Json
};

// ../toolcraft/src/package-metadata.ts
import { existsSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

// ../toolcraft/src/index.ts
var commandConfigSymbol = /* @__PURE__ */ Symbol("toolcraft.command.config");
var commandSourcePathSymbol = /* @__PURE__ */ Symbol("toolcraft.command.sourcePath");
function cloneScope(scope) {
  return scope === void 0 ? void 0 : [...scope];
}
function cloneSecretDefinition(secret) {
  return {
    env: secret.env,
    description: secret.description,
    optional: secret.optional
  };
}
function cloneSecrets(secrets) {
  if (secrets === void 0) {
    return {};
  }
  return Object.fromEntries(
    Object.entries(secrets).map(([key, secret]) => [key, cloneSecretDefinition(secret)])
  );
}
function cloneRequires(requires) {
  if (requires === void 0) {
    return void 0;
  }
  return {
    auth: requires.auth,
    apiVersion: requires.apiVersion,
    check: requires.check
  };
}
function cloneCommandExamples(examples) {
  return (examples ?? []).map((example) => ({
    title: example.title,
    params: { ...example.params }
  }));
}
function parseStackPath(candidate) {
  if (candidate.startsWith("file://")) {
    try {
      return fileURLToPath2(candidate);
    } catch {
      return void 0;
    }
  }
  if (candidate.startsWith("/")) {
    return candidate;
  }
  return void 0;
}
function extractStackPath(line) {
  const trimmed = line.trim();
  const fileIndex = trimmed.indexOf("file://");
  if (fileIndex >= 0) {
    const location2 = trimmed.slice(fileIndex);
    const separatorIndex2 = location2.lastIndexOf(":");
    const previousSeparatorIndex2 = separatorIndex2 >= 0 ? location2.lastIndexOf(":", separatorIndex2 - 1) : -1;
    const candidate2 = separatorIndex2 >= 0 && previousSeparatorIndex2 >= 0 ? location2.slice(0, previousSeparatorIndex2) : location2;
    return parseStackPath(candidate2);
  }
  const slashIndex = trimmed.indexOf("/");
  if (slashIndex < 0) {
    return void 0;
  }
  const location = trimmed.slice(slashIndex);
  const separatorIndex = location.lastIndexOf(":");
  const previousSeparatorIndex = separatorIndex >= 0 ? location.lastIndexOf(":", separatorIndex - 1) : -1;
  const candidate = separatorIndex >= 0 && previousSeparatorIndex >= 0 ? location.slice(0, previousSeparatorIndex) : location;
  return parseStackPath(candidate);
}
function inferCommandSourcePath() {
  const stack = new Error().stack;
  if (typeof stack !== "string") {
    return void 0;
  }
  for (const line of stack.split("\n").slice(1)) {
    const candidate = extractStackPath(line);
    if (candidate === void 0) {
      continue;
    }
    if (candidate.includes("/packages/toolcraft/src/index.ts") || candidate.includes("/packages/toolcraft/dist/index.js") || candidate.includes("/node_modules/toolcraft/dist/index.js")) {
      continue;
    }
    return candidate;
  }
  return void 0;
}
function composeChecks(parentCheck, childCheck) {
  if (parentCheck === void 0) {
    return childCheck;
  }
  if (childCheck === void 0) {
    return parentCheck;
  }
  return async (ctx) => {
    const parentResult = await parentCheck(ctx);
    if (!parentResult.ok) {
      return parentResult;
    }
    return childCheck(ctx);
  };
}
function mergeRequires(parent, child) {
  if (parent === void 0 && child === void 0) {
    return void 0;
  }
  const merged = {
    auth: child?.auth ?? parent?.auth,
    apiVersion: child?.apiVersion ?? parent?.apiVersion,
    check: composeChecks(parent?.check, child?.check)
  };
  if (merged.auth === void 0 && merged.apiVersion === void 0 && merged.check === void 0) {
    return void 0;
  }
  return merged;
}
function mergeSecrets(parent, child) {
  return cloneSecrets({
    ...parent,
    ...child
  });
}
function resolveCommandScope(ownScope, inheritedScope) {
  return cloneScope(ownScope ?? inheritedScope) ?? ["cli", "sdk"];
}
function createBaseCommand(config) {
  const command = {
    kind: "command",
    name: config.name,
    description: config.description,
    hidden: config.hidden ?? false,
    examples: cloneCommandExamples(config.examples),
    aliases: [...config.aliases ?? []],
    positional: [...config.positional ?? []],
    params: config.params,
    result: config.result,
    secrets: cloneSecrets(config.secrets),
    scope: resolveCommandScope(config.scope, void 0),
    confirm: config.confirm ?? false,
    humanInLoop: config.humanInLoop,
    requires: cloneRequires(config.requires),
    handler: config.handler,
    render: config.render
  };
  Object.defineProperty(command, commandConfigSymbol, {
    value: {
      scope: cloneScope(config.scope),
      hidden: config.hidden ?? false,
      examples: cloneCommandExamples(config.examples),
      result: config.result,
      humanInLoop: config.humanInLoop,
      secrets: cloneSecrets(config.secrets),
      requires: cloneRequires(config.requires),
      sourcePath: inferCommandSourcePath()
    }
  });
  return command;
}
function getInternalCommandConfig(command) {
  return command[commandConfigSymbol];
}
function materializeCommand(command, inherited) {
  const internal = getInternalCommandConfig(command);
  const materialized = {
    kind: "command",
    name: command.name,
    description: command.description,
    hidden: internal.hidden,
    examples: cloneCommandExamples(internal.examples),
    aliases: [...command.aliases],
    positional: [...command.positional],
    params: command.params,
    result: internal.result,
    secrets: mergeSecrets(inherited.secrets, internal.secrets),
    scope: resolveCommandScope(internal.scope, inherited.scope),
    confirm: command.confirm,
    humanInLoop: mergeHumanInLoopFromGroup(inherited.humanInLoop, internal.humanInLoop),
    requires: mergeRequires(inherited.requires, internal.requires),
    handler: command.handler,
    render: command.render
  };
  Object.defineProperty(materialized, commandConfigSymbol, {
    value: {
      scope: cloneScope(internal.scope),
      hidden: internal.hidden,
      examples: cloneCommandExamples(internal.examples),
      result: internal.result,
      humanInLoop: internal.humanInLoop,
      secrets: cloneSecrets(internal.secrets),
      requires: cloneRequires(internal.requires),
      sourcePath: internal.sourcePath
    }
  });
  Object.defineProperty(materialized, commandSourcePathSymbol, {
    value: internal.sourcePath
  });
  return materialized;
}
function defineCommand(config) {
  validateHumanInLoopOnDefine(config);
  return materializeCommand(
    createBaseCommand(config),
    {
      scope: void 0,
      humanInLoop: void 0,
      secrets: {},
      requires: void 0
    }
  );
}

// src/terminal-pilot.ts
import { randomUUID } from "node:crypto";

// src/terminal-session.ts
import { EventEmitter } from "node:events";
import { accessSync, chmodSync, constants } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import * as nodePty from "node-pty";

// src/ansi.ts
var ESC = 27;
var BEL = 7;
var ST = 156;
var CSI = 155;
var OSC = 157;
var DCS = 144;
var SOS = 152;
var PM = 158;
var APC = 159;
function stripAnsi(input) {
  let output = "";
  for (let index = 0; index < input.length; index += 1) {
    const code = input.charCodeAt(index);
    if (code === ESC) {
      const nextCode = input.charCodeAt(index + 1);
      if (nextCode === 91) {
        index = consumeCsi(input, index + 2);
        continue;
      }
      if (nextCode === 93) {
        index = consumeTerminatedString(input, index + 2, true);
        continue;
      }
      if (nextCode === 80 || nextCode === 88 || nextCode === 94 || nextCode === 95) {
        index = consumeTerminatedString(input, index + 2, false);
        continue;
      }
      if (!Number.isNaN(nextCode)) {
        index += 1;
      }
      continue;
    }
    if (code === CSI) {
      index = consumeCsi(input, index + 1);
      continue;
    }
    if (code === OSC) {
      index = consumeTerminatedString(input, index + 1, true);
      continue;
    }
    if (code === DCS || code === SOS || code === PM || code === APC) {
      index = consumeTerminatedString(input, index + 1, false);
      continue;
    }
    output += input[index];
  }
  return output;
}
function consumeCsi(input, index) {
  while (index < input.length) {
    const code = input.charCodeAt(index);
    if (code >= 64 && code <= 126) {
      return index;
    }
    index += 1;
  }
  return input.length;
}
function consumeTerminatedString(input, index, allowBellTerminator) {
  while (index < input.length) {
    const code = input.charCodeAt(index);
    if (code === ST || allowBellTerminator && code === BEL) {
      return index;
    }
    if (code === ESC && input.charCodeAt(index + 1) === 92) {
      return index + 1;
    }
    index += 1;
  }
  return input.length;
}

// src/errors.ts
function hasOwnErrorCode(error, code) {
  return error instanceof Error && Object.prototype.hasOwnProperty.call(error, "code") && error.code === code;
}

// src/terminal-buffer.ts
var RESET_SGR = "\x1B[0m";
var DEC_SPECIAL_GRAPHICS = {
  j: "\u2518",
  k: "\u2510",
  l: "\u250C",
  m: "\u2514",
  n: "\u253C",
  q: "\u2500",
  t: "\u251C",
  u: "\u2524",
  v: "\u2534",
  w: "\u252C",
  x: "\u2502"
};
var TerminalBuffer = class {
  _cols;
  _rows;
  _screen;
  _primaryScreen = null;
  _cursorX = 0;
  _cursorY = 0;
  _savedCursor;
  _scrollTop = 0;
  _scrollBottom;
  _state = 0 /* Normal */;
  _csiParams = "";
  _csiPrivate = "";
  _autoWrap = true;
  _pendingWrap = false;
  _originMode = false;
  _insertMode = false;
  _tabStops;
  _lastPrintedChar = null;
  _style = createDefaultStyleState();
  _styleSequence = "";
  _stringState = 0 /* Normal */;
  _charsetTarget = null;
  _g0Charset = "ascii";
  _g1Charset = "ascii";
  _shiftOut = false;
  displayBuffer;
  constructor(cols, rows) {
    this._cols = cols;
    this._rows = rows;
    this._scrollBottom = rows - 1;
    this._screen = this._makeScreen(cols, rows);
    this._tabStops = this._createDefaultTabStops(cols);
    this._savedCursor = this._createSavedCursorState();
    this.displayBuffer = Object.defineProperties(
      {},
      {
        cursorX: { get: () => this._cursorX, enumerable: true },
        cursorY: { get: () => this._cursorY, enumerable: true },
        data: { get: () => this._screen, enumerable: true }
      }
    );
  }
  write(data) {
    for (const ch of data) {
      this._feed(ch);
    }
  }
  renderLine(row) {
    const cells = this._screen[row] ?? [];
    let lastVisibleCell = -1;
    for (let index = cells.length - 1; index >= 0; index -= 1) {
      if (cells[index] !== null) {
        lastVisibleCell = index;
        break;
      }
    }
    if (lastVisibleCell === -1) {
      return "";
    }
    let line = "";
    let activeStyle = "";
    for (let index = 0; index <= lastVisibleCell; index += 1) {
      const cell = cells[index];
      const cellStyle = cell?.style ?? "";
      if (cellStyle !== activeStyle) {
        line += cellStyle.length > 0 ? cellStyle : RESET_SGR;
        activeStyle = cellStyle;
      }
      line += cell?.[1] ?? " ";
    }
    if (activeStyle.length > 0) {
      line += RESET_SGR;
    }
    return line;
  }
  resize(cols, rows) {
    while (this._screen.length < rows) {
      this._screen.push(this._makeRow(cols));
    }
    this._screen.length = rows;
    for (let y = 0; y < rows; y++) {
      const row = this._screen[y] ?? this._makeRow(cols);
      while (row.length < cols) row.push(null);
      row.length = cols;
      this._screen[y] = row;
    }
    this._cols = cols;
    this._rows = rows;
    this._scrollTop = this._clamp(this._scrollTop, 0, rows - 1);
    this._scrollBottom = this._clamp(this._scrollBottom, 0, rows - 1);
    if (this._scrollTop >= this._scrollBottom) {
      this._scrollTop = 0;
      this._scrollBottom = rows - 1;
    }
    this._cursorX = this._clamp(this._cursorX, 0, cols - 1);
    this._cursorY = this._clamp(this._cursorY, 0, rows - 1);
  }
  _makeScreen(cols, rows) {
    return Array.from({ length: rows }, () => this._makeRow(cols));
  }
  _makeRow(cols) {
    return Array(cols).fill(null);
  }
  _createDefaultTabStops(cols) {
    const tabStops = /* @__PURE__ */ new Set();
    for (let column = 8; column < cols; column += 8) {
      tabStops.add(column);
    }
    return tabStops;
  }
  _clamp(value, min, max) {
    return Math.max(min, Math.min(max, value));
  }
  _createSavedCursorState() {
    return {
      x: this._cursorX,
      y: this._cursorY,
      autoWrap: this._autoWrap,
      style: { ...this._style, fg: this._style.fg?.slice(), bg: this._style.bg?.slice() },
      styleSequence: this._styleSequence
    };
  }
  _saveCursor() {
    this._savedCursor = this._createSavedCursorState();
  }
  _restoreCursor() {
    this._cursorX = this._clamp(this._savedCursor.x, 0, this._cols - 1);
    this._cursorY = this._clamp(this._savedCursor.y, 0, this._rows - 1);
    this._autoWrap = this._savedCursor.autoWrap;
    this._style = {
      ...this._savedCursor.style,
      fg: this._savedCursor.style.fg?.slice(),
      bg: this._savedCursor.style.bg?.slice()
    };
    this._styleSequence = this._savedCursor.styleSequence;
  }
  _resetModes() {
    this._autoWrap = true;
    this._originMode = false;
    this._insertMode = false;
    this._pendingWrap = false;
    this._tabStops = this._createDefaultTabStops(this._cols);
    this._g0Charset = "ascii";
    this._g1Charset = "ascii";
    this._shiftOut = false;
    this._resetStyle();
  }
  _writePrintable(ch) {
    const width = this._cellWidth(ch);
    if (width === 0) {
      this._appendCombiningMark(ch);
      return;
    }
    if (this._autoWrap && this._pendingWrap) {
      this._cursorX = 0;
      this._newline();
    } else if (this._autoWrap && this._cursorX + width > this._cols) {
      this._cursorX = 0;
      this._newline();
    }
    if (this._insertMode) {
      const row = this._screen[this._cursorY];
      if (row) {
        row.splice(this._cursorX, 0, ...Array(width).fill(null));
        row.splice(this._cols);
      }
    }
    this._setChar(this._cursorY, this._cursorX, ch);
    for (let column = 1; column < width && this._cursorX + column < this._cols; column += 1) {
      const row = this._screen[this._cursorY];
      if (row) row[this._cursorX + column] = null;
    }
    this._lastPrintedChar = ch;
    if (!this._autoWrap) {
      this._cursorX = Math.min(this._cursorX + width, this._cols - 1);
      this._pendingWrap = false;
    } else if (this._cursorX + width >= this._cols) {
      this._cursorX = this._cols - 1;
      this._pendingWrap = true;
    } else {
      this._cursorX += width;
      this._pendingWrap = false;
    }
  }
  _cellWidth(ch) {
    const codePoint = ch.codePointAt(0);
    if (codePoint === void 0) return 0;
    if (isCombiningCodePoint(codePoint)) {
      return 0;
    }
    if (codePoint >= 4352 && codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || codePoint >= 11904 && codePoint <= 12350 || codePoint >= 12353 && codePoint <= 13247 || codePoint >= 13312 && codePoint <= 19903 || codePoint >= 19968 && codePoint <= 42191 || codePoint >= 44032 && codePoint <= 55215 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65049 || codePoint >= 65072 && codePoint <= 65135 || codePoint >= 65280 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 127488 && codePoint <= 131069 || codePoint >= 131072 && codePoint <= 262141) {
      return Math.min(2, this._cols);
    }
    return 1;
  }
  _appendCombiningMark(ch) {
    const target = this._findCombiningTarget();
    if (target === null) {
      return;
    }
    const cell = this._screen[target.y]?.[target.x];
    if (cell === null || cell === void 0) {
      return;
    }
    cell[1] += ch;
  }
  _findCombiningTarget() {
    const startX = this._pendingWrap ? this._cursorX : this._cursorX - 1;
    for (let y = this._cursorY; y >= 0; y -= 1) {
      const row = this._screen[y];
      if (row === void 0) {
        continue;
      }
      for (let x = y === this._cursorY ? startX : this._cols - 1; x >= 0; x -= 1) {
        if (row[x] !== null) {
          return { x, y };
        }
      }
    }
    return null;
  }
  _setChar(y, x, ch) {
    const row = this._screen[y];
    if (row && x >= 0 && x < this._cols) {
      const renderedChar = this._style.conceal ? " " : ch;
      const cell = [renderedChar.charCodeAt(0), renderedChar];
      if (this._styleSequence.length > 0) {
        Object.defineProperty(cell, "style", {
          value: this._styleSequence,
          writable: true,
          configurable: true
        });
      }
      row[x] = cell;
    }
  }
  _eraseLine(y, fromX, toX) {
    const row = this._screen[y];
    if (!row) return;
    for (let x = fromX; x <= toX && x < this._cols; x++) {
      row[x] = null;
    }
  }
  _scrollUp(count) {
    for (let i = 0; i < count; i++) {
      this._screen.splice(this._scrollTop, 1);
      this._screen.splice(this._scrollBottom, 0, this._makeRow(this._cols));
    }
  }
  _scrollDown(count) {
    for (let i = 0; i < count; i++) {
      this._screen.splice(this._scrollBottom, 1);
      this._screen.splice(this._scrollTop, 0, this._makeRow(this._cols));
    }
  }
  _newline() {
    this._pendingWrap = false;
    if (this._cursorY === this._scrollBottom) {
      this._scrollUp(1);
    } else {
      this._cursorY = Math.min(this._cursorY + 1, this._rows - 1);
    }
  }
  _parseCsiParams() {
    if (!this._csiParams) return [];
    const values = this._csiParams.split(";").flatMap((segment) => segment.split(":")).map((segment) => segment === "" ? 0 : parseInt(segment, 10));
    if ((values[0] === 38 || values[0] === 48) && values[1] === 2 && values[2] === 0) {
      values.splice(2, 1);
    }
    return values;
  }
  _execCsi(final) {
    const params2 = this._parseCsiParams();
    const p0 = params2[0] ?? 0;
    const p1 = params2[1] ?? 0;
    if (this._csiPrivate === "?") {
      if (final === "h" || final === "l") {
        if (params2.includes(7)) {
          this._autoWrap = final === "h";
        }
        if (params2.includes(6)) {
          this._originMode = final === "h";
          this._cursorX = 0;
          this._cursorY = this._originMode ? this._scrollTop : 0;
        }
        if (params2.includes(1049)) {
          if (final === "h") {
            this._primaryScreen = {
              screen: this._screen,
              cursorX: this._cursorX,
              cursorY: this._cursorY,
              pendingWrap: this._pendingWrap,
              style: { ...this._style, fg: this._style.fg?.slice(), bg: this._style.bg?.slice() },
              styleSequence: this._styleSequence
            };
            this._screen = this._makeScreen(this._cols, this._rows);
            this._cursorX = 0;
            this._cursorY = 0;
            this._pendingWrap = false;
          } else {
            if (this._primaryScreen !== null) {
              this._screen = this._primaryScreen.screen;
              this._cursorX = this._primaryScreen.cursorX;
              this._cursorY = this._primaryScreen.cursorY;
              this._pendingWrap = this._primaryScreen.pendingWrap;
              this._style = this._primaryScreen.style;
              this._styleSequence = this._primaryScreen.styleSequence;
              this._primaryScreen = null;
            }
          }
          if (final === "h") this._resetStyle();
        }
      }
      return;
    }
    if ((final === "h" || final === "l") && params2.includes(4)) {
      this._insertMode = final === "h";
      return;
    }
    switch (final) {
      case "A":
        this._cursorY = this._clamp(this._cursorY - Math.max(1, p0), 0, this._rows - 1);
        break;
      case "B":
        this._cursorY = this._clamp(this._cursorY + Math.max(1, p0), 0, this._rows - 1);
        break;
      case "C":
      // cursor forward
      case "a":
        this._cursorX = this._clamp(this._cursorX + Math.max(1, p0), 0, this._cols - 1);
        break;
      case "D":
        this._cursorX = this._clamp(this._cursorX - Math.max(1, p0), 0, this._cols - 1);
        break;
      case "E":
        this._cursorY = this._clamp(this._cursorY + Math.max(1, p0), 0, this._rows - 1);
        this._cursorX = 0;
        break;
      case "F":
        this._cursorY = this._clamp(this._cursorY - Math.max(1, p0), 0, this._rows - 1);
        this._cursorX = 0;
        break;
      case "G":
      // cursor horizontal absolute
      case "`":
        this._cursorX = this._clamp(Math.max(1, p0) - 1, 0, this._cols - 1);
        break;
      case "H":
      // cursor position
      case "f":
        this._cursorY = this._originMode ? this._clamp(this._scrollTop + Math.max(1, p0) - 1, this._scrollTop, this._scrollBottom) : this._clamp(Math.max(1, p0) - 1, 0, this._rows - 1);
        this._cursorX = this._clamp(Math.max(1, p1) - 1, 0, this._cols - 1);
        break;
      case "I":
        for (let i = 0; i < Math.max(1, p0); i++) {
          this._cursorX = Math.min(this._cols - 1, (Math.floor(this._cursorX / 8) + 1) * 8);
        }
        break;
      case "J":
        if (p0 === 0) {
          this._eraseLine(this._cursorY, this._cursorX, this._cols - 1);
          for (let y = this._cursorY + 1; y < this._rows; y++)
            this._eraseLine(y, 0, this._cols - 1);
        } else if (p0 === 1) {
          for (let y = 0; y < this._cursorY; y++) this._eraseLine(y, 0, this._cols - 1);
          this._eraseLine(this._cursorY, 0, this._cursorX);
        } else if (p0 === 2) {
          for (let y = 0; y < this._rows; y++) this._eraseLine(y, 0, this._cols - 1);
        }
        break;
      case "K":
        if (p0 === 0) this._eraseLine(this._cursorY, this._cursorX, this._cols - 1);
        else if (p0 === 1) this._eraseLine(this._cursorY, 0, this._cursorX);
        else if (p0 === 2) this._eraseLine(this._cursorY, 0, this._cols - 1);
        break;
      case "X":
        this._eraseLine(this._cursorY, this._cursorX, this._cursorX + Math.max(1, p0) - 1);
        break;
      case "L": {
        if (this._cursorY < this._scrollTop || this._cursorY > this._scrollBottom) {
          break;
        }
        const n = Math.max(1, p0);
        for (let i = 0; i < n; i++) {
          this._screen.splice(this._scrollBottom, 1);
          this._screen.splice(this._cursorY, 0, this._makeRow(this._cols));
        }
        break;
      }
      case "M": {
        if (this._cursorY < this._scrollTop || this._cursorY > this._scrollBottom) {
          break;
        }
        const n = Math.max(1, p0);
        for (let i = 0; i < n; i++) {
          this._screen.splice(this._cursorY, 1);
          this._screen.splice(this._scrollBottom, 0, this._makeRow(this._cols));
        }
        break;
      }
      case "P": {
        const row = this._screen[this._cursorY];
        if (row) {
          const n = Math.max(1, p0);
          row.splice(this._cursorX, n);
          while (row.length < this._cols) row.push(null);
        }
        break;
      }
      case "@": {
        const row = this._screen[this._cursorY];
        if (row) {
          const n = Math.max(1, p0);
          for (let i = 0; i < n; i++) row.splice(this._cursorX, 0, null);
          row.splice(this._cols);
        }
        break;
      }
      case "S":
        this._scrollUp(Math.max(1, p0));
        break;
      case "T":
        if (params2.length <= 1) this._scrollDown(Math.max(1, p0));
        break;
      case "Z": {
        const n = Math.max(1, p0);
        for (let i = 0; i < n; i++) {
          this._cursorX = Math.max(0, (Math.ceil(this._cursorX / 8) - 1) * 8);
        }
        break;
      }
      case "b":
        if (this._lastPrintedChar !== null) {
          for (let index = 0; index < Math.max(1, p0); index += 1) {
            this._writePrintable(this._lastPrintedChar);
          }
        }
        break;
      case "d":
        this._cursorY = this._clamp(Math.max(1, p0) - 1, 0, this._rows - 1);
        break;
      case "e":
        this._cursorY = this._clamp(this._cursorY + Math.max(1, p0), 0, this._rows - 1);
        break;
      case "r": {
        const top = this._clamp(Math.max(1, p0) - 1, 0, this._rows - 1);
        const bottom = this._clamp((p1 === 0 ? this._rows : p1) - 1, 0, this._rows - 1);
        if (top < bottom) {
          this._scrollTop = top;
          this._scrollBottom = bottom;
        }
        this._cursorX = 0;
        this._cursorY = this._originMode ? this._scrollTop : 0;
        break;
      }
      case "s":
        this._saveCursor();
        break;
      case "u":
        this._restoreCursor();
        break;
      case "p":
        if (this._csiPrivate === "!") {
          this._resetModes();
        }
        break;
      case "m":
        this._applySgr(params2);
        break;
      default:
        break;
    }
  }
  _feed(ch) {
    const code = ch.charCodeAt(0);
    if (this._state !== 0 /* Normal */ && (code === 24 || code === 26)) {
      this._state = 0 /* Normal */;
      return;
    }
    if (this._state === 2 /* Csi */ && code === 27) {
      this._state = 1 /* Escape */;
      return;
    }
    switch (this._state) {
      case 0 /* Normal */:
        this._feedNormal(ch, code);
        break;
      case 1 /* Escape */:
        this._feedEscape(ch, code);
        break;
      case 2 /* Csi */:
        this._feedCsi(ch, code);
        break;
      case 3 /* Osc */:
        if (code === 7 || code === 156) {
          this._state = 0 /* Normal */;
        } else if (code === 27) {
          this._stringState = 3 /* Osc */;
          this._state = 5 /* StringEscape */;
        }
        break;
      case 4 /* Str */:
        if (code === 156) {
          this._state = 0 /* Normal */;
        } else if (code === 27) {
          this._stringState = 4 /* Str */;
          this._state = 5 /* StringEscape */;
        }
        break;
      case 5 /* StringEscape */:
        this._state = ch === "\\" ? 0 /* Normal */ : this._stringState;
        break;
      case 6 /* EscCharset */:
        if (this._charsetTarget === "g0") this._g0Charset = ch === "0" ? "graphics" : "ascii";
        if (this._charsetTarget === "g1") this._g1Charset = ch === "0" ? "graphics" : "ascii";
        this._charsetTarget = null;
        this._state = 0 /* Normal */;
        break;
      case 7 /* EscHash */:
        if (ch === "8") {
          for (let row = 0; row < this._rows; row += 1) {
            for (let column = 0; column < this._cols; column += 1) {
              this._setChar(row, column, "E");
            }
          }
          this._cursorX = 0;
          this._cursorY = 0;
        }
        this._state = 0 /* Normal */;
        break;
    }
  }
  _feedNormal(ch, code) {
    if (code === 27) {
      this._state = 1 /* Escape */;
    } else if (code === 155) {
      this._csiParams = "";
      this._csiPrivate = "";
      this._state = 2 /* Csi */;
    } else if (code === 157) {
      this._state = 3 /* Osc */;
    } else if (code === 144 || code === 152 || code === 158 || code === 159) {
      this._state = 4 /* Str */;
    } else if (code === 133) {
      this._cursorX = 0;
      this._newline();
    } else if (code === 156) {
    } else if (code === 7 || code === 5 || code === 6) {
    } else if (code === 8) {
      this._pendingWrap = false;
      if (this._cursorX > 0) this._cursorX--;
    } else if (code === 127) {
    } else if (code === 9) {
      const nextTabStop = [...this._tabStops].sort((left, right) => left - right).find((tabStop) => tabStop > this._cursorX);
      this._cursorX = nextTabStop ?? this._cols - 1;
    } else if (code === 10 || code === 11 || code === 12) {
      this._newline();
    } else if (code === 13) {
      this._pendingWrap = false;
      this._cursorX = 0;
    } else if (code === 14 || code === 15) {
      this._shiftOut = code === 14;
    } else if (code >= 32 && code !== 127) {
      const charset = this._shiftOut ? this._g1Charset : this._g0Charset;
      this._writePrintable(charset === "graphics" ? DEC_SPECIAL_GRAPHICS[ch] ?? ch : ch);
    }
  }
  _feedEscape(ch, code) {
    this._state = 0 /* Normal */;
    if (code === 91) {
      this._csiParams = "";
      this._csiPrivate = "";
      this._state = 2 /* Csi */;
    } else if (code === 93) {
      this._state = 3 /* Osc */;
    } else if (code === 80 || code === 88 || code === 94 || code === 95) {
      this._state = 4 /* Str */;
    } else if (code === 40 || code === 41 || code === 42 || code === 43 || code === 45 || code === 46) {
      this._charsetTarget = code === 40 ? "g0" : code === 41 ? "g1" : null;
      this._state = 6 /* EscCharset */;
    } else if (code === 35) {
      this._state = 7 /* EscHash */;
    } else if (code === 55) {
      this._saveCursor();
    } else if (code === 56) {
      this._restoreCursor();
    } else if (code === 68) {
      this._newline();
    } else if (code === 69) {
      this._cursorX = 0;
      this._newline();
    } else if (code === 77) {
      if (this._cursorY === this._scrollTop) {
        this._scrollDown(1);
      } else {
        this._cursorY = Math.max(0, this._cursorY - 1);
      }
    } else if (code === 72) {
      this._tabStops.add(this._cursorX);
    } else if (code === 99) {
      this._screen = this._makeScreen(this._cols, this._rows);
      this._cursorX = 0;
      this._cursorY = 0;
      this._scrollTop = 0;
      this._scrollBottom = this._rows - 1;
      this._resetModes();
      this._savedCursor = this._createSavedCursorState();
    }
  }
  _feedCsi(ch, code) {
    if (code >= 64 && code <= 126) {
      this._execCsi(ch);
      this._state = 0 /* Normal */;
    } else if (code === 63 || code === 33 || code === 62 || code === 32) {
      this._csiPrivate = ch;
    } else if (code >= 48 && code <= 57 || code === 59 || code === 58) {
      this._csiParams += ch;
    }
  }
  _resetStyle() {
    this._style = createDefaultStyleState();
    this._styleSequence = "";
  }
  _applySgr(params2) {
    const normalizedParams = params2.length === 0 ? [0] : params2;
    for (let index = 0; index < normalizedParams.length; index += 1) {
      const value = normalizedParams[index] ?? 0;
      switch (value) {
        case 0:
          this._resetStyle();
          break;
        case 1:
          this._style.bold = true;
          break;
        case 2:
          this._style.dim = true;
          break;
        case 3:
          this._style.italic = true;
          break;
        case 4:
          this._style.underline = true;
          break;
        case 7:
          this._style.inverse = true;
          break;
        case 8:
          this._style.conceal = true;
          break;
        case 9:
          this._style.strikethrough = true;
          break;
        case 21:
        case 22:
          this._style.bold = false;
          this._style.dim = false;
          break;
        case 23:
          this._style.italic = false;
          break;
        case 24:
          this._style.underline = false;
          break;
        case 27:
          this._style.inverse = false;
          break;
        case 28:
          this._style.conceal = false;
          break;
        case 29:
          this._style.strikethrough = false;
          break;
        case 39:
          this._style.fg = void 0;
          break;
        case 49:
          this._style.bg = void 0;
          break;
        case 38:
        case 48:
          index = this._applyExtendedColor(value, normalizedParams, index);
          break;
        default:
          if (value >= 30 && value <= 37 || value >= 90 && value <= 97) {
            this._style.fg = [value];
          } else if (value >= 40 && value <= 47 || value >= 100 && value <= 107) {
            this._style.bg = [value];
          }
          break;
      }
    }
    this._styleSequence = serializeStyleState(this._style);
  }
  _applyExtendedColor(control, params2, index) {
    const mode = params2[index + 1];
    const target = control === 38 ? "fg" : "bg";
    if (mode === 5) {
      const paletteIndex = params2[index + 2];
      if (paletteIndex !== void 0) {
        this._style[target] = [control, 5, paletteIndex];
        return index + 2;
      }
      return index;
    }
    if (mode === 2) {
      const red = params2[index + 2];
      const green = params2[index + 3];
      const blue = params2[index + 4];
      if (red !== void 0 && green !== void 0 && blue !== void 0) {
        this._style[target] = [control, 2, red, green, blue];
        return index + 4;
      }
    }
    return index;
  }
};
function createDefaultStyleState() {
  return {
    bold: false,
    dim: false,
    italic: false,
    underline: false,
    inverse: false,
    conceal: false,
    strikethrough: false
  };
}
function isCombiningCodePoint(codePoint) {
  return codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071;
}
function serializeStyleState(state) {
  const codes = [];
  if (state.bold) {
    codes.push(1);
  }
  if (state.dim) {
    codes.push(2);
  }
  if (state.italic) {
    codes.push(3);
  }
  if (state.underline) {
    codes.push(4);
  }
  if (state.inverse) {
    codes.push(7);
  }
  if (state.conceal) {
    codes.push(8);
  }
  if (state.strikethrough) {
    codes.push(9);
  }
  if (state.fg !== void 0) {
    codes.push(...state.fg);
  }
  if (state.bg !== void 0) {
    codes.push(...state.bg);
  }
  return codes.length === 0 ? "" : `\x1B[${codes.join(";")}m`;
}

// src/keys.ts
var NAMED_KEY_SEQUENCES = {
  Enter: "\r",
  Tab: "	",
  Escape: "\x1B",
  Backspace: "\x7F",
  Delete: "\x1B[3~",
  ArrowUp: "\x1B[A",
  ArrowDown: "\x1B[B",
  ArrowRight: "\x1B[C",
  ArrowLeft: "\x1B[D",
  Home: "\x1B[H",
  End: "\x1B[F",
  PageUp: "\x1B[5~",
  PageDown: "\x1B[6~",
  Space: " "
};
var NAMED_KEY_LOWER = new Map(
  Object.entries(NAMED_KEY_SEQUENCES).map(([k, v]) => [k.toLowerCase(), v])
);
var VALID_KEYS_HINT = `Valid keys: ${Object.keys(NAMED_KEY_SEQUENCES).join(", ")}, Control+<letter>, Alt+<key>`;
var NAMED_KEY_PATTERN = Object.keys(NAMED_KEY_SEQUENCES).map(caseInsensitivePattern).join("|");
var TERMINAL_KEY_PATTERN = `^(?:${NAMED_KEY_PATTERN}|.|[Cc][Oo][Nn][Tt][Rr][Oo][Ll]\\+[A-Za-z]|[Aa][Ll][Tt]\\+.+)$`;
function unknownKeyError(key) {
  return new Error(`Unknown terminal key: ${key}. ${VALID_KEYS_HINT}`);
}
function keyToSequence(key) {
  const lowerKey = key.toLowerCase();
  const namedSequence = NAMED_KEY_LOWER.get(lowerKey);
  if (namedSequence !== void 0) {
    return namedSequence;
  }
  if (lowerKey.startsWith("control+")) {
    return controlKeyToSequence(key.slice("control+".length));
  }
  if (lowerKey.startsWith("alt+")) {
    const nestedKey = key.slice("alt+".length);
    if (nestedKey.length === 0) {
      throw unknownKeyError(key);
    }
    if (nestedKey.length === 1) {
      return "\x1B" + nestedKey;
    }
    try {
      return "\x1B" + keyToSequence(nestedKey);
    } catch {
      throw unknownKeyError(key);
    }
  }
  if (key.length === 1) {
    return key;
  }
  throw unknownKeyError(key);
}
function controlKeyToSequence(controlKey) {
  if (controlKey.length !== 1) {
    throw unknownKeyError(`Control+${controlKey}`);
  }
  const uppercaseLetter = controlKey.toUpperCase();
  const charCode = uppercaseLetter.charCodeAt(0);
  if (charCode < 65 || charCode > 90) {
    throw unknownKeyError(`Control+${controlKey}`);
  }
  return String.fromCharCode(charCode - 64);
}
function caseInsensitivePattern(value) {
  let pattern = "";
  for (const character of value) {
    const lower = character.toLowerCase();
    const upper = character.toUpperCase();
    pattern += lower === upper ? escapePatternCharacter(character) : `[${upper}${lower}]`;
  }
  return pattern;
}
function escapePatternCharacter(character) {
  return character.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
}

// src/terminal-screen.ts
var TerminalScreen = class {
  lines;
  rawLines;
  cursor;
  size;
  constructor({
    lines,
    rawLines,
    cursor,
    size
  }) {
    this.lines = Object.freeze(lines.map((line) => stripAnsi(line)));
    this.rawLines = Object.freeze([...rawLines]);
    this.cursor = Object.freeze({ ...cursor });
    this.size = Object.freeze({ ...size });
    Object.freeze(this);
  }
  get text() {
    return this.lines.join("\n");
  }
  contains(substring) {
    return this.text.includes(substring);
  }
  line(index) {
    const normalizedIndex = index < 0 ? this.lines.length + index : index;
    const line = this.lines[normalizedIndex];
    if (line === void 0) {
      throw new RangeError(`Line index out of bounds: ${index}`);
    }
    return line;
  }
};

// src/terminal-session.ts
var DEFAULT_COLS = 120;
var DEFAULT_ROWS = 40;
var DEFAULT_TIMEOUT_MS = 1e4;
var WAIT_FOR_POLL_MS = 10;
var TYPE_DELAY_MS = 15;
var CLOSE_AFTER_SIGNAL_GRACE_MS = 250;
var CLOSE_AFTER_SIGTERM_MS = 1e3;
var CLOSE_AFTER_SIGKILL_MS = 1e3;
var TerminalSession = class {
  id;
  command;
  pid;
  exitCode = null;
  pty;
  terminal;
  emitter = new EventEmitter();
  exitPromise;
  rawBuffer = "";
  lastDataAt = Date.now();
  currentCols;
  currentRows;
  closePromise = null;
  constructor({
    id,
    command,
    args = [],
    cwd = process.cwd(),
    env = process.env,
    cols = DEFAULT_COLS,
    rows = DEFAULT_ROWS,
    observe = false
  }) {
    assertTerminalGeometry(cols, rows);
    this.id = id;
    this.command = command;
    this.currentCols = cols;
    this.currentRows = rows;
    this.terminal = new TerminalBuffer(cols, rows);
    this.pty = createPtyProcess({ command, args, cwd, env, cols, rows });
    this.pid = this.pty.pid;
    const dataSubscription = this.pty.onData((chunk) => {
      this.rawBuffer += chunk;
      this.lastDataAt = Date.now();
      this.terminal.write(chunk);
      if (observe) {
        process.stderr.write(chunk);
      }
    });
    let exitSubscription;
    this.exitPromise = new Promise((resolve) => {
      exitSubscription = this.pty.onExit(({ exitCode }) => {
        if (this.exitCode !== null) {
          resolve(this.exitCode);
          return;
        }
        this.exitCode = exitCode;
        dataSubscription.dispose();
        exitSubscription?.dispose();
        this.emitter.emit("exit", exitCode);
        resolve(exitCode);
      });
    });
  }
  async type(text) {
    for (const character of text) {
      await this.send(character);
      await sleep(TYPE_DELAY_MS);
    }
  }
  async fill(text) {
    await this.send(text.replace(/\r?\n/g, "\r"));
  }
  async press(key) {
    await this.send(keyToSequence(key));
  }
  async send(raw) {
    if (this.exitCode !== null) {
      throw new Error(`Terminal session "${this.id}" has already exited.`);
    }
    this.pty.write(raw);
  }
  async signal(sig) {
    if (this.exitCode !== null) {
      return;
    }
    this.pty.kill(sig);
  }
  async waitFor(pattern, opts) {
    const timeout = opts?.timeout ?? DEFAULT_TIMEOUT_MS;
    assertTimeout(timeout);
    const startedAt = Date.now();
    while (Date.now() - startedAt <= timeout) {
      const matched = matchPattern(this.rawBuffer, pattern);
      if (matched !== null) {
        return matched;
      }
      if (this.exitCode !== null) {
        throw new Error(`Terminal session "${this.id}" exited before matching pattern: ${String(pattern)}`);
      }
      await sleep(WAIT_FOR_POLL_MS);
    }
    throw new Error(`Timed out waiting for pattern after ${timeout}ms: ${String(pattern)}`);
  }
  async waitForQuiet(ms) {
    assertQuietPeriod(ms);
    while (true) {
      const remaining = ms - (Date.now() - this.lastDataAt);
      if (remaining <= 0) {
        return;
      }
      await sleep(remaining);
    }
  }
  async screen() {
    const rawLines = [];
    for (let row = 0; row < this.currentRows; row += 1) {
      rawLines.push(this.terminal.renderLine(row));
    }
    return new TerminalScreen({
      lines: rawLines,
      rawLines,
      cursor: {
        row: this.terminal.displayBuffer.cursorY,
        col: this.terminal.displayBuffer.cursorX
      },
      size: {
        rows: this.currentRows,
        cols: this.currentCols
      }
    });
  }
  async history(opts) {
    const normalized = normalizeHistoryBuffer(stripAnsi(this.rawBuffer));
    const lines = splitHistoryLines(normalized);
    if (opts?.last === void 0) {
      return lines;
    }
    if (!Number.isInteger(opts.last) || opts.last < 0) {
      throw new Error("History last must be a non-negative integer.");
    }
    const start = Math.max(0, lines.length - opts.last);
    return lines.slice(start);
  }
  async resize(cols, rows) {
    assertTerminalGeometry(cols, rows);
    this.currentCols = cols;
    this.currentRows = rows;
    if (this.exitCode === null) {
      this.pty.resize(cols, rows);
    }
    this.terminal.resize(cols, rows);
  }
  async waitForExit(opts) {
    if (opts?.timeout !== void 0) {
      assertTimeout(opts.timeout);
    }
    if (this.exitCode !== null) {
      return this.exitCode;
    }
    if (opts?.timeout !== void 0) {
      const result = await waitForExit(this.exitPromise, opts.timeout);
      if (result === null) {
        throw new Error(`Timed out waiting for process to exit after ${opts.timeout}ms`);
      }
      return result;
    }
    return this.exitPromise;
  }
  async close() {
    if (this.exitCode !== null) {
      return this.exitCode;
    }
    this.closePromise ??= this.closeProcess().catch((error) => {
      this.closePromise = null;
      throw error;
    });
    return this.closePromise;
  }
  async closeProcess() {
    const gracefulExitCode = await waitForExit(this.exitPromise, CLOSE_AFTER_SIGNAL_GRACE_MS);
    if (gracefulExitCode !== null) {
      return gracefulExitCode;
    }
    if (this.exitCode === null) {
      this.pty.kill("SIGTERM");
      const afterSigterm = await waitForExit(this.exitPromise, CLOSE_AFTER_SIGTERM_MS);
      if (afterSigterm !== null) {
        return afterSigterm;
      }
    }
    if (this.exitCode === null) {
      this.pty.kill("SIGKILL");
      const afterSigkill = await waitForExit(this.exitPromise, CLOSE_AFTER_SIGKILL_MS);
      if (afterSigkill !== null) {
        return afterSigkill;
      }
    }
    throw new Error("Timed out waiting for process to exit after SIGKILL.");
  }
  on(event, cb) {
    this.emitter.on(event, cb);
  }
};
function assertTerminalGeometry(cols, rows) {
  if (!Number.isInteger(cols) || cols <= 0 || !Number.isInteger(rows) || rows <= 0) {
    throw new Error("Terminal columns and rows must be positive integers.");
  }
}
function assertTimeout(timeout) {
  if (!Number.isFinite(timeout) || timeout < 0) {
    throw new Error("Timeout must be a finite non-negative number.");
  }
}
function assertQuietPeriod(duration) {
  if (!Number.isFinite(duration) || duration < 0) {
    throw new Error("Quiet period must be a finite non-negative number.");
  }
}
function createPtyProcess({
  command,
  args,
  cwd,
  env,
  cols,
  rows
}) {
  ensureSpawnHelperExecutable();
  return nodePty.spawn(command, args, {
    cwd,
    env,
    cols,
    rows,
    encoding: "utf8"
  });
}
var spawnHelperChecked = false;
function ensureSpawnHelperExecutable() {
  if (spawnHelperChecked) return;
  spawnHelperChecked = true;
  const require2 = createRequire(import.meta.url);
  const nodePtyDir = dirname(require2.resolve("node-pty"));
  const helper = join(nodePtyDir, "..", "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
  try {
    accessSync(helper, constants.X_OK);
  } catch (error) {
    if (isMissingFileError(error)) {
      return;
    }
    try {
      chmodSync(helper, 493);
    } catch (chmodError) {
      if (isMissingFileError(chmodError)) {
        return;
      }
      throw chmodError;
    }
  }
}
function isMissingFileError(error) {
  return hasOwnErrorCode(error, "ENOENT");
}
function matchPattern(buffer, pattern) {
  const clean = normalizeHistoryBuffer(stripAnsi(buffer));
  for (const line of clean.split("\n")) {
    if (typeof pattern === "string") {
      if (line.includes(pattern)) return line;
    } else {
      const flags = removeCharacter(pattern.flags, "g");
      if (new RegExp(pattern.source, flags).test(line)) return line;
    }
  }
  return null;
}
function removeCharacter(input, charToRemove) {
  let output = "";
  for (const character of input) {
    if (character !== charToRemove) {
      output += character;
    }
  }
  return output;
}
function splitHistoryLines(input) {
  const lines = input.split("\n");
  if (lines.length > 0 && lines[lines.length - 1] === "") {
    lines.pop();
  }
  return lines;
}
function normalizeHistoryBuffer(input) {
  let output = "";
  let line = "";
  let cursor = 0;
  for (const character of input) {
    if (character === "\r") {
      cursor = 0;
      continue;
    }
    if (character === "\b") {
      cursor = Math.max(0, cursor - 1);
      continue;
    }
    if (character === "\n") {
      output += `${line}
`;
      line = "";
      cursor = 0;
      continue;
    }
    line = `${line.slice(0, cursor)}${character}${line.slice(cursor + 1)}`;
    cursor += 1;
  }
  return output + line;
}
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}
async function waitForExit(exitPromise, timeout) {
  return new Promise((resolve) => {
    let settled = false;
    const timer = setTimeout(() => {
      if (settled) {
        return;
      }
      settled = true;
      resolve(null);
    }, timeout);
    void exitPromise.then((code) => {
      if (settled) {
        return;
      }
      settled = true;
      clearTimeout(timer);
      resolve(code);
    });
  });
}

// src/terminal-pilot.ts
var DEFAULT_COLS2 = 120;
var DEFAULT_ROWS2 = 40;
var TerminalPilot = class _TerminalPilot {
  sessionMap = /* @__PURE__ */ new Map();
  static async launch() {
    return new _TerminalPilot();
  }
  async newSession(opts) {
    const session = new TerminalSession({
      id: randomUUID(),
      command: opts.command,
      args: opts.args,
      cwd: opts.cwd,
      env: opts.env,
      cols: opts.cols ?? DEFAULT_COLS2,
      rows: opts.rows ?? DEFAULT_ROWS2,
      observe: opts.observe ?? false
    });
    this.sessionMap.set(session.id, session);
    return session;
  }
  getSession(id) {
    const session = this.sessionMap.get(id);
    if (session === void 0) {
      throw new Error(`Session not found: ${id}`);
    }
    return session;
  }
  deleteSession(id) {
    this.sessionMap.delete(id);
  }
  sessions() {
    return [...this.sessionMap.values()].filter((s) => s.exitCode === null);
  }
  async close() {
    const sessions = [...this.sessionMap.values()];
    await Promise.all(
      sessions.map(async (session) => {
        await session.close();
        this.sessionMap.delete(session.id);
      })
    );
  }
};

// src/commands/runtime.ts
var SESSION_ENV_VAR = "TERMINAL_PILOT_SESSION";
var sharedRuntime;
function getTerminalPilotRuntime(runtime) {
  if (runtime !== void 0) {
    return runtime;
  }
  sharedRuntime ??= createTerminalPilotRuntime();
  return sharedRuntime;
}
function createTerminalPilotRuntime(options = {}) {
  const launchPilot = options.launchPilot ?? TerminalPilot.launch;
  const nameToId = /* @__PURE__ */ new Map();
  const idToName = /* @__PURE__ */ new Map();
  const pendingNames = /* @__PURE__ */ new Set();
  let pilotPromise;
  function getRequestedName(name, env) {
    const requestedName = name ?? env?.get(SESSION_ENV_VAR);
    if (requestedName !== void 0 && requestedName.trim().length === 0) {
      throw new UserError("Session name must not be empty.");
    }
    return requestedName;
  }
  async function getPilot() {
    pilotPromise ??= launchPilot();
    return pilotPromise;
  }
  function nextSessionName() {
    let index = 1;
    while (nameToId.has(`s${index}`) || pendingNames.has(`s${index}`)) {
      index += 1;
    }
    return `s${index}`;
  }
  function rememberSession(name, session) {
    nameToId.set(name, session.id);
    idToName.set(session.id, name);
    return { name, session };
  }
  function forgetSession(name, sessionId) {
    if (nameToId.get(name) === sessionId) {
      nameToId.delete(name);
    }
    if (idToName.get(sessionId) === name) {
      idToName.delete(sessionId);
    }
  }
  function formatAvailableSessions(names) {
    if (names.length === 0) {
      return "No active sessions are available.";
    }
    return `Available sessions: ${names.join(", ")}.`;
  }
  async function lookupNamedSession(name) {
    const sessionId = nameToId.get(name);
    if (sessionId === void 0) {
      const active = await listSessions();
      throw new UserError(
        `Session "${name}" was not found. ${formatAvailableSessions(active.map((entry) => entry.name))}`
      );
    }
    const pilot = await getPilot();
    try {
      return { name, session: pilot.getSession(sessionId) };
    } catch {
      forgetSession(name, sessionId);
      const active = await listSessions();
      throw new UserError(
        `Session "${name}" was not found. ${formatAvailableSessions(active.map((entry) => entry.name))}`
      );
    }
  }
  async function listSessions() {
    const pilot = await getPilot();
    return pilot.sessions().flatMap((session) => {
      const name = idToName.get(session.id);
      if (name === void 0) {
        return [];
      }
      return [{ name, session }];
    });
  }
  async function discardExitedSessionName(name) {
    const sessionId = nameToId.get(name);
    if (sessionId === void 0) {
      return;
    }
    const pilot = await getPilot();
    try {
      const session = pilot.getSession(sessionId);
      if (session.exitCode === null) {
        return;
      }
      pilot.deleteSession(sessionId);
    } catch {
    }
    forgetSession(name, sessionId);
  }
  return {
    async createSession(params2, env) {
      if (params2.command.trim().length === 0) {
        throw new UserError("Command must not be empty.");
      }
      const requestedName = getRequestedName(params2.session, env) ?? nextSessionName();
      await discardExitedSessionName(requestedName);
      if (nameToId.has(requestedName) || pendingNames.has(requestedName)) {
        throw new UserError(`Session "${requestedName}" already exists.`);
      }
      pendingNames.add(requestedName);
      try {
        const pilot = await getPilot();
        const session = await pilot.newSession({
          command: params2.command,
          args: params2.args,
          cwd: params2.cwd,
          cols: params2.cols,
          rows: params2.rows,
          observe: params2.observe
        });
        return rememberSession(requestedName, session);
      } finally {
        pendingNames.delete(requestedName);
      }
    },
    async resolveSession(name, env) {
      const requestedName = getRequestedName(name, env);
      if (requestedName !== void 0) {
        return lookupNamedSession(requestedName);
      }
      const active = await listSessions();
      if (active.length === 1) {
        return active[0];
      }
      if (active.length === 0) {
        throw new UserError("No active sessions. Create one with create-session.");
      }
      throw new UserError(
        `Multiple active sessions require an explicit session name. Pass --session or set ${SESSION_ENV_VAR}. ${formatAvailableSessions(active.map((entry) => entry.name))}`
      );
    },
    async closeSession(name, env) {
      const namedSession = await this.resolveSession(name, env);
      const exitCode = await namedSession.session.close();
      const pilot = await getPilot();
      pilot.deleteSession(namedSession.session.id);
      forgetSession(namedSession.name, namedSession.session.id);
      return {
        exitCode,
        name: namedSession.name
      };
    },
    listSessions,
    async close() {
      if (pilotPromise === void 0) {
        return;
      }
      const pilot = await pilotPromise;
      await pilot.close();
      pilotPromise = void 0;
      nameToId.clear();
      idToName.clear();
      pendingNames.clear();
    }
  };
}

// src/commands/resize.ts
var params = S.Object({
  cols: S.Number({ description: "Terminal width in columns", jsonType: "integer", minimum: 1 }),
  rows: S.Number({ description: "Terminal height in rows", jsonType: "integer", minimum: 1 }),
  session: S.Optional(
    S.String({ short: "s", description: "Session name", minLength: 1, pattern: "\\S" })
  )
});
var resize = defineCommand({
  name: "resize",
  description: "Resize an active terminal session",
  scope: ["cli", "mcp", "sdk"],
  params,
  handler: async ({ params: params2, env, terminalPilotRuntime }) => {
    const namedSession = await getTerminalPilotRuntime(terminalPilotRuntime).resolveSession(
      params2.session,
      env
    );
    await namedSession.session.resize(params2.cols, params2.rows);
    return void 0;
  }
});
export {
  resize
};
//# sourceMappingURL=resize.js.map
