dsh-lark-bot 0.17.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -141,14 +141,29 @@ Markdown、toast 与旧客户端降级路径同时显示中英文。agent 最终
141
141
  | `/model`、`/providers`、`/provider`、`/key` | 打开交互式管理卡片(模型直接点选/恢复默认;管理写操作走多轮向导)|
142
142
  | `/model use <provider/model>` | 热切换当前会话模型(也兼容唯一模型 ID;下一轮生效,无需重启)|
143
143
  | `/model default <id>` | 写入 dsh 默认模型 `agent-default-model`(管理员)|
144
- | `/model add\|remove <provider> <modelId>` | 添加 / 删除 provider 的模型(管理员)|
144
+ | `/model add\|remove <provider> <modelId> [--input-modalities text,image]` | 添加 / 删除 provider 的模型,可声明视觉输入能力(管理员)|
145
145
  | `/provider add\|update\|remove <id>` | 管理 provider(管理员;deepseek-official 与自定义 pi-ai)|
146
- | `/key set\|remove\|list <引用名>` | 管理 dsh 凭据(set / remove 需管理员)|
146
+ | `/key set <引用名>`、`/key remove\|list <引用名>` | 通过仅请求者可提交的安全表单设置 dsh 凭据;remove 需管理员 |
147
+ | `/secret status\|set\|remove <dsh-credential\|app-secret> <引用>` | 查询状态或安全采集/删除受支持密钥(写操作需管理员;值不进入 Agent) |
148
+ | `/language show\|set plain\|agent …\|reset …` | 管理普通文本与 Agent 回答语言策略(写操作需管理员) |
147
149
  | `/ask <问题>` | 发送问答卡,回答写入会话上下文|
148
150
  | `/invite user\|admin\|group <id>`、`/invite list`、`/invite remove user\|group <id>` | 管理访问白名单(写操作需管理员)|
149
151
  | `/help` | 查看帮助|
150
152
 
151
- 飞书消息中的图片会下载到本地 media 目录并传给 dsh;文本类文件会读取内容并注入任务上下文。
153
+ 每轮 SDK / ACP / Web 请求都会注入结构化、无密钥的频道上下文,并注册官方 runtime Skill
154
+ `dsh-lark-bot`。API Key、token 与 App Secret 必须经 `/key set <引用名>`、`/secret set …` 或 Agent
155
+ 工具 `lark_request_secret` 打开的密码表单提交;普通聊天、旧 `/key set <引用名> <值>` 与
156
+ `--api-key` 不再消费值。表单只允许发起者提交,值直接写入本机受支持目标,不进入 prompt、session、
157
+ 任务账本、归档、日志、诊断包或回复。Guardian 安全模式是降级恢复面,不提供该完整配置与密钥工具。
158
+
159
+ 飞书消息中的图片会按文件内容识别 PNG/JPEG/WebP/GIF 并补全安全扩展名;默认 SDK 会经 dsh
160
+ 附件存储校验后发送原生 image block,而不是把路径当作图片。无法读取或模型不支持视觉时会明确
161
+ 失败,agent 被要求不得用工作区内其他图片替代。文本类文件会读取内容并注入任务上下文。
162
+ `/model` 卡片会把 dsh 默认模型并入可切换目录(即使 provider 的显式列表尚未包含它),
163
+ 并用去除公共前缀后的短标签、每行最多两个按钮适配移动端。provider 名称、模型、输入模态和
164
+ 推理档位从 models.dev 运行时目录发现(15 分钟内存缓存);网络失败时只使用 dsh settings 中的
165
+ 显式配置与默认选择,不回退到代码内置名单。通过命令或向导新增视觉模型时可声明 `text,image`,
166
+ 能力字段会原样写入 settings。目录地址可用 `DSH_LARK_MODEL_CATALOG_URL` 替换。
152
167
 
153
168
  **DSH session 消息级同步(`web` adapter)**:发送 `/session` 只会列出当前 canonical workspace
154
169
  的非 subagent session 元数据,不显示正文;选择后确认卡会列明标题、ID、workspace、更新时间、
@@ -229,19 +244,27 @@ guardian 仍只救援其配置的主实例。
229
244
 
230
245
  **结果文件直接回传**:SDK / ACP / Web agent 可调用 `lark_send_file`,把当前会话 workspace、实际执行 worktree、当前 scope 归档或实例日志中的文件直接上传到原飞书聊天 / 话题;普通 `/archive [note]` 会在落盘后立即发送 Markdown + JSONL,失败时保留路径并可用 `/archive send <id> [scope|chatId]` 重试或由管理员转发到指定会话。上传只接受普通文件,默认单文件不超过 20 MiB;真实路径必须位于 bridge 计算的会话目录内,runtime 自报 cwd 不能扩大边界。
231
246
 
232
- **逐操作审批与 scope 权限策略**:默认 SDK Web 宿主在 `tools/pre-execute` 强制拦截高风险调用,并接入 dsh rc.8 官方 `approval/request` seam;ACP 走原生 `session/request_permission`。默认 `ask` 会弹出“允许执行一次 / 拒绝”卡。管理员可用 `/permission allow` 对当前隔离 scope 自动放行逐工具审批,或用 `/permission deny` 直接拒绝并向聊天给出明确反馈;`/permission ask` 恢复逐次询问。member 隔离下可从目标 `/status` 复制 scope,执行 `/permission <策略> <scope>`;只允许修改当前聊天内 scope。策略成功落盘后才确认,持久化到 profile 的 `permission-policies.json`(0600),重启不丢,且显示在 `/status`。该策略不绕过较大/高风险任务的计划门禁;legacy `headless` 不具备工具回调能力。
247
+ **逐操作审批与 scope 权限策略**:SDK / ACP / Web runtime 在任何本地快速通道和计划门裁决前,先通过鉴权回环读取当前 immutable scope `ask|allow|deny`。`deny` 对低风险与高风险工具都先行拒绝并返回 `permission-policy` 来源;`ask` 对保守只读自省静默放行、对高风险调用弹“允许执行一次 / 拒绝”卡;`allow` 自动放行逐工具审批,但仍不替代高风险任务的计划确认或 Harness 文件沙箱。管理员可用 `/permission allow|deny|ask [scope]` 修改当前聊天内 scope;策略成功落盘后才确认,持久化到 profile 的 `permission-policies.json`(0600),重启不丢并显示在 `/status`。legacy `headless` 不具备工具回调能力。
233
248
 
234
249
  **关键任务计划门禁**:SDK / ACP / Web agent 在修改文件、运行脚本等较大或高风险动作前使用
235
250
  `lark_request_plan_approval`;同一 turn 未获批准时,runtime pre-execute 策略会拒绝写入、删除、
236
251
  移动、非只读 shell 命令与 `run_code`。一次计划批准只放行随后一次高风险调用,计划外的后续调用必须
237
- 重新确认。`date`、`pwd`、`ls`、`find`、`rg`、`git status/log/diff` 等单条
238
- 只读检查直接放行;包含串联、重定向、命令替换或未知程序的 shell 调用仍保守地走计划门禁。
252
+ 重新确认。快速通道只保留无路径的 `date`、`id`、`pwd`、`uname`、`whoami` 与受限的
253
+ `git status/log/diff` 等仓库内检查;`cat`、`grep`、`find`、`head`、`tail`、`rg`、`ls` 等可读取文件或枚举路径的命令不在快速通道,避免借工作区外路径读取环境或凭据。SDK `bash` 自动附带的 `description`、`workdir` 与
254
+ `run_in_background:false` 经无副作用校验后不会改变只读判定。包含未知参数、串联、重定向、
255
+ 命令替换或未知程序的 shell 调用仍保守地走计划门禁。
239
256
  bridge 先把完整 Markdown 计划作为普通消息发出,再弹出“批准,开始执行 /
240
257
  继续规划”决策卡;卡内可填写修改意见。工具在等待期间阻塞且暂停空闲超时,批准后原任务自动继续;
241
258
  继续规划时 agent 会收到意见、修订计划并再次请求确认。门禁无固定十分钟截止,跟随所属 run 的取消
242
259
  信号;停止任务会精确取消该 session 的 pending 卡并撤回。可信部署可设置
243
260
  `DSH_LARK_PLAN_GATE=off` 关闭这层独立门禁(逐工具审批仍按原策略执行);legacy headless adapter 不具备工具回调能力。
244
261
 
262
+ 插件可控的拒绝统一为 `[policy-denial layer=<plan-gate|permission-policy|tool-approval>]`,随后给出
263
+ `reason` 与 `to change`;Harness 自己的 `[sandbox: ...]` 明确归类为 `file-sandbox`。高风险分类器、
264
+ persona 中的只读说明和拒绝文本由 `src/policy/tool-policy.ts` 同一来源生成,因此策略调整不会只改
265
+ 提示词或只改执行钩子。persona 同时要求任一层拒绝后停止,不得换用等价命令、工具或路径绕行。
266
+ 计划门与逐工具审批仍保留不同语义,`/permission allow` 不扩大文件沙箱,也不替代计划确认。
267
+
245
268
  **任务中向你提问(问答卡)**:agent 需要你拍板、确认或补充信息时,通过 `lark_ask_user` 工具弹**问答卡**(单选 / 多选 / 自由文本)。可提交卡片,也可直接回复该卡片输入任意文字;单选/多选没有合适项时,回复文字就是补充答案。系统按被回复的 card messageId 精确匹配 pending 问题,回答后任务自动继续,等待期间运行超时看门狗暂停。(与 `/ask` 的“你主动提问”方向相反。)
