{"version":3,"file":"profile-command.mjs","names":[],"sources":["../../../src/commands/profile-command.ts"],"sourcesContent":["/**\n * /profile — Graduated autonomy profiles.\n *\n * Usage:\n *   /profile                    — show current profile + list available\n *   /profile <name>             — activate a profile (supervised|training|autonomous|custom)\n *   /profile off                — deactivate profile, revert to supervised\n *\n * Profiles are preset delegation configurations:\n *   supervised  — all actions require wallet approval (default)\n *   training    — $50/tx, $200/day, 10 actions/day, 24h expiry\n *   autonomous  — $500/tx, $2k/week, 50 actions/day, 30d expiry\n *   custom      — user-defined policies (no preset rules)\n */\n\nimport {\n  listProfiles,\n  getProfile,\n  getActiveProfile,\n  activateProfile,\n  deactivateProfile,\n  formatProfileDisplay,\n  type ProfileId,\n} from '../services/autonomy-profiles.js';\nimport { getPolicyMode, isDelegationMode } from '../services/policy-types.js';\nimport {\n  prepareDelegation,\n  signDelegation,\n  storeDelegation,\n} from '../services/delegation-service.js';\n\nconst VALID_PROFILES = new Set(['supervised', 'training', 'autonomous', 'custom']);\n\nexport const profileCommand = {\n  name: 'profile',\n  description: 'Autonomy profile: /profile [supervised|training|autonomous|custom|off]',\n  acceptsArgs: true,\n  requireAuth: true,\n\n  handler: async (ctx?: any) => {\n    const args = (ctx?.args ?? '').trim().toLowerCase();\n    const userId = ctx?.senderId ?? ctx?.userId ?? 'default';\n\n    // No args: show current profile + list\n    if (!args) {\n      return showProfiles(userId);\n    }\n\n    // Deactivate\n    if (args === 'off' || args === 'reset' || args === 'none') {\n      return handleDeactivate(userId);\n    }\n\n    // Activate a profile\n    if (VALID_PROFILES.has(args)) {\n      return handleActivate(userId, args as ProfileId);\n    }\n\n    return {\n      text: [\n        'Unknown profile. Available profiles:',\n        '',\n        '  `/profile supervised` — all actions need wallet approval',\n        '  `/profile training` — small limits, 24h expiry',\n        '  `/profile autonomous` — production limits, 30d expiry',\n        '  `/profile custom` — define your own rules',\n        '  `/profile off` — deactivate and revert to supervised',\n        '',\n        'Use `/profile` with no args to see details.',\n      ].join('\\n'),\n    };\n  },\n};\n\nfunction showProfiles(userId: string) {\n  const activeId = getActiveProfile(userId);\n  const profiles = listProfiles();\n  const mode = getPolicyMode();\n  const modeLabel = mode === 'delegation' ? 'delegation (on-chain)' : 'simple (app-layer)';\n\n  const lines: string[] = [];\n  lines.push('**Autonomy Profiles**');\n  lines.push(`Policy mode: ${modeLabel}`);\n  lines.push('');\n\n  for (const p of profiles) {\n    const isActive = p.id === activeId;\n    lines.push(formatProfileDisplay(p, isActive));\n    lines.push('');\n  }\n\n  lines.push('---');\n  lines.push('Activate: `/profile <name>` — Deactivate: `/profile off`');\n\n  if (isDelegationMode()) {\n    lines.push('Delegations are auto-signed when you activate a profile.');\n  }\n\n  return { text: lines.join('\\n') };\n}\n\nasync function handleActivate(userId: string, profileId: ProfileId) {\n  const lines: string[] = [];\n\n  try {\n    const { profile, policies } = activateProfile(userId, profileId);\n\n    lines.push(`**Profile activated: ${profile.name}**`);\n    lines.push('');\n\n    for (const s of profile.summary) {\n      lines.push(`  ${s}`);\n    }\n\n    if (policies.length > 0) {\n      lines.push('');\n      lines.push(`Created ${policies.length} polic${policies.length === 1 ? 'y' : 'ies'} from template.`);\n\n      // Auto-create and sign delegations when in delegation mode\n      if (isDelegationMode()) {\n        const delegationResults = await autoDelegateForPolicies(policies, userId);\n        if (delegationResults.signed > 0) {\n          lines.push('');\n          lines.push(`Signed ${delegationResults.signed} on-chain delegation${delegationResults.signed === 1 ? '' : 's'} automatically.`);\n          for (const detail of delegationResults.details) {\n            lines.push(`  ${detail}`);\n          }\n        }\n        if (delegationResults.failed > 0) {\n          lines.push('');\n          lines.push(`Failed to sign ${delegationResults.failed} delegation${delegationResults.failed === 1 ? '' : 's'}:`);\n          for (const err of delegationResults.errors) {\n            lines.push(`  ${err}`);\n          }\n          lines.push('You can retry manually with `/delegate create <policy-name>`.');\n        }\n      }\n    }\n\n    if (profileId === 'supervised') {\n      lines.push('');\n      lines.push('No policies created. All actions require wallet approval.');\n    }\n\n    if (profileId === 'custom') {\n      lines.push('');\n      lines.push('Use natural language to create policies:');\n      lines.push('  \"Never spend more than $500/day on swaps\"');\n      lines.push('  \"Only interact with Uniswap and Aave\"');\n    }\n  } catch (err: any) {\n    lines.push(`Failed to activate profile: ${err.message}`);\n  }\n\n  return { text: lines.join('\\n') };\n}\n\n// ─── Auto-Delegation Helper ─────────────────────────────────────────────\n\ninterface AutoDelegationResults {\n  signed: number;\n  failed: number;\n  details: string[];\n  errors: string[];\n}\n\n/**\n * Auto-create and sign delegations for newly created profile policies.\n * Calls prepareDelegation → signDelegation → storeDelegation for each policy.\n * Non-throwing: captures errors per-policy so partial success is reported.\n */\nasync function autoDelegateForPolicies(\n  policies: import('../services/policy-types.js').Policy[],\n  userId: string,\n): Promise<AutoDelegationResults> {\n  const results: AutoDelegationResults = { signed: 0, failed: 0, details: [], errors: [] };\n\n  for (const policy of policies) {\n    try {\n      // Step 1: Compile policy to delegation\n      const prepResult = await prepareDelegation({ policy });\n      if ('error' in prepResult) {\n        results.failed++;\n        results.errors.push(`${policy.name}: ${prepResult.error}`);\n        continue;\n      }\n\n      const { compilation, chainId } = prepResult;\n\n      // Step 2: Sign the delegation\n      const signResult = await signDelegation(compilation.delegation, chainId);\n      if ('error' in signResult) {\n        results.failed++;\n        results.errors.push(`${policy.name}: ${signResult.error}`);\n        continue;\n      }\n\n      // Step 3: Store the signed delegation\n      const unmappedRules = compilation.unmappedRules.map(r => r.rule.type);\n      await storeDelegation(policy, userId, signResult.signed, chainId, unmappedRules);\n\n      results.signed++;\n      results.details.push(`${policy.name} — chain ${chainId}, ${compilation.mappedRules.length} caveat${compilation.mappedRules.length === 1 ? '' : 's'}`);\n    } catch (err: any) {\n      results.failed++;\n      results.errors.push(`${policy.name}: ${err.message}`);\n    }\n  }\n\n  return results;\n}\n\nfunction handleDeactivate(userId: string) {\n  deactivateProfile(userId);\n\n  return {\n    text: [\n      '**Profile deactivated**',\n      '',\n      'Reverted to supervised mode. All actions require wallet approval.',\n      'Any profile-generated policies have been removed.',\n      '',\n      'Note: existing on-chain delegations are NOT automatically revoked.',\n      'Use `/delegate revoke <name>` to revoke on-chain delegations.',\n    ].join('\\n'),\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+BA,MAAM,iBAAiB,IAAI,IAAI;CAAC;CAAc;CAAY;CAAc;CAAS,CAAC;AAElF,MAAa,iBAAiB;CAC5B,MAAM;CACN,aAAa;CACb,aAAa;CACb,aAAa;CAEb,SAAS,OAAO,QAAc;EAC5B,MAAM,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa;EACnD,MAAM,SAAS,KAAK,YAAY,KAAK,UAAU;AAG/C,MAAI,CAAC,KACH,QAAO,aAAa,OAAO;AAI7B,MAAI,SAAS,SAAS,SAAS,WAAW,SAAS,OACjD,QAAO,iBAAiB,OAAO;AAIjC,MAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,QAAQ,KAAkB;AAGlD,SAAO,EACL,MAAM;GACJ;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK,EACb;;CAEJ;AAED,SAAS,aAAa,QAAgB;CACpC,MAAM,WAAW,iBAAiB,OAAO;CACzC,MAAM,WAAW,cAAc;CAE/B,MAAM,YADO,eAAe,KACD,eAAe,0BAA0B;CAEpE,MAAM,QAAkB,EAAE;AAC1B,OAAM,KAAK,wBAAwB;AACnC,OAAM,KAAK,gBAAgB,YAAY;AACvC,OAAM,KAAK,GAAG;AAEd,MAAK,MAAM,KAAK,UAAU;EACxB,MAAM,WAAW,EAAE,OAAO;AAC1B,QAAM,KAAK,qBAAqB,GAAG,SAAS,CAAC;AAC7C,QAAM,KAAK,GAAG;;AAGhB,OAAM,KAAK,MAAM;AACjB,OAAM,KAAK,2DAA2D;AAEtE,KAAI,kBAAkB,CACpB,OAAM,KAAK,2DAA2D;AAGxE,QAAO,EAAE,MAAM,MAAM,KAAK,KAAK,EAAE;;AAGnC,eAAe,eAAe,QAAgB,WAAsB;CAClE,M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