SLOPSHOPPER

dispatch-pilot

Dispatch Pilot:一个在 Claude 之外的决策模型(默认 Perplexity 的 pplx,没有 Perplexity key 时退回 TypeSafe 的 Jev,也可以固定用 Jev)在你每次发消息时决定主 agent 这一轮的…

panebandspinnerguardcommandtoast
★ 2v0.8.2MITupdated 2026-10-22alexcz-a11y/claude-mods/dispatch-pilot
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dispatch-pilot
│ ┃ 依据 ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ ◆ 依据 · 主 agent │ dispatch-pilot │ │ ┃ 功能(/dp <名字> on|off) signals 开 main- ● dispatch-pilot: sett│ 主 agent 未路由:决策模型没配好(pplx:没有填 │ │ ┃ [ ‹ 上一个 (p) ] [ 下一个 › (n) ] band 上按 ● dispatch-pilot: imag│ perplexityApiKey 或 PERPLEXITY_API_KEY) │ │ ┃ ╭─────────────────────────────────────────── ⏺ Read(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ │ ◆ 主 agent — ▱▱ ⎿ Read 6 lines │ ┃ │ 状态 未路由 · 决策模型没配好 ⏺ Update(src/auth.ts) │ ┃ │ 类型 没有配好决策模型的密钥或账号,或者 ⎿ Added 2 lines, removed 1 line │ ┃ │ 后端 pplx ⏺ Bash(bun test) │ ┃ │ 细节 pplx:没有填 perplexityApiKey 或 P ⎿ 3 pass, 1 fail │ ┃ │ 排查 debug log(claude --debug-file │ ┃ │ <路径>)里有这次请求的那一行,写着 ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ 久、怎么失败的 │ ┃ ╰─────────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ ◆ 决策日志 还没有决定 › /dp │ ⎿ dispatch-pilot: 依据面板已打开:p / n 翻看 agent,Esc 关闭 │ ● dispatch-pilot: pplx key: not set │ ● dispatch-pilot: skills: no decision model is set up, so the main ag │ │ ⟨Claude Code's own drawing⟩ ◆ 第 1 轮 0:42 · 主 agent · 未路由 · 决策模型没配好 · /dp log 看依据 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⟨Claude Code's own drawing⟩ ◆

Draws

Band
⟨Claude Code's own drawing⟩ ◆ 第 1 轮 0:42 · 主 agent · 未路由 · 决策模型没配好 · /dp log 看依据
Pane · 依据
◆ 依据 · 主 agent 1/1 功能(/dp <名字> on|off) signals 开 main-effort 开 unres [ ‹ 上一个 (p) ] [ 下一个 › (n) ] band 上按 0-9 直接选 ╭─────────────────────────────────────────────────────────── │ ◆ 主 agent — ▱▱▱▱▱ — │ 状态 未路由 · 决策模型没配好 │ 类型 没有配好决策模型的密钥或账号,或者密钥被拒绝 │ 后端 pplx │ 细节 pplx:没有填 perplexityApiKey 或 PERPLEXITY_API_KE │ 排查 debug log(claude --debug-file │ <路径>)里有这次请求的那一行,写着它发了什么、等了 │ 久、怎么失败的 ╰─────────────────────────────────────────────────────────── ◆ 决策日志 还没有决定
README

Dispatch Pilot

Dispatch Pilot 是 alex-mods marketplace 里的一个 Claude Code mod。它在 Claude 之外调用一个决策模型(默认是 Perplexity 的 pplx;没有 Perplexity 的 key、但有 TypeSafe 的 key 时退回 TypeSafe 的 Jev,也可以指定用 Jev),替你决定 Claude Code 怎么干活:主 agent 每一轮用哪档 effort,派出的 agent 用哪个模型和哪档 effort,主 agent 该看哪几个 skill。它还能替 agent 看图:截图、录屏交给一个看图的模型核对,agent 不必自己看(0.5.0 起,见「看图核对」和「图像:发给谁,什么时候发」)。

主 agent 的模型从不改变,所以 prompt cache 不受影响。这只在 Claude Code 订阅下成立,见「要求」。

它做什么

决策模型只负责给出判断,不参与回答你。每个判断的结果写在看板上,依据记进决策日志,在依据面板里看(/dp),也可以用 /dp log N 在对话里列出。

  • 主 agent 的 effort。 你每发一条消息,Dispatch Pilot 把这条消息和最近几条消息发给决策模型,问它这项工作需要多少逐步推理,得到 low、medium、high、xhigh、max 五档各自的概率。取概率最高的一档,并列时取较高的一档;如果高一档的概率也够高(pplx 0.45,Jev 0.3),就再往上取一档(升高容易:低估一档要付出质量,高估一档只多花 token);max 只在它自己的概率达到 thetaMax 时才用。这一轮的每个模型请求都按这一档发出。一轮进行中,每隔几步(rejudgeEvery),以及主 agent 派出 agent、启动 Workflow 或加载 skill 时,会再判断一次(中途重判);升档和降档都有防抖:升档要置信度达到 thetaUp(pplx 0,Jev 0.3),降档要达到 thetaDown(0.55)而且一次只降一档,升档之后 holdSteps(5)步之内不降。派出 agent 交回结果、后台任务结束,会话空闲时它们会开始主 agent 的新一轮,这样的一轮也走同样的判断:决策模型读到的是那条报告的文字,只判 effort:不推荐 skill,不问未解决次数,也不在这一轮中途重判(会话自己的 xhigh 用在只是看一眼结果上是浪费);报告送进一轮正在进行的对话时不另外判断。引擎把派出 agent 交回的结果和另一个 Claude 会话的消息都当作 peer 消息交来,mod 分不开它们,所以会话空闲时到达的另一个会话的消息,同样开始这样的一轮、同样只判 effort。定时任务、插件自己发的消息和空消息都不判断。你输入的 skill 或 markdown 命令(例如 /implement #19)开始的一轮也照常判断:决策模型读你输入的命令和参数,以及这个命令是做什么的,不读命令展开后的正文;参数里的点名照样算;这样的一轮不推荐 skill。/dp、/clear 这类本地命令不开始一轮,也就不判断。
  • 派出 agent 的模型和 effort。 主 agent 用 Agent 工具派出一个 agent 时,决策模型为它选模型(默认在 haiku、sonnet、opus 中选,打开 agentFable 后加入 fable)和 effort(haiku 用的是 Haiku 5.5,它也接受 effort)。三个模型的分工按 Artificial Analysis 的基准定(见下面的「模型和 effort 的依据」):haiku 只做一两步就能跑完、结果只需要收集起来并按要求排版的只读查找,sonnet 承担大多数执行类工作(终端、需求明确的代码修改、自动化、调研汇报),opus 做需要审慎判断或细微错误代价高的工作(安全、并发、涉及钱、迁移、生产)、难推理、设计、原因未知的 bug、科学或算法类代码,以及结论取决于记忆中的事实、而且无法在仓库或文档里查证的调研;fable 在 AA 上没有领先 Opus 的地方,价格是 2.5 倍,所以仍默认关闭。决策出来的 effort 不低于所选模型的下限:sonnet 和 opus 至少 medium,haiku 和 fable 没有下限(haiku 也带决策出来的 effort)。你在消息里点名的模型或 effort(「用 opus」「effort 开 low」)照办:点没点名由决策模型判断,把握要达到 0.5,effort 的点名只在消息里出现 effort、档位名、推理这类字眼时才问;决策请求整体失败时读不出点名,见「局限和待评测」。下限和往上取的一档都不会改你点名的值,你排除的模型(「别用 opus」)不会用(决策请求整体失败时除外,见「局限和待评测」)。主 agent 自己为这个 agent 指定了模型时,只有决策模型选了别的、而且置信度达到 agentOverride 才推翻它。每次 Agent 调用的结果后面还会附一段英文说明,告诉主 agent 这个 agent 以什么模型和 effort 启动、是谁定的(没路由时写原因);fork、teammate 和被拒绝启动的派出不附。
  • Workflow 里的 agent。 主 agent 提交 Workflow 脚本时,对脚本里每个 agent() 调用点做同样的判断,把模型和 effort 写进脚本再运行,并告诉主 agent 写了什么;workflowMode 选 return 时改为退回脚本,附上逐个调用的推荐,让主 agent 自己写进去。一个脚本最多问 24 个调用点、4 个请求;脚本里写的 model 只有是字面量时才当作主 agent 的指定。脚本写不进去的(用 scriptPath 或 name 提交、恢复的运行、读不了的脚本),以及超出 24 个、prompt 在运行时才拼出来看不出任务、选项不是对象字面量写不进去的调用,在每个 agent 派出时(agent.spawn)按它的 label 对上调用来设置,这叫兜底:模型设在派出上,effort 在它的每一步发出;对不上调用、或调用当时没能判断的,按派出带来的任务当场判断。
  • 卡住时强制升档。 主 agent 或派出 agent 的工具调用失败累计到 escalateAfter 次时(中间成功一次不清零,只在升档、判为预期内之后清零),再问决策模型一次,把它的 effort 升一档(escalateMode 选 max 则直接升到 max);haiku agent 同样先升 effort,effort 已经到顶时改用 sonnet 接着做(escalateHaikuTo)。这些失败本来就在意料之中的,例如先写下、要看它红的测试,或者没找到东西而以非零退出的搜索,不升档;是不是预期内失败由决策模型判断,不靠关键词。你自己拒绝的调用从不算失败。
  • 未解决次数。 你本人的每条消息(包括斜杠命令)发出时,决策模型还回答一道三选一的题:这条消息是在说你和主 agent 最近在处理的那个问题仍未解决、已经解决,还是换了新问题或无关;不靠关键词,「再看看」或贴一段同样的报错也认得出。「仍未解决」把握够(暂定 0.5)次数加一,「已经解决」或「新问题或无关」把握更高(暂定 0.7)才清零,都没到次数不变。次数存在会话里,/clear 和新会话清零,/compact 和热重载保留;agent 交回结果、后台任务通知开始的一轮不问。依据卡片显示次数和这一次的结论。次数和下面的摘要一起作为决策模型判断 effort 的依据,见「强提示」。这项功能(unresolved 开关,次数、摘要、强提示共用)默认关闭:评测里它对默认的决策模型没有提升,所以不问这道题、不数次数、不写摘要、不给强提示。它挂在 main-effort 上:main-effort 关着时,unresolved 开着也不问、不数次数、不写摘要。/dp unresolved on 打开,对 pplx 和 Jev 都生效;/dp unresolved off 再关。开关存在 $.store,你手动设过的状态升级后保持原样;0.3.1 里它是默认开着的,开着时没有保存过任何设置,所以从 0.3.1 升级上来、一直开着的,现在变成了关闭,要用请自己打开。
  • 问题摘要。 你本人的消息开始的那一轮结束后,一个便宜的模型(summaryModel,默认 haiku,用你的 Claude 登录和用量)在后台续写一份简短的摘要:问题是什么、试过哪些做法、现在到了哪一步,不超过 500 token,只记试过什么,不判断成没成功;你的下一条消息说「仍未解决」时,最后一次尝试标上「未解决」。决策模型发消息时读它,借此看到超出上下文预算的更早几轮;它从不等摘要写完,来不及时用上一份。写失败(出错、超时)保留旧摘要并在决策日志里记一条。问题解决、换了问题、/clear 和新会话时和次数一起清空,/compact 和热重载保留。依据面板里能看摘要全文。交给写摘要模型的内容先脱敏;contextMessages 为 0 时不写(摘要是对话的转述)。默认关闭,随 unresolved 开关一起打开和关闭。
  • 强提示。 次数达到 unresolvedMaxAfter(默认 3,0 到 10,0 表示不给)时,发消息时和中途重判时 effort 题的说明里多一条:这项工作属于多次尝试都没解决的故障。它只描述情境:不写档位的名字或序号,pickEffort 的规则和 thetaMax 都不变,用不用最高一档仍由决策模型结合摘要和对话自己决定。次数和摘要也进这两种请求的 state(unresolved_count、problem_summary);派出 agent 和 Workflow 里 agent 的决定读摘要和次数当背景,但从不加强提示(「查一个文件」这类子任务不该因此判到最高一档)。发消息时带的是这条消息之前的次数(这条消息自己的结论要同一个请求的回答才知道),所以默认设置下,第三次说「仍未解决」的那条消息(次数在它的回答里到 3)的请求还读不到强提示,它的中途重判先读到,下一条消息的请求再带上。每次给了强提示,决策日志记一条(次数、已给强提示、决策模型判出的档位),依据卡片显示「已给强提示」;看板不新增事件。unresolved 开关关着(默认)时这些都不带。
  • skill。 主 agent 不再读完整的 skill 列表(装的 skill 多时这一段很长),读到的是一句固定的提示。改由决策模型在你发消息时,从本会话的 skill 里挑出相关的几个,连同名字、描述和相关度附在消息后面交给主 agent;只能由你触发的 skill 不推荐给主 agent,只在看板上提示你(「可试 /x」)。一轮进行中,主 agent 还可以用 find_skill 工具按几个词查 skill。skill 本身和 Skill 工具都不变,主 agent 仍然可以按名字加载任何 skill。
  • 看图核对(visual-check,默认开)。agent 截了图、录了屏,不必自己看:它调用 visual_check 工具,交上截图或录屏、比较的对象和几条检查项。比较的对象可以是参考图(设计稿、实物照片)、另一张截图(改动前后、另一个画质档位)、一串画质档位,或一段文字规范;每条检查项点名图上的一个部分,加一个看得见的属性。图像后端(见下面的「图像:发给谁,什么时候发」)一两秒内对每条回答过、不过或没把握。一次调用最多 24 条检查项;不过的检查项最多附 3 条的裁图;look: true 一次最多回 8 张图;画质档位最多 12 档。图的路径按模型给的原样用,只去掉首尾的空白(macOS 截图的文件名里有 U+202F,不能折叠空白)。有参考图或另一张截图时,先在两张图上框出点名的部分,裁下来放大再判断(放大复核,要 Jev),全屏另扫一遍「哪里不同」,没点名的地方变了也会报出来;录屏由 mod 用 ffmpeg 均匀抽帧,几帧一起判断,只问粗的运动问题(有没有回弹、终点是否大偏、元素出现或消失)。「不过」时附出问题那一块的裁图,「没把握」时把缩过的整图还给 agent 当场自己看,「过」只代表没看出明显问题。判定看决策模型说「成立」的概率:截图(整图、放大复核的裁图)至少 0.8 过、至多 0.2 不过,录屏至多 0.4 就不过,其间没把握(2026-10-15 之前是 0.9 / 0.2);比画质档位时判「没差别」仍要每个点名区域到 0.9。检查项要对照画面上看得见的东西来写(另一个元素、画面边缘、画上标出的目标),不要写像素坐标,工具说明里也这么要求。它只判粗的差异:尺寸、圆角、色值、字重这类数值查代码或运行时的值,缓动、质感这类观感自己看,交付前主 agent 仍亲自看一次最终结果。同一条检查项连续两次不过,回答里提醒先自己看一次图。比一串画质档位时(sequence,要 Jev),逐对比较相邻两档在点名区域里有没有看得出的差别,找到再往上看不出差别的那一档,省得交给你逐档去看。派出 agent 和 Workflow 里的 agent 也能用。
  • 截图接管(screenshot-takeover,默认关)。打开后,agent 在当前这个循环里自己生成的图(截图、抽出的帧)在它看到之前被换成一句说明:图存在哪、有多大、请用看图核对;它要亲自看时,用 visual_check 的 look: true 取回缩过的原图。Read 读到的图片文件算;任何 mcp__ 开头的工具(除了 Dispatch Pilot 自己的)返回的图块也算,不限于截图类工具,换掉的图块先存成临时文件。参考图、你贴的图和循环开始前就有的文件照常给 agent 看。适合调 3D 效果、反复建模这类粗调阶段:截图多,又不必每张都进上下文。它要 visual-check 开着、而且有图像后端,否则不生效(图换掉了 agent 就看不到了)。
  • 带图路由(image-routing,默认关)。你贴了参考图让 agent 建模时,Dispatch Pilot 先把参考图交给图像后端,读出「照着做出来有多复杂」,是 0 到 4 的一个读数;同一组图只读一次。读数以文字作为提示进入主 agent 的 effort、派出 agent 和 Workflow 里 agent 的模型和 effort,只是提示,不直接定档,锁定、点名和下限照旧优先。带图的消息因此晚一点才定 effort(多等的时间不超过约 3 秒,等不到就照常按文字定);一轮做到一半主 agent 读了参考图(修改时间早于这个循环的图片文件),或你又贴了图,会立刻重判一次(要 midturn-effort 开着)。agent 自己截的图不算参考图。读数失败时决定照常进行,只是不带读数。
  • 失败时放行。 决策模型超时(timeoutMs)、出错、回答无法解析,或者没有配密钥时,消息照常进入,不额外等待,这一轮用会话自己的 effort,看板上写明原因,并弹一个 toast。

本文提到的配置项(例如 escalateAfter、timeoutMs),默认值都在「配置」的表里。每项功能都可以用 /dp 单独关掉,也可以整个 mod 一起关(见「控制:/dp」)。完整的行为规则(各种优先级、各种失败情形、看板和日志的写法)见 DEVELOPMENT.md 的「它做什么」。

模型和 effort 的依据

模型的分工、往上取一档、中途的门槛和各模型的 effort 下限,都按 Artificial Analysis(AA)Intelligence Index v4.3.2 的十个分项校正过。几个要点:Sonnet 5.5 的分数随 effort 掉得很快(Terminal-Bench:low 20.7%、medium 29.8%、high 43.9%、max 63.6%;指数 36、41、47、56),所以低估 sonnet 的代价大;Opus 5.5 在 medium 就有 51;Sonnet 与 Opus 在终端、自动化、知识工作上持平或略高,拉开的是事实知识(Omniscience 32 对 46)、难推理(HLE 差 6.4)和科学代码(SciCode 差 5.9);Haiku 4.5 在 Terminal-Bench 上是 0%。数字、来源和已存评测回答按新规则离线重算的结果见 docs/research/aa-benchmarks-2026-10.md。

看板

看板是 Dispatch Pilot 常驻的界面,只显示读数和结论,依据放在依据面板里。给人看的文字都是中文,模型名和 effort 档名照 /model、/effort 的写法。

  • prompt 上方的 band。 一轮进行中,顶上一条状态条:第几轮、用时、agent 的运行 / 完成 / 失败 / 排队数、Workflow 的进度、中途重判的次数。下面每个 agent 一行:主 agent 在最前,其余按开始的先后,各带数字键(0 是主 agent,1 到 9 按先后)、名字、模型和 effort、状态,以及一条时间色带(同一根时间轴,看得出谁和谁并行)。状态格写运行或完成了多久、失败、排队,或者「未路由 · 原因」。再下面是这一轮的事件流:每个决定、中途重判和强制升档(一次改档只算一条,写从哪档到哪档)、skill 推荐和「可试 /x」、find_skill 的查询,以及请求失败、回答迟到。一轮结束后 band 折成一行:主 agent 的模型和 effort、这一档是怎么来的、「可试 /x」。引擎给 band 的行数不到 4 行时,退成一行摘要。
  • 脚部右端的摘要。 连同和左边隔开的一列,不超过 12 列:状态符号、主 agent 的模型和 effort、+N 个运行中的 agent;放不下时 effort 先写短(xhi),再省掉模型。
  • 未路由。 一轮或一个 agent 的模型和 effort 照引擎原样发出、没有经过 Dispatch Pilot 的决定,看板上总写原因:决策模型超时、连不上、繁忙、被限速、额度用完、密钥被拒绝、没配好、回答读不懂,或者功能已关。路由失败时还会弹一个 toast,写谁没路由和原因;离上一个 toast 不到 2 秒的不弹,免得几个 agent 一起失败时刷屏(失败照样写在看板上)。
  • 看图核对的计数。 visual-check 开着时,band 里每个 agent 的行末多一格「核对 N:x 过 · y 不过 · z 没把握」(N 是检查项数,一轮里原地更新),截图接管开着时再加「接管 n」。每次核对和每次接管在决策日志里留一条:检查项、结论、概率、图片路径、是否放大复核、用时。核对出错不弹 toast,只在看板和日志里记。依据卡片多一行「看图核对」;带图路由读过参考图时,卡片多一行「参考图」,写读数的档位和来自几张图。
  • 选中一个 agent。 在空的 prompt 里按它的数字键,依据面板就打开在它的卡片上。
  • 别的端(Desktop、VS Code、手机)。 时间色带、概率条和置信条改用 Svg 画(这些端没有终端的 Raster),数字用等宽数字,列能对齐。这些端用鼠标点,不用按键(ADR 0012):band 状态条右边有「依据」(打开依据面板)和「▾ 收起」(折成一行,行末是「▸ 展开」,本会话里一直保持);agent 的名字可以点,不带数字键;effort 写成彩色的字。agent 在跑时每 5 秒才重画一次,运行中的色带自己往前长。依据面板顶上是一排 agent 标签、「看它的对话」和「关闭」;卡片里的规则是一张清单,effort 概率是一条堆叠条,份额写在下面;决策日志点轮次折叠,每条一行,指着它看概率和理由;最下面「功能开关」展开后,每个开关一个按钮,effort 锁定用下拉选择,按下就改,和 /dp 改的一样会保存。脚部是一个不超过 24 个字符的标签。
  • 状态行(只在 VS Code 和手机上)。 VS Code 不画 band,所以用 prompt 下方的状态行写 band 的一行摘要:第几轮、主 agent 的模型·effort;一轮结束后加上这一档是怎么来的和「可试 /x」;还有各个 agent 的个数。你写消息时,prompt 提示也写在这一行(ADR 0011)。终端上不用状态行,因为终端会在这一行前面加一个关不掉的 ⚠(ADR 0004);Desktop 上也不用,band 空闲时照样画着那一行,你写消息时 prompt 提示就写在 band 的那一行上(ADR 0012)。
  • Desktop 用的是它自带的 Claude Code,要 2.1.300 及以上,否则整个 mod 加载不了,而且不报错(怎么看版本、密钥怎么填,见「安装」的「Claude Desktop」)。版本不够时,在菜单 Claude → Check for Updates 更新 Desktop,再开新会话。本机 Desktop 自带的 Claude Code 已是 2.1.308(2026-10-22),main 上的版本直接在 Desktop 里用,不再另出兼容版;2.1.308 上只跑过 plugin validate,界面还没在它上面亲眼看过(0.8.1 的改动在 2.1.299 的兼容版上真机点过)。
  • 关掉的功能(/dp <功能> off)的决定、事件和计数不出现在 band 和脚部;/dp off 时 band 上没有 Dispatch Pilot 的内容,脚部写 ○ dp 已关。claude -p 没有界面,内容写进 debug log。

依据面板

/dp 打开依据面板,再输一次或按 Esc 关掉;/dp log 也是打开它。全屏且终端够宽时它停靠在对话右边(约 75 列),否则在 prompt 上方。面板窄时文字换行缩进,不截断。

  • 顶部(灰字):每项功能的开关状态(名字加「开」或「关」,关着的用灰色,默认关的 hook-block-failures 也在内)、/dp lock 的锁定,以及本会话 skill 画像的情况(skill 画像:保留 52 · 新写 3 · 失败 1;写的过程中是「生成中 2/5」;停写时写原因;有失败时按 f 列出失败的 skill 和原因)。
  • 依据卡片。 「‹ 上一个 (p) / 下一个 › (n)」按 band 的顺序翻看 agent。选中派出的 agent 时旁边多一个「看它的对话 (x)」,按下后主视图换成这个 agent 的对话,按钮变成「↩ 回主对话 (x)」;Workflow 里的 agent 没有这个按钮(2.1.302 实测引擎不让打开),主视图没切过去时弹一个 toast 写原因。需要 Claude Code 2.1.300 及以上。卡片是选中 agent 的依据:状态;没路由时几个字的原因,再写失败的类型、决策模型、细节和去 debug log 哪里看;给它的模型(派出 agent 和 Workflow 里的 agent)和理由(主 agent 也有);各档 effort 的概率;规则推演,从决策模型给的概率走到最终的 effort,每一步写它做了什么(最可能的一档、max 门槛、上取一档,给了模型下限时再加模型下限;强制升档和中途重判有它们自己的步骤);结果。主 agent 的卡片还注明发消息时的置信度只记录、不参与选档,并列出这一轮的强制升档和每次中途重判(建议档、当前档、带门槛刻度的置信条,和结论:升档、降档、降档被拦、防抖中还差几步、保持)。卡片只画决定时存下的推演,从不重新计算。
  • 决策日志。 按轮分组,最新的一轮在前,每条带编号、结果(颜色和 ✔ · ⚠ ✘ 符号;每轮的标题按同样的符号计数)、模型和 effort、是哪项功能针对什么、各档概率和理由。每轮有一个字母键(从 a 起,跳过 p、n、f)折叠或展开,最新两轮默认展开。日志保留最近 20 轮、最多 300 条。
  • 面板的按键只在面板拿到键盘时有用(/dp 打开时会拿键盘;在 band 上按数字键打开的不抢键盘,可以接着按别的数字)。面板没被放出来时(比如接着的端不放面板)会立即关掉,并说明原因(/dp 在回复里说,按数字键打开的弹一个 toast),这时用 /dp log 10 在对话里看。

发给决策模型的内容

  • 你这条消息,加上之前最近的几条消息(最多 contextMessages 条,总长度不超过 contextTokens)。主 agent 的 effort 题单独发一个请求,能读到的最近对话比和 skill 推荐一起发时长得多(Jev 默认 96000 token,对 6000;pplx 48000);skill 推荐的请求和它并行发出。选 Jev 时,state 超过 24000 token 的请求带上长上下文请求头(TypeSafe-Danger-Zone-Long-Context,一个请求可到 262k),这条消息的两个请求都最多等 3000 毫秒(带头的请求实测约 1.0–1.6 秒,额度紧时另一个请求还要排在它后面等额度,见「限制」);没超过就和以前一样。每条只有文字和调用过的工具名,不包含文件内容和工具输出。一轮中途重判时发的是这一轮最近几步(rejudgeSteps)的摘要:主 agent 写的文字、调用的工具和一句话结果。这一句说明调用在做什么:它自带的说明、skill 或 Workflow 的名字、文件路径的最后两段、搜索的 pattern 或 query、URL,或者 shell 命令的第一行,各最多 24 token,先脱敏;不含文件内容、写入的内容和工具输出;它不带更早的对话,预算仍是 24000(一般只用几千),步骤等它仍只等 rejudgeWaitMs。
  • 问题摘要(写好之后,发消息时的 effort 请求里):不超过 500 token,是 summaryModel 对你和主 agent 这个问题的转述,输入给它的内容先脱敏;它占 state 的预算,最近的对话让给它。
  • 派出 agent 和 Workflow 里的 agent:主 agent 写给它的任务(prompt)、描述、agent 类型,加上你这一轮说的话;unresolved 开着时还有问题摘要(summaryModel 写的,默认 Haiku 5.5)和次数(只当背景,不加强提示);还有它的背景(ADR 0007,选 Jev 时 2026-10-15 起也带,ADR 0009):派出它的那段对话,到这次 Agent 或 Workflow 调用为止(同样只有文字和工具名,不包含文件内容和工具输出;子 agent 派出的 agent 读那个子 agent 自己的对话);Workflow 里的 agent 还有整个脚本(脱敏)。先放任务和你的话,背景填剩下的预算(Jev 96000,pplx 派出 agent 32000、Workflow 一个请求 48000),脚本最多占三分之一,对话从新往旧放。
  • 一起派出的 agent 合进一个请求(ADR 0009)。同一条消息里的几个 Agent 调用,和 Workflow 里一起启动、要当场判断的那批 agent(fan-out),共用一个请求:你的话、摘要、对话和脚本只放一份,每个 agent 的任务各占一个字段、各问各的题。一个请求最多 8 个 agent,多了分成几个合并请求。同一条消息里的 Agent 调用要都到齐才发,没到的最多多等 300 毫秒(fork、teammate 这类不经路由的调用永远不会到);只派出一个 agent 时不等。同时在途的请求有上限:Jev 最多 4 个(1.14 实测同时答 4 个长请求和答 1 个一样快),pplx 最多 5 个,占满时新到的 agent 并进下一个请求;所有请求还都受账号的速率限额约束(jevQps、jevTokensPerSecond、pplxQps)。Workflow 的 agent 不是一次生成的(分阶段、按结果再派),后来启动的 agent 进下一个请求。每个 agent 最多等 6000 毫秒(Jev;pplx 8000),等不到就按主 agent 原来的要求启动,看板写明原因。
  • Workflow 在后台运行、你又发了消息时,等到 agent 启动才判断的那些 agent(prompt 是数据的调用、读不了的脚本),读的仍是启动 Workflow 那一轮你的话、那时的问题摘要和到那次调用为止的对话,不是你后来的消息。
  • 打开 skill 推荐时:本会话每个 skill 的名字和画像(还没有画像的用描述),以及排在前面的几个 skill 的描述、画像和 SKILL.md 开头约 700 个字符。skill 画像由你自己的 Claude 登录写(模型是 skillsProfileModel),用你的用量,不经过决策模型的提供方。
  • 发送前对常见的 secret 格式脱敏,替换成 [REDACTED]:各家的 API key 和 token(含 Perplexity 的 pplx-...)、password=... 这类赋值(键名带引号的 JSON 写法 "apiKey": "..." 也算)、URL 里的密码、私钥和 JWT。
  • 请求发往你用的决策模型:默认的 pplx 发往 Perplexity(api.perplexity.ai),选 Jev(或没有 Perplexity key、退回 Jev)时发往 TypeSafe(api.typesafe.ai)。带图的请求不是这样,见下一节。
  • 每次请求的结果和每个决定都写进 debug log(claude --debug-file <路径>),不进入会话。

图像:发给谁,什么时候发

图没法脱敏,带图请求里的文字也不脱敏。 只有不带图的决策请求,文字发出前才会替换常见的 secret 格式;看图核对的检查项、文字规范和图一样原样发出,截图里的密钥、聊天记录、个人信息也会原样发出去。装之前请先想清楚你的 agent 会截什么图。debug log 只记张数、尺寸、估算的 token 和耗时,从不写图的内容和密钥。

发给谁。 带图的请求用图像后端,和 decisionModel 无关:

  • 有 TypeSafe 的 key:发往 TypeSafe(api.typesafe.ai),固定用 jev-1.14.0(框题只有 1.14 有,也免得 jev-latest 改指向时看图的行为悄悄变),请求头带 TypeSafe-Danger-Zone-Images: true。
  • 没有 TypeSafe 的 key、但有 Perplexity 的 key:发往 Perplexity(api.perplexity.ai)。决策日志里记一条「看图改用 pplx」。
  • 两个 key 都没有:三项图像功能都不可用,visual_check 不会出现在 agent 的工具列表里。

所以决策模型选了 pplx、又填了 TypeSafe 的 key 时,图发给 TypeSafe,不发给 Perplexity;不带图的决策仍照你选的决策模型走,带图路由读出的读数是文字,随后和别的文字一起发往你选的决策模型。

哪些功能、什么时候发。

  • 看图核对:只在 agent 调用 visual_check 时发(look: true 不发,只把缩过的图还给 agent)。发的是这次调用里 images、reference、compare_to 点名的图;录屏发抽出的帧(Jev 12 帧,pplx 8 帧);有参考图时还有从图上裁下来的局部放大图。每次调用在对话里看得见。开关关着时调用不发请求。
  • 截图接管:自己不发任何图。 它把图拦在 agent 之外;图会不会发给图像后端,要看 agent 之后是否拿它调用看图核对。
  • 带图路由:你发的消息带图时发,一轮进行中主 agent 读了参考图或你又贴了图时也发;一组最多 6 张,每张缩到约 100 万像素以内,同一组图只发一次。agent 自己截的图不发。
  • 默认设置下,只有看图核对会发图(它默认开,但要 agent 去调用)。截图接管和带图路由默认关,装好后不会有图被自动发出去。

磁盘上的临时文件。 缩图、裁图、抽帧要写临时文件,放在 $TMPDIR/dispatch-pilot/<会话 id>/(截图接管存下的 MCP 截图也在这里),mod 不清理,由系统清 $TMPDIR。缩图用 macOS 自带的 sips,录屏抽帧用 ffmpeg(要自己装)。不在 CLI 里($.process.run 不可用)或没有 sips 时,图已经合格(PNG 或 JPEG、尺寸在限制内、方向正)就原样发,否则相关的检查项记没把握并写明原因;没有 ffmpeg 时,录屏的检查项记没把握。

不想发图:/dp visual-check off(以及 /dp image-routing off、/dp screenshot-takeover off,后两个默认就是关)。

开销

  • 决策请求。 评测里 800 个 effort 请求共 614,292 input token(平均约 770 个),Jev 约 0.026 美元。评测的上下文很短;Jev 的 state 现在最多约 6.7k token,一个这样的 effort 请求不到 0.0003 美元(Jev 只按输入计费,每百万 token 0.042 美元),带 skill 推荐的约 2.9 万 token,约 0.0012 美元。默认的 pplx 同样只按输入计费,每百万 token 0.02 美元,同样大小的请求约是 Jev 的一半。
  • skill 推荐。 打开后,每条消息的第一个请求还带着本会话每个 skill 的名字和画像:111 个 skill 都写好画像时约 2.19 万 input token(不带画像约 8.6k);第一段分到 0.1 以上的 skill 才会发第二个请求,约 1.3k。作为交换,隐藏 skill 列表每个会话省下约 6.6k input token(本机 66 个 skill 时实测),换成的提示只有 360 个字符。
  • skill 画像用你自己的 Claude 登录写(模型是 skillsProfileModel),算在你的用量里:每份约 2k 输入和 200 输出 token,每个 SKILL.md 版本只写一次,每次会话开始最多写 skillsProfilesPerSession 份。
  • 问题摘要同样用你自己的 Claude 登录写(模型是 summaryModel),算在你的用量里:你本人的消息开始的每一轮结束后一次,输入是上一份摘要加这一轮(你的话、主 agent 的最终回复、工具汇总,各自截断),输出不超过 500 token。
  • 图像(只在你用到这些功能时才有开销)。看图核对:Jev 约每百万像素 2,600 token,每张图只算一次,每百万 token 0.042 美元;评测集基线里每张图平均约 2,300 token、不到 0.0001 美元,界面和海面的整套判断(整图加放大复核)一次约 6,000 token,延迟一题中位约 1.6 秒(两个请求接着发)。pplx 约每百万像素 1,000 token,要再乘题数,所以带图请求的题要少。带图路由的复杂度读数每张图约 1,000 token,另加最多约 3 秒的等待。截图接管不发请求,省的是 agent 上下文里的图。
  • claude plugin details dispatch-pilot@alex-mods(2.1.289)显示 0 个组件、常驻开销约 0 token:它看不到 mod 在运行时附加和替换的内容。其中有两样常驻:find_skill 工具和(图像后端可用时)visual_check 工具的说明都在主 agent 的工具列表里,每个会话都占一点上下文(visual_check 的 Jev 版说明约 3,900 个字符),这里没有算进去。

要求

  • Claude Code 2.1.300 及以上,mod 在 Claude Code 里默认启用。兜底在 agent.spawn 上设 Workflow agent 的模型,2.1.300 起才生效;更早的版本上这些 agent 只改得了 effort,模型按脚本或引擎的走。0.8.2 测试用的是 Claude Code 2.1.302(选 Jev 时 skill 推荐的第二段至少等 800 毫秒:同一个 key 上几个会话同时发消息时,第一段变慢,共用的 1500 毫秒不够第二段用;用测试里扮演引擎的 world 验证,并用 5 个并行的无头会话在真实 Jev 上实测过;同样的改动在 0.8.2-desktop.1 里,用 Desktop 自带的 2.1.299 跑过同样的并行实测),0.8.1 也是(Desktop 等非终端端按「点」来画,ADR 0012:重画放慢到 5 秒、运行中的色带用 SMIL 自己长、band 的「依据」按钮、依据面板的 agent 标签和底部开关、Desktop 上不写状态行;同样的改动用兼容版 0.8.0-desktop.1 在 Desktop 自带的 2.1.299 上真机点过一遍),0.8.0 测试用的是 Claude Code 2.1.302(Desktop 等非终端端的 Svg 标记、等宽字、band 折叠和状态行只用测试里扮演引擎的 world 验证过,SVG 渲染出来看过;没在 Desktop 上亲眼看过,Desktop 自带的 2.1.299 加载不了 dp),0.7.1 也是(TYPESAFE_API_KEY 的环境变量兜底,用测试里扮演引擎的 world 验证过;为它而做的 Claude Desktop 没法试,Desktop 内置的 2.1.299 加载不了 0.7.0 起的 mod,见「安装」的「Claude Desktop」),0.7.0 也是(兜底改在 agent.spawn 上:派出时改模型对 Workflow agent 生效、派出带着 label 和任务、没写 label 的调用 label 是 prompt 前 60 个字符、运行的第一个 agent 在 Workflow 工具返回之前就派出而工具不等它,用临时探针在真实会话里实测过;新的兜底用测试里扮演引擎的 world 验证过,没有在真实会话里跑过一轮),0.6.2 用的是 Claude Code 2.1.301(强提示改成另问一道 effort 题、按同一请求的三选一取用、max 门槛用 hintThetaMax:用测试里扮演引擎的 world 和评测里的真实 Jev 验证过,没有在真实会话里跑过一轮),0.6.1 也是(全面代码审查的修复,用测试里扮演引擎的 world 验证过,没有在真实会话里跑过一轮),0.6.0 也是(Jev 1.14 的长上下文、一起派出的 agent 合进一个请求和 Jev 的限速,用测试里扮演引擎的 world 和评测里的真实 Jev 验证过,没有在真实会话里跑过一轮),0.5.0 用的是 Claude Code 2.1.300(图像功能用到的引擎行为用 event-probe 实测过:引擎里图块的形状、引擎把图缩到长边 2000、换掉 Read 的图片结果又不留 [Image: …] 文字的写法、注册工具的回答能用哪些形式、hook 的 10 秒只算 mod 自己的代码;整套图像功能没有在真实会话里跑通一轮,见「局限」),0.4.5 也是(find_skill 直接在主 agent 的工具列表里,用 event-probe 实测过;看板的模型名新字色在浅色终端上目测过),0.4.4 也是(派出 agent 自己那一轮的 turn.start、被 SendMessage 唤醒的 agent 的 agent.spawn,在真实会话里实测过),0.4.3 用的是 Claude Code 2.1.296(选 pplx 时派出 agent 和 Workflow 请求里的对话和脚本、agent 启动时才判断的读启动那一轮,在真实会话里实测过),0.4.2 也是(被 TaskStop 停掉的 Workflow agent 的结束实测过),0.4.1 也是(Workflow agent 的 agent.spawn、Haiku 5.5 的 effort 在真实会话里实测过),0.4.0 用的是 Claude Code 2.1.294(默认的 pplx 配置跑通一轮真实流程,见 #53),此前版本用的是 2.1.291(订阅登录,看板和依据面板在终端里看过)和 jev-1.13.0;缓存和评测的实测是在 2.1.289 上做的;跑 eval/ 和 scripts/ 里的 Node 脚本用的是 Node 26.5,用 mod 本身不需要 Node。
  • 只支持 Claude Code 订阅(ADR 0001,docs/adr/0001-main-agent-effort-only-no-model-switch.md)。Dispatch Pilot 每轮、每一步都改主 agent 的 effort,但从不改它的模型:换模型必然让 prompt cache 失效,而在订阅下,同一个模型内切换 effort 保留缓存(2.1.289 上 Opus 5.5 加订阅实测)。Bedrock、Vertex 和各种网关上切换 effort 会让缓存失效,不在支持范围内。Claude Code 的文档只点名了 Opus 5.5、Sonnet 5.5 和 Fable 5.1 保留缓存,其他大多数模型上每档 effort 各有一份缓存,切换会重算整段请求(见 docs/research/decision-models-and-caching.md 的 3.4)。
  • 一个决策模型的账号。 默认的决策模型是 pplx,要 Perplexity 的 API key(Decisions API);Jev 要 TypeSafe 的 API key。没有 Perplexity 的 key、但有 TypeSafe 的 key 时,自动退回 Jev(0.3.1 的老用户升级后不会失去路由,依据面板的决策日志里会有一条说明原因);两种 key 都没有时 mod 不发任何请求,每一轮都按会话自己的 effort 走,看板上写明缺的是 Perplexity 的 key。
  • 要用全部图像功能,需要 TypeSafe 的 API key。 放大复核、全屏「哪里不同」、档位序列、录屏取 12 帧都靠 Jev 1.14。只有 Perplexity 的 key 时(没有 TypeSafe 的 key),三项图像功能仍可用,但看图核对只做整图判断:不框、不裁、没有放大复核,有参考图时「过」只能记没把握;档位序列不可用;一个请求最多 8 张图,录屏取 8 帧。两个 key 都没有,图像功能都不可用。图发给谁见「图像:发给谁,什么时候发」。
  • 缩图、裁图用 macOS 自带的 sips,录屏抽帧用 ffmpeg(要自己装)。只有看图核对和带图路由需要它们,其余功能不需要。截图接管把 MCP 工具返回的图存成临时文件,用的是 macOS 的 base64 -D(Linux 的 base64 不认这个参数);存不下来时图原样留给 agent。

安装

claude plugin marketplace add alexcz-a11y/claude-mods
claude plugin install dispatch-pilot@alex-mods --scope user

想改 mod 或者试未发布的改动时,也可以从本地克隆添加:claude plugin marketplace add ./claude-mods(相对路径要以 ./ 或 ../ 开头,否则会被当成 GitHub 仓库)。从本地目录添加的 marketplace,Claude Code 直接从那个目录加载 mod,克隆里检出的是哪个版本,用的就是哪个版本。

在 shell 里装好的 mod,下次启动 Claude Code 时才加载:装好后重启 Claude Code,或者在已经开着的会话里运行 /reload-plugins。在会话里运行 /plugin,看到 1 mod active · dispatch-pilot 说明 mod 已经加载;运行 /dp 会打开依据面板,/dp status 列出各项功能的开关。接着给它一个决策模型的密钥。

pplx(默认)。 给它 Perplexity 的 API key,有两种给法,同时给了就用第 1 种:

  1. 在 Claude Code 的会话里运行 /plugin configure dispatch-pilot@alex-mods,在弹出的配置对话框里填 perplexityApiKey;输入会被遮住。在会话里用 /plugin 安装时也会弹出这个对话框;在 shell 里用 claude plugin install 安装不会弹,装好后用这条命令,或者用 stdin 传进去(需要 jq):
   read -rs PERPLEXITY_API_KEY && export PERPLEXITY_API_KEY   # 粘贴密钥后回车,不回显,值也不会留在 shell 历史里
   jq -n '{perplexityApiKey: env.PERPLEXITY_API_KEY}' | claude plugin configure dispatch-pilot@alex-mods --values-stdin
  1. 设环境变量 PERPLEXITY_API_KEY(启动 Claude Code 的环境里要有)。在 Claude Desktop 里只能用这一种,填在哪见下面的「Claude Desktop」。

不要用 claude plugin install --config perplexityApiKey=... 传密钥,也不要用 jq --arg:它们的值会出现在进程参数里,同一台机器上的 ps 看得到。

--values-stdin 读一个 JSON 对象,值都是单行字符串,没写到的选项保持原值。保存之后要重启 Claude Code 才生效,命令也会提示 Configuration saved. Restart Claude Code to apply it.。不带参数运行 claude plugin configure dispatch-pilot@alex-mods 会列出所有选项,并标出哪些还没有设置。

Jev。 想用 Jev,就把 decisionModel 设成 jev(在 /config 里选,或写进 pluginConfigs),再给它 TypeSafe 的 API key,给法同上,同时给了也用第 1 种:配置对话框里填 typesafeApiKey(或者 stdin 的 JSON 里写 typesafeApiKey),或者设环境变量 TYPESAFE_API_KEY。全部图像功能也要这个 key(见「要求」),不管决策模型是哪个。设成 jev 就始终用 Jev,哪怕也有 Perplexity 的 key。Jev 的决策固定用 jev-1.14.0,不跟着 jev-latest 走:门槛是在这个版本上量过的,TypeSafe 换版本时 mod 的行为不会悄悄变。

两种 key 都只放在请求头里,不会出现在 debug log、看板、依据面板和 $.state 里;会话开始时 debug log 只写 key 从哪里来(pplx key:、jev key: 后面是 from the options、环境变量名或 not set),不写 key 本身。

Claude Desktop(Code 标签)。 Desktop 的 Code 标签收不到 keychain 里的敏感 userConfig(#35,上游 anthropics/claude-code#89749):在那里 mod 拿到的 typesafeApiKey、perplexityApiKey 总是空的,配置对话框里填过也一样。Desktop 也不读 ~/.zshrc 里 export 的变量(从 Dock 或 Finder 打开时,它只从 shell 配置里取 PATH 和固定的几个 Claude Code 变量)。所以在 Desktop 里,密钥只能用环境变量 PERPLEXITY_API_KEY 和(或)TYPESAFE_API_KEY 给,可以放在两个地方:

  • 已保存的环境(加密保存)。 从 Desktop 2.31226.0(2026-10-08)起,环境变量挂在已保存的环境上,不再有对所有本地会话都生效的那一份。每个已保存的环境各有一份变量,开会话时选的是哪个环境,会话就带上哪个环境的变量;「This computer」从空白开始,不带任何变量。所以每个用来开会话的环境都要加上密钥,直接从「This computer」开的会话拿不到。改版前全机通用的变量,已经复制进了 Desktop 自动建的那些环境。Claude Code 文档的 Desktop 页还写着鼠标悬停在 Local 上、点齿轮打开本地环境编辑器,那是改版前的入口。
  • ~/.claude/settings.json 的 env(明文)。 写在这里,Desktop 的每个会话都拿得到,终端也一样,不用一个环境一个环境地加;代价是密钥明文存在这个文件里。同一个变量两处都设了,Desktop 的会话用已保存环境里的那个:Desktop 启动会话时,它给的环境优先于 settings 文件的 env。

Desktop 内置的 Claude Code 版本还要在 2.1.300 及以上(在 Desktop 的会话里运行 /status,看 Claude Code 那一行)。0.7.0 起 mod 用到 prompt.change 事件,2.1.299 不认它,整个模块加载失败,而且界面上什么也不报:没有看板,/dp 也没有,只有 --debug-file 的日志里有一行 hooks module dispatch-pilot@alex-mods failed to load。0.7.1 的环境变量兜底(TYPESAFE_API_KEY)只用测试里扮演引擎的 world 验证过,没有在真实的 Desktop 会话里试过:写这段时 Desktop 内置的是 2.1.299,加载不了 Dispatch Pilot。2026-10-22 起 Desktop 内置的是 2.1.308,可以加载。

只有 TypeSafe 的 key 的老用户不用改任何配置:decisionModel 没设(或设的是 pplx、已移除的 clef、拼错的值)又没有 Perplexity 的 key 时,用 Jev,每个会话的决策日志(/dp 打开的依据面板)里有一条「改用 Jev」写明原因。以后想换成 pplx,只要填上 Perplexity 的 key。

decisionModel 在 /config 里是下拉选择,有 pplx(默认)和 jev 两项;填了别的值(包括已移除的 clef),按没设处理,也就是默认的 pplx(没有 Perplexity 的 key 时按上面的规则退回 Jev)。

更新

从 GitHub 添加 marketplace 的,在 shell 里运行:

claude plugin marketplace update alex-mods
claude plugin update dispatch-pilot@alex-mods

第一条刷新 marketplace 的列表,第二条更新 mod。更新之后重启 Claude Code,或者在开着的会话里运行 /reload-plugins。

claude plugin update 看的是版本号(.claude-plugin/plugin.json 的 version):版本号和你装的一样,它就回答已经是最新版本(is already at the latest version),不换掉本机的副本,哪怕分支上已经有新的提交。新的版本会升版本号。这个 marketplace 默认不自动更新;要打开,在会话里运行 /plugin,到 Marketplaces 里选 alex-mods,再选 Enable auto-update。自动更新同样只在版本号变了时才换。

从本地克隆安装的,不用 claude plugin update:在克隆里取新的提交(例如 git -C claude-mods pull),然后重启 Claude Code 或运行 /reload-plugins。Claude Code 直接从克隆加载 mod,不看版本号。

从 jev-pilot 切换

Dispatch Pilot 和 jev-pilot 不能共存:两者都在 turn.step 上改主 agent 的 effort,会互相覆盖。已经装了 jev-pilot 的话,按这个顺序切换:

  1. 先在 jev-pilot 还启用的会话里运行 /jev-pilot:setup restore。 它把 /jev-pilot:setup 改过的 skill 设置(settings 里的 skillOverrides)恢复成原样,并删掉备份。这条命令是 jev-pilot 自己的,只有它加载着才能用,所以要在停用它之前运行。不恢复的话,那些 skill 会一直对主 agent 隐藏,Dispatch Pilot 也推荐不了它们。没有运行过 /jev-pilot:setup 的话,这一步可以跳过。
  2. 停用 jev-pilot:claude plugin disable jev-pilot@jev-pilot。
  3. 重启 Claude Code:已经开着的会话还带着 jev-pilot,要重启。
  4. 之后只用 claude 启动,不要用 claude-jev。 jev-pilot 的 marketplace 安装停用之后,claude-jev 启动器会改用 --plugin-dir 加载它在 ~/.claude/plugins/marketplaces/jev-pilot 里的本地副本,jev-pilot 又被加载进来(还会起它自己的 router),两者就又撞在一起了。

配置

选项的值存在两个地方:

  • 敏感项(typesafeApiKey、perplexityApiKey)存进平台的安全凭据存储(Claude Code 文档的说法),输入时被遮住,不在 /config 里出现。用配置对话框(/plugin configure dispatch-pilot@alex-mods),或者 claude plugin configure ... --values-stdin 填,见「安装」。两项为空时分别读环境变量 TYPESAFE_API_KEY、PERPLEXITY_API_KEY;Cla
Source 91 files
hooks/dispatch-pilot.ts 72 lines
1// Dispatch Pilot's entry: it only assembles. Each feature lives in its own
2// file under features/ and registers its own hooks; the core goes last.
3//
4// Order is nesting: what registers first is outermost and sees an event
5// first. Features go above the core so that on every event they share, each
6// feature has run before the core finishes the event (sends the decision
7// request, writes the step). To add a feature: one file, one line here,
8// above `registerCore` (DEVELOPMENT.md, 开发).
9
10import type { Register } from 'claude-code'
11import { registerScreens, registerStatus } from './board/screens.tsx'
12import { registerCore } from './core/core.ts'
13import { registerLoopStart } from './core/loop-start.ts'
14import { registerReport } from './core/report.ts'
15import { setup } from './core/setup.ts'
16import { registerControl } from './features/control.ts'
17import { registerDispatchedAgents } from './features/dispatched-agents.ts'
18import { registerEscalation } from './features/escalation.ts'
19import { registerFindSkill } from './features/find-skill.ts'
20import { registerImageRouting } from './features/image-routing.ts'
21import { registerMainEffort } from './features/main-effort.ts'
22import { registerMidturnEffort } from './features/midturn-effort.ts'
23import { registerPromptHint } from './features/prompt-hint.ts'
24import { registerReferenceMidturn } from './features/reference-midturn.ts'
25import { registerUnresolved } from './features/unresolved.ts'
26import { registerVisualCheck } from './features/visual-check.ts'
27import { registerScreenshotTakeover } from './features/screenshot-takeover.ts'
28import { registerSkillProfiles } from './features/skill-profiles.ts'
29import { registerSkills } from './features/skills.ts'
30import { registerWorkflowAgents } from './features/workflow-agents.ts'
31import { registerWorkflowLabels } from './features/workflow-labels.ts'
32
33export const register: Register = (on, options) => {
34  const ctx = setup(options)
35
36  // The status line where the band is not drawn: outermost of all, so a turn's end reads the board the report wrote.
37  registerStatus(on)
38  // The decision report keeps the board's turn count: outermost but the status line, so a turn is counted before anything beneath reads the board.
39  registerReport(on)
40  // The screens draw the report's data (the band, the footer); no feature touches them.
41  registerScreens(on)
42
43  // When each loop began (the screenshot takeover and the routing's reference images read it): no switch, no decision.
44  registerLoopStart(on)
45
46  // Features, outermost first.
47  registerControl(on, ctx)
48  registerMainEffort(on, ctx)
49  registerUnresolved(on, ctx)
50  registerEscalation(on, ctx) // above the mid-turn feature: its raise is in the plan before a mid-turn answer is applied
51  // Outside the mid-turn feature: a Read has been recorded in the turn's steps by the time this feature asks it to judge again.
52  registerReferenceMidturn(on, ctx)
53  registerMidturnEffort(on, ctx)
54  registerDispatchedAgents(on, ctx)
55  registerWorkflowAgents(on, ctx)
56  // Inside workflow-agents: a Workflow call is this feature's only once that feature has sent the script on, so the
57  // agents of other runs never wait while it is still deciding.
58  registerWorkflowLabels(on, ctx)
59  // Outside skills: at session start it writes the profiles of the skills that feature has just read.
60  registerSkillProfiles(on, ctx)
61  registerSkills(on, ctx)
62  registerFindSkill(on, ctx)
63  registerVisualCheck(on, ctx)
64  registerScreenshotTakeover(on, ctx)
65  registerImageRouting(on, ctx)
66  // The prompt box's hint: it decides nothing, and reads only the switches and the lock.
67  registerPromptHint(on)
68
69  // The core: always last.
70  registerCore(on, ctx)
71}
72
hooks/board/screens.tsx 326 lines
1// The screens' hooks (ADR 0004: drawn from the decision report's data, never
2// written to by a feature): the band above the prompt (`AbovePrompt`), the
3// summary at the right end of the footer (`SessionMode`) and the rationale pane
4// (`Pane`, the pane `/dp` opens). One hook tree for every surface, branching on
5// `e.surface`: every surface draws the same design (band.tsx, footer.tsx,
6// pane.tsx), its marks (time ribbons, probability bars, confidence meters) a
7// Raster on the terminal and an Svg on Desktop, VS Code and the mobile app;
8// off the terminal the footer's tag is at most 24 characters and the log keeps
9// to a window short of Desktop's 2000 nodes.
10//
11// Where the band is not drawn (a session without a terminal: VS Code draws
12// none, Desktop's is gone while idle), the status line under the prompt says
13// the band's line in words (status-line.ts, ADR 0011): its hooks set it as a
14// turn starts and ends, an agent starts and the person runs `/dp`.
15//
16// Each hook reads the board, the log and the agent the person picked from
17// $.state while it draws, so the host draws it again when they change; while
18// an agent runs it asks for one more frame every `TICK_MS` on the terminal (the
19// spinner, the running clocks and ribbons) and every `SLOW_TICK_MS` elsewhere,
20// where a redraw costs the person a press (view.ts) and the running ribbons
21// grow by themselves in between. The band and the footer keep what other mods
22// draw in the same place: the engine's drawing beneath goes in first (spec
23// story 38); the pane is Dispatch Pilot's own.
24
25import type { EngineInterface, On, RenderInput, Timer } from 'claude-code'
26import { errorText } from '../decision/backend.ts'
27import { report, type NoticeIo, type SwitchIo } from '../core/report.ts'
28import { isOn, isShown, keepSwitch, listSwitches, masterOn, setMaster, setSwitch, SWITCHES_KEY } from '../core/switches.ts'
29import type { Effort } from '../decision/effort.ts'
30import { bandTree, statusText } from './band.tsx'
31import { FOOTER_COLUMNS, footerTree, TAG_CHARS } from './footer.tsx'
32import { paneTree } from './pane.tsx'
33import { appPaneTree } from './pane-app.tsx'
34import { nodeCount, rasterMarks, showsText, svgMarks, type Marks } from './kit.tsx'
35import { NO_PANE_STATE, PANE_COLUMNS, PANE_ID, PANE_TITLE, withFold } from './rationale.ts'
36import { screenView, SLOW_TICK_MS, TICK_MS, type AgentRow, type ScreenView } from './view.ts'
37import { bandHintIs, hintLineIs, statusLineUsed, surfacesAre, turnLineIs, type StatusUpdate } from './status-line.ts'
38
39const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
40const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
41const SELECTED = { plugin: 'dispatch-pilot', key: 'selected' } as const
42const PROFILES = { plugin: 'dispatch-pilot', key: 'skillProfiles' } as const
43const LOCK = { plugin: 'dispatch-pilot', key: 'lock' } as const
44const PANE_VIEW = { plugin: 'dispatch-pilot', key: 'paneView' } as const
45const COUNT = { plugin: 'dispatch-pilot', key: 'unresolved' } as const
46const BAND_FOLD = { plugin: 'dispatch-pilot', key: 'bandFolded' } as const
47const DRAFT_HINT = { plugin: 'dispatch-pilot', key: 'draftHint' } as const
48
49/** The log's windows for a surface that refuses a large tree, widest first: what the pane keeps of the log and of the re-decisions. */
50const WINDOWS = [
51  { entries: 40, mids: 20 },
52  { entries: 16, mids: 8 },
53  { entries: 4, mids: 3 },
54  { entries: 0, mids: 0 },
55] as const
56/** A tree this big is drawn again in the next window: Desktop refuses 2000. */
57const MOST_NODES = 1800
58
59/** The next frame asked for while an agent runs (module state: a hot reload cancels it with the old module, and the next draw asks again). */
60let ticking: Timer | null = null
61
62/** The screens' view, read from $.state now (a read while drawing subscribes the drawing to the value); `slow` for a surface other than the terminal. */
63async function viewOf($: EngineInterface, isWorking: boolean, slow: boolean): Promise<ScreenView> {
64  const [board, log, picked, now] = await Promise.all([$.state.get(BOARD), $.state.get(DECISIONS), $.state.get(SELECTED), $.clock.now()])
65  return screenView({
66    board: board.value ?? { turn: 0, nodes: [] },
67    log: log.value ?? [],
68    now,
69    selected: picked.value ?? null,
70    master: masterOn(),
71    isOn,
72    isShown,
73    isWorking,
74    slow,
75  })
76}
77
78/** The first engine with `$.ui.view`. */
79const VIEW_SINCE = [2, 1, 300] as const
80
81/** Whether a version (`2.1.299`, `2.1.300-dev.…`) is `least` or later; one that does not read as a version is taken to be. */
82export function atLeast(version: string, least: readonly number[]): boolean {
83  const parts = /^(\d+)\.(\d+)\.(\d+)/.exec(version)
84  if (parts === null) return true
85  for (let i = 0; i < least.length; i++) {
86    const part = Number(parts[i + 1])
87    const want = least[i] ?? 0
88    if (part !== want) return part > want
89  }
90  return true
91}
92
93/** Whether the engine can put an agent's transcript in the main view (`$.ui.view`); an engine that does not say its version is taken to. */
94async function viewsTranscripts($: EngineInterface): Promise<boolean> {
95  const version = await $.session.version().catch(() => undefined)
96  return version === undefined || atLeast(version.version, VIEW_SINCE)
97}
98
99/** The surface's marks: a Raster's cells on the terminal, an Svg where the surface has one. */
100function marksOf($: EngineInterface, e: RenderInput<'AbovePrompt' | 'Pane'>): Marks {
101  return e.surface === 'terminal' ? rasterMarks($.ui.resolve(e).Raster) : svgMarks($.ui.resolve(e).Svg, $.ui.resolve(e).Box)
102}
103
104/** One more frame while something runs, in `TICK_MS` on the terminal and `SLOW_TICK_MS` elsewhere (a view that looks ahead); none once nothing does. */
105function tick($: EngineInterface, view: ScreenView): void {
106  const moving = view.live && view.rows.some((row) => row.node.state === 'running')
107  if (!moving || ticking !== null) return
108  try {
109    ticking = $.clock.after(view.ahead > 0 ? SLOW_TICK_MS : TICK_MS, () => {
110      ticking = null
111      $.ui.invalidate('ui.render')
112    })
113  } catch {
114    // no timer: the screens move on at the board's next change
115    ticking = null
116  }
117}
118
119/**
120 * Puts an agent's transcript in the main view (null: the main conversation back), from a press in the pane; a view the
121 * engine does not move is the decision report's to tell (a toast).
122 */
123async function showTranscript($: EngineInterface, agentId: string | null): Promise<void> {
124  // The engine's refusal comes back as `deny`; a hook's, as an error.
125  const why = await $.ui.view(agentId === null ? {} : { agentId }).then(
126    (shown) => shown.deny,
127    (error: unknown) => errorText(error),
128  )
129  if (why === undefined) return
130  const io: NoticeIo = { debug: (line) => $.ui.log(line, { to: 'debug' }), now: () => $.clock.now(), toast: (text) => $.ui.toast(text) }
131  await report(io, { unviewed: { agent: agentId, reason: why } })
132}
133
134/** The agent picked, its card shown in the rationale pane (written from a press, never while drawing). */
135async function pick($: EngineInterface, row: AgentRow): Promise<void> {
136  await $.state.set(SELECTED, { turn: row.node.turn, id: row.node.id })
137}
138
139/** Sets the status line to what `update` says, when it changed. */
140function putStatusLine($: EngineInterface, update: StatusUpdate): void {
141  if (update.changed) $.ui.status(update.line)
142}
143
144/** The status line again from the board: where the session draws (it can change), then the band's line. */
145async function refreshStatus($: EngineInterface): Promise<void> {
146  const surfaces = await $.session.surfaces().catch(() => [] as const)
147  putStatusLine($, surfacesAre(surfaces))
148  // A session with a terminal has no line: the board is not read for it.
149  if (statusLineUsed()) putStatusLine($, turnLineIs(statusText(await viewOf($, false, true))))
150}
151
152/** `refreshStatus`, once the event is through: a line that cannot be set never stops anything. */
153async function refreshQuietly($: EngineInterface): Promise<void> {
154  try {
155    await refreshStatus($)
156  } catch {
157    // the line keeps what it said
158  }
159}
160
161/**
162 * The status line's hooks (status-line.ts), which only watch: outermost of all (dispatch-pilot.ts), so that when a
163 * turn ends the line reads the board the decision report has just written.
164 */
165export function registerStatus(on: On): void {
166  on('session.start', { cwd: /(?:)/ }, async ($, e, next) => {
167    const result = await next(e)
168    await refreshQuietly($)
169    return result
170  })
171  on('turn.start', { turnId: /(?:)/ }, async ($, e, next) => {
172    const result = await next(e)
173    // The draft the hint was about has been sent: off the status line, and off the band's idle line.
174    if (e.agentId === undefined) {
175      putStatusLine($, hintLineIs(null))
176      if (bandHintIs(null)) await $.state.set(DRAFT_HINT, null).catch(() => undefined)
177    }
178    await refreshQuietly($)
179    return result
180  })
181  on('agent.spawn', { tool_use_id: /(?:)/ }, async ($, e, next) => {
182    const result = await next(e)
183    await refreshQuietly($)
184    return result
185  })
186  on('turn.complete', { turnId: /(?:)/ }, async ($, e, next) => {
187    const result = await next(e)
188    await refreshQuietly($)
189    return result
190  })
191  on('command.run', { command: 'dp' }, async ($, e, next) => {
192    const result = await next(e)
193    await refreshQuietly($)
194    return result
195  })
196}
197
198export function registerScreens(on: On): void {
199  // The band above the prompt.
200  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
201    if (e.props.hasSurvey) return next(e)
202    const own = await next(e)
203    try {
204      const t = $.ui.resolve(e)
205      // The time ribbons: the terminal's Raster, an Svg elsewhere.
206      const marks = marksOf($, e)
207      const [view, folded, drafted] = await Promise.all([viewOf($, e.props.isWorking, e.surface !== 'terminal'), e.surface === 'terminal' ? null : $.state.get(BAND_FOLD), e.surface === 'terminal' ? null : $.state.get(DRAFT_HINT)])
208      tick($, view)
209      // The terminal folds the band itself; elsewhere the band has its own fold, kept for the session.
210      const fold = folded === null ? undefined : { folded: folded.value === true, set: (value: boolean) => void $.state.set(BAND_FOLD, value).catch(() => undefined) }
211      // A digit (off the terminal, the agent's name or 依据) brings up the pane: a press is the person's asking, so the
212      // pane is placed at any width; it opens without taking the keys, so the next digit still picks. One not placed
213      // is closed again, and the decision report tells the person why in a toast.
214      const open = async () => {
215        const opened = await $.ui.open({ id: PANE_ID, title: PANE_TITLE, closeOnEscape: true, columns: PANE_COLUMNS })
216        if (!opened.isPlaced) {
217          await $.ui.close({ id: PANE_ID })
218          const io: NoticeIo = { debug: (line) => $.ui.log(line, { to: 'debug' }), now: () => $.clock.now(), toast: (text) => $.ui.toast(text) }
219          await report(io, { unplaced: { reason: opened.reason } })
220        }
221      }
222      const select = async (row: AgentRow) => {
223        await pick($, row)
224        await open()
225      }
226      const acts = {
227        select: (row: AgentRow) => void select(row).catch(() => undefined),
228        ...(fold === undefined ? {} : { fold }),
229        // Off the terminal the band's own 依据, where the terminal writes `/dp log`.
230        ...(e.surface === 'terminal' ? {} : { open: () => void open().catch(() => undefined) }),
231      }
232      const tree = bandTree(t, view, { cols: e.props.bodyColumns, rows: e.props.maxRows }, acts, marks, drafted?.value ?? null)
233      if (tree === null) return own
234      const { Box } = t
235      return (
236        <Box flexDirection="column">
237          {own}
238          {tree}
239        </Box>
240      )
241    } catch (error) {
242      // A band that cannot be drawn leaves the place to the others.
243      $.ui.log(`band not drawn: ${errorText(error)}`, { to: 'debug' })
244      return own
245    }
246  })
247
248  // The right end of the footer, beside the engine's modes.
249  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
250    const own = await next(e)
251    try {
252      const t = $.ui.resolve(e)
253      const view = await viewOf($, false, e.surface !== 'terminal')
254      tick($, view)
255      // A column between the engine's modes (or another mod's drawing) and the tag, when there are any: it counts in what the tag adds.
256      const gap = showsText(own, e.props.modes.length > 0) ? 1 : 0
257      const tree = footerTree(t, view, (e.surface === 'terminal' ? FOOTER_COLUMNS : TAG_CHARS) - gap)
258      if (tree === null) return own
259      const { Box } = t
260      return (
261        <Box gap={gap}>
262          {own}
263          {tree}
264        </Box>
265      )
266    } catch (error) {
267      $.ui.log(`footer not drawn: ${errorText(error)}`, { to: 'debug' })
268      return own
269    }
270  })
271
272  // The rationale pane (`/dp`): the card of the agent picked, the decision log.
273  on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e, next) => {
274    try {
275      const t = $.ui.resolve(e)
276      const [view, log, profiles, lock, kept, count] = await Promise.all([viewOf($, false, e.surface !== 'terminal'), $.state.get(DECISIONS), $.state.get(PROFILES), $.state.get(LOCK), $.state.get(PANE_VIEW), $.state.get(COUNT)])
277      tick($, view)
278      const entries = log.value ?? []
279      const state = kept.value ?? NO_PANE_STATE
280      const shown = isOn('skills') && isOn('skill-profiles') ? (profiles.value ?? null) : null
281      // The summary the session holds, while the feature that writes it is on.
282      const summary = isOn('unresolved') ? (count.value?.summary ?? null) : null
283      const viewing = e.props.view.agentId ?? null
284      // The terminal's labels spell their keys; Desktop draws a key beside its Button, and the others take none.
285      // Claude Desktop's own engine (2.1.299) has no `$.ui.view`: no 看它的对话 there, rather than a button that only says so.
286      const canView = await viewsTranscripts($)
287      const input = { view, log: entries, profiles: shown, switches: listSwitches().map((s) => ({ name: s.name, on: s.on })), master: masterOn(), lock: lock.value ?? null, viewing, summary, state, spellKeys: e.surface === 'terminal', canView }
288      const act = {
289        pick: (row: AgentRow) => void pick($, row).catch(() => undefined),
290        view: (agentId: string | null) => void showTranscript($, agentId).catch(() => undefined),
291        fold: (turn: number, open: boolean) => void $.state.set(PANE_VIEW, withFold(state, turn, open, entries)).catch(() => undefined),
292        failures: (open: boolean) => void $.state.set(PANE_VIEW, { ...state, failures: open }).catch(() => undefined),
293        // Off the terminal the pane's own 关闭: the surface's × is not always heard (Desktop).
294        ...(e.surface === 'terminal' ? {} : { close: () => void $.ui.close({ id: PANE_ID }).catch(() => undefined) }),
295      }
296      const marks = marksOf($, e)
297      if (e.surface === 'terminal') return paneTree(t, input, e.props.bodyColumns, act, marks)
298      // Elsewhere the pane is clicked: the switches and the lock change where they are shown, as `/dp` would change
299      // them (control.ts): the switch kept in $.store, the screens drawn again without what a switch that is off owns.
300      const reporting: SwitchIo = { redraw: () => $.ui.invalidate('ui.render') }
301      const flip = async (name: string, wanted: boolean) => {
302        if (name === 'master') setMaster(wanted)
303        else if (!setSwitch(name, wanted)) return
304        await report(reporting, { switched: true })
305        await keepSwitch({ get: () => $.store.get(SWITCHES_KEY), set: (value) => $.store.set(SWITCHES_KEY, value) }, name)
306      }
307      const acts = {
308        ...act,
309        toggle: (name: string, wanted: boolean) => void flip(name, wanted).catch(() => undefined),
310        lock: (effort: Effort | null) => void $.state.set(LOCK, effort).catch(() => undefined),
311        switches: (open: boolean) => void $.state.set(PANE_VIEW, { ...state, switches: open }).catch(() => undefined),
312      }
313      // The widest window of the log that stays short of Desktop's 2000 nodes.
314      let tree = appPaneTree(t, { ...input, window: WINDOWS[0] }, e.props.bodyColumns, acts, marks)
315      for (const window of WINDOWS.slice(1)) {
316        if (nodeCount(tree) < MOST_NODES) break
317        tree = appPaneTree(t, { ...input, window }, e.props.bodyColumns, acts, marks)
318      }
319      return tree
320    } catch (error) {
321      $.ui.log(`rationale pane not drawn: ${errorText(error)}`, { to: 'debug' })
322      return next(e)
323    }
324  })
325}
326
hooks/core/core.ts 145 lines
1// The core: the innermost hooks of every event it shares with the features.
2// The entry registers it last, so on each event every feature's hook has run
3// (on the way down) before the core finishes the event:
4//
5//   prompt.submit  sends the message's ballot as up to two decision requests
6//                  (the effort question alone, the rest together; ADR 0005),
7//                  in parallel, hands each part its answers, then lets the
8//                  prompt in
9//   turn.start     opens the main turn's record, with the effort its prompt
10//                  was decided at
11//   turn.step      the one writer of effort (and of a non-main loop's model):
12//                  sends every step as the plan table says
13//   classic.PreToolUse  notes the calls a settings hook refused (core/outcomes.ts)
14//   command.run    notes the command the person runs: the prompt that follows
15//                  may be its command turn (core/commands.ts)
16//
17// The core owns the unmatched registration of these events; a feature always
18// registers them with a matcher (DEVELOPMENT.md, 开发).
19//
20// Switched off (`/dp off`, core/switches.ts) the core stands down: prompt.submit
21// asks nothing and turn.step sends every step as the engine made it.
22
23import type { HttpInit, On } from 'claude-code'
24import { messageText } from '../decision/context.ts'
25import { EFFORT_PART } from '../decision/effort.ts'
26import { askGroups, type AskIo } from './ask-group.ts'
27import { collect, type Contribution } from './ballot.ts'
28import { forgetCommand, noteCommand, typedCommand } from './commands.ts'
29import { noteBlocked } from './outcomes.ts'
30import { newTurn, planStep, replace, takePending, turnKey, type Cell, type PendingDecision } from './plans.ts'
31import type { Ctx } from './setup.ts'
32import { reportStep, type StepIo } from './report.ts'
33import { masterOn } from './switches.ts'
34
35const PENDING = { plugin: 'dispatch-pilot', key: 'pending' } as const
36const TURNS = { plugin: 'dispatch-pilot', key: 'turns' } as const
37const AGENTS = { plugin: 'dispatch-pilot', key: 'agents' } as const
38const LOCK = { plugin: 'dispatch-pilot', key: 'lock' } as const
39const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
40const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
41const PPLX_RATE = { plugin: 'dispatch-pilot', key: 'pplxRate' } as const
42
43/** Prompts whose prompt.submit is letting them in right now: a turn that starts meanwhile is theirs. */
44const entering: string[] = []
45
46/** The prompt now being let in, when it is the only one: a turn that starts meanwhile is its (what a feature's `turn.start` takes its decision for). */
47export function enteringPrompt(): string | undefined {
48  return entering.length === 1 ? entering[0] : undefined
49}
50
51export function registerCore(on: On, ctx: Ctx): void {
52  on('prompt.submit', async ($, e, next) => {
53    // Every feature above has seen whether this is a command turn.
54    forgetCommand(e.text)
55    const ballot = collect(e.text)
56    // Switched off (/dp off): whatever was put in the ballot is not asked.
57    if (ballot.length === 0 || !masterOn()) return next(e)
58    const messages = ctx.config.context.messages > 0 ? await $.session.messages().catch(() => []) : []
59    const io: AskIo = {
60      backend: {
61        fetch: (url: string, init: HttpInit) => $.http.fetch(url, init),
62        sleep: (ms: number, signal: AbortSignal) => $.clock.sleep(ms, { signal }),
63        pace: { now: () => $.clock.now(), sentAt: { get: () => $.state.get(PPLX_RATE), set: (value, options) => $.state.set(PPLX_RATE, value, options) } },
64      },
65      now: () => $.clock.now(),
66      debug: (line) => $.ui.log(line, { to: 'debug' }),
67    }
68    // The main agent's effort goes in a request of its own (ADR 0005), the rest of the ballot in one. Both go out at once,
69    // with one wait (a long effort request makes it longer for both), each is answered or fails on its own, and each part
70    // reads the outcome of the request it was in.
71    const blocks = await askGroups(io, ctx, { prompt: e.text, messages, groups: requestGroups(ballot) })
72    entering.push(e.text)
73    try {
74      return await next(blocks.length > 0 ? { ...e, context: [...(e.context ?? []), ...blocks] } : e)
75    } finally {
76      const at = entering.indexOf(e.text)
77      if (at >= 0) entering.splice(at, 1)
78    }
79  })
80
81  on('command.run', async ($, e, next) => {
82    noteCommand(e)
83    return next(e)
84  })
85
86  on('turn.start', async ($, e, next) => {
87    // An agent's run is a turn of its own loop (2.1.299 on): no message of the person starts it, and none is its to take.
88    if (e.agentId !== undefined) return next(e)
89    const pending: Cell<PendingDecision[]> = { get: () => $.state.get(PENDING), set: (value, options) => $.state.set(PENDING, value, options) }
90    // A command turn starts with the engine's command message: the prompt was the command as typed.
91    const started = typedCommand(e.text) ?? e.text
92    // Its own prompt's decision: the prompt now entering (whatever an inner
93    // hook made of its text), else a queued prompt with the turn's text.
94    const entered = enteringPrompt()
95    const texts = entered === undefined ? [started] : [entered, started]
96    const { before } = await replace(pending, (list) => takePending(list ?? [], texts).rest)
97    // What the landed write took out of the list it found.
98    const own = takePending(before ?? [], texts).taken
99    // The turn's message as the decision model read it (later decisions about the turn reuse it). A pending
100    // entry, decided or not, says the person's own message started the turn (only such a turn is re-decided);
101    // one marked `report` says a report did (decided at its start, not re-decided).
102    const prompt = messageText(started, ctx.config.contextByKind.rejudge)
103    await $.state.set({ ...TURNS, id: turnKey(e.turnId, undefined) }, newTurn(prompt, own?.effort ?? null, own !== null && own.report !== true))
104    return next(e)
105  })
106
107  // Beneath every feature's tool.call: which calls a PreToolUse settings hook refused (the call itself then only
108  // sees an error), for the features that count failures and read a loop's steps (core/outcomes.ts).
109  on('classic.PreToolUse', async ($, e, next) => {
110    const decided = await next(e)
111    if (decided.deny !== undefined && e.tool_use_id) noteBlocked(e.tool_use_id)
112    return decided
113  })
114
115  on('turn.step', async function* ($, e, next) {
116    // Switched off (/dp off): every step goes out as the engine made it, lock or no lock.
117    if (!masterOn()) return yield* next(e)
118    const agentId = e.agentId
119    const { value: turn } = await $.state.get({ ...TURNS, id: turnKey(e.turnId, agentId) })
120    const { value: agent } = agentId === undefined ? { value: undefined } : await $.state.get({ ...AGENTS, id: agentId })
121    const { value: lock = null } = agentId === undefined ? await $.state.get(LOCK) : { value: null }
122    const { step, source } = planStep(e, { lock, turn, agent })
123    // What the step goes out with, for the board: every loop's, the main agent's included.
124    const io: StepIo = {
125      board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
126      decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
127      debug: (line) => $.ui.log(line, { to: 'debug' }),
128      now: () => $.clock.now(),
129      toast: (text) => $.ui.toast(text),
130      agents: () => $.agent.list(),
131    }
132    await reportStep(io, { ...(agentId === undefined ? {} : { agentId }), model: step.model, effort: step.effort, source })
133    return yield* next(step)
134  })
135}
136
137/**
138 * The requests a ballot goes out in: the main agent's effort question alone, every other part's together (the skills'
139 * question is the longest and sets a smaller state budget, so it cannot share a request with the effort question without
140 * cutting the conversation the effort question reads). A group no part is in is not made: no empty request.
141 */
142function requestGroups(ballot: readonly Contribution[]): Contribution[][] {
143  return [ballot.filter((part) => part.part === EFFORT_PART), ballot.filter((part) => part.part !== EFFORT_PART)].filter((group) => group.length > 0)
144}
145
hooks/core/loop-start.ts 62 lines
1// When a loop began (#62, spec #55; GLOSSARY 循环), kept in `$.state` under `loops` (types/index.d.ts): for the main agent the
2// `turn.start` of its latest turn, for a dispatched or Workflow agent its `agent.spawn`. The images work tells an image the loop
3// made from one that was there before it by a file's modification time against this moment, and two features read it:
4//
5//   - the screenshot takeover (#62) takes over the images whose files are `isFromLoop`;
6//   - the reference images of the routing (#64) are the files that are not (`startedBefore`).
7//
8// Recording it is not a feature and has no switch: it costs one `$.state.set` per loop. A reader asks for the loop of an agent
9// with `$.state.get({ plugin: 'dispatch-pilot', key: 'loops', id: agent })` (`MAIN` for the main agent), and gets
10// `{ startedAt }`, or nothing when no beginning was seen: it is then not known which files are older, and the reader leaves the
11// file as it is. (`validate` wants a state reference's plugin and key written as literals in the file that reads it, so a reader
12// declares `const LOOPS = { plugin: 'dispatch-pilot', key: 'loops' } as const` itself.) The state outlives a hot reload, which
13// resets the modules.
14
15import type { On } from 'claude-code'
16import { errorText } from '../decision/backend.ts'
17import { MAIN } from './plans.ts'
18
19/** The `$.state` family of the loops' beginnings, by loop: `main` or the agentId. */
20const LOOPS = { plugin: 'dispatch-pilot', key: 'loops' } as const
21
22/**
23 * Whether a file modified at `mtimeMs` (`$.fs.stat`) was made in the loop that began at `startedAt`. A file saved in the very
24 * millisecond the loop began counts as the loop's: only a file older than the beginning was there before it.
25 */
26export function isFromLoop(mtimeMs: number, startedAt: number): boolean {
27  return mtimeMs >= startedAt
28}
29
30/** The converse, for the reference images of a loop (#64): the file was modified before the loop began. */
31export function startedBefore(mtimeMs: number, startedAt: number): boolean {
32  return !isFromLoop(mtimeMs, startedAt)
33}
34
35export function registerLoopStart(on: On): void {
36  // A turn of the main agent starts its loop afresh. An agent's own run has a `turn.start` too (2.1.299 on), which only fills
37  // in for a spawn that was not seen: the spawn is the loop's beginning.
38  on('turn.start', { turnId: /(?:)/ }, async ($, e, next) => {
39    try {
40      const startedAt = await $.clock.now()
41      if (e.agentId === undefined) {
42        await $.state.set({ ...LOOPS, id: MAIN }, { startedAt })
43      } else if ((await $.state.get({ ...LOOPS, id: e.agentId })).value === undefined) {
44        await $.state.set({ ...LOOPS, id: e.agentId }, { startedAt })
45      }
46    } catch (error) {
47      $.ui.log(`loop start was not recorded: ${errorText(error)}`, { to: 'debug' })
48    }
49    return next(e)
50  })
51
52  // The beginning is the moment the spawn is raised (the agent's id is known once it returns); a resumed run is a loop of its own.
53  on('agent.spawn', { tool_use_id: /(?:)/ }, async ($, e, next) => {
54    const startedAt = await $.clock.now().catch(() => undefined)
55    const started = await next(e)
56    if (started.deny === undefined && startedAt !== undefined && started.agentId !== undefined) {
57      await $.state.set({ ...LOOPS, id: started.agentId }, { startedAt }).catch((error: unknown) => $.ui.log(`loop start was not recorded: ${errorText(error)}`, { to: 'debug' }))
58    }
59    return started
60  })
61}
62
hooks/core/report.ts 1296 lines
1// The decision report (「决定汇报」, ADR 0004): the one writer of what Dispatch
2// Pilot shows people. The board, the decision log, the debug log and the toasts
3// are all written here, from the same structured data in $.state
4// (types/index.d.ts: `board`, `decisionLog`, `skillProfiles`); the screens
5// (hooks/board/) only draw that data.
6//
7// Two entries, and nothing else, are for others to call:
8//
9//   report(io, what)        记一条决定: a feature (or a screen) hands over one
10//                           thing to show, tagged by its kind (`Reported`):
11//                           `decision`, a decision it made or why it could not
12//                           make one (which feature, about which agent, the
13//                           outcome, why, the rules' working when there is one:
14//                           the decision log, the agent's node, the debug log; a
15//                           route that failed raises a toast); `decisions`,
16//                           several of one event (the agent() calls of a
17//                           Workflow script: one write each, one toast at most);
18//                           `tally`, what a feature counts as a loop goes (the
19//                           mid-turn re-decisions, a loop's failed calls and
20//                           forced raises: on the agent's node); `switched`, the
21//                           person flipped the mod or a feature (`/dp`: the
22//                           screens draw again); `profiles`, how writing the
23//                           session's skill profiles goes (#33; core/profile-report.ts
24//                           has its data); `fellBack`, the decision model in use
25//                           is not the one asked for; `unplaced`, a pane the
26//                           person asked for that the surface did not place (a
27//                           toast); `unviewed`, a transcript the person asked
28//                           for from the pane that the engine did not show (a
29//                           toast). `io` is what that kind needs of the host
30//                           (`IoOf`): a `ReportIo` for most.
31//   reportStep(io, step)    记一步读数: the reading of one model request, the
32//                           model and effort an agent's step went out with,
33//                           whoever's loop it is. Only observes, never decides
34//                           anything (ADR 0003). The core calls it from its
35//                           `turn.step`, which knows what the step goes out with.
36//
37// The rest of a loop's life (spawned, ended) and the board's turn count the
38// module hears with hooks of its own (`registerReport`, which the entry file
39// registers first: `turn.start`, `agent.spawn`, `turn.complete`, changing nothing
40// in them); nobody calls those. What else is exported (`decisionLine`,
41// `callNodeId`, `unplacedText`, the types) only shapes or reads data.
42//
43// Pure but for those hooks: `$` stays in the hook owner's file (it may not cross
44// an import), so the caller builds its io of closures, a `ReportIo` as:
45//
46//   const io: ReportIo = {
47//     board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
48//     decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
49//     debug: (line) => $.ui.log(line, { to: 'debug' }),
50//     now: () => $.clock.now(),
51//     toast: (text) => $.ui.toast(text),
52//   }
53//
54// where `BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const` and
55// `DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const` are
56// the file's own literal refs (DEVELOPMENT.md, 开发). Neither entry ever
57// throws: a report that cannot be kept must not stop the decision or the step.
58
59import type { EngineInterface, On } from 'claude-code'
60import { errorText, failureLine, failureWords, type Failure } from '../decision/backend.ts'
61import { modelFamily, type AgentModel } from '../decision/dispatched-agent.ts'
62import { isEffort, type Effort } from '../decision/effort.ts'
63import type { BackendName } from './setup.ts'
64import type { UnresolvedChange, UnresolvedOption, UnresolvedThresholds } from '../decision/unresolved.ts'
65import type { CheckTally, VisualCheckRecord } from '../decision/visual-check-record.ts'
66import { fitsTemplate } from '../decision/workflow-labels.ts'
67import { type Cell, type EffortSource, update } from './plans.ts'
68import { masterOn } from './switches.ts'
69import { profilesAdvance, profilesBegin, profilesEntry, profilesLine, type ProfileEvent, type ProfilesState } from './profile-report.ts'
70
71export type { ProfileEvent, ProfilesState, ProfilesStop } from './profile-report.ts'
72
73const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
74const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
75
76// ---- the data (mirrors types/index.d.ts) --------------------------------------
77
78/** A model family, as a person says it (`/model`). */
79export type Model = AgentModel
80/** How a log entry reads: a decision made, a thing to watch, a failure, a plain record. */
81export type Tone = 'ok' | 'warn' | 'fail' | 'info'
82export type AgentState = 'queued' | 'running' | 'done' | 'failed'
83
84/** One step of the rules' working: its rule, whether it took effect, and the rule's own fields. */
85export type RuleStep = { rule: string; applied: boolean; [field: string]: string | number | boolean | null }
86
87/** A failed decision request, with the decision model that failed. */
88export type NodeFailure = Failure & { backend: string }
89
90/** One agent of one turn on the board. */
91export type BoardNode = {
92  turn: number
93  /**
94   * `main`, the agentId, or for a Workflow's agent not started yet the id of its call (`callNodeId`), for a
95   * Workflow not routed as a whole its tool call's id.
96   */
97  id: string
98  kind: 'main' | 'agent' | 'wf'
99  name: string
100  type: string
101  model?: Model
102  effort?: Effort | number
103  state: AgentState
104  t0: number
105  dur?: number
106  routed: boolean
107  locked?: true
108  why?: string
109  failure?: NodeFailure
110  decision?: number
111  /** The Workflow it belongs to (a Workflow agent, or the call of the script that stands for it before it starts). */
112  workflow?: { id: string; name: string }
113  /** The main agent's mid-turn re-decisions of the turn: steps made, decisions, level changes; `late`: an answer is not back, `failure`: the latest request failed. midturn-effort's. */
114  midturn?: { steps: number; judged: number; changed: number; late?: true; failure?: NodeFailure }
115  /** The failed tool calls, hook blocks and forced raises of the agent's loop (the escalation feature counts them); absent while none. */
116  counts?: { failed: number; blocked: number; raised: number; late?: true }
117  /** The agent's visual_check calls of the loop, counted by verdict (and the images the screenshot takeover kept from it, #62); absent while none. visual-check's. */
118  visualChecks?: CheckTally
119}
120
121/** What an agent's step read: its model by family and its effort as it went out (absent: a model without effort). */
122export type Reading = { model?: Model; effort?: Effort | number }
123
124/**
125 * The id of the node a Workflow call of a script stands on until its agent starts (an agent of a Workflow has no id
126 * before): `<tool_use_id>#<index>`, the Workflow tool call's own id and the call's place in the script.
127 */
128export function callNodeId(workflow: string, index: number): string {
129  return `${workflow}#${index}`
130}
131
132/** The Workflow tool call a call's node (`callNodeId`) belongs to; null for any other node. */
133export function callWorkflowOf(id: string): string | null {
134  const at = id.indexOf('#')
135  return at < 0 ? null : id.slice(0, at)
136}
137
138/** One reading that differed from the agent's previous one in the same turn (types/index.d.ts, `board.changes`). */
139export type ReadingChange = {
140  turn: number
141  id: string
142  /** Seconds from the start of `turn`. */
143  at: number
144  /** The `n` of the decision log's last entry when it was read. */
145  after: number
146  from: Reading
147  to: Reading
148}
149
150/**
151 * What a feature met beside an agent's route that is neither a decision nor the route itself, for the band's
152 * event stream (types/index.d.ts, `board.notes`): a request that failed (`failed`, `why` its words), one that
153 * gave nothing to use (`skipped`, `why` the Skip), an answer not back in time (`late`, `why` '').
154 */
155export type BoardNote = {
156  turn: number
157  /** `main`, or the agentId it was about. */
158  id: string
159  feature: string
160  /** Seconds from the start of `turn`. */
161  at: number
162  /** The `n` of the decision log's last entry when it was written. */
163  after: number
164  kind: 'failed' | 'skipped' | 'late'
165  why: string
166}
167
168export type Board = {
169  turn: number
170  /** When the latest turns started (`$.clock.now()`), by turn. */
171  starts?: { turn: number; at: number }[]
172  changes?: ReadingChange[]
173  notes?: BoardNote[]
174  nodes: BoardNode[]
175}
176
177/** The board keeps at most this many notes (those of the nodes' turns). */
178const NOTES_KEPT = 50
179
180/** One decision as the log keeps it. */
181export type LogEntry = {
182  n: number
183  turn: number
184  /** Seconds from the start of `turn` to when it was reported (0 for a decision made before its turn started); absent in an entry an earlier version wrote. */
185  at?: number
186  feature: string
187  agent?: string
188  tone: Tone
189  outcome: string
190  subject: string
191  reason: string
192  probs?: Record<Effort, number>
193  conf?: number
194  trace?: RuleStep[]
195  floor?: { from: Effort; to: Effort; model: Model }
196  /** The model (by family) and effort an agent was decided to run with (the main agent: its effort only); the agent's node says what its steps went out with. */
197  model?: Model
198  effort?: Effort
199  mid?: { current: Effort; picked: Effort; result: Effort; threshold?: number; held?: string; remaining?: number }
200  forced?: ForcedRaise
201  skills?: SkillsPicked
202  counts?: { failed: number; blocked: number; raised: number }
203  /** A Workflow call's decision that was sent back to the main agent to write in (return mode). */
204  sentBack?: true
205  /** The complexity reading of the reference images that went into this decision's request (#63). */
206  reference?: ReferenceRecord
207  /** An unresolved-count judgement (`unresolved`). */
208  unresolved?: UnresolvedRecord
209  /** The strong hint was given with this decision's request (#41). */
210  hint?: HintRecord
211  /** A visual_check call (#58): its checks and their verdicts, whether the zoomed re-check was done, how long it took. */
212  visualCheck?: VisualCheckRecord
213  /** An entry of feature `decision-model`: which requests the fallback is about, the ones that decide (`text`) or the ones with images (`images`). */
214  fallbackFor?: 'text' | 'images'
215}
216
217/** What the reference images a request came with read as (`decision/complexity.ts`): the level, 0 (trivial) to 4 (very complex), and how many images it came from. */
218export type ReferenceRecord = { level: number; images: number }
219
220/** The strong hint given with a request: the count it was given at, the setting it had reached, and `mid` when it was a mid-turn re-decision's. */
221/**
222 * A strong hint given: the count and the setting it reached; `where: 'mid'` for a mid-turn re-decision's. `used` (a message's):
223 * whether the hinted effort answer was the one taken (the message's own three-way answer said still unresolved); false: the plain one was.
224 */
225export type HintRecord = { count: number; maxAfter: number; where?: 'mid'; used?: boolean }
226
227/**
228 * What one message's answer to the unresolved question did to the count: the count before and after, the change, the
229 * option the answer leaned to most and every option's probability, the backend's confidence (on record only), and
230 * the two bars it was held to. The card draws it as it is; nothing is worked out again (ADR 0004).
231 */
232export type UnresolvedRecord = {
233  before: number
234  count: number
235  change: UnresolvedChange
236  top: UnresolvedOption
237  probs: Record<UnresolvedOption, number>
238  conf?: number
239  thresholds: UnresolvedThresholds
240}
241
242/** A raise the failures forced: the level (or, for a haiku agent, the model) it went from and to, and the level it holds the agent at least at. */
243export type ForcedRaise = { kind: 'effort' | 'model'; from: string; to: string; floor?: Effort }
244
245/** The skills a message (or a find_skill call) got: those suggested to the main agent, and those only the person can start (「可试 /x」), each with its relevance. */
246export type SkillsPicked = { suggest: { name: string; relevance: number }[]; try: { name: string; relevance: number }[] }
247
248/** The log keeps the entries of this many latest turns, and at most `LOG_ENTRIES` of them. */
249const LOG_TURNS = 20
250export const LOG_ENTRIES = 300
251
252// ---- what a feature hands over ------------------------------------------------
253
254/** What every report says of who it is about. */
255type About = {
256  /** The feature's switch name; a report's decision adds ` (agent report)`. */
257  feature: string
258  /** `main`, or the agentId of the dispatched or Workflow agent. */
259  agent: string
260  /**
261   * `next`: made before the turn it is for has started (at `prompt.submit`, for a message that will start
262   * the turn), so it belongs to the turn to come; `current` (the default): the turn running now.
263   */
264  forTurn?: 'current' | 'next'
265  /** What it was about, for the log: the start of the message, an agent's label. */
266  subject?: string
267  /**
268   * How to start the agent's node when the board has none yet (the main agent's is known). `state`: `running` by
269   * default, `queued` for a decision made for a turn to come or for a Workflow call whose agent has not started.
270   * `workflow`: the Workflow the agent (or its call) belongs to.
271   */
272  node?: { kind: 'agent' | 'wf'; name: string; type: string; state?: AgentState; workflow?: { id: string; name: string } }
273  /** Whether it left the agent routed (a decision) or not (a failure): the node's `routed`. Left as it is when not given. */
274  routed?: boolean
275  /**
276   * The id of the node that stood for this agent before it started (a Workflow call, queued): the agent's node
277   * takes its place, and the decision made for the call (its `decision` link), when it has one.
278   */
279  replaces?: string
280  /**
281   * A decision beside the agent's route (a mid-turn re-decision, a forced raise, a skill suggestion): in the log,
282   * and not on the agent's node (its `decision` link, `routed` and `why` stay the route's).
283   */
284  aside?: true
285}
286
287/** A decision made. */
288export type Decided = About & {
289  /** What was decided, in a few words: `effort high`. */
290  outcome: string
291  /** Why: what the decision model said, the rule that applied. */
292  reason: string
293  tone?: Tone
294  probs?: Record<Effort, number>
295  conf?: number
296  trace?: RuleStep[]
297  floor?: LogEntry['floor']
298  mid?: LogEntry['mid']
299  /** The model (by family) and the effort it decided for an agent: in the log entry, since the node's own are what its steps read. */
300  model?: Model
301  effort?: Effort
302  /** A Workflow call's decision that was sent back to the main agent to write in (return mode). */
303  sentBack?: true
304  forced?: ForcedRaise
305  skills?: SkillsPicked
306  counts?: LogEntry['counts']
307  reference?: ReferenceRecord
308  unresolved?: UnresolvedRecord
309  hint?: HintRecord
310  /** A visual_check call: what was checked, the verdicts, the times (#58). */
311  visualCheck?: VisualCheckRecord
312}
313
314/** A decision the feature could not make: the decision request failed. Not an entry of the log; it says why on the agent's node. */
315export type NotDecided = About & { failure: NodeFailure }
316
317/**
318 * No decision was asked for, or none could be made without a failed request: why the agent (or the Workflow) runs
319 * as it was written, in a few words, on its node. Not a log entry. `offBoard`: nothing to show at all, so nothing is
320 * written (a script with no agent() call).
321 */
322export type Left = About & { why: string; offBoard?: true }
323
324/**
325 * An agent whose decision was made earlier, for its call, has started: the agent is on the board as the one the
326 * decision routed. Not a log entry (the decision is, since it was made).
327 */
328export type Started = About & { started: true }
329
330/**
331 * Why a feature that was asked for something said nothing, when that is neither a decision nor a failed request:
332 * the answer said nothing about the skills (`unanswered`), the session's skills could not be read (`unread`),
333 * there was no skill to rate (`none`), an error of the mod's own (`error`; the debug log has it). Not in the log and
334 * on no node: a note on the board (`board.notes`, kind `skipped`), which the band's event stream draws.
335 */
336export type Skip = 'unanswered' | 'unread' | 'none' | 'error'
337export type Skipped = About & { skipped: Skip; aside: true }
338
339export type ReportedDecision = Decided | NotDecided | Left | Started | Skipped
340
341/** What a feature counts as its loop goes (`report`'s `tally`), not a decision of its own. */
342export type Tallied =
343  /** The main agent's turn as the mid-turn re-decision sees it. `quiet`: not re-decided yet this turn (nothing to show). `late`: the answer for this step is not back; `failure`: its request failed. */
344  | { feature: 'midturn-effort'; agent: 'main'; steps: number; judged: number; changed: number; quiet: boolean; late?: true; failure?: NodeFailure }
345  /** A loop's failed tool calls, hook blocks and forced raises (all 0: none yet, as the main agent's at a new turn). */
346  | { feature: 'escalation'; agent: string; failed: number; blocked: number; raised: number; late?: true }
347  /**
348   * What a visual_check call found, to be added to its agent's count for the loop (#58): checks that passed, failed, got no
349   * verdict to trust; `takeovers`: images the screenshot takeover kept from the agent (#62). Unlike the two above these are
350   * the call's own numbers, not a running total: the board adds them to the node's.
351   */
352  | { feature: 'visual-check'; agent: string; passed: number; failed: number; unsure: number; takeovers?: number }
353
354/** What one model request went out with, as the core sends it. */
355type StepReading = {
356  /** Absent for the main agent. */
357  agentId?: string
358  /** The model id as sent. */
359  model: string
360  /** The effort as sent; absent for a model without effort. */
361  effort?: string | number
362  /** Where the effort came from: the person's lock, a plan, or the engine (not routed). */
363  source: EffortSource
364}
365
366/** An agent of the roster `$.agent.list()` answers, as far as a node needs it. */
367type RosterAgent = { id: string; name?: string; description: string; type: string }
368
369/**
370 * What the readings need beyond `ReportIo`: the roster of dispatched agents (a Workflow's agents have their nodes from
371 * their spawns). `stepIo($)` builds it.
372 */
373export type StepIo = ReportIo & {
374  /** `() => $.agent.list()`: dispatched agents only, a Workflow's are not in it. */
375  agents: () => Promise<readonly RosterAgent[]>
376}
377
378/** What the module needs of the host, as closures (see the top of the file). */
379export type ReportIo = {
380  board: Cell<Board>
381  decisions: Cell<LogEntry[]>
382  /** `(line) => $.ui.log(line, { to: 'debug' })` */
383  debug: (line: string) => void
384  /** `() => $.clock.now()`: when a decision, a reading or a note is reported. */
385  now: () => Promise<number>
386  /** The host's toast, as `toast: (text) => $.ui.toast(text)`: a route that failed. */
387  toast: (text: string) => void
388}
389
390// ---- entry one (记一条决定): what a feature hands over ----------------------------
391
392/** What `report` is handed, one kind at a time (see the top of the file). */
393export type Reported =
394  /** A decision made, or why none was (`ReportedDecision`). */
395  | { decision: ReportedDecision }
396  /** The decisions of one event, in the order made: one write to the log and one to the board, at most one toast. */
397  | { decisions: readonly ReportedDecision[] }
398  /** What a feature counts as a loop goes (`Tallied`). */
399  | { tally: Tallied }
400  /** The person flipped the mod or a feature (`/dp`). */
401  | { switched: true }
402  /** How writing the session's skill profiles goes (`ProfileEvent`). */
403  | { profiles: ProfileEvent }
404  /** The decision model in use is not the one asked for: no Perplexity key, so Jev (`DecisionModelEvent`). */
405  | { fellBack: DecisionModelEvent }
406  /** A pane the person asked for (a digit on the band) that the surface did not place, with the surface's reason; it was closed again. */
407  | { unplaced: { reason: string } }
408  /** A transcript the person asked for from the pane (an agent's, or the main one back: `agent` null) that the engine did not show, with its reason. */
409  | { unviewed: { agent: string | null; reason: string } }
410
411/** What a toast of its own needs of the host: the debug log, the clock and the toast. */
412export type NoticeIo = Pick<ReportIo, 'debug' | 'now' | 'toast'>
413
414/** What the decision model's fallback needs of the host: the board (for the turn), the decision log and the debug log. */
415export type DecisionModelIo = Pick<ReportIo, 'board' | 'decisions' | 'debug'>
416
417/** The host closures each kind of report needs: a switch only the redraw, the skill profiles their own state, a pane not placed the toast, the rest a `ReportIo`. */
418type IoOf<R extends Reported> = R extends { switched: true }
419  ? SwitchIo
420  : R extends { profiles: ProfileEvent }
421    ? ProfilesIo
422    : R extends { fellBack: DecisionModelEvent }
423      ? DecisionModelIo
424      : R extends { unplaced: unknown } | { unviewed: unknown }
425        ? NoticeIo
426        : ReportIo
427
428/**
429 * Entry one (记一条决定): reports what a feature hands over, by its kind; `io` is what that kind needs of the host
430 * (`IoOf`). Never throws.
431 */
432export async function report<R extends Reported>(io: IoOf<R>, what: R): Promise<void> {
433  const item: Reported = what
434  if ('decision' in item) return reportDecisions(io as ReportIo, [item.decision])
435  if ('decisions' in item) return reportDecisions(io as ReportIo, item.decisions)
436  if ('tally' in item) return reportTally(io as ReportIo, item.tally)
437  if ('switched' in item) return reportSwitch(io as SwitchIo)
438  if ('profiles' in item) return reportProfiles(io as ProfilesIo, item.profiles)
439  if ('fellBack' in item) return reportFellBack(io as DecisionModelIo, item.fellBack)
440  if ('unviewed' in item) return reportUnviewed(io as NoticeIo, item.unviewed)
441  return reportUnplaced(io as NoticeIo, item.unplaced)
442}
443
444/** A transcript the pane asked for and the engine did not show: the debug line and a toast with the engine's reason. Never throws. */
445async function reportUnviewed(io: NoticeIo, unviewed: { agent: string | null; reason: string }): Promise<void> {
446  try {
447    io.debug(`transcript of ${unviewed.agent ?? 'main'} not shown: ${unviewed.reason}`)
448    toastOnce(io, await io.now(), unviewed.agent === null ? `没能回到主对话:${unviewed.reason}` : `没能打开这个 agent 的对话:${unviewed.reason}`)
449  } catch {
450    // a notice that cannot be given leaves the view as it is
451  }
452}
453
454/** The rationale pane was not placed, in the person's words: why (the surface's own reason), and where to look instead. */
455export function unplacedText(reason: string): string {
456  return `依据面板没有放出来(${reason}),已经关上;/dp log 10 在对话里列出最近 10 条决定`
457}
458
459/**
460 * A pane the person asked for that the surface did not place: the debug line, and a toast so they know (the `/dp`
461 * command says it in its answer instead), unless a toast went up within `TOAST_GAP_MS`. Never throws.
462 */
463async function reportUnplaced(io: NoticeIo, unplaced: { reason: string }): Promise<void> {
464  try {
465    io.debug(`rationale pane not placed (${unplaced.reason}), closed again`)
466    toastOnce(io, await io.now(), unplacedText(unplaced.reason))
467  } catch {
468    // a notice that cannot be given leaves the pane closed all the same
469  }
470}
471
472/**
473 * The decisions of one event (a single one, or the several agents of a Workflow): the debug log line and the
474 * decision log entry of each decision made, the agents' nodes on the board, a note for the band when a request
475 * beside a route came to nothing, and a toast when a route failed. One write to the log, one to the board, at
476 * most one toast; each is what it would make of it alone, in the order given. Never throws.
477 */
478async function reportDecisions(io: ReportIo, decisions: readonly ReportedDecision[]): Promise<void> {
479  if (decisions.length === 0) return
480  try {
481    // Which turn each is for. A board that cannot be read does not stop a decision from being logged (as turn 1).
482    let unread = false
483    const board = await read(io.board).catch((error: unknown) => {
484      io.debug(`board not read: ${errorText(error)}`)
485      unread = true
486      return EMPTY
487    })
488    const now = await io.now()
489    const turnOf = (decision: ReportedDecision) => Math.max(unread ? 1 : 0, board.turn + (decision.forTurn === 'next' ? 1 : 0))
490    const made = decisions.filter(isDecided)
491    for (const decision of made) io.debug(decisionLine(decision))
492    // The number of each decision in the log, in the order made.
493    const numbers: number[] = []
494    if (made.length > 0) {
495      try {
496        await update(io.decisions, (list) => {
497          numbers.length = 0
498          let all = list ?? []
499          for (const decision of made) {
500            all = appendEntry(all, entryOf(decision, turnOf(decision), elapsed(board, turnOf(decision), now)))
501            numbers.push(all.at(-1)?.n ?? 0)
502          }
503          return all
504        })
505      } catch (error) {
506        numbers.length = 0
507        io.debug(`decision not kept for /dp log: ${errorText(error)}`)
508      }
509    }
510    // A request beside the route that came to nothing: a note for the band's event stream, after the log's last entry.
511    const noted = decisions.filter((decision): decision is Skipped | (NotDecided & { aside: true }) => 'skipped' in decision || ('failure' in decision && decision.aside === true))
512    const logged = noted.length === 0 ? 0 : (numbers.at(-1) ?? (await lastLogged(io)))
513    const notes = noted.map((decision): BoardNote => {
514      const of = { turn: turnOf(decision), id: decision.agent, feature: decision.feature, at: elapsed(board, turnOf(decision), now), after: logged }
515      return 'skipped' in decision ? { ...of, kind: 'skipped', why: decision.skipped } : { ...of, kind: 'failed', why: failureLine(decision.failure.backend, decision.failure) }
516    })
517    let after = board
518    // A decision beside the agent's route is not on its node; a Workflow with nothing to show is not on the board.
519    const onBoard = (decision: ReportedDecision) => decision.aside !== true && !('skipped' in decision) && !('offBoard' in decision)
520    if (decisions.some(onBoard) || notes.length > 0) {
521      try {
522        after = await update(io.board, (current) => {
523          let next = current ?? EMPTY
524          let at = 0
525          for (const decision of decisions) {
526            const n = isDecided(decision) ? numbers[at++] : undefined
527            if (onBoard(decision)) next = withNode(next, turnOf(decision), decision as Decided | NotDecided | Left | Started, n)
528          }
529          return notes.length === 0 ? next : withNotes(next, notes)
530        })
531      } catch (error) {
532        io.debug(`decision not kept on the board: ${errorText(error)}`)
533      }
534    }
535    // The routes that failed: a toast, so the person notices; the board says the rest.
536    const failed = decisions.filter((decision): decision is NotDecided => 'failure' in decision && decision.aside !== true)
537    if (failed.length > 0) toastOnce(io, now, failedText(failed, after, turnOf))
538  } catch (error) {
539    io.debug(`decision not reported: ${errorText(error)}`)
540  }
541}
542
543/** A decision that was made (the others say why there is none, or that an agent started). */
544function isDecided(decision: ReportedDecision): decision is Decided {
545  return 'outcome' in decision
546}
547
548/** The `n` of the decision log's last entry (0: none, or the log cannot be read). */
549async function lastLogged(io: ReportIo): Promise<number> {
550  try {
551    return ((await io.decisions.get()).value ?? []).at(-1)?.n ?? 0
552  } catch {
553    return 0
554  }
555}
556
557/** The engine drops a plugin's second toast within this many milliseconds of its last one (measured on 2.1.289). */
558const TOAST_GAP_MS = 2000
559
560/** When the last toast was raised (module state: a hot reload forgets it, and the next toast may then be one the engine drops). */
561let toastedAt = Number.NEGATIVE_INFINITY
562
563/**
564 * Raises the toast unless one was raised within `TOAST_GAP_MS`, which the engine would drop: the failures that
565 * follow one closely are on the board all the same.
566 */
567function toastOnce(io: Pick<ReportIo, 'toast'>, now: number, text: string): void {
568  if (now - toastedAt < TOAST_GAP_MS) return
569  toastedAt = now
570  try {
571    io.toast(text)
572  } catch {
573    // a toast that cannot be shown is skipped: the board has it
574  }
575}
576
577/** The toast for the routes of one event that failed: who is not routed, and why (the first failure's words, then its details). */
578function failedText(failed: readonly NotDecided[], board: Board, turnOf: (decision: ReportedDecision) => number): string {
579  const first = failed[0] as NotDecided
580  const why = `${failureWords(first.failure)}(${failureLine(first.failure.backend, first.failure)})`
581  if (failed.length > 1) return `${failed.length} 个 agent 未路由:${why}`
582  if (first.agent === 'main') return `主 agent 未路由:${why}`
583  const name = board.nodes.find((node) => node.turn === turnOf(first) && node.id === first.agent)?.name ?? first.node?.name ?? first.agent
584  return `「${name.length > 24 ? `${name.slice(0, 23)}…` : name}」未路由:${why}`
585}
586
587/** The board with the notes added: those of turns older than the nodes' dropped, and the oldest past `NOTES_KEPT`. */
588function withNotes(board: Board, notes: readonly BoardNote[]): Board {
589  return { ...board, notes: [...(board.notes ?? []), ...notes].filter((note) => note.turn >= board.turn - 1).slice(-NOTES_KEPT) }
590}
591
592// ---- entry two (记一步读数): a step's reading ----------------------------------------
593
594/** How many writes may be lost to other writers in a row: a Workflow's agents step within milliseconds of each other. */
595const READING_ATTEMPTS = 32
596
597/**
598 * Entry two (记一步读数): reports the reading of one step, the model (by family) and the effort it
599 * went out with, whether the effort was routed, and that the agent is running.
600 * Reading never changes what is sent. The agent's node is made at its first
601 * step when the board has none (named from the roster of dispatched agents; a
602 * Workflow's agent has its node from its spawn, and a loop neither knows is not
603 * an agent of the board), carries its start, and a reading that differs from
604 * the node's previous one adds a change event. Writes the board only when
605 * something is new. Never throws.
606 */
607export async function reportStep(io: StepIo, step: StepReading): Promise<void> {
608  const id = step.agentId ?? 'main'
609  const main = step.agentId === undefined
610  const family = modelFamily(step.model)
611  const effort = typeof step.effort === 'number' || isEffort(step.effort) ? step.effort : undefined
612  const reading: Reading = { ...(family === null ? {} : { model: family }), ...(effort === undefined ? {} : { effort }) }
613  // `source`: the engine's own effort goes out unless a plan sets it. An agent that was decided to run as it does has no plan
614  // to say so (a Workflow script was written into): its reading is checked against its decision below.
615  let routed = step.source !== 'engine'
616  const locked = step.source === 'locked'
617  try {
618    const now = await io.now()
619    const seen = main ? now : seenAt(id, now)
620    const peek = await read(io.board)
621    const before = main ? mainNode(peek) : continuing(peek, id)
622    // A node that has not begun is named now (the roster may know it only from here on); one that has keeps its name, and
623    // a Workflow's agent has its name from its spawn.
624    const identity = main || (before !== undefined && (begun(before) || before.kind === 'wf')) ? null : await lookUp(io, id)
625    if (!main && before === undefined && identity === null) return
626    const prior = main ? undefined : (before ?? callNodeOf(peek, identity))
627    if (!routed && prior?.routed === true && prior.decision !== undefined) routed = await wentOutAsDecided(io, prior.decision, reading)
628    const logged = before !== undefined && differs(before, reading) ? (((await io.decisions.get()).value ?? []).at(-1)?.n ?? 0) : 0
629    await modify(
630      io.board,
631      (current) => {
632        const board = current ?? EMPTY
633        const old = main ? mainNode(board) : continuing(board, id)
634        if (old === undefined && identity === null && !main) return undefined
635        const turn = old?.turn ?? board.turn
636        const started = old !== undefined && begun(old)
637        // A Workflow's agent that starts takes the place of the node its call stood for, and what was decided for it.
638        const stood = old === undefined && !main ? callNodeOf(board, identity) : undefined
639        // A node made before its first step (a spawn, a decision) that now goes out routed has nothing left to say of why it would not be.
640        const made = old !== undefined && !started && routed ? without(old, 'why', 'failure') : old
641        const base = made ?? { ...newNode(turn, id, identity ?? undefined, 'running'), ...carriedFrom(stood, routed) }
642        const named = identity !== null && !started ? { kind: identity.kind, name: identity.name, type: identity.type } : {}
643        const next: BoardNode = {
644          ...without(base, 'model', 'effort', 'locked', 'dur'),
645          ...named,
646          state: 'running',
647          t0: main ? 0 : started ? base.t0 : elapsed(board, turn, seen),
648          routed,
649          ...reading,
650          ...(locked ? { locked: true as const } : {}),
651        }
652        const changes = old !== undefined && differs(old, reading) ? [{ turn, id, at: elapsed(board, turn, now), after: logged, from: readingOf(old), to: reading }] : []
653        if (old !== undefined && changes.length === 0 && JSON.stringify(old) === JSON.stringify(next)) return undefined
654        return {
655          ...board,
656          ...(changes.length === 0 ? {} : { changes: [...(board.changes ?? []), ...changes].filter((change) => change.turn >= board.turn - 1) }),
657          nodes: takenOver(board.nodes, old, stood, next),
658        }
659      },
660      READING_ATTEMPTS,
661    )
662    if (!main) firstSeen.delete(id)
663  } catch (error) {
664    io.debug(`reading not kept on the board: ${errorText(error)}`)
665  }
666}
667
668/** Why an agent's turn did not end in an answer, in the board's words (a node's `why` when it failed and nothing else said). */
669export const ENDED_WORDS = { error: '出错', refusal: '拒绝回答', aborted: '被中断' } as const
670
671/** How a loop's turn ended (`turn.complete`). */
672type LoopEnd = { agentId?: string; reason: 'answer' | 'aborted' | 'refusal' | 'error'; durationMs: number }
673
674/**
675 * Reports the end of a loop's turn: done after an answer, else failed (and
676 * why, when nothing else said), for as long as it ran. The main agent's turn
677 * ends its own node; an agent's, its own, wherever its turn's node is. Never throws.
678 */
679async function reportEnd(io: StepIo, end: LoopEnd): Promise<void> {
680  const id = end.agentId ?? 'main'
681  const main = end.agentId === undefined
682  try {
683    const now = await io.now()
684    const peek = await read(io.board)
685    const known = main ? mainNode(peek) : continuing(peek, id)
686    // The loop is over: whatever its steps missed, it is looked up once more in full.
687    missed.delete(id)
688    const identity = main || known !== undefined ? null : await identify(io, id)
689    if (!main && known === undefined && identity === null) return
690    const seen = main || known !== undefined ? now : (firstSeen.get(id) ?? now - end.durationMs)
691    await modify(
692      io.board,
693      (current) => {
694        const board = current ?? EMPTY
695        const old = main ? mainNode(board) : continuing(board, id)
696        if (old === undefined && identity === null && !main) return undefined
697        const turn = old?.turn ?? board.turn
698        const stood = old === undefined && !main ? callNodeOf(board, identity) : undefined
699        const base = old ?? { ...newNode(turn, id, identity ?? undefined, 'running'), ...carriedFrom(stood, true) }
700        const { reason } = end
701        const next: BoardNode = {
702          ...base,
703          ...(old === undefined && !main ? { t0: elapsed(board, turn, seen) } : {}),
704          state: reason === 'answer' ? 'done' : 'failed',
705          dur: Math.round(end.durationMs) / 1000,
706          ...(reason !== 'answer' && base.why === undefined ? { why: ENDED_WORDS[reason] } : {}),
707        }
708        return { ...board, nodes: takenOver(board.nodes, old, stood, next) }
709      },
710      READING_ATTEMPTS,
711    )
712    if (!main) firstSeen.delete(id)
713  } catch (error) {
714    io.debug(`end of loop not kept on the board: ${errorText(error)}`)
715  }
716}
717
718/**
719 * Reports an agent started: queued until its first step. Its node is made (or,
720 * when a decision about it made one, marked queued from now); the agent's own
721 * first step starts it. A Workflow's agent (`workflow`: the Workflow tool
722 * call's id) is called by its label, and takes the place of the node its call
723 * stood for. Never throws.
724 */
725async function reportSpawn(io: StepIo, spawn: { agentId: string; name?: string; description: string; type: string; workflow?: string }): Promise<void> {
726  try {
727    const now = await io.now()
728    const identity: Identity =
729      spawn.workflow === undefined
730        ? { kind: 'agent', name: nameOf(spawn.name, spawn.description, spawn.agentId), type: spawn.type }
731        : { kind: 'wf', name: nameOf(undefined, spawn.description, spawn.agentId), type: 'workflow' }
732    await modify(
733      io.board,
734      (current) => {
735        const board = current ?? EMPTY
736        const old = continuing(board, spawn.agentId)
737        if (old !== undefined && begun(old)) return undefined
738        const turn = old?.turn ?? board.turn
739        const stood = old === undefined ? callNodeOf(board, identity, spawn.workflow) : undefined
740        // Routed as its call was: its first step is checked against the call's decision.
741        const base = old ?? { ...newNode(turn, spawn.agentId, identity, 'queued'), ...carriedFrom(stood, false), routed: stood?.routed ?? false }
742        const next: BoardNode = { ...base, state: 'queued', t0: elapsed(board, turn, now) }
743        return { ...board, nodes: takenOver(board.nodes, old, stood, next) }
744      },
745      READING_ATTEMPTS,
746    )
747  } catch (error) {
748    io.debug(`agent not kept on the board: ${errorText(error)}`)
749  }
750}
751
752// ---- what `report` does with a tally --------------------------------------------
753
754/**
755 * Reports what a feature counts as its loop goes, which is no decision: the
756 * mid-turn re-decision's steps, decisions and changes of the main agent's
757 * turn, and each loop's failed tool calls and forced raises. On the agent's
758 * node of the current turn (`midturn`, `counts`); an answer that is late, or a
759 * re-decision's request that failed, is also a note for the band's event
760 * stream. Writes the board only when the node changed. Never throws.
761 */
762async function reportTally(io: ReportIo, tally: Tallied): Promise<void> {
763  try {
764    const noteworthy = ('late' in tally && tally.late === true) || ('failure' in tally && tally.failure !== undefined)
765    const now = await io.now()
766    const logged = noteworthy ? await lastLogged(io) : 0
767    await modify(io.board, (current) => withTally(current ?? EMPTY, tally, { now, logged }))
768  } catch (error) {
769    io.debug(`tally not kept on the board: ${errorText(error)}`)
770  }
771}
772
773// ---- what `report` does with a switch -------------------------------------------
774
775/** What a switch needs of the host: `() => $.ui.invalidate('ui.render')`, the screens drawn again. */
776export type SwitchIo = { redraw: () => void }
777
778/**
779 * Reports a switch the person flipped (the control feature's `/dp`). The board
780 * and the decision log keep what they hold: the screens read the switches as
781 * they draw, and leave out what a feature that is off owns (its decisions, the
782 * parts of the nodes it writes, `defineSwitch`'s `parts`), so they are drawn
783 * again now. Never throws.
784 */
785function reportSwitch(io: SwitchIo): void {
786  try {
787    io.redraw()
788  } catch {
789    // a redraw that cannot be asked for waits for the next change of the board
790  }
791}
792
793/**
794 * The board with the tally on its agent's node (the main agent's of the turn running, an agent's where its steps
795 * go on: `continuing`), and a note when an answer just went late or a request just failed; undefined when the
796 * node already says it, or there is nothing to say. A loop with no node is no agent of the board (the readings
797 * make nodes), the main agent's is made.
798 */
799function withTally(board: Board, tally: Tallied, when: { now: number; logged: number }): Board | undefined {
800  const main = tally.agent === 'main'
801  const old = main ? mainNode(board) : continuing(board, tally.agent)
802  if (old === undefined && !main) return undefined
803  let next: BoardNode
804  const notes: BoardNote[] = []
805  const note = (turn: number, kind: BoardNote['kind'], why: string) =>
806    notes.push({ turn, id: tally.agent, feature: tally.feature, at: elapsed(board, turn, when.now), after: when.logged, kind, why })
807  if (tally.feature === 'midturn-effort') {
808    if (tally.quiet) return undefined
809    const midturn = { steps: tally.steps, judged: tally.judged, changed: tally.changed, ...(tally.late === true ? { late: true as const } : {}), ...(tally.failure === undefined ? {} : { failure: tally.failure }) }
810    next = { ...(old ?? newNode(board.turn, tally.agent, undefined, 'running')), midturn }
811    if (tally.late === true && old?.midturn?.late !== true) note(next.turn, 'late', '')
812    if (tally.failure !== undefined && JSON.stringify(old?.midturn?.failure) !== JSON.stringify(tally.failure)) note(next.turn, 'failed', failureLine(tally.failure.backend, tally.failure))
813  } else if (tally.feature === 'visual-check') {
814    const added = tally.passed + tally.failed + tally.unsure + (tally.takeovers ?? 0)
815    if (added === 0) return undefined
816    const was = old?.visualChecks
817    const takeovers = (was?.takeovers ?? 0) + (tally.takeovers ?? 0)
818    const visualChecks = { passed: (was?.passed ?? 0) + tally.passed, failed: (was?.failed ?? 0) + tally.failed, unsure: (was?.unsure ?? 0) + tally.unsure, ...(takeovers > 0 ? { takeovers } : {}) }
819    next = { ...(old ?? newNode(board.turn, tally.agent, undefined, 'running')), visualChecks }
820  } else {
821    const any = tally.failed + tally.blocked + tally.raised > 0
822    if (old === undefined && !any) return undefined
823    const base = old ?? newNode(board.turn, tally.agent, undefined, 'running')
824    next = any
825      ? { ...base, counts: { failed: tally.failed, blocked: tally.blocked, raised: tally.raised, ...(tally.late === true ? { late: true as const } : {}) } }
826      : without(base, 'counts')
827    if (tally.late === true && old?.counts?.late !== true) note(next.turn, 'late', '')
828  }
829  if (old !== undefined && JSON.stringify(old) === JSON.stringify(next)) return undefined
830  const changed = { ...board, nodes: [...board.nodes.filter((node) => node !== old), next] }
831  return notes.length === 0 ? changed : withNotes(changed, notes)
832}
833
834/** What a dispatched agent is called on the board: its name, else its description, else its id. */
835function nameOf(name: string | undefined, description: string, id: string): string {
836  return name !== undefined && name !== '' ? name : description !== '' ? description : id
837}
838
839/** Who a loop with no node is, from what the engine says; null: not an agent the board shows. */
840type Identity = { kind: 'agent' | 'wf'; name: string; type: string }
841
842/** Who a loop is, by the roster; null when it is not there, or the roster cannot be read. */
843async function identify(io: StepIo, id: string): Promise<Identity | null> {
844  try {
845    const info = (await io.agents()).find((agent) => agent.id === id)
846    return info === undefined ? null : { kind: 'agent', name: nameOf(info.name, info.description, id), type: info.type }
847  } catch (error) {
848    io.debug(`agent roster not read: ${errorText(error)}`)
849    return null
850  }
851}
852
853/**
854 * The loops a step found no one to be, by id: how many of their steps have looked. Module state: a hot reload forgets
855 * it, and costs each such loop one look-up more.
856 */
857const missed = new Map<string, number>()
858const MISSED_KEPT = 64
859
860/**
861 * `identify` for a step, at most as often as the answer can change: the first step of a loop no one knows (an engine
862 * fork) reads the roster, and its later steps would read it again. After a miss, the roster is read again at the
863 * loop's 2nd, 4th, 8th... step (an agent it lists late).
864 */
865async function lookUp(io: StepIo, id: string): Promise<Identity | null> {
866  const sightings = (missed.get(id) ?? 0) + 1
867  const found = missed.get(id) === undefined || (sightings & (sightings - 1)) === 0 ? await identify(io, id) : null
868  // The newest miss goes last, so the oldest go first past `MISSED_KEPT`.
869  missed.delete(id)
870  if (found !== null) return found
871  missed.set(id, sightings)
872  for (const key of missed.keys()) if (missed.size > MISSED_KEPT) missed.delete(key)
873  return null
874}
875
876/**
877 * When a loop no node was made for was first seen (module state: a hot reload forgets it, and an agent only
878 * found later then starts at that step). An agent the roster lists late has its name from a later step, or from
879 * the end of its loop, and starts when it first stepped.
880 */
881const firstSeen = new Map<string, number>()
882const FIRST_SEEN_KEPT = 64
883
884function seenAt(id: string, now: number): number {
885  const seen = firstSeen.get(id)
886  if (seen !== undefined) return seen
887  firstSeen.set(id, now)
888  for (const key of firstSeen.keys()) if (firstSeen.size > FIRST_SEEN_KEPT) firstSeen.delete(key)
889  return now
890}
891
892/**
893 * The node a Workflow call of a script stands for before its agent starts (a decision was made for the call, or it
894 * was left as written): one of the Workflow's calls (of the Workflow `workflow`, when it is given), queued and called
895 * what the agent's label is; else one whose label is a template the agent's label fits (`verify:${b.id}` for
896 * `verify:st4`), queued or already started by another of its agents. Null when there is none, or the agent is not a
897 * Workflow's.
898 */
899function callNodeOf(board: Board, identity: Identity | null | undefined, workflow?: string): BoardNode | undefined {
900  if (identity === null || identity === undefined || identity.kind !== 'wf') return undefined
901  const calls = board.nodes.filter(
902    (node) => node.kind === 'wf' && node.workflow !== undefined && callWorkflowOf(node.id) === node.workflow.id && (workflow === undefined || node.workflow.id === workflow),
903  )
904  return (
905    calls.find((node) => node.state === 'queued' && node.name === identity.name) ??
906    calls.find((node) => (node.state === 'queued' || node.state === 'running') && fitsTemplate(node.name, identity.name))
907  )
908}
909
910/**
911 * The board's nodes once `next` takes the place of `old` (its own node before, if any) and of the call node it
912 * `stood` for. A call written as a template stands for every agent it starts: it stays, marked started (`running`),
913 * for the agents after this one, and the screens leave it out (`isCallNode`).
914 */
915function takenOver(nodes: readonly BoardNode[], old: BoardNode | undefined, stood: BoardNode | undefined, next: BoardNode): BoardNode[] {
916  const kept = stood !== undefined && stood.name.includes('${') ? { ...stood, state: 'running' as const } : undefined
917  return [...nodes.filter((node) => node !== old && node !== stood), ...(kept === undefined ? [] : [kept]), next]
918}
919
920/** What a Workflow's agent takes over from the node its call stood for: the Workflow, the decision made for it, and why it was left as written (when its steps go out unrouted). */
921function carriedFrom(stood: BoardNode | undefined, routed: boolean): Partial<BoardNode> {
922  if (stood === undefined) return {}
923  return {
924    ...(stood.workflow === undefined ? {} : { workflow: stood.workflow }),
925    ...(stood.decision === undefined ? {} : { decision: stood.decision }),
926    ...(routed || stood.why === undefined ? {} : { why: stood.why }),
927    ...(routed || stood.failure === undefined ? {} : { failure: stood.failure }),
928  }
929}
930
931/** Whether a reading is the model and effort the decision numbered `n` in the log decided for the agent (a decision that names none: no). */
932async function wentOutAsDecided(io: ReportIo, n: number, reading: Reading): Promise<boolean> {
933  try {
934    const entry = ((await io.decisions.get()).value ?? []).find((kept) => kept.n === n)
935    return entry?.model !== undefined && entry.model === reading.model && entry.effort === reading.effort
936  } catch {
937    return false
938  }
939}
940
941/** The main agent's node of the turn running. */
942function mainNode(board: Board): BoardNode | undefined {
943  return board.nodes.find((node) => node.turn === board.turn && node.id === 'main')
944}
945
946/**
947 * An agent's node that its steps go on in: its latest one, if it is of the turn
948 * running or has not ended (an agent still running when the next turn starts
949 * stays in the turn it began in); else it is a new row in this turn.
950 */
951function continuing(board: Board, id: string): BoardNode | undefined {
952  const latest = board.nodes.filter((node) => node.id === id).reduce<BoardNode | undefined>((best, node) => (best === undefined || node.turn >= best.turn ? node : best), undefined)
953  return latest !== undefined && (latest.turn === board.turn || latest.state === 'queued' || latest.state === 'running') ? latest : undefined
954}
955
956/** Whether the node has had a reading: its start is the first step's, and its name is settled. */
957function begun(node: BoardNode): boolean {
958  return node.state !== 'queued' && (node.id === 'main' || node.t0 > 0 || node.model !== undefined || node.effort !== undefined)
959}
960
961function readingOf(node: BoardNode): Reading {
962  return { ...(node.model === undefined ? {} : { model: node.model }), ...(node.effort === undefined ? {} : { effort: node.effort }) }
963}
964
965/** Whether the node has a previous reading, and it is not this one. */
966function differs(node: BoardNode, reading: Reading): boolean {
967  if (node.model === undefined && node.effort === undefined) return false
968  return node.model !== reading.model || node.effort !== reading.effort
969}
970
971/** Seconds from the start of `turn` to `ms` (0 when the turn's start is not known). */
972function elapsed(board: Board, turn: number, ms: number): number {
973  const start = board.starts?.find((kept) => kept.turn === turn)?.at
974  return start === undefined ? 0 : Math.max(0, Math.round(ms - start)) / 1000
975}
976
977// ---- the turn count and the loops' lifecycle ------------------------------------
978
979/**
980 * The board when a main turn starts at `now`: the count up by one, the nodes of older turns gone (the turn before it
981 * stays: it is folded into one line). A node still running or queued stays in its turn, with that turn's start, for as
982 * long as the log keeps its decisions (`LOG_TURNS`): a Workflow's agents, and its calls whose agents have not started,
983 * outlive the turn that launched it while the person goes on talking. A stopped Workflow's agents end (`turn.complete`,
984 * `aborted`); the calls of agents it never started stay queued until then, and the screens leave them out.
985 */
986function startTurn(board: Board | undefined, now: number): Board {
987  const turn = (board?.turn ?? 0) + 1
988  const kept = (of: number) => of >= turn - 1
989  // The main agent's turn is over when the next one starts, whatever its node says.
990  const live = (node: BoardNode) => node.id !== 'main' && (node.state === 'running' || node.state === 'queued') && node.turn > turn - LOG_TURNS
991  const nodes = (board?.nodes ?? []).filter((node) => kept(node.turn) || live(node))
992  return {
993    turn,
994    starts: [...(board?.starts ?? []).filter((start) => kept(start.turn) || nodes.some((node) => node.turn === start.turn)), { turn, at: now }],
995    ...(board?.changes === undefined ? {} : { changes: board.changes.filter((change) => kept(change.turn)) }),
996    ...(board?.notes === undefined ? {} : { notes: board.notes.filter((note) => kept(note.turn)) }),
997    nodes,
998  }
999}
1000
1001/**
1002 * What the module's own hooks need of the host, as closures over `$`. `$` is followed only into a function of
1003 * the same file, so the core builds its `StepIo` itself (core.ts, `turn.step`): keep the two alike.
1004 */
1005function stepIo($: EngineInterface): StepIo {
1006  return {
1007    board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
1008    decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
1009    debug: (line) => $.ui.log(line, { to: 'debug' }),
1010    now: () => $.clock.now(),
1011    toast: (text) => $.ui.toast(text),
1012    agents: () => $.agent.list(),
1013  }
1014}
1015
1016/**
1017 * The module's own hooks, which only watch (every event goes on as it is):
1018 * a main turn starting (the board's turn count and its start time), a
1019 * dispatched agent spawned (queued until its first step), a loop's turn ending
1020 * (its node done or failed). A board that cannot be kept never stops anything.
1021 */
1022export function registerReport(on: On): void {
1023  on('turn.start', { turnId: /(?:)/ }, async ($, e, next) => {
1024    // The board counts the main loop's turns; an agent's run is a turn of its own loop (2.1.299 on).
1025    if (e.agentId !== undefined) return next(e)
1026    try {
1027      const now = await $.clock.now()
1028      await update(stepIo($).board, (board) => startTurn(board, now))
1029    } catch {
1030      // the count is the board's own: a turn starts without it
1031    }
1032    return next(e)
1033  })
1034
1035  on('agent.spawn', { tool_use_id: /(?:)/ }, async ($, e, next) => {
1036    const result = await next(e)
1037    if (result.deny !== undefined || result.agentId === undefined) return result
1038    // A Workflow's agent is on the board, in its call's place, while Dispatch Pilot is on.
1039    if (e.workflow !== undefined && !masterOn()) return result
1040    await reportSpawn(stepIo($), {
1041      agentId: result.agentId,
1042      ...(e.name === undefined ? {} : { name: e.name }),
1043      description: e.description,
1044      type: e.subagentType,
1045      ...(e.workflow === undefined ? {} : { workflow: e.tool_use_id }),
1046    })
1047    return result
1048  })
1049
1050  on('turn.complete', { turnId: /(?:)/ }, async ($, e, next) => {
1051    const result = await next(e)
1052    await reportEnd(stepIo($), { ...(e.agentId === undefined ? {} : { agentId: e.agentId }), reason: e.reason, durationMs: e.durationMs })
1053    return result
1054  })
1055}
1056
1057// ---- the log ------------------------------------------------------------------
1058
1059/** A decision as one line: `effort high · "the message":why`. The debug log's line, and `/dp log N`'s after `#n feature:`. */
1060export function decisionLine(decision: { outcome: string; subject?: string; reason: string }): string {
1061  return `${decision.outcome}${decision.subject ? ` · ${decision.subject}` : ''}:${decision.reason}`
1062}
1063
1064/** The list with `entry` added last, numbered, the entries of turns older than the latest `LOG_TURNS` dropped, and then the oldest past `LOG_ENTRIES`. */
1065function appendEntry(list: readonly LogEntry[], entry: Omit<LogEntry, 'n'>): LogEntry[] {
1066  const all = [...list, { n: (list.at(-1)?.n ?? 0) + 1, ...entry }]
1067  const latest = Math.max(...all.map((kept) => kept.turn))
1068  return all.filter((kept) => kept.turn > latest - LOG_TURNS).slice(-LOG_ENTRIES)
1069}
1070
1071function entryOf(decision: Decided, turn: number, at: number): Omit<LogEntry, 'n'> {
1072  return {
1073    turn,
1074    at,
1075    feature: decision.feature,
1076    agent: decision.agent,
1077    tone: decision.tone ?? 'ok',
1078    outcome: decision.outcome,
1079    subject: decision.subject ?? '',
1080    reason: decision.reason,
1081    ...(decision.probs === undefined ? {} : { probs: decision.probs }),
1082    ...(decision.conf === undefined ? {} : { conf: decision.conf }),
1083    ...(decision.trace === undefined ? {} : { trace: decision.trace }),
1084    ...(decision.floor === undefined ? {} : { floor: decision.floor }),
1085    ...(decision.model === undefined ? {} : { model: decision.model }),
1086    ...(decision.effort === undefined ? {} : { effort: decision.effort }),
1087    ...(decision.mid === undefined ? {} : { mid: decision.mid }),
1088    ...(decision.forced === undefined ? {} : { forced: decision.forced }),
1089    ...(decision.skills === undefined ? {} : { skills: decision.skills }),
1090    ...(decision.counts === undefined ? {} : { counts: decision.counts }),
1091    ...(decision.reference === undefined ? {} : { reference: decision.reference }),
1092    ...(decision.unresolved === undefined ? {} : { unresolved: decision.unresolved }),
1093    ...(decision.hint === undefined ? {} : { hint: decision.hint }),
1094    ...(decision.visualCheck === undefined ? {} : { visualCheck: decision.visualCheck }),
1095    ...(decision.sentBack === true ? { sentBack: true as const } : {}),
1096  }
1097}
1098
1099// ---- the board ----------------------------------------------------------------
1100
1101const EMPTY: Board = { turn: 0, nodes: [] }
1102
1103function newNode(turn: number, id: string, node: About['node'], state: AgentState): BoardNode {
1104  if (id === 'main') return { turn, id, kind: 'main', name: '主 agent', type: 'main', state, t0: 0, routed: false }
1105  return { turn, id, kind: node?.kind ?? 'agent', name: node?.name ?? id, type: node?.type ?? 'agent', state: node?.state ?? state, t0: 0, routed: false, ...(node?.workflow === undefined ? {} : { workflow: node.workflow }) }
1106}
1107
1108/** The board with the decision on its agent's node of `turn` (the node made when there is none), `n` the decision's number in the log when it has one. */
1109function withNode(board: Board, turn: number, decision: Decided | NotDecided | Left | Started, n: number | undefined): Board {
1110  const old = board.nodes.find((node) => node.turn === turn && node.id === decision.agent)
1111  const late = old === undefined ? lateCall(board, turn, decision, n) : undefined
1112  if (late !== undefined) return late
1113  // The node that stood for the agent before it started gives it what was decided for it, and goes (a template's stays, started).
1114  const stood = old === undefined && decision.replaces !== undefined ? board.nodes.find((node) => node.id === decision.replaces) : undefined
1115  const inherited = stood?.decision === undefined ? {} : { decision: stood.decision }
1116  const base = old ?? { ...newNode(turn, decision.agent, decision.node, decision.forTurn === 'next' ? 'queued' : 'running'), ...inherited }
1117  return { ...board, nodes: takenOver(board.nodes, old, stood, decided(base, decision, n)) }
1118}
1119
1120/** `base` with the decision on it: what was decided and whether it routed, or why not. */
1121function decided(base: BoardNode, decision: Decided | NotDecided | Left | Started, n: number | undefined): BoardNode {
1122  const routed = decision.routed === undefined ? {} : { routed: decision.routed }
1123  if ('failure' in decision) return { ...base, ...routed, why: failureLine(decision.failure.backend, decision.failure), failure: decision.failure }
1124  if ('why' in decision) return { ...without(base, 'failure'), routed: false, why: decision.why }
1125  if ('started' in decision) return { ...without(base, 'why', 'failure'), routed: true, state: 'running' }
1126  return {
1127    ...(decision.routed === true ? without(base, 'why', 'failure') : base),
1128    ...routed,
1129    ...(n === undefined ? {} : { decision: n }),
1130  }
1131}
1132
1133/**
1134 * The board once a Workflow call's decision reaches it after the call's agents have started, undefined when none has:
1135 * the engine spawns a run's first agents before the Workflow tool returns (2.1.302), and workflow-agents reports its
1136 * calls after it does, so an agent can be on the board, named by its label, before its call. Each such agent of this
1137 * turn (one not yet of any Workflow, nor decided, called what the call is or fitting its template) takes the decision
1138 * and the Workflow; the call waits on the board no more (a template's stays, started, for its agents to come).
1139 */
1140function lateCall(board: Board, turn: number, decision: Decided | NotDecided | Left | Started, n: number | undefined): Board | undefined {
1141  const node = decision.node
1142  if (callWorkflowOf(decision.agent) === null || node?.kind !== 'wf' || node.workflow === undefined) return undefined
1143  const started = board.nodes.filter(
1144    (one) =>
1145      one.turn === turn &&
1146      one.kind === 'wf' &&
1147      callWorkflowOf(one.id) === null &&
1148      one.workflow === undefined &&
1149      one.decision === undefined &&
1150      (one.state === 'queued' || one.state === 'running') &&
1151      (one.name === node.name || fitsTemplate(node.name, one.name)),
1152  )
1153  if (started.length === 0) return undefined
1154  const taken = new Map(started.map((one) => [one, { ...decided({ ...one, workflow: node.workflow }, decision, n), state: one.state }] as const))
1155  const nodes = board.nodes.map((one) => taken.get(one) ?? one)
1156  // A template's call stands for its agents still to come: started, so the screens leave it out (`isCallNode`).
1157  const template = node.name.includes('${') ? [decided({ ...newNode(turn, decision.agent, node, 'running'), state: 'running' }, decision, n)] : []
1158  return { ...board, nodes: [...nodes, ...template] }
1159}
1160
1161/** The value of a cell, or the empty board. */
1162async function read(cell: Cell<Board>): Promise<Board> {
1163  return (await cell.get()).value ?? EMPTY
1164}
1165
1166/** The turn a session start belongs to: the board's, and at least 1, where the first message will be (a board that cannot be read puts it there). */
1167async function sessionTurn(cell: Cell<Board>): Promise<number> {
1168  return Math.max(1, (await read(cell).catch(() => EMPTY)).turn)
1169}
1170
1171/** The list with `entry` in the place of the entry `same` finds, keeping its number; else added last. */
1172function replacingOrAppending(list: readonly LogEntry[], same: (kept: LogEntry) => boolean, entry: Omit<LogEntry, 'n'>): LogEntry[] {
1173  const at = list.findIndex(same)
1174  return at < 0 ? appendEntry(list, entry) : list.map((kept, i) => (i === at ? { n: kept.n, ...entry } : kept))
1175}
1176
1177/** `update` that writes only when `change` has something to write (it returns undefined when the value stands). */
1178async function modify<T>(cell: Cell<T>, change: (current: T | undefined) => T | undefined, attempts = 8): Promise<void> {
1179  for (let attempt = 0; attempt < attempts; attempt++) {
1180    const { value, version } = await cell.get()
1181    const next = change(value)
1182    if (next === undefined) return
1183    if ((await cell.set(next, { ifVersion: version })).isSet) return
1184  }
1185  throw new Error(`$.state write lost to other writers ${attempts} times in a row`)
1186}
1187
1188/** The object without these keys (a $.state value holds no `undefined`). */
1189function without<T extends object, K extends keyof T>(value: T, ...keys: K[]): Omit<T, K> {
1190  const rest = { ...value }
1191  for (const key of keys) delete rest[key]
1192  return rest
1193}
1194
1195// ---- what `report` does with the decision model's fallback ------------------------------
1196
1197/** The decision model that decides is not the one asked for (ADR 0006): e.g. `asked` is pplx, `using` is Jev, since there is no Perplexity key and there is a TypeSafe one. */
1198export type DecisionModelEvent = {
1199  asked: BackendName
1200  using: BackendName
hooks/core/setup.ts 762 lines
1// The options the person set (userConfig), read once per load into what every
2// feature receives: `ctx`. Pure: no `$`.
3//
4// Every option is read here, and only here: its bounds and its fallback are
5// written once, and every feature (and the eval, which builds its requests
6// from the same Config) reads the value from `ctx.config`. The fallbacks are
7// the manifest's defaults (the engine fills those in; a test or the eval may
8// leave an option out), except for the options whose default depends on the
9// decision model: those have no default in the manifest, so the engine
10// passes nothing for them until the person sets one, and their defaults are
11// in BACKEND_DEFAULTS below, the one table the mod, the eval and
12// scripts/decide*.ts read them from.
13
14import type { PluginOptions } from 'claude-code'
15import type { Backend, BackendName } from '../decision/backend.ts'
16import type { ContextLimits } from '../decision/context.ts'
17import { DEFAULT_AGENT_MODELS, WORDS_SHARE, type AgentModel, type DispatchAsk, type DispatchSettings } from '../decision/dispatched-agent.ts'
18import type { EffortAsk, EffortRules } from '../decision/effort.ts'
19import { RAISE_MODES, type RaiseMode } from '../decision/escalation.ts'
20import { jevBackend } from '../decision/jev.ts'
21import { JEV_DEFAULT_LIMITS, jevRateLimited, type JevLimits } from '../decision/jev-rate.ts'
22import type { MidturnLimits, MidturnRules } from '../decision/midturn.ts'
23import { resolveModel, type ResolvedModel } from '../decision/model-ids.ts'
24import { pplxBackend } from '../decision/pplx.ts'
25import { rateLimited } from '../decision/pplx-rate.ts'
26import type { SkillPolicy } from '../decision/skills.ts'
27import type { DecisionRequest } from '../decision/system-one.ts'
28import { BATCHES_BUDGET_MS } from '../decision/workflow.ts'
29import { listSwitches } from './switches.ts'
30
31/** The decision models the person can choose (`decisionModel`): Perplexity's pplx-decider and TypeSafe's Jev (decision/backend.ts, where the pure modules read it). */
32export type { BackendName }
33
34/**
35 * The decision model the person asked for: Jev when `decisionModel` names it, else pplx, the default (ADR 0006). Anything
36 * that names neither (unset, a typo, the `clef` of a 0.3.x configuration) reads as unset. Which one decides in the end also
37 * depends on the keys (`chooseBackend`).
38 */
39export function backendNameOf(options: PluginOptions): BackendName {
40  return options.decisionModel === 'jev' ? 'jev' : 'pplx'
41}
42
43/** Which decision model decides, and whether it is not the one asked for. */
44export type Choice = { backend: BackendName; fellBack: boolean }
45
46/**
47 * The decision model that decides (ADR 0006). Jev when the person asked for Jev. Otherwise pplx when there is a Perplexity key;
48 * with none, Jev when there is a TypeSafe key (`fellBack`: a 0.3.1 configuration keeps its routing); with neither, pplx, which
49 * then fails every request with the Perplexity key named as the one missing.
50 */
51export function chooseBackend(asked: BackendName, keys: { perplexity: string; typesafe: string }): Choice {
52  if (asked === 'jev') return { backend: 'jev', fellBack: false }
53  if (keys.perplexity !== '') return { backend: 'pplx', fellBack: false }
54  return keys.typesafe !== '' ? { backend: 'jev', fellBack: true } : { backend: 'pplx', fellBack: false }
55}
56
57/**
58 * The decision model that takes requests with images (#56, ADR 0008), apart from the one that decides everything else and
59 * whatever `decisionModel` says: Jev with a TypeSafe key (its Box question and one-time image tokens make zooming possible);
60 * else pplx with a Perplexity key, which cannot zoom (`fellBack`); else none (null), and the features that need images are unavailable.
61 */
62export function chooseImageBackend(keys: { perplexity: string; typesafe: string }): Choice | null {
63  if (keys.typesafe !== '') return { backend: 'jev', fellBack: false }
64  return keys.perplexity !== '' ? { backend: 'pplx', fellBack: true } : null
65}
66
67/**
68 * A `decisionModel` that names a decision model since removed (Clef, 0.4.0), left in the person's settings from before.
69 * The engine reads a value outside the option's list as the option's default (and warns), so the mod is handed the
70 * default, never the old value: this finds it in the settings file itself (`pluginConfigs[dispatch-pilot@...].options`,
71 * as `$.settings.read({ source: 'user' })` returns them). Null when the settings name none.
72 */
73export function removedDecisionModel(settings: unknown): 'clef' | null {
74  const configs = (settings as { pluginConfigs?: unknown } | null | undefined)?.pluginConfigs
75  if (typeof configs !== 'object' || configs === null) return null
76  for (const [plugin, config] of Object.entries(configs)) {
77    if (!plugin.startsWith('dispatch-pilot@')) continue
78    const options = (config as { options?: unknown } | null)?.options
79    if (typeof options === 'object' && options !== null && (options as { decisionModel?: unknown }).decisionModel === 'clef') return 'clef'
80  }
81  return null
82}
83
84/** The options whose default depends on the decision model: the manifest gives them none. */
85export const PER_BACKEND_OPTIONS = [
86  'timeoutMs',
87  'contextMessages',
88  'contextTokens',
89  'rejudgeSteps',
90  'rejudgeWaitMs',
91  'thetaUp',
92  'thetaDown',
93  'thetaMax',
94  'thetaExpected',
95  'agentOverride',
96  'skillsMinRelevance',
97  'findSkillMinRelevance',
98] as const
99export type PerBackendOption = (typeof PER_BACKEND_OPTIONS)[number]
100
101/**
102 * The kinds of request whose state has a budget of its own (`contextTokens`
103 * reads by kind): a message that carries the skills' question (and find_skill's
104 * first stage) is `Config.context`; the rest are these. `rejudge` is a
105 * mid-turn re-decision and a stuck one.
106 */
107export const CONTEXT_KINDS = ['messagePlain', 'rejudge', 'agent', 'workflow'] as const
108export type ContextKind = (typeof CONTEXT_KINDS)[number]
109
110/**
111 * What one decision model brings: each option's default where the person left
112 * it unset, the most `contextTokens` and `contextMessages` read as, how every
113 * question is asked and the threshold for taking the level above.
114 *
115 * Adding a decision model means touching, beyond its entry here: `BackendName`; the backend in decision/ and its
116 * construction in `setup()` (`configs`, `backends`, and whether it passes through the rate limit); `backendNameOf` and
117 * `chooseBackend` (which key decides, and what it falls back to); `DECISION_MODELS` in core/report.ts (its name and key
118 * settings, for the fallback entry); `decisionModel`'s options in plugin.json, its key option and the README's
119 * configuration tables (a column each); and, for the eval, `backendFor` and `PRICES` in eval/node.ts, `--backend` in
120 * eval/run.ts and eval/eval-v2-flow.ts, and the BACKENDS list in eval/lib/docs.ts. A `Record<BackendName, ...>` the compiler
121 * checks (this table, `setup()`, PRICES, DECISION_MODELS); the rest it does not, and tests/docs-sync.test.ts only the README tables.
122 */
123export type BackendDefaults = Readonly<Record<PerBackendOption, number>> & {
124  /** `contextTokens` above this reads as this. */
125  contextTokensMax: number
126  /** `contextMessages` above this reads as this. */
127  contextMessagesMax: number
128  /**
129   * The least probability the level above the most probable one needs to be taken instead (`EffortRules.roundUp`, decision/effort.ts).
130   * Not an option: set from the stored answers of the decision model (eval/resummarize.ts), like the other values of the table.
131   */
132  roundUp: number
133  /**
134   * `thetaMax` for an effort question that carries the strong hint (#41: the problem has come back unsolved
135   * `unresolvedMaxAfter` times; decision/unresolved.ts `withHint`), at a message and mid-turn. Never above `thetaMax`.
136   * Not an option: set from the stored answers of the flows' hinted requests (DEVELOPMENT.md 「强提示(#41)」).
137   */
138  hintThetaMax: number
139  /**
140   * How the decision model is asked, language and kind of question (the eval's variables, `effort-submit` for the effort question
141   * beside a message, `subagent` for an agent's): `turnStart` for that question, `agent` for the questions about a dispatched agent
142   * and a Workflow's, `other` for every other one (the mid-turn re-decision, a stuck loop, the skills, the problem summary's text).
143   * Not options.
144   */
145  ask: { turnStart: EffortAsk; agent: EffortAsk; other: EffortAsk }
146  /**
147   * What the state of each other kind of request may take, in estimated tokens (`contextTokens` is the message that carries the
148   * skills' question). Not options: each is the most that kind's longest question leaves, worked out in DEVELOPMENT.md (配置,
149   * 「Jev 的上下文默认值怎么算」) and checked by tests/backend-defaults.test.ts. What the person sets as `contextTokens` holds for
150   * every kind, each taking the smaller of it and its own.
151   */
152  contextByKind: Readonly<Record<ContextKind, number>>
153  /**
154   * Whether an agent's request carries the background it was written in, in what its brief and the person's words leave
155   * of the budget: the conversation it was dispatched from (`recent_context`) and, for a Workflow's agents, the script
156   * (`workflow_script`). It fills the request to its budget, so it is on where the decision model answers a full request
157   * in time. Not an option.
158   */
159  agentBackground: boolean
160  /**
161   * How long a request past the model's regular limits waits for its answer, at least (`Backend.longContext`: Jev's
162   * long-context header), and so does every request sent beside it, which may wait behind it for its place within the
163   * account's token rate (decision/jev-rate.ts); null where no request is (pplx). Not an option: set by the latency measured.
164   */
165  longWaitMs: number | null
166  /**
167   * How many requests about agents go out at once at most (core/agent-lane.ts): the agents that come while they are
168   * all out wait, and are merged into the next request. Not an option: set by how the model answers several at once.
169   */
170  agentLanes: number
171  /**
172   * How long find_skill's two requests may take in all, in ms; null: as long
173   * as a message waits (`timeoutMs`). Not an option: set by the latency
174   * measured, not calibrated. A hook has 10 s of its own, and the timer's wait
175   * counts toward it (the mods reference, Limits): this leaves room for the rest.
176   */
177  findSkillWaitMs: number | null
178  /**
179   * The least a skills ranking's second request is given, in ms, however much of the wait the first took (beside a message
180   * and in find_skill); null: only what the first left. Not an option: set by the latency measured.
181   */
182  skillsSecondStageMs: number | null
183  /** Whether find_skill's first request offers a skill by its profile (else by its description); the second re-reads it by both. */
184  findSkillProfiles: boolean
185}
186
187/**
188 * Jev's: the values the eval of #4, #14, #15 and #16 set or kept (README, 配置 has the table; DEVELOPMENT.md, 配置 what each rests on),
189 * except the ones that say how much Jev reads of the conversation: by the person's decision ("the more it is given, the
190 * better it judges"), those are set to what Jev takes, not to what the eval ran (4 messages, 2000 tokens, 4 steps). Jev
191 * takes 64k tokens a request and 32k for "the state and the longest question", or 262k for both with its long-context
192 * header (decision/jev.ts, `needsLongContext`). The longest question is the first stage of the skills (111 skills with
193 * profiles: about 16k tokens as the mod counts, 21.9k as Jev does), which shares its request with the state, so
194 * `contextTokens` is what that leaves, 6000 (DEVELOPMENT.md, 配置, 「Jev 的上下文默认值怎么算」; tests/backend-defaults.test.ts
195 * checks the sum). The counts that fill a state are at their most (`contextMessages` 2000, `rejudgeSteps` 16), so the
196 * token budget, not the count, ends what is sent.
197 */
198const JEV_DEFAULTS: BackendDefaults = {
199  timeoutMs: 1500,
200  // As many as pplx: the budget ends what is sent (32, the old most, held a long conversation to a fraction of 96000 tokens).
201  contextMessages: 2000,
202  contextMessagesMax: 2000,
203  contextTokens: 6000,
204  contextTokensMax: 16000,
205  // A message's effort request and an agent's (dispatched, or a Workflow's) go past Jev's regular limits, with the long-context
206  // header (2026-10-15, DEVELOPMENT.md 「Jev 的长上下文」): the state takes up to 96000 estimated tokens, about 115k as Jev counts
207  // Chinese (1.2 a token; English up to 1.37, about 132k), within 40-60% of its 262,144: the share of a window a model reads
208  // best in, by the person's rule of thumb, and never full. Measured: the ctx30 run, 94k tokens of one conversation, 25 of 30
209  // right against 13 of 30 with the newest 24000 (p 0.0005); eval v2's whole conversations, 146k tokens on average (56%),
210  // came out no better than 24000 (60.0% against 67.5%); the docs call the long context less accurate than staying within
211  // the regular limits. A re-decision stays at 24000: it reads this turn's steps (16 at most, a few thousand tokens), and a
212  // step waits only `rejudgeWaitMs` for it. The other kinds have questions of at most 700 tokens as Jev counts them, a Workflow
213  // batch 20,100 for 8 agents, far under 262k.
214  contextByKind: { messagePlain: 96000, rejudge: 24000, agent: 96000, workflow: 96000 },
215  // On (2026-10-15): an agent's request reads the conversation it was dispatched from, and a Workflow's its script, to 96000
216  // tokens; the agents dispatched together share one request (core/agent-lane.ts), so the conversation is paid for once.
217  agentBackground: true,
218  // A request of 96000 estimated tokens took 1.0-1.6 s (p50 1.34 s) on 1.14 at 100-120k Jev tokens (eval v2, 2026-10-15); 3000
219  // leaves room for the wait for its place within the account's token rate (decision/jev-rate.ts) when a burst is out.
220  longWaitMs: 3000,
221  // Four: four long requests of one key sent at once (115k tokens each) were all answered in 1.39-1.53 s, one alone in 1.44 s
222  // (2026-10-15, DEVELOPMENT.md 「Jev 的长上下文」); more were not tried. The account's token rate paces them beyond that
223  // (decision/jev-rate.ts: four full ones take most of a burst). The agents that come while four are out go in the next request.
224  agentLanes: 4,
225  rejudgeSteps: 16,
226  // A step waits this long for a re-decision not yet back before it goes on at the level it had: Jev's mid-turn requests took about 280 ms
227  // at p50 and 350 ms at p90 (DEVELOPMENT.md, 配置), and they are sent when the step's tools start, so they are mostly back by then.
228  rejudgeWaitMs: 300,
229  // Raising is easy, lowering is hard (AA: a Sonnet 5.5 at medium scores 41 on the index and at high 47, at low 36; Terminal-Bench
230  // 20.7% at low against 43.9% at high): 0.4 to 0.3 for a raise, 0.6 to 0.75 for a lowering, 3 to 5 steps held after a raise.
231  // The lowering gate came back down to 0.55 in 0.2.3: with 0.75 the level sent was too high too often (too high 11.5/11.0% to
232  // 19.5/17.5%); a scan of the stored effort-midturn answers (eval/rescore.ts --theta-down) found none of 0.55 to 0.75 to bring it back, and 0.55 is the one with the least too high and too low together.
233  thetaUp: 0.3,
234  thetaDown: 0.55,
235  thetaMax: 0.5,
236  thetaExpected: 0.25,
237  agentOverride: 0.6,
238  // #16, both runs on the old wording: from 0.7 to 0.75 the Chinese-English gap of the skill suggestions went from -3.7 to -2.3 points.
239  skillsMinRelevance: 0.75,
240  findSkillMinRelevance: 0.5,
241  findSkillWaitMs: null,
242  // Several sessions on one key slow the first request (26k tokens) from 0.6-0.8 s to 0.9-1.3 s, and the second took
243  // 0.27-0.48 s: sharing 1500 ms, 3 of 15 messages lost the second (2026-10-19, five sessions at once). 800 ms is above
244  // the second's slowest; a message waits 2.3 s at most then, 3.8 s with a long effort request (`longWaitMs`).
245  skillsSecondStageMs: 800,
246  findSkillProfiles: true,
247  // Raising is easy (DEVELOPMENT.md, 「按 AA 基准校正」): the level above the most probable one is taken from 0.3.
248  roundUp: 0.3,
249  // The hinted effort question's (2026-10-16, DEVELOPMENT.md 「强提示(#41)」): over the hinted answers of the flows,
250  // 0.4 took max recall to 20/20 on long-context and 7/7 on eval-v2 (0.5: 18/20 and 7/7), max where it is not accepted 9/15
251  // (0.5: 8/15); Jev's hinted answers of the real session that set this off were 0.37-0.48.
252  hintThetaMax: 0.4,
253  // effort-submit on the current wording, one run each (2026-10-05): asked in Chinese, Chinese items 85% and English
254  // items 89%; asked in English, 79% and 78%. An agent's questions are asked in Chinese since Jev 1.14 (the subagent eval of
255  // 2026-10-15, DEVELOPMENT.md 「Jev 1.14」: models-hint-zh 72/71% and again 72/72%, against models-hint's 71/68%; on 1.13 the
256  // Chinese wording had been the weaker, 67/64% and 65/65%). The other questions stay in English.
257  ask: { turnStart: { language: 'zh', primitive: 'score' }, agent: { language: 'zh', primitive: 'score' }, other: { language: 'en', primitive: 'score' } },
258}
259
260/**
261 * pplx-decider-v1.1-27b's: B′ of eval v2 (#45, ADR 0006: the state within 48000 tokens, every question in English, no problem
262 * summary), with the thresholds calibrated on its own stored answers (DEVELOPMENT.md, eval v2 的结果). It takes 262,144 tokens
263 * a request (state and questions), so what it reads is not cut to Jev's 32k: 2000 messages (the budget, not the count, ends
264 * what is sent) and its state up to what it answers within a message's wait (below); the skills' two stages keep Jev's 6000,
265 * since the profiles of the skills are the same length for either model. A request takes seconds, not Jev's fraction of one,
266 * so a message waits 8000 ms (a hook has 10 s) and a step 6000 ms for a re-decision. What the eval did not calibrate for pplx
267 * (the failure bar, the agents' override, the skills' relevance) is Jev's.
268 */
269const PPLX_DEFAULTS: BackendDefaults = {
270  timeoutMs: 8000,
271  contextMessages: 2000,
272  contextMessagesMax: 2000,
273  contextTokens: 6000,
274  contextTokensMax: 48000,
275  // Time, not the window, ends the state (measured 2026-10-13, DEVELOPMENT.md 「pplx 的 agent 预算」): pplx counts about 2.2
276  // tokens for each the mod estimates, and the time grows with them (the docs: 90k tokens 5 s, 190k 14 s, the full window
277  // 23 s). A state of 48000 took 4.3-5.9 s alone and 72000 8.3-8.8 s, past the 8000 ms wait. Agents are dispatched several
278  // at once, each request filled with the conversation (`agentBackground`): five at once at 32000 took 5.2 s at most, three
279  // at 48000 up to 7.6 s. So a dispatched agent's request, and each of a Workflow's when it takes several (`planBatches`),
280  // is 32000; a Workflow's one request keeps 48000.
281  contextByKind: { messagePlain: 48000, rejudge: 48000, agent: 32000, workflow: 48000 },
282  // On: pplx answers a full request in about 4 s, several at once (`pplxQps` lets five go together).
283  agentBackground: true,
284  // pplx takes 262k in every request (no header), and its own wait is seconds already.
285  longWaitMs: null,
286  // Five: five requests of 32000 at once were all answered within 5.2 s (`pplxQps` lets five go in a second).
287  agentLanes: 5,
288  rejudgeSteps: 16,
289  // A re-decision takes seconds, not 300 ms: a step waits for it up to this long (the most the manifest allows is 8000).
290  rejudgeWaitMs: 6000,
291  // Calibrated offline on the stored pplx answers (eval v2, DEVELOPMENT.md): thetaMax 0.47 (0.48 sits on submit-034's p(max) of
292  // 0.480), thetaDown 0.55 as Jev's (from 0.6 up, the English score question sends the level too high more often than Jev).
293  // thetaUp 0 raises a level mid-turn on any answer above it (0.3 is the cautious alternative); it does not move the level a
294  // message is sent at, which thetaMax and roundUp decide.
295  thetaUp: 0,
296  thetaDown: 0.55,
297  thetaMax: 0.47,
298  thetaExpected: 0.25,
299  agentOverride: 0.6,
300  skillsMinRelevance: 0.75,
301  findSkillMinRelevance: 0.5,
302  // Find_skill's two requests wait as long as the profiles' question takes (a message's wait would be 8000 ms of a 10 s hook).
303  findSkillWaitMs: 6000,
304  // pplx's waits are seconds already, and a longer one would go past a hook's 10 s.
305  skillsSecondStageMs: null,
306  findSkillProfiles: true,
307  // The level above the most probable one is taken from 0.45 (ADR 0006): the offline scan of the stored effort-submit answers
308  // (English questions) took the level sent too high from 18.5% to 13.0% with the recall of max unchanged (11 of 16); eval v2's
309  // level too low went from 12.5% to 15.0%.
310  roundUp: 0.45,
311  // Its own thetaMax: the hint was not measured on pplx with the wording of 2026-10-16.
312  hintThetaMax: 0.47,
313  ask: { turnStart: { language: 'en', primitive: 'score' }, agent: { language: 'en', primitive: 'score' }, other: { language: 'en', primitive: 'score' } },
314}
315
316/** The defaults by decision model: the only place they are written. */
317export const BACKEND_DEFAULTS: Readonly<Record<BackendName, BackendDefaults>> = {
318  pplx: PPLX_DEFAULTS,
319  jev: JEV_DEFAULTS,
320}
321
322/**
323 * What the state of a message's decision request may take: the message that
324 * carries the skills' question (`withSkills`) has `context`, whose tokens
325 * leave room for that question; the effort question's request, and any other
326 * plain message, has `contextByKind.messagePlain` (ADR 0005). The core and the
327 * eval build the request's state from the same limits.
328 */
329export function messageLimits(config: Pick<Config, 'context' | 'contextByKind'>, withSkills: boolean): ContextLimits {
330  return withSkills ? config.context : { ...config.context, tokens: config.contextByKind.messagePlain }
331}
332
333/**
334 * How much of each of the person's messages is kept for the turn (`said`): what the largest request that reads them (a
335 * dispatched agent's, a Workflow's) can send of them, a third of its budget (`dispatchWords`). The mod keeps them so
336 * (features/dispatched-agents.ts), and the eval cuts an item's message the same way.
337 */
338export function saidTokens(config: Pick<Config, 'contextByKind'>): number {
339  return Math.floor(Math.max(config.contextByKind.agent, config.contextByKind.workflow) * WORDS_SHARE)
340}
341
342/**
343 * How long an agent waits for its decision at most (`Config.agents.waitMs`): the request about it and one ahead of it in
344 * the lane (core/agent-lane.ts), each as long as a long request may wait, within what a hook can spare (BATCHES_BUDGET_MS).
345 * Jev 6000, pplx 8000.
346 */
347export function agentWaitMs(timeoutMs: number, longWaitMs: number | null): number {
348  return Math.min(BATCHES_BUDGET_MS, 2 * Math.max(timeoutMs, longWaitMs ?? 0))
349}
350
351/**
352 * How long requests sent together wait for their answers: `timeoutMs`, or `longWaitMs` at least once any of them goes past
353 * the decision model's regular limits (`Backend.longContext`), behind which the others may wait for their place within the
354 * account's token rate (decision/jev-rate.ts).
355 */
356export function waitFor(ctx: { readonly config: Pick<Config, 'timeoutMs' | 'longWaitMs'>; readonly backend: Pick<Backend, 'longContext'> }, requests: readonly DecisionRequest[]): number {
357  const { timeoutMs, longWaitMs } = ctx.config
358  if (longWaitMs === null || !requests.some((request) => ctx.backend.longContext?.(request) === true)) return timeoutMs
359  return Math.max(timeoutMs, longWaitMs)
360}
361
362/**
363 * How long a re-decision's request (mid-turn, or a stuck loop's) waits for its answer: as long as a long request may, since
364 * long ones of the mod's (a message's, an agent's) may be ahead of it for a place within the account's token rate
365 * (decision/jev-rate.ts). The step it is for waits only `rejudgeWaitMs` for it, and an answer that comes later is taken at
366 * a later step.
367 */
368export function redecisionWaitMs(config: Pick<Config, 'timeoutMs' | 'longWaitMs'>): number {
369  return Math.max(config.timeoutMs, config.longWaitMs ?? 0)
370}
371
372/** The settings are also the effort rules' parameters (`EffortRules`: `thetaMax` and `roundUp`): `traceEffort(reading, config)`. */
373export type Config = EffortRules & {
374  /** The decision model the options were read for: its defaults (BACKEND_DEFAULTS) stand for what the person left unset. */
375  backend: BackendName
376  /**
377   * What came from that decision model's defaults (for the debug log, describeDefaults): the options the person left
378   * unset, with the value each took, and an option set above that model's most, read as the most.
379   */
380  defaults: { used: readonly (readonly [PerBackendOption, number])[]; capped: readonly { option: PerBackendOption; set: number; read: number }[] }
381  /** The TypeSafe key in the options (`typesafeApiKey`, trimmed; '' if unset). Not enumerable (see readConfig): it is not in a written-out or copied config. The environment's (`Secrets`) stands where this is empty. */
382  readonly typesafeApiKey: string
383  /** The Perplexity key in the options (`perplexityApiKey`, trimmed; '' if unset; not enumerable either): the environment's (`Secrets`) stands where this is empty. */
384  readonly perplexityApiKey: string
385  /** How many pplx requests the mod sends in a second at most (`pplxQps`; the account's limit): the rest wait their turn (decision/pplx-rate.ts). */
386  pplxQps: number
387  /**
388   * The TypeSafe account's limits (`jevQps`, `jevTokensPerSecond`; the console's rate limits, the default plan's 80 requests
389   * and 100,000 input tokens a second): every Jev request is paced within them (decision/jev-rate.ts).
390   */
391  jevLimits: JevLimits
392  /** How long a decision request may take before the prompt goes on without it. */
393  timeoutMs: number
394  /**
395   * How long a request past the decision model's regular limits waits, at least, and every request sent beside it
396   * (BACKEND_DEFAULTS longWaitMs; `waitFor`); null: no request is.
397   */
398  longWaitMs: number | null
399  /**
400   * How the decision model is asked (BACKEND_DEFAULTS ask): `turnStart` the effort question beside each message, `agent` the
401   * questions about an agent (a dispatched agent's and a Workflow's, `dispatchSettings`), `other` every other question (`ctx.ask`).
402   */
403  ask: { turnStart: EffortAsk; agent: EffortAsk; other: EffortAsk }
404  /**
405   * What the decision model reads of the conversation: how many recent messages, how many tokens in all. The tokens are the
406   * budget of a message that carries the skills' question (and of find_skill's first stage); the other kinds of request have
407   * theirs in `contextByKind` (a mid-turn re-decision's in `midturn.limits`, too).
408   */
409  context: ContextLimits
410  /** The tokens the state of each other kind of request may take: the decision model's default for the kind, or what the person set if smaller. */
411  contextByKind: Readonly<Record<ContextKind, number>>
412  /** The main agent's effort decided again while a turn runs (#5); a stuck loop's re-decision (#7) reads its loop the same way. */
413  midturn: {
414    /** Re-decide at every step whose index is a multiple of this; 0 for never. */
415    every: number
416    /** How long a step waits for a re-decision (or a stuck one) not back yet. */
417    waitMs: number
418    /** What a re-decision reads: the latest steps, within the context budget. */
419    limits: MidturnLimits
420    /** How an answer moves the level: thetaUp, thetaDown, thetaMax, roundUp, holdSteps. */
421    rules: MidturnRules
422  }
423  /** Forced escalation (#7). */
424  escalation: {
425    /** Counted failures that make a loop stuck. */
426    after: number
427    mode: RaiseMode
428    /** Forced raises a loop gets at most. */
429    limit: number
430    /** The failures count as expected when the answer reaches this probability. */
431    thetaExpected: number
432    /** The model a failing haiku agent is switched to, resolved to a full id; null: never switch (left empty, or a name no model family has). */
433    haikuTo: ResolvedModel | null
434    /** `escalateHaikuTo` as the person wrote it, for the log when it names no model. */
435    haikuToWritten: string
436  }
437  /** Dispatched agents and a Workflow's agents (#6, #8, #9). */
438  agents: {
439    /** The models the decision model may choose, cheapest first (fable with `agentFable`). */
440    models: readonly AgentModel[]
441    /** The decision model's pick replaces the main agent's (or the script's) only at this confidence or above. */
442    thetaOverride: number
443    /** `rewrite` writes a Workflow's decisions into its script; `return` sends the Workflow back with them, once. */
444    workflowMode: 'rewrite' | 'return'
445    /** Whether an agent's request carries the conversation it was dispatched from and, a Workflow's, the script (the decision model's: BACKEND_DEFAULTS `agentBackground`). */
446    background: boolean
447    /** How many requests about agents go out at once at most (BACKEND_DEFAULTS `agentLanes`, core/agent-lane.ts). */
448    lanes: number
449    /**
450     * How long an agent waits for its decision at most before it starts as it was asked: for the request about it and one
451     * ahead of it in the lane, each as long as a long request may take, within the 8000 ms a hook can spare (`agentWaitMs`).
452     */
453    waitMs: number
454  }
455  /** Skills (#10, #11, #12). */
456  skills: {
457    /** What a message is suggested: at most `max`, from `minRelevance`. */
458    suggest: SkillPolicy
459    /** What find_skill returns: at most `max`, from `minRelevance`. */
460    find: SkillPolicy
461    /** How long find_skill's two requests may take in all (the decision model's: BACKEND_DEFAULTS findSkillWaitMs). */
462    findWaitMs: number
463    /** The least a ranking's second request is given (BACKEND_DEFAULTS skillsSecondStageMs); null: what the first left. */
464    secondStageMs: number | null
465    /** Whether find_skill's first request offers skills by their profiles (the decision model's: findSkillProfiles). */
466    findByProfile: boolean
467    /** How many of stage one's best stage two re-reads. */
468    shortlist: number
469    /** Skills the main agent keeps in its listing (names as the listing spells them). */
470    alwaysListed: readonly string[]
471    /** Skills never offered, to the main agent or to the person. */
472    neverSuggested: readonly string[]
473    /** The model that writes skill profiles; part of every profile's key. */
474    profileModel: string
475    /** How many missing profiles a session start writes at most. */
476    profilesPerSession: number
477  }
478  /** The unresolved count and the problem summary (#39, #40). */
479  unresolved: {
480    /** The model that writes the problem summary after each of the person's turns (`summaryModel`). */
481    summaryModel: string
482    /** The count from which the effort question of a message and of a mid-turn re-decision carries the strong hint (`unresolvedMaxAfter`; 0: never). */
483    maxAfter: number
484    /** `thetaMax` for an effort question that carries the strong hint: the decision model's `hintThetaMax`, never above `thetaMax`. */
485    thetaMax: number
486  }
487}
488
489/** The effort rules for an answer to an effort question that carried the strong hint: `thetaMax` is the hint's (`unresolved.thetaMax`). */
490export function hintedRules<R extends EffortRules>(rules: R, config: Pick<Config, 'unresolved'>): R {
491  return { ...rules, thetaMax: Math.min(rules.thetaMax, config.unresolved.thetaMax) }
492}
493
494/**
495 * What the mod reads from the environment: `$.env.get` is asynchronous and needs `$`, which neither `setup` nor an import may
496 * have, so the session start (features/control.ts) reads it into this object, which `ctx.backend` reads when it asks. A
497 * value set in the options always comes first. Nothing here is ever written down: not to the debug log, the board or `$.state`.
498 */
499export type Secrets = {
500  /** `PERPLEXITY_API_KEY`, trimmed; '' while unread or unset. */
501  perplexityEnvKey: string
502  /** `TYPESAFE_API_KEY`, trimmed; '' while unread or unset. Desktop hands a mod no sensitive option (#35): this is its way in there. */
503  typesafeEnvKey: string
504}
505
506/** The Perplexity key in use: the options' (`perplexityApiKey`) first, else the environment's. '' for none. */
507export function perplexityKey(config: Pick<Config, 'perplexityApiKey'>, secrets: Secrets): string {
508  return config.perplexityApiKey !== '' ? config.perplexityApiKey : secrets.perplexityEnvKey
509}
510
511/** The TypeSafe key in use: the options' (`typesafeApiKey`) first, else the environment's. '' for none. */
512export function typesafeKey(config: Pick<Config, 'typesafeApiKey'>, secrets: Secrets): string {
513  return config.typesafeApiKey !== '' ? config.typesafeApiKey : secrets.typesafeEnvKey
514}
515
516/**
517 * Where a key in use came from, for the session start's debug line: `from the options`, `from <variable>` or `not set`.
518 * Never the key itself.
519 */
520export function keySource(option: string, environment: string, variable: string): string {
521  return option !== '' ? 'from the options' : environment !== '' ? `from ${variable}` : 'not set'
522}
523
524/**
525 * What the entry hands every feature's register: data and pure functions, never `$`.
526 *
527 * Which decision model decides is not known at register: either key may be in the environment, which the session start
528 * reads (`secrets`). `config`, `backend`, `ask` and `fellBack` are therefore read afresh at each use and follow the choice: a
529 * feature that keeps a value from `ctx.config` when it registers keeps the wrong model's (the defaults differ), so it reads
530 * `ctx.config` where it acts.
531 */
532export type Ctx = {
533  /** The settings of the decision model that decides (`chooseBackend`). */
534  readonly config: Config
535  /** The decision model that decides. */
536  readonly backend: Backend
537  /** What the session start read from the environment (a key not in the options). */
538  readonly secrets: Secrets
539  /** How every question but the effort question beside a message is asked: the decision model's (`config.ask.other`). */
540  readonly ask: EffortAsk
541  /** Whether Jev decides only because there is no Perplexity key (a TypeSafe key is set): the session start records it. */
542  readonly fellBack: boolean
543  /**
544   * The decision model that takes requests with images, with the backend to ask (`chooseImageBackend`); null when there is none
545   * and the features that need images are unavailable. `fellBack`: it is pplx for want of a TypeSafe key, which cannot zoom
546   * (needs Box questions). It is the same backend object as `backend` would be, so a pplx request goes through the rate limit
547   * (its `io` needs `pace`, as every request's does).
548   */
549  readonly images: { readonly name: BackendName; readonly backend: Backend; readonly fellBack: boolean } | null
550}
551
552/** `table` is only a test's way to read a table the shipped one does not have (a decision model not added yet). */
553export function setup(options: PluginOptions, table: Readonly<Record<BackendName, BackendDefaults>> = BACKEND_DEFAULTS): Ctx {
554  const asked = backendNameOf(options)
555  // Both are worked out here, whichever decides: pure and cheap, and `chooseBackend` picks between them once the environment is read.
556  const configs: Record<BackendName, Config> = { pplx: readConfig(options, table, 'pplx'), jev: readConfig(options, table, 'jev') }
557  const secrets: Secrets = { perplexityEnvKey: '', typesafeEnvKey: '' }
558  const backends: Record<BackendName, Backend> = {
559    // Every request goes through its account's rate limit: pplx's (#51), Jev's (requests and input tokens a second).
560    pplx: rateLimited(pplxBackend(() => perplexityKey(configs.pplx, secrets)), configs.pplx.pplxQps),
561    jev: jevRateLimited(jevBackend(() => typesafeKey(configs.jev, secrets)), () => configs.jev.jevLimits),
562  }
563  const keys = () => ({ perplexity: perplexityKey(configs.pplx, secrets), typesafe: typesafeKey(configs.jev, secrets) })
564  const choice = () => chooseBackend(asked, keys())
565  return {
566    get config() {
567      return configs[choice().backend]
568    },
569    get backend() {
570      return backends[choice().backend]
571    },
572    secrets,
573    get ask() {
574      return configs[choice().backend].ask.other
575    },
576    get fellBack() {
577      return choice().fellBack
578    },
579    get images() {
580      const chosen = chooseImageBackend(keys())
581      return chosen === null ? null : { name: chosen.backend, backend: backends[chosen.backend], fellBack: chosen.fellBack }
582    },
583  }
584}
585
586/**
587 * The person's options, each within its bounds; where one is missing or of
588 * the wrong type, the manifest's default, or for an option whose default
589 * depends on the decision model (PER_BACKEND_OPTIONS), that model's
590 * (`table`, BACKEND_DEFAULTS unless a test reads another). `contextTokens`
591 * and `contextMessages` read at most that model's most. `backend` is the
592 * decision model it reads for: what `decisionModel` asks for unless the
593 * keys decide otherwise (`setup` reads both).
594 */
595export function readConfig(options: PluginOptions, table: Readonly<Record<BackendName, BackendDefaults>> = BACKEND_DEFAULTS, backend: BackendName = backendNameOf(options)): Config {
596  const defaults = table[backend]
597  const used: (readonly [PerBackendOption, number])[] = []
598  const capped: { option: PerBackendOption; set: number; read: number }[] = []
599  /** A per-backend option: the person's value within [min, max], else the decision model's default (noted for the log). */
600  const own = (option: PerBackendOption, min: number, max: number, round = false) => {
601    const set = options[option]
602    if (!isNumber(set)) {
603      used.push([option, defaults[option]])
604      return defaults[option]
605    }
606    const read = numberIn(set, min, max, defaults[option])
607    const value = round ? Math.round(read) : read
608    if (set > max) capped.push({ option, set, read: value })
609    return value
610  }
611  const whole = (value: unknown, min: number, max: number, fallback: number) => Math.round(numberIn(value, min, max, fallback))
612  const { roundUp } = defaults
613  const thetaMax = own('thetaMax', 0, 1)
614  // `contextTokens` by kind of request: unset, each kind's own (BACKEND_DEFAULTS); set, the smaller of it and each kind's.
615  const contextTokens = own('contextTokens', 100, defaults.contextTokensMax, true)
616  const byKind = (cap: number) => (isNumber(options.contextTokens) ? Math.min(contextTokens, cap) : cap)
617  const context = { messages: own('contextMessages', 0, defaults.contextMessagesMax, true), tokens: byKind(defaults.contextTokens) }
618  const contextByKind = Object.fromEntries(CONTEXT_KINDS.map((kind) => [kind, byKind(defaults.contextByKind[kind])])) as Record<ContextKind, number>
619  const haikuToWritten = stringOf(options.escalateHaikuTo, 'sonnet').trim()
620  // A hook's own budget is 10 s and the timer's wait counts toward it.
621  const timeoutMs = own('timeoutMs', 200, 8000)
622  const config: Omit<Config, 'typesafeApiKey' | 'perplexityApiKey'> = {
623    backend,
624    defaults: { used, capped },
625    pplxQps: whole(options.pplxQps, 1, 50, 5),
626    jevLimits: {
627      requestsPerSecond: whole(options.jevQps, 1, 1000, JEV_DEFAULT_LIMITS.requestsPerSecond),
628      tokensPerSecond: whole(options.jevTokensPerSecond, 10_000, 100_000_000, JEV_DEFAULT_LIMITS.tokensPerSecond),
629    },
630    timeoutMs,
631    longWaitMs: defaults.longWaitMs,
632    ask: defaults.ask,
633    thetaMax,
634    roundUp,
635    context,
636    contextByKind,
637    midturn: {
638      every: whole(options.rejudgeEvery, 0, 50, 3),
639      // A hook's own budget is 10 s and the timer's wait counts toward it, as for `timeoutMs`.
640      waitMs: own('rejudgeWaitMs', 0, 8000, true),
641      limits: { steps: own('rejudgeSteps', 1, 16, true), tokens: contextByKind.rejudge },
642      rules: {
643        thetaUp: own('thetaUp', 0, 1),
644        thetaDown: own('thetaDown', 0, 1),
645        thetaMax,
646        roundUp,
647        holdSteps: whole(options.holdSteps, 0, 50, 5),
648      },
649    },
650    escalation: {
651      after: whole(options.escalateAfter, 1, 20, 2),
652      mode: RAISE_MODES.find((mode) => mode === options.escalateMode) ?? 'one-level',
653      limit: whole(options.escalateLimit, 0, 10, 2),
654      thetaExpected: own('thetaExpected', 0, 1),
655      haikuTo: haikuToWritten === '' ? null : resolveModel(haikuToWritten),
656      haikuToWritten,
657    },
658    agents: {
659      models: options.agentFable === true ? [...DEFAULT_AGENT_MODELS, 'fable'] : DEFAULT_AGENT_MODELS,
660      thetaOverride: own('agentOverride', 0, 1),
661      workflowMode: stringOf(options.workflowMode, 'rewrite') === 'return' ? 'return' : 'rewrite',
662      background: defaults.agentBackground,
663      lanes: defaults.agentLanes,
664      waitMs: agentWaitMs(timeoutMs, defaults.longWaitMs),
665    },
666    skills: {
667      suggest: { max: whole(options.skillsMax, 0, 10, 3), minRelevance: own('skillsMinRelevance', 0, 1) },
668      find: { max: whole(options.findSkillMax, 1, 10, 5), minRelevance: own('findSkillMinRelevance', 0, 1) },
669      findWaitMs: defaults.findSkillWaitMs ?? timeoutMs,
670      secondStageMs: defaults.skillsSecondStageMs,
671      findByProfile: defaults.findSkillProfiles,
672      shortlist: whole(options.skillsShortlist, 1, 10, 4),
673      alwaysListed: namesOf(options.skillsAlwaysListed),
674      neverSuggested: namesOf(options.skillsNeverSuggested),
675      profileModel: stringOf(options.skillsProfileModel, DEFAULT_PROFILE_MODEL).trim() || DEFAULT_PROFILE_MODEL,
676      profilesPerSession: whole(options.skillsProfilesPerSession, 0, 500, 30),
677    },
678    unresolved: {
679      summaryModel: stringOf(options.summaryModel, DEFAULT_SUMMARY_MODEL).trim() || DEFAULT_SUMMARY_MODEL,
680      maxAfter: whole(options.unresolvedMaxAfter, 0, 10, 3),
681      thetaMax: Math.min(thetaMax, defaults.hintThetaMax),
682    },
683  }
684  // In the table's order, whatever order they were read in.
685  used.sort((a, b) => PER_BACKEND_OPTIONS.indexOf(a[0]) - PER_BACKEND_OPTIONS.indexOf(b[0]))
686  // The keys are not enumerable: `JSON.stringify(config)`, `{ ...config }` and `Object.keys` do not meet them, so a
687  // config written to a log, a result file or the board (the eval saves its settings) cannot carry a key by accident.
688  return Object.defineProperties(config, {
689    typesafeApiKey: { value: stringOf(options.typesafeApiKey, '').trim(), enumerable: false },
690    perplexityApiKey: { value: stringOf(options.perplexityApiKey, '').trim(), enumerable: false },
691  }) as Config
692}
693
694/**
695 * One debug-log line on what the decision model's defaults decided, e.g.
696 * `settings for jev: left unset, so jev's defaults: timeoutMs 1500, ...;
697 * skill suggestions on until /dp skills off; contextTokens 20000 reads as
698 * 16000, the most with jev`. The skills' switch is read as it stands, so the session start loads the person's switches first.
699 */
700export function describeDefaults(config: Pick<Config, 'backend' | 'defaults' | 'skills'>): string {
701  const { backend, defaults } = config
702  const used = defaults.used.length === 0 ? 'every option set' : `left unset, so ${backend}'s defaults: ${defaults.used.map(([option, value]) => `${option} ${value}`).join(', ')}`
703  const capped = defaults.capped.map((cap) => `; ${cap.option} ${cap.set} reads as ${cap.read}, the most with ${backend}`).join('')
704  // The skills' own switch, not `isOn`: with the master switch off the skills' switch has not moved, and `/dp skills on` would not turn anything on.
705  const skillsSwitchOn = listSwitches().find((info) => info.name === 'skills')?.on ?? true
706  const suggestions = !skillsSwitchOn ? 'skill suggestions off (/dp skills on)' : config.skills.suggest.max === 0 ? 'skill suggestions off (skillsMax 0)' : 'skill suggestions on until /dp skills off'
707  return `settings for ${backend}: ${used}; ${suggestions}${capped}`
708}
709
710/**
711 * How an agent's model and effort are decided (decision/dispatched-agent.ts):
712 * the same for a dispatched agent (#6) and a Workflow's agents (#8, #9), and
713 * for the eval; its questions are asked as the decision model asks about an
714 * agent (`config.ask.agent`), and `ask` writes them otherwise (the eval's variants).
715 */
716export function dispatchSettings(ctx: { config: Pick<Config, 'agents' | 'thetaMax' | 'roundUp' | 'ask'> }, ask: Partial<DispatchAsk> = {}): DispatchSettings {
717  // Each read goes to `ctx`: a feature builds this when it registers, before the session start has settled the decision model.
718  return {
719    get models() {
720      return ctx.config.agents.models
721    },
722    get ask() {
723      return { ...ctx.config.ask.agent, ...ask }
724    },
725    get thetaOverride() {
726      return ctx.config.agents.thetaOverride
727    },
728    get thetaMax() {
729      return ctx.config.thetaMax
730    },
731    get roundUp() {
732      return ctx.config.roundUp
733    },
734  }
735}
736
737/** The cheap model that writes skill profiles, unless the person names another (`skillsProfileModel`). */
738const DEFAULT_PROFILE_MODEL = 'haiku'
739
740/** The cheap model that writes the problem summary, unless the person names another (`summaryModel`). */
741const DEFAULT_SUMMARY_MODEL = 'haiku'
742
743function isNumber(value: unknown): value is number {
744  return typeof value === 'number' && Number.isFinite(value)
745}
746
747/** A numeric option clamped to [min, max]; `fallback` when it is not a number. */
748function numberIn(value: unknown, min: number, max: number, fallback: number): number {
749  return isNumber(value) ? Math.min(max, Math.max(min, value)) : fallback
750}
751
752/** A string option; `fallback` when it is not a string. A sensitive one never set arrives as ''. */
753function stringOf(value: unknown, fallback: string): string {
754  return typeof value === 'string' ? value : fallback
755}
756
757/** A list-of-names option (`multiple` in the manifest; a comma-separated string also reads): trimmed, empty ones dropped. */
758function namesOf(value: unknown): string[] {
759  const items = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : []
760  return items.flatMap((item) => (typeof item === 'string' && item.trim() !== '' ? [item.trim()] : []))
761}
762
hooks/features/control.ts 215 lines
1// Feature: the person's control over Dispatch Pilot, the `/dp` command.
2//
3//   /dp                  opens the rationale pane (依据面板), or closes it when open
4//   /dp log              opens the same pane (the old habit's name for it)
5//   /dp status           what is on, the lock
6//   /dp on | off         the whole mod
7//   /dp <name> on | off  one feature (each registers its own, core/switches.ts)
8//   /dp lock <effort>    hold the main agent at that effort on every step
9//   /dp unlock           release it
10//   /dp log N            the last N decisions and why, in the conversation
11//
12// A pane the surface does not place (one that places no panes) is closed again
13// at once, and the answer says so (spec #22: no pane left open and waiting).
14// Only a session with a terminal hands the pane the keyboard (p / n, Esc):
15// elsewhere the person clicks, and a pane asking for the keys is shown again
16// whenever it is hidden (Desktop, while the engine lists the request).
17//
18// What the person flips is kept in $.store and loaded back at session start.
19// The engine puts the plugin's name before a command's answer, so the texts
20// here do not start with one.
21//
22// It also records what the engine measures of the session (context fill, limit
23// percentages, cost) in the debug log. Only recorded: nothing reads them to
24// decide anything (spec, 可见性与控制; a later quota-saving mode may).
25
26import type { EngineInterface, On, RenderSurface, SessionMeasureInput } from 'claude-code'
27import { EFFORTS, isEffort, type Effort } from '../decision/effort.ts'
28import { decisionLine, LOG_ENTRIES, report, unplacedText, type DecisionModelIo, type LogEntry, type SwitchIo } from '../core/report.ts'
29import { describeDefaults, keySource, removedDecisionModel, type Ctx } from '../core/setup.ts'
30import { defineSwitch, isOn, keepSwitch, listSwitches, loadOverrides, masterOn, setMaster, setSwitch, SWITCHES_KEY } from '../core/switches.ts'
31import { errorText } from '../decision/backend.ts'
32import { PANE_COLUMNS, PANE_ID, PANE_TITLE } from '../board/rationale.ts'
33
34const LOCK = { plugin: 'dispatch-pilot', key: 'lock' } as const
35const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
36const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
37
38export function registerControl(on: On, ctx: Ctx): void {
39  defineSwitch({ name: 'signals', info: '把上下文、限额和花费的读数记进 debug log,不参与任何决策' })
40
41  // Under a match-all matcher: other features set themselves up at session start too.
42  on('session.start', { cwd: /(?:)/ }, async ($, e, next) => {
43    // The person's switches first: the features beneath read them while the session starts.
44    loadOverrides(await $.store.get(SWITCHES_KEY).catch(() => undefined))
45    // The environment's keys (the options' come first), for the requests that follow; never written down, only where they came from.
46    // Read before anything is said of the decision model: whether it is pplx or Jev, and who takes images, depends on them (core/setup.ts, `Ctx`).
47    ctx.secrets.perplexityEnvKey = ((await $.env.get('PERPLEXITY_API_KEY').catch(() => undefined)) ?? '').trim()
48    ctx.secrets.typesafeEnvKey = ((await $.env.get('TYPESAFE_API_KEY').catch(() => undefined)) ?? '').trim()
49    // Which options the decision model's defaults decided (core/setup.ts BACKEND_DEFAULTS).
50    $.ui.log(describeDefaults(ctx.config), { to: 'debug' })
51    const modelIo: DecisionModelIo = {
52      board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
53      decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
54      debug: (line) => $.ui.log(line, { to: 'debug' }),
55    }
56    // Jev decides only for want of a Perplexity key: the decision log says so (ADR 0006), where the person looks for why.
57    if (ctx.fellBack) await report(modelIo, { fellBack: { asked: 'pplx', using: 'jev' } })
58    // The model that takes images (#56, ADR 0008) is chosen by the keys alone: pplx for want of a TypeSafe key is said once; none, in the debug log.
59    const images = ctx.images
60    if (images === null) $.ui.log('images: no decision model takes them (no TypeSafe or Perplexity key)', { to: 'debug' })
61    else if (images.fellBack) await report(modelIo, { fellBack: { asked: 'jev', using: images.name, for: 'images' } })
62    if (ctx.config.backend === 'pplx') $.ui.log(`pplx key: ${keySource(ctx.config.perplexityApiKey, ctx.secrets.perplexityEnvKey, 'PERPLEXITY_API_KEY')}`, { to: 'debug' })
63    // Jev's key serves the decisions when Jev decides and the images when Jev takes them (whatever decides the rest).
64    if (ctx.config.backend === 'jev' || images?.name === 'jev') $.ui.log(`jev key: ${keySource(ctx.config.typesafeApiKey, ctx.secrets.typesafeEnvKey, 'TYPESAFE_API_KEY')}`, { to: 'debug' })
65    // A decisionModel left over in the person's settings that names a model since removed: the engine reads it as the default.
66    const removed = removedDecisionModel(await $.settings.read({ source: 'user' }).catch(() => undefined))
67    if (removed !== null) $.ui.log(`decisionModel ${removed} 已移除,按没设处理`, { to: 'debug' })
68    const result = await next(e)
69    await $.command
70      .register({
71        name: 'dp',
72        description: 'Dispatch Pilot:依据面板、功能开关、effort 锁定、最近的决定',
73        argumentHint: '[log | status | on|off | <name> on|off | lock <effort> | unlock | log N]',
74        immediate: true,
75      })
76      .catch((error) => $.ui.log(`/dp was not registered: ${errorText(error)}`, { to: 'debug' }))
77    return result
78  })
79
80  // `window` is in every measurement: a matcher on a field that is always there.
81  on('session.measure', { context: { window: /(?:)/ } }, async ($, e, next) => {
82    if (isOn('signals')) {
83      try {
84        $.ui.log(describeSignals(e), { to: 'debug' })
85      } catch {
86        // a reading that cannot be written down is skipped
87      }
88    }
89    return next(e)
90  })
91
92  on('command.run', { command: 'dp' }, async ($, e) => {
93    const command = parseControl(e.args)
94    // The screens draw again: they leave out what a feature that is off owns.
95    const reporting: SwitchIo = { redraw: () => $.ui.invalidate('ui.render') }
96    // Keeps one switch as the person just flipped it, beside whatever another session saved meanwhile;
97    // says so when it cannot.
98    const save = async (name: string) =>
99      (await keepSwitch({ get: () => $.store.get(SWITCHES_KEY), set: (value) => $.store.set(SWITCHES_KEY, value) }, name)) ? '' : '(没有保存:本地存储用不了,只在这个会话里有效)'
100    try {
101      switch (command.kind) {
102        case 'pane': {
103          // `/dp` toggles; `/dp log` only opens (and asks for the keys again).
104          if (command.toggle && (await $.ui.panes()).some((pane) => pane.id === PANE_ID)) {
105            await $.ui.close({ id: PANE_ID })
106            return { text: '依据面板已关闭' }
107          }
108          const keys = await takesKeys($)
109          // `focus` is true or left out (the host's check).
110          const opened = await $.ui.open({ id: PANE_ID, title: PANE_TITLE, ...(keys ? { focus: true as const } : {}), closeOnEscape: true, columns: PANE_COLUMNS })
111          if (opened.isPlaced) return { text: keys ? '依据面板已打开:p / n 翻看 agent,Esc 关闭' : '依据面板已打开' }
112          await $.ui.close({ id: PANE_ID })
113          return { text: unplacedText(opened.reason) }
114        }
115        case 'status': {
116          const { value: lock = null } = await $.state.get(LOCK)
117          return { text: describeStatus(lock) }
118        }
119        case 'master':
120          setMaster(command.on)
121          await report(reporting, { switched: true })
122          return { text: `Dispatch Pilot 已${command.on ? '打开' : '关闭'}${await save('master')}` }
123        case 'switch': {
124          const spec = listSwitches().find((s) => s.name === command.name)
125          if (spec === undefined || !setSwitch(command.name, command.on)) {
126            const names = listSwitches().map((s) => s.name).join(', ')
127            return { text: `没有叫「${command.name}」的开关(现有:${names})` }
128          }
129          await report(reporting, { switched: true })
130          return { text: `${spec.name} 已${command.on ? '打开' : '关闭'}:${spec.info}${await save(spec.name)}` }
131        }
132        case 'lock': {
133          await $.state.set(LOCK, command.effort)
134          const inert = masterOn() ? '' : '(Dispatch Pilot 关着:/dp on 才生效)'
135          return { text: `主 agent 已锁在 ${command.effort}:每一步都用这一档${inert};/dp unlock 解除` }
136        }
137        case 'unlock':
138          await $.state.set(LOCK, null)
139          return { text: '已解除锁定,effort 回到按决定走' }
140        case 'log': {
141          const { value: kept = [] } = await $.state.get(DECISIONS)
142          return { text: describeDecisions(kept.slice(-command.count)) }
143        }
144        case 'unknown':
145          return { text: `没看懂这条命令。\n${USAGE}` }
146      }
147    } catch (error) {
148      // Always answer: a failing command must not leave the person without a word.
149      return { text: `出错了(${errorText(error)})` }
150    }
151  })
152}
153
154/** Whether the pane takes the keyboard: where the session has a terminal, or where it does not say where it draws. */
155async function takesKeys($: EngineInterface): Promise<boolean> {
156  const surfaces: readonly RenderSurface[] = await $.session.surfaces().catch(() => [])
157  return surfaces.length === 0 || surfaces.includes('terminal')
158}
159
160type Control =
161  | { kind: 'pane'; toggle: boolean }
162  | { kind: 'status' }
163  | { kind: 'master'; on: boolean }
164  | { kind: 'switch'; name: string; on: boolean }
165  | { kind: 'lock'; effort: Effort }
166  | { kind: 'unlock' }
167  | { kind: 'log'; count: number }
168  | { kind: 'unknown' }
169
170/** The words after `/dp`, case and spacing aside. */
171function parseControl(args: string): Control {
172  const words = args.trim().toLowerCase().split(/\s+/).filter(Boolean)
173  const [first, second] = words
174  if (words.length === 0) return { kind: 'pane', toggle: true }
175  if (words.length === 1 && first === 'status') return { kind: 'status' }
176  if (words.length === 1 && (first === 'on' || first === 'off')) return { kind: 'master', on: first === 'on' }
177  if (words.length === 1 && first === 'unlock') return { kind: 'unlock' }
178  if (words.length === 2 && first === 'lock' && second === 'off') return { kind: 'unlock' }
179  if (words.length === 2 && first === 'lock' && isEffort(second)) return { kind: 'lock', effort: second }
180  if (words.length === 1 && first === 'log') return { kind: 'pane', toggle: false }
181  if (words.length === 2 && first === 'log' && /^[1-9]\d*$/.test(second ?? '')) return { kind: 'log', count: Math.min(LOG_ENTRIES, Number(second)) }
182  if (words.length === 2 && first !== undefined && (second === 'on' || second === 'off')) return { kind: 'switch', name: first, on: second === 'on' }
183  return { kind: 'unknown' }
184}
185
186const USAGE = `/dp(依据面板) | /dp status | /dp on|off | /dp <功能名> on|off | /dp lock <${EFFORTS.join('|')}> | /dp unlock | /dp log N`
187
188/** `/dp status`'s answer: whether the mod is on, the lock, each feature's switch. */
189function describeStatus(lock: Effort | null): string {
190  const switches = listSwitches()
191  const width = Math.max(0, ...switches.map((s) => s.name.length))
192  return [
193    `Dispatch Pilot ${masterOn() ? '开着' : '关着'}。effort 锁定:${lock ?? '没有'}。`,
194    '功能开关(/dp <功能名> on|off):',
195    ...switches.map((s) => `  ${s.on ? '开' : '关'}  ${s.name.padEnd(width)}  ${s.info}`),
196    USAGE,
197  ].join('\n')
198}
199
200/** `/dp log N`'s answer: the decisions, oldest first, each with its reason. */
201function describeDecisions(entries: readonly LogEntry[]): string {
202  if (entries.length === 0) return '还没有记下任何决定'
203  const header = `最近 ${entries.length} 条决定,最新的在最后`
204  return [header, ...entries.map((entry) => `#${entry.n} ${entry.feature}:${decisionLine(entry)}`)].join('\n')
205}
206
207/** One measurement as a debug-log line: what the engine reported, `n/a` for what it has no figure for. */
208function describeSignals(measure: SessionMeasureInput): string {
209  const { context, rateLimits, cost } = measure
210  const fill = context.percent === undefined ? `n/a (window ${context.window})` : `${context.percent}% (${context.tokens ?? '?'}/${context.window} tokens)`
211  const limits = rateLimits.length === 0 ? 'n/a' : rateLimits.map((limit) => `${limit.kind} ${limit.percentUsed}%${limit.resetsAt === undefined ? '' : ` resets ${limit.resetsAt}`}`).join(', ')
212  const spent = cost === undefined ? 'n/a' : `$${cost.usd.toFixed(4)}`
213  return `signals: context ${fill}; limits ${limits}; cost ${spent}; changed ${measure.changed.join(', ')}`
214}
215
hooks/features/dispatched-agents.ts 204 lines
1// Feature: each agent the main agent dispatches gets its own decision on its
2// model and effort, once, when it is spawned (agent.spawn). The model is
3// rewritten on the spawn; the effort goes into the plan table under the
4// agent's id, and the core's turn.step writer sends it on every step of that
5// agent. The main agent's own model and cache are untouched (ADR 0001).
6//
7// The decision reads the person's own words this turn (`said`), so a model
8// they name for the work wins over the decision model, which wins over the
9// main agent's pick; it also reads the problem summary and the conversation
10// the agent is dispatched from, what the main agent wrote the brief out of
11// (BACKEND_DEFAULTS agentBackground). Agents dispatched together (one message,
12// several Agent calls) share one request (core/agent-lane.ts, ADR 0009): what
13// they share goes in once, each brief beside it. A failed or late answer lets
14// the agent start as the main agent asked.
15//
16// The main agent reads, after the Agent tool's result, the model and effort its
17// agent started with and whose choice the model was (#34): agent.spawn runs
18// inside the Agent tool call, under its id, so the spawn leaves the note for the
19// call to append.
20//
21// Its switch is `dispatched-agents` (`/dp dispatched-agents off`).
22
23import type { EngineInterface, HttpInit, On } from 'claude-code'
24import { timedOut, within, type Failure } from '../decision/backend.ts'
25import { conversationUpTo, messageText, type ContextMessage } from '../decision/context.ts'
26import { dispatchEvidence, dispatchNote, dispatchReason, modelFamily, termsOf, type DispatchNote } from '../decision/dispatched-agent.ts'
27import { quoteStart } from '../decision/redact.ts'
28import { problemBackground, readingBackground } from '../decision/workflow.ts'
29import { agentCallsBeside, askAgent, type AgentAnswer, type AgentInput, type LaneIo } from '../core/agent-lane.ts'
30import { update, type Cell } from '../core/plans.ts'
31import { isPersonsMessage } from '../core/prompts.ts'
32import { report, type ReportIo } from '../core/report.ts'
33import { dispatchSettings, saidTokens, type Ctx } from '../core/setup.ts'
34import { defineSwitch, isOn } from '../core/switches.ts'
35import { sessionReading } from './reference-hint.ts'
36import { UNRESOLVED_SWITCH } from './unresolved.ts'
37
38const AGENTS = { plugin: 'dispatch-pilot', key: 'agents' } as const
39const SAID = { plugin: 'dispatch-pilot', key: 'said' } as const
40const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
41const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
42const COUNT = { plugin: 'dispatch-pilot', key: 'unresolved' } as const
43const PPLX_RATE = { plugin: 'dispatch-pilot', key: 'pplxRate' } as const
44const READINGS = { plugin: 'dispatch-pilot', key: 'referenceReadings' } as const
45
46/** The switch's name, in `/dp` and in the decision log. */
47const SWITCH = 'dispatched-agents'
48/**
49 * The notes spawns left for their Agent tool calls, by the call's tool_use_id: written by the agent.spawn inside the
50 * call, taken as the call returns. A module variable (CLAUDE.md): the kit's `$.state` does not show the outer hook
51 * what the nested spawn wrote (measured in the kit, DEVELOPMENT.md 已实测的引擎行为; not yet on the engine), and a hot
52 * reload while an agent runs loses only that agent's note. At most MAX_NOTES are kept: past that (calls whose result never came
53 * back, or more agents running at once) the oldest go.
54 */
55const pendingNotes = new Map<string, string>()
56const MAX_NOTES = 32
57/** At most this many of the person's messages are kept for one turn. */
58const MAX_SAID = 8
59
60export function registerDispatchedAgents(on: On, ctx: Ctx): void {
61  defineSwitch({ name: SWITCH, info: '主 agent 派出 agent 时决定它的模型和 effort' })
62  const settings = dispatchSettings(ctx)
63
64  // The person's words this turn: a message sent while idle starts them
65  // afresh, one typed during the turn joins them. Other prompts (an agent's
66  // hand-back, a task notification) leave them as they are. Kept whatever the
67  // switches say (nothing is asked or changed here), so a decision made right
68  // after the person switches the feature back on still reads them.
69  on('prompt.submit', { text: /(?:)/ }, async ($, e, next) => {
70    const result = await next(e)
71    if (!isPersonsMessage(e) || result.drop !== undefined) return result
72    const words = messageText(e.text, saidTokens(ctx.config))
73    const said: Cell<string[]> = { get: () => $.state.get(SAID), set: (value, options) => $.state.set(SAID, value, options) }
74    await update(said, (list) => (e.turnId === undefined ? [words] : [...(list ?? []), words].slice(-MAX_SAID)))
75    return result
76  })
77
78  // The note the spawn left for its Agent tool call goes beside the tool's result; a call whose spawn left none (a fork,
79  // a teammate, a refused spawn) is answered as it is.
80  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
81    const result = await next(e)
82    const note = pendingNotes.get(e.tool_use_id)
83    pendingNotes.delete(e.tool_use_id)
84    if (note === undefined || result.deny !== undefined) return result
85    return { ...result, context: [...(result.context ?? []), note] }
86  })
87
88  on('agent.spawn', { tool_use_id: /(?:)/ }, async ($, e, next) => {
89    // A fork always runs on its parent's model. A teammate lives across many
90    // tasks that one decision at its spawn cannot see. A Workflow's agent is the
91    // Workflow features': workflow-agents wrote its call into the script, or
92    // workflow-labels routes it at this same spawn. A resumed run (2.1.299 on)
93    // goes on as its agent was decided: the engine keeps its model, and its plan
94    // is the one written here.
95    if (e.fork || e.isTeammate || e.workflow !== undefined || e.resume !== undefined) return next(e)
96    /** Leaves the note for the Agent tool call this spawn belongs to. */
97    const leaveNote = (note: DispatchNote) => {
98      pendingNotes.set(e.tool_use_id, dispatchNote(note))
99      while (pendingNotes.size > MAX_NOTES) pendingNotes.delete(pendingNotes.keys().next().value as string)
100    }
101    if (!isOn(SWITCH)) {
102      const started = await next(e)
103      if (started.deny === undefined) leaveNote({ routed: false, started: started.model, why: 'off' })
104      return started
105    }
106    const { value: said = [] } = await $.state.get(SAID)
107    // The problem the main agent is on goes along as background, with no hint (#41): the summary (the cheap model's, Haiku 5.5
108    // by default) and the count, while the unresolved switch is on and there are any.
109    const { value: held } = isOn(UNRESOLVED_SWITCH) ? await $.state.get(COUNT) : { value: undefined }
110    // The conversation the agent is dispatched from (the main one, or the dispatching agent's own): up to the Agent call
111    // where the decision model reads it (BACKEND_DEFAULTS agentBackground), and the Agent calls of the same message, which
112    // are asked about with it.
113    const recent = await conversationOf($, e.parentAgentId)
114    // What the session's reference images read as (#64): the latest reading, as text.
115    const reference = await sessionReading({ get: () => $.state.get(READINGS) }, (line) => $.ui.log(line, { to: 'debug' }))
116    const lines = !ctx.config.agents.background || recent.length === 0 ? [] : (conversationUpTo(recent, ctx.config.context.messages, e.tool_use_id) ?? conversationUpTo(recent, ctx.config.context.messages) ?? [])
117    const input: AgentInput = {
118      dispatch: { user_message: '', agent_type: e.subagentType, description: e.description, prompt: e.prompt, requested_model: e.model ?? null },
119      shared: {
120        words: said.join('\n'),
121        background: {
122          ...problemBackground(held, ctx.ask.language),
123          ...readingBackground(reference),
124          ...(lines.length === 0 ? {} : { recent: lines }),
125        },
126      },
127    }
128    const io: LaneIo = {
129      backend: {
130        fetch: (url: string, init: HttpInit) => $.http.fetch(url, init),
131        sleep: (ms: number, signal: AbortSignal) => $.clock.sleep(ms, { signal }),
132        pace: { now: () => $.clock.now(), sentAt: { get: () => $.state.get(PPLX_RATE), set: (value, options) => $.state.set(PPLX_RATE, value, options) } },
133      },
134      now: () => $.clock.now(),
135      debug: (line) => $.ui.log(line, { to: 'debug' }),
136    }
137    const reporting: ReportIo = {
138      board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
139      decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
140      debug: (line) => $.ui.log(line, { to: 'debug' }),
141      now: () => $.clock.now(),
142      toast: (text) => $.ui.toast(text),
143    }
144    const about = `${quoteStart(e.description)}(${e.subagentType})`
145    /** What every report of this agent says of it; its id is known once it has started (a spawn is not yet an agent). */
146    const reportOf = (agent: string) => ({ feature: SWITCH, agent, subject: about, node: { kind: 'agent' as const, name: e.name ?? (e.description === '' ? e.subagentType : e.description), type: e.subagentType } })
147    // Asked with the agents dispatched beside it (core/agent-lane.ts), which logs the request; it waits `agents.waitMs` at most.
148    const waitMs = ctx.config.agents.waitMs
149    const deadline = (await $.clock.now()) + waitMs
150    const call = { id: e.tool_use_id, siblings: agentCallsBeside(recent, e.tool_use_id) }
151    const late: AgentAnswer = { ok: false, failure: timedOut(waitMs) }
152    const asked = await within(io.backend.sleep, askAgent(ctx, settings, { key: `agent:${e.parentAgentId ?? 'main'}`, kind: 'agent', input, call, deadline, about: `agent ${about}`, io }), waitMs, late)
153    // The agent starts as the main agent asked; the board says why it was not routed, once it has an id to say it of.
154    // A spawn refused beneath started no agent: there is nothing to say of it.
155    const notRouted = async (failure: Failure) => {
156      const started = await next(e)
157      if (started.deny !== undefined) return started
158      await report(reporting, { decision: { ...reportOf(started.agentId ?? e.tool_use_id), routed: false, failure: { backend: ctx.backend.name, ...failure } } })
159      leaveNote({ routed: false, started: started.model, why: { failure, backend: ctx.backend.name } })
160      return started
161    }
162    if (!asked.ok) return notRouted(asked.failure)
163    const decision = asked.decision
164    // The main agent's pick, when it stands, goes on as the main agent wrote it.
165    const spawn = decision.model !== null && decision.model !== modelFamily(e.model) ? { ...e, model: decision.model } : e
166    const result = await next(spawn)
167    if (result.deny !== undefined) return result
168    leaveNote({ routed: true, decision, started: result.model, requested: modelFamily(e.model), thetaOverride: settings.thetaOverride })
169    // The agent has started: nothing after this may fail its spawn.
170    try {
171      // The effort and the person's terms go into the plan (what changes the agent later keeps to the
172      // terms); the model is set on the spawn, and a planned model would also pin every step against the
173      // engine's overload fallback.
174      const terms = termsOf(decision)
175      if (result.agentId !== undefined && (decision.effort !== null || terms !== null)) {
176        await $.state.set({ ...AGENTS, id: result.agentId }, { effort: decision.effort, floor: null, model: null, terms })
177      }
178      const family = decision.model ?? modelFamily(result.model)
179      const model = family ?? result.model
180      const outcome = decision.effort === null ? model : `${model} ${decision.effort}`
181      await report(reporting, {
182        decision: {
183          ...reportOf(result.agentId ?? e.tool_use_id),
184          routed: true,
185          outcome,
186          reason: dispatchReason(decision, modelFamily(e.model), settings.thetaOverride, '主 agent 指定的'),
187          ...dispatchEvidence(decision),
188          ...(family === null ? {} : { model: family }),
189          ...(decision.effort === null ? {} : { effort: decision.effort }),
190        },
191      })
192    } catch (error) {
193      $.ui.log(`agent ${about} started (${result.agentId ?? 'no id'}), but its plan was not recorded: ${String(error)}`, { to: 'debug' })
194    }
195    return result
196  })
197}
198
199/** The conversation of the loop `agentId` (absent: the main one), as the transcript rows; none when it cannot be read. */
200async function conversationOf($: EngineInterface, agentId: string | undefined): Promise<readonly ContextMessage[]> {
201  const read: unknown = await (agentId === undefined ? $.session.messages() : $.session.messages({ agentId })).catch(() => [])
202  return Array.isArray(read) ? (read as ContextMessage[]) : []
203}
204
hooks/features/escalation.ts 681 lines
1// Feature: a loop whose tool calls keep failing goes up a level (#7).
2//
3// Every tool call of the main agent and of the agents it dispatches is told
4// apart as it ends (core/outcomes.ts), and each loop's failures are counted
5// here, in one record (`escalation`) that the mid-turn re-decision (#5) sends
6// in its counts too: a call the person refused is no failure, one a hook
7// blocked counts toward escalating only with `hook-block-failures` on, and
8// the counts start over whenever this feature deals with them (a forced
9// raise, failures found expected, or nothing left to raise).
10//
11// When a loop's counted failures reach `escalateAfter`, the decision model is
12// asked at once, as the call that reaches them ends (story 18): the mid-turn
13// effort question with the trouble, and whether the failures are what the
14// work expects (a test written to fail first, a search that finds nothing).
15// The loop's next step takes the answer, waiting `rejudgeWaitMs` at most, as
16// a mid-turn re-decision does; an answer later than that is taken at a later
17// step. Expected: the counts start over and the answer is an ordinary
18// re-decision. Otherwise (also when no answer comes) the loop goes up: one
19// level (at most to xhigh) or straight to max, at most `escalateLimit` times
20// per turn (per run, for an agent); a haiku agent already at the top level
21// goes on as another model. The person's terms for an agent's work hold
22// (core/plans.ts `AgentPlan`).
23//
24// It sits above the mid-turn feature (the entry registers it first), so a
25// step's own mid-turn answer finds the raise already in the turn's plan and
26// cannot undercut it.
27
28import type { EngineInterface, HttpInit, On, TurnStepInput } from 'claude-code'
29import { describeAsked, errorText, failureLine, within, type BackendIo, type Failure } from '../decision/backend.ts'
30import { AGENT_MODELS, effortFloor, modelFamily, type AgentModel, type Terms } from '../decision/dispatched-agent.ts'
31import { briefOf, forcedTarget, readExpected, rowsFromTranscript, stepsFromRows, stuckRequest, traceRaise, troubleText, type RaiseMode, type TranscriptRow } from '../decision/escalation.ts'
32import { higherEffort, isEffort, probsOf, readEffort, readingText, type Effort, type EffortReading } from '../decision/effort.ts'
33import { contentLanguage, judgeMidturn, MIDTURN_LEVEL, midturnRecord, outcomeOf, verdictReason, type MidturnInput, type MidturnLimits, type MidturnPosition, type MidturnRules, type MidturnVerdict } from '../decision/midturn.ts'
34import { modelId, type ResolvedModel } from '../decision/model-ids.ts'
35import { quoteStart } from '../decision/redact.ts'
36import { answersFor } from '../decision/system-one.ts'
37import { endedAs, noteEnded, wasBlocked } from '../core/outcomes.ts'
38import { floorHeld, forced, MAIN, newTurn, redecided, replace, turnKey, update, type AgentPlan, type Cell, type TurnRecord } from '../core/plans.ts'
39import { report, type Decided, type ReportIo } from '../core/report.ts'
40import { redecisionWaitMs, type Ctx } from '../core/setup.ts'
41import { defineSwitch, isOn, masterOn } from '../core/switches.ts'
42
43const ESCALATION = { plugin: 'dispatch-pilot', key: 'escalation' } as const
44const TURNS = { plugin: 'dispatch-pilot', key: 'turns' } as const
45const AGENTS = { plugin: 'dispatch-pilot', key: 'agents' } as const
46const LOCK = { plugin: 'dispatch-pilot', key: 'lock' } as const
47const RUNS = { plugin: 'dispatch-pilot', key: 'workflowRuns' } as const
48const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
49const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
50const PPLX_RATE = { plugin: 'dispatch-pilot', key: 'pplxRate' } as const
51
52/** At most this many Workflow runs' directories are kept. */
53const MAX_RUNS = 8
54
55/** The feature's switch (`/dp escalation on|off`). */
56const SWITCH = 'escalation'
57/** Whether a call one of the person's hooks blocked counts as a failure (`/dp hook-block-failures on|off`); off by default. */
58const BLOCKS_SWITCH = 'hook-block-failures'
59
60/** One loop's failed calls and forced raises (`escalation` in types/index.d.ts): the main agent's for one turn, an agent's for its run. */
61type LoopRecord = {
62  /** The main turn the counts belong to; '' for an agent. */
63  turnId: string
64  /** Calls that failed, and calls a hook refused, since the loop began. */
65  failures: number
66  hookBlocks: number
67  /** The counts when they last started over: what is counted is the rest. */
68  base: Counted
69  /** Forced raises so far (failures found expected are not one). */
70  raises: number
71  /** The loop's latest step, the engine's effort and model on it: what a re-decision asked as a call ends reads. */
72  step: number | null
73  engine: Effort | null
74  model: string | null
75  /** The step a stuck re-decision was last asked for; null before the first. */
76  askedFor: number | null
77  /** An agent's step at its latest raise (the main agent's is its turn's `raisedAt`); null before one. */
78  raisedAt: number | null
79  /** The escalation switch was off when the loop was last seen: what was counted meanwhile is written off once it is back on. */
80  paused: boolean
81}
82
83type Counted = { failures: number; hookBlocks: number }
84
85/** What the feature runs with: the shared ctx and the options it reads. */
86type Settings = {
87  ctx: Ctx
88  /** Counted failures that make a loop stuck. */
89  after: number
90  mode: RaiseMode
91  /** Forced raises a loop gets at most. */
92  limit: number
93  /** The failures count as expected when the answer reaches this probability. */
94  thetaExpected: number
95  /** The model a failing haiku agent is switched to, as a step names it (the engine takes no alias for a step); null for none. */
96  haikuTo: ResolvedModel | null
97  /** `escalateHaikuTo` as written, for the log when it names no model. */
98  haikuToWritten: string
99  /** The models agents may run on: a ruled-out escalateHaikuTo gives way to the next of them up. */
100  models: readonly AgentModel[]
101  /** The mid-turn rules: what a raise the decision model itself suggests needs, and how an ordinary re-decision moves the level. */
102  rules: MidturnRules
103  limits: MidturnLimits
104  /** How long a step waits for a stuck re-decision not back yet. */
105  waitMs: number
106}
107
108/** What the decision model made of a stuck loop. */
109type Stuck = {
110  /** The effort answer; null when it was not asked or not answered. */
111  reading: EffortReading | null
112  /** The probability that the failures were expected; null without an answer. */
113  expected: number | null
114  /** Why the question went unanswered, when it did. */
115  failure: Failure | null
116  /** No transcript of the loop could be read: nothing was asked. */
117  unread: boolean
118}
119
120/**
121 * A stuck re-decision on its way, or answered and not yet taken, by loop id:
122 * asked for step `forStep` (of turn `turnId`, for the main agent), about the
123 * counts in `covered` (what starts over once it is dealt with). `answer`
124 * never rejects; once it resolves, `settled` holds it and `ms` how long it took.
125 * Promises cannot live in $.state: a reload drops them, and the loop's next
126 * step asks again.
127 */
128type Asking = { forStep: number; turnId: string; covered: Counted; about: string; answer: Promise<Stuck>; settled: Stuck | null; ms: number }
129const asking = new Map<string, Asking>()
130/**
131 * The loops a stuck re-decision is being set up for (before it is in `asking`). Taken before `launch`'s first await: the
132 * calls of one step that fail together reach it one after another with nothing awaited between, and only the first asks.
133 * A reload drops it with `asking`.
134 */
135const launching = new Set<string>()
136
137export function registerEscalation(on: On, ctx: Ctx): void {
138  defineSwitch({ name: SWITCH, info: '工具调用接连失败的 agent,强制升高它的 effort', parts: ['counts'] })
139  defineSwitch({ name: BLOCKS_SWITCH, info: '判断要不要强制升档时,把被你的 hook 拦下的调用也算失败', default: false })
140  // Read at each use: which decision model's settings these are is settled at the session start (core/setup.ts, `Ctx`).
141  const settings: Settings = {
142    ctx,
143    get after() {
144      return ctx.config.escalation.after
145    },
146    get mode() {
147      return ctx.config.escalation.mode
148    },
149    get limit() {
150      return ctx.config.escalation.limit
151    },
152    get thetaExpected() {
153      return ctx.config.escalation.thetaExpected
154    },
155    get haikuTo() {
156      return ctx.config.escalation.haikuTo
157    },
158    get haikuToWritten() {
159      return ctx.config.escalation.haikuToWritten
160    },
161    get models() {
162      return ctx.config.agents.models
163    },
164    get rules() {
165      return ctx.config.midturn.rules
166    },
167    get limits() {
168      return ctx.config.midturn.limits
169    },
170    get waitMs() {
171      return ctx.config.midturn.waitMs
172    },
173  }
174
175  on('tool.call', { tool: /(?:)/ }, async ($, e, next) => {
176    const result = await next(e)
177    // The calls the model made, not another plugin's `$.tool.call`; counted while Dispatch Pilot is on, whatever this
178    // feature's switch says (the mid-turn re-decision sends the counts too).
179    if (next.origin.plugin !== 'engine' || !masterOn()) return result
180    try {
181      // A Workflow's run: its directory holds each of its agents' transcripts, which the engine keeps from the mod.
182      const run = e.tool === 'Workflow' ? launchedRun(result.result) : null
183      if (run !== null) {
184        const runs: Cell<{ runId: string; dir: string }[]> = { get: () => $.state.get(RUNS), set: (value, options) => $.state.set(RUNS, value, options) }
185        await update(runs, (list) => [...(list ?? []).filter((kept) => kept.runId !== run.runId), run].slice(-MAX_RUNS))
186      }
187      const ended = outcomeOf(e.tool, result, wasBlocked(e.tool_use_id))
188      noteEnded(e.tool_use_id, ended)
189      // A refusal by a plugin's tool.call hook (`{ deny }`) is nobody's failure and no settings hook's block: the
190      // Workflow feature's hand-back of a script is one. Only what the tool reported, and what the settings hooks refused, count.
191      if (typeof result.deny === 'string' || (ended !== 'failed' && ended !== 'blocked')) return result
192      const id = e.agentId ?? MAIN
193      const ref = { ...ESCALATION, id }
194      const cell: Cell<LoopRecord> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
195      const record = await update(cell, (r) => {
196        const loop = r ?? newLoop('')
197        return ended === 'failed' ? { ...loop, failures: loop.failures + 1 } : { ...loop, hookBlocks: loop.hookBlocks + 1 }
198      })
199      if (!isOn(SWITCH)) return result
200      await showCounts($, id, record, null)
201      // The call that reaches the threshold asks at once: the answer is for the loop's next step (once per step).
202      if (record.step !== null && record.askedFor !== record.step + 1) await launch($, settings, e.agentId, record, record.step + 1)
203    } catch (error) {
204      $.ui.log(`escalation: ${errorText(error)}`, { to: 'debug' })
205    }
206    return result
207  })
208
209  on('turn.step', { turnId: /(?:)/ }, async function* ($, e, next) {
210    if (masterOn()) {
211      try {
212        await atStep($, settings, e)
213      } catch (error) {
214        $.ui.log(`escalation: ${errorText(error)}`, { to: 'debug' })
215      }
216    }
217    return yield* next(e)
218  })
219}
220
221/**
222 * At a loop's step: keeps where the loop is (a new main turn starts its counts
223 * afresh), then takes the stuck re-decision meant for this step and applies
224 * it. With none on its way while the counted failures call for one (nothing
225 * to raise when the call ended, or a reload dropped the request), deals with
226 * them here: written off when nothing can be raised, else asked now.
227 */
228async function atStep($: EngineInterface, s: Settings, e: TurnStepInput): Promise<void> {
229  const main = e.agentId === undefined
230  const id = e.agentId ?? MAIN
231  const ref = { ...ESCALATION, id }
232  const cell: Cell<LoopRecord> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
233  const engine = isEffort(e.effort) ? e.effort : null
234  const enabled = isOn(SWITCH)
235  /** Whether a record belongs to an earlier main turn (or there is none): this step starts the turn's counts afresh. */
236  const startsTurn = (r: LoopRecord | undefined) => main && (r === undefined || r.turnId !== e.turnId)
237  const { before, after } = await replace(cell, (r) => {
238    const loop = startsTurn(r) || r === undefined ? newLoop(main ? e.turnId : '') : r
239    // Back on after being off: what was counted meanwhile is written off, so it is counted from here on.
240    const written = enabled && loop.paused ? { ...loop, base: { failures: loop.failures, hookBlocks: loop.hookBlocks }, paused: false } : loop
241    return { ...written, step: e.index, engine, model: e.model, paused: !enabled }
242  })
243  let record = after
244  if (startsTurn(before)) {
245    // A new main turn: what the one before counted, and asked, is over.
246    asking.delete(MAIN)
247    await showCounts($, MAIN, null, null)
248  }
249  if (!enabled) return
250
251  let pending = asking.get(id)
252  if (pending === undefined || (main && pending.turnId !== e.turnId) || pending.forStep > e.index) {
253    if (pending !== undefined) return
254    // No re-decision on its way, though the counted failures may call for one: nothing could be raised when
255    // the call ended, or a reload dropped the request. Dealt with here: written off, or asked now.
256    const counted = countedOf(record)
257    if (counted.failures + counted.hookBlocks < s.after || record.raises >= s.limit || record.askedFor === e.index || s.ctx.backend.configured === false) return
258    record = await update(cell, (r) => ({ ...(r ?? record), askedFor: e.index }))
259    const raise = await raiseOf($, s, e.agentId, record, e.index)
260    if (raise.kind === 'none') return
261    if (raise.kind === 'keep') {
262      const kept = await startOver($, cell, id, countedNow(record), false)
263      const brief = e.agentId === undefined ? '' : briefOf((await agentRows($, e.agentId)) ?? [])
264      await decide($, id, kept, { outcome: raise.outcome, about: aboutOf(e.agentId, brief, e.index, counted), reason: raise.reason, tone: 'info' })
265      return
266    }
267    await launch($, s, e.agentId, record, e.index)
268    pending = asking.get(id)
269    if (pending === undefined) return
270  }
271  const answer = pending.settled ?? (await within((ms, signal) => $.clock.sleep(ms, { signal }), pending.answer, s.waitMs, null))
272  if (answer === null) {
273    // Not back yet: the step goes as it is, and the answer is taken at a later step (as a mid-turn re-decision's).
274    await showCounts($, id, record, 'late')
275    return
276  }
277  asking.delete(id)
278  await apply($, s, e, cell, pending.covered, pending.about, answer)
279}
280
281/** What a stuck loop's re-decision would do, from where the loop stands. */
282type Raise =
283  /** Leave the loop be: the person's lock holds the main agent's effort, or the step takes no effort level. */
284  | { kind: 'none' }
285  /** Nothing to raise: the failures are written off, and the decision recorded. */
286  | { kind: 'keep'; outcome: string; reason: string }
287  /** A higher effort, from `current`. */
288  | { kind: 'level'; current: Effort; target: Effort }
289  /** Another model (a haiku agent at the top level). */
290  | { kind: 'model'; from: string; to: ResolvedModel; note: string }
291
292/**
293 * What raising the loop would be at step `at`, by its plan: the main agent's
294 * turn (unless the person locked its effort), or an agent's effective model
295 * (the plan's, else the engine's) and the person's terms for its work.
296 */
297async function raiseOf($: EngineInterface, s: Settings, agentId: string | undefined, record: LoopRecord, at: number): Promise<Raise> {
298  const top = (current: Effort) => ({ kind: 'keep' as const, outcome: `effort ${current}(保持)`, reason: s.mode === 'max' ? '已经是 max' : '升一档最高到 xhigh' })
299  if (agentId === undefined) {
300    const { value: lock = null } = await $.state.get(LOCK)
301    if (lock !== null || record.engine === null) return { kind: 'none' }
302    const { value: turn } = await $.state.get({ ...TURNS, id: turnKey(record.turnId, undefined) })
303    const current = higherEffort(turn?.effort ?? record.engine, floorHeld(turn, at)) as Effort
304    const target = forcedTarget(current, s.mode)
305    return target === null ? top(current) : { kind: 'level', current, target }
306  }
307  const { value: planned } = await $.state.get({ ...AGENTS, id: agentId })
308  const model = planned?.model ?? record.model ?? ''
309  const family = modelFamily(model)
310  // A model the mod does not know, and that takes no effort level: nothing to raise.
311  if (family === null && record.engine === null) return { kind: 'none' }
312  const named = planned?.terms?.effort ?? null
313  // Without a level of its own (moved off a model that takes none), its steps go at the engine's own for an agent: medium (measured on 2.1.289).
314  const current = higherEffort(planned?.effort ?? record.engine ?? 'medium', planned?.floor ?? null) as Effort
315  const target = named === null ? forcedTarget(current, s.mode) : null
316  // A haiku agent goes up a level like any other; at the top (or held at the effort the person named) it goes on as another model.
317  if (family === 'haiku' && target === null) {
318    const to = haikuSwitch(s, planned?.terms ?? null)
319    if (!('why' in to)) return { kind: 'model', from: model, to: to.to, note: to.note }
320    if (named === null) return { kind: 'keep', outcome: `effort ${current}(保持)`, reason: `${top(current).reason},${to.why}` }
321  }
322  if (named !== null) return { kind: 'keep', outcome: `effort ${named}(保持)`, reason: `${named} 是你给它点名的 effort` }
323  return target === null ? top(current) : { kind: 'level', current, target }
324}
325
326/**
327 * Sends the stuck re-decision for the loop's step `forStep`, when its counted
328 * failures call for one and there is something to raise; the answer waits in
329 * `asking` for that step. Once per step, one at a time per loop.
330 */
331async function launch($: EngineInterface, s: Settings, agentId: string | undefined, record: LoopRecord, forStep: number): Promise<void> {
332  const id = agentId ?? MAIN
333  const counted = countedOf(record)
334  if (counted.failures + counted.hookBlocks < s.after || record.raises >= s.limit || s.ctx.backend.configured === false || asking.has(id) || launching.has(id)) return
335  launching.add(id)
336  try {
337    await send($, s, id, agentId, record, forStep, counted)
338  } finally {
339    launching.delete(id)
340  }
341}
342
343/** What `launch` does once it holds the loop: the question about its trouble, its answer left in `asking`. */
344async function send($: EngineInterface, s: Settings, id: string, agentId: string | undefined, record: LoopRecord, forStep: number, counted: Counted): Promise<void> {
345  const raise = await raiseOf($, s, agentId, record, forStep)
346  if (raise.kind !== 'level' && raise.kind !== 'model') return
347  const ref = { ...ESCALATION, id }
348  const cell: Cell<LoopRecord> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
349  await update(cell, (r) => ({ ...(r ?? record), askedFor: forStep }))
350  // What the counts say since they last started over, and what they start over from once this is dealt with.
351  const since = { failures: record.failures - record.base.failures, hookBlocks: record.hookBlocks - record.base.hookBlocks }
352  const entry: Asking = { forStep, turnId: record.turnId, covered: countedNow(record), about: '', answer: Promise.resolve(UNREAD), settled: null, ms: 0 }
353
354  let input: MidturnInput
355  if (agentId === undefined) {
356    const { value: turn } = await $.state.get({ ...TURNS, id: turnKey(record.turnId, undefined) })
357    const plan = turn ?? newTurn('', null, false)
358    const rows = (await $.session.messages().catch(() => [])) as TranscriptRow[]
359    entry.about = aboutOf(undefined, '', forStep, counted)
360    input = {
361      message: plan.prompt,
362      step: forStep,
363      current_effort: raise.kind === 'level' ? raise.current : 'medium',
364      counts: { judgments: plan.decisions, changes: plan.changes, failures: since.failures, hook_blocks: since.hookBlocks },
365      recent_steps: stepsFromRows(rows, { language: contentLanguage(plan.prompt), ended: endedAs }),
366      trouble: troubleText(counted),
367    }
368  } else {
369    const rows = await agentRows($, agentId)
370    const brief = rows === null ? '' : briefOf(rows)
371    entry.about = aboutOf(agentId, brief, forStep, counted)
372    if (rows === null) {
373      // No transcript to read (a workflow agent whose run the mod did not record): raised without asking.
374      entry.settled = UNREAD
375      asking.set(id, entry)
376      return
377    }
378    input = {
379      message: brief,
380      step: forStep,
381      current_effort: raise.kind === 'level' ? raise.current : 'medium',
382      counts: { judgments: 1 + record.raises, changes: record.raises, failures: since.failures, hook_blocks: since.hookBlocks },
383      recent_steps: stepsFromRows(rows, { language: contentLanguage(brief), ended: endedAs }),
384      trouble: troubleText(counted),
385    }
386  }
387  // A haiku agent switched to another model: only whether its failures were expected is asked.
388  const { request, effortPart, expectedPart } = stuckRequest(input, { limits: s.limits, ask: s.ctx.ask, effort: raise.kind === 'level' })
389  const io: BackendIo = {
390    fetch: (url: string, init: HttpInit) => $.http.fetch(url, init),
391    sleep: (ms: number, signal: AbortSignal) => $.clock.sleep(ms, { signal }),
392    pace: { now: () => $.clock.now(), sentAt: { get: () => $.state.get(PPLX_RATE), set: (value, options) => $.state.set(PPLX_RATE, value, options) } },
393  }
394  const startedAt = await $.clock.now()
395  // As long as a long request may take, as a mid-turn re-decision's: the step waits for it only `rejudgeWaitMs`.
396  entry.answer = s.ctx.backend.ask(io, request, redecisionWaitMs(s.ctx.config)).then(async (asked): Promise<Stuck> => {
397    entry.ms = (await $.clock.now()) - startedAt
398    $.ui.log(`request [${Object.keys(request.questions).join(', ')}] for ${entry.about} to ${s.ctx.backend.name}: ${describeAsked(asked, entry.ms)}`, { to: 'debug' })
399    let stuck: Stuck = { reading: null, expected: null, failure: null, unread: false }
400    if (!asked.ok) stuck = { ...stuck, failure: asked.failure }
401    else {
402      const expected = readExpected(answersFor(expectedPart, asked.answers))
403      stuck = {
404        reading: effortPart === null ? null : readEffort(answersFor(effortPart, asked.answers)[MIDTURN_LEVEL]),
405        expected,
406        failure: expected === null ? { kind: 'parse', detail: 'no answer to the question' } : null,
407        unread: false,
408      }
409    }
410    entry.settled = stuck
411    return stuck
412  })
413  asking.set(id, entry)
414}
415
416/** The answer when nothing could be asked: no transcript of the agent to read. */
417const UNREAD: Stuck = { reading: null, expected: null, failure: null, unread: true }
418
419/**
420 * Applies a stuck re-decision's answer at step `e`, to the loop as it stands
421 * now (a re-decision may have moved it since the question went out): expected
422 * failures leave an ordinary re-decision; otherwise the loop goes up (or, when
423 * it can no longer, its failures are written off). Either way the counts the
424 * question covered start over.
425 */
426async function apply($: EngineInterface, s: Settings, e: TurnStepInput, cell: Cell<LoopRecord>, covered: Counted, about: string, answer: Stuck): Promise<void> {
427  const id = e.agentId ?? MAIN
428  const { value: record } = await cell.get()
429  if (record === undefined) return
430  const raise = await raiseOf($, s, e.agentId, record, e.index)
431  if (raise.kind === 'none') return
432  if (raise.kind === 'keep') {
433    const kept = await startOver($, cell, id, covered, false)
434    await decide($, id, kept, { outcome: raise.outcome, about, reason: raise.reason, tone: 'info' })
435    return
436  }
437  const p = answer.expected
438  if (p !== null && p >= s.thetaExpected) {
439    const why = `这些失败是预期内的(概率 ${p.toFixed(2)},预期内失败门槛 ${s.thetaExpected.toFixed(2)}),不强制升档`
440    if (raise.kind === 'model') {
441      const kept = await startOver($, cell, id, covered, false)
442      await decide($, id, kept, { outcome: `model ${raise.from}(保持)`, about, reason: why, tone: 'info' })
443      return
444    }
445    // Expected: nothing is forced; the answer's effort is an ordinary re-decision, as mid-turn.
446    const level = await redecide($, s, e, record, raise.current, answer.reading)
447    const kept = await startOver($, cell, id, covered, false)
448    await decide($, id, kept, {
449      outcome: `effort ${level.effort}${level.effort === raise.current ? '(保持)' : `(原 ${raise.current})`}`,
450      about,
451      reason: level.why === null ? why : `${why};${level.why}`,
452      tone: level.effort === raise.current ? 'info' : 'ok',
453      ...(level.working === undefined
454        ? {}
455        : {
456            probs: probsOf(level.working.reading),
457            conf: level.working.verdict.confidence,
458            trace: [...level.working.verdict.trace.pick.steps, ...level.working.verdict.trace.steps],
459            mid: midturnRecord(level.working.verdict, level.working.position, s.rules),
460          }),
461    })
462    return
463  }
464
465  if (raise.kind === 'model') {
466    const ref = { ...AGENTS, id }
467    const planCell: Cell<AgentPlan> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
468    await update(planCell, (r) => ({ ...(r ?? { effort: null, floor: null, model: null, terms: null }), model: raise.to.id }))
469    const raised = await startOver($, cell, id, covered, true, e.index)
470    await decide($, id, raised, {
471      outcome: `model ${raise.to.id}(原 ${raise.from})`,
472      about,
473      reason: `haiku 的 effort 已经到顶,改用 ${raise.to.id}${raise.note};${knownReason(s, answer)}`,
474      tone: 'warn',
475      forced: { kind: 'model', from: raise.from, to: raise.to.id },
476    })
477    return
478  }
479  const { level, steps } = traceRaise(answer.reading, { from: raise.current, target: raise.target, mode: s.mode }, s.rules)
480  if (e.agentId === undefined) {
481    // Raised from this step on; for holdSteps steps nothing lowers it below the forced level, then ordinary re-decisions take over.
482    const ref = { ...TURNS, id: turnKey(e.turnId, undefined) }
483    const turnCell: Cell<TurnRecord> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
484    await update(turnCell, (r) => forced(r ?? newTurn('', null, false), level, raise.target, e.index, s.rules.holdSteps))
485  } else {
486    // The raise holds for the rest of the agent's run: nothing re-decides an agent mid-run, so it goes into its effort.
487    const ref = { ...AGENTS, id }
488    const planCell: Cell<AgentPlan> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
489    await update(planCell, (r) => ({ ...(r ?? { effort: null, floor: null, model: null, terms: null }), effort: level }))
490  }
491  const raised = await startOver($, cell, id, covered, true, e.index)
492  await decide($, id, raised, {
493    outcome: `effort ${level}(原 ${raise.current})`,
494    about,
495    reason: raiseReason(s, answer, level, raise.target),
496    tone: 'warn',
497    forced: { kind: 'effort', from: raise.current, to: level, floor: raise.target },
498    trace: steps,
499    ...(answer.reading === null ? {} : { probs: probsOf(answer.reading), ...(answer.reading.confidence === null ? {} : { conf: answer.reading.confidence }) }),
500  })
501}
502
503/**
504 * An ordinary re-decision from a stuck loop's effort answer, its failures
505 * found expected: the main agent's turn by the mid-turn rules (a turn the
506 * person started, as mid-turn), an agent's plan the same way. The level it
507 * goes on at, and why (null when there was nothing to decide from).
508 */
509async function redecide(
510  $: EngineInterface,
511  s: Settings,
512  e: TurnStepInput,
513  record: LoopRecord,
514  current: Effort,
515  reading: EffortReading | null,
516): Promise<{ effort: Effort; why: string | null; working?: { reading: EffortReading; verdict: MidturnVerdict; position: MidturnPosition } }> {
517  if (reading === null) return { effort: current, why: null }
518  if (e.agentId === undefined) {
519    const ref = { ...TURNS, id: turnKey(e.turnId, undefined) }
520    const turnCell: Cell<TurnRecord> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
521    const { value: turn } = await turnCell.get()
522    if (turn?.person !== true) return { effort: current, why: null }
523    const position = { current, sinceRaise: turn.raisedAt == null ? null : e.index - turn.raisedAt, atLeast: floorHeld(turn, e.index) }
524    const verdict = judgeMidturn(reading, position, s.rules)
525    await update(turnCell, (r) => redecided(r ?? turn, current, verdict.effort, e.index))
526    return { effort: verdict.effort, why: `${readingText(reading)};${verdictReason(verdict, position, s.rules)}`, working: { reading, verdict, position } }
527  }
528  const ref = { ...AGENTS, id: e.agentId }
529  const planCell: Cell<AgentPlan> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
530  const { value: plan } = await planCell.get()
531  // A routed agent's re-decision goes no lower than its model's floor either (effortFloor): its effort was decided with it.
532  const floor = higherEffort(plan?.floor ?? null, plan?.effort == null ? null : effortFloor(modelFamily(plan.model ?? record.model ?? '')))
533  const position = { current, sinceRaise: record.raisedAt === null ? null : e.index - record.raisedAt, atLeast: floor }
534  const verdict = judgeMidturn(reading, position, s.rules)
535  if (verdict.effort !== current) await update(planCell, (r) => ({ ...(r ?? { effort: null, floor: null, model: null, terms: null }), effort: verdict.effort }))
536  return { effort: verdict.effort, why: `${readingText(reading)};${verdictReason(verdict, position, s.rules)}`, working: { reading, verdict, position } }
537}
538
539/**
540 * The model a failing haiku agent goes on as: `escalateHaikuTo`, unless the
541 * person ruled it out for the agent's work, then the next model up that agents
542 * may run on and the person did not rule out. None (with why) when the person
543 * named haiku, when escalateHaikuTo names no model, or when every model up is
544 * ruled out.
545 */
546function haikuSwitch(s: Settings, terms: Terms | null): { to: ResolvedModel; note: string } | { why: string } {
547  if (terms?.model === 'haiku') return { why: 'haiku 是你给它点名的模型' }
548  const to = s.haikuTo
549  if (to === null) return { why: s.haikuToWritten === '' ? '没有设置失败的 haiku 改用哪个模型' : `设置的改用模型 ${JSON.stringify(s.haikuToWritten)} 这个 mod 不认识` }
550  const banned = terms?.banned ?? []
551  if (!banned.includes(to.family)) return { to, note: '' }
552  const up = AGENT_MODELS.slice(AGENT_MODELS.indexOf(to.family) + 1).find((family) => s.models.includes(family) && !banned.includes(family))
553  if (up !== undefined) return { to: { family: up, id: modelId(up) }, note: `(${to.family} 被你排除了)` }
554  const above = AGENT_MODELS.filter((family) => family !== 'haiku' && banned.includes(family))
555  return { why: `haiku 以上的模型都被你排除了(${above.join('、')})` }
556}
557
558/** The run a Workflow tool's result says it launched: its id and its directory; null for none (refused, failed). */
559function launchedRun(result: unknown): { runId: string; dir: string } | null {
560  if (typeof result !== 'object' || result === null) return null
561  const { runId, transcriptDir } = result as { runId?: unknown; transcriptDir?: unknown }
562  return typeof runId === 'string' && typeof transcriptDir === 'string' ? { runId, dir: transcriptDir } : null
563}
564
565/**
566 * An agent's transcript: as the session gives it, or for a workflow's agent
567 * (the engine keeps it from the mod) from the run's directory on disk, found
568 * among the runs this feature noted; null when neither can be read. The
569 * agent's own file says which run it is of: the run's journal holds every
570 * agent's result and past 4 MiB `$.fs.read` refuses it.
571 */
572async function agentRows($: EngineInterface, agentId: string): Promise<TranscriptRow[] | null> {
573  const found: unknown = await $.session.messages({ agentId }).catch(() => null)
574  if (Array.isArray(found)) return found as TranscriptRow[]
575  const { value: runs = [] } = await $.state.get(RUNS)
576  for (const run of [...runs].reverse()) {
577    const text = await $.fs.read(`${run.dir}/agent-${agentId}.jsonl`).catch(() => null)
578    if (text !== null) return rowsFromTranscript(text)
579  }
580  return null
581}
582
583/** What a decision about the loop is about: its step and the failures, and for an agent its task (`brief`, '' when unknown). */
584function aboutOf(agentId: string | undefined, brief: string, at: number, counted: Counted): string {
585  const failed = `工具调用失败 ${counted.failures + counted.hookBlocks} 次`
586  if (agentId === undefined) return `第 ${at} 步(${failed})`
587  return `${brief === '' ? `agent ${agentId}` : `agent ${quoteStart(brief)}`},第 ${at} 步(${failed})`
588}
589
590/** What the decision report needs of the host: its two cells, the debug log, the clock and the toast. */
591function ioOf($: EngineInterface): ReportIo {
592  return {
593    board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
594    decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
595    debug: (line) => $.ui.log(line, { to: 'debug' }),
596    now: () => $.clock.now(),
597    toast: (text) => $.ui.toast(text),
598  }
599}
600
601/** What a decision of this feature says, besides who it is about and the loop's counts (`decide` adds them). */
602type Said = Pick<Decided, 'outcome' | 'reason' | 'tone' | 'probs' | 'conf' | 'trace' | 'floor' | 'mid' | 'forced'> & { about: string }
603
604/**
605 * Reports a decision of this feature (debug log, `/dp log`, the board data), about loop `id`
606 * (`main`, or an agent's id) and with its counts as they stand. Beside the loop's own route: not on its node.
607 */
608async function decide($: EngineInterface, id: string, record: LoopRecord, said: Said): Promise<void> {
609  const { about, ...rest } = said
610  await report(ioOf($), {
611    decision: {
612      ...rest,
613      feature: SWITCH,
614      agent: id,
615      aside: true,
616      subject: about,
617      counts: { failed: record.failures, blocked: record.hookBlocks, raised: record.raises },
618    },
619  })
620}
621
622/** Why a forced raise went where it did, for the decision log. */
623function raiseReason(s: Settings, answer: Stuck, level: Effort, target: Effort): string {
624  const how = s.mode === 'max' ? '强制升到 max' : '强制升一档'
625  const higher = level === target ? '' : ',回答自己的判断更高'
626  return `${how}${higher};${knownReason(s, answer)}${answer.reading === null ? '' : `;${readingText(answer.reading)}`}`
627}
628
629/** Whether the failures were known to be expected, for the decision log: why they were not. */
630function knownReason(s: Settings, answer: Stuck): string {
631  if (answer.unread) return '读不到这个 agent 的记录,没有问这些失败是不是预期内的'
632  if (answer.expected !== null) return `不是预期内的失败(概率 ${answer.expected.toFixed(2)},预期内失败门槛 ${s.thetaExpected.toFixed(2)})`
633  return `决策模型没有回答(${failureLine(s.ctx.backend.name, answer.failure ?? { kind: 'parse', detail: 'no answer to the question' })})`
634}
635
636function newLoop(turnId: string): LoopRecord {
637  return { turnId, failures: 0, hookBlocks: 0, base: { failures: 0, hookBlocks: 0 }, raises: 0, step: null, engine: null, model: null, askedFor: null, raisedAt: null, paused: false }
638}
639
640/** The failures counted toward escalating: since the counts last started over, hook blocks only when they count. */
641function countedOf(record: LoopRecord): Counted {
642  return {
643    failures: record.failures - record.base.failures,
644    hookBlocks: isOn(BLOCKS_SWITCH) ? record.hookBlocks - record.base.hookBlocks : 0,
645  }
646}
647
648/** The counts as they stand: where they start over from once the failures are dealt with. */
649function countedNow(record: LoopRecord): Counted {
650  return { failures: record.failures, hookBlocks: record.hookBlocks }
651}
652
653/** The loop's counts start over from `covered` (a raise counts as one), and are shown. */
654async function startOver($: EngineInterface, cell: Cell<LoopRecord>, id: string, covered: Counted, raised: boolean, at?: number): Promise<LoopRecord> {
655  const record = await update(cell, (r) => ({
656    ...(r ?? newLoop('')),
657    base: { failures: Math.max(covered.failures, r?.base.failures ?? 0), hookBlocks: Math.max(covered.hookBlocks, r?.base.hookBlocks ?? 0) },
658    raises: (r?.raises ?? 0) + (raised ? 1 : 0),
659    ...(raised && at !== undefined ? { raisedAt: at } : {}),
660  }))
661  await showCounts($, id, record, null)
662  return record
663}
664
665/**
666 * Reports a loop's counts (on the board's node of it): the main agent's, or an agent's (null record: none yet, as
667 * at a new turn, whose node is a new one). `note`: `late`, a note for the band's event stream too.
668 */
669async function showCounts($: EngineInterface, id: string, record: LoopRecord | null, note: 'late' | null): Promise<void> {
670  await report(ioOf($), {
671    tally: {
672      feature: 'escalation',
673      agent: id,
674      failed: record?.failures ?? 0,
675      blocked: record?.hookBlocks ?? 0,
676      raised: record?.raises ?? 0,
677      ...(note === null ? {} : { late: true as const }),
678    },
679  })
680}
681
hooks/features/find-skill.ts 236 lines
1// Feature: find_skill (#12). Most skills are left out of the main agent's
2// listing (features/skills.ts, ADR 0002), so when, partway through a turn,
3// the work turns out to need a skill nobody suggested, the main agent can ask:
4// it calls the tool with a few words on the work, and the decision model rates
5// the session's skills against them, the same way it rates them beside a
6// message (the same ranker, `modRanker`, in the same two stages (#11), over the
7// same skills and their profiles, with the recent conversation read by the
8// same rules). Nothing is pushed: the skills come back only as the tool's
9// answer.
10//
11// Its switch is `find-skill` (`/dp find-skill off`), apart from `skills`
12// (spec #56). The tool stays registered whatever the switches say, with a
13// description that never changes (the tool list is part of the prompt cache);
14// switched off, it says so when called.
15
16import type { EngineInterface, HttpInit, On } from 'claude-code'
17import { type Asked, type BackendIo, describeAsked, errorText, failureText } from '../decision/backend.ts'
18import { turnStartState } from '../decision/context.ts'
19import { quoteStart } from '../decision/redact.ts'
20import { modRanker, pickSkills, skillOpening, type SkillPick, type SkillPolicy, type SkillRanking } from '../decision/skills.ts'
21import { answersFor, mergeParts, type DecisionRequest } from '../decision/system-one.ts'
22import { readSessionSkills } from '../core/profiles.ts'
23import { report, type ReportIo } from '../core/report.ts'
24import type { Ctx } from '../core/setup.ts'
25import { describeStages, rankingSettings, secondStageMs, type CatalogSkill } from '../core/skills.ts'
26import { defineSwitch, isOn, masterOn } from '../core/switches.ts'
27
28const CATALOG = { plugin: 'dispatch-pilot', key: 'skillCatalog' } as const
29const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
30const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
31const PPLX_RATE = { plugin: 'dispatch-pilot', key: 'pplxRate' } as const
32
33/** The switch's name, in `/dp` and in the decision log. */
34const SWITCH = 'find-skill'
35/** The skills feature's switch for profiles (#11): off, skills are rated by their descriptions here too. */
36const PROFILES = 'skill-profiles'
37/** The tool's name; the model calls it as `mcp__dispatch-pilot__find_skill`. */
38const TOOL = 'find_skill'
39const TOOL_CALLED = 'mcp__dispatch-pilot__find_skill'
40
41/** What the model reads about the tool. Fixed: nothing of the session goes into it. */
42const DESCRIPTION =
43  "Searches this session's skills for the ones that fit a piece of work, and returns each one's exact name, its relevance (0 to 1) and what it is for. Use it when the work at hand might have a skill you have not been shown: a file format, a service or its tooling, or a way of working such as reviewing, planning, testing or releasing. Load a skill it returns with the Skill tool by that exact name. Skills only the user can start are never returned."
44const INPUT = {
45  type: 'object',
46  properties: {
47    query: {
48      type: 'string',
49      description: 'The kind of work you need a skill for, in a few words, such as "fill in a form in a PDF file" or "review a branch before merging".',
50    },
51  },
52  required: ['query'],
53  additionalProperties: false,
54}
55/** How an answer that brings no skill ends: the main agent's way on. */
56const CARRY_ON = 'Carry on without it, or load a skill you know with the Skill tool by its exact name.'
57
58/**
59 * The session's skills: as read earlier this session (the skills feature
60 * reads them at its start), else read now, with the profiles the store holds
61 * (#11), and kept for the session; null when the session cannot be read.
62 */
63async function sessionCatalog($: EngineInterface, model: string): Promise<CatalogSkill[] | null> {
64  const { value } = await $.state.get(CATALOG)
65  if (value) return value.skills
66  const found = await readSessionSkills(
67    {
68      commands: () => $.command.list(),
69      listed: async () => (await $.session.usage({ breakdown: 'summary' })).context.breakdown?.skills?.skillFrontmatter ?? [],
70      overrides: async (source) => (await $.settings.read({ source })).skillOverrides,
71      home: () => $.env.get('HOME'),
72      cwd: () => $.session.cwd(),
73      exists: (path) => $.fs.exists(path),
74      read: (path) => $.fs.read(path),
75      list: (path) => $.fs.list(path),
76      get: (key) => $.store.get(key),
77    },
78    model,
79  )
80  if (found !== null) await $.state.set(CATALOG, { skills: found.skills })
81  return found?.skills ?? null
82}
83
84/** One decision request for find_skill through the person's decision model, its outcome in the debug log. */
85async function askLogged($: EngineInterface, ctx: Ctx, what: string, about: string, request: DecisionRequest, timeoutMs: number): Promise<Asked> {
86  const io: BackendIo = {
87    fetch: (url: string, init: HttpInit) => $.http.fetch(url, init),
88    sleep: (ms: number, signal: AbortSignal) => $.clock.sleep(ms, { signal }),
89    pace: { now: () => $.clock.now(), sentAt: { get: () => $.state.get(PPLX_RATE), set: (value, options) => $.state.set(PPLX_RATE, value, options) } },
90  }
91  const startedAt = await $.clock.now()
92  const asked = await ctx.backend.ask(io, request, timeoutMs)
93  const ms = (await $.clock.now()) - startedAt
94  $.ui.log(`${what} [${Object.keys(request.questions).join(', ')}] to ${ctx.backend.name} ${about}: ${describeAsked(asked, ms)}`, { to: 'debug' })
95  return asked
96}
97
98/** The opening of a catalog skill's SKILL.md for the ranking's second stage; null when it has no file. */
99async function openingOf($: EngineInterface, catalog: readonly CatalogSkill[], name: string): Promise<string | null> {
100  const file = catalog.find((skill) => skill.name === name)?.file ?? null
101  return file === null ? null : skillOpening(await $.fs.read(file))
102}
103
104export function registerFindSkill(on: On, ctx: Ctx): void {
105  defineSwitch({ name: SWITCH, info: '回答主 agent 的 find_skill:挑出适合它说的那项工作的 skill' })
106
107  /** Skills never offered (the option the skills feature reads too). */
108  const neverSuggested = new Set(ctx.config.skills.neverSuggested)
109  const policy = (): SkillPolicy => ctx.config.skills.find
110  /** How the mod's ranker ranks: the settings it rates the skills beside each message with. */
111  const rankBy = rankingSettings(ctx)
112  /** The model whose profiles the skills are offered by (#11). */
113  const model = ctx.config.skills.profileModel
114
115  // Registered once every plugin is loaded, under a match-all matcher (other
116  // features set themselves up at session start too). Without a decision
117  // model nothing could rate the skills, and the main agent keeps its listing.
118  on('session.start', { cwd: /(?:)/ }, async ($, e, next) => {
119    const result = await next(e)
120    if (ctx.backend.configured === false) return result
121    try {
122      // In the prompt's tool list (2.1.293 on; older engines put it behind ToolSearch, as the listing's hint allows for):
123      // the main agent's skill listing is cut short, and this is its way to the rest. Its description never changes.
124      const { tool } = await $.tool.register({ name: TOOL, description: DESCRIPTION, inputSchema: INPUT, isDeferred: false })
125      if (tool !== TOOL_CALLED) $.ui.log(`find_skill is registered as ${tool}, but the hook answers ${TOOL_CALLED}: its calls will fail`, { to: 'debug' })
126    } catch (error) {
127      $.ui.log(`find_skill was not registered: ${errorText(error)}`, { to: 'debug' })
128    }
129    return result
130  })
131
132  // The model's call: answered here, never passed on. Whatever goes wrong,
133  // the answer says so at once (fail open: the turn goes on without a skill).
134  on('tool.call', { tool: TOOL_CALLED }, async ($, e) => {
135    if (!masterOn()) return { result: `Dispatch Pilot is switched off (/dp on turns it back on), so find_skill rated no skills. ${CARRY_ON}` }
136    if (!isOn(SWITCH)) return { result: `find_skill is switched off (/dp ${SWITCH} on turns it back on), so it rated no skills. ${CARRY_ON}` }
137    // A dispatched agent's listing is left whole (ADR 0002): it has every skill in view.
138    if (e.agentId !== undefined) {
139      return { result: "find_skill rates skills for the main agent, whose skill listing is cut short. Yours lists this session's skills: pick from it and load one with the Skill tool by its exact name." }
140    }
141    const query = typeof e.query === 'string' ? e.query.replace(/\s+/g, ' ').trim() : ''
142    if (query === '') return { result: 'find_skill needs a query: a few words on the kind of work you need a skill for.' }
143    const io: ReportIo = {
144      board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
145      decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
146      debug: (line) => $.ui.log(line, { to: 'debug' }),
147      now: () => $.clock.now(),
148      toast: (text) => $.ui.toast(text),
149    }
150    // The main agent's own call, beside its decision for the turn: in the log, not on its node.
151    const call = { feature: SWITCH, agent: 'main', aside: true as const }
152    try {
153      // The skills the main agent can load, as a message asks about them: their question of stage
154      // one is the very one beside a message (those only the person can start have one of their
155      // own, which is not asked: they never come back); each by its profile, as beside a message,
156      // unless profiles are switched off.
157      const known = await sessionCatalog($, model)
158      const candidates = known?.filter((skill) => skill.by === 'model' && !neverSuggested.has(skill.name)).map((skill) => (isOn(PROFILES) ? skill : { ...skill, profile: null })) ?? null
159      if (candidates === null) {
160        await report(io, { decision: { ...call, skipped: 'unread' as const } })
161        return { result: `find_skill could not read this session's skills. ${CARRY_ON}` }
162      }
163      const about = `for find_skill ${quoteStart(query)}`
164      const ranker = modRanker(
165        {
166          ask: (request, timeoutMs) => askLogged($, ctx, 'second request', about, request, timeoutMs),
167          opening: (option) => openingOf($, candidates, option.name),
168        },
169        rankBy,
170      )
171      // The first request offers each skill by its profile where the decision model can read them all in time
172      // (BACKEND_DEFAULTS findSkillProfiles), else by its description; the second re-reads by both.
173      const part = ranker.part(ctx.config.skills.findByProfile ? candidates : candidates.map((skill) => ({ ...skill, profile: null })))
174      if (part === null) {
175        await report(io, { decision: { ...call, skipped: 'none' as const } })
176        return { result: `This session has no skill that find_skill could return. ${CARRY_ON}` }
177      }
178
179      // The same state as beside a message, the work named in place of the message; the ranker's second
180      // request (#11) asks about the same. Both requests share one wait: the second gets what the first left
181      // of it, and with Jev 800 ms at least (core/skills.ts secondStageMs). The wait is the decision model's (findWaitMs: a message's timeoutMs with Jev),
182      // within the hook's own 10 s.
183      const waitMs = ctx.config.skills.findWaitMs
184      const startedAt = await $.clock.now()
185      const messages = ctx.config.context.messages > 0 ? await $.session.messages().catch(() => []) : []
186      const request = mergeParts(turnStartState({ prompt: query, messages, limits: ctx.config.context }), [part])
187      const asked = await askLogged($, ctx, 'request', about, request, waitMs)
188      const left = secondStageMs(waitMs, (await $.clock.now()) - startedAt, ctx.config.skills.secondStageMs)
189      const ranked = asked.ok ? await ranker.rank(answersFor(part, asked.answers), candidates, { state: request.state, timeoutMs: left }) : null
190      const unranked = { kind: 'parse' as const, detail: 'no answer about the skills' }
191      const lost = !asked.ok ? asked.failure : ranked === null ? unranked : ranked.failed
192      if (ranked === null || lost !== undefined) {
193        const failure = lost ?? unranked
194        const why = failureText(ctx.backend.name, failure)
195        await report(io, { decision: { ...call, failure: { backend: ctx.backend.name, ...failure } } })
196        return { result: `find_skill could not rate the skills (${why}). ${CARRY_ON}` }
197      }
198
199      // Only skills the main agent can load were asked about, and they alone can come back.
200      const { suggest } = pickSkills(ranked, candidates, policy())
201      const names = suggest.map((skill) => skill.name).join('、')
202      await report(io, {
203        decision: {
204          ...call,
205          subject: quoteStart(query),
206          outcome: suggest.length > 0 ? `查到 ${names}` : '没查到 skill',
207          reason: describeRanking(ranked, policy()),
208          tone: suggest.length > 0 ? 'ok' : 'info',
209          skills: { suggest: suggest.map(({ name, relevance }) => ({ name, relevance })), try: [] },
210        },
211      })
212      return { result: found(query, suggest, policy()) }
213    } catch (error) {
214      $.ui.log(`find_skill failed: ${errorText(error)}`, { to: 'debug' })
215      await report(io, { decision: { ...call, skipped: 'error' as const } })
216      return { result: `find_skill could not rate the skills (an error in Dispatch Pilot, written to the debug log). ${CARRY_ON}` }
217    }
218  })
219}
220
221/** Why: what each stage of the ranking said (`describeStages`), and the bar a skill had to reach. */
222function describeRanking(ranking: SkillRanking, policy: SkillPolicy): string {
223  return `${describeStages(ranking)};相关度 ${policy.minRelevance.toFixed(2)} 起返回,最多 ${policy.max} 个`
224}
225
226/** The answer: the skills that fit, each by name, relevance and description, most relevant first; or that none does. */
227function found(query: string, suggest: readonly SkillPick[], policy: SkillPolicy): string {
228  if (suggest.length === 0) {
229    return `No skill fits "${query}": none reached relevance ${policy.minRelevance.toFixed(2)}. Carry on without one, try other words for the work, or load a skill you know with the Skill tool by its exact name.`
230  }
231  return [
232    `Skills that fit "${query}", rated by Dispatch Pilot’s decision model (relevance 0 to 1), most relevant first. Load one with the Skill tool by its exact name if it fits the work:`,
233    ...suggest.map((skill) => `- ${skill.name} (relevance ${skill.relevance.toFixed(2)})${skill.description ? `: ${skill.description}` : ''}`),
234  ].join('\n')
235}
236
hooks/features/image-routing.ts 263 lines
1// Feature: image routing (#63, ADR 0008), the first half. When the person's message comes with reference images, its effort is
2// decided from what the images read as, not from the words alone: how complex it is to build what they show.
3//
4// The switch is `image-routing` (`/dp image-routing on`), off by default: the images leave the machine for the decision model.
5//
6// The effort question of such a message is not in its ballot (features/main-effort.ts hands it to core/deferred.ts instead). The
7// images are not in `prompt.submit` (it carries their metadata only), they are in the message's row when the engine appends it
8// (`session.append`, door `prompt`; the row also names the file the original is in). So the decision waits for the turn:
9//   1. session.append  notes the message's images (their files, or their bytes when no file is named), not the whole conversation.
10//   2. turn.start      reads the images (core/complexity.ts: a request to the decision model that takes images, at most ~3 s, a
11//                      group asked only once), then sends the effort question with the reading in its state, as any message's,
12//                      and writes the answer as a pending decision, which the core claims in this same `turn.start`: the first
13//                      step goes out at that effort. The core stays the one writer of the plan (ADR 0003).
14// Whatever goes wrong with the reading, the effort is decided without it; when the effort request fails, the turn goes out
15// unrouted, and says why (the main-effort feature's report). A lock, and an effort or a model the person named, still come
16// first: the plan table's priorities are not touched (core/plans.ts `planStep`).
17
18import type { EngineInterface, HttpInit, On } from 'claude-code'
19import { type BackendIo, describeAsked, errorText, within } from '../decision/backend.ts'
20import type { ReferenceReading } from '../decision/complexity.ts'
21import { MIN_ASK_MS } from '../core/agent-lane.ts'
22import { askGroups, type AskIo } from '../core/ask-group.ts'
23import { CALL_ROOM_MS } from '../core/call-budget.ts'
24import { readReferenceComplexity, type ComplexityIo, type ReferenceReadings, type ReferenceSource } from '../core/complexity.ts'
25import { enteringPrompt } from '../core/core.ts'
26import type { Cell } from '../core/plans.ts'
27import { takeDeferred } from '../core/deferred.ts'
28import type { ImageFilesIo } from '../core/image-files.ts'
29import { report, type NodeFailure, type ReportIo } from '../core/report.ts'
30import type { Ctx } from '../core/setup.ts'
31import { defineSwitch, isOn, masterOn } from '../core/switches.ts'
32import { newWorkFile } from '../core/work-files.ts'
33
34/** The switch's name, in `/dp` and in the decision log. */
35export const IMAGE_ROUTING_SWITCH = 'image-routing'
36
37const PPLX_RATE = { plugin: 'dispatch-pilot', key: 'pplxRate' } as const
38const READINGS = { plugin: 'dispatch-pilot', key: 'referenceReadings' } as const
39const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
40const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
41
42/** How long the turn's start waits for the reading: the images prepared and the request answered (ADR 0008: about 3 seconds). */
43const READING_WAIT_MS = 3000
44
45/** Whether a prompt's attachments (`prompt.submit`'s `e.attachments`) include an image. */
46export function hasImage(attachments: readonly { type: string }[] | undefined): boolean {
47  return attachments?.some((attachment) => attachment.type === 'image') === true
48}
49
50// ---- The images of the message --------------------------------------------------------------------------------------
51
52/** A message's images as its row carried them: the words (what the person typed) and the images to read. */
53type Pasted = { text: string; sources: ReferenceSource[] }
54
55/**
56 * The latest messages' images, newest last (module level: the message's row comes in `session.append` and its turn starts a
57 * moment later; a hot reload in between loses them, at the cost of that one message's reading). They are taken when the turn
58 * starts, and a message that never starts a turn is pushed out by the next ones.
59 */
60const pasted: Pasted[] = []
61const MOST_PASTED = 4
62
63/** A pasted image's bytes are kept for a reading only up to this long (base64 characters): the file the row names is the better source. */
64const MOST_BYTES = 12_000_000
65
66/** A block of a row's content, as the engine appends it. */
67export type Block = { type: string; [field: string]: unknown }
68
69/**
70 * The file a row names for an image the person pasted: the engine adds a text block, `[Image: source: <path> ...]`, with the
71 * path of the original (before it was scaled to fit the model). Null for any other text.
72 */
73function sourceOf(text: string): string | null {
74  return /\[Image: source: (\/[^\s\]]*?\.(?:png|jpe?g|gif|webp|heic|heif|tiff?|bmp))/i.exec(text)?.[1] ?? null
75}
76
77/** What the images of a user row come to: their files when the row names them, else their bytes. Null for a row with no image. */
78export function pastedOf(content: readonly Block[]): Pasted | null {
79  const images = content.filter((block) => block.type === 'image')
80  if (images.length === 0) return null
81  const texts = content.flatMap((block) => (block.type === 'text' && typeof block.text === 'string' ? [block.text] : []))
82  const paths = texts.flatMap((text) => {
83    const path = sourceOf(text)
84    return path === null ? [] : [path]
85  })
86  const bytes = images.flatMap((block) => {
87    const source = block.source as { data?: unknown } | undefined
88    return typeof source?.data === 'string' && source.data.length <= MOST_BYTES ? [source.data] : []
89  })
90  const sources: ReferenceSource[] = paths.length > 0 ? paths.map((path) => ({ path })) : bytes.map((base64) => ({ base64 }))
91  return { text: texts.filter((text) => !text.startsWith('[Image')).join('\n').trim(), sources }
92}
93
94/**
95 * The images of the message the turn starts for (the latest one whose words are one of `texts`); they are taken. Null when no
96 * message matches: the images of another message are not guessed at, the effort is decided without a reading.
97 */
98function takePasted(texts: readonly string[]): Pasted | null {
99  const wanted = texts.map((text) => text.trim())
100  let at = -1
101  pasted.forEach((one, i) => {
102    if (wanted.includes(one.text)) at = i
103  })
104  const found = pasted[at]
105  pasted.length = 0
106  return found ?? null
107}
108
109// ---- The engine, as closures -----------------------------------------------------------------------------------------
110
111/** The files the images need of the engine, as closures. */
112function filesOf($: EngineInterface): ImageFilesIo {
113  return {
114    run: (argv, init) => $.process.run(argv, init),
115    readBytes: async (path) => (await $.fs.read(path, { as: 'bytes' })).base64,
116    // The session's directory in the mod's temporary directory, like every file the mod makes (core/work-files.ts, #62).
117    newFile: (extension) => newWorkFile({ run: (argv) => $.process.run(argv), tmpdir: () => $.env.get('TMPDIR'), sessionId: () => $.session.id() }, extension),
118  }
119}
120
121export function registerImageRouting(on: On, ctx: Ctx): void {
122  defineSwitch({ name: IMAGE_ROUTING_SWITCH, info: '带图路由:发消息带参考图时,先读出图的复杂度,再决定主 agent 的 effort(默认关,图会发给决策模型)', default: false })
123
124  // The message's row: its images, noted for the turn that starts next. Looked at only while the feature could use them, and
125  // never changed.
126  on('session.append', { door: 'prompt' }, async (_$, e, next) => {
127    if (e.agentId === undefined && e.message.type === 'user' && isOn(IMAGE_ROUTING_SWITCH) && ctx.images !== null) {
128      const one = pastedOf(e.message.content as Block[])
129      if (one !== null) {
130        pasted.push(one)
131        if (pasted.length > MOST_PASTED) pasted.shift()
132      }
133    }
134    return next(e)
135  })
136
137  // The main agent's turn starts: the message that came with images is decided now. Inside the core's `turn.start`, which claims
138  // the decision written here.
139  on('turn.start', { turnId: /(?:)/ }, async ($, e, next) => {
140    if (e.agentId !== undefined) return next(e)
141    const entering = enteringPrompt()
142    const taken = takeDeferred(entering === undefined ? [e.text] : [entering, e.text])
143    if (taken === null) return next(e)
144    try {
145      // Switched off (/dp off) since the message was sent: nothing is asked, the turn goes out as the engine made it.
146      if (masterOn()) await decide($, ctx, taken, [e.text, taken.prompt])
147    } catch (error) {
148      $.ui.log(`image routing: ${errorText(error)}`, { to: 'debug' })
149    }
150    return next(e)
151  })
152}
153
154/** What a request to the decision model needs of the engine, as closures. */
155function backendOf($: EngineInterface): BackendIo {
156  return {
157    fetch: (url: string, init: HttpInit) => $.http.fetch(url, init),
158    sleep: (ms: number, signal: AbortSignal) => $.clock.sleep(ms, { signal }),
159    pace: { now: () => $.clock.now(), sentAt: { get: () => $.state.get(PPLX_RATE), set: (value, options) => $.state.set(PPLX_RATE, value, options) } },
160  }
161}
162
163/**
164 * Everything a reading needs of the engine, as closures: `$` may not cross a file (DEVELOPMENT.md 「事件和 matcher」), and a picture
165 * met in the middle of a turn (features/reference-midturn.ts) is read the same way. Each hook file builds it from its own `$`.
166 */
167export type ReadIo = {
168  backend: BackendIo
169  files: ImageFilesIo
170  store: Cell<ReferenceReadings>
171  now: () => Promise<number>
172  debug: (line: string) => void
173  /** A reading that failed, for the board's notes: beside the route, no toast. */
174  note: (failure: NodeFailure) => Promise<void>
175}
176
177/**
178 * What the reference images `sources` read as: asked of the image backend (a group read before is answered from the readings
179 * kept), within `READING_WAIT_MS`. Null when there is no reading: no image backend, the images could not be read, the request
180 * failed or came too late; the board notes a failed one, beside the route and without a toast. Never throws. The message that
181 * starts a turn (below) and a picture met in the middle of one (features/reference-midturn.ts) read the same way.
182 */
183export async function readReference(io: ReadIo, ctx: Ctx, sources: readonly ReferenceSource[]): Promise<ReferenceReading | null> {
184  const images = ctx.images
185  if (images === null || sources.length === 0) return null
186  try {
187    const complexity: ComplexityIo = {
188      files: io.files,
189      ask: async (request) => {
190        const at = await io.now()
191        const asked = await images.backend.ask(io.backend, request, READING_WAIT_MS)
192        io.debug(`complexity reading [${Object.keys(request.questions).join(', ')}] to ${images.backend.name}: ${describeAsked(asked, (await io.now()) - at)}`)
193        return asked
194      },
195      store: io.store,
196      now: io.now,
197      backend: images.name,
198      debug: io.debug,
199    }
200    const late = { late: true } as const
201    const read = await within(io.backend.sleep, readReferenceComplexity(complexity, sources), READING_WAIT_MS, late)
202    if ('late' in read) {
203      io.debug(`image routing: no reading in ${READING_WAIT_MS} ms; the effort is decided without it`)
204      await io.note({ backend: images.name, kind: 'timeout', detail: `no reading in ${READING_WAIT_MS} ms` })
205      return null
206    }
207    if (read.ok) {
208      io.debug(`image routing: the images read as level ${read.reading.level} (${read.cached ? 'read before' : 'asked'}), from ${read.reading.images} image${read.reading.images === 1 ? '' : 's'}`)
209      return read.reading
210    }
211    io.debug(`image routing: no reading (${read.reason}); the effort is decided without it`)
212    if (read.failure !== undefined) await io.note({ backend: images.name, ...read.failure })
213    return null
214  } catch (error) {
215    io.debug(`image routing: ${errorText(error)}`)
216    return null
217  }
218}
219
220/** What a reading needs of the engine, from this file's hooks. */
221function readIoOf($: EngineInterface): ReadIo {
222  return {
223    backend: backendOf($),
224    files: filesOf($),
225    store: { get: () => $.state.get(READINGS), set: (value: ReferenceReadings, options) => $.state.set(READINGS, value, options) },
226    now: () => $.clock.now(),
227    debug: (line) => $.ui.log(line, { to: 'debug' }),
228    note: (failure) => note($, failure),
229  }
230}
231
232/** The message's effort, decided with the reading of its images when there is one. */
233async function decide($: EngineInterface, ctx: Ctx, taken: NonNullable<ReturnType<typeof takeDeferred>>, texts: readonly string[]): Promise<void> {
234  const debug = (line: string) => $.ui.log(line, { to: 'debug' })
235  const backend = backendOf($)
236  const startedAt = await $.clock.now()
237  let reading: ReferenceReading | null = null
238  // Off since the message was sent: it is decided as any message is, without its images.
239  if (ctx.images !== null && isOn(IMAGE_ROUTING_SWITCH)) {
240    const found = takePasted(texts)
241    if (found === null || found.sources.length === 0) debug('image routing: the message came with images, but none was found to read; its effort is decided without a reading')
242    else reading = await readReference(readIoOf($), ctx, found.sources)
243  }
244  // The effort question, as a message's ever is: the reading is in its state. Its answer is written as the pending decision.
245  const messages = ctx.config.context.messages > 0 ? await $.session.messages().catch(() => []) : []
246  const spent = (await $.clock.now()) - startedAt
247  const io: AskIo = { backend, now: () => $.clock.now(), debug }
248  // A `$.clock.sleep` counts toward the hook's 10 s: the effort request waits for what is left of the call room, never longer than the decision model's own setting.
249  await askGroups(io, ctx, { prompt: taken.prompt, messages, groups: [[taken.deferred(reading)]], maxWaitMs: Math.max(MIN_ASK_MS, CALL_ROOM_MS - spent) })
250}
251
252/** A reading that failed, for the board's notes: beside the route, no toast (the effort is decided all the same). */
253async function note($: EngineInterface, failure: NodeFailure): Promise<void> {
254  const io: ReportIo = {
255    board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
256    decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
257    debug: (line) => $.ui.log(line, { to: 'debug' }),
258    now: () => $.clock.now(),
259    toast: (text) => $.ui.toast(text),
260  }
261  await report(io, { decision: { feature: IMAGE_ROUTING_SWITCH, agent: 'main', aside: true, failure } })
262}
263
hooks/features/main-effort.ts 219 lines
1// Feature: the main agent's effort, decided each time the person sends a
2// message, and when a report starts a turn of its own: a dispatched agent's
3// hand-back or a background task's notice reaching the idle session (those
4// turns are usually a look at a result and the next dispatch; the session's own
5// effort would be a waste). It adds the effort question to the message's ballot
6// (the core sends it); the answer becomes the effort of the turn the message
7// starts, on every step of that turn (the core's turn.step writer). A report's
8// text is read as the message; its turn is not re-decided mid-turn.
9//
10// A command turn (#19: `/implement #19`, a skill or markdown command the
11// person typed) is decided like their message: the decision model reads the
12// command as typed and what the command is for (core/commands.ts), never the
13// prompt it expands to.
14//
15// A message typed while a turn runs (`e.turnId`) is delivered into that turn
16// at its next step (a `queued_command` attachment; measured on 2.1.289), so
17// its decision takes the running turn from then on. It also waits as pending,
18// in case the turn ends first and the message starts a turn of its own.
19
20import type { EngineInterface, On } from 'claude-code'
21import { errorText } from '../decision/backend.ts'
22import { EFFORTS, LEVEL, probsOf, readEffort, readingText, traceEffort, type Effort, type EffortReading } from '../decision/effort.ts'
23import { quoteStart } from '../decision/redact.ts'
24import { turnStartPart } from '../decision/turn-start.ts'
25import { givesHint, HINTED, judgeUnresolved, readUnresolved, UNRESOLVED, usesHinted } from '../decision/unresolved.ts'
26import { contribute, type Contribution, type PartOutcome } from '../core/ballot.ts'
27import { commandOf, commandState } from '../core/commands.ts'
28import { hintDecision, keptCount, keptSummary, moveCount, unresolvedDecision, type CountCell } from '../core/unresolved.ts'
29import { defer, withdraw } from '../core/deferred.ts'
30import { addPending, revise, turnKey, update, type Cell, type PendingDecision, type TurnRecord } from '../core/plans.ts'
31import { isPersonsMessage, startsReportTurn } from '../core/prompts.ts'
32import { report, type HintRecord, type ReferenceRecord, type ReportIo, type UnresolvedRecord } from '../core/report.ts'
33import { hintedRules, type Ctx } from '../core/setup.ts'
34import { defineSwitch, isOn } from '../core/switches.ts'
35import type { ReferenceReading } from '../decision/complexity.ts'
36import { hasImage, IMAGE_ROUTING_SWITCH } from './image-routing.ts'
37import { UNRESOLVED_SWITCH } from './unresolved.ts'
38
39const PENDING = { plugin: 'dispatch-pilot', key: 'pending' } as const
40const TURNS = { plugin: 'dispatch-pilot', key: 'turns' } as const
41const BOARD = { plugin: 'dispatch-pilot', key: 'board' } as const
42const DECISIONS = { plugin: 'dispatch-pilot', key: 'decisionLog' } as const
43const CATALOG = { plugin: 'dispatch-pilot', key: 'skillCatalog' } as const
44const COUNT = { plugin: 'dispatch-pilot', key: 'unresolved' } as const
45
46/**
47 * What a command turn's command is for: its skill in the session's catalog as
48 * the skills feature read it (by its profile while profiles are on), else the
49 * command as `$.command.list()` describes it.
50 */
51async function describeCommand($: EngineInterface, name: string): Promise<Readonly<Record<string, string>> | null> {
52  const { value: catalog } = await $.state.get(CATALOG)
53  const found = catalog?.skills.find((skill) => skill.name === name)
54  const skill = found && !isOn('skill-profiles') ? { ...found, profile: null } : found
55  const listed = skill?.description ? undefined : (await $.command.list().catch(() => [])).find((command) => command.name === name)?.description
56  return commandState(name, skill, listed)
57}
58
59/** The unresolved count and summary in `$.state`, as a cell. */
60function countCell($: EngineInterface): CountCell {
61  return { get: () => $.state.get(COUNT), set: (value, options) => $.state.set(COUNT, value, options) }
62}
63
64export function registerMainEffort(on: On, ctx: Ctx): void {
65  defineSwitch({ name: 'main-effort', info: '发消息时决定主 agent 的 effort' })
66
67  on('prompt.submit', { text: /(?:)/ }, async ($, e, next) => {
68    // The person's own message, or a report that starts a turn of its own (a dispatched agent's hand-back, a task notice).
69    const handBack = !isPersonsMessage(e) && startsReportTurn(e)
70    if ((!isPersonsMessage(e) && !handBack) || !isOn('main-effort')) return next(e)
71    const pending: Cell<PendingDecision[]> = { get: () => $.state.get(PENDING), set: (value, options) => $.state.set(PENDING, value, options) }
72    let added: PendingDecision | null = null
73
74    /** The message waits for its turn, decided or not: the turn it starts is the person's own (mid-turn re-decisions are for such turns). */
75    const wait = async (effort: Effort | null) => {
76      const entry: PendingDecision = { text: e.text, effort, at: await $.clock.now(), ...(handBack ? { report: true as const } : {}) }
77      await update(pending, (list) => addPending(list ?? [], entry))
78      added = entry
79    }
80
81    const ran = handBack ? null : commandOf(e.text)
82    const command = ran === null ? null : await describeCommand($, ran.command)
83
84    // The person's own message also asks whether it says the problem they are on is still not solved (the unresolved
85    // count); a report that starts a turn is no word of theirs, and the switch can leave the question out. It travels
86    // in this part, so it is in the effort request with the state it reads (ADR 0005).
87    const counting = !handBack && isOn(UNRESOLVED_SWITCH)
88    // The summary there is: a write that is not done yet is no reason to wait, the decision uses the one before it.
89    const summary = counting ? await keptSummary(countCell($)).catch(() => null) : null
90    // The count before this message (its own answer comes in the same request), and with it the strong hint once it has
91    // reached the setting: a sentence in the effort question about the kind of work, the level still the decision model's (ADR 0005).
92    const count = counting ? await keptCount(countCell($)).catch(() => 0) : 0
93    const maxAfter = ctx.config.unresolved.maxAfter
94    const hint: HintRecord | undefined = givesHint(count, maxAfter) ? { count, maxAfter } : undefined
95    // A message with reference images (#63) is decided when its turn starts, once its images have been read: its effort part
96    // does not go in the ballot, and the image-routing feature asks it at `turn.start` (core/deferred.ts). That turn has started
97    // by then, so its decision is about the turn running.
98    const imaged = !handBack && ran === null && e.turnId === undefined && ctx.images !== null && isOn(IMAGE_ROUTING_SWITCH) && hasImage(e.attachments)
99    // About the main agent of the turn this message starts, or of the one running when it was typed into it.
100    const forTurn = e.turnId === undefined && !imaged ? ('next' as const) : ('current' as const)
101
102    /** Whether the hinted effort answer was the one used (set by decideEffort; false when it was not asked or not used). */
103    let hintUsed = false
104
105    /** The effort this message's turn goes out at, and the board's word for it. */
106    const decideEffort = async (outcome: PartOutcome, io: ReportIo, unresolved?: UnresolvedRecord, reference?: ReferenceRecord): Promise<Effort | null> => {
107      const about = { feature: handBack ? 'main-effort (agent report)' : 'main-effort', agent: 'main', forTurn, subject: quoteStart(e.text) }
108      if (!outcome.ok) {
109        await report(io, { decision: { ...about, routed: false, failure: { backend: ctx.backend.name, ...outcome.failure } } })
110        await wait(null)
111        return null
112      }
113      // With the strong hint the request asked the hinted effort question beside the plain one: its answer is taken when this
114      // message's own three-way answer added one to the count (the problem is still unresolved), else the plain one's.
115      const hintedReading = hint === undefined || !usesHinted(unresolved?.change ?? null) ? null : readEffort(outcome.answers[HINTED])
116      const reading = hintedReading ?? readEffort(outcome.answers[LEVEL])
117      if (hint !== undefined) hintUsed = hintedReading !== null
118      if (reading === null) {
119        await report(io, { decision: { ...about, routed: false, failure: { backend: ctx.backend.name, kind: 'parse', detail: 'no effort answer' } } })
120        await wait(null)
121        return null
122      }
123      // pickEffort's rules with their working: the board shows the steps, never recomputes them (#23). With the strong hint, max has its own threshold.
124      const rules = hintedReading === null ? ctx.config : hintedRules(ctx.config, ctx.config)
125      const { effort, steps } = traceEffort(reading, rules)
126      await report(io, {
127        decision: {
128          ...about,
129          routed: true,
130          outcome: `effort ${effort}`,
131          // The level as data: what reads the log (the band, the pane) never reads it out of the words.
132          effort,
133          reason: describeReading(reading, effort, rules.thetaMax),
134          probs: probsOf(reading),
135          ...(reading.confidence === null ? {} : { conf: reading.confidence }),
136          trace: steps,
137          // What the reference images it came with read as: the card draws it with the effort's.
138          ...(reference === undefined ? {} : { reference }),
139          // What this message did to the unresolved count: the card draws it with the effort's.
140          ...(unresolved === undefined ? {} : { unresolved }),
141          // The card says the hint was given, and whether its answer was the one used.
142          ...(hint === undefined ? {} : { hint: { ...hint, used: hintedReading !== null } }),
143        },
144      })
145      await wait(effort)
146      const running = e.turnId
147      if (running !== undefined) {
148        const ref = { ...TURNS, id: turnKey(running, undefined) }
149        const turn: Cell<TurnRecord> = { get: () => $.state.get(ref), set: (value, options) => $.state.set(ref, value, options) }
150        await update(turn, (record) => revise(record, effort))
151      }
152      return effort
153    }
154
155    /**
156     * What the answer to the unresolved question does to the count, which is moved here: what the log and the card say
157     * of it; null when there is no answer or the count cannot be kept (the debug log says so, the count stays).
158     */
159    const countUnresolved = async (answered: Extract<PartOutcome, { ok: true }>) => {
160      const reading = readUnresolved(answered.answers[UNRESOLVED])
161      if (reading === null) {
162        $.ui.log(`unresolved for ${quoteStart(e.text)}: no answer, the count stays`, { to: 'debug' })
163        return null
164      }
165      const judged = judgeUnresolved(reading)
166      try {
167        return unresolvedDecision(judged, await moveCount(countCell($), judged.change))
168      } catch (error) {
169        $.ui.log(`unresolved count not kept: ${errorText(error)}`, { to: 'debug' })
170        return null
171      }
172    }
173
174    /** The message's effort part; `reading`: what its reference images read as, when they have been (the state carries it, the decision reports it). */
175    const effortPart = (reading: ReferenceReading | null): Contribution => ({
176      // Asked as the decision model's table says for these questions (Chinese with Jev); the other questions keep ctx.ask's.
177      ...turnStartPart({ ask: ctx.config.ask.turnStart, unresolved: counting, command, summary, count, maxAfter, reference: reading }),
178      settle: async (outcome) => {
179        const io: ReportIo = {
180          board: { get: () => $.state.get(BOARD), set: (value, options) => $.state.set(BOARD, value, options) },
181          decisions: { get: () => $.state.get(DECISIONS), set: (value, options) => $.state.set(DECISIONS, value, options) },
182          debug: (line) => $.ui.log(line, { to: 'debug' }),
183          now: () => $.clock.now(),
184          toast: (text) => $.ui.toast(text),
185        }
186        // The count first, so the effort's decision can say what this message did to it; neither depends on the other
187        // (either answer can be missing, and the effort is decided and kept whatever becomes of the count).
188        const counted = counting && outcome.ok ? await countUnresolved(outcome) : null
189        const effort = await decideEffort(outcome, io, counted?.unresolved, reading ?? undefined)
190        // A count that moved is a decision of its own in the log (an answer that left it as it was is on the effort's card only).
191        if (counted?.unresolved !== undefined && counted.unresolved.before !== counted.unresolved.count) {
192          await report(io, { decision: { feature: UNRESOLVED_SWITCH, agent: 'main', aside: true, forTurn, subject: quoteStart(e.text), ...counted } })
193        }
194        // Each hint given is a decision of its own in the log: the count, that it was given, the level that came of it.
195        if (hint !== undefined) await report(io, { decision: { feature: UNRESOLVED_SWITCH, agent: 'main', aside: true, forTurn, subject: quoteStart(e.text), ...hintDecision({ ...hint, used: hintUsed }, effort) } })
196      },
197    })
198    if (imaged) defer(e.text, effortPart)
199    else contribute(e.text, effortPart(null))
200
201    const result = await next(e)
202    // Refused beneath: no turn will take this decision.
203    if (imaged && result.drop !== undefined) withdraw(e.text)
204    const withdrawn = added as PendingDecision | null
205    if (result.drop !== undefined && withdrawn !== null) {
206      await update(pending, (list) => (list ?? []).filter((entry) => !(entry.text === withdrawn.text && entry.at === withdrawn.at)))
207    }
208    return result
209  })
210}
211
212/** Why a level was picked: every level's probability, `max` held back below thetaMax when it was the most likely, and the backend's confidence. */
213function describeReading(reading: EffortReading, picked: Effort, thetaMax: number): string {
214  const p = reading.probabilities
215  const max = p[EFFORTS.length - 1] ?? 0
216  const held = picked !== 'max' && p.every((other) => other <= max)
217  return readingText(reading, held ? `max 的概率没到 max 门槛 ${thetaMax.toFixed(2)}` : undefined)
218}
219