qlogicagent 2.12.4 → 2.12.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/dist/cli.js
CHANGED
|
@@ -1039,7 +1039,7 @@ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;as
|
|
|
1039
1039
|
`)})}function kj(){return Sd("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","### Background execution & parallel fan-out","- `agent(background=true)` returns a task id immediately and keeps working \u2014 use it for independent subtasks so you can continue in parallel. Launch several in one message for parallel work.","- `exec(background=true)` does the same for long-running commands (dev servers, builds, watchers).",'- Track background work with the `task` tool: action "output" reads status/output by taskId, action "cancel" stops it; `list` shows active background tasks.',"- Completed background tasks are announced automatically at the start of your next turn \u2014 you do not need to busy-poll.","- For multi-step plans, create checklist tasks first, then fan out unblocked independent steps to background agents and set each checklist task's owner to the returned task id.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify genuinely ambiguous requests before proceeding.","For ordinary creative media requests, infer sensible defaults and use the appropriate media tool directly.","Ask before media generation only when a missing detail is critical to the result or the user is choosing among materially different outputs.","","## Project Rules Management","You can create, edit, and delete project rule files at `.qlogicagent/rules/*.md`.","These files are loaded into your system prompt every turn \u2014 changes take effect immediately.","Use this to help users establish coding conventions, workflow guidelines, or project-specific instructions.","When the user asks to 'add a rule', 'set up conventions', or 'configure instructions', write to `.qlogicagent/rules/<descriptive-name>.md`.","You may also create or edit `.qlogicagent/INSTRUCTIONS.md` for a single top-level instruction file.","","## File Operations \u2014 Use Dedicated Tools","File operations (creating, modifying, or deleting files) should use the dedicated `write` / `edit` / `read` tools, which take structured file-path arguments.","Do NOT use shell redirection (`echo >`, `cat >`, `>>`, `tee`) to create or modify files.","Use `exec` only for real commands (build, test, git, package managers).","This keeps file paths explicit and permission checks accurate.","","### Choosing among the edit tools","- `write` \u2014 create a new file or fully replace one. Overwrites.","- `edit` \u2014 single-file, exact-string replacement for precise surgical edits. Call it repeatedly for multiple edits in one file.","- `patch` / `apply_patch` \u2014 multi-file changes in one shot via the V4A diff format (`*** Begin Patch` \u2026 `*** End Patch`), incl. Add/Update/Delete/Move. Prefer for cross-file refactors.","Do NOT reach for `patch` to change one line in one file \u2014 use `edit`.","","### Searching \u2014 prefer `search` over `exec grep`","Use the `search` tool for finding files/content: it excludes VCS and dependency dirs (`.git`, `node_modules`, `dist`, \u2026) and returns structured matches. `exec grep -r` scans those too, so the two can disagree \u2014 `search` is the consistent, intended path.","","## Deliverable Discipline \u2014 Long Output Goes to Files","The chat window is a conversation surface, not a document dump. Users see deliverables in the workspace file tree and the side panel.","- Long documents/plans/designs/reports/tutorials (anything beyond ~40 lines) MUST be written to a workspace file (e.g. `docs/` or an appropriate project directory) using the file tools. In chat, reply with a 3-5 sentence summary and reference the file \u2014 do NOT paste the full document into the conversation.","- Code longer than ~30 lines belongs in a workspace file; in chat, reference the file path and quote only the key fragment.","- Generated media is already persisted to the workspace `assets/` directory automatically \u2014 do not repeat raw URL lists in your reply."].join(`
|
|
1040
1040
|
`))}function kw(t){return Sd("language",()=>t?["# Language","",`Always respond in ${t}.`,`Use ${t} for all text output, explanations, and descriptions.`,"Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
|
|
1041
1041
|
`):["# Language","","Respond in the same language as the user's message.","If the user writes in English, respond in English. If in Chinese, respond in Chinese.","Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
|
|
1042
|
-
`))}var wj={requiresFreshTool:!1,allowedToolNames:[]},bte=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],ww=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${bte.join("|")})\\b`,"i"),kte=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,wte=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,Ste=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,xte=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,Rte=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,Tte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,Pte=/https?:\/\/\S+/i,Ate=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,Ite=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i,Cte=/(?:\btts\b|\btext[-\s]?to[-\s]?speech\b|\bread\s+(?:this\s+)?(?:aloud|out)\b|\bgenerate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bcreate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bmake\s+(?:a\s+)?(?:voice\s+message|spoken\s+audio)\b|\u6587\u5b57\u8f6c\u8bed\u97f3|\u8bed\u97f3\u5408\u6210|\u8f6c\u6210\u8bed\u97f3|\u8f6c\u8bed\u97f3|\u751f\u6210.*(?:\u8bed\u97f3|\u97f3\u9891|\u58f0\u97f3|\u5f55\u97f3|\u6709\u58f0)|(?:\u8bfb|\u6717\u8bfb|\u64ad\u62a5|\u914d\u97f3|\u65c1\u767d).*(?:\u4e00\u6bb5|\u8fd9\u6bb5|\u8fd9\u4e9b|\u6587\u5b57|\u5185\u5bb9|\u8bed\u97f3|\u97f3\u9891)?)/i,_te=/(?:\bmusic_generate\b|\bgenerate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bcreate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bmake\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\u751f\u6210.*(?:\u6b4c\u66f2|\u97f3\u4e50|\u65cb\u5f8b|\u914d\u4e50|\u80cc\u666f\u97f3\u4e50|\u7eaf\u97f3\u4e50|\u54fc\u5531)|(?:\u4f5c\u66f2|\u7f16\u66f2|\u5199\u4e00\u9996\u6b4c))/i,Ete=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function xj(t){let e=typeof t=="string"?t:Aj(t);return e.trim()?_te.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:Cte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:Ite.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:Pte.test(e)&&Ate.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:wte.test(e)&&ww.test(e)||Ste.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:kte.test(e)&&ww.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:ww.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:xte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:Rte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:Tte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:wj:wj}function Rj(t){let r=(typeof t=="string"?t:Aj(t)).trim();return!r||r.length>24?!1:Ete.test(r)}var Mte=new Set(["think","task","agent","ask_user"]);function Tj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=Sj(i);return r.has(s)||Mte.has(s)});return n.some(i=>r.has(Sj(i)))?n:[...t]}function Pj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return Er("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
|
|
1042
|
+
`))}var wj={requiresFreshTool:!1,allowedToolNames:[]},bte=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],ww=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${bte.join("|")})\\b`,"i"),kte=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,wte=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,Ste=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,xte=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,Rte=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,Tte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,Pte=/https?:\/\/\S+/i,Ate=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,Ite=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i,Cte=/(?:\btts\b|\btext[-\s]?to[-\s]?speech\b|\bread\s+(?:this\s+)?(?:aloud|out)\b|\bgenerate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bcreate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bmake\s+(?:a\s+)?(?:voice\s+message|spoken\s+audio)\b|\u6587\u5b57\u8f6c\u8bed\u97f3|\u8bed\u97f3\u5408\u6210|\u8f6c\u6210\u8bed\u97f3|\u8f6c\u8bed\u97f3|\u751f\u6210.*(?:\u8bed\u97f3|\u97f3\u9891|\u58f0\u97f3|\u5f55\u97f3|\u6709\u58f0)|(?:\u8bfb|\u6717\u8bfb|\u64ad\u62a5|\u914d\u97f3|\u65c1\u767d).*(?:\u4e00\u6bb5|\u8fd9\u6bb5|\u8fd9\u4e9b|\u6587\u5b57|\u5185\u5bb9|\u8bed\u97f3|\u97f3\u9891)?)/i,_te=/(?:\bmusic_generate\b|\bgenerate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bcreate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bmake\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\u751f\u6210.*(?:\u6b4c\u66f2|\u97f3\u4e50|\u65cb\u5f8b|\u914d\u4e50|\u80cc\u666f\u97f3\u4e50|\u7eaf\u97f3\u4e50|\u54fc\u5531)|(?:\u4f5c\u66f2|\u7f16\u66f2|\u5199\u4e00\u9996\u6b4c))/i,Ete=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function xj(t){let e=typeof t=="string"?t:Aj(t);return e.trim()?_te.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:Cte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:Ite.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:Pte.test(e)&&Ate.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:wte.test(e)&&ww.test(e)||Ste.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:kte.test(e)&&ww.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:ww.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:xte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:Rte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:Tte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:wj:wj}function Rj(t){let r=(typeof t=="string"?t:Aj(t)).trim();return!r||r.length>24?!1:Ete.test(r)}var Mte=new Set(["think","task","agent","ask_user","team","send_message"]);function Tj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=Sj(i);return r.has(s)||Mte.has(s)});return n.some(i=>r.has(Sj(i)))?n:[...t]}function Pj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return Er("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
|
|
1043
1043
|
`));if(t.reason==="memory-mutation")return Er("fresh_workspace_evidence",()=>["# Memory File Action Required","","The latest user request explicitly asks to use the memory tool for a memory file action.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use the requested memory action and target filename instead of workspace file write/edit tools.","For removal requests, call memory with action='remove' and set old_text to the exact INDEX.md line or labeled marker line the user asked to remove.","Do not call action='add', action='remember', or action='create_file' for a removal request.","Do not merely describe the memory content or create a regular workspace file."].join(`
|
|
1044
1044
|
`));if(t.reason==="media-generation"){let r=t.mediaKind==="tts"?"spoken audio / text-to-speech":t.mediaKind==="music"?"music or song":"image",n=t.mediaKind==="tts"?"Do not answer by saying you cannot generate audio when the TTS tool is available, and do not invent a placeholder audio URL.":t.mediaKind==="music"?"Do not answer by describing music in text or inventing a placeholder audio URL.":"Do not answer by inventing a Markdown image URL or placeholder attachment path.",o=t.mediaKind==="tts"?"Use TTS for spoken-word output, narration, reading text aloud, or voice messages. STT is only for transcribing incoming speech.":t.mediaKind==="music"?"Use music generation for songs, melodies, BGM, or sung/musical output; use TTS only for spoken words.":"Use image generation for pictures, illustrations, posters, avatars, or visual output.";return Er("fresh_workspace_evidence",()=>["# Media Generation Required","",`The latest user request asks you to create ${r}.`,`Before answering, call the appropriate media tool for this turn: ${e}.`,n,o,"For ordinary creative requests, infer reasonable defaults for purpose, style, and size instead of asking follow-up questions.","Ask the user only when a missing detail is critical to the result or the request is genuinely ambiguous."].join(`
|
|
1045
1045
|
`))}return Er("fresh_workspace_evidence",()=>["# Fresh Workspace Evidence","","The latest user request asks for current workspace, shell, or URL state.",`Before answering, call one of these tools for this turn: ${e}.`,"Do not answer this request from conversation history, memory, or prior tool results.","For an explicit filename, inspect that exact file first and report the observed value.","If the filename is not found at the given path, use search to locate it, then read the located file before answering.","A filename search alone is not enough to answer content or code-symbol questions."].join(`
|
|
@@ -1190,12 +1190,12 @@ ${s.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
|
|
|
1190
1190
|
`)}],details:{type:"team",action:"create",teamName:n.team.name}}}case"delete":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let n=await t.deleteTeam(r.teamName);return n.success?{content:[{type:"text",text:`Team "${r.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:r.teamName}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}}}case"list":{let n=await t.listTeams();if(!n.teams||n.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let o=[`Active teams (${n.teams.length}):`,""];for(let i of n.teams)o.push(`- **${i.name}**: ${i.description||"(no description)"} \u2014 ${i.members.length} members`);return{content:[{type:"text",text:o.join(`
|
|
1191
1191
|
`)}],details:{type:"team",action:"list",count:n.teams.length}}}case"status":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let n=await t.getTeamStatus(r.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=n.team,i=n.memberProgress??{},s=[`Team: ${o.name}`,`Description: ${o.description||"\u2014"}`,`Lead: ${o.leadId}`,`Created: ${o.createdAt}`,"",`Members (${o.members.length}):`];for(let a of o.members){let c=a.tools?` [tools: ${a.tools.join(", ")}]`:"",u=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",d=i[a.name],p=a.isActive===!1?" (idle)":" (active)";if(d){let m=[];if(d.runningFor&&m.push(`running ${Math.round(d.runningFor/1e3)}s`),d.lastToolCall&&m.push(`tool: ${d.lastToolCall}`),d.idleFor!==void 0&&d.idleFor>5&&m.push(`idle ${d.idleFor}s`),d.mediaProgress){let g=d.mediaProgress;m.push(`${g.mediaType} ${g.percent}% [${g.status}] taskId=${g.taskId}${g.provider?` provider=${g.provider}`:""}`)}m.length&&(p=` (${m.join(", ")})`)}s.push(` - ${a.name} (${a.role})${c}${u}${p}`)}return{content:[{type:"text",text:s.join(`
|
|
1192
1192
|
`)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}import*as RU from"node:path";ve();function One(t){if(t&&typeof t=="object"&&"content"in t){let e=t.content;if(typeof e=="string")return e}return""}function jne(t,e){return`[message from ${e}]
|
|
1193
|
-
${t}`}function TU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Zt({onNotification:(s,a,c)=>{t.sendNotification("team.member.notification",{memberId:s,method:a,params:c})},onStateChange:(s,a)=>{t.sendNotification("team.member.state",{memberId:s,state:a});let c=i.getHandle(s),d=i.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,a,{missedBeats:i.getMissedBeats(s),lastActivityAt:c?.lastActivityAt,usage:d&&d.totalTokens>0?{inputTokens:d.inputTokens,outputTokens:d.outputTokens,totalTokens:d.totalTokens}:void 0})},onExit:(s,a,c)=>{for(let u of n.values()){let d=u.members.find(p=>p.cwd&&Aa(u.name,p.name)===s);d&&(d.isActive=!1)}r.unregister(s),e.info(`[team] member ${s} exited (code=${a}, signal=${c})`)},onMcpToolCall:(s,a,c)=>t.handleMcpToolCall(s,a,c),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:RU.join(H().getUserAgentHome(),"agent-logs")});return{async createTeam(s){if(n.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let a=await na(),c=[];for(let m of s.members??[]){let g={...m,isActive:!0};if(a){let f=`team-${s.teamName}-${m.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),h=await mE(a,f,o);h?(g.worktreePath=h.worktreePath,g.worktreeBranch=h.branch,g.cwd=h.worktreePath,e.info(`[team] provisioned worktree for ${m.name}: ${h.worktreePath}`)):(g.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${m.name}, using shared cwd`))}else g.cwd=process.cwd();c.push(g)}let u={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:c,createdAt:new Date().toISOString()};n.set(s.teamName,u);let d=[];for(let m of c){if(!m.cwd)continue;let g=Aa(s.teamName,m.name);try{await i.spawn({memberId:g,name:m.name,cwd:m.cwd,prompt:`You are the "${m.name}" team member. Role: ${m.role}.`,agentType:m.role,verbose:t.verbose}),r.register({memberId:g,name:m.name,teamName:s.teamName,role:m.role,deliver:async(
|
|
1193
|
+
${t}`}function TU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Zt({onNotification:(s,a,c)=>{t.sendNotification("team.member.notification",{memberId:s,method:a,params:c})},onStateChange:(s,a)=>{t.sendNotification("team.member.state",{memberId:s,state:a});let c=i.getHandle(s),d=i.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,a,{missedBeats:i.getMissedBeats(s),lastActivityAt:c?.lastActivityAt,usage:d&&d.totalTokens>0?{inputTokens:d.inputTokens,outputTokens:d.outputTokens,totalTokens:d.totalTokens}:void 0})},onExit:(s,a,c)=>{for(let u of n.values()){let d=u.members.find(p=>p.cwd&&Aa(u.name,p.name)===s);d&&(d.isActive=!1)}r.unregister(s),e.info(`[team] member ${s} exited (code=${a}, signal=${c})`)},onMcpToolCall:(s,a,c)=>t.handleMcpToolCall(s,a,c),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:RU.join(H().getUserAgentHome(),"agent-logs")});return{async createTeam(s){if(n.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let a=await na(),c=[];for(let m of s.members??[]){let g={...m,isActive:!0};if(a){let f=`team-${s.teamName}-${m.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),h=await mE(a,f,o);h?(g.worktreePath=h.worktreePath,g.worktreeBranch=h.branch,g.cwd=h.worktreePath,e.info(`[team] provisioned worktree for ${m.name}: ${h.worktreePath}`)):(g.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${m.name}, using shared cwd`))}else g.cwd=process.cwd();c.push(g)}let u={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:c,createdAt:new Date().toISOString()};n.set(s.teamName,u);let d=[];for(let m of c){if(!m.cwd)continue;let g=Aa(s.teamName,m.name);try{let f=t.getLlmConfig();await i.spawn({memberId:g,name:m.name,cwd:m.cwd,prompt:`You are the "${m.name}" team member. Role: ${m.role}.`,agentType:m.role,verbose:t.verbose,...f?{model:f.model,apiKey:f.apiKey,baseUrl:f.baseUrl}:{}}),r.register({memberId:g,name:m.name,teamName:s.teamName,role:m.role,deliver:async(h,y)=>One(await i.sendTask(g,jne(h,y))),isAlive:()=>i.isAlive(g)}),e.info(`[team] spawned child process for ${m.name} in ${m.cwd}`)}catch(f){let h=f instanceof Error?f.message:String(f);e.warn(`[team] failed to spawn child process for ${m.name}: ${h}`),m.isActive=!1,d.push({name:m.name,error:h})}}let p=c.filter(m=>m.cwd).length;return p>0&&d.length===p?(n.delete(s.teamName),{success:!1,error:`All ${p} team member(s) failed to spawn: `+d.map(m=>`${m.name} (${m.error})`).join("; ")}):(t.sendNotification("team.updated",{teamName:s.teamName,action:"created",members:u.members.map(m=>({agentName:m.name,role:m.role,worktreePath:m.worktreePath,pid:i.getHandle(Aa(s.teamName,m.name))?.pid}))}),d.length>0?{success:!0,team:u,partialFailures:d}:{success:!0,team:u})},async deleteTeam(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};for(let u of a.members){let d=Aa(s,u.name);r.unregister(d),i.kill(d),i.remove(d)}let c=await na();if(c)for(let u of a.members)u.worktreePath&&u.worktreeBranch&&(await gE(c,u.worktreePath,u.worktreeBranch,o),e.info(`[team] cleaned up worktree for ${u.name}: ${u.worktreePath}`));return n.delete(s),t.sendNotification("team.updated",{teamName:s,action:"destroyed",members:[]}),{success:!0}},async listTeams(){return{success:!0,teams:[...n.values()]}},async getTeamStatus(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};let c={};for(let u of a.members){let d=Aa(s,u.name),p=i.getStatus(d);p&&(u.isActive=p.alive,c[u.name]={mediaProgress:p.mediaProgress,lastToolCall:p.lastToolCall,idleFor:p.idleFor,runningFor:p.runningFor})}return{success:!0,team:a,memberProgress:c}},dispose(){i.dispose()}}}function Aa(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function PU({host:t,log:e,toolCatalog:r,teamRegistry:n}){let o=TU(t,e,n);Fr(async()=>o.dispose()),r.addTool(xU(o))}var Lne="send_message",Une={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function AU(t){return{name:Lne,label:"Send Message",isEgress:!0,egressCarriesData:!0,description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:Une,execute:async(e,r)=>{if(!r.to||r.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!r.message||r.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(r.to!=="*"&&t.listTeammates){let s=t.listTeammates();if(!s.includes(r.to))return{content:[{type:"text",text:`Error: agent "${r.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let n=await t.sendMessage({to:r.to.trim(),message:r.message.trim(),summary:r.summary,senderId:t.getSenderId()});if(!n.success)return{content:[{type:"text",text:`Message delivery failed: ${n.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:n.error}};let o=r.to==="*"?`broadcast (${n.recipients?.length||0} recipients)`:r.to,i=n.replies?.length?`
|
|
1194
1194
|
|
|
1195
1195
|
`+n.replies.map(s=>`${s.name} replied:
|
|
1196
1196
|
${s.reply}`).join(`
|
|
1197
1197
|
|
|
1198
|
-
`):"";return{content:[{type:"text",text:`Message sent to ${o}.${i}`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients,replies:n.replies}}}}}function IU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(AU({sendMessage:async o=>{e.info(`[send_message] ${o.senderId} -> ${o.to}: ${o.message}`);let i=await n.deliver(o.to,o.message,o.senderId);return i.ok?{success:!0,recipients:i.replies?.map(s=>s.name)??[],replies:i.replies}:{success:!1,error:i.error}},getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>n.list().filter(o=>o.alive).map(o=>o.name)}))}function CU(t){let e=new qd;nU({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host),getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext()},hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),pU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),vU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),SU({log:t.log,toolCatalog:t.toolCatalog}),cU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),PU({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log,toolCatalog:t.toolCatalog,teamRegistry:e}),IU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Fne={id:"cli-core-tools",kind:"core",register:Hne};function _U(t){Fne.register(t)}function Hne(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext(),sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,i){t.host.emitAgentStatus(n,o,i)},handleMcpToolCall(n,o,i){return t.host.handleMcpToolCall(n,o,i)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker};CU(r)}var zne={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
1198
|
+
`):"";return{content:[{type:"text",text:`Message sent to ${o}.${i}`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients,replies:n.replies}}}}}function IU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(AU({sendMessage:async o=>{e.info(`[send_message] ${o.senderId} -> ${o.to}: ${o.message}`);let i=await n.deliver(o.to,o.message,o.senderId);return i.ok?{success:!0,recipients:i.replies?.map(s=>s.name)??[],replies:i.replies}:{success:!1,error:i.error}},getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>n.list().filter(o=>o.alive).map(o=>o.name)}))}function CU(t){let e=new qd;nU({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host),getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext()},hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),pU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),vU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),SU({log:t.log,toolCatalog:t.toolCatalog}),cU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),PU({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},getLlmConfig:()=>t.host.getLlmConfig(),sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log,toolCatalog:t.toolCatalog,teamRegistry:e}),IU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Fne={id:"cli-core-tools",kind:"core",register:Hne};function _U(t){Fne.register(t)}function Hne(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentBaseUrl(){return t.host.getCurrentBaseUrl()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext(),getLlmConfig:()=>{let n=t.host.getCurrentModel(),o=t.host.getCurrentApiKey();return!n||!o?null:{model:n,apiKey:o,baseUrl:t.host.getCurrentBaseUrl()||void 0}},sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,i){t.host.emitAgentStatus(n,o,i)},handleMcpToolCall(n,o,i){return t.host.handleMcpToolCall(n,o,i)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker};CU(r)}var zne={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
1199
1199
|
- goToDefinition: jump to symbol definition
|
|
1200
1200
|
- findReferences: find all usages of a symbol
|
|
1201
1201
|
- hover: get type/docs for symbol at position
|
|
@@ -1252,6 +1252,6 @@ CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled
|
|
|
1252
1252
|
Available skills:
|
|
1253
1253
|
${n}`}ve();import{randomUUID as tie}from"node:crypto";var Zoe=10080*60*1e3;function Joe(t){return{async record(e){if(!t)return"disabled";try{let r=await t.getConsent();return!r.enabled||!r.signalsEnabled?"disabled":(await t.recordSignal(e),"recorded")}catch{return"failed"}},async recordSkillUsage(e,r){let n=Uw(e);return n?this.record({resourceId:n,event:r,attribution:"skill-subturn",metadata:{skillName:e?.name,version:e?.registryVersion,effectiveRiskTier:e?.registryEffectiveRiskTier}}):"skipped"},async recordSkillLifecycle(e,r){let n=Uw(e);return n?this.record({resourceId:n,event:r,attribution:"skill-lifecycle",metadata:{skillName:e?.name,version:e?.registryVersion}}):"skipped"},async recordKeptSignals(e,r={}){let n=r.now??new Date,o=r.retentionMs??Zoe,i=[];for(let s of Object.values(e.records)){if(!Xoe(s,n,o))continue;let a=await this.recordSkillLifecycle(s,"kept");a==="recorded"&&(s.registryKeptSignalAt=n.toISOString()),i.push({skillName:s.name,status:a})}return i}}}function lF(){let t=xr();return t?Joe(t):null}function Uw(t){return t?.source!=="installed"||t.registrySourceTier==="official"?null:t.registryResourceId??t.name}function Xoe(t,e,r){if(!Uw(t)||t.registryKeptSignalAt)return!1;let n=Date.parse(t.lastUsedAt??t.createdAt);return Number.isFinite(n)?e.getTime()-n>=r:!1}import{spawn as IMe}from"node:child_process";function uF(t={}){let e=t.platform??process.platform;if(e!=="win32")return{level:"L0",available:!1,backend:"unsupported-platform",platform:e,reason:"unsupported-platform"};let r=t.processTreeLauncherAvailable===!0||t.jobObjectAvailable===!0;return{level:"L0",available:r,backend:r?"windows-process-tree-launcher":"unavailable",platform:e,reason:r?void 0:"windows-l0-not-provisioned"}}function dF(){return{envelope:"l0-launcher-audit-v1",backend:"windows-process-tree-launcher",defaultHostAccess:!0,noFsNetworkRestriction:!0,processTree:{killOnClose:!0,trackChildren:!0},jobObject:{implemented:!1,ready:!0}}}function Yoe(t={}){let e=t.availability??uF({platform:t.platform,appContainerAvailable:t.appContainerAvailable,jobObjectAvailable:t.jobObjectAvailable,processTreeLauncherAvailable:t.processTreeLauncherAvailable});return{getAvailability(){return e},decide(r){if(r.origin==="first-party"||r.origin==="official"||r.official===!0)return{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"first-party-action",backend:"first-party",l0:e};if(r.origin==="community"&&r.executable===!0){let o=e.available?"launcher-required":"launcher-unavailable";return{allowed:e.available,spawnAllowed:e.available,launcherRequired:!0,reason:o,backend:"community-l0-launcher",l0:e,launcher:eie(r,e.available?"allowed":"blocked",o)}}let n=r.riskTier??"unknown";return!Qoe(n)||!r.executable?{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"community-low-risk",backend:"community-l1-l2",l0:e}:r.autoRun===!1?{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"manual-run",backend:"community-l1-l2",l0:e}:{allowed:e.available,spawnAllowed:e.available,launcherRequired:!0,reason:e.available?"l0-available":"l0-unavailable",backend:"community-l0",l0:e}}}}function pF(){return Yoe()}function Qoe(t){return t==="R2"||t==="R3"}function eie(t,e,r){return{level:"L0",mode:"os-native-launcher",defaultHostAccess:!0,noFsNetworkRestriction:!0,audit:{envelope:"l0-launcher-audit-v1",subject:{origin:t.origin,official:t.official===!0,executable:t.executable===!0,autoRun:t.autoRun===!0},decision:e,reason:r},windows:dF()}}async function fF(t){let{host:e,toolCatalog:r,skillName:n,skillContent:o,userArgs:i,signal:s}=t,a=`skill_${n}_${tie().slice(0,8)}`,c=e.getAgent();if(!c)return"[skill] Cannot execute: no LLM provider configured";let u=H().getOwnerProfileDir(),d=e.getCurrentSessionId()||"skill",p=Ae(u).records[n],m=t.communitySignalReporter??lF(),g=(t.skillSandbox??pF()).decide({origin:yF(p)?"community":"first-party",riskTier:p?.registryEffectiveRiskTier??p?.registryRiskTier??"unknown",executable:!0,autoRun:!0});if(!g.allowed)return await m?.recordSkillUsage(p,"fail"),`[skill "${n}"] blocked: community ${g.reason} (${g.l0.reason??g.l0.backend})`;let f=hF(n,p);e.getCurrentHooks()?.invoke("subagent.started",{sessionId:d,turnId:a,subagentId:a,agentType:f}).catch(()=>{});let h=new Set(["skill","agent"]),y=r.getToolManifest().filter(b=>!h.has(b.function.name)),S=i??`Execute skill "${n}" instructions.`,w=[],v;for await(let b of c.run({turnId:a,sessionId:d,messages:[{role:"user",content:S}],tools:y,systemPrompt:o,config:{parentDepth:1,maxRounds:5}},s)){if(b.type==="end"&&b.content)return mF(e,d,a,f,"normal"),gF(u,n,!0),await m?.recordSkillUsage(p,"success"),b.content;if(b.type==="delta"&&b.text&&w.push(b.text),b.type==="error"){v=b.error;break}}return mF(e,d,a,f,v?"error":"normal",v),v?(aw(u,n,!1),await m?.recordSkillUsage(p,"error"),`[skill "${n}"] error: ${v}`):(gF(u,n,!0),await m?.recordSkillUsage(p,"success"),w.join("")||`[skill "${n}"] completed (no output)`)}function hF(t,e){return rie(e)?`community-skill:${t}`:`skill:${t}`}function rie(t){return yF(t)}function yF(t){return t?.source!=="installed"?!1:t.registrySourceTier!=="official"}function mF(t,e,r,n,o,i){t.getCurrentHooks()?.invoke("subagent.stopped",{sessionId:e,turnId:r,subagentId:r,agentType:n,reason:o,error:i}).catch(()=>{})}function gF(t,e,r){aw(t,e,r);let n=Ae(t);cC(n,e),Ue(t,n)}var nie={id:"skill-meta-tool",kind:"skill",register:({host:t,...e})=>oie(t,e)};function vF(t,e){nie.register({...e,host:t})}function oie(t,e){let r=e.pathService;e.toolCatalog.addTool(cF({listSkills:()=>{let n=eC(t.getActiveProjectRoot()).map(o=>({name:o.name,description:o.description,source:o.enabledScope,filePath:o.filePath,baseDir:o.baseDir}));return n.push(...t.getPluginSkills()),n},listSkillsFull:async n=>{let o=[],i=new Set;for(let s of so(t.getActiveProjectRoot())){let a=s.enabledScope;n&&a!==n||(i.add(a),o.push({name:s.name,description:s.description??`Skill (${a})`,category:a,scope:s.enabledScope,version:s.version}))}for(let s of t.getPluginSkills())n&&s.source!==n||(i.add(s.source??"plugin"),o.push({name:s.name,description:`Plugin skill (${s.source})`,category:s.source,scope:"plugin"}));return{skills:o,categories:[...i]}},readSkillContent:async n=>{let o=ao(n);if(!o)return null;try{return await rr.promises.readFile(o.filePath,"utf8")}catch{return null}},viewSkill:async(n,o)=>{let i=ao(n);if(!i)return null;let s=o?_i.join(i.baseDir,o):i.filePath;try{let a=await rr.promises.readFile(s,"utf8");return{name:n,content:a}}catch{return null}},executeSkillSubturn:async(n,o,i,s)=>fF({host:t,toolCatalog:e.toolCatalog,skillName:n,skillContent:o,userArgs:i,signal:s}),manageSkill:async n=>{let o=t.getActiveProjectRoot(),i=r.getUserSkillsDir(),s=_i.join(i,n.name),a=_i.join(s,"SKILL.md"),c=r.getOwnerProfileDir();switch(n.action){case"create":{let u=n.content??"",p=ob(u,n.name,`Skill: ${n.name}`)??u,m=Wl(p,n.name);if(!m.valid)return{success:!1,message:`Skill validation failed: ${m.errors.join("; ")}`};let g=Ae(c);if(g.records[n.name]?.pinned&&rr.existsSync(a))return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};await rr.promises.mkdir(s,{recursive:!0}),await rr.promises.writeFile(a,p,"utf8"),t.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:p,scope:"project"}}),dt(),Ot(g,n.name,"created"),Ue(c,g),$n(n.name),o&&Ur(o,n.name);let f=t.getMemoryLearningSink(),h=t.getMemoryUserId();if(f&&h){let S=p.split(`
|
|
1254
1254
|
`).slice(0,3).join(" ").slice(0,200),w=o?_i.basename(o):"unknown";f.ingestExtracted([{text:`Learned skill "${n.name}" in project "${w}": ${S}`,category:"skill-learning"}],h).catch(()=>{})}let y=o?` (project-scoped). To make it available across all projects, use: skill promote name:"${n.name}"`:"";return{success:!0,message:`Skill "${n.name}" created${y}`,path:s}}case"edit":{let u=Ae(c);if(u.records[n.name]?.pinned)return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};let d=n.content??"",m=ob(d,n.name)??d;return await rr.promises.writeFile(a,m,"utf8"),tb(u,n.name),Ue(c,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:m,scope:"project"}}),{success:!0,message:`Skill "${n.name}" updated`,path:a}}case"patch":{let u=Ae(c);if(u.records[n.name]?.pinned)return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};let d=await rr.promises.readFile(a,"utf8");if(!n.oldString||!d.includes(n.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let p=d.replace(n.oldString,n.newString??"");return await rr.promises.writeFile(a,p,"utf8"),tb(u,n.name),Ue(c,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:p,scope:"project"}}),{success:!0,message:`Skill "${n.name}" patched`,path:a}}case"delete":{let u=Ae(c);return u.records[n.name]?.pinned?{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`}:(await rr.promises.rm(s,{recursive:!0,force:!0}),Hl(u,n.name),Ue(c,u),No(n.name),o&&Nn(o,n.name),t.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",action:"delete",scope:"project"}}),dt(),{success:!0,message:`Skill "${n.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${n.action}`}}},promoteSkill:async n=>{let o=ao(n);if(!o)return{success:!1,message:`Skill "${n}" not found in skill store. Cannot promote.`};let i=r.getOwnerProfileDir(),s=Ae(i),a=Ot(s,n);a.source="promoted",Ue(i,s),No(n);let c=t.getActiveProjectRoot();c&&Nn(c,n);let u="";try{u=await rr.promises.readFile(o.filePath,"utf8")}catch{}return t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:n,category:"promoted",content:u,scope:"global"}}),dt(),{success:!0,message:`Skill "${n}" promoted to global. It is now available across all projects.`,path:o.baseDir}}}))}function bF(t){let e=nF({log:t.log,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,projectRoot:t.projectRoot,memdir:t.memdir,toolCatalog:t.toolCatalog,currentUserId:t.currentUserId,prefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,compressionClient:{transport:t.agentClient.transport,apiKey:t.agentClient.apiKey},sendNotification:(o,i)=>t.sendNotification(o,i)}),r=e.hooks;qU({config:t.config,projectRoot:t.projectRoot,pathService:t.pathService,log:t.log,toolCatalog:t.toolCatalog,currentManager:t.currentMcpManager,setManager:t.setMcpManager,setReady:t.setMcpReady}),JU({config:t.config,hooks:r,log:t.log,pathService:t.pathService,toolCatalog:t.toolCatalog,setPluginLoader:t.setPluginLoader});let n=QU({config:t.config,toolCatalog:t.toolCatalog,hooks:r,log:t.log,sessionId:t.sessionId,getTurnId:t.getTurnId,getActiveProjectRoot:()=>t.projectRoot,getActiveWorkdir:()=>t.pathService.getActiveWorkdir(),getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentUnregister:t.currentPermissionUnregister});return vF({getActiveProjectRoot:()=>t.projectRoot,getPluginSkills:t.getPluginSkills,getAgent:t.getAgent,getCurrentSessionId:()=>t.sessionId,getCurrentHooks:()=>r,sendNotification:t.sendNotification,getMemoryLearningSink:()=>e.memoryLearningSink,getMemoryUserId:()=>e.memoryUserId},{config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),_U({config:t.config,host:t.coreToolHost,hooks:r,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),UU({config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),t.sessionId&&r.invoke("session.created",{sessionId:t.sessionId}).catch(()=>{}),aF({config:t.config,hooks:r,ruleEngine:n.ruleEngine,sessionId:t.sessionId,currentFileWatcher:t.currentFileWatcher,log:t.log,setFileWatcher:t.setFileWatcher}),{hooks:r,memoryHandlerProvider:e.memoryHandlerProvider,memoryDreamProvider:e.memoryDreamProvider,memoryUserId:e.memoryUserId,permissionChecker:n.permissionChecker,permissionUnregister:n.permissionUnregister,ruleEngine:n.ruleEngine}}function kF(t){let{provider:e,model:r,apiKey:n,baseUrl:o}=t.resolvedConfig,i=hu({provider:e,model:r,apiKey:n,baseUrl:o},t.providerRegistry);return i.transport=pM(i.transport,t.sessionId||"default"),{transport:i.transport,apiKey:n,model:r,provider:e,baseUrl:o??""}}function wF(t){return{agent:new Fo({llmTransport:t.client.transport,apiKey:t.client.apiKey,toolInvoker:t.toolInvoker,log:t.log,hooks:t.hooks,maxRounds:t.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot,runtimePorts:fc()}),...t.client}}import{randomUUID as iie}from"node:crypto";async function SF(t){let e=[],r=t.result.content.map(d=>{if(d.type==="image"&&d.data){let p=d.mimeType||"image/png";return e.push(`data:${p};base64,${d.data}`),"[Image]"}return d.text??""}).join(`
|
|
1255
|
-
`),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,i=o?r:void 0,s=t.result.details?.type,a=t.result.details?{...t.result.details}:void 0,c=s?.split("_")[0];if(s==="three_d_generate"&&(c="3d"),c&&["image","tts","video","music","3d"].includes(c)){let d=t.result.details?.mediaUrls??[];if(d.length>0)try{let p=await t.mediaPersistence.downloadAll(d,{type:c,sessionId:t.sessionId||void 0},{warn:m=>t.log(m)});if(p.length>0){let m=new Map(p.map(g=>[g.remoteUrl,GL(g.localPath)]));for(let g of p)r=r.replaceAll(g.remoteUrl,g.localPath);d=d.map(g=>m.get(g)??g),t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:p.map(g=>({remoteUrl:g.remoteUrl,localPath:g.localPath,bytes:g.bytes,mimeType:g.mimeType}))})}}catch{}a&&(a.mediaUrls=d)}if(s==="task"&&!o&&t.result.details?.taskList)try{let d=t.result.details;d?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:d.taskList,summary:{total:d.total??d.taskList.length,completed:d.completed??0,inProgress:d.inProgress??0,notStarted:d.notStarted??0}})}catch{}let u=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:i,toolReferences:u,imageUrls:n,details:a}}function xF(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let i=t.toolCatalog.findTool(r);if(!i)return{result:"",error:`Unknown tool: ${r}`};if(typeof i.execute!="function")return{result:"",error:`Tool is not executable: ${r}`};let s=i.execute,a=`tc_${iie().slice(0,8)}`;try{let c=JSON.parse(n),u=t.getSessionId(),d;try{d=t.mediaPersistence.getMediaDir()}catch{d=void 0}let p=await IM(d,()=>s(a,c,o));return await SF({turnId:e,sessionId:u,result:p,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(m,g)=>t.sendNotification(m,g)})}catch(c){return{result:"",error:c instanceof Error?c.message:String(c)}}}}}function RF(t){let e={info:s=>t.log(s),warn:s=>t.log(`[warn] ${s}`),error:s=>t.log(`[error] ${s}`),debug:s=>{t.verbose&&t.log(`[debug] ${s}`)}},r=xF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=kF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=bF({config:t.config,log:e,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,getTurnId:t.getTurnId,projectRoot:t.projectRoot,pathService:t.pathService,memdir:t.memdir,currentUserId:t.currentUserId,memoryPrefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,agentClient:n,toolCatalog:t.toolCatalog,currentMcpManager:t.runtimeSession.mcpManager,setMcpManager:t.setMcpManager,setMcpReady:t.setMcpReady,setPluginLoader:t.setPluginLoader,getPluginSkills:()=>t.runtimeSession.getPluginSkills(),getAgent:t.getAgent,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentPermissionUnregister:t.runtimeSession.permissionUnregister,coreToolHost:t.coreToolHost,toolInvoker:r,currentFileWatcher:t.runtimeSession.fileWatcher,setFileWatcher:t.setFileWatcher});return t.runtimeSession.applyBootstrap(o),{agent:wF({client:n,toolInvoker:r,log:e,hooks:o.hooks,maxRounds:t.config.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}).agent,agentClient:n,toolInvoker:r,hooks:o.hooks}}var aie=sie(import.meta.url);function cie(){for(let t of["../package.json","../../package.json"])try{return aie(t).version}catch{}return"0.0.0"}var TF=cie();var lie=new Set(["thread.user_response"]);var np=class{running=!1;startedAt=Date.now();packageVersion=TF;rpcContract=new Ui;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Nd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ua;backgroundTasks=new Fa(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=nr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Dd();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new Ld;idleDreamCoordinator;petConfirmCoordinator;modelRegistryHydration=null;get registry(){return this.runtimeServices.providerRegistry}get mediaClient(){return this.runtimeServices.mediaClient}get mediaPersistence(){return this.runtimeServices.mediaPersistence}get pathService(){return this.runtimeServices.pathService}get toolCatalog(){return this.runtimeServices.toolCatalog}get petRuntime(){return this.runtimeServices.petRuntime}get currentHooks(){return this.runtimeSession.currentHooks}get permissionChecker(){return this.runtimeSession.permissionChecker}set permissionChecker(e){this.runtimeSession.permissionChecker=e}set mcpManager(e){this.runtimeSession.mcpManager=e}get memoryProvider(){return this.runtimeSession.memoryProvider}set memoryProvider(e){this.runtimeSession.memoryProvider=e}get memoryDreamProvider(){return this.runtimeSession.memoryDreamProvider}set memoryDreamProvider(e){this.runtimeSession.memoryDreamProvider=e}get memoryUserId(){return this.runtimeSession.memoryUserId}set memoryUserId(e){this.runtimeSession.memoryUserId=e}constructor(e){this.verbose=e.verbose,this.runtimeServices=JL({verbose:e.verbose,getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Fd({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=NL({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Ud({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Gt(20,this.getActiveProjectRoot()),runDream:r=>zo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ao({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),this.backgroundTasks.onTaskSettled(r=>{this.pendingTaskNotifications.push(SS(r,r.output??r.error??""))})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}drainPendingTaskNotifications(){if(this.pendingTaskNotifications.length===0)return[];let e=this.pendingTaskNotifications;return this.pendingTaskNotifications=[],e}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=W();e.load(),await jn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){this.configureTurnMedia(void 0,this.currentTurnId||"tools-list")}configureTurnMedia(e,r){let n=this;this.runtimeServices.configureTurnMedia({host:{get currentMediaApiKeys(){return n.currentMediaApiKeys},set currentMediaApiKeys(o){n.currentMediaApiKeys=o},get sessionState(){return n.sessionState},sendNotification:(o,i)=>this.sendNotification(o,i)},config:e,turnId:r})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(Sm(e)||Hi(e)){this.acpServer.dispatchMessage(e);return}if(Fi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!km(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{await ZS(),this.runtimeSession.stopFileWatcher(),await this.runtimeSession.disconnectMcp(),this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=jj(this);handleMessage(e){if(e.id!==void 0&&!lie.has(e.method)){let n=Qa(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);if(r){let n=o=>{e.id!==void 0&&this.rpcIds.has(e.id)&&this.sendResponse(e.id,void 0,{code:k.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})};try{Promise.resolve(r(e)).catch(n)}catch(o){n(o)}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:k.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=HL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return OL({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=this.runtimeServices.ensureMemoryProvider(this.memoryUserId);this.runtimeSession.memoryProvider=e.handlerProvider,this.runtimeSession.memoryDreamProvider=e.dreamProvider,this.runtimeSession.memoryUserId=e.userId}resolveAgent(e){let r=$L(e,u=>this.log(u));if(!r)return null;let{provider:n,model:o,apiKey:i,baseUrl:s,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s),this.agent;e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s);let c=RF({config:e,taskStore:this.taskStore,backgroundTasks:this.backgroundTasks,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),pathService:this.pathService,memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),resolvedTextConfig:r,verbose:this.verbose,providerRegistry:this.registry,mediaPersistence:this.mediaPersistence,toolCatalog:this.toolCatalog,runtimeSession:this.runtimeSession,setMcpManager:u=>{this.runtimeSession.mcpManager=u},setMcpReady:u=>{this.runtimeSession.mcpReady=u},setPluginLoader:u=>{this.runtimeSession.pluginLoader=u},getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)?{sessionId:this.currentSessionId,requestPermission:u=>this.acpServer.requestPermission(u)}:void 0,sendNotification:(u,d)=>this.sendNotification(u,d),isPetActive:()=>this.petRuntime.isActive(),coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,getBackgroundTasks:()=>this.backgroundTasks,getConversationHistory:()=>this.currentSessionId?this.sessionHistory.getResumedHistory(this.currentSessionId):null,isGroupContext:()=>Ga(),sendNotification:(u,d)=>this.sendNotification(u,d),emitAgentStatus:(u,d,p)=>this.emitAgentStatus(u,d,p),handleMcpToolCall:(u,d,p)=>this.handleMcpToolCall(u,d,p)},setFileWatcher:u=>{this.runtimeSession.fileWatcher=u},log:u=>this.log(u)});return this.agent=c.agent,this.lastLlmConfigKey=a,this.currentTransport=c.agentClient.transport,this.currentApiKey=c.agentClient.apiKey,this.currentModel=c.agentClient.model,this.currentProvider=c.agentClient.provider,this.currentBaseUrl=c.agentClient.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}invalidateResolvedLlmCache(){this.agent=null,this.lastLlmConfigKey="",this.currentTransport=null,this.currentApiKey="",this.currentModel="",this.currentProvider="",this.currentBaseUrl="",this.currentMediaApiKeys=null}emitAgentStatus(e,r,n){this.sendNotification("agents.status",LL(e,r,n))}createDreamHandlerHost(){return UL({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getToolCatalog:()=>this.runtimeServices.toolCatalog,getTaskStore:()=>this.taskStore,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return zL({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e),pendingAskUser:this.pendingAskUser})}async handleMcpToolCall(e,r,n){return jL({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let s=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!s.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${s.reason}`);return}}let i={jsonrpc:"2.0",id:e};n?i.error=n:i.result=r,this.writeStdout(i)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),i=setTimeout(()=>{if(!this.rpcIds.has(e))return;let s=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),s&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:k.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);i.unref?.(),this.rpcDeadlineTimers.set(e,i)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(!(this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)&&ux(this.acpServer,this.currentSessionId,e,r))){let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
|
|
1255
|
+
`),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,i=o?r:void 0,s=t.result.details?.type,a=t.result.details?{...t.result.details}:void 0,c=s?.split("_")[0];if(s==="three_d_generate"&&(c="3d"),c&&["image","tts","video","music","3d"].includes(c)){let d=t.result.details?.mediaUrls??[];if(d.length>0)try{let p=await t.mediaPersistence.downloadAll(d,{type:c,sessionId:t.sessionId||void 0},{warn:m=>t.log(m)});if(p.length>0){let m=new Map(p.map(g=>[g.remoteUrl,GL(g.localPath)]));for(let g of p)r=r.replaceAll(g.remoteUrl,g.localPath);d=d.map(g=>m.get(g)??g),t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:p.map(g=>({remoteUrl:g.remoteUrl,localPath:g.localPath,bytes:g.bytes,mimeType:g.mimeType}))})}}catch{}a&&(a.mediaUrls=d)}if(s==="task"&&!o&&t.result.details?.taskList)try{let d=t.result.details;d?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:d.taskList,summary:{total:d.total??d.taskList.length,completed:d.completed??0,inProgress:d.inProgress??0,notStarted:d.notStarted??0}})}catch{}let u=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:i,toolReferences:u,imageUrls:n,details:a}}function xF(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let i=t.toolCatalog.findTool(r);if(!i)return{result:"",error:`Unknown tool: ${r}`};if(typeof i.execute!="function")return{result:"",error:`Tool is not executable: ${r}`};let s=i.execute,a=`tc_${iie().slice(0,8)}`;try{let c=JSON.parse(n),u=t.getSessionId(),d;try{d=t.mediaPersistence.getMediaDir()}catch{d=void 0}let p=await IM(d,()=>s(a,c,o));return await SF({turnId:e,sessionId:u,result:p,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(m,g)=>t.sendNotification(m,g)})}catch(c){return{result:"",error:c instanceof Error?c.message:String(c)}}}}}function RF(t){let e={info:s=>t.log(s),warn:s=>t.log(`[warn] ${s}`),error:s=>t.log(`[error] ${s}`),debug:s=>{t.verbose&&t.log(`[debug] ${s}`)}},r=xF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=kF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=bF({config:t.config,log:e,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,getTurnId:t.getTurnId,projectRoot:t.projectRoot,pathService:t.pathService,memdir:t.memdir,currentUserId:t.currentUserId,memoryPrefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,agentClient:n,toolCatalog:t.toolCatalog,currentMcpManager:t.runtimeSession.mcpManager,setMcpManager:t.setMcpManager,setMcpReady:t.setMcpReady,setPluginLoader:t.setPluginLoader,getPluginSkills:()=>t.runtimeSession.getPluginSkills(),getAgent:t.getAgent,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentPermissionUnregister:t.runtimeSession.permissionUnregister,coreToolHost:t.coreToolHost,toolInvoker:r,currentFileWatcher:t.runtimeSession.fileWatcher,setFileWatcher:t.setFileWatcher});return t.runtimeSession.applyBootstrap(o),{agent:wF({client:n,toolInvoker:r,log:e,hooks:o.hooks,maxRounds:t.config.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}).agent,agentClient:n,toolInvoker:r,hooks:o.hooks}}var aie=sie(import.meta.url);function cie(){for(let t of["../package.json","../../package.json"])try{return aie(t).version}catch{}return"0.0.0"}var TF=cie();var lie=new Set(["thread.user_response"]);var np=class{running=!1;startedAt=Date.now();packageVersion=TF;rpcContract=new Ui;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Nd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ua;backgroundTasks=new Fa(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=nr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Dd();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new Ld;idleDreamCoordinator;petConfirmCoordinator;modelRegistryHydration=null;get registry(){return this.runtimeServices.providerRegistry}get mediaClient(){return this.runtimeServices.mediaClient}get mediaPersistence(){return this.runtimeServices.mediaPersistence}get pathService(){return this.runtimeServices.pathService}get toolCatalog(){return this.runtimeServices.toolCatalog}get petRuntime(){return this.runtimeServices.petRuntime}get currentHooks(){return this.runtimeSession.currentHooks}get permissionChecker(){return this.runtimeSession.permissionChecker}set permissionChecker(e){this.runtimeSession.permissionChecker=e}set mcpManager(e){this.runtimeSession.mcpManager=e}get memoryProvider(){return this.runtimeSession.memoryProvider}set memoryProvider(e){this.runtimeSession.memoryProvider=e}get memoryDreamProvider(){return this.runtimeSession.memoryDreamProvider}set memoryDreamProvider(e){this.runtimeSession.memoryDreamProvider=e}get memoryUserId(){return this.runtimeSession.memoryUserId}set memoryUserId(e){this.runtimeSession.memoryUserId=e}constructor(e){this.verbose=e.verbose,this.runtimeServices=JL({verbose:e.verbose,getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Fd({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=NL({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Ud({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Gt(20,this.getActiveProjectRoot()),runDream:r=>zo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ao({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),this.backgroundTasks.onTaskSettled(r=>{this.pendingTaskNotifications.push(SS(r,r.output??r.error??""))})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}drainPendingTaskNotifications(){if(this.pendingTaskNotifications.length===0)return[];let e=this.pendingTaskNotifications;return this.pendingTaskNotifications=[],e}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=W();e.load(),await jn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){this.configureTurnMedia(void 0,this.currentTurnId||"tools-list")}configureTurnMedia(e,r){let n=this;this.runtimeServices.configureTurnMedia({host:{get currentMediaApiKeys(){return n.currentMediaApiKeys},set currentMediaApiKeys(o){n.currentMediaApiKeys=o},get sessionState(){return n.sessionState},sendNotification:(o,i)=>this.sendNotification(o,i)},config:e,turnId:r})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(Sm(e)||Hi(e)){this.acpServer.dispatchMessage(e);return}if(Fi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!km(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{await ZS(),this.runtimeSession.stopFileWatcher(),await this.runtimeSession.disconnectMcp(),this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=jj(this);handleMessage(e){if(e.id!==void 0&&!lie.has(e.method)){let n=Qa(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);if(r){let n=o=>{e.id!==void 0&&this.rpcIds.has(e.id)&&this.sendResponse(e.id,void 0,{code:k.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})};try{Promise.resolve(r(e)).catch(n)}catch(o){n(o)}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:k.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=HL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return OL({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=this.runtimeServices.ensureMemoryProvider(this.memoryUserId);this.runtimeSession.memoryProvider=e.handlerProvider,this.runtimeSession.memoryDreamProvider=e.dreamProvider,this.runtimeSession.memoryUserId=e.userId}resolveAgent(e){let r=$L(e,u=>this.log(u));if(!r)return null;let{provider:n,model:o,apiKey:i,baseUrl:s,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s),this.agent;e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s);let c=RF({config:e,taskStore:this.taskStore,backgroundTasks:this.backgroundTasks,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),pathService:this.pathService,memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),resolvedTextConfig:r,verbose:this.verbose,providerRegistry:this.registry,mediaPersistence:this.mediaPersistence,toolCatalog:this.toolCatalog,runtimeSession:this.runtimeSession,setMcpManager:u=>{this.runtimeSession.mcpManager=u},setMcpReady:u=>{this.runtimeSession.mcpReady=u},setPluginLoader:u=>{this.runtimeSession.pluginLoader=u},getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)?{sessionId:this.currentSessionId,requestPermission:u=>this.acpServer.requestPermission(u)}:void 0,sendNotification:(u,d)=>this.sendNotification(u,d),isPetActive:()=>this.petRuntime.isActive(),coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentBaseUrl:()=>this.currentBaseUrl,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,getBackgroundTasks:()=>this.backgroundTasks,getConversationHistory:()=>this.currentSessionId?this.sessionHistory.getResumedHistory(this.currentSessionId):null,isGroupContext:()=>Ga(),sendNotification:(u,d)=>this.sendNotification(u,d),emitAgentStatus:(u,d,p)=>this.emitAgentStatus(u,d,p),handleMcpToolCall:(u,d,p)=>this.handleMcpToolCall(u,d,p)},setFileWatcher:u=>{this.runtimeSession.fileWatcher=u},log:u=>this.log(u)});return this.agent=c.agent,this.lastLlmConfigKey=a,this.currentTransport=c.agentClient.transport,this.currentApiKey=c.agentClient.apiKey,this.currentModel=c.agentClient.model,this.currentProvider=c.agentClient.provider,this.currentBaseUrl=c.agentClient.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}invalidateResolvedLlmCache(){this.agent=null,this.lastLlmConfigKey="",this.currentTransport=null,this.currentApiKey="",this.currentModel="",this.currentProvider="",this.currentBaseUrl="",this.currentMediaApiKeys=null}emitAgentStatus(e,r,n){this.sendNotification("agents.status",LL(e,r,n))}createDreamHandlerHost(){return UL({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getToolCatalog:()=>this.runtimeServices.toolCatalog,getTaskStore:()=>this.taskStore,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveMemoryRoot:()=>Fw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return zL({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e),pendingAskUser:this.pendingAskUser})}async handleMcpToolCall(e,r,n){return jL({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let s=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!s.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${s.reason}`);return}}let i={jsonrpc:"2.0",id:e};n?i.error=n:i.result=r,this.writeStdout(i)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),i=setTimeout(()=>{if(!this.rpcIds.has(e))return;let s=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),s&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:k.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);i.unref?.(),this.rpcDeadlineTimers.set(e,i)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(!(this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)&&ux(this.acpServer,this.currentSessionId,e,r))){let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
|
|
1256
1256
|
`)}enableIdleDream(e){this.idleDreamCoordinator.enable(e)}cancelIdleDreamTimer(){this.idleDreamCoordinator.cancelTimer()}disposeSessionRuntime(){this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.agent=null,this.lastLlmConfigKey="",this.memoryPrefetchState=nr(),this.runtimeSession.resetAfterSessionDispose()}closeMemoryProviders(){this.runtimeServices.closeMemoryProviders({memoryProvider:this.memoryProvider,memoryDreamProvider:this.memoryDreamProvider}),this.runtimeSession.resetMemoryProviders()}initAcpServer(){let e=CL(this,TF,this.createAcpExtendedHandlerHost());this.acpServer=new ec(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}};function PF(t){let e={verbose:!1};for(let r of t.slice(2))(r==="--verbose"||r==="-v")&&(e.verbose=!0);return e}import{writeFileSync as uie,appendFileSync as IF,mkdirSync as die}from"node:fs";import{join as Hw}from"node:path";import{homedir as pie}from"node:os";var CF=Hw(process.env.QLOGICAGENT_HOME||Hw(pie(),".qlogicagent"),"debug-logs");try{die(CF,{recursive:!0})}catch{}var zw=Hw(CF,"acp-session.log");try{uie(zw,"")}catch{}function Ht(t){let e=`[${new Date().toISOString()}] ${t}
|
|
1257
1257
|
`;_F.call(process.stderr,e);try{IF(zw,e)}catch{}}var _F=process.stderr.write.bind(process.stderr);process.stderr.write=((t,...e)=>{let r=typeof t=="string"?t:Buffer.from(t).toString();try{IF(zw,r)}catch{}return _F(t,...e)});Ht(`PID=${process.pid} argv=${JSON.stringify(process.argv.slice(1))} cwd=${process.cwd()} HOME=${process.env.QLOGICAGENT_HOME??"(unset)"} NODE=${process.version}`);var EF=PF(process.argv),mie=!process.argv.includes("--no-acp"),gie=new Ao({verbose:EF.verbose}),Bw=new np({verbose:EF.verbose,transport:gie});mie&&(Bw.initAcpServer(),Ht("ACP server initialized, waiting for messages"));process.on("unhandledRejection",t=>{Ht(`unhandledRejection: ${t instanceof Error?t.stack??t.message:String(t)}`)});process.on("uncaughtException",t=>{Ht(`uncaughtException: ${t.stack??t.message}`)});process.stdin.on("end",()=>{Ht("stdin END received")});process.stdin.on("close",()=>{Ht("stdin CLOSE received")});process.stdout.on("error",t=>{Ht(`stdout ERROR: ${t.message}`)});process.stdout.on("close",()=>{Ht("stdout CLOSE")});process.on("exit",t=>{Ht(`process.exit code=${t}`)});var AF=!1;async function MF(t){if(!AF){AF=!0,Ht(`${t} received`);try{YA(),await Bw.stop()}finally{process.exit(0)}}}process.on("SIGTERM",()=>{MF("SIGTERM")});process.on("SIGINT",()=>{MF("SIGINT")});process.on("SIGHUP",()=>{Ht("SIGHUP received")});Ht("calling server.start()");Bw.start();Ht("server.start() returned, event loop active");
|
package/dist/index.js
CHANGED
|
@@ -1038,7 +1038,7 @@ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;as
|
|
|
1038
1038
|
`)})}function hj(){return wd("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","### Background execution & parallel fan-out","- `agent(background=true)` returns a task id immediately and keeps working \u2014 use it for independent subtasks so you can continue in parallel. Launch several in one message for parallel work.","- `exec(background=true)` does the same for long-running commands (dev servers, builds, watchers).",'- Track background work with the `task` tool: action "output" reads status/output by taskId, action "cancel" stops it; `list` shows active background tasks.',"- Completed background tasks are announced automatically at the start of your next turn \u2014 you do not need to busy-poll.","- For multi-step plans, create checklist tasks first, then fan out unblocked independent steps to background agents and set each checklist task's owner to the returned task id.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify genuinely ambiguous requests before proceeding.","For ordinary creative media requests, infer sensible defaults and use the appropriate media tool directly.","Ask before media generation only when a missing detail is critical to the result or the user is choosing among materially different outputs.","","## Project Rules Management","You can create, edit, and delete project rule files at `.qlogicagent/rules/*.md`.","These files are loaded into your system prompt every turn \u2014 changes take effect immediately.","Use this to help users establish coding conventions, workflow guidelines, or project-specific instructions.","When the user asks to 'add a rule', 'set up conventions', or 'configure instructions', write to `.qlogicagent/rules/<descriptive-name>.md`.","You may also create or edit `.qlogicagent/INSTRUCTIONS.md` for a single top-level instruction file.","","## File Operations \u2014 Use Dedicated Tools","File operations (creating, modifying, or deleting files) should use the dedicated `write` / `edit` / `read` tools, which take structured file-path arguments.","Do NOT use shell redirection (`echo >`, `cat >`, `>>`, `tee`) to create or modify files.","Use `exec` only for real commands (build, test, git, package managers).","This keeps file paths explicit and permission checks accurate.","","### Choosing among the edit tools","- `write` \u2014 create a new file or fully replace one. Overwrites.","- `edit` \u2014 single-file, exact-string replacement for precise surgical edits. Call it repeatedly for multiple edits in one file.","- `patch` / `apply_patch` \u2014 multi-file changes in one shot via the V4A diff format (`*** Begin Patch` \u2026 `*** End Patch`), incl. Add/Update/Delete/Move. Prefer for cross-file refactors.","Do NOT reach for `patch` to change one line in one file \u2014 use `edit`.","","### Searching \u2014 prefer `search` over `exec grep`","Use the `search` tool for finding files/content: it excludes VCS and dependency dirs (`.git`, `node_modules`, `dist`, \u2026) and returns structured matches. `exec grep -r` scans those too, so the two can disagree \u2014 `search` is the consistent, intended path.","","## Deliverable Discipline \u2014 Long Output Goes to Files","The chat window is a conversation surface, not a document dump. Users see deliverables in the workspace file tree and the side panel.","- Long documents/plans/designs/reports/tutorials (anything beyond ~40 lines) MUST be written to a workspace file (e.g. `docs/` or an appropriate project directory) using the file tools. In chat, reply with a 3-5 sentence summary and reference the file \u2014 do NOT paste the full document into the conversation.","- Code longer than ~30 lines belongs in a workspace file; in chat, reference the file path and quote only the key fragment.","- Generated media is already persisted to the workspace `assets/` directory automatically \u2014 do not repeat raw URL lists in your reply."].join(`
|
|
1039
1039
|
`))}function vw(t){return wd("language",()=>t?["# Language","",`Always respond in ${t}.`,`Use ${t} for all text output, explanations, and descriptions.`,"Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
|
|
1040
1040
|
`):["# Language","","Respond in the same language as the user's message.","If the user writes in English, respond in English. If in Chinese, respond in Chinese.","Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
|
|
1041
|
-
`))}var yj={requiresFreshTool:!1,allowedToolNames:[]},cte=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],bw=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${cte.join("|")})\\b`,"i"),lte=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,ute=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,dte=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,pte=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,mte=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,gte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,fte=/https?:\/\/\S+/i,hte=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,yte=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i,vte=/(?:\btts\b|\btext[-\s]?to[-\s]?speech\b|\bread\s+(?:this\s+)?(?:aloud|out)\b|\bgenerate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bcreate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bmake\s+(?:a\s+)?(?:voice\s+message|spoken\s+audio)\b|\u6587\u5b57\u8f6c\u8bed\u97f3|\u8bed\u97f3\u5408\u6210|\u8f6c\u6210\u8bed\u97f3|\u8f6c\u8bed\u97f3|\u751f\u6210.*(?:\u8bed\u97f3|\u97f3\u9891|\u58f0\u97f3|\u5f55\u97f3|\u6709\u58f0)|(?:\u8bfb|\u6717\u8bfb|\u64ad\u62a5|\u914d\u97f3|\u65c1\u767d).*(?:\u4e00\u6bb5|\u8fd9\u6bb5|\u8fd9\u4e9b|\u6587\u5b57|\u5185\u5bb9|\u8bed\u97f3|\u97f3\u9891)?)/i,bte=/(?:\bmusic_generate\b|\bgenerate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bcreate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bmake\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\u751f\u6210.*(?:\u6b4c\u66f2|\u97f3\u4e50|\u65cb\u5f8b|\u914d\u4e50|\u80cc\u666f\u97f3\u4e50|\u7eaf\u97f3\u4e50|\u54fc\u5531)|(?:\u4f5c\u66f2|\u7f16\u66f2|\u5199\u4e00\u9996\u6b4c))/i,kte=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function bj(t){let e=typeof t=="string"?t:xj(t);return e.trim()?bte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:vte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:yte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:fte.test(e)&&hte.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:ute.test(e)&&bw.test(e)||dte.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:lte.test(e)&&bw.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:bw.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:pte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:mte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:gte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:yj:yj}function kj(t){let r=(typeof t=="string"?t:xj(t)).trim();return!r||r.length>24?!1:kte.test(r)}var wte=new Set(["think","task","agent","ask_user"]);function wj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=vj(i);return r.has(s)||wte.has(s)});return n.some(i=>r.has(vj(i)))?n:[...t]}function Sj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return _r("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
|
|
1041
|
+
`))}var yj={requiresFreshTool:!1,allowedToolNames:[]},cte=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],bw=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${cte.join("|")})\\b`,"i"),lte=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,ute=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,dte=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,pte=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,mte=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,gte=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,fte=/https?:\/\/\S+/i,hte=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,yte=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i,vte=/(?:\btts\b|\btext[-\s]?to[-\s]?speech\b|\bread\s+(?:this\s+)?(?:aloud|out)\b|\bgenerate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bcreate\s+(?:a\s+)?(?:spoken\s+)?(?:audio|voice|speech|narration)\b|\bmake\s+(?:a\s+)?(?:voice\s+message|spoken\s+audio)\b|\u6587\u5b57\u8f6c\u8bed\u97f3|\u8bed\u97f3\u5408\u6210|\u8f6c\u6210\u8bed\u97f3|\u8f6c\u8bed\u97f3|\u751f\u6210.*(?:\u8bed\u97f3|\u97f3\u9891|\u58f0\u97f3|\u5f55\u97f3|\u6709\u58f0)|(?:\u8bfb|\u6717\u8bfb|\u64ad\u62a5|\u914d\u97f3|\u65c1\u767d).*(?:\u4e00\u6bb5|\u8fd9\u6bb5|\u8fd9\u4e9b|\u6587\u5b57|\u5185\u5bb9|\u8bed\u97f3|\u97f3\u9891)?)/i,bte=/(?:\bmusic_generate\b|\bgenerate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bcreate\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\bmake\s+(?:a\s+)?(?:song|music|melody|bgm)\b|\u751f\u6210.*(?:\u6b4c\u66f2|\u97f3\u4e50|\u65cb\u5f8b|\u914d\u4e50|\u80cc\u666f\u97f3\u4e50|\u7eaf\u97f3\u4e50|\u54fc\u5531)|(?:\u4f5c\u66f2|\u7f16\u66f2|\u5199\u4e00\u9996\u6b4c))/i,kte=/^(?:hi|hello|hey|ping|test|yo|在吗|在不在|你在吗|你好|您好|早上好|中午好|晚上好|哈喽|嗨|有人吗|能听到吗|你是谁|你还在吗)[?!!?.。~\s]*$/i;function bj(t){let e=typeof t=="string"?t:xj(t);return e.trim()?bte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"music",allowedToolNames:["music_generate"]}:vte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"tts",allowedToolNames:["tts"]}:yte.test(e)?{requiresFreshTool:!0,reason:"media-generation",mediaKind:"image",allowedToolNames:["image_generate"]}:fte.test(e)&&hte.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:ute.test(e)&&bw.test(e)||dte.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:lte.test(e)&&bw.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:bw.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:pte.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:mte.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:gte.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:yj:yj}function kj(t){let r=(typeof t=="string"?t:xj(t)).trim();return!r||r.length>24?!1:kte.test(r)}var wte=new Set(["think","task","agent","ask_user","team","send_message"]);function wj(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(i=>{let s=vj(i);return r.has(s)||wte.has(s)});return n.some(i=>r.has(vj(i)))?n:[...t]}function Sj(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");if(t.reason==="file-mutation")return _r("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
|
|
1042
1042
|
`));if(t.reason==="memory-mutation")return _r("fresh_workspace_evidence",()=>["# Memory File Action Required","","The latest user request explicitly asks to use the memory tool for a memory file action.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use the requested memory action and target filename instead of workspace file write/edit tools.","For removal requests, call memory with action='remove' and set old_text to the exact INDEX.md line or labeled marker line the user asked to remove.","Do not call action='add', action='remember', or action='create_file' for a removal request.","Do not merely describe the memory content or create a regular workspace file."].join(`
|
|
1043
1043
|
`));if(t.reason==="media-generation"){let r=t.mediaKind==="tts"?"spoken audio / text-to-speech":t.mediaKind==="music"?"music or song":"image",n=t.mediaKind==="tts"?"Do not answer by saying you cannot generate audio when the TTS tool is available, and do not invent a placeholder audio URL.":t.mediaKind==="music"?"Do not answer by describing music in text or inventing a placeholder audio URL.":"Do not answer by inventing a Markdown image URL or placeholder attachment path.",o=t.mediaKind==="tts"?"Use TTS for spoken-word output, narration, reading text aloud, or voice messages. STT is only for transcribing incoming speech.":t.mediaKind==="music"?"Use music generation for songs, melodies, BGM, or sung/musical output; use TTS only for spoken words.":"Use image generation for pictures, illustrations, posters, avatars, or visual output.";return _r("fresh_workspace_evidence",()=>["# Media Generation Required","",`The latest user request asks you to create ${r}.`,`Before answering, call the appropriate media tool for this turn: ${e}.`,n,o,"For ordinary creative requests, infer reasonable defaults for purpose, style, and size instead of asking follow-up questions.","Ask the user only when a missing detail is critical to the result or the request is genuinely ambiguous."].join(`
|
|
1044
1044
|
`))}return _r("fresh_workspace_evidence",()=>["# Fresh Workspace Evidence","","The latest user request asks for current workspace, shell, or URL state.",`Before answering, call one of these tools for this turn: ${e}.`,"Do not answer this request from conversation history, memory, or prior tool results.","For an explicit filename, inspect that exact file first and report the observed value.","If the filename is not found at the given path, use search to locate it, then read the located file before answering.","A filename search alone is not enough to answer content or code-symbol questions."].join(`
|
|
@@ -1189,12 +1189,12 @@ ${s.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
|
|
|
1189
1189
|
`)}],details:{type:"team",action:"create",teamName:n.team.name}}}case"delete":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let n=await t.deleteTeam(r.teamName);return n.success?{content:[{type:"text",text:`Team "${r.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:r.teamName}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}}}case"list":{let n=await t.listTeams();if(!n.teams||n.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let o=[`Active teams (${n.teams.length}):`,""];for(let i of n.teams)o.push(`- **${i.name}**: ${i.description||"(no description)"} \u2014 ${i.members.length} members`);return{content:[{type:"text",text:o.join(`
|
|
1190
1190
|
`)}],details:{type:"team",action:"list",count:n.teams.length}}}case"status":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let n=await t.getTeamStatus(r.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=n.team,i=n.memberProgress??{},s=[`Team: ${o.name}`,`Description: ${o.description||"\u2014"}`,`Lead: ${o.leadId}`,`Created: ${o.createdAt}`,"",`Members (${o.members.length}):`];for(let a of o.members){let c=a.tools?` [tools: ${a.tools.join(", ")}]`:"",u=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",d=i[a.name],p=a.isActive===!1?" (idle)":" (active)";if(d){let m=[];if(d.runningFor&&m.push(`running ${Math.round(d.runningFor/1e3)}s`),d.lastToolCall&&m.push(`tool: ${d.lastToolCall}`),d.idleFor!==void 0&&d.idleFor>5&&m.push(`idle ${d.idleFor}s`),d.mediaProgress){let g=d.mediaProgress;m.push(`${g.mediaType} ${g.percent}% [${g.status}] taskId=${g.taskId}${g.provider?` provider=${g.provider}`:""}`)}m.length&&(p=` (${m.join(", ")})`)}s.push(` - ${a.name} (${a.role})${c}${u}${p}`)}return{content:[{type:"text",text:s.join(`
|
|
1191
1191
|
`)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}import*as kU from"node:path";ve();function Tne(t){if(t&&typeof t=="object"&&"content"in t){let e=t.content;if(typeof e=="string")return e}return""}function Pne(t,e){return`[message from ${e}]
|
|
1192
|
-
${t}`}function wU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Vt({onNotification:(s,a,c)=>{t.sendNotification("team.member.notification",{memberId:s,method:a,params:c})},onStateChange:(s,a)=>{t.sendNotification("team.member.state",{memberId:s,state:a});let c=i.getHandle(s),d=i.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,a,{missedBeats:i.getMissedBeats(s),lastActivityAt:c?.lastActivityAt,usage:d&&d.totalTokens>0?{inputTokens:d.inputTokens,outputTokens:d.outputTokens,totalTokens:d.totalTokens}:void 0})},onExit:(s,a,c)=>{for(let u of n.values()){let d=u.members.find(p=>p.cwd&&Ta(u.name,p.name)===s);d&&(d.isActive=!1)}r.unregister(s),e.info(`[team] member ${s} exited (code=${a}, signal=${c})`)},onMcpToolCall:(s,a,c)=>t.handleMcpToolCall(s,a,c),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:kU.join(H().getUserAgentHome(),"agent-logs")});return{async createTeam(s){if(n.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let a=await ta(),c=[];for(let m of s.members??[]){let g={...m,isActive:!0};if(a){let f=`team-${s.teamName}-${m.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),h=await lE(a,f,o);h?(g.worktreePath=h.worktreePath,g.worktreeBranch=h.branch,g.cwd=h.worktreePath,e.info(`[team] provisioned worktree for ${m.name}: ${h.worktreePath}`)):(g.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${m.name}, using shared cwd`))}else g.cwd=process.cwd();c.push(g)}let u={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:c,createdAt:new Date().toISOString()};n.set(s.teamName,u);let d=[];for(let m of c){if(!m.cwd)continue;let g=Ta(s.teamName,m.name);try{await i.spawn({memberId:g,name:m.name,cwd:m.cwd,prompt:`You are the "${m.name}" team member. Role: ${m.role}.`,agentType:m.role,verbose:t.verbose}),r.register({memberId:g,name:m.name,teamName:s.teamName,role:m.role,deliver:async(
|
|
1192
|
+
${t}`}function wU(t,e,r){let n=new Map,o={info:s=>e.info(s),warn:s=>e.warn(s)},i=new Vt({onNotification:(s,a,c)=>{t.sendNotification("team.member.notification",{memberId:s,method:a,params:c})},onStateChange:(s,a)=>{t.sendNotification("team.member.state",{memberId:s,state:a});let c=i.getHandle(s),d=i.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,a,{missedBeats:i.getMissedBeats(s),lastActivityAt:c?.lastActivityAt,usage:d&&d.totalTokens>0?{inputTokens:d.inputTokens,outputTokens:d.outputTokens,totalTokens:d.totalTokens}:void 0})},onExit:(s,a,c)=>{for(let u of n.values()){let d=u.members.find(p=>p.cwd&&Ta(u.name,p.name)===s);d&&(d.isActive=!1)}r.unregister(s),e.info(`[team] member ${s} exited (code=${a}, signal=${c})`)},onMcpToolCall:(s,a,c)=>t.handleMcpToolCall(s,a,c),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:kU.join(H().getUserAgentHome(),"agent-logs")});return{async createTeam(s){if(n.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let a=await ta(),c=[];for(let m of s.members??[]){let g={...m,isActive:!0};if(a){let f=`team-${s.teamName}-${m.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),h=await lE(a,f,o);h?(g.worktreePath=h.worktreePath,g.worktreeBranch=h.branch,g.cwd=h.worktreePath,e.info(`[team] provisioned worktree for ${m.name}: ${h.worktreePath}`)):(g.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${m.name}, using shared cwd`))}else g.cwd=process.cwd();c.push(g)}let u={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:c,createdAt:new Date().toISOString()};n.set(s.teamName,u);let d=[];for(let m of c){if(!m.cwd)continue;let g=Ta(s.teamName,m.name);try{let f=t.getLlmConfig();await i.spawn({memberId:g,name:m.name,cwd:m.cwd,prompt:`You are the "${m.name}" team member. Role: ${m.role}.`,agentType:m.role,verbose:t.verbose,...f?{model:f.model,apiKey:f.apiKey,baseUrl:f.baseUrl}:{}}),r.register({memberId:g,name:m.name,teamName:s.teamName,role:m.role,deliver:async(h,y)=>Tne(await i.sendTask(g,Pne(h,y))),isAlive:()=>i.isAlive(g)}),e.info(`[team] spawned child process for ${m.name} in ${m.cwd}`)}catch(f){let h=f instanceof Error?f.message:String(f);e.warn(`[team] failed to spawn child process for ${m.name}: ${h}`),m.isActive=!1,d.push({name:m.name,error:h})}}let p=c.filter(m=>m.cwd).length;return p>0&&d.length===p?(n.delete(s.teamName),{success:!1,error:`All ${p} team member(s) failed to spawn: `+d.map(m=>`${m.name} (${m.error})`).join("; ")}):(t.sendNotification("team.updated",{teamName:s.teamName,action:"created",members:u.members.map(m=>({agentName:m.name,role:m.role,worktreePath:m.worktreePath,pid:i.getHandle(Ta(s.teamName,m.name))?.pid}))}),d.length>0?{success:!0,team:u,partialFailures:d}:{success:!0,team:u})},async deleteTeam(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};for(let u of a.members){let d=Ta(s,u.name);r.unregister(d),i.kill(d),i.remove(d)}let c=await ta();if(c)for(let u of a.members)u.worktreePath&&u.worktreeBranch&&(await uE(c,u.worktreePath,u.worktreeBranch,o),e.info(`[team] cleaned up worktree for ${u.name}: ${u.worktreePath}`));return n.delete(s),t.sendNotification("team.updated",{teamName:s,action:"destroyed",members:[]}),{success:!0}},async listTeams(){return{success:!0,teams:[...n.values()]}},async getTeamStatus(s){let a=n.get(s);if(!a)return{success:!1,error:`Team "${s}" not found.`};let c={};for(let u of a.members){let d=Ta(s,u.name),p=i.getStatus(d);p&&(u.isActive=p.alive,c[u.name]={mediaProgress:p.mediaProgress,lastToolCall:p.lastToolCall,idleFor:p.idleFor,runningFor:p.runningFor})}return{success:!0,team:a,memberProgress:c}},dispose(){i.dispose()}}}function Ta(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function SU({host:t,log:e,toolCatalog:r,teamRegistry:n}){let o=wU(t,e,n);Ur(async()=>o.dispose()),r.addTool(bU(o))}var Ane="send_message",Ine={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function xU(t){return{name:Ane,label:"Send Message",isEgress:!0,egressCarriesData:!0,description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:Ine,execute:async(e,r)=>{if(!r.to||r.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!r.message||r.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(r.to!=="*"&&t.listTeammates){let s=t.listTeammates();if(!s.includes(r.to))return{content:[{type:"text",text:`Error: agent "${r.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let n=await t.sendMessage({to:r.to.trim(),message:r.message.trim(),summary:r.summary,senderId:t.getSenderId()});if(!n.success)return{content:[{type:"text",text:`Message delivery failed: ${n.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:n.error}};let o=r.to==="*"?`broadcast (${n.recipients?.length||0} recipients)`:r.to,i=n.replies?.length?`
|
|
1193
1193
|
|
|
1194
1194
|
`+n.replies.map(s=>`${s.name} replied:
|
|
1195
1195
|
${s.reply}`).join(`
|
|
1196
1196
|
|
|
1197
|
-
`):"";return{content:[{type:"text",text:`Message sent to ${o}.${i}`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients,replies:n.replies}}}}}function RU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(xU({sendMessage:async o=>{e.info(`[send_message] ${o.senderId} -> ${o.to}: ${o.message}`);let i=await n.deliver(o.to,o.message,o.senderId);return i.ok?{success:!0,recipients:i.replies?.map(s=>s.name)??[],replies:i.replies}:{success:!1,error:i.error}},getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>n.list().filter(o=>o.alive).map(o=>o.name)}))}function TU(t){let e=new Bd;QL({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host),getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext()},hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),cU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),gU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),vU({log:t.log,toolCatalog:t.toolCatalog}),oU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),SU({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log,toolCatalog:t.toolCatalog,teamRegistry:e}),RU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Cne={id:"cli-core-tools",kind:"core",register:_ne};function PU(t){Cne.register(t)}function _ne(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext(),sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,i){t.host.emitAgentStatus(n,o,i)},handleMcpToolCall(n,o,i){return t.host.handleMcpToolCall(n,o,i)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker};TU(r)}var Ene={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
1197
|
+
`):"";return{content:[{type:"text",text:`Message sent to ${o}.${i}`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients,replies:n.replies}}}}}function RU({host:t,log:e,toolCatalog:r,teamRegistry:n}){r.addTool(xU({sendMessage:async o=>{e.info(`[send_message] ${o.senderId} -> ${o.to}: ${o.message}`);let i=await n.deliver(o.to,o.message,o.senderId);return i.ok?{success:!0,recipients:i.replies?.map(s=>s.name)??[],replies:i.replies}:{success:!1,error:i.error}},getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>n.list().filter(o=>o.alive).map(o=>o.name)}))}function TU(t){let e=new Bd;QL({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host),getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext()},hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),cU({toolCatalog:t.toolCatalog,host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),gU({toolCatalog:t.toolCatalog,host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),vU({log:t.log,toolCatalog:t.toolCatalog}),oU({config:t.config,toolCatalog:t.toolCatalog,host:{currentSessionId:t.host.currentSessionId}}),SU({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},getLlmConfig:()=>t.host.getLlmConfig(),sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log,toolCatalog:t.toolCatalog,teamRegistry:e}),RU({toolCatalog:t.toolCatalog,host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log,teamRegistry:e})}var Cne={id:"cli-core-tools",kind:"core",register:_ne};function PU(t){Cne.register(t)}function _ne(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentBaseUrl(){return t.host.getCurrentBaseUrl()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},getBackgroundTasks:()=>t.host.getBackgroundTasks(),getConversationHistory:()=>t.host.getConversationHistory(),isGroupContext:()=>t.host.isGroupContext(),getLlmConfig:()=>{let n=t.host.getCurrentModel(),o=t.host.getCurrentApiKey();return!n||!o?null:{model:n,apiKey:o,baseUrl:t.host.getCurrentBaseUrl()||void 0}},sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,i){t.host.emitAgentStatus(n,o,i)},handleMcpToolCall(n,o,i){return t.host.handleMcpToolCall(n,o,i)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker};TU(r)}var Ene={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
1198
1198
|
- goToDefinition: jump to symbol definition
|
|
1199
1199
|
- findReferences: find all usages of a symbol
|
|
1200
1200
|
- hover: get type/docs for symbol at position
|
|
@@ -1251,5 +1251,5 @@ CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled
|
|
|
1251
1251
|
Available skills:
|
|
1252
1252
|
${n}`}ve();import{randomUUID as qoe}from"node:crypto";var Loe=10080*60*1e3;function Uoe(t){return{async record(e){if(!t)return"disabled";try{let r=await t.getConsent();return!r.enabled||!r.signalsEnabled?"disabled":(await t.recordSignal(e),"recorded")}catch{return"failed"}},async recordSkillUsage(e,r){let n=Lw(e);return n?this.record({resourceId:n,event:r,attribution:"skill-subturn",metadata:{skillName:e?.name,version:e?.registryVersion,effectiveRiskTier:e?.registryEffectiveRiskTier}}):"skipped"},async recordSkillLifecycle(e,r){let n=Lw(e);return n?this.record({resourceId:n,event:r,attribution:"skill-lifecycle",metadata:{skillName:e?.name,version:e?.registryVersion}}):"skipped"},async recordKeptSignals(e,r={}){let n=r.now??new Date,o=r.retentionMs??Loe,i=[];for(let s of Object.values(e.records)){if(!Foe(s,n,o))continue;let a=await this.recordSkillLifecycle(s,"kept");a==="recorded"&&(s.registryKeptSignalAt=n.toISOString()),i.push({skillName:s.name,status:a})}return i}}}function oF(){let t=Sr();return t?Uoe(t):null}function Lw(t){return t?.source!=="installed"||t.registrySourceTier==="official"?null:t.registryResourceId??t.name}function Foe(t,e,r){if(!Lw(t)||t.registryKeptSignalAt)return!1;let n=Date.parse(t.lastUsedAt??t.createdAt);return Number.isFinite(n)?e.getTime()-n>=r:!1}import{spawn as mMe}from"node:child_process";function iF(t={}){let e=t.platform??process.platform;if(e!=="win32")return{level:"L0",available:!1,backend:"unsupported-platform",platform:e,reason:"unsupported-platform"};let r=t.processTreeLauncherAvailable===!0||t.jobObjectAvailable===!0;return{level:"L0",available:r,backend:r?"windows-process-tree-launcher":"unavailable",platform:e,reason:r?void 0:"windows-l0-not-provisioned"}}function sF(){return{envelope:"l0-launcher-audit-v1",backend:"windows-process-tree-launcher",defaultHostAccess:!0,noFsNetworkRestriction:!0,processTree:{killOnClose:!0,trackChildren:!0},jobObject:{implemented:!1,ready:!0}}}function Hoe(t={}){let e=t.availability??iF({platform:t.platform,appContainerAvailable:t.appContainerAvailable,jobObjectAvailable:t.jobObjectAvailable,processTreeLauncherAvailable:t.processTreeLauncherAvailable});return{getAvailability(){return e},decide(r){if(r.origin==="first-party"||r.origin==="official"||r.official===!0)return{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"first-party-action",backend:"first-party",l0:e};if(r.origin==="community"&&r.executable===!0){let o=e.available?"launcher-required":"launcher-unavailable";return{allowed:e.available,spawnAllowed:e.available,launcherRequired:!0,reason:o,backend:"community-l0-launcher",l0:e,launcher:Boe(r,e.available?"allowed":"blocked",o)}}let n=r.riskTier??"unknown";return!zoe(n)||!r.executable?{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"community-low-risk",backend:"community-l1-l2",l0:e}:r.autoRun===!1?{allowed:!0,spawnAllowed:!0,launcherRequired:!1,reason:"manual-run",backend:"community-l1-l2",l0:e}:{allowed:e.available,spawnAllowed:e.available,launcherRequired:!0,reason:e.available?"l0-available":"l0-unavailable",backend:"community-l0",l0:e}}}}function aF(){return Hoe()}function zoe(t){return t==="R2"||t==="R3"}function Boe(t,e,r){return{level:"L0",mode:"os-native-launcher",defaultHostAccess:!0,noFsNetworkRestriction:!0,audit:{envelope:"l0-launcher-audit-v1",subject:{origin:t.origin,official:t.official===!0,executable:t.executable===!0,autoRun:t.autoRun===!0},decision:e,reason:r},windows:sF()}}async function uF(t){let{host:e,toolCatalog:r,skillName:n,skillContent:o,userArgs:i,signal:s}=t,a=`skill_${n}_${qoe().slice(0,8)}`,c=e.getAgent();if(!c)return"[skill] Cannot execute: no LLM provider configured";let u=H().getOwnerProfileDir(),d=e.getCurrentSessionId()||"skill",p=Ae(u).records[n],m=t.communitySignalReporter??oF(),g=(t.skillSandbox??aF()).decide({origin:pF(p)?"community":"first-party",riskTier:p?.registryEffectiveRiskTier??p?.registryRiskTier??"unknown",executable:!0,autoRun:!0});if(!g.allowed)return await m?.recordSkillUsage(p,"fail"),`[skill "${n}"] blocked: community ${g.reason} (${g.l0.reason??g.l0.backend})`;let f=dF(n,p);e.getCurrentHooks()?.invoke("subagent.started",{sessionId:d,turnId:a,subagentId:a,agentType:f}).catch(()=>{});let h=new Set(["skill","agent"]),y=r.getToolManifest().filter(b=>!h.has(b.function.name)),S=i??`Execute skill "${n}" instructions.`,w=[],v;for await(let b of c.run({turnId:a,sessionId:d,messages:[{role:"user",content:S}],tools:y,systemPrompt:o,config:{parentDepth:1,maxRounds:5}},s)){if(b.type==="end"&&b.content)return cF(e,d,a,f,"normal"),lF(u,n,!0),await m?.recordSkillUsage(p,"success"),b.content;if(b.type==="delta"&&b.text&&w.push(b.text),b.type==="error"){v=b.error;break}}return cF(e,d,a,f,v?"error":"normal",v),v?(iw(u,n,!1),await m?.recordSkillUsage(p,"error"),`[skill "${n}"] error: ${v}`):(lF(u,n,!0),await m?.recordSkillUsage(p,"success"),w.join("")||`[skill "${n}"] completed (no output)`)}function dF(t,e){return Woe(e)?`community-skill:${t}`:`skill:${t}`}function Woe(t){return pF(t)}function pF(t){return t?.source!=="installed"?!1:t.registrySourceTier!=="official"}function cF(t,e,r,n,o,i){t.getCurrentHooks()?.invoke("subagent.stopped",{sessionId:e,turnId:r,subagentId:r,agentType:n,reason:o,error:i}).catch(()=>{})}function lF(t,e,r){iw(t,e,r);let n=Ae(t);oC(n,e),Ue(t,n)}var Goe={id:"skill-meta-tool",kind:"skill",register:({host:t,...e})=>Koe(t,e)};function mF(t,e){Goe.register({...e,host:t})}function Koe(t,e){let r=e.pathService;e.toolCatalog.addTool(nF({listSkills:()=>{let n=JI(t.getActiveProjectRoot()).map(o=>({name:o.name,description:o.description,source:o.enabledScope,filePath:o.filePath,baseDir:o.baseDir}));return n.push(...t.getPluginSkills()),n},listSkillsFull:async n=>{let o=[],i=new Set;for(let s of io(t.getActiveProjectRoot())){let a=s.enabledScope;n&&a!==n||(i.add(a),o.push({name:s.name,description:s.description??`Skill (${a})`,category:a,scope:s.enabledScope,version:s.version}))}for(let s of t.getPluginSkills())n&&s.source!==n||(i.add(s.source??"plugin"),o.push({name:s.name,description:`Plugin skill (${s.source})`,category:s.source,scope:"plugin"}));return{skills:o,categories:[...i]}},readSkillContent:async n=>{let o=so(n);if(!o)return null;try{return await tr.promises.readFile(o.filePath,"utf8")}catch{return null}},viewSkill:async(n,o)=>{let i=so(n);if(!i)return null;let s=o?Ai.join(i.baseDir,o):i.filePath;try{let a=await tr.promises.readFile(s,"utf8");return{name:n,content:a}}catch{return null}},executeSkillSubturn:async(n,o,i,s)=>uF({host:t,toolCatalog:e.toolCatalog,skillName:n,skillContent:o,userArgs:i,signal:s}),manageSkill:async n=>{let o=t.getActiveProjectRoot(),i=r.getUserSkillsDir(),s=Ai.join(i,n.name),a=Ai.join(s,"SKILL.md"),c=r.getOwnerProfileDir();switch(n.action){case"create":{let u=n.content??"",p=rb(u,n.name,`Skill: ${n.name}`)??u,m=ql(p,n.name);if(!m.valid)return{success:!1,message:`Skill validation failed: ${m.errors.join("; ")}`};let g=Ae(c);if(g.records[n.name]?.pinned&&tr.existsSync(a))return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};await tr.promises.mkdir(s,{recursive:!0}),await tr.promises.writeFile(a,p,"utf8"),t.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:p,scope:"project"}}),dt(),Ot(g,n.name,"created"),Ue(c,g),Un(n.name),o&&Lr(o,n.name);let f=t.getMemoryLearningSink(),h=t.getMemoryUserId();if(f&&h){let S=p.split(`
|
|
1253
1253
|
`).slice(0,3).join(" ").slice(0,200),w=o?Ai.basename(o):"unknown";f.ingestExtracted([{text:`Learned skill "${n.name}" in project "${w}": ${S}`,category:"skill-learning"}],h).catch(()=>{})}let y=o?` (project-scoped). To make it available across all projects, use: skill promote name:"${n.name}"`:"";return{success:!0,message:`Skill "${n.name}" created${y}`,path:s}}case"edit":{let u=Ae(c);if(u.records[n.name]?.pinned)return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};let d=n.content??"",m=rb(d,n.name)??d;return await tr.promises.writeFile(a,m,"utf8"),Qv(u,n.name),Ue(c,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:m,scope:"project"}}),{success:!0,message:`Skill "${n.name}" updated`,path:a}}case"patch":{let u=Ae(c);if(u.records[n.name]?.pinned)return{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`};let d=await tr.promises.readFile(a,"utf8");if(!n.oldString||!d.includes(n.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let p=d.replace(n.oldString,n.newString??"");return await tr.promises.writeFile(a,p,"utf8"),Qv(u,n.name),Ue(c,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",content:p,scope:"project"}}),{success:!0,message:`Skill "${n.name}" patched`,path:a}}case"delete":{let u=Ae(c);return u.records[n.name]?.pinned?{success:!1,message:`Skill "${n.name}" is pinned. Unpin it first.`}:(await tr.promises.rm(s,{recursive:!0,force:!0}),Fl(u,n.name),Ue(c,u),Oo(n.name),o&&Ln(o,n.name),t.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:n.name,category:n.category??"learned",action:"delete",scope:"project"}}),dt(),{success:!0,message:`Skill "${n.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${n.action}`}}},promoteSkill:async n=>{let o=so(n);if(!o)return{success:!1,message:`Skill "${n}" not found in skill store. Cannot promote.`};let i=r.getOwnerProfileDir(),s=Ae(i),a=Ot(s,n);a.source="promoted",Ue(i,s),Oo(n);let c=t.getActiveProjectRoot();c&&Ln(c,n);let u="";try{u=await tr.promises.readFile(o.filePath,"utf8")}catch{}return t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:n,category:"promoted",content:u,scope:"global"}}),dt(),{success:!0,message:`Skill "${n}" promoted to global. It is now available across all projects.`,path:o.baseDir}}}))}function gF(t){let e=YU({log:t.log,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,projectRoot:t.projectRoot,memdir:t.memdir,toolCatalog:t.toolCatalog,currentUserId:t.currentUserId,prefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,compressionClient:{transport:t.agentClient.transport,apiKey:t.agentClient.apiKey},sendNotification:(o,i)=>t.sendNotification(o,i)}),r=e.hooks;FU({config:t.config,projectRoot:t.projectRoot,pathService:t.pathService,log:t.log,toolCatalog:t.toolCatalog,currentManager:t.currentMcpManager,setManager:t.setMcpManager,setReady:t.setMcpReady}),GU({config:t.config,hooks:r,log:t.log,pathService:t.pathService,toolCatalog:t.toolCatalog,setPluginLoader:t.setPluginLoader});let n=ZU({config:t.config,toolCatalog:t.toolCatalog,hooks:r,log:t.log,sessionId:t.sessionId,getTurnId:t.getTurnId,getActiveProjectRoot:()=>t.projectRoot,getActiveWorkdir:()=>t.pathService.getActiveWorkdir(),getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentUnregister:t.currentPermissionUnregister});return mF({getActiveProjectRoot:()=>t.projectRoot,getPluginSkills:t.getPluginSkills,getAgent:t.getAgent,getCurrentSessionId:()=>t.sessionId,getCurrentHooks:()=>r,sendNotification:t.sendNotification,getMemoryLearningSink:()=>e.memoryLearningSink,getMemoryUserId:()=>e.memoryUserId},{config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),PU({config:t.config,host:t.coreToolHost,hooks:r,log:t.log,toolCatalog:t.toolCatalog,toolInvoker:t.toolInvoker}),$U({config:t.config,pathService:t.pathService,toolCatalog:t.toolCatalog}),t.sessionId&&r.invoke("session.created",{sessionId:t.sessionId}).catch(()=>{}),rF({config:t.config,hooks:r,ruleEngine:n.ruleEngine,sessionId:t.sessionId,currentFileWatcher:t.currentFileWatcher,log:t.log,setFileWatcher:t.setFileWatcher}),{hooks:r,memoryHandlerProvider:e.memoryHandlerProvider,memoryDreamProvider:e.memoryDreamProvider,memoryUserId:e.memoryUserId,permissionChecker:n.permissionChecker,permissionUnregister:n.permissionUnregister,ruleEngine:n.ruleEngine}}function fF(t){let{provider:e,model:r,apiKey:n,baseUrl:o}=t.resolvedConfig,i=fu({provider:e,model:r,apiKey:n,baseUrl:o},t.providerRegistry);return i.transport=cM(i.transport,t.sessionId||"default"),{transport:i.transport,apiKey:n,model:r,provider:e,baseUrl:o??""}}function hF(t){return{agent:new Dn({llmTransport:t.client.transport,apiKey:t.client.apiKey,toolInvoker:t.toolInvoker,log:t.log,hooks:t.hooks,maxRounds:t.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot,runtimePorts:pc()}),...t.client}}import{randomUUID as Voe}from"node:crypto";async function yF(t){let e=[],r=t.result.content.map(d=>{if(d.type==="image"&&d.data){let p=d.mimeType||"image/png";return e.push(`data:${p};base64,${d.data}`),"[Image]"}return d.text??""}).join(`
|
|
1254
|
-
`),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,i=o?r:void 0,s=t.result.details?.type,a=t.result.details?{...t.result.details}:void 0,c=s?.split("_")[0];if(s==="three_d_generate"&&(c="3d"),c&&["image","tts","video","music","3d"].includes(c)){let d=t.result.details?.mediaUrls??[];if(d.length>0)try{let p=await t.mediaPersistence.downloadAll(d,{type:c,sessionId:t.sessionId||void 0},{warn:m=>t.log(m)});if(p.length>0){let m=new Map(p.map(g=>[g.remoteUrl,zL(g.localPath)]));for(let g of p)r=r.replaceAll(g.remoteUrl,g.localPath);d=d.map(g=>m.get(g)??g),t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:p.map(g=>({remoteUrl:g.remoteUrl,localPath:g.localPath,bytes:g.bytes,mimeType:g.mimeType}))})}}catch{}a&&(a.mediaUrls=d)}if(s==="task"&&!o&&t.result.details?.taskList)try{let d=t.result.details;d?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:d.taskList,summary:{total:d.total??d.taskList.length,completed:d.completed??0,inProgress:d.inProgress??0,notStarted:d.notStarted??0}})}catch{}let u=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:i,toolReferences:u,imageUrls:n,details:a}}function vF(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let i=t.toolCatalog.findTool(r);if(!i)return{result:"",error:`Unknown tool: ${r}`};if(typeof i.execute!="function")return{result:"",error:`Tool is not executable: ${r}`};let s=i.execute,a=`tc_${Voe().slice(0,8)}`;try{let c=JSON.parse(n),u=t.getSessionId(),d;try{d=t.mediaPersistence.getMediaDir()}catch{d=void 0}let p=await RM(d,()=>s(a,c,o));return await yF({turnId:e,sessionId:u,result:p,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(m,g)=>t.sendNotification(m,g)})}catch(c){return{result:"",error:c instanceof Error?c.message:String(c)}}}}}function bF(t){let e={info:s=>t.log(s),warn:s=>t.log(`[warn] ${s}`),error:s=>t.log(`[error] ${s}`),debug:s=>{t.verbose&&t.log(`[debug] ${s}`)}},r=vF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=fF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=gF({config:t.config,log:e,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,getTurnId:t.getTurnId,projectRoot:t.projectRoot,pathService:t.pathService,memdir:t.memdir,currentUserId:t.currentUserId,memoryPrefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,agentClient:n,toolCatalog:t.toolCatalog,currentMcpManager:t.runtimeSession.mcpManager,setMcpManager:t.setMcpManager,setMcpReady:t.setMcpReady,setPluginLoader:t.setPluginLoader,getPluginSkills:()=>t.runtimeSession.getPluginSkills(),getAgent:t.getAgent,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentPermissionUnregister:t.runtimeSession.permissionUnregister,coreToolHost:t.coreToolHost,toolInvoker:r,currentFileWatcher:t.runtimeSession.fileWatcher,setFileWatcher:t.setFileWatcher});return t.runtimeSession.applyBootstrap(o),{agent:hF({client:n,toolInvoker:r,log:e,hooks:o.hooks,maxRounds:t.config.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}).agent,agentClient:n,toolInvoker:r,hooks:o.hooks}}var Joe=Zoe(import.meta.url);function Xoe(){for(let t of["../package.json","../../package.json"])try{return Joe(t).version}catch{}return"0.0.0"}var kF=Xoe();var Yoe=new Set(["thread.user_response"]);var Fw=class{running=!1;startedAt=Date.now();packageVersion=kF;rpcContract=new Ki;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Dd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ga;backgroundTasks=new Ka(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=rr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Md();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new jd;idleDreamCoordinator;petConfirmCoordinator;modelRegistryHydration=null;get registry(){return this.runtimeServices.providerRegistry}get mediaClient(){return this.runtimeServices.mediaClient}get mediaPersistence(){return this.runtimeServices.mediaPersistence}get pathService(){return this.runtimeServices.pathService}get toolCatalog(){return this.runtimeServices.toolCatalog}get petRuntime(){return this.runtimeServices.petRuntime}get currentHooks(){return this.runtimeSession.currentHooks}get permissionChecker(){return this.runtimeSession.permissionChecker}set permissionChecker(e){this.runtimeSession.permissionChecker=e}set mcpManager(e){this.runtimeSession.mcpManager=e}get memoryProvider(){return this.runtimeSession.memoryProvider}set memoryProvider(e){this.runtimeSession.memoryProvider=e}get memoryDreamProvider(){return this.runtimeSession.memoryDreamProvider}set memoryDreamProvider(e){this.runtimeSession.memoryDreamProvider=e}get memoryUserId(){return this.runtimeSession.memoryUserId}set memoryUserId(e){this.runtimeSession.memoryUserId=e}constructor(e){this.verbose=e.verbose,this.runtimeServices=GL({verbose:e.verbose,getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Ud({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=_L({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Ld({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),resolveMemoryRoot:()=>Uw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Wt(20,this.getActiveProjectRoot()),runDream:r=>Uo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ui({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),this.backgroundTasks.onTaskSettled(r=>{this.pendingTaskNotifications.push(rx(r,r.output??r.error??""))})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}drainPendingTaskNotifications(){if(this.pendingTaskNotifications.length===0)return[];let e=this.pendingTaskNotifications;return this.pendingTaskNotifications=[],e}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=W();e.load(),await Hn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){this.configureTurnMedia(void 0,this.currentTurnId||"tools-list")}configureTurnMedia(e,r){let n=this;this.runtimeServices.configureTurnMedia({host:{get currentMediaApiKeys(){return n.currentMediaApiKeys},set currentMediaApiKeys(o){n.currentMediaApiKeys=o},get sessionState(){return n.sessionState},sendNotification:(o,i)=>this.sendNotification(o,i)},config:e,turnId:r})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(eg(e)||Zi(e)){this.acpServer.dispatchMessage(e);return}if(Vi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Ym(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{await Cx(),this.runtimeSession.stopFileWatcher(),await this.runtimeSession.disconnectMcp(),this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=Dj(this);handleMessage(e){if(e.id!==void 0&&!Yoe.has(e.method)){let n=sc(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);if(r){let n=o=>{e.id!==void 0&&this.rpcIds.has(e.id)&&this.sendResponse(e.id,void 0,{code:k.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})};try{Promise.resolve(r(e)).catch(n)}catch(o){n(o)}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:k.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=jL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return ML({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=this.runtimeServices.ensureMemoryProvider(this.memoryUserId);this.runtimeSession.memoryProvider=e.handlerProvider,this.runtimeSession.memoryDreamProvider=e.dreamProvider,this.runtimeSession.memoryUserId=e.userId}resolveAgent(e){let r=EL(e,u=>this.log(u));if(!r)return null;let{provider:n,model:o,apiKey:i,baseUrl:s,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s),this.agent;e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s);let c=bF({config:e,taskStore:this.taskStore,backgroundTasks:this.backgroundTasks,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),pathService:this.pathService,memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),resolvedTextConfig:r,verbose:this.verbose,providerRegistry:this.registry,mediaPersistence:this.mediaPersistence,toolCatalog:this.toolCatalog,runtimeSession:this.runtimeSession,setMcpManager:u=>{this.runtimeSession.mcpManager=u},setMcpReady:u=>{this.runtimeSession.mcpReady=u},setPluginLoader:u=>{this.runtimeSession.pluginLoader=u},getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)?{sessionId:this.currentSessionId,requestPermission:u=>this.acpServer.requestPermission(u)}:void 0,sendNotification:(u,d)=>this.sendNotification(u,d),isPetActive:()=>this.petRuntime.isActive(),coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,getBackgroundTasks:()=>this.backgroundTasks,getConversationHistory:()=>this.currentSessionId?this.sessionHistory.getResumedHistory(this.currentSessionId):null,isGroupContext:()=>Qa(),sendNotification:(u,d)=>this.sendNotification(u,d),emitAgentStatus:(u,d,p)=>this.emitAgentStatus(u,d,p),handleMcpToolCall:(u,d,p)=>this.handleMcpToolCall(u,d,p)},setFileWatcher:u=>{this.runtimeSession.fileWatcher=u},log:u=>this.log(u)});return this.agent=c.agent,this.lastLlmConfigKey=a,this.currentTransport=c.agentClient.transport,this.currentApiKey=c.agentClient.apiKey,this.currentModel=c.agentClient.model,this.currentProvider=c.agentClient.provider,this.currentBaseUrl=c.agentClient.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}invalidateResolvedLlmCache(){this.agent=null,this.lastLlmConfigKey="",this.currentTransport=null,this.currentApiKey="",this.currentModel="",this.currentProvider="",this.currentBaseUrl="",this.currentMediaApiKeys=null}emitAgentStatus(e,r,n){this.sendNotification("agents.status",NL(e,r,n))}createDreamHandlerHost(){return $L({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getToolCatalog:()=>this.runtimeServices.toolCatalog,getTaskStore:()=>this.taskStore,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveMemoryRoot:()=>Uw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return LL({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e),pendingAskUser:this.pendingAskUser})}async handleMcpToolCall(e,r,n){return DL({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let s=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!s.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${s.reason}`);return}}let i={jsonrpc:"2.0",id:e};n?i.error=n:i.result=r,this.writeStdout(i)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),i=setTimeout(()=>{if(!this.rpcIds.has(e))return;let s=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),s&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:k.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);i.unref?.(),this.rpcDeadlineTimers.set(e,i)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(!(this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)&&qx(this.acpServer,this.currentSessionId,e,r))){let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
|
|
1254
|
+
`),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,i=o?r:void 0,s=t.result.details?.type,a=t.result.details?{...t.result.details}:void 0,c=s?.split("_")[0];if(s==="three_d_generate"&&(c="3d"),c&&["image","tts","video","music","3d"].includes(c)){let d=t.result.details?.mediaUrls??[];if(d.length>0)try{let p=await t.mediaPersistence.downloadAll(d,{type:c,sessionId:t.sessionId||void 0},{warn:m=>t.log(m)});if(p.length>0){let m=new Map(p.map(g=>[g.remoteUrl,zL(g.localPath)]));for(let g of p)r=r.replaceAll(g.remoteUrl,g.localPath);d=d.map(g=>m.get(g)??g),t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:p.map(g=>({remoteUrl:g.remoteUrl,localPath:g.localPath,bytes:g.bytes,mimeType:g.mimeType}))})}}catch{}a&&(a.mediaUrls=d)}if(s==="task"&&!o&&t.result.details?.taskList)try{let d=t.result.details;d?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:d.taskList,summary:{total:d.total??d.taskList.length,completed:d.completed??0,inProgress:d.inProgress??0,notStarted:d.notStarted??0}})}catch{}let u=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:i,toolReferences:u,imageUrls:n,details:a}}function vF(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let i=t.toolCatalog.findTool(r);if(!i)return{result:"",error:`Unknown tool: ${r}`};if(typeof i.execute!="function")return{result:"",error:`Tool is not executable: ${r}`};let s=i.execute,a=`tc_${Voe().slice(0,8)}`;try{let c=JSON.parse(n),u=t.getSessionId(),d;try{d=t.mediaPersistence.getMediaDir()}catch{d=void 0}let p=await RM(d,()=>s(a,c,o));return await yF({turnId:e,sessionId:u,result:p,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(m,g)=>t.sendNotification(m,g)})}catch(c){return{result:"",error:c instanceof Error?c.message:String(c)}}}}}function bF(t){let e={info:s=>t.log(s),warn:s=>t.log(`[warn] ${s}`),error:s=>t.log(`[error] ${s}`),debug:s=>{t.verbose&&t.log(`[debug] ${s}`)}},r=vF({mediaPersistence:t.mediaPersistence,toolCatalog:t.toolCatalog,getSessionId:()=>t.sessionId,log:s=>t.log(s),sendNotification:t.sendNotification}),n=fF({resolvedConfig:t.resolvedTextConfig,providerRegistry:t.providerRegistry,sessionId:t.sessionId}),o=gF({config:t.config,log:e,taskStore:t.taskStore,backgroundTasks:t.backgroundTasks,sessionId:t.sessionId,getTurnId:t.getTurnId,projectRoot:t.projectRoot,pathService:t.pathService,memdir:t.memdir,currentUserId:t.currentUserId,memoryPrefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,agentClient:n,toolCatalog:t.toolCatalog,currentMcpManager:t.runtimeSession.mcpManager,setMcpManager:t.setMcpManager,setMcpReady:t.setMcpReady,setPluginLoader:t.setPluginLoader,getPluginSkills:()=>t.runtimeSession.getPluginSkills(),getAgent:t.getAgent,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentPermissionUnregister:t.runtimeSession.permissionUnregister,coreToolHost:t.coreToolHost,toolInvoker:r,currentFileWatcher:t.runtimeSession.fileWatcher,setFileWatcher:t.setFileWatcher});return t.runtimeSession.applyBootstrap(o),{agent:hF({client:n,toolInvoker:r,log:e,hooks:o.hooks,maxRounds:t.config.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}).agent,agentClient:n,toolInvoker:r,hooks:o.hooks}}var Joe=Zoe(import.meta.url);function Xoe(){for(let t of["../package.json","../../package.json"])try{return Joe(t).version}catch{}return"0.0.0"}var kF=Xoe();var Yoe=new Set(["thread.user_response"]);var Fw=class{running=!1;startedAt=Date.now();packageVersion=kF;rpcContract=new Ki;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;runtimeServices;runtimeSession=new Dd;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Ga;backgroundTasks=new Ka(this.taskStore);pendingTaskNotifications=[];memoryPrefetchState=rr();lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=Md();pendingAskUser=new Map;sessionTaskDomain;acpSessionMeta=null;multiAgentHandlerHost;acpServer=null;sessionHistory=new jd;idleDreamCoordinator;petConfirmCoordinator;modelRegistryHydration=null;get registry(){return this.runtimeServices.providerRegistry}get mediaClient(){return this.runtimeServices.mediaClient}get mediaPersistence(){return this.runtimeServices.mediaPersistence}get pathService(){return this.runtimeServices.pathService}get toolCatalog(){return this.runtimeServices.toolCatalog}get petRuntime(){return this.runtimeServices.petRuntime}get currentHooks(){return this.runtimeSession.currentHooks}get permissionChecker(){return this.runtimeSession.permissionChecker}set permissionChecker(e){this.runtimeSession.permissionChecker=e}set mcpManager(e){this.runtimeSession.mcpManager=e}get memoryProvider(){return this.runtimeSession.memoryProvider}set memoryProvider(e){this.runtimeSession.memoryProvider=e}get memoryDreamProvider(){return this.runtimeSession.memoryDreamProvider}set memoryDreamProvider(e){this.runtimeSession.memoryDreamProvider=e}get memoryUserId(){return this.runtimeSession.memoryUserId}set memoryUserId(e){this.runtimeSession.memoryUserId=e}constructor(e){this.verbose=e.verbose,this.runtimeServices=GL({verbose:e.verbose,getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Ud({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=_L({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Ld({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),resolveMemoryRoot:()=>Uw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),listRecentSessions:()=>Wt(20,this.getActiveProjectRoot()),runDream:r=>Uo.call(this.createDreamHandlerHost(),r)}),W().onChange(()=>{this.invalidateResolvedLlmCache()}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ui({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),this.backgroundTasks.onTaskSettled(r=>{this.pendingTaskNotifications.push(rx(r,r.output??r.error??""))})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}drainPendingTaskNotifications(){if(this.pendingTaskNotifications.length===0)return[];let e=this.pendingTaskNotifications;return this.pendingTaskNotifications=[],e}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=W();e.load(),await Hn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){this.configureTurnMedia(void 0,this.currentTurnId||"tools-list")}configureTurnMedia(e,r){let n=this;this.runtimeServices.configureTurnMedia({host:{get currentMediaApiKeys(){return n.currentMediaApiKeys},set currentMediaApiKeys(o){n.currentMediaApiKeys=o},get sessionState(){return n.sessionState},sendNotification:(o,i)=>this.sendNotification(o,i)},config:e,turnId:r})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(eg(e)||Zi(e)){this.acpServer.dispatchMessage(e);return}if(Vi(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!Ym(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{await Cx(),this.runtimeSession.stopFileWatcher(),await this.runtimeSession.disconnectMcp(),this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=Dj(this);handleMessage(e){if(e.id!==void 0&&!Yoe.has(e.method)){let n=sc(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);if(r){let n=o=>{e.id!==void 0&&this.rpcIds.has(e.id)&&this.sendResponse(e.id,void 0,{code:k.INTERNAL_ERROR,message:o instanceof Error?o.message:String(o)})};try{Promise.resolve(r(e)).catch(n)}catch(o){n(o)}}else e.id!==void 0&&this.sendResponse(e.id,void 0,{code:k.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=jL({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return ML({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=this.runtimeServices.ensureMemoryProvider(this.memoryUserId);this.runtimeSession.memoryProvider=e.handlerProvider,this.runtimeSession.memoryDreamProvider=e.dreamProvider,this.runtimeSession.memoryUserId=e.userId}resolveAgent(e){let r=EL(e,u=>this.log(u));if(!r)return null;let{provider:n,model:o,apiKey:i,baseUrl:s,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s),this.agent;e.model=o,e.provider=n,e.apiKey=i,s&&(e.baseUrl=s);let c=bF({config:e,taskStore:this.taskStore,backgroundTasks:this.backgroundTasks,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),pathService:this.pathService,memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),resolvedTextConfig:r,verbose:this.verbose,providerRegistry:this.registry,mediaPersistence:this.mediaPersistence,toolCatalog:this.toolCatalog,runtimeSession:this.runtimeSession,setMcpManager:u=>{this.runtimeSession.mcpManager=u},setMcpReady:u=>{this.runtimeSession.mcpReady=u},setPluginLoader:u=>{this.runtimeSession.pluginLoader=u},getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)?{sessionId:this.currentSessionId,requestPermission:u=>this.acpServer.requestPermission(u)}:void 0,sendNotification:(u,d)=>this.sendNotification(u,d),isPetActive:()=>this.petRuntime.isActive(),coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentBaseUrl:()=>this.currentBaseUrl,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,getBackgroundTasks:()=>this.backgroundTasks,getConversationHistory:()=>this.currentSessionId?this.sessionHistory.getResumedHistory(this.currentSessionId):null,isGroupContext:()=>Qa(),sendNotification:(u,d)=>this.sendNotification(u,d),emitAgentStatus:(u,d,p)=>this.emitAgentStatus(u,d,p),handleMcpToolCall:(u,d,p)=>this.handleMcpToolCall(u,d,p)},setFileWatcher:u=>{this.runtimeSession.fileWatcher=u},log:u=>this.log(u)});return this.agent=c.agent,this.lastLlmConfigKey=a,this.currentTransport=c.agentClient.transport,this.currentApiKey=c.agentClient.apiKey,this.currentModel=c.agentClient.model,this.currentProvider=c.agentClient.provider,this.currentBaseUrl=c.agentClient.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}invalidateResolvedLlmCache(){this.agent=null,this.lastLlmConfigKey="",this.currentTransport=null,this.currentApiKey="",this.currentModel="",this.currentProvider="",this.currentBaseUrl="",this.currentMediaApiKeys=null}emitAgentStatus(e,r,n){this.sendNotification("agents.status",NL(e,r,n))}createDreamHandlerHost(){return $L({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getToolCatalog:()=>this.runtimeServices.toolCatalog,getTaskStore:()=>this.taskStore,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveMemoryRoot:()=>Uw.join(this.pathService.getProjectAgentDir(this.getActiveProjectRoot()),"memory"),resolveTranscriptDir:()=>this.pathService.getProjectSessionsRoot(this.getActiveProjectRoot()),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return LL({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e),pendingAskUser:this.pendingAskUser})}async handleMcpToolCall(e,r,n){return DL({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let s=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!s.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${s.reason}`);return}}let i={jsonrpc:"2.0",id:e};n?i.error=n:i.result=r,this.writeStdout(i)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),i=setTimeout(()=>{if(!this.rpcIds.has(e))return;let s=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),s&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:k.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);i.unref?.(),this.rpcDeadlineTimers.set(e,i)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(!(this.acpServer&&this.currentSessionId&&this.acpServer.hasSession(this.currentSessionId)&&qx(this.acpServer,this.currentSessionId,e,r))){let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
|
|
1255
1255
|
`)}enableIdleDream(e){this.idleDreamCoordinator.enable(e)}cancelIdleDreamTimer(){this.idleDreamCoordinator.cancelTimer()}disposeSessionRuntime(){this.runtimeSession.unregisterPermissions(),this.closeMemoryProviders(),this.agent=null,this.lastLlmConfigKey="",this.memoryPrefetchState=rr(),this.runtimeSession.resetAfterSessionDispose()}closeMemoryProviders(){this.runtimeServices.closeMemoryProviders({memoryProvider:this.memoryProvider,memoryDreamProvider:this.memoryDreamProvider}),this.runtimeSession.resetMemoryProviders()}initAcpServer(){let e=TL(this,kF,this.createAcpExtendedHandlerHost());this.acpServer=new ac(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}};export{Dn as Agent,Fw as StdioServer,Ui as StdioTransport,$i as buildSkillInstruction,Ow as createHookRegistry,xz as parseCliArgs};
|
|
@@ -8,6 +8,7 @@ export interface CliCoreToolHostDeps {
|
|
|
8
8
|
getCurrentTransport(): LLMTransport | null;
|
|
9
9
|
getCurrentApiKey(): string;
|
|
10
10
|
getCurrentModel(): string;
|
|
11
|
+
getCurrentBaseUrl(): string;
|
|
11
12
|
getCurrentSessionId(): string;
|
|
12
13
|
getActiveProjectRoot(): string;
|
|
13
14
|
getVerbose(): boolean;
|
|
@@ -7,6 +7,16 @@ export interface TeamToolService extends TeamToolDeps {
|
|
|
7
7
|
export interface TeamToolServiceHost {
|
|
8
8
|
readonly currentSessionId: string;
|
|
9
9
|
readonly verbose: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Current LLM config to hand to spawned member subprocesses. Without it the
|
|
12
|
+
* member has no model and fails its first turn ("cannot connect to llmrouter
|
|
13
|
+
* model catalog"). Returns null when no provider is configured yet.
|
|
14
|
+
*/
|
|
15
|
+
getLlmConfig(): {
|
|
16
|
+
model: string;
|
|
17
|
+
apiKey: string;
|
|
18
|
+
baseUrl?: string;
|
|
19
|
+
} | null;
|
|
10
20
|
sendNotification(method: string, params: Record<string, unknown>): void;
|
|
11
21
|
emitAgentStatus(agentId: string, state: string, extra?: {
|
|
12
22
|
missedBeats?: number;
|