246
269
 
247
270
  计划、审批与问答卡提交后会立即显示成功提示、发送一条终态确认并撤回原卡,避免按钮仍停留在聊天中造成“未生效”的误解;失效卡会返回明确错误提示,入站点击与失效原因写入结构化日志。确认或撤回失败不会影响已经提交给 agent 的决策、审批结果或答案。本地人机决策回调会以 JSON 空白流保活,避免 Node HTTP 客户端在等待 5 分钟后切断仍有效的卡片。
@@ -292,7 +315,7 @@ profile 的前台进程会拒绝并提示先停止,生命周期锁阻止并发
292
315
  (需 `--api` / `--base-url` / 至少一个 `--model`,与官方 schema 一致)或 `deepseek-official`。
293
316
  - `/key set|remove|list`:读写 `~/.dsh/.credentials.yaml`(0600);settings 只存 `apiKeyEnv` 引用,
294
317
  字面密钥不进 settings / 聊天记录。
295
- - **凭据引用必须关联**:`/key set <引用名> <值>` 只写入凭据文件;provider 要生效还须在其
318
+ - **凭据引用必须关联**:`/key set <引用名>` 通过安全表单写入凭据文件;provider 要生效还须在其
296
319
  `apiKeyEnv` 字段引用同一名字(`/provider add|update ... --api-key-env <引用名>`,或向导中填写)。
297
320
  引用名与 provider ID 相同且 provider 未设 `apiKeyEnv` 时,`/key set` 会自动补关联;
298
321
  已存在的老配置在下次运行时也会自动补齐。
@@ -301,7 +324,7 @@ profile 的前台进程会拒绝并提示先停止,生命周期锁阻止并发
301
324
  `https://www.kingapi.xyz`)会自动补全为 `/v1`。dsh runtime 启动后需几百毫秒才注册
302
325
  pi-ai 路由,桥接会重试握手直到注册完成(避免 “no adapter registered for provider”)。
303
326
 
304
- 安全提醒:在飞书会话输入密钥会对可见成员暴露,建议私聊使用或 `--api-key-env` 引用环境变量;bot 不在任何回复中回显密钥值。
327
+ 安全提醒:不要在普通飞书消息中输入密钥;使用安全表单或 `--api-key-env` 引用环境变量。bot 不读取旧式带值命令,也不在回复中回显密钥值。
305
328
 
306
329
  ## 升级、禁用与卸载
307
330
 
@@ -401,8 +424,8 @@ dsh plugin --profile dsh-lark remove dsh-lark-bot
401
424
  自动/人工验证边界见 [`docs/DSH_RC8_AUDIT.md`](docs/DSH_RC8_AUDIT.md)。
402
425
  - **运行时**:Node.js ≥ 22.19(见 `package.json` engines)。
403
426
  - **平台**:Linux / macOS / Windows(飞书 WebSocket 出站长连接,免公网服务器 / 域名 / 内网穿透)。
404
- - 默认 adapter 为官方 **`@deepseek-ai/dsh-sdk-client`**(SDK JSON-RPC runtime,原生 session 续跑 +
405
- token 级流式事件);`DSH_LARK_ADAPTER=acp` 切到官方 **ACP server**(审批卡);`headless` 保留旧版
427
+ - 默认 adapter 为官方 **`@deepseek-ai/dsh-sdk-client`**(SDK JSON-RPC runtime,原生 session 续跑、
428
+ token 级流式事件与 dsh attachment store 原生图片块);`DSH_LARK_ADAPTER=acp` 切到官方 **ACP server**(审批卡);`headless` 保留旧版
406
429
  子进程 fallback;`DSH_LARK_ADAPTER=web` 驱动**本地 dsh web agent**(`session.prompt` +
407
430
  `/api/events.mux`,网页端成为唯一写者,从根上消除多写者会话损坏)。首次启动自动在
408
431
  `~/.dsh/profiles/dsh-lark-sdk`(或 `dsh-lark-acp`)创建 runtime profile。
@@ -458,8 +481,9 @@ SDK 模式下 dsh 原生 session 续跑,headless 模式则把历史注入下
458
481
  | `DSH_LARK_DSH_COMMAND` | `自动发现` | dsh 启动命令;通常无需设置|
459
482
  | `DSH_LARK_DSH_ARGS` | `自动发现` | dsh 启动参数,逗号分隔;通常无需设置|
460
483
  | `DSH_LARK_ADAPTER` | `sdk` | `sdk`(默认,approval answerer)/ `acp`(协议原生审批)/ `headless`(legacy)/ `web`(本地 dsh web agent,单写者)|
461
- | `DSH_LARK_PROVIDER` | `deepseek-official` | 模型 provider|
462
- | `DSH_LARK_MODEL` | `deepseek-v4-flash` | 默认模型|
484
+ | `DSH_LARK_PROVIDER` | 未设置 | 模型 provider;可由对象形式的 dsh 默认模型提供|
485
+ | `DSH_LARK_MODEL` | 未设置 | 默认模型;可由 dsh `agent-default-model` 提供|
486
+ | `DSH_LARK_MODEL_CATALOG_URL` | `https://models.dev/api.json` | provider / 模型能力实时目录或兼容镜像|
463
487
  | `DSH_LARK_MAX_TOKENS` | 未设置 | SDK agent 每请求输出 token 上限|
464
488
  | `DSH_LARK_WEB_URL` | `http://127.0.0.1:3080` | `web` 适配器:本地 dsh web agent 的 base URL|
465
489
  | `DSH_LARK_SESSION_PROJECTION` | `true` | `web` 适配器:启用用户显式绑定后的历史/实时消息投影;绝不自动切换(`0` 关闭)|
@@ -495,6 +519,11 @@ SDK 模式下 dsh 原生 session 续跑,headless 模式则把历史注入下
495
519
  | `DSH_LARK_UPGRADE_NOTIFY` | `false` | `true` 时发现新版本向指定 chat 推送飞书通知(默认仅日志)|
496
520
  | `DSH_LARK_UPGRADE_NOTIFY_CHAT` | — | 接收更新通知的 chat id(配合 `DSH_LARK_UPGRADE_NOTIFY=true`)|
497
521
 
522
+ SDK / ACP 启动会先解析完整 provider/model route:显式双字段优先;缺失时读取 dsh 对象形式
523
+ `agent-default-model: { provider, model }`;仍无法得到完整 route 时在 bridge/doctor 入口给出本项目的
524
+ 明确配置错误,不把空 provider 传给上游 runtime。受管 service 的 install/start/restart 会把旧 env
525
+ 文件中的受管键与当前 shell 合并(当前 shell 显式值优先),避免从另一个终端重启时静默丢失已有 route。
526
+
498
527
  启动时会自动查找本机常见的 `@deepseek-ai/dsh` 安装位置。只有自动发现失败或需要指定特殊 profile 时,才需要设置这两个变量。
499
528
 
500
529
  ## 权限与数据
@@ -587,10 +616,18 @@ pnpm check:publish-bundle # 校验 dist 与全部 exports/bin 入口一致(
587
616
  pnpm ci:local
588
617
  pnpm release:check # ci:local + 上游一致性检查
589
618
  pnpm compat:probe # 临时安装锁定版 dsh,验证 SDK/ACP 握手及 SDK 工具/续接
590
- pnpm dsh:upstream # 对比 npm 上游 stable 与锁定矩阵
619
+ pnpm upstream:report # 只读检查 dsh + dsh-TUI 的 GitHub Release/npm 双源发布
620
+ pnpm dsh:upstream # upstream:report 的兼容别名
591
621
  pnpm security:monitor # 假冒仓库与仿冒包监控(建议每周)
