import {
  FlowAgentService,
  acquireFlowAgentLease,
  appendAgentLedgerEvent,
  buildFlowAgentContext,
  canMatches,
  classifyBlockerCause,
  classifyNodeState,
  cleanupExpiredFlowAgentLeases,
  computeAgentCommandId,
  createAgentCommand,
  evaluateFlowAgentPolicy,
  executeQueuedAgentCommands,
  getFlowAgentMaps,
  isCapabilityMatch,
  isExternalMutation,
  planRalphLoopCommands,
  queueAgentCommand,
  readAgentLedgerEvents,
  readQueuedAgentCommands,
  releaseFlowAgentLease,
  requiredCapabilityForCommand,
  resolveRuntimeRefs,
  resourceMatches,
  snapshotNode,
  tickFlowAgent,
  updateAgentCommand,
  validateAgentCommand,
  validateFlowAgentLease
} from "../chunk-7ZKV7F6Z.mjs";
import {
  RUN_RECORD_AUDIT_TYPE,
  appendRunRecord,
  buildAuthzFromProps,
  buildFlowNodeFromBlock,
  buildServicesFromHandlers,
  canToType,
  clearRuntimeForTemplateClone,
  compileBaseUcanFlow,
  computePendingInvocationId,
  createInvocationStore,
  createMemoryInvocationStore,
  createMemoryUcanDelegationStore,
  createRuntimeStateManager,
  createUcanDelegationStore,
  createUcanService,
  decompileToBaseUcanFlow,
  executeNode,
  findFailedListenersForSourceRun,
  getAction,
  getActionByCan,
  getActionForBlock,
  getActiveEditor,
  getAllActions,
  getAllCanMappings,
  getOrCreateBlockPendingMap,
  getPendingInvocationsMap,
  hasAction,
  isAuthorized,
  isRuntimeRef,
  mergeCompiledFlows,
  queuePendingInvocation,
  readCompiledFlowFromYDoc,
  readFlow,
  readFlowAsBaseUcan,
  readFlowFromEditor,
  readPendingInvocations,
  readRunRecords,
  reconcilePendingInvocations,
  registerAction,
  removePendingInvocation,
  replayFailedListenerRun,
  setActiveEditor,
  setupFlowFromBaseUcan,
  snapshotInputRefs,
  typeToCan,
  writeRunRecordAndReconcile
} from "../chunk-GCR6VY7O.mjs";
import {
  computeCID,
  computeJsonCID
} from "../chunk-VU34HOXM.mjs";

