@pithosai/pithosai 1.0.3 → 1.0.5
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/README.md +64 -26
- package/dist/336.mjs +2 -0
- package/dist/935.mjs +2 -2
- package/dist/cosai.mjs +134 -264
- package/dist/heartbeat.mjs +134 -264
- package/dist/init.mjs +2 -0
- package/dist/mktai.mjs +134 -264
- package/dist/pithosai.mjs +134 -264
- package/dist/pmsai.mjs +134 -264
- package/dist/qasai.mjs +134 -264
- package/dist/rdsai.mjs +134 -264
- package/dist/render-markdown.mjs +10 -7
- package/dist/wrsai.mjs +134 -264
- package/package.json +5 -10
- package/scripts/{postinstall-init-db.js → postinstall-init.js} +1 -1
- package/shims/package-root.cjs +1 -1
- package/dist/475.mjs +0 -2
- package/dist/init-pithosai-db.mjs +0 -2
- package/pithosai.sql +0 -177
- package/shims/chalk-cjs-shim.cjs +0 -45
package/dist/qasai.mjs
CHANGED
|
@@ -1,150 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";let t=e(import.meta.url);var i,r,s,o,a,n,l,d,c,u,p,h={7701(e){e.exports=import("@mariozechner/jiti").then(function(e){return e})},4588(e){e.exports=import("@mariozechner/pi-agent-core").then(function(e){return e})},785(e){e.exports=import("@mariozechner/pi-ai").then(function(e){return e})},4127(e){e.exports=import("@mariozechner/pi-tui").then(function(e){return e})},4204(e){e.exports=import("@sinclair/typebox").then(function(e){return e})},8068(e){e.exports=import("@sinclair/typebox/compiler").then(function(e){return e})},9690(e){e.exports=import("ajv").then(function(e){return e})},3529(e){e.exports=import("better-sqlite3").then(function(e){return e})},5590(e){e.exports=import("chalk").then(function(e){return e})},9748(e){e.exports=import("chokidar").then(function(e){return e})},3994(e){e.exports=import("cli-highlight").then(function(e){return e})},5347(e){e.exports=import("commander").then(function(e){return e})},8188(e){e.exports=import("diff").then(function(e){return e})},1852(e){e.exports=import("file-type").then(function(e){return e})},5213(e){e.exports=import("glob").then(function(e){return e})},35(e){e.exports=import("handlebars").then(function(e){return e})},8632(e){e.exports=import("hosted-git-info").then(function(e){return e})},2022(e){e.exports=import("i18next").then(function(e){return e})},4261(e){e.exports=import("ignore").then(function(e){return e})},4082(e){e.exports=import("log4js").then(function(e){return e})},8703(e){e.exports=import("marked").then(function(e){return e})},3637(e){e.exports=import("minimatch").then(function(e){return e})},9392(e){e.exports=import("playwright").then(function(e){return e})},2641(e){e.exports=import("proper-lockfile").then(function(e){return e})},7522(e){e.exports=import("readdirp").then(function(e){return e})},4773(e){e.exports=import("strip-ansi").then(function(e){return e})},4132(e){e.exports=import("uuid").then(function(e){return e})},1464(e){e.exports=import("yaml").then(function(e){return e})},5317(e){e.exports=t("child_process")},9896(e){e.exports=t("fs")},1943(e){e.exports=t("fs/promises")},3339(e){e.exports=t("module")},6698(e){e.exports=t("node:async_hooks")},1421(e){e.exports=t("node:child_process")},7598(e){e.exports=t("node:crypto")},8474(e){e.exports=t("node:events")},3024(e){e.exports=t("node:fs")},1455(e){e.exports=t("node:fs/promises")},8995(e){e.exports=t("node:module")},8161(e){e.exports=t("node:os")},6760(e){e.exports=t("node:path")},481(e){e.exports=t("node:readline")},3136(e){e.exports=t("node:url")},7975(e){e.exports=t("node:util")},857(e){e.exports=t("os")},6928(e){e.exports=t("path")},3785(e){e.exports=t("readline")},2203(e){e.exports=t("stream")},9786(e){e.exports=t("stream/promises")},7016(e){e.exports=t("url")},4467(e,t,i){i.a(e,async function(e,t){try{var r=i(5590);i(7103);var s=i(3525),o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},1200(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(1442),o=i(9354),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a,t()}catch(e){t(e)}})},2937(e,t,i){i.a(e,async function(e,t){try{i(1455);var r=i(5590);i(6928),i(5374),i(7635);var s=i(4459),o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},9793(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},6955(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(3716),o=i(4462),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a,t()}catch(e){t(e)}})},7103(e,t,i){i.d(t,{$M:()=>g,C3:()=>p,GO:()=>c,V8:()=>f,lb:()=>k,pA:()=>w,tb:()=>h});var r=i(9896),s=i(857),o=i(6928);let a=(0,i(7016).fileURLToPath)("file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/config.js"),n=(0,o.dirname)(a),l="file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/config.js".includes("$bunfs")||"file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/config.js".includes("~BUN")||"file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/config.js".includes("%7EBUN");function d(){let e=process.env.PI_PACKAGE_DIR;if(e)return"~"===e?(0,s.homedir)():e.startsWith("~/")?(0,s.homedir)()+e.slice(1):e;if(l)return(0,o.dirname)(process.execPath);let t=n;for(;t!==(0,o.dirname)(t);){if((0,r.existsSync)((0,o.join)(t,"package.json")))return t;t=(0,o.dirname)(t)}return n}function c(){if(l)return(0,o.join)((0,o.dirname)(process.execPath),"theme");let e=d(),t=(0,r.existsSync)((0,o.join)(e,"src"))?"src":"dist";return(0,o.join)(e,t,"modes","interactive","theme")}process.versions.bun;let u=JSON.parse((0,r.readFileSync)((0,o.join)(d(),"package.json"),"utf-8")),p=u.piConfig?.name||"pi",h=u.piConfig?.configDir||".pi";u.version;let m=`${p.toUpperCase()}_CODING_AGENT_DIR`;function g(){let e=process.env[m];return e?"~"===e?(0,s.homedir)():e.startsWith("~/")?(0,s.homedir)()+e.slice(1):e:(0,o.join)((0,s.homedir)(),h,"agent")}function f(){return(0,o.join)(g(),"themes")}function w(){return(0,o.join)(g(),"settings.json")}function k(){return(0,o.join)(g(),"bin")}},2765(e,t,i){i.a(e,async function(e,t){try{i(3024),i(6760);var r=i(785);i(7103);var s=i(9354),o=i(1957),a=i(125),n=i(9927),l=i(8006),d=i(3064),c=i(1573),u=i(7775),p=i(3525),h=e([r,s,o,a,n,l,d,c,u,p]);[r,s,o,a,n,l,d,c,u,p]=h.then?(await h)():h,t()}catch(e){t(e)}})},7683(e,t,i){i.a(e,async function(e,t){try{var r=i(785);i(9896),i(6928);var s=i(2641);i(7103),i(7868);var o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},125(e,t,i){i.a(e,async function(e,t){try{i(7598),i(3024),i(8161),i(6760),i(5317);var r=i(4773);i(3409);var s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},4673(e,t,i){i.a(e,async function(e,t){try{var r=i(785);i(2729);var s=i(8322);i(5250);var o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},8322(e,t,i){i.a(e,async function(e,t){try{var r=i(785);i(2729),i(5250);var s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},9927(e,t,i){i.a(e,async function(e,t){try{var r=i(4673),s=i(8322);i(5250);var o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},5250(){},8846(e,t,i){i(8474)},9532(e,t,i){i(1421)},8006(e,t,i){i.a(e,async function(e,t){try{i(9896),i(6928),i(7103);var r=i(9354);i(9816);var s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},3064(e,t,i){i.a(e,async function(e,t){try{var r=i(5101),s=i(3624),o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},5101(e,t,i){i.a(e,async function(e,t){try{i(3024);var r=i(8995);i(8161),i(6760),i(3136);var s=i(7701),o=i(4588),a=i(785),n=i(4127),l=i(4204);i(7103);var d=i(8285);i(8846),i(9532);var c=e([s,o,a,n,l,d]);[s,o,a,n,l,d]=c.then?(await c)():c,(0,r.createRequire)("file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/core/extensions/loader.js"),t()}catch(e){t(e)}})},3624(e,t,i){i.a(e,async function(e,t){try{var r=i(9354),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},473(e,t,i){i(9896),i(6928)},3716(e,t,i){i.a(e,async function(e,r){try{i.d(t,{pc:()=>h});var s=i(4127),o=i(9896),a=i(6928),n=i(7103),l=e([s]);s=(l.then?(await l)():l)[0];let c={interrupt:"escape",clear:"ctrl+c",exit:"ctrl+d",suspend:"ctrl+z",cycleThinkingLevel:"shift+tab",cycleModelForward:"ctrl+p",cycleModelBackward:"shift+ctrl+p",selectModel:"ctrl+l",expandTools:"ctrl+o",toggleThinking:"ctrl+t",toggleSessionNamedFilter:"ctrl+n",externalEditor:"ctrl+g",followUp:"alt+enter",dequeue:"alt+up",pasteImage:"ctrl+v",newSession:[],tree:[],fork:[],resume:[]},u={...s.DEFAULT_EDITOR_KEYBINDINGS,...c},p=["interrupt","clear","exit","suspend","cycleThinkingLevel","cycleModelForward","cycleModelBackward","selectModel","expandTools","toggleThinking","toggleSessionNamedFilter","externalEditor","followUp","dequeue","pasteImage","newSession","tree","fork","resume"];function d(e){return p.includes(e)}class h{config;appActionToKeys;constructor(e){this.config=e,this.appActionToKeys=new Map,this.buildMaps()}static create(e=(0,n.$M)()){let t=(0,a.join)(e,"keybindings.json"),i=h.loadFromFile(t),r=new h(i),o={};for(let[e,t]of Object.entries(i))d(e)&&"expandTools"!==e||(o[e]=t);return(0,s.setEditorKeybindings)(new s.EditorKeybindingsManager(o)),r}static inMemory(e={}){return new h(e)}static loadFromFile(e){if(!(0,o.existsSync)(e))return{};try{return JSON.parse((0,o.readFileSync)(e,"utf-8"))}catch{return{}}}buildMaps(){for(let[e,t]of(this.appActionToKeys.clear(),Object.entries(c))){let i=Array.isArray(t)?t:[t];this.appActionToKeys.set(e,[...i])}for(let[e,t]of Object.entries(this.config)){if(void 0===t||!d(e))continue;let i=Array.isArray(t)?t:[t];this.appActionToKeys.set(e,i)}}matches(e,t){let i=this.appActionToKeys.get(t);if(!i)return!1;for(let t of i)if((0,s.matchesKey)(e,t))return!0;return!1}getKeys(e){return this.appActionToKeys.get(e)??[]}getEffectiveConfig(){let e={...u};for(let[t,i]of Object.entries(this.config))void 0!==i&&(e[t]=i);return e}}r()}catch(e){r(e)}})},2729(){},2910(e,t,i){i.a(e,async function(e,t){try{var r=i(785),s=i(4204),o=i(9690);i(9896),i(6928),i(7103),i(7868);var a=e([r,o,s]);[r,o,s]=a.then?(await a)():a,o.default.default||o.default;let n=s.Type.Object({only:s.Type.Optional(s.Type.Array(s.Type.String())),order:s.Type.Optional(s.Type.Array(s.Type.String()))}),l=s.Type.Object({only:s.Type.Optional(s.Type.Array(s.Type.String())),order:s.Type.Optional(s.Type.Array(s.Type.String()))}),d=s.Type.Object({supportsStore:s.Type.Optional(s.Type.Boolean()),supportsDeveloperRole:s.Type.Optional(s.Type.Boolean()),supportsReasoningEffort:s.Type.Optional(s.Type.Boolean()),supportsUsageInStreaming:s.Type.Optional(s.Type.Boolean()),maxTokensField:s.Type.Optional(s.Type.Union([s.Type.Literal("max_completion_tokens"),s.Type.Literal("max_tokens")])),requiresToolResultName:s.Type.Optional(s.Type.Boolean()),requiresAssistantAfterToolResult:s.Type.Optional(s.Type.Boolean()),requiresThinkingAsText:s.Type.Optional(s.Type.Boolean()),requiresMistralToolIds:s.Type.Optional(s.Type.Boolean()),thinkingFormat:s.Type.Optional(s.Type.Union([s.Type.Literal("openai"),s.Type.Literal("zai"),s.Type.Literal("qwen")])),openRouterRouting:s.Type.Optional(n),vercelGatewayRouting:s.Type.Optional(l)}),c=s.Type.Object({}),u=s.Type.Union([d,c]),p=s.Type.Object({id:s.Type.String({minLength:1}),name:s.Type.Optional(s.Type.String({minLength:1})),api:s.Type.Optional(s.Type.String({minLength:1})),reasoning:s.Type.Optional(s.Type.Boolean()),input:s.Type.Optional(s.Type.Array(s.Type.Union([s.Type.Literal("text"),s.Type.Literal("image")]))),cost:s.Type.Optional(s.Type.Object({input:s.Type.Number(),output:s.Type.Number(),cacheRead:s.Type.Number(),cacheWrite:s.Type.Number()})),contextWindow:s.Type.Optional(s.Type.Number()),maxTokens:s.Type.Optional(s.Type.Number()),headers:s.Type.Optional(s.Type.Record(s.Type.String(),s.Type.String())),compat:s.Type.Optional(u)}),h=s.Type.Object({name:s.Type.Optional(s.Type.String({minLength:1})),reasoning:s.Type.Optional(s.Type.Boolean()),input:s.Type.Optional(s.Type.Array(s.Type.Union([s.Type.Literal("text"),s.Type.Literal("image")]))),cost:s.Type.Optional(s.Type.Object({input:s.Type.Optional(s.Type.Number()),output:s.Type.Optional(s.Type.Number()),cacheRead:s.Type.Optional(s.Type.Number()),cacheWrite:s.Type.Optional(s.Type.Number())})),contextWindow:s.Type.Optional(s.Type.Number()),maxTokens:s.Type.Optional(s.Type.Number()),headers:s.Type.Optional(s.Type.Record(s.Type.String(),s.Type.String())),compat:s.Type.Optional(u)}),m=s.Type.Object({baseUrl:s.Type.Optional(s.Type.String({minLength:1})),apiKey:s.Type.Optional(s.Type.String({minLength:1})),api:s.Type.Optional(s.Type.String({minLength:1})),headers:s.Type.Optional(s.Type.Record(s.Type.String(),s.Type.String())),authHeader:s.Type.Optional(s.Type.Boolean()),models:s.Type.Optional(s.Type.Array(p)),modelOverrides:s.Type.Optional(s.Type.Record(s.Type.String(),h))});s.Type.Object({providers:s.Type.Record(s.Type.String(),m)});t()}catch(e){t(e)}})},2715(e,t,i){i.a(e,async function(e,t){try{var r=i(785),s=i(5590),o=i(3637),a=i(4467),n=e([r,s,o,a]);[r,s,o,a]=n.then?(await n)():n,t()}catch(e){t(e)}})},5891(e,t,i){i.a(e,async function(e,t){try{i(1421),i(7598),i(3024),i(8161),i(6760);var r=i(4261),s=i(3637);i(7103);var o=i(891),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a,t()}catch(e){t(e)}})},1573(e,t,i){i.a(e,async function(e,t){try{i(9896),i(857),i(6928),i(7103);var r=i(1957),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},7868(e,t,i){i(5317)},1397(e,t,i){i.a(e,async function(e,t){try{i(3024),i(8161),i(6760);var r=i(5590);i(7103);var s=i(9354);i(8846);var o=i(5101),a=i(5891),n=i(1573);i(430);var l=i(5039),d=e([r,s,o,a,n,l]);[r,s,o,a,n,l]=d.then?(await d)():d,t()}catch(e){t(e)}})},7085(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Fl:()=>c.Fl,G3:()=>c.G3,JD:()=>c.JD,a2:()=>c.a2,ij:()=>c.ij,rJ:()=>c.rJ,xH:()=>c.xH,yZ:()=>c.yZ}),i(6760);var s=i(4588);i(7103);var o=i(2765),a=i(7683);i(2729);var n=i(2910),l=i(2715),d=i(1397);i(9816),i(430),i(5582);var c=i(3525),u=e([s,o,a,n,l,d,c]);[s,o,a,n,l,d,c]=u.then?(await u)():u,r()}catch(e){r(e)}})},9816(e,i,r){function s(e){for(let t=0;t<100;t++){let t=randomUUID().slice(0,8);if(!e.has(t))return t}return randomUUID()}function o(e){let t=`--${e.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`,i=join(getDefaultAgentDir(),"sessions",t);return existsSync(i)||mkdirSync(i,{recursive:!0}),i}function a(e){if(!existsSync(e))return[];let t=readFileSync(e,"utf8"),i=[];for(let e of t.trim().split("\n"))if(e.trim())try{let t=JSON.parse(e);i.push(t)}catch{}if(0===i.length)return i;let r=i[0];return"session"!==r.type||"string"!=typeof r.id?[]:i}function n(e){try{let t=openSync(e,"r"),i=Buffer.alloc(512),r=readSync(t,i,0,512,0);closeSync(t);let s=i.toString("utf8",0,r).split("\n")[0];if(!s)return!1;let o=JSON.parse(s);return"session"===o.type&&"string"==typeof o.id}catch{return!1}}function l(e){return"string"==typeof e.role&&"content"in e}async function d(e){try{let t,i=await readFile(e,"utf8"),r=[];for(let e of i.trim().split("\n"))if(e.trim())try{r.push(JSON.parse(e))}catch{}if(0===r.length)return null;let s=r[0];if("session"!==s.type)return null;let o=await stat(e),a=0,n="",d=[];for(let e of r){if("session_info"===e.type&&e.name&&(t=e.name.trim()),"message"!==e.type)continue;a++;let i=e.message;if(!l(i)||"user"!==i.role&&"assistant"!==i.role)continue;let r=function(e){let t=e.content;return"string"==typeof t?t:t.filter(e=>"text"===e.type).map(e=>e.text).join(" ")}(i);r&&(d.push(r),n||"user"!==i.role||(n=r))}let c="string"==typeof s.cwd?s.cwd:"",u=s.parentSession,p=function(e,t,i){let r=function(e){let t;for(let i of e){if("message"!==i.type)continue;let e=i.message;if(!l(e)||"user"!==e.role&&"assistant"!==e.role)continue;let r=e.timestamp;if("number"==typeof r){t=Math.max(t??0,r);continue}let s=i.timestamp;if("string"==typeof s){let e=new Date(s).getTime();Number.isNaN(e)||(t=Math.max(t??0,e))}}return t}(e);if("number"==typeof r&&r>0)return new Date(r);let s="string"==typeof t.timestamp?new Date(t.timestamp).getTime():NaN;return Number.isNaN(s)?i:new Date(s)}(r,s,o.mtime);return{path:e,id:s.id,cwd:c,name:t,parentSessionPath:u,created:new Date(s.timestamp),modified:p,messageCount:a,firstMessage:n||"(no messages)",allMessagesText:d.join(" ")}}catch{return null}}async function c(e,t,i=0,r){let s=[];if(!existsSync(e))return s;try{let o=(await readdir(e)).filter(e=>e.endsWith(".jsonl")).map(t=>join(e,t)),a=r??o.length,n=0;for(let e of(await Promise.all(o.map(async e=>{let r=await d(e);return n++,t?.(i+n,a),r}))))e&&s.push(e)}catch{}return s}t("crypto"),r(9896),r(1943),r(6928),r(7103),r(2729);class u{sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;fileEntries=[];byId=new Map;labelsById=new Map;leafId=null;constructor(e,t,i,r){this.cwd=e,this.sessionDir=t,this.persist=r,r&&t&&!existsSync(t)&&mkdirSync(t,{recursive:!0}),i?this.setSessionFile(i):this.newSession()}setSessionFile(e){if(this.sessionFile=resolve(e),existsSync(this.sessionFile)){var t;let e,i;if(this.fileEntries=a(this.sessionFile),0===this.fileEntries.length){let e=this.sessionFile;this.newSession(),this.sessionFile=e,this._rewriteFile(),this.flushed=!0;return}let r=this.fileEntries.find(e=>"session"===e.type);this.sessionId=r?.id??randomUUID(),e=(t=this.fileEntries).find(e=>"session"===e.type),!((i=e?.version??1)>=3)&&(i<2&&function(e){let t=new Set,i=null;for(let r of e){if("session"===r.type){r.version=2;continue}if(r.id=s(t),r.parentId=i,i=r.id,"compaction"===r.type&&"number"==typeof r.firstKeptEntryIndex){let t=e[r.firstKeptEntryIndex];t&&"session"!==t.type&&(r.firstKeptEntryId=t.id),delete r.firstKeptEntryIndex}}}(t),i<3&&function(e){for(let t of e){if("session"===t.type){t.version=3;continue}"message"===t.type&&t.message&&"hookMessage"===t.message.role&&(t.message.role="custom")}}(t),1)&&this._rewriteFile(),this._buildIndex(),this.flushed=!0}else{let e=this.sessionFile;this.newSession(),this.sessionFile=e}}newSession(e){this.sessionId=randomUUID();let t=new Date().toISOString(),i={type:"session",version:3,id:this.sessionId,timestamp:t,cwd:this.cwd,parentSession:e?.parentSession};if(this.fileEntries=[i],this.byId.clear(),this.labelsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let e=t.replace(/[:.]/g,"-");this.sessionFile=join(this.getSessionDir(),`${e}_${this.sessionId}.jsonl`)}return this.sessionFile}_buildIndex(){for(let e of(this.byId.clear(),this.labelsById.clear(),this.leafId=null,this.fileEntries))"session"!==e.type&&(this.byId.set(e.id,e),this.leafId=e.id,"label"===e.type&&(e.label?this.labelsById.set(e.targetId,e.label):this.labelsById.delete(e.targetId)))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let e=`${this.fileEntries.map(e=>JSON.stringify(e)).join("\n")}
|
|
3
|
-
|
|
4
|
-
`);
|
|
5
|
-
`)
|
|
6
|
-
`),
|
|
7
|
-
`);let e=r[r.
|
|
8
|
-
`),c.add(o.id),t.push(o),e=o.id}return this.fileEntries=[d,...r,...t],this.sessionId=o,this.sessionFile=l,this.flushed=!0,this._buildIndex(),l}let p=[],h=r[r.length-1]?.id||null;for(let{targetId:e,label:t}of u){let i={type:"label",id:s(new Set([...c,...p.map(e=>e.id)])),parentId:h,timestamp:new Date().toISOString(),targetId:e,label:t};p.push(i),h=i.id}this.fileEntries=[d,...r,...p],this.sessionId=o,this._buildIndex()}static create(e,t){let i=t??o(e);return new u(e,i,void 0,!0)}static open(e,t){let i=a(e).find(e=>"session"===e.type);return new u(i?.cwd??process.cwd(),t??resolve(e,".."),e,!0)}static continueRecent(e,t){let i=t??o(e),r=function(e){try{let t=readdirSync(e).filter(e=>e.endsWith(".jsonl")).map(t=>join(e,t)).filter(n).map(e=>({path:e,mtime:statSync(e).mtime})).sort((e,t)=>t.mtime.getTime()-e.mtime.getTime());return t[0]?.path||null}catch{return null}}(i);return r?new u(e,i,r,!0):new u(e,i,void 0,!0)}static inMemory(e=process.cwd()){return new u(e,"",void 0,!1)}static forkFrom(e,t,i){let r=a(e);if(0===r.length)throw Error(`Cannot fork: source session file is empty or invalid: ${e}`);if(!r.find(e=>"session"===e.type))throw Error(`Cannot fork: source session has no header: ${e}`);let s=i??o(t);existsSync(s)||mkdirSync(s,{recursive:!0});let n=randomUUID(),l=new Date().toISOString(),d=l.replace(/[:.]/g,"-"),c=join(s,`${d}_${n}.jsonl`);for(let i of(appendFileSync(c,`${JSON.stringify({type:"session",version:3,id:n,timestamp:l,cwd:t,parentSession:e})}
|
|
9
|
-
`),r))"session"!==i.type&&appendFileSync(c,`${JSON.stringify(i)}
|
|
10
|
-
`);return new u(t,s,c,!0)}static async list(e,t,i){let r=t??o(e),s=await c(r,i);return s.sort((e,t)=>t.modified.getTime()-e.modified.getTime()),s}static async listAll(e){let t=getSessionsDir();try{if(!existsSync(t))return[];let i=(await readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>join(t,e.name)),r=0,s=[];for(let e of i)try{let t=(await readdir(e)).filter(e=>e.endsWith(".jsonl"));s.push(t.map(t=>join(e,t))),r+=t.length}catch{s.push([])}let o=0,a=[],n=s.flat();for(let t of(await Promise.all(n.map(async t=>{let i=await d(t);return o++,e?.(o,r),i}))))t&&a.push(t);return a.sort((e,t)=>t.modified.getTime()-e.modified.getTime()),a}catch{return[]}}}},430(e,t,i){i.d(t,{V:()=>n});var r=i(9896),s=i(6928),o=i(7103);function a(e,t){let i={...e};for(let r of Object.keys(t)){let s=t[r],o=e[r];void 0!==s&&("object"!=typeof s||null===s||Array.isArray(s)||"object"!=typeof o||null===o||Array.isArray(o)?i[r]=s:i[r]={...o,...s})}return i}class n{settingsPath;projectSettingsPath;globalSettings;inMemoryProjectSettings;settings;persist;modifiedFields=new Set;modifiedNestedFields=new Map;globalSettingsLoadError=null;constructor(e,t,i,r,s=null){this.settingsPath=e,this.projectSettingsPath=t,this.persist=r,this.globalSettings=i,this.inMemoryProjectSettings={},this.globalSettingsLoadError=s;let o=this.loadProjectSettings();this.settings=a(this.globalSettings,o)}static create(e=process.cwd(),t=(0,o.$M)()){let i=(0,s.join)(t,"settings.json"),r=(0,s.join)(e,o.tb,"settings.json"),a={},l=null;try{a=n.loadFromFile(i)}catch(e){l=e,console.error(`Warning: Invalid JSON in ${i}: ${e}`),console.error("Fix the syntax error to enable settings persistence.")}return new n(i,r,a,!0,l)}static inMemory(e={}){return new n(null,null,e,!1)}static loadFromFile(e){if(!(0,r.existsSync)(e))return{};let t=JSON.parse((0,r.readFileSync)(e,"utf-8"));return n.migrateSettings(t)}static migrateSettings(e){if("queueMode"in e&&!("steeringMode"in e)&&(e.steeringMode=e.queueMode,delete e.queueMode),"skills"in e&&"object"==typeof e.skills&&null!==e.skills&&!Array.isArray(e.skills)){let t=e.skills;void 0!==t.enableSkillCommands&&void 0===e.enableSkillCommands&&(e.enableSkillCommands=t.enableSkillCommands),Array.isArray(t.customDirectories)&&t.customDirectories.length>0?e.skills=t.customDirectories:delete e.skills}return e}loadProjectSettings(){if(!this.persist)return structuredClone(this.inMemoryProjectSettings);if(!this.projectSettingsPath||!(0,r.existsSync)(this.projectSettingsPath))return{};try{let e=(0,r.readFileSync)(this.projectSettingsPath,"utf-8"),t=JSON.parse(e);return n.migrateSettings(t)}catch(e){return console.error(`Warning: Could not read project settings file: ${e}`),{}}}getGlobalSettings(){return structuredClone(this.globalSettings)}getProjectSettings(){return this.loadProjectSettings()}reload(){let e=null;if(this.persist&&this.settingsPath)try{e=n.loadFromFile(this.settingsPath),this.globalSettingsLoadError=null}catch(e){this.globalSettingsLoadError=e}e&&(this.globalSettings=e),this.modifiedFields.clear(),this.modifiedNestedFields.clear();let t=this.loadProjectSettings();this.settings=a(this.globalSettings,t)}applyOverrides(e){this.settings=a(this.settings,e)}markModified(e,t){this.modifiedFields.add(e),t&&(this.modifiedNestedFields.has(e)||this.modifiedNestedFields.set(e,new Set),this.modifiedNestedFields.get(e).add(t))}save(){if(this.persist&&this.settingsPath){if(this.globalSettingsLoadError){let e=this.loadProjectSettings();this.settings=a(this.globalSettings,e);return}try{let e=(0,s.dirname)(this.settingsPath);(0,r.existsSync)(e)||(0,r.mkdirSync)(e,{recursive:!0});let t=n.loadFromFile(this.settingsPath),i={...t};for(let e of this.modifiedFields){let r=this.globalSettings[e];if(this.modifiedNestedFields.has(e)&&"object"==typeof r&&null!==r){let s=this.modifiedNestedFields.get(e),o={...t[e]??{}};for(let e of s)o[e]=r[e];i[e]=o}else i[e]=r}this.globalSettings=i,(0,r.writeFileSync)(this.settingsPath,JSON.stringify(this.globalSettings,null,2),"utf-8")}catch(e){console.error(`Warning: Could not save settings file: ${e}`)}}let e=this.loadProjectSettings();this.settings=a(this.globalSettings,e)}saveProjectSettings(e){if(!this.persist){this.inMemoryProjectSettings=structuredClone(e);return}if(this.projectSettingsPath)try{let t=(0,s.dirname)(this.projectSettingsPath);(0,r.existsSync)(t)||(0,r.mkdirSync)(t,{recursive:!0}),(0,r.writeFileSync)(this.projectSettingsPath,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error(`Warning: Could not save project settings file: ${e}`)}}getLastChangelogVersion(){return this.settings.lastChangelogVersion}setLastChangelogVersion(e){this.globalSettings.lastChangelogVersion=e,this.markModified("lastChangelogVersion"),this.save()}getDefaultProvider(){return this.settings.defaultProvider}getDefaultModel(){return this.settings.defaultModel}setDefaultProvider(e){this.globalSettings.defaultProvider=e,this.markModified("defaultProvider"),this.save()}setDefaultModel(e){this.globalSettings.defaultModel=e,this.markModified("defaultModel"),this.save()}setDefaultModelAndProvider(e,t){this.globalSettings.defaultProvider=e,this.globalSettings.defaultModel=t,this.markModified("defaultProvider"),this.markModified("defaultModel"),this.save()}getSteeringMode(){return this.settings.steeringMode||"one-at-a-time"}setSteeringMode(e){this.globalSettings.steeringMode=e,this.markModified("steeringMode"),this.save()}getFollowUpMode(){return this.settings.followUpMode||"one-at-a-time"}setFollowUpMode(e){this.globalSettings.followUpMode=e,this.markModified("followUpMode"),this.save()}getTheme(){return this.settings.theme}setTheme(e){this.globalSettings.theme=e,this.markModified("theme"),this.save()}getDefaultThinkingLevel(){return this.settings.defaultThinkingLevel}setDefaultThinkingLevel(e){this.globalSettings.defaultThinkingLevel=e,this.markModified("defaultThinkingLevel"),this.save()}getCompactionEnabled(){return this.settings.compaction?.enabled??!0}setCompactionEnabled(e){this.globalSettings.compaction||(this.globalSettings.compaction={}),this.globalSettings.compaction.enabled=e,this.markModified("compaction","enabled"),this.save()}getCompactionReserveTokens(){return this.settings.compaction?.reserveTokens??16384}getCompactionKeepRecentTokens(){return this.settings.compaction?.keepRecentTokens??2e4}getCompactionSettings(){return{enabled:this.getCompactionEnabled(),reserveTokens:this.getCompactionReserveTokens(),keepRecentTokens:this.getCompactionKeepRecentTokens()}}getBranchSummarySettings(){return{reserveTokens:this.settings.branchSummary?.reserveTokens??16384}}getRetryEnabled(){return this.settings.retry?.enabled??!0}setRetryEnabled(e){this.globalSettings.retry||(this.globalSettings.retry={}),this.globalSettings.retry.enabled=e,this.markModified("retry","enabled"),this.save()}getRetrySettings(){return{enabled:this.getRetryEnabled(),maxRetries:this.settings.retry?.maxRetries??3,baseDelayMs:this.settings.retry?.baseDelayMs??2e3,maxDelayMs:this.settings.retry?.maxDelayMs??6e4}}getHideThinkingBlock(){return this.settings.hideThinkingBlock??!1}setHideThinkingBlock(e){this.globalSettings.hideThinkingBlock=e,this.markModified("hideThinkingBlock"),this.save()}getShellPath(){return this.settings.shellPath}setShellPath(e){this.globalSettings.shellPath=e,this.markModified("shellPath"),this.save()}getQuietStartup(){return this.settings.quietStartup??!1}setQuietStartup(e){this.globalSettings.quietStartup=e,this.markModified("quietStartup"),this.save()}getShellCommandPrefix(){return this.settings.shellCommandPrefix}setShellCommandPrefix(e){this.globalSettings.shellCommandPrefix=e,this.markModified("shellCommandPrefix"),this.save()}getCollapseChangelog(){return this.settings.collapseChangelog??!1}setCollapseChangelog(e){this.globalSettings.collapseChangelog=e,this.markModified("collapseChangelog"),this.save()}getPackages(){return[...this.settings.packages??[]]}setPackages(e){this.globalSettings.packages=e,this.markModified("packages"),this.save()}setProjectPackages(e){let t=this.loadProjectSettings();t.packages=e,this.saveProjectSettings(t),this.settings=a(this.globalSettings,t)}getExtensionPaths(){return[...this.settings.extensions??[]]}setExtensionPaths(e){this.globalSettings.extensions=e,this.markModified("extensions"),this.save()}setProjectExtensionPaths(e){let t=this.loadProjectSettings();t.extensions=e,this.saveProjectSettings(t),this.settings=a(this.globalSettings,t)}getSkillPaths(){return[...this.settings.skills??[]]}setSkillPaths(e){this.globalSettings.skills=e,this.markModified("skills"),this.save()}setProjectSkillPaths(e){let t=this.loadProjectSettings();t.skills=e,this.saveProjectSettings(t),this.settings=a(this.globalSettings,t)}getPromptTemplatePaths(){return[...this.settings.prompts??[]]}setPromptTemplatePaths(e){this.globalSettings.prompts=e,this.markModified("prompts"),this.save()}setProjectPromptTemplatePaths(e){let t=this.loadProjectSettings();t.prompts=e,this.saveProjectSettings(t),this.settings=a(this.globalSettings,t)}getThemePaths(){return[...this.settings.themes??[]]}setThemePaths(e){this.globalSettings.themes=e,this.markModified("themes"),this.save()}setProjectThemePaths(e){let t=this.loadProjectSettings();t.themes=e,this.saveProjectSettings(t),this.settings=a(this.globalSettings,t)}getEnableSkillCommands(){return this.settings.enableSkillCommands??!0}setEnableSkillCommands(e){this.globalSettings.enableSkillCommands=e,this.markModified("enableSkillCommands"),this.save()}getThinkingBudgets(){return this.settings.thinkingBudgets}getShowImages(){return this.settings.terminal?.showImages??!0}setShowImages(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.showImages=e,this.markModified("terminal","showImages"),this.save()}getClearOnShrink(){return this.settings.terminal?.clearOnShrink!==void 0?this.settings.terminal.clearOnShrink:"1"===process.env.PI_CLEAR_ON_SHRINK}setClearOnShrink(e){this.globalSettings.terminal||(this.globalSettings.terminal={}),this.globalSettings.terminal.clearOnShrink=e,this.markModified("terminal","clearOnShrink"),this.save()}getImageAutoResize(){return this.settings.images?.autoResize??!0}setImageAutoResize(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.autoResize=e,this.markModified("images","autoResize"),this.save()}getBlockImages(){return this.settings.images?.blockImages??!1}setBlockImages(e){this.globalSettings.images||(this.globalSettings.images={}),this.globalSettings.images.blockImages=e,this.markModified("images","blockImages"),this.save()}getEnabledModels(){return this.settings.enabledModels}setEnabledModels(e){this.globalSettings.enabledModels=e,this.markModified("enabledModels"),this.save()}getDoubleEscapeAction(){return this.settings.doubleEscapeAction??"tree"}setDoubleEscapeAction(e){this.globalSettings.doubleEscapeAction=e,this.markModified("doubleEscapeAction"),this.save()}getShowHardwareCursor(){return this.settings.showHardwareCursor??"1"===process.env.PI_HARDWARE_CURSOR}setShowHardwareCursor(e){this.globalSettings.showHardwareCursor=e,this.markModified("showHardwareCursor"),this.save()}getEditorPaddingX(){return this.settings.editorPaddingX??0}setEditorPaddingX(e){this.globalSettings.editorPaddingX=Math.max(0,Math.min(3,Math.floor(e))),this.markModified("editorPaddingX"),this.save()}getAutocompleteMaxVisible(){return this.settings.autocompleteMaxVisible??5}setAutocompleteMaxVisible(e){this.globalSettings.autocompleteMaxVisible=Math.max(3,Math.min(20,Math.floor(e))),this.markModified("autocompleteMaxVisible"),this.save()}getCodeBlockIndent(){return this.settings.markdown?.codeBlockIndent??" "}}},5039(e,t,i){i.a(e,async function(e,r){try{i.d(t,{UI:()=>c,lg:()=>u});var s=i(9896),o=i(4261);i(857);var a=i(6928);i(7103);var n=i(1957),l=e([o,n]);[o,n]=l.then?(await l)():l;let h=[".gitignore",".ignore",".fdignore"];function d(e){return e.split(a.sep).join("/")}function c(e){let{dir:t,source:i}=e;return function e(t,i,r,l,c){let u=[],p=[];if(!(0,s.existsSync)(t))return{skills:u,diagnostics:p};let m=c??t,g=l??(0,o.default)(),f=(0,a.relative)(m,t),w=f?`${d(f)}/`:"";for(let e of h){let i=(0,a.join)(t,e);if((0,s.existsSync)(i))try{let e=(0,s.readFileSync)(i,"utf-8").split(/\r?\n/).map(e=>(function(e,t){let i=e.trim();if(!i||i.startsWith("#")&&!i.startsWith("\\#"))return null;let r=e,s=!1;r.startsWith("!")?(s=!0,r=r.slice(1)):r.startsWith("\\!")&&(r=r.slice(1)),r.startsWith("/")&&(r=r.slice(1));let o=t?`${t}${r}`:r;return s?`!${o}`:o})(e,w)).filter(e=>!!e);e.length>0&&g.add(e)}catch{}}try{for(let o of(0,s.readdirSync)(t,{withFileTypes:!0})){if(o.name.startsWith(".")||"node_modules"===o.name)continue;let l=(0,a.join)(t,o.name),c=o.isDirectory(),h=o.isFile();if(o.isSymbolicLink())try{let e=(0,s.statSync)(l);c=e.isDirectory(),h=e.isFile()}catch{continue}let f=d((0,a.relative)(m,l)),w=c?`${f}/`:f;if(g.ignores(w))continue;if(c){let t=e(l,i,!1,g,m);u.push(...t.skills),p.push(...t.diagnostics);continue}if(!h)continue;let k=r&&o.name.endsWith(".md"),y=!r&&"SKILL.md"===o.name;if(!k&&!y)continue;let v=function(e,t){let i=[];try{var r;let o,l,d=(0,s.readFileSync)(e,"utf-8"),{frontmatter:c}=(0,n.y)(d),u=(0,a.dirname)(e),p=(0,a.basename)(u);for(let t of(r=c.description,o=[],r&&""!==r.trim()?r.length>1024&&o.push(`description exceeds 1024 characters (${r.length})`):o.push("description is required"),o))i.push({type:"warning",message:t,path:e});let h=c.name||p;for(let t of(l=[],h!==p&&l.push(`name "${h}" does not match parent directory "${p}"`),h.length>64&&l.push(`name exceeds 64 characters (${h.length})`),/^[a-z0-9-]+$/.test(h)||l.push("name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)"),(h.startsWith("-")||h.endsWith("-"))&&l.push("name must not start or end with a hyphen"),h.includes("--")&&l.push("name must not contain consecutive hyphens"),l))i.push({type:"warning",message:t,path:e});if(!c.description||""===c.description.trim())return{skill:null,diagnostics:i};return{skill:{name:h,description:c.description,filePath:e,baseDir:u,source:t,disableModelInvocation:!0===c["disable-model-invocation"]},diagnostics:i}}catch(r){let t=r instanceof Error?r.message:"failed to parse skill file";return i.push({type:"warning",message:t,path:e}),{skill:null,diagnostics:i}}}(l,i);v.skill&&u.push(v.skill),p.push(...v.diagnostics)}}catch{}return{skills:u,diagnostics:p}}(t,i,!0)}function u(e){let t=e.filter(e=>!e.disableModelInvocation);if(0===t.length)return"";let i=["\n\nThe following skills provide specialized instructions for specific tasks.","Use the read tool to load a skill's file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>"];for(let e of t)i.push(" <skill>"),i.push(` <name>${p(e.name)}</name>`),i.push(` <description>${p(e.description)}</description>`),i.push(` <location>${p(e.filePath)}</location>`),i.push(" </skill>");return i.push("</available_skills>"),i.join("\n")}function p(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}r()}catch(e){r(e)}})},7775(e,t,i){i.a(e,async function(e,t){try{i(7103);var r=i(5039),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},5582(){process.env.PI_TIMING,Date.now()},843(e,t,i){i.a(e,async function(e,r){try{i.d(t,{n:()=>f,r:()=>h});var s=i(7598),o=i(3024),a=i(8161),n=i(6760),l=i(4204),d=i(5317),c=i(3409),u=i(7939),p=e([l]);let m=(l=(p.then?(await p)():p)[0]).Type.Object({command:l.Type.String({description:"Bash command to execute"}),timeout:l.Type.Optional(l.Type.Number({description:"Timeout in seconds (optional, no default timeout)"}))}),g={exec:(e,t,{onData:i,signal:r,timeout:s,env:a})=>new Promise((n,l)=>{let u,{shell:p,args:h}=(0,c.lG)();if(!(0,o.existsSync)(t))return void l(Error(`Working directory does not exist: ${t}
|
|
11
|
-
Cannot execute bash commands.`));let m=(0,d.spawn)(p,[...h,e],{cwd:t,detached:!0,env:a??(0,c.yJ)(),stdio:["ignore","pipe","pipe"]}),g=!1;void 0!==s&&s>0&&(u=setTimeout(()=>{g=!0,m.pid&&(0,c.g8)(m.pid)},1e3*s)),m.stdout&&m.stdout.on("data",i),m.stderr&&m.stderr.on("data",i),m.on("error",e=>{u&&clearTimeout(u),r&&r.removeEventListener("abort",f),l(e)});let f=()=>{m.pid&&(0,c.g8)(m.pid)};r&&(r.aborted?f():r.addEventListener("abort",f,{once:!0})),m.on("close",e=>{(u&&clearTimeout(u),r&&r.removeEventListener("abort",f),r?.aborted)?l(Error("aborted")):g?l(Error(`timeout:${s}`)):n({exitCode:e})})})};function h(e,t){let i=t?.operations??g,r=t?.commandPrefix,l=t?.spawnHook;return{name:"bash",label:"bash",description:"Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last 2000 lines or 50KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.",parameters:m,execute:async(t,{command:d,timeout:p},h,m)=>{var g;let f,w=(g=r?`${r}
|
|
12
|
-
${d}`:d,f={command:g,cwd:e,env:{...(0,c.yJ)()}},l?l(f):f);return new Promise((e,t)=>{let r,l,d=0,c=[],g=0;i.exec(w.command,w.cwd,{onData:e=>{if((d+=e.length)>51200&&!r){let e;for(let t of(e=(0,s.randomBytes)(8).toString("hex"),r=(0,n.join)((0,a.tmpdir)(),`pi-bash-${e}.log`),l=(0,o.createWriteStream)(r),c))l.write(t)}for(l&&l.write(e),c.push(e),g+=e.length;g>102400&&c.length>1;){let e=c.shift();g-=e.length}if(m){let e=Buffer.concat(c).toString("utf-8"),t=(0,u.Zo)(e);m({content:[{type:"text",text:t.content||""}],details:{truncation:t.truncated?t:void 0,fullOutputPath:r}})}},signal:h,timeout:p,env:w.env}).then(({exitCode:i})=>{let s;l&&l.end();let o=Buffer.concat(c).toString("utf-8"),a=(0,u.Zo)(o),n=a.content||"(no output)";if(a.truncated){s={truncation:a,fullOutputPath:r};let e=a.totalLines-a.outputLines+1,t=a.totalLines;if(a.lastLinePartial){let e=(0,u.Xq)(Buffer.byteLength(o.split("\n").pop()||"","utf-8"));n+=`
|
|
13
|
-
|
|
14
|
-
[Showing last ${(0,u.Xq)(a.outputBytes)} of line ${t} (line is ${e}). Full output: ${r}]`}else"lines"===a.truncatedBy?n+=`
|
|
15
|
-
|
|
16
|
-
[Showing lines ${e}-${t} of ${a.totalLines}. Full output: ${r}]`:n+=`
|
|
17
|
-
|
|
18
|
-
[Showing lines ${e}-${t} of ${a.totalLines} (${(0,u.Xq)(51200)} limit). Full output: ${r}]`}0!==i&&null!==i?(n+=`
|
|
19
|
-
|
|
20
|
-
Command exited with code ${i}`,t(Error(n))):e({content:[{type:"text",text:n}],details:s})}).catch(e=>{l&&l.end();let i=Buffer.concat(c).toString("utf-8");if("aborted"===e.message)i&&(i+="\n\n"),i+="Command aborted",t(Error(i));else if(e.message.startsWith("timeout:")){let r=e.message.split(":")[1];i&&(i+="\n\n"),i+=`Command timed out after ${r} seconds`,t(Error(i))}else t(e)})})}}}let f=h(process.cwd());r()}catch(e){r(e)}})},4517(e,t,i){i.a(e,async function(e,r){try{i.d(t,{CZ:()=>p,F8:()=>m,NF:()=>d,Nw:()=>u,Uv:()=>g,Vb:()=>c,Vf:()=>h,vp:()=>f});var s=i(8188),o=i(9896),a=i(1943),n=i(5374),l=e([s]);function d(e){let t=e.indexOf("\r\n"),i=e.indexOf("\n");return -1===i||-1===t?"\n":t<i?"\r\n":"\n"}function c(e){return e.replace(/\r\n/g,"\n").replace(/\r/g,"\n")}function u(e,t){return"\r\n"===t?e.replace(/\n/g,"\r\n"):e}function p(e){return e.split("\n").map(e=>e.trimEnd()).join("\n").replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function h(e,t){let i=e.indexOf(t);if(-1!==i)return{found:!0,index:i,matchLength:t.length,usedFuzzyMatch:!1,contentForReplacement:e};let r=p(e),s=p(t),o=r.indexOf(s);return -1===o?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:e}:{found:!0,index:o,matchLength:s.length,usedFuzzyMatch:!0,contentForReplacement:r}}function m(e){return e.startsWith("\uFEFF")?{bom:"\uFEFF",text:e.slice(1)}:{bom:"",text:e}}function g(e,t,i=4){let r,o=s.diffLines(e,t),a=[],n=e.split("\n"),l=t.split("\n"),d=Math.max(n.length,l.length),c=String(d).length,u=1,p=1,h=!1;for(let e=0;e<o.length;e++){let t=o[e],s=t.value.split("\n");if(""===s[s.length-1]&&s.pop(),t.added||t.removed){for(let e of(void 0===r&&(r=p),s))if(t.added){let t=String(p).padStart(c," ");a.push(`+${t} ${e}`),p++}else{let t=String(u).padStart(c," ");a.push(`-${t} ${e}`),u++}h=!0}else{let t=e<o.length-1&&(o[e+1].added||o[e+1].removed);if(h||t){let e=s,r=0,o=0;for(let n of(h||(r=Math.max(0,s.length-i),e=s.slice(r)),!t&&e.length>i&&(o=e.length-i,e=e.slice(0,i)),r>0&&(a.push(` ${"".padStart(c," ")} ...`),u+=r,p+=r),e)){let e=String(u).padStart(c," ");a.push(` ${e} ${n}`),u++,p++}o>0&&(a.push(` ${"".padStart(c," ")} ...`),u+=o,p+=o)}else u+=s.length,p+=s.length;h=!1}}return{diff:a.join("\n"),firstChangedLine:r}}async function f(e,t,i,r){let s=(0,n.wT)(e,r);try{try{await (0,a.access)(s,o.constants.R_OK)}catch{return{error:`File not found: ${e}`}}let r=await (0,a.readFile)(s,"utf-8"),{text:n}=m(r),l=c(n),d=c(t),u=c(i),f=h(l,d);if(!f.found)return{error:`Could not find the exact text in ${e}. The old text must match exactly including all whitespace and newlines.`};let w=p(l),k=p(d),y=w.split(k).length-1;if(y>1)return{error:`Found ${y} occurrences of the text in ${e}. The text must be unique. Please provide more context to make it unique.`};let v=f.contentForReplacement,b=v.substring(0,f.index)+u+v.substring(f.index+f.matchLength);if(v===b)return{error:`No changes would be made to ${e}. The replacement produces identical content.`};return g(v,b)}catch(e){return{error:e instanceof Error?e.message:String(e)}}}s=(l.then?(await l)():l)[0],r()}catch(e){r(e)}})},3773(e,t,i){i.a(e,async function(e,r){try{i.d(t,{J:()=>c,z:()=>h});var s=i(4204),o=i(9896),a=i(1943),n=i(4517),l=i(5374),d=e([s,n]);[s,n]=d.then?(await d)():d;let u=s.Type.Object({path:s.Type.String({description:"Path to the file to edit (relative or absolute)"}),oldText:s.Type.String({description:"Exact text to find and replace (must match exactly)"}),newText:s.Type.String({description:"New text to replace the old text with"})}),p={readFile:e=>(0,a.readFile)(e),writeFile:(e,t)=>(0,a.writeFile)(e,t,"utf-8"),access:e=>(0,a.access)(e,o.constants.R_OK|o.constants.W_OK)};function c(e,t){let i=t?.operations??p;return{name:"edit",label:"edit",description:"Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",parameters:u,execute:async(t,{path:r,oldText:s,newText:o},a)=>{let d=(0,l.wT)(r,e);return new Promise((e,t)=>{if(a?.aborted)return void t(Error("Operation aborted"));let l=!1,c=()=>{l=!0,t(Error("Operation aborted"))};a&&a.addEventListener("abort",c,{once:!0}),(async()=>{try{try{await i.access(d)}catch{a&&a.removeEventListener("abort",c),t(Error(`File not found: ${r}`));return}if(l)return;let u=(await i.readFile(d)).toString("utf-8");if(l)return;let{bom:p,text:h}=(0,n.F8)(u),m=(0,n.NF)(h),g=(0,n.Vb)(h),f=(0,n.Vb)(s),w=(0,n.Vb)(o),k=(0,n.Vf)(g,f);if(!k.found){a&&a.removeEventListener("abort",c),t(Error(`Could not find the exact text in ${r}. The old text must match exactly including all whitespace and newlines.`));return}let y=(0,n.CZ)(g),v=(0,n.CZ)(f),b=y.split(v).length-1;if(b>1){a&&a.removeEventListener("abort",c),t(Error(`Found ${b} occurrences of the text in ${r}. The text must be unique. Please provide more context to make it unique.`));return}if(l)return;let S=k.contentForReplacement,T=S.substring(0,k.index)+w+S.substring(k.index+k.matchLength);if(S===T){a&&a.removeEventListener("abort",c),t(Error(`No changes made to ${r}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`));return}let C=p+(0,n.Nw)(T,m);if(await i.writeFile(d,C),l)return;a&&a.removeEventListener("abort",c);let E=(0,n.Uv)(S,T);e({content:[{type:"text",text:`Successfully replaced text in ${r}.`}],details:{diff:E.diff,firstChangedLine:E.firstChangedLine}})}catch(e){a&&a.removeEventListener("abort",c),l||t(e)}})()})}}}let h=c(process.cwd());r()}catch(e){r(e)}})},8378(e,t,i){i.a(e,async function(e,r){try{i.d(t,{S:()=>f,a:()=>h});var s=i(4204),o=i(5317),a=i(9896),n=i(5213),l=i(6928),d=i(7614),c=i(5374),u=i(7939),p=e([s,d,n]);[s,d,n]=p.then?(await p)():p;let m=s.Type.Object({pattern:s.Type.String({description:"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"}),path:s.Type.Optional(s.Type.String({description:"Directory to search in (default: current directory)"})),limit:s.Type.Optional(s.Type.Number({description:"Maximum number of results (default: 1000)"}))}),g={exists:a.existsSync,glob:(e,t,i)=>[]};function h(e,t){let i=t?.operations;return{name:"find",label:"find",description:"Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to 1000 results or 50KB (whichever is hit first).",parameters:m,execute:async(t,{pattern:r,path:s,limit:p},h)=>new Promise((t,m)=>{if(h?.aborted)return void m(Error("Operation aborted"));let f=()=>m(Error("Operation aborted"));h?.addEventListener("abort",f,{once:!0}),(async()=>{try{let w=(0,c.wT)(s||".",e),k=p??1e3,y=i??g;if(i?.glob){if(!await y.exists(w))return void m(Error(`Path not found: ${w}`));let e=await y.glob(r,w,{ignore:["**/node_modules/**","**/.git/**"],limit:k});if(h?.removeEventListener("abort",f),0===e.length)return void t({content:[{type:"text",text:"No files found matching pattern"}],details:void 0});let i=e.map(e=>e.startsWith(w)?e.slice(w.length+1):l.relative(w,e)),s=i.length>=k,o=i.join("\n"),a=(0,u.vB)(o,{maxLines:Number.MAX_SAFE_INTEGER}),n=a.content,d={},c=[];s&&(c.push(`${k} results limit reached`),d.resultLimitReached=k),a.truncated&&(c.push(`${(0,u.Xq)(51200)} limit reached`),d.truncation=a),c.length>0&&(n+=`
|
|
21
|
-
|
|
22
|
-
[${c.join(". ")}]`),t({content:[{type:"text",text:n}],details:Object.keys(d).length>0?d:void 0});return}let v=await (0,d.r)("fd",!0);if(!v)return void m(Error("fd is not available and could not be downloaded"));let b=["--glob","--color=never","--hidden","--max-results",String(k)],S=new Set,T=l.join(w,".gitignore");(0,a.existsSync)(T)&&S.add(T);try{for(let e of(0,n.globSync)("**/.gitignore",{cwd:w,dot:!0,absolute:!0,ignore:["**/node_modules/**","**/.git/**"]}))S.add(e)}catch{}for(let e of S)b.push("--ignore-file",e);b.push(r,w);let C=(0,o.spawnSync)(v,b,{encoding:"utf-8",maxBuffer:0xa00000});if(h?.removeEventListener("abort",f),C.error)return void m(Error(`Failed to run fd: ${C.error.message}`));let E=C.stdout?.trim()||"";if(0!==C.status){let e=C.stderr?.trim()||`fd exited with code ${C.status}`;if(!E)return void m(Error(e))}if(!E)return void t({content:[{type:"text",text:"No files found matching pattern"}],details:void 0});let x=E.split("\n"),I=[];for(let e of x){let t=e.replace(/\r$/,"").trim();if(!t)continue;let i=t.endsWith("/")||t.endsWith("\\"),r=t;r=t.startsWith(w)?t.slice(w.length+1):l.relative(w,t),i&&!r.endsWith("/")&&(r+="/"),I.push(r)}let A=I.length>=k,O=I.join("\n"),P=(0,u.vB)(O,{maxLines:Number.MAX_SAFE_INTEGER}),R=P.content,M={},L=[];A&&(L.push(`${k} results limit reached. Use limit=${2*k} for more, or refine pattern`),M.resultLimitReached=k),P.truncated&&(L.push(`${(0,u.Xq)(51200)} limit reached`),M.truncation=P),L.length>0&&(R+=`
|
|
23
|
-
|
|
24
|
-
[${L.join(". ")}]`),t({content:[{type:"text",text:R}],details:Object.keys(M).length>0?M:void 0})}catch(e){h?.removeEventListener("abort",f),m(e)}})()})}}let f=h(process.cwd());r()}catch(e){r(e)}})},4169(e,t,i){i.a(e,async function(e,r){try{i.d(t,{F:()=>h,L:()=>f});var s=i(481),o=i(4204),a=i(5317),n=i(9896),l=i(6928),d=i(7614),c=i(5374),u=i(7939),p=e([o,d]);[o,d]=p.then?(await p)():p;let m=o.Type.Object({pattern:o.Type.String({description:"Search pattern (regex or literal string)"}),path:o.Type.Optional(o.Type.String({description:"Directory or file to search (default: current directory)"})),glob:o.Type.Optional(o.Type.String({description:"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'"})),ignoreCase:o.Type.Optional(o.Type.Boolean({description:"Case-insensitive search (default: false)"})),literal:o.Type.Optional(o.Type.Boolean({description:"Treat pattern as literal string instead of regex (default: false)"})),context:o.Type.Optional(o.Type.Number({description:"Number of lines to show before and after each match (default: 0)"})),limit:o.Type.Optional(o.Type.Number({description:"Maximum number of matches to return (default: 100)"}))}),g={isDirectory:e=>(0,n.statSync)(e).isDirectory(),readFile:e=>(0,n.readFileSync)(e,"utf-8")};function h(e,t){let i=t?.operations;return{name:"grep",label:"grep",description:"Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to 100 matches or 50KB (whichever is hit first). Long lines are truncated to 500 chars.",parameters:m,execute:async(t,{pattern:r,path:o,glob:n,ignoreCase:p,literal:h,context:m,limit:f},w)=>new Promise((t,k)=>{if(w?.aborted)return void k(Error("Operation aborted"));let y=!1,v=e=>{y||(y=!0,e())};(async()=>{try{let y,b=await (0,d.r)("rg",!0);if(!b)return void v(()=>k(Error("ripgrep (rg) is not available and could not be downloaded")));let S=(0,c.wT)(o||".",e),T=i??g;try{y=await T.isDirectory(S)}catch(e){v(()=>k(Error(`Path not found: ${S}`)));return}let C=m&&m>0?m:0,E=Math.max(1,f??100),x=new Map,I=async e=>{let t=x.get(e);if(!t){try{t=(await T.readFile(e)).replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n")}catch{t=[]}x.set(e,t)}return t},A=["--json","--line-number","--color=never","--hidden"];p&&A.push("--ignore-case"),h&&A.push("--fixed-strings"),n&&A.push("--glob",n),A.push(r,S);let O=(0,a.spawn)(b,A,{stdio:["ignore","pipe","pipe"]}),P=(0,s.createInterface)({input:O.stdout}),R="",M=0,L=!1,N=!1,D=!1,_=!1,F=[],H=()=>{P.close(),w?.removeEventListener("abort",j)},$=(e=!1)=>{O.killed||(_=e,O.kill())},j=()=>{D=!0,$()};w?.addEventListener("abort",j,{once:!0}),O.stderr?.on("data",e=>{R+=e.toString()});let z=async(e,t)=>{let i=(e=>{if(y){let t=l.relative(S,e);if(t&&!t.startsWith(".."))return t.replace(/\\/g,"/")}return l.basename(e)})(e),r=await I(e);if(!r.length)return[`${i}:${t}: (unable to read file)`];let s=[],o=C>0?Math.max(1,t-C):t,a=C>0?Math.min(r.length,t+C):t;for(let e=o;e<=a;e++){let o=(r[e-1]??"").replace(/\r/g,""),a=e===t,{text:n,wasTruncated:l}=(0,u.rT)(o);l&&(N=!0),a?s.push(`${i}:${e}: ${n}`):s.push(`${i}-${e}- ${n}`)}return s},U=[];P.on("line",e=>{let t;if(e.trim()&&!(M>=E)){try{t=JSON.parse(e)}catch{return}if("match"===t.type){M++;let e=t.data?.path?.text,i=t.data?.line_number;e&&"number"==typeof i&&U.push({filePath:e,lineNumber:i}),M>=E&&(L=!0,$(!0))}}}),O.on("error",e=>{H(),v(()=>k(Error(`Failed to run ripgrep: ${e.message}`)))}),O.on("close",async e=>{if(H(),D)return void v(()=>k(Error("Operation aborted")));if(!_&&0!==e&&1!==e){let t=R.trim()||`ripgrep exited with code ${e}`;v(()=>k(Error(t)));return}if(0===M)return void v(()=>t({content:[{type:"text",text:"No matches found"}],details:void 0}));for(let e of U){let t=await z(e.filePath,e.lineNumber);F.push(...t)}let i=F.join("\n"),r=(0,u.vB)(i,{maxLines:Number.MAX_SAFE_INTEGER}),s=r.content,o={},a=[];L&&(a.push(`${E} matches limit reached. Use limit=${2*E} for more, or refine pattern`),o.matchLimitReached=E),r.truncated&&(a.push(`${(0,u.Xq)(51200)} limit reached`),o.truncation=r),N&&(a.push("Some lines truncated to 500 chars. Use read tool to see full lines"),o.linesTruncated=!0),a.length>0&&(s+=`
|
|
25
|
-
|
|
26
|
-
[${a.join(". ")}]`),v(()=>t({content:[{type:"text",text:s}],details:Object.keys(o).length>0?o:void 0}))})}catch(e){v(()=>k(e))}})()})}}let f=h(process.cwd());r()}catch(e){r(e)}})},3525(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Fl:()=>n.F,G3:()=>p,JD:()=>o.J,XU:()=>h,a2:()=>a.a,ij:()=>l.i,rJ:()=>s.r,xH:()=>d.x,yZ:()=>c.y});var s=i(843),o=i(3773),a=i(8378),n=i(4169),l=i(2964),d=i(4737),c=i(770),u=e([n,a,l,d,s,o,c]);[n,a,l,d,s,o,c]=u.then?(await u)():u;let h={read:d.X,bash:s.n,edit:o.z,write:c.E,grep:n.L,find:a.S,ls:l.c};function p(e,t){return[(0,d.x)(e,t?.read),(0,s.r)(e,t?.bash),(0,o.J)(e),(0,c.y)(e)]}r()}catch(e){r(e)}})},2964(e,t,i){i.a(e,async function(e,r){try{i.d(t,{c:()=>h,i:()=>c});var s=i(4204),o=i(9896),a=i(6928),n=i(5374),l=i(7939),d=e([s]);let u=(s=(d.then?(await d)():d)[0]).Type.Object({path:s.Type.Optional(s.Type.String({description:"Directory to list (default: current directory)"})),limit:s.Type.Optional(s.Type.Number({description:"Maximum number of entries to return (default: 500)"}))}),p={exists:o.existsSync,stat:o.statSync,readdir:o.readdirSync};function c(e,t){let i=t?.operations??p;return{name:"ls",label:"ls",description:"List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to 500 entries or 50KB (whichever is hit first).",parameters:u,execute:async(t,{path:r,limit:s},o)=>new Promise((t,d)=>{if(o?.aborted)return void d(Error("Operation aborted"));let c=()=>d(Error("Operation aborted"));o?.addEventListener("abort",c,{once:!0}),(async()=>{try{let u,p=(0,n.wT)(r||".",e),h=s??500;if(!await i.exists(p))return void d(Error(`Path not found: ${p}`));if(!(await i.stat(p)).isDirectory())return void d(Error(`Not a directory: ${p}`));try{u=await i.readdir(p)}catch(e){d(Error(`Cannot read directory: ${e.message}`));return}u.sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase()));let m=[],g=!1;for(let e of u){if(m.length>=h){g=!0;break}let t=a.join(p,e),r="";try{(await i.stat(t)).isDirectory()&&(r="/")}catch{continue}m.push(e+r)}if(o?.removeEventListener("abort",c),0===m.length)return void t({content:[{type:"text",text:"(empty directory)"}],details:void 0});let f=m.join("\n"),w=(0,l.vB)(f,{maxLines:Number.MAX_SAFE_INTEGER}),k=w.content,y={},v=[];g&&(v.push(`${h} entries limit reached. Use limit=${2*h} for more`),y.entryLimitReached=h),w.truncated&&(v.push(`${(0,l.Xq)(51200)} limit reached`),y.truncation=w),v.length>0&&(k+=`
|
|
27
|
-
|
|
28
|
-
[${v.join(". ")}]`),t({content:[{type:"text",text:k}],details:Object.keys(y).length>0?y:void 0})}catch(e){o?.removeEventListener("abort",c),d(e)}})()})}}let h=c(process.cwd());r()}catch(e){r(e)}})},5374(e,t,i){i.d(t,{sT:()=>c,wT:()=>d});var r=i(3024),s=i(8161),o=i(6760);let a=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function n(e){return e.replace(/'/g,"’")}function l(e){try{return(0,r.accessSync)(e,r.constants.F_OK),!0}catch{return!1}}function d(e,t){let i=function(e){let t=(e.startsWith("@")?e.slice(1):e).replace(a," ");return"~"===t?s.homedir():t.startsWith("~/")?s.homedir()+t.slice(1):t}(e);return(0,o.isAbsolute)(i)?i:(0,o.resolve)(t,i)}function c(e,t){let i=d(e,t);if(l(i))return i;let r=i.replace(/ (AM|PM)\./g," $1.");if(r!==i&&l(r))return r;let s=i.normalize("NFD");if(s!==i&&l(s))return s;let o=n(i);if(o!==i&&l(o))return o;let a=n(s);return a!==i&&l(a)?a:i}},4737(e,t,i){i.a(e,async function(e,r){try{i.d(t,{X:()=>g,x:()=>p});var s=i(4204),o=i(9896),a=i(1943),n=i(7635),l=i(4459),d=i(5374),c=i(7939),u=e([s,l]);[s,l]=u.then?(await u)():u;let h=s.Type.Object({path:s.Type.String({description:"Path to the file to read (relative or absolute)"}),offset:s.Type.Optional(s.Type.Number({description:"Line number to start reading from (1-indexed)"})),limit:s.Type.Optional(s.Type.Number({description:"Maximum number of lines to read"}))}),m={readFile:e=>(0,a.readFile)(e),access:e=>(0,a.access)(e,o.constants.R_OK),detectImageMimeType:l.r};function p(e,t){let i=t?.autoResizeImages??!0,r=t?.operations??m;return{name:"read",label:"read",description:"Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to 2000 lines or 50KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.",parameters:h,execute:async(t,{path:s,offset:o,limit:a},l)=>{let u=(0,d.sT)(s,e);return new Promise((e,t)=>{if(l?.aborted)return void t(Error("Operation aborted"));let d=!1,p=()=>{d=!0,t(Error("Operation aborted"))};l&&l.addEventListener("abort",p,{once:!0}),(async()=>{try{let t,h;if(await r.access(u),d)return;let m=r.detectImageMimeType?await r.detectImageMimeType(u):void 0;if(m){let e=(await r.readFile(u)).toString("base64");if(i){let i=await (0,n.y)({type:"image",data:e,mimeType:m}),r=(0,n.u)(i),s=`Read image file [${i.mimeType}]`;r&&(s+=`
|
|
29
|
-
${r}`),t=[{type:"text",text:s},{type:"image",data:i.data,mimeType:i.mimeType}]}else{let i=`Read image file [${m}]`;t=[{type:"text",text:i},{type:"image",data:e,mimeType:m}]}}else{let e,i,n,l=(await r.readFile(u)).toString("utf-8").split("\n"),d=l.length,p=o?Math.max(0,o-1):0,m=p+1;if(p>=l.length)throw Error(`Offset ${o} is beyond end of file (${l.length} lines total)`);if(void 0!==a){let t=Math.min(p+a,l.length);e=l.slice(p,t).join("\n"),i=t-p}else e=l.slice(p).join("\n");let g=(0,c.vB)(e);if(g.firstLineExceedsLimit){let e=(0,c.Xq)(Buffer.byteLength(l[p],"utf-8"));n=`[Line ${m} is ${e}, exceeds ${(0,c.Xq)(51200)} limit. Use bash: sed -n '${m}p' ${s} | head -c 51200]`,h={truncation:g}}else if(g.truncated){let e=m+g.outputLines-1,t=e+1;n=g.content,"lines"===g.truncatedBy?n+=`
|
|
30
|
-
|
|
31
|
-
[Showing lines ${m}-${e} of ${d}. Use offset=${t} to continue.]`:n+=`
|
|
32
|
-
|
|
33
|
-
[Showing lines ${m}-${e} of ${d} (${(0,c.Xq)(51200)} limit). Use offset=${t} to continue.]`,h={truncation:g}}else if(void 0!==i&&p+i<l.length){let e=l.length-(p+i),t=p+i+1;n=g.content+`
|
|
34
|
-
|
|
35
|
-
[${e} more lines in file. Use offset=${t} to continue.]`}else n=g.content;t=[{type:"text",text:n}]}if(d)return;l&&l.removeEventListener("abort",p),e({content:t,details:h})}catch(e){l&&l.removeEventListener("abort",p),d||t(e)}})()})}}}let g=p(process.cwd());r()}catch(e){r(e)}})},7939(e,t,i){function r(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function s(e,t={}){let i=t.maxLines??2e3,r=t.maxBytes??51200,o=Buffer.byteLength(e,"utf-8"),a=e.split("\n"),n=a.length;if(n<=i&&o<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:n,totalBytes:o,outputLines:n,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:i,maxBytes:r};if(Buffer.byteLength(a[0],"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:n,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:i,maxBytes:r};let l=[],d=0,c="lines";for(let e=0;e<a.length&&e<i;e++){let t=a[e],i=Buffer.byteLength(t,"utf-8")+ +(e>0);if(d+i>r){c="bytes";break}l.push(t),d+=i}l.length>=i&&d<=r&&(c="lines");let u=l.join("\n"),p=Buffer.byteLength(u,"utf-8");return{content:u,truncated:!0,truncatedBy:c,totalLines:n,totalBytes:o,outputLines:l.length,outputBytes:p,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:i,maxBytes:r}}function o(e,t={}){let i=t.maxLines??2e3,r=t.maxBytes??51200,s=Buffer.byteLength(e,"utf-8"),a=e.split("\n"),n=a.length;if(n<=i&&s<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:n,totalBytes:s,outputLines:n,outputBytes:s,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:i,maxBytes:r};let l=[],d=0,c="lines",u=!1;for(let e=a.length-1;e>=0&&l.length<i;e--){let t=a[e],i=Buffer.byteLength(t,"utf-8")+ +(l.length>0);if(d+i>r){if(c="bytes",0===l.length){let e=function(e,t){let i=Buffer.from(e,"utf-8");if(i.length<=t)return e;let r=i.length-t;for(;r<i.length&&(192&i[r])==128;)r++;return i.slice(r).toString("utf-8")}(t,r);l.unshift(e),d=Buffer.byteLength(e,"utf-8"),u=!0}break}l.unshift(t),d+=i}l.length>=i&&d<=r&&(c="lines");let p=l.join("\n"),h=Buffer.byteLength(p,"utf-8");return{content:p,truncated:!0,truncatedBy:c,totalLines:n,totalBytes:s,outputLines:l.length,outputBytes:h,lastLinePartial:u,firstLineExceedsLimit:!1,maxLines:i,maxBytes:r}}function a(e,t=500){return e.length<=t?{text:e,wasTruncated:!1}:{text:`${e.slice(0,t)}... [truncated]`,wasTruncated:!0}}i.d(t,{Xq:()=>r,Zo:()=>o,rT:()=>a,vB:()=>s})},770(e,t,i){i.a(e,async function(e,r){try{i.d(t,{E:()=>p,y:()=>d});var s=i(4204),o=i(1943),a=i(6928),n=i(5374),l=e([s]);let c=(s=(l.then?(await l)():l)[0]).Type.Object({path:s.Type.String({description:"Path to the file to write (relative or absolute)"}),content:s.Type.String({description:"Content to write to the file"})}),u={writeFile:(e,t)=>(0,o.writeFile)(e,t,"utf-8"),mkdir:e=>(0,o.mkdir)(e,{recursive:!0}).then(()=>{})};function d(e,t){let i=t?.operations??u;return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",parameters:c,execute:async(t,{path:r,content:s},o)=>{let l=(0,n.wT)(r,e),d=(0,a.dirname)(l);return new Promise((e,t)=>{if(o?.aborted)return void t(Error("Operation aborted"));let a=!1,n=()=>{a=!0,t(Error("Operation aborted"))};o&&o.addEventListener("abort",n,{once:!0}),(async()=>{try{if(await i.mkdir(d),a||(await i.writeFile(l,s),a))return;o&&o.removeEventListener("abort",n),e({content:[{type:"text",text:`Successfully wrote ${s.length} bytes to ${r}`}],details:void 0})}catch(e){o&&o.removeEventListener("abort",n),a||t(e)}})()})}}}let p=d(process.cwd());r()}catch(e){r(e)}})},8285(e,t,i){i.a(e,async function(e,r){try{i.d(t,{CK:()=>w.CK,Fl:()=>u.Fl,G3:()=>u.G3,JD:()=>u.JD,UI:()=>p.UI,a2:()=>u.a2,ij:()=>u.ij,lg:()=>p.lg,pd:()=>w.pd,rJ:()=>u.rJ,xH:()=>u.xH,yZ:()=>u.yZ}),i(7103);var s=i(2765),o=i(7683),a=i(9927);i(8846);var n=i(3064);i(2729);var l=i(2910),d=i(5891),c=i(1397),u=i(7085);i(9816),i(430);var p=i(5039),h=i(3525),m=i(828),g=i(3774),f=i(2514),w=i(9354);i(4917);var k=i(1957);i(3409);var y=e([s,o,a,n,l,d,c,u,p,h,m,g,f,w,k]);[s,o,a,n,l,d,c,u,p,h,m,g,f,w,k]=y.then?(await y)():y,r()}catch(e){r(e)}})},828(e,t,i){i.a(e,async function(e,t){try{var r=i(785),s=i(5590);i(3785);var o=i(4467),a=i(1200),n=i(2937),l=i(9793),d=i(6955);i(7103);var c=i(7683),u=i(8006),p=i(3716),h=i(2910),m=i(2715),g=i(5891),f=i(1397),w=i(7085);i(9816),i(430),i(5582);var k=i(3525),y=i(4964),v=i(3774),b=i(9354),S=e([r,s,o,a,n,l,d,c,u,p,h,m,g,f,w,k,y,v,b]);[r,s,o,a,n,l,d,c,u,p,h,m,g,f,w,k,y,v,b]=S.then?(await S)():S,t()}catch(e){t(e)}})},4964(e,t,i){i.a(e,async function(e,t){try{var r=i(5590);i(9896),i(6928),i(7103);var s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},3774(e,t,i){i.a(e,async function(e,t){try{var r=i(7797);i(7054);var s=i(6013),o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},3223(e,t,i){i.a(e,async function(e,t){try{var r=i(9354),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},7888(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=e([r,s]);[r,s]=o.then?(await o)():o,r.Container,t()}catch(e){t(e)}})},8065(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(4773),o=(i(7939),i(9354)),a=i(1258),n=i(1159),l=i(8819),d=e([a,s,l,n,o,r]);[a,s,l,n,o,r]=d.then?(await d)():d,r.Container,t()}catch(e){t(e)}})},1639(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(1258),o=i(1159),a=e([o,r,s]);[o,r,s]=a.then?(await a)():a,r.Container,t()}catch(e){t(e)}})},1023(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1159),a=e([r,o,s]);[r,o,s]=a.then?(await a)():a,r.Box,t()}catch(e){t(e)}})},234(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1159),a=e([r,o,s]);[r,o,s]=a.then?(await a)():a,r.Box,t()}catch(e){t(e)}})},1442(e,t,i){i.a(e,async function(e,t){try{var r=i(6760),s=i(4127),o=i(7103),a=i(9354),n=i(1258),l=i(1159),d=e([l,a,s,n]);[l,a,s,n]=d.then?(await d)():d;s.Container,t()}catch(e){t(e)}})},2477(e,t,i){i.d(t,{r:()=>r});class r{tui;onTick;onExpire;intervalId;remainingSeconds;constructor(e,t,i,r){this.tui=t,this.onTick=i,this.onExpire=r,this.remainingSeconds=Math.ceil(e/1e3),this.onTick(this.remainingSeconds),this.intervalId=setInterval(()=>{this.remainingSeconds--,this.onTick(this.remainingSeconds),this.tui?.requestRender(),this.remainingSeconds<=0&&(this.dispose(),this.onExpire())},1e3)}dispose(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0)}}},7949(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=e([r]);(r=(s.then?(await s)():s)[0]).Editor,t()}catch(e){t(e)}})},5625(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=e([r,s]);[r,s]=o.then?(await o)():o,r.Container,t()}catch(e){t(e)}})},9595(e,t,i){i.a(e,async function(e,t){try{var r=i(9354),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},5783(e,t,i){i.a(e,async function(e,r){try{i.d(t,{i:()=>d});var s=i(8188),o=i(9354),a=e([s,o]);function n(e){let t=e.match(/^([+-\s])(\s*\d*)\s(.*)$/);return t?{prefix:t[1],lineNum:t[2],content:t[3]}:null}function l(e){return e.replace(/\t/g," ")}function d(e,t={}){let i=e.split("\n"),r=[],a=0;for(;a<i.length;){let e=i[a],t=n(e);if(!t){r.push(o.w4.fg("toolDiffContext",e)),a++;continue}if("-"===t.prefix){let e=[];for(;a<i.length;){let t=n(i[a]);if(!t||"-"!==t.prefix)break;e.push({lineNum:t.lineNum,content:t.content}),a++}let t=[];for(;a<i.length;){let e=n(i[a]);if(!e||"+"!==e.prefix)break;t.push({lineNum:e.lineNum,content:e.content}),a++}if(1===e.length&&1===t.length){let i=e[0],a=t[0],{removedLine:n,addedLine:d}=function(e,t){let i=s.diffWords(e,t),r="",a="",n=!0,l=!0;for(let e of i)if(e.removed){let t=e.value;if(n){let e=t.match(/^(\s*)/)?.[1]||"";t=t.slice(e.length),r+=e,n=!1}t&&(r+=o.w4.inverse(t))}else if(e.added){let t=e.value;if(l){let e=t.match(/^(\s*)/)?.[1]||"";t=t.slice(e.length),a+=e,l=!1}t&&(a+=o.w4.inverse(t))}else r+=e.value,a+=e.value;return{removedLine:r,addedLine:a}}(l(i.content),l(a.content));r.push(o.w4.fg("toolDiffRemoved",`-${i.lineNum} ${n}`)),r.push(o.w4.fg("toolDiffAdded",`+${a.lineNum} ${d}`))}else{for(let t of e)r.push(o.w4.fg("toolDiffRemoved",`-${t.lineNum} ${l(t.content)}`));for(let e of t)r.push(o.w4.fg("toolDiffAdded",`+${e.lineNum} ${l(e.content)}`))}}else"+"===t.prefix?r.push(o.w4.fg("toolDiffAdded",`+${t.lineNum} ${l(t.content)}`)):r.push(o.w4.fg("toolDiffContext",` ${t.lineNum} ${l(t.content)}`)),a++}return r.join("\n")}[s,o]=a.then?(await a)():a,r()}catch(e){r(e)}})},1258(e,t,i){i.a(e,async function(e,r){try{i.d(t,{i:()=>a});var s=i(9354),o=e([s]);s=(o.then?(await o)():o)[0];class a{color;constructor(e=e=>s.w4.fg("border",e)){this.color=e}invalidate(){}render(e){return[this.color("─".repeat(Math.max(1,e)))]}}r()}catch(e){r(e)}})},3681(e,t,i){i.a(e,async function(e,t){try{i(1421),i(3024),i(8161),i(6760);var r=i(4127),s=i(9354),o=i(1258),a=i(1159),n=e([s,a,o,r]);[s,a,o,r]=n.then?(await n)():n,r.Container,t()}catch(e){t(e)}})},1786(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=(i(2477),i(1258)),a=i(1159),n=e([s,a,o,r]);[s,a,o,r]=n.then?(await n)():n,r.Container,t()}catch(e){t(e)}})},4589(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=(i(2477),i(1258)),a=i(1159),n=e([a,o,s,r]);[a,o,s,r]=n.then?(await n)():n,r.Container,t()}catch(e){t(e)}})},4047(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=e([r,s]);[r,s]=o.then?(await o)():o,t()}catch(e){t(e)}})},2514(e,t,i){i.a(e,async function(e,t){try{var r=i(3223),s=i(7888),o=i(8065),a=i(1639),n=i(1023),l=i(234),d=i(7949),c=i(5625),u=i(9595),p=i(5783),h=i(1258),m=i(3681),g=i(1786),f=i(4589),w=i(4047),k=i(1159),y=i(4384),v=i(8081),b=i(9072),S=i(2905),T=i(4462),C=i(6391),E=i(5400),x=i(4340),I=i(8757),A=i(9212),O=i(8121),P=i(4232),R=i(3337),M=i(3055),L=i(8819),N=e([r,s,o,a,n,l,d,c,u,p,h,m,g,f,w,k,y,v,b,S,T,C,E,x,I,A,O,P,R,M,L]);[r,s,o,a,n,l,d,c,u,p,h,m,g,f,w,k,y,v,b,S,T,C,E,x,I,A,O,P,R,M,L]=N.then?(await N)():N,t()}catch(e){t(e)}})},1159(e,t,i){i.a(e,async function(e,r){try{i.d(t,{$k:()=>d,fy:()=>l,gK:()=>u,le:()=>p,p4:()=>c});var s=i(4127),o=i(9354),a=e([s,o]);function n(e){return 0===e.length?"":1===e.length?e[0]:e.join("/")}function l(e){return n((0,s.getEditorKeybindings)().getKeys(e))}function d(e,t){return n(e.getKeys(t))}function c(e,t){return o.w4.fg("dim",l(e))+o.w4.fg("muted",` ${t}`)}function u(e,t,i){return o.w4.fg("dim",d(e,t))+o.w4.fg("muted",` ${i}`)}function p(e,t){return o.w4.fg("dim",e)+o.w4.fg("muted",` ${t}`)}[s,o]=a.then?(await a)():a,r()}catch(e){r(e)}})},4384(e,t,i){i.a(e,async function(e,t){try{var r=i(785),s=i(4127),o=(i(5317),i(9354)),a=i(1258),n=i(1159),l=e([r,a,n,o,s]);[r,a,n,o,s]=l.then?(await l)():l,s.Container,t()}catch(e){t(e)}})},8081(e,t,i){i.a(e,async function(e,t){try{var r=i(785),s=i(4127),o=i(9354),a=i(1258),n=i(1159),l=e([a,n,r,o,s]);[a,n,r,o,s]=l.then?(await l)():l,s.Container,t()}catch(e){t(e)}})},9072(e,t,i){i.a(e,async function(e,t){try{var r=i(785),s=i(4127),o=i(9354),a=i(1258),n=e([a,r,o,s]);[a,r,o,s]=n.then?(await n)():n,s.Container,t()}catch(e){t(e)}})},2905(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=e([o,s,r]);[o,s,r]=a.then?(await a)():a;r.Container,t()}catch(e){t(e)}})},4747(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Fo:()=>d,iR:()=>n});var s=i(4127),o=e([s]);function a(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function n(e){return!!e.name?.trim()}function l(e,t){let i=`${e.id} ${e.name??""} ${e.allMessagesText} ${e.cwd}`;if("regex"===t.mode){if(!t.regex)return{matches:!1,score:0};let e=i.search(t.regex);return e<0?{matches:!1,score:0}:{matches:!0,score:.1*e}}if(0===t.tokens.length)return{matches:!0,score:0};let r=0,o=null;for(let e of t.tokens){if("phrase"===e.kind){null===o&&(o=a(i));let t=a(e.value);if(!t)continue;let s=o.indexOf(t);if(s<0)return{matches:!1,score:0};r+=.1*s;continue}let t=(0,s.fuzzyMatch)(e.value,i);if(!t.matches)return{matches:!1,score:0};r+=t.score}return{matches:!0,score:r}}function d(e,t,i,r="all"){let s="all"===r?e:e.filter(e=>"all"===r||n(e));if(!t.trim())return s;let o=function(e){let t=e.trim();if(!t)return{mode:"tokens",tokens:[],regex:null};if(t.startsWith("re:")){let e=t.slice(3).trim();if(!e)return{mode:"regex",tokens:[],regex:null,error:"Empty regex"};try{return{mode:"regex",tokens:[],regex:RegExp(e,"i")}}catch(t){let e=t instanceof Error?t.message:String(t);return{mode:"regex",tokens:[],regex:null,error:e}}}let i=[],r="",s=!1,o=!1,a=e=>{let t=r.trim();r="",t&&i.push({kind:e,value:t})};for(let e=0;e<t.length;e++){let i=t[e];if('"'===i){s?(a("phrase"),s=!1):(a("fuzzy"),s=!0);continue}if(!s&&/\s/.test(i)){a("fuzzy");continue}r+=i}return(s&&(o=!0),o)?{mode:"tokens",tokens:t.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0).map(e=>({kind:"fuzzy",value:e})),regex:null}:(a(s?"phrase":"fuzzy"),{mode:"tokens",tokens:i,regex:null})}(t);if(o.error)return[];if("recent"===i){let e=[];for(let t of s)l(t,o).matches&&e.push(t);return e}let a=[];for(let e of s){let t=l(e,o);t.matches&&a.push({session:e,score:t.score})}return a.sort((e,t)=>e.score!==t.score?e.score-t.score:t.session.modified.getTime()-e.session.modified.getTime()),a.map(e=>e.session)}s=(o.then?(await o)():o)[0],r()}catch(e){r(e)}})},4462(e,t,i){i.a(e,async function(e,t){try{var r=i(1421),s=i(3024),o=i(1455),a=i(8161),n=i(4127),l=i(3716),d=i(9354),c=i(1258),u=i(1159),p=i(4747),h=e([p,u,c,l,n,d]);[p,u,c,l,n,d]=h.then?(await h)():h;n.Container,t()}catch(e){t(e)}})},6391(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a;r.Container,r.Container,t()}catch(e){t(e)}})},5400(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a,r.Container,t()}catch(e){t(e)}})},4340(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1159),a=e([s,o,r]);[s,o,r]=a.then?(await a)():a,r.Box,t()}catch(e){t(e)}})},8757(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a,r.Container,t()}catch(e){t(e)}})},9212(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=e([r,s,o]);[r,s,o]=a.then?(await a)():a;r.Container,t()}catch(e){t(e)}})},8121(e,t,i){i.a(e,async function(e,t){try{var r=i(8161),s=i(4127),o=i(4773),a=i(4517),n=i(3525),l=(i(7939),i(360),i(3409),i(9354)),d=i(5783),c=i(1159),u=i(8819),p=e([n,a,u,o,s,d,c,l]);[n,a,u,o,s,d,c,l]=p.then?(await p)():p;s.Container,t()}catch(e){t(e)}})},4232(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=i(1159),n=e([a,s,r,o]);[a,s,r,o]=n.then?(await n)():n;r.Container,t()}catch(e){t(e)}})},3055(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=i(1258),a=e([s,r,o]);[s,r,o]=a.then?(await a)():a;r.Container,t()}catch(e){t(e)}})},3337(e,t,i){i.a(e,async function(e,t){try{var r=i(4127),s=i(9354),o=e([r,s]);[r,s]=o.then?(await o)():o,r.Container,t()}catch(e){t(e)}})},8819(e,t,i){i.a(e,async function(e,r){try{i.d(t,{J:()=>a});var s=i(4127),o=e([s]);function a(e,t,i,r=0){if(!e)return{visualLines:[],skippedCount:0};let o=new s.Text(e,r,0).render(i);if(o.length<=t)return{visualLines:o,skippedCount:0};let n=o.slice(-t),l=o.length-t;return{visualLines:n,skippedCount:l}}s=(o.then?(await o)():o)[0],r()}catch(e){r(e)}})},7797(e,t,i){i.a(e,async function(e,t){try{i(7598),i(3024),i(8161),i(6760);var r=i(785),s=i(4127);i(5317),i(7103);var o=i(2765);i(473);var a=i(3716);i(2729);var n=i(2715);i(9816),i(2809),i(4917),i(6691);var l=i(7614),d=i(3223),c=i(7888),u=i(8065),p=i(1639),h=i(1023),m=i(234),g=i(7949),f=i(5625),w=i(9595),k=i(1258),y=i(3681),v=i(1786),b=i(4589),S=i(4047),T=i(1159),C=i(4384),E=i(8081),x=i(9072),I=i(2905),A=i(4462),O=i(6391),P=i(4340),R=i(8121),M=i(4232),L=i(3337),N=i(3055),D=i(9354),_=e([r,s,o,a,n,l,d,c,u,p,h,m,g,f,w,k,y,v,b,S,T,C,E,x,I,A,O,P,R,M,L,N,D]);[r,s,o,a,n,l,d,c,u,p,h,m,g,f,w,k,y,v,b,S,T,C,E,x,I,A,O,P,R,M,L,N,D]=_.then?(await _)():_;class F{options;session;ui;chatContainer;pendingMessagesContainer;statusContainer;defaultEditor;editor;autocompleteProvider;fdPath;editorContainer;footer;footerDataProvider;keybindings;version;isInitialized=!1;onInputCallback;loadingAnimation=void 0;pendingWorkingMessage=void 0;defaultWorkingMessage="Working...";lastSigintTime=0;lastEscapeTime=0;changelogMarkdown=void 0;lastStatusSpacer=void 0;lastStatusText=void 0;streamingComponent=void 0;streamingMessage=void 0;pendingTools=new Map;toolOutputExpanded=!1;hideThinkingBlock=!1;skillCommands=new Map;unsubscribe;isBashMode=!1;bashComponent=void 0;pendingBashComponents=[];autoCompactionLoader=void 0;autoCompactionEscapeHandler;retryLoader=void 0;retryEscapeHandler;compactionQueuedMessages=[];shutdownRequested=!1;extensionSelector=void 0;extensionInput=void 0;extensionEditor=void 0;extensionWidgetsAbove=new Map;extensionWidgetsBelow=new Map;widgetContainerAbove;widgetContainerBelow;customFooter=void 0;headerContainer;builtInHeader=void 0;customHeader=void 0;get agent(){return this.session.agent}get sessionManager(){return this.session.sessionManager}get settingsManager(){return this.session.settingsManager}constructor(e,t={}){this.options=t,this.session=e,this.version=VERSION,this.ui=new TUI(new ProcessTerminal,this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink()),this.headerContainer=new Container,this.chatContainer=new Container,this.pendingMessagesContainer=new Container,this.statusContainer=new Container,this.widgetContainerAbove=new Container,this.widgetContainerBelow=new Container,this.keybindings=KeybindingsManager.create();let i=this.settingsManager.getEditorPaddingX(),r=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor=new CustomEditor(this.ui,getEditorTheme(),this.keybindings,{paddingX:i,autocompleteMaxVisible:r}),this.editor=this.defaultEditor,this.editorContainer=new Container,this.editorContainer.addChild(this.editor),this.footerDataProvider=new FooterDataProvider,this.footer=new FooterComponent(e,this.footerDataProvider),this.footer.setAutoCompactEnabled(e.autoCompactionEnabled),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock(),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),initTheme(this.settingsManager.getTheme(),!0)}setupAutocomplete(e){let t=BUILTIN_SLASH_COMMANDS.map(e=>({name:e.name,description:e.description})),i=t.find(e=>"model"===e.name);i&&(i.getArgumentCompletions=e=>{let t=this.session.scopedModels.length>0?this.session.scopedModels.map(e=>e.model):this.session.modelRegistry.getAvailable();if(0===t.length)return null;let i=t.map(e=>({id:e.id,provider:e.provider,label:`${e.provider}/${e.id}`})),r=fuzzyFilter(i,e,e=>`${e.id} ${e.provider}`);return 0===r.length?null:r.map(e=>({value:e.label,label:e.id,description:e.provider}))});let r=this.session.promptTemplates.map(e=>({name:e.name,description:e.description})),s=new Set(t.map(e=>e.name)),o=(this.session.extensionRunner?.getRegisteredCommands(s)??[]).map(e=>({name:e.name,description:e.description??"(extension command)",getArgumentCompletions:e.getArgumentCompletions}));this.skillCommands.clear();let a=[];if(this.settingsManager.getEnableSkillCommands())for(let e of this.session.resourceLoader.getSkills().skills){let t=`skill:${e.name}`;this.skillCommands.set(t,e.filePath),a.push({name:t,description:e.description})}this.autocompleteProvider=new CombinedAutocompleteProvider([...t,...r,...o,...a],process.cwd(),e),this.defaultEditor.setAutocompleteProvider(this.autocompleteProvider)}async init(){if(!this.isInitialized){if(this.changelogMarkdown=this.getChangelogForDisplay(),this.fdPath=await ensureTool("fd"),this.ui.addChild(this.headerContainer),this.options.verbose||!this.settingsManager.getQuietStartup()){let e=theme.bold(theme.fg("accent",APP_NAME))+theme.fg("dim",` v${this.version}`),t=this.keybindings,i=[appKeyHint(t,"interrupt","to interrupt"),appKeyHint(t,"clear","to clear"),rawKeyHint(`${appKey(t,"clear")} twice`,"to exit"),appKeyHint(t,"exit","to exit (empty)"),appKeyHint(t,"suspend","to suspend"),keyHint("deleteToLineEnd","to delete to end"),appKeyHint(t,"cycleThinkingLevel","to cycle thinking level"),rawKeyHint(`${appKey(t,"cycleModelForward")}/${appKey(t,"cycleModelBackward")}`,"to cycle models"),appKeyHint(t,"selectModel","to select model"),appKeyHint(t,"expandTools","to expand tools"),appKeyHint(t,"toggleThinking","to expand thinking"),appKeyHint(t,"externalEditor","for external editor"),rawKeyHint("/","for commands"),rawKeyHint("!","to run bash"),rawKeyHint("!!","to run bash (no context)"),appKeyHint(t,"followUp","to queue follow-up"),appKeyHint(t,"dequeue","to edit all queued messages"),appKeyHint(t,"pasteImage","to paste image"),rawKeyHint("drop files","to attach")].join("\n");if(this.builtInHeader=new Text(`${e}
|
|
36
|
-
${i}`,1,0),this.headerContainer.addChild(new Spacer(1)),this.headerContainer.addChild(this.builtInHeader),this.headerContainer.addChild(new Spacer(1)),this.changelogMarkdown){if(this.headerContainer.addChild(new DynamicBorder),this.settingsManager.getCollapseChangelog()){let e=this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/),t=e?e[1]:this.version,i=`Updated to v${t}. Use ${theme.bold("/changelog")} to view full changelog.`;this.headerContainer.addChild(new Text(i,1,0))}else this.headerContainer.addChild(new Text(theme.bold(theme.fg("accent","What's New")),1,0)),this.headerContainer.addChild(new Spacer(1)),this.headerContainer.addChild(new Markdown(this.changelogMarkdown.trim(),1,0,this.getMarkdownThemeWithSettings())),this.headerContainer.addChild(new Spacer(1));this.headerContainer.addChild(new DynamicBorder)}}else if(this.builtInHeader=new Text("",0,0),this.headerContainer.addChild(this.builtInHeader),this.changelogMarkdown){this.headerContainer.addChild(new Spacer(1));let e=this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/),t=e?e[1]:this.version,i=`Updated to v${t}. Use ${theme.bold("/changelog")} to view full changelog.`;this.headerContainer.addChild(new Text(i,1,0))}this.ui.addChild(this.chatContainer),this.ui.addChild(this.pendingMessagesContainer),this.ui.addChild(this.statusContainer),this.renderWidgets(),this.ui.addChild(this.widgetContainerAbove),this.ui.addChild(this.editorContainer),this.ui.addChild(this.widgetContainerBelow),this.ui.addChild(this.footer),this.ui.setFocus(this.editor),this.setupKeyHandlers(),this.setupEditorSubmitHandler(),await this.initExtensions(),this.renderInitialMessages(),this.ui.start(),this.isInitialized=!0,this.updateTerminalTitle(),this.subscribeToAgent(),onThemeChange(()=>{this.ui.invalidate(),this.updateEditorBorderColor(),this.ui.requestRender()}),this.footerDataProvider.onBranchChange(()=>{this.ui.requestRender()}),await this.updateAvailableProviderCount()}}updateTerminalTitle(){let e=path.basename(process.cwd()),t=this.sessionManager.getSessionName();t?this.ui.terminal.setTitle(`π - ${t} - ${e}`):this.ui.terminal.setTitle(`π - ${e}`)}async run(){await this.init(),this.checkForNewVersion().then(e=>{e&&this.showNewVersionNotification(e)});let{migratedProviders:e,modelFallbackMessage:t,initialMessage:i,initialImages:r,initialMessages:s}=this.options;e&&e.length>0&&this.showWarning(`Migrated credentials to auth.json: ${e.join(", ")}`);let o=this.session.modelRegistry.getError();if(o&&this.showError(`models.json error: ${o}`),t&&this.showWarning(t),i)try{await this.session.prompt(i,{images:r})}catch(t){let e=t instanceof Error?t.message:"Unknown error occurred";this.showError(e)}if(s)for(let e of s)try{await this.session.prompt(e)}catch(t){let e=t instanceof Error?t.message:"Unknown error occurred";this.showError(e)}for(;;){let e=await this.getUserInput();try{await this.session.prompt(e)}catch(t){let e=t instanceof Error?t.message:"Unknown error occurred";this.showError(e)}}}async checkForNewVersion(){if(!process.env.PI_SKIP_VERSION_CHECK)try{let e=await fetch("https://registry.npmjs.org/@mariozechner/pi-coding-agent/latest");if(!e.ok)return;let t=(await e.json()).version;if(t&&t!==this.version)return t;return}catch{return}}getChangelogForDisplay(){if(this.session.state.messages.length>0)return;let e=this.settingsManager.getLastChangelogVersion(),t=getChangelogPath(),i=parseChangelog(t);if(!e)return void this.settingsManager.setLastChangelogVersion(VERSION);{let t=getNewEntries(i,e);if(t.length>0)return this.settingsManager.setLastChangelogVersion(VERSION),t.map(e=>e.content).join("\n\n")}}getMarkdownThemeWithSettings(){return{...getMarkdownTheme(),codeBlockIndent:this.settingsManager.getCodeBlockIndent()}}formatDisplayPath(e){let t=os.homedir(),i=e;return i.startsWith(t)&&(i=`~${i.slice(t.length)}`),i}getShortPath(e,t){let i=e.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);if(i&&t.startsWith("npm:"))return i[2];let r=e.match(/git\/[^/]+\/[^/]+\/(.*)/);return r&&t.startsWith("git:")?r[1]:this.formatDisplayPath(e)}getDisplaySourceInfo(e,t){return"local"===e?"user"===t?{label:"user",color:"muted"}:"project"===t?{label:"project",color:"muted"}:"temporary"===t?{label:"path",scopeLabel:"temp",color:"muted"}:{label:"path",color:"muted"}:"cli"===e?{label:"path",scopeLabel:"temporary"===t?"temp":void 0,color:"muted"}:{label:e,scopeLabel:"user"===t?"user":"project"===t?"project":"temporary"===t?"temp":void 0,color:"accent"}}getScopeGroup(e,t){return"cli"===e||"temporary"===t?"path":"user"===t?"user":"project"===t?"project":"path"}isPackageSource(e){return e.startsWith("npm:")||e.startsWith("git:")}buildScopeGroups(e,t){let i={user:{scope:"user",paths:[],packages:new Map},project:{scope:"project",paths:[],packages:new Map},path:{scope:"path",paths:[],packages:new Map}};for(let r of e){let e=this.findMetadata(r,t),s=e?.source??"local",o=e?.scope??"project",a=i[this.getScopeGroup(s,o)];if(this.isPackageSource(s)){let e=a.packages.get(s)??[];e.push(r),a.packages.set(s,e)}else a.paths.push(r)}return[i.user,i.project,i.path].filter(e=>e.paths.length>0||e.packages.size>0)}formatScopeGroups(e,t){let i=[];for(let r of e){for(let e of(i.push(` ${theme.fg("accent",r.scope)}`),[...r.paths].sort((e,t)=>e.localeCompare(t))))i.push(theme.fg("dim",` ${t.formatPath(e)}`));for(let[e,s]of Array.from(r.packages.entries()).sort(([e],[t])=>e.localeCompare(t)))for(let r of(i.push(` ${theme.fg("mdLink",e)}`),[...s].sort((e,t)=>e.localeCompare(t))))i.push(theme.fg("dim",` ${t.formatPackagePath(r,e)}`))}return i.join("\n")}findMetadata(e,t){let i=t.get(e);if(i)return i;let r=e;for(;r.includes("/");){r=r.substring(0,r.lastIndexOf("/"));let e=t.get(r);if(e)return e}}formatPathWithSource(e,t){let i=this.findMetadata(e,t);if(i){let t=this.getShortPath(e,i.source),{label:r,scopeLabel:s}=this.getDisplaySourceInfo(i.source,i.scope),o=s?`${r} (${s})`:r;return`${o} ${t}`}return this.formatDisplayPath(e)}formatDiagnostics(e,t){let i=[],r=new Map,s=[];for(let t of e)if("collision"===t.type&&t.collision){let e=r.get(t.collision.name)??[];e.push(t),r.set(t.collision.name,e)}else s.push(t);for(let[e,s]of r){let r=s[0]?.collision;if(r)for(let o of(i.push(theme.fg("warning",` "${e}" collision:`)),i.push(theme.fg("dim",` ${theme.fg("success","✓")} ${this.formatPathWithSource(r.winnerPath,t)}`)),s))o.collision&&i.push(theme.fg("dim",` ${theme.fg("warning","✗")} ${this.formatPathWithSource(o.collision.loserPath,t)} (skipped)`))}for(let e of s)if(e.path){let r=this.formatPathWithSource(e.path,t);i.push(theme.fg("error"===e.type?"error":"warning",` ${r}`)),i.push(theme.fg("error"===e.type?"error":"warning",` ${e.message}`))}else i.push(theme.fg("error"===e.type?"error":"warning",` ${e.message}`));return i.join("\n")}showLoadedResources(e){let t=e?.force||this.options.verbose||!this.settingsManager.getQuietStartup(),i=t||e?.showDiagnosticsWhenQuiet===!0;if(!t&&!i)return;let r=this.session.resourceLoader.getPathMetadata(),s=(e,t="mdHeading")=>theme.fg(t,`[${e}]`),o=this.session.resourceLoader.getSkills(),a=this.session.resourceLoader.getPrompts(),n=this.session.resourceLoader.getThemes();if(t){let t=this.session.resourceLoader.getAgentsFiles().agentsFiles;if(t.length>0){this.chatContainer.addChild(new Spacer(1));let e=t.map(e=>theme.fg("dim",` ${this.formatDisplayPath(e.path)}`)).join("\n");this.chatContainer.addChild(new Text(`${s("Context")}
|
|
37
|
-
${e}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let i=o.skills;if(i.length>0){let e=i.map(e=>e.filePath),t=this.buildScopeGroups(e,r),o=this.formatScopeGroups(t,{formatPath:e=>this.formatDisplayPath(e),formatPackagePath:(e,t)=>this.getShortPath(e,t)});this.chatContainer.addChild(new Text(`${s("Skills")}
|
|
38
|
-
${o}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let a=this.session.promptTemplates;if(a.length>0){let e=a.map(e=>e.filePath),t=this.buildScopeGroups(e,r),i=new Map(a.map(e=>[e.filePath,e])),o=this.formatScopeGroups(t,{formatPath:e=>{let t=i.get(e);return t?`/${t.name}`:this.formatDisplayPath(e)},formatPackagePath:e=>{let t=i.get(e);return t?`/${t.name}`:this.formatDisplayPath(e)}});this.chatContainer.addChild(new Text(`${s("Prompts")}
|
|
39
|
-
${o}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let l=e?.extensionPaths??[];if(l.length>0){let e=this.buildScopeGroups(l,r),t=this.formatScopeGroups(e,{formatPath:e=>this.formatDisplayPath(e),formatPackagePath:(e,t)=>this.getShortPath(e,t)});this.chatContainer.addChild(new Text(`${s("Extensions","mdHeading")}
|
|
40
|
-
${t}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let d=n.themes.filter(e=>e.sourcePath);if(d.length>0){let e=d.map(e=>e.sourcePath),t=this.buildScopeGroups(e,r),i=this.formatScopeGroups(t,{formatPath:e=>this.formatDisplayPath(e),formatPackagePath:(e,t)=>this.getShortPath(e,t)});this.chatContainer.addChild(new Text(`${s("Themes")}
|
|
41
|
-
${i}`,0,0)),this.chatContainer.addChild(new Spacer(1))}}if(i){let e=o.diagnostics;if(e.length>0){let t=this.formatDiagnostics(e,r);this.chatContainer.addChild(new Text(`${theme.fg("warning","[Skill conflicts]")}
|
|
42
|
-
${t}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let t=a.diagnostics;if(t.length>0){let e=this.formatDiagnostics(t,r);this.chatContainer.addChild(new Text(`${theme.fg("warning","[Prompt conflicts]")}
|
|
43
|
-
${e}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let i=[],s=this.session.resourceLoader.getExtensions().errors;if(s.length>0)for(let e of s)i.push({type:"error",message:e.error,path:e.path});let l=this.session.extensionRunner?.getCommandDiagnostics()??[];i.push(...l);let d=this.session.extensionRunner?.getShortcutDiagnostics()??[];if(i.push(...d),i.length>0){let e=this.formatDiagnostics(i,r);this.chatContainer.addChild(new Text(`${theme.fg("warning","[Extension issues]")}
|
|
44
|
-
${e}`,0,0)),this.chatContainer.addChild(new Spacer(1))}let c=n.diagnostics;if(c.length>0){let e=this.formatDiagnostics(c,r);this.chatContainer.addChild(new Text(`${theme.fg("warning","[Theme conflicts]")}
|
|
45
|
-
${e}`,0,0)),this.chatContainer.addChild(new Spacer(1))}}}async initExtensions(){let e=this.createExtensionUIContext();await this.session.bindExtensions({uiContext:e,commandContextActions:{waitForIdle:()=>this.session.agent.waitForIdle(),newSession:async e=>(this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear(),await this.session.newSession(e))?(this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),this.renderInitialMessages(),this.ui.requestRender(),{cancelled:!1}):{cancelled:!0},fork:async e=>{let t=await this.session.fork(e);return t.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),this.editor.setText(t.selectedText),this.showStatus("Forked to new session"),{cancelled:!1})},navigateTree:async(e,t)=>{let i=await this.session.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label});return i.cancelled?{cancelled:!0}:(this.chatContainer.clear(),this.renderInitialMessages(),i.editorText&&!this.editor.getText().trim()&&this.editor.setText(i.editorText),this.showStatus("Navigated to selected point"),{cancelled:!1})},switchSession:async e=>(await this.handleResumeSession(e),{cancelled:!1})},shutdownHandler:()=>{this.shutdownRequested=!0},onError:e=>{this.showExtensionError(e.extensionPath,e.error,e.stack)}}),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),this.setupAutocomplete(this.fdPath);let t=this.session.extensionRunner;t?(this.setupExtensionShortcuts(t),this.showLoadedResources({extensionPaths:t.getExtensionPaths(),force:!1})):this.showLoadedResources({extensionPaths:[],force:!1})}getRegisteredToolDefinition(e){let t=(this.session.extensionRunner?.getAllRegisteredTools()??[]).find(t=>t.definition.name===e);return t?.definition}setupExtensionShortcuts(e){let t=e.getShortcuts(this.keybindings.getEffectiveConfig());if(0===t.size)return;let i=()=>({ui:this.createExtensionUIContext(),hasUI:!0,cwd:process.cwd(),sessionManager:this.sessionManager,modelRegistry:this.session.modelRegistry,model:this.session.model,isIdle:()=>!this.session.isStreaming,abort:()=>this.session.abort(),hasPendingMessages:()=>this.session.pendingMessageCount>0,shutdown:()=>{this.shutdownRequested=!0},getContextUsage:()=>this.session.getContextUsage(),compact:e=>{(async()=>{try{let t=await this.executeCompaction(e?.customInstructions,!1);t&&e?.onComplete?.(t)}catch(i){let t=i instanceof Error?i:Error(String(i));e?.onError?.(t)}})()},getSystemPrompt:()=>this.session.systemPrompt});this.defaultEditor.onExtensionShortcut=e=>{for(let[r,s]of t)if(matchesKey(e,r))return Promise.resolve(s.handler(i())).catch(e=>{this.showError(`Shortcut handler error: ${e instanceof Error?e.message:String(e)}`)}),!0;return!1}}setExtensionStatus(e,t){this.footerDataProvider.setExtensionStatus(e,t),this.ui.requestRender()}setExtensionWidget(e,t,i){let r,s=i?.placement??"aboveEditor",o=t=>{let i=t.get(e);i?.dispose&&i.dispose(),t.delete(e)};if(o(this.extensionWidgetsAbove),o(this.extensionWidgetsBelow),void 0===t)return void this.renderWidgets();if(Array.isArray(t)){let e=new Container;for(let i of t.slice(0,F.MAX_WIDGET_LINES))e.addChild(new Text(i,1,0));t.length>F.MAX_WIDGET_LINES&&e.addChild(new Text(theme.fg("muted","... (widget truncated)"),1,0)),r=e}else r=t(this.ui,theme);("belowEditor"===s?this.extensionWidgetsBelow:this.extensionWidgetsAbove).set(e,r),this.renderWidgets()}clearExtensionWidgets(){for(let e of this.extensionWidgetsAbove.values())e.dispose?.();for(let e of this.extensionWidgetsBelow.values())e.dispose?.();this.extensionWidgetsAbove.clear(),this.extensionWidgetsBelow.clear(),this.renderWidgets()}resetExtensionUI(){this.extensionSelector&&this.hideExtensionSelector(),this.extensionInput&&this.hideExtensionInput(),this.extensionEditor&&this.hideExtensionEditor(),this.ui.hideOverlay(),this.setExtensionFooter(void 0),this.setExtensionHeader(void 0),this.clearExtensionWidgets(),this.footerDataProvider.clearExtensionStatuses(),this.footer.invalidate(),this.setCustomEditorComponent(void 0),this.defaultEditor.onExtensionShortcut=void 0,this.updateTerminalTitle(),this.loadingAnimation&&this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${appKey(this.keybindings,"interrupt")} to interrupt)`)}static MAX_WIDGET_LINES=null;renderWidgets(){this.widgetContainerAbove&&this.widgetContainerBelow&&(this.renderWidgetContainer(this.widgetContainerAbove,this.extensionWidgetsAbove,!0,!0),this.renderWidgetContainer(this.widgetContainerBelow,this.extensionWidgetsBelow,!1,!1),this.ui.requestRender())}renderWidgetContainer(e,t,i,r){if(e.clear(),0===t.size){i&&e.addChild(new Spacer(1));return}for(let i of(r&&e.addChild(new Spacer(1)),t.values()))e.addChild(i)}setExtensionFooter(e){this.customFooter?.dispose&&this.customFooter.dispose(),this.customFooter?this.ui.removeChild(this.customFooter):this.ui.removeChild(this.footer),e?(this.customFooter=e(this.ui,theme,this.footerDataProvider),this.ui.addChild(this.customFooter)):(this.customFooter=void 0,this.ui.addChild(this.footer)),this.ui.requestRender()}setExtensionHeader(e){if(!this.builtInHeader)return;this.customHeader?.dispose&&this.customHeader.dispose();let t=this.customHeader||this.builtInHeader,i=this.headerContainer.children.indexOf(t);e?(this.customHeader=e(this.ui,theme),-1!==i?this.headerContainer.children[i]=this.customHeader:this.headerContainer.children.unshift(this.customHeader)):(this.customHeader=void 0,-1!==i&&(this.headerContainer.children[i]=this.builtInHeader)),this.ui.requestRender()}createExtensionUIContext(){return{select:(e,t,i)=>this.showExtensionSelector(e,t,i),confirm:(e,t,i)=>this.showExtensionConfirm(e,t,i),input:(e,t,i)=>this.showExtensionInput(e,t,i),notify:(e,t)=>this.showExtensionNotify(e,t),setStatus:(e,t)=>this.setExtensionStatus(e,t),setWorkingMessage:e=>{this.loadingAnimation?e?this.loadingAnimation.setMessage(e):this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${appKey(this.keybindings,"interrupt")} to interrupt)`):this.pendingWorkingMessage=e},setWidget:(e,t,i)=>this.setExtensionWidget(e,t,i),setFooter:e=>this.setExtensionFooter(e),setHeader:e=>this.setExtensionHeader(e),setTitle:e=>this.ui.terminal.setTitle(e),custom:(e,t)=>this.showExtensionCustom(e,t),setEditorText:e=>this.editor.setText(e),getEditorText:()=>this.editor.getText(),editor:(e,t)=>this.showExtensionEditor(e,t),setEditorComponent:e=>this.setCustomEditorComponent(e),get theme(){return theme},getAllThemes:()=>getAvailableThemesWithPaths(),getTheme:e=>getThemeByName(e),setTheme:e=>{if(e instanceof Theme)return setThemeInstance(e),this.ui.requestRender(),{success:!0};let t=setTheme(e,!0);return t.success&&this.ui.requestRender(),t},getToolsExpanded:()=>this.toolOutputExpanded,setToolsExpanded:e=>this.setToolsExpanded(e)}}showExtensionSelector(e,t,i){return new Promise(r=>{if(i?.signal?.aborted)return void r(void 0);let s=()=>{this.hideExtensionSelector(),r(void 0)};i?.signal?.addEventListener("abort",s,{once:!0}),this.extensionSelector=new ExtensionSelectorComponent(e,t,e=>{i?.signal?.removeEventListener("abort",s),this.hideExtensionSelector(),r(e)},()=>{i?.signal?.removeEventListener("abort",s),this.hideExtensionSelector(),r(void 0)},{tui:this.ui,timeout:i?.timeout}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionSelector),this.ui.setFocus(this.extensionSelector),this.ui.requestRender()})}hideExtensionSelector(){this.extensionSelector?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionSelector=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}async showExtensionConfirm(e,t,i){let r=await this.showExtensionSelector(`${e}
|
|
46
|
-
${t}`,["Yes","No"],i);return"Yes"===r}showExtensionInput(e,t,i){return new Promise(r=>{if(i?.signal?.aborted)return void r(void 0);let s=()=>{this.hideExtensionInput(),r(void 0)};i?.signal?.addEventListener("abort",s,{once:!0}),this.extensionInput=new ExtensionInputComponent(e,t,e=>{i?.signal?.removeEventListener("abort",s),this.hideExtensionInput(),r(e)},()=>{i?.signal?.removeEventListener("abort",s),this.hideExtensionInput(),r(void 0)},{tui:this.ui,timeout:i?.timeout}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionInput),this.ui.setFocus(this.extensionInput),this.ui.requestRender()})}hideExtensionInput(){this.extensionInput?.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionInput=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionEditor(e,t){return new Promise(i=>{this.extensionEditor=new ExtensionEditorComponent(this.ui,this.keybindings,e,t,e=>{this.hideExtensionEditor(),i(e)},()=>{this.hideExtensionEditor(),i(void 0)}),this.editorContainer.clear(),this.editorContainer.addChild(this.extensionEditor),this.ui.setFocus(this.extensionEditor),this.ui.requestRender()})}hideExtensionEditor(){this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.extensionEditor=void 0,this.ui.setFocus(this.editor),this.ui.requestRender()}setCustomEditorComponent(e){let t=this.editor.getText();if(this.editorContainer.clear(),e){let i=e(this.ui,getEditorTheme(),this.keybindings);if(i.onSubmit=this.defaultEditor.onSubmit,i.onChange=this.defaultEditor.onChange,i.setText(t),void 0!==i.borderColor&&(i.borderColor=this.defaultEditor.borderColor),void 0!==i.setPaddingX&&i.setPaddingX(this.defaultEditor.getPaddingX()),i.setAutocompleteProvider&&this.autocompleteProvider&&i.setAutocompleteProvider(this.autocompleteProvider),"actionHandlers"in i&&i.actionHandlers instanceof Map)for(let[e,t]of(i.onEscape=this.defaultEditor.onEscape,i.onCtrlD=this.defaultEditor.onCtrlD,i.onPasteImage=this.defaultEditor.onPasteImage,i.onExtensionShortcut=e=>this.defaultEditor.onExtensionShortcut?.(e),this.defaultEditor.actionHandlers))i.actionHandlers.set(e,t);this.editor=i}else this.defaultEditor.setText(t),this.editor=this.defaultEditor;this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()}showExtensionNotify(e,t){"error"===t?this.showError(e):"warning"===t?this.showWarning(e):this.showStatus(e)}async showExtensionCustom(e,t){let i=this.editor.getText(),r=t?.overlay??!1,s=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.editor.setText(i),this.ui.setFocus(this.editor),this.ui.requestRender()};return new Promise((i,o)=>{let a,n=!1,l=e=>{if(!n){n=!0,r?this.ui.hideOverlay():s(),i(e);try{a?.dispose?.()}catch{}}};Promise.resolve(e(this.ui,theme,this.keybindings,l)).then(e=>{if(!n)if(a=e,r){let e=this.ui.showOverlay(a,(()=>{if(t?.overlayOptions)return"function"==typeof t.overlayOptions?t.overlayOptions():t.overlayOptions;let e=a.width;return e?{width:e}:void 0})());t?.onHandle?.(e)}else this.editorContainer.clear(),this.editorContainer.addChild(a),this.ui.setFocus(a),this.ui.requestRender()}).catch(e=>{n||(r||s(),o(e))})})}showExtensionError(e,t,i){let r=`Extension "${e}" error: ${t}`,s=new Text(theme.fg("error",r),1,0);if(this.chatContainer.addChild(s),i){let e=i.split("\n").slice(1).map(e=>theme.fg("dim",` ${e.trim()}`)).join("\n");e&&this.chatContainer.addChild(new Text(e,1,0))}this.ui.requestRender()}setupKeyHandlers(){this.defaultEditor.onEscape=()=>{if(this.loadingAnimation)this.restoreQueuedMessagesToEditor({abort:!0});else if(this.session.isBashRunning)this.session.abortBash();else if(this.isBashMode)this.editor.setText(""),this.isBashMode=!1,this.updateEditorBorderColor();else if(!this.editor.getText().trim()){let e=this.settingsManager.getDoubleEscapeAction();if("none"!==e){let t=Date.now();t-this.lastEscapeTime<500?("tree"===e?this.showTreeSelector():this.showUserMessageSelector(),this.lastEscapeTime=0):this.lastEscapeTime=t}}},this.defaultEditor.onAction("clear",()=>this.handleCtrlC()),this.defaultEditor.onCtrlD=()=>this.handleCtrlD(),this.defaultEditor.onAction("suspend",()=>this.handleCtrlZ()),this.defaultEditor.onAction("cycleThinkingLevel",()=>this.cycleThinkingLevel()),this.defaultEditor.onAction("cycleModelForward",()=>this.cycleModel("forward")),this.defaultEditor.onAction("cycleModelBackward",()=>this.cycleModel("backward")),this.ui.onDebug=()=>this.handleDebugCommand(),this.defaultEditor.onAction("selectModel",()=>this.showModelSelector()),this.defaultEditor.onAction("expandTools",()=>this.toggleToolOutputExpansion()),this.defaultEditor.onAction("toggleThinking",()=>this.toggleThinkingBlockVisibility()),this.defaultEditor.onAction("externalEditor",()=>this.openExternalEditor()),this.defaultEditor.onAction("followUp",()=>this.handleFollowUp()),this.defaultEditor.onAction("dequeue",()=>this.handleDequeue()),this.defaultEditor.onAction("newSession",()=>this.handleClearCommand()),this.defaultEditor.onAction("tree",()=>this.showTreeSelector()),this.defaultEditor.onAction("fork",()=>this.showUserMessageSelector()),this.defaultEditor.onAction("resume",()=>this.showSessionSelector()),this.defaultEditor.onChange=e=>{let t=this.isBashMode;this.isBashMode=e.trimStart().startsWith("!"),t!==this.isBashMode&&this.updateEditorBorderColor()},this.defaultEditor.onPasteImage=()=>{this.handleClipboardImagePaste()}}async handleClipboardImagePaste(){try{let e=await readClipboardImage();if(!e)return;let t=os.tmpdir(),i=extensionForImageMimeType(e.mimeType)??"png",r=`pi-clipboard-${crypto.randomUUID()}.${i}`,s=path.join(t,r);fs.writeFileSync(s,Buffer.from(e.bytes)),this.editor.insertTextAtCursor?.(s),this.ui.requestRender()}catch{}}setupEditorSubmitHandler(){this.defaultEditor.onSubmit=async e=>{if(e=e.trim()){if("/settings"===e){this.showSettingsSelector(),this.editor.setText("");return}if("/scoped-models"===e){this.editor.setText(""),await this.showModelsSelector();return}if("/model"===e||e.startsWith("/model ")){let t=e.startsWith("/model ")?e.slice(7).trim():void 0;this.editor.setText(""),await this.handleModelCommand(t);return}if(e.startsWith("/export")){await this.handleExportCommand(e),this.editor.setText("");return}if("/share"===e){await this.handleShareCommand(),this.editor.setText("");return}if("/copy"===e){this.handleCopyCommand(),this.editor.setText("");return}if("/name"===e||e.startsWith("/name ")){this.handleNameCommand(e),this.editor.setText("");return}if("/session"===e){this.handleSessionCommand(),this.editor.setText("");return}if("/changelog"===e){this.handleChangelogCommand(),this.editor.setText("");return}if("/hotkeys"===e){this.handleHotkeysCommand(),this.editor.setText("");return}if("/fork"===e){this.showUserMessageSelector(),this.editor.setText("");return}if("/tree"===e){this.showTreeSelector(),this.editor.setText("");return}if("/login"===e){this.showOAuthSelector("login"),this.editor.setText("");return}if("/logout"===e){this.showOAuthSelector("logout"),this.editor.setText("");return}if("/new"===e){this.editor.setText(""),await this.handleClearCommand();return}if("/compact"===e||e.startsWith("/compact ")){let t=e.startsWith("/compact ")?e.slice(9).trim():void 0;this.editor.setText(""),await this.handleCompactCommand(t);return}if("/reload"===e){this.editor.setText(""),await this.handleReloadCommand();return}if("/debug"===e){this.handleDebugCommand(),this.editor.setText("");return}if("/arminsayshi"===e){this.handleArminSaysHi(),this.editor.setText("");return}if("/resume"===e){this.showSessionSelector(),this.editor.setText("");return}if("/quit"===e){this.editor.setText(""),await this.shutdown();return}if(e.startsWith("!")){let t=e.startsWith("!!"),i=t?e.slice(2).trim():e.slice(1).trim();if(i){if(this.session.isBashRunning){this.showWarning("A bash command is already running. Press Esc to cancel it first."),this.editor.setText(e);return}this.editor.addToHistory?.(e),await this.handleBashCommand(i,t),this.isBashMode=!1,this.updateEditorBorderColor();return}}if(this.session.isCompacting)return void(this.isExtensionCommand(e)?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e)):this.queueCompactionMessage(e,"steer"));if(this.session.isStreaming){this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e,{streamingBehavior:"steer"}),this.updatePendingMessagesDisplay(),this.ui.requestRender();return}this.flushPendingBashComponents(),this.onInputCallback&&this.onInputCallback(e),this.editor.addToHistory?.(e)}}}subscribeToAgent(){this.unsubscribe=this.session.subscribe(async e=>{await this.handleEvent(e)})}async handleEvent(e){switch(!this.isInitialized&&await this.init(),this.footer.invalidate(),e.type){case"agent_start":this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.retryLoader&&(this.retryLoader.stop(),this.retryLoader=void 0),this.loadingAnimation&&this.loadingAnimation.stop(),this.statusContainer.clear(),this.loadingAnimation=new Loader(this.ui,e=>theme.fg("accent",e),e=>theme.fg("muted",e),this.defaultWorkingMessage),this.statusContainer.addChild(this.loadingAnimation),void 0!==this.pendingWorkingMessage&&(this.pendingWorkingMessage&&this.loadingAnimation.setMessage(this.pendingWorkingMessage),this.pendingWorkingMessage=void 0),this.ui.requestRender();break;case"message_start":"custom"===e.message.role?(this.addMessageToChat(e.message),this.ui.requestRender()):"user"===e.message.role?(this.addMessageToChat(e.message),this.updatePendingMessagesDisplay(),this.ui.requestRender()):"assistant"===e.message.role&&(this.streamingComponent=new AssistantMessageComponent(void 0,this.hideThinkingBlock,this.getMarkdownThemeWithSettings()),this.streamingMessage=e.message,this.chatContainer.addChild(this.streamingComponent),this.streamingComponent.updateContent(this.streamingMessage),this.ui.requestRender());break;case"message_update":if(this.streamingComponent&&"assistant"===e.message.role){for(let t of(this.streamingMessage=e.message,this.streamingComponent.updateContent(this.streamingMessage),this.streamingMessage.content))if("toolCall"===t.type)if(this.pendingTools.has(t.id)){let e=this.pendingTools.get(t.id);e&&e.updateArgs(t.arguments)}else{this.chatContainer.addChild(new Text("",0,0));let e=new ToolExecutionComponent(t.name,t.arguments,{showImages:this.settingsManager.getShowImages()},this.getRegisteredToolDefinition(t.name),this.ui);e.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(e),this.pendingTools.set(t.id,e)}this.ui.requestRender()}break;case"message_end":if("user"===e.message.role)break;if(this.streamingComponent&&"assistant"===e.message.role){let t;if(this.streamingMessage=e.message,"aborted"===this.streamingMessage.stopReason){let e=this.session.retryAttempt;t=e>0?`Aborted after ${e} retry attempt${e>1?"s":""}`:"Operation aborted",this.streamingMessage.errorMessage=t}if(this.streamingComponent.updateContent(this.streamingMessage),"aborted"===this.streamingMessage.stopReason||"error"===this.streamingMessage.stopReason){for(let[,e]of(t||(t=this.streamingMessage.errorMessage||"Error"),this.pendingTools.entries()))e.updateResult({content:[{type:"text",text:t}],isError:!0});this.pendingTools.clear()}else for(let[,e]of this.pendingTools.entries())e.setArgsComplete();this.streamingComponent=void 0,this.streamingMessage=void 0,this.footer.invalidate()}this.ui.requestRender();break;case"tool_execution_start":if(!this.pendingTools.has(e.toolCallId)){let t=new ToolExecutionComponent(e.toolName,e.args,{showImages:this.settingsManager.getShowImages()},this.getRegisteredToolDefinition(e.toolName),this.ui);t.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(t),this.pendingTools.set(e.toolCallId,t),this.ui.requestRender()}break;case"tool_execution_update":{let t=this.pendingTools.get(e.toolCallId);t&&(t.updateResult({...e.partialResult,isError:!1},!0),this.ui.requestRender());break}case"tool_execution_end":{let t=this.pendingTools.get(e.toolCallId);t&&(t.updateResult({...e.result,isError:e.isError}),this.pendingTools.delete(e.toolCallId),this.ui.requestRender());break}case"agent_end":this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0,this.statusContainer.clear()),this.streamingComponent&&(this.chatContainer.removeChild(this.streamingComponent),this.streamingComponent=void 0,this.streamingMessage=void 0),this.pendingTools.clear(),await this.checkShutdownRequested(),this.ui.requestRender();break;case"auto_compaction_start":{this.autoCompactionEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortCompaction()},this.statusContainer.clear();let t="overflow"===e.reason?"Context overflow detected, ":"";this.autoCompactionLoader=new Loader(this.ui,e=>theme.fg("accent",e),e=>theme.fg("muted",e),`${t}Auto-compacting... (${appKey(this.keybindings,"interrupt")} to cancel)`),this.statusContainer.addChild(this.autoCompactionLoader),this.ui.requestRender();break}case"auto_compaction_end":this.autoCompactionEscapeHandler&&(this.defaultEditor.onEscape=this.autoCompactionEscapeHandler,this.autoCompactionEscapeHandler=void 0),this.autoCompactionLoader&&(this.autoCompactionLoader.stop(),this.autoCompactionLoader=void 0,this.statusContainer.clear()),e.aborted?this.showStatus("Auto-compaction cancelled"):e.result?(this.chatContainer.clear(),this.rebuildChatFromMessages(),this.addMessageToChat({role:"compactionSummary",tokensBefore:e.result.tokensBefore,summary:e.result.summary,timestamp:Date.now()}),this.footer.invalidate()):e.errorMessage&&(this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(theme.fg("error",e.errorMessage),1,0))),this.flushCompactionQueue({willRetry:e.willRetry}),this.ui.requestRender();break;case"auto_retry_start":{this.retryEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortRetry()},this.statusContainer.clear();let t=Math.round(e.delayMs/1e3);this.retryLoader=new Loader(this.ui,e=>theme.fg("warning",e),e=>theme.fg("muted",e),`Retrying (${e.attempt}/${e.maxAttempts}) in ${t}s... (${appKey(this.keybindings,"interrupt")} to cancel)`),this.statusContainer.addChild(this.retryLoader),this.ui.requestRender();break}case"auto_retry_end":this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.retryLoader&&(this.retryLoader.stop(),this.retryLoader=void 0,this.statusContainer.clear()),e.success||this.showError(`Retry failed after ${e.attempt} attempts: ${e.finalError||"Unknown error"}`),this.ui.requestRender()}}getUserMessageText(e){return"user"!==e.role?"":("string"==typeof e.content?[{type:"text",text:e.content}]:e.content.filter(e=>"text"===e.type)).map(e=>e.text).join("")}showStatus(e){let t=this.chatContainer.children,i=t.length>0?t[t.length-1]:void 0,r=t.length>1?t[t.length-2]:void 0;if(i&&r&&i===this.lastStatusText&&r===this.lastStatusSpacer){this.lastStatusText.setText(theme.fg("dim",e)),this.ui.requestRender();return}let s=new Spacer(1),o=new Text(theme.fg("dim",e),1,0);this.chatContainer.addChild(s),this.chatContainer.addChild(o),this.lastStatusSpacer=s,this.lastStatusText=o,this.ui.requestRender()}addMessageToChat(e,t){switch(e.role){case"bashExecution":{let t=new BashExecutionComponent(e.command,this.ui,e.excludeFromContext);e.output&&t.appendOutput(e.output),t.setComplete(e.exitCode,e.cancelled,e.truncated?{truncated:!0}:void 0,e.fullOutputPath),this.chatContainer.addChild(t);break}case"custom":if(e.display){let t=this.session.extensionRunner?.getMessageRenderer(e.customType),i=new CustomMessageComponent(e,t,this.getMarkdownThemeWithSettings());i.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(i)}break;case"compactionSummary":{this.chatContainer.addChild(new Spacer(1));let t=new CompactionSummaryMessageComponent(e,this.getMarkdownThemeWithSettings());t.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(t);break}case"branchSummary":{this.chatContainer.addChild(new Spacer(1));let t=new BranchSummaryMessageComponent(e,this.getMarkdownThemeWithSettings());t.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(t);break}case"user":{let i=this.getUserMessageText(e);if(i){let e=parseSkillBlock(i);if(e){this.chatContainer.addChild(new Spacer(1));let t=new SkillInvocationMessageComponent(e,this.getMarkdownThemeWithSettings());if(t.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(t),e.userMessage){let t=new UserMessageComponent(e.userMessage,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(t)}}else{let e=new UserMessageComponent(i,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(e)}t?.populateHistory&&this.editor.addToHistory?.(i)}break}case"assistant":{let t=new AssistantMessageComponent(e,this.hideThinkingBlock,this.getMarkdownThemeWithSettings());this.chatContainer.addChild(t)}}}renderSessionContext(e,t={}){for(let i of(this.pendingTools.clear(),t.updateFooter&&(this.footer.invalidate(),this.updateEditorBorderColor()),e.messages))if("assistant"===i.role){for(let e of(this.addMessageToChat(i),i.content))if("toolCall"===e.type){let t=new ToolExecutionComponent(e.name,e.arguments,{showImages:this.settingsManager.getShowImages()},this.getRegisteredToolDefinition(e.name),this.ui);if(t.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(t),"aborted"===i.stopReason||"error"===i.stopReason){let e;if("aborted"===i.stopReason){let t=this.session.retryAttempt;e=t>0?`Aborted after ${t} retry attempt${t>1?"s":""}`:"Operation aborted"}else e=i.errorMessage||"Error";t.updateResult({content:[{type:"text",text:e}],isError:!0})}else this.pendingTools.set(e.id,t)}}else if("toolResult"===i.role){let e=this.pendingTools.get(i.toolCallId);e&&(e.updateResult(i),this.pendingTools.delete(i.toolCallId))}else this.addMessageToChat(i,t);this.pendingTools.clear(),this.ui.requestRender()}renderInitialMessages(){let e=this.sessionManager.buildSessionContext();this.renderSessionContext(e,{updateFooter:!0,populateHistory:!0});let t=this.sessionManager.getEntries().filter(e=>"compaction"===e.type).length;if(t>0){let e=1===t?"1 time":`${t} times`;this.showStatus(`Session compacted ${e}`)}}async getUserInput(){return new Promise(e=>{this.onInputCallback=t=>{this.onInputCallback=void 0,e(t)}})}rebuildChatFromMessages(){this.chatContainer.clear();let e=this.sessionManager.buildSessionContext();this.renderSessionContext(e)}handleCtrlC(){let e=Date.now();e-this.lastSigintTime<500?this.shutdown():(this.clearEditor(),this.lastSigintTime=e)}handleCtrlD(){this.shutdown()}isShuttingDown=!1;async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0;let e=this.session.extensionRunner;e?.hasHandlers("session_shutdown")&&await e.emit({type:"session_shutdown"}),await new Promise(e=>process.nextTick(e)),await this.ui.terminal.drainInput(1e3),this.stop(),process.exit(0)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}handleCtrlZ(){process.once("SIGCONT",()=>{this.ui.start(),this.ui.requestRender(!0)}),this.ui.stop(),process.kill(0,"SIGTSTP")}async handleFollowUp(){let e=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(e){if(this.session.isCompacting)return void(this.isExtensionCommand(e)?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e)):this.queueCompactionMessage(e,"followUp"));this.session.isStreaming?(this.editor.addToHistory?.(e),this.editor.setText(""),await this.session.prompt(e,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):this.editor.onSubmit&&this.editor.onSubmit(e)}}handleDequeue(){let e=this.restoreQueuedMessagesToEditor();0===e?this.showStatus("No queued messages to restore"):this.showStatus(`Restored ${e} queued message${e>1?"s":""} to editor`)}updateEditorBorderColor(){if(this.isBashMode)this.editor.borderColor=theme.getBashModeBorderColor();else{let e=this.session.thinkingLevel||"off";this.editor.borderColor=theme.getThinkingBorderColor(e)}this.ui.requestRender()}cycleThinkingLevel(){let e=this.session.cycleThinkingLevel();void 0===e?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${e}`))}async cycleModel(e){try{let t=await this.session.cycleModel(e);if(void 0===t){let e=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(e)}else{this.footer.invalidate(),this.updateEditorBorderColor();let e=t.model.reasoning&&"off"!==t.thinkingLevel?` (thinking: ${t.thinkingLevel})`:"";this.showStatus(`Switched to ${t.model.name||t.model.id}${e}`)}}catch(e){this.showError(e instanceof Error?e.message:String(e))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(e){for(let t of(this.toolOutputExpanded=e,this.chatContainer.children))"object"==typeof t&&null!==t&&"setExpanded"in t&&"function"==typeof t.setExpanded&&t.setExpanded(e);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.chatContainer.clear(),this.rebuildChatFromMessages(),this.streamingComponent&&this.streamingMessage&&(this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock),this.streamingComponent.updateContent(this.streamingMessage),this.chatContainer.addChild(this.streamingComponent)),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}openExternalEditor(){let e=process.env.VISUAL||process.env.EDITOR;if(!e)return void this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");let t=this.editor.getExpandedText?.()??this.editor.getText(),i=path.join(os.tmpdir(),`pi-editor-${Date.now()}.pi.md`);try{fs.writeFileSync(i,t,"utf-8"),this.ui.stop();let[r,...s]=e.split(" "),o=spawnSync(r,[...s,i],{stdio:"inherit"});if(0===o.status){let e=fs.readFileSync(i,"utf-8").replace(/\n$/,"");this.editor.setText(e)}}finally{try{fs.unlinkSync(i)}catch{}this.ui.start(),this.ui.requestRender(!0)}}clearEditor(){this.editor.setText(""),this.ui.requestRender()}showError(e){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(theme.fg("error",`Error: ${e}`),1,0)),this.ui.requestRender()}showWarning(e){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(theme.fg("warning",`Warning: ${e}`),1,0)),this.ui.requestRender()}showNewVersionNotification(e){let t=theme.fg("accent",getUpdateInstruction("@mariozechner/pi-coding-agent")),i=theme.fg("muted",`New version ${e} is available. `)+t,r=theme.fg("accent","https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md"),s=theme.fg("muted","Changelog: ")+r;this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder(e=>theme.fg("warning",e))),this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning","Update Available"))}
|
|
47
|
-
${i}
|
|
48
|
-
${s}`,1,0)),this.chatContainer.addChild(new DynamicBorder(e=>theme.fg("warning",e))),this.ui.requestRender()}getAllQueuedMessages(){return{steering:[...this.session.getSteeringMessages(),...this.compactionQueuedMessages.filter(e=>"steer"===e.mode).map(e=>e.text)],followUp:[...this.session.getFollowUpMessages(),...this.compactionQueuedMessages.filter(e=>"followUp"===e.mode).map(e=>e.text)]}}clearAllQueues(){let{steering:e,followUp:t}=this.session.clearQueue(),i=this.compactionQueuedMessages.filter(e=>"steer"===e.mode).map(e=>e.text),r=this.compactionQueuedMessages.filter(e=>"followUp"===e.mode).map(e=>e.text);return this.compactionQueuedMessages=[],{steering:[...e,...i],followUp:[...t,...r]}}updatePendingMessagesDisplay(){this.pendingMessagesContainer.clear();let{steering:e,followUp:t}=this.getAllQueuedMessages();if(e.length>0||t.length>0){for(let t of(this.pendingMessagesContainer.addChild(new Spacer(1)),e)){let e=theme.fg("dim",`Steering: ${t}`);this.pendingMessagesContainer.addChild(new TruncatedText(e,1,0))}for(let e of t){let t=theme.fg("dim",`Follow-up: ${e}`);this.pendingMessagesContainer.addChild(new TruncatedText(t,1,0))}let i=this.getAppKeyDisplay("dequeue"),r=theme.fg("dim",`↳ ${i} to edit all queued messages`);this.pendingMessagesContainer.addChild(new TruncatedText(r,1,0))}}restoreQueuedMessagesToEditor(e){let{steering:t,followUp:i}=this.clearAllQueues(),r=[...t,...i];if(0===r.length)return this.updatePendingMessagesDisplay(),e?.abort&&this.agent.abort(),0;let s=r.join("\n\n"),o=e?.currentText??this.editor.getText(),a=[s,o].filter(e=>e.trim()).join("\n\n");return this.editor.setText(a),this.updatePendingMessagesDisplay(),e?.abort&&this.agent.abort(),r.length}queueCompactionMessage(e,t){this.compactionQueuedMessages.push({text:e,mode:t}),this.editor.addToHistory?.(e),this.editor.setText(""),this.updatePendingMessagesDisplay(),this.showStatus("Queued message for after compaction")}isExtensionCommand(e){if(!e.startsWith("/"))return!1;let t=this.session.extensionRunner;if(!t)return!1;let i=e.indexOf(" "),r=-1===i?e.slice(1):e.slice(1,i);return!!t.getCommand(r)}async flushCompactionQueue(e){if(0===this.compactionQueuedMessages.length)return;let t=[...this.compactionQueuedMessages];this.compactionQueuedMessages=[],this.updatePendingMessagesDisplay();let i=e=>{this.session.clearQueue(),this.compactionQueuedMessages=t,this.updatePendingMessagesDisplay(),this.showError(`Failed to send queued message${t.length>1?"s":""}: ${e instanceof Error?e.message:String(e)}`)};try{if(e?.willRetry){for(let e of t)this.isExtensionCommand(e.text)?await this.session.prompt(e.text):"followUp"===e.mode?await this.session.followUp(e.text):await this.session.steer(e.text);this.updatePendingMessagesDisplay();return}let r=t.findIndex(e=>!this.isExtensionCommand(e.text));if(-1===r){for(let e of t)await this.session.prompt(e.text);return}let s=t.slice(0,r),o=t[r],a=t.slice(r+1);for(let e of s)await this.session.prompt(e.text);for(let e of(this.session.prompt(o.text).catch(e=>{i(e)}),a))this.isExtensionCommand(e.text)?await this.session.prompt(e.text):"followUp"===e.mode?await this.session.followUp(e.text):await this.session.steer(e.text);this.updatePendingMessagesDisplay()}catch(e){i(e)}}flushPendingBashComponents(){for(let e of this.pendingBashComponents)this.pendingMessagesContainer.removeChild(e),this.chatContainer.addChild(e);this.pendingBashComponents=[]}showSelector(e){let t=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor)},{component:i,focus:r}=e(t);this.editorContainer.clear(),this.editorContainer.addChild(i),this.ui.setFocus(r),this.ui.requestRender()}showSettingsSelector(){this.showSelector(e=>{let t=new SettingsSelectorComponent({autoCompact:this.session.autoCompactionEnabled,showImages:this.settingsManager.getShowImages(),autoResizeImages:this.settingsManager.getImageAutoResize(),blockImages:this.settingsManager.getBlockImages(),enableSkillCommands:this.settingsManager.getEnableSkillCommands(),steeringMode:this.session.steeringMode,followUpMode:this.session.followUpMode,thinkingLevel:this.session.thinkingLevel,availableThinkingLevels:this.session.getAvailableThinkingLevels(),currentTheme:this.settingsManager.getTheme()||"dark",availableThemes:getAvailableThemes(),hideThinkingBlock:this.hideThinkingBlock,collapseChangelog:this.settingsManager.getCollapseChangelog(),doubleEscapeAction:this.settingsManager.getDoubleEscapeAction(),showHardwareCursor:this.settingsManager.getShowHardwareCursor(),editorPaddingX:this.settingsManager.getEditorPaddingX(),autocompleteMaxVisible:this.settingsManager.getAutocompleteMaxVisible(),quietStartup:this.settingsManager.getQuietStartup(),clearOnShrink:this.settingsManager.getClearOnShrink()},{onAutoCompactChange:e=>{this.session.setAutoCompactionEnabled(e),this.footer.setAutoCompactEnabled(e)},onShowImagesChange:e=>{for(let t of(this.settingsManager.setShowImages(e),this.chatContainer.children))t instanceof ToolExecutionComponent&&t.setShowImages(e)},onAutoResizeImagesChange:e=>{this.settingsManager.setImageAutoResize(e)},onBlockImagesChange:e=>{this.settingsManager.setBlockImages(e)},onEnableSkillCommandsChange:e=>{this.settingsManager.setEnableSkillCommands(e),this.setupAutocomplete(this.fdPath)},onSteeringModeChange:e=>{this.session.setSteeringMode(e)},onFollowUpModeChange:e=>{this.session.setFollowUpMode(e)},onThinkingLevelChange:e=>{this.session.setThinkingLevel(e),this.footer.invalidate(),this.updateEditorBorderColor()},onThemeChange:e=>{let t=setTheme(e,!0);this.settingsManager.setTheme(e),this.ui.invalidate(),t.success||this.showError(`Failed to load theme "${e}": ${t.error}
|
|
49
|
-
Fell back to dark theme.`)},onThemePreview:e=>{setTheme(e,!0).success&&(this.ui.invalidate(),this.ui.requestRender())},onHideThinkingBlockChange:e=>{for(let t of(this.hideThinkingBlock=e,this.settingsManager.setHideThinkingBlock(e),this.chatContainer.children))t instanceof AssistantMessageComponent&&t.setHideThinkingBlock(e);this.chatContainer.clear(),this.rebuildChatFromMessages()},onCollapseChangelogChange:e=>{this.settingsManager.setCollapseChangelog(e)},onQuietStartupChange:e=>{this.settingsManager.setQuietStartup(e)},onDoubleEscapeActionChange:e=>{this.settingsManager.setDoubleEscapeAction(e)},onShowHardwareCursorChange:e=>{this.settingsManager.setShowHardwareCursor(e),this.ui.setShowHardwareCursor(e)},onEditorPaddingXChange:e=>{this.settingsManager.setEditorPaddingX(e),this.defaultEditor.setPaddingX(e),this.editor!==this.defaultEditor&&void 0!==this.editor.setPaddingX&&this.editor.setPaddingX(e)},onAutocompleteMaxVisibleChange:e=>{this.settingsManager.setAutocompleteMaxVisible(e),this.defaultEditor.setAutocompleteMaxVisible(e),this.editor!==this.defaultEditor&&void 0!==this.editor.setAutocompleteMaxVisible&&this.editor.setAutocompleteMaxVisible(e)},onClearOnShrinkChange:e=>{this.settingsManager.setClearOnShrink(e),this.ui.setClearOnShrink(e)},onCancel:()=>{e(),this.ui.requestRender()}});return{component:t,focus:t.getSettingsList()}})}async handleModelCommand(e){if(!e)return void this.showModelSelector();let t=await this.findExactModelMatch(e);if(t){try{await this.session.setModel(t),this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Model: ${t.id}`),this.checkDaxnutsEasterEgg(t)}catch(e){this.showError(e instanceof Error?e.message:String(e))}return}this.showModelSelector(e)}async findExactModelMatch(e){let t,i=e.trim();if(!i)return;let r="";if(i.includes("/")){let e=i.split("/",2);t=e[0]?.trim().toLowerCase(),r=e[1]?.trim().toLowerCase()??""}else r=i.toLowerCase();if(!r)return;let s=(await this.getModelCandidates()).filter(e=>{let i=e.id.toLowerCase()===r,s=!t||e.provider.toLowerCase()===t;return i&&s});return 1===s.length?s[0]:void 0}async getModelCandidates(){if(this.session.scopedModels.length>0)return this.session.scopedModels.map(e=>e.model);this.session.modelRegistry.refresh();try{return await this.session.modelRegistry.getAvailable()}catch{return[]}}async updateAvailableProviderCount(){let e=await this.getModelCandidates(),t=new Set(e.map(e=>e.provider));this.footerDataProvider.setAvailableProviderCount(t.size)}showModelSelector(e){this.showSelector(t=>{let i=new ModelSelectorComponent(this.ui,this.session.model,this.settingsManager,this.session.modelRegistry,this.session.scopedModels,async e=>{try{await this.session.setModel(e),this.footer.invalidate(),this.updateEditorBorderColor(),t(),this.showStatus(`Model: ${e.id}`),this.checkDaxnutsEasterEgg(e)}catch(e){t(),this.showError(e instanceof Error?e.message:String(e))}},()=>{t(),this.ui.requestRender()},e);return{component:i,focus:i}})}async showModelsSelector(){this.session.modelRegistry.refresh();let e=this.session.modelRegistry.getAvailable();if(0===e.length)return void this.showStatus("No models available");let t=this.session.scopedModels,i=t.length>0,r=new Set,s=!1;if(i){for(let e of t)r.add(`${e.model.provider}/${e.model.id}`);s=!0}else{let e=this.settingsManager.getEnabledModels();if(void 0!==e&&e.length>0)for(let t of(s=!0,await resolveModelScope(e,this.session.modelRegistry)))r.add(`${t.model.provider}/${t.model.id}`)}let o=new Set(r),a=s,n=async t=>{if(t.size>0&&t.size<e.length){let e=this.session.thinkingLevel,i=await resolveModelScope(Array.from(t),this.session.modelRegistry);this.session.setScopedModels(i.map(t=>({model:t.model,thinkingLevel:t.thinkingLevel??e})))}else this.session.setScopedModels([]);await this.updateAvailableProviderCount(),this.ui.requestRender()};this.showSelector(t=>{let i=new ScopedModelsSelectorComponent({allModels:e,enabledModelIds:o,hasEnabledModelsFilter:a},{onModelToggle:async(e,t)=>{t?o.add(e):o.delete(e),a=!0,await n(o)},onEnableAll:async e=>{for(let t of(o.clear(),e))o.add(t);a=!1,await n(o)},onClearAll:async()=>{o.clear(),a=!0,await n(o)},onToggleProvider:async(e,t,i)=>{for(let e of t)i?o.add(e):o.delete(e);a=!0,await n(o)},onPersist:t=>{let i=t.length===e.length?void 0:t;this.settingsManager.setEnabledModels(i),this.showStatus("Model selection saved to settings")},onCancel:()=>{t(),this.ui.requestRender()}});return{component:i,focus:i}})}showUserMessageSelector(){let e=this.session.getUserMessagesForForking();0===e.length?this.showStatus("No messages to fork from"):this.showSelector(t=>{let i=new UserMessageSelectorComponent(e.map(e=>({id:e.entryId,text:e.text})),async e=>{let i=await this.session.fork(e);if(i.cancelled){t(),this.ui.requestRender();return}this.chatContainer.clear(),this.renderInitialMessages(),this.editor.setText(i.selectedText),t(),this.showStatus("Branched to new session")},()=>{t(),this.ui.requestRender()});return{component:i,focus:i.getMessageList()}})}showTreeSelector(e){let t=this.sessionManager.getTree(),i=this.sessionManager.getLeafId();0===t.length?this.showStatus("No entries in session"):this.showSelector(r=>{let s=new TreeSelectorComponent(t,i,this.ui.terminal.rows,async e=>{let t,s;if(e===i){r(),this.showStatus("Already at this point");return}r();let o=!1;for(;;){let i=await this.showExtensionSelector("Summarize branch?",["No summary","Summarize","Summarize with custom prompt"]);if(void 0===i)return void this.showTreeSelector(e);if(o="No summary"!==i,"Summarize with custom prompt"!==i||(t=await this.showExtensionEditor("Custom summarization instructions"),void 0!==t))break}let a=this.defaultEditor.onEscape;o&&(this.defaultEditor.onEscape=()=>{this.session.abortBranchSummary()},this.chatContainer.addChild(new Spacer(1)),s=new Loader(this.ui,e=>theme.fg("accent",e),e=>theme.fg("muted",e),`Summarizing branch... (${appKey(this.keybindings,"interrupt")} to cancel)`),this.statusContainer.addChild(s),this.ui.requestRender());try{let i=await this.session.navigateTree(e,{summarize:o,customInstructions:t});if(i.aborted){this.showStatus("Branch summarization cancelled"),this.showTreeSelector(e);return}if(i.cancelled)return void this.showStatus("Navigation cancelled");this.chatContainer.clear(),this.renderInitialMessages(),i.editorText&&!this.editor.getText().trim()&&this.editor.setText(i.editorText),this.showStatus("Navigated to selected point")}catch(e){this.showError(e instanceof Error?e.message:String(e))}finally{s&&(s.stop(),this.statusContainer.clear()),this.defaultEditor.onEscape=a}},()=>{r(),this.ui.requestRender()},(e,t)=>{this.sessionManager.appendLabelChange(e,t),this.ui.requestRender()},e);return{component:s,focus:s}})}showSessionSelector(){this.showSelector(e=>{let t=new SessionSelectorComponent(e=>SessionManager.list(this.sessionManager.getCwd(),this.sessionManager.getSessionDir(),e),SessionManager.listAll,async t=>{e(),await this.handleResumeSession(t)},()=>{e(),this.ui.requestRender()},()=>{this.shutdown()},()=>this.ui.requestRender(),{renameSession:async(e,t)=>{let i=(t??"").trim();i&&SessionManager.open(e).appendSessionInfo(i)},showRenameHint:!0,keybindings:this.keybindings},this.sessionManager.getSessionFile());return{component:t,focus:t}})}async handleResumeSession(e){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),await this.session.switchSession(e),this.chatContainer.clear(),this.renderInitialMessages(),this.showStatus("Resumed session")}async showOAuthSelector(e){if("logout"===e){let e=this.session.modelRegistry.authStorage.list().filter(e=>this.session.modelRegistry.authStorage.get(e)?.type==="oauth");if(0===e.length)return void this.showStatus("No OAuth providers logged in. Use /login first.")}this.showSelector(t=>{let i=new OAuthSelectorComponent(e,this.session.modelRegistry.authStorage,async i=>{if(t(),"login"===e)await this.showLoginDialog(i);else{let e=getOAuthProviders().find(e=>e.id===i),t=e?.name||i;try{this.session.modelRegistry.authStorage.logout(i),this.session.modelRegistry.refresh(),await this.updateAvailableProviderCount(),this.showStatus(`Logged out of ${t}`)}catch(e){this.showError(`Logout failed: ${e instanceof Error?e.message:String(e)}`)}}},()=>{t(),this.ui.requestRender()});return{component:i,focus:i}})}async showLoginDialog(e){let t,i,r=getOAuthProviders().find(t=>t.id===e),s=r?.name||e,o=r?.usesCallbackServer??!1,a=new LoginDialogComponent(this.ui,e,(e,t)=>{});this.editorContainer.clear(),this.editorContainer.addChild(a),this.ui.setFocus(a),this.ui.requestRender();let n=new Promise((e,r)=>{t=e,i=r}),l=()=>{this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor),this.ui.requestRender()};try{await this.session.modelRegistry.authStorage.login(e,{onAuth:r=>{a.showAuth(r.url,r.instructions),o?a.showManualInput("Paste redirect URL below, or complete login in browser:").then(e=>{e&&t&&(t(e),t=void 0)}).catch(()=>{i&&(i(Error("Login cancelled")),i=void 0)}):"github-copilot"===e&&a.showWaiting("Waiting for browser authentication...")},onPrompt:async e=>a.showPrompt(e.message,e.placeholder),onProgress:e=>{a.showProgress(e)},onManualCodeInput:()=>n,signal:a.signal}),l(),this.session.modelRegistry.refresh(),await this.updateAvailableProviderCount(),this.showStatus(`Logged in to ${s}. Credentials saved to ${getAuthPath()}`)}catch(t){l();let e=t instanceof Error?t.message:String(t);"Login cancelled"!==e&&this.showError(`Failed to login to ${s}: ${e}`)}}async handleReloadCommand(){if(this.session.isStreaming)return void this.showWarning("Wait for the current response to finish before reloading.");if(this.session.isCompacting)return void this.showWarning("Wait for compaction to finish before reloading.");this.resetExtensionUI();let e=new BorderedLoader(this.ui,theme,"Reloading extensions, skills, prompts, themes...",{cancellable:!1}),t=this.editor;this.editorContainer.clear(),this.editorContainer.addChild(e),this.ui.setFocus(e),this.ui.requestRender();let i=t=>{e.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(t),this.ui.setFocus(t),this.ui.requestRender()};try{await this.session.reload(),setRegisteredThemes(this.session.resourceLoader.getThemes().themes),this.hideThinkingBlock=this.settingsManager.getHideThinkingBlock();let e=this.settingsManager.getTheme(),t=e?setTheme(e,!0):{success:!0};t.success||this.showError(`Failed to load theme "${e}": ${t.error}
|
|
50
|
-
Fell back to dark theme.`);let r=this.settingsManager.getEditorPaddingX(),s=this.settingsManager.getAutocompleteMaxVisible();this.defaultEditor.setPaddingX(r),this.defaultEditor.setAutocompleteMaxVisible(s),this.editor!==this.defaultEditor&&(this.editor.setPaddingX?.(r),this.editor.setAutocompleteMaxVisible?.(s)),this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor()),this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink()),this.setupAutocomplete(this.fdPath);let o=this.session.extensionRunner;o&&this.setupExtensionShortcuts(o),this.rebuildChatFromMessages(),i(this.editor),this.showLoadedResources({extensionPaths:o?.getExtensionPaths()??[],force:!1,showDiagnosticsWhenQuiet:!0});let a=this.session.modelRegistry.getError();a&&this.showError(`models.json error: ${a}`),this.showStatus("Reloaded extensions, skills, prompts, themes")}catch(e){i(t),this.showError(`Reload failed: ${e instanceof Error?e.message:String(e)}`)}}async handleExportCommand(e){let t=e.split(/\s+/),i=t.length>1?t[1]:void 0;try{let e=await this.session.exportToHtml(i);this.showStatus(`Session exported to: ${e}`)}catch(e){this.showError(`Failed to export session: ${e instanceof Error?e.message:"Unknown error"}`)}}async handleShareCommand(){try{let e=spawnSync("gh",["auth","status"],{encoding:"utf-8"});if(0!==e.status)return void this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.")}catch{this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");return}let e=path.join(os.tmpdir(),"session.html");try{await this.session.exportToHtml(e)}catch(e){this.showError(`Failed to export session: ${e instanceof Error?e.message:"Unknown error"}`);return}let t=new BorderedLoader(this.ui,theme,"Creating gist...");this.editorContainer.clear(),this.editorContainer.addChild(t),this.ui.setFocus(t),this.ui.requestRender();let i=()=>{t.dispose(),this.editorContainer.clear(),this.editorContainer.addChild(this.editor),this.ui.setFocus(this.editor);try{fs.unlinkSync(e)}catch{}},r=null;t.onAbort=()=>{r?.kill(),i(),this.showStatus("Share cancelled")};try{let s=await new Promise(t=>{r=spawn("gh",["gist","create","--public=false",e]);let i="",s="";r.stdout?.on("data",e=>{i+=e.toString()}),r.stderr?.on("data",e=>{s+=e.toString()}),r.on("close",e=>t({stdout:i,stderr:s,code:e}))});if(t.signal.aborted)return;if(i(),0!==s.code){let e=s.stderr?.trim()||"Unknown error";this.showError(`Failed to create gist: ${e}`);return}let o=s.stdout?.trim(),a=o?.split("/").pop();if(!a)return void this.showError("Failed to parse gist ID from gh output");let n=getShareViewerUrl(a);this.showStatus(`Share URL: ${n}
|
|
51
|
-
Gist: ${o}`)}catch(e){t.signal.aborted||(i(),this.showError(`Failed to create gist: ${e instanceof Error?e.message:"Unknown error"}`))}}handleCopyCommand(){let e=this.session.getLastAssistantText();if(!e)return void this.showError("No agent messages to copy yet.");try{copyToClipboard(e),this.showStatus("Copied last agent message to clipboard")}catch(e){this.showError(e instanceof Error?e.message:String(e))}}handleNameCommand(e){let t=e.replace(/^\/name\s*/,"").trim();if(!t){let e=this.sessionManager.getSessionName();e?(this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(theme.fg("dim",`Session name: ${e}`),1,0))):this.showWarning("Usage: /name <name>"),this.ui.requestRender();return}this.sessionManager.appendSessionInfo(t),this.updateTerminalTitle(),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(theme.fg("dim",`Session name set: ${t}`),1,0)),this.ui.requestRender()}handleSessionCommand(){let e=this.session.getSessionStats(),t=this.sessionManager.getSessionName(),i=`${theme.bold("Session Info")}
|
|
52
|
-
|
|
53
|
-
`;t&&(i+=`${theme.fg("dim","Name:")} ${t}
|
|
54
|
-
`),i+=`${theme.fg("dim","File:")} ${e.sessionFile??"In-memory"}
|
|
55
|
-
${theme.fg("dim","ID:")} ${e.sessionId}
|
|
56
|
-
|
|
57
|
-
${theme.bold("Messages")}
|
|
58
|
-
${theme.fg("dim","User:")} ${e.userMessages}
|
|
59
|
-
${theme.fg("dim","Assistant:")} ${e.assistantMessages}
|
|
60
|
-
${theme.fg("dim","Tool Calls:")} ${e.toolCalls}
|
|
61
|
-
${theme.fg("dim","Tool Results:")} ${e.toolResults}
|
|
62
|
-
${theme.fg("dim","Total:")} ${e.totalMessages}
|
|
63
|
-
|
|
64
|
-
${theme.bold("Tokens")}
|
|
65
|
-
${theme.fg("dim","Input:")} ${e.tokens.input.toLocaleString()}
|
|
66
|
-
${theme.fg("dim","Output:")} ${e.tokens.output.toLocaleString()}
|
|
67
|
-
`,e.tokens.cacheRead>0&&(i+=`${theme.fg("dim","Cache Read:")} ${e.tokens.cacheRead.toLocaleString()}
|
|
68
|
-
`),e.tokens.cacheWrite>0&&(i+=`${theme.fg("dim","Cache Write:")} ${e.tokens.cacheWrite.toLocaleString()}
|
|
69
|
-
`),i+=`${theme.fg("dim","Total:")} ${e.tokens.total.toLocaleString()}
|
|
70
|
-
`,e.cost>0&&(i+=`
|
|
71
|
-
${theme.bold("Cost")}
|
|
72
|
-
${theme.fg("dim","Total:")} ${e.cost.toFixed(4)}`),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(i,1,0)),this.ui.requestRender()}handleChangelogCommand(){let e=getChangelogPath(),t=parseChangelog(e),i=t.length>0?t.reverse().map(e=>e.content).join("\n\n"):"No changelog entries found.";this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder),this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent","What's New")),1,0)),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Markdown(i,1,1,this.getMarkdownThemeWithSettings())),this.chatContainer.addChild(new DynamicBorder),this.ui.requestRender()}capitalizeKey(e){return e.split("/").map(e=>e.split("+").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("+")).join("/")}getAppKeyDisplay(e){return this.capitalizeKey(appKey(this.keybindings,e))}getEditorKeyDisplay(e){return this.capitalizeKey(editorKey(e))}handleHotkeysCommand(){let e=this.getEditorKeyDisplay("cursorWordLeft"),t=this.getEditorKeyDisplay("cursorWordRight"),i=this.getEditorKeyDisplay("cursorLineStart"),r=this.getEditorKeyDisplay("cursorLineEnd"),s=this.getEditorKeyDisplay("jumpForward"),o=this.getEditorKeyDisplay("jumpBackward"),a=this.getEditorKeyDisplay("pageUp"),n=this.getEditorKeyDisplay("pageDown"),l=this.getEditorKeyDisplay("submit"),d=this.getEditorKeyDisplay("newLine"),c=this.getEditorKeyDisplay("deleteWordBackward"),u=this.getEditorKeyDisplay("deleteWordForward"),p=this.getEditorKeyDisplay("deleteToLineStart"),h=this.getEditorKeyDisplay("deleteToLineEnd"),m=this.getEditorKeyDisplay("yank"),g=this.getEditorKeyDisplay("yankPop"),f=this.getEditorKeyDisplay("undo"),w=this.getEditorKeyDisplay("tab"),k=this.getAppKeyDisplay("interrupt"),y=this.getAppKeyDisplay("clear"),v=this.getAppKeyDisplay("exit"),b=this.getAppKeyDisplay("suspend"),S=this.getAppKeyDisplay("cycleThinkingLevel"),T=this.getAppKeyDisplay("cycleModelForward"),C=this.getAppKeyDisplay("selectModel"),E=this.getAppKeyDisplay("expandTools"),x=this.getAppKeyDisplay("toggleThinking"),I=this.getAppKeyDisplay("externalEditor"),A=this.getAppKeyDisplay("followUp"),O=this.getAppKeyDisplay("dequeue"),P=`
|
|
73
|
-
**Navigation**
|
|
74
|
-
| Key | Action |
|
|
75
|
-
|-----|--------|
|
|
76
|
-
| \`Arrow keys\` | Move cursor / browse history (Up when empty) |
|
|
77
|
-
| \`${e}\` / \`${t}\` | Move by word |
|
|
78
|
-
| \`${i}\` | Start of line |
|
|
79
|
-
| \`${r}\` | End of line |
|
|
80
|
-
| \`${s}\` | Jump forward to character |
|
|
81
|
-
| \`${o}\` | Jump backward to character |
|
|
82
|
-
| \`${a}\` / \`${n}\` | Scroll by page |
|
|
83
|
-
|
|
84
|
-
**Editing**
|
|
85
|
-
| Key | Action |
|
|
86
|
-
|-----|--------|
|
|
87
|
-
| \`${l}\` | Send message |
|
|
88
|
-
| \`${d}\` | New line${"win32"===process.platform?" (Ctrl+Enter on Windows Terminal)":""} |
|
|
89
|
-
| \`${c}\` | Delete word backwards |
|
|
90
|
-
| \`${u}\` | Delete word forwards |
|
|
91
|
-
| \`${p}\` | Delete to start of line |
|
|
92
|
-
| \`${h}\` | Delete to end of line |
|
|
93
|
-
| \`${m}\` | Paste the most-recently-deleted text |
|
|
94
|
-
| \`${g}\` | Cycle through the deleted text after pasting |
|
|
95
|
-
| \`${f}\` | Undo |
|
|
96
|
-
|
|
97
|
-
**Other**
|
|
98
|
-
| Key | Action |
|
|
99
|
-
|-----|--------|
|
|
100
|
-
| \`${w}\` | Path completion / accept autocomplete |
|
|
101
|
-
| \`${k}\` | Cancel autocomplete / abort streaming |
|
|
102
|
-
| \`${y}\` | Clear editor (first) / exit (second) |
|
|
103
|
-
| \`${v}\` | Exit (when editor is empty) |
|
|
104
|
-
| \`${b}\` | Suspend to background |
|
|
105
|
-
| \`${S}\` | Cycle thinking level |
|
|
106
|
-
| \`${T}\` | Cycle models |
|
|
107
|
-
| \`${C}\` | Open model selector |
|
|
108
|
-
| \`${E}\` | Toggle tool output expansion |
|
|
109
|
-
| \`${x}\` | Toggle thinking block visibility |
|
|
110
|
-
| \`${I}\` | Edit message in external editor |
|
|
111
|
-
| \`${A}\` | Queue follow-up message |
|
|
112
|
-
| \`${O}\` | Restore queued messages |
|
|
113
|
-
| \`Ctrl+V\` | Paste image from clipboard |
|
|
114
|
-
| \`/\` | Slash commands |
|
|
115
|
-
| \`!\` | Run bash command |
|
|
116
|
-
| \`!!\` | Run bash command (excluded from context) |
|
|
117
|
-
`,R=this.session.extensionRunner;if(R){let e=R.getShortcuts(this.keybindings.getEffectiveConfig());if(e.size>0)for(let[t,i]of(P+=`
|
|
118
|
-
**Extensions**
|
|
119
|
-
| Key | Action |
|
|
120
|
-
|-----|--------|
|
|
121
|
-
`,e)){let e=i.description??i.extensionPath,r=t.replace(/\b\w/g,e=>e.toUpperCase());P+=`| \`${r}\` | ${e} |
|
|
122
|
-
`}}this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder),this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent","Keyboard Shortcuts")),1,0)),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Markdown(P.trim(),1,1,this.getMarkdownThemeWithSettings())),this.chatContainer.addChild(new DynamicBorder),this.ui.requestRender()}async handleClearCommand(){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear(),await this.session.newSession(),this.chatContainer.clear(),this.pendingMessagesContainer.clear(),this.compactionQueuedMessages=[],this.streamingComponent=void 0,this.streamingMessage=void 0,this.pendingTools.clear(),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(`${theme.fg("accent","✓ New session started")}`,1,1)),this.ui.requestRender()}handleDebugCommand(){let e=this.ui.terminal.columns,t=this.ui.terminal.rows,i=this.ui.render(e),r=getDebugLogPath(),s=[`Debug output at ${new Date().toISOString()}`,`Terminal: ${e}x${t}`,`Total lines: ${i.length}`,"","=== All rendered lines with visible widths ===",...i.map((e,t)=>{let i=visibleWidth(e),r=JSON.stringify(e);return`[${t}] (w=${i}) ${r}`}),"","=== Agent messages (JSONL) ===",...this.session.messages.map(e=>JSON.stringify(e)),""].join("\n");fs.mkdirSync(path.dirname(r),{recursive:!0}),fs.writeFileSync(r,s),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Text(`${theme.fg("accent","✓ Debug log written")}
|
|
123
|
-
${theme.fg("muted",r)}`,1,1)),this.ui.requestRender()}handleArminSaysHi(){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ArminComponent(this.ui)),this.ui.requestRender()}handleDaxnuts(){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DaxnutsComponent(this.ui)),this.ui.requestRender()}checkDaxnutsEasterEgg(e){"opencode"===e.provider&&e.id.toLowerCase().includes("kimi-k2.5")&&this.handleDaxnuts()}async handleBashCommand(e,t=!1){let i=this.session.extensionRunner,r=i?await i.emitUserBash({type:"user_bash",command:e,excludeFromContext:t,cwd:process.cwd()}):void 0;if(r?.result){let i=r.result;this.bashComponent=new BashExecutionComponent(e,this.ui,t),this.session.isStreaming?(this.pendingMessagesContainer.addChild(this.bashComponent),this.pendingBashComponents.push(this.bashComponent)):this.chatContainer.addChild(this.bashComponent),i.output&&this.bashComponent.appendOutput(i.output),this.bashComponent.setComplete(i.exitCode,i.cancelled,i.truncated?{truncated:!0,content:i.output}:void 0,i.fullOutputPath),this.session.recordBashResult(e,i,{excludeFromContext:t}),this.bashComponent=void 0,this.ui.requestRender();return}let s=this.session.isStreaming;this.bashComponent=new BashExecutionComponent(e,this.ui,t),s?(this.pendingMessagesContainer.addChild(this.bashComponent),this.pendingBashComponents.push(this.bashComponent)):this.chatContainer.addChild(this.bashComponent),this.ui.requestRender();try{let i=await this.session.executeBash(e,e=>{this.bashComponent&&(this.bashComponent.appendOutput(e),this.ui.requestRender())},{excludeFromContext:t,operations:r?.operations});this.bashComponent&&this.bashComponent.setComplete(i.exitCode,i.cancelled,i.truncated?{truncated:!0,content:i.output}:void 0,i.fullOutputPath)}catch(e){this.bashComponent&&this.bashComponent.setComplete(void 0,!1),this.showError(`Bash command failed: ${e instanceof Error?e.message:"Unknown error"}`)}this.bashComponent=void 0,this.ui.requestRender()}async handleCompactCommand(e){this.sessionManager.getEntries().filter(e=>"message"===e.type).length<2?this.showWarning("Nothing to compact (no messages yet)"):await this.executeCompaction(e,!1)}async executeCompaction(e,t=!1){let i;this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.statusContainer.clear();let r=this.defaultEditor.onEscape;this.defaultEditor.onEscape=()=>{this.session.abortCompaction()},this.chatContainer.addChild(new Spacer(1));let s=`(${appKey(this.keybindings,"interrupt")} to cancel)`,o=t?`Auto-compacting context... ${s}`:`Compacting context... ${s}`,a=new Loader(this.ui,e=>theme.fg("accent",e),e=>theme.fg("muted",e),o);this.statusContainer.addChild(a),this.ui.requestRender();try{i=await this.session.compact(e),this.rebuildChatFromMessages();let t=createCompactionSummaryMessage(i.summary,i.tokensBefore,new Date().toISOString());this.addMessageToChat(t),this.footer.invalidate()}catch(t){let e=t instanceof Error?t.message:String(t);"Compaction cancelled"===e||t instanceof Error&&"AbortError"===t.name?this.showError("Compaction cancelled"):this.showError(`Compaction failed: ${e}`)}finally{a.stop(),this.statusContainer.clear(),this.defaultEditor.onEscape=r}return this.flushCompactionQueue({willRetry:!1}),i}stop(){this.loadingAnimation&&(this.loadingAnimation.stop(),this.loadingAnimation=void 0),this.footer.dispose(),this.footerDataProvider.dispose(),this.unsubscribe&&this.unsubscribe(),this.isInitialized&&(this.ui.stop(),this.isInitialized=!1)}}t()}catch(e){t(e)}})},9354(e,t,i){i.a(e,async function(e,r){try{let O,P,R,M,L,N;i.d(t,{CK:()=>b,hH:()=>A,i_:()=>w,ju:()=>I,kX:()=>x,pd:()=>E,sQ:()=>C,w4:()=>U,wY:()=>T});var s=i(3024),o=i(6760),a=i(4204),n=i(8068),l=i(5590),d=i(3994),c=i(7103),u=e([a,n,l,d]);[a,n,l,d]=u.then?(await u)():u;let D=a.Type.Union([a.Type.String(),a.Type.Integer({minimum:0,maximum:255})]),_=a.Type.Object({$schema:a.Type.Optional(a.Type.String()),name:a.Type.String(),vars:a.Type.Optional(a.Type.Record(a.Type.String(),D)),colors:a.Type.Object({accent:D,border:D,borderAccent:D,borderMuted:D,success:D,error:D,warning:D,muted:D,dim:D,text:D,thinkingText:D,selectedBg:D,userMessageBg:D,userMessageText:D,customMessageBg:D,customMessageText:D,customMessageLabel:D,toolPendingBg:D,toolSuccessBg:D,toolErrorBg:D,toolTitle:D,toolOutput:D,mdHeading:D,mdLink:D,mdLinkUrl:D,mdCode:D,mdCodeBlock:D,mdCodeBlockBorder:D,mdQuote:D,mdQuoteBorder:D,mdHr:D,mdListBullet:D,toolDiffAdded:D,toolDiffRemoved:D,toolDiffContext:D,syntaxComment:D,syntaxKeyword:D,syntaxFunction:D,syntaxVariable:D,syntaxString:D,syntaxNumber:D,syntaxType:D,syntaxOperator:D,syntaxPunctuation:D,thinkingOff:D,thinkingMinimal:D,thinkingLow:D,thinkingMedium:D,thinkingHigh:D,thinkingXhigh:D,bashMode:D}),export:a.Type.Optional(a.Type.Object({pageBg:a.Type.Optional(D),cardBg:a.Type.Optional(D),infoBg:a.Type.Optional(D)}))}),F=n.TypeCompiler.Compile(_);function p(e){let t=e.replace("#","");if(6!==t.length)throw Error(`Invalid hex color: ${e}`);let i=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),s=parseInt(t.substring(4,6),16);if(Number.isNaN(i)||Number.isNaN(r)||Number.isNaN(s))throw Error(`Invalid hex color: ${e}`);return{r:i,g:r,b:s}}let H=[0,95,135,175,215,255],$=Array.from({length:24},(e,t)=>8+10*t);function h(e){let t=1/0,i=0;for(let r=0;r<H.length;r++){let s=Math.abs(e-H[r]);s<t&&(t=s,i=r)}return i}function m(e,t,i,r,s,o){let a=e-r,n=t-s,l=i-o;return a*a*.299+n*n*.587+l*l*.114}function g(e){let t,i,r,s,o,a,n,l,d,c,u,g,f,{r:w,g:k,b:y}=p(e);return t=h(w),i=h(k),r=h(y),s=H[t],o=H[i],a=H[r],n=m(w,k,y,s,o,a),l=Math.round(.299*w+.587*k+.114*y),c=$[d=function(e){let t=1/0,i=0;for(let r=0;r<$.length;r++){let s=Math.abs(e-$[r]);s<t&&(t=s,i=r)}return i}(l)],u=m(w,k,y,c,c,c),g=Math.max(w,k,y),f=Math.min(w,k,y),g-f<10&&u<n?232+d:16+36*t+6*i+r}class j{name;sourcePath;fgColors;bgColors;mode;constructor(e,t,i,r={}){for(let[t,s]of(this.name=r.name,this.sourcePath=r.sourcePath,this.mode=i,this.fgColors=new Map,Object.entries(e)))this.fgColors.set(t,function(e,t){if(""===e)return"\x1b[39m";if("number"==typeof e)return`\x1b[38;5;${e}m`;if(e.startsWith("#"))if("truecolor"===t){let{r:t,g:i,b:r}=p(e);return`\x1b[38;2;${t};${i};${r}m`}else{let t=g(e);return`\x1b[38;5;${t}m`}throw Error(`Invalid color value: ${e}`)}(s,i));for(let[e,r]of(this.bgColors=new Map,Object.entries(t)))this.bgColors.set(e,function(e,t){if(""===e)return"\x1b[49m";if("number"==typeof e)return`\x1b[48;5;${e}m`;if(e.startsWith("#"))if("truecolor"===t){let{r:t,g:i,b:r}=p(e);return`\x1b[48;2;${t};${i};${r}m`}else{let t=g(e);return`\x1b[48;5;${t}m`}throw Error(`Invalid color value: ${e}`)}(r,i))}fg(e,t){let i=this.fgColors.get(e);if(!i)throw Error(`Unknown theme color: ${e}`);return`${i}${t}\x1b[39m`}bg(e,t){let i=this.bgColors.get(e);if(!i)throw Error(`Unknown theme background color: ${e}`);return`${i}${t}\x1b[49m`}bold(e){return l.default.bold(e)}italic(e){return l.default.italic(e)}underline(e){return l.default.underline(e)}inverse(e){return l.default.inverse(e)}strikethrough(e){return l.default.strikethrough(e)}getFgAnsi(e){let t=this.fgColors.get(e);if(!t)throw Error(`Unknown theme color: ${e}`);return t}getBgAnsi(e){let t=this.bgColors.get(e);if(!t)throw Error(`Unknown theme background color: ${e}`);return t}getColorMode(){return this.mode}getThinkingBorderColor(e){switch(e){case"off":default:return e=>this.fg("thinkingOff",e);case"minimal":return e=>this.fg("thinkingMinimal",e);case"low":return e=>this.fg("thinkingLow",e);case"medium":return e=>this.fg("thinkingMedium",e);case"high":return e=>this.fg("thinkingHigh",e);case"xhigh":return e=>this.fg("thinkingXhigh",e)}}getBashModeBorderColor(){return e=>this.fg("bashMode",e)}}function f(){if(!O){let e=(0,c.GO)(),t=o.join(e,"dark.json"),i=o.join(e,"light.json");O={dark:JSON.parse(s.readFileSync(t,"utf-8")),light:JSON.parse(s.readFileSync(i,"utf-8"))}}return O}function w(){let e=new Set(Object.keys(f())),t=(0,c.V8)();if(s.existsSync(t))for(let i of s.readdirSync(t))i.endsWith(".json")&&e.add(i.slice(0,-5));for(let t of q.keys())e.add(t);return Array.from(e).sort()}function k(e,t){let i;try{i=JSON.parse(t)}catch(t){throw Error(`Failed to parse theme ${e}: ${t}`)}return function(e,t){if(!F.Check(t)){let i=Array.from(F.Errors(t)),r=[],s=[];for(let e of i){let t=e.path.match(/^\/colors\/(\w+)$/);t&&e.message.includes("Required")?r.push(t[1]):s.push(` - ${e.path}: ${e.message}`)}let o=`Invalid theme "${e}":
|
|
124
|
-
`;throw r.length>0&&(o+="\nMissing required color tokens:\n",o+=r.map(e=>` - ${e}`).join("\n"),o+='\n\nPlease add these colors to your theme\'s "colors" object.',o+="\nSee the built-in themes (dark.json, light.json) for reference values."),s.length>0&&(o+=`
|
|
125
|
-
|
|
126
|
-
Other errors:
|
|
127
|
-
${s.join("\n")}`),Error(o)}return t}(e,i)}function y(e,t){let i=q.get(e);if(i)return i;let r=function(e){let t=f();if(e in t)return t[e];let i=q.get(e);if(i?.sourcePath){let e=s.readFileSync(i.sourcePath,"utf-8");return k(i.sourcePath,e)}if(i)throw Error(`Theme "${e}" does not have a source path for export`);let r=(0,c.V8)(),a=o.join(r,`${e}.json`);if(!s.existsSync(a))throw Error(`Theme not found: ${e}`);let n=s.readFileSync(a,"utf-8");return k(e,n)}(e);return function(e,t,i){let r=t??function(){let e=process.env.COLORTERM;if("truecolor"===e||"24bit"===e||process.env.WT_SESSION)return"truecolor";let t=process.env.TERM||"";return"dumb"===t||""===t||"linux"===t||"Apple_Terminal"===process.env.TERM_PROGRAM?"256color":"truecolor"}(),s=function(e,t={}){let i={};for(let[r,s]of Object.entries(e))i[r]=function e(t,i,r=new Set){if("number"==typeof t||""===t||t.startsWith("#"))return t;if(r.has(t))throw Error(`Circular variable reference detected: ${t}`);if(!(t in i))throw Error(`Variable reference not found: ${t}`);return r.add(t),e(i[t],i,r)}(s,t);return i}(e.colors,e.vars),o={},a={},n=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);for(let[e,t]of Object.entries(s))n.has(e)?a[e]=t:o[e]=t;return new j(o,a,r,{name:e.name,sourcePath:void 0})}(r,t)}let z=Symbol.for("@mariozechner/pi-coding-agent:theme"),U=new Proxy({},{get(e,t){let i=globalThis[z];if(!i)throw Error("Theme not initialized. Call initTheme() first.");return i[t]}});function v(e){globalThis[z]=e}let q=new Map;function b(e,t=!1){let i=e??function(){let e=process.env.COLORFGBG||"";if(e){let t=e.split(";");if(t.length>=2){let e=parseInt(t[1],10);if(!Number.isNaN(e))return e<8?"dark":"light"}}return"dark"}();P=i;try{v(y(i)),t&&function(){if(R&&(R.close(),R=void 0),!P||"dark"===P||"light"===P)return;let e=(0,c.V8)(),t=o.join(e,`${P}.json`);if(s.existsSync(t))try{R=s.watch(t,e=>{"change"===e?setTimeout(()=>{try{v(y(P)),M&&M()}catch(e){}},100):"rename"===e&&setTimeout(()=>{!s.existsSync(t)&&(P="dark",v(y("dark")),R&&(R.close(),R=void 0),M&&M())},100)})}catch(e){}}()}catch(e){P="dark",v(y("dark"))}}function S(e){(L!==e||!N)&&(L=e,N={keyword:t=>e.fg("syntaxKeyword",t),built_in:t=>e.fg("syntaxType",t),literal:t=>e.fg("syntaxNumber",t),number:t=>e.fg("syntaxNumber",t),string:t=>e.fg("syntaxString",t),comment:t=>e.fg("syntaxComment",t),function:t=>e.fg("syntaxFunction",t),title:t=>e.fg("syntaxFunction",t),class:t=>e.fg("syntaxType",t),type:t=>e.fg("syntaxType",t),attr:t=>e.fg("syntaxVariable",t),variable:t=>e.fg("syntaxVariable",t),params:t=>e.fg("syntaxVariable",t),operator:t=>e.fg("syntaxOperator",t),punctuation:t=>e.fg("syntaxPunctuation",t)});return N}function T(e,t){let i={language:t&&(0,d.supportsLanguage)(t)?t:void 0,ignoreIllegals:!0,theme:S(U)};try{return(0,d.highlight)(e,i).split("\n")}catch{return e.split("\n")}}function C(e){let t=e.split(".").pop()?.toLowerCase();if(t)return({ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"})[t]}function E(){return{heading:e=>U.fg("mdHeading",e),link:e=>U.fg("mdLink",e),linkUrl:e=>U.fg("mdLinkUrl",e),code:e=>U.fg("mdCode",e),codeBlock:e=>U.fg("mdCodeBlock",e),codeBlockBorder:e=>U.fg("mdCodeBlockBorder",e),quote:e=>U.fg("mdQuote",e),quoteBorder:e=>U.fg("mdQuoteBorder",e),hr:e=>U.fg("mdHr",e),listBullet:e=>U.fg("mdListBullet",e),bold:e=>U.bold(e),italic:e=>U.italic(e),underline:e=>U.underline(e),strikethrough:e=>l.default.strikethrough(e),highlightCode:(e,t)=>{let i={language:t&&(0,d.supportsLanguage)(t)?t:void 0,ignoreIllegals:!0,theme:S(U)};try{return(0,d.highlight)(e,i).split("\n")}catch{return e.split("\n").map(e=>U.fg("mdCodeBlock",e))}}}}function x(){return{selectedPrefix:e=>U.fg("accent",e),selectedText:e=>U.fg("accent",e),description:e=>U.fg("muted",e),scrollInfo:e=>U.fg("muted",e),noMatch:e=>U.fg("muted",e)}}function I(){return{borderColor:e=>U.fg("borderMuted",e),selectList:x()}}function A(){return{label:(e,t)=>t?U.fg("accent",e):e,value:(e,t)=>t?U.fg("accent",e):U.fg("muted",e),description:e=>U.fg("dim",e),cursor:U.fg("accent","→ "),hint:e=>U.fg("dim",e)}}r()}catch(e){r(e)}})},7054(e,t,i){i(1421),i(481)},6013(e,t,i){i.a(e,async function(e,t){try{i(7598),i(3785);var r=i(9354),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},2809(e,t,i){i(9896),i(7103)},6691(e,t,i){i(5317);let r=(0,i(3339).createRequire)("file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/utils/clipboard-native.js"),s="linux"!==process.platform||!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY);if(!process.env.TERMUX_VERSION&&s)try{r("@mariozechner/clipboard")}catch{}i(7429)},4917(e,t,i){i(5317),i(857),i(6691)},1957(e,t,i){i.a(e,async function(e,r){try{i.d(t,{y:()=>a});var s=i(1464),o=e([s]);s=(o.then?(await o)():o)[0];let a=e=>{let{yamlString:t,body:i}=(e=>{let t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(!t.startsWith("---"))return{yamlString:null,body:t};let i=t.indexOf("\n---",3);return -1===i?{yamlString:null,body:t}:{yamlString:t.slice(4,i),body:t.slice(i+4).trim()}})(e);return t?{frontmatter:(0,s.parse)(t)??{},body:i}:{frontmatter:{},body:i}};r()}catch(e){r(e)}})},891(e,t,i){i.a(e,async function(e,t){try{var r=i(8632),s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},360(e,t,i){i.d(t,{Q:()=>s});var r=i(7429);async function s(e,t){if("image/png"===t)return{data:e,mimeType:t};let i=await (0,r.P)();if(!i)return null;try{let t=new Uint8Array(Buffer.from(e,"base64")),r=i.PhotonImage.new_from_byteslice(t);try{let e=r.get_bytes();return{data:Buffer.from(e).toString("base64"),mimeType:"image/png"}}finally{r.free()}}catch{return null}}},7635(e,t,i){i.d(t,{u:()=>a,y:()=>o});var r=i(7429);let s={maxWidth:2e3,maxHeight:2e3,maxBytes:4718592,jpegQuality:80};async function o(e,t){let i,o={...s,...t},a=Buffer.from(e.data,"base64"),n=await (0,r.P)();if(!n)return{data:e.data,mimeType:e.mimeType,originalWidth:0,originalHeight:0,width:0,height:0,wasResized:!1};try{let t,r=(i=n.PhotonImage.new_from_byteslice(new Uint8Array(a))).get_width(),s=i.get_height(),d=e.mimeType?.split("/")[1]??"png",c=a.length;if(r<=o.maxWidth&&s<=o.maxHeight&&c<=o.maxBytes)return{data:e.data,mimeType:e.mimeType??`image/${d}`,originalWidth:r,originalHeight:s,width:r,height:s,wasResized:!1};let u=r,p=s;function l(e,t,r){let s=n.resize(i,e,t,n.SamplingFilter.Lanczos3);try{var o,a;let e=s.get_bytes(),t=s.get_bytes_jpeg(r);return o={buffer:e,mimeType:"image/png"},a={buffer:t,mimeType:"image/jpeg"},o.buffer.length<=a.buffer.length?o:a}finally{s.free()}}u>o.maxWidth&&(p=Math.round(p*o.maxWidth/u),u=o.maxWidth),p>o.maxHeight&&(u=Math.round(u*o.maxHeight/p),p=o.maxHeight);let h=[85,70,55,40],m=u,g=p;if((t=l(u,p,o.jpegQuality)).buffer.length<=o.maxBytes)return{data:Buffer.from(t.buffer).toString("base64"),mimeType:t.mimeType,originalWidth:r,originalHeight:s,width:m,height:g,wasResized:!0};for(let e of h)if((t=l(u,p,e)).buffer.length<=o.maxBytes)return{data:Buffer.from(t.buffer).toString("base64"),mimeType:t.mimeType,originalWidth:r,originalHeight:s,width:m,height:g,wasResized:!0};for(let e of[1,.75,.5,.35,.25]){if(m=Math.round(u*e),g=Math.round(p*e),m<100||g<100)break;for(let e of h)if((t=l(m,g,e)).buffer.length<=o.maxBytes)return{data:Buffer.from(t.buffer).toString("base64"),mimeType:t.mimeType,originalWidth:r,originalHeight:s,width:m,height:g,wasResized:!0}}return{data:Buffer.from(t.buffer).toString("base64"),mimeType:t.mimeType,originalWidth:r,originalHeight:s,width:m,height:g,wasResized:!0}}catch{return{data:e.data,mimeType:e.mimeType,originalWidth:0,originalHeight:0,width:0,height:0,wasResized:!1}}finally{i&&i.free()}}function a(e){if(!e.wasResized)return;let t=e.originalWidth/e.width;return`[Image: original ${e.originalWidth}x${e.originalHeight}, displayed at ${e.width}x${e.height}. Multiply coordinates by ${t.toFixed(2)} to map to original image.]`}},4459(e,t,i){i.a(e,async function(e,r){try{i.d(t,{r:()=>n});var s=i(1455),o=i(1852),a=e([o]);o=(a.then?(await a)():a)[0];let l=new Set(["image/jpeg","image/png","image/gif","image/webp"]);async function n(e){let t=await (0,s.open)(e,"r");try{let e=Buffer.alloc(4100),{bytesRead:i}=await t.read(e,0,4100,0);if(0===i)return null;let r=await (0,o.fileTypeFromBuffer)(e.subarray(0,i));if(!r||!l.has(r.mime))return null;return r.mime}finally{await t.close()}}r()}catch(e){r(e)}})},7429(e,t,i){i.d(t,{P:()=>c});var r=i(3339),s=i(6928),o=i(7016);let a=(0,r.createRequire)("file:///Users/lidh04/Projects/scripts/pithosai/node_modules/@mariozechner/pi-coding-agent/dist/utils/photon.js")("fs"),n="photon_rs_bg.wasm",l=null,d=null;async function c(){return l||d||(d=(async()=>{let e=function(){let e,t=a.readFileSync.bind(a),i=(e=s.dirname(process.execPath),[s.join(e,n),s.join(e,"photon",n),s.join(process.cwd(),n)]),r=(...e)=>{let[r,s]=e,l="string"==typeof r?r:r instanceof URL?(0,o.fileURLToPath)(r):null;if(l?.endsWith(n))try{return t(...e)}catch(e){if(e?.code&&"ENOENT"!==e.code)throw e;for(let e of i)if(a.existsSync(e)){if(void 0===s)return t(e);return t(e,s)}throw e}return t(...e)};try{a.readFileSync=r}catch{Object.defineProperty(a,"readFileSync",{value:r,writable:!0,configurable:!0})}return()=>{try{a.readFileSync=t}catch{Object.defineProperty(a,"readFileSync",{value:t,writable:!0,configurable:!0})}}}();try{return l=await i.e("475").then(i.bind(i,7414))}catch{return l=null}finally{e()}})())}},3409(e,t,i){i.d(t,{Q:()=>p,g8:()=>h,lG:()=>c,yJ:()=>u});var r=i(3024),s=i(6760),o=i(5317),a=i(7103),n=i(430);let l=null;function d(){if("win32"===process.platform){try{let e=(0,o.spawnSync)("where",["bash.exe"],{encoding:"utf-8",timeout:5e3});if(0===e.status&&e.stdout){let t=e.stdout.trim().split(/\r?\n/)[0];if(t&&(0,r.existsSync)(t))return t}}catch{}return null}try{let e=(0,o.spawnSync)("which",["bash"],{encoding:"utf-8",timeout:5e3});if(0===e.status&&e.stdout){let t=e.stdout.trim().split(/\r?\n/)[0];if(t)return t}}catch{}return null}function c(){if(l)return l;let e=n.V.create().getShellPath();if(e){if((0,r.existsSync)(e))return l={shell:e,args:["-c"]};throw Error(`Custom shell path not found: ${e}
|
|
128
|
-
Please update shellPath in ${(0,a.pA)()}`)}if("win32"===process.platform){let e=[],t=process.env.ProgramFiles;t&&e.push(`${t}\\Git\\bin\\bash.exe`);let i=process.env["ProgramFiles(x86)"];for(let t of(i&&e.push(`${i}\\Git\\bin\\bash.exe`),e))if((0,r.existsSync)(t))return l={shell:t,args:["-c"]};let s=d();if(s)return l={shell:s,args:["-c"]};throw Error(`No bash shell found. Options:
|
|
129
|
-
1. Install Git for Windows: https://git-scm.com/download/win
|
|
130
|
-
2. Add your bash to PATH (Cygwin, MSYS2, etc.)
|
|
131
|
-
3. Set shellPath in ${(0,a.pA)()}
|
|
132
|
-
|
|
133
|
-
Searched Git Bash in:
|
|
134
|
-
${e.map(e=>` ${e}`).join("\n")}`)}if((0,r.existsSync)("/bin/bash"))return l={shell:"/bin/bash",args:["-c"]};let t=d();return l=t?{shell:t,args:["-c"]}:{shell:"sh",args:["-c"]}}function u(){let e=(0,a.lb)(),t=Object.keys(process.env).find(e=>"path"===e.toLowerCase())??"PATH",i=process.env[t]??"",r=i.split(s.delimiter).filter(Boolean).includes(e)?i:[e,i].filter(Boolean).join(s.delimiter);return{...process.env,[t]:r}}function p(e){return Array.from(e).filter(e=>{let t=e.codePointAt(0);return void 0!==t&&(9===t||10===t||13===t||!(t<=31)&&(!(t>=65529)||!(t<=65531)))}).join("")}function h(e){if("win32"===process.platform)try{(0,o.spawn)("taskkill",["/F","/T","/PID",String(e)],{stdio:"ignore",detached:!0})}catch{}else try{process.kill(-e,"SIGKILL")}catch{try{process.kill(e,"SIGKILL")}catch{}}}},7614(e,t,i){i.a(e,async function(e,r){try{i.d(t,{r:()=>f});var s=i(5590),o=i(5317),a=i(9896),n=i(857),l=i(6928),d=i(2203),c=i(9786),u=i(7103),p=e([s]);s=(p.then?(await p)():p)[0];let w=(0,u.lb)(),k={fd:{name:"fd",repo:"sharkdp/fd",binaryName:"fd",tagPrefix:"v",getAssetName:(e,t,i)=>"darwin"===t?`fd-v${e}-${"arm64"===i?"aarch64":"x86_64"}-apple-darwin.tar.gz`:"linux"===t?`fd-v${e}-${"arm64"===i?"aarch64":"x86_64"}-unknown-linux-gnu.tar.gz`:"win32"===t?`fd-v${e}-${"arm64"===i?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null},rg:{name:"ripgrep",repo:"BurntSushi/ripgrep",binaryName:"rg",tagPrefix:"",getAssetName:(e,t,i)=>"darwin"===t?`ripgrep-${e}-${"arm64"===i?"aarch64":"x86_64"}-apple-darwin.tar.gz`:"linux"===t?"arm64"===i?`ripgrep-${e}-aarch64-unknown-linux-gnu.tar.gz`:`ripgrep-${e}-x86_64-unknown-linux-musl.tar.gz`:"win32"===t?`ripgrep-${e}-${"arm64"===i?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null}};async function h(e){let t=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{headers:{"User-Agent":`${u.C3}-coding-agent`}});if(!t.ok)throw Error(`GitHub API error: ${t.status}`);return(await t.json()).tag_name.replace(/^v/,"")}async function m(e,t){let i=await fetch(e);if(!i.ok)throw Error(`Failed to download: ${i.status}`);if(!i.body)throw Error("No response body");let r=(0,a.createWriteStream)(t);await (0,c.finished)(d.Readable.fromWeb(i.body).pipe(r))}async function g(e){let t=k[e];if(!t)throw Error(`Unknown tool: ${e}`);let i=(0,n.platform)(),r=(0,n.arch)(),s=await h(t.repo),d=t.getAssetName(s,i,r);if(!d)throw Error(`Unsupported platform: ${i}/${r}`);(0,a.mkdirSync)(w,{recursive:!0});let c=`https://github.com/${t.repo}/releases/download/${t.tagPrefix}${s}/${d}`,u=(0,l.join)(w,d),p="win32"===i?".exe":"",g=(0,l.join)(w,t.binaryName+p);await m(c,u);let f=(0,l.join)(w,"extract_tmp");(0,a.mkdirSync)(f,{recursive:!0});try{d.endsWith(".tar.gz")?(0,o.spawnSync)("tar",["xzf",u,"-C",f],{stdio:"pipe"}):d.endsWith(".zip")&&(0,o.spawnSync)("unzip",["-o",u,"-d",f],{stdio:"pipe"});let e=(0,l.join)(f,d.replace(/\.(tar\.gz|zip)$/,"")),r=(0,l.join)(e,t.binaryName+p);if((0,a.existsSync)(r))(0,a.renameSync)(r,g);else throw Error(`Binary not found in archive: ${r}`);"win32"!==i&&(0,a.chmodSync)(g,493)}finally{(0,a.rmSync)(u,{force:!0}),(0,a.rmSync)(f,{recursive:!0,force:!0})}return g}let y={fd:"fd-find",rg:"ripgrep"};async function f(e,t=!1){let i=function(e){let t=k[e];if(!t)return null;let i=(0,l.join)(w,t.binaryName+("win32"===(0,n.platform)()?".exe":""));return(0,a.existsSync)(i)?i:!function(e){try{let t=(0,o.spawnSync)(e,["--version"],{stdio:"pipe"});return void 0===t.error||null===t.error}catch{return!1}}(t.binaryName)?null:t.binaryName}(e);if(i)return i;let r=k[e];if(r){if("android"===(0,n.platform)()){let i=y[e]??e;t||console.log(s.default.yellow(`${r.name} not found. Install with: pkg install ${i}`));return}t||console.log(s.default.dim(`${r.name} not found. Downloading...`));try{let i=await g(e);return t||console.log(s.default.dim(`${r.name} installed to ${i}`)),i}catch(e){t||console.log(s.default.yellow(`Failed to download ${r.name}: ${e instanceof Error?e.message:e}`));return}}}r()}catch(e){r(e)}})},569(e,t,i){i.a(e,async function(e,t){try{var r=i(8376),s=i(5012),o=i(4071),a=e([r,o]);[r,o]=a.then?(await a)():a,(async function(){let e=await (0,r.T)(),t=[process.argv[0],"qasai","-r","QA","--chat",...process.argv.slice(2)];await e.parseAsync(t),await (0,o.dz)()})().catch(async e=>{(0,o.vV)(e.message||String(e)),await (0,o.dz)(),process.exit(s.dc.RUNTIME)}),t()}catch(e){t(e)}})},4239(e,t,i){i.d(t,{i:()=>s,w:()=>o});var r=i(8474);let s={IDLE:"idle",RUNNING:"running",PAUSED:"paused",STOPPED:"stopped"};class o extends r.EventEmitter{constructor(){super(),this._agent=null,this._status=s.IDLE,this._currentRequest=null,this._currentTask=null}get status(){return this._status}get agent(){return this._agent}get currentRequest(){return this._currentRequest}get currentTask(){return this._currentTask}attach(e,t,i){this._agent=e,this._status=s.RUNNING,this._currentRequest=t,this._currentTask=i??null}detach(){this._agent=null,this._status===s.RUNNING&&(this._status=s.IDLE)}stop(){this._agent&&this._status===s.RUNNING&&(this._agent.abort(),this._status=s.STOPPED,this.emit("stopped"))}pause(){this._agent&&this._status===s.RUNNING&&(this._agent.abort(),this._status=s.PAUSED,this.emit("paused"))}resume(){this._status=s.IDLE,this.emit("resumed")}updateRequest(e){this._currentRequest=e}reset(){this._agent=null,this._status=s.IDLE,this._currentRequest=null,this._currentTask=null}}},1165(e,t,i){i.d(t,{o4:()=>s});let r=null;function s(e){return e??(r||(r={write(e,t={}){("stderr"===t.stream?process.stderr:process.stdout).write(e)}}),r)}},6275(e,t,i){i.a(e,async function(e,r){try{i.d(t,{F:()=>d});var s=i(8641),o=i(9949),a=i(4071),n=i(1165),l=e([a,s]);[a,s]=l.then?(await l)():l;let c=!1,u="",p=(0,o.fD)();function d(e={}){let t=!0===e.markdown,i=(0,n.o4)(e.outputSink);return e=>{switch("agent_start"===e.type&&(c=!1,u="",(0,o.Cl)(p)),e.type){case"tool_execution_start":(0,s.Rp)(e,i);break;case"tool_execution_update":(0,s.sJ)(e);break;case"tool_execution_end":(0,s.g4)(e,i);break;case"turn_end":{let t=e.message,i={messageRole:t?.role,stopReason:t?.stopReason,contentBlocks:t?.content?.length??0,toolResultsCount:e.toolResults?.length??0,toolResults:e.toolResults?.map(e=>({toolName:e.toolName,isError:e.isError}))};(0,a.IW)(`[turn_end] ${JSON.stringify(i)}`);break}case"message_update":if(e.assistantMessageEvent?.type==="text_delta"){(0,a.IW)(`[stream_event] ${JSON.stringify(e.assistantMessageEvent)}`);let r=e.assistantMessageEvent.delta??"";if(r)if(c=!0,u+=r,t){if((0,o.sO)(p,r),(0,o.NG)(p)){let e=(0,s.R$)((0,o.DP)(p),{markdown:!0});e&&i.write(e,{kind:"assistant"})}}else(0,s.ld)(r,{withNewlineHeuristics:!0,outputSink:i});else t||(0,s.ld)(r,{withNewlineHeuristics:!0,outputSink:i})}break;case"message_end":if(e.message?.role==="assistant"){let r=(0,s.JZ)(e.message);if(e.message.errorMessage||e.message.error)(0,s.cU)(e.message,i);else if(c){if(t&&p.pendingBuffer){let e=(0,s.R$)((0,o.DP)(p),{markdown:!0});e&&i.write(e,{kind:"assistant"})}r?(0,a.IW)(r):u&&(0,a.IW)(u)}else if(!c&&r){let e=(0,s.R$)(r,{markdown:t});i.write(e,{kind:"assistant"}),(0,a.IW)(r)}(0,s.cD)(e.message)}u="",(0,o.Cl)(p),c=!1}}}r()}catch(e){r(e)}})},546(e,t,i){i.a(e,async function(e,r){try{i.d(t,{FX:()=>s.F,gY:()=>o.g});var s=i(6275),o=i(8302),a=i(8641),n=e([s,o,a]);[s,o,a]=n.then?(await n)():n,r()}catch(e){r(e)}})},9949(e,t,i){function r(){return{pendingBuffer:"",inFencedCodeBlock:!1}}function s(e){e.pendingBuffer="",e.inFencedCodeBlock=!1}function o(e,t){t&&(function(e){if(!e)return 0;let t=e.match(/```/g);return t?t.length:0}(t)%2==1&&(e.inFencedCodeBlock=!e.inFencedCodeBlock),e.pendingBuffer+=t)}function a(e){return!!e.pendingBuffer&&!e.inFencedCodeBlock&&(e.pendingBuffer.includes("\n\n")||e.pendingBuffer.endsWith("\n"))}function n(e){let t=e.pendingBuffer;return e.pendingBuffer="",t}i.d(t,{Cl:()=>s,DP:()=>n,NG:()=>a,fD:()=>r,sO:()=>o})},8641(e,t,i){i.a(e,async function(e,r){try{i.d(t,{JZ:()=>m,R$:()=>h,Rp:()=>c,cD:()=>b,cU:()=>y,g4:()=>p,ld:()=>v,sJ:()=>u,u$:()=>k,u7:()=>w});var s=i(4071),o=i(161),a=i(1165),n=e([o,s]);[o,s]=n.then?(await n)():n;let S="\x1b[0m";function l(e){return null==e?"":"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):String(e)}function d(e){if(!e?.content||!Array.isArray(e.content))return"";let t=e.content.filter(e=>e?.type==="text"&&e?.text!=null).map(e=>e.text).join("");return(t=function(e){if("string"!=typeof e||!e.trim())return e;let t=e.trim();if(!1===(t.startsWith("{")&&t.endsWith("}")))return e;try{let i=JSON.parse(t);if(!i||"object"!=typeof i||!Array.isArray(i.content))return e;return i.content.filter(e=>e?.type==="text"&&e?.text!=null).map(e=>e.text).join("")}catch{return e}}(t)).length<=8e3?t:t.slice(0,8e3)+"\n... (truncated)"}function c(e,t){let i=(0,a.o4)(t),r=`${e.toolName} ${l(e.args)}`.trim();i.write("\n"+h("```shell\n"+r+"\n```",{markdown:!0})+"\n",{kind:"tool"}),(0,s.IW)(`[tool] ${e.toolName} ${l(e.args)}`)}function u(e){let t="string"==typeof e.partialResult?e.partialResult:JSON.stringify(e.partialResult??"");(0,s.IW)(`[tool] ${e.toolName} partial result => ${t}`)}function p(e,t){let i=(0,a.o4)(t),r=e.isError?"\x1b[31m✗"+S:"\x1b[32m✓"+S,o=e.isError?e.result&&d(e.result)||e.errorMessage||"error":d(e.result),n=e.isError?"✗":"✓";o?(i.write("\n"+r+" "+h(o,{markdown:!0})+"\n",{kind:"tool"}),(0,s.IW)(`${n} ${o}`)):(i.write("\n"+r+"\n",{kind:"tool"}),(0,s.IW)(`${n}`)),(0,s.IW)(`[tool] ${e.toolName} => ${e.isError?"error":"ok"}`)}function h(e,t={}){return e&&"string"==typeof e?!0===t.markdown?(0,o.o)(e):e:e??""}function m(e){return e?.content?e.content.filter(e=>"text"===e.type&&e.text).map(e=>e.text).join(""):""}function g(e,t){if(t&&!0===t.isError||!0===e.isError)return!0;let i=e.result;return!(!i||"object"!=typeof i||Array.isArray(i))&&(!0===i.isError||"error"in i&&null!=i.error)||!1}function f(e,t){return"string"==typeof e.name&&""!==e.name.trim()?e.name.trim():"string"==typeof e.toolName&&""!==e.toolName.trim()?e.toolName.trim():t?.role==="toolResult"&&"string"==typeof t.toolName&&""!==t.toolName.trim()?t.toolName.trim():"tool"}function w(e){if(!e?.content||!Array.isArray(e.content))return"";let t=e.role,i=[];for(let r of e.content){let s=function(e,t,i){if(!e||"object"!=typeof e)return"";let r=e.type;if("text"===r&&"string"==typeof e.text&&e.text)return"toolResult"===t?"":`${"user"===t?"user":"toolResult"===t||"tool"===t?"tool":"assist"}: ${e.text}`;if("thinking"===r&&"string"==typeof e.thinking&&e.thinking)return`assist: ${e.thinking}`;if("toolCall"===r){let t=f(e,i);return`tool: ${t}`}if("toolResult"===r){let t=f(e,i),r=g(e,i)?"failure":"success";return`tool: ${t} ${r}`}return""}(r,t,e);s&&i.push(s)}if(0===i.length&&"toolResult"===t){let t=f({},e),i=g({},e)?"failure":"success";return`tool: ${t} ${i}`}return i.join("\n")}function k(e){return e?.content?e.content.filter(e=>"thinking"===e.type&&e.thinking).map(e=>e.thinking).join(""):""}function y(e,t){if(!e?.errorMessage&&!e?.error)return;let i=(0,a.o4)(t),r=e.error,o=e.errorMessage??(r&&"object"==typeof r?r.message:void 0)??(null!=r?String(r):"Unknown error"),n=e.errorStack??(r&&"object"==typeof r?r.stack:void 0),l=["\n--- API error ---\n",o+"\n"];n&&String(n)!==o&&l.push("\nStack:\n"+n+"\n"),null!=e.errorCode&&l.push("Code: "+e.errorCode+"\n"),null!=e.errorStatus&&l.push("Status: "+e.errorStatus+"\n"),e.errorBody&&l.push("Response: "+("string"==typeof e.errorBody?e.errorBody:JSON.stringify(e.errorBody))+"\n"),l.push("-----------------\n");let d=l.join("");i.write(d,{stream:"stderr",kind:"error"}),(0,s.vV)(d.trim())}function v(e,t={}){let{withNewlineHeuristics:i=!1,outputSink:r}=t,s=(0,a.o4)(r),o=e??"";o&&(s.write(o,{kind:"assistant"}),i&&(o.endsWith(":")||o.endsWith("。")||o.endsWith(":")||o.endsWith("!")||o.endsWith("!")||o.endsWith("?")||o.endsWith("?"))&&s.write("\n",{kind:"assistant"}))}function b(e){e&&(0,s.KH)("[llm_response] "+JSON.stringify(e))}r()}catch(e){r(e)}})},8302(e,t,i){i.a(e,async function(e,r){try{i.d(t,{g:()=>d});var s=i(8641),o=i(9949),a=i(4071),n=i(1165),l=e([a,s]);[a,s]=l.then?(await l)():l;let c=!1,u=!1,p="",h=(0,o.fD)();function d(e={}){let t=!0===e.markdown,i=(0,n.o4)(e.outputSink),r="function"==typeof e.getShowThinking?e.getShowThinking:()=>!0,l="function"==typeof e.t?e.t:e=>"reasoner.thinkingHeader"===e?"\n--- Thinking:\n":"\n\n--- Reply:\n";return e=>{"agent_start"===e.type&&(c=!1,u=!1,p="",(0,o.Cl)(h));let n=r();if("tool_execution_start"===e.type)return void(0,s.Rp)(e,i);if("tool_execution_update"===e.type)return void(0,s.sJ)(e);if("tool_execution_end"===e.type)return void(0,s.g4)(e,i);if("turn_end"===e.type){let t=e.message,i={messageRole:t?.role,stopReason:t?.stopReason,contentBlocks:t?.content?.length??0,toolResultsCount:e.toolResults?.length??0,toolResults:e.toolResults?.map(e=>({toolName:e.toolName,isError:e.isError}))};(0,a.IW)(`
|
|
135
|
-
[turn_end] ${JSON.stringify(i,null,2)}
|
|
136
|
-
`);return}if("message_update"===e.type&&e.assistantMessageEvent){let r=e.assistantMessageEvent;if((0,a.IW)(`[stream_event] ${JSON.stringify(r)}
|
|
137
|
-
`),n&&"thinking_delta"===r.type){let e=r.delta??"";if(String(e).trim().length>0){if(!c){c=!0;let e=l("reasoner.thinkingHeader");i.write(e,{kind:"thinking"}),(0,a.IW)(e)}i.write(e,{kind:"thinking"}),(0,a.IW)(e)}}if("text_delta"===r.type){let e=r.delta??"";if(e){if(!u&&n&&c){let e=l("reasoner.replyHeader");(0,a.IW)(e),i.write(e,{kind:"assistant"})}if(u=!0,p+=e,t){if((0,o.sO)(h,e),(0,o.NG)(h)){let e=(0,s.R$)((0,o.DP)(h),{markdown:!0});e&&i.write(e,{kind:"assistant"})}}else(0,s.ld)(e,{withNewlineHeuristics:!0,outputSink:i})}else t||(0,s.ld)(r.delta,{withNewlineHeuristics:!0,outputSink:i})}}if("message_end"===e.type&&e.message?.role==="assistant"){if(e.message.errorMessage||e.message.error)(0,s.cU)(e.message,i);else{let r=(0,s.u$)(e.message),d=(0,s.JZ)(e.message);if(n&&r&&!c){let e=l("reasoner.thinkingHeader");i.write(e,{kind:"thinking"}),i.write(r,{kind:"thinking"}),(0,a.IW)(e),(0,a.IW)(r)}let m=c||n&&!!r;if(u){if(t&&h.pendingBuffer){let e=(0,s.R$)((0,o.DP)(h),{markdown:!0});e&&i.write(e,{kind:"assistant"})}d?(0,a.IW)(d):p&&(0,a.IW)(p)}else if(d){if(m){let e=l("reasoner.replyHeader");(0,a.IW)(e),i.write(e,{kind:"assistant"})}let e=(0,s.R$)(d,{markdown:t});i.write(e,{kind:"assistant"}),(0,a.IW)(d)}}(0,s.cD)(e.message),p="",(0,o.Cl)(h),c=!1,u=!1}}}r()}catch(e){r(e)}})},4757(e,t,i){i.a(e,async function(e,r){try{i.d(t,{N:()=>P});var s=i(6760),o=i(4768),a=i(785),n=i(4588),l=i(8285),d=i(9243),c=i(9522),u=i(6048),p=i(9434),h=i(4820),m=i(546),g=i(1165),f=i(5012),w=i(4071),k=i(4788),y=i(178),v=i(6551),b=i(8362),S=i(4224),T=i(6669);i(7096);var C=i(3375),E=i(7790),x=i(2369),I=i(8359),A=i(4427),O=e([l,p,k,y,x,o,b,h,u,d,c,A,T,a,n,v,C,m,I,w]);[l,p,k,y,x,o,b,h,u,d,c,A,T,a,n,v,C,m,I,w]=O.then?(await O)():O;let R=new Set(["read","read_file","list_files","read_pdf","web_fetch","web_search","proxy_downloader","read_email"]);async function P(e,t){var i;(0,w.KH)("bootstrap",JSON.stringify(e),JSON.stringify(t));let r=t.mode??"agent",l=(0,g.o4)(t.outputSink),p=await (0,x.Lf)(),k=(0,s.resolve)(t.cwd),y=await (0,o.s)(k),O=t.lang,P=t.role,M=(0,b.l)(O),L=(0,C.bf)(y);L.loaded&&(0,w.fH)(`Hook system initialized (${L.sources.join(", ")})`),(void 0===O||void 0===P)&&y&&(void 0===O&&null!=y.lang&&(O=y.lang),void 0===P&&y.supportedRoles?.length&&(P=y.supportedRoles[0])),O=O||"en",P=P??"RD";let N=(0,h.Al)(t);N||((0,w.vV)(M("errors.noApiKey")),process.exit(f.dc.CONFIG)),e.model=N.model.id;let D="agent"===r?await (0,u.N)(k,O,P):null,_=await (0,d.G)(y,P,k,{allowNames:D}),F=(0,c.E)(k,D),H=[..._,...F];H=(0,C.sD)(H,{cwd:k,role:P,lang:O});let $=await (0,A.Ex)({cwd:k,lang:O,role:P,mode:r,task:e,skillsDir:t.skillsDir,modelConfig:N});t.newSession&&(0,w.fH)(M("run.newSessionNoHistory"));let{systemPrompt:j,initialMessages:z}=$,U="1"===process.env.PITHOSAI_DEBUG_STREAM||"true"===process.env.PITHOSAI_DEBUG_STREAM?(0,T.M)():a.streamSimple,q=async(e,t,i)=>{let r=await U(e,t,{...i,...e?.contextWindow!=null&&{contextWindow:e.contextWindow}});return(0,E.z)(r,e)},B=N.model?.supportsTools===!1?[]:(i=H,"agent"===r?i:(i??[]).filter(e=>R.has(String(e?.name??"")))),W=new n.Agent({initialState:{systemPrompt:j,model:N.model,tools:B,messages:z},convertToLlm:e=>(0,v.C)(e,N.model),getApiKey:N.getApiKey,streamFn:q});W=(0,C.ux)(W,{cwd:k,role:P,lang:O}),t.reasoner?W.subscribe((0,m.gY)({getShowThinking:()=>!0,markdown:t.markdown,t:M,outputSink:l})):W.subscribe((0,m.FX)({markdown:t.markdown,outputSink:l}));let K={apiError:!1,apiErrorMessage:void 0,failoverReason:null};return W.subscribe(t=>{if("message_end"===t.type&&t.message){if(e&&e.id)try{(0,I.$R)(p,e),(0,I.kF)(p,{taskId:e.id,message:t.message,role:P,lang:O,mode:r,model:e.model??"deepSeekChat"})}catch(t){(0,w.vV)(`Failed to insert task message for task ${e.id}: ${t&&"object"==typeof t&&"message"in t?t.message:String(t)}`)}if("assistant"===t.message.role&&(t.message.errorMessage||t.message.error)){K.apiError=!0;let e="";if("string"==typeof t.message.errorMessage?e=t.message.errorMessage:"string"==typeof t.message.error?e=t.message.error:t.message.error&&"object"==typeof t.message.error&&"string"==typeof t.message.error.message&&(e=t.message.error.message),K.apiErrorMessage=e||void 0,K.failoverReason=e?(0,S.bn)(e):null,"string"==typeof e&&e.toLowerCase().includes("terminated"))try{W.abort()}catch(e){(0,w.vV)(`Failed to abort agent after stream termination error: ${e&&"object"==typeof e&&"message"in e?e.message:String(e)}`)}}}}),{agent:W,cwd:k,runState:K}}r()}catch(e){r(e)}})},6669(e,t,i){i.a(e,async function(e,r){try{i.d(t,{M:()=>n});var s=i(785),o=i(4071),a=e([s,o]);function n(){return async function(e,t,i){let r=await (0,s.streamSimple)(e,t,i),a=r[Symbol.asyncIterator].bind(r),n=!1;return r[Symbol.asyncIterator]=function(){let e=a();return{async next(){let t=await e.next();return t.done?(0,o.IW)(`[pi-agent stream] iterator finished (saw done/error: ${n})
|
|
138
|
-
`):(t.value?.type==="done"||t.value?.type==="error")&&(n=!0,(0,o.IW)(`[pi-agent stream] event: ${t.value.type}
|
|
139
|
-
`)),t}}},r}}[s,o]=a.then?(await a)():a,r()}catch(e){r(e)}})},4224(e,t,i){i.d(t,{bn:()=>c});let r=[/rate[_ ]limit|too many requests|429/i,"exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit"],s=[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded"],o=[/timeout|timed out|deadline exceeded|context deadline exceeded/i],a=[/\b402\b/,"payment required","insufficient credits","credit balance","plans & billing"],n=[/invalid[_ ]?api[_ ]?key/i,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],l=["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format"];function d(e,t){if(!e)return!1;let i=e.toLowerCase();return t.some(e=>e instanceof RegExp?e.test(i):i.includes(e))}function c(e){return e?d(e,r)||d(e,s)?"rate_limit":d(e,l)?"format":function(e){if(!e)return!1;let t=e.toLowerCase();return!!t&&(!!d(t,a)||t.includes("billing")&&(t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan")))}(e)?"billing":d(e,o)?"timeout":d(e,n)?"auth":null:null}},3375(e,t,i){i.a(e,async function(e,r){try{i.d(t,{bf:()=>l,sD:()=>u,ux:()=>d});var s=i(7096),o=i(4071),a=i(3586),n=e([a,o]);function l(e){let t=[];if(e?.hooks?.active){let i=e.hooks.active;if("debug"===i.type){let e=(0,a._3)({logData:i.options?.data||!1});if(s.sX.registerAll(e),i.options?.performance){let e=(0,a.TA)();s.sX.registerAll(e)}if(i.options?.stats){let e=(0,a.sD)();s.sX.registerAll(e)}t.push("settings:debug")}else if("debug-basic"===i.type){let e=(0,a._3)({logData:i.options?.data||!1});s.sX.registerAll(e),t.push("settings:debug-basic")}else if("security"===i.type){let e=(0,a.n$)(i.options||{});s.sX.registerAll(e),t.push("settings:security")}}else{let e="1"===process.env.PITHOSAI_DEBUG_HOOKS||"true"===process.env.PITHOSAI_DEBUG_HOOKS,i="1"===process.env.PITHOSAI_SECURITY_HOOKS||"true"===process.env.PITHOSAI_SECURITY_HOOKS;if(e){let e=(0,a._3)({logData:"1"===process.env.PITHOSAI_DEBUG_HOOKS_DATA});s.sX.registerAll(e);let i=(0,a.TA)();s.sX.registerAll(i);let r=(0,a.sD)();s.sX.registerAll(r),t.push("env:debug")}if(i){let e=process.env.PITHOSAI_BLOCKED_TOOLS?process.env.PITHOSAI_BLOCKED_TOOLS.split(",").map(e=>e.trim()):[],i=(0,a.n$)({blockedTools:e,maxPromptLength:parseInt(process.env.PITHOSAI_MAX_PROMPT_LENGTH||"10000",10)});s.sX.registerAll(i),t.push("env:security")}}return{loaded:t.length>0,sources:t}}function d(e,t={}){let{cwd:i,role:r,lang:a}=t;if(!e||"function"!=typeof e.prompt)return(0,o.MD)("Agent does not have prompt method, skipping hook wrapping"),e;let n=e.prompt.bind(e);return e.prompt=async function(e){let t={request:e,cwd:i,role:r,lang:a,timestamp:Date.now()};await s.sX.trigger(s.WD.BEFORE_AGENT_RUN,t);try{let t=await n(e),o={request:e,result:t,cwd:i,role:r,lang:a,timestamp:Date.now()};return await s.sX.trigger(s.WD.AFTER_AGENT_RUN,o),t}catch(o){let t={request:e,error:o,cwd:i,role:r,lang:a,timestamp:Date.now()};throw await s.sX.trigger(s.WD.AFTER_AGENT_RUN,t),o}},"function"==typeof e.subscribe&&e.subscribe(e=>{try{c(e,t)}catch(t){(0,o.MD)(`Hook handler error for ${e?.type}: ${t?.message??t}`)}}),e}async function c(e,t){let{cwd:i,role:r,lang:o}=t;switch(e.type){case"message_start":if(e.message?.role==="assistant"){let t={messages:e.messages||[],model:e.model,cwd:i,role:r,lang:o,timestamp:Date.now()};await s.sX.trigger(s.WD.BEFORE_MODEL_CALL,t)}break;case"message_update":{let t={message:e.message,assistantMessageEvent:e.assistantMessageEvent,messages:e.messages||[],model:e.model,cwd:i,role:r,lang:o,timestamp:Date.now()};s.sX.trigger(s.WD.MESSAGE_UPDATE,t).catch(()=>{});break}case"message_end":if(e.message?.role==="assistant"){let t={messages:e.messages||[],message:e.message,model:e.model,cwd:i,role:r,lang:o,timestamp:Date.now()};await s.sX.trigger(s.WD.AFTER_MODEL_CALL,t)}break;case"tool_call":{let t={toolCall:e.toolCall,messages:e.messages||[],cwd:i,role:r,lang:o,timestamp:Date.now()};await s.sX.trigger(s.WD.BEFORE_TOOL_CALL,t);break}case"tool_result":{let t={toolCall:e.toolCall,result:e.result,messages:e.messages||[],cwd:i,role:r,lang:o,timestamp:Date.now()};await s.sX.trigger(s.WD.AFTER_TOOL_CALL,t)}}}function u(e,t={}){return e.map(e=>(function(e,t={}){let{cwd:i,role:r,lang:o}=t;if("function"!=typeof e.execute)return e;let a=e.execute,n=async function(t,n,l,d){let c=n||{},u={name:e.name,description:e.description,params:c,toolCallId:t,cwd:i,role:r,lang:o,timestamp:Date.now()},p=await s.sX.trigger(s.WD.BEFORE_TOOL_EXECUTE,u),h=null!=p&&void 0!==p.params?p.params:c;try{let n=await a(t,h,l,d),c={name:e.name,description:e.description,params:h,result:n,toolCallId:t,cwd:i,role:r,lang:o,timestamp:Date.now()};return await s.sX.trigger(s.WD.AFTER_TOOL_EXECUTE,c),n}catch(n){let a={name:e.name,description:e.description,params:h,error:n,toolCallId:t,cwd:i,role:r,lang:o,timestamp:Date.now()};throw await s.sX.trigger(s.WD.AFTER_TOOL_EXECUTE,a),n}};return{...e,execute:n}})(e,t))}[a,o]=n.then?(await n)():n,r()}catch(e){r(e)}})},3586(e,t,i){i.a(e,async function(e,r){try{i.d(t,{TA:()=>l,_3:()=>n,n$:()=>d,sD:()=>c});var s=i(7096),o=i(4071),a=e([o]);function n(e={}){let{logData:t=!1,includeHooks:i=Object.values(s.WD),excludeHooks:r=[s.WD.MESSAGE_UPDATE]}=e,a={};return Object.values(s.WD).forEach(e=>{!i.includes(e)||r.includes(e)||(a[e]=async e=>{let{hookType:i,data:r,result:s,error:a,timestamp:n}=e,l=a?"error":"info",d=a?"❌":"✅",c=a?` (error: ${a.message})`:"",u=`${d} Hook: ${i}${c}`;if(t){let e=JSON.stringify(r,null,2),t=void 0!==s?JSON.stringify(s,null,2):"";u+=`
|
|
2
|
+
import{createRequire as e}from"node:module";let t=e(import.meta.url);var r,i,a,o,n,s,l,d,c,u,p,m={4588(e){e.exports=import("@mariozechner/pi-agent-core").then(function(e){return e})},785(e){e.exports=import("@mariozechner/pi-ai").then(function(e){return e})},2421(e){e.exports=import("@mariozechner/pi-coding-agent").then(function(e){return e})},4127(e){e.exports=import("@mariozechner/pi-tui").then(function(e){return e})},4204(e){e.exports=import("@sinclair/typebox").then(function(e){return e})},3529(e){e.exports=import("better-sqlite3").then(function(e){return e})},5590(e){e.exports=import("chalk").then(function(e){return e})},9748(e){e.exports=import("chokidar").then(function(e){return e})},5347(e){e.exports=import("commander").then(function(e){return e})},35(e){e.exports=import("handlebars").then(function(e){return e})},2022(e){e.exports=import("i18next").then(function(e){return e})},4082(e){e.exports=import("log4js").then(function(e){return e})},8703(e){e.exports=import("marked").then(function(e){return e})},9392(e){e.exports=import("playwright").then(function(e){return e})},2641(e){e.exports=import("proper-lockfile").then(function(e){return e})},7522(e){e.exports=import("readdirp").then(function(e){return e})},4132(e){e.exports=import("uuid").then(function(e){return e})},1943(e){e.exports=t("fs/promises")},6698(e){e.exports=t("node:async_hooks")},1421(e){e.exports=t("node:child_process")},7598(e){e.exports=t("node:crypto")},3024(e){e.exports=t("node:fs")},1455(e){e.exports=t("node:fs/promises")},8995(e){e.exports=t("node:module")},8161(e){e.exports=t("node:os")},6760(e){e.exports=t("node:path")},481(e){e.exports=t("node:readline")},3136(e){e.exports=t("node:url")},7975(e){e.exports=t("node:util")},6928(e){e.exports=t("path")},569(e,t,r){r.a(e,async function(e,t){try{var i=r(8376),a=r(5012),o=r(4071),n=e([i,o]);[i,o]=n.then?(await n)():n,(async function(){let e=await (0,i.T)(),t=[process.argv[0],"qasai","-r","QA","--chat",...process.argv.slice(2)];await e.parseAsync(t),await (0,o.dz)()})().catch(async e=>{(0,o.vV)(e.message||String(e)),await (0,o.dz)(),process.exit(a.dc.RUNTIME)}),t()}catch(e){t(e)}})},4267(e,r,i){i.d(r,{w:()=>n,i:()=>o});let a=t("node:events"),o={IDLE:"idle",RUNNING:"running",PAUSED:"paused",STOPPED:"stopped"};class n extends a.EventEmitter{constructor(){super(),this._agent=null,this._status=o.IDLE,this._currentRequest=null,this._currentTask=null}get status(){return this._status}get agent(){return this._agent}get currentRequest(){return this._currentRequest}get currentTask(){return this._currentTask}attach(e,t,r){this._agent=e,this._status=o.RUNNING,this._currentRequest=t,this._currentTask=r??null}detach(){this._agent=null,this._status===o.RUNNING&&(this._status=o.IDLE)}stop(){this._agent&&this._status===o.RUNNING&&(this._agent.abort(),this._status=o.STOPPED,this.emit("stopped"))}pause(){this._agent&&this._status===o.RUNNING&&(this._agent.abort(),this._status=o.PAUSED,this.emit("paused"))}resume(){this._status=o.IDLE,this.emit("resumed")}updateRequest(e){this._currentRequest=e}reset(){this._agent=null,this._status=o.IDLE,this._currentRequest=null,this._currentTask=null}}},1165(e,t,r){r.d(t,{o4:()=>a});let i=null;function a(e){return e??(i||(i={write(e,t={}){("stderr"===t.stream?process.stderr:process.stdout).write(e)}}),i)}},6275(e,t,r){r.a(e,async function(e,i){try{r.d(t,{F:()=>d});var a=r(8641),o=r(9949),n=r(4071),s=r(1165),l=e([n,a]);[n,a]=l.then?(await l)():l;let c=!1,u="",p=(0,o.fD)();function d(e={}){let t=!0===e.markdown,r=(0,s.o4)(e.outputSink);return e=>{switch("agent_start"===e.type&&(c=!1,u="",(0,o.Cl)(p)),e.type){case"tool_execution_start":(0,a.Rp)(e,r);break;case"tool_execution_update":(0,a.sJ)(e);break;case"tool_execution_end":(0,a.g4)(e,r);break;case"turn_end":{let t=e.message,r={messageRole:t?.role,stopReason:t?.stopReason,contentBlocks:t?.content?.length??0,toolResultsCount:e.toolResults?.length??0,toolResults:e.toolResults?.map(e=>({toolName:e.toolName,isError:e.isError}))};(0,n.IW)(`[turn_end] ${JSON.stringify(r)}`);break}case"message_update":if(e.assistantMessageEvent?.type==="text_delta"){(0,n.IW)(`[stream_event] ${JSON.stringify(e.assistantMessageEvent)}`);let i=e.assistantMessageEvent.delta??"";if(i)if(c=!0,u+=i,t){if((0,o.sO)(p,i),(0,o.NG)(p)){let e=(0,a.R$)((0,o.DP)(p),{markdown:!0});e&&r.write(e,{kind:"assistant"})}}else(0,a.ld)(i,{withNewlineHeuristics:!0,outputSink:r});else t||(0,a.ld)(i,{withNewlineHeuristics:!0,outputSink:r})}break;case"message_end":if(e.message?.role==="assistant"){let i=(0,a.JZ)(e.message);if(e.message.errorMessage||e.message.error)(0,a.cU)(e.message,r);else if(c){if(t&&p.pendingBuffer){let e=(0,a.R$)((0,o.DP)(p),{markdown:!0});e&&r.write(e,{kind:"assistant"})}i?(0,n.IW)(i):u&&(0,n.IW)(u)}else if(!c&&i){let e=(0,a.R$)(i,{markdown:t});r.write(e,{kind:"assistant"}),(0,n.IW)(i)}(0,a.cD)(e.message)}u="",(0,o.Cl)(p),c=!1}}}i()}catch(e){i(e)}})},546(e,t,r){r.a(e,async function(e,i){try{r.d(t,{FX:()=>a.F,gY:()=>o.g});var a=r(6275),o=r(8302),n=r(8641),s=e([a,o,n]);[a,o,n]=s.then?(await s)():s,i()}catch(e){i(e)}})},9949(e,t,r){function i(){return{pendingBuffer:"",inFencedCodeBlock:!1}}function a(e){e.pendingBuffer="",e.inFencedCodeBlock=!1}function o(e,t){t&&(function(e){if(!e)return 0;let t=e.match(/```/g);return t?t.length:0}(t)%2==1&&(e.inFencedCodeBlock=!e.inFencedCodeBlock),e.pendingBuffer+=t)}r.d(t,{Cl:()=>a,DP:()=>l,NG:()=>s,fD:()=>i,sO:()=>o});let n=/^\s*\d+\.\s/;function s(e){if(!e.pendingBuffer||e.inFencedCodeBlock)return!1;if(e.pendingBuffer.includes("\n\n"))return!0;if(e.pendingBuffer.endsWith("\n")){let t;return!(0!==(t=String(e.pendingBuffer??"").split(/\r?\n/).filter(e=>""!==e.trim())).length&&t.every(e=>n.test(e)))}return!1}function l(e){let t=e.pendingBuffer;return e.pendingBuffer="",t}},8641(e,t,r){r.a(e,async function(e,i){try{r.d(t,{JZ:()=>f,R$:()=>g,Rp:()=>p,cD:()=>T,cU:()=>b,g4:()=>h,ld:()=>S,sJ:()=>m,u$:()=>y,u7:()=>v});var a=r(4071),o=r(161),n=r(5460),s=r(1165),l=e([o,a]);[o,a]=l.then?(await l)():l;let E="\x1b[0m";function d(e){return String(e??"").replace(/\r/g,"").split("\n").map(e=>`\x1b[48;2;30;41;59m\x1b[38;2;236;242;255m ${e} ${E}`).join("\n")}function c(e){return null==e?"":"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):String(e)}function u(e){if(!e?.content||!Array.isArray(e.content))return"";let t=e.content.filter(e=>e?.type==="text"&&e?.text!=null).map(e=>e.text).join("");return(t=function(e){if("string"!=typeof e||!e.trim())return e;let t=e.trim();if(!1===(t.startsWith("{")&&t.endsWith("}")))return e;try{let r=JSON.parse(t);if(!r||"object"!=typeof r||!Array.isArray(r.content))return e;return r.content.filter(e=>e?.type==="text"&&e?.text!=null).map(e=>e.text).join("")}catch{return e}}(t)).length<=8e3?t:t.slice(0,8e3)+"\n... (truncated)"}function p(e,t){let r=(0,s.o4)(t),i=`${e.toolName} ${c(e.args)}`.trim();r.write(d(i)+"\n",{kind:"tool"}),(0,a.IW)(`[tool] ${e.toolName} ${c(e.args)}`)}function m(e){let t="string"==typeof e.partialResult?e.partialResult:JSON.stringify(e.partialResult??"");(0,a.IW)(`[tool] ${e.toolName} partial result => ${t}`)}function h(e,t){let r=(0,s.o4)(t),i=e.isError?"\x1b[31m✗"+E:"\x1b[32m✓"+E,o=e.isError?e.result&&u(e.result)||e.errorMessage||"error":u(e.result),l=e.isError?"✗":"✓";if(o){let e=(0,n.cs)(o),t=g(e,{markdown:!0}).split("\n").map(e=>e.trimEnd()).filter(e=>""!==e.trim());if(t.length>0){let e=[d(`${i} ${t[0]}`),...t.slice(1).map(e=>d(` ${e}`))].join("\n");r.write(e+"\n\n",{kind:"tool"})}else r.write(d(i)+"\n\n",{kind:"tool"});(0,a.IW)(`${l} ${o}`)}else r.write(d(i)+"\n\n",{kind:"tool"}),(0,a.IW)(`${l}`);(0,a.IW)(`[tool] ${e.toolName} => ${e.isError?"error":"ok"}`)}function g(e,t={}){return e&&"string"==typeof e?!0===t.markdown?(0,o.o)(e):e:e??""}function f(e){return e?.content?e.content.filter(e=>"text"===e.type&&e.text).map(e=>e.text).join(""):""}function k(e,t){if(t&&!0===t.isError||!0===e.isError)return!0;let r=e.result;return!(!r||"object"!=typeof r||Array.isArray(r))&&(!0===r.isError||"error"in r&&null!=r.error)||!1}function w(e,t){return"string"==typeof e.name&&""!==e.name.trim()?e.name.trim():"string"==typeof e.toolName&&""!==e.toolName.trim()?e.toolName.trim():t?.role==="toolResult"&&"string"==typeof t.toolName&&""!==t.toolName.trim()?t.toolName.trim():"tool"}function v(e){if(!e?.content||!Array.isArray(e.content))return"";let t=e.role,r=[];for(let i of e.content){let a=function(e,t,r){if(!e||"object"!=typeof e)return"";let i=e.type;if("text"===i&&"string"==typeof e.text&&e.text)return"toolResult"===t?"":`${"user"===t?"user":"toolResult"===t||"tool"===t?"tool":"assist"}: ${e.text}`;if("thinking"===i&&"string"==typeof e.thinking&&e.thinking)return`assist: ${e.thinking}`;if("toolCall"===i){let t=w(e,r);return`tool: ${t}`}if("toolResult"===i){let t=w(e,r),i=k(e,r)?"failure":"success";return`tool: ${t} ${i}`}return""}(i,t,e);a&&r.push(a)}if(0===r.length&&"toolResult"===t){let t=w({},e),r=k({},e)?"failure":"success";return`tool: ${t} ${r}`}return r.join("\n")}function y(e){return e?.content?e.content.filter(e=>"thinking"===e.type&&e.thinking).map(e=>e.thinking).join(""):""}function b(e,t){if(!e?.errorMessage&&!e?.error)return;let r=(0,s.o4)(t),i=e.error,o=e.errorMessage??(i&&"object"==typeof i?i.message:void 0)??(null!=i?String(i):"Unknown error"),n=e.errorStack??(i&&"object"==typeof i?i.stack:void 0),l=["\n--- API error ---\n",o+"\n"];n&&String(n)!==o&&l.push("\nStack:\n"+n+"\n"),null!=e.errorCode&&l.push("Code: "+e.errorCode+"\n"),null!=e.errorStatus&&l.push("Status: "+e.errorStatus+"\n"),e.errorBody&&l.push("Response: "+("string"==typeof e.errorBody?e.errorBody:JSON.stringify(e.errorBody))+"\n"),l.push("-----------------\n");let d=l.join("");r.write(d,{stream:"stderr",kind:"error"}),(0,a.vV)(d.trim())}function S(e,t={}){let{withNewlineHeuristics:r=!1,outputSink:i}=t,a=(0,s.o4)(i),o=e??"";o&&(a.write(o,{kind:"assistant"}),r&&(o.endsWith(":")||o.endsWith("。")||o.endsWith(":")||o.endsWith("!")||o.endsWith("!")||o.endsWith("?")||o.endsWith("?"))&&a.write("\n",{kind:"assistant"}))}function T(e){e&&(0,a.KH)("[llm_response] "+JSON.stringify(e))}i()}catch(e){i(e)}})},8302(e,t,r){r.a(e,async function(e,i){try{r.d(t,{g:()=>d});var a=r(8641),o=r(9949),n=r(4071),s=r(1165),l=e([n,a]);[n,a]=l.then?(await l)():l;let c=!1,u=!1,p="",m=(0,o.fD)();function d(e={}){let t=!0===e.markdown,r=(0,s.o4)(e.outputSink),i="function"==typeof e.getShowThinking?e.getShowThinking:()=>!0,l="function"==typeof e.t?e.t:e=>"reasoner.thinkingHeader"===e?"\n--- Thinking:\n":"\n\n--- Reply:\n";return e=>{"agent_start"===e.type&&(c=!1,u=!1,p="",(0,o.Cl)(m));let s=i();if("tool_execution_start"===e.type)return void(0,a.Rp)(e,r);if("tool_execution_update"===e.type)return void(0,a.sJ)(e);if("tool_execution_end"===e.type)return void(0,a.g4)(e,r);if("turn_end"===e.type){let t=e.message,r={messageRole:t?.role,stopReason:t?.stopReason,contentBlocks:t?.content?.length??0,toolResultsCount:e.toolResults?.length??0,toolResults:e.toolResults?.map(e=>({toolName:e.toolName,isError:e.isError}))};(0,n.IW)(`
|
|
3
|
+
[turn_end] ${JSON.stringify(r,null,2)}
|
|
4
|
+
`);return}if("message_update"===e.type&&e.assistantMessageEvent){let i=e.assistantMessageEvent;if((0,n.IW)(`[stream_event] ${JSON.stringify(i)}
|
|
5
|
+
`),s&&"thinking_delta"===i.type){let e=i.delta??"";if(String(e).trim().length>0){if(!c){c=!0;let e=l("reasoner.thinkingHeader");r.write(e,{kind:"thinking"}),(0,n.IW)(e)}r.write(e,{kind:"thinking"}),(0,n.IW)(e)}}if("text_delta"===i.type){let e=i.delta??"";if(e){if(!u&&s&&c){let e=l("reasoner.replyHeader");(0,n.IW)(e),r.write(e,{kind:"assistant"})}if(u=!0,p+=e,t){if((0,o.sO)(m,e),(0,o.NG)(m)){let e=(0,a.R$)((0,o.DP)(m),{markdown:!0});e&&r.write(e,{kind:"assistant"})}}else(0,a.ld)(e,{withNewlineHeuristics:!0,outputSink:r})}else t||(0,a.ld)(i.delta,{withNewlineHeuristics:!0,outputSink:r})}}if("message_end"===e.type&&e.message?.role==="assistant"){if(e.message.errorMessage||e.message.error)(0,a.cU)(e.message,r);else{let i=(0,a.u$)(e.message),d=(0,a.JZ)(e.message);if(s&&i&&!c){let e=l("reasoner.thinkingHeader");r.write(e,{kind:"thinking"}),r.write(i,{kind:"thinking"}),(0,n.IW)(e),(0,n.IW)(i)}let h=c||s&&!!i;if(u){if(t&&m.pendingBuffer){let e=(0,a.R$)((0,o.DP)(m),{markdown:!0});e&&r.write(e,{kind:"assistant"})}d?(0,n.IW)(d):p&&(0,n.IW)(p)}else if(d){if(h){let e=l("reasoner.replyHeader");(0,n.IW)(e),r.write(e,{kind:"assistant"})}let e=(0,a.R$)(d,{markdown:t});r.write(e,{kind:"assistant"}),(0,n.IW)(d)}}(0,a.cD)(e.message),p="",(0,o.Cl)(m),c=!1,u=!1}}}i()}catch(e){i(e)}})},4757(e,t,r){r.a(e,async function(e,i){try{r.d(t,{N:()=>P});var a=r(6760),o=r(4768),n=r(785),s=r(4588),l=r(2421),d=r(9243),c=r(9522),u=r(6048),p=r(9434),m=r(4820),h=r(546),g=r(1165),f=r(5012),k=r(4071),w=r(4788),v=r(178),y=r(6551),b=r(8362),S=r(4224),T=r(6669);r(7096);var E=r(3375),x=r(7790),C=r(2369),A=r(8359),I=r(4427),O=e([l,p,w,v,C,o,b,m,u,d,c,I,T,n,s,y,E,h,A,k]);[l,p,w,v,C,o,b,m,u,d,c,I,T,n,s,y,E,h,A,k]=O.then?(await O)():O;let R=new Set(["read","read_file","list_files","read_pdf","web_fetch","web_search","proxy_downloader","read_email"]);async function P(e,t){var r;(0,k.KH)("bootstrap",JSON.stringify(e),JSON.stringify(t));let i=t.mode??"agent",l=(0,g.o4)(t.outputSink),p=await (0,C.Lf)(),w=(0,a.resolve)(t.cwd),v=await (0,o.s)(w),O=t.lang,P=t.role,N=(0,b.l)(O),L=(0,E.bf)(v);L.loaded&&(0,k.fH)(`Hook system initialized (${L.sources.join(", ")})`),(void 0===O||void 0===P)&&v&&(void 0===O&&null!=v.lang&&(O=v.lang),void 0===P&&v.supportedRoles?.length&&(P=v.supportedRoles[0])),O=O||"en",P=P??"RD";let D=(0,m.Al)(t);D||((0,k.vV)(N("errors.noApiKey")),process.exit(f.dc.CONFIG)),e.model=D.model.id;let _="agent"===i?await (0,u.N)(w,O,P):null,H=await (0,d.G)(v,P,w,{allowNames:_}),M=(0,c.E)(w,_),F=[...H,...M];F=(0,E.sD)(F,{cwd:w,role:P,lang:O});let j=await (0,I.Ex)({cwd:w,lang:O,role:P,mode:i,task:e,skillsDir:t.skillsDir,modelConfig:D});t.newSession&&(0,k.fH)(N("run.newSessionNoHistory"));let{systemPrompt:$,initialMessages:z}=j,U="1"===process.env.PITHOSAI_DEBUG_STREAM||"true"===process.env.PITHOSAI_DEBUG_STREAM?(0,T.M)():n.streamSimple,q=async(e,t,r)=>{let i=await U(e,t,{...r,...e?.contextWindow!=null&&{contextWindow:e.contextWindow}});return(0,x.z)(i,e)},W=D.model?.supportsTools===!1?[]:(r=F,"agent"===i?r:(r??[]).filter(e=>R.has(String(e?.name??"")))),B=new s.Agent({initialState:{systemPrompt:$,model:D.model,tools:W,messages:z},convertToLlm:e=>(0,y.C)(e,D.model),getApiKey:D.getApiKey,streamFn:q});B=(0,E.ux)(B,{cwd:w,role:P,lang:O}),t.reasoner?B.subscribe((0,h.gY)({getShowThinking:()=>!0,markdown:t.markdown,t:N,outputSink:l})):B.subscribe((0,h.FX)({markdown:t.markdown,outputSink:l}));let K={apiError:!1,apiErrorMessage:void 0,failoverReason:null};return B.subscribe(t=>{if("message_end"===t.type&&t.message&&(e&&e.id&&Promise.resolve((0,A.$R)(p,e)).then(()=>(0,A.kF)(p,{taskId:e.id,message:t.message,role:P,lang:O,mode:i,model:e.model??"deepSeekChat"})).catch(t=>{(0,k.vV)(`Failed to insert task message for task ${e.id}: ${t&&"object"==typeof t&&"message"in t?t.message:String(t)}`)}),"assistant"===t.message.role&&(t.message.errorMessage||t.message.error))){K.apiError=!0;let e="";if("string"==typeof t.message.errorMessage?e=t.message.errorMessage:"string"==typeof t.message.error?e=t.message.error:t.message.error&&"object"==typeof t.message.error&&"string"==typeof t.message.error.message&&(e=t.message.error.message),K.apiErrorMessage=e||void 0,K.failoverReason=e?(0,S.bn)(e):null,"string"==typeof e&&e.toLowerCase().includes("terminated"))try{B.abort()}catch(e){(0,k.vV)(`Failed to abort agent after stream termination error: ${e&&"object"==typeof e&&"message"in e?e.message:String(e)}`)}}}),{agent:B,cwd:w,runState:K}}i()}catch(e){i(e)}})},6669(e,t,r){r.a(e,async function(e,i){try{r.d(t,{M:()=>s});var a=r(785),o=r(4071),n=e([a,o]);function s(){return async function(e,t,r){let i=await (0,a.streamSimple)(e,t,r),n=i[Symbol.asyncIterator].bind(i),s=!1;return i[Symbol.asyncIterator]=function(){let e=n();return{async next(){let t=await e.next();return t.done?(0,o.IW)(`[pi-agent stream] iterator finished (saw done/error: ${s})
|
|
6
|
+
`):(t.value?.type==="done"||t.value?.type==="error")&&(s=!0,(0,o.IW)(`[pi-agent stream] event: ${t.value.type}
|
|
7
|
+
`)),t}}},i}}[a,o]=n.then?(await n)():n,i()}catch(e){i(e)}})},4224(e,t,r){r.d(t,{bn:()=>c});let i=[/rate[_ ]limit|too many requests|429/i,"exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit"],a=[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded"],o=[/timeout|timed out|deadline exceeded|context deadline exceeded/i],n=[/\b402\b/,"payment required","insufficient credits","credit balance","plans & billing"],s=[/invalid[_ ]?api[_ ]?key/i,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],l=["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format"];function d(e,t){if(!e)return!1;let r=e.toLowerCase();return t.some(e=>e instanceof RegExp?e.test(r):r.includes(e))}function c(e){return e?d(e,i)||d(e,a)?"rate_limit":d(e,l)?"format":function(e){if(!e)return!1;let t=e.toLowerCase();return!!t&&(!!d(t,n)||t.includes("billing")&&(t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan")))}(e)?"billing":d(e,o)?"timeout":d(e,s)?"auth":null:null}},3375(e,t,r){r.a(e,async function(e,i){try{r.d(t,{bf:()=>l,sD:()=>u,ux:()=>d});var a=r(7096),o=r(4071),n=r(3586),s=e([n,o]);function l(e){let t=[];if(e?.hooks?.active){let r=e.hooks.active;if("debug"===r.type){let e=(0,n._3)({logData:r.options?.data||!1});if(a.sX.registerAll(e),r.options?.performance){let e=(0,n.TA)();a.sX.registerAll(e)}if(r.options?.stats){let e=(0,n.sD)();a.sX.registerAll(e)}t.push("settings:debug")}else if("debug-basic"===r.type){let e=(0,n._3)({logData:r.options?.data||!1});a.sX.registerAll(e),t.push("settings:debug-basic")}else if("security"===r.type){let e=(0,n.n$)(r.options||{});a.sX.registerAll(e),t.push("settings:security")}}else{let e="1"===process.env.PITHOSAI_DEBUG_HOOKS||"true"===process.env.PITHOSAI_DEBUG_HOOKS,r="1"===process.env.PITHOSAI_SECURITY_HOOKS||"true"===process.env.PITHOSAI_SECURITY_HOOKS;if(e){let e=(0,n._3)({logData:"1"===process.env.PITHOSAI_DEBUG_HOOKS_DATA});a.sX.registerAll(e);let r=(0,n.TA)();a.sX.registerAll(r);let i=(0,n.sD)();a.sX.registerAll(i),t.push("env:debug")}if(r){let e=process.env.PITHOSAI_BLOCKED_TOOLS?process.env.PITHOSAI_BLOCKED_TOOLS.split(",").map(e=>e.trim()):[],r=(0,n.n$)({blockedTools:e,maxPromptLength:parseInt(process.env.PITHOSAI_MAX_PROMPT_LENGTH||"10000",10)});a.sX.registerAll(r),t.push("env:security")}}return{loaded:t.length>0,sources:t}}function d(e,t={}){let{cwd:r,role:i,lang:n}=t;if(!e||"function"!=typeof e.prompt)return(0,o.MD)("Agent does not have prompt method, skipping hook wrapping"),e;let s=e.prompt.bind(e);return e.prompt=async function(e){let t={request:e,cwd:r,role:i,lang:n,timestamp:Date.now()};await a.sX.trigger(a.WD.BEFORE_AGENT_RUN,t);try{let t=await s(e),o={request:e,result:t,cwd:r,role:i,lang:n,timestamp:Date.now()};return await a.sX.trigger(a.WD.AFTER_AGENT_RUN,o),t}catch(o){let t={request:e,error:o,cwd:r,role:i,lang:n,timestamp:Date.now()};throw await a.sX.trigger(a.WD.AFTER_AGENT_RUN,t),o}},"function"==typeof e.subscribe&&e.subscribe(e=>{try{c(e,t)}catch(t){(0,o.MD)(`Hook handler error for ${e?.type}: ${t?.message??t}`)}}),e}async function c(e,t){let{cwd:r,role:i,lang:o}=t;switch(e.type){case"message_start":if(e.message?.role==="assistant"){let t={messages:e.messages||[],model:e.model,cwd:r,role:i,lang:o,timestamp:Date.now()};await a.sX.trigger(a.WD.BEFORE_MODEL_CALL,t)}break;case"message_update":{let t={message:e.message,assistantMessageEvent:e.assistantMessageEvent,messages:e.messages||[],model:e.model,cwd:r,role:i,lang:o,timestamp:Date.now()};a.sX.trigger(a.WD.MESSAGE_UPDATE,t).catch(()=>{});break}case"message_end":if(e.message?.role==="assistant"){let t={messages:e.messages||[],message:e.message,model:e.model,cwd:r,role:i,lang:o,timestamp:Date.now()};await a.sX.trigger(a.WD.AFTER_MODEL_CALL,t)}break;case"tool_call":{let t={toolCall:e.toolCall,messages:e.messages||[],cwd:r,role:i,lang:o,timestamp:Date.now()};await a.sX.trigger(a.WD.BEFORE_TOOL_CALL,t);break}case"tool_result":{let t={toolCall:e.toolCall,result:e.result,messages:e.messages||[],cwd:r,role:i,lang:o,timestamp:Date.now()};await a.sX.trigger(a.WD.AFTER_TOOL_CALL,t)}}}function u(e,t={}){return e.map(e=>(function(e,t={}){let{cwd:r,role:i,lang:o}=t;if("function"!=typeof e.execute)return e;let n=e.execute,s=async function(t,s,l,d){let c=s||{},u={name:e.name,description:e.description,params:c,toolCallId:t,cwd:r,role:i,lang:o,timestamp:Date.now()},p=await a.sX.trigger(a.WD.BEFORE_TOOL_EXECUTE,u),m=null!=p&&void 0!==p.params?p.params:c;try{let s=await n(t,m,l,d),c={name:e.name,description:e.description,params:m,result:s,toolCallId:t,cwd:r,role:i,lang:o,timestamp:Date.now()};return await a.sX.trigger(a.WD.AFTER_TOOL_EXECUTE,c),s}catch(s){let n={name:e.name,description:e.description,params:m,error:s,toolCallId:t,cwd:r,role:i,lang:o,timestamp:Date.now()};throw await a.sX.trigger(a.WD.AFTER_TOOL_EXECUTE,n),s}};return{...e,execute:s}})(e,t))}[n,o]=s.then?(await s)():s,i()}catch(e){i(e)}})},3586(e,t,r){r.a(e,async function(e,i){try{r.d(t,{TA:()=>l,_3:()=>s,n$:()=>d,sD:()=>c});var a=r(7096),o=r(4071),n=e([o]);function s(e={}){let{logData:t=!1,includeHooks:r=Object.values(a.WD),excludeHooks:i=[a.WD.MESSAGE_UPDATE]}=e,n={};return Object.values(a.WD).forEach(e=>{!r.includes(e)||i.includes(e)||(n[e]=async e=>{let{hookType:r,data:i,result:a,error:n,timestamp:s}=e,l=n?"error":"info",d=n?"❌":"✅",c=n?` (error: ${n.message})`:"",u=`${d} Hook: ${r}${c}`;if(t){let e=JSON.stringify(i,null,2),t=void 0!==a?JSON.stringify(a,null,2):"";u+=`
|
|
140
8
|
Data: ${e}`,t&&(u+=`
|
|
141
|
-
Result: ${t}`)}switch(l){case"error":(0,o.vV)(u);break;case"warn":(0,o.JE)(u);break;case"debug":(0,o.MD)(u);break;default:(0,o.fH)(u)}return
|
|
9
|
+
Result: ${t}`)}switch(l){case"error":(0,o.vV)(u);break;case"warn":(0,o.JE)(u);break;case"debug":(0,o.MD)(u);break;default:(0,o.fH)(u)}return i})}),n}function l(){let e=new Map;return{[a.WD.BEFORE_MODEL_CALL]:t=>{let{data:r}=t,i=`model_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return e.set(i,{startTime:Date.now(),messages:r.messages?.length||0,model:r.model}),t.data._timingKey=i,r},[a.WD.AFTER_MODEL_CALL]:t=>{let{data:r,result:i}=t,a=r._timingKey;if(a&&e.has(a)){let t=e.get(a),r=Date.now()-t.startTime;(0,o.fH)(`⏱️ Model call performance: ${r}ms for ${t.messages} messages (${t.model})`),e.delete(a)}return r},[a.WD.BEFORE_TOOL_EXECUTE]:t=>{let{data:r}=t,i=`tool_${r.name}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return e.set(i,{startTime:Date.now(),toolName:r.name,params:r.params}),t.data._timingKey=i,r},[a.WD.AFTER_TOOL_EXECUTE]:t=>{let{data:r,result:i}=t,a=r._timingKey;if(a&&e.has(a)){let t=e.get(a),r=Date.now()-t.startTime;(0,o.fH)(`⏱️ Tool execution: ${t.toolName} took ${r}ms`),e.delete(a)}return r}}}function d(e={}){let{blockedTools:t=[],maxPromptLength:r=1e4}=e;return{[a.WD.BEFORE_SYSTEM_PROMPT_BUILD]:e=>{let{data:t}=e;return t.systemPrompt&&t.systemPrompt.length>r&&(0,o.JE)(`⚠️ System prompt is too long: ${t.systemPrompt.length} characters (max: ${r})`),t},[a.WD.BEFORE_TOOL_EXECUTE]:e=>{let{data:r}=e;if(t.includes(r.name))throw Error(`Tool "${r.name}" is blocked by security policy`);let i=JSON.stringify(r.params||{});for(let e of[/password/i,/secret/i,/api[_-]?key/i,/token/i,/credential/i])if(e.test(i)){(0,o.JE)(`⚠️ Potential sensitive information in tool "${r.name}" parameters`);break}return r},[a.WD.BEFORE_MODEL_CALL]:e=>{let{data:t}=e,r=JSON.stringify(t.messages||[]);for(let e of[/password\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/token\s*[:=]/i])if(e.test(r)){(0,o.JE)("⚠️ Potential sensitive information in model call messages");break}return t}}}function c(){let e={modelCalls:0,toolCalls:0,totalTokens:0,errors:0,startTime:Date.now()};return{[a.WD.BEFORE_MODEL_CALL]:t=>(e.modelCalls++,t?.data),[a.WD.BEFORE_TOOL_EXECUTE]:t=>(e.toolCalls++,t?.data),[a.WD.AFTER_MODEL_CALL]:t=>(t?.result?.usage&&(e.totalTokens+=t.result.usage.total_tokens||0),t?.data),[a.WD.AFTER_TOOL_EXECUTE]:t=>(t?.error&&e.errors++,t?.data),[a.WD.AFTER_AGENT_RUN]:t=>{let r=Date.now()-e.startTime;return(0,o.fH)("\uD83D\uDCCA Agent run stats:"),(0,o.fH)(` Model calls: ${e.modelCalls}`),(0,o.fH)(` Tool calls: ${e.toolCalls}`),(0,o.fH)(` Total tokens: ${e.totalTokens}`),(0,o.fH)(` Errors: ${e.errors}`),(0,o.fH)(` Duration: ${r}ms`),t?.data??null}}}o=(n.then?(await n)():n)[0],i()}catch(e){i(e)}})},7096(e,t,r){r.d(t,{WD:()=>i,sX:()=>a});let i={BEFORE_SYSTEM_PROMPT_BUILD:"beforeSystemPromptBuild",AFTER_SYSTEM_PROMPT_BUILD:"afterSystemPromptBuild",BEFORE_MODEL_CALL:"beforeModelCall",AFTER_MODEL_CALL:"afterModelCall",MESSAGE_UPDATE:"messageUpdate",BEFORE_TOOL_CALL:"beforeToolCall",AFTER_TOOL_CALL:"afterToolCall",BEFORE_TOOL_EXECUTE:"beforeToolExecute",AFTER_TOOL_EXECUTE:"afterToolExecute",BEFORE_AGENT_RUN:"beforeAgentRun",AFTER_AGENT_RUN:"afterAgentRun"},a=new class{constructor(){this.hooks=new Map,Object.values(i).forEach(e=>{this.hooks.set(e,[])})}register(e,t){if(!this.hooks.has(e))throw Error(`Unknown hook type: ${e}`);let r=this.hooks.get(e);return r.push(t),()=>{let e=r.indexOf(t);e>-1&&r.splice(e,1)}}registerAll(e){let t=Object.entries(e).map(([e,t])=>this.register(e,t));return()=>{t.forEach(e=>e())}}async trigger(e,t,r={}){let{mutateData:i=!0}=r;if(!this.hooks.has(e))throw Error(`Unknown hook type: ${e}`);let a=this.hooks.get(e);if(0===a.length)return t;let o=t;for(let t of a)try{let r={hookType:e,data:o,timestamp:Date.now()},a=await t(r);i&&void 0!==a&&(o=a)}catch(t){console.error(`Error in hook handler for ${e}:`,t)}return o}async triggerWithAction(e,t,r,i){let a,o=await this.trigger(e,r);try{a=await i(o);let e={hookType:t,data:o,result:a,timestamp:Date.now()};await this.trigger(t,e,{mutateData:!1})}catch(r){let e={hookType:t,data:o,error:r,timestamp:Date.now()};throw await this.trigger(t,e,{mutateData:!1}),r}return a}clear(){this.hooks.forEach((e,t)=>{this.hooks.set(t,[])})}getStats(){let e={};return this.hooks.forEach((t,r)=>{e[r]=t.length}),e}}},1224(e,t,r){r.d(t,{c:()=>o});var i=r(481);let a=!1;function o(e){if(!process.stdin.isTTY)return()=>{};!a&&process.stdin.isTTY&&((0,i.emitKeypressEvents)(process.stdin),a=!0);let t=process.stdin.isRaw;process.stdin.setRawMode(!0),process.stdin.resume();let r=(t,r)=>{r&&(r.ctrl&&"s"===r.name?(process.stdout.write("\n[Ctrl+S] Stopping agent...\n"),e.stop()):r.ctrl&&"p"===r.name?(process.stdout.write("\n[Ctrl+P] Pausing agent...\n"),e.pause()):r.ctrl&&"c"===r.name&&(process.stdout.write("\n"),process.exit(0)))};return process.stdin.on("keypress",r),()=>{process.stdin.removeListener("keypress",r),process.stdin.isTTY&&process.stdin.setRawMode(t??!1);try{process.stdin.pause()}catch{}}}},6551(e,t,r){r.a(e,async function(e,i){try{r.d(t,{C:()=>s});var a=r(4071),o=r(178),n=e([o,a]);function s(e,t=null){let r=(e||[]).filter(e=>null!=e&&["user","assistant","toolResult"].includes(e.role)),i=[];for(let e=0;e<r.length;e++){let t=r[e];if("toolResult"===t.role){let e=i.length>0?i[i.length-1]:void 0;(e&&"assistant"===e.role&&Array.isArray(e.content)&&"error"!==e.stopReason&&e.content.some(e=>e&&"toolCall"===e.type)||e&&"toolResult"===e.role)&&i.push(t);continue}i.push(t)}let n=function(e=process.env,t=null){let r=e=>{if(null==e||""===e)return;let t=Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?t:void 0},i=t?(0,o.Kr)(t):null,a=null!=i&&null!=i.maxMessageTokens?i.maxMessageTokens:null!=i?Math.max(0,i.maxContextTokens-i.reservedSystemTokens):void 0;return{maxMessageTokens:r(e.PITHOSAI_MAX_MESSAGE_TOKENS)??a,maxHistoryMessages:r(e.PITHOSAI_MAX_HISTORY_MESSAGES),minHistoryMessages:r(e.PITHOSAI_MIN_HISTORY_MESSAGES),maxToolResultChars:r(e.PITHOSAI_MAX_TOOL_RESULT_CHARS),minToolResultChars:r(e.PITHOSAI_MIN_TOOL_RESULT_CHARS)}}(process.env,t);return i=(0,o.G1)(i,n).messages,(0,a.KH)("[llm_request] "+JSON.stringify(i)),i}[o,a]=n.then?(await n)():n,i()}catch(e){i(e)}})},7790(e,t,r){r.d(t,{z:()=>i});function i(e,t){return e}},8038(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Wf:()=>l});var a=r(4071),o=r(1482),n=e([a]);a=(n.then?(await n)():n)[0];let d=new Map;function s(e){let t=d.get(e);if(t)return t;let r={lane:e,queue:[],active:0,maxConcurrent:1,draining:!1};return d.set(e,r),r}function l(e,t){var r;let i,n,l;return r=o.A.Main,i=r.trim()||o.A.Main,n=t?.warnAfterMs??2e3,l=s(i),new Promise((r,o)=>{l.queue.push({task:()=>e(),resolve:e=>r(e),reject:o,enqueuedAt:Date.now(),warnAfterMs:n,onWait:t?.onWait}),(0,a.KH)(`lane enqueue: lane=${i} depth=${l.queue.length+l.active}`),function(e){let t=s(e);if(t.draining)return;t.draining=!0;let r=()=>{for(;t.active<t.maxConcurrent&&t.queue.length>0;){let i=t.queue.shift(),o=Date.now()-i.enqueuedAt;o>=i.warnAfterMs&&(i.onWait?.(o,t.queue.length),(0,a._F)(`lane wait exceeded: lane=${e} waitedMs=${o} queueAhead=${t.queue.length}`)),(0,a.KH)(`lane dequeue: lane=${e} waitedMs=${o} queueAhead=${t.queue.length}`),t.active+=1,(async()=>{let o=Date.now();try{let n=await i.task();t.active-=1,(0,a.KH)(`lane task done: lane=${e} durationMs=${Date.now()-o} active=${t.active} queued=${t.queue.length}`),r(),i.resolve(n)}catch(n){t.active-=1,e.startsWith("auth-probe:")||e.startsWith("session:probe-")||(0,a.CN)(`lane task error: lane=${e} durationMs=${Date.now()-o} error="${String(n)}"`),r(),i.reject(n)}})()}t.draining=!1};r()}(i)})}i()}catch(e){i(e)}})},7420(e,t,r){r.a(e,async function(e,i){try{r.d(t,{_:()=>d});var a=r(1421),o=r(6760),n=r(7975),s=r(4071),l=e([s]);async function d(e,t){let r,i="number"==typeof t?{timeoutMs:t}:t,{timeoutMs:n,cwd:s,input:l,env:d}=i,{windowsVerbatimArguments:c}=i,u=void 0!==l,p=(r=o.basename(e[0]??""),"npm"===r||"npm.cmd"===r||"npm.exe"===r||("node"===r||"node.exe"===r)&&(e[1]??"").includes("npm-cli.js")),m=d?{...process.env,...d}:{...process.env};return p&&(null==m.NPM_CONFIG_FUND&&(m.NPM_CONFIG_FUND="false"),null==m.npm_config_fund&&(m.npm_config_fund="false")),await new Promise((t,r)=>{let i=(0,a.spawn)(e[0],e.slice(1),{stdio:[u?"pipe":"inherit","pipe","pipe"],cwd:s,env:m,windowsVerbatimArguments:c}),o="",d="",p=!1,h=setTimeout(()=>{i.kill("SIGKILL")},n);u&&i.stdin&&(i.stdin.write(l??""),i.stdin.end()),i.stdout?.on("data",e=>{o+=e.toString()}),i.stderr?.on("data",e=>{d+=e.toString()}),i.on("error",e=>{p||(p=!0,clearTimeout(h),r(e))}),i.on("close",(e,r)=>{p||(p=!0,clearTimeout(h),t({stdout:o,stderr:d,code:e,signal:r,killed:i.killed}))})})}s=(l.then?(await l)():l)[0],(0,n.promisify)(a.execFile),i()}catch(e){i(e)}})},1482(e,t,r){r.d(t,{A:()=>i});let i={Main:"main",Cron:"cron",Subagent:"subagent",Nested:"nested"}},4788(e,t,r){r.a(e,async function(e,i){try{r.d(t,{EY:()=>f,aG:()=>k,by:()=>w});var a=r(6760),o=r(1455),n=r(5012),s=r(8362),l=r(8359),d=r(8391),c=r(5885),u=r(4071),p=e([l,d,u,s]);function m(e="en"){let t=n.aL[e]??n.aL[n.Kc];return"zh"===e?`## 语言:
|
|
142
10
|
- **语言**: 简体中文(请使用简体中文回复)。`:`## languages:
|
|
143
|
-
- **Language**: ${t} (respond in ${t}).`}async function
|
|
11
|
+
- **Language**: ${t} (respond in ${t}).`}async function h(e,t,r){try{let i=await (0,l.Lf)(),a=await (0,d.S)(i,{role:r,lang:"zh"===t?"zh":"en"});if(n.GV.every(e=>null!=a[e]&&""!==String(a[e]).trim())){let r=n.GV.map(e=>(a[e]??"").trim()).filter(Boolean);if(0===r.length)return"";let i=(0,s.l)(t)("prompt.projectDir",{cwd:e}),o=m(t);return[r[0],i,o,...r.slice(1)].join("\n\n---\n\n")}return(0,u.vV)("not find all prompt base names, byNames:",JSON.stringify(Object.keys(a))),""}catch(e){return(0,u.vV)("cannot load system prompt from db. error:",e.message,e.stack),""}}async function g(e,t,r){let{missing:i,pithosaiDir:l}=await (0,c.k)(e,t,r);if(i.length>0){let e=Error("Missing prompt files");throw e.code="MISSING_PROMPT_FILES",e.missing=i,e.pithosaiDir=l,e}let d=(0,a.join)(e,".pithosai",r),u=(0,n.nQ)(t),p=[];for(let e of u){let t=(await (0,o.readFile)((0,a.join)(d,e),"utf-8")).trim();t&&p.push(t)}let h=(0,s.l)(t)("prompt.projectDir",{cwd:e}),g=m(t);return[p[0],h,g,...p.slice(1)].join("\n\n---\n\n")}async function f(e,t="en",r="RD"){try{return await g(e,t,r)}catch(a){let i=await h(e,t,r);if(i)return i;throw a}}async function k(e,t="en"){let r,i=(0,a.join)(e,".pithosai","rules");try{await (0,o.readdir)(i)}catch{return""}try{r=await (0,o.readdir)(i)}catch{return""}let n=r.filter(e=>e.toLowerCase().endsWith(".md"));if(0===n.length)return"";let l=[];for(let e of n)try{let t=(await (0,o.readFile)((0,a.join)(i,e),"utf-8")).trim();t&&l.push(t)}catch{continue}if(0===l.length)return"";let d=l.join("\n\n"),c=(0,s.l)("zh"===t?"zh":"en");return"# "+c("prompt.baseRequirementHeading")+"\n\n"+d}async function w(e,t="RD",r="en"){let i=(0,a.join)(e,".pithosai",t,"memory.md"),n=String(r??"").toLowerCase().startsWith("zh")?"# 记忆":"# memory";try{let e=(await (0,o.readFile)(i,"utf-8")).trim();if(!e)return"";return`${n}
|
|
144
12
|
|
|
145
|
-
${e}`}catch(e){if(e?.code==="ENOENT")return"";throw e}}[l,d,u,
|
|
146
|
-
`,{stream:"stderr",kind:"run"}),(0,
|
|
147
|
-
`,{kind:"run"}),(0,
|
|
13
|
+
${e}`}catch(e){if(e?.code==="ENOENT")return"";throw e}}[l,d,u,s]=p.then?(await p)():p,i()}catch(e){i(e)}})},178(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Bz:()=>p,G1:()=>d,Kr:()=>n,QF:()=>m,uO:()=>l,yg:()=>u});var a=r(4071),o=e([a]);a=(o.then?(await o)():o)[0];let u=8e3,p=5e4;function n(e){let t=e?.contextWindow??128e3,r=Math.min(32e3,Math.floor(t/4)),i=e?.maxTokens??4096,o=Math.max(0,t-r-i),n={maxContextTokens:t,maxSystemChars:4*r,reservedSystemTokens:r,maxMessageTokens:o};return(0,a.KH)("[request_size_limits] "+JSON.stringify({maxContextTokens:n.maxContextTokens,maxSystemChars:n.maxSystemChars,reservedSystemTokens:n.reservedSystemTokens,maxMessageTokens:n.maxMessageTokens})),n}let m=5e3,h="\n[Content truncated for request size limit.]";function s(e){if(!Array.isArray(e)||0===e.length)return 0;try{var t;return t=JSON.stringify(e),"string"!=typeof t?0:Math.ceil(Buffer.byteLength(t,"utf8")/4)}catch{return 0}}function l(e,t={}){let r=t.maxChars??128e3;if("string"!=typeof e)return{text:"",truncated:!1};if(e.length<=r)return{text:e,truncated:!1};let i=e.split(/\n\n---\n\n/);if(i.length<=1)return{text:e.slice(0,r)+h,truncated:!0};let a=i[0],o="\n\n---\n\n";for(let e=1;e<i.length;e++){let t=a+o+i[e];if(!(t.length<=r))return{text:a=a+o+"[Additional sections omitted for request size.]",truncated:!0};a=t}return{text:a,truncated:!1}}function d(e,t={}){let r=t.maxMessageTokens??96e3,i=t.maxHistoryMessages??40,o=t.minHistoryMessages??10,n=t.maxToolResultChars??u,l=t.minToolResultChars??2e3;if(!Array.isArray(e)||r<=0)return{messages:e??[],truncated:!1};let m=[...e],h=!1,g=i,f=n,k=s(e);for(;;){let e=function(e,t={}){let r=t.maxMessages??40;if(!Array.isArray(e)||e.length<=r)return{messages:e??[],truncated:!1};let i=e.length-r,a=e.slice(i);for(;a.length>0&&a[0]?.role==="toolResult";)a=a.slice(1);return{messages:a,truncated:!0}}(m,{maxMessages:g});m=e.messages,e.truncated&&(h=!0);let t=function(e,t={}){let r=t.maxToolResultChars??u,i=t.maxImageBase64Chars??p;if(!Array.isArray(e))return{messages:e??[],truncated:!1};let a=!1;return{messages:e.map(e=>{if(e?.role!=="toolResult"||!Array.isArray(e.content))return e;let t=e.content.map(e=>{if(!e)return e;if("toolResult"===e.type&&"string"==typeof e.result){let t=function(e,t=p){if("string"!=typeof e)return{text:String(e),hadOversizedImage:!1,truncated:!1};let r=!1;try{let i=JSON.parse(e);return i&&"object"==typeof i&&"string"==typeof i.body&&i.body.length>t&&(i.body="[Image omitted: too large for request. Reduce size or use a URL.]",i.bodyTruncated=!0,i.bodyOmittedReason="Image too large for request size limit.",r=!0),{text:JSON.stringify(i),hadOversizedImage:r,truncated:r}}catch{let t=c(e,u);return{text:t.text,hadOversizedImage:!1,truncated:t.truncated}}}(e.result,i);(t.hadOversizedImage||t.truncated)&&(a=!0);let o=t.text;return o.length>r&&(o=c(o,r).text,a=!0),{...e,result:o}}if("text"===e.type&&"string"==typeof e.text){if(e.text.length<=r)return e;let t=c(e.text,r);return a=!0,{...e,text:t.text}}return e});return{...e,content:t}}),truncated:a}}(m,{maxToolResultChars:f,maxImageBase64Chars:p});if(m=t.messages,t.truncated&&(h=!0),s(m)<=r)break;if(g>o)g=Math.max(o,Math.floor(.75*g));else if(f>l)f=Math.max(l,Math.floor(.7*f));else break}if(h&&k>r){let e=s(m);(0,a.KH)(`[message_budget] applied token budget: initialTokens=${k}, finalTokens=${e}, maxMessageTokens=${r}, maxHistoryMessages=${i}, maxToolResultChars=${n}`)}return{messages:m,truncated:h}}function c(e,t=u){return"string"!=typeof e?{text:String(e),truncated:!1}:e.length<=t?{text:e,truncated:!1}:{text:e.slice(0,t)+h,truncated:!0}}i()}catch(e){i(e)}})},5885(e,t,r){r.d(t,{k:()=>n});var i=r(6760),a=r(1455),o=r(5012);async function n(e,t="en",r="RD"){let s=(0,i.join)(e,".pithosai",r),l=(0,o.fP)(t),d=[];for(let e of l)try{await (0,a.access)((0,i.join)(s,e))}catch{d.push(e)}return{missing:d,pithosaiDir:s}}},3242(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Ty:()=>y,eF:()=>v});var a=r(4757),o=r(5012),n=r(8362),s=r(4071),l=r(3188),d=r(8641),c=r(1165),u=r(7648);r(7598);var p=r(4267),m=r(9737),h=e([s,a,n,d,u]);function g(e,t,r="info"){let i=String(t??"");if("warn"===r){e.write(`${i}
|
|
14
|
+
`,{stream:"stderr",kind:"run"}),(0,s._F)(i);return}e.write(`${i}
|
|
15
|
+
`,{kind:"run"}),(0,s.KH)(i)}async function f(e){let{outputSink:t,t:r,attempt:i}=e,a=r("warnings.apiRetry",{attempt:String(i),max:String(o.Fu)});g(t,a,"warn");let n=o.k.min+Math.floor(Math.random()*(o.k.max-o.k.min+1));await (0,l.y)(n)}async function k(e){let{agent:t,normalizedRequest:r,timeoutMs:i,timeoutErrorMessage:a,runState:n,controller:s,outputSink:l,t:d}=e;for(let e=1;e<=o.Fu;e++){if(n.apiError=!1,"apiErrorMessage"in n&&(n.apiErrorMessage=void 0),"failoverReason"in n&&(n.failoverReason=null),await function(e,t,r){return(0,m.n)(e,t,()=>Error(r))}(t.prompt(r),i,a),s&&(s.status===p.i.STOPPED||s.status===p.i.PAUSED))return{outcome:"stopped"};if(!n.apiError)return{outcome:"success"};if("string"!=typeof n.failoverReason||"timeout"!==n.failoverReason)break;e<o.Fu&&await f({outputSink:l,t:d,attempt:e})}return{outcome:"error"}}function w(e,t){let r="string"==typeof e?e.trimStart():"",i=r.toLowerCase(),a="/new"===i||/^\/new\s/.test(i),o=a?r.replace(/^\s*\/new\s*/i,"").trim():"string"==typeof e?e:"",n={...t};return a&&(n.newSession=!0),{request:o,opts:n}}async function v(e,t){let r=t??{},i=w([e.title??"",e.description??""].filter(Boolean).join("\n\n"),r),s=i.request;r=i.opts;let l=null!=r.outputSink,d=(0,c.o4)(r.outputSink),{agent:p,cwd:m,runState:h}=await (0,a.N)(e,{...r,outputSink:d}),f=(0,n.l)(r.lang||"en"),v=(null!=r.timeout?1e3*r.timeout:null)??("string"==typeof process.env.PITHOSAI_TIMEOUT_MS?parseInt(process.env.PITHOSAI_TIMEOUT_MS,10):null)??o.TZ,y=r.controller??null;y&&y.attach(p,s,e),g(d,f("run.cwd",{cwd:m})),g(d,f("run.request",{request:s})),d.write("\n",{kind:"run"});try{await (0,u.we)({outputSink:d,routeToolUserLogViaSink:l},async()=>{await k({agent:p,normalizedRequest:s,timeoutMs:v,timeoutErrorMessage:f("errors.runTimeout",{seconds:String(Math.round(v/1e3))}),runState:h,controller:y,outputSink:d,t:f})})}finally{y&&y.detach()}d.write("\n",{kind:"run"})}async function y(e,t){let r=t??{},i=w([e.title??"",e.description??""].filter(Boolean).join("\n\n"),r),s=i.request;r=i.opts;let l=null!=r.outputSink,p=(0,c.o4)(r.outputSink),{agent:m,cwd:h,runState:f}=await (0,a.N)(e,{...r,outputSink:p}),v=(0,n.l)(r.lang||"en"),y=(null!=r.timeout?1e3*r.timeout:null)??("string"==typeof process.env.PITHOSAI_TIMEOUT_MS?parseInt(process.env.PITHOSAI_TIMEOUT_MS,10):null)??o.TZ,b=r.controller??null;b&&b.attach(m,s,e);let S=[];m.subscribe(e=>{"agent_end"===e.type&&e.messages?.length&&(S=e.messages.filter(e=>e?.role==="assistant").map(e=>(0,d.JZ)(e)?.trim()??"").filter(e=>e.length>0))}),g(p,v("run.cwd",{cwd:h})),g(p,v("run.request",{request:s})),p.write("\n",{kind:"run"});try{return await (0,u.we)({outputSink:p,routeToolUserLogViaSink:l},async()=>{let e=await k({agent:m,normalizedRequest:s,timeoutMs:y,timeoutErrorMessage:v("errors.runTimeout",{seconds:String(Math.round(y/1e3))}),runState:f,controller:b,outputSink:p,t:v});if("success"===e.outcome){p.write("\n",{kind:"run"});let e=S.length?S.join("\n\n"):void 0;return{success:!0,results:S,result:e}}p.write("\n",{kind:"run"});let t=S.length?S.join("\n\n"):void 0;return{success:!1,results:S,result:t,error:f.apiErrorMessage??"Agent run failed"}})}catch(t){p.write("\n",{kind:"run"});let e=t?.message??String(t);return{success:!1,error:e}}finally{b&&b.detach()}}[s,a,n,d,u]=h.then?(await h)():h,i()}catch(e){i(e)}})},2130(e,t,r){r.d(t,{f:()=>n});var i=r(1455),a=r(6760),o=r(3024);class n{constructor(e,t){this.cwd=e,this.tracker=t,this.customToolsDir=(0,a.join)(e,".pithosai","custom-tools"),this.templates=this.loadTemplates()}loadTemplates(){return{cli:this.generateCliToolTemplate(),api:this.generateApiToolTemplate(),file:this.generateFileToolTemplate(),data:this.generateDataToolTemplate()}}generateCliToolTemplate(){return`import { exec } from 'child_process';
|
|
148
16
|
import { promisify } from 'util';
|
|
149
17
|
|
|
150
18
|
const execAsync = promisify(exec);
|
|
@@ -246,7 +114,7 @@ export function {{toolFunctionName}}(config = {}) {
|
|
|
246
114
|
}
|
|
247
115
|
}
|
|
248
116
|
};
|
|
249
|
-
}`}analyzeSkillType(e,t){let i=e.toLowerCase();if(i.includes("bash")||i.includes("command")||i.includes("terminal")||i.includes("exec"))return"cli";if(i.includes("api")||i.includes("http")||i.includes("endpoint")||i.includes("request"))return"api";if(i.includes("file")||i.includes("directory")||i.includes("folder")||i.includes("path"))return"file";if(i.includes("data")||i.includes("process")||i.includes("transform")||i.includes("convert"))return"data";let r=Object.keys(t.paramFrequency).join(" ").toLowerCase();return r.includes("output")||r.includes("file")?"file":r.includes("url")||r.includes("endpoint")?"api":"cli"}extractParameters(e,t){let i,r=[],s=/(?:parameter|arg|option|flag)\s+([\w-]+)(?:\s*[:=]\s*([^\r\n]+))?/gi;for(;null!==(i=s.exec(e));){let e=i[1].replace(/^-{1,2}/,""),s=i[2]||`Parameter ${e}`,o="string";s.toLowerCase().includes("number")||s.toLowerCase().includes("count")||s.toLowerCase().includes("delay")?o="number":(s.toLowerCase().includes("boolean")||s.toLowerCase().includes("flag")||s.toLowerCase().includes("enable"))&&(o="boolean");let a=this.isParameterRequired(e,t);r.push({name:e,type:o,description:s.trim(),required:a})}for(let e of this.tracker.getCommonParameters(t.skillName,20)){let[t,i]=e.param.split("=");if(!r.find(e=>e.name===t)){let s="string";try{let e=JSON.parse(i);"boolean"==typeof e?s="boolean":"number"==typeof e&&(s="number")}catch{}r.push({name:t,type:s,description:`Parameter ${t} (auto-detected from usage)`,required:e.percentage>80})}}return r}isParameterRequired(e,t){let i=t.totalExecutions;return Object.entries(t.paramFrequency).filter(([t])=>t.startsWith(`${e}=`)).reduce((e,[,t])=>e+t,0)/i>.9}generateParameterSchema(e){let t={},i=[];for(let r of e){let e={type:r.type,description:r.description};void 0!==r.defaultValue&&(e.default=r.defaultValue),t[r.name]=e,r.required&&i.push(r.name)}let r={type:"object",properties:t};return i.length>0&&(r.required=i),JSON.stringify(r,null,2)}generateCommandCode(e,t,i){let r=[];r.push('let command = "";');let s=this.tracker.getExecutionHistory(e,10),o=new Set;for(let e of s)e.params.command&&o.add(e.params.command);if(o.size>0){let e=Array.from(o)[0];r.push(`command = "${e}";`)}else r.push(`command = "${e}";`);for(let e of t)"boolean"===e.type?(r.push(`if (params.${e.name}) {`),r.push(` command += " --${e.name}";`),r.push("}")):("number"===e.type||"string"===e.type)&&(r.push(`if (params.${e.name} !== undefined) {`),r.push(` command += \` --${e.name} "\${params.${e.name}}"\`;`),r.push("}"));return r.join("\n ")}async convert(e,t,i){let r=this.tracker.stats[e];if(!r)throw Error(`No usage statistics found for skill: ${e}`);let s=this.analyzeSkillType(t,r),o=this.extractParameters(t,r),a=`${e}_tool`,n=`create${e.charAt(0).toUpperCase()+e.slice(1)}Tool`,l=this.generateParameterSchema(o),d=(this.templates[s]||this.templates.cli).replace(/{{toolName}}/g,a).replace(/{{toolFunctionName}}/g,n).replace(/{{toolDescription}}/g,i.description||`Tool converted from ${e} skill`).replace(/{{parametersSchema}}/g,l);if("cli"===s){let t=this.generateCommandCode(e,o,r);d=d.replace(/{{commandGeneration}}/g,t)}let c={name:a,originalSkill:e,skillType:s,convertedAt:new Date().toISOString(),parameters:o.map(e=>({name:e.name,type:e.type,required:e.required,description:e.description})),usageStats:{totalExecutions:r.totalExecutions,successRate:r.successfulExecutions/r.totalExecutions,avgExecutionTime:r.avgExecutionTime,lastExecuted:r.lastExecuted},metadata:i};return{name:a,description:i.description||`Tool converted from ${e} skill`,parameters:o.reduce((e,t)=>(e[t.name]={type:t.type,description:t.description,required:t.required},e),{}),implementation:d,metadata:JSON.stringify(c,null,2)}}async saveTool(e){await (0,r.mkdir)(this.customToolsDir,{recursive:!0});let t=(0,s.join)(this.customToolsDir,`${e.name}.js`),i=(0,s.join)(this.customToolsDir,`${e.name}.json`);return await (0,r.writeFile)(t,e.implementation,"utf-8"),await (0,r.writeFile)(i,e.metadata,"utf-8"),t}toolExists(e){let t=`${e}_tool`,i=(0,s.join)(this.customToolsDir,`${t}.js`),r=(0,s.join)(this.customToolsDir,`${t}.json`);return(0,o.existsSync)(i)&&(0,o.existsSync)(r)}async loadExistingTools(){return!(0,o.existsSync)(this.customToolsDir),[]}async getConversionReport(e,t,i){let r=this.tracker.stats[e];if(!r)throw Error(`No usage statistics found for skill: ${e}`);let s=this.analyzeSkillType(t,r),o=this.extractParameters(t,r),a=Math.min(50,r.avgExecutionTime/100),n=(1-r.successfulExecutions/r.totalExecutions)*30;return{skillName:e,conversionScore:r.conversionScore,suggestedType:s,parameters:o,estimatedBenefits:{performance:a,reliability:n,usability:20},ready:r.totalExecutions>=3&&r.conversionScore>=60}}}},9434(e,t,i){i.a(e,async function(e,r){try{i.d(t,{A$:()=>s.A});var s=i(5671),o=i(8285),a=i(7415),n=e([s,o,a]);[s,o,a]=n.then?(await n)():n,r()}catch(e){r(e)}})},5671(e,t,i){i.a(e,async function(e,r){try{i.d(t,{A:()=>d});var s=i(3024),o=i(6760),a=i(8285),n=i(8140),l=e([a]);function d(e){let t=(0,o.resolve)((0,n.X)(e));return(0,s.existsSync)(t)?(0,a.UI)({dir:t,source:"path"}):{skills:[],diagnostics:[{type:"warning",message:`Skills directory not found: ${t} (no skills loaded)`,path:t}]}}a=(l.then?(await l)():l)[0],r()}catch(e){r(e)}})},7415(e,t,i){i.a(e,async function(e,t){try{i(1455);var r=i(4204);i(5846);var s=e([r]);r=(s.then?(await s)():s)[0],t()}catch(e){t(e)}})},5846(e,t,i){i.d(t,{m:()=>a});var r=i(3024),s=i(6760),o=i(1455);class a{constructor(e){this.cwd=e,this.storagePath=(0,s.join)(e,".pithosai","skill-executions.json"),this.statsPath=(0,s.join)(e,".pithosai","skill-stats.json"),this.conversionConfigPath=(0,s.join)(e,".pithosai","skill-conversion.json"),this.executions=this.loadExecutions(),this.stats=this.loadStats(),this.config=this.loadConfig()}loadExecutions(){try{if((0,r.existsSync)(this.storagePath)){let e=(0,r.readFileSync)(this.storagePath,"utf-8");return JSON.parse(e)}}catch(e){console.warn(`Failed to load skill executions: ${e.message}`)}return[]}loadStats(){try{if((0,r.existsSync)(this.statsPath)){let e=(0,r.readFileSync)(this.statsPath,"utf-8");return JSON.parse(e)}}catch(e){console.warn(`Failed to load skill stats: ${e.message}`)}return{}}loadConfig(){let e={autoConvert:!0,minFrequency:3,minSuccessRate:.7,excludedSkills:[],customTemplates:{},conversionThreshold:.8};try{if((0,r.existsSync)(this.conversionConfigPath)){let t=(0,r.readFileSync)(this.conversionConfigPath,"utf-8");return{...e,...JSON.parse(t)}}}catch(e){console.warn(`Failed to load conversion config: ${e.message}`)}return e}async saveExecutions(){try{await (0,o.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),(0,r.writeFileSync)(this.storagePath,JSON.stringify(this.executions,null,2),"utf-8")}catch(e){console.warn(`Failed to save skill executions: ${e.message}`)}}async saveStats(){try{await (0,o.mkdir)((0,s.dirname)(this.statsPath),{recursive:!0}),(0,r.writeFileSync)(this.statsPath,JSON.stringify(this.stats,null,2),"utf-8")}catch(e){console.warn(`Failed to save skill stats: ${e.message}`)}}async record(e,t,i,r,s){let o={skillName:e,timestamp:new Date().toISOString(),params:this.sanitizeParams(t),success:i,executionTime:r,...s&&{error:s}};this.executions.push(o);let a=this.executions.filter(t=>t.skillName===e);a.length>1e3&&(this.executions=this.executions.filter(t=>t.skillName!==e||a.slice(-1e3).includes(t))),await this.saveExecutions(),await this.updateStats(e,o)}sanitizeParams(e){let t={...e},i=["password","secret","token","key","apiKey","apikey"];for(let e of Object.keys(t)){let r=e.toLowerCase();i.some(e=>r.includes(e))&&(t[e]="***REDACTED***")}return t}async updateStats(e,t){this.stats[e]||(this.stats[e]={skillName:e,totalExecutions:0,successfulExecutions:0,failedExecutions:0,avgExecutionTime:0,paramFrequency:{},lastExecuted:t.timestamp,conversionScore:0});let i=this.stats[e];i.totalExecutions++,t.success?i.successfulExecutions++:i.failedExecutions++;let r=i.avgExecutionTime*(i.totalExecutions-1)+t.executionTime;for(let[e,s]of(i.avgExecutionTime=r/i.totalExecutions,Object.entries(t.params))){let t=`${e}=${JSON.stringify(s)}`;i.paramFrequency[t]=(i.paramFrequency[t]||0)+1}i.lastExecuted=t.timestamp,i.conversionScore=this.calculateConversionScore(i),await this.saveStats()}calculateConversionScore(e){let t;t=0+Math.min(e.totalExecutions/10,40)+30*(e.successfulExecutions/e.totalExecutions);let i=Object.keys(e.paramFrequency).length,r=Math.max(...Object.values(e.paramFrequency));return t+=i>0?r/e.totalExecutions*20:0,Math.min(100,t+=e.avgExecutionTime>0?Math.min(10,1e3/e.avgExecutionTime):0)}getSuggestedConversions(e=100*this.config.conversionThreshold){let t=[];for(let[i,r]of Object.entries(this.stats))!this.config.excludedSkills.includes(i)&&r.totalExecutions>=this.config.minFrequency&&r.conversionScore>=e&&t.push({skillName:i,score:r.conversionScore,stats:r});return t.sort((e,t)=>t.score-e.score)}getExecutionHistory(e,t=50){return this.executions.filter(t=>t.skillName===e).slice(-t)}getCommonParameters(e,t=10){let i=this.stats[e];if(!i||!i.paramFrequency)return[];let r=i.totalExecutions;return Object.entries(i.paramFrequency).map(([e,t])=>({param:e,frequency:t,percentage:t/r*100})).sort((e,t)=>t.frequency-e.frequency).slice(0,t)}async clearSkillRecords(e){this.executions=this.executions.filter(t=>t.skillName!==e),delete this.stats[e],await this.saveExecutions(),await this.saveStats()}async clearAllRecords(){this.executions=[],this.stats={},await this.saveExecutions(),await this.saveStats()}getSummary(){let e=Object.keys(this.stats),t=e.reduce((e,t)=>e+this.stats[t].totalExecutions,0),i=e.length>0?e.reduce((e,t)=>{let i=this.stats[t];return e+i.successfulExecutions/i.totalExecutions},0)/e.length:0,r=e.map(e=>({skillName:e,executions:this.stats[e].totalExecutions,score:this.stats[e].conversionScore})).sort((e,t)=>t.executions-e.executions).slice(0,10);return{totalSkills:e.length,totalExecutions:t,avgSuccessRate:100*i,topSkills:r}}}},4427(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Ex:()=>g});var s=i(6760),o=i(8285),a=i(9434),n=i(4788),l=i(178),d=i(8362),c=i(7096),u=i(2369),p=i(8359),h=i(4071),m=e([u,d,n,a,o,l,p,h]);async function g({cwd:e,lang:t,role:i,mode:r="agent",task:m,skillsDir:g,modelConfig:f}){let w,k=await (0,u.Lf)(),y=(0,d.l)(t),v=(0,d.l)("zh"===t?"zh":"en"),b="",S="";if("agent"===r){try{w=await (0,n.EY)(e,t,i)}catch(e){if(e?.code==="MISSING_PROMPT_FILES"){let t=Error(`Missing prompt files in ${e.pithosaiDir}: ${(e.missing||[]).join(", ")}`);throw t.code=e.code,t.pithosaiDir=e.pithosaiDir,t.missing=e.missing,t}throw e}b=await (0,n.aG)(e,t),S=await (0,n.by)(e,i,t)}else{let e;e=String(t??"").toLowerCase().startsWith("zh"),w="dialog"===r?e?"你是助理(对话模式)。\n只回答用户的问题。\n可以在必要时使用只读工具:read、list_files、read_pdf、web_fetch、web_search、proxy_downloader、read_email。\n禁止使用任何会修改环境或执行命令的工具(如 write/edit/bash/exec/queue_exec 等)。\n不要展示工具调用 JSON。\n只输出最终答案,不要添加额外说明或元评论。":"You are a helpful assistant (DIALOG MODE).\nAnswer the user's question directly.\nYou may use read-only tools when needed: read, list_files, read_pdf, web_fetch, web_search, proxy_downloader, read_email.\nNever use mutating/execution tools (e.g. write/edit/bash/exec/queue_exec).\nDo NOT output tool-call JSON.\nOutput only the final answer, with no extra commentary.":e?"你是规划助手(计划模式)。\n为用户的请求生成一个计划(Markdown)。\n只输出计划内容(Markdown)。\n可以在必要时使用只读工具:read、list_files、read_pdf、web_fetch、web_search、proxy_downloader、read_email。\n禁止使用任何会修改环境或执行命令的工具(如 write/edit/bash/exec/queue_exec 等)。":"You are a planning assistant (PLAN MODE).\nCreate a plan in Markdown for the user's request.\nOutput ONLY the plan content (Markdown).\nYou may use read-only tools when needed: read, list_files, read_pdf, web_fetch, web_search, proxy_downloader, read_email.\nNever use mutating/execution tools (e.g. write/edit/bash/exec/queue_exec)."}let T="",C="",E="";if("agent"===r){let t=g||(0,s.resolve)(e,".pithosai","skills"),{skills:i}=(0,a.A$)(t);i.length>0&&(T=(0,o.lg)(i)+"\n"+y("prompt.skillsInstruction")),C=v("prompt.toolArgSizeLimit",{maxChars:String(l.QF)}),E=v("prompt.toolCallJsonFormat",{})}let x={systemPromptBase:w,requirementsBlock:b,memoryBlock:S,skillsBlock:T,parts:[w],lang:t,role:i,cwd:e},I=(await c.sX.trigger(c.WD.BEFORE_SYSTEM_PROMPT_BUILD,x)).parts||[w];b&&I.push(b),S&&I.push(S),T&&I.push(T);let A=I.join("\n\n---\n\n"),O=A,P=A;if(f){let{maxSystemChars:e}=(0,l.Kr)(f.model),{text:t}=(0,l.uO)(A,{maxChars:e});O=t,P="agent"===r?O+"\n\n---\n\n"+C+"\n\n"+E:O}else"agent"===r&&(P=A+"\n\n---\n\n"+C+"\n\n"+E);let R={systemPromptRaw:A,systemPromptTruncated:O,systemPrompt:P,toolArgLimitBlock:C,toolCallJsonFormatBlock:E,lang:t,role:i,cwd:e};P=(await c.sX.trigger(c.WD.AFTER_SYSTEM_PROMPT_BUILD,R)).systemPrompt||P;let M=[];if(m&&m.id)try{let e=(0,p.XV)(k,{taskId:m.id,asc:!1}),t=[];for(let i of e)try{t.push(JSON.parse(i.message))}catch{}M=t.reverse(),(0,h.KH)(`Loaded ${M.length} task messages for task ${m.id}`)}catch(e){(0,h.CN)(`Failed to load task messages for task ${m.id}: ${e.message}`),M=[]}return{systemPrompt:P,systemPromptRaw:A,systemPromptTruncated:O,initialMessages:M}}[u,d,n,a,o,l,p,h]=m.then?(await m)():m,r()}catch(e){r(e)}})},9662(e,t,i){i.a(e,async function(e,r){try{i.d(t,{v:()=>d});var s=i(9748),o=i(6760),a=i(3024),n=i(4071),l=e([s,n]);[s,n]=l.then?(await l)():l;class d{constructor(e="./prompts.md"){this.filePath=o.resolve(e),this.watcher=null,this.lastModified=null,this.debounceTimeout=null}async initialize(){try{await a.promises.access(this.filePath)}catch{await this.createSampleFile()}}async createSampleFile(){let e=`# Task List
|
|
117
|
+
}`}analyzeSkillType(e,t){let r=e.toLowerCase();if(r.includes("bash")||r.includes("command")||r.includes("terminal")||r.includes("exec"))return"cli";if(r.includes("api")||r.includes("http")||r.includes("endpoint")||r.includes("request"))return"api";if(r.includes("file")||r.includes("directory")||r.includes("folder")||r.includes("path"))return"file";if(r.includes("data")||r.includes("process")||r.includes("transform")||r.includes("convert"))return"data";let i=Object.keys(t.paramFrequency).join(" ").toLowerCase();return i.includes("output")||i.includes("file")?"file":i.includes("url")||i.includes("endpoint")?"api":"cli"}extractParameters(e,t){let r,i=[],a=/(?:parameter|arg|option|flag)\s+([\w-]+)(?:\s*[:=]\s*([^\r\n]+))?/gi;for(;null!==(r=a.exec(e));){let e=r[1].replace(/^-{1,2}/,""),a=r[2]||`Parameter ${e}`,o="string";a.toLowerCase().includes("number")||a.toLowerCase().includes("count")||a.toLowerCase().includes("delay")?o="number":(a.toLowerCase().includes("boolean")||a.toLowerCase().includes("flag")||a.toLowerCase().includes("enable"))&&(o="boolean");let n=this.isParameterRequired(e,t);i.push({name:e,type:o,description:a.trim(),required:n})}for(let e of this.tracker.getCommonParameters(t.skillName,20)){let[t,r]=e.param.split("=");if(!i.find(e=>e.name===t)){let a="string";try{let e=JSON.parse(r);"boolean"==typeof e?a="boolean":"number"==typeof e&&(a="number")}catch{}i.push({name:t,type:a,description:`Parameter ${t} (auto-detected from usage)`,required:e.percentage>80})}}return i}isParameterRequired(e,t){let r=t.totalExecutions;return Object.entries(t.paramFrequency).filter(([t])=>t.startsWith(`${e}=`)).reduce((e,[,t])=>e+t,0)/r>.9}generateParameterSchema(e){let t={},r=[];for(let i of e){let e={type:i.type,description:i.description};void 0!==i.defaultValue&&(e.default=i.defaultValue),t[i.name]=e,i.required&&r.push(i.name)}let i={type:"object",properties:t};return r.length>0&&(i.required=r),JSON.stringify(i,null,2)}generateCommandCode(e,t,r){let i=[];i.push('let command = "";');let a=this.tracker.getExecutionHistory(e,10),o=new Set;for(let e of a)e.params.command&&o.add(e.params.command);if(o.size>0){let e=Array.from(o)[0];i.push(`command = "${e}";`)}else i.push(`command = "${e}";`);for(let e of t)"boolean"===e.type?(i.push(`if (params.${e.name}) {`),i.push(` command += " --${e.name}";`),i.push("}")):("number"===e.type||"string"===e.type)&&(i.push(`if (params.${e.name} !== undefined) {`),i.push(` command += \` --${e.name} "\${params.${e.name}}"\`;`),i.push("}"));return i.join("\n ")}async convert(e,t,r){let i=this.tracker.stats[e];if(!i)throw Error(`No usage statistics found for skill: ${e}`);let a=this.analyzeSkillType(t,i),o=this.extractParameters(t,i),n=`${e}_tool`,s=`create${e.charAt(0).toUpperCase()+e.slice(1)}Tool`,l=this.generateParameterSchema(o),d=(this.templates[a]||this.templates.cli).replace(/{{toolName}}/g,n).replace(/{{toolFunctionName}}/g,s).replace(/{{toolDescription}}/g,r.description||`Tool converted from ${e} skill`).replace(/{{parametersSchema}}/g,l);if("cli"===a){let t=this.generateCommandCode(e,o,i);d=d.replace(/{{commandGeneration}}/g,t)}let c={name:n,originalSkill:e,skillType:a,convertedAt:new Date().toISOString(),parameters:o.map(e=>({name:e.name,type:e.type,required:e.required,description:e.description})),usageStats:{totalExecutions:i.totalExecutions,successRate:i.successfulExecutions/i.totalExecutions,avgExecutionTime:i.avgExecutionTime,lastExecuted:i.lastExecuted},metadata:r};return{name:n,description:r.description||`Tool converted from ${e} skill`,parameters:o.reduce((e,t)=>(e[t.name]={type:t.type,description:t.description,required:t.required},e),{}),implementation:d,metadata:JSON.stringify(c,null,2)}}async saveTool(e){await (0,i.mkdir)(this.customToolsDir,{recursive:!0});let t=(0,a.join)(this.customToolsDir,`${e.name}.js`),r=(0,a.join)(this.customToolsDir,`${e.name}.json`);return await (0,i.writeFile)(t,e.implementation,"utf-8"),await (0,i.writeFile)(r,e.metadata,"utf-8"),t}toolExists(e){let t=`${e}_tool`,r=(0,a.join)(this.customToolsDir,`${t}.js`),i=(0,a.join)(this.customToolsDir,`${t}.json`);return(0,o.existsSync)(r)&&(0,o.existsSync)(i)}async loadExistingTools(){return!(0,o.existsSync)(this.customToolsDir),[]}async getConversionReport(e,t,r){let i=this.tracker.stats[e];if(!i)throw Error(`No usage statistics found for skill: ${e}`);let a=this.analyzeSkillType(t,i),o=this.extractParameters(t,i),n=Math.min(50,i.avgExecutionTime/100),s=(1-i.successfulExecutions/i.totalExecutions)*30;return{skillName:e,conversionScore:i.conversionScore,suggestedType:a,parameters:o,estimatedBenefits:{performance:n,reliability:s,usability:20},ready:i.totalExecutions>=3&&i.conversionScore>=60}}}},9434(e,t,r){r.a(e,async function(e,i){try{r.d(t,{A$:()=>a.A});var a=r(5671),o=r(2421),n=r(7415),s=e([a,o,n]);[a,o,n]=s.then?(await s)():s,i()}catch(e){i(e)}})},5671(e,t,r){r.a(e,async function(e,i){try{r.d(t,{A:()=>d});var a=r(3024),o=r(6760),n=r(2421),s=r(8140),l=e([n]);function d(e){let t=(0,o.resolve)((0,s.X)(e));return(0,a.existsSync)(t)?(0,n.loadSkillsFromDir)({dir:t,source:"path"}):{skills:[],diagnostics:[{type:"warning",message:`Skills directory not found: ${t} (no skills loaded)`,path:t}]}}n=(l.then?(await l)():l)[0],i()}catch(e){i(e)}})},7415(e,t,r){r.a(e,async function(e,t){try{r(1455);var i=r(4204);r(5846);var a=e([i]);i=(a.then?(await a)():a)[0],t()}catch(e){t(e)}})},5846(e,t,r){r.d(t,{m:()=>n});var i=r(3024),a=r(6760),o=r(1455);class n{constructor(e){this.cwd=e,this.storagePath=(0,a.join)(e,".pithosai","skill-executions.json"),this.statsPath=(0,a.join)(e,".pithosai","skill-stats.json"),this.conversionConfigPath=(0,a.join)(e,".pithosai","skill-conversion.json"),this.executions=this.loadExecutions(),this.stats=this.loadStats(),this.config=this.loadConfig()}loadExecutions(){try{if((0,i.existsSync)(this.storagePath)){let e=(0,i.readFileSync)(this.storagePath,"utf-8");return JSON.parse(e)}}catch(e){console.warn(`Failed to load skill executions: ${e.message}`)}return[]}loadStats(){try{if((0,i.existsSync)(this.statsPath)){let e=(0,i.readFileSync)(this.statsPath,"utf-8");return JSON.parse(e)}}catch(e){console.warn(`Failed to load skill stats: ${e.message}`)}return{}}loadConfig(){let e={autoConvert:!0,minFrequency:3,minSuccessRate:.7,excludedSkills:[],customTemplates:{},conversionThreshold:.8};try{if((0,i.existsSync)(this.conversionConfigPath)){let t=(0,i.readFileSync)(this.conversionConfigPath,"utf-8");return{...e,...JSON.parse(t)}}}catch(e){console.warn(`Failed to load conversion config: ${e.message}`)}return e}async saveExecutions(){try{await (0,o.mkdir)((0,a.dirname)(this.storagePath),{recursive:!0}),(0,i.writeFileSync)(this.storagePath,JSON.stringify(this.executions,null,2),"utf-8")}catch(e){console.warn(`Failed to save skill executions: ${e.message}`)}}async saveStats(){try{await (0,o.mkdir)((0,a.dirname)(this.statsPath),{recursive:!0}),(0,i.writeFileSync)(this.statsPath,JSON.stringify(this.stats,null,2),"utf-8")}catch(e){console.warn(`Failed to save skill stats: ${e.message}`)}}async record(e,t,r,i,a){let o={skillName:e,timestamp:new Date().toISOString(),params:this.sanitizeParams(t),success:r,executionTime:i,...a&&{error:a}};this.executions.push(o);let n=this.executions.filter(t=>t.skillName===e);n.length>1e3&&(this.executions=this.executions.filter(t=>t.skillName!==e||n.slice(-1e3).includes(t))),await this.saveExecutions(),await this.updateStats(e,o)}sanitizeParams(e){let t={...e},r=["password","secret","token","key","apiKey","apikey"];for(let e of Object.keys(t)){let i=e.toLowerCase();r.some(e=>i.includes(e))&&(t[e]="***REDACTED***")}return t}async updateStats(e,t){this.stats[e]||(this.stats[e]={skillName:e,totalExecutions:0,successfulExecutions:0,failedExecutions:0,avgExecutionTime:0,paramFrequency:{},lastExecuted:t.timestamp,conversionScore:0});let r=this.stats[e];r.totalExecutions++,t.success?r.successfulExecutions++:r.failedExecutions++;let i=r.avgExecutionTime*(r.totalExecutions-1)+t.executionTime;for(let[e,a]of(r.avgExecutionTime=i/r.totalExecutions,Object.entries(t.params))){let t=`${e}=${JSON.stringify(a)}`;r.paramFrequency[t]=(r.paramFrequency[t]||0)+1}r.lastExecuted=t.timestamp,r.conversionScore=this.calculateConversionScore(r),await this.saveStats()}calculateConversionScore(e){let t;t=0+Math.min(e.totalExecutions/10,40)+30*(e.successfulExecutions/e.totalExecutions);let r=Object.keys(e.paramFrequency).length,i=Math.max(...Object.values(e.paramFrequency));return t+=r>0?i/e.totalExecutions*20:0,Math.min(100,t+=e.avgExecutionTime>0?Math.min(10,1e3/e.avgExecutionTime):0)}getSuggestedConversions(e=100*this.config.conversionThreshold){let t=[];for(let[r,i]of Object.entries(this.stats))!this.config.excludedSkills.includes(r)&&i.totalExecutions>=this.config.minFrequency&&i.conversionScore>=e&&t.push({skillName:r,score:i.conversionScore,stats:i});return t.sort((e,t)=>t.score-e.score)}getExecutionHistory(e,t=50){return this.executions.filter(t=>t.skillName===e).slice(-t)}getCommonParameters(e,t=10){let r=this.stats[e];if(!r||!r.paramFrequency)return[];let i=r.totalExecutions;return Object.entries(r.paramFrequency).map(([e,t])=>({param:e,frequency:t,percentage:t/i*100})).sort((e,t)=>t.frequency-e.frequency).slice(0,t)}async clearSkillRecords(e){this.executions=this.executions.filter(t=>t.skillName!==e),delete this.stats[e],await this.saveExecutions(),await this.saveStats()}async clearAllRecords(){this.executions=[],this.stats={},await this.saveExecutions(),await this.saveStats()}getSummary(){let e=Object.keys(this.stats),t=e.reduce((e,t)=>e+this.stats[t].totalExecutions,0),r=e.length>0?e.reduce((e,t)=>{let r=this.stats[t];return e+r.successfulExecutions/r.totalExecutions},0)/e.length:0,i=e.map(e=>({skillName:e,executions:this.stats[e].totalExecutions,score:this.stats[e].conversionScore})).sort((e,t)=>t.executions-e.executions).slice(0,10);return{totalSkills:e.length,totalExecutions:t,avgSuccessRate:100*r,topSkills:i}}}},4427(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Ex:()=>g});var a=r(6760),o=r(2421),n=r(9434),s=r(4788),l=r(178),d=r(8362),c=r(7096),u=r(2369),p=r(8359),m=r(4071),h=e([u,d,s,n,o,l,p,m]);async function g({cwd:e,lang:t,role:r,mode:i="agent",task:h,skillsDir:g,modelConfig:f}){let k,w=await (0,u.Lf)(),v=(0,d.l)(t),y=(0,d.l)("zh"===t?"zh":"en"),b="",S="";if("agent"===i){try{k=await (0,s.EY)(e,t,r)}catch(e){if(e?.code==="MISSING_PROMPT_FILES"){let t=Error(`Missing prompt files in ${e.pithosaiDir}: ${(e.missing||[]).join(", ")}`);throw t.code=e.code,t.pithosaiDir=e.pithosaiDir,t.missing=e.missing,t}throw e}b=await (0,s.aG)(e,t),S=await (0,s.by)(e,r,t)}else{let e;e=String(t??"").toLowerCase().startsWith("zh"),k="dialog"===i?e?"你是助理(对话模式)。\n只回答用户的问题。\n可以在必要时使用只读工具:read、list_files、read_pdf、web_fetch、web_search、proxy_downloader、read_email。\n禁止使用任何会修改环境或执行命令的工具(如 write/edit/bash/exec/queue_exec 等)。\n不要展示工具调用 JSON。\n只输出最终答案,不要添加额外说明或元评论。":"You are a helpful assistant (DIALOG MODE).\nAnswer the user's question directly.\nYou may use read-only tools when needed: read, list_files, read_pdf, web_fetch, web_search, proxy_downloader, read_email.\nNever use mutating/execution tools (e.g. write/edit/bash/exec/queue_exec).\nDo NOT output tool-call JSON.\nOutput only the final answer, with no extra commentary.":e?"你是规划助手(计划模式)。\n为用户的请求生成一个计划(Markdown)。\n只输出计划内容(Markdown)。\n可以在必要时使用只读工具:read、list_files、read_pdf、web_fetch、web_search、proxy_downloader、read_email。\n禁止使用任何会修改环境或执行命令的工具(如 write/edit/bash/exec/queue_exec 等)。":"You are a planning assistant (PLAN MODE).\nCreate a plan in Markdown for the user's request.\nOutput ONLY the plan content (Markdown).\nYou may use read-only tools when needed: read, list_files, read_pdf, web_fetch, web_search, proxy_downloader, read_email.\nNever use mutating/execution tools (e.g. write/edit/bash/exec/queue_exec)."}let T="",E="",x="";if("agent"===i){let t=g||(0,a.resolve)(e,".pithosai","skills"),{skills:r}=(0,n.A$)(t);r.length>0&&(T=(0,o.formatSkillsForPrompt)(r)+"\n"+v("prompt.skillsInstruction")),E=y("prompt.toolArgSizeLimit",{maxChars:String(l.QF)}),x=y("prompt.toolCallJsonFormat",{})}let C={systemPromptBase:k,requirementsBlock:b,memoryBlock:S,skillsBlock:T,parts:[k],lang:t,role:r,cwd:e},A=(await c.sX.trigger(c.WD.BEFORE_SYSTEM_PROMPT_BUILD,C)).parts||[k];b&&A.push(b),S&&A.push(S),T&&A.push(T);let I=A.join("\n\n---\n\n"),O=I,P=I;if(f){let{maxSystemChars:e}=(0,l.Kr)(f.model),{text:t}=(0,l.uO)(I,{maxChars:e});O=t,P="agent"===i?O+"\n\n---\n\n"+E+"\n\n"+x:O}else"agent"===i&&(P=I+"\n\n---\n\n"+E+"\n\n"+x);let R={systemPromptRaw:I,systemPromptTruncated:O,systemPrompt:P,toolArgLimitBlock:E,toolCallJsonFormatBlock:x,lang:t,role:r,cwd:e};P=(await c.sX.trigger(c.WD.AFTER_SYSTEM_PROMPT_BUILD,R)).systemPrompt||P;let N=[];if(h&&h.id)try{let e=await (0,p.XV)(w,{taskId:h.id,asc:!1}),t=[];for(let r of e)try{t.push(JSON.parse(r.message))}catch{}N=t.reverse(),(0,m.KH)(`Loaded ${N.length} task messages for task ${h.id}`)}catch(e){(0,m.CN)(`Failed to load task messages for task ${h.id}: ${e.message}`),N=[]}return{systemPrompt:P,systemPromptRaw:I,systemPromptTruncated:O,initialMessages:N}}[u,d,s,n,o,l,p,m]=h.then?(await h)():h,i()}catch(e){i(e)}})},9662(e,t,r){r.a(e,async function(e,i){try{r.d(t,{v:()=>d});var a=r(9748),o=r(6760),n=r(3024),s=r(4071),l=e([a,s]);[a,s]=l.then?(await l)():l;class d{constructor(e="./prompts.md"){this.filePath=o.resolve(e),this.watcher=null,this.lastModified=null,this.debounceTimeout=null}async initialize(){try{await n.promises.access(this.filePath)}catch{await this.createSampleFile()}}async createSampleFile(){let e=`# Task List
|
|
250
118
|
|
|
251
119
|
## Pending Tasks
|
|
252
120
|
|
|
@@ -265,40 +133,40 @@ Task format (same as TaskManager):
|
|
|
265
133
|
## Completed Tasks
|
|
266
134
|
|
|
267
135
|
## Failed Tasks
|
|
268
|
-
`;await
|
|
269
|
-
Original description: ${
|
|
270
|
-
`,{kind:"tool"}),(0,o.KH)(
|
|
271
|
-
`,{kind:"tool"}),(0,o.KH)(
|
|
272
|
-
`)}r()}catch(e){r(e)}})},3122(e,t,i){function r(e,t,i={}){let{required:s=!1,trim:o=!0,label:a=t,allowEmpty:n=!1}=i,l=e[t];if("string"!=typeof l){if(s)throw Error(`${a} required`);return}let d=o?l.trim():l;if(!d&&!n){if(s)throw Error(`${a} required`);return}return d}function s(e,t,i={}){let r,{required:o=!1,label:a=t,integer:n=!1}=i,l=e[t];if("number"==typeof l&&Number.isFinite(l))r=l;else if("string"==typeof l){let e=l.trim();if(e){let t=Number.parseFloat(e);Number.isFinite(t)&&(r=t)}}if(void 0===r){if(o)throw Error(`${a} required`);return}return n?Math.trunc(r):r}function o(e,t,i={}){let{required:r=!1,label:s=t}=i,a=e[t];if(null==a){if(r)throw Error(`${s} required`);return}if("boolean"==typeof a)return a;if("string"==typeof a){let e=a.trim().toLowerCase();if("true"===e||"1"===e||"yes"===e)return!0;if("false"===e||"0"===e||"no"===e)return!1}if("number"==typeof a)return 0!==a;if(r)throw Error(`${s} required`)}function a(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:e}}i.d(t,{Ao:()=>a,GE:()=>o,h_:()=>r,jV:()=>s})},7536(e,t,i){i.d(t,{Pc:()=>c,Ui:()=>p,WO:()=>d,ZU:()=>a,gm:()=>l});var r=i(1455),s=i(6760),o=i(3024);async function a(e,t={}){let i=(0,s.join)(e,".pithosai","custom-tools"),l=t.importTool;if(!(0,o.existsSync)(i))return[];let d=[];try{for(let e of(await (0,r.readdir)(i)).filter(e=>e.endsWith(".js")))try{let t=await n((0,s.join)(i,e),l);t&&d.push(t)}catch(t){console.warn(`Failed to load custom tool from ${e}:`,t.message)}}catch(e){console.warn("Failed to read custom tools directory:",e.message)}return d}async function n(e,t){try{let i,r=`file://${e}`,s=t?await t(r):await import(r),o=Object.keys(s).find(e=>e.startsWith("create")&&e.endsWith("Tool"));if(!o)throw Error(`No tool creation function found in ${e}`);let a=s[o];if("function"!=typeof a)throw Error(`${o} is not a function in ${e}`);let n=a();if(!n.name||!n.execute||"function"!=typeof n.execute)throw Error(`Invalid tool structure in ${e}`);return i=n.parameters,null!=i&&"object"==typeof i&&"object"===i.type||(n.parameters={type:"object",properties:null!=i&&"object"==typeof i&&null!=i.properties?i.properties:null==i||"object"!=typeof i||"type"in i?{}:i}),n}catch(t){return console.warn(`Error loading custom tool from ${e}:`,t.message),null}}async function l(e){let t=(0,s.join)(e,".pithosai","custom-tools");if(!(0,o.existsSync)(t))return[];let i=[];try{for(let e of(await (0,r.readdir)(t)).filter(e=>e.endsWith(".json")))try{let a=(0,s.join)(t,e),n=await (0,r.readFile)(a,"utf-8"),l=JSON.parse(n),d=e.replace(".json",".js"),c=(0,s.join)(t,d);(0,o.existsSync)(c)&&i.push({name:l.name,description:l.description||"No description",metadata:l,filePath:c})}catch(t){console.warn(`Failed to load metadata from ${e}:`,t.message)}}catch(e){console.warn("Failed to read custom tools metadata:",e.message)}return i}async function d(e,t){let r=t.endsWith("_tool")?t:`${t}_tool`,a=(0,s.join)(e,".pithosai","custom-tools"),n=(0,s.join)(a,`${r}.js`),l=(0,s.join)(a,`${r}.json`);try{let e=await Promise.resolve().then(i.t.bind(i,1943,19));return(0,o.existsSync)(n)&&await e.unlink(n),(0,o.existsSync)(l)&&await e.unlink(l),!0}catch(e){return console.warn(`Failed to remove custom tool ${t}:`,e.message),!1}}async function c(e,t,r){let a=t.endsWith("_tool")?t:`${t}_tool`,n=(0,s.join)(e,".pithosai","custom-tools"),l=(0,s.join)(n,`${a}.js`),d=(0,s.join)(n,`${a}.js.disabled`),c=(0,s.join)(n,`${a}.json`),u=(0,s.join)(n,`${a}.json.disabled`);try{let e=await Promise.resolve().then(i.t.bind(i,1943,19));return r?((0,o.existsSync)(d)&&await e.rename(d,l),(0,o.existsSync)(u)&&await e.rename(u,c)):((0,o.existsSync)(l)&&await e.rename(l,d),(0,o.existsSync)(c)&&await e.rename(c,u)),!0}catch(e){return console.warn(`Failed to ${r?"enable":"disable"} custom tool ${t}:`,e.message),!1}}async function u(e,t){let i=t.endsWith("_tool")?t:`${t}_tool`,r=(0,s.join)(e,".pithosai","custom-tools"),a=(0,s.join)(r,`${i}.js`);return(0,o.existsSync)(a)}async function p(e){let t=await l(e),i=[];for(let r of t){let t=await u(e,r.name);i.push({name:r.name,enabled:t,lastUsed:r.metadata.usageStats?.lastExecuted,usageCount:r.metadata.usageStats?.totalExecutions||0,successRate:r.metadata.usageStats?.successRate,avgExecutionTime:r.metadata.usageStats?.avgExecutionTime})}return i}},1305(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Df:()=>b,Md:()=>y,XN:()=>w,ZM:()=>v,jI:()=>k});var s=i(6760),o=i(3024),a=i(8161),n=i(4204),l=i(3122),d=i(4071),c=i(8362),u=e([n,c,d]);function p(e,t){let i=e?.roles?.[t];return i&&"object"==typeof i&&"string"==typeof i.email&&i.email.trim()&&"string"==typeof i.password?i:null}function h(e){let t=e.smtp?.host;if(!t||"string"!=typeof t||!t.trim())return null;let i=e.smtp?.port??587;return{host:t.trim(),port:Number(i)||587,secure:465===i}}function m(e){let t=e.imap,i=t?.host;if(!i||"string"!=typeof i||!i.trim())return null;let r=t?.port??993;return{host:i.trim(),port:Number(r)||993,user:e.email.trim(),password:e.password}}[n,c,d]=u.then?(await u)():u;let S=n.Type.Object({limit:n.Type.Optional(n.Type.Number({description:"Maximum number of emails to return (default 10).",minimum:1,maximum:50})),mailbox:n.Type.Optional(n.Type.String({description:"IMAP mailbox name (default INBOX)."}))}),T=n.Type.Object({to:n.Type.String({description:"Recipient email address(es), comma-separated."}),subject:n.Type.String({description:"Email subject."}),text:n.Type.Optional(n.Type.String({description:"Plain text body."})),html:n.Type.Optional(n.Type.String({description:"HTML body (optional)."})),attachments:n.Type.Optional(n.Type.Array(n.Type.Object({filename:n.Type.String({description:"Attachment filename (e.g. document.pdf)."}),filePath:n.Type.String({description:"Absolute or project-relative path to the file on disk. Use only filePath; inline base64 content is not supported."})}),{description:"Optional attachments. Each item must have filename and filePath only. Do not use inline base64 content; the file must exist on disk at filePath."}))});async function g(e,t){let r=m(e);if(!r)return{emails:[],error:"IMAP not configured for this role. Add roles.<role>.imap.host in .settings.json."};let a=await i.e("613").then(i.bind(i,2220)),n=a.default??a,l=(await i.e("236").then(i.bind(i,7351))).simpleParser,d=Math.min(50,Math.max(1,t.limit||10)),c=(t.mailbox||"INBOX").trim()||"INBOX",u="number"==typeof t.maxTextLength&&t.maxTextLength>0?t.maxTextLength:2e3,p="number"==typeof t.maxAttachmentInlineSize&&t.maxAttachmentInlineSize>=0?t.maxAttachmentInlineSize:2097152,h=t.attachmentsDir??(t.projectCwd?(0,s.join)(t.projectCwd,".pithosai","attachments"):void 0);return new Promise(e=>{let t=new n({user:r.user,password:r.password,host:r.host,port:r.port,tls:!0,tlsOptions:{rejectUnauthorized:!1}}),i=[],a=i=>{t.end(),e({emails:[],error:i?.message||String(i)})};t.once("error",a),t.once("ready",()=>{t.openBox(c,!1,(r,n)=>{if(r)return void a(r);let c=Math.min(n.messages.total,d);if(0===c){t.end(),e({emails:[]});return}let m=`${Math.max(1,n.messages.total-d+1)}:${n.messages.total}`,g=t.seq.fetch(m,{bodies:"",struct:!0}),f=0,w=!1,k=()=>{f>=c&&!w&&(w=!0,t.end(),e({emails:i.reverse()}))};g.on("message",e=>{e.on("body",e=>{l(e,(e,t)=>{if(e){f++,k();return}let r=t.text||t.textAsText||"",a=Array.isArray(t.attachments)?t.attachments.map((e,t)=>(function(e,t,i,r=0){let a=e.filename||e.contentType?.split("/")[0]||"attachment",n=e.contentType||"application/octet-stream",l=e.content,d=l?l.length:e.size??0;if(l&&d>102400&&i)try{(0,o.mkdirSync)(i,{recursive:!0});let e=`${r}_${(a.replace(/^.*[/\\]/,"").replace(/\0/g,"")||"attachment").replace(/[<>:"|?*\s]+/g,"_").slice(0,200)}`,t=(0,s.join)(i,e);return(0,o.writeFileSync)(t,l,{flag:"w"}),{filename:a,contentType:n,filePath:t,size:d}}catch{return{filename:a,contentType:n,size:d}}let c={filename:a,contentType:n,size:d};return l&&d>0&&d<=t&&(c.content=l.toString("base64")),c})(e,p,h,t)):[];i.push({from:t.from?.text||"",to:t.to?.text||"",subject:t.subject||"",date:t.date?new Date(t.date).toISOString():"",text:r.slice(0,u),...a.length>0?{attachments:a}:{}}),f++,k()})})}),g.once("error",a)})}),t.connect()})}async function f(e,t){let r,n=h(e);if(!n)return{success:!1,error:"SMTP not configured for this role. Add roles.<role>.smtp.host in .settings.json."};let l=(await i.e("220").then(i.bind(i,1663))).default.createTransport({host:n.host,port:n.port,secure:n.secure,auth:{user:e.email.trim(),pass:e.password}}),d=t.to.trim(),c=t.text?.trim(),u=t.html?.trim();if(!c&&!u)return{success:!1,error:"Either text or html body is required."};try{r=function(e,t){if(!Array.isArray(e))return[];for(let t of e){if(!t||"object"!=typeof t)continue;let e=void 0!==t.content&&null!==t.content&&String(t.content).length>0,i="string"==typeof t.filePath&&t.filePath.trim().length>0;if(e&&!i)throw Error("Attachments must use filePath only; inline base64 content is not supported. Save the file to disk and pass its path in filePath.")}let i=[];for(let r of e){if(!r||"string"!=typeof r.filename||"string"!=typeof r.filePath)continue;let e=r.filePath.trim();if(!e)continue;let n=r.filename.trim()||"attachment",{path:l}=function(e,t){let i=t||process.cwd(),r=(0,s.resolve)(i,e.trim());if(!(0,o.existsSync)(r))throw Error(`Attachment file not found: ${r}`);let n=(0,o.statSync)(r);if(!n.isFile())throw Error(`Attachment path is not a file: ${r}`);let l=(0,a.homedir)(),d=r.startsWith(process.cwd()),c=l&&r.startsWith(l);if(!d&&!c)throw Error(`Attachment path must be under project or home directory: ${r}`);if(n.size>0x1900000)throw Error(`Attachment file too large (${n.size} bytes, max 26214400): ${r}`);return{path:r,size:n.size}}(e,t);i.push({filename:n,content:(0,o.readFileSync)(l)})}return i}(t.attachments,t.projectCwd)}catch(e){return{success:!1,error:e?.message||String(e)}}try{let i=await l.sendMail({from:e.email.trim(),to:d,subject:t.subject.trim(),text:c||void 0,html:u||void 0,attachments:r.length>0?r:void 0});return{success:!0,messageId:i.messageId}}catch(e){return{success:!1,error:e?.message||String(e)}}}function w(e,t){let i=p(e,t);return i&&m(i)?{label:"Read Email",name:"read_email",description:"Read recent emails from the inbox for the current role. Uses IMAP config from .settings.json for this role.",parameters:S,execute:async(e,t)=>{let r=t&&"object"==typeof t?t:{},s=(0,l.jV)(r,"limit",{integer:!0}),o=(0,l.h_)(r,"mailbox"),a=await g(i,{limit:s??10,mailbox:o??"INBOX"});return(0,l.Ao)(a)}}:null}function k(e,t){let i=p(e,t);return i&&h(i)?{label:"Send Email",name:"send_email",description:"Send an email using the current role's SMTP account configured in .settings.json. Call this tool once per email; do not invoke it again for the same message after a successful result. For attachments, use only filePath (path to a file on disk); inline base64 content is not supported.",parameters:T,execute:async(e,t)=>{let r=t&&"object"==typeof t?t:{},s=(0,l.h_)(r,"to",{required:!0}),o=(0,l.h_)(r,"subject",{required:!0}),a=(0,l.h_)(r,"text"),n=(0,l.h_)(r,"html"),d=Array.isArray(r.attachments)?r.attachments:void 0;if(!s)throw Error("to required");if(!o)throw Error("subject required");let c=await f(i,{to:s,subject:o,text:a,html:n,attachments:d,projectCwd:process.cwd()});return(0,l.Ao)(c)}}:null}async function y(e,t,i={}){let r=p(e,t);return r?g(r,{limit:i.limit??20,mailbox:i.mailbox??"INBOX",maxTextLength:i.maxTextLength??5e4,maxAttachmentInlineSize:i.maxAttachmentInlineSize,projectCwd:i.projectCwd,attachmentsDir:i.attachmentsDir}):{emails:[],error:"No email config for role."}}async function v(e,t,i){let r=p(e,t);return r?f(r,i):{success:!1,error:"No email config for role."}}async function b(e,t,r,s={}){let o=p(e,t),a={close:()=>{}};if(!o)return a;let n=m(o);if(!n)return a;let l=s.lang??(0,c.a)(),u=(0,c.l)(l),h=await i.e("613").then(i.bind(i,2220)),g=h.default??h,f=!1,w=null,k=null,y=!1;return!function e(){f||(y=!1,(w=new g({user:n.user,password:n.password,host:n.host,port:n.port,tls:!0,tlsOptions:{rejectUnauthorized:!1},keepalive:!0})).once("error",e=>{if((0,d.vV)(u("heartbeat.imapError",{message:e?.message||e})),w)try{w.end()}catch(e){}}),w.once("end",()=>{w=null,f||y||(y=!0,(0,d.vV)(u("heartbeat.imapDisconnectedReconnect",{ms:String(5e3)})),setTimeout(()=>{e()},5e3))}),w.on("close",()=>{}),w.once("ready",()=>{f||w.openBox("INBOX",!1,e=>{if(e){if((0,d.vV)(u("heartbeat.imapOpenBoxError",{message:e?.message||e})),w)try{w.end()}catch(e){}return}f||(w.on("mail",e=>{Promise.resolve(r(e)).catch(e=>(0,d.vV)(u("heartbeat.onNewMailError",{message:e?.message||e})))}),k||(k=setInterval(()=>{if(!f&&w&&"authenticated"===w.state)try{"function"==typeof w._client?.send?w._client.send("NOOP"):"function"==typeof w._enqueue&&w._enqueue("NOOP",!0)}catch(e){}},174e4)))})}),w.connect())}(),{close(){if(f=!0,k&&(clearInterval(k),k=null),w){try{w.removeAllListeners("close"),w.end()}catch(e){}w=null}}}}r()}catch(e){r(e)}})},3772(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Z:()=>w,w:()=>f});var s=i(4204),o=i(4071),a=i(7420),n=i(8038),l=i(3122),d=i(178),c=e([d,s,n,a,o]);[d,s,n,a,o]=c.then?(await c)():c;let m=Math.floor(d.yg/2);function u(e,t=m,i=20,r=20){if("string"!=typeof e)return{text:"",truncated:!1};if(e.length<=t)return{text:e,truncated:!1};let s=e.split("\n");if(s.length<=i+r)return{text:e.slice(0,t)+"\n[Content truncated for request size limit.]",truncated:!0};let o=s.slice(0,i).join("\n"),a=s.slice(-r).join("\n"),n=s.length-i-r;return{text:o+"\n[... "+n+" lines omitted ...]\n"+a,truncated:!0}}let g=s.Type.Object({command:s.Type.String({description:"Executable name or path (e.g. 'node', 'npm', '/usr/bin/env')."}),args:s.Type.Optional(s.Type.Array(s.Type.String(),{description:"Arguments to pass to the command. Omit or empty for no arguments."})),timeoutMs:s.Type.Optional(s.Type.Number({description:"Timeout in milliseconds. Default 60000.",minimum:1e3})),cwd:s.Type.Optional(s.Type.String({description:"Working directory for the command. Omit for process cwd."})),input:s.Type.Optional(s.Type.String({description:"Stdin content to pipe to the command."})),env:s.Type.Optional(s.Type.Record(s.Type.String(),s.Type.String(),{description:"Extra environment variables (merged with process.env)."}))});function p(e){let t={timeoutMs:"number"==typeof e.timeoutMs&&e.timeoutMs>=1e3?e.timeoutMs:6e4};if(null!=e.cwd&&String(e.cwd).trim()&&(t.cwd=String(e.cwd).trim()),void 0!==e.input&&(t.input="string"==typeof e.input?e.input:String(e.input)),null!=e.env&&"object"==typeof e.env&&!Array.isArray(e.env))for(let[i,r]of(t.env={},Object.entries(e.env)))null!=i&&"string"==typeof r&&(t.env[i]=r);return t}function h(e){let t=u(e.stdout??""),i=u(e.stderr??""),r={ok:0===e.code,stdout:t.text,stderr:i.text,code:e.code,signal:e.signal??null,killed:e.killed};return t.truncated&&(r.stdoutTruncated=!0),i.truncated&&(r.stderrTruncated=!0),r}let f={name:"exec",label:"Exec",description:"Run a shell command with a timeout. Command runs immediately (not queued). Use for one-off commands. Provide executable and optional args, cwd, stdin, env.",parameters:g,execute:async(e,t,i,r)=>{let s=null!=t.command?String(t.command).trim():"";if(!s)return(0,l.Ao)({ok:!1,error:"command is required"});let n=Array.isArray(t.args)?t.args.map(e=>String(e)):[],d=[s,...n],c=p(t);(0,o.JX)(JSON.stringify({tool:"exec",toolCallId:e,command:d,timeoutMs:c.timeoutMs}));try{let e=await (0,a._)(d,c),t=h(e);return e.stderr?.trim()&&(0,o.JX)(`exec stderr: ${e.stderr.trim()}`),(0,l.Ao)(t)}catch(e){return(0,o.CN)(`exec failed: ${s} ${n.join(" ")}: ${String(e)}`),(0,l.Ao)({ok:!1,error:String(e?.message??e),stdout:"",stderr:""})}}},w={name:"queue_exec",label:"Queue Exec",description:"Run a shell command through the main command queue. Same parameters as exec, but execution is serialized with other queued commands. Prefer this when running multiple commands or when the agent uses other process tools.",parameters:g,execute:async(e,t,i,r)=>{let s=null!=t.command?String(t.command).trim():"";if(!s)return(0,l.Ao)({ok:!1,error:"command is required"});let d=Array.isArray(t.args)?t.args.map(e=>String(e)):[],c=[s,...d],u=p(t);(0,o.JX)(JSON.stringify({tool:"queue_exec",toolCallId:e,command:c,timeoutMs:u.timeoutMs}));try{let e=await (0,n.Wf)(()=>(0,a._)(c,u)),t=h(e);return e.stderr?.trim()&&(0,o.JX)(`queue_exec stderr: ${e.stderr.trim()}`),(0,l.Ao)(t)}catch(e){return(0,o.CN)(`queue_exec failed: ${s} ${d.join(" ")}: ${String(e)}`),(0,l.Ao)({ok:!1,error:String(e?.message??e),stdout:"",stderr:""})}}};r()}catch(e){r(e)}})},9243(e,t,i){i.a(e,async function(e,r){try{i.d(t,{G:()=>w});var s=i(3513),o=i(3772),a=i(4508),n=i(1942),l=i(1305),d=i(3591),c=i(3124),u=i(68),p=i(1549),h=i(7619),m=i(7536),g=e([s,p,h,o,a,n,c,l,u,d]);function f(e,t){return null==e||e.has(t.toLowerCase())}async function w(e,t,i,r={}){let g=r.allowNames??null,k=e?.tools?{config:{tools:e.tools}}:{},y=[];if(f(g,"list_files")&&y.push(s.i),f(g,"read_pdf")&&y.push(p.Hw),f(g,"playwright_view_markdown")&&y.push(h.Ef),f(g,"exec")&&y.push(o.w),f(g,"queue_exec")&&y.push(o.Z),i){let e=null==g||g.has("customer_tools")||g.has("custom_tools");try{let t=await (0,m.ZU)(i);if(e)y.push(...t);else for(let e of t){let t=String(e.name??"").toLowerCase();g?.has(t)&&y.push(e)}}catch(e){console.warn(`Failed to load custom tools: ${e.message}`)}}let v=(0,a.dW)(k);v&&f(g,"web_fetch")&&y.push(v);let b=(0,n.t)(k);b&&f(g,"web_search")&&y.push(b);let S=(0,c.Q)(k);S&&f(g,"proxy_downloader")&&y.push(S);let T=t?(0,l.XN)(e,t):null;T&&f(g,"read_email")&&y.push(T);let C=t?(0,l.jI)(e,t):null;C&&f(g,"send_email")&&y.push(C);let E=(0,u.Ei)(k);E&&f(g,"html_to_markdown")&&y.push(E);let x=(0,u.Gz)(k);x&&f(g,"markdown_to_html")&&y.push(x);let I=(0,d.H)();I&&f(g,"wechat_publish_article")&&y.push(I);let A=(0,d.f)();return A&&f(g,"wechat_generate_cover_image")&&y.push(A),y}[s,p,h,o,a,n,c,l,u,d]=g.then?(await g)():g,r()}catch(e){r(e)}})},3513(e,t,i){i.a(e,async function(e,r){try{i.d(t,{i:()=>h});var s=i(1455),o=i(6760),a=i(4204),n=i(4071),l=i(7648),d=i(8362),c=i(4768),u=i(3122),p=e([a,n,c,d,l]);[a,n,c,d,l]=p.then?(await p)():p;let h={name:"list_files",label:"List Files",description:"List files and directories in a directory. Use to explore the project. Default is the current project directory.",parameters:a.Type.Object({path:a.Type.Optional(a.Type.String({description:"Directory path to list (relative to project or absolute). Omit for current directory."}))}),execute:async(e,t,i,r)=>{let a=t.path&&(0,o.resolve)(process.cwd(),t.path)||process.cwd(),p=await (0,s.readdir)(a,{withFileTypes:!0}),h=p.map(e=>e.isDirectory()?`${e.name}/`:e.name),m={path:a,count:p.length,entries:h};(0,n.JX)(JSON.stringify({tool:"list_files",toolCallId:e,params:t,payload:m}));let g=await (0,c.s)(process.cwd()),f=g?.lang??(0,d.a)(),w=(0,d.l)(f);return(0,l.Uz)(w("tools.listFiles.result",{path:a,count:m.count})),(0,u.Ao)(m)}};r()}catch(e){r(e)}})},68(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Ei:()=>c,Gz:()=>u,LZ:()=>p});var s=i(4204),o=i(3122),a=i(8703),n=e([a,s]);function l(e,t={}){if(!e||"string"!=typeof e)return"";let{forWechat:i,...r}=t;if(i)return function(e,t={}){let i=[],{Renderer:r}=a.marked,s=new r;s.paragraph=function(e){let t=this.parser.parseInline(e.tokens);return`<p style="${h}">${t}</p>
|
|
273
|
-
`},
|
|
274
|
-
`},
|
|
136
|
+
`;await n.promises.writeFile(this.filePath,e,"utf-8"),(0,s.KH)(`📄 Created sample task file: ${this.filePath}`)}async watch(e){await this.initialize(),(0,s.KH)(`👀 Watching task file: ${this.filePath}`),this.watcher=a.default.watch(this.filePath,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:1e3,pollInterval:100}}),this.watcher.on("change",t=>{(0,s.MD)(`📝 Task file changed: ${t}`),this.debounceTimeout&&clearTimeout(this.debounceTimeout),this.debounceTimeout=setTimeout(async()=>{try{let r=(await n.promises.stat(t)).mtimeMs;this.lastModified!==r&&(this.lastModified=r,await e(t))}catch(e){(0,s.vV)("Failed to read task file stats:",e)}},1500)}),this.watcher.on("error",e=>{(0,s.vV)("Task file watcher error:",e)})}unwatch(){this.watcher&&this.watcher.close()}}i()}catch(e){i(e)}})},5534(e,t,r){r.a(e,async function(e,i){try{r.d(t,{j:()=>u});var a=r(3024),o=r(6760),n=r(2641),s=r(4071),l=r(4132),d=r(8359),c=e([n,d,l,s]);[n,d,l,s]=c.then?(await c)():c;class u{constructor(e="./prompts.md"){this.filePath=o.resolve(e),this._cachedContent=null,this._tasksCache=null}async withFileLock(e){let t;try{return t=await n.default.lock(this.filePath,{retries:5,retryDelay:100}),await e()}catch(e){throw(0,s.vV)("Task file lock failed:",e),e}finally{if(t)try{await t()}catch(e){(0,s.vV)("Releasing task file lock failed:",e)}}}normalizeField(e,t){if(!e)return"";let r=String(e).trim();if(r=r.replace(/^[-*]\s+/,""),t){let e=RegExp(String.raw`^\**${t}\**\s*[:=]\s*`,"i");r=r.replace(e,"")}return r.trim()}parseContent(e){let t=e.split("\n"),r=[],i=null,a=null,o=e=>{let t=e.substring(3).toLowerCase();return t.includes("待处理")||t.includes("pending")?"pending":t.includes("处理中")||t.includes("processing")?"processing":t.includes("完成")||t.includes("completed")?"completed":t.includes("失败")||t.includes("failed")?"failed":null};for(let e=0;e<t.length;e++){let n=t[e],s=n.trim();if(s.startsWith("## ")){a=o(s);continue}if(i&&/^[-*]\s*end$/i.test(s)){r.push(i),i=null;continue}if(s.startsWith("### [")){let t=s.match(/### \[(\w+)\]\s*(.+)/);t&&(i={id:null,status:t[1],title:t[2],description:"",createdAt:new Date().toISOString(),section:a,lineNumber:e,rawLine:s,metaLines:[]})}else i&&s.length>0&&i.metaLines.push(n)}return r.map(e=>{let t,r,i=e.metaLines||[],a=i[0]||"",o=i[1]||"",n=i[2]||"",s=this.normalizeField(a,"id")||e.id,l=o.replace(/^[-*]\s+/,"").trim(),d=/^\**model\**\s*[:=]/i.test(l),c="deepSeekChat";d?(c=this.normalizeField(o,"model"),t=n,r=i.slice(3)):(t=o,r=i.slice(2));let u=this.normalizeField(t,"title")||e.title||"",p=r.join("\n"),m=this.normalizeField(p,"description"),h=i.find(e=>/^\s*[-*]\s*\*\*createdAt\*\*/.test(e.trim())),g=h?this.normalizeField(h,"createdAt"):e.createdAt,{metaLines:f,...k}=e;return{...k,id:s,model:c,title:u,description:m,createdAt:g}})}async parseTasks(){return this.withFileLock(async()=>{let e=await a.promises.readFile(this.filePath,"utf-8");if(e===this._cachedContent&&null!=this._tasksCache)return this._tasksCache;let t=this.parseContent(e);return this._cachedContent=e,this._tasksCache=t,t})}async getPendingTasks(){return(await this.parseTasks()).filter(e=>"pending"===e.status)}async markTaskAsProcessing(e){return this.updateTaskStatus(e,"processing")}async markTaskAsCompleted(e,t){return this.updateTaskStatus(e,"completed",t)}async markTaskAsFailed(e,t){return this.updateTaskStatus(e,"failed",{error:t})}async updateTaskStatus(e,t,r={}){let i;await this.withFileLock(async()=>{let o,n,l=await a.promises.readFile(this.filePath,"utf-8"),d=l.split("\n"),c=!1,u="completed"===t||"failed"===t?(o=this.parseContent(l).find(t=>t.id===e),n=o?.createdAt??new Date().toISOString(),{...r,createdAt:n}):r;for(let r=0;r<d.length;r++)if(this.normalizeField(d[r],"id")===e){c=!0;let e=r;for(;e>=0&&!d[e].startsWith("### [");)e--;e>=0&&(d[e]=d[e].replace(/### \[(\w+)\]/,`### [${t}]`),"completed"===t?await this.moveTaskToSection(d,e,"completed",u):"processing"===t?await this.moveTaskToSection(d,e,"processing"):"failed"===t&&await this.moveTaskToSection(d,e,"failed",u));break}if(!c)throw Error(`Task ${e} not found`);let p=d.join("\n");await a.promises.writeFile(this.filePath,p,"utf-8"),this._cachedContent=null,this._tasksCache=null,(0,s.fH)(`📝 Updated task status: ${e} -> ${t}`),i=this.parseContent(p).find(t=>t.id===e)});try{let e=await (0,d.Lf)();if(!i)return;await (0,d.$R)(e,{id:i.id,title:i.title,description:i.description,model:i.model,status:i.status??t,createdAt:i.createdAt,updatedAt:new Date().toISOString()})}catch(t){(0,s.vV)(`Failed to upsert task ${e} into sqlite:`,t)}}async moveTaskToSection(e,t,r,i={}){let a=t+1;for(;a<e.length&&!e[a].startsWith("### [")&&!e[a].startsWith("## ");)a++;let o=e.slice(t,a);e.splice(t,a-t);let n=e.findIndex(e=>{if(!e.startsWith("## "))return!1;let t=e.toLowerCase();return"completed"===r?t.includes("完成")||t.includes("completed"):"processing"===r?t.includes("处理中")||t.includes("processing"):"failed"===r&&(t.includes("失败")||t.includes("failed"))});-1===n&&(e.push("","completed"===r?"## Completed Tasks":"failed"===r?"## Failed Tasks":"## Processing Tasks",""),n=e.length-1);let s=n+1;if("completed"===r||"failed"===r)for(;s<e.length&&!e[s].startsWith("## ")&&""===e[s].trim();)s++;else for(;s<e.length&&!e[s].startsWith("## ");)s++;if("completed"===r?o.push("","- **result**: SUCCESS"):"failed"===r&&o.push("","- **result**: FAILURE"),i.completedAt&&o.push("",`- **completedAt**: ${i.completedAt}`),i.createdAt&&o.push("",`- **createdAt**: ${i.createdAt}`),void 0!==i.error&&null!==i.error){let e="object"==typeof i.error&&null!==i.error&&"message"in i.error?String(i.error.message):String(i.error);o.push("","- **error**:"," "+e.replace(/\n/g,"\n "))}let l=function(e){let t=[],r=!1;for(let i of e)""===i.trim()?(r||t.push(""),r=!0):(t.push(i),r=!1);return t}(o);return e.splice(s,0,...l,""),e}async addTask(e){let{title:t,description:r,model:i}=e??{};return this.withFileLock(async()=>{let e=(await a.promises.readFile(this.filePath,"utf-8")).split("\n"),o=`task-${(0,l.v4)().slice(0,8)}`,n=e.findIndex(e=>{if(!e.startsWith("##"))return!1;let t=e.toLowerCase();return t.includes("待处理")||t.includes("pending")});-1===n&&(e.push("","## Pending Tasks",""),n=e.length-1);let d=n+1;for(;d<e.length&&!e[d].startsWith("## ");)d++;let c=[`- **id**: ${o}`];null!=i&&""!==String(i).trim()&&c.push(`- **model**: ${String(i).trim()}`),c.push(`- **title**: ${t}`);let u=String(r||"").trim();u&&(c.push("- **description**:"),c.push(...u.split("\n"))),c.push("- end");let p=["",`### [pending] ${t}`,...c];return e.splice(d,0,...p),await a.promises.writeFile(this.filePath,e.join("\n"),"utf-8"),this._cachedContent=null,this._tasksCache=null,(0,s.fH)(`📝 Added new task: ${t} (${o})`),o})}}i()}catch(e){i(e)}})},1773(e,t,r){r.a(e,async function(e,i){try{r.d(t,{c:()=>n});var a=r(4071),o=e([a]);a=(o.then?(await o)():o)[0];class n{constructor(){this.handlers=new Map,this.setupDefaultHandlers()}setupDefaultHandlers(){this.handlers.set("default",this.defaultHandler.bind(this))}async process(e){let t=e?.title??"(untitled)";(0,a.fH)(`⚙️ Processing task: ${t}`),(0,a.MD)("Task details:",e);let r=this.getHandler(e);return await r(e)}async defaultHandler(e){let t=e?.title??"(untitled)",r=e?.description??"";return{success:!0,message:`Task "${t}" processed successfully.`,timestamp:new Date().toISOString(),output:`Processing result for task "${t}".
|
|
137
|
+
Original description: ${r}`}}getHandler(e){return this.handlers.get("default")}registerHandler(e,t){this.handlers.set(e,t)}}i()}catch(e){i(e)}})},7648(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Uz:()=>d,cb:()=>c,we:()=>l});var a=r(6698),o=r(4071),n=e([o]);o=(n.then?(await n)():n)[0];let u=new a.AsyncLocalStorage;function s(){return u.getStore()}function l(e,t){return u.run(e,t)}function d(e){let t=s(),r=String(e??"");if(t?.routeToolUserLogViaSink&&t.outputSink){t.outputSink.write(`${r}
|
|
138
|
+
`,{kind:"tool"}),(0,o.KH)(r);return}(0,o.fH)(r)}function c(e,t){let r=String(e??""),i=s(),a=null!=t&&"object"==typeof t&&"function"==typeof t.write?t:i?.routeToolUserLogViaSink&&i.outputSink?i.outputSink:null;if(a){a.write(`${r}
|
|
139
|
+
`,{kind:"tool"}),(0,o.KH)(r);return}process.stdout.write(`${r}
|
|
140
|
+
`)}i()}catch(e){i(e)}})},3122(e,t,r){function i(e,t,r={}){let{required:a=!1,trim:o=!0,label:n=t,allowEmpty:s=!1}=r,l=e[t];if("string"!=typeof l){if(a)throw Error(`${n} required`);return}let d=o?l.trim():l;if(!d&&!s){if(a)throw Error(`${n} required`);return}return d}function a(e,t,r={}){let i,{required:o=!1,label:n=t,integer:s=!1}=r,l=e[t];if("number"==typeof l&&Number.isFinite(l))i=l;else if("string"==typeof l){let e=l.trim();if(e){let t=Number.parseFloat(e);Number.isFinite(t)&&(i=t)}}if(void 0===i){if(o)throw Error(`${n} required`);return}return s?Math.trunc(i):i}function o(e,t,r={}){let{required:i=!1,label:a=t}=r,n=e[t];if(null==n){if(i)throw Error(`${a} required`);return}if("boolean"==typeof n)return n;if("string"==typeof n){let e=n.trim().toLowerCase();if("true"===e||"1"===e||"yes"===e)return!0;if("false"===e||"0"===e||"no"===e)return!1}if("number"==typeof n)return 0!==n;if(i)throw Error(`${a} required`)}function n(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],details:e}}r.d(t,{Ao:()=>n,GE:()=>o,h_:()=>i,jV:()=>a})},7536(e,t,r){r.d(t,{Pc:()=>c,Ui:()=>p,WO:()=>d,ZU:()=>n,gm:()=>l});var i=r(1455),a=r(6760),o=r(3024);async function n(e,t={}){let r=(0,a.join)(e,".pithosai","custom-tools"),l=t.importTool;if(!(0,o.existsSync)(r))return[];let d=[];try{for(let e of(await (0,i.readdir)(r)).filter(e=>e.endsWith(".js")))try{let t=await s((0,a.join)(r,e),l);t&&d.push(t)}catch(t){console.warn(`Failed to load custom tool from ${e}:`,t.message)}}catch(e){console.warn("Failed to read custom tools directory:",e.message)}return d}async function s(e,t){try{let r,i=`file://${e}`,a=t?await t(i):await import(i),o=Object.keys(a).find(e=>e.startsWith("create")&&e.endsWith("Tool"));if(!o)throw Error(`No tool creation function found in ${e}`);let n=a[o];if("function"!=typeof n)throw Error(`${o} is not a function in ${e}`);let s=n();if(!s.name||!s.execute||"function"!=typeof s.execute)throw Error(`Invalid tool structure in ${e}`);return r=s.parameters,null!=r&&"object"==typeof r&&"object"===r.type||(s.parameters={type:"object",properties:null!=r&&"object"==typeof r&&null!=r.properties?r.properties:null==r||"object"!=typeof r||"type"in r?{}:r}),s}catch(t){return console.warn(`Error loading custom tool from ${e}:`,t.message),null}}async function l(e){let t=(0,a.join)(e,".pithosai","custom-tools");if(!(0,o.existsSync)(t))return[];let r=[];try{for(let e of(await (0,i.readdir)(t)).filter(e=>e.endsWith(".json")))try{let n=(0,a.join)(t,e),s=await (0,i.readFile)(n,"utf-8"),l=JSON.parse(s),d=e.replace(".json",".js"),c=(0,a.join)(t,d);(0,o.existsSync)(c)&&r.push({name:l.name,description:l.description||"No description",metadata:l,filePath:c})}catch(t){console.warn(`Failed to load metadata from ${e}:`,t.message)}}catch(e){console.warn("Failed to read custom tools metadata:",e.message)}return r}async function d(e,t){let i=t.endsWith("_tool")?t:`${t}_tool`,n=(0,a.join)(e,".pithosai","custom-tools"),s=(0,a.join)(n,`${i}.js`),l=(0,a.join)(n,`${i}.json`);try{let e=await Promise.resolve().then(r.t.bind(r,1943,19));return(0,o.existsSync)(s)&&await e.unlink(s),(0,o.existsSync)(l)&&await e.unlink(l),!0}catch(e){return console.warn(`Failed to remove custom tool ${t}:`,e.message),!1}}async function c(e,t,i){let n=t.endsWith("_tool")?t:`${t}_tool`,s=(0,a.join)(e,".pithosai","custom-tools"),l=(0,a.join)(s,`${n}.js`),d=(0,a.join)(s,`${n}.js.disabled`),c=(0,a.join)(s,`${n}.json`),u=(0,a.join)(s,`${n}.json.disabled`);try{let e=await Promise.resolve().then(r.t.bind(r,1943,19));return i?((0,o.existsSync)(d)&&await e.rename(d,l),(0,o.existsSync)(u)&&await e.rename(u,c)):((0,o.existsSync)(l)&&await e.rename(l,d),(0,o.existsSync)(c)&&await e.rename(c,u)),!0}catch(e){return console.warn(`Failed to ${i?"enable":"disable"} custom tool ${t}:`,e.message),!1}}async function u(e,t){let r=t.endsWith("_tool")?t:`${t}_tool`,i=(0,a.join)(e,".pithosai","custom-tools"),n=(0,a.join)(i,`${r}.js`);return(0,o.existsSync)(n)}async function p(e){let t=await l(e),r=[];for(let i of t){let t=await u(e,i.name);r.push({name:i.name,enabled:t,lastUsed:i.metadata.usageStats?.lastExecuted,usageCount:i.metadata.usageStats?.totalExecutions||0,successRate:i.metadata.usageStats?.successRate,avgExecutionTime:i.metadata.usageStats?.avgExecutionTime})}return r}},1305(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Df:()=>b,Md:()=>v,XN:()=>k,ZM:()=>y,jI:()=>w});var a=r(6760),o=r(3024),n=r(8161),s=r(4204),l=r(3122),d=r(4071),c=r(8362),u=e([s,c,d]);function p(e,t){let r=e?.roles?.[t];return r&&"object"==typeof r&&"string"==typeof r.email&&r.email.trim()&&"string"==typeof r.password?r:null}function m(e){let t=e.smtp?.host;if(!t||"string"!=typeof t||!t.trim())return null;let r=e.smtp?.port??587;return{host:t.trim(),port:Number(r)||587,secure:465===r}}function h(e){let t=e.imap,r=t?.host;if(!r||"string"!=typeof r||!r.trim())return null;let i=t?.port??993;return{host:r.trim(),port:Number(i)||993,user:e.email.trim(),password:e.password}}[s,c,d]=u.then?(await u)():u;let S=s.Type.Object({limit:s.Type.Optional(s.Type.Number({description:"Maximum number of emails to return (default 10).",minimum:1,maximum:50})),mailbox:s.Type.Optional(s.Type.String({description:"IMAP mailbox name (default INBOX)."}))}),T=s.Type.Object({to:s.Type.String({description:"Recipient email address(es), comma-separated."}),subject:s.Type.String({description:"Email subject."}),text:s.Type.Optional(s.Type.String({description:"Plain text body."})),html:s.Type.Optional(s.Type.String({description:"HTML body (optional)."})),attachments:s.Type.Optional(s.Type.Array(s.Type.Object({filename:s.Type.String({description:"Attachment filename (e.g. document.pdf)."}),filePath:s.Type.String({description:"Absolute or project-relative path to the file on disk. Use only filePath; inline base64 content is not supported."})}),{description:"Optional attachments. Each item must have filename and filePath only. Do not use inline base64 content; the file must exist on disk at filePath."}))});async function g(e,t){let i=h(e);if(!i)return{emails:[],error:"IMAP not configured for this role. Add roles.<role>.imap.host in .settings.json."};let n=await r.e("613").then(r.bind(r,2220)),s=n.default??n,l=(await r.e("236").then(r.bind(r,7351))).simpleParser,d=Math.min(50,Math.max(1,t.limit||10)),c=(t.mailbox||"INBOX").trim()||"INBOX",u="number"==typeof t.maxTextLength&&t.maxTextLength>0?t.maxTextLength:2e3,p="number"==typeof t.maxAttachmentInlineSize&&t.maxAttachmentInlineSize>=0?t.maxAttachmentInlineSize:2097152,m=t.attachmentsDir??(t.projectCwd?(0,a.join)(t.projectCwd,".pithosai","attachments"):void 0);return new Promise(e=>{let t=new s({user:i.user,password:i.password,host:i.host,port:i.port,tls:!0,tlsOptions:{rejectUnauthorized:!1}}),r=[],n=r=>{t.end(),e({emails:[],error:r?.message||String(r)})};t.once("error",n),t.once("ready",()=>{t.openBox(c,!1,(i,s)=>{if(i)return void n(i);let c=Math.min(s.messages.total,d);if(0===c){t.end(),e({emails:[]});return}let h=`${Math.max(1,s.messages.total-d+1)}:${s.messages.total}`,g=t.seq.fetch(h,{bodies:"",struct:!0}),f=0,k=!1,w=()=>{f>=c&&!k&&(k=!0,t.end(),e({emails:r.reverse()}))};g.on("message",e=>{e.on("body",e=>{l(e,(e,t)=>{if(e){f++,w();return}let i=t.text||t.textAsText||"",n=Array.isArray(t.attachments)?t.attachments.map((e,t)=>(function(e,t,r,i=0){let n=e.filename||e.contentType?.split("/")[0]||"attachment",s=e.contentType||"application/octet-stream",l=e.content,d=l?l.length:e.size??0;if(l&&d>102400&&r)try{(0,o.mkdirSync)(r,{recursive:!0});let e=`${i}_${(n.replace(/^.*[/\\]/,"").replace(/\0/g,"")||"attachment").replace(/[<>:"|?*\s]+/g,"_").slice(0,200)}`,t=(0,a.join)(r,e);return(0,o.writeFileSync)(t,l,{flag:"w"}),{filename:n,contentType:s,filePath:t,size:d}}catch{return{filename:n,contentType:s,size:d}}let c={filename:n,contentType:s,size:d};return l&&d>0&&d<=t&&(c.content=l.toString("base64")),c})(e,p,m,t)):[];r.push({from:t.from?.text||"",to:t.to?.text||"",subject:t.subject||"",date:t.date?new Date(t.date).toISOString():"",text:i.slice(0,u),...n.length>0?{attachments:n}:{}}),f++,w()})})}),g.once("error",n)})}),t.connect()})}async function f(e,t){let i,s=m(e);if(!s)return{success:!1,error:"SMTP not configured for this role. Add roles.<role>.smtp.host in .settings.json."};let l=(await r.e("220").then(r.bind(r,1663))).default.createTransport({host:s.host,port:s.port,secure:s.secure,auth:{user:e.email.trim(),pass:e.password}}),d=t.to.trim(),c=t.text?.trim(),u=t.html?.trim();if(!c&&!u)return{success:!1,error:"Either text or html body is required."};try{i=function(e,t){if(!Array.isArray(e))return[];for(let t of e){if(!t||"object"!=typeof t)continue;let e=void 0!==t.content&&null!==t.content&&String(t.content).length>0,r="string"==typeof t.filePath&&t.filePath.trim().length>0;if(e&&!r)throw Error("Attachments must use filePath only; inline base64 content is not supported. Save the file to disk and pass its path in filePath.")}let r=[];for(let i of e){if(!i||"string"!=typeof i.filename||"string"!=typeof i.filePath)continue;let e=i.filePath.trim();if(!e)continue;let s=i.filename.trim()||"attachment",{path:l}=function(e,t){let r=t||process.cwd(),i=(0,a.resolve)(r,e.trim());if(!(0,o.existsSync)(i))throw Error(`Attachment file not found: ${i}`);let s=(0,o.statSync)(i);if(!s.isFile())throw Error(`Attachment path is not a file: ${i}`);let l=(0,n.homedir)(),d=i.startsWith(process.cwd()),c=l&&i.startsWith(l);if(!d&&!c)throw Error(`Attachment path must be under project or home directory: ${i}`);if(s.size>0x1900000)throw Error(`Attachment file too large (${s.size} bytes, max 26214400): ${i}`);return{path:i,size:s.size}}(e,t);r.push({filename:s,content:(0,o.readFileSync)(l)})}return r}(t.attachments,t.projectCwd)}catch(e){return{success:!1,error:e?.message||String(e)}}try{let r=await l.sendMail({from:e.email.trim(),to:d,subject:t.subject.trim(),text:c||void 0,html:u||void 0,attachments:i.length>0?i:void 0});return{success:!0,messageId:r.messageId}}catch(e){return{success:!1,error:e?.message||String(e)}}}function k(e,t){let r=p(e,t);return r&&h(r)?{label:"Read Email",name:"read_email",description:"Read recent emails from the inbox for the current role. Uses IMAP config from .settings.json for this role.",parameters:S,execute:async(e,t)=>{let i=t&&"object"==typeof t?t:{},a=(0,l.jV)(i,"limit",{integer:!0}),o=(0,l.h_)(i,"mailbox"),n=await g(r,{limit:a??10,mailbox:o??"INBOX"});return(0,l.Ao)(n)}}:null}function w(e,t){let r=p(e,t);return r&&m(r)?{label:"Send Email",name:"send_email",description:"Send an email using the current role's SMTP account configured in .settings.json. Call this tool once per email; do not invoke it again for the same message after a successful result. For attachments, use only filePath (path to a file on disk); inline base64 content is not supported.",parameters:T,execute:async(e,t)=>{let i=t&&"object"==typeof t?t:{},a=(0,l.h_)(i,"to",{required:!0}),o=(0,l.h_)(i,"subject",{required:!0}),n=(0,l.h_)(i,"text"),s=(0,l.h_)(i,"html"),d=Array.isArray(i.attachments)?i.attachments:void 0;if(!a)throw Error("to required");if(!o)throw Error("subject required");let c=await f(r,{to:a,subject:o,text:n,html:s,attachments:d,projectCwd:process.cwd()});return(0,l.Ao)(c)}}:null}async function v(e,t,r={}){let i=p(e,t);return i?g(i,{limit:r.limit??20,mailbox:r.mailbox??"INBOX",maxTextLength:r.maxTextLength??5e4,maxAttachmentInlineSize:r.maxAttachmentInlineSize,projectCwd:r.projectCwd,attachmentsDir:r.attachmentsDir}):{emails:[],error:"No email config for role."}}async function y(e,t,r){let i=p(e,t);return i?f(i,r):{success:!1,error:"No email config for role."}}async function b(e,t,i,a={}){let o=p(e,t),n={close:()=>{}};if(!o)return n;let s=h(o);if(!s)return n;let l=a.lang??(0,c.a)(),u=(0,c.l)(l),m=await r.e("613").then(r.bind(r,2220)),g=m.default??m,f=!1,k=null,w=null,v=!1;return!function e(){f||(v=!1,(k=new g({user:s.user,password:s.password,host:s.host,port:s.port,tls:!0,tlsOptions:{rejectUnauthorized:!1},keepalive:!0})).once("error",e=>{if((0,d.vV)(u("heartbeat.imapError",{message:e?.message||e})),k)try{k.end()}catch(e){}}),k.once("end",()=>{k=null,f||v||(v=!0,(0,d.vV)(u("heartbeat.imapDisconnectedReconnect",{ms:String(5e3)})),setTimeout(()=>{e()},5e3))}),k.on("close",()=>{}),k.once("ready",()=>{f||k.openBox("INBOX",!1,e=>{if(e){if((0,d.vV)(u("heartbeat.imapOpenBoxError",{message:e?.message||e})),k)try{k.end()}catch(e){}return}f||(k.on("mail",e=>{Promise.resolve(i(e)).catch(e=>(0,d.vV)(u("heartbeat.onNewMailError",{message:e?.message||e})))}),w||(w=setInterval(()=>{if(!f&&k&&"authenticated"===k.state)try{"function"==typeof k._client?.send?k._client.send("NOOP"):"function"==typeof k._enqueue&&k._enqueue("NOOP",!0)}catch(e){}},174e4)))})}),k.connect())}(),{close(){if(f=!0,w&&(clearInterval(w),w=null),k){try{k.removeAllListeners("close"),k.end()}catch(e){}k=null}}}}i()}catch(e){i(e)}})},3772(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Z:()=>k,w:()=>f});var a=r(4204),o=r(4071),n=r(7420),s=r(8038),l=r(3122),d=r(178),c=e([d,a,s,n,o]);[d,a,s,n,o]=c.then?(await c)():c;let h=Math.floor(d.yg/2);function u(e,t=h,r=20,i=20){if("string"!=typeof e)return{text:"",truncated:!1};if(e.length<=t)return{text:e,truncated:!1};let a=e.split("\n");if(a.length<=r+i)return{text:e.slice(0,t)+"\n[Content truncated for request size limit.]",truncated:!0};let o=a.slice(0,r).join("\n"),n=a.slice(-i).join("\n"),s=a.length-r-i;return{text:o+"\n[... "+s+" lines omitted ...]\n"+n,truncated:!0}}let g=a.Type.Object({command:a.Type.String({description:"Executable name or path (e.g. 'node', 'npm', '/usr/bin/env')."}),args:a.Type.Optional(a.Type.Array(a.Type.String(),{description:"Arguments to pass to the command. Omit or empty for no arguments."})),timeoutMs:a.Type.Optional(a.Type.Number({description:"Timeout in milliseconds. Default 60000.",minimum:1e3})),cwd:a.Type.Optional(a.Type.String({description:"Working directory for the command. Omit for process cwd."})),input:a.Type.Optional(a.Type.String({description:"Stdin content to pipe to the command."})),env:a.Type.Optional(a.Type.Record(a.Type.String(),a.Type.String(),{description:"Extra environment variables (merged with process.env)."}))});function p(e){let t={timeoutMs:"number"==typeof e.timeoutMs&&e.timeoutMs>=1e3?e.timeoutMs:6e4};if(null!=e.cwd&&String(e.cwd).trim()&&(t.cwd=String(e.cwd).trim()),void 0!==e.input&&(t.input="string"==typeof e.input?e.input:String(e.input)),null!=e.env&&"object"==typeof e.env&&!Array.isArray(e.env))for(let[r,i]of(t.env={},Object.entries(e.env)))null!=r&&"string"==typeof i&&(t.env[r]=i);return t}function m(e){let t=u(e.stdout??""),r=u(e.stderr??""),i={ok:0===e.code,stdout:t.text,stderr:r.text,code:e.code,signal:e.signal??null,killed:e.killed};return t.truncated&&(i.stdoutTruncated=!0),r.truncated&&(i.stderrTruncated=!0),i}let f={name:"exec",label:"Exec",description:"Run a shell command with a timeout. Command runs immediately (not queued). Use for one-off commands. Provide executable and optional args, cwd, stdin, env.",parameters:g,execute:async(e,t,r,i)=>{let a=null!=t.command?String(t.command).trim():"";if(!a)return(0,l.Ao)({ok:!1,error:"command is required"});let s=Array.isArray(t.args)?t.args.map(e=>String(e)):[],d=[a,...s],c=p(t);(0,o.JX)(JSON.stringify({tool:"exec",toolCallId:e,command:d,timeoutMs:c.timeoutMs}));try{let e=await (0,n._)(d,c),t=m(e);return e.stderr?.trim()&&(0,o.JX)(`exec stderr: ${e.stderr.trim()}`),(0,l.Ao)(t)}catch(e){return(0,o.CN)(`exec failed: ${a} ${s.join(" ")}: ${String(e)}`),(0,l.Ao)({ok:!1,error:String(e?.message??e),stdout:"",stderr:""})}}},k={name:"queue_exec",label:"Queue Exec",description:"Run a shell command through the main command queue. Same parameters as exec, but execution is serialized with other queued commands. Prefer this when running multiple commands or when the agent uses other process tools.",parameters:g,execute:async(e,t,r,i)=>{let a=null!=t.command?String(t.command).trim():"";if(!a)return(0,l.Ao)({ok:!1,error:"command is required"});let d=Array.isArray(t.args)?t.args.map(e=>String(e)):[],c=[a,...d],u=p(t);(0,o.JX)(JSON.stringify({tool:"queue_exec",toolCallId:e,command:c,timeoutMs:u.timeoutMs}));try{let e=await (0,s.Wf)(()=>(0,n._)(c,u)),t=m(e);return e.stderr?.trim()&&(0,o.JX)(`queue_exec stderr: ${e.stderr.trim()}`),(0,l.Ao)(t)}catch(e){return(0,o.CN)(`queue_exec failed: ${a} ${d.join(" ")}: ${String(e)}`),(0,l.Ao)({ok:!1,error:String(e?.message??e),stdout:"",stderr:""})}}};i()}catch(e){i(e)}})},9243(e,t,r){r.a(e,async function(e,i){try{r.d(t,{G:()=>k});var a=r(3513),o=r(3772),n=r(4508),s=r(1942),l=r(1305),d=r(3591),c=r(3124),u=r(68),p=r(1549),m=r(7619),h=r(7536),g=e([a,p,m,o,n,s,c,l,u,d]);function f(e,t){return null==e||e.has(t.toLowerCase())}async function k(e,t,r,i={}){let g=i.allowNames??null,w=e?.tools?{config:{tools:e.tools}}:{},v=[];if(f(g,"list_files")&&v.push(a.i),f(g,"read_pdf")&&v.push(p.Hw),f(g,"playwright_view_markdown")&&v.push(m.Ef),f(g,"exec")&&v.push(o.w),f(g,"queue_exec")&&v.push(o.Z),r){let e=null==g||g.has("customer_tools")||g.has("custom_tools");try{let t=await (0,h.ZU)(r);if(e)v.push(...t);else for(let e of t){let t=String(e.name??"").toLowerCase();g?.has(t)&&v.push(e)}}catch(e){console.warn(`Failed to load custom tools: ${e.message}`)}}let y=(0,n.dW)(w);y&&f(g,"web_fetch")&&v.push(y);let b=(0,s.t)(w);b&&f(g,"web_search")&&v.push(b);let S=(0,c.Q)(w);S&&f(g,"proxy_downloader")&&v.push(S);let T=t?(0,l.XN)(e,t):null;T&&f(g,"read_email")&&v.push(T);let E=t?(0,l.jI)(e,t):null;E&&f(g,"send_email")&&v.push(E);let x=(0,u.Ei)(w);x&&f(g,"html_to_markdown")&&v.push(x);let C=(0,u.Gz)(w);C&&f(g,"markdown_to_html")&&v.push(C);let A=(0,d.H)();A&&f(g,"wechat_publish_article")&&v.push(A);let I=(0,d.f)();return I&&f(g,"wechat_generate_cover_image")&&v.push(I),v}[a,p,m,o,n,s,c,l,u,d]=g.then?(await g)():g,i()}catch(e){i(e)}})},3513(e,t,r){r.a(e,async function(e,i){try{r.d(t,{i:()=>m});var a=r(1455),o=r(6760),n=r(4204),s=r(4071),l=r(7648),d=r(8362),c=r(4768),u=r(3122),p=e([n,s,c,d,l]);[n,s,c,d,l]=p.then?(await p)():p;let m={name:"list_files",label:"List Files",description:"List files and directories in a directory. Use to explore the project. Default is the current project directory.",parameters:n.Type.Object({path:n.Type.Optional(n.Type.String({description:"Directory path to list (relative to project or absolute). Omit for current directory."}))}),execute:async(e,t,r,i)=>{let n=t.path&&(0,o.resolve)(process.cwd(),t.path)||process.cwd(),p=await (0,a.readdir)(n,{withFileTypes:!0}),m=p.map(e=>e.isDirectory()?`${e.name}/`:e.name),h={path:n,count:p.length,entries:m};(0,s.JX)(JSON.stringify({tool:"list_files",toolCallId:e,params:t,payload:h}));let g=await (0,c.s)(process.cwd()),f=g?.lang??(0,d.a)(),k=(0,d.l)(f);return(0,l.Uz)(k("tools.listFiles.result",{path:n,count:h.count})),(0,u.Ao)(h)}};i()}catch(e){i(e)}})},68(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Ei:()=>c,Gz:()=>u,LZ:()=>p});var a=r(4204),o=r(3122),n=r(8703),s=e([n,a]);function l(e,t={}){if(!e||"string"!=typeof e)return"";let{forWechat:r,...i}=t;if(r)return function(e,t={}){let r=[],{Renderer:i}=n.marked,a=new i;a.paragraph=function(e){let t=this.parser.parseInline(e.tokens);return`<p style="${m}">${t}</p>
|
|
141
|
+
`},a.heading=function(e){let t=this.parser.parseInline(e.tokens);return`<h${e.depth} style="${h(e.depth)}">${t}</h${e.depth}>
|
|
142
|
+
`},a.blockquote=function(e){let t=this.parser.parse(e.tokens);return`<blockquote style="${g}">
|
|
275
143
|
${t}</blockquote>
|
|
276
|
-
`},
|
|
277
|
-
`},
|
|
278
|
-
${t?t+"\n":""}`}return`<p style="${
|
|
279
|
-
`}).join("")},
|
|
144
|
+
`},a.code=function(e){let t=d(e.text);return`<pre style="${f}"><code>${t}</code></pre>
|
|
145
|
+
`},a.codespan=function(e){let t=d(e.text);return`<code style="${k}">${t}</code>`},a.link=function(e){let t=r.length+1;r.push({index:t,href:e.href,title:e.title??null});let i=this.parser.parseInline(e.tokens);return`${i}<sup style="font-size:12px;color:#666;">[${t}]</sup>`},a.list=function(e){let t=e.ordered,r="number"==typeof e.start?e.start:1;return e.items.map((e,i)=>{let a=this.parser.parse(e.tokens).trim(),o=t?`${r+i}. `:"• ",n=a.match(/^\s*<p[^>]*>([\s\S]*?)<\/p>/);if(n){let e=n[1].trim(),t=a.slice(n[0].length).trim();return`<p style="${m}">${o}${e}</p>
|
|
146
|
+
${t?t+"\n":""}`}return`<p style="${m}">${o}${a}</p>
|
|
147
|
+
`}).join("")},a.table=function(e){let t=e.header.map(e=>this.tablecell(e)).join(""),r=e.rows.map(e=>this.tablerow({text:e.map(e=>this.tablecell(e)).join("")})).join("");return`<table style="${w}">
|
|
280
148
|
<thead>
|
|
281
149
|
<tr>
|
|
282
150
|
${t}</tr>
|
|
283
151
|
</thead>
|
|
284
152
|
<tbody>
|
|
285
|
-
${
|
|
153
|
+
${r}</tbody>
|
|
286
154
|
</table>
|
|
287
|
-
`},
|
|
288
|
-
`},
|
|
289
|
-
`};let o={gfm:!0,breaks:!0,...t,renderer:
|
|
290
|
-
`).join("");
|
|
155
|
+
`},a.tablecell=function(e){let t=e.header?"th":"td",r=e.align?` align="${e.align}"`:"",i=this.parser.parseInline(e.tokens);return`<${t} style="${v}"${r}>${i}</${t}>
|
|
156
|
+
`},a.hr=function(){return`<hr style="${y}">
|
|
157
|
+
`};let o={gfm:!0,breaks:!0,...t,renderer:a},s=n.marked.parse(e.trim(),o);if(s=s.replace(/<li([^>]*)>((?:(?!<li[\s>]).)*?)<\/li>/gi,(e,t,r)=>{let i=r.replace(/<p[^>]*>\s*<\/p>/gi,"").replace(/<br\s*\/?>/gi," ").trim();return""===i?"":e}),r.length>0){let e=r.map(e=>`<p style="${T}">[${e.index}] ${d(e.href)}</p>
|
|
158
|
+
`).join("");s+=`<div style="${b}">
|
|
291
159
|
<p style="${S}">参考文献</p>
|
|
292
|
-
${e}</div>`}return
|
|
160
|
+
${e}</div>`}return s}(e,i);let a={gfm:!0,breaks:!0,...i};try{return n.marked.parse(e.trim(),a)}catch(e){throw Error(`Failed to convert markdown to HTML: ${e.message}`)}}[n,a]=s.then?(await s)():s;let m="margin:0 0 1em 0; font-size:16px; line-height:1.6; color:#333;",h=e=>`font-size:${({1:"22px",2:"18px",3:"16px",4:"15px",5:"14px",6:"13px"})[e]||"16px"}; font-weight:bold; color:#333; margin:1em 0 0.5em 0;`,g="margin:0.5em 0; padding:0.5em 0 0.5em 1em; border-left:4px solid #ddd; color:#666; background:#f9f9f9;",f="display:block; margin:0.5em 0; padding:12px; font-family:monospace; font-size:14px; background:#f5f5f5; color:#333; border-radius:4px; overflow-x:auto;",k="font-family:monospace; font-size:14px; background:#f5f5f5; padding:2px 6px; border-radius:3px;",w="border-collapse:collapse; width:100%; margin:0.5em 0;",v="border:1px solid #ddd; padding:8px 12px; font-size:14px;",y="border:none; border-top:1px solid #eee; margin:1em 0;",b="margin-top:1.5em; padding-top:1em; border-top:1px solid #eee;",S="font-size:14px; font-weight:bold; color:#333; margin-bottom:0.5em;",T="font-size:13px; color:#666; margin:0.2em 0;";function d(e){return"string"!=typeof e?"":e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}let E=a.Type.Object({html:a.Type.String({description:"HTML string to convert to markdown."}),preserveWhitespace:a.Type.Optional(a.Type.Boolean({description:"Preserve original whitespace formatting. Default: false.",default:!1})),maxChars:a.Type.Optional(a.Type.Number({description:"Max length of returned markdown (truncated if exceeded). Default 8000 to avoid API errors.",default:8e3}))}),x=a.Type.Object({markdown:a.Type.String({description:"Markdown string to convert to HTML."}),forWechat:a.Type.Optional(a.Type.Boolean({description:"If true, output HTML optimized for WeChat Official Account (inline styles, links as footnotes). Default: false.",default:!1})),gfm:a.Type.Optional(a.Type.Boolean({description:"Enable GitHub Flavored Markdown. Default: true.",default:!0})),breaks:a.Type.Optional(a.Type.Boolean({description:"Convert line breaks to <br>. Default: true.",default:!0})),sanitize:a.Type.Optional(a.Type.Boolean({description:"Sanitize HTML output. Default: false.",default:!1})),maxChars:a.Type.Optional(a.Type.Number({description:"Max length of returned HTML (truncated if exceeded). Default 8000 to avoid API errors.",default:8e3}))});function c(e={}){let t=e.config?.tools?.markdown;return t?.enabled===!1?null:{name:"html_to_markdown",description:"Convert HTML to markdown format.",parameters:E,execute:async(e,t)=>{let r,i;try{i=(0,o.h_)(t,"html",{required:!0,label:"html",allowEmpty:!0});let e=!0===t.preserveWhitespace;r=function(e){if(!e||"string"!=typeof e)return"";let t=e.trim();return t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/<h1[^>]*>(.*?)<\/h1>/gi,"# $1\n\n")).replace(/<h2[^>]*>(.*?)<\/h2>/gi,"## $1\n\n")).replace(/<h3[^>]*>(.*?)<\/h3>/gi,"### $1\n\n")).replace(/<h4[^>]*>(.*?)<\/h4>/gi,"#### $1\n\n")).replace(/<h5[^>]*>(.*?)<\/h5>/gi,"##### $1\n\n")).replace(/<h6[^>]*>(.*?)<\/h6>/gi,"###### $1\n\n")).replace(/<p[^>]*>(.*?)<\/p>/gi,"$1\n\n")).replace(/<br\s*\/?>/gi," \n")).replace(/<(?:b|strong)[^>]*>(.*?)<\/(?:b|strong)>/gi,"**$1**")).replace(/<(?:i|em)[^>]*>(.*?)<\/(?:i|em)>/gi,"*$1*")).replace(/<a[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/gi,"[$2]($1)")).replace(/<img[^>]*src="([^"]*)"[^>]*alt="([^"]*)"[^>]*>/gi,"")).replace(/<img[^>]*src="([^"]*)"[^>]*>/gi,"")).replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,(e,t)=>{let r=t.trim().replace(/\n\s*/g," ");return"- "+r+"\n"})).replace(/<ul[^>]*>/gi,"")).replace(/<\/ul>/gi,"\n")).replace(/<ol[^>]*>/gi,"")).replace(/<\/ol>/gi,"\n")).replace(/<pre[^>]*>\s*<code[^>]*>([\s\S]*?)<\/code>\s*<\/pre>/gi,(e,t)=>{let r=t.trim();return"```\n"+r+"\n```\n\n"})).replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,(e,t)=>{let r=t.trim();return"`"+r+"`"})).replace(/<blockquote[^>]*>(.*?)<\/blockquote>/gis,"> $1\n\n")).replace(/<hr\s*\/?>/gi,"---\n")).replace(/<[^>]*>/g,"")).replace(/</g,"<")).replace(/>/g,">")).replace(/&/g,"&")).replace(/"/g,'"')).replace(/'|'/g,"'")).replace(/ /g," ")).replace(/\n\s*\n\s*\n/g,"\n\n")).replace(/^\s+|\s+$/g,"")).replace(/\n\s+$/gm,"\n")}(i),e||(r=(r=r.replace(/\s+/g," ")).replace(/\n\s*\n\s*\n/g,"\n\n"))}catch(e){return(0,o.Ao)({markdown:"",originalLength:"string"==typeof i?i.length:0,convertedLength:0,success:!1,error:e instanceof Error?e.message:String(e)})}let a=(0,o.jV)(t,"maxChars",{integer:!0}),n="number"==typeof a&&a>=100?Math.min(a,5e5):8e3,s=r.length>n,l=s?r.slice(0,n):r;return(0,o.Ao)({markdown:l,originalLength:i.length,convertedLength:r.length,truncated:s||void 0,maxChars:s?n:void 0,success:!0})}}}function u(e={}){let t=e.config?.tools?.markdown;return t?.enabled===!1?null:{name:"markdown_to_html",description:"Convert markdown to HTML format. Use forWechat: true for WeChat Official Account (inline styles, links as footnotes).",parameters:x,execute:async(e,t)=>{let r,i;try{r=(0,o.h_)(t,"markdown",{required:!0,label:"markdown",allowEmpty:!0});let e=!1!==t.gfm,a=!1!==t.breaks,n=!0===t.sanitize,s=!0===t.forWechat;n&&console.warn("HTML sanitization requested but not implemented. Consider using a sanitization library."),i=l(r,{gfm:e,breaks:a,forWechat:s})}catch(e){return(0,o.Ao)({html:"",originalLength:"string"==typeof r?r.length:0,convertedLength:0,success:!1,error:e instanceof Error?e.message:String(e)})}let a=(0,o.jV)(t,"maxChars",{integer:!0}),n="number"==typeof a&&a>=100?Math.min(a,5e5):8e3,s=i.length>n,d=s?i.slice(0,n):i;return(0,o.Ao)({html:d,originalLength:r.length,convertedLength:i.length,truncated:s||void 0,maxChars:s?n:void 0,success:!0})}}}function p(e,t={}){return l(e,t)}i()}catch(e){i(e)}})},8619(e,t,r){r.d(t,{A:()=>n});var i=r(8995),a=r(6760),o=r(4399);let n=(0,i.createRequire)((0,a.join)((0,o.F8)(),"package.json"))("pdf-parse")},1549(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Hw:()=>g});var a=r(1455),o=r(6760),n=r(4204),s=r(4071),l=r(7648),d=r(8362),c=r(4768),u=r(8619),p=e([n,c,d,l,s]);async function m(e){if(!Buffer.isBuffer(e))throw Error("pdfToMarkdown expects a Buffer");let t=await (0,u.A)(e),r="string"==typeof t.text?t.text:"",i="number"==typeof t.numpages&&t.numpages>0?t.numpages:0,a=t.info&&"object"==typeof t.info?t.info:void 0,o=a&&"string"==typeof a.Title?a.Title:void 0;return{markdown:function(e,t={}){if("string"!=typeof e)return"*No text content extracted.*";let r=e.trim();if(!r)return"*No text content extracted.*";let i=r.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n").map(e=>e.trim()).filter(e=>e.length>0),a=[],o=[];for(let e of i)e.length>0?o.push(e):o.length>0&&(a.push(o.join(" ")),o=[]);o.length>0&&a.push(o.join(" "));let n=a.join("\n\n"),s=t.title&&String(t.title).trim()?String(t.title).trim():"PDF Document",l=null!=t.numpages&&Number.isInteger(t.numpages)&&t.numpages>0?`
|
|
293
161
|
|
|
294
|
-
*Pages: ${t.numpages}*`:"";return`# ${
|
|
162
|
+
*Pages: ${t.numpages}*`:"";return`# ${s}${l}
|
|
295
163
|
|
|
296
|
-
${
|
|
164
|
+
${n}`}(r,{numpages:i,title:o}),numpages:i,info:a}}async function h(e,t=process.cwd()){let r=(0,o.resolve)(t,e),i=await (0,a.readFile)(r);return m(i)}[n,c,d,l,s]=p.then?(await p)():p;let g={name:"read_pdf",label:"Read PDF",description:"Read a PDF file and return its text content as markdown. Provide the file path relative to the project or an absolute path.",parameters:n.Type.Object({path:n.Type.String({description:"Path to the PDF file (relative to project or absolute)."})}),execute:async(e,t,r,i)=>{let a=t.path&&String(t.path).trim();if(!a)return{content:[{type:"text",text:"Error: path is required."}],details:{error:"path is required"}};let n=process.cwd();try{let{markdown:t,numpages:r,info:i}=await h(a,n),u={path:(0,o.resolve)(n,a),numpages:r,markdown:t};(0,s.JX)(JSON.stringify({tool:"read_pdf",toolCallId:e,params:{path:a},payload:{path:u.path,numpages:r}}));let p=await (0,c.s)(n),m=p?.lang??(0,d.a)(),g=(0,d.l)(m);return(0,l.Uz)(g("tools.readPdf.result",{path:u.path,numpages:r})),{content:[{type:"text",text:t}],details:{path:u.path,numpages:r,info:i}}}catch(r){let t=r?.message??String(r);return(0,s.JX)(JSON.stringify({tool:"read_pdf",toolCallId:e,params:{path:a},error:t})),{content:[{type:"text",text:`Error reading PDF: ${t}`}],details:{error:t,path:(0,o.resolve)(n,a)}}}}};i()}catch(e){i(e)}})},9522(e,t,r){r.a(e,async function(e,i){try{r.d(t,{E:()=>n});var a=r(2421),o=e([a]);a=(o.then?(await o)():o)[0];let s=["read","bash","edit","write","grep","find","ls"];function n(e,t){if(null==t)return[...(0,a.createCodingTools)(e),(0,a.createGrepTool)(e),(0,a.createLsTool)(e)];let r=[],i={read:()=>(0,a.createReadTool)(e),bash:()=>(0,a.createBashTool)(e),edit:()=>(0,a.createEditTool)(e),write:()=>(0,a.createWriteTool)(e),grep:()=>(0,a.createGrepTool)(e),find:()=>(0,a.createFindTool)(e),ls:()=>(0,a.createLsTool)(e)};for(let e of s)t.has(e)&&r.push(i[e]());return r}i()}catch(e){i(e)}})},6973(e,t,r){r.a(e,async function(e,i){try{r.d(t,{showMarkdownResultInPlaywright:()=>h});var a=r(1455),o=r(6760),n=r(8161),s=r(9392),l=r(68),d=r(7648),c=e([l,s,d]);[l,s,d]=c.then?(await c)():c;let g=["--app=about:blank","--disable-extensions","--disable-infobars","--no-first-run","--no-default-browser-check","--window-size=1100,800"];function u(e){return"string"!=typeof e?"":e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function p(e,t={}){let{args:r=[],...i}=t;return s.chromium.launchPersistentContext(e,{headless:!1,args:[...g,...r],...i})}async function m(){let e=await (0,a.mkdtemp)((0,o.join)((0,n.tmpdir)(),"pithosai-preview-")),t=process.env.PITHOSAI_PLAYWRIGHT_CHANNEL,r="string"==typeof t?t.trim():"";if("bundled"===r||"chromium"===r)return{context:await p(e),userDataDir:e};if(""!==r)return{context:await p(e,{channel:r}),userDataDir:e};try{return{context:await p(e,{channel:"chrome"}),userDataDir:e}}catch{return{context:await p(e),userDataDir:e}}}async function h(e){let{markdown:t,t:r,documentTitle:i,skipStdoutOpening:o=!1,outputSink:n=null}=e;if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER||!t||"string"!=typeof t||!t.trim())return;o||(0,d.cb)(r("cli.resultPreviewOpening"),n??void 0);let s=function(e,t={}){var r;let i=(0,l.LZ)(e,{forWechat:!0}),a=u(t.documentTitle??"Pithosai"),o=u(t.toolbar?.copyLabel??"Copy markdown"),n=u(t.toolbar?.closeLabel??"Close"),s=(r=t.toolbar?.copiedHint??"Copied!",JSON.stringify(r).replace(/</g,"\\u003c"));return`<!DOCTYPE html>
|
|
297
165
|
<html lang="zh-CN">
|
|
298
166
|
<head>
|
|
299
167
|
<meta charset="utf-8"/>
|
|
300
168
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
301
|
-
<title>${
|
|
169
|
+
<title>${a}</title>
|
|
302
170
|
<style>
|
|
303
171
|
:root {
|
|
304
172
|
--bar-bg: #ffffff;
|
|
@@ -390,18 +258,18 @@ ${a}`}(i,{numpages:r,title:o}),numpages:r,info:s}}async function m(e,t=process.c
|
|
|
390
258
|
<body>
|
|
391
259
|
<div class="pithosai-shell">
|
|
392
260
|
<header class="pithosai-toolbar" role="banner">
|
|
393
|
-
<div class="pithosai-toolbar-title">${
|
|
261
|
+
<div class="pithosai-toolbar-title">${a}</div>
|
|
394
262
|
<div class="pithosai-toolbar-actions">
|
|
395
263
|
<span id="pithosai-copy-hint" class="pithosai-copy-hint" aria-live="polite"></span>
|
|
396
264
|
<button type="button" class="pithosai-btn pithosai-btn--copy" id="pithosai-copy-btn">${o}</button>
|
|
397
|
-
<button type="button" class="pithosai-btn pithosai-btn--close" id="pithosai-close-btn">${
|
|
265
|
+
<button type="button" class="pithosai-btn pithosai-btn--close" id="pithosai-close-btn">${n}</button>
|
|
398
266
|
</div>
|
|
399
267
|
</header>
|
|
400
|
-
<article class="pithosai-article">${
|
|
268
|
+
<article class="pithosai-article">${i}</article>
|
|
401
269
|
</div>
|
|
402
270
|
<script>
|
|
403
271
|
(function () {
|
|
404
|
-
var COPIED_HINT = ${
|
|
272
|
+
var COPIED_HINT = ${s};
|
|
405
273
|
async function copyMarkdown() {
|
|
406
274
|
if (typeof window.__pithosaiGetMarkdown !== "function") {
|
|
407
275
|
console.warn("pithosai: __pithosaiGetMarkdown not bound (open via pithosai preview)");
|
|
@@ -448,69 +316,70 @@ ${a}`}(i,{numpages:r,title:o}),numpages:r,info:s}}async function m(e,t=process.c
|
|
|
448
316
|
})();
|
|
449
317
|
</script>
|
|
450
318
|
</body>
|
|
451
|
-
</html>`}(t,{documentTitle:r
|
|
452
|
-
${o} ${
|
|
453
|
-
`})).replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,(e,t)=>{let
|
|
454
|
-
- ${
|
|
455
|
-
${e.text}`:e.text;s=(0,n.it)(i)}return(0,n.EJ)(s.trim(),r).text}({detail:t,contentType:i.headers.get("content-type"),maxChars:4e3});throw Error(`Web fetch failed (${i.status}): ${r||i.statusText}`)}let h=i.headers.get("content-type")??"application/octet-stream",m=await (0,a.BQ)(i),f="raw",w=m;if(h.includes("text/html"))if(e.readabilityEnabled){let t=await (0,n.rm)({html:m,url:u,extractMode:e.extractMode});if(t?.text)w=t.text,r=t.title,f="readability";else{let t=await p({...e,url:u});if(t)w=t.text,r=t.title,f="firecrawl";else throw Error("Web fetch extraction failed: Readability and Firecrawl returned no content.")}}else throw Error("Web fetch extraction failed: Readability disabled and Firecrawl unavailable.");else if(h.includes("application/json"))try{w=JSON.stringify(JSON.parse(m),null,2),f="json"}catch{w=m,f="raw"}let k=(0,n.EJ)(w,e.maxChars),y={url:e.url,finalUrl:u,status:i.status,contentType:h,title:r,extractMode:e.extractMode,extractor:f,truncated:k.truncated,length:k.text.length,fetchedAt:new Date().toISOString(),tookMs:Date.now()-l,text:k.text};return(0,a.aR)(g,s,y,e.cacheTtlMs),y}async function p(e){if(!e.firecrawlEnabled||!e.firecrawlApiKey)return null;try{let t=await c({url:e.url,extractMode:e.extractMode,apiKey:e.firecrawlApiKey,baseUrl:e.firecrawlBaseUrl,onlyMainContent:e.firecrawlOnlyMainContent,maxAgeMs:e.firecrawlMaxAgeMs,proxy:e.firecrawlProxy,storeInCache:e.firecrawlStoreInCache,timeoutSeconds:e.firecrawlTimeoutSeconds});return{text:t.text,title:t.title}}catch{return null}}function h(e){var t,i;let r,s,n,l=function(e){let t=e?.tools?.web?.fetch;if(t&&"object"==typeof t)return t}(e?.config);if(t={fetch:l,sandboxed:e?.sandboxed},"boolean"==typeof t.fetch?.enabled&&!t.fetch.enabled)return null;let d="boolean"!=typeof l?.readability||l.readability,c=function(e){if(!e||"object"!=typeof e)return;let t=e.firecrawl;if(t&&"object"==typeof t)return t}(l),p=(r=c&&"string"==typeof c.apiKey?c.apiKey.trim():"",s=(process.env.FIRECRAWL_API_KEY??"").trim(),r||s||void 0),h=(i={firecrawl:c,apiKey:p},"boolean"==typeof i.firecrawl?.enabled?i.firecrawl.enabled:!!i.apiKey),g=(c&&"string"==typeof c.baseUrl?c.baseUrl.trim():"")||m,w="boolean"!=typeof c?.onlyMainContent||c.onlyMainContent,k=(n=function(e){let t=e&&"number"==typeof e.maxAgeMs?e.maxAgeMs:void 0;if("number"!=typeof t||!Number.isFinite(t))return;let i=Math.max(0,Math.floor(t));return i>0?i:void 0}(c),"number"==typeof n?n:1728e5),y=(0,a.vc)(c?.timeoutSeconds??l?.timeoutSeconds,30),v=l&&"string"==typeof l.userAgent&&l.userAgent||"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";return{label:"Web Fetch",name:"web_fetch",description:"Fetch and extract readable content from a URL (HTML → markdown/text). Use for lightweight page access without browser automation.",parameters:f,execute:async(e,t)=>{var i,r;let s,n,c=t&&"object"==typeof t?t:{},m=(0,o.h_)(c,"url",{required:!0}),f="text"===(0,o.h_)(c,"extractMode")?"text":"markdown",b=(0,o.jV)(c,"maxChars",{integer:!0}),S=await u({url:m,extractMode:f,maxChars:(i=b??l?.maxChars,s="number"==typeof i&&Number.isFinite(i)?i:5e4,Math.max(100,Math.floor(s))),maxRedirects:(r=l?.maxRedirects,n="number"==typeof r&&Number.isFinite(r)?r:3,Math.max(0,Math.floor(n))),timeoutSeconds:(0,a.vc)(l?.timeoutSeconds,30),cacheTtlMs:(0,a.d6)(l?.cacheTtlMinutes,15),userAgent:v,readabilityEnabled:d,firecrawlEnabled:h,firecrawlApiKey:p,firecrawlBaseUrl:g,firecrawlOnlyMainContent:w,firecrawlMaxAgeMs:k,firecrawlProxy:"auto",firecrawlStoreInCache:!0,firecrawlTimeoutSeconds:y});return(0,o.Ao)(S)}}}r()}catch(e){r(e)}})},3124(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Q:()=>u});var s=i(4204),o=i(3122),a=i(178),n=e([s,a]);[s,a]=n.then?(await n)():n;let p="Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",h=s.Type.Object({url:s.Type.String({description:"HTTP or HTTPS URL to fetch through proxy."}),apiKey:s.Type.Optional(s.Type.String({description:"ScraperAPI API key. If not provided, will use SCRAPERAPI_API_KEY environment variable."})),render:s.Type.Optional(s.Type.Boolean({description:"Enable JavaScript rendering. Default: false."})),countryCode:s.Type.Optional(s.Type.String({description:"Country code for geotargeting (e.g., 'us', 'gb', 'de')."})),premium:s.Type.Optional(s.Type.Boolean({description:"Use premium residential proxies. Default: false."})),sessionNumber:s.Type.Optional(s.Type.Number({description:"Session number for sticky sessions (keep same IP across requests)."})),deviceType:s.Type.Optional(s.Type.String({description:"Device type ('desktop', 'mobile', 'tablet'). Default: 'desktop'."})),timeoutSeconds:s.Type.Optional(s.Type.Number({description:"Timeout in seconds. Default: 30."})),maxRetries:s.Type.Optional(s.Type.Number({description:"Maximum number of retries on failure. Default: 2."})),retryDelayMs:s.Type.Optional(s.Type.Number({description:"Delay between retries in milliseconds. Default: 1000."})),maxRedirects:s.Type.Optional(s.Type.Number({description:"Maximum number of redirects to follow. Default: 3."})),userAgent:s.Type.Optional(s.Type.String({description:"Custom User-Agent header. Default: modern Chrome user agent."})),keepHeaders:s.Type.Optional(s.Type.Boolean({description:"Include response headers in result. Default: false."})),maxChars:s.Type.Optional(s.Type.Number({description:"Max length of body in result when text/HTML (truncated if exceeded). Default 32000 to avoid LLM request size limits.",default:32e3}))});async function l(e,t){let i,{timeoutSeconds:r=30,maxRetries:s=2,retryDelayMs:o=1e3,userAgent:a=p,maxRedirects:n=3}=t,l={headers:{"User-Agent":a},redirect:"follow"};for(let t=0;t<=s;t++)try{let t=new AbortController,i=setTimeout(()=>t.abort(),1e3*r),s=await fetch(e,{...l,signal:t.signal});return clearTimeout(i),s.redirected&&s.url,s}catch(e){if(i=e,t<s){let e=o*Math.pow(2,t);await function(e){return new Promise(t=>setTimeout(t,e))}(e)}}throw Error(`Failed to fetch after ${s+1} attempts: ${i?.message||"Unknown error"}`)}async function d(e,t){let i=e.headers.get("content-type")||"",r=e.headers.get("content-length"),s={url:e.url,status:e.status,statusText:e.statusText,contentType:i,contentLength:r?parseInt(r,10):null,fetchedAt:new Date().toISOString()};if(t){let t={};e.headers.forEach((e,i)=>{t[i]=e}),s.headers=t}if(i.includes("application/json"))s.body=await e.json();else if(i.includes("text/")||i.includes("application/xml")||i.includes("application/xhtml+xml"))s.body=await e.text();else{let t=await e.arrayBuffer();s.body=Buffer.from(t).toString("base64")}return s}async function c(e){let t=(0,o.h_)(e,"url",{required:!0}),i=function(e){let t=(0,o.h_)(e,"apiKey");if(t)return t;let i=process.env.SCRAPERAPI_API_KEY;if(i&&"string"==typeof i&&i.trim())return i.trim();throw Error("apiKey required")}(e),r=(0,o.GE)(e,"render",{defaultValue:!1}),s=(0,o.h_)(e,"countryCode"),n=(0,o.GE)(e,"premium",{defaultValue:!1}),c=(0,o.jV)(e,"sessionNumber"),u=(0,o.h_)(e,"deviceType",{defaultValue:"desktop"}),h=(0,o.jV)(e,"timeoutSeconds",{defaultValue:30}),m=(0,o.jV)(e,"maxRetries",{defaultValue:2}),g=(0,o.jV)(e,"retryDelayMs",{defaultValue:1e3}),f=(0,o.jV)(e,"maxRedirects",{defaultValue:3}),w=(0,o.h_)(e,"userAgent",{defaultValue:p}),k=(0,o.GE)(e,"keepHeaders",{defaultValue:!1}),y=(0,o.jV)(e,"maxChars",{integer:!0}),v="number"==typeof y&&y>=100?Math.min(y,5e5):32e3;try{new URL(t)}catch{throw Error(`Invalid URL: ${t}`)}let b=function(e,t){let{apiKey:i,render:r,countryCode:s,premium:o,sessionNumber:a,deviceType:n,url:l}=t,d=new URLSearchParams;return d.set("api_key",i),!0===r&&d.set("render","true"),s&&d.set("country_code",s),!0===o&&d.set("premium","true"),void 0!==a&&d.set("session_number",a.toString()),n&&d.set("device_type",n),d.set("url",l),`${e}?${d.toString()}`}("https://api.scraperapi.com",{apiKey:i,render:r,countryCode:s,premium:n,sessionNumber:c,deviceType:u,url:t}),S=Date.now();try{let e=await l(b,{timeoutSeconds:h,maxRetries:m,retryDelayMs:g,userAgent:w,maxRedirects:f}),t=await d(e,k),o=Date.now(),p=t.contentType&&/^image\//i.test(t.contentType);if("string"==typeof t.body){let e=p?Math.min(v,a.Bz):v;t.body.length>e&&(t.bodyLength=t.body.length,t.body=t.body.slice(0,e),t.bodyTruncated=!0,t.maxChars=e,p&&(t.bodyOmittedReason="Image truncated for request size limit."))}else if("object"==typeof t.body&&null!==t.body){let e=JSON.stringify(t.body);e.length>v&&(t.bodyLength=e.length,t.body=e.slice(0,v),t.bodyTruncated=!0,t.maxChars=v)}return t.tookMs=o-S,t.scraperApiParams={render:r,countryCode:s||null,premium:n,sessionNumber:c||null,deviceType:u,usedApiKey:i.substring(0,8)+"..."+i.substring(i.length-4)},t}catch(t){let e=Date.now();throw Error(`Proxy fetch failed after ${e-S}ms: ${t.message}`)}}function u(e){let t=e?.config?.tools?.proxy;return t?.enabled===!1?null:{label:"Proxy Downloader",name:"proxy_downloader",description:"Fetch HTTP(S) URLs through ScraperAPI proxy service. Supports JavaScript rendering, geotargeting, premium proxies, and sticky sessions.",parameters:h,execute:async(e,t)=>{let i=await c(t);return(0,o.Ao)(i)}}}r()}catch(e){r(e)}})},1942(e,t,i){i.a(e,async function(e,r){try{i.d(t,{t:()=>u});var s=i(4204),o=i(3122),a=i(4671),n=e([s]);s=(n.then?(await n)():n)[0];let p="https://openrouter.ai/api/v1",h="https://api.perplexity.ai",m="perplexity/sonar-pro",g=["pplx-"],f=["sk-or-"],w=new Map,k=s.Type.Object({query:s.Type.String({description:"Search query string."}),count:s.Type.Optional(s.Type.Number({description:"Number of results to return (1-10).",minimum:1,maximum:10})),country:s.Type.Optional(s.Type.String({description:"2-letter country code for region-specific results (e.g., 'DE', 'US', 'ALL'). Default: 'US'."})),search_lang:s.Type.Optional(s.Type.String({description:"ISO language code for search results (e.g., 'de', 'en', 'fr')."})),ui_lang:s.Type.Optional(s.Type.String({description:"ISO language code for UI elements."}))});function l(e){return"string"==typeof e?e.trim():""}async function d(e){let t=`${e.baseUrl.replace(/\/$/,"")}/chat/completions`,i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`,"HTTP-Referer":"https://clawdbot.com","X-Title":"Web Search"},body:JSON.stringify({model:e.model,messages:[{role:"user",content:e.query}]}),signal:(0,a.wj)(void 0,1e3*e.timeoutSeconds)});if(!i.ok){let e=await (0,a.BQ)(i);throw Error(`Perplexity API error (${i.status}): ${e||i.statusText}`)}let r=await i.json(),s=r.choices?.[0]?.message?.content??"No response",o=r.citations??[];return{content:s,citations:o}}async function c(e){let t=(0,a.dU)(`${e.provider}:${e.query}:${e.count}:${e.country||"default"}:${e.search_lang||"default"}:${e.ui_lang||"default"}`),i=(0,a.xe)(w,t);if(i)return{...i.value,cached:!0};let r=Date.now();if("perplexity"===e.provider){let{content:i,citations:s}=await d({query:e.query,apiKey:e.apiKey,baseUrl:e.perplexityBaseUrl??p,model:e.perplexityModel??m,timeoutSeconds:e.timeoutSeconds}),o={query:e.query,provider:e.provider,model:e.perplexityModel??m,tookMs:Date.now()-r,content:i,citations:s};return(0,a.aR)(w,t,o,e.cacheTtlMs),o}if("brave"!==e.provider)throw Error("Unsupported web search provider.");let s=new URL("https://api.search.brave.com/res/v1/web/search");s.searchParams.set("q",e.query),s.searchParams.set("count",String(e.count)),e.country&&s.searchParams.set("country",e.country),e.search_lang&&s.searchParams.set("search_lang",e.search_lang),e.ui_lang&&s.searchParams.set("ui_lang",e.ui_lang);let o=await fetch(s.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":e.apiKey},signal:(0,a.wj)(void 0,1e3*e.timeoutSeconds)});if(!o.ok){let e=await (0,a.BQ)(o);throw Error(`Brave Search API error (${o.status}): ${e||o.statusText}`)}let n=await o.json(),l=(Array.isArray(n.web?.results)?n.web?.results??[]:[]).map(e=>({title:e.title??"",url:e.url??"",description:e.description??"",published:e.age??void 0,siteName:function(e){if(e)try{return new URL(e).hostname}catch{return}}(e.url??"")})),c={query:e.query,provider:e.provider,count:l.length,tookMs:Date.now()-r,results:l};return(0,a.aR)(w,t,c,e.cacheTtlMs),c}function u(e){var t;let i,r=function(e){let t=e?.tools?.web?.search;if(t&&"object"==typeof t)return t}(e?.config);if(t={search:r,sandboxed:e?.sandboxed},"boolean"==typeof t.search?.enabled&&!t.search.enabled)return null;let s=(i=r&&"string"==typeof r.provider?r.provider.trim().toLowerCase():"","perplexity"===i?"perplexity":"brave"),n=function(e){if(!e||"object"!=typeof e)return{};let t=e.perplexity;return t&&"object"==typeof t?t:{}}(r),d="perplexity"===s?"Search the web using Perplexity Sonar (direct or via OpenRouter). Returns AI-synthesized answers with citations from real-time web search.":"Search the web using Brave Search API. Supports region-specific and localized search via country and language parameters. Returns titles, URLs, and snippets for fast research.";return{label:"Web Search",name:"web_search",description:d,parameters:k,execute:async(e,t)=>{let i,d,u,w="perplexity"===s?function(e){let t=l(e?.apiKey);if(t)return{apiKey:t,source:"config"};let i=l(process.env.PERPLEXITY_API_KEY);if(i)return{apiKey:i,source:"perplexity_env"};let r=l(process.env.OPENROUTER_API_KEY);return r?{apiKey:r,source:"openrouter_env"}:{apiKey:void 0,source:"none"}}(n):void 0,k="perplexity"===s?w?.apiKey:(i=r&&"string"==typeof r.apiKey?r.apiKey.trim():"",d=(process.env.BRAVE_API_KEY??"").trim(),i||d||void 0);if(!k)return(0,o.Ao)("perplexity"===s?{error:"missing_perplexity_api_key",message:"web_search (perplexity) needs an API key. Set PERPLEXITY_API_KEY or OPENROUTER_API_KEY, or configure tools.web.search.perplexity.apiKey."}:{error:"missing_brave_api_key",message:"web_search needs a Brave Search API key. Set BRAVE_API_KEY in the environment or configure tools.web.search.apiKey."});let y=t&&"object"==typeof t?t:{},v=(0,o.h_)(y,"query",{required:!0}),b=(0,o.jV)(y,"count",{integer:!0})??r?.maxResults,S=(0,o.h_)(y,"country"),T=(0,o.h_)(y,"search_lang"),C=(0,o.h_)(y,"ui_lang"),E=await c({query:v,count:(u="number"==typeof b&&Number.isFinite(b)?b:5,Math.max(1,Math.min(10,Math.floor(u)))),apiKey:k,timeoutSeconds:(0,a.vc)(r?.timeoutSeconds,30),cacheTtlMs:(0,a.d6)(r?.cacheTtlMinutes,15),provider:s,country:S,search_lang:T,ui_lang:C,perplexityBaseUrl:function(e,t,i){let r=e&&"string"==typeof e.baseUrl?e.baseUrl.trim():"";if(r)return r;if("perplexity_env"===t)return h;if("openrouter_env"===t)return p;if("config"===t){let e=function(e){if(!e)return;let t=e.toLowerCase();return g.some(e=>t.startsWith(e))?"direct":f.some(e=>t.startsWith(e))?"openrouter":void 0}(i);if("direct"===e)return h}return p}(n,w?.source,w?.apiKey),perplexityModel:(n&&"string"==typeof n.model?n.model.trim():"")||m});return(0,o.Ao)(E)}}}r()}catch(e){r(e)}})},4671(e,t,i){function r(e,t){return Math.max(1,Math.floor("number"==typeof e&&Number.isFinite(e)?e:t))}function s(e,t){return Math.round(6e4*("number"==typeof e&&Number.isFinite(e)?Math.max(0,e):t))}function o(e){return e.trim().toLowerCase()}function a(e,t){let i=e.get(t);return i?Date.now()>i.expiresAt?(e.delete(t),null):{value:i.value,cached:!0}:null}function n(e,t,i,r){if(!(r<=0)){if(e.size>=100){let t=e.keys().next();t.done||e.delete(t.value)}e.set(t,{value:i,expiresAt:Date.now()+r,insertedAt:Date.now()})}}function l(e,t){if(t<=0)return e??new AbortController().signal;let i=new AbortController,r=setTimeout(()=>i.abort(),t);return e&&e.addEventListener("abort",()=>{clearTimeout(r),i.abort()},{once:!0}),i.signal.addEventListener("abort",()=>clearTimeout(r),{once:!0}),i.signal}async function d(e){try{return await e.text()}catch{return""}}i.d(t,{BQ:()=>d,aR:()=>n,d6:()=>s,dU:()=>o,vc:()=>r,wj:()=>l,xe:()=>a})},3591(e,t,i){i.a(e,async function(e,r){try{i.d(t,{H:()=>g,f:()=>f});var s=i(4204),o=i(3122),a=e([s]);s=(a.then?(await a)():a)[0];let w="black-forest-labs/flux.2-pro";function n(){let e=process.env.WECHAT_APPID?.trim(),t=process.env.WECHAT_SECRET?.trim(),i=process.env.OPENROUTER_API_KEY?.trim();return e&&t&&i?{appId:e,secret:t,openRouterKey:i,imageModel:process.env.OPENROUTER_IMAGE_MODEL?.trim()||w,author:process.env.WECHAT_AUTHOR?.trim()||"田威 AI",defaultCoverUrl:process.env.DEFAULT_COVER_URL?.trim()||void 0}:null}async function l(e){let t=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${e.appId}&secret=${e.secret}`,i=await fetch(t),r=await i.json(),s=r?.access_token;if(!s||"string"!=typeof s)throw Error(`Failed to get WeChat token: ${JSON.stringify(r)}`);return s}async function d(e,t,i="16:9"){let r="1:1"!==i?` Aspect ratio: ${i}.`:"",s=`${r} ${t}`.trim(),o=JSON.stringify({model:e.imageModel||w,messages:[{role:"user",content:s}],modalities:["image"]}),a=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e.openRouterKey}`,"Content-Type":"application/json","HTTP-Referer":process.env.OPENROUTER_REFERRER||"https://github.com/pithosai"},body:o}),n=await a.json();if(!a.ok)throw Error(`OpenRouter API error: ${a.status} ${JSON.stringify(n)}`);let l=n?.choices?.[0]?.message,c=l?.images??l?.content?.filter?.(e=>e?.type==="image"),u=c?.[0]?.image_url?.url??c?.[0]?.imageUrl?.url??c?.[0]?.url;return{output:u||null,status:u?"succeeded":"failed"}}async function c(e){if(e.startsWith("data:")){let t=e.replace(/^data:image\/\w+;base64,/,"");return Buffer.from(t,"base64")}let t=await fetch(e);if(!t.ok)throw Error(`Failed to download image: ${t.status}`);let i=await t.arrayBuffer();return Buffer.from(i)}async function u(e,t,i="cover.png"){let r=new FormData,s=new Blob([t],{type:"image/png"});r.append("media",s,i);let o=await fetch(`https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${e}&type=image`,{method:"POST",body:r}),a=await o.json();if(a?.errcode&&0!==a.errcode)throw Error(`WeChat upload failed: ${a.errmsg||JSON.stringify(a)}`);return a}async function p(e,t){let i=JSON.stringify({articles:[{title:t.title,author:t.author,digest:t.digest,content:t.content,thumb_media_id:t.thumb_media_id,need_open_comment:1,only_fans_can_comment:0}]}),r=await fetch(`https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:i}),s=await r.json();if(s?.errcode&&0!==s.errcode)throw Error(`WeChat draft failed: ${s.errmsg||JSON.stringify(s)}`);return s}async function h(e,t,i){let r=(await d(e,t,"16:9")).output;if(r&&!r.startsWith("ERROR"))return{buffer:await c(r)};if(e.defaultCoverUrl)return{buffer:await c(e.defaultCoverUrl)};throw Error("Failed to generate cover and no DEFAULT_COVER_URL provided")}let k=s.Type.Object({title:s.Type.String({description:"WeChat article title."}),content_html:s.Type.String({description:"WeChat article body in HTML."}),cover_prompt:s.Type.String({description:"Prompt for generating the WeChat article cover image."}),digest:s.Type.String({description:"Short summary shown in WeChat article list (recommended 50–100 chars)."})});async function m(e,t){let i=Date.now().toString(36),r=await l(e),{buffer:s}=await h(e,t.cover_prompt,i),o=(await u(r,s,`wechat_cover_${i}.png`)).media_id;if(!o)return{success:!1,error:"Failed to upload cover image"};let a=(await p(r,{title:t.title,author:e.author||"Pithosai AI",digest:t.digest,content:t.content_html,thumb_media_id:o})).media_id;return a?{success:!0,draft_media_id:a}:{success:!1,error:"Failed to create draft"}}function g(){let e=n();return e?{label:"WeChat: Publish Article",name:"wechat_publish_article",description:"Publish an article to WeChat Official Account (公众号) draft box. Generates a cover image, uploads it to WeChat material library, and creates a draft. For WeChat platform only.",parameters:k,execute:async(t,i)=>{let r=i&&"object"==typeof i?i:{},s=(0,o.h_)(r,"title",{required:!0}),a=(0,o.h_)(r,"content_html",{required:!0}),n=(0,o.h_)(r,"cover_prompt",{required:!0}),l=(0,o.h_)(r,"digest",{required:!0});if(!s||!a||!n||!l)throw Error("title, content_html, cover_prompt, and digest are required");try{let t=await m(e,{title:s,content_html:a,cover_prompt:n,digest:l});return(0,o.Ao)(t)}catch(e){return(0,o.Ao)({success:!1,error:e?.message||String(e)})}}}:null}function f(){let e=n();if(!e)return null;let t=s.Type.Object({prompt:s.Type.String({description:"Prompt for WeChat article cover image."}),aspect_ratio:s.Type.Optional(s.Type.Union([s.Type.Literal("1:1"),s.Type.Literal("16:9"),s.Type.Literal("9:16"),s.Type.Literal("4:3"),s.Type.Literal("3:4")],{description:"Cover aspect ratio. Default: 16:9."}))});return{label:"WeChat: Generate Cover Image",name:"wechat_generate_cover_image",description:"Generate a cover image for WeChat Official Account articles. For WeChat platform only. Use before or alongside wechat_publish_article.",parameters:t,execute:async(t,i)=>{let r=i&&"object"==typeof i?i:{},s=(0,o.h_)(r,"prompt",{required:!0}),a=(0,o.h_)(r,"aspect_ratio")||"16:9";if(!s)throw Error("prompt is required");try{let t=await d(e,s,a),i=t.output;return(0,o.Ao)({success:!0,image_url:i,status:t.status})}catch(e){return(0,o.Ao)({success:!1,error:e?.message||String(e)})}}}}r()}catch(e){r(e)}})},6652(e,t,i){i.a(e,async function(e,r){try{i.d(t,{e:()=>d});var s=i(6760),o=i(8476),a=i(8362),n=i(1048),l=e([a,n,o]);function d(e,t){return e.command("add-role <role>").description(t("cli.addRoleDescription")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-l, --lang <lang>",t("cli.langOption")).action(async(t,i)=>{let r=(0,s.resolve)(i.cwd||process.cwd()),l=e.opts(),d=i.lang??l.lang??(0,a.a)();await (0,n.e)(r,e.opts().logPath),await (0,o.Cm)(r,t,d)})}[a,n,o]=l.then?(await l)():l,r()}catch(e){r(e)}})},829(e,t,i){i.a(e,async function(e,r){try{i.d(t,{w:()=>u});var s=i(481),o=i(4239),a=i(1224),n=i(8601),l=i(4071),d=e([l]);async function c(e,t,i={}){let r=!1!==i.allowRequestEdit,o=i.tuiSession??null,a="function"==typeof o?.writeLn?o.writeLn.bind(o):"function"==typeof o?.appendLine?o.appendLine.bind(o):null,d=i.io?.writeLn??a??(e=>process.stdout.write(e+"\n")),u=!!(o&&"function"==typeof o.readSubmittedLine),p=u?null:(0,s.createInterface)({input:process.stdin,output:process.stdout,completer:(0,n.Q$)()});d(""),d(t("run.pauseHeader")),d(t("run.pauseCurrentRequest",{request:e.currentRequest??""})),d(t("run.pauseHelp"));try{for(;;){u&&("function"==typeof o.ensureInputEditorActive&&o.ensureInputEditorActive(),d(t("run.pausePrompt")));let i=((u?await o.readSubmittedLine():await function(e,t){return new Promise(i=>{e.question(t,e=>i(e??""))})}(p,t("run.pausePrompt")))??"").trim(),s=i.toLowerCase();if((0,l.IW)("pauseSubPrompt",JSON.stringify({cmd:s,line:i})),"continue"===s||"c"===s)return p?.close(),{action:"continue",request:e.currentRequest};if("exit"===s||"e"===s)return p?.close(),{action:"exit",request:null};if(""!==i){if(!r){d(t("run.pauseHelp"));continue}e.updateRequest(i),d(t("run.pauseRequestUpdated",{request:i}))}}}finally{p?.close()}}async function u(e,t){let{controller:i,t:r,execute:s,allowRequestEdit:n=!0,useKeypressInterceptor:l=!0,tuiSession:d=null,io:u=null}=t,p=[e?.title??"",e?.description??""].filter(Boolean).join("\n\n"),h="function"==typeof d?.writeLn?d.writeLn.bind(d):"function"==typeof d?.appendLine?d.appendLine.bind(d):null,m=u?.writeLn??h??(e=>process.stdout.write(e+"\n"));for(;;){i.reset();let t=l?(0,a.c)(i):()=>{};try{await s(e,p)}finally{t()}if(i.status===o.i.PAUSED){let e;d&&"function"!=typeof d.readSubmittedLine&&d.suspendForReadline();try{e=await c(i,r,{allowRequestEdit:n,tuiSession:d,io:u})}finally{d&&"function"!=typeof d.readSubmittedLine&&d.resumeFromReadline()}if("exit"===e.action){m(r("run.agentStopped")),i.reset(),"function"==typeof d?.ensureInputEditorActive&&d.ensureInputEditorActive();break}p=e.request??p,i.resume(),"function"==typeof d?.ensureInputEditorActive&&d.ensureInputEditorActive();continue}i.status===o.i.STOPPED&&(m(r("run.agentStopped")),i.reset(),"function"==typeof d?.ensureInputEditorActive&&d.ensureInputEditorActive());break}}l=(d.then?(await d)():d)[0],r()}catch(e){r(e)}})},9766(e,t,i){i.a(e,async function(e,r){try{i.d(t,{$i:()=>b,YP:()=>h,Ym:()=>m,d1:()=>g});var s=i(4127),o=i(8601),a=i(9782),n=i(8691),l=e([s,n]);function d(e){return String(e).replace(/(?:\.{3}|…)((?:\u001b\[[0-9;]*m)*)$/u,"$1")}function c(e,t){let i=(0,s.truncateToWidth)(String(e??""),Math.max(0,t)),r=Math.max(0,t-(0,s.visibleWidth)(i));return i+" ".repeat(r)}function u(){process.stdout.write("\x1b[?1006h\x1b[?1002h\x1b[?1000h")}function p(){process.stdout.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l")}[s,n]=l.then?(await l)():l;class f{constructor(){this.lines=[],this.maxLines=8e3,this._viewportPinLine=null}setViewportPin(e){this._viewportPinLine=Math.max(0,e)}clearViewportPin(){this._viewportPinLine=null}appendLine(e){if(this.lines.push(e),this.lines.length>this.maxLines){let e=this.lines.length-this.maxLines;this.lines=this.lines.slice(-this.maxLines),null!=this._viewportPinLine&&(this._viewportPinLine=Math.max(0,this._viewportPinLine-e))}}appendRaw(e){0===this.lines.length?this.lines.push(e):this.lines[this.lines.length-1]+=e}viewportLines(e,t){if(0===this.lines.length)return[""];let i=Math.max(1,e),r=this.lines.length,o=Math.max(0,r-i),a=o;return null!=this._viewportPinLine&&(a=Math.min(Math.max(0,this._viewportPinLine),o)),this.lines.slice(a,a+i).map(e=>(0,s.truncateToWidth)(e,t))}tailLines(e,t){return this.viewportLines(e,t)}bumpViewStart(e,t){let i=Math.max(1,t),r=this.lines.length;if(0===r)return;let s=Math.max(0,r-i),o=null!=this._viewportPinLine?Math.min(this._viewportPinLine,s):s;this._viewportPinLine=Math.max(0,Math.min(s,o+e))}}class w{constructor(e,t){this.tui=e,this.getMessage=t,this.intervalId=null,this.frame=0,this.active=!1,this.phase="loading"}_startTick(e){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.intervalId=setInterval(()=>{let e="loading"===this.phase?a.d2.length:a.Mm.length;this.frame=(this.frame+1)%e,this.tui.requestRender()},e)}setActive(e){e!==this.active&&(this.active=e,e?(this.phase="loading",this.frame=0,this._startTick(80)):this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null))}enterRunningPhase(){this.active&&"running"!==this.phase&&(this.phase="running",this.frame=0,this._startTick(120),this.tui.requestRender())}isActive(){return this.active}isRunningPhase(){return this.active&&"running"===this.phase}render(e){let t="loading"===this.phase?a.d2:a.Mm,i=t[this.frame%t.length],r=this.getMessage()??"";return[(0,s.truncateToWidth)(`${i} ${r}`,e)]}invalidate(){}}class k{constructor(e,t){this.focused=!1,this.editor=new s.Editor(e,{borderColor:e=>n.m.dim(e),selectList:{selectedPrefix:e=>n.m.cyan.bold(e),selectedText:e=>n.m.cyan(e),description:e=>n.m.dim(e),scrollInfo:e=>n.m.dim(e),noMatch:e=>n.m.yellow(e)}},{paddingX:1,autocompleteMaxVisible:8}),this.editor.setAutocompleteProvider((0,o.ML)(t))}isAutocompleteActive(){return this.editor.isShowingAutocomplete()}handleInput(e){(0,s.matchesKey)(e,"ctrl+d")&&!this.editor.getText().trim()&&process.exit(0),this.editor.handleInput(e)}render(e){let t,i;this.editor.focused=this.focused;let r=Math.max(3,e-2),o=this.editor.render(r);if(o.length<2)return o;let a=Math.max(1,r-2*this.editor.getPaddingX()),l=this.editor.isShowingAutocomplete()&&this.editor.autocompleteList?this.editor.autocompleteList.render(a).length:0,u=o.length-l-1;if(u<1)return o;let p=o.slice(1,u),h=o.slice(u+1),m=n.m.cyan(" → "),g=p.map((e,t)=>{let i=d((0,s.truncateToWidth)(d(e??""),r));if(0!==t)return c(i,r);let o=d((0,s.truncateToWidth)(i,Math.max(0,r-3)));return`${m}${c(o,Math.max(0,r-3))}`}),f=(t=`┌${"─".repeat(r)}┐`,n.m.cyan(t)),w=(i=`└${"─".repeat(r)}┘`,n.m.cyan(i)),k=e=>n.m.cyan("│")+e+n.m.cyan("│"),y=[f];for(let e of g)y.push(k(e));for(let e of(y.push(w),h))y.push(k(e));return y}invalidate(){this.editor.invalidate()}}class y{constructor(e){let{terminal:t,transcript:i,loading:r,prompt:s}=e;this.terminal=t,this.transcript=i,this.loading=r,this.prompt=s,this.focused=!1}handleInput(e){this.prompt.focused=this.focused,this.prompt.handleInput(e)}invalidate(){this.prompt.invalidate()}render(e){this.prompt.focused=this.focused;let t=this.terminal.rows,i=this.prompt.render(e),r=+!!this.loading.isActive(),s=r?this.loading.render(e):[],o=Math.max(1,t-i.length-r);return[...this.transcript.viewportLines(o,e),...s,...i]}}class v extends s.TUI{constructor(e){super(e),this.agentRunning=!1,this.agentController=null,this.onTranscriptPageScroll=null,this.transcriptPageScrollGuard=null,this.onAgentControlNotice=null}setAgentRunning(e,t){this.agentRunning=e,this.agentController=t}handleInput(e){if(this.onTranscriptPageScroll&&this.transcriptPageScrollGuard?.()!==!0){let t=Math.max(3,this.terminal.rows-3),i=Math.max(3,Math.floor(.85*t));if((0,s.matchesKey)(e,"pageUp"))return void this.onTranscriptPageScroll(-i);if((0,s.matchesKey)(e,"pageDown"))return void this.onTranscriptPageScroll(i);if((0,s.matchesKey)(e,"up"))return void this.onTranscriptPageScroll(-1);if((0,s.matchesKey)(e,"down"))return void this.onTranscriptPageScroll(1);if((0,s.matchesKey)(e,"ctrl+u"))return void this.onTranscriptPageScroll(-i);if((0,s.matchesKey)(e,"ctrl+f"))return void this.onTranscriptPageScroll(i)}if(this.agentRunning&&this.agentController){if((0,s.matchesKey)(e,"ctrl+s")){let e=`${n.m.yellow("[Ctrl+S]")} Stopping agent...`;this.onAgentControlNotice?this.onAgentControlNotice(e):process.stdout.write(`
|
|
319
|
+
</html>`}(t,{documentTitle:i??r("cli.resultPreviewTitle"),toolbar:{copyLabel:r("cli.resultPreviewCopy"),closeLabel:r("cli.resultPreviewClose"),copiedHint:r("cli.resultPreviewCopied")}}),{context:c,userDataDir:p}=await m();try{let e=c.pages(),r=e.length>0?e[0]:await c.newPage();await r.exposeFunction("__pithosaiGetMarkdown",()=>t),await r.exposeFunction("__pithosaiClosePreview",async()=>{await c.close().catch(()=>{})}),await r.setContent(s,{waitUntil:"domcontentloaded"});let i=c.browser();await Promise.race([r.waitForEvent("close",{timeout:0}),new Promise(e=>{i?i.once("disconnected",e):c.once("close",e)})])}finally{await c.close().catch(()=>{}),await (0,a.rm)(p,{recursive:!0,force:!0}).catch(()=>{})}}i()}catch(e){i(e)}})},7619(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Ef:()=>g});var a=r(1455),o=r(6760),n=r(4204),s=r(4071),l=r(8362),d=r(4768),c=r(3122),u=r(7648),p=r(6973),m=e([n,d,l,s,p,u]);async function h(e){let t,r,i,{markdown:n,path:s,cwd:l,t:d}=e,c="string"==typeof n&&""!==n.trim(),u="string"==typeof s&&""!==s.trim();if(c===u)return{ok:!1,error:d("tools.playwrightView.errorNoSource")};if(c){let e=String(n).trim();return e?{ok:!0,markdown:e,sourceKey:"tools.playwrightView.sourceInline",sourceVars:{}}:{ok:!1,error:d("tools.playwrightView.errorEmpty")}}let p=String(s).trim(),m=(0,o.resolve)(l,p);if(t=(0,o.resolve)(l),r=(0,o.resolve)(m),!(i=(0,o.relative)(t,r))||i.startsWith("..")||0)return{ok:!1,error:d("tools.playwrightView.errorFileOutside")};try{let e=await (0,a.stat)(m);if(!e.isFile())return{ok:!1,error:d("tools.playwrightView.errorNotAFile")};if(e.size>2097152)return{ok:!1,error:d("tools.playwrightView.errorFileTooLarge",{maxBytes:String(2097152)})};let t=await (0,a.readFile)(m,"utf8");if(!t.trim())return{ok:!1,error:d("tools.playwrightView.errorEmpty")};return{ok:!0,markdown:t,sourceKey:"tools.playwrightView.sourceFile",sourceVars:{path:m}}}catch(t){let e=t?.message??String(t);return{ok:!1,error:d("tools.playwrightView.errorFileRead",{message:e})}}}[n,d,l,s,p,u]=m.then?(await m)():m;let g={name:"playwright_view_markdown",label:"Playwright markdown preview",description:"Open an interactive browser preview of markdown (WeChat-style HTML). Provide either markdown text OR path to a .md file under the project; not both. Blocks until the user closes the preview. Respects PITHOSAI_SKIP_RESULT_BROWSER=1 and PITHOSAI_PLAYWRIGHT_CHANNEL.",parameters:n.Type.Object({markdown:n.Type.Optional(n.Type.String({description:"Raw markdown to preview. Omit if using path. Do not pass both markdown and path."})),path:n.Type.Optional(n.Type.String({description:"Path to a markdown file (relative to project or absolute under project root). Omit if passing markdown."})),document_title:n.Type.Optional(n.Type.String({description:"Optional title shown in the preview window toolbar."}))}),execute:async(e,t,r,i)=>{let a=process.cwd(),o=await (0,d.s)(a),n=o?.lang??(0,l.a)(),m=(0,l.l)(n);(0,s.JX)(JSON.stringify({tool:"playwright_view_markdown",toolCallId:e,hasMarkdown:"string"==typeof t?.markdown,hasPath:"string"==typeof t?.path}));let g=await h({markdown:t?.markdown,path:t?.path,cwd:a,t:m});if(!g.ok)return(0,c.Ao)({ok:!1,error:g.error});if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER)return(0,c.Ao)({ok:!1,skipped:!0,reason:m("tools.playwrightView.skipped")});let f="string"==typeof t?.document_title&&t.document_title.trim()?t.document_title.trim():void 0;await (0,p.showMarkdownResultInPlaywright)({markdown:g.markdown,t:m,documentTitle:f??m("cli.resultPreviewTitle")});let k=m(g.sourceKey,g.sourceVars);return(0,u.Uz)(m("tools.playwrightView.result",{source:k})),(0,c.Ao)({ok:!0,source:k})}};i()}catch(e){i(e)}})},6048(e,t,r){r.a(e,async function(e,i){try{r.d(t,{N:()=>d});var a=r(6760),o=r(1455),n=r(8359),s=r(9966),l=e([n]);async function d(e,t,r){let i,l=(0,a.join)(e,".pithosai",r,`TOOLS${"zh"===t?"-zh.md":".md"}`);try{i=await (0,o.readFile)(l,"utf-8")}catch{try{let e=await (0,n.Lf)(),a=await (0,n.N6)(e,{lang:"zh"===t?"zh":"en",role:r,name:"TOOLS"}),o=a?.content;if(!o||"string"!=typeof o)return null;let l=await (0,n.Iz)(e)??process.env.PITHOSAI_RSA_PUBLIC_KEY?.trim();if(!l)return null;i=(0,s.Yc)(o,l)}catch{return null}}let d=function(e){let t=(function(e){let t=e.trimStart();if(!t.startsWith("---"))return e;let r=t.slice(3),i=r.indexOf("\n---");return -1===i?e:r.slice(i+4).trimStart()})(e).split(/\r?\n/),r=new Set;for(let e of t){let t=e.trim();t&&!/^#\s*/.test(t)&&/^[a-z][a-z0-9_]*$/i.test(t)&&r.add(t.toLowerCase())}return r}(i);return 0===d.size?null:d}n=(l.then?(await l)():l)[0],i()}catch(e){i(e)}})},2696(e,t,r){function i(e){return e.replace(/<[^>]+>/g,"").replace(/ /gi," ").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/gi,"'").replace(/</gi,"<").replace(/>/gi,">").replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCharCode(Number.parseInt(t,16))).replace(/&#(\d+);/gi,(e,t)=>String.fromCharCode(Number.parseInt(t,10)))}function a(e){return e.replace(/\r/g,"").replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").replace(/[ \t]{2,}/g," ").trim()}function o(e){let t=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i),r=t?a(i(t[1])):void 0,o=e.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<noscript[\s\S]*?<\/noscript>/gi,"");return o=(o=(o=(o=o.replace(/<a\s+[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(e,t,r)=>{let o=a(i(r));return o?`[${o}](${t})`:t})).replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(e,t,r)=>{let o="#".repeat(Math.max(1,Math.min(6,Number.parseInt(t,10)))),n=a(i(r));return`
|
|
320
|
+
${o} ${n}
|
|
321
|
+
`})).replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,(e,t)=>{let r=a(i(t));return r?`
|
|
322
|
+
- ${r}`:""})).replace(/<(br|hr)\s*\/?>/gi,"\n").replace(/<\/(p|div|section|article|header|footer|table|tr|ul|ol)>/gi,"\n"),{text:o=a(o=i(o)),title:r}}function n(e){let t=e;return a(t=(t=(t=(t=(t=(t=(t=t.replace(/!\[[^\]]*]\([^)]+\)/g,"")).replace(/\[([^\]]+)]\([^)]+\)/g,"$1")).replace(/```[\s\S]*?```/g,e=>e.replace(/```[^\n]*\n?/g,"").replace(/```/g,""))).replace(/`([^`]+)`/g,"$1")).replace(/^#{1,6}\s+/gm,"")).replace(/^\s*[-*+]\s+/gm,"")).replace(/^\s*\d+\.\s+/gm,""))}function s(e,t){return e.length<=t?{text:e,truncated:!1}:{text:e.slice(0,t),truncated:!0}}async function l(e){let t=()=>{let t=o(e.html);return"text"===e.extractMode?{text:n(t.text)||a(i(e.html)),title:t.title}:t};try{let[{Readability:i},{parseHTML:n}]=await Promise.all([r.e("511").then(r.bind(r,5522)),r.e("691").then(r.bind(r,4382))]),{document:s}=n(e.html);try{s.baseURI=e.url}catch{}let l=new i(s,{charThreshold:0}).parse();if(!l?.content)return t();let d=l.title||void 0;if("text"===e.extractMode){let e=a(l.textContent??"");return e?{text:e,title:d}:t()}let c=o(l.content);return{text:c.text,title:d??c.title}}catch{return t()}}r.d(t,{EJ:()=>s,Yj:()=>o,it:()=>n,rm:()=>l})},4508(e,t,r){r.a(e,async function(e,i){try{r.d(t,{dW:()=>m});var a=r(4204),o=r(3122),n=r(4671),s=r(2696),l=e([a]);a=(l.then?(await l)():l)[0];let h="https://api.firecrawl.dev",g=new Map,f=a.Type.Object({url:a.Type.String({description:"HTTP or HTTPS URL to fetch."}),extractMode:a.Type.Optional(a.Type.Union([a.Type.Literal("markdown"),a.Type.Literal("text")],{description:'Extraction mode ("markdown" or "text"). Default: markdown.'})),maxChars:a.Type.Optional(a.Type.Number({description:"Maximum characters to return (truncates when exceeded).",minimum:100}))});async function d(e){let t=(0,n.wj)(void 0,1e3*e.timeoutSeconds),r=new Set,i=e.url,a=0;for(;;){var o;let n;try{n=new URL(i)}catch{throw Error("Invalid URL: must be http or https")}if(!["http:","https:"].includes(n.protocol))throw Error("Invalid URL: must be http or https");!function(e){let t=e.toLowerCase().trim();if(!t)throw Error("Invalid hostname");if("localhost"===t||t.endsWith(".localhost"))throw Error("Blocked: localhost not allowed");if("[::1]"===t||"::1"===t)throw Error("Blocked: loopback not allowed");let r=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){let e=Number.parseInt(r[1],10),t=Number.parseInt(r[2],10);if(Number.parseInt(r[3],10),Number.parseInt(r[4],10),127===e)throw Error("Blocked: loopback not allowed");if(10===e||172===e&&t>=16&&t<=31||192===e&&168===t)throw Error("Blocked: private network not allowed")}}(n.hostname);let s=await fetch(n.toString(),{method:"GET",headers:{Accept:"*/*","User-Agent":e.userAgent,"Accept-Language":"en-US,en;q=0.9"},signal:t,redirect:"manual"});if(o=s.status,301===o||302===o||303===o||307===o||308===o){let t=s.headers.get("location");if(!t)throw Error(`Redirect missing location header (${s.status})`);if((a+=1)>e.maxRedirects)throw Error(`Too many redirects (limit: ${e.maxRedirects})`);let o=new URL(t,n).toString();if(r.has(o))throw Error("Redirect loop detected");r.add(o),s.body?.cancel(),i=o;continue}return{response:s,finalUrl:i}}}async function c(e){let t=function(e){let t=e.trim();if(!t)return`${h}/v2/scrape`;try{let e=new URL(t);if(e.pathname&&"/"!==e.pathname)return e.toString();return e.pathname="/v2/scrape",e.toString()}catch{return`${h}/v2/scrape`}}(e.baseUrl),r={url:e.url,formats:["markdown"],onlyMainContent:e.onlyMainContent,timeout:1e3*e.timeoutSeconds,maxAge:e.maxAgeMs,proxy:e.proxy,storeInCache:e.storeInCache},i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(r),signal:(0,n.wj)(void 0,1e3*e.timeoutSeconds)}),a=await i.json();if(!i.ok||a?.success===!1){let e=a?.error||i.statusText;throw Error(`Firecrawl fetch failed (${i.status}): ${e}`.trim())}let o=a?.data??{},l="string"==typeof o.markdown?o.markdown:"string"==typeof o.content?o.content:"";return{text:"text"===e.extractMode?(0,s.it)(l):l,title:o.metadata?.title,finalUrl:o.metadata?.sourceURL,status:o.metadata?.statusCode,warning:a?.warning}}async function u(e){let t,r,i,a=(0,n.dU)(`fetch:${e.url}:${e.extractMode}:${e.maxChars}`),o=(0,n.xe)(g,a);if(o)return{...o.value,cached:!0};try{t=new URL(e.url)}catch{throw Error("Invalid URL: must be http or https")}if(!["http:","https:"].includes(t.protocol))throw Error("Invalid URL: must be http or https");let l=Date.now(),u=e.url;try{let t=await d({url:e.url,maxRedirects:e.maxRedirects,timeoutSeconds:e.timeoutSeconds,userAgent:e.userAgent});r=t.response,u=t.finalUrl}catch(t){if(e.firecrawlEnabled&&e.firecrawlApiKey){let t=await c({url:u,extractMode:e.extractMode,apiKey:e.firecrawlApiKey,baseUrl:e.firecrawlBaseUrl,onlyMainContent:e.firecrawlOnlyMainContent,maxAgeMs:e.firecrawlMaxAgeMs,proxy:e.firecrawlProxy,storeInCache:e.firecrawlStoreInCache,timeoutSeconds:e.firecrawlTimeoutSeconds}),r=(0,s.EJ)(t.text,e.maxChars),i={url:e.url,finalUrl:t.finalUrl||u,status:t.status??200,contentType:"text/markdown",title:t.title,extractMode:e.extractMode,extractor:"firecrawl",truncated:r.truncated,length:r.text.length,fetchedAt:new Date().toISOString(),tookMs:Date.now()-l,text:r.text,warning:t.warning};return(0,n.aR)(g,a,i,e.cacheTtlMs),i}throw t}if(!r.ok){if(e.firecrawlEnabled&&e.firecrawlApiKey){let t=await c({url:e.url,extractMode:e.extractMode,apiKey:e.firecrawlApiKey,baseUrl:e.firecrawlBaseUrl,onlyMainContent:e.firecrawlOnlyMainContent,maxAgeMs:e.firecrawlMaxAgeMs,proxy:e.firecrawlProxy,storeInCache:e.firecrawlStoreInCache,timeoutSeconds:e.firecrawlTimeoutSeconds}),i=(0,s.EJ)(t.text,e.maxChars),o={url:e.url,finalUrl:t.finalUrl||u,status:t.status??r.status,contentType:"text/markdown",title:t.title,extractMode:e.extractMode,extractor:"firecrawl",truncated:i.truncated,length:i.text.length,fetchedAt:new Date().toISOString(),tookMs:Date.now()-l,text:i.text,warning:t.warning};return(0,n.aR)(g,a,o,e.cacheTtlMs),o}let t=await (0,n.BQ)(r),i=function(e){let{detail:t,contentType:r,maxChars:i}=e;if(!t)return"";let a=t,o=r?.toLowerCase();if(o?.includes("text/html")||function(e){let t=e.trimStart();if(!t)return!1;let r=t.slice(0,256).toLowerCase();return r.startsWith("<!doctype html")||r.startsWith("<html")}(t)){let e=(0,s.Yj)(t),r=e.title?`${e.title}
|
|
323
|
+
${e.text}`:e.text;a=(0,s.it)(r)}return(0,s.EJ)(a.trim(),i).text}({detail:t,contentType:r.headers.get("content-type"),maxChars:4e3});throw Error(`Web fetch failed (${r.status}): ${i||r.statusText}`)}let m=r.headers.get("content-type")??"application/octet-stream",h=await (0,n.BQ)(r),f="raw",k=h;if(m.includes("text/html"))if(e.readabilityEnabled){let t=await (0,s.rm)({html:h,url:u,extractMode:e.extractMode});if(t?.text)k=t.text,i=t.title,f="readability";else{let t=await p({...e,url:u});if(t)k=t.text,i=t.title,f="firecrawl";else throw Error("Web fetch extraction failed: Readability and Firecrawl returned no content.")}}else throw Error("Web fetch extraction failed: Readability disabled and Firecrawl unavailable.");else if(m.includes("application/json"))try{k=JSON.stringify(JSON.parse(h),null,2),f="json"}catch{k=h,f="raw"}let w=(0,s.EJ)(k,e.maxChars),v={url:e.url,finalUrl:u,status:r.status,contentType:m,title:i,extractMode:e.extractMode,extractor:f,truncated:w.truncated,length:w.text.length,fetchedAt:new Date().toISOString(),tookMs:Date.now()-l,text:w.text};return(0,n.aR)(g,a,v,e.cacheTtlMs),v}async function p(e){if(!e.firecrawlEnabled||!e.firecrawlApiKey)return null;try{let t=await c({url:e.url,extractMode:e.extractMode,apiKey:e.firecrawlApiKey,baseUrl:e.firecrawlBaseUrl,onlyMainContent:e.firecrawlOnlyMainContent,maxAgeMs:e.firecrawlMaxAgeMs,proxy:e.firecrawlProxy,storeInCache:e.firecrawlStoreInCache,timeoutSeconds:e.firecrawlTimeoutSeconds});return{text:t.text,title:t.title}}catch{return null}}function m(e){var t,r;let i,a,s,l=function(e){let t=e?.tools?.web?.fetch;if(t&&"object"==typeof t)return t}(e?.config);if(t={fetch:l,sandboxed:e?.sandboxed},"boolean"==typeof t.fetch?.enabled&&!t.fetch.enabled)return null;let d="boolean"!=typeof l?.readability||l.readability,c=function(e){if(!e||"object"!=typeof e)return;let t=e.firecrawl;if(t&&"object"==typeof t)return t}(l),p=(i=c&&"string"==typeof c.apiKey?c.apiKey.trim():"",a=(process.env.FIRECRAWL_API_KEY??"").trim(),i||a||void 0),m=(r={firecrawl:c,apiKey:p},"boolean"==typeof r.firecrawl?.enabled?r.firecrawl.enabled:!!r.apiKey),g=(c&&"string"==typeof c.baseUrl?c.baseUrl.trim():"")||h,k="boolean"!=typeof c?.onlyMainContent||c.onlyMainContent,w=(s=function(e){let t=e&&"number"==typeof e.maxAgeMs?e.maxAgeMs:void 0;if("number"!=typeof t||!Number.isFinite(t))return;let r=Math.max(0,Math.floor(t));return r>0?r:void 0}(c),"number"==typeof s?s:1728e5),v=(0,n.vc)(c?.timeoutSeconds??l?.timeoutSeconds,30),y=l&&"string"==typeof l.userAgent&&l.userAgent||"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";return{label:"Web Fetch",name:"web_fetch",description:"Fetch and extract readable content from a URL (HTML → markdown/text). Use for lightweight page access without browser automation.",parameters:f,execute:async(e,t)=>{var r,i;let a,s,c=t&&"object"==typeof t?t:{},h=(0,o.h_)(c,"url",{required:!0}),f="text"===(0,o.h_)(c,"extractMode")?"text":"markdown",b=(0,o.jV)(c,"maxChars",{integer:!0}),S=await u({url:h,extractMode:f,maxChars:(r=b??l?.maxChars,a="number"==typeof r&&Number.isFinite(r)?r:5e4,Math.max(100,Math.floor(a))),maxRedirects:(i=l?.maxRedirects,s="number"==typeof i&&Number.isFinite(i)?i:3,Math.max(0,Math.floor(s))),timeoutSeconds:(0,n.vc)(l?.timeoutSeconds,30),cacheTtlMs:(0,n.d6)(l?.cacheTtlMinutes,15),userAgent:y,readabilityEnabled:d,firecrawlEnabled:m,firecrawlApiKey:p,firecrawlBaseUrl:g,firecrawlOnlyMainContent:k,firecrawlMaxAgeMs:w,firecrawlProxy:"auto",firecrawlStoreInCache:!0,firecrawlTimeoutSeconds:v});return(0,o.Ao)(S)}}}i()}catch(e){i(e)}})},3124(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Q:()=>u});var a=r(4204),o=r(3122),n=r(178),s=e([a,n]);[a,n]=s.then?(await s)():s;let p="Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",m=a.Type.Object({url:a.Type.String({description:"HTTP or HTTPS URL to fetch through proxy."}),apiKey:a.Type.Optional(a.Type.String({description:"ScraperAPI API key. If not provided, will use SCRAPERAPI_API_KEY environment variable."})),render:a.Type.Optional(a.Type.Boolean({description:"Enable JavaScript rendering. Default: false."})),countryCode:a.Type.Optional(a.Type.String({description:"Country code for geotargeting (e.g., 'us', 'gb', 'de')."})),premium:a.Type.Optional(a.Type.Boolean({description:"Use premium residential proxies. Default: false."})),sessionNumber:a.Type.Optional(a.Type.Number({description:"Session number for sticky sessions (keep same IP across requests)."})),deviceType:a.Type.Optional(a.Type.String({description:"Device type ('desktop', 'mobile', 'tablet'). Default: 'desktop'."})),timeoutSeconds:a.Type.Optional(a.Type.Number({description:"Timeout in seconds. Default: 30."})),maxRetries:a.Type.Optional(a.Type.Number({description:"Maximum number of retries on failure. Default: 2."})),retryDelayMs:a.Type.Optional(a.Type.Number({description:"Delay between retries in milliseconds. Default: 1000."})),maxRedirects:a.Type.Optional(a.Type.Number({description:"Maximum number of redirects to follow. Default: 3."})),userAgent:a.Type.Optional(a.Type.String({description:"Custom User-Agent header. Default: modern Chrome user agent."})),keepHeaders:a.Type.Optional(a.Type.Boolean({description:"Include response headers in result. Default: false."})),maxChars:a.Type.Optional(a.Type.Number({description:"Max length of body in result when text/HTML (truncated if exceeded). Default 32000 to avoid LLM request size limits.",default:32e3}))});async function l(e,t){let r,{timeoutSeconds:i=30,maxRetries:a=2,retryDelayMs:o=1e3,userAgent:n=p,maxRedirects:s=3}=t,l={headers:{"User-Agent":n},redirect:"follow"};for(let t=0;t<=a;t++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3*i),a=await fetch(e,{...l,signal:t.signal});return clearTimeout(r),a.redirected&&a.url,a}catch(e){if(r=e,t<a){let e=o*Math.pow(2,t);await function(e){return new Promise(t=>setTimeout(t,e))}(e)}}throw Error(`Failed to fetch after ${a+1} attempts: ${r?.message||"Unknown error"}`)}async function d(e,t){let r=e.headers.get("content-type")||"",i=e.headers.get("content-length"),a={url:e.url,status:e.status,statusText:e.statusText,contentType:r,contentLength:i?parseInt(i,10):null,fetchedAt:new Date().toISOString()};if(t){let t={};e.headers.forEach((e,r)=>{t[r]=e}),a.headers=t}if(r.includes("application/json"))a.body=await e.json();else if(r.includes("text/")||r.includes("application/xml")||r.includes("application/xhtml+xml"))a.body=await e.text();else{let t=await e.arrayBuffer();a.body=Buffer.from(t).toString("base64")}return a}async function c(e){let t=(0,o.h_)(e,"url",{required:!0}),r=function(e){let t=(0,o.h_)(e,"apiKey");if(t)return t;let r=process.env.SCRAPERAPI_API_KEY;if(r&&"string"==typeof r&&r.trim())return r.trim();throw Error("apiKey required")}(e),i=(0,o.GE)(e,"render",{defaultValue:!1}),a=(0,o.h_)(e,"countryCode"),s=(0,o.GE)(e,"premium",{defaultValue:!1}),c=(0,o.jV)(e,"sessionNumber"),u=(0,o.h_)(e,"deviceType",{defaultValue:"desktop"}),m=(0,o.jV)(e,"timeoutSeconds",{defaultValue:30}),h=(0,o.jV)(e,"maxRetries",{defaultValue:2}),g=(0,o.jV)(e,"retryDelayMs",{defaultValue:1e3}),f=(0,o.jV)(e,"maxRedirects",{defaultValue:3}),k=(0,o.h_)(e,"userAgent",{defaultValue:p}),w=(0,o.GE)(e,"keepHeaders",{defaultValue:!1}),v=(0,o.jV)(e,"maxChars",{integer:!0}),y="number"==typeof v&&v>=100?Math.min(v,5e5):32e3;try{new URL(t)}catch{throw Error(`Invalid URL: ${t}`)}let b=function(e,t){let{apiKey:r,render:i,countryCode:a,premium:o,sessionNumber:n,deviceType:s,url:l}=t,d=new URLSearchParams;return d.set("api_key",r),!0===i&&d.set("render","true"),a&&d.set("country_code",a),!0===o&&d.set("premium","true"),void 0!==n&&d.set("session_number",n.toString()),s&&d.set("device_type",s),d.set("url",l),`${e}?${d.toString()}`}("https://api.scraperapi.com",{apiKey:r,render:i,countryCode:a,premium:s,sessionNumber:c,deviceType:u,url:t}),S=Date.now();try{let e=await l(b,{timeoutSeconds:m,maxRetries:h,retryDelayMs:g,userAgent:k,maxRedirects:f}),t=await d(e,w),o=Date.now(),p=t.contentType&&/^image\//i.test(t.contentType);if("string"==typeof t.body){let e=p?Math.min(y,n.Bz):y;t.body.length>e&&(t.bodyLength=t.body.length,t.body=t.body.slice(0,e),t.bodyTruncated=!0,t.maxChars=e,p&&(t.bodyOmittedReason="Image truncated for request size limit."))}else if("object"==typeof t.body&&null!==t.body){let e=JSON.stringify(t.body);e.length>y&&(t.bodyLength=e.length,t.body=e.slice(0,y),t.bodyTruncated=!0,t.maxChars=y)}return t.tookMs=o-S,t.scraperApiParams={render:i,countryCode:a||null,premium:s,sessionNumber:c||null,deviceType:u,usedApiKey:r.substring(0,8)+"..."+r.substring(r.length-4)},t}catch(t){let e=Date.now();throw Error(`Proxy fetch failed after ${e-S}ms: ${t.message}`)}}function u(e){let t=e?.config?.tools?.proxy;return t?.enabled===!1?null:{label:"Proxy Downloader",name:"proxy_downloader",description:"Fetch HTTP(S) URLs through ScraperAPI proxy service. Supports JavaScript rendering, geotargeting, premium proxies, and sticky sessions.",parameters:m,execute:async(e,t)=>{let r=await c(t);return(0,o.Ao)(r)}}}i()}catch(e){i(e)}})},1942(e,t,r){r.a(e,async function(e,i){try{r.d(t,{t:()=>u});var a=r(4204),o=r(3122),n=r(4671),s=e([a]);a=(s.then?(await s)():s)[0];let p="https://openrouter.ai/api/v1",m="https://api.perplexity.ai",h="perplexity/sonar-pro",g=["pplx-"],f=["sk-or-"],k=new Map,w=a.Type.Object({query:a.Type.String({description:"Search query string."}),count:a.Type.Optional(a.Type.Number({description:"Number of results to return (1-10).",minimum:1,maximum:10})),country:a.Type.Optional(a.Type.String({description:"2-letter country code for region-specific results (e.g., 'DE', 'US', 'ALL'). Default: 'US'."})),search_lang:a.Type.Optional(a.Type.String({description:"ISO language code for search results (e.g., 'de', 'en', 'fr')."})),ui_lang:a.Type.Optional(a.Type.String({description:"ISO language code for UI elements."}))});function l(e){return"string"==typeof e?e.trim():""}async function d(e){let t=`${e.baseUrl.replace(/\/$/,"")}/chat/completions`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`,"HTTP-Referer":"https://clawdbot.com","X-Title":"Web Search"},body:JSON.stringify({model:e.model,messages:[{role:"user",content:e.query}]}),signal:(0,n.wj)(void 0,1e3*e.timeoutSeconds)});if(!r.ok){let e=await (0,n.BQ)(r);throw Error(`Perplexity API error (${r.status}): ${e||r.statusText}`)}let i=await r.json(),a=i.choices?.[0]?.message?.content??"No response",o=i.citations??[];return{content:a,citations:o}}async function c(e){let t=(0,n.dU)(`${e.provider}:${e.query}:${e.count}:${e.country||"default"}:${e.search_lang||"default"}:${e.ui_lang||"default"}`),r=(0,n.xe)(k,t);if(r)return{...r.value,cached:!0};let i=Date.now();if("perplexity"===e.provider){let{content:r,citations:a}=await d({query:e.query,apiKey:e.apiKey,baseUrl:e.perplexityBaseUrl??p,model:e.perplexityModel??h,timeoutSeconds:e.timeoutSeconds}),o={query:e.query,provider:e.provider,model:e.perplexityModel??h,tookMs:Date.now()-i,content:r,citations:a};return(0,n.aR)(k,t,o,e.cacheTtlMs),o}if("brave"!==e.provider)throw Error("Unsupported web search provider.");let a=new URL("https://api.search.brave.com/res/v1/web/search");a.searchParams.set("q",e.query),a.searchParams.set("count",String(e.count)),e.country&&a.searchParams.set("country",e.country),e.search_lang&&a.searchParams.set("search_lang",e.search_lang),e.ui_lang&&a.searchParams.set("ui_lang",e.ui_lang);let o=await fetch(a.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":e.apiKey},signal:(0,n.wj)(void 0,1e3*e.timeoutSeconds)});if(!o.ok){let e=await (0,n.BQ)(o);throw Error(`Brave Search API error (${o.status}): ${e||o.statusText}`)}let s=await o.json(),l=(Array.isArray(s.web?.results)?s.web?.results??[]:[]).map(e=>({title:e.title??"",url:e.url??"",description:e.description??"",published:e.age??void 0,siteName:function(e){if(e)try{return new URL(e).hostname}catch{return}}(e.url??"")})),c={query:e.query,provider:e.provider,count:l.length,tookMs:Date.now()-i,results:l};return(0,n.aR)(k,t,c,e.cacheTtlMs),c}function u(e){var t;let r,i=function(e){let t=e?.tools?.web?.search;if(t&&"object"==typeof t)return t}(e?.config);if(t={search:i,sandboxed:e?.sandboxed},"boolean"==typeof t.search?.enabled&&!t.search.enabled)return null;let a=(r=i&&"string"==typeof i.provider?i.provider.trim().toLowerCase():"","perplexity"===r?"perplexity":"brave"),s=function(e){if(!e||"object"!=typeof e)return{};let t=e.perplexity;return t&&"object"==typeof t?t:{}}(i),d="perplexity"===a?"Search the web using Perplexity Sonar (direct or via OpenRouter). Returns AI-synthesized answers with citations from real-time web search.":"Search the web using Brave Search API. Supports region-specific and localized search via country and language parameters. Returns titles, URLs, and snippets for fast research.";return{label:"Web Search",name:"web_search",description:d,parameters:w,execute:async(e,t)=>{let r,d,u,k="perplexity"===a?function(e){let t=l(e?.apiKey);if(t)return{apiKey:t,source:"config"};let r=l(process.env.PERPLEXITY_API_KEY);if(r)return{apiKey:r,source:"perplexity_env"};let i=l(process.env.OPENROUTER_API_KEY);return i?{apiKey:i,source:"openrouter_env"}:{apiKey:void 0,source:"none"}}(s):void 0,w="perplexity"===a?k?.apiKey:(r=i&&"string"==typeof i.apiKey?i.apiKey.trim():"",d=(process.env.BRAVE_API_KEY??"").trim(),r||d||void 0);if(!w)return(0,o.Ao)("perplexity"===a?{error:"missing_perplexity_api_key",message:"web_search (perplexity) needs an API key. Set PERPLEXITY_API_KEY or OPENROUTER_API_KEY, or configure tools.web.search.perplexity.apiKey."}:{error:"missing_brave_api_key",message:"web_search needs a Brave Search API key. Set BRAVE_API_KEY in the environment or configure tools.web.search.apiKey."});let v=t&&"object"==typeof t?t:{},y=(0,o.h_)(v,"query",{required:!0}),b=(0,o.jV)(v,"count",{integer:!0})??i?.maxResults,S=(0,o.h_)(v,"country"),T=(0,o.h_)(v,"search_lang"),E=(0,o.h_)(v,"ui_lang"),x=await c({query:y,count:(u="number"==typeof b&&Number.isFinite(b)?b:5,Math.max(1,Math.min(10,Math.floor(u)))),apiKey:w,timeoutSeconds:(0,n.vc)(i?.timeoutSeconds,30),cacheTtlMs:(0,n.d6)(i?.cacheTtlMinutes,15),provider:a,country:S,search_lang:T,ui_lang:E,perplexityBaseUrl:function(e,t,r){let i=e&&"string"==typeof e.baseUrl?e.baseUrl.trim():"";if(i)return i;if("perplexity_env"===t)return m;if("openrouter_env"===t)return p;if("config"===t){let e=function(e){if(!e)return;let t=e.toLowerCase();return g.some(e=>t.startsWith(e))?"direct":f.some(e=>t.startsWith(e))?"openrouter":void 0}(r);if("direct"===e)return m}return p}(s,k?.source,k?.apiKey),perplexityModel:(s&&"string"==typeof s.model?s.model.trim():"")||h});return(0,o.Ao)(x)}}}i()}catch(e){i(e)}})},4671(e,t,r){function i(e,t){return Math.max(1,Math.floor("number"==typeof e&&Number.isFinite(e)?e:t))}function a(e,t){return Math.round(6e4*("number"==typeof e&&Number.isFinite(e)?Math.max(0,e):t))}function o(e){return e.trim().toLowerCase()}function n(e,t){let r=e.get(t);return r?Date.now()>r.expiresAt?(e.delete(t),null):{value:r.value,cached:!0}:null}function s(e,t,r,i){if(!(i<=0)){if(e.size>=100){let t=e.keys().next();t.done||e.delete(t.value)}e.set(t,{value:r,expiresAt:Date.now()+i,insertedAt:Date.now()})}}function l(e,t){if(t<=0)return e??new AbortController().signal;let r=new AbortController,i=setTimeout(()=>r.abort(),t);return e&&e.addEventListener("abort",()=>{clearTimeout(i),r.abort()},{once:!0}),r.signal.addEventListener("abort",()=>clearTimeout(i),{once:!0}),r.signal}async function d(e){try{return await e.text()}catch{return""}}r.d(t,{BQ:()=>d,aR:()=>s,d6:()=>a,dU:()=>o,vc:()=>i,wj:()=>l,xe:()=>n})},3591(e,t,r){r.a(e,async function(e,i){try{r.d(t,{H:()=>g,f:()=>f});var a=r(4204),o=r(3122),n=e([a]);a=(n.then?(await n)():n)[0];let k="black-forest-labs/flux.2-pro";function s(){let e=process.env.WECHAT_APPID?.trim(),t=process.env.WECHAT_SECRET?.trim(),r=process.env.OPENROUTER_API_KEY?.trim();return e&&t&&r?{appId:e,secret:t,openRouterKey:r,imageModel:process.env.OPENROUTER_IMAGE_MODEL?.trim()||k,author:process.env.WECHAT_AUTHOR?.trim()||"田威 AI",defaultCoverUrl:process.env.DEFAULT_COVER_URL?.trim()||void 0}:null}async function l(e){let t=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${e.appId}&secret=${e.secret}`,r=await fetch(t),i=await r.json(),a=i?.access_token;if(!a||"string"!=typeof a)throw Error(`Failed to get WeChat token: ${JSON.stringify(i)}`);return a}async function d(e,t,r="16:9"){let i="1:1"!==r?` Aspect ratio: ${r}.`:"",a=`${i} ${t}`.trim(),o=JSON.stringify({model:e.imageModel||k,messages:[{role:"user",content:a}],modalities:["image"]}),n=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${e.openRouterKey}`,"Content-Type":"application/json","HTTP-Referer":process.env.OPENROUTER_REFERRER||"https://github.com/pithosai"},body:o}),s=await n.json();if(!n.ok)throw Error(`OpenRouter API error: ${n.status} ${JSON.stringify(s)}`);let l=s?.choices?.[0]?.message,c=l?.images??l?.content?.filter?.(e=>e?.type==="image"),u=c?.[0]?.image_url?.url??c?.[0]?.imageUrl?.url??c?.[0]?.url;return{output:u||null,status:u?"succeeded":"failed"}}async function c(e){if(e.startsWith("data:")){let t=e.replace(/^data:image\/\w+;base64,/,"");return Buffer.from(t,"base64")}let t=await fetch(e);if(!t.ok)throw Error(`Failed to download image: ${t.status}`);let r=await t.arrayBuffer();return Buffer.from(r)}async function u(e,t,r="cover.png"){let i=new FormData,a=new Blob([t],{type:"image/png"});i.append("media",a,r);let o=await fetch(`https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${e}&type=image`,{method:"POST",body:i}),n=await o.json();if(n?.errcode&&0!==n.errcode)throw Error(`WeChat upload failed: ${n.errmsg||JSON.stringify(n)}`);return n}async function p(e,t){let r=JSON.stringify({articles:[{title:t.title,author:t.author,digest:t.digest,content:t.content,thumb_media_id:t.thumb_media_id,need_open_comment:1,only_fans_can_comment:0}]}),i=await fetch(`https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:r}),a=await i.json();if(a?.errcode&&0!==a.errcode)throw Error(`WeChat draft failed: ${a.errmsg||JSON.stringify(a)}`);return a}async function m(e,t,r){let i=(await d(e,t,"16:9")).output;if(i&&!i.startsWith("ERROR"))return{buffer:await c(i)};if(e.defaultCoverUrl)return{buffer:await c(e.defaultCoverUrl)};throw Error("Failed to generate cover and no DEFAULT_COVER_URL provided")}let w=a.Type.Object({title:a.Type.String({description:"WeChat article title."}),content_html:a.Type.String({description:"WeChat article body in HTML."}),cover_prompt:a.Type.String({description:"Prompt for generating the WeChat article cover image."}),digest:a.Type.String({description:"Short summary shown in WeChat article list (recommended 50–100 chars)."})});async function h(e,t){let r=Date.now().toString(36),i=await l(e),{buffer:a}=await m(e,t.cover_prompt,r),o=(await u(i,a,`wechat_cover_${r}.png`)).media_id;if(!o)return{success:!1,error:"Failed to upload cover image"};let n=(await p(i,{title:t.title,author:e.author||"Pithosai AI",digest:t.digest,content:t.content_html,thumb_media_id:o})).media_id;return n?{success:!0,draft_media_id:n}:{success:!1,error:"Failed to create draft"}}function g(){let e=s();return e?{label:"WeChat: Publish Article",name:"wechat_publish_article",description:"Publish an article to WeChat Official Account (公众号) draft box. Generates a cover image, uploads it to WeChat material library, and creates a draft. For WeChat platform only.",parameters:w,execute:async(t,r)=>{let i=r&&"object"==typeof r?r:{},a=(0,o.h_)(i,"title",{required:!0}),n=(0,o.h_)(i,"content_html",{required:!0}),s=(0,o.h_)(i,"cover_prompt",{required:!0}),l=(0,o.h_)(i,"digest",{required:!0});if(!a||!n||!s||!l)throw Error("title, content_html, cover_prompt, and digest are required");try{let t=await h(e,{title:a,content_html:n,cover_prompt:s,digest:l});return(0,o.Ao)(t)}catch(e){return(0,o.Ao)({success:!1,error:e?.message||String(e)})}}}:null}function f(){let e=s();if(!e)return null;let t=a.Type.Object({prompt:a.Type.String({description:"Prompt for WeChat article cover image."}),aspect_ratio:a.Type.Optional(a.Type.Union([a.Type.Literal("1:1"),a.Type.Literal("16:9"),a.Type.Literal("9:16"),a.Type.Literal("4:3"),a.Type.Literal("3:4")],{description:"Cover aspect ratio. Default: 16:9."}))});return{label:"WeChat: Generate Cover Image",name:"wechat_generate_cover_image",description:"Generate a cover image for WeChat Official Account articles. For WeChat platform only. Use before or alongside wechat_publish_article.",parameters:t,execute:async(t,r)=>{let i=r&&"object"==typeof r?r:{},a=(0,o.h_)(i,"prompt",{required:!0}),n=(0,o.h_)(i,"aspect_ratio")||"16:9";if(!a)throw Error("prompt is required");try{let t=await d(e,a,n),r=t.output;return(0,o.Ao)({success:!0,image_url:r,status:t.status})}catch(e){return(0,o.Ao)({success:!1,error:e?.message||String(e)})}}}}i()}catch(e){i(e)}})},6652(e,t,r){r.a(e,async function(e,i){try{r.d(t,{e:()=>d});var a=r(6760),o=r(8476),n=r(8362),s=r(1048),l=e([n,s,o]);function d(e,t){return e.command("add-role <role>").description(t("cli.addRoleDescription")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-l, --lang <lang>",t("cli.langOption")).action(async(t,r)=>{let i=(0,a.resolve)(r.cwd||process.cwd()),l=e.opts(),d=r.lang??l.lang??(0,n.a)();await (0,s.e)(i,e.opts().logPath),await (0,o.Cm)(i,t,d)})}[n,s,o]=l.then?(await l)():l,i()}catch(e){i(e)}})},829(e,t,r){r.a(e,async function(e,i){try{r.d(t,{w:()=>u});var a=r(481),o=r(4267),n=r(1224),s=r(8601),l=r(4071),d=e([l]);async function c(e,t,r={}){let i=!1!==r.allowRequestEdit,o=r.tuiSession??null,n="function"==typeof o?.writeLn?o.writeLn.bind(o):"function"==typeof o?.appendLine?o.appendLine.bind(o):null,d=r.io?.writeLn??n??(e=>process.stdout.write(e+"\n")),u=!!(o&&"function"==typeof o.readSubmittedLine),p=u?null:(0,a.createInterface)({input:process.stdin,output:process.stdout,completer:(0,s.Q$)()});d(""),d(t("run.pauseHeader")),d(t("run.pauseCurrentRequest",{request:e.currentRequest??""})),d(t("run.pauseHelp"));try{for(;;){u&&("function"==typeof o.ensureInputEditorActive&&o.ensureInputEditorActive(),d(t("run.pausePrompt")));let r=((u?await o.readSubmittedLine():await function(e,t){return new Promise(r=>{e.question(t,e=>r(e??""))})}(p,t("run.pausePrompt")))??"").trim(),a=r.toLowerCase();if((0,l.IW)("pauseSubPrompt",JSON.stringify({cmd:a,line:r})),"continue"===a||"c"===a)return p?.close(),{action:"continue",request:e.currentRequest};if("exit"===a||"e"===a)return p?.close(),{action:"exit",request:null};if(""!==r){if(!i){d(t("run.pauseHelp"));continue}e.updateRequest(r),d(t("run.pauseRequestUpdated",{request:r}))}}}finally{p?.close()}}async function u(e,t){let{controller:r,t:i,execute:a,allowRequestEdit:s=!0,useKeypressInterceptor:l=!0,tuiSession:d=null,io:u=null}=t,p=[e?.title??"",e?.description??""].filter(Boolean).join("\n\n"),m="function"==typeof d?.writeLn?d.writeLn.bind(d):"function"==typeof d?.appendLine?d.appendLine.bind(d):null,h=u?.writeLn??m??(e=>process.stdout.write(e+"\n"));for(;;){r.reset();let t=l?(0,n.c)(r):()=>{};try{await a(e,p)}finally{t()}if(r.status===o.i.PAUSED){let e;d&&"function"!=typeof d.readSubmittedLine&&d.suspendForReadline();try{e=await c(r,i,{allowRequestEdit:s,tuiSession:d,io:u})}finally{d&&"function"!=typeof d.readSubmittedLine&&d.resumeFromReadline()}if("exit"===e.action){h(i("run.agentStopped")),r.reset(),"function"==typeof d?.ensureInputEditorActive&&d.ensureInputEditorActive();break}p=e.request??p,r.resume(),"function"==typeof d?.ensureInputEditorActive&&d.ensureInputEditorActive();continue}r.status===o.i.STOPPED&&(h(i("run.agentStopped")),r.reset(),"function"==typeof d?.ensureInputEditorActive&&d.ensureInputEditorActive());break}}l=(d.then?(await d)():d)[0],i()}catch(e){i(e)}})},9766(e,t,r){r.a(e,async function(e,i){try{r.d(t,{$i:()=>b,YP:()=>m,Ym:()=>h,d1:()=>g});var a=r(4127),o=r(8601),n=r(9782),s=r(8691),l=e([a,s]);function d(e){return String(e).replace(/(?:\.{3}|…)((?:\u001b\[[0-9;]*m)*)$/u,"$1")}function c(e,t){let r=(0,a.truncateToWidth)(String(e??""),Math.max(0,t)),i=Math.max(0,t-(0,a.visibleWidth)(r));return r+" ".repeat(i)}function u(){process.stdout.write("\x1b[?1006h\x1b[?1002h\x1b[?1000h")}function p(){process.stdout.write("\x1b[?1006l\x1b[?1002l\x1b[?1000l")}[a,s]=l.then?(await l)():l;class f{constructor(){this.lines=[],this.maxLines=8e3,this._viewportPinLine=null}setViewportPin(e){this._viewportPinLine=Math.max(0,e)}clearViewportPin(){this._viewportPinLine=null}appendLine(e){if(this.lines.push(e),this.lines.length>this.maxLines){let e=this.lines.length-this.maxLines;this.lines=this.lines.slice(-this.maxLines),null!=this._viewportPinLine&&(this._viewportPinLine=Math.max(0,this._viewportPinLine-e))}}appendRaw(e){0===this.lines.length?this.lines.push(e):this.lines[this.lines.length-1]+=e}viewportLines(e,t){if(0===this.lines.length)return[""];let r=Math.max(1,e),i=this.lines.length,o=Math.max(0,i-r),n=o;return null!=this._viewportPinLine&&(n=Math.min(Math.max(0,this._viewportPinLine),o)),this.lines.slice(n,n+r).map(e=>(0,a.truncateToWidth)(e,t))}tailLines(e,t){return this.viewportLines(e,t)}bumpViewStart(e,t){let r=Math.max(1,t),i=this.lines.length;if(0===i)return;let a=Math.max(0,i-r),o=null!=this._viewportPinLine?Math.min(this._viewportPinLine,a):a;this._viewportPinLine=Math.max(0,Math.min(a,o+e))}}class k{constructor(e,t){this.tui=e,this.getMessage=t,this.intervalId=null,this.frame=0,this.active=!1,this.preserveReservedRows=!1,this.phase="loading"}_startTick(e){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.intervalId=setInterval(()=>{let e="loading"===this.phase?n.d2.length:n.Mm.length;this.frame=(this.frame+1)%e,this.tui.requestRender()},e)}setActive(e){e!==this.active&&(this.active=e,e?(this.preserveReservedRows=!0,this.phase="loading",this.frame=0,this._startTick(80)):this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null))}enterRunningPhase(){this.active&&"running"!==this.phase&&(this.phase="running",this.frame=0,this._startTick(120),this.tui.requestRender())}isActive(){return this.active}isRunningPhase(){return this.active&&"running"===this.phase}reservedHeight(){return this.active||this.preserveReservedRows?3:0}render(e){if(!this.active)return[c("",e)];let t="loading"===this.phase?n.d2:n.Mm,r=t[this.frame%t.length],i=this.getMessage()??"";return[(0,a.truncateToWidth)(`${r} ${i}`,e)]}invalidate(){}}class w{constructor(e,t){this.focused=!1,this.editor=new a.Editor(e,{borderColor:e=>s.m.dim(e),selectList:{selectedPrefix:e=>s.m.cyan.bold(e),selectedText:e=>s.m.cyan(e),description:e=>s.m.dim(e),scrollInfo:e=>s.m.dim(e),noMatch:e=>s.m.yellow(e)}},{paddingX:1,autocompleteMaxVisible:8}),this.editor.setAutocompleteProvider((0,o.ML)(t))}isAutocompleteActive(){return this.editor.isShowingAutocomplete()}handleInput(e){(0,a.matchesKey)(e,"ctrl+d")&&!this.editor.getText().trim()&&process.exit(0),this.editor.handleInput(e)}render(e){let t,r;this.editor.focused=this.focused;let i=Math.max(3,e-2),o=this.editor.render(i);if(o.length<2)return o;let n=Math.max(1,i-2*this.editor.getPaddingX()),l=this.editor.isShowingAutocomplete()&&this.editor.autocompleteList?this.editor.autocompleteList.render(n).length:0,u=o.length-l-1;if(u<1)return o;let p=o.slice(1,u),m=o.slice(u+1),h=s.m.cyan(" → "),g=p.map((e,t)=>{let r=d((0,a.truncateToWidth)(d(e??""),i));if(0!==t)return c(r,i);let o=d((0,a.truncateToWidth)(r,Math.max(0,i-3)));return`${h}${c(o,Math.max(0,i-3))}`}),f=(t=`┌${"─".repeat(i)}┐`,s.m.cyan(t)),k=(r=`└${"─".repeat(i)}┘`,s.m.cyan(r)),w=e=>s.m.cyan("│")+e+s.m.cyan("│"),v=[f];for(let e of g)v.push(w(e));for(let e of(v.push(k),m))v.push(w(e));return v}invalidate(){this.editor.invalidate()}}class v{constructor(e){let{terminal:t,transcript:r,loading:i,prompt:a}=e;this.terminal=t,this.transcript=r,this.loading=i,this.prompt=a,this.focused=!1}handleInput(e){this.prompt.focused=this.focused,this.prompt.handleInput(e)}invalidate(){this.prompt.invalidate()}render(e){this.prompt.focused=this.focused;let t=this.terminal.rows,r=this.prompt.render(e),i=this.loading.reservedHeight(),a=i>0?[c("",e),...this.loading.render(e),c("",e)]:[],o=Math.max(1,t-r.length-i),n=this.transcript.viewportLines(o,e);for(;n.length<o;)n.push(c("",e));return n.length>o&&(n=n.slice(0,o)),[...n,...a,...r]}}class y extends a.TUI{constructor(e){super(e),this.agentRunning=!1,this.agentController=null,this.onTranscriptPageScroll=null,this.transcriptPageScrollGuard=null,this.onAgentControlNotice=null}setAgentRunning(e,t){this.agentRunning=e,this.agentController=t}handleInput(e){if(this.onTranscriptPageScroll&&this.transcriptPageScrollGuard?.()!==!0){let t=Math.max(3,this.terminal.rows-3),r=Math.max(3,Math.floor(.85*t));if((0,a.matchesKey)(e,"pageUp"))return void this.onTranscriptPageScroll(-r);if((0,a.matchesKey)(e,"pageDown"))return void this.onTranscriptPageScroll(r);if((0,a.matchesKey)(e,"up"))return void this.onTranscriptPageScroll(-1);if((0,a.matchesKey)(e,"down"))return void this.onTranscriptPageScroll(1);if((0,a.matchesKey)(e,"ctrl+u"))return void this.onTranscriptPageScroll(-r);if((0,a.matchesKey)(e,"ctrl+f"))return void this.onTranscriptPageScroll(r)}if(this.agentRunning&&this.agentController){if((0,a.matchesKey)(e,"ctrl+s")){let e=`${s.m.yellow("[Ctrl+S]")} Stopping agent...`;this.onAgentControlNotice?this.onAgentControlNotice(e):process.stdout.write(`
|
|
456
324
|
${e}
|
|
457
|
-
`),this.agentController.stop();return}if((0,
|
|
325
|
+
`),this.agentController.stop();return}if((0,a.matchesKey)(e,"ctrl+p")){let e=`${s.m.yellow("[Ctrl+P]")} Pausing agent...`;this.onAgentControlNotice?this.onAgentControlNotice(e):process.stdout.write(`
|
|
458
326
|
${e}
|
|
459
|
-
`),this.agentController.pause();return}(0,s.matchesKey)(e,"ctrl+c")&&(this.onAgentControlNotice||process.stdout.write("\n"),process.exit(0));return}super.handleInput(e)}}function h(){return"1"!==process.env.PITHOSAI_NO_TUI&&!!(process.stdout.isTTY&&process.stdin.isTTY)}class b{constructor(e){let{t,cwd:i,runOpts:r={}}=e;this.t=t,this.cwd=i,this.runOpts=r,this.terminal=new s.ProcessTerminal,this.tui=new v(this.terminal),this.transcript=new f,this.loadingLine=new w(this.tui,()=>this.loadingMessage),this.loadingMessage="",this.loadingRunningMessage=null,this.loadingPhase=null,this.prompt=new k(this.tui,r),this.layout=new y({terminal:this.terminal,transcript:this.transcript,loading:this.loadingLine,prompt:this.prompt});let o=new s.Container;o.addChild(this.layout),this.tui.addChild(o),this.tui.setFocus(this.layout),this._resolveLine=null,this.prompt.editor.onSubmit=e=>{let t=this._resolveLine;this._resolveLine=null;let i="string"==typeof e?String(e).replace(/^\s*[>→]\s*/u,""):"",r=i.trim();r&&this.prompt.editor.addToHistory(r),this.requestTuiFullRedraw(),t?.(i)},this.tui.onTranscriptPageScroll=e=>this.scrollTranscriptBy(e),this.tui.transcriptPageScrollGuard=()=>this.prompt.isAutocompleteActive(),this.tui.onAgentControlNotice=e=>{this.transcript.appendLine(e),this.transcript.clearViewportPin(),this.requestTuiRedraw()},this.tui.addInputListener(e=>{let t=function(e){let t=String(e).match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);if(!t)return null;let i=parseInt(t[1],10);return 64===i||96===i?-3:65===i||97===i?3:null}(e);if(null!=t&&this.tui.transcriptPageScrollGuard?.()!==!0)return this.scrollTranscriptBy(t),{consume:!0}})}requestTuiRedraw(){this.layout.invalidate(),this.tui.requestRender()}requestTuiRedrawEnsuringInputEditor(){this.prompt.invalidate(),this.layout.invalidate(),this.tui.requestRender()}repaintInputEditorRegion(){let e=this.terminal.columns,t=this.terminal.rows,i=this.prompt.render(e),r=Math.max(1,t-i.length+1),o="\x1b[s";for(let t=0;t<i.length;t++){let a=String(i[t]).replace(s.CURSOR_MARKER,""),n=(0,s.truncateToWidth)(a,e,"",!0);o+=`\x1b[${r+t};1H${n}`}o+="\x1b[u",this.terminal.write(o)}requestTuiFullRedraw(){this.layout.invalidate(),this.tui.requestRender(!0)}scrollTranscriptBy(e){let t=this.terminal.rows,i=this.terminal.columns,r=this.layout.prompt.render(i).length,s=+!!this.loadingLine.isActive(),o=Math.max(1,t-r-s);this.transcript.bumpViewStart(e,o),this.requestTuiRedrawEnsuringInputEditor(),this.repaintInputEditorRegion()}start(){this.tui.start(),u(),this.tui.setFocus(this.layout),this.layout.focused=!0,this.prompt.focused=!0}stop(){this.loadingLine.setActive(!1),p(),this.tui.stop()}suspendForReadline(){this.loadingLine.setActive(!1),p(),this.tui.stop()}resumeFromReadline(){this.tui.start(),u(),this.tui.setFocus(this.layout),this.layout.focused=!0,this.prompt.focused=!0,this.requestTuiFullRedraw()}appendLines(e){for(let t of e)this.transcript.appendLine(t);this.requestTuiRedraw()}appendLine(e){this.transcript.appendLine(e),this.requestTuiRedraw()}clearLoadingIfActive(){this.loadingLine.isActive()&&("waiting"===this.loadingPhase&&this.loadingRunningMessage&&(this.loadingMessage=this.loadingRunningMessage),this.loadingPhase="running",this.loadingLine.enterRunningPhase())}appendAgentChunk(e){if(!e)return;this.clearLoadingIfActive(),this.transcript.clearViewportPin();let t=String(e).split("\n");for(let e=0;e<t.length;e++)e>0&&this.transcript.appendLine(""),t[e]&&this.transcript.appendRaw(t[e]);this.requestTuiRedraw()}setLoading(e,t="",i={}){let{runningMessage:r=null}=i;this.loadingMessage=t,this.loadingRunningMessage=r,this.loadingPhase=e?"waiting":null,this.loadingLine.setActive(e),this.requestTuiRedraw()}getAgentOutputSink(){return{write:(e,t={})=>{"stderr"===t.stream?(this.clearLoadingIfActive(),this.transcript.clearViewportPin(),this.transcript.appendLine(n.m.red(String(e))),this.requestTuiRedraw()):this.appendAgentChunk(String(e))}}}getIo(){return{write:e=>{this.appendAgentChunk(String(e))},writeLn:e=>{let t=String(e).split(/\r?\n/);t.length>0&&""===t[t.length-1]&&(t=t.slice(0,-1)),t.length>0&&this.clearLoadingIfActive();let i=this.transcript.lines.length;for(let e of t)this.transcript.appendLine(e);t.length>=4&&this.transcript.setViewportPin(i),this.requestTuiRedraw()}}}clearTranscriptViewportPin(){this.transcript.clearViewportPin()}attachControllerForRun(e){this.tui.setAgentRunning(!0,{stop:()=>e.stop(),pause:()=>e.pause()})}detachControllerForRun(){this.tui.setAgentRunning(!1,null)}readSubmittedLine(){return new Promise(e=>{this._resolveLine=e})}ensureInputEditorActive(){this.tui.setFocus(this.layout),this.layout.focused=!0,this.prompt.focused=!0,this.requestTuiFullRedraw()}}function m(e){let{session:t,cwd:i,t:r,mode:s}=e;"dialog"===s?t.appendLines([r("run.interactiveModeDialogTitle"),r("run.interactiveModeCwd",{cwd:i}),r("run.interactiveModeDialogTips"),""]):"plan"===s?t.appendLines([r("run.interactiveModePlanTitle"),r("run.interactiveModeCwd",{cwd:i}),r("run.interactiveModePlanTips"),""]):t.appendLines([r("run.interactiveModeAgentTitle"),r("run.interactiveModeCwd",{cwd:i}),r("run.interactiveModeAgentTips"),""])}function g(e,t,i){let r=t.mode??"agent",s=[i("run.interactiveExitHint")];"dialog"===r?s.push(i("run.replIntroDialog")):"plan"===r?s.push(i("run.replIntroPlan")):s.push(i("run.shellHint")),s.push(i("run.newSessionHint"),i("run.controlHint"),i("run.replTabCompletionHint"),i("run.tuiScrollTranscriptHint"),""),e.appendLines(s)}r()}catch(e){r(e)}})},924(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Z:()=>l});var s=i(6760),o=i(6478),a=i(1048),n=e([a,o]);function l(e,t){return e.command("heartbeat").description(t("cli.heartbeatDescription")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("-l, --lang <lang>",t("cli.langOption")).option("--interval <seconds>",t("cli.heartbeatIntervalOption"),"60").option("--once",t("cli.heartbeatOnceOption"),!1).option("--reasoner",t("cli.reasonerOption"),!1).option("--chat",t("cli.chatOption"),!1).option("--cursor [model]",t("cli.cursorOption")).option("--timeout <seconds>",t("cli.timeoutOption")).option("--no-markdown","Plain text output only (default: markdown when TTY)").action(async function(){let t=e.opts(),i=this.optsWithGlobals?this.optsWithGlobals():this.opts(),r=(0,s.resolve)(i.cwd||process.cwd());await (0,a.e)(r,t.logPath);let n=!1!==i.markdown&&!!process.stdout.isTTY,l={role:t.role??i.role,lang:t.lang??i.lang,reasoner:!0===i.reasoner,chat:!0===i.chat,cursor:i.cursor||void 0,timeout:null!=i.timeout?Number(i.timeout):void 0,markdown:n},d=Number(i.interval)||60;!0===i.once?await (0,o.I)(r,l):await (0,o.D)(r,{...l,intervalSeconds:d})})}[a,o]=n.then?(await n)():n,r()}catch(e){r(e)}})},2520(e,t,i){i.a(e,async function(e,r){try{i.d(t,{J:()=>g});var s=i(5347),o=i(6928),a=i(3136),n=i(7096),l=i(3586),d=i(4071),c=i(4768),u=e([s,l,c,d]);async function p(e){return import((0,a.pathToFileURL)(e).href)}async function h(e){try{let t=await (0,c.s)(process.cwd());t.hooks||(t.hooks={}),t.hooks.active=e,await (0,c.L)(process.cwd(),t)}catch(e){(0,d.vV)(`Failed to save hook config: ${e.message}`)}}async function m(){try{let e=await (0,c.s)(process.cwd());if(!e.hooks)return!1;if(n.sX.clear(),e.hooks.active){let t=e.hooks.active;if("debug"===t.type){let e=(0,l._3)({logData:t.options?.data||!1});if(n.sX.registerAll(e),t.options?.performance){let e=(0,l.TA)();n.sX.registerAll(e)}if(t.options?.stats){let e=(0,l.sD)();n.sX.registerAll(e)}}else if("debug-basic"===t.type){let e=(0,l._3)({logData:t.options?.data||!1});n.sX.registerAll(e)}if("security"===t.type){let e=(0,l.n$)(t.options||{});n.sX.registerAll(e)}}if(e.hooks.customHandlers&&e.hooks.customHandlers.length>0)for(let t of((0,d.fH)(`Loading ${e.hooks.customHandlers.length} custom hook handlers...`),e.hooks.customHandlers))try{let e=o.isAbsolute(t.file)?t.file:o.join(process.cwd(),t.file),i=await p(e);"function"==typeof i.default?(n.sX.register(t.type,i.default),(0,d.MD)(`Loaded custom handler for ${t.type} from ${t.file}`)):(0,d.JE)(`Invalid handler in ${t.file}: default export is not a function`)}catch(e){(0,d.vV)(`Failed to load custom handler ${t.file}: ${e.message}`)}return!0}catch(e){return(0,d.vV)(`Failed to load hook config: ${e.message}`),!1}}function g(e,t){let i=new s.Command("hooks").description(t("hooks.description")).alias("hook");i.command("list").description(t("hooks.list.description")).option("-v, --verbose",t("hooks.list.options.verbose")).action(async e=>{try{await m();let i=await (0,c.s)(process.cwd());i.hooks&&i.hooks.active&&(0,d.MD)(`Loaded hook config: ${JSON.stringify(i.hooks.active)}`);let r=n.sX.getStats();(0,d.fH)(t("hooks.list.title")),(0,d.fH)("=".repeat(50)),Object.entries(r).forEach(([t,i])=>{(0,d.fH)(`${i>0?"✅":"❌"} ${t}: ${i} handlers`),e.verbose&&i>0&&n.sX.hooks.get(t).forEach((e,t)=>{(0,d.fH)(` ${t+1}. ${e.name||"anonymous"}`)})}),(0,d.fH)("=".repeat(50));let s=Object.values(r).reduce((e,t)=>e+t,0);(0,d.fH)(t("hooks.list.total",{total:s})),i.hooks&&i.hooks.active&&((0,d.fH)("\n\uD83D\uDCCB Active Hook Configuration:"),(0,d.fH)(`Type: ${i.hooks.active.type}`),i.hooks.active.options&&(0,d.fH)(`Options: ${JSON.stringify(i.hooks.active.options)}`))}catch(e){(0,d.vV)(t("hooks.list.error",{error:e.message}))}}),i.command("debug").description(t("hooks.debug.description")).option("-d, --data",t("hooks.debug.options.data")).option("-p, --performance",t("hooks.debug.options.performance")).option("-s, --stats",t("hooks.debug.options.stats")).option("-a, --all",t("hooks.debug.options.all")).action(async e=>{try{n.sX.clear();let i=0,r={type:"debug",options:{}};if(e.all||e.data){let e=(0,l._3)({logData:!0});n.sX.registerAll(e),i+=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.debug")),r.options.data=!0}if(e.all||e.performance){let e=(0,l.TA)();n.sX.registerAll(e),i+=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.performance")),r.options.performance=!0}if(e.all||e.stats){let e=(0,l.sD)();n.sX.registerAll(e),i+=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.stats")),r.options.stats=!0}if(0===i){let e=(0,l._3)({logData:!1});n.sX.registerAll(e),i=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.basic")),r.type="debug-basic"}await h(r),(0,d.fH)(t("hooks.debug.success",{count:i}))}catch(e){(0,d.vV)(t("hooks.debug.error",{error:e.message}))}}),i.command("security").description(t("hooks.security.description")).option("-b, --block <tools>",t("hooks.security.options.block")).option("-m, --max-prompt <length>",t("hooks.security.options.maxPrompt")).action(async e=>{try{let i=e.block?e.block.split(",").map(e=>e.trim()):[],r=e.maxPrompt?parseInt(e.maxPrompt,10):1e4,s=(0,l.n$)({blockedTools:i,maxPromptLength:r});n.sX.clear(),n.sX.registerAll(s),await h({type:"security",options:{blockedTools:i,maxPromptLength:r}}),(0,d.fH)(t("hooks.security.success")),i.length>0&&(0,d.fH)(t("hooks.security.blockedTools",{tools:i.join(", ")})),(0,d.fH)(t("hooks.security.maxPrompt",{length:r}))}catch(e){(0,d.vV)(t("hooks.security.error",{error:e.message}))}}),i.command("clear").description(t("hooks.clear.description")).action(async()=>{try{n.sX.clear();let e=await (0,c.s)(process.cwd());e.hooks&&(delete e.hooks.active,await (0,c.L)(process.cwd(),e)),(0,d.fH)(t("hooks.clear.success"))}catch(e){(0,d.vV)(t("hooks.clear.error",{error:e.message}))}}),i.command("test").description(t("hooks.test.description")).argument("[hookType]",t("hooks.test.argument.hookType")).action(async e=>{try{if(e){if(!Object.values(n.WD).includes(e))return void(0,d.vV)(t("hooks.test.invalidType",{type:e}));let i={test:!0,timestamp:Date.now(),hookType:e},r=await n.sX.trigger(e,i);(0,d.fH)(t("hooks.test.triggered",{type:e})),(0,d.fH)(t("hooks.test.result",{result:JSON.stringify(r,null,2)}))}else{for(let e of Object.values(n.WD)){let i={test:!0,timestamp:Date.now(),hookType:e};await n.sX.trigger(e,i),(0,d.fH)(t("hooks.test.triggered",{type:e}))}(0,d.fH)(t("hooks.test.allTriggered"))}}catch(e){(0,d.vV)(t("hooks.test.error",{error:e.message}))}}),i.command("register").description(t("hooks.register.description")).argument("<hookType>",t("hooks.register.argument.hookType")).argument("<handlerFile>",t("hooks.register.argument.handlerFile")).action(async(e,i)=>{try{if(!Object.values(n.WD).includes(e))return void(0,d.vV)(t("hooks.register.invalidType",{type:e}));let r=o.isAbsolute(i)?i:o.join(process.cwd(),i),s=await p(r);if("function"!=typeof s.default)return void(0,d.vV)(t("hooks.register.invalidHandler"));let a=n.sX.register(e,s.default);(0,d.fH)(t("hooks.register.success",{type:e,file:i}));let l=await (0,c.s)(process.cwd());l.hooks||(l.hooks={}),l.hooks.customHandlers||(l.hooks.customHandlers=[]),l.hooks.customHandlers.push({type:e,file:i,timestamp:new Date().toISOString()}),await (0,c.L)(process.cwd(),l),(0,d.fH)("Saved custom hook handler to settings"),process.on("exit",()=>a())}catch(e){(0,d.vV)(t("hooks.register.error",{error:e.message}))}}),i.command("status").description(t("hooks.status.description")).action(async()=>{try{await m();let e=await (0,c.s)(process.cwd()),t=n.sX.getStats(),i=Object.values(t).reduce((e,t)=>e+t,0);if((0,d.fH)("\uD83D\uDCCB Hook Status"),(0,d.fH)("=".repeat(50)),e.hooks&&e.hooks.active){let t=e.hooks.active;(0,d.fH)("\uD83D\uDCCB Active Hook Configuration:"),(0,d.fH)(`Type: ${t.type}`),t.options&&(0,d.fH)(`Options: ${JSON.stringify(t.options,null,2)}`)}else(0,d.fH)("\uD83D\uDCCB No active hook configuration");(0,d.fH)(""),(0,d.fH)("\uD83D\uDCCA Hook Statistics:"),(0,d.fH)(`Total handlers: ${i}`),(0,d.fH)(`Enabled hooks: ${Object.values(t).filter(e=>e>0).length}/${Object.keys(t).length}`),i>0&&((0,d.fH)(""),(0,d.fH)("\uD83D\uDCC8 Handler distribution:"),Object.entries(t).forEach(([e,t])=>{t>0&&(0,d.fH)(` ${e}: ${t} handlers`)})),(0,d.fH)("=".repeat(50))}catch(e){(0,d.vV)(t("hooks.status.error",{error:e.message}))}}),e.addCommand(i)}[s,l,c,d]=u.then?(await u)():u,r()}catch(e){r(e)}})},8(e,t,i){i.a(e,async function(e,r){try{i.d(t,{z:()=>d});var s=i(6760),o=i(8476),a=i(8362),n=i(1048),l=e([a,n,o]);function d(e,t){return e.command("init [dir]").description(t("cli.initDescription")).option("-t, --type <type>",t("cli.initTypeOption"),"js").addHelpText("after",t("cli.initExamples")).action(async(t,i)=>{let r=e.opts(),l=r.role??"RD",d=r.lang??(0,a.a)(),c=(0,s.resolve)(t||".");await (0,n.e)(c,r.logPath);try{await (0,o.Ts)(c,{...i,role:l,lang:d})}catch(e){process.exit(e?.exitCode??1)}})}[a,n,o]=l.then?(await l)():l,r()}catch(e){r(e)}})},1048(e,t,i){i.a(e,async function(e,r){try{i.d(t,{e:()=>l});var s=i(6760),o=i(1455),a=i(4071),n=e([a]);async function l(e,t){if(t)return(0,a.cS)(t),t;let i=(0,s.join)(e,"logs");await (0,o.mkdir)(i,{recursive:!0});let r=(0,s.join)(i,"pithosai.log");return(0,a.cS)(r),r}a=(n.then?(await n)():n)[0],r()}catch(e){r(e)}})},4072(e,t,i){i.a(e,async function(e,r){try{i.d(t,{v:()=>g});var s=i(6760),o=i(1455),a=i(8359),n=i(465),l=i(3327),d=i(6354),c=i(4768),u=i(8362),p=e([a,l,d,c,u]);function h(e){process.stdout.write(`${e}
|
|
460
|
-
`)}async function m({cwd:e,role:t,start:i,end:r,t:c,skipLlm:u=!1,modelOpts:p,lang:m="en"}){var g;let f=s.resolve(e),w=await (0,a.Lf)(),{startIso:k,endIso:y}=(0,n.v)(i,r),v=(g=(0,a.LW)(w,{role:t,startIso:k,endIso:y}),[...g].sort((e,t)=>{let i=(0,a.gg)(w,e),r=(0,a.gg)(w,t),s=i?.createdAt??"",o=r?.createdAt??"";return s===o?e.localeCompare(t):o.localeCompare(s)})),b=[];for(let e of v){let i=(0,a.gg)(w,e),r=(0,a.eC)(w,{taskId:e,role:t,asc:!0}),s=(0,l.$)(r);b.push({taskId:e,title:i?.title??e,status:i?.status??"unknown",description:i?.description??"",contributionSummary:s})}let S=(0,l.x)({role:t,entries:b}),T="1"===process.env.PITHOSAI_MEMORIZE_SKIP_LLM,C=b.length>0&&!u&&!T,E=S;if(C)try{E=await (0,d.V)({markdown:S,role:t,modelOpts:p??{},lang:m})}catch(t){let e=t&&"object"==typeof t&&"message"in t?String(t.message):String(t);h(c("cli.memorizeLlmFallback",{message:e})),E=S}let x=s.join(f,".pithosai",t);await (0,o.mkdir)(x,{recursive:!0});let I=s.join(x,"memory.md");return await (0,o.writeFile)(I,E,"utf8"),0===b.length?h(c("cli.memorizeNoTasks",{role:t,path:I})):h(c("cli.memorizeWrote",{path:I,count:String(b.length)})),{path:I,taskCount:b.length}}function g(e,t){let i=e.command("memorize").description(t("cli.memorizeDescription")).requiredOption("--start <date>",t("cli.memorizeStartOption")).requiredOption("--end <date>",t("cli.memorizeEndOption")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("--no-llm",t("cli.memorizeNoLlmOption")).option("--reasoner",t("cli.reasonerOption"),!1).option("--chat",t("cli.chatOption"),!1).option("--cursor [model]",t("cli.cursorOption")).option("--model <key>",t("cli.taskModelOption")).addHelpText("after",t("cli.memorizeExamples"));return i.action(async function(){let i=e.opts(),r=this.optsWithGlobals?this.optsWithGlobals():this.opts(),o=r.cwd?s.resolve(r.cwd):process.cwd(),a=r.role??i.role;a&&""!==String(a).trim()||(h(t("cli.memorizeRoleRequired")),process.exit(1));try{let e=!1===r.llm,s=await (0,c.s)(o),n=i.lang??s?.lang??(0,u.a)();await m({cwd:o,role:String(a).trim(),start:r.start,end:r.end,t,skipLlm:e,lang:n,modelOpts:{reasoner:!0===r.reasoner,chat:!0===r.chat,cursor:r.cursor||void 0,model:r.model||void 0}})}catch(i){let e=i&&"object"==typeof i&&"message"in i?String(i.message):String(i);h(t("cli.memorizeDateError",{message:e})),process.exit(1)}}),i}[a,l,d,c,u]=p.then?(await p)():p,r()}catch(e){r(e)}})},8376(e,t,i){i.a(e,async function(e,r){try{i.d(t,{T:()=>C});var s=i(3024),o=i(6760),a=i(5347),n=i(8),l=i(3780),d=i(924),c=i(6806),u=i(2457),p=i(4117),h=i(6652),m=i(6765),g=i(2555),f=i(2520),w=i(831),k=i(4072),y=i(2734),v=i(8362),b=i(4768),S=i(4399),T=e([b,v,a,n,h,l,g,f,c,u,p,d,w,k,y,m]);[b,v,a,n,h,l,g,f,c,u,p,d,w,k,y,m]=T.then?(await T)():T;let E=JSON.parse((0,s.readFileSync)((0,o.join)((0,S.F8)(),"package.json"),"utf8"));async function C(){var e;let t,i=(t=(e=process.argv).findIndex(e=>"--lang"===e||"-l"===e),-1!==t&&e[t+1]?e[t+1].toLowerCase():null),r=(0,o.resolve)(process.cwd()),s=await (0,b.s)(r);i=i??s?.lang??(0,v.a)();let S=(0,v.l)(i),T=new a.Command,C={"Usage:":S("cli.helpUsage"),"Arguments:":S("cli.helpArguments"),"Options:":S("cli.helpOptions"),"Commands:":S("cli.helpCommands"),"Global Options:":S("cli.helpGlobalOptions")},x={styleTitle:e=>Object.hasOwn(C,e)?C[e]:e};T.configureHelp(x),T.name("pithosai").description(S("cli.description")).version(E.version,"-V, --version",S("cli.versionOption")).option("-r, --role <role>",S("cli.roleOption")).option("-l, --lang <lang>",S("cli.langOption")).option("-i, --interactive",S("cli.interactiveModeOption")).option("--log-path <file>","Path for log file (defaults to <project>/logs/pithosai.log)").helpOption("-h, --help",S("cli.helpOption"));let I=(0,n.z)(T,S);I&&I.configureHelp(x);let A=(0,h.e)(T,S);A&&A.configureHelp(x),(0,l.B)(T);let O=T.commands[T.commands.length-1];O&&O.configureHelp(x),(0,g.F)(T);let P=T.commands[T.commands.length-1];P&&P.configureHelp(x),(0,f.J)(T,S);let R=T.commands[T.commands.length-1];R&&R.configureHelp(x),(0,c.H)(T);let M=T.commands[T.commands.length-1];M&&M.configureHelp(x);let L=(0,u.N)(T,S);L&&L.configureHelp(x);let N=(0,p.O)(T,S);N&&N.configureHelp(x);let D=(0,d.Z)(T,S);D&&D.configureHelp(x);let _=(0,w.y)(T,S);_&&_.configureHelp(x);let F=(0,k.v)(T,S);F&&F.configureHelp(x);let H=(0,y.S)(T,S);return H&&H.configureHelp(x),(0,m.E)(T,S),T}r()}catch(e){r(e)}})},8601(e,t,i){function r(e){let t=e?.mode??"agent",i=["/install-skill ","/list","/list-skill","/new","/remove-skill ","/select ","/show","/show-prompt","/show-task","exit","quit"];return"agent"===t&&i.push("/shell"),i.sort((e,t)=>e.localeCompare(t)),i}function s(e){let t=r(e);return e=>[t.filter(t=>t.startsWith(e)),e]}function o(e){let t=r(e);return{getSuggestions(e,i,r){let s=(e[i]??"").slice(0,r),o=s.trimStart();if(o.startsWith("/")){let e=t.filter(e=>e.startsWith("/")&&e.startsWith(o));return 0===e.length?null:{items:e.map(e=>({value:e,label:e})),prefix:s}}let a=s.trim();if(""===a)return null;let n=t.filter(e=>!e.startsWith("/")&&e.startsWith(a));return 0===n.length?null:{items:n.map(e=>({value:e,label:e})),prefix:s}},applyCompletion(e,t,i,r,s){let o=e[t]??"",a=s.slice(0,s.length-s.trimStart().length),n=o.slice(0,i-s.length),l=o.slice(i),d=n+a+r.value+l,c=[...e];return c[t]=d,{lines:c,cursorLine:t,cursorCol:n.length+a.length+r.value.length}}}}function a(){let e=["continue","c","exit","e"].sort((e,t)=>e.localeCompare(t));return t=>[e.filter(e=>e.startsWith(t)),t]}i.d(t,{ML:()=>o,Q$:()=>a,ry:()=>s})},6765(e,t,i){i.a(e,async function(e,r){try{i.d(t,{E:()=>Y});var s=i(6760),o=i(1455),a=i(7598),n=i(481),l=i(3242),d=i(4768),c=i(8362),u=i(1048),p=i(5012),h=i(4071),m=i(2482),g=i(7175),f=i(3689),w=i(8359),k=i(5910),y=i(4239),v=i(829),b=i(9737),S=i(9782),T=i(161),C=i(1529),E=i(4427),x=i(8601),I=i(8691),A=i(9766),O=i(4361),P=e([E,k,C,h,w,T,l,m,d,c,u,A,I,v]);[E,k,C,h,w,T,l,m,d,c,u,A,I,v]=P.then?(await P)():P;let J={write:e=>{process.stdout.write(e)},writeLn:e=>{process.stdout.write(e+"\n")}};function R(e){let{io:t,t:i,message:r,tuiSession:s=null}=e,o=(0,O.K)({t:i,message:r});s?((0,h.CN)(o),t.writeLn(I.m.red(o))):(0,h.vV)(o)}async function M(e,t,i){let{waitingMessage:r,runningMessage:s}=t,o="string"==typeof s&&""!==s.trim(),a=o?s:r;if(i){i.setLoading(!0,r,{runningMessage:o?s:null});try{return await e}finally{i.setLoading(!1)}}return(0,S.vg)(e,r,a)}async function L(e){let{markdown:t,runOpts:i,t:r,tuiSession:s=null}=e;if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER)return;let o=i.mode??"agent";if(("dialog"===o||"plan"===o)&&t?.trim())try{await (0,C.G)({markdown:t,t:r,tuiSession:s})}catch(t){let e=r("cli.resultPreviewFailed",{message:t?.message??String(t)});s?((0,h.CN)(e),s.getIo().writeLn(I.m.red(e))):(0,h.vV)(e)}}function N(e){let t=null!=e.timeout?1e3*e.timeout:null,i="string"==typeof process.env.PITHOSAI_TIMEOUT_MS?parseInt(process.env.PITHOSAI_TIMEOUT_MS,10):null;return t??i??p.TZ}async function D(e){let{trimmedRequest:t,runOpts:r,t:s,io:o=J,tuiSession:a=null}=e,n=r.mode??"agent";if(("dialog"===n||"plan"===n)&&t.toLowerCase().startsWith("/shell"))return o.writeLn(s("cli.shellDisabledInMode")),!0;if(!t.toLowerCase().startsWith("/shell"))return!1;let{executeShellCommand:l,formatShellResult:d}=await Promise.resolve().then(i.bind(i,2482)),c=t.substring(6).trim();if(!c)return o.writeLn(s("shell.noCommand")),!0;try{let e=N(r),t=await l(c,r.cwd,e,s),i=d(c,t,s);if(o.writeLn(i),!t.success){let e=s("shell.logFailed",{command:c,code:null!=t.exitCode?String(t.exitCode):"N/A"});a?((0,h.CN)(e),o.writeLn(I.m.red(e))):(0,h.vV)(e)}}catch(t){o.writeLn(s("shell.executionError",{error:t.message}));let e=s("shell.logExecutionError",{message:t.message});a?((0,h.CN)(e),o.writeLn(I.m.red(e))):(0,h.vV)(e)}return!0}async function _(e){let{globalOpts:t,t:i,skillsIo:r}=e;await (0,g.At)({globalOpts:t,t:i,io:r})}async function F(e){let{globalOpts:t,t:i,skillsIo:r,parsed:s}=e;await (0,g.NB)({skillName:s.skillName,force:s.force,globalOpts:t,t:i,io:r})}async function H(e){let{globalOpts:t,t:i,skillsIo:r,parsed:s}=e;await (0,g.HM)({skillName:s.skillName,globalOpts:t,t:i,io:r})}async function $(e){let{trimmedRequest:t,runOpts:i,t:r,io:s=J,tuiSession:o=null}=e,a=(0,f.D)(t);if(!a)return!1;if("invalid"===a.type)return"list"===a.command?s.writeLn(r("run.skillSlash.listNoExtra")):"install"===a.command?s.writeLn(r("run.skillSlash.installUsage")):s.writeLn(r("run.skillSlash.removeUsage")),!0;let n={cwd:i.cwd,lang:i.lang??(0,c.a)()},l={log:e=>s.writeLn(e),warn:e=>s.writeLn(e),writeStdout:e=>s.write(e)};try{"list"===a.type?await _({globalOpts:n,t:r,skillsIo:l}):"install"===a.type?await F({globalOpts:n,t:r,skillsIo:l,parsed:a}):await H({globalOpts:n,t:r,skillsIo:l,parsed:a})}catch(t){let e=r("run.skillSlash.failed",{message:t?.message??String(t)});o?((0,h.CN)(e),s.writeLn(I.m.red(e))):(0,h.vV)(e)}return!0}async function j(e){let{body:t,runOpts:i,t:r,taskRef:n,controller:d,io:c=J,tuiSession:u=null,outputSink:p=null}=e,h=N(i)+1e4,m={id:n.taskId,status:"pending",title:t,description:"",createdAt:new Date().toISOString(),section:null},g={...d?{...i,controller:d}:i,mode:"plan",outputSink:p??{write(){}}},f=function(e){let t=String(e).split(/\r?\n/)[0].trim(),i=t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"");if(!i){let e=(0,a.createHash)("md5").update(t||"plan","utf8").digest("hex").slice(0,8);return`${e}-plan.md`}return i.length>80&&(i=i.slice(0,80).replace(/-+$/g,"")),`${i}-plan.md`}(t),w=(0,s.resolve)((0,s.join)(i.cwd,f)),k=(0,b.n)((0,l.Ty)(m,g),h,()=>Error(r("errors.runTimeout",{seconds:String(Math.round(h/1e3))})));try{let e=await M(k,{waitingMessage:r("cli.planRunning")},u),t=(e&&"string"==typeof e.result&&e.result.length>0?e.result:Array.isArray(e?.results)&&e.results.length>0?e.results.join("\n\n"):"")??"";await (0,o.writeFile)(w,t,"utf8"),c.writeLn(r("cli.planWritten",{path:w})),t.trim()&&t.length>1024&&await L({markdown:t,runOpts:i,t:r,tuiSession:u}),e&&!1===e.success&&e.error&&R({io:c,t:r,message:e.error,tuiSession:u})}catch(e){if(d&&(d.status===y.i.STOPPED||d.status===y.i.PAUSED))return;R({io:c,t:r,message:e?.message??String(e),tuiSession:u})}}function z(e){return e.replace(/\r\n?/g,"\n").replace(/\n/g,"<br>").replace(/\|/g,"\\|")}async function U(e,t,i,r=J,o=null){if(!/^\/show-prompt\s*$/i.test(e))return!1;let a=i.cwd,n=await (0,d.s)(a),l=i.lang??n?.lang??(0,c.a)(),u=i.role??n?.supportedRoles?.[0]??"RD",p=i.mode??"agent";if(!["agent","dialog","plan"].includes(p))return r.writeLn(t("cli.showPromptInvalidMode")),!0;try{let e="agent"===p?(0,s.resolve)(a,".pithosai","skills"):void 0,n=(await (0,E.Ex)({cwd:a,lang:l,role:u,mode:p,skillsDir:e})).systemPrompt;if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER){let e=!0===i.markdown?(0,T.o)(n):n;return r.writeLn(e),!0}try{await (0,C.G)({markdown:n,t,documentTitle:t("run.showPrompt.previewDocumentTitle"),tuiSession:o})}catch(i){let e=t("cli.resultPreviewFailed",{message:i?.message??String(i)});o?((0,h.CN)(e),r.writeLn(I.m.red(e))):(0,h.vV)(e)}return!0}catch(e){return r.writeLn(t("cli.showPromptError",{message:e&&"object"==typeof e&&"message"in e?String(e.message):String(e)})),!0}}async function q(e,t,i,r,s=J){if(!/^\/show(\s+.*)?$/i.test(e))return!1;let o=await (0,w.Lf)(),a=(0,w.gg)(o,t.taskId),n=(0,w.XV)(o,{taskId:t.taskId,asc:!1,limit:1e6}),l=Array.isArray(n)?n:[],d=l.length,c=function(e){let t={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0};for(let i of e){let e=function(e){if(e&&"object"==typeof e)return e;if("string"!=typeof e||""===e.trim())return null;try{let t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch{return null}}(i?.message),r=e?.usage;r&&"object"==typeof r&&("number"==typeof r.input&&Number.isFinite(r.input)&&(t.input+=r.input),"number"==typeof r.output&&Number.isFinite(r.output)&&(t.output+=r.output),"number"==typeof r.cacheRead&&Number.isFinite(r.cacheRead)&&(t.cacheRead+=r.cacheRead),"number"==typeof r.cacheWrite&&Number.isFinite(r.cacheWrite)&&(t.cacheWrite+=r.cacheWrite),"number"==typeof r.totalTokens&&Number.isFinite(r.totalTokens)&&(t.totalTokens+=r.totalTokens))}return t}(l),u=r.mode??"agent",p=a?.model?String(a.model):"string"==typeof r.cursor&&""!==r.cursor.trim()?`cursor:${r.cursor.trim()}`:!0===r.reasoner?"deepSeekReasoner":!0===r.chat?"deepSeekChat":"deepSeekCoder",h=a?.status?String(a.status):"unknown",m=(0,k.vt)(a?.title?String(a.title):"",30),g=`
|
|
327
|
+
`),this.agentController.pause();return}(0,a.matchesKey)(e,"ctrl+c")&&(this.onAgentControlNotice||process.stdout.write("\n"),process.exit(0));return}super.handleInput(e)}}function m(){return"1"!==process.env.PITHOSAI_NO_TUI&&!!(process.stdout.isTTY&&process.stdin.isTTY)}class b{constructor(e){let{t,cwd:r,runOpts:i={}}=e;this.t=t,this.cwd=r,this.runOpts=i,this.terminal=new a.ProcessTerminal,this.tui=new y(this.terminal),this.transcript=new f,this.loadingLine=new k(this.tui,()=>this.loadingMessage),this.loadingMessage="",this.loadingRunningMessage=null,this.loadingPhase=null,this.prompt=new w(this.tui,i),this.layout=new v({terminal:this.terminal,transcript:this.transcript,loading:this.loadingLine,prompt:this.prompt});let o=new a.Container;o.addChild(this.layout),this.tui.addChild(o),this.tui.setFocus(this.layout),this._resolveLine=null,this.prompt.editor.onSubmit=e=>{let t=this._resolveLine;this._resolveLine=null;let r="string"==typeof e?String(e).replace(/^\s*[>→]\s*/u,""):"",i=r.trim();i&&this.prompt.editor.addToHistory(i),this.requestTuiFullRedraw(),t?.(r)},this.tui.onTranscriptPageScroll=e=>this.scrollTranscriptBy(e),this.tui.transcriptPageScrollGuard=()=>this.prompt.isAutocompleteActive(),this.tui.onAgentControlNotice=e=>{this.transcript.appendLine(e),this.transcript.clearViewportPin(),this.requestTuiRedraw()},this.tui.addInputListener(e=>{let t=function(e){let t=String(e).match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);if(!t)return null;let r=parseInt(t[1],10);return 64===r||96===r?-3:65===r||97===r?3:null}(e);if(null!=t&&this.tui.transcriptPageScrollGuard?.()!==!0)return this.scrollTranscriptBy(t),{consume:!0}})}requestTuiRedraw(){this.layout.invalidate(),this.tui.requestRender()}requestTuiRedrawEnsuringInputEditor(){this.prompt.invalidate(),this.layout.invalidate(),this.tui.requestRender()}repaintInputEditorRegion(){let e=this.terminal.columns,t=this.terminal.rows,r=this.prompt.render(e),i=Math.max(1,t-r.length+1),o="\x1b[s";for(let t=0;t<r.length;t++){let n=String(r[t]).replace(a.CURSOR_MARKER,""),s=(0,a.truncateToWidth)(n,e,"",!0);o+=`\x1b[2K\x1b[${i+t};1H${s}`}o+="\x1b[u",this.terminal.write(o)}requestTuiFullRedraw(){this.layout.invalidate(),this.tui.requestRender(!0)}scrollTranscriptBy(e){let t=this.terminal.rows,r=this.terminal.columns,i=this.layout.prompt.render(r).length,a=this.loadingLine.reservedHeight(),o=Math.max(1,t-i-a);if(this.transcript.bumpViewStart(e,o),this.loadingLine.isActive()){this.layout.invalidate(),this.prompt.invalidate(),this.tui.requestRender(!0);return}this.requestTuiRedrawEnsuringInputEditor(),process.nextTick(()=>this.repaintInputEditorRegion())}start(){this.tui.start(),u(),this.tui.setFocus(this.layout),this.layout.focused=!0,this.prompt.focused=!0}stop(){this.loadingLine.setActive(!1),p(),this.tui.stop()}suspendForReadline(){this.loadingLine.setActive(!1),p(),this.tui.stop()}resumeFromReadline(){this.tui.start(),u(),this.tui.setFocus(this.layout),this.layout.focused=!0,this.prompt.focused=!0,this.requestTuiFullRedraw()}appendLines(e){for(let t of e)this.transcript.appendLine(t);this.requestTuiRedraw()}appendLine(e){this.transcript.appendLine(e),this.requestTuiRedraw()}clearLoadingIfActive(){this.loadingLine.isActive()&&("waiting"===this.loadingPhase&&this.loadingRunningMessage&&(this.loadingMessage=this.loadingRunningMessage),this.loadingPhase="running",this.loadingLine.enterRunningPhase())}appendAgentChunk(e){if(!e)return;this.clearLoadingIfActive(),this.transcript.clearViewportPin();let t=String(e).split("\n");for(let e=0;e<t.length;e++)e>0&&this.transcript.appendLine(""),t[e]&&this.transcript.appendRaw(t[e]);this.requestTuiRedraw()}setLoading(e,t="",r={}){let{runningMessage:i=null}=r;this.loadingMessage=t,this.loadingRunningMessage=i,this.loadingPhase=e?"waiting":null,this.loadingLine.setActive(e),this.requestTuiRedraw()}getAgentOutputSink(){return{write:(e,t={})=>{"stderr"===t.stream?(this.clearLoadingIfActive(),this.transcript.clearViewportPin(),this.transcript.appendLine(s.m.red(String(e))),this.requestTuiRedraw()):this.appendAgentChunk(String(e))}}}getIo(){return{write:e=>{this.appendAgentChunk(String(e))},writeLn:e=>{let t=String(e).split(/\r?\n/);t.length>0&&""===t[t.length-1]&&(t=t.slice(0,-1)),t.length>0&&this.clearLoadingIfActive();let r=this.transcript.lines.length;for(let e of t)this.transcript.appendLine(e);t.length>=4&&this.transcript.setViewportPin(r),this.requestTuiRedraw()}}}clearTranscriptViewportPin(){this.transcript.clearViewportPin()}setTranscriptViewportPin(e){this.transcript.setViewportPin(e),this.requestTuiFullRedraw()}attachControllerForRun(e){this.tui.setAgentRunning(!0,{stop:()=>e.stop(),pause:()=>e.pause()})}detachControllerForRun(){this.tui.setAgentRunning(!1,null)}readSubmittedLine(){return new Promise(e=>{this._resolveLine=e})}ensureInputEditorActive(){this.tui.setFocus(this.layout),this.layout.focused=!0,this.prompt.focused=!0,this.requestTuiFullRedraw()}}function h(e){let{session:t,cwd:r,t:i,mode:a}=e;"dialog"===a?t.appendLines([i("run.interactiveModeDialogTitle"),i("run.interactiveModeCwd",{cwd:r}),i("run.interactiveModeDialogTips"),""]):"plan"===a?t.appendLines([i("run.interactiveModePlanTitle"),i("run.interactiveModeCwd",{cwd:r}),i("run.interactiveModePlanTips"),""]):t.appendLines([i("run.interactiveModeAgentTitle"),i("run.interactiveModeCwd",{cwd:r}),i("run.interactiveModeAgentTips"),""])}function g(e,t,r){let i=t.mode??"agent",a=[r("run.interactiveExitHint")];"dialog"===i?a.push(r("run.replIntroDialog")):"plan"===i?a.push(r("run.replIntroPlan")):a.push(r("run.shellHint")),a.push(r("run.newSessionHint"),r("run.controlHint"),r("run.replTabCompletionHint"),r("run.tuiScrollTranscriptHint"),""),e.appendLines(a)}i()}catch(e){i(e)}})},924(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Z:()=>l});var a=r(6760),o=r(6478),n=r(1048),s=e([n,o]);function l(e,t){return e.command("heartbeat").description(t("cli.heartbeatDescription")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("-l, --lang <lang>",t("cli.langOption")).option("--interval <seconds>",t("cli.heartbeatIntervalOption"),"60").option("--once",t("cli.heartbeatOnceOption"),!1).option("--reasoner",t("cli.reasonerOption"),!1).option("--chat",t("cli.chatOption"),!1).option("--cursor [model]",t("cli.cursorOption")).option("--timeout <seconds>",t("cli.timeoutOption")).option("--no-markdown","Plain text output only (default: markdown when TTY)").action(async function(){let t=e.opts(),r=this.optsWithGlobals?this.optsWithGlobals():this.opts(),i=(0,a.resolve)(r.cwd||process.cwd());await (0,n.e)(i,t.logPath);let s=!1!==r.markdown&&!!process.stdout.isTTY,l={role:t.role??r.role,lang:t.lang??r.lang,reasoner:!0===r.reasoner,chat:!0===r.chat,cursor:r.cursor||void 0,timeout:null!=r.timeout?Number(r.timeout):void 0,markdown:s},d=Number(r.interval)||60;!0===r.once?await (0,o.I)(i,l):await (0,o.D)(i,{...l,intervalSeconds:d})})}[n,o]=s.then?(await s)():s,i()}catch(e){i(e)}})},2520(e,t,r){r.a(e,async function(e,i){try{r.d(t,{J:()=>g});var a=r(5347),o=r(6928),n=r(3136),s=r(7096),l=r(3586),d=r(4071),c=r(4768),u=e([a,l,c,d]);async function p(e){return import((0,n.pathToFileURL)(e).href)}async function m(e){try{let t=await (0,c.s)(process.cwd());t.hooks||(t.hooks={}),t.hooks.active=e,await (0,c.L)(process.cwd(),t)}catch(e){(0,d.vV)(`Failed to save hook config: ${e.message}`)}}async function h(){try{let e=await (0,c.s)(process.cwd());if(!e.hooks)return!1;if(s.sX.clear(),e.hooks.active){let t=e.hooks.active;if("debug"===t.type){let e=(0,l._3)({logData:t.options?.data||!1});if(s.sX.registerAll(e),t.options?.performance){let e=(0,l.TA)();s.sX.registerAll(e)}if(t.options?.stats){let e=(0,l.sD)();s.sX.registerAll(e)}}else if("debug-basic"===t.type){let e=(0,l._3)({logData:t.options?.data||!1});s.sX.registerAll(e)}if("security"===t.type){let e=(0,l.n$)(t.options||{});s.sX.registerAll(e)}}if(e.hooks.customHandlers&&e.hooks.customHandlers.length>0)for(let t of((0,d.fH)(`Loading ${e.hooks.customHandlers.length} custom hook handlers...`),e.hooks.customHandlers))try{let e=o.isAbsolute(t.file)?t.file:o.join(process.cwd(),t.file),r=await p(e);"function"==typeof r.default?(s.sX.register(t.type,r.default),(0,d.MD)(`Loaded custom handler for ${t.type} from ${t.file}`)):(0,d.JE)(`Invalid handler in ${t.file}: default export is not a function`)}catch(e){(0,d.vV)(`Failed to load custom handler ${t.file}: ${e.message}`)}return!0}catch(e){return(0,d.vV)(`Failed to load hook config: ${e.message}`),!1}}function g(e,t){let r=new a.Command("hooks").description(t("hooks.description")).alias("hook");r.command("list").description(t("hooks.list.description")).option("-v, --verbose",t("hooks.list.options.verbose")).action(async e=>{try{await h();let r=await (0,c.s)(process.cwd());r.hooks&&r.hooks.active&&(0,d.MD)(`Loaded hook config: ${JSON.stringify(r.hooks.active)}`);let i=s.sX.getStats();(0,d.fH)(t("hooks.list.title")),(0,d.fH)("=".repeat(50)),Object.entries(i).forEach(([t,r])=>{(0,d.fH)(`${r>0?"✅":"❌"} ${t}: ${r} handlers`),e.verbose&&r>0&&s.sX.hooks.get(t).forEach((e,t)=>{(0,d.fH)(` ${t+1}. ${e.name||"anonymous"}`)})}),(0,d.fH)("=".repeat(50));let a=Object.values(i).reduce((e,t)=>e+t,0);(0,d.fH)(t("hooks.list.total",{total:a})),r.hooks&&r.hooks.active&&((0,d.fH)("\n\uD83D\uDCCB Active Hook Configuration:"),(0,d.fH)(`Type: ${r.hooks.active.type}`),r.hooks.active.options&&(0,d.fH)(`Options: ${JSON.stringify(r.hooks.active.options)}`))}catch(e){(0,d.vV)(t("hooks.list.error",{error:e.message}))}}),r.command("debug").description(t("hooks.debug.description")).option("-d, --data",t("hooks.debug.options.data")).option("-p, --performance",t("hooks.debug.options.performance")).option("-s, --stats",t("hooks.debug.options.stats")).option("-a, --all",t("hooks.debug.options.all")).action(async e=>{try{s.sX.clear();let r=0,i={type:"debug",options:{}};if(e.all||e.data){let e=(0,l._3)({logData:!0});s.sX.registerAll(e),r+=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.debug")),i.options.data=!0}if(e.all||e.performance){let e=(0,l.TA)();s.sX.registerAll(e),r+=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.performance")),i.options.performance=!0}if(e.all||e.stats){let e=(0,l.sD)();s.sX.registerAll(e),r+=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.stats")),i.options.stats=!0}if(0===r){let e=(0,l._3)({logData:!1});s.sX.registerAll(e),r=Object.keys(e).length,(0,d.fH)(t("hooks.debug.added.basic")),i.type="debug-basic"}await m(i),(0,d.fH)(t("hooks.debug.success",{count:r}))}catch(e){(0,d.vV)(t("hooks.debug.error",{error:e.message}))}}),r.command("security").description(t("hooks.security.description")).option("-b, --block <tools>",t("hooks.security.options.block")).option("-m, --max-prompt <length>",t("hooks.security.options.maxPrompt")).action(async e=>{try{let r=e.block?e.block.split(",").map(e=>e.trim()):[],i=e.maxPrompt?parseInt(e.maxPrompt,10):1e4,a=(0,l.n$)({blockedTools:r,maxPromptLength:i});s.sX.clear(),s.sX.registerAll(a),await m({type:"security",options:{blockedTools:r,maxPromptLength:i}}),(0,d.fH)(t("hooks.security.success")),r.length>0&&(0,d.fH)(t("hooks.security.blockedTools",{tools:r.join(", ")})),(0,d.fH)(t("hooks.security.maxPrompt",{length:i}))}catch(e){(0,d.vV)(t("hooks.security.error",{error:e.message}))}}),r.command("clear").description(t("hooks.clear.description")).action(async()=>{try{s.sX.clear();let e=await (0,c.s)(process.cwd());e.hooks&&(delete e.hooks.active,await (0,c.L)(process.cwd(),e)),(0,d.fH)(t("hooks.clear.success"))}catch(e){(0,d.vV)(t("hooks.clear.error",{error:e.message}))}}),r.command("test").description(t("hooks.test.description")).argument("[hookType]",t("hooks.test.argument.hookType")).action(async e=>{try{if(e){if(!Object.values(s.WD).includes(e))return void(0,d.vV)(t("hooks.test.invalidType",{type:e}));let r={test:!0,timestamp:Date.now(),hookType:e},i=await s.sX.trigger(e,r);(0,d.fH)(t("hooks.test.triggered",{type:e})),(0,d.fH)(t("hooks.test.result",{result:JSON.stringify(i,null,2)}))}else{for(let e of Object.values(s.WD)){let r={test:!0,timestamp:Date.now(),hookType:e};await s.sX.trigger(e,r),(0,d.fH)(t("hooks.test.triggered",{type:e}))}(0,d.fH)(t("hooks.test.allTriggered"))}}catch(e){(0,d.vV)(t("hooks.test.error",{error:e.message}))}}),r.command("register").description(t("hooks.register.description")).argument("<hookType>",t("hooks.register.argument.hookType")).argument("<handlerFile>",t("hooks.register.argument.handlerFile")).action(async(e,r)=>{try{if(!Object.values(s.WD).includes(e))return void(0,d.vV)(t("hooks.register.invalidType",{type:e}));let i=o.isAbsolute(r)?r:o.join(process.cwd(),r),a=await p(i);if("function"!=typeof a.default)return void(0,d.vV)(t("hooks.register.invalidHandler"));let n=s.sX.register(e,a.default);(0,d.fH)(t("hooks.register.success",{type:e,file:r}));let l=await (0,c.s)(process.cwd());l.hooks||(l.hooks={}),l.hooks.customHandlers||(l.hooks.customHandlers=[]),l.hooks.customHandlers.push({type:e,file:r,timestamp:new Date().toISOString()}),await (0,c.L)(process.cwd(),l),(0,d.fH)("Saved custom hook handler to settings"),process.on("exit",()=>n())}catch(e){(0,d.vV)(t("hooks.register.error",{error:e.message}))}}),r.command("status").description(t("hooks.status.description")).action(async()=>{try{await h();let e=await (0,c.s)(process.cwd()),t=s.sX.getStats(),r=Object.values(t).reduce((e,t)=>e+t,0);if((0,d.fH)("\uD83D\uDCCB Hook Status"),(0,d.fH)("=".repeat(50)),e.hooks&&e.hooks.active){let t=e.hooks.active;(0,d.fH)("\uD83D\uDCCB Active Hook Configuration:"),(0,d.fH)(`Type: ${t.type}`),t.options&&(0,d.fH)(`Options: ${JSON.stringify(t.options,null,2)}`)}else(0,d.fH)("\uD83D\uDCCB No active hook configuration");(0,d.fH)(""),(0,d.fH)("\uD83D\uDCCA Hook Statistics:"),(0,d.fH)(`Total handlers: ${r}`),(0,d.fH)(`Enabled hooks: ${Object.values(t).filter(e=>e>0).length}/${Object.keys(t).length}`),r>0&&((0,d.fH)(""),(0,d.fH)("\uD83D\uDCC8 Handler distribution:"),Object.entries(t).forEach(([e,t])=>{t>0&&(0,d.fH)(` ${e}: ${t} handlers`)})),(0,d.fH)("=".repeat(50))}catch(e){(0,d.vV)(t("hooks.status.error",{error:e.message}))}}),e.addCommand(r)}[a,l,c,d]=u.then?(await u)():u,i()}catch(e){i(e)}})},8(e,t,r){r.a(e,async function(e,i){try{r.d(t,{z:()=>d});var a=r(6760),o=r(8476),n=r(8362),s=r(1048),l=e([n,s,o]);function d(e,t){return e.command("init [dir]").description(t("cli.initDescription")).option("-t, --type <type>",t("cli.initTypeOption"),"js").addHelpText("after",t("cli.initExamples")).action(async(t,r)=>{let i=e.opts(),l=i.role??"RD",d=i.lang??(0,n.a)(),c=(0,a.resolve)(t||".");await (0,s.e)(c,i.logPath);try{await (0,o.Ts)(c,{...r,role:l,lang:d})}catch(e){process.exit(e?.exitCode??1)}})}[n,s,o]=l.then?(await l)():l,i()}catch(e){i(e)}})},1048(e,t,r){r.a(e,async function(e,i){try{r.d(t,{e:()=>l});var a=r(6760),o=r(1455),n=r(4071),s=e([n]);async function l(e,t){if(t)return(0,n.cS)(t),t;let r=(0,a.join)(e,"logs");await (0,o.mkdir)(r,{recursive:!0});let i=(0,a.join)(r,"pithosai.log");return(0,n.cS)(i),i}n=(s.then?(await s)():s)[0],i()}catch(e){i(e)}})},4072(e,t,r){r.a(e,async function(e,i){try{r.d(t,{v:()=>f});var a=r(6760),o=r(1455),n=r(8359),s=r(465),l=r(3327),d=r(6354),c=r(4768),u=r(8362),p=e([n,l,d,c,u]);function m(e){process.stdout.write(`${e}
|
|
328
|
+
`)}async function h(e,t){let r=new Map;for(let i of e)r.set(i,await (0,n.gg)(t,i));return[...e].sort((e,t)=>{let i=r.get(e),a=r.get(t),o=i?.createdAt??"",n=a?.createdAt??"";return o===n?e.localeCompare(t):n.localeCompare(o)})}async function g({cwd:e,role:t,start:r,end:i,t:c,skipLlm:u=!1,modelOpts:p,lang:g="en"}){let f=a.resolve(e),k=await (0,n.Lf)(),{startIso:w,endIso:v}=(0,s.v)(r,i),y=await (0,n.LW)(k,{role:t,startIso:w,endIso:v}),b=await h(y,k),S=[];for(let e of b){let r=await (0,n.gg)(k,e),i=await (0,n.eC)(k,{taskId:e,role:t,asc:!0}),a=(0,l.$)(i);S.push({taskId:e,title:r?.title??e,status:r?.status??"unknown",description:r?.description??"",contributionSummary:a})}let T=(0,l.x)({role:t,entries:S}),E="1"===process.env.PITHOSAI_MEMORIZE_SKIP_LLM,x=S.length>0&&!u&&!E,C=T;if(x)try{C=await (0,d.V)({markdown:T,role:t,modelOpts:p??{},lang:g})}catch(t){let e=t&&"object"==typeof t&&"message"in t?String(t.message):String(t);m(c("cli.memorizeLlmFallback",{message:e})),C=T}let A=a.join(f,".pithosai",t);await (0,o.mkdir)(A,{recursive:!0});let I=a.join(A,"memory.md");return await (0,o.writeFile)(I,C,"utf8"),0===S.length?m(c("cli.memorizeNoTasks",{role:t,path:I})):m(c("cli.memorizeWrote",{path:I,count:String(S.length)})),{path:I,taskCount:S.length}}function f(e,t){let r=e.command("memorize").description(t("cli.memorizeDescription")).requiredOption("--start <date>",t("cli.memorizeStartOption")).requiredOption("--end <date>",t("cli.memorizeEndOption")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("--no-llm",t("cli.memorizeNoLlmOption")).option("--reasoner",t("cli.reasonerOption"),!1).option("--chat",t("cli.chatOption"),!1).option("--cursor [model]",t("cli.cursorOption")).option("--model <key>",t("cli.taskModelOption")).addHelpText("after",t("cli.memorizeExamples"));return r.action(async function(){let r=e.opts(),i=this.optsWithGlobals?this.optsWithGlobals():this.opts(),o=i.cwd?a.resolve(i.cwd):process.cwd(),n=i.role??r.role;n&&""!==String(n).trim()||(m(t("cli.memorizeRoleRequired")),process.exit(1));try{let e=!1===i.llm,a=await (0,c.s)(o),s=r.lang??a?.lang??(0,u.a)();await g({cwd:o,role:String(n).trim(),start:i.start,end:i.end,t,skipLlm:e,lang:s,modelOpts:{reasoner:!0===i.reasoner,chat:!0===i.chat,cursor:i.cursor||void 0,model:i.model||void 0}})}catch(r){let e=r&&"object"==typeof r&&"message"in r?String(r.message):String(r);m(t("cli.memorizeDateError",{message:e})),process.exit(1)}}),r}[n,l,d,c,u]=p.then?(await p)():p,i()}catch(e){i(e)}})},5900(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Q:()=>l});var a=r(6760),o=r(2369),n=r(5012),s=e([o]);function l(e,t){return e.command("migrate-db").description(t("cli.migrateDbDescription")).option("--db-path <file>",t("cli.migrateDbDbPathOption")).action(async e=>{try{let r=e.dbPath?(0,a.resolve)(e.dbPath):await (0,o.sA)(n.qu),i=await (0,o.tT)({path:r});if("migrated"===i.action)return void console.log(t("cli.migrateDbMigrated"));if("file_missing"===i.reason)return void console.log(t("cli.migrateDbSkippedMissing",{path:r}));if("already_encrypted_with_key"===i.reason)return void console.log(t("cli.migrateDbSkippedAlready"));console.log(t("cli.migrateDbSkippedNotPlain"))}catch(e){e instanceof o.IH?console.error(t("cli.migrateDbErrNoSqlcipher")):console.error(e instanceof Error?e.message:String(e)),process.exit(1)}})}o=(s.then?(await s)():s)[0],i()}catch(e){i(e)}})},8376(e,t,r){r.a(e,async function(e,i){try{r.d(t,{T:()=>x});var a=r(3024),o=r(6760),n=r(5347),s=r(8),l=r(5900),d=r(3780),c=r(924),u=r(6806),p=r(2457),m=r(4117),h=r(6652),g=r(6765),f=r(2555),k=r(2520),w=r(831),v=r(4072),y=r(2734),b=r(8362),S=r(4768),T=r(4399),E=e([S,b,n,s,l,h,d,f,k,u,p,m,c,w,v,y,g]);[S,b,n,s,l,h,d,f,k,u,p,m,c,w,v,y,g]=E.then?(await E)():E;let C=JSON.parse((0,a.readFileSync)((0,o.join)((0,T.F8)(),"package.json"),"utf8"));async function x(){var e;let t,r=(t=(e=process.argv).findIndex(e=>"--lang"===e||"-l"===e),-1!==t&&e[t+1]?e[t+1].toLowerCase():null),i=(0,o.resolve)(process.cwd()),a=await (0,S.s)(i);r=r??a?.lang??(0,b.a)();let T=(0,b.l)(r),E=new n.Command,x={"Usage:":T("cli.helpUsage"),"Arguments:":T("cli.helpArguments"),"Options:":T("cli.helpOptions"),"Commands:":T("cli.helpCommands"),"Global Options:":T("cli.helpGlobalOptions")},A={styleTitle:e=>Object.hasOwn(x,e)?x[e]:e};E.configureHelp(A),E.name("pithosai").description(T("cli.description")).version(C.version,"-V, --version",T("cli.versionOption")).option("-r, --role <role>",T("cli.roleOption")).option("-l, --lang <lang>",T("cli.langOption")).option("-i, --interactive",T("cli.interactiveModeOption")).option("--log-path <file>","Path for log file (defaults to <project>/logs/pithosai.log)").helpOption("-h, --help",T("cli.helpOption"));let I=(0,s.z)(E,T);I&&I.configureHelp(A);let O=(0,l.Q)(E,T);O&&O.configureHelp(A);let P=(0,h.e)(E,T);P&&P.configureHelp(A),(0,d.B)(E);let R=E.commands[E.commands.length-1];R&&R.configureHelp(A),(0,f.F)(E);let N=E.commands[E.commands.length-1];N&&N.configureHelp(A),(0,k.J)(E,T);let L=E.commands[E.commands.length-1];L&&L.configureHelp(A),(0,u.H)(E);let D=E.commands[E.commands.length-1];D&&D.configureHelp(A);let _=(0,p.N)(E,T);_&&_.configureHelp(A);let H=(0,m.O)(E,T);H&&H.configureHelp(A);let M=(0,c.Z)(E,T);M&&M.configureHelp(A);let F=(0,w.y)(E,T);F&&F.configureHelp(A);let j=(0,v.v)(E,T);j&&j.configureHelp(A);let $=(0,y.S)(E,T);return $&&$.configureHelp(A),(0,g.E)(E,T),E}i()}catch(e){i(e)}})},8601(e,t,r){function i(e){let t=e?.mode??"agent",r=["/install-skill ","/list","/list-skill","/new","/remove-skill ","/select ","/show","/show-prompt","/show-task","exit","quit"];return"agent"===t&&r.push("/shell"),r.sort((e,t)=>e.localeCompare(t)),r}function a(e){let t=i(e);return e=>[t.filter(t=>t.startsWith(e)),e]}function o(e){let t=i(e);return{getSuggestions(e,r,i){let a=(e[r]??"").slice(0,i),o=a.trimStart();if(o.startsWith("/")){let e=t.filter(e=>e.startsWith("/")&&e.startsWith(o));return 0===e.length?null:{items:e.map(e=>({value:e,label:e})),prefix:a}}let n=a.trim();if(""===n)return null;let s=t.filter(e=>!e.startsWith("/")&&e.startsWith(n));return 0===s.length?null:{items:s.map(e=>({value:e,label:e})),prefix:a}},applyCompletion(e,t,r,i,a){let o=e[t]??"",n=a.slice(0,a.length-a.trimStart().length),s=o.slice(0,r-a.length),l=o.slice(r),d=s+n+i.value+l,c=[...e];return c[t]=d,{lines:c,cursorLine:t,cursorCol:s.length+n.length+i.value.length}}}}function n(){let e=["continue","c","exit","e"].sort((e,t)=>e.localeCompare(t));return t=>[e.filter(e=>e.startsWith(t)),t]}r.d(t,{ML:()=>o,Q$:()=>n,ry:()=>a})},6765(e,t,r){r.a(e,async function(e,i){try{r.d(t,{E:()=>Q});var a=r(6760),o=r(1455),n=r(7598),s=r(481),l=r(3242),d=r(4768),c=r(8362),u=r(1048),p=r(5012),m=r(4071),h=r(2482),g=r(7175),f=r(3689),k=r(8359),w=r(5910),v=r(4267),y=r(829),b=r(9737),S=r(9782),T=r(161),E=r(1529),x=r(4427),C=r(8601),A=r(8691),I=r(9766),O=r(4361),P=r(8948),R=e([x,w,E,m,k,T,l,h,d,c,u,P,I,A,y]);[x,w,E,m,k,T,l,h,d,c,u,P,I,A,y]=R.then?(await R)():R;let J={write:e=>{process.stdout.write(e)},writeLn:e=>{process.stdout.write(e+"\n")}};function N(e){let{io:t,t:r,message:i,tuiSession:a=null}=e,o=(0,O.K)({t:r,message:i});a?((0,m.CN)(o),t.writeLn(A.m.red(o))):(0,m.vV)(o)}async function L(e,t,r){let{waitingMessage:i,runningMessage:a}=t,o="string"==typeof a&&""!==a.trim(),n=o?a:i;if(r){r.setLoading(!0,i,{runningMessage:o?a:null});try{return await e}finally{r.setLoading(!1)}}return(0,S.vg)(e,i,n)}async function D(e){let{markdown:t,runOpts:r,t:i,tuiSession:a=null}=e;if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER)return;let o=r.mode??"agent";if(("dialog"===o||"plan"===o)&&t?.trim())try{await (0,E.G)({markdown:t,t:i,tuiSession:a})}catch(t){let e=i("cli.resultPreviewFailed",{message:t?.message??String(t)});a?((0,m.CN)(e),a.getIo().writeLn(A.m.red(e))):(0,m.vV)(e)}}function _(e){let t=null!=e.timeout?1e3*e.timeout:null,r="string"==typeof process.env.PITHOSAI_TIMEOUT_MS?parseInt(process.env.PITHOSAI_TIMEOUT_MS,10):null;return t??r??p.TZ}async function H(e){let{trimmedRequest:t,runOpts:i,t:a,io:o=J,tuiSession:n=null}=e,s=i.mode??"agent";if(("dialog"===s||"plan"===s)&&t.toLowerCase().startsWith("/shell"))return o.writeLn(a("cli.shellDisabledInMode")),!0;if(!t.toLowerCase().startsWith("/shell"))return!1;let{executeShellCommand:l,formatShellResult:d}=await Promise.resolve().then(r.bind(r,2482)),c=t.substring(6).trim();if(!c)return o.writeLn(a("shell.noCommand")),!0;try{let e=_(i),t=await l(c,i.cwd,e,a),r=d(c,t,a);if(o.writeLn(r),!t.success){let e=a("shell.logFailed",{command:c,code:null!=t.exitCode?String(t.exitCode):"N/A"});n?((0,m.CN)(e),o.writeLn(A.m.red(e))):(0,m.vV)(e)}}catch(t){o.writeLn(a("shell.executionError",{error:t.message}));let e=a("shell.logExecutionError",{message:t.message});n?((0,m.CN)(e),o.writeLn(A.m.red(e))):(0,m.vV)(e)}return!0}async function M(e){let{globalOpts:t,t:r,skillsIo:i}=e;await (0,g.At)({globalOpts:t,t:r,io:i})}async function F(e){let{globalOpts:t,t:r,skillsIo:i,parsed:a}=e;await (0,g.NB)({skillName:a.skillName,force:a.force,globalOpts:t,t:r,io:i})}async function j(e){let{globalOpts:t,t:r,skillsIo:i,parsed:a}=e;await (0,g.HM)({skillName:a.skillName,globalOpts:t,t:r,io:i})}async function $(e){let{trimmedRequest:t,runOpts:r,t:i,io:a=J,tuiSession:o=null}=e,n=(0,f.D)(t);if(!n)return!1;if("invalid"===n.type)return"list"===n.command?a.writeLn(i("run.skillSlash.listNoExtra")):"install"===n.command?a.writeLn(i("run.skillSlash.installUsage")):a.writeLn(i("run.skillSlash.removeUsage")),!0;let s={cwd:r.cwd,lang:r.lang??(0,c.a)()},l={log:e=>a.writeLn(e),warn:e=>a.writeLn(e),writeStdout:e=>a.write(e)};try{"list"===n.type?await M({globalOpts:s,t:i,skillsIo:l}):"install"===n.type?await F({globalOpts:s,t:i,skillsIo:l,parsed:n}):await j({globalOpts:s,t:i,skillsIo:l,parsed:n})}catch(t){let e=i("run.skillSlash.failed",{message:t?.message??String(t)});o?((0,m.CN)(e),a.writeLn(A.m.red(e))):(0,m.vV)(e)}return!0}async function z(e){let{body:t,runOpts:r,t:i,taskRef:s,controller:d,io:c=J,tuiSession:u=null,outputSink:p=null}=e,m=_(r)+1e4,h={id:s.taskId,status:"pending",title:t,description:"",createdAt:new Date().toISOString(),section:null},g={...d?{...r,controller:d}:r,mode:"plan",outputSink:p??{write(){}}},f=function(e){let t=String(e).split(/\r?\n/)[0].trim(),r=t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"");if(!r){let e=(0,n.createHash)("md5").update(t||"plan","utf8").digest("hex").slice(0,8);return`${e}-plan.md`}return r.length>80&&(r=r.slice(0,80).replace(/-+$/g,"")),`${r}-plan.md`}(t),k=(0,a.resolve)((0,a.join)(r.cwd,f)),w=(0,b.n)((0,l.Ty)(h,g),m,()=>Error(i("errors.runTimeout",{seconds:String(Math.round(m/1e3))})));try{let e=await L(w,{waitingMessage:i("cli.planRunning")},u),t=(e&&"string"==typeof e.result&&e.result.length>0?e.result:Array.isArray(e?.results)&&e.results.length>0?e.results.join("\n\n"):"")??"";await (0,o.writeFile)(k,t,"utf8"),c.writeLn(i("cli.planWritten",{path:k})),t.trim()&&t.length>1024&&await D({markdown:t,runOpts:r,t:i,tuiSession:u}),e&&!1===e.success&&e.error&&N({io:c,t:i,message:e.error,tuiSession:u})}catch(e){if(d&&(d.status===v.i.STOPPED||d.status===v.i.PAUSED))return;N({io:c,t:i,message:e?.message??String(e),tuiSession:u})}}function U(e){return e.replace(/\r\n?/g,"\n").replace(/\n/g,"<br>").replace(/\|/g,"\\|")}async function q(e,t,r,i=J,o=null){if(!/^\/show-prompt\s*$/i.test(e))return!1;let n=r.cwd,s=await (0,d.s)(n),l=r.lang??s?.lang??(0,c.a)(),u=r.role??s?.supportedRoles?.[0]??"RD",p=r.mode??"agent";if(!["agent","dialog","plan"].includes(p))return i.writeLn(t("cli.showPromptInvalidMode")),!0;try{let e="agent"===p?(0,a.resolve)(n,".pithosai","skills"):void 0,s=(await (0,x.Ex)({cwd:n,lang:l,role:u,mode:p,skillsDir:e})).systemPrompt;if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER){let e=!0===r.markdown?(0,T.o)(s):s;return i.writeLn(e),!0}try{await (0,E.G)({markdown:s,t,documentTitle:t("run.showPrompt.previewDocumentTitle"),tuiSession:o})}catch(r){let e=t("cli.resultPreviewFailed",{message:r?.message??String(r)});o?((0,m.CN)(e),i.writeLn(A.m.red(e))):(0,m.vV)(e)}return!0}catch(e){return i.writeLn(t("cli.showPromptError",{message:e&&"object"==typeof e&&"message"in e?String(e.message):String(e)})),!0}}async function W(e,t,r,i,a=J){if(!/^\/show(\s+.*)?$/i.test(e))return!1;let o=await (0,k.Lf)(),n=await (0,k.gg)(o,t.taskId),s=await (0,k.XV)(o,{taskId:t.taskId,asc:!1,limit:1e6}),l=Array.isArray(s)?s:[],d=l.length,c=function(e){let t={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0};for(let r of e){let e=function(e){if(e&&"object"==typeof e)return e;if("string"!=typeof e||""===e.trim())return null;try{let t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch{return null}}(r?.message),i=e?.usage;i&&"object"==typeof i&&("number"==typeof i.input&&Number.isFinite(i.input)&&(t.input+=i.input),"number"==typeof i.output&&Number.isFinite(i.output)&&(t.output+=i.output),"number"==typeof i.cacheRead&&Number.isFinite(i.cacheRead)&&(t.cacheRead+=i.cacheRead),"number"==typeof i.cacheWrite&&Number.isFinite(i.cacheWrite)&&(t.cacheWrite+=i.cacheWrite),"number"==typeof i.totalTokens&&Number.isFinite(i.totalTokens)&&(t.totalTokens+=i.totalTokens))}return t}(l),u=i.mode??"agent",p=n?.model?String(n.model):"string"==typeof i.cursor&&""!==i.cursor.trim()?`cursor:${i.cursor.trim()}`:!0===i.reasoner?"deepSeekReasoner":!0===i.chat?"deepSeekChat":"deepSeekCoder",m=n?.status?String(n.status):"unknown",h=(0,w.vt)(n?.title?String(n.title):"",30),g=`
|
|
461
329
|
---
|
|
462
|
-
### ${
|
|
330
|
+
### ${r("run.show.title")}
|
|
463
331
|
|
|
464
|
-
| ${
|
|
332
|
+
| ${r("run.show.field")} | ${r("run.show.value")} |
|
|
465
333
|
| --- | --- |
|
|
466
|
-
| ${
|
|
467
|
-
| ${
|
|
468
|
-
| ${
|
|
469
|
-
| ${
|
|
470
|
-
| ${
|
|
471
|
-
| ${
|
|
472
|
-
| ${
|
|
473
|
-
| ${
|
|
474
|
-
| ${
|
|
475
|
-
| ${
|
|
476
|
-
| ${
|
|
477
|
-
`,f=!0===r.markdown?(0,T.o)(g):g;return s.writeLn(f),!0}async function B(e,t,i,r,s=J,o=null){let a=/^\/show-task(?:\s+(\d+))?\s*$/i.exec(e);if(!a)return!1;let n=await (0,w.Lf)(),l=t.taskId;if(null!=a[1]){let e=Number(a[1]),r=Array.isArray(t.persistedTasks)&&t.persistedTasks.length>0?t.persistedTasks:(0,w.Vk)(n);if(t.persistedTasks=r,!Array.isArray(r)||0===r.length)return s.writeLn(i("run.list.noPersistedTasks")),s.writeLn(i("run.list.createTasksFirstHint")),!0;let o=r[e];if(!o)return s.writeLn(i("run.list.invalidIndex",{index:String(e),maxIndex:String(Math.max(0,r.length-1))})),!0;l=String(o.id??"")}let d=(0,w.XV)(n,{taskId:l,asc:!1});d=d.reverse();let c=(0,k.ZP)(d);if(0===c.length)return s.writeLn(i("run.showTask.emptyNoMessages")),!0;let u=(0,k.JT)({taskId:l,taskTitle:(Array.isArray(t.persistedTasks)?t.persistedTasks.find(e=>String(e?.id??"")===l)?.title:void 0)??(0,w.gg)(n,l)?.title??"",pairs:c,t:i});if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER){let e=!0===r.markdown?(0,T.o)(u):u;return s.writeLn(e),!0}try{await (0,C.G)({markdown:u,t:i,documentTitle:i("run.showTask.previewDocumentTitle"),tuiSession:o})}catch(t){let e=i("cli.resultPreviewFailed",{message:t?.message??String(t)});o?((0,h.CN)(e),s.writeLn(I.m.red(e))):(0,h.vV)(e)}return!0}async function W(e,t,i,r,s=J){if(!e.toLowerCase().startsWith("/list"))return!1;let o=await (0,w.Lf)(),a=(0,w.Vk)(o);if(t.persistedTasks=a,0===a.length)return s.writeLn(i("run.list.noPersistedTasks")),s.writeLn(i("run.list.createTasksFirstHint")),!0;let n=["",i("run.list.persistedTasksHeader",{count:String(a.length)}),"","| index | task id | task title | description | createTime |","| --- | --- | --- | --- | --- |"];for(let e=0;e<a.length;e++)n.push(function(e,t){let i=String(e.title??"").trim(),r=(0,k.vt)(i,30),s=z(r),o=String(e.description??"").trim(),a=(0,k.vt)(o,30),n=z(a),l=z(String(e.createdAt??"")),d=z(String(e.id??""));return`| ${t} | ${d} | ${s} | ${n} | ${l} |`}(a[e],e));n.push(""),n.push(i("run.list.selectTaskHint")),n.push("");let l=n.join("\n"),d=!0===r.markdown?(0,T.o)(l):l;return s.writeLn(d),!0}async function K(e,t,i,r){let{taskRef:s,controller:o,tuiSession:a=null,outputSink:n=null,io:d=J}=r,c=N(t)+1e4,u={id:s.taskId,status:"pending",title:e,description:"",createdAt:new Date().toISOString(),section:null},p=o?{...t,controller:o}:t;null!=n&&(p={...p,outputSink:n});let h=t.mode??"agent",m="dialog"===h?(0,l.Ty)(u,p):(0,l.eF)(u,p),g=(0,b.n)(m,c,()=>Error(i("errors.runTimeout",{seconds:String(Math.round(c/1e3))})));try{if("dialog"===h){let e=await M(g,{waitingMessage:i("cli.waitingReply"),runningMessage:i("cli.runningReply")},a),r=(e&&"string"==typeof e.result&&e.result.length>0?e.result:Array.isArray(e?.results)&&e.results.length>0?e.results.join("\n\n"):"")??"";e&&!1===e.success&&e.error&&R({io:d,t:i,message:e.error,tuiSession:a}),r.trim()&&r.length>1024&&await L({markdown:r,runOpts:t,t:i,tuiSession:a})}else await M(g,{waitingMessage:i("cli.waitingReply"),runningMessage:i("cli.runningReply")},a)}catch(e){if(o&&(o.status===y.i.STOPPED||o.status===y.i.PAUSED))return;R({io:d,t:i,message:e?.message??String(e),tuiSession:a})}}async function V(e,t,i,r){let{taskRef:s,controller:o,io:n=J,tuiSession:l=null,outputSink:d=null}=r,c=l&&"function"==typeof l.getAgentOutputSink?l.getAgentOutputSink():d??null,u=e.trim();if(await D({trimmedRequest:u,runOpts:t,t:i,io:n,tuiSession:l})||await $({trimmedRequest:u,runOpts:t,t:i,io:n,tuiSession:l})||await W(u,s,i,t,n)||await B(u,s,i,t,n,l)||await U(u,i,t,n,l)||await q(u,s,i,t,n))return;let p=function(e,t,i,r=J){let s=/^\/select\s+(\d+)\s*$/i.exec(e);if(!s)return{handled:!1};let o=t.persistedTasks;if(!Array.isArray(o)||0===o.length)return r.writeLn(i("run.list.noTasksCached")),{handled:!0};let a=Number(s[1]),n=o[a];return n?(t.taskId=n.id,{handled:!0,selectedTaskId:String(n.id),selectedIndex:a}):(r.writeLn(i("run.list.invalidIndex",{index:String(a),maxIndex:String(Math.max(0,o.length-1))})),{handled:!0})}(u,s,i,n);if(p.handled){p.selectedTaskId&&"number"==typeof p.selectedIndex&&(n.writeLn(i("run.list.selectedTask",{index:String(p.selectedIndex)})),await q("/show",s,i,t,n));return}if(u.toLowerCase().startsWith("/select"))return void n.writeLn(i("run.list.selectUsage"));let h=/^\/new(\s+|$)/i.test(u)?(s.taskId=(0,a.randomUUID)(),u.replace(/^\/new\s*/i,"").trim()):u;""!==h&&("plan"===t.mode?await j({body:h,runOpts:t,t:i,taskRef:s,controller:o,io:n,tuiSession:l,outputSink:c}):await K(h,t,i,{taskRef:s,controller:o,tuiSession:l,outputSink:c,io:n}))}async function G(e,t,i){let r,s=new y.w,o=e.mode??"agent";for(r=e.mode??"agent",process.stdout.write(t("run.interactiveExitHint")+"\n"),"dialog"===r?process.stdout.write(t("run.replIntroDialog")+"\n"):"plan"===r?process.stdout.write(t("run.replIntroPlan")+"\n"):process.stdout.write(t("run.shellHint")+"\n"),process.stdout.write(t("run.newSessionHint")+"\n"),process.stdout.write(t("run.controlHint")+"\n"),process.stdout.write(t("run.replTabCompletionHint")+"\n");;){let r=await function(e,t){return new Promise(i=>{let r=(0,n.createInterface)({input:process.stdin,output:process.stdout,completer:(0,x.ry)(t)});r.question(e,e=>{r.close(),i(e??"")})})}(t("run.interactivePrompt"),e),a=("string"==typeof r?r:"").replace(/\r\n?/g,"\n").trim(),l=a.toLowerCase();if(("exit"===l||"quit"===l)&&process.exit(0),""===a)continue;if(("dialog"===o||"plan"===o)&&a.toLowerCase().startsWith("/shell")){process.stdout.write(t("cli.shellDisabledInMode")+"\n");continue}let d=N(e);await (0,m.as)({line:a,cwd:e.cwd,t,timeoutMs:d})||await (0,v.w)({title:a,...i},{controller:s,t,execute:(r,o)=>V(o,e,t,{taskRef:i,controller:s})})}}function Y(e,t){return e.argument("[request]",t("cli.requestArgument")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("--skills-dir <dir>",t("cli.skillsDirOption")).option("--reasoner",t("cli.reasonerOption"),!1).option("--chat",t("cli.chatOption"),!1).option("--cursor [model]",t("cli.cursorOption")).option("--timeout <seconds>",t("cli.timeoutOption")).option("--no-interactive",t("cli.interactiveOption")).option("--no-markdown","Plain text output only (default: markdown when TTY)").option("--mode <agent|dialog|plan>",t("cli.modeOption"),"agent").addHelpText("after",t("cli.runExamples")).action(async function(t){var i;let r,o,n,l=e.opts(),p=this.optsWithGlobals?this.optsWithGlobals():this.opts(),h=void 0===t||"string"==typeof t&&""===t.trim();if(h&&!l.interactive)return void e.outputHelp();let m={taskId:(0,a.randomUUID)()},g=(0,s.resolve)(p.cwd||process.cwd()),f=await (0,d.s)(g),w=l.lang??f?.lang??(0,c.a)(),k=(0,c.l)(w);await (0,u.e)(g,l.logPath);let b=(r=null!=p.timeout?Number(p.timeout):void 0,o=!1!==p.markdown&&!!process.stdout.isTTY,{cwd:g,skillsDir:p.skillsDir,reasoner:!0===p.reasoner,chat:!0===p.chat,cursor:p.cursor||void 0,lang:l.lang,role:l.role,timeout:r,markdown:o,mode:(i=p.mode,n="string"==typeof i?i.trim().toLowerCase():"agent","dialog"===n||"plan"===n?n:"agent")}),S=!1!==p.interactive&&(!h||l.interactive);if((0,A.YP)()&&S){let e=new A.$i({t:k,cwd:g,runOpts:b});e.start();try{h&&l.interactive&&((0,A.Ym)({session:e,cwd:g,t:k,mode:b.mode??"agent"}),(0,A.d1)(e,b,k));let i=new y.w,r=async t=>{await (0,v.w)({title:t,...m},{controller:i,t:k,useKeypressInterceptor:!1,tuiSession:e,io:e.getIo(),execute:async(t,r)=>{e.attachControllerForRun(i);try{await V(r,b,k,{taskRef:m,controller:i,io:e.getIo(),tuiSession:e})}finally{e.detachControllerForRun()}}})};for(h||(await r("string"==typeof t?t:String(t??"")),await new Promise(e=>setImmediate(e)));;){let t=await e.readSubmittedLine(),i="string"==typeof t?t.replace(/\r\n?/g,"\n").trim():"";""!==i&&e.clearTranscriptViewportPin();let s=i.toLowerCase();if("exit"===s||"quit"===s)break;if(""!==i){if(("dialog"===b.mode||"plan"===b.mode)&&i.toLowerCase().startsWith("/shell")){e.getIo().writeLn(k("cli.shellDisabledInMode"));continue}e.appendLine(`${I.m.green.bold(k("run.tuiYouLabel"))} ${i}`),await r(i)}}}finally{e.stop()}return}let T=new y.w;h&&l.interactive?function(e,t,i="agent"){if("dialog"===i){process.stdout.write(t("run.interactiveModeDialogTitle")+"\n"),process.stdout.write(t("run.interactiveModeCwd",{cwd:e})+"\n"),process.stdout.write(t("run.interactiveModeDialogTips")+"\n\n");return}if("plan"===i){process.stdout.write(t("run.interactiveModePlanTitle")+"\n"),process.stdout.write(t("run.interactiveModeCwd",{cwd:e})+"\n"),process.stdout.write(t("run.interactiveModePlanTips")+"\n\n");return}process.stdout.write(t("run.interactiveModeAgentTitle")+"\n"),process.stdout.write(t("run.interactiveModeCwd",{cwd:e})+"\n"),process.stdout.write(t("run.interactiveModeAgentTips")+"\n\n")}(g,k,b.mode??"agent"):h||await (0,v.w)({title:t,...m},{controller:T,t:k,tuiSession:null,io:J,execute:(e,t)=>V(t,b,k,{taskRef:m,controller:T})}),await new Promise(e=>setImmediate(e)),S&&await G(b,k,m)}),e}r()}catch(e){r(e)}})},1529(e,t,i){i.a(e,async function(e,r){try{i.d(t,{G:()=>a});var s=i(4071),o=e([s]);async function a(e){let{markdown:t,t:r,documentTitle:o,tuiSession:a=null}=e;if(t&&"string"==typeof t&&t.trim()){if("chrome"==("chrome"===process.env.PITHOSAI_RESULT_BROWSER?"chrome":"terminal")){let{showMarkdownResultInPlaywright:e}=await Promise.resolve().then(i.bind(i,6973)),s=a&&"function"==typeof a.getAgentOutputSink?a.getAgentOutputSink():null;await e({markdown:t,t:r,documentTitle:o,outputSink:s});return}try{let{showMarkdownInPiTui:e}=await i.e("935").then(i.bind(i,8498));await e({markdown:t,t:r,documentTitle:o,tuiSession:a})}catch(e){(0,s.vV)(r("cli.resultPreviewFailed",{message:e?.message??String(e)}))}}}s=(o.then?(await o)():o)[0],r()}catch(e){r(e)}})},4361(e,t,i){i.d(t,{K:()=>r});function r(e){let{t,message:i}=e,r=String(i??"").trim()||t("errors.unknownRunError");return t("errors.agentRunFailed",{message:r})}},6806(e,t,i){i.a(e,async function(e,r){try{i.d(t,{H:()=>d});var s=i(6760),o=i(8362),a=i(2482),n=i(4071),l=e([o,a,n]);function d(e){let t=e.command("shell").description("Execute shell commands").argument("[command]","Shell command to execute").option("-C, --cwd <dir>","Working directory (default: current directory)").option("--timeout <seconds>","Timeout in seconds (default: 30)","30").option("--raw","Output raw result without formatting").addHelpText("after",`
|
|
334
|
+
| ${r("run.show.taskId")} | ${t.taskId} |
|
|
335
|
+
| ${r("cli.taskLabelTitle")} | ${h} |
|
|
336
|
+
| ${r("run.show.mode")} | ${u} |
|
|
337
|
+
| ${r("run.show.model")} | ${p} |
|
|
338
|
+
| ${r("run.show.status")} | ${m} |
|
|
339
|
+
| ${r("run.show.messageCount")} | ${String(d)} |
|
|
340
|
+
| ${r("run.show.usageInput")} | ${String(c.input)} |
|
|
341
|
+
| ${r("run.show.usageOutput")} | ${String(c.output)} |
|
|
342
|
+
| ${r("run.show.usageCacheRead")} | ${String(c.cacheRead)} |
|
|
343
|
+
| ${r("run.show.usageCacheWrite")} | ${String(c.cacheWrite)} |
|
|
344
|
+
| ${r("run.show.usageTotalTokens")} | ${String(c.totalTokens)} |
|
|
345
|
+
`,f=!0===i.markdown?(0,T.o)(g):g;return a.writeLn(f),!0}async function B(e,t,r,i,a=J,o=null){let n=/^\/show-task(?:\s+(\d+))?\s*$/i.exec(e);if(!n)return!1;let s=await (0,k.Lf)(),l=t.taskId;if(null!=n[1]){let e=Number(n[1]),i=Array.isArray(t.persistedTasks)&&t.persistedTasks.length>0?t.persistedTasks:await (0,k.Vk)(s);if(t.persistedTasks=i,!Array.isArray(i)||0===i.length)return a.writeLn(r("run.list.noPersistedTasks")),a.writeLn(r("run.list.createTasksFirstHint")),!0;let o=i[e];if(!o)return a.writeLn(r("run.list.invalidIndex",{index:String(e),maxIndex:String(Math.max(0,i.length-1))})),!0;l=String(o.id??"")}let d=await (0,k.XV)(s,{taskId:l,asc:!1});d=d.reverse();let c=(0,w.ZP)(d);if(0===c.length)return a.writeLn(r("run.showTask.emptyNoMessages")),!0;let u=(0,w.JT)({taskId:l,taskTitle:(Array.isArray(t.persistedTasks)?t.persistedTasks.find(e=>String(e?.id??"")===l)?.title:void 0)??(await (0,k.gg)(s,l))?.title??"",pairs:c,t:r});if("1"===process.env.PITHOSAI_SKIP_RESULT_BROWSER){let e=!0===i.markdown?(0,T.o)(u):u;return a.writeLn(e),!0}try{await (0,E.G)({markdown:u,t:r,documentTitle:r("run.showTask.previewDocumentTitle"),tuiSession:o})}catch(t){let e=r("cli.resultPreviewFailed",{message:t?.message??String(t)});o?((0,m.CN)(e),a.writeLn(A.m.red(e))):(0,m.vV)(e)}return!0}async function K(e,t,r,i,a=J){if(!e.toLowerCase().startsWith("/list"))return!1;let o=await (0,k.Lf)(),n=await (0,k.Vk)(o);if(t.persistedTasks=n,0===n.length)return a.writeLn(r("run.list.noPersistedTasks")),a.writeLn(r("run.list.createTasksFirstHint")),!0;let s=["",r("run.list.persistedTasksHeader",{count:String(n.length)}),"","| index | task id | task title | description | createTime |","| --- | --- | --- | --- | --- |"];for(let e=0;e<n.length;e++)s.push(function(e,t){let r=String(e.title??"").trim(),i=(0,w.vt)(r,30),a=U(i),o=String(e.description??"").trim(),n=(0,w.vt)(o,30),s=U(n),l=U(String(e.createdAt??"")),d=U(String(e.id??""));return`| ${t} | ${d} | ${a} | ${s} | ${l} |`}(n[e],e));s.push(""),s.push(r("run.list.selectTaskHint")),s.push("");let l=s.join("\n"),d=!0===i.markdown?(0,T.o)(l):l;return a.writeLn(d),!0}async function V(e,t,r,i){let{taskRef:a,controller:o,tuiSession:n=null,outputSink:s=null,io:d=J}=i,c=_(t)+1e4,u={id:a.taskId,status:"pending",title:e,description:"",createdAt:new Date().toISOString(),section:null},p=o?{...t,controller:o}:t;null!=s&&(p={...p,outputSink:s});let m=t.mode??"agent",h="dialog"===m?(0,l.Ty)(u,p):(0,l.eF)(u,p),g=(0,b.n)(h,c,()=>Error(r("errors.runTimeout",{seconds:String(Math.round(c/1e3))})));try{if("dialog"===m){let e=await L(g,{waitingMessage:r("cli.waitingReply"),runningMessage:r("cli.runningReply")},n),i=(e&&"string"==typeof e.result&&e.result.length>0?e.result:Array.isArray(e?.results)&&e.results.length>0?e.results.join("\n\n"):"")??"";e&&!1===e.success&&e.error&&N({io:d,t:r,message:e.error,tuiSession:n}),i.trim()&&i.length>1024&&await D({markdown:i,runOpts:t,t:r,tuiSession:n})}else await L(g,{waitingMessage:r("cli.waitingReply"),runningMessage:r("cli.runningReply")},n)}catch(e){if(o&&(o.status===v.i.STOPPED||o.status===v.i.PAUSED))return;N({io:d,t:r,message:e?.message??String(e),tuiSession:n})}}async function Y(e,t,r,i){let{taskRef:a,controller:o,io:s=J,tuiSession:l=null,outputSink:d=null}=i,c=l&&"function"==typeof l.getAgentOutputSink?l.getAgentOutputSink():d??null,u=e.trim();if(await H({trimmedRequest:u,runOpts:t,t:r,io:s,tuiSession:l})||await $({trimmedRequest:u,runOpts:t,t:r,io:s,tuiSession:l})||await K(u,a,r,t,s)||await B(u,a,r,t,s,l)||await q(u,r,t,s,l)||await W(u,a,r,t,s))return;let p=function(e,t,r,i=J){let a=/^\/select\s+(\d+)\s*$/i.exec(e);if(!a)return{handled:!1};let o=t.persistedTasks;if(!Array.isArray(o)||0===o.length)return i.writeLn(r("run.list.noTasksCached")),{handled:!0};let n=Number(a[1]),s=o[n];return s?(t.taskId=s.id,{handled:!0,selectedTaskId:String(s.id),selectedIndex:n}):(i.writeLn(r("run.list.invalidIndex",{index:String(n),maxIndex:String(Math.max(0,o.length-1))})),{handled:!0})}(u,a,r,s);if(p.handled){p.selectedTaskId&&"number"==typeof p.selectedIndex&&(s.writeLn(r("run.list.selectedTask",{index:String(p.selectedIndex)})),await W("/show",a,r,t,s));return}if(u.toLowerCase().startsWith("/select"))return void s.writeLn(r("run.list.selectUsage"));let m=/^\/new(\s+|$)/i.test(u)?(a.taskId=(0,n.randomUUID)(),u.replace(/^\/new\s*/i,"").trim()):u;""!==m&&("plan"===t.mode?await z({body:m,runOpts:t,t:r,taskRef:a,controller:o,io:s,tuiSession:l,outputSink:c}):await V(m,t,r,{taskRef:a,controller:o,tuiSession:l,outputSink:c,io:s}))}async function G(e,t,r){let i,a=new v.w,o=e.mode??"agent";for(i=e.mode??"agent",process.stdout.write(t("run.interactiveExitHint")+"\n"),"dialog"===i?process.stdout.write(t("run.replIntroDialog")+"\n"):"plan"===i?process.stdout.write(t("run.replIntroPlan")+"\n"):process.stdout.write(t("run.shellHint")+"\n"),process.stdout.write(t("run.newSessionHint")+"\n"),process.stdout.write(t("run.controlHint")+"\n"),process.stdout.write(t("run.replTabCompletionHint")+"\n");;){let i=await function(e,t){return new Promise(r=>{let i=(0,s.createInterface)({input:process.stdin,output:process.stdout,completer:(0,C.ry)(t)});i.question(e,e=>{i.close(),r(e??"")})})}(t("run.interactivePrompt"),e),n=("string"==typeof i?i:"").replace(/\r\n?/g,"\n").trim(),l=n.toLowerCase();if(("exit"===l||"quit"===l)&&process.exit(0),""===n)continue;if(("dialog"===o||"plan"===o)&&n.toLowerCase().startsWith("/shell")){process.stdout.write(t("cli.shellDisabledInMode")+"\n");continue}let d=_(e);await (0,h.as)({line:n,cwd:e.cwd,t,timeoutMs:d})||await (0,y.w)({title:n,...r},{controller:a,t,execute:(i,o)=>Y(o,e,t,{taskRef:r,controller:a})})}}function Q(e,t){return e.argument("[request]",t("cli.requestArgument")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("--skills-dir <dir>",t("cli.skillsDirOption")).option("--reasoner",t("cli.reasonerOption"),!1).option("--chat",t("cli.chatOption"),!1).option("--cursor [model]",t("cli.cursorOption")).option("--timeout <seconds>",t("cli.timeoutOption")).option("--no-interactive",t("cli.interactiveOption")).option("--no-markdown","Plain text output only (default: markdown when TTY)").option("--mode <agent|dialog|plan>",t("cli.modeOption"),"agent").addHelpText("after",t("cli.runExamples")).action(async function(t){var r;let i,o,s,l=e.opts(),p=this.optsWithGlobals?this.optsWithGlobals():this.opts(),m=void 0===t||"string"==typeof t&&""===t.trim();if(m&&!l.interactive)return void e.outputHelp();let h={taskId:(0,n.randomUUID)()},g=(0,a.resolve)(p.cwd||process.cwd()),f=await (0,d.s)(g),k=l.lang??f?.lang??(0,c.a)(),w=(0,c.l)(k);await (0,u.e)(g,l.logPath);let b=(i=null!=p.timeout?Number(p.timeout):void 0,o=!1!==p.markdown&&!!process.stdout.isTTY,{cwd:g,skillsDir:p.skillsDir,reasoner:!0===p.reasoner,chat:!0===p.chat,cursor:p.cursor||void 0,lang:l.lang,role:l.role,timeout:i,markdown:o,mode:(r=p.mode,s="string"==typeof r?r.trim().toLowerCase():"agent","dialog"===s||"plan"===s?s:"agent")}),S=!1!==p.interactive&&(!m||l.interactive);if((0,I.YP)()&&S){let e=new I.$i({t:w,cwd:g,runOpts:b});e.start(),(0,P.TS)(e.getIo(),{columns:e.terminal.columns});try{m&&l.interactive&&((0,I.Ym)({session:e,cwd:g,t:w,mode:b.mode??"agent"}),(0,I.d1)(e,b,w)),e.setTranscriptViewportPin(0);let r=new v.w,i=async t=>{await (0,y.w)({title:t,...h},{controller:r,t:w,useKeypressInterceptor:!1,tuiSession:e,io:e.getIo(),execute:async(t,i)=>{e.attachControllerForRun(r);try{await Y(i,b,w,{taskRef:h,controller:r,io:e.getIo(),tuiSession:e})}finally{e.detachControllerForRun()}}})};for(m||(await i("string"==typeof t?t:String(t??"")),await new Promise(e=>setImmediate(e)));;){let t=await e.readSubmittedLine(),r="string"==typeof t?t.replace(/\r\n?/g,"\n").trim():"";""!==r&&e.clearTranscriptViewportPin();let a=r.toLowerCase();if("exit"===a||"quit"===a)break;if(""!==r){if(("dialog"===b.mode||"plan"===b.mode)&&r.toLowerCase().startsWith("/shell")){e.getIo().writeLn(w("cli.shellDisabledInMode"));continue}e.appendLine(`${A.m.green.bold(w("run.tuiYouLabel"))} ${r}`),await i(r)}}}finally{e.stop()}return}let T=new v.w;m&&l.interactive?function(e,t,r="agent"){if("dialog"===r){process.stdout.write(t("run.interactiveModeDialogTitle")+"\n"),process.stdout.write(t("run.interactiveModeCwd",{cwd:e})+"\n"),process.stdout.write(t("run.interactiveModeDialogTips")+"\n\n");return}if("plan"===r){process.stdout.write(t("run.interactiveModePlanTitle")+"\n"),process.stdout.write(t("run.interactiveModeCwd",{cwd:e})+"\n"),process.stdout.write(t("run.interactiveModePlanTips")+"\n\n");return}process.stdout.write(t("run.interactiveModeAgentTitle")+"\n"),process.stdout.write(t("run.interactiveModeCwd",{cwd:e})+"\n"),process.stdout.write(t("run.interactiveModeAgentTips")+"\n\n")}(g,w,b.mode??"agent"):m||await (0,y.w)({title:t,...h},{controller:T,t:w,tuiSession:null,io:J,execute:(e,t)=>Y(t,b,w,{taskRef:h,controller:T})}),await new Promise(e=>setImmediate(e)),S&&await G(b,w,h)}),e}i()}catch(e){i(e)}})},1529(e,t,r){r.a(e,async function(e,i){try{r.d(t,{G:()=>n});var a=r(4071),o=e([a]);async function n(e){let{markdown:t,t:i,documentTitle:o,tuiSession:n=null}=e;if(t&&"string"==typeof t&&t.trim()){if("chrome"==("chrome"===process.env.PITHOSAI_RESULT_BROWSER?"chrome":"terminal")){let{showMarkdownResultInPlaywright:e}=await Promise.resolve().then(r.bind(r,6973)),a=n&&"function"==typeof n.getAgentOutputSink?n.getAgentOutputSink():null;await e({markdown:t,t:i,documentTitle:o,outputSink:a});return}try{let{showMarkdownInPiTui:e}=await r.e("935").then(r.bind(r,8498));await e({markdown:t,t:i,documentTitle:o,tuiSession:n})}catch(e){(0,a.vV)(i("cli.resultPreviewFailed",{message:e?.message??String(e)}))}}}a=(o.then?(await o)():o)[0],i()}catch(e){i(e)}})},4361(e,t,r){r.d(t,{K:()=>i});function i(e){let{t,message:r}=e,i=String(r??"").trim()||t("errors.unknownRunError");return t("errors.agentRunFailed",{message:i})}},6806(e,t,r){r.a(e,async function(e,i){try{r.d(t,{H:()=>d});var a=r(6760),o=r(8362),n=r(2482),s=r(4071),l=e([o,n,s]);function d(e){let t=e.command("shell").description("Execute shell commands").argument("[command]","Shell command to execute").option("-C, --cwd <dir>","Working directory (default: current directory)").option("--timeout <seconds>","Timeout in seconds (default: 30)","30").option("--raw","Output raw result without formatting").addHelpText("after",`
|
|
478
346
|
Examples:
|
|
479
347
|
$ pithosai shell "ls -la"
|
|
480
348
|
$ pithosai shell "git status" --cwd ./my-project
|
|
481
349
|
$ pithosai shell "npm test" --timeout 60
|
|
482
|
-
$ pithosai shell --raw "echo hello"`);return t.action(async function(i
|
|
350
|
+
$ pithosai shell --raw "echo hello"`);return t.action(async function(r,i){let l=e.opts(),d=this.optsWithGlobals?this.optsWithGlobals():{...l,...i},c=d.lang||"en",u=(0,o.l)(c),p=(0,a.resolve)(d.cwd||process.cwd()),m=1e3*Number(d.timeout);if(!r||""===r.trim()){console.error(u("shell.noCommand")),t.help();return}try{let e=await (0,n.executeShellCommand)(r,p,m,u);if(d.raw)e.output&&process.stdout.write(e.output),e.error&&process.stderr.write(e.error),process.exit(+!e.success);else{let t=(0,n.formatShellResult)(r,e,u);console.log(t),e.success||((0,s.vV)(`Shell command failed: ${r} (exit code: ${e.exitCode})`),process.exit(e.exitCode||1))}}catch(e){console.error(u("shell.executionError",{error:e.message})),(0,s.vV)(`Shell command execution error: ${e.message}`),process.exit(1)}}),t}[o,n,s]=l.then?(await l)():l,i()}catch(e){i(e)}})},2457(e,t,r){r.a(e,async function(e,i){try{r.d(t,{N:()=>c});var a=r(8362),o=r(9616),n=r(4071),s=r(9782),l=e([a,o,n]);[a,o,n]=l.then?(await l)():l;let u=`You are a shell assistant. Output only the shell commands that fulfill the user's request.
|
|
483
351
|
Do not output any explanation, markdown, code fences, or other text. Only raw shell commands.
|
|
484
|
-
If multiple commands are needed, output one command per line.`;async function d(e,t,
|
|
485
|
-
📊 ${e.skillName}`),(0,u.fH)(` Score: ${e.score.toFixed(1)}/100`),(0,u.fH)(` Executions: ${
|
|
486
|
-
📈 ${
|
|
487
|
-
${
|
|
488
|
-
${
|
|
489
|
-
${
|
|
490
|
-
${
|
|
491
|
-
${
|
|
492
|
-
${
|
|
493
|
-
📊 ${o("skillConvert.generalStats")}:`),(0,u.fH)(` ${o("skillConvert.totalExecutions")}: ${
|
|
494
|
-
📝 ${o("skillConvert.recentExecutions")}:`),
|
|
495
|
-
🎯 ${o("skillConvert.commonParameters")}:`),
|
|
496
|
-
📈 ${o("skillConvert.overallStats")}:`),(0,u.fH)(` ${o("skillConvert.totalSkillsTracked")}: ${e.totalSkills}`),(0,u.fH)(` ${o("skillConvert.totalExecutions")}: ${e.totalExecutions}`),(0,u.fH)(` ${o("skillConvert.avgSuccessRate")}: ${e.avgSuccessRate.toFixed(1)}%`),e.topSkills.length>0)for(let
|
|
497
|
-
🏆 ${o("skillConvert.topSkills")}:`),e.topSkills)){let e=t.stats[
|
|
498
|
-
💡 ${o("skillConvert.conversionSuggestions")}:`),
|
|
499
|
-
${s} ${e.name}`),(0,u.fH)(` ${e.description}`),(0,u.fH)(` ${t("skillConvert.originalSkill")}: ${e.metadata.originalSkill}`),(0,u.fH)(` ${t("skillConvert.converted")}: ${new Date(e.metadata.convertedAt).toLocaleDateString()}`),i&&(i.usageCount>0&&(0,u.fH)(` ${t("skillConvert.usageCount")}: ${i.usageCount}`),i.lastUsed&&(0,u.fH)(` ${t("skillConvert.lastUsed")}: ${new Date(i.lastUsed).toLocaleDateString()}`))}}catch(e){(0,u.vV)(t("skillConvert.toolsError",{error:e.message}))}}),r.command("remove <tool-name>").description("Remove a converted tool").action(async e=>{let t=process.cwd(),r=(0,c.l)("en");try{let s=await i.e("156").then(i.bind(i,6039));await s.confirm({message:r("skillConvert.confirmRemoveTool",{toolName:e}),initial:!1})?await (0,d.WO)(t,e)?(0,u.fH)(r("skillConvert.toolRemoved",{toolName:e})):(0,u.vV)(r("skillConvert.toolRemoveFailed",{toolName:e})):(0,u.fH)(r("skillConvert.removeCancelled"))}catch(e){(0,u.vV)(r("skillConvert.toolsError",{error:e.message}))}}),r.command("enable <tool-name>").description("Enable a disabled tool").action(async e=>{let t=process.cwd(),i=(0,c.l)("en");try{await (0,d.Pc)(t,e,!0)?(0,u.fH)(i("skillConvert.toolEnabled",{toolName:e})):(0,u.vV)(i("skillConvert.toolEnableFailed",{toolName:e}))}catch(e){(0,u.vV)(i("skillConvert.toolsError",{error:e.message}))}}),r.command("disable <tool-name>").description("Disable a tool (without removing it)").action(async e=>{let t=process.cwd(),i=(0,c.l)("en");try{await (0,d.Pc)(t,e,!1)?(0,u.fH)(i("skillConvert.toolDisabled",{toolName:e})):(0,u.vV)(i("skillConvert.toolDisableFailed",{toolName:e}))}catch(e){(0,u.vV)(i("skillConvert.toolsError",{error:e.message}))}}),t}[s,c,u]=p.then?(await p)():p,r()}catch(e){r(e)}})},3689(e,t,i){i.d(t,{D:()=>r});function r(e){let t=e.trim();if(!t.startsWith("/"))return null;if(/^\/list-skill\b/i.test(t))return t.replace(/^\/list-skill\s*/i,"").trim()?{type:"invalid",command:"list",reason:"extraArgs"}:{type:"list"};if(/^\/install-skill\b/i.test(t)){let e=t.replace(/^\/install-skill\s*/i,"").trim().split(/\s+/).filter(Boolean),i=!1,r=[];for(let t of e)"--force"===t?i=!0:r.push(t);return r.length>1?{type:"invalid",command:"install",reason:"tooManyArgs"}:{type:"install",force:i,skillName:r[0]}}if(/^\/remove-skill\b/i.test(t)){let e=t.replace(/^\/remove-skill\s*/i,"").trim();return e?{type:"remove",skillName:e}:{type:"invalid",command:"remove",reason:"missingName"}}return null}},7175(e,t,i){i.d(t,{At:()=>u,HM:()=>p,NB:()=>c,aE:()=>l});var r=i(6760),s=i(1455),o=i(3024),a=i(1421);let n=(0,i(7975).promisify)(a.exec);function l(){return{log:e=>{console.log(e)},warn:e=>{console.warn(e)},writeStdout:e=>{process.stdout.write(e)}}}async function d(e,t,i){try{var r;let s=`clawhub install ${e} --dir "${t}"`;return i&&(s=`${s} --force`),await (r=s,new Promise((e,t)=>{let i=(0,a.spawn)(r,{shell:!0,stdio:"inherit"});i.on("error",t),i.on("close",(i,r)=>{0===i?e():t(Error(`Command exited with code ${i??"null"}${r?` (signal ${r})`:""}`))})})),!0}catch(t){throw Error(`Failed to download skill "${e}": ${t.message}`)}}async function c(e){let{skillName:t,force:i=!1,globalOpts:o,t:a,io:l}=e,c=(0,r.resolve)(o.cwd||process.cwd()),u=(0,r.join)(c,".pithosai","skills");await (0,s.mkdir)(u,{recursive:!0}),l.log(a("skills.installing",{dir:u}));try{try{await n("which clawhub")}catch{throw Error("ClawHub CLI is not installed or not in PATH. Please install it first: npm install -g clawhub")}let e=[];if(t)e=[t];else{l.log(a("skills.fetchingList"));let t=await n("clawhub list | awk '{print $1}'"),i=function(e){if(null!=e&&"object"==typeof e&&"stdout"in e){let t=e.stdout;return null==t?"":String(t)}return Array.isArray(e)&&null!=e[0]?String(e[0]):""}(t);i&&(l.writeStdout(i),i.endsWith("\n")||l.writeStdout("\n"));let r=i.split("\n").map(e=>e.trim()).filter(Boolean);if(!r.length)return void l.warn(a("skills.noSkillsAvailable"));e=r}let r=0;for(let t of e)try{await d(t,u,i)&&(r++,l.log(a("skills.installed",{name:t})))}catch(e){l.warn(a("skills.downloadFailed",{name:t,error:e.message}))}l.log(a("skills.complete",{count:String(r),total:String(e.length)}))}catch(e){throw Error(`Failed to install skills: ${e.message}`)}}async function u(e){let{globalOpts:t,t:i,io:a}=e,n=(0,r.resolve)(t.cwd||process.cwd()),l=(0,r.join)(n,".pithosai","skills");if(!(0,o.existsSync)(l))return void a.log(i("skills.noSkillsDir"));try{let e=(await (0,s.readdir)(l)).filter(e=>"."!==e&&".."!==e);for(let t of(a.log(i("skills.installedList",{count:String(e.length),dir:l})),e)){let e=(0,r.basename)(t,".md"),i=(0,r.join)(l,t,"_meta.json");if((0,o.existsSync)(i))try{let e=await (0,s.readFile)(i,"utf-8"),t=JSON.parse(e);a.log(` • ${t.slug}: ${t.ownerId||"No description"}`),a.log(` Installed: ${t.publishedAt||"Unknown"}`)}catch{a.log(` • ${e}: (no metadata)`)}else a.log(` • ${e}: (no metadata)`)}}catch(e){throw Error(`Failed to list skills: ${e.message}`)}}async function p(e){let{skillName:t,globalOpts:i,t:a,io:n}=e,l=(0,r.resolve)(i.cwd||process.cwd()),d=(0,r.join)(l,".pithosai","skills");if(!(0,o.existsSync)(d))return void n.log(a("skills.noSkillsDir"));let c=(0,r.join)(d,t,"SKILL.md"),u=(0,r.join)(d,t,"_meta.json");if(!(0,o.existsSync)(c))return void n.warn(a("skills.notInstalled",{name:t}));try{await (0,s.unlink)(c),(0,o.existsSync)(u)&&await (0,s.unlink)(u);let e=(0,r.join)(d,t);await (0,s.rm)(e,{recursive:!0,force:!0}),n.log(a("skills.removed",{name:t}))}catch(e){throw Error(`Failed to remove skill "${t}": ${e.message}`)}}},3780(e,t,i){i.a(e,async function(e,r){try{i.d(t,{B:()=>l});var s=i(5347),o=i(8362),a=i(7175),n=e([s,o]);function l(e){let t=e.command("skills").description("Manage skills from Clawhub AI").option("-l, --lang <lang>","Language for prompts (default: en)").option("-C, --cwd <dir>","Project directory (default: current directory)");t.command("install").description("Install skills from Clawhub AI using ClawHub CLI").argument("[skill-name]","Specific skill name to install (default: all)").option("-f, --force","Force reinstall even if skill exists").action(async(t,i)=>{try{let r=e.opts(),s=(0,o.l)(r.lang||"en");await (0,a.NB)({skillName:t,force:!0===i.force,globalOpts:r,t:s,io:(0,a.aE)()})}catch(e){console.error(`Failed to install skills: ${e.message}`),process.exit(1)}}),t.command("list").description("List installed skills").action(async()=>{try{let t=e.opts(),i=(0,o.l)(t.lang||"en");await (0,a.At)({globalOpts:t,t:i,io:(0,a.aE)()})}catch(e){console.error(`Failed to list skills: ${e.message}`),process.exit(1)}}),t.command("remove").description("Remove installed skill").argument("<skill-name>","Skill name to remove").action(async t=>{try{let i=e.opts(),r=(0,o.l)(i.lang||"en");await (0,a.HM)({skillName:t,globalOpts:i,t:r,io:(0,a.aE)()})}catch(e){console.error(`Failed to remove skill: ${e.message}`),process.exit(1)}})}[s,o]=n.then?(await n)():n,r()}catch(e){r(e)}})},831(e,t,i){i.a(e,async function(e,r){try{i.d(t,{y:()=>f});var s=i(6760),o=i(9662),a=i(3242),n=i(5534),l=i(1773),d=i(4071),c=i(1048),u=i(4239),p=i(829),h=e([l,a,p,c,n,o,d]);async function m(e,t,{runOpts:i,t:r,controller:s,request:o}){let c=new n.j(e),u=(await c.parseTasks()).find(e=>e.id===t);u||((0,d.vV)(r("cli.taskNotFound",{taskId:t})),process.exit(1));let p=i??{cwd:process.cwd()},h=s?{...p,controller:s}:p,m="string"==typeof o&&""!==o.trim()?{...u,title:o,description:""}:u,g=new l.c;g.registerHandler("default",async e=>{let t=await (0,a.Ty)(e,h);return{success:t.success,message:t.success?r("cli.taskAgentCompleted"):t.error??r("cli.taskAgentRunFailed"),timestamp:new Date().toISOString(),output:t.result??t.error??""}});try{let e=await g.process(m);(0,d.KH)("result",JSON.stringify(e));let i=e?.timestamp??new Date().toISOString(),s=e?.output!=null?String(e.output):e?.message!=null?String(e.message):r("cli.taskDone");await c.markTaskAsCompleted(t,{result:s,completedAt:i})}catch(e){await c.markTaskAsFailed(t,e),(0,d.vV)(r("cli.taskFailed",{message:String(e?.message??e)})),process.exit(1)}}async function g(e,t,i,r){var s;let o,a=await e.parseTasks(),n=a.filter(e=>"processing"===e.status),l=null;if(n.length>0)l=n[0],(0,d.fH)(r("cli.taskStartingProcessorProcessing",{id:l.id,title:l.title}));else{let t=a.filter(e=>"pending"===e.status);if(0===t.length)return void(0,d.fH)(r("cli.taskNoPending"));l=t[0],await e.markTaskAsProcessing(l.id),(0,d.fH)(r("cli.taskPickedTask",{id:l.id,title:l.title}))}s=l,o=s.description?s.description.slice(0,80)+(s.description.length>80?"…":""):"",console.log(r("cli.taskProcessingHeader")),console.log(`${r("cli.taskLabelId")} ${s.id}`),console.log(`${r("cli.taskLabelTitle")} ${s.title}`),console.log(`${r("cli.taskLabelStatus")} ${s.status}`),o&&console.log(`${r("cli.taskLabelDescription")} ${o}`),console.log(r("cli.taskProcessingSeparator"));let c={...i,model:l.model||i.model},h=new u.w;try{await (0,p.w)(l,{controller:h,t:r,execute:async(e,i)=>{await m(t,l.id,{runOpts:c,t:r,controller:h,request:i})}})}catch(e){(0,d.vV)(r("cli.taskProcessorFailed",{message:e.message}))}}function f(e,t){let i=e.command("task").description(t("cli.taskDescription")).option("-f, --file <path>",t("cli.taskFileOption"),"").option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("-l, --lang <lang>",t("cli.langOption")).option("--skills-dir <dir>",t("cli.skillsDirOption")).option("--model <key>",t("cli.taskModelOption")).option("--timeout <seconds>",t("cli.timeoutOption")).option("--no-markdown","Plain text output only (default: markdown enabled)").option("--new-session",t("cli.taskNewSessionOption")).addHelpText("after",t("cli.taskExamples"));return i.action(async function(){let i=e.opts(),r=this.optsWithGlobals?this.optsWithGlobals():this.opts(),a=function(e,t={}){return{cwd:s.resolve(e.cwd||process.cwd()),skillsDir:e.skillsDir,lang:t.lang??e.lang,role:t.role??e.role,timeout:null!=e.timeout?Number(e.timeout):void 0,newSession:!0===e.newSession,model:e.model||void 0,markdown:!1!==e.markdown}}(r,i),l=a.cwd||process.cwd(),u=void 0!==r.file&&""!==r.file?r.file:"prompts.md",p=s.resolve(l,u);await (0,c.e)(l,i.logPath);let h=new n.j(p),m=new o.v(p),f=!1,w=!1,k=async()=>{if(f){w=!0;return}f=!0;try{do w=!1,await g(h,p,a,t);while(w)}finally{f=!1}};await m.initialize(),await k(),await m.watch(async()=>{await k()}),(0,d.fH)(t("cli.taskWatcherRunning"))}),i}[l,a,p,c,n,o,d]=h.then?(await h)():h,r()}catch(e){r(e)}})},4117(e,t,i){i.a(e,async function(e,r){try{i.d(t,{O:()=>c});var s=i(8362),o=i(9616),a=i(4071),n=i(9782),l=e([s,o,a]);[s,o,a]=l.then?(await l)():l;let u=`You are a writing assistant. Fulfill the user's request by writing the requested text.
|
|
352
|
+
If multiple commands are needed, output one command per line.`;async function d(e,t,r){let i=`${e.baseUrl.replace(/\/$/,"")}/chat/completions`,a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t?`Bearer ${t}`:""},body:JSON.stringify({model:e.id,messages:r,stream:!1,max_tokens:e.maxTokens??1024})});if(!a.ok){let e=await a.text();throw Error(`Ollama API error ${a.status}: ${e}`)}let o=await a.json(),n=o?.choices?.[0]?.message?.content;if(null==n)throw Error("Ollama API returned no content");return"string"==typeof n?n:String(n)}function c(e,t){let r=t||(0,a.l)("en"),i=e.command("shell-tips").description(r("shellTips.description")).argument("<request...>",r("shellTips.argument")).addHelpText("after",r("shellTips.examples"));return i.action(async function(t){let r=Array.isArray(t)?t.join(" ").trim():String(t).trim(),i=e.opts(),l=(this.optsWithGlobals?this.optsWithGlobals():{...i,...this.opts()}).lang||"en",c=(0,a.l)(l),p=process.env.CURSOR_MODEL;delete process.env.CURSOR_MODEL;let m=(0,o.aN)({local:!0});void 0!==p?process.env.CURSOR_MODEL=p:delete process.env.CURSOR_MODEL,m||((0,n.vV)(c("errors.ollamaNotConfigured")),process.exit(1));let{model:h,getApiKey:g}=m,f=await g();try{let e,t,i=(e=(await (0,s.$A)(d(h,f,[{role:"system",content:u},{role:"user",content:r}]),c("shellTips.loading"))).trim(),(t=/^```(?:bash|shell|sh)?\s*\n?([\s\S]*?)```/gm.exec(e))&&(e=t[1].trim()),e);i&&(process.stdout.write(i),i.endsWith("\n")||process.stdout.write("\n"))}catch(e){(0,n.vV)(e?.message??String(e)),process.exit(1)}}),i}i()}catch(e){i(e)}})},2482(e,t,r){r.a(e,async function(e,i){try{r.d(t,{as:()=>d,executeShellCommand:()=>s,formatShellResult:()=>l});var a=r(1421),o=r(4071),n=e([o]);async function s(e,t,r=3e4,i){return new Promise(n=>{if(!e||""===e.trim())return void n({success:!1,output:"",error:i?i("shell.errorNoCommand"):"No command provided after /shell prefix.",exitCode:1});(0,o.fH)(i?i("shell.executing",{command:e}):`[shell] Executing: ${e}`);let s=(0,a.spawn)(e,{shell:!0,cwd:t,stdio:["pipe","pipe","pipe"]}),l="",d="",c=null;s.stdout.on("data",e=>{l+=e.toString()}),s.stderr.on("data",e=>{d+=e.toString()}),s.on("error",e=>{c&&clearTimeout(c),n({success:!1,output:l,error:i?i("shell.errorSpawnFailed",{message:e.message}):`Failed to spawn process: ${e.message}`,exitCode:null})}),s.on("close",e=>{c&&clearTimeout(c),n({success:0===e,output:l,error:d,exitCode:e})}),c=setTimeout(()=>{s.kill("SIGTERM"),n({success:!1,output:l,error:i?i("shell.errorTimedOut",{seconds:String(r/1e3)}):`Command timed out after ${r/1e3} seconds`,exitCode:null})},r)})}function l(e,t,r){let i=null===t.exitCode?r("shell.resultExitCodeNa"):String(t.exitCode),a=r(t.success?"shell.resultSuccessYes":"shell.resultSuccessNo"),o=[];return o.push(r("shell.resultCommand",{command:e})),o.push(r("shell.resultExitCode",{code:i})),o.push(r("shell.resultSuccessLabel")+" "+a),t.output&&(o.push(""),o.push(r("shell.resultOutput")),o.push("─".repeat(50)),o.push(t.output.trim()),o.push("─".repeat(50))),t.error&&(o.push(""),o.push(r("shell.resultError")),o.push("─".repeat(50)),o.push(t.error.trim()),o.push("─".repeat(50))),o.join("\n")}async function d(e){let{line:t,cwd:r,t:i,timeoutMs:a=3e4,io:n=null}=e;if(!t.trim().toLowerCase().startsWith("/shell"))return!1;let d=n?.writeLn??(e=>process.stdout.write(e+"\n")),c=t.trim().substring(6).trim();if(!c)return d(i("shell.noCommand")),!0;try{let e=await s(c,r,a,i),t=l(c,e,i);d(t),d(""),e.success||(0,o.vV)(i("shell.logFailed",{command:c,code:null!=e.exitCode?String(e.exitCode):"N/A"}))}catch(e){d(i("shell.executionError",{error:e.message})),(0,o.vV)(i("shell.logExecutionError",{message:e.message}))}return!0}o=(n.then?(await n)():n)[0],i()}catch(e){i(e)}})},2734(e,t,r){r.a(e,async function(e,i){try{r.d(t,{S:()=>d});var a=r(6760),o=r(4768),n=r(8362),s=r(4427),l=e([n,o,s]);function d(e,t){return e.command("show-prompt").description(t("cli.showPromptDescription")).option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("-l, --lang <lang>",t("cli.langOption")).option("--mode <mode>",t("cli.showPromptModeOption"),"agent").option("--raw",t("cli.showPromptRawOption"),!1).option("--truncated",t("cli.showPromptTruncatedOption"),!1).action(async function(){let r=e.opts(),i=this.optsWithGlobals?this.optsWithGlobals():this.opts(),l=(0,a.resolve)(i.cwd||process.cwd()),d=r.lang??i.lang;if(!d){let e=await (0,o.s)(l);d=e?.lang??(0,n.a)()}let c=r.role??i.role;if(!c){let e=await (0,o.s)(l);c=e?.supportedRoles?.[0]??"RD"}let u=i.mode;["agent","dialog","plan"].includes(u)||(console.error(t("cli.showPromptInvalidMode")),process.exit(1));try{let e="agent"===u?(0,a.resolve)(l,".pithosai","skills"):void 0,t=await (0,s.Ex)({cwd:l,lang:d,role:c,mode:u,skillsDir:e});i.raw?console.log(t.systemPromptRaw):i.truncated?console.log(t.systemPromptTruncated):console.log(t.systemPrompt)}catch(e){console.error(t("cli.showPromptError",{message:e.message})),process.exit(1)}})}[n,o,s]=l.then?(await l)():l,i()}catch(e){i(e)}})},5910(e,t,r){r.a(e,async function(e,i){try{r.d(t,{JT:()=>d,ZP:()=>l,vt:()=>c});var a=r(8641),o=r(5935),n=e([a]);function s(e){if(e&&"object"==typeof e)return e;if("string"!=typeof e||""===e.trim())return null;try{let t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch{return null}}function l(e){if(!Array.isArray(e)||0===e.length)return[];let t=[],r=0;for(;r<e.length;){let i=s(e[r].message);if(i?.role!=="user"){r+=1;continue}let o=(0,a.JZ)(i),n="string"==typeof e[r].createdAt?e[r].createdAt:"";r+=1;let l=[];for(;r<e.length;){let t=s(e[r].message);if(t?.role==="user")break;if(t?.role==="assistant"){let e=(0,a.JZ)(t);e&&l.push(e)}r+=1}t.push({question:o,answer:l.join("\n\n"),createdAt:n})}return t.length>100?t.slice(0,100):t}function d(e){let{taskId:t,taskTitle:r,pairs:i,t:a}=e,o=c(r,30),n=[`## ${a("run.showTask.title")}`,"",`| ${a("run.show.field")} | ${a("run.show.value")} |`,"| --- | --- |",`| ${a("run.show.taskId")} | \`${t}\` |`,`| ${a("cli.taskLabelTitle")} | ${o} |`,"","---",""];for(let e=0;e<i.length;e++){let t=i[e];n.push(`### ${a("run.showTask.turnHeading",{index:String(e+1)})}`),n.push(""),n.push(`**${a("run.showTask.createdLabel")}:** ${t.createdAt||"—"}`),n.push(""),n.push(`**${a("run.showTask.questionLabel")}**`),n.push(""),n.push(t.question.trim()||a("run.showTask.emptyQuestion")),n.push(""),n.push(`**${a("run.showTask.answerLabel")}**`),n.push(""),n.push(t.answer.trim()?t.answer:a("run.showTask.emptyAnswer")),n.push(""),n.push("---"),n.push("")}return n.join("\n").trimEnd()}function c(e,t){if("string"!=typeof e||""===e.trim())return"—";if(!Number.isFinite(t)||t<=0)return e.trim();let r=e.trim();return(0,o.$0)(r)>t?`${function(e,t){let r="";for(let i of e){let e=r+i;if((0,o.$0)(e)>t)break;r=e}return r}(r,t)}...`:r}a=(n.then?(await n)():n)[0],i()}catch(e){i(e)}})},2555(e,t,r){r.a(e,async function(e,i){try{r.d(t,{F:()=>m});var a=r(5347),o=r(1455),n=r(6760),s=r(5846),l=r(2130),d=r(7536),c=r(8362),u=r(4071),p=e([a,c,u]);function m(e){let t=e.command("skill-convert").description("Convert successful skills to permanent tools").option("-C, --cwd <dir>","Project directory (default: current directory)").option("-l, --lang <lang>","Language for output (default: en)").action(async e=>{e.cwd||process.cwd();let r=e.lang||"en",i=(0,c.l)(r);(0,u.fH)(i("skillConvert.welcome")),process.argv.slice(3).length||t.help()});t.command("list").description("List skills that can be converted to tools").option("--threshold <score>","Minimum conversion score (0-100)","60").action(async(e,t)=>{let r=t.parent||{},i=r.opts&&r.opts().cwd||process.cwd(),a=r.opts&&r.opts().lang||"en",o=(0,c.l)(a);try{let t=new s.m(i),r=parseInt(e.threshold,10),a=t.getSuggestedConversions(r),n=t.getSummary();if((0,u.fH)(o("skillConvert.listHeader",{totalSkills:n.totalSkills,totalExecutions:n.totalExecutions})),0===a.length)return void(0,u.fH)(o("skillConvert.noSuggestions",{threshold:r}));for(let e of((0,u.fH)("\n"+o("skillConvert.suggestedConversions")),(0,u.fH)("=".repeat(60)),a)){let r=e.stats,i=(r.successfulExecutions/r.totalExecutions*100).toFixed(1);(0,u.fH)(`
|
|
353
|
+
📊 ${e.skillName}`),(0,u.fH)(` Score: ${e.score.toFixed(1)}/100`),(0,u.fH)(` Executions: ${r.totalExecutions} (${i}% success)`),(0,u.fH)(` Avg. Time: ${r.avgExecutionTime.toFixed(0)}ms`),(0,u.fH)(` Last Used: ${new Date(r.lastExecuted).toLocaleDateString()}`);let a=t.getCommonParameters(e.skillName,3);a.length>0&&(0,u.fH)(` Common Params: ${a.map(e=>e.param).join(", ")}`)}(0,u.fH)("\n"+o("skillConvert.convertHint"))}catch(e){(0,u.vV)(o("skillConvert.listError",{error:e.message}))}}),t.command("convert <skill-name>").description("Convert a skill to a permanent tool").option("--force","Force conversion even if tool exists").option("--dry-run","Show conversion report without actually converting").action(async(e,t,i)=>{let a=i.parent||{},d=a.opts&&a.opts().cwd||process.cwd(),p=a.opts&&a.opts().lang||"en",m=(0,c.l)(p);try{let i,a,c=new s.m(d),p=new l.f(d,c),h=(0,n.join)(d,".pithosai","skills"),g=(0,n.join)(h,e,"SKILL.md");try{let e=(i=await (0,o.readFile)(g,"utf-8")).match(/^---\n([\s\S]*?)\n---\n/);if(e){let t=e[1].split("\n");for(let e of(a={},t)){let t=e.match(/^(\w+):\s*(.+)$/);if(t){let[,e,r]=t;a[e]=r}}}}catch(t){(0,u.vV)(m("skillConvert.skillNotFound",{skillName:e,error:t.message}));return}if(p.toolExists(e)&&!t.force){(0,u.JE)(m("skillConvert.alreadyConverted",{skillName:e})),(0,u.fH)(m("skillConvert.useForceHint"));return}let f=await p.getConversionReport(e,i,a);for(let t of((0,u.fH)(m("skillConvert.conversionReportHeader",{skillName:e})),(0,u.fH)("=".repeat(60)),(0,u.fH)(`
|
|
354
|
+
📈 ${m("skillConvert.conversionScore")}: ${f.conversionScore.toFixed(1)}/100`),(0,u.fH)(`🔧 ${m("skillConvert.suggestedType")}: ${f.suggestedType}`),(0,u.fH)(`✅ ${m("skillConvert.ready")}: ${f.ready?"✓":"✗"}`),(0,u.fH)(`
|
|
355
|
+
${m("skillConvert.estimatedBenefits")}:`),(0,u.fH)(` 🚀 ${m("skillConvert.performance")}: +${f.estimatedBenefits.performance.toFixed(1)}%`),(0,u.fH)(` 🔒 ${m("skillConvert.reliability")}: +${f.estimatedBenefits.reliability.toFixed(1)}%`),(0,u.fH)(` 👤 ${m("skillConvert.usability")}: +${f.estimatedBenefits.usability.toFixed(1)}%`),(0,u.fH)(`
|
|
356
|
+
${m("skillConvert.parameters")}:`),f.parameters)){let e=t.required?"✓":"○";(0,u.fH)(` ${e} ${t.name} (${t.type}): ${t.description}`)}if(!f.ready&&!t.force){(0,u.JE)(`
|
|
357
|
+
${m("skillConvert.notReadyWarning")}`),(0,u.fH)(m("skillConvert.moreUsageHint"));return}if(t.dryRun)return void(0,u.fH)(`
|
|
358
|
+
${m("skillConvert.dryRunComplete")}`);if(!t.force){let t=await r.e("156").then(r.bind(r,6039));if(!await t.confirm({message:m("skillConvert.confirmConversion",{skillName:e}),initial:!0}))return void(0,u.fH)(m("skillConvert.conversionCancelled"))}(0,u.fH)(m("skillConvert.converting",{skillName:e}));let k=await p.convert(e,i,a),w=await p.saveTool(k);(0,u.fH)(m("skillConvert.conversionSuccess",{skillName:e,toolName:k.name,toolPath:w})),(0,u.fH)(`
|
|
359
|
+
${m("skillConvert.usageExample")}:`),(0,u.fH)(` ${k.name} --help`),(0,u.fH)(`
|
|
360
|
+
${m("skillConvert.nextSteps")}:`),(0,u.fH)(` 1. ${m("skillConvert.restartAgent")}`),(0,u.fH)(` 2. ${m("skillConvert.testTool")}`),(0,u.fH)(` 3. ${m("skillConvert.manageTools")}`)}catch(t){(0,u.vV)(m("skillConvert.conversionError",{skillName:e,error:t.message}))}}),t.command("stats").description("Show skill usage statistics").option("--skill <name>","Show stats for specific skill").action(async(e,t)=>{let r=t.parent||{},i=r.opts&&r.opts().cwd||process.cwd(),a=r.opts&&r.opts().lang||"en",o=(0,c.l)(a);try{let t=new s.m(i);if(e.skill){let r=t.stats[e.skill];if(!r)return void(0,u.vV)(o("skillConvert.noStatsForSkill",{skillName:e.skill}));let i=(r.successfulExecutions/r.totalExecutions*100).toFixed(1);(0,u.fH)(o("skillConvert.skillStatsHeader",{skillName:e.skill})),(0,u.fH)("=".repeat(60)),(0,u.fH)(`
|
|
361
|
+
📊 ${o("skillConvert.generalStats")}:`),(0,u.fH)(` ${o("skillConvert.totalExecutions")}: ${r.totalExecutions}`),(0,u.fH)(` ${o("skillConvert.successful")}: ${r.successfulExecutions} (${i}%)`),(0,u.fH)(` ${o("skillConvert.failed")}: ${r.failedExecutions}`),(0,u.fH)(` ${o("skillConvert.avgTime")}: ${r.avgExecutionTime.toFixed(0)}ms`),(0,u.fH)(` ${o("skillConvert.lastUsed")}: ${new Date(r.lastExecuted).toLocaleString()}`),(0,u.fH)(` ${o("skillConvert.conversionScore")}: ${r.conversionScore.toFixed(1)}/100`);let a=t.getExecutionHistory(e.skill,10);if(a.length>0)for(let e of((0,u.fH)(`
|
|
362
|
+
📝 ${o("skillConvert.recentExecutions")}:`),a.slice(-5).reverse())){let t=new Date(e.timestamp).toLocaleTimeString(),r=e.success?"✓":"✗";(0,u.fH)(` ${t} ${r} ${e.executionTime}ms`)}let n=t.getCommonParameters(e.skill,5);if(n.length>0)for(let e of((0,u.fH)(`
|
|
363
|
+
🎯 ${o("skillConvert.commonParameters")}:`),n))(0,u.fH)(` ${e.param} (${e.percentage.toFixed(1)}%)`)}else{let e=t.getSummary();if((0,u.fH)(o("skillConvert.overallStatsHeader")),(0,u.fH)("=".repeat(60)),(0,u.fH)(`
|
|
364
|
+
📈 ${o("skillConvert.overallStats")}:`),(0,u.fH)(` ${o("skillConvert.totalSkillsTracked")}: ${e.totalSkills}`),(0,u.fH)(` ${o("skillConvert.totalExecutions")}: ${e.totalExecutions}`),(0,u.fH)(` ${o("skillConvert.avgSuccessRate")}: ${e.avgSuccessRate.toFixed(1)}%`),e.topSkills.length>0)for(let r of((0,u.fH)(`
|
|
365
|
+
🏆 ${o("skillConvert.topSkills")}:`),e.topSkills)){let e=t.stats[r.skillName],i=e?(e.successfulExecutions/e.totalExecutions*100).toFixed(1):"N/A";(0,u.fH)(` ${r.skillName}: ${r.executions} execs, ${i}% success, score: ${r.score.toFixed(1)}`)}let r=t.getSuggestedConversions();if(r.length>0)for(let e of((0,u.fH)(`
|
|
366
|
+
💡 ${o("skillConvert.conversionSuggestions")}:`),r.slice(0,3)))(0,u.fH)(` ${e.skillName} (score: ${e.score.toFixed(1)})`)}}catch(e){(0,u.vV)(o("skillConvert.statsError",{error:e.message}))}}),t.command("clear [skill-name]").description("Clear skill execution records").option("--all","Clear all records").action(async(e,t,i)=>{let a=i.parent||{},o=a.opts&&a.opts().cwd||process.cwd(),n=a.opts&&a.opts().lang||"en",l=(0,c.l)(n);try{let i=new s.m(o);if(t.all){let e=await r.e("156").then(r.bind(r,6039));await e.confirm({message:l("skillConvert.confirmClearAll"),initial:!1})?(await i.clearAllRecords(),(0,u.fH)(l("skillConvert.allRecordsCleared"))):(0,u.fH)(l("skillConvert.clearCancelled"))}else e?(await i.clearSkillRecords(e),(0,u.fH)(l("skillConvert.skillRecordsCleared",{skillName:e}))):(0,u.vV)(l("skillConvert.specifySkillOrAll"))}catch(e){(0,u.vV)(l("skillConvert.clearError",{error:e.message}))}});let i=t.command("tools").description("Manage converted tools");return i.command("list").description("List all converted tools").action(async()=>{let e=process.cwd(),t=(0,c.l)("en");try{let r=await (0,d.gm)(e),i=await (0,d.Ui)(e);if(0===r.length)return void(0,u.fH)(t("skillConvert.noConvertedTools"));for(let e of((0,u.fH)(t("skillConvert.convertedToolsHeader")),(0,u.fH)("=".repeat(60)),r)){let r=i.find(t=>t.name===e.name),a=r?.enabled?"✓":"✗";(0,u.fH)(`
|
|
367
|
+
${a} ${e.name}`),(0,u.fH)(` ${e.description}`),(0,u.fH)(` ${t("skillConvert.originalSkill")}: ${e.metadata.originalSkill}`),(0,u.fH)(` ${t("skillConvert.converted")}: ${new Date(e.metadata.convertedAt).toLocaleDateString()}`),r&&(r.usageCount>0&&(0,u.fH)(` ${t("skillConvert.usageCount")}: ${r.usageCount}`),r.lastUsed&&(0,u.fH)(` ${t("skillConvert.lastUsed")}: ${new Date(r.lastUsed).toLocaleDateString()}`))}}catch(e){(0,u.vV)(t("skillConvert.toolsError",{error:e.message}))}}),i.command("remove <tool-name>").description("Remove a converted tool").action(async e=>{let t=process.cwd(),i=(0,c.l)("en");try{let a=await r.e("156").then(r.bind(r,6039));await a.confirm({message:i("skillConvert.confirmRemoveTool",{toolName:e}),initial:!1})?await (0,d.WO)(t,e)?(0,u.fH)(i("skillConvert.toolRemoved",{toolName:e})):(0,u.vV)(i("skillConvert.toolRemoveFailed",{toolName:e})):(0,u.fH)(i("skillConvert.removeCancelled"))}catch(e){(0,u.vV)(i("skillConvert.toolsError",{error:e.message}))}}),i.command("enable <tool-name>").description("Enable a disabled tool").action(async e=>{let t=process.cwd(),r=(0,c.l)("en");try{await (0,d.Pc)(t,e,!0)?(0,u.fH)(r("skillConvert.toolEnabled",{toolName:e})):(0,u.vV)(r("skillConvert.toolEnableFailed",{toolName:e}))}catch(e){(0,u.vV)(r("skillConvert.toolsError",{error:e.message}))}}),i.command("disable <tool-name>").description("Disable a tool (without removing it)").action(async e=>{let t=process.cwd(),r=(0,c.l)("en");try{await (0,d.Pc)(t,e,!1)?(0,u.fH)(r("skillConvert.toolDisabled",{toolName:e})):(0,u.vV)(r("skillConvert.toolDisableFailed",{toolName:e}))}catch(e){(0,u.vV)(r("skillConvert.toolsError",{error:e.message}))}}),t}[a,c,u]=p.then?(await p)():p,i()}catch(e){i(e)}})},3689(e,t,r){r.d(t,{D:()=>i});function i(e){let t=e.trim();if(!t.startsWith("/"))return null;if(/^\/list-skill\b/i.test(t))return t.replace(/^\/list-skill\s*/i,"").trim()?{type:"invalid",command:"list",reason:"extraArgs"}:{type:"list"};if(/^\/install-skill\b/i.test(t)){let e=t.replace(/^\/install-skill\s*/i,"").trim().split(/\s+/).filter(Boolean),r=!1,i=[];for(let t of e)"--force"===t?r=!0:i.push(t);return i.length>1?{type:"invalid",command:"install",reason:"tooManyArgs"}:{type:"install",force:r,skillName:i[0]}}if(/^\/remove-skill\b/i.test(t)){let e=t.replace(/^\/remove-skill\s*/i,"").trim();return e?{type:"remove",skillName:e}:{type:"invalid",command:"remove",reason:"missingName"}}return null}},7175(e,t,r){r.d(t,{At:()=>u,HM:()=>p,NB:()=>c,aE:()=>l});var i=r(6760),a=r(1455),o=r(3024),n=r(1421);let s=(0,r(7975).promisify)(n.exec);function l(){return{log:e=>{console.log(e)},warn:e=>{console.warn(e)},writeStdout:e=>{process.stdout.write(e)}}}async function d(e,t,r){try{var i;let a=`clawhub install ${e} --dir "${t}"`;return r&&(a=`${a} --force`),await (i=a,new Promise((e,t)=>{let r=(0,n.spawn)(i,{shell:!0,stdio:"inherit"});r.on("error",t),r.on("close",(r,i)=>{0===r?e():t(Error(`Command exited with code ${r??"null"}${i?` (signal ${i})`:""}`))})})),!0}catch(t){throw Error(`Failed to download skill "${e}": ${t.message}`)}}async function c(e){let{skillName:t,force:r=!1,globalOpts:o,t:n,io:l}=e,c=(0,i.resolve)(o.cwd||process.cwd()),u=(0,i.join)(c,".pithosai","skills");await (0,a.mkdir)(u,{recursive:!0}),l.log(n("skills.installing",{dir:u}));try{try{await s("which clawhub")}catch{throw Error("ClawHub CLI is not installed or not in PATH. Please install it first: npm install -g clawhub")}let e=[];if(t)e=[t];else{l.log(n("skills.fetchingList"));let t=await s("clawhub list | awk '{print $1}'"),r=function(e){if(null!=e&&"object"==typeof e&&"stdout"in e){let t=e.stdout;return null==t?"":String(t)}return Array.isArray(e)&&null!=e[0]?String(e[0]):""}(t);r&&(l.writeStdout(r),r.endsWith("\n")||l.writeStdout("\n"));let i=r.split("\n").map(e=>e.trim()).filter(Boolean);if(!i.length)return void l.warn(n("skills.noSkillsAvailable"));e=i}let i=0;for(let t of e)try{await d(t,u,r)&&(i++,l.log(n("skills.installed",{name:t})))}catch(e){l.warn(n("skills.downloadFailed",{name:t,error:e.message}))}l.log(n("skills.complete",{count:String(i),total:String(e.length)}))}catch(e){throw Error(`Failed to install skills: ${e.message}`)}}async function u(e){let{globalOpts:t,t:r,io:n}=e,s=(0,i.resolve)(t.cwd||process.cwd()),l=(0,i.join)(s,".pithosai","skills");if(!(0,o.existsSync)(l))return void n.log(r("skills.noSkillsDir"));try{let e=(await (0,a.readdir)(l)).filter(e=>"."!==e&&".."!==e);for(let t of(n.log(r("skills.installedList",{count:String(e.length),dir:l})),e)){let e=(0,i.basename)(t,".md"),r=(0,i.join)(l,t,"_meta.json");if((0,o.existsSync)(r))try{let e=await (0,a.readFile)(r,"utf-8"),t=JSON.parse(e);n.log(` • ${t.slug}: ${t.ownerId||"No description"}`),n.log(` Installed: ${t.publishedAt||"Unknown"}`)}catch{n.log(` • ${e}: (no metadata)`)}else n.log(` • ${e}: (no metadata)`)}}catch(e){throw Error(`Failed to list skills: ${e.message}`)}}async function p(e){let{skillName:t,globalOpts:r,t:n,io:s}=e,l=(0,i.resolve)(r.cwd||process.cwd()),d=(0,i.join)(l,".pithosai","skills");if(!(0,o.existsSync)(d))return void s.log(n("skills.noSkillsDir"));let c=(0,i.join)(d,t,"SKILL.md"),u=(0,i.join)(d,t,"_meta.json");if(!(0,o.existsSync)(c))return void s.warn(n("skills.notInstalled",{name:t}));try{await (0,a.unlink)(c),(0,o.existsSync)(u)&&await (0,a.unlink)(u);let e=(0,i.join)(d,t);await (0,a.rm)(e,{recursive:!0,force:!0}),s.log(n("skills.removed",{name:t}))}catch(e){throw Error(`Failed to remove skill "${t}": ${e.message}`)}}},3780(e,t,r){r.a(e,async function(e,i){try{r.d(t,{B:()=>l});var a=r(5347),o=r(8362),n=r(7175),s=e([a,o]);function l(e){let t=e.command("skills").description("Manage skills from Clawhub AI").option("-l, --lang <lang>","Language for prompts (default: en)").option("-C, --cwd <dir>","Project directory (default: current directory)");t.command("install").description("Install skills from Clawhub AI using ClawHub CLI").argument("[skill-name]","Specific skill name to install (default: all)").option("-f, --force","Force reinstall even if skill exists").action(async(t,r)=>{try{let i=e.opts(),a=(0,o.l)(i.lang||"en");await (0,n.NB)({skillName:t,force:!0===r.force,globalOpts:i,t:a,io:(0,n.aE)()})}catch(e){console.error(`Failed to install skills: ${e.message}`),process.exit(1)}}),t.command("list").description("List installed skills").action(async()=>{try{let t=e.opts(),r=(0,o.l)(t.lang||"en");await (0,n.At)({globalOpts:t,t:r,io:(0,n.aE)()})}catch(e){console.error(`Failed to list skills: ${e.message}`),process.exit(1)}}),t.command("remove").description("Remove installed skill").argument("<skill-name>","Skill name to remove").action(async t=>{try{let r=e.opts(),i=(0,o.l)(r.lang||"en");await (0,n.HM)({skillName:t,globalOpts:r,t:i,io:(0,n.aE)()})}catch(e){console.error(`Failed to remove skill: ${e.message}`),process.exit(1)}})}[a,o]=s.then?(await s)():s,i()}catch(e){i(e)}})},8948(e,t,r){r.a(e,async function(e,i){try{r.d(t,{TS:()=>n});var a=r(8691),o=e([a]);function n(e,t={}){let r=function(e={}){var t;let r,i,o,n,s,l=(t=e.columns,i=(r="\n\n\n\n ____ ___ _____ _ _ ___ ____ _ ___ \n| _ \\_ _|_ _| | | |/ _ \\/ ___| / \\ |_ _|\n| |_) | | | | | |_| | | | \\___ \\ / _ \\ | | \n| __/| | | | | _ | |_| |___) / ___ \\ | | \n|_| |___| |_| |_| |_|\\___/|____/_/ \\_\\___|\n\n".split("\n")).reduce((e,t)=>Math.max(e,t.length),0),o=Number.isFinite(t)&&t>0?t:process.stdout.columns??80,n=Math.max(0,Math.floor((o-i)/2)),s=" ".repeat(n),r.map(e=>s+e).join("\n"));return`${a.m.cyan(l)}
|
|
368
|
+
`}(t);e&&"function"==typeof e.writeLn?e.writeLn(r.trimEnd()):e&&"function"==typeof e.write?e.write(r):process.stdout.write(r)}a=(o.then?(await o)():o)[0],i()}catch(e){i(e)}})},831(e,t,r){r.a(e,async function(e,i){try{r.d(t,{y:()=>f});var a=r(6760),o=r(9662),n=r(3242),s=r(5534),l=r(1773),d=r(4071),c=r(1048),u=r(4267),p=r(829),m=e([l,n,p,c,s,o,d]);async function h(e,t,{runOpts:r,t:i,controller:a,request:o}){let c=new s.j(e),u=(await c.parseTasks()).find(e=>e.id===t);u||((0,d.vV)(i("cli.taskNotFound",{taskId:t})),process.exit(1));let p=r??{cwd:process.cwd()},m=a?{...p,controller:a}:p,h="string"==typeof o&&""!==o.trim()?{...u,title:o,description:""}:u,g=new l.c;g.registerHandler("default",async e=>{let t=await (0,n.Ty)(e,m);return{success:t.success,message:t.success?i("cli.taskAgentCompleted"):t.error??i("cli.taskAgentRunFailed"),timestamp:new Date().toISOString(),output:t.result??t.error??""}});try{let e=await g.process(h);(0,d.KH)("result",JSON.stringify(e));let r=e?.timestamp??new Date().toISOString(),a=e?.output!=null?String(e.output):e?.message!=null?String(e.message):i("cli.taskDone");await c.markTaskAsCompleted(t,{result:a,completedAt:r})}catch(e){await c.markTaskAsFailed(t,e),(0,d.vV)(i("cli.taskFailed",{message:String(e?.message??e)})),process.exit(1)}}async function g(e,t,r,i){var a;let o,n=await e.parseTasks(),s=n.filter(e=>"processing"===e.status),l=null;if(s.length>0)l=s[0],(0,d.fH)(i("cli.taskStartingProcessorProcessing",{id:l.id,title:l.title}));else{let t=n.filter(e=>"pending"===e.status);if(0===t.length)return void(0,d.fH)(i("cli.taskNoPending"));l=t[0],await e.markTaskAsProcessing(l.id),(0,d.fH)(i("cli.taskPickedTask",{id:l.id,title:l.title}))}a=l,o=a.description?a.description.slice(0,80)+(a.description.length>80?"…":""):"",console.log(i("cli.taskProcessingHeader")),console.log(`${i("cli.taskLabelId")} ${a.id}`),console.log(`${i("cli.taskLabelTitle")} ${a.title}`),console.log(`${i("cli.taskLabelStatus")} ${a.status}`),o&&console.log(`${i("cli.taskLabelDescription")} ${o}`),console.log(i("cli.taskProcessingSeparator"));let c={...r,model:l.model||r.model},m=new u.w;try{await (0,p.w)(l,{controller:m,t:i,execute:async(e,r)=>{await h(t,l.id,{runOpts:c,t:i,controller:m,request:r})}})}catch(e){(0,d.vV)(i("cli.taskProcessorFailed",{message:e.message}))}}function f(e,t){let r=e.command("task").description(t("cli.taskDescription")).option("-f, --file <path>",t("cli.taskFileOption"),"").option("-C, --cwd <dir>",t("cli.cwdOption")).option("-r, --role <role>",t("cli.roleOption")).option("-l, --lang <lang>",t("cli.langOption")).option("--skills-dir <dir>",t("cli.skillsDirOption")).option("--model <key>",t("cli.taskModelOption")).option("--timeout <seconds>",t("cli.timeoutOption")).option("--no-markdown","Plain text output only (default: markdown enabled)").option("--new-session",t("cli.taskNewSessionOption")).addHelpText("after",t("cli.taskExamples"));return r.action(async function(){let r=e.opts(),i=this.optsWithGlobals?this.optsWithGlobals():this.opts(),n=function(e,t={}){return{cwd:a.resolve(e.cwd||process.cwd()),skillsDir:e.skillsDir,lang:t.lang??e.lang,role:t.role??e.role,timeout:null!=e.timeout?Number(e.timeout):void 0,newSession:!0===e.newSession,model:e.model||void 0,markdown:!1!==e.markdown}}(i,r),l=n.cwd||process.cwd(),u=void 0!==i.file&&""!==i.file?i.file:"prompts.md",p=a.resolve(l,u);await (0,c.e)(l,r.logPath);let m=new s.j(p),h=new o.v(p),f=!1,k=!1,w=async()=>{if(f){k=!0;return}f=!0;try{do k=!1,await g(m,p,n,t);while(k)}finally{f=!1}};await h.initialize(),await w(),await h.watch(async()=>{await w()}),(0,d.fH)(t("cli.taskWatcherRunning"))}),r}[l,n,p,c,s,o,d]=m.then?(await m)():m,i()}catch(e){i(e)}})},4117(e,t,r){r.a(e,async function(e,i){try{r.d(t,{O:()=>c});var a=r(8362),o=r(9616),n=r(4071),s=r(9782),l=e([a,o,n]);[a,o,n]=l.then?(await l)():l;let u=`You are a writing assistant. Fulfill the user's request by writing the requested text.
|
|
500
369
|
Output only the final text: no meta-commentary, no "Here is...", no markdown code fences unless the user asked for code or markdown.
|
|
501
|
-
If the user asks for a specific format (email, list, paragraph), match that format.`;async function d(e,t,
|
|
502
|
-
${t||""}`.match(/(?:project|项目)[::]\s*([^\s\n]+)/i);return
|
|
370
|
+
If the user asks for a specific format (email, list, paragraph), match that format.`;async function d(e,t,r){let i=`${e.baseUrl.replace(/\/$/,"")}/chat/completions`,a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t?`Bearer ${t}`:""},body:JSON.stringify({model:e.id,messages:r,stream:!1,max_tokens:e.maxTokens??2048})});if(!a.ok){let e=await a.text();throw Error(`Ollama API error ${a.status}: ${e}`)}let o=await a.json(),n=o?.choices?.[0]?.message?.content;if(null==n)throw Error("Ollama API returned no content");return"string"==typeof n?n:String(n)}function c(e,t){let r=t||(0,a.l)("en"),i=e.command("writer").description(r("writer.description")).argument("<request...>",r("writer.argument")).addHelpText("after",r("writer.examples"));return i.action(async function(t){let r=Array.isArray(t)?t.join(" ").trim():String(t).trim(),i=(this.optsWithGlobals?this.optsWithGlobals():{...e.opts(),...this.opts()}).lang||"en",l=(0,a.l)(i),c=process.env.CURSOR_MODEL;delete process.env.CURSOR_MODEL;let p=(0,o.aN)({local:!0,modelId:"qwen2.5:14b"});void 0!==c?process.env.CURSOR_MODEL=c:delete process.env.CURSOR_MODEL,p||((0,n.vV)(l("errors.ollamaNotConfigured")),process.exit(1));let{model:m,getApiKey:h}=p,g=await h();try{let e=(await (0,s.$A)(d(m,g,[{role:"system",content:u},{role:"user",content:r}]),l("writer.loading"))).trim();e&&(process.stdout.write(e),e.endsWith("\n")||process.stdout.write("\n"))}catch(e){(0,n.vV)(e?.message??String(e)),process.exit(1)}}),i}i()}catch(e){i(e)}})},5012(e,t,r){r.d(t,{Av:()=>h,Fu:()=>f,GV:()=>u,Kc:()=>c,Lq:()=>l,OA:()=>g,TZ:()=>w,aL:()=>d,dc:()=>o,fP:()=>p,k:()=>k,nQ:()=>m,qu:()=>n,tb:()=>s});var i=r(6760),a=r(8161);let o={USAGE:1,CONFIG:2,RUNTIME:3},n=(0,i.join)((0,a.homedir)(),".pithosai"),s="pithosai.db",l=["en","zh","ja","ko","fr","de","es","pt","zh-Hant","it","ar","nl"],d={en:"English",zh:"Simplified Chinese",ja:"Japanese",ko:"Korean",fr:"French",de:"German",es:"Spanish",pt:"Portuguese","zh-Hant":"Traditional Chinese",it:"Italian",ar:"Arabic",nl:"Dutch"},c="en",u=["IDENTITY","ABILITIES","AGENTS"];function p(e="en"){let t="zh"===e?"-zh.md":".md";return u.map(e=>`${e}${t}`)}function m(e="en"){return p(e)}let h=["js","ts","python"],g=["node_modules","dist","venv","env","env.local","env.development.local","env.test.local","env.production.local"],f=3,k={min:1e3,max:3e3},w=18e5},614(e,t,r){r.a(e,async function(e,i){try{r.d(t,{P2:()=>k,hf:()=>b,lx:()=>T});var a=r(6760),o=r(8161),n=r(3024),s=r(7522),l=r(1305),d=r(4768),c=r(8476),u=r(935),p=r(8359),m=r(4071),h=r(5012),g=e([c,s,d,l,u,p,m]);[c,s,d,l,u,p,m]=g.then?(await g)():g;let S=[/^(re:\s*)*task:/i,/^([Rr][eE]:\s*)*任务:/,/^([Rr][eE]:\s*)*任务:/,/^([Rr][eE]:\s*)*任务:/,/^([Rr][eE]:\s*)*任务:/,/^(回复:\s*)*task:/i,/^(回复:\s*)*task:/i,/^(回复:\s*)*任务:/,/^(回复:\s*)*任务:/,/^(回复:\s*)*任务:/,/^(回复:\s*)*任务:/],T="PM",E=/[((](RD|PM|CO|QA)[))]/i,x=/<([^>]+)>/;function f(e){let t=(e||"").trim();for(let e of S)if(e.test(t))return!0;return!1}function k(e){let t=function(e){let t=(e||"").trim();for(let e of S)if(e.test(t)){t=t.replace(e,"").trim();break}return t}(e?.subject??""),r=(e?.body??"").trim();return t?r?t+"\n\n"+r:t:r}function w(e){let t=(e||"").trim(),r=t.match(x);return r?r[1].trim():t}async function v({projectName:e,targetPath:t},r={}){let i=r.role||T,a=r.lang||"en";try{return await (0,c.Ts)(t,{role:i,lang:a,type:"js",noExit:!0}),{projectName:e,projectPath:t}}catch(e){throw(0,m.JE)("heartbeat init project failed:",e?.message||e,"path:",t),e}}async function y(e,t={}){let{from:r}=t,i=w(r);if(!e||!String(e).trim()){let e=(0,o.homedir)(),r=(0,a.join)(e,"Projects",i||"","default");return(0,n.existsSync)(r)?{projectName:"default",projectPath:r}:v({projectName:"default",targetPath:r},t)}let l=String(e).trim(),d=(0,o.homedir)(),c=null,u=new Set(h.OA);try{let e=(0,s.default)(d,{type:"directories",depth:5,directoryFilter:e=>!u.has(e.basename)});for await(let t of e)if(!u.has(t.basename)&&t.basename===l){c=t.fullPath,e.destroy();break}}catch{}if(c)return{projectName:l,projectPath:c};let p=i?(0,a.join)(d,"Projects",i,l):(0,a.join)(d,"Projects",l);return v({projectName:l,targetPath:p},t)}async function b(e,t,r={}){let i=await (0,d.s)(e),{limit:a,email:o}=r,{emails:n,error:s}=await (0,l.Md)(i,t,{limit:a??20,maxTextLength:5e4,projectCwd:e});if(s)return(0,m.JE)("heartbeat fetch inbox, inboxRole:",t,"email:",o,"error:",s),[];let c=[],h=r.states??null,g=await (0,p.Lf)(r.stateDir);for(let e of n){let i=(0,u.bq)(e),a=w(e.from);if(!await (0,p.J7)(g,{email:o,role:t,customerEmail:a})){(0,m.JE)("heartbeat skip the email:",i,"email:",o,"role:",t,"customerEmail:",a,"invalid customer");continue}if(!f(e.subject)){(0,m.JE)("heartbeat skip non-task subject:",e.subject);continue}if(await (0,p._D)(g,i)){(0,m.JE)("heartbeat skip task:",i,"already processed");continue}let n=function(e){let t=(e||"").trim().match(E);return t?t[1].toUpperCase():null}(e.subject);if(null!=n&&n!==t){(0,m.JE)("heartbeat skip task:",i,"role mismatch:",n,"expected:",t);continue}let s=(e.text||"").trim()||"(no body)",l=null!=h?{role:t,email:o,states:h}:{role:t,email:o},d=function(e,t,r={}){let{role:i,email:a}=r,o=r.states;if(f(e)&&i&&a&&o&&Array.isArray(o)&&o.length>0){for(let e of o)if(e.role==i&&e.email==a)return e.projectName}let n=`${e||""}
|
|
371
|
+
${t||""}`.match(/(?:project|项目)[::]\s*([^\s\n]+)/i);return n&&n[1]&&n[1].trim()||null}(e.subject||"",s,l),{projectName:k,projectPath:v}=await y(d,{role:t,lang:r.lang??"en",from:e.from});(0,m.fH)("heartbeat resolve project info from home subject:",e.subject,"extracted:",d,"role:",t,"email:",o,"projectName:",k,"projectPath:",v),c.push({id:i,subject:e.subject,body:s,date:e.date||"",email:o,from:e.from||"",role:t,projectName:k,projectPath:v,...Array.isArray(e.attachments)&&e.attachments.length>0?{attachments:e.attachments}:{}})}return c}i()}catch(e){i(e)}})},2003(e,t,r){r.a(e,async function(e,i){try{r.d(t,{rr:()=>u});var a=r(1455),o=r(6760),n=r(35),s=r(8703),l=r(4399),d=e([s,n]);[s,n]=d.then?(await d)():d;let p=new Map;async function c(e){let t="zh"===e?"zh":"en";if(p.has(t))return p.get(t);let r="zh"===t?"email-reply-template-zh.html":"email-reply-template.html",i=(0,o.join)(l.gb,r),s=await (0,a.readFile)(i,"utf-8"),d=n.default.compile(s);return p.set(t,d),d}async function u(e,t){var r;let i=await c(t),a=(r=e.responseMarkdown)&&"string"==typeof r?s.marked.parse(r):"",o=i({subject:e.subject,projectName:e.projectName,projectPath:e.projectPath,request:e.request??"",response:a,date:e.date}),n=`Project: ${e.projectName}
|
|
503
372
|
Project path: ${e.projectPath}
|
|
504
373
|
Your request:
|
|
505
374
|
${e.request??""}
|
|
506
375
|
|
|
507
376
|
Response:
|
|
508
|
-
${e.responseMarkdown}`;return{subject:e.subject,html:o,text:a.trim()}}r()}catch(e){r(e)}})},4822(e,t,i){i.a(e,async function(e,r){try{i.d(t,{IG:()=>w,lx:()=>l.lx});var s=i(6760),o=i(8161),a=i(3024),n=i(935),l=i(614),d=i(3242),c=i(1305),u=i(2003),p=i(4768),h=i(5012),m=i(4071),g=i(8362),f=e([p,g,l,d,u,c,n,m]);async function w(e,t={}){var i;let r=(0,s.resolve)(e),f=await (0,p.s)(r),k=t.role??f?.supportedRoles?.[0]??l.lx,y=f?.roles?.[k]?.email,v=t.lang??f?.lang??(0,g.a)(),b=(0,g.l)(v);if(!y)return void(0,m.vV)(b("heartbeat.emailRequired",{role:k}));let S=await (0,n.cp)(h.qu,{email:y,role:k});(0,m.fH)(b("heartbeat.loadedState",{email:y,role:k,states:JSON.stringify(S)}));let T=await (0,l.hf)(r,k,{limit:20,lang:v,email:y,states:S,stateDir:h.qu});(0,m.fH)(b("heartbeat.fetchFound",{count:T.length,ids:T.map(e=>e.id).join(", ")}));let C=function(e,t,i){let r=0;for(let s of i){let i=e.find(e=>e.role===s.role&&e.email===s.email&&e.projectName===s.projectName);i||(i={email:s.email,role:s.role,projectName:s.projectName,projectPath:s.projectPath,processed:[],unprocessed:[]},e.push(i));let o=new Set(i.processed||[]),a=new Set(i.unprocessed.map(e=>e.id));o.has(s.id)||a.has(s.id)||(r++,i.unprocessed.push({id:s.id,subject:s.subject,body:s.body,date:s.date,from:s.from,role:t,projectName:s.projectName,projectPath:s.projectPath,...Array.isArray(s.attachments)&&s.attachments.length>0?{attachments:s.attachments}:{}}),a.add(s.id))}return r}(S,k,T);C>0&&(await (0,n.br)(S,h.qu,{email:y,role:k}),(0,m.fH)(b("heartbeat.savedState",{email:y,role:k})));let E=!1,x=(i={email:y,role:k},S.find(e=>e.email===i.email&&e.role===i.role&&e.unprocessed.length>0));{let e=x?`${x.projectName||x.email} (${x.unprocessed?.length??0} unprocessed)`:"none";(0,m.fH)(b("heartbeat.mergedAndNext",{merged:C,stateSummary:e}))}let I=x?.unprocessed?.shift();if(I){let e=function(e,t){if(t.projectPath&&String(t.projectPath).trim()&&(0,a.existsSync)(t.projectPath))return t.projectPath;let i=t.projectName;if(!i||!String(i).trim())return e;let r=(0,s.join)((0,o.homedir)(),String(i).trim());return(0,a.existsSync)(r)?r:e}(r,I);(0,m.fH)(b("heartbeat.runningTask",{subject:I.subject}));let i=(0,l.P2)(I),n=await (0,d.Ty)({id:I.id,status:"pending",title:i,description:"",model:void 0,createdAt:new Date().toISOString(),section:null},{cwd:e,role:k,lang:v,reasoner:t.reasoner,chat:t.chat,timeout:t.timeout,markdown:t.markdown});if(n.success){x.processed.push(I.id),E=!0;let e=n.result?.trim()||"(Task completed with no text output.)",t="Re: "+(I.subject||"task"),r=await (0,u.rr)({subject:t,projectName:I.projectName,projectPath:I.projectPath,request:i,responseMarkdown:e,date:new Date().toISOString()},v),s=await (0,c.ZM)(f,k,{to:I.from,subject:r.subject,html:r.html});!s.success&&s.error&&(0,m.vV)(b("heartbeat.replyEmailFailed",{error:s.error}))}else{(0,m.vV)(b("heartbeat.taskFailed",{error:n.error||"unknown"})),x.unprocessed.unshift(I);let e="Task failed: "+(n.error||"unknown error"),t="Re: "+(I.subject||"task")+" [FAILED]",r=await (0,u.rr)({subject:t,projectName:I.projectName,projectPath:I.projectPath,request:i,responseMarkdown:e,date:new Date().toISOString()},v),s=await (0,c.ZM)(f,k,{to:process.env.SUPPORT_EMAIL||"support@pithosai.com",subject:r.subject,html:r.html});!s.success&&s.error&&(0,m.vV)(b("heartbeat.failureReplyEmailFailed",{error:s.error}))}}(C>0||E)&&(await (0,n.br)(S,h.qu,{email:y,role:k}),(0,m.fH)(b("heartbeat.savedState",{email:y,role:k})));let A=S.reduce((e,t)=>e+t.processed.length,0),O=S.reduce((e,t)=>e+t.unprocessed.length,0);return{processedCount:A,ranOne:E,unprocessedCount:O}}[p,g,l,d,u,c,n,m]=f.then?(await f)():f,r()}catch(e){r(e)}})},6478(e,t,i){i.a(e,async function(e,r){try{i.d(t,{D:()=>h,I:()=>o.IG});var s=i(6760),o=i(4822),a=i(4768),n=i(4071),l=i(8362),d=i(1305),c=i(8359),u=i(5012),p=e([a,c,l,d,o,n]);async function h(e,t={}){let i=(0,s.resolve)(e),r=await (0,a.s)(i),p=t.role??r?.supportedRoles?.[0]??o.lx,m=await (0,c.Lf)(u.qu),g=(0,c.bY)(m);if(!g.find(e=>e.role===p)?.email){let e=t.lang??r?.lang??(0,l.a)(),i=(0,l.l)(e);throw Error(i("heartbeat.emailRequired",{role:p}))}let f={role:t.role,lang:t.lang,reasoner:t.reasoner,chat:t.chat,timeout:t.timeout,markdown:t.markdown},w=t.lang??r?.lang??(0,l.a)(),k=(0,l.l)(w);(0,n.fH)(k("heartbeat.startedIdle",{role:p}));let y=await (0,d.Df)(r,p,async()=>{await (0,o.IG)(i,f)},{lang:w}),v=()=>{y.close(),(0,n.fH)(k("heartbeat.imapClosedShutdown")),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v),await new Promise(()=>{})}[a,c,l,d,o,n]=p.then?(await p)():p,r()}catch(e){r(e)}})},935(e,t,i){i.a(e,async function(e,r){try{i.d(t,{bq:()=>h,br:()=>u,cp:()=>d}),i(6760);var s=i(7598);i(3024);var o=i(5012),a=i(8359),n=i(4071),l=e([n,a]);async function d(e=o.qu,t={}){return t.email&&t.role?c(e,t.email,t.role):null}async function c(e,t,i){let r=await (0,a.Lf)(e),s=(0,a.O3)(r,{email:t,role:i}),o=[];for(let e of s){if(!e.projectName||!e.projectPath){(0,n.JE)("loadHeartbeatStateFromStorage skip process:",e.id,"projectName:",e.projectName,"projectPath:",e.projectPath);continue}let s=(0,a.SW)(r,e.id),l=[],d=[];for(let t of s){let i=(0,a.x_)(r,t.emailId);if(!i)continue;let s=(0,a.tJ)(r,i.id),o=s.length>0?s.map(e=>({filename:e.filename,contentType:e.contentType,size:e.size,...null!=e.content?{content:e.content}:{},...null!=e.filePath?{filePath:e.filePath}:{}})):void 0,n={id:i.id,subject:i.subject,body:i.body,date:i.date,from:i.from,projectName:e.projectName,projectPath:e.projectPath,...o?{attachments:o}:{}};t.status===a.au.PROCESSED?l.push(i.id):d.push(n)}o.push({email:t,role:i,projectName:e.projectName,projectPath:e.projectPath,processed:l,unprocessed:d})}return o}async function u(e,t=o.qu,i={}){if(i.email&&i.role)return void await p({states:e,stateDir:t,email:i.email,role:i.role})}async function p(e){let{states:t,stateDir:i,email:r,role:s}=e,o=await (0,a.Lf)(i);for(let e of t){let{projectName:t,projectPath:i}=e,n=(0,a.Vr)(o,{email:r,role:s,projectName:t,projectPath:i}),l=r||"",d=new Set([...e.processed,...e.unprocessed.map(e=>e.id)]);for(let t of((0,a.Jo)(o,n.id,d),e.processed))(0,a.x_)(o,t)||(0,a.YC)(o,{id:t,subject:"",body:"",date:"",from:"",to:l}),(0,a.Fh)(o,{processId:n.id,emailId:t,processCount:1,status:a.au.PROCESSED});for(let t of e.unprocessed)if((0,a.YC)(o,{id:t.id,subject:t.subject||"",body:t.body||"",date:t.date||"",from:t.from||"",to:l}),(0,a.Fh)(o,{processId:n.id,emailId:t.id,processCount:0,status:a.au.UNPROCESSED}),Array.isArray(t.attachments)&&t.attachments.length>0)for(let e of((0,a.yh)(o,t.id),t.attachments))e&&"string"==typeof e.filename&&"string"==typeof e.contentType&&"number"==typeof e.size&&(0,a.PT)(o,{emailId:t.id,filename:e.filename,contentType:e.contentType,size:e.size,content:e.content??null,filePath:e.filePath??null})}}function h(e){let t=(e.from||"").trim(),i=(e.date||"").trim(),r=(e.subject||"").trim(),o=`${t}|${i}|${r}`;return(0,s.createHash)("md5").update(o,"utf8").digest("hex")}[n,a]=l.then?(await l)():l,r()}catch(e){r(e)}})},8362(e,t,i){i.a(e,async function(e,r){try{i.d(t,{a:()=>y,l:()=>v});var s=i(2022),o=i(5012),a=i(5951),n=i(9995),l=i(247),d=i(9556),c=i(1984),u=i(7493),p=i(7893),h=i(5490),m=i(6150),g=i(8112),f=i(3998),w=i(5946),k=e([s]);s=(k.then?(await k)():k)[0];let b={ar:{translation:a.A},de:{translation:n.A},en:{translation:l.A},es:{translation:d.A},fr:{translation:c.A},it:{translation:u.A},ja:{translation:p.A},ko:{translation:h.A},nl:{translation:m.A},pt:{translation:g.A},zh:{translation:f.A},"zh-hant":{translation:w.A}};function y(){let e=(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").split(/[_.]/)[0].toLowerCase()||"";return e&&Object.hasOwn(b,e)?e:o.Kc}let S=!1;function v(e="en"){S||(s.default.init({lng:o.Kc,fallbackLng:o.Kc,resources:b,interpolation:{escapeValue:!1},showSupportNotice:!1}),S=!0);let t="string"==typeof e?e.trim():"";if(t){let e=t.toLowerCase();t="zh-tw"===e||"zh-hk"===e?"zh-hant":e}let i=t&&Object.hasOwn(b,t)?t:o.Kc;return(e,t={})=>s.default.t(e,{lng:i,...t})}r()}catch(e){r(e)}})},5951(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"المتطلب الأساسي",projectDir:"دليل المشروع (اعمل هنا): {{cwd}}",skillsInstruction:"استخدم أداة read_skill لتحميل تعليمات المهارة الكاملة عندما تتطابق المهمة مع وصفها.",toolArgSizeLimit:"لا تتجاوز أبداً {{maxChars}} حرفاً في معامل استدعاء أداة واحد (مثلاً content في write). الواجهة قد تقصّ النص الأطول وتسبب أخطاء \xabUnterminated string in JSON\xbb. للملفات أو السكربتات الطويلة، قسّم إلى استدعاءات write متعددة (حسب الملف أو حسب قطع أقل من {{maxChars}} حرفاً).",toolCallJsonFormat:'معطيات استدعاء الأداة يجب أن تكون JSON صالحاً: كل مفتاح وكل قيمة نصية بين علامتي تنصيص مزدوجة. مثال لـ write: {"path": "filename.md", "content": "المحتوى هنا"}. لا تحذف التنصيص حول المفاتيح أو القيم (مثلاً path: file.md غير صالح).'},errors:{missingPromptFiles:"ملفات التلميحات المطلوبة مفقودة في {{dir}}:",runInit:"شغّل 'pithosai init' في جذر المشروع لإنشاء .pithosai مع القوالب.",noApiKey:"لم يتم العثور على مفتاح API. اضبط DEEPSEEK_API_KEY أو OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama غير مهيأ. اضبط OPENAI_LOCAL_API_BASE أو استخدم مشروعاً بنموذج محلي.",noValidTemplateFiles:"لا توجد ملفات قوالب صالحة في {{dir}}. المتوقع *-<lang>.md (مثلاً IDENTITY-ja.md). شغّل 'pithosai init' لإنشاء .pithosai مع القوالب.",runTimeout:"انتهت مهلة تشغيل الوكيل بعد {{seconds}} ثانية. استخدم --timeout <seconds> أو PITHOSAI_TIMEOUT_MS للتعديل.",agentRunFailed:"فشل التشغيل: {{message}}",unknownRunError:"خطأ غير معروف"},warnings:{sessionAppend:"إلحاق الجلسة: {{message}}",apiRetry:"خطأ API في المحاولة {{attempt}}/{{max}}؛ إعادة المحاولة..."},reasoner:{thinkingHeader:"\n--- تفكير:\n",replyHeader:"\n\n--- رد:\n"},run:{cwd:"cwd {{cwd}}",request:"الطلب: {{request}}",interactivePrompt:"أنت: ",tuiYouLabel:"أنت:",interactiveExitHint:"يرجى الإجابة أو إدخال طلب جديد (اكتب 'exit' أو 'quit' للخروج من CLI).",interactiveModeCwd:"المجلد الحالي: {{cwd}}",interactiveModeAgentTitle:"--- الوضع التفاعلي — وكيل (أدوات كاملة) ---",interactiveModeAgentTips:"- مجموعة أدوات كاملة (قراءة وكتابة وتنفيذ حسب الإعدادات).\n- تُخزَّن الجولات لكل مهمة في قاعدة البيانات المحلية.\n- `/new` يعيّن معرّف مهمة جديدًا ولا يُحمّل الرسائل السابقة.\n- `/shell <أمر>` للتنفيذ في الطرفية؛ `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة.\n- `/list-skill` و`/install-skill` و`/remove-skill` يعادل `pithosai skills list|install|remove` (ClawHub). Ctrl+S للإيقاف، Ctrl+P للإيقاف المؤقت.",interactiveModeDialogTitle:"--- الوضع التفاعلي — حوار (أسئلة وأجوبة للقراءة فقط) ---",interactiveModeDialogTips:"- تُستخدم أدوات القراءة فقط (لا shell ولا تعديل ملفات ولا تنفيذ أوامر).\n- تُخزَّن الجولات لكل مهمة في قاعدة البيانات المحلية.\n- `/new` يعيّن معرّف مهمة جديدًا ولا يُحمّل الرسائل السابقة.\n- `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة.\n- `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub) مثل واجهة `pithosai skills`.",interactiveModePlanTitle:"--- وضع الخطة ---",interactiveModePlanTips:"- تُكتب كل إجابة في `<slug>-plan.md` داخل مجلد المشروع (السطر الأول من الطلب يؤثر على الاسم).\n- أدوات قراءة فقط؛ shell والأدوات المعدِّلة معطّلة.\n- `/new` يعيّن معرّف مهمة جديدًا.\n- `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة.\n- `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub) مثل واجهة `pithosai skills`.\n- بعد كل تشغيل يمكنك متابعة طلب خطة جديد عند المطالبة (مثل agent/dialog).",list:{noPersistedTasks:"لم يتم العثور على مهام محفوظة.",createTasksFirstHint:"أنشئ المهام أولاً باستخدام `pithosai task`.",persistedTasksHeader:"--- المهام المحفوظة ({{count}}) ---",selectTaskHint:"استخدم `/select <index>` لتشغيل مهمة.",noTasksCached:"لا توجد مهام مخزنة مؤقتاً. شغّل `/list` أولاً.",invalidIndex:"فهرس غير صالح: {{index}}. النطاق المسموح: 0-{{maxIndex}}.",selectUsage:"الاستخدام: /select <index>",selectedTask:"تم اختيار المهمة #{{index}}."},skillSlash:{installUsage:"الاستخدام: /install-skill [--force] [اسم-المهارة]",removeUsage:"الاستخدام: /remove-skill <اسم-المهارة>",listNoExtra:"أمر /list-skill لا يقبل وسائط.",failed:"فشل أمر المهارة: {{message}}"},show:{title:"المهمة الحالية",field:"الحقل",value:"القيمة",taskId:"taskId",mode:"الوضع",model:"النموذج",status:"الحالة",messageCount:"عدد_الرسائل",usageInput:"الاستخدام.إدخال",usageOutput:"الاستخدام.إخراج",usageCacheRead:"الاستخدام.قراءة_الكاش",usageCacheWrite:"الاستخدام.كتابة_الكاش",usageTotalTokens:"الاستخدام.إجمالي_الرموز"},showTask:{title:"أسئلة وأجوبة المهمة",taskIdLabel:"معرّف المهمة",turnHeading:"الجولة {{index}}",questionLabel:"السؤال",answerLabel:"الإجابة",createdLabel:"تاريخ الإنشاء",emptyQuestion:"(سؤال فارغ)",emptyAnswer:"(لا رد نصي من المساعد)",emptyNoMessages:"لا رسائل مستخدم لهذه المهمة بعد.",previewDocumentTitle:"أسئلة وأجوبة المهمة"},showPrompt:{previewDocumentTitle:"مطالبة النظام",previewHeading:"مطالبة النظام"},shellHint:"استخدم '/shell <command>' لتنفيذ أوامر shell (مثال: '/shell ls -la').",replIntroDialog:"وضع الحوار: أدوات قراءة فقط — `/shell` معطّل. استخدم `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة. `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub).",replIntroPlan:"وضع الخطة: تُحفظ كل إجابة في `<slug>-plan.md` (السطر الأول يؤثر على الاسم). `/shell` معطّل؛ الإخراج قليل حتى الاكتمال. استخدم `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة. `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub).",newSessionHint:"استخدم '/new <طلب>' لبدء جلسة جديدة (بدون سجل الدردشة).",newSessionNoHistory:"استخدام جلسة جديدة (بدون سجل الدردشة).",controlHint:"اضغط Ctrl+S لإيقاف الوكيل الجاري، Ctrl+P للإيقاف المؤقت وإدخال أوامر فرعية.",replTabCompletionHint:"اضغط Tab لإكمال أوامر الشرطة المائلة (مثل /list و /list-skill و /show) أو exit/quit.",tuiScrollTranscriptHint:"في واجهة الطرفية: عجلة الفأرة، الأسهم، PgUp/PgDn، Ctrl+U/Ctrl+F (صفحة). Ctrl+U/F تمرّر السجل. Ctrl+D يبقى لنهاية المدخلات/الخروج عند السطر الفارغ أو الحذف للأمام أثناء الكتابة.",agentStopped:"تم إيقاف الوكيل.",pauseHeader:"--- الوكيل متوقف مؤقتاً ---",pauseCurrentRequest:"الطلب الحالي: {{request}}",pauseHelp:"الأوامر: 'continue' أو 'c' للمتابعة، 'exit' أو 'e' للخروج، أو اكتب طلباً جديداً لاستبدال الطلب الحالي.",pausePrompt:"[متوقف مؤقتاً] ",pauseRequestUpdated:"تم تحديث الطلب إلى: {{request}}"},shell:{noCommand:"لم يتم تقديم أمر بعد بادئة /shell. الاستخدام: /shell <command>",executionError:"خطأ في تنفيذ أمر shell: {{error}}",executing:"[shell] جاري التنفيذ: {{command}}",errorNoCommand:"لم يتم تقديم أمر بعد بادئة /shell.",errorSpawnFailed:"فشل بدء العملية: {{message}}",errorTimedOut:"انتهت مهلة الأمر بعد {{seconds}} ثانية",logFailed:"فشل أمر shell: {{command}} (رمز الخروج: {{code}})",logExecutionError:"خطأ تنفيذ أمر shell: {{message}}",resultCommand:"الأمر: {{command}}",resultExitCode:"رمز الخروج: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"النجاح:",resultSuccessYes:"نعم",resultSuccessNo:"لا",resultOutput:"المخرجات:",resultError:"الخطأ:"},init:{invalidType:'--type غير صالح "{{value}}"؛ اختر: {{choices}}',invalidLang:'--lang غير صالح "{{value}}"؛ اختر: {{choices}}',templatesDirNotFound:"لم يتم العثور على دليل القوالب: {{dir}}",createdPromptTemplates:"تم إنشاء {{dir}} (قوالب التلميحات)",createdSessions:"تم إنشاء {{dir}} (سجل الجلسات)",initialized:"تم تهيئة مشروع {{type}} في {{targetDir}}",promptFilesIn:"ملفات التلميحات في {{pithosaiDir}}، بيانات الجلسة في {{sessionsDir}}",runHint:'شغّل "pithosai -C {{targetDir}} \\"طلبك\\"" للبدء.',createdFile:"تم إنشاء {{path}}",roleAlreadyAdded:"الدور {{role}} موجود بالفعل في .pithosai؛ تخطي.",addedRoleTemplates:"تمت إضافة قوالب الأدوار إلى {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: أُغلقت المعاينة ({{source}})",skipped:"تخطّي معاينة المتصفح (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"قدّم إما markdown أو path فقط (لا كلاهما ولا بلا).",errorEmpty:"محتوى Markdown فارغ.",errorFileOutside:"يجب أن يبقى path داخل مجلد المشروع.",errorNotAFile:"path ليس ملفًا عاديًا.",errorFileTooLarge:"الملف أكبر من {{maxBytes}} بايت.",errorFileRead:"تعذّر قراءة الملف: {{message}}",sourceInline:"Markdown مضمّن",sourceFile:"ملف {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"البريد الإلكتروني لا يجب أن يكون فارغاً للـ heartbeat. قم بتكوين بريد دور {{role}} في جدول email_roles في قاعدة بيانات sqlite3.",loadedState:"تم تحميل حالة الـ heartbeat من SQLite للبريد {{email}} والدور {{role}}، الحالات: {{states}}",fetchFound:"وجد جلب الـ heartbeat للصندوق الوارد {{count}} مهام جديدة: {{ids}}",savedState:"تم حفظ حالة الـ heartbeat في SQLite للبريد {{email}} والدور {{role}}",mergedAndNext:"تم دمج {{merged}} مهام في الحالة، التالي للمعالجة: {{stateSummary}}",replyEmailFailed:"فشل إرسال بريد الرد للـ heartbeat: {{error}}",taskFailed:"فشلت مهمة الـ heartbeat: {{error}}",failureReplyEmailFailed:"فشل إرسال بريد إشعار الفشل للـ heartbeat: {{error}}"},cli:{description:"Pithosai: ينفذ الكود أو المشاريع من طلب بلغة طبيعية. يتم تحميل تلميحات الدور من قاعدة بيانات SQLite أثناء وقت التشغيل (مع خيار التراجع إلى .pithosai/<role>/*.md). أنشئ مشروعًا باستخدام 'pithosai init'.",versionOption:"عرض الإصدار",roleOption:"الدور (مجموعة القوالب لـ init)؛ القوالب في templates/<role>/",langOption:"لغة التلميحات وقوالب init: en, zh (الافتراضي: en)",interactiveModeOption:"الدخول إلى الوضع التفاعلي دون طلب؛ عرض نصائح الوضع وطلب الإدخال",initDescription:"إنشاء مشروع جديد وبنية دليل .pithosai/. يتم تحميل تلميحات الدور من قاعدة بيانات SQLite أثناء وقت التشغيل (مع خيار التراجع إلى .pithosai/<role>/*.md).",initTypeOption:"نوع المشروع: js أو ts أو python",initExamples:"\nأمثلة:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"إضافة قوالب الأدوار إلى .pithosai/<role>/ في المشروع",addRoleArgument:"الدور المراد إضافته (مثلاً PM, QA)",requestArgument:'ما الذي تريد بناؤه (مثلاً "واجهة CLI تحول CSV إلى JSON"). إذا حذفته، يعرض المساعدة.',cwdOption:"دليل المشروع (الافتراضي: الدليل الحالي)",skillsDirOption:"دليل المهارات لـ read_skill (الافتراضي: ./.pithosai/skills أو PITHOSAI_SKILLS_DIR)",reasonerOption:"استخدم نموذج DeepSeek Reasoner (تفكير)؛ الافتراضي DeepSeek Coder",chatOption:"استخدم نموذج DeepSeek Chat (محادثة عامة، وليس كود)؛ الافتراضي DeepSeek Coder",cursorOption:"استخدم نموذج Cursor CLI (المصادقة عبر cursor-agent login، لا حاجة لمفتاح API). يمكن تحديد النموذج اختيارياً: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"أقصى وقت تشغيل للوكيل بالثواني (الافتراضي: 1800). تجاوز بـ PITHOSAI_TIMEOUT_MS (مللي ثانية).",interactiveOption:"تعطيل المطالبة التفاعلية (الافتراضي: بعد كل رد، مطالبة بالرسالة التالية)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"جارٍ إنشاء الخطة…",waitingReply:"بانتظار الرد…",runningReply:"جارٍ التنفيذ…",resultPreviewOpening:"جارٍ فتح معاينة النتيجة في المتصفح…",resultPreviewTitle:"نتيجة Pithosai",resultPreviewFailed:"تعذر فتح المعاينة: {{message}}",resultPreviewCopy:"نسخ Markdown",resultPreviewClose:"إغلاق",resultPreviewCopied:"تم النسخ إلى الحافظة",resultPreviewTerminalHint:"↑↓ أو j/k \xb7 PgUp/PgDn أو Ctrl+U/Ctrl+D \xb7 Home/End أو gg/G \xb7 q/Esc للإغلاق",runExamples:'\nأمثلة:\n pithosai "أضف نقطة نهاية REST تُرجع الوقت الحالي"\n pithosai -C ./my-app "شغّل الاختبارات وأصلح الأخطاء"\n pithosai -i # الوضع التفاعلي: تحميل أحدث الجلسة ثم طلب الطلبات\n pithosai --no-interactive "طلب واحد" # رد واحد، بدون مطالبة متابعة\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"الاستخدام:",helpArguments:"الوسائط:",helpOptions:"الخيارات:",helpCommands:"الأوامر:",helpGlobalOptions:"الخيارات العامة:",helpOption:"عرض المساعدة للأمر",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"مراقبة ملف المهام ومعالجة المهام واحدة تلو الأخرى في نفس العملية",taskFileOption:"مسار ملف Markdown للمهام (الافتراضي: prompts.md في جذر المشروع)",taskModelOption:"مفتاح النموذج للمهمة (deepSeekCoder، deepSeekChat، deepSeekReasoner، ollamaQwen25، ollamaQwen25Coder، ollamaDeepSeekR1، cursorAutoModel، cursorSonnet، cursorSonnetThinking، cursorOpus، cursorGpt)",taskNewSessionOption:"البدء بجلسة جديدة (بدون سجل محادثة)",taskExamples:"\nأمثلة:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"المهمة غير موجودة: {{taskId}}",taskAgentCompleted:"اكتمل الوكيل.",taskAgentRunFailed:"فشل تشغيل الوكيل.",taskDone:"تم",taskFailed:"فشلت المهمة: {{message}}",taskProcessingHeader:"--- معالجة المهمة ---",taskLabelId:"المعرّف:",taskLabelTitle:"العنوان:",taskLabelStatus:"الحالة:",taskLabelDescription:"الوصف:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"بدء المعالج للمهمة قيد التنفيذ {{id}} ({{title}}).",taskNoPending:"لا توجد مهام معلّقة.",taskPickedTask:"تم اختيار المهمة {{id}} ({{title}})؛ بدء المعالج.",taskProcessorFailed:"فشل معالج المهام: {{message}}",taskWatcherRunning:"مراقب المهام يعمل. اضغط Ctrl+C للإيقاف.",memorizeDescription:"يكتب .pithosai/<role>/memory.md بملخصات للمهام التي شارك فيها الدور (رسائل مهام محفوظة ضمن النطاق الزمني).",memorizeStartOption:"بداية النطاق: YYYY-MM-DD أو ISO",memorizeEndOption:"نهاية النطاق: YYYY-MM-DD أو ISO",memorizeRoleRequired:"الدور مطلوب (-r/--role أو --role العام).",memorizeWrote:"تمت الكتابة إلى {{path}} ({{count}} مهمة).",memorizeNoTasks:"لا مهام في النطاق للدور {{role}}؛ تمت كتابة الترويسة إلى {{path}}.",memorizeDateError:"نطاق تاريخ غير صالح: {{message}}",memorizeNoLlmOption:"تخطي ملخص LLM؛ كتابة الذاكرة المنظمة فقط (مثل PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"فشل ملخص LLM ({{message}})؛ تمت كتابة ذاكرة منظمة دون ملخص.",memorizeExamples:"\nأمثلة:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Get shell commands for a request (Ollama only, outputs commands only)",argument:"What you want to do (e.g. list large files in current dir)",loading:"Getting commands...",examples:'\nExamples:\n $ pithosai shell-tips list json files in current directory\n $ pithosai shell-tips "find and replace foo with bar in all .js files"'},writer:{description:"Generate text for a request (Ollama qwen2.5:14b)",argument:"What to write (e.g. short email declining a meeting)",loading:"Writing...",examples:'\nExamples:\n $ pithosai writer short email declining a meeting\n $ pithosai writer "three bullet points for a project kickoff"'},skills:{installing:"تثبيت المهارات في {{dir}}",fetchingList:"جلب المهارات المتاحة من ClawHub...",fetchingIndex:"جلب فهرس المهارات من {{url}}",notFound:"المهارة '{{name}}' غير موجودة",noSkillsAvailable:"لا توجد مهارات متاحة من ClawHub",noSkillsFound:"لم يتم العثور على مهارات",downloadFailed:"فشل تحميل المهارة '{{name}}': {{error}}",installed:"تم تثبيت المهارة '{{name}}'",complete:"اكتمل التثبيت: {{count}} من {{total}} مهارات مثبتة",alreadyInstalled:"المهارة '{{name}}' مثبتة بالفعل (استخدم --force لإعادة التثبيت)",downloading:"جاري تحميل المهارة '{{name}}' من {{url}}",noSkillsDir:"لم يتم العثور على دليل المهارات. قم بتثبيت المهارات أولاً.",noSkillsInstalled:"لا توجد مهارات مثبتة",installedList:"المهارات المثبتة ({{count}} إجمالاً) في {{dir}}:",notInstalled:"المهارة '{{name}}' غير مثبتة",removed:"تمت إزالة المهارة '{{name}}'"},skillConvert:{welcome:"نظام تحويل المهارات - تحويل المهارات الناجحة إلى أدوات دائمة",listHeader:"تحليل تحويل المهارات ({{totalSkills}} مهارات، {{totalExecutions}} عملية تنفيذ)",noSuggestions:"لا توجد مهارات تصل إلى عتبة التحويل {{threshold}}.",suggestedConversions:"التحويلات المقترحة:",convertHint:"استخدم 'pithosai skill-convert convert <اسم-المهارة>' لتحويل مهارة.",skillNotFound:"المهارة '{{skillName}}' غير موجودة أو لا يمكن قراءتها: {{error}}",alreadyConverted:"المهارة '{{skillName}}' تم تحويلها بالفعل إلى أداة.",useForceHint:"استخدم --force للتحويل مرة أخرى.",conversionReportHeader:"تقرير تحويل '{{skillName}}':",conversionScore:"درجة التحويل",suggestedType:"النوع المقترح",ready:"جاهز للتحويل",estimatedBenefits:"الفوائد المقدّرة",performance:"تحسين الأداء",reliability:"تحسين الموثوقية",usability:"تحسين سهولة الاستخدام",parameters:"المعاملات",notReadyWarning:"هذه المهارة ليست جاهزة للتحويل التلقائي.",moreUsageHint:"استخدم المهارة بشكل أكثر تكراراً أو استخدم --force لفرض التحويل.",dryRunComplete:"اكتملت المحاكاة. لم يتم إجراء أي تغييرات.",confirmConversion:"تحويل '{{skillName}}' إلى أداة دائمة؟",conversionCancelled:"تم إلغاء التحويل.",converting:"جاري تحويل '{{skillName}}' إلى أداة...",conversionSuccess:"تم تحويل '{{skillName}}' بنجاح إلى '{{toolName}}'.\nالأداة محفوظة في: {{toolPath}}",usageExample:"مثال الاستخدام:",nextSteps:"الخطوات التالية:",restartAgent:"أعد تشغيل الوكيل لتحميل الأداة الجديدة",testTool:"اختبر الأداة: <اسم-الأداة> --help",manageTools:"إدارة الأدوات: pithosai skill-convert tools",listError:"خطأ في عرض المهارات: {{error}}",conversionError:"خطأ في تحويل '{{skillName}}': {{error}}",skillStatsHeader:"إحصائيات '{{skillName}}':",generalStats:"إحصائيات عامة",totalExecutions:"إجمالي عمليات التنفيذ",successful:"ناجحة",failed:"فاشلة",avgTime:"متوسط وقت التنفيذ",lastUsed:"آخر استخدام",recentExecutions:"عمليات التنفيذ الأخيرة",commonParameters:"المعاملات الشائعة",overallStatsHeader:"إحصائيات المهارات الإجمالية",overallStats:"إحصائيات إجمالية",totalSkillsTracked:"إجمالي المهارات المتتبعة",avgSuccessRate:"متوسط معدل النجاح",topSkills:"أكثر المهارات استخداماً",conversionSuggestions:"اقتراحات التحويل",statsError:"خطأ في الحصول على الإحصائيات: {{error}}",confirmClearAll:"مسح جميع سجلات تنفيذ المهارات؟ لا يمكن التراجع عن هذا الإجراء.",allRecordsCleared:"تم مسح جميع سجلات تنفيذ المهارات.",skillRecordsCleared:"تم مسح سجلات تنفيذ '{{skillName}}'.",clearCancelled:"تم إلغاء عملية المسح.",specifySkillOrAll:"حدد اسم مهارة أو استخدم --all",clearError:"خطأ في مسح السجلات: {{error}}",noConvertedTools:"لم يتم العثور على أدوات محوّلة.",convertedToolsHeader:"الأدوات المحوّلة:",originalSkill:"المهارة الأصلية",converted:"تم التحويل في",usageCount:"عدد الاستخدامات",toolsError:"خطأ في إدارة الأدوات: {{error}}",confirmRemoveTool:"إزالة الأداة '{{toolName}}'؟",toolRemoved:"تمت إزالة الأداة '{{toolName}}'.",toolRemoveFailed:"فشل في إزالة الأداة '{{toolName}}'.",removeCancelled:"تم إلغاء إزالة الأداة.",toolEnabled:"تم تفعيل الأداة '{{toolName}}'.",toolEnableFailed:"فشل في تفعيل الأداة '{{toolName}}'.",toolDisabled:"تم تعطيل الأداة '{{toolName}}'.",toolDisableFailed:"فشل في تعطيل الأداة '{{toolName}}'.",noStatsForSkill:"لم يتم العثور على إحصائيات للمهارة '{{skillName}}'."},hooks:{description:"إدارة خطافات الوكيل للتصحيح والأمان والمراقبة",list:{description:"عرض جميع الخطافات المسجلة",title:"\uD83D\uDCCB الخطافات المسجلة",total:"المجموع: {{total}} معالج",options:{verbose:"عرض معلومات تفصيلية عن المعالجات"},error:"فشل في عرض الخطافات: {{error}}"},debug:{description:"تفعيل خطافات التصحيح لمراقبة سلوك الوكيل",options:{data:"تسجيل البيانات الكاملة في مخرجات التصحيح",performance:"تفعيل خطافات مراقبة الأداء",stats:"تفعيل خطافات جمع الإحصائيات",all:"تفعيل جميع خطافات التصحيح"},added:{debug:"تمت إضافة خطافات سجل التصحيح",performance:"تمت إضافة خطافات مراقبة الأداء",stats:"تمت إضافة خطافات جمع الإحصائيات",basic:"تمت إضافة خطافات التصحيح الأساسية"},success:"تم تفعيل خطافات التصحيح ({{count}} معالج مسجل)",error:"فشل في تفعيل خطافات التصحيح: {{error}}"},security:{description:"تفعيل خطافات الأمان للتحكم في الوصول والمراقبة",options:{block:"قائمة أدوات للحظر مفصولة بفواصل",maxPrompt:"الحد الأقصى المسموح لطول المطالبة (الافتراضي: 10000)"},success:"تم تفعيل خطافات الأمان",blockedTools:"الأدوات المحظورة: {{tools}}",maxPrompt:"الحد الأقصى لطول المطالبة: {{length}} حرف",error:"فشل في تفعيل خطافات الأمان: {{error}}"},clear:{description:"مسح جميع الخطافات المسجلة",success:"تم مسح جميع الخطافات",error:"فشل في مسح الخطافات: {{error}}"},test:{description:"اختبار الخطافات عن طريق تشغيلها ببيانات اختبار",argument:{hookType:"نوع خطاف محدد للاختبار (اختياري)"},invalidType:"نوع خطاف غير صالح: {{type}}",triggered:"تم تشغيل الخطاف: {{type}}",result:"النتيجة: {{result}}",allTriggered:"تم تشغيل جميع الخطافات بنجاح",error:"فشل في اختبار الخطافات: {{error}}"},register:{description:"تسجيل معالج خطاف مخصص من ملف",argument:{hookType:"نوع الخطاف لتسجيل المعالج له",handlerFile:"مسار ملف المعالج (يجب أن يصدّر دالة افتراضية)"},invalidType:"نوع خطاف غير صالح: {{type}}",invalidHandler:"يجب أن يصدّر ملف المعالج دالة افتراضية",success:"تم تسجيل معالج لـ {{type}} من {{file}}",error:"فشل في تسجيل الخطاف: {{error}}"},status:{description:"عرض تكوين الخطافات الحالي والإحصائيات",title:"\uD83D\uDCCB حالة الخطافات",error:"فشل في الحصول على حالة الخطافات: {{error}}"}}}},9995(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Grundanforderung",projectDir:"Projektverzeichnis (hier arbeiten): {{cwd}}",skillsInstruction:"Verwende das read_skill-Tool, um die vollst\xe4ndigen Anweisungen einer F\xe4higkeit zu laden, wenn die Aufgabe zu ihrer Beschreibung passt.",toolArgSizeLimit:"\xdcberschreiten Sie niemals {{maxChars}} Zeichen in einem einzelnen Tool-Aufrufargument (z. B. dem content eines write). Gr\xf6\xdfere Nutzdaten k\xf6nnen von der API abgeschnitten werden und „Unterminated string in JSON“-Fehler verursachen. Lange Dateien oder Skripte in mehrere write-Aufrufe aufteilen (z. B. pro Datei oder pro Abschnitt unter {{maxChars}} Zeichen).",toolCallJsonFormat:'Tool-Aufrufargumente m\xfcssen g\xfcltiges JSON sein: Jeder Schl\xfcssel und jeder Zeichenkettenwert in doppelten Anf\xfchrungszeichen. Beispiel f\xfcr write: {"path": "dateiname.md", "content": "Inhalt hier"}. Lassen Sie keine Anf\xfchrungszeichen um Schl\xfcssel oder Werte weg (z. B. path: datei.md ist ung\xfcltig).'},errors:{missingPromptFiles:"Fehlende erforderliche Prompt-Dateien in {{dir}}:",runInit:"F\xfchre 'pithosai init' im Projektstamm aus, um .pithosai mit Vorlagen zu erstellen.",noApiKey:"Kein API-Schl\xfcssel gefunden. Setze DEEPSEEK_API_KEY oder OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama ist nicht konfiguriert. Setze OPENAI_LOCAL_API_BASE oder verwende ein Projekt mit lokalem Modell.",noValidTemplateFiles:"Keine g\xfcltigen Vorlagendateien in {{dir}}. Erwartet *-<lang>.md (z. B. IDENTITY-ja.md). F\xfchre 'pithosai init' aus, um .pithosai mit Vorlagen zu erstellen.",runTimeout:"Agent-Lauf nach {{seconds}} Sekunden abgelaufen. Verwende --timeout <Sekunden> oder PITHOSAI_TIMEOUT_MS zur Anpassung.",agentRunFailed:"Ausf\xfchrung fehlgeschlagen: {{message}}",unknownRunError:"Unbekannter Fehler"},warnings:{sessionAppend:"Sitzung anh\xe4ngen: {{message}}",apiRetry:"API-Fehler bei Versuch {{attempt}}/{{max}}; erneuter Versuch..."},reasoner:{thinkingHeader:"\n--- Denken:\n",replyHeader:"\n\n--- Antwort:\n"},run:{cwd:"cwd {{cwd}}",request:"Anfrage: {{request}}",interactivePrompt:"Sie: ",tuiYouLabel:"Sie:",interactiveExitHint:"Bitte antworten oder neue Anfrage eingeben („exit“ oder „quit“ zum Beenden der CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Interaktiv — Agent (volles Toolset) ---",interactiveModeAgentTips:"- Volles Toolset (Lesen, Schreiben, Ausf\xfchren, je nach Konfiguration).\n- Gespr\xe4che werden pro Aufgabe in der lokalen Datenbank gespeichert.\n- `/new` vergibt eine neue Aufgaben-ID; fr\xfchere Nachrichten werden nicht geladen.\n- `/shell <Befehl>` f\xfcr Shell; `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr Persistenz.\n- `/list-skill`, `/install-skill` und `/remove-skill` entsprechen `pithosai skills list|install|remove` (ClawHub). Strg+S stoppt, Strg+P pausiert.",interactiveModeDialogTitle:"--- Interaktiv — Dialog (Nur-Lese-Q&A) ---",interactiveModeDialogTips:"- Antworten nutzen nur Lesewerkzeuge (keine Shell, keine Datei\xe4nderungen, keine Befehle).\n- Gespr\xe4che werden pro Aufgabe in der lokalen Datenbank gespeichert.\n- `/new` vergibt eine neue Aufgaben-ID; fr\xfchere Nachrichten werden nicht geladen.\n- `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr persistierte Aufgaben.\n- `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub) wie die `pithosai skills`-CLI.",interactiveModePlanTitle:"--- Planmodus ---",interactiveModePlanTips:"- Jede Antwort wird als `<slug>-plan.md` im Projektverzeichnis gespeichert (die erste Zeile der Anfrage beeinflusst den Dateinamen).\n- Nur Lesewerkzeuge; Shell und \xe4ndernde Tools sind deaktiviert.\n- `/new` vergibt eine neue Aufgaben-ID.\n- `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr persistierte Aufgaben.\n- `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub) wie die `pithosai skills`-CLI.\n- Nach jedem Lauf k\xf6nnen Sie im Prompt weitere Plan-Anfragen eingeben (wie bei agent/dialog).",list:{noPersistedTasks:"Keine gespeicherten Aufgaben gefunden.",createTasksFirstHint:"Erstelle zuerst Aufgaben mit `pithosai task`.",persistedTasksHeader:"--- Gespeicherte Aufgaben ({{count}}) ---",selectTaskHint:"Verwende `/select <index>`, um eine Aufgabe auszuf\xfchren.",noTasksCached:"Keine Aufgaben zwischengespeichert. Bitte erst `/list` ausf\xfchren.",invalidIndex:"Ung\xfcltiger Index {{index}}. G\xfcltiger Bereich: 0-{{maxIndex}}.",selectUsage:"Verwendung: /select <index>",selectedTask:"Aufgabe #{{index}} ausgew\xe4hlt."},skillSlash:{installUsage:"Verwendung: /install-skill [--force] [skill-name]",removeUsage:"Verwendung: /remove-skill <skill-name>",listNoExtra:"/list-skill akzeptiert keine Argumente.",failed:"Skill-Befehl fehlgeschlagen: {{message}}"},show:{title:"Aktuelle Aufgabe",field:"Feld",value:"Wert",taskId:"taskId",mode:"Modus",model:"Modell",status:"Status",messageCount:"AnzahlNachrichten",usageInput:"Nutzung.Eingabe",usageOutput:"Nutzung.Ausgabe",usageCacheRead:"Nutzung.CacheLesen",usageCacheWrite:"Nutzung.CacheSchreiben",usageTotalTokens:"Nutzung.GesamtTokens"},showTask:{title:"Aufgaben-Q&A",taskIdLabel:"Aufgaben-ID",turnHeading:"Runde {{index}}",questionLabel:"Frage",answerLabel:"Antwort",createdLabel:"Erstellt",emptyQuestion:"(leere Frage)",emptyAnswer:"(keine Assistentenantwort als Text)",emptyNoMessages:"Noch keine Nutzernachrichten f\xfcr diese Aufgabe.",previewDocumentTitle:"Aufgaben-Q&A"},showPrompt:{previewDocumentTitle:"Systemaufforderung",previewHeading:"Systemaufforderung"},shellHint:"Verwenden Sie '/shell <Befehl>' zum Ausf\xfchren von Shell-Befehlen (z.B. '/shell ls -la').",replIntroDialog:"Dialogmodus: nur Lesewerkzeuge — `/shell` ist deaktiviert. `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` gelten f\xfcr persistierte Aufgaben. `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub).",replIntroPlan:"Planmodus: jede Antwort landet in `<slug>-plan.md` (erste Zeile beeinflusst den Namen). `/shell` ist deaktiviert; Ausgabe bleibt bis zum Abschluss minimal. `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr persistierte Aufgaben. `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub).",newSessionHint:"Verwenden Sie '/new <Anfrage>' f\xfcr eine neue Sitzung (ohne Chatverlauf).",newSessionNoHistory:"Neue Sitzung wird verwendet (ohne Chatverlauf).",controlHint:"Strg+S dr\xfccken, um den laufenden Agenten zu stoppen, Strg+P zum Pausieren und Eingabe von Unterbefehlen.",replTabCompletionHint:"Tab zum Vervollst\xe4ndigen von Slash-Befehlen (z. B. /list, /list-skill, /show) oder exit/quit.",tuiScrollTranscriptHint:"Terminal-UI: Bei langem Protokoll — Mausrad, Pfeiltasten, Bild↑/↓, Strg+U/Strg+F (Seite). Strg+U/F scrollen das Protokoll statt der \xfcblichen Editor-K\xfcrzel. Strg+D bleibt EOF/Beenden bei leerer Zeile bzw. Zeichen l\xf6schen.",agentStopped:"Agent gestoppt.",pauseHeader:"--- Agent pausiert ---",pauseCurrentRequest:"Aktuelle Anfrage: {{request}}",pauseHelp:"Befehle: 'continue' oder 'c' zum Fortsetzen, 'exit' oder 'e' zum Beenden, oder geben Sie eine neue Anfrage ein, um die aktuelle zu ersetzen.",pausePrompt:"[pausiert] ",pauseRequestUpdated:"Anfrage aktualisiert auf: {{request}}"},shell:{noCommand:"Kein Befehl nach /shell-Pr\xe4fix angegeben. Verwendung: /shell <Befehl>",executionError:"Fehler beim Ausf\xfchren des Shell-Befehls: {{error}}",executing:"[shell] Ausf\xfchren: {{command}}",errorNoCommand:"Kein Befehl nach /shell-Pr\xe4fix angegeben.",errorSpawnFailed:"Prozess konnte nicht gestartet werden: {{message}}",errorTimedOut:"Befehl nach {{seconds}} Sekunden abgelaufen",logFailed:"Shell-Befehl fehlgeschlagen: {{command}} (Exit-Code: {{code}})",logExecutionError:"Shell-Befehl Ausf\xfchrungsfehler: {{message}}",resultCommand:"Befehl: {{command}}",resultExitCode:"Exit-Code: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Erfolg:",resultSuccessYes:"Ja",resultSuccessNo:"Nein",resultOutput:"Ausgabe:",resultError:"Fehler:"},init:{invalidType:'Ung\xfcltiges --type "{{value}}"; w\xe4hle: {{choices}}',invalidLang:'Ung\xfcltiges --lang "{{value}}"; w\xe4hle: {{choices}}',templatesDirNotFound:"Vorlagenverzeichnis nicht gefunden: {{dir}}",createdPromptTemplates:"{{dir}} erstellt (Prompt-Vorlagen)",createdSessions:"{{dir}} erstellt (Sitzungsverlauf)",initialized:"{{type}}-Projekt in {{targetDir}} initialisiert",promptFilesIn:"Prompt-Dateien in {{pithosaiDir}}, Sitzungsdaten in {{sessionsDir}}",runHint:'F\xfchre "pithosai -C {{targetDir}} \\"deine Anfrage\\"" aus, um zu starten.',createdFile:"{{path}} erstellt",roleAlreadyAdded:"Rolle {{role}} bereits in .pithosai vorhanden; \xfcberspringen.",addedRoleTemplates:"Rollen-Vorlagen zu {{dir}} hinzugef\xfcgt"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: Vorschau geschlossen ({{source}})",skipped:"Browser-Vorschau \xfcbersprungen (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Geben Sie genau eines von markdown oder path an (nicht beides, nicht keines).",errorEmpty:"Der Markdown-Inhalt ist leer.",errorFileOutside:"path muss im Projektverzeichnis liegen.",errorNotAFile:"path ist keine regul\xe4re Datei.",errorFileTooLarge:"Datei ist gr\xf6\xdfer als {{maxBytes}} Bytes.",errorFileRead:"Datei konnte nicht gelesen werden: {{message}}",sourceInline:"Inline-Markdown",sourceFile:"Datei {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"E-Mail darf f\xfcr Heartbeat nicht leer sein. Konfigurieren Sie die E-Mail f\xfcr Rolle {{role}} in der Tabelle email_roles in der sqlite3-Datenbank.",loadedState:"Heartbeat-Zustand aus SQLite geladen f\xfcr E-Mail {{email}} und Rolle {{role}}, Zust\xe4nde: {{states}}",fetchFound:"Heartbeat-Inbox-Abruf hat {{count}} neue Aufgaben gefunden: {{ids}}",savedState:"Heartbeat-Zustand in SQLite gespeichert f\xfcr E-Mail {{email}} und Rolle {{role}}",mergedAndNext:"{{merged}} Aufgaben in Zustand zusammengef\xfchrt, n\xe4chster zu bearbeiten: {{stateSummary}}",replyEmailFailed:"Heartbeat-Antwort-E-Mail fehlgeschlagen: {{error}}",taskFailed:"Heartbeat-Aufgabe fehlgeschlagen: {{error}}",failureReplyEmailFailed:"Heartbeat-Fehlermeldungs-E-Mail fehlgeschlagen: {{error}}"},cli:{description:"Pithosai: setzt Code oder Projekte aus einer Anfrage in nat\xfcrlicher Sprache um. Rollen-Prompts werden zur Laufzeit aus der SQLite-Datenbank geladen (mit optionalem Fallback auf .pithosai/<role>/*.md). Erstellen Sie ein Projekt mit 'pithosai init'.",versionOption:"Version ausgeben",roleOption:"Rolle (Vorlagensatz f\xfcr init); Vorlagen in templates/<role>/",langOption:"Sprache f\xfcr Prompts und Init-Vorlagen: en, zh (Standard: en)",interactiveModeOption:"Interaktiven Modus ohne Anfrage starten; Modushinweise anzeigen und zur Eingabe auffordern",initDescription:"Neues Projekt und .pithosai/ Verzeichnisstruktur erstellen. Rollen-Prompts werden zur Laufzeit aus der SQLite-Datenbank geladen (mit optionalem Fallback auf .pithosai/<role>/*.md).",initTypeOption:"Projekttyp: js, ts oder python",initExamples:"\nBeispiele:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Rollen-Vorlagen zu .pithosai/<role>/ im Projekt hinzuf\xfcgen",addRoleArgument:"Hinzuzuf\xfcgende Rolle (z. B. PM, QA)",requestArgument:'Was gebaut werden soll (z. B. "Ein CLI, der CSV in JSON konvertiert"). Bei Weglassen: Hilfe anzeigen.',cwdOption:"Projektverzeichnis (Standard: aktuelles Verzeichnis)",skillsDirOption:"F\xe4higkeiten-Verzeichnis f\xfcr read_skill (Standard: ./.pithosai/skills oder PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner (Denk-)Modell verwenden; Standard ist DeepSeek Coder",chatOption:"DeepSeek Chat-Modell verwenden (allgemeiner Chat, kein Code); Standard ist DeepSeek Coder",cursorOption:"Cursor CLI-Modell verwenden (Auth via cursor-agent login, kein API-Schl\xfcssel n\xf6tig). Optional Modell angeben: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"Max. Agent-Laufzeit in Sekunden (Standard: 1800). \xdcberschreiben mit PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"Interaktive Eingabeaufforderung deaktivieren (Standard: nach jeder Antwort nach n\xe4chster Nachricht fragen)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Plan wird erstellt…",waitingReply:"Warten auf Antwort…",runningReply:"L\xe4uft…",resultPreviewOpening:"Vorschau wird im Browser ge\xf6ffnet…",resultPreviewTitle:"Pithosai-Ergebnis",resultPreviewFailed:"Vorschau konnte nicht ge\xf6ffnet werden: {{message}}",resultPreviewCopy:"Markdown kopieren",resultPreviewClose:"Schlie\xdfen",resultPreviewCopied:"In die Zwischenablage kopiert",resultPreviewTerminalHint:"↑↓ oder j/k \xb7 PgUp/PgDn oder Ctrl+U/Ctrl+D \xb7 Home/End oder gg/G \xb7 q/Esc schlie\xdfen",runExamples:'\nBeispiele:\n pithosai "F\xfcge einen REST-Endpoint hinzu, der die aktuelle Zeit zur\xfcckgibt"\n pithosai -C ./my-app "Tests ausf\xfchren und Fehler beheben"\n pithosai -i # Interaktiver Modus: letzte Sitzung laden, dann zur Eingabe auffordern\n pithosai --no-interactive "Einmal" # eine Antwort, keine Folgenachfrage\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Verwendung:",helpArguments:"Argumente:",helpOptions:"Optionen:",helpCommands:"Befehle:",helpGlobalOptions:"Globale Optionen:",helpOption:"Hilfe f\xfcr Befehl anzeigen",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Aufgabendatei \xfcberwachen und Aufgaben nacheinander im selben Prozess verarbeiten",taskFileOption:"Pfad zur Aufgaben-Markdown-Datei (Standard: prompts.md im Projektroot)",taskModelOption:"Modellschl\xfcssel f\xfcr die Aufgabe (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Mit neuer Sitzung starten (kein Chatverlauf)",taskExamples:"\nBeispiele:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Aufgabe nicht gefunden: {{taskId}}",taskAgentCompleted:"Agent abgeschlossen.",taskAgentRunFailed:"Agentenlauf fehlgeschlagen.",taskDone:"Fertig",taskFailed:"Aufgabe fehlgeschlagen: {{message}}",taskProcessingHeader:"--- Aufgabe wird verarbeitet ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Starte Verarbeitung f\xfcr laufende Aufgabe {{id}} ({{title}}).",taskNoPending:"Keine ausstehenden Aufgaben.",taskPickedTask:"Aufgabe {{id}} ({{title}}) ausgew\xe4hlt; starte Verarbeitung.",taskProcessorFailed:"Aufgabenprozessor fehlgeschlagen: {{message}}",taskWatcherRunning:"Aufgaben\xfcberwachung aktiv. Strg+C zum Beenden.",memorizeDescription:"Schreibt .pithosai/<role>/memory.md mit Zusammenfassungen der Aufgaben, an denen die Rolle beteiligt war (persistierte Aufgabenmeldungen im Zeitraum).",memorizeStartOption:"Beginn: YYYY-MM-DD oder ISO-Datum/-zeit",memorizeEndOption:"Ende: YYYY-MM-DD oder ISO-Datum/-zeit",memorizeRoleRequired:"Rolle ist erforderlich (-r/--role oder globales --role).",memorizeWrote:"Geschrieben: {{path}} ({{count}} Aufgabe(n)).",memorizeNoTasks:"Keine Aufgaben im Zeitraum f\xfcr Rolle {{role}}; Kopfzeile nach {{path}} geschrieben.",memorizeDateError:"Ung\xfcltiger Datumsbereich: {{message}}",memorizeNoLlmOption:"LLM-Zusammenfassung \xfcberspringen; nur strukturiertes Ged\xe4chtnis schreiben (wie PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"LLM-Zusammenfassung fehlgeschlagen ({{message}}); strukturiertes Ged\xe4chtnis ohne Zusammenfassung geschrieben.",memorizeExamples:"\nBeispiele:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Get shell commands for a request (Ollama only, outputs commands only)",argument:"What you want to do (e.g. list large files in current dir)",loading:"Getting commands...",examples:'\nExamples:\n $ pithosai shell-tips list json files in current directory\n $ pithosai shell-tips "find and replace foo with bar in all .js files"'},writer:{description:"Generate text for a request (Ollama qwen2.5:14b)",argument:"What to write (e.g. short email declining a meeting)",loading:"Writing...",examples:'\nExamples:\n $ pithosai writer short email declining a meeting\n $ pithosai writer "three bullet points for a project kickoff"'},skills:{installing:"F\xe4higkeiten in {{dir}} installieren",fetchingList:"Verf\xfcgbare F\xe4higkeiten von ClawHub abrufen...",fetchingIndex:"F\xe4higkeiten-Index von {{url}} abrufen",notFound:"F\xe4higkeit '{{name}}' nicht gefunden",noSkillsAvailable:"Keine F\xe4higkeiten von ClawHub verf\xfcgbar",noSkillsFound:"Keine F\xe4higkeiten gefunden",downloadFailed:"Herunterladen der F\xe4higkeit '{{name}}' fehlgeschlagen: {{error}}",installed:"F\xe4higkeit '{{name}}' installiert",complete:"Installation abgeschlossen: {{count}} von {{total}} F\xe4higkeiten installiert",alreadyInstalled:"F\xe4higkeit '{{name}}' bereits installiert (--force zum Neuinstallieren verwenden)",downloading:"F\xe4higkeit '{{name}}' von {{url}} wird heruntergeladen",noSkillsDir:"Kein F\xe4higkeiten-Verzeichnis gefunden. Installieren Sie zuerst F\xe4higkeiten.",noSkillsInstalled:"Keine F\xe4higkeiten installiert",installedList:"Installierte F\xe4higkeiten ({{count}} insgesamt) in {{dir}}:",notInstalled:"F\xe4higkeit '{{name}}' ist nicht installiert",removed:"F\xe4higkeit '{{name}}' entfernt"},skillConvert:{welcome:"F\xe4higkeiten-Konvertierungssystem - Erfolgreiche F\xe4higkeiten in permanente Tools umwandeln",listHeader:"F\xe4higkeiten-Konvertierungsanalyse ({{totalSkills}} F\xe4higkeiten, {{totalExecutions}} Ausf\xfchrungen)",noSuggestions:"Keine F\xe4higkeiten erreichen den Konvertierungsschwellenwert von {{threshold}}.",suggestedConversions:"Vorgeschlagene Konvertierungen:",convertHint:"Verwende 'pithosai skill-convert convert <F\xe4higkeitenname>' zum Konvertieren.",skillNotFound:"F\xe4higkeit '{{skillName}}' nicht gefunden oder nicht lesbar: {{error}}",alreadyConverted:"F\xe4higkeit '{{skillName}}' wurde bereits in ein Tool konvertiert.",useForceHint:"Verwende --force zum erneuten Konvertieren.",conversionReportHeader:"Konvertierungsbericht f\xfcr '{{skillName}}':",conversionScore:"Konvertierungsscore",suggestedType:"Vorgeschlagener Typ",ready:"Bereit zur Konvertierung",estimatedBenefits:"Gesch\xe4tzte Vorteile",performance:"Leistungsverbesserung",reliability:"Zuverl\xe4ssigkeitsverbesserung",usability:"Benutzerfreundlichkeitsverbesserung",parameters:"Parameter",notReadyWarning:"Diese F\xe4higkeit ist nicht bereit f\xfcr die automatische Konvertierung.",moreUsageHint:"Verwende die F\xe4higkeit h\xe4ufiger oder nutze --force zur erzwungenen Konvertierung.",dryRunComplete:"Testlauf abgeschlossen. Keine \xc4nderungen vorgenommen.",confirmConversion:"'{{skillName}}' in ein permanentes Tool konvertieren?",conversionCancelled:"Konvertierung abgebrochen.",converting:"'{{skillName}}' wird in Tool konvertiert...",conversionSuccess:"'{{skillName}}' erfolgreich in '{{toolName}}' konvertiert.\nTool gespeichert in: {{toolPath}}",usageExample:"Verwendungsbeispiel:",nextSteps:"N\xe4chste Schritte:",restartAgent:"Agent neu starten, um das neue Tool zu laden",testTool:"Tool testen: <Tool-Name> --help",manageTools:"Tools verwalten: pithosai skill-convert tools",listError:"Fehler beim Auflisten der F\xe4higkeiten: {{error}}",conversionError:"Fehler bei der Konvertierung von '{{skillName}}': {{error}}",skillStatsHeader:"Statistiken f\xfcr '{{skillName}}':",generalStats:"Allgemeine Statistiken",totalExecutions:"Ausf\xfchrungen gesamt",successful:"Erfolgreich",failed:"Fehlgeschlagen",avgTime:"Durchschnittliche Ausf\xfchrungszeit",lastUsed:"Zuletzt verwendet",recentExecutions:"Letzte Ausf\xfchrungen",commonParameters:"H\xe4ufige Parameter",overallStatsHeader:"Gesamtstatistiken der F\xe4higkeiten",overallStats:"Gesamtstatistiken",totalSkillsTracked:"Verfolgte F\xe4higkeiten gesamt",avgSuccessRate:"Durchschnittliche Erfolgsrate",topSkills:"Meistgenutzte F\xe4higkeiten",conversionSuggestions:"Konvertierungsvorschl\xe4ge",statsError:"Fehler beim Abrufen der Statistiken: {{error}}",confirmClearAll:"ALLE F\xe4higkeiten-Ausf\xfchrungsdatens\xe4tze l\xf6schen? Dies kann nicht r\xfcckg\xe4ngig gemacht werden.",allRecordsCleared:"Alle F\xe4higkeiten-Ausf\xfchrungsdatens\xe4tze gel\xf6scht.",skillRecordsCleared:"Ausf\xfchrungsdatens\xe4tze f\xfcr '{{skillName}}' gel\xf6scht.",clearCancelled:"L\xf6schvorgang abgebrochen.",specifySkillOrAll:"Bitte F\xe4higkeitenname angeben oder --all verwenden",clearError:"Fehler beim L\xf6schen der Datens\xe4tze: {{error}}",noConvertedTools:"Keine konvertierten Tools gefunden.",convertedToolsHeader:"Konvertierte Tools:",originalSkill:"Urspr\xfcngliche F\xe4higkeit",converted:"Konvertiert am",usageCount:"Verwendungsanzahl",toolsError:"Fehler bei der Tool-Verwaltung: {{error}}",confirmRemoveTool:"Tool '{{toolName}}' entfernen?",toolRemoved:"Tool '{{toolName}}' entfernt.",toolRemoveFailed:"Entfernen von Tool '{{toolName}}' fehlgeschlagen.",removeCancelled:"Tool-Entfernung abgebrochen.",toolEnabled:"Tool '{{toolName}}' aktiviert.",toolEnableFailed:"Aktivierung von Tool '{{toolName}}' fehlgeschlagen.",toolDisabled:"Tool '{{toolName}}' deaktiviert.",toolDisableFailed:"Deaktivierung von Tool '{{toolName}}' fehlgeschlagen.",noStatsForSkill:"Keine Statistiken f\xfcr F\xe4higkeit '{{skillName}}' gefunden."},hooks:{description:"Agent-Hooks f\xfcr Debugging, Sicherheit und \xdcberwachung verwalten",list:{description:"Alle registrierten Hooks auflisten",title:"\uD83D\uDCCB Registrierte Hooks",total:"Gesamt: {{total}} Handler",options:{verbose:"Detaillierte Handler-Informationen anzeigen"},error:"Hooks konnten nicht aufgelistet werden: {{error}}"},debug:{description:"Debug-Hooks zur \xdcberwachung des Agent-Verhaltens aktivieren",options:{data:"Vollst\xe4ndige Daten in der Debug-Ausgabe protokollieren",performance:"Performance-\xdcberwachungs-Hooks aktivieren",stats:"Statistik-Erfassungs-Hooks aktivieren",all:"Alle Debug-Hooks aktivieren"},added:{debug:"Debug-Logging-Hooks hinzugef\xfcgt",performance:"Performance-\xdcberwachungs-Hooks hinzugef\xfcgt",stats:"Statistik-Erfassungs-Hooks hinzugef\xfcgt",basic:"Basis-Debug-Hooks hinzugef\xfcgt"},success:"Debug-Hooks aktiviert ({{count}} Handler registriert)",error:"Debug-Hooks konnten nicht aktiviert werden: {{error}}"},security:{description:"Sicherheits-Hooks f\xfcr Zugriffskontrolle und \xdcberwachung aktivieren",options:{block:"Kommagetrennte Liste der zu blockierenden Tools",maxPrompt:"Maximal erlaubte Prompt-L\xe4nge (Standard: 10000)"},success:"Sicherheits-Hooks aktiviert",blockedTools:"Blockierte Tools: {{tools}}",maxPrompt:"Maximale Prompt-L\xe4nge: {{length}} Zeichen",error:"Sicherheits-Hooks konnten nicht aktiviert werden: {{error}}"},clear:{description:"Alle registrierten Hooks l\xf6schen",success:"Alle Hooks gel\xf6scht",error:"Hooks konnten nicht gel\xf6scht werden: {{error}}"},test:{description:"Hooks mit Testdaten ausl\xf6sen und testen",argument:{hookType:"Bestimmter Hook-Typ zum Testen (optional)"},invalidType:"Ung\xfcltiger Hook-Typ: {{type}}",triggered:"Hook ausgel\xf6st: {{type}}",result:"Ergebnis: {{result}}",allTriggered:"Alle Hooks erfolgreich ausgel\xf6st",error:"Hooks konnten nicht getestet werden: {{error}}"},register:{description:"Benutzerdefinierten Hook-Handler aus einer Datei registrieren",argument:{hookType:"Hook-Typ f\xfcr den Handler",handlerFile:"Pfad zur Handler-Datei (muss eine Standardfunktion exportieren)"},invalidType:"Ung\xfcltiger Hook-Typ: {{type}}",invalidHandler:"Handler-Datei muss eine Standardfunktion exportieren",success:"Handler f\xfcr {{type}} aus {{file}} registriert",error:"Hook konnte nicht registriert werden: {{error}}"},status:{description:"Aktuelle Hook-Konfiguration und Statistiken anzeigen",title:"\uD83D\uDCCB Hook-Status",error:"Hook-Status konnte nicht abgerufen werden: {{error}}"}}}},247(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Base requirement",projectDir:"Project directory (work here): {{cwd}}",skillsInstruction:"Use the read_skill tool to load a skill's full instructions when the task matches its description.",toolArgSizeLimit:'Never exceed {{maxChars}} characters in a single tool-call argument (e.g. the content of a write call). The API can truncate larger payloads and cause "Unterminated string in JSON" errors. For long files or scripts, split into multiple write calls (e.g. by file or by chunk under {{maxChars}} chars each).',toolCallJsonFormat:'Tool-call arguments must be valid JSON: every key and every string value must be in double quotes. Example for write: {"path": "filename.md", "content": "content here"}. Do not omit quotes around keys or values (e.g. path: file.md or content: text is invalid).'},errors:{missingPromptFiles:"missing required prompt files in {{dir}}:",runInit:"Run 'pithosai init' in the project root to create .pithosai with templates.",noApiKey:"no API key found. Set CURSOR_MODEL (e.g. auto), DEEPSEEK_API_KEY, or OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama is not configured. Set OPENAI_LOCAL_API_BASE or use a project with local model.",noValidTemplateFiles:"no valid template files in {{dir}}. Expected *-<lang>.md (e.g. IDENTITY-ja.md). Run 'pithosai init' to create .pithosai with templates.",runTimeout:"Agent run timed out after {{seconds}} seconds. Use --timeout <seconds> or PITHOSAI_TIMEOUT_MS to adjust.",agentRunFailed:"Run failed: {{message}}",unknownRunError:"Unknown error"},warnings:{sessionAppend:"session append: {{message}}",apiRetry:"API error on attempt {{attempt}}/{{max}}; retrying..."},reasoner:{thinkingHeader:"\n--- Thinking:\n",replyHeader:"\n\n--- Reply:\n"},run:{cwd:"cwd {{cwd}}",request:"request: {{request}}",interactivePrompt:"You: ",tuiYouLabel:"You:",interactiveExitHint:"Please answer or input new request(type 'exit' or 'quit' to exit the CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Interactive mode — Agent (full tools) ---",interactiveModeAgentTips:"- Full toolset (read, write, exec, and other tools as configured).\n- Conversation turns are stored per task in the local database.\n- `/new` assigns a new task id so prior messages are not loaded.\n- `/shell <command>` runs shell commands; `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work with persisted tasks.\n- `/list-skill`, `/install-skill`, and `/remove-skill` mirror `pithosai skills list|install|remove` (ClawHub). Ctrl+S stops the run, Ctrl+P pauses.",interactiveModeDialogTitle:"--- Interactive mode — Dialog (read-only Q&A) ---",interactiveModeDialogTips:"- Answers use read-only tools only (no shell, file edits, or command execution).\n- Conversation turns are stored per task in the local database.\n- `/new` assigns a new task id so prior messages are not loaded.\n- `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work with persisted tasks.\n- `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub) like the `pithosai skills` CLI.",interactiveModePlanTitle:"--- Plan mode ---",interactiveModePlanTips:"- Each reply is written to a `<slug>-plan.md` file in the project directory (the first line of your request shapes the filename).\n- Read-only tools only; shell and mutating tools are disabled.\n- `/new` assigns a new task id.\n- `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work with persisted tasks.\n- `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub) like the `pithosai skills` CLI.\n- You can enter more plan requests at the prompt after each run (same as agent/dialog).",list:{noPersistedTasks:"No persisted tasks found.",createTasksFirstHint:"Create tasks first using `pithosai task`.",persistedTasksHeader:"--- Persisted tasks ({{count}}) ---",selectTaskHint:"Use `/select <index>` to run a task.",noTasksCached:"No tasks cached. Run `/list` first.",invalidIndex:"Invalid index {{index}}. Valid range: 0-{{maxIndex}}.",selectUsage:"Usage: /select <index>",selectedTask:"Selected task #{{index}}."},skillSlash:{installUsage:"Usage: /install-skill [--force] [skill-name]",removeUsage:"Usage: /remove-skill <skill-name>",listNoExtra:"/list-skill does not take arguments.",failed:"Skill command failed: {{message}}"},show:{title:"Current task",field:"Field",value:"Value",taskId:"taskId",mode:"mode",model:"model",status:"status",messageCount:"messageCount",usageInput:"usage.input",usageOutput:"usage.output",usageCacheRead:"usage.cacheRead",usageCacheWrite:"usage.cacheWrite",usageTotalTokens:"usage.totalTokens"},showTask:{title:"Task Q&A",taskIdLabel:"Task ID",turnHeading:"Turn {{index}}",questionLabel:"Question",answerLabel:"Answer",createdLabel:"Created",emptyQuestion:"(empty question)",emptyAnswer:"(no assistant text reply)",emptyNoMessages:"No user messages for this task yet. Nothing to show.",previewDocumentTitle:"Task Q&A"},showPrompt:{previewDocumentTitle:"System prompt",previewHeading:"System prompt"},shellHint:"Use '/shell <command>' to execute shell commands (e.g., '/shell ls -la').",replIntroDialog:"Dialog mode: read-only tools only — `/shell` is disabled. `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work for persisted tasks. `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub).",replIntroPlan:"Plan mode: each reply is written to `<slug>-plan.md` in the project directory (first line of the request shapes the filename). `/shell` is disabled; output stays minimal until the plan completes. `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work for persisted tasks. `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub).",newSessionHint:"Use '/new <request>' to start a new session (no chat history).",newSessionNoHistory:"Using new session (no chat history).",controlHint:"Press Ctrl+S to stop the running agent, Ctrl+P to pause and enter sub-commands.",replTabCompletionHint:"Press Tab to complete slash commands (e.g. /list, /list-skill, /show) or exit/quit.",tuiScrollTranscriptHint:"In the terminal UI, long output: scroll with the mouse wheel, arrows, PgUp/PgDn, or Ctrl+U / Ctrl+F (page). Ctrl+U/Ctrl+F scroll the transcript instead of the editor’s usual line-edit shortcuts. Ctrl+D is unchanged (EOF / exit on empty line, delete forward when typing).",agentStopped:"Agent stopped.",pauseHeader:"--- Agent paused ---",pauseCurrentRequest:"Current request: {{request}}",pauseHelp:"Commands: 'continue' or 'c' to resume, 'exit' or 'e' to quit, or type a new request to replace the current one.",pausePrompt:"[paused] ",pauseRequestUpdated:"Request updated to: {{request}}"},shell:{noCommand:"No command provided after /shell prefix. Usage: /shell <command>",executionError:"Error executing shell command: {{error}}",executing:"[shell] Executing: {{command}}",errorNoCommand:"No command provided after /shell prefix.",errorSpawnFailed:"Failed to spawn process: {{message}}",errorTimedOut:"Command timed out after {{seconds}} seconds",logFailed:"Shell command failed: {{command}} (exit code: {{code}})",logExecutionError:"Shell command execution error: {{message}}",resultCommand:"Command: {{command}}",resultExitCode:"Exit code: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Success:",resultSuccessYes:"Yes",resultSuccessNo:"No",resultOutput:"Output:",resultError:"Error:"},init:{invalidType:'invalid --type "{{value}}"; choose: {{choices}}',invalidLang:'invalid --lang "{{value}}"; choose: {{choices}}',templatesDirNotFound:"templates directory not found: {{dir}}",createdPromptTemplates:"created {{dir}} (prompt templates)",createdSessions:"created {{dir}} (session history)",initialized:"initialized {{type}} project in {{targetDir}}",promptFilesIn:"prompt files in {{pithosaiDir}}, session data in {{sessionsDir}}",runHint:'run "pithosai -C {{targetDir}} \\"your request\\"" to start.',createdFile:"created {{path}}",roleAlreadyAdded:"role {{role}} already present in .pithosai; skipping.",addedRoleTemplates:"added role templates to {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: preview closed ({{source}})",skipped:"Browser preview skipped (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Provide exactly one of markdown or path (not both, not neither).",errorEmpty:"Markdown content is empty.",errorFileOutside:"path must stay under the project directory.",errorNotAFile:"path is not a regular file.",errorFileTooLarge:"File is larger than {{maxBytes}} bytes.",errorFileRead:"Could not read file: {{message}}",sourceInline:"inline markdown",sourceFile:"file {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"Email must not be empty for heartbeat. Configure role {{role}} email in email_roles table in sqlite3 db",loadedState:"Loaded heartbeat state from SQLite for email {{email}} and role {{role}}, states: {{states}}",fetchFound:"Heartbeat fetch inbox found {{count}} new tasks: {{ids}}",savedState:"Saved heartbeat state to SQLite for email {{email}} and role {{role}}",mergedAndNext:"Merged {{merged}} tasks into state, found next state to process: {{stateSummary}}",replyEmailFailed:"Heartbeat reply email failed: {{error}}",taskFailed:"Heartbeat task failed: {{error}}",failureReplyEmailFailed:"Heartbeat failure reply email failed: {{error}}"},cli:{description:"Pithosai: implements code or projects from a natural-language request. Role prompts are loaded from the SQLite DB at runtime (with optional fallback to .pithosai/<role>/*.md). Create project with 'pithosai init'.",versionOption:"output version",roleOption:"role (template set to use for init); templates are in templates/<role>/",langOption:"language for prompts and init templates: en, zh (default: en)",interactiveModeOption:"enter interactive mode without a request; show mode tips and prompt for input",initDescription:"Create a new project and .pithosai/ directory structure. Role prompts are loaded from the SQLite DB at runtime (with optional fallback to .pithosai/<role>/*.md).",initTypeOption:"project type: js, ts, or python",initExamples:"\nExamples:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Add role templates to .pithosai/<role>/ in the project",addRoleArgument:"role to add (e.g. PM, QA)",requestArgument:'what to build (e.g. "A CLI that converts CSV to JSON"). If omitted, show help.',cwdOption:"project directory (default: current directory)",skillsDirOption:"skills directory for read_skill (default: ./.pithosai/skills or PITHOSAI_SKILLS_DIR)",reasonerOption:"use DeepSeek Reasoner (thinking) model; default is DeepSeek Coder",chatOption:"use DeepSeek Chat model (general chat, not code); default is DeepSeek Coder",cursorOption:"use Cursor CLI model (auth via cursor-agent login, no API key needed). Optionally specify model: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"max agent run time in seconds (default: 1800). Override with PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"disable interactive prompt (default: after each reply, prompt for your next message)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Generating plan…",waitingReply:"Waiting for reply…",runningReply:"Running…",resultPreviewOpening:"Opening result preview in browser…",resultPreviewTitle:"Pithosai result",resultPreviewFailed:"Could not open result preview: {{message}}",resultPreviewCopy:"Copy markdown",resultPreviewClose:"Close",resultPreviewCopied:"Copied to clipboard",resultPreviewTerminalHint:"↑↓ or j/k \xb7 PgUp/PgDn or Ctrl+U/Ctrl+D \xb7 Home/End or gg/G \xb7 q/Esc close",runExamples:'\nExamples:\n pithosai "Add a REST endpoint that returns the current time"\n pithosai -C ./my-app "Run tests and fix failures"\n pithosai -i # interactive mode: load latest session, then prompt for requests\n pithosai --no-interactive "One shot" # single reply, no follow-up prompt\n pithosai --mode dialog "Explain this error" # chat only; no tools or /shell\n pithosai --mode plan "Sprint plan for the API" # writes e.g. sprint-plan-for-the-api-plan.md\n',helpUsage:"Usage:",helpArguments:"Arguments:",helpOptions:"Options:",helpCommands:"Commands:",helpGlobalOptions:"Global Options:",helpOption:"display help for command",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Watch task file and process tasks (one at a time in the same process)",taskFileOption:"Path to task markdown file (default: prompts.md in project root)",taskModelOption:"Model key for the task (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Start with a new session (no chat history)",taskExamples:"\nExamples:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Task not found: {{taskId}}",taskAgentCompleted:"Agent completed.",taskAgentRunFailed:"Agent run failed.",taskDone:"Done",taskFailed:"Task failed: {{message}}",taskProcessingHeader:"--- Processing task ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Starting processor for processing task {{id}} ({{title}}).",taskNoPending:"No pending tasks.",taskPickedTask:"Picked task {{id}} ({{title}}); starting processor.",taskProcessorFailed:"Task processor failed: {{message}}",taskWatcherRunning:"Task watcher running. Ctrl+C to stop.",showPromptDescription:"Display the system prompt that would be used for a run",showPromptModeOption:"mode: agent, dialog, or plan (default: agent)",showPromptRawOption:"show raw prompt before truncation and tool blocks",showPromptTruncatedOption:"show truncated prompt (requires model config)",showPromptInvalidMode:"Invalid mode. Must be 'agent', 'dialog', or 'plan'.",showPromptError:"Error building prompt: {{message}}",memorizeDescription:"Write .pithosai/<role>/memory.md with summaries of tasks the role participated in (from persisted task messages in the date range).",memorizeStartOption:"Range start: YYYY-MM-DD or ISO datetime",memorizeEndOption:"Range end: YYYY-MM-DD or ISO datetime",memorizeRoleRequired:"Role is required (use -r/--role or global --role).",memorizeWrote:"Wrote {{path}} ({{count}} task(s)).",memorizeNoTasks:"No tasks in range for role {{role}}; wrote header to {{path}}.",memorizeDateError:"Invalid date range: {{message}}",memorizeNoLlmOption:"Skip LLM summarization; write structured memory only (same as PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"LLM summarization failed ({{message}}); wrote structured memory without summary.",memorizeExamples:"\nExamples:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Get shell commands for a request (Ollama only, outputs commands only)",argument:"What you want to do (e.g. list large files in current dir)",loading:"Getting commands...",examples:'\nExamples:\n $ pithosai shell-tips list json files in current directory\n $ pithosai shell-tips "find and replace foo with bar in all .js files"'},writer:{description:"Generate text for a request (Ollama qwen2.5:14b)",argument:"What to write (e.g. short email declining a meeting)",loading:"Writing...",examples:'\nExamples:\n $ pithosai writer short email declining a meeting\n $ pithosai writer "three bullet points for a project kickoff"'},skills:{installing:"Installing skills to {{dir}}",fetchingList:"Fetching available skills from ClawHub...",fetchingIndex:"Fetching skills index from {{url}}",notFound:"Skill '{{name}}' not found",noSkillsAvailable:"No skills available from ClawHub",noSkillsFound:"No skills found",downloadFailed:"Failed to download skill '{{name}}': {{error}}",installed:"Installed skill '{{name}}'",complete:"Installation complete: {{count}} of {{total}} skills installed",alreadyInstalled:"Skill '{{name}}' already installed (use --force to reinstall)",downloading:"Downloading skill '{{name}}' from {{url}}",noSkillsDir:"No skills directory found. Install skills first.",noSkillsInstalled:"No skills installed",installedList:"Installed skills ({{count}} total) in {{dir}}:",notInstalled:"Skill '{{name}}' is not installed",removed:"Removed skill '{{name}}'"},skillConvert:{welcome:"Skill Conversion System - Convert successful skills to permanent tools",listHeader:"Skill Conversion Analysis ({{totalSkills}} skills, {{totalExecutions}} executions)",noSuggestions:"No skills meet the conversion threshold of {{threshold}}.",suggestedConversions:"Suggested Conversions:",convertHint:"Use 'pithosai skill-convert convert <skill-name>' to convert a skill.",skillNotFound:"Skill '{{skillName}}' not found or cannot be read: {{error}}",alreadyConverted:"Skill '{{skillName}}' has already been converted to a tool.",useForceHint:"Use --force to convert again.",conversionReportHeader:"Conversion Report for '{{skillName}}':",conversionScore:"Conversion Score",suggestedType:"Suggested Type",ready:"Ready for Conversion",estimatedBenefits:"Estimated Benefits",performance:"Performance Improvement",reliability:"Reliability Improvement",usability:"Usability Improvement",parameters:"Parameters",notReadyWarning:"This skill is not ready for automatic conversion.",moreUsageHint:"Use the skill more frequently or use --force to convert anyway.",dryRunComplete:"Dry run complete. No changes were made.",confirmConversion:"Convert '{{skillName}}' to a permanent tool?",conversionCancelled:"Conversion cancelled.",converting:"Converting '{{skillName}}' to tool...",conversionSuccess:"Successfully converted '{{skillName}}' to '{{toolName}}'.\nTool saved to: {{toolPath}}",usageExample:"Usage Example:",nextSteps:"Next Steps:",restartAgent:"Restart the agent to load the new tool",testTool:"Test the tool with: <tool-name> --help",manageTools:"Manage tools with: pithosai skill-convert tools",listError:"Error listing skills: {{error}}",conversionError:"Error converting '{{skillName}}': {{error}}",skillStatsHeader:"Statistics for '{{skillName}}':",generalStats:"General Statistics",totalExecutions:"Total Executions",successful:"Successful",failed:"Failed",avgTime:"Average Execution Time",lastUsed:"Last Used",recentExecutions:"Recent Executions",commonParameters:"Common Parameters",overallStatsHeader:"Overall Skill Statistics",overallStats:"Overall Statistics",totalSkillsTracked:"Total Skills Tracked",avgSuccessRate:"Average Success Rate",topSkills:"Top Skills by Usage",conversionSuggestions:"Conversion Suggestions",statsError:"Error getting statistics: {{error}}",confirmClearAll:"Clear ALL skill execution records? This cannot be undone.",allRecordsCleared:"All skill execution records cleared.",skillRecordsCleared:"Skill execution records for '{{skillName}}' cleared.",clearCancelled:"Clear operation cancelled.",specifySkillOrAll:"Please specify a skill name or use --all",clearError:"Error clearing records: {{error}}",noConvertedTools:"No converted tools found.",convertedToolsHeader:"Converted Tools:",originalSkill:"Original Skill",converted:"Converted",usageCount:"Usage Count",toolsError:"Error managing tools: {{error}}",confirmRemoveTool:"Remove tool '{{toolName}}'?",toolRemoved:"Tool '{{toolName}}' removed.",toolRemoveFailed:"Failed to remove tool '{{toolName}}'.",removeCancelled:"Tool removal cancelled.",toolEnabled:"Tool '{{toolName}}' enabled.",toolEnableFailed:"Failed to enable tool '{{toolName}}'.",toolDisabled:"Tool '{{toolName}}' disabled.",toolDisableFailed:"Failed to disable tool '{{toolName}}'.",noStatsForSkill:"No statistics found for skill '{{skillName}}'."},hooks:{description:"Manage agent hooks for debugging, security, and monitoring",list:{description:"List all registered hooks",title:"\uD83D\uDCCB Registered Hooks",total:"Total: {{total}} handlers",options:{verbose:"Show detailed handler information"},error:"Failed to list hooks: {{error}}"},debug:{description:"Enable debug hooks for monitoring agent behavior",options:{data:"Log full data in debug output",performance:"Enable performance monitoring hooks",stats:"Enable statistics collection hooks",all:"Enable all debug hooks"},added:{debug:"Added debug logging hooks",performance:"Added performance monitoring hooks",stats:"Added statistics collection hooks",basic:"Added basic debug hooks"},success:"Debug hooks enabled ({{count}} handlers registered)",error:"Failed to enable debug hooks: {{error}}"},security:{description:"Enable security hooks for access control and monitoring",options:{block:"Comma-separated list of tools to block",maxPrompt:"Maximum allowed prompt length (default: 10000)"},success:"Security hooks enabled",blockedTools:"Blocked tools: {{tools}}",maxPrompt:"Maximum prompt length: {{length}} characters",error:"Failed to enable security hooks: {{error}}"},clear:{description:"Clear all registered hooks",success:"All hooks cleared",error:"Failed to clear hooks: {{error}}"},test:{description:"Test hooks by triggering them with test data",argument:{hookType:"Specific hook type to test (optional)"},invalidType:"Invalid hook type: {{type}}",triggered:"Triggered hook: {{type}}",result:"Result: {{result}}",allTriggered:"All hooks triggered successfully",error:"Failed to test hooks: {{error}}"},register:{description:"Register a custom hook handler from a file",argument:{hookType:"Hook type to register handler for",handlerFile:"Path to handler file (must export default function)"},invalidType:"Invalid hook type: {{type}}",invalidHandler:"Handler file must export a default function",success:"Registered handler for {{type}} from {{file}}",error:"Failed to register hook: {{error}}"},status:{description:"Show current hook configuration and statistics",title:"\uD83D\uDCCB Hook Status",error:"Failed to get hook status: {{error}}"}}}},9556(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Requisito base",projectDir:"Directorio del proyecto (trabajar aqu\xed): {{cwd}}",skillsInstruction:"Usa la herramienta read_skill para cargar las instrucciones completas de una habilidad cuando la tarea coincida con su descripci\xf3n.",toolArgSizeLimit:"No superes nunca {{maxChars}} caracteres en un solo argumento de llamada a herramienta (p. ej. el content de un write). La API puede truncar payloads mayores y provocar errores \xabUnterminated string in JSON\xbb. Para archivos o scripts largos, divide en varias llamadas write (por archivo o por fragmento de menos de {{maxChars}} caracteres).",toolCallJsonFormat:'Los argumentos de llamada a herramienta deben ser JSON v\xe1lido: cada clave y cada valor de cadena entre comillas dobles. Ejemplo para write: {"path": "archivo.md", "content": "contenido aqu\xed"}. No omitas comillas en claves o valores (p. ej. path: archivo.md es inv\xe1lido).'},errors:{missingPromptFiles:"Faltan archivos de prompt requeridos en {{dir}}:",runInit:"Ejecuta 'pithosai init' en la ra\xedz del proyecto para crear .pithosai con plantillas.",noApiKey:"No se encontr\xf3 clave API. Configura DEEPSEEK_API_KEY u OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama no est\xe1 configurado. Configura OPENAI_LOCAL_API_BASE o usa un proyecto con modelo local.",noValidTemplateFiles:"No hay archivos de plantilla v\xe1lidos en {{dir}}. Se espera *-<lang>.md (ej. IDENTITY-ja.md). Ejecuta 'pithosai init' para crear .pithosai con plantillas.",runTimeout:"La ejecuci\xf3n del agente expir\xf3 tras {{seconds}} segundos. Usa --timeout <segundos> o PITHOSAI_TIMEOUT_MS para ajustar.",agentRunFailed:"Error en la ejecuci\xf3n: {{message}}",unknownRunError:"Error desconocido"},warnings:{sessionAppend:"A\xf1adir a sesi\xf3n: {{message}}",apiRetry:"Error de API en intento {{attempt}}/{{max}}; reintentando..."},reasoner:{thinkingHeader:"\n--- Pensamiento:\n",replyHeader:"\n\n--- Respuesta:\n"},run:{cwd:"cwd {{cwd}}",request:"petici\xf3n: {{request}}",interactivePrompt:"T\xfa: ",tuiYouLabel:"T\xfa:",interactiveExitHint:"Responde o escribe una nueva petici\xf3n (escribe 'exit' o 'quit' para salir de la CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Modo interactivo — Agente (herramientas completas) ---",interactiveModeAgentTips:"- Conjunto completo de herramientas (lectura, escritura, ejecuci\xf3n, seg\xfan configuraci\xf3n).\n- Los turnos se guardan por tarea en la base de datos local.\n- `/new` asigna un id de tarea nuevo; no se cargan mensajes anteriores.\n- `/shell <comando>` para shell; `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas.\n- `/list-skill`, `/install-skill` y `/remove-skill` equivalen a `pithosai skills list|install|remove` (ClawHub). Ctrl+S detiene, Ctrl+P pausa.",interactiveModeDialogTitle:"--- Modo interactivo — Di\xe1logo (solo lectura) ---",interactiveModeDialogTips:"- Solo herramientas de solo lectura (sin shell, edici\xf3n de archivos ni ejecuci\xf3n de comandos).\n- Los turnos se guardan por tarea en la base de datos local.\n- `/new` asigna un id de tarea nuevo; no se cargan mensajes anteriores.\n- `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas.\n- `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub) como la CLI `pithosai skills`.",interactiveModePlanTitle:"--- Modo plan ---",interactiveModePlanTips:"- Cada respuesta se escribe en `<slug>-plan.md` en el directorio del proyecto (la primera l\xednea de la petici\xf3n influye en el nombre).\n- Solo herramientas de lectura; shell y herramientas mutadoras desactivadas.\n- `/new` asigna un id de tarea nuevo.\n- `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas.\n- `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub) como la CLI `pithosai skills`.\n- Tras cada ejecuci\xf3n puede seguir con otra petici\xf3n de plan en el prompt (igual que agent/dialog).",list:{noPersistedTasks:"No se encontraron tareas guardadas.",createTasksFirstHint:"Crea tareas primero usando `pithosai task`.",persistedTasksHeader:"--- Tareas guardadas ({{count}}) ---",selectTaskHint:"Usa `/select <index>` para ejecutar una tarea.",noTasksCached:"No hay tareas en cach\xe9. Ejecuta `/list` primero.",invalidIndex:"\xcdndice no v\xe1lido {{index}}. Rango v\xe1lido: 0-{{maxIndex}}.",selectUsage:"Uso: /select <index>",selectedTask:"Tarea #{{index}} seleccionada."},skillSlash:{installUsage:"Uso: /install-skill [--force] [nombre-skill]",removeUsage:"Uso: /remove-skill <nombre-skill>",listNoExtra:"/list-skill no admite argumentos.",failed:"Fall\xf3 el comando de skill: {{message}}"},show:{title:"Tarea actual",field:"Campo",value:"Valor",taskId:"taskId",mode:"modo",model:"modelo",status:"estado",messageCount:"cantidadMensajes",usageInput:"uso.entrada",usageOutput:"uso.salida",usageCacheRead:"uso.cacheLectura",usageCacheWrite:"uso.cacheEscritura",usageTotalTokens:"uso.totalTokens"},showTask:{title:"Preguntas y respuestas de la tarea",taskIdLabel:"ID de tarea",turnHeading:"Turno {{index}}",questionLabel:"Pregunta",answerLabel:"Respuesta",createdLabel:"Creado",emptyQuestion:"(pregunta vac\xeda)",emptyAnswer:"(sin respuesta de texto del asistente)",emptyNoMessages:"A\xfan no hay mensajes de usuario para esta tarea.",previewDocumentTitle:"Preguntas y respuestas de la tarea"},showPrompt:{previewDocumentTitle:"Mensaje del sistema",previewHeading:"Mensaje del sistema"},shellHint:"Use '/shell <comando>' para ejecutar comandos de shell (ejemplo: '/shell ls -la').",replIntroDialog:"Modo di\xe1logo: solo herramientas de lectura — `/shell` desactivado. `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas. `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub).",replIntroPlan:"Modo plan: cada respuesta se guarda en `<slug>-plan.md` (la primera l\xednea influye en el nombre). `/shell` desactivado; salida m\xednima hasta terminar. `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas. `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub).",newSessionHint:"Use '/new <petici\xf3n>' para iniciar una nueva sesi\xf3n (sin historial de chat).",newSessionNoHistory:"Usando nueva sesi\xf3n (sin historial de chat).",controlHint:"Presiona Ctrl+S para detener el agente en ejecuci\xf3n, Ctrl+P para pausar y entrar en subcomandos.",replTabCompletionHint:"Tab para completar comandos con barra (p. ej. /list, /list-skill, /show) o exit/quit.",tuiScrollTranscriptHint:"En la UI de terminal: rueda, flechas, Re/Av P\xe1g, Ctrl+U/Ctrl+F (p\xe1gina). Ctrl+U/F desplazan el historial. Ctrl+D sigue siendo EOF/salir con l\xednea vac\xeda o borrar adelante al escribir.",agentStopped:"Agente detenido.",pauseHeader:"--- Agente en pausa ---",pauseCurrentRequest:"Solicitud actual: {{request}}",pauseHelp:"Comandos: 'continue' o 'c' para continuar, 'exit' o 'e' para salir, o escribe una nueva solicitud para reemplazar la actual.",pausePrompt:"[en pausa] ",pauseRequestUpdated:"Solicitud actualizada a: {{request}}"},shell:{noCommand:"No se proporcion\xf3 ning\xfan comando despu\xe9s del prefijo /shell. Uso: /shell <comando>",executionError:"Error al ejecutar el comando de shell: {{error}}",executing:"[shell] Ejecutando: {{command}}",errorNoCommand:"No se proporcion\xf3 ning\xfan comando despu\xe9s del prefijo /shell.",errorSpawnFailed:"Error al iniciar el proceso: {{message}}",errorTimedOut:"El comando expir\xf3 tras {{seconds}} segundos",logFailed:"Comando shell fallido: {{command}} (c\xf3digo de salida: {{code}})",logExecutionError:"Error de ejecuci\xf3n del comando shell: {{message}}",resultCommand:"Comando: {{command}}",resultExitCode:"C\xf3digo de salida: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"\xc9xito:",resultSuccessYes:"S\xed",resultSuccessNo:"No",resultOutput:"Salida:",resultError:"Error:"},init:{invalidType:'--type inv\xe1lido "{{value}}"; elige: {{choices}}',invalidLang:'--lang inv\xe1lido "{{value}}"; elige: {{choices}}',templatesDirNotFound:"Directorio de plantillas no encontrado: {{dir}}",createdPromptTemplates:"creado {{dir}} (plantillas de prompt)",createdSessions:"creado {{dir}} (historial de sesiones)",initialized:"proyecto {{type}} inicializado en {{targetDir}}",promptFilesIn:"archivos de prompt en {{pithosaiDir}}, datos de sesi\xf3n en {{sessionsDir}}",runHint:'ejecuta "pithosai -C {{targetDir}} \\"tu petici\xf3n\\"" para empezar.',createdFile:"creado {{path}}",roleAlreadyAdded:"el rol {{role}} ya est\xe1 en .pithosai; omitiendo.",addedRoleTemplates:"plantillas de rol a\xf1adidas a {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: vista previa cerrada ({{source}})",skipped:"Vista previa del navegador omitida (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Indica exactamente markdown o path (no ambos ni ninguno).",errorEmpty:"El contenido Markdown est\xe1 vac\xedo.",errorFileOutside:"path debe estar dentro del directorio del proyecto.",errorNotAFile:"path no es un archivo regular.",errorFileTooLarge:"El archivo supera {{maxBytes}} bytes.",errorFileRead:"No se pudo leer el archivo: {{message}}",sourceInline:"Markdown en l\xednea",sourceFile:"archivo {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"El correo no puede estar vac\xedo para el heartbeat. Configure el correo del rol {{role}} en la tabla email_roles en la base de datos sqlite3.",loadedState:"Estado del heartbeat cargado desde SQLite para correo {{email}} y rol {{role}}, estados: {{states}}",fetchFound:"El heartbeat encontr\xf3 {{count}} tareas nuevas en la bandeja: {{ids}}",savedState:"Estado del heartbeat guardado en SQLite para correo {{email}} y rol {{role}}",mergedAndNext:"Se fusionaron {{merged}} tareas en el estado, siguiente a procesar: {{stateSummary}}",replyEmailFailed:"Fall\xf3 el env\xedo del correo de respuesta del heartbeat: {{error}}",taskFailed:"Fall\xf3 la tarea del heartbeat: {{error}}",failureReplyEmailFailed:"Fall\xf3 el env\xedo del correo de notificaci\xf3n de fallo del heartbeat: {{error}}"},cli:{description:"Pithosai: implementa c\xf3digo o proyectos a partir de una petici\xf3n en lenguaje natural. Los prompts de rol se cargan desde la base de datos SQLite en tiempo de ejecuci\xf3n (con fallback opcional a .pithosai/<role>/*.md). Cree un proyecto con 'pithosai init'.",versionOption:"mostrar versi\xf3n",roleOption:"rol (conjunto de plantillas para init); plantillas en templates/<role>/",langOption:"idioma para prompts y plantillas init: en, zh (por defecto: en)",interactiveModeOption:"entrar en modo interactivo sin petici\xf3n; mostrar consejos del modo y pedir entrada",initDescription:"Crear un proyecto nuevo y la estructura de directorio .pithosai/. Los prompts de rol se cargan desde la base de datos SQLite en tiempo de ejecuci\xf3n (con fallback opcional a .pithosai/<role>/*.md).",initTypeOption:"tipo de proyecto: js, ts o python",initExamples:"\nEjemplos:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"A\xf1adir plantillas de rol a .pithosai/<role>/ en el proyecto",addRoleArgument:"rol a a\xf1adir (ej. PM, QA)",requestArgument:'qu\xe9 construir (ej. "Un CLI que convierte CSV a JSON"). Si se omite, mostrar ayuda.',cwdOption:"directorio del proyecto (por defecto: directorio actual)",skillsDirOption:"directorio de habilidades para read_skill (por defecto: ./.pithosai/skills o PITHOSAI_SKILLS_DIR)",reasonerOption:"usar modelo DeepSeek Reasoner (pensamiento); por defecto DeepSeek Coder",chatOption:"usar modelo DeepSeek Chat (chat general, no c\xf3digo); por defecto DeepSeek Coder",cursorOption:"usar modelo Cursor CLI (autenticaci\xf3n v\xeda cursor-agent login, sin clave API). Opcionalmente especificar modelo: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"tiempo m\xe1ximo de ejecuci\xf3n del agente en segundos (por defecto: 1800). Anular con PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"desactivar el mensaje interactivo (por defecto: tras cada respuesta, pedir la siguiente)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Generando el plan…",waitingReply:"Esperando respuesta…",runningReply:"Ejecutando…",resultPreviewOpening:"Abriendo vista previa del resultado en el navegador…",resultPreviewTitle:"Resultado de Pithosai",resultPreviewFailed:"No se pudo abrir la vista previa: {{message}}",resultPreviewCopy:"Copiar Markdown",resultPreviewClose:"Cerrar",resultPreviewCopied:"Copiado al portapapeles",resultPreviewTerminalHint:"↑↓ o j/k \xb7 PgUp/PgDn o Ctrl+U/Ctrl+D \xb7 Home/End o gg/G \xb7 q/Esc cerrar",runExamples:'\nEjemplos:\n pithosai "A\xf1ade un endpoint REST que devuelva la hora actual"\n pithosai -C ./my-app "Ejecutar tests y corregir fallos"\n pithosai -i # modo interactivo: cargar \xfaltima sesi\xf3n y pedir peticiones\n pithosai --no-interactive "Una vez" # una respuesta, sin pedir siguiente\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Uso:",helpArguments:"Argumentos:",helpOptions:"Opciones:",helpCommands:"Comandos:",helpGlobalOptions:"Opciones globales:",helpOption:"mostrar ayuda del comando",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Observa el archivo de tareas y proc\xe9salas de una en una en el mismo proceso",taskFileOption:"Ruta al Markdown de tareas (predeterminado: prompts.md en la ra\xedz del proyecto)",taskModelOption:"Clave de modelo para la tarea (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Empezar con una sesi\xf3n nueva (sin historial de chat)",taskExamples:"\nEjemplos:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Tarea no encontrada: {{taskId}}",taskAgentCompleted:"Agente completado.",taskAgentRunFailed:"Fall\xf3 la ejecuci\xf3n del agente.",taskDone:"Hecho",taskFailed:"Tarea fallida: {{message}}",taskProcessingHeader:"--- Procesando tarea ---",taskLabelId:"id:",taskLabelTitle:"t\xedtulo:",taskLabelStatus:"estado:",taskLabelDescription:"descripci\xf3n:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Iniciando procesador para la tarea en proceso {{id}} ({{title}}).",taskNoPending:"No hay tareas pendientes.",taskPickedTask:"Tarea {{id}} ({{title}}) elegida; iniciando procesador.",taskProcessorFailed:"Fall\xf3 el procesador de tareas: {{message}}",taskWatcherRunning:"Vigilancia de tareas en ejecuci\xf3n. Ctrl+C para detener.",memorizeDescription:"Escribe .pithosai/<role>/memory.md con res\xfamenes de las tareas en las que particip\xf3 el rol (mensajes de tarea persistidos en el rango de fechas).",memorizeStartOption:"Inicio del rango: YYYY-MM-DD o fecha-hora ISO",memorizeEndOption:"Fin del rango: YYYY-MM-DD o fecha-hora ISO",memorizeRoleRequired:"El rol es obligatorio (-r/--role o --role global).",memorizeWrote:"Escrito {{path}} ({{count}} tarea(s)).",memorizeNoTasks:"Sin tareas en el rango para el rol {{role}}; solo cabecera en {{path}}.",memorizeDateError:"Rango de fechas no v\xe1lido: {{message}}",memorizeNoLlmOption:"Omitir resumen con LLM; escribir solo memoria estructurada (igual que PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"Fall\xf3 el resumen con LLM ({{message}}); se escribi\xf3 memoria estructurada sin resumen.",memorizeExamples:"\nEjemplos:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Obtener comandos shell para una petici\xf3n (solo Ollama)",argument:"Qu\xe9 quieres hacer (ej. listar archivos grandes en el directorio actual)",loading:"Obteniendo comandos...",examples:'\nEjemplos:\n $ pithosai shell-tips listar archivos json en el directorio actual\n $ pithosai shell-tips "buscar y reemplazar foo por bar en todos los .js"'},writer:{description:"Generar texto para una petici\xf3n (Ollama qwen2.5:14b)",argument:"Qu\xe9 escribir (ej. email corto para declinar una reuni\xf3n)",loading:"Escribiendo...",examples:'\nEjemplos:\n $ pithosai writer email corto para declinar una reuni\xf3n\n $ pithosai writer "tres puntos para un kickoff de proyecto"'},skills:{installing:"Instalando habilidades en {{dir}}",fetchingList:"Obteniendo habilidades disponibles de ClawHub...",fetchingIndex:"Obteniendo \xedndice de habilidades desde {{url}}",notFound:"Habilidad '{{name}}' no encontrada",noSkillsAvailable:"No hay habilidades disponibles de ClawHub",noSkillsFound:"No se encontraron habilidades",downloadFailed:"Error al descargar la habilidad '{{name}}': {{error}}",installed:"Habilidad '{{name}}' instalada",complete:"Instalaci\xf3n completada: {{count}} de {{total}} habilidades instaladas",alreadyInstalled:"Habilidad '{{name}}' ya instalada (usa --force para reinstalar)",downloading:"Descargando habilidad '{{name}}' desde {{url}}",noSkillsDir:"No se encontr\xf3 el directorio de habilidades. Instala habilidades primero.",noSkillsInstalled:"No hay habilidades instaladas",installedList:"Habilidades instaladas ({{count}} total) en {{dir}}:",notInstalled:"Habilidad '{{name}}' no est\xe1 instalada",removed:"Habilidad '{{name}}' eliminada"},skillConvert:{welcome:"Sistema de conversi\xf3n de habilidades - Convertir habilidades exitosas en herramientas permanentes",listHeader:"An\xe1lisis de conversi\xf3n de habilidades ({{totalSkills}} habilidades, {{totalExecutions}} ejecuciones)",noSuggestions:"Ninguna habilidad alcanza el umbral de conversi\xf3n de {{threshold}}.",suggestedConversions:"Conversiones sugeridas:",convertHint:"Usa 'pithosai skill-convert convert <nombre-habilidad>' para convertir una habilidad.",skillNotFound:"Habilidad '{{skillName}}' no encontrada o no se puede leer: {{error}}",alreadyConverted:"La habilidad '{{skillName}}' ya ha sido convertida en herramienta.",useForceHint:"Usa --force para convertir de nuevo.",conversionReportHeader:"Informe de conversi\xf3n de '{{skillName}}':",conversionScore:"Puntuaci\xf3n de conversi\xf3n",suggestedType:"Tipo sugerido",ready:"Listo para conversi\xf3n",estimatedBenefits:"Beneficios estimados",performance:"Mejora de rendimiento",reliability:"Mejora de fiabilidad",usability:"Mejora de usabilidad",parameters:"Par\xe1metros",notReadyWarning:"Esta habilidad no est\xe1 lista para la conversi\xf3n autom\xe1tica.",moreUsageHint:"Usa la habilidad con m\xe1s frecuencia o usa --force para forzar la conversi\xf3n.",dryRunComplete:"Simulaci\xf3n completada. No se realizaron cambios.",confirmConversion:"\xbfConvertir '{{skillName}}' en herramienta permanente?",conversionCancelled:"Conversi\xf3n cancelada.",converting:"Convirtiendo '{{skillName}}' en herramienta...",conversionSuccess:"'{{skillName}}' convertido exitosamente en '{{toolName}}'.\nHerramienta guardada en: {{toolPath}}",usageExample:"Ejemplo de uso:",nextSteps:"Pr\xf3ximos pasos:",restartAgent:"Reinicia el agente para cargar la nueva herramienta",testTool:"Probar herramienta: <nombre-herramienta> --help",manageTools:"Gestionar herramientas: pithosai skill-convert tools",listError:"Error al listar habilidades: {{error}}",conversionError:"Error al convertir '{{skillName}}': {{error}}",skillStatsHeader:"Estad\xedsticas de '{{skillName}}':",generalStats:"Estad\xedsticas generales",totalExecutions:"Ejecuciones totales",successful:"Exitosas",failed:"Fallidas",avgTime:"Tiempo promedio de ejecuci\xf3n",lastUsed:"\xdaltimo uso",recentExecutions:"Ejecuciones recientes",commonParameters:"Par\xe1metros comunes",overallStatsHeader:"Estad\xedsticas generales de habilidades",overallStats:"Estad\xedsticas generales",totalSkillsTracked:"Total de habilidades rastreadas",avgSuccessRate:"Tasa de \xe9xito promedio",topSkills:"Habilidades m\xe1s usadas",conversionSuggestions:"Sugerencias de conversi\xf3n",statsError:"Error al obtener estad\xedsticas: {{error}}",confirmClearAll:"\xbfBorrar TODOS los registros de ejecuci\xf3n de habilidades? Esta acci\xf3n no se puede deshacer.",allRecordsCleared:"Todos los registros de ejecuci\xf3n de habilidades han sido borrados.",skillRecordsCleared:"Los registros de ejecuci\xf3n de '{{skillName}}' han sido borrados.",clearCancelled:"Operaci\xf3n de borrado cancelada.",specifySkillOrAll:"Especifica un nombre de habilidad o usa --all",clearError:"Error al borrar registros: {{error}}",noConvertedTools:"No se encontraron herramientas convertidas.",convertedToolsHeader:"Herramientas convertidas:",originalSkill:"Habilidad original",converted:"Convertido el",usageCount:"N\xfamero de usos",toolsError:"Error al gestionar herramientas: {{error}}",confirmRemoveTool:"\xbfEliminar herramienta '{{toolName}}'?",toolRemoved:"Herramienta '{{toolName}}' eliminada.",toolRemoveFailed:"Fallo al eliminar herramienta '{{toolName}}'.",removeCancelled:"Eliminaci\xf3n de herramienta cancelada.",toolEnabled:"Herramienta '{{toolName}}' habilitada.",toolEnableFailed:"Fallo al habilitar herramienta '{{toolName}}'.",toolDisabled:"Herramienta '{{toolName}}' deshabilitada.",toolDisableFailed:"Fallo al deshabilitar herramienta '{{toolName}}'.",noStatsForSkill:"No se encontraron estad\xedsticas para la habilidad '{{skillName}}'."},hooks:{description:"Gestionar hooks del agente para depuraci\xf3n, seguridad y monitoreo",list:{description:"Listar todos los hooks registrados",title:"\uD83D\uDCCB Hooks registrados",total:"Total: {{total}} manejadores",options:{verbose:"Mostrar informaci\xf3n detallada de los manejadores"},error:"Error al listar hooks: {{error}}"},debug:{description:"Habilitar hooks de depuraci\xf3n para monitorear el comportamiento del agente",options:{data:"Registrar datos completos en la salida de depuraci\xf3n",performance:"Habilitar hooks de monitoreo de rendimiento",stats:"Habilitar hooks de recopilaci\xf3n de estad\xedsticas",all:"Habilitar todos los hooks de depuraci\xf3n"},added:{debug:"Hooks de registro de depuraci\xf3n a\xf1adidos",performance:"Hooks de monitoreo de rendimiento a\xf1adidos",stats:"Hooks de recopilaci\xf3n de estad\xedsticas a\xf1adidos",basic:"Hooks de depuraci\xf3n b\xe1sicos a\xf1adidos"},success:"Hooks de depuraci\xf3n habilitados ({{count}} manejadores registrados)",error:"Error al habilitar hooks de depuraci\xf3n: {{error}}"},security:{description:"Habilitar hooks de seguridad para control de acceso y monitoreo",options:{block:"Lista de herramientas a bloquear separadas por comas",maxPrompt:"Longitud m\xe1xima permitida del prompt (por defecto: 10000)"},success:"Hooks de seguridad habilitados",blockedTools:"Herramientas bloqueadas: {{tools}}",maxPrompt:"Longitud m\xe1xima del prompt: {{length}} caracteres",error:"Error al habilitar hooks de seguridad: {{error}}"},clear:{description:"Eliminar todos los hooks registrados",success:"Todos los hooks eliminados",error:"Error al eliminar hooks: {{error}}"},test:{description:"Probar hooks dispar\xe1ndolos con datos de prueba",argument:{hookType:"Tipo de hook espec\xedfico a probar (opcional)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",triggered:"Hook disparado: {{type}}",result:"Resultado: {{result}}",allTriggered:"Todos los hooks disparados exitosamente",error:"Error al probar hooks: {{error}}"},register:{description:"Registrar un manejador de hook personalizado desde un archivo",argument:{hookType:"Tipo de hook para registrar el manejador",handlerFile:"Ruta al archivo del manejador (debe exportar una funci\xf3n por defecto)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",invalidHandler:"El archivo del manejador debe exportar una funci\xf3n por defecto",success:"Manejador para {{type}} registrado desde {{file}}",error:"Error al registrar hook: {{error}}"},status:{description:"Mostrar la configuraci\xf3n actual de hooks y estad\xedsticas",title:"\uD83D\uDCCB Estado de hooks",error:"Error al obtener el estado de hooks: {{error}}"}}}},1984(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Exigence de base",projectDir:"R\xe9pertoire du projet (travailler ici) : {{cwd}}",skillsInstruction:"Utilise l'outil read_skill pour charger les instructions compl\xe8tes d'une comp\xe9tence lorsque la t\xe2che correspond \xe0 sa description.",toolArgSizeLimit:"Ne d\xe9passez jamais {{maxChars}} caract\xe8res pour un seul argument d'appel d'outil (ex. le content d'un write). L'API peut tronquer au-del\xe0 et provoquer des erreurs \xab Unterminated string in JSON \xbb. Pour les longs fichiers ou scripts, divisez en plusieurs appels write (par fichier ou par bloc de moins de {{maxChars}} caract\xe8res).",toolCallJsonFormat:'Les arguments d\'appel d\'outil doivent \xeatre du JSON valide : chaque cl\xe9 et chaque valeur cha\xeene entre guillemets doubles. Exemple pour write : {"path": "fichier.md", "content": "contenu ici"}. N\'omettez pas les guillemets pour les cl\xe9s ou valeurs (ex. path: fichier.md est invalide).'},errors:{missingPromptFiles:"fichiers de prompt requis manquants dans {{dir}} :",runInit:"Ex\xe9cutez 'pithosai init' \xe0 la racine du projet pour cr\xe9er .pithosai avec les mod\xe8les.",noApiKey:"Cl\xe9 API introuvable. D\xe9finissez DEEPSEEK_API_KEY ou OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama n'est pas configur\xe9. D\xe9finissez OPENAI_LOCAL_API_BASE ou utilisez un projet avec mod\xe8le local.",noValidTemplateFiles:"aucun fichier de mod\xe8le valide dans {{dir}}. Attendu *-<lang>.md (ex. IDENTITY-ja.md). Ex\xe9cutez 'pithosai init' pour cr\xe9er .pithosai avec les mod\xe8les.",runTimeout:"Ex\xe9cution de l'agent expir\xe9e apr\xe8s {{seconds}} secondes. Utilisez --timeout <secondes> ou PITHOSAI_TIMEOUT_MS pour ajuster.",agentRunFailed:"\xc9chec de l'ex\xe9cution : {{message}}",unknownRunError:"Erreur inconnue"},warnings:{sessionAppend:"ajout de session : {{message}}",apiRetry:"Erreur API \xe0 la tentative {{attempt}}/{{max}} ; nouvel essai..."},reasoner:{thinkingHeader:"\n--- R\xe9flexion:\n",replyHeader:"\n\n--- R\xe9ponse:\n"},run:{cwd:"cwd {{cwd}}",request:"demande : {{request}}",interactivePrompt:"Vous : ",tuiYouLabel:"Vous :",interactiveExitHint:"R\xe9pondez ou saisissez une nouvelle demande (tapez 'exit' ou 'quit' pour quitter la CLI).",interactiveModeCwd:"CWD : {{cwd}}",interactiveModeAgentTitle:"--- Mode interactif — Agent (outils complets) ---",interactiveModeAgentTips:"- Jeu d’outils complet (lecture, \xe9criture, ex\xe9cution, selon la configuration).\n- Les tours sont stock\xe9s par t\xe2che dans la base locale.\n- `/new` attribue un nouvel id de t\xe2che ; les messages pr\xe9c\xe9dents ne sont pas charg\xe9s.\n- `/shell <commande>` pour le shell ; `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es.\n- `/list-skill`, `/install-skill` et `/remove-skill` \xe9quivalent \xe0 `pithosai skills list|install|remove` (ClawHub). Ctrl+S arr\xeate, Ctrl+P met en pause.",interactiveModeDialogTitle:"--- Mode interactif — Dialogue (Q&R en lecture seule) ---",interactiveModeDialogTips:"- R\xe9ponses avec outils en lecture seule uniquement (pas de shell, d’\xe9dition de fichiers ni d’ex\xe9cution de commandes).\n- Les tours sont stock\xe9s par t\xe2che dans la base locale.\n- `/new` attribue un nouvel id de t\xe2che ; les messages pr\xe9c\xe9dents ne sont pas charg\xe9s.\n- `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es.\n- `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub), comme la CLI `pithosai skills`.",interactiveModePlanTitle:"--- Mode plan ---",interactiveModePlanTips:"- Chaque r\xe9ponse est \xe9crite dans `<slug>-plan.md` \xe0 la racine du projet (la premi\xe8re ligne de la requ\xeate influence le nom).\n- Outils en lecture seule uniquement ; shell et outils modificateurs d\xe9sactiv\xe9s.\n- `/new` attribue un nouvel id de t\xe2che.\n- `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es.\n- `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub), comme la CLI `pithosai skills`.\n- Apr\xe8s chaque ex\xe9cution, vous pouvez saisir une nouvelle demande de plan au prompt (comme agent/dialog).",list:{noPersistedTasks:"Aucune t\xe2che enregistr\xe9e trouv\xe9e.",createTasksFirstHint:"Cr\xe9ez d'abord des t\xe2ches avec `pithosai task`.",persistedTasksHeader:"--- T\xe2ches enregistr\xe9es ({{count}}) ---",selectTaskHint:"Utilisez `/select <index>` pour ex\xe9cuter une t\xe2che.",noTasksCached:"Aucune t\xe2che en cache. Ex\xe9cutez `/list` d'abord.",invalidIndex:"Index invalide {{index}}. Plage valide : 0-{{maxIndex}}.",selectUsage:"Utilisation : /select <index>",selectedTask:"T\xe2che n\xb0{{index}} s\xe9lectionn\xe9e."},skillSlash:{installUsage:"Utilisation : /install-skill [--force] [nom-du-skill]",removeUsage:"Utilisation : /remove-skill <nom-du-skill>",listNoExtra:"/list-skill n’accepte pas d’arguments.",failed:"Commande skill en \xe9chec : {{message}}"},show:{title:"T\xe2che actuelle",field:"Champ",value:"Valeur",taskId:"taskId",mode:"mode",model:"mod\xe8le",status:"statut",messageCount:"nombreMessages",usageInput:"usage.entr\xe9e",usageOutput:"usage.sortie",usageCacheRead:"usage.cacheLecture",usageCacheWrite:"usage.cache\xc9criture",usageTotalTokens:"usage.totalTokens"},showTask:{title:"Q&R de la t\xe2che",taskIdLabel:"ID de t\xe2che",turnHeading:"Tour {{index}}",questionLabel:"Question",answerLabel:"R\xe9ponse",createdLabel:"Cr\xe9\xe9",emptyQuestion:"(question vide)",emptyAnswer:"(pas encore de r\xe9ponse texte de l’assistant)",emptyNoMessages:"Aucun message utilisateur pour cette t\xe2che pour l’instant.",previewDocumentTitle:"Q&R de la t\xe2che"},showPrompt:{previewDocumentTitle:"Invite syst\xe8me",previewHeading:"Invite syst\xe8me"},shellHint:"Utilisez '/shell <commande>' pour ex\xe9cuter des commandes shell (exemple: '/shell ls -la').",replIntroDialog:"Mode dialogue : outils en lecture seule uniquement — `/shell` est d\xe9sactiv\xe9. `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es. `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub).",replIntroPlan:"Mode plan : chaque r\xe9ponse est enregistr\xe9e dans `<slug>-plan.md` (la premi\xe8re ligne influence le nom). `/shell` est d\xe9sactiv\xe9 ; sortie minimale jusqu’\xe0 la fin. `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es. `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub).",newSessionHint:"Utilisez '/new <requ\xeate>' pour d\xe9marrer une nouvelle session (sans historique de chat).",newSessionNoHistory:"Utilisation d'une nouvelle session (sans historique de chat).",controlHint:"Appuyez sur Ctrl+S pour arr\xeater l'agent en cours, Ctrl+P pour mettre en pause et entrer des sous-commandes.",replTabCompletionHint:"Tab pour compl\xe9ter les commandes slash (ex. /list, /list-skill, /show) ou exit/quit.",tuiScrollTranscriptHint:"Dans l’interface terminal : molette, fl\xe8ches, Page pr\xe9c./suiv., Ctrl+U/Ctrl+F (page). Ctrl+U/F font d\xe9filer le journal. Ctrl+D reste EOF / quitter si ligne vide, suppression avant si saisie.",agentStopped:"Agent arr\xeat\xe9.",pauseHeader:"--- Agent en pause ---",pauseCurrentRequest:"Requ\xeate actuelle : {{request}}",pauseHelp:"Commandes : 'continue' ou 'c' pour reprendre, 'exit' ou 'e' pour quitter, ou tapez une nouvelle requ\xeate pour remplacer la requ\xeate actuelle.",pausePrompt:"[en pause] ",pauseRequestUpdated:"Requ\xeate mise \xe0 jour : {{request}}"},shell:{noCommand:"Aucune commande fournie apr\xe8s le pr\xe9fixe /shell. Utilisation: /shell <commande>",executionError:"Erreur lors de l'ex\xe9cution de la commande shell: {{error}}",executing:"[shell] Ex\xe9cution : {{command}}",errorNoCommand:"Aucune commande fournie apr\xe8s le pr\xe9fixe /shell.",errorSpawnFailed:"\xc9chec du d\xe9marrage du processus : {{message}}",errorTimedOut:"Commande expir\xe9e apr\xe8s {{seconds}} secondes",logFailed:"\xc9chec de la commande shell : {{command}} (code de sortie : {{code}})",logExecutionError:"Erreur d'ex\xe9cution de la commande shell : {{message}}",resultCommand:"Commande : {{command}}",resultExitCode:"Code de sortie : {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Succ\xe8s :",resultSuccessYes:"Oui",resultSuccessNo:"Non",resultOutput:"Sortie :",resultError:"Erreur :"},init:{invalidType:'--type invalide "{{value}}" ; choisir : {{choices}}',invalidLang:'--lang invalide "{{value}}" ; choisir : {{choices}}',templatesDirNotFound:"r\xe9pertoire des mod\xe8les introuvable : {{dir}}",createdPromptTemplates:"cr\xe9\xe9 {{dir}} (mod\xe8les de prompt)",createdSessions:"cr\xe9\xe9 {{dir}} (historique des sessions)",initialized:"projet {{type}} initialis\xe9 dans {{targetDir}}",promptFilesIn:"fichiers de prompt dans {{pithosaiDir}}, donn\xe9es de session dans {{sessionsDir}}",runHint:'ex\xe9cutez "pithosai -C {{targetDir}} \\"votre demande\\"" pour d\xe9marrer.',createdFile:"cr\xe9\xe9 {{path}}",roleAlreadyAdded:"r\xf4le {{role}} d\xe9j\xe0 pr\xe9sent dans .pithosai ; ignor\xe9.",addedRoleTemplates:"mod\xe8les de r\xf4le ajout\xe9s \xe0 {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown : aper\xe7u ferm\xe9 ({{source}})",skipped:"Aper\xe7u navigateur ignor\xe9 (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Indiquez exactement markdown ou path (pas les deux, pas aucun).",errorEmpty:"Le contenu Markdown est vide.",errorFileOutside:"path doit rester dans le r\xe9pertoire du projet.",errorNotAFile:"path n’est pas un fichier ordinaire.",errorFileTooLarge:"Le fichier d\xe9passe {{maxBytes}} octets.",errorFileRead:"Impossible de lire le fichier : {{message}}",sourceInline:"Markdown inline",sourceFile:"fichier {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"L'adresse e-mail ne doit pas \xeatre vide pour le heartbeat. Configurez l'e-mail du r\xf4le {{role}} dans la table email_roles de la base de donn\xe9es sqlite3.",loadedState:"\xc9tat du heartbeat charg\xe9 depuis SQLite pour l'e-mail {{email}} et le r\xf4le {{role}}, \xe9tats : {{states}}",fetchFound:"Le heartbeat a trouv\xe9 {{count}} nouvelles t\xe2ches dans la bo\xeete de r\xe9ception : {{ids}}",savedState:"\xc9tat du heartbeat enregistr\xe9 dans SQLite pour l'e-mail {{email}} et le r\xf4le {{role}}",mergedAndNext:"{{merged}} t\xe2ches fusionn\xe9es dans l'\xe9tat, prochaine \xe0 traiter : {{stateSummary}}",replyEmailFailed:"\xc9chec de l'envoi de l'e-mail de r\xe9ponse du heartbeat : {{error}}",taskFailed:"\xc9chec de la t\xe2che du heartbeat : {{error}}",failureReplyEmailFailed:"\xc9chec de l'envoi de l'e-mail de notification d'\xe9chec du heartbeat : {{error}}"},cli:{description:"Pithosai : impl\xe9mente du code ou des projets \xe0 partir d'une demande en langage naturel. Les invites de r\xf4le sont charg\xe9es depuis la base de donn\xe9es SQLite au moment de l'ex\xe9cution (avec repli optionnel vers .pithosai/<role>/*.md). Cr\xe9ez un projet avec 'pithosai init'.",versionOption:"afficher la version",roleOption:"r\xf4le (jeu de mod\xe8les pour init) ; mod\xe8les dans templates/<role>/",langOption:"langue des prompts et mod\xe8les init : en, zh (par d\xe9faut : en)",interactiveModeOption:"entrer en mode interactif sans demande ; afficher les conseils du mode et demander une saisie",initDescription:"Cr\xe9er un nouveau projet et la structure de r\xe9pertoire .pithosai/. Les invites de r\xf4le sont charg\xe9es depuis la base de donn\xe9es SQLite au moment de l'ex\xe9cution (avec repli optionnel vers .pithosai/<role>/*.md).",initTypeOption:"type de projet : js, ts ou python",initExamples:"\nExemples :\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Ajouter les mod\xe8les de r\xf4le \xe0 .pithosai/<role>/ dans le projet",addRoleArgument:"r\xf4le \xe0 ajouter (ex. PM, QA)",requestArgument:'quoi construire (ex. "Un CLI qui convertit CSV en JSON"). Si omis, afficher l\'aide.',cwdOption:"r\xe9pertoire du projet (par d\xe9faut : r\xe9pertoire courant)",skillsDirOption:"r\xe9pertoire des comp\xe9tences pour read_skill (par d\xe9faut : ./.pithosai/skills ou PITHOSAI_SKILLS_DIR)",reasonerOption:"utiliser le mod\xe8le DeepSeek Reasoner (r\xe9flexion) ; par d\xe9faut DeepSeek Coder",chatOption:"utiliser le mod\xe8le DeepSeek Chat (chat g\xe9n\xe9ral, pas de code) ; par d\xe9faut DeepSeek Coder",cursorOption:"utiliser le mod\xe8le Cursor CLI (auth via cursor-agent login, pas de cl\xe9 API n\xe9cessaire). Sp\xe9cifier optionnellement le mod\xe8le : auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"dur\xe9e max d'ex\xe9cution de l'agent en secondes (par d\xe9faut : 1800). Remplacer avec PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"d\xe9sactiver l'invite interactive (par d\xe9faut : apr\xe8s chaque r\xe9ponse, demander la suivante)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"G\xe9n\xe9ration du plan…",waitingReply:"En attente de r\xe9ponse…",runningReply:"En cours…",resultPreviewOpening:"Ouverture de l'aper\xe7u dans le navigateur…",resultPreviewTitle:"R\xe9sultat Pithosai",resultPreviewFailed:"Impossible d'ouvrir l'aper\xe7u : {{message}}",resultPreviewCopy:"Copier le Markdown",resultPreviewClose:"Fermer",resultPreviewCopied:"Copi\xe9 dans le presse-papiers",resultPreviewTerminalHint:"↑↓ ou j/k \xb7 PgUp/PgDn ou Ctrl+U/Ctrl+D \xb7 Home/End ou gg/G \xb7 q/\xc9chap fermer",runExamples:'\nExemples :\n pithosai "Ajouter un endpoint REST qui renvoie l\'heure actuelle"\n pithosai -C ./my-app "Ex\xe9cuter les tests et corriger les \xe9checs"\n pithosai -i # mode interactif : charger la derni\xe8re session puis demander des requ\xeates\n pithosai --no-interactive "Une fois" # une r\xe9ponse, sans demande de suite\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Utilisation :",helpArguments:"Arguments :",helpOptions:"Options :",helpCommands:"Commandes :",helpGlobalOptions:"Options globales :",helpOption:"afficher l'aide de la commande",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Surveiller le fichier de t\xe2ches et les traiter une par une dans le m\xeame processus",taskFileOption:"Chemin du fichier Markdown des t\xe2ches (d\xe9faut : prompts.md \xe0 la racine du projet)",taskModelOption:"Cl\xe9 de mod\xe8le pour la t\xe2che (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"D\xe9marrer avec une nouvelle session (pas d’historique de chat)",taskExamples:"\nExemples :\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"T\xe2che introuvable : {{taskId}}",taskAgentCompleted:"Agent termin\xe9.",taskAgentRunFailed:"\xc9chec de l’ex\xe9cution de l’agent.",taskDone:"Termin\xe9",taskFailed:"\xc9chec de la t\xe2che : {{message}}",taskProcessingHeader:"--- Traitement de la t\xe2che ---",taskLabelId:"id :",taskLabelTitle:"titre :",taskLabelStatus:"statut :",taskLabelDescription:"description :",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"D\xe9marrage du processeur pour la t\xe2che en cours {{id}} ({{title}}).",taskNoPending:"Aucune t\xe2che en attente.",taskPickedTask:"T\xe2che {{id}} ({{title}}) s\xe9lectionn\xe9e ; d\xe9marrage du processeur.",taskProcessorFailed:"\xc9chec du processeur de t\xe2ches : {{message}}",taskWatcherRunning:"Surveillance des t\xe2ches active. Ctrl+C pour arr\xeater.",memorizeDescription:"\xc9crit .pithosai/<role>/memory.md avec des r\xe9sum\xe9s des t\xe2ches auxquelles le r\xf4le a particip\xe9 (messages de t\xe2ches persist\xe9s sur la p\xe9riode).",memorizeStartOption:"D\xe9but de p\xe9riode : YYYY-MM-DD ou date-heure ISO",memorizeEndOption:"Fin de p\xe9riode : YYYY-MM-DD ou date-heure ISO",memorizeRoleRequired:"Le r\xf4le est obligatoire (-r/--role ou --role global).",memorizeWrote:"\xc9crit {{path}} ({{count}} t\xe2che(s)).",memorizeNoTasks:"Aucune t\xe2che sur la p\xe9riode pour le r\xf4le {{role}} ; en-t\xeate \xe9crit dans {{path}}.",memorizeDateError:"Plage de dates invalide : {{message}}",memorizeNoLlmOption:"Ignorer le r\xe9sum\xe9 LLM ; \xe9crire uniquement la m\xe9moire structur\xe9e (comme PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"\xc9chec du r\xe9sum\xe9 LLM ({{message}}) ; m\xe9moire structur\xe9e \xe9crite sans r\xe9sum\xe9.",memorizeExamples:"\nExemples :\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Obtenir les commandes shell pour une requ\xeate (Ollama uniquement)",argument:"Ce que vous voulez faire (ex. lister les gros fichiers du r\xe9pertoire courant)",loading:"R\xe9cup\xe9ration des commandes...",examples:'\nExemples :\n $ pithosai shell-tips lister les fichiers json du r\xe9pertoire courant\n $ pithosai shell-tips "remplacer foo par bar dans tous les .js"'},writer:{description:"G\xe9n\xe9rer du texte pour une requ\xeate (Ollama qwen2.5:14b)",argument:"Quoi \xe9crire (ex. court email pour d\xe9cliner une r\xe9union)",loading:"\xc9criture...",examples:'\nExemples :\n $ pithosai writer court email pour d\xe9cliner une r\xe9union\n $ pithosai writer "trois points pour un kickoff projet"'},skills:{installing:"Installation des comp\xe9tences dans {{dir}}",fetchingList:"R\xe9cup\xe9ration des comp\xe9tences disponibles depuis ClawHub...",fetchingIndex:"R\xe9cup\xe9ration de l'index des comp\xe9tences depuis {{url}}",notFound:"Comp\xe9tence '{{name}}' non trouv\xe9e",noSkillsAvailable:"Aucune comp\xe9tence disponible depuis ClawHub",noSkillsFound:"Aucune comp\xe9tence trouv\xe9e",downloadFailed:"\xc9chec du t\xe9l\xe9chargement de la comp\xe9tence '{{name}}' : {{error}}",installed:"Comp\xe9tence '{{name}}' install\xe9e",complete:"Installation termin\xe9e : {{count}} sur {{total}} comp\xe9tences install\xe9es",alreadyInstalled:"Comp\xe9tence '{{name}}' d\xe9j\xe0 install\xe9e (utilisez --force pour r\xe9installer)",downloading:"T\xe9l\xe9chargement de la comp\xe9tence '{{name}}' depuis {{url}}",noSkillsDir:"Aucun r\xe9pertoire de comp\xe9tences trouv\xe9. Installez d'abord des comp\xe9tences.",noSkillsInstalled:"Aucune comp\xe9tence install\xe9e",installedList:"Comp\xe9tences install\xe9es ({{count}} au total) dans {{dir}} :",notInstalled:"Comp\xe9tence '{{name}}' n'est pas install\xe9e",removed:"Comp\xe9tence '{{name}}' supprim\xe9e"},skillConvert:{welcome:"Syst\xe8me de conversion de comp\xe9tences - Convertir les comp\xe9tences r\xe9ussies en outils permanents",listHeader:"Analyse de conversion de comp\xe9tences ({{totalSkills}} comp\xe9tences, {{totalExecutions}} ex\xe9cutions)",noSuggestions:"Aucune comp\xe9tence n'atteint le seuil de conversion de {{threshold}}.",suggestedConversions:"Conversions sugg\xe9r\xe9es :",convertHint:"Utilisez 'pithosai skill-convert convert <nom-comp\xe9tence>' pour convertir une comp\xe9tence.",skillNotFound:"Comp\xe9tence '{{skillName}}' introuvable ou illisible : {{error}}",alreadyConverted:"La comp\xe9tence '{{skillName}}' a d\xe9j\xe0 \xe9t\xe9 convertie en outil.",useForceHint:"Utilisez --force pour convertir \xe0 nouveau.",conversionReportHeader:"Rapport de conversion de '{{skillName}}' :",conversionScore:"Score de conversion",suggestedType:"Type sugg\xe9r\xe9",ready:"Pr\xeat pour la conversion",estimatedBenefits:"B\xe9n\xe9fices estim\xe9s",performance:"Am\xe9lioration des performances",reliability:"Am\xe9lioration de la fiabilit\xe9",usability:"Am\xe9lioration de l'utilisabilit\xe9",parameters:"Param\xe8tres",notReadyWarning:"Cette comp\xe9tence n'est pas pr\xeate pour la conversion automatique.",moreUsageHint:"Utilisez la comp\xe9tence plus fr\xe9quemment ou utilisez --force pour forcer la conversion.",dryRunComplete:"Simulation termin\xe9e. Aucune modification effectu\xe9e.",confirmConversion:"Convertir '{{skillName}}' en outil permanent ?",conversionCancelled:"Conversion annul\xe9e.",converting:"Conversion de '{{skillName}}' en outil...",conversionSuccess:"'{{skillName}}' converti avec succ\xe8s en '{{toolName}}'.\nOutil enregistr\xe9 dans : {{toolPath}}",usageExample:"Exemple d'utilisation :",nextSteps:"\xc9tapes suivantes :",restartAgent:"Red\xe9marrez l'agent pour charger le nouvel outil",testTool:"Tester l'outil : <nom-outil> --help",manageTools:"G\xe9rer les outils : pithosai skill-convert tools",listError:"Erreur lors de la liste des comp\xe9tences : {{error}}",conversionError:"Erreur lors de la conversion de '{{skillName}}' : {{error}}",skillStatsHeader:"Statistiques de '{{skillName}}' :",generalStats:"Statistiques g\xe9n\xe9rales",totalExecutions:"Ex\xe9cutions totales",successful:"R\xe9ussies",failed:"\xc9chou\xe9es",avgTime:"Temps d'ex\xe9cution moyen",lastUsed:"Derni\xe8re utilisation",recentExecutions:"Ex\xe9cutions r\xe9centes",commonParameters:"Param\xe8tres courants",overallStatsHeader:"Statistiques globales des comp\xe9tences",overallStats:"Statistiques globales",totalSkillsTracked:"Comp\xe9tences suivies au total",avgSuccessRate:"Taux de r\xe9ussite moyen",topSkills:"Comp\xe9tences les plus utilis\xe9es",conversionSuggestions:"Suggestions de conversion",statsError:"Erreur lors de l'obtention des statistiques : {{error}}",confirmClearAll:"Effacer TOUS les enregistrements d'ex\xe9cution de comp\xe9tences ? Cette action est irr\xe9versible.",allRecordsCleared:"Tous les enregistrements d'ex\xe9cution de comp\xe9tences ont \xe9t\xe9 effac\xe9s.",skillRecordsCleared:"Les enregistrements d'ex\xe9cution de '{{skillName}}' ont \xe9t\xe9 effac\xe9s.",clearCancelled:"Op\xe9ration d'effacement annul\xe9e.",specifySkillOrAll:"Veuillez sp\xe9cifier un nom de comp\xe9tence ou utiliser --all",clearError:"Erreur lors de l'effacement des enregistrements : {{error}}",noConvertedTools:"Aucun outil converti trouv\xe9.",convertedToolsHeader:"Outils convertis :",originalSkill:"Comp\xe9tence d'origine",converted:"Converti le",usageCount:"Nombre d'utilisations",toolsError:"Erreur lors de la gestion des outils : {{error}}",confirmRemoveTool:"Supprimer l'outil '{{toolName}}' ?",toolRemoved:"Outil '{{toolName}}' supprim\xe9.",toolRemoveFailed:"\xc9chec de la suppression de l'outil '{{toolName}}'.",removeCancelled:"Suppression de l'outil annul\xe9e.",toolEnabled:"Outil '{{toolName}}' activ\xe9.",toolEnableFailed:"\xc9chec de l'activation de l'outil '{{toolName}}'.",toolDisabled:"Outil '{{toolName}}' d\xe9sactiv\xe9.",toolDisableFailed:"\xc9chec de la d\xe9sactivation de l'outil '{{toolName}}'.",noStatsForSkill:"Aucune statistique trouv\xe9e pour la comp\xe9tence '{{skillName}}'."},hooks:{description:"G\xe9rer les hooks d'agent pour le d\xe9bogage, la s\xe9curit\xe9 et la surveillance",list:{description:"Lister tous les hooks enregistr\xe9s",title:"\uD83D\uDCCB Hooks enregistr\xe9s",total:"Total : {{total}} gestionnaires",options:{verbose:"Afficher les informations d\xe9taill\xe9es des gestionnaires"},error:"Impossible de lister les hooks : {{error}}"},debug:{description:"Activer les hooks de d\xe9bogage pour surveiller le comportement de l'agent",options:{data:"Journaliser les donn\xe9es compl\xe8tes dans la sortie de d\xe9bogage",performance:"Activer les hooks de surveillance des performances",stats:"Activer les hooks de collecte de statistiques",all:"Activer tous les hooks de d\xe9bogage"},added:{debug:"Hooks de journalisation de d\xe9bogage ajout\xe9s",performance:"Hooks de surveillance des performances ajout\xe9s",stats:"Hooks de collecte de statistiques ajout\xe9s",basic:"Hooks de d\xe9bogage de base ajout\xe9s"},success:"Hooks de d\xe9bogage activ\xe9s ({{count}} gestionnaires enregistr\xe9s)",error:"Impossible d'activer les hooks de d\xe9bogage : {{error}}"},security:{description:"Activer les hooks de s\xe9curit\xe9 pour le contr\xf4le d'acc\xe8s et la surveillance",options:{block:"Liste d'outils \xe0 bloquer s\xe9par\xe9s par des virgules",maxPrompt:"Longueur maximale autoris\xe9e du prompt (par d\xe9faut : 10000)"},success:"Hooks de s\xe9curit\xe9 activ\xe9s",blockedTools:"Outils bloqu\xe9s : {{tools}}",maxPrompt:"Longueur maximale du prompt : {{length}} caract\xe8res",error:"Impossible d'activer les hooks de s\xe9curit\xe9 : {{error}}"},clear:{description:"Effacer tous les hooks enregistr\xe9s",success:"Tous les hooks effac\xe9s",error:"Impossible d'effacer les hooks : {{error}}"},test:{description:"Tester les hooks en les d\xe9clenchant avec des donn\xe9es de test",argument:{hookType:"Type de hook sp\xe9cifique \xe0 tester (optionnel)"},invalidType:"Type de hook invalide : {{type}}",triggered:"Hook d\xe9clench\xe9 : {{type}}",result:"R\xe9sultat : {{result}}",allTriggered:"Tous les hooks d\xe9clench\xe9s avec succ\xe8s",error:"Impossible de tester les hooks : {{error}}"},register:{description:"Enregistrer un gestionnaire de hook personnalis\xe9 depuis un fichier",argument:{hookType:"Type de hook pour lequel enregistrer le gestionnaire",handlerFile:"Chemin vers le fichier du gestionnaire (doit exporter une fonction par d\xe9faut)"},invalidType:"Type de hook invalide : {{type}}",invalidHandler:"Le fichier du gestionnaire doit exporter une fonction par d\xe9faut",success:"Gestionnaire pour {{type}} enregistr\xe9 depuis {{file}}",error:"Impossible d'enregistrer le hook : {{error}}"},status:{description:"Afficher la configuration actuelle des hooks et les statistiques",title:"\uD83D\uDCCB Statut des hooks",error:"Impossible d'obtenir le statut des hooks : {{error}}"}}}},7493(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Requisito di base",projectDir:"Directory del progetto (lavora qui): {{cwd}}",skillsInstruction:"Usa lo strumento read_skill per caricare le istruzioni complete di un'abilit\xe0 quando il compito corrisponde alla sua descrizione.",toolArgSizeLimit:"Non superare mai {{maxChars}} caratteri in un singolo argomento di chiamata a strumento (es. il content di un write). L'API pu\xf2 troncare payload pi\xf9 grandi e causare errori \xabUnterminated string in JSON\xbb. Per file o script lunghi, suddividi in pi\xf9 chiamate write (per file o per blocco sotto {{maxChars}} caratteri).",toolCallJsonFormat:'Gli argomenti di chiamata a strumento devono essere JSON valido: ogni chiave e ogni valore stringa tra virgolette doppie. Esempio per write: {"path": "file.md", "content": "contenuto qui"}. Non omettere le virgolette per chiavi o valori (es. path: file.md \xe8 invalido).'},errors:{missingPromptFiles:"file di prompt richiesti mancanti in {{dir}}:",runInit:"Esegui 'pithosai init' nella root del progetto per creare .pithosai con i modelli.",noApiKey:"Chiave API non trovata. Imposta DEEPSEEK_API_KEY o OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama non configurato. Imposta OPENAI_LOCAL_API_BASE o usa un progetto con modello locale.",noValidTemplateFiles:"nessun file di modello valido in {{dir}}. Atteso *-<lang>.md (es. IDENTITY-ja.md). Esegui 'pithosai init' per creare .pithosai con i modelli.",runTimeout:"Esecuzione dell'agente scaduta dopo {{seconds}} secondi. Usa --timeout <secondi> o PITHOSAI_TIMEOUT_MS per modificare.",agentRunFailed:"Esecuzione non riuscita: {{message}}",unknownRunError:"Errore sconosciuto"},warnings:{sessionAppend:"append sessione: {{message}}",apiRetry:"Errore API al tentativo {{attempt}}/{{max}}; riprovo..."},reasoner:{thinkingHeader:"\n--- Pensiero:\n",replyHeader:"\n\n--- Risposta:\n"},run:{cwd:"cwd {{cwd}}",request:"richiesta: {{request}}",interactivePrompt:"Tu: ",tuiYouLabel:"Tu:",interactiveExitHint:"Rispondi o inserisci una nuova richiesta (digita 'exit' o 'quit' per uscire dalla CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Modalit\xe0 interattiva — Agent (strumenti completi) ---",interactiveModeAgentTips:"- Strumenti completi (lettura, scrittura, esecuzione, secondo configurazione).\n- I turni sono salvati per attivit\xe0 nel database locale.\n- `/new` assegna un nuovo id attivit\xe0; i messaggi precedenti non vengono caricati.\n- `/shell <comando>` per la shell; `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite.\n- `/list-skill`, `/install-skill` e `/remove-skill` equivalgono a `pithosai skills list|install|remove` (ClawHub). Ctrl+S arresta, Ctrl+P mette in pausa.",interactiveModeDialogTitle:"--- Modalit\xe0 interattiva — Dialogo (Q&A in sola lettura) ---",interactiveModeDialogTips:"- Solo strumenti in sola lettura (niente shell, modifiche ai file o esecuzione comandi).\n- I turni sono salvati per attivit\xe0 nel database locale.\n- `/new` assegna un nuovo id attivit\xe0; i messaggi precedenti non vengono caricati.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite.\n- `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub) come la CLI `pithosai skills`.",interactiveModePlanTitle:"--- Modalit\xe0 piano ---",interactiveModePlanTips:"- Ogni risposta viene scritta in `<slug>-plan.md` nella directory del progetto (la prima riga della richiesta influenza il nome).\n- Solo strumenti in sola lettura; shell e strumenti mutanti disattivati.\n- `/new` assegna un nuovo id attivit\xe0.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite.\n- `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub) come la CLI `pithosai skills`.\n- Dopo ogni esecuzione puoi inserire un’altra richiesta di piano al prompt (come agent/dialog).",list:{noPersistedTasks:"Nessuna attivit\xe0 salvata trovata.",createTasksFirstHint:"Crea prima le attivit\xe0 usando `pithosai task`.",persistedTasksHeader:"--- Attivit\xe0 salvate ({{count}}) ---",selectTaskHint:"Usa `/select <index>` per eseguire un'attivit\xe0.",noTasksCached:"Nessuna attivit\xe0 in cache. Esegui `/list` prima.",invalidIndex:"Indice non valido {{index}}. Intervallo valido: 0-{{maxIndex}}.",selectUsage:"Uso: /select <index>",selectedTask:"Attivit\xe0 #{{index}} selezionata."},skillSlash:{installUsage:"Uso: /install-skill [--force] [nome-skill]",removeUsage:"Uso: /remove-skill <nome-skill>",listNoExtra:"/list-skill non accetta argomenti.",failed:"Comando skill non riuscito: {{message}}"},show:{title:"Attivit\xe0 corrente",field:"Campo",value:"Valore",taskId:"taskId",mode:"modalit\xe0",model:"modello",status:"stato",messageCount:"conteggioMessaggi",usageInput:"utilizzo.input",usageOutput:"utilizzo.output",usageCacheRead:"utilizzo.cacheLettura",usageCacheWrite:"utilizzo.cacheScrittura",usageTotalTokens:"utilizzo.tokenTotali"},showTask:{title:"Q&A attivit\xe0",taskIdLabel:"ID attivit\xe0",turnHeading:"Turno {{index}}",questionLabel:"Domanda",answerLabel:"Risposta",createdLabel:"Creato",emptyQuestion:"(domanda vuota)",emptyAnswer:"(nessuna risposta testuale dell’assistente)",emptyNoMessages:"Nessun messaggio utente per questa attivit\xe0.",previewDocumentTitle:"Q&A attivit\xe0"},showPrompt:{previewDocumentTitle:"Prompt di sistema",previewHeading:"Prompt di sistema"},shellHint:"Usa '/shell <comando>' per eseguire comandi shell (esempio: '/shell ls -la').",replIntroDialog:"Modalit\xe0 dialogo: solo strumenti in sola lettura — `/shell` disattivato. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite. `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub).",replIntroPlan:"Modalit\xe0 piano: ogni risposta in `<slug>-plan.md` (prima riga influenza il nome). `/shell` disattivato; output minimo fino al completamento. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite. `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub).",newSessionHint:"Usa '/new <richiesta>' per avviare una nuova sessione (senza cronologia chat).",newSessionNoHistory:"Uso nuova sessione (senza cronologia chat).",controlHint:"Premi Ctrl+S per fermare l'agente in esecuzione, Ctrl+P per mettere in pausa e inserire sottocomandi.",replTabCompletionHint:"Tab per completare i comandi con slash (es. /list, /list-skill, /show) o exit/quit.",tuiScrollTranscriptHint:"Nell’UI terminale: rotella, frecce, PagSu/PagGi\xf9, Ctrl+U/Ctrl+F (pagina). Ctrl+U/F scorrono il registro. Ctrl+D resta EOF/uscita a riga vuota o elimina avanti durante la digitazione.",agentStopped:"Agente fermato.",pauseHeader:"--- Agente in pausa ---",pauseCurrentRequest:"Richiesta attuale: {{request}}",pauseHelp:"Comandi: 'continue' o 'c' per riprendere, 'exit' o 'e' per uscire, oppure digita una nuova richiesta per sostituire quella attuale.",pausePrompt:"[in pausa] ",pauseRequestUpdated:"Richiesta aggiornata a: {{request}}"},shell:{noCommand:"Nessun comando fornito dopo il prefisso /shell. Utilizzo: /shell <comando>",executionError:"Errore durante l'esecuzione del comando shell: {{error}}",executing:"[shell] Esecuzione: {{command}}",errorNoCommand:"Nessun comando fornito dopo il prefisso /shell.",errorSpawnFailed:"Avvio del processo non riuscito: {{message}}",errorTimedOut:"Comando scaduto dopo {{seconds}} secondi",logFailed:"Comando shell fallito: {{command}} (codice di uscita: {{code}})",logExecutionError:"Errore di esecuzione comando shell: {{message}}",resultCommand:"Comando: {{command}}",resultExitCode:"Codice di uscita: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Successo:",resultSuccessYes:"S\xec",resultSuccessNo:"No",resultOutput:"Output:",resultError:"Errore:"},init:{invalidType:'--type non valido "{{value}}"; scegli: {{choices}}',invalidLang:'--lang non valido "{{value}}"; scegli: {{choices}}',templatesDirNotFound:"directory modelli non trovata: {{dir}}",createdPromptTemplates:"creato {{dir}} (modelli di prompt)",createdSessions:"creato {{dir}} (cronologia sessioni)",initialized:"progetto {{type}} inizializzato in {{targetDir}}",promptFilesIn:"file di prompt in {{pithosaiDir}}, dati sessione in {{sessionsDir}}",runHint:'esegui "pithosai -C {{targetDir}} \\"tua richiesta\\"" per iniziare.',createdFile:"creato {{path}}",roleAlreadyAdded:"ruolo {{role}} gi\xe0 presente in .pithosai; ignorato.",addedRoleTemplates:"modelli di ruolo aggiunti a {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: anteprima chiusa ({{source}})",skipped:"Anteprima browser saltata (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Fornisci esattamente markdown o path (non entrambi, non nessuno).",errorEmpty:"Il contenuto Markdown \xe8 vuoto.",errorFileOutside:"path deve restare nella directory del progetto.",errorNotAFile:"path non \xe8 un file normale.",errorFileTooLarge:"Il file supera {{maxBytes}} byte.",errorFileRead:"Impossibile leggere il file: {{message}}",sourceInline:"Markdown inline",sourceFile:"file {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"L'e-mail non pu\xf2 essere vuoto per il heartbeat. Configura l'e-mail del ruolo {{role}} nella tabella email_roles nel database sqlite3.",loadedState:"Stato del heartbeat caricato da SQLite per e-mail {{email}} e ruolo {{role}}, stati: {{states}}",fetchFound:"Il heartbeat ha trovato {{count}} nuovi task nella inbox: {{ids}}",savedState:"Stato del heartbeat salvato in SQLite per e-mail {{email}} e ruolo {{role}}",mergedAndNext:"Uniti {{merged}} task nello stato, prossimo da elaborare: {{stateSummary}}",replyEmailFailed:"Invio e-mail di risposta del heartbeat fallito: {{error}}",taskFailed:"Task del heartbeat fallito: {{error}}",failureReplyEmailFailed:"Invio e-mail di notifica fallimento del heartbeat fallito: {{error}}"},cli:{description:"Pithosai: implementa codice o progetti da una richiesta in linguaggio naturale. I prompt di ruolo vengono caricati dal database SQLite in fase di esecuzione (con fallback opzionale su .pithosai/<role>/*.md). Crea un progetto con 'pithosai init'.",versionOption:"mostra versione",roleOption:"ruolo (set di modelli per init); modelli in templates/<role>/",langOption:"lingua per prompt e modelli init: en, zh (predefinito: en)",interactiveModeOption:"entrare in modalit\xe0 interattiva senza richiesta; mostrare i suggerimenti della modalit\xe0 e chiedere input",initDescription:"Crea un nuovo progetto e la struttura della directory .pithosai/. I prompt di ruolo vengono caricati dal database SQLite in fase di esecuzione (con fallback opzionale su .pithosai/<role>/*.md).",initTypeOption:"tipo di progetto: js, ts o python",initExamples:"\nEsempi:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Aggiungi modelli di ruolo a .pithosai/<role>/ nel progetto",addRoleArgument:"ruolo da aggiungere (es. PM, QA)",requestArgument:'cosa costruire (es. "Un CLI che converte CSV in JSON"). Se omesso, mostra aiuto.',cwdOption:"directory del progetto (predefinito: directory corrente)",skillsDirOption:"directory abilit\xe0 per read_skill (predefinito: ./.pithosai/skills o PITHOSAI_SKILLS_DIR)",reasonerOption:"usa il modello DeepSeek Reasoner (ragionamento); predefinito DeepSeek Coder",chatOption:"usa il modello DeepSeek Chat (chat generale, non codice); predefinito DeepSeek Coder",cursorOption:"usa il modello Cursor CLI (autenticazione via cursor-agent login, nessuna chiave API necessaria). Specifica opzionalmente il modello: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"tempo max esecuzione agente in secondi (predefinito: 1800). Sovrascrivi con PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"disattiva prompt interattivo (predefinito: dopo ogni risposta chiedi la successiva)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Generazione del piano…",waitingReply:"In attesa di risposta…",runningReply:"In esecuzione…",resultPreviewOpening:"Apertura anteprima del risultato nel browser…",resultPreviewTitle:"Risultato Pithosai",resultPreviewFailed:"Impossibile aprire l'anteprima: {{message}}",resultPreviewCopy:"Copia Markdown",resultPreviewClose:"Chiudi",resultPreviewCopied:"Copiato negli appunti",resultPreviewTerminalHint:"↑↓ o j/k \xb7 PgUp/PgDn o Ctrl+U/Ctrl+D \xb7 Home/End o gg/G \xb7 q/Esc chiudi",runExamples:'\nEsempi:\n pithosai "Aggiungi un endpoint REST che restituisce l\'ora corrente"\n pithosai -C ./my-app "Esegui i test e correggi i fallimenti"\n pithosai -i # modalit\xe0 interattiva: carica ultima sessione poi chiedi richieste\n pithosai --no-interactive "Una volta" # una risposta, senza richiesta di seguito\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Uso:",helpArguments:"Argomenti:",helpOptions:"Opzioni:",helpCommands:"Comandi:",helpGlobalOptions:"Opzioni globali:",helpOption:"mostra aiuto per il comando",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Monitora il file delle attivit\xe0 e le elabora una alla volta nello stesso processo",taskFileOption:"Percorso del Markdown delle attivit\xe0 (predefinito: prompts.md nella root del progetto)",taskModelOption:"Chiave modello per l’attivit\xe0 (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Inizia con una nuova sessione (nessuna cronologia chat)",taskExamples:"\nEsempi:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Attivit\xe0 non trovata: {{taskId}}",taskAgentCompleted:"Agente completato.",taskAgentRunFailed:"Esecuzione agente non riuscita.",taskDone:"Fatto",taskFailed:"Attivit\xe0 non riuscita: {{message}}",taskProcessingHeader:"--- Elaborazione attivit\xe0 ---",taskLabelId:"id:",taskLabelTitle:"titolo:",taskLabelStatus:"stato:",taskLabelDescription:"descrizione:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Avvio processore per l’attivit\xe0 in elaborazione {{id}} ({{title}}).",taskNoPending:"Nessuna attivit\xe0 in sospeso.",taskPickedTask:"Attivit\xe0 {{id}} ({{title}}) selezionata; avvio processore.",taskProcessorFailed:"Processore attivit\xe0 non riuscito: {{message}}",taskWatcherRunning:"Monitor attivit\xe0 in esecuzione. Ctrl+C per uscire.",memorizeDescription:"Scrive .pithosai/<role>/memory.md con riepiloghi delle attivit\xe0 a cui il ruolo ha partecipato (messaggi attivit\xe0 persistiti nell’intervallo).",memorizeStartOption:"Inizio intervallo: YYYY-MM-DD o data/ora ISO",memorizeEndOption:"Fine intervallo: YYYY-MM-DD o data/ora ISO",memorizeRoleRequired:"Il ruolo \xe8 obbligatorio (-r/--role o --role globale).",memorizeWrote:"Scritto {{path}} ({{count}} attivit\xe0).",memorizeNoTasks:"Nessuna attivit\xe0 nell’intervallo per il ruolo {{role}}; intestazione in {{path}}.",memorizeDateError:"Intervallo date non valido: {{message}}",memorizeNoLlmOption:"Salta il riepilogo LLM; scrivi solo memoria strutturata (come PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"Riepilogo LLM non riuscito ({{message}}); scritta memoria strutturata senza riepilogo.",memorizeExamples:"\nEsempi:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Ottieni comandi shell per una richiesta (solo Ollama)",argument:"Cosa vuoi fare (es. elencare file grandi nella directory corrente)",loading:"Recupero comandi...",examples:'\nEsempi:\n $ pithosai shell-tips elenca file json nella directory corrente\n $ pithosai shell-tips "cerca e sostituisci foo con bar in tutti i .js"'},writer:{description:"Genera testo per una richiesta (Ollama qwen2.5:14b)",argument:"Cosa scrivere (es. breve email per declinare un meeting)",loading:"Scrittura...",examples:'\nEsempi:\n $ pithosai writer breve email per declinare un meeting\n $ pithosai writer "tre punti per un kickoff di progetto"'},skills:{installing:"Installazione delle abilit\xe0 in {{dir}}",fetchingList:"Recupero delle abilit\xe0 disponibili da ClawHub...",fetchingIndex:"Recupero dell'indice delle abilit\xe0 da {{url}}",notFound:"Abilit\xe0 '{{name}}' non trovata",noSkillsAvailable:"Nessuna abilit\xe0 disponibile da ClawHub",noSkillsFound:"Nessuna abilit\xe0 trovata",downloadFailed:"Download dell'abilit\xe0 '{{name}}' fallito: {{error}}",installed:"Abilit\xe0 '{{name}}' installata",complete:"Installazione completata: {{count}} di {{total}} abilit\xe0 installate",alreadyInstalled:"Abilit\xe0 '{{name}}' gi\xe0 installata (usa --force per reinstallare)",downloading:"Download dell'abilit\xe0 '{{name}}' da {{url}}",noSkillsDir:"Nessuna directory delle abilit\xe0 trovata. Installa prima le abilit\xe0.",noSkillsInstalled:"Nessuna abilit\xe0 installata",installedList:"Abilit\xe0 installate ({{count}} totali) in {{dir}}:",notInstalled:"Abilit\xe0 '{{name}}' non \xe8 installata",removed:"Abilit\xe0 '{{name}}' rimossa"},skillConvert:{welcome:"Sistema di conversione abilit\xe0 - Converti abilit\xe0 di successo in strumenti permanenti",listHeader:"Analisi conversione abilit\xe0 ({{totalSkills}} abilit\xe0, {{totalExecutions}} esecuzioni)",noSuggestions:"Nessuna abilit\xe0 raggiunge la soglia di conversione di {{threshold}}.",suggestedConversions:"Conversioni suggerite:",convertHint:"Usa 'pithosai skill-convert convert <nome-abilit\xe0>' per convertire un'abilit\xe0.",skillNotFound:"Abilit\xe0 '{{skillName}}' non trovata o non leggibile: {{error}}",alreadyConverted:"L'abilit\xe0 '{{skillName}}' \xe8 gi\xe0 stata convertita in strumento.",useForceHint:"Usa --force per convertire di nuovo.",conversionReportHeader:"Report di conversione di '{{skillName}}':",conversionScore:"Punteggio di conversione",suggestedType:"Tipo suggerito",ready:"Pronto per la conversione",estimatedBenefits:"Benefici stimati",performance:"Miglioramento prestazioni",reliability:"Miglioramento affidabilit\xe0",usability:"Miglioramento usabilit\xe0",parameters:"Parametri",notReadyWarning:"Questa abilit\xe0 non \xe8 pronta per la conversione automatica.",moreUsageHint:"Usa l'abilit\xe0 pi\xf9 frequentemente o usa --force per forzare la conversione.",dryRunComplete:"Esecuzione di prova completata. Nessuna modifica effettuata.",confirmConversion:"Convertire '{{skillName}}' in strumento permanente?",conversionCancelled:"Conversione annullata.",converting:"Conversione di '{{skillName}}' in strumento...",conversionSuccess:"'{{skillName}}' convertito con successo in '{{toolName}}'.\nStrumento salvato in: {{toolPath}}",usageExample:"Esempio di utilizzo:",nextSteps:"Prossimi passi:",restartAgent:"Riavvia l'agente per caricare il nuovo strumento",testTool:"Testa strumento: <nome-strumento> --help",manageTools:"Gestisci strumenti: pithosai skill-convert tools",listError:"Errore nell'elencare le abilit\xe0: {{error}}",conversionError:"Errore nella conversione di '{{skillName}}': {{error}}",skillStatsHeader:"Statistiche di '{{skillName}}':",generalStats:"Statistiche generali",totalExecutions:"Esecuzioni totali",successful:"Riuscite",failed:"Fallite",avgTime:"Tempo medio di esecuzione",lastUsed:"Ultimo utilizzo",recentExecutions:"Esecuzioni recenti",commonParameters:"Parametri comuni",overallStatsHeader:"Statistiche generali delle abilit\xe0",overallStats:"Statistiche generali",totalSkillsTracked:"Abilit\xe0 tracciate totali",avgSuccessRate:"Tasso di successo medio",topSkills:"Abilit\xe0 pi\xf9 utilizzate",conversionSuggestions:"Suggerimenti di conversione",statsError:"Errore nell'ottenere le statistiche: {{error}}",confirmClearAll:"Cancellare TUTTI i record di esecuzione delle abilit\xe0? Questa azione \xe8 irreversibile.",allRecordsCleared:"Tutti i record di esecuzione delle abilit\xe0 sono stati cancellati.",skillRecordsCleared:"I record di esecuzione di '{{skillName}}' sono stati cancellati.",clearCancelled:"Operazione di cancellazione annullata.",specifySkillOrAll:"Specifica un nome di abilit\xe0 o usa --all",clearError:"Errore nella cancellazione dei record: {{error}}",noConvertedTools:"Nessuno strumento convertito trovato.",convertedToolsHeader:"Strumenti convertiti:",originalSkill:"Abilit\xe0 originale",converted:"Convertito il",usageCount:"Conteggio utilizzi",toolsError:"Errore nella gestione degli strumenti: {{error}}",confirmRemoveTool:"Rimuovere lo strumento '{{toolName}}'?",toolRemoved:"Strumento '{{toolName}}' rimosso.",toolRemoveFailed:"Rimozione dello strumento '{{toolName}}' fallita.",removeCancelled:"Rimozione strumento annullata.",toolEnabled:"Strumento '{{toolName}}' abilitato.",toolEnableFailed:"Abilitazione dello strumento '{{toolName}}' fallita.",toolDisabled:"Strumento '{{toolName}}' disabilitato.",toolDisableFailed:"Disabilitazione dello strumento '{{toolName}}' fallita.",noStatsForSkill:"Nessuna statistica trovata per l'abilit\xe0 '{{skillName}}'."},hooks:{description:"Gestire gli hook dell'agente per debug, sicurezza e monitoraggio",list:{description:"Elencare tutti gli hook registrati",title:"\uD83D\uDCCB Hook registrati",total:"Totale: {{total}} gestori",options:{verbose:"Mostrare informazioni dettagliate sui gestori"},error:"Impossibile elencare gli hook: {{error}}"},debug:{description:"Abilitare gli hook di debug per monitorare il comportamento dell'agente",options:{data:"Registrare i dati completi nell'output di debug",performance:"Abilitare gli hook di monitoraggio delle prestazioni",stats:"Abilitare gli hook di raccolta statistiche",all:"Abilitare tutti gli hook di debug"},added:{debug:"Hook di log di debug aggiunti",performance:"Hook di monitoraggio delle prestazioni aggiunti",stats:"Hook di raccolta statistiche aggiunti",basic:"Hook di debug di base aggiunti"},success:"Hook di debug abilitati ({{count}} gestori registrati)",error:"Impossibile abilitare gli hook di debug: {{error}}"},security:{description:"Abilitare gli hook di sicurezza per il controllo degli accessi e il monitoraggio",options:{block:"Lista di strumenti da bloccare separati da virgole",maxPrompt:"Lunghezza massima consentita del prompt (predefinito: 10000)"},success:"Hook di sicurezza abilitati",blockedTools:"Strumenti bloccati: {{tools}}",maxPrompt:"Lunghezza massima del prompt: {{length}} caratteri",error:"Impossibile abilitare gli hook di sicurezza: {{error}}"},clear:{description:"Cancellare tutti gli hook registrati",success:"Tutti gli hook cancellati",error:"Impossibile cancellare gli hook: {{error}}"},test:{description:"Testare gli hook attivandoli con dati di prova",argument:{hookType:"Tipo di hook specifico da testare (opzionale)"},invalidType:"Tipo di hook non valido: {{type}}",triggered:"Hook attivato: {{type}}",result:"Risultato: {{result}}",allTriggered:"Tutti gli hook attivati con successo",error:"Impossibile testare gli hook: {{error}}"},register:{description:"Registrare un gestore di hook personalizzato da un file",argument:{hookType:"Tipo di hook per cui registrare il gestore",handlerFile:"Percorso del file del gestore (deve esportare una funzione predefinita)"},invalidType:"Tipo di hook non valido: {{type}}",invalidHandler:"Il file del gestore deve esportare una funzione predefinita",success:"Gestore per {{type}} registrato da {{file}}",error:"Impossibile registrare l'hook: {{error}}"},status:{description:"Mostrare la configurazione attuale degli hook e le statistiche",title:"\uD83D\uDCCB Stato degli hook",error:"Impossibile ottenere lo stato degli hook: {{error}}"}}}},7893(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"基本要件",projectDir:"プロジェクトディレクトリ(ここで作業): {{cwd}}",skillsInstruction:"タスクが説明と一致する場合、read_skill ツールでスキルの完全な指示を読み込んでください。",toolArgSizeLimit:"1 回のツール呼び出しの引数(例: write の content)は {{maxChars}} 文字を超えてはいけません。超えると API が切り詰め「Unterminated string in JSON」エラーになります。長いファイルやスクリプトは複数の write 呼び出しに分割してください(ファイル単位または {{maxChars}} 文字以内のチャンク単位)。",toolCallJsonFormat:'ツール呼び出しの引数は有効な JSON にしてください。すべてのキーと文字列値はダブルクォートで囲んでください。write の例: {"path": "ファイル名.md", "content": "内容"}。キーや値のクォートを省略しないでください(例: path: file.md は無効)。'},errors:{missingPromptFiles:"{{dir}} に必要なプロンプトファイルがありません:",runInit:"プロジェクトルートで 'pithosai init' を実行して .pithosai とテンプレートを作成してください。",noApiKey:"API キーが見つかりません。DEEPSEEK_API_KEY または OPENROUTER_API_KEY を設定してください。",ollamaNotConfigured:"Ollama が設定されていません。OPENAI_LOCAL_API_BASE を設定するか、ローカルモデルを持つプロジェクトを使用してください。",noValidTemplateFiles:"{{dir}} に有効なテンプレートファイルがありません。*-<lang>.md(例: IDENTITY-ja.md)が必要です。'pithosai init' を実行して .pithosai とテンプレートを作成してください。",runTimeout:"エージェントの実行が {{seconds}} 秒でタイムアウトしました。--timeout <秒> または PITHOSAI_TIMEOUT_MS で調整できます。",agentRunFailed:"実行に失敗しました: {{message}}",unknownRunError:"不明なエラー"},warnings:{sessionAppend:"セッション追加: {{message}}",apiRetry:"API エラー、試行 {{attempt}}/{{max}};再試行中..."},reasoner:{thinkingHeader:"\n--- 思考:\n",replyHeader:"\n\n--- 返答:\n"},run:{cwd:"cwd {{cwd}}",request:"リクエスト: {{request}}",interactivePrompt:"あなた: ",tuiYouLabel:"あなた:",interactiveExitHint:"回答するか新しいリクエストを入力してください('exit' または 'quit' で CLI を終了)。",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- インタラクティブ — エージェント(全ツール)---",interactiveModeAgentTips:"- 設定に応じた全ツール(読み取り・書き込み・実行など)が使えます。\n- 会話はタスク単位でローカル DB に保存されます。\n- `/new` で新しいタスク ID が割り当てられ、過去メッセージは読み込まれません。\n- `/shell <command>` でシェル実行。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` で永続化タスクを操作。\n- `/list-skill`、`/install-skill`、`/remove-skill` は `pithosai skills list|install|remove` と同じ(ClawHub)。Ctrl+S で停止、Ctrl+P で一時停止。",interactiveModeDialogTitle:"--- インタラクティブ — ダイアログ(読み取り専用 Q&A)---",interactiveModeDialogTips:"- 読み取り専用ツールのみ(シェル・ファイル編集・コマンド実行は不可)。\n- 会話はタスク単位でローカル DB に保存されます。\n- `/new` で新しいタスク ID が割り当てられ、過去メッセージは読み込まれません。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` で永続化タスクを操作。\n- `/list-skill`、`/install-skill`、`/remove-skill` でスキルを管理(ClawHub、`pithosai skills` CLI と同等)。",interactiveModePlanTitle:"--- プランモード ---",interactiveModePlanTips:"- 各応答はプロジェクト直下の `<slug>-plan.md` に保存されます(リクエスト先頭行がファイル名に影響)。\n- 読み取り専用ツールのみ。シェルや変更系ツールは不可。\n- `/new` で新しいタスク ID が割り当てられます。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` で永続化タスクを操作。\n- `/list-skill`、`/install-skill`、`/remove-skill` でスキルを管理(ClawHub、`pithosai skills` CLI と同等)。\n- 各実行後もプロンプトで次の計画リクエストを入力できます(agent/dialog と同様)。",list:{noPersistedTasks:"保存されたタスクが見つかりません。",createTasksFirstHint:"`pithosai task` を使って先にタスクを作成してください。",persistedTasksHeader:"--- 保存されたタスク ({{count}}) ---",selectTaskHint:"タスクを実行するには `/select <index>` を使用してください。",noTasksCached:"キャッシュされたタスクがありません。先に `/list` を実行してください。",invalidIndex:"無効なインデックス {{index}} です。有効範囲: 0-{{maxIndex}}。",selectUsage:"使い方: /select <index>",selectedTask:"タスク #{{index}} を選択しました。"},skillSlash:{installUsage:"使い方: /install-skill [--force] [スキル名]",removeUsage:"使い方: /remove-skill <スキル名>",listNoExtra:"/list-skill に引数は取れません。",failed:"スキルコマンドが失敗しました: {{message}}"},show:{title:"現在のタスク",field:"項目",value:"値",taskId:"taskId",mode:"モード",model:"モデル",status:"ステータス",messageCount:"メッセージ数",usageInput:"使用量.入力",usageOutput:"使用量.出力",usageCacheRead:"使用量.キャッシュ読込",usageCacheWrite:"使用量.キャッシュ書込",usageTotalTokens:"使用量.合計トークン"},showTask:{title:"タスクQ&A",taskIdLabel:"タスクID",turnHeading:"ターン {{index}}",questionLabel:"質問",answerLabel:"回答",createdLabel:"作成日時",emptyQuestion:"(質問なし)",emptyAnswer:"(アシスタントのテキスト回答なし)",emptyNoMessages:"このタスクにはまだユーザーメッセージがありません。",previewDocumentTitle:"タスクQ&A"},showPrompt:{previewDocumentTitle:"システムプロンプト",previewHeading:"システムプロンプト"},shellHint:"シェルコマンドを実行するには '/shell <コマンド>' を使用します(例: '/shell ls -la')。",replIntroDialog:"ダイアログモード:読み取り専用ツールのみ — `/shell` は無効。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` が永続化タスクに使えます。`/list-skill`、`/install-skill`、`/remove-skill` でスキル管理(ClawHub)。",replIntroPlan:"プランモード:各応答は `<slug>-plan.md` に保存(先頭行がファイル名に影響)。`/shell` は無効。完了まで出力は最小限です。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` が永続化タスクに使えます。`/list-skill`、`/install-skill`、`/remove-skill` でスキル管理(ClawHub)。",newSessionHint:"新しいセッション(チャット履歴なし)を開始するには '/new <リクエスト>' を使用します。",newSessionNoHistory:"新しいセッションを使用しています(チャット履歴なし)。",controlHint:"Ctrl+S で実行中のエージェントを停止、Ctrl+P で一時停止してサブコマンドに入ります。",replTabCompletionHint:"Tab でスラッシュコマンド(例: /list、/list-skill、/show)や exit/quit を補完できます。",tuiScrollTranscriptHint:"ターミナル UI:ホイール、矢印、PgUp/PgDn、Ctrl+U/Ctrl+F(ページ)。Ctrl+U/F はログをスクロール。Ctrl+D は空行で終了・入力中は前方削除のまま。",agentStopped:"エージェントが停止しました。",pauseHeader:"--- エージェント一時停止中 ---",pauseCurrentRequest:"現在のリクエスト:{{request}}",pauseHelp:"コマンド:'continue' または 'c' で再開、'exit' または 'e' で終了、またはリクエストを入力して置き換えます。",pausePrompt:"[一時停止] ",pauseRequestUpdated:"リクエストを更新しました:{{request}}"},shell:{noCommand:"/shell プレフィックスの後にコマンドが指定されていません。使用法: /shell <コマンド>",executionError:"シェルコマンドの実行中にエラーが発生しました: {{error}}",executing:"[shell] 実行中: {{command}}",errorNoCommand:"/shell プレフィックスの後にコマンドが指定されていません。",errorSpawnFailed:"プロセスの起動に失敗しました: {{message}}",errorTimedOut:"コマンドは {{seconds}} 秒でタイムアウトしました",logFailed:"Shell コマンドが失敗しました: {{command}} (終了コード: {{code}})",logExecutionError:"Shell コマンド実行エラー: {{message}}",resultCommand:"コマンド: {{command}}",resultExitCode:"終了コード: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"成功:",resultSuccessYes:"はい",resultSuccessNo:"いいえ",resultOutput:"出力:",resultError:"エラー:"},init:{invalidType:'--type "{{value}}" は無効です。選択肢: {{choices}}',invalidLang:'--lang "{{value}}" は無効です。選択肢: {{choices}}',templatesDirNotFound:"テンプレートディレクトリが見つかりません: {{dir}}",createdPromptTemplates:"{{dir}} を作成しました(プロンプトテンプレート)",createdSessions:"{{dir}} を作成しました(セッション履歴)",initialized:"{{targetDir}} に {{type}} プロジェクトを初期化しました",promptFilesIn:"プロンプトファイルは {{pithosaiDir}}、セッションデータは {{sessionsDir}}",runHint:'開始するには "pithosai -C {{targetDir}} \\"リクエスト\\"" を実行してください。',createdFile:"{{path}} を作成しました",roleAlreadyAdded:"ロール {{role}} は既に .pithosai にあります;スキップします。",addedRoleTemplates:"{{dir}} にロールテンプレートを追加しました"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: プレビューを閉じました({{source}})",skipped:"ブラウザプレビューをスキップしました(PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"markdown と path のどちらか一方だけを指定してください。",errorEmpty:"Markdown が空です。",errorFileOutside:"path はプロジェクトディレクトリ内である必要があります。",errorNotAFile:"path は通常のファイルではありません。",errorFileTooLarge:"ファイルが大きすぎます(最大 {{maxBytes}} バイト)。",errorFileRead:"ファイルを読めませんでした: {{message}}",sourceInline:"インライン Markdown",sourceFile:"ファイル {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"ハートビート用のメールは空にできません。sqlite3 DB の email_roles テーブルでロール {{role}} のメールを設定してください。",loadedState:"SQLite からハートビート状態を読み込みました(メール {{email}}、ロール {{role}})。状態: {{states}}",fetchFound:"ハートビートの受信トレイ取得で {{count}} 件の新規タスクを検出: {{ids}}",savedState:"ハートビート状態を SQLite に保存しました(メール {{email}}、ロール {{role}})",mergedAndNext:"{{merged}} 件のタスクを状態にマージしました。次に処理するスロット: {{stateSummary}}",replyEmailFailed:"ハートビートの返信メール送信に失敗しました: {{error}}",taskFailed:"ハートビートのタスクに失敗しました: {{error}}",failureReplyEmailFailed:"ハートビートの失敗通知メール送信に失敗しました: {{error}}"},cli:{description:"Pithosai: 自然言語のリクエストからコードやプロジェクトを実装します。 役割プロンプトは実行時に SQLite データベースから読み込まれます(オプションで .pithosai/<role>/*.md にフォールバック)。'pithosai init' でプロジェクトを作成します。",versionOption:"バージョンを表示",roleOption:"ロール(init 用テンプレートセット);テンプレートは templates/<role>/ にあります",langOption:"プロンプトと init テンプレートの言語: en, zh(デフォルト: en)",interactiveModeOption:"リクエストなしでインタラクティブモードに入る;モードの説明を表示して入力を待つ",initDescription:"新規プロジェクトと .pithosai/ ディレクトリ構造を作成。役割プロンプトは実行時に SQLite データベースから読み込まれます(オプションで .pithosai/<role>/*.md にフォールバック)。",initTypeOption:"プロジェクトタイプ: js, ts, python",initExamples:"\n例:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"プロジェクトの .pithosai/<role>/ にロールテンプレートを追加",addRoleArgument:"追加するロール(例: PM, QA)",requestArgument:'作成するもの(例: "CSV を JSON に変換する CLI")。省略するとヘルプを表示。',cwdOption:"プロジェクトディレクトリ(デフォルト: カレントディレクトリ)",skillsDirOption:"read_skill 用スキルディレクトリ(デフォルト: ./.pithosai/skills または PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner(思考)モデルを使用;デフォルトは DeepSeek Coder",chatOption:"DeepSeek Chat モデルを使用(一般チャット、コード以外);デフォルトは DeepSeek Coder",cursorOption:"Cursor CLI モデルを使用(cursor-agent login で認証、API キー不要)。オプションでモデル指定: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"エージェント最大実行時間(秒、デフォルト: 1800)。PITHOSAI_TIMEOUT_MS(ミリ秒)で上書き可能。",interactiveOption:"対話プロンプトを無効にする(デフォルト: 各返答後に次のメッセージを促す)",modeOption:"variant: agent(既定・ツール可)、dialog(回答のみ・ツールなし)、plan(プロジェクト直下に <slug>-plan.md のみ出力・ツールなし)",shellDisabledInMode:"dialog / plan モードでは /shell は無効です。",planWritten:"プランを {{path}} に書き込みました",planRunning:"プランを生成中…",waitingReply:"応答を待っています…",runningReply:"実行中…",resultPreviewOpening:"ブラウザで結果プレビューを開いています…",resultPreviewTitle:"Pithosai の結果",resultPreviewFailed:"結果プレビューを開けませんでした: {{message}}",resultPreviewCopy:"Markdown をコピー",resultPreviewClose:"閉じる",resultPreviewCopied:"クリップボードにコピーしました",resultPreviewTerminalHint:"↑↓ または j/k \xb7 PgUp/PgDn または Ctrl+U/Ctrl+D \xb7 Home/End または gg/G \xb7 q/Esc で閉じる",runExamples:'\n例:\n pithosai "現在時刻を返す REST エンドポイントを追加"\n pithosai -C ./my-app "テストを実行して失敗を修正"\n pithosai -i # インタラクティブモード:最新セッション読み込み後プロンプト\n pithosai --no-interactive "1回" # 1回の返答、続きのプロンプトなし\n pithosai --mode dialog "このエラーを説明"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"使用法:",helpArguments:"引数:",helpOptions:"オプション:",helpCommands:"コマンド:",helpGlobalOptions:"グローバルオプション:",helpOption:"コマンドのヘルプを表示",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"タスクファイルを監視し、同一プロセスで1件ずつ処理します",taskFileOption:"タスク用 Markdown のパス(既定:プロジェクトルートの prompts.md)",taskModelOption:"タスクのモデルキー(deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"新しいセッションで開始(チャット履歴なし)",taskExamples:"\n例:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"タスクが見つかりません: {{taskId}}",taskAgentCompleted:"エージェントが完了しました。",taskAgentRunFailed:"エージェントの実行に失敗しました。",taskDone:"完了",taskFailed:"タスクが失敗しました: {{message}}",taskProcessingHeader:"--- タスクを処理中 ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"処理中タスク {{id}}({{title}})のプロセッサを開始します。",taskNoPending:"保留中のタスクはありません。",taskPickedTask:"タスク {{id}}({{title}})を選択しました。プロセッサを開始します。",taskProcessorFailed:"タスクプロセッサが失敗しました: {{message}}",taskWatcherRunning:"タスクウォッチャー実行中。Ctrl+C で停止。",memorizeDescription:"指定期間にロールが関与したタスク(永続化されたタスクメッセージ)を要約し、.pithosai/<role>/memory.md に書き出します。",memorizeStartOption:"開始日: YYYY-MM-DD または ISO 日時",memorizeEndOption:"終了日: YYYY-MM-DD または ISO 日時",memorizeRoleRequired:"ロールが必要です(-r/--role またはグローバル --role)。",memorizeWrote:"{{path}} に書き込みました({{count}} 件のタスク)。",memorizeNoTasks:"ロール {{role}} の期間内タスクはありません。{{path}} にヘッダのみ書き込みました。",memorizeDateError:"日付範囲が無効です: {{message}}",memorizeNoLlmOption:"LLM 要約をスキップし、構造化メモリのみ書き込む(PITHOSAI_MEMORIZE_SKIP_LLM=1 と同じ)。",memorizeLlmFallback:"LLM 要約に失敗しました({{message}})。要約なしの構造化メモリを書き込みました。",memorizeExamples:"\n例:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"リクエストに応じたシェルコマンドを取得(Ollama のみ、コマンドのみ出力)",argument:"やりたいこと(例:カレントディレクトリの大きいファイルを一覧)",loading:"コマンドを取得中...",examples:'\n例:\n $ pithosai shell-tips カレントディレクトリの json ファイルを一覧\n $ pithosai shell-tips "全 .js ファイルで foo を bar に置換"'},writer:{description:"リクエストに応じてテキストを生成(Ollama qwen2.5:14b)",argument:"書く内容(例:会議を断る短いメール)",loading:"執筆中...",examples:'\n例:\n $ pithosai writer 会議を断る短いメール\n $ pithosai writer "プロジェクトキックオフの3つのポイント"'},skills:{installing:"スキルを {{dir}} にインストール中",fetchingList:"ClawHub から利用可能なスキルを取得中...",fetchingIndex:"{{url}} からスキルインデックスを取得中",notFound:"スキル '{{name}}' が見つかりません",noSkillsAvailable:"ClawHub から利用可能なスキルはありません",noSkillsFound:"スキルが見つかりません",downloadFailed:"スキル '{{name}}' のダウンロードに失敗: {{error}}",installed:"スキル '{{name}}' をインストールしました",complete:"インストール完了: {{count}} / {{total}} スキルをインストール",alreadyInstalled:"スキル '{{name}}' は既にインストール済み(再インストールには --force を使用)",downloading:"スキル '{{name}}' を {{url}} からダウンロード中",noSkillsDir:"スキルディレクトリが見つかりません。まずスキルをインストールしてください。",noSkillsInstalled:"インストール済みスキルはありません",installedList:"インストール済みスキル(合計 {{count}}){{dir}} 内:",notInstalled:"スキル '{{name}}' はインストールされていません",removed:"スキル '{{name}}' を削除しました"},skillConvert:{welcome:"スキル変換システム - 成功したスキルを永続ツールに変換",listHeader:"スキル変換分析({{totalSkills}} スキル、{{totalExecutions}} 回実行)",noSuggestions:"変換しきい値 {{threshold}} を満たすスキルはありません。",suggestedConversions:"変換推奨:",convertHint:"'pithosai skill-convert convert <スキル名>' でスキルを変換できます。",skillNotFound:"スキル '{{skillName}}' が見つからないか読み取れません: {{error}}",alreadyConverted:"スキル '{{skillName}}' は既にツールに変換されています。",useForceHint:"--force を使って再度変換できます。",conversionReportHeader:"'{{skillName}}' 変換レポート:",conversionScore:"変換スコア",suggestedType:"推奨タイプ",ready:"変換準備完了",estimatedBenefits:"見込み効果",performance:"パフォーマンス向上",reliability:"信頼性向上",usability:"使いやすさ向上",parameters:"パラメーター",notReadyWarning:"このスキルは自動変換の準備ができていません。",moreUsageHint:"スキルをもっと使用するか、--force で強制変換してください。",dryRunComplete:"ドライラン完了。変更はありません。",confirmConversion:"'{{skillName}}' を永続ツールに変換しますか?",conversionCancelled:"変換がキャンセルされました。",converting:"'{{skillName}}' をツールに変換中...",conversionSuccess:"'{{skillName}}' を '{{toolName}}' に変換しました。\nツール保存先: {{toolPath}}",usageExample:"使用例:",nextSteps:"次のステップ:",restartAgent:"新しいツールを読み込むためにエージェントを再起動してください",testTool:"ツールをテスト: <ツール名> --help",manageTools:"ツール管理: pithosai skill-convert tools",listError:"スキル一覧の取得でエラー: {{error}}",conversionError:"'{{skillName}}' の変換でエラー: {{error}}",skillStatsHeader:"'{{skillName}}' の統計情報:",generalStats:"一般統計",totalExecutions:"合計実行回数",successful:"成功",failed:"失敗",avgTime:"平均実行時間",lastUsed:"最終使用",recentExecutions:"最近の実行",commonParameters:"よく使うパラメーター",overallStatsHeader:"全体スキル統計",overallStats:"全体統計",totalSkillsTracked:"追跡スキル数",avgSuccessRate:"平均成功率",topSkills:"使用量上位のスキル",conversionSuggestions:"変換候補",statsError:"統計の取得でエラー: {{error}}",confirmClearAll:"すべてのスキル実行記録を消去しますか?この操作は取り消せません。",allRecordsCleared:"すべてのスキル実行記録が消去されました。",skillRecordsCleared:"'{{skillName}}' のスキル実行記録が消去されました。",clearCancelled:"消去がキャンセルされました。",specifySkillOrAll:"スキル名を指定するか --all を使用してください",clearError:"記録の消去でエラー: {{error}}",noConvertedTools:"変換されたツールはありません。",convertedToolsHeader:"変換済みツール:",originalSkill:"元のスキル",converted:"変換日時",usageCount:"使用回数",toolsError:"ツール管理でエラー: {{error}}",confirmRemoveTool:"ツール '{{toolName}}' を削除しますか?",toolRemoved:"ツール '{{toolName}}' が削除されました。",toolRemoveFailed:"ツール '{{toolName}}' の削除に失敗しました。",removeCancelled:"ツール削除がキャンセルされました。",toolEnabled:"ツール '{{toolName}}' が有効になりました。",toolEnableFailed:"ツール '{{toolName}}' の有効化に失敗しました。",toolDisabled:"ツール '{{toolName}}' が無効になりました。",toolDisableFailed:"ツール '{{toolName}}' の無効化に失敗しました。",noStatsForSkill:"スキル '{{skillName}}' の統計情報が見つかりません。"},hooks:{description:"デバッグ、セキュリティ、監視用のエージェントフックを管理",list:{description:"登録済みのすべてのフックを一覧表示",title:"\uD83D\uDCCB 登録済みフック",total:"合計: {{total}} ハンドラー",options:{verbose:"詳細なハンドラー情報を表示"},error:"フックの一覧表示に失敗: {{error}}"},debug:{description:"エージェントの動作を監視するデバッグフックを有効化",options:{data:"デバッグ出力に完全なデータを記録",performance:"パフォーマンス監視フックを有効化",stats:"統計収集フックを有効化",all:"すべてのデバッグフックを有効化"},added:{debug:"デバッグログフックを追加しました",performance:"パフォーマンス監視フックを追加しました",stats:"統計収集フックを追加しました",basic:"基本デバッグフックを追加しました"},success:"デバッグフックを有効化しました({{count}} ハンドラー登録済み)",error:"デバッグフックの有効化に失敗: {{error}}"},security:{description:"アクセス制御と監視のためのセキュリティフックを有効化",options:{block:"ブロックするツールのカンマ区切りリスト",maxPrompt:"最大プロンプト長(デフォルト: 10000)"},success:"セキュリティフックを有効化しました",blockedTools:"ブロックされたツール: {{tools}}",maxPrompt:"最大プロンプト長: {{length}} 文字",error:"セキュリティフックの有効化に失敗: {{error}}"},clear:{description:"登録済みのすべてのフックをクリア",success:"すべてのフックをクリアしました",error:"フックのクリアに失敗: {{error}}"},test:{description:"テストデータでフックをトリガーしてテスト",argument:{hookType:"テストするフックタイプ(省略可)"},invalidType:"無効なフックタイプ: {{type}}",triggered:"フックをトリガーしました: {{type}}",result:"結果: {{result}}",allTriggered:"すべてのフックが正常にトリガーされました",error:"フックのテストに失敗: {{error}}"},register:{description:"ファイルからカスタムフックハンドラーを登録",argument:{hookType:"ハンドラーを登録するフックタイプ",handlerFile:"ハンドラーファイルのパス(デフォルト関数をエクスポートする必要あり)"},invalidType:"無効なフックタイプ: {{type}}",invalidHandler:"ハンドラーファイルはデフォルト関数をエクスポートする必要があります",success:"{{file}} から {{type}} のハンドラーを登録しました",error:"フックの登録に失敗: {{error}}"},status:{description:"現在のフック設定と統計情報を表示",title:"\uD83D\uDCCB フックステータス",error:"フックステータスの取得に失敗: {{error}}"}}}},5490(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"기본 요구사항",projectDir:"프로젝트 디렉터리 (여기서 작업): {{cwd}}",skillsInstruction:"작업이 설명과 일치할 때 read_skill 도구를 사용하여 해당 스킬의 전체 지침을 로드하세요.",toolArgSizeLimit:'단일 도구 호출 인수(예: write의 content)는 {{maxChars}}자를 절대 초과하면 안 됩니다. 초과 시 API가 잘라 "Unterminated string in JSON" 오류가 납니다. 긴 파일이나 스크립트는 여러 write 호출로 나누세요(파일별 또는 {{maxChars}}자 이내 청크별).',toolCallJsonFormat:'도구 호출 인수는 유효한 JSON이어야 합니다. 모든 키와 문자열 값은 큰따옴표로 감싸세요. write 예: {"path": "파일명.md", "content": "내용"}. 키나 값의 따옴표를 생략하지 마세요(예: path: file.md는 무효).'},errors:{missingPromptFiles:"{{dir}}에 필요한 프롬프트 파일이 없습니다:",runInit:"프로젝트 루트에서 'pithosai init'을 실행하여 .pithosai와 템플릿을 만드세요.",noApiKey:"API 키를 찾을 수 없습니다. DEEPSEEK_API_KEY 또는 OPENROUTER_API_KEY를 설정하세요.",ollamaNotConfigured:"Ollama가 설정되지 않았습니다. OPENAI_LOCAL_API_BASE를 설정하거나 로컬 모델이 있는 프로젝트를 사용하세요.",noValidTemplateFiles:"{{dir}}에 유효한 템플릿 파일이 없습니다. *-<lang>.md (예: IDENTITY-ja.md) 형식이 필요합니다. 'pithosai init'을 실행하여 .pithosai와 템플릿을 만드세요.",runTimeout:"에이전트 실행이 {{seconds}}초 후 타임아웃되었습니다. --timeout <초> 또는 PITHOSAI_TIMEOUT_MS로 조정하세요.",agentRunFailed:"실행 실패: {{message}}",unknownRunError:"알 수 없는 오류"},warnings:{sessionAppend:"세션 추가: {{message}}",apiRetry:"API 오류, 시도 {{attempt}}/{{max}}; 재시도 중..."},reasoner:{thinkingHeader:"\n--- 생각:\n",replyHeader:"\n\n--- 답변:\n"},run:{cwd:"cwd {{cwd}}",request:"요청: {{request}}",interactivePrompt:"당신: ",tuiYouLabel:"당신:",interactiveExitHint:"답변하거나 새 요청을 입력하세요 (CLI 종료: 'exit' 또는 'quit' 입력).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- 대화형 모드 — 에이전트(전체 도구) ---",interactiveModeAgentTips:"- 설정에 따라 읽기\xb7쓰기\xb7실행 등 전체 도구를 사용할 수 있습니다.\n- 대화는 작업별로 로컬 DB에 저장됩니다.\n- `/new`는 새 작업 ID를 부여하며 이전 메시지를 불러오지 않습니다.\n- `/shell <명령>`으로 셸 실행, `/list`, `/select`, `/show`, `/show-task`, `/show-prompt`로 저장된 작업 관리.\n- `/list-skill`, `/install-skill`, `/remove-skill`은 `pithosai skills list|install|remove`와 동일(ClawHub). Ctrl+S 중지, Ctrl+P 일시정지.",interactiveModeDialogTitle:"--- 대화형 모드 — 다이얼로그(읽기 전용 Q&A) ---",interactiveModeDialogTips:"- 읽기 전용 도구만 사용합니다(셸, 파일 편집, 명령 실행 불가).\n- 대화는 작업별로 로컬 DB에 저장됩니다.\n- `/new`는 새 작업 ID를 부여하며 이전 메시지를 불러오지 않습니다.\n- `/list`, `/select`, `/show`, `/show-task`, `/show-prompt`로 저장된 작업을 다룹니다.\n- `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub, `pithosai skills` CLI와 동일).",interactiveModePlanTitle:"--- 계획 모드 ---",interactiveModePlanTips:"- 각 응답은 프로젝트 디렉터리의 `<slug>-plan.md`에 기록됩니다(요청 첫 줄이 파일명에 영향).\n- 읽기 전용 도구만 사용; 셸 및 변경 도구는 비활성화됩니다.\n- `/new`는 새 작업 ID를 부여합니다.\n- `/list`, `/select`, `/show`, `/show-task`, `/show-prompt`로 저장된 작업을 다룹니다.\n- `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub, `pithosai skills` CLI와 동일).\n- 실행이 끝난 뒤 프롬프트에서 새 계획 요청을 이어갈 수 있습니다(agent/dialog과 동일).",list:{noPersistedTasks:"저장된 작업을 찾을 수 없습니다.",createTasksFirstHint:"`pithosai task`로 먼저 작업을 생성하세요.",persistedTasksHeader:"--- 저장된 작업 ({{count}}) ---",selectTaskHint:"작업을 실행하려면 `/select <index>`를 사용하세요.",noTasksCached:"캐시된 작업이 없습니다. 먼저 `/list`를 실행하세요.",invalidIndex:"잘못된 인덱스 {{index}}입니다. 유효 범위: 0-{{maxIndex}}.",selectUsage:"사용법: /select <index>",selectedTask:"작업 #{{index}}를 선택했습니다."},skillSlash:{installUsage:"사용법: /install-skill [--force] [스킬이름]",removeUsage:"사용법: /remove-skill <스킬이름>",listNoExtra:"/list-skill은 인자를 받지 않습니다.",failed:"스킬 명령 실패: {{message}}"},show:{title:"현재 작업",field:"항목",value:"값",taskId:"taskId",mode:"모드",model:"모델",status:"상태",messageCount:"메시지수",usageInput:"사용량.입력",usageOutput:"사용량.출력",usageCacheRead:"사용량.캐시읽기",usageCacheWrite:"사용량.캐시쓰기",usageTotalTokens:"사용량.총토큰"},showTask:{title:"작업 Q&A",taskIdLabel:"작업 ID",turnHeading:"{{index}}번째 턴",questionLabel:"질문",answerLabel:"답변",createdLabel:"생성 시각",emptyQuestion:"(빈 질문)",emptyAnswer:"(어시스턴트 텍스트 답변 없음)",emptyNoMessages:"이 작업에 사용자 메시지가 아직 없습니다.",previewDocumentTitle:"작업 Q&A"},showPrompt:{previewDocumentTitle:"시스템 프롬프트",previewHeading:"시스템 프롬프트"},shellHint:"셸 명령을 실행하려면 '/shell <명령>'을 사용하세요 (예: '/shell ls -la').",replIntroDialog:"대화 모드: 읽기 전용 도구만 — `/shell` 비활성화. 저장된 작업에는 `/list`, `/select`, `/show`, `/show-task`, `/show-prompt` 사용. `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub).",replIntroPlan:"계획 모드: 각 응답은 `<slug>-plan.md`에 저장(첫 줄이 파일명에 영향). `/shell` 비활성화; 완료 전까지 출력은 최소화. 저장된 작업에는 `/list`, `/select`, `/show`, `/show-task`, `/show-prompt` 사용. `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub).",newSessionHint:"새 세션(채팅 기록 없음)을 시작하려면 '/new <요청>'을 사용하세요.",newSessionNoHistory:"새 세션 사용 중입니다(채팅 기록 없음).",controlHint:"Ctrl+S를 눌러 실행 중인 에이전트를 중지하고, Ctrl+P를 눌러 일시 중지 후 하위 명령을 입력합니다.",replTabCompletionHint:"Tab으로 슬래시 명령(예: /list, /list-skill, /show) 또는 exit/quit을 완성할 수 있습니다.",tuiScrollTranscriptHint:"터미널 UI: 휠, 방향키, PgUp/PgDn, Ctrl+U/Ctrl+F(페이지). Ctrl+U/F는 로그 스크롤. Ctrl+D는 빈 줄 종료\xb7입력 중 앞으로 삭제 그대로.",agentStopped:"에이전트가 중지되었습니다.",pauseHeader:"--- 에이전트 일시 중지됨 ---",pauseCurrentRequest:"현재 요청: {{request}}",pauseHelp:"명령: 'continue' 또는 'c'로 계속, 'exit' 또는 'e'로 종료, 또는 새 요청을 입력하여 현재 요청을 교체합니다.",pausePrompt:"[일시 중지] ",pauseRequestUpdated:"요청이 업데이트됨: {{request}}"},shell:{noCommand:"/shell 접두사 뒤에 명령이 제공되지 않았습니다. 사용법: /shell <명령>",executionError:"셸 명령 실행 중 오류 발생: {{error}}",executing:"[shell] 실행 중: {{command}}",errorNoCommand:"/shell 접두사 뒤에 명령이 제공되지 않았습니다.",errorSpawnFailed:"프로세스 시작 실패: {{message}}",errorTimedOut:"{{seconds}}초 후 명령 시간 초과",logFailed:"Shell 명령 실패: {{command}} (종료 코드: {{code}})",logExecutionError:"Shell 명령 실행 오류: {{message}}",resultCommand:"명령: {{command}}",resultExitCode:"종료 코드: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"성공:",resultSuccessYes:"예",resultSuccessNo:"아니오",resultOutput:"출력:",resultError:"오류:"},init:{invalidType:'--type "{{value}}"이(가) 잘못되었습니다. 선택: {{choices}}',invalidLang:'--lang "{{value}}"이(가) 잘못되었습니다. 선택: {{choices}}',templatesDirNotFound:"템플릿 디렉터리를 찾을 수 없습니다: {{dir}}",createdPromptTemplates:"{{dir}} 생성됨 (프롬프트 템플릿)",createdSessions:"{{dir}} 생성됨 (세션 기록)",initialized:"{{targetDir}}에 {{type}} 프로젝트를 초기화했습니다",promptFilesIn:"프롬프트 파일: {{pithosaiDir}}, 세션 데이터: {{sessionsDir}}",runHint:'시작하려면 "pithosai -C {{targetDir}} \\"요청 내용\\""을 실행하세요.',createdFile:"{{path}} 생성됨",roleAlreadyAdded:"역할 {{role}}이(가) 이미 .pithosai에 있습니다; 건너뜁니다.",addedRoleTemplates:"{{dir}}에 역할 템플릿을 추가했습니다"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: 미리보기 종료 ({{source}})",skipped:"브라우저 미리보기 건너뜀 (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"markdown 또는 path 중 하나만 제공하세요.",errorEmpty:"Markdown 내용이 비어 있습니다.",errorFileOutside:"path는 프로젝트 디렉터리 안에 있어야 합니다.",errorNotAFile:"path가 일반 파일이 아닙니다.",errorFileTooLarge:"파일이 너무 큽니다 (최대 {{maxBytes}}바이트).",errorFileRead:"파일을 읽을 수 없습니다: {{message}}",sourceInline:"인라인 Markdown",sourceFile:"파일 {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"하트비트용 이메일을 비워 둘 수 없습니다. sqlite3 DB의 email_roles 테이블에서 역할 {{role}}의 이메일을 설정하세요.",loadedState:"SQLite에서 하트비트 상태를 불러왔습니다 (이메일 {{email}}, 역할 {{role}}). 상태: {{states}}",fetchFound:"하트비트 수신함 조회에서 새 작업 {{count}}건 발견: {{ids}}",savedState:"하트비트 상태를 SQLite에 저장했습니다 (이메일 {{email}}, 역할 {{role}})",mergedAndNext:"상태에 작업 {{merged}}건을 병합했습니다. 다음 처리 대상: {{stateSummary}}",replyEmailFailed:"하트비트 회신 메일 전송 실패: {{error}}",taskFailed:"하트비트 작업 실패: {{error}}",failureReplyEmailFailed:"하트비트 실패 알림 메일 전송 실패: {{error}}"},cli:{description:"Pithosai: 자연어 요청으로 코드나 프로젝트를 구현합니다. 역할 프롬프트는 런타임에 SQLite 데이터베이스에서 로드됩니다 (선택적으로 .pithosai/<role>/*.md로 폴백). 'pithosai init'으로 프로젝트를 생성합니다.",versionOption:"버전 출력",roleOption:"역할 (init용 템플릿 세트); 템플릿은 templates/<role>/에 있음",langOption:"프롬프트 및 init 템플릿 언어: en, zh (기본값: en)",interactiveModeOption:"요청 없이 대화형 모드로 진입; 모드 안내를 표시하고 입력 대기",initDescription:"새 프로젝트와 .pithosai/ 디렉토리 구조 생성. 역할 프롬프트는 런타임에 SQLite 데이터베이스에서 로드됩니다 (선택적으로 .pithosai/<role>/*.md로 폴백).",initTypeOption:"프로젝트 유형: js, ts, python",initExamples:"\n예:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"프로젝트의 .pithosai/<role>/에 역할 템플릿 추가",addRoleArgument:"추가할 역할 (예: PM, QA)",requestArgument:'구현할 내용 (예: "CSV를 JSON으로 변환하는 CLI"). 생략하면 도움말 표시.',cwdOption:"프로젝트 디렉터리 (기본값: 현재 디렉터리)",skillsDirOption:"read_skill용 스킬 디렉터리 (기본값: ./.pithosai/skills 또는 PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner(사고) 모델 사용; 기본값은 DeepSeek Coder",chatOption:"DeepSeek Chat 모델 사용 (일반 채팅, 코드 아님); 기본값은 DeepSeek Coder",cursorOption:"Cursor CLI 모델 사용 (cursor-agent login으로 인증, API 키 불필요). 선택적으로 모델 지정: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"에이전트 최대 실행 시간(초, 기본값: 1800). PITHOSAI_TIMEOUT_MS(ms)로 덮어쓸 수 있음.",interactiveOption:"대화형 프롬프트 비활성화 (기본값: 각 응답 후 다음 메시지 입력 요청)",modeOption:"실행 모드: agent(기본값, 도구 사용 가능), dialog(답변만, 도구 없음), plan(프로젝트 루트에 <slug>-plan.md만 작성, 도구 없음)",shellDisabledInMode:"dialog 및 plan 모드에서는 /shell 명령이 비활성화됩니다.",planWritten:"계획을 {{path}}에 저장했습니다",planRunning:"계획 생성 중…",waitingReply:"응답을 기다리는 중…",runningReply:"실행 중…",resultPreviewOpening:"브라우저에서 결과 미리보기를 여는 중…",resultPreviewTitle:"Pithosai 결과",resultPreviewFailed:"결과 미리보기를 열 수 없습니다: {{message}}",resultPreviewCopy:"Markdown 복사",resultPreviewClose:"닫기",resultPreviewCopied:"클립보드에 복사됨",resultPreviewTerminalHint:"↑↓ 또는 j/k \xb7 PgUp/PgDn 또는 Ctrl+U/Ctrl+D \xb7 Home/End 또는 gg/G \xb7 q/Esc로 닫기",runExamples:'\n예:\n pithosai "현재 시간을 반환하는 REST 엔드포인트 추가"\n pithosai -C ./my-app "테스트 실행 후 실패 수정"\n pithosai -i # 대화형 모드: 최신 세션 로드 후 요청 입력\n pithosai --no-interactive "한 번" # 한 번만 응답, 후속 프롬프트 없음\n pithosai --mode dialog "이 오류 설명"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"사용법:",helpArguments:"인수:",helpOptions:"옵션:",helpCommands:"명령:",helpGlobalOptions:"전역 옵션:",helpOption:"명령 도움말 표시",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"작업 파일을 감시하고 같은 프로세스에서 한 번에 하나씩 처리합니다",taskFileOption:"작업 Markdown 파일 경로(기본값: 프로젝트 루트의 prompts.md)",taskModelOption:"작업용 모델 키(deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"새 세션으로 시작(채팅 기록 없음)",taskExamples:"\n예:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"작업을 찾을 수 없음: {{taskId}}",taskAgentCompleted:"에이전트가 완료되었습니다.",taskAgentRunFailed:"에이전트 실행에 실패했습니다.",taskDone:"완료",taskFailed:"작업 실패: {{message}}",taskProcessingHeader:"--- 작업 처리 중 ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"처리 중인 작업 {{id}}({{title}})에 대한 프로세서를 시작합니다.",taskNoPending:"대기 중인 작업이 없습니다.",taskPickedTask:"작업 {{id}}({{title}})을(를) 선택했습니다. 프로세서를 시작합니다.",taskProcessorFailed:"작업 프로세서 실패: {{message}}",taskWatcherRunning:"작업 감시기 실행 중. Ctrl+C로 종료.",memorizeDescription:"기간 내 역할이 참여한 작업(저장된 작업 메시지)을 요약해 .pithosai/<role>/memory.md에 씁니다.",memorizeStartOption:"시작: YYYY-MM-DD 또는 ISO 날짜시간",memorizeEndOption:"종료: YYYY-MM-DD 또는 ISO 날짜시간",memorizeRoleRequired:"역할이 필요합니다(-r/--role 또는 전역 --role).",memorizeWrote:"{{path}}에 기록했습니다(작업 {{count}}개).",memorizeNoTasks:"역할 {{role}}에 해당 기간 작업이 없습니다. {{path}}에 헤더만 썼습니다.",memorizeDateError:"날짜 범위가 잘못되었습니다: {{message}}",memorizeNoLlmOption:"LLM 요약 건너뛰기; 구조화된 메모리만 기록(PITHOSAI_MEMORIZE_SKIP_LLM=1과 동일).",memorizeLlmFallback:"LLM 요약 실패({{message}}); 요약 없이 구조화된 메모리를 기록했습니다.",memorizeExamples:"\n예:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"요청에 맞는 셸 명령어 가져오기 (Ollama 전용, 명령어만 출력)",argument:"하고 싶은 작업 (예: 현재 디렉터리의 큰 파일 목록)",loading:"명령어 가져오는 중...",examples:'\n예:\n $ pithosai shell-tips 현재 디렉터리의 json 파일 목록\n $ pithosai shell-tips "모든 .js 파일에서 foo를 bar로 바꾸기"'},writer:{description:"요청에 맞는 텍스트 생성 (Ollama qwen2.5:14b)",argument:"쓸 내용 (예: 회의 거절 짧은 이메일)",loading:"작성 중...",examples:'\n예:\n $ pithosai writer 회의 거절 짧은 이메일\n $ pithosai writer "프로젝트 킥오프 세 가지 요점"'},skills:{installing:"스킬을 {{dir}}에 설치 중",fetchingList:"ClawHub에서 사용 가능한 스킬 가져오는 중...",fetchingIndex:"{{url}}에서 스킬 인덱스 가져오는 중",notFound:"스킬 '{{name}}'을(를) 찾을 수 없습니다",noSkillsAvailable:"ClawHub에서 사용 가능한 스킬이 없습니다",noSkillsFound:"스킬을 찾을 수 없습니다",downloadFailed:"스킬 '{{name}}' 다운로드 실패: {{error}}",installed:"스킬 '{{name}}' 설치 완료",complete:"설치 완료: {{count}} / {{total}} 스킬 설치됨",alreadyInstalled:"스킬 '{{name}}'이(가) 이미 설치됨 (재설치하려면 --force 사용)",downloading:"스킬 '{{name}}'을(를) {{url}}에서 다운로드 중",noSkillsDir:"스킬 디렉터리를 찾을 수 없습니다. 먼저 스킬을 설치하세요.",noSkillsInstalled:"설치된 스킬이 없습니다",installedList:"설치된 스킬 (총 {{count}}개) {{dir}} 내:",notInstalled:"스킬 '{{name}}'이(가) 설치되지 않았습니다",removed:"스킬 '{{name}}'을(를) 제거했습니다"},skillConvert:{welcome:"스킬 변환 시스템 - 성공적인 스킬을 영구 도구로 변환",listHeader:"스킬 변환 분석 ({{totalSkills}}개 스킬, {{totalExecutions}}회 실행)",noSuggestions:"변환 임계값 {{threshold}}을(를) 충족하는 스킬이 없습니다.",suggestedConversions:"변환 추천:",convertHint:"'pithosai skill-convert convert <스킬명>'을 사용하여 스킬을 변환하세요.",skillNotFound:"스킬 '{{skillName}}'을(를) 찾을 수 없거나 읽을 수 없습니다: {{error}}",alreadyConverted:"스킬 '{{skillName}}'은(는) 이미 도구로 변환되었습니다.",useForceHint:"--force를 사용하여 다시 변환하세요.",conversionReportHeader:"'{{skillName}}' 변환 보고서:",conversionScore:"변환 점수",suggestedType:"추천 유형",ready:"변환 준비 완료",estimatedBenefits:"예상 이점",performance:"성능 향상",reliability:"안정성 향상",usability:"사용성 향상",parameters:"매개변수",notReadyWarning:"이 스킬은 아직 자동 변환이 준비되지 않았습니다.",moreUsageHint:"스킬을 더 자주 사용하거나 --force를 사용하여 강제 변환하세요.",dryRunComplete:"시뮬레이션 실행 완료. 변경 사항이 없습니다.",confirmConversion:"'{{skillName}}'을(를) 영구 도구로 변환하시겠습니까?",conversionCancelled:"변환이 취소되었습니다.",converting:"'{{skillName}}'을(를) 도구로 변환 중...",conversionSuccess:"'{{skillName}}'을(를) '{{toolName}}'(으)로 성공적으로 변환했습니다.\n도구 저장 위치: {{toolPath}}",usageExample:"사용 예:",nextSteps:"다음 단계:",restartAgent:"새 도구를 로드하려면 에이전트를 재시작하세요",testTool:"도구 테스트: <도구명> --help",manageTools:"도구 관리: pithosai skill-convert tools",listError:"스킬 목록 조회 중 오류: {{error}}",conversionError:"'{{skillName}}' 변환 중 오류: {{error}}",skillStatsHeader:"'{{skillName}}' 통계:",generalStats:"일반 통계",totalExecutions:"총 실행 횟수",successful:"성공",failed:"실패",avgTime:"평균 실행 시간",lastUsed:"마지막 사용",recentExecutions:"최근 실행",commonParameters:"자주 쓰는 매개변수",overallStatsHeader:"전체 스킬 통계",overallStats:"전체 통계",totalSkillsTracked:"추적된 스킬 수",avgSuccessRate:"평균 성공률",topSkills:"사용량 상위 스킬",conversionSuggestions:"변환 추천",statsError:"통계 조회 중 오류: {{error}}",confirmClearAll:"모든 스킬 실행 기록을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",allRecordsCleared:"모든 스킬 실행 기록이 삭제되었습니다.",skillRecordsCleared:"'{{skillName}}'의 스킬 실행 기록이 삭제되었습니다.",clearCancelled:"삭제 작업이 취소되었습니다.",specifySkillOrAll:"스킬 이름을 지정하거나 --all을 사용하세요",clearError:"기록 삭제 중 오류: {{error}}",noConvertedTools:"변환된 도구가 없습니다.",convertedToolsHeader:"변환된 도구:",originalSkill:"원본 스킬",converted:"변환 일시",usageCount:"사용 횟수",toolsError:"도구 관리 중 오류: {{error}}",confirmRemoveTool:"도구 '{{toolName}}'을(를) 제거하시겠습니까?",toolRemoved:"도구 '{{toolName}}'이(가) 제거되었습니다.",toolRemoveFailed:"도구 '{{toolName}}' 제거 실패.",removeCancelled:"도구 제거가 취소되었습니다.",toolEnabled:"도구 '{{toolName}}'이(가) 활성화되었습니다.",toolEnableFailed:"도구 '{{toolName}}' 활성화 실패.",toolDisabled:"도구 '{{toolName}}'이(가) 비활성화되었습니다.",toolDisableFailed:"도구 '{{toolName}}' 비활성화 실패.",noStatsForSkill:"스킬 '{{skillName}}'의 통계를 찾을 수 없습니다."},hooks:{description:"디버깅, 보안 및 모니터링을 위한 에이전트 훅 관리",list:{description:"등록된 모든 훅 목록 표시",title:"\uD83D\uDCCB 등록된 훅",total:"총계: {{total}} 핸들러",options:{verbose:"상세 핸들러 정보 표시"},error:"훅 목록 표시 실패: {{error}}"},debug:{description:"에이전트 동작 모니터링을 위한 디버그 훅 활성화",options:{data:"디버그 출력에 전체 데이터 기록",performance:"성능 모니터링 훅 활성화",stats:"통계 수집 훅 활성화",all:"모든 디버그 훅 활성화"},added:{debug:"디버그 로그 훅을 추가했습니다",performance:"성능 모니터링 훅을 추가했습니다",stats:"통계 수집 훅을 추가했습니다",basic:"기본 디버그 훅을 추가했습니다"},success:"디버그 훅이 활성화되었습니다 ({{count}} 핸들러 등록됨)",error:"디버그 훅 활성화 실패: {{error}}"},security:{description:"접근 제어 및 모니터링을 위한 보안 훅 활성화",options:{block:"차단할 도구의 쉼표 구분 목록",maxPrompt:"최대 허용 프롬프트 길이 (기본값: 10000)"},success:"보안 훅이 활성화되었습니다",blockedTools:"차단된 도구: {{tools}}",maxPrompt:"최대 프롬프트 길이: {{length}} 문자",error:"보안 훅 활성화 실패: {{error}}"},clear:{description:"등록된 모든 훅 제거",success:"모든 훅이 제거되었습니다",error:"훅 제거 실패: {{error}}"},test:{description:"테스트 데이터로 훅을 트리거하여 테스트",argument:{hookType:"테스트할 특정 훅 유형 (선택사항)"},invalidType:"잘못된 훅 유형: {{type}}",triggered:"훅을 트리거했습니다: {{type}}",result:"결과: {{result}}",allTriggered:"모든 훅이 성공적으로 트리거되었습니다",error:"훅 테스트 실패: {{error}}"},register:{description:"파일에서 사용자 정의 훅 핸들러 등록",argument:{hookType:"핸들러를 등록할 훅 유형",handlerFile:"핸들러 파일 경로 (기본 함수를 내보내야 함)"},invalidType:"잘못된 훅 유형: {{type}}",invalidHandler:"핸들러 파일은 기본 함수를 내보내야 합니다",success:"{{file}}에서 {{type}}의 핸들러를 등록했습니다",error:"훅 등록 실패: {{error}}"},status:{description:"현재 훅 구성 및 통계 정보 표시",title:"\uD83D\uDCCB 훅 상태",error:"훅 상태 조회 실패: {{error}}"}}}},6150(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Basisvereiste",projectDir:"Projectmap (werk hier): {{cwd}}",skillsInstruction:"Gebruik het read_skill-hulpmiddel om de volledige instructies van een vaardigheid te laden wanneer de taak overeenkomt met de beschrijving.",toolArgSizeLimit:'Overschrijd nooit {{maxChars}} tekens in \xe9\xe9n tool-aanroepargument (bijv. de content van een write). De API kan grotere payloads afkappen en "Unterminated string in JSON"-fouten veroorzaken. Splits lange bestanden of scripts in meerdere write-aanroepen (bijv. per bestand of per stuk van onder {{maxChars}} tekens).',toolCallJsonFormat:'Tool-aanroepargumenten moeten geldige JSON zijn: elke sleutel en elke tekenreekswaarde tussen dubbele aanhalingstekens. Voorbeeld voor write: {"path": "bestand.md", "content": "inhoud hier"}. Laat geen aanhalingstekens weg bij sleutels of waarden (bijv. path: bestand.md is ongeldig).'},errors:{missingPromptFiles:"ontbrekende vereiste promptbestanden in {{dir}}:",runInit:"Voer 'pithosai init' uit in de projectroot om .pithosai met sjablonen aan te maken.",noApiKey:"Geen API-sleutel gevonden. Stel DEEPSEEK_API_KEY of OPENROUTER_API_KEY in.",ollamaNotConfigured:"Ollama is niet geconfigureerd. Stel OPENAI_LOCAL_API_BASE in of gebruik een project met lokaal model.",noValidTemplateFiles:"geen geldige sjabloonbestanden in {{dir}}. Verwacht *-<lang>.md (bijv. IDENTITY-ja.md). Voer 'pithosai init' uit om .pithosai met sjablonen aan te maken.",runTimeout:"Agent-run timeout na {{seconds}} seconden. Gebruik --timeout <seconden> of PITHOSAI_TIMEOUT_MS om aan te passen.",agentRunFailed:"Uitvoering mislukt: {{message}}",unknownRunError:"Onbekende fout"},warnings:{sessionAppend:"sessie toevoegen: {{message}}",apiRetry:"API-fout bij poging {{attempt}}/{{max}}; opnieuw proberen..."},reasoner:{thinkingHeader:"\n--- Denken:\n",replyHeader:"\n\n--- Antwoord:\n"},run:{cwd:"cwd {{cwd}}",request:"verzoek: {{request}}",interactivePrompt:"Jij: ",tuiYouLabel:"Jij:",interactiveExitHint:"Beantwoord of voer een nieuw verzoek in (typ 'exit' of 'quit' om de CLI te verlaten).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Interactieve modus — Agent (volledige tools) ---",interactiveModeAgentTips:"- Volledige toolset (lezen, schrijven, uitvoeren, afhankelijk van configuratie).\n- Beurten worden per taak in de lokale database opgeslagen.\n- `/new` wijst een nieuwe taak-id toe; eerdere berichten worden niet geladen.\n- `/shell <commando>` voor shell; `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken.\n- `/list-skill`, `/install-skill` en `/remove-skill` komen overeen met `pithosai skills list|install|remove` (ClawHub). Ctrl+S stopt, Ctrl+P pauzeert.",interactiveModeDialogTitle:"--- Interactieve modus — Dialoog (alleen-lezen Q&A) ---",interactiveModeDialogTips:"- Alleen read-only tools (geen shell, geen bestandsbewerking of opdrachten).\n- Beurten worden per taak in de lokale database opgeslagen.\n- `/new` wijst een nieuwe taak-id toe; eerdere berichten worden niet geladen.\n- `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken.\n- `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub), zoals de `pithosai skills`-CLI.",interactiveModePlanTitle:"--- Planmodus ---",interactiveModePlanTips:"- Elk antwoord wordt weggeschreven naar `<slug>-plan.md` in de projectmap (de eerste regel van het verzoek be\xefnvloedt de bestandsnaam).\n- Alleen read-only tools; shell en muterende tools uitgeschakeld.\n- `/new` wijst een nieuwe taak-id toe.\n- `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken.\n- `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub), zoals de `pithosai skills`-CLI.\n- Na elke run kunt u verdergaan met een nieuw planverzoek bij de prompt (zoals agent/dialog).",list:{noPersistedTasks:"Geen opgeslagen taken gevonden.",createTasksFirstHint:"Maak eerst taken aan met `pithosai task`.",persistedTasksHeader:"--- Opgeslagen taken ({{count}}) ---",selectTaskHint:"Gebruik `/select <index>` om een taak uit te voeren.",noTasksCached:"Geen taken in cache. Voer eerst `/list` uit.",invalidIndex:"Ongeldige index {{index}}. Geldig bereik: 0-{{maxIndex}}.",selectUsage:"Gebruik: /select <index>",selectedTask:"Taak #{{index}} geselecteerd."},skillSlash:{installUsage:"Gebruik: /install-skill [--force] [skill-naam]",removeUsage:"Gebruik: /remove-skill <skill-naam>",listNoExtra:"/list-skill accepteert geen argumenten.",failed:"Skill-opdracht mislukt: {{message}}"},show:{title:"Huidige taak",field:"Veld",value:"Waarde",taskId:"taskId",mode:"modus",model:"model",status:"status",messageCount:"aantalBerichten",usageInput:"gebruik.invoer",usageOutput:"gebruik.uitvoer",usageCacheRead:"gebruik.cacheLezen",usageCacheWrite:"gebruik.cacheSchrijven",usageTotalTokens:"gebruik.totaalTokens"},showTask:{title:"Taak Q&A",taskIdLabel:"Taak-ID",turnHeading:"Beurt {{index}}",questionLabel:"Vraag",answerLabel:"Antwoord",createdLabel:"Aangemaakt",emptyQuestion:"(lege vraag)",emptyAnswer:"(nog geen assistenttekst)",emptyNoMessages:"Nog geen gebruikersberichten voor deze taak.",previewDocumentTitle:"Taak Q&A"},showPrompt:{previewDocumentTitle:"Systeemprompt",previewHeading:"Systeemprompt"},shellHint:"Gebruik '/shell <commando>' om shell-commando's uit te voeren (bijvoorbeeld: '/shell ls -la').",replIntroDialog:"Dialoogmodus: alleen lezen — `/shell` uit. `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken. `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub).",replIntroPlan:"Planmodus: elk antwoord naar `<slug>-plan.md` (eerste regel be\xefnvloedt de naam). `/shell` uit; minimale uitvoer tot klaar. `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken. `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub).",newSessionHint:"Gebruik '/new <verzoek>' om een nieuwe sessie te starten (zonder chatgeschiedenis).",newSessionNoHistory:"Nieuwe sessie in gebruik (zonder chatgeschiedenis).",controlHint:"Druk op Ctrl+S om de lopende agent te stoppen, Ctrl+P om te pauzeren en subopdrachten in te voeren.",replTabCompletionHint:"Tab om slash-commando's aan te vullen (bijv. /list, /list-skill, /show) of exit/quit.",tuiScrollTranscriptHint:"In de terminal-UI: muiswiel, pijltjes, Page Up/Down, Ctrl+U/Ctrl+F (pagina). Ctrl+U/F scrollen het logboek. Ctrl+D blijft EOF/afsluiten bij lege regel of vooruit wissen tijdens typen.",agentStopped:"Agent gestopt.",pauseHeader:"--- Agent gepauzeerd ---",pauseCurrentRequest:"Huidig verzoek: {{request}}",pauseHelp:"Opdrachten: 'continue' of 'c' om door te gaan, 'exit' of 'e' om af te sluiten, of typ een nieuw verzoek om het huidige te vervangen.",pausePrompt:"[gepauzeerd] ",pauseRequestUpdated:"Verzoek bijgewerkt naar: {{request}}"},shell:{noCommand:"Geen commando opgegeven na /shell-voorvoegsel. Gebruik: /shell <commando>",executionError:"Fout bij het uitvoeren van shell-commando: {{error}}",executing:"[shell] Uitvoeren: {{command}}",errorNoCommand:"Geen commando opgegeven na /shell-voorvoegsel.",errorSpawnFailed:"Proces starten mislukt: {{message}}",errorTimedOut:"Commando verlopen na {{seconds}} seconden",logFailed:"Shell-commando mislukt: {{command}} (afsluitcode: {{code}})",logExecutionError:"Shell-commando uitvoeringsfout: {{message}}",resultCommand:"Commando: {{command}}",resultExitCode:"Afsluitcode: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Geslaagd:",resultSuccessYes:"Ja",resultSuccessNo:"Nee",resultOutput:"Uitvoer:",resultError:"Fout:"},init:{invalidType:'ongeldige --type "{{value}}"; kies: {{choices}}',invalidLang:'ongeldige --lang "{{value}}"; kies: {{choices}}',templatesDirNotFound:"sjablonenmap niet gevonden: {{dir}}",createdPromptTemplates:"{{dir}} aangemaakt (prompt-sjablonen)",createdSessions:"{{dir}} aangemaakt (sessiegeschiedenis)",initialized:"{{type}}-project ge\xefnitialiseerd in {{targetDir}}",promptFilesIn:"promptbestanden in {{pithosaiDir}}, sessiedata in {{sessionsDir}}",runHint:'voer "pithosai -C {{targetDir}} \\"jouw verzoek\\"" uit om te starten.',createdFile:"{{path}} aangemaakt",roleAlreadyAdded:"rol {{role}} staat al in .pithosai; overslaan.",addedRoleTemplates:"rolsjablonen toegevoegd aan {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: voorbeeld gesloten ({{source}})",skipped:"Browservoorbeeld overgeslagen (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Geef precies markdown of path op (niet beide, niet geen).",errorEmpty:"Markdown-inhoud is leeg.",errorFileOutside:"path moet binnen de projectmap blijven.",errorNotAFile:"path is geen gewoon bestand.",errorFileTooLarge:"Bestand is groter dan {{maxBytes}} bytes.",errorFileRead:"Bestand lezen mislukt: {{message}}",sourceInline:"inline Markdown",sourceFile:"bestand {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"E-mail mag niet leeg zijn voor heartbeat. Configureer e-mail voor rol {{role}} in de email_roles-tabel in de sqlite3-database.",loadedState:"Heartbeat-status geladen uit SQLite voor e-mail {{email}} en rol {{role}}, statussen: {{states}}",fetchFound:"Heartbeat-inbox ophalen vond {{count}} nieuwe taken: {{ids}}",savedState:"Heartbeat-status opgeslagen in SQLite voor e-mail {{email}} en rol {{role}}",mergedAndNext:"{{merged}} taken samengevoegd in status, volgende om te verwerken: {{stateSummary}}",replyEmailFailed:"Heartbeat-antwoordmail verzenden mislukt: {{error}}",taskFailed:"Heartbeat-taak mislukt: {{error}}",failureReplyEmailFailed:"Heartbeat-foutmelding-mail verzenden mislukt: {{error}}"},cli:{description:"Pithosai: implementeert code of projecten vanuit een verzoek in natuurlijke taal. Rolprompts worden tijdens runtime geladen vanuit de SQLite-database (met optionele fallback naar .pithosai/<role>/*.md). Maak een project met 'pithosai init'.",versionOption:"versie tonen",roleOption:"rol (sjabloonset voor init); sjablonen in templates/<role>/",langOption:"taal voor prompts en init-sjablonen: en, zh (standaard: en)",interactiveModeOption:"interactieve modus starten zonder verzoek; modustips tonen en om invoer vragen",initDescription:"Nieuw project en .pithosai/ directorystructuur aanmaken. Rolprompts worden tijdens runtime geladen vanuit de SQLite-database (met optionele fallback naar .pithosai/<role>/*.md).",initTypeOption:"projecttype: js, ts of python",initExamples:"\nVoorbeelden:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Rolsjablonen toevoegen aan .pithosai/<role>/ in het project",addRoleArgument:"rol om toe te voegen (bijv. PM, QA)",requestArgument:'wat te bouwen (bijv. "Een CLI die CSV naar JSON converteert"). Weglaten toont help.',cwdOption:"projectmap (standaard: huidige map)",skillsDirOption:"vaardighedenmap voor read_skill (standaard: ./.pithosai/skills of PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner (denken)-model gebruiken; standaard is DeepSeek Coder",chatOption:"DeepSeek Chat-model gebruiken (algemene chat, geen code); standaard is DeepSeek Coder",cursorOption:"Cursor CLI-model gebruiken (auth via cursor-agent login, geen API-sleutel nodig). Optioneel model opgeven: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"max. agent-runtijd in seconden (standaard: 1800). Overschrijven met PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"interactieve prompt uitschakelen (standaard: na elk antwoord om volgende bericht vragen)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Plan genereren…",waitingReply:"Wachten op antwoord…",runningReply:"Bezig met uitvoeren…",resultPreviewOpening:"Voorbeeld openen in de browser…",resultPreviewTitle:"Pithosai-resultaat",resultPreviewFailed:"Voorbeeld openen mislukt: {{message}}",resultPreviewCopy:"Markdown kopi\xebren",resultPreviewClose:"Sluiten",resultPreviewCopied:"Gekopieerd naar klembord",resultPreviewTerminalHint:"↑↓ of j/k \xb7 PgUp/PgDn of Ctrl+U/Ctrl+D \xb7 Home/End of gg/G \xb7 q/Esc sluiten",runExamples:'\nVoorbeelden:\n pithosai "Voeg een REST-endpoint toe die de huidige tijd teruggeeft"\n pithosai -C ./my-app "Tests uitvoeren en fouten herstellen"\n pithosai -i # interactieve modus: laatste sessie laden, dan om verzoeken vragen\n pithosai --no-interactive "Een keer" # \xe9\xe9n antwoord, geen vervolgvraag\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Gebruik:",helpArguments:"Argumenten:",helpOptions:"Opties:",helpCommands:"Commando's:",helpGlobalOptions:"Globale opties:",helpOption:"help voor commando tonen",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Bewaak het takenbestand en verwerk taken \xe9\xe9n voor \xe9\xe9n in hetzelfde proces",taskFileOption:"Pad naar taken-Markdown (standaard: prompts.md in projectroot)",taskModelOption:"Modelcode voor de taak (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Starten met nieuwe sessie (geen chatgeschiedenis)",taskExamples:"\nVoorbeelden:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Taak niet gevonden: {{taskId}}",taskAgentCompleted:"Agent voltooid.",taskAgentRunFailed:"Agentrun mislukt.",taskDone:"Klaar",taskFailed:"Taak mislukt: {{message}}",taskProcessingHeader:"--- Taak verwerken ---",taskLabelId:"id:",taskLabelTitle:"titel:",taskLabelStatus:"status:",taskLabelDescription:"beschrijving:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Processor starten voor lopende taak {{id}} ({{title}}).",taskNoPending:"Geen openstaande taken.",taskPickedTask:"Taak {{id}} ({{title}}) gekozen; processor starten.",taskProcessorFailed:"Taakprocessor mislukt: {{message}}",taskWatcherRunning:"Taakwatcher actief. Ctrl+C om te stoppen.",memorizeDescription:"Schrijft .pithosai/<role>/memory.md met samenvattingen van taken waaraan de rol deelnam (persistente taakberichten in het bereik).",memorizeStartOption:"Start bereik: YYYY-MM-DD of ISO-datum/tijd",memorizeEndOption:"Einde bereik: YYYY-MM-DD of ISO-datum/tijd",memorizeRoleRequired:"Rol is verplicht (-r/--role of globale --role).",memorizeWrote:"Geschreven: {{path}} ({{count}} taak/taken).",memorizeNoTasks:"Geen taken in bereik voor rol {{role}}; alleen kop naar {{path}}.",memorizeDateError:"Ongeldig datumbereik: {{message}}",memorizeNoLlmOption:"LLM-samenvatting overslaan; alleen gestructureerd geheugen schrijven (zelfde als PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"LLM-samenvatting mislukt ({{message}}); gestructureerd geheugen zonder samenvatting geschreven.",memorizeExamples:"\nVoorbeelden:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Krijg shell-commando's voor een verzoek (alleen Ollama)",argument:"Wat je wilt doen (bijv. grote bestanden in huidige map lijsten)",loading:"Commando's ophalen...",examples:'\nVoorbeelden:\n $ pithosai shell-tips lijst json-bestanden in huidige map\n $ pithosai shell-tips "vind en vervang foo door bar in alle .js"'},writer:{description:"Genereer tekst voor een verzoek (Ollama qwen2.5:14b)",argument:"Wat te schrijven (bijv. korte e-mail om meeting af te zeggen)",loading:"Schrijven...",examples:'\nVoorbeelden:\n $ pithosai writer korte e-mail meeting afzeggen\n $ pithosai writer "drie bulletpoints voor project kickoff"'},skills:{installing:"Vaardigheden installeren in {{dir}}",fetchingList:"Beschikbare vaardigheden ophalen van ClawHub...",fetchingIndex:"Vaardighedenindex ophalen van {{url}}",notFound:"Vaardigheid '{{name}}' niet gevonden",noSkillsAvailable:"Geen vaardigheden beschikbaar van ClawHub",noSkillsFound:"Geen vaardigheden gevonden",downloadFailed:"Downloaden van vaardigheid '{{name}}' mislukt: {{error}}",installed:"Vaardigheid '{{name}}' ge\xefnstalleerd",complete:"Installatie voltooid: {{count}} van {{total}} vaardigheden ge\xefnstalleerd",alreadyInstalled:"Vaardigheid '{{name}}' al ge\xefnstalleerd (gebruik --force om opnieuw te installeren)",downloading:"Vaardigheid '{{name}}' downloaden van {{url}}",noSkillsDir:"Geen vaardighedenmap gevonden. Installeer eerst vaardigheden.",noSkillsInstalled:"Geen vaardigheden ge\xefnstalleerd",installedList:"Ge\xefnstalleerde vaardigheden ({{count}} totaal) in {{dir}}:",notInstalled:"Vaardigheid '{{name}}' is niet ge\xefnstalleerd",removed:"Vaardigheid '{{name}}' verwijderd"},skillConvert:{welcome:"Vaardigheden-conversiesysteem - Succesvolle vaardigheden omzetten naar permanente tools",listHeader:"Vaardigheden-conversieanalyse ({{totalSkills}} vaardigheden, {{totalExecutions}} uitvoeringen)",noSuggestions:"Geen vaardigheden bereiken de conversiedrempel van {{threshold}}.",suggestedConversions:"Voorgestelde conversies:",convertHint:"Gebruik 'pithosai skill-convert convert <vaardigheidsnaam>' om een vaardigheid te converteren.",skillNotFound:"Vaardigheid '{{skillName}}' niet gevonden of niet leesbaar: {{error}}",alreadyConverted:"Vaardigheid '{{skillName}}' is al geconverteerd naar een tool.",useForceHint:"Gebruik --force om opnieuw te converteren.",conversionReportHeader:"Conversierapport voor '{{skillName}}':",conversionScore:"Conversiescore",suggestedType:"Voorgesteld type",ready:"Klaar voor conversie",estimatedBenefits:"Geschatte voordelen",performance:"Prestatieverbetering",reliability:"Betrouwbaarheidsverbetering",usability:"Gebruiksvriendelijkheidsverbetering",parameters:"Parameters",notReadyWarning:"Deze vaardigheid is niet klaar voor automatische conversie.",moreUsageHint:"Gebruik de vaardigheid vaker of gebruik --force om conversie te forceren.",dryRunComplete:"Proefrun voltooid. Geen wijzigingen aangebracht.",confirmConversion:"'{{skillName}}' converteren naar een permanent tool?",conversionCancelled:"Conversie geannuleerd.",converting:"'{{skillName}}' wordt geconverteerd naar tool...",conversionSuccess:"'{{skillName}}' succesvol geconverteerd naar '{{toolName}}'.\nTool opgeslagen in: {{toolPath}}",usageExample:"Gebruiksvoorbeeld:",nextSteps:"Volgende stappen:",restartAgent:"Herstart de agent om het nieuwe tool te laden",testTool:"Tool testen: <toolnaam> --help",manageTools:"Tools beheren: pithosai skill-convert tools",listError:"Fout bij het oplijsten van vaardigheden: {{error}}",conversionError:"Fout bij het converteren van '{{skillName}}': {{error}}",skillStatsHeader:"Statistieken voor '{{skillName}}':",generalStats:"Algemene statistieken",totalExecutions:"Totaal uitvoeringen",successful:"Geslaagd",failed:"Mislukt",avgTime:"Gemiddelde uitvoeringstijd",lastUsed:"Laatst gebruikt",recentExecutions:"Recente uitvoeringen",commonParameters:"Veelgebruikte parameters",overallStatsHeader:"Totale vaardighedenstatistieken",overallStats:"Totale statistieken",totalSkillsTracked:"Totaal bijgehouden vaardigheden",avgSuccessRate:"Gemiddeld slagingspercentage",topSkills:"Meest gebruikte vaardigheden",conversionSuggestions:"Conversiesuggesties",statsError:"Fout bij het ophalen van statistieken: {{error}}",confirmClearAll:"ALLE uitvoeringsrecords van vaardigheden wissen? Dit kan niet ongedaan worden gemaakt.",allRecordsCleared:"Alle uitvoeringsrecords van vaardigheden zijn gewist.",skillRecordsCleared:"Uitvoeringsrecords van '{{skillName}}' zijn gewist.",clearCancelled:"Wisbewerking geannuleerd.",specifySkillOrAll:"Geef een vaardigheidsnaam op of gebruik --all",clearError:"Fout bij het wissen van records: {{error}}",noConvertedTools:"Geen geconverteerde tools gevonden.",convertedToolsHeader:"Geconverteerde tools:",originalSkill:"Oorspronkelijke vaardigheid",converted:"Geconverteerd op",usageCount:"Gebruiksaantal",toolsError:"Fout bij het beheren van tools: {{error}}",confirmRemoveTool:"Tool '{{toolName}}' verwijderen?",toolRemoved:"Tool '{{toolName}}' verwijderd.",toolRemoveFailed:"Verwijderen van tool '{{toolName}}' mislukt.",removeCancelled:"Toolverwijdering geannuleerd.",toolEnabled:"Tool '{{toolName}}' ingeschakeld.",toolEnableFailed:"Inschakelen van tool '{{toolName}}' mislukt.",toolDisabled:"Tool '{{toolName}}' uitgeschakeld.",toolDisableFailed:"Uitschakelen van tool '{{toolName}}' mislukt.",noStatsForSkill:"Geen statistieken gevonden voor vaardigheid '{{skillName}}'."},hooks:{description:"Agent-hooks beheren voor debugging, beveiliging en monitoring",list:{description:"Alle geregistreerde hooks weergeven",title:"\uD83D\uDCCB Geregistreerde hooks",total:"Totaal: {{total}} handlers",options:{verbose:"Gedetailleerde handler-informatie weergeven"},error:"Kan hooks niet weergeven: {{error}}"},debug:{description:"Debug-hooks inschakelen om het gedrag van de agent te monitoren",options:{data:"Volledige gegevens loggen in debug-uitvoer",performance:"Prestatie-monitoring-hooks inschakelen",stats:"Statistiekverzamelings-hooks inschakelen",all:"Alle debug-hooks inschakelen"},added:{debug:"Debug-logging-hooks toegevoegd",performance:"Prestatie-monitoring-hooks toegevoegd",stats:"Statistiekverzamelings-hooks toegevoegd",basic:"Basis debug-hooks toegevoegd"},success:"Debug-hooks ingeschakeld ({{count}} handlers geregistreerd)",error:"Kan debug-hooks niet inschakelen: {{error}}"},security:{description:"Beveiligingshooks inschakelen voor toegangscontrole en monitoring",options:{block:"Kommagescheiden lijst van te blokkeren tools",maxPrompt:"Maximale toegestane promptlengte (standaard: 10000)"},success:"Beveiligingshooks ingeschakeld",blockedTools:"Geblokkeerde tools: {{tools}}",maxPrompt:"Maximale promptlengte: {{length}} tekens",error:"Kan beveiligingshooks niet inschakelen: {{error}}"},clear:{description:"Alle geregistreerde hooks wissen",success:"Alle hooks gewist",error:"Kan hooks niet wissen: {{error}}"},test:{description:"Hooks testen door ze te activeren met testgegevens",argument:{hookType:"Specifiek hook-type om te testen (optioneel)"},invalidType:"Ongeldig hook-type: {{type}}",triggered:"Hook geactiveerd: {{type}}",result:"Resultaat: {{result}}",allTriggered:"Alle hooks succesvol geactiveerd",error:"Kan hooks niet testen: {{error}}"},register:{description:"Aangepaste hook-handler registreren vanuit een bestand",argument:{hookType:"Hook-type om de handler voor te registreren",handlerFile:"Pad naar handler-bestand (moet een standaardfunctie exporteren)"},invalidType:"Ongeldig hook-type: {{type}}",invalidHandler:"Handler-bestand moet een standaardfunctie exporteren",success:"Handler voor {{type}} geregistreerd vanuit {{file}}",error:"Kan hook niet registreren: {{error}}"},status:{description:"Huidige hook-configuratie en statistieken weergeven",title:"\uD83D\uDCCB Hook-status",error:"Kan hook-status niet ophalen: {{error}}"}}}},8112(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"Requisito base",projectDir:"Diret\xf3rio do projeto (trabalhar aqui): {{cwd}}",skillsInstruction:"Use a ferramenta read_skill para carregar as instru\xe7\xf5es completas de uma habilidade quando a tarefa corresponder \xe0 sua descri\xe7\xe3o.",toolArgSizeLimit:"Nunca exceda {{maxChars}} caracteres num \xfanico argumento de chamada a ferramenta (ex.: o content de um write). A API pode truncar payloads maiores e causar erros \xabUnterminated string in JSON\xbb. Para ficheiros ou scripts longos, divida em v\xe1rias chamadas write (por ficheiro ou por bloco de menos de {{maxChars}} caracteres).",toolCallJsonFormat:'Os argumentos de chamada a ferramenta devem ser JSON v\xe1lido: cada chave e cada valor de cadeia entre aspas duplas. Exemplo para write: {"path": "ficheiro.md", "content": "conte\xfado aqui"}. N\xe3o omita aspas em chaves ou valores (ex.: path: ficheiro.md \xe9 inv\xe1lido).'},errors:{missingPromptFiles:"arquivos de prompt obrigat\xf3rios em falta em {{dir}}:",runInit:"Execute 'pithosai init' na raiz do projeto para criar .pithosai com os modelos.",noApiKey:"Chave API n\xe3o encontrada. Defina DEEPSEEK_API_KEY ou OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama n\xe3o configurado. Defina OPENAI_LOCAL_API_BASE ou use um projeto com modelo local.",noValidTemplateFiles:"nenhum ficheiro de modelo v\xe1lido em {{dir}}. Esperado *-<lang>.md (ex.: IDENTITY-ja.md). Execute 'pithosai init' para criar .pithosai com os modelos.",runTimeout:"Execu\xe7\xe3o do agente expirou ap\xf3s {{seconds}} segundos. Use --timeout <segundos> ou PITHOSAI_TIMEOUT_MS para ajustar.",agentRunFailed:"Falha na execu\xe7\xe3o: {{message}}",unknownRunError:"Erro desconhecido"},warnings:{sessionAppend:"anexar sess\xe3o: {{message}}",apiRetry:"Erro de API na tentativa {{attempt}}/{{max}}; a tentar de novo..."},reasoner:{thinkingHeader:"\n--- Pensamento:\n",replyHeader:"\n\n--- Resposta:\n"},run:{cwd:"cwd {{cwd}}",request:"pedido: {{request}}",interactivePrompt:"Voc\xea: ",tuiYouLabel:"Voc\xea:",interactiveExitHint:"Responda ou insira um novo pedido (digite 'exit' ou 'quit' para sair da CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Modo interativo — Agente (ferramentas completas) ---",interactiveModeAgentTips:"- Conjunto completo de ferramentas (leitura, escrita, execu\xe7\xe3o, conforme configura\xe7\xe3o).\n- As mensagens s\xe3o guardadas por tarefa na base de dados local.\n- `/new` atribui um novo id de tarefa; mensagens anteriores n\xe3o s\xe3o carregadas.\n- `/shell <comando>` para shell; `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas.\n- `/list-skill`, `/install-skill` e `/remove-skill` equivalem a `pithosai skills list|install|remove` (ClawHub). Ctrl+S para, Ctrl+P pausa.",interactiveModeDialogTitle:"--- Modo interativo — Di\xe1logo (Q&A s\xf3 de leitura) ---",interactiveModeDialogTips:"- Apenas ferramentas de leitura (sem shell, edi\xe7\xe3o de ficheiros ou execu\xe7\xe3o de comandos).\n- As mensagens s\xe3o guardadas por tarefa na base de dados local.\n- `/new` atribui um novo id de tarefa; mensagens anteriores n\xe3o s\xe3o carregadas.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas.\n- `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub) como a CLI `pithosai skills`.",interactiveModePlanTitle:"--- Modo plano ---",interactiveModePlanTips:"- Cada resposta \xe9 escrita em `<slug>-plan.md` no diret\xf3rio do projeto (a primeira linha do pedido influencia o nome).\n- Apenas ferramentas de leitura; shell e ferramentas mutadoras desativadas.\n- `/new` atribui um novo id de tarefa.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas.\n- `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub) como a CLI `pithosai skills`.\n- Ap\xf3s cada execu\xe7\xe3o pode continuar com outro pedido de plano no prompt (como agent/dialog).",list:{noPersistedTasks:"Nenhuma tarefa persistida encontrada.",createTasksFirstHint:"Crie tarefas primeiro usando `pithosai task`.",persistedTasksHeader:"--- Tarefas persistidas ({{count}}) ---",selectTaskHint:"Use `/select <index>` para executar uma tarefa.",noTasksCached:"Nenhuma tarefa em cache. Execute `/list` primeiro.",invalidIndex:"\xcdndice inv\xe1lido {{index}}. Intervalo v\xe1lido: 0-{{maxIndex}}.",selectUsage:"Uso: /select <index>",selectedTask:"Tarefa #{{index}} selecionada."},skillSlash:{installUsage:"Uso: /install-skill [--force] [nome-da-skill]",removeUsage:"Uso: /remove-skill <nome-da-skill>",listNoExtra:"/list-skill n\xe3o aceita argumentos.",failed:"Comando de skill falhou: {{message}}"},show:{title:"Tarefa atual",field:"Campo",value:"Valor",taskId:"taskId",mode:"modo",model:"modelo",status:"status",messageCount:"quantidadeMensagens",usageInput:"uso.entrada",usageOutput:"uso.sa\xedda",usageCacheRead:"uso.cacheLeitura",usageCacheWrite:"uso.cacheEscrita",usageTotalTokens:"uso.totalTokens"},showTask:{title:"P&R da tarefa",taskIdLabel:"ID da tarefa",turnHeading:"Turno {{index}}",questionLabel:"Pergunta",answerLabel:"Resposta",createdLabel:"Criado",emptyQuestion:"(pergunta vazia)",emptyAnswer:"(sem resposta em texto do assistente)",emptyNoMessages:"Ainda n\xe3o h\xe1 mensagens de utilizador para esta tarefa.",previewDocumentTitle:"P&R da tarefa"},showPrompt:{previewDocumentTitle:"Prompt do sistema",previewHeading:"Prompt do sistema"},shellHint:"Use '/shell <comando>' para executar comandos shell (exemplo: '/shell ls -la').",replIntroDialog:"Modo di\xe1logo: apenas leitura — `/shell` desativado. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas. `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub).",replIntroPlan:"Modo plano: cada resposta em `<slug>-plan.md` (primeira linha influencia o nome). `/shell` desativado; sa\xedda m\xednima at\xe9 concluir. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas. `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub).",newSessionHint:"Use '/new <pedido>' para iniciar uma nova sess\xe3o (sem hist\xf3rico de chat).",newSessionNoHistory:"A usar nova sess\xe3o (sem hist\xf3rico de chat).",controlHint:"Pressione Ctrl+S para parar o agente em execu\xe7\xe3o, Ctrl+P para pausar e entrar em subcomandos.",replTabCompletionHint:"Tab para completar comandos com barra (ex.: /list, /list-skill, /show) ou exit/quit.",tuiScrollTranscriptHint:"Na UI do terminal: roda, setas, PgUp/PgDn, Ctrl+U/Ctrl+F (p\xe1gina). Ctrl+U/F rolam o hist\xf3rico. Ctrl+D continua como EOF/sair com linha vazia ou apagar \xe0 frente ao digitar.",agentStopped:"Agente parado.",pauseHeader:"--- Agente em pausa ---",pauseCurrentRequest:"Pedido atual: {{request}}",pauseHelp:"Comandos: 'continue' ou 'c' para continuar, 'exit' ou 'e' para sair, ou digite um novo pedido para substituir o atual.",pausePrompt:"[em pausa] ",pauseRequestUpdated:"Pedido atualizado para: {{request}}"},shell:{noCommand:"Nenhum comando fornecido ap\xf3s o prefixo /shell. Uso: /shell <comando>",executionError:"Erro ao executar comando shell: {{error}}",executing:"[shell] Executando: {{command}}",errorNoCommand:"Nenhum comando fornecido ap\xf3s o prefixo /shell.",errorSpawnFailed:"Falha ao iniciar o processo: {{message}}",errorTimedOut:"Comando expirou ap\xf3s {{seconds}} segundos",logFailed:"Comando shell falhou: {{command}} (c\xf3digo de sa\xedda: {{code}})",logExecutionError:"Erro de execu\xe7\xe3o do comando shell: {{message}}",resultCommand:"Comando: {{command}}",resultExitCode:"C\xf3digo de sa\xedda: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Sucesso:",resultSuccessYes:"Sim",resultSuccessNo:"N\xe3o",resultOutput:"Sa\xedda:",resultError:"Erro:"},init:{invalidType:'--type inv\xe1lido "{{value}}"; escolha: {{choices}}',invalidLang:'--lang inv\xe1lido "{{value}}"; escolha: {{choices}}',templatesDirNotFound:"diret\xf3rio de modelos n\xe3o encontrado: {{dir}}",createdPromptTemplates:"criado {{dir}} (modelos de prompt)",createdSessions:"criado {{dir}} (hist\xf3rico de sess\xf5es)",initialized:"projeto {{type}} inicializado em {{targetDir}}",promptFilesIn:"ficheiros de prompt em {{pithosaiDir}}, dados de sess\xe3o em {{sessionsDir}}",runHint:'execute "pithosai -C {{targetDir}} \\"seu pedido\\"" para come\xe7ar.',createdFile:"criado {{path}}",roleAlreadyAdded:"papel {{role}} j\xe1 presente em .pithosai; a ignorar.",addedRoleTemplates:"modelos de papel adicionados a {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: pr\xe9-visualiza\xe7\xe3o fechada ({{source}})",skipped:"Pr\xe9-visualiza\xe7\xe3o do navegador ignorada (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Forne\xe7a exatamente markdown ou path (n\xe3o ambos, nem nenhum).",errorEmpty:"O conte\xfado Markdown est\xe1 vazio.",errorFileOutside:"path deve ficar dentro do diret\xf3rio do projeto.",errorNotAFile:"path n\xe3o \xe9 um ficheiro normal.",errorFileTooLarge:"O ficheiro \xe9 maior que {{maxBytes}} bytes.",errorFileRead:"N\xe3o foi poss\xedvel ler o ficheiro: {{message}}",sourceInline:"Markdown inline",sourceFile:"ficheiro {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"O e-mail n\xe3o pode estar vazio para o heartbeat. Configure o e-mail do papel {{role}} na tabela email_roles na base de dados sqlite3.",loadedState:"Estado do heartbeat carregado do SQLite para o e-mail {{email}} e o papel {{role}}, estados: {{states}}",fetchFound:"O heartbeat encontrou {{count}} novas tarefas na caixa de entrada: {{ids}}",savedState:"Estado do heartbeat guardado no SQLite para o e-mail {{email}} e o papel {{role}}",mergedAndNext:"{{merged}} tarefas fundidas no estado, pr\xf3xima a processar: {{stateSummary}}",replyEmailFailed:"Falha no envio do e-mail de resposta do heartbeat: {{error}}",taskFailed:"Tarefa do heartbeat falhou: {{error}}",failureReplyEmailFailed:"Falha no envio do e-mail de notifica\xe7\xe3o de falha do heartbeat: {{error}}"},cli:{description:"Pithosai: implementa c\xf3digo ou projetos a partir de um pedido em linguagem natural. Os prompts de fun\xe7\xe3o s\xe3o carregados do banco de dados SQLite em tempo de execu\xe7\xe3o (com fallback opcional para .pithosai/<role>/*.md). Crie um projeto com 'pithosai init'.",versionOption:"mostrar vers\xe3o",roleOption:"papel (conjunto de modelos para init); modelos em templates/<role>/",langOption:"idioma para prompts e modelos init: en, zh (predefinido: en)",interactiveModeOption:"entrar em modo interativo sem pedido; mostrar dicas do modo e pedir entrada",initDescription:"Criar um novo projeto e a estrutura de diret\xf3rio .pithosai/. Os prompts de fun\xe7\xe3o s\xe3o carregados do banco de dados SQLite em tempo de execu\xe7\xe3o (com fallback opcional para .pithosai/<role>/*.md).",initTypeOption:"tipo de projeto: js, ts ou python",initExamples:"\nExemplos:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Adicionar modelos de papel a .pithosai/<role>/ no projeto",addRoleArgument:"papel a adicionar (ex.: PM, QA)",requestArgument:'o que construir (ex.: "Um CLI que converte CSV em JSON"). Se omitir, mostra ajuda.',cwdOption:"diret\xf3rio do projeto (predefinido: diret\xf3rio atual)",skillsDirOption:"diret\xf3rio de habilidades para read_skill (predefinido: ./.pithosai/skills ou PITHOSAI_SKILLS_DIR)",reasonerOption:"usar modelo DeepSeek Reasoner (racioc\xednio); predefinido \xe9 DeepSeek Coder",chatOption:"usar modelo DeepSeek Chat (chat geral, n\xe3o c\xf3digo); predefinido \xe9 DeepSeek Coder",cursorOption:"usar modelo Cursor CLI (autentica\xe7\xe3o via cursor-agent login, sem chave API). Opcionalmente especificar modelo: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"tempo m\xe1ximo de execu\xe7\xe3o do agente em segundos (predefinido: 1800). Sobrescrever com PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"desativar prompt interativo (predefinido: ap\xf3s cada resposta, pedir a seguinte)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Gerando o plano…",waitingReply:"Aguardando resposta…",runningReply:"Executando…",resultPreviewOpening:"Abrindo pr\xe9-visualiza\xe7\xe3o do resultado no navegador…",resultPreviewTitle:"Resultado Pithosai",resultPreviewFailed:"N\xe3o foi poss\xedvel abrir a pr\xe9-visualiza\xe7\xe3o: {{message}}",resultPreviewCopy:"Copiar Markdown",resultPreviewClose:"Fechar",resultPreviewCopied:"Copiado para a \xe1rea de transfer\xeancia",resultPreviewTerminalHint:"↑↓ ou j/k \xb7 PgUp/PgDn ou Ctrl+U/Ctrl+D \xb7 Home/End ou gg/G \xb7 q/Esc fechar",runExamples:'\nExemplos:\n pithosai "Adicionar um endpoint REST que devolve a hora atual"\n pithosai -C ./my-app "Executar testes e corrigir falhas"\n pithosai -i # modo interativo: carregar \xfaltima sess\xe3o e pedir pedidos\n pithosai --no-interactive "Uma vez" # uma resposta, sem pedir seguinte\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Uso:",helpArguments:"Argumentos:",helpOptions:"Op\xe7\xf5es:",helpCommands:"Comandos:",helpGlobalOptions:"Op\xe7\xf5es globais:",helpOption:"mostrar ajuda do comando",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Monitora o ficheiro de tarefas e processa-as uma de cada vez no mesmo processo",taskFileOption:"Caminho para o Markdown das tarefas (predefini\xe7\xe3o: prompts.md na raiz do projeto)",taskModelOption:"Chave do modelo para a tarefa (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Come\xe7ar com uma sess\xe3o nova (sem hist\xf3rico de chat)",taskExamples:"\nExemplos:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Tarefa n\xe3o encontrada: {{taskId}}",taskAgentCompleted:"Agente conclu\xeddo.",taskAgentRunFailed:"Execu\xe7\xe3o do agente falhou.",taskDone:"Conclu\xeddo",taskFailed:"Tarefa falhou: {{message}}",taskProcessingHeader:"--- A processar tarefa ---",taskLabelId:"id:",taskLabelTitle:"t\xedtulo:",taskLabelStatus:"estado:",taskLabelDescription:"descri\xe7\xe3o:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"A iniciar processador para a tarefa em processamento {{id}} ({{title}}).",taskNoPending:"N\xe3o h\xe1 tarefas pendentes.",taskPickedTask:"Tarefa {{id}} ({{title}}) escolhida; a iniciar processador.",taskProcessorFailed:"Processador de tarefas falhou: {{message}}",taskWatcherRunning:"Monitor de tarefas em execu\xe7\xe3o. Ctrl+C para parar.",memorizeDescription:"Escreve .pithosai/<role>/memory.md com resumos das tarefas em que o papel participou (mensagens persistidas no intervalo).",memorizeStartOption:"In\xedcio do intervalo: YYYY-MM-DD ou data/hora ISO",memorizeEndOption:"Fim do intervalo: YYYY-MM-DD ou data/hora ISO",memorizeRoleRequired:"O papel \xe9 obrigat\xf3rio (-r/--role ou --role global).",memorizeWrote:"Gravado {{path}} ({{count}} tarefa(s)).",memorizeNoTasks:"Nenhuma tarefa no intervalo para o papel {{role}}; cabe\xe7alho em {{path}}.",memorizeDateError:"Intervalo de datas inv\xe1lido: {{message}}",memorizeNoLlmOption:"Ignorar resumo por LLM; gravar apenas mem\xf3ria estruturada (igual a PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"Falha no resumo por LLM ({{message}}); mem\xf3ria estruturada gravada sem resumo.",memorizeExamples:"\nExemplos:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"Obter comandos shell para um pedido (apenas Ollama)",argument:"O que pretende fazer (ex. listar ficheiros grandes no diret\xf3rio atual)",loading:"A obter comandos...",examples:'\nExemplos:\n $ pithosai shell-tips listar ficheiros json no diret\xf3rio atual\n $ pithosai shell-tips "encontrar e substituir foo por bar em todos os .js"'},writer:{description:"Gerar texto para um pedido (Ollama qwen2.5:14b)",argument:"O que escrever (ex. email curto a recusar uma reuni\xe3o)",loading:"A escrever...",examples:'\nExemplos:\n $ pithosai writer email curto a recusar reuni\xe3o\n $ pithosai writer "tr\xeas pontos para um kickoff de projeto"'},skills:{installing:"A instalar habilidades em {{dir}}",fetchingList:"A obter habilidades dispon\xedveis do ClawHub...",fetchingIndex:"A obter \xedndice de habilidades de {{url}}",notFound:"Habilidade '{{name}}' n\xe3o encontrada",noSkillsAvailable:"Nenhuma habilidade dispon\xedvel do ClawHub",noSkillsFound:"Nenhuma habilidade encontrada",downloadFailed:"Falha ao descarregar habilidade '{{name}}': {{error}}",installed:"Habilidade '{{name}}' instalada",complete:"Instala\xe7\xe3o conclu\xedda: {{count}} de {{total}} habilidades instaladas",alreadyInstalled:"Habilidade '{{name}}' j\xe1 instalada (use --force para reinstalar)",downloading:"A descarregar habilidade '{{name}}' de {{url}}",noSkillsDir:"Nenhum diret\xf3rio de habilidades encontrado. Instale habilidades primeiro.",noSkillsInstalled:"Nenhuma habilidade instalada",installedList:"Habilidades instaladas ({{count}} total) em {{dir}}:",notInstalled:"Habilidade '{{name}}' n\xe3o est\xe1 instalada",removed:"Habilidade '{{name}}' removida"},skillConvert:{welcome:"Sistema de convers\xe3o de habilidades - Converter habilidades bem-sucedidas em ferramentas permanentes",listHeader:"An\xe1lise de convers\xe3o de habilidades ({{totalSkills}} habilidades, {{totalExecutions}} execu\xe7\xf5es)",noSuggestions:"Nenhuma habilidade atinge o limiar de convers\xe3o de {{threshold}}.",suggestedConversions:"Convers\xf5es sugeridas:",convertHint:"Use 'pithosai skill-convert convert <nome-habilidade>' para converter uma habilidade.",skillNotFound:"Habilidade '{{skillName}}' n\xe3o encontrada ou ileg\xedvel: {{error}}",alreadyConverted:"A habilidade '{{skillName}}' j\xe1 foi convertida em ferramenta.",useForceHint:"Use --force para converter novamente.",conversionReportHeader:"Relat\xf3rio de convers\xe3o de '{{skillName}}':",conversionScore:"Pontua\xe7\xe3o de convers\xe3o",suggestedType:"Tipo sugerido",ready:"Pronto para convers\xe3o",estimatedBenefits:"Benef\xedcios estimados",performance:"Melhoria de desempenho",reliability:"Melhoria de fiabilidade",usability:"Melhoria de usabilidade",parameters:"Par\xe2metros",notReadyWarning:"Esta habilidade n\xe3o est\xe1 pronta para convers\xe3o autom\xe1tica.",moreUsageHint:"Use a habilidade com mais frequ\xeancia ou use --force para for\xe7ar a convers\xe3o.",dryRunComplete:"Simula\xe7\xe3o conclu\xedda. Nenhuma altera\xe7\xe3o realizada.",confirmConversion:"Converter '{{skillName}}' em ferramenta permanente?",conversionCancelled:"Convers\xe3o cancelada.",converting:"A converter '{{skillName}}' em ferramenta...",conversionSuccess:"'{{skillName}}' convertido com sucesso em '{{toolName}}'.\nFerramenta guardada em: {{toolPath}}",usageExample:"Exemplo de utiliza\xe7\xe3o:",nextSteps:"Pr\xf3ximos passos:",restartAgent:"Reinicie o agente para carregar a nova ferramenta",testTool:"Testar ferramenta: <nome-ferramenta> --help",manageTools:"Gerir ferramentas: pithosai skill-convert tools",listError:"Erro ao listar habilidades: {{error}}",conversionError:"Erro ao converter '{{skillName}}': {{error}}",skillStatsHeader:"Estat\xedsticas de '{{skillName}}':",generalStats:"Estat\xedsticas gerais",totalExecutions:"Execu\xe7\xf5es totais",successful:"Bem-sucedidas",failed:"Falhadas",avgTime:"Tempo m\xe9dio de execu\xe7\xe3o",lastUsed:"\xdaltima utiliza\xe7\xe3o",recentExecutions:"Execu\xe7\xf5es recentes",commonParameters:"Par\xe2metros comuns",overallStatsHeader:"Estat\xedsticas globais de habilidades",overallStats:"Estat\xedsticas globais",totalSkillsTracked:"Total de habilidades rastreadas",avgSuccessRate:"Taxa de sucesso m\xe9dia",topSkills:"Habilidades mais usadas",conversionSuggestions:"Sugest\xf5es de convers\xe3o",statsError:"Erro ao obter estat\xedsticas: {{error}}",confirmClearAll:"Apagar TODOS os registos de execu\xe7\xe3o de habilidades? Esta a\xe7\xe3o n\xe3o pode ser desfeita.",allRecordsCleared:"Todos os registos de execu\xe7\xe3o de habilidades foram apagados.",skillRecordsCleared:"Os registos de execu\xe7\xe3o de '{{skillName}}' foram apagados.",clearCancelled:"Opera\xe7\xe3o de limpeza cancelada.",specifySkillOrAll:"Especifique um nome de habilidade ou use --all",clearError:"Erro ao limpar registos: {{error}}",noConvertedTools:"Nenhuma ferramenta convertida encontrada.",convertedToolsHeader:"Ferramentas convertidas:",originalSkill:"Habilidade original",converted:"Convertido em",usageCount:"N\xfamero de utiliza\xe7\xf5es",toolsError:"Erro ao gerir ferramentas: {{error}}",confirmRemoveTool:"Remover ferramenta '{{toolName}}'?",toolRemoved:"Ferramenta '{{toolName}}' removida.",toolRemoveFailed:"Falha ao remover ferramenta '{{toolName}}'.",removeCancelled:"Remo\xe7\xe3o de ferramenta cancelada.",toolEnabled:"Ferramenta '{{toolName}}' ativada.",toolEnableFailed:"Falha ao ativar ferramenta '{{toolName}}'.",toolDisabled:"Ferramenta '{{toolName}}' desativada.",toolDisableFailed:"Falha ao desativar ferramenta '{{toolName}}'.",noStatsForSkill:"Nenhuma estat\xedstica encontrada para a habilidade '{{skillName}}'."},hooks:{description:"Gerenciar hooks do agente para depura\xe7\xe3o, seguran\xe7a e monitoramento",list:{description:"Listar todos os hooks registrados",title:"\uD83D\uDCCB Hooks registrados",total:"Total: {{total}} manipuladores",options:{verbose:"Mostrar informa\xe7\xf5es detalhadas dos manipuladores"},error:"Falha ao listar hooks: {{error}}"},debug:{description:"Ativar hooks de depura\xe7\xe3o para monitorar o comportamento do agente",options:{data:"Registrar dados completos na sa\xedda de depura\xe7\xe3o",performance:"Ativar hooks de monitoramento de desempenho",stats:"Ativar hooks de coleta de estat\xedsticas",all:"Ativar todos os hooks de depura\xe7\xe3o"},added:{debug:"Hooks de registro de depura\xe7\xe3o adicionados",performance:"Hooks de monitoramento de desempenho adicionados",stats:"Hooks de coleta de estat\xedsticas adicionados",basic:"Hooks de depura\xe7\xe3o b\xe1sicos adicionados"},success:"Hooks de depura\xe7\xe3o ativados ({{count}} manipuladores registrados)",error:"Falha ao ativar hooks de depura\xe7\xe3o: {{error}}"},security:{description:"Ativar hooks de seguran\xe7a para controle de acesso e monitoramento",options:{block:"Lista de ferramentas a bloquear separadas por v\xedrgulas",maxPrompt:"Comprimento m\xe1ximo permitido do prompt (padr\xe3o: 10000)"},success:"Hooks de seguran\xe7a ativados",blockedTools:"Ferramentas bloqueadas: {{tools}}",maxPrompt:"Comprimento m\xe1ximo do prompt: {{length}} caracteres",error:"Falha ao ativar hooks de seguran\xe7a: {{error}}"},clear:{description:"Limpar todos os hooks registrados",success:"Todos os hooks limpos",error:"Falha ao limpar hooks: {{error}}"},test:{description:"Testar hooks disparando-os com dados de teste",argument:{hookType:"Tipo de hook espec\xedfico para testar (opcional)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",triggered:"Hook disparado: {{type}}",result:"Resultado: {{result}}",allTriggered:"Todos os hooks disparados com sucesso",error:"Falha ao testar hooks: {{error}}"},register:{description:"Registrar um manipulador de hook personalizado a partir de um arquivo",argument:{hookType:"Tipo de hook para registrar o manipulador",handlerFile:"Caminho para o arquivo do manipulador (deve exportar uma fun\xe7\xe3o padr\xe3o)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",invalidHandler:"O arquivo do manipulador deve exportar uma fun\xe7\xe3o padr\xe3o",success:"Manipulador para {{type}} registrado de {{file}}",error:"Falha ao registrar hook: {{error}}"},status:{description:"Mostrar configura\xe7\xe3o atual dos hooks e estat\xedsticas",title:"\uD83D\uDCCB Estado dos hooks",error:"Falha ao obter estado dos hooks: {{error}}"}}}},5946(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"基本要求",projectDir:"專案目錄(在此工作):{{cwd}}",skillsInstruction:"當任務與某技能的描述匹配時,使用 read_skill 工具載入該技能的完整說明。",toolArgSizeLimit:"單一工具呼叫參數(如 write 的 content)嚴禁超過 {{maxChars}} 字元,否則可能觸發「Unterminated string in JSON」錯誤。長檔案或腳本請拆成多次 write 呼叫(按檔案或按每段不超過 {{maxChars}} 字元)。",toolCallJsonFormat:'工具呼叫參數必須是合法 JSON:所有鍵和字串值都必須用雙引號包裹。例如 write:{"path": "檔名.md", "content": "內容"}。不要省略鍵或值的引號(如 path: file.md 或 content: 文字 為無效)。'},errors:{missingPromptFiles:"缺少必需的提示檔案,目錄:{{dir}}",runInit:"請在專案根目錄執行 'pithosai init' 以建立 .pithosai 及範本。",noApiKey:"找不到 API 金鑰。請設定 DEEPSEEK_API_KEY 或 OPENROUTER_API_KEY。",ollamaNotConfigured:"未設定 Ollama。請設定 OPENAI_LOCAL_API_BASE 或在專案中設定本地模型。",noValidTemplateFiles:"目錄 {{dir}} 中無有效範本檔案。需要 *-<lang>.md 格式(如 IDENTITY-ja.md)。請執行 'pithosai init' 建立 .pithosai 及範本。",runTimeout:"Agent 執行在 {{seconds}} 秒後逾時。可使用 --timeout <秒> 或 PITHOSAI_TIMEOUT_MS 調整。",agentRunFailed:"執行失敗:{{message}}",unknownRunError:"未知錯誤"},warnings:{sessionAppend:"工作階段附加失敗:{{message}}",apiRetry:"API 錯誤,第 {{attempt}}/{{max}} 次嘗試;正在重試…"},reasoner:{thinkingHeader:"\n--- 思考:\n",replyHeader:"\n\n--- 回覆:\n"},run:{cwd:"工作目錄 {{cwd}}",request:"請求:{{request}}",interactivePrompt:"您:",tuiYouLabel:"您:",interactiveExitHint:"請回答或輸入新請求(輸入 'exit' 或 'quit' 可結束 CLI)。",interactiveModeCwd:"工作目錄:{{cwd}}",interactiveModeAgentTitle:"--- 互動模式 — 代理(完整工具)---",interactiveModeAgentTips:"- 使用完整工具集(讀取、寫入、執行及專案設定的其他工具)。\n- 對話依任務儲存在本機資料庫中。\n- `/new` 會指派新的任務 id,不會載入先前訊息。\n- `/shell <命令>` 執行 shell;`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 用於已持久化任務。\n- `/list-skill`、`/install-skill`、`/remove-skill` 等同 `pithosai skills list|install|remove`(ClawHub)。Ctrl+S 停止,Ctrl+P 暫停。",interactiveModeDialogTitle:"--- 互動模式 — 對話(唯讀問答)---",interactiveModeDialogTips:"- 僅使用唯讀工具(不可用 shell、寫入檔案或執行命令)。\n- 對話依任務儲存在本機資料庫中。\n- 使用 `/new` 會指派新的任務 id,不會載入先前訊息。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),與 `pithosai skills` CLI 相同。",interactiveModePlanTitle:"--- 計畫模式 ---",interactiveModePlanTips:"- 每次回覆會寫入專案目錄下的 `<slug>-plan.md`(請求首行影響檔名)。\n- 僅唯讀工具;shell 與修改類工具不可用。\n- `/new` 會指派新的任務 id。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),與 `pithosai skills` CLI 相同。\n- 每次執行結束後可在提示符繼續輸入新的計畫請求(與 agent/dialog 相同)。",list:{noPersistedTasks:"找不到已持久化的任務。",createTasksFirstHint:"請先使用 `pithosai task` 建立任務。",persistedTasksHeader:"--- 已持久化的任務({{count}})---",selectTaskHint:"使用 `/select <index>` 來執行任務。",noTasksCached:"沒有快取的任務。請先執行 `/list`。",invalidIndex:"無效的索引 {{index}}。有效範圍:0-{{maxIndex}}。",selectUsage:"用法:/select <index>",selectedTask:"已選擇任務 #{{index}}。"},skillSlash:{installUsage:"用法:/install-skill [--force] [技能名稱]",removeUsage:"用法:/remove-skill <技能名稱>",listNoExtra:"/list-skill 不接受參數。",failed:"技能指令失敗:{{message}}"},show:{title:"目前任務",field:"欄位",value:"值",taskId:"taskId",mode:"模式",model:"模型",status:"狀態",messageCount:"訊息數",usageInput:"用量.輸入",usageOutput:"用量.輸出",usageCacheRead:"用量.快取讀取",usageCacheWrite:"用量.快取寫入",usageTotalTokens:"用量.總Token"},showTask:{title:"任務問答",taskIdLabel:"任務 ID",turnHeading:"第 {{index}} 輪",questionLabel:"問題",answerLabel:"回答",createdLabel:"建立時間",emptyQuestion:"(空問題)",emptyAnswer:"(尚無助理文字回覆)",emptyNoMessages:"此任務尚無使用者訊息,無可顯示內容。",previewDocumentTitle:"任務問答"},showPrompt:{previewDocumentTitle:"系統提示",previewHeading:"系統提示"},shellHint:"使用 '/shell <命令>' 執行 shell 命令(例如:'/shell ls -la')。",replIntroDialog:"對話模式:僅唯讀工具 — `/shell` 已停用。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",replIntroPlan:"計畫模式:每次回覆寫入專案目錄下的 `<slug>-plan.md`(請求首行影響檔名)。`/shell` 已停用;計畫完成前輸出保持精簡。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",newSessionHint:"使用 '/new <請求>' 開始新工作階段(不讀取聊天記錄)。",newSessionNoHistory:"使用新工作階段(無聊天記錄)。",controlHint:"按 Ctrl+S 停止正在執行的代理,按 Ctrl+P 暫停並進入子命令模式。",replTabCompletionHint:"按 Tab 鍵可補全以 / 開頭的指令(如 /list、/list-skill),或補全 exit、quit。",tuiScrollTranscriptHint:"全螢幕終端:滑鼠滾輪、方向鍵、PgUp/PgDn、Ctrl+U/Ctrl+F(翻頁)。Ctrl+U/F 捲動日誌。Ctrl+D 仍為清空列結束或輸入時向前刪除。",agentStopped:"代理已停止。",pauseHeader:"--- 代理已暫停 ---",pauseCurrentRequest:"目前請求:{{request}}",pauseHelp:"命令:'continue' 或 'c' 繼續執行,'exit' 或 'e' 退出,或輸入新請求替換目前請求。",pausePrompt:"[已暫停] ",pauseRequestUpdated:"請求已更新為:{{request}}"},shell:{noCommand:"/shell 前綴後未提供命令。用法:/shell <命令>",executionError:"執行 shell 命令時出錯:{{error}}",executing:"[shell] 執行中:{{command}}",errorNoCommand:"/shell 前綴後未提供命令。",errorSpawnFailed:"啟動進程失敗:{{message}}",errorTimedOut:"命令在 {{seconds}} 秒後逾時",logFailed:"Shell 命令失敗:{{command}}(退出碼:{{code}})",logExecutionError:"Shell 命令執行錯誤:{{message}}",resultCommand:"命令:{{command}}",resultExitCode:"退出碼:{{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"成功:",resultSuccessYes:"是",resultSuccessNo:"否",resultOutput:"輸出:",resultError:"錯誤:"},init:{invalidType:'無效的 --type "{{value}}";可選:{{choices}}',invalidLang:'無效的 --lang "{{value}}";可選:{{choices}}',templatesDirNotFound:"找不到範本目錄:{{dir}}",createdPromptTemplates:"已建立 {{dir}}(提示範本)",createdSessions:"已建立 {{dir}}(工作階段歷史)",initialized:"已在 {{targetDir}} 中初始化 {{type}} 專案",promptFilesIn:"提示檔案位於 {{pithosaiDir}},工作階段資料位於 {{sessionsDir}}",runHint:'執行 "pithosai -C {{targetDir}} \\"你的請求\\"" 開始。',createdFile:"已建立 {{path}}",roleAlreadyAdded:"角色 {{role}} 已存在於 .pithosai,略過。",addedRoleTemplates:"已將角色範本新增至 {{dir}}"},tools:{listFiles:{result:"list_files:已在 {{path}} 下列出 {{count}} 個項目"},playwrightView:{result:"playwright_view_markdown:預覽已關閉({{source}})",skipped:"已略過瀏覽器預覽(PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"請只提供 markdown 或 path 其中之一(不可同時提供或皆省略)。",errorEmpty:"Markdown 內容為空。",errorFileOutside:"path 必須位於專案目錄下。",errorNotAFile:"path 不是一般檔案。",errorFileTooLarge:"檔案超過 {{maxBytes}} 位元組。",errorFileRead:"無法讀取檔案:{{message}}",sourceInline:"內嵌 Markdown",sourceFile:"檔案 {{path}}"}},heartbeat:{started:"心跳已啟動(每 {{interval}} 秒輪詢)。檢查郵件主旨前綴「task:」或「任務:」。",startedIdle:"心跳已啟動(IMAP IDLE),角色 {{role}}。等待新郵件。",imapClosedShutdown:"心跳 IMAP 連線已關閉;正在關閉程序。",imapError:"心跳 IMAP 錯誤:{{message}}",imapDisconnectedReconnect:"心跳 IMAP 已斷線;{{ms}} 毫秒後重連",imapOpenBoxError:"心跳 IMAP openBox 錯誤:{{message}}",onNewMailError:"心跳 onNewMail 錯誤:{{message}}",runningTask:"心跳:正在執行任務 {{subject}}",emailRequired:"心跳的信箱不可為空。請在 sqlite3 資料庫的 email_roles 表中設定角色 {{role}} 的信箱。",loadedState:"已從 SQLite 載入心跳狀態,信箱 {{email}},角色 {{role}},狀態:{{states}}",fetchFound:"心跳擷取收件匣發現 {{count}} 個新任務:{{ids}}",savedState:"已將心跳狀態儲存至 SQLite,信箱 {{email}},角色 {{role}}",mergedAndNext:"已合併 {{merged}} 個任務到狀態,下一個待處理:{{stateSummary}}",replyEmailFailed:"心跳回覆郵件傳送失敗:{{error}}",taskFailed:"心跳任務執行失敗:{{error}}",failureReplyEmailFailed:"心跳失敗通知郵件傳送失敗:{{error}}"},cli:{description:"Pithosai:根據自然語言請求實作程式碼或專案。角色提示在運行時從 SQLite 資料庫加載(可選回退到 .pithosai/<role>/*.md)。使用 'pithosai init' 建立專案。",versionOption:"輸出版本號",roleOption:"角色(init 使用的範本集);範本位於 templates/<role>/",langOption:"提示與 init 範本語言:en、zh(預設:en)",interactiveModeOption:"無請求時進入互動模式;顯示模式說明並提示輸入",initDescription:"建立新專案及 .pithosai/ 目錄結構。角色提示在運行時從 SQLite 資料庫加載(可選回退到 .pithosai/<role>/*.md)。",initTypeOption:"專案類型:js、ts 或 python",initExamples:"\n範例:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"將角色範本新增至專案中的 .pithosai/<role>/",addRoleArgument:"要新增的角色(如 PM、QA)",requestArgument:'要建構的內容(例如 "將 CSV 轉為 JSON 的 CLI")。省略則顯示說明。',cwdOption:"專案目錄(預設:目前目錄)",skillsDirOption:"read_skill 技能目錄(預設:./.pithosai/skills 或 PITHOSAI_SKILLS_DIR)",reasonerOption:"使用 DeepSeek Reasoner(思考)模型;預設為 DeepSeek Coder",chatOption:"使用 DeepSeek Chat 模型(一般對話,非程式碼);預設為 DeepSeek Coder",cursorOption:"使用 Cursor CLI 模型(透過 cursor-agent login 認證,無需 API 金鑰)。可選擇指定模型:auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"Agent 最長執行時間(秒,預設 1800)。可用 PITHOSAI_TIMEOUT_MS(毫秒)覆蓋。",interactiveOption:"停用互動提示(預設:每次回覆後詢問下一則訊息)",modeOption:"執行模式:agent(預設,可使用工具)、dialog(僅回答,無工具)、plan(僅將計畫寫入專案根目錄 <slug>-plan.md,無工具)",shellDisabledInMode:"在 dialog 與 plan 模式下已停用 /shell 命令。",planWritten:"計畫已寫入 {{path}}",planRunning:"正在產生計畫…",waitingReply:"正在等待回覆…",runningReply:"正在執行…",resultPreviewOpening:"正在瀏覽器中開啟結果預覽…",resultPreviewTitle:"Pithosai 結果",resultPreviewFailed:"無法開啟結果預覽:{{message}}",resultPreviewCopy:"複製 Markdown",resultPreviewClose:"關閉",resultPreviewCopied:"已複製到剪貼簿",resultPreviewTerminalHint:"↑↓ 或 j/k \xb7 PgUp/PgDn 或 Ctrl+U/Ctrl+D \xb7 Home/End 或 gg/G \xb7 q/Esc 關閉",runExamples:'\n範例:\n pithosai "新增回傳目前時間的 REST 介面"\n pithosai -C ./my-app "執行測試並修復失敗"\n pithosai -i # 互動模式:載入最新工作階段後提示輸入\n pithosai --no-interactive "單次" # 單次回覆,無後續提示\n pithosai --mode dialog "解釋此錯誤"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"用法:",helpArguments:"參數:",helpOptions:"選項:",helpCommands:"命令:",helpGlobalOptions:"全域選項:",helpOption:"顯示命令說明",heartbeatDescription:"輪詢收件匣中任務郵件(主旨「task:...」或「任務:...」),入隊並逐個執行。狀態保存在 ~/.pithosai/heartbeat-state.json。",heartbeatIntervalOption:"輪詢間隔(秒,預設 60)",heartbeatOnceOption:"只執行一次(拉取郵件並處理一個任務後結束)",taskDescription:"監聽任務檔案並在同一程序內逐個處理任務",taskFileOption:"任務 Markdown 檔案路徑(預設:專案根目錄下的 prompts.md)",taskModelOption:"任務使用的模型鍵(deepSeekCoder、deepSeekChat、deepSeekReasoner、ollamaQwen25、ollamaQwen25Coder、ollamaDeepSeekR1、cursorAutoModel、cursorSonnet、cursorSonnetThinking、cursorOpus、cursorGpt)",taskNewSessionOption:"使用新工作階段(無聊天紀錄)",taskExamples:"\n範例:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"找不到任務:{{taskId}}",taskAgentCompleted:"Agent 已完成。",taskAgentRunFailed:"Agent 執行失敗。",taskDone:"完成",taskFailed:"任務失敗:{{message}}",taskProcessingHeader:"--- 正在處理任務 ---",taskLabelId:"id:",taskLabelTitle:"標題:",taskLabelStatus:"狀態:",taskLabelDescription:"描述:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"正在為處理中任務 {{id}}({{title}})啟動處理器。",taskNoPending:"沒有待處理任務。",taskPickedTask:"已選擇任務 {{id}}({{title}});正在啟動處理器。",taskProcessorFailed:"任務處理器失敗:{{message}}",taskWatcherRunning:"任務監看器執行中。按 Ctrl+C 停止。",memorizeDescription:"依日期範圍內該角色參與的任務(持久化的任務訊息)產生摘要,寫入 .pithosai/<role>/memory.md。",memorizeStartOption:"範圍開始:YYYY-MM-DD 或 ISO 日期時間",memorizeEndOption:"範圍結束:YYYY-MM-DD 或 ISO 日期時間",memorizeRoleRequired:"必須指定角色(使用 -r/--role 或全域 --role)。",memorizeWrote:"已寫入 {{path}}(共 {{count}} 個任務)。",memorizeNoTasks:"角色 {{role}} 在範圍內無任務;已寫入標頭至 {{path}}。",memorizeDateError:"日期範圍無效:{{message}}",memorizeNoLlmOption:"略過 LLM 摘要,僅寫入結構化記憶(等同 PITHOSAI_MEMORIZE_SKIP_LLM=1)。",memorizeLlmFallback:"LLM 摘要失敗({{message}});已寫入未摘要的結構化記憶。",memorizeExamples:"\n範例:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"依請求取得 shell 指令(僅 Ollama,僅輸出指令)",argument:"你想做什麼(例如列出目前目錄中的大檔案)",loading:"正在取得指令…",examples:'\n範例:\n $ pithosai shell-tips 列出目前目錄的 json 檔案\n $ pithosai shell-tips "在所有 .js 檔案中將 foo 替換為 bar"'},writer:{description:"依請求產生文字(Ollama qwen2.5:14b)",argument:"要寫什麼(例如簡短拒絕會議的郵件)",loading:"正在撰寫…",examples:'\n範例:\n $ pithosai writer 簡短拒絕會議的郵件\n $ pithosai writer "專案啟動會三項要點"'},skills:{installing:"正在安裝技能至 {{dir}}",fetchingList:"正在從 ClawHub 取得可用技能...",fetchingIndex:"正在從 {{url}} 取得技能索引",notFound:"找不到技能「{{name}}」",noSkillsAvailable:"ClawHub 中沒有可用技能",noSkillsFound:"找不到任何技能",downloadFailed:"下載技能「{{name}}」失敗:{{error}}",installed:"已安裝技能「{{name}}」",complete:"安裝完成:{{count}} / {{total}} 個技能已安裝",alreadyInstalled:"技能「{{name}}」已安裝(使用 --force 重新安裝)",downloading:"正在從 {{url}} 下載技能「{{name}}」",noSkillsDir:"找不到技能目錄。請先安裝技能。",noSkillsInstalled:"未安裝任何技能",installedList:"已安裝技能(共 {{count}} 個)位於 {{dir}}:",notInstalled:"技能「{{name}}」未安裝",removed:"已移除技能「{{name}}」"},skillConvert:{welcome:"技能轉換系統 - 將成功的技能轉換為永久工具",listHeader:"技能轉換分析({{totalSkills}} 個技能,{{totalExecutions}} 次執行)",noSuggestions:"沒有技能達到轉換閾值 {{threshold}}。",suggestedConversions:"建議轉換的技能:",convertHint:"使用 'pithosai skill-convert convert <技能名稱>' 轉換技能。",skillNotFound:"找不到技能 '{{skillName}}' 或無法讀取:{{error}}",alreadyConverted:"技能 '{{skillName}}' 已轉換為工具。",useForceHint:"使用 --force 強制重新轉換。",conversionReportHeader:"'{{skillName}}' 轉換報告:",conversionScore:"轉換分數",suggestedType:"建議類型",ready:"準備轉換",estimatedBenefits:"預計收益",performance:"效能提升",reliability:"可靠性提升",usability:"可用性提升",parameters:"參數",notReadyWarning:"此技能尚未準備好自動轉換。",moreUsageHint:"請更頻繁地使用該技能,或使用 --force 強制轉換。",dryRunComplete:"模擬執行完成。未進行任何變更。",confirmConversion:"將 '{{skillName}}' 轉換為永久工具?",conversionCancelled:"轉換已取消。",converting:"正在將 '{{skillName}}' 轉換為工具...",conversionSuccess:"成功將 '{{skillName}}' 轉換為 '{{toolName}}'。\n工具儲存至:{{toolPath}}",usageExample:"使用範例:",nextSteps:"後續步驟:",restartAgent:"重新啟動代理以載入新工具",testTool:"測試工具:<工具名稱> --help",manageTools:"管理工具:pithosai skill-convert tools",listError:"列出技能時出錯:{{error}}",conversionError:"轉換 '{{skillName}}' 時出錯:{{error}}",skillStatsHeader:"'{{skillName}}' 統計資訊:",generalStats:"一般統計",totalExecutions:"總執行次數",successful:"成功",failed:"失敗",avgTime:"平均執行時間",lastUsed:"最後使用",recentExecutions:"最近執行",commonParameters:"常用參數",overallStatsHeader:"整體技能統計",overallStats:"整體統計",totalSkillsTracked:"追蹤的技能總數",avgSuccessRate:"平均成功率",topSkills:"使用最多的技能",conversionSuggestions:"轉換建議",statsError:"取得統計資訊時出錯:{{error}}",confirmClearAll:"清除所有技能執行記錄?此操作無法復原。",allRecordsCleared:"所有技能執行記錄已清除。",skillRecordsCleared:"'{{skillName}}' 的技能執行記錄已清除。",clearCancelled:"清除操作已取消。",specifySkillOrAll:"請指定技能名稱或使用 --all",clearError:"清除記錄時出錯:{{error}}",noConvertedTools:"未找到已轉換的工具。",convertedToolsHeader:"已轉換的工具:",originalSkill:"原始技能",converted:"轉換時間",usageCount:"使用次數",toolsError:"管理工具時出錯:{{error}}",confirmRemoveTool:"移除工具 '{{toolName}}'?",toolRemoved:"工具 '{{toolName}}' 已移除。",toolRemoveFailed:"移除工具 '{{toolName}}' 失敗。",removeCancelled:"工具移除已取消。",toolEnabled:"工具 '{{toolName}}' 已啟用。",toolEnableFailed:"啟用工具 '{{toolName}}' 失敗。",toolDisabled:"工具 '{{toolName}}' 已停用。",toolDisableFailed:"停用工具 '{{toolName}}' 失敗。",noStatsForSkill:"找不到技能 '{{skillName}}' 的統計資訊。"},hooks:{description:"管理代理鉤子,用於偵錯、安全和監控",list:{description:"列出所有已註冊的鉤子",title:"\uD83D\uDCCB 已註冊的鉤子",total:"總計:{{total}} 個處理器",options:{verbose:"顯示詳細的處理器資訊"},error:"列出鉤子失敗:{{error}}"},debug:{description:"啟用偵錯鉤子以監控代理行為",options:{data:"在偵錯輸出中記錄完整資料",performance:"啟用效能監控鉤子",stats:"啟用統計收集鉤子",all:"啟用所有偵錯鉤子"},added:{debug:"已新增偵錯日誌鉤子",performance:"已新增效能監控鉤子",stats:"已新增統計收集鉤子",basic:"已新增基本偵錯鉤子"},success:"偵錯鉤子已啟用({{count}} 個處理器已註冊)",error:"啟用偵錯鉤子失敗:{{error}}"},security:{description:"啟用安全鉤子進行存取控制和監控",options:{block:"要封鎖的工具清單,以逗號分隔",maxPrompt:"最大允許的提示長度(預設:10000)"},success:"安全鉤子已啟用",blockedTools:"已封鎖的工具:{{tools}}",maxPrompt:"最大提示長度:{{length}} 個字元",error:"啟用安全鉤子失敗:{{error}}"},clear:{description:"清除所有已註冊的鉤子",success:"所有鉤子已清除",error:"清除鉤子失敗:{{error}}"},test:{description:"使用測試資料觸發鉤子進行測試",argument:{hookType:"要測試的特定鉤子類型(選填)"},invalidType:"無效的鉤子類型:{{type}}",triggered:"已觸發鉤子:{{type}}",result:"結果:{{result}}",allTriggered:"所有鉤子已成功觸發",error:"測試鉤子失敗:{{error}}"},register:{description:"從檔案註冊自訂鉤子處理器",argument:{hookType:"要註冊處理器的鉤子類型",handlerFile:"處理器檔案路徑(必須匯出預設函式)"},invalidType:"無效的鉤子類型:{{type}}",invalidHandler:"處理器檔案必須匯出一個預設函式",success:"已為 {{type}} 註冊來自 {{file}} 的處理器",error:"註冊鉤子失敗:{{error}}"},status:{description:"顯示目前鉤子設定和統計資訊",title:"\uD83D\uDCCB 鉤子狀態",error:"取得鉤子狀態失敗:{{error}}"}}}},3998(e,t,i){i.d(t,{A:()=>r});let r={prompt:{baseRequirementHeading:"基本要求",projectDir:"项目目录(在此工作):{{cwd}}",skillsInstruction:"当任务与某技能的描述匹配时,使用 read_skill 工具加载该技能的完整说明。",toolArgSizeLimit:"单个工具调用参数(如 write 的 content)严禁超过 {{maxChars}} 字符,否则可能触发「Unterminated string in JSON」错误。长文件或脚本请拆成多次 write 调用(按文件或按每段不超过 {{maxChars}} 字符)。",toolCallJsonFormat:'工具调用参数必须是合法 JSON:所有键和字符串值都必须用双引号包裹。例如 write:{"path": "文件名.md", "content": "内容"}。不要省略键或值的引号(如 path: file.md 或 content: 文字 为无效)。'},errors:{missingPromptFiles:"缺少必需的提示文件,目录:{{dir}}",runInit:"请在项目根目录执行 'pithosai init' 以创建 .pithosai 及模板。",noApiKey:"未找到 API 密钥。请设置 DEEPSEEK_API_KEY 或 OPENROUTER_API_KEY。",ollamaNotConfigured:"未配置 Ollama。请设置 OPENAI_LOCAL_API_BASE 或在项目中配置本地模型。",noValidTemplateFiles:"目录 {{dir}} 中无有效模板文件。需要 *-<lang>.md 格式(如 IDENTITY-ja.md)。请执行 'pithosai init' 创建 .pithosai 及模板。",runTimeout:"Agent 运行在 {{seconds}} 秒后超时。可使用 --timeout <秒> 或 PITHOSAI_TIMEOUT_MS 调整。",agentRunFailed:"运行失败:{{message}}",unknownRunError:"未知错误"},warnings:{sessionAppend:"会话追加失败:{{message}}",apiRetry:"API 错误,第 {{attempt}}/{{max}} 次尝试;正在重试…"},reasoner:{thinkingHeader:"\n--- 思考:\n",replyHeader:"\n\n--- 回复:\n"},run:{cwd:"工作目录 {{cwd}}",request:"请求:{{request}}",interactivePrompt:"您:",tuiYouLabel:"您:",interactiveExitHint:"请回答或输入新请求(输入 'exit' 或 'quit' 可退出 CLI)。",interactiveModeCwd:"工作目录:{{cwd}}",interactiveModeAgentTitle:"--- 交互模式 — 代理(完整工具)---",interactiveModeAgentTips:"- 使用完整工具集(读、写、执行及项目配置的其他工具)。\n- 对话按任务保存在本地数据库中。\n- `/new` 会分配新的任务 id,不会加载此前消息。\n- `/shell <命令>` 执行 shell;`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 用于已持久化任务。\n- `/list-skill`、`/install-skill`、`/remove-skill` 与 `pithosai skills list|install|remove` 相同(ClawHub)。Ctrl+S 停止,Ctrl+P 暂停。",interactiveModeDialogTitle:"--- 交互模式 — 对话(只读问答)---",interactiveModeDialogTips:"- 仅使用只读工具(不可用 shell、写文件或执行命令)。\n- 对话按任务保存在本地数据库中。\n- 使用 `/new` 会分配新的任务 id,不会加载此前消息。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),与 `pithosai skills` CLI 一致。",interactiveModePlanTitle:"--- 计划模式 ---",interactiveModePlanTips:"- 每次回复会写入项目目录下的 `<slug>-plan.md`(请求首行影响文件名)。\n- 仅只读工具;shell 与修改类工具不可用。\n- `/new` 会分配新的任务 id。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),与 `pithosai skills` CLI 一致。\n- 每次运行结束后可在提示符继续输入新的计划请求(与 agent/dialog 相同)。",list:{noPersistedTasks:"未找到已持久化的任务。",createTasksFirstHint:"请先使用 `pithosai task` 创建任务。",persistedTasksHeader:"--- 已持久化的任务({{count}})---",selectTaskHint:"使用 `/select <index>` 来运行一个任务。",noTasksCached:"没有缓存的任务。请先执行 `/list`。",invalidIndex:"无效的索引 {{index}}。有效范围:0-{{maxIndex}}。",selectUsage:"用法:/select <index>",selectedTask:"已选择任务 #{{index}}。"},skillSlash:{installUsage:"用法:/install-skill [--force] [技能名]",removeUsage:"用法:/remove-skill <技能名>",listNoExtra:"/list-skill 不接受参数。",failed:"技能命令失败:{{message}}"},show:{title:"当前任务",field:"字段",value:"值",taskId:"taskId",mode:"模式",model:"模型",status:"状态",messageCount:"消息数",usageInput:"用量.输入",usageOutput:"用量.输出",usageCacheRead:"用量.缓存读取",usageCacheWrite:"用量.缓存写入",usageTotalTokens:"用量.总Token"},showTask:{title:"任务问答",taskIdLabel:"任务 ID",turnHeading:"第 {{index}} 轮",questionLabel:"问题",answerLabel:"回答",createdLabel:"创建时间",emptyQuestion:"(空问题)",emptyAnswer:"(尚无助手文本回复)",emptyNoMessages:"此任务尚无用户消息,无可展示内容。",previewDocumentTitle:"任务问答"},showPrompt:{previewDocumentTitle:"系统提示",previewHeading:"系统提示"},shellHint:"使用 '/shell <命令>' 执行 shell 命令(例如:'/shell ls -la')。",replIntroDialog:"对话模式:仅只读工具 — `/shell` 已禁用。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",replIntroPlan:"计划模式:每次回复写入项目目录下的 `<slug>-plan.md`(请求首行影响文件名)。`/shell` 已禁用;计划完成前输出保持精简。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",newSessionHint:"使用 '/new <请求>' 开始新会话(不读取聊天历史)。",newSessionNoHistory:"使用新会话(无聊天历史)。",controlHint:"按 Ctrl+S 停止正在运行的代理,按 Ctrl+P 暂停并进入子命令模式。",replTabCompletionHint:"按 Tab 键可补全以 / 开头的命令(如 /list、/list-skill),或补全 exit、quit。",tuiScrollTranscriptHint:"全屏终端:鼠标滚轮、方向键、PgUp/PgDn、Ctrl+U/Ctrl+F(翻页)。Ctrl+U/F 用于滚动日志。Ctrl+D 仍为清空行退出或输入时向前删除。",agentStopped:"代理已停止。",pauseHeader:"--- 代理已暂停 ---",pauseCurrentRequest:"当前请求:{{request}}",pauseHelp:"命令:'continue' 或 'c' 继续执行,'exit' 或 'e' 退出,或输入新请求替换当前请求。",pausePrompt:"[已暂停] ",pauseRequestUpdated:"请求已更新为:{{request}}"},shell:{noCommand:"/shell 前缀后未提供命令。用法:/shell <命令>",executionError:"执行 shell 命令时出错:{{error}}",executing:"[shell] 执行中:{{command}}",errorNoCommand:"/shell 前缀后未提供命令。",errorSpawnFailed:"启动进程失败:{{message}}",errorTimedOut:"命令在 {{seconds}} 秒后超时",logFailed:"Shell 命令失败:{{command}}(退出码:{{code}})",logExecutionError:"Shell 命令执行错误:{{message}}",resultCommand:"命令:{{command}}",resultExitCode:"退出码:{{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"成功:",resultSuccessYes:"是",resultSuccessNo:"否",resultOutput:"输出:",resultError:"错误:"},init:{invalidType:'无效的 --type "{{value}}";可选:{{choices}}',invalidLang:'无效的 --lang "{{value}}";可选:{{choices}}',templatesDirNotFound:"未找到模板目录:{{dir}}",createdPromptTemplates:"已创建 {{dir}}(提示模板)",createdSessions:"已创建 {{dir}}(会话历史)",initialized:"已在 {{targetDir}} 中初始化 {{type}} 项目",promptFilesIn:"提示文件位于 {{pithosaiDir}},会话数据位于 {{sessionsDir}}",runHint:'运行 "pithosai -C {{targetDir}} \\"你的请求\\"" 开始。',createdFile:"已创建 {{path}}",roleAlreadyAdded:"角色 {{role}} 已存在于 .pithosai,跳过。",addedRoleTemplates:"已将角色模板添加到 {{dir}}"},tools:{listFiles:{result:"list_files:已在 {{path}} 下列出 {{count}} 个条目"},playwrightView:{result:"playwright_view_markdown:预览已关闭({{source}})",skipped:"已跳过浏览器预览(PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"请只提供 markdown 或 path 其中之一(不能同时提供或都省略)。",errorEmpty:"Markdown 内容为空。",errorFileOutside:"path 必须位于项目目录下。",errorNotAFile:"path 不是普通文件。",errorFileTooLarge:"文件超过 {{maxBytes}} 字节。",errorFileRead:"无法读取文件:{{message}}",sourceInline:"内联 Markdown",sourceFile:"文件 {{path}}"}},heartbeat:{started:"心跳已启动(每 {{interval}} 秒轮询)。检查邮件主题前缀「task:」或「任务:」。",startedIdle:"心跳已启动(IMAP IDLE),角色 {{role}}。等待新邮件。",imapClosedShutdown:"心跳 IMAP 连接已关闭;正在关闭进程。",imapError:"心跳 IMAP 错误:{{message}}",imapDisconnectedReconnect:"心跳 IMAP 已断开;{{ms}} 毫秒后重连",imapOpenBoxError:"心跳 IMAP openBox 错误:{{message}}",onNewMailError:"心跳 onNewMail 错误:{{message}}",runningTask:"心跳:正在执行任务 {{subject}}",emailRequired:"心跳的邮箱不能为空。请在 sqlite3 数据库的 email_roles 表中配置角色 {{role}} 的邮箱。",loadedState:"已从 SQLite 加载心跳状态,邮箱 {{email}},角色 {{role}},状态:{{states}}",fetchFound:"心跳拉取收件箱发现 {{count}} 个新任务:{{ids}}",savedState:"已将心跳状态保存到 SQLite,邮箱 {{email}},角色 {{role}}",mergedAndNext:"已合并 {{merged}} 个任务到状态,下一个待处理:{{stateSummary}}",replyEmailFailed:"心跳回复邮件发送失败:{{error}}",taskFailed:"心跳任务执行失败:{{error}}",failureReplyEmailFailed:"心跳失败通知邮件发送失败:{{error}}"},cli:{description:"Pithosai:根据自然语言请求实现代码或项目。角色提示在运行时从 SQLite 数据库加载(可选回退到 .pithosai/<role>/*.md)。使用 'pithosai init' 创建项目。",versionOption:"输出版本号",roleOption:"角色(init 使用的模板集);模板位于 templates/<role>/",langOption:"提示与 init 模板语言:en、zh(默认:en)",interactiveModeOption:"无请求时进入交互模式;显示模式说明并提示输入",initDescription:"创建新项目及 .pithosai/ 目录结构。角色提示在运行时从 SQLite 数据库加载(可选回退到 .pithosai/<role>/*.md)。",initTypeOption:"项目类型:js、ts 或 python",initExamples:"\n示例:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"将角色模板添加到项目中的 .pithosai/<role>/",addRoleArgument:"要添加的角色(如 PM、QA)",requestArgument:'要构建的内容(例如 "将 CSV 转为 JSON 的 CLI")。省略则显示帮助。',cwdOption:"项目目录(默认:当前目录)",skillsDirOption:"read_skill 技能目录(默认:./.pithosai/skills 或 PITHOSAI_SKILLS_DIR)",reasonerOption:"使用 DeepSeek Reasoner(思考)模型;默认为 DeepSeek Coder",chatOption:"使用 DeepSeek Chat 模型(通用对话,非代码);默认为 DeepSeek Coder",cursorOption:"使用 Cursor CLI 模型(通过 cursor-agent login 认证,无需 API 密钥)。可指定模型:auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"Agent 最长运行时间(秒,默认 1800)。可用 PITHOSAI_TIMEOUT_MS(毫秒)覆盖。",interactiveOption:"禁用交互提示(默认:每次回复后询问下一条消息)",modeOption:"运行模式:agent(默认,可使用工具)、dialog(仅回答,无工具)、plan(仅将计划写入项目根目录 <slug>-plan.md,无工具)",shellDisabledInMode:"在 dialog 与 plan 模式下已禁用 /shell 命令。",planWritten:"计划已写入 {{path}}",planRunning:"正在生成计划…",waitingReply:"正在等待回复…",runningReply:"正在运行…",resultPreviewOpening:"正在浏览器中打开结果预览…",resultPreviewTitle:"Pithosai 结果",resultPreviewFailed:"无法打开结果预览:{{message}}",resultPreviewCopy:"复制 Markdown",resultPreviewClose:"关闭",resultPreviewCopied:"已复制到剪贴板",resultPreviewTerminalHint:"↑↓ 或 j/k \xb7 PgUp/PgDn 或 Ctrl+U/Ctrl+D \xb7 Home/End 或 gg/G \xb7 q/Esc 关闭",runExamples:'\n示例:\n pithosai "添加返回当前时间的 REST 接口"\n pithosai -C ./my-app "运行测试并修复失败"\n pithosai -i # 交互模式:加载最新会话后提示输入\n pithosai --no-interactive "单次" # 单次回复,无后续提示\n pithosai --mode dialog "解释这个错误" # 仅对话;无工具与 /shell\n pithosai --mode plan "api sprint plan" # 写入例如 api-sprint-plan-plan.md\n',helpUsage:"用法:",helpArguments:"参数:",helpOptions:"选项:",helpCommands:"命令:",helpGlobalOptions:"全局选项:",helpOption:"显示命令帮助",heartbeatDescription:"轮询收件箱中任务邮件(主题「task:...」或「任务:...」),入队并逐个执行。状态保存在 ~/.pithosai/heartbeat-state.json。",heartbeatIntervalOption:"轮询间隔(秒,默认 60)",heartbeatOnceOption:"只运行一次(拉取邮件并处理一个任务后退出)",taskDescription:"监听任务文件并在同一进程内逐个处理任务",taskFileOption:"任务 Markdown 文件路径(默认:项目根目录下的 prompts.md)",taskModelOption:"任务使用的模型键(deepSeekCoder、deepSeekChat、deepSeekReasoner、ollamaQwen25、ollamaQwen25Coder、ollamaDeepSeekR1、cursorAutoModel、cursorSonnet、cursorSonnetThinking、cursorOpus、cursorGpt)",taskNewSessionOption:"使用新会话(无聊天记录)",taskExamples:"\n示例:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"未找到任务:{{taskId}}",taskAgentCompleted:"Agent 已完成。",taskAgentRunFailed:"Agent 运行失败。",taskDone:"完成",taskFailed:"任务失败:{{message}}",taskProcessingHeader:"--- 正在处理任务 ---",taskLabelId:"id:",taskLabelTitle:"标题:",taskLabelStatus:"状态:",taskLabelDescription:"描述:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"正在为处理中任务 {{id}}({{title}})启动处理器。",taskNoPending:"没有待处理任务。",taskPickedTask:"已选择任务 {{id}}({{title}});正在启动处理器。",taskProcessorFailed:"任务处理器失败:{{message}}",taskWatcherRunning:"任务监视器运行中。按 Ctrl+C 停止。",showPromptDescription:"显示运行时会使用的系统提示",showPromptModeOption:"模式:agent、dialog 或 plan(默认:agent)",showPromptRawOption:"显示截断和工具块之前的原始提示",showPromptTruncatedOption:"显示截断后的提示(需要模型配置)",showPromptInvalidMode:"无效模式。必须是 'agent'、'dialog' 或 'plan'。",showPromptError:"构建提示时出错:{{message}}",memorizeDescription:"根据日期范围内该角色参与的任务(持久化的任务消息)生成摘要,写入 .pithosai/<role>/memory.md。",memorizeStartOption:"范围开始:YYYY-MM-DD 或 ISO 日期时间",memorizeEndOption:"范围结束:YYYY-MM-DD 或 ISO 日期时间",memorizeRoleRequired:"必须指定角色(使用 -r/--role 或全局 --role)。",memorizeWrote:"已写入 {{path}}(共 {{count}} 个任务)。",memorizeNoTasks:"角色 {{role}} 在范围内无任务;已写入头部到 {{path}}。",memorizeDateError:"日期范围无效:{{message}}",memorizeNoLlmOption:"跳过 LLM 摘要,仅写入结构化记忆(等同于 PITHOSAI_MEMORIZE_SKIP_LLM=1)。",memorizeLlmFallback:"LLM 摘要失败({{message}});已写入未摘要的结构化记忆。",memorizeExamples:"\n示例:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n"},shellTips:{description:"根据请求获取 shell 命令(仅 Ollama,仅输出命令)",argument:"你想做什么(例如列出当前目录中的大文件)",loading:"正在获取命令…",examples:'\n示例:\n $ pithosai shell-tips 列出当前目录下的 json 文件\n $ pithosai shell-tips "在所有 .js 文件中将 foo 替换为 bar"'},writer:{description:"根据请求生成文本(Ollama qwen2.5:14b)",argument:"要写什么(例如简短拒绝会议的邮件)",loading:"正在撰写…",examples:'\n示例:\n $ pithosai writer 简短拒绝会议的邮件\n $ pithosai writer "项目启动会三个要点"'},skills:{installing:"正在安装技能到 {{dir}}",fetchingList:"正在从 ClawHub 获取可用技能...",fetchingIndex:"正在从 {{url}} 获取技能索引",notFound:"未找到技能 '{{name}}'",noSkillsAvailable:"ClawHub 中没有可用技能",noSkillsFound:"未找到任何技能",downloadFailed:"下载技能 '{{name}}' 失败:{{error}}",installed:"已安装技能 '{{name}}'",complete:"安装完成:已安装 {{count}} 个技能,共 {{total}} 个",alreadyInstalled:"技能 '{{name}}' 已安装(使用 --force 重新安装)",downloading:"正在从 {{url}} 下载技能 '{{name}}'",noSkillsDir:"未找到技能目录。请先安装技能。",noSkillsInstalled:"未安装任何技能",installedList:"已安装技能(共 {{count}} 个)在 {{dir}}:",notInstalled:"技能 '{{name}}' 未安装",removed:"已移除技能 '{{name}}'"},skillConvert:{welcome:"技能转换系统 - 将成功的技能转换为永久工具",listHeader:"技能转换分析({{totalSkills}} 个技能,{{totalExecutions}} 次执行)",noSuggestions:"没有技能达到转换阈值 {{threshold}}。",suggestedConversions:"建议转换的技能:",convertHint:"使用 'pithosai skill-convert convert <技能名称>' 转换技能。",skillNotFound:"未找到技能 '{{skillName}}' 或无法读取:{{error}}",alreadyConverted:"技能 '{{skillName}}' 已转换为工具。",useForceHint:"使用 --force 强制重新转换。",conversionReportHeader:"'{{skillName}}' 转换报告:",conversionScore:"转换分数",suggestedType:"建议类型",ready:"准备转换",estimatedBenefits:"预计收益",performance:"性能提升",reliability:"可靠性提升",usability:"可用性提升",parameters:"参数",notReadyWarning:"此技能尚未准备好自动转换。",moreUsageHint:"请更频繁地使用该技能,或使用 --force 强制转换。",dryRunComplete:"模拟运行完成。未进行任何更改。",confirmConversion:"将 '{{skillName}}' 转换为永久工具?",conversionCancelled:"转换已取消。",converting:"正在将 '{{skillName}}' 转换为工具...",conversionSuccess:"成功将 '{{skillName}}' 转换为 '{{toolName}}'。\n工具保存到:{{toolPath}}",usageExample:"使用示例:",nextSteps:"后续步骤:",restartAgent:"重启代理以加载新工具",testTool:"测试工具:<工具名称> --help",manageTools:"管理工具:pithosai skill-convert tools",listError:"列出技能时出错:{{error}}",conversionError:"转换 '{{skillName}}' 时出错:{{error}}",skillStatsHeader:"'{{skillName}}' 统计信息:",generalStats:"常规统计",totalExecutions:"总执行次数",successful:"成功",failed:"失败",avgTime:"平均执行时间",lastUsed:"最后使用",recentExecutions:"最近执行",commonParameters:"常用参数",overallStatsHeader:"整体技能统计",overallStats:"整体统计",totalSkillsTracked:"跟踪的技能总数",avgSuccessRate:"平均成功率",topSkills:"使用最多的技能",conversionSuggestions:"转换建议",statsError:"获取统计信息时出错:{{error}}",confirmClearAll:"清除所有技能执行记录?此操作不可撤销。",allRecordsCleared:"所有技能执行记录已清除。",skillRecordsCleared:"'{{skillName}}' 的技能执行记录已清除。",clearCancelled:"清除操作已取消。",specifySkillOrAll:"请指定技能名称或使用 --all",clearError:"清除记录时出错:{{error}}",noConvertedTools:"未找到转换的工具。",convertedToolsHeader:"已转换的工具:",originalSkill:"原始技能",converted:"转换时间",usageCount:"使用次数",toolsError:"管理工具时出错:{{error}}",confirmRemoveTool:"移除工具 '{{toolName}}'?",toolRemoved:"工具 '{{toolName}}' 已移除。",toolRemoveFailed:"移除工具 '{{toolName}}' 失败。",removeCancelled:"工具移除已取消。",toolEnabled:"工具 '{{toolName}}' 已启用。",toolEnableFailed:"启用工具 '{{toolName}}' 失败。",toolDisabled:"工具 '{{toolName}}' 已禁用。",toolDisableFailed:"禁用工具 '{{toolName}}' 失败。",noStatsForSkill:"未找到技能 '{{skillName}}' 的统计信息。"},hooks:{description:"管理代理钩子,用于调试、安全和监控",list:{description:"列出所有已注册的钩子",title:"\uD83D\uDCCB 已注册的钩子",total:"总计:{{total}} 个处理器",options:{verbose:"显示详细的处理器信息"},error:"列出钩子失败:{{error}}"},debug:{description:"启用调试钩子以监控代理行为",options:{data:"在调试输出中记录完整数据",performance:"启用性能监控钩子",stats:"启用统计收集钩子",all:"启用所有调试钩子"},added:{debug:"已添加调试日志钩子",performance:"已添加性能监控钩子",stats:"已添加统计收集钩子",basic:"已添加基本调试钩子"},success:"调试钩子已启用({{count}} 个处理器已注册)",error:"启用调试钩子失败:{{error}}"},security:{description:"启用安全钩子进行访问控制和监控",options:{block:"要阻止的工具列表,用逗号分隔",maxPrompt:"最大允许的提示长度(默认:10000)"},success:"安全钩子已启用",blockedTools:"已阻止的工具:{{tools}}",maxPrompt:"最大提示长度:{{length}} 个字符",error:"启用安全钩子失败:{{error}}"},clear:{description:"清除所有已注册的钩子",success:"所有钩子已清除",error:"清除钩子失败:{{error}}"},test:{description:"使用测试数据触发钩子进行测试",argument:{hookType:"要测试的特定钩子类型(可选)"},invalidType:"无效的钩子类型:{{type}}",triggered:"已触发钩子:{{type}}",result:"结果:{{result}}",allTriggered:"所有钩子已成功触发",error:"测试钩子失败:{{error}}"},register:{description:"从文件注册自定义钩子处理器",argument:{hookType:"要注册处理器的钩子类型",handlerFile:"处理器文件路径(必须导出默认函数)"},invalidType:"无效的钩子类型:{{type}}",invalidHandler:"处理器文件必须导出一个默认函数",success:"已为 {{type}} 注册来自 {{file}} 的处理器",error:"注册钩子失败:{{error}}"},status:{description:"显示当前钩子配置和统计信息",title:"\uD83D\uDCCB 钩子状态",error:"获取钩子状态失败:{{error}}"}}}},8476(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Cm:()=>a.C,Ts:()=>a.T});var s=i(2883),o=i(9320),a=i(9188),n=e([s,o,a]);[s,o,a]=n.then?(await n)():n,r()}catch(e){r(e)}})},9188(e,t,i){i.a(e,async function(e,r){try{i.d(t,{C:()=>m,T:()=>h});var s=i(6760),o=i(1455),a=i(5012),n=i(4071),l=i(4399),d=i(8362),c=i(4768),u=i(9320),p=e([u,d,n,c]);async function h(e,t={}){let i=!0===t.noExit,r=(0,s.resolve)(e||"."),l=(t.lang||"en").toLowerCase(),p=(0,d.l)(l),m=(t.type||"js").toLowerCase();if(!a.Av.includes(m)){let e=p("init.invalidType",{value:t.type??"",choices:a.Av.join(", ")});if((0,n.vV)(e),i)throw Object.assign(Error(e),{exitCode:a.dc.USAGE});process.exit(a.dc.USAGE)}if(!a.Lq.includes(l)){let e=p("init.invalidLang",{value:t.lang??"",choices:a.Lq.join(", ")});if((0,n.vV)(e),i)throw Object.assign(Error(e),{exitCode:a.dc.USAGE});process.exit(a.dc.USAGE)}let g=t.role||"RD",f=(0,s.basename)(r);await (0,o.mkdir)(r,{recursive:!0}),await (0,u.Y)({targetDir:r,type:m,projectName:f,t:p,role:g});let w=(0,s.join)(r,".pithosai","sessions");await (0,o.mkdir)(w,{recursive:!0}),(0,n.fH)(p("init.createdSessions",{dir:w})),await (0,c.L)(r,{lang:l,project:{type:m,name:f,cwd:r},supportedRoles:[g],tools:{web:{fetch:{enabled:!0},search:{enabled:!0}}}}),(0,n.fH)(p("init.initialized",{type:m,targetDir:r})),(0,n.fH)(p("init.promptFilesIn",{pithosaiDir:(0,s.join)(r,".pithosai"),sessionsDir:w})),(0,n.fH)(p("init.runHint",{targetDir:r}))}async function m(e,t,i="en",r){let u=(0,s.resolve)(e),p=r??(0,d.l)(i),h=(0,l.mi)(t);try{await (0,o.access)(h)}catch{(0,n.vV)(p("init.templatesDirNotFound",{dir:h})),process.exit(a.dc.CONFIG)}let g=await (0,c.s)(u),f=g?.supportedRoles??[];f.includes(t)||(f.push(t),await (0,c.L)(u,{...g,supportedRoles:f}))}[u,d,n,c]=p.then?(await p)():p,r()}catch(e){r(e)}})},9320(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Y:()=>d});var s=i(6760),o=i(1455);i(5012);var a=i(4071),n=e([a]);function l(e){let t=".pithosai/\nlogs/\n\n",i="node_modules/\n.env\ncoverage/\n*.log\nnpm-debug.log*\n.DS_Store";return"python"===e?t+"__pycache__/\n*.py[cod]\n*$py.class\n.env\nvenv/\n.venv/\n.pytest_cache/\n.mypy_cache/\n*.egg-info/\n.eggs/\ndist/\nbuild/":"ts"===e?t+i+"\ndist/\n":t+i}async function d(e){let{targetDir:t,type:i,projectName:r,t:n,role:d="RD"}=e,c=r||(0,s.dirname)(t)||"project";if("PM"===d||"QA"===d||"CO"===d||"MKT"===d||"SRE"===d){let e=`# Requirements
|
|
377
|
+
${e.responseMarkdown}`;return{subject:e.subject,html:o,text:n.trim()}}i()}catch(e){i(e)}})},4822(e,t,r){r.a(e,async function(e,i){try{r.d(t,{IG:()=>k,lx:()=>l.lx});var a=r(6760),o=r(8161),n=r(3024),s=r(935),l=r(614),d=r(3242),c=r(1305),u=r(2003),p=r(4768),m=r(5012),h=r(4071),g=r(8362),f=e([p,g,l,d,u,c,s,h]);async function k(e,t={}){var r;let i=(0,a.resolve)(e),f=await (0,p.s)(i),w=t.role??f?.supportedRoles?.[0]??l.lx,v=f?.roles?.[w]?.email,y=t.lang??f?.lang??(0,g.a)(),b=(0,g.l)(y);if(!v)return void(0,h.vV)(b("heartbeat.emailRequired",{role:w}));let S=await (0,s.cp)(m.qu,{email:v,role:w});(0,h.fH)(b("heartbeat.loadedState",{email:v,role:w,states:JSON.stringify(S)}));let T=await (0,l.hf)(i,w,{limit:20,lang:y,email:v,states:S,stateDir:m.qu});(0,h.fH)(b("heartbeat.fetchFound",{count:T.length,ids:T.map(e=>e.id).join(", ")}));let E=function(e,t,r){let i=0;for(let a of r){let r=e.find(e=>e.role===a.role&&e.email===a.email&&e.projectName===a.projectName);r||(r={email:a.email,role:a.role,projectName:a.projectName,projectPath:a.projectPath,processed:[],unprocessed:[]},e.push(r));let o=new Set(r.processed||[]),n=new Set(r.unprocessed.map(e=>e.id));o.has(a.id)||n.has(a.id)||(i++,r.unprocessed.push({id:a.id,subject:a.subject,body:a.body,date:a.date,from:a.from,role:t,projectName:a.projectName,projectPath:a.projectPath,...Array.isArray(a.attachments)&&a.attachments.length>0?{attachments:a.attachments}:{}}),n.add(a.id))}return i}(S,w,T);E>0&&(await (0,s.br)(S,m.qu,{email:v,role:w}),(0,h.fH)(b("heartbeat.savedState",{email:v,role:w})));let x=!1,C=(r={email:v,role:w},S.find(e=>e.email===r.email&&e.role===r.role&&e.unprocessed.length>0));{let e=C?`${C.projectName||C.email} (${C.unprocessed?.length??0} unprocessed)`:"none";(0,h.fH)(b("heartbeat.mergedAndNext",{merged:E,stateSummary:e}))}let A=C?.unprocessed?.shift();if(A){let e=function(e,t){if(t.projectPath&&String(t.projectPath).trim()&&(0,n.existsSync)(t.projectPath))return t.projectPath;let r=t.projectName;if(!r||!String(r).trim())return e;let i=(0,a.join)((0,o.homedir)(),String(r).trim());return(0,n.existsSync)(i)?i:e}(i,A);(0,h.fH)(b("heartbeat.runningTask",{subject:A.subject}));let r=(0,l.P2)(A),s=await (0,d.Ty)({id:A.id,status:"pending",title:r,description:"",model:void 0,createdAt:new Date().toISOString(),section:null},{cwd:e,role:w,lang:y,reasoner:t.reasoner,chat:t.chat,timeout:t.timeout,markdown:t.markdown});if(s.success){C.processed.push(A.id),x=!0;let e=s.result?.trim()||"(Task completed with no text output.)",t="Re: "+(A.subject||"task"),i=await (0,u.rr)({subject:t,projectName:A.projectName,projectPath:A.projectPath,request:r,responseMarkdown:e,date:new Date().toISOString()},y),a=await (0,c.ZM)(f,w,{to:A.from,subject:i.subject,html:i.html});!a.success&&a.error&&(0,h.vV)(b("heartbeat.replyEmailFailed",{error:a.error}))}else{(0,h.vV)(b("heartbeat.taskFailed",{error:s.error||"unknown"})),C.unprocessed.unshift(A);let e="Task failed: "+(s.error||"unknown error"),t="Re: "+(A.subject||"task")+" [FAILED]",i=await (0,u.rr)({subject:t,projectName:A.projectName,projectPath:A.projectPath,request:r,responseMarkdown:e,date:new Date().toISOString()},y),a=await (0,c.ZM)(f,w,{to:process.env.SUPPORT_EMAIL||"support@pithosai.com",subject:i.subject,html:i.html});!a.success&&a.error&&(0,h.vV)(b("heartbeat.failureReplyEmailFailed",{error:a.error}))}}(E>0||x)&&(await (0,s.br)(S,m.qu,{email:v,role:w}),(0,h.fH)(b("heartbeat.savedState",{email:v,role:w})));let I=S.reduce((e,t)=>e+t.processed.length,0),O=S.reduce((e,t)=>e+t.unprocessed.length,0);return{processedCount:I,ranOne:x,unprocessedCount:O}}[p,g,l,d,u,c,s,h]=f.then?(await f)():f,i()}catch(e){i(e)}})},6478(e,t,r){r.a(e,async function(e,i){try{r.d(t,{D:()=>m,I:()=>o.IG});var a=r(6760),o=r(4822),n=r(4768),s=r(4071),l=r(8362),d=r(1305),c=r(8359),u=r(5012),p=e([n,c,l,d,o,s]);async function m(e,t={}){let r=(0,a.resolve)(e),i=await (0,n.s)(r),p=t.role??i?.supportedRoles?.[0]??o.lx,h=await (0,c.Lf)(u.qu),g=await (0,c.bY)(h);if(!g.find(e=>e.role===p)?.email){let e=t.lang??i?.lang??(0,l.a)(),r=(0,l.l)(e);throw Error(r("heartbeat.emailRequired",{role:p}))}let f={role:t.role,lang:t.lang,reasoner:t.reasoner,chat:t.chat,timeout:t.timeout,markdown:t.markdown},k=t.lang??i?.lang??(0,l.a)(),w=(0,l.l)(k);(0,s.fH)(w("heartbeat.startedIdle",{role:p}));let v=await (0,d.Df)(i,p,async()=>{await (0,o.IG)(r,f)},{lang:k}),y=()=>{v.close(),(0,s.fH)(w("heartbeat.imapClosedShutdown")),process.exit(0)};process.on("SIGINT",y),process.on("SIGTERM",y),await new Promise(()=>{})}[n,c,l,d,o,s]=p.then?(await p)():p,i()}catch(e){i(e)}})},935(e,t,r){r.a(e,async function(e,i){try{r.d(t,{bq:()=>m,br:()=>u,cp:()=>d}),r(6760);var a=r(7598);r(3024);var o=r(5012),n=r(8359),s=r(4071),l=e([s,n]);async function d(e=o.qu,t={}){return t.email&&t.role?c(e,t.email,t.role):null}async function c(e,t,r){let i=await (0,n.Lf)(e),a=await (0,n.O3)(i,{email:t,role:r}),o=[];for(let e of a){if(!e.projectName||!e.projectPath){(0,s.JE)("loadHeartbeatStateFromStorage skip process:",e.id,"projectName:",e.projectName,"projectPath:",e.projectPath);continue}let a=await (0,n.SW)(i,e.id),l=[],d=[];for(let t of a){let r=await (0,n.x_)(i,t.emailId);if(!r)continue;let a=await (0,n.tJ)(i,r.id),o=a.length>0?a.map(e=>({filename:e.filename,contentType:e.contentType,size:e.size,...null!=e.content?{content:e.content}:{},...null!=e.filePath?{filePath:e.filePath}:{}})):void 0,s={id:r.id,subject:r.subject,body:r.body,date:r.date,from:r.from,projectName:e.projectName,projectPath:e.projectPath,...o?{attachments:o}:{}};t.status===n.au.PROCESSED?l.push(r.id):d.push(s)}o.push({email:t,role:r,projectName:e.projectName,projectPath:e.projectPath,processed:l,unprocessed:d})}return o}async function u(e,t=o.qu,r={}){if(r.email&&r.role)return void await p({states:e,stateDir:t,email:r.email,role:r.role})}async function p(e){let{states:t,stateDir:r,email:i,role:a}=e,o=await (0,n.Lf)(r);for(let e of t){let{projectName:t,projectPath:r}=e,s=await (0,n.Vr)(o,{email:i,role:a,projectName:t,projectPath:r}),l=i||"",d=new Set([...e.processed,...e.unprocessed.map(e=>e.id)]);for(let t of(await (0,n.Jo)(o,s.id,d),e.processed))await (0,n.x_)(o,t)||await (0,n.YC)(o,{id:t,subject:"",body:"",date:"",from:"",to:l}),await (0,n.Fh)(o,{processId:s.id,emailId:t,processCount:1,status:n.au.PROCESSED});for(let t of e.unprocessed)if(await (0,n.YC)(o,{id:t.id,subject:t.subject||"",body:t.body||"",date:t.date||"",from:t.from||"",to:l}),await (0,n.Fh)(o,{processId:s.id,emailId:t.id,processCount:0,status:n.au.UNPROCESSED}),Array.isArray(t.attachments)&&t.attachments.length>0)for(let e of(await (0,n.yh)(o,t.id),t.attachments))e&&"string"==typeof e.filename&&"string"==typeof e.contentType&&"number"==typeof e.size&&await (0,n.PT)(o,{emailId:t.id,filename:e.filename,contentType:e.contentType,size:e.size,content:e.content??null,filePath:e.filePath??null})}}function m(e){let t=(e.from||"").trim(),r=(e.date||"").trim(),i=(e.subject||"").trim(),o=`${t}|${r}|${i}`;return(0,a.createHash)("md5").update(o,"utf8").digest("hex")}[s,n]=l.then?(await l)():l,i()}catch(e){i(e)}})},8362(e,t,r){r.a(e,async function(e,i){try{r.d(t,{a:()=>v,l:()=>y});var a=r(2022),o=r(5012),n=r(5951),s=r(9995),l=r(247),d=r(9556),c=r(1984),u=r(7493),p=r(7893),m=r(5490),h=r(6150),g=r(8112),f=r(3998),k=r(5946),w=e([a]);a=(w.then?(await w)():w)[0];let b={ar:{translation:n.A},de:{translation:s.A},en:{translation:l.A},es:{translation:d.A},fr:{translation:c.A},it:{translation:u.A},ja:{translation:p.A},ko:{translation:m.A},nl:{translation:h.A},pt:{translation:g.A},zh:{translation:f.A},"zh-hant":{translation:k.A}};function v(){let e=(process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG||"").split(/[_.]/)[0].toLowerCase()||"";return e&&Object.hasOwn(b,e)?e:o.Kc}let S=!1;function y(e="en"){S||(a.default.init({lng:o.Kc,fallbackLng:o.Kc,resources:b,interpolation:{escapeValue:!1},showSupportNotice:!1}),S=!0);let t="string"==typeof e?e.trim():"";if(t){let e=t.toLowerCase();t="zh-tw"===e||"zh-hk"===e?"zh-hant":e}let r=t&&Object.hasOwn(b,t)?t:o.Kc;return(e,t={})=>a.default.t(e,{lng:r,...t})}i()}catch(e){i(e)}})},5951(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"المتطلب الأساسي",projectDir:"دليل المشروع (اعمل هنا): {{cwd}}",skillsInstruction:"استخدم أداة read_skill لتحميل تعليمات المهارة الكاملة عندما تتطابق المهمة مع وصفها.",toolArgSizeLimit:"لا تتجاوز أبداً {{maxChars}} حرفاً في معامل استدعاء أداة واحد (مثلاً content في write). الواجهة قد تقصّ النص الأطول وتسبب أخطاء \xabUnterminated string in JSON\xbb. للملفات أو السكربتات الطويلة، قسّم إلى استدعاءات write متعددة (حسب الملف أو حسب قطع أقل من {{maxChars}} حرفاً).",toolCallJsonFormat:'معطيات استدعاء الأداة يجب أن تكون JSON صالحاً: كل مفتاح وكل قيمة نصية بين علامتي تنصيص مزدوجة. مثال لـ write: {"path": "filename.md", "content": "المحتوى هنا"}. لا تحذف التنصيص حول المفاتيح أو القيم (مثلاً path: file.md غير صالح).'},errors:{missingPromptFiles:"ملفات التلميحات المطلوبة مفقودة في {{dir}}:",runInit:"شغّل 'pithosai init' في جذر المشروع لإنشاء .pithosai مع القوالب.",noApiKey:"لم يتم العثور على مفتاح API. اضبط DEEPSEEK_API_KEY أو OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama غير مهيأ. اضبط OPENAI_LOCAL_API_BASE أو استخدم مشروعاً بنموذج محلي.",noValidTemplateFiles:"لا توجد ملفات قوالب صالحة في {{dir}}. المتوقع *-<lang>.md (مثلاً IDENTITY-ja.md). شغّل 'pithosai init' لإنشاء .pithosai مع القوالب.",runTimeout:"انتهت مهلة تشغيل الوكيل بعد {{seconds}} ثانية. استخدم --timeout <seconds> أو PITHOSAI_TIMEOUT_MS للتعديل.",agentRunFailed:"فشل التشغيل: {{message}}",unknownRunError:"خطأ غير معروف"},warnings:{sessionAppend:"إلحاق الجلسة: {{message}}",apiRetry:"خطأ API في المحاولة {{attempt}}/{{max}}؛ إعادة المحاولة..."},reasoner:{thinkingHeader:"\n--- تفكير:\n",replyHeader:"\n\n--- رد:\n"},run:{cwd:"cwd {{cwd}}",request:"الطلب: {{request}}",interactivePrompt:"أنت: ",tuiYouLabel:"أنت:",interactiveExitHint:"يرجى الإجابة أو إدخال طلب جديد (اكتب 'exit' أو 'quit' للخروج من CLI).",interactiveModeCwd:"المجلد الحالي: {{cwd}}",interactiveModeAgentTitle:"--- الوضع التفاعلي — وكيل (أدوات كاملة) ---",interactiveModeAgentTips:"- مجموعة أدوات كاملة (قراءة وكتابة وتنفيذ حسب الإعدادات).\n- تُخزَّن الجولات لكل مهمة في قاعدة البيانات المحلية.\n- `/new` يعيّن معرّف مهمة جديدًا ولا يُحمّل الرسائل السابقة.\n- `/shell <أمر>` للتنفيذ في الطرفية؛ `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة.\n- `/list-skill` و`/install-skill` و`/remove-skill` يعادل `pithosai skills list|install|remove` (ClawHub). Ctrl+S للإيقاف، Ctrl+P للإيقاف المؤقت.",interactiveModeDialogTitle:"--- الوضع التفاعلي — حوار (أسئلة وأجوبة للقراءة فقط) ---",interactiveModeDialogTips:"- تُستخدم أدوات القراءة فقط (لا shell ولا تعديل ملفات ولا تنفيذ أوامر).\n- تُخزَّن الجولات لكل مهمة في قاعدة البيانات المحلية.\n- `/new` يعيّن معرّف مهمة جديدًا ولا يُحمّل الرسائل السابقة.\n- `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة.\n- `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub) مثل واجهة `pithosai skills`.",interactiveModePlanTitle:"--- وضع الخطة ---",interactiveModePlanTips:"- تُكتب كل إجابة في `<slug>-plan.md` داخل مجلد المشروع (السطر الأول من الطلب يؤثر على الاسم).\n- أدوات قراءة فقط؛ shell والأدوات المعدِّلة معطّلة.\n- `/new` يعيّن معرّف مهمة جديدًا.\n- `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة.\n- `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub) مثل واجهة `pithosai skills`.\n- بعد كل تشغيل يمكنك متابعة طلب خطة جديد عند المطالبة (مثل agent/dialog).",list:{noPersistedTasks:"لم يتم العثور على مهام محفوظة.",createTasksFirstHint:"أنشئ المهام أولاً باستخدام `pithosai task`.",persistedTasksHeader:"--- المهام المحفوظة ({{count}}) ---",selectTaskHint:"استخدم `/select <index>` لتشغيل مهمة.",noTasksCached:"لا توجد مهام مخزنة مؤقتاً. شغّل `/list` أولاً.",invalidIndex:"فهرس غير صالح: {{index}}. النطاق المسموح: 0-{{maxIndex}}.",selectUsage:"الاستخدام: /select <index>",selectedTask:"تم اختيار المهمة #{{index}}."},skillSlash:{installUsage:"الاستخدام: /install-skill [--force] [اسم-المهارة]",removeUsage:"الاستخدام: /remove-skill <اسم-المهارة>",listNoExtra:"أمر /list-skill لا يقبل وسائط.",failed:"فشل أمر المهارة: {{message}}"},show:{title:"المهمة الحالية",field:"الحقل",value:"القيمة",taskId:"taskId",mode:"الوضع",model:"النموذج",status:"الحالة",messageCount:"عدد_الرسائل",usageInput:"الاستخدام.إدخال",usageOutput:"الاستخدام.إخراج",usageCacheRead:"الاستخدام.قراءة_الكاش",usageCacheWrite:"الاستخدام.كتابة_الكاش",usageTotalTokens:"الاستخدام.إجمالي_الرموز"},showTask:{title:"أسئلة وأجوبة المهمة",taskIdLabel:"معرّف المهمة",turnHeading:"الجولة {{index}}",questionLabel:"السؤال",answerLabel:"الإجابة",createdLabel:"تاريخ الإنشاء",emptyQuestion:"(سؤال فارغ)",emptyAnswer:"(لا رد نصي من المساعد)",emptyNoMessages:"لا رسائل مستخدم لهذه المهمة بعد.",previewDocumentTitle:"أسئلة وأجوبة المهمة"},showPrompt:{previewDocumentTitle:"مطالبة النظام",previewHeading:"مطالبة النظام"},shellHint:"استخدم '/shell <command>' لتنفيذ أوامر shell (مثال: '/shell ls -la').",replIntroDialog:"وضع الحوار: أدوات قراءة فقط — `/shell` معطّل. استخدم `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة. `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub).",replIntroPlan:"وضع الخطة: تُحفظ كل إجابة في `<slug>-plan.md` (السطر الأول يؤثر على الاسم). `/shell` معطّل؛ الإخراج قليل حتى الاكتمال. استخدم `/list` و`/select` و`/show` و`/show-task` و`/show-prompt` للمهام المخزّنة. `/list-skill` و`/install-skill` و`/remove-skill` لإدارة المهارات (ClawHub).",newSessionHint:"استخدم '/new <طلب>' لبدء جلسة جديدة (بدون سجل الدردشة).",newSessionNoHistory:"استخدام جلسة جديدة (بدون سجل الدردشة).",controlHint:"اضغط Ctrl+S لإيقاف الوكيل الجاري، Ctrl+P للإيقاف المؤقت وإدخال أوامر فرعية.",replTabCompletionHint:"اضغط Tab لإكمال أوامر الشرطة المائلة (مثل /list و /list-skill و /show) أو exit/quit.",tuiScrollTranscriptHint:"في واجهة الطرفية: عجلة الفأرة، الأسهم، PgUp/PgDn، Ctrl+U/Ctrl+F (صفحة). Ctrl+U/F تمرّر السجل. Ctrl+D يبقى لنهاية المدخلات/الخروج عند السطر الفارغ أو الحذف للأمام أثناء الكتابة.",agentStopped:"تم إيقاف الوكيل.",pauseHeader:"--- الوكيل متوقف مؤقتاً ---",pauseCurrentRequest:"الطلب الحالي: {{request}}",pauseHelp:"الأوامر: 'continue' أو 'c' للمتابعة، 'exit' أو 'e' للخروج، أو اكتب طلباً جديداً لاستبدال الطلب الحالي.",pausePrompt:"[متوقف مؤقتاً] ",pauseRequestUpdated:"تم تحديث الطلب إلى: {{request}}"},shell:{noCommand:"لم يتم تقديم أمر بعد بادئة /shell. الاستخدام: /shell <command>",executionError:"خطأ في تنفيذ أمر shell: {{error}}",executing:"[shell] جاري التنفيذ: {{command}}",errorNoCommand:"لم يتم تقديم أمر بعد بادئة /shell.",errorSpawnFailed:"فشل بدء العملية: {{message}}",errorTimedOut:"انتهت مهلة الأمر بعد {{seconds}} ثانية",logFailed:"فشل أمر shell: {{command}} (رمز الخروج: {{code}})",logExecutionError:"خطأ تنفيذ أمر shell: {{message}}",resultCommand:"الأمر: {{command}}",resultExitCode:"رمز الخروج: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"النجاح:",resultSuccessYes:"نعم",resultSuccessNo:"لا",resultOutput:"المخرجات:",resultError:"الخطأ:"},init:{invalidType:'--type غير صالح "{{value}}"؛ اختر: {{choices}}',invalidLang:'--lang غير صالح "{{value}}"؛ اختر: {{choices}}',templatesDirNotFound:"لم يتم العثور على دليل القوالب: {{dir}}",createdPromptTemplates:"تم إنشاء {{dir}} (قوالب التلميحات)",createdSessions:"تم إنشاء {{dir}} (سجل الجلسات)",initialized:"تم تهيئة مشروع {{type}} في {{targetDir}}",promptFilesIn:"ملفات التلميحات في {{pithosaiDir}}، بيانات الجلسة في {{sessionsDir}}",runHint:'شغّل "pithosai -C {{targetDir}} \\"طلبك\\"" للبدء.',createdFile:"تم إنشاء {{path}}",roleAlreadyAdded:"الدور {{role}} موجود بالفعل في .pithosai؛ تخطي.",addedRoleTemplates:"تمت إضافة قوالب الأدوار إلى {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: أُغلقت المعاينة ({{source}})",skipped:"تخطّي معاينة المتصفح (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"قدّم إما markdown أو path فقط (لا كلاهما ولا بلا).",errorEmpty:"محتوى Markdown فارغ.",errorFileOutside:"يجب أن يبقى path داخل مجلد المشروع.",errorNotAFile:"path ليس ملفًا عاديًا.",errorFileTooLarge:"الملف أكبر من {{maxBytes}} بايت.",errorFileRead:"تعذّر قراءة الملف: {{message}}",sourceInline:"Markdown مضمّن",sourceFile:"ملف {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"البريد الإلكتروني لا يجب أن يكون فارغاً للـ heartbeat. قم بتكوين بريد دور {{role}} في جدول email_roles في قاعدة بيانات sqlite3.",loadedState:"تم تحميل حالة الـ heartbeat من SQLite للبريد {{email}} والدور {{role}}، الحالات: {{states}}",fetchFound:"وجد جلب الـ heartbeat للصندوق الوارد {{count}} مهام جديدة: {{ids}}",savedState:"تم حفظ حالة الـ heartbeat في SQLite للبريد {{email}} والدور {{role}}",mergedAndNext:"تم دمج {{merged}} مهام في الحالة، التالي للمعالجة: {{stateSummary}}",replyEmailFailed:"فشل إرسال بريد الرد للـ heartbeat: {{error}}",taskFailed:"فشلت مهمة الـ heartbeat: {{error}}",failureReplyEmailFailed:"فشل إرسال بريد إشعار الفشل للـ heartbeat: {{error}}"},cli:{description:"Pithosai: ينفذ الكود أو المشاريع من طلب بلغة طبيعية. يتم تحميل تلميحات الدور من قاعدة بيانات SQLite أثناء وقت التشغيل (مع خيار التراجع إلى .pithosai/<role>/*.md). أنشئ مشروعًا باستخدام 'pithosai init'.",versionOption:"عرض الإصدار",roleOption:"الدور (مجموعة القوالب لـ init)؛ القوالب في templates/<role>/",langOption:"لغة التلميحات وقوالب init: en, zh (الافتراضي: en)",interactiveModeOption:"الدخول إلى الوضع التفاعلي دون طلب؛ عرض نصائح الوضع وطلب الإدخال",initDescription:"إنشاء مشروع جديد وبنية دليل .pithosai/. يتم تحميل تلميحات الدور من قاعدة بيانات SQLite أثناء وقت التشغيل (مع خيار التراجع إلى .pithosai/<role>/*.md).",initTypeOption:"نوع المشروع: js أو ts أو python",initExamples:"\nأمثلة:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"إضافة قوالب الأدوار إلى .pithosai/<role>/ في المشروع",addRoleArgument:"الدور المراد إضافته (مثلاً PM, QA)",requestArgument:'ما الذي تريد بناؤه (مثلاً "واجهة CLI تحول CSV إلى JSON"). إذا حذفته، يعرض المساعدة.',cwdOption:"دليل المشروع (الافتراضي: الدليل الحالي)",skillsDirOption:"دليل المهارات لـ read_skill (الافتراضي: ./.pithosai/skills أو PITHOSAI_SKILLS_DIR)",reasonerOption:"استخدم نموذج DeepSeek Reasoner (تفكير)؛ الافتراضي DeepSeek Coder",chatOption:"استخدم نموذج DeepSeek Chat (محادثة عامة، وليس كود)؛ الافتراضي DeepSeek Coder",cursorOption:"استخدم نموذج Cursor CLI (المصادقة عبر cursor-agent login، لا حاجة لمفتاح API). يمكن تحديد النموذج اختيارياً: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"أقصى وقت تشغيل للوكيل بالثواني (الافتراضي: 1800). تجاوز بـ PITHOSAI_TIMEOUT_MS (مللي ثانية).",interactiveOption:"تعطيل المطالبة التفاعلية (الافتراضي: بعد كل رد، مطالبة بالرسالة التالية)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"جارٍ إنشاء الخطة…",waitingReply:"بانتظار الرد…",runningReply:"جارٍ التنفيذ…",resultPreviewOpening:"جارٍ فتح معاينة النتيجة في المتصفح…",resultPreviewTitle:"نتيجة Pithosai",resultPreviewFailed:"تعذر فتح المعاينة: {{message}}",resultPreviewCopy:"نسخ Markdown",resultPreviewClose:"إغلاق",resultPreviewCopied:"تم النسخ إلى الحافظة",resultPreviewTerminalHint:"↑↓ أو j/k \xb7 PgUp/PgDn أو Ctrl+U/Ctrl+D \xb7 Home/End أو gg/G \xb7 q/Esc للإغلاق",runExamples:'\nأمثلة:\n pithosai "أضف نقطة نهاية REST تُرجع الوقت الحالي"\n pithosai -C ./my-app "شغّل الاختبارات وأصلح الأخطاء"\n pithosai -i # الوضع التفاعلي: تحميل أحدث الجلسة ثم طلب الطلبات\n pithosai --no-interactive "طلب واحد" # رد واحد، بدون مطالبة متابعة\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"الاستخدام:",helpArguments:"الوسائط:",helpOptions:"الخيارات:",helpCommands:"الأوامر:",helpGlobalOptions:"الخيارات العامة:",helpOption:"عرض المساعدة للأمر",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"مراقبة ملف المهام ومعالجة المهام واحدة تلو الأخرى في نفس العملية",taskFileOption:"مسار ملف Markdown للمهام (الافتراضي: prompts.md في جذر المشروع)",taskModelOption:"مفتاح النموذج للمهمة (deepSeekCoder، deepSeekChat، deepSeekReasoner، ollamaQwen25، ollamaQwen25Coder، ollamaDeepSeekR1، cursorAutoModel، cursorSonnet، cursorSonnetThinking، cursorOpus، cursorGpt)",taskNewSessionOption:"البدء بجلسة جديدة (بدون سجل محادثة)",taskExamples:"\nأمثلة:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"المهمة غير موجودة: {{taskId}}",taskAgentCompleted:"اكتمل الوكيل.",taskAgentRunFailed:"فشل تشغيل الوكيل.",taskDone:"تم",taskFailed:"فشلت المهمة: {{message}}",taskProcessingHeader:"--- معالجة المهمة ---",taskLabelId:"المعرّف:",taskLabelTitle:"العنوان:",taskLabelStatus:"الحالة:",taskLabelDescription:"الوصف:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"بدء المعالج للمهمة قيد التنفيذ {{id}} ({{title}}).",taskNoPending:"لا توجد مهام معلّقة.",taskPickedTask:"تم اختيار المهمة {{id}} ({{title}})؛ بدء المعالج.",taskProcessorFailed:"فشل معالج المهام: {{message}}",taskWatcherRunning:"مراقب المهام يعمل. اضغط Ctrl+C للإيقاف.",memorizeDescription:"يكتب .pithosai/<role>/memory.md بملخصات للمهام التي شارك فيها الدور (رسائل مهام محفوظة ضمن النطاق الزمني).",memorizeStartOption:"بداية النطاق: YYYY-MM-DD أو ISO",memorizeEndOption:"نهاية النطاق: YYYY-MM-DD أو ISO",memorizeRoleRequired:"الدور مطلوب (-r/--role أو --role العام).",memorizeWrote:"تمت الكتابة إلى {{path}} ({{count}} مهمة).",memorizeNoTasks:"لا مهام في النطاق للدور {{role}}؛ تمت كتابة الترويسة إلى {{path}}.",memorizeDateError:"نطاق تاريخ غير صالح: {{message}}",memorizeNoLlmOption:"تخطي ملخص LLM؛ كتابة الذاكرة المنظمة فقط (مثل PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"فشل ملخص LLM ({{message}})؛ تمت كتابة ذاكرة منظمة دون ملخص.",memorizeExamples:"\nأمثلة:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"ترقية ملف pithosai.db النصي القديم (مثل v1.0.4) إلى SQLCipher. يستخدم مفتاحًا مرتبطًا بالجهاز كما في التطبيق (راجع docs/device-id.md). آمن للتشغيل أكثر من مرة.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Get shell commands for a request (Ollama only, outputs commands only)",argument:"What you want to do (e.g. list large files in current dir)",loading:"Getting commands...",examples:'\nExamples:\n $ pithosai shell-tips list json files in current directory\n $ pithosai shell-tips "find and replace foo with bar in all .js files"'},writer:{description:"Generate text for a request (Ollama qwen2.5:14b)",argument:"What to write (e.g. short email declining a meeting)",loading:"Writing...",examples:'\nExamples:\n $ pithosai writer short email declining a meeting\n $ pithosai writer "three bullet points for a project kickoff"'},skills:{installing:"تثبيت المهارات في {{dir}}",fetchingList:"جلب المهارات المتاحة من ClawHub...",fetchingIndex:"جلب فهرس المهارات من {{url}}",notFound:"المهارة '{{name}}' غير موجودة",noSkillsAvailable:"لا توجد مهارات متاحة من ClawHub",noSkillsFound:"لم يتم العثور على مهارات",downloadFailed:"فشل تحميل المهارة '{{name}}': {{error}}",installed:"تم تثبيت المهارة '{{name}}'",complete:"اكتمل التثبيت: {{count}} من {{total}} مهارات مثبتة",alreadyInstalled:"المهارة '{{name}}' مثبتة بالفعل (استخدم --force لإعادة التثبيت)",downloading:"جاري تحميل المهارة '{{name}}' من {{url}}",noSkillsDir:"لم يتم العثور على دليل المهارات. قم بتثبيت المهارات أولاً.",noSkillsInstalled:"لا توجد مهارات مثبتة",installedList:"المهارات المثبتة ({{count}} إجمالاً) في {{dir}}:",notInstalled:"المهارة '{{name}}' غير مثبتة",removed:"تمت إزالة المهارة '{{name}}'"},skillConvert:{welcome:"نظام تحويل المهارات - تحويل المهارات الناجحة إلى أدوات دائمة",listHeader:"تحليل تحويل المهارات ({{totalSkills}} مهارات، {{totalExecutions}} عملية تنفيذ)",noSuggestions:"لا توجد مهارات تصل إلى عتبة التحويل {{threshold}}.",suggestedConversions:"التحويلات المقترحة:",convertHint:"استخدم 'pithosai skill-convert convert <اسم-المهارة>' لتحويل مهارة.",skillNotFound:"المهارة '{{skillName}}' غير موجودة أو لا يمكن قراءتها: {{error}}",alreadyConverted:"المهارة '{{skillName}}' تم تحويلها بالفعل إلى أداة.",useForceHint:"استخدم --force للتحويل مرة أخرى.",conversionReportHeader:"تقرير تحويل '{{skillName}}':",conversionScore:"درجة التحويل",suggestedType:"النوع المقترح",ready:"جاهز للتحويل",estimatedBenefits:"الفوائد المقدّرة",performance:"تحسين الأداء",reliability:"تحسين الموثوقية",usability:"تحسين سهولة الاستخدام",parameters:"المعاملات",notReadyWarning:"هذه المهارة ليست جاهزة للتحويل التلقائي.",moreUsageHint:"استخدم المهارة بشكل أكثر تكراراً أو استخدم --force لفرض التحويل.",dryRunComplete:"اكتملت المحاكاة. لم يتم إجراء أي تغييرات.",confirmConversion:"تحويل '{{skillName}}' إلى أداة دائمة؟",conversionCancelled:"تم إلغاء التحويل.",converting:"جاري تحويل '{{skillName}}' إلى أداة...",conversionSuccess:"تم تحويل '{{skillName}}' بنجاح إلى '{{toolName}}'.\nالأداة محفوظة في: {{toolPath}}",usageExample:"مثال الاستخدام:",nextSteps:"الخطوات التالية:",restartAgent:"أعد تشغيل الوكيل لتحميل الأداة الجديدة",testTool:"اختبر الأداة: <اسم-الأداة> --help",manageTools:"إدارة الأدوات: pithosai skill-convert tools",listError:"خطأ في عرض المهارات: {{error}}",conversionError:"خطأ في تحويل '{{skillName}}': {{error}}",skillStatsHeader:"إحصائيات '{{skillName}}':",generalStats:"إحصائيات عامة",totalExecutions:"إجمالي عمليات التنفيذ",successful:"ناجحة",failed:"فاشلة",avgTime:"متوسط وقت التنفيذ",lastUsed:"آخر استخدام",recentExecutions:"عمليات التنفيذ الأخيرة",commonParameters:"المعاملات الشائعة",overallStatsHeader:"إحصائيات المهارات الإجمالية",overallStats:"إحصائيات إجمالية",totalSkillsTracked:"إجمالي المهارات المتتبعة",avgSuccessRate:"متوسط معدل النجاح",topSkills:"أكثر المهارات استخداماً",conversionSuggestions:"اقتراحات التحويل",statsError:"خطأ في الحصول على الإحصائيات: {{error}}",confirmClearAll:"مسح جميع سجلات تنفيذ المهارات؟ لا يمكن التراجع عن هذا الإجراء.",allRecordsCleared:"تم مسح جميع سجلات تنفيذ المهارات.",skillRecordsCleared:"تم مسح سجلات تنفيذ '{{skillName}}'.",clearCancelled:"تم إلغاء عملية المسح.",specifySkillOrAll:"حدد اسم مهارة أو استخدم --all",clearError:"خطأ في مسح السجلات: {{error}}",noConvertedTools:"لم يتم العثور على أدوات محوّلة.",convertedToolsHeader:"الأدوات المحوّلة:",originalSkill:"المهارة الأصلية",converted:"تم التحويل في",usageCount:"عدد الاستخدامات",toolsError:"خطأ في إدارة الأدوات: {{error}}",confirmRemoveTool:"إزالة الأداة '{{toolName}}'؟",toolRemoved:"تمت إزالة الأداة '{{toolName}}'.",toolRemoveFailed:"فشل في إزالة الأداة '{{toolName}}'.",removeCancelled:"تم إلغاء إزالة الأداة.",toolEnabled:"تم تفعيل الأداة '{{toolName}}'.",toolEnableFailed:"فشل في تفعيل الأداة '{{toolName}}'.",toolDisabled:"تم تعطيل الأداة '{{toolName}}'.",toolDisableFailed:"فشل في تعطيل الأداة '{{toolName}}'.",noStatsForSkill:"لم يتم العثور على إحصائيات للمهارة '{{skillName}}'."},hooks:{description:"إدارة خطافات الوكيل للتصحيح والأمان والمراقبة",list:{description:"عرض جميع الخطافات المسجلة",title:"\uD83D\uDCCB الخطافات المسجلة",total:"المجموع: {{total}} معالج",options:{verbose:"عرض معلومات تفصيلية عن المعالجات"},error:"فشل في عرض الخطافات: {{error}}"},debug:{description:"تفعيل خطافات التصحيح لمراقبة سلوك الوكيل",options:{data:"تسجيل البيانات الكاملة في مخرجات التصحيح",performance:"تفعيل خطافات مراقبة الأداء",stats:"تفعيل خطافات جمع الإحصائيات",all:"تفعيل جميع خطافات التصحيح"},added:{debug:"تمت إضافة خطافات سجل التصحيح",performance:"تمت إضافة خطافات مراقبة الأداء",stats:"تمت إضافة خطافات جمع الإحصائيات",basic:"تمت إضافة خطافات التصحيح الأساسية"},success:"تم تفعيل خطافات التصحيح ({{count}} معالج مسجل)",error:"فشل في تفعيل خطافات التصحيح: {{error}}"},security:{description:"تفعيل خطافات الأمان للتحكم في الوصول والمراقبة",options:{block:"قائمة أدوات للحظر مفصولة بفواصل",maxPrompt:"الحد الأقصى المسموح لطول المطالبة (الافتراضي: 10000)"},success:"تم تفعيل خطافات الأمان",blockedTools:"الأدوات المحظورة: {{tools}}",maxPrompt:"الحد الأقصى لطول المطالبة: {{length}} حرف",error:"فشل في تفعيل خطافات الأمان: {{error}}"},clear:{description:"مسح جميع الخطافات المسجلة",success:"تم مسح جميع الخطافات",error:"فشل في مسح الخطافات: {{error}}"},test:{description:"اختبار الخطافات عن طريق تشغيلها ببيانات اختبار",argument:{hookType:"نوع خطاف محدد للاختبار (اختياري)"},invalidType:"نوع خطاف غير صالح: {{type}}",triggered:"تم تشغيل الخطاف: {{type}}",result:"النتيجة: {{result}}",allTriggered:"تم تشغيل جميع الخطافات بنجاح",error:"فشل في اختبار الخطافات: {{error}}"},register:{description:"تسجيل معالج خطاف مخصص من ملف",argument:{hookType:"نوع الخطاف لتسجيل المعالج له",handlerFile:"مسار ملف المعالج (يجب أن يصدّر دالة افتراضية)"},invalidType:"نوع خطاف غير صالح: {{type}}",invalidHandler:"يجب أن يصدّر ملف المعالج دالة افتراضية",success:"تم تسجيل معالج لـ {{type}} من {{file}}",error:"فشل في تسجيل الخطاف: {{error}}"},status:{description:"عرض تكوين الخطافات الحالي والإحصائيات",title:"\uD83D\uDCCB حالة الخطافات",error:"فشل في الحصول على حالة الخطافات: {{error}}"}}}},9995(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Grundanforderung",projectDir:"Projektverzeichnis (hier arbeiten): {{cwd}}",skillsInstruction:"Verwende das read_skill-Tool, um die vollst\xe4ndigen Anweisungen einer F\xe4higkeit zu laden, wenn die Aufgabe zu ihrer Beschreibung passt.",toolArgSizeLimit:"\xdcberschreiten Sie niemals {{maxChars}} Zeichen in einem einzelnen Tool-Aufrufargument (z. B. dem content eines write). Gr\xf6\xdfere Nutzdaten k\xf6nnen von der API abgeschnitten werden und „Unterminated string in JSON“-Fehler verursachen. Lange Dateien oder Skripte in mehrere write-Aufrufe aufteilen (z. B. pro Datei oder pro Abschnitt unter {{maxChars}} Zeichen).",toolCallJsonFormat:'Tool-Aufrufargumente m\xfcssen g\xfcltiges JSON sein: Jeder Schl\xfcssel und jeder Zeichenkettenwert in doppelten Anf\xfchrungszeichen. Beispiel f\xfcr write: {"path": "dateiname.md", "content": "Inhalt hier"}. Lassen Sie keine Anf\xfchrungszeichen um Schl\xfcssel oder Werte weg (z. B. path: datei.md ist ung\xfcltig).'},errors:{missingPromptFiles:"Fehlende erforderliche Prompt-Dateien in {{dir}}:",runInit:"F\xfchre 'pithosai init' im Projektstamm aus, um .pithosai mit Vorlagen zu erstellen.",noApiKey:"Kein API-Schl\xfcssel gefunden. Setze DEEPSEEK_API_KEY oder OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama ist nicht konfiguriert. Setze OPENAI_LOCAL_API_BASE oder verwende ein Projekt mit lokalem Modell.",noValidTemplateFiles:"Keine g\xfcltigen Vorlagendateien in {{dir}}. Erwartet *-<lang>.md (z. B. IDENTITY-ja.md). F\xfchre 'pithosai init' aus, um .pithosai mit Vorlagen zu erstellen.",runTimeout:"Agent-Lauf nach {{seconds}} Sekunden abgelaufen. Verwende --timeout <Sekunden> oder PITHOSAI_TIMEOUT_MS zur Anpassung.",agentRunFailed:"Ausf\xfchrung fehlgeschlagen: {{message}}",unknownRunError:"Unbekannter Fehler"},warnings:{sessionAppend:"Sitzung anh\xe4ngen: {{message}}",apiRetry:"API-Fehler bei Versuch {{attempt}}/{{max}}; erneuter Versuch..."},reasoner:{thinkingHeader:"\n--- Denken:\n",replyHeader:"\n\n--- Antwort:\n"},run:{cwd:"cwd {{cwd}}",request:"Anfrage: {{request}}",interactivePrompt:"Sie: ",tuiYouLabel:"Sie:",interactiveExitHint:"Bitte antworten oder neue Anfrage eingeben („exit“ oder „quit“ zum Beenden der CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Interaktiv — Agent (volles Toolset) ---",interactiveModeAgentTips:"- Volles Toolset (Lesen, Schreiben, Ausf\xfchren, je nach Konfiguration).\n- Gespr\xe4che werden pro Aufgabe in der lokalen Datenbank gespeichert.\n- `/new` vergibt eine neue Aufgaben-ID; fr\xfchere Nachrichten werden nicht geladen.\n- `/shell <Befehl>` f\xfcr Shell; `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr Persistenz.\n- `/list-skill`, `/install-skill` und `/remove-skill` entsprechen `pithosai skills list|install|remove` (ClawHub). Strg+S stoppt, Strg+P pausiert.",interactiveModeDialogTitle:"--- Interaktiv — Dialog (Nur-Lese-Q&A) ---",interactiveModeDialogTips:"- Antworten nutzen nur Lesewerkzeuge (keine Shell, keine Datei\xe4nderungen, keine Befehle).\n- Gespr\xe4che werden pro Aufgabe in der lokalen Datenbank gespeichert.\n- `/new` vergibt eine neue Aufgaben-ID; fr\xfchere Nachrichten werden nicht geladen.\n- `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr persistierte Aufgaben.\n- `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub) wie die `pithosai skills`-CLI.",interactiveModePlanTitle:"--- Planmodus ---",interactiveModePlanTips:"- Jede Antwort wird als `<slug>-plan.md` im Projektverzeichnis gespeichert (die erste Zeile der Anfrage beeinflusst den Dateinamen).\n- Nur Lesewerkzeuge; Shell und \xe4ndernde Tools sind deaktiviert.\n- `/new` vergibt eine neue Aufgaben-ID.\n- `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr persistierte Aufgaben.\n- `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub) wie die `pithosai skills`-CLI.\n- Nach jedem Lauf k\xf6nnen Sie im Prompt weitere Plan-Anfragen eingeben (wie bei agent/dialog).",list:{noPersistedTasks:"Keine gespeicherten Aufgaben gefunden.",createTasksFirstHint:"Erstelle zuerst Aufgaben mit `pithosai task`.",persistedTasksHeader:"--- Gespeicherte Aufgaben ({{count}}) ---",selectTaskHint:"Verwende `/select <index>`, um eine Aufgabe auszuf\xfchren.",noTasksCached:"Keine Aufgaben zwischengespeichert. Bitte erst `/list` ausf\xfchren.",invalidIndex:"Ung\xfcltiger Index {{index}}. G\xfcltiger Bereich: 0-{{maxIndex}}.",selectUsage:"Verwendung: /select <index>",selectedTask:"Aufgabe #{{index}} ausgew\xe4hlt."},skillSlash:{installUsage:"Verwendung: /install-skill [--force] [skill-name]",removeUsage:"Verwendung: /remove-skill <skill-name>",listNoExtra:"/list-skill akzeptiert keine Argumente.",failed:"Skill-Befehl fehlgeschlagen: {{message}}"},show:{title:"Aktuelle Aufgabe",field:"Feld",value:"Wert",taskId:"taskId",mode:"Modus",model:"Modell",status:"Status",messageCount:"AnzahlNachrichten",usageInput:"Nutzung.Eingabe",usageOutput:"Nutzung.Ausgabe",usageCacheRead:"Nutzung.CacheLesen",usageCacheWrite:"Nutzung.CacheSchreiben",usageTotalTokens:"Nutzung.GesamtTokens"},showTask:{title:"Aufgaben-Q&A",taskIdLabel:"Aufgaben-ID",turnHeading:"Runde {{index}}",questionLabel:"Frage",answerLabel:"Antwort",createdLabel:"Erstellt",emptyQuestion:"(leere Frage)",emptyAnswer:"(keine Assistentenantwort als Text)",emptyNoMessages:"Noch keine Nutzernachrichten f\xfcr diese Aufgabe.",previewDocumentTitle:"Aufgaben-Q&A"},showPrompt:{previewDocumentTitle:"Systemaufforderung",previewHeading:"Systemaufforderung"},shellHint:"Verwenden Sie '/shell <Befehl>' zum Ausf\xfchren von Shell-Befehlen (z.B. '/shell ls -la').",replIntroDialog:"Dialogmodus: nur Lesewerkzeuge — `/shell` ist deaktiviert. `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` gelten f\xfcr persistierte Aufgaben. `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub).",replIntroPlan:"Planmodus: jede Antwort landet in `<slug>-plan.md` (erste Zeile beeinflusst den Namen). `/shell` ist deaktiviert; Ausgabe bleibt bis zum Abschluss minimal. `/list`, `/select`, `/show`, `/show-task` und `/show-prompt` f\xfcr persistierte Aufgaben. `/list-skill`, `/install-skill` und `/remove-skill` verwalten Skills (ClawHub).",newSessionHint:"Verwenden Sie '/new <Anfrage>' f\xfcr eine neue Sitzung (ohne Chatverlauf).",newSessionNoHistory:"Neue Sitzung wird verwendet (ohne Chatverlauf).",controlHint:"Strg+S dr\xfccken, um den laufenden Agenten zu stoppen, Strg+P zum Pausieren und Eingabe von Unterbefehlen.",replTabCompletionHint:"Tab zum Vervollst\xe4ndigen von Slash-Befehlen (z. B. /list, /list-skill, /show) oder exit/quit.",tuiScrollTranscriptHint:"Terminal-UI: Bei langem Protokoll — Mausrad, Pfeiltasten, Bild↑/↓, Strg+U/Strg+F (Seite). Strg+U/F scrollen das Protokoll statt der \xfcblichen Editor-K\xfcrzel. Strg+D bleibt EOF/Beenden bei leerer Zeile bzw. Zeichen l\xf6schen.",agentStopped:"Agent gestoppt.",pauseHeader:"--- Agent pausiert ---",pauseCurrentRequest:"Aktuelle Anfrage: {{request}}",pauseHelp:"Befehle: 'continue' oder 'c' zum Fortsetzen, 'exit' oder 'e' zum Beenden, oder geben Sie eine neue Anfrage ein, um die aktuelle zu ersetzen.",pausePrompt:"[pausiert] ",pauseRequestUpdated:"Anfrage aktualisiert auf: {{request}}"},shell:{noCommand:"Kein Befehl nach /shell-Pr\xe4fix angegeben. Verwendung: /shell <Befehl>",executionError:"Fehler beim Ausf\xfchren des Shell-Befehls: {{error}}",executing:"[shell] Ausf\xfchren: {{command}}",errorNoCommand:"Kein Befehl nach /shell-Pr\xe4fix angegeben.",errorSpawnFailed:"Prozess konnte nicht gestartet werden: {{message}}",errorTimedOut:"Befehl nach {{seconds}} Sekunden abgelaufen",logFailed:"Shell-Befehl fehlgeschlagen: {{command}} (Exit-Code: {{code}})",logExecutionError:"Shell-Befehl Ausf\xfchrungsfehler: {{message}}",resultCommand:"Befehl: {{command}}",resultExitCode:"Exit-Code: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Erfolg:",resultSuccessYes:"Ja",resultSuccessNo:"Nein",resultOutput:"Ausgabe:",resultError:"Fehler:"},init:{invalidType:'Ung\xfcltiges --type "{{value}}"; w\xe4hle: {{choices}}',invalidLang:'Ung\xfcltiges --lang "{{value}}"; w\xe4hle: {{choices}}',templatesDirNotFound:"Vorlagenverzeichnis nicht gefunden: {{dir}}",createdPromptTemplates:"{{dir}} erstellt (Prompt-Vorlagen)",createdSessions:"{{dir}} erstellt (Sitzungsverlauf)",initialized:"{{type}}-Projekt in {{targetDir}} initialisiert",promptFilesIn:"Prompt-Dateien in {{pithosaiDir}}, Sitzungsdaten in {{sessionsDir}}",runHint:'F\xfchre "pithosai -C {{targetDir}} \\"deine Anfrage\\"" aus, um zu starten.',createdFile:"{{path}} erstellt",roleAlreadyAdded:"Rolle {{role}} bereits in .pithosai vorhanden; \xfcberspringen.",addedRoleTemplates:"Rollen-Vorlagen zu {{dir}} hinzugef\xfcgt"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: Vorschau geschlossen ({{source}})",skipped:"Browser-Vorschau \xfcbersprungen (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Geben Sie genau eines von markdown oder path an (nicht beides, nicht keines).",errorEmpty:"Der Markdown-Inhalt ist leer.",errorFileOutside:"path muss im Projektverzeichnis liegen.",errorNotAFile:"path ist keine regul\xe4re Datei.",errorFileTooLarge:"Datei ist gr\xf6\xdfer als {{maxBytes}} Bytes.",errorFileRead:"Datei konnte nicht gelesen werden: {{message}}",sourceInline:"Inline-Markdown",sourceFile:"Datei {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"E-Mail darf f\xfcr Heartbeat nicht leer sein. Konfigurieren Sie die E-Mail f\xfcr Rolle {{role}} in der Tabelle email_roles in der sqlite3-Datenbank.",loadedState:"Heartbeat-Zustand aus SQLite geladen f\xfcr E-Mail {{email}} und Rolle {{role}}, Zust\xe4nde: {{states}}",fetchFound:"Heartbeat-Inbox-Abruf hat {{count}} neue Aufgaben gefunden: {{ids}}",savedState:"Heartbeat-Zustand in SQLite gespeichert f\xfcr E-Mail {{email}} und Rolle {{role}}",mergedAndNext:"{{merged}} Aufgaben in Zustand zusammengef\xfchrt, n\xe4chster zu bearbeiten: {{stateSummary}}",replyEmailFailed:"Heartbeat-Antwort-E-Mail fehlgeschlagen: {{error}}",taskFailed:"Heartbeat-Aufgabe fehlgeschlagen: {{error}}",failureReplyEmailFailed:"Heartbeat-Fehlermeldungs-E-Mail fehlgeschlagen: {{error}}"},cli:{description:"Pithosai: setzt Code oder Projekte aus einer Anfrage in nat\xfcrlicher Sprache um. Rollen-Prompts werden zur Laufzeit aus der SQLite-Datenbank geladen (mit optionalem Fallback auf .pithosai/<role>/*.md). Erstellen Sie ein Projekt mit 'pithosai init'.",versionOption:"Version ausgeben",roleOption:"Rolle (Vorlagensatz f\xfcr init); Vorlagen in templates/<role>/",langOption:"Sprache f\xfcr Prompts und Init-Vorlagen: en, zh (Standard: en)",interactiveModeOption:"Interaktiven Modus ohne Anfrage starten; Modushinweise anzeigen und zur Eingabe auffordern",initDescription:"Neues Projekt und .pithosai/ Verzeichnisstruktur erstellen. Rollen-Prompts werden zur Laufzeit aus der SQLite-Datenbank geladen (mit optionalem Fallback auf .pithosai/<role>/*.md).",initTypeOption:"Projekttyp: js, ts oder python",initExamples:"\nBeispiele:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Rollen-Vorlagen zu .pithosai/<role>/ im Projekt hinzuf\xfcgen",addRoleArgument:"Hinzuzuf\xfcgende Rolle (z. B. PM, QA)",requestArgument:'Was gebaut werden soll (z. B. "Ein CLI, der CSV in JSON konvertiert"). Bei Weglassen: Hilfe anzeigen.',cwdOption:"Projektverzeichnis (Standard: aktuelles Verzeichnis)",skillsDirOption:"F\xe4higkeiten-Verzeichnis f\xfcr read_skill (Standard: ./.pithosai/skills oder PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner (Denk-)Modell verwenden; Standard ist DeepSeek Coder",chatOption:"DeepSeek Chat-Modell verwenden (allgemeiner Chat, kein Code); Standard ist DeepSeek Coder",cursorOption:"Cursor CLI-Modell verwenden (Auth via cursor-agent login, kein API-Schl\xfcssel n\xf6tig). Optional Modell angeben: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"Max. Agent-Laufzeit in Sekunden (Standard: 1800). \xdcberschreiben mit PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"Interaktive Eingabeaufforderung deaktivieren (Standard: nach jeder Antwort nach n\xe4chster Nachricht fragen)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Plan wird erstellt…",waitingReply:"Warten auf Antwort…",runningReply:"L\xe4uft…",resultPreviewOpening:"Vorschau wird im Browser ge\xf6ffnet…",resultPreviewTitle:"Pithosai-Ergebnis",resultPreviewFailed:"Vorschau konnte nicht ge\xf6ffnet werden: {{message}}",resultPreviewCopy:"Markdown kopieren",resultPreviewClose:"Schlie\xdfen",resultPreviewCopied:"In die Zwischenablage kopiert",resultPreviewTerminalHint:"↑↓ oder j/k \xb7 PgUp/PgDn oder Ctrl+U/Ctrl+D \xb7 Home/End oder gg/G \xb7 q/Esc schlie\xdfen",runExamples:'\nBeispiele:\n pithosai "F\xfcge einen REST-Endpoint hinzu, der die aktuelle Zeit zur\xfcckgibt"\n pithosai -C ./my-app "Tests ausf\xfchren und Fehler beheben"\n pithosai -i # Interaktiver Modus: letzte Sitzung laden, dann zur Eingabe auffordern\n pithosai --no-interactive "Einmal" # eine Antwort, keine Folgenachfrage\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Verwendung:",helpArguments:"Argumente:",helpOptions:"Optionen:",helpCommands:"Befehle:",helpGlobalOptions:"Globale Optionen:",helpOption:"Hilfe f\xfcr Befehl anzeigen",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Aufgabendatei \xfcberwachen und Aufgaben nacheinander im selben Prozess verarbeiten",taskFileOption:"Pfad zur Aufgaben-Markdown-Datei (Standard: prompts.md im Projektroot)",taskModelOption:"Modellschl\xfcssel f\xfcr die Aufgabe (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Mit neuer Sitzung starten (kein Chatverlauf)",taskExamples:"\nBeispiele:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Aufgabe nicht gefunden: {{taskId}}",taskAgentCompleted:"Agent abgeschlossen.",taskAgentRunFailed:"Agentenlauf fehlgeschlagen.",taskDone:"Fertig",taskFailed:"Aufgabe fehlgeschlagen: {{message}}",taskProcessingHeader:"--- Aufgabe wird verarbeitet ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Starte Verarbeitung f\xfcr laufende Aufgabe {{id}} ({{title}}).",taskNoPending:"Keine ausstehenden Aufgaben.",taskPickedTask:"Aufgabe {{id}} ({{title}}) ausgew\xe4hlt; starte Verarbeitung.",taskProcessorFailed:"Aufgabenprozessor fehlgeschlagen: {{message}}",taskWatcherRunning:"Aufgaben\xfcberwachung aktiv. Strg+C zum Beenden.",memorizeDescription:"Schreibt .pithosai/<role>/memory.md mit Zusammenfassungen der Aufgaben, an denen die Rolle beteiligt war (persistierte Aufgabenmeldungen im Zeitraum).",memorizeStartOption:"Beginn: YYYY-MM-DD oder ISO-Datum/-zeit",memorizeEndOption:"Ende: YYYY-MM-DD oder ISO-Datum/-zeit",memorizeRoleRequired:"Rolle ist erforderlich (-r/--role oder globales --role).",memorizeWrote:"Geschrieben: {{path}} ({{count}} Aufgabe(n)).",memorizeNoTasks:"Keine Aufgaben im Zeitraum f\xfcr Rolle {{role}}; Kopfzeile nach {{path}} geschrieben.",memorizeDateError:"Ung\xfcltiger Datumsbereich: {{message}}",memorizeNoLlmOption:"LLM-Zusammenfassung \xfcberspringen; nur strukturiertes Ged\xe4chtnis schreiben (wie PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"LLM-Zusammenfassung fehlgeschlagen ({{message}}); strukturiertes Ged\xe4chtnis ohne Zusammenfassung geschrieben.",memorizeExamples:"\nBeispiele:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Get shell commands for a request (Ollama only, outputs commands only)",argument:"What you want to do (e.g. list large files in current dir)",loading:"Getting commands...",examples:'\nExamples:\n $ pithosai shell-tips list json files in current directory\n $ pithosai shell-tips "find and replace foo with bar in all .js files"'},writer:{description:"Generate text for a request (Ollama qwen2.5:14b)",argument:"What to write (e.g. short email declining a meeting)",loading:"Writing...",examples:'\nExamples:\n $ pithosai writer short email declining a meeting\n $ pithosai writer "three bullet points for a project kickoff"'},skills:{installing:"F\xe4higkeiten in {{dir}} installieren",fetchingList:"Verf\xfcgbare F\xe4higkeiten von ClawHub abrufen...",fetchingIndex:"F\xe4higkeiten-Index von {{url}} abrufen",notFound:"F\xe4higkeit '{{name}}' nicht gefunden",noSkillsAvailable:"Keine F\xe4higkeiten von ClawHub verf\xfcgbar",noSkillsFound:"Keine F\xe4higkeiten gefunden",downloadFailed:"Herunterladen der F\xe4higkeit '{{name}}' fehlgeschlagen: {{error}}",installed:"F\xe4higkeit '{{name}}' installiert",complete:"Installation abgeschlossen: {{count}} von {{total}} F\xe4higkeiten installiert",alreadyInstalled:"F\xe4higkeit '{{name}}' bereits installiert (--force zum Neuinstallieren verwenden)",downloading:"F\xe4higkeit '{{name}}' von {{url}} wird heruntergeladen",noSkillsDir:"Kein F\xe4higkeiten-Verzeichnis gefunden. Installieren Sie zuerst F\xe4higkeiten.",noSkillsInstalled:"Keine F\xe4higkeiten installiert",installedList:"Installierte F\xe4higkeiten ({{count}} insgesamt) in {{dir}}:",notInstalled:"F\xe4higkeit '{{name}}' ist nicht installiert",removed:"F\xe4higkeit '{{name}}' entfernt"},skillConvert:{welcome:"F\xe4higkeiten-Konvertierungssystem - Erfolgreiche F\xe4higkeiten in permanente Tools umwandeln",listHeader:"F\xe4higkeiten-Konvertierungsanalyse ({{totalSkills}} F\xe4higkeiten, {{totalExecutions}} Ausf\xfchrungen)",noSuggestions:"Keine F\xe4higkeiten erreichen den Konvertierungsschwellenwert von {{threshold}}.",suggestedConversions:"Vorgeschlagene Konvertierungen:",convertHint:"Verwende 'pithosai skill-convert convert <F\xe4higkeitenname>' zum Konvertieren.",skillNotFound:"F\xe4higkeit '{{skillName}}' nicht gefunden oder nicht lesbar: {{error}}",alreadyConverted:"F\xe4higkeit '{{skillName}}' wurde bereits in ein Tool konvertiert.",useForceHint:"Verwende --force zum erneuten Konvertieren.",conversionReportHeader:"Konvertierungsbericht f\xfcr '{{skillName}}':",conversionScore:"Konvertierungsscore",suggestedType:"Vorgeschlagener Typ",ready:"Bereit zur Konvertierung",estimatedBenefits:"Gesch\xe4tzte Vorteile",performance:"Leistungsverbesserung",reliability:"Zuverl\xe4ssigkeitsverbesserung",usability:"Benutzerfreundlichkeitsverbesserung",parameters:"Parameter",notReadyWarning:"Diese F\xe4higkeit ist nicht bereit f\xfcr die automatische Konvertierung.",moreUsageHint:"Verwende die F\xe4higkeit h\xe4ufiger oder nutze --force zur erzwungenen Konvertierung.",dryRunComplete:"Testlauf abgeschlossen. Keine \xc4nderungen vorgenommen.",confirmConversion:"'{{skillName}}' in ein permanentes Tool konvertieren?",conversionCancelled:"Konvertierung abgebrochen.",converting:"'{{skillName}}' wird in Tool konvertiert...",conversionSuccess:"'{{skillName}}' erfolgreich in '{{toolName}}' konvertiert.\nTool gespeichert in: {{toolPath}}",usageExample:"Verwendungsbeispiel:",nextSteps:"N\xe4chste Schritte:",restartAgent:"Agent neu starten, um das neue Tool zu laden",testTool:"Tool testen: <Tool-Name> --help",manageTools:"Tools verwalten: pithosai skill-convert tools",listError:"Fehler beim Auflisten der F\xe4higkeiten: {{error}}",conversionError:"Fehler bei der Konvertierung von '{{skillName}}': {{error}}",skillStatsHeader:"Statistiken f\xfcr '{{skillName}}':",generalStats:"Allgemeine Statistiken",totalExecutions:"Ausf\xfchrungen gesamt",successful:"Erfolgreich",failed:"Fehlgeschlagen",avgTime:"Durchschnittliche Ausf\xfchrungszeit",lastUsed:"Zuletzt verwendet",recentExecutions:"Letzte Ausf\xfchrungen",commonParameters:"H\xe4ufige Parameter",overallStatsHeader:"Gesamtstatistiken der F\xe4higkeiten",overallStats:"Gesamtstatistiken",totalSkillsTracked:"Verfolgte F\xe4higkeiten gesamt",avgSuccessRate:"Durchschnittliche Erfolgsrate",topSkills:"Meistgenutzte F\xe4higkeiten",conversionSuggestions:"Konvertierungsvorschl\xe4ge",statsError:"Fehler beim Abrufen der Statistiken: {{error}}",confirmClearAll:"ALLE F\xe4higkeiten-Ausf\xfchrungsdatens\xe4tze l\xf6schen? Dies kann nicht r\xfcckg\xe4ngig gemacht werden.",allRecordsCleared:"Alle F\xe4higkeiten-Ausf\xfchrungsdatens\xe4tze gel\xf6scht.",skillRecordsCleared:"Ausf\xfchrungsdatens\xe4tze f\xfcr '{{skillName}}' gel\xf6scht.",clearCancelled:"L\xf6schvorgang abgebrochen.",specifySkillOrAll:"Bitte F\xe4higkeitenname angeben oder --all verwenden",clearError:"Fehler beim L\xf6schen der Datens\xe4tze: {{error}}",noConvertedTools:"Keine konvertierten Tools gefunden.",convertedToolsHeader:"Konvertierte Tools:",originalSkill:"Urspr\xfcngliche F\xe4higkeit",converted:"Konvertiert am",usageCount:"Verwendungsanzahl",toolsError:"Fehler bei der Tool-Verwaltung: {{error}}",confirmRemoveTool:"Tool '{{toolName}}' entfernen?",toolRemoved:"Tool '{{toolName}}' entfernt.",toolRemoveFailed:"Entfernen von Tool '{{toolName}}' fehlgeschlagen.",removeCancelled:"Tool-Entfernung abgebrochen.",toolEnabled:"Tool '{{toolName}}' aktiviert.",toolEnableFailed:"Aktivierung von Tool '{{toolName}}' fehlgeschlagen.",toolDisabled:"Tool '{{toolName}}' deaktiviert.",toolDisableFailed:"Deaktivierung von Tool '{{toolName}}' fehlgeschlagen.",noStatsForSkill:"Keine Statistiken f\xfcr F\xe4higkeit '{{skillName}}' gefunden."},hooks:{description:"Agent-Hooks f\xfcr Debugging, Sicherheit und \xdcberwachung verwalten",list:{description:"Alle registrierten Hooks auflisten",title:"\uD83D\uDCCB Registrierte Hooks",total:"Gesamt: {{total}} Handler",options:{verbose:"Detaillierte Handler-Informationen anzeigen"},error:"Hooks konnten nicht aufgelistet werden: {{error}}"},debug:{description:"Debug-Hooks zur \xdcberwachung des Agent-Verhaltens aktivieren",options:{data:"Vollst\xe4ndige Daten in der Debug-Ausgabe protokollieren",performance:"Performance-\xdcberwachungs-Hooks aktivieren",stats:"Statistik-Erfassungs-Hooks aktivieren",all:"Alle Debug-Hooks aktivieren"},added:{debug:"Debug-Logging-Hooks hinzugef\xfcgt",performance:"Performance-\xdcberwachungs-Hooks hinzugef\xfcgt",stats:"Statistik-Erfassungs-Hooks hinzugef\xfcgt",basic:"Basis-Debug-Hooks hinzugef\xfcgt"},success:"Debug-Hooks aktiviert ({{count}} Handler registriert)",error:"Debug-Hooks konnten nicht aktiviert werden: {{error}}"},security:{description:"Sicherheits-Hooks f\xfcr Zugriffskontrolle und \xdcberwachung aktivieren",options:{block:"Kommagetrennte Liste der zu blockierenden Tools",maxPrompt:"Maximal erlaubte Prompt-L\xe4nge (Standard: 10000)"},success:"Sicherheits-Hooks aktiviert",blockedTools:"Blockierte Tools: {{tools}}",maxPrompt:"Maximale Prompt-L\xe4nge: {{length}} Zeichen",error:"Sicherheits-Hooks konnten nicht aktiviert werden: {{error}}"},clear:{description:"Alle registrierten Hooks l\xf6schen",success:"Alle Hooks gel\xf6scht",error:"Hooks konnten nicht gel\xf6scht werden: {{error}}"},test:{description:"Hooks mit Testdaten ausl\xf6sen und testen",argument:{hookType:"Bestimmter Hook-Typ zum Testen (optional)"},invalidType:"Ung\xfcltiger Hook-Typ: {{type}}",triggered:"Hook ausgel\xf6st: {{type}}",result:"Ergebnis: {{result}}",allTriggered:"Alle Hooks erfolgreich ausgel\xf6st",error:"Hooks konnten nicht getestet werden: {{error}}"},register:{description:"Benutzerdefinierten Hook-Handler aus einer Datei registrieren",argument:{hookType:"Hook-Typ f\xfcr den Handler",handlerFile:"Pfad zur Handler-Datei (muss eine Standardfunktion exportieren)"},invalidType:"Ung\xfcltiger Hook-Typ: {{type}}",invalidHandler:"Handler-Datei muss eine Standardfunktion exportieren",success:"Handler f\xfcr {{type}} aus {{file}} registriert",error:"Hook konnte nicht registriert werden: {{error}}"},status:{description:"Aktuelle Hook-Konfiguration und Statistiken anzeigen",title:"\uD83D\uDCCB Hook-Status",error:"Hook-Status konnte nicht abgerufen werden: {{error}}"}}}},247(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Base requirement",projectDir:"Project directory (work here): {{cwd}}",skillsInstruction:"Use the read_skill tool to load a skill's full instructions when the task matches its description.",toolArgSizeLimit:'Never exceed {{maxChars}} characters in a single tool-call argument (e.g. the content of a write call). The API can truncate larger payloads and cause "Unterminated string in JSON" errors. For long files or scripts, split into multiple write calls (e.g. by file or by chunk under {{maxChars}} chars each).',toolCallJsonFormat:'Tool-call arguments must be valid JSON: every key and every string value must be in double quotes. Example for write: {"path": "filename.md", "content": "content here"}. Do not omit quotes around keys or values (e.g. path: file.md or content: text is invalid).'},errors:{missingPromptFiles:"missing required prompt files in {{dir}}:",runInit:"Run 'pithosai init' in the project root to create .pithosai with templates.",noApiKey:"no API key found. Set CURSOR_MODEL (e.g. auto), DEEPSEEK_API_KEY, or OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama is not configured. Set OPENAI_LOCAL_API_BASE or use a project with local model.",noValidTemplateFiles:"no valid template files in {{dir}}. Expected *-<lang>.md (e.g. IDENTITY-ja.md). Run 'pithosai init' to create .pithosai with templates.",runTimeout:"Agent run timed out after {{seconds}} seconds. Use --timeout <seconds> or PITHOSAI_TIMEOUT_MS to adjust.",agentRunFailed:"Run failed: {{message}}",unknownRunError:"Unknown error"},warnings:{sessionAppend:"session append: {{message}}",apiRetry:"API error on attempt {{attempt}}/{{max}}; retrying..."},reasoner:{thinkingHeader:"\n--- Thinking:\n",replyHeader:"\n\n--- Reply:\n"},run:{cwd:"cwd {{cwd}}",request:"request: {{request}}",interactivePrompt:"You: ",tuiYouLabel:"You:",interactiveExitHint:"Please answer or input new request(type 'exit' or 'quit' to exit the CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Interactive mode — Agent (full tools) ---",interactiveModeAgentTips:"- Full toolset (read, write, exec, and other tools as configured).\n- Conversation turns are stored per task in the local database.\n- `/new` assigns a new task id so prior messages are not loaded.\n- `/shell <command>` runs shell commands; `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work with persisted tasks.\n- `/list-skill`, `/install-skill`, and `/remove-skill` mirror `pithosai skills list|install|remove` (ClawHub). Ctrl+S stops the run, Ctrl+P pauses.",interactiveModeDialogTitle:"--- Interactive mode — Dialog (read-only Q&A) ---",interactiveModeDialogTips:"- Answers use read-only tools only (no shell, file edits, or command execution).\n- Conversation turns are stored per task in the local database.\n- `/new` assigns a new task id so prior messages are not loaded.\n- `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work with persisted tasks.\n- `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub) like the `pithosai skills` CLI.",interactiveModePlanTitle:"--- Plan mode ---",interactiveModePlanTips:"- Each reply is written to a `<slug>-plan.md` file in the project directory (the first line of your request shapes the filename).\n- Read-only tools only; shell and mutating tools are disabled.\n- `/new` assigns a new task id.\n- `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work with persisted tasks.\n- `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub) like the `pithosai skills` CLI.\n- You can enter more plan requests at the prompt after each run (same as agent/dialog).",list:{noPersistedTasks:"No persisted tasks found.",createTasksFirstHint:"Create tasks first using `pithosai task`.",persistedTasksHeader:"--- Persisted tasks ({{count}}) ---",selectTaskHint:"Use `/select <index>` to run a task.",noTasksCached:"No tasks cached. Run `/list` first.",invalidIndex:"Invalid index {{index}}. Valid range: 0-{{maxIndex}}.",selectUsage:"Usage: /select <index>",selectedTask:"Selected task #{{index}}."},skillSlash:{installUsage:"Usage: /install-skill [--force] [skill-name]",removeUsage:"Usage: /remove-skill <skill-name>",listNoExtra:"/list-skill does not take arguments.",failed:"Skill command failed: {{message}}"},show:{title:"Current task",field:"Field",value:"Value",taskId:"taskId",mode:"mode",model:"model",status:"status",messageCount:"messageCount",usageInput:"usage.input",usageOutput:"usage.output",usageCacheRead:"usage.cacheRead",usageCacheWrite:"usage.cacheWrite",usageTotalTokens:"usage.totalTokens"},showTask:{title:"Task Q&A",taskIdLabel:"Task ID",turnHeading:"Turn {{index}}",questionLabel:"Question",answerLabel:"Answer",createdLabel:"Created",emptyQuestion:"(empty question)",emptyAnswer:"(no assistant text reply)",emptyNoMessages:"No user messages for this task yet. Nothing to show.",previewDocumentTitle:"Task Q&A"},showPrompt:{previewDocumentTitle:"System prompt",previewHeading:"System prompt"},shellHint:"Use '/shell <command>' to execute shell commands (e.g., '/shell ls -la').",replIntroDialog:"Dialog mode: read-only tools only — `/shell` is disabled. `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work for persisted tasks. `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub).",replIntroPlan:"Plan mode: each reply is written to `<slug>-plan.md` in the project directory (first line of the request shapes the filename). `/shell` is disabled; output stays minimal until the plan completes. `/list`, `/select`, `/show`, `/show-task`, and `/show-prompt` work for persisted tasks. `/list-skill`, `/install-skill`, and `/remove-skill` manage skills (ClawHub).",newSessionHint:"Use '/new <request>' to start a new session (no chat history).",newSessionNoHistory:"Using new session (no chat history).",controlHint:"Press Ctrl+S to stop the running agent, Ctrl+P to pause and enter sub-commands.",replTabCompletionHint:"Press Tab to complete slash commands (e.g. /list, /list-skill, /show) or exit/quit.",tuiScrollTranscriptHint:"In the terminal UI, long output: scroll with the mouse wheel, arrows, PgUp/PgDn, or Ctrl+U / Ctrl+F (page). Ctrl+U/Ctrl+F scroll the transcript instead of the editor’s usual line-edit shortcuts. Ctrl+D is unchanged (EOF / exit on empty line, delete forward when typing).",agentStopped:"Agent stopped.",pauseHeader:"--- Agent paused ---",pauseCurrentRequest:"Current request: {{request}}",pauseHelp:"Commands: 'continue' or 'c' to resume, 'exit' or 'e' to quit, or type a new request to replace the current one.",pausePrompt:"[paused] ",pauseRequestUpdated:"Request updated to: {{request}}"},shell:{noCommand:"No command provided after /shell prefix. Usage: /shell <command>",executionError:"Error executing shell command: {{error}}",executing:"[shell] Executing: {{command}}",errorNoCommand:"No command provided after /shell prefix.",errorSpawnFailed:"Failed to spawn process: {{message}}",errorTimedOut:"Command timed out after {{seconds}} seconds",logFailed:"Shell command failed: {{command}} (exit code: {{code}})",logExecutionError:"Shell command execution error: {{message}}",resultCommand:"Command: {{command}}",resultExitCode:"Exit code: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Success:",resultSuccessYes:"Yes",resultSuccessNo:"No",resultOutput:"Output:",resultError:"Error:"},init:{invalidType:'invalid --type "{{value}}"; choose: {{choices}}',invalidLang:'invalid --lang "{{value}}"; choose: {{choices}}',templatesDirNotFound:"templates directory not found: {{dir}}",createdPromptTemplates:"created {{dir}} (prompt templates)",createdSessions:"created {{dir}} (session history)",initialized:"initialized {{type}} project in {{targetDir}}",promptFilesIn:"prompt files in {{pithosaiDir}}, session data in {{sessionsDir}}",runHint:'run "pithosai -C {{targetDir}} \\"your request\\"" to start.',createdFile:"created {{path}}",roleAlreadyAdded:"role {{role}} already present in .pithosai; skipping.",addedRoleTemplates:"added role templates to {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: preview closed ({{source}})",skipped:"Browser preview skipped (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Provide exactly one of markdown or path (not both, not neither).",errorEmpty:"Markdown content is empty.",errorFileOutside:"path must stay under the project directory.",errorNotAFile:"path is not a regular file.",errorFileTooLarge:"File is larger than {{maxBytes}} bytes.",errorFileRead:"Could not read file: {{message}}",sourceInline:"inline markdown",sourceFile:"file {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"Email must not be empty for heartbeat. Configure role {{role}} email in email_roles table in sqlite3 db",loadedState:"Loaded heartbeat state from SQLite for email {{email}} and role {{role}}, states: {{states}}",fetchFound:"Heartbeat fetch inbox found {{count}} new tasks: {{ids}}",savedState:"Saved heartbeat state to SQLite for email {{email}} and role {{role}}",mergedAndNext:"Merged {{merged}} tasks into state, found next state to process: {{stateSummary}}",replyEmailFailed:"Heartbeat reply email failed: {{error}}",taskFailed:"Heartbeat task failed: {{error}}",failureReplyEmailFailed:"Heartbeat failure reply email failed: {{error}}"},cli:{description:"Pithosai: implements code or projects from a natural-language request. Role prompts are loaded from the SQLite DB at runtime (with optional fallback to .pithosai/<role>/*.md). Create project with 'pithosai init'.",versionOption:"output version",roleOption:"role (template set to use for init); templates are in templates/<role>/",langOption:"language for prompts and init templates: en, zh (default: en)",interactiveModeOption:"enter interactive mode without a request; show mode tips and prompt for input",initDescription:"Create a new project and .pithosai/ directory structure. Role prompts are loaded from the SQLite DB at runtime (with optional fallback to .pithosai/<role>/*.md).",initTypeOption:"project type: js, ts, or python",initExamples:"\nExamples:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Add role templates to .pithosai/<role>/ in the project",addRoleArgument:"role to add (e.g. PM, QA)",requestArgument:'what to build (e.g. "A CLI that converts CSV to JSON"). If omitted, show help.',cwdOption:"project directory (default: current directory)",skillsDirOption:"skills directory for read_skill (default: ./.pithosai/skills or PITHOSAI_SKILLS_DIR)",reasonerOption:"use DeepSeek Reasoner (thinking) model; default is DeepSeek Coder",chatOption:"use DeepSeek Chat model (general chat, not code); default is DeepSeek Coder",cursorOption:"use Cursor CLI model (auth via cursor-agent login, no API key needed). Optionally specify model: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"max agent run time in seconds (default: 1800). Override with PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"disable interactive prompt (default: after each reply, prompt for your next message)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Generating plan…",waitingReply:"Waiting for reply…",runningReply:"Running…",resultPreviewOpening:"Opening result preview in browser…",resultPreviewTitle:"Pithosai result",resultPreviewFailed:"Could not open result preview: {{message}}",resultPreviewCopy:"Copy markdown",resultPreviewClose:"Close",resultPreviewCopied:"Copied to clipboard",resultPreviewTerminalHint:"↑↓ or j/k \xb7 PgUp/PgDn or Ctrl+U/Ctrl+D \xb7 Home/End or gg/G \xb7 q/Esc close",runExamples:'\nExamples:\n pithosai "Add a REST endpoint that returns the current time"\n pithosai -C ./my-app "Run tests and fix failures"\n pithosai -i # interactive mode: load latest session, then prompt for requests\n pithosai --no-interactive "One shot" # single reply, no follow-up prompt\n pithosai --mode dialog "Explain this error" # chat only; no tools or /shell\n pithosai --mode plan "Sprint plan for the API" # writes e.g. sprint-plan-for-the-api-plan.md\n',helpUsage:"Usage:",helpArguments:"Arguments:",helpOptions:"Options:",helpCommands:"Commands:",helpGlobalOptions:"Global Options:",helpOption:"display help for command",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Watch task file and process tasks (one at a time in the same process)",taskFileOption:"Path to task markdown file (default: prompts.md in project root)",taskModelOption:"Model key for the task (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Start with a new session (no chat history)",taskExamples:"\nExamples:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Task not found: {{taskId}}",taskAgentCompleted:"Agent completed.",taskAgentRunFailed:"Agent run failed.",taskDone:"Done",taskFailed:"Task failed: {{message}}",taskProcessingHeader:"--- Processing task ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Starting processor for processing task {{id}} ({{title}}).",taskNoPending:"No pending tasks.",taskPickedTask:"Picked task {{id}} ({{title}}); starting processor.",taskProcessorFailed:"Task processor failed: {{message}}",taskWatcherRunning:"Task watcher running. Ctrl+C to stop.",showPromptDescription:"Display the system prompt that would be used for a run",showPromptModeOption:"mode: agent, dialog, or plan (default: agent)",showPromptRawOption:"show raw prompt before truncation and tool blocks",showPromptTruncatedOption:"show truncated prompt (requires model config)",showPromptInvalidMode:"Invalid mode. Must be 'agent', 'dialog', or 'plan'.",showPromptError:"Error building prompt: {{message}}",memorizeDescription:"Write .pithosai/<role>/memory.md with summaries of tasks the role participated in (from persisted task messages in the date range).",memorizeStartOption:"Range start: YYYY-MM-DD or ISO datetime",memorizeEndOption:"Range end: YYYY-MM-DD or ISO datetime",memorizeRoleRequired:"Role is required (use -r/--role or global --role).",memorizeWrote:"Wrote {{path}} ({{count}} task(s)).",memorizeNoTasks:"No tasks in range for role {{role}}; wrote header to {{path}}.",memorizeDateError:"Invalid date range: {{message}}",memorizeNoLlmOption:"Skip LLM summarization; write structured memory only (same as PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"LLM summarization failed ({{message}}); wrote structured memory without summary.",memorizeExamples:"\nExamples:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Get shell commands for a request (Ollama only, outputs commands only)",argument:"What you want to do (e.g. list large files in current dir)",loading:"Getting commands...",examples:'\nExamples:\n $ pithosai shell-tips list json files in current directory\n $ pithosai shell-tips "find and replace foo with bar in all .js files"'},writer:{description:"Generate text for a request (Ollama qwen2.5:14b)",argument:"What to write (e.g. short email declining a meeting)",loading:"Writing...",examples:'\nExamples:\n $ pithosai writer short email declining a meeting\n $ pithosai writer "three bullet points for a project kickoff"'},skills:{installing:"Installing skills to {{dir}}",fetchingList:"Fetching available skills from ClawHub...",fetchingIndex:"Fetching skills index from {{url}}",notFound:"Skill '{{name}}' not found",noSkillsAvailable:"No skills available from ClawHub",noSkillsFound:"No skills found",downloadFailed:"Failed to download skill '{{name}}': {{error}}",installed:"Installed skill '{{name}}'",complete:"Installation complete: {{count}} of {{total}} skills installed",alreadyInstalled:"Skill '{{name}}' already installed (use --force to reinstall)",downloading:"Downloading skill '{{name}}' from {{url}}",noSkillsDir:"No skills directory found. Install skills first.",noSkillsInstalled:"No skills installed",installedList:"Installed skills ({{count}} total) in {{dir}}:",notInstalled:"Skill '{{name}}' is not installed",removed:"Removed skill '{{name}}'"},skillConvert:{welcome:"Skill Conversion System - Convert successful skills to permanent tools",listHeader:"Skill Conversion Analysis ({{totalSkills}} skills, {{totalExecutions}} executions)",noSuggestions:"No skills meet the conversion threshold of {{threshold}}.",suggestedConversions:"Suggested Conversions:",convertHint:"Use 'pithosai skill-convert convert <skill-name>' to convert a skill.",skillNotFound:"Skill '{{skillName}}' not found or cannot be read: {{error}}",alreadyConverted:"Skill '{{skillName}}' has already been converted to a tool.",useForceHint:"Use --force to convert again.",conversionReportHeader:"Conversion Report for '{{skillName}}':",conversionScore:"Conversion Score",suggestedType:"Suggested Type",ready:"Ready for Conversion",estimatedBenefits:"Estimated Benefits",performance:"Performance Improvement",reliability:"Reliability Improvement",usability:"Usability Improvement",parameters:"Parameters",notReadyWarning:"This skill is not ready for automatic conversion.",moreUsageHint:"Use the skill more frequently or use --force to convert anyway.",dryRunComplete:"Dry run complete. No changes were made.",confirmConversion:"Convert '{{skillName}}' to a permanent tool?",conversionCancelled:"Conversion cancelled.",converting:"Converting '{{skillName}}' to tool...",conversionSuccess:"Successfully converted '{{skillName}}' to '{{toolName}}'.\nTool saved to: {{toolPath}}",usageExample:"Usage Example:",nextSteps:"Next Steps:",restartAgent:"Restart the agent to load the new tool",testTool:"Test the tool with: <tool-name> --help",manageTools:"Manage tools with: pithosai skill-convert tools",listError:"Error listing skills: {{error}}",conversionError:"Error converting '{{skillName}}': {{error}}",skillStatsHeader:"Statistics for '{{skillName}}':",generalStats:"General Statistics",totalExecutions:"Total Executions",successful:"Successful",failed:"Failed",avgTime:"Average Execution Time",lastUsed:"Last Used",recentExecutions:"Recent Executions",commonParameters:"Common Parameters",overallStatsHeader:"Overall Skill Statistics",overallStats:"Overall Statistics",totalSkillsTracked:"Total Skills Tracked",avgSuccessRate:"Average Success Rate",topSkills:"Top Skills by Usage",conversionSuggestions:"Conversion Suggestions",statsError:"Error getting statistics: {{error}}",confirmClearAll:"Clear ALL skill execution records? This cannot be undone.",allRecordsCleared:"All skill execution records cleared.",skillRecordsCleared:"Skill execution records for '{{skillName}}' cleared.",clearCancelled:"Clear operation cancelled.",specifySkillOrAll:"Please specify a skill name or use --all",clearError:"Error clearing records: {{error}}",noConvertedTools:"No converted tools found.",convertedToolsHeader:"Converted Tools:",originalSkill:"Original Skill",converted:"Converted",usageCount:"Usage Count",toolsError:"Error managing tools: {{error}}",confirmRemoveTool:"Remove tool '{{toolName}}'?",toolRemoved:"Tool '{{toolName}}' removed.",toolRemoveFailed:"Failed to remove tool '{{toolName}}'.",removeCancelled:"Tool removal cancelled.",toolEnabled:"Tool '{{toolName}}' enabled.",toolEnableFailed:"Failed to enable tool '{{toolName}}'.",toolDisabled:"Tool '{{toolName}}' disabled.",toolDisableFailed:"Failed to disable tool '{{toolName}}'.",noStatsForSkill:"No statistics found for skill '{{skillName}}'."},hooks:{description:"Manage agent hooks for debugging, security, and monitoring",list:{description:"List all registered hooks",title:"\uD83D\uDCCB Registered Hooks",total:"Total: {{total}} handlers",options:{verbose:"Show detailed handler information"},error:"Failed to list hooks: {{error}}"},debug:{description:"Enable debug hooks for monitoring agent behavior",options:{data:"Log full data in debug output",performance:"Enable performance monitoring hooks",stats:"Enable statistics collection hooks",all:"Enable all debug hooks"},added:{debug:"Added debug logging hooks",performance:"Added performance monitoring hooks",stats:"Added statistics collection hooks",basic:"Added basic debug hooks"},success:"Debug hooks enabled ({{count}} handlers registered)",error:"Failed to enable debug hooks: {{error}}"},security:{description:"Enable security hooks for access control and monitoring",options:{block:"Comma-separated list of tools to block",maxPrompt:"Maximum allowed prompt length (default: 10000)"},success:"Security hooks enabled",blockedTools:"Blocked tools: {{tools}}",maxPrompt:"Maximum prompt length: {{length}} characters",error:"Failed to enable security hooks: {{error}}"},clear:{description:"Clear all registered hooks",success:"All hooks cleared",error:"Failed to clear hooks: {{error}}"},test:{description:"Test hooks by triggering them with test data",argument:{hookType:"Specific hook type to test (optional)"},invalidType:"Invalid hook type: {{type}}",triggered:"Triggered hook: {{type}}",result:"Result: {{result}}",allTriggered:"All hooks triggered successfully",error:"Failed to test hooks: {{error}}"},register:{description:"Register a custom hook handler from a file",argument:{hookType:"Hook type to register handler for",handlerFile:"Path to handler file (must export default function)"},invalidType:"Invalid hook type: {{type}}",invalidHandler:"Handler file must export a default function",success:"Registered handler for {{type}} from {{file}}",error:"Failed to register hook: {{error}}"},status:{description:"Show current hook configuration and statistics",title:"\uD83D\uDCCB Hook Status",error:"Failed to get hook status: {{error}}"}}}},9556(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Requisito base",projectDir:"Directorio del proyecto (trabajar aqu\xed): {{cwd}}",skillsInstruction:"Usa la herramienta read_skill para cargar las instrucciones completas de una habilidad cuando la tarea coincida con su descripci\xf3n.",toolArgSizeLimit:"No superes nunca {{maxChars}} caracteres en un solo argumento de llamada a herramienta (p. ej. el content de un write). La API puede truncar payloads mayores y provocar errores \xabUnterminated string in JSON\xbb. Para archivos o scripts largos, divide en varias llamadas write (por archivo o por fragmento de menos de {{maxChars}} caracteres).",toolCallJsonFormat:'Los argumentos de llamada a herramienta deben ser JSON v\xe1lido: cada clave y cada valor de cadena entre comillas dobles. Ejemplo para write: {"path": "archivo.md", "content": "contenido aqu\xed"}. No omitas comillas en claves o valores (p. ej. path: archivo.md es inv\xe1lido).'},errors:{missingPromptFiles:"Faltan archivos de prompt requeridos en {{dir}}:",runInit:"Ejecuta 'pithosai init' en la ra\xedz del proyecto para crear .pithosai con plantillas.",noApiKey:"No se encontr\xf3 clave API. Configura DEEPSEEK_API_KEY u OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama no est\xe1 configurado. Configura OPENAI_LOCAL_API_BASE o usa un proyecto con modelo local.",noValidTemplateFiles:"No hay archivos de plantilla v\xe1lidos en {{dir}}. Se espera *-<lang>.md (ej. IDENTITY-ja.md). Ejecuta 'pithosai init' para crear .pithosai con plantillas.",runTimeout:"La ejecuci\xf3n del agente expir\xf3 tras {{seconds}} segundos. Usa --timeout <segundos> o PITHOSAI_TIMEOUT_MS para ajustar.",agentRunFailed:"Error en la ejecuci\xf3n: {{message}}",unknownRunError:"Error desconocido"},warnings:{sessionAppend:"A\xf1adir a sesi\xf3n: {{message}}",apiRetry:"Error de API en intento {{attempt}}/{{max}}; reintentando..."},reasoner:{thinkingHeader:"\n--- Pensamiento:\n",replyHeader:"\n\n--- Respuesta:\n"},run:{cwd:"cwd {{cwd}}",request:"petici\xf3n: {{request}}",interactivePrompt:"T\xfa: ",tuiYouLabel:"T\xfa:",interactiveExitHint:"Responde o escribe una nueva petici\xf3n (escribe 'exit' o 'quit' para salir de la CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Modo interactivo — Agente (herramientas completas) ---",interactiveModeAgentTips:"- Conjunto completo de herramientas (lectura, escritura, ejecuci\xf3n, seg\xfan configuraci\xf3n).\n- Los turnos se guardan por tarea en la base de datos local.\n- `/new` asigna un id de tarea nuevo; no se cargan mensajes anteriores.\n- `/shell <comando>` para shell; `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas.\n- `/list-skill`, `/install-skill` y `/remove-skill` equivalen a `pithosai skills list|install|remove` (ClawHub). Ctrl+S detiene, Ctrl+P pausa.",interactiveModeDialogTitle:"--- Modo interactivo — Di\xe1logo (solo lectura) ---",interactiveModeDialogTips:"- Solo herramientas de solo lectura (sin shell, edici\xf3n de archivos ni ejecuci\xf3n de comandos).\n- Los turnos se guardan por tarea en la base de datos local.\n- `/new` asigna un id de tarea nuevo; no se cargan mensajes anteriores.\n- `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas.\n- `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub) como la CLI `pithosai skills`.",interactiveModePlanTitle:"--- Modo plan ---",interactiveModePlanTips:"- Cada respuesta se escribe en `<slug>-plan.md` en el directorio del proyecto (la primera l\xednea de la petici\xf3n influye en el nombre).\n- Solo herramientas de lectura; shell y herramientas mutadoras desactivadas.\n- `/new` asigna un id de tarea nuevo.\n- `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas.\n- `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub) como la CLI `pithosai skills`.\n- Tras cada ejecuci\xf3n puede seguir con otra petici\xf3n de plan en el prompt (igual que agent/dialog).",list:{noPersistedTasks:"No se encontraron tareas guardadas.",createTasksFirstHint:"Crea tareas primero usando `pithosai task`.",persistedTasksHeader:"--- Tareas guardadas ({{count}}) ---",selectTaskHint:"Usa `/select <index>` para ejecutar una tarea.",noTasksCached:"No hay tareas en cach\xe9. Ejecuta `/list` primero.",invalidIndex:"\xcdndice no v\xe1lido {{index}}. Rango v\xe1lido: 0-{{maxIndex}}.",selectUsage:"Uso: /select <index>",selectedTask:"Tarea #{{index}} seleccionada."},skillSlash:{installUsage:"Uso: /install-skill [--force] [nombre-skill]",removeUsage:"Uso: /remove-skill <nombre-skill>",listNoExtra:"/list-skill no admite argumentos.",failed:"Fall\xf3 el comando de skill: {{message}}"},show:{title:"Tarea actual",field:"Campo",value:"Valor",taskId:"taskId",mode:"modo",model:"modelo",status:"estado",messageCount:"cantidadMensajes",usageInput:"uso.entrada",usageOutput:"uso.salida",usageCacheRead:"uso.cacheLectura",usageCacheWrite:"uso.cacheEscritura",usageTotalTokens:"uso.totalTokens"},showTask:{title:"Preguntas y respuestas de la tarea",taskIdLabel:"ID de tarea",turnHeading:"Turno {{index}}",questionLabel:"Pregunta",answerLabel:"Respuesta",createdLabel:"Creado",emptyQuestion:"(pregunta vac\xeda)",emptyAnswer:"(sin respuesta de texto del asistente)",emptyNoMessages:"A\xfan no hay mensajes de usuario para esta tarea.",previewDocumentTitle:"Preguntas y respuestas de la tarea"},showPrompt:{previewDocumentTitle:"Mensaje del sistema",previewHeading:"Mensaje del sistema"},shellHint:"Use '/shell <comando>' para ejecutar comandos de shell (ejemplo: '/shell ls -la').",replIntroDialog:"Modo di\xe1logo: solo herramientas de lectura — `/shell` desactivado. `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas. `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub).",replIntroPlan:"Modo plan: cada respuesta se guarda en `<slug>-plan.md` (la primera l\xednea influye en el nombre). `/shell` desactivado; salida m\xednima hasta terminar. `/list`, `/select`, `/show`, `/show-task` y `/show-prompt` para tareas persistidas. `/list-skill`, `/install-skill` y `/remove-skill` gestionan skills (ClawHub).",newSessionHint:"Use '/new <petici\xf3n>' para iniciar una nueva sesi\xf3n (sin historial de chat).",newSessionNoHistory:"Usando nueva sesi\xf3n (sin historial de chat).",controlHint:"Presiona Ctrl+S para detener el agente en ejecuci\xf3n, Ctrl+P para pausar y entrar en subcomandos.",replTabCompletionHint:"Tab para completar comandos con barra (p. ej. /list, /list-skill, /show) o exit/quit.",tuiScrollTranscriptHint:"En la UI de terminal: rueda, flechas, Re/Av P\xe1g, Ctrl+U/Ctrl+F (p\xe1gina). Ctrl+U/F desplazan el historial. Ctrl+D sigue siendo EOF/salir con l\xednea vac\xeda o borrar adelante al escribir.",agentStopped:"Agente detenido.",pauseHeader:"--- Agente en pausa ---",pauseCurrentRequest:"Solicitud actual: {{request}}",pauseHelp:"Comandos: 'continue' o 'c' para continuar, 'exit' o 'e' para salir, o escribe una nueva solicitud para reemplazar la actual.",pausePrompt:"[en pausa] ",pauseRequestUpdated:"Solicitud actualizada a: {{request}}"},shell:{noCommand:"No se proporcion\xf3 ning\xfan comando despu\xe9s del prefijo /shell. Uso: /shell <comando>",executionError:"Error al ejecutar el comando de shell: {{error}}",executing:"[shell] Ejecutando: {{command}}",errorNoCommand:"No se proporcion\xf3 ning\xfan comando despu\xe9s del prefijo /shell.",errorSpawnFailed:"Error al iniciar el proceso: {{message}}",errorTimedOut:"El comando expir\xf3 tras {{seconds}} segundos",logFailed:"Comando shell fallido: {{command}} (c\xf3digo de salida: {{code}})",logExecutionError:"Error de ejecuci\xf3n del comando shell: {{message}}",resultCommand:"Comando: {{command}}",resultExitCode:"C\xf3digo de salida: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"\xc9xito:",resultSuccessYes:"S\xed",resultSuccessNo:"No",resultOutput:"Salida:",resultError:"Error:"},init:{invalidType:'--type inv\xe1lido "{{value}}"; elige: {{choices}}',invalidLang:'--lang inv\xe1lido "{{value}}"; elige: {{choices}}',templatesDirNotFound:"Directorio de plantillas no encontrado: {{dir}}",createdPromptTemplates:"creado {{dir}} (plantillas de prompt)",createdSessions:"creado {{dir}} (historial de sesiones)",initialized:"proyecto {{type}} inicializado en {{targetDir}}",promptFilesIn:"archivos de prompt en {{pithosaiDir}}, datos de sesi\xf3n en {{sessionsDir}}",runHint:'ejecuta "pithosai -C {{targetDir}} \\"tu petici\xf3n\\"" para empezar.',createdFile:"creado {{path}}",roleAlreadyAdded:"el rol {{role}} ya est\xe1 en .pithosai; omitiendo.",addedRoleTemplates:"plantillas de rol a\xf1adidas a {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: vista previa cerrada ({{source}})",skipped:"Vista previa del navegador omitida (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Indica exactamente markdown o path (no ambos ni ninguno).",errorEmpty:"El contenido Markdown est\xe1 vac\xedo.",errorFileOutside:"path debe estar dentro del directorio del proyecto.",errorNotAFile:"path no es un archivo regular.",errorFileTooLarge:"El archivo supera {{maxBytes}} bytes.",errorFileRead:"No se pudo leer el archivo: {{message}}",sourceInline:"Markdown en l\xednea",sourceFile:"archivo {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"El correo no puede estar vac\xedo para el heartbeat. Configure el correo del rol {{role}} en la tabla email_roles en la base de datos sqlite3.",loadedState:"Estado del heartbeat cargado desde SQLite para correo {{email}} y rol {{role}}, estados: {{states}}",fetchFound:"El heartbeat encontr\xf3 {{count}} tareas nuevas en la bandeja: {{ids}}",savedState:"Estado del heartbeat guardado en SQLite para correo {{email}} y rol {{role}}",mergedAndNext:"Se fusionaron {{merged}} tareas en el estado, siguiente a procesar: {{stateSummary}}",replyEmailFailed:"Fall\xf3 el env\xedo del correo de respuesta del heartbeat: {{error}}",taskFailed:"Fall\xf3 la tarea del heartbeat: {{error}}",failureReplyEmailFailed:"Fall\xf3 el env\xedo del correo de notificaci\xf3n de fallo del heartbeat: {{error}}"},cli:{description:"Pithosai: implementa c\xf3digo o proyectos a partir de una petici\xf3n en lenguaje natural. Los prompts de rol se cargan desde la base de datos SQLite en tiempo de ejecuci\xf3n (con fallback opcional a .pithosai/<role>/*.md). Cree un proyecto con 'pithosai init'.",versionOption:"mostrar versi\xf3n",roleOption:"rol (conjunto de plantillas para init); plantillas en templates/<role>/",langOption:"idioma para prompts y plantillas init: en, zh (por defecto: en)",interactiveModeOption:"entrar en modo interactivo sin petici\xf3n; mostrar consejos del modo y pedir entrada",initDescription:"Crear un proyecto nuevo y la estructura de directorio .pithosai/. Los prompts de rol se cargan desde la base de datos SQLite en tiempo de ejecuci\xf3n (con fallback opcional a .pithosai/<role>/*.md).",initTypeOption:"tipo de proyecto: js, ts o python",initExamples:"\nEjemplos:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"A\xf1adir plantillas de rol a .pithosai/<role>/ en el proyecto",addRoleArgument:"rol a a\xf1adir (ej. PM, QA)",requestArgument:'qu\xe9 construir (ej. "Un CLI que convierte CSV a JSON"). Si se omite, mostrar ayuda.',cwdOption:"directorio del proyecto (por defecto: directorio actual)",skillsDirOption:"directorio de habilidades para read_skill (por defecto: ./.pithosai/skills o PITHOSAI_SKILLS_DIR)",reasonerOption:"usar modelo DeepSeek Reasoner (pensamiento); por defecto DeepSeek Coder",chatOption:"usar modelo DeepSeek Chat (chat general, no c\xf3digo); por defecto DeepSeek Coder",cursorOption:"usar modelo Cursor CLI (autenticaci\xf3n v\xeda cursor-agent login, sin clave API). Opcionalmente especificar modelo: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"tiempo m\xe1ximo de ejecuci\xf3n del agente en segundos (por defecto: 1800). Anular con PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"desactivar el mensaje interactivo (por defecto: tras cada respuesta, pedir la siguiente)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Generando el plan…",waitingReply:"Esperando respuesta…",runningReply:"Ejecutando…",resultPreviewOpening:"Abriendo vista previa del resultado en el navegador…",resultPreviewTitle:"Resultado de Pithosai",resultPreviewFailed:"No se pudo abrir la vista previa: {{message}}",resultPreviewCopy:"Copiar Markdown",resultPreviewClose:"Cerrar",resultPreviewCopied:"Copiado al portapapeles",resultPreviewTerminalHint:"↑↓ o j/k \xb7 PgUp/PgDn o Ctrl+U/Ctrl+D \xb7 Home/End o gg/G \xb7 q/Esc cerrar",runExamples:'\nEjemplos:\n pithosai "A\xf1ade un endpoint REST que devuelva la hora actual"\n pithosai -C ./my-app "Ejecutar tests y corregir fallos"\n pithosai -i # modo interactivo: cargar \xfaltima sesi\xf3n y pedir peticiones\n pithosai --no-interactive "Una vez" # una respuesta, sin pedir siguiente\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Uso:",helpArguments:"Argumentos:",helpOptions:"Opciones:",helpCommands:"Comandos:",helpGlobalOptions:"Opciones globales:",helpOption:"mostrar ayuda del comando",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Observa el archivo de tareas y proc\xe9salas de una en una en el mismo proceso",taskFileOption:"Ruta al Markdown de tareas (predeterminado: prompts.md en la ra\xedz del proyecto)",taskModelOption:"Clave de modelo para la tarea (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Empezar con una sesi\xf3n nueva (sin historial de chat)",taskExamples:"\nEjemplos:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Tarea no encontrada: {{taskId}}",taskAgentCompleted:"Agente completado.",taskAgentRunFailed:"Fall\xf3 la ejecuci\xf3n del agente.",taskDone:"Hecho",taskFailed:"Tarea fallida: {{message}}",taskProcessingHeader:"--- Procesando tarea ---",taskLabelId:"id:",taskLabelTitle:"t\xedtulo:",taskLabelStatus:"estado:",taskLabelDescription:"descripci\xf3n:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Iniciando procesador para la tarea en proceso {{id}} ({{title}}).",taskNoPending:"No hay tareas pendientes.",taskPickedTask:"Tarea {{id}} ({{title}}) elegida; iniciando procesador.",taskProcessorFailed:"Fall\xf3 el procesador de tareas: {{message}}",taskWatcherRunning:"Vigilancia de tareas en ejecuci\xf3n. Ctrl+C para detener.",memorizeDescription:"Escribe .pithosai/<role>/memory.md con res\xfamenes de las tareas en las que particip\xf3 el rol (mensajes de tarea persistidos en el rango de fechas).",memorizeStartOption:"Inicio del rango: YYYY-MM-DD o fecha-hora ISO",memorizeEndOption:"Fin del rango: YYYY-MM-DD o fecha-hora ISO",memorizeRoleRequired:"El rol es obligatorio (-r/--role o --role global).",memorizeWrote:"Escrito {{path}} ({{count}} tarea(s)).",memorizeNoTasks:"Sin tareas en el rango para el rol {{role}}; solo cabecera en {{path}}.",memorizeDateError:"Rango de fechas no v\xe1lido: {{message}}",memorizeNoLlmOption:"Omitir resumen con LLM; escribir solo memoria estructurada (igual que PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"Fall\xf3 el resumen con LLM ({{message}}); se escribi\xf3 memoria estructurada sin resumen.",memorizeExamples:"\nEjemplos:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Obtener comandos shell para una petici\xf3n (solo Ollama)",argument:"Qu\xe9 quieres hacer (ej. listar archivos grandes en el directorio actual)",loading:"Obteniendo comandos...",examples:'\nEjemplos:\n $ pithosai shell-tips listar archivos json en el directorio actual\n $ pithosai shell-tips "buscar y reemplazar foo por bar en todos los .js"'},writer:{description:"Generar texto para una petici\xf3n (Ollama qwen2.5:14b)",argument:"Qu\xe9 escribir (ej. email corto para declinar una reuni\xf3n)",loading:"Escribiendo...",examples:'\nEjemplos:\n $ pithosai writer email corto para declinar una reuni\xf3n\n $ pithosai writer "tres puntos para un kickoff de proyecto"'},skills:{installing:"Instalando habilidades en {{dir}}",fetchingList:"Obteniendo habilidades disponibles de ClawHub...",fetchingIndex:"Obteniendo \xedndice de habilidades desde {{url}}",notFound:"Habilidad '{{name}}' no encontrada",noSkillsAvailable:"No hay habilidades disponibles de ClawHub",noSkillsFound:"No se encontraron habilidades",downloadFailed:"Error al descargar la habilidad '{{name}}': {{error}}",installed:"Habilidad '{{name}}' instalada",complete:"Instalaci\xf3n completada: {{count}} de {{total}} habilidades instaladas",alreadyInstalled:"Habilidad '{{name}}' ya instalada (usa --force para reinstalar)",downloading:"Descargando habilidad '{{name}}' desde {{url}}",noSkillsDir:"No se encontr\xf3 el directorio de habilidades. Instala habilidades primero.",noSkillsInstalled:"No hay habilidades instaladas",installedList:"Habilidades instaladas ({{count}} total) en {{dir}}:",notInstalled:"Habilidad '{{name}}' no est\xe1 instalada",removed:"Habilidad '{{name}}' eliminada"},skillConvert:{welcome:"Sistema de conversi\xf3n de habilidades - Convertir habilidades exitosas en herramientas permanentes",listHeader:"An\xe1lisis de conversi\xf3n de habilidades ({{totalSkills}} habilidades, {{totalExecutions}} ejecuciones)",noSuggestions:"Ninguna habilidad alcanza el umbral de conversi\xf3n de {{threshold}}.",suggestedConversions:"Conversiones sugeridas:",convertHint:"Usa 'pithosai skill-convert convert <nombre-habilidad>' para convertir una habilidad.",skillNotFound:"Habilidad '{{skillName}}' no encontrada o no se puede leer: {{error}}",alreadyConverted:"La habilidad '{{skillName}}' ya ha sido convertida en herramienta.",useForceHint:"Usa --force para convertir de nuevo.",conversionReportHeader:"Informe de conversi\xf3n de '{{skillName}}':",conversionScore:"Puntuaci\xf3n de conversi\xf3n",suggestedType:"Tipo sugerido",ready:"Listo para conversi\xf3n",estimatedBenefits:"Beneficios estimados",performance:"Mejora de rendimiento",reliability:"Mejora de fiabilidad",usability:"Mejora de usabilidad",parameters:"Par\xe1metros",notReadyWarning:"Esta habilidad no est\xe1 lista para la conversi\xf3n autom\xe1tica.",moreUsageHint:"Usa la habilidad con m\xe1s frecuencia o usa --force para forzar la conversi\xf3n.",dryRunComplete:"Simulaci\xf3n completada. No se realizaron cambios.",confirmConversion:"\xbfConvertir '{{skillName}}' en herramienta permanente?",conversionCancelled:"Conversi\xf3n cancelada.",converting:"Convirtiendo '{{skillName}}' en herramienta...",conversionSuccess:"'{{skillName}}' convertido exitosamente en '{{toolName}}'.\nHerramienta guardada en: {{toolPath}}",usageExample:"Ejemplo de uso:",nextSteps:"Pr\xf3ximos pasos:",restartAgent:"Reinicia el agente para cargar la nueva herramienta",testTool:"Probar herramienta: <nombre-herramienta> --help",manageTools:"Gestionar herramientas: pithosai skill-convert tools",listError:"Error al listar habilidades: {{error}}",conversionError:"Error al convertir '{{skillName}}': {{error}}",skillStatsHeader:"Estad\xedsticas de '{{skillName}}':",generalStats:"Estad\xedsticas generales",totalExecutions:"Ejecuciones totales",successful:"Exitosas",failed:"Fallidas",avgTime:"Tiempo promedio de ejecuci\xf3n",lastUsed:"\xdaltimo uso",recentExecutions:"Ejecuciones recientes",commonParameters:"Par\xe1metros comunes",overallStatsHeader:"Estad\xedsticas generales de habilidades",overallStats:"Estad\xedsticas generales",totalSkillsTracked:"Total de habilidades rastreadas",avgSuccessRate:"Tasa de \xe9xito promedio",topSkills:"Habilidades m\xe1s usadas",conversionSuggestions:"Sugerencias de conversi\xf3n",statsError:"Error al obtener estad\xedsticas: {{error}}",confirmClearAll:"\xbfBorrar TODOS los registros de ejecuci\xf3n de habilidades? Esta acci\xf3n no se puede deshacer.",allRecordsCleared:"Todos los registros de ejecuci\xf3n de habilidades han sido borrados.",skillRecordsCleared:"Los registros de ejecuci\xf3n de '{{skillName}}' han sido borrados.",clearCancelled:"Operaci\xf3n de borrado cancelada.",specifySkillOrAll:"Especifica un nombre de habilidad o usa --all",clearError:"Error al borrar registros: {{error}}",noConvertedTools:"No se encontraron herramientas convertidas.",convertedToolsHeader:"Herramientas convertidas:",originalSkill:"Habilidad original",converted:"Convertido el",usageCount:"N\xfamero de usos",toolsError:"Error al gestionar herramientas: {{error}}",confirmRemoveTool:"\xbfEliminar herramienta '{{toolName}}'?",toolRemoved:"Herramienta '{{toolName}}' eliminada.",toolRemoveFailed:"Fallo al eliminar herramienta '{{toolName}}'.",removeCancelled:"Eliminaci\xf3n de herramienta cancelada.",toolEnabled:"Herramienta '{{toolName}}' habilitada.",toolEnableFailed:"Fallo al habilitar herramienta '{{toolName}}'.",toolDisabled:"Herramienta '{{toolName}}' deshabilitada.",toolDisableFailed:"Fallo al deshabilitar herramienta '{{toolName}}'.",noStatsForSkill:"No se encontraron estad\xedsticas para la habilidad '{{skillName}}'."},hooks:{description:"Gestionar hooks del agente para depuraci\xf3n, seguridad y monitoreo",list:{description:"Listar todos los hooks registrados",title:"\uD83D\uDCCB Hooks registrados",total:"Total: {{total}} manejadores",options:{verbose:"Mostrar informaci\xf3n detallada de los manejadores"},error:"Error al listar hooks: {{error}}"},debug:{description:"Habilitar hooks de depuraci\xf3n para monitorear el comportamiento del agente",options:{data:"Registrar datos completos en la salida de depuraci\xf3n",performance:"Habilitar hooks de monitoreo de rendimiento",stats:"Habilitar hooks de recopilaci\xf3n de estad\xedsticas",all:"Habilitar todos los hooks de depuraci\xf3n"},added:{debug:"Hooks de registro de depuraci\xf3n a\xf1adidos",performance:"Hooks de monitoreo de rendimiento a\xf1adidos",stats:"Hooks de recopilaci\xf3n de estad\xedsticas a\xf1adidos",basic:"Hooks de depuraci\xf3n b\xe1sicos a\xf1adidos"},success:"Hooks de depuraci\xf3n habilitados ({{count}} manejadores registrados)",error:"Error al habilitar hooks de depuraci\xf3n: {{error}}"},security:{description:"Habilitar hooks de seguridad para control de acceso y monitoreo",options:{block:"Lista de herramientas a bloquear separadas por comas",maxPrompt:"Longitud m\xe1xima permitida del prompt (por defecto: 10000)"},success:"Hooks de seguridad habilitados",blockedTools:"Herramientas bloqueadas: {{tools}}",maxPrompt:"Longitud m\xe1xima del prompt: {{length}} caracteres",error:"Error al habilitar hooks de seguridad: {{error}}"},clear:{description:"Eliminar todos los hooks registrados",success:"Todos los hooks eliminados",error:"Error al eliminar hooks: {{error}}"},test:{description:"Probar hooks dispar\xe1ndolos con datos de prueba",argument:{hookType:"Tipo de hook espec\xedfico a probar (opcional)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",triggered:"Hook disparado: {{type}}",result:"Resultado: {{result}}",allTriggered:"Todos los hooks disparados exitosamente",error:"Error al probar hooks: {{error}}"},register:{description:"Registrar un manejador de hook personalizado desde un archivo",argument:{hookType:"Tipo de hook para registrar el manejador",handlerFile:"Ruta al archivo del manejador (debe exportar una funci\xf3n por defecto)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",invalidHandler:"El archivo del manejador debe exportar una funci\xf3n por defecto",success:"Manejador para {{type}} registrado desde {{file}}",error:"Error al registrar hook: {{error}}"},status:{description:"Mostrar la configuraci\xf3n actual de hooks y estad\xedsticas",title:"\uD83D\uDCCB Estado de hooks",error:"Error al obtener el estado de hooks: {{error}}"}}}},1984(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Exigence de base",projectDir:"R\xe9pertoire du projet (travailler ici) : {{cwd}}",skillsInstruction:"Utilise l'outil read_skill pour charger les instructions compl\xe8tes d'une comp\xe9tence lorsque la t\xe2che correspond \xe0 sa description.",toolArgSizeLimit:"Ne d\xe9passez jamais {{maxChars}} caract\xe8res pour un seul argument d'appel d'outil (ex. le content d'un write). L'API peut tronquer au-del\xe0 et provoquer des erreurs \xab Unterminated string in JSON \xbb. Pour les longs fichiers ou scripts, divisez en plusieurs appels write (par fichier ou par bloc de moins de {{maxChars}} caract\xe8res).",toolCallJsonFormat:'Les arguments d\'appel d\'outil doivent \xeatre du JSON valide : chaque cl\xe9 et chaque valeur cha\xeene entre guillemets doubles. Exemple pour write : {"path": "fichier.md", "content": "contenu ici"}. N\'omettez pas les guillemets pour les cl\xe9s ou valeurs (ex. path: fichier.md est invalide).'},errors:{missingPromptFiles:"fichiers de prompt requis manquants dans {{dir}} :",runInit:"Ex\xe9cutez 'pithosai init' \xe0 la racine du projet pour cr\xe9er .pithosai avec les mod\xe8les.",noApiKey:"Cl\xe9 API introuvable. D\xe9finissez DEEPSEEK_API_KEY ou OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama n'est pas configur\xe9. D\xe9finissez OPENAI_LOCAL_API_BASE ou utilisez un projet avec mod\xe8le local.",noValidTemplateFiles:"aucun fichier de mod\xe8le valide dans {{dir}}. Attendu *-<lang>.md (ex. IDENTITY-ja.md). Ex\xe9cutez 'pithosai init' pour cr\xe9er .pithosai avec les mod\xe8les.",runTimeout:"Ex\xe9cution de l'agent expir\xe9e apr\xe8s {{seconds}} secondes. Utilisez --timeout <secondes> ou PITHOSAI_TIMEOUT_MS pour ajuster.",agentRunFailed:"\xc9chec de l'ex\xe9cution : {{message}}",unknownRunError:"Erreur inconnue"},warnings:{sessionAppend:"ajout de session : {{message}}",apiRetry:"Erreur API \xe0 la tentative {{attempt}}/{{max}} ; nouvel essai..."},reasoner:{thinkingHeader:"\n--- R\xe9flexion:\n",replyHeader:"\n\n--- R\xe9ponse:\n"},run:{cwd:"cwd {{cwd}}",request:"demande : {{request}}",interactivePrompt:"Vous : ",tuiYouLabel:"Vous :",interactiveExitHint:"R\xe9pondez ou saisissez une nouvelle demande (tapez 'exit' ou 'quit' pour quitter la CLI).",interactiveModeCwd:"CWD : {{cwd}}",interactiveModeAgentTitle:"--- Mode interactif — Agent (outils complets) ---",interactiveModeAgentTips:"- Jeu d’outils complet (lecture, \xe9criture, ex\xe9cution, selon la configuration).\n- Les tours sont stock\xe9s par t\xe2che dans la base locale.\n- `/new` attribue un nouvel id de t\xe2che ; les messages pr\xe9c\xe9dents ne sont pas charg\xe9s.\n- `/shell <commande>` pour le shell ; `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es.\n- `/list-skill`, `/install-skill` et `/remove-skill` \xe9quivalent \xe0 `pithosai skills list|install|remove` (ClawHub). Ctrl+S arr\xeate, Ctrl+P met en pause.",interactiveModeDialogTitle:"--- Mode interactif — Dialogue (Q&R en lecture seule) ---",interactiveModeDialogTips:"- R\xe9ponses avec outils en lecture seule uniquement (pas de shell, d’\xe9dition de fichiers ni d’ex\xe9cution de commandes).\n- Les tours sont stock\xe9s par t\xe2che dans la base locale.\n- `/new` attribue un nouvel id de t\xe2che ; les messages pr\xe9c\xe9dents ne sont pas charg\xe9s.\n- `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es.\n- `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub), comme la CLI `pithosai skills`.",interactiveModePlanTitle:"--- Mode plan ---",interactiveModePlanTips:"- Chaque r\xe9ponse est \xe9crite dans `<slug>-plan.md` \xe0 la racine du projet (la premi\xe8re ligne de la requ\xeate influence le nom).\n- Outils en lecture seule uniquement ; shell et outils modificateurs d\xe9sactiv\xe9s.\n- `/new` attribue un nouvel id de t\xe2che.\n- `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es.\n- `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub), comme la CLI `pithosai skills`.\n- Apr\xe8s chaque ex\xe9cution, vous pouvez saisir une nouvelle demande de plan au prompt (comme agent/dialog).",list:{noPersistedTasks:"Aucune t\xe2che enregistr\xe9e trouv\xe9e.",createTasksFirstHint:"Cr\xe9ez d'abord des t\xe2ches avec `pithosai task`.",persistedTasksHeader:"--- T\xe2ches enregistr\xe9es ({{count}}) ---",selectTaskHint:"Utilisez `/select <index>` pour ex\xe9cuter une t\xe2che.",noTasksCached:"Aucune t\xe2che en cache. Ex\xe9cutez `/list` d'abord.",invalidIndex:"Index invalide {{index}}. Plage valide : 0-{{maxIndex}}.",selectUsage:"Utilisation : /select <index>",selectedTask:"T\xe2che n\xb0{{index}} s\xe9lectionn\xe9e."},skillSlash:{installUsage:"Utilisation : /install-skill [--force] [nom-du-skill]",removeUsage:"Utilisation : /remove-skill <nom-du-skill>",listNoExtra:"/list-skill n’accepte pas d’arguments.",failed:"Commande skill en \xe9chec : {{message}}"},show:{title:"T\xe2che actuelle",field:"Champ",value:"Valeur",taskId:"taskId",mode:"mode",model:"mod\xe8le",status:"statut",messageCount:"nombreMessages",usageInput:"usage.entr\xe9e",usageOutput:"usage.sortie",usageCacheRead:"usage.cacheLecture",usageCacheWrite:"usage.cache\xc9criture",usageTotalTokens:"usage.totalTokens"},showTask:{title:"Q&R de la t\xe2che",taskIdLabel:"ID de t\xe2che",turnHeading:"Tour {{index}}",questionLabel:"Question",answerLabel:"R\xe9ponse",createdLabel:"Cr\xe9\xe9",emptyQuestion:"(question vide)",emptyAnswer:"(pas encore de r\xe9ponse texte de l’assistant)",emptyNoMessages:"Aucun message utilisateur pour cette t\xe2che pour l’instant.",previewDocumentTitle:"Q&R de la t\xe2che"},showPrompt:{previewDocumentTitle:"Invite syst\xe8me",previewHeading:"Invite syst\xe8me"},shellHint:"Utilisez '/shell <commande>' pour ex\xe9cuter des commandes shell (exemple: '/shell ls -la').",replIntroDialog:"Mode dialogue : outils en lecture seule uniquement — `/shell` est d\xe9sactiv\xe9. `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es. `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub).",replIntroPlan:"Mode plan : chaque r\xe9ponse est enregistr\xe9e dans `<slug>-plan.md` (la premi\xe8re ligne influence le nom). `/shell` est d\xe9sactiv\xe9 ; sortie minimale jusqu’\xe0 la fin. `/list`, `/select`, `/show`, `/show-task` et `/show-prompt` pour les t\xe2ches persist\xe9es. `/list-skill`, `/install-skill` et `/remove-skill` g\xe8rent les skills (ClawHub).",newSessionHint:"Utilisez '/new <requ\xeate>' pour d\xe9marrer une nouvelle session (sans historique de chat).",newSessionNoHistory:"Utilisation d'une nouvelle session (sans historique de chat).",controlHint:"Appuyez sur Ctrl+S pour arr\xeater l'agent en cours, Ctrl+P pour mettre en pause et entrer des sous-commandes.",replTabCompletionHint:"Tab pour compl\xe9ter les commandes slash (ex. /list, /list-skill, /show) ou exit/quit.",tuiScrollTranscriptHint:"Dans l’interface terminal : molette, fl\xe8ches, Page pr\xe9c./suiv., Ctrl+U/Ctrl+F (page). Ctrl+U/F font d\xe9filer le journal. Ctrl+D reste EOF / quitter si ligne vide, suppression avant si saisie.",agentStopped:"Agent arr\xeat\xe9.",pauseHeader:"--- Agent en pause ---",pauseCurrentRequest:"Requ\xeate actuelle : {{request}}",pauseHelp:"Commandes : 'continue' ou 'c' pour reprendre, 'exit' ou 'e' pour quitter, ou tapez une nouvelle requ\xeate pour remplacer la requ\xeate actuelle.",pausePrompt:"[en pause] ",pauseRequestUpdated:"Requ\xeate mise \xe0 jour : {{request}}"},shell:{noCommand:"Aucune commande fournie apr\xe8s le pr\xe9fixe /shell. Utilisation: /shell <commande>",executionError:"Erreur lors de l'ex\xe9cution de la commande shell: {{error}}",executing:"[shell] Ex\xe9cution : {{command}}",errorNoCommand:"Aucune commande fournie apr\xe8s le pr\xe9fixe /shell.",errorSpawnFailed:"\xc9chec du d\xe9marrage du processus : {{message}}",errorTimedOut:"Commande expir\xe9e apr\xe8s {{seconds}} secondes",logFailed:"\xc9chec de la commande shell : {{command}} (code de sortie : {{code}})",logExecutionError:"Erreur d'ex\xe9cution de la commande shell : {{message}}",resultCommand:"Commande : {{command}}",resultExitCode:"Code de sortie : {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Succ\xe8s :",resultSuccessYes:"Oui",resultSuccessNo:"Non",resultOutput:"Sortie :",resultError:"Erreur :"},init:{invalidType:'--type invalide "{{value}}" ; choisir : {{choices}}',invalidLang:'--lang invalide "{{value}}" ; choisir : {{choices}}',templatesDirNotFound:"r\xe9pertoire des mod\xe8les introuvable : {{dir}}",createdPromptTemplates:"cr\xe9\xe9 {{dir}} (mod\xe8les de prompt)",createdSessions:"cr\xe9\xe9 {{dir}} (historique des sessions)",initialized:"projet {{type}} initialis\xe9 dans {{targetDir}}",promptFilesIn:"fichiers de prompt dans {{pithosaiDir}}, donn\xe9es de session dans {{sessionsDir}}",runHint:'ex\xe9cutez "pithosai -C {{targetDir}} \\"votre demande\\"" pour d\xe9marrer.',createdFile:"cr\xe9\xe9 {{path}}",roleAlreadyAdded:"r\xf4le {{role}} d\xe9j\xe0 pr\xe9sent dans .pithosai ; ignor\xe9.",addedRoleTemplates:"mod\xe8les de r\xf4le ajout\xe9s \xe0 {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown : aper\xe7u ferm\xe9 ({{source}})",skipped:"Aper\xe7u navigateur ignor\xe9 (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Indiquez exactement markdown ou path (pas les deux, pas aucun).",errorEmpty:"Le contenu Markdown est vide.",errorFileOutside:"path doit rester dans le r\xe9pertoire du projet.",errorNotAFile:"path n’est pas un fichier ordinaire.",errorFileTooLarge:"Le fichier d\xe9passe {{maxBytes}} octets.",errorFileRead:"Impossible de lire le fichier : {{message}}",sourceInline:"Markdown inline",sourceFile:"fichier {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"L'adresse e-mail ne doit pas \xeatre vide pour le heartbeat. Configurez l'e-mail du r\xf4le {{role}} dans la table email_roles de la base de donn\xe9es sqlite3.",loadedState:"\xc9tat du heartbeat charg\xe9 depuis SQLite pour l'e-mail {{email}} et le r\xf4le {{role}}, \xe9tats : {{states}}",fetchFound:"Le heartbeat a trouv\xe9 {{count}} nouvelles t\xe2ches dans la bo\xeete de r\xe9ception : {{ids}}",savedState:"\xc9tat du heartbeat enregistr\xe9 dans SQLite pour l'e-mail {{email}} et le r\xf4le {{role}}",mergedAndNext:"{{merged}} t\xe2ches fusionn\xe9es dans l'\xe9tat, prochaine \xe0 traiter : {{stateSummary}}",replyEmailFailed:"\xc9chec de l'envoi de l'e-mail de r\xe9ponse du heartbeat : {{error}}",taskFailed:"\xc9chec de la t\xe2che du heartbeat : {{error}}",failureReplyEmailFailed:"\xc9chec de l'envoi de l'e-mail de notification d'\xe9chec du heartbeat : {{error}}"},cli:{description:"Pithosai : impl\xe9mente du code ou des projets \xe0 partir d'une demande en langage naturel. Les invites de r\xf4le sont charg\xe9es depuis la base de donn\xe9es SQLite au moment de l'ex\xe9cution (avec repli optionnel vers .pithosai/<role>/*.md). Cr\xe9ez un projet avec 'pithosai init'.",versionOption:"afficher la version",roleOption:"r\xf4le (jeu de mod\xe8les pour init) ; mod\xe8les dans templates/<role>/",langOption:"langue des prompts et mod\xe8les init : en, zh (par d\xe9faut : en)",interactiveModeOption:"entrer en mode interactif sans demande ; afficher les conseils du mode et demander une saisie",initDescription:"Cr\xe9er un nouveau projet et la structure de r\xe9pertoire .pithosai/. Les invites de r\xf4le sont charg\xe9es depuis la base de donn\xe9es SQLite au moment de l'ex\xe9cution (avec repli optionnel vers .pithosai/<role>/*.md).",initTypeOption:"type de projet : js, ts ou python",initExamples:"\nExemples :\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Ajouter les mod\xe8les de r\xf4le \xe0 .pithosai/<role>/ dans le projet",addRoleArgument:"r\xf4le \xe0 ajouter (ex. PM, QA)",requestArgument:'quoi construire (ex. "Un CLI qui convertit CSV en JSON"). Si omis, afficher l\'aide.',cwdOption:"r\xe9pertoire du projet (par d\xe9faut : r\xe9pertoire courant)",skillsDirOption:"r\xe9pertoire des comp\xe9tences pour read_skill (par d\xe9faut : ./.pithosai/skills ou PITHOSAI_SKILLS_DIR)",reasonerOption:"utiliser le mod\xe8le DeepSeek Reasoner (r\xe9flexion) ; par d\xe9faut DeepSeek Coder",chatOption:"utiliser le mod\xe8le DeepSeek Chat (chat g\xe9n\xe9ral, pas de code) ; par d\xe9faut DeepSeek Coder",cursorOption:"utiliser le mod\xe8le Cursor CLI (auth via cursor-agent login, pas de cl\xe9 API n\xe9cessaire). Sp\xe9cifier optionnellement le mod\xe8le : auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"dur\xe9e max d'ex\xe9cution de l'agent en secondes (par d\xe9faut : 1800). Remplacer avec PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"d\xe9sactiver l'invite interactive (par d\xe9faut : apr\xe8s chaque r\xe9ponse, demander la suivante)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"G\xe9n\xe9ration du plan…",waitingReply:"En attente de r\xe9ponse…",runningReply:"En cours…",resultPreviewOpening:"Ouverture de l'aper\xe7u dans le navigateur…",resultPreviewTitle:"R\xe9sultat Pithosai",resultPreviewFailed:"Impossible d'ouvrir l'aper\xe7u : {{message}}",resultPreviewCopy:"Copier le Markdown",resultPreviewClose:"Fermer",resultPreviewCopied:"Copi\xe9 dans le presse-papiers",resultPreviewTerminalHint:"↑↓ ou j/k \xb7 PgUp/PgDn ou Ctrl+U/Ctrl+D \xb7 Home/End ou gg/G \xb7 q/\xc9chap fermer",runExamples:'\nExemples :\n pithosai "Ajouter un endpoint REST qui renvoie l\'heure actuelle"\n pithosai -C ./my-app "Ex\xe9cuter les tests et corriger les \xe9checs"\n pithosai -i # mode interactif : charger la derni\xe8re session puis demander des requ\xeates\n pithosai --no-interactive "Une fois" # une r\xe9ponse, sans demande de suite\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Utilisation :",helpArguments:"Arguments :",helpOptions:"Options :",helpCommands:"Commandes :",helpGlobalOptions:"Options globales :",helpOption:"afficher l'aide de la commande",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Surveiller le fichier de t\xe2ches et les traiter une par une dans le m\xeame processus",taskFileOption:"Chemin du fichier Markdown des t\xe2ches (d\xe9faut : prompts.md \xe0 la racine du projet)",taskModelOption:"Cl\xe9 de mod\xe8le pour la t\xe2che (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"D\xe9marrer avec une nouvelle session (pas d’historique de chat)",taskExamples:"\nExemples :\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"T\xe2che introuvable : {{taskId}}",taskAgentCompleted:"Agent termin\xe9.",taskAgentRunFailed:"\xc9chec de l’ex\xe9cution de l’agent.",taskDone:"Termin\xe9",taskFailed:"\xc9chec de la t\xe2che : {{message}}",taskProcessingHeader:"--- Traitement de la t\xe2che ---",taskLabelId:"id :",taskLabelTitle:"titre :",taskLabelStatus:"statut :",taskLabelDescription:"description :",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"D\xe9marrage du processeur pour la t\xe2che en cours {{id}} ({{title}}).",taskNoPending:"Aucune t\xe2che en attente.",taskPickedTask:"T\xe2che {{id}} ({{title}}) s\xe9lectionn\xe9e ; d\xe9marrage du processeur.",taskProcessorFailed:"\xc9chec du processeur de t\xe2ches : {{message}}",taskWatcherRunning:"Surveillance des t\xe2ches active. Ctrl+C pour arr\xeater.",memorizeDescription:"\xc9crit .pithosai/<role>/memory.md avec des r\xe9sum\xe9s des t\xe2ches auxquelles le r\xf4le a particip\xe9 (messages de t\xe2ches persist\xe9s sur la p\xe9riode).",memorizeStartOption:"D\xe9but de p\xe9riode : YYYY-MM-DD ou date-heure ISO",memorizeEndOption:"Fin de p\xe9riode : YYYY-MM-DD ou date-heure ISO",memorizeRoleRequired:"Le r\xf4le est obligatoire (-r/--role ou --role global).",memorizeWrote:"\xc9crit {{path}} ({{count}} t\xe2che(s)).",memorizeNoTasks:"Aucune t\xe2che sur la p\xe9riode pour le r\xf4le {{role}} ; en-t\xeate \xe9crit dans {{path}}.",memorizeDateError:"Plage de dates invalide : {{message}}",memorizeNoLlmOption:"Ignorer le r\xe9sum\xe9 LLM ; \xe9crire uniquement la m\xe9moire structur\xe9e (comme PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"\xc9chec du r\xe9sum\xe9 LLM ({{message}}) ; m\xe9moire structur\xe9e \xe9crite sans r\xe9sum\xe9.",memorizeExamples:"\nExemples :\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Obtenir les commandes shell pour une requ\xeate (Ollama uniquement)",argument:"Ce que vous voulez faire (ex. lister les gros fichiers du r\xe9pertoire courant)",loading:"R\xe9cup\xe9ration des commandes...",examples:'\nExemples :\n $ pithosai shell-tips lister les fichiers json du r\xe9pertoire courant\n $ pithosai shell-tips "remplacer foo par bar dans tous les .js"'},writer:{description:"G\xe9n\xe9rer du texte pour une requ\xeate (Ollama qwen2.5:14b)",argument:"Quoi \xe9crire (ex. court email pour d\xe9cliner une r\xe9union)",loading:"\xc9criture...",examples:'\nExemples :\n $ pithosai writer court email pour d\xe9cliner une r\xe9union\n $ pithosai writer "trois points pour un kickoff projet"'},skills:{installing:"Installation des comp\xe9tences dans {{dir}}",fetchingList:"R\xe9cup\xe9ration des comp\xe9tences disponibles depuis ClawHub...",fetchingIndex:"R\xe9cup\xe9ration de l'index des comp\xe9tences depuis {{url}}",notFound:"Comp\xe9tence '{{name}}' non trouv\xe9e",noSkillsAvailable:"Aucune comp\xe9tence disponible depuis ClawHub",noSkillsFound:"Aucune comp\xe9tence trouv\xe9e",downloadFailed:"\xc9chec du t\xe9l\xe9chargement de la comp\xe9tence '{{name}}' : {{error}}",installed:"Comp\xe9tence '{{name}}' install\xe9e",complete:"Installation termin\xe9e : {{count}} sur {{total}} comp\xe9tences install\xe9es",alreadyInstalled:"Comp\xe9tence '{{name}}' d\xe9j\xe0 install\xe9e (utilisez --force pour r\xe9installer)",downloading:"T\xe9l\xe9chargement de la comp\xe9tence '{{name}}' depuis {{url}}",noSkillsDir:"Aucun r\xe9pertoire de comp\xe9tences trouv\xe9. Installez d'abord des comp\xe9tences.",noSkillsInstalled:"Aucune comp\xe9tence install\xe9e",installedList:"Comp\xe9tences install\xe9es ({{count}} au total) dans {{dir}} :",notInstalled:"Comp\xe9tence '{{name}}' n'est pas install\xe9e",removed:"Comp\xe9tence '{{name}}' supprim\xe9e"},skillConvert:{welcome:"Syst\xe8me de conversion de comp\xe9tences - Convertir les comp\xe9tences r\xe9ussies en outils permanents",listHeader:"Analyse de conversion de comp\xe9tences ({{totalSkills}} comp\xe9tences, {{totalExecutions}} ex\xe9cutions)",noSuggestions:"Aucune comp\xe9tence n'atteint le seuil de conversion de {{threshold}}.",suggestedConversions:"Conversions sugg\xe9r\xe9es :",convertHint:"Utilisez 'pithosai skill-convert convert <nom-comp\xe9tence>' pour convertir une comp\xe9tence.",skillNotFound:"Comp\xe9tence '{{skillName}}' introuvable ou illisible : {{error}}",alreadyConverted:"La comp\xe9tence '{{skillName}}' a d\xe9j\xe0 \xe9t\xe9 convertie en outil.",useForceHint:"Utilisez --force pour convertir \xe0 nouveau.",conversionReportHeader:"Rapport de conversion de '{{skillName}}' :",conversionScore:"Score de conversion",suggestedType:"Type sugg\xe9r\xe9",ready:"Pr\xeat pour la conversion",estimatedBenefits:"B\xe9n\xe9fices estim\xe9s",performance:"Am\xe9lioration des performances",reliability:"Am\xe9lioration de la fiabilit\xe9",usability:"Am\xe9lioration de l'utilisabilit\xe9",parameters:"Param\xe8tres",notReadyWarning:"Cette comp\xe9tence n'est pas pr\xeate pour la conversion automatique.",moreUsageHint:"Utilisez la comp\xe9tence plus fr\xe9quemment ou utilisez --force pour forcer la conversion.",dryRunComplete:"Simulation termin\xe9e. Aucune modification effectu\xe9e.",confirmConversion:"Convertir '{{skillName}}' en outil permanent ?",conversionCancelled:"Conversion annul\xe9e.",converting:"Conversion de '{{skillName}}' en outil...",conversionSuccess:"'{{skillName}}' converti avec succ\xe8s en '{{toolName}}'.\nOutil enregistr\xe9 dans : {{toolPath}}",usageExample:"Exemple d'utilisation :",nextSteps:"\xc9tapes suivantes :",restartAgent:"Red\xe9marrez l'agent pour charger le nouvel outil",testTool:"Tester l'outil : <nom-outil> --help",manageTools:"G\xe9rer les outils : pithosai skill-convert tools",listError:"Erreur lors de la liste des comp\xe9tences : {{error}}",conversionError:"Erreur lors de la conversion de '{{skillName}}' : {{error}}",skillStatsHeader:"Statistiques de '{{skillName}}' :",generalStats:"Statistiques g\xe9n\xe9rales",totalExecutions:"Ex\xe9cutions totales",successful:"R\xe9ussies",failed:"\xc9chou\xe9es",avgTime:"Temps d'ex\xe9cution moyen",lastUsed:"Derni\xe8re utilisation",recentExecutions:"Ex\xe9cutions r\xe9centes",commonParameters:"Param\xe8tres courants",overallStatsHeader:"Statistiques globales des comp\xe9tences",overallStats:"Statistiques globales",totalSkillsTracked:"Comp\xe9tences suivies au total",avgSuccessRate:"Taux de r\xe9ussite moyen",topSkills:"Comp\xe9tences les plus utilis\xe9es",conversionSuggestions:"Suggestions de conversion",statsError:"Erreur lors de l'obtention des statistiques : {{error}}",confirmClearAll:"Effacer TOUS les enregistrements d'ex\xe9cution de comp\xe9tences ? Cette action est irr\xe9versible.",allRecordsCleared:"Tous les enregistrements d'ex\xe9cution de comp\xe9tences ont \xe9t\xe9 effac\xe9s.",skillRecordsCleared:"Les enregistrements d'ex\xe9cution de '{{skillName}}' ont \xe9t\xe9 effac\xe9s.",clearCancelled:"Op\xe9ration d'effacement annul\xe9e.",specifySkillOrAll:"Veuillez sp\xe9cifier un nom de comp\xe9tence ou utiliser --all",clearError:"Erreur lors de l'effacement des enregistrements : {{error}}",noConvertedTools:"Aucun outil converti trouv\xe9.",convertedToolsHeader:"Outils convertis :",originalSkill:"Comp\xe9tence d'origine",converted:"Converti le",usageCount:"Nombre d'utilisations",toolsError:"Erreur lors de la gestion des outils : {{error}}",confirmRemoveTool:"Supprimer l'outil '{{toolName}}' ?",toolRemoved:"Outil '{{toolName}}' supprim\xe9.",toolRemoveFailed:"\xc9chec de la suppression de l'outil '{{toolName}}'.",removeCancelled:"Suppression de l'outil annul\xe9e.",toolEnabled:"Outil '{{toolName}}' activ\xe9.",toolEnableFailed:"\xc9chec de l'activation de l'outil '{{toolName}}'.",toolDisabled:"Outil '{{toolName}}' d\xe9sactiv\xe9.",toolDisableFailed:"\xc9chec de la d\xe9sactivation de l'outil '{{toolName}}'.",noStatsForSkill:"Aucune statistique trouv\xe9e pour la comp\xe9tence '{{skillName}}'."},hooks:{description:"G\xe9rer les hooks d'agent pour le d\xe9bogage, la s\xe9curit\xe9 et la surveillance",list:{description:"Lister tous les hooks enregistr\xe9s",title:"\uD83D\uDCCB Hooks enregistr\xe9s",total:"Total : {{total}} gestionnaires",options:{verbose:"Afficher les informations d\xe9taill\xe9es des gestionnaires"},error:"Impossible de lister les hooks : {{error}}"},debug:{description:"Activer les hooks de d\xe9bogage pour surveiller le comportement de l'agent",options:{data:"Journaliser les donn\xe9es compl\xe8tes dans la sortie de d\xe9bogage",performance:"Activer les hooks de surveillance des performances",stats:"Activer les hooks de collecte de statistiques",all:"Activer tous les hooks de d\xe9bogage"},added:{debug:"Hooks de journalisation de d\xe9bogage ajout\xe9s",performance:"Hooks de surveillance des performances ajout\xe9s",stats:"Hooks de collecte de statistiques ajout\xe9s",basic:"Hooks de d\xe9bogage de base ajout\xe9s"},success:"Hooks de d\xe9bogage activ\xe9s ({{count}} gestionnaires enregistr\xe9s)",error:"Impossible d'activer les hooks de d\xe9bogage : {{error}}"},security:{description:"Activer les hooks de s\xe9curit\xe9 pour le contr\xf4le d'acc\xe8s et la surveillance",options:{block:"Liste d'outils \xe0 bloquer s\xe9par\xe9s par des virgules",maxPrompt:"Longueur maximale autoris\xe9e du prompt (par d\xe9faut : 10000)"},success:"Hooks de s\xe9curit\xe9 activ\xe9s",blockedTools:"Outils bloqu\xe9s : {{tools}}",maxPrompt:"Longueur maximale du prompt : {{length}} caract\xe8res",error:"Impossible d'activer les hooks de s\xe9curit\xe9 : {{error}}"},clear:{description:"Effacer tous les hooks enregistr\xe9s",success:"Tous les hooks effac\xe9s",error:"Impossible d'effacer les hooks : {{error}}"},test:{description:"Tester les hooks en les d\xe9clenchant avec des donn\xe9es de test",argument:{hookType:"Type de hook sp\xe9cifique \xe0 tester (optionnel)"},invalidType:"Type de hook invalide : {{type}}",triggered:"Hook d\xe9clench\xe9 : {{type}}",result:"R\xe9sultat : {{result}}",allTriggered:"Tous les hooks d\xe9clench\xe9s avec succ\xe8s",error:"Impossible de tester les hooks : {{error}}"},register:{description:"Enregistrer un gestionnaire de hook personnalis\xe9 depuis un fichier",argument:{hookType:"Type de hook pour lequel enregistrer le gestionnaire",handlerFile:"Chemin vers le fichier du gestionnaire (doit exporter une fonction par d\xe9faut)"},invalidType:"Type de hook invalide : {{type}}",invalidHandler:"Le fichier du gestionnaire doit exporter une fonction par d\xe9faut",success:"Gestionnaire pour {{type}} enregistr\xe9 depuis {{file}}",error:"Impossible d'enregistrer le hook : {{error}}"},status:{description:"Afficher la configuration actuelle des hooks et les statistiques",title:"\uD83D\uDCCB Statut des hooks",error:"Impossible d'obtenir le statut des hooks : {{error}}"}}}},7493(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Requisito di base",projectDir:"Directory del progetto (lavora qui): {{cwd}}",skillsInstruction:"Usa lo strumento read_skill per caricare le istruzioni complete di un'abilit\xe0 quando il compito corrisponde alla sua descrizione.",toolArgSizeLimit:"Non superare mai {{maxChars}} caratteri in un singolo argomento di chiamata a strumento (es. il content di un write). L'API pu\xf2 troncare payload pi\xf9 grandi e causare errori \xabUnterminated string in JSON\xbb. Per file o script lunghi, suddividi in pi\xf9 chiamate write (per file o per blocco sotto {{maxChars}} caratteri).",toolCallJsonFormat:'Gli argomenti di chiamata a strumento devono essere JSON valido: ogni chiave e ogni valore stringa tra virgolette doppie. Esempio per write: {"path": "file.md", "content": "contenuto qui"}. Non omettere le virgolette per chiavi o valori (es. path: file.md \xe8 invalido).'},errors:{missingPromptFiles:"file di prompt richiesti mancanti in {{dir}}:",runInit:"Esegui 'pithosai init' nella root del progetto per creare .pithosai con i modelli.",noApiKey:"Chiave API non trovata. Imposta DEEPSEEK_API_KEY o OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama non configurato. Imposta OPENAI_LOCAL_API_BASE o usa un progetto con modello locale.",noValidTemplateFiles:"nessun file di modello valido in {{dir}}. Atteso *-<lang>.md (es. IDENTITY-ja.md). Esegui 'pithosai init' per creare .pithosai con i modelli.",runTimeout:"Esecuzione dell'agente scaduta dopo {{seconds}} secondi. Usa --timeout <secondi> o PITHOSAI_TIMEOUT_MS per modificare.",agentRunFailed:"Esecuzione non riuscita: {{message}}",unknownRunError:"Errore sconosciuto"},warnings:{sessionAppend:"append sessione: {{message}}",apiRetry:"Errore API al tentativo {{attempt}}/{{max}}; riprovo..."},reasoner:{thinkingHeader:"\n--- Pensiero:\n",replyHeader:"\n\n--- Risposta:\n"},run:{cwd:"cwd {{cwd}}",request:"richiesta: {{request}}",interactivePrompt:"Tu: ",tuiYouLabel:"Tu:",interactiveExitHint:"Rispondi o inserisci una nuova richiesta (digita 'exit' o 'quit' per uscire dalla CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Modalit\xe0 interattiva — Agent (strumenti completi) ---",interactiveModeAgentTips:"- Strumenti completi (lettura, scrittura, esecuzione, secondo configurazione).\n- I turni sono salvati per attivit\xe0 nel database locale.\n- `/new` assegna un nuovo id attivit\xe0; i messaggi precedenti non vengono caricati.\n- `/shell <comando>` per la shell; `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite.\n- `/list-skill`, `/install-skill` e `/remove-skill` equivalgono a `pithosai skills list|install|remove` (ClawHub). Ctrl+S arresta, Ctrl+P mette in pausa.",interactiveModeDialogTitle:"--- Modalit\xe0 interattiva — Dialogo (Q&A in sola lettura) ---",interactiveModeDialogTips:"- Solo strumenti in sola lettura (niente shell, modifiche ai file o esecuzione comandi).\n- I turni sono salvati per attivit\xe0 nel database locale.\n- `/new` assegna un nuovo id attivit\xe0; i messaggi precedenti non vengono caricati.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite.\n- `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub) come la CLI `pithosai skills`.",interactiveModePlanTitle:"--- Modalit\xe0 piano ---",interactiveModePlanTips:"- Ogni risposta viene scritta in `<slug>-plan.md` nella directory del progetto (la prima riga della richiesta influenza il nome).\n- Solo strumenti in sola lettura; shell e strumenti mutanti disattivati.\n- `/new` assegna un nuovo id attivit\xe0.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite.\n- `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub) come la CLI `pithosai skills`.\n- Dopo ogni esecuzione puoi inserire un’altra richiesta di piano al prompt (come agent/dialog).",list:{noPersistedTasks:"Nessuna attivit\xe0 salvata trovata.",createTasksFirstHint:"Crea prima le attivit\xe0 usando `pithosai task`.",persistedTasksHeader:"--- Attivit\xe0 salvate ({{count}}) ---",selectTaskHint:"Usa `/select <index>` per eseguire un'attivit\xe0.",noTasksCached:"Nessuna attivit\xe0 in cache. Esegui `/list` prima.",invalidIndex:"Indice non valido {{index}}. Intervallo valido: 0-{{maxIndex}}.",selectUsage:"Uso: /select <index>",selectedTask:"Attivit\xe0 #{{index}} selezionata."},skillSlash:{installUsage:"Uso: /install-skill [--force] [nome-skill]",removeUsage:"Uso: /remove-skill <nome-skill>",listNoExtra:"/list-skill non accetta argomenti.",failed:"Comando skill non riuscito: {{message}}"},show:{title:"Attivit\xe0 corrente",field:"Campo",value:"Valore",taskId:"taskId",mode:"modalit\xe0",model:"modello",status:"stato",messageCount:"conteggioMessaggi",usageInput:"utilizzo.input",usageOutput:"utilizzo.output",usageCacheRead:"utilizzo.cacheLettura",usageCacheWrite:"utilizzo.cacheScrittura",usageTotalTokens:"utilizzo.tokenTotali"},showTask:{title:"Q&A attivit\xe0",taskIdLabel:"ID attivit\xe0",turnHeading:"Turno {{index}}",questionLabel:"Domanda",answerLabel:"Risposta",createdLabel:"Creato",emptyQuestion:"(domanda vuota)",emptyAnswer:"(nessuna risposta testuale dell’assistente)",emptyNoMessages:"Nessun messaggio utente per questa attivit\xe0.",previewDocumentTitle:"Q&A attivit\xe0"},showPrompt:{previewDocumentTitle:"Prompt di sistema",previewHeading:"Prompt di sistema"},shellHint:"Usa '/shell <comando>' per eseguire comandi shell (esempio: '/shell ls -la').",replIntroDialog:"Modalit\xe0 dialogo: solo strumenti in sola lettura — `/shell` disattivato. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite. `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub).",replIntroPlan:"Modalit\xe0 piano: ogni risposta in `<slug>-plan.md` (prima riga influenza il nome). `/shell` disattivato; output minimo fino al completamento. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` per le attivit\xe0 persistite. `/list-skill`, `/install-skill` e `/remove-skill` gestiscono le skill (ClawHub).",newSessionHint:"Usa '/new <richiesta>' per avviare una nuova sessione (senza cronologia chat).",newSessionNoHistory:"Uso nuova sessione (senza cronologia chat).",controlHint:"Premi Ctrl+S per fermare l'agente in esecuzione, Ctrl+P per mettere in pausa e inserire sottocomandi.",replTabCompletionHint:"Tab per completare i comandi con slash (es. /list, /list-skill, /show) o exit/quit.",tuiScrollTranscriptHint:"Nell’UI terminale: rotella, frecce, PagSu/PagGi\xf9, Ctrl+U/Ctrl+F (pagina). Ctrl+U/F scorrono il registro. Ctrl+D resta EOF/uscita a riga vuota o elimina avanti durante la digitazione.",agentStopped:"Agente fermato.",pauseHeader:"--- Agente in pausa ---",pauseCurrentRequest:"Richiesta attuale: {{request}}",pauseHelp:"Comandi: 'continue' o 'c' per riprendere, 'exit' o 'e' per uscire, oppure digita una nuova richiesta per sostituire quella attuale.",pausePrompt:"[in pausa] ",pauseRequestUpdated:"Richiesta aggiornata a: {{request}}"},shell:{noCommand:"Nessun comando fornito dopo il prefisso /shell. Utilizzo: /shell <comando>",executionError:"Errore durante l'esecuzione del comando shell: {{error}}",executing:"[shell] Esecuzione: {{command}}",errorNoCommand:"Nessun comando fornito dopo il prefisso /shell.",errorSpawnFailed:"Avvio del processo non riuscito: {{message}}",errorTimedOut:"Comando scaduto dopo {{seconds}} secondi",logFailed:"Comando shell fallito: {{command}} (codice di uscita: {{code}})",logExecutionError:"Errore di esecuzione comando shell: {{message}}",resultCommand:"Comando: {{command}}",resultExitCode:"Codice di uscita: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Successo:",resultSuccessYes:"S\xec",resultSuccessNo:"No",resultOutput:"Output:",resultError:"Errore:"},init:{invalidType:'--type non valido "{{value}}"; scegli: {{choices}}',invalidLang:'--lang non valido "{{value}}"; scegli: {{choices}}',templatesDirNotFound:"directory modelli non trovata: {{dir}}",createdPromptTemplates:"creato {{dir}} (modelli di prompt)",createdSessions:"creato {{dir}} (cronologia sessioni)",initialized:"progetto {{type}} inizializzato in {{targetDir}}",promptFilesIn:"file di prompt in {{pithosaiDir}}, dati sessione in {{sessionsDir}}",runHint:'esegui "pithosai -C {{targetDir}} \\"tua richiesta\\"" per iniziare.',createdFile:"creato {{path}}",roleAlreadyAdded:"ruolo {{role}} gi\xe0 presente in .pithosai; ignorato.",addedRoleTemplates:"modelli di ruolo aggiunti a {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: anteprima chiusa ({{source}})",skipped:"Anteprima browser saltata (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Fornisci esattamente markdown o path (non entrambi, non nessuno).",errorEmpty:"Il contenuto Markdown \xe8 vuoto.",errorFileOutside:"path deve restare nella directory del progetto.",errorNotAFile:"path non \xe8 un file normale.",errorFileTooLarge:"Il file supera {{maxBytes}} byte.",errorFileRead:"Impossibile leggere il file: {{message}}",sourceInline:"Markdown inline",sourceFile:"file {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"L'e-mail non pu\xf2 essere vuoto per il heartbeat. Configura l'e-mail del ruolo {{role}} nella tabella email_roles nel database sqlite3.",loadedState:"Stato del heartbeat caricato da SQLite per e-mail {{email}} e ruolo {{role}}, stati: {{states}}",fetchFound:"Il heartbeat ha trovato {{count}} nuovi task nella inbox: {{ids}}",savedState:"Stato del heartbeat salvato in SQLite per e-mail {{email}} e ruolo {{role}}",mergedAndNext:"Uniti {{merged}} task nello stato, prossimo da elaborare: {{stateSummary}}",replyEmailFailed:"Invio e-mail di risposta del heartbeat fallito: {{error}}",taskFailed:"Task del heartbeat fallito: {{error}}",failureReplyEmailFailed:"Invio e-mail di notifica fallimento del heartbeat fallito: {{error}}"},cli:{description:"Pithosai: implementa codice o progetti da una richiesta in linguaggio naturale. I prompt di ruolo vengono caricati dal database SQLite in fase di esecuzione (con fallback opzionale su .pithosai/<role>/*.md). Crea un progetto con 'pithosai init'.",versionOption:"mostra versione",roleOption:"ruolo (set di modelli per init); modelli in templates/<role>/",langOption:"lingua per prompt e modelli init: en, zh (predefinito: en)",interactiveModeOption:"entrare in modalit\xe0 interattiva senza richiesta; mostrare i suggerimenti della modalit\xe0 e chiedere input",initDescription:"Crea un nuovo progetto e la struttura della directory .pithosai/. I prompt di ruolo vengono caricati dal database SQLite in fase di esecuzione (con fallback opzionale su .pithosai/<role>/*.md).",initTypeOption:"tipo di progetto: js, ts o python",initExamples:"\nEsempi:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Aggiungi modelli di ruolo a .pithosai/<role>/ nel progetto",addRoleArgument:"ruolo da aggiungere (es. PM, QA)",requestArgument:'cosa costruire (es. "Un CLI che converte CSV in JSON"). Se omesso, mostra aiuto.',cwdOption:"directory del progetto (predefinito: directory corrente)",skillsDirOption:"directory abilit\xe0 per read_skill (predefinito: ./.pithosai/skills o PITHOSAI_SKILLS_DIR)",reasonerOption:"usa il modello DeepSeek Reasoner (ragionamento); predefinito DeepSeek Coder",chatOption:"usa il modello DeepSeek Chat (chat generale, non codice); predefinito DeepSeek Coder",cursorOption:"usa il modello Cursor CLI (autenticazione via cursor-agent login, nessuna chiave API necessaria). Specifica opzionalmente il modello: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"tempo max esecuzione agente in secondi (predefinito: 1800). Sovrascrivi con PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"disattiva prompt interattivo (predefinito: dopo ogni risposta chiedi la successiva)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Generazione del piano…",waitingReply:"In attesa di risposta…",runningReply:"In esecuzione…",resultPreviewOpening:"Apertura anteprima del risultato nel browser…",resultPreviewTitle:"Risultato Pithosai",resultPreviewFailed:"Impossibile aprire l'anteprima: {{message}}",resultPreviewCopy:"Copia Markdown",resultPreviewClose:"Chiudi",resultPreviewCopied:"Copiato negli appunti",resultPreviewTerminalHint:"↑↓ o j/k \xb7 PgUp/PgDn o Ctrl+U/Ctrl+D \xb7 Home/End o gg/G \xb7 q/Esc chiudi",runExamples:'\nEsempi:\n pithosai "Aggiungi un endpoint REST che restituisce l\'ora corrente"\n pithosai -C ./my-app "Esegui i test e correggi i fallimenti"\n pithosai -i # modalit\xe0 interattiva: carica ultima sessione poi chiedi richieste\n pithosai --no-interactive "Una volta" # una risposta, senza richiesta di seguito\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Uso:",helpArguments:"Argomenti:",helpOptions:"Opzioni:",helpCommands:"Comandi:",helpGlobalOptions:"Opzioni globali:",helpOption:"mostra aiuto per il comando",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Monitora il file delle attivit\xe0 e le elabora una alla volta nello stesso processo",taskFileOption:"Percorso del Markdown delle attivit\xe0 (predefinito: prompts.md nella root del progetto)",taskModelOption:"Chiave modello per l’attivit\xe0 (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Inizia con una nuova sessione (nessuna cronologia chat)",taskExamples:"\nEsempi:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Attivit\xe0 non trovata: {{taskId}}",taskAgentCompleted:"Agente completato.",taskAgentRunFailed:"Esecuzione agente non riuscita.",taskDone:"Fatto",taskFailed:"Attivit\xe0 non riuscita: {{message}}",taskProcessingHeader:"--- Elaborazione attivit\xe0 ---",taskLabelId:"id:",taskLabelTitle:"titolo:",taskLabelStatus:"stato:",taskLabelDescription:"descrizione:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Avvio processore per l’attivit\xe0 in elaborazione {{id}} ({{title}}).",taskNoPending:"Nessuna attivit\xe0 in sospeso.",taskPickedTask:"Attivit\xe0 {{id}} ({{title}}) selezionata; avvio processore.",taskProcessorFailed:"Processore attivit\xe0 non riuscito: {{message}}",taskWatcherRunning:"Monitor attivit\xe0 in esecuzione. Ctrl+C per uscire.",memorizeDescription:"Scrive .pithosai/<role>/memory.md con riepiloghi delle attivit\xe0 a cui il ruolo ha partecipato (messaggi attivit\xe0 persistiti nell’intervallo).",memorizeStartOption:"Inizio intervallo: YYYY-MM-DD o data/ora ISO",memorizeEndOption:"Fine intervallo: YYYY-MM-DD o data/ora ISO",memorizeRoleRequired:"Il ruolo \xe8 obbligatorio (-r/--role o --role globale).",memorizeWrote:"Scritto {{path}} ({{count}} attivit\xe0).",memorizeNoTasks:"Nessuna attivit\xe0 nell’intervallo per il ruolo {{role}}; intestazione in {{path}}.",memorizeDateError:"Intervallo date non valido: {{message}}",memorizeNoLlmOption:"Salta il riepilogo LLM; scrivi solo memoria strutturata (come PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"Riepilogo LLM non riuscito ({{message}}); scritta memoria strutturata senza riepilogo.",memorizeExamples:"\nEsempi:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Ottieni comandi shell per una richiesta (solo Ollama)",argument:"Cosa vuoi fare (es. elencare file grandi nella directory corrente)",loading:"Recupero comandi...",examples:'\nEsempi:\n $ pithosai shell-tips elenca file json nella directory corrente\n $ pithosai shell-tips "cerca e sostituisci foo con bar in tutti i .js"'},writer:{description:"Genera testo per una richiesta (Ollama qwen2.5:14b)",argument:"Cosa scrivere (es. breve email per declinare un meeting)",loading:"Scrittura...",examples:'\nEsempi:\n $ pithosai writer breve email per declinare un meeting\n $ pithosai writer "tre punti per un kickoff di progetto"'},skills:{installing:"Installazione delle abilit\xe0 in {{dir}}",fetchingList:"Recupero delle abilit\xe0 disponibili da ClawHub...",fetchingIndex:"Recupero dell'indice delle abilit\xe0 da {{url}}",notFound:"Abilit\xe0 '{{name}}' non trovata",noSkillsAvailable:"Nessuna abilit\xe0 disponibile da ClawHub",noSkillsFound:"Nessuna abilit\xe0 trovata",downloadFailed:"Download dell'abilit\xe0 '{{name}}' fallito: {{error}}",installed:"Abilit\xe0 '{{name}}' installata",complete:"Installazione completata: {{count}} di {{total}} abilit\xe0 installate",alreadyInstalled:"Abilit\xe0 '{{name}}' gi\xe0 installata (usa --force per reinstallare)",downloading:"Download dell'abilit\xe0 '{{name}}' da {{url}}",noSkillsDir:"Nessuna directory delle abilit\xe0 trovata. Installa prima le abilit\xe0.",noSkillsInstalled:"Nessuna abilit\xe0 installata",installedList:"Abilit\xe0 installate ({{count}} totali) in {{dir}}:",notInstalled:"Abilit\xe0 '{{name}}' non \xe8 installata",removed:"Abilit\xe0 '{{name}}' rimossa"},skillConvert:{welcome:"Sistema di conversione abilit\xe0 - Converti abilit\xe0 di successo in strumenti permanenti",listHeader:"Analisi conversione abilit\xe0 ({{totalSkills}} abilit\xe0, {{totalExecutions}} esecuzioni)",noSuggestions:"Nessuna abilit\xe0 raggiunge la soglia di conversione di {{threshold}}.",suggestedConversions:"Conversioni suggerite:",convertHint:"Usa 'pithosai skill-convert convert <nome-abilit\xe0>' per convertire un'abilit\xe0.",skillNotFound:"Abilit\xe0 '{{skillName}}' non trovata o non leggibile: {{error}}",alreadyConverted:"L'abilit\xe0 '{{skillName}}' \xe8 gi\xe0 stata convertita in strumento.",useForceHint:"Usa --force per convertire di nuovo.",conversionReportHeader:"Report di conversione di '{{skillName}}':",conversionScore:"Punteggio di conversione",suggestedType:"Tipo suggerito",ready:"Pronto per la conversione",estimatedBenefits:"Benefici stimati",performance:"Miglioramento prestazioni",reliability:"Miglioramento affidabilit\xe0",usability:"Miglioramento usabilit\xe0",parameters:"Parametri",notReadyWarning:"Questa abilit\xe0 non \xe8 pronta per la conversione automatica.",moreUsageHint:"Usa l'abilit\xe0 pi\xf9 frequentemente o usa --force per forzare la conversione.",dryRunComplete:"Esecuzione di prova completata. Nessuna modifica effettuata.",confirmConversion:"Convertire '{{skillName}}' in strumento permanente?",conversionCancelled:"Conversione annullata.",converting:"Conversione di '{{skillName}}' in strumento...",conversionSuccess:"'{{skillName}}' convertito con successo in '{{toolName}}'.\nStrumento salvato in: {{toolPath}}",usageExample:"Esempio di utilizzo:",nextSteps:"Prossimi passi:",restartAgent:"Riavvia l'agente per caricare il nuovo strumento",testTool:"Testa strumento: <nome-strumento> --help",manageTools:"Gestisci strumenti: pithosai skill-convert tools",listError:"Errore nell'elencare le abilit\xe0: {{error}}",conversionError:"Errore nella conversione di '{{skillName}}': {{error}}",skillStatsHeader:"Statistiche di '{{skillName}}':",generalStats:"Statistiche generali",totalExecutions:"Esecuzioni totali",successful:"Riuscite",failed:"Fallite",avgTime:"Tempo medio di esecuzione",lastUsed:"Ultimo utilizzo",recentExecutions:"Esecuzioni recenti",commonParameters:"Parametri comuni",overallStatsHeader:"Statistiche generali delle abilit\xe0",overallStats:"Statistiche generali",totalSkillsTracked:"Abilit\xe0 tracciate totali",avgSuccessRate:"Tasso di successo medio",topSkills:"Abilit\xe0 pi\xf9 utilizzate",conversionSuggestions:"Suggerimenti di conversione",statsError:"Errore nell'ottenere le statistiche: {{error}}",confirmClearAll:"Cancellare TUTTI i record di esecuzione delle abilit\xe0? Questa azione \xe8 irreversibile.",allRecordsCleared:"Tutti i record di esecuzione delle abilit\xe0 sono stati cancellati.",skillRecordsCleared:"I record di esecuzione di '{{skillName}}' sono stati cancellati.",clearCancelled:"Operazione di cancellazione annullata.",specifySkillOrAll:"Specifica un nome di abilit\xe0 o usa --all",clearError:"Errore nella cancellazione dei record: {{error}}",noConvertedTools:"Nessuno strumento convertito trovato.",convertedToolsHeader:"Strumenti convertiti:",originalSkill:"Abilit\xe0 originale",converted:"Convertito il",usageCount:"Conteggio utilizzi",toolsError:"Errore nella gestione degli strumenti: {{error}}",confirmRemoveTool:"Rimuovere lo strumento '{{toolName}}'?",toolRemoved:"Strumento '{{toolName}}' rimosso.",toolRemoveFailed:"Rimozione dello strumento '{{toolName}}' fallita.",removeCancelled:"Rimozione strumento annullata.",toolEnabled:"Strumento '{{toolName}}' abilitato.",toolEnableFailed:"Abilitazione dello strumento '{{toolName}}' fallita.",toolDisabled:"Strumento '{{toolName}}' disabilitato.",toolDisableFailed:"Disabilitazione dello strumento '{{toolName}}' fallita.",noStatsForSkill:"Nessuna statistica trovata per l'abilit\xe0 '{{skillName}}'."},hooks:{description:"Gestire gli hook dell'agente per debug, sicurezza e monitoraggio",list:{description:"Elencare tutti gli hook registrati",title:"\uD83D\uDCCB Hook registrati",total:"Totale: {{total}} gestori",options:{verbose:"Mostrare informazioni dettagliate sui gestori"},error:"Impossibile elencare gli hook: {{error}}"},debug:{description:"Abilitare gli hook di debug per monitorare il comportamento dell'agente",options:{data:"Registrare i dati completi nell'output di debug",performance:"Abilitare gli hook di monitoraggio delle prestazioni",stats:"Abilitare gli hook di raccolta statistiche",all:"Abilitare tutti gli hook di debug"},added:{debug:"Hook di log di debug aggiunti",performance:"Hook di monitoraggio delle prestazioni aggiunti",stats:"Hook di raccolta statistiche aggiunti",basic:"Hook di debug di base aggiunti"},success:"Hook di debug abilitati ({{count}} gestori registrati)",error:"Impossibile abilitare gli hook di debug: {{error}}"},security:{description:"Abilitare gli hook di sicurezza per il controllo degli accessi e il monitoraggio",options:{block:"Lista di strumenti da bloccare separati da virgole",maxPrompt:"Lunghezza massima consentita del prompt (predefinito: 10000)"},success:"Hook di sicurezza abilitati",blockedTools:"Strumenti bloccati: {{tools}}",maxPrompt:"Lunghezza massima del prompt: {{length}} caratteri",error:"Impossibile abilitare gli hook di sicurezza: {{error}}"},clear:{description:"Cancellare tutti gli hook registrati",success:"Tutti gli hook cancellati",error:"Impossibile cancellare gli hook: {{error}}"},test:{description:"Testare gli hook attivandoli con dati di prova",argument:{hookType:"Tipo di hook specifico da testare (opzionale)"},invalidType:"Tipo di hook non valido: {{type}}",triggered:"Hook attivato: {{type}}",result:"Risultato: {{result}}",allTriggered:"Tutti gli hook attivati con successo",error:"Impossibile testare gli hook: {{error}}"},register:{description:"Registrare un gestore di hook personalizzato da un file",argument:{hookType:"Tipo di hook per cui registrare il gestore",handlerFile:"Percorso del file del gestore (deve esportare una funzione predefinita)"},invalidType:"Tipo di hook non valido: {{type}}",invalidHandler:"Il file del gestore deve esportare una funzione predefinita",success:"Gestore per {{type}} registrato da {{file}}",error:"Impossibile registrare l'hook: {{error}}"},status:{description:"Mostrare la configurazione attuale degli hook e le statistiche",title:"\uD83D\uDCCB Stato degli hook",error:"Impossibile ottenere lo stato degli hook: {{error}}"}}}},7893(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"基本要件",projectDir:"プロジェクトディレクトリ(ここで作業): {{cwd}}",skillsInstruction:"タスクが説明と一致する場合、read_skill ツールでスキルの完全な指示を読み込んでください。",toolArgSizeLimit:"1 回のツール呼び出しの引数(例: write の content)は {{maxChars}} 文字を超えてはいけません。超えると API が切り詰め「Unterminated string in JSON」エラーになります。長いファイルやスクリプトは複数の write 呼び出しに分割してください(ファイル単位または {{maxChars}} 文字以内のチャンク単位)。",toolCallJsonFormat:'ツール呼び出しの引数は有効な JSON にしてください。すべてのキーと文字列値はダブルクォートで囲んでください。write の例: {"path": "ファイル名.md", "content": "内容"}。キーや値のクォートを省略しないでください(例: path: file.md は無効)。'},errors:{missingPromptFiles:"{{dir}} に必要なプロンプトファイルがありません:",runInit:"プロジェクトルートで 'pithosai init' を実行して .pithosai とテンプレートを作成してください。",noApiKey:"API キーが見つかりません。DEEPSEEK_API_KEY または OPENROUTER_API_KEY を設定してください。",ollamaNotConfigured:"Ollama が設定されていません。OPENAI_LOCAL_API_BASE を設定するか、ローカルモデルを持つプロジェクトを使用してください。",noValidTemplateFiles:"{{dir}} に有効なテンプレートファイルがありません。*-<lang>.md(例: IDENTITY-ja.md)が必要です。'pithosai init' を実行して .pithosai とテンプレートを作成してください。",runTimeout:"エージェントの実行が {{seconds}} 秒でタイムアウトしました。--timeout <秒> または PITHOSAI_TIMEOUT_MS で調整できます。",agentRunFailed:"実行に失敗しました: {{message}}",unknownRunError:"不明なエラー"},warnings:{sessionAppend:"セッション追加: {{message}}",apiRetry:"API エラー、試行 {{attempt}}/{{max}};再試行中..."},reasoner:{thinkingHeader:"\n--- 思考:\n",replyHeader:"\n\n--- 返答:\n"},run:{cwd:"cwd {{cwd}}",request:"リクエスト: {{request}}",interactivePrompt:"あなた: ",tuiYouLabel:"あなた:",interactiveExitHint:"回答するか新しいリクエストを入力してください('exit' または 'quit' で CLI を終了)。",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- インタラクティブ — エージェント(全ツール)---",interactiveModeAgentTips:"- 設定に応じた全ツール(読み取り・書き込み・実行など)が使えます。\n- 会話はタスク単位でローカル DB に保存されます。\n- `/new` で新しいタスク ID が割り当てられ、過去メッセージは読み込まれません。\n- `/shell <command>` でシェル実行。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` で永続化タスクを操作。\n- `/list-skill`、`/install-skill`、`/remove-skill` は `pithosai skills list|install|remove` と同じ(ClawHub)。Ctrl+S で停止、Ctrl+P で一時停止。",interactiveModeDialogTitle:"--- インタラクティブ — ダイアログ(読み取り専用 Q&A)---",interactiveModeDialogTips:"- 読み取り専用ツールのみ(シェル・ファイル編集・コマンド実行は不可)。\n- 会話はタスク単位でローカル DB に保存されます。\n- `/new` で新しいタスク ID が割り当てられ、過去メッセージは読み込まれません。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` で永続化タスクを操作。\n- `/list-skill`、`/install-skill`、`/remove-skill` でスキルを管理(ClawHub、`pithosai skills` CLI と同等)。",interactiveModePlanTitle:"--- プランモード ---",interactiveModePlanTips:"- 各応答はプロジェクト直下の `<slug>-plan.md` に保存されます(リクエスト先頭行がファイル名に影響)。\n- 読み取り専用ツールのみ。シェルや変更系ツールは不可。\n- `/new` で新しいタスク ID が割り当てられます。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` で永続化タスクを操作。\n- `/list-skill`、`/install-skill`、`/remove-skill` でスキルを管理(ClawHub、`pithosai skills` CLI と同等)。\n- 各実行後もプロンプトで次の計画リクエストを入力できます(agent/dialog と同様)。",list:{noPersistedTasks:"保存されたタスクが見つかりません。",createTasksFirstHint:"`pithosai task` を使って先にタスクを作成してください。",persistedTasksHeader:"--- 保存されたタスク ({{count}}) ---",selectTaskHint:"タスクを実行するには `/select <index>` を使用してください。",noTasksCached:"キャッシュされたタスクがありません。先に `/list` を実行してください。",invalidIndex:"無効なインデックス {{index}} です。有効範囲: 0-{{maxIndex}}。",selectUsage:"使い方: /select <index>",selectedTask:"タスク #{{index}} を選択しました。"},skillSlash:{installUsage:"使い方: /install-skill [--force] [スキル名]",removeUsage:"使い方: /remove-skill <スキル名>",listNoExtra:"/list-skill に引数は取れません。",failed:"スキルコマンドが失敗しました: {{message}}"},show:{title:"現在のタスク",field:"項目",value:"値",taskId:"taskId",mode:"モード",model:"モデル",status:"ステータス",messageCount:"メッセージ数",usageInput:"使用量.入力",usageOutput:"使用量.出力",usageCacheRead:"使用量.キャッシュ読込",usageCacheWrite:"使用量.キャッシュ書込",usageTotalTokens:"使用量.合計トークン"},showTask:{title:"タスクQ&A",taskIdLabel:"タスクID",turnHeading:"ターン {{index}}",questionLabel:"質問",answerLabel:"回答",createdLabel:"作成日時",emptyQuestion:"(質問なし)",emptyAnswer:"(アシスタントのテキスト回答なし)",emptyNoMessages:"このタスクにはまだユーザーメッセージがありません。",previewDocumentTitle:"タスクQ&A"},showPrompt:{previewDocumentTitle:"システムプロンプト",previewHeading:"システムプロンプト"},shellHint:"シェルコマンドを実行するには '/shell <コマンド>' を使用します(例: '/shell ls -la')。",replIntroDialog:"ダイアログモード:読み取り専用ツールのみ — `/shell` は無効。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` が永続化タスクに使えます。`/list-skill`、`/install-skill`、`/remove-skill` でスキル管理(ClawHub)。",replIntroPlan:"プランモード:各応答は `<slug>-plan.md` に保存(先頭行がファイル名に影響)。`/shell` は無効。完了まで出力は最小限です。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` が永続化タスクに使えます。`/list-skill`、`/install-skill`、`/remove-skill` でスキル管理(ClawHub)。",newSessionHint:"新しいセッション(チャット履歴なし)を開始するには '/new <リクエスト>' を使用します。",newSessionNoHistory:"新しいセッションを使用しています(チャット履歴なし)。",controlHint:"Ctrl+S で実行中のエージェントを停止、Ctrl+P で一時停止してサブコマンドに入ります。",replTabCompletionHint:"Tab でスラッシュコマンド(例: /list、/list-skill、/show)や exit/quit を補完できます。",tuiScrollTranscriptHint:"ターミナル UI:ホイール、矢印、PgUp/PgDn、Ctrl+U/Ctrl+F(ページ)。Ctrl+U/F はログをスクロール。Ctrl+D は空行で終了・入力中は前方削除のまま。",agentStopped:"エージェントが停止しました。",pauseHeader:"--- エージェント一時停止中 ---",pauseCurrentRequest:"現在のリクエスト:{{request}}",pauseHelp:"コマンド:'continue' または 'c' で再開、'exit' または 'e' で終了、またはリクエストを入力して置き換えます。",pausePrompt:"[一時停止] ",pauseRequestUpdated:"リクエストを更新しました:{{request}}"},shell:{noCommand:"/shell プレフィックスの後にコマンドが指定されていません。使用法: /shell <コマンド>",executionError:"シェルコマンドの実行中にエラーが発生しました: {{error}}",executing:"[shell] 実行中: {{command}}",errorNoCommand:"/shell プレフィックスの後にコマンドが指定されていません。",errorSpawnFailed:"プロセスの起動に失敗しました: {{message}}",errorTimedOut:"コマンドは {{seconds}} 秒でタイムアウトしました",logFailed:"Shell コマンドが失敗しました: {{command}} (終了コード: {{code}})",logExecutionError:"Shell コマンド実行エラー: {{message}}",resultCommand:"コマンド: {{command}}",resultExitCode:"終了コード: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"成功:",resultSuccessYes:"はい",resultSuccessNo:"いいえ",resultOutput:"出力:",resultError:"エラー:"},init:{invalidType:'--type "{{value}}" は無効です。選択肢: {{choices}}',invalidLang:'--lang "{{value}}" は無効です。選択肢: {{choices}}',templatesDirNotFound:"テンプレートディレクトリが見つかりません: {{dir}}",createdPromptTemplates:"{{dir}} を作成しました(プロンプトテンプレート)",createdSessions:"{{dir}} を作成しました(セッション履歴)",initialized:"{{targetDir}} に {{type}} プロジェクトを初期化しました",promptFilesIn:"プロンプトファイルは {{pithosaiDir}}、セッションデータは {{sessionsDir}}",runHint:'開始するには "pithosai -C {{targetDir}} \\"リクエスト\\"" を実行してください。',createdFile:"{{path}} を作成しました",roleAlreadyAdded:"ロール {{role}} は既に .pithosai にあります;スキップします。",addedRoleTemplates:"{{dir}} にロールテンプレートを追加しました"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: プレビューを閉じました({{source}})",skipped:"ブラウザプレビューをスキップしました(PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"markdown と path のどちらか一方だけを指定してください。",errorEmpty:"Markdown が空です。",errorFileOutside:"path はプロジェクトディレクトリ内である必要があります。",errorNotAFile:"path は通常のファイルではありません。",errorFileTooLarge:"ファイルが大きすぎます(最大 {{maxBytes}} バイト)。",errorFileRead:"ファイルを読めませんでした: {{message}}",sourceInline:"インライン Markdown",sourceFile:"ファイル {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"ハートビート用のメールは空にできません。sqlite3 DB の email_roles テーブルでロール {{role}} のメールを設定してください。",loadedState:"SQLite からハートビート状態を読み込みました(メール {{email}}、ロール {{role}})。状態: {{states}}",fetchFound:"ハートビートの受信トレイ取得で {{count}} 件の新規タスクを検出: {{ids}}",savedState:"ハートビート状態を SQLite に保存しました(メール {{email}}、ロール {{role}})",mergedAndNext:"{{merged}} 件のタスクを状態にマージしました。次に処理するスロット: {{stateSummary}}",replyEmailFailed:"ハートビートの返信メール送信に失敗しました: {{error}}",taskFailed:"ハートビートのタスクに失敗しました: {{error}}",failureReplyEmailFailed:"ハートビートの失敗通知メール送信に失敗しました: {{error}}"},cli:{description:"Pithosai: 自然言語のリクエストからコードやプロジェクトを実装します。 役割プロンプトは実行時に SQLite データベースから読み込まれます(オプションで .pithosai/<role>/*.md にフォールバック)。'pithosai init' でプロジェクトを作成します。",versionOption:"バージョンを表示",roleOption:"ロール(init 用テンプレートセット);テンプレートは templates/<role>/ にあります",langOption:"プロンプトと init テンプレートの言語: en, zh(デフォルト: en)",interactiveModeOption:"リクエストなしでインタラクティブモードに入る;モードの説明を表示して入力を待つ",initDescription:"新規プロジェクトと .pithosai/ ディレクトリ構造を作成。役割プロンプトは実行時に SQLite データベースから読み込まれます(オプションで .pithosai/<role>/*.md にフォールバック)。",initTypeOption:"プロジェクトタイプ: js, ts, python",initExamples:"\n例:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"プロジェクトの .pithosai/<role>/ にロールテンプレートを追加",addRoleArgument:"追加するロール(例: PM, QA)",requestArgument:'作成するもの(例: "CSV を JSON に変換する CLI")。省略するとヘルプを表示。',cwdOption:"プロジェクトディレクトリ(デフォルト: カレントディレクトリ)",skillsDirOption:"read_skill 用スキルディレクトリ(デフォルト: ./.pithosai/skills または PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner(思考)モデルを使用;デフォルトは DeepSeek Coder",chatOption:"DeepSeek Chat モデルを使用(一般チャット、コード以外);デフォルトは DeepSeek Coder",cursorOption:"Cursor CLI モデルを使用(cursor-agent login で認証、API キー不要)。オプションでモデル指定: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"エージェント最大実行時間(秒、デフォルト: 1800)。PITHOSAI_TIMEOUT_MS(ミリ秒)で上書き可能。",interactiveOption:"対話プロンプトを無効にする(デフォルト: 各返答後に次のメッセージを促す)",modeOption:"variant: agent(既定・ツール可)、dialog(回答のみ・ツールなし)、plan(プロジェクト直下に <slug>-plan.md のみ出力・ツールなし)",shellDisabledInMode:"dialog / plan モードでは /shell は無効です。",planWritten:"プランを {{path}} に書き込みました",planRunning:"プランを生成中…",waitingReply:"応答を待っています…",runningReply:"実行中…",resultPreviewOpening:"ブラウザで結果プレビューを開いています…",resultPreviewTitle:"Pithosai の結果",resultPreviewFailed:"結果プレビューを開けませんでした: {{message}}",resultPreviewCopy:"Markdown をコピー",resultPreviewClose:"閉じる",resultPreviewCopied:"クリップボードにコピーしました",resultPreviewTerminalHint:"↑↓ または j/k \xb7 PgUp/PgDn または Ctrl+U/Ctrl+D \xb7 Home/End または gg/G \xb7 q/Esc で閉じる",runExamples:'\n例:\n pithosai "現在時刻を返す REST エンドポイントを追加"\n pithosai -C ./my-app "テストを実行して失敗を修正"\n pithosai -i # インタラクティブモード:最新セッション読み込み後プロンプト\n pithosai --no-interactive "1回" # 1回の返答、続きのプロンプトなし\n pithosai --mode dialog "このエラーを説明"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"使用法:",helpArguments:"引数:",helpOptions:"オプション:",helpCommands:"コマンド:",helpGlobalOptions:"グローバルオプション:",helpOption:"コマンドのヘルプを表示",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"タスクファイルを監視し、同一プロセスで1件ずつ処理します",taskFileOption:"タスク用 Markdown のパス(既定:プロジェクトルートの prompts.md)",taskModelOption:"タスクのモデルキー(deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"新しいセッションで開始(チャット履歴なし)",taskExamples:"\n例:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"タスクが見つかりません: {{taskId}}",taskAgentCompleted:"エージェントが完了しました。",taskAgentRunFailed:"エージェントの実行に失敗しました。",taskDone:"完了",taskFailed:"タスクが失敗しました: {{message}}",taskProcessingHeader:"--- タスクを処理中 ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"処理中タスク {{id}}({{title}})のプロセッサを開始します。",taskNoPending:"保留中のタスクはありません。",taskPickedTask:"タスク {{id}}({{title}})を選択しました。プロセッサを開始します。",taskProcessorFailed:"タスクプロセッサが失敗しました: {{message}}",taskWatcherRunning:"タスクウォッチャー実行中。Ctrl+C で停止。",memorizeDescription:"指定期間にロールが関与したタスク(永続化されたタスクメッセージ)を要約し、.pithosai/<role>/memory.md に書き出します。",memorizeStartOption:"開始日: YYYY-MM-DD または ISO 日時",memorizeEndOption:"終了日: YYYY-MM-DD または ISO 日時",memorizeRoleRequired:"ロールが必要です(-r/--role またはグローバル --role)。",memorizeWrote:"{{path}} に書き込みました({{count}} 件のタスク)。",memorizeNoTasks:"ロール {{role}} の期間内タスクはありません。{{path}} にヘッダのみ書き込みました。",memorizeDateError:"日付範囲が無効です: {{message}}",memorizeNoLlmOption:"LLM 要約をスキップし、構造化メモリのみ書き込む(PITHOSAI_MEMORIZE_SKIP_LLM=1 と同じ)。",memorizeLlmFallback:"LLM 要約に失敗しました({{message}})。要約なしの構造化メモリを書き込みました。",memorizeExamples:"\n例:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"旧バージョンの平文 pithosai.db(例: v1.0.4)を SQLCipher に移行します。アプリ実行時と同じデバイスバインド鍵を使います(docs/device-id.md 参照)。複数回実行しても安全です。",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"リクエストに応じたシェルコマンドを取得(Ollama のみ、コマンドのみ出力)",argument:"やりたいこと(例:カレントディレクトリの大きいファイルを一覧)",loading:"コマンドを取得中...",examples:'\n例:\n $ pithosai shell-tips カレントディレクトリの json ファイルを一覧\n $ pithosai shell-tips "全 .js ファイルで foo を bar に置換"'},writer:{description:"リクエストに応じてテキストを生成(Ollama qwen2.5:14b)",argument:"書く内容(例:会議を断る短いメール)",loading:"執筆中...",examples:'\n例:\n $ pithosai writer 会議を断る短いメール\n $ pithosai writer "プロジェクトキックオフの3つのポイント"'},skills:{installing:"スキルを {{dir}} にインストール中",fetchingList:"ClawHub から利用可能なスキルを取得中...",fetchingIndex:"{{url}} からスキルインデックスを取得中",notFound:"スキル '{{name}}' が見つかりません",noSkillsAvailable:"ClawHub から利用可能なスキルはありません",noSkillsFound:"スキルが見つかりません",downloadFailed:"スキル '{{name}}' のダウンロードに失敗: {{error}}",installed:"スキル '{{name}}' をインストールしました",complete:"インストール完了: {{count}} / {{total}} スキルをインストール",alreadyInstalled:"スキル '{{name}}' は既にインストール済み(再インストールには --force を使用)",downloading:"スキル '{{name}}' を {{url}} からダウンロード中",noSkillsDir:"スキルディレクトリが見つかりません。まずスキルをインストールしてください。",noSkillsInstalled:"インストール済みスキルはありません",installedList:"インストール済みスキル(合計 {{count}}){{dir}} 内:",notInstalled:"スキル '{{name}}' はインストールされていません",removed:"スキル '{{name}}' を削除しました"},skillConvert:{welcome:"スキル変換システム - 成功したスキルを永続ツールに変換",listHeader:"スキル変換分析({{totalSkills}} スキル、{{totalExecutions}} 回実行)",noSuggestions:"変換しきい値 {{threshold}} を満たすスキルはありません。",suggestedConversions:"変換推奨:",convertHint:"'pithosai skill-convert convert <スキル名>' でスキルを変換できます。",skillNotFound:"スキル '{{skillName}}' が見つからないか読み取れません: {{error}}",alreadyConverted:"スキル '{{skillName}}' は既にツールに変換されています。",useForceHint:"--force を使って再度変換できます。",conversionReportHeader:"'{{skillName}}' 変換レポート:",conversionScore:"変換スコア",suggestedType:"推奨タイプ",ready:"変換準備完了",estimatedBenefits:"見込み効果",performance:"パフォーマンス向上",reliability:"信頼性向上",usability:"使いやすさ向上",parameters:"パラメーター",notReadyWarning:"このスキルは自動変換の準備ができていません。",moreUsageHint:"スキルをもっと使用するか、--force で強制変換してください。",dryRunComplete:"ドライラン完了。変更はありません。",confirmConversion:"'{{skillName}}' を永続ツールに変換しますか?",conversionCancelled:"変換がキャンセルされました。",converting:"'{{skillName}}' をツールに変換中...",conversionSuccess:"'{{skillName}}' を '{{toolName}}' に変換しました。\nツール保存先: {{toolPath}}",usageExample:"使用例:",nextSteps:"次のステップ:",restartAgent:"新しいツールを読み込むためにエージェントを再起動してください",testTool:"ツールをテスト: <ツール名> --help",manageTools:"ツール管理: pithosai skill-convert tools",listError:"スキル一覧の取得でエラー: {{error}}",conversionError:"'{{skillName}}' の変換でエラー: {{error}}",skillStatsHeader:"'{{skillName}}' の統計情報:",generalStats:"一般統計",totalExecutions:"合計実行回数",successful:"成功",failed:"失敗",avgTime:"平均実行時間",lastUsed:"最終使用",recentExecutions:"最近の実行",commonParameters:"よく使うパラメーター",overallStatsHeader:"全体スキル統計",overallStats:"全体統計",totalSkillsTracked:"追跡スキル数",avgSuccessRate:"平均成功率",topSkills:"使用量上位のスキル",conversionSuggestions:"変換候補",statsError:"統計の取得でエラー: {{error}}",confirmClearAll:"すべてのスキル実行記録を消去しますか?この操作は取り消せません。",allRecordsCleared:"すべてのスキル実行記録が消去されました。",skillRecordsCleared:"'{{skillName}}' のスキル実行記録が消去されました。",clearCancelled:"消去がキャンセルされました。",specifySkillOrAll:"スキル名を指定するか --all を使用してください",clearError:"記録の消去でエラー: {{error}}",noConvertedTools:"変換されたツールはありません。",convertedToolsHeader:"変換済みツール:",originalSkill:"元のスキル",converted:"変換日時",usageCount:"使用回数",toolsError:"ツール管理でエラー: {{error}}",confirmRemoveTool:"ツール '{{toolName}}' を削除しますか?",toolRemoved:"ツール '{{toolName}}' が削除されました。",toolRemoveFailed:"ツール '{{toolName}}' の削除に失敗しました。",removeCancelled:"ツール削除がキャンセルされました。",toolEnabled:"ツール '{{toolName}}' が有効になりました。",toolEnableFailed:"ツール '{{toolName}}' の有効化に失敗しました。",toolDisabled:"ツール '{{toolName}}' が無効になりました。",toolDisableFailed:"ツール '{{toolName}}' の無効化に失敗しました。",noStatsForSkill:"スキル '{{skillName}}' の統計情報が見つかりません。"},hooks:{description:"デバッグ、セキュリティ、監視用のエージェントフックを管理",list:{description:"登録済みのすべてのフックを一覧表示",title:"\uD83D\uDCCB 登録済みフック",total:"合計: {{total}} ハンドラー",options:{verbose:"詳細なハンドラー情報を表示"},error:"フックの一覧表示に失敗: {{error}}"},debug:{description:"エージェントの動作を監視するデバッグフックを有効化",options:{data:"デバッグ出力に完全なデータを記録",performance:"パフォーマンス監視フックを有効化",stats:"統計収集フックを有効化",all:"すべてのデバッグフックを有効化"},added:{debug:"デバッグログフックを追加しました",performance:"パフォーマンス監視フックを追加しました",stats:"統計収集フックを追加しました",basic:"基本デバッグフックを追加しました"},success:"デバッグフックを有効化しました({{count}} ハンドラー登録済み)",error:"デバッグフックの有効化に失敗: {{error}}"},security:{description:"アクセス制御と監視のためのセキュリティフックを有効化",options:{block:"ブロックするツールのカンマ区切りリスト",maxPrompt:"最大プロンプト長(デフォルト: 10000)"},success:"セキュリティフックを有効化しました",blockedTools:"ブロックされたツール: {{tools}}",maxPrompt:"最大プロンプト長: {{length}} 文字",error:"セキュリティフックの有効化に失敗: {{error}}"},clear:{description:"登録済みのすべてのフックをクリア",success:"すべてのフックをクリアしました",error:"フックのクリアに失敗: {{error}}"},test:{description:"テストデータでフックをトリガーしてテスト",argument:{hookType:"テストするフックタイプ(省略可)"},invalidType:"無効なフックタイプ: {{type}}",triggered:"フックをトリガーしました: {{type}}",result:"結果: {{result}}",allTriggered:"すべてのフックが正常にトリガーされました",error:"フックのテストに失敗: {{error}}"},register:{description:"ファイルからカスタムフックハンドラーを登録",argument:{hookType:"ハンドラーを登録するフックタイプ",handlerFile:"ハンドラーファイルのパス(デフォルト関数をエクスポートする必要あり)"},invalidType:"無効なフックタイプ: {{type}}",invalidHandler:"ハンドラーファイルはデフォルト関数をエクスポートする必要があります",success:"{{file}} から {{type}} のハンドラーを登録しました",error:"フックの登録に失敗: {{error}}"},status:{description:"現在のフック設定と統計情報を表示",title:"\uD83D\uDCCB フックステータス",error:"フックステータスの取得に失敗: {{error}}"}}}},5490(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"기본 요구사항",projectDir:"프로젝트 디렉터리 (여기서 작업): {{cwd}}",skillsInstruction:"작업이 설명과 일치할 때 read_skill 도구를 사용하여 해당 스킬의 전체 지침을 로드하세요.",toolArgSizeLimit:'단일 도구 호출 인수(예: write의 content)는 {{maxChars}}자를 절대 초과하면 안 됩니다. 초과 시 API가 잘라 "Unterminated string in JSON" 오류가 납니다. 긴 파일이나 스크립트는 여러 write 호출로 나누세요(파일별 또는 {{maxChars}}자 이내 청크별).',toolCallJsonFormat:'도구 호출 인수는 유효한 JSON이어야 합니다. 모든 키와 문자열 값은 큰따옴표로 감싸세요. write 예: {"path": "파일명.md", "content": "내용"}. 키나 값의 따옴표를 생략하지 마세요(예: path: file.md는 무효).'},errors:{missingPromptFiles:"{{dir}}에 필요한 프롬프트 파일이 없습니다:",runInit:"프로젝트 루트에서 'pithosai init'을 실행하여 .pithosai와 템플릿을 만드세요.",noApiKey:"API 키를 찾을 수 없습니다. DEEPSEEK_API_KEY 또는 OPENROUTER_API_KEY를 설정하세요.",ollamaNotConfigured:"Ollama가 설정되지 않았습니다. OPENAI_LOCAL_API_BASE를 설정하거나 로컬 모델이 있는 프로젝트를 사용하세요.",noValidTemplateFiles:"{{dir}}에 유효한 템플릿 파일이 없습니다. *-<lang>.md (예: IDENTITY-ja.md) 형식이 필요합니다. 'pithosai init'을 실행하여 .pithosai와 템플릿을 만드세요.",runTimeout:"에이전트 실행이 {{seconds}}초 후 타임아웃되었습니다. --timeout <초> 또는 PITHOSAI_TIMEOUT_MS로 조정하세요.",agentRunFailed:"실행 실패: {{message}}",unknownRunError:"알 수 없는 오류"},warnings:{sessionAppend:"세션 추가: {{message}}",apiRetry:"API 오류, 시도 {{attempt}}/{{max}}; 재시도 중..."},reasoner:{thinkingHeader:"\n--- 생각:\n",replyHeader:"\n\n--- 답변:\n"},run:{cwd:"cwd {{cwd}}",request:"요청: {{request}}",interactivePrompt:"당신: ",tuiYouLabel:"당신:",interactiveExitHint:"답변하거나 새 요청을 입력하세요 (CLI 종료: 'exit' 또는 'quit' 입력).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- 대화형 모드 — 에이전트(전체 도구) ---",interactiveModeAgentTips:"- 설정에 따라 읽기\xb7쓰기\xb7실행 등 전체 도구를 사용할 수 있습니다.\n- 대화는 작업별로 로컬 DB에 저장됩니다.\n- `/new`는 새 작업 ID를 부여하며 이전 메시지를 불러오지 않습니다.\n- `/shell <명령>`으로 셸 실행, `/list`, `/select`, `/show`, `/show-task`, `/show-prompt`로 저장된 작업 관리.\n- `/list-skill`, `/install-skill`, `/remove-skill`은 `pithosai skills list|install|remove`와 동일(ClawHub). Ctrl+S 중지, Ctrl+P 일시정지.",interactiveModeDialogTitle:"--- 대화형 모드 — 다이얼로그(읽기 전용 Q&A) ---",interactiveModeDialogTips:"- 읽기 전용 도구만 사용합니다(셸, 파일 편집, 명령 실행 불가).\n- 대화는 작업별로 로컬 DB에 저장됩니다.\n- `/new`는 새 작업 ID를 부여하며 이전 메시지를 불러오지 않습니다.\n- `/list`, `/select`, `/show`, `/show-task`, `/show-prompt`로 저장된 작업을 다룹니다.\n- `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub, `pithosai skills` CLI와 동일).",interactiveModePlanTitle:"--- 계획 모드 ---",interactiveModePlanTips:"- 각 응답은 프로젝트 디렉터리의 `<slug>-plan.md`에 기록됩니다(요청 첫 줄이 파일명에 영향).\n- 읽기 전용 도구만 사용; 셸 및 변경 도구는 비활성화됩니다.\n- `/new`는 새 작업 ID를 부여합니다.\n- `/list`, `/select`, `/show`, `/show-task`, `/show-prompt`로 저장된 작업을 다룹니다.\n- `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub, `pithosai skills` CLI와 동일).\n- 실행이 끝난 뒤 프롬프트에서 새 계획 요청을 이어갈 수 있습니다(agent/dialog과 동일).",list:{noPersistedTasks:"저장된 작업을 찾을 수 없습니다.",createTasksFirstHint:"`pithosai task`로 먼저 작업을 생성하세요.",persistedTasksHeader:"--- 저장된 작업 ({{count}}) ---",selectTaskHint:"작업을 실행하려면 `/select <index>`를 사용하세요.",noTasksCached:"캐시된 작업이 없습니다. 먼저 `/list`를 실행하세요.",invalidIndex:"잘못된 인덱스 {{index}}입니다. 유효 범위: 0-{{maxIndex}}.",selectUsage:"사용법: /select <index>",selectedTask:"작업 #{{index}}를 선택했습니다."},skillSlash:{installUsage:"사용법: /install-skill [--force] [스킬이름]",removeUsage:"사용법: /remove-skill <스킬이름>",listNoExtra:"/list-skill은 인자를 받지 않습니다.",failed:"스킬 명령 실패: {{message}}"},show:{title:"현재 작업",field:"항목",value:"값",taskId:"taskId",mode:"모드",model:"모델",status:"상태",messageCount:"메시지수",usageInput:"사용량.입력",usageOutput:"사용량.출력",usageCacheRead:"사용량.캐시읽기",usageCacheWrite:"사용량.캐시쓰기",usageTotalTokens:"사용량.총토큰"},showTask:{title:"작업 Q&A",taskIdLabel:"작업 ID",turnHeading:"{{index}}번째 턴",questionLabel:"질문",answerLabel:"답변",createdLabel:"생성 시각",emptyQuestion:"(빈 질문)",emptyAnswer:"(어시스턴트 텍스트 답변 없음)",emptyNoMessages:"이 작업에 사용자 메시지가 아직 없습니다.",previewDocumentTitle:"작업 Q&A"},showPrompt:{previewDocumentTitle:"시스템 프롬프트",previewHeading:"시스템 프롬프트"},shellHint:"셸 명령을 실행하려면 '/shell <명령>'을 사용하세요 (예: '/shell ls -la').",replIntroDialog:"대화 모드: 읽기 전용 도구만 — `/shell` 비활성화. 저장된 작업에는 `/list`, `/select`, `/show`, `/show-task`, `/show-prompt` 사용. `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub).",replIntroPlan:"계획 모드: 각 응답은 `<slug>-plan.md`에 저장(첫 줄이 파일명에 영향). `/shell` 비활성화; 완료 전까지 출력은 최소화. 저장된 작업에는 `/list`, `/select`, `/show`, `/show-task`, `/show-prompt` 사용. `/list-skill`, `/install-skill`, `/remove-skill`로 스킬 관리(ClawHub).",newSessionHint:"새 세션(채팅 기록 없음)을 시작하려면 '/new <요청>'을 사용하세요.",newSessionNoHistory:"새 세션 사용 중입니다(채팅 기록 없음).",controlHint:"Ctrl+S를 눌러 실행 중인 에이전트를 중지하고, Ctrl+P를 눌러 일시 중지 후 하위 명령을 입력합니다.",replTabCompletionHint:"Tab으로 슬래시 명령(예: /list, /list-skill, /show) 또는 exit/quit을 완성할 수 있습니다.",tuiScrollTranscriptHint:"터미널 UI: 휠, 방향키, PgUp/PgDn, Ctrl+U/Ctrl+F(페이지). Ctrl+U/F는 로그 스크롤. Ctrl+D는 빈 줄 종료\xb7입력 중 앞으로 삭제 그대로.",agentStopped:"에이전트가 중지되었습니다.",pauseHeader:"--- 에이전트 일시 중지됨 ---",pauseCurrentRequest:"현재 요청: {{request}}",pauseHelp:"명령: 'continue' 또는 'c'로 계속, 'exit' 또는 'e'로 종료, 또는 새 요청을 입력하여 현재 요청을 교체합니다.",pausePrompt:"[일시 중지] ",pauseRequestUpdated:"요청이 업데이트됨: {{request}}"},shell:{noCommand:"/shell 접두사 뒤에 명령이 제공되지 않았습니다. 사용법: /shell <명령>",executionError:"셸 명령 실행 중 오류 발생: {{error}}",executing:"[shell] 실행 중: {{command}}",errorNoCommand:"/shell 접두사 뒤에 명령이 제공되지 않았습니다.",errorSpawnFailed:"프로세스 시작 실패: {{message}}",errorTimedOut:"{{seconds}}초 후 명령 시간 초과",logFailed:"Shell 명령 실패: {{command}} (종료 코드: {{code}})",logExecutionError:"Shell 명령 실행 오류: {{message}}",resultCommand:"명령: {{command}}",resultExitCode:"종료 코드: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"성공:",resultSuccessYes:"예",resultSuccessNo:"아니오",resultOutput:"출력:",resultError:"오류:"},init:{invalidType:'--type "{{value}}"이(가) 잘못되었습니다. 선택: {{choices}}',invalidLang:'--lang "{{value}}"이(가) 잘못되었습니다. 선택: {{choices}}',templatesDirNotFound:"템플릿 디렉터리를 찾을 수 없습니다: {{dir}}",createdPromptTemplates:"{{dir}} 생성됨 (프롬프트 템플릿)",createdSessions:"{{dir}} 생성됨 (세션 기록)",initialized:"{{targetDir}}에 {{type}} 프로젝트를 초기화했습니다",promptFilesIn:"프롬프트 파일: {{pithosaiDir}}, 세션 데이터: {{sessionsDir}}",runHint:'시작하려면 "pithosai -C {{targetDir}} \\"요청 내용\\""을 실행하세요.',createdFile:"{{path}} 생성됨",roleAlreadyAdded:"역할 {{role}}이(가) 이미 .pithosai에 있습니다; 건너뜁니다.",addedRoleTemplates:"{{dir}}에 역할 템플릿을 추가했습니다"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: 미리보기 종료 ({{source}})",skipped:"브라우저 미리보기 건너뜀 (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"markdown 또는 path 중 하나만 제공하세요.",errorEmpty:"Markdown 내용이 비어 있습니다.",errorFileOutside:"path는 프로젝트 디렉터리 안에 있어야 합니다.",errorNotAFile:"path가 일반 파일이 아닙니다.",errorFileTooLarge:"파일이 너무 큽니다 (최대 {{maxBytes}}바이트).",errorFileRead:"파일을 읽을 수 없습니다: {{message}}",sourceInline:"인라인 Markdown",sourceFile:"파일 {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"하트비트용 이메일을 비워 둘 수 없습니다. sqlite3 DB의 email_roles 테이블에서 역할 {{role}}의 이메일을 설정하세요.",loadedState:"SQLite에서 하트비트 상태를 불러왔습니다 (이메일 {{email}}, 역할 {{role}}). 상태: {{states}}",fetchFound:"하트비트 수신함 조회에서 새 작업 {{count}}건 발견: {{ids}}",savedState:"하트비트 상태를 SQLite에 저장했습니다 (이메일 {{email}}, 역할 {{role}})",mergedAndNext:"상태에 작업 {{merged}}건을 병합했습니다. 다음 처리 대상: {{stateSummary}}",replyEmailFailed:"하트비트 회신 메일 전송 실패: {{error}}",taskFailed:"하트비트 작업 실패: {{error}}",failureReplyEmailFailed:"하트비트 실패 알림 메일 전송 실패: {{error}}"},cli:{description:"Pithosai: 자연어 요청으로 코드나 프로젝트를 구현합니다. 역할 프롬프트는 런타임에 SQLite 데이터베이스에서 로드됩니다 (선택적으로 .pithosai/<role>/*.md로 폴백). 'pithosai init'으로 프로젝트를 생성합니다.",versionOption:"버전 출력",roleOption:"역할 (init용 템플릿 세트); 템플릿은 templates/<role>/에 있음",langOption:"프롬프트 및 init 템플릿 언어: en, zh (기본값: en)",interactiveModeOption:"요청 없이 대화형 모드로 진입; 모드 안내를 표시하고 입력 대기",initDescription:"새 프로젝트와 .pithosai/ 디렉토리 구조 생성. 역할 프롬프트는 런타임에 SQLite 데이터베이스에서 로드됩니다 (선택적으로 .pithosai/<role>/*.md로 폴백).",initTypeOption:"프로젝트 유형: js, ts, python",initExamples:"\n예:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"프로젝트의 .pithosai/<role>/에 역할 템플릿 추가",addRoleArgument:"추가할 역할 (예: PM, QA)",requestArgument:'구현할 내용 (예: "CSV를 JSON으로 변환하는 CLI"). 생략하면 도움말 표시.',cwdOption:"프로젝트 디렉터리 (기본값: 현재 디렉터리)",skillsDirOption:"read_skill용 스킬 디렉터리 (기본값: ./.pithosai/skills 또는 PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner(사고) 모델 사용; 기본값은 DeepSeek Coder",chatOption:"DeepSeek Chat 모델 사용 (일반 채팅, 코드 아님); 기본값은 DeepSeek Coder",cursorOption:"Cursor CLI 모델 사용 (cursor-agent login으로 인증, API 키 불필요). 선택적으로 모델 지정: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"에이전트 최대 실행 시간(초, 기본값: 1800). PITHOSAI_TIMEOUT_MS(ms)로 덮어쓸 수 있음.",interactiveOption:"대화형 프롬프트 비활성화 (기본값: 각 응답 후 다음 메시지 입력 요청)",modeOption:"실행 모드: agent(기본값, 도구 사용 가능), dialog(답변만, 도구 없음), plan(프로젝트 루트에 <slug>-plan.md만 작성, 도구 없음)",shellDisabledInMode:"dialog 및 plan 모드에서는 /shell 명령이 비활성화됩니다.",planWritten:"계획을 {{path}}에 저장했습니다",planRunning:"계획 생성 중…",waitingReply:"응답을 기다리는 중…",runningReply:"실행 중…",resultPreviewOpening:"브라우저에서 결과 미리보기를 여는 중…",resultPreviewTitle:"Pithosai 결과",resultPreviewFailed:"결과 미리보기를 열 수 없습니다: {{message}}",resultPreviewCopy:"Markdown 복사",resultPreviewClose:"닫기",resultPreviewCopied:"클립보드에 복사됨",resultPreviewTerminalHint:"↑↓ 또는 j/k \xb7 PgUp/PgDn 또는 Ctrl+U/Ctrl+D \xb7 Home/End 또는 gg/G \xb7 q/Esc로 닫기",runExamples:'\n예:\n pithosai "현재 시간을 반환하는 REST 엔드포인트 추가"\n pithosai -C ./my-app "테스트 실행 후 실패 수정"\n pithosai -i # 대화형 모드: 최신 세션 로드 후 요청 입력\n pithosai --no-interactive "한 번" # 한 번만 응답, 후속 프롬프트 없음\n pithosai --mode dialog "이 오류 설명"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"사용법:",helpArguments:"인수:",helpOptions:"옵션:",helpCommands:"명령:",helpGlobalOptions:"전역 옵션:",helpOption:"명령 도움말 표시",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"작업 파일을 감시하고 같은 프로세스에서 한 번에 하나씩 처리합니다",taskFileOption:"작업 Markdown 파일 경로(기본값: 프로젝트 루트의 prompts.md)",taskModelOption:"작업용 모델 키(deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"새 세션으로 시작(채팅 기록 없음)",taskExamples:"\n예:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"작업을 찾을 수 없음: {{taskId}}",taskAgentCompleted:"에이전트가 완료되었습니다.",taskAgentRunFailed:"에이전트 실행에 실패했습니다.",taskDone:"완료",taskFailed:"작업 실패: {{message}}",taskProcessingHeader:"--- 작업 처리 중 ---",taskLabelId:"id:",taskLabelTitle:"title:",taskLabelStatus:"status:",taskLabelDescription:"description:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"처리 중인 작업 {{id}}({{title}})에 대한 프로세서를 시작합니다.",taskNoPending:"대기 중인 작업이 없습니다.",taskPickedTask:"작업 {{id}}({{title}})을(를) 선택했습니다. 프로세서를 시작합니다.",taskProcessorFailed:"작업 프로세서 실패: {{message}}",taskWatcherRunning:"작업 감시기 실행 중. Ctrl+C로 종료.",memorizeDescription:"기간 내 역할이 참여한 작업(저장된 작업 메시지)을 요약해 .pithosai/<role>/memory.md에 씁니다.",memorizeStartOption:"시작: YYYY-MM-DD 또는 ISO 날짜시간",memorizeEndOption:"종료: YYYY-MM-DD 또는 ISO 날짜시간",memorizeRoleRequired:"역할이 필요합니다(-r/--role 또는 전역 --role).",memorizeWrote:"{{path}}에 기록했습니다(작업 {{count}}개).",memorizeNoTasks:"역할 {{role}}에 해당 기간 작업이 없습니다. {{path}}에 헤더만 썼습니다.",memorizeDateError:"날짜 범위가 잘못되었습니다: {{message}}",memorizeNoLlmOption:"LLM 요약 건너뛰기; 구조화된 메모리만 기록(PITHOSAI_MEMORIZE_SKIP_LLM=1과 동일).",memorizeLlmFallback:"LLM 요약 실패({{message}}); 요약 없이 구조화된 메모리를 기록했습니다.",memorizeExamples:"\n예:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"v1.0.4 등 레거시 평문 pithosai.db를 SQLCipher로 업그레이드합니다. 앱 런타임과 동일한 디바이스 바운드 키를 사용합니다(docs/device-id.md 참고). 여러 번 실행해도 안전합니다.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"요청에 맞는 셸 명령어 가져오기 (Ollama 전용, 명령어만 출력)",argument:"하고 싶은 작업 (예: 현재 디렉터리의 큰 파일 목록)",loading:"명령어 가져오는 중...",examples:'\n예:\n $ pithosai shell-tips 현재 디렉터리의 json 파일 목록\n $ pithosai shell-tips "모든 .js 파일에서 foo를 bar로 바꾸기"'},writer:{description:"요청에 맞는 텍스트 생성 (Ollama qwen2.5:14b)",argument:"쓸 내용 (예: 회의 거절 짧은 이메일)",loading:"작성 중...",examples:'\n예:\n $ pithosai writer 회의 거절 짧은 이메일\n $ pithosai writer "프로젝트 킥오프 세 가지 요점"'},skills:{installing:"스킬을 {{dir}}에 설치 중",fetchingList:"ClawHub에서 사용 가능한 스킬 가져오는 중...",fetchingIndex:"{{url}}에서 스킬 인덱스 가져오는 중",notFound:"스킬 '{{name}}'을(를) 찾을 수 없습니다",noSkillsAvailable:"ClawHub에서 사용 가능한 스킬이 없습니다",noSkillsFound:"스킬을 찾을 수 없습니다",downloadFailed:"스킬 '{{name}}' 다운로드 실패: {{error}}",installed:"스킬 '{{name}}' 설치 완료",complete:"설치 완료: {{count}} / {{total}} 스킬 설치됨",alreadyInstalled:"스킬 '{{name}}'이(가) 이미 설치됨 (재설치하려면 --force 사용)",downloading:"스킬 '{{name}}'을(를) {{url}}에서 다운로드 중",noSkillsDir:"스킬 디렉터리를 찾을 수 없습니다. 먼저 스킬을 설치하세요.",noSkillsInstalled:"설치된 스킬이 없습니다",installedList:"설치된 스킬 (총 {{count}}개) {{dir}} 내:",notInstalled:"스킬 '{{name}}'이(가) 설치되지 않았습니다",removed:"스킬 '{{name}}'을(를) 제거했습니다"},skillConvert:{welcome:"스킬 변환 시스템 - 성공적인 스킬을 영구 도구로 변환",listHeader:"스킬 변환 분석 ({{totalSkills}}개 스킬, {{totalExecutions}}회 실행)",noSuggestions:"변환 임계값 {{threshold}}을(를) 충족하는 스킬이 없습니다.",suggestedConversions:"변환 추천:",convertHint:"'pithosai skill-convert convert <스킬명>'을 사용하여 스킬을 변환하세요.",skillNotFound:"스킬 '{{skillName}}'을(를) 찾을 수 없거나 읽을 수 없습니다: {{error}}",alreadyConverted:"스킬 '{{skillName}}'은(는) 이미 도구로 변환되었습니다.",useForceHint:"--force를 사용하여 다시 변환하세요.",conversionReportHeader:"'{{skillName}}' 변환 보고서:",conversionScore:"변환 점수",suggestedType:"추천 유형",ready:"변환 준비 완료",estimatedBenefits:"예상 이점",performance:"성능 향상",reliability:"안정성 향상",usability:"사용성 향상",parameters:"매개변수",notReadyWarning:"이 스킬은 아직 자동 변환이 준비되지 않았습니다.",moreUsageHint:"스킬을 더 자주 사용하거나 --force를 사용하여 강제 변환하세요.",dryRunComplete:"시뮬레이션 실행 완료. 변경 사항이 없습니다.",confirmConversion:"'{{skillName}}'을(를) 영구 도구로 변환하시겠습니까?",conversionCancelled:"변환이 취소되었습니다.",converting:"'{{skillName}}'을(를) 도구로 변환 중...",conversionSuccess:"'{{skillName}}'을(를) '{{toolName}}'(으)로 성공적으로 변환했습니다.\n도구 저장 위치: {{toolPath}}",usageExample:"사용 예:",nextSteps:"다음 단계:",restartAgent:"새 도구를 로드하려면 에이전트를 재시작하세요",testTool:"도구 테스트: <도구명> --help",manageTools:"도구 관리: pithosai skill-convert tools",listError:"스킬 목록 조회 중 오류: {{error}}",conversionError:"'{{skillName}}' 변환 중 오류: {{error}}",skillStatsHeader:"'{{skillName}}' 통계:",generalStats:"일반 통계",totalExecutions:"총 실행 횟수",successful:"성공",failed:"실패",avgTime:"평균 실행 시간",lastUsed:"마지막 사용",recentExecutions:"최근 실행",commonParameters:"자주 쓰는 매개변수",overallStatsHeader:"전체 스킬 통계",overallStats:"전체 통계",totalSkillsTracked:"추적된 스킬 수",avgSuccessRate:"평균 성공률",topSkills:"사용량 상위 스킬",conversionSuggestions:"변환 추천",statsError:"통계 조회 중 오류: {{error}}",confirmClearAll:"모든 스킬 실행 기록을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",allRecordsCleared:"모든 스킬 실행 기록이 삭제되었습니다.",skillRecordsCleared:"'{{skillName}}'의 스킬 실행 기록이 삭제되었습니다.",clearCancelled:"삭제 작업이 취소되었습니다.",specifySkillOrAll:"스킬 이름을 지정하거나 --all을 사용하세요",clearError:"기록 삭제 중 오류: {{error}}",noConvertedTools:"변환된 도구가 없습니다.",convertedToolsHeader:"변환된 도구:",originalSkill:"원본 스킬",converted:"변환 일시",usageCount:"사용 횟수",toolsError:"도구 관리 중 오류: {{error}}",confirmRemoveTool:"도구 '{{toolName}}'을(를) 제거하시겠습니까?",toolRemoved:"도구 '{{toolName}}'이(가) 제거되었습니다.",toolRemoveFailed:"도구 '{{toolName}}' 제거 실패.",removeCancelled:"도구 제거가 취소되었습니다.",toolEnabled:"도구 '{{toolName}}'이(가) 활성화되었습니다.",toolEnableFailed:"도구 '{{toolName}}' 활성화 실패.",toolDisabled:"도구 '{{toolName}}'이(가) 비활성화되었습니다.",toolDisableFailed:"도구 '{{toolName}}' 비활성화 실패.",noStatsForSkill:"스킬 '{{skillName}}'의 통계를 찾을 수 없습니다."},hooks:{description:"디버깅, 보안 및 모니터링을 위한 에이전트 훅 관리",list:{description:"등록된 모든 훅 목록 표시",title:"\uD83D\uDCCB 등록된 훅",total:"총계: {{total}} 핸들러",options:{verbose:"상세 핸들러 정보 표시"},error:"훅 목록 표시 실패: {{error}}"},debug:{description:"에이전트 동작 모니터링을 위한 디버그 훅 활성화",options:{data:"디버그 출력에 전체 데이터 기록",performance:"성능 모니터링 훅 활성화",stats:"통계 수집 훅 활성화",all:"모든 디버그 훅 활성화"},added:{debug:"디버그 로그 훅을 추가했습니다",performance:"성능 모니터링 훅을 추가했습니다",stats:"통계 수집 훅을 추가했습니다",basic:"기본 디버그 훅을 추가했습니다"},success:"디버그 훅이 활성화되었습니다 ({{count}} 핸들러 등록됨)",error:"디버그 훅 활성화 실패: {{error}}"},security:{description:"접근 제어 및 모니터링을 위한 보안 훅 활성화",options:{block:"차단할 도구의 쉼표 구분 목록",maxPrompt:"최대 허용 프롬프트 길이 (기본값: 10000)"},success:"보안 훅이 활성화되었습니다",blockedTools:"차단된 도구: {{tools}}",maxPrompt:"최대 프롬프트 길이: {{length}} 문자",error:"보안 훅 활성화 실패: {{error}}"},clear:{description:"등록된 모든 훅 제거",success:"모든 훅이 제거되었습니다",error:"훅 제거 실패: {{error}}"},test:{description:"테스트 데이터로 훅을 트리거하여 테스트",argument:{hookType:"테스트할 특정 훅 유형 (선택사항)"},invalidType:"잘못된 훅 유형: {{type}}",triggered:"훅을 트리거했습니다: {{type}}",result:"결과: {{result}}",allTriggered:"모든 훅이 성공적으로 트리거되었습니다",error:"훅 테스트 실패: {{error}}"},register:{description:"파일에서 사용자 정의 훅 핸들러 등록",argument:{hookType:"핸들러를 등록할 훅 유형",handlerFile:"핸들러 파일 경로 (기본 함수를 내보내야 함)"},invalidType:"잘못된 훅 유형: {{type}}",invalidHandler:"핸들러 파일은 기본 함수를 내보내야 합니다",success:"{{file}}에서 {{type}}의 핸들러를 등록했습니다",error:"훅 등록 실패: {{error}}"},status:{description:"현재 훅 구성 및 통계 정보 표시",title:"\uD83D\uDCCB 훅 상태",error:"훅 상태 조회 실패: {{error}}"}}}},6150(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Basisvereiste",projectDir:"Projectmap (werk hier): {{cwd}}",skillsInstruction:"Gebruik het read_skill-hulpmiddel om de volledige instructies van een vaardigheid te laden wanneer de taak overeenkomt met de beschrijving.",toolArgSizeLimit:'Overschrijd nooit {{maxChars}} tekens in \xe9\xe9n tool-aanroepargument (bijv. de content van een write). De API kan grotere payloads afkappen en "Unterminated string in JSON"-fouten veroorzaken. Splits lange bestanden of scripts in meerdere write-aanroepen (bijv. per bestand of per stuk van onder {{maxChars}} tekens).',toolCallJsonFormat:'Tool-aanroepargumenten moeten geldige JSON zijn: elke sleutel en elke tekenreekswaarde tussen dubbele aanhalingstekens. Voorbeeld voor write: {"path": "bestand.md", "content": "inhoud hier"}. Laat geen aanhalingstekens weg bij sleutels of waarden (bijv. path: bestand.md is ongeldig).'},errors:{missingPromptFiles:"ontbrekende vereiste promptbestanden in {{dir}}:",runInit:"Voer 'pithosai init' uit in de projectroot om .pithosai met sjablonen aan te maken.",noApiKey:"Geen API-sleutel gevonden. Stel DEEPSEEK_API_KEY of OPENROUTER_API_KEY in.",ollamaNotConfigured:"Ollama is niet geconfigureerd. Stel OPENAI_LOCAL_API_BASE in of gebruik een project met lokaal model.",noValidTemplateFiles:"geen geldige sjabloonbestanden in {{dir}}. Verwacht *-<lang>.md (bijv. IDENTITY-ja.md). Voer 'pithosai init' uit om .pithosai met sjablonen aan te maken.",runTimeout:"Agent-run timeout na {{seconds}} seconden. Gebruik --timeout <seconden> of PITHOSAI_TIMEOUT_MS om aan te passen.",agentRunFailed:"Uitvoering mislukt: {{message}}",unknownRunError:"Onbekende fout"},warnings:{sessionAppend:"sessie toevoegen: {{message}}",apiRetry:"API-fout bij poging {{attempt}}/{{max}}; opnieuw proberen..."},reasoner:{thinkingHeader:"\n--- Denken:\n",replyHeader:"\n\n--- Antwoord:\n"},run:{cwd:"cwd {{cwd}}",request:"verzoek: {{request}}",interactivePrompt:"Jij: ",tuiYouLabel:"Jij:",interactiveExitHint:"Beantwoord of voer een nieuw verzoek in (typ 'exit' of 'quit' om de CLI te verlaten).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Interactieve modus — Agent (volledige tools) ---",interactiveModeAgentTips:"- Volledige toolset (lezen, schrijven, uitvoeren, afhankelijk van configuratie).\n- Beurten worden per taak in de lokale database opgeslagen.\n- `/new` wijst een nieuwe taak-id toe; eerdere berichten worden niet geladen.\n- `/shell <commando>` voor shell; `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken.\n- `/list-skill`, `/install-skill` en `/remove-skill` komen overeen met `pithosai skills list|install|remove` (ClawHub). Ctrl+S stopt, Ctrl+P pauzeert.",interactiveModeDialogTitle:"--- Interactieve modus — Dialoog (alleen-lezen Q&A) ---",interactiveModeDialogTips:"- Alleen read-only tools (geen shell, geen bestandsbewerking of opdrachten).\n- Beurten worden per taak in de lokale database opgeslagen.\n- `/new` wijst een nieuwe taak-id toe; eerdere berichten worden niet geladen.\n- `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken.\n- `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub), zoals de `pithosai skills`-CLI.",interactiveModePlanTitle:"--- Planmodus ---",interactiveModePlanTips:"- Elk antwoord wordt weggeschreven naar `<slug>-plan.md` in de projectmap (de eerste regel van het verzoek be\xefnvloedt de bestandsnaam).\n- Alleen read-only tools; shell en muterende tools uitgeschakeld.\n- `/new` wijst een nieuwe taak-id toe.\n- `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken.\n- `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub), zoals de `pithosai skills`-CLI.\n- Na elke run kunt u verdergaan met een nieuw planverzoek bij de prompt (zoals agent/dialog).",list:{noPersistedTasks:"Geen opgeslagen taken gevonden.",createTasksFirstHint:"Maak eerst taken aan met `pithosai task`.",persistedTasksHeader:"--- Opgeslagen taken ({{count}}) ---",selectTaskHint:"Gebruik `/select <index>` om een taak uit te voeren.",noTasksCached:"Geen taken in cache. Voer eerst `/list` uit.",invalidIndex:"Ongeldige index {{index}}. Geldig bereik: 0-{{maxIndex}}.",selectUsage:"Gebruik: /select <index>",selectedTask:"Taak #{{index}} geselecteerd."},skillSlash:{installUsage:"Gebruik: /install-skill [--force] [skill-naam]",removeUsage:"Gebruik: /remove-skill <skill-naam>",listNoExtra:"/list-skill accepteert geen argumenten.",failed:"Skill-opdracht mislukt: {{message}}"},show:{title:"Huidige taak",field:"Veld",value:"Waarde",taskId:"taskId",mode:"modus",model:"model",status:"status",messageCount:"aantalBerichten",usageInput:"gebruik.invoer",usageOutput:"gebruik.uitvoer",usageCacheRead:"gebruik.cacheLezen",usageCacheWrite:"gebruik.cacheSchrijven",usageTotalTokens:"gebruik.totaalTokens"},showTask:{title:"Taak Q&A",taskIdLabel:"Taak-ID",turnHeading:"Beurt {{index}}",questionLabel:"Vraag",answerLabel:"Antwoord",createdLabel:"Aangemaakt",emptyQuestion:"(lege vraag)",emptyAnswer:"(nog geen assistenttekst)",emptyNoMessages:"Nog geen gebruikersberichten voor deze taak.",previewDocumentTitle:"Taak Q&A"},showPrompt:{previewDocumentTitle:"Systeemprompt",previewHeading:"Systeemprompt"},shellHint:"Gebruik '/shell <commando>' om shell-commando's uit te voeren (bijvoorbeeld: '/shell ls -la').",replIntroDialog:"Dialoogmodus: alleen lezen — `/shell` uit. `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken. `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub).",replIntroPlan:"Planmodus: elk antwoord naar `<slug>-plan.md` (eerste regel be\xefnvloedt de naam). `/shell` uit; minimale uitvoer tot klaar. `/list`, `/select`, `/show`, `/show-task` en `/show-prompt` voor persistente taken. `/list-skill`, `/install-skill` en `/remove-skill` beheren skills (ClawHub).",newSessionHint:"Gebruik '/new <verzoek>' om een nieuwe sessie te starten (zonder chatgeschiedenis).",newSessionNoHistory:"Nieuwe sessie in gebruik (zonder chatgeschiedenis).",controlHint:"Druk op Ctrl+S om de lopende agent te stoppen, Ctrl+P om te pauzeren en subopdrachten in te voeren.",replTabCompletionHint:"Tab om slash-commando's aan te vullen (bijv. /list, /list-skill, /show) of exit/quit.",tuiScrollTranscriptHint:"In de terminal-UI: muiswiel, pijltjes, Page Up/Down, Ctrl+U/Ctrl+F (pagina). Ctrl+U/F scrollen het logboek. Ctrl+D blijft EOF/afsluiten bij lege regel of vooruit wissen tijdens typen.",agentStopped:"Agent gestopt.",pauseHeader:"--- Agent gepauzeerd ---",pauseCurrentRequest:"Huidig verzoek: {{request}}",pauseHelp:"Opdrachten: 'continue' of 'c' om door te gaan, 'exit' of 'e' om af te sluiten, of typ een nieuw verzoek om het huidige te vervangen.",pausePrompt:"[gepauzeerd] ",pauseRequestUpdated:"Verzoek bijgewerkt naar: {{request}}"},shell:{noCommand:"Geen commando opgegeven na /shell-voorvoegsel. Gebruik: /shell <commando>",executionError:"Fout bij het uitvoeren van shell-commando: {{error}}",executing:"[shell] Uitvoeren: {{command}}",errorNoCommand:"Geen commando opgegeven na /shell-voorvoegsel.",errorSpawnFailed:"Proces starten mislukt: {{message}}",errorTimedOut:"Commando verlopen na {{seconds}} seconden",logFailed:"Shell-commando mislukt: {{command}} (afsluitcode: {{code}})",logExecutionError:"Shell-commando uitvoeringsfout: {{message}}",resultCommand:"Commando: {{command}}",resultExitCode:"Afsluitcode: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Geslaagd:",resultSuccessYes:"Ja",resultSuccessNo:"Nee",resultOutput:"Uitvoer:",resultError:"Fout:"},init:{invalidType:'ongeldige --type "{{value}}"; kies: {{choices}}',invalidLang:'ongeldige --lang "{{value}}"; kies: {{choices}}',templatesDirNotFound:"sjablonenmap niet gevonden: {{dir}}",createdPromptTemplates:"{{dir}} aangemaakt (prompt-sjablonen)",createdSessions:"{{dir}} aangemaakt (sessiegeschiedenis)",initialized:"{{type}}-project ge\xefnitialiseerd in {{targetDir}}",promptFilesIn:"promptbestanden in {{pithosaiDir}}, sessiedata in {{sessionsDir}}",runHint:'voer "pithosai -C {{targetDir}} \\"jouw verzoek\\"" uit om te starten.',createdFile:"{{path}} aangemaakt",roleAlreadyAdded:"rol {{role}} staat al in .pithosai; overslaan.",addedRoleTemplates:"rolsjablonen toegevoegd aan {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: voorbeeld gesloten ({{source}})",skipped:"Browservoorbeeld overgeslagen (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Geef precies markdown of path op (niet beide, niet geen).",errorEmpty:"Markdown-inhoud is leeg.",errorFileOutside:"path moet binnen de projectmap blijven.",errorNotAFile:"path is geen gewoon bestand.",errorFileTooLarge:"Bestand is groter dan {{maxBytes}} bytes.",errorFileRead:"Bestand lezen mislukt: {{message}}",sourceInline:"inline Markdown",sourceFile:"bestand {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"E-mail mag niet leeg zijn voor heartbeat. Configureer e-mail voor rol {{role}} in de email_roles-tabel in de sqlite3-database.",loadedState:"Heartbeat-status geladen uit SQLite voor e-mail {{email}} en rol {{role}}, statussen: {{states}}",fetchFound:"Heartbeat-inbox ophalen vond {{count}} nieuwe taken: {{ids}}",savedState:"Heartbeat-status opgeslagen in SQLite voor e-mail {{email}} en rol {{role}}",mergedAndNext:"{{merged}} taken samengevoegd in status, volgende om te verwerken: {{stateSummary}}",replyEmailFailed:"Heartbeat-antwoordmail verzenden mislukt: {{error}}",taskFailed:"Heartbeat-taak mislukt: {{error}}",failureReplyEmailFailed:"Heartbeat-foutmelding-mail verzenden mislukt: {{error}}"},cli:{description:"Pithosai: implementeert code of projecten vanuit een verzoek in natuurlijke taal. Rolprompts worden tijdens runtime geladen vanuit de SQLite-database (met optionele fallback naar .pithosai/<role>/*.md). Maak een project met 'pithosai init'.",versionOption:"versie tonen",roleOption:"rol (sjabloonset voor init); sjablonen in templates/<role>/",langOption:"taal voor prompts en init-sjablonen: en, zh (standaard: en)",interactiveModeOption:"interactieve modus starten zonder verzoek; modustips tonen en om invoer vragen",initDescription:"Nieuw project en .pithosai/ directorystructuur aanmaken. Rolprompts worden tijdens runtime geladen vanuit de SQLite-database (met optionele fallback naar .pithosai/<role>/*.md).",initTypeOption:"projecttype: js, ts of python",initExamples:"\nVoorbeelden:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Rolsjablonen toevoegen aan .pithosai/<role>/ in het project",addRoleArgument:"rol om toe te voegen (bijv. PM, QA)",requestArgument:'wat te bouwen (bijv. "Een CLI die CSV naar JSON converteert"). Weglaten toont help.',cwdOption:"projectmap (standaard: huidige map)",skillsDirOption:"vaardighedenmap voor read_skill (standaard: ./.pithosai/skills of PITHOSAI_SKILLS_DIR)",reasonerOption:"DeepSeek Reasoner (denken)-model gebruiken; standaard is DeepSeek Coder",chatOption:"DeepSeek Chat-model gebruiken (algemene chat, geen code); standaard is DeepSeek Coder",cursorOption:"Cursor CLI-model gebruiken (auth via cursor-agent login, geen API-sleutel nodig). Optioneel model opgeven: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"max. agent-runtijd in seconden (standaard: 1800). Overschrijven met PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"interactieve prompt uitschakelen (standaard: na elk antwoord om volgende bericht vragen)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Plan genereren…",waitingReply:"Wachten op antwoord…",runningReply:"Bezig met uitvoeren…",resultPreviewOpening:"Voorbeeld openen in de browser…",resultPreviewTitle:"Pithosai-resultaat",resultPreviewFailed:"Voorbeeld openen mislukt: {{message}}",resultPreviewCopy:"Markdown kopi\xebren",resultPreviewClose:"Sluiten",resultPreviewCopied:"Gekopieerd naar klembord",resultPreviewTerminalHint:"↑↓ of j/k \xb7 PgUp/PgDn of Ctrl+U/Ctrl+D \xb7 Home/End of gg/G \xb7 q/Esc sluiten",runExamples:'\nVoorbeelden:\n pithosai "Voeg een REST-endpoint toe die de huidige tijd teruggeeft"\n pithosai -C ./my-app "Tests uitvoeren en fouten herstellen"\n pithosai -i # interactieve modus: laatste sessie laden, dan om verzoeken vragen\n pithosai --no-interactive "Een keer" # \xe9\xe9n antwoord, geen vervolgvraag\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Gebruik:",helpArguments:"Argumenten:",helpOptions:"Opties:",helpCommands:"Commando's:",helpGlobalOptions:"Globale opties:",helpOption:"help voor commando tonen",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Bewaak het takenbestand en verwerk taken \xe9\xe9n voor \xe9\xe9n in hetzelfde proces",taskFileOption:"Pad naar taken-Markdown (standaard: prompts.md in projectroot)",taskModelOption:"Modelcode voor de taak (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Starten met nieuwe sessie (geen chatgeschiedenis)",taskExamples:"\nVoorbeelden:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Taak niet gevonden: {{taskId}}",taskAgentCompleted:"Agent voltooid.",taskAgentRunFailed:"Agentrun mislukt.",taskDone:"Klaar",taskFailed:"Taak mislukt: {{message}}",taskProcessingHeader:"--- Taak verwerken ---",taskLabelId:"id:",taskLabelTitle:"titel:",taskLabelStatus:"status:",taskLabelDescription:"beschrijving:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"Processor starten voor lopende taak {{id}} ({{title}}).",taskNoPending:"Geen openstaande taken.",taskPickedTask:"Taak {{id}} ({{title}}) gekozen; processor starten.",taskProcessorFailed:"Taakprocessor mislukt: {{message}}",taskWatcherRunning:"Taakwatcher actief. Ctrl+C om te stoppen.",memorizeDescription:"Schrijft .pithosai/<role>/memory.md met samenvattingen van taken waaraan de rol deelnam (persistente taakberichten in het bereik).",memorizeStartOption:"Start bereik: YYYY-MM-DD of ISO-datum/tijd",memorizeEndOption:"Einde bereik: YYYY-MM-DD of ISO-datum/tijd",memorizeRoleRequired:"Rol is verplicht (-r/--role of globale --role).",memorizeWrote:"Geschreven: {{path}} ({{count}} taak/taken).",memorizeNoTasks:"Geen taken in bereik voor rol {{role}}; alleen kop naar {{path}}.",memorizeDateError:"Ongeldig datumbereik: {{message}}",memorizeNoLlmOption:"LLM-samenvatting overslaan; alleen gestructureerd geheugen schrijven (zelfde als PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"LLM-samenvatting mislukt ({{message}}); gestructureerd geheugen zonder samenvatting geschreven.",memorizeExamples:"\nVoorbeelden:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Krijg shell-commando's voor een verzoek (alleen Ollama)",argument:"Wat je wilt doen (bijv. grote bestanden in huidige map lijsten)",loading:"Commando's ophalen...",examples:'\nVoorbeelden:\n $ pithosai shell-tips lijst json-bestanden in huidige map\n $ pithosai shell-tips "vind en vervang foo door bar in alle .js"'},writer:{description:"Genereer tekst voor een verzoek (Ollama qwen2.5:14b)",argument:"Wat te schrijven (bijv. korte e-mail om meeting af te zeggen)",loading:"Schrijven...",examples:'\nVoorbeelden:\n $ pithosai writer korte e-mail meeting afzeggen\n $ pithosai writer "drie bulletpoints voor project kickoff"'},skills:{installing:"Vaardigheden installeren in {{dir}}",fetchingList:"Beschikbare vaardigheden ophalen van ClawHub...",fetchingIndex:"Vaardighedenindex ophalen van {{url}}",notFound:"Vaardigheid '{{name}}' niet gevonden",noSkillsAvailable:"Geen vaardigheden beschikbaar van ClawHub",noSkillsFound:"Geen vaardigheden gevonden",downloadFailed:"Downloaden van vaardigheid '{{name}}' mislukt: {{error}}",installed:"Vaardigheid '{{name}}' ge\xefnstalleerd",complete:"Installatie voltooid: {{count}} van {{total}} vaardigheden ge\xefnstalleerd",alreadyInstalled:"Vaardigheid '{{name}}' al ge\xefnstalleerd (gebruik --force om opnieuw te installeren)",downloading:"Vaardigheid '{{name}}' downloaden van {{url}}",noSkillsDir:"Geen vaardighedenmap gevonden. Installeer eerst vaardigheden.",noSkillsInstalled:"Geen vaardigheden ge\xefnstalleerd",installedList:"Ge\xefnstalleerde vaardigheden ({{count}} totaal) in {{dir}}:",notInstalled:"Vaardigheid '{{name}}' is niet ge\xefnstalleerd",removed:"Vaardigheid '{{name}}' verwijderd"},skillConvert:{welcome:"Vaardigheden-conversiesysteem - Succesvolle vaardigheden omzetten naar permanente tools",listHeader:"Vaardigheden-conversieanalyse ({{totalSkills}} vaardigheden, {{totalExecutions}} uitvoeringen)",noSuggestions:"Geen vaardigheden bereiken de conversiedrempel van {{threshold}}.",suggestedConversions:"Voorgestelde conversies:",convertHint:"Gebruik 'pithosai skill-convert convert <vaardigheidsnaam>' om een vaardigheid te converteren.",skillNotFound:"Vaardigheid '{{skillName}}' niet gevonden of niet leesbaar: {{error}}",alreadyConverted:"Vaardigheid '{{skillName}}' is al geconverteerd naar een tool.",useForceHint:"Gebruik --force om opnieuw te converteren.",conversionReportHeader:"Conversierapport voor '{{skillName}}':",conversionScore:"Conversiescore",suggestedType:"Voorgesteld type",ready:"Klaar voor conversie",estimatedBenefits:"Geschatte voordelen",performance:"Prestatieverbetering",reliability:"Betrouwbaarheidsverbetering",usability:"Gebruiksvriendelijkheidsverbetering",parameters:"Parameters",notReadyWarning:"Deze vaardigheid is niet klaar voor automatische conversie.",moreUsageHint:"Gebruik de vaardigheid vaker of gebruik --force om conversie te forceren.",dryRunComplete:"Proefrun voltooid. Geen wijzigingen aangebracht.",confirmConversion:"'{{skillName}}' converteren naar een permanent tool?",conversionCancelled:"Conversie geannuleerd.",converting:"'{{skillName}}' wordt geconverteerd naar tool...",conversionSuccess:"'{{skillName}}' succesvol geconverteerd naar '{{toolName}}'.\nTool opgeslagen in: {{toolPath}}",usageExample:"Gebruiksvoorbeeld:",nextSteps:"Volgende stappen:",restartAgent:"Herstart de agent om het nieuwe tool te laden",testTool:"Tool testen: <toolnaam> --help",manageTools:"Tools beheren: pithosai skill-convert tools",listError:"Fout bij het oplijsten van vaardigheden: {{error}}",conversionError:"Fout bij het converteren van '{{skillName}}': {{error}}",skillStatsHeader:"Statistieken voor '{{skillName}}':",generalStats:"Algemene statistieken",totalExecutions:"Totaal uitvoeringen",successful:"Geslaagd",failed:"Mislukt",avgTime:"Gemiddelde uitvoeringstijd",lastUsed:"Laatst gebruikt",recentExecutions:"Recente uitvoeringen",commonParameters:"Veelgebruikte parameters",overallStatsHeader:"Totale vaardighedenstatistieken",overallStats:"Totale statistieken",totalSkillsTracked:"Totaal bijgehouden vaardigheden",avgSuccessRate:"Gemiddeld slagingspercentage",topSkills:"Meest gebruikte vaardigheden",conversionSuggestions:"Conversiesuggesties",statsError:"Fout bij het ophalen van statistieken: {{error}}",confirmClearAll:"ALLE uitvoeringsrecords van vaardigheden wissen? Dit kan niet ongedaan worden gemaakt.",allRecordsCleared:"Alle uitvoeringsrecords van vaardigheden zijn gewist.",skillRecordsCleared:"Uitvoeringsrecords van '{{skillName}}' zijn gewist.",clearCancelled:"Wisbewerking geannuleerd.",specifySkillOrAll:"Geef een vaardigheidsnaam op of gebruik --all",clearError:"Fout bij het wissen van records: {{error}}",noConvertedTools:"Geen geconverteerde tools gevonden.",convertedToolsHeader:"Geconverteerde tools:",originalSkill:"Oorspronkelijke vaardigheid",converted:"Geconverteerd op",usageCount:"Gebruiksaantal",toolsError:"Fout bij het beheren van tools: {{error}}",confirmRemoveTool:"Tool '{{toolName}}' verwijderen?",toolRemoved:"Tool '{{toolName}}' verwijderd.",toolRemoveFailed:"Verwijderen van tool '{{toolName}}' mislukt.",removeCancelled:"Toolverwijdering geannuleerd.",toolEnabled:"Tool '{{toolName}}' ingeschakeld.",toolEnableFailed:"Inschakelen van tool '{{toolName}}' mislukt.",toolDisabled:"Tool '{{toolName}}' uitgeschakeld.",toolDisableFailed:"Uitschakelen van tool '{{toolName}}' mislukt.",noStatsForSkill:"Geen statistieken gevonden voor vaardigheid '{{skillName}}'."},hooks:{description:"Agent-hooks beheren voor debugging, beveiliging en monitoring",list:{description:"Alle geregistreerde hooks weergeven",title:"\uD83D\uDCCB Geregistreerde hooks",total:"Totaal: {{total}} handlers",options:{verbose:"Gedetailleerde handler-informatie weergeven"},error:"Kan hooks niet weergeven: {{error}}"},debug:{description:"Debug-hooks inschakelen om het gedrag van de agent te monitoren",options:{data:"Volledige gegevens loggen in debug-uitvoer",performance:"Prestatie-monitoring-hooks inschakelen",stats:"Statistiekverzamelings-hooks inschakelen",all:"Alle debug-hooks inschakelen"},added:{debug:"Debug-logging-hooks toegevoegd",performance:"Prestatie-monitoring-hooks toegevoegd",stats:"Statistiekverzamelings-hooks toegevoegd",basic:"Basis debug-hooks toegevoegd"},success:"Debug-hooks ingeschakeld ({{count}} handlers geregistreerd)",error:"Kan debug-hooks niet inschakelen: {{error}}"},security:{description:"Beveiligingshooks inschakelen voor toegangscontrole en monitoring",options:{block:"Kommagescheiden lijst van te blokkeren tools",maxPrompt:"Maximale toegestane promptlengte (standaard: 10000)"},success:"Beveiligingshooks ingeschakeld",blockedTools:"Geblokkeerde tools: {{tools}}",maxPrompt:"Maximale promptlengte: {{length}} tekens",error:"Kan beveiligingshooks niet inschakelen: {{error}}"},clear:{description:"Alle geregistreerde hooks wissen",success:"Alle hooks gewist",error:"Kan hooks niet wissen: {{error}}"},test:{description:"Hooks testen door ze te activeren met testgegevens",argument:{hookType:"Specifiek hook-type om te testen (optioneel)"},invalidType:"Ongeldig hook-type: {{type}}",triggered:"Hook geactiveerd: {{type}}",result:"Resultaat: {{result}}",allTriggered:"Alle hooks succesvol geactiveerd",error:"Kan hooks niet testen: {{error}}"},register:{description:"Aangepaste hook-handler registreren vanuit een bestand",argument:{hookType:"Hook-type om de handler voor te registreren",handlerFile:"Pad naar handler-bestand (moet een standaardfunctie exporteren)"},invalidType:"Ongeldig hook-type: {{type}}",invalidHandler:"Handler-bestand moet een standaardfunctie exporteren",success:"Handler voor {{type}} geregistreerd vanuit {{file}}",error:"Kan hook niet registreren: {{error}}"},status:{description:"Huidige hook-configuratie en statistieken weergeven",title:"\uD83D\uDCCB Hook-status",error:"Kan hook-status niet ophalen: {{error}}"}}}},8112(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"Requisito base",projectDir:"Diret\xf3rio do projeto (trabalhar aqui): {{cwd}}",skillsInstruction:"Use a ferramenta read_skill para carregar as instru\xe7\xf5es completas de uma habilidade quando a tarefa corresponder \xe0 sua descri\xe7\xe3o.",toolArgSizeLimit:"Nunca exceda {{maxChars}} caracteres num \xfanico argumento de chamada a ferramenta (ex.: o content de um write). A API pode truncar payloads maiores e causar erros \xabUnterminated string in JSON\xbb. Para ficheiros ou scripts longos, divida em v\xe1rias chamadas write (por ficheiro ou por bloco de menos de {{maxChars}} caracteres).",toolCallJsonFormat:'Os argumentos de chamada a ferramenta devem ser JSON v\xe1lido: cada chave e cada valor de cadeia entre aspas duplas. Exemplo para write: {"path": "ficheiro.md", "content": "conte\xfado aqui"}. N\xe3o omita aspas em chaves ou valores (ex.: path: ficheiro.md \xe9 inv\xe1lido).'},errors:{missingPromptFiles:"arquivos de prompt obrigat\xf3rios em falta em {{dir}}:",runInit:"Execute 'pithosai init' na raiz do projeto para criar .pithosai com os modelos.",noApiKey:"Chave API n\xe3o encontrada. Defina DEEPSEEK_API_KEY ou OPENROUTER_API_KEY.",ollamaNotConfigured:"Ollama n\xe3o configurado. Defina OPENAI_LOCAL_API_BASE ou use um projeto com modelo local.",noValidTemplateFiles:"nenhum ficheiro de modelo v\xe1lido em {{dir}}. Esperado *-<lang>.md (ex.: IDENTITY-ja.md). Execute 'pithosai init' para criar .pithosai com os modelos.",runTimeout:"Execu\xe7\xe3o do agente expirou ap\xf3s {{seconds}} segundos. Use --timeout <segundos> ou PITHOSAI_TIMEOUT_MS para ajustar.",agentRunFailed:"Falha na execu\xe7\xe3o: {{message}}",unknownRunError:"Erro desconhecido"},warnings:{sessionAppend:"anexar sess\xe3o: {{message}}",apiRetry:"Erro de API na tentativa {{attempt}}/{{max}}; a tentar de novo..."},reasoner:{thinkingHeader:"\n--- Pensamento:\n",replyHeader:"\n\n--- Resposta:\n"},run:{cwd:"cwd {{cwd}}",request:"pedido: {{request}}",interactivePrompt:"Voc\xea: ",tuiYouLabel:"Voc\xea:",interactiveExitHint:"Responda ou insira um novo pedido (digite 'exit' ou 'quit' para sair da CLI).",interactiveModeCwd:"CWD: {{cwd}}",interactiveModeAgentTitle:"--- Modo interativo — Agente (ferramentas completas) ---",interactiveModeAgentTips:"- Conjunto completo de ferramentas (leitura, escrita, execu\xe7\xe3o, conforme configura\xe7\xe3o).\n- As mensagens s\xe3o guardadas por tarefa na base de dados local.\n- `/new` atribui um novo id de tarefa; mensagens anteriores n\xe3o s\xe3o carregadas.\n- `/shell <comando>` para shell; `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas.\n- `/list-skill`, `/install-skill` e `/remove-skill` equivalem a `pithosai skills list|install|remove` (ClawHub). Ctrl+S para, Ctrl+P pausa.",interactiveModeDialogTitle:"--- Modo interativo — Di\xe1logo (Q&A s\xf3 de leitura) ---",interactiveModeDialogTips:"- Apenas ferramentas de leitura (sem shell, edi\xe7\xe3o de ficheiros ou execu\xe7\xe3o de comandos).\n- As mensagens s\xe3o guardadas por tarefa na base de dados local.\n- `/new` atribui um novo id de tarefa; mensagens anteriores n\xe3o s\xe3o carregadas.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas.\n- `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub) como a CLI `pithosai skills`.",interactiveModePlanTitle:"--- Modo plano ---",interactiveModePlanTips:"- Cada resposta \xe9 escrita em `<slug>-plan.md` no diret\xf3rio do projeto (a primeira linha do pedido influencia o nome).\n- Apenas ferramentas de leitura; shell e ferramentas mutadoras desativadas.\n- `/new` atribui um novo id de tarefa.\n- `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas.\n- `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub) como a CLI `pithosai skills`.\n- Ap\xf3s cada execu\xe7\xe3o pode continuar com outro pedido de plano no prompt (como agent/dialog).",list:{noPersistedTasks:"Nenhuma tarefa persistida encontrada.",createTasksFirstHint:"Crie tarefas primeiro usando `pithosai task`.",persistedTasksHeader:"--- Tarefas persistidas ({{count}}) ---",selectTaskHint:"Use `/select <index>` para executar uma tarefa.",noTasksCached:"Nenhuma tarefa em cache. Execute `/list` primeiro.",invalidIndex:"\xcdndice inv\xe1lido {{index}}. Intervalo v\xe1lido: 0-{{maxIndex}}.",selectUsage:"Uso: /select <index>",selectedTask:"Tarefa #{{index}} selecionada."},skillSlash:{installUsage:"Uso: /install-skill [--force] [nome-da-skill]",removeUsage:"Uso: /remove-skill <nome-da-skill>",listNoExtra:"/list-skill n\xe3o aceita argumentos.",failed:"Comando de skill falhou: {{message}}"},show:{title:"Tarefa atual",field:"Campo",value:"Valor",taskId:"taskId",mode:"modo",model:"modelo",status:"status",messageCount:"quantidadeMensagens",usageInput:"uso.entrada",usageOutput:"uso.sa\xedda",usageCacheRead:"uso.cacheLeitura",usageCacheWrite:"uso.cacheEscrita",usageTotalTokens:"uso.totalTokens"},showTask:{title:"P&R da tarefa",taskIdLabel:"ID da tarefa",turnHeading:"Turno {{index}}",questionLabel:"Pergunta",answerLabel:"Resposta",createdLabel:"Criado",emptyQuestion:"(pergunta vazia)",emptyAnswer:"(sem resposta em texto do assistente)",emptyNoMessages:"Ainda n\xe3o h\xe1 mensagens de utilizador para esta tarefa.",previewDocumentTitle:"P&R da tarefa"},showPrompt:{previewDocumentTitle:"Prompt do sistema",previewHeading:"Prompt do sistema"},shellHint:"Use '/shell <comando>' para executar comandos shell (exemplo: '/shell ls -la').",replIntroDialog:"Modo di\xe1logo: apenas leitura — `/shell` desativado. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas. `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub).",replIntroPlan:"Modo plano: cada resposta em `<slug>-plan.md` (primeira linha influencia o nome). `/shell` desativado; sa\xedda m\xednima at\xe9 concluir. `/list`, `/select`, `/show`, `/show-task` e `/show-prompt` para tarefas persistidas. `/list-skill`, `/install-skill` e `/remove-skill` gerem skills (ClawHub).",newSessionHint:"Use '/new <pedido>' para iniciar uma nova sess\xe3o (sem hist\xf3rico de chat).",newSessionNoHistory:"A usar nova sess\xe3o (sem hist\xf3rico de chat).",controlHint:"Pressione Ctrl+S para parar o agente em execu\xe7\xe3o, Ctrl+P para pausar e entrar em subcomandos.",replTabCompletionHint:"Tab para completar comandos com barra (ex.: /list, /list-skill, /show) ou exit/quit.",tuiScrollTranscriptHint:"Na UI do terminal: roda, setas, PgUp/PgDn, Ctrl+U/Ctrl+F (p\xe1gina). Ctrl+U/F rolam o hist\xf3rico. Ctrl+D continua como EOF/sair com linha vazia ou apagar \xe0 frente ao digitar.",agentStopped:"Agente parado.",pauseHeader:"--- Agente em pausa ---",pauseCurrentRequest:"Pedido atual: {{request}}",pauseHelp:"Comandos: 'continue' ou 'c' para continuar, 'exit' ou 'e' para sair, ou digite um novo pedido para substituir o atual.",pausePrompt:"[em pausa] ",pauseRequestUpdated:"Pedido atualizado para: {{request}}"},shell:{noCommand:"Nenhum comando fornecido ap\xf3s o prefixo /shell. Uso: /shell <comando>",executionError:"Erro ao executar comando shell: {{error}}",executing:"[shell] Executando: {{command}}",errorNoCommand:"Nenhum comando fornecido ap\xf3s o prefixo /shell.",errorSpawnFailed:"Falha ao iniciar o processo: {{message}}",errorTimedOut:"Comando expirou ap\xf3s {{seconds}} segundos",logFailed:"Comando shell falhou: {{command}} (c\xf3digo de sa\xedda: {{code}})",logExecutionError:"Erro de execu\xe7\xe3o do comando shell: {{message}}",resultCommand:"Comando: {{command}}",resultExitCode:"C\xf3digo de sa\xedda: {{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"Sucesso:",resultSuccessYes:"Sim",resultSuccessNo:"N\xe3o",resultOutput:"Sa\xedda:",resultError:"Erro:"},init:{invalidType:'--type inv\xe1lido "{{value}}"; escolha: {{choices}}',invalidLang:'--lang inv\xe1lido "{{value}}"; escolha: {{choices}}',templatesDirNotFound:"diret\xf3rio de modelos n\xe3o encontrado: {{dir}}",createdPromptTemplates:"criado {{dir}} (modelos de prompt)",createdSessions:"criado {{dir}} (hist\xf3rico de sess\xf5es)",initialized:"projeto {{type}} inicializado em {{targetDir}}",promptFilesIn:"ficheiros de prompt em {{pithosaiDir}}, dados de sess\xe3o em {{sessionsDir}}",runHint:'execute "pithosai -C {{targetDir}} \\"seu pedido\\"" para come\xe7ar.',createdFile:"criado {{path}}",roleAlreadyAdded:"papel {{role}} j\xe1 presente em .pithosai; a ignorar.",addedRoleTemplates:"modelos de papel adicionados a {{dir}}"},tools:{listFiles:{result:"list_files: listed {{count}} entries in {{path}}"},playwrightView:{result:"playwright_view_markdown: pr\xe9-visualiza\xe7\xe3o fechada ({{source}})",skipped:"Pr\xe9-visualiza\xe7\xe3o do navegador ignorada (PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"Forne\xe7a exatamente markdown ou path (n\xe3o ambos, nem nenhum).",errorEmpty:"O conte\xfado Markdown est\xe1 vazio.",errorFileOutside:"path deve ficar dentro do diret\xf3rio do projeto.",errorNotAFile:"path n\xe3o \xe9 um ficheiro normal.",errorFileTooLarge:"O ficheiro \xe9 maior que {{maxBytes}} bytes.",errorFileRead:"N\xe3o foi poss\xedvel ler o ficheiro: {{message}}",sourceInline:"Markdown inline",sourceFile:"ficheiro {{path}}"}},heartbeat:{started:"Heartbeat started (poll every {{interval}}s). Checking email for subjects starting with 'task:' or '任务:'.",startedIdle:"Heartbeat started (IMAP IDLE) for role {{role}}. Waiting for new email.",imapClosedShutdown:"Heartbeat IMAP connection closed; shutting down process.",imapError:"Heartbeat IMAP error: {{message}}",imapDisconnectedReconnect:"Heartbeat IMAP disconnected; reconnecting in {{ms}} ms",imapOpenBoxError:"Heartbeat IMAP openBox error: {{message}}",onNewMailError:"Heartbeat onNewMail error: {{message}}",runningTask:"Heartbeat: running task {{subject}}",emailRequired:"O e-mail n\xe3o pode estar vazio para o heartbeat. Configure o e-mail do papel {{role}} na tabela email_roles na base de dados sqlite3.",loadedState:"Estado do heartbeat carregado do SQLite para o e-mail {{email}} e o papel {{role}}, estados: {{states}}",fetchFound:"O heartbeat encontrou {{count}} novas tarefas na caixa de entrada: {{ids}}",savedState:"Estado do heartbeat guardado no SQLite para o e-mail {{email}} e o papel {{role}}",mergedAndNext:"{{merged}} tarefas fundidas no estado, pr\xf3xima a processar: {{stateSummary}}",replyEmailFailed:"Falha no envio do e-mail de resposta do heartbeat: {{error}}",taskFailed:"Tarefa do heartbeat falhou: {{error}}",failureReplyEmailFailed:"Falha no envio do e-mail de notifica\xe7\xe3o de falha do heartbeat: {{error}}"},cli:{description:"Pithosai: implementa c\xf3digo ou projetos a partir de um pedido em linguagem natural. Os prompts de fun\xe7\xe3o s\xe3o carregados do banco de dados SQLite em tempo de execu\xe7\xe3o (com fallback opcional para .pithosai/<role>/*.md). Crie um projeto com 'pithosai init'.",versionOption:"mostrar vers\xe3o",roleOption:"papel (conjunto de modelos para init); modelos em templates/<role>/",langOption:"idioma para prompts e modelos init: en, zh (predefinido: en)",interactiveModeOption:"entrar em modo interativo sem pedido; mostrar dicas do modo e pedir entrada",initDescription:"Criar um novo projeto e a estrutura de diret\xf3rio .pithosai/. Os prompts de fun\xe7\xe3o s\xe3o carregados do banco de dados SQLite em tempo de execu\xe7\xe3o (com fallback opcional para .pithosai/<role>/*.md).",initTypeOption:"tipo de projeto: js, ts ou python",initExamples:"\nExemplos:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"Adicionar modelos de papel a .pithosai/<role>/ no projeto",addRoleArgument:"papel a adicionar (ex.: PM, QA)",requestArgument:'o que construir (ex.: "Um CLI que converte CSV em JSON"). Se omitir, mostra ajuda.',cwdOption:"diret\xf3rio do projeto (predefinido: diret\xf3rio atual)",skillsDirOption:"diret\xf3rio de habilidades para read_skill (predefinido: ./.pithosai/skills ou PITHOSAI_SKILLS_DIR)",reasonerOption:"usar modelo DeepSeek Reasoner (racioc\xednio); predefinido \xe9 DeepSeek Coder",chatOption:"usar modelo DeepSeek Chat (chat geral, n\xe3o c\xf3digo); predefinido \xe9 DeepSeek Coder",cursorOption:"usar modelo Cursor CLI (autentica\xe7\xe3o via cursor-agent login, sem chave API). Opcionalmente especificar modelo: auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"tempo m\xe1ximo de execu\xe7\xe3o do agente em segundos (predefinido: 1800). Sobrescrever com PITHOSAI_TIMEOUT_MS (ms).",interactiveOption:"desativar prompt interativo (predefinido: ap\xf3s cada resposta, pedir a seguinte)",modeOption:"variant: agent (default, may use tools), dialog (answer only, no tools), plan (write <slug>-plan.md in project root, no tools)",shellDisabledInMode:"Shell commands are disabled in dialog and plan mode.",planWritten:"Plan written to {{path}}",planRunning:"Gerando o plano…",waitingReply:"Aguardando resposta…",runningReply:"Executando…",resultPreviewOpening:"Abrindo pr\xe9-visualiza\xe7\xe3o do resultado no navegador…",resultPreviewTitle:"Resultado Pithosai",resultPreviewFailed:"N\xe3o foi poss\xedvel abrir a pr\xe9-visualiza\xe7\xe3o: {{message}}",resultPreviewCopy:"Copiar Markdown",resultPreviewClose:"Fechar",resultPreviewCopied:"Copiado para a \xe1rea de transfer\xeancia",resultPreviewTerminalHint:"↑↓ ou j/k \xb7 PgUp/PgDn ou Ctrl+U/Ctrl+D \xb7 Home/End ou gg/G \xb7 q/Esc fechar",runExamples:'\nExemplos:\n pithosai "Adicionar um endpoint REST que devolve a hora atual"\n pithosai -C ./my-app "Executar testes e corrigir falhas"\n pithosai -i # modo interativo: carregar \xfaltima sess\xe3o e pedir pedidos\n pithosai --no-interactive "Uma vez" # uma resposta, sem pedir seguinte\n pithosai --mode dialog "Explain this error"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"Uso:",helpArguments:"Argumentos:",helpOptions:"Op\xe7\xf5es:",helpCommands:"Comandos:",helpGlobalOptions:"Op\xe7\xf5es globais:",helpOption:"mostrar ajuda do comando",heartbeatDescription:"Poll inbox for task emails (subject 'task:...' or '任务:...'), enqueue and run them one by one. State in ~/.pithosai/heartbeat-state.json.",heartbeatIntervalOption:"Poll interval in seconds (default: 60)",heartbeatOnceOption:"Run one tick (fetch, process one task if any) then exit",taskDescription:"Monitora o ficheiro de tarefas e processa-as uma de cada vez no mesmo processo",taskFileOption:"Caminho para o Markdown das tarefas (predefini\xe7\xe3o: prompts.md na raiz do projeto)",taskModelOption:"Chave do modelo para a tarefa (deepSeekCoder, deepSeekChat, deepSeekReasoner, ollamaQwen25, ollamaQwen25Coder, ollamaDeepSeekR1, cursorAutoModel, cursorSonnet, cursorSonnetThinking, cursorOpus, cursorGpt)",taskNewSessionOption:"Come\xe7ar com uma sess\xe3o nova (sem hist\xf3rico de chat)",taskExamples:"\nExemplos:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"Tarefa n\xe3o encontrada: {{taskId}}",taskAgentCompleted:"Agente conclu\xeddo.",taskAgentRunFailed:"Execu\xe7\xe3o do agente falhou.",taskDone:"Conclu\xeddo",taskFailed:"Tarefa falhou: {{message}}",taskProcessingHeader:"--- A processar tarefa ---",taskLabelId:"id:",taskLabelTitle:"t\xedtulo:",taskLabelStatus:"estado:",taskLabelDescription:"descri\xe7\xe3o:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"A iniciar processador para a tarefa em processamento {{id}} ({{title}}).",taskNoPending:"N\xe3o h\xe1 tarefas pendentes.",taskPickedTask:"Tarefa {{id}} ({{title}}) escolhida; a iniciar processador.",taskProcessorFailed:"Processador de tarefas falhou: {{message}}",taskWatcherRunning:"Monitor de tarefas em execu\xe7\xe3o. Ctrl+C para parar.",memorizeDescription:"Escreve .pithosai/<role>/memory.md com resumos das tarefas em que o papel participou (mensagens persistidas no intervalo).",memorizeStartOption:"In\xedcio do intervalo: YYYY-MM-DD ou data/hora ISO",memorizeEndOption:"Fim do intervalo: YYYY-MM-DD ou data/hora ISO",memorizeRoleRequired:"O papel \xe9 obrigat\xf3rio (-r/--role ou --role global).",memorizeWrote:"Gravado {{path}} ({{count}} tarefa(s)).",memorizeNoTasks:"Nenhuma tarefa no intervalo para o papel {{role}}; cabe\xe7alho em {{path}}.",memorizeDateError:"Intervalo de datas inv\xe1lido: {{message}}",memorizeNoLlmOption:"Ignorar resumo por LLM; gravar apenas mem\xf3ria estruturada (igual a PITHOSAI_MEMORIZE_SKIP_LLM=1).",memorizeLlmFallback:"Falha no resumo por LLM ({{message}}); mem\xf3ria estruturada gravada sem resumo.",memorizeExamples:"\nExemplos:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"Upgrade a legacy plaintext pithosai.db (e.g. from v1.0.4) to SQLCipher. Uses the same device-bound key as the app (see docs/device-id.md). Safe to run more than once.",migrateDbDbPathOption:"SQLite database file (default: PITHOSAI_DB_PATH if set, otherwise ~/.pithosai/pithosai.db)",migrateDbMigrated:"Database file was migrated to SQLCipher.",migrateDbSkippedAlready:"Database already uses this encryption key; no migration was needed.",migrateDbSkippedMissing:"No database file at {{path}}; nothing to migrate.",migrateDbSkippedNotPlain:"File is not a readable legacy plaintext SQLite database, or it was created with a different key; left unchanged.",migrateDbErrNoSqlcipher:"SQLCipher is not available in this Node install (native module failed to load). Install or build @journeyapps/sqlcipher for your platform, then retry."},shellTips:{description:"Obter comandos shell para um pedido (apenas Ollama)",argument:"O que pretende fazer (ex. listar ficheiros grandes no diret\xf3rio atual)",loading:"A obter comandos...",examples:'\nExemplos:\n $ pithosai shell-tips listar ficheiros json no diret\xf3rio atual\n $ pithosai shell-tips "encontrar e substituir foo por bar em todos os .js"'},writer:{description:"Gerar texto para um pedido (Ollama qwen2.5:14b)",argument:"O que escrever (ex. email curto a recusar uma reuni\xe3o)",loading:"A escrever...",examples:'\nExemplos:\n $ pithosai writer email curto a recusar reuni\xe3o\n $ pithosai writer "tr\xeas pontos para um kickoff de projeto"'},skills:{installing:"A instalar habilidades em {{dir}}",fetchingList:"A obter habilidades dispon\xedveis do ClawHub...",fetchingIndex:"A obter \xedndice de habilidades de {{url}}",notFound:"Habilidade '{{name}}' n\xe3o encontrada",noSkillsAvailable:"Nenhuma habilidade dispon\xedvel do ClawHub",noSkillsFound:"Nenhuma habilidade encontrada",downloadFailed:"Falha ao descarregar habilidade '{{name}}': {{error}}",installed:"Habilidade '{{name}}' instalada",complete:"Instala\xe7\xe3o conclu\xedda: {{count}} de {{total}} habilidades instaladas",alreadyInstalled:"Habilidade '{{name}}' j\xe1 instalada (use --force para reinstalar)",downloading:"A descarregar habilidade '{{name}}' de {{url}}",noSkillsDir:"Nenhum diret\xf3rio de habilidades encontrado. Instale habilidades primeiro.",noSkillsInstalled:"Nenhuma habilidade instalada",installedList:"Habilidades instaladas ({{count}} total) em {{dir}}:",notInstalled:"Habilidade '{{name}}' n\xe3o est\xe1 instalada",removed:"Habilidade '{{name}}' removida"},skillConvert:{welcome:"Sistema de convers\xe3o de habilidades - Converter habilidades bem-sucedidas em ferramentas permanentes",listHeader:"An\xe1lise de convers\xe3o de habilidades ({{totalSkills}} habilidades, {{totalExecutions}} execu\xe7\xf5es)",noSuggestions:"Nenhuma habilidade atinge o limiar de convers\xe3o de {{threshold}}.",suggestedConversions:"Convers\xf5es sugeridas:",convertHint:"Use 'pithosai skill-convert convert <nome-habilidade>' para converter uma habilidade.",skillNotFound:"Habilidade '{{skillName}}' n\xe3o encontrada ou ileg\xedvel: {{error}}",alreadyConverted:"A habilidade '{{skillName}}' j\xe1 foi convertida em ferramenta.",useForceHint:"Use --force para converter novamente.",conversionReportHeader:"Relat\xf3rio de convers\xe3o de '{{skillName}}':",conversionScore:"Pontua\xe7\xe3o de convers\xe3o",suggestedType:"Tipo sugerido",ready:"Pronto para convers\xe3o",estimatedBenefits:"Benef\xedcios estimados",performance:"Melhoria de desempenho",reliability:"Melhoria de fiabilidade",usability:"Melhoria de usabilidade",parameters:"Par\xe2metros",notReadyWarning:"Esta habilidade n\xe3o est\xe1 pronta para convers\xe3o autom\xe1tica.",moreUsageHint:"Use a habilidade com mais frequ\xeancia ou use --force para for\xe7ar a convers\xe3o.",dryRunComplete:"Simula\xe7\xe3o conclu\xedda. Nenhuma altera\xe7\xe3o realizada.",confirmConversion:"Converter '{{skillName}}' em ferramenta permanente?",conversionCancelled:"Convers\xe3o cancelada.",converting:"A converter '{{skillName}}' em ferramenta...",conversionSuccess:"'{{skillName}}' convertido com sucesso em '{{toolName}}'.\nFerramenta guardada em: {{toolPath}}",usageExample:"Exemplo de utiliza\xe7\xe3o:",nextSteps:"Pr\xf3ximos passos:",restartAgent:"Reinicie o agente para carregar a nova ferramenta",testTool:"Testar ferramenta: <nome-ferramenta> --help",manageTools:"Gerir ferramentas: pithosai skill-convert tools",listError:"Erro ao listar habilidades: {{error}}",conversionError:"Erro ao converter '{{skillName}}': {{error}}",skillStatsHeader:"Estat\xedsticas de '{{skillName}}':",generalStats:"Estat\xedsticas gerais",totalExecutions:"Execu\xe7\xf5es totais",successful:"Bem-sucedidas",failed:"Falhadas",avgTime:"Tempo m\xe9dio de execu\xe7\xe3o",lastUsed:"\xdaltima utiliza\xe7\xe3o",recentExecutions:"Execu\xe7\xf5es recentes",commonParameters:"Par\xe2metros comuns",overallStatsHeader:"Estat\xedsticas globais de habilidades",overallStats:"Estat\xedsticas globais",totalSkillsTracked:"Total de habilidades rastreadas",avgSuccessRate:"Taxa de sucesso m\xe9dia",topSkills:"Habilidades mais usadas",conversionSuggestions:"Sugest\xf5es de convers\xe3o",statsError:"Erro ao obter estat\xedsticas: {{error}}",confirmClearAll:"Apagar TODOS os registos de execu\xe7\xe3o de habilidades? Esta a\xe7\xe3o n\xe3o pode ser desfeita.",allRecordsCleared:"Todos os registos de execu\xe7\xe3o de habilidades foram apagados.",skillRecordsCleared:"Os registos de execu\xe7\xe3o de '{{skillName}}' foram apagados.",clearCancelled:"Opera\xe7\xe3o de limpeza cancelada.",specifySkillOrAll:"Especifique um nome de habilidade ou use --all",clearError:"Erro ao limpar registos: {{error}}",noConvertedTools:"Nenhuma ferramenta convertida encontrada.",convertedToolsHeader:"Ferramentas convertidas:",originalSkill:"Habilidade original",converted:"Convertido em",usageCount:"N\xfamero de utiliza\xe7\xf5es",toolsError:"Erro ao gerir ferramentas: {{error}}",confirmRemoveTool:"Remover ferramenta '{{toolName}}'?",toolRemoved:"Ferramenta '{{toolName}}' removida.",toolRemoveFailed:"Falha ao remover ferramenta '{{toolName}}'.",removeCancelled:"Remo\xe7\xe3o de ferramenta cancelada.",toolEnabled:"Ferramenta '{{toolName}}' ativada.",toolEnableFailed:"Falha ao ativar ferramenta '{{toolName}}'.",toolDisabled:"Ferramenta '{{toolName}}' desativada.",toolDisableFailed:"Falha ao desativar ferramenta '{{toolName}}'.",noStatsForSkill:"Nenhuma estat\xedstica encontrada para a habilidade '{{skillName}}'."},hooks:{description:"Gerenciar hooks do agente para depura\xe7\xe3o, seguran\xe7a e monitoramento",list:{description:"Listar todos os hooks registrados",title:"\uD83D\uDCCB Hooks registrados",total:"Total: {{total}} manipuladores",options:{verbose:"Mostrar informa\xe7\xf5es detalhadas dos manipuladores"},error:"Falha ao listar hooks: {{error}}"},debug:{description:"Ativar hooks de depura\xe7\xe3o para monitorar o comportamento do agente",options:{data:"Registrar dados completos na sa\xedda de depura\xe7\xe3o",performance:"Ativar hooks de monitoramento de desempenho",stats:"Ativar hooks de coleta de estat\xedsticas",all:"Ativar todos os hooks de depura\xe7\xe3o"},added:{debug:"Hooks de registro de depura\xe7\xe3o adicionados",performance:"Hooks de monitoramento de desempenho adicionados",stats:"Hooks de coleta de estat\xedsticas adicionados",basic:"Hooks de depura\xe7\xe3o b\xe1sicos adicionados"},success:"Hooks de depura\xe7\xe3o ativados ({{count}} manipuladores registrados)",error:"Falha ao ativar hooks de depura\xe7\xe3o: {{error}}"},security:{description:"Ativar hooks de seguran\xe7a para controle de acesso e monitoramento",options:{block:"Lista de ferramentas a bloquear separadas por v\xedrgulas",maxPrompt:"Comprimento m\xe1ximo permitido do prompt (padr\xe3o: 10000)"},success:"Hooks de seguran\xe7a ativados",blockedTools:"Ferramentas bloqueadas: {{tools}}",maxPrompt:"Comprimento m\xe1ximo do prompt: {{length}} caracteres",error:"Falha ao ativar hooks de seguran\xe7a: {{error}}"},clear:{description:"Limpar todos os hooks registrados",success:"Todos os hooks limpos",error:"Falha ao limpar hooks: {{error}}"},test:{description:"Testar hooks disparando-os com dados de teste",argument:{hookType:"Tipo de hook espec\xedfico para testar (opcional)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",triggered:"Hook disparado: {{type}}",result:"Resultado: {{result}}",allTriggered:"Todos os hooks disparados com sucesso",error:"Falha ao testar hooks: {{error}}"},register:{description:"Registrar um manipulador de hook personalizado a partir de um arquivo",argument:{hookType:"Tipo de hook para registrar o manipulador",handlerFile:"Caminho para o arquivo do manipulador (deve exportar uma fun\xe7\xe3o padr\xe3o)"},invalidType:"Tipo de hook inv\xe1lido: {{type}}",invalidHandler:"O arquivo do manipulador deve exportar uma fun\xe7\xe3o padr\xe3o",success:"Manipulador para {{type}} registrado de {{file}}",error:"Falha ao registrar hook: {{error}}"},status:{description:"Mostrar configura\xe7\xe3o atual dos hooks e estat\xedsticas",title:"\uD83D\uDCCB Estado dos hooks",error:"Falha ao obter estado dos hooks: {{error}}"}}}},5946(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"基本要求",projectDir:"專案目錄(在此工作):{{cwd}}",skillsInstruction:"當任務與某技能的描述匹配時,使用 read_skill 工具載入該技能的完整說明。",toolArgSizeLimit:"單一工具呼叫參數(如 write 的 content)嚴禁超過 {{maxChars}} 字元,否則可能觸發「Unterminated string in JSON」錯誤。長檔案或腳本請拆成多次 write 呼叫(按檔案或按每段不超過 {{maxChars}} 字元)。",toolCallJsonFormat:'工具呼叫參數必須是合法 JSON:所有鍵和字串值都必須用雙引號包裹。例如 write:{"path": "檔名.md", "content": "內容"}。不要省略鍵或值的引號(如 path: file.md 或 content: 文字 為無效)。'},errors:{missingPromptFiles:"缺少必需的提示檔案,目錄:{{dir}}",runInit:"請在專案根目錄執行 'pithosai init' 以建立 .pithosai 及範本。",noApiKey:"找不到 API 金鑰。請設定 DEEPSEEK_API_KEY 或 OPENROUTER_API_KEY。",ollamaNotConfigured:"未設定 Ollama。請設定 OPENAI_LOCAL_API_BASE 或在專案中設定本地模型。",noValidTemplateFiles:"目錄 {{dir}} 中無有效範本檔案。需要 *-<lang>.md 格式(如 IDENTITY-ja.md)。請執行 'pithosai init' 建立 .pithosai 及範本。",runTimeout:"Agent 執行在 {{seconds}} 秒後逾時。可使用 --timeout <秒> 或 PITHOSAI_TIMEOUT_MS 調整。",agentRunFailed:"執行失敗:{{message}}",unknownRunError:"未知錯誤"},warnings:{sessionAppend:"工作階段附加失敗:{{message}}",apiRetry:"API 錯誤,第 {{attempt}}/{{max}} 次嘗試;正在重試…"},reasoner:{thinkingHeader:"\n--- 思考:\n",replyHeader:"\n\n--- 回覆:\n"},run:{cwd:"工作目錄 {{cwd}}",request:"請求:{{request}}",interactivePrompt:"您:",tuiYouLabel:"您:",interactiveExitHint:"請回答或輸入新請求(輸入 'exit' 或 'quit' 可結束 CLI)。",interactiveModeCwd:"工作目錄:{{cwd}}",interactiveModeAgentTitle:"--- 互動模式 — 代理(完整工具)---",interactiveModeAgentTips:"- 使用完整工具集(讀取、寫入、執行及專案設定的其他工具)。\n- 對話依任務儲存在本機資料庫中。\n- `/new` 會指派新的任務 id,不會載入先前訊息。\n- `/shell <命令>` 執行 shell;`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 用於已持久化任務。\n- `/list-skill`、`/install-skill`、`/remove-skill` 等同 `pithosai skills list|install|remove`(ClawHub)。Ctrl+S 停止,Ctrl+P 暫停。",interactiveModeDialogTitle:"--- 互動模式 — 對話(唯讀問答)---",interactiveModeDialogTips:"- 僅使用唯讀工具(不可用 shell、寫入檔案或執行命令)。\n- 對話依任務儲存在本機資料庫中。\n- 使用 `/new` 會指派新的任務 id,不會載入先前訊息。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),與 `pithosai skills` CLI 相同。",interactiveModePlanTitle:"--- 計畫模式 ---",interactiveModePlanTips:"- 每次回覆會寫入專案目錄下的 `<slug>-plan.md`(請求首行影響檔名)。\n- 僅唯讀工具;shell 與修改類工具不可用。\n- `/new` 會指派新的任務 id。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),與 `pithosai skills` CLI 相同。\n- 每次執行結束後可在提示符繼續輸入新的計畫請求(與 agent/dialog 相同)。",list:{noPersistedTasks:"找不到已持久化的任務。",createTasksFirstHint:"請先使用 `pithosai task` 建立任務。",persistedTasksHeader:"--- 已持久化的任務({{count}})---",selectTaskHint:"使用 `/select <index>` 來執行任務。",noTasksCached:"沒有快取的任務。請先執行 `/list`。",invalidIndex:"無效的索引 {{index}}。有效範圍:0-{{maxIndex}}。",selectUsage:"用法:/select <index>",selectedTask:"已選擇任務 #{{index}}。"},skillSlash:{installUsage:"用法:/install-skill [--force] [技能名稱]",removeUsage:"用法:/remove-skill <技能名稱>",listNoExtra:"/list-skill 不接受參數。",failed:"技能指令失敗:{{message}}"},show:{title:"目前任務",field:"欄位",value:"值",taskId:"taskId",mode:"模式",model:"模型",status:"狀態",messageCount:"訊息數",usageInput:"用量.輸入",usageOutput:"用量.輸出",usageCacheRead:"用量.快取讀取",usageCacheWrite:"用量.快取寫入",usageTotalTokens:"用量.總Token"},showTask:{title:"任務問答",taskIdLabel:"任務 ID",turnHeading:"第 {{index}} 輪",questionLabel:"問題",answerLabel:"回答",createdLabel:"建立時間",emptyQuestion:"(空問題)",emptyAnswer:"(尚無助理文字回覆)",emptyNoMessages:"此任務尚無使用者訊息,無可顯示內容。",previewDocumentTitle:"任務問答"},showPrompt:{previewDocumentTitle:"系統提示",previewHeading:"系統提示"},shellHint:"使用 '/shell <命令>' 執行 shell 命令(例如:'/shell ls -la')。",replIntroDialog:"對話模式:僅唯讀工具 — `/shell` 已停用。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",replIntroPlan:"計畫模式:每次回覆寫入專案目錄下的 `<slug>-plan.md`(請求首行影響檔名)。`/shell` 已停用;計畫完成前輸出保持精簡。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用於已持久化任務。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",newSessionHint:"使用 '/new <請求>' 開始新工作階段(不讀取聊天記錄)。",newSessionNoHistory:"使用新工作階段(無聊天記錄)。",controlHint:"按 Ctrl+S 停止正在執行的代理,按 Ctrl+P 暫停並進入子命令模式。",replTabCompletionHint:"按 Tab 鍵可補全以 / 開頭的指令(如 /list、/list-skill),或補全 exit、quit。",tuiScrollTranscriptHint:"全螢幕終端:滑鼠滾輪、方向鍵、PgUp/PgDn、Ctrl+U/Ctrl+F(翻頁)。Ctrl+U/F 捲動日誌。Ctrl+D 仍為清空列結束或輸入時向前刪除。",agentStopped:"代理已停止。",pauseHeader:"--- 代理已暫停 ---",pauseCurrentRequest:"目前請求:{{request}}",pauseHelp:"命令:'continue' 或 'c' 繼續執行,'exit' 或 'e' 退出,或輸入新請求替換目前請求。",pausePrompt:"[已暫停] ",pauseRequestUpdated:"請求已更新為:{{request}}"},shell:{noCommand:"/shell 前綴後未提供命令。用法:/shell <命令>",executionError:"執行 shell 命令時出錯:{{error}}",executing:"[shell] 執行中:{{command}}",errorNoCommand:"/shell 前綴後未提供命令。",errorSpawnFailed:"啟動進程失敗:{{message}}",errorTimedOut:"命令在 {{seconds}} 秒後逾時",logFailed:"Shell 命令失敗:{{command}}(退出碼:{{code}})",logExecutionError:"Shell 命令執行錯誤:{{message}}",resultCommand:"命令:{{command}}",resultExitCode:"退出碼:{{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"成功:",resultSuccessYes:"是",resultSuccessNo:"否",resultOutput:"輸出:",resultError:"錯誤:"},init:{invalidType:'無效的 --type "{{value}}";可選:{{choices}}',invalidLang:'無效的 --lang "{{value}}";可選:{{choices}}',templatesDirNotFound:"找不到範本目錄:{{dir}}",createdPromptTemplates:"已建立 {{dir}}(提示範本)",createdSessions:"已建立 {{dir}}(工作階段歷史)",initialized:"已在 {{targetDir}} 中初始化 {{type}} 專案",promptFilesIn:"提示檔案位於 {{pithosaiDir}},工作階段資料位於 {{sessionsDir}}",runHint:'執行 "pithosai -C {{targetDir}} \\"你的請求\\"" 開始。',createdFile:"已建立 {{path}}",roleAlreadyAdded:"角色 {{role}} 已存在於 .pithosai,略過。",addedRoleTemplates:"已將角色範本新增至 {{dir}}"},tools:{listFiles:{result:"list_files:已在 {{path}} 下列出 {{count}} 個項目"},playwrightView:{result:"playwright_view_markdown:預覽已關閉({{source}})",skipped:"已略過瀏覽器預覽(PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"請只提供 markdown 或 path 其中之一(不可同時提供或皆省略)。",errorEmpty:"Markdown 內容為空。",errorFileOutside:"path 必須位於專案目錄下。",errorNotAFile:"path 不是一般檔案。",errorFileTooLarge:"檔案超過 {{maxBytes}} 位元組。",errorFileRead:"無法讀取檔案:{{message}}",sourceInline:"內嵌 Markdown",sourceFile:"檔案 {{path}}"}},heartbeat:{started:"心跳已啟動(每 {{interval}} 秒輪詢)。檢查郵件主旨前綴「task:」或「任務:」。",startedIdle:"心跳已啟動(IMAP IDLE),角色 {{role}}。等待新郵件。",imapClosedShutdown:"心跳 IMAP 連線已關閉;正在關閉程序。",imapError:"心跳 IMAP 錯誤:{{message}}",imapDisconnectedReconnect:"心跳 IMAP 已斷線;{{ms}} 毫秒後重連",imapOpenBoxError:"心跳 IMAP openBox 錯誤:{{message}}",onNewMailError:"心跳 onNewMail 錯誤:{{message}}",runningTask:"心跳:正在執行任務 {{subject}}",emailRequired:"心跳的信箱不可為空。請在 sqlite3 資料庫的 email_roles 表中設定角色 {{role}} 的信箱。",loadedState:"已從 SQLite 載入心跳狀態,信箱 {{email}},角色 {{role}},狀態:{{states}}",fetchFound:"心跳擷取收件匣發現 {{count}} 個新任務:{{ids}}",savedState:"已將心跳狀態儲存至 SQLite,信箱 {{email}},角色 {{role}}",mergedAndNext:"已合併 {{merged}} 個任務到狀態,下一個待處理:{{stateSummary}}",replyEmailFailed:"心跳回覆郵件傳送失敗:{{error}}",taskFailed:"心跳任務執行失敗:{{error}}",failureReplyEmailFailed:"心跳失敗通知郵件傳送失敗:{{error}}"},cli:{description:"Pithosai:根據自然語言請求實作程式碼或專案。角色提示在運行時從 SQLite 資料庫加載(可選回退到 .pithosai/<role>/*.md)。使用 'pithosai init' 建立專案。",versionOption:"輸出版本號",roleOption:"角色(init 使用的範本集);範本位於 templates/<role>/",langOption:"提示與 init 範本語言:en、zh(預設:en)",interactiveModeOption:"無請求時進入互動模式;顯示模式說明並提示輸入",initDescription:"建立新專案及 .pithosai/ 目錄結構。角色提示在運行時從 SQLite 資料庫加載(可選回退到 .pithosai/<role>/*.md)。",initTypeOption:"專案類型:js、ts 或 python",initExamples:"\n範例:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"將角色範本新增至專案中的 .pithosai/<role>/",addRoleArgument:"要新增的角色(如 PM、QA)",requestArgument:'要建構的內容(例如 "將 CSV 轉為 JSON 的 CLI")。省略則顯示說明。',cwdOption:"專案目錄(預設:目前目錄)",skillsDirOption:"read_skill 技能目錄(預設:./.pithosai/skills 或 PITHOSAI_SKILLS_DIR)",reasonerOption:"使用 DeepSeek Reasoner(思考)模型;預設為 DeepSeek Coder",chatOption:"使用 DeepSeek Chat 模型(一般對話,非程式碼);預設為 DeepSeek Coder",cursorOption:"使用 Cursor CLI 模型(透過 cursor-agent login 認證,無需 API 金鑰)。可選擇指定模型:auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"Agent 最長執行時間(秒,預設 1800)。可用 PITHOSAI_TIMEOUT_MS(毫秒)覆蓋。",interactiveOption:"停用互動提示(預設:每次回覆後詢問下一則訊息)",modeOption:"執行模式:agent(預設,可使用工具)、dialog(僅回答,無工具)、plan(僅將計畫寫入專案根目錄 <slug>-plan.md,無工具)",shellDisabledInMode:"在 dialog 與 plan 模式下已停用 /shell 命令。",planWritten:"計畫已寫入 {{path}}",planRunning:"正在產生計畫…",waitingReply:"正在等待回覆…",runningReply:"正在執行…",resultPreviewOpening:"正在瀏覽器中開啟結果預覽…",resultPreviewTitle:"Pithosai 結果",resultPreviewFailed:"無法開啟結果預覽:{{message}}",resultPreviewCopy:"複製 Markdown",resultPreviewClose:"關閉",resultPreviewCopied:"已複製到剪貼簿",resultPreviewTerminalHint:"↑↓ 或 j/k \xb7 PgUp/PgDn 或 Ctrl+U/Ctrl+D \xb7 Home/End 或 gg/G \xb7 q/Esc 關閉",runExamples:'\n範例:\n pithosai "新增回傳目前時間的 REST 介面"\n pithosai -C ./my-app "執行測試並修復失敗"\n pithosai -i # 互動模式:載入最新工作階段後提示輸入\n pithosai --no-interactive "單次" # 單次回覆,無後續提示\n pithosai --mode dialog "解釋此錯誤"\n pithosai --mode plan "api sprint plan"\n',helpUsage:"用法:",helpArguments:"參數:",helpOptions:"選項:",helpCommands:"命令:",helpGlobalOptions:"全域選項:",helpOption:"顯示命令說明",heartbeatDescription:"輪詢收件匣中任務郵件(主旨「task:...」或「任務:...」),入隊並逐個執行。狀態保存在 ~/.pithosai/heartbeat-state.json。",heartbeatIntervalOption:"輪詢間隔(秒,預設 60)",heartbeatOnceOption:"只執行一次(拉取郵件並處理一個任務後結束)",taskDescription:"監聽任務檔案並在同一程序內逐個處理任務",taskFileOption:"任務 Markdown 檔案路徑(預設:專案根目錄下的 prompts.md)",taskModelOption:"任務使用的模型鍵(deepSeekCoder、deepSeekChat、deepSeekReasoner、ollamaQwen25、ollamaQwen25Coder、ollamaDeepSeekR1、cursorAutoModel、cursorSonnet、cursorSonnetThinking、cursorOpus、cursorGpt)",taskNewSessionOption:"使用新工作階段(無聊天紀錄)",taskExamples:"\n範例:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"找不到任務:{{taskId}}",taskAgentCompleted:"Agent 已完成。",taskAgentRunFailed:"Agent 執行失敗。",taskDone:"完成",taskFailed:"任務失敗:{{message}}",taskProcessingHeader:"--- 正在處理任務 ---",taskLabelId:"id:",taskLabelTitle:"標題:",taskLabelStatus:"狀態:",taskLabelDescription:"描述:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"正在為處理中任務 {{id}}({{title}})啟動處理器。",taskNoPending:"沒有待處理任務。",taskPickedTask:"已選擇任務 {{id}}({{title}});正在啟動處理器。",taskProcessorFailed:"任務處理器失敗:{{message}}",taskWatcherRunning:"任務監看器執行中。按 Ctrl+C 停止。",memorizeDescription:"依日期範圍內該角色參與的任務(持久化的任務訊息)產生摘要,寫入 .pithosai/<role>/memory.md。",memorizeStartOption:"範圍開始:YYYY-MM-DD 或 ISO 日期時間",memorizeEndOption:"範圍結束:YYYY-MM-DD 或 ISO 日期時間",memorizeRoleRequired:"必須指定角色(使用 -r/--role 或全域 --role)。",memorizeWrote:"已寫入 {{path}}(共 {{count}} 個任務)。",memorizeNoTasks:"角色 {{role}} 在範圍內無任務;已寫入標頭至 {{path}}。",memorizeDateError:"日期範圍無效:{{message}}",memorizeNoLlmOption:"略過 LLM 摘要,僅寫入結構化記憶(等同 PITHOSAI_MEMORIZE_SKIP_LLM=1)。",memorizeLlmFallback:"LLM 摘要失敗({{message}});已寫入未摘要的結構化記憶。",memorizeExamples:"\n範例:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"將舊版明文 pithosai.db(例如 v1.0.4)升級為 SQLCipher。使用與應用程式執行時相同的裝置綁定金鑰(參見 docs/device-id.md)。可重複執行。",migrateDbDbPathOption:"SQLite 資料庫檔案路徑(預設:若已設定 PITHOSAI_DB_PATH 則使用該路徑,否則為 ~/.pithosai/pithosai.db)",migrateDbMigrated:"資料庫檔案已遷移為 SQLCipher 格式。",migrateDbSkippedAlready:"資料庫已使用目前金鑰加密,無需遷移。",migrateDbSkippedMissing:"路徑 {{path}} 下沒有資料庫檔案,未執行任何動作。",migrateDbSkippedNotPlain:"該檔案不是可讀的舊版明文 SQLite,或使用了其他金鑰,未做修改。",migrateDbErrNoSqlcipher:"目前 Node 環境無法載入 SQLCipher 原生模組。請為目前平台安裝或編譯 @journeyapps/sqlcipher 後再試。"},shellTips:{description:"依請求取得 shell 指令(僅 Ollama,僅輸出指令)",argument:"你想做什麼(例如列出目前目錄中的大檔案)",loading:"正在取得指令…",examples:'\n範例:\n $ pithosai shell-tips 列出目前目錄的 json 檔案\n $ pithosai shell-tips "在所有 .js 檔案中將 foo 替換為 bar"'},writer:{description:"依請求產生文字(Ollama qwen2.5:14b)",argument:"要寫什麼(例如簡短拒絕會議的郵件)",loading:"正在撰寫…",examples:'\n範例:\n $ pithosai writer 簡短拒絕會議的郵件\n $ pithosai writer "專案啟動會三項要點"'},skills:{installing:"正在安裝技能至 {{dir}}",fetchingList:"正在從 ClawHub 取得可用技能...",fetchingIndex:"正在從 {{url}} 取得技能索引",notFound:"找不到技能「{{name}}」",noSkillsAvailable:"ClawHub 中沒有可用技能",noSkillsFound:"找不到任何技能",downloadFailed:"下載技能「{{name}}」失敗:{{error}}",installed:"已安裝技能「{{name}}」",complete:"安裝完成:{{count}} / {{total}} 個技能已安裝",alreadyInstalled:"技能「{{name}}」已安裝(使用 --force 重新安裝)",downloading:"正在從 {{url}} 下載技能「{{name}}」",noSkillsDir:"找不到技能目錄。請先安裝技能。",noSkillsInstalled:"未安裝任何技能",installedList:"已安裝技能(共 {{count}} 個)位於 {{dir}}:",notInstalled:"技能「{{name}}」未安裝",removed:"已移除技能「{{name}}」"},skillConvert:{welcome:"技能轉換系統 - 將成功的技能轉換為永久工具",listHeader:"技能轉換分析({{totalSkills}} 個技能,{{totalExecutions}} 次執行)",noSuggestions:"沒有技能達到轉換閾值 {{threshold}}。",suggestedConversions:"建議轉換的技能:",convertHint:"使用 'pithosai skill-convert convert <技能名稱>' 轉換技能。",skillNotFound:"找不到技能 '{{skillName}}' 或無法讀取:{{error}}",alreadyConverted:"技能 '{{skillName}}' 已轉換為工具。",useForceHint:"使用 --force 強制重新轉換。",conversionReportHeader:"'{{skillName}}' 轉換報告:",conversionScore:"轉換分數",suggestedType:"建議類型",ready:"準備轉換",estimatedBenefits:"預計收益",performance:"效能提升",reliability:"可靠性提升",usability:"可用性提升",parameters:"參數",notReadyWarning:"此技能尚未準備好自動轉換。",moreUsageHint:"請更頻繁地使用該技能,或使用 --force 強制轉換。",dryRunComplete:"模擬執行完成。未進行任何變更。",confirmConversion:"將 '{{skillName}}' 轉換為永久工具?",conversionCancelled:"轉換已取消。",converting:"正在將 '{{skillName}}' 轉換為工具...",conversionSuccess:"成功將 '{{skillName}}' 轉換為 '{{toolName}}'。\n工具儲存至:{{toolPath}}",usageExample:"使用範例:",nextSteps:"後續步驟:",restartAgent:"重新啟動代理以載入新工具",testTool:"測試工具:<工具名稱> --help",manageTools:"管理工具:pithosai skill-convert tools",listError:"列出技能時出錯:{{error}}",conversionError:"轉換 '{{skillName}}' 時出錯:{{error}}",skillStatsHeader:"'{{skillName}}' 統計資訊:",generalStats:"一般統計",totalExecutions:"總執行次數",successful:"成功",failed:"失敗",avgTime:"平均執行時間",lastUsed:"最後使用",recentExecutions:"最近執行",commonParameters:"常用參數",overallStatsHeader:"整體技能統計",overallStats:"整體統計",totalSkillsTracked:"追蹤的技能總數",avgSuccessRate:"平均成功率",topSkills:"使用最多的技能",conversionSuggestions:"轉換建議",statsError:"取得統計資訊時出錯:{{error}}",confirmClearAll:"清除所有技能執行記錄?此操作無法復原。",allRecordsCleared:"所有技能執行記錄已清除。",skillRecordsCleared:"'{{skillName}}' 的技能執行記錄已清除。",clearCancelled:"清除操作已取消。",specifySkillOrAll:"請指定技能名稱或使用 --all",clearError:"清除記錄時出錯:{{error}}",noConvertedTools:"未找到已轉換的工具。",convertedToolsHeader:"已轉換的工具:",originalSkill:"原始技能",converted:"轉換時間",usageCount:"使用次數",toolsError:"管理工具時出錯:{{error}}",confirmRemoveTool:"移除工具 '{{toolName}}'?",toolRemoved:"工具 '{{toolName}}' 已移除。",toolRemoveFailed:"移除工具 '{{toolName}}' 失敗。",removeCancelled:"工具移除已取消。",toolEnabled:"工具 '{{toolName}}' 已啟用。",toolEnableFailed:"啟用工具 '{{toolName}}' 失敗。",toolDisabled:"工具 '{{toolName}}' 已停用。",toolDisableFailed:"停用工具 '{{toolName}}' 失敗。",noStatsForSkill:"找不到技能 '{{skillName}}' 的統計資訊。"},hooks:{description:"管理代理鉤子,用於偵錯、安全和監控",list:{description:"列出所有已註冊的鉤子",title:"\uD83D\uDCCB 已註冊的鉤子",total:"總計:{{total}} 個處理器",options:{verbose:"顯示詳細的處理器資訊"},error:"列出鉤子失敗:{{error}}"},debug:{description:"啟用偵錯鉤子以監控代理行為",options:{data:"在偵錯輸出中記錄完整資料",performance:"啟用效能監控鉤子",stats:"啟用統計收集鉤子",all:"啟用所有偵錯鉤子"},added:{debug:"已新增偵錯日誌鉤子",performance:"已新增效能監控鉤子",stats:"已新增統計收集鉤子",basic:"已新增基本偵錯鉤子"},success:"偵錯鉤子已啟用({{count}} 個處理器已註冊)",error:"啟用偵錯鉤子失敗:{{error}}"},security:{description:"啟用安全鉤子進行存取控制和監控",options:{block:"要封鎖的工具清單,以逗號分隔",maxPrompt:"最大允許的提示長度(預設:10000)"},success:"安全鉤子已啟用",blockedTools:"已封鎖的工具:{{tools}}",maxPrompt:"最大提示長度:{{length}} 個字元",error:"啟用安全鉤子失敗:{{error}}"},clear:{description:"清除所有已註冊的鉤子",success:"所有鉤子已清除",error:"清除鉤子失敗:{{error}}"},test:{description:"使用測試資料觸發鉤子進行測試",argument:{hookType:"要測試的特定鉤子類型(選填)"},invalidType:"無效的鉤子類型:{{type}}",triggered:"已觸發鉤子:{{type}}",result:"結果:{{result}}",allTriggered:"所有鉤子已成功觸發",error:"測試鉤子失敗:{{error}}"},register:{description:"從檔案註冊自訂鉤子處理器",argument:{hookType:"要註冊處理器的鉤子類型",handlerFile:"處理器檔案路徑(必須匯出預設函式)"},invalidType:"無效的鉤子類型:{{type}}",invalidHandler:"處理器檔案必須匯出一個預設函式",success:"已為 {{type}} 註冊來自 {{file}} 的處理器",error:"註冊鉤子失敗:{{error}}"},status:{description:"顯示目前鉤子設定和統計資訊",title:"\uD83D\uDCCB 鉤子狀態",error:"取得鉤子狀態失敗:{{error}}"}}}},3998(e,t,r){r.d(t,{A:()=>i});let i={prompt:{baseRequirementHeading:"基本要求",projectDir:"项目目录(在此工作):{{cwd}}",skillsInstruction:"当任务与某技能的描述匹配时,使用 read_skill 工具加载该技能的完整说明。",toolArgSizeLimit:"单个工具调用参数(如 write 的 content)严禁超过 {{maxChars}} 字符,否则可能触发「Unterminated string in JSON」错误。长文件或脚本请拆成多次 write 调用(按文件或按每段不超过 {{maxChars}} 字符)。",toolCallJsonFormat:'工具调用参数必须是合法 JSON:所有键和字符串值都必须用双引号包裹。例如 write:{"path": "文件名.md", "content": "内容"}。不要省略键或值的引号(如 path: file.md 或 content: 文字 为无效)。'},errors:{missingPromptFiles:"缺少必需的提示文件,目录:{{dir}}",runInit:"请在项目根目录执行 'pithosai init' 以创建 .pithosai 及模板。",noApiKey:"未找到 API 密钥。请设置 DEEPSEEK_API_KEY 或 OPENROUTER_API_KEY。",ollamaNotConfigured:"未配置 Ollama。请设置 OPENAI_LOCAL_API_BASE 或在项目中配置本地模型。",noValidTemplateFiles:"目录 {{dir}} 中无有效模板文件。需要 *-<lang>.md 格式(如 IDENTITY-ja.md)。请执行 'pithosai init' 创建 .pithosai 及模板。",runTimeout:"Agent 运行在 {{seconds}} 秒后超时。可使用 --timeout <秒> 或 PITHOSAI_TIMEOUT_MS 调整。",agentRunFailed:"运行失败:{{message}}",unknownRunError:"未知错误"},warnings:{sessionAppend:"会话追加失败:{{message}}",apiRetry:"API 错误,第 {{attempt}}/{{max}} 次尝试;正在重试…"},reasoner:{thinkingHeader:"\n--- 思考:\n",replyHeader:"\n\n--- 回复:\n"},run:{cwd:"工作目录 {{cwd}}",request:"请求:{{request}}",interactivePrompt:"您:",tuiYouLabel:"您:",interactiveExitHint:"请回答或输入新请求(输入 'exit' 或 'quit' 可退出 CLI)。",interactiveModeCwd:"工作目录:{{cwd}}",interactiveModeAgentTitle:"--- 交互模式 — 代理(完整工具)---",interactiveModeAgentTips:"- 使用完整工具集(读、写、执行及项目配置的其他工具)。\n- 对话按任务保存在本地数据库中。\n- `/new` 会分配新的任务 id,不会加载此前消息。\n- `/shell <命令>` 执行 shell;`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 用于已持久化任务。\n- `/list-skill`、`/install-skill`、`/remove-skill` 与 `pithosai skills list|install|remove` 相同(ClawHub)。Ctrl+S 停止,Ctrl+P 暂停。",interactiveModeDialogTitle:"--- 交互模式 — 对话(只读问答)---",interactiveModeDialogTips:"- 仅使用只读工具(不可用 shell、写文件或执行命令)。\n- 对话按任务保存在本地数据库中。\n- 使用 `/new` 会分配新的任务 id,不会加载此前消息。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),与 `pithosai skills` CLI 一致。",interactiveModePlanTitle:"--- 计划模式 ---",interactiveModePlanTips:"- 每次回复会写入项目目录下的 `<slug>-plan.md`(请求首行影响文件名)。\n- 仅只读工具;shell 与修改类工具不可用。\n- `/new` 会分配新的任务 id。\n- `/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。\n- `/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub),与 `pithosai skills` CLI 一致。\n- 每次运行结束后可在提示符继续输入新的计划请求(与 agent/dialog 相同)。",list:{noPersistedTasks:"未找到已持久化的任务。",createTasksFirstHint:"请先使用 `pithosai task` 创建任务。",persistedTasksHeader:"--- 已持久化的任务({{count}})---",selectTaskHint:"使用 `/select <index>` 来运行一个任务。",noTasksCached:"没有缓存的任务。请先执行 `/list`。",invalidIndex:"无效的索引 {{index}}。有效范围:0-{{maxIndex}}。",selectUsage:"用法:/select <index>",selectedTask:"已选择任务 #{{index}}。"},skillSlash:{installUsage:"用法:/install-skill [--force] [技能名]",removeUsage:"用法:/remove-skill <技能名>",listNoExtra:"/list-skill 不接受参数。",failed:"技能命令失败:{{message}}"},show:{title:"当前任务",field:"字段",value:"值",taskId:"taskId",mode:"模式",model:"模型",status:"状态",messageCount:"消息数",usageInput:"用量.输入",usageOutput:"用量.输出",usageCacheRead:"用量.缓存读取",usageCacheWrite:"用量.缓存写入",usageTotalTokens:"用量.总Token"},showTask:{title:"任务问答",taskIdLabel:"任务 ID",turnHeading:"第 {{index}} 轮",questionLabel:"问题",answerLabel:"回答",createdLabel:"创建时间",emptyQuestion:"(空问题)",emptyAnswer:"(尚无助手文本回复)",emptyNoMessages:"此任务尚无用户消息,无可展示内容。",previewDocumentTitle:"任务问答"},showPrompt:{previewDocumentTitle:"系统提示",previewHeading:"系统提示"},shellHint:"使用 '/shell <命令>' 执行 shell 命令(例如:'/shell ls -la')。",replIntroDialog:"对话模式:仅只读工具 — `/shell` 已禁用。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",replIntroPlan:"计划模式:每次回复写入项目目录下的 `<slug>-plan.md`(请求首行影响文件名)。`/shell` 已禁用;计划完成前输出保持精简。`/list`、`/select`、`/show`、`/show-task`、`/show-prompt` 可用于已持久化任务。`/list-skill`、`/install-skill`、`/remove-skill` 管理技能(ClawHub)。",newSessionHint:"使用 '/new <请求>' 开始新会话(不读取聊天历史)。",newSessionNoHistory:"使用新会话(无聊天历史)。",controlHint:"按 Ctrl+S 停止正在运行的代理,按 Ctrl+P 暂停并进入子命令模式。",replTabCompletionHint:"按 Tab 键可补全以 / 开头的命令(如 /list、/list-skill),或补全 exit、quit。",tuiScrollTranscriptHint:"全屏终端:鼠标滚轮、方向键、PgUp/PgDn、Ctrl+U/Ctrl+F(翻页)。Ctrl+U/F 用于滚动日志。Ctrl+D 仍为清空行退出或输入时向前删除。",agentStopped:"代理已停止。",pauseHeader:"--- 代理已暂停 ---",pauseCurrentRequest:"当前请求:{{request}}",pauseHelp:"命令:'continue' 或 'c' 继续执行,'exit' 或 'e' 退出,或输入新请求替换当前请求。",pausePrompt:"[已暂停] ",pauseRequestUpdated:"请求已更新为:{{request}}"},shell:{noCommand:"/shell 前缀后未提供命令。用法:/shell <命令>",executionError:"执行 shell 命令时出错:{{error}}",executing:"[shell] 执行中:{{command}}",errorNoCommand:"/shell 前缀后未提供命令。",errorSpawnFailed:"启动进程失败:{{message}}",errorTimedOut:"命令在 {{seconds}} 秒后超时",logFailed:"Shell 命令失败:{{command}}(退出码:{{code}})",logExecutionError:"Shell 命令执行错误:{{message}}",resultCommand:"命令:{{command}}",resultExitCode:"退出码:{{code}}",resultExitCodeNa:"N/A",resultSuccessLabel:"成功:",resultSuccessYes:"是",resultSuccessNo:"否",resultOutput:"输出:",resultError:"错误:"},init:{invalidType:'无效的 --type "{{value}}";可选:{{choices}}',invalidLang:'无效的 --lang "{{value}}";可选:{{choices}}',templatesDirNotFound:"未找到模板目录:{{dir}}",createdPromptTemplates:"已创建 {{dir}}(提示模板)",createdSessions:"已创建 {{dir}}(会话历史)",initialized:"已在 {{targetDir}} 中初始化 {{type}} 项目",promptFilesIn:"提示文件位于 {{pithosaiDir}},会话数据位于 {{sessionsDir}}",runHint:'运行 "pithosai -C {{targetDir}} \\"你的请求\\"" 开始。',createdFile:"已创建 {{path}}",roleAlreadyAdded:"角色 {{role}} 已存在于 .pithosai,跳过。",addedRoleTemplates:"已将角色模板添加到 {{dir}}"},tools:{listFiles:{result:"list_files:已在 {{path}} 下列出 {{count}} 个条目"},playwrightView:{result:"playwright_view_markdown:预览已关闭({{source}})",skipped:"已跳过浏览器预览(PITHOSAI_SKIP_RESULT_BROWSER=1)",errorNoSource:"请只提供 markdown 或 path 其中之一(不能同时提供或都省略)。",errorEmpty:"Markdown 内容为空。",errorFileOutside:"path 必须位于项目目录下。",errorNotAFile:"path 不是普通文件。",errorFileTooLarge:"文件超过 {{maxBytes}} 字节。",errorFileRead:"无法读取文件:{{message}}",sourceInline:"内联 Markdown",sourceFile:"文件 {{path}}"}},heartbeat:{started:"心跳已启动(每 {{interval}} 秒轮询)。检查邮件主题前缀「task:」或「任务:」。",startedIdle:"心跳已启动(IMAP IDLE),角色 {{role}}。等待新邮件。",imapClosedShutdown:"心跳 IMAP 连接已关闭;正在关闭进程。",imapError:"心跳 IMAP 错误:{{message}}",imapDisconnectedReconnect:"心跳 IMAP 已断开;{{ms}} 毫秒后重连",imapOpenBoxError:"心跳 IMAP openBox 错误:{{message}}",onNewMailError:"心跳 onNewMail 错误:{{message}}",runningTask:"心跳:正在执行任务 {{subject}}",emailRequired:"心跳的邮箱不能为空。请在 sqlite3 数据库的 email_roles 表中配置角色 {{role}} 的邮箱。",loadedState:"已从 SQLite 加载心跳状态,邮箱 {{email}},角色 {{role}},状态:{{states}}",fetchFound:"心跳拉取收件箱发现 {{count}} 个新任务:{{ids}}",savedState:"已将心跳状态保存到 SQLite,邮箱 {{email}},角色 {{role}}",mergedAndNext:"已合并 {{merged}} 个任务到状态,下一个待处理:{{stateSummary}}",replyEmailFailed:"心跳回复邮件发送失败:{{error}}",taskFailed:"心跳任务执行失败:{{error}}",failureReplyEmailFailed:"心跳失败通知邮件发送失败:{{error}}"},cli:{description:"Pithosai:根据自然语言请求实现代码或项目。角色提示在运行时从 SQLite 数据库加载(可选回退到 .pithosai/<role>/*.md)。使用 'pithosai init' 创建项目。",versionOption:"输出版本号",roleOption:"角色(init 使用的模板集);模板位于 templates/<role>/",langOption:"提示与 init 模板语言:en、zh(默认:en)",interactiveModeOption:"无请求时进入交互模式;显示模式说明并提示输入",initDescription:"创建新项目及 .pithosai/ 目录结构。角色提示在运行时从 SQLite 数据库加载(可选回退到 .pithosai/<role>/*.md)。",initTypeOption:"项目类型:js、ts 或 python",initExamples:"\n示例:\n pithosai init\n pithosai init my-app --type js\n pithosai init --lang zh\n pithosai init ./backend --type ts --lang zh\n",addRoleDescription:"将角色模板添加到项目中的 .pithosai/<role>/",addRoleArgument:"要添加的角色(如 PM、QA)",requestArgument:'要构建的内容(例如 "将 CSV 转为 JSON 的 CLI")。省略则显示帮助。',cwdOption:"项目目录(默认:当前目录)",skillsDirOption:"read_skill 技能目录(默认:./.pithosai/skills 或 PITHOSAI_SKILLS_DIR)",reasonerOption:"使用 DeepSeek Reasoner(思考)模型;默认为 DeepSeek Coder",chatOption:"使用 DeepSeek Chat 模型(通用对话,非代码);默认为 DeepSeek Coder",cursorOption:"使用 Cursor CLI 模型(通过 cursor-agent login 认证,无需 API 密钥)。可指定模型:auto, sonnet-4.6, opus-4.6, gpt-5.2",timeoutOption:"Agent 最长运行时间(秒,默认 1800)。可用 PITHOSAI_TIMEOUT_MS(毫秒)覆盖。",interactiveOption:"禁用交互提示(默认:每次回复后询问下一条消息)",modeOption:"运行模式:agent(默认,可使用工具)、dialog(仅回答,无工具)、plan(仅将计划写入项目根目录 <slug>-plan.md,无工具)",shellDisabledInMode:"在 dialog 与 plan 模式下已禁用 /shell 命令。",planWritten:"计划已写入 {{path}}",planRunning:"正在生成计划…",waitingReply:"正在等待回复…",runningReply:"正在运行…",resultPreviewOpening:"正在浏览器中打开结果预览…",resultPreviewTitle:"Pithosai 结果",resultPreviewFailed:"无法打开结果预览:{{message}}",resultPreviewCopy:"复制 Markdown",resultPreviewClose:"关闭",resultPreviewCopied:"已复制到剪贴板",resultPreviewTerminalHint:"↑↓ 或 j/k \xb7 PgUp/PgDn 或 Ctrl+U/Ctrl+D \xb7 Home/End 或 gg/G \xb7 q/Esc 关闭",runExamples:'\n示例:\n pithosai "添加返回当前时间的 REST 接口"\n pithosai -C ./my-app "运行测试并修复失败"\n pithosai -i # 交互模式:加载最新会话后提示输入\n pithosai --no-interactive "单次" # 单次回复,无后续提示\n pithosai --mode dialog "解释这个错误" # 仅对话;无工具与 /shell\n pithosai --mode plan "api sprint plan" # 写入例如 api-sprint-plan-plan.md\n',helpUsage:"用法:",helpArguments:"参数:",helpOptions:"选项:",helpCommands:"命令:",helpGlobalOptions:"全局选项:",helpOption:"显示命令帮助",heartbeatDescription:"轮询收件箱中任务邮件(主题「task:...」或「任务:...」),入队并逐个执行。状态保存在 ~/.pithosai/heartbeat-state.json。",heartbeatIntervalOption:"轮询间隔(秒,默认 60)",heartbeatOnceOption:"只运行一次(拉取邮件并处理一个任务后退出)",taskDescription:"监听任务文件并在同一进程内逐个处理任务",taskFileOption:"任务 Markdown 文件路径(默认:项目根目录下的 prompts.md)",taskModelOption:"任务使用的模型键(deepSeekCoder、deepSeekChat、deepSeekReasoner、ollamaQwen25、ollamaQwen25Coder、ollamaDeepSeekR1、cursorAutoModel、cursorSonnet、cursorSonnetThinking、cursorOpus、cursorGpt)",taskNewSessionOption:"使用新会话(无聊天记录)",taskExamples:"\n示例:\n $ pithosai task\n $ pithosai task --file ./my-tasks.md\n $ pithosai task --file /path/to/prompts.md --role RD --timeout 120\n $ pithosai task --model cursorSonnet --new-session\n $ pithosai task -f ./tasks.md --model deepSeekChat --timeout 300",taskNotFound:"未找到任务:{{taskId}}",taskAgentCompleted:"Agent 已完成。",taskAgentRunFailed:"Agent 运行失败。",taskDone:"完成",taskFailed:"任务失败:{{message}}",taskProcessingHeader:"--- 正在处理任务 ---",taskLabelId:"id:",taskLabelTitle:"标题:",taskLabelStatus:"状态:",taskLabelDescription:"描述:",taskProcessingSeparator:"------------------------",taskStartingProcessorProcessing:"正在为处理中任务 {{id}}({{title}})启动处理器。",taskNoPending:"没有待处理任务。",taskPickedTask:"已选择任务 {{id}}({{title}});正在启动处理器。",taskProcessorFailed:"任务处理器失败:{{message}}",taskWatcherRunning:"任务监视器运行中。按 Ctrl+C 停止。",showPromptDescription:"显示运行时会使用的系统提示",showPromptModeOption:"模式:agent、dialog 或 plan(默认:agent)",showPromptRawOption:"显示截断和工具块之前的原始提示",showPromptTruncatedOption:"显示截断后的提示(需要模型配置)",showPromptInvalidMode:"无效模式。必须是 'agent'、'dialog' 或 'plan'。",showPromptError:"构建提示时出错:{{message}}",memorizeDescription:"根据日期范围内该角色参与的任务(持久化的任务消息)生成摘要,写入 .pithosai/<role>/memory.md。",memorizeStartOption:"范围开始:YYYY-MM-DD 或 ISO 日期时间",memorizeEndOption:"范围结束:YYYY-MM-DD 或 ISO 日期时间",memorizeRoleRequired:"必须指定角色(使用 -r/--role 或全局 --role)。",memorizeWrote:"已写入 {{path}}(共 {{count}} 个任务)。",memorizeNoTasks:"角色 {{role}} 在范围内无任务;已写入头部到 {{path}}。",memorizeDateError:"日期范围无效:{{message}}",memorizeNoLlmOption:"跳过 LLM 摘要,仅写入结构化记忆(等同于 PITHOSAI_MEMORIZE_SKIP_LLM=1)。",memorizeLlmFallback:"LLM 摘要失败({{message}});已写入未摘要的结构化记忆。",memorizeExamples:"\n示例:\n pithosai memorize --start 2026-01-01 --end 2026-01-31 -r RD\n pithosai -r PM memorize --start 2026-04-01 --end 2026-04-10\n pithosai memorize --start 2026-04-01 --end 2026-04-30 -r RD --chat\n",migrateDbDescription:"将旧版明文 pithosai.db(例如 v1.0.4)升级为 SQLCipher。使用与应用运行时相同的设备绑定密钥(参见 docs/device-id.md)。可重复执行。",migrateDbDbPathOption:"SQLite 数据库文件路径(默认:若设置了 PITHOSAI_DB_PATH 则使用该路径,否则为 ~/.pithosai/pithosai.db)",migrateDbMigrated:"数据库文件已迁移为 SQLCipher 格式。",migrateDbSkippedAlready:"数据库已使用当前密钥加密,无需迁移。",migrateDbSkippedMissing:"路径 {{path}} 下没有数据库文件,未执行任何操作。",migrateDbSkippedNotPlain:"该文件不是可读的旧版明文 SQLite,或使用了其他密钥,未做修改。",migrateDbErrNoSqlcipher:"当前 Node 环境无法加载 SQLCipher 原生模块。请为当前平台安装或编译 @journeyapps/sqlcipher 后再试。"},shellTips:{description:"根据请求获取 shell 命令(仅 Ollama,仅输出命令)",argument:"你想做什么(例如列出当前目录中的大文件)",loading:"正在获取命令…",examples:'\n示例:\n $ pithosai shell-tips 列出当前目录下的 json 文件\n $ pithosai shell-tips "在所有 .js 文件中将 foo 替换为 bar"'},writer:{description:"根据请求生成文本(Ollama qwen2.5:14b)",argument:"要写什么(例如简短拒绝会议的邮件)",loading:"正在撰写…",examples:'\n示例:\n $ pithosai writer 简短拒绝会议的邮件\n $ pithosai writer "项目启动会三个要点"'},skills:{installing:"正在安装技能到 {{dir}}",fetchingList:"正在从 ClawHub 获取可用技能...",fetchingIndex:"正在从 {{url}} 获取技能索引",notFound:"未找到技能 '{{name}}'",noSkillsAvailable:"ClawHub 中没有可用技能",noSkillsFound:"未找到任何技能",downloadFailed:"下载技能 '{{name}}' 失败:{{error}}",installed:"已安装技能 '{{name}}'",complete:"安装完成:已安装 {{count}} 个技能,共 {{total}} 个",alreadyInstalled:"技能 '{{name}}' 已安装(使用 --force 重新安装)",downloading:"正在从 {{url}} 下载技能 '{{name}}'",noSkillsDir:"未找到技能目录。请先安装技能。",noSkillsInstalled:"未安装任何技能",installedList:"已安装技能(共 {{count}} 个)在 {{dir}}:",notInstalled:"技能 '{{name}}' 未安装",removed:"已移除技能 '{{name}}'"},skillConvert:{welcome:"技能转换系统 - 将成功的技能转换为永久工具",listHeader:"技能转换分析({{totalSkills}} 个技能,{{totalExecutions}} 次执行)",noSuggestions:"没有技能达到转换阈值 {{threshold}}。",suggestedConversions:"建议转换的技能:",convertHint:"使用 'pithosai skill-convert convert <技能名称>' 转换技能。",skillNotFound:"未找到技能 '{{skillName}}' 或无法读取:{{error}}",alreadyConverted:"技能 '{{skillName}}' 已转换为工具。",useForceHint:"使用 --force 强制重新转换。",conversionReportHeader:"'{{skillName}}' 转换报告:",conversionScore:"转换分数",suggestedType:"建议类型",ready:"准备转换",estimatedBenefits:"预计收益",performance:"性能提升",reliability:"可靠性提升",usability:"可用性提升",parameters:"参数",notReadyWarning:"此技能尚未准备好自动转换。",moreUsageHint:"请更频繁地使用该技能,或使用 --force 强制转换。",dryRunComplete:"模拟运行完成。未进行任何更改。",confirmConversion:"将 '{{skillName}}' 转换为永久工具?",conversionCancelled:"转换已取消。",converting:"正在将 '{{skillName}}' 转换为工具...",conversionSuccess:"成功将 '{{skillName}}' 转换为 '{{toolName}}'。\n工具保存到:{{toolPath}}",usageExample:"使用示例:",nextSteps:"后续步骤:",restartAgent:"重启代理以加载新工具",testTool:"测试工具:<工具名称> --help",manageTools:"管理工具:pithosai skill-convert tools",listError:"列出技能时出错:{{error}}",conversionError:"转换 '{{skillName}}' 时出错:{{error}}",skillStatsHeader:"'{{skillName}}' 统计信息:",generalStats:"常规统计",totalExecutions:"总执行次数",successful:"成功",failed:"失败",avgTime:"平均执行时间",lastUsed:"最后使用",recentExecutions:"最近执行",commonParameters:"常用参数",overallStatsHeader:"整体技能统计",overallStats:"整体统计",totalSkillsTracked:"跟踪的技能总数",avgSuccessRate:"平均成功率",topSkills:"使用最多的技能",conversionSuggestions:"转换建议",statsError:"获取统计信息时出错:{{error}}",confirmClearAll:"清除所有技能执行记录?此操作不可撤销。",allRecordsCleared:"所有技能执行记录已清除。",skillRecordsCleared:"'{{skillName}}' 的技能执行记录已清除。",clearCancelled:"清除操作已取消。",specifySkillOrAll:"请指定技能名称或使用 --all",clearError:"清除记录时出错:{{error}}",noConvertedTools:"未找到转换的工具。",convertedToolsHeader:"已转换的工具:",originalSkill:"原始技能",converted:"转换时间",usageCount:"使用次数",toolsError:"管理工具时出错:{{error}}",confirmRemoveTool:"移除工具 '{{toolName}}'?",toolRemoved:"工具 '{{toolName}}' 已移除。",toolRemoveFailed:"移除工具 '{{toolName}}' 失败。",removeCancelled:"工具移除已取消。",toolEnabled:"工具 '{{toolName}}' 已启用。",toolEnableFailed:"启用工具 '{{toolName}}' 失败。",toolDisabled:"工具 '{{toolName}}' 已禁用。",toolDisableFailed:"禁用工具 '{{toolName}}' 失败。",noStatsForSkill:"未找到技能 '{{skillName}}' 的统计信息。"},hooks:{description:"管理代理钩子,用于调试、安全和监控",list:{description:"列出所有已注册的钩子",title:"\uD83D\uDCCB 已注册的钩子",total:"总计:{{total}} 个处理器",options:{verbose:"显示详细的处理器信息"},error:"列出钩子失败:{{error}}"},debug:{description:"启用调试钩子以监控代理行为",options:{data:"在调试输出中记录完整数据",performance:"启用性能监控钩子",stats:"启用统计收集钩子",all:"启用所有调试钩子"},added:{debug:"已添加调试日志钩子",performance:"已添加性能监控钩子",stats:"已添加统计收集钩子",basic:"已添加基本调试钩子"},success:"调试钩子已启用({{count}} 个处理器已注册)",error:"启用调试钩子失败:{{error}}"},security:{description:"启用安全钩子进行访问控制和监控",options:{block:"要阻止的工具列表,用逗号分隔",maxPrompt:"最大允许的提示长度(默认:10000)"},success:"安全钩子已启用",blockedTools:"已阻止的工具:{{tools}}",maxPrompt:"最大提示长度:{{length}} 个字符",error:"启用安全钩子失败:{{error}}"},clear:{description:"清除所有已注册的钩子",success:"所有钩子已清除",error:"清除钩子失败:{{error}}"},test:{description:"使用测试数据触发钩子进行测试",argument:{hookType:"要测试的特定钩子类型(可选)"},invalidType:"无效的钩子类型:{{type}}",triggered:"已触发钩子:{{type}}",result:"结果:{{result}}",allTriggered:"所有钩子已成功触发",error:"测试钩子失败:{{error}}"},register:{description:"从文件注册自定义钩子处理器",argument:{hookType:"要注册处理器的钩子类型",handlerFile:"处理器文件路径(必须导出默认函数)"},invalidType:"无效的钩子类型:{{type}}",invalidHandler:"处理器文件必须导出一个默认函数",success:"已为 {{type}} 注册来自 {{file}} 的处理器",error:"注册钩子失败:{{error}}"},status:{description:"显示当前钩子配置和统计信息",title:"\uD83D\uDCCB 钩子状态",error:"获取钩子状态失败:{{error}}"}}}},8476(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Cm:()=>n.C,Ts:()=>n.T});var a=r(2883),o=r(9320),n=r(9188),s=e([a,o,n]);[a,o,n]=s.then?(await s)():s,i()}catch(e){i(e)}})},9188(e,t,r){r.a(e,async function(e,i){try{r.d(t,{C:()=>h,T:()=>m});var a=r(6760),o=r(1455),n=r(5012),s=r(4071),l=r(4399),d=r(8362),c=r(4768),u=r(9320),p=e([u,d,s,c]);async function m(e,t={}){let r=!0===t.noExit,i=(0,a.resolve)(e||"."),l=(t.lang||"en").toLowerCase(),p=(0,d.l)(l),h=(t.type||"js").toLowerCase();if(!n.Av.includes(h)){let e=p("init.invalidType",{value:t.type??"",choices:n.Av.join(", ")});if((0,s.vV)(e),r)throw Object.assign(Error(e),{exitCode:n.dc.USAGE});process.exit(n.dc.USAGE)}if(!n.Lq.includes(l)){let e=p("init.invalidLang",{value:t.lang??"",choices:n.Lq.join(", ")});if((0,s.vV)(e),r)throw Object.assign(Error(e),{exitCode:n.dc.USAGE});process.exit(n.dc.USAGE)}let g=t.role||"RD",f=(0,a.basename)(i);await (0,o.mkdir)(i,{recursive:!0}),await (0,u.Y)({targetDir:i,type:h,projectName:f,t:p,role:g});let k=(0,a.join)(i,".pithosai","sessions");await (0,o.mkdir)(k,{recursive:!0}),(0,s.fH)(p("init.createdSessions",{dir:k})),await (0,c.L)(i,{lang:l,project:{type:h,name:f,cwd:i},supportedRoles:[g],tools:{web:{fetch:{enabled:!0},search:{enabled:!0}}}}),(0,s.fH)(p("init.initialized",{type:h,targetDir:i})),(0,s.fH)(p("init.promptFilesIn",{pithosaiDir:(0,a.join)(i,".pithosai"),sessionsDir:k})),(0,s.fH)(p("init.runHint",{targetDir:i}))}async function h(e,t,r="en",i){let u=(0,a.resolve)(e),p=i??(0,d.l)(r),m=(0,l.mi)(t);try{await (0,o.access)(m)}catch{(0,s.vV)(p("init.templatesDirNotFound",{dir:m})),process.exit(n.dc.CONFIG)}let g=await (0,c.s)(u),f=g?.supportedRoles??[];f.includes(t)||(f.push(t),await (0,c.L)(u,{...g,supportedRoles:f}))}[u,d,s,c]=p.then?(await p)():p,i()}catch(e){i(e)}})},9320(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Y:()=>d});var a=r(6760),o=r(1455);r(5012);var n=r(4071),s=e([n]);function l(e){let t=".pithosai/\nlogs/\n\n",r="node_modules/\n.env\ncoverage/\n*.log\nnpm-debug.log*\n.DS_Store";return"python"===e?t+"__pycache__/\n*.py[cod]\n*$py.class\n.env\nvenv/\n.venv/\n.pytest_cache/\n.mypy_cache/\n*.egg-info/\n.eggs/\ndist/\nbuild/":"ts"===e?t+r+"\ndist/\n":t+r}async function d(e){let{targetDir:t,type:r,projectName:i,t:s,role:d="RD"}=e,c=i||(0,a.dirname)(t)||"project";if("PM"===d||"QA"===d||"CO"===d||"MKT"===d||"SRE"===d){let e=`# Requirements
|
|
509
378
|
|
|
510
379
|
Describe your requirements here.
|
|
511
|
-
`,
|
|
512
|
-
`;for(let
|
|
513
|
-
`}
|
|
380
|
+
`,r=(0,a.join)(t,"rules");await (0,o.mkdir)(r,{recursive:!0});let i=(0,a.join)(r,"requirements.md");await (0,o.writeFile)(i,e),(0,n.fH)(s("init.createdFile",{path:i}));return}if("js"===r||"ts"===r){let e={name:c.replace(/\s+/g,"-").toLowerCase(),version:"1.0.0",description:"",type:"module",main:"ts"===r?"dist/index.js":"index.js",scripts:{start:"ts"===r?"node dist/index.js":"node index.js",build:"ts"===r?"tsc":void 0},..."ts"===r&&{devDependencies:{typescript:"^5.0.0"}}};e.scripts?.build===void 0&&delete e.scripts.build,await (0,o.writeFile)((0,a.join)(t,"package.json"),JSON.stringify(e,null,2)),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,"package.json")})),"ts"===r?(await (0,o.writeFile)((0,a.join)(t,"tsconfig.json"),JSON.stringify({compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",outDir:"dist",rootDir:"src",strict:!0},include:["src/**/*"]},null,2)),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,"tsconfig.json")})),await (0,o.mkdir)((0,a.join)(t,"src"),{recursive:!0}),await (0,o.writeFile)((0,a.join)(t,"src","index.ts"),'console.log("Hello, world");\n'),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,"src","index.ts")}))):(await (0,o.writeFile)((0,a.join)(t,"index.js"),'console.log("Hello, world");\n'),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,"index.js")}))),await (0,o.writeFile)((0,a.join)(t,".gitignore"),l(r)),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,".gitignore")}))}"python"===r&&(await (0,o.writeFile)((0,a.join)(t,"requirements.txt"),"# Add dependencies here\n"),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,"requirements.txt")})),await (0,o.writeFile)((0,a.join)(t,"main.py"),'def main():\n print("Hello, world")\n\n\nif __name__ == "__main__":\n main()\n'),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,"main.py")})),await (0,o.writeFile)((0,a.join)(t,".gitignore"),l(r)),(0,n.fH)(s("init.createdFile",{path:(0,a.join)(t,".gitignore")})))}n=(s.then?(await s)():s)[0],i()}catch(e){i(e)}})},2883(e,t,r){r.a(e,async function(e,t){try{r(6760),r(3024),r(1455),r(4399),r(5012);var i=r(4071),a=e([i]);i=(a.then?(await a)():a)[0],t()}catch(e){t(e)}})},3327(e,t,r){r.a(e,async function(e,i){try{r.d(t,{$:()=>s,x:()=>l});var a=r(8641),o=e([a]);function n(e,t){let r=String(e??"");return r.length<=t?r:`${r.slice(0,t)}…`}function s(e){let t=[];for(let r of e){let e=function(e){try{return JSON.parse(e)}catch{return{role:"assistant",content:[{type:"text",text:n(e,800)}]}}}(r.message),i=(0,a.u7)(e);i&&i.trim()&&t.push(i.trim())}return n(t.join("\n"),1200)}function l({role:e,entries:t}){let r=[`## ${e} memory`,""];if(0===t.length)return r.push("_No tasks with persisted activity for this role in the selected date range._",""),`${r.join("\n").trimEnd()}
|
|
381
|
+
`;for(let a of t){var i;let{taskId:t,title:o,status:s,description:l,contributionSummary:d}=a;r.push(`### ${t}`),r.push(`title: ${o}`);let c=l?n(l.trim(),400):"",u=function(e){let{status:t}=e;return"completed"===t?"Capture any follow-ups or lessons learned in the backlog or docs.":"failed"===t?"Review errors, narrow scope if needed, and retry with clearer acceptance criteria.":"processing"===t?"Resolve blocking issues or let the current run finish before expanding scope.":"Drive the task to completion and verify acceptance criteria."}({status:s}),p=[`Current status: ${s}. ${(i={status:s},"completed"===i.status?"Finished successfully.":"failed"===i.status?"Ended with failure.":"processing"===i.status?"Currently in progress.":"Not finished yet (pending or other status).")}`,c?`Task context (excerpt): ${c}`:null,d?`Contribution (${e}): ${d}`:`Contribution (${e}): (no assistant text extracted from stored messages)`,`Improvement: ${u}`].filter(Boolean).join(" ");r.push(p),r.push("")}return`${r.join("\n").trimEnd()}
|
|
382
|
+
`}a=(o.then?(await o)():o)[0],i()}catch(e){i(e)}})},465(e,t,r){r.d(t,{v:()=>a});let i=/^\d{4}-\d{2}-\d{2}$/;function a(e,t){let r,a,o=String(e??"").trim(),n=String(t??"").trim();if(!o||!n)throw Error("start and end are required");if(i.test(o))r=`${o}T00:00:00.000Z`;else{let e=new Date(o);if(Number.isNaN(e.getTime()))throw Error("invalid start date");r=e.toISOString()}if(i.test(n))a=`${n}T23:59:59.999Z`;else{let e=new Date(n);if(Number.isNaN(e.getTime()))throw Error("invalid end date");a=e.toISOString()}if(r>a)throw Error("start must be before or equal to end");return{startIso:r,endIso:a}}},6354(e,t,r){r.a(e,async function(e,i){try{r.d(t,{V:()=>l});var a=r(4820),o=e([a]);a=(o.then?(await o)():o)[0];let d=`You turn structured role memory (tasks, contributions, status) into a short, readable summary for a software project.
|
|
514
383
|
|
|
515
384
|
Output markdown only. The first heading must be exactly: ## {role} memory (use the role from the user message).
|
|
516
385
|
|
|
@@ -530,10 +399,10 @@ Do not wrap the whole document in a code fence. No preamble before the first ##
|
|
|
530
399
|
- **后续 / 待办**:尚待完成的事项、风险、未决问题,或针对该角色的建议下一步。
|
|
531
400
|
|
|
532
401
|
使用简洁的条目或短段落。若某节无话可说,可省略或写一行(例如「无待跟进事项。」)。
|
|
533
|
-
不要用代码围栏包裹整篇文档。第一个 ## 标题前不要写任何前言。`;function
|
|
402
|
+
不要用代码围栏包裹整篇文档。第一个 ## 标题前不要写任何前言。`;function n(e){return String(e??"").toLowerCase().startsWith("zh")}async function s(e,t,r){let i,a=`${e.baseUrl.replace(/\/$/,"")}/chat/completions`,o=JSON.stringify({model:e.id,messages:r,stream:!1,max_tokens:e.maxTokens??8192});for(let e=1;e<=4;e++)try{let e=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t?`Bearer ${t}`:""},body:o,signal:AbortSignal.timeout(18e4)});if(!e.ok){let t=await e.text();throw Error(`Chat API error ${e.status}: ${t}`)}let r=await e.json(),i=r?.choices?.[0]?.message?.content;if(null==i)throw Error("Chat API returned no content");return"string"==typeof i?i:String(i)}catch(t){if(i=t,!(e<4&&null!=t&&"object"==typeof t&&("name"in t&&"AbortError"===t.name||"code"in t&&"string"==typeof t.code&&("ETIMEDOUT"===t.code||"UND_ERR_CONNECT_TIMEOUT"===t.code))))throw t}throw i instanceof Error?i:Error(String(i))}async function l({markdown:e,role:t,modelOpts:r={},lang:i}){let o=e.length<=12e4?e:`${e.slice(0,12e4)}
|
|
534
403
|
|
|
535
404
|
_[… truncated for LLM input …]_
|
|
536
|
-
`,l=(0,
|
|
405
|
+
`,l=(0,a.Al)(r);if(!l)throw Error("No model configured (API keys, --cursor, or local Ollama — same as `pithosai` run).");let{model:u,getApiKey:p}=l,m=await p(),h=function({role:e,body:t,lang:r}){return n(r)?`角色:${e}
|
|
537
406
|
|
|
538
407
|
请将以下结构化记忆按你在系统说明中的格式整理为摘要:
|
|
539
408
|
|
|
@@ -541,14 +410,14 @@ ${t}`:`Role: ${e}
|
|
|
541
410
|
|
|
542
411
|
Structured memory to summarize into the format described in your instructions:
|
|
543
412
|
|
|
544
|
-
${t}`}({role:t,body:o,lang:
|
|
545
|
-
`}
|
|
413
|
+
${t}`}({role:t,body:o,lang:i}),g=(await s(u,m,[{role:"system",content:n(i)?c:d},{role:"user",content:h}])).trim();if(!g)throw Error("Empty model response");return g.endsWith("\n")?g:`${g}
|
|
414
|
+
`}i()}catch(e){i(e)}})},4820(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Al:()=>u,aN:()=>c});var a=r(785),o=r(5e3),n=r(1576),s=r(9068),l=r(7817),d=e([s,a,l]);function c(e={}){let t=!0===e.reasoner,r=!0===e.chat,i=(process.env.CURSOR_MODEL||"").trim(),l=e.cursor;if(l){(0,s.VL)();let e="auto";return"string"==typeof l&&l?e=l:i&&(e=i),{model:s.Ei[e]||{...s.PR,id:e},getApiKey:async()=>"cursor-cli-no-key"}}if(e.local)return{model:(e.modelId&&n.wc[e.modelId])??n.ZU,getApiKey:async()=>"ollama"};let d=(process.env.DEEPSEEK_API_KEY||"").trim(),u=(process.env.OPENROUTER_API_KEY||"").trim();if(d)return{model:t?o.pE:r?o.Eq:o.rz,getApiKey:async()=>d};let p=(process.env.OPENAI_LOCAL_API_BASE||"").trim(),m=(process.env.OPENAI_LOCAL_API_KEY||"").trim();if(p.length>0||m.length>0){let e=p||n.lE,t=m||"ollama";return{model:{...n.ZU,baseUrl:e.replace(/\/$/,"")||e},getApiKey:async()=>t}}return u?{model:(0,a.getModel)("openrouter",t?"deepseek/deepseek-reasoner":"deepseek/deepseek-chat"),getApiKey:async()=>u}:null}function u(e){let t=e?.model,r=null!=t&&""!==String(t).trim()?String(t).trim():null;return null!=r?function(e,t){let r=t[e];if(!r)return null;if(e.startsWith("cursor"))return(0,s.VL)(),{model:r,getApiKey:async()=>"cursor-cli-no-key"};if(e.startsWith("deepSeek")){let e=(process.env.DEEPSEEK_API_KEY||"").trim();return e?{model:r,getApiKey:async()=>e}:null}return e.startsWith("ollama")?{model:r,getApiKey:async()=>"ollama"}:null}(r,l.q):c({reasoner:e?.reasoner===!0,chat:e?.chat===!0,cursor:e?.cursor})}[s,a,l]=d.then?(await d)():d,i()}catch(e){i(e)}})},9068(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Ei:()=>w,Lv:()=>k,Ny:()=>h,PR:()=>m,VL:()=>d,ff:()=>f,pS:()=>g});var a=r(1421);r(8161),r(6760);var o=r(785),n=e([o]);o=(n.then?(await n)():n)[0];let c="cursor-cli",u="cursor",p={input:0,output:0,cacheRead:0,cacheWrite:0},m={id:"auto",name:"Cursor Auto",api:c,provider:u,baseUrl:"",reasoning:!1,input:["text"],cost:p,contextWindow:2e5,maxTokens:16384},h={id:"sonnet-4.6",name:"Cursor Sonnet 4.6",api:c,provider:u,baseUrl:"",reasoning:!1,input:["text"],cost:p,contextWindow:2e5,maxTokens:16384},g={id:"sonnet-4.6-thinking",name:"Cursor Sonnet 4.6 Thinking",api:c,provider:u,baseUrl:"",reasoning:!0,input:["text"],cost:p,contextWindow:2e5,maxTokens:16384},f={id:"opus-4.6",name:"Cursor Opus 4.6",api:c,provider:u,baseUrl:"",reasoning:!1,input:["text"],cost:p,contextWindow:2e5,maxTokens:16384},k={id:"gpt-5.2",name:"Cursor GPT 5.2",api:c,provider:u,baseUrl:"",reasoning:!1,input:["text"],cost:p,contextWindow:128e3,maxTokens:16384},w={auto:m,"sonnet-4.6":h,"sonnet-4.6-thinking":g,"opus-4.6":f,"gpt-5.2":k},v="<<TOOL_CALL_BEGIN>>",y="<<TOOL_CALL_END>>",b="<<TOOL_USE_STOP>>";function s(e){if(!e)return e;let t="<|DSML|function_calls>",r="</|DSML|function_calls>",i=e;for(;;){let e=i.indexOf(t);if(-1===e)break;let a=i.indexOf(r,e+t.length);if(-1===a)break;i=i.slice(0,e)+i.slice(a+r.length)}for(let e of["<|DSML|","</|DSML|"])for(;;){let t=i.indexOf(e);if(-1===t)break;let r=i.indexOf(">",t);if(-1===r)break;i=i.slice(0,t)+i.slice(r+1)}return i}function l(e,t,r){let i=(0,o.createAssistantMessageEventStream)();return(async()=>{let o=Array.isArray(t?.tools)&&t.tools.length>0,n={role:"assistant",content:[],api:c,provider:u,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},l={type:"text",text:""},d=e.reasoning?{type:"thinking",thinking:""}:null;try{let c=function(e){if(!e||0===e.length)return"";let t=e.map(e=>{let t=e.parameters&&"object"==typeof e.parameters?JSON.stringify(e.parameters):"{}";return`### ${e.name}
|
|
546
415
|
Description: ${e.description}
|
|
547
416
|
Parameters (JSON Schema): ${t}`}).join("\n\n");return`
|
|
548
417
|
<available_tools>
|
|
549
418
|
You have the following tools available. When you need to use a tool, output a tool call using EXACTLY this format (one per call, each on its own line):
|
|
550
419
|
|
|
551
|
-
${
|
|
420
|
+
${v}{"id":"call_<n>","name":"<tool_name>","arguments":{<args>}}${y}
|
|
552
421
|
|
|
553
422
|
Replace <n> with a sequential number starting from 1, <tool_name> with the tool name, and <args> with the JSON arguments.
|
|
554
423
|
|
|
@@ -558,43 +427,44 @@ ${b}
|
|
|
558
427
|
IMPORTANT: Output tool calls as shown above. Do NOT wrap them in markdown code fences.
|
|
559
428
|
|
|
560
429
|
${t}
|
|
561
|
-
</available_tools>`}(t.tools),{systemPrompt:u,messages:p}=function(e){let t=Array.isArray(e?.messages)?e.messages:[];if("string"==typeof e?.systemPrompt&&e.systemPrompt.length>0)return{systemPrompt:e.systemPrompt,messages:t};if("string"==typeof e?.system&&e.system.length>0)return{systemPrompt:e.system,messages:t};if(t.length>0&&t[0]?.role==="system"){let e=t[0];return{systemPrompt:("string"==typeof e.content?e.content:Array.isArray(e.content)?e.content.filter(e=>e?.type==="text").map(e=>e.text).join("\n"):"")||"",messages:t.slice(1)}}return{systemPrompt:"",messages:t}}(t),
|
|
430
|
+
</available_tools>`}(t.tools),{systemPrompt:u,messages:p}=function(e){let t=Array.isArray(e?.messages)?e.messages:[];if("string"==typeof e?.systemPrompt&&e.systemPrompt.length>0)return{systemPrompt:e.systemPrompt,messages:t};if("string"==typeof e?.system&&e.system.length>0)return{systemPrompt:e.system,messages:t};if(t.length>0&&t[0]?.role==="system"){let e=t[0];return{systemPrompt:("string"==typeof e.content?e.content:Array.isArray(e.content)?e.content.filter(e=>e?.type==="text").map(e=>e.text).join("\n"):"")||"",messages:t.slice(1)}}return{systemPrompt:"",messages:t}}(t),m=function(e,t){let r=[];for(let i of(e&&r.push(`<system>
|
|
562
431
|
${e}
|
|
563
|
-
</system>`),t))switch(
|
|
432
|
+
</system>`),t))switch(i.role){case"user":{let e="string"==typeof i.content?i.content:i.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n");r.push(`<user>
|
|
564
433
|
${e}
|
|
565
|
-
</user>`);break}case"assistant":{let e=
|
|
566
|
-
${b}`),
|
|
567
|
-
${
|
|
568
|
-
</assistant>`);break}case"toolResult":{let e=
|
|
434
|
+
</user>`);break}case"assistant":{let e=i.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),t=i.content.filter(e=>"toolCall"===e.type),a=e;t.length>0&&(a+="\n"+t.map(e=>`${v}${JSON.stringify({id:e.id,name:e.name,arguments:e.arguments})}${y}`).join("\n")+`
|
|
435
|
+
${b}`),r.push(`<assistant>
|
|
436
|
+
${a}
|
|
437
|
+
</assistant>`);break}case"toolResult":{let e=i.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n");r.push(`<tool_result tool_call_id="${i.toolCallId}" name="${i.toolName}" is_error="${i.isError}">
|
|
569
438
|
${e}
|
|
570
|
-
</tool_result>`)}}return i.join("\n\n")}(u,p),m=[c,h].filter(Boolean).join("\n\n"),g=await function(e,t,i,r={}){let{onLine:o}=r;return new Promise((r,a)=>{let n=process.env.CURSOR_AGENT_BIN||"cursor-agent",l=["--print","--mode","ask","--trust","--model",e,"--output-format","stream-json","--stream-partial-output","--workspace",process.cwd(),t],d=(0,s.spawn)(n,l,{cwd:process.cwd(),env:process.env,stdio:["ignore","pipe","pipe"]}),c=setTimeout(()=>{d.kill("SIGKILL")},3e5),u="",p=[];d.stderr.setEncoding("utf8"),d.stderr.on("data",e=>u+=e);let h="";if(d.stdout.setEncoding("utf8"),d.stdout.on("data",e=>{let t=(h+=e).split("\n");for(let e of(h=t.pop()??"",t)){let t=e.trim();t&&(p.push(t),o?.(t))}}),i){let e=()=>{d.kill("SIGTERM")};i.addEventListener("abort",e,{once:!0}),d.on("close",()=>i.removeEventListener("abort",e))}d.on("error",e=>{(clearTimeout(c),e?.code==="ENOENT")?a(Error("cursor-agent not found. Install it: curl https://cursor.com/install -fsS | bash && cursor-agent login")):a(e)}),d.on("close",e=>{if(clearTimeout(c),h.trim()){let e=h.trim();p.push(e),o?.(e)}r({code:e??0,lines:p,stderr:u})})})}(e.id,m,i?.signal);if(i?.signal?.aborted)throw Error("Request was aborted");if(0!==g.code&&g.stderr){let e=g.stderr.trim();if(e.includes("not logged in")||e.includes("authentication")||e.includes("Unauthorized"))throw Error("Cursor authentication required. Run: cursor-agent login");throw Error(`cursor-agent exited with code ${g.code}: ${e}`)}let{text:f,thinking:w,usage:k}=function(e){let t=[],i=[],r=null;for(let s of e)try{let e=JSON.parse(s);if("assistant"===e.type&&e.message?.content)for(let r of e.message.content)"text"===r.type&&r.text&&t.push(r.text),"thinking"===r.type&&r.thinking&&i.push(r.thinking);else"result"===e.type&&e.usage&&(r=e.usage)}catch{}return{text:t.join(""),thinking:i.join(""),usage:r}}(g.lines);k&&(a.usage.input=k.inputTokens??0,a.usage.output=k.outputTokens??0,a.usage.cacheRead=k.cacheReadTokens??0,a.usage.cacheWrite=k.cacheWriteTokens??0,a.usage.totalTokens=a.usage.input+a.usage.output+a.usage.cacheRead+a.usage.cacheWrite);let S=!o&&f?n(f):f,T=S?function(e){let t,i=[],r=[],s=RegExp(y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=0;for(;null!==(t=s.exec(e));){let a=e.slice(o,t.index);a.trim()&&r.push(a);let n=t.index+y.length,l=e.indexOf(v,n);if(-1===l)break;let d=e.slice(n,l).trim();try{let e=JSON.parse(d);i.push({type:"toolCall",id:e.id||`call_${i.length+1}`,name:e.name,arguments:e.arguments||{}})}catch{r.push(e.slice(t.index,l+v.length))}s.lastIndex=o=l+v.length}let a=e.slice(o).replace(b,"").trim();return a&&r.push(a),{textParts:r,toolCalls:i}}(S):{textParts:[],toolCalls:[]},C=T.textParts.join("\n").trim();if(!f){let e=g.lines.join("\n"),t=o?e:n(e);if(t.trim()){let e={type:"text",text:t.trim()};a.content.push(e),r.push({type:"start",partial:a}),r.push({type:"text_start",contentIndex:0,partial:a}),r.push({type:"text_delta",contentIndex:0,delta:t.trim(),partial:a}),r.push({type:"text_end",contentIndex:0,content:t.trim(),partial:a}),r.push({type:"done",reason:"stop",message:a}),r.end();return}throw Error("cursor-agent returned empty response. Ensure you are logged in: cursor-agent login")}if(r.push({type:"start",partial:a}),d&&w&&(d.thinking=w,a.content.push(d)),C){l.text=C,a.content.push(l);let e=a.content.length-1;r.push({type:"text_start",contentIndex:e,partial:a}),r.push({type:"text_delta",contentIndex:e,delta:C,partial:a}),r.push({type:"text_end",contentIndex:e,content:C,partial:a})}for(let e of T.toolCalls){a.content.push(e);let t=a.content.length-1;r.push({type:"toolcall_start",contentIndex:t,partial:a}),r.push({type:"toolcall_delta",contentIndex:t,delta:JSON.stringify(e.arguments),partial:a}),r.push({type:"toolcall_end",contentIndex:t,toolCall:e,partial:a})}a.stopReason=T.toolCalls.length>0?"toolUse":"stop",r.push({type:"done",reason:a.stopReason,message:a}),r.end()}catch(e){a.stopReason=i?.signal?.aborted?"aborted":"error",a.errorMessage=e instanceof Error?e.message:String(e),r.push({type:"error",reason:a.stopReason,error:a}),r.end()}})(),r}let S=!1;function d(){S||(S=!0,(0,o.registerApiProvider)({api:c,stream:l,streamSimple:l}))}r()}catch(e){r(e)}})},5e3(e,t,i){i.d(t,{Eq:()=>s,pE:()=>o,rz:()=>r});let r={id:"deepseek-chat",name:"DeepSeek Coder",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096},s={id:"deepseek-chat",name:"DeepSeek Chat",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096},o={id:"deepseek-reasoner",name:"DeepSeek Reasoner",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:65536,maxTokens:8192}},9616(e,t,i){i.a(e,async function(e,r){try{i.d(t,{aN:()=>a.aN});var s=i(7817);i(1576);var o=i(9068),a=i(4820),n=e([s,o,a]);[s,o,a]=n.then?(await n)():n,r()}catch(e){r(e)}})},7817(e,t,i){i.a(e,async function(e,r){try{i.d(t,{q:()=>l});var s=i(5e3),o=i(1576),a=i(9068),n=e([a]);a=(n.then?(await n)():n)[0];let l={deepSeekCoder:s.rz,deepSeekChat:s.Eq,deepSeekReasoner:s.pE,ollamaQwen25:o.eM,ollamaQwen25Coder:o.ZU,ollamaDeepSeekR1:o.Z5,cursorAutoModel:a.PR,cursorSonnet:a.Ny,cursorSonnetThinking:a.pS,cursorOpus:a.ff,cursorGpt:a.Lv};r()}catch(e){r(e)}})},1576(e,t,i){i.d(t,{Z5:()=>a,ZU:()=>o,eM:()=>s,lE:()=>l,wc:()=>n});let r="http://localhost:11434/v1",s={id:"qwen2.5:14b",name:"Qwen2.5 14B (Ollama)",api:"openai-completions",provider:"ollama",baseUrl:(process.env.OPENAI_LOCAL_API_BASE||"").trim()||r,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096,supportsTools:!1},o={id:"qwen2.5-coder:14b",name:"Qwen2.5 Coder 14B (Ollama)",api:"openai-completions",provider:"ollama",baseUrl:(process.env.OPENAI_LOCAL_API_BASE||"").trim()||r,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096,supportsTools:!1},a={id:"deepseek-r1:14b",name:"DeepSeek R1 14B (Ollama)",api:"openai-completions",provider:"ollama",baseUrl:(process.env.OPENAI_LOCAL_API_BASE||"").trim()||r,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4096,maxTokens:4096,supportsTools:!1},n={[s.id]:s,[o.id]:o,[a.id]:a},l=r},8391(e,t,i){i.a(e,async function(e,r){try{i.d(t,{S:()=>l});var s=i(5012),o=i(8359),a=i(9966),n=e([o]);function l(e,t){let i=(0,o.Iz)(e)??process.env.PITHOSAI_RSA_PUBLIC_KEY?.trim()??null;if(!i)throw Error("Missing RSA public key. Set pithosai_security_key.security_key or PITHOSAI_RSA_PUBLIC_KEY to decrypt role prompts.");let{role:r,lang:n}=t,l=(0,o.iV)(e,{role:r,lang:n}),d=Object.fromEntries(l.map(e=>[e.name,e])),c={};for(let e of s.GV){let t=d[e];t&&(c[e]=(0,a.Yc)(t.content,i))}return c}o=(n.then?(await n)():n)[0],r()}catch(e){r(e)}})},9966(e,t,i){i.d(t,{Yc:()=>o});var r=i(7598);let s=r.constants.RSA_PKCS1_PADDING;function o(e,t){var i;let o,a=(i="public",(o=(t||"").trim()).includes("-----BEGIN")?o:("private"===i?"-----BEGIN PRIVATE KEY-----\n":"-----BEGIN PUBLIC KEY-----\n")+o.replace(/\s/g,"").replace(/.{64}/g,"$&\n").replace(/\n$/,"")+("private"===i?"\n-----END PRIVATE KEY-----":"\n-----END PUBLIC KEY-----")),n=Buffer.from(e,"hex");if(n.length<284)throw Error("Role prompt content too short (invalid or corrupted)");let l=n.subarray(0,256),d=n.subarray(256,268),c=n.subarray(268,284),u=n.subarray(284),p=(0,r.publicDecrypt)({key:a,padding:s},l);if(32!==p.length)throw Error(`Unwrapped key must be 32 bytes (got ${p.length}).`);let h=(0,r.createDecipheriv)("aes-256-gcm",p,d,{authTagLength:16});return h.setAuthTag(c),h.update(u,void 0,"utf8")+h.final("utf8")}},4768(e,t,i){i.a(e,async function(e,r){try{i.d(t,{L:()=>u,s:()=>c});var s=i(6760);i(8161);var o=i(1455),a=i(8359),n=i(4071),l=e([n,a]);[n,a]=l.then?(await l)():l;let p=".settings.json",h={web:{fetch:{enabled:!0},search:{enabled:!0}}};function d(e,t){let i=t?.project?.type??t?.type??"js",r={name:t?.project?.name??((0,s.basename)(e)||"project"),cwd:t?.project?.cwd??e,type:"ts"===i||"python"===i||"rust"===i||"java"===i?i:"js"},o=Array.isArray(t?.supportedRoles)?t.supportedRoles:[],a=t?.tools&&"object"==typeof t.tools?{web:{fetch:t.tools.web?.fetch&&"object"==typeof t.tools.web.fetch?{enabled:!!t.tools.web.fetch.enabled}:{enabled:!0},search:t.tools.web?.search&&"object"==typeof t.tools.web.search?{enabled:!!t.tools.web.search.enabled}:{enabled:!0}}}:{...h},n=t?.roles&&"object"==typeof t.roles?t.roles:{},l=t?.hooks&&"object"==typeof t.hooks?t.hooks:{};return{...t?.lang!=null&&{lang:String(t.lang)},project:r,supportedRoles:o,roles:n,tools:a,hooks:l}}async function c(e){try{let t=await (0,o.readFile)((0,s.join)(e,p),"utf-8"),i=JSON.parse(t),r=d(e,i),n=await (0,a.Lf)();return r.roles=(0,a.uh)(n),r}catch(e){return null}}async function u(e,t){let i=(0,s.join)(e,p),r=await c(e)??d(e,{}),a=t.project?.type??t.type??r.project.type,n={...{...null!=t.lang?{lang:t.lang}:null!=r.lang?{lang:r.lang}:{},project:{name:t.project?.name??r.project.name,cwd:t.project?.cwd??r.project.cwd,type:"ts"===a||"python"===a||"rust"===a||"java"===a?a:"js"},supportedRoles:Array.isArray(t.supportedRoles)?t.supportedRoles:r.supportedRoles,roles:t.roles&&"object"==typeof t.roles?t.roles:r.roles??{},tools:t.tools&&"object"==typeof t.tools?{web:{fetch:t.tools.web?.fetch!=null?{enabled:!!t.tools.web.fetch.enabled}:r.tools.web.fetch,search:t.tools.web?.search!=null?{enabled:!!t.tools.web.search.enabled}:r.tools.web.search}}:r.tools,hooks:t.hooks&&"object"==typeof t.hooks?t.hooks:r.hooks??{}}};void 0===n.lang&&delete n.lang,await (0,o.writeFile)(i,JSON.stringify(n,null,2),"utf-8")}r()}catch(e){r(e)}})},2369(e,t,i){i.a(e,async function(e,r){try{i.d(t,{Lf:()=>h});var s=i(6760),o=i(1455),a=i(3529),n=i(5012),l=i(8388),d=e([a]);a=(d.then?(await d)():d)[0];let m=null;async function c(e=n.qu){let t=process.env.PITHOSAI_DB_PATH||(0,s.join)(e,n.tb);return await (0,o.mkdir)((0,s.dirname)(t),{recursive:!0}),t}async function u(e=n.qu){if(m)return m;let t=await c(e);return(m=new a.default(t)).pragma("journal_mode = WAL"),m.pragma("foreign_keys = ON"),m}async function p(e=null){let t=e||await u();for(let e of l.nk)t.exec(e);!function(e){let t=e.prepare("PRAGMA table_info(pithosai_task_message)").all();if(0===t.length)return;let i=new Set(t.map(e=>e.name));for(let[t,r]of[["role","'PM'"],["lang","'en'"],["mode","'agent'"],["model","'deepSeekChat'"]])i.has(t)||e.exec(`ALTER TABLE pithosai_task_message ADD COLUMN ${t} TEXT NOT NULL DEFAULT ${r}`)}(t)}async function h(e=n.qu){let t=await u(e);return await p(t),t}r()}catch(e){r(e)}})},8359(e,t,i){i.a(e,async function(e,r){try{i.d(t,{$R:()=>C,Fh:()=>m,Iz:()=>T,J7:()=>v,Jo:()=>w,LW:()=>O,Lf:()=>s.Lf,N6:()=>b,O3:()=>l,PT:()=>u,SW:()=>g,Vk:()=>x,Vr:()=>n,XV:()=>A,YC:()=>d,_D:()=>f,au:()=>R,bY:()=>k,eC:()=>P,gg:()=>E,iV:()=>S,kF:()=>I,tJ:()=>p,uh:()=>y,x_:()=>c,yh:()=>h});var s=i(2369);i(8388);var o=e([s]);s=(o.then?(await o)():o)[0];let R={UNPROCESSED:0,PROCESSED:1};function a(){return new Date().toISOString()}function n(e,t){let{email:i,role:r,projectName:s,projectPath:o}=t,n=a(),l=e.prepare("SELECT * FROM heartbeat_email_process WHERE email = ? AND role = ? AND projectName = ?").get(i,r,s);if(l)return e.prepare("UPDATE heartbeat_email_process SET projectPath = ?, updatedAt = ? WHERE id = ?").run(o,n,l.id),e.prepare("SELECT * FROM heartbeat_email_process WHERE id = ?").get(l.id);let d=e.prepare(`INSERT INTO heartbeat_email_process (email, role, projectName, projectPath, createdAt, updatedAt)
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
ORDER BY id ${o}`).all(t,i);let a=Math.max(1,Math.min(Number(s)||500,1e4));return e.prepare(`SELECT * FROM pithosai_task_message
|
|
439
|
+
</tool_result>`)}}return r.join("\n\n")}(u,p),h=[c,m].filter(Boolean).join("\n\n"),g=await function(e,t,r,i={}){let{onLine:o}=i;return new Promise((i,n)=>{let s=process.env.CURSOR_AGENT_BIN||"cursor-agent",l=["--print","--mode","ask","--trust","--model",e,"--output-format","stream-json","--stream-partial-output","--workspace",process.cwd(),t],d=(0,a.spawn)(s,l,{cwd:process.cwd(),env:process.env,stdio:["ignore","pipe","pipe"]}),c=setTimeout(()=>{d.kill("SIGKILL")},3e5),u="",p=[];d.stderr.setEncoding("utf8"),d.stderr.on("data",e=>u+=e);let m="";if(d.stdout.setEncoding("utf8"),d.stdout.on("data",e=>{let t=(m+=e).split("\n");for(let e of(m=t.pop()??"",t)){let t=e.trim();t&&(p.push(t),o?.(t))}}),r){let e=()=>{d.kill("SIGTERM")};r.addEventListener("abort",e,{once:!0}),d.on("close",()=>r.removeEventListener("abort",e))}d.on("error",e=>{(clearTimeout(c),e?.code==="ENOENT")?n(Error("cursor-agent not found. Install it: curl https://cursor.com/install -fsS | bash && cursor-agent login")):n(e)}),d.on("close",e=>{if(clearTimeout(c),m.trim()){let e=m.trim();p.push(e),o?.(e)}i({code:e??0,lines:p,stderr:u})})})}(e.id,h,r?.signal);if(r?.signal?.aborted)throw Error("Request was aborted");if(0!==g.code&&g.stderr){let e=g.stderr.trim();if(e.includes("not logged in")||e.includes("authentication")||e.includes("Unauthorized"))throw Error("Cursor authentication required. Run: cursor-agent login");throw Error(`cursor-agent exited with code ${g.code}: ${e}`)}let{text:f,thinking:k,usage:w}=function(e){let t=[],r=[],i=null;for(let a of e)try{let e=JSON.parse(a);if("assistant"===e.type&&e.message?.content)for(let i of e.message.content)"text"===i.type&&i.text&&t.push(i.text),"thinking"===i.type&&i.thinking&&r.push(i.thinking);else"result"===e.type&&e.usage&&(i=e.usage)}catch{}return{text:t.join(""),thinking:r.join(""),usage:i}}(g.lines);w&&(n.usage.input=w.inputTokens??0,n.usage.output=w.outputTokens??0,n.usage.cacheRead=w.cacheReadTokens??0,n.usage.cacheWrite=w.cacheWriteTokens??0,n.usage.totalTokens=n.usage.input+n.usage.output+n.usage.cacheRead+n.usage.cacheWrite);let S=!o&&f?s(f):f,T=S?function(e){let t,r=[],i=[],a=RegExp(v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=0;for(;null!==(t=a.exec(e));){let n=e.slice(o,t.index);n.trim()&&i.push(n);let s=t.index+v.length,l=e.indexOf(y,s);if(-1===l)break;let d=e.slice(s,l).trim();try{let e=JSON.parse(d);r.push({type:"toolCall",id:e.id||`call_${r.length+1}`,name:e.name,arguments:e.arguments||{}})}catch{i.push(e.slice(t.index,l+y.length))}a.lastIndex=o=l+y.length}let n=e.slice(o).replace(b,"").trim();return n&&i.push(n),{textParts:i,toolCalls:r}}(S):{textParts:[],toolCalls:[]},E=T.textParts.join("\n").trim();if(!f){let e=g.lines.join("\n"),t=o?e:s(e);if(t.trim()){let e={type:"text",text:t.trim()};n.content.push(e),i.push({type:"start",partial:n}),i.push({type:"text_start",contentIndex:0,partial:n}),i.push({type:"text_delta",contentIndex:0,delta:t.trim(),partial:n}),i.push({type:"text_end",contentIndex:0,content:t.trim(),partial:n}),i.push({type:"done",reason:"stop",message:n}),i.end();return}throw Error("cursor-agent returned empty response. Ensure you are logged in: cursor-agent login")}if(i.push({type:"start",partial:n}),d&&k&&(d.thinking=k,n.content.push(d)),E){l.text=E,n.content.push(l);let e=n.content.length-1;i.push({type:"text_start",contentIndex:e,partial:n}),i.push({type:"text_delta",contentIndex:e,delta:E,partial:n}),i.push({type:"text_end",contentIndex:e,content:E,partial:n})}for(let e of T.toolCalls){n.content.push(e);let t=n.content.length-1;i.push({type:"toolcall_start",contentIndex:t,partial:n}),i.push({type:"toolcall_delta",contentIndex:t,delta:JSON.stringify(e.arguments),partial:n}),i.push({type:"toolcall_end",contentIndex:t,toolCall:e,partial:n})}n.stopReason=T.toolCalls.length>0?"toolUse":"stop",i.push({type:"done",reason:n.stopReason,message:n}),i.end()}catch(e){n.stopReason=r?.signal?.aborted?"aborted":"error",n.errorMessage=e instanceof Error?e.message:String(e),i.push({type:"error",reason:n.stopReason,error:n}),i.end()}})(),i}let S=!1;function d(){S||(S=!0,(0,o.registerApiProvider)({api:c,stream:l,streamSimple:l}))}i()}catch(e){i(e)}})},5e3(e,t,r){r.d(t,{Eq:()=>a,pE:()=>o,rz:()=>i});let i={id:"deepseek-chat",name:"DeepSeek Coder",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096},a={id:"deepseek-chat",name:"DeepSeek Chat",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096},o={id:"deepseek-reasoner",name:"DeepSeek Reasoner",api:"openai-completions",provider:"deepseek",baseUrl:"https://api.deepseek.com",reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:65536,maxTokens:8192}},9616(e,t,r){r.a(e,async function(e,i){try{r.d(t,{aN:()=>n.aN});var a=r(7817);r(1576);var o=r(9068),n=r(4820),s=e([a,o,n]);[a,o,n]=s.then?(await s)():s,i()}catch(e){i(e)}})},7817(e,t,r){r.a(e,async function(e,i){try{r.d(t,{q:()=>l});var a=r(5e3),o=r(1576),n=r(9068),s=e([n]);n=(s.then?(await s)():s)[0];let l={deepSeekCoder:a.rz,deepSeekChat:a.Eq,deepSeekReasoner:a.pE,ollamaQwen25:o.eM,ollamaQwen25Coder:o.ZU,ollamaDeepSeekR1:o.Z5,cursorAutoModel:n.PR,cursorSonnet:n.Ny,cursorSonnetThinking:n.pS,cursorOpus:n.ff,cursorGpt:n.Lv};i()}catch(e){i(e)}})},1576(e,t,r){r.d(t,{Z5:()=>n,ZU:()=>o,eM:()=>a,lE:()=>l,wc:()=>s});let i="http://localhost:11434/v1",a={id:"qwen2.5:14b",name:"Qwen2.5 14B (Ollama)",api:"openai-completions",provider:"ollama",baseUrl:(process.env.OPENAI_LOCAL_API_BASE||"").trim()||i,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096,supportsTools:!1},o={id:"qwen2.5-coder:14b",name:"Qwen2.5 Coder 14B (Ollama)",api:"openai-completions",provider:"ollama",baseUrl:(process.env.OPENAI_LOCAL_API_BASE||"").trim()||i,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:32768,maxTokens:4096,supportsTools:!1},n={id:"deepseek-r1:14b",name:"DeepSeek R1 14B (Ollama)",api:"openai-completions",provider:"ollama",baseUrl:(process.env.OPENAI_LOCAL_API_BASE||"").trim()||i,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:4096,maxTokens:4096,supportsTools:!1},s={[a.id]:a,[o.id]:o,[n.id]:n},l=i},8391(e,t,r){r.a(e,async function(e,i){try{r.d(t,{S:()=>l});var a=r(5012),o=r(8359),n=r(9966),s=e([o]);async function l(e,t){let r=await (0,o.Iz)(e)??process.env.PITHOSAI_RSA_PUBLIC_KEY?.trim()??null;if(!r)throw Error("Missing RSA public key. Set pithosai_security_key.security_key or PITHOSAI_RSA_PUBLIC_KEY to decrypt role prompts.");let{role:i,lang:s}=t,l=await (0,o.iV)(e,{role:i,lang:s}),d=Object.fromEntries(l.map(e=>[e.name,e])),c={};for(let e of a.GV){let t=d[e];t&&(c[e]=(0,n.Yc)(t.content,r))}return c}o=(s.then?(await s)():s)[0],i()}catch(e){i(e)}})},9966(e,t,r){r.d(t,{Yc:()=>o});var i=r(7598);let a=i.constants.RSA_PKCS1_PADDING;function o(e,t){var r;let o,n=(r="public",(o=(t||"").trim()).includes("-----BEGIN")?o:("private"===r?"-----BEGIN PRIVATE KEY-----\n":"-----BEGIN PUBLIC KEY-----\n")+o.replace(/\s/g,"").replace(/.{64}/g,"$&\n").replace(/\n$/,"")+("private"===r?"\n-----END PRIVATE KEY-----":"\n-----END PUBLIC KEY-----")),s=Buffer.from(e,"hex");if(s.length<284)throw Error("Role prompt content too short (invalid or corrupted)");let l=s.subarray(0,256),d=s.subarray(256,268),c=s.subarray(268,284),u=s.subarray(284),p=(0,i.publicDecrypt)({key:n,padding:a},l);if(32!==p.length)throw Error(`Unwrapped key must be 32 bytes (got ${p.length}).`);let m=(0,i.createDecipheriv)("aes-256-gcm",p,d,{authTagLength:16});return m.setAuthTag(c),m.update(u,void 0,"utf8")+m.final("utf8")}},4768(e,t,r){r.a(e,async function(e,i){try{r.d(t,{L:()=>u,s:()=>c});var a=r(6760);r(8161);var o=r(1455),n=r(8359),s=r(4071),l=e([s,n]);[s,n]=l.then?(await l)():l;let p=".settings.json",m={web:{fetch:{enabled:!0},search:{enabled:!0}}};function d(e,t){let r=t?.project?.type??t?.type??"js",i={name:t?.project?.name??((0,a.basename)(e)||"project"),cwd:t?.project?.cwd??e,type:"ts"===r||"python"===r||"rust"===r||"java"===r?r:"js"},o=Array.isArray(t?.supportedRoles)?t.supportedRoles:[],n=t?.tools&&"object"==typeof t.tools?{web:{fetch:t.tools.web?.fetch&&"object"==typeof t.tools.web.fetch?{enabled:!!t.tools.web.fetch.enabled}:{enabled:!0},search:t.tools.web?.search&&"object"==typeof t.tools.web.search?{enabled:!!t.tools.web.search.enabled}:{enabled:!0}}}:{...m},s=t?.roles&&"object"==typeof t.roles?t.roles:{},l=t?.hooks&&"object"==typeof t.hooks?t.hooks:{};return{...t?.lang!=null&&{lang:String(t.lang)},project:i,supportedRoles:o,roles:s,tools:n,hooks:l}}async function c(e){try{let t=await (0,o.readFile)((0,a.join)(e,p),"utf-8"),r=JSON.parse(t),i=d(e,r),s=await (0,n.Lf)();return i.roles=await (0,n.uh)(s),i}catch(e){return null}}async function u(e,t){let r=(0,a.join)(e,p),i=await c(e)??d(e,{}),n=t.project?.type??t.type??i.project.type,s={...{...null!=t.lang?{lang:t.lang}:null!=i.lang?{lang:i.lang}:{},project:{name:t.project?.name??i.project.name,cwd:t.project?.cwd??i.project.cwd,type:"ts"===n||"python"===n||"rust"===n||"java"===n?n:"js"},supportedRoles:Array.isArray(t.supportedRoles)?t.supportedRoles:i.supportedRoles,roles:t.roles&&"object"==typeof t.roles?t.roles:i.roles??{},tools:t.tools&&"object"==typeof t.tools?{web:{fetch:t.tools.web?.fetch!=null?{enabled:!!t.tools.web.fetch.enabled}:i.tools.web.fetch,search:t.tools.web?.search!=null?{enabled:!!t.tools.web.search.enabled}:i.tools.web.search}}:i.tools,hooks:t.hooks&&"object"==typeof t.hooks?t.hooks:i.hooks??{}}};void 0===s.lang&&delete s.lang,await (0,o.writeFile)(r,JSON.stringify(s,null,2),"utf-8")}i()}catch(e){i(e)}})},2369(e,t,r){r.a(e,async function(e,i){try{r.d(t,{IH:()=>D,Lf:()=>R,sA:()=>I,tT:()=>T});var a=r(6760),o=r(1455),n=r(3024),s=r(4071),l=r(3529),d=r(5012),c=r(8388),u=r(2651),p=e([s,l,u]);[s,l,u]=p.then?(await p)():p;let N=null;try{let e=await r.e("336").then(r.bind(r,5627));N=e.default??e}catch{N=null}let L=null;async function m(e){let t=await e.all("PRAGMA table_info(pithosai_task_message)");if(0===t.length)return;let r=new Set(t.map(e=>e.name));for(let[t,i]of[["role","'PM'"],["lang","'en'"],["mode","'agent'"],["model","'deepSeekChat'"]])r.has(t)||await e.exec(`ALTER TABLE pithosai_task_message ADD COLUMN ${t} TEXT NOT NULL DEFAULT ${i}`)}function h(e,t,r=[]){return new Promise((i,a)=>{e.get(t,r,(e,t)=>{e?a(e):i(t)})})}function g(e,t){return new Promise((r,i)=>{e.exec(t,e=>{e?i(e):r()})})}function f(e){return new Promise((t,r)=>{e.close(e=>{e?r(e):t()})})}function k(e){return String(e).replace(/'/g,"''")}function w(e){let{sqlite3:t,path:r}=e;return new Promise((e,i)=>{let a=new t.Database(r,t.OPEN_READWRITE|t.OPEN_CREATE,t=>{t?i(t):e(a)})})}async function v(e){await h(e,"SELECT count(*) AS total FROM sqlite_master")}async function y(e,t,r){let i=await w({sqlite3:e,path:t});try{var a;return(0,s.JX)(`[storage] openSqlcipherAdapterWithKey key=${r}, path=${t}`),await g(i,`PRAGMA key = '${k(r)}'`),await g(i,"PRAGMA cipher_compatibility = 4"),await v(i),await g(i,"PRAGMA journal_mode = WAL"),await g(i,"PRAGMA foreign_keys = ON"),a=i,{run:(e,t=[])=>(function(e,t,r=[]){return new Promise((i,a)=>{e.run(t,r,function(e){e?a(e):i({id:Number(this.lastID??0),changes:Number(this.changes??0)})})})})(a,e,t),get:(e,t=[])=>h(a,e,t),all:(e,t=[])=>(function(e,t,r=[]){return new Promise((i,a)=>{e.all(t,r,(e,t)=>{e?a(e):i(t??[])})})})(a,e,t),exec:e=>g(a,e),close:()=>f(a)}}catch(e){throw await f(i),(0,s.CN)(`[storage] openSqlcipherAdapterWithKey key=${r}, path=${t} error: ${e.message}`,e.stack),e}}async function b(e){try{await v(e);return}catch{}await g(e,"PRAGMA key = ''"),await v(e)}async function S(e){if(function(e){try{let t=new l.default(e,{fileMustExist:!0});try{t.pragma("query_only = ON"),t.prepare("SELECT count(*) AS c FROM sqlite_master").get()}finally{t.close()}return!0}catch{return!1}}(e.path))return!0;let t=await w(e);try{return await b(t),await f(t),!0}catch{return await f(t),!1}}class D extends Error{constructor(){super("The SQLCipher native module (@journeyapps/sqlcipher) is not available. Install or rebuild it for your platform to migrate or open encrypted databases."),this.name="SqlcipherUnavailableError"}}async function T(e){let{path:t}=e;if(!(0,n.existsSync)(t))return{action:"skipped",reason:"file_missing"};if(!N)throw new D;let r=N.verbose(),i=e.cipherKey??await (0,u.Ib)(t),a=e.cipherKey??i,o=await w({sqlite3:r,path:t});try{return await g(o,`PRAGMA key = '${k(a)}'`),await g(o,"PRAGMA cipher_compatibility = 4"),await v(o),await f(o),{action:"skipped",reason:"already_encrypted_with_key"}}catch{await f(o)}return await S({sqlite3:r,path:t})?(await E({sqlite3:r,path:t,cipherKey:i}),{action:"migrated"}):{action:"skipped",reason:"not_plaintext_or_unreadable"}}async function E(e){let{sqlite3:t,path:r,cipherKey:i}=e,a=`${r}.enc-migrating`,s=`${r}.plain-backup`;(0,n.existsSync)(a)&&await (0,o.unlink)(a),(0,n.existsSync)(s)&&await (0,o.unlink)(s);let l=await w({sqlite3:t,path:r});try{await b(l),await g(l,`ATTACH DATABASE '${k(a)}' AS encrypted KEY '${k(i)}'`),await g(l,"SELECT sqlcipher_export('encrypted')"),await g(l,"DETACH DATABASE encrypted")}finally{await f(l)}await (0,o.rename)(r,s);try{await (0,o.rename)(a,r),await (0,o.unlink)(s)}catch(e){throw(0,n.existsSync)(r)&&await (0,o.unlink)(r),await (0,o.rename)(s,r),(0,n.existsSync)(a)&&await (0,o.unlink)(a),e}}async function x(e,t){let r=t&&"object"==typeof t&&"code"in t?String(t.code):"",i=t instanceof Error?t.message:String(t),a="";try{if((0,n.existsSync)(e)){let t=await (0,o.stat)(e);a=`File exists; ${t.isFile()?"regular file":"not a regular file"}; size ${t.size} bytes.`}else a="File does not exist (unexpected after getDbPath)."}catch{a=""}let s=[a,`path: ${e}`,`Check PITHOSAI_DB_PATH points to the real SQLite file (not a directory or ${u.l4}).`,`If ~/.pithosai/${u.l4} was replaced, the device-derived key changed — restore that file from backup (see docs/device-id.md).`,"If the file is corrupt or not SQLite at all, move it aside and let the app create a new DB, or restore from backup."];return`Cannot open storage database (${r||"error"}): ${i}
|
|
440
|
+
${s.join("\n")}`}async function C(e){let t,{sqlite3:r,path:i,cipherKey:a}=e;try{return await y(r,i,a)}catch(e){t=e}if(!await S({sqlite3:r,path:i}))throw Error(await x(i,t),{cause:t});return await E({sqlite3:r,path:i,cipherKey:a}),y(r,i,a)}async function A(e){if((0,a.basename)(e)===u.l4)throw Error(`Invalid database path: ${e} is the device metadata file (${u.l4}), not pithosai.db. Fix PITHOSAI_DB_PATH.`);if(!(0,n.existsSync)(e))return;let t=await (0,o.stat)(e);if(t.isDirectory())throw Error(`Invalid database path: ${e} is a directory, not a file. Fix PITHOSAI_DB_PATH.`);0===t.size&&await (0,o.unlink)(e)}async function I(e=d.qu){let t=process.env.PITHOSAI_DB_PATH||(0,a.join)(e,d.tb);return await (0,o.mkdir)((0,a.dirname)(t),{recursive:!0}),await A(t),t}async function O(e=d.qu){if(L)return L;let t=await I(e);if(!N){let e;try{e=new l.default(t)}catch(r){let e=r&&"object"==typeof r&&"code"in r?String(r.code):"";if("SQLITE_NOTADB"===e||r instanceof Error&&/not a database/i.test(r.message))throw Error(`Cannot open ${t} as plain SQLite (${e||"SQLITE_NOTADB"}). The file may be SQLCipher-encrypted or not a database: install @journeyapps/sqlcipher, or fix PITHOSAI_DB_PATH / replace the file with a valid plain SQLite database.`,{cause:r});throw r}return e.pragma("journal_mode = WAL"),e.pragma("foreign_keys = ON"),L={run:async(t,r=[])=>{let i=e.prepare(t).run(...r);return{id:Number(i.lastInsertRowid??0),changes:Number(i.changes??0)}},get:async(t,r=[])=>e.prepare(t).get(...r),all:async(t,r=[])=>e.prepare(t).all(...r),exec:async t=>{e.exec(t)},close:async()=>{e.close()}}}let r=N.verbose(),i=await (0,u.Ib)(t);return L=await C({sqlite3:r,path:t,cipherKey:i})}async function P(e=null){let t=e||await O();for(let e of c.nk)await t.exec(e);await m(t)}async function R(e=d.qu){let t=await O(e);return await P(t),t}i()}catch(e){i(e)}},1)},8359(e,t,r){r.a(e,async function(e,i){try{r.d(t,{$R:()=>d.$R,Fh:()=>s.Fh,Iz:()=>l.Iz,J7:()=>s.J7,Jo:()=>s.Jo,LW:()=>d.LW,Lf:()=>a.Lf,N6:()=>l.N6,O3:()=>n.O3,PT:()=>s.PT,SW:()=>s.SW,Vk:()=>d.Vk,Vr:()=>n.Vr,XV:()=>d.XV,YC:()=>s.YC,_D:()=>s._D,au:()=>s.au,bY:()=>s.bY,eC:()=>d.eC,gg:()=>d.gg,iV:()=>l.iV,kF:()=>d.kF,tJ:()=>s.tJ,uh:()=>s.uh,x_:()=>s.x_,yh:()=>s.yh});var a=r(2369),o=r(2651);r(8388);var n=r(1379),s=r(8434),l=r(1967),d=r(4133),c=e([a,o]);[a,o]=c.then?(await c)():c,i()}catch(e){i(e)}})},2651(e,t,r){r.a(e,async function(e,i){try{r.d(t,{Ib:()=>S,l4:()=>x});var a=r(6760),o=r(1455),n=r(3024),s=r(1421),l=r(7975),d=r(7598),c=r(8161),u=r(4071),p=e([u]);u=(p.then?(await p)():p)[0];let T=(0,l.promisify)(s.execFile),E=(0,l.promisify)(d.pbkdf2),x=".device_key";function m(e){return(0,a.join)(e,x)}async function h(e){let t=m(e);if(!(0,n.existsSync)(t))return{};try{let e=await (0,o.readFile)(t,"utf8"),r=JSON.parse(e);return r&&"object"==typeof r?r:{}}catch{return{}}}async function g(e,t){await (0,o.mkdir)(e,{recursive:!0});let r={...await h(e),...t};await (0,o.writeFile)(m(e),JSON.stringify(r,null,2),{encoding:"utf8",mode:384})}async function f(e){let t=(await h(e)).persistentId;if("string"==typeof t&&t.length>0)return t;let r=(0,d.randomBytes)(16).toString("hex");return await g(e,{persistentId:r}),r}async function k(e){let t=c.platform();try{if("linux"===t&&(0,n.existsSync)("/etc/machine-id")){let e=(await (0,o.readFile)("/etc/machine-id","utf8")).trim();if(e)return e}if("darwin"===t)try{let{stdout:e}=await T("ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",maxBuffer:262144}),t=e.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(t?.[1])return t[1]}catch{}}catch{}return f(e)}async function w(e){let t=(await h(e)).machineIdSnapshot;if("string"==typeof t&&t.length>0)return t;let r=await k(e);return await g(e,{machineIdSnapshot:r}),r}async function v(e){let t=await w(e),r={};return r.hostname=c.hostname(),r.platform=c.platform(),r.arch=c.arch(),r.cpus=c.cpus().length,r.totalMemory=c.totalmem(),r.macAddress=function(){try{let e=c.networkInterfaces(),t=[];for(let r of Object.keys(e)){let i=e[r];if(i)for(let e of i)!e.internal&&e.mac&&"00:00:00:00:00:00"!==e.mac&&t.push(e.mac)}let r=[...new Set(t)].sort((e,t)=>e.toLowerCase().localeCompare(t.toLowerCase(),"en"));if(0===r.length)return"unknown-mac";return r[0]}catch{}return"unknown-mac"}(),r.machineId=t,r}async function y(e){let t=(await h(e)).salt;if("string"==typeof t&&t.length>0)return t;let r=(0,d.randomBytes)(16).toString("hex");return await g(e,{salt:r}),r}async function b(e){await (0,o.mkdir)(e,{recursive:!0});let t=await v(e),r=function(e){let t={};for(let r of C)t[r]=e[r];return JSON.stringify(t)}(t),i=await y(e);return(await E(r,i,1e5,32,"sha256")).toString("hex")}let C=["platform","arch","machineId"],A=new Map;async function S(e){let t=(0,a.dirname)(e),r=A.get(t);if(r)return(0,u.JX)(`[storage] resolveSqlcipherCipherKey cached key=${r}`),r;let i=await b(t);return A.set(t,i),(0,u.JX)(`[storage] resolveSqlcipherCipherKey key=${i}`),i}i()}catch(e){i(e)}})},8434(e,t,r){r.d(t,{Fh:()=>c,J7:()=>f,Jo:()=>m,PT:()=>s,SW:()=>u,YC:()=>o,_D:()=>p,au:()=>a,bY:()=>h,tJ:()=>l,uh:()=>g,x_:()=>n,yh:()=>d});var i=r(3637);let a={UNPROCESSED:0,PROCESSED:1};async function o(e,t){let r=(0,i.k)();return await e.run(`INSERT INTO emails (id, subject, body, date, "from", "to", createdAt, updatedAt)
|
|
441
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
442
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
443
|
+
subject = excluded.subject,
|
|
444
|
+
body = excluded.body,
|
|
445
|
+
date = excluded.date,
|
|
446
|
+
"from" = excluded."from",
|
|
447
|
+
"to" = excluded."to",
|
|
448
|
+
updatedAt = excluded.updatedAt`,[t.id,t.subject,t.body,t.date,t.from,t.to,r,r]),e.get("SELECT * FROM emails WHERE id = ?",[t.id])}function n(e,t){return e.get("SELECT * FROM emails WHERE id = ?",[t])}async function s(e,t){let r=await e.run(`INSERT INTO email_attachments (emailId, filename, contentType, size, content, filePath)
|
|
449
|
+
VALUES (?, ?, ?, ?, ?, ?)`,[t.emailId,t.filename,t.contentType,t.size,t.content??null,t.filePath??null]);return e.get("SELECT * FROM email_attachments WHERE id = ?",[r.id])}function l(e,t){return e.all("SELECT * FROM email_attachments WHERE emailId = ? ORDER BY id",[t])}async function d(e,t){await e.run("DELETE FROM email_attachments WHERE emailId = ?",[t])}async function c(e,t){let r=(0,i.k)(),o=t.status??a.UNPROCESSED,n=t.processCount??0;return await e.run(`INSERT INTO email_tasks (processId, emailId, status, processCount, createdAt, updatedAt)
|
|
450
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
451
|
+
ON CONFLICT(processId, emailId) DO UPDATE SET
|
|
452
|
+
status = excluded.status,
|
|
453
|
+
processCount = excluded.processCount,
|
|
454
|
+
updatedAt = excluded.updatedAt`,[t.processId,t.emailId,o,n,r,r]),e.get("SELECT * FROM email_tasks WHERE processId = ? AND emailId = ?",[t.processId,t.emailId])}function u(e,t,r={}){return void 0!==r.status?e.all("SELECT * FROM email_tasks WHERE processId = ? AND status = ? ORDER BY createdAt",[t,r.status]):e.all("SELECT * FROM email_tasks WHERE processId = ? ORDER BY createdAt",[t])}function p(e,t){return e.get("SELECT * FROM email_tasks WHERE emailId = ? LIMIT 1",[t])}async function m(e,t,r){if(0===r.size)return void await e.run("DELETE FROM email_tasks WHERE processId = ?",[t]);let i=[...r],a=i.map(()=>"?").join(",");await e.run(`DELETE FROM email_tasks WHERE processId = ? AND emailId NOT IN (${a})`,[t,...i])}function h(e){return e.all("SELECT * FROM email_roles ORDER BY role, email")}async function g(e){let t=await h(e),r={};for(let e of t)r[e.role]||(r[e.role]={email:e.email,password:e.password,imap:{host:e.imap_host,port:e.imap_port},smtp:{host:e.smtp_host,port:e.smtp_port}});return r}async function f(e,t){let{email:r,role:i,customerEmail:a}=t;return null!=await e.get("SELECT 1 FROM email_customers WHERE email = ? AND role = ? AND customer_email = ? AND status = ?",[r,i,a,1])}},1379(e,t,r){r.d(t,{O3:()=>o,Vr:()=>a});var i=r(3637);async function a(e,t){let{email:r,role:a,projectName:o,projectPath:n}=t,s=(0,i.k)(),l=await e.get("SELECT * FROM heartbeat_email_process WHERE email = ? AND role = ? AND projectName = ?",[r,a,o]);if(l)return await e.run("UPDATE heartbeat_email_process SET projectPath = ?, updatedAt = ? WHERE id = ?",[n,s,l.id]),e.get("SELECT * FROM heartbeat_email_process WHERE id = ?",[l.id]);let d=await e.run(`INSERT INTO heartbeat_email_process (email, role, projectName, projectPath, createdAt, updatedAt)
|
|
455
|
+
VALUES (?, ?, ?, ?, ?, ?)`,[r,a,o,n,s,s]);return e.get("SELECT * FROM heartbeat_email_process WHERE id = ?",[d.id])}function o(e,t={}){return t.email&&t.role?e.all("SELECT * FROM heartbeat_email_process WHERE email = ? AND role = ? ORDER BY id",[t.email,t.role]):t.email?e.all("SELECT * FROM heartbeat_email_process WHERE email = ? ORDER BY id",[t.email]):t.role?e.all("SELECT * FROM heartbeat_email_process WHERE role = ? ORDER BY id",[t.role]):e.all("SELECT * FROM heartbeat_email_process ORDER BY id")}},1967(e,t,r){function i(e,t){let{lang:r,role:i,name:a}=t;return e.get("SELECT * FROM pithosai_role_prompts WHERE lang = ? AND role = ? AND name = ?",[r,i,a])}function a(e,t){let{role:r,lang:i}=t;return e.all("SELECT * FROM pithosai_role_prompts WHERE role = ? AND lang = ? ORDER BY name",[r,i])}async function o(e){let t=await e.get("SELECT security_key FROM pithosai_security_key WHERE id = ?",[1]),r=t?.security_key;return null!=r&&String(r).trim()||null}r.d(t,{Iz:()=>o,N6:()=>i,iV:()=>a})},3637(e,t,r){r.d(t,{k:()=>i});function i(){return new Date().toISOString()}},4133(e,t,r){r.d(t,{$R:()=>a,LW:()=>d,Vk:()=>n,XV:()=>l,eC:()=>c,gg:()=>o,kF:()=>s});var i=r(3637);async function a(e,t){let r=await e.get("SELECT * FROM pithosai_task WHERE id = ?",[t.id]);if(r)return r;let a=(0,i.k)(),o=t.createdAt??a,n=t.updatedAt??a;return await e.run(`INSERT INTO pithosai_task (id, title, description, model, status, createdAt, updatedAt)
|
|
456
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,[t.id,t.title,t.description,t.model,t.status,o,n]),e.get("SELECT * FROM pithosai_task WHERE id = ?",[t.id])}function o(e,t){return e.get("SELECT * FROM pithosai_task WHERE id = ?",[t])}function n(e){return e.all("SELECT * FROM pithosai_task ORDER BY createdAt DESC, id DESC")}async function s(e,t){let r=t.createdAt??(0,i.k)(),a=t.role??"PM",o=t.lang??"en",n=t.mode??"agent",s=t.model??"deepSeekChat",l="string"==typeof t.message?t.message:JSON.stringify(t.message??null),d=await e.get(`SELECT * FROM pithosai_task_message
|
|
457
|
+
WHERE taskId = ? AND message = ? AND role = ? AND lang = ? AND mode = ? AND model = ?
|
|
458
|
+
ORDER BY id
|
|
459
|
+
LIMIT 1`,[t.taskId,l,a,o,n,s]);if(d)return d;let c=await e.run(`INSERT INTO pithosai_task_message (taskId, message, createdAt, role, lang, mode, model)
|
|
460
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,[t.taskId,l,r,a,o,n,s]);return e.get("SELECT * FROM pithosai_task_message WHERE id = ?",[c.id])}function l(e,{taskId:t,asc:r=!1,limit:i=100}){let a=r?"ASC":"DESC";return null==i?e.all(`SELECT * FROM pithosai_task_message WHERE taskId = ? ORDER BY id ${a}`,[t]):e.all(`SELECT * FROM pithosai_task_message WHERE taskId = ? ORDER BY id ${a} LIMIT ${i}`,[t])}async function d(e,t){return(await e.all(`SELECT DISTINCT taskId FROM pithosai_task_message
|
|
461
|
+
WHERE role = ? AND createdAt >= ? AND createdAt <= ?
|
|
462
|
+
ORDER BY taskId ASC`,[t.role,t.startIso,t.endIso])).map(e=>e.taskId)}function c(e,{taskId:t,role:r,asc:i=!0,limit:a}){let o=i?"ASC":"DESC";if(null==a)return e.all(`SELECT * FROM pithosai_task_message
|
|
595
463
|
WHERE taskId = ? AND role = ?
|
|
596
|
-
ORDER BY id ${o}
|
|
597
|
-
|
|
464
|
+
ORDER BY id ${o}`,[t,r]);let n=Math.max(1,Math.min(Number(a)||500,1e4));return e.all(`SELECT * FROM pithosai_task_message
|
|
465
|
+
WHERE taskId = ? AND role = ?
|
|
466
|
+
ORDER BY id ${o}
|
|
467
|
+
LIMIT ?`,[t,r,n])}},8388(e,t,r){r.d(t,{nk:()=>i});let i=[`
|
|
598
468
|
CREATE TABLE IF NOT EXISTS heartbeat_email_process (
|
|
599
469
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
600
470
|
email TEXT NOT NULL,
|
|
@@ -704,22 +574,22 @@ CREATE TABLE IF NOT EXISTS pithosai_security_key (
|
|
|
704
574
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
705
575
|
security_key TEXT NOT NULL
|
|
706
576
|
);
|
|
707
|
-
`]},5935(e,t,
|
|
708
|
-
${
|
|
709
|
-
`:`${
|
|
710
|
-
`},strong({tokens:e}){return o.w4.strong(this.parser.parseInline(e))},em({tokens:e}){return o.w4.muted(this.parser.parseInline(e))},codespan:({text:e})=>o.w4.muted(e),link({tokens:e,href:t}){var i
|
|
577
|
+
`]},5935(e,t,r){r.d(t,{$0:()=>n,dE:()=>o});let i=RegExp("\\x1b\\[[0-9;]*m","g"),a=RegExp("\\x1b\\]8;;.*?\\x1b\\\\|\\x1b\\]8;;\\x1b\\\\","g");function o(e){return 0===e||e<32||e>=127&&e<160||8205===e||8204===e||e>=65024&&e<=65039||e>=917760&&e<=917999||e>=768&&e<=879||e>=6832&&e<=6911||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65056&&e<=65071?0:e>=127744&&e<=129791||e>=9728&&e<=10175||e>=65280&&e<=65519?2:e<4352?e>=12288&&e<=12351?2:1:e>=4352&&e<=4607||e>=11904&&e<=42191||e>=44032&&e<=55215||e>=63744&&e<=64255||e>=65040&&e<=65135||e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}function n(e){let t=e.replace(a,"").replace(i,""),r=0;for(let e=0;e<t.length;){let i=t.codePointAt(e)??0;r+=o(i),e+=i>65535?2:1}return r}},9782(e,t,r){r.d(t,{$A:()=>o,Mm:()=>a,d2:()=>i,vg:()=>n});let i=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],a=["|","/","-","\\"];async function o(e,t="Loading..."){let r=0,a=setInterval(()=>{let e=i[r%i.length];process.stderr.write(`\r ${e} ${t}`),r+=1},80);try{return await e}finally{clearInterval(a),process.stderr.isTTY?process.stderr.write("\r\x1b[K"):process.stderr.write("\n")}}async function n(e,t="Loading...",r=t){let o=!0,s="loading",l=0,d=process.stdout.write,c=()=>{o&&(o=!1,clearInterval(u),process.stderr.isTTY?process.stderr.write("\r\x1b[K"):process.stderr.write("\n"))},u=setInterval(()=>{if(!o)return;let e="loading"===s?i:a,n=e[l%e.length],d="loading"===s?t:r;process.stderr.write(`\r ${n} ${d}`),l+=1},80);process.stdout.write=function(...e){return o&&("loading"===s&&(process.stderr.isTTY?(s="running",l=0):c()),process.stdout.write=d),d.apply(process.stdout,e)};try{return await e}finally{c(),process.stdout.write=d}}},161(e,t,r){r.a(e,async function(e,i){try{r.d(t,{o:()=>l});var a=r(8703),o=r(1483),n=r(6022),s=e([o,a]);[o,a]=s.then?(await s)():s;let d="\x1b]8;;",c=!1;function l(e){if("string"!=typeof e||!e.trim())return e??"";c||(a.marked.use({renderer:{heading({tokens:e,depth:t}){let r=this.parser.parseInline(e),i=o.w4.heading(r);return 1===t?`
|
|
578
|
+
${i}
|
|
579
|
+
`:`${i}
|
|
580
|
+
`},strong({tokens:e}){return o.w4.strong(this.parser.parseInline(e))},em({tokens:e}){return o.w4.muted(this.parser.parseInline(e))},codespan:({text:e})=>o.w4.muted(e),link({tokens:e,href:t}){var r,i;return r=this.parser.parseInline(e),i=t??"",i?.trim()?(0,o.D8)()?`${d}${i}\x1b\\${r}${d}\x1b\\`:`${r} (${i})`:r},blockquote({tokens:e}){let t=this.parser.parse(e).trimEnd().split("\n").map(e=>o.w4.muted("│ ")+e).join("\n");return`
|
|
711
581
|
${t}
|
|
712
582
|
|
|
713
|
-
`},hr(){let e=Math.min(process.stdout?.columns??80,80)-2;return"\n"+o.w4.muted("─".repeat(Math.max(0,e)))+"\n"},code({text:e,lang:t}){let
|
|
714
|
-
${
|
|
583
|
+
`},hr(){let e=Math.min(process.stdout?.columns??80,80)-2;return"\n"+o.w4.muted("─".repeat(Math.max(0,e)))+"\n"},code({text:e,lang:t}){let r=(t??"").trim().toLowerCase(),i=/^(bash|sh|shell|zsh)$/.test(r),a=/^(javascript|js|typescript|ts|python|py|java|rust|rs|c|cpp|c\+\+)$/.test(r),n=i?o.w4.command:a?o.w4.info:o.w4.muted,s=t?o.w4.muted(`[${t}] `):"",l=e.replace(/\n$/,"").split("\n").map(e=>n(e)).join("\n");return`
|
|
584
|
+
${s}${l}
|
|
715
585
|
|
|
716
|
-
`},list({items:e,ordered:t}){let
|
|
717
|
-
${
|
|
586
|
+
`},list({items:e,ordered:t}){let r=e.map((e,r)=>{let i=t?`${r+1}. `:"• ";return this.listitem(e).trimEnd().split("\n").map((e,t)=>0===t?o.w4.accent(i)+e:" "+e).join("\n")}).join("\n");return`
|
|
587
|
+
${r}
|
|
718
588
|
|
|
719
|
-
`},listitem({tokens:e,task:t,checked:
|
|
589
|
+
`},listitem({tokens:e,task:t,checked:r}){return(t?o.w4[r?"success":"muted"](r?"[x] ":"[ ] "):"")+this.parser.parse(e)},paragraph({tokens:e}){return this.parser.parseInline(e)+"\n\n"},table(e){let t=e?.header??[],r=e?.rows??[],i=e?.align,a=e=>e?null!=e.tokens?this.parser.parseInline(e.tokens):"string"==typeof e.text?e.text:String(e):"";if(!Array.isArray(t)||!Array.isArray(r)||0===t.length){let e=[t,...r].filter(Array.isArray).map(e=>e.map(a).join(" | ")).join("\n");return e?`
|
|
720
590
|
${o.w4.muted(e)}
|
|
721
|
-
`:"\n"}let
|
|
591
|
+
`:"\n"}let s=t.length,l=t.map(a),d={left:"left",center:"center",right:"right"},c=l.map((e,t)=>({key:String(t),header:o.w4.heading(e),align:d[i?.[t]]??"left"})),u=r.map(e=>{let t={},r=Array.isArray(e)?e:[];for(let e=0;e<s;e+=1)t[String(e)]=o.w4.muted(a(r[e]));return t}),p=(0,n.b)({columns:c,rows:u,padding:1,border:"unicode"});return`
|
|
722
592
|
${p}
|
|
723
|
-
`},tablerow:({text:e})=>e,tablecell({tokens:e}){return this.parser.parseInline(e)},br:()=>"\n",text(e){return e.tokens&&e.tokens.length>0?this.parser.parseInline(e.tokens):e.text??""},html:()=>"",checkbox:({checked:e})=>o.w4[e?"success":"muted"](e?"[x]":"[ ]")+" "}}),
|
|
724
|
-
`}let o=Math.max(0,e.padding??1),
|
|
725
|
-
`}},1483(e,t,
|
|
593
|
+
`},tablerow:({text:e})=>e,tablecell({tokens:e}){return this.parser.parseInline(e)},br:()=>"\n",text(e){return e.tokens&&e.tokens.length>0?this.parser.parseInline(e.tokens):e.text??""},html:()=>"",checkbox:({checked:e})=>o.w4[e?"success":"muted"](e?"[x]":"[ ]")+" "}}),a.marked.setOptions({gfm:!0,breaks:!0}),c=!0);let t="string"!=typeof e?"":e.trim().replace(/\r\n/g,"\n").replace(/\r/g,"\n");try{let e=a.marked.parse(t,{async:!1});return"string"==typeof e?e:String(e)}catch{return e}}i()}catch(e){i(e)}})},9005(e,t,r){r.d(t,{A:()=>i});let i={accent:"#FF5A2D",accentBright:"#FF7A3D",accentDim:"#D14A22",info:"#FF8A5B",success:"#2FBF71",warn:"#FFB020",error:"#E23D2D",muted:"#8B7F77"}},6022(e,t,r){r.d(t,{b:()=>o});var i=r(5935);function a(e,t){return t<=0?"":e.repeat(t)}function o(e){let t=e.rows.map(e=>{let t={};for(let[r,i]of Object.entries(e))t[r]=null==i?"":String(i);return t}),r=e.border??"unicode";if("none"===r){let r=e.columns,i=[r.map(e=>e.header).join(" | "),...t.map(e=>r.map(t=>e[t.key]??"").join(" | "))];return`${i.join("\n")}
|
|
594
|
+
`}let o=Math.max(0,e.padding??1),n=e.columns,s=n.map(e=>({headerW:(0,i.$0)(e.header),cellW:Math.max(0,...t.map(t=>(0,i.$0)(t[e.key]??"")))})),l=n.map((e,t)=>{let r=s[t],i=Math.max(r?.headerW??0,r?.cellW??0)+2*o,a=e.maxWidth?Math.min(i,e.maxWidth):i;return Math.max(e.minWidth??3,a)}),d=function(e){if(null!=e&&Number.isFinite(e)&&!(e<=0))return Math.floor(e)}(e.width),c=n.length+1,u=l.reduce((e,t)=>e+t,0)+c,p=e=>Math.max((s[e]?.headerW??0)+2*o,(s[e]?.cellW??0)+2*o,3),m=n.map((e,t)=>Math.max(e.minWidth??3,p(t))),h=n.map((e,t)=>p(t));if(d&&u>d){let e=u-d,t=n.map((e,t)=>({i:t,w:l[t]??0})).filter(({i:e})=>!!n[e]?.flex).sort((e,t)=>t.w-e.w).map(e=>e.i),r=n.map((e,t)=>({i:t,w:l[t]??0})).filter(({i:e})=>!n[e]?.flex).sort((e,t)=>t.w-e.w).map(e=>e.i),i=(t,r)=>{for(;e>0;){let i=!1;for(let a of t)if(!((l[a]??0)<=(r[a]??0))&&(l[a]=(l[a]??0)-1,i=!0,(e-=1)<=0))break;if(!i)break}};i(t,m),i(t,h),i(r,m),i(r,h)}if(d){let e=n.length+1,t=d-(l.reduce((e,t)=>e+t,0)+e);if(t>0){let e=n.map((e,t)=>({c:e,i:t})).filter(({c:e})=>!!e.flex).map(({i:e})=>e);if(e.length>0){let r=n.map(e=>"number"==typeof e.maxWidth&&e.maxWidth>0?Math.floor(e.maxWidth):1/0);for(;t>0;){let i=!1;for(let a of e)if(!((l[a]??0)>=(r[a]??1/0))&&(l[a]=(l[a]??0)+1,i=!0,(t-=1)<=0))break;if(!i)break}}}}let g="ascii"===r?{tl:"+",tr:"+",bl:"+",br:"+",h:"-",v:"|",t:"+",ml:"+",m:"+",mr:"+",b:"+"}:{tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│",t:"┬",ml:"├",m:"┼",mr:"┤",b:"┴"},f=(e,t,r)=>`${e}${l.map(e=>a(g.h,e)).join(t)}${r}`,k=e=>Math.max(1,l[e]-2*o),w=a(" ",o),v=(e,t=!1)=>{let r=n.map(r=>t?r.header:e[r.key]??"").map((e,t)=>(function(e,t){if(t<=0)return[e];let r=[];for(let t=0;t<e.length;){if("\x1b"===e[t]){if("["===e[t+1]){let i=t+2;for(;i<e.length;){let t=e[i];if("m"===t)break;if(t&&t>="0"&&t<="9"||";"===t){i+=1;continue}break}if("m"===e[i]){r.push({kind:"ansi",value:e.slice(t,i+1)}),t=i+1;continue}}if("]"===e[t+1]&&"8;;"===e.slice(t+2,t+5)){let i=e.indexOf("\x1b\\",t+5);if(i>=0){r.push({kind:"ansi",value:e.slice(t,i+2)}),t=i+2;continue}}}let a=e.codePointAt(t)??0,o=String.fromCodePoint(a);r.push({kind:"char",value:o,w:(0,i.dE)(a)}),t+=a>65535?2:1}let a=r.findIndex(e=>"char"===e.kind);if(a<0)return[e];let o=-1;for(let e=r.length-1;e>=0;e-=1)if(r[e]?.kind==="char"){o=e;break}let n=r.slice(0,a).filter(e=>"ansi"===e.kind).map(e=>e.value).join(""),s=r.slice(o+1).filter(e=>"ansi"===e.kind).map(e=>e.value).join(""),l=r.slice(a,o+1),d=[],c=e=>" "===e||" "===e||"/"===e||"-"===e||"_"===e||"."===e,u=e=>" "===e||" "===e,p=[],m=0,h=null,g=e=>(e??p).map(e=>e.value).join(""),f=e=>{let t=e.replace(/\s+$/,"");0!==t.trim().length&&d.push(t)},k=e=>{if(0===p.length)return;if(null==e||e<=0){f(g()),p.length=0,m=0,h=null;return}let t=p.slice(0,e),r=p.slice(e);for(f(g(t));r.length>0&&r[0]?.kind==="char"&&u(r[0].value);)r.shift();p.length=0,p.push(...r),m=r.filter(e=>"char"===e.kind).reduce((e,t)=>e+(t.w??1),0),h=null};for(let e of l){if("ansi"===e.kind){p.push(e);continue}let r=e.value,i=e.w??1;if("\n"===r||"\r"===r){k(p.length);continue}m+i>t&&m>0&&k(h),p.push(e),m+=i,c(r)&&(h=p.length)}return(k(p.length),d.length)?n||s?d.map(e=>e?`${n}${e}${s}`:e):d:[""]})(e,k(t))),o=Math.max(...r.map(e=>e.length)),s=[];for(let e=0;e<o;e+=1){let t=r.map((t,r)=>{let o=function(e,t,r){let o=(0,i.$0)(e);if(o>=t)return e;let n=t-o;if("right"===r)return`${a(" ",n)}${e}`;if("center"===r){let t=Math.floor(n/2),r=n-t;return`${a(" ",t)}${e}${a(" ",r)}`}return`${e}${a(" ",n)}`}(t[e]??"",k(r),n[r]?.align??"left");return`${w}${o}${w}`});s.push(`${g.v}${t.join(g.v)}${g.v}`)}return s},y=[];for(let e of(y.push(f(g.tl,g.t,g.tr)),y.push(...v({},!0)),y.push(f(g.ml,g.m,g.mr)),t))y.push(...v(e,!1));return y.push(f(g.bl,g.b,g.br)),`${y.join("\n")}
|
|
595
|
+
`}},1483(e,t,r){r.a(e,async function(e,i){try{let s,l,d,c,u,p,m,h,g,f;r.d(t,{D8:()=>y,w4:()=>v});var a=r(8691),o=r(9005),n=e([a]);a=(n.then?(await n)():n)[0];let k="string"==typeof process.env.FORCE_COLOR&&process.env.FORCE_COLOR.trim().length>0&&"0"!==process.env.FORCE_COLOR.trim(),w=process.env.NO_COLOR&&!k?new a.g({level:0}):a.m,v={accent:(s=o.A.accent,w.hex(s)),accentBright:(l=o.A.accentBright,w.hex(l)),accentDim:(d=o.A.accentDim,w.hex(d)),info:(c=o.A.info,w.hex(c)),success:(u=o.A.success,w.hex(u)),warn:(p=o.A.warn,w.hex(p)),error:(m=o.A.error,w.hex(m)),muted:(h=o.A.muted,w.hex(h)),heading:w.bold.hex(o.A.accent),strong:w.bold.hex(o.A.accentBright),command:(g=o.A.accentBright,w.hex(g)),option:(f=o.A.warn,w.hex(f))},y=()=>w.level>0;i()}catch(e){i(e)}})},8691(e,t,r){r.a(e,async function(e,i){try{r.d(t,{g:()=>a.Chalk,m:()=>n});var a=r(5590),o=e([a]);a=(o.then?(await o)():o)[0];let n=function(){if("function"==typeof a.default.hex)return a.default;let e=a.default.default;return e&&"function"==typeof e.hex?e:a.default}();i()}catch(e){i(e)}})},4071(e,t,r){r.a(e,async function(e,i){try{let v;r.d(t,{CN:()=>h,IW:()=>k,JE:()=>u,JX:()=>w,KH:()=>f,MD:()=>m,_F:()=>g,cS:()=>s,dz:()=>l,fH:()=>p,vV:()=>c});var a=r(4082),o=e([a]);function n(e){let t=function(e=process.argv[1]){return"string"!=typeof e||0===e.length?"all":e.includes("/dist/")?"INFO":"all"}();a.default.configure({appenders:{file:{type:"file",filename:e||"/tmp/pithosai_log_file.log",layout:{type:"pattern",pattern:"%d{yyyy-MM-dd hh:mm:ss.SSS} %p %f:%l %m"}}},categories:{default:{appenders:["file"],level:t,enableCallStack:!0}}}),(v=a.default.getLogger()).callStackLinesToSkip=1}function s(e){e&&"string"==typeof e&&(process.env.PITHOSAI_LOG_FILEPATH=e,n(e))}function l(){return new Promise(e=>{a.default.shutdown(e)})}function d(e){return e.map(e=>e instanceof Error?e.message||String(e):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)).join(" ")}function c(...e){let t=e.length>1?d(e):e[0]??"";v.error(t)}function u(...e){let t=e.length>1?d(e):e[0]??"";v.warn(t)}function p(...e){let t=e.length>1?d(e):e[0]??"";v.info(t)}function m(...e){let t=e.length>1?d(e):e[0]??"";v.debug(t)}function h(...e){let t=e.length>1?d(e):e[0]??"";v.error(t)}function g(...e){let t=e.length>1?d(e):e[0]??"";v.warn(t)}function f(...e){try{let t=e.length>1?d(e):e[0]??"";v.info(t)}catch{}}function k(...e){let t=e.length>1?d(e):e[0]??"";v.info(t)}function w(...e){let t=e.length>1?d(e):e[0]??"";v.debug(t)}a=(o.then?(await o)():o)[0],n(process.env.PITHOSAI_LOG_FILEPATH),i()}catch(e){i(e)}})},8140(e,t,r){r.d(t,{X:()=>i});function i(e){return e&&e.startsWith("~")?(process.env.HOME||process.env.USERPROFILE||"")+e.slice(1):e}},4399(e,t,r){let i;r.d(t,{F8:()=>p,gb:()=>h,mi:()=>g});var a=r(6760),o=r(3136),n=r(3024),s=r(8995);let l=function(){if("u">typeof __dirname)return __dirname;let e=(0,a.dirname)((0,o.fileURLToPath)("file:///Users/lidh04/Projects/scripts/pithosai/src/utils/paths.js"));if((0,n.existsSync)(e))return e;let t=process.argv[1];if(t&&"-"!==t&&!t.startsWith("-"))try{return(0,a.dirname)((0,n.realpathSync)(t))}catch{}return e}(),d=(0,s.createRequire)(function(){let e=(0,o.fileURLToPath)("file:///Users/lidh04/Projects/scripts/pithosai/src/utils/paths.js");if((0,n.existsSync)(e))return"file:///Users/lidh04/Projects/scripts/pithosai/src/utils/paths.js";let t=process.argv[1];if(t&&"-"!==t&&!t.startsWith("-"))try{let e=(0,n.realpathSync)(t);if((0,n.existsSync)(e))return(0,o.pathToFileURL)(e).href}catch{}return"file:///Users/lidh04/Projects/scripts/pithosai/src/utils/paths.js"}());function c(e){let t=(0,a.join)(e,"package.json");if(!(0,n.existsSync)(t))return!1;try{let e=JSON.parse((0,n.readFileSync)(t,"utf8"));return"@pithosai/pithosai"===e.name||"pithosai"===e.name}catch{return!1}}function u(e){let t=e;for(let e=0;e<24;e++){if(c(t))return t;let e=(0,a.dirname)(t);if(e===t)break;t=e}return null}function p(){if(i)return i;let e=function(){for(let e of[(0,a.join)(l,"..","shims","package-root.cjs"),(0,a.join)(l,"..","..","shims","package-root.cjs")])try{let t=d(e);if("string"==typeof t&&c(t))return t}catch{}return null}();if(e)return i=e;try{let e=d.resolve("@pithosai/pithosai/package.json"),t=(0,a.dirname)(e);if(c(t))return i=t}catch{}try{let e=d.resolve("pithosai/package.json"),t=(0,a.dirname)(e);if(c(t))return i=t}catch{}let t=process.argv[1];if(t&&"-"!==t&&!t.startsWith("-"))try{let e=u((0,a.dirname)((0,n.realpathSync)(t)));if(e)return i=e}catch{}let r=u(l);if(r)return i=r;throw Error("pithosai: could not find package root. Reinstall @pithosai/pithosai.")}let m=p(),h=(0,a.join)(m,"templates");function g(e){return(0,a.join)(h,e)}},9737(e,t,r){r.d(t,{n:()=>i});function i(e,t,r){let i,a=new Promise((e,a)=>{void 0!==(i=setTimeout(()=>a(r()),t))&&"function"==typeof i.unref&&i.unref()});return Promise.race([e.finally(()=>{void 0!==i&&clearTimeout(i)}),a])}},3188(e,t,r){r.d(t,{y:()=>i});function i(e){return new Promise(t=>setTimeout(t,e))}},5460(e,t,r){r.d(t,{cs:()=>i});function i(e){if("string"!=typeof e||""===e)return e;let t=e.replace(/\r\n/g,"\n").split("\n");for(;t.length>0&&""===t[0].trim();)t.shift();let r=[],i=!1;for(let e of t){if(""===e.trim())continue;if(3===r.length){i=!0;break}let t=e.length>400?e.slice(0,400).replace(/\s+$/,"")+"...":e;r.push(t)}let a=r.join("\n");return i&&(a+="\n..."),a}}},h={};function g(e){var t=h[e];if(void 0!==t)return t.exports;var r=h[e]={exports:{}};return m[e](r,r.exports,g),r.exports}g.m=m,i=(r="function"==typeof Symbol)?Symbol("rspack queues"):"__rspack_queues",a=g.aE=r?Symbol("rspack exports"):"__webpack_exports__",o=r?Symbol("rspack error"):"__rspack_error",n=r?Symbol("rspack done"):"__rspack_done",s=g.zS=r?Symbol("rspack defer"):"__rspack_defer",l=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},g.a=(e,t,r)=>{r&&((d=[]).d=-1);var d,c,u,p,m=new Set,f=e.exports,k=new Promise((e,t)=>{p=t,u=e});k[a]=f,k[i]=e=>{d&&e(d),m.forEach(e),k.catch(()=>{})},e.exports=k,t(e=>{c=e.map(e=>{if(null!==e&&"object"==typeof e){if(!e[i]&&e[s]){var t=e[s];if(!t.some(e=>{var t=h[e];return!t||!1===t[n]}))return e;var r=e;e={then(e){Promise.all(t.map(g)).then(()=>e(r))}}}if(e[i])return e;if(e.then){var d=[];d.d=0,e.then(e=>{c[a]=e,l(d)},e=>{c[o]=e,l(d)});var c={};return c[s]=!1,c[i]=e=>e(d),c}}var u={};return u[i]=()=>{},u[a]=e,u});var t,r=()=>c.map(e=>{if(e[s])return e;if(e[o])throw e[o];return e[a]}),u=new Promise(e=>{(t=()=>e(r)).r=0;var a=e=>e!==d&&!m.has(e)&&(m.add(e),e&&!e.d&&(t.r++,e.push(t)));c.map(e=>e[s]||e[i](a))});return t.r?u:r()},e=>(e?p(k[o]=e):u(f),l(d),k[n]=!0)),d&&d.d<0&&(d.d=0)},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,g.t=function(e,t){if(1&t&&(e=this(e)),8&t||"object"==typeof e&&e&&(4&t&&e.__esModule||16&t&&"function"==typeof e.then))return e;var r=Object.create(null);g.r(r);var i={};d=d||[null,c({}),c([]),c(c)];for(var a=2&t&&e;("object"==typeof a||"function"==typeof a)&&!~d.indexOf(a);a=c(a))Object.getOwnPropertyNames(a).forEach(t=>{i[t]=()=>e[t]});return i.default=()=>e,g.d(r,i),r},g.d=(e,t)=>{for(var r in t)g.o(t,r)&&!g.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},g.f={},g.e=e=>Promise.all(Object.keys(g.f).reduce((t,r)=>(g.f[r](e,t),t),[])),g.u=e=>""+e+".mjs",g.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),g.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},g.p="",g.rv=()=>"1.7.6",u={43:0},p=e=>{var t,r,i=e.__rspack_esm_ids,a=e.__webpack_modules__,o=e.__rspack_esm_runtime,n=0;for(t in a)g.o(a,t)&&(g.m[t]=a[t]);for(o&&o(g);n<i.length;n++)r=i[n],g.o(u,r)&&u[r]&&u[r][0](),u[i[n]]=0},g.f.j=function(e,t){var r=g.o(u,e)?u[e]:void 0;if(0!==r)if(r)t.push(r[1]);else{var i=import("./"+g.u(e)).then(p,t=>{throw 0!==u[e]&&(u[e]=void 0),t}),i=Promise.race([i,new Promise(t=>{r=u[e]=[t]})]);t.push(r[1]=i)}},g.ruid="bundler=rspack@1.7.6",g(569);
|