592
622
  ```
593
623
 
624
+ 仓库的 `upstream-release-watch` GitHub Actions 每天运行,也可手动触发。它以
625
+ `scripts/upstream-release-config.mjs` 中经人工确认的 `trackFrom` 为首次基线,合并全部非 draft
626
+ GitHub Releases 与 npm 全版本/发布时间/dist-tags;每个新“上游 + 版本”创建一个带
627
+ `upstream-update` label 的跟踪 Issue。同一版本的 npm-only Issue 会在 GitHub Release 后续补发时
628
+ 原地补充,closed Issue 也参与隐藏标记去重。该自动化只搬运并安全截断外部发布信息,不分析兼容性、
629
+ 不修改依赖或代码,也不自动创建适配 PR。
630
+
594
631
  开发规范见 [`AGENTS.md`](AGENTS.md),模块契约见 [`docs/API.md`](docs/API.md),架构见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)。
595
632
  兼容矩阵的升级政策与自动化见 [`docs/COMPATIBILITY.md`](docs/COMPATIBILITY.md)。
596
633
 
package/README_EN.md CHANGED
@@ -139,14 +139,34 @@ Send a normal message to the bot in Feishu to get started. Common commands:
139
139
  | `/model`, `/providers`, `/provider`, `/key` | Open the interactive hub (tap a model or restore the default; management writes use a multi-turn wizard) |
140
140
  | `/model use <provider/model>` | Hot-switch the current session model (a unique bare model ID also works; effective next message, no restart) |
141
141
  | `/model default <id>` | Write the dsh default model `agent-default-model` (admin) |
142
- | `/model add\|remove <provider> <modelId>` | Add / remove a provider model (admin) |
142
+ | `/model add\|remove <provider> <modelId> [--input-modalities text,image]` | Add / remove a provider model and declare vision input (admin) |
143
143
  | `/provider add\|update\|remove <id>` | Manage providers (admin; deepseek-official and custom pi-ai) |
144
- | `/key set\|remove\|list <ref>` | Manage dsh credentials (set / remove require admin) |
144
+ | `/key set <ref>`, `/key remove\|list <ref>` | Set dsh credentials through an owner-only secure form; remove requires admin |
145
+ | `/secret status\|set\|remove <dsh-credential\|app-secret> <ref>` | Inspect status or securely collect/remove a supported secret (admin writes) |
146
+ | `/language show\|set plain\|agent …\|reset …` | Manage plain-message and agent-answer language policy (admin writes) |
145
147
  | `/ask <question>` | Send a Q&A card; the answer is written back to session context |
146
148
  | `/invite user\|admin\|group <id>`、`/invite list`、`/invite remove user\|group <id>` | Manage the access allowlist (mutating commands require admin) |
147
149
  | `/help` | Show help |
148
150
 
149
- Images in Feishu messages are downloaded to the local media directory and passed to dsh; text files are read and their content is injected into the task context.
151
+ Every SDK, ACP, and Web turn receives structured, secret-free channel context and the official runtime
152
+ `dsh-lark-bot` skill. API keys, tokens, and App Secrets must be entered through the owner-only password form opened
153
+ by `/key set <ref>`, `/secret set …`, or `lark_request_secret`. Ordinary chat, legacy `/key set <ref> <value>`, and
154
+ `--api-key` no longer consume values. The value never enters prompts, sessions, jobs, archives, logs, diagnostics,
155
+ or replies. Guardian safe mode is a degraded recovery surface without the full configuration/secret seam.
156
+ The form payload still traverses Feishu/Lark; platform-side auditing and retention are outside this project's control,
157
+ so use a trusted direct chat. The bridge guarantees that the value is not an ordinary chat message and is never sent
158
+ to the cloud LLM.
159
+
160
+ Feishu images are detected by content as PNG/JPEG/WebP/GIF and receive a safe extension. The default
161
+ SDK validates them through dsh's attachment store and sends native image blocks instead of path text.
162
+ Unreadable or unsupported images fail explicitly, and the agent is instructed never to substitute another
163
+ workspace image. Text files are read and injected into the task context.
164
+ The `/model` card merges the dsh default into its switchable catalogue even when a provider's explicit
165
+ list omits it, and uses compact distinguishing labels with at most two buttons per mobile row. Provider
166
+ names, models, input modalities, and reasoning-effort options are discovered from the models.dev runtime
167
+ catalogue and cached in memory for 15 minutes. If it is unavailable, only explicit dsh settings and the
168
+ configured default are shown—there is no hardcoded fallback list. Override the feed with
169
+ `DSH_LARK_MODEL_CATALOG_URL`; model commands and the wizard preserve `inputModalities`.
150
170
 
151
171
  **Message-level DSH session sync (`web` adapter)**: `/session` lists metadata only for non-subagent sessions
152
172
  in the current canonical workspace—never message bodies. The confirmation card freezes the title, ID,
@@ -239,7 +259,8 @@ reject `web`, because a shared Web agent broadcast stream cannot isolate session
239
259
  changes, scripts, or other substantial/high-risk actions. A runtime pre-execute policy denies writes, deletes,
240
260
  moves, non-read-only shell commands and `run_code` until a plan is approved. Each approval grants only the next
241
261
  high-risk call; later unplanned calls require approval again. Single read-only inspections such as `date`, `pwd`,
242
- `ls`, `find`, `rg`, and `git status/log/diff` run directly; shell chaining,
262
+ `ls`, `find`, `rg`, and `git status/log/diff` run directly. Inert SDK `bash` metadata (`description`,
263
+ `workdir`, and `run_in_background:false`) does not change that decision; unknown metadata, shell chaining,
243
264
  redirection, command substitution, and unknown executables remain behind the conservative plan gate. The bridge sends the complete Markdown plan as a normal
244
265
  message, then a card with **Approve and execute** / **Continue planning** plus optional feedback. The tool blocks
245
266
  and pauses the idle watchdog; approval resumes the original turn, while revision returns the feedback and requires
@@ -247,6 +268,13 @@ another plan. There is no fixed ten-minute deadline: the gate follows the owning
247
268
  stopping it cancels and recalls only that session's pending card. Trusted deployments may set
248
269
  `DSH_LARK_PLAN_GATE=off` to disable this separate gate (ordinary per-tool approval still applies). The legacy headless adapter cannot use callback tools.
249
270
 
271
+ Plugin-controlled refusals now use `[policy-denial layer=<plan-gate|permission-policy|tool-approval>]`
272
+ followed by `reason` and `to change`; Harness `[sandbox: ...]` errors are identified as the
273
+ `file-sandbox` layer. The high-risk classifier, persona read-only guidance, and denial text share
274
+ `src/policy/tool-policy.ts`, so policy changes cannot update only the prompt or only enforcement.
275
+ The plan gate and per-tool approval retain distinct semantics: `/permission allow` neither expands
276
+ the file sandbox nor replaces plan confirmation.
277
+
250
278
  **Mid-task questions (question cards)**: when the agent needs a decision, confirmation, or missing information, it sends a **question card** via the `lark_ask_user` tool (single choice / multi choice / free text). Submit the form or reply directly to that card with any text—even when none of the listed choices fits. The replied card message id selects the exact pending question, the agent resumes automatically, and the run-timeout watchdog pauses while it waits. (The opposite direction of `/ask`, where you ask the agent.)
251
279
 
252
280
  Plan, approval and question-card submissions immediately show a native toast, post a terminal confirmation and recall the original card. Stale cards return an explicit error toast, while received actions and stale reasons are written to structured logs. Confirmation/recall failures do not change the decision already delivered to the agent. Local human-decision callbacks stream insignificant JSON whitespace while waiting so Node's HTTP client cannot invalidate a live card after five minutes.
@@ -302,7 +330,7 @@ Configuration is persisted the official dsh way (the same storage protocol as th
302
330
  changes (effective on the next message). A bare pi-ai Base URL (e.g. `https://www.kingapi.xyz`)
303
331
  is completed with `/v1` automatically.
304
332
 
305
- Security note: typing a key in a Feishu conversation exposes it to everyone who can see that chat; prefer private chats or `--api-key-env` references to environment variables. The bot never echoes key values in any reply.
333
+ Security note: never type a key in ordinary Feishu chat. Use the secure form or an `--api-key-env` environment reference. Legacy value-bearing commands are not consumed, and replies never echo values.
306
334
 
307
335
  ## Upgrade, Disable & Uninstall
308
336
 
@@ -394,7 +422,7 @@ See [`docs/QUICK_START.md`](docs/QUICK_START.md) for installation details, state
394
422
  - **DeepSeek Harness (`dsh`)**: verified against **dsh 0.1.0-rc.8** (last verified 2026-08-22: clean temporary install, SDK JSON-RPC / ACP initialize, tool/approval, live-session resume, and restart-collision probes), connected through the official `@deepseek-ai/dsh-sdk-client` / `@deepseek-ai/dsh-acp`; see [`docs/COMPATIBILITY.md`](docs/COMPATIBILITY.md) for exact pins and probing, [`docs/adapter-notes.md`](docs/adapter-notes.md) for adapter details, and [`docs/DSH_RC8_AUDIT.md`](docs/DSH_RC8_AUDIT.md) for rc.8 risks and verification boundaries.
395
423
  - **Runtime**: Node.js ≥ 22.19 (see `engines` in `package.json`).
396
424
  - **Platform**: Linux / macOS / Windows (Feishu outbound WebSocket long connection; no public server, domain or tunneling required).
397
- - The default adapter is the official **`@deepseek-ai/dsh-sdk-client`** (SDK JSON-RPC runtime with native continuation, streaming events, and the rc.8 approval answerer); `DSH_LARK_ADAPTER=acp` switches to the official **ACP server** with protocol-native approval; `headless` keeps the legacy subprocess fallback; `DSH_LARK_ADAPTER=web` drives the **local dsh web agent** (`session.prompt` + `/api/events.mux` — the web agent becomes the single writer, eliminating multi-writer session-log corruption at the root). On first start the bot creates the runtime profile at `~/.dsh/profiles/dsh-lark-sdk` (or `dsh-lark-acp`).
425
+ - The default adapter is the official **`@deepseek-ai/dsh-sdk-client`** (SDK JSON-RPC runtime with native continuation, streaming events, dsh attachment-store image blocks, and the rc.8 approval answerer); `DSH_LARK_ADAPTER=acp` switches to the official **ACP server** with protocol-native approval; `headless` keeps the legacy subprocess fallback; `DSH_LARK_ADAPTER=web` drives the **local dsh web agent** (`session.prompt` + `/api/events.mux` — the web agent becomes the single writer, eliminating multi-writer session-log corruption at the root). On first start the bot creates the runtime profile at `~/.dsh/profiles/dsh-lark-sdk` (or `dsh-lark-acp`).
398
426
 
