import {
  CLAIM_FORMAT_VERSION,
  PENDING_FORMAT_VERSION,
  PHASE_FORMAT_VERSION,
  RecoveryAgentCandidateTraceStore,
  TERMINAL_FORMAT_VERSION,
  applyExactAgentProfileDiff,
  assertExactObjectKeys,
  assertNoGitIndirection,
  assertPreparedCandidateIntegrity,
  assertRecoveryMatchesStaged,
  assertTerminalAllowedInPhase,
  assertTerminalMatchesClaim,
  assertTerminalMatchesStaged,
  beginPreparedCandidateDisposal,
  candidateClaimFileInternals,
  candidateCleanupDeadline,
  candidateCleanupTimeout,
  canonicalCandidateBytes,
  canonicalCandidateDigest,
  captureMaterializedWorkspace,
  consumePreparedCandidateExecution,
  deepFreezeCandidate,
  embeddedCandidateArtifact,
  freezeGenericAgentCandidateProfile,
  immutableCandidateValue,
  parseExactAgentProfile,
  parseExactAgentProfileDiff,
  parseExactCandidateProfile,
  persistCandidateModelSettlementEvidence,
  persistCandidateOutputArtifact,
  readCandidateGitTreeFiles,
  recoveredTerminalRecord,
  rejectedFinish,
  rejectedStage,
  requireStagedTerminal,
  runCandidateGit,
  sealAgentCandidateBundle,
  sealAgentCandidateExecutorFinalCapture,
  sealAgentCandidateModelSettlement,
  sealTerminalDigest,
  sha256Bytes,
  terminalRecord,
  usdToNanos,
  verifyBytes,
  verifyMaterializedWorkspace,
  withinCandidateCleanupDeadline
} from "./chunk-37V4KQDC.js";

// src/candidate-execution/builder.ts
import { verifyCodeSurface } from "@tangle-network/agent-eval/campaign";
function buildAgentCandidateBundle(input) {
  if (Object.hasOwn(input.lineage, "profileDiffIds")) {
    throw new Error("profileDiffIds is derived from the profile source and cannot be supplied");
  }
  const compiledProfile = compileCandidateProfile(input.profile);
  const profileDiffIds = compiledProfile.profileDiffIds;
  const bundle = {
    schemaVersion: 1,
    kind: "agent-candidate-bundle",
    digestAlgorithm: "rfc8785-sha256",
    profile: compiledProfile.profile,
    code: compileCandidateCode(input.code),
    execution: input.execution,
    ...input.knowledge ? { knowledge: input.knowledge } : {},
    memory: input.memory,
    lineage: {
      ...input.lineage,
      ...profileDiffIds.length > 0 ? { profileDiffIds } : {}
    }
  };
  return sealAgentCandidateBundle(bundle);
}
function compileCandidateProfile(source) {
  if (source.kind === "candidate-profile") {
    return {
      profile: parseExactCandidateProfile(source.profile),
      profileDiffIds: []
    };
  }
  if (source.kind === "profile") {
    return { profile: freezeGenericAgentCandidateProfile(source.profile), profileDiffIds: [] };
  }
  if (source.kind !== "profile-diffs") {
    throw new Error(
      `unsupported candidate profile source: ${String(source.kind)}`
    );
  }
  if (source.diffs.length === 0) {
    throw new Error("profile-diffs source requires at least one AgentProfileDiff");
  }
  let profile = parseExactAgentProfile(source.base, "base profile");
  const profileDiffIds = [];
  for (const [index, inputDiff] of source.diffs.entries()) {
    const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`);
    profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`);
    profileDiffIds.push(canonicalCandidateDigest(diff));
  }
  return { profile: freezeGenericAgentCandidateProfile(profile), profileDiffIds };
}
function compileCandidateCode(source) {
  if (source.kind === "disabled" || source.kind === "no-op") return source;
  if (source.kind !== "code-surface") {
    throw new Error(
      `unsupported candidate code source: ${String(source.kind)}`
    );
  }
  const verified = verifyCodeSurface(source.surface, source.worktreeDir);
  const patch = embeddedCandidateArtifact(verified.patchBytes);
  if (patch.sha256 !== source.surface.patch.sha256 || patch.byteLength !== source.surface.patch.byteLength) {
    throw new Error("verified CodeSurface patch bytes do not match its content identity");
  }
  return {
    kind: "git-patch",
    repository: source.repository,
    baseCommit: source.surface.baseCommit,
    baseTree: source.surface.baseTree,
    candidateTree: source.surface.candidateTree,
    patch: { format: "git-diff-binary", artifact: patch }
  };
}