// src/core/templates/oracleInitFlow.ts
var oracleInitSurveySchema = {
  title: "Oracle Configuration",
  description: "Provide the details needed to initialise a new oracle on the IXO network.",
  logoPosition: "right",
  pages: [
    {
      name: "basicInfo",
      title: "Basic Information",
      elements: [
        {
          type: "text",
          name: "projectName",
          title: "Project Name",
          description: "Used as the folder name \u2014 no spaces or special characters.",
          isRequired: true,
          validators: [
            {
              type: "regex",
              text: "Only lowercase letters, numbers, and hyphens are allowed (no spaces or special characters).",
              regex: "^[a-z0-9]+(-[a-z0-9]+)*$"
            }
          ]
        },
        {
          type: "text",
          name: "pin",
          title: "PIN",
          description: "A 6-digit PIN used to secure wallet operations.",
          isRequired: true,
          inputType: "password",
          maxLength: 6,
          validators: [
            {
              type: "regex",
              text: "PIN must be exactly 6 digits.",
              regex: "^\\d{6}$"
            }
          ]
        }
      ]
    },
    {
      name: "oracleDetails",
      title: "Oracle Details",
      elements: [
        {
          type: "text",
          name: "oracleName",
          title: "Oracle Name",
          isRequired: true
        },
        {
          type: "text",
          name: "orgName",
          title: "Organisation Name",
          isRequired: true
        },
        {
          type: "comment",
          name: "description",
          title: "Description",
          isRequired: true
        },
        {
          type: "text",
          name: "location",
          title: "Location",
          isRequired: true
        },
        {
          type: "text",
          name: "logoUrl",
          title: "Logo URL",
          isRequired: true,
          inputType: "url",
          validators: [{ type: "url" }]
        },
        {
          type: "text",
          name: "coverImageUrl",
          title: "Cover Image URL",
          isRequired: true,
          inputType: "url",
          validators: [{ type: "url" }]
        }
      ]
    },
    {
      name: "serviceConfig",
      title: "Service Configuration",
      elements: [
        {
          type: "text",
          name: "apiUrl",
          title: "API URL",
          isRequired: true,
          inputType: "url",
          defaultValue: "http://localhost:4000",
          validators: [{ type: "url" }]
        },
        {
          type: "text",
          name: "price",
          title: "Price",
          description: "Service price in IXO tokens (minimum 1).",
          isRequired: true,
          inputType: "number",
          defaultValue: 100,
          validators: [
            {
              type: "numeric",
              text: "Price must be at least 1.",
              minValue: 1
            }
          ]
        },
        {
          type: "dropdown",
          name: "llmModel",
          title: "LLM Model",
          isRequired: true,
          choices: [
            { value: "kimi-k2.5", text: "Kimi K2.5" },
            { value: "claude-sonnet", text: "Claude Sonnet" },
            { value: "gpt-4o", text: "GPT-4o" },
            { value: "gemini-2.5", text: "Gemini 2.5" },
            { value: "llama-4", text: "Llama 4" },
            { value: "custom", text: "Custom" }
          ]
        },
        {
          type: "comment",
          name: "opening",
          title: "Opening Message",
          description: "The greeting or introduction the agent uses when starting a conversation.",
          isRequired: false
        },
        {
          type: "comment",
          name: "communicationStyle",
          title: "Communication Style",
          description: "How the agent should communicate (e.g. formal, friendly, concise).",
          isRequired: false
        },
        {
          type: "comment",
          name: "capabilities",
          title: "What can the agent do?",
          description: "Describe what this agent is capable of doing for users.",
          isRequired: false
        }
      ]
    }
  ]
};
function createOracleInitFlowTemplate() {
  const metadata = {
    "@context": "https://schema.ixo.world/flow/v1",
    _type: "flow/oracle-init",
    schema_version: "1.0.0",
    doc_id: "",
    title: "Oracle Init Flow",
    createdAt: (/* @__PURE__ */ new Date()).toISOString(),
    createdBy: "",
    flowOwnerDid: ""
  };
  const nodes = [
    // ------------------------------------------------------------------
    // [1] Form — collects all oracle configuration
    // ------------------------------------------------------------------
    {
      id: "oracle-form",
      type: "form",
      props: {
        title: "Oracle Configuration",
        description: "Enter the details for your new oracle.",
        icon: "checklist",
        surveySchema: JSON.stringify(oracleInitSurveySchema)
      }
    },
    // ------------------------------------------------------------------
    // [2] Skills — skill/MCP configuration
    // ------------------------------------------------------------------
    {
      id: "oracle-skills",
      type: "skills",
      props: {
        title: "Oracle Skills & MCP Servers",
        description: "Configure skills and MCP servers for the oracle.",
        icon: "tools",
        skills: "[]",
        entityDid: "",
        mcpServers: "[]",
        status: "pending"
      },
      activationCondition: {
        upstreamNodeId: "oracle-form",
        requiredStatus: "approved"
      }
    },
    // ------------------------------------------------------------------
    // [3] Action — Generate & Fund Wallet
    //     Generates a new wallet and funds it in one step.
    // ------------------------------------------------------------------
    {
      id: "oracle-wallet",
      type: "action",
      props: {
        title: "Generate & Fund Wallet",
        description: "Generate a new IXO wallet and fund it with tokens.",
        icon: "bolt",
        actionType: "qi/wallet.generateAndFund",
        inputs: JSON.stringify({}),
        requiresConfirmation: ""
      },
      activationCondition: {
        upstreamNodeId: "oracle-skills",
        requiredStatus: "approved"
      }
    },
    // ------------------------------------------------------------------
    // [4] Action — Create Identity (IID + Matrix)
    //     Creates the on-chain IID document, then registers the Matrix account.
    // ------------------------------------------------------------------
    {
      id: "oracle-identity",
      type: "action",
      props: {
        title: "Create Identity",
        description: "Create on-chain DID document and register Matrix account.",
        icon: "bolt",
        actionType: "qi/identity.create",
        inputs: JSON.stringify({
          mnemonic: "{{oracle-wallet.output.mnemonic}}",
          did: "{{oracle-wallet.output.did}}",
          address: "{{oracle-wallet.output.address}}",
          pubKey: "{{oracle-wallet.output.pubKey}}",
          formAnswers: "{{oracle-form.output.form.answers}}"
        }),
        requiresConfirmation: ""
      },
      activationCondition: {
        upstreamNodeId: "oracle-wallet",
        requiredStatus: "approved"
      }
    },
    // ------------------------------------------------------------------
    // [5] Action — Create Oracle Entity
    //     On-chain entity creation with P-256 encryption key.
    // ------------------------------------------------------------------
    {
      id: "oracle-entity-create",
      type: "action",
      props: {
        title: "Create Oracle Entity",
        description: "Create the oracle entity on the IXO network.",
        icon: "bolt",
        actionType: "qi/entity.createOracle",
        inputs: JSON.stringify({
          // Wallet outputs
          mnemonic: "{{oracle-wallet.output.mnemonic}}",
          address: "{{oracle-wallet.output.address}}",
          did: "{{oracle-wallet.output.did}}",
          pubKey: "{{oracle-wallet.output.pubKey}}",
          // Matrix outputs (from identity block)
          matrixAccessToken: "{{oracle-identity.output.matrixAccessToken}}",
          matrixRoomId: "{{oracle-identity.output.matrixRoomId}}",
          // Form outputs — whole blob, action parses & destructures
          formAnswers: "{{oracle-form.output.form.answers}}"
        }),
        requiresConfirmation: ""
      },
      activationCondition: {
        upstreamNodeId: "oracle-identity",
        requiredStatus: "approved"
      }
    },
    // ------------------------------------------------------------------
    // [6] Action — Configure Oracle (contract + secrets + config)
    //     Creates the user↔oracle DM room, encrypts secrets, stores config.
    // ------------------------------------------------------------------
    {
      id: "oracle-configure",
      type: "action",
      props: {
        title: "Configure Oracle",
        description: "Contract oracle, encrypt secrets, and store configuration.",
        icon: "bolt",
        actionType: "qi/oracle.configureOracle",
        inputs: JSON.stringify({
          // Contract input
          oracleEntityDid: "{{oracle-entity-create.output.entityDid}}",
          // Secrets routing (matrixRoomId comes from contract phase, not inputs)
          publicKeyMultibase: "{{oracle-entity-create.output.encryptionPublicKeyMultibase}}",
          verificationMethodId: "{{oracle-entity-create.output.encryptionVerificationMethodId}}",
          // Fresh mxLogin params
          matrixHomeServerUrl: "{{oracle-identity.output.matrixHomeServerUrl}}",
          matrixUsername: "{{oracle-identity.output.matrixUserId}}",
          // Sensitive plaintext values
          mnemonic: "{{oracle-wallet.output.mnemonic}}",
          matrixPassword: "{{oracle-identity.output.matrixPassword}}",
          matrixRecoveryPhrase: "{{oracle-identity.output.matrixRecoveryPhrase}}",
          // MCP auth secrets (already JWE-encrypted by skills block FlowDetail)
          mcpAuthSecrets: "{{oracle-skills.output.mcpAuthSecrets}}",
          // Skills outputs
          skills: "{{oracle-skills.output.skills}}",
          mcpServers: "{{oracle-skills.output.mcpServers}}",
          // Identifiers
          matrixUserId: "{{oracle-identity.output.matrixUserId}}",
          matrixAccountRoomId: "{{oracle-identity.output.matrixRoomId}}",
          entityDid: "{{oracle-entity-create.output.entityDid}}",
          oracleAddress: "{{oracle-wallet.output.address}}",
          oracleDid: "{{oracle-wallet.output.did}}",
          // Form outputs — whole blob, action parses & destructures
          formAnswers: "{{oracle-form.output.form.answers}}"
        }),
        requiresConfirmation: ""
      },
      activationCondition: {
        upstreamNodeId: "oracle-entity-create",
        requiredStatus: "approved"
      }
    },
    // ------------------------------------------------------------------
    // [7] Action — Deploy Oracle (setup + start)
    //     Clones repo, writes config, builds, then starts the process.
    // ------------------------------------------------------------------
    {
      id: "oracle-deploy",
      type: "action",
      props: {
        title: "Deploy Oracle",
        description: "Set up environment and start the oracle process.",
        icon: "bolt",
        actionType: "qi/oracle.deploy",
        inputs: JSON.stringify({
          entityDid: "{{oracle-entity-create.output.entityDid}}",
          roomId: "{{oracle-configure.output.userOracleRoomId}}",
          skills: "{{oracle-skills.output.skills}}",
          mcpServers: "{{oracle-skills.output.mcpServers}}",
          mnemonic: "{{oracle-wallet.output.mnemonic}}",
          matrixPassword: "{{oracle-identity.output.matrixPassword}}",
          matrixRecoveryPhrase: "{{oracle-identity.output.matrixRecoveryPhrase}}",
          matrixUsername: "{{oracle-identity.output.matrixUserId}}",
          matrixAccountRoomId: "{{oracle-identity.output.matrixRoomId}}",
          freshAccessToken: "{{oracle-configure.output.freshAccessToken}}",
          openRouterApiKey: "{{oracle-configure.output.openRouterApiKeyPlaintext}}",
          // Form outputs — whole blob, action parses & destructures
          formAnswers: "{{oracle-form.output.form.answers}}"
        }),
        requiresConfirmation: ""
      },
      activationCondition: {
        upstreamNodeId: "oracle-configure",
        requiredStatus: "approved"
      }
    },
    // ------------------------------------------------------------------
    // [8] Secrets — display credentials and download
    // ------------------------------------------------------------------
    {
      id: "oracle-secrets",
      type: "secrets",
      props: {
        title: "Oracle Credentials",
        description: "Download your oracle credentials after setup is complete.",
        icon: "key",
        downloadEndpoint: "",
        entityDid: "{{oracle-entity-create.output.entityDid}}"
      },
      activationCondition: {
        upstreamNodeId: "oracle-deploy",
        requiredStatus: "approved"
      }
    }
  ];
  return { metadata, nodes };
}
export {
  FlowAgentService,
  RUN_RECORD_AUDIT_TYPE,
  acquireFlowAgentLease,
  appendAgentLedgerEvent,
  appendRunRecord,
  buildAuthzFromProps,
  buildFlowAgentContext,
  buildFlowNodeFromBlock,
  buildServicesFromHandlers,
  canMatches,
  canToType,
  classifyBlockerCause,
  classifyNodeState,
  cleanupExpiredFlowAgentLeases,
  clearRuntimeForTemplateClone,
  compileBaseUcanFlow,
  computeAgentCommandId,
  computeCID,
  computeJsonCID,
  computePendingInvocationId,
  createAgentCommand,
  createInvocationStore,
  createMemoryInvocationStore,
  createMemoryUcanDelegationStore,
  createOracleInitFlowTemplate,
  createRuntimeStateManager,
  createUcanDelegationStore,
  createUcanService,
  decompileToBaseUcanFlow,
  evaluateFlowAgentPolicy,
  executeNode,
  executeQueuedAgentCommands,
  findFailedListenersForSourceRun,
  getAction,
  getActionByCan,
  getActionForBlock,
  getActiveEditor,
  getAllActions,
  getAllCanMappings,
  getFlowAgentMaps,
  getOrCreateBlockPendingMap,
  getPendingInvocationsMap,
  hasAction,
  isAuthorized,
  isCapabilityMatch,
  isExternalMutation,
  isRuntimeRef,
  mergeCompiledFlows,
  oracleInitSurveySchema,
  planRalphLoopCommands,
  queueAgentCommand,
  queuePendingInvocation,
  readAgentLedgerEvents,
  readCompiledFlowFromYDoc,
  readFlow,
  readFlowAsBaseUcan,
  readFlowFromEditor,
  readPendingInvocations,
  readQueuedAgentCommands,
  readRunRecords,
  reconcilePendingInvocations,
  registerAction,
  releaseFlowAgentLease,
  removePendingInvocation,
  replayFailedListenerRun,
  requiredCapabilityForCommand,
  resolveRuntimeRefs,
  resourceMatches,
  setActiveEditor,
  setupFlowFromBaseUcan,
  snapshotInputRefs,
  snapshotNode,
  tickFlowAgent,
  typeToCan,
  updateAgentCommand,
  validateAgentCommand,
  validateFlowAgentLease,
  writeRunRecordAndReconcile
};
//# sourceMappingURL=index.mjs.map