399
427
  ## Known limitations
400
428
 
@@ -429,8 +457,9 @@ Core environment variables:
429
457
  | `DSH_LARK_DSH_COMMAND` | auto-discovered | dsh launch command; usually not needed |
430
458
  | `DSH_LARK_DSH_ARGS` | auto-discovered | dsh launch args, comma-separated; usually not needed |
431
459
  | `DSH_LARK_ADAPTER` | `sdk` | `sdk` (default, approval answerer) / `acp` (protocol-native approval) / `headless` (legacy) / `web` (local dsh web agent, single writer) |
432
- | `DSH_LARK_PROVIDER` | `deepseek-official` | Model provider |
433
- | `DSH_LARK_MODEL` | `deepseek-v4-flash` | Default model |
460
+ | `DSH_LARK_PROVIDER` | unset | Model provider; may come from an object-form dsh default selection |
461
+ | `DSH_LARK_MODEL` | unset | Default model; may come from dsh `agent-default-model` |
462
+ | `DSH_LARK_MODEL_CATALOG_URL` | `https://models.dev/api.json` | Live provider/model capability feed or compatible mirror |
434
463
  | `DSH_LARK_MAX_TOKENS` | unset | Per-request output token cap for SDK agents |
435
464
  | `DSH_LARK_WEB_URL` | `http://127.0.0.1:3080` | `web` adapter: base URL of the local dsh web agent |
436
465
  | `DSH_LARK_SESSION_PROJECTION` | `true` | `web` adapter: enable history/live message projection after explicit user binding; never auto-switches (`0` disables) |
@@ -552,10 +581,18 @@ pnpm check:publish-bundle # verifies dist matches every export & the CLI entry
552
581
  pnpm ci:local
553
582
  pnpm release:check # ci:local + upstream consistency check
554
583
  pnpm compat:probe # temp-installs pinned dsh; probes SDK/ACP plus SDK tool/resume
555
- pnpm dsh:upstream # compares npm upstream stable with the pinned matrix
584
+ pnpm upstream:report # read-only dsh + dsh-TUI GitHub Release/npm source report
585
+ pnpm dsh:upstream # backward-compatible alias for upstream:report
556
586
  pnpm security:monitor # impostor-repo & npm copycat monitor (recommended weekly)
557
587
  ```
558
588
 
589
+ The repository's `upstream-release-watch` GitHub Actions workflow runs daily and can also be dispatched
590
+ manually. Its reviewed `trackFrom` baselines live in `scripts/upstream-release-config.mjs`. It merges every
591
+ non-draft GitHub Release with npm versions, publish times, and dist-tags, then creates one `upstream-update`
592
+ Issue per upstream/version. A later GitHub Release enriches the existing npm-only Issue, while hidden markers
593
+ deduplicate both open and closed Issues. This automation only transports sanitized, bounded release data; it
594
+ does not assess compatibility, modify dependencies/code, or create adaptation PRs.
595
+
559
596
  See [`AGENTS.md`](AGENTS.md) for the development workflow, [`docs/API.md`](docs/API.md) for module contracts, and [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the architecture. See [`docs/COMPATIBILITY.md`](docs/COMPATIBILITY.md) for the compatibility matrix, upgrade policy and automation.
560
597
 
561
598
  Contributions are welcome via Issues and PRs; see [`AGENTS.md`](AGENTS.md) for the workflow (required reading, commit conventions, push policy) and [`docs/ECOSYSTEM.md`](docs/ECOSYSTEM.md) for ecosystem delivery standards.
package/cordis.patch.yml CHANGED
@@ -44,10 +44,23 @@
44
44
  endpoint: !!js process.env.DSH_LARK_FILE_URL
45
45
  token: !!js process.env.DSH_LARK_NOTIFY_TOKEN
46
46
 
47
+ - id: lark-secret
48
+ name: 'dsh-lark-bot/secret'
49
+ config:
50
+ endpoint: !!js process.env.DSH_LARK_SECRET_URL
51
+ token: !!js process.env.DSH_LARK_NOTIFY_TOKEN
52
+
53
+ - id: lark-ask
54
+ name: 'dsh-lark-bot/ask'
55
+ config:
56
+ endpoint: !!js process.env.DSH_LARK_ASK_URL
57
+ token: !!js process.env.DSH_LARK_NOTIFY_TOKEN
58
+
47
59
  - id: lark-plan-approval
48
60
  name: 'dsh-lark-bot/plan'
49
61
  config:
50
62
  endpoint: !!js process.env.DSH_LARK_PLAN_URL
63
+ policyEndpoint: !!js process.env.DSH_LARK_APPROVAL_URL
51
64
  token: !!js process.env.DSH_LARK_NOTIFY_TOKEN
52
65
  mode: !!js process.env.DSH_LARK_PLAN_GATE
53
66
 
package/dist/approval.js CHANGED
@@ -1,28 +1,10 @@
1
- // src/notify/plan-tool.ts
1
+ // src/policy/tool-policy.ts
2
2
  var READ_ONLY_SHELL_TOOLS = /* @__PURE__ */ new Set(["bash", "shell"]);
3
3
  var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
4
- "basename",
5
- "cat",
6
4
  "date",
7
- "df",
8
- "dirname",
9
- "du",
10
- "find",
11
- "grep",
12
- "head",
13
5
  "id",
14
- "jq",
15
- "ls",
16
- "pgrep",
17
- "ps",
18
6
  "pwd",
19
- "readlink",
20
- "realpath",
21
- "rg",
22
- "stat",
23
- "tail",
24
7
  "uname",
25
- "wc",
26
8
  "whoami"
27
9
  ]);
28
10
  var READ_ONLY_GIT_SUBCOMMANDS = /* @__PURE__ */ new Set([
@@ -36,6 +18,17 @@ var READ_ONLY_GIT_SUBCOMMANDS = /* @__PURE__ */ new Set([
36
18
  "status"
37
19
  ]);
38
20
  var SHELL_CONTROL_SYNTAX = /[\n\r;&|<>`]|\$\(|\$\{/u;
21
+ function policyDenialText(denial) {
22
+ return `[policy-denial layer=${denial.layer}] denied by ${denial.layer}: ${denial.reason}
23
+ to change: ${denial.toChange}`;
24
+ }
25
+ function toolApprovalDenial(toolName) {
26
+ return {
27
+ layer: "tool-approval",
28
+ reason: `the user rejected the one-shot approval for tool ${toolName}`,
29
+ toChange: "choose a safer alternative or ask the user before requesting approval again"
30
+ };
31
+ }
39
32
  function isHighRiskTool(ctx, execution) {
40
33
  if (execution.name === "lark_request_plan_approval") return false;
41
34
  if (execution.name === "run_code") return true;
@@ -69,28 +62,17 @@ function isSimpleReadOnlyShellCommand(rawArguments) {
69
62
  (word) => word === "-u" || word === "--utc" || word === "--universal" || word.startsWith("+")
70
63
  );
71
64
  }
72
- if (executable === "rg") {
73
- return !words.slice(1).some(
74
- (word) => word === "--pre" || word.startsWith("--pre=") || word === "--hostname-bin" || word.startsWith("--hostname-bin=")
75
- );
76
- }
77
- if (executable === "find") {
78
- return !words.slice(1).some(
79
- (word) => ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf"].includes(word)
80
- );
81
- }
82
- if (executable === "tail") {
83
- return !words.slice(1).some(
84
- (word) => word === "-f" || word === "-F" || word === "--follow" || word.startsWith("--follow=")
85
- );
86
- }
87
- return true;
65
+ return words.length === 1;
88
66
  }
89
67
  function shellCommand(rawArguments) {
90
68
  if (typeof rawArguments === "object" && rawArguments !== null && !Array.isArray(rawArguments)) {
91
- const entries = Object.entries(rawArguments);
92
- if (entries.length !== 1 || entries[0]?.[0] !== "command") return void 0;
93
- const command = entries[0][1];
69
+ const record = rawArguments;
70
+ const allowedKeys = /* @__PURE__ */ new Set(["command", "description", "workdir", "run_in_background"]);
71
+ if (Object.keys(record).some((key) => !allowedKeys.has(key))) return void 0;
72
+ if (record.description !== void 0 && typeof record.description !== "string") return void 0;
73
+ if (record.workdir !== void 0 && typeof record.workdir !== "string") return void 0;
74
+ if (record.run_in_background !== void 0 && record.run_in_background !== false) return void 0;
75
+ const command = record.command;
94
76
  return typeof command === "string" ? command : void 0;
95
77
  }
96
78
  if (typeof rawArguments !== "string") return void 0;
@@ -101,11 +83,7 @@ function shellCommand(rawArguments) {
101
83
  }
102
84
  }
103
85
  function isReadOnlyGitCommand(words) {
104
- let index = 0;
105
- while (words[index] === "-C") {
106
- if (!words[index + 1]) return false;
107
- index += 2;
108
- }
86
+ const index = 0;
109
87
  const subcommand = words[index];
110
88
  if (subcommand === "branch") {
111
89
  const flags = words.slice(index + 1);
@@ -119,7 +97,7 @@ function isReadOnlyGitCommand(words) {
119
97
  }
120
98
  if (!subcommand || !READ_ONLY_GIT_SUBCOMMANDS.has(subcommand)) return false;
121
99
  return !words.slice(index + 1).some(
122
- (word) => word === "-o" || word === "--output" || word.startsWith("--output=") || word === "--ext-diff" || word === "--textconv"
100
+ (word) => word === "-o" || word === "--output" || word.startsWith("--output=") || word === "--ext-diff" || word === "--textconv" || word === "--no-index" || word.startsWith("/") || word.startsWith("~") || /(^|\/)\.\.(\/|$)/u.test(word)
123
101
  );
124
102
  }
125
103
 
@@ -134,21 +112,29 @@ function apply(ctx, config = {}) {
134
112
  inFlightGrant.delete(request.agent);
135
113
  return "allowed-once";
136
114
  }
137
- return requestBridgeApproval(config, request, next);
115
+ return (await requestBridgeApproval(config, request, next)).outcome;
138
116
  });