// src/candidate-execution/claim-file-store.ts
import { randomUUID } from "crypto";
import { linkSync } from "fs";
import { mkdir, open, unlink } from "fs/promises";
import { join } from "path";
var {
  assertExpiredLease,
  assertLease,
  assertSameSlot,
  assertUnexpiredLease,
  attemptRecord,
  claimSlot,
  leaseDigest,
  newLease,
  readClaim,
  readClaimIfPresent,
  readTerminal,
  readTerminalIfPresent,
  readTransitionIfPresent,
  rejectedExistingClaim,
  rejectedRetry,
  retryRejection,
  sealAttemptRef,
  sealClaim,
  sealLease
} = candidateClaimFileInternals;
var FileAgentCandidateExecutionClaimStore = class {
  directory;
  now;
  constructor(options) {
    if (options.directory.length === 0) {
      throw new Error("candidate execution claim directory must not be empty");
    }
    this.directory = options.directory;
    this.now = options.now ?? Date.now;
  }
  async tryClaim(requested) {
    const claim = sealClaim(requested);
    await mkdir(this.directory, { recursive: true });
    const claimPath = this.claimPath(claim);
    const existing = await readClaimIfPresent(claimPath);
    if (existing) {
      assertSameSlot(existing.claim, claim, claimPath);
      return rejectedExistingClaim(existing.claim, claim);
    }
    assertUnexpiredLease(claim.leaseExpiresAtMs, this.now());
    const retryFailure = await this.retryFailure(claim);
    if (retryFailure) return rejectedRetry(claim, retryFailure);
    const lease = newLease(claim);
    const acquired = await writeRecordIfAbsent(this.directory, claimPath, {
      version: CLAIM_FORMAT_VERSION,
      ...claim,
      phase: "claimed",
      leaseDigest: leaseDigest(lease)
    });
    if (acquired) return Object.freeze({ acquired: true, claim, lease });
    const winner = await readClaim(claimPath);
    assertSameSlot(winner.claim, claim, claimPath);
    return rejectedExistingClaim(winner.claim, claim);
  }
  async getAttempt(requestedAttempt) {
    return await this.storedAttempt(sealAttemptRef(requestedAttempt));
  }
  async markCandidateMayRun(requestedLease) {
    const lease = sealLease(requestedLease);
    const claimPath = this.claimPath(lease);
    const stored = await readClaim(claimPath);
    assertSameSlot(stored.claim, lease, claimPath);
    assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
    const state = await this.transitionState(stored.claim);
    if (state.phase === "candidate-may-run") {
      return Object.freeze({ marked: false, phase: "candidate-may-run" });
    }
    if (state.staged) {
      throw new Error("candidate execution terminal was staged before candidate-may-run phase");
    }
    assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now());
    const marked = await writeRecordIfAbsent(
      this.directory,
      this.transitionPath(stored.claim, 1),
      {
        version: PHASE_FORMAT_VERSION,
        kind: "candidate-execution-phase",
        executionId: stored.claim.executionId,
        attempt: stored.claim.attempt,
        executionPlanDigest: stored.claim.executionPlanDigest,
        phase: "candidate-may-run"
      },
      this.ownerPublication(stored.claim)
    );
    if (marked) return Object.freeze({ marked: true, phase: "candidate-may-run" });
    const winner = await this.transitionState(stored.claim);
    if (winner.phase === "candidate-may-run") {
      return Object.freeze({ marked: false, phase: "candidate-may-run" });
    }
    throw new Error("candidate execution terminal was staged before candidate-may-run phase");
  }
  async stageTerminal(requestedLease, result) {
    const lease = sealLease(requestedLease);
    const claimPath = this.claimPath(lease);
    const stored = await readClaim(claimPath);
    assertSameSlot(stored.claim, lease, claimPath);
    assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
    const terminal = terminalRecord(stored.claim, result);
    const state = await this.transitionState(stored.claim);
    if (state.staged) return rejectedStage(state.staged, terminal);
    assertTerminalAllowedInPhase(state.phase, terminal);
    assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now());
    const transition = state.phase === "claimed" ? 1 : 2;
    const staged = await writeRecordIfAbsent(
      this.directory,
      this.transitionPath(stored.claim, transition),
      {
        version: PENDING_FORMAT_VERSION,
        kind: "candidate-execution-pending-terminal",
        terminal
      },
      this.ownerPublication(stored.claim)
    );
    if (staged) return Object.freeze({ staged: true, terminal });
    const winner = await this.transitionState(stored.claim);
    if (!winner.staged) {
      throw new Error("candidate execution phase transition won while staging terminal");
    }
    return rejectedStage(winner.staged, terminal);
  }
  async finish(requestedLease, requestedTerminalDigest) {
    const lease = sealLease(requestedLease);
    const terminalDigest = sealTerminalDigest(requestedTerminalDigest);
    const claimPath = this.claimPath(lease);
    const stored = await readClaim(claimPath);
    assertSameSlot(stored.claim, lease, claimPath);
    assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
    const state = await this.transitionState(stored.claim);
    const staged = requireStagedTerminal(state.staged, terminalDigest);
    const terminalPath = this.terminalPath(lease);
    const existing = await readTerminalIfPresent(terminalPath);
    if (existing) {
      assertTerminalMatchesClaim(existing, stored.claim, terminalPath);
      assertTerminalMatchesStaged(existing, staged, terminalPath);
      return rejectedFinish(existing, terminalDigest);
    }
    assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now());
    const finished = await writeRecordIfAbsent(
      this.directory,
      terminalPath,
      {
        version: TERMINAL_FORMAT_VERSION,
        terminal: staged
      },
      this.ownerPublication(stored.claim)
    );
    if (finished) return Object.freeze({ finished: true, terminal: staged });
    const winner = await readTerminal(terminalPath);
    assertSameSlot(winner, lease, terminalPath);
    assertTerminalMatchesClaim(winner, stored.claim, terminalPath);
    assertTerminalMatchesStaged(winner, staged, terminalPath);
    return rejectedFinish(winner, terminalDigest);
  }
  async recoverExpired(requestedAttempt, evidence) {
    const attempt = sealAttemptRef(requestedAttempt);
    const record2 = await this.storedAttempt(attempt);
    if (!record2) throw new Error("candidate execution recovery does not name an acquired attempt");
    const recovered = recoveredTerminalRecord(record2.claim, record2.phase, evidence);
    if (record2.staged) assertRecoveryMatchesStaged(record2.staged, recovered);
    const requestedDigest = record2.staged?.terminalDigest ?? recovered.terminalDigest;
    if (record2.terminal) return rejectedFinish(record2.terminal, requestedDigest);
    assertExpiredLease(record2.claim.leaseExpiresAtMs, this.now());
    let staged = record2.staged;
    if (!staged) {
      const transition = record2.phase === "claimed" ? 1 : 2;
      const didStage = await writeRecordIfAbsent(
        this.directory,
        this.transitionPath(record2.claim, transition),
        {
          version: PENDING_FORMAT_VERSION,
          kind: "candidate-execution-pending-terminal",
          terminal: recovered
        }
      );
      if (didStage) {
        staged = recovered;
      } else {
        const winner2 = await this.transitionState(record2.claim);
        if (!winner2.staged) {
          throw new Error(
            "candidate execution recovery lost terminal staging to a phase transition"
          );
        }
        assertRecoveryMatchesStaged(winner2.staged, recovered);
        staged = winner2.staged;
      }
    }
    const terminalPath = this.terminalPath(attempt);
    const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {
      version: TERMINAL_FORMAT_VERSION,
      terminal: staged
    });
    if (didFinish) return Object.freeze({ finished: true, terminal: staged });
    const winner = await readTerminal(terminalPath);
    assertSameSlot(winner, attempt, terminalPath);
    assertTerminalMatchesClaim(winner, record2.claim, terminalPath);
    assertTerminalMatchesStaged(winner, staged, terminalPath);
    return rejectedFinish(winner, staged.terminalDigest);
  }
  async storedAttempt(claim) {
    const claimPath = this.claimPath(claim);
    const stored = await readClaimIfPresent(claimPath);
    if (!stored) return void 0;
    assertSameSlot(stored.claim, claim, claimPath);
    const state = await this.transitionState(stored.claim);
    const terminalPath = this.terminalPath(claim);
    const terminal = await readTerminalIfPresent(terminalPath);
    if (terminal) {
      assertTerminalMatchesClaim(terminal, stored.claim, terminalPath);
      if (!state.staged) {
        throw new Error(
          `candidate execution terminal record at ${terminalPath} has no staged outbox`
        );
      }
      assertTerminalMatchesStaged(terminal, state.staged, terminalPath);
    }
    return attemptRecord(stored.claim, state.phase, state.staged, terminal);
  }
  async transitionState(claim) {
    const firstPath = this.transitionPath(claim, 1);
    const first = await readTransitionIfPresent(firstPath, claim);
    if (!first) return { phase: "claimed" };
    if (first.kind === "pending") return { phase: "claimed", staged: first.terminal };
    const secondPath = this.transitionPath(claim, 2);
    const second = await readTransitionIfPresent(secondPath, claim);
    if (!second) return { phase: "candidate-may-run" };
    if (second.kind !== "pending") {
      throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`);
    }
    return { phase: "candidate-may-run", staged: second.terminal };
  }
  async retryFailure(claim) {
    if (claim.attempt === 1) return void 0;
    return retryRejection(
      claim,
      await this.storedAttempt({
        executionId: claim.executionId,
        attempt: claim.attempt - 1
      })
    );
  }
  ownerPublication(claim) {
    return {
      authorizePublish: () => {
        assertUnexpiredLease(claim.leaseExpiresAtMs, this.now());
        return true;
      }
    };
  }
  claimPath(claim) {
    return join(this.directory, `${claimSlot(claim)}.claim.json`);
  }
  terminalPath(claim) {
    return join(this.directory, `${claimSlot(claim)}.terminal.json`);
  }
  transitionPath(claim, ordinal) {
    return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`);
  }
};
async function writeRecordIfAbsent(directory, destination, record2, options = {}) {
  const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`);
  const handle = await open(temporaryPath, "wx", 384);
  try {
    await handle.writeFile(
      Buffer.concat([Buffer.from(canonicalCandidateBytes(record2)), Buffer.from("\n")])
    );
    await handle.sync();
  } finally {
    await handle.close();
  }
  let written = false;
  try {
    if (options.authorizePublish && options.authorizePublish() !== true) {
      throw new Error("candidate execution record publication was not authorized");
    }
    linkSync(temporaryPath, destination);
    written = true;
    await syncDirectory(directory);
  } catch (error) {
    if (!isNodeError(error, "EEXIST")) throw error;
  } finally {
    await unlink(temporaryPath).catch((error) => {
      if (!isNodeError(error, "ENOENT")) throw error;
    });
  }
  return written;
}
async function syncDirectory(directory) {
  const handle = await open(directory, "r");
  try {
    await handle.sync();
  } finally {
    await handle.close();
  }
}
function isNodeError(error, code) {
  return error !== null && typeof error === "object" && "code" in error && error.code === code;
}

// src/candidate-execution/dispose.ts
async function disposePreparedAgentCandidateExecution(prepared, options = {}) {
  const initialState = assertPreparedCandidateIntegrity(prepared);
  const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs;
  if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {
    throw new Error("disposal cleanup timeout exceeds the frozen preparation bound");
  }
  const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs);
  const state = beginPreparedCandidateDisposal(prepared);
  const cleanup = [];
  if (state.memory.mode === "isolated") {
    const reservation = state.memoryReservation;
    if (!reservation) throw new Error("isolated memory reservation is missing");
    cleanup.push(
      withinCandidateCleanupDeadline(
        async () => {
          const closed = await state.ports.memory.close({
            executionId: state.executionId,
            preparationId: reservation.preparationId,
            accessDigest: reservation.accessDigest,
            effectiveNamespace: reservation.effectiveNamespace,
            reason: "abandoned"
          });
          if (closed.closed !== true || Object.keys(closed).some((key) => key !== "closed")) {
            throw new Error("abandoned isolated memory access did not acknowledge closure");
          }
        },
        cleanupDeadlineAtMs,
        "isolated memory disposal"
      )
    );
  }
  cleanup.push(
    withinCandidateCleanupDeadline(
      async () => {
        const settlement = sealAgentCandidateModelSettlement(
          await state.ports.models.settleGrant({
            executionId: state.executionId,
            preparationId: state.preparationId,
            grantDigest: state.modelReservation.digest,
            resolved: state.resolvedModel,
            reason: "abandoned"
          }),
          {
            preparationId: state.preparationId,
            grantDigest: state.modelReservation.digest,
            model: state.resolvedModel.model
          }
        );
        if (settlement.usage.modelCalls !== 0) {
          throw new Error("unexecuted model reservation unexpectedly contains calls");
        }
      },
      cleanupDeadlineAtMs,
      "model reservation disposal"
    )
  );
  const results = await Promise.allSettled(cleanup);
  const failures = results.filter((result) => result.status === "rejected").map((result) => result.reason);
  if (failures.length > 0) {
    consumePreparedCandidateExecution(prepared, "disposal-failed");
    throw new AggregateError(failures, "candidate preparation disposal failed");
  }
  consumePreparedCandidateExecution(prepared, "disposed");
  return Object.freeze({ disposed: true });
}

// src/candidate-execution/protected-model-port.ts
var MAX_RECENT_SETTLEMENTS = 4096;
var RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1e3;
function createProtectedAgentCandidateModelPort(options) {
  const gatewayDomain = assertGatewayDomain(options.gatewayDomain);
  const activationEnvNames = exactEnvironmentNames(options.activationEnvNames);
  const reservations = /* @__PURE__ */ new Map();
  const recentSettlements = /* @__PURE__ */ new Map();
  return {
    resolve: async (input) => {
      const request = immutableCandidateValue(input);
      const resolved = validateResolvedModel(await options.resolveModel(request), request);
      return immutableCandidateValue(resolved);
    },
    reserveGrant: async (input) => {
      pruneExpiredState(reservations, recentSettlements, Date.now());
      const request = immutableCandidateValue(input);
      validateReserveInput(request);
      const requestDigest = canonicalCandidateDigest(request);
      const key = reservationKey(request.executionId, request.preparationId);
      if (recentSettlements.has(key)) {
        throw new Error("protected model reservation is already settled");
      }
      const previous = reservations.get(key);
      if (previous && previous.requestDigest !== requestDigest) {
        throw new Error("protected model reservation retry changed immutable input");
      }
      const reservation = validateReservation(
        await options.client.reserve(request),
        request,
        gatewayDomain
      );
      const responseDigest = canonicalCandidateDigest(reservation);
      if (recentSettlements.has(key)) {
        throw new Error("protected model reservation completed after the grant was settled");
      }
      const recorded = previous ?? reservations.get(key);
      if (recorded && recorded.requestDigest !== requestDigest) {
        throw new Error("protected model reservation retry changed immutable input");
      }
      if (recorded && recorded.responseDigest !== responseDigest) {
        throw new Error("protected model reservation retry returned different evidence");
      }
      if (!recorded) {
        reservations.set(key, {
          requestDigest,
          responseDigest,
          executionId: request.executionId,
          preparationId: request.preparationId,
          grantDigest: reservation.digest,
          expiresAtMs: request.expiresAtMs,
          resolved: immutableCandidateValue(request.resolved),
          limits: immutableCandidateValue(request.limits),
          maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, "reserved maxCostUsd"),
          activation: "reserved"
        });
      }
      return reservation;
    },
    activateGrant: async (input) => {
      pruneExpiredState(reservations, recentSettlements, Date.now());
      const request = immutableCandidateValue(input);
      const key = reservationKey(request.executionId, request.preparationId);
      if (recentSettlements.has(key)) throw new Error("protected model grant is already settled");
      const state = reservations.get(key);
      if (!state) throw new Error("protected model grant was not reserved by this port");
      assertGrantIdentity(state, request);
      if (state.settlementDigest) throw new Error("protected model grant is already settled");
      if (state.activation !== "reserved") {
        throw new Error("protected model grant activation is single-use");
      }
      if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {
        throw new Error("protected model activation deadline must be a positive safe integer");
      }
      if (request.deadlineAtMs <= Date.now()) {
        throw new Error("protected model activation deadline must be in the future");
      }
      if (request.deadlineAtMs > state.expiresAtMs) {
        throw new Error("protected model activation deadline exceeds the reserved expiry");
      }
      state.activation = "activating";
      try {
        const activation = validateActivation(
          await options.client.activate(request),
          state.limits.maxModelCalls === 0 ? [] : activationEnvNames
        );
        if (recentSettlements.has(key) || reservations.get(key) !== state) {
          throw new Error("protected model grant settled while activation was in flight");
        }
        state.activation = "activated";
        return activation;
      } catch (error) {
        state.activation = "reserved";
        throw error;
      }
    },
    settleGrant: async (input) => {
      const now = Date.now();
      pruneExpiredState(reservations, recentSettlements, now);
      const request = immutableCandidateValue(input);
      const key = reservationKey(request.executionId, request.preparationId);
      const state = reservations.get(key);
      if (state) assertGrantIdentity(state, request);
      const remembered = state ?? recentSettlements.get(key);
      if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {
        throw new Error("protected model settlement retry changed the termination reason");
      }
      const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {
        preparationId: request.preparationId,
        grantDigest: request.grantDigest,
        model: request.resolved.model
      });
      if (state) assertWithinReservedLimits(sealed.fixedUsage, state);
      const settlementDigest = canonicalCandidateDigest(sealed.value);
      if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {
        throw new Error("protected model settlement retry returned a different final ledger");
      }
      if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {
        throw new Error("protected model settlement retry changed the termination reason");
      }
      const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS;
      if (state) {
        state.settlementDigest = settlementDigest;
        state.settlementReason = request.reason;
      }
      reservations.delete(key);
      rememberSettlement(recentSettlements, key, {
        settlementDigest,
        settlementReason: request.reason,
        expiresAtMs
      });
      return sealed.value;
    }
  };
}
function validateReserveInput(input) {
  if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {
    throw new Error("protected model reservation expiry must be a positive safe integer");
  }
  if (input.expiresAtMs <= Date.now()) {
    throw new Error("protected model reservation expiry must be in the future");
  }
  for (const [name, value] of [
    ["maxModelCalls", input.limits.maxModelCalls],
    ["maxInputTokens", input.limits.maxInputTokens],
    ["maxOutputTokens", input.limits.maxOutputTokens]
  ]) {
    if (!Number.isSafeInteger(value) || value < 0) {
      throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`);
    }
  }
  usdToNanos(input.limits.maxCostUsd, "reserved maxCostUsd");
}
function validateReservation(value, expected, gatewayDomain) {
  const source = exactRecord(
    value,
    ["preparationId", "digest", "expiresAtMs", "enforcedLimits", "network"],
    "protected model reservation response"
  );
  if (source.preparationId !== expected.preparationId) {
    throw new Error("protected model reservation response changed preparation identity");
  }
  if (!isSha256Digest(source.digest)) {
    throw new Error("protected model reservation response has an invalid digest");
  }
  if (source.expiresAtMs !== expected.expiresAtMs) {
    throw new Error("protected model reservation response changed expiry");
  }
  exactRecord(
    source.enforcedLimits,
    ["maxModelCalls", "maxInputTokens", "maxOutputTokens", "maxCostUsd"],
    "protected model reservation enforced limits"
  );
  if (canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)) {
    throw new Error("protected model reservation response changed enforced limits");
  }
  const network = validateReservationNetwork(
    source.network,
    expected.limits.maxModelCalls,
    gatewayDomain
  );
  return immutableCandidateValue({
    preparationId: source.preparationId,
    digest: source.digest,
    expiresAtMs: source.expiresAtMs,
    enforcedLimits: source.enforcedLimits,
    network
  });
}
function validateReservationNetwork(value, maxModelCalls, gatewayDomain) {
  if (maxModelCalls === 0) {
    const source2 = exactRecord(value, ["mode"], "protected model reservation network");
    if (source2.mode !== "disabled") {
      throw new Error("zero-call protected model reservation must disable gateway access");
    }
    return { mode: "disabled" };
  }
  const source = exactRecord(value, ["mode", "domains"], "protected model reservation network");
  if (source.mode !== "gateway-only") {
    throw new Error("protected model reservation must allow only its model gateway");
  }
  if (!Array.isArray(source.domains) || source.domains.length !== 1 || source.domains[0] !== gatewayDomain) {
    throw new Error("protected model reservation returned an unexpected gateway domain");
  }
  return { mode: "gateway-only", domains: [gatewayDomain] };
}
function validateActivation(value, expectedNames) {
  const source = exactRecord(value, ["env"], "protected model activation response");
  const env = record(source.env, "protected model activation environment");
  const actualNames = Object.keys(env).sort();
  if (actualNames.length !== expectedNames.length || actualNames.some((name, index) => name !== expectedNames[index])) {
    throw new Error("protected model activation returned unexpected environment names");
  }
  const detached = /* @__PURE__ */ Object.create(null);
  for (const name of expectedNames) {
    const value2 = env[name];
    if (typeof value2 !== "string" || value2.length < 8 || value2.length > 65536) {
      throw new Error(`protected model activation ${name} must be a non-empty protected value`);
    }
    detached[name] = value2;
  }
  return Object.freeze({ env: Object.freeze(detached) });
}
function validateResolvedModel(value, expected) {
  const source = exactRecord(
    value,
    ["requested", "provider", "model", "snapshot", "reasoningEffort"],
    "resolved candidate model"
  );
  if (source.requested !== expected.requested) {
    throw new Error("model resolver changed the evaluator-owned request");
  }
  if (source.reasoningEffort !== expected.reasoningEffort) {
    throw new Error("model resolver changed the evaluator-owned reasoning effort");
  }
  for (const name of ["requested", "provider", "model", "snapshot"]) {
    if (typeof source[name] !== "string" || source[name].length === 0) {
      throw new Error(`resolved candidate model ${name} must be non-empty`);
    }
  }
  return source;
}
function assertGrantIdentity(expected, actual) {
  if (actual.executionId !== expected.executionId || actual.preparationId !== expected.preparationId || actual.grantDigest !== expected.grantDigest || canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)) {
    throw new Error("protected model grant input does not match its immutable reservation");
  }
}
function assertWithinReservedLimits(usage, reservation) {
  for (const [name, actual, limit] of [
    ["model calls", usage.modelCalls, reservation.limits.maxModelCalls],
    ["input tokens", usage.inputTokens, reservation.limits.maxInputTokens],
    ["output tokens", usage.outputTokens, reservation.limits.maxOutputTokens],
    ["cost USD nanos", usage.costUsdNanos, reservation.maxCostUsdNanos]
  ]) {
    if (actual > limit) {
      throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`);
    }
  }
}
function exactEnvironmentNames(values) {
  if (values.length === 0) {
    throw new Error("protected model activation environment names must not be empty");
  }
  const names = [...values].sort();
  if (new Set(names).size !== names.length) {
    throw new Error("protected model activation environment names must be unique");
  }
  for (const name of names) {
    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || ["__proto__", "constructor", "prototype"].includes(name)) {
      throw new Error(`protected model activation environment name is invalid: ${name}`);
    }
  }
  return Object.freeze(names);
}
function assertGatewayDomain(value) {
  if (value.length > 253 || value !== value.toLowerCase() || value.endsWith(".") || value.includes(":") || value === "localhost" || value.endsWith(".localhost") || value === "metadata.google" || value === "metadata.google.internal") {
    throw new Error("protected model gateway must be an exact lowercase public DNS name");
  }
  const labels = value.split(".");
  if (labels.length < 2 || !labels.every(
    (label) => label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label)
  ) || !/[a-z]/.test(labels.at(-1) ?? "")) {
    throw new Error("protected model gateway must be an exact lowercase public DNS name");
  }
  return value;
}
function reservationKey(executionId, preparationId) {
  return canonicalCandidateDigest({ executionId, preparationId });
}
function pruneExpiredState(reservations, settlements, now) {
  for (const [key, value] of reservations) {
    if (value.expiresAtMs <= now) reservations.delete(key);
  }
  for (const [key, value] of settlements) {
    if (value.expiresAtMs <= now) settlements.delete(key);
  }
}
function rememberSettlement(settlements, key, value) {
  settlements.delete(key);
  settlements.set(key, value);
  while (settlements.size > MAX_RECENT_SETTLEMENTS) {
    const oldest = settlements.keys().next().value;
    if (oldest === void 0) return;
    settlements.delete(oldest);
  }
}
function isSha256Digest(value) {
  return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);
}
function exactRecord(value, keys, label) {
  const source = record(value, label);
  assertExactObjectKeys(source, keys, label);
  return source;
}
function record(value, label) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new Error(`${label} must be an object`);
  }
  const prototype = Object.getPrototypeOf(value);
  if (prototype !== Object.prototype && prototype !== null) {
    throw new Error(`${label} must be a plain object`);
  }
  return value;
}

// src/candidate-execution/recover.ts
async function recoverExpiredAgentCandidateExecution(options) {
  const record2 = await options.claimStore.getAttempt(options.attempt);
  if (!record2) throw new Error("candidate execution recovery attempt is missing");
  if (record2.terminal) {
    return Object.freeze({ finished: false, terminal: record2.terminal, exactReplay: true });
  }
  const cleanupTimeoutMs = candidateCleanupTimeout(
    options.cleanupTimeoutMs ?? record2.claim.cleanup.cleanupTimeoutMs
  );
  if (cleanupTimeoutMs > record2.claim.cleanup.cleanupTimeoutMs) {
    throw new Error("recovery cleanup timeout exceeds the frozen preparation bound");
  }
  const now = options.now ?? Date.now;
  if (now() < record2.claim.leaseExpiresAtMs) {
    throw new Error("candidate execution lease has not expired");
  }
  const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs);
  const controller = new AbortController();
  controller.abort(new Error("recovering an expired candidate execution"));
  const recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore);
  const processClosure = withinCandidateCleanupDeadline(
    async () => {
      const stopped = await options.executor.stopAndCapture(
        {
          executionId: record2.claim.executionId,
          executionPlanDigest: record2.claim.executionPlanDigest
        },
        {
          traceStore: recoveryTraceStore,
          reason: "failed",
          signal: controller.signal,
          deadlineAtMs: record2.claim.leaseExpiresAtMs
        }
      );
      sealAgentCandidateExecutorFinalCapture(stopped);
      return { stopped: true };
    },
    cleanupDeadlineAtMs,
    "expired candidate process termination"
  );
  const modelClosure = withinCandidateCleanupDeadline(
    async () => sealAgentCandidateModelSettlement(
      await options.ports.models.settleGrant({
        executionId: record2.claim.executionId,
        preparationId: record2.claim.cleanup.preparationId,
        grantDigest: record2.claim.cleanup.modelGrantDigest,
        resolved: record2.claim.cleanup.resolvedModel,
        reason: "failed"
      }),
      {
        preparationId: record2.claim.cleanup.preparationId,
        grantDigest: record2.claim.cleanup.modelGrantDigest,
        model: record2.claim.cleanup.resolvedModel.model
      }
    ),
    cleanupDeadlineAtMs,
    "expired candidate model settlement"
  );
  const memoryClosure = record2.claim.cleanup.memory ? withinCandidateCleanupDeadline(
    async () => {
      const memory2 = record2.claim.cleanup.memory;
      if (!memory2) throw new Error("expired candidate memory handle is missing");
      const closed = await options.ports.memory.close({
        executionId: record2.claim.executionId,
        preparationId: record2.claim.cleanup.preparationId,
        accessDigest: memory2.accessDigest,
        effectiveNamespace: memory2.effectiveNamespace,
        reason: "failed"
      });
      if (closed.closed !== true || Object.keys(closed).some((key) => key !== "closed")) {
        throw new Error("expired candidate memory did not acknowledge closure");
      }
      return { closed: true };
    },
    cleanupDeadlineAtMs,
    "expired candidate memory closure"
  ) : void 0;
  const operations = [processClosure, modelClosure, ...memoryClosure ? [memoryClosure] : []];
  const outcomes = await Promise.allSettled(operations);
  const failures = outcomes.filter((outcome) => outcome.status === "rejected").map((outcome) => outcome.reason);
  if (failures.length > 0) {
    throw new AggregateError(failures, "expired candidate cleanup could not be proven");
  }
  const model = await modelClosure;
  const modelSettlement = await withinCandidateCleanupDeadline(
    () => persistCandidateModelSettlementEvidence(
      {
        executionId: record2.claim.executionId,
        executionPlanDigest: record2.claim.executionPlanDigest,
        resolvedModel: record2.claim.cleanup.resolvedModel
      },
      model,
      options.outputArtifacts
    ),
    cleanupDeadlineAtMs,
    "expired candidate model-settlement persistence"
  );
  const memory = record2.claim.cleanup.memory;
  return await options.claimStore.recoverExpired(options.attempt, {
    failureClass: record2.phase === "claimed" && model.fixedUsage.modelCalls === 0 ? "pre-model-infrastructure" : "unknown",
    usage: model.fixedUsage,
    modelSettlement: modelSettlement.artifact,
    process: {
      stopped: true,
      executionPlanDigest: record2.claim.executionPlanDigest
    },
    model: {
      closed: true,
      preparationId: record2.claim.cleanup.preparationId,
      grantDigest: record2.claim.cleanup.modelGrantDigest
    },
    ...memory ? {
      memory: {
        closed: true,
        preparationId: record2.claim.cleanup.preparationId,
        accessDigest: memory.accessDigest,
        effectiveNamespace: memory.effectiveNamespace
      }
    } : {}
  });
}

// src/candidate-execution/workspace-archive.ts
import { randomUUID as randomUUID2 } from "crypto";
import { constants as fsConstants } from "fs";
import {
  lstat,
  mkdir as mkdir2,
  mkdtemp,
  open as open2,
  readdir,
  readFile,
  realpath,
  rename,
  rm,
  writeFile
} from "fs/promises";
import { tmpdir } from "os";
import { dirname, isAbsolute, join as join2, resolve, sep, win32 } from "path";
import { isAnyArrayBuffer, isSharedArrayBuffer } from "util/types";
import { extract, pack } from "tar-stream";
var archiveKind = "agent-candidate-workspace-archive";
var workspaceEntryPrefix = "workspace/";
var repositoryMetadataEntry = "metadata/repository.json";
var repositoryBundleEntry = "metadata/repository.bundle";
var fixedTarTime = /* @__PURE__ */ new Date(0);
var defaultLimits = Object.freeze({
  maxArchiveBytes: 512 * 1024 * 1024,
  maxEmbeddedArtifactBytes: 1024 * 1024,
  maxFiles: 5e4,
  maxFileBytes: 128 * 1024 * 1024,
  maxTotalFileBytes: 256 * 1024 * 1024,
  maxPathBytes: 4096,
  maxRepositoryBundleBytes: 128 * 1024 * 1024
});
async function captureAgentCandidateWorkspace(rootInput, options = {}) {
  const root = resolve(rootInput);
  const limits = workspaceLimits(options.limits);
  const captured = options.includeRepository ? await captureRepository(root, limits) : await captureMaterializedWorkspace(root, {
    limits: {
      maxFiles: limits.maxFiles,
      maxFileBytes: limits.maxFileBytes,
      maxTotalFileBytes: limits.maxTotalFileBytes
    }
  });
  assertWorkspaceFilesWithinLimits(captured.files, limits);
  const repository = "repository" in captured ? captured.repository : void 0;
  return captureWorkspaceFiles(captured.files, repository, limits, options.artifactPersistence);
}
async function captureAgentCandidateWorkspaceFiles(input, options = {}) {
  const limits = workspaceLimits(options.limits);
  return captureWorkspaceFiles(
    normalizeWorkspaceFiles(input, limits),
    void 0,
    limits,
    options.artifactPersistence
  );
}
async function captureWorkspaceFiles(files, repository, limits, artifactPersistence) {
  const material = workspaceManifest(files);
  const manifest = canonicalCandidateBytes(material);
  const archive = await encodeWorkspaceArchive(files, repository, limits.maxArchiveBytes);
  if (!artifactPersistence && (manifest.byteLength > limits.maxEmbeddedArtifactBytes || archive.byteLength > limits.maxEmbeddedArtifactBytes)) {
    throw new Error(
      "candidate workspace artifacts exceed maxEmbeddedArtifactBytes; artifactPersistence is required"
    );
  }
  const manifestArtifact = await captureWorkspaceArtifact("manifest", manifest, artifactPersistence);
  const archiveArtifact = await captureWorkspaceArtifact("archive", archive, artifactPersistence);
  const snapshot = deepFreezeCandidate({
    schemaVersion: 1,
    kind: "agent-candidate-workspace-snapshot",
    digest: canonicalCandidateDigest(material),
    material,
    manifest: manifestArtifact,
    archive: archiveArtifact
  });
  return Object.freeze({ snapshot, archive });
}
async function captureWorkspaceArtifact(kind, bytes, persistence) {
  if (!persistence) return embeddedCandidateArtifact(bytes);
  if (!persistence.executionId.trim()) {
    throw new Error("candidate workspace artifact persistence requires an executionId");
  }
  return persistCandidateOutputArtifact(persistence.outputArtifacts, {
    executionId: persistence.executionId,
    purpose: kind === "manifest" ? "candidate-workspace-manifest" : "candidate-workspace-archive",
    bytes,
    ...persistence.signal ? { signal: persistence.signal } : {}
  });
}
function createAgentCandidateWorkspacePort(options = {}) {
  const limits = workspaceLimits(options.limits);
  const port = {
    materialize: async ({ role, snapshot, archive, destination }) => {
      await materializeAgentCandidateWorkspace({
        role,
        snapshot,
        archive,
        destination,
        limits
      });
    }
  };
  return Object.freeze(port);
}
async function materializeAgentCandidateWorkspace(input) {
  verifyBytes(
    input.archive,
    input.snapshot.archive.sha256,
    input.snapshot.archive.byteLength,
    "candidate workspace archive"
  );
  const decoded = await parseWorkspaceArchive(input.archive, input.limits);
  if (decoded.repository && input.role !== "task") {
    throw new Error("only task workspaces may carry a Git repository");
  }
  assertArchiveMatchesSnapshot(decoded.files, input.snapshot);
  const destination = resolve(input.destination);
  await prepareEmptyDestination(destination);
  const staging = await mkdtemp(`${destination}.materializing-`);
  try {
    await writeWorkspaceFiles(staging, decoded.files);
    if (decoded.repository) {
      await materializeRepository(decoded.repository, staging);
    }
    await verifyMaterializedWorkspace(staging, input.snapshot.material, {
      ignoredProtectedRootEntries: decoded.repository ? [".git"] : []
    });
    await rename(staging, destination);
  } catch (error) {
    await rm(staging, { recursive: true, force: true });
    await rm(destination, { recursive: true, force: true });
    throw error;
  }
}
async function captureRepository(root, limits) {
  const stats = await lstat(root);
  if (!stats.isDirectory() || stats.isSymbolicLink() || await realpath(root) !== root) {
    throw new Error("candidate repository root must be a real directory");
  }
  const topLevel = (await runCandidateGit(root, ["rev-parse", "--show-toplevel"])).stdout.toString("utf8").trim();
  if (resolve(topLevel) !== root) {
    throw new Error("candidate repository capture must start at the Git worktree root");
  }
  const gitDir = resolve(
    (await runCandidateGit(root, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim()
  );
  if (await realpath(gitDir) !== gitDir || gitDir.includes(":")) {
    throw new Error("candidate repository Git object store has an unsupported path");
  }
  await assertNoGitIndirection(root, gitDir, "candidate repository");
  const headCommit = (await runCandidateGit(root, ["rev-parse", "HEAD"])).stdout.toString("utf8").trim();
  const headTree = (await runCandidateGit(root, ["rev-parse", "HEAD^{tree}"])).stdout.toString("utf8").trim();
  assertGitObjectId(headCommit, "HEAD");
  assertGitObjectId(headTree, "HEAD tree");
  if (headCommit.length !== headTree.length) {
    throw new Error("candidate repository HEAD and tree use different object formats");
  }
  const files = await readCandidateGitTreeFiles(root, headTree, {}, limits);
  assertWorkspaceFilesWithinLimits(files, limits);
  const reachableBytesText = (await runCandidateGit(root, ["rev-list", "--disk-usage", "--objects", "HEAD"])).stdout.toString("utf8").trim();
  const reachableBytes = Number(reachableBytesText);
  if (!Number.isSafeInteger(reachableBytes) || reachableBytes < 0) {
    throw new Error("candidate repository reachable size is invalid");
  }
  if (reachableBytes > limits.maxRepositoryBundleBytes) {
    throw new Error("candidate repository exceeds maxRepositoryBundleBytes");
  }
  const temporary = await mkdtemp(join2(tmpdir(), "agent-candidate-workspace-bundle-"));
  const bundlePath = join2(temporary, `${randomUUID2()}.bundle`);
  try {
    await runCandidateGit(root, ["bundle", "create", bundlePath, "HEAD"]);
    const bundle = Uint8Array.from(await readFile(bundlePath));
    if (bundle.byteLength > limits.maxRepositoryBundleBytes) {
      throw new Error("candidate repository bundle exceeds maxRepositoryBundleBytes");
    }
    return {
      files,
      repository: {
        headCommit,
        headTree,
        bundle: {
          sha256: sha256Bytes(bundle),
          byteLength: bundle.byteLength,
          bytes: bundle
        }
      }
    };
  } finally {
    await rm(temporary, { recursive: true, force: true });
  }
}
async function encodeWorkspaceArchive(files, repository, maxArchiveBytes) {
  const archive = pack();
  const output = collectStream(archive, maxArchiveBytes, "candidate workspace archive");
  try {
    await writeWorkspaceArchiveEntries(archive, files, repository);
    archive.finalize();
    return await output;
  } catch (error) {
    archive.destroy(error instanceof Error ? error : new Error(String(error)));
    await output.catch(() => void 0);
    throw error;
  }
}
async function verifyCanonicalWorkspaceArchive(files, repository, expected, maxArchiveBytes) {
  const archive = pack();
  const comparison = streamEqualsBytes(
    archive,
    expected,
    maxArchiveBytes,
    "candidate workspace archive"
  );
  try {
    await writeWorkspaceArchiveEntries(archive, files, repository);
    archive.finalize();
    if (!await comparison) throw new Error("candidate workspace tar is not canonical");
  } catch (error) {
    archive.destroy(error instanceof Error ? error : new Error(String(error)));
    await comparison.catch(() => void 0);
    throw error;
  }
}
async function writeWorkspaceArchiveEntries(archive, files, repository) {
  for (const file of files) {
    await writeTarEntry(archive, `${workspaceEntryPrefix}${file.path}`, file.mode, file.bytes);
  }
  if (!repository) return;
  const metadata = canonicalCandidateBytes({
    schemaVersion: 1,
    kind: archiveKind,
    headCommit: repository.headCommit,
    headTree: repository.headTree,
    bundle: {
      sha256: repository.bundle.sha256,
      byteLength: repository.bundle.byteLength
    }
  });
  await writeTarEntry(archive, repositoryMetadataEntry, 384, metadata);
  await writeTarEntry(archive, repositoryBundleEntry, 384, repository.bundle.bytes);
}
async function parseWorkspaceArchive(bytes, limits) {
  if (bytes.byteLength > limits.maxArchiveBytes) {
    throw new Error("candidate workspace archive exceeds maxArchiveBytes");
  }
  const parser = extract();
  const files = [];
  const observedEntryNames = /* @__PURE__ */ new Set();
  const observedPaths = /* @__PURE__ */ new Set();
  let totalBytes = 0;
  let retainedEntryBytes = 0;
  let previousPath;
  let repositoryMetadata;
  let repositoryBundle;
  const decoded = (async () => {
    for await (const entry of parser) {
      const name = entry.header.name;
      if (entry.header.type !== "file" || typeof name !== "string" || observedEntryNames.has(name)) {
        throw new Error("candidate workspace tar contains an invalid entry");
      }
      observedEntryNames.add(name);
      if (name.startsWith(workspaceEntryPrefix)) {
        if (files.length >= limits.maxFiles) {
          throw new Error("candidate workspace archive has an invalid file count");
        }
        const path = safeArchivePath(name.slice(workspaceEntryPrefix.length), limits.maxPathBytes);
        if (entry.header.mode !== 420 && entry.header.mode !== 493) {
          throw new Error(`candidate workspace archive has an unsupported mode: ${path}`);
        }
        assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
        const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `workspace file ${path}`);
        retainedEntryBytes += fileBytes.byteLength;
        assertWorkspacePathOrder(
          path,
          previousPath,
          observedPaths,
          "candidate workspace archive paths must be unique and sorted"
        );
        previousPath = path;
        if (fileBytes.byteLength > limits.maxTotalFileBytes - totalBytes) {
          throw new Error("candidate workspace archive exceeds maxTotalFileBytes");
        }
        totalBytes += fileBytes.byteLength;
        files.push({ path, mode: entry.header.mode, bytes: fileBytes });
      } else if (name === repositoryMetadataEntry) {
        if (entry.header.mode !== 384 || repositoryMetadata) {
          throw new Error("candidate workspace archive repository metadata is invalid");
        }
        assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
        const metadataBytes = await readTarEntry(
          entry,
          limits.maxPathBytes,
          "candidate repository metadata"
        );
        retainedEntryBytes += metadataBytes.byteLength;
        repositoryMetadata = parseRepositoryMetadata(metadataBytes, limits.maxRepositoryBundleBytes);
      } else if (name === repositoryBundleEntry) {
        if (entry.header.mode !== 384 || repositoryBundle) {
          throw new Error("candidate workspace archive repository bundle is invalid");
        }
        assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits);
        repositoryBundle = await readTarEntry(
          entry,
          limits.maxRepositoryBundleBytes,
          "candidate Git bundle"
        );
        retainedEntryBytes += repositoryBundle.byteLength;
      } else {
        throw new Error(`candidate workspace tar contains an unsupported entry: ${name}`);
      }
    }
    if (Boolean(repositoryMetadata) !== Boolean(repositoryBundle)) {
      throw new Error("candidate workspace archive repository evidence is incomplete");
    }
    const repository = repositoryMetadata && repositoryBundle ? repositoryFromTar(repositoryMetadata, repositoryBundle) : void 0;
    return { files, ...repository ? { repository } : {} };
  })();
  parser.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
  const result = await decoded;
  await verifyCanonicalWorkspaceArchive(
    result.files,
    result.repository,
    bytes,
    limits.maxArchiveBytes
  );
  return result;
}
function assertRetainedArchiveSize(archiveBytes, retainedEntryBytes, entryBytes, limits) {
  if (!Number.isSafeInteger(entryBytes) || entryBytes === void 0 || entryBytes < 0 || entryBytes > limits.maxArchiveBytes - archiveBytes - retainedEntryBytes) {
    throw new Error("candidate workspace archive exceeds maxArchiveBytes while decoding");
  }
}
function parseRepositoryMetadata(bytes, maxBundleBytes) {
  let value;
  try {
    value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
  } catch (error) {
    throw new Error("candidate workspace archive repository metadata is invalid", { cause: error });
  }
  if (!isRecord(value) || Object.keys(value).sort().join(",") !== "bundle,headCommit,headTree,kind,schemaVersion" || value.schemaVersion !== 1 || value.kind !== archiveKind || typeof value.headCommit !== "string" || typeof value.headTree !== "string" || !isRecord(value.bundle) || Object.keys(value.bundle).sort().join(",") !== "byteLength,sha256" || typeof value.bundle.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(value.bundle.sha256) || !Number.isSafeInteger(value.bundle.byteLength) || value.bundle.byteLength <= 0 || value.bundle.byteLength > maxBundleBytes) {
    throw new Error("candidate workspace archive repository is invalid");
  }
  if (!Buffer.from(canonicalCandidateBytes(value)).equals(Buffer.from(bytes))) {
    throw new Error("candidate workspace archive repository metadata is not canonical");
  }
  assertGitObjectId(value.headCommit, "repository HEAD");
  assertGitObjectId(value.headTree, "repository HEAD tree");
  if (value.headCommit.length !== value.headTree.length) {
    throw new Error("candidate repository HEAD and tree use different object formats");
  }
  return {
    schemaVersion: 1,
    kind: archiveKind,
    headCommit: value.headCommit,
    headTree: value.headTree,
    bundle: {
      sha256: value.bundle.sha256,
      byteLength: value.bundle.byteLength
    }
  };
}
function repositoryFromTar(metadata, bundle) {
  verifyBytes(bundle, metadata.bundle.sha256, metadata.bundle.byteLength, "candidate Git bundle");
  return {
    headCommit: metadata.headCommit,
    headTree: metadata.headTree,
    bundle: { ...metadata.bundle, bytes: bundle }
  };
}
async function writeTarEntry(archive, name, mode, bytes) {
  await new Promise((resolveEntry, rejectEntry) => {
    archive.entry(
      {
        name,
        mode,
        uid: 0,
        gid: 0,
        size: bytes.byteLength,
        mtime: fixedTarTime,
        type: "file",
        uname: "",
        gname: ""
      },
      Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),
      (error) => error ? rejectEntry(error) : resolveEntry()
    );
  });
}
async function readTarEntry(entry, maxBytes, label) {
  const size = entry.header.size;
  if (!Number.isSafeInteger(size) || size === void 0 || size < 0 || size > maxBytes) {
    throw new Error(`${label} has an invalid tar size`);
  }
  const bytes = await collectStream(entry, maxBytes, label);
  if (bytes.byteLength !== size) throw new Error(`${label} differs from its tar size`);
  return bytes;
}
async function collectStream(stream, maxBytes, label) {
  const chunks = [];
  let totalBytes = 0;
  for await (const chunk of stream) {
    if (chunk.byteLength > maxBytes - totalBytes) {
      const error = new Error(`${label} exceeds its size limit`);
      if ("destroy" in stream && typeof stream.destroy === "function") stream.destroy(error);
      throw error;
    }
    const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
    chunks.push(bytes);
    totalBytes += bytes.byteLength;
  }
  return Buffer.concat(chunks, totalBytes);
}
async function streamEqualsBytes(stream, expected, maxBytes, label) {
  const expectedBuffer = Buffer.from(expected.buffer, expected.byteOffset, expected.byteLength);
  let equal = true;
  let offset = 0;
  for await (const chunk of stream) {
    if (chunk.byteLength > maxBytes - offset) {
      const error = new Error(`${label} exceeds its size limit`);
      if ("destroy" in stream && typeof stream.destroy === "function") stream.destroy(error);
      throw error;
    }
    const observed = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
    if (offset + observed.byteLength > expectedBuffer.byteLength || !observed.equals(expectedBuffer.subarray(offset, offset + observed.byteLength))) {
      equal = false;
    }
    offset += observed.byteLength;
  }
  return equal && offset === expectedBuffer.byteLength;
}
async function prepareEmptyDestination(destination) {
  await mkdir2(destination, { recursive: true, mode: 448 });
  const stats = await lstat(destination);
  if (!stats.isDirectory() || stats.isSymbolicLink() || await realpath(destination) !== destination) {
    throw new Error("candidate workspace destination must be a real directory");
  }
  if ((await readdir(destination)).length > 0) {
    throw new Error("candidate workspace destination must be empty");
  }
}
async function writeWorkspaceFiles(destination, files) {
  for (const file of files) {
    const path = workspacePath(destination, file.path);
    await mkdir2(dirname(path), { recursive: true, mode: 448 });
    const descriptor = await open2(
      path,
      fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (typeof fsConstants.O_NOFOLLOW === "number" ? fsConstants.O_NOFOLLOW : 0),
      384
    );
    try {
      await descriptor.writeFile(file.bytes);
      const stats = await descriptor.stat();
      if (!stats.isFile() || stats.nlink !== 1) {
        throw new Error(`candidate workspace file identity changed while writing: ${file.path}`);
      }
      await descriptor.chmod(file.mode);
    } finally {
      await descriptor.close();
    }
  }
}
async function materializeRepository(repository, destination) {
  const temporary = await mkdtemp(join2(tmpdir(), "agent-candidate-workspace-bundle-"));
  const bundlePath = join2(temporary, `${randomUUID2()}.bundle`);
  try {
    await writeFile(bundlePath, repository.bundle.bytes, { flag: "wx", mode: 384 });
    await runCandidateGit(destination, [
      "init",
      "--quiet",
      "--initial-branch=candidate",
      `--object-format=${repository.headCommit.length === 64 ? "sha256" : "sha1"}`
    ]);
    await runCandidateGit(destination, ["bundle", "verify", bundlePath]);
    await runCandidateGit(destination, ["bundle", "unbundle", bundlePath]);
    const objectType = (await runCandidateGit(destination, ["cat-file", "-t", repository.headCommit])).stdout.toString("utf8").trim();
    if (objectType !== "commit") throw new Error("candidate repository HEAD is not a commit");
    const observedTree = (await runCandidateGit(destination, ["rev-parse", `${repository.headCommit}^{tree}`])).stdout.toString("utf8").trim();
    if (observedTree !== repository.headTree) {
      throw new Error("candidate repository bundle HEAD tree changed");
    }
    await runCandidateGit(destination, ["update-ref", "--no-deref", "HEAD", repository.headCommit]);
    await runCandidateGit(destination, ["read-tree", repository.headTree]);
    const status = (await runCandidateGit(destination, ["status", "--porcelain=v1", "--untracked-files=all"])).stdout.toString("utf8").trim();
    if (status) throw new Error("candidate repository files do not exactly match HEAD");
  } finally {
    await rm(temporary, { recursive: true, force: true });
  }
}
function workspaceManifest(files) {
  return {
    schemaVersion: 1,
    kind: "agent-candidate-workspace-manifest",
    files: files.map((file) => ({
      path: file.path,
      mode: file.mode,
      sha256: sha256Bytes(file.bytes),
      byteLength: file.bytes.byteLength
    }))
  };
}
function assertArchiveMatchesSnapshot(files, snapshot) {
  const material = workspaceManifest(files);
  const materialBytes = canonicalCandidateBytes(material);
  verifyBytes(
    materialBytes,
    snapshot.manifest.sha256,
    snapshot.manifest.byteLength,
    "candidate workspace manifest"
  );
  if (canonicalCandidateDigest(material) !== snapshot.digest || !Buffer.from(materialBytes).equals(Buffer.from(canonicalCandidateBytes(snapshot.material)))) {
    throw new Error("candidate workspace archive does not match its snapshot manifest");
  }
}
function assertWorkspaceFilesWithinLimits(files, limits) {
  if (files.length > limits.maxFiles) {
    throw new Error("candidate workspace exceeds maxFiles");
  }
  let totalBytes = 0;
  let previousPath;
  const observedPaths = /* @__PURE__ */ new Set();
  for (const file of files) {
    const path = safeArchivePath(file.path, limits.maxPathBytes);
    assertWorkspacePathOrder(
      path,
      previousPath,
      observedPaths,
      "candidate workspace paths must be unique and sorted"
    );
    previousPath = path;
    if (file.mode !== 420 && file.mode !== 493) {
      throw new Error(`candidate workspace file has unsupported mode: ${path}`);
    }
    if (file.bytes.byteLength > limits.maxFileBytes) {
      throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`);
    }
    totalBytes += file.bytes.byteLength;
    if (totalBytes > limits.maxTotalFileBytes) {
      throw new Error("candidate workspace exceeds maxTotalFileBytes");
    }
  }
}
function normalizeWorkspaceFiles(input, limits) {
  if (!Array.isArray(input)) {
    throw new Error("candidate workspace files must be an array");
  }
  const fileCount = input.length;
  if (fileCount > limits.maxFiles) {
    throw new Error("candidate workspace exceeds maxFiles");
  }
  let totalBytes = 0;
  const files = [];
  for (let index = 0; index < fileCount; index++) {
    const inputFile = input[index];
    if (!isRecord(inputFile) || Object.keys(inputFile).sort().join(",") !== "bytes,mode,path") {
      throw new Error(`candidate workspace file ${index} is invalid`);
    }
    const descriptors = Object.getOwnPropertyDescriptors(inputFile);
    if (!("value" in (descriptors.path ?? {})) || !("value" in (descriptors.mode ?? {})) || !("value" in (descriptors.bytes ?? {}))) {
      throw new Error(`candidate workspace file ${index} must use fixed values`);
    }
    const path = safeArchivePath(descriptors.path?.value, limits.maxPathBytes);
    const mode = descriptors.mode?.value;
    const inputBytes = descriptors.bytes?.value;
    if (mode !== 420 && mode !== 493) {
      throw new Error(`candidate workspace file has unsupported mode: ${path}`);
    }
    const view = inspectWorkspaceBytes(inputBytes, path);
    if (view.byteLength > limits.maxFileBytes) {
      throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`);
    }
    if (view.byteLength > limits.maxTotalFileBytes - totalBytes) {
      throw new Error("candidate workspace exceeds maxTotalFileBytes");
    }
    if (view.byteLength > Math.max(0, limits.maxArchiveBytes - 1024)) {
      throw new Error("candidate workspace archive exceeds maxArchiveBytes");
    }
    totalBytes += view.byteLength;
    files.push({ path, mode, bytes: detachWorkspaceBytes(view) });
  }
  files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
  assertWorkspaceFilesWithinLimits(files, limits);
  return files;
}
function workspaceLimits(overrides) {
  const limits = { ...defaultLimits, ...overrides };
  for (const [name, value] of Object.entries(limits)) {
    if (!Number.isSafeInteger(value) || value <= 0) {
      throw new Error(`candidate workspace ${name} must be a positive safe integer`);
    }
  }
  return Object.freeze(limits);
}
function safeArchivePath(value, maxPathBytes) {
  if (typeof value !== "string" || !value || !isWellFormedUnicode(value) || Buffer.byteLength(value, "utf8") > maxPathBytes || isAbsolute(value) || win32.isAbsolute(value) || value.includes("\\") || value.includes("\0") || hasControlCharacter(value) || value.split("/").some((part) => !part || part === "." || part === "..") || [".git", ".sidecar"].includes(value.split("/")[0]?.toLowerCase() ?? "")) {
    throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`);
  }
  return value;
}
function assertWorkspacePathOrder(path, previousPath, observedPaths, errorMessage) {
  if (previousPath !== void 0 && previousPath >= path) throw new Error(errorMessage);
  for (let slash = path.indexOf("/"); slash !== -1; slash = path.indexOf("/", slash + 1)) {
    if (observedPaths.has(path.slice(0, slash))) throw new Error(errorMessage);
  }
  observedPaths.add(path);
}
function inspectWorkspaceBytes(input, path) {
  let buffer;
  let byteOffset;
  let byteLength;
  try {
    buffer = typedArrayBufferGetter.call(input);
    byteOffset = typedArrayByteOffsetGetter.call(input);
    byteLength = typedArrayByteLengthGetter.call(input);
  } catch {
    throw new Error(`candidate workspace file bytes are invalid: ${path}`);
  }
  if (isSharedArrayBuffer(buffer)) {
    throw new Error(`candidate workspace file uses shared bytes: ${path}`);
  }
  if (!isAnyArrayBuffer(buffer)) {
    throw new Error(`candidate workspace file bytes are invalid: ${path}`);
  }
  return { buffer, byteOffset, byteLength };
}
function detachWorkspaceBytes(input) {
  const { buffer, byteOffset, byteLength } = input;
  const copy = new Uint8Array(byteLength);
  Uint8Array.prototype.set.call(copy, new Uint8Array(buffer, byteOffset, byteLength));
  return copy;
}
function isWellFormedUnicode(value) {
  for (let index = 0; index < value.length; index++) {
    const code = value.charCodeAt(index);
    if (code >= 55296 && code <= 56319) {
      const next = value.charCodeAt(index + 1);
      if (!(next >= 56320 && next <= 57343)) return false;
      index++;
    } else if (code >= 56320 && code <= 57343) {
      return false;
    }
  }
  return true;
}
function workspacePath(root, relativePath) {
  const path = resolve(root, relativePath);
  if (!path.startsWith(`${root}${sep}`)) {
    throw new Error(`candidate workspace archive path escapes its destination: ${relativePath}`);
  }
  return path;
}
function assertGitObjectId(value, label) {
  if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)) {
    throw new Error(`candidate repository ${label} is not a Git object id`);
  }
}
function hasControlCharacter(value) {
  for (let index = 0; index < value.length; index++) {
    const code = value.charCodeAt(index);
    if (code < 32 || code === 127) return true;
  }
  return false;
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireTypedArrayGetter(name) {
  const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
  const getter = Object.getOwnPropertyDescriptor(typedArrayPrototype, name)?.get;
  if (!getter) throw new Error(`typed array intrinsic ${name} accessor is unavailable`);
  return getter;
}
var typedArrayBufferGetter = requireTypedArrayGetter("buffer");
var typedArrayByteOffsetGetter = requireTypedArrayGetter("byteOffset");
var typedArrayByteLengthGetter = requireTypedArrayGetter("byteLength");

export {
  buildAgentCandidateBundle,
  FileAgentCandidateExecutionClaimStore,
  disposePreparedAgentCandidateExecution,
  createProtectedAgentCandidateModelPort,
  recoverExpiredAgentCandidateExecution,
  captureAgentCandidateWorkspace,
  captureAgentCandidateWorkspaceFiles,
  createAgentCandidateWorkspacePort
};
//# sourceMappingURL=chunk-FTXM7Q7P.js.map