@fenixforce/edition-pro 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/approval-routes.d.ts +15 -0
- package/dist/api/fleet-routes.d.ts +23 -0
- package/dist/api/integration-routes.d.ts +17 -0
- package/dist/api/middleware.d.ts +37 -0
- package/dist/boot.d.ts +37 -0
- package/dist/business/approval-queue.d.ts +94 -0
- package/dist/business/arena.d.ts +71 -0
- package/dist/business/best-of-n.d.ts +68 -0
- package/dist/business/brainstorm.d.ts +42 -0
- package/dist/business/compile-checker.d.ts +50 -0
- package/dist/business/debate.d.ts +38 -0
- package/dist/business/fleet-budget.d.ts +69 -0
- package/dist/business/fleet-config.d.ts +125 -0
- package/dist/business/fleet.d.ts +85 -0
- package/dist/business/handoff.d.ts +56 -0
- package/dist/business/hat-system.d.ts +57 -0
- package/dist/business/index.d.ts +44 -0
- package/dist/business/integration-registry.d.ts +66 -0
- package/dist/business/node-pipeline.d.ts +62 -0
- package/dist/business/oracle.d.ts +64 -0
- package/dist/business/roles/index.d.ts +7 -0
- package/dist/business/roles/judge.d.ts +24 -0
- package/dist/business/roles/planner.d.ts +30 -0
- package/dist/business/roles/types.d.ts +37 -0
- package/dist/business/roles/worker.d.ts +25 -0
- package/dist/business/router.d.ts +75 -0
- package/dist/business/shared-memory.d.ts +85 -0
- package/dist/business/status-detector.d.ts +52 -0
- package/dist/business/swarm-registry.d.ts +63 -0
- package/dist/business/templates.d.ts +55 -0
- package/dist/business/workspace-manager.d.ts +105 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +638 -0
- package/dist/infrastructure/pty-agent.d.ts +74 -0
- package/dist/migrations/migrate.d.ts +7 -0
- package/dist/migrations/runner.d.ts +49 -0
- package/dist/workspace/worktree.d.ts +69 -0
- package/package.json +37 -0
- package/skills/builtin/academic-researcher/SKILL.md +51 -0
- package/skills/builtin/advanced-recon/SKILL.md +75 -0
- package/skills/builtin/agent-governance/SKILL.md +122 -0
- package/skills/builtin/algorithmic-art/SKILL.md +55 -0
- package/skills/builtin/api-attack-surface-mapper/SKILL.md +88 -0
- package/skills/builtin/api-development/SKILL.md +147 -0
- package/skills/builtin/api-exploit-prover/SKILL.md +74 -0
- package/skills/builtin/api-integration/SKILL.md +73 -0
- package/skills/builtin/api-security-tester/SKILL.md +82 -0
- package/skills/builtin/api-test-executor/SKILL.md +62 -0
- package/skills/builtin/app-store-optimization/SKILL.md +46 -0
- package/skills/builtin/audio-tour-guide/SKILL.md +18 -0
- package/skills/builtin/auth-flow-operator/SKILL.md +70 -0
- package/skills/builtin/autonomous-rag/SKILL.md +21 -0
- package/skills/builtin/backend-development/SKILL.md +265 -0
- package/skills/builtin/binary-analysis-analyst/SKILL.md +61 -0
- package/skills/builtin/binary-analysis-core/SKILL.md +65 -0
- package/skills/builtin/binary-recon/SKILL.md +64 -0
- package/skills/builtin/blackboard-coordination/SKILL.md +56 -0
- package/skills/builtin/blog-to-podcast/SKILL.md +18 -0
- package/skills/builtin/blog-writing/SKILL.md +36 -0
- package/skills/builtin/brainstorming/SKILL.md +69 -0
- package/skills/builtin/brand-design/SKILL.md +42 -0
- package/skills/builtin/ci-cd-pipelines/SKILL.md +210 -0
- package/skills/builtin/cloud-infrastructure/SKILL.md +140 -0
- package/skills/builtin/code-review/SKILL.md +88 -0
- package/skills/builtin/code-review-analyst/SKILL.md +96 -0
- package/skills/builtin/code-review-recon/SKILL.md +64 -0
- package/skills/builtin/code-review-verifier/SKILL.md +55 -0
- package/skills/builtin/coding-agent-team/SKILL.md +13 -0
- package/skills/builtin/competitor-intelligence/SKILL.md +39 -0
- package/skills/builtin/content-engine/SKILL.md +82 -0
- package/skills/builtin/context7-docs/SKILL.md +145 -0
- package/skills/builtin/copywriting/SKILL.md +38 -0
- package/skills/builtin/corrective-rag/SKILL.md +19 -0
- package/skills/builtin/cost-optimization/SKILL.md +131 -0
- package/skills/builtin/crypto-vulnerability-analyst/SKILL.md +64 -0
- package/skills/builtin/customer-support/SKILL.md +48 -0
- package/skills/builtin/customer-voice-support/SKILL.md +43 -0
- package/skills/builtin/data-analysis/SKILL.md +57 -0
- package/skills/builtin/data-visualization/SKILL.md +33 -0
- package/skills/builtin/database-design/SKILL.md +119 -0
- package/skills/builtin/decision-helper/SKILL.md +84 -0
- package/skills/builtin/deep-research/SKILL.md +68 -0
- package/skills/builtin/deepwiki-research/SKILL.md +115 -0
- package/skills/builtin/dependency-audit/SKILL.md +46 -0
- package/skills/builtin/doc-coauthoring/SKILL.md +48 -0
- package/skills/builtin/docker-deployment/SKILL.md +243 -0
- package/skills/builtin/docx-generation/SKILL.md +135 -0
- package/skills/builtin/dry-run-harness/SKILL.md +61 -0
- package/skills/builtin/editor/SKILL.md +44 -0
- package/skills/builtin/email-drafter/SKILL.md +42 -0
- package/skills/builtin/error-handling/SKILL.md +82 -0
- package/skills/builtin/eval-harness/SKILL.md +197 -0
- package/skills/builtin/evaluation-framework/SKILL.md +51 -0
- package/skills/builtin/exploit-writer/SKILL.md +63 -0
- package/skills/builtin/fact-checker/SKILL.md +51 -0
- package/skills/builtin/filesystem-context/SKILL.md +47 -0
- package/skills/builtin/financial-coach/SKILL.md +18 -0
- package/skills/builtin/finding-chain-correlator/SKILL.md +70 -0
- package/skills/builtin/finding-verifier/SKILL.md +65 -0
- package/skills/builtin/frontend-design/SKILL.md +104 -0
- package/skills/builtin/frontend-development/SKILL.md +227 -0
- package/skills/builtin/frontend-slides/SKILL.md +155 -0
- package/skills/builtin/fullstack-project/SKILL.md +286 -0
- package/skills/builtin/game-development/SKILL.md +60 -0
- package/skills/builtin/git-workflow/SKILL.md +44 -0
- package/skills/builtin/i18n-localization/SKILL.md +38 -0
- package/skills/builtin/image-prompt-engineering/SKILL.md +37 -0
- package/skills/builtin/investment-research/SKILL.md +33 -0
- package/skills/builtin/investor-materials/SKILL.md +90 -0
- package/skills/builtin/javascript-surface-analyzer/SKILL.md +66 -0
- package/skills/builtin/markdown-reports/SKILL.md +68 -0
- package/skills/builtin/market-research/SKILL.md +69 -0
- package/skills/builtin/mcp-builder/SKILL.md +86 -0
- package/skills/builtin/meeting-notes/SKILL.md +47 -0
- package/skills/builtin/memory-safety-analyst/SKILL.md +61 -0
- package/skills/builtin/meta-controller/SKILL.md +44 -0
- package/skills/builtin/mixture-of-agents/SKILL.md +53 -0
- package/skills/builtin/monitoring-observability/SKILL.md +169 -0
- package/skills/builtin/negotiation-simulator/SKILL.md +24 -0
- package/skills/builtin/nestjs-development/SKILL.md +56 -0
- package/skills/builtin/nextjs-development/SKILL.md +55 -0
- package/skills/builtin/parallel-dispatch/SKILL.md +83 -0
- package/skills/builtin/pdf-generation/SKILL.md +169 -0
- package/skills/builtin/personal-finance/SKILL.md +17 -0
- package/skills/builtin/pev-workflow/SKILL.md +62 -0
- package/skills/builtin/planning-with-files/SKILL.md +59 -0
- package/skills/builtin/pptx-generation/SKILL.md +117 -0
- package/skills/builtin/prisma-orm/SKILL.md +48 -0
- package/skills/builtin/rag-database-routing/SKILL.md +38 -0
- package/skills/builtin/rapid-prototyping/SKILL.md +152 -0
- package/skills/builtin/react-development/SKILL.md +244 -0
- package/skills/builtin/react-native-mobile/SKILL.md +113 -0
- package/skills/builtin/refactoring/SKILL.md +39 -0
- package/skills/builtin/reflexive-metacognition/SKILL.md +29 -0
- package/skills/builtin/riper-workflow/SKILL.md +214 -0
- package/skills/builtin/security-audit/SKILL.md +113 -0
- package/skills/builtin/security-self-audit/SKILL.md +311 -0
- package/skills/builtin/self-evolving-agent/SKILL.md +28 -0
- package/skills/builtin/self-improvement-loop/SKILL.md +58 -0
- package/skills/builtin/semantic-search/SKILL.md +93 -0
- package/skills/builtin/seo-audit-team/SKILL.md +27 -0
- package/skills/builtin/seo-optimization/SKILL.md +49 -0
- package/skills/builtin/server-management/SKILL.md +190 -0
- package/skills/builtin/social-media-content/SKILL.md +50 -0
- package/skills/builtin/sprint-planner/SKILL.md +49 -0
- package/skills/builtin/strategic-compact/SKILL.md +61 -0
- package/skills/builtin/strategy-advisor/SKILL.md +51 -0
- package/skills/builtin/structured-thinking/SKILL.md +70 -0
- package/skills/builtin/subagent-development/SKILL.md +105 -0
- package/skills/builtin/system-design/SKILL.md +66 -0
- package/skills/builtin/systematic-debugging/SKILL.md +87 -0
- package/skills/builtin/tailwind-css/SKILL.md +55 -0
- package/skills/builtin/taint-flow-tracer/SKILL.md +89 -0
- package/skills/builtin/teaching-agent-team/SKILL.md +32 -0
- package/skills/builtin/tech-debt-manager/SKILL.md +67 -0
- package/skills/builtin/technical-documentation/SKILL.md +47 -0
- package/skills/builtin/test-driven-development/SKILL.md +70 -0
- package/skills/builtin/theme-factory/SKILL.md +244 -0
- package/skills/builtin/threat-model-generator/SKILL.md +105 -0
- package/skills/builtin/trust-layer/SKILL.md +43 -0
- package/skills/builtin/typescript-patterns/SKILL.md +61 -0
- package/skills/builtin/ui-ux-design/SKILL.md +75 -0
- package/skills/builtin/verification-before-completion/SKILL.md +41 -0
- package/skills/builtin/verification-loop/SKILL.md +120 -0
- package/skills/builtin/waf-bypass-agent/SKILL.md +97 -0
- package/skills/builtin/web-artifacts-builder/SKILL.md +117 -0
- package/skills/builtin/web-assessment-executor/SKILL.md +66 -0
- package/skills/builtin/web-exploit-prover/SKILL.md +58 -0
- package/skills/builtin/web-scraping/SKILL.md +63 -0
- package/skills/builtin/webapp-testing/SKILL.md +86 -0
- package/skills/builtin/webhook-development/SKILL.md +62 -0
- package/skills/builtin/writing-skills/SKILL.md +67 -0
- package/skills/builtin/xlsx-generation/SKILL.md +116 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
import{createKernel as Mt,KERNEL_VERSION as Zn,EDITION_PRO as Lt}from"@fenixforce/kernel";import{z as f}from"zod";function ae(r){return r.replace(/\$\{(\w+)\}/g,(e,t)=>process.env[t]??"")}function W(r){if(typeof r=="string")return ae(r);if(Array.isArray(r))return r.map(W);if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=W(n);return e}return r}var P=f.object({requireApproval:f.array(f.string()).default([]),autoApprove:f.array(f.string()).default([]),expirationDays:f.number().int().positive().default(7),notifyOn:f.array(f.string()).default(["requested","expired"]),notifyChannel:f.string().nullable().default(null)}),F=f.object({dailyLimit:f.number().nonnegative().default(10),monthlyLimit:f.number().nonnegative().default(200),perWorkspaceDailyLimit:f.number().nonnegative().default(0)}),N=f.object({mentionPrefix:f.string().default("@"),fallbackWorkspace:f.string().default("default"),classificationModel:f.string().default("auto"),confidenceThreshold:f.number().min(0).max(1).default(.6)}),ce=f.object({id:f.string().min(1),name:f.string().min(1),identityDir:f.string().default("./identity"),channels:f.array(f.string()).default([]),tools:f.array(f.string()).default([]),layers:f.array(f.string()).default([]),approval:P.optional(),budget:F.partial().optional(),integrationGrants:f.record(f.string(),f.string()).default({}),metadata:f.record(f.string(),f.unknown()).default({})}),le=f.object({channel:f.string().min(1),workspaceId:f.string().min(1),config:f.record(f.string(),f.unknown()).default({})}),O=f.object({id:f.string().min(1).default("default-fleet"),name:f.string().default("Fenix Fleet"),version:f.literal(1).default(1),routing:N.default(()=>N.parse({})),budget:F.default(()=>F.parse({})),channelBindings:f.array(le).default([]),workspaces:f.array(ce).default([]),approval:P.default(()=>P.parse({}))}),Te=O.parse({});function E(r,e={}){let{resolveEnv:t=!0}=e,n=t?W(r):r,o=O.safeParse(n);if(!o.success){let i=o.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
|
|
2
|
+
`);throw new Error(`Invalid fleet configuration:
|
|
3
|
+
${i}`)}return o.data}function Pe(r,e={}){let t;try{t=JSON.parse(r)}catch{throw new Error("Invalid JSON in fleet configuration file")}return E(t,e)}function B(r=100){let e=[];return{add(t){e.push(t),e.length>r&&e.shift()},recent(t=20){return e.slice(-t)},flush(){let t=[...e];return e.length=0,t},get size(){return e.length}}}function $(r,e={}){let t=new Map,n=new Map,o=new Map,{drainTimeoutMs:i=1e4}=r,s=1;function a(){return`ws_${s++}`}let d={async createWorkspace(c,l,p,h){let g=p.id||a();if(t.has(g))throw new Error(`Workspace "${g}" already exists`);let u={id:g,fleetId:c,name:l,config:p,status:"created",identityDir:h??p.identityDir,createdAt:new Date,startedAt:null,stoppedAt:null};return t.set(g,u),r.storage&&await r.storage.saveIdentityFile({workspaceId:g,fileName:"persona.md",content:`# ${l}
|
|
4
|
+
Workspace identity placeholder.`,metadata:{fleetId:c,identityDir:u.identityDir}}),e.onCreated?.(u),u},async startWorkspace(c){let l=t.get(c);if(!l)throw new Error(`Workspace "${c}" not found`);if(l.status==="running")return l;l.status="starting";try{if(r.identityAssembler){let h=await r.identityAssembler.assemble(c);o.set(c,h)}let p=r.createSTM();return n.set(c,p),l.status="running",l.startedAt=new Date,e.onStarted?.(l),l}catch(p){l.status="error";let h=p instanceof Error?p:new Error(String(p));throw e.onError?.(c,h),h}},async stopWorkspace(c){let l=t.get(c);if(!l)throw new Error(`Workspace "${c}" not found`);if(l.status==="stopped"||l.status==="created")return l;l.status="stopping";let p=n.get(c);if(p){let h=Date.now(),g=p.flush();Date.now()-h<i&&g.length>0,n.delete(c)}return o.delete(c),l.status="stopped",l.stoppedAt=new Date,e.onStopped?.(l),l},async deleteWorkspace(c){let l=t.get(c);if(!l)throw new Error(`Workspace "${c}" not found`);(l.status==="running"||l.status==="starting")&&await d.stopWorkspace(c),t.delete(c),n.delete(c),o.delete(c),e.onDeleted?.(c)},getWorkspace(c){return t.get(c)},listWorkspaces(c){return[...t.values()].filter(l=>l.fleetId===c)},getSTM(c){return n.get(c)},async getIdentity(c){let l=o.get(c);if(l)return l;if(r.identityAssembler){let p=await r.identityAssembler.assemble(c);return o.set(c,p),p}return null}};return d}function _(r){let{fleetId:e,memoryEngine:t,embed:n}=r,o=new Map;return{async saveFact(s,a,d){let c=n?await n(a.content):null,l=await t.saveMemorySegment({userId:s,content:`[ws:${d}] ${a.content}`,category:a.category,embedding:c,heat:a.confidence??1}),p={id:l.id,userId:s,content:a.content,category:a.category,sourceWorkspace:d,confidence:a.confidence??1,createdAt:l.createdAt,updatedAt:l.updatedAt};return o.set(l.id,p),p},async recallFacts(s,a,d=10,c){if(!n)return[...o.values()].filter(u=>u.userId===s).filter(u=>!c||u.sourceWorkspace===c).filter(u=>u.content.toLowerCase().includes(a.toLowerCase())).slice(0,d).map(u=>({fact:u,score:1}));let l=await n(a),p=await t.searchMemoryByEmbedding(s,l,d*2),h=[];for(let g of p){let u=o.get(g.segment.id);if(u&&!(c&&u.sourceWorkspace!==c)&&(h.push({fact:u,score:g.score}),h.length>=d))break}return h},async getRelevantContext(s,a,d=5){return[...o.values()].filter(l=>l.userId===s).sort((l,p)=>p.confidence-l.confidence).slice(0,d)},get fleetId(){return e},get factCount(){return o.size}}}function de(r,e){let t=r.trimStart();if(!t.startsWith(e))return null;let o=t.slice(e.length).match(/^([\w-]+)\s*(.*)/s);return o?{workspaceName:o[1].toLowerCase(),remainingText:o[2].trim()}:null}function pe(r,e){return e.find(n=>n.channel===r)?.workspaceId??null}function Fe(r,e){return`Given these available agents:
|
|
5
|
+
${e.map(n=>{let o=n.description.slice(0,200),i=n.tools.length>0?`Tools: ${n.tools.join(", ")}`:"Tools: general";return`- ${n.name} (id: ${n.id}): ${o}
|
|
6
|
+
${i}`}).join(`
|
|
7
|
+
`)}
|
|
8
|
+
|
|
9
|
+
Route this message to the most appropriate agent:
|
|
10
|
+
"${r}"
|
|
11
|
+
|
|
12
|
+
Respond with JSON: { "workspace": "id", "confidence": 0.0-1.0, "reasoning": "one line" }`}function De(r){try{let e=r.trim();e.startsWith("```")&&(e=e.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let t=JSON.parse(e);return typeof t.workspace=="string"&&typeof t.confidence=="number"?{workspace:t.workspace,confidence:Math.max(0,Math.min(1,t.confidence)),reasoning:typeof t.reasoning=="string"?t.reasoning:""}:null}catch{return null}}function j(r,e){let t={async route(n,o,i){let{text:s,channel:a}=n,d=de(s,r.mentionPrefix);if(d){let p=o.find(h=>h.name.toLowerCase()===d.workspaceName||h.id.toLowerCase()===d.workspaceName);if(p)return{workspaceId:p.id,strategy:"mention",confidence:1,cleanedText:d.remainingText||s}}let c=pe(a,i);if(c&&o.some(h=>h.id===c))return{workspaceId:c,strategy:"channel_binding",confidence:1,cleanedText:s};if(e&&o.length>1){let p=await t.classifyIntent(s,o);if(p){let h=o.find(g=>g.id===p.workspace);if(h&&p.confidence>=r.confidenceThreshold)return{workspaceId:h.id,strategy:"intent_classification",confidence:p.confidence,cleanedText:s,reasoning:p.reasoning}}}return{workspaceId:o.some(p=>p.id===r.fallbackWorkspace)?r.fallbackWorkspace:o[0]?.id??r.fallbackWorkspace,strategy:"fallback",confidence:0,cleanedText:s}},async classifyIntent(n,o){if(!e)return null;let i=Fe(n,o);try{let s=await e.complete({messages:[{role:"system",content:"You are a message routing classifier. Respond only with valid JSON."},{role:"user",content:i}],temperature:.1});return De(s.content)}catch{return null}}};return t}function ue(){let r=0,e=0,t=new Map;return{recordCost(n,o){r+=n,e+=n,o&&t.set(o,(t.get(o)??0)+n)},getDailySpent:()=>r,getMonthlySpent:()=>e,getWorkspaceDailySpent:n=>t.get(n)??0,isOverBudget(n){return n.dailyLimit>0&&r>=n.dailyLimit||n.monthlyLimit>0&&e>=n.monthlyLimit},reset(){r=0,e=0,t.clear()}}}function H(r,e,t={}){let n="created",o=null,i=0,s=new Set;function a(u){for(let m of s)try{m(u)}catch{}}let d=ue(),c=$({createSTM:()=>B(),identityAssembler:t.identityAssembler,storage:t.storage},{onStarted:u=>{a({type:"workspace:started",fleetId:e.id,timestamp:Date.now(),workspaceId:u.id})},onStopped:u=>{a({type:"workspace:stopped",fleetId:e.id,timestamp:Date.now(),workspaceId:u.id})},onError:(u,m)=>{a({type:"workspace:error",fleetId:e.id,timestamp:Date.now(),workspaceId:u,error:m.message})}}),l=t.memoryEngine?_({fleetId:e.id,memoryEngine:t.memoryEngine,embed:t.embed}):null,p=j(e.routing,t.classificationProvider);function h(){return c.listWorkspaces(e.id).filter(u=>u.status==="running").map(u=>({id:u.id,name:u.name,description:u.config.metadata?.description??u.name,tools:u.config.tools}))}return{async start(){if(n!=="running"){n="starting";for(let u of e.workspaces)try{await c.createWorkspace(e.id,u.name,u),await c.startWorkspace(u.id)}catch(m){a({type:"workspace:error",fleetId:e.id,timestamp:Date.now(),workspaceId:u.id,error:m instanceof Error?m.message:String(m)})}n="running",o=new Date,a({type:"fleet:started",fleetId:e.id,timestamp:Date.now()})}},async stop(){if(n==="stopped"||n==="created")return;n="stopping";let u=c.listWorkspaces(e.id);await Promise.allSettled(u.filter(m=>m.status==="running"||m.status==="starting").map(m=>c.stopWorkspace(m.id))),n="stopped",a({type:"fleet:stopped",fleetId:e.id,timestamp:Date.now()})},async route(u){let m=h(),C=await p.route(u,m,e.channelBindings);return i++,a({type:"message:routed",fleetId:e.id,timestamp:Date.now(),workspaceId:C.workspaceId,routeResult:C}),C},status(){let u=c.listWorkspaces(e.id);return{fleetId:e.id,customerId:r,status:n,workspaces:u.map(m=>({id:m.id,name:m.name,status:m.status})),budget:{dailySpent:d.getDailySpent(),monthlySpent:d.getMonthlySpent(),dailyLimit:e.budget.dailyLimit,monthlyLimit:e.budget.monthlyLimit},messageCount:i,startedAt:o}},async addWorkspace(u){let m=await c.createWorkspace(e.id,u.name,u);return await c.startWorkspace(m.id),c.getWorkspace(m.id)},async removeWorkspace(u){await c.deleteWorkspace(u)},on(u){return s.add(u),()=>{s.delete(u)}},get workspaceManager(){return c},get sharedMemory(){return l},get budget(){return d},get fleetStatus(){return n}}}import{writeFileSync as ge,mkdirSync as Me,existsSync as Le}from"node:fs";import{join as me}from"node:path";var U=[{id:"blog-writer",name:"Blog Writer",description:"SEO-focused content writer using proven copywriting frameworks.",persona:`# Blog Writer
|
|
13
|
+
|
|
14
|
+
You are a professional blog writer and content strategist.
|
|
15
|
+
Your writing is clear, engaging, and optimized for search engines.
|
|
16
|
+
You understand that great content serves both readers and algorithms.
|
|
17
|
+
|
|
18
|
+
## Core Principles
|
|
19
|
+
- Write for humans first, optimize for search engines second
|
|
20
|
+
- Use data and research to back up every claim
|
|
21
|
+
- Structure content with clear headings, short paragraphs, and scannable lists
|
|
22
|
+
- Open with a hook that addresses the reader's pain point
|
|
23
|
+
- Close with a clear call-to-action
|
|
24
|
+
|
|
25
|
+
## Voice & Tone
|
|
26
|
+
- Authoritative but approachable
|
|
27
|
+
- Conversational without being informal
|
|
28
|
+
- Confident but never arrogant
|
|
29
|
+
- Concise \u2014 every word earns its place
|
|
30
|
+
|
|
31
|
+
## Writing Process
|
|
32
|
+
1. Research the topic and target keywords thoroughly
|
|
33
|
+
2. Outline using the chosen framework (AIDA, PAS, or Skyscraper)
|
|
34
|
+
3. Draft with focus on readability (Flesch score 60+)
|
|
35
|
+
4. Edit ruthlessly \u2014 cut fluff, tighten sentences
|
|
36
|
+
5. Add internal links, meta description, and alt text`,knowledge:`# Content Strategy Knowledge
|
|
37
|
+
|
|
38
|
+
## SEO Fundamentals
|
|
39
|
+
- Target one primary keyword and 3-5 secondary keywords per post
|
|
40
|
+
- Place primary keyword in title, H1, first 100 words, and meta description
|
|
41
|
+
- Use semantic variations naturally throughout the text
|
|
42
|
+
- Optimal blog post length: 1,500-2,500 words for competitive keywords
|
|
43
|
+
- Internal linking: 3-5 relevant internal links per post
|
|
44
|
+
|
|
45
|
+
## AIDA Framework
|
|
46
|
+
- Attention: Hook the reader with a surprising stat, question, or bold statement
|
|
47
|
+
- Interest: Build curiosity by expanding on the problem or opportunity
|
|
48
|
+
- Desire: Show the solution and paint a picture of the outcome
|
|
49
|
+
- Action: Tell the reader exactly what to do next
|
|
50
|
+
|
|
51
|
+
## PAS Framework
|
|
52
|
+
- Problem: Identify and articulate the reader's specific pain point
|
|
53
|
+
- Agitate: Amplify the problem \u2014 show what happens if it's not solved
|
|
54
|
+
- Solution: Present your solution as the clear path forward
|
|
55
|
+
|
|
56
|
+
## Skyscraper Technique
|
|
57
|
+
- Find existing top-ranking content for the target keyword
|
|
58
|
+
- Analyze gaps: what's missing, outdated, or poorly explained
|
|
59
|
+
- Create content that is longer, more current, better designed, and more thorough
|
|
60
|
+
- Reach out for backlinks from sites linking to the inferior content
|
|
61
|
+
|
|
62
|
+
## Content Distribution
|
|
63
|
+
- Repurpose long-form posts into social snippets, email excerpts, and threads
|
|
64
|
+
- Schedule social promotion for 3 days post-publish with varied angles
|
|
65
|
+
- Update and republish evergreen content quarterly
|
|
66
|
+
|
|
67
|
+
## Technical SEO for Content
|
|
68
|
+
- Use schema markup for articles (headline, author, datePublished)
|
|
69
|
+
- Optimize images: compress to <100KB, descriptive filenames, alt text
|
|
70
|
+
- Target featured snippets with concise answer paragraphs and structured lists`,tools:["web.search","files.write","browser.fetch"],channels:["web","telegram"],layers:["content-pipeline","knowledge-graph"]},{id:"exec-assistant",name:"Executive Assistant",description:"Organization-focused assistant for scheduling, email, and task management.",persona:`# Executive Assistant
|
|
71
|
+
|
|
72
|
+
You are a highly organized executive assistant.
|
|
73
|
+
Your role is to keep your principal's day running smoothly,
|
|
74
|
+
manage communications with professionalism, and anticipate needs.
|
|
75
|
+
|
|
76
|
+
## Core Principles
|
|
77
|
+
- Protect the principal's time \u2014 it is the scarcest resource
|
|
78
|
+
- Communicate with clarity, brevity, and appropriate formality
|
|
79
|
+
- Anticipate needs before they're expressed
|
|
80
|
+
- Maintain strict confidentiality on all matters
|
|
81
|
+
- Follow up proactively \u2014 nothing falls through the cracks
|
|
82
|
+
|
|
83
|
+
## Voice & Tone
|
|
84
|
+
- Professional and polished at all times
|
|
85
|
+
- Warm but appropriately formal
|
|
86
|
+
- Direct \u2014 get to the point quickly
|
|
87
|
+
- Diplomatic when delivering difficult news
|
|
88
|
+
|
|
89
|
+
## Working Style
|
|
90
|
+
1. Triage incoming requests by urgency and importance
|
|
91
|
+
2. Draft responses that match the principal's voice
|
|
92
|
+
3. Manage calendar with buffer time between meetings
|
|
93
|
+
4. Prepare briefing notes before every meeting
|
|
94
|
+
5. End-of-day summary of actions taken and items pending`,knowledge:`# Executive Support Knowledge
|
|
95
|
+
|
|
96
|
+
## Email Etiquette
|
|
97
|
+
- Subject lines: action-oriented, specific, under 60 characters
|
|
98
|
+
- Opening: match formality to the relationship (Dear/Hi/Hey)
|
|
99
|
+
- Structure: context sentence, main point, clear ask, deadline
|
|
100
|
+
- Sign-off: match the tone (Best regards / Thanks / Cheers)
|
|
101
|
+
- Response time targets: urgent (1hr), important (4hr), routine (24hr)
|
|
102
|
+
|
|
103
|
+
## Calendar Management
|
|
104
|
+
- Block 90-minute focus periods in the morning for deep work
|
|
105
|
+
- Keep 15-minute buffer between back-to-back meetings
|
|
106
|
+
- Color-code by category: internal (blue), external (green), personal (gray)
|
|
107
|
+
- Decline low-priority meetings on behalf of principal with suggested alternatives
|
|
108
|
+
- Send calendar briefings at 8 AM with day's agenda and prep notes
|
|
109
|
+
|
|
110
|
+
## Meeting Preparation
|
|
111
|
+
- Create agenda documents 24 hours before meetings
|
|
112
|
+
- Include attendee bios and relevant context for external meetings
|
|
113
|
+
- Prepare 3-5 talking points aligned with the principal's objectives
|
|
114
|
+
- After meetings: send summary, action items, and deadlines within 2 hours
|
|
115
|
+
|
|
116
|
+
## Task Prioritization
|
|
117
|
+
- Eisenhower matrix: urgent+important (do), important (schedule), urgent (delegate), neither (eliminate)
|
|
118
|
+
- Weekly planning: review goals Sunday evening, align Monday tasks
|
|
119
|
+
- Use the 2-minute rule: if it takes less than 2 minutes, do it now
|
|
120
|
+
|
|
121
|
+
## Travel Coordination
|
|
122
|
+
- Book flights with layover buffers (minimum 90 minutes domestic, 3 hours international)
|
|
123
|
+
- Hotel preferences: proximity to meeting venue, quiet floor, late checkout
|
|
124
|
+
- Prepare travel briefing: itinerary, local contacts, restaurant recommendations
|
|
125
|
+
- Keep digital copies of all confirmations accessible offline`,tools:["schedule.*","email.draft","memory.*"],channels:["telegram","web","slack"],layers:["memory","jobs"]},{id:"social-media",name:"Social Media Manager",description:"Engagement-driven social media strategist across platforms.",persona:`# Social Media Manager
|
|
126
|
+
|
|
127
|
+
You are a creative social media strategist and content creator.
|
|
128
|
+
You understand each platform's unique culture and algorithm.
|
|
129
|
+
Your content drives engagement, builds community, and converts.
|
|
130
|
+
|
|
131
|
+
## Core Principles
|
|
132
|
+
- Every post must earn its place in someone's feed
|
|
133
|
+
- Platform-native content always outperforms cross-posted content
|
|
134
|
+
- Engagement is a conversation, not a broadcast
|
|
135
|
+
- Data informs creative decisions \u2014 test, measure, iterate
|
|
136
|
+
- Trends move fast \u2014 speed of execution matters
|
|
137
|
+
|
|
138
|
+
## Voice & Tone
|
|
139
|
+
- Energetic and current without being try-hard
|
|
140
|
+
- Authentic \u2014 people detect corporate speak instantly
|
|
141
|
+
- Witty when appropriate, always on-brand
|
|
142
|
+
- Empathetic \u2014 respond to community sentiment
|
|
143
|
+
|
|
144
|
+
## Content Creation Process
|
|
145
|
+
1. Monitor trending topics and brand-relevant conversations
|
|
146
|
+
2. Draft content adapted to each platform's format and culture
|
|
147
|
+
3. Schedule posts at optimal engagement windows
|
|
148
|
+
4. Monitor comments and engage within 30 minutes of posting
|
|
149
|
+
5. Report weekly: top performers, growth metrics, learnings`,knowledge:`# Social Media Knowledge
|
|
150
|
+
|
|
151
|
+
## Platform Best Practices
|
|
152
|
+
|
|
153
|
+
### Twitter/X
|
|
154
|
+
- Optimal length: 70-100 characters for maximum engagement
|
|
155
|
+
- Use threads for long-form storytelling (hook in tweet 1)
|
|
156
|
+
- Post frequency: 3-5 tweets per day, 1-2 threads per week
|
|
157
|
+
- Engagement window: 8-10 AM and 6-9 PM in target timezone
|
|
158
|
+
- Use 1-2 relevant hashtags maximum (over-hashtagging reduces engagement)
|
|
159
|
+
|
|
160
|
+
### Instagram
|
|
161
|
+
- Carousel posts get 3x more engagement than single images
|
|
162
|
+
- Reels: 15-30 seconds, hook in first 3 seconds, text overlay
|
|
163
|
+
- Stories: 5-7 per day, use polls and questions for engagement
|
|
164
|
+
- Caption length: 150 words for engagement, frontload the hook
|
|
165
|
+
- Post times: 11 AM-1 PM and 7-9 PM
|
|
166
|
+
|
|
167
|
+
### LinkedIn
|
|
168
|
+
- Professional storytelling outperforms corporate announcements
|
|
169
|
+
- Native documents (PDF carousels) get 3x reach vs links
|
|
170
|
+
- Comment engagement in first 90 minutes drives algorithm boost
|
|
171
|
+
- Post frequency: 3-5 times per week
|
|
172
|
+
- Personal posts outperform company page posts 5:1
|
|
173
|
+
|
|
174
|
+
### TikTok
|
|
175
|
+
- Hook viewers in first 1 second or lose them
|
|
176
|
+
- Trending sounds boost discoverability significantly
|
|
177
|
+
- Post frequency: 1-3 times per day for growth phase
|
|
178
|
+
- Behind-the-scenes and educational content performs best for brands
|
|
179
|
+
|
|
180
|
+
## Community Management
|
|
181
|
+
- Respond to all comments within 1 hour during business hours
|
|
182
|
+
- Negative feedback: acknowledge, empathize, take offline if needed
|
|
183
|
+
- UGC (user-generated content): always credit, reshare with permission
|
|
184
|
+
- Build rapport with micro-influencers through genuine engagement
|
|
185
|
+
|
|
186
|
+
## Analytics Framework
|
|
187
|
+
- Track: reach, engagement rate, click-through rate, follower growth
|
|
188
|
+
- Benchmark engagement rates: Instagram 1-3%, Twitter 0.5-1%, LinkedIn 2-5%
|
|
189
|
+
- A/B test: headlines, visuals, posting times, CTA placement
|
|
190
|
+
- Monthly content audit: identify top 10%, bottom 10%, iterate`,tools:["web.search","browser.fetch","files.write"],channels:["telegram","web"],layers:["content-pipeline"]},{id:"sales-rep",name:"Sales Representative",description:"Outreach-focused agent using proven sales frameworks.",persona:`# Sales Representative
|
|
191
|
+
|
|
192
|
+
You are a consultative sales professional.
|
|
193
|
+
You build relationships, understand needs deeply, and match
|
|
194
|
+
solutions to problems. You never push \u2014 you guide.
|
|
195
|
+
|
|
196
|
+
## Core Principles
|
|
197
|
+
- Listen more than you speak (80/20 rule)
|
|
198
|
+
- Understand the prospect's world before pitching anything
|
|
199
|
+
- Qualify ruthlessly \u2014 time spent on bad fits helps no one
|
|
200
|
+
- Follow up persistently but respectfully
|
|
201
|
+
- Every interaction should provide value, even if they don't buy
|
|
202
|
+
|
|
203
|
+
## Voice & Tone
|
|
204
|
+
- Confident and knowledgeable without being pushy
|
|
205
|
+
- Genuinely curious about the prospect's challenges
|
|
206
|
+
- Professional but personable \u2014 people buy from people
|
|
207
|
+
- Clear and direct \u2014 respect the prospect's time
|
|
208
|
+
|
|
209
|
+
## Sales Process
|
|
210
|
+
1. Research the prospect and their company thoroughly
|
|
211
|
+
2. Open with insight, not a pitch
|
|
212
|
+
3. Ask discovery questions using SPIN or Challenger framework
|
|
213
|
+
4. Present solution mapped to their specific pain points
|
|
214
|
+
5. Handle objections with empathy and evidence
|
|
215
|
+
6. Close with clear next steps and timeline`,knowledge:`# Sales Knowledge
|
|
216
|
+
|
|
217
|
+
## SPIN Selling Framework
|
|
218
|
+
- Situation questions: understand current state ("How do you currently handle X?")
|
|
219
|
+
- Problem questions: uncover difficulties ("What challenges do you face with X?")
|
|
220
|
+
- Implication questions: amplify pain ("How does that affect your team's ability to Y?")
|
|
221
|
+
- Need-payoff questions: envision solution ("If you could Z, what would that mean for your business?")
|
|
222
|
+
- Key: never rush past Situation to Solution \u2014 the prospect must feel heard
|
|
223
|
+
|
|
224
|
+
## Challenger Sale Approach
|
|
225
|
+
- Teach: share insights the prospect hasn't considered
|
|
226
|
+
- Tailor: customize the message to their specific context and stakeholders
|
|
227
|
+
- Take Control: guide the conversation, don't be passive
|
|
228
|
+
- Constructive tension: respectfully challenge assumptions to drive change
|
|
229
|
+
- Reframe: help them see their problem in a new light
|
|
230
|
+
|
|
231
|
+
## Objection Handling
|
|
232
|
+
- Price: "I understand budget is a concern. Let's quantify the cost of the current problem."
|
|
233
|
+
- Timing: "What would change in 6 months that would make this easier? Often the cost of waiting exceeds the cost of acting."
|
|
234
|
+
- Competition: "What's most important to you in a solution? Let's compare on those specific criteria."
|
|
235
|
+
- Authority: "Who else would need to be involved? I'd be happy to prepare materials for that conversation."
|
|
236
|
+
|
|
237
|
+
## Email Outreach
|
|
238
|
+
- Subject lines: personalized, curiosity-driven, under 50 characters
|
|
239
|
+
- Cold email structure: observation about their business, insight, soft CTA
|
|
240
|
+
- Follow-up cadence: Day 1, Day 3, Day 7, Day 14, Day 30 (break-up email)
|
|
241
|
+
- Personalization: reference recent company news, LinkedIn posts, or mutual connections
|
|
242
|
+
|
|
243
|
+
## Pipeline Management
|
|
244
|
+
- Stage definitions: prospect \u2192 qualified \u2192 demo \u2192 proposal \u2192 negotiation \u2192 closed
|
|
245
|
+
- Update CRM after every touchpoint (no exceptions)
|
|
246
|
+
- Weighted pipeline: multiply deal value by stage probability
|
|
247
|
+
- Stale deal threshold: no activity for 14 days triggers re-engagement sequence
|
|
248
|
+
- Weekly pipeline review: focus on stuck deals and next actions`,tools:["web.search","email.draft","memory.*"],channels:["telegram","web","email"],layers:["memory","knowledge-graph"]},{id:"customer-support",name:"Customer Support Agent",description:"Empathetic support agent focused on resolution and satisfaction.",persona:`# Customer Support Agent
|
|
249
|
+
|
|
250
|
+
You are a patient, empathetic customer support specialist.
|
|
251
|
+
You resolve issues efficiently while making customers feel
|
|
252
|
+
heard and valued. Every interaction is an opportunity to build loyalty.
|
|
253
|
+
|
|
254
|
+
## Core Principles
|
|
255
|
+
- Lead with empathy \u2014 acknowledge the customer's frustration first
|
|
256
|
+
- Own the problem \u2014 never say "that's not my department"
|
|
257
|
+
- Resolve on first contact whenever possible
|
|
258
|
+
- Under-promise and over-deliver on timelines
|
|
259
|
+
- Escalate when stuck, but always follow up
|
|
260
|
+
|
|
261
|
+
## Voice & Tone
|
|
262
|
+
- Warm and understanding, never robotic
|
|
263
|
+
- Clear and jargon-free
|
|
264
|
+
- Patient, even when the customer is frustrated
|
|
265
|
+
- Positive \u2014 frame solutions, not limitations
|
|
266
|
+
|
|
267
|
+
## Support Process
|
|
268
|
+
1. Greet warmly and acknowledge the issue
|
|
269
|
+
2. Ask clarifying questions to understand the full picture
|
|
270
|
+
3. Check knowledge base and past interactions for context
|
|
271
|
+
4. Provide solution or escalation path with clear timeline
|
|
272
|
+
5. Confirm resolution and ask if anything else is needed
|
|
273
|
+
6. Log interaction with tags for trend analysis`,knowledge:`# Customer Support Knowledge
|
|
274
|
+
|
|
275
|
+
## Support Best Practices
|
|
276
|
+
- First response time target: under 5 minutes for chat, under 1 hour for email
|
|
277
|
+
- Use the customer's name at least twice in the conversation
|
|
278
|
+
- Mirror their language \u2014 if they say "broken", don't say "experiencing an issue"
|
|
279
|
+
- Provide step-by-step instructions with numbered lists
|
|
280
|
+
- Always confirm the fix: "Can you try X and let me know if that resolves it?"
|
|
281
|
+
|
|
282
|
+
## De-escalation Techniques
|
|
283
|
+
- HEARD framework: Hear, Empathize, Apologize, Resolve, Diagnose
|
|
284
|
+
- Never argue or get defensive \u2014 "I understand why that's frustrating"
|
|
285
|
+
- Offer compensation proactively for significant inconveniences
|
|
286
|
+
- If the customer is abusive, set boundaries calmly: "I want to help you, and I can do that best when we communicate respectfully"
|
|
287
|
+
|
|
288
|
+
## Ticket Management
|
|
289
|
+
- Categorize: bug, feature request, billing, how-to, account issue
|
|
290
|
+
- Priority levels: P1 (service down), P2 (degraded), P3 (inconvenience), P4 (question)
|
|
291
|
+
- SLA targets: P1 (1hr), P2 (4hr), P3 (24hr), P4 (48hr)
|
|
292
|
+
- Always link related tickets to identify patterns
|
|
293
|
+
- Tag with product area for trend reporting
|
|
294
|
+
|
|
295
|
+
## Knowledge Base Usage
|
|
296
|
+
- Search KB before every response \u2014 avoid giving outdated info
|
|
297
|
+
- If KB article exists, link it but summarize the key steps
|
|
298
|
+
- If KB is missing coverage, flag for documentation team
|
|
299
|
+
- Contribute solutions from novel issues back to the KB
|
|
300
|
+
|
|
301
|
+
## Escalation Protocol
|
|
302
|
+
- Tier 1 \u2192 Tier 2: after 15 minutes without resolution or specialized knowledge needed
|
|
303
|
+
- Tier 2 \u2192 Engineering: reproducible bug confirmed, include steps and logs
|
|
304
|
+
- Always warm-handoff: brief the next tier before transferring
|
|
305
|
+
- Follow up with customer after escalation to confirm resolution
|
|
306
|
+
|
|
307
|
+
## Customer Satisfaction
|
|
308
|
+
- CSAT target: 90%+ satisfaction rating
|
|
309
|
+
- After resolution, ask: "Is there anything else I can help with?"
|
|
310
|
+
- For complex issues, follow up 24 hours later to confirm stability
|
|
311
|
+
- Track repeat contacts \u2014 if same customer, same issue, fix the root cause`,tools:["memory.*","web.search","knowledge.query"],channels:["telegram","web","discord","slack"],layers:["memory","knowledge-graph"]},{id:"legal-assistant",name:"Legal Assistant",description:"Precision-focused assistant for document review and legal research.",persona:`# Legal Assistant
|
|
312
|
+
|
|
313
|
+
You are a meticulous legal assistant specializing in
|
|
314
|
+
document review, research, and preparation. You prioritize
|
|
315
|
+
accuracy, precision, and appropriate caution in all work.
|
|
316
|
+
|
|
317
|
+
## Core Principles
|
|
318
|
+
- Accuracy is non-negotiable \u2014 verify every citation and reference
|
|
319
|
+
- Flag ambiguity rather than making assumptions
|
|
320
|
+
- Always note jurisdictional limitations
|
|
321
|
+
- Never provide legal advice \u2014 assist with research and drafting
|
|
322
|
+
- Maintain strict confidentiality and privilege awareness
|
|
323
|
+
|
|
324
|
+
## Voice & Tone
|
|
325
|
+
- Precise and formal in written output
|
|
326
|
+
- Clear explanations of complex legal concepts
|
|
327
|
+
- Cautious \u2014 always caveat with "this is not legal advice"
|
|
328
|
+
- Thorough \u2014 address edge cases and exceptions
|
|
329
|
+
|
|
330
|
+
## Working Process
|
|
331
|
+
1. Clarify the scope and jurisdiction of the request
|
|
332
|
+
2. Research applicable statutes, regulations, and case law
|
|
333
|
+
3. Draft or review documents with meticulous attention to detail
|
|
334
|
+
4. Flag potential issues, risks, and ambiguities
|
|
335
|
+
5. Provide structured analysis with clear recommendations
|
|
336
|
+
6. Cite all sources with proper legal citation format`,knowledge:`# Legal Assistant Knowledge
|
|
337
|
+
|
|
338
|
+
## Document Review Patterns
|
|
339
|
+
- Red flags in contracts: unilateral amendment clauses, unlimited liability, auto-renewal without notice, non-mutual indemnification
|
|
340
|
+
- Key sections to scrutinize: definitions, representations & warranties, limitation of liability, termination, governing law, dispute resolution
|
|
341
|
+
- Track changes protocol: accept/reject individually, never bulk-accept
|
|
342
|
+
- Version control: filename format [DocumentName]_v[X]_[Date]_[Initials]
|
|
343
|
+
|
|
344
|
+
## Legal Research Process
|
|
345
|
+
- Start with secondary sources (treatises, law reviews) for overview
|
|
346
|
+
- Move to primary sources (statutes, regulations, case law)
|
|
347
|
+
- Check for recent amendments or overruling decisions
|
|
348
|
+
- Note circuit splits or jurisdictional variations
|
|
349
|
+
- Shepardize/KeyCite all cases before relying on them
|
|
350
|
+
|
|
351
|
+
## Citation Basics
|
|
352
|
+
- Bluebook format for formal documents
|
|
353
|
+
- Include pinpoint citations to specific pages or paragraphs
|
|
354
|
+
- Subsequent references: use short form after first full citation
|
|
355
|
+
- Signal usage: See (direct support), Cf. (analogous), But see (contrary)
|
|
356
|
+
|
|
357
|
+
## Drafting Standards
|
|
358
|
+
- Define all key terms in a definitions section
|
|
359
|
+
- Use "shall" for obligations, "may" for permissions, "will" for future events
|
|
360
|
+
- Avoid ambiguous modifiers: "reasonable", "promptly" \u2014 quantify where possible
|
|
361
|
+
- Cross-reference internal sections by number, not page
|
|
362
|
+
- Include severability clause in all agreements
|
|
363
|
+
|
|
364
|
+
## Privilege & Confidentiality
|
|
365
|
+
- Attorney-client privilege: communications for purpose of legal advice
|
|
366
|
+
- Work product doctrine: materials prepared in anticipation of litigation
|
|
367
|
+
- Mark privileged documents clearly: "ATTORNEY-CLIENT PRIVILEGED AND CONFIDENTIAL"
|
|
368
|
+
- Never forward privileged communications without counsel approval
|
|
369
|
+
|
|
370
|
+
## Risk Assessment Framework
|
|
371
|
+
- Likelihood: almost certain, likely, possible, unlikely, rare
|
|
372
|
+
- Impact: catastrophic, major, moderate, minor, insignificant
|
|
373
|
+
- Risk rating: likelihood \xD7 impact matrix
|
|
374
|
+
- Recommend mitigation strategies for high and critical risks
|
|
375
|
+
- Document all risk assessments with date and basis`,tools:["files.read","web.search","memory.*"],channels:["web","telegram"],layers:["memory","knowledge-graph"]},{id:"receptionist",name:"Receptionist",description:"Warm, professional front-desk agent for scheduling and communication.",persona:`# Receptionist
|
|
376
|
+
|
|
377
|
+
You are a warm, professional receptionist and first point
|
|
378
|
+
of contact. You create excellent first impressions, manage
|
|
379
|
+
scheduling efficiently, and ensure smooth communication flow.
|
|
380
|
+
|
|
381
|
+
## Core Principles
|
|
382
|
+
- First impressions matter \u2014 be warm, professional, and helpful
|
|
383
|
+
- Everyone deserves prompt, courteous attention
|
|
384
|
+
- Know the team's availability and preferences
|
|
385
|
+
- Route inquiries to the right person quickly
|
|
386
|
+
- Keep the front desk organized and information current
|
|
387
|
+
|
|
388
|
+
## Voice & Tone
|
|
389
|
+
- Warm and welcoming \u2014 smile comes through in your words
|
|
390
|
+
- Professional but not stiff
|
|
391
|
+
- Helpful and proactive \u2014 anticipate what the caller needs
|
|
392
|
+
- Calm and composed, even during busy periods
|
|
393
|
+
|
|
394
|
+
## Communication Flow
|
|
395
|
+
1. Greet warmly with name and organization
|
|
396
|
+
2. Listen attentively to the request
|
|
397
|
+
3. Confirm understanding by restating the need
|
|
398
|
+
4. Take action: schedule, transfer, or take a message
|
|
399
|
+
5. Confirm next steps and thank the caller
|
|
400
|
+
6. Follow up on any promised callbacks`,knowledge:`# Receptionist Knowledge
|
|
401
|
+
|
|
402
|
+
## Phone Etiquette
|
|
403
|
+
- Answer within 3 rings with a consistent greeting
|
|
404
|
+
- Greeting format: "Good [morning/afternoon], [Company]. This is [Name], how may I help you?"
|
|
405
|
+
- Place callers on hold gracefully: "May I place you on a brief hold while I check on that?"
|
|
406
|
+
- Return within 60 seconds: "Thank you for holding, I appreciate your patience."
|
|
407
|
+
- Transfer protocol: announce the caller to the recipient before connecting
|
|
408
|
+
- If unavailable: "They're currently in a meeting. May I take a message or schedule a callback?"
|
|
409
|
+
|
|
410
|
+
## Scheduling Best Practices
|
|
411
|
+
- Confirm timezone for all appointments with external parties
|
|
412
|
+
- Double-check for conflicts before confirming any booking
|
|
413
|
+
- Send calendar invite immediately after booking
|
|
414
|
+
- Include: date, time, duration, location/link, attendee names, agenda if available
|
|
415
|
+
- Reminder cadence: 24 hours before, 1 hour before
|
|
416
|
+
- Cancellation: offer 2-3 alternative times immediately
|
|
417
|
+
|
|
418
|
+
## Message Taking
|
|
419
|
+
- Essential fields: caller name, company, phone, email, reason, urgency
|
|
420
|
+
- Read the message back to confirm accuracy
|
|
421
|
+
- Delivery priority: urgent (immediately via text), important (within 1 hour), routine (end of day digest)
|
|
422
|
+
- Mark messages as delivered once confirmed
|
|
423
|
+
|
|
424
|
+
## Visitor Management
|
|
425
|
+
- Greet visitors within 10 seconds of arrival
|
|
426
|
+
- Verify appointment, offer water/coffee, show to waiting area
|
|
427
|
+
- Notify the host immediately upon visitor arrival
|
|
428
|
+
- If host is delayed, keep visitor informed with estimated wait time
|
|
429
|
+
- Maintain visitor log: name, company, host, time in/out
|
|
430
|
+
|
|
431
|
+
## Directory & Routing
|
|
432
|
+
- Maintain up-to-date contact directory for all team members
|
|
433
|
+
- Know each person's role and department for proper routing
|
|
434
|
+
- Keep list of frequently asked questions for self-service answers
|
|
435
|
+
- Emergency contacts: posted and memorized
|
|
436
|
+
- After-hours protocol: voicemail greeting with emergency contact number
|
|
437
|
+
|
|
438
|
+
## Front Desk Organization
|
|
439
|
+
- Check voicemails first thing and return all by 10 AM
|
|
440
|
+
- Process incoming mail and packages by noon
|
|
441
|
+
- Update team out-of-office schedule daily
|
|
442
|
+
- Prepare next-day visitor list each afternoon
|
|
443
|
+
- Restock reception area supplies weekly`,tools:["schedule.*","voice.*","email.draft"],channels:["telegram","web","whatsapp"],layers:["memory","jobs"]},{id:"data-analyst",name:"Data Analyst",description:"Clarity-focused analyst for data exploration and insight generation.",persona:`# Data Analyst
|
|
444
|
+
|
|
445
|
+
You are a rigorous data analyst who transforms raw data
|
|
446
|
+
into clear, actionable insights. You combine technical skill
|
|
447
|
+
with strong communication to make data accessible to all.
|
|
448
|
+
|
|
449
|
+
## Core Principles
|
|
450
|
+
- Let the data tell the story \u2014 never force a narrative
|
|
451
|
+
- Question assumptions, including your own
|
|
452
|
+
- Reproducibility is essential \u2014 document every step
|
|
453
|
+
- Simple explanations of complex findings
|
|
454
|
+
- Statistical significance matters \u2014 report confidence levels
|
|
455
|
+
|
|
456
|
+
## Voice & Tone
|
|
457
|
+
- Clear and precise \u2014 no jargon without explanation
|
|
458
|
+
- Objective \u2014 present findings without bias
|
|
459
|
+
- Thorough \u2014 address limitations and caveats
|
|
460
|
+
- Visual \u2014 prefer charts and tables over paragraphs of numbers
|
|
461
|
+
|
|
462
|
+
## Analysis Process
|
|
463
|
+
1. Clarify the business question and success criteria
|
|
464
|
+
2. Assess data quality, completeness, and potential biases
|
|
465
|
+
3. Explore with descriptive statistics and visualizations
|
|
466
|
+
4. Apply appropriate analytical methods
|
|
467
|
+
5. Validate findings with sanity checks and cross-references
|
|
468
|
+
6. Present insights with clear recommendations and next steps`,knowledge:`# Data Analysis Knowledge
|
|
469
|
+
|
|
470
|
+
## Analysis Frameworks
|
|
471
|
+
- Define the question precisely before touching the data
|
|
472
|
+
- Hypothesis-driven analysis: state H0 and H1 before running tests
|
|
473
|
+
- MECE principle: categories should be mutually exclusive, collectively exhaustive
|
|
474
|
+
- Funnel analysis: identify where the biggest drop-offs occur
|
|
475
|
+
- Cohort analysis: group users by acquisition period to track behavior over time
|
|
476
|
+
|
|
477
|
+
## Data Quality Checks
|
|
478
|
+
- Missing values: quantify percentage, determine if MCAR/MAR/MNAR
|
|
479
|
+
- Outliers: use IQR method (1.5\xD7 below Q1 or above Q3) or z-score (>3)
|
|
480
|
+
- Duplicates: check on primary keys and composite keys
|
|
481
|
+
- Data types: verify dates parse correctly, numerics aren't stored as strings
|
|
482
|
+
- Referential integrity: all foreign keys have matching primary records
|
|
483
|
+
- Freshness: confirm data is as recent as expected
|
|
484
|
+
|
|
485
|
+
## Statistical Essentials
|
|
486
|
+
- Descriptive: mean, median, mode, standard deviation, percentiles
|
|
487
|
+
- Correlation \u2260 causation \u2014 always note this limitation
|
|
488
|
+
- p-value threshold: 0.05 for standard, 0.01 for high-stakes decisions
|
|
489
|
+
- Confidence intervals: report 95% CI alongside point estimates
|
|
490
|
+
- Sample size: power analysis before running experiments
|
|
491
|
+
- Effect size matters as much as statistical significance
|
|
492
|
+
|
|
493
|
+
## Visualization Guidelines
|
|
494
|
+
- Bar charts: comparing categories
|
|
495
|
+
- Line charts: trends over time
|
|
496
|
+
- Scatter plots: relationship between two continuous variables
|
|
497
|
+
- Histograms: distribution of a single variable
|
|
498
|
+
- Heatmaps: correlation matrices or dense cross-tabulations
|
|
499
|
+
- Rule of thumb: if you need a legend with more than 7 items, simplify
|
|
500
|
+
- Always label axes, include units, and add a descriptive title
|
|
501
|
+
- Avoid: 3D charts, pie charts with >5 slices, dual y-axes
|
|
502
|
+
|
|
503
|
+
## SQL Best Practices
|
|
504
|
+
- Use CTEs (WITH clauses) for readable, modular queries
|
|
505
|
+
- Always include WHERE clauses on date ranges to avoid full table scans
|
|
506
|
+
- Aggregate before joining to reduce row explosion
|
|
507
|
+
- Use COALESCE for null handling in calculations
|
|
508
|
+
- Comment complex logic inline for future maintainers
|
|
509
|
+
|
|
510
|
+
## Reporting Standards
|
|
511
|
+
- Executive summary: 3-5 key findings in bullet points
|
|
512
|
+
- Methodology section: data sources, time period, filters, assumptions
|
|
513
|
+
- Findings: organized by business question, each with supporting visual
|
|
514
|
+
- Limitations: data gaps, caveats, confidence levels
|
|
515
|
+
- Recommendations: specific, actionable, prioritized by impact
|
|
516
|
+
- Appendix: detailed tables, SQL queries, additional breakdowns`,tools:["code.execute","files.*","web.search"],channels:["web","telegram","slack"],layers:["knowledge-graph"]}];function G(){return[...U]}function q(r){return U.find(e=>e.id===r)}function We(r,e,t){let n=t?.personaAppend?`${r.persona}
|
|
517
|
+
|
|
518
|
+
${t.personaAppend}`:r.persona,o=t?.knowledgeAppend?`${r.knowledge}
|
|
519
|
+
|
|
520
|
+
${t.knowledgeAppend}`:r.knowledge,i=t?.tools??r.tools,s=t?.channels??r.channels,a=t?.layers??r.layers;Le(e)||Me(e,{recursive:!0});let d=me(e,"persona.md"),c=me(e,"knowledge.md");return ge(d,n,"utf-8"),ge(c,o,"utf-8"),{personaPath:d,knowledgePath:c,tools:i,channels:s,layers:a}}import{randomUUID as Ne}from"node:crypto";var J=class{storage;executor;notifier;config;listeners=new Set;constructor(e,t,n,o={}){this.storage=e,this.executor=t,this.notifier=n??null,this.config={defaultExpirationDays:o.defaultExpirationDays??7,notifyChannel:o.notifyChannel??null,autoApprovalThreshold:o.autoApprovalThreshold??5}}on(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(e,t){for(let n of this.listeners)try{n({type:e,item:t})}catch{}}async submit(e){let t=new Date,n=new Date(t.getTime()+this.config.defaultExpirationDays*24*60*60*1e3),o={id:Ne(),...e,status:"pending",createdAt:t,expiresAt:n,resolvedAt:null,resolvedBy:null,notes:null};if(await this.storage.insertApproval(o),this.emit("approval:pending",o),this.notifier&&this.config.notifyChannel){let i=`\u{1F514} Approval needed: ${o.content}
|
|
521
|
+
Workspace: ${o.workspaceId}
|
|
522
|
+
Tool: ${o.toolCall.tool}
|
|
523
|
+
ID: ${o.id}`;await this.notifier.send(this.config.notifyChannel,i).catch(()=>{})}return o}async list(e){return this.storage.listApprovals(e??{})}async approve(e,t){let n=await this.storage.getApproval(e);if(!n)throw new Error(`Approval item "${e}" not found`);if(n.status!=="pending")throw new Error(`Cannot approve item with status "${n.status}"`);let o=await this.executor.execute(n.toolCall),i={status:"approved",resolvedAt:new Date,resolvedBy:t??null};await this.storage.updateApproval(e,i);let s={...n,...i};return this.emit("approval:approved",s),{item:s,result:o}}async reject(e,t,n){let o=await this.storage.getApproval(e);if(!o)throw new Error(`Approval item "${e}" not found`);if(o.status!=="pending")throw new Error(`Cannot reject item with status "${o.status}"`);let i={status:"rejected",resolvedAt:new Date,resolvedBy:n??null,notes:t??null};await this.storage.updateApproval(e,i);let s={...o,...i};return this.emit("approval:rejected",s),s}async edit(e,t,n){let o=await this.storage.getApproval(e);if(!o)throw new Error(`Approval item "${e}" not found`);if(o.status!=="pending")throw new Error(`Cannot edit item with status "${o.status}"`);let i={status:"edited",resolvedAt:new Date,resolvedBy:n??null,notes:t};await this.storage.updateApproval(e,i);let s={...o,...i};return this.emit("approval:edited",s),s}async expireStale(){let e=await this.storage.listApprovals({status:"pending"}),t=new Date,n=[];for(let o of e)if(o.expiresAt<=t){let i={status:"expired",resolvedAt:t};await this.storage.updateApproval(o.id,i);let s={...o,...i};this.emit("approval:expired",s),n.push(s)}return n}};async function Oe(r,e,t,n=5){return await r.countConsecutiveApprovals(e,t)>=n}var D=[{id:"gmail",name:"Gmail",protocol:"MCP",authMethod:"oauth2",capabilities:["email.read","email.send","email.draft"]},{id:"google-calendar",name:"Google Calendar",protocol:"MCP",authMethod:"oauth2",capabilities:["calendar.read","calendar.write","calendar.schedule"]},{id:"facebook",name:"Facebook",protocol:"MCP",authMethod:"oauth2",capabilities:["social.post","social.read"]},{id:"instagram",name:"Instagram",protocol:"MCP",authMethod:"oauth2",capabilities:["social.post","social.read"]},{id:"linkedin",name:"LinkedIn",protocol:"MCP",authMethod:"oauth2",capabilities:["social.post","social.read"]},{id:"x-twitter",name:"X (Twitter)",protocol:"MCP",authMethod:"api_key",capabilities:["social.post","social.read"]},{id:"notion",name:"Notion",protocol:"MCP",authMethod:"api_key",capabilities:["docs.read","docs.write"]},{id:"slack",name:"Slack",protocol:"MCP",authMethod:"oauth2",capabilities:["messaging.send","messaging.read"]},{id:"wordpress",name:"WordPress",protocol:"builtin",authMethod:"api_key",capabilities:["publish.post","publish.page"]}];function Be(){let r=new Map,e=new Map;function t(o,i){return`${o}:${i}`}function n(o,i){return`${o}:${i}`}return{getConnection(o,i){return r.get(t(o,i))},saveConnection(o){r.set(t(o.fleetId,o.integrationId),o)},deleteConnection(o,i){return r.delete(t(o,i))},listConnections(o){let i=[];for(let s of r.values())s.fleetId===o&&i.push(s);return i},getWorkspaceGrant(o,i){return e.get(n(o,i))},saveWorkspaceGrant(o){e.set(n(o.workspaceId,o.integrationId),o)},deleteWorkspaceGrant(o,i){return e.delete(n(o,i))},listWorkspaceGrants(o){let i=[];for(let s of e.values())s.workspaceId===o&&i.push(s);return i}}}var z=class{constructor(e,t){this.storage=e;this.secretStore=t}listAvailable(){return D}async connect(e,t,n){if(!D.find(s=>s.id===t))throw new Error(`Unknown integration: ${t}`);if(!n)throw new Error("Credentials must not be empty");await this.secretStore.store(e,t,n);let i={fleetId:e,integrationId:t,status:"connected",connectedAt:new Date};return this.storage.saveConnection(i),i}disconnect(e,t){this.secretStore.delete(e,t),this.storage.deleteConnection(e,t)}getStatus(e,t){let n=this.storage.getConnection(e,t);return n||{fleetId:e,integrationId:t,status:"disconnected",connectedAt:null}}grantAccess(e,t){if(!D.find(o=>o.id===t))throw new Error(`Unknown integration: ${t}`);this.storage.saveWorkspaceGrant({workspaceId:e,integrationId:t,grantedAt:new Date})}revokeAccess(e,t){this.storage.deleteWorkspaceGrant(e,t)}getWorkspaceIntegrations(e){return this.storage.listWorkspaceGrants(e)}};function K(r){let e=r??new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function V(r){let e=r??new Date;return new Date(e.getFullYear(),e.getMonth(),1).getTime()}var Y=class{constructor(e,t){this.config=e;this.costTracker=t}entries=[];handlers=new Set;recordCost(e,t){this.entries.push({workspaceId:e,amount:t,timestamp:Date.now()})}getCostToday(){let e=K(),t=0;for(let n of this.entries)n.timestamp>=e&&(t+=n.amount);return t}getCostThisMonth(){let e=V(),t=0;for(let n of this.entries)n.timestamp>=e&&(t+=n.amount);return t}getWorkspaceCost(e,t){let n=t==="day"?K():V(),o=0;for(let i of this.entries)i.workspaceId===e&&i.timestamp>=n&&(o+=i.amount);return o}canSpend(e,t){if(this.config.dailyLimit>0){let o=this.getCostToday()+t;if(o>this.config.dailyLimit)return this.notifyExceeded({workspaceId:e,type:"fleet_daily",current:o,limit:this.config.dailyLimit}),!1}if(this.config.monthlyLimit>0){let o=this.getCostThisMonth()+t;if(o>this.config.monthlyLimit)return this.notifyExceeded({workspaceId:e,type:"fleet_monthly",current:o,limit:this.config.monthlyLimit}),!1}let n=this.config.perWorkspaceDailyLimit;if(n&&n>0){let o=this.getWorkspaceCost(e,"day")+t;if(o>n)return this.notifyExceeded({workspaceId:e,type:"workspace_daily",current:o,limit:n}),!1}return!0}onBudgetExceeded(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}getBreakdown(){let e=new Map,t=K(),n=V();for(let o of this.entries){let i=e.get(o.workspaceId);i||(i={daily:0,monthly:0},e.set(o.workspaceId,i)),o.timestamp>=n&&(i.monthly+=o.amount),o.timestamp>=t&&(i.daily+=o.amount)}return e}notifyExceeded(e){for(let t of this.handlers)try{t(e)}catch{}}};function $e(){return`task_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}async function fe(r,e,t){let n=r.taskQueue.filter(l=>l.status==="pending").length,o=r.taskQueue.filter(l=>l.status==="completed").length,i=r.taskQueue.filter(l=>l.status==="failed").length,s=_e(r,n,o,i),a=await e(s),d=je(a),c=[];for(let l of d.newTasks){let p={id:$e(),workspaceId:r.workspaceId,title:l.title,description:l.description,scope:l.scope,status:l.assignToWorkerId?"assigned":"pending",assignedWorkerIds:l.assignToWorkerId?[l.assignToWorkerId]:[],createdAt:new Date};c.push(p),t?.("planner:task-created",{taskId:p.id,title:p.title,scope:p.scope,workspaceId:r.workspaceId})}return d.spawnSubPlanner&&t?.("planner:sub-planner-requested",{domain:d.spawnSubPlanner.domain,scope:d.spawnSubPlanner.scope,parentWorkspaceId:r.workspaceId}),c}function he(r,e,t){return r.status="assigned",r.assignedWorkerIds=[e],t?.("planner:task-assigned",{taskId:r.id,workerId:e}),r}function _e(r,e,t,n){let o=r.taskQueue.slice(-10).map(i=>`- [${i.status}] ${i.title} (${i.scope})`).join(`
|
|
524
|
+
`);return`You are a Planner agent for workspace ${r.workspaceId}.
|
|
525
|
+
Your role: decompose goals into tasks and assign them to workers. Never execute tasks yourself.
|
|
526
|
+
|
|
527
|
+
## Current State
|
|
528
|
+
- Available workers: ${r.workerIds.length} (${r.workerIds.join(", ")})
|
|
529
|
+
- Pending tasks: ${e}
|
|
530
|
+
- Completed tasks: ${t}
|
|
531
|
+
- Failed tasks: ${n}
|
|
532
|
+
${r.roleConfig.taskScope?`- Task scope: ${r.roleConfig.taskScope}`:""}
|
|
533
|
+
|
|
534
|
+
## Recent Tasks
|
|
535
|
+
${o||"(none)"}
|
|
536
|
+
|
|
537
|
+
## Instructions
|
|
538
|
+
Analyze the current state and output JSON:
|
|
539
|
+
{"newTasks": [{"title": "...", "description": "...", "scope": "...", "assignToWorkerId": "..."}], "spawnSubPlanner": null}
|
|
540
|
+
|
|
541
|
+
Only create tasks if there is meaningful work to do. If all goals are met, output empty newTasks.`}function je(r){try{let e=r.match(/\{[\s\S]*\}/);if(e){let t=JSON.parse(e[0]);return{newTasks:Array.isArray(t.newTasks)?t.newTasks:[],spawnSubPlanner:t.spawnSubPlanner??void 0}}}catch{}return{newTasks:[]}}async function ye(r,e,t,n){if(r.loopWarningCount>=3){let o={taskId:e.id,workerId:r.workspaceId,reason:`Loop warning threshold reached (${r.loopWarningCount} warnings)`,context:e.description};return n?.("escalation:requested",{...o,suggestOracle:!0}),e.status="escalated",{task:e,output:null,escalated:!0}}e.status="running",n?.("worker:task-started",{taskId:e.id,workspaceId:r.workspaceId});try{let o=await t(e);return e.status="completed",e.result=o,e.completedAt=new Date,n?.("worker:task-completed",{taskId:e.id,workspaceId:r.workspaceId}),{task:e,output:o,escalated:!1}}catch(o){return e.status="failed",e.error=o instanceof Error?o.message:String(o),n?.("worker:task-failed",{taskId:e.id,workspaceId:r.workspaceId,error:e.error}),{task:e,output:null,escalated:!1}}}function we(r,e){let t=r.filter(o=>!(o.status!=="pending"&&o.status!=="assigned"||o.status==="assigned"&&!o.assignedWorkerIds.includes(e.workspaceId)||e.taskScope&&o.scope!==e.taskScope)),n=t.find(o=>o.assignedWorkerIds.includes(e.workspaceId));return n||(t.sort((o,i)=>o.createdAt.getTime()-i.createdAt.getTime())[0]??null)}function ke(r,e,t){return{taskId:r.id,workerId:e,reason:t,context:`Task: ${r.title}
|
|
542
|
+
Description: ${r.description}
|
|
543
|
+
Scope: ${r.scope}`}}var Q={completionThreshold:.9,maxErrorRate:.2,requireHumanApproval:!1};async function ve(r,e=Q,t,n){let o=r.tasks.length;if(o===0)return{verdict:"cycle:complete",goalAchievementRate:1,openTaskCount:0,workerErrorRate:0,notes:"No tasks in cycle \u2014 trivially complete."};let i=r.tasks.filter(g=>g.status==="completed").length,s=r.tasks.filter(g=>g.status==="failed").length,a=r.tasks.filter(g=>g.status==="pending"||g.status==="assigned"||g.status==="running").length,d=i/o,c=o>0?s/o:0,l,p;if(d>=e.completionThreshold&&a===0?(l="cycle:complete",p=`Achievement rate ${(d*100).toFixed(0)}% meets threshold.`):c>e.maxErrorRate?(l="cycle:escalate",p=`Error rate ${(c*100).toFixed(0)}% exceeds max ${(e.maxErrorRate*100).toFixed(0)}%.`):a>0?(l="cycle:continue",p=`${a} tasks still open. Achievement at ${(d*100).toFixed(0)}%.`):(l="cycle:continue",p=`Achievement rate ${(d*100).toFixed(0)}% below threshold ${(e.completionThreshold*100).toFixed(0)}%.`),t&&r.roleConfig.evaluationCriteria?.length){let g=await He(r,t);g&&(p+=` LLM evaluation: ${g}`)}let h={verdict:l,goalAchievementRate:d,openTaskCount:a,workerErrorRate:c,notes:p};return n?.(l,{workspaceId:r.workspaceId,...h,requiresApproval:l==="cycle:escalate"&&e.requireHumanApproval}),h}function Ce(r){return r.some(e=>e.status==="pending"||e.status==="assigned"||e.status==="running")}async function He(r,e){let t=r.roleConfig.evaluationCriteria?.join(`
|
|
544
|
+
- `)??"",n=r.tasks.map(i=>`[${i.status}] ${i.title}: ${i.error??"ok"}`).join(`
|
|
545
|
+
`),o=`Evaluate this planning cycle against the criteria below.
|
|
546
|
+
|
|
547
|
+
## Criteria
|
|
548
|
+
- ${t}
|
|
549
|
+
|
|
550
|
+
## Tasks
|
|
551
|
+
${n}
|
|
552
|
+
|
|
553
|
+
Provide a one-sentence evaluation summary.`;try{return await e(o)}catch{return null}}var be={slot:"oracle",maxTokensIn:2e3,maxTokensOut:500,invocationBudget:5},X=class{config;llmCall;recordCost;emit;sessionInvocations=new Map;constructor(e={},t,n){this.config={...be,...e},this.llmCall=t,this.recordCost=n?.recordCost??null,this.emit=n?.emit??null}async consult(e){let t=this.sessionInvocations.get(e.sessionId)??0;if(t>=this.config.invocationBudget)throw new M(e.sessionId,t,this.config.invocationBudget);let n=this.config.maxTokensIn*4,o=e.contextExcerpt.length>n?e.contextExcerpt.slice(0,n)+`
|
|
554
|
+
[...truncated]`:e.contextExcerpt,i=Ue(e.problem,o,e.question),s=await this.llmCall(i,this.config.maxTokensOut),a=`oracle_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.sessionInvocations.set(e.sessionId,t+1),this.recordCost?.(s.tokensUsed,"oracle_spend",e.sessionId),this.emit?.("oracle:consultation-completed",{consultationId:a,workerId:e.workerId,sessionId:e.sessionId,tokensCost:s.tokensUsed,invocationNumber:t+1,budgetRemaining:this.config.invocationBudget-t-1}),{guidance:s.text,tokensCost:s.tokensUsed,consultationId:a}}formatGuidanceBlock(e){return`## Oracle Guidance
|
|
555
|
+
_Consultation ${e.consultationId}_
|
|
556
|
+
|
|
557
|
+
${e.guidance}`}getRemainingBudget(e){let t=this.sessionInvocations.get(e)??0;return Math.max(0,this.config.invocationBudget-t)}resetSession(e){this.sessionInvocations.delete(e)}};function Ue(r,e,t){return`You are an Oracle \u2014 a high-capability strategic advisor. A worker agent is stuck and needs your guidance.
|
|
558
|
+
|
|
559
|
+
## Problem
|
|
560
|
+
${r}
|
|
561
|
+
|
|
562
|
+
## Relevant Context
|
|
563
|
+
${e}
|
|
564
|
+
|
|
565
|
+
## Question
|
|
566
|
+
${t}
|
|
567
|
+
|
|
568
|
+
Provide concise, actionable strategic guidance. Focus on unblocking the worker. Do not repeat the problem statement.`}var M=class extends Error{constructor(t,n,o){super(`Oracle budget exceeded for session ${t}: ${n}/${o} invocations used`);this.sessionId=t;this.used=n;this.budget=o;this.name="OracleBudgetExceededError"}};var xe={k:3,minJudgeConfidence:.7,maxDepth:3},Z=class{config;execute;judge;investigate;checkBudget;emit;constructor(e={},t){this.config={...xe,...e},this.execute=t.execute,this.judge=t.judge,this.investigate=t.investigate??null,this.checkBudget=t.checkBudget??null,this.emit=t.emit??null}async select(e,t=0){if(t>=this.config.maxDepth)throw new Error(`Best-of-N max depth ${this.config.maxDepth} reached for task ${e.id}`);if(this.checkBudget&&!this.checkBudget(this.config.k))throw new L(e.id,this.config.k);this.emit?.("bestofn:spawning-candidates",{taskId:e.id,k:this.config.k,depth:t});let n=Array.from({length:this.config.k},(p,h)=>`candidate_${e.id}_${h}_${Math.random().toString(36).slice(2,6)}`),i=(await Promise.allSettled(n.map(p=>this.execute(e,p)))).filter(p=>p.status==="fulfilled").map(p=>p.value);if(i.length===0)throw new Error(`All ${this.config.k} candidates failed for task ${e.id}`);let s=await this.judge(i,this.config.judgePrompt),a=[...s].sort((p,h)=>h.score-p.score),d=a[0],c=!1;if(d.confidence<this.config.minJudgeConfidence&&this.investigate){this.emit?.("bestofn:low-confidence-investigating",{taskId:e.id,topConfidence:d.confidence,threshold:this.config.minJudgeConfidence});let p=await this.investigate(e,i,s),h=await this.judge(i,`${this.config.judgePrompt??""}
|
|
569
|
+
|
|
570
|
+
Additional context from investigation:
|
|
571
|
+
${p}`),g=[...h].sort((m,C)=>C.score-m.score),u=i.find(m=>m.candidateId===g[0].candidateId);return this.emit?.("bestofn:winner-selected",{taskId:e.id,winnerId:u.candidateId,score:g[0].score,confidence:g[0].confidence,reranAfterInvestigation:!0}),{winner:u,scores:h,depth:t,reranAfterInvestigation:!0}}let l=i.find(p=>p.candidateId===d.candidateId);return this.emit?.("bestofn:winner-selected",{taskId:e.id,winnerId:l.candidateId,score:d.score,confidence:d.confidence,reranAfterInvestigation:c}),{winner:l,scores:a,depth:t,reranAfterInvestigation:c}}},L=class extends Error{constructor(t,n){super(`Budget exceeded: cannot spawn ${n} candidates for task ${t}`);this.taskId=t;this.candidatesRequested=n;this.name="BudgetExceededError"}};var Ge={rounds:2,requireApproval:!1};async function qe(r,e,t){let n=[],o=0,i=r.advocatePrompt??"You are an Advocate. Propose and defend a solution. Be specific and actionable.",s=r.criticPrompt??"You are a Critic. Challenge assumptions, find failure modes, and identify risks. Be thorough but constructive.",a=await e("advocate",Ie(i,r.topic,r.context,null));o++;for(let l=1;l<=r.rounds;l++){t?.("debate:round-started",{round:l,topic:r.topic});let p=await e("critic",Je(s,r.topic,r.context,a));o++,n.push({roundNumber:l,advocateArgument:a,criticChallenge:p}),l<r.rounds&&(a=await e("advocate",Ie(i,r.topic,r.context,p)),o++),t?.("debate:round-completed",{round:l,topic:r.topic})}let d=await e("synthesizer",ze(r.topic,n));o++;let c=Ke(r.topic,n,d,o);return t?.("debate:completed",{topic:r.topic,rounds:r.rounds,llmCallCount:o,requiresApproval:r.requireApproval??!1}),c}function Ie(r,e,t,n){let o=`${r}
|
|
572
|
+
|
|
573
|
+
## Topic
|
|
574
|
+
${e}
|
|
575
|
+
|
|
576
|
+
## Context
|
|
577
|
+
${t}`;return n?o+=`
|
|
578
|
+
|
|
579
|
+
## Critic's Challenge
|
|
580
|
+
${n}
|
|
581
|
+
|
|
582
|
+
Respond to the critic's challenges. Strengthen your proposal where valid, concede where the critic is right.`:o+=`
|
|
583
|
+
|
|
584
|
+
Propose a solution and defend it.`,o}function Je(r,e,t,n){return`${r}
|
|
585
|
+
|
|
586
|
+
## Topic
|
|
587
|
+
${e}
|
|
588
|
+
|
|
589
|
+
## Context
|
|
590
|
+
${t}
|
|
591
|
+
|
|
592
|
+
## Advocate's Proposal
|
|
593
|
+
${n}
|
|
594
|
+
|
|
595
|
+
Challenge the advocate's assumptions and identify failure modes.`}function ze(r,e){let t=e.map(n=>`### Round ${n.roundNumber}
|
|
596
|
+
**Advocate:** ${n.advocateArgument}
|
|
597
|
+
|
|
598
|
+
**Critic:** ${n.criticChallenge}`).join(`
|
|
599
|
+
|
|
600
|
+
`);return`Synthesize this debate into a structured recommendation.
|
|
601
|
+
|
|
602
|
+
## Topic
|
|
603
|
+
${r}
|
|
604
|
+
|
|
605
|
+
## Debate Transcript
|
|
606
|
+
${t}
|
|
607
|
+
|
|
608
|
+
Output JSON:
|
|
609
|
+
{"recommendation": "...", "keyRisks": ["..."], "minorityConsiderations": ["..."]}`}function Ke(r,e,t,n){try{let o=t.match(/\{[\s\S]*\}/);if(o){let i=JSON.parse(o[0]);return{topic:r,rounds:e,recommendation:i.recommendation??t,keyRisks:Array.isArray(i.keyRisks)?i.keyRisks:[],minorityConsiderations:Array.isArray(i.minorityConsiderations)?i.minorityConsiderations:[],llmCallCount:n}}}catch{}return{topic:r,rounds:e,recommendation:t,keyRisks:[],minorityConsiderations:[],llmCallCount:n}}var Ve={agentCount:4,synthesize:!0};async function Ye(r,e,t){let n=r.agentCount??4,o=r.perspectives??tt(n);t?.("brainstorm:started",{agentCount:n,perspectives:o,prompt:r.prompt});let i=o.slice(0,n).map((p,h)=>{let g=`brainstorm_agent_${h}`,u=Qe(r.prompt,p);return e(g,u).then(m=>Xe(m,p))}),s=await Promise.allSettled(i),a=s.filter(p=>p.status==="fulfilled").flatMap(p=>p.value);if(t?.("brainstorm:ideas-collected",{totalIdeas:a.length,agentsResponded:s.filter(p=>p.status==="fulfilled").length}),!r.synthesize)return{topIdeas:a.map(p=>({...p,crossAgentFrequency:1,score:1})),allIdeas:a,themes:[],agentCount:n};let d=Ze(a),c=et(a),l=d.sort((p,h)=>h.score-p.score).slice(0,10);return t?.("brainstorm:completed",{topIdeasCount:l.length,themeCount:c.length,totalIdeas:a.length}),{topIdeas:l,allIdeas:a,themes:c,agentCount:n}}function Qe(r,e){return`You are a brainstorming agent with the perspective: **${e}**.
|
|
610
|
+
|
|
611
|
+
## Problem
|
|
612
|
+
${r}
|
|
613
|
+
|
|
614
|
+
## Instructions
|
|
615
|
+
Generate 3-5 creative ideas. For each idea output a JSON line:
|
|
616
|
+
{"title": "...", "rationale": "...", "implementationSketch": "..."}
|
|
617
|
+
|
|
618
|
+
Think from your assigned perspective. Be creative and specific. Output only JSON lines.`}function Xe(r,e){let t=[];for(let n of r.split(`
|
|
619
|
+
`)){let o=n.trim();if(!(!o||!o.startsWith("{")))try{let i=JSON.parse(o);i.title&&i.rationale&&t.push({title:i.title,rationale:i.rationale,implementationSketch:i.implementationSketch??"",agentPerspective:e})}catch{}}return t}function Ze(r){return r.map(e=>{let t=new Set(e.title.toLowerCase().split(/\s+/)),n=0;for(let o of r){if(o===e||o.agentPerspective===e.agentPerspective)continue;let i=new Set(o.title.toLowerCase().split(/\s+/));[...t].filter(a=>i.has(a)&&a.length>3).length>=2&&n++}return{...e,crossAgentFrequency:n+1,score:n+1}})}function et(r){let e=new Map;for(let t of r){let n=t.title.toLowerCase().split(/\s+/).filter(s=>s.length>3),o=n.slice(0,2).join(" ")||"general",i=!1;for(let[s,a]of e){let d=new Set(s.split(" "));if(n.some(c=>d.has(c))){a.push(t),i=!0;break}}i||e.set(o,[t])}return Array.from(e.entries()).map(([t,n])=>({theme:t,ideas:n}))}function tt(r){return["technical feasibility","user experience","cost efficiency","risk assessment","scalability","innovation","simplicity","market fit"].slice(0,r)}import{execFile as nt}from"node:child_process";var Se=3e4,ee=20;async function rt(r,e,t){let n=r.timeout||Se;if(r.packagePaths&&r.packagePaths.length>1)return st(r,n,e,t);let o=Date.now(),{stdout:i,stderr:s,exitCode:a}=await Ee(r.command,n),d=Date.now()-o,c=`${i}
|
|
620
|
+
${s}`;await t?.(`compile-log/${r.workspaceId}/${Date.now()}`,c);let l=te(s),p=a===0,h=l.sort((u,m)=>u.line-m.line).slice(0,ee),g={workspaceId:r.workspaceId,passed:p,fileCount:r.changedFiles.length,elapsedMs:d,errors:h};return e?.(p?"compile:pass":"compile:fail",{workspaceId:r.workspaceId,fileCount:g.fileCount,elapsedMs:d,errorCount:l.length}),g}function ot(r){if(r.passed)return`Compilation passed (${r.fileCount} files, ${r.elapsedMs}ms).`;let e=[`Compilation failed \u2014 ${r.errors.length} error(s):`];for(let t of r.errors)e.push(` ${t.file}:${t.line}:${t.column} \u2014 ${t.message}`);if(r.packageResults){let t=r.packageResults.filter(n=>!n.passed);t.length&&e.push(`Failed packages: ${t.map(n=>n.packagePath).join(", ")}`)}return e.join(`
|
|
621
|
+
`)}async function st(r,e,t,n){let o=Date.now(),s=(await Promise.allSettled(r.packagePaths.map(async l=>{let p=Date.now(),h=`cd ${l} && ${r.command}`,{stderr:g,exitCode:u}=await Ee(h,e),m=te(g);return await n?.(`compile-log/${r.workspaceId}/${l}/${Date.now()}`,g),{packagePath:l,passed:u===0,errors:m.slice(0,ee),elapsedMs:Date.now()-p}}))).filter(l=>l.status==="fulfilled").map(l=>l.value),a=s.flatMap(l=>l.errors).slice(0,ee),d=s.every(l=>l.passed),c={workspaceId:r.workspaceId,passed:d,fileCount:r.changedFiles.length,elapsedMs:Date.now()-o,errors:a,packageResults:s};return t?.(d?"compile:pass":"compile:fail",{workspaceId:r.workspaceId,packageCount:s.length,failedPackages:s.filter(l=>!l.passed).length,elapsedMs:c.elapsedMs}),c}function te(r){let e=[],t=[/^(.+?)\((\d+),(\d+)\):\s*(error|warning)\s+(.+)$/gm,/^(.+?):(\d+):(\d+):\s*(error|warning):?\s*(.+)$/gm];for(let n of t){let o;for(;(o=n.exec(r))!==null;)e.push({file:o[1].trim(),line:parseInt(o[2],10),column:parseInt(o[3],10),severity:o[4],message:o[5].trim()})}return e}function Ee(r,e){return new Promise(t=>{let[n,...o]=r.split(/\s+/);nt(n,o,{timeout:e,shell:!0,maxBuffer:4*1024*1024},(s,a,d)=>{t({stdout:a??"",stderr:d??"",exitCode:s?s.code??1:0})}).on("error",()=>{t({stdout:"",stderr:"Failed to spawn process",exitCode:1})})})}async function it(r,e,t){let n=(r.recentToolCalls??[]).slice(-50);t?.("handoff:generating-summary",{taskId:r.taskId,toolCallCount:n.length,trigger:r.trigger});let o=n.map(p=>`[${p.tool}] ${p.input.slice(0,200)} \u2192 ${p.output.slice(0,200)}`).join(`
|
|
622
|
+
`),i=await e(lt(o)),s=dt(n),a=pt(n),d=ut(n),c=[];r.gitBranch&&c.push(`branch: ${r.gitBranch}`),r.modifiedFiles&&c.push(...r.modifiedFiles.map(p=>`file: ${p}`));let l={taskId:r.taskId,completedSteps:s,currentState:a,openQuestions:d,artifacts:c,suggestedNextActions:gt(s,d),compressedContext:i};return t?.("handoff:summary-ready",{taskId:r.taskId,stepsCount:s.length,questionsCount:d.length,artifactsCount:c.length}),l}function at(r){return[`# Handoff: Task ${r.taskId}`,"","## Completed Steps",...r.completedSteps.map(t=>`- ${t}`),"","## Current State",r.currentState,"","## Open Questions",...r.openQuestions.length?r.openQuestions.map(t=>`- ${t}`):["(none)"],"","## Artifacts",...r.artifacts.map(t=>`- ${t}`),"","## Suggested Next Actions",...r.suggestedNextActions.map(t=>`- ${t}`),"","## Working Context (compressed)",r.compressedContext].join(`
|
|
623
|
+
`)}async function ct(r,e){await e(`handoff/${r.taskId}`,JSON.stringify(r,null,2))}function lt(r){return`Compress the following agent tool call log into a concise summary.
|
|
624
|
+
Include decision rationale, not just action logs. Target 10:1 compression ratio.
|
|
625
|
+
Focus on: what was decided, why, and what state the work is in.
|
|
626
|
+
|
|
627
|
+
## Tool Call Log
|
|
628
|
+
${r}
|
|
629
|
+
|
|
630
|
+
Provide a compressed summary paragraph.`}function dt(r){let e=[];for(let t of r)t.tool==="write"||t.tool==="edit"?e.push(`Modified file via ${t.tool}`):t.tool==="bash"&&t.output.length>0?e.push(`Ran command: ${t.input.slice(0,80)}`):t.tool==="read"&&e.push(`Read file: ${t.input.slice(0,80)}`);return e.filter((t,n)=>n===0||t!==e[n-1])}function pt(r){if(r.length===0)return"No activity recorded.";let e=r[r.length-1];return`Last action: [${e.tool}] ${e.input.slice(0,150)}`}function ut(r){let e=[];for(let t of r)(t.output.includes("error")||t.output.includes("Error"))&&e.push(`Possible issue with ${t.tool}: ${t.output.slice(0,100)}`);return e.slice(0,5)}function gt(r,e){let t=[];return e.length>0&&t.push("Review and resolve open questions listed above"),r.length>0&&t.push("Verify the changes made during the background session"),t.push("Run tests to validate the current state"),t}var mt={agentCount:3,evaluationCriteria:{correctness:.5,efficiency:.3,style:.2}},ne=class{execute;judge;generateDiff;emit;constructor(e){this.execute=e.execute,this.judge=e.judge,this.generateDiff=e.generateDiff??null,this.emit=e.emit??null}async compete(e){let{taskId:t,agentCount:n,evaluationCriteria:o}=e;this.emit?.("arena:started",{taskId:t,agentCount:n});let i=Array.from({length:n},(u,m)=>`arena_${t}_${m}_${Math.random().toString(36).slice(2,6)}`),a=(await Promise.allSettled(i.map(u=>{let m=this.execute(t,u);return e.timeLimitMs?Promise.race([m,ht(e.timeLimitMs,u)]):m}))).filter(u=>u.status==="fulfilled").map(u=>u.value);if(a.length===0)throw new Error(`All ${n} arena contestants failed for task ${t}`);this.emit?.("arena:contestants-finished",{taskId:t,finished:a.length,total:n});let c=(await this.judge(a,o)).map(u=>({...u,weightedTotal:u.correctnessScore*o.correctness+u.efficiencyScore*o.efficiency+u.styleScore*o.style})),l=[...c].sort((u,m)=>m.weightedTotal-u.weightedTotal),p=a.find(u=>u.agentId===l[0].agentId),h=[];if(this.generateDiff){let u=a.filter(C=>C.agentId!==p.agentId),m=await Promise.allSettled(u.map(async C=>({winnerId:p.agentId,loserId:C.agentId,diffSummary:await this.generateDiff(p,C)})));for(let C of m)C.status==="fulfilled"&&h.push(C.value)}let g={taskId:t,winner:p,scores:c,diffs:h,allContestants:a};return this.emit?.("arena:completed",{taskId:t,winnerId:p.agentId,winnerScore:l[0].weightedTotal,contestantCount:a.length}),g}};function ft(r){let e=r.scores.sort((t,n)=>n.weightedTotal-t.weightedTotal).map((t,n)=>`${n+1}. ${t.agentId}: ${t.weightedTotal.toFixed(2)} \u2014 ${t.reasoning}`).join(`
|
|
631
|
+
`);return{type:"arena-review",taskId:r.taskId,summary:`Arena: ${r.allContestants.length} contestants, winner=${r.winner.agentId}
|
|
632
|
+
|
|
633
|
+
${e}`,metadata:{winnerId:r.winner.agentId,scores:r.scores,diffs:r.diffs}}}function ht(r,e){return new Promise((t,n)=>setTimeout(()=>n(new Error(`Arena timeout for ${e} after ${r}ms`)),r))}function re(r){let e=new Map(r.map(s=>[s.id,s])),t=new Map,n=new Set,o=new Set;function i(s){if(t.has(s))return t.get(s);if(o.has(s))throw new Error(`Circular dependency detected involving node "${s}"`);o.add(s);let a=e.get(s);if(!a)throw new Error(`Unknown node dependency: "${s}"`);let d=0;for(let c of a.dependsOn)d=Math.max(d,i(c)+1);return o.delete(s),n.add(s),t.set(s,d),d}for(let s of r)n.has(s.id)||i(s.id);return r.map(s=>({node:s,depth:t.get(s.id)})).sort((s,a)=>s.depth-a.depth)}async function yt(r,e,t){let n=r.concurrentNodes??3,o=re(r.nodes),i=new Map(r.nodes.map(g=>[g.id,g])),s={},a={};for(let g of r.nodes)a[g.id]="pending";let d=Date.now();function c(g,u,m){t?.({type:g,pipelineId:r.id,nodeId:u,timestamp:Date.now(),detail:m})}c("pipeline:start");let l=new Map;for(let{node:g,depth:u}of o){let m=l.get(u)??[];m.push(g),l.set(u,m)}let p=Math.max(...Array.from(l.keys()),0);try{for(let g=0;g<=p;g++){let u=l.get(g)??[];if(u.length!==0)for(let m=0;m<u.length;m+=n){let C=u.slice(m,m+n);await Promise.all(C.map(async I=>{try{await h(I)}catch(S){throw a[I.id]="failed",c("node:error",I.id,S instanceof Error?S.message:String(S)),S}}))}}return c("pipeline:complete"),{pipelineId:r.id,status:"completed",results:s,nodeStatuses:a,startedAt:d,completedAt:Date.now()}}catch(g){let u=g instanceof Error?g.message:String(g);return c("pipeline:error",void 0,u),{pipelineId:r.id,status:"failed",results:s,nodeStatuses:a,startedAt:d,completedAt:Date.now(),error:u}}async function h(g){let u={};for(let I of g.dependsOn)s[I]&&(u[I]=s[I]);let m={prompt:"",previous:u};if(g.inputTransformer&&(m=await g.inputTransformer(m)),g.skipCondition?.(m)){a[g.id]="skipped",c("node:skip",g.id),s[g.id]={nodeId:g.id,output:"",metadata:{skipped:!0},finishReason:"completed",durationMs:0};return}a[g.id]="running",c("node:start",g.id);let C=Date.now();if(!g.agent&&g.inputTransformer)s[g.id]={nodeId:g.id,output:m.prompt,metadata:m.context??{},finishReason:"completed",durationMs:Date.now()-C};else{let I=await e(g.id,g.agent,m),S={nodeId:g.id,output:I.output,metadata:I.metadata??{},finishReason:I.finishReason??"completed",durationMs:Date.now()-C};if(g.outputTransformer){let ie=await g.outputTransformer({prompt:S.output,context:S.metadata,previous:u});S={...S,output:ie.prompt,metadata:ie.context??{}}}s[g.id]=S}a[g.id]="completed",c("node:complete",g.id)}}function wt(r){re(r)}function kt(r){return re(r).map(({node:e})=>e.id)}var R=class extends Error{constructor(t){super(`Circular swarm dependency detected: ${t.join(" \u2192 ")}`);this.cycle=t;this.name="CircularSwarmDependencyError"}},oe=class{entries=new Map;handlers=new Set;parentId;constructor(e){this.parentId=e}register(e,t){this.detectCycles(e,t.coordinator);let n={...t,id:e,hierarchy:[this.parentId,e],started:!1};this.entries.set(e,n),this.emit("swarm:registered",e,n.hierarchy)}async unregister(e){let t=this.entries.get(e);t&&(t.started&&await t.coordinator.stop(),this.entries.delete(e),this.emit("swarm:unregistered",e,t.hierarchy))}has(e){return this.entries.has(e)}get(e){return this.entries.get(e)}list(){return Array.from(this.entries.keys())}async delegate(e,t){let n=this.entries.get(e);if(!n)throw new Error(`Swarm "${e}" is not registered`);n.started||(await n.coordinator.start(),n.started=!0),this.emit("swarm:delegation:start",e,n.hierarchy);try{let o=await n.coordinator.route(t);return this.emit("swarm:delegation:complete",e,n.hierarchy),o}catch(o){let i=o instanceof Error?o.message:String(o);throw this.emit("swarm:delegation:error",e,n.hierarchy,i),o}}on(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}async stopAll(){let e=Array.from(this.entries.values());await Promise.allSettled(e.filter(t=>t.started).map(async t=>{await t.coordinator.stop(),t.started=!1}))}detectCycles(e,t){let n=new Set,o=[e];for(;o.length>0;){let i=o.pop();if(n.has(i))continue;if(n.add(i),this.entries.get(i)&&i===this.parentId){let a=Array.from(n);throw new R(a)}}for(let[i,s]of this.entries)if(s.coordinator===t&&i!==e)throw new R([this.parentId,e,i])}emit(e,t,n,o){let i={type:e,swarmId:t,hierarchy:n,timestamp:Date.now(),detail:o};for(let s of this.handlers)try{s(i)}catch{}}};var vt=new Set(["agent:step","tool:executing","tool:start","llm:generating","token"]),Ct=new Set(["agent:stop","swarm:stop","agent:end"]),se=class{statuses=new Map;pendingApprovals=new Map;pendingHIL=new Map;handlers=new Set;config;constructor(e={}){this.config={unknownThresholdMs:e.unknownThresholdMs??3e4,recentWindowMs:e.recentWindowMs??5e3}}ingest(e){let{agentInstanceId:t,type:n,timestamp:o}=e;if(n==="approval:requested"){let d=e.data?.callId;if(d){let c=this.pendingApprovals.get(t)??new Set;c.add(d),this.pendingApprovals.set(t,c)}}if(n==="approval:granted"||n==="approval:denied"){let d=e.data?.callId;d&&this.pendingApprovals.get(t)?.delete(d)}if(n==="hil:question"){let d=e.data?.questionId;if(d){let c=this.pendingHIL.get(t)??new Set;c.add(d),this.pendingHIL.set(t,c)}}if(n==="hil:answered"||n==="hil:timeout"){let d=e.data?.questionId;d&&this.pendingHIL.get(t)?.delete(d)}let i=this.classify(t,n,e.data),a=this.statuses.get(t)?.status??"unknown";this.statuses.set(t,{agentInstanceId:t,status:i,lastSignalAt:o,detail:n}),a!==i&&this.emit({type:"worker:status:changed",agentInstanceId:t,previousStatus:a,newStatus:i,timestamp:o})}getStatus(e){let t=this.statuses.get(e);return!t||Date.now()-t.lastSignalAt>this.config.unknownThresholdMs?"unknown":t.status}getRecord(e){return this.statuses.get(e)}listAll(){return Array.from(this.statuses.values()).map(e=>({...e,status:this.getStatus(e.agentInstanceId)}))}getAvailable(){return this.listAll().filter(e=>e.status==="idle").map(e=>e.agentInstanceId)}on(e){return this.handlers.add(e),()=>{this.handlers.delete(e)}}clear(){this.statuses.clear(),this.pendingApprovals.clear(),this.pendingHIL.clear()}classify(e,t,n){let o=this.pendingApprovals.get(e);if(o&&o.size>0)return"awaiting-approval";let i=this.pendingHIL.get(e);if(i&&i.size>0)return"awaiting-hil";if((t==="error"||t==="swarm:stop"||t==="agent:end")&&(n?.finishReason??n?.reason)==="error")return"error";if(vt.has(t))return"processing";if(Ct.has(t)){let a=n?.finishReason??n?.reason;return a==="complete"||a==="completed"?"idle":a==="error"?"error":"idle"}return this.statuses.get(e)?.status??"processing"}emit(e){for(let t of this.handlers)try{t(e)}catch{}}};import{createKernel as bt,bootKernel as xt,KERNEL_VERSION as Ae}from"@fenixforce/kernel";var It={edition:"pro",channels:["telegram","web","discord","slack","whatsapp","sms"],tools:["*"],layers:["memory","knowledge-graph","content-pipeline","jobs","approval-gates"]};async function St(r,e={}){let t=bt({...It,...e.kernelConfig}),n=await xt({edition:"pro",tools:["*"],maxTurns:20,databaseUrl:process.env.DATABASE_URL});if(r!=null){let o=E(r),i=e.customerId??"default",s=H(i,o,e.fleetDeps);return s.on(a=>{t.bus.emit({type:"extension:fired",timestamp:a.timestamp,sessionId:a.workspaceId??a.fleetId,extensionId:"fleet-coordinator",hook:a.type})}),await s.start(),{mode:"fleet",kernel:t,runningKernel:n,fleet:s,health(){let a=s.status(),d=a.workspaces.some(l=>l.status==="error"),c=a.workspaces.length>0&&a.workspaces.every(l=>l.status==="running");return{status:d?"degraded":c?"ok":"degraded",mode:"fleet",version:Ae,fleet:a}},async stop(){await s.stop(),await n.stop()}}}return{mode:"single",kernel:t,runningKernel:n,fleet:null,health(){return{status:n.health().status,mode:"single",version:Ae}},async stop(){await n.stop()}}}var A={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"};function Et(){return new Response(null,{status:204,headers:A})}function y(r,e=200){return Response.json(r,{status:e,headers:A})}function b(r,e,t){return Response.json({error:e,...t?{code:t}:{}},{status:r,headers:A})}var v=class extends Error{constructor(t,n,o){super(n);this.status=t;this.code=o}};function Re(r){return async(e,t)=>{try{return await r(e,t)}catch(n){if(n instanceof v)return b(n.status,n.message,n.code);let o=n instanceof Error?n.message:String(n);return b(500,`Internal server error: ${o}`,"INTERNAL_ERROR")}}}function w(r,e){if(!e)return null;let t=r.headers.get("Authorization");if(!t)throw new v(401,"Missing Authorization header","AUTH_REQUIRED");let n=t.replace(/^Bearer\s+/i,"");if(n!==e)throw new v(401,"Invalid token","AUTH_INVALID");return n}async function x(r){try{return await r.json()}catch{throw new v(400,"Invalid JSON body","INVALID_JSON")}}function T(r,e){let t=e.filter(n=>r[n]===void 0||r[n]===null);if(t.length>0)throw new v(400,`Missing required fields: ${t.join(", ")}`,"VALIDATION_ERROR")}function k(r,e,t){let n=[],o=e.replace(/:(\w+)/g,(i,s)=>(n.push(s),"([^/]+)"));return{method:r.toUpperCase(),pattern:new RegExp(`^${o}$`),paramNames:n,handler:Re(t)}}function At(r,e,t){for(let n of r){if(n.method!==e.toUpperCase())continue;let o=t.match(n.pattern);if(o){let i={};for(let s=0;s<n.paramNames.length;s++)i[n.paramNames[s]]=o[s+1];return{route:n,params:i}}}return null}function Rt(r){let{coordinator:e,fleetBudget:t,authToken:n,onConfigUpdate:o,onWorkspaceMessage:i}=r;return[k("GET","/api/v1/fleet",s=>(w(s,n),y(e.status()))),k("PUT","/api/v1/fleet/config",async s=>{w(s,n);let a=await x(s),d=E(a);return o&&await o(d),y({updated:!0,config:d})}),k("GET","/api/v1/workspaces",s=>{w(s,n);let a=e.status();return y({workspaces:a.workspaces})}),k("POST","/api/v1/workspaces",async s=>{w(s,n);let a=await x(s),d;if(a.templateId){let l=q(a.templateId);if(!l)throw new v(400,`Unknown template: ${a.templateId}`,"INVALID_TEMPLATE");d={id:a.id??`ws-${a.templateId}-${Date.now()}`,name:a.name??l.name,identityDir:"./identity",channels:l.channels,tools:l.tools,layers:l.layers,integrationGrants:{},metadata:{templateId:a.templateId}}}else{if(!a.id||!a.name)throw new v(400,"Either templateId or both id and name are required","VALIDATION_ERROR");d={id:a.id,name:a.name,identityDir:a.config?.identityDir??"./identity",channels:a.config?.channels??[],tools:a.config?.tools??[],layers:a.config?.layers??[],integrationGrants:a.config?.integrationGrants??{},metadata:a.config?.metadata??{}}}let c=await e.addWorkspace(d);return y({id:c.id,name:c.name,status:c.status},201)}),k("GET","/api/v1/workspaces/:id",(s,a)=>{w(s,n);let d=e.workspaceManager.getWorkspace(a.id);if(!d)return b(404,"Workspace not found","NOT_FOUND");let c=t?{daily:t.getWorkspaceCost(a.id,"day"),monthly:t.getWorkspaceCost(a.id,"month")}:null;return y({id:d.id,name:d.name,status:d.status,fleetId:d.fleetId,config:d.config,cost:c,createdAt:d.createdAt,startedAt:d.startedAt})}),k("PUT","/api/v1/workspaces/:id",async(s,a)=>{w(s,n);let d=e.workspaceManager.getWorkspace(a.id);if(!d)return b(404,"Workspace not found","NOT_FOUND");let c=await x(s),l={...d.config,...c,id:d.config.id};await e.removeWorkspace(a.id);let p=await e.addWorkspace(l);return y({id:p.id,name:p.name,status:p.status,updated:!0})}),k("DELETE","/api/v1/workspaces/:id",async(s,a)=>(w(s,n),e.workspaceManager.getWorkspace(a.id)?(await e.removeWorkspace(a.id),y({deleted:!0,id:a.id})):b(404,"Workspace not found","NOT_FOUND"))),k("POST","/api/v1/workspaces/:id/start",async(s,a)=>{if(w(s,n),!e.workspaceManager.getWorkspace(a.id))return b(404,"Workspace not found","NOT_FOUND");await e.workspaceManager.startWorkspace(a.id);let c=e.workspaceManager.getWorkspace(a.id);return y({id:c.id,status:c.status})}),k("POST","/api/v1/workspaces/:id/stop",async(s,a)=>{if(w(s,n),!e.workspaceManager.getWorkspace(a.id))return b(404,"Workspace not found","NOT_FOUND");await e.workspaceManager.stopWorkspace(a.id);let c=e.workspaceManager.getWorkspace(a.id);return y({id:a.id,status:c?.status??"stopped"})}),k("POST","/api/v1/workspaces/:id/message",async(s,a)=>{w(s,n);let d=e.workspaceManager.getWorkspace(a.id);if(!d)return b(404,"Workspace not found","NOT_FOUND");if(d.status!=="running")throw new v(400,`Workspace is ${d.status}, not running`,"WORKSPACE_NOT_RUNNING");let c=await x(s);if(T(c,["message"]),i){let l=await i(a.id,c.message,c.userId??"api");return y({delivered:!0,workspaceId:a.id,result:l})}return y({delivered:!0,workspaceId:a.id})}),k("GET","/api/v1/templates",s=>{w(s,n);let a=G().map(d=>({id:d.id,name:d.name,description:d.description,tools:d.tools,channels:d.channels}));return y({templates:a})}),k("GET","/api/v1/fleet/budget",s=>(w(s,n),t?y({daily:{spent:t.getCostToday()},monthly:{spent:t.getCostThisMonth()}}):b(501,"Budget tracking not configured","NOT_IMPLEMENTED"))),k("GET","/api/v1/fleet/budget/breakdown",s=>{if(w(s,n),!t)return b(501,"Budget tracking not configured","NOT_IMPLEMENTED");let a=t.getBreakdown(),d={};for(let[c,l]of a)d[c]=l;return y({breakdown:d})})]}function Tt(r){let{registry:e,fleetId:t,authToken:n}=r;return[k("GET","/api/v1/integrations",o=>{w(o,n);let s=e.listAvailable().map(a=>{let d=e.getStatus(t,a.id);return{...a,connectionStatus:d.status,connectedAt:d.connectedAt}});return y({integrations:s})}),k("POST","/api/v1/integrations/:id/connect",async(o,i)=>{w(o,n);let s=await x(o);T(s,["credentials"]);try{let a=await e.connect(t,i.id,s.credentials);return y(a,201)}catch(a){throw a instanceof Error&&a.message.startsWith("Unknown integration")?new v(404,a.message,"NOT_FOUND"):a}}),k("DELETE","/api/v1/integrations/:id/disconnect",(o,i)=>(w(o,n),e.disconnect(t,i.id),y({disconnected:!0,integrationId:i.id}))),k("POST","/api/v1/integrations/:id/grant/:wsId",(o,i)=>{w(o,n);try{e.grantAccess(i.wsId,i.id)}catch(s){throw s instanceof Error&&s.message.startsWith("Unknown integration")?new v(404,s.message,"NOT_FOUND"):s}return y({granted:!0,workspaceId:i.wsId,integrationId:i.id})}),k("DELETE","/api/v1/integrations/:id/revoke/:wsId",(o,i)=>(w(o,n),e.revokeAccess(i.wsId,i.id),y({revoked:!0,workspaceId:i.wsId,integrationId:i.id})))]}var Pt={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive",...A};function Ft(r,e){return`event: ${r}
|
|
634
|
+
data: ${JSON.stringify(e)}
|
|
635
|
+
|
|
636
|
+
`}function Dt(r){let{approvalQueue:e,authToken:t}=r;return[k("GET","/api/v1/approvals",async n=>{w(n,t);let o=new URL(n.url),i=o.searchParams.get("workspaceId")??void 0,s=o.searchParams.get("status"),a=parseInt(o.searchParams.get("limit")??"50",10),d=await e.list({workspaceId:i,status:s,limit:a});return y({approvals:d,total:d.length})}),k("GET","/api/v1/approvals/stream",n=>{w(n,t);let o=new ReadableStream({start(i){let s=new TextEncoder,a=(l,p)=>{try{i.enqueue(s.encode(Ft(l,p)))}catch{}},d=e.on(l=>{a(l.type,l.item)}),c=setInterval(()=>{try{i.enqueue(s.encode(`: heartbeat
|
|
637
|
+
|
|
638
|
+
`))}catch{clearInterval(c),d()}},3e4);n.signal.addEventListener("abort",()=>{clearInterval(c),d();try{i.close()}catch{}})}});return new Response(o,{headers:Pt})}),k("GET","/api/v1/approvals/:id",async(n,o)=>{w(n,t);let s=(await e.list({})).find(a=>a.id===o.id);return s?y(s):b(404,"Approval not found","NOT_FOUND")}),k("POST","/api/v1/approvals/:id/approve",async(n,o)=>{w(n,t);let i=await x(n).catch(()=>({}));try{let{item:s,result:a}=await e.approve(o.id,i.resolvedBy);return y({item:s,result:a})}catch(s){if(s instanceof Error){if(s.message.includes("not found"))throw new v(404,s.message,"NOT_FOUND");if(s.message.includes("Cannot approve"))throw new v(400,s.message,"INVALID_STATUS")}throw s}}),k("POST","/api/v1/approvals/:id/reject",async(n,o)=>{w(n,t);let i=await x(n).catch(()=>({}));try{let s=await e.reject(o.id,i.notes,i.resolvedBy);return y(s)}catch(s){if(s instanceof Error){if(s.message.includes("not found"))throw new v(404,s.message,"NOT_FOUND");if(s.message.includes("Cannot reject"))throw new v(400,s.message,"INVALID_STATUS")}throw s}}),k("POST","/api/v1/approvals/:id/edit",async(n,o)=>{w(n,t);let i=await x(n);if(!i.notes)throw new v(400,"Notes are required for edit","VALIDATION_ERROR");try{let s=await e.edit(o.id,i.notes,i.resolvedBy);return y(s)}catch(s){if(s instanceof Error){if(s.message.includes("not found"))throw new v(404,s.message,"NOT_FOUND");if(s.message.includes("Cannot edit"))throw new v(400,s.message,"INVALID_STATUS")}throw s}})]}var Wt="pro",er={...Lt},Nt={edition:Wt,channels:["telegram","web","discord","slack","whatsapp","sms"],tools:["*"],layers:["memory","knowledge-graph","content-pipeline","jobs","approval-gates"]};function tr(r){return Mt({...Nt,...r})}export{v as ApiException,P as ApprovalConfigSchema,J as ApprovalQueue,ne as ArenaEngine,U as BUILTIN_TEMPLATES,L as BestOfNBudgetError,Z as BestOfNEngine,F as BudgetConfigSchema,A as CORS_HEADERS,le as ChannelBindingSchema,R as CircularSwarmDependencyError,mt as DEFAULT_ARENA_CONFIG,xe as DEFAULT_BEST_OF_N,Ve as DEFAULT_BRAINSTORM_CONFIG,Se as DEFAULT_COMPILE_TIMEOUT,Ge as DEFAULT_DEBATE_CONFIG,Te as DEFAULT_FLEET_CONFIG,Q as DEFAULT_JUDGE_CONFIG,be as DEFAULT_ORACLE_CONFIG,Wt as EDITION,Y as FleetBudget,O as FleetConfigSchema,N as FleetRouterConfigSchema,z as IntegrationRegistry,Zn as KERNEL_VERSION,D as KNOWN_INTEGRATIONS,M as OracleBudgetExceededError,X as OracleHandler,Nt as PRO_KERNEL_CONFIG,er as PRO_MANIFEST,se as StatusDetector,oe as SwarmRegistry,ce as WorkspaceConfigSchema,We as applyTemplate,he as assignTaskToWorker,St as bootPro,k as buildRoute,Oe as checkAutoApproval,we as claimNextTask,Et as corsPreflightResponse,Dt as createApprovalRoutes,ke as createEscalation,ue as createFleetBudgetTracker,H as createFleetCoordinator,j as createFleetRouter,Rt as createFleetRoutes,Be as createInMemoryIntegrationStorage,B as createInMemorySTM,Tt as createIntegrationRoutes,Mt as createKernel,_ as createSharedMemoryBridge,$ as createWorkspaceManager,b as errorResponse,ve as evaluateCycle,yt as executePipeline,ye as executeWorkerTask,de as extractMention,ft as formatArenaForApproval,ot as formatErrorSummary,at as formatHandoffMessage,it as generateHandoffSummary,kt as getExecutionOrder,q as getTemplate,y as jsonResponse,G as listTemplates,E as loadFleetConfig,Pe as loadFleetConfigFromJSON,pe as matchChannelBinding,At as matchRoute,te as parseCompileErrors,x as parseJsonBody,ct as persistHandoff,ae as resolveEnvVar,Ye as runBrainstorm,rt as runCompileCheck,qe as runDebate,fe as runPlannerCycle,Ce as shouldContinue,tr as startPro,w as validateAuth,wt as validateDAG,T as validateRequired,Re as withErrorHandling};
|