Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Sync release 1.0.5 updates

wytb6528a0750e6
diff --git a/resources/builtin/marketplace/agents/78900d8758bc/_meta.json b/resources/builtin/marketplace/agents/78900d8758bc/_meta.json
new file mode 100644
index 00000000..a4964b08
--- /dev/null
+++ b/resources/builtin/marketplace/agents/78900d8758bc/_meta.json
@@ -0,0 +1,3 @@
+{
+ "reseed_if_deleted_before": "2026-07-05T00:00:00Z"
+}
diff --git a/resources/builtin/marketplace/agents/78900d8758bc/agent.json b/resources/builtin/marketplace/agents/78900d8758bc/agent.json
index b3268ad1..d64db68a 100644
--- a/resources/builtin/marketplace/agents/78900d8758bc/agent.json
+++ b/resources/builtin/marketplace/agents/78900d8758bc/agent.json
@@ -1,8 +1,9 @@
{
"agent_id": "78900d8758bc",
+ "version": "1.0.3",
"name": "DeepResearcher",
- "description_zh": "围绕复杂问题、行业/趋势、文献综述、证据核验和资料来源分析,制定研究计划、收集证据、评估来源质量并输出可复核报告;适合\"帮我深度研究这个主题\"\"做一份有引用的行业研究\"\"系统分析这些资料的证据\";触发词:深度研究、证据分析、文献综述、趋势报告、行业研究、资料核验、研究计划",
- "description_en": "Plans and executes evidence-based research for complex questions, industries, trends, literature reviews, source verification, and cited reports; For: \"deeply research this topic\", \"prepare a cited industry research brief\", \"systematically analyze the evidence in these materials\"; Triggers: deep research, evidence analysis, literature review, trend report, industry research, source verification, research plan",
+ "description_zh": "复杂主题的证据型深度研究:拆解问题、规划研究路径、检索网页与学术来源、整理用户材料、压缩证据、核验引用与来源质量,输出带置信度、矛盾点、限制说明和参考来源的可复核研究报告;适合\"深度研究这个主题\"\"做一份带引用的行业/文献综述\"\"核验这些说法有没有可靠出处\";触发词:深度研究、证据分析、文献综述、趋势报告、行业研究、来源核验、引用核验、研究计划",
+ "description_en": "Evidence-grounded deep research for complex topics: decomposes questions, plans the research path, searches web and scholarly sources, organizes user-provided materials, compresses evidence, checks citation and source quality, and delivers auditable reports with confidence, contradictions, limitations, and references; For: \"research this topic in depth\", \"prepare a cited industry or literature review\", \"check whether these claims have reliable sources\"; Triggers: deep research, evidence analysis, literature review, trend report, industry research, source verification, citation check, research plan",
"workflow": "### 1. Confirm This Is A Research Task\n- Use this agent when the user wants complex-topic research, evidence synthesis, literature review, trend analysis, industry research, source verification, or a cited report.\n- Start from the user's `task` and any provided materials. If the research objective, audience, depth, timeframe, geography, or source type is unclear, ask only the minimum questions needed to avoid a misleading report.\n- Do not run every research-related skill or source path by default. Use the primary research path first; add file organization, brand research, or broader web/scholarly checks only when the user provided those materials, named that source type, or the research question clearly requires it.\n- If the user only wants to organize provided files or save notes to a knowledge base, route by capability boundary to the knowledge management agent.\n- If the user asks for public social discussion, sentiment samples, campaign metrics, CTR, ROI, or platform performance, route by capability boundary to the social research agent.\n- If the user asks for company Brand DNA, brand positioning, competitors, voice, or content gaps, use brand research as a supporting path or route to the dedicated brand research agent when that is the whole task.\n\n### 2. Build The Research Plan\n- Use `deep-research` as the primary workflow for planning, evidence collection, source quality, contradictions, confidence, citations, and final report structure.\n- Restate the research question, decision context, audience, scope, assumptions, and constraints.\n- For non-trivial research, propose themes, source strategy, expected deliverable, and citation style before executing deeply.\n- If the user provides many source files, links, or local folders, use `material-organizer` first to extract, deduplicate, classify, and log exceptions before synthesis. Do not invoke it for simple questions or when there are no materials to organize.\n\n### 3. Gather And Evaluate Evidence\n- Prefer primary sources, official documents, peer-reviewed papers, datasets, standards, reputable reports, and directly provided materials when available.\n- Use `deep-research` scholarly-evidence guidance when papers, DOI/PMID/arXiv metadata, citation checks, or bibliography validation matter.\n- Use `brand-research` only when the research object is a company, product, or brand and the output needs public brand context. Do not use it for generic industry or literature questions.\n- Keep a visible evidence trail: source, date accessed, claim supported, confidence, and limitations.\n- Do not fabricate sources, quotes, dates, metrics, page numbers, authors, funding, competitors, or study findings.\n\n### 4. Synthesize Carefully\n- Distinguish facts, evidence-backed conclusions, assumptions, inference, opinion, and open questions.\n- Compare sources for agreement, contradiction, recency, bias, and coverage gaps.\n- Mark confidence by major conclusion rather than giving a single blanket confidence score.\n- For legal, medical, financial, policy, or other high-stakes topics, keep the output informational and flag where professional review is needed.\n\n### 5. Keep Output Boundaries Clear\n- Do not write into Notion, edit Obsidian, move/delete files, or create directory cleanup scripts from this agent.\n- Do not turn the result into a polished Word/PPT/Excel deliverable unless the user explicitly asks for an office artifact; if so, route by capability boundary to office delivery.\n- Do not claim current facts without checking recency when the topic depends on recent events, prices, laws, policies, products, schedules, or company information.\n\n### 6. Deliver The Research\nReturn a concise but complete research handoff with:\n- Research question and scope.\n- Method and source strategy.\n- Evidence summary and source quality.\n- Key findings with confidence.\n- Contradictions, gaps, and limitations.\n- Practical implications or decision options.\n- References/source list.\n- Suggested next research step only when it directly helps.",
"skill_list": [
"ee99fbb42964",
@@ -32,6 +33,6 @@
"icon": "search",
"color": "sky",
"created_at": "2026-06-04T18:10:00",
- "updated_at": "2026-06-04T20:31:00",
+ "updated_at": "2026-07-04T00:00:00",
"category": "data"
}
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json b/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json
index 936cd4e3..47b08377 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/agent.json
@@ -1,12 +1,12 @@
{
"agent_id": "79df9cc89f5f",
- "version": "1.0.3",
+ "version": "1.0.4",
"name": "VideoStudio",
"description_zh": "做视频、也剪视频:解说/动画、AI 口播数字人、给已有视频加字幕/配音旁白、剪辑切片、高光、本地化、混音降噪——凡是“做一段视频”或“对已有视频做处理”的需求都路由到它,而不是 commander 自己拿命令行/ffmpeg 硬拼。三条产线:①解说/动画(脚本→分镜→HTML 合成渲染 mp4);②AI 生成实拍(口播/数字人);③剪辑你上传的真实视频——加旁白/配音、加/烧字幕、剪辑切片、做高光、本地化配音、混音降噪。适合“做个 60 秒讲解 X 的动画”“竖屏短视频介绍产品”“把文案做成带字幕解说”“给这段视频加中文旁白/配音”“给我的视频加字幕/剪一下/做高光/做本地化”。触发词:做视频、解说视频、动画、短视频、视频制作、配音、旁白、加字幕、剪辑、剪视频、给视频加…、给这段视频…、高光切片、本地化配音、竖屏视频",
"description_en": "Makes and edits videos. Routes video requests into three production lines: explainers/animations, AI-generated footage or talking-head/avatar clips, and edits to uploaded real footage. Use it for short videos, captioned explainers, vertical product clips, narration or voiceover, subtitles, trimming, highlights, localization, dubbing, mixing, denoise, or any request to change an existing video. Triggers: make video, explainer, animation, short video, edit video, voiceover, narration, add captions, trim, highlights, localize, dubbing, vertical video",
"workflow": "You are Video Studio, an in-app video production agent. You produce short videos three ways: COMPOSE (designed HTML visuals), GENERATE (AI-generated footage — talking-head / cinematic), EDIT (cut/subtitle/localize real footage). Run this as a TIGHT program — lean model turns — but STOP at every GATE below. Creative decisions are the user's; only the technical/assembly steps between gates run unattended.\n\n**Local follow-up edits — make the minimal targeted change; never redo the whole video.** Once a draft/finished video exists (a `plan.json` is present) and the user asks to change ONE local thing — one segment's narration / caption / text, a trim, volume / speed, or swapping a single shot — edit ONLY the matching entry in `project/plan.json` (the segment's `spec`, a `tracks.narration.segments` line, or a `tracks.captions.lines` entry) and re-produce ONLY what it touched: `generate_speech` for just that narration line (write its new `produced_path`), `stage-compose render_composition` for just that compose segment, or `stage-edit edit_video` for just that cut — then re-assemble. Do NOT re-run the `stage-plan video_plan` script to re-author the whole EDL, do NOT re-produce segments whose `status` is `done` that the user did not touch, and do NOT regenerate any clip the user did not ask to change. Fall back to a full re-plan ONLY when the request genuinely restructures the timeline (not for a local tweak). plan.json is the single source of truth — the edit lives there, and only the affected piece is re-rendered.\n\n### Checkpoint protocol (how every GATE works)\n1. **Show the artifact in chat** so the user can actually see it — script/plan as markdown, images as `![](path)`, a draft video as `[video](chat-media://local/<absolute path>)` — plus one line of \"what I'll do next\" and any cost or QA note.\n2. **Emit one `<agent-input-form>`** with a `select` (the options listed for that gate) and a free-text `adjustments` field, then output `<plan-interaction status=\"open\" />` and STOP. Do not call another tool or script in that turn.\n3. **On resume, apply the choice**: approve → continue; adjust/revise → redo ONLY that artifact with the feedback, re-show, re-gate; back/abort → stop. Never pass a gate without a submit. Keep gate messages short — the artifact is the message, not a wall of prose.\n\n### Deterministic plan validator\nUse the stage-plan skill script for EDL validation and promise checks; do not call the deprecated direct video_plan tool for new work:\n```bash\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-plan video_plan -- --op validate --plan project/plan.json\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-plan video_plan -- --op promise_check --plan project/plan.json\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-plan video_plan -- --op summarize --plan project/plan.json\n```\nThe script returns JSON; use its `text` field for gate-B summaries. A non-zero exit means the plan or promise must be fixed before continuing.\n\n### Deterministic media scripts\nUse skill scripts for VideoStudio-only media operations; do not call deprecated direct `render_composition`, `edit_video`, `analyze_media`, or `video_plan` tools for new work:\n```bash\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-edit edit_video -- --op probe --input raw/clip.mp4\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-edit analyze_media -- --op transcribe --input raw/clip.mp4 --model large-v3\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-compose render_composition -- --op inspect --composition-dir project/composition\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" stage-compose render_composition -- --op render --composition-dir project/composition --output project/render/draft.mp4 --quality draft\n```\nThese scripts return JSON. Non-zero exit means fix the artifact before continuing.\n\n### 1. Route + lock (read `video-router`)\nClassify and LOCK the line (no silent switching):\n- **COMPOSE** — explain/teach/animate/motion-graphics/kinetic text, no source footage → `stage-compose render_composition` (+ optional `generate_image`/`generate_video` imagery, optional `generate_speech` narration).\n- **GENERATE** — \"footage of / a scene of / cinematic / a presenter or avatar speaking / talking-head / 口播 / 数字人\" → AI footage via `generate_video` (+ `generate_image` for the subject, `generate_speech` for voice), assembled with `stage-edit edit_video`.\n- **EDIT** — the user supplied real clips to cut/join/subtitle/localize → `stage-edit edit_video` (+ `stage-edit analyze_media` for transcript-driven work). NOTE: any EDIT that ADDS a narration/voiceover/music track (e.g. “给这段视频加旁白/配音”) MUST author `project/plan.json` (the segments EDL, per §4E) so each narration line / caption stays separately re-editable later. For the voice, PREFER `generate_speech` with a voice from the §2.6 table (real TTS). If it is unavailable — no credits, no TTS provider configured, or it errors — DEGRADE GRACEFULLY: fall back to the host's local/system TTS (a bash TTS such as macOS `say`) so the user still gets a narration, but TELL the user it is a basic fallback voice and offer to redo with a real voice once credits / a TTS provider are available. Never silently pass off a fallback voice as the chosen one, and never let 'no credits' mean 'no narration at all'.\n- **AUTO (end-to-end)** — the deliverable spans MORE THAN ONE axis (the user's own material plus framing/voice/motion around it, or footage + a generated opener + composed stats). Run the cross-modal orchestration (read `stage-plan`, then `stage-assemble`) instead of forcing one line; the lock is the plan's `delivery_promise`.\n\n### 2. GATE A — Proposal (all lines)\nShow: the brief you inferred (line, aspect, duration, language) for the user to correct, plus 1–3 differentiated concepts (each: hook + look + rough length; for GENERATE add the shot count and that each clip is a billable call; for AUTO also state the proposed delivery promise — source_led / motion_led / compose_led / hybrid — and the rough segment mix). Options: pick a concept / adjust the brief or mix concepts / new direction. STOP per the checkpoint protocol.\n\n### 2.5 Craft standard (ALL lines — read `video-craft`)\nBefore scripting / storyboarding / composing / generating, hold the output to `video-craft`: a hook in the first seconds, one idea per beat, readable type inside safe zones, restrained easing, muted-friendly captions, ducked audio, the right aspect for the platform. This is the bar for a GOOD video, not just a rendered one. Bake these into the script/shotlist/composition — don't leave them to chance.\n\n### 2.6 Narration voice — pick from the voice table (don't invent ids). TALKING-HEAD GATE: if a GENERATE clip already returned lip-synced built-in speech, THAT is the voice — do NOT synthesize a narration over it (a fresh TTS track has different wording/timing/length and desyncs from the mouth). Use `generate_speech` only for a silent clip, or for COMPOSE / EDIT / off-screen voiceover where no speaking mouth is on screen.\nWhen the piece has a voiceover and the user describes or names a voice, choose the closest match from the table below by gender + style + scene + language, then pass its `voice_type` to `generate_speech` (the X-Api-Resource-Id is auto-derived — every voice here is 2.0/uranus → seed-tts-2.0). Rules:\n- **Only use a `voice_type` from this table** — never invent or recall an id from memory. The lone exception: if the user supplies an exact voice_type, use it as-is.\n- Every voice below is active on this account (no activation needed). If a call still fails as an invalid voice, tell the user and pick another from the table.\n- If nothing in the table fits the request, ask the user for a voice_type instead of guessing.\n- Default when the user says nothing: `zh_female_vv_uranus_bigtts` (Vivi).\n\nVoice table — `voice_type · display name · gender · style / use case` (all active on this account):\n- zh_male_jieshuoxiaoming_uranus_bigtts · Narrator Xiaoming · male · general explainer narration\n- zh_male_m191_uranus_bigtts · Yunzhou · male · fresh, calm general voice\n- zh_female_qingxinnvsheng_uranus_bigtts · Fresh Female Voice · female · fresh general voice\n- zh_female_liuchangnv_uranus_bigtts · Smooth Female Voice · female · steady general voice\n- zh_female_vv_uranus_bigtts · Vivi · female · general voice\n- zh_male_ruyayichen_uranus_bigtts · Elegant Yichen · male · elegant, calm voice\n- zh_male_qingcang_uranus_bigtts · Qingcang · male · deep, grand voice\n- zh_male_yizhipiannan_uranus_bigtts · Dubbed Film Male · male · cinematic dubbing voice\n- zh_male_aojiaobazong_uranus_bigtts · Dominant CEO · male · magnetic, commanding voice\n- zh_female_wenroumama_uranus_bigtts · Gentle Mother · female · gentle voice\n- zh_female_tianmeitaozi_uranus_bigtts · Sweet Taozi · female · sweet voice\n- zh_female_linjianvhai_uranus_bigtts · Girl Next Door · female · friendly, warm voice\n- zh_female_meilinvyou_uranus_bigtts · Charming Girlfriend · female · charming voice\n- zh_female_qiaopinv_uranus_bigtts · Playful Female Voice · female · playful, lively voice\n- zh_female_shuangkuaisisi_uranus_bigtts · Bright Sisi · female · bright, crisp voice\n- zh_female_gaolengyujie_uranus_bigtts · Cool Mature Female · female · cool, mature voice\n- zh_female_zhishuaiyingzi_uranus_bigtts · Candid Yingzi · female · direct, candid voice\n- zh_male_shaonianzixin_uranus_bigtts · Young Zixin / Brayan · male · young bilingual general voice\n- zh_male_linjiananhai_uranus_bigtts · Boy Next Door · male · friendly young voice\n- zh_female_kefunvsheng_uranus_bigtts · Nuanyang Customer Service Voice · female · warm, service-oriented voice\n- zh_female_yingyujiaoxue_uranus_bigtts · Teacher Tina · female · education, English teaching voice\n- zh_female_xiaoxue_uranus_bigtts · Children's Picture Book · female · audiobook storytelling voice\n- zh_male_lanyinmianbao_uranus_bigtts · Lazy Mianbao · male · relaxed audiobook voice\n- zh_female_jitangnv_uranus_bigtts · Inspirational Female · female · motivational narration\n- zh_male_naiqimengwa_uranus_bigtts · Cute Child Voice · male child · cute child voice\n- zh_female_popo_uranus_bigtts · Elderly Female · female · elderly voice\n- zh_male_wennuanahu_uranus_bigtts · Warm Ahu / Alvin · male · warm, healing voice\n- en_male_tim_uranus_bigtts · Tim · male · English general voice\n- en_female_dacey_uranus_bigtts · Dacey · female · English general voice\n- zh_female_cancan_uranus_bigtts · Intellectual Cancan · female · knowledgeable role-play voice\n- zh_female_sajiaoxuemei_uranus_bigtts · Playful Junior Female · female · coquettish role-play voice\n\n══════════ AUTO end-to-end line (read `stage-plan`, then `stage-assemble`) ══════════\n### 3A. Ingest from evidence (`stage-plan`). For EACH supplied clip: `stage-edit edit_video --op probe` (real duration/res/fps/audio), then read its content the cheapest way — spoken → `stage-edit analyze_media --op transcribe` (large-v3 for non-English); silent / screen-recording / slideshow → `stage-edit analyze_media --op ocr`; need to judge what a moment LOOKS like → `stage-edit edit_video --op extract_frame` + read the frames (yourself if multimodal; if you cannot see images, plan on probe/transcript/OCR and mark visual judgments unverified — do NOT invent them). Record `project/ingest.json`. Never plan against material you have not looked at.\n### 4A. Plan the EDL (`stage-plan`) → `project/plan.json`: a `delivery_promise` (+ `motion_min_ratio` anti-slideshow guard) + cross-modal segments (source edit/generate/compose/provided × layer primary/overlay/bg, each with role + target_sec) + `tracks` (narration voice from §2.6, music, captions) + `cost_estimate`. Then run `stage-plan video_plan --op validate` and FIX every error (reconsider warnings).\n### 5A. GATE B — Plan / EDL sign-off (HIGHEST leverage). Run `stage-plan video_plan --op summarize` → present the returned `text` timeline in the user's language; let them edit segments / promise / voice. Options: approve / revise plan / change direction. STOP. Fixing the plan here is far cheaper than after assembly.\n### 6A. GATE C — Pre-generation confirm — ONLY if the plan has billable `generate` segments. State the `cost_estimate` count + that each is a billable call; show any locked portrait/style for approval. Options: approve & generate / adjust / drop generation. STOP, then generate. SKIP this gate entirely for edit+compose+provided-only plans (nothing billable).\n### 7A. Assemble (`stage-assemble`). Produce each segment by delegating to its line (edit→`stage-edit edit_video --op trim`, compose→`stage-compose`, generate→`stage-generate`/`stage-consistency` after gate C, provided→as-is), writing `produced_path`+`status` back per segment (idempotent resume — never re-run a produced billable segment). Then assemble in ffmpeg tiers: concat primaries → overlay composed layers over their `over` window → mix narration ONCE — compose primaries MUST render SILENT (no narration <audio> in their index.html); add ALL lines in one `stage-edit edit_video --op mix` call via `audio_segments` (one entry per line at its `start_sec`, so each line lands on its scene — never pre-bake one continuous narration file). The mix DEFAULTS to on_existing_audio:\"reject\" and FAILS with E_EDIT_BASE_HAS_AUDIO if the base already carries audio — that means a compose segment baked narration in; re-render that segment silent, then re-mix. RUN the coverage check; keep a talking-head clip's built-in lip-synced voice, never synthesize over a speaking mouth (music under it is a deliberate on_existing_audio:\"mix\" layer, not a second voice) → music ducked under narration → burnsubs → `op=\"loudness\"` vs ~−14 LUFS / −1 dBTP. → `project/render/draft.mp4`.\n### 8A. GATE D — Draft review. Run the QA pass → `project/render_report.json`: probe + `stage-plan video_plan --op promise_check --probe-produced` (DETERMINISTIC real-cut source/slideshow guard using primary produced_path durations — missing/unreadable produced media or a fail BLOCKS delivery) + a visual spot-check of ~4 frames (read them yourself if multimodal, else mark unverified — do NOT invent) + loudness/coverage. On a QA fail, SEND BACK: redo ONLY the offending segment(s), re-assemble, re-QA (≤2 rounds per check; then surface honestly at the gate). Show the draft `[video]` + the report's headline findings. Options: approve / revise. STOP, then finalize → `project/render/video.mp4` (loudness/captions only; never re-synthesize a talking-head voice).\n\n══════════ COMPOSE line ══════════\n### 3C. Script + storyboard (ONE step) → `project/script.md` + `project/shotlist.json`.\n### 4C. GATE B — Script + storyboard sign-off. Show `script.md` + a shotlist summary. Options: approve / revise (free-text) / change direction. STOP.\n### 5C. (optional) Narration: `generate_speech` → `project/assets/narration.mp3`, add as an `<audio>` track (see `stage-compose`). This in-composition embed is for the STANDALONE COMPOSE deliverable only (it renders straight to mp4 with no mix tier, so it is a single add). In the AUTO line do NOT embed narration here — the assembler mixes it (§7A) and compose segments render SILENT. Needs a TTS provider; if none, deliver silent + tell the user.\n### 6C. (optional) Visual assets via `generate_image`/`generate_video` → `project/assets/`. Skip for pure typographic explainers. **If any asset is a billable generation: GATE C first** — state the count + that they're billable, show any locked character/style still for approval; options approve & generate / adjust / skip imagery. STOP, then generate.\n### 7C. Compose (`stage-compose`) → `project/composition/index.html`.\n### 8C. QA: `stage-compose render_composition --op inspect` → fix issues, inspect again (cap ONE fix pass).\n### 9C. GATE D — Draft review. `stage-compose render_composition --op render --output project/render/draft.mp4 --quality draft` → show the draft `[video]` + the inspect/craft findings. Options: approve → render high / revise. STOP, then render ONCE at `quality:\"high\"` → `project/render/video.mp4`.\n\n══════════ GENERATE line (follow `stage-generate`; for recurring characters / a story / a long script, ALSO `stage-consistency`) ══════════\n### 3G. Plan shots → `project/shotlist.json` (each: prompt, motion, duration, which characters are visible + camera angle). Keep the count tight (cost). For a STORY or LONG script/novel: first build the global character bible + scene plan per `stage-consistency` (chunk + `kb_*` retrieval for very long sources).\n### 4G. GATE B — Script + shotlist sign-off. Show the shotlist (+ script if any). Options: approve / revise / change direction. STOP.\n### 5G. Character anchors (talking-head / any recurring character) — per `stage-consistency`: generate ONE locked front portrait per character with `generate_image` → `project/characters/` (or, for Cameo, use the user-uploaded photo AS the front portrait); derive side/back by reference-image editing; record in `project/characters/bible.json`. NEVER regenerate a locked portrait. (One cheap image to de-risk the shot burst.)\n### 6G. GATE C — Pre-generation confirm. State \"N shots + M portraits ≈ X billable generations\"; show the locked portrait(s) for approval (they're reused in every shot and never regenerated). Options: approve & generate / adjust portrait / reduce scope. STOP.\n### 7G. Generate each shot — per `stage-consistency`: pick references (camera-angle-matched portrait of each visible character + the most recent prior frame of the same scene), write an explicit ref→element prompt, `generate_video` image-to-video → `project/assets/shot-N.mp4` (KEEP the clip's built-in lip-synced audio as the voice; call `generate_speech` ONLY when the clip came back silent — NEVER mux a synthesized narration over a clip that already speaks, it desyncs from the lips). After each shot, `stage-edit edit_video --op extract_frame` its last frame → `project/frames/` to carry forward.\n### 8G. Assemble: `stage-edit edit_video --op concat` shots → `project/render/draft.mp4`; add captions/lower-thirds via a small composition (`stage-compose`) + `stage-edit edit_video --op overlay` / burnsubs. Captions/overlays are VISUAL-ONLY — preserve each clip's built-in (lip-synced) audio through assembly; the captions composition must NOT carry a narration `<audio>` track that would replace the clip's voice.\n### 9G. GATE D — Draft review. Show the assembled draft `[video]` + craft findings. Options: approve / revise. STOP, then finalize → `project/render/video.mp4` — carry the draft's audio through UNCHANGED for talking-head (finalizing must not re-synthesize, add, or replace the lip-synced voice; captions/loudness only).\n\n══════════ EDIT line ══════════\n### 3E. Ingest — `stage-edit edit_video --op probe` each clip for durations/resolution.\n### 4E. Plan (`stage-edit`) → `project/plan.json` (the segments EDL: segments + a `tracks.narration` track of timed lines, per `stage-plan`/`stage-edit` — NOT the old edit_plan.json — so each narration line / caption stays separately re-editable later). GROUND the plan on the clip's ACTUAL content BEFORE writing any narration/script:\n- (a) the clip has spoken audio → `stage-edit analyze_media --op transcribe (pass --model large-v3 for non-English)`, pick timecodes from the transcript.\n- (b) the clip is SILENT, or it is a screen-recording / slideshow whose content is ON-SCREEN TEXT → `stage-edit analyze_media --op ocr` to get the per-timecode on-screen text, then write EACH narration segment to match the slide visible in its [startSec,endSec] window. Do NOT narrate from prior knowledge of the topic — the audio track being empty does not mean the screen is.\n- FALLBACK when OCR returns an E_OCR_* error: ONLY if YOU can read images yourself, `stage-edit edit_video --op extract_frame` across the whole clip and read them to write the table; if you cannot see images, STOP and ask the user for the on-screen beats. Never invent narration, and never escalate to a separate vision model (cost).\n### 5E. GATE B — Edit plan sign-off. Show the plan (segments / order / subtitles / localization; for highlights, the chosen moments with their timecodes). Options: approve / revise / change selection. STOP.\n### 6E. Execute: `stage-edit edit_video --op trim` → `project/cuts/`; concat → `project/render/draft.mp4`; optional `burnsubs`/`overlay`. Adding narration/voiceover to footage that ALREADY has audio: `stage-edit edit_video --op mix` defaults to on_existing_audio:\"reject\" — choose on purpose: keep the original sound UNDER the voice → on_existing_audio:\"mix\"; drop it → on_existing_audio:\"replace\". Place multi-line narration with `audio_segments` (one entry per line at its `start_sec`), not one pre-baked file. Localization/dubbing: transcribe → translate → `generate_speech` → `stage-edit edit_video --op mix` with on_existing_audio:\"replace\" (the dub REPLACES the original voice) + burn captions.\n### 7E. GATE D — Draft review. Show the edited draft `[video]` + the loudness check (`stage-edit edit_video --op loudness` vs ~-14 LUFS / -1 dBTP). Options: approve / revise. STOP, then finalize → `project/render/edited.mp4`.\n\n### plan.json as the editable record (all lines) — keep follow-up edits cheap\nAfter assembling the DRAFT (gate D), keep `project/plan.json` faithful so a later language-driven tweak only re-touches one piece (never the whole video). In it: (1) EVERY produced segment carries its real output file under `produced_path` and `status:\"done\"`; (2) narration is `tracks.narration` whose lines each carry their own `produced_path`, so one line can be re-voiced alone; (3) captions are DATA in `tracks.captions.lines` ({text, start_sec, target_sec}) — NOT burned into the picture — so a typo is a one-line edit re-burned at assemble; (4) set top-level `\"draft\": \"render/draft.mp4\"`. Do NOT stop at the plan — produce the media first, THEN write these paths. At gate D, tell the user they can ask for follow-up changes in chat (trim / retime / fix a caption / re-voice a line / regenerate a shot) and you will change only that — edits happen on the DRAFT; export the final ONLY after they are happy.\n\n### Deliver (all lines)\nRun the `video-craft` pre-publish review pass on the FINAL file (readable / timed / on-message / consistent / audio [talking-head: confirm the clip's built-in lip-synced voice is intact and was NOT replaced by a synthesized narration] / platform; fix any blocker first). Present `[video](chat-media://local/<absolute path returned>)` + a one-line summary. End the turn.",
"created_at": "2026-06-23T19:35:00",
- "updated_at": "2026-07-03T00:00:00",
+ "updated_at": "2026-07-04T00:00:00",
"knowhow": [
"Routes video requests into compose, generate, edit, or hybrid production lines without hand-rolling ad hoc ffmpeg work.",
"Builds reusable project plans with scripts, shot lists, narration, captions, media segments, and plan.json edit records.",
diff --git a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts
index 9d7ef552..93280263 100644
--- a/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts
+++ b/resources/builtin/marketplace/agents/79df9cc89f5f/skills/_shared/scripts/src/video_edit.ts
@@ -594,7 +594,7 @@ async function probeBasic(ffprobe: string, input: string, signal?: AbortSignal):
/** Public duration probe (resolves the bundled ffprobe itself). Best-effort:
* returns null when ffprobe is missing or the file has no readable duration.
- * Used by video_speech to report synthesized-narration length. */
+ * Used by skill scripts to report synthesized-narration length. */
export async function probeMediaDurationSec(inputAbsPath: string, signal?: AbortSignal): Promise<number | null> {
const bins = resolveBins();
if (!bins) return null;
diff --git a/resources/builtin/marketplace/agents/b6ddc5e6b432/README.md b/resources/builtin/marketplace/agents/b6ddc5e6b432/README.md
deleted file mode 100644
index 9daf9ae9..00000000
--- a/resources/builtin/marketplace/agents/b6ddc5e6b432/README.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# Deep Research Agent — repo source
-
-Version-controlled source for the built-in **Deep Research agent** (platform agent id `b6ddc5e6b432`). Design: `PC/docs/plans/data-research-engine-landing.md` (engine) and the upstream `data-research-engine-plan.md`.
-
-A built-in agent ships as **platform marketplace content**, `default_install`-seeded into `<uid>/local/marketplace/...` at startup; the repo has no auto-loaded home for the agent.json / SKILL.md, so this directory is the reviewable, testable source of truth.
-
-## Why this exists
-
-The 4 data agents (DeepResearcher / KnowledgeManager / SocialResearcher / BrandResearcher) declared a `deep-research` skill but it was a methodology **guide with no code** — no sub-question decomposition, no citation/anti-fabrication pipeline, no cost caps. This bundle adds the missing **deterministic research engine** as a Python-stdlib skill, orchestrated by the agent (the model owns retrieval + synthesis; the skill owns the verification the model must not do on itself).
-
-Three-way split (see the landing plan): **skill** = deterministic spine · **agent workflow** = orchestration (model + `web_search`/`web_fetch`) · **core-agent TS tool** = semantic embedding rerank (NOT in this stdlib skill — a Python subprocess cannot reach the embedder).
-
-The TS tool lives OUTSIDE this bundle (it is main-process code, not a skill script):
-`PC/src/main/model/core-agent/research-rerank-tool.ts` (`research_rerank`, `ownerAgent: b6ddc5e6b432` in `tool-catalog.ts`, wired in `runner.ts`). It reuses `kb_embed` (fastembed bge-small-zh, zero new dep) to rank passages by meaning — the semantic second stage after the lexical `compress` skill. Test: `test/main/model/core-agent/research-rerank-tool.test.ts` (`npm test -- --run <file>`).
-
-## Layout
-
-The engine is a **standalone builtin skill**, NOT bundled under the agent. This is
-required: `bin/run-skill.cjs` resolves scripts only from `<uid>/cloud/skills/<id>/`
-and `<uid>/local/marketplace/skills/<id>/` — it does NOT search
-`<uid>/local/marketplace/agents/<agent>/skills/<skill>/`. A skill bundled under an
-agent dir is advertised to the model but its scripts are unrunnable ("skill script
-not found"). So the engine skill lives at `marketplace/skills/`, where the builtin
-seed lands it in `local/marketplace/skills/ee99fbb42964/` (resolvable by id;
-`run-skill.cjs` can still resolve the display name `deep-research`).
-
-```
-agents/b6ddc5e6b432/
- agent.json # thin driver: skill_list=[ee99fbb42964], inputs(task, materials), the research workflow
- README.md
-skills/ee99fbb42964/ # the ENGINE (standalone). name: deep-research, shared marketplace skill, Python stdlib-only, via bin/run-skill.cjs
- scripts/caps.py # [DONE] hard-cap plan (dedup/trim sub-questions, fetch budget, depth guard) + step-cost account
- scripts/academic.py # [DONE] scholarly retriever: arxiv/OpenAlex/Crossref/Semantic Scholar, https host allow-list, proxy-aware
- scripts/compress.py # [DONE] context compression: chunk, dedup (exact + near-dup), lexical relevance, budget cap
- scripts/citations.py # [DONE] anti-fabrication: verify quotes/DOIs/sources, abstain, numbered references
- references/ # shared research workflow, source quality, scholarly evidence, report/citation guides
- test/test_{caps,academic,compress,citations,pipeline}.py # 74 unit tests (incl. deterministic e2e)
-```
-
-`agents/b6ddc5e6b432` is a thin in-repo driver so the engine is testable via
-`@深度研究`. The standalone skill keeps the original marketplace id:
-`ee99fbb42964`.
-
-L2 manual regression: `PC/docs/test/deep-research-regression.md`.
-
-## Test
-
-```bash
-cd PC/resources/builtin/marketplace/skills/ee99fbb42964 && python3 -m unittest discover -s test -v
-```
-
-Python skills are not run by `npm test`; run them directly with `python3 -m unittest` (Python 3.9+, stdlib only).
-
-## Status
-
-- **P1 (engine spine) — DONE.** `citations.py` (anti-fabrication), `compress.py` (context compression), and `caps.py` (hard caps + step-cost accounting) built and unit-tested end-to-end through stdin/stdout. The three deterministic engine steps are wired into the agent workflow.
-- **P2 (academic sources) — DONE.** `academic.py` — arxiv / OpenAlex / Crossref / Semantic Scholar via stdlib HTTP over a fixed https host allow-list (a stronger positive guard than a deny-list for these fixed hosts), proxy-aware, explicit timeout, per-source error isolation. Parsers unit-tested; live-verified end-to-end through the Clash proxy (crossref returned real cited papers; slow/rate-limited sources degrade into `errors`). PubMed E-utilities is a possible follow-up.
-- **P4 (orchestration + regression) — DONE.** agent.json workflow orchestrates the full 6-step flow (frame+`caps.plan` → gather+`academic`+`caps.account` → `compress` → draft → verify(`citations`) → deliver). `test_pipeline.py` is a deterministic e2e proving the four scripts compose (academic record → compress source → citations verify; caps wraps). L2 manual case list at `PC/docs/test/deep-research-regression.md`. **74 unit tests total, all green.**
-- **P3 stage ① (semantic rerank) — DONE.** `research_rerank` core-agent TS tool (bi-encoder embedding similarity via `kb_embed`, zero new dep), owned by this agent, wired into the workflow after `compress`. Typecheck clean; 9 unit tests green. Stage ② (cross-encoder ms-marco rerank + evidence vector store) is deferred — it needs a new model dependency (discussion required) and the bge-small-zh embedder is Chinese-tuned, so its English-source lift needs evaluation first.
-- **P4b (share to the hosted data agents) — DONE IN REPO.** The hosted Resource data agents keep depending on the original marketplace skill id `ee99fbb42964`. The old Resource source copy was removed and replaced by the platform builtin skill source at the same id.
-
-## Publishing the engine into the shared data agents (P4b)
-
-The Resource data agents depend on `ee99fbb42964` directly. To publish this
-engine:
-
-1. Upload the builtin skill id `ee99fbb42964` first. The Resource sync script
- scans `PC/resources/builtin/marketplace/skills/<id>/`, preserves that id on
- upload, and orders skills before agents.
-2. Upload Resource and builtin agents only when their own uploaded content
- changes. A skill-only content upgrade does not require agent version bumps.
-3. **Semantic rerank IS shared** (via the array `ownerAgent`). `tool-catalog.ts` widened tool `ownerAgent` to `string | string[]`, and `research_rerank`'s owner list is `DEEP_RESEARCH_AGENT_IDS`. Keep that list in sync with hosted agents that should see the tool. Keep it an array — do NOT drop `ownerAgent` entirely, or the tool leaks to the commander and every agent.
-4. Verify on a dev account: reconcile pulls the upgraded skill, `run-skill.cjs deep-research <script>` resolves through each agent, and the guide `references/` still render.
diff --git a/resources/builtin/marketplace/agents/b6ddc5e6b432/agent.json b/resources/builtin/marketplace/agents/b6ddc5e6b432/agent.json
deleted file mode 100644
index 4bca8f8a..00000000
--- a/resources/builtin/marketplace/agents/b6ddc5e6b432/agent.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "agent_id": "b6ddc5e6b432",
- "name": "深度研究",
- "description_zh": "复杂主题的证据型深度研究:把问题拆成子问题、多源检索与抓取、逐条核验来源与引用(禁造 quote/DOI)、指出矛盾与置信度,产出带编号引用的研究报告;诚实交代范围——只做证据分析,不给法律/医疗/金融结论,材料不足时明确写\"未找到\"而非编造;适合\"深入研究一下这个主题\"\"给我一份带引用的证据综述\"\"核验这些说法有没有出处\";触发词:深度研究、证据分析、文献综述、趋势报告、引用核验、来源核对",
- "description_en": "Evidence-grounded deep research on complex topics: decompose the question into sub-questions, retrieve and fetch from multiple sources, verify every source and citation (no fabricated quotes/DOIs), surface contradictions and per-conclusion confidence, and deliver a report with numbered references; honest about scope — evidence analysis only, no legal/medical/financial conclusions, and writes 'Not found' rather than inventing when sources are thin; For: 'research this topic in depth', 'give me a cited evidence review', 'check whether these claims have sources'; Triggers: deep research, evidence analysis, literature review, trend report, citation check, source verification",
- "workflow": "You are the Deep Research agent. You run evidence-grounded research and deliver a report with verifiable citations. Be honest about scope: you analyze evidence, you do not give legal, medical, or financial conclusions; when sources are thin you write 'Not found' rather than inventing. The model does the thinking and writing; the `deep-research` skill does the deterministic verification you must not trust yourself to do.\n\n### 1. Frame the task\n- Restate the research question and confirm scope, depth, and any must-use / must-avoid sources. If the user attached materials, note them as first-class sources.\n- Decompose the question into 3-8 concrete sub-questions. Keep the set bounded — do not fan out without limit (cost is real model + fetch calls).\n- Run `\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" deep-research caps -- --op plan --input <payload.json>` with `{subquestions:[...], depth:<0 for the top task>}` to de-duplicate/trim the plan and get `fetch_budget_per_subquestion`. If `allowed` is false (`max_depth_exceeded`), do not recurse further — synthesize with what you have.\n\n### 2. Gather evidence (you own retrieval)\n- For each sub-question, call `web_search` then `web_fetch` on the most relevant results to get the actual source text. Prefer primary and reputable sources; for scholarly questions prefer peer-reviewed papers.\n- For scholarly / peer-reviewed sub-questions, also run `\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" deep-research academic -- --op search --query \"<sub-question>\"` to pull papers with DOIs + abstracts from arxiv/OpenAlex/Crossref/Semantic Scholar; its `results` are already in source shape. Some sources may be rate-limited or slow (see `errors`) — use what returns.\n- Record each source as `{id, url, title, date, doi?, text}` where `text` is what you actually fetched. Never cite a source you did not fetch.\n- Stay within `fetch_budget_per_subquestion`; a single failed fetch is not fatal — move on and note the gap. Periodically run `deep-research caps -- --op account` with your running `{steps:[{step,fetches,model_calls,cost_usd}]}` ledger; when it returns `stop: true`, stop gathering and synthesize with what you have. Say what you sampled.\n\n### 3. Compress the context (when sources are long)\n- When the fetched text for a sub-question is large, run `\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" deep-research compress -- --input <payload.json>` with `{query:<sub-question>, sources:[{id,url,title,text}]}` to drop boilerplate/duplicate passages and keep the most relevant text within a char budget before you synthesize. Read from `data.kept`; small inputs pass through unchanged.\n- `compress` ranks by keyword overlap, which misses passages that are on-topic but worded differently. When wording varies (synonyms/paraphrase), pass the compressed `kept` passages to the `research_rerank` tool `{query:<sub-question>, passages:[{text,id,url,title}]}` to reorder them by semantic (embedding) similarity, then keep its top-ranked ones. It returns `ranked:[{index, score}]` — map back to your passages by `index`.\n\n### 4. Draft claims with citations\n- Write the key findings as claims. For each claim attach one or more citations `{source, quote, doi?}` where `quote` is an EXACT span copied from that source's fetched text. Do not paraphrase inside a quote.\n\n### 5. Verify before you deliver (deterministic guardrail)\n- Build a payload `{sources:[…], claims:[…]}` and run:\n `\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" deep-research citations -- --op verify --input <payload.json>`\n- Read the result: if `abstain` is true (no sources), tell the user you could not gather source material rather than writing a report. For every entry in `flags` (invented quote, malformed/unresolvable DOI, phantom source), FIX it — recheck the source, correct or drop the citation, or soften the claim — then re-run. Do not ship a report with unresolved flags.\n\n### 6. Deliver\n- Write the report from the verified claims only. Use the returned `references` for a numbered reference list, and cite inline by ref number.\n- State per-conclusion confidence, call out contradictions between sources, and list what remained unverified or not found. Close with suggested next research steps.\n\nBoundaries: escalate to the appropriate entry when the task is really knowledge-base capture (write to notes/Notion/Obsidian), social-media scraping/metrics, or office-document production — those are other agents' jobs, not this one.",
- "created_at": "2026-07-02T00:00:00",
- "updated_at": "2026-07-03T00:00:00",
- "category": "data",
- "runtime": {
- "kind": "in_process"
- },
- "interactive": true,
- "output_format": "text",
- "skill_list": [
- "ee99fbb42964"
- ],
- "inputs": [
- {
- "id": "task",
- "label": "Research task",
- "type": "text",
- "required": true,
- "default": "",
- "description": "Research question or objective."
- },
- {
- "id": "materials",
- "label": "Reference materials (optional)",
- "type": "file",
- "required": false,
- "default": "",
- "description": "Relevant files or links to use as first-hand research sources."
- }
- ]
-}
diff --git a/resources/builtin/marketplace/agents/e064dca9e1bd/agent.json b/resources/builtin/marketplace/agents/e064dca9e1bd/agent.json
index 8b232ff2..6c8d201f 100644
--- a/resources/builtin/marketplace/agents/e064dca9e1bd/agent.json
+++ b/resources/builtin/marketplace/agents/e064dca9e1bd/agent.json
@@ -1,12 +1,12 @@
{
"agent_id": "e064dca9e1bd",
- "version": "1.0.1",
+ "version": "1.0.2",
"name": "SeoGeoAgent",
"description_zh": "SEO/GEO 诊断与优化:给一个 URL,抓取+技术审计+内容质量+结构化数据+核心网页指标(CWV)+GEO 可引用性评分,出健康分、分级行动清单、可视化看板;能持续监控漂移、在拿到本地仓库时直接改代码并复测、按 GEO 模式写/优化内容;适合“诊断一下 orkas.ai 的 SEO”“帮我修一下这个页面的 SEO 问题”“监控这页有没有退步”“给这页写一段答案前置的内容”;触发词:SEO、GEO、诊断、优化、技术审计、内容质量、可引用性、核心网页指标、CWV、健康分、收录、结构化数据、监控、改代码、AI 可见性",
"description_en": "SEO/GEO diagnosis and optimization: given a URL, crawl + audit technical SEO, content quality, structured data, Core Web Vitals and GEO citability, and deliver a health score, tiered action plan and dashboard; can monitor for drift, edit source code and re-test when given a local repo, and write/optimize GEO content; For: ‘diagnose the SEO of orkas.ai’, ‘fix this page’s SEO issues’, ‘monitor this page for regressions’, ‘write answer-first content for this page’; Triggers: SEO, GEO, audit, diagnose, optimize, content, citability, Core Web Vitals, CWV, health score, indexing, structured data, monitor, edit code, AI visibility",
"workflow": "You are the SEO/GEO Agent. You diagnose on-page SEO/GEO, can edit source to fix issues (only with a local repo), write/optimize content, and monitor for regressions. Be honest about scope: findings are Measured/Estimated from live fetches; GEO scoring is on-page readiness, not proof of AI citation; you have no rank/traffic/competitor data unless the user supplies it, OR a Google Search Console (`gsearch-console`) or Bing Webmaster (`bing-webmaster`) connector is connected — then real clicks/impressions/position for the user's own verified property become available as Measured data (the Bing index also powers ChatGPT/Copilot, so Bing doubles as a GEO signal). Canonical domains are apex only (https://orkas.ai / https://orkas.work). Never git commit/push or publish without explicit confirmation.\n\n### 0. Pick the mode (from the user's intent + inputs)\n- DIAGNOSE (default — runs DEEP, end to end): ‘diagnose / audit / check the SEO/GEO of <url>’ — a URL. Runs the full picture in one go: on-page chain + keyword opportunity pool + AI-visibility probe + multi-page. No confirmation gate — the cost is just a handful of model calls on the user's own provider/keys (no paid SEO API), so run it straight through.\n- QUICK DIAGNOSE: ‘quick / 快速 / on-page only / 只看本页 / seo-only’ — only the free single-page on-page chain plus an Estimated keyword opportunity pool; no probe, no multi-page.\n- MONITOR: ‘monitor / what changed / re-check’, or a scheduled auto-task dispatch — compares against a saved baseline.\n- APPLY: ‘fix / apply / 改一下’ AND a local repo path (`repo_path` or in the message) — edits source there and re-tests.\n- CONTENT: ‘write / optimize / rewrite content / 写/优化文案’ — produces or improves a draft.\nRun only the matching mode; when unsure, DIAGNOSE and offer the others. ‘seo-only’/‘geo-only’ just narrows which findings you emphasize.\n\n### A. DIAGNOSE — pipeline (one bash command; a temp dir chains the deterministic skills, the last line prints the report envelope)\n```\nP=$(mktemp -d) && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-crawl crawl -- \"<url>\" --out \"$P/crawl.json\" >/dev/null && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-tech-audit audit -- --input \"$P/crawl.json\" --out \"$P/tech.json\" >/dev/null && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-content content -- --input \"$P/crawl.json\" --out \"$P/content.json\" >/dev/null && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-schema schema -- --op validate --input \"$P/crawl.json\" --out \"$P/schema.json\" >/dev/null && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" geo-score geo_score -- --input \"$P/crawl.json\" --out \"$P/geo.json\" >/dev/null && \\\n( \"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-cwv cwv -- \"<url>\" --out \"$P/cwv.json\" >/dev/null 2>&1 || true ) && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-opportunity opportunity -- --crawl \"$P/crawl.json\" --out \"$P/opportunities.json\" >/dev/null && \\\n\"$ORKAS_NODE\" \"$ORKAS_PC_DIR/bin/run-skill.cjs\" seo-report report -- --audit \"$P/tech.json\" --add \"$P/content.json\" --add \"$P/schema.json\" --add \"$P/cwv.json\" --geo \"$P/geo.json\" --crawl \"$P/crawl.json\" --opportunities \"$P/opportunities.json\"\n```\n(Keep `$P` — later modes reuse `$P/crawl.json`, `$P/geo.json`, scores.) `seo-cwv` (Core Web Vitals via PageSpeed) is OPTIONAL and non-fatal: keyless PageSpeed is rate-limited (HTTP 429), so it may write nothing — the report tolerates a missing `cwv.json`. For reliable CWV, set the `ORKAS_PAGESPEED_KEY` env (free key). If the core chain errors or the crawl prints `{\"ok\": false, ...}` (blocked/non-public host, network/proxy, too many redirects), explain plainly and stop — never fabricate a report.\n1. Emit the `dashboard` object verbatim inside one `:::dashboard` … `:::` fence.\n2. `write_file` the `action_plan_md` to `ACTION-PLAN.md`.\n3. Summarize in 2–4 lines: SEO health, GEO score, # critical/high, top keyword/GEO opportunity, and the top 1–3 fixes. Be honest that the GEO score is ON-PAGE citation-readiness, NOT measured AI visibility — a clean page near-always scores high, which is not evidence AI engines actually cite you.\n4. DIAGNOSE defaults to DEEP and runs end to end — do NOT stop at the single clean page, and do NOT ask for confirmation (the cost is a handful of model calls on the user's own keys; no paid SEO API). After the on-page dashboard, immediately run §E (AI-visibility probe — comparative share-of-voice vs 2–4 competitors) and the multi-page pass below, then fold share-of-voice, keyword opportunities, per-page health/GEO and coverage gaps into the `:::dashboard` + `ACTION-PLAN.md`. Only QUICK DIAGNOSE (the user says ‘quick’ / ‘on-page only’) stops at the on-page result.\n- Multi-page (DEEP): from `$P/crawl.json`'s robots/declared sitemaps, sample ~5–10 representative pages across sections (home + a blog post + a /compare/* + a /use/* + docs + marketplace), run the crawl→audit chain per page, and aggregate — per-page health/GEO plus coverage gaps (target intents with no dedicated page). Bound the count and state what you sampled; never silently audit only the homepage when the user asked about the site.\n- Search consoles (DEEP, if connected): for EACH console the `## Connectors` block lists — `gsearch-console` and/or `bing-webmaster` — pull its real performance; do NOT stop after the first, and if both are listed you MUST query both (they are separate properties — a site can have data in one and not the other). Per console: `list_connector_tools` then `call_connector_tool` `list_sites` to pick the property that owns the site, then GSC → `query_search_analytics` grouped by query and by page and write raw rows to `$P/gsc-query.json` / `$P/gsc-page.json`; Bing → `query_keyword_stats` + `query_page_stats` and write raw rows to `$P/bing-query.json` / `$P/bing-page.json`. Use them to upgrade traffic/keyword/position findings from Estimated to Measured, surface quick-wins (high-impression, low-CTR, position 8–20), and reconcile your declared target queries against what each engine actually shows the site for. Bing coverage is the closest free proxy for AI-engine (ChatGPT/Copilot) visibility, so weak Bing presence is a real GEO gap. Say plainly for any console that is not connected — those findings stay Estimated.\n\n### B. MONITOR\n- Re-run the DIAGNOSE pipeline (fresh crawl + scores).\n- GSC (if connected): if the `## Connectors` block lists `gsearch-console`, capture real Search Console performance for THIS url so drift can track it. Call `list_connector_tools({connector_id:\"gsearch-console\"})` once for the schema, then `call_connector_tool` `list_sites` → pick the property that owns the url (`sc-domain:<host>` or `https://<host>/`), then `call_connector_tool` `query_search_analytics` with args `{siteUrl, dimensions:[\"date\"], dimensionFilter:{dimension:\"page\",operator:\"equals\",expression:\"<url>\"}, rowLimit:1000}` for the last 28 days, and `write_file` the raw result to `$P/gsc.json`. Skip silently (no error; note \"no GSC data\") if gsearch-console is absent, the account does not own the property, or it errors.\n- Bing (if connected): if the `## Connectors` block lists `bing-webmaster`, capture Bing performance for THIS url too — `list_connector_tools({connector_id:\"bing-webmaster\"})`, then `call_connector_tool` `list_sites` → pick the property that owns the url, then `query_page_stats` and keep ONLY the row whose page matches the url (Bing has no per-page filter param), `write_file` that to `$P/bing.json`. Skip silently (note \"no Bing data\") if bing-webmaster is absent, not the owner, returns no row for the url, or errors.\n- Snapshot: `seo-monitor monitor -- --op snapshot --input \"$P/crawl.json\" --health <H> --geo <G> --gsc \"$P/gsc.json\" --bing \"$P/bing.json\" --out \"$P/current.json\"` (omit `--gsc`/`--bing` for any source you have no data from).\n- If a baseline exists (the project's `baseline.json`): `seo-monitor monitor -- --op compare --baseline baseline.json --current \"$P/current.json\"` — this now also drifts real search performance (Measured) when both snapshots carry it: GSC clicks/impressions/average position, plus Bing clicks/impressions (Bing counts only — its avg-position scale isn't drift-tracked). Reconcile against the prior ACTION-PLAN's leading indicators — a TODO whose leading indicator is now met → mark it done; a new regression → add a TODO.\n- Present a dashboard (health/GEO Metric, a GSC and/or Bing Metric for clicks/impressions/position when available, a drift Table, and an Alert for any regression) and update `ACTION-PLAN.md`. Then refresh the baseline (`snapshot ... --gsc \"$P/gsc.json\" --bing \"$P/bing.json\" --out baseline.json` — include whichever sources you captured). If there was no baseline, set it and say so.\n\n### C. APPLY — only with a local repo path (edits stay under that path)\n- DIAGNOSE first (or reuse a recent ACTION-PLAN) to get the prioritized fixes.\n- For each source-fixable item (title/meta/canonical/hreflang/img alt/headings/`robots.txt`/`sitemap.xml`/`llms.txt`/JSON-LD via `seo-schema --op generate`):\n 1. `read_file` the target, prepare the edit.\n 2. Show a short diff summary + which TODO + its leading indicator, and ASK for confirmation (unless the user authorized batch edits). Apex domains only.\n 3. On approval, `edit_file`/`write_file` (path-sandbox: only under the repo path). Append one line to `changelog.jsonl`: `{ts, file, todo_id, change, leading_indicator}`.\n 4. Re-test: `seo-crawl crawl -- --file <edited file>` (or the localhost preview URL) → re-run the audits → confirm the finding cleared.\n- Never git commit/push or publish. Summarize what changed and what to verify.\n\n### D. CONTENT — draft only (publishing is APPLY + confirmation)\n- Brief: from the target query/topic + `seo-content` gaps + the page data, write a brief (target query, intent, outline, entities to cover, the answer-first opening).\n- Write/rewrite with your own model + `web_search` for facts (cite sources). Front-load a direct answer, use short quotable chunks, add FAQ/structured data via `seo-schema --op generate` (JSON-LD must match the visible text 1:1).\n- Self-check the draft with `seo-content` (and `seo-schema --op validate` on a rendered draft via `seo-crawl --file`). Iterate once.\n- Deliver as a DRAFT. Do not auto-publish; writing it into the site/CMS is APPLY mode and needs explicit confirmation.\n\n### E. AI-visibility probe — the GEO differentiator (the DEEP default runs it automatically, end to end; QUICK DIAGNOSE skips it). This is the real-visibility measurement a clean on-page score cannot give.\n- Bound the query set to ~10–15 and cache results, since each answer costs a model call.\n- `geo-probe geo_probe -- --op queries --input \"$P/crawl.json\"` → queries + derived brand/domain. Name 2–4 competitors (e.g. Cline, Claude Desktop, OpenClaw, Devin, n8n) so share-of-voice is comparative.\n- Ask each query to your own model (and/or `web_search` for a retrieval-grounded answer), recording `{query, model, mode:\"param\"|\"retrieval\", text}`; pipe the payload to `geo-probe geo_probe -- --op score` and write it to `$P/geo-probe.json`.\n- After console pulls and GEO scoring, run `seo-opportunity opportunity -- --crawl \"$P/crawl.json\" --gsc \"$P/gsc-query.json\" --gsc-pages \"$P/gsc-page.json\" --bing \"$P/bing-query.json\" --bing-pages \"$P/bing-page.json\" --geo-probe \"$P/geo-probe.json\" --out \"$P/opportunities.json\"` (omit missing optional files), then rerun `seo-report report ... --opportunities \"$P/opportunities.json\" --geo-probe \"$P/geo-probe.json\"` for the final dashboard/ACTION-PLAN.\n- Report share-of-voice + citation rate honestly: a parametric-memory mention is weaker than a sourced citation, and the tier is Measured only when every answer came from a retrieval-capable model.",
"created_at": "2026-06-24T15:00:00",
- "updated_at": "2026-06-26T00:00:00",
+ "updated_at": "2026-07-04T00:00:00",
"knowhow": [
"Audits public URLs across technical SEO, content quality, structured data, Core Web Vitals, and GEO citation readiness.",
"Turns crawl and console data into measured or estimated findings with health scores, dashboards, and prioritized action plans.",
diff --git a/resources/builtin/marketplace/skills/6743aa0797a2/_meta.json b/resources/builtin/marketplace/skills/6743aa0797a2/_meta.json
new file mode 100644
index 00000000..0b5174b9
--- /dev/null
+++ b/resources/builtin/marketplace/skills/6743aa0797a2/_meta.json
@@ -0,0 +1,4 @@
+{
+ "version": "1.0.1",
+ "updated_at": "2026-07-04T00:00:00"
+}
diff --git a/resources/builtin/marketplace/skills/9be6fda271a5/_meta.json b/resources/builtin/marketplace/skills/9be6fda271a5/_meta.json
new file mode 100644
index 00000000..0b5174b9
--- /dev/null
+++ b/resources/builtin/marketplace/skills/9be6fda271a5/_meta.json
@@ -0,0 +1,4 @@
+{
+ "version": "1.0.1",
+ "updated_at": "2026-07-04T00:00:00"
+}
diff --git a/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json b/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json
index 4cd680c1..1eec1966 100644
--- a/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json
+++ b/resources/builtin/marketplace/skills/ee99fbb42964/_meta.json
@@ -1,4 +1,5 @@
{
- "version": "1.0.2",
+ "version": "1.0.3",
+ "updated_at": "2026-07-04T00:00:00",
"reseed_if_deleted_before": "2026-07-03T00:00:00Z"
}
diff --git a/scripts/codesign-adhoc.cjs b/scripts/codesign-adhoc.cjs
index 99af3596..4780c77b 100644
--- a/scripts/codesign-adhoc.cjs
+++ b/scripts/codesign-adhoc.cjs
@@ -101,9 +101,11 @@ function targetSqliteVecPackage(targetPlatform, targetArch) {
function pruneSqliteVecPackages(nodeModules, targetPlatform, targetArch) {
const keepPackage = targetSqliteVecPackage(targetPlatform, targetArch);
- for (const dirName of listDirs(nodeModules)) {
- if (/^sqlite-vec-(darwin|linux|windows)-/i.test(dirName) && dirName !== keepPackage) {
- removeIfExists(path.join(nodeModules, dirName));
+ for (const parentDir of sqliteVecPackageParentDirs(nodeModules)) {
+ for (const dirName of listDirs(parentDir)) {
+ if (/^sqlite-vec-(darwin|linux|windows)-/i.test(dirName) && dirName !== keepPackage) {
+ removeIfExists(path.join(parentDir, dirName));
+ }
}
}
}
@@ -118,11 +120,12 @@ function targetCanvasPackage(targetPlatform, targetArch) {
}
function pruneCanvasPackages(nodeModules, targetPlatform, targetArch) {
- const napiDir = path.join(nodeModules, '@napi-rs');
const keepPackage = targetCanvasPackage(targetPlatform, targetArch);
- for (const dirName of listDirs(napiDir)) {
- if (/^canvas-/i.test(dirName) && dirName !== keepPackage) {
- removeIfExists(path.join(napiDir, dirName));
+ for (const parentDir of canvasPackageParentDirs(nodeModules)) {
+ for (const dirName of listDirs(parentDir)) {
+ if (/^canvas-/i.test(dirName) && dirName !== keepPackage) {
+ removeIfExists(path.join(parentDir, dirName));
+ }
}
}
}
@@ -134,11 +137,12 @@ function targetTokenizersPackage(targetPlatform, targetArch) {
}
function pruneTokenizersPackages(nodeModules, targetPlatform, targetArch) {
- const tokenizersDir = path.join(nodeModules, '@anush008');
const keepPackage = targetTokenizersPackage(targetPlatform, targetArch);
- for (const dirName of listDirs(tokenizersDir)) {
- if (/^tokenizers-/i.test(dirName) && dirName !== keepPackage) {
- removeIfExists(path.join(tokenizersDir, dirName));
+ for (const parentDir of tokenizersPackageParentDirs(nodeModules)) {
+ for (const dirName of listDirs(parentDir)) {
+ if (/^tokenizers-/i.test(dirName) && dirName !== keepPackage) {
+ removeIfExists(path.join(parentDir, dirName));
+ }
}
}
}
@@ -147,6 +151,57 @@ function packageDir(nodeModules, packageName) {
return path.join(nodeModules, ...packageName.split('/'));
}
+function sqliteVecPackageParentDirs(nodeModules) {
+ return [
+ nodeModules,
+ path.join(nodeModules, 'sqlite-vec', 'node_modules'),
+ ];
+}
+
+function sqliteVecPackageDir(nodeModules, packageName) {
+ for (const parentDir of sqliteVecPackageParentDirs(nodeModules)) {
+ const candidate = path.join(parentDir, packageName);
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
+ return candidate;
+ }
+ }
+ return path.join(nodeModules, packageName);
+}
+
+function canvasPackageParentDirs(nodeModules) {
+ return [
+ path.join(nodeModules, '@napi-rs'),
+ path.join(nodeModules, '@napi-rs', 'canvas', 'node_modules', '@napi-rs'),
+ ];
+}
+
+function canvasPackageDir(nodeModules, packageName) {
+ for (const parentDir of canvasPackageParentDirs(nodeModules)) {
+ const candidate = path.join(parentDir, packageName);
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
+ return candidate;
+ }
+ }
+ return path.join(nodeModules, '@napi-rs', packageName);
+}
+
+function tokenizersPackageParentDirs(nodeModules) {
+ return [
+ path.join(nodeModules, '@anush008'),
+ path.join(nodeModules, '@anush008', 'tokenizers', 'node_modules', '@anush008'),
+ ];
+}
+
+function tokenizersPackageDir(nodeModules, packageName) {
+ for (const parentDir of tokenizersPackageParentDirs(nodeModules)) {
+ const candidate = path.join(parentDir, packageName);
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
+ return candidate;
+ }
+ }
+ return path.join(nodeModules, '@anush008', packageName);
+}
+
function requireOnlyPackages(parentDir, pattern, allowedPackages) {
const allowed = new Set(allowedPackages.filter(Boolean));
for (const dirName of listDirs(parentDir)) {
@@ -195,8 +250,11 @@ function verifyPackedNativePayload(nodeModules, targetPlatform, targetArch) {
requireOnlyPackages(path.join(nodeModules, '@esbuild'), /^.+$/, [esbuildPackage]);
requireOnlyPackages(nodeModules, /^sqlite-vec-(darwin|linux|windows)-/i, [sqlitePackage]);
+ requireOnlyPackages(path.join(nodeModules, 'sqlite-vec', 'node_modules'), /^sqlite-vec-(darwin|linux|windows)-/i, [sqlitePackage]);
requireOnlyPackages(path.join(nodeModules, '@napi-rs'), /^canvas-/i, [canvasPackage]);
+ requireOnlyPackages(path.join(nodeModules, '@napi-rs', 'canvas', 'node_modules', '@napi-rs'), /^canvas-/i, [canvasPackage]);
requireOnlyPackages(path.join(nodeModules, '@anush008'), /^tokenizers-/i, [tokenizersPackage]);
+ requireOnlyPackages(path.join(nodeModules, '@anush008', 'tokenizers', 'node_modules', '@anush008'), /^tokenizers-/i, [tokenizersPackage]);
if (targetPlatform !== 'darwin' && fs.existsSync(path.join(nodeModules, 'fsevents'))) {
throw new Error('[native-deps-gate] fsevents must not be included in non-macOS packages');
@@ -209,15 +267,15 @@ function verifyPackedNativePayload(nodeModules, targetPlatform, targetArch) {
);
requiredFile(
`${sqlitePackage} binary`,
- path.join(packageDir(nodeModules, sqlitePackage), 'vec0.dylib'),
+ path.join(sqliteVecPackageDir(nodeModules, sqlitePackage), 'vec0.dylib'),
);
requiredFile(
`${canvasPackage} binary`,
- path.join(packageDir(nodeModules, `@napi-rs/${canvasPackage}`), `skia.darwin-${targetArch}.node`),
+ path.join(canvasPackageDir(nodeModules, canvasPackage), `skia.darwin-${targetArch}.node`),
);
requiredFile(
`${tokenizersPackage} binary`,
- path.join(packageDir(nodeModules, `@anush008/${tokenizersPackage}`), 'tokenizers.darwin-universal.node'),
+ path.join(tokenizersPackageDir(nodeModules, tokenizersPackage), 'tokenizers.darwin-universal.node'),
);
} else if (targetPlatform === 'win32') {
requiredFile(
@@ -226,15 +284,15 @@ function verifyPackedNativePayload(nodeModules, targetPlatform, targetArch) {
);
requiredFile(
`${sqlitePackage} binary`,
- path.join(packageDir(nodeModules, sqlitePackage), 'vec0.dll'),
+ path.join(sqliteVecPackageDir(nodeModules, sqlitePackage), 'vec0.dll'),
);
requiredFile(
`${canvasPackage} binary`,
- path.join(packageDir(nodeModules, `@napi-rs/${canvasPackage}`), 'skia.win32-x64-msvc.node'),
+ path.join(canvasPackageDir(nodeModules, canvasPackage), 'skia.win32-x64-msvc.node'),
);
requiredFile(
`${tokenizersPackage} binary`,
- path.join(packageDir(nodeModules, `@anush008/${tokenizersPackage}`), 'tokenizers.win32-x64-msvc.node'),
+ path.join(tokenizersPackageDir(nodeModules, tokenizersPackage), 'tokenizers.win32-x64-msvc.node'),
);
}
@@ -244,9 +302,9 @@ function verifyPackedNativePayload(nodeModules, targetPlatform, targetArch) {
);
verifyPackageVersion(nodeModules, lock, `@esbuild/${esbuildPackage}`, verified);
- verifyPackageVersion(nodeModules, lock, sqlitePackage, verified);
- verifyPackageVersion(nodeModules, lock, `@napi-rs/${canvasPackage}`, verified);
- verifyPackageVersion(nodeModules, lock, `@anush008/${tokenizersPackage}`, verified);
+ verifyPackageVersionAtDir(sqliteVecPackageDir(nodeModules, sqlitePackage), lock, sqlitePackage, verified);
+ verifyPackageVersionAtDir(canvasPackageDir(nodeModules, canvasPackage), lock, `@napi-rs/${canvasPackage}`, verified);
+ verifyPackageVersionAtDir(tokenizersPackageDir(nodeModules, tokenizersPackage), lock, `@anush008/${tokenizersPackage}`, verified);
verifyPackageVersion(nodeModules, lock, 'better-sqlite3', verified);
for (const pkgDir of [
path.join(nodeModules, 'onnxruntime-node'),
@@ -347,7 +405,11 @@ function packageJsonPath(nodeModules, packageName) {
}
function verifyPackageVersion(nodeModules, lock, packageName, verified, lockPath = packageLockEntryPath(packageName)) {
- const pkg = readJsonFile(`${packageName} package.json`, packageJsonPath(nodeModules, packageName));
+ verifyPackageVersionAtDir(packageDir(nodeModules, packageName), lock, packageName, verified, lockPath);
+}
+
+function verifyPackageVersionAtDir(pkgDir, lock, packageName, verified, lockPath = packageLockEntryPath(packageName)) {
+ const pkg = readJsonFile(`${packageName} package.json`, path.join(pkgDir, 'package.json'));
const expected = lockPackageVersion(lock, packageName, lockPath);
if (String(pkg.version || '') !== String(expected)) {
throw new Error(`[native-deps-gate] ${packageName} version mismatch: packaged=${pkg.version || '(missing)'} lock=${expected}`);
diff --git a/src/core-agent/src/agent/persistent-session.ts b/src/core-agent/src/agent/persistent-session.ts
index e8d33d9f..2a85fc20 100644
--- a/src/core-agent/src/agent/persistent-session.ts
+++ b/src/core-agent/src/agent/persistent-session.ts
@@ -6,7 +6,7 @@ import type {
ToolResultContent,
ToolUseContent,
} from "../shared/types.js";
-import { Session } from "./session.js";
+import { Session, type ToolResultCompactionOptions } from "./session.js";
/** Synthetic content written when a prior run aborted after the model
* issued a tool_use but before the tool produced a tool_result. Both
@@ -41,8 +41,13 @@ export class PersistentSession extends Session {
sessionFile: string;
/** Per-parent-class option: cap on how many turns stay in memory. */
maxHistoryTurns?: number;
+ /** Optional LLM-facing tool_result compaction. Raw JSONL history stays intact. */
+ toolResultCompaction?: ToolResultCompactionOptions | false;
}) {
- super({ maxHistoryTurns: opts.maxHistoryTurns });
+ super({
+ maxHistoryTurns: opts.maxHistoryTurns,
+ toolResultCompaction: opts.toolResultCompaction,
+ });
this.sessionFile = opts.sessionFile;
this.loadFromDisk();
}
diff --git a/src/core-agent/src/agent/runner.ts b/src/core-agent/src/agent/runner.ts
index 45385d7b..dd32a6c1 100644
--- a/src/core-agent/src/agent/runner.ts
+++ b/src/core-agent/src/agent/runner.ts
@@ -790,7 +790,7 @@ export class AgentRunner {
// fills (PC: buildRunner from the resolved model); only an unknown model
// hits the 200K fallback. ContextOverflowError (caught below) still
// recovers if a single turn blows past the threshold.
- const tokensBefore = this.session.estimateTokens();
+ const tokensBefore = this.session.estimateModelTokens();
// Look the window up by the model the stream ACTUALLY used: rotating-
// provider can fail over to a different-window candidate mid-run, and the
// host fills the catalog for every candidate (PC buildRunner). Fall back
@@ -809,7 +809,7 @@ export class AgentRunner {
// summary). Skip that no-progress pass; later turns push the big
// result out of the kept window and real compaction resumes (and a
// genuine overflow is still caught by ContextOverflowError below).
- const keptTailTokens = this.session.estimateKeptTailTokens();
+ const keptTailTokens = Math.min(this.session.estimateKeptTailTokens(), tokensBefore);
const wouldFree = tokensBefore - keptTailTokens;
if (wouldFree > contextWindow * MIN_COMPACTION_SAVINGS_RATIO) {
log.info(`Context nearing limit (${tokensBefore}/${contextWindow}), compacting...`);
@@ -818,7 +818,7 @@ export class AgentRunner {
yield {
type: "compaction",
tokensBefore,
- tokensAfter: this.session.estimateTokens(),
+ tokensAfter: this.session.estimateModelTokens(),
summary: compactSummary || undefined,
};
} else {
@@ -865,13 +865,13 @@ export class AgentRunner {
if (err instanceof ContextOverflowError) {
// Try compaction
try {
- const tokensBefore = this.session.estimateTokens();
+ const tokensBefore = this.session.estimateModelTokens();
const overflowSummary = await this.compactSession(provider, modelId, systemPrompt, params.cacheRetention);
compactionCount++;
yield {
type: "compaction",
tokensBefore,
- tokensAfter: this.session.estimateTokens(),
+ tokensAfter: this.session.estimateModelTokens(),
summary: overflowSummary || undefined,
};
continue;
diff --git a/src/core-agent/src/agent/session.ts b/src/core-agent/src/agent/session.ts
index 9bc70593..fa8ee575 100644
--- a/src/core-agent/src/agent/session.ts
+++ b/src/core-agent/src/agent/session.ts
@@ -1,6 +1,68 @@
import type { ImageContent, Message, MessageContent, Usage } from "../shared/types.js";
import type { ToolResultImage } from "../tools/base.js";
+export type ToolResultCompactionOptions = {
+ /** Minimum content length before an old tool_result is compacted. */
+ minChars?: number;
+ /** Total tool_result characters before old smaller results are compacted. */
+ aggregateMinChars?: number;
+ /** Minimum individual result length for aggregate-mode compaction. */
+ aggregateMinResultChars?: number;
+ /** Preview characters kept for aggregate-mode compacted results. */
+ aggregatePreviewChars?: number;
+ /** Keep tool results from the latest N assistant steps verbatim. */
+ keepRecentAssistantSteps?: number;
+ /** Always keep the newest N tool_result blocks verbatim. */
+ keepRecentToolResults?: number;
+ /** Preview characters from the beginning of a compacted result. */
+ previewHeadChars?: number;
+ /** Preview characters from the end of a compacted result. */
+ previewTailChars?: number;
+ /** Minimum serialized input length before an old tool_use input is compacted. */
+ toolUseInputMinChars?: number;
+ /** Total tool_use input characters before old smaller inputs are compacted. */
+ toolUseInputAggregateMinChars?: number;
+ /** Minimum individual input length for aggregate-mode tool_use compaction. */
+ toolUseInputAggregateMinInputChars?: number;
+ /** Long string fields above this size are replaced with a head/tail preview. */
+ toolUseInputStringMinChars?: number;
+ /** Total preview characters kept inside each compacted long string field. */
+ toolUseInputPreviewChars?: number;
+ /** Always keep the newest N tool_use blocks verbatim. */
+ keepRecentToolUses?: number;
+ /** Optional sync persistence hook. Returning a path makes the compacted view re-readable. */
+ persistToolResult?: (info: {
+ toolName: string;
+ toolUseId: string;
+ content: string;
+ isError?: boolean;
+ }) => string | undefined;
+};
+
+type NormalizedToolResultCompactionOptions = Required<
+ Omit<ToolResultCompactionOptions, "persistToolResult">
+> & Pick<ToolResultCompactionOptions, "persistToolResult">;
+
+const DEFAULT_TOOL_RESULT_COMPACTION: NormalizedToolResultCompactionOptions = {
+ minChars: 8 * 1024,
+ aggregateMinChars: 16 * 1024,
+ aggregateMinResultChars: 768,
+ aggregatePreviewChars: 80,
+ keepRecentAssistantSteps: 1,
+ keepRecentToolResults: 2,
+ previewHeadChars: 800,
+ previewTailChars: 400,
+ toolUseInputMinChars: 8 * 1024,
+ toolUseInputAggregateMinChars: 16 * 1024,
+ toolUseInputAggregateMinInputChars: 768,
+ toolUseInputStringMinChars: 240,
+ toolUseInputPreviewChars: 160,
+ keepRecentToolUses: 2,
+};
+
+type ToolResultCompactionMode = "full-preview" | "aggregate-ref";
+type ToolUseInputCompactionMode = "full-preview" | "aggregate-ref";
+
/**
* Session manages the conversation history for an agent run.
*
@@ -10,9 +72,17 @@ import type { ToolResultImage } from "../tools/base.js";
export class Session {
private messages: Message[] = [];
private readonly maxHistoryTurns: number;
+ private readonly toolResultCompaction: NormalizedToolResultCompactionOptions | null;
+ private readonly compactedToolResultRefs = new Map<string, string>();
- constructor(opts?: { maxHistoryTurns?: number }) {
- this.maxHistoryTurns = opts?.maxHistoryTurns ?? 100;
+ constructor(opts?: {
+ maxHistoryTurns?: number;
+ toolResultCompaction?: ToolResultCompactionOptions | false;
+ }) {
+ this.maxHistoryTurns = opts?.maxHistoryTurns ?? 50;
+ this.toolResultCompaction = opts?.toolResultCompaction
+ ? { ...DEFAULT_TOOL_RESULT_COMPACTION, ...opts.toolResultCompaction }
+ : null;
}
/** Add a message to the session. */
@@ -79,18 +149,91 @@ export class Session {
}
}
+ const assistantStepsAfter = this.computeAssistantStepsAfter();
+ const toolNameById = this.computeToolNameById();
+ const toolResultStats = this.computeToolResultStats();
+ const totalToolResults = toolResultStats.count;
+ const toolUseInputStats = this.computeToolUseInputStats();
+ const totalToolUses = toolUseInputStats.count;
+ let toolResultOrdinal = 0;
+ let toolUseOrdinal = 0;
+
const result: Message[] = [];
for (let i = 0; i < this.messages.length; i++) {
const msg = this.messages[i];
const includeImages = i > lastAssistantIndex;
- const content = includeImages
- ? [...msg.content]
- : msg.content.filter((c) => c.type !== "image");
+ const content: MessageContent[] = [];
+ for (const c of msg.content) {
+ if (!includeImages && c.type === "image") continue;
+ if (c.type === "tool_use") {
+ const rawInputJson = stringifyToolInput(c.input);
+ const ordinal = toolUseOrdinal++;
+ const mode = this.toolUseInputCompactionMode(
+ c,
+ i,
+ ordinal,
+ totalToolUses,
+ rawInputJson.length,
+ toolUseInputStats.chars,
+ assistantStepsAfter,
+ );
+ if (mode) {
+ const compactedInput = this.compactToolUseInput(
+ c.name,
+ c.input,
+ rawInputJson,
+ mode,
+ );
+ content.push({
+ ...c,
+ input: stringifyToolInput(compactedInput).length < rawInputJson.length
+ ? compactedInput
+ : c.input,
+ });
+ } else {
+ content.push(c);
+ }
+ continue;
+ }
+ if (c.type !== "tool_result") {
+ content.push(c);
+ continue;
+ }
+ const ordinal = toolResultOrdinal++;
+ const mode = this.toolResultCompactionMode(
+ c,
+ i,
+ ordinal,
+ totalToolResults,
+ toolResultStats.chars,
+ assistantStepsAfter,
+ );
+ if (mode) {
+ const compactedContent = this.compactToolResultContent(
+ c.toolUseId,
+ toolNameById.get(c.toolUseId) || "tool_result",
+ c.content,
+ c.isError,
+ mode,
+ );
+ content.push({
+ ...c,
+ content: compactedContent.length < c.content.length ? compactedContent : c.content,
+ });
+ } else {
+ content.push(c);
+ }
+ }
if (content.length > 0) result.push({ role: msg.role, content });
}
return result;
}
+ /** Estimate the token count for the same compacted view sent to providers. */
+ estimateModelTokens(): number {
+ return sumMessageTokens(this.getMessagesForModel());
+ }
+
/** Stable session identifier used as `prompt_cache_key`. The base `Session`
* is anonymous (returns undefined); `PersistentSession` overrides this to
* return its jsonl basename. A transient in-memory session (e.g. reflection)
@@ -185,14 +328,324 @@ export class Session {
return sumMessageTokens(this.messages);
}
+ private computeAssistantStepsAfter(): number[] {
+ const out = new Array<number>(this.messages.length);
+ let count = 0;
+ for (let i = this.messages.length - 1; i >= 0; i--) {
+ out[i] = count;
+ if (this.messages[i].role === "assistant") count++;
+ }
+ return out;
+ }
+
+ private computeToolNameById(): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const msg of this.messages) {
+ if (msg.role !== "assistant") continue;
+ for (const c of msg.content) {
+ if (c.type === "tool_use" && c.id) out.set(c.id, c.name);
+ }
+ }
+ return out;
+ }
+
+ private computeToolResultStats(): { count: number; chars: number } {
+ let count = 0;
+ let chars = 0;
+ for (const msg of this.messages) {
+ for (const c of msg.content) {
+ if (c.type === "tool_result") {
+ count++;
+ chars += c.content.length;
+ }
+ }
+ }
+ return { count, chars };
+ }
+
+ private computeToolUseInputStats(): { count: number; chars: number } {
+ let count = 0;
+ let chars = 0;
+ for (const msg of this.messages) {
+ for (const c of msg.content) {
+ if (c.type === "tool_use") {
+ count++;
+ chars += stringifyToolInput(c.input).length;
+ }
+ }
+ }
+ return { count, chars };
+ }
+
+ private toolResultCompactionMode(
+ content: Extract<MessageContent, { type: "tool_result" }>,
+ messageIndex: number,
+ ordinal: number,
+ totalToolResults: number,
+ totalToolResultChars: number,
+ assistantStepsAfter: number[],
+ ): ToolResultCompactionMode | null {
+ const opts = this.toolResultCompaction;
+ if (!opts) return null;
+ const newerToolResults = totalToolResults - ordinal - 1;
+ if (newerToolResults < opts.keepRecentToolResults) return null;
+ if ((assistantStepsAfter[messageIndex] ?? 0) <= opts.keepRecentAssistantSteps) return null;
+ if (content.content.length >= opts.minChars) return "full-preview";
+ if (
+ totalToolResultChars > opts.aggregateMinChars
+ && content.content.length >= opts.aggregateMinResultChars
+ ) {
+ return "aggregate-ref";
+ }
+ return null;
+ }
+
+ private toolUseInputCompactionMode(
+ _content: Extract<MessageContent, { type: "tool_use" }>,
+ messageIndex: number,
+ ordinal: number,
+ totalToolUses: number,
+ inputChars: number,
+ totalToolUseInputChars: number,
+ assistantStepsAfter: number[],
+ ): ToolUseInputCompactionMode | null {
+ const opts = this.toolResultCompaction;
+ if (!opts) return null;
+ const newerToolUses = totalToolUses - ordinal - 1;
+ if (newerToolUses < opts.keepRecentToolUses) return null;
+ if ((assistantStepsAfter[messageIndex] ?? 0) <= opts.keepRecentAssistantSteps) return null;
+ if (inputChars >= opts.toolUseInputMinChars) return "full-preview";
+ if (
+ totalToolUseInputChars > opts.toolUseInputAggregateMinChars
+ && inputChars >= opts.toolUseInputAggregateMinInputChars
+ ) {
+ return "aggregate-ref";
+ }
+ return null;
+ }
+
+ private compactToolUseInput(
+ toolName: string,
+ input: Record<string, unknown>,
+ rawInputJson: string,
+ mode: ToolUseInputCompactionMode,
+ ): Record<string, unknown> {
+ const opts = this.toolResultCompaction;
+ if (!opts) return input;
+
+ const compacted = compactToolUseValue(input, opts, 0);
+ if (!isPlainObject(compacted)) return input;
+
+ const note = (
+ `Old ${toolName} tool input compacted for repeated context; ` +
+ `mode=${mode}, original_json_chars=${rawInputJson.length}. ` +
+ "The tool call already executed; inspect the paired tool_result or current files if more detail is needed."
+ );
+ return { ...compacted, __orkas_context_note: note };
+ }
+
+ private compactToolResultContent(
+ toolUseId: string,
+ toolName: string,
+ content: string,
+ isError?: boolean,
+ mode: ToolResultCompactionMode = "full-preview",
+ ): string {
+ const opts = this.toolResultCompaction;
+ if (!opts) return content;
+
+ const refPath = this.getToolResultRef(toolUseId, toolName, content, isError);
+ if (mode === "aggregate-ref") {
+ const preview = content.slice(0, opts.aggregatePreviewChars).replace(/\s+/g, " ").trim();
+ const previewLine = preview ? `\npreview: ${preview}` : "";
+ const refLine = refPath
+ ? "Use read_file(path) with the path attribute to retrieve the full content."
+ : "Full content remains in session history but was omitted from this model call.";
+ return (
+ `<compacted-tool-result tool="${escapeAttr(toolName)}" call_id="${escapeAttr(toolUseId)}" ` +
+ `status="${isError ? "error" : "success"}" original_size="${content.length}" mode="aggregate"` +
+ `${refPath ? ` path="${escapeAttr(refPath)}"` : ""}>\n` +
+ `[old tool result omitted after total tool_result context exceeded ${opts.aggregateMinChars} chars]` +
+ previewLine +
+ `\n${refLine}\n` +
+ `</compacted-tool-result>`
+ );
+ }
+
+ const head = content.slice(0, opts.previewHeadChars);
+ const tail = content.length > opts.previewHeadChars + opts.previewTailChars
+ ? content.slice(-opts.previewTailChars)
+ : "";
+ const omitted = Math.max(0, content.length - head.length - tail.length);
+ const tailBlock = tail
+ ? `\n\n[... ${omitted} chars omitted ...]\n\npreview_tail:\n${tail}`
+ : "";
+ const refLine = refPath
+ ? `[Full content saved to: ${refPath}. Use read_file(path) to retrieve verbatim.]`
+ : "[Full content remains in session history but was omitted from this model call.]";
+
+ return (
+ `<compacted-tool-result tool="${escapeAttr(toolName)}" call_id="${escapeAttr(toolUseId)}" ` +
+ `status="${isError ? "error" : "success"}" original_size="${content.length}"` +
+ `${refPath ? ` path="${escapeAttr(refPath)}"` : ""}>\n` +
+ `[tool result compacted for repeated context]\n` +
+ `preview_head:\n${head}` +
+ tailBlock +
+ `\n${refLine}\n` +
+ `</compacted-tool-result>`
+ );
+ }
+
+ private getToolResultRef(
+ toolUseId: string,
+ toolName: string,
+ content: string,
+ isError?: boolean,
+ ): string | undefined {
+ const existing = extractPersistedPath(content);
+ if (existing) return existing;
+
+ const cacheKey = `${toolUseId}:${content.length}:${content.slice(0, 64)}:${content.slice(-64)}`;
+ const cached = this.compactedToolResultRefs.get(cacheKey);
+ if (cached) return cached;
+
+ try {
+ const ref = this.toolResultCompaction?.persistToolResult?.({
+ toolName,
+ toolUseId,
+ content,
+ isError,
+ });
+ if (ref) this.compactedToolResultRefs.set(cacheKey, ref);
+ return ref;
+ } catch {
+ return undefined;
+ }
+ }
+
private trimHistory(): void {
// Each user+assistant pair = 1 turn
const turns = Math.floor(this.messages.length / 2);
if (turns <= this.maxHistoryTurns) return;
const excess = turns - this.maxHistoryTurns;
- this.messages = this.messages.slice(excess * 2);
+ const start = this.findSafeTrimStart(excess * 2);
+ this.messages = this.messages.slice(start);
}
+
+ private findSafeTrimStart(start: number): number {
+ let i = start;
+ while (i < this.messages.length) {
+ const msg = this.messages[i];
+ if (isToolResultOnlyMessage(msg) || isImageOnlyMessage(msg)) {
+ i++;
+ continue;
+ }
+ break;
+ }
+ return i;
+ }
+}
+
+function extractPersistedPath(content: string): string | undefined {
+ const attr = /<persisted-output\b[^>]*\bpath="([^"]+)"/.exec(content);
+ if (attr?.[1]) return unescapeAttr(attr[1]);
+ const line = /\[Full content saved to:\s*([^\]]+?)\.\s*Use read_file\(path\)/.exec(content);
+ return line?.[1];
+}
+
+function isToolResultOnlyMessage(msg: Message): boolean {
+ return msg.role === "user" && msg.content.length > 0 && msg.content.every((c) => c.type === "tool_result");
+}
+
+function isImageOnlyMessage(msg: Message): boolean {
+ return msg.role === "user" && msg.content.length > 0 && msg.content.every((c) => c.type === "image");
+}
+
+const TOOL_USE_ARRAY_HEAD_ITEMS = 16;
+const TOOL_USE_ARRAY_TAIL_ITEMS = 4;
+const TOOL_USE_INPUT_MAX_DEPTH = 8;
+
+function compactToolUseValue(
+ value: unknown,
+ opts: NormalizedToolResultCompactionOptions,
+ depth: number,
+): unknown {
+ if (typeof value === "string") return compactToolUseString(value, opts);
+ if (Array.isArray(value)) {
+ if (depth >= TOOL_USE_INPUT_MAX_DEPTH) {
+ return `[old nested tool input array omitted: items=${value.length}]`;
+ }
+ const compactItem = (item: unknown) => compactToolUseValue(item, opts, depth + 1);
+ const keepCount = TOOL_USE_ARRAY_HEAD_ITEMS + TOOL_USE_ARRAY_TAIL_ITEMS;
+ if (value.length <= keepCount + 1) return value.map(compactItem);
+ return [
+ ...value.slice(0, TOOL_USE_ARRAY_HEAD_ITEMS).map(compactItem),
+ { __orkas_omitted_array_items: value.length - keepCount },
+ ...value.slice(-TOOL_USE_ARRAY_TAIL_ITEMS).map(compactItem),
+ ];
+ }
+ if (isPlainObject(value)) {
+ if (depth >= TOOL_USE_INPUT_MAX_DEPTH) {
+ return `[old nested tool input object omitted: keys=${Object.keys(value).length}]`;
+ }
+ const out: Record<string, unknown> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ out[key] = compactToolUseValue(entry, opts, depth + 1);
+ }
+ return out;
+ }
+ return value;
+}
+
+function compactToolUseString(
+ value: string,
+ opts: NormalizedToolResultCompactionOptions,
+): string {
+ if (value.length < opts.toolUseInputStringMinChars) return value;
+
+ const previewChars = Math.max(32, opts.toolUseInputPreviewChars);
+ const headChars = Math.ceil(previewChars * 0.7);
+ const tailChars = Math.max(0, previewChars - headChars);
+ const head = value.slice(0, headChars);
+ const tail = tailChars > 0 && value.length > headChars + tailChars
+ ? value.slice(-tailChars)
+ : "";
+ const tailBlock = tail ? `\npreview_tail:\n${tail}` : "";
+ const compacted = (
+ `[old tool input string compacted: original_size=${value.length} chars]\n` +
+ `preview_head:\n${head}` +
+ tailBlock
+ );
+ return compacted.length < value.length ? compacted : value;
+}
+
+function stringifyToolInput(input: Record<string, unknown>): string {
+ try {
+ return JSON.stringify(input) ?? "";
+ } catch {
+ return String(input);
+ }
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function escapeAttr(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/"/g, "&quot;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;");
+}
+
+function unescapeAttr(value: string): string {
+ return value
+ .replace(/&quot;/g, "\"")
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">")
+ .replace(/&amp;/g, "&");
}
/** Sum the heuristic token estimate across a set of messages. Shared by
diff --git a/src/core-agent/src/tools/base.ts b/src/core-agent/src/tools/base.ts
index 08fa6bbc..a8989ca5 100644
--- a/src/core-agent/src/tools/base.ts
+++ b/src/core-agent/src/tools/base.ts
@@ -70,11 +70,64 @@ export interface AgentTool {
export function toToolDefinition(tool: AgentTool): ToolDefinition {
return {
name: tool.name,
- description: tool.description,
- inputSchema: tool.inputSchema,
+ description: compactDescription(tool.description, 480),
+ inputSchema: compactSchema(tool.inputSchema),
};
}
+const SCHEMA_DESCRIPTION_MAX_CHARS = 220;
+const DROPPED_SCHEMA_KEYS = new Set([
+ "$comment",
+ "$schema",
+ "example",
+ "examples",
+ "markdownDescription",
+]);
+
+function compactSchema(value: Record<string, unknown>): Record<string, unknown> {
+ const compacted = compactSchemaValue(value);
+ return isRecord(compacted) ? compacted : value;
+}
+
+function compactSchemaValue(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(compactSchemaValue);
+ if (!isRecord(value)) return value;
+
+ const out: Record<string, unknown> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ if (DROPPED_SCHEMA_KEYS.has(key)) continue;
+ if (key === "description" && typeof entry === "string") {
+ out[key] = compactDescription(entry, SCHEMA_DESCRIPTION_MAX_CHARS);
+ } else {
+ out[key] = compactSchemaValue(entry);
+ }
+ }
+ return out;
+}
+
+function compactDescription(text: string, maxChars: number): string {
+ const normalized = String(text || "").replace(/\s+/g, " ").trim();
+ if (normalized.length <= maxChars) return normalized;
+
+ const sentenceCut = findSentenceBoundary(normalized, maxChars);
+ const cut = sentenceCut > Math.floor(maxChars * 0.55) ? sentenceCut : maxChars;
+ return `${normalized.slice(0, cut).trimEnd()}...`;
+}
+
+function findSentenceBoundary(text: string, before: number): number {
+ for (let i = Math.min(before, text.length - 1); i >= 0; i--) {
+ const ch = text[i];
+ if (ch === "." || ch === "!" || ch === "?" || ch === ";" || ch === "\u3002" || ch === "\uff01" || ch === "\uff1f") {
+ return i + 1;
+ }
+ }
+ return -1;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
/** Helper to define a tool inline. */
export function defineTool(opts: {
name: string;
diff --git a/src/core-agent/src/tools/builtin.ts b/src/core-agent/src/tools/builtin.ts
index 5406d3c6..86cb77fa 100644
--- a/src/core-agent/src/tools/builtin.ts
+++ b/src/core-agent/src/tools/builtin.ts
@@ -93,7 +93,7 @@ export const bashTool: AgentTool = defineTool({
timeoutMs: { type: "number", description: "Timeout in milliseconds (default: 3600000 = 60 min). Pass a larger value for unusually long-running commands like full builds, large installs, network fetches, video processing." },
run_in_background: {
type: "boolean",
- description: "Run detached and return immediately with a pid + log file path instead of waiting. Use for commands that may outlast any reasonable timeout (long builds, renders, big downloads). Poll progress by reading the log file; stop the process with `kill <pid>`. The process is NOT stopped automatically when the conversation ends.",
+ description: "Run detached and return immediately with pid + log path. Use for long builds, renders, downloads, or servers. Poll by reading the log; stop with `kill <pid>`. It keeps running after the conversation ends.",
},
},
required: ["command"],
diff --git a/src/core-agent/src/tools/memory-tool.ts b/src/core-agent/src/tools/memory-tool.ts
index 0ea4d3a6..a0d3e2c5 100644
--- a/src/core-agent/src/tools/memory-tool.ts
+++ b/src/core-agent/src/tools/memory-tool.ts
@@ -37,39 +37,18 @@ export interface MemoryToolHandler {
};
}
-const TOOL_DESCRIPTION = `Manage your persistent cross-session memory. This memory survives across conversations.
+const TOOL_DESCRIPTION = `Manage durable cross-session memory.
-Three scopes (default "agent"):
-- "agent" (DEFAULT): YOUR OWN durable agent memory — preferences for how this agent should work, task-domain conventions, reusable lessons, and facts/decisions specific to what you do. Other agents do NOT see these, and you do NOT see theirs. Use this for most saves in a specific-agent conversation.
-- "shared": durable facts that EVERY agent should know — project/environment facts, cross-cutting decisions, repo layout, shared conventions. Use sparingly because it lands in every agent's context.
-- "user": the user's global profile/preferences — identity, role, expertise, broad preferences, communication style, or tech stack that should follow the user across every agent.
+Targets:
+- agent (default): this agent's private lessons, workflow preferences, recurring task facts, and corrections.
+- shared: stable project/environment facts every agent should know. Use sparingly.
+- user: stable user-wide profile/preferences every agent should know.
-TARGET ROUTING:
-- If the user says "remember this", "note this", or corrects how YOU should work while talking to a specific agent, use target "agent" unless they clearly say it should apply globally.
-- Use target "user" only for stable user-wide preferences/profile facts every agent should know: identity, broad preferences, communication style, expertise, or tech stack.
-- Use target "shared" only for stable non-user facts every agent should know: project/environment facts, shared decisions, shared conventions, or repo/workspace facts.
-- Never put agent-specific lessons, output preferences, workflow corrections, or task-domain conventions into target "user" or "shared".
+Use when the user asks to remember something, gives a durable correction/preference, or states a future-relevant fact. Do not save trivia, raw dumps/logs, rediscoverable facts, one-off task state, plans, progress, or temporary debug notes.
-LANGUAGE:
-- Write new or replaced entries in the user's current UI/response language.
-- If the remembered fact was stated in another language, translate/summarize it into the current UI/response language before saving.
-- Preserve proper nouns, commands, file paths, code identifiers, URLs, and quoted user wording when exact text matters.
+Routing: agent-specific lessons -> agent; user identity/style/preferences -> user; repo/project conventions -> shared. Write in the user's current language while preserving code, paths, commands, URLs, and exact quoted wording when needed.
-WHEN TO SAVE:
-- User explicitly says "remember this" or "note that"
-- User corrections or preferences (highest priority)
-- Durable decisions or milestones that will still matter in future conversations (NOT the current task's working decisions)
-- User's role, expertise, or global communication preferences (→ target "user")
-- Stable project conventions or environment facts (→ target "shared")
-- This agent's reusable working preferences, recurring task facts, output corrections, or domain lessons (→ target "agent")
-
-WHEN TO SKIP:
-- Trivial or obvious information
-- Easily re-discoverable facts
-- Raw data dumps, code blocks, or logs
-- Session-specific ephemera or the current task's state: temporary debug info, one-off questions, and your plan / progress / status this session — what you are doing, have done, or still need to do (e.g. "X is updated, but Y still needs checking"). Memory is for durable facts about the user and project, not work-in-progress.
-
-Actions: "add" (append new entry), "replace" (update existing by substring match), "remove" (delete by substring match), "list" (view current entries).`;
+Actions: add, replace (by old_text substring), remove (by old_text substring), list.`;
export function createCrossSessionMemoryTool(handler: MemoryToolHandler): AgentTool {
return {
diff --git a/src/core-agent/src/tools/metacognition-tool.ts b/src/core-agent/src/tools/metacognition-tool.ts
index 2365b37b..48d6062f 100644
--- a/src/core-agent/src/tools/metacognition-tool.ts
+++ b/src/core-agent/src/tools/metacognition-tool.ts
@@ -30,37 +30,20 @@ function buildDescription(limits?: { competence?: number; strategies?: number })
compLimit && stratLimit
? [
'',
- `CONTENT LIMITS (hard cap; oversize writes are REJECTED — not truncated):`,
+ `Limits (oversize writes are rejected):`,
`- competence: ${compLimit} characters`,
`- strategies: ${stratLimit} characters`,
- '',
- `The file is a living summary, not a log. When approaching the limit,`,
- `CONDENSE before adding: merge related bullets, drop stale items, keep`,
- `the most actionable insights. A "read" before "write" returns the`,
- `current usage so you know the remaining budget.`,
+ `Keep these files condensed living summaries, not logs.`,
].join('\n')
: '';
- return `Manage your metacognitive self-assessment and learning strategies. These persist across conversations.
-
-Two targets:
-- "competence": Your self-assessment — what you're good at, known weaknesses, learning priorities.
-- "strategies": Your learning strategies library — which approaches work best for which tasks.
-
-WHEN TO UPDATE COMPETENCE:
-- After succeeding at a previously weak area → note the improvement
-- After user corrections → note the weakness
-- After discovering a new capability or limitation
-- Periodically review and update priorities
+ return `Read or replace this agent's persistent metacognition notes.
-WHEN TO UPDATE STRATEGIES:
-- After discovering that a learning approach works well or poorly
-- After trying a new approach to skill creation
-- To record which strategy types suit which task categories
+Targets:
+- competence: strengths, weaknesses, limits, and learning priorities.
+- strategies: which learning/work approaches help for which task types.
-Actions: "read" (view current content), "write" (replace entire content).
-Content is free-form markdown. Structure with ## headings for different sections.
-Language: when the host prompt specifies a user/UI language, write human-readable metacognition content in that language while preserving code, file paths, commands, and exact quoted wording.${limitBlock}`;
+Update after meaningful user corrections, newly discovered capabilities/limits, or useful strategy lessons. Skip routine task progress. Action "write" replaces the whole markdown file; read first if you need current content/usage. Use the user's current language for prose and preserve code, paths, commands, and quoted wording.${limitBlock}`;
}
export function createMetacognitionTool(
diff --git a/src/core-agent/test/metacognition-tool.test.ts b/src/core-agent/test/metacognition-tool.test.ts
index 22b4df83..be2e4517 100644
--- a/src/core-agent/test/metacognition-tool.test.ts
+++ b/src/core-agent/test/metacognition-tool.test.ts
@@ -27,16 +27,15 @@ describe('createMetacognitionTool', () => {
it('omits the limit block when no limits are supplied', () => {
const tool = createMetacognitionTool(mockHandler());
- expect(tool.description).not.toMatch(/CONTENT LIMITS/);
+ expect(tool.description).not.toMatch(/oversize writes are rejected/);
});
it('embeds char limits in description when supplied', () => {
const tool = createMetacognitionTool(mockHandler(), { competence: 3000, strategies: 2500 });
- expect(tool.description).toMatch(/CONTENT LIMITS/);
+ expect(tool.description).toMatch(/Limits \(oversize writes are rejected\)/);
expect(tool.description).toMatch(/competence: 3000 characters/);
expect(tool.description).toMatch(/strategies: 2500 characters/);
- expect(tool.description).toMatch(/REJECTED/);
- expect(tool.description).toMatch(/CONDENSE/);
+ expect(tool.description).toMatch(/condensed living summaries/);
});
});
diff --git a/src/core-agent/test/session.test.ts b/src/core-agent/test/session.test.ts
index d2e070f9..ede50f29 100644
--- a/src/core-agent/test/session.test.ts
+++ b/src/core-agent/test/session.test.ts
@@ -99,6 +99,241 @@ describe("Session", () => {
});
});
+ it("compacts old large tool results only in the model view and keeps a re-readable ref", () => {
+ const persisted: string[] = [];
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 100,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 0,
+ previewHeadChars: 10,
+ previewTailChars: 5,
+ persistToolResult: ({ toolName, toolUseId, content }) => {
+ expect(toolName).toBe("bash");
+ expect(toolUseId).toBe("call-old");
+ expect(content.length).toBeGreaterThan(100);
+ persisted.push("/tmp/tool-results/bash.call-old.txt");
+ return "/tmp/tool-results/bash.call-old.txt";
+ },
+ },
+ });
+ const raw = "0123456789" + "x".repeat(2_000) + "TAIL!";
+
+ session.addAssistantMessage([{ type: "tool_use", id: "call-old", name: "bash", input: { command: "big" } }]);
+ session.addToolResult("call-old", raw, undefined, false);
+ session.addAssistantMessage([{ type: "text", text: "I saw the output." }]);
+
+ const modelMessages = session.getMessagesForModel();
+ const compacted = modelMessages[1].content[0];
+ expect(compacted.type).toBe("tool_result");
+ expect((compacted as { content: string }).content).toContain("<compacted-tool-result");
+ expect((compacted as { content: string }).content).toContain('tool="bash"');
+ expect((compacted as { content: string }).content).toContain("/tmp/tool-results/bash.call-old.txt");
+ expect((compacted as { content: string }).content).toContain("preview_head:\n0123456789");
+ expect((compacted as { content: string }).content).toContain("preview_tail:\nTAIL!");
+ expect((compacted as { content: string }).content.length).toBeLessThan(raw.length);
+ expect(persisted).toHaveLength(1);
+
+ const rawMessages = session.getMessages();
+ expect((rawMessages[1].content[0] as { content: string }).content).toBe(raw);
+
+ session.getMessagesForModel();
+ expect(persisted).toHaveLength(1);
+ });
+
+ it("keeps fresh large tool results verbatim for the next model call", () => {
+ const persisted: string[] = [];
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 100,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 0,
+ persistToolResult: () => {
+ persisted.push("unexpected");
+ return "/tmp/unexpected.txt";
+ },
+ },
+ });
+ const raw = "x".repeat(500);
+
+ session.addAssistantMessage([{ type: "tool_use", id: "call-fresh", name: "bash", input: {} }]);
+ session.addToolResult("call-fresh", raw, undefined, false);
+
+ const modelMessages = session.getMessagesForModel();
+ expect((modelMessages[1].content[0] as { content: string }).content).toBe(raw);
+ expect(persisted).toHaveLength(0);
+ });
+
+ it("compacts old medium tool results once aggregate tool_result text exceeds the threshold", () => {
+ const persisted: string[] = [];
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 8 * 1024,
+ aggregateMinChars: 1_000,
+ aggregateMinResultChars: 100,
+ aggregatePreviewChars: 16,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 0,
+ persistToolResult: ({ toolUseId, content }) => {
+ persisted.push(content);
+ return `/tmp/tool-results/${toolUseId}.txt`;
+ },
+ },
+ });
+ const first = "alpha-" + "a".repeat(700);
+ const second = "beta-" + "b".repeat(700);
+
+ session.addAssistantMessage([{ type: "tool_use", id: "call-1", name: "bash", input: {} }]);
+ session.addToolResult("call-1", first, undefined, false);
+ session.addAssistantMessage([{ type: "tool_use", id: "call-2", name: "bash", input: {} }]);
+ session.addToolResult("call-2", second, undefined, false);
+ session.addAssistantMessage([{ type: "text", text: "seen" }]);
+
+ const modelMessages = session.getMessagesForModel();
+ const compacted = modelMessages
+ .flatMap((m) => m.content)
+ .filter((c) => c.type === "tool_result")
+ .map((c) => (c as { content: string }).content);
+
+ expect(compacted).toHaveLength(2);
+ expect(compacted[0]).toContain('mode="aggregate"');
+ expect(compacted[0]).toContain("total tool_result context exceeded 1000 chars");
+ expect(compacted[0]).toContain('path="/tmp/tool-results/call-1.txt"');
+ expect(compacted[0]).toContain("preview: alpha-");
+ expect(compacted[0]).not.toContain("preview_tail:");
+ expect(compacted[0].length).toBeLessThan(first.length);
+ expect(compacted[1]).toContain('path="/tmp/tool-results/call-2.txt"');
+ expect(persisted).toEqual([first, second]);
+ expect((session.getMessages()[1].content[0] as { content: string }).content).toBe(first);
+ });
+
+ it("keeps recent tool results verbatim even when aggregate compaction is active", () => {
+ const persisted: string[] = [];
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 8 * 1024,
+ aggregateMinChars: 1_000,
+ aggregateMinResultChars: 100,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 2,
+ persistToolResult: ({ toolUseId }) => {
+ persisted.push(toolUseId);
+ return `/tmp/tool-results/${toolUseId}.txt`;
+ },
+ },
+ });
+ const raws = ["one-", "two-", "three-"].map((prefix) => prefix + "x".repeat(600));
+ for (let i = 0; i < raws.length; i++) {
+ const id = `call-${i + 1}`;
+ session.addAssistantMessage([{ type: "tool_use", id, name: "bash", input: {} }]);
+ session.addToolResult(id, raws[i], undefined, false);
+ }
+ session.addAssistantMessage([{ type: "text", text: "seen" }]);
+
+ const contents = session.getMessagesForModel()
+ .flatMap((m) => m.content)
+ .filter((c) => c.type === "tool_result")
+ .map((c) => (c as { content: string }).content);
+
+ expect(contents[0]).toContain('mode="aggregate"');
+ expect(contents[1]).toBe(raws[1]);
+ expect(contents[2]).toBe(raws[2]);
+ expect(persisted).toEqual(["call-1"]);
+ });
+
+ it("compacts old tool_use inputs only in the model view", () => {
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 999_999,
+ aggregateMinChars: 999_999,
+ toolUseInputMinChars: 999_999,
+ toolUseInputAggregateMinChars: 1_000,
+ toolUseInputAggregateMinInputChars: 100,
+ toolUseInputStringMinChars: 80,
+ toolUseInputPreviewChars: 48,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 0,
+ keepRecentToolUses: 0,
+ },
+ });
+ const fileContent = "START-" + "x".repeat(900) + "-END";
+ const command = "printf " + "y".repeat(900);
+
+ session.addAssistantMessage([{ type: "tool_use", id: "call-write", name: "write_file", input: { path: "/tmp/a.txt", content: fileContent } }]);
+ session.addToolResult("call-write", "ok", undefined, false);
+ session.addAssistantMessage([{ type: "tool_use", id: "call-bash", name: "bash", input: { command } }]);
+ session.addToolResult("call-bash", "ok", undefined, false);
+ session.addAssistantMessage([{ type: "text", text: "seen" }]);
+
+ const toolUses = session.getMessagesForModel()
+ .flatMap((m) => m.content)
+ .filter((c) => c.type === "tool_use") as Array<{ input: Record<string, unknown> }>;
+
+ expect(toolUses).toHaveLength(2);
+ expect(toolUses[0].input.path).toBe("/tmp/a.txt");
+ expect(toolUses[0].input.__orkas_context_note).toEqual(expect.stringContaining("original_json_chars"));
+ expect(toolUses[0].input.content).toEqual(expect.stringContaining("old tool input string compacted"));
+ expect(toolUses[0].input.content).toEqual(expect.stringContaining("START-"));
+ expect(toolUses[0].input.content).toEqual(expect.stringContaining("-END"));
+ expect(toolUses[0].input.content).not.toBe(fileContent);
+ expect(toolUses[1].input.command).toEqual(expect.stringContaining("old tool input string compacted"));
+
+ const rawToolUse = session.getMessages()[0].content[0];
+ expect(rawToolUse.type).toBe("tool_use");
+ expect((rawToolUse as { input: Record<string, unknown> }).input.content).toBe(fileContent);
+ });
+
+ it("keeps recent tool_use inputs verbatim even when input compaction is active", () => {
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 999_999,
+ aggregateMinChars: 999_999,
+ toolUseInputMinChars: 999_999,
+ toolUseInputAggregateMinChars: 1_000,
+ toolUseInputAggregateMinInputChars: 100,
+ toolUseInputStringMinChars: 80,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 0,
+ keepRecentToolUses: 1,
+ },
+ });
+ const oldCommand = "old-" + "x".repeat(900);
+ const freshCommand = "fresh-" + "y".repeat(900);
+
+ session.addAssistantMessage([{ type: "tool_use", id: "call-old", name: "bash", input: { command: oldCommand } }]);
+ session.addToolResult("call-old", "ok", undefined, false);
+ session.addAssistantMessage([{ type: "tool_use", id: "call-fresh", name: "bash", input: { command: freshCommand } }]);
+ session.addToolResult("call-fresh", "ok", undefined, false);
+ session.addAssistantMessage([{ type: "text", text: "seen" }]);
+
+ const commands = session.getMessagesForModel()
+ .flatMap((m) => m.content)
+ .filter((c) => c.type === "tool_use")
+ .map((c) => (c as { input: Record<string, unknown> }).input.command);
+
+ expect(commands[0]).toEqual(expect.stringContaining("old tool input string compacted"));
+ expect(commands[1]).toBe(freshCommand);
+ });
+
+ it("estimateModelTokens uses the compacted provider view", () => {
+ const session = new Session({
+ toolResultCompaction: {
+ minChars: 100,
+ keepRecentAssistantSteps: 0,
+ keepRecentToolResults: 0,
+ previewHeadChars: 10,
+ previewTailChars: 10,
+ persistToolResult: () => "/tmp/tool-results/bash.big.txt",
+ },
+ });
+ session.addAssistantMessage([{ type: "tool_use", id: "call-big", name: "bash", input: {} }]);
+ session.addToolResult("call-big", "a".repeat(20_000), undefined, false);
+ session.addAssistantMessage([{ type: "text", text: "seen" }]);
+
+ expect(session.estimateTokens()).toBeGreaterThan(4_000);
+ expect(session.estimateModelTokens()).toBeLessThan(1_000);
+ });
+
it("trims history to exactly maxHistoryTurns and keeps the newest turns", () => {
const session = new Session({ maxHistoryTurns: 2 });
for (let i = 0; i < 4; i++) {
@@ -113,6 +348,36 @@ describe("Session", () => {
expect((msgs[3].content[0] as { text: string }).text).toBe("Response 3");
});
+ it("trims at a provider-safe boundary when the cut lands on a tool_result", () => {
+ const session = new Session({ maxHistoryTurns: 2 });
+ session.addUserMessage("start");
+ session.addAssistantMessage([{ type: "tool_use", id: "call-old", name: "bash", input: {} }]);
+ session.addToolResult("call-old", "ok", undefined, false);
+ session.addAssistantMessage([{ type: "text", text: "tool done" }]);
+ session.addUserMessage("next");
+ session.addAssistantMessage([{ type: "text", text: "next response" }]);
+
+ const msgs = session.getMessages();
+ expect(msgs[0].content[0].type).not.toBe("tool_result");
+ expect(msgs.flatMap((m) => m.content).some(
+ (c) => c.type === "tool_result" && c.toolUseId === "call-old",
+ )).toBe(false);
+ expect((msgs.at(-1)?.content[0] as { text: string }).text).toBe("next response");
+ });
+
+ it("defaults to keeping the newest 50 internal turns", () => {
+ const session = new Session();
+ for (let i = 0; i < 55; i++) {
+ session.addUserMessage(`User message ${i}`);
+ session.addAssistantMessage([{ type: "text", text: `Response ${i}` }]);
+ }
+
+ expect(session.length).toBe(100);
+ const msgs = session.getMessages();
+ expect((msgs[0].content[0] as { text: string }).text).toBe("User message 5");
+ expect((msgs[99].content[0] as { text: string }).text).toBe("Response 54");
+ });
+
it("compacts session with summary", () => {
const session = new Session();
diff --git a/src/core-agent/test/tools.test.ts b/src/core-agent/test/tools.test.ts
index ba8f8161..bc56c325 100644
--- a/src/core-agent/test/tools.test.ts
+++ b/src/core-agent/test/tools.test.ts
@@ -58,6 +58,48 @@ describe("Tools", () => {
inputSchema: { type: "object" },
});
});
+
+ it("compacts descriptions without changing schema semantics", () => {
+ const longDescription = "Use this tool carefully. " + "detail ".repeat(120);
+ const tool = defineTool({
+ name: "schema_tool",
+ description: longDescription,
+ inputSchema: {
+ $schema: "https://json-schema.org/draft/2020-12/schema",
+ type: "object",
+ required: ["mode"],
+ properties: {
+ mode: {
+ type: "string",
+ enum: ["fast", "safe"],
+ description: "Choose execution mode. " + "extra ".repeat(80),
+ examples: ["fast"],
+ },
+ count: { type: "number", minimum: 1, maximum: 10 },
+ },
+ examples: [{ mode: "fast" }],
+ },
+ async execute() {
+ return { content: "" };
+ },
+ });
+
+ const def = toToolDefinition(tool);
+ expect(def.description.length).toBeLessThan(longDescription.length);
+ expect(def.inputSchema).toMatchObject({
+ type: "object",
+ required: ["mode"],
+ properties: {
+ mode: { type: "string", enum: ["fast", "safe"] },
+ count: { type: "number", minimum: 1, maximum: 10 },
+ },
+ });
+ expect(def.inputSchema).not.toHaveProperty("$schema");
+ expect(def.inputSchema).not.toHaveProperty("examples");
+ const modeSchema = (def.inputSchema.properties as Record<string, Record<string, unknown>>).mode;
+ expect(modeSchema.description).toEqual(expect.stringContaining("Choose execution mode."));
+ expect(modeSchema).not.toHaveProperty("examples");
+ });
});
describe("getBuiltinTools", () => {
diff --git a/src/main/features/builtin_marketplace.ts b/src/main/features/builtin_marketplace.ts
index 9aed905e..3a9412f7 100644
--- a/src/main/features/builtin_marketplace.ts
+++ b/src/main/features/builtin_marketplace.ts
@@ -5,21 +5,19 @@
* platform agents/skills. It is not a third source tier at runtime: this module
* copies missing packaged content into the normal per-user marketplace install
* tree, writes ordinary installs.json rows, and lets marketplace reconcile take
- * over once the server is reachable. In dev, a newer packaged builtin can also
- * overlay the same-id marketplace install while preserving install metadata; this
- * keeps git-managed builtin changes runnable before they are published upstream.
+ * over once the server is reachable. A newer packaged builtin can also overlay
+ * the same-id marketplace install while preserving install metadata; this keeps
+ * git-managed builtin changes runnable before they are published upstream.
*/
import * as fs from 'node:fs';
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
-import * as crypto from 'node:crypto';
import {
packagedBuiltinMarketplaceAgentsDir,
packagedBuiltinMarketplaceSkillsDir,
userMarketplaceAgentDir,
- userMarketplaceAgentSkillsDir,
userMarketplaceSkillDir,
} from '../paths';
import { createLogger } from '../logger';
@@ -27,11 +25,9 @@ import { safeId } from '../storage';
import { sha256OfFile } from '../util/sha256';
import {
MARKETPLACE_RESOURCE_MANIFEST_NAME,
- MARKETPLACE_TREE_HASH_ALGORITHM,
MARKETPLACE_TREE_HASH_SKIP_NAMES,
marketplaceContentTreeFiles,
marketplaceContentTreeHash,
- marketplaceContentTreeHashForFiles,
} from '../util/marketplace-tree-hash';
import {
DEFAULT_MARKETPLACE_VERSION,
@@ -45,7 +41,6 @@ import { postJson } from './marketplace';
const log = createLogger('builtin-marketplace');
const BUILTIN_CREATE_UID = '0';
-const ENABLE_BUILTIN_DEV_OVERLAY = false;
export interface BuiltinMarketplaceSeedOptions {
shouldContinue?: () => boolean;
@@ -80,17 +75,6 @@ function _safeDirEntries(root: string): fs.Dirent[] {
}
}
-async function _copyDir(src: string, dst: string): Promise<void> {
- await fsp.mkdir(dst, { recursive: true });
- for (const entry of await fsp.readdir(src, { withFileTypes: true })) {
- if (entry.name === '.' || entry.name === '..' || entry.name === '_install.json') continue;
- const from = path.join(src, entry.name);
- const to = path.join(dst, entry.name);
- if (entry.isDirectory()) await _copyDir(from, to);
- else if (entry.isFile()) await fsp.copyFile(from, to);
- }
-}
-
function _readJsonObject(file: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
@@ -152,19 +136,25 @@ function _builtinAgentUpdatedAt(agentJson: Record<string, unknown>): number {
return _timestampMs(agentJson.updated_at);
}
+function _builtinAgentReseedIfDeletedBefore(srcDir: string, agentJson: Record<string, unknown>): number {
+ const meta = _readJsonObject(path.join(srcDir, '_meta.json'));
+ return _timestampMs(meta?.reseed_if_deleted_before)
+ || _timestampMs(agentJson.reseed_if_deleted_before);
+}
+
function _builtinSkillVersion(srcDir: string): string {
const meta = _readJsonObject(path.join(srcDir, '_meta.json'));
return normalizeInstallVersion(meta?.version);
}
-function _builtinSkillReseedIfDeletedBefore(srcDir: string): number {
+function _builtinSkillUpdatedAt(srcDir: string): number {
const meta = _readJsonObject(path.join(srcDir, '_meta.json'));
- return _timestampMs(meta?.reseed_if_deleted_before);
+ return _timestampMs(meta?.updated_at);
}
-function _freshnessAt(row: { published_at?: number; updated_at?: number } | null | undefined): number {
- if (!row) return 0;
- return typeof row.updated_at === 'number' ? row.updated_at : (typeof row.published_at === 'number' ? row.published_at : 0);
+function _builtinSkillReseedIfDeletedBefore(srcDir: string): number {
+ const meta = _readJsonObject(path.join(srcDir, '_meta.json'));
+ return _timestampMs(meta?.reseed_if_deleted_before);
}
function _emptyUrl(value: unknown): boolean {
@@ -190,6 +180,49 @@ function _readInstallMetaObject(dir: string): Record<string, unknown> | null {
return _readJsonObject(path.join(dir, '_install.json'));
}
+function _rawVersion(value: unknown): string {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function _localInstallVersion(
+ meta: Record<string, unknown> | null,
+ manifestRow: { version?: string; updated_at?: number } | null | undefined,
+): { missing: boolean; version: string } {
+ const metaVersion = _rawVersion(meta?.version);
+ if (meta && !metaVersion) return { missing: true, version: '' };
+ const rowVersion = _rawVersion(manifestRow?.version);
+ const version = metaVersion || rowVersion;
+ return version
+ ? { missing: false, version }
+ : { missing: true, version: '' };
+}
+
+function _localInstallUpdatedAt(
+ meta: Record<string, unknown> | null,
+ manifestRow: { published_at?: number; updated_at?: number } | null | undefined,
+): number {
+ return Math.max(
+ _timestampMs(meta?.updated_at),
+ _timestampMs(meta?.published_at),
+ _timestampMs(manifestRow?.updated_at),
+ _timestampMs(manifestRow?.published_at),
+ );
+}
+
+function _shouldSyncBuiltinInstall(
+ packagedVersion: string,
+ packagedUpdatedAt: number,
+ meta: Record<string, unknown> | null,
+ manifestRow: { version?: string; published_at?: number; updated_at?: number } | null | undefined,
+): boolean {
+ const local = _localInstallVersion(meta, manifestRow);
+ if (local.missing) return true;
+ const versionCompare = _compareVersions(packagedVersion, local.version);
+ if (versionCompare > 0) return true;
+ if (versionCompare < 0) return false;
+ return packagedUpdatedAt > 0 && packagedUpdatedAt > _localInstallUpdatedAt(meta, manifestRow);
+}
+
function _isLocalBuiltinSeedMeta(meta: Record<string, unknown> | null): boolean {
return _isLegacyBuiltinSeedMeta(meta, 'agent_json_url');
}
@@ -210,76 +243,18 @@ function _isLocalResourceSeedMeta(meta: Record<string, unknown> | null): boolean
return !!meta && meta.seed_source === 'resource';
}
-type ResourceSeedManifest = {
- resource_hash: string;
- files: string[];
-};
-
-function _readResourceSeedManifest(
- target: string,
+function _shouldTakeOverResourceSeedFromBuiltin(
+ uid: string,
kind: 'agent' | 'skill',
id: string,
-): ResourceSeedManifest | null {
- const manifest = _readJsonObject(path.join(target, MARKETPLACE_RESOURCE_MANIFEST_NAME));
- if (!manifest) return null;
- if (manifest.kind !== kind || manifest.id !== id) return null;
- if (manifest.hashAlgorithm && manifest.hashAlgorithm !== MARKETPLACE_TREE_HASH_ALGORITHM) return null;
- const resourceHash = typeof manifest.resource_hash === 'string' ? manifest.resource_hash.trim() : '';
- const files = _safeManagedFiles(manifest.files);
- return resourceHash && files.length ? { resource_hash: resourceHash, files } : null;
-}
-
-function _legacyLocaleContentTreeHashForFiles(root: string, files: Iterable<string>): string {
- const normalized = Array.from(new Set(Array.from(files)
- .map((rel) => _normalizeManagedRel(rel))
- .filter((rel): rel is string => !!rel)))
- .sort((a, b) => a.localeCompare(b));
- if (!normalized.length) return '';
-
- const h = crypto.createHash('sha256');
- h.update(`${MARKETPLACE_TREE_HASH_ALGORITHM}\0`);
- for (const rel of normalized) {
- let bytes: Buffer;
- try {
- bytes = fs.readFileSync(path.join(root, rel));
- } catch {
- return '';
- }
- h.update(rel.replace(/\\/g, '/'));
- h.update('\0');
- h.update(String(bytes.length));
- h.update('\0');
- h.update(bytes);
- h.update('\0');
- }
- return h.digest('hex');
-}
-
-function _resourceSeedLocallyModified(target: string, kind: 'agent' | 'skill', id: string): boolean {
- const manifest = _readResourceSeedManifest(target, kind, id);
- if (!manifest) return true;
- const currentHash = marketplaceContentTreeHashForFiles(target, manifest.files);
- if (
- currentHash !== manifest.resource_hash
- && _legacyLocaleContentTreeHashForFiles(target, manifest.files) !== manifest.resource_hash
- ) {
- return true;
- }
-
- const managed = new Set(manifest.files);
- return marketplaceContentTreeFiles(target).some((rel) => !managed.has(rel));
-}
-
-function _shouldTakeOverResourceSeedFromBuiltin(uid: string, kind: 'agent' | 'skill', id: string): boolean {
- if (!ENABLE_BUILTIN_DEV_OVERLAY) return false;
+ packagedVersion: string,
+ packagedUpdatedAt: number,
+ manifestRow: { version?: string; published_at?: number; updated_at?: number } | null,
+): boolean {
const target = kind === 'agent' ? userMarketplaceAgentDir(uid, id) : userMarketplaceSkillDir(uid, id);
const meta = _readInstallMetaObject(target);
if (!_isLocalResourceSeedMeta(meta)) return false;
- if (_resourceSeedLocallyModified(target, kind, id)) {
- log.warn(`skip builtin ${kind} resource handoff ${id}: local install was modified`);
- return false;
- }
- return true;
+ return _shouldSyncBuiltinInstall(packagedVersion, packagedUpdatedAt, meta, manifestRow);
}
async function _removeResourceSeedManifest(target: string): Promise<void> {
@@ -309,6 +284,15 @@ function _shouldBypassBuiltinSkillTombstone(srcDir: string, deletedAt: number):
return cutoff > 0 && deletedAt > 0 && deletedAt < cutoff;
}
+function _shouldBypassBuiltinAgentTombstone(
+ srcDir: string,
+ agentJson: Record<string, unknown>,
+ deletedAt: number,
+): boolean {
+ const cutoff = _builtinAgentReseedIfDeletedBefore(srcDir, agentJson);
+ return cutoff > 0 && deletedAt > 0 && deletedAt < cutoff;
+}
+
function _shouldRefreshBuiltinAgent(
uid: string,
installId: string,
@@ -321,17 +305,7 @@ function _shouldRefreshBuiltinAgent(
if (!canRefresh) return false;
const packagedVersion = _builtinAgentVersion(agentJson);
- const localVersion = normalizeInstallVersion(meta.version || manifestRow?.version);
- const versionCmp = _compareVersions(packagedVersion, localVersion);
- if (versionCmp > 0) return true;
- if (versionCmp < 0) return false;
-
- const packagedFresh = _builtinAgentUpdatedAt(agentJson);
- const localFresh = _freshnessAt({
- published_at: typeof meta.published_at === 'number' ? meta.published_at : manifestRow?.published_at,
- updated_at: typeof meta.updated_at === 'number' ? meta.updated_at : manifestRow?.updated_at,
- });
- return packagedFresh > localFresh;
+ return _shouldSyncBuiltinInstall(packagedVersion, _builtinAgentUpdatedAt(agentJson), meta, manifestRow);
}
function _shouldRefreshBuiltinSkill(
@@ -345,15 +319,8 @@ function _shouldRefreshBuiltinSkill(
const canRefresh = _isBuiltinSeedSkillRow(manifestRow) || (!manifestRow && _isLocalBuiltinSeedSkillMeta(meta));
if (!canRefresh) return false;
- const packagedTreeHash = marketplaceContentTreeHash(srcDir);
- if (!packagedTreeHash) return false;
-
- if (_builtinSkillLocallyModified(target, meta)) {
- log.warn(`skip builtin skill refresh ${installId}: local install was modified`);
- return false;
- }
-
- return meta.content_tree_hash !== packagedTreeHash;
+ const packagedVersion = _builtinSkillVersion(srcDir);
+ return _shouldSyncBuiltinInstall(packagedVersion, _builtinSkillUpdatedAt(srcDir), meta, manifestRow);
}
function _shouldOverlayMarketplaceAgentFromBuiltin(
@@ -362,20 +329,13 @@ function _shouldOverlayMarketplaceAgentFromBuiltin(
agentJson: Record<string, unknown>,
manifestRow: AgentInstall | null,
): boolean {
- if (!ENABLE_BUILTIN_DEV_OVERLAY || !manifestRow?.agent_json_url) return false;
+ if (!manifestRow?.agent_json_url) return false;
const target = userMarketplaceAgentDir(uid, installId);
const meta = _readInstallMetaObject(target) || {};
if (_isLocalResourceSeedMeta(meta)) return false;
const packagedVersion = _builtinAgentVersion(agentJson);
- const localVersion = normalizeInstallVersion(meta.version || manifestRow.version);
- if (_compareVersions(packagedVersion, localVersion) <= 0) return false;
-
- if (_agentLocallyModified(target, meta)) {
- log.warn(`skip builtin agent overlay ${installId}: local install was modified`);
- return false;
- }
- return true;
+ return _shouldSyncBuiltinInstall(packagedVersion, _builtinAgentUpdatedAt(agentJson), meta, manifestRow);
}
function _shouldOverlayMarketplaceSkillFromBuiltin(
@@ -384,69 +344,13 @@ function _shouldOverlayMarketplaceSkillFromBuiltin(
srcDir: string,
manifestRow: SkillInstall | null,
): boolean {
- if (!ENABLE_BUILTIN_DEV_OVERLAY || !manifestRow?.bundle_url) return false;
+ if (!manifestRow?.bundle_url) return false;
const target = userMarketplaceSkillDir(uid, installId);
const meta = _readInstallMetaObject(target) || {};
if (_isLocalResourceSeedMeta(meta)) return false;
const packagedVersion = _builtinSkillVersion(srcDir);
- const localVersion = normalizeInstallVersion(meta.version || manifestRow.version);
- if (_compareVersions(packagedVersion, localVersion) <= 0) return false;
-
- if (_builtinSkillLocallyModified(target, meta)) {
- log.warn(`skip builtin skill overlay ${installId}: local install was modified`);
- return false;
- }
- return true;
-}
-
-function _agentLocallyModified(target: string, meta: Record<string, unknown>): boolean {
- const agentJsonFile = path.join(target, 'agent.json');
- if (typeof meta.content_sha === 'string' && meta.content_sha) {
- const diskSha = sha256OfFile(agentJsonFile);
- if (diskSha && diskSha !== meta.content_sha) return true;
- }
- if (typeof meta.content_tree_hash === 'string' && meta.content_tree_hash) {
- const managedFiles = _safeManagedFiles(meta.builtin_files);
- const currentTreeHash = managedFiles.length
- ? marketplaceContentTreeHashForFiles(target, managedFiles)
- : marketplaceContentTreeHash(target);
- return !!currentTreeHash && currentTreeHash !== meta.content_tree_hash;
- }
- return false;
-}
-
-function _builtinSkillLocallyModified(target: string, meta: Record<string, unknown>): boolean {
- const skillMdFile = path.join(target, 'SKILL.md');
- if (typeof meta.content_sha === 'string' && meta.content_sha) {
- const diskSha = sha256OfFile(skillMdFile);
- if (diskSha && diskSha !== meta.content_sha) return true;
- }
- if (typeof meta.content_tree_hash === 'string' && meta.content_tree_hash) {
- const managedFiles = _safeManagedFiles(meta.builtin_files);
- const currentTreeHash = managedFiles.length
- ? marketplaceContentTreeHashForFiles(target, managedFiles)
- : marketplaceContentTreeHash(target);
- return !!currentTreeHash && currentTreeHash !== meta.content_tree_hash;
- }
- return false;
-}
-
-function _installMetaBase(
- installedAt: number,
- contentSha: string | null,
- opts: { version?: string; updated_at?: number } = {},
-): Record<string, unknown> {
- return {
- version: normalizeInstallVersion(opts.version),
- published_at: 0,
- ...(typeof opts.updated_at === 'number' && opts.updated_at > 0 ? { updated_at: opts.updated_at } : {}),
- installed_at: installedAt,
- create_uid: BUILTIN_CREATE_UID,
- default_install: true,
- seed_source: 'builtin',
- ...(contentSha ? { content_sha: contentSha } : {}),
- };
+ return _shouldSyncBuiltinInstall(packagedVersion, _builtinSkillUpdatedAt(srcDir), meta, manifestRow);
}
function _agentSeedInstallRow(installId: string, agentJson: Record<string, unknown>, installedAt: number): AgentInstall {
@@ -465,11 +369,17 @@ function _agentSeedInstallRow(installId: string, agentJson: Record<string, unkno
};
}
-function _skillSeedInstallRow(installId: string, installedAt: number, version = DEFAULT_MARKETPLACE_VERSION): SkillInstall {
+function _skillSeedInstallRow(
+ installId: string,
+ installedAt: number,
+ version = DEFAULT_MARKETPLACE_VERSION,
+ updatedAt = 0,
+): SkillInstall {
return {
id: installId,
version: normalizeInstallVersion(version),
published_at: 0,
+ ...(updatedAt > 0 ? { updated_at: updatedAt } : {}),
bundle_url: '',
installed_at: installedAt,
create_uid: BUILTIN_CREATE_UID,
@@ -486,29 +396,38 @@ async function _writeAgentSeed(
installedAt = Date.now(),
): Promise<void> {
const target = userMarketplaceAgentDir(uid, installId);
- await fsp.rm(target, { recursive: true, force: true });
+ const existing = _readInstallMetaObject(target) || {};
+ const previousFiles = _safeManagedFiles(existing.builtin_files);
+ const files = marketplaceContentTreeFiles(srcDir);
await fsp.mkdir(target, { recursive: true });
+ await _removeStaleManagedFiles(target, previousFiles, files);
+ await _copyManagedFiles(srcDir, target, files);
await fsp.writeFile(
path.join(target, 'agent.json'),
`${JSON.stringify({ ...agentJson, agent_id: installId }, null, 2)}\n`,
'utf8',
);
- const srcSkills = path.join(srcDir, 'skills');
- try {
- if (fs.statSync(srcSkills).isDirectory()) {
- await _copyDir(srcSkills, userMarketplaceAgentSkillsDir(uid, installId));
- }
- } catch { /* agent has no bundled private skills */ }
const contentSha = sha256OfFile(path.join(target, 'agent.json'));
+ const contentTreeHash = marketplaceContentTreeHash(srcDir);
+ const updatedAt = _builtinAgentUpdatedAt(agentJson);
await fsp.writeFile(
path.join(target, '_install.json'),
`${JSON.stringify({
- ..._installMetaBase(installedAt, contentSha || null, {
- version: _builtinAgentVersion(agentJson),
- updated_at: _builtinAgentUpdatedAt(agentJson),
- }),
- agent_json_url: '',
- agent_skills_bundle_url: '',
+ ...existing,
+ version: _builtinAgentVersion(agentJson),
+ published_at: typeof existing.published_at === 'number' ? existing.published_at : 0,
+ ...(updatedAt > 0
+ ? { updated_at: updatedAt }
+ : (typeof existing.updated_at === 'number' ? { updated_at: existing.updated_at } : {})),
+ installed_at: typeof existing.installed_at === 'number' ? existing.installed_at : installedAt,
+ create_uid: typeof existing.create_uid === 'string' ? existing.create_uid : BUILTIN_CREATE_UID,
+ default_install: typeof existing.default_install === 'boolean' ? existing.default_install : true,
+ seed_source: 'builtin',
+ agent_json_url: typeof existing.agent_json_url === 'string' ? existing.agent_json_url : '',
+ agent_skills_bundle_url: typeof existing.agent_skills_bundle_url === 'string' ? existing.agent_skills_bundle_url : '',
+ ...(contentSha ? { content_sha: contentSha } : {}),
+ ...(contentTreeHash ? { content_tree_hash: contentTreeHash } : {}),
+ builtin_files: files,
}, null, 2)}\n`,
'utf8',
);
@@ -537,15 +456,18 @@ async function _writeAgentMarketplaceOverlay(
const contentSha = sha256OfFile(path.join(target, 'agent.json'));
const contentTreeHash = marketplaceContentTreeHash(srcDir);
+ const updatedAt = _builtinAgentUpdatedAt(agentJson);
await fsp.writeFile(
path.join(target, '_install.json'),
`${JSON.stringify({
...existing,
version: _builtinAgentVersion(agentJson),
published_at: typeof existing.published_at === 'number' ? existing.published_at : manifestRow.published_at,
- ...(typeof existing.updated_at === 'number'
- ? { updated_at: existing.updated_at }
- : (typeof manifestRow.updated_at === 'number' ? { updated_at: manifestRow.updated_at } : {})),
+ ...(updatedAt > 0
+ ? { updated_at: updatedAt }
+ : (typeof existing.updated_at === 'number'
+ ? { updated_at: existing.updated_at }
+ : (typeof manifestRow.updated_at === 'number' ? { updated_at: manifestRow.updated_at } : {}))),
installed_at: typeof existing.installed_at === 'number' ? existing.installed_at : manifestRow.installed_at,
create_uid: typeof existing.create_uid === 'string' ? existing.create_uid : (manifestRow.create_uid || BUILTIN_CREATE_UID),
default_install: typeof existing.default_install === 'boolean'
@@ -646,11 +568,22 @@ async function _writeSkillSeed(
const contentSha = sha256OfFile(path.join(target, 'SKILL.md'));
const contentTreeHash = marketplaceContentTreeHash(srcDir);
const version = _builtinSkillVersion(srcDir);
+ const updatedAt = _builtinSkillUpdatedAt(srcDir);
await fsp.writeFile(
path.join(target, '_install.json'),
`${JSON.stringify({
- ..._installMetaBase(installedAt, contentSha || null, { version }),
- bundle_url: '',
+ ...existing,
+ version,
+ published_at: typeof existing.published_at === 'number' ? existing.published_at : 0,
+ ...(updatedAt > 0
+ ? { updated_at: updatedAt }
+ : (typeof existing.updated_at === 'number' ? { updated_at: existing.updated_at } : {})),
+ installed_at: typeof existing.installed_at === 'number' ? existing.installed_at : installedAt,
+ create_uid: typeof existing.create_uid === 'string' ? existing.create_uid : BUILTIN_CREATE_UID,
+ default_install: typeof existing.default_install === 'boolean' ? existing.default_install : true,
+ seed_source: 'builtin',
+ bundle_url: typeof existing.bundle_url === 'string' ? existing.bundle_url : '',
+ ...(contentSha ? { content_sha: contentSha } : {}),
...(contentTreeHash ? { content_tree_hash: contentTreeHash } : {}),
builtin_files: files,
}, null, 2)}\n`,
@@ -675,15 +608,18 @@ async function _writeSkillMarketplaceOverlay(
const contentSha = sha256OfFile(path.join(target, 'SKILL.md'));
const contentTreeHash = marketplaceContentTreeHash(srcDir);
const version = _builtinSkillVersion(srcDir);
+ const updatedAt = _builtinSkillUpdatedAt(srcDir);
await fsp.writeFile(
path.join(target, '_install.json'),
`${JSON.stringify({
...existing,
version,
published_at: typeof existing.published_at === 'number' ? existing.published_at : manifestRow.published_at,
- ...(typeof existing.updated_at === 'number'
- ? { updated_at: existing.updated_at }
- : (typeof manifestRow.updated_at === 'number' ? { updated_at: manifestRow.updated_at } : {})),
+ ...(updatedAt > 0
+ ? { updated_at: updatedAt }
+ : (typeof existing.updated_at === 'number'
+ ? { updated_at: existing.updated_at }
+ : (typeof manifestRow.updated_at === 'number' ? { updated_at: manifestRow.updated_at } : {}))),
installed_at: typeof existing.installed_at === 'number' ? existing.installed_at : manifestRow.installed_at,
create_uid: typeof existing.create_uid === 'string' ? existing.create_uid : (manifestRow.create_uid || BUILTIN_CREATE_UID),
default_install: typeof existing.default_install === 'boolean'
@@ -718,7 +654,6 @@ export async function seedBuiltinMarketplaceForUser(
const manifest = await readInstalls(uid);
const installedAgents = new Set(manifest.agents.map((a) => a.id));
const installedSkills = new Set(manifest.skills.map((s) => s.id));
- const deletedAgents = new Set(Object.keys(manifest._deleted_at?.agents || {}));
let manifestChanged = false;
for (const entry of _safeDirEntries(packagedBuiltinMarketplaceAgentsDir())) {
@@ -734,7 +669,12 @@ export async function seedBuiltinMarketplaceForUser(
log.warn(`skip builtin agent ${entry.name}: directory name must equal 12-hex agent_id`);
continue;
}
- if (deletedAgents.has(installId)) continue;
+ const agentDeletedAt = _deletedAt(manifest._deleted_at?.agents, installId);
+ if (agentDeletedAt > 0) {
+ if (!_shouldBypassBuiltinAgentTombstone(srcDir, agentJson, agentDeletedAt)) continue;
+ if (_clearDeletedAt(manifest, 'agents', installId)) manifestChanged = true;
+ log.info(`reseed builtin agent ${installId}: packaged content supersedes old uninstall tombstone`);
+ }
const manifestAgentIndex = manifest.agents.findIndex((a) => a.id === installId);
const manifestAgent = manifestAgentIndex >= 0 ? manifest.agents[manifestAgentIndex] : null;
const targetAgentJson = path.join(userMarketplaceAgentDir(uid, installId), 'agent.json');
@@ -742,7 +682,14 @@ export async function seedBuiltinMarketplaceForUser(
const installedAt = manifestAgent?.installed_at || Date.now();
await _writeAgentSeed(uid, installId, srcDir, agentJson, installedAt);
result.seeded_agents++;
- } else if (_shouldTakeOverResourceSeedFromBuiltin(uid, 'agent', installId)) {
+ } else if (_shouldTakeOverResourceSeedFromBuiltin(
+ uid,
+ 'agent',
+ installId,
+ _builtinAgentVersion(agentJson),
+ _builtinAgentUpdatedAt(agentJson),
+ manifestAgent,
+ )) {
if (manifestAgent?.agent_json_url) {
await _writeAgentMarketplaceOverlay(uid, installId, srcDir, agentJson, manifestAgent);
} else {
@@ -789,6 +736,7 @@ export async function seedBuiltinMarketplaceForUser(
log.info(`reseed builtin skill ${installId}: packaged content supersedes old uninstall tombstone`);
}
const packagedVersion = _builtinSkillVersion(srcDir);
+ const packagedUpdatedAt = _builtinSkillUpdatedAt(srcDir);
const manifestSkillIndex = manifest.skills.findIndex((s) => s.id === installId);
const manifestSkill = manifestSkillIndex >= 0 ? manifest.skills[manifestSkillIndex] : null;
const targetSkillMd = path.join(userMarketplaceSkillDir(uid, installId), 'SKILL.md');
@@ -796,14 +744,26 @@ export async function seedBuiltinMarketplaceForUser(
const installedAt = manifestSkill?.installed_at || Date.now();
await _writeSkillSeed(uid, installId, srcDir, installedAt);
result.seeded_skills++;
- } else if (_shouldTakeOverResourceSeedFromBuiltin(uid, 'skill', installId)) {
+ } else if (_shouldTakeOverResourceSeedFromBuiltin(
+ uid,
+ 'skill',
+ installId,
+ packagedVersion,
+ packagedUpdatedAt,
+ manifestSkill,
+ )) {
if (manifestSkill?.bundle_url) {
await _writeSkillMarketplaceOverlay(uid, installId, srcDir, manifestSkill);
} else {
const installedAt = manifestSkill?.installed_at || Date.now();
await _writeSkillSeed(uid, installId, srcDir, installedAt);
if (manifestSkillIndex >= 0) {
- manifest.skills[manifestSkillIndex] = _skillSeedInstallRow(installId, installedAt, packagedVersion);
+ manifest.skills[manifestSkillIndex] = _skillSeedInstallRow(
+ installId,
+ installedAt,
+ packagedVersion,
+ packagedUpdatedAt,
+ );
manifestChanged = true;
}
}
@@ -813,7 +773,12 @@ export async function seedBuiltinMarketplaceForUser(
await _writeSkillSeed(uid, installId, srcDir, installedAt);
result.seeded_skills++;
if (manifestSkillIndex >= 0) {
- manifest.skills[manifestSkillIndex] = _skillSeedInstallRow(installId, installedAt, packagedVersion);
+ manifest.skills[manifestSkillIndex] = _skillSeedInstallRow(
+ installId,
+ installedAt,
+ packagedVersion,
+ packagedUpdatedAt,
+ );
manifestChanged = true;
}
} else if (manifestSkill && _shouldOverlayMarketplaceSkillFromBuiltin(uid, installId, srcDir, manifestSkill)) {
@@ -821,7 +786,7 @@ export async function seedBuiltinMarketplaceForUser(
result.seeded_skills++;
}
if (!installedSkills.has(installId)) {
- manifest.skills.push(_skillSeedInstallRow(installId, Date.now(), packagedVersion));
+ manifest.skills.push(_skillSeedInstallRow(installId, Date.now(), packagedVersion, packagedUpdatedAt));
installedSkills.add(installId);
result.manifest_skills++;
}
diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.ts
index 50e0e01d..a2f2463d 100644
--- a/src/main/features/chat_attachments.ts
+++ b/src/main/features/chat_attachments.ts
@@ -1,6 +1,8 @@
/**
* Per-conversation file attachments for main chat (`normal`).
- * Layout: `data/<uid>/cloud/chat_attachments/<cid>/`.
+ * Layout:
+ * sent/committed attachments: `data/<uid>/cloud/chat_attachments/<cid>/`
+ * composer-only drafts: `data/<uid>/local/chat_attachment_drafts/<draftCid>/`
*
* Supported kinds — mirrors `contexts` upload whitelist:
* text — .md / .markdown / .txt / .csv / .tsv / .json / .yaml / .yml / .log
@@ -14,7 +16,10 @@
* `chat-media://` protocol)
*
* Lifecycle:
- * uploadAttachment — write original to disk; NO preprocessing. PDF/DOCX/
+ * uploadAttachment — write original to disk; NO preprocessing. Draft CIDs
+ * (`main_chat`, `projchat-*`) are local-only until
+ * adoptDraftAttachments moves them into a real cid.
+ * PDF/DOCX/
* XLSX/PPTX extract + image grayscale happen lazily on read via
* features/file_indexer (which caches under
* <uid>/local/file_cache/<hash>/). Video is kept raw
@@ -39,7 +44,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
-import { chatAttachmentDir, userChatAttachmentsDir, userChatsDir } from '../paths';
+import { chatAttachmentDir, chatAttachmentDraftDir, userChatAttachmentsDir, userChatsDir } from '../paths';
import { createLogger } from '../logger';
import { t } from '../i18n';
import { toCompressedGrayJpeg } from '../util/image-transform';
@@ -80,6 +85,7 @@ const MAX_BYTES_VIDEO = 200 * 1024 * 1024;
const MAX_BYTES_AUDIO = 50 * 1024 * 1024;
const MAX_FILENAME_LEN = 200;
+const MAX_CONVERSATION_ATTACHMENT_INDEX_FILES = 40;
// ── Types ────────────────────────────────────────────────────────────────
@@ -129,6 +135,16 @@ function safeCid(cid: unknown): string {
return cid;
}
+const COMMANDER_DRAFT_CID = 'main_chat';
+const PROJECT_DRAFT_PREFIX = 'projchat-';
+
+export function isDraftAttachmentCid(cid: unknown): boolean {
+ return typeof cid === 'string' && (
+ cid === COMMANDER_DRAFT_CID
+ || cid.startsWith(PROJECT_DRAFT_PREFIX)
+ );
+}
+
function kindOf(ext: string): AttachmentKind {
const e = ext.toLowerCase();
if (e === PDF_EXT) return 'pdf';
@@ -152,8 +168,61 @@ function maxBytesFor(ext: string): number {
return MAX_BYTES_TEXT;
}
+function _moveFileBestEffort(from: string, to: string): void {
+ try { fs.renameSync(from, to); }
+ catch {
+ fs.copyFileSync(from, to);
+ try { fs.unlinkSync(from); } catch { /* best-effort */ }
+ }
+}
+
+function _legacyDraftCloudDir(userId: string, cid: string): string {
+ return chatAttachmentDir(userId, cid);
+}
+
+function migrateLegacyDraftCloudDir(userId: string, cid: string): void {
+ if (!isDraftAttachmentCid(cid)) return;
+ const legacy = _legacyDraftCloudDir(userId, cid);
+ if (!fs.existsSync(legacy)) return;
+
+ const local = chatAttachmentDraftDir(userId, cid);
+ let names: string[] = [];
+ try { names = fs.readdirSync(legacy).filter((n) => !n.startsWith('.')); }
+ catch { /* ignore */ }
+
+ try {
+ if (!fs.existsSync(local)) {
+ fs.mkdirSync(path.dirname(local), { recursive: true });
+ fs.renameSync(legacy, local);
+ } else {
+ fs.mkdirSync(local, { recursive: true });
+ for (const name of fs.readdirSync(legacy)) {
+ const from = path.join(legacy, name);
+ let st: fs.Stats;
+ try { st = fs.statSync(from); } catch { continue; }
+ if (!st.isFile()) continue;
+ _moveFileBestEffort(from, uniqueTarget(local, name));
+ }
+ try { fs.rmdirSync(legacy); } catch { /* best-effort */ }
+ }
+ } catch (err) {
+ log.warn(`migrate legacy draft attachments user=${userId} cid=${cid}: ${(err as Error).message}`);
+ return;
+ }
+
+ for (const name of names) notifyAttachmentDeleted(cid, name);
+}
+
+function attachmentDirForCid(userId: string, cid: string): string {
+ if (isDraftAttachmentCid(cid)) {
+ migrateLegacyDraftCloudDir(userId, cid);
+ return chatAttachmentDraftDir(userId, cid);
+ }
+ return chatAttachmentDir(userId, cid);
+}
+
function ensureDir(userId: string, cid: string): string {
- const dir = chatAttachmentDir(userId, cid);
+ const dir = attachmentDirForCid(userId, cid);
fs.mkdirSync(dir, { recursive: true });
return dir;
}
@@ -178,6 +247,14 @@ function notifyAttachmentDeleted(cid: string, name: string): void {
} catch { /* features/sync stripped */ }
}
+function notifyAttachmentDirtyIfSyncable(cid: string, name: string): void {
+ if (!isDraftAttachmentCid(cid)) notifyAttachmentDirty(cid, name);
+}
+
+function notifyAttachmentDeletedIfSyncable(cid: string, name: string): void {
+ if (!isDraftAttachmentCid(cid)) notifyAttachmentDeleted(cid, name);
+}
+
function uniqueTarget(dir: string, name: string): string {
let target = path.join(dir, name);
if (!fs.existsSync(target)) return target;
@@ -326,7 +403,7 @@ export async function uploadAttachment(
const st = fs.statSync(target);
const kind = kindOf(ext);
log.info(`upload user=${userId} cid=${safeConvId} name=${finalName} kind=${kind} bytes=${st.size}`);
- notifyAttachmentDirty(safeConvId, finalName);
+ notifyAttachmentDirtyIfSyncable(safeConvId, finalName);
return {
ok: true,
info: {
@@ -398,7 +475,7 @@ export async function importAttachmentFromPath(
const st = fs.statSync(target);
const kind = kindOf(ext);
log.info(`import user=${userId} cid=${safeConvId} name=${finalName} kind=${kind} bytes=${st.size}`);
- notifyAttachmentDirty(safeConvId, finalName);
+ notifyAttachmentDirtyIfSyncable(safeConvId, finalName);
return {
ok: true,
info: {
@@ -415,7 +492,7 @@ export function listAttachments(userId: string, cid: string): AttachmentInfo[] {
let safeConvId: string;
try { safeConvId = safeCid(cid); }
catch { return []; }
- const dir = chatAttachmentDir(userId, safeConvId);
+ const dir = attachmentDirForCid(userId, safeConvId);
let items: fs.Dirent[];
try { items = fs.readdirSync(dir, { withFileTypes: true }); }
catch { return []; }
@@ -483,7 +560,7 @@ export function deleteAttachment(userId: string, cid: string, name: string): Res
safeName = safeAttachmentName(name);
safeConvId = safeCid(cid);
} catch (err) { return { ok: false, error: (err as Error).message }; }
- const dir = chatAttachmentDir(userId, safeConvId);
+ const dir = attachmentDirForCid(userId, safeConvId);
const p = path.join(dir, safeName);
if (!fs.existsSync(p)) return { ok: false, error: 'not found' };
try { fs.unlinkSync(p); }
@@ -497,7 +574,7 @@ export function deleteAttachment(userId: string, cid: string, name: string): Res
try {
if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
} catch { /* best-effort */ }
- notifyAttachmentDeleted(safeConvId, safeName);
+ notifyAttachmentDeletedIfSyncable(safeConvId, safeName);
return { ok: true };
}
@@ -528,7 +605,7 @@ export function resolveAttachmentAbsPath(
} catch (err) {
return { ok: false, code: 'bad_input', error: (err as Error).message };
}
- const root = path.resolve(chatAttachmentDir(userId, safeConvId));
+ const root = path.resolve(attachmentDirForCid(userId, safeConvId));
const abs = path.resolve(root, safeName);
const rel = path.relative(root, abs);
if (rel.startsWith('..') || path.isAbsolute(rel)) {
@@ -671,7 +748,7 @@ export function adoptDraftAttachments(
catch (err) { return { ok: false, error: (err as Error).message }; }
if (srcSafe === dstSafe) return { ok: false, error: 'same cid' };
- const src = chatAttachmentDir(userId, srcSafe);
+ const src = attachmentDirForCid(userId, srcSafe);
if (!fs.existsSync(src)) return { ok: true, count: 0 };
const dst = chatAttachmentDir(userId, dstSafe);
let movedNames: string[] = [];
@@ -703,7 +780,7 @@ export function adoptDraftAttachments(
try { count = fs.readdirSync(dst).filter((n) => !n.startsWith('.')).length; }
catch { /* ignore */ }
for (const name of movedNames) {
- notifyAttachmentDeleted(srcSafe, name);
+ notifyAttachmentDeletedIfSyncable(srcSafe, name);
notifyAttachmentDirty(dstSafe, name);
}
log.info(`adopt user=${userId} ${srcSafe} → ${dstSafe} count=${count}`);
@@ -716,7 +793,7 @@ export async function purgeByCid(userId: string, cid: string): Promise<number> {
let safeConvId: string;
try { safeConvId = safeCid(cid); }
catch { return 0; }
- const dir = chatAttachmentDir(userId, safeConvId);
+ const dir = attachmentDirForCid(userId, safeConvId);
let count = 0;
let names: string[] = [];
try {
@@ -731,7 +808,7 @@ export async function purgeByCid(userId: string, cid: string): Promise<number> {
} catch (err) { log.warn(`purgeByCid(${cid}): ${(err as Error).message}`); }
try { await purgeFileCacheByCid(userId, safeConvId); }
catch (err) { log.warn(`purge file_cache cid=${safeConvId}: ${(err as Error).message}`); }
- for (const name of names) notifyAttachmentDeleted(safeConvId, name);
+ for (const name of names) notifyAttachmentDeletedIfSyncable(safeConvId, name);
return count;
}
@@ -762,6 +839,13 @@ export interface BuildManifestOpts {
maxImages?: number;
}
+export interface BuildConversationAttachmentIndexOpts {
+ /** Attachment names already represented by the current-turn manifest. */
+ excludeNames?: readonly string[];
+ /** Max files listed in the lightweight conversation-wide index. */
+ maxFiles?: number;
+}
+
/**
* Produce the model-facing view of the attachments for one turn:
* - text → listed with `total_chars` (cheap: one fs.readFileSync
@@ -879,6 +963,87 @@ export async function buildAttachmentManifest(
return { manifest, images, skipped, metadata: metadata() };
}
+/**
+ * Build a cheap, conversation-wide attachment directory listing. Unlike the
+ * current-turn manifest above, this is meant to survive session history trims:
+ * it lists already-uploaded files by name/path/kind, without inlining image
+ * bytes or file contents.
+ */
+export async function buildConversationAttachmentIndex(
+ userId: string,
+ cid: string,
+ opts: BuildConversationAttachmentIndexOpts = {},
+): Promise<string> {
+ let safeConvId: string;
+ try { safeConvId = safeCid(cid); }
+ catch { return ''; }
+
+ const dir = chatAttachmentDir(userId, safeConvId);
+ let dirents: fs.Dirent[];
+ try { dirents = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return ''; }
+
+ const excluded = new Set<string>();
+ for (const rawName of opts.excludeNames || []) {
+ try { excluded.add(safeAttachmentName(rawName)); }
+ catch { /* ignore invalid caller input */ }
+ }
+
+ const maxFiles = Math.max(1, Math.min(200, opts.maxFiles ?? MAX_CONVERSATION_ATTACHMENT_INDEX_FILES));
+ const files = dirents
+ .filter((d) => d.isFile() && !d.name.startsWith('.') && !excluded.has(d.name))
+ .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
+
+ if (!files.length) return '';
+
+ const entries: string[] = [];
+ for (const d of files.slice(0, maxFiles)) {
+ let nm: string;
+ try { nm = safeAttachmentName(d.name); }
+ catch { continue; }
+ const abs = path.join(dir, nm);
+ let st: fs.Stats;
+ try { st = fs.statSync(abs); }
+ catch { continue; }
+ const ext = path.extname(nm).toLowerCase();
+ const kind = kindOf(ext);
+ const attrs = [
+ `name="${escapeAttr(nm)}"`,
+ `path="${escapeAttr(abs)}"`,
+ `kind="${kind}"`,
+ `size="${st.size}"`,
+ ];
+
+ if (kind === 'text') {
+ try {
+ const meta = await statFile(userId, abs);
+ attrs.push(`total_chars="${meta.totalChars}"`);
+ } catch (err) {
+ log.warn(`attachment index statFile text failed name=${nm}: ${(err as Error).message}`);
+ }
+ } else {
+ const cached = getCachedMeta(userId, abs);
+ if (cached?.totalChars !== undefined) attrs.push(`total_chars="${cached.totalChars}"`);
+ }
+
+ if (kind === 'image') attrs.push('inline="false"');
+ if (kind === 'video' || kind === 'audio') attrs.push('model_readable="false"');
+ entries.push(`<file ${attrs.join(' ')}/>`);
+ }
+
+ if (!entries.length) return '';
+ const omitted = files.length > entries.length
+ ? `\n<omitted count="${files.length - entries.length}"/>`
+ : '';
+ return (
+ `<conversation-attachments cid="${escapeAttr(safeConvId)}">\n` +
+ '<!-- Files uploaded earlier in this conversation. Use read_file/stat_file with path for content; images/videos are not inline. -->\n' +
+ entries.join('\n') +
+ omitted +
+ '\n</conversation-attachments>'
+ );
+}
+
function escapeAttr(s: string): string {
return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index a6515f33..272329db 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -40,6 +40,7 @@ import {
import type { StateFile } from './state';
import {
GroupMessage, appendVisible, readSlice, buildReplayPrefix,
+ type ChatUseSelection,
type MarketplaceInstallRequest,
} from './visibility';
import {
@@ -68,6 +69,7 @@ import { readInstalls } from '../marketplace_installs';
import { createSkillTurnBuffer, onAgentTurnEnd, onUserMessage } from '../expert_signals/turn_hooks';
import {
compactPromptDescription,
+ listAgentOwnedSkillIds,
listSkillSpecs,
openSkillReadRoots,
resolveSkillAllowlistRefs,
@@ -185,46 +187,76 @@ function _normaliseSkillMentionText(s: string): string {
return String(s || '').toLowerCase().replace(/\s+/g, ' ').trim();
}
-function _hasSkillUseIntent(text: string): boolean {
- return /(?:使用|调用|運行|运行|执行|use|run|call|execute)/i.test(text);
+function _normalizeUseSelections(value: unknown): ChatUseSelection[] {
+ const raw = Array.isArray(value) ? value : [];
+ const out: ChatUseSelection[] = [];
+ const seen = new Set<string>();
+ for (const item of raw) {
+ if (!item || typeof item !== 'object') continue;
+ const rec = item as Record<string, unknown>;
+ const kind = rec.kind === 'skill' ? 'skill' : (rec.kind === 'connector' ? 'connector' : '');
+ if (!kind) continue;
+ const id = String(rec.id || rec.name || '').trim();
+ const name = String(rec.name || rec.id || '').trim();
+ if (!id && !name) continue;
+ const cleanId = id || name;
+ const key = `${kind}:${cleanId}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({
+ kind,
+ id: cleanId,
+ ...(name && name !== cleanId ? { name } : {}),
+ });
+ }
+ return out;
}
-function _escapeRe(s: string): string {
- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+function _selectedSkillRefs(useSelections: readonly ChatUseSelection[] | undefined): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const sel of useSelections || []) {
+ if (sel?.kind !== 'skill') continue;
+ const ref = String(sel.id || sel.name || '').trim();
+ if (!ref || seen.has(ref)) continue;
+ seen.add(ref);
+ out.push(ref);
+ }
+ return out;
}
-function _workflowMentionsSkill(workflow: string, spec: SkillAllowlistRef): boolean {
- const hay = String(workflow || '').toLowerCase();
- const refs = [spec.id, spec.name].filter((v): v is string => typeof v === 'string' && !!v.trim());
- for (const ref of refs) {
- const needle = ref.toLowerCase().trim();
- if (!needle) continue;
- if (/^[a-z0-9_.-]+$/i.test(needle)) {
- const re = new RegExp(`(^|[^a-z0-9_.-])${_escapeRe(needle)}(?=$|[^a-z0-9_.-])`, 'i');
- if (re.test(hay)) return true;
- } else if (hay.includes(needle)) {
- return true;
- }
+function _appendSkillRefs(base: readonly string[], extra: readonly string[]): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const id of [...base, ...extra]) {
+ const clean = String(id || '').trim();
+ if (!clean || seen.has(clean)) continue;
+ seen.add(clean);
+ out.push(clean);
}
- return false;
+ return out;
+}
+
+function _hasSkillUseIntent(text: string): boolean {
+ return /(?:使用|调用|運行|运行|执行|use|run|call|execute)/i.test(text);
}
-async function _runtimeSkillListForAgent(agent: agentsFeat.Agent): Promise<string[]> {
- const workflow = String(agent.workflow || '');
- if (!workflow.trim()) return [];
+async function _runtimeSkillListForAgent(uid: string, agent: agentsFeat.Agent): Promise<string[]> {
// Owner-scoped: a private (`ownerAgent`) skill of another agent never
// resolves here, so it can't enter this agent's runtime skill list.
const specs = await listSkillSpecs({ forAgentId: agent.agent_id }).catch((err) => {
- log.warn(`skill workflow filter list failed agent=${agent.agent_id}: ${(err as Error).message}`);
+ log.warn(`skill allowlist resolution failed agent=${agent.agent_id}: ${(err as Error).message}`);
return [] as SkillAllowlistRef[];
});
- if (!specs.length) return [];
- const refs = Array.isArray(agent.skill_list) ? agent.skill_list : specs.map((s) => s.id);
- if (!refs.length) return [];
- const allowedIds = new Set(resolveSkillAllowlistRefs(specs, refs).ids);
- return specs
- .filter((s) => allowedIds.has(s.id) && _workflowMentionsSkill(workflow, s))
- .map((s) => s.id);
+ const refs = Array.isArray(agent.skill_list) ? agent.skill_list : [];
+ const resolved = specs.length && refs.length
+ ? resolveSkillAllowlistRefs(specs, refs).ids
+ : refs.filter((id): id is string => typeof id === 'string' && !!id.trim());
+ const owned = await listAgentOwnedSkillIds(uid, agent.agent_id).catch((err) => {
+ log.warn(`agent-owned skill scan failed agent=${agent.agent_id}: ${(err as Error).message}`);
+ return [] as string[];
+ });
+ return _appendSkillRefs(resolved, owned);
}
async function _findDisabledSkillUseRequest(uid: string, text: string):
@@ -352,6 +384,7 @@ interface QueueItem {
* LLM payload so commander / agent can see file paths + kinds and
* extract values for `inputs_schema` (especially `type=file` fields). */
attachments?: string[];
+ useSelections?: ChatUseSelection[];
/** Shadow-tap marker: this turn was triggered NOT because the actor was
* a declared recipient (`to` includes them), but because the bus woke
* them as an observer (e.g. commander wakes on every agent → user reply
@@ -617,6 +650,7 @@ export interface EnqueueParams {
text: string;
model_text?: string;
attachments?: string[];
+ use_selections?: ChatUseSelection[];
produced?: string[];
form?: ChatFormPayload;
created_agents?: Array<{ agent_id: string; name: string; kind?: 'created' | 'updated' }>;
@@ -835,18 +869,29 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
else to = [USER_ID];
}
- // Floor reset: while handed off to an agent, a user message that resolves to
- // the commander means the user explicitly addressed the commander (the no-`@`
- // default would have been the floor agent) — or the floor agent became
- // unroutable and we fell back to commander. Either way the hand-off is over;
- // return the floor to the commander. A one-shot `@<otherAgent>` (to does NOT
- // contain commander) leaves the floor untouched.
- if (fromKind === 'user' && floorRecipient && to.includes(COMMANDER_ID)) {
- try {
- await setActiveRecipient(uid, cid, COMMANDER_ID);
- await markOrchestrationInterrupted(uid, cid, text, floorRecipient);
+ // Floor update: a user-visible recipient choice is the conversation floor.
+ // Manual @ / chip selection should stick until the user switches again, the
+ // agent hands back, or the commander performs a new hand_off_to.
+ if (fromKind === 'user') {
+ const agentRecipients = to.filter((id) => !RESERVED_IDS.has(id));
+ if (to.includes(COMMANDER_ID)) {
+ if (floorRecipient) {
+ try {
+ await setActiveRecipient(uid, cid, COMMANDER_ID);
+ await markOrchestrationInterrupted(uid, cid, text, floorRecipient);
+ }
+ catch (err) { log.warn(`floor reset failed cid=${cid}: ${(err as Error).message}`); }
+ }
+ } else if (agentRecipients.length === 1) {
+ const nextFloor = agentRecipients[0];
+ try {
+ await setActiveRecipient(uid, cid, nextFloor);
+ if (floorRecipient && floorRecipient !== nextFloor) {
+ await markOrchestrationInterrupted(uid, cid, text, floorRecipient);
+ }
+ }
+ catch (err) { log.warn(`floor switch failed cid=${cid}: ${(err as Error).message}`); }
}
- catch (err) { log.warn(`floor reset failed cid=${cid}: ${(err as Error).message}`); }
}
// Auto-add any non-reserved recipient that isn't already a member.
@@ -939,6 +984,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
const msgId = genId12();
const ts = nowIso();
const mentions = parseMentions(rewrittenText);
+ const useSelections = _normalizeUseSelections(params.use_selections);
const msg: GroupMessage = {
id: msgId, ts, from: fromActorId, to,
@@ -947,6 +993,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
text: rewrittenText,
...(params.model_text && params.model_text.trim() ? { model_text: params.model_text } : {}),
...(params.attachments && params.attachments.length ? { attachments: params.attachments } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
...(params.produced && params.produced.length ? { produced: params.produced } : {}),
...(params.form ? { form: params.form } : {}),
...(params.created_agents && params.created_agents.length ? { created_agents: params.created_agents } : {}),
@@ -1007,6 +1054,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
fromActorId,
llmPayload: composeLlmTurnPayload(fromActorId, msg),
...(msg.attachments && msg.attachments.length ? { attachments: msg.attachments.slice() } : {}),
+ ...(msg.use_selections && msg.use_selections.length ? { useSelections: msg.use_selections.slice() } : {}),
});
const wake = w.wake; w.wake = null;
wake?.();
@@ -1019,7 +1067,7 @@ async function _enqueueBody(params: EnqueueParams, state: CidState): Promise<Gro
// the DAG demands. Adding a shadow-tap on top was double-firing: it
// created an extra commander turn whose only output (per prompt) was an
// empty final (silently dropped), wasting one LLM call per agent reply.
- // For non-plan flows (one-shot @-mention dispatch), commander has no
+ // For non-plan flows (direct @-mention dispatch), commander has no
// orchestration role at all — letting it stay asleep keeps the chat
// clean and avoids prompt-driven mistakes (the model second-guessing the
// agent's form / re-dispatching for "polish").
@@ -1536,6 +1584,21 @@ async function runActorTurn(
}
}
+ // Conversation-level attachment index. The current-turn manifest above is
+ // stored in session history, so after many tool-loop turns it can be trimmed
+ // away. Re-list persisted conversation attachments every turn as cheap path
+ // metadata so an agent can recover files uploaded earlier without relying on
+ // the first attachment-bearing message still being in context.
+ try {
+ const { buildConversationAttachmentIndex } = await import('../chat_attachments');
+ const index = await buildConversationAttachmentIndex(uid, cid, {
+ excludeNames: item.attachments || [],
+ });
+ if (index) messageText = `${index}\n${messageText}`;
+ } catch (err) {
+ log.warn(`conversation attachment index build failed cid=${cid} actor=${actor.id}: ${(err as Error).message}`);
+ }
+
if (isCommander && item.fromActorId === USER_ID) {
const disabledSkill = await _findDisabledSkillUseRequest(uid, item.llmPayload);
if (disabledSkill) {
@@ -1561,6 +1624,8 @@ async function runActorTurn(
let systemPrompt: string;
let extraTools: AgentTool[] = [];
let skillList: string[] | undefined;
+ const selectedSkillRefs = _selectedSkillRefs(item.useSelections);
+ const forceOpenSkillRefs: string[] = selectedSkillRefs;
// CLI-backed agents fetch the spec but skip systemPrompt / skillList /
// extraTools — the LLM stream is replaced below by `runCliAgentTurn`.
// Hoisted here so the branch below can read it without re-fetching.
@@ -1627,10 +1692,13 @@ async function runActorTurn(
systemPrompt = ''; // unused on CLI path
} else {
systemPrompt = await buildAgentInGroupSystemPrompt(uid, agent, workingDir);
- // Runtime skills are the intersection of the agent's whitelist and
- // workflow references. A broad whitelist is authoring metadata; only
- // skills the workflow actually names should reach the prompt.
- skillList = await _runtimeSkillListForAgent(agent);
+ // Runtime skills start from the agent-authored skill_list and append
+ // agent-owned private/self-evolved skills. User-explicit picker choices
+ // are appended at the tail even if they are outside the authored list.
+ skillList = _appendSkillRefs(
+ await _runtimeSkillListForAgent(uid, agent),
+ selectedSkillRefs,
+ );
extraTools = [buildSkillSearchTool(uid)];
}
}
@@ -1874,6 +1942,7 @@ async function runActorTurn(
attachmentMetadata: turnAttachmentMetadata,
...(extraTools.length ? { extraTools } : {}),
...(skillList !== undefined ? { skillList } : {}),
+ ...(forceOpenSkillRefs.length ? { forceOpenSkillRefs } : {}),
// Skills are NOT project-scoped this round; agent skillList still
// gates in-process agents' rendered skills and SkillStore.
})) {
@@ -2083,18 +2152,14 @@ async function runActorTurn(
const target = await agentsFeat.getAgent(editId);
if (!target) {
workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Agent edit failed: agent not found (id=${editId}).</span>`;
- } else if (target.source !== 'custom' && !false) {
+ } else if (target.source !== 'custom') {
workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ Marketplace agents can't be edited from the main chat; fork one in the right-hand detail panel and edit there.</span>`;
} else if (agentsFeat.isCliAgent(target)) {
workingText = `${workingText}\n\n<span style="color:var(--danger)">⚠️ External agents can only be edited from the right-hand detail panel.</span>`;
} else {
- // `updateAgentSpec` dispatches: custom → updateCustomAgent,
- // marketplace + dev → agents_dev.updateBuiltinAgentSpec
- // (which writes the local marketplace install dir). The
- // dev-env source guard above is what makes the marketplace
- // branch reachable; the direct `updateCustomAgent` call this
- // replaces would short-circuit to null because the custom
- // agent.json doesn't exist for marketplace ids.
+ // The open-source build only permits main-chat edits for
+ // user-owned custom agents. Marketplace/external agents are
+ // edited through their detail surfaces or forked first.
const updated = await agentsFeat.updateAgentSpec(editId, fields);
if (updated) {
createdAgents.push({ agent_id: updated.agent_id, name: updated.name, kind: 'updated' });
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 443810ff..bec7556b 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -75,7 +75,7 @@ export async function runtimeStatus(
* if subscribe runs after send, those first events are lost. */
export const subscribeBus = subscribe;
-import type { GroupMessage } from './visibility';
+import type { ChatUseSelection, GroupMessage } from './visibility';
import {
type ChatFormPayload, encodeSubmission, buildMention,
} from './router';
@@ -96,12 +96,13 @@ export interface SendInput {
text: string;
model_text?: string;
attachments?: string[];
+ use_selections?: ChatUseSelection[];
}
export async function send(
input: SendInput,
): Promise<{ ok: boolean; msg?: GroupMessage; error?: string }> {
- const { userId, cid, text, model_text, attachments } = input;
+ const { userId, cid, text, model_text, attachments, use_selections } = input;
if (!safeId(cid)) return { ok: false, error: 'invalid cid' };
if (!text || !text.trim()) return { ok: false, error: 'empty message' };
await seedReservedActors(userId, cid);
@@ -124,6 +125,7 @@ export async function send(
text,
...(model_text && model_text.trim() ? { model_text } : {}),
...(attachments && attachments.length ? { attachments: [...attachments] } : {}),
+ ...(use_selections && use_selections.length ? { use_selections } : {}),
});
return { ok: true, msg };
} catch (err) {
diff --git a/src/main/features/group_chat/visibility.ts b/src/main/features/group_chat/visibility.ts
index 6bcf360f..fc9e5a8d 100644
--- a/src/main/features/group_chat/visibility.ts
+++ b/src/main/features/group_chat/visibility.ts
@@ -26,6 +26,12 @@ import { createLogger } from '../../logger';
const log = createLogger('group_chat.visibility');
+export interface ChatUseSelection {
+ kind: 'skill' | 'connector';
+ id: string;
+ name?: string;
+}
+
export interface GroupMessage {
/** Stable per-message id (not jsonl line index). Used by visibility +
* dedupe. */
@@ -48,6 +54,10 @@ export interface GroupMessage {
model_text?: string;
/** Attachment filenames (only meaningful for user messages). */
attachments?: string[];
+ /** Structured composer selections captured at send time. The text still
+ * carries the human-readable "use X" wording; this preserves the internal
+ * id so agent skill allowlists can include explicit user choices. */
+ use_selections?: ChatUseSelection[];
/** Absolute paths produced by local-exec tools during this turn (only on
* commander/agent messages). */
produced?: string[];
diff --git a/src/main/features/recycle_bin.ts b/src/main/features/recycle_bin.ts
index 2de4d221..3d01ac12 100644
--- a/src/main/features/recycle_bin.ts
+++ b/src/main/features/recycle_bin.ts
@@ -272,6 +272,10 @@ function editConversationRootFromRelPath(relPath: string): { kind: 'agent' | 'sk
if (chat && safeId(chat[2])) return { kind: chat[1] as 'agent' | 'skill', id: chat[2] };
const session = /^cloud\/sessions\/(agent|skill)-(.+)\.jsonl$/.exec(relPath);
if (session && safeId(session[2])) return { kind: session[1] as 'agent' | 'skill', id: session[2] };
+ const sessionToolResults = /^cloud\/sessions\/(agent|skill)-(.+?)\.tool-results(?:\/|$)/.exec(relPath);
+ if (sessionToolResults && safeId(sessionToolResults[2])) {
+ return { kind: sessionToolResults[1] as 'agent' | 'skill', id: sessionToolResults[2] };
+ }
return null;
}
@@ -353,6 +357,22 @@ async function collectCloudFilesMatching(uid: string, relDir: string, predicate:
.filter(isSafeCloudRelPath);
}
+async function collectCloudFilesUnderMatchingDirs(uid: string, relDir: string, predicate: (name: string) => boolean): Promise<string[]> {
+ const safeRelDir = relDir.replace(/\/+$/, '');
+ if (!isSafeCloudRelPath(`${safeRelDir}/__probe__`)) return [];
+ let entries: fs.Dirent[] = [];
+ try {
+ const abs = resolveCloudRelPath(userCloudRoot(uid), safeRelDir);
+ entries = await fsp.readdir(abs, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const batches = await Promise.all(entries
+ .filter((entry) => entry.isDirectory() && predicate(entry.name))
+ .map((entry) => collectCloudFilesUnder(uid, `${safeRelDir}/${entry.name}`)));
+ return batches.flat();
+}
+
export async function collectCloudEntryFiles(uid: string, relPath: string): Promise<string[]> {
if (!isSafeCloudRelPath(relPath)) return [];
try {
@@ -390,11 +410,17 @@ async function expandRecycleRelPaths(uid: string, relPaths: string[]): Promise<s
}
const commanderSession = `cloud/sessions/gconv-${cid}.jsonl`;
if ((await collectCloudEntryFiles(uid, commanderSession)).length) out.add(commanderSession);
+ for (const relPath of await collectCloudFilesUnder(uid, `cloud/sessions/gconv-${cid}.tool-results`)) out.add(relPath);
for (const relPath of await collectCloudFilesMatching(
uid,
'cloud/sessions',
(name) => name.startsWith(`gmember-${cid}-`) && name.endsWith('.jsonl'),
)) out.add(relPath);
+ for (const relPath of await collectCloudFilesUnderMatchingDirs(
+ uid,
+ 'cloud/sessions',
+ (name) => name.startsWith(`gmember-${cid}-`) && name.endsWith('.tool-results'),
+ )) out.add(relPath);
}
for (const pid of projectIds) {
for (const relPath of await collectCloudFilesUnder(uid, `cloud/projects/${pid}`)) out.add(relPath);
@@ -1599,6 +1625,7 @@ export async function createAppRecycleBatchForAgent(
`cloud/agents/${agentId}`,
`cloud/chats/agent/${agentId}`,
`cloud/sessions/agent-${agentId}.jsonl`,
+ `cloud/sessions/agent-${agentId}.tool-results`,
]);
return createAppRecycleBatch(uid, Array.from(rels), { kind: 'agent' });
}
@@ -1612,6 +1639,7 @@ export async function createAppRecycleBatchForSkill(
`cloud/skills/${skillId}`,
`cloud/chats/skill/${skillId}`,
`cloud/sessions/skill-${skillId}.jsonl`,
+ `cloud/sessions/skill-${skillId}.tool-results`,
], { kind: 'skill' });
}
diff --git a/src/main/features/sessions_sweep.ts b/src/main/features/sessions_sweep.ts
index ed083ffd..c674b122 100644
--- a/src/main/features/sessions_sweep.ts
+++ b/src/main/features/sessions_sweep.ts
@@ -38,7 +38,7 @@ import * as path from 'node:path';
import { userSessionsDir, userLocalSessionsDir } from '../paths';
import { createLogger } from '../logger';
import { listConversations } from './chats';
-import { isEphemeralSessionId } from '../model/core-agent/session-store';
+import { isEphemeralSessionId, toolResultsDirForSession } from '../model/core-agent/session-store';
const log = createLogger('sessions-sweep');
@@ -124,6 +124,7 @@ async function sweepCloud(userId: string, result: SweepResult): Promise<void> {
if (!reason) continue;
try {
await fsp.unlink(path.join(dir, name));
+ await fsp.rm(toolResultsDirForSession(userId, sid), { recursive: true, force: true });
result[reason]++;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
@@ -153,6 +154,8 @@ async function sweepLocalByAge(userId: string, result: SweepResult, now: number)
if (now - st.mtimeMs <= EPHEMERAL_AGE_MS) continue;
try {
await fsp.unlink(full);
+ const sid = name.slice(0, -'.jsonl'.length);
+ await fsp.rm(toolResultsDirForSession(userId, sid), { recursive: true, force: true });
result.local_aged_out++;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
diff --git a/src/main/features/users.ts b/src/main/features/users.ts
index 187fd2c1..5fe6ad68 100644
--- a/src/main/features/users.ts
+++ b/src/main/features/users.ts
@@ -276,10 +276,11 @@ export function activateUser(uid: string): void {
ensureUserLayout(uid);
- // Purge tool-results/ entries older than 7 days. Best-effort (nothrow);
+ // Purge machine-local tool-results/ entries older than 7 days. Best-effort (nothrow);
// failure here should not block uid activation. See util/tool-result-cap.ts
- // — these are oversized tool outputs persisted to disk with a
- // <persisted-output> reference in the tool_result that went to the LLM.
+ // — these are oversized CLI/local-agent tool outputs persisted to disk with a
+ // <persisted-output> reference. Resumable core-agent session refs live next to
+ // cloud/sessions/<sid>.jsonl and are cleaned with the session lifecycle.
// We only clean on activate (not on session end) because the individual
// files are small and the 7-day window is comfortably above typical
// conversation lifetimes.
diff --git a/src/main/index.ts b/src/main/index.ts
index e47b6cdd..0a16ce5f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -62,8 +62,10 @@ protocol.registerSchemesAsPrivileged([
scheme: 'kb-file',
privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true },
},
- // `chat-media://cid/<encCid>/<encName>` — serves image + video bytes out
- // of the active user's `<uid>/cloud/chat_attachments/<cid>/`. `stream:true`
+ // `chat-media://cid/<encCid>/<encName>` — serves image + video bytes for a
+ // cid attachment. Sent attachments resolve under cloud/chat_attachments/;
+ // composer-only draft cids resolve under local/chat_attachment_drafts/.
+ // `stream:true`
// only enables a streamed Response body — it does NOT make Chromium issue
// byte-range requests on its own; the handler must advertise
// `Accept-Ranges: bytes` and serve `206` itself (see `serveFileRange`).
@@ -697,9 +699,10 @@ function registerKbFileProtocol(): void {
});
}
-// `chat-media://cid/<encCid>/<encName>` — streams a single attachment file
-// out of the active user's `<uid>/cloud/chat_attachments/<cid>/` for the
-// renderer's `<img>` / `<video>` tags. The two-segment path (fixed host +
+// `chat-media://cid/<encCid>/<encName>` — streams a single attachment file for
+// the renderer's `<img>` / `<video>` tags. Sent attachments resolve under
+// cloud/chat_attachments/; composer-only draft cids resolve under local drafts.
+// The two-segment path (fixed host +
// cid + name) sidesteps URL-parser divergence the way `kb-file` does.
//
// All the safety work (name + cid validation, path-traversal guard, file
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index a56a0c2d..be39d879 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -1054,12 +1054,17 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
// ── Group chat (replaces legacy conversations.send / .stream / .markFormSubmitted) ──
- 'groupChat.send': async ({ cid, content, attachments }, ctx) => {
+ 'groupChat.send': async ({ cid, content, attachments, use_selections }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
const text = (content || '').trim();
if (!text) throw new Error('empty message');
const atts = Array.isArray(attachments) ? attachments.filter((n: any) => typeof n === 'string') : [];
- return groupChat.send({ userId: ctx.userId, cid, text, ...(atts.length ? { attachments: atts } : {}) });
+ const useSelections = Array.isArray(use_selections) ? use_selections : [];
+ return groupChat.send({
+ userId: ctx.userId, cid, text,
+ ...(atts.length ? { attachments: atts } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ });
},
'groupChat.abort': async ({ cid }, ctx) => {
@@ -1193,11 +1198,13 @@ const invokeHandlers: Record<string, InvokeHandler> = {
'conversations.attachments.delete': async ({ cid, name }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
- await recycleBin.createAppRecycleBatchForCloudEntry(
- ctx.userId,
- `cloud/chat_attachments/${cid}/${name || ''}`,
- 'attachment',
- );
+ if (!chatAttachments.isDraftAttachmentCid(cid)) {
+ await recycleBin.createAppRecycleBatchForCloudEntry(
+ ctx.userId,
+ `cloud/chat_attachments/${cid}/${name || ''}`,
+ 'attachment',
+ );
+ }
return chatAttachments.deleteAttachment(ctx.userId, cid, name || '');
},
@@ -2374,7 +2381,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
// unexpected throws.
const streamHandlers: Record<string, StreamHandler> = {
- 'conversations.sendStream': async function* ({ cid, content, attachments }, ctx, signal) {
+ 'conversations.sendStream': async function* ({ cid, content, attachments, use_selections }, ctx, signal) {
if (!safeId(cid)) {
yield { type: 'error', text: 'invalid cid' };
return;
@@ -2385,6 +2392,7 @@ const streamHandlers: Record<string, StreamHandler> = {
return;
}
const atts = Array.isArray(attachments) ? attachments.filter((n: any) => typeof n === 'string') : [];
+ const useSelections = Array.isArray(use_selections) ? use_selections : [];
// Legacy `conversations.stream` is now a thin wrapper around the
// group_chat bus. Subscribe to the bus directly BEFORE calling
// `groupChat.send` — `send` internally wakes the recipient worker
@@ -2424,6 +2432,7 @@ const streamHandlers: Record<string, StreamHandler> = {
sendRes = await groupChat.send({
userId: ctx.userId, cid, text,
...(atts.length ? { attachments: atts } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
});
} catch (err) {
sendErr = err;
diff --git a/src/main/model/client.ts b/src/main/model/client.ts
index a86fe71c..31b49008 100644
--- a/src/main/model/client.ts
+++ b/src/main/model/client.ts
@@ -94,6 +94,9 @@ export interface ChatOptions {
* `skill_list: []`. Sourced from the target agent's `skill_list` field
* (see `features/agents.ts`). */
skillList?: string[];
+ /** User-explicit skill refs selected in the composer. Open/global skills
+ * named here may be rendered even when an agent skill allowlist is active. */
+ forceOpenSkillRefs?: readonly string[];
/** Project-scope skill allowlist applied ONLY to the System A render
* block (`getSystemPromptBlock`). Resolved from the conversation's
* project bindings at the top of `runTurn`. The runner intersects this
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index e10f0b83..da365624 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -709,6 +709,7 @@ export function modelTurnContextForLog(input: {
streamIdleTimeout?: number;
maxToolLoops?: number;
skillList?: readonly string[];
+ forceOpenSkillRefs?: readonly string[];
projectAllowedSkillIds?: readonly string[];
extraTools?: readonly AgentTool[];
extraRoots?: readonly string[];
@@ -757,6 +758,7 @@ export function modelTurnContextForLog(input: {
max_tool_loops: input.maxToolLoops,
skill_list_mode: input.skillList === undefined ? 'all' : 'allowlist',
skill_list_count: input.skillList === undefined ? undefined : input.skillList.length,
+ force_open_skill_count: input.forceOpenSkillRefs?.length,
project_skill_allowlist_count: input.projectAllowedSkillIds?.length,
extra_tool_count: input.extraTools?.length || 0,
extra_root_count: input.extraRoots?.length || 0,
@@ -793,6 +795,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
maxToolLoops,
abortSignal = null,
skillList,
+ forceOpenSkillRefs,
projectAllowedSkillIds,
extraTools,
extraRoots,
@@ -829,6 +832,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
streamIdleTimeout,
maxToolLoops,
skillList,
+ forceOpenSkillRefs,
projectAllowedSkillIds,
extraTools,
extraRoots,
@@ -994,6 +998,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
...(turnId ? { turnId } : {}),
...(projectId ? { projectId } : {}),
...(skillList !== undefined ? { skillList } : {}),
+ ...(forceOpenSkillRefs && forceOpenSkillRefs.length ? { forceOpenSkillRefs } : {}),
...(projectAllowedSkillIds !== undefined ? { projectAllowedSkillIds } : {}),
...(extraTools && extraTools.length ? { extraTools } : {}),
...(extraRoots && extraRoots.length ? { extraRoots } : {}),
@@ -1037,6 +1042,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
streamIdleTimeout,
maxToolLoops,
skillList,
+ forceOpenSkillRefs,
projectAllowedSkillIds,
extraTools,
extraRoots,
diff --git a/src/main/model/core-agent/file-tools.ts b/src/main/model/core-agent/file-tools.ts
index 21a59d85..473a74ee 100644
--- a/src/main/model/core-agent/file-tools.ts
+++ b/src/main/model/core-agent/file-tools.ts
@@ -265,37 +265,7 @@ function createReadFileTool(opts: FileToolsOpts): AgentTool {
name: 'read_file',
executionMode: 'parallel',
description:
- 'Read a slice of a file\'s text by absolute path.\n'
- + '\n'
- + 'Parameters:\n'
- + ' path — required. Must be inside the current workspace or this conversation\'s attachment dir.\n'
- + ' charStart — 0-based inclusive start offset. Default 0.\n'
- + ' charEnd — 0-based exclusive end offset. Default = total_chars (end of file).\n'
- + '\n'
- + 'Response header:\n'
- + ' <file path="..." kind="..." total_chars="N" covered="a-b" lines="x-y"> … </file>\n'
- + ' `covered` echoes the clamped [charStart, charEnd) actually returned; `lines` is the\n'
- + ' absolute line range shown.\n'
- + '\n'
- + 'Body format:\n'
- + ' Each line is prefixed with its absolute line number and a tab: `<n>\\t<line text>`.\n'
- + ' The `<n>\\t` prefix is a DISPLAY annotation, NOT part of the file — when you pass text\n'
- + ' back to `edit_file` as old_string, use the raw line WITHOUT the number+tab prefix.\n'
- + '\n'
- + 'How to use:\n'
- + ' - Whole file: omit charStart/charEnd. Header tells you total_chars.\n'
- + ' - Continue: set charStart = previous response\'s covered end.\n'
- + ' - total_chars is usually already in the `<attachments>` manifest or in a prior\n'
- + ' `search_files` hit — use it to plan charStart/charEnd.\n'
- + ' - If a PDF or modern Office file has never been read/stated before, this tool returns E_NEED_STAT.\n'
- + ' Call `stat_file(path)` first to trigger extraction, then come back.\n'
- + ' - Legacy Office files (.doc/.xls/.ppt) return E_UNSUPPORTED_FILE; ask the user\n'
- + ' for a .docx/.xlsx/.pptx export if the content is required.\n'
- + ' - For image kind, no range applies; a compressed grayscale JPEG is returned inline\n'
- + ' as a user-turn image.\n'
- + '\n'
- + 'The server does NOT truncate and has NO size cap — you receive exactly the range you ask for.\n'
- + 'You are responsible for your own context budget.',
+ 'Read a file or character slice inside the visible workspace/attachments. Text lines are returned as "<line>\\t<text>"; do not include that prefix in edit_file old_string. Use charStart/charEnd for large files. For new PDF/Office files, stat_file may be required first; images return an inline compressed preview.',
inputSchema: {
type: 'object',
properties: {
@@ -444,21 +414,7 @@ function createStatFileTool(opts: FileToolsOpts): AgentTool {
return {
name: 'stat_file',
description:
- 'Ensure a file\'s text is extracted and return its `total_chars`. Use this when the\n'
- + '`<attachments>` manifest or a `search_files` result did NOT already include\n'
- + '`total_chars` for the file — typically for a PDF or modern Office file that has never been read.\n'
- + '\n'
- + 'Parameters:\n'
- + ' path — required. Absolute path inside workspace or current attachment dir.\n'
- + '\n'
- + 'Response:\n'
- + ' <file path="..." kind="text|pdf|docx|spreadsheet|presentation" total_chars="N"/>\n'
- + '\n'
- + 'Notes:\n'
- + ' - Skip this call when total_chars is already provided — go straight to read_file.\n'
- + ' - This tool does pdfjs / mammoth / OOXML extraction; first call on a large\n'
- + ' document may take a few seconds, subsequent read_file calls hit the cache instantly.\n'
- + ' - Returns E_NO_TEXT for image kind; images are displayed via read_file directly.',
+ 'Extract/cache readable text metadata and return total_chars for a visible file. Use before first read_file when attachments/search_files did not provide total_chars, especially for PDF/Office. Skip when total_chars is already known. Images return E_NO_TEXT; use read_file for image previews.',
inputSchema: {
type: 'object',
properties: {
@@ -533,14 +489,7 @@ function createOcrFileTool(opts: FileToolsOpts): AgentTool {
name: 'ocr_file',
executionMode: 'sequential',
description:
- 'Run local OCR on visual text in a file and return Markdown. Use this when read_file/stat_file cannot recover text from visual content: scanned PDFs, image-only PDF pages, screenshots, photos of documents, or text embedded in images. For normal text PDFs/Office files, use stat_file/read_file first. For mixed PDFs, combine read_file text with ocr_file visual text.\n'
- + '\n'
- + 'Parameters:\n'
- + ' path — required. Absolute path inside the current workspace or this conversation\'s attachment dir.\n'
- + ' pages — optional for PDFs. Page list/ranges like "1-3,5". Omit to OCR all pages.\n'
- + '\n'
- + 'Supported inputs in this version: PDF pages and image files (.png/.jpg/.jpeg/.webp/.gif). Office documents should be read with read_file; embedded-image OCR for Office is not supported yet.\n'
- + 'The OCR engine is local RapidOCR + ONNXRuntime and does not consume cloud model credits. If the local OCR runtime is not installed, this tool installs it into Orkas\'s managed runtime directory. If this tool returns an E_OCR_* error, do not try to install or repair OCR dependencies with bash/pip/uv; report the tool error and process log.',
+ 'Run local OCR on visible PDFs/images and return Markdown. Use for scanned PDFs, screenshots, photos, or image-only pages when read_file/stat_file cannot recover visual text. For normal text PDFs/Office, use stat_file/read_file first. If E_OCR_* occurs, report it; do not repair OCR with shell package installs.',
inputSchema: {
type: 'object',
properties: {
@@ -675,23 +624,7 @@ function createSearchFilesTool(opts: FileToolsOpts): AgentTool {
name: 'search_files',
executionMode: 'parallel',
description:
- 'Discover files when you do NOT already have the path. Scans the active workspace +\n'
- + 'the current conversation\'s attachment dir.\n'
- + 'Query forms:\n'
- + ' • substring (case-insensitive): "contract" matches "Contract_v2.pdf"\n'
- + ' • glob: "*.pdf", "design*"\n'
- + 'Returns each hit with path/name/size/mtime/ext/source. If the file\'s text has\n'
- + 'already been extracted (cache hit), `total_chars` is also included — use it to\n'
- + 'plan read_file without an extra stat_file round-trip. If `total_chars` is absent,\n'
- + 'you need `stat_file(path)` before your first read_file on that file.\n'
- + 'This tool does NOT trigger extract — it stays cheap even over large directories.\n'
- + 'Use this when:\n'
- + ' • the user names a file that is NOT in the current <attachments> block — try here\n'
- + ' before telling them the file is missing; the workspace is in scope too\n'
- + ' • the user refers to a file by a fuzzy phrase ("the contract")\n'
- + ' • exploring the workspace for files matching a pattern\n'
- + 'Do NOT call this on a filename that is already listed in <attachments> — the `path`\n'
- + 'attribute there is the authoritative absolute path; feed it straight to `read_file`.',
+ 'Find files by substring or glob when the path is unknown. Scans visible workspace/attachments and returns path/name/size/mtime/ext/source; cached total_chars may be included. Does not extract content. If a file is already listed in <attachments>, use that path directly.',
inputSchema: {
type: 'object',
properties: {
@@ -851,7 +784,7 @@ function createGrepFilesTool(opts: FileToolsOpts): AgentTool {
properties: {
pattern: { type: 'string', description: 'Pattern to search for.' },
regex: { type: 'boolean', description: 'Default false — treat pattern as a case-insensitive substring.' },
- glob: { type: 'string', description: 'Optional. Limit the search to files matching this glob. No "/" → match the basename at any depth (e.g. "*.ts", "*.{vue}"); with "/" → match the path relative to its root (e.g. "src/**", "src/**/*.ts"). Use it to cut noise + tokens on large projects.' },
+ glob: { type: 'string', description: 'Optional file glob. No "/" matches basenames; with "/" matches relative paths, e.g. "src/**/*.ts".' },
output_mode: { type: 'string', enum: ['content', 'files', 'count'], description: 'content (default): one line per match. files: just the file paths that contain a match — much cheaper when you only need which files. count: number of matches per file.' },
},
required: ['pattern'],
@@ -1072,13 +1005,7 @@ function createListFilesTool(opts: FileToolsOpts): AgentTool {
name: 'list_files',
executionMode: 'parallel',
description:
- 'List the entries (files and subdirectories) of a directory by absolute path.\n'
- + '\n'
- + 'Parameters:\n'
- + ' path — required. Must be inside the current workspace, this conversation\'s\n'
- + ' attachment dir, or a user-granted folder.\n'
- + '\n'
- + 'Each line is `d <name>` for a directory or `f <name>` for a file.',
+ 'List files and subdirectories in a visible directory. Output lines are "d <name>" for directories and "f <name>" for files.',
inputSchema: {
type: 'object',
properties: {
diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.ts
index 4f2f4db6..1382a431 100644
--- a/src/main/model/core-agent/local-tools.ts
+++ b/src/main/model/core-agent/local-tools.ts
@@ -1883,17 +1883,7 @@ function createInteractiveCliStartTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'interactive_cli_start',
description:
- 'Start a local CLI command as a live interactive session with persistent stdin/stdout. ' +
- 'The model decides per command: use this instead of bash for any local CLI, built-in or external, ' +
- 'when the command is expected to wait for live stdin from the user, such as OAuth login, ' +
- 'verification/device codes, password prompts, yes/no confirmations, setup wizards, or other interactive prompts. ' +
- 'Set `purpose` to a short user-facing phrase that explains what the user is being asked to do, for example "Authorize Google Workspace access". ' +
- 'For OAuth login commands, prefer the browser/callback flow and do not pass --no-browser or --no-launch-browser unless the user explicitly says a browser flow is unavailable. ' +
- 'Do not use this for discovery, validation, --help, install checks, commands that merely print errors, or any command expected to finish without user input; use bash for those. ' +
- 'Do not ask the user to paste authorization codes, passwords, tokens, or other secrets into chat. ' +
- 'When user input is needed, tell the user to enter it in the Orkas interactive CLI panel; that input goes directly to the CLI and is not part of chat history. ' +
- 'For ordinary one-shot commands that do not need later stdin, use bash instead. ' +
- 'The session is pipe-backed, not a full terminal TTY, so avoid curses/full-screen TUI programs.',
+ 'Start a local CLI command that needs live user stdin, such as OAuth/device-code login, password prompts, confirmations, or setup wizards. Use bash for one-shot commands, --help, validation, and installs. Tell users to enter secrets/codes in the interactive CLI panel, not chat. Avoid full-screen TUI programs.',
inputSchema: {
type: 'object',
properties: {
@@ -2070,13 +2060,7 @@ function createWriteFileTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'write_file',
description:
- 'Write content to a file. Use this for workspace artefacts the user wants to keep ' +
- '(notes, source code, markdown, CSV, etc.). Creates parent directories as needed. ' +
- 'If the target path already exists and was not written by you earlier in this turn, ' +
- 'the basename is automatically suffixed (`-2 / -3 / ...`) to avoid clobbering, and ' +
- 'the rename is surfaced in a `<file-renamed>` block in the tool result. Always read ' +
- 'that block (when present) and use the saved path verbatim in any subsequent read or ' +
- 'message to the user.',
+ 'Write a kept workspace artifact such as source, notes, markdown, or CSV. Creates parents. On collision with a file not written by you this turn, the basename is auto-suffixed and reported in <file-renamed>; use that final path afterward.',
inputSchema: coreWriteFileTool.inputSchema,
async execute(input, ctx) {
if (!getLocalExecGranted()) return deniedResult();
@@ -2129,23 +2113,7 @@ function createEditFileTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'edit_file',
description:
- 'Replace `old_string` with `new_string` inside an existing text file. ' +
- 'Cheaper and safer than rewriting the whole file via `write_file`; the rest of the file is preserved verbatim.\n' +
- '\n' +
- 'Parameters:\n' +
- ' path — required. Absolute or workspace-relative path. The file MUST already exist.\n' +
- ' old_string — required. Exact text to find. Must be unique in the file unless `replace_all=true`.\n' +
- ' new_string — required. Replacement text. May be empty (deletes `old_string`).\n' +
- ' replace_all — optional, default false. When true, every occurrence of `old_string` is replaced.\n' +
- '\n' +
- 'How to use:\n' +
- ' - Prefer this over `write_file` for targeted edits to existing files.\n' +
- ' - Read the file with `read_file` first so `old_string` matches its current contents. `read_file` shows each line as `<n>\\t<text>` — `old_string` must be the raw text WITHOUT that line-number+tab prefix. On `E_STALE` the file changed since you read it (e.g. another worker) — `read_file` it again, then redo the edit.\n' +
- ' - To CREATE a new file, use `write_file` instead — `edit_file` does not create files.\n' +
- ' - Make `old_string` long enough to be unique. On `E_MULTIPLE_MATCHES`, expand `old_string` with surrounding context, or set `replace_all=true` if every occurrence should change.\n' +
- ' - Cannot edit pdf / Office / image files in place (text from those is extracted, not the source). Use `write_file` if you really need to overwrite the binary.\n' +
- '\n' +
- 'Permission: requires local execution permission (same gate as `write_file` / `bash`).',
+ 'Replace old_string with new_string in an existing text file. Prefer this for targeted edits; use write_file to create files. old_string must match raw file text (not read_file line-number prefixes) and be unique unless replace_all=true. On E_STALE, reread then retry. Cannot edit PDF/Office/image sources in place.',
inputSchema: {
type: 'object',
properties: {
@@ -2411,25 +2379,7 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'create_artifact',
description:
- 'Build a small interactive app (self-contained HTML/CSS/JS) that is rendered LIVE and clickable inside this chat reply, embedded in a sandboxed iframe.\n' +
- '\n' +
- 'Use it for: interactive dashboards, calculators, data visualizations with filters or drill-down, configurators, simulators, quizzes, mini-games — anything the user should operate directly. For static/read-only KPI, table, timeline, alert, or simple chart summaries, prefer `:::dashboard`. Do NOT use it for static documents (use `html_to_pdf`) or images (use `generate_image`).\n' +
- '\n' +
- 'Input: `{ title?, files: [{ path, content, encoding? }, ...] }`\n' +
- ' - `files` MUST include a top-level `index.html` (the entry point). Up to 20 files, 256 KB per file, 1 MB total.\n' +
- ' - `path` is a forward-slash relative path (e.g. `index.html`, `assets/app.js`). No `..`, no leading `/`, no dotfiles, no `__orkas/...`.\n' +
- ' - Allowed extensions: text — `.html .htm .js .mjs .css .json .svg .xml .txt .csv`; binary (base64 only) — `.png .jpg .jpeg .gif .webp .ico .wasm .woff .woff2 .ttf .otf`.\n' +
- ' - `content` is UTF-8 text by default; for a binary extension set `"encoding":"base64"` and pass base64 bytes.\n' +
- '\n' +
- 'Constraints: the app runs OFFLINE — no network, no external CDN. Inline your CSS/JS or split into sibling files referenced by RELATIVE URL. The iframe is sandboxed (scripts + forms allowed; it cannot reach the host app).\n' +
- '\n' +
- 'To get what the user does back: the app sends a message to its parent —\n' +
- ' `parent.postMessage({ __orkasArtifact: true, type: "submit", payload: <json-serialisable value> }, "*")`\n' +
- 'and that arrives as the user\'s next message to you (a readable summary plus a machine tag). Optionally include `<script src="__orkas/bridge.js"></script>` to get `window.orkasArtifact.send(payload)` plus automatic iframe height — without the bridge the iframe is a fixed height (call `window.orkasArtifact.resize(px)` or post `{type:"resize",height:px}` to change it).\n' +
- '\n' +
- 'After calling this tool, do NOT also paste the artifact\'s HTML in your reply — it is already shown.\n' +
- '\n' +
- 'Permission: requires local execution permission (same gate as `write_file` / `html_to_pdf`).',
+ 'Create an offline interactive HTML/CSS/JS artifact rendered live in chat. Use for calculators, dashboards, filters, simulations, quizzes, mini-games; prefer :::dashboard for static summaries. Input files: [{path, content, encoding?}], including top-level index.html; no network/CDN, use relative sibling files. Optional __orkas/bridge.js provides send(payload)/resize. Do not paste HTML after calling.',
inputSchema: {
type: 'object',
properties: {
@@ -2541,24 +2491,7 @@ function createDeleteFileTool(opts: LocalToolsOpts): AgentTool {
return {
name: 'delete_file',
description:
- 'Delete a single file from disk via a two-step user-confirmed flow.\n' +
- '\n' +
- 'Sandbox is identical to `edit_file` (workspace + current attachment ' +
- 'dir + writable extraRoots). Use instead of `bash rm` — `bash` is ' +
- 'unaware of the sandbox + the confirm gate.\n' +
- '\n' +
- 'Flow:\n' +
- ' Step 1 — `delete_file({path})` (no token). Tool emits an inline ' +
- 'confirm card to the user and returns `requires_user_confirmation: ' +
- 'true` with a `confirmation_token`. Multiple Step 1 calls from the ' +
- 'same turn may be grouped into one user-facing card. The tool does NOT block. Tell ' +
- 'the user in prose what you intend to delete; do NOT retry with ' +
- 'the token in the same turn — wait for the user to click the card ' +
- 'and reply, then retry on the next turn.\n' +
- ' Step 2 — `delete_file({path, confirmation_token})`. Tool checks ' +
- 'the token state: granted → unlink + return success; pending → user ' +
- "hasn't clicked yet, stop and wait; denied → user declined, give up; " +
- 'invalid → token expired or path changed, call Step 1 again.',
+ 'Delete one visible file through a two-step user confirmation flow. First call with path only to show a confirm card and get confirmation_token; do not retry in the same turn. After the user confirms, call again with path and token. Use this instead of bash rm.',
inputSchema: {
type: 'object',
properties: {
diff --git a/src/main/model/core-agent/office-tools.ts b/src/main/model/core-agent/office-tools.ts
index 8d85dccc..9dbd0b4a 100644
--- a/src/main/model/core-agent/office-tools.ts
+++ b/src/main/model/core-agent/office-tools.ts
@@ -217,16 +217,7 @@ function createDocxTool(opts: OfficeToolsOpts): AgentTool {
return {
name: 'create_docx',
description:
- 'Create a Word (.docx) document from structured content, using the built-in Office engine ' +
- '(no Microsoft Office required; macOS + Windows). Provide an output `path` plus ordered `paragraphs`; ' +
- 'an optional `title` is added as a Heading 1. Each paragraph may set `style` (Heading1/Heading2/Normal/Quote), ' +
- '`align`, `list` (bullet/ordered), and inline run styling: `bold`, `italic`, `font`, `size` (e.g. "14pt"), ' +
- '`color` (e.g. "#1F4E79"), `underline`, `highlight`. Add data `tables` (each `{ rows: [[…]], colWidths? }`) and ' +
- '`images` (each `{ src, width?, height?, align? }`; `src` must be a file inside this conversation\'s ' +
- 'workspace/attachments). Body order is paragraphs, then tables, then images. For CJK content pass `locale` ' +
- '(e.g. "zh-CN"). Returns the saved path and a first-page PNG preview. If the path already exists and was not ' +
- 'written by you this turn, the basename is auto-suffixed (`-2 / -3 / ...`); use the `<file-renamed>` path ' +
- 'verbatim afterwards.',
+ 'Create a .docx with path plus optional title, paragraphs, tables, images, locale, preview. paragraphs: [{text, style?, align?, list?, bold?, italic?, font?, size?, color?}]. tables: [{rows:[[cell]], colWidths?}]. images: [{src,width?,height?,align?}], src in workspace/attachments. Returns saved path/preview; collisions return <file-renamed>.',
inputSchema: {
type: 'object',
properties: {
@@ -324,15 +315,7 @@ function createXlsxTool(opts: OfficeToolsOpts): AgentTool {
return {
name: 'create_xlsx',
description:
- 'Create an Excel (.xlsx) spreadsheet from a grid of rows, using the built-in Office engine ' +
- '(no Microsoft Office required; macOS + Windows). Provide an output `path` and `rows` (an array of rows, each an ' +
- 'array of cells). A cell is a string/number, or an object `{ value, formula, format, bold }` plus optional ' +
- 'styling: `fill` (cell background, e.g. "#1F4E79"), `font.color`, `font.size`, `italic`, `underline`, `halign` ' +
- '(left/center/right), `valign`, `wrap`, `border` (e.g. "thin"), `merge` (e.g. "A1:C1"). `formula` is an Excel ' +
- 'formula WITHOUT the leading "=" (e.g. "SUM(B2:B10)"). Cells are placed A1, B1, … by position; empty cells ' +
- 'are skipped. Optional `sheet` (default "Sheet1") and `columns` (per-column `{ name:"A", width, hidden }`). ' +
- 'For a multi-sheet workbook pass `sheets` instead — an array of `{ name, rows, columns }`. Returns the saved ' +
- 'path and a PNG preview. Auto-suffixes on collision (see the `<file-renamed>` block).',
+ 'Create a .xlsx workbook with path plus rows or sheets. rows is [[cell]], where cell is string/number or {value, formula?, format?, bold?, fill?, font.color?, font.size?, merge?}; formulas omit the leading "=". sheets: [{name, rows, columns?}]. Returns saved path/preview; collisions return <file-renamed>.',
inputSchema: {
type: 'object',
properties: {
@@ -436,16 +419,7 @@ function createPptxTool(opts: OfficeToolsOpts): AgentTool {
return {
name: 'create_pptx',
description:
- 'Create a PowerPoint (.pptx) deck from a list of slides, using the built-in Office engine ' +
- '(no Microsoft Office required; macOS + Windows). Provide an output `path` and `slides`. ' +
- 'For a simple deck, set `title`, `body` (newlines become separate body lines), and `layout` ' +
- '(e.g. "Title Slide", "Title and Content"). For a designed slide, set `background` ' +
- '(hex like "#06101D", scheme color, or gradient "C1-C2-angle"), `transition` (fade/push/wipe/morph), and ' +
- '`shapes` — free-positioned text boxes: each needs a position (`x`/`y`/`width`/`height` in units like "1in" / ' +
- '"120pt") and may add any style prop (`text`, `fill`, `color`, `size`, `bold`, `align`, `font`, `geometry`). ' +
- 'A slide may also carry `images` (each `{ src, x, y, width, height }`; `src` must be a file in this ' +
- 'conversation\'s workspace/attachments) and `tables` (each `{ rows: [[…]], x?, y?, colWidths? }`). ' +
- 'Returns the saved path and a first-slide PNG preview. Auto-suffixes on collision (see the `<file-renamed>` block).',
+ 'Create a .pptx with path and slides. slides: [{title?, body?, layout?, background?, transition?, shapes?, images?, tables?}]. shapes need text/x/y/width/height plus style fields; images need src/x/y/width/height with src in workspace/attachments. Returns saved path/preview; collisions return <file-renamed>.',
inputSchema: {
type: 'object',
properties: {
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index 10ecf416..e0d29c23 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -32,7 +32,7 @@ import { t } from '../../i18n';
// tool-catalog.ts: TOOL_CATALOG kept as the source of truth for the drift
// test (tool-catalog.test.ts asserts injected names ⊆ catalog) and for any
// future targeted use; runtime no longer renders the prompt block from it.
-import { getSession, memoryScopeForSession } from './session-store';
+import { getSession, memoryScopeForSession, toolResultsDirForSession } from './session-store';
import {
addEntry,
replaceEntry,
@@ -54,7 +54,6 @@ import { createResearchRerankTool } from './research-rerank-tool';
import { isToolVisibleToAgent } from './tool-catalog';
import { createWebSearchOverrideTool } from './search-tools';
import {
- sessionToolResultsDir,
agentEvolvedSkillsDir,
agentPrivateSkillsDir,
userMarketplaceAgentSkillsDir,
@@ -186,6 +185,9 @@ export interface BuildRunnerParams {
* agents in projects retain access to their own evolved skills. See
* CLAUDE.md §6 + `features/projects.ts::resolveProjectScope`. */
projectAllowedSkillIds?: readonly string[];
+ /** User-explicit skill refs selected in the composer. These are rendered
+ * even when they live in open/global skill roots that are normally lazy. */
+ forceOpenSkillRefs?: readonly string[];
/** Extra tools added to core-agent's builtins (e.g. group_chat commander
* gets dispatch tools (`run_worker` / `dispatch_to`) plus marketplace /
* skill-search / automation-listing tools). */
@@ -384,6 +386,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...(params.onSkillAdvertised ? { onSkillAdvertised: params.onSkillAdvertised } : {}),
displayNameById: skillDisplayNameById,
...(openSkillSourcesVisible ? { includeOpenSources: true } : {}),
+ ...(params.forceOpenSkillRefs?.length ? { forceOpenSkillRefs: [...params.forceOpenSkillRefs] } : {}),
}),
]);
@@ -446,7 +449,11 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// overrides `bash` and `write_file` with the permission-gated versions.
const systemSkillReadRoots = uid ? [userSystemSkillsDir(uid)] : [];
const agentPrivateSkillReadRoots = uid && agentId
- ? [userMarketplaceAgentSkillsDir(uid, agentId), agentPrivateSkillsDir(uid, agentId)]
+ ? [
+ userMarketplaceAgentSkillsDir(uid, agentId),
+ agentPrivateSkillsDir(uid, agentId),
+ agentEvolvedSkillsDir(uid, agentId),
+ ]
: [];
const fileReadOnlyExtraRoots = [
...(params.fileReadOnlyExtraRoots || []),
@@ -488,7 +495,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
...(params.projectId ? { projectId: params.projectId } : {}),
...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),
...(fileReadOnlyExtraRoots.length || params.sessionId
- ? { readOnlyExtraRoots: [...fileReadOnlyExtraRoots, sessionToolResultsDir(uid, params.sessionId)] }
+ ? { readOnlyExtraRoots: [...fileReadOnlyExtraRoots, toolResultsDirForSession(uid, params.sessionId)] }
: {}),
...(params.onSkillInvoked ? { onSkillInvoked: params.onSkillInvoked } : {}),
})
@@ -625,13 +632,14 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// >100K read spills + stays re-pageable via charStart/charEnd); a tool still
// exempts itself only by an Infinity entry in MAX_RESULT_CHARS_BY_TOOL.
// `uid` being empty happens in ad-hoc test scenarios; skip wrapping there —
- // no sessionToolResultsDir to resolve and no LLM in the loop that would
+ // no per-session tool-results dir to resolve and no LLM in the loop that would
// over-feed context anyway.
+ const toolResultsDir = uid ? toolResultsDirForSession(uid, params.sessionId) : '';
const wrappedTools = uid
? visibleTools.map((t) =>
wrapToolWithCap(t, {
maxChars: MAX_RESULT_CHARS_BY_TOOL[t.name] ?? DEFAULT_MAX_RESULT_CHARS,
- toolResultsDir: sessionToolResultsDir(uid, params.sessionId),
+ toolResultsDir,
}),
)
: visibleTools;
@@ -641,7 +649,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// our wrappedTools via last-write-wins. Used by the snapshot below and by
// the catalog-drift test (`tool-catalog.test.ts`); we no longer render a
// `## Available tools` block into the system prompt because the model
- // already receives every tool's full description + JSON schema via the
+ // already receives every tool's compact description + JSON schema via the
// SDK tool-use protocol — the prompt block was an information subset
// duplicating ~800 chars per call without giving the model anything new.
const builtinTools = mod.getBuiltinTools();
@@ -656,21 +664,20 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// tracks where each definition came from so the debug panel can call out
// injected vs. caller-supplied tools.
const toolDefMap = new Map<string, ToolDefSnapshot>();
+ const snapshotTool = (t: AgentTool, source: ToolDefSnapshot['source']): ToolDefSnapshot => {
+ const def = mod.toToolDefinition(t);
+ return {
+ name: def.name,
+ description: def.description,
+ inputSchema: def.inputSchema,
+ source,
+ };
+ };
for (const t of builtinTools) {
- toolDefMap.set(t.name, {
- name: t.name,
- description: t.description,
- inputSchema: t.inputSchema,
- source: 'core-agent',
- });
+ toolDefMap.set(t.name, snapshotTool(t, 'core-agent'));
}
for (const t of wrappedTools) {
- toolDefMap.set(t.name, {
- name: t.name,
- description: t.description,
- inputSchema: t.inputSchema,
- source: extraToolNameSet.has(t.name) ? 'extra' : 'orkas',
- });
+ toolDefMap.set(t.name, snapshotTool(t, extraToolNameSet.has(t.name) ? 'extra' : 'orkas'));
}
const toolDefs: ToolDefSnapshot[] = Array.from(toolDefMap.values())
.sort((a, b) => a.name.localeCompare(b.name));
diff --git a/src/main/model/core-agent/session-store.ts b/src/main/model/core-agent/session-store.ts
index adacb09b..edba9e3c 100644
--- a/src/main/model/core-agent/session-store.ts
+++ b/src/main/model/core-agent/session-store.ts
@@ -21,18 +21,26 @@
* stripped once at startup by `util/migrate-session-ids.ts` and should not appear
* here at runtime.
*
- * session jsonl only carries the LLM-facing view (including tool_use /
- * tool_result / compaction); it's a separate file from
+ * session jsonl carries the raw resumable LLM-turn history (tool_use /
+ * tool_result pairs included). `Session.getMessagesForModel()` may apply a
+ * transient send-time view (old image stripping / old tool_result compaction);
+ * it's a separate file from
* `<uid>/cloud/chats/<cid>.jsonl` (the UI-facing view).
*/
import * as path from 'node:path';
import * as fs from 'node:fs';
-import { userSessionFile, userLocalSessionFile } from '../../paths';
+import {
+ sessionCloudToolResultsDir,
+ sessionToolResultsDir,
+ userSessionFile,
+ userLocalSessionFile,
+} from '../../paths';
import { getActiveUserId } from '../../features/users';
import { createLogger } from '../../logger';
import { logErrorRef, logPathRef, maskId } from '../../util/log-redact';
+import { persistToolResult } from '../../util/tool-result-cap';
const log = createLogger('model');
@@ -117,6 +125,14 @@ export function sessionFileFor(sessionId: string): string {
return resolveSessionPath(getActiveUserId(), sessionId);
}
+export function toolResultsDirForSession(userId: string, sessionId: string): string {
+ // Validate the id with the same router that owns the session jsonl path.
+ resolveSessionPath(userId, sessionId);
+ return isEphemeralSessionId(sessionId)
+ ? sessionToolResultsDir(userId, sessionId)
+ : sessionCloudToolResultsDir(userId, sessionId);
+}
+
/**
* Lazy cache of loaded `PersistentSession` instances keyed by session_id.
* Two concurrent calls with the same session_id get the same instance so
@@ -144,11 +160,20 @@ export async function getSession(sessionId: string): Promise<PersistentSessionIn
const cached = cache.get(sessionId);
if (cached) return cached;
- const file = sessionFileFor(sessionId);
+ const userId = getActiveUserId();
+ const file = resolveSessionPath(userId, sessionId);
fs.mkdirSync(path.dirname(file), { recursive: true });
const Ctor = await getCtor();
- const session = new Ctor({ sessionFile: file });
+ const session = new Ctor({
+ sessionFile: file,
+ toolResultCompaction: {
+ persistToolResult: ({ toolName, content }) => {
+ const safeToolName = sanitizeToolResultName(toolName);
+ return persistToolResult(toolResultsDirForSession(userId, sessionId), safeToolName, content);
+ },
+ },
+ });
cache.set(sessionId, session);
return session;
}
@@ -160,7 +185,8 @@ export function evictSession(sessionId: string): void {
/** Delete the on-disk jsonl. Caller is responsible for also evicting. */
export function deleteSessionFile(sessionId: string): void {
- const file = sessionFileFor(sessionId);
+ const userId = getActiveUserId();
+ const file = resolveSessionPath(userId, sessionId);
try { fs.unlinkSync(file); }
catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
@@ -171,6 +197,8 @@ export function deleteSessionFile(sessionId: string): void {
});
}
}
+ try { fs.rmSync(toolResultsDirForSession(userId, sessionId), { recursive: true, force: true }); }
+ catch (err) { log.warn('session tool-results delete failed', { session_id: maskId(sessionId), error: logErrorRef(err) }); }
}
/** Same as deleteSessionFile but takes an explicit userId (caller has the
@@ -189,6 +217,14 @@ export function deleteSessionFileForUser(userId: string, sessionId: string): voi
});
}
}
+ try { fs.rmSync(toolResultsDirForSession(userId, sessionId), { recursive: true, force: true }); }
+ catch (err) {
+ log.warn('session tool-results delete failed', {
+ user_id: maskId(userId),
+ session_id: maskId(sessionId),
+ error: logErrorRef(err),
+ });
+ }
}
/** Flush all cached sessions — called by `features/users.activateUser()` on uid switch. */
@@ -200,3 +236,10 @@ export function _evictAll(): void {
export function _cacheSize(): number {
return cache.size;
}
+
+function sanitizeToolResultName(name: string): string {
+ const safe = String(name || 'tool_result')
+ .replace(/[^A-Za-z0-9_.-]/g, '_')
+ .slice(0, 64);
+ return safe || 'tool_result';
+}
diff --git a/src/main/model/core-agent/skill-registry.ts b/src/main/model/core-agent/skill-registry.ts
index b7e241ff..49740337 100644
--- a/src/main/model/core-agent/skill-registry.ts
+++ b/src/main/model/core-agent/skill-registry.ts
@@ -42,6 +42,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {
+ agentEvolvedSkillsDir,
agentPrivateSkillsDir,
userMarketplaceAgentSkillsDir,
userMarketplaceSkillsDir,
@@ -435,6 +436,25 @@ function _buildDisplayNameByInternalId(specs: SkillAllowlistRef[]): Map<string,
return out;
}
+function orderSkillsByRefs<T extends SkillAllowlistRef>(specs: T[], refs: string[]): T[] {
+ if (specs.length < 2 || !refs.length) return specs;
+ const order = new Map<string, number>();
+ for (const ref of refs) {
+ const key = String(ref || '').trim().toLowerCase();
+ if (!key || order.has(key)) continue;
+ order.set(key, order.size);
+ }
+ if (!order.size) return specs;
+ return specs
+ .map((s, idx) => {
+ const keys = [s.id, s.name].map((v) => String(v || '').trim().toLowerCase()).filter(Boolean);
+ const rank = Math.min(...keys.map((k) => order.get(k) ?? Number.POSITIVE_INFINITY));
+ return { s, idx, rank };
+ })
+ .sort((a, b) => (a.rank - b.rank) || (a.idx - b.idx))
+ .map((row) => row.s);
+}
+
function _buildDisplayNameByRef(specs: SkillAllowlistRef[]): Map<string, string> {
const out = new Map<string, string>();
for (const s of specs || []) {
@@ -723,6 +743,13 @@ export interface SystemPromptBlockOptions {
* Mirrors the agent-private tool `ownerAgent` default-deny gate.
*/
agentId?: string;
+ /**
+ * User-explicit skills selected from the composer/picker in addition to an
+ * agent's default allowlist. This is primarily for open/global skills, which
+ * stay lazy by default but must become visible when the user explicitly asks
+ * an agent to use one.
+ */
+ forceOpenSkillRefs?: string[];
}
/**
@@ -730,10 +757,10 @@ export interface SystemPromptBlockOptions {
* system prompt so the LLM knows what's available. Empty string when
* no skills are found (core-agent treats `""` as "skip the section").
*
- * When `opts.allowlist` is provided, only skills whose `id` is in the
- * allowlist are rendered. Rendering always goes through
- * `renderSkillLines` so the `Source` label is derived from the exact root
- * path rather than basename.
+ * When `opts.allowlist` is provided, trusted skills are restricted to that
+ * list, then the acting agent's private skills and user-forced open skills
+ * are appended. Rendering always goes through `renderSkillLines` so the
+ * `Source` label is derived from the exact root path rather than basename.
*/
export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}): Promise<string> {
const loader = await getLoader();
@@ -755,17 +782,19 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
let rendered: typeof specs;
let allowlisted = false;
- let explicitAllow: Set<string> | null = null;
+ let rawAllow: string[] = [];
if (opts.allowlist === undefined) {
rendered = filterDisabled(specs);
} else {
allowlisted = true;
- const rawAllow = opts.allowlist.filter((id) => typeof id === 'string' && id.length > 0);
- if (rawAllow.length === 0) return '';
- const { ids } = resolveSkillAllowlistRefs(specs, rawAllow);
- const allow = new Set([...ids, ...rawAllow]);
- explicitAllow = allow;
- rendered = filterDisabled(specs.filter((s) => allow.has(s.id)));
+ rawAllow = opts.allowlist.filter((id) => typeof id === 'string' && id.length > 0);
+ if (rawAllow.length === 0) {
+ rendered = [];
+ } else {
+ const { ids } = resolveSkillAllowlistRefs(specs, rawAllow);
+ const allow = new Set([...ids, ...rawAllow]);
+ rendered = filterDisabled(specs.filter((s) => allow.has(s.id)));
+ }
}
const actorAgentId = (opts.agentId || '').trim();
@@ -775,7 +804,6 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
for (const { root, specs: privateList } of await loadAgentPrivateSkillSpecs(uid, actorAgentId)) {
const privateSpecs = filterDisabled(privateList)
.filter((s) => !s.ownerAgent || s.ownerAgent === actorAgentId)
- .filter((s) => !explicitAllow || explicitAllow.has(s.id))
.filter((s) => !existingIds.has(s.id));
if (!privateSpecs.length) continue;
rootEntries.push({ label: privateIndex === 0 ? 'agent' : `agent${privateIndex + 1}`, root });
@@ -793,23 +821,27 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
// packages (so it won't try to re-install something already present).
// Allowlisted render paths stay trusted-only. Agent metadata has its own
// trusted+external helper, and still excludes the unbounded global tier.
- const externalRootSet = new Set<string>();
- let externalRankByRoot: Map<string, number> | null = null;
+ const openRootSet = new Set<string>();
+ const openRankByRoot = new Map<string, number>();
+ const addPromptRoot = (label: string, root: string) => {
+ const resolved = path.resolve(root);
+ if (rootEntries.some((r) => r.label === label && path.resolve(r.root) === resolved)) return;
+ rootEntries.push({ label, root: resolved });
+ };
if (opts.includeOpenSources && !allowlisted) {
const openDirs = _computeOpenTierDirs(uid);
if (openDirs.external.length) {
const openLoader = await getOpenLoader(openDirs);
if (openLoader) {
- externalRankByRoot = new Map();
openDirs.external.forEach((dir, i) => {
const resolved = path.resolve(dir);
- externalRootSet.add(resolved);
- externalRankByRoot!.set(resolved, SOURCE_DEDUPE_RANK.external);
- rootEntries.push({ label: i === 0 ? 'external' : `external${i + 1}`, root: resolved });
+ openRootSet.add(resolved);
+ openRankByRoot.set(resolved, SOURCE_DEDUPE_RANK.external);
+ addPromptRoot(i === 0 ? 'external' : `external${i + 1}`, resolved);
});
const trustedIds = new Set(rendered.map((s) => s.id));
const externalSpecs = openLoader.list().filter((s) => {
- if (!externalRootSet.has(path.resolve(s.source))) return false;
+ if (!openRootSet.has(path.resolve(s.source))) return false;
if (trustedIds.has(s.id)) return false;
if (disabled && disabled.has(s.id)) return false;
// Registry-backed only: drops a companion whose package was removed
@@ -822,13 +854,55 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
}
}
+ const forcedOpenRefs = (opts.forceOpenSkillRefs || [])
+ .filter((id) => typeof id === 'string' && id.length > 0);
+ if (forcedOpenRefs.length) {
+ const openDirs = _computeOpenTierDirs(uid);
+ const openLoader = await getOpenLoader(openDirs);
+ if (openLoader) {
+ const externalRoots = openDirs.external.map((d) => path.resolve(d));
+ const globalRoots = openDirs.global.map((d) => path.resolve(d));
+ const externalSet = new Set(externalRoots);
+ const globalSet = new Set(globalRoots);
+ const openSpecs = openLoader.list().filter((s) => {
+ const root = path.resolve(s.source);
+ if (!externalSet.has(root) && !globalSet.has(root)) return false;
+ if (disabled && disabled.has(s.id)) return false;
+ if (externalSet.has(root)) {
+ const meta = packageMetaForSkillDir(uid, s.dir);
+ if (!meta.package_name || meta.package_enabled === false) return false;
+ }
+ return true;
+ });
+ const { ids } = resolveSkillAllowlistRefs(openSpecs, forcedOpenRefs);
+ const allow = new Set([...ids, ...forcedOpenRefs]);
+ const existingIds = new Set(rendered.map((s) => s.id));
+ const forcedSpecs = openSpecs.filter((s) => allow.has(s.id) && !existingIds.has(s.id));
+ for (const s of forcedSpecs) {
+ const root = path.resolve(s.source);
+ const externalIdx = externalRoots.indexOf(root);
+ const globalIdx = globalRoots.indexOf(root);
+ if (externalIdx >= 0) {
+ openRootSet.add(root);
+ openRankByRoot.set(root, SOURCE_DEDUPE_RANK.external);
+ addPromptRoot(externalIdx === 0 ? 'external' : `external${externalIdx + 1}`, root);
+ } else if (globalIdx >= 0) {
+ openRootSet.add(root);
+ openRankByRoot.set(root, SOURCE_DEDUPE_RANK.global);
+ addPromptRoot(globalIdx === 0 ? 'global' : `global${globalIdx + 1}`, root);
+ }
+ }
+ rendered = [...rendered, ...forcedSpecs];
+ }
+ }
+
// Dedupe by display name; product/platform shadows custom/open tiers
// (builtin > platform > custom > external > global). When external is merged
// we pass a root-aware rank so the external roots map to their tier rank;
// otherwise the default rank applies.
- rendered = externalRankByRoot
+ rendered = openRankByRoot.size
? dedupeSkillsByDisplayName(rendered, (s) => {
- const r = externalRankByRoot!.get(path.resolve(s.source || ''));
+ const r = openRankByRoot.get(path.resolve(s.source || ''));
return r !== undefined ? r : skillSourceRank(s);
})
: dedupeSkillsByDisplayName(rendered);
@@ -840,14 +914,20 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
// same-name shared one for a non-owner. (Mirrors agent-private tool gating.)
rendered = rendered.filter((s) => !s.ownerAgent || s.ownerAgent === actorAgentId);
+ if (allowlisted) {
+ rendered = orderSkillsByRefs(rendered, [...rawAllow, ...forcedOpenRefs]);
+ }
+
// Advertise signal stays trusted-only (`A.custom` / `A.platform`); external
// entries are rendered but not advertised — their invocation is still
// attributed downstream via `onSkillInvoked` (B tier).
if (opts.onSkillAdvertised && rendered.length) {
for (const s of rendered) {
- if (externalRootSet.has(path.resolve(s.source || ''))) continue;
+ if (openRootSet.has(path.resolve(s.source || ''))) continue;
+ const label = skillSourceLabelForSpec(s);
+ if (label === 'unknown') continue;
try {
- opts.onSkillAdvertised(s.id, skillSourceLabelForSpec(s) === 'custom' ? 'A.custom' : 'A.platform');
+ opts.onSkillAdvertised(s.id, label === 'custom' ? 'A.custom' : 'A.platform');
} catch { /* callback throws are non-fatal; signal emission is best-effort */ }
}
}
@@ -1042,6 +1122,43 @@ export async function listSkills(): Promise<Array<{ id: string; name: string; de
return loader.list().map((s) => ({ id: s.id, name: s.name, description: pick(s, lang) }));
}
+function scanSkillIds(root: string): string[] {
+ try {
+ if (!fs.statSync(root).isDirectory()) return [];
+ return fs.readdirSync(root, { withFileTypes: true })
+ .filter((entry) => {
+ if (entry.name.startsWith('.')) return false;
+ const dir = path.join(root, entry.name);
+ if (!entry.isDirectory() && !(entry.isSymbolicLink() && fs.statSync(dir).isDirectory())) return false;
+ return fs.existsSync(path.join(dir, 'SKILL.md'));
+ })
+ .map((entry) => entry.name)
+ .sort((a, b) => a.localeCompare(b));
+ } catch {
+ return [];
+ }
+}
+
+export async function listAgentOwnedSkillIds(uid: string, agentId: string): Promise<string[]> {
+ const owner = String(agentId || '').trim();
+ if (!uid || !owner) return [];
+ const out: string[] = [];
+ const seen = new Set<string>();
+ const add = (id: string) => {
+ const clean = String(id || '').trim();
+ if (!clean || seen.has(clean)) return;
+ seen.add(clean);
+ out.push(clean);
+ };
+ for (const { specs: privateList } of await loadAgentPrivateSkillSpecs(uid, owner)) {
+ for (const s of privateList) {
+ if (!s.ownerAgent || s.ownerAgent === owner) add(s.id);
+ }
+ }
+ for (const id of scanSkillIds(agentEvolvedSkillsDir(uid, owner))) add(id);
+ return out;
+}
+
/**
* Full `SkillSpec[]` snapshot — used by `features/agents.ts` to filter
* unknown ids out of `agent.skill_list` writes. Goes through the registry
diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.ts
index e3f94a29..1d9a7e69 100644
--- a/src/main/model/core-agent/tool-catalog.ts
+++ b/src/main/model/core-agent/tool-catalog.ts
@@ -71,13 +71,12 @@ export interface ToolCatalogEntry {
*/
/**
* Agent ids that share the deep-research engine, so its `research_rerank` tool
- * is visible to all of them: the in-repo Deep Research front-door plus the
- * hosted data/research agents that can hand work into the research flow —
+ * is visible to the platform DeepResearcher and hosted data/research agents
+ * that can hand work into the research flow:
* DeepResearcher / KnowledgeManager / SocialResearcher / BrandResearcher.
* Referenced by opaque marketplace id (as skill_list does), not by name.
*/
export const DEEP_RESEARCH_AGENT_IDS = [
- 'b6ddc5e6b432', // DeepResearch
'78900d8758bc', // DeepResearcher
'5dd962efb425', // KnowledgeManager
'17c0a2e95df3', // SocialResearcher
diff --git a/src/main/paths.ts b/src/main/paths.ts
index 5c613ebf..0c5a39ee 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -160,6 +160,8 @@ export const savedAppDir = (uid: string, appId: string) => path.join(userSa
// and is the single place that decides which side an id lands on.
export const userSessionsDir = (uid: string) => path.join(userCloudRoot(uid), 'sessions');
export const userSessionFile = (uid: string, sessionId: string) => path.join(userSessionsDir(uid), `${sessionId}.jsonl`);
+export const sessionCloudToolResultsDir = (uid: string, sessionId: string) =>
+ path.join(userSessionsDir(uid), `${sessionId}.tool-results`);
export const userLocalSessionsDir = (uid: string) => path.join(userLocalRoot(uid), 'sessions');
export const userLocalSessionFile = (uid: string, sessionId: string) => path.join(userLocalSessionsDir(uid), `${sessionId}.jsonl`);
@@ -344,11 +346,9 @@ export const userChatsIndexPath = (uid: string) => path.join(userSearchDir(
// Dev-only LLM-call archive (features/devtools.ts + model/core-agent/client.ts).
export const userTestDir = (uid: string) => path.join(userLocalRoot(uid), 'test');
-// Spill copy for oversized tool output (>50K chars): the tool_result keeps
-// only a preview + file reference; the model can pull back the full text
-// via read_file(path). One subdirectory per session_id; startup
-// `sweepToolResults(uid)` cleans entries older than 7 days by mtime.
-// Never synced.
+// Machine-local spill copy for oversized CLI/local-agent tool output. Core
+// agent resumable sessions use `sessionCloudToolResultsDir()` instead so the
+// persisted-output refs travel with `cloud/sessions/<sid>.jsonl`.
export const userToolResultsDir = (uid: string) => path.join(userLocalRoot(uid), 'tool-results');
export const sessionToolResultsDir = (uid: string, sessionId: string) =>
path.join(userToolResultsDir(uid), sessionId);
@@ -550,6 +550,11 @@ export const qualitySkillReportFile = (uid: string, sid: string) =>
export const qualityAgentReportFile = (uid: string, aid: string) =>
path.join(userQualityAgentsDir(uid), `${aid}.json`);
+// Composer-only attachment drafts. These bytes are not message content yet, so
+// they stay local until a send flow adopts them into cloud/chat_attachments/<cid>/.
+export const userChatAttachmentDraftsDir = (uid: string) => path.join(userLocalRoot(uid), 'chat_attachment_drafts');
+export const chatAttachmentDraftDir = (uid: string, cid: string) => path.join(userChatAttachmentDraftsDir(uid), cid);
+
// ── Multi-device sync (machine-private state) ────────────────────────────
// `<uid>/local/sync/` is the engine's per-machine bookkeeping; nothing here
// crosses devices (per plan §3.2). `index.json` is the last-synced snapshot
@@ -682,6 +687,7 @@ export function ensureUserLayout(uid: string): void {
userSearchDir(uid),
userTestDir(uid),
userFileCacheDir(uid),
+ userChatAttachmentDraftsDir(uid),
userToolResultsDir(uid),
userSyncDir(uid),
userSyncConflictsDir(uid),
diff --git a/src/main/util/tool-result-cap.ts b/src/main/util/tool-result-cap.ts
index be5af298..16727e43 100644
--- a/src/main/util/tool-result-cap.ts
+++ b/src/main/util/tool-result-cap.ts
@@ -6,7 +6,7 @@
* assembly in runner.ts. Three-tier handling:
* len ≤ maxChars → pass through unchanged
* maxChars < len ≤ PERSIST → in-place truncation + trailing marker
- * len > PERSIST → spill to tool-results/<sid>/<name>.<id>.txt,
+ * len > PERSIST → spill to the caller-provided tool-results dir,
* rewrite tool_result into a <persisted-output>
* wrapper (preview + reference); the model can
* pull the original back via read_file(path)
@@ -87,7 +87,7 @@ export interface WrapOpts {
/** maxChars cap for this tool. Infinity → decorator returns the original
* tool directly. */
maxChars: number;
- /** Spill directory (typically `sessionToolResultsDir(uid, sessionId)`).
+ /** Spill directory (local for CLI/local-agent; cloud-adjacent for resumable core-agent sessions).
* The decorator does not care about uid / sessionId; the caller assembles
* the path and passes it in. The directory is mkdir'd on demand, not
* required to exist beforehand. */
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 15252c97..95e4dff4 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -135,7 +135,7 @@
</button>
<button type="button" class="new-chat-scenario-chip" data-scenario="seo_geo">
<span data-ui-icon="globe" data-ui-icon-class="new-chat-scenario-icon"></span>
- <span class="new-chat-scenario-label" data-i18n="new_chat.quick.seo_geo">SeoGeo</span>
+ <span class="new-chat-scenario-label" data-i18n="new_chat.quick.seo_geo">AI Search Visibility</span>
</button>
<button type="button" class="new-chat-scenario-chip" data-scenario="office">
<span data-ui-icon="file-text" data-ui-icon-class="new-chat-scenario-icon"></span>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 49fbd481..7c9906d0 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -193,7 +193,7 @@
"new_chat.quick.creation": "Writing",
"new_chat.quick.data": "Deep Research",
"new_chat.quick.video": "Make video",
- "new_chat.quick.seo_geo": "SeoGeo",
+ "new_chat.quick.seo_geo": "AI Search Visibility",
"new_chat.quick.office": "Documents",
"new_chat.external_agent_entry": "Connect Codex, Claude Code & other AI coding tools",
"new_chat.quick.agent_required": "Install or enable “{name}” before using this shortcut.",
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index df3d966e..17354606 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -181,7 +181,7 @@
"new_chat.quick.creation": "文章作成",
"new_chat.quick.data": "深掘り調査",
"new_chat.quick.video": "動画制作",
- "new_chat.quick.seo_geo": "SeoGeo",
+ "new_chat.quick.seo_geo": "AI検索での露出",
"new_chat.quick.office": "資料整理",
"new_chat.external_agent_entry": "Codex・Claude Code など AI コーディングツールを接続",
"new_chat.quick.agent_required": "このショートカットを使うには「{name}」をインストールまたは有効化してください。",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 8698fa8d..9b19fa37 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -193,7 +193,7 @@
"new_chat.quick.creation": "文章写作",
"new_chat.quick.data": "深度研究",
"new_chat.quick.video": "制作视频",
- "new_chat.quick.seo_geo": "SeoGeo",
+ "new_chat.quick.seo_geo": "AI/搜索曝光",
"new_chat.quick.office": "整理文档",
"new_chat.external_agent_entry": "接入 Codex、Claude Code 等 AI 编程工具",
"new_chat.quick.agent_required": "需要先安装或启用「{name}」后才可使用这个入口。",
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index a824c5c3..4f4fb153 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -3538,7 +3538,7 @@ async function _triggerPickerItem(kind, itemId, itemName, anchorId, dataset) {
if (kind === 'skill') {
_agentsTrackClick('chat_skill_select', { target, skill_id: String(itemId || itemName || '') });
_consumeAtKeyChar();
- setChatSkill(target, itemName || itemId);
+ setChatSkill(target, itemId, itemName || itemId);
const inputId = target === 'new-chat' ? 'new-chat-input' : (target === 'project' ? 'project-chat-input' : 'chat-input');
_focusInput(document.getElementById(inputId));
return;
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index 88f8e403..e2759c3a 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -336,8 +336,8 @@ function setView(view, cid, opts = {}) {
// the landing page is entered — the user explicitly asked for a clean
// slate here, so prior in-session picks don't leak forward.
if (typeof onEnterNewChatView === 'function') onEnterNewChatView();
- // Draft attachment chips (commander tab's pool under `main_chat/`): re-paint from
- // the in-memory Map immediately, and re-sync with disk in case a prior
+ // Draft attachment chips (commander tab's local `main_chat/` pool): re-paint
+ // from the in-memory Map immediately, and re-sync with disk in case a prior
// session left files on disk without a dataUrl.
if (typeof _chatAttachRenderChips === 'function') _chatAttachRenderChips(DRAFT_CID);
if (typeof _chatAttachRefreshFromServer === 'function') _chatAttachRefreshFromServer(DRAFT_CID);
diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.js
index a1952249..2a594c48 100644
--- a/src/renderer/modules/chat-file-viewer.js
+++ b/src/renderer/modules/chat-file-viewer.js
@@ -597,14 +597,33 @@ function _officeFitFrameHeight(res) {
return Math.max(260, Math.min(max, Math.ceil(raw)));
}
+const _VIEWER_VIDEO_END_REPLAY_SECONDS = 0.25;
+
+function _viewerVideoShouldReplayFromStart(startTime, duration, ended) {
+ if (ended) return true;
+ const rawDuration = Number(duration);
+ if (!Number.isFinite(rawDuration) || rawDuration <= 0) return false;
+ return startTime >= Math.max(0, rawDuration - _VIEWER_VIDEO_END_REPLAY_SECONDS);
+}
+
function _viewerVideoPlaybackOptions(opts) {
const rawTime = Number(opts && opts.startTime);
+ const startTime = Number.isFinite(rawTime) && rawTime > 0 ? rawTime : 0;
+ const rawDuration = Number(opts && opts.duration);
return {
autoplay: !!(opts && opts.autoplay),
- startTime: Number.isFinite(rawTime) && rawTime > 0 ? rawTime : 0,
+ startTime: _viewerVideoShouldReplayFromStart(startTime, rawDuration, !!(opts && opts.ended)) ? 0 : startTime,
};
}
+function _viewerVideoSeekTarget(startTime, duration) {
+ if (!Number.isFinite(startTime) || startTime <= 0) return 0;
+ const rawDuration = Number(duration);
+ if (!Number.isFinite(rawDuration) || rawDuration <= 0) return startTime;
+ if (_viewerVideoShouldReplayFromStart(startTime, rawDuration, false)) return 0;
+ return Math.min(startTime, Math.max(0, rawDuration - 0.05));
+}
+
function _applyViewerVideoPlayback(video, opts) {
if (!video) return;
const playback = _viewerVideoPlaybackOptions(opts);
@@ -612,11 +631,7 @@ function _applyViewerVideoPlayback(video, opts) {
const seek = () => {
if (playback.startTime > 0) {
try {
- const duration = Number(video.duration);
- const target = Number.isFinite(duration) && duration > 0
- ? Math.min(playback.startTime, Math.max(0, duration - 0.05))
- : playback.startTime;
- video.currentTime = target;
+ video.currentTime = _viewerVideoSeekTarget(playback.startTime, video.duration);
} catch (_) { /* setting currentTime can throw before metadata on some codecs */ }
}
};
@@ -879,5 +894,5 @@ async function openChatFileViewer(absPath, displayName, opts) {
// CJS bridge for vitest — pure functions only, per PC/CLAUDE.md §9.
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
- module.exports = { _kindOf, _extOf, _chatMediaLocalUrl, _viewerAbsPathFromChatMediaLocalUrl, _viewerCanAddToLibrary, _viewerVideoPlaybackOptions };
+ module.exports = { _kindOf, _extOf, _chatMediaLocalUrl, _viewerAbsPathFromChatMediaLocalUrl, _viewerCanAddToLibrary, _viewerVideoPlaybackOptions, _viewerVideoSeekTarget };
}
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 933c5fc9..247703bd 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -587,24 +587,33 @@ function _chatRichCreateApi(textarea, editor) {
const end = typeof textarea.selectionEnd === 'number' ? textarea.selectionEnd : start;
_chatRichSetSelection(editor, start, end);
},
- setTextareaSelection(start, end = start) {
+ setTextareaSelection(start, end = start, opts = {}) {
+ const next = { start, end: typeof end === 'number' ? end : start };
if (nativeSetSelectionRange) {
- try { nativeSetSelectionRange(start, end); } catch (_) {}
+ try { nativeSetSelectionRange(next.start, next.end); } catch (_) {}
} else {
- textarea.selectionStart = start;
- textarea.selectionEnd = end;
+ textarea.selectionStart = next.start;
+ textarea.selectionEnd = next.end;
+ }
+ if (!opts || opts.pending !== false) {
+ this.pendingSelection = next;
}
- this.pendingSelection = { start, end };
},
syncTextareaSelectionFromEditor() {
const sel = _chatRichSelectionIndexes(editor);
if (!sel) return;
- this.setTextareaSelection(sel.start, sel.end);
+ // This mirrors the browser-owned contenteditable caret into the hidden
+ // textarea. It must not schedule a reverse editor selection update,
+ // otherwise normal ArrowLeft/ArrowRight movement gets snapped back by
+ // the next sync tick.
+ this.setTextareaSelection(sel.start, sel.end, { pending: false });
},
- renderFromTextarea() {
+ renderFromTextarea(opts = {}) {
const value = String(textarea.value || '');
const changed = value !== this.lastValue;
+ let shouldAutoGrow = !!(opts && opts.forceHeight);
if (changed) {
+ shouldAutoGrow = true;
this.lastValue = value;
const start = typeof textarea.selectionStart === 'number' ? textarea.selectionStart : value.length;
const end = typeof textarea.selectionEnd === 'number' ? textarea.selectionEnd : start;
@@ -618,7 +627,7 @@ function _chatRichCreateApi(textarea, editor) {
_chatRichSetSelection(editor, this.pendingSelection.start, this.pendingSelection.end);
this.pendingSelection = null;
}
- this.autoGrow(_chatRichAutoGrowMax(textarea.id));
+ if (shouldAutoGrow) this.autoGrow(_chatRichAutoGrowMax(textarea.id));
},
syncFromEditor(emit) {
this.syncTextareaSelectionFromEditor();
@@ -2345,10 +2354,9 @@ function _findRenderedMessageForHistoryRecord(container, gm) {
const _chatAttachments = new Map(); // cid → Array<{name, displayName?, kind, bytes, dataUrl?, sha256?, reused?}>
-// Draft cid used by the commander (new-chat) tab — files land under
-// `data/<uid>/chat_attachments/main_chat/` until the user hits send, at which
-// point the backend renames that dir to the freshly-minted conversation cid
-// (see `adoptDraftAttachments`).
+// Draft cid used by the commander (new-chat) tab — files land in a local-only
+// draft pool until the user hits send, at which point the backend adopts that
+// dir into the freshly-minted conversation cid (see `adoptDraftAttachments`).
const DRAFT_CID = 'main_chat';
const CHAT_ATTACH_ACCEPT = [
@@ -2943,7 +2951,7 @@ function _renderMessageAttachmentsHtml(names, cid) {
const floatingTitle = escapeHtml(_chatVideoFloatingTitle());
return `<span class="chat-msg-attach is-video" data-attach-name="${label}" data-attach-cid="${escapeHtml(cid)}" title="${label}">
<span class="chat-msg-attach-video-shell">
- <video class="chat-msg-attach-video" controls controlslist="nodownload nofullscreen noremoteplayback" disablepictureinpicture disableremoteplayback playsinline preload="metadata" src="${url}"></video>
+ <video class="chat-msg-attach-video" width="320" height="180" controls controlslist="nodownload nofullscreen noremoteplayback" disablepictureinpicture disableremoteplayback playsinline preload="metadata" src="${url}"></video>
<button type="button" class="chat-msg-attach-video-float" data-attach-video-open="1" aria-label="${floatingTitle}" title="${floatingTitle}">${_uiIconHtml('maximize', 'ui-icon chat-msg-attach-video-float-svg')}</button>
</span>
<span class="chat-msg-attach-label">${label}</span>
@@ -3198,6 +3206,9 @@ function _hydrateMessageAttachmentThumbs(msgDiv, cid) {
if (!name || !chipCid) return;
const video = chip.querySelector('video.chat-msg-attach-video');
const startTime = video && Number.isFinite(Number(video.currentTime)) ? Math.max(0, Number(video.currentTime) || 0) : 0;
+ const duration = video && Number.isFinite(Number(video.duration)) ? Math.max(0, Number(video.duration) || 0) : 0;
+ const ended = !!(video && video.ended);
+ const playbackOpts = { cid: chipCid, autoplay: true, startTime, duration, ended };
try { if (video && typeof video.pause === 'function') video.pause(); } catch (_) {}
try { if (window.Monitor) (() => {})('chat_attachment_video_floating_open'); } catch (_) {}
try {
@@ -3207,7 +3218,7 @@ function _hydrateMessageAttachmentThumbs(msgDiv, cid) {
_showFileMissingToast(name);
return;
}
- openChatFileViewer(res.path, name, { cid: chipCid, autoplay: true, startTime });
+ openChatFileViewer(res.path, name, playbackOpts);
} catch (err) {
_convLog.warn('attachments.absPath video threw', { cid: chipCid, name, error: String(err && err.message || err) });
_showFileMissingToast(name);
@@ -3348,8 +3359,8 @@ function _initChatAttachInput() {
// The commander (new-chat) tab's "+" button uses the same upload
// pipeline; the only difference is that it passes DRAFT_CID instead of
// a real conversation cid. After the user clicks send,
-// handleNewChatSubmit calls adopt to rename the whole `main_chat/`
-// directory to the freshly-minted cid; the pre-processing cache
+// handleNewChatSubmit calls adopt to move the whole local `main_chat/`
+// draft directory to the freshly-minted cid; the pre-processing cache
// follows in place and doesn't need to be rerun.
function _initNewChatAttachInput() {
@@ -4538,6 +4549,109 @@ function _streamingMarkdownBodyHtml(display) {
return `<div class="markdown-body">${_renderMessageMarkdown(display)}</div>`;
}
+function _streamingStableMediaKey(kind, src) {
+ const normalizedKind = String(kind || '').trim().toLowerCase();
+ const normalizedSrc = String(src || '').trim();
+ if (!normalizedKind || !normalizedSrc) return '';
+ return `${normalizedKind}\x1f${normalizedSrc}`;
+}
+
+function _streamingCollectStableMedia(root) {
+ const stable = new Map();
+ if (!root || typeof root.querySelectorAll !== 'function') return stable;
+ const add = (kind, src, node) => {
+ const key = _streamingStableMediaKey(kind, src);
+ if (!key || !node) return;
+ const list = stable.get(key) || [];
+ list.push(node);
+ stable.set(key, list);
+ };
+ root.querySelectorAll('.chat-md-video-shell').forEach((shell) => {
+ const video = shell && shell.querySelector ? shell.querySelector('video.chat-md-video[src]') : null;
+ add('video', video && video.getAttribute ? video.getAttribute('src') : '', shell);
+ });
+ root.querySelectorAll('.chat-md-audio-card').forEach((card) => {
+ const audio = card && card.querySelector ? card.querySelector('audio.chat-md-audio[src]') : null;
+ add('audio', audio && audio.getAttribute ? audio.getAttribute('src') : '', card);
+ });
+ return stable;
+}
+
+function _streamingCopyElementAttributes(target, source) {
+ if (!target || !source || !target.attributes || !source.attributes) return;
+ const keep = new Set();
+ Array.from(source.attributes).forEach((attr) => {
+ keep.add(attr.name);
+ if (target.getAttribute(attr.name) !== attr.value) target.setAttribute(attr.name, attr.value);
+ });
+ Array.from(target.attributes).forEach((attr) => {
+ if (!keep.has(attr.name)) target.removeAttribute(attr.name);
+ });
+}
+
+function _streamingSyncStableMediaNode(existing, fresh) {
+ if (!existing || !fresh) return existing;
+ _streamingCopyElementAttributes(existing, fresh);
+ const existingMedia = existing.querySelector
+ ? existing.querySelector('video.chat-md-video[src], audio.chat-md-audio[src]')
+ : null;
+ const freshMedia = fresh.querySelector
+ ? fresh.querySelector('video.chat-md-video[src], audio.chat-md-audio[src]')
+ : null;
+ if (existingMedia && freshMedia) _streamingCopyElementAttributes(existingMedia, freshMedia);
+
+ const existingOpen = existing.querySelector
+ ? existing.querySelector('[data-chat-md-video-open="1"]')
+ : null;
+ const freshOpen = fresh.querySelector
+ ? fresh.querySelector('[data-chat-md-video-open="1"]')
+ : null;
+ if (existingOpen && freshOpen) _streamingCopyElementAttributes(existingOpen, freshOpen);
+ else if (!existingOpen && freshOpen && existing.appendChild) existing.appendChild(freshOpen);
+ else if (existingOpen && !freshOpen && existingOpen.remove) existingOpen.remove();
+ return existing;
+}
+
+function _streamingRestoreStableMedia(nextRoot, stable) {
+ if (!nextRoot || !stable || !stable.size || typeof nextRoot.querySelectorAll !== 'function') return;
+ nextRoot.querySelectorAll('.chat-md-video-shell').forEach((freshShell) => {
+ const video = freshShell && freshShell.querySelector ? freshShell.querySelector('video.chat-md-video[src]') : null;
+ const key = _streamingStableMediaKey('video', video && video.getAttribute ? video.getAttribute('src') : '');
+ const reusable = key ? stable.get(key) : null;
+ const existing = reusable && reusable.shift ? reusable.shift() : null;
+ if (existing && freshShell.replaceWith) freshShell.replaceWith(_streamingSyncStableMediaNode(existing, freshShell));
+ });
+ nextRoot.querySelectorAll('.chat-md-audio-card').forEach((freshCard) => {
+ const audio = freshCard && freshCard.querySelector ? freshCard.querySelector('audio.chat-md-audio[src]') : null;
+ const key = _streamingStableMediaKey('audio', audio && audio.getAttribute ? audio.getAttribute('src') : '');
+ const reusable = key ? stable.get(key) : null;
+ const existing = reusable && reusable.shift ? reusable.shift() : null;
+ if (existing && freshCard.replaceWith) freshCard.replaceWith(_streamingSyncStableMediaNode(existing, freshCard));
+ });
+}
+
+function _setStreamingFinalHtml(finalEl, html) {
+ if (!finalEl) return;
+ if (
+ typeof document === 'undefined'
+ || !document.createElement
+ || typeof finalEl.querySelectorAll !== 'function'
+ || typeof finalEl.replaceChildren !== 'function'
+ ) {
+ finalEl.innerHTML = html;
+ return;
+ }
+ const stable = _streamingCollectStableMedia(finalEl);
+ if (!stable.size) {
+ finalEl.innerHTML = html;
+ return;
+ }
+ const tmp = document.createElement('div');
+ tmp.innerHTML = html;
+ _streamingRestoreStableMedia(tmp, stable);
+ finalEl.replaceChildren(...Array.from(tmp.childNodes));
+}
+
function _invalidateStreamingMathPaint(msg) {
if (!msg) return;
if (msg._streamMathTimer) {
@@ -4576,7 +4690,7 @@ async function _flushStreamingMathPaint(msg) {
&& latest.finalEl === job.finalEl
&& job.finalEl.isConnected !== false
) {
- job.finalEl.innerHTML = rendered;
+ _setStreamingFinalHtml(job.finalEl, rendered);
msg.dataset.streamPaintedDisplay = job.display;
msg._streamMathLatestPaint = null;
if (job.stickBottom) _stickBottomFromMsg(msg);
@@ -4592,7 +4706,7 @@ function _paintStreamingFinalMarkdown(msg, finalEl, display, { stickBottom = fal
const sig = _streamMathSignatureForText(display);
if (!sig || typeof typesetMathHtml !== 'function') {
_invalidateStreamingMathPaint(msg);
- finalEl.innerHTML = html;
+ _setStreamingFinalHtml(finalEl, html);
msg.dataset.streamPaintedDisplay = display;
if (sig && typeof typesetMath === 'function') typesetMath(finalEl);
if (stickBottom) _stickBottomFromMsg(msg);
@@ -5633,8 +5747,9 @@ async function handleNewChatSubmit() {
return;
}
- // Rename `main_chat/` → `<convId>/` on disk. Preprocessing caches
- // (`.<name>.extracted.NNN.md`) move with their source — nothing to re-run.
+ // Adopt local `main_chat/` draft files into `<convId>/` on disk.
+ // Preprocessing caches (`.<name>.extracted.NNN.md`) move with their source
+ // when present — nothing to re-run.
let attachments = [];
if (draftNames.length) {
try {
@@ -5680,7 +5795,11 @@ async function handleNewChatSubmit() {
_transferNewChatRecipientTo(convId);
_renderRecipientChip('conversation');
if (newBtn) newBtn.disabled = false;
- await sendInCurrentConversation(content, attachments.length ? { attachments } : undefined);
+ const extra = {
+ ...(attachments.length ? { attachments } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ };
+ await sendInCurrentConversation(content, Object.keys(extra).length ? extra : undefined);
}
async function handleChatSubmit() {
@@ -5726,6 +5845,7 @@ async function handleChatSubmit() {
}
enqueueMessage(cid, applyQuotePrefix(raw, 'conversation'), null, {
recipient: recipientSnapshot,
+ extra: useSelections.length ? { use_selections: useSelections } : undefined,
});
_clearQuote(cid);
input.value = '';
@@ -5748,7 +5868,11 @@ async function handleChatSubmit() {
// is aborted, the files remain on disk but the user can re-attach via the
// "+" button (listAttachments shows what's still there).
if (attachments.length) _chatAttachClear(cid);
- await sendInCurrentConversation(content, attachments.length ? { attachments } : undefined);
+ const extra = {
+ ...(attachments.length ? { attachments } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ };
+ await sendInCurrentConversation(content, Object.keys(extra).length ? extra : undefined);
}
// One transient controller per conversation send. Multi-cid support comes
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
index 71272d0a..09bdd338 100644
--- a/src/renderer/modules/project-detail.js
+++ b/src/renderer/modules/project-detail.js
@@ -1788,7 +1788,11 @@ async function _submitProjectChat() {
}
if (btn) btn.disabled = false;
if (typeof sendInCurrentConversation === 'function') {
- await sendInCurrentConversation(content, _adopted.length ? { attachments: _adopted } : undefined);
+ const extra = {
+ ...(_adopted.length ? { attachments: _adopted } : {}),
+ ...(useSelections.length ? { use_selections: useSelections } : {}),
+ };
+ await sendInCurrentConversation(content, Object.keys(extra).length ? extra : undefined);
}
}
diff --git a/src/renderer/modules/queue-draft.js b/src/renderer/modules/queue-draft.js
index 5fb7678b..e2b9f3bd 100644
--- a/src/renderer/modules/queue-draft.js
+++ b/src/renderer/modules/queue-draft.js
@@ -133,6 +133,9 @@ function _dispatchNextQueued(cid) {
// Falling back to current chip is only for legacy queue rows persisted before
// snapshots existed.
let use = _queueItemUseSelection(next);
+ const inlineUseSelections = (typeof _chatUseSelectionsFromText === 'function')
+ ? _chatUseSelectionsFromText(next.content || '')
+ : [];
if (use && typeof isChatUseAllowedForTarget === 'function' && !isChatUseAllowedForTarget('conversation', use.kind)) {
use = null;
}
@@ -156,9 +159,17 @@ function _dispatchNextQueued(cid) {
const content = next.direct
? next.content
: applyRecipientPrefix(withUse, 'conversation', { recipientSnapshot: next.recipient });
+ const extra = next.extra && typeof next.extra === 'object' ? { ...next.extra } : {};
+ if (!Array.isArray(extra.use_selections) && typeof _normalizeChatUseSelections === 'function') {
+ const selections = _normalizeChatUseSelections([
+ ...inlineUseSelections,
+ ...(use ? [use] : []),
+ ]);
+ if (selections.length) extra.use_selections = selections;
+ }
// Fire-and-forget: sendInCurrentConversation handles its own errors via
// _streamingSetError + _finishStreamingMsg (which will re-enter this fn).
- sendInCurrentConversation(content, next.extra);
+ sendInCurrentConversation(content, Object.keys(extra).length ? extra : undefined);
}
function renderMessageQueue(cid) {
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index 923e848b..b7e40a89 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -593,8 +593,10 @@ function setChatUseSelection(target, selection, opts = {}) {
input?.focus();
}
-function setChatSkill(target, name) {
- setChatUseSelection(target, name ? { kind: 'skill', id: name, name } : null);
+function setChatSkill(target, idOrName, maybeName) {
+ const id = String(idOrName || maybeName || '').trim();
+ const name = String(maybeName || idOrName || '').trim();
+ setChatUseSelection(target, id || name ? { kind: 'skill', id: id || name, name: name || id } : null);
}
function setChatConnector(target, connectorId, connectorName) {
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 9c9e2437..bdc8336a 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -1163,7 +1163,7 @@ function _markdownVideoHtml(src, label, title) {
const openButton = localPath
? `<button type="button" class="chat-md-video-float" data-chat-md-video-open="1" data-video-src="${escapeHtml(src)}" aria-label="${escapeHtml(openLabel)}" title="${escapeHtml(openLabel)}">${_markdownVideoOpenIconHtml()}</button>`
: '';
- return `<span class="chat-md-video-shell"><video class="chat-md-video" controls controlslist="nodownload nofullscreen noremoteplayback" disablepictureinpicture disableremoteplayback playsinline preload="metadata" src="${escapeHtml(src)}"${t} aria-label="${escapeHtml(label || 'video')}"></video>${openButton}</span>`;
+ return `<span class="chat-md-video-shell"><video class="chat-md-video" width="640" height="360" controls controlslist="nodownload nofullscreen noremoteplayback" disablepictureinpicture disableremoteplayback playsinline preload="metadata" src="${escapeHtml(src)}"${t} aria-label="${escapeHtml(label || 'video')}"></video>${openButton}</span>`;
}
function _markdownMediaLabel(src, label, fallback) {
@@ -1302,13 +1302,16 @@ if (typeof document !== 'undefined') document.addEventListener('click', (e) => {
const shell = btn.closest('.chat-md-video-shell');
const video = shell && shell.querySelector ? shell.querySelector('video.chat-md-video') : null;
const startTime = video && Number.isFinite(Number(video.currentTime)) ? Math.max(0, Number(video.currentTime) || 0) : 0;
+ const duration = video && Number.isFinite(Number(video.duration)) ? Math.max(0, Number(video.duration) || 0) : 0;
+ const ended = !!(video && video.ended);
+ const playbackOpts = { autoplay: true, startTime, duration, ended };
try { if (video && typeof video.pause === 'function') video.pause(); } catch (_) {}
try { if (window.Monitor) (() => {})('chat_md_video_floating_open'); } catch (_) {}
if (typeof openChatVideoUrlViewer === 'function') {
- openChatVideoUrlViewer(src, name, { autoplay: true, startTime });
+ openChatVideoUrlViewer(src, name, playbackOpts);
return;
}
- openChatFileViewer(absPath, name, { autoplay: true, startTime });
+ openChatFileViewer(absPath, name, playbackOpts);
}, true);
// Bare URL autolink termination set. URLs per RFC 3986 are ASCII; CJK
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 4c0e1464..f7d2a246 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -4861,14 +4861,14 @@ body.model-not-configured .main-content { flex-direction: column; }
display: inline-flex;
align-items: center;
max-width: 100%;
- min-height: 1.45em;
+ min-height: 1.35em;
margin: 0 1px;
- padding: 0 6px;
+ padding: 0 5px;
border: 1px solid var(--border);
border-radius: 7px;
background: var(--surface-2);
color: var(--text-2);
- font-size: inherit;
+ font-size: 13px;
font-weight: inherit;
line-height: 1.35;
vertical-align: 0.08em;
@@ -5250,18 +5250,30 @@ body.model-not-configured .main-content { flex-direction: column; }
/* Video attachment — inline playable. Wider than images so controls fit;
max-height keeps it from dominating a long bubble. */
.chat-msg-attach.is-video {
+ box-sizing: border-box;
padding: 4px;
flex-direction: column;
align-items: stretch;
- max-width: 320px;
+ width: min(320px, 100%);
+ max-width: 100%;
}
-.chat-msg-attach-video {
+.chat-msg-attach-video-shell {
+ position: relative;
display: block;
width: 100%;
- max-height: 240px;
+ aspect-ratio: 16 / 9;
+ overflow: hidden;
border-radius: 4px;
background: #000;
}
+.chat-msg-attach-video {
+ display: block;
+ width: 100%;
+ height: 100%;
+ border-radius: 0;
+ object-fit: contain;
+ background: #000;
+}
.chat-msg-attach.is-video .chat-msg-attach-label {
text-align: center;
font-size: 11px;
@@ -5325,12 +5337,24 @@ body.model-not-configured .main-content { flex-direction: column; }
text-overflow: ellipsis;
white-space: nowrap;
}
-.chat-md-video {
+.chat-md-video-shell {
+ position: relative;
display: block;
+ width: min(640px, 100%);
max-width: 100%;
- max-height: 360px;
- border-radius: 6px;
+ aspect-ratio: 16 / 9;
margin: 6px 0;
+ overflow: hidden;
+ border-radius: 6px;
+ background: #000;
+}
+.chat-md-video {
+ display: block;
+ width: 100%;
+ height: 100%;
+ border-radius: 0;
+ margin: 0;
+ object-fit: contain;
background: #000;
}
.chat-md-video::-webkit-media-controls-fullscreen-button,
@@ -5856,6 +5880,13 @@ body.model-not-configured .main-content { flex-direction: column; }
.chat-msg-produced .chat-msg-produced-item.is-produced-overflow {
display: none;
}
+.chat-msg-produced.is-expanded {
+ max-height: 168px;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ padding-right: 2px;
+ scrollbar-gutter: stable;
+}
.chat-msg-produced.is-expanded .chat-msg-produced-item.is-produced-overflow {
display: inline-flex;
}
diff --git a/test/main/features/builtin_marketplace.test.ts b/test/main/features/builtin_marketplace.test.ts
index 998810ad..b8a7d196 100644
--- a/test/main/features/builtin_marketplace.test.ts
+++ b/test/main/features/builtin_marketplace.test.ts
@@ -4,15 +4,17 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
+import {
+ MARKETPLACE_RESOURCE_MANIFEST_NAME,
+ marketplaceContentTreeFiles,
+ marketplaceContentTreeHash,
+} from '../../../src/main/util/marketplace-tree-hash';
+
const postJsonMock = vi.hoisted(() => vi.fn());
-const devtoolsMock = vi.hoisted(() => ({ isDev: false }));
vi.mock('../../../src/main/features/marketplace', () => ({
postJson: postJsonMock,
}));
-vi.mock('../../../src/main/features/devtools', () => ({
- isDevEnv: () => devtoolsMock.isDev,
-}));
let tmpDir: string;
let prevWs: string | undefined;
@@ -26,7 +28,6 @@ beforeEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
process.env.ORKAS_BUILTIN_ROOT = path.join(tmpDir, 'builtin');
postJsonMock.mockReset();
- devtoolsMock.isDev = false;
vi.resetModules();
});
@@ -45,6 +46,12 @@ function writeBuiltinAgent(dir: string, agentJson: Record<string, unknown>): voi
fs.writeFileSync(path.join(root, 'agent.json'), JSON.stringify({ agent_id: dir, ...agentJson }, null, 2), 'utf8');
}
+function writeBuiltinAgentMeta(dir: string, meta: Record<string, unknown>): void {
+ const root = path.join(tmpDir, 'builtin', 'marketplace', 'agents', dir);
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(path.join(root, '_meta.json'), JSON.stringify(meta, null, 2), 'utf8');
+}
+
function writeBuiltinAgentSkill(agentDir: string, skillDir: string, name = skillDir): void {
const root = path.join(tmpDir, 'builtin', 'marketplace', 'agents', agentDir, 'skills', skillDir);
fs.mkdirSync(root, { recursive: true });
@@ -67,6 +74,18 @@ function sha256(text: string): string {
return crypto.createHash('sha256').update(text).digest('hex');
}
+function writeResourceSeedManifest(dir: string, kind: 'agent' | 'skill', id: string): void {
+ fs.writeFileSync(path.join(dir, MARKETPLACE_RESOURCE_MANIFEST_NAME), JSON.stringify({
+ schemaVersion: 1,
+ hashAlgorithm: 'sha256-tree-v1',
+ kind,
+ id,
+ resource_hash: marketplaceContentTreeHash(dir),
+ resource_online_hash: 'online-hash',
+ files: marketplaceContentTreeFiles(dir),
+ }, null, 2), 'utf8');
+}
+
describe('builtin marketplace seed', () => {
it('seeds agents and skills without requiring marketplace versions', async () => {
writeBuiltinAgent(TEST_AGENT_ID, {
@@ -145,6 +164,14 @@ describe('builtin marketplace seed', () => {
const paths = await import('../../../src/main/paths');
const installs = await import('../../../src/main/features/marketplace_installs');
await seed.seedBuiltinMarketplaceForUser('u1');
+ const localAgentDir = paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID);
+ fs.writeFileSync(path.join(localAgentDir, 'runtime-note.txt'), 'keep me\n', 'utf8');
+ const initialMetaPath = path.join(localAgentDir, '_install.json');
+ const initialMeta = JSON.parse(fs.readFileSync(initialMetaPath, 'utf8'));
+ fs.writeFileSync(initialMetaPath, JSON.stringify({
+ ...initialMeta,
+ status: 'approved',
+ }, null, 2), 'utf8');
writeBuiltinAgent(TEST_AGENT_ID, {
agent_id: TEST_AGENT_ID,
@@ -164,9 +191,12 @@ describe('builtin marketplace seed', () => {
const agentJson = JSON.parse(fs.readFileSync(path.join(paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID), 'agent.json'), 'utf8'));
expect(agentJson.version).toBe('1.1.0');
expect(agentJson.workflow).toBe('Write new.');
+ expect(fs.readFileSync(path.join(localAgentDir, 'runtime-note.txt'), 'utf8')).toBe('keep me\n');
const meta = JSON.parse(fs.readFileSync(path.join(paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID), '_install.json'), 'utf8'));
expect(meta.version).toBe('1.1.0');
expect(meta.seed_source).toBe('builtin');
+ expect(meta.status).toBe('approved');
+ expect(meta.builtin_files).toContain('agent.json');
const manifest = await installs.readInstalls('u1');
expect(manifest.agents[0]).toMatchObject({
id: TEST_AGENT_ID,
@@ -209,7 +239,122 @@ describe('builtin marketplace seed', () => {
expect(agentJson.workflow).toBe('Write revised.');
});
- it('does not overwrite resolved marketplace agent content with packaged builtin content', async () => {
+ it('refreshes builtin agent content when the local install has no version', async () => {
+ writeBuiltinAgent(TEST_AGENT_ID, {
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Writes things',
+ category: 'general',
+ workflow: 'Write old.',
+ updated_at: '2026-01-01T00:00:00Z',
+ });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ await seed.seedBuiltinMarketplaceForUser('u1');
+
+ const localRoot = paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID);
+ fs.writeFileSync(path.join(localRoot, 'agent.json'), JSON.stringify({
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Local stale copy',
+ category: 'general',
+ workflow: 'Write stale.',
+ }, null, 2), 'utf8');
+ const metaPath = path.join(localRoot, '_install.json');
+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
+ delete meta.version;
+ fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8');
+
+ writeBuiltinAgent(TEST_AGENT_ID, {
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Writes things',
+ category: 'general',
+ workflow: 'Write restored.',
+ updated_at: '2026-01-01T00:00:00Z',
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_agents: 1,
+ manifest_agents: 0,
+ });
+
+ const agentJson = JSON.parse(fs.readFileSync(path.join(localRoot, 'agent.json'), 'utf8'));
+ expect(agentJson.workflow).toBe('Write restored.');
+ const refreshedMeta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
+ expect(refreshedMeta.version).toBe('1.0.0');
+ });
+
+ it('does not overwrite resolved marketplace agent content when packaged builtin is not newer', async () => {
+ writeBuiltinAgent(TEST_AGENT_ID, {
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Writes things',
+ category: 'general',
+ workflow: 'Write bundled.',
+ updated_at: '2026-01-01T00:00:00Z',
+ });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ await seed.seedBuiltinMarketplaceForUser('u1');
+ const localUpdatedAt = Date.parse('2026-01-05T00:00:00Z');
+ await installs.addAgentInstall('u1', {
+ id: TEST_AGENT_ID,
+ version: '1.0.0',
+ published_at: localUpdatedAt,
+ agent_json_url: 'https://cdn.test/writer.json',
+ agent_skills_bundle_url: '',
+ create_uid: '0',
+ default_install: true,
+ });
+ const officialAgentJson = JSON.stringify({
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Official copy',
+ category: 'general',
+ workflow: 'Write official.',
+ }, null, 2);
+ const localAgentDir = paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID);
+ fs.writeFileSync(path.join(localAgentDir, 'agent.json'), officialAgentJson, 'utf8');
+ fs.writeFileSync(path.join(localAgentDir, '_install.json'), JSON.stringify({
+ version: '1.0.0',
+ published_at: localUpdatedAt,
+ agent_json_url: 'https://cdn.test/writer.json',
+ agent_skills_bundle_url: '',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: true,
+ content_sha: sha256(officialAgentJson),
+ }, null, 2), 'utf8');
+
+ writeBuiltinAgent(TEST_AGENT_ID, {
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Bundled same-version copy',
+ category: 'general',
+ workflow: 'Write bundled same version.',
+ updated_at: '2026-01-04T00:00:00Z',
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_agents: 0,
+ manifest_agents: 0,
+ });
+
+ const agentJson = JSON.parse(fs.readFileSync(path.join(paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID), 'agent.json'), 'utf8'));
+ expect(agentJson.workflow).toBe('Write official.');
+ });
+
+ it('overlays newer builtin agent content onto a lower-version marketplace install', async () => {
writeBuiltinAgent(TEST_AGENT_ID, {
agent_id: TEST_AGENT_ID,
version: '1.0.0',
@@ -234,22 +379,31 @@ describe('builtin marketplace seed', () => {
create_uid: '0',
default_install: true,
});
- fs.writeFileSync(
- path.join(paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID), 'agent.json'),
- JSON.stringify({
- agent_id: TEST_AGENT_ID,
- version: '1.0.0',
- name: 'Writer',
- description: 'Official copy',
- category: 'general',
- workflow: 'Write official.',
- }, null, 2),
- 'utf8',
- );
+ const officialAgentJson = JSON.stringify({
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Official copy',
+ category: 'general',
+ workflow: 'Write official.',
+ }, null, 2);
+ const localAgentDir = paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID);
+ fs.writeFileSync(path.join(localAgentDir, 'agent.json'), officialAgentJson, 'utf8');
+ fs.writeFileSync(path.join(localAgentDir, '_install.json'), JSON.stringify({
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 10,
+ agent_json_url: 'https://cdn.test/writer.json',
+ agent_skills_bundle_url: '',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: true,
+ content_sha: sha256(officialAgentJson),
+ }, null, 2), 'utf8');
writeBuiltinAgent(TEST_AGENT_ID, {
agent_id: TEST_AGENT_ID,
- version: '9.0.0',
+ version: '1.1.0',
name: 'Writer',
description: 'Bundled newer copy',
category: 'general',
@@ -258,17 +412,99 @@ describe('builtin marketplace seed', () => {
});
await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
- seeded_agents: 0,
+ seeded_agents: 1,
manifest_agents: 0,
});
- const agentJson = JSON.parse(fs.readFileSync(path.join(paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID), 'agent.json'), 'utf8'));
- expect(agentJson.workflow).toBe('Write official.');
+ const agentJson = JSON.parse(fs.readFileSync(path.join(localAgentDir, 'agent.json'), 'utf8'));
+ expect(agentJson.version).toBe('1.1.0');
+ expect(agentJson.workflow).toBe('Write bundled newer.');
+ const meta = JSON.parse(fs.readFileSync(path.join(localAgentDir, '_install.json'), 'utf8'));
+ expect(meta).toMatchObject({
+ version: '1.1.0',
+ seed_source: 'builtin',
+ agent_json_url: 'https://cdn.test/writer.json',
+ });
+ });
+
+ it('overlays newer builtin agent content even when the marketplace install was locally edited', async () => {
+ writeBuiltinAgent(TEST_AGENT_ID, {
+ agent_id: TEST_AGENT_ID,
+ version: '1.1.0',
+ name: 'Writer',
+ description: 'Bundled newer copy',
+ category: 'general',
+ workflow: 'Write bundled newer.',
+ updated_at: '2026-01-04T00:00:00Z',
+ });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ await installs.addAgentInstall('u1', {
+ id: TEST_AGENT_ID,
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 10,
+ agent_json_url: 'https://cdn.test/writer.json',
+ agent_skills_bundle_url: '',
+ create_uid: '0',
+ default_install: true,
+ });
+
+ const originalAgentJson = JSON.stringify({
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Official copy',
+ category: 'general',
+ workflow: 'Write official.',
+ }, null, 2);
+ const editedAgentJson = JSON.stringify({
+ agent_id: TEST_AGENT_ID,
+ version: '1.0.0',
+ name: 'Writer',
+ description: 'Locally edited copy',
+ category: 'general',
+ workflow: 'Write locally edited.',
+ }, null, 2);
+ const localAgentDir = paths.userMarketplaceAgentDir('u1', TEST_AGENT_ID);
+ fs.mkdirSync(localAgentDir, { recursive: true });
+ fs.writeFileSync(path.join(localAgentDir, 'agent.json'), editedAgentJson, 'utf8');
+ fs.writeFileSync(path.join(localAgentDir, '_install.json'), JSON.stringify({
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 10,
+ agent_json_url: 'https://cdn.test/writer.json',
+ agent_skills_bundle_url: '',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: true,
+ content_sha: sha256(originalAgentJson),
+ }, null, 2), 'utf8');
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_agents: 1,
+ manifest_agents: 0,
+ });
+
+ const agentJson = JSON.parse(fs.readFileSync(path.join(localAgentDir, 'agent.json'), 'utf8'));
+ expect(agentJson.version).toBe('1.1.0');
+ expect(agentJson.workflow).toBe('Write bundled newer.');
+ const meta = JSON.parse(fs.readFileSync(path.join(localAgentDir, '_install.json'), 'utf8'));
+ expect(meta).toMatchObject({
+ version: '1.1.0',
+ seed_source: 'builtin',
+ agent_json_url: 'https://cdn.test/writer.json',
+ });
});
it('refreshes builtin skill content without replacing local-only files', async () => {
writeBuiltinSkill('ee99fbb42964', 'deep-research');
- writeBuiltinSkillMeta('ee99fbb42964', { version: '1.0.1' });
+ writeBuiltinSkillMeta('ee99fbb42964', {
+ version: '1.0.1',
+ updated_at: '2026-01-01T00:00:00Z',
+ });
const seed = await import('../../../src/main/features/builtin_marketplace');
const paths = await import('../../../src/main/paths');
@@ -280,6 +516,10 @@ describe('builtin marketplace seed', () => {
const builtinRoot = path.join(tmpDir, 'builtin', 'marketplace', 'skills', 'ee99fbb42964');
fs.mkdirSync(path.join(builtinRoot, 'scripts'), { recursive: true });
fs.writeFileSync(path.join(builtinRoot, 'scripts', 'guard.py'), 'print("ok")\n', 'utf8');
+ writeBuiltinSkillMeta('ee99fbb42964', {
+ version: '1.0.1',
+ updated_at: '2026-01-02T00:00:00Z',
+ });
await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
seeded_skills: 1,
@@ -291,16 +531,100 @@ describe('builtin marketplace seed', () => {
const meta = JSON.parse(fs.readFileSync(path.join(localRoot, '_install.json'), 'utf8'));
expect(meta.seed_source).toBe('builtin');
expect(meta.version).toBe('1.0.1');
+ expect(meta.updated_at).toBe(Date.parse('2026-01-02T00:00:00Z'));
expect(meta.content_tree_hash).toEqual(expect.any(String));
expect(meta.builtin_files).toContain('scripts/guard.py');
const manifest = await installs.readInstalls('u1');
expect(manifest.skills[0]).toMatchObject({
id: 'ee99fbb42964',
version: '1.0.1',
+ updated_at: Date.parse('2026-01-02T00:00:00Z'),
seed_source: 'builtin',
});
});
+ it('refreshes builtin skill seed when packaged version is newer even after local edits', async () => {
+ const skillId = 'ee99fbb42964';
+ writeBuiltinSkill(skillId, 'deep-research');
+ writeBuiltinSkillMeta(skillId, { version: '1.0.0' });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ await seed.seedBuiltinMarketplaceForUser('u1');
+
+ const localRoot = paths.userMarketplaceSkillDir('u1', skillId);
+ fs.writeFileSync(
+ path.join(localRoot, 'SKILL.md'),
+ '---\nname: deep-research\ndescription: edited\n---\n\nlocal edit\n',
+ 'utf8',
+ );
+
+ const builtinRoot = path.join(tmpDir, 'builtin', 'marketplace', 'skills', skillId);
+ fs.writeFileSync(
+ path.join(builtinRoot, 'SKILL.md'),
+ '---\nname: deep-research\ndescription: newer\n---\n\nnew builtin body\n',
+ 'utf8',
+ );
+ writeBuiltinSkillMeta(skillId, { version: '1.0.1' });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_skills: 1,
+ manifest_skills: 0,
+ });
+
+ expect(fs.readFileSync(path.join(localRoot, 'SKILL.md'), 'utf8')).toBe(
+ '---\nname: deep-research\ndescription: newer\n---\n\nnew builtin body\n',
+ );
+ const meta = JSON.parse(fs.readFileSync(path.join(localRoot, '_install.json'), 'utf8'));
+ expect(meta).toMatchObject({
+ version: '1.0.1',
+ seed_source: 'builtin',
+ });
+ });
+
+ it('refreshes builtin skill content when the local install has no version', async () => {
+ const skillId = 'ee99fbb42964';
+ writeBuiltinSkill(skillId, 'deep-research');
+ writeBuiltinSkillMeta(skillId, {
+ version: '1.0.1',
+ updated_at: '2026-01-01T00:00:00Z',
+ });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ await seed.seedBuiltinMarketplaceForUser('u1');
+
+ const localRoot = paths.userMarketplaceSkillDir('u1', skillId);
+ fs.writeFileSync(
+ path.join(localRoot, 'SKILL.md'),
+ '---\nname: deep-research\ndescription: edited\n---\n\nlocal edit\n',
+ 'utf8',
+ );
+ const metaPath = path.join(localRoot, '_install.json');
+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
+ delete meta.version;
+ fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8');
+
+ const builtinRoot = path.join(tmpDir, 'builtin', 'marketplace', 'skills', skillId);
+ fs.writeFileSync(
+ path.join(builtinRoot, 'SKILL.md'),
+ '---\nname: deep-research\ndescription: public\n---\n\nrestored builtin body\n',
+ 'utf8',
+ );
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_skills: 1,
+ manifest_skills: 0,
+ });
+
+ expect(fs.readFileSync(path.join(localRoot, 'SKILL.md'), 'utf8')).toBe(
+ '---\nname: deep-research\ndescription: public\n---\n\nrestored builtin body\n',
+ );
+ const refreshedMeta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
+ expect(refreshedMeta.version).toBe('1.0.1');
+ expect(refreshedMeta.updated_at).toBe(Date.parse('2026-01-01T00:00:00Z'));
+ });
+
it('refreshes legacy builtin skill seeds that predate seed_source and tree hashes', async () => {
const skillId = 'ee99fbb42964';
writeBuiltinSkill(skillId, 'deep-research');
@@ -392,6 +716,87 @@ describe('builtin marketplace seed', () => {
]);
});
+ it('re-seeds a builtin agent when packaged metadata supersedes an old uninstall tombstone', async () => {
+ const agentId = '78900d8758bc';
+ writeBuiltinAgent(agentId, {
+ version: '1.0.2',
+ name: 'DeepResearcher',
+ description: 'Research deeply',
+ category: 'data',
+ workflow: 'Research.',
+ updated_at: '2026-07-04T00:00:00Z',
+ });
+ writeBuiltinAgentMeta(agentId, {
+ reseed_if_deleted_before: '2026-07-05T00:00:00Z',
+ });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ await installs.writeInstalls('u1', {
+ version: installs.CURRENT_VERSION,
+ agents: [],
+ skills: [],
+ _deleted_at: {
+ agents: { [agentId]: Date.parse('2026-07-04T23:59:59Z') },
+ },
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_agents: 1,
+ manifest_agents: 1,
+ });
+
+ const agentJson = JSON.parse(fs.readFileSync(path.join(paths.userMarketplaceAgentDir('u1', agentId), 'agent.json'), 'utf8'));
+ expect(agentJson.name).toBe('DeepResearcher');
+ const manifest = await installs.readInstalls('u1');
+ expect(manifest._deleted_at?.agents?.[agentId]).toBeUndefined();
+ expect(manifest.agents).toEqual([
+ expect.objectContaining({
+ id: agentId,
+ version: '1.0.2',
+ seed_source: 'builtin',
+ }),
+ ]);
+ });
+
+ it('keeps a newer builtin agent uninstall tombstone respected', async () => {
+ const agentId = '78900d8758bc';
+ writeBuiltinAgent(agentId, {
+ version: '1.0.2',
+ name: 'DeepResearcher',
+ description: 'Research deeply',
+ category: 'data',
+ workflow: 'Research.',
+ updated_at: '2026-07-04T00:00:00Z',
+ });
+ writeBuiltinAgentMeta(agentId, {
+ reseed_if_deleted_before: '2026-07-05T00:00:00Z',
+ });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ await installs.writeInstalls('u1', {
+ version: installs.CURRENT_VERSION,
+ agents: [],
+ skills: [],
+ _deleted_at: {
+ agents: { [agentId]: Date.parse('2026-07-05T00:00:00Z') },
+ },
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_agents: 0,
+ manifest_agents: 0,
+ });
+
+ expect(fs.existsSync(path.join(paths.userMarketplaceAgentDir('u1', agentId), 'agent.json'))).toBe(false);
+ const manifest = await installs.readInstalls('u1');
+ expect(manifest._deleted_at?.agents?.[agentId]).toEqual(Date.parse('2026-07-05T00:00:00Z'));
+ expect(manifest.agents).toEqual([]);
+ });
+
it('keeps a newer builtin skill uninstall tombstone respected', async () => {
const skillId = 'ee99fbb42964';
writeBuiltinSkill(skillId, 'deep-research');
@@ -423,6 +828,240 @@ describe('builtin marketplace seed', () => {
expect(manifest.skills).toEqual([]);
});
+ it('overlays newer builtin skill content onto a lower-version marketplace install', async () => {
+ const skillId = 'ee99fbb42964';
+ writeBuiltinSkill(skillId, 'deep-research');
+ const builtinRoot = path.join(tmpDir, 'builtin', 'marketplace', 'skills', skillId);
+ writeBuiltinSkillMeta(skillId, { version: '1.0.1' });
+ fs.mkdirSync(path.join(builtinRoot, 'scripts'), { recursive: true });
+ fs.writeFileSync(path.join(builtinRoot, 'scripts', 'guard.py'), 'print("ok")\n', 'utf8');
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ const localRoot = paths.userMarketplaceSkillDir('u1', skillId);
+ fs.mkdirSync(localRoot, { recursive: true });
+ const oldSkill = '---\nname: deep-research\ndescription: old\n---\n\nold body\n';
+ fs.writeFileSync(path.join(localRoot, 'SKILL.md'), oldSkill, 'utf8');
+ fs.writeFileSync(path.join(localRoot, 'runtime-note.txt'), 'keep me\n', 'utf8');
+ fs.writeFileSync(path.join(localRoot, '_install.json'), JSON.stringify({
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: false,
+ status: 'approved',
+ content_sha: sha256(oldSkill),
+ }, null, 2), 'utf8');
+ await installs.addSkillInstall('u1', {
+ id: skillId,
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: false,
+ status: 'approved',
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_skills: 1,
+ manifest_skills: 0,
+ });
+
+ expect(fs.readFileSync(path.join(localRoot, 'runtime-note.txt'), 'utf8')).toBe('keep me\n');
+ expect(fs.existsSync(path.join(localRoot, 'scripts', 'guard.py'))).toBe(true);
+ const localMeta = JSON.parse(fs.readFileSync(path.join(localRoot, '_install.json'), 'utf8'));
+ expect(localMeta).toMatchObject({
+ version: '1.0.1',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: false,
+ status: 'approved',
+ seed_source: 'builtin',
+ });
+ expect(localMeta.content_sha).toEqual(expect.any(String));
+ expect(localMeta.content_tree_hash).toEqual(expect.any(String));
+ expect(localMeta.builtin_files).toContain('scripts/guard.py');
+
+ const manifest = await installs.readInstalls('u1');
+ expect(manifest.skills).toEqual([
+ expect.objectContaining({
+ id: skillId,
+ version: '1.0.0',
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ }),
+ ]);
+ expect((manifest.skills[0] as any).seed_source).toBeUndefined();
+
+ const users = await import('../../../src/main/features/users');
+ users.activateUser('u1');
+ const skills = await import('../../../src/main/features/skills');
+ expect((await skills.listSkills()).find((s) => s.id === skillId)?.version).toBe('1.0.1');
+ });
+
+ it('does not hand off a resource-owned marketplace skill when packaged builtin is not newer', async () => {
+ const skillId = '9be6fda271a5';
+ writeBuiltinSkill(skillId, 'material-organizer');
+ writeBuiltinSkillMeta(skillId, { version: '1.0.1' });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ const localRoot = paths.userMarketplaceSkillDir('u1', skillId);
+ fs.mkdirSync(localRoot, { recursive: true });
+ const skillBody = '---\nname: material-organizer\ndescription: public\n---\n\npublic body\n';
+ fs.writeFileSync(path.join(localRoot, 'SKILL.md'), skillBody, 'utf8');
+ writeResourceSeedManifest(localRoot, 'skill', skillId);
+ fs.writeFileSync(path.join(localRoot, '_install.json'), JSON.stringify({
+ version: '1.0.1',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/material-organizer.zip',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: false,
+ status: 'approved',
+ content_sha: sha256(skillBody),
+ seed_source: 'resource',
+ }, null, 2), 'utf8');
+ await installs.addSkillInstall('u1', {
+ id: skillId,
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/material-organizer.zip',
+ installed_at: 12,
+ create_uid: '0',
+ default_install: false,
+ status: 'approved',
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_skills: 0,
+ manifest_skills: 0,
+ });
+
+ expect(fs.readFileSync(path.join(localRoot, 'SKILL.md'), 'utf8')).toBe(skillBody);
+ expect(fs.existsSync(path.join(localRoot, MARKETPLACE_RESOURCE_MANIFEST_NAME))).toBe(true);
+ const localMeta = JSON.parse(fs.readFileSync(path.join(localRoot, '_install.json'), 'utf8'));
+ expect(localMeta).toMatchObject({
+ version: '1.0.1',
+ bundle_url: 'https://cdn.test/material-organizer.zip',
+ seed_source: 'resource',
+ });
+ const manifest = await installs.readInstalls('u1');
+ expect(manifest.skills[0]).toMatchObject({
+ id: skillId,
+ version: '1.0.0',
+ bundle_url: 'https://cdn.test/material-organizer.zip',
+ });
+ expect((manifest.skills[0] as any).seed_source).toBeUndefined();
+ });
+
+ it('overlays newer builtin skill over a resource-owned marketplace skill even after local edits', async () => {
+ const skillId = '6743aa0797a2';
+ writeBuiltinSkill(skillId, 'brand-research');
+ writeBuiltinSkillMeta(skillId, { version: '1.0.2' });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ const localRoot = paths.userMarketplaceSkillDir('u1', skillId);
+ fs.mkdirSync(localRoot, { recursive: true });
+ const originalSkill = '---\nname: brand-research\ndescription: public\n---\n\npublic body\n';
+ const editedSkill = '---\nname: brand-research\ndescription: edited\n---\n\nlocal edit\n';
+ fs.writeFileSync(path.join(localRoot, 'SKILL.md'), originalSkill, 'utf8');
+ writeResourceSeedManifest(localRoot, 'skill', skillId);
+ fs.writeFileSync(path.join(localRoot, 'SKILL.md'), editedSkill, 'utf8');
+ fs.writeFileSync(path.join(localRoot, '_install.json'), JSON.stringify({
+ version: '1.0.1',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/brand-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ content_sha: sha256(originalSkill),
+ seed_source: 'resource',
+ }, null, 2), 'utf8');
+ await installs.addSkillInstall('u1', {
+ id: skillId,
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/brand-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_skills: 1,
+ manifest_skills: 0,
+ });
+
+ expect(fs.readFileSync(path.join(localRoot, 'SKILL.md'), 'utf8')).toBe(originalSkill);
+ const localMeta = JSON.parse(fs.readFileSync(path.join(localRoot, '_install.json'), 'utf8'));
+ expect(localMeta).toMatchObject({
+ version: '1.0.2',
+ seed_source: 'builtin',
+ bundle_url: 'https://cdn.test/brand-research.zip',
+ });
+ expect(fs.existsSync(path.join(localRoot, MARKETPLACE_RESOURCE_MANIFEST_NAME))).toBe(false);
+ });
+
+ it('overlays newer builtin skill content even when the marketplace install was locally edited', async () => {
+ const skillId = 'ee99fbb42964';
+ writeBuiltinSkill(skillId, 'deep-research');
+ const builtinRoot = path.join(tmpDir, 'builtin', 'marketplace', 'skills', skillId);
+ writeBuiltinSkillMeta(skillId, { version: '1.0.1' });
+
+ const seed = await import('../../../src/main/features/builtin_marketplace');
+ const paths = await import('../../../src/main/paths');
+ const installs = await import('../../../src/main/features/marketplace_installs');
+ const localRoot = paths.userMarketplaceSkillDir('u1', skillId);
+ fs.mkdirSync(localRoot, { recursive: true });
+ const originalSkill = '---\nname: deep-research\ndescription: old\n---\n\nold body\n';
+ const editedSkill = '---\nname: deep-research\ndescription: edited\n---\n\nlocal edit\n';
+ fs.writeFileSync(path.join(localRoot, 'SKILL.md'), editedSkill, 'utf8');
+ fs.writeFileSync(path.join(localRoot, '_install.json'), JSON.stringify({
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ content_sha: sha256(originalSkill),
+ }, null, 2), 'utf8');
+ await installs.addSkillInstall('u1', {
+ id: skillId,
+ version: '1.0.0',
+ published_at: 10,
+ updated_at: 11,
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ installed_at: 12,
+ create_uid: '0',
+ });
+
+ await expect(seed.seedBuiltinMarketplaceForUser('u1')).resolves.toMatchObject({
+ seeded_skills: 1,
+ manifest_skills: 0,
+ });
+
+ expect(fs.readFileSync(path.join(localRoot, 'SKILL.md'), 'utf8')).toBe('---\nname: deep-research\ndescription: public\n---\n\npublic body\n');
+ const localMeta = JSON.parse(fs.readFileSync(path.join(localRoot, '_install.json'), 'utf8'));
+ expect(localMeta).toMatchObject({
+ version: '1.0.1',
+ seed_source: 'builtin',
+ bundle_url: 'https://cdn.test/deep-research.zip',
+ });
+ });
+
it('resolves builtin skill seed rows to official marketplace rows by exact id', async () => {
writeBuiltinSkill('seo-crawl', 'SEO Crawl');
const seed = await import('../../../src/main/features/builtin_marketplace');
diff --git a/test/main/features/chat_attachments.test.ts b/test/main/features/chat_attachments.test.ts
index fc2425a8..e02d6a66 100644
--- a/test/main/features/chat_attachments.test.ts
+++ b/test/main/features/chat_attachments.test.ts
@@ -31,6 +31,14 @@ function attDir(): string {
return path.join(tmpDir, UID, 'cloud', 'chat_attachments', CID);
}
+function cloudAttDir(cid: string): string {
+ return path.join(tmpDir, UID, 'cloud', 'chat_attachments', cid);
+}
+
+function draftAttDir(cid: string): string {
+ return path.join(tmpDir, UID, 'local', 'chat_attachment_drafts', cid);
+}
+
async function loadMod() {
return import('../../../src/main/features/chat_attachments');
}
@@ -54,6 +62,16 @@ describe('chat_attachments › uploadAttachment', () => {
expect(siblings).toEqual([]);
});
+ it('stores commander draft attachments in local-only storage', async () => {
+ const m = await loadMod();
+ const r = await m.uploadAttachment(UID, 'main_chat', 'draft.txt', Buffer.from('hi', 'utf8'));
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(fs.existsSync(path.join(draftAttDir('main_chat'), 'draft.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(cloudAttDir('main_chat'), 'draft.txt'))).toBe(false);
+ expect(m.listPendingAttachments(UID, 'main_chat').map((i) => i.name)).toEqual(['draft.txt']);
+ });
+
it('stores PDF without pre-extracting (no sibling cache files)', async () => {
const m = await loadMod();
const r = await m.uploadAttachment(UID, CID, 'report.pdf', makeMinimalPdf(['Page One', 'Page Two']));
@@ -360,23 +378,20 @@ describe('chat_attachments › purgeByCid', () => {
describe('chat_attachments › adoptDraftAttachments', () => {
const DRAFT = 'main_chat';
- function dirFor(cid: string): string {
- return path.join(tmpDir, UID, 'cloud', 'chat_attachments', cid);
- }
-
it('renames draft dir to target cid when target does not exist', async () => {
const m = await loadMod();
await m.uploadAttachment(UID, DRAFT, 'note.txt', Buffer.from('hi'));
await m.uploadAttachment(UID, DRAFT, 'doc.pdf', makeMinimalPdf(['p1']));
- expect(fs.existsSync(dirFor(DRAFT))).toBe(true);
+ expect(fs.existsSync(draftAttDir(DRAFT))).toBe(true);
+ expect(fs.existsSync(cloudAttDir(DRAFT))).toBe(false);
const r = m.adoptDraftAttachments(UID, DRAFT, CID);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.count).toBe(2);
- expect(fs.existsSync(dirFor(DRAFT))).toBe(false);
- expect(fs.existsSync(path.join(dirFor(CID), 'note.txt'))).toBe(true);
- expect(fs.existsSync(path.join(dirFor(CID), 'doc.pdf'))).toBe(true);
+ expect(fs.existsSync(draftAttDir(DRAFT))).toBe(false);
+ expect(fs.existsSync(path.join(cloudAttDir(CID), 'note.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(cloudAttDir(CID), 'doc.pdf'))).toBe(true);
});
it('returns count=0 without error when draft dir is absent', async () => {
@@ -401,9 +416,20 @@ describe('chat_attachments › adoptDraftAttachments', () => {
const r = m.adoptDraftAttachments(UID, DRAFT, CID);
expect(r.ok).toBe(true);
if (!r.ok) return;
- expect(fs.existsSync(path.join(dirFor(CID), 'kept.txt'))).toBe(true);
- expect(fs.existsSync(path.join(dirFor(CID), 'new.txt'))).toBe(true);
- expect(fs.existsSync(dirFor(DRAFT))).toBe(false);
+ expect(fs.existsSync(path.join(cloudAttDir(CID), 'kept.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(cloudAttDir(CID), 'new.txt'))).toBe(true);
+ expect(fs.existsSync(draftAttDir(DRAFT))).toBe(false);
+ });
+
+ it('migrates legacy cloud draft attachments back to local storage on access', async () => {
+ const m = await loadMod();
+ fs.mkdirSync(cloudAttDir(DRAFT), { recursive: true });
+ fs.writeFileSync(path.join(cloudAttDir(DRAFT), 'legacy.txt'), 'old draft');
+
+ const items = m.listPendingAttachments(UID, DRAFT);
+ expect(items.map((i) => i.name)).toEqual(['legacy.txt']);
+ expect(fs.existsSync(path.join(draftAttDir(DRAFT), 'legacy.txt'))).toBe(true);
+ expect(fs.existsSync(cloudAttDir(DRAFT))).toBe(false);
});
});
@@ -864,3 +890,40 @@ describe('chat_attachments › buildAttachmentManifest', () => {
expect(r.skipped[0].reason).toMatch(/no longer exists|不存在/);
});
});
+
+describe('chat_attachments › buildConversationAttachmentIndex', () => {
+ it('lists persisted conversation attachments without leaking file bodies', async () => {
+ const m = await loadMod();
+ const body = '# Orkas 1.0.5\nRelease note: local attachment index stays lightweight.';
+ await m.uploadAttachment(UID, CID, 'orkas-1.0.5-update.md', Buffer.from(body, 'utf8'));
+ await m.uploadAttachment(UID, CID, 'intro.mp4', Buffer.from('fake-video'));
+ await m.uploadAttachment(UID, CID, 'logo.png', Buffer.from('fake-image'));
+
+ const index = await m.buildConversationAttachmentIndex(UID, CID);
+
+ expect(index).toContain('<conversation-attachments');
+ expect(index).toContain('name="orkas-1.0.5-update.md"');
+ expect(index).toContain('kind="text"');
+ expect(index).toContain(`total_chars="${body.length}"`);
+ expect(index).toContain('name="intro.mp4"');
+ expect(index).toContain('kind="video"');
+ expect(index).toContain('model_readable="false"');
+ expect(index).toContain('name="logo.png"');
+ expect(index).toContain('kind="image"');
+ expect(index).toContain('inline="false"');
+ expect(index).not.toContain('local attachment index stays lightweight');
+ });
+
+ it('excludes current-turn attachment names already covered by the manifest', async () => {
+ const m = await loadMod();
+ await m.uploadAttachment(UID, CID, 'old.md', Buffer.from('old', 'utf8'));
+ await m.uploadAttachment(UID, CID, 'current.md', Buffer.from('current', 'utf8'));
+
+ const index = await m.buildConversationAttachmentIndex(UID, CID, {
+ excludeNames: ['current.md'],
+ });
+
+ expect(index).toContain('name="old.md"');
+ expect(index).not.toContain('name="current.md"');
+ });
+});
diff --git a/test/main/features/group_chat/bus-integration.test.ts b/test/main/features/group_chat/bus-integration.test.ts
index b5dd2d26..bbe964d9 100644
--- a/test/main/features/group_chat/bus-integration.test.ts
+++ b/test/main/features/group_chat/bus-integration.test.ts
@@ -969,6 +969,55 @@ describe('group_chat bus integration › G8d in-process dispatch (run_worker / d
expect(commanderCallsAfter, 'commander must NOT run for the no-@ follow-up while handed off').toBe(commanderCallsBefore);
}, 15_000);
+ it('manual @ to another agent while handed off makes that agent the sticky floor', async () => {
+ const cid = newCid();
+ const state = await import('../../../../src/main/features/group_chat/state');
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+
+ const tutorId = 'a11122223333';
+ const tutorName = 'TutorA';
+ const tutorDir = paths.agentDir(TEST_UID, tutorId);
+ fs.mkdirSync(tutorDir, { recursive: true });
+ fs.writeFileSync(path.join(tutorDir, 'agent.json'), JSON.stringify({
+ agent_id: tutorId, name: tutorName, description: 'interactive tutor', workflow: 'teach',
+ interactive: true, created_at: 't', updated_at: 't',
+ }));
+
+ _setScript(state.buildGconvSessionId(cid), [
+ { type: '__call_tool__', name: 'hand_off_to', input: { to: tutorName, message: 'teach this' } },
+ { type: 'final', text: 'Over to TutorA.' },
+ ]);
+ _setScript(state.buildGmemberSessionId(cid, tutorId), [
+ { type: 'final', text: 'TutorA: ready.' },
+ ]);
+
+ bus.subscribe(TEST_UID, cid, () => {});
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'teach me' });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ expect((await state.readState(TEST_UID, cid)).active_recipient).toBe(tutorId);
+
+ _setScript(state.buildGmemberSessionId(cid, AGENT_ID), [
+ { type: 'final', text: 'Writer: switching context.' },
+ ]);
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: `@${AGENT_NAME} quick aside` });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+ expect((await state.readState(TEST_UID, cid)).active_recipient).toBe(AGENT_ID);
+
+ const tutorCallsBefore = _recordedCalls.filter((c) => c.sid === state.buildGmemberSessionId(cid, tutorId)).length;
+ const writerCallsBefore = _recordedCalls.filter((c) => c.sid === state.buildGmemberSessionId(cid, AGENT_ID)).length;
+ _setScript(state.buildGmemberSessionId(cid, AGENT_ID), [
+ { type: 'final', text: 'Writer: still here.' },
+ ]);
+ await bus.enqueue({ uid: TEST_UID, cid, fromActorId: 'user', text: 'continue with that' });
+ await waitForQuiescent(TEST_UID, cid, 4000);
+
+ const tutorCallsAfter = _recordedCalls.filter((c) => c.sid === state.buildGmemberSessionId(cid, tutorId)).length;
+ const writerCallsAfter = _recordedCalls.filter((c) => c.sid === state.buildGmemberSessionId(cid, AGENT_ID)).length;
+ expect(writerCallsAfter, 'no-@ follow-up should stay with the manually selected agent').toBe(writerCallsBefore + 1);
+ expect(tutorCallsAfter, 'no-@ follow-up must not snap back to the previous hand-off agent').toBe(tutorCallsBefore);
+ }, 15_000);
+
// hand_off_to a NON-interactive agent: it answers the user (one-shot, saving the
// commander's synthesis call), but the floor stays with the commander.
it('hand_off_to non-interactive agent: one-shot answer, floor stays commander', async () => {
diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.ts
index 52d8c7d8..ae4b87df 100644
--- a/test/main/features/group_chat/bus.test.ts
+++ b/test/main/features/group_chat/bus.test.ts
@@ -172,6 +172,33 @@ describe('group_chat bus › enqueue routing + persistence', () => {
expect(visibility.buildReplayPrefix(slice, 'missing').prefix).toContain('Please resolve the conflict using the hidden protocol.');
});
+ it('keeps earlier conversation attachments visible on later turns without reattaching', async () => {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const attachments = await import('../../../../src/main/features/chat_attachments');
+ const cid = 'cid-attachment-index';
+
+ await attachments.uploadAttachment(
+ TEST_UID,
+ cid,
+ 'orkas-1.0.5-update.md',
+ Buffer.from('# Orkas 1.0.5\nAttachment index keeps old files discoverable.', 'utf8'),
+ );
+
+ await bus.enqueue({
+ uid: TEST_UID,
+ cid,
+ fromActorId: 'user',
+ text: 'please check the old md again',
+ });
+ await waitForQuiescent(TEST_UID, cid);
+
+ const call = streamProbe.messages.find((m) => m.includes('please check the old md again')) || '';
+ expect(call).toContain('<conversation-attachments');
+ expect(call).toContain('name="orkas-1.0.5-update.md"');
+ expect(call).toContain('kind="text"');
+ expect(call).toContain('total_chars=');
+ });
+
it('strips commander result markers and records commander model failures', async () => {
const bus = await import('../../../../src/main/features/group_chat/bus');
const paths = await import('../../../../src/main/paths');
diff --git a/test/main/features/group_chat/router.test.ts b/test/main/features/group_chat/router.test.ts
index d378361a..83520ab3 100644
--- a/test/main/features/group_chat/router.test.ts
+++ b/test/main/features/group_chat/router.test.ts
@@ -108,7 +108,7 @@ describe('group_chat router › resolveRecipients', () => {
expect(r.to).toEqual(['commander']);
});
- it('user one-shot @<otherAgent> while handed off routes only to that agent', () => {
+ it('user explicit @<otherAgent> while handed off routes only to that agent', () => {
const members2 = [...members, { kind: 'agent' as const, id: 'coder', joined_at: 't' }];
const r = resolveRecipients({
fromKind: 'user', fromId: 'user', text: '@coder quick q', members: members2,
diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.ts
index 21ad956b..0d1634e0 100644
--- a/test/main/model/core-agent/tool-catalog.test.ts
+++ b/test/main/model/core-agent/tool-catalog.test.ts
@@ -7,7 +7,7 @@ import {
getToolsSystemPromptBlock,
isToolVisibleToAgent,
} from '../../../../src/main/model/core-agent/tool-catalog';
-import { getBuiltinTools } from '../../../../src/core-agent/src/tools';
+import { getBuiltinTools, toToolDefinition, type AgentTool } from '../../../../src/core-agent/src/tools';
import { createCrossSessionMemoryTool } from '../../../../src/core-agent/src/tools/memory-tool';
import { createMetacognitionTool } from '../../../../src/core-agent/src/tools/metacognition-tool';
import { createLocalTools, createFileTools } from '../../../../src/main/model/core-agent/local-tools';
@@ -17,9 +17,13 @@ import { createImageGenTool } from '../../../../src/main/model/core-agent/image-
import { createOfficeTools } from '../../../../src/main/model/core-agent/office-tools';
const DEEP_RESEARCH_SKILL_ID = 'ee99fbb42964';
+const TOOL_DESCRIPTION_REVIEW_CHARS = 900;
+const PARAM_DESCRIPTION_REVIEW_CHARS = 280;
+const SOURCE_DESCRIPTION_BUDGET_EXCEPTIONS = new Set([
+ 'generate_image:/inputSchema/properties/output_path',
+]);
const RERANK_OWNER_AGENT_RESOURCES = [
- { id: 'b6ddc5e6b432', name: '深度研究', kind: 'builtin', hasDeepResearchSkill: true },
{ id: '78900d8758bc', name: 'DeepResearcher', kind: 'builtin', hasDeepResearchSkill: true },
{ id: '5dd962efb425', name: 'KnowledgeManager', kind: 'resource', hasDeepResearchSkill: false },
{ id: '17c0a2e95df3', name: 'SocialResearcher', kind: 'resource', hasDeepResearchSkill: true },
@@ -47,37 +51,45 @@ function agentJsonPath(spec: typeof RERANK_OWNER_AGENT_RESOURCES[number]): strin
* Avoid buildRunner here because that pulls in auth / session / network; call
* the same factories runner.ts uses to assemble allTools.
*/
-function enumerateAllInjectedToolNames(): Set<string> {
- const names = new Set<string>();
+function enumerateAllInjectedTools(): AgentTool[] {
+ const tools: AgentTool[] = [];
// core-agent builtins (always merged into AgentRunner's tool map)
- for (const t of getBuiltinTools()) names.add(t.name);
+ tools.push(...getBuiltinTools());
// injected (memory + metacognition)
- names.add(
+ tools.push(
createCrossSessionMemoryTool({
- add: async () => {},
- replace: async () => {},
- remove: async () => {},
- list: async () => '',
- }).name,
+ add: () => ({ ok: true, entries: [], usage: { current: 0, limit: 1 } }),
+ replace: () => ({ ok: true, entries: [], usage: { current: 0, limit: 1 } }),
+ remove: () => ({ ok: true, entries: [], usage: { current: 0, limit: 1 } }),
+ list: () => ({ ok: true, entries: [], usage: { current: 0, limit: 1 } }),
+ }),
);
- names.add(
+ tools.push(
createMetacognitionTool({
- read: async () => '',
- write: async () => {},
- }).name,
+ read: () => ({ ok: true, content: '', usage: { current: 0, limit: 1 } }),
+ write: () => ({ ok: true, usage: { current: 0, limit: 1 } }),
+ }),
);
// local + file + kb + image gen.
// Pass cid + onArtifactCreated so `create_artifact` is included — runner.ts
// wires both through for group-chat turns (see local-tools.createLocalTools).
- for (const t of createLocalTools({ userId: 'testuid', cid: 'testcid', onArtifactCreated: () => {} })) names.add(t.name);
- for (const t of createFileTools({ userId: 'testuid', cid: 'testcid' })) names.add(t.name);
- for (const t of createKbTools({ userId: 'testuid' })) names.add(t.name);
- for (const t of createChatHistoryTools({ userId: 'testuid' })) names.add(t.name);
- names.add(createImageGenTool({ userId: 'testuid', cid: 'testcid' }).name);
- for (const t of createOfficeTools({ userId: 'testuid', cid: 'testcid' })) names.add(t.name);
+ tools.push(...createLocalTools({ userId: 'testuid', cid: 'testcid', onArtifactCreated: () => {} }));
+ tools.push(...createFileTools({ userId: 'testuid', cid: 'testcid' }));
+ tools.push(...createKbTools({ userId: 'testuid' }));
+ tools.push(...createChatHistoryTools({ userId: 'testuid' }));
+ tools.push(createImageGenTool({ userId: 'testuid', cid: 'testcid' }));
+ tools.push(...createOfficeTools({ userId: 'testuid', cid: 'testcid' }));
+
+ const byName = new Map<string, AgentTool>();
+ for (const tool of tools) byName.set(tool.name, tool);
+ return [...byName.values()];
+}
+
+function enumerateAllInjectedToolNames(): Set<string> {
+ const names = new Set(enumerateAllInjectedTools().map((t) => t.name));
// Connector umbrella meta-tools: two fixed tools, only injected when ≥1 connector is visible
// to the actor. Asserting presence in the catalog independent of runtime visibility — calling
@@ -90,6 +102,62 @@ function enumerateAllInjectedToolNames(): Set<string> {
return names;
}
+function walkSchemaDescriptions(
+ schema: unknown,
+ visit: (path: string, description: string) => void,
+ path = '/inputSchema',
+): void {
+ if (!schema || typeof schema !== 'object') return;
+ if (Array.isArray(schema)) {
+ schema.forEach((item, index) => walkSchemaDescriptions(item, visit, `${path}/${index}`));
+ return;
+ }
+ const obj = schema as Record<string, unknown>;
+ if (typeof obj.description === 'string') visit(path, obj.description);
+ for (const [key, value] of Object.entries(obj)) {
+ if (key === 'description') continue;
+ walkSchemaDescriptions(value, visit, `${path}/${escapePointerSegment(key)}`);
+ }
+}
+
+function descriptionAtPath(schema: unknown, path: string): string | undefined {
+ const parts = path
+ .replace(/^\/inputSchema/, '')
+ .split('/')
+ .filter(Boolean);
+ let cursor: unknown = schema;
+ for (const part of parts) {
+ const key = unescapePointerSegment(part);
+ if (Array.isArray(cursor)) {
+ cursor = cursor[Number(key)];
+ } else {
+ cursor = (cursor as Record<string, unknown>)?.[key];
+ }
+ }
+ return typeof (cursor as Record<string, unknown> | undefined)?.description === 'string'
+ ? ((cursor as Record<string, unknown>).description as string)
+ : undefined;
+}
+
+function escapePointerSegment(value: string): string {
+ return value.replace(/~/g, '~0').replace(/\//g, '~1');
+}
+
+function unescapePointerSegment(value: string): string {
+ return value.replace(/~1/g, '/').replace(/~0/g, '~');
+}
+
+function providerGuidanceText(tool: AgentTool): string {
+ const def = toToolDefinition(tool);
+ return `${def.description}\n${JSON.stringify(def.inputSchema)}`.toLowerCase();
+}
+
+function toolByName(name: string): AgentTool {
+ const tool = enumerateAllInjectedTools().find((t) => t.name === name);
+ if (!tool) throw new Error(`tool not enumerated: ${name}`);
+ return tool;
+}
+
describe('tool-catalog', () => {
it('TOOL_CATALOG covers every tool name injected by runner (anti-drift)', () => {
const injected = enumerateAllInjectedToolNames();
@@ -103,6 +171,68 @@ describe('tool-catalog', () => {
expect(names.length).toBe(new Set(names).size);
});
+ it('provider tool definition compaction preserves existing parameter descriptions', () => {
+ const lost: string[] = [];
+ for (const tool of enumerateAllInjectedTools()) {
+ const def = toToolDefinition(tool);
+ walkSchemaDescriptions(tool.inputSchema, (path, description) => {
+ if (!description.trim()) return;
+ const compacted = descriptionAtPath(def.inputSchema, path);
+ if (!compacted?.trim()) lost.push(`${tool.name}:${path}`);
+ });
+ expect(def.description.length, `${tool.name} provider description budget`).toBeLessThanOrEqual(480);
+ }
+ expect(lost).toEqual([]);
+ });
+
+ it('source tool descriptions stay under the review budget', () => {
+ const overBudget: string[] = [];
+ for (const tool of enumerateAllInjectedTools()) {
+ if (tool.description.length > TOOL_DESCRIPTION_REVIEW_CHARS) {
+ overBudget.push(`${tool.name}:description=${tool.description.length}`);
+ }
+ walkSchemaDescriptions(tool.inputSchema, (path, description) => {
+ const key = `${tool.name}:${path}`;
+ if (description.length > PARAM_DESCRIPTION_REVIEW_CHARS && !SOURCE_DESCRIPTION_BUDGET_EXCEPTIONS.has(key)) {
+ overBudget.push(`${tool.name}:${path}.description=${description.length}`);
+ }
+ });
+ }
+ expect(
+ overBudget,
+ `Tool descriptions above ${TOOL_DESCRIPTION_REVIEW_CHARS} chars or parameter descriptions above ${PARAM_DESCRIPTION_REVIEW_CHARS} chars need explicit review before landing.`,
+ ).toEqual([]);
+ });
+
+ it('critical tools keep enough provider-visible guidance to choose and call them', () => {
+ const checks: Record<string, string[]> = {
+ read_file: ['read', 'charstart', 'charend', 'stat_file'],
+ stat_file: ['total_chars', 'before', 'read_file'],
+ search_files: ['path is unknown', 'substring', 'glob'],
+ grep_files: ['pattern', 'glob', 'output_mode'],
+ write_file: ['write', 'path', 'content'],
+ edit_file: ['old_string', 'new_string', 'unique', 'e_stale'],
+ create_artifact: ['interactive', 'files', 'path', 'content', 'index.html'],
+ delete_file: ['confirmation', 'confirmation_token', 'path'],
+ interactive_cli_start: ['live user stdin', 'command', 'purpose'],
+ generate_image: ['generate', 'image', 'prompt', 'output_path', 'reference'],
+ create_docx: ['paragraphs', 'tables', 'images', 'path'],
+ create_xlsx: ['rows', 'sheets', 'formula', 'path'],
+ create_pptx: ['slides', 'shapes', 'images', 'path'],
+ cross_session_memory: ['remember', 'agent', 'shared', 'user', 'add', 'replace', 'remove', 'list'],
+ metacognition: ['competence', 'strategies', 'read', 'write'],
+ };
+
+ const missing: string[] = [];
+ for (const [name, needles] of Object.entries(checks)) {
+ const text = providerGuidanceText(toolByName(name));
+ for (const needle of needles) {
+ if (!text.includes(needle)) missing.push(`${name}:${needle}`);
+ }
+ }
+ expect(missing).toEqual([]);
+ });
+
it('empty names input returns an empty block', () => {
expect(getToolsSystemPromptBlock([])).toBe('');
});
@@ -152,7 +282,7 @@ describe('tool-catalog', () => {
describe('isToolVisibleToAgent (ownerAgent gate)', () => {
it('un-owned catalog tools are visible to every actor', () => {
expect(isToolVisibleToAgent('read_file', '')).toBe(true);
- expect(isToolVisibleToAgent('generate_image', 'video-studio')).toBe(true);
+ expect(isToolVisibleToAgent('generate_image', 'image-studio')).toBe(true);
expect(isToolVisibleToAgent('generate_image', 'anything')).toBe(true);
});
@@ -187,7 +317,7 @@ describe('isToolVisibleToAgent (ownerAgent gate)', () => {
}
checked.push(spec.id);
}
- expect(checked).toEqual(['b6ddc5e6b432', '78900d8758bc']);
+ expect(checked).toEqual(['78900d8758bc']);
});
it('an array ownerAgent still hides the tool from the commander and non-owners', () => {
diff --git a/test/main/model/session-store.test.ts b/test/main/model/session-store.test.ts
index 027c3e1a..357d1dc0 100644
--- a/test/main/model/session-store.test.ts
+++ b/test/main/model/session-store.test.ts
@@ -37,12 +37,14 @@ afterAll(() => {
// the post-reset module graph (importing at the top would capture the stale default `WS_ROOT`
// before beforeAll runs).
async function loadRouting() {
- const { sessionFileFor } = await import('../../../src/main/model/core-agent/session-store');
+ const { sessionFileFor, toolResultsDirForSession } = await import('../../../src/main/model/core-agent/session-store');
const { WS_ROOT } = await import('../../../src/main/paths');
return {
sessionFileFor,
+ toolResultsDirForSession,
cloudDir: path.join(WS_ROOT, uid, 'cloud', 'sessions'),
localDir: path.join(WS_ROOT, uid, 'local', 'sessions'),
+ localToolResultsDir: path.join(WS_ROOT, uid, 'local', 'tool-results'),
};
}
@@ -59,6 +61,12 @@ describe('session-store.sessionFileFor', () => {
expect(sessionFileFor(id)).toBe(path.join(cloudDir, `${id}.jsonl`));
});
+ it('routes resumable tool-results next to the cloud session file', async () => {
+ const { toolResultsDirForSession, cloudDir } = await loadRouting();
+ const id = 'gmember-cid01-agentX';
+ expect(toolResultsDirForSession(uid, id)).toBe(path.join(cloudDir, `${id}.tool-results`));
+ });
+
it('routes skill-edit → <uid>/cloud/sessions/', async () => {
const { sessionFileFor, cloudDir } = await loadRouting();
const id = 'skill-my_skill_id';
@@ -72,7 +80,7 @@ describe('session-store.sessionFileFor', () => {
});
it('routes ephemeral kinds (extract-img / reflect / memory-extract / anon) → <uid>/local/sessions/', async () => {
- const { sessionFileFor, localDir } = await loadRouting();
+ const { sessionFileFor, toolResultsDirForSession, localDir, localToolResultsDir } = await loadRouting();
for (const id of [
'extract-img-077355b2',
'reflect-abc123',
@@ -80,6 +88,7 @@ describe('session-store.sessionFileFor', () => {
'anon-12345678',
]) {
expect(sessionFileFor(id)).toBe(path.join(localDir, `${id}.jsonl`));
+ expect(toolResultsDirForSession(uid, id)).toBe(path.join(localToolResultsDir, id));
}
});
diff --git a/test/main/model/skill-registry-open-tier.test.ts b/test/main/model/skill-registry-open-tier.test.ts
index 92264f11..192453eb 100644
--- a/test/main/model/skill-registry-open-tier.test.ts
+++ b/test/main/model/skill-registry-open-tier.test.ts
@@ -104,6 +104,21 @@ describe('skill-registry › open tier (includeOpenSources)', () => {
expect(text).toContain('skill_search');
});
+ it('renders a user-forced global skill even when an allowlist is active', async () => {
+ writeSkill(customDir(), 'mine', 'mine', 'custom skill');
+ const globalRoot = path.join(homeDir(), '.claude', 'skills');
+ writeSkill(globalRoot, 'claude-skill', 'claude-skill', 'global skill');
+
+ const { getSystemPromptBlock } = await loadRegistry();
+ const text = await getSystemPromptBlock({
+ allowlist: ['mine'],
+ forceOpenSkillRefs: ['claude-skill'],
+ });
+ expect(text).toContain('**mine** (Source: custom)');
+ expect(text).toContain('**claude-skill** (Source: global)');
+ expect(text).not.toContain('skill_search');
+ });
+
it('omits the skill_search hint when open sources are not requested', async () => {
writeSkill(customDir(), 'mine', 'mine', 'custom skill');
const { getSystemPromptBlock } = await loadRegistry();
diff --git a/test/main/model/skill-registry.test.ts b/test/main/model/skill-registry.test.ts
index 536f0495..d88fe9e4 100644
--- a/test/main/model/skill-registry.test.ts
+++ b/test/main/model/skill-registry.test.ts
@@ -32,6 +32,9 @@ function systemDirFor(uid: string): string {
function agentPrivateDir(agentId: string): string {
return path.join(tmpDir, TEST_UID, 'cloud', 'agents', agentId, 'private_skills');
}
+function agentEvolvedDir(agentId: string): string {
+ return path.join(tmpDir, TEST_UID, 'cloud', 'agents', agentId, 'skills');
+}
function writeSkill(root: string, id: string, name: string, description: string, installMeta?: Record<string, unknown>) {
const skillDir = path.join(root, id);
@@ -100,6 +103,37 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
expect(text).toBe('');
});
+ it('still renders the acting agent private skills under an empty allowlist', async () => {
+ writeSkill(builtinDir(), 'translate', 'Translate', 'T');
+ writeSkill(agentPrivateDir('agent-a'), 'private-helper', 'private-helper', 'private help');
+ const { getSystemPromptBlock } = await loadRegistry();
+ const text = await getSystemPromptBlock({ agentId: 'agent-a', allowlist: [] });
+ expect(text).toContain('private-helper');
+ expect(text).not.toContain('translate');
+ });
+
+ it('does not render self-evolved skills under an empty allowlist', async () => {
+ writeSkill(builtinDir(), 'translate', 'Translate', 'T');
+ writeSkill(agentEvolvedDir('agent-a'), 'evolved-helper', 'evolved-helper', 'evolved help');
+ const { getSystemPromptBlock } = await loadRegistry();
+ const text = await getSystemPromptBlock({ agentId: 'agent-a', allowlist: [] });
+ expect(text).not.toContain('evolved-helper');
+ expect(text).not.toContain('translate');
+ });
+
+ it('preserves allowlist order when mixing agent-scoped and trusted skills', async () => {
+ writeSkill(customDir(), 'selected-helper', 'selected-helper', 'selected help');
+ writeSkill(agentPrivateDir('agent-a'), 'default-helper', 'default-helper', 'default help');
+ const { getSystemPromptBlock } = await loadRegistry();
+ const text = await getSystemPromptBlock({
+ agentId: 'agent-a',
+ allowlist: ['default-helper', 'selected-helper'],
+ forceOpenSkillRefs: ['selected-helper'],
+ });
+ expect(text.indexOf('default-helper')).toBeGreaterThanOrEqual(0);
+ expect(text.indexOf('selected-helper')).toBeGreaterThan(text.indexOf('default-helper'));
+ });
+
it('silently drops unknown ids in the allowlist', async () => {
writeSkill(builtinDir(), 'translate', 'Translate', 'T');
const { getSystemPromptBlock } = await loadRegistry();
@@ -254,6 +288,16 @@ describe('skill-registry › getSystemPromptBlock(allowlist)', () => {
expect(second).toContain('private-two');
expect(constructed).toBe(2);
});
+
+ it('lists agent-owned private and self-evolved skill ids', async () => {
+ writeSkill(agentPrivateDir('video-studio'), 'private-one', 'private-one', 'first private skill');
+ writeSkill(agentEvolvedDir('video-studio'), 'evolved-one', 'evolved-one', 'first evolved skill');
+ const { listAgentOwnedSkillIds } = await loadRegistry();
+ await expect(listAgentOwnedSkillIds(TEST_UID, 'video-studio')).resolves.toEqual([
+ 'private-one',
+ 'evolved-one',
+ ]);
+ });
});
describe('skill-registry › getSystemSkillsPromptBlock', () => {
diff --git a/test/main/paths.test.ts b/test/main/paths.test.ts
index f75c0b53..d25689ab 100644
--- a/test/main/paths.test.ts
+++ b/test/main/paths.test.ts
@@ -75,6 +75,8 @@ describe('paths › cloud-synced per-user', () => {
expect(p.chatAttachmentDir(uid, 'c1'))
.toBe(path.join(p.WS_ROOT, uid, 'cloud', 'chat_attachments', 'c1'));
expect(p.userSessionsDir(uid)).toBe(path.join(p.WS_ROOT, uid, 'cloud', 'sessions'));
+ expect(p.sessionCloudToolResultsDir(uid, 'gconv-c1'))
+ .toBe(path.join(p.WS_ROOT, uid, 'cloud', 'sessions', 'gconv-c1.tool-results'));
expect(p.userContextsDir(uid)).toBe(path.join(p.WS_ROOT, uid, 'cloud', 'contexts'));
expect(p.userMemoryFile(uid)).toBe(path.join(p.WS_ROOT, uid, 'cloud', 'memory', 'MEMORY.md'));
});
@@ -125,6 +127,8 @@ describe('paths › local (per-user, not synced)', () => {
expect(p.userChatsIndexPath(uid))
.toBe(path.join(p.WS_ROOT, uid, 'local', 'search', 'chats.idx.json'));
expect(p.userTestDir(uid)).toBe(path.join(p.WS_ROOT, uid, 'local', 'test'));
+ expect(p.chatAttachmentDraftDir(uid, 'main_chat'))
+ .toBe(path.join(p.WS_ROOT, uid, 'local', 'chat_attachment_drafts', 'main_chat'));
expect(p.userWorkspaceConfigFile(uid))
.toBe(path.join(p.WS_ROOT, uid, 'local', 'workspace.json'));
});
@@ -182,6 +186,7 @@ describe('paths › ensureTopLevelLayout side effect', () => {
path.join(tmpDir, 'u1', 'local', 'config'),
path.join(tmpDir, 'u1', 'local', 'search'),
path.join(tmpDir, 'u1', 'local', 'test'),
+ path.join(tmpDir, 'u1', 'local', 'chat_attachment_drafts'),
]) {
expect(fs.existsSync(d), `expected ${d} to exist`).toBe(true);
}
diff --git a/test/main/prompts/contract.test.ts b/test/main/prompts/contract.test.ts
index 960f131b..142e7945 100644
--- a/test/main/prompts/contract.test.ts
+++ b/test/main/prompts/contract.test.ts
@@ -151,13 +151,12 @@ describe('prompts ↔ code contract', () => {
const commanderPrompt = fs.readFileSync(path.join(PROMPTS_DIR, 'chat_commander.md'), 'utf-8');
const memoryTool = readFile('src/core-agent/src/tools/memory-tool.ts');
- expect(memoryTool).toContain('Three scopes (default "agent")');
- expect(memoryTool).toContain('"agent" (DEFAULT): YOUR OWN durable agent memory');
- expect(memoryTool).toContain('"shared": durable facts that EVERY agent should know');
- expect(memoryTool).toContain('"user": the user\'s global profile/preferences');
- expect(memoryTool).toContain('LANGUAGE:');
- expect(memoryTool).toContain('current UI/response language');
- expect(memoryTool).toContain('Preserve proper nouns, commands, file paths');
+ expect(memoryTool).toContain('- agent (default):');
+ expect(memoryTool).toContain('- shared: stable project/environment facts every agent should know');
+ expect(memoryTool).toContain('- user: stable user-wide profile/preferences every agent should know');
+ expect(memoryTool).toContain('Write in the user\'s current language');
+ expect(memoryTool).toContain('preserving code, paths, commands, URLs');
+ expect(memoryTool).toContain('exact quoted wording');
expect(agentPrompt).toContain('`target: "agent"` = your own agent memory');
expect(agentPrompt).toContain('`target: "user"` = global user profile/preferences');
diff --git a/test/renderer/category-tabs.test.ts b/test/renderer/category-tabs.test.ts
index b548ef77..f7fa7d61 100644
--- a/test/renderer/category-tabs.test.ts
+++ b/test/renderer/category-tabs.test.ts
@@ -380,14 +380,14 @@ describe('agent and skill category tabs', () => {
_openSkillsCache = [
{ id: 'global-helper', name: 'Global Helper', source: 'global', enabled: true, description: 'pkg' }
];
- setChatSkill = (target, name) => { pickedSkillCalls.push([target, name]); };
+ setChatSkill = (target, id, name) => { pickedSkillCalls.push([target, id, name]); };
`, context);
// Commander: all picker tabs; global open-tier skill selectable.
expect(vm.runInContext('_agentPickerVisibleTabs("new-chat-recipient-chip")', context))
.toEqual(['agents', 'skills', 'connectors', 'library']);
await context._triggerPickerItem('skill', 'global-helper', 'Global Helper', 'new-chat-recipient-chip');
- expect(context.pickedSkillCalls).toEqual([['new-chat', 'Global Helper']]);
+ expect(context.pickedSkillCalls).toEqual([['new-chat', 'global-helper', 'Global Helper']]);
// Agent recipient uses the same visible picker tabs; runtime capability
// gates live in the main process. Trusted skill selection still works.
@@ -396,7 +396,7 @@ describe('agent and skill category tabs', () => {
expect(vm.runInContext('_agentPickerVisibleTabs("new-chat-recipient-chip")', context))
.toEqual(['agents', 'skills', 'connectors', 'library']);
await context._triggerPickerItem('skill', 'trusted', 'Trusted Skill', 'new-chat-recipient-chip');
- expect(context.pickedSkillCalls).toEqual([['new-chat', 'Trusted Skill']]);
+ expect(context.pickedSkillCalls).toEqual([['new-chat', 'trusted', 'Trusted Skill']]);
});
it('hides external package recipe groups from the picker for an agent recipient', () => {
diff --git a/test/renderer/chat-file-viewer.test.ts b/test/renderer/chat-file-viewer.test.ts
index f91eb7fe..1a73d73f 100644
--- a/test/renderer/chat-file-viewer.test.ts
+++ b/test/renderer/chat-file-viewer.test.ts
@@ -7,13 +7,14 @@
import { describe, it, expect } from 'vitest';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const viewer = require('../../src/renderer/modules/chat-file-viewer.js');
-const { _kindOf, _extOf, _chatMediaLocalUrl, _viewerAbsPathFromChatMediaLocalUrl, _viewerCanAddToLibrary, _viewerVideoPlaybackOptions } = viewer as {
+const { _kindOf, _extOf, _chatMediaLocalUrl, _viewerAbsPathFromChatMediaLocalUrl, _viewerCanAddToLibrary, _viewerVideoPlaybackOptions, _viewerVideoSeekTarget } = viewer as {
_kindOf: (name: string) => string;
_extOf: (name: string) => string;
_chatMediaLocalUrl: (abs: string) => string;
_viewerAbsPathFromChatMediaLocalUrl: (src: string) => string;
_viewerCanAddToLibrary: (nameOrKind: string) => boolean;
- _viewerVideoPlaybackOptions: (opts?: { autoplay?: boolean; startTime?: number }) => { autoplay: boolean; startTime: number };
+ _viewerVideoPlaybackOptions: (opts?: { autoplay?: boolean; startTime?: number; duration?: number; ended?: boolean }) => { autoplay: boolean; startTime: number };
+ _viewerVideoSeekTarget: (startTime: number, duration?: number) => number;
};
describe('chat-file-viewer › _kindOf', () => {
@@ -150,4 +151,26 @@ describe('chat-file-viewer › _viewerVideoPlaybackOptions', () => {
expect(_viewerVideoPlaybackOptions()).toEqual({ autoplay: false, startTime: 0 });
expect(_viewerVideoPlaybackOptions({ autoplay: false, startTime: -1 })).toEqual({ autoplay: false, startTime: 0 });
});
+
+ it('replays from the beginning when the source video has ended', () => {
+ expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 9.5, duration: 10, ended: true })).toEqual({ autoplay: true, startTime: 0 });
+ });
+
+ it('replays from the beginning when the source position is at the end', () => {
+ expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 9.9, duration: 10 })).toEqual({ autoplay: true, startTime: 0 });
+ });
+
+ it('keeps mid-video resume positions', () => {
+ expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 5, duration: 10 })).toEqual({ autoplay: true, startTime: 5 });
+ });
+});
+
+describe('chat-file-viewer › _viewerVideoSeekTarget', () => {
+ it('seeks to the beginning when metadata reveals an end position', () => {
+ expect(_viewerVideoSeekTarget(9.9, 10)).toBe(0);
+ });
+
+ it('keeps a safe in-range mid-video seek target', () => {
+ expect(_viewerVideoSeekTarget(4.25, 10)).toBe(4.25);
+ });
});
diff --git a/test/renderer/conversation-produced-chips.test.ts b/test/renderer/conversation-produced-chips.test.ts
index 833d0a0d..30051c90 100644
--- a/test/renderer/conversation-produced-chips.test.ts
+++ b/test/renderer/conversation-produced-chips.test.ts
@@ -53,7 +53,7 @@ describe('conversation produced chips', () => {
expect(source).toContain("row.classList.add('is-expanded')");
expect(source).not.toContain("window.ConversationInfo.openAndSetTab('files')");
expect(styleSource).toContain('.chat-msg-produced.is-expanded');
- expect(styleSource).toContain('max-height: 240px;');
+ expect(styleSource).toContain('max-height: 168px;');
expect(styleSource).toContain('overflow-y: auto;');
});
@@ -81,3 +81,12 @@ describe('conversation produced chips', () => {
expect(ordered[0].path).toBe('/workspace/b/report.md');
});
});
+
+describe('chat video layout', () => {
+ it('reserves a stable 16:9 slot for inline chat videos', () => {
+ expect(styleSource).toContain('.chat-md-video-shell');
+ expect(styleSource).toContain('aspect-ratio: 16 / 9;');
+ expect(styleSource).toContain('width: min(640px, 100%);');
+ expect(styleSource).toContain('.chat-msg-attach-video-shell');
+ });
+});
diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.ts
index 6a0d140c..9bb4e534 100644
--- a/test/renderer/conversation-sidebar.test.ts
+++ b/test/renderer/conversation-sidebar.test.ts
@@ -632,6 +632,45 @@ describe('conversation history reconcile', () => {
});
describe('conversation streaming math detection', () => {
+ it('reuses inline video nodes across streaming markdown repaints', () => {
+ const context = loadConversationRenderer();
+ const src = 'chat-media://local/Users/test/clip.mp4';
+ const existingVideo = {
+ getAttribute(name: string) { return name === 'src' ? src : ''; },
+ };
+ const existingShell = {
+ querySelector(selector: string) {
+ if (selector === 'video.chat-md-video[src]') return existingVideo;
+ if (selector === 'video.chat-md-video[src], audio.chat-md-audio[src]') return existingVideo;
+ return null;
+ },
+ };
+ const freshVideo = {
+ getAttribute(name: string) { return name === 'src' ? src : ''; },
+ };
+ let replacement: unknown = null;
+ const freshShell = {
+ replaceWith(node: unknown) { replacement = node; },
+ querySelector(selector: string) {
+ if (selector === 'video.chat-md-video[src]') return freshVideo;
+ if (selector === 'video.chat-md-video[src], audio.chat-md-audio[src]') return freshVideo;
+ return null;
+ },
+ };
+ const freshRoot = {
+ querySelectorAll(selector: string) {
+ if (selector === '.chat-md-video-shell') return [freshShell];
+ if (selector === '.chat-md-audio-card') return [];
+ return [];
+ },
+ };
+ const stable = new Map([[context._streamingStableMediaKey('video', src), [existingShell]]]);
+
+ context._streamingRestoreStableMedia(freshRoot, stable);
+
+ expect(replacement).toBe(existingShell);
+ });
+
it('detects closed inline and display math while streaming', () => {
const context = loadConversationRenderer();
diff --git a/test/renderer/utils-autolink.test.ts b/test/renderer/utils-autolink.test.ts
index 4df0941a..a7612c77 100644
--- a/test/renderer/utils-autolink.test.ts
+++ b/test/renderer/utils-autolink.test.ts
@@ -170,6 +170,8 @@ describe('markdown media links', () => {
const out = inlineFormat('[video](chat-media://local/Users/test/car_driving.mp4)');
expect(out).toContain('<span class="chat-md-video-shell">');
expect(out).toContain('<video class="chat-md-video"');
+ expect(out).toContain('width="640"');
+ expect(out).toContain('height="360"');
expect(out).toContain('controls');
expect(out).toContain('controlslist="nodownload nofullscreen noremoteplayback"');
expect(out).toContain('disablepictureinpicture');