139
117
  approvalCtx.on("tools/pre-execute", async (execution, next) => {
140
- if (!isHighRiskTool(approvalCtx, execution)) return next();
118
+ const highRisk = isHighRiskTool(approvalCtx, execution);
119
+ if (!highRisk && !approvalEndpoint(config)) return next();
141
120
  const request = {
142
121
  ...execution.agent === void 0 ? {} : { agent: execution.agent },
143
122
  toolName: execution.name,
144
123
  reason: approvalReason(execution),
145
- toolInput: execution.arguments
124
+ toolInput: execution.arguments,
125
+ lowRisk: !highRisk
146
126
  };
147
- const outcome = await requestBridgeApproval(config, request, async () => "unavailable");
148
- if (outcome !== "allowed-once") {
127
+ const decision = await requestBridgeApproval(config, request, async () => "unavailable");
128
+ if (decision.outcome !== "allowed-once") {
149
129
  return {
150
130
  kind: "deny",
151
- reason: outcome === "rejected" ? "The user rejected this one-shot tool execution. Continue with a safer alternative." : "This tool execution was not approved and remains blocked."
131
+ reason: policyDenialText(
132
+ decision.denial ?? (decision.outcome === "rejected" ? toolApprovalDenial(execution.name) : {
133
+ layer: "tool-approval",
134
+ reason: `tool ${execution.name} did not receive approval (${decision.outcome})`,
135
+ toChange: "retry only after approval is available, or choose a safer alternative"
136
+ })
137
+ )
152
138
  };
153
139
  }
154
140
  if (execution.agent) inFlightGrant.set(execution.agent, execution.name);
@@ -160,11 +146,13 @@ function apply(ctx, config = {}) {
160
146
  });
161
147
  }
162
148
  async function requestBridgeApproval(config, request, next) {
163
- const endpoint = config.endpoint ?? process.env.DSH_LARK_APPROVAL_URL;
149
+ const endpoint = approvalEndpoint(config);
164
150
  const token = config.token ?? process.env.DSH_LARK_NOTIFY_TOKEN;
165
- if (!endpoint || !token) return next();
151
+ if (!endpoint || !token) return { outcome: await next() };
166
152
  const sessionId = request.agent?.session?.id;
167
- if (sessionId === void 0 || typeof request.toolName !== "string") return "unavailable";
153
+ if (sessionId === void 0 || typeof request.toolName !== "string") {
154
+ return { outcome: "unavailable" };
155
+ }
168
156
  try {
169
157
  const response = await fetch(endpoint, {
170
158
  method: "POST",
@@ -175,16 +163,23 @@ async function requestBridgeApproval(config, request, next) {
175
163
  toolName: request.toolName,
176
164
  ...request.callId === void 0 ? {} : { callId: String(request.callId) },
177
165
  ...typeof request.reason === "string" ? { reason: request.reason } : {},
178
- ...request.toolInput === void 0 ? {} : { toolInput: request.toolInput }
166
+ ...request.toolInput === void 0 ? {} : { toolInput: request.toolInput },
167
+ ..."lowRisk" in request && request.lowRisk === true ? { lowRisk: true } : {}
179
168
  }),
180
169
  ...request.signal === void 0 ? {} : { signal: request.signal }
181
170
  });
182
171
  const body = await response.json();
183
- return response.ok && body.ok === true && isOutcome(body.outcome) ? body.outcome : "unavailable";
172
+ return response.ok && body.ok === true && isOutcome(body.outcome) ? {
173
+ outcome: body.outcome,
174
+ ...isPolicyDenial(body.denial) ? { denial: body.denial } : {}
175
+ } : { outcome: "unavailable" };
184
176
  } catch {
185
- return request.signal?.aborted ? "cancelled" : "unavailable";
177
+ return { outcome: request.signal?.aborted ? "cancelled" : "unavailable" };
186
178
  }
187
179
  }
