import {
  isRuntimeRef,
  readPendingInvocations
} from "./chunk-GCR6VY7O.mjs";

// src/core/lib/flowCompiler/resolveRefs.ts
function resolveRuntimeRefs(nb, getNodeOutput, triggerContext) {
  return resolveValue(nb, getNodeOutput, triggerContext);
}
function resolveValue(value, getNodeOutput, triggerContext) {
  if (isRuntimeRef(value)) {
    return resolveRef(value.$ref, getNodeOutput, triggerContext);
  }
  if (Array.isArray(value)) {
    return value.map((item) => resolveValue(item, getNodeOutput, triggerContext));
  }
  if (typeof value === "object" && value !== null) {
    const result = {};
    for (const [key, val] of Object.entries(value)) {
      result[key] = resolveValue(val, getNodeOutput, triggerContext);
    }
    return result;
  }
  return value;
}
function resolveRef(ref, getNodeOutput, triggerContext) {
  if (ref.startsWith("trigger.payload.")) {
    if (!triggerContext) {
      throw new Error(`Trigger ref "${ref}" used outside of a listener invocation context. trigger.payload.* refs are only valid on block.event-triggered blocks.`);
    }
    const fieldPath2 = ref.slice("trigger.payload.".length);
    return getNestedValue(triggerContext.payload, fieldPath2);
  }
  if (triggerContext && Object.prototype.hasOwnProperty.call(triggerContext.refSnapshots, ref)) {
    return triggerContext.refSnapshots[ref];
  }
  const outputIndex = ref.indexOf(".output.");
  if (outputIndex === -1) {
    throw new Error(`Invalid runtime reference "${ref}". Expected format: "nodeId.output.fieldPath" or "trigger.payload.fieldPath"`);
  }
  const nodeId = ref.slice(0, outputIndex);
  const fieldPath = ref.slice(outputIndex + ".output.".length);
  const output = getNodeOutput(nodeId);
  if (!output) {
    return void 0;
  }
  return getNestedValue(output, fieldPath);
}
function getNestedValue(obj, path) {
  const parts = path.split(".");
  let current = obj;
  for (const part of parts) {
    if (current == null || typeof current !== "object") {
      return void 0;
    }
    current = current[part];
  }
  return current;
}

// src/core/lib/flowAgent/store.ts
import * as Y from "yjs";