180
+ function approvalEndpoint(config) {
181
+ return config.endpoint ?? process.env.DSH_LARK_APPROVAL_URL;
182
+ }
188
183
  function approvalReason(execution) {
189
184
  if (typeof execution.arguments === "object" && execution.arguments !== null && "description" in execution.arguments && typeof execution.arguments.description === "string") {
190
185
  return execution.arguments.description;
@@ -194,6 +189,11 @@ function approvalReason(execution) {
194
189
  function isOutcome(value) {
195
190
  return value === "allowed-once" || value === "rejected" || value === "cancelled" || value === "unavailable";
196
191
  }
192
+ function isPolicyDenial(value) {
193
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
194
+ const denial = value;
195
+ return (denial.layer === "plan-gate" || denial.layer === "permission-policy" || denial.layer === "tool-approval" || denial.layer === "file-sandbox") && typeof denial.reason === "string" && typeof denial.toChange === "string";
196
+ }
197
197
  export {
198
198
  apply,
199
199
  inject,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/notify/plan-tool.ts","../src/notify/approval-answerer.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\nimport {\n objectArgs,\n requiredString,\n type RawToolExecution,\n type ToolPluginContext,\n} from './raw-tool.js';\n\nexport const name = 'lark-plan-approval';\nexport const inject = ['tools'];\n\nexport interface Config {\n endpoint?: string;\n token?: string;\n mode?: 'strict' | 'off';\n}\n\nexport interface PlanPolicyExecution {\n name: string;\n arguments: unknown;\n agent?: object;\n}\n\nconst READ_ONLY_SHELL_TOOLS = new Set(['bash', 'shell']);\nconst READ_ONLY_COMMANDS = new Set([\n 'basename',\n 'cat',\n 'date',\n 'df',\n 'dirname',\n 'du',\n 'find',\n 'grep',\n 'head',\n 'id',\n 'jq',\n 'ls',\n 'pgrep',\n 'ps',\n 'pwd',\n 'readlink',\n 'realpath',\n 'rg',\n 'stat',\n 'tail',\n 'uname',\n 'wc',\n 'whoami',\n]);\nconst READ_ONLY_GIT_SUBCOMMANDS = new Set([\n 'diff',\n 'ls-files',\n 'ls-tree',\n 'log',\n 'merge-base',\n 'rev-parse',\n 'show',\n 'status',\n]);\nconst SHELL_CONTROL_SYNTAX = /[\\n\\r;&|<>`]|\\$\\(|\\$\\{/u;\n\ntype PlanPolicyContext = ToolPluginContext & {\n on(\n event: 'agent/pre-step',\n listener: (\n payload: { agent: object; turn: number },\n next: () => Promise<unknown>,\n ) => Promise<unknown>,\n ): unknown;\n on(\n event: 'tools/pre-execute',\n listener: (\n execution: PlanPolicyExecution,\n next: () => Promise<unknown>,\n ) => Promise<unknown>,\n ): unknown;\n};\n\n/** Human plan gate for substantial or high-risk repository actions. */\nexport function apply(ctx: Context, config: Config = {}) {\n const policyCtx = ctx as PlanPolicyContext;\n const currentTurns = new WeakMap<object, number>();\n const approvedCalls = new WeakMap<object, number>();\n const gateDisabled = (config.mode ?? process.env.DSH_LARK_PLAN_GATE) === 'off';\n\n policyCtx.on('agent/pre-step', async (payload, next) => {\n currentTurns.set(payload.agent, payload.turn);\n return next();\n });\n policyCtx.on('tools/pre-execute', async (execution, next) => {\n if (gateDisabled) return next();\n if (!isHighRiskTool(policyCtx, execution)) return next();\n const agent = execution.agent;\n const turn = agent ? currentTurns.get(agent) : undefined;\n if (agent && turn !== undefined && approvedCalls.get(agent) === turn) {\n approvedCalls.delete(agent);\n return next();\n }\n return {\n kind: 'deny',\n reason:\n 'This action is blocked until the current turn calls lark_request_plan_approval and the user approves the plan.',\n };\n });\n\n policyCtx.tools.register({\n name: 'lark_request_plan_approval',\n description:\n 'Before modifying files, running scripts, or taking another substantial/high-risk action, draft a complete plan and call this tool before execution. It sends the full plan as a normal Feishu/Lark message, then waits for Approve or Continue planning plus optional feedback. Do not execute until approved. If revision is requested, revise the plan and call this tool again.',\n parameters: {\n type: 'object',\n additionalProperties: false,\n required: ['plan'],\n properties: {\n plan: { type: 'string', minLength: 1, description: 'Complete readable plan in Markdown.' },\n },\n },\n output: {\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['resolved'],\n properties: {\n resolved: { type: 'boolean' },\n decision: { type: 'string', enum: ['approved', 'revise'] },\n feedback: { type: 'string' },\n error: { type: 'string' },\n },\n },\n render: (_args, rawValue) => {\n const value = rawValue as {\n resolved: boolean;\n decision?: string;\n feedback?: string;\n error?: string;\n };\n return [{\n type: 'text',\n text: value.resolved\n ? `Plan decision: ${value.decision}${value.feedback ? `; feedback: ${value.feedback}` : ''}`\n : `Plan approval failed: ${value.error ?? 'cancelled'}`,\n }];\n },\n },\n async execute(rawArgs, exec: RawToolExecution | undefined) {\n const args = objectArgs(rawArgs, 'lark_request_plan_approval');\n const plan = requiredString(args, 'plan', 'lark_request_plan_approval');\n const endpoint = config.endpoint ?? process.env.DSH_LARK_PLAN_URL;\n const token = config.token ?? process.env.DSH_LARK_NOTIFY_TOKEN;\n if (!endpoint || !token) {\n throw new Error('lark_request_plan_approval is not configured (endpoint/token missing)');\n }\n const sessionId = exec?.agent?.session === undefined\n ? undefined\n : String(exec.agent.session.id);\n if (!sessionId) throw new Error('lark_request_plan_approval needs an active session');\n let response: Response;\n try {\n response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ token, sessionId, plan }),\n ...(exec?.signal === undefined ? {} : { signal: exec.signal }),\n });\n } catch (error) {\n if (exec?.signal?.aborted) return { resolved: false, error: 'cancelled' };\n throw error;\n }\n const body = await response.json() as {\n ok?: boolean;\n decision?: 'approved' | 'revise';\n feedback?: string;\n error?: string;\n };\n if (!response.ok || body.ok !== true || !body.decision) {\n if (body.error?.toLowerCase().includes('cancel')) {\n return { resolved: false, error: body.error };\n }\n throw new Error(body.error ?? `plan approval delivery failed (${response.status})`);\n }\n if (body.decision === 'approved' && exec?.agent) {\n const turn = currentTurns.get(exec.agent);\n if (turn !== undefined) approvedCalls.set(exec.agent, turn);\n }\n return {\n resolved: true,\n decision: body.decision,\n ...(body.feedback ? { feedback: body.feedback } : {}),\n };\n },\n });\n}\n\nexport function isHighRiskTool(ctx: ToolPluginContext, execution: PlanPolicyExecution): boolean {\n if (execution.name === 'lark_request_plan_approval') return false;\n if (execution.name === 'run_code') return true;\n const normalized = execution.name.toLowerCase().replaceAll('-', '_');\n if (READ_ONLY_SHELL_TOOLS.has(normalized)) {\n return !isSimpleReadOnlyShellCommand(execution.arguments);\n }\n try {\n const view = ctx.tools.get?.(execution.name, execution.agent)?.presentCall?.(\n execution.arguments,\n ) as { card?: string; kind?: string } | undefined;\n if (view?.card === 'terminal' || view?.card === 'diff') return true;\n const kind = view?.kind;\n if (kind && ['edit', 'delete', 'move', 'execute'].includes(kind)) return true;\n } catch {\n // Fall through to the conservative name classifier.\n }\n return /(^|_)(bash|shell|exec|execute|run|write|edit|patch|delete|remove|move|rename)(_|$)/u\n .test(normalized);\n}\n\n/**\n * Read-only shell calls bypass both the plan gate and one-shot approval.\n * Keep this deliberately narrow: one command only, no shell composition, and\n * an allowlisted executable/subcommand. Unknown syntax remains high risk.\n */\nfunction isSimpleReadOnlyShellCommand(rawArguments: unknown): boolean {\n const command = shellCommand(rawArguments)?.trim();\n if (!command || SHELL_CONTROL_SYNTAX.test(command)) return false;\n const words = command.split(/\\s+/u);\n const executablePath = words[0];\n if (\n !executablePath ||\n (executablePath.includes('/') &&\n !executablePath.startsWith('/bin/') &&\n !executablePath.startsWith('/usr/bin/'))\n ) return false;\n const executable = executablePath.split('/').at(-1);\n if (!executable) return false;\n if (executable === 'git') return isReadOnlyGitCommand(words.slice(1));\n if (!READ_ONLY_COMMANDS.has(executable)) return false;\n if (executable === 'date') {\n return words.slice(1).every((word) =>\n word === '-u' || word === '--utc' || word === '--universal' || word.startsWith('+')\n );\n }\n if (executable === 'rg') {\n return !words.slice(1).some((word) =>\n word === '--pre' ||\n word.startsWith('--pre=') ||\n word === '--hostname-bin' ||\n word.startsWith('--hostname-bin=')\n );\n }\n if (executable === 'find') {\n return !words.slice(1).some((word) =>\n ['-delete', '-exec', '-execdir', '-ok', '-okdir', '-fprint', '-fprint0', '-fprintf'].includes(word)\n );\n }\n if (executable === 'tail') {\n return !words.slice(1).some((word) =>\n word === '-f' || word === '-F' || word === '--follow' || word.startsWith('--follow=')\n );\n }\n return true;\n}\n\nfunction shellCommand(rawArguments: unknown): string | undefined {\n if (typeof rawArguments === 'object' && rawArguments !== null && !Array.isArray(rawArguments)) {\n const entries = Object.entries(rawArguments);\n if (entries.length !== 1 || entries[0]?.[0] !== 'command') return undefined;\n const command = entries[0][1];\n return typeof command === 'string' ? command : undefined;\n }\n if (typeof rawArguments !== 'string') return undefined;\n try {\n return shellCommand(JSON.parse(rawArguments));\n } catch {\n return rawArguments;\n }\n}\n\nfunction isReadOnlyGitCommand(words: readonly string[]): boolean {\n let index = 0;\n while (words[index] === '-C') {\n if (!words[index + 1]) return false;\n index += 2;\n }\n const subcommand = words[index];\n if (subcommand === 'branch') {\n const flags = words.slice(index + 1);\n return flags.length === 0 || flags.every((word) =>\n ['--show-current', '--list', '--all', '-a', '--remotes', '-r', '-v', '-vv'].includes(word)\n );\n }\n if (subcommand === 'remote') {\n const args = words.slice(index + 1);\n return args.length === 0 ||\n args.every((word) => word === '-v' || word === '--verbose') ||\n args[0] === 'get-url';\n }\n if (!subcommand || !READ_ONLY_GIT_SUBCOMMANDS.has(subcommand)) return false;\n return !words.slice(index + 1).some((word) =>\n word === '-o' ||\n word === '--output' ||\n word.startsWith('--output=') ||\n word === '--ext-diff' ||\n word === '--textconv'\n );\n}\n","import type { Context } from '@deepseek-ai/cordis';\nimport { isHighRiskTool, type PlanPolicyExecution } from './plan-tool.js';\nimport type { ToolPluginContext } from './raw-tool.js';\n\nexport const name = 'lark-approval-answerer';\nexport const inject = ['approval', 'tools'];\n\nexport interface Config {\n endpoint?: string;\n token?: string;\n}\n\ntype Outcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';\n\ninterface RawApprovalRequest {\n agent?: { session?: { id?: unknown } };\n toolName?: unknown;\n callId?: unknown;\n reason?: unknown;\n toolInput?: unknown;\n signal?: AbortSignal;\n}\n\ntype ApprovalContext = Context & {\n on(\n event: 'approval/request',\n listener: (request: RawApprovalRequest, next: () => Promise<Outcome>) => Promise<Outcome>,\n ): unknown;\n on(\n event: 'tools/pre-execute',\n listener: (\n execution: PlanPolicyExecution,\n next: () => Promise<unknown>,\n ) => Promise<unknown>,\n ): unknown;\n};\n\n/** Terminal rc.8 approval answerer for the nested SDK and host runtimes. */\nexport function apply(ctx: Context, config: Config = {}): void {\n const approvalCtx = ctx as ApprovalContext & ToolPluginContext;\n const inFlightGrant = new WeakMap<object, string>();\n\n approvalCtx.on('approval/request', async (request, next) => {\n if (request.agent && inFlightGrant.get(request.agent) === request.toolName) {\n inFlightGrant.delete(request.agent);\n return 'allowed-once';\n }\n return requestBridgeApproval(config, request, next);\n });\n\n approvalCtx.on('tools/pre-execute', async (execution, next) => {\n if (!isHighRiskTool(approvalCtx, execution)) return next();\n const request: RawApprovalRequest = {\n ...(execution.agent === undefined\n ? {}\n : { agent: execution.agent as NonNullable<RawApprovalRequest['agent']> }),\n toolName: execution.name,\n reason: approvalReason(execution),\n toolInput: execution.arguments,\n };\n const outcome = await requestBridgeApproval(config, request, async () => 'unavailable');\n if (outcome !== 'allowed-once') {\n return {\n kind: 'deny',\n reason: outcome === 'rejected'\n ? 'The user rejected this one-shot tool execution. Continue with a safer alternative.'\n : 'This tool execution was not approved and remains blocked.',\n };\n }\n if (execution.agent) inFlightGrant.set(execution.agent, execution.name);\n try {\n return await next();\n } finally {\n if (execution.agent) inFlightGrant.delete(execution.agent);\n }\n });\n}\n\nasync function requestBridgeApproval(\n config: Config,\n request: RawApprovalRequest,\n next: () => Promise<Outcome>,\n): Promise<Outcome> {\n const endpoint = config.endpoint ?? process.env.DSH_LARK_APPROVAL_URL;\n const token = config.token ?? process.env.DSH_LARK_NOTIFY_TOKEN;\n if (!endpoint || !token) return next();\n const sessionId = request.agent?.session?.id;\n if (sessionId === undefined || typeof request.toolName !== 'string') return 'unavailable';\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n token,\n sessionId: String(sessionId),\n toolName: request.toolName,\n ...(request.callId === undefined ? {} : { callId: String(request.callId) }),\n ...(typeof request.reason === 'string' ? { reason: request.reason } : {}),\n ...(request.toolInput === undefined ? {} : { toolInput: request.toolInput }),\n }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n });\n const body = await response.json() as { ok?: boolean; outcome?: unknown };\n return response.ok && body.ok === true && isOutcome(body.outcome)\n ? body.outcome\n : 'unavailable';\n } catch {\n return request.signal?.aborted ? 'cancelled' : 'unavailable';\n }\n}\n\nfunction approvalReason(execution: PlanPolicyExecution): string {\n if (\n typeof execution.arguments === 'object' && execution.arguments !== null &&\n 'description' in execution.arguments &&\n typeof (execution.arguments as { description?: unknown }).description === 'string'\n ) {\n return (execution.arguments as { description: string }).description;\n }\n return `Execute high-risk tool ${execution.name}`;\n}\n\nfunction isOutcome(value: unknown): value is Outcome {\n return value === 'allowed-once' || value === 'rejected' ||\n value === 'cancelled' || value === 'unavailable';\n}\n"],"mappings":";AAuBA,IAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,OAAO,CAAC;AACvD,IAAM,qBAAqB,oBAAI,IAAI;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,4BAA4B,oBAAI,IAAI;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,uBAAuB;AAsItB,SAAS,eAAe,KAAwB,WAAyC;AAC9F,MAAI,UAAU,SAAS,6BAA8B,QAAO;AAC5D,MAAI,UAAU,SAAS,WAAY,QAAO;AAC1C,QAAM,aAAa,UAAU,KAAK,YAAY,EAAE,WAAW,KAAK,GAAG;AACnE,MAAI,sBAAsB,IAAI,UAAU,GAAG;AACzC,WAAO,CAAC,6BAA6B,UAAU,SAAS;AAAA,EAC1D;AACA,MAAI;AACF,UAAM,OAAO,IAAI,MAAM,MAAM,UAAU,MAAM,UAAU,KAAK,GAAG;AAAA,MAC7D,UAAU;AAAA,IACZ;AACA,QAAI,MAAM,SAAS,cAAc,MAAM,SAAS,OAAQ,QAAO;AAC/D,UAAM,OAAO,MAAM;AACnB,QAAI,QAA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,UAAU,kBAAkB,UAAU,cAC3C,UAAU,eAAe,UAAU;AACvC;","names":[]}
1
+ {"version":3,"sources":["../src/policy/tool-policy.ts","../src/notify/approval-answerer.ts"],"sourcesContent":["import type { ToolPluginContext } from '../notify/raw-tool.js';\n\nexport type PolicyLayer = 'plan-gate' | 'permission-policy' | 'tool-approval' | 'file-sandbox';\n\nexport interface PolicyDenial {\n layer: PolicyLayer;\n reason: string;\n toChange: string;\n}\n\nexport interface PlanPolicyExecution {\n name: string;\n arguments: unknown;\n agent?: object;\n}\n\nconst READ_ONLY_SHELL_TOOLS = new Set(['bash', 'shell']);\nconst READ_ONLY_COMMANDS = new Set([\n 'date', 'id', 'pwd', 'uname', 'whoami',\n]);\nconst READ_ONLY_GIT_SUBCOMMANDS = new Set([\n 'diff', 'ls-files', 'ls-tree', 'log', 'merge-base', 'rev-parse', 'show', 'status',\n]);\nconst SHELL_CONTROL_SYNTAX = /[\\n\\r;&|<>`]|\\$\\(|\\$\\{/u;\n\nexport function policyDenialText(denial: PolicyDenial): string {\n return `[policy-denial layer=${denial.layer}] denied by ${denial.layer}: ${denial.reason}\\n` +\n `to change: ${denial.toChange}`;\n}\n\nexport function planGateDenial(): PolicyDenial {\n return {\n layer: 'plan-gate',\n reason: 'this substantial or high-risk action has no plan approval for the current turn',\n toChange: 'call lark_request_plan_approval and wait for approval; /permission does not change the plan gate',\n };\n}\n\nexport function permissionPolicyDenial(scope: string, toolName: string): PolicyDenial {\n return {\n layer: 'permission-policy',\n reason: `tool ${toolName} is blocked by scope ${scope}'s deny policy`,\n toChange: `an admin can run /permission ask ${scope} or /permission allow ${scope}`,\n };\n}\n\nexport function toolApprovalDenial(toolName: string): PolicyDenial {\n return {\n layer: 'tool-approval',\n reason: `the user rejected the one-shot approval for tool ${toolName}`,\n toChange: 'choose a safer alternative or ask the user before requesting approval again',\n };\n}\n\n/** Persona text generated from the same command vocabulary used for enforcement. */\nexport function renderToolPolicyPersona(): string[] {\n return [\n `The bridge policy treats one uncomposed shell call as read-only only when its executable is one of: ${[...READ_ONLY_COMMANDS].join(', ')}; read-only git subcommands are ${[...READ_ONLY_GIT_SUBCOMMANDS].join(', ')} plus listing branch/remote forms.`,\n 'Read-only calls must not use chaining, redirects, command substitution, background execution, escalation, or mutating flags; run qualifying inspections directly.',\n 'Before modifying files, installing packages, running scripts, pushing, deleting, or taking another substantial or high-risk action, use lark_request_plan_approval and wait for approval.',\n 'The plan-gate confirms the intended plan; /permission separately controls per-tool approval and never bypasses the plan-gate or the Harness file-sandbox.',\n 'Policy refusals use [policy-denial layer=...] with a reason and to-change instruction. Harness errors beginning [sandbox: ...] are file-sandbox refusals. Report the named layer and exact error; never invent a different restriction.',\n 'After any policy or sandbox refusal, do not try an equivalent command, tool, or path to obtain the same result. Stop, report the refusal accurately, and let the user decide whether to change the policy or approve another approach.',\n ];\n}\n\nexport function isHighRiskTool(ctx: ToolPluginContext, execution: PlanPolicyExecution): boolean {\n if (execution.name === 'lark_request_plan_approval') return false;\n if (execution.name === 'run_code') return true;\n const normalized = execution.name.toLowerCase().replaceAll('-', '_');\n if (READ_ONLY_SHELL_TOOLS.has(normalized)) {\n return !isSimpleReadOnlyShellCommand(execution.arguments);\n }\n try {\n const view = ctx.tools.get?.(execution.name, execution.agent)?.presentCall?.(\n execution.arguments,\n ) as { card?: string; kind?: string } | undefined;\n if (view?.card === 'terminal' || view?.card === 'diff') return true;\n const kind = view?.kind;\n if (kind && ['edit', 'delete', 'move', 'execute'].includes(kind)) return true;\n } catch {\n // Fall through to the conservative name classifier.\n }\n return /(^|_)(bash|shell|exec|execute|run|write|edit|patch|delete|remove|move|rename)(_|$)/u\n .test(normalized);\n}\n\nfunction isSimpleReadOnlyShellCommand(rawArguments: unknown): boolean {\n const command = shellCommand(rawArguments)?.trim();\n if (!command || SHELL_CONTROL_SYNTAX.test(command)) return false;\n const words = command.split(/\\s+/u);\n const executablePath = words[0];\n if (\n !executablePath ||\n (executablePath.includes('/') &&\n !executablePath.startsWith('/bin/') &&\n !executablePath.startsWith('/usr/bin/'))\n ) return false;\n const executable = executablePath.split('/').at(-1);\n if (!executable) return false;\n if (executable === 'git') return isReadOnlyGitCommand(words.slice(1));\n if (!READ_ONLY_COMMANDS.has(executable)) return false;\n if (executable === 'date') {\n return words.slice(1).every((word) =>\n word === '-u' || word === '--utc' || word === '--universal' || word.startsWith('+')\n );\n }\n return words.length === 1;\n}\n\nfunction shellCommand(rawArguments: unknown): string | undefined {\n if (typeof rawArguments === 'object' && rawArguments !== null && !Array.isArray(rawArguments)) {\n const record = rawArguments as Record<string, unknown>;\n const allowedKeys = new Set(['command', 'description', 'workdir', 'run_in_background']);\n if (Object.keys(record).some((key) => !allowedKeys.has(key))) return undefined;\n if (record.description !== undefined && typeof record.description !== 'string') return undefined;\n if (record.workdir !== undefined && typeof record.workdir !== 'string') return undefined;\n if (record.run_in_background !== undefined && record.run_in_background !== false) return undefined;\n const command = record.command;\n return typeof command === 'string' ? command : undefined;\n }\n if (typeof rawArguments !== 'string') return undefined;\n try {\n return shellCommand(JSON.parse(rawArguments));\n } catch {\n return rawArguments;\n }\n}\n\nfunction isReadOnlyGitCommand(words: readonly string[]): boolean {\n const index = 0;\n const subcommand = words[index];\n if (subcommand === 'branch') {\n const flags = words.slice(index + 1);\n return flags.length === 0 || flags.every((word) =>\n ['--show-current', '--list', '--all', '-a', '--remotes', '-r', '-v', '-vv'].includes(word)\n );\n }\n if (subcommand === 'remote') {\n const args = words.slice(index + 1);\n return args.length === 0 ||\n args.every((word) => word === '-v' || word === '--verbose') ||\n args[0] === 'get-url';\n }\n if (!subcommand || !READ_ONLY_GIT_SUBCOMMANDS.has(subcommand)) return false;\n return !words.slice(index + 1).some((word) =>\n word === '-o' || word === '--output' || word.startsWith('--output=') ||\n word === '--ext-diff' || word === '--textconv' || word === '--no-index' ||\n word.startsWith('/') || word.startsWith('~') || /(^|\\/)\\.\\.(\\/|$)/u.test(word)\n );\n}\n","import type { Context } from '@deepseek-ai/cordis';\nimport {\n isHighRiskTool,\n policyDenialText,\n toolApprovalDenial,\n type PlanPolicyExecution,\n type PolicyDenial,\n} from '../policy/tool-policy.js';\nimport type { ToolPluginContext } from './raw-tool.js';\n\nexport const name = 'lark-approval-answerer';\nexport const inject = ['approval', 'tools'];\n\nexport interface Config {\n endpoint?: string;\n token?: string;\n}\n\ntype Outcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';\n\ninterface ApprovalDecision {\n outcome: Outcome;\n denial?: PolicyDenial;\n}\n\ninterface RawApprovalRequest {\n agent?: { session?: { id?: unknown } };\n toolName?: unknown;\n callId?: unknown;\n reason?: unknown;\n toolInput?: unknown;\n signal?: AbortSignal;\n lowRisk?: boolean;\n}\n\ntype ApprovalContext = Context & {\n on(\n event: 'approval/request',\n listener: (request: RawApprovalRequest, next: () => Promise<Outcome>) => Promise<Outcome>,\n ): unknown;\n on(\n event: 'tools/pre-execute',\n listener: (\n execution: PlanPolicyExecution,\n next: () => Promise<unknown>,\n ) => Promise<unknown>,\n ): unknown;\n};\n\n/** Terminal rc.8 approval answerer for the nested SDK and host runtimes. */\nexport function apply(ctx: Context, config: Config = {}): void {\n const approvalCtx = ctx as ApprovalContext & ToolPluginContext;\n const inFlightGrant = new WeakMap<object, string>();\n\n approvalCtx.on('approval/request', async (request, next) => {\n if (request.agent && inFlightGrant.get(request.agent) === request.toolName) {\n inFlightGrant.delete(request.agent);\n return 'allowed-once';\n }\n return (await requestBridgeApproval(config, request, next)).outcome;\n });\n\n approvalCtx.on('tools/pre-execute', async (execution, next) => {\n const highRisk = isHighRiskTool(approvalCtx, execution);\n if (!highRisk && !approvalEndpoint(config)) return next();\n const request: RawApprovalRequest = {\n ...(execution.agent === undefined\n ? {}\n : { agent: execution.agent as NonNullable<RawApprovalRequest['agent']> }),\n toolName: execution.name,\n reason: approvalReason(execution),\n toolInput: execution.arguments,\n lowRisk: !highRisk,\n };\n const decision = await requestBridgeApproval(config, request, async () => 'unavailable');\n if (decision.outcome !== 'allowed-once') {\n return {\n kind: 'deny',\n reason: policyDenialText(\n decision.denial ?? (\n decision.outcome === 'rejected'\n ? toolApprovalDenial(execution.name)\n : {\n layer: 'tool-approval',\n reason: `tool ${execution.name} did not receive approval (${decision.outcome})`,\n toChange: 'retry only after approval is available, or choose a safer alternative',\n }\n ),\n ),\n };\n }\n if (execution.agent) inFlightGrant.set(execution.agent, execution.name);\n try {\n return await next();\n } finally {\n if (execution.agent) inFlightGrant.delete(execution.agent);\n }\n });\n}\n\nasync function requestBridgeApproval(\n config: Config,\n request: RawApprovalRequest,\n next: () => Promise<Outcome>,\n): Promise<ApprovalDecision> {\n const endpoint = approvalEndpoint(config);\n const token = config.token ?? process.env.DSH_LARK_NOTIFY_TOKEN;\n if (!endpoint || !token) return { outcome: await next() };\n const sessionId = request.agent?.session?.id;\n if (sessionId === undefined || typeof request.toolName !== 'string') {\n return { outcome: 'unavailable' };\n }\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n token,\n sessionId: String(sessionId),\n toolName: request.toolName,\n ...(request.callId === undefined ? {} : { callId: String(request.callId) }),\n ...(typeof request.reason === 'string' ? { reason: request.reason } : {}),\n ...(request.toolInput === undefined ? {} : { toolInput: request.toolInput }),\n ...('lowRisk' in request && request.lowRisk === true ? { lowRisk: true } : {}),\n }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n });\n const body = await response.json() as {\n ok?: boolean;\n outcome?: unknown;\n denial?: unknown;\n };\n return response.ok && body.ok === true && isOutcome(body.outcome)\n ? {\n outcome: body.outcome,\n ...(isPolicyDenial(body.denial) ? { denial: body.denial } : {}),\n }\n : { outcome: 'unavailable' };\n } catch {\n return { outcome: request.signal?.aborted ? 'cancelled' : 'unavailable' };\n }\n}\n\nfunction approvalEndpoint(config: Config): string | undefined {\n return config.endpoint ?? process.env.DSH_LARK_APPROVAL_URL;\n}\n\nfunction approvalReason(execution: PlanPolicyExecution): string {\n if (\n typeof execution.arguments === 'object' && execution.arguments !== null &&\n 'description' in execution.arguments &&\n typeof (execution.arguments as { description?: unknown }).description === 'string'\n ) {\n return (execution.arguments as { description: string }).description;\n }\n return `Execute high-risk tool ${execution.name}`;\n}\n\nfunction isOutcome(value: unknown): value is Outcome {\n return value === 'allowed-once' || value === 'rejected' ||\n value === 'cancelled' || value === 'unavailable';\n}\n\nfunction isPolicyDenial(value: unknown): value is PolicyDenial {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const denial = value as Partial<PolicyDenial>;\n return (\n denial.layer === 'plan-gate' || denial.layer === 'permission-policy' ||\n denial.layer === 'tool-approval' || denial.layer === 'file-sandbox'\n ) && typeof denial.reason === 'string' && typeof denial.toChange === 'string';\n}\n"],"mappings":";AAgBA,IAAM,wBAAwB,oBAAI,IAAI,CAAC,QAAQ,OAAO,CAAC;AACvD,IAAM,qBAAqB,oBAAI,IAAI;AAAA,EACjC;AAAA,EAAQ;AAAA,EAAM;AAAA,EAAO;AAAA,EAAS;AAChC,CAAC;AACD,IAAM,4BAA4B,oBAAI,IAAI;AAAA,EACxC;AAAA,EAAQ;AAAA,EAAY;AAAA,EAAW;AAAA,EAAO;AAAA,EAAc;AAAA,EAAa;AAAA,EAAQ;AAC3E,CAAC;AACD,IAAM,uBAAuB;AAEtB,SAAS,iBAAiB,QAA8B;AAC7D,SAAO,wBAAwB,OAAO,KAAK,eAAe,OAAO,KAAK,KAAK,OAAO,MAAM;AAAA,aACxE,OAAO,QAAQ;AACjC;AAkBO,SAAS,mBAAmB,UAAgC;AACjE,SAAO;AAAA,IACL,OAAO;AAAA,IACP,QAAQ,oDAAoD,QAAQ;AAAA,IACpE,UAAU;AAAA,EACZ;AACF;AAcO,SAAS,eAAe,KAAwB,WAAyC;AAC9F,MAAI,UAAU,SAAS,6BAA8B,QAAO;AAC5D,MAAI,UAAU,SAAS,WAAY,QAAO;AAC1C,QAAM,aAAa,UAAU,KAAK,YAAY,EAAE,WAAW,KAAK,GAAG;AACnE,MAAI,sBAAsB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