// src/core/lib/flowAgent/utils.ts
function stableStringify(value) {
  if (value === void 0) return "null";
  if (value === null || typeof value !== "object") {
    return JSON.stringify(value);
  }
  if (Array.isArray(value)) {
    return `[${value.map((item) => stableStringify(item)).join(",")}]`;
  }
  const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
  return `{${entries.map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`).join(",")}}`;
}
function fnv1a32(input) {
  let hash = 2166136261;
  for (let i = 0; i < input.length; i++) {
    hash ^= input.charCodeAt(i);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0");
}
function createIntentHash(intent) {
  return fnv1a32(stableStringify(intent));
}
function parseJsonProp(value, fallback) {
  if (value == null || value === "") return fallback;
  if (typeof value === "object") return value;
  if (typeof value !== "string") return fallback;
  try {
    const parsed = JSON.parse(value);
    return parsed;
  } catch {
    return fallback;
  }
}
function getBlockActionType(block) {
  const props = block?.props;
  const actionType = props?.actionType;
  return typeof actionType === "string" && actionType.length > 0 ? actionType : void 0;
}
function getBlockTitle(block) {
  const props = block?.props;
  const title = props?.title;
  return typeof title === "string" && title.length > 0 ? title : void 0;
}
function getBlockType(block) {
  const type = block?.type;
  return typeof type === "string" && type.length > 0 ? type : "block";
}
function getBlockProps(block) {
  return block?.props || {};
}
function getBlockId(block) {
  const id = block?.id;
  return typeof id === "string" && id.length > 0 ? id : void 0;
}
function getAssigneeDid(block) {
  const props = getBlockProps(block);
  const assignment = parseJsonProp(props.assignment, {});
  const did = assignment?.assignedActor?.did;
  return typeof did === "string" && did.length > 0 ? did : void 0;
}
function getDueAt(block) {
  const props = getBlockProps(block);
  const ttlAbsoluteDueDate = props.ttlAbsoluteDueDate;
  if (typeof ttlAbsoluteDueDate !== "string" || ttlAbsoluteDueDate.length === 0) return void 0;
  const parsed = new Date(ttlAbsoluteDueDate).getTime();
  return Number.isFinite(parsed) ? parsed : void 0;
}
function capabilityForCommand(can, flowUri, nodeId) {
  return {
    can,
    with: `${flowUri}:${nodeId}`
  };
}

// src/core/lib/flowAgent/store.ts
var FLOW_AGENT_OUTBOX_KEY = "agentOutbox";
var FLOW_AGENT_LEASES_KEY = "agentLeases";
var FLOW_AGENT_AUDIT_SCOPE = "__flow_agent__";
function getFlowAgentMaps(yDoc) {
  return {
    outbox: yDoc.getMap(FLOW_AGENT_OUTBOX_KEY),
    leases: yDoc.getMap(FLOW_AGENT_LEASES_KEY)
  };
}
function computeAgentCommandId(params) {
  const intentHash = createIntentHash(params);
  return `${params.flowId}:${params.nodeId}:${intentHash}`;
}
function queueAgentCommand(yDoc, command) {
  const { outbox } = getFlowAgentMaps(yDoc);
  const existing = outbox.get(command.id);
  if (existing) return { command: existing, created: false };
  outbox.set(command.id, command);
  appendAgentLedgerEvent(yDoc, {
    type: "agent.command",
    flowId: command.flowId,
    nodeId: command.nodeId,
    commandId: command.id,
    actorDid: command.actorDid,
    timestamp: command.createdAt,
    details: {
      commandType: command.type,
      status: command.status,
      idempotencyKey: command.idempotencyKey,
      reason: command.reason
    }
  });
  return { command, created: true };
}
function readQueuedAgentCommands(yDoc) {
  const { outbox } = getFlowAgentMaps(yDoc);
  const commands = [];
  outbox.forEach((command) => {
    if (command.status === "queued" || command.status === "leased" || command.status === "running") {
      commands.push(command);
    }
  });
  commands.sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
  return commands;
}
function updateAgentCommand(yDoc, commandId, patch) {
  const { outbox } = getFlowAgentMaps(yDoc);
  const current = outbox.get(commandId);
  if (!current) return null;
  const next = { ...current, ...patch };
  outbox.set(commandId, next);
  return next;
}
function appendAgentLedgerEvent(yDoc, event) {
  const auditMap = yDoc.getMap("auditTrail");
  let arr = auditMap.get(FLOW_AGENT_AUDIT_SCOPE);
  if (!arr) {
    arr = new Y.Array();
    auditMap.set(FLOW_AGENT_AUDIT_SCOPE, arr);
  }
  const fullEvent = {
    id: event.id || `${event.type}:${event.commandId || event.nodeId || "flow"}:${createIntentHash(event.details)}:${event.timestamp}`,
    type: event.type,
    flowId: event.flowId,
    actorDid: event.actorDid,
    timestamp: event.timestamp,
    details: JSON.parse(stableStringify(event.details))
  };
  if (event.nodeId) fullEvent.nodeId = event.nodeId;
  if (event.commandId) fullEvent.commandId = event.commandId;
  arr.push([
    {
      id: fullEvent.id,
      type: fullEvent.type,
      details: fullEvent,
      meta: {
        timestamp: new Date(fullEvent.timestamp).toISOString(),
        userId: fullEvent.actorDid,
        editable: false
      }
    }
  ]);
  return fullEvent;
}
function readAgentLedgerEvents(yDoc, eventType) {
  const auditMap = yDoc.getMap("auditTrail");
  const arr = auditMap.get(FLOW_AGENT_AUDIT_SCOPE);
  if (!arr) return [];
  const events = [];
  arr.forEach((value) => {
    if (!value || typeof value !== "object") return;
    const entry = value;
    if (!entry.details) return;
    if (eventType && entry.details.type !== eventType) return;
    events.push(entry.details);
  });
  events.sort((a, b) => a.timestamp - b.timestamp || a.id.localeCompare(b.id));
  return events;
}

// src/core/lib/flowAgent/policy.ts
var COMMAND_CAPABILITIES = {
  diagnose_blocker: "flow/observe",
  assign_actor: "flow/node/assign",
  notify_actor: "flow/notify",
  execute_action: "flow/node/execute",
  validate_external_state: "flow/mutation/execute",
  submit_claim: "flow/claim/submit",
  watch_udid: "flow/observe",
  archive_flow: "flow/archive",
  propose_config_change: "flow/config/propose"
};
function requiredCapabilityForCommand(type, flowUri, nodeId) {
  return capabilityForCommand(COMMAND_CAPABILITIES[type], flowUri, nodeId);
}
function isCapabilityMatch(granted, required) {
  return canMatches(granted.can, required.can) && resourceMatches(granted.with, required.with);
}
function canMatches(granted, required) {
  if (granted === "*" || granted === required) return true;
  if (granted.endsWith("/*")) {
    const prefix = granted.slice(0, -1);
    return required.startsWith(prefix);
  }
  return false;
}
function resourceMatches(granted, required) {
  if (granted === "*" || granted === required) return true;
  if (granted.endsWith("*")) {
    const prefix = granted.slice(0, -1);
    return required.startsWith(prefix);
  }
  return false;
}
function evaluateFlowAgentPolicy({
  actorDid,
  commandType,
  flowUri,
  nodeId,
  delegationStore,
  delegations,
  now = Date.now()
}) {
  const required = requiredCapabilityForCommand(commandType, flowUri, nodeId);
  const candidates = delegations || delegationStore?.getByAudience(actorDid) || [];
  for (const delegation of candidates) {
    if (delegation.audienceDid !== actorDid) continue;
    if (delegation.expiration != null && delegation.expiration <= now) continue;
    if (!delegation.capabilities.some((capability) => isCapabilityMatch(capability, required))) continue;
    return {
      allowed: true,
      reason: "Allowed by UCAN delegation",
      capability: required,
      proofCids: [delegation.cid, ...delegation.proofCids]
    };
  }
  return {
    allowed: false,
    reason: `Actor ${actorDid} lacks ${required.can} on ${required.with}`,
    capability: required,
    proofCids: []
  };
}

// src/core/lib/flowAgent/commands.ts
function createAgentCommand({ type, flowId, flowUri, nodeId, actor, reason, payload = {}, now = Date.now() }) {
  const capability = requiredCapabilityForCommand(type, flowUri, nodeId);
  const id = computeAgentCommandId({ flowId, nodeId, type, payload });
  return {
    id,
    type,
    flowId,
    flowUri,
    nodeId,
    actorDid: actor.did,
    status: "queued",
    capability,
    idempotencyKey: `${id}:${createIntentHash({ capability, payload })}`,
    createdAt: now,
    updatedAt: now,
    reason,
    payload
  };
}
function validateAgentCommand(command) {
  if (!command.id) return { valid: false, error: "Command id is required" };
  if (!command.flowId) return { valid: false, error: "flowId is required" };
  if (!command.flowUri) return { valid: false, error: "flowUri is required" };
  if (!command.nodeId) return { valid: false, error: "nodeId is required" };
  if (!command.actorDid) return { valid: false, error: "actorDid is required" };
  if (!command.capability?.can || !command.capability?.with) return { valid: false, error: "capability is required" };
  if (!command.idempotencyKey) return { valid: false, error: "idempotencyKey is required" };
  if (isExternalMutation(command.type) && !command.payload.validator) {
    return {
      valid: false,
      error: `${command.type} requires payload.validator for post-action read-back validation`
    };
  }
  if (command.type === "propose_config_change" && !command.payload.proposal) {
    return { valid: false, error: "Config changes must be expressed as payload.proposal" };
  }
  return { valid: true };
}
function isExternalMutation(type) {
  return type === "validate_external_state";
}

// src/core/lib/flowAgent/context.ts
function buildFlowAgentContext({ yDoc, flowId, flowUri = `ixo:flow:${flowId}`, actor, blocks, editor, now }) {
  return {
    yDoc,
    flowId,
    flowUri,
    actor,
    ...blocks ? { blocks } : {},
    ...editor ? { editor } : {},
    ...now ? { now } : {}
  };
}

// src/core/lib/flowAgent/lease.ts
var DEFAULT_FLOW_AGENT_LEASE_TTL_MS = 6e4;
function acquireFlowAgentLease({
  leases,
  commandId,
  nodeId,
  actorDid,
  now = Date.now(),
  ttlMs = DEFAULT_FLOW_AGENT_LEASE_TTL_MS
}) {
  const current = leases.get(commandId);
  if (current && current.expiresAt > now && current.actorDid !== actorDid) {
    return null;
  }
  const nextEpoch = current ? current.epoch + 1 : 1;
  const lease = {
    id: `${commandId}:lease:${nextEpoch}`,
    commandId,
    nodeId,
    actorDid,
    acquiredAt: now,
    expiresAt: now + ttlMs,
    epoch: nextEpoch
  };
  leases.set(commandId, lease);
  return lease;
}
function validateFlowAgentLease(leases, lease, now = Date.now()) {
  const current = leases.get(lease.commandId);
  return !!current && current.actorDid === lease.actorDid && current.epoch === lease.epoch && current.expiresAt > now;
}
function releaseFlowAgentLease(leases, lease) {
  const current = leases.get(lease.commandId);
  if (!current || current.actorDid !== lease.actorDid || current.epoch !== lease.epoch) return false;
  leases.delete(lease.commandId);
  return true;
}
function cleanupExpiredFlowAgentLeases(leases, now = Date.now()) {
  const expired = [];
  leases.forEach((lease, commandId) => {
    if (lease.expiresAt <= now) {
      expired.push(lease);
      leases.delete(commandId);
    }
  });
  return expired;
}

// src/core/lib/flowAgent/state.ts
function classifyBlockerCause(block, runtime) {
  const props = getBlockProps(block);
  if (runtime.error?.code === "missing_ucan") return "missing_ucan";
  if (runtime.error?.code === "validation_mismatch") return "validation_mismatch";
  if (runtime.error?.code === "external_confirmation_pending") return "external_confirmation_pending";
  if (runtime.error) return "service_error";
  const conditions = parseJsonProp(props.conditions, {});
  if (conditions.enabled && Array.isArray(conditions.conditions) && conditions.conditions.length > 0) {
    return "failed_upstream";
  }
  const inputs = parseJsonProp(props.inputs, {});
  const requiredInputs = parseJsonProp(props.requiredInputs, []);
  if (requiredInputs.some((key) => inputs[key] == null || inputs[key] === "")) {
    return "missing_input";
  }
  return void 0;
}
function classifyNodeState({ block, runtime, now, pendingInvocationCount = 0 }) {
  if (runtime.state === "completed" || runtime.state === "cancelled") return "Done";
  if (runtime.state === "failed" || runtime.error) return "Blocked";
  const dueAt = getDueAt(block);
  if (dueAt != null && dueAt <= now) return "Overdue";
  if (pendingInvocationCount > 0) return "Pending";
  return "Pending";
}
function snapshotNode(block, runtime, now, pendingInvocationCount = 0) {
  const nodeId = getBlockId(block);
  if (!nodeId) {
    throw new Error("Cannot snapshot a block without an id");
  }
  const publicState = classifyNodeState({ block, runtime, now, pendingInvocationCount });
  const dueAt = getDueAt(block);
  const assigneeDid = getAssigneeDid(block);
  const snapshot = {
    nodeId,
    blockType: getBlockType(block),
    runtime,
    publicState,
    pendingInvocationCount
  };
  const actionType = getBlockActionType(block);
  if (actionType) snapshot.actionType = actionType;
  const title = getBlockTitle(block);
  if (title) snapshot.title = title;
  if (publicState === "Blocked") {
    snapshot.blockerCause = classifyBlockerCause(block, runtime) || "unknown";
  }
  if (assigneeDid) snapshot.assigneeDid = assigneeDid;
  if (dueAt != null) snapshot.dueAt = dueAt;
  return snapshot;
}

// src/core/lib/flowAgent/orchestrator.ts
function getBlocks(context) {
  return context.blocks || context.editor?.document || [];
}
function getRuntime(yDoc, nodeId) {
  const runtime = yDoc.getMap("runtime");
  const value = runtime.get(nodeId);
  return value && typeof value === "object" ? value : {};
}
function validateInputs(block) {
  const props = getBlockProps(block);
  const inputs = parseJsonProp(props.inputs, {});
  const requiredInputs = parseJsonProp(props.requiredInputs, []);
  const missing = requiredInputs.filter((key) => inputs[key] == null || inputs[key] === "");
  if (missing.length > 0) {
    return { valid: false, reason: `Missing required inputs: ${missing.join(", ")}` };
  }
  return { valid: true };
}
function chooseActor(block, options) {
  const props = getBlockProps(block);
  const actionType = getBlockActionType(block);
  const requiredSkill = typeof props.requiredSkill === "string" ? props.requiredSkill : actionType;
  if (!options.candidateActors || options.candidateActors.length === 0) return void 0;
  if (!requiredSkill) return options.candidateActors[0];
  return options.candidateActors.find((actor) => actor.skills?.includes(requiredSkill)) || options.candidateActors[0];
}
function canQueueCommand(type, nodeId, context, options) {
  return evaluateFlowAgentPolicy({
    actorDid: context.actor.did,
    commandType: type,
    flowUri: context.flowUri,
    nodeId,
    delegationStore: options.delegationStore,
    delegations: options.delegations,
    now: context.now?.() || Date.now()
  }).allowed;
}
function queueIfAuthorized(context, options, type, nodeId, reason, payload) {
  const now = context.now?.() || Date.now();
  const policy = evaluateFlowAgentPolicy({
    actorDid: context.actor.did,
    commandType: type,
    flowUri: context.flowUri,
    nodeId,
    delegationStore: options.delegationStore,
    delegations: options.delegations,
    now
  });
  appendAgentLedgerEvent(context.yDoc, {
    type: "agent.decision",
    flowId: context.flowId,
    nodeId,
    actorDid: context.actor.did,
    timestamp: now,
    details: {
      commandType: type,
      allowed: policy.allowed,
      reason: policy.reason,
      capability: policy.capability
    }
  });
  if (!policy.allowed) return null;
  const command = createAgentCommand({
    type,
    flowId: context.flowId,
    flowUri: context.flowUri,
    nodeId,
    actor: context.actor,
    reason,
    payload,
    now
  });
  const validation = validateAgentCommand(command);
  if (!validation.valid) {
    appendAgentLedgerEvent(context.yDoc, {
      type: "agent.validation",
      flowId: context.flowId,
      nodeId,
      commandId: command.id,
      actorDid: context.actor.did,
      timestamp: now,
      details: { valid: false, error: validation.error }
    });
    return null;
  }
  return queueAgentCommand(context.yDoc, command).created ? command : null;
}
function planForSnapshot(context, options, block, snapshot) {
  const queued = [];
  const actionType = getBlockActionType(block);
  if (snapshot.publicState === "Done") {
    const runtime = snapshot.runtime;
    if (actionType === "qi/claim.submit" && runtime.output?.claimId && !runtime.output?.udid) {
      const command = queueIfAuthorized(context, options, "watch_udid", snapshot.nodeId, "Claim submitted but UDID is not yet observed", {
        claimId: runtime.output.claimId,
        timeoutMs: 864e5
      });
      if (command) queued.push(command);
    }
    return queued;
  }
  if (snapshot.publicState === "Overdue") {
    const command = queueIfAuthorized(context, options, "notify_actor", snapshot.nodeId, "Action node is overdue", {
      assigneeDid: snapshot.assigneeDid,
      dueAt: snapshot.dueAt,
      severity: "overdue"
    });
    if (command) queued.push(command);
    return queued;
  }
  if (snapshot.publicState === "Blocked") {
    const command = queueIfAuthorized(context, options, "diagnose_blocker", snapshot.nodeId, "Action node is blocked and requires diagnosis", {
      cause: snapshot.blockerCause || "unknown",
      error: snapshot.runtime.error
    });
    if (command) queued.push(command);
    return queued;
  }
  const assigneeDid = getAssigneeDid(block);
  if (!assigneeDid) {
    const actor = chooseActor(block, options);
    const command = queueIfAuthorized(context, options, "assign_actor", snapshot.nodeId, "Action node has no assigned actor", {
      targetActorDid: actor?.did,
      targetMatrixUserId: actor?.matrixUserId,
      requiredActionType: actionType
    });
    if (command) queued.push(command);
    return queued;
  }
  const inputValidation = validateInputs(block);
  if (!inputValidation.valid) {
    const command = queueIfAuthorized(context, options, "diagnose_blocker", snapshot.nodeId, inputValidation.reason || "Action node inputs are not ready", {
      cause: "missing_input"
    });
    if (command) queued.push(command);
    return queued;
  }
  if (actionType === "qi/claim.submit") {
    const command = queueIfAuthorized(context, options, "submit_claim", snapshot.nodeId, "Claim action is pending and agent is authorized to submit", {
      actionType
    });
    if (command) queued.push(command);
    return queued;
  }
  if (actionType && canQueueCommand("execute_action", snapshot.nodeId, context, options)) {
    const command = queueIfAuthorized(context, options, "execute_action", snapshot.nodeId, "Action node is pending and executable", {
      actionType
    });
    if (command) queued.push(command);
    return queued;
  }
  const notifyCommand = queueIfAuthorized(context, options, "notify_actor", snapshot.nodeId, "Action node is pending but the Flow Agent cannot execute it", {
    assigneeDid,
    requiredActionType: actionType,
    severity: "attention"
  });
  if (notifyCommand) queued.push(notifyCommand);
  return queued;
}
function planRalphLoopCommands(context, options = {}) {
  const now = context.now?.() || Date.now();
  const blocks = getBlocks(context);
  const snapshots = [];
  const queuedCommands = [];
  for (const block of blocks) {
    const nodeId = getBlockId(block);
    if (!nodeId) continue;
    const pendingInvocationCount = readPendingInvocations(context.yDoc, nodeId).length;
    const snapshot = snapshotNode(block, getRuntime(context.yDoc, nodeId), now, pendingInvocationCount);
    snapshots.push(snapshot);
    queuedCommands.push(...planForSnapshot(context, options, block, snapshot));
  }
  const flowDone = snapshots.length > 0 && snapshots.every((snapshot) => snapshot.publicState === "Done");
  if (flowDone && options.archiveWhenDone !== false) {
    const archiveCommand = queueIfAuthorized(context, options, "archive_flow", context.flowId, "All Ralph loop action nodes are done", {
      restartIfRepeats: true
    });
    if (archiveCommand) queuedCommands.push(archiveCommand);
  }
  return { snapshots, queuedCommands, flowDone };
}
async function callExecutor(command, context, executor) {
  switch (command.type) {
    case "execute_action":
      return executor.executeAction ? executor.executeAction(command, context) : { commandId: command.id, success: false, error: "No executeAction handler configured" };
    case "assign_actor":
      return executor.assignActor ? executor.assignActor(command, context) : { commandId: command.id, success: false, error: "No assignActor handler configured" };
    case "notify_actor":
      return executor.notifyActor ? executor.notifyActor(command, context) : { commandId: command.id, success: false, error: "No notifyActor handler configured" };
    case "validate_external_state":
      return executor.validateExternalState ? executor.validateExternalState(command, context) : { commandId: command.id, success: false, error: "No validateExternalState handler configured" };
    case "submit_claim":
      return executor.submitClaim ? executor.submitClaim(command, context) : { commandId: command.id, success: false, error: "No submitClaim handler configured" };
    case "watch_udid":
      return executor.watchUdid ? executor.watchUdid(command, context) : { commandId: command.id, success: false, error: "No watchUdid handler configured" };
    case "archive_flow":
      return executor.archiveFlow ? executor.archiveFlow(command, context) : { commandId: command.id, success: false, error: "No archiveFlow handler configured" };
    case "propose_config_change":
      return executor.proposeConfigChange ? executor.proposeConfigChange(command, context) : { commandId: command.id, success: false, error: "No proposeConfigChange handler configured" };
    case "diagnose_blocker":
      return executor.diagnoseBlocker ? executor.diagnoseBlocker(command, context) : { commandId: command.id, success: false, error: "No diagnoseBlocker handler configured" };
  }
}
async function executeQueuedAgentCommands(context, options = {}) {
  const executor = options.executor;
  if (!executor) return [];
  const now = context.now?.() || Date.now();
  const { leases } = getFlowAgentMaps(context.yDoc);
  const results = [];
  for (const command of readQueuedAgentCommands(context.yDoc)) {
    const validation = validateAgentCommand(command);
    if (!validation.valid) {
      updateAgentCommand(context.yDoc, command.id, { status: "failed", error: validation.error, updatedAt: now });
      results.push({ commandId: command.id, success: false, error: validation.error });
      continue;
    }
    const policy = evaluateFlowAgentPolicy({
      actorDid: context.actor.did,
      commandType: command.type,
      flowUri: context.flowUri,
      nodeId: command.nodeId,
      delegationStore: options.delegationStore,
      delegations: options.delegations,
      now
    });
    if (!policy.allowed) {
      updateAgentCommand(context.yDoc, command.id, { status: "skipped", error: policy.reason, updatedAt: now });
      results.push({ commandId: command.id, success: false, error: policy.reason });
      continue;
    }
    const lease = acquireFlowAgentLease({
      leases,
      commandId: command.id,
      nodeId: command.nodeId,
      actorDid: context.actor.did,
      now,
      ttlMs: options.leaseTtlMs
    });
    if (!lease) {
      continue;
    }
    updateAgentCommand(context.yDoc, command.id, { status: "running", lease, updatedAt: now });
    try {
      const result = await callExecutor({ ...command, lease, status: "running" }, context, executor);
      if (!validateFlowAgentLease(leases, lease, context.now?.() || Date.now())) {
        const leaseError = "Lease expired or was superseded before command commit";
        updateAgentCommand(context.yDoc, command.id, { status: "failed", error: leaseError, updatedAt: context.now?.() || Date.now() });
        results.push({ commandId: command.id, success: false, error: leaseError });
        continue;
      }
      updateAgentCommand(context.yDoc, command.id, {
        status: result.success ? "confirmed" : "failed",
        error: result.error,
        updatedAt: context.now?.() || Date.now()
      });
      appendAgentLedgerEvent(context.yDoc, {
        type: result.success ? "agent.validation" : "agent.escalation",
        flowId: context.flowId,
        nodeId: command.nodeId,
        commandId: command.id,
        actorDid: context.actor.did,
        timestamp: context.now?.() || Date.now(),
        details: {
          success: result.success,
          confirmed: result.confirmed,
          output: result.output,
          error: result.error
        }
      });
      results.push(result);
    } finally {
      releaseFlowAgentLease(leases, lease);
    }
  }
  return results;
}
async function tickFlowAgent(context, options = {}) {
  const plan = planRalphLoopCommands(context, options);
  const executedCommands = await executeQueuedAgentCommands(context, options);
  return {
    flowDone: plan.flowDone,
    snapshots: plan.snapshots,
    queuedCommands: plan.queuedCommands,
    executedCommands
  };
}

// src/core/lib/flowAgent/service.ts
var FlowAgentService = class {
  constructor(context, options = {}) {
    this.context = context;
    this.options = options;
    this.timer = null;
    this.running = false;
  }
  async tick() {
    if (this.running) {
      return {
        flowDone: false,
        snapshots: [],
        queuedCommands: [],
        executedCommands: []
      };
    }
    this.running = true;
    try {
      const result = await tickFlowAgent(this.context, this.options);
      await this.options.onTick?.(result);
      return result;
    } catch (error) {
      this.options.onError?.(error);
      throw error;
    } finally {
      this.running = false;
    }
  }
  start() {
    if (this.timer) return;
    const intervalMs = this.options.intervalMs || 3e4;
    this.timer = setInterval(() => {
      this.tick().catch((error) => {
        this.options.onError?.(error);
      });
    }, intervalMs);
  }
  stop() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  }
};

export {
  resolveRuntimeRefs,
  getFlowAgentMaps,
  computeAgentCommandId,
  queueAgentCommand,
  readQueuedAgentCommands,
  updateAgentCommand,
  appendAgentLedgerEvent,
  readAgentLedgerEvents,
  requiredCapabilityForCommand,
  isCapabilityMatch,
  canMatches,
  resourceMatches,
  evaluateFlowAgentPolicy,
  createAgentCommand,
  validateAgentCommand,
  isExternalMutation,
  buildFlowAgentContext,
  acquireFlowAgentLease,
  validateFlowAgentLease,
  releaseFlowAgentLease,
  cleanupExpiredFlowAgentLeases,
  classifyBlockerCause,
  classifyNodeState,
  snapshotNode,
  planRalphLoopCommands,
  executeQueuedAgentCommands,
  tickFlowAgent,
  FlowAgentService
};
//# sourceMappingURL=chunk-7ZKV7F6Z.mjs.map