@thincoder/core 0.11.1 → 0.11.2
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/CHANGELOG.md +46 -2
- package/advisor/convergence.mjs +34 -3
- package/advisor/loop.mjs +42 -10
- package/advisor/messages.mjs +42 -25
- package/advisor/project-context.mjs +171 -42
- package/advisor/run.mjs +7 -4
- package/advisor.mjs +29 -43
- package/agent/batch-attribution.mjs +87 -0
- package/agent/batch-changed-surface.mjs +129 -0
- package/agent/completion.mjs +44 -3
- package/agent/dispatch-gates.mjs +6 -0
- package/agent/dispatch.mjs +8 -3
- package/agent/family-tools.mjs +27 -12
- package/agent/helpers.mjs +122 -1
- package/agent/offload.mjs +25 -29
- package/agent/post-turn.mjs +24 -10
- package/agent/record-results.mjs +18 -1
- package/agent/run-stages.mjs +77 -32
- package/agent/run-start.mjs +37 -0
- package/agent/setup-reminders.mjs +9 -2
- package/agent/setup.mjs +24 -11
- package/agent/spawn-child.mjs +38 -1
- package/agent/timers.mjs +5 -3
- package/agent/turn-loop.mjs +30 -5
- package/agent/turn-projection.mjs +386 -0
- package/agent/turn-task-state.mjs +274 -0
- package/agent/turn-tool-process.mjs +168 -0
- package/agent/write-gate-ledger.mjs +569 -0
- package/agent/write-gate.mjs +29 -352
- package/agent-tools/advisor-async.mjs +29 -169
- package/agent-tools/advisor-launch.mjs +178 -0
- package/agent-tools/advisor-settle.mjs +28 -1
- package/agent-tools/advisor.mjs +36 -47
- package/agent-tools/audit-block.mjs +6 -6
- package/agent-tools/batch-closeout.mjs +273 -35
- package/agent-tools/batch-gate.mjs +142 -342
- package/agent-tools/batch-ledger-bind.mjs +226 -17
- package/agent-tools/batch-ledger-view.mjs +109 -0
- package/agent-tools/batch-lifecycle.mjs +169 -46
- package/agent-tools/batch-paths.mjs +29 -8
- package/agent-tools/batch-record-write.mjs +417 -0
- package/agent-tools/batch-regions.mjs +215 -0
- package/agent-tools/batch-reopen.mjs +23 -11
- package/agent-tools/batch-segment-vocab.mjs +379 -0
- package/agent-tools/batch-skeleton.mjs +192 -239
- package/agent-tools/batch-supersede.mjs +232 -0
- package/agent-tools/batch-tier-gate.mjs +297 -0
- package/agent-tools/batch.mjs +182 -439
- package/agent-tools/consult.mjs +7 -4
- package/agent-tools/context.mjs +44 -17
- package/agent-tools/design-review-record.mjs +225 -0
- package/agent-tools/design-slots.mjs +1 -1
- package/agent-tools/design-token.mjs +279 -81
- package/agent-tools/doc-check.mjs +43 -33
- package/agent-tools/doc-graph.mjs +140 -0
- package/agent-tools/eng.mjs +9 -8
- package/agent-tools/escalate-async.mjs +2 -2
- package/agent-tools/manifest.mjs +34 -18
- package/agent-tools/read-history.mjs +112 -11
- package/agent-tools/review-facts.mjs +10 -3
- package/agent-tools/settings.mjs +23 -2
- package/agent-tools/spawn-gates.mjs +9 -8
- package/agent-tools/ssh-session.mjs +2 -2
- package/agent-tools/ssh-text.mjs +155 -0
- package/agent-tools/ssh-transport.mjs +19 -148
- package/agent-tools/subagent-actions-query.mjs +10 -6
- package/agent-tools/subagent-async.mjs +8 -9
- package/agent-tools/subagent-brief.mjs +76 -0
- package/agent-tools/subagent-design-token.mjs +168 -0
- package/agent-tools/subagent-run.mjs +1 -1
- package/agent-tools/subagent-scheduler.mjs +4 -4
- package/agent-tools/subagent-spawn.mjs +90 -110
- package/agent-tools/subagent.mjs +11 -10
- package/agent-tools/taskbook-block.mjs +94 -0
- package/agent-tools/timer.mjs +12 -8
- package/agent-tools/verify.mjs +13 -4
- package/agent-tools.mjs +7 -3
- package/agent.mjs +20 -1
- package/attachments.mjs +3 -3
- package/browser/actions.mjs +9 -3
- package/browser/cdp.mjs +45 -17
- package/browser/launch.mjs +25 -43
- package/browser/pool.mjs +299 -0
- package/browser/queue.mjs +2 -0
- package/browser/session-state.mjs +450 -0
- package/browser/session.mjs +127 -151
- package/browser/snapshot.mjs +89 -0
- package/client-identity.mjs +1 -1
- package/config-defaults.mjs +2 -1
- package/config-migrate.mjs +40 -0
- package/config-normalize.mjs +28 -2
- package/config-reload.mjs +59 -0
- package/config.mjs +62 -98
- package/context-degrade.mjs +38 -10
- package/context-echo.mjs +11 -0
- package/context.mjs +149 -83
- package/conventions.mjs +11 -9
- package/declaration.mjs +31 -5
- package/declared-repos.mjs +94 -0
- package/doc-check/doc-names.mjs +73 -0
- package/doc-check/doc-tokens.mjs +110 -0
- package/doc-check/existence.mjs +160 -0
- package/doc-check/index.mjs +309 -213
- package/doc-check/line-refs.mjs +27 -101
- package/doc-check/paragraph.mjs +218 -102
- package/doc-graph/anchors.mjs +474 -0
- package/doc-graph/doc-batch-face.mjs +59 -0
- package/doc-graph/doc-suffix.mjs +27 -0
- package/doc-graph/graph-tokens.mjs +160 -0
- package/doc-graph.mjs +778 -0
- package/explore-distill.mjs +11 -5
- package/i18n.mjs +1 -1
- package/instance-inbox-watch.mjs +272 -0
- package/instance-inbox.mjs +218 -0
- package/instance-registry.mjs +179 -0
- package/knowledge/README.md +3 -0
- package/knowledge/prompt-resources.md +6 -0
- package/ledger-close-proof.mjs +100 -49
- package/ledger-close.mjs +188 -0
- package/ledger-cmd.mjs +47 -91
- package/ledger-consistency.mjs +113 -0
- package/ledger-db.mjs +47 -15
- package/ledger-executors.mjs +1 -1
- package/ledger-tools.mjs +78 -19
- package/ledger-write-ops.mjs +130 -41
- package/ledger.mjs +1 -1
- package/manifest-discovery.mjs +3 -1
- package/manifest-schema.mjs +27 -5
- package/memory/schema.mjs +2 -2
- package/package.json +3 -1
- package/path-resolve.mjs +338 -57
- package/prompt-files.mjs +91 -1
- package/prompt-overlays.mjs +9 -6
- package/prompts/advisor-design.md +62 -21
- package/prompts/advisor-round1.md +34 -1
- package/prompts/advisor-round2.md +40 -7
- package/prompts/advisor-round3.md +39 -6
- package/prompts/common.md +14 -387
- package/prompts/consult-base.md +5 -1
- package/prompts/discipline-engineering.md +226 -51
- package/prompts/discipline-normal.md +4 -255
- package/prompts/knowledge/business-gates.md +22 -0
- package/prompts/knowledge/decision-quality.md +23 -0
- package/prompts/knowledge/doc-lookup.md +35 -0
- package/prompts/knowledge/document-writing.md +51 -0
- package/prompts/knowledge/documentation-evaluation.md +56 -0
- package/prompts/knowledge/evidence-discipline.md +57 -0
- package/prompts/knowledge/normal-coding-workflow.md +104 -0
- package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
- package/prompts/knowledge/normal-work-management.md +57 -0
- package/prompts/knowledge/product-security.md +23 -0
- package/prompts/knowledge/project-records.md +62 -0
- package/prompts/knowledge/tool-advisor.md +29 -0
- package/prompts/knowledge/tool-apply-patch.md +18 -0
- package/prompts/knowledge/tool-bash.md +39 -0
- package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
- package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
- package/prompts/knowledge/tool-batch-review.md +12 -0
- package/prompts/knowledge/tool-batch.md +80 -0
- package/prompts/knowledge/tool-browser.md +57 -0
- package/prompts/knowledge/tool-code-search.md +4 -0
- package/prompts/knowledge/tool-consult-start.md +12 -0
- package/prompts/knowledge/tool-consult-stop.md +6 -0
- package/prompts/knowledge/tool-context.md +6 -0
- package/prompts/knowledge/tool-delete.md +17 -0
- package/prompts/knowledge/tool-doc-check.md +70 -0
- package/prompts/knowledge/tool-doc-graph-read.md +20 -0
- package/prompts/knowledge/tool-doc-graph.md +49 -0
- package/prompts/knowledge/tool-doc-search.md +6 -0
- package/prompts/knowledge/tool-edit.md +38 -0
- package/prompts/knowledge/tool-eng.md +2 -0
- package/prompts/knowledge/tool-execute.md +16 -0
- package/prompts/knowledge/tool-fetch.md +12 -0
- package/prompts/knowledge/tool-file-ops.md +16 -0
- package/prompts/knowledge/tool-get-current-time.md +7 -0
- package/prompts/knowledge/tool-git-read.md +19 -0
- package/prompts/knowledge/tool-git.md +29 -0
- package/prompts/knowledge/tool-glob.md +15 -0
- package/prompts/knowledge/tool-goal.md +8 -0
- package/prompts/knowledge/tool-grep.md +18 -0
- package/prompts/knowledge/tool-hashline-edit.md +14 -0
- package/prompts/knowledge/tool-insert-after.md +15 -0
- package/prompts/knowledge/tool-instance-list.md +6 -0
- package/prompts/knowledge/tool-instance-send.md +10 -0
- package/prompts/knowledge/tool-knowledge.md +18 -0
- package/prompts/knowledge/tool-ledger-read.md +35 -0
- package/prompts/knowledge/tool-ledger.md +42 -0
- package/prompts/knowledge/tool-lint.md +16 -0
- package/prompts/knowledge/tool-ls.md +13 -0
- package/prompts/knowledge/tool-lsp.md +11 -0
- package/prompts/knowledge/tool-main-history.md +2 -0
- package/prompts/knowledge/tool-manifest-read.md +14 -0
- package/prompts/knowledge/tool-manifest.md +31 -0
- package/prompts/knowledge/tool-memory-read.md +20 -0
- package/prompts/knowledge/tool-memory.md +15 -0
- package/prompts/knowledge/tool-notify-parent.md +12 -0
- package/prompts/knowledge/tool-operations.md +114 -0
- package/prompts/knowledge/tool-peer-instances.md +2 -0
- package/prompts/knowledge/tool-plan.md +6 -0
- package/prompts/knowledge/tool-process-read.md +13 -0
- package/prompts/knowledge/tool-process.md +15 -0
- package/prompts/knowledge/tool-question.md +16 -0
- package/prompts/knowledge/tool-read-history-batch.md +22 -0
- package/prompts/knowledge/tool-read-history.md +36 -0
- package/prompts/knowledge/tool-read-image.md +11 -0
- package/prompts/knowledge/tool-read.md +21 -0
- package/prompts/knowledge/tool-recent-changes.md +6 -0
- package/prompts/knowledge/tool-repo-outline.md +4 -0
- package/prompts/knowledge/tool-settings-read.md +12 -0
- package/prompts/knowledge/tool-settings.md +18 -0
- package/prompts/knowledge/tool-skill.md +6 -0
- package/prompts/knowledge/tool-ssh.md +52 -0
- package/prompts/knowledge/tool-subagent.md +59 -0
- package/prompts/knowledge/tool-task.md +12 -0
- package/prompts/knowledge/tool-team-ledger-read.md +11 -0
- package/prompts/knowledge/tool-team-ledger.md +11 -0
- package/prompts/knowledge/tool-timer.md +23 -0
- package/prompts/knowledge/tool-tree.md +14 -0
- package/prompts/knowledge/tool-verify.md +19 -0
- package/prompts/knowledge/tool-wait-for.md +25 -0
- package/prompts/knowledge/tool-websearch.md +19 -0
- package/prompts/knowledge/tool-write.md +9 -0
- package/prompts/knowledge/upstream-protocol.md +43 -0
- package/prompts/persona-eng-coder.md +21 -3
- package/prompts/persona-eng-designer.md +131 -169
- package/prompts/persona-engineering.md +142 -84
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-plan.md +5 -1
- package/prompts/subagent-base.md +2 -0
- package/provider/anthropic.mjs +6 -4
- package/provider/core.mjs +3 -2
- package/provider/errors.mjs +29 -4
- package/provider/google.mjs +24 -7
- package/provider/responses.mjs +3 -1
- package/provider-flows.mjs +2 -2
- package/session-index-build.mjs +1 -1
- package/session-index-pass.mjs +1 -1
- package/session-index-query.mjs +1 -1
- package/session-index.mjs +1 -1
- package/session-lifecycle.mjs +72 -17
- package/session-slot-write.mjs +37 -5
- package/session.mjs +24 -8
- package/skip-dirs.mjs +2 -2
- package/team-ledger.mjs +13 -9
- package/token-ttl.mjs +73 -4
- package/token-window.mjs +167 -33
- package/tool-docs/advisor.md +2 -27
- package/tool-docs/apply_patch.md +1 -15
- package/tool-docs/bash.md +2 -41
- package/tool-docs/batch-eng-coder.md +3 -0
- package/tool-docs/batch-eng-designer.md +3 -0
- package/tool-docs/batch-review.md +3 -0
- package/tool-docs/batch.md +2 -84
- package/tool-docs/browser.md +2 -49
- package/tool-docs/code_search.md +2 -2
- package/tool-docs/consult_start.md +2 -8
- package/tool-docs/consult_stop.md +2 -4
- package/tool-docs/context.md +1 -5
- package/tool-docs/delete.md +2 -17
- package/tool-docs/doc_check.md +2 -107
- package/tool-docs/doc_graph-read.md +3 -0
- package/tool-docs/doc_graph.md +3 -0
- package/tool-docs/doc_search.md +2 -4
- package/tool-docs/edit.md +1 -38
- package/tool-docs/eng.md +3 -1
- package/tool-docs/execute.md +2 -18
- package/tool-docs/fetch.md +2 -14
- package/tool-docs/file_ops.md +2 -18
- package/tool-docs/get_current_time.md +1 -6
- package/tool-docs/git-read.md +3 -0
- package/tool-docs/git.md +2 -35
- package/tool-docs/glob.md +2 -10
- package/tool-docs/goal.md +1 -6
- package/tool-docs/grep.md +2 -18
- package/tool-docs/hashline_edit.md +2 -15
- package/tool-docs/insert_after.md +2 -16
- package/tool-docs/instance_list.md +3 -0
- package/tool-docs/instance_send.md +3 -0
- package/tool-docs/knowledge.md +3 -0
- package/tool-docs/ledger-read.md +3 -0
- package/tool-docs/ledger.md +3 -8
- package/tool-docs/lint.md +2 -10
- package/tool-docs/ls.md +2 -11
- package/tool-docs/lsp.md +2 -9
- package/tool-docs/main_history.md +3 -1
- package/tool-docs/manifest-read.md +2 -8
- package/tool-docs/manifest.md +2 -35
- package/tool-docs/memory-read.md +3 -0
- package/tool-docs/memory.md +2 -20
- package/tool-docs/notify_parent.md +2 -13
- package/tool-docs/peer_instances.md +3 -1
- package/tool-docs/plan.md +1 -5
- package/tool-docs/process-read.md +3 -0
- package/tool-docs/process.md +2 -13
- package/tool-docs/question.md +3 -17
- package/tool-docs/read.md +2 -19
- package/tool-docs/read_history-batch.md +3 -0
- package/tool-docs/read_history.md +2 -18
- package/tool-docs/read_image.md +2 -9
- package/tool-docs/recent_changes.md +2 -2
- package/tool-docs/repo_outline.md +2 -2
- package/tool-docs/settings-read.md +3 -0
- package/tool-docs/settings.md +1 -12
- package/tool-docs/skill.md +2 -6
- package/tool-docs/ssh.md +1 -62
- package/tool-docs/subagent.md +2 -100
- package/tool-docs/task.md +1 -7
- package/tool-docs/team_ledger-read.md +3 -0
- package/tool-docs/team_ledger.md +3 -9
- package/tool-docs/timer.md +2 -19
- package/tool-docs/tree.md +2 -13
- package/tool-docs/verify.md +2 -12
- package/tool-docs/wait_for.md +2 -32
- package/tool-docs/websearch.md +2 -19
- package/tool-docs/write.md +2 -12
- package/tools/browser.mjs +52 -7
- package/tools/doc-write-gate.mjs +73 -0
- package/tools/edit-batch.mjs +170 -92
- package/tools/edit-diff.mjs +78 -62
- package/tools/edit-receipt.mjs +39 -0
- package/tools/execute.mjs +1 -1
- package/tools/file.mjs +16 -8
- package/tools/git.mjs +24 -9
- package/tools/index.mjs +6 -0
- package/tools/knowledge.mjs +143 -0
- package/tools/linter.mjs +3 -3
- package/tools/ops.mjs +3 -1
- package/tools/patch.mjs +123 -43
- package/tools/shared.mjs +28 -27
- package/tools/write-gate-params.mjs +31 -0
- package/tools/write-path.mjs +16 -4
- package/window-policy.mjs +203 -0
- package/doc-check/anchors.mjs +0 -235
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* taskbook-block.mjs — 工程角色的任务书正文块构造器(`AGENT-LOOP-SUBAGENT.md` §8.1 载体 ∥ 切片 ∥ 快照)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么另立一档(同 `audit-block.mjs` 的 D23-3 外提先例):块构造是纯函数 ⇒ 判据可直测,
|
|
5
|
+
* 而装配点 `subagent-spawn.mjs` 已接近设计时行数线,不因新增逻辑逼近它。
|
|
6
|
+
*
|
|
7
|
+
* 三件事都在本档定:
|
|
8
|
+
* - **切片**:按角色取段(§8.1)——eng-coder 取 §2,eng-designer 取 §1 + §2。切法 = 段头之间的文本,
|
|
9
|
+
* 段界判据消费批次档段解析的既有实现(`batch-segment-vocab.mjs` 的 `sectionHeaderRe` ∥ `sectionBodyLines`
|
|
10
|
+
* ——段头形态与「下一个 `## §N`」两处判据的唯一住所;`batch-skeleton.mjs` 只再导出其中 `sectionHeaderRe`,
|
|
11
|
+
* 故本档直接消费叶档);不解析标题文字,也不在本档另写一份段界正则。
|
|
12
|
+
* - **快照**:正文由装配点在 spawn 当刻读一次后传进来,此后批档改动不回流——本档零 fs,只做切与拼。
|
|
13
|
+
* - **失效即拒**:该角色的段切不出来(没有对应段头)⇒ 抛错并点名路径与缺失段,不退回「只发指向句」
|
|
14
|
+
* (退回会让 §8.1 的承诺落空而无人知道)。
|
|
15
|
+
*
|
|
16
|
+
* 不截断:截断后的副本仍自称任务书原文,比不给更坏(§8.1)。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { sectionHeaderRe, sectionBodyLines } from "./batch-segment-vocab.mjs"
|
|
20
|
+
|
|
21
|
+
/** 角色 → 进 system 固块的段号(§8.1)。eng-designer 取 §1 + §2:§1 是约束它的裁决、§2 是它自己的笔;
|
|
22
|
+
* §3–§6 不进固块,由该角色按需从磁盘读(改动随时可见)。非工程角色不在此表 ⇒ 不携任务书块。 */
|
|
23
|
+
export const TASK_BOOK_SEGMENTS = Object.freeze({
|
|
24
|
+
"eng-coder": Object.freeze([2]),
|
|
25
|
+
"eng-designer": Object.freeze([1, 2]),
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
/** 块首说明行(§8.1):让子代理知道手里这份是快照,改写/引述之前要回读磁盘。 */
|
|
29
|
+
const SNAPSHOT_NOTE =
|
|
30
|
+
"[Task book — the text below is the batch record verbatim as it stood at spawn time; later edits to the record do not flow into this copy. " +
|
|
31
|
+
"Re-read the record on disk before rewriting or quoting any segment — the batch tool's `edit` anchors only on the current on-disk text.]"
|
|
32
|
+
|
|
33
|
+
/** 段体首尾空行不计(段头之间的空行属版式,不属于该段内容)。 */
|
|
34
|
+
function withoutBlankEdges(lines) {
|
|
35
|
+
let start = 0
|
|
36
|
+
let end = lines.length
|
|
37
|
+
while (start < end && lines[start].trim() === "") start++
|
|
38
|
+
while (end > start && lines[end - 1].trim() === "") end--
|
|
39
|
+
return lines.slice(start, end)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 任务书正文块(§8.1 / §8.2 收集序首块):纯函数——零 fs、零副作用。
|
|
44
|
+
* @param {{ role: string, record: { path: string, text: string } }} input
|
|
45
|
+
* `role` = 本次 spawn 的角色;`record.path` = 批档绝对路径(拒文点名用);
|
|
46
|
+
* `record.text` = **spawn 当刻**读到的批档全文(快照本体)。
|
|
47
|
+
* @returns {string} 块文本(段之间 `\n\n`;与其它块之间的分隔由装配侧 `join("\n\n")` 施加)
|
|
48
|
+
*/
|
|
49
|
+
export function buildTaskBookBlock({ role, record }) {
|
|
50
|
+
const segs = TASK_BOOK_SEGMENTS[role]
|
|
51
|
+
if (!segs) {
|
|
52
|
+
throw new Error(`buildTaskBookBlock: role '${role}' takes no task-book block — only the engineering roles (${Object.keys(TASK_BOOK_SEGMENTS).join(" / ")}) carry one; every other role gets its task book from the structured parameters`)
|
|
53
|
+
}
|
|
54
|
+
const path = record?.path
|
|
55
|
+
const text = record?.text
|
|
56
|
+
if (typeof path !== "string" || path.trim() === "") {
|
|
57
|
+
throw new Error("buildTaskBookBlock: record.path is required (the batch record's absolute path) — the refusal text must name the record it could not cut a segment out of")
|
|
58
|
+
}
|
|
59
|
+
if (typeof text !== "string") {
|
|
60
|
+
throw new Error(`buildTaskBookBlock: record.text is required for ${path} (the batch record's full text as read at spawn time)`)
|
|
61
|
+
}
|
|
62
|
+
const parts = [SNAPSHOT_NOTE]
|
|
63
|
+
for (const seg of segs) {
|
|
64
|
+
const hdr = sectionHeaderRe(seg).exec(text)
|
|
65
|
+
if (!hdr) {
|
|
66
|
+
throw new Error(`Task book unavailable — spawn refused: the batch record at ${path} has no "## §${seg}" section header, so the ${role} task book (§${segs.join(" + §")}) cannot be cut from it. Restore that segment header (create is the batch record skeleton's only authoritative entry), or point batchDoc at the record that carries it.`)
|
|
67
|
+
}
|
|
68
|
+
const nl = text.indexOf("\n", hdr.index)
|
|
69
|
+
const headerLine = (nl < 0 ? text.slice(hdr.index) : text.slice(hdr.index, nl)).replace(/\r$/, "")
|
|
70
|
+
const body = withoutBlankEdges(sectionBodyLines(text, seg) ?? [])
|
|
71
|
+
parts.push([headerLine, ...body].join("\n"))
|
|
72
|
+
}
|
|
73
|
+
return parts.join("\n\n")
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 首条 user 消息的任务书指向句(§3.1「首条 user 消息只留指向句:批档路径 + 其余段自读」)。
|
|
78
|
+
*
|
|
79
|
+
* 两句都不带「only」/「唯一」措辞:「唯一任务通道」只对 eng-coder 的那一段成立,eng-designer 的通道是
|
|
80
|
+
* 整份批档(§1 的裁决对它具约束力),对它声称唯一通道即与 §3.1 互斥。
|
|
81
|
+
* @param {string} role — 本次 spawn 的角色(只有 TASK_BOOK_SEGMENTS 里的角色有指向句)
|
|
82
|
+
* @param {string} recordPath — 批档绝对路径(装配点已解析)
|
|
83
|
+
* @returns {string} 一行机械任务书行
|
|
84
|
+
*/
|
|
85
|
+
export function taskBookPointerLine(role, recordPath) {
|
|
86
|
+
const segs = TASK_BOOK_SEGMENTS[role]
|
|
87
|
+
if (!segs) {
|
|
88
|
+
throw new Error(`taskBookPointerLine: role '${role}' has no task-book pointer line — only the engineering roles (${Object.keys(TASK_BOOK_SEGMENTS).join(" / ")}) carry one`)
|
|
89
|
+
}
|
|
90
|
+
if (role === "eng-coder") {
|
|
91
|
+
return `Task book: §2 of the batch record at ${recordPath} — reproduced verbatim in your system prompt as it stood at spawn time. Read the record itself for any other segment; §5 of that record is where you record the implementation.`
|
|
92
|
+
}
|
|
93
|
+
return `Task book: the batch record at ${recordPath} — §1 (the rulings that bind you) and §2 (your own pen) are reproduced verbatim in your system prompt as they stood at spawn time. Read the record itself for §3–§6, and re-read the current §2 text before you edit it.`
|
|
94
|
+
}
|
package/agent-tools/timer.mjs
CHANGED
|
@@ -93,7 +93,7 @@ export const timerTool = {
|
|
|
93
93
|
properties: {
|
|
94
94
|
seconds: {
|
|
95
95
|
type: "number",
|
|
96
|
-
description: "Thinking budget in seconds (
|
|
96
|
+
description: "Thinking budget in seconds — required for a one-shot timer (pass at / every / daily to choose another form instead). Longer for complex reasoning, shorter for simple tasks.",
|
|
97
97
|
},
|
|
98
98
|
at: {
|
|
99
99
|
type: "string",
|
|
@@ -135,7 +135,7 @@ export const timerTool = {
|
|
|
135
135
|
const hasDaily = args.daily !== undefined && args.daily !== null
|
|
136
136
|
const hasCancel = args.cancel !== undefined && args.cancel !== null
|
|
137
137
|
const wantsList = args.list === true
|
|
138
|
-
// `list` 键在场须恰为 `true`——否则显式拒(防 `{list:false}`
|
|
138
|
+
// `list` 键在场须恰为 `true`——否则显式拒(防 `{list:false}` 静默落一次性定时器:无义键触发真实副作用)。
|
|
139
139
|
if (args.list !== undefined && args.list !== null && args.list !== true) {
|
|
140
140
|
throw new Error(
|
|
141
141
|
`timer: list accepts only true (got: ${String(args.list)}) — omit list to set a timer; pass { list: true } to list pending timers`,
|
|
@@ -166,7 +166,7 @@ export const timerTool = {
|
|
|
166
166
|
throw new Error(`timer at must be a local clock time "YYYY-MM-DDTHH:MM[:SS]" (e.g. "2026-10-13T09:00"), got: ${String(raw)}`)
|
|
167
167
|
}
|
|
168
168
|
expiresAt = ts // 过时点 ⇒ 所给刻(delay ≤ 0 ⇒ 即时投递——AC-45① 口径;不重排)
|
|
169
|
-
message =
|
|
169
|
+
message = `Time's up (at ${localText(ts)})${DEFAULT_TAIL}`
|
|
170
170
|
} else if (hasEvery) {
|
|
171
171
|
form = "every"
|
|
172
172
|
everySec = Number(args.every)
|
|
@@ -175,22 +175,26 @@ export const timerTool = {
|
|
|
175
175
|
}
|
|
176
176
|
everyMs = everySec * 1000
|
|
177
177
|
expiresAt = nextFireAt({ everyMs, expiresAt: now }, now) // 首投 = 设时 + N(非立即——防「设置即投」双投感)
|
|
178
|
-
message =
|
|
178
|
+
message = `Time's up (every ${everySec} seconds)${DEFAULT_TAIL}`
|
|
179
179
|
} else if (hasDaily) {
|
|
180
180
|
form = "daily"
|
|
181
181
|
if (typeof args.daily !== "string" || !DAILY_RE.test(args.daily)) {
|
|
182
182
|
throw new Error(`timer daily must be a local "HH:MM" time (24-hour, e.g. "09:00"), got: ${String(args.daily)}`)
|
|
183
183
|
}
|
|
184
184
|
expiresAt = nextFireAt({ daily: args.daily }, now) // 今日该刻未过 ⇒ 今日;已过 ⇒ 明日(非即时)
|
|
185
|
-
message =
|
|
185
|
+
message = `Time's up (daily at ${args.daily})${DEFAULT_TAIL}`
|
|
186
186
|
} else {
|
|
187
|
-
// D15.3#1
|
|
188
|
-
|
|
187
|
+
// D15.3#1:`seconds` 必填——默认 180 那条兜底已撤(缺了就拒,不替调用方选预算);
|
|
188
|
+
// 非法值(非数字/非正数)显式报错——静默 NaN 定时器永不触发的坑
|
|
189
|
+
if (!hasSeconds) {
|
|
190
|
+
throw new Error("timer: seconds is required for a one-shot timer (or pass at / every / daily) — got none")
|
|
191
|
+
}
|
|
192
|
+
const seconds = Number(args.seconds)
|
|
189
193
|
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
190
194
|
throw new Error(`timer seconds must be a positive number, got: ${args.seconds}`)
|
|
191
195
|
}
|
|
192
196
|
expiresAt = now + seconds * 1000
|
|
193
|
-
message =
|
|
197
|
+
message = `Time's up (${seconds}s)${DEFAULT_TAIL}`
|
|
194
198
|
oneShotSec = seconds
|
|
195
199
|
}
|
|
196
200
|
|
package/agent-tools/verify.mjs
CHANGED
|
@@ -82,7 +82,7 @@ export const verifyTool = {
|
|
|
82
82
|
properties: {
|
|
83
83
|
verification: {
|
|
84
84
|
type: "object",
|
|
85
|
-
description: "Your declaration of whether you already ran the project's verification and its outcome — self-reported evidence (verify does not execute the command).",
|
|
85
|
+
description: "Your declaration of whether you already ran the project's verification and its outcome — self-reported evidence (verify does not execute the command). Required when code files changed: omitting it is refused there (the doc-only fast path and the no-code path need no declaration).",
|
|
86
86
|
properties: {
|
|
87
87
|
status: { type: "string", enum: ["passed", "failed", "skipped"], description: "The verification outcome you declare: 'passed' → allowed; 'failed' → blocked; 'skipped' → allowed but requires a summary reason." },
|
|
88
88
|
command: { type: "string", description: "Optional: the verification command you ran (self-reported)." },
|
|
@@ -173,9 +173,10 @@ export const verifyTool = {
|
|
|
173
173
|
// 1b. Doc-only fast path: every changed file is documentation (docs/, *.md,
|
|
174
174
|
// LICENSE…) — syntax checks and a verification declaration are meaningless
|
|
175
175
|
// for doc changes, and the task list/self-review checklist add nothing either.
|
|
176
|
-
// Paths inside a declared code segment
|
|
177
|
-
//
|
|
178
|
-
//
|
|
176
|
+
// Paths inside a declared code segment are product code — excluded from the fast
|
|
177
|
+
// path, consistent with the design gate. There is no default segment: the layout is
|
|
178
|
+
// what the project declares (`codePaths` in its manifest), so a project that never
|
|
179
|
+
// declares one has no code segment at all (a `.md` under `src/` then reads as a doc).
|
|
179
180
|
// Empty list (no changes / git unavailable)
|
|
180
181
|
// intentionally falls through to the normal path below.
|
|
181
182
|
const conv = loadProjectDeclaration(cwd)
|
|
@@ -192,6 +193,14 @@ export const verifyTool = {
|
|
|
192
193
|
// is not a code change — no declaration is demanded for it).
|
|
193
194
|
const codeFiles = changedFiles.filter((f) => isCodePath(f, conv))
|
|
194
195
|
|
|
196
|
+
// 有码面必填(KD-6):缺参是**入参面**语义,不是 BLOCKED 报面——抛前先置 `_verifyPassed = false`
|
|
197
|
+
// (fail-closed:不改状态就抛,`thincoder-core/agent/completion.mjs` 读到的仍是上一轮的 `true`,
|
|
198
|
+
// 本次交付门被悄悄放行)。无码面(`codeFiles.length === 0`)不要求——既有语义零变。
|
|
199
|
+
if (codeFiles.length > 0 && (args.verification === undefined || args.verification === null)) {
|
|
200
|
+
ctx.agent._verifyPassed = false
|
|
201
|
+
throw new Error("verify: verification is required when code files changed — declare {status: 'passed'|'failed'|'skipped'}")
|
|
202
|
+
}
|
|
203
|
+
|
|
195
204
|
// 2. Advisory syntax hint (D-V5) — node --check on changed .js/.mjs when node
|
|
196
205
|
// exists. SOFT hint only — it does NOT gate done (no language-specific
|
|
197
206
|
// enforcement; a non-JS project or a missing node simply skips silently).
|
package/agent-tools.mjs
CHANGED
|
@@ -19,9 +19,10 @@ export { readHistoryTool } from "./agent-tools/read-history.mjs"
|
|
|
19
19
|
// ——depth-0 段挂载(子代理面裁见 §6.16.6 `family-tools.mjs` `depthOnly`)。
|
|
20
20
|
export { contextTool } from "./agent-tools/context.mjs"
|
|
21
21
|
export { batchTool } from "./agent-tools/batch.mjs"
|
|
22
|
-
// 批次档生命周期工具(BATCH-RECORD §4.3 挂载表——主名 `batch`
|
|
23
|
-
//
|
|
24
|
-
//
|
|
22
|
+
// 批次档生命周期工具(BATCH-RECORD §4.3 挂载表——主名 `batch` 单工具**六 action**(create / attach / append /
|
|
23
|
+
// edit / status / close):depth-0 主 agent 全量六动作(create/attach/close + append/edit/status 域随模式——
|
|
24
|
+
// 工程面 = append §1/§4/§6 ∥ status §1;普通面 = append §1/§2/§4/§5/§6 ∥ status §1/§2/§5)(轮 2 裁定②:§4/§6
|
|
25
|
+
// 状态面走普通文档写)(D-BR18);eng 子代理 / 评审实例按身份 profile 只挂 append/edit/status(TOOLS.md §6.29 ②)。
|
|
25
26
|
// CORE-UNIFICATION TOOLS #83(统一登记册——VSC `agent-tools/index.mjs` 含 consult 家族;
|
|
26
27
|
// CLI 原把 consult 另挂 `agent/setup.mjs` 的家族段装配 ⇒ 归位:登记册即单一来源,装配方只读本档)。
|
|
27
28
|
export { consultStartTool, consultStopTool } from "./agent-tools/consult.mjs"
|
|
@@ -29,3 +30,6 @@ export { consultStartTool, consultStopTool } from "./agent-tools/consult.mjs"
|
|
|
29
30
|
// (depth>0 段装配——`agent/family-tools.mjs`;depth-0 / consult 不装配)。
|
|
30
31
|
export { parentChannelTool } from "./agent-tools/parent-channel.mjs"
|
|
31
32
|
export { docCheckTool } from "./agent-tools/doc-check.mjs" // 文档纪律机检(DOC-DISCIPLINE.md §3.20 条目 S——产品内建 · 报告态 · 非门禁)
|
|
33
|
+
// 文档锚点图(DOC-GRAPH.md §2.5——扫描 ∥ 正向 ∥ 反向 ∥ 链路;边表与台账同库)。两变体互斥装配:全量四动作挂
|
|
34
|
+
// depth-0 ∥ 只读三动作(无 `scan`)挂全部 depth>0 角色段与 advisor 面(AGENT-LOOP-SUBAGENT.md §6.60.2)。
|
|
35
|
+
export { docGraphTool, docGraphReadTool } from "./agent-tools/doc-graph.mjs"
|
package/agent.mjs
CHANGED
|
@@ -11,6 +11,9 @@
|
|
|
11
11
|
import { beginRun } from "./agent/run-start.mjs"
|
|
12
12
|
import { runTurnLoop } from "./agent/turn-loop.mjs"
|
|
13
13
|
import { finalizeAgentTurn } from "./agent/run-stages.mjs"
|
|
14
|
+
// 跨轮机读投影(CONTEXT-COMPACTION §1.1 ∥ SESSION §2 · 台账 #2395):完成轮登记点住本档——
|
|
15
|
+
// 只有 `finalizeAgentTurn` 成功返回之后才登记,ContinueError / AbortError / 其它异常不登记。
|
|
16
|
+
import { registerCompletedTurn, noteTurnRunError } from "./agent/turn-projection.mjs"
|
|
14
17
|
import {
|
|
15
18
|
escapeXml, listWorkDir,
|
|
16
19
|
readonlyToolNames, collectGitContext, loadProjectInstructions,
|
|
@@ -76,9 +79,15 @@ export function createAgent({
|
|
|
76
79
|
_tok: null, _tokRatio: 1, // §6.17 估算自校准池化比({key,num,den};采样 = turn-loop,清空 = /new)
|
|
77
80
|
_compressFailures: 0,
|
|
78
81
|
_emptyRetries: 0, // empty-response retry budget (per-run; reset on a fresh user turn)
|
|
82
|
+
// §6.6 `wrote` 判据与注入帽的载体(AGENT-LOOP.md §6.6 · §6.2 resume 保留集):
|
|
83
|
+
// `_batchWrites` = `batch` 工具成功写盘的累计数(`onWritten` 各汇聚点自增);`_designTurnNotices` = 本链已注入的设计轮提醒条数。
|
|
84
|
+
_batchWrites: 0, _designTurnNotices: 0,
|
|
79
85
|
_runStartHistoryLen: 0, // machine-line length at the start of the current run — end-of-run exploration distillation slices from here
|
|
80
86
|
_pendingDistill: null, // in-flight end-of-run exploration distillation (SEND-STALL-DISTILL §2.1) — awaited at next run start / TUI exit flush
|
|
81
87
|
_currentTurn: 0, _maxTurns: DEFAULT_MAX_TURNS, // turn counter for status bar display
|
|
88
|
+
// 跨轮机读投影(CONTEXT-COMPACTION §1.1 ∥ SESSION §2 · 台账 #2395):轮记录 ∥ 活动轮账本 ∥
|
|
89
|
+
// 待折叠的完成轮。三件只在轮边界改写(`agent/turn-projection.mjs`),新 agent 从空账起。
|
|
90
|
+
_turns: [], _turnLedger: null, _turnPending: null, _turnStartLen: null, _turnResponseEnd: null,
|
|
82
91
|
}
|
|
83
92
|
}
|
|
84
93
|
|
|
@@ -89,18 +98,28 @@ export async function runAgent(agent, input, callbacks = {}, { depth = 0, signal
|
|
|
89
98
|
})
|
|
90
99
|
|
|
91
100
|
let thrownError = null
|
|
101
|
+
let finalResponse = null
|
|
92
102
|
try {
|
|
93
|
-
|
|
103
|
+
finalResponse = await runTurnLoop(agent, {
|
|
94
104
|
maxTurns, threshold, toolSchemas, toolByName, systemPrompt,
|
|
95
105
|
depth, signal, autoTurn, suspDriven, streamOutput, consumeInjected, consumeQueuedInput, callbacks, distillSignal,
|
|
96
106
|
})
|
|
107
|
+
// 本轮原始机读段的终点(折叠边界):此后回合收尾注入的异步结果不属于本轮的模型过程,
|
|
108
|
+
// 折叠时保留(下一个模型请求仍看得见它们)。
|
|
109
|
+
agent._turnResponseEnd = agent.history.length
|
|
110
|
+
return finalResponse
|
|
97
111
|
} catch (e) {
|
|
98
112
|
thrownError = e
|
|
113
|
+
// 异常面只记账不登记(异常轮不折叠):原因留给同一账本(续跑沿用)。
|
|
114
|
+
noteTurnRunError(agent._turnLedger, e)
|
|
99
115
|
throw e
|
|
100
116
|
} finally {
|
|
101
117
|
// 2026-09-05 实践轮:回合收尾(consult 清理/async 池分流/guard 继承——原 425-462
|
|
102
118
|
// 段 + collectSettledAsync 466-494 整体迁 agent/run-stages.mjs finalizeAgentTurn——
|
|
103
119
|
// CLI 对位 VS run-stages——finally 只剩一行调用 + 骨架注释)。
|
|
104
120
|
await finalizeAgentTurn(agent, { signal, autoTurn, upstreamTurn, timerTurn, suspDriven, thrownError, depth })
|
|
121
|
+
// 正常返回 ∧ 收尾成功 ⇒ 登记完成轮(设计 §2:ContinueError / AbortError / 其它异常不登记,
|
|
122
|
+
// 续跑沿用同一账本)。登记只置事实与折叠计划——机读线在下一轮起点(`beginRun`)才折叠。
|
|
123
|
+
if (!thrownError) registerCompletedTurn(agent, { finalResponse })
|
|
105
124
|
}
|
|
106
125
|
}
|
package/attachments.mjs
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* attachments.mjs — 回合附件(粘贴图)族:dataURL 解析 ∕ 临时落盘管线 ∕ 非多模态降级
|
|
3
3
|
* (上提核件 —— 处理流批 R5 · 2026-09-28)。
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* `savePastedImages`
|
|
5
|
+
* 上提源(迁移前源档)= VSC `thincoder-vscode/src/extension/image-handler.mjs`(`parseDataUrl` ·
|
|
6
|
+
* `savePastedImages` · `downgradeNonVisionImages`);预算语义(合计 30MB ∕ 轮 · 溢出项弃后
|
|
7
7
|
* **继续扫**「其余照发」)与配额单位 = 桌面同档 `thincoder-desktop/src/main/attachments.mjs`
|
|
8
8
|
* (15MB ∕ 条 —— 与核 `read_image` 内闸同值同单位:`tools/file.mjs` `MAX_IMAGE_BYTES = 15_000_000`,
|
|
9
9
|
* 接纳面不得宽于该闸)。本档 = 单源(消费面 = 桌面 `src/main/attachments.mjs`;VSC 自持副本已随本批(parity-b4)迁移改指本档)。
|
|
@@ -112,7 +112,7 @@ export function savePastedImages(dataUrls, cwd, { fs } = {}) {
|
|
|
112
112
|
*/
|
|
113
113
|
export async function downgradeNonVisionImages({ text, images, model, visionReader, signal } = {}) {
|
|
114
114
|
const keep = { text, images, downgraded: false }
|
|
115
|
-
if (!Array.isArray(images) || images.length === 0) return keep // 无图 ⇒ no-op(VSC
|
|
115
|
+
if (!Array.isArray(images) || images.length === 0) return keep // 无图 ⇒ no-op(VSC 侧 `downgradeNonVisionImages` 同判)
|
|
116
116
|
if (!model || !isNonVisionModel(model)) return keep // 多模态主模型 ∕ 模型缺省 ⇒ 不降级
|
|
117
117
|
if (typeof visionReader !== "function") {
|
|
118
118
|
throw new TypeError("downgradeNonVisionImages: visionReader seam missing — inject the one-shot vision-subagent reader")
|
package/browser/actions.mjs
CHANGED
|
@@ -143,11 +143,17 @@ async function actScreenshot(args, ctx, h) {
|
|
|
143
143
|
return `[screenshot] ${saved.path} (${saved.bytes} bytes)`
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
-
/** close(§2.2):幂等——无会话 ⇒ `[close] no browser session`(成功态)。
|
|
146
|
+
/** close(§2.2 ∥ §12):幂等——无会话 ⇒ `[close] no browser session`(成功态)。
|
|
147
|
+
* 有会话 ⇒ 摘自己;仍有用者则浏览器留着、回执明说还有几家在用;最后一个关 ⇒ 末关(浏览器关 + 删锁)。
|
|
148
|
+
* 两形回执不可互换:前者浏览器还在跑,后者它已经不在了(模型据此判断「还能不能接着用」)。
|
|
149
|
+
* 末关但浏览器没关成(中止 ∥ 关不下去)⇒ **不得报「已关」**:回执明说它还在跑、下一位持有者收它(§12 代价 4)。 */
|
|
147
150
|
async function actClose(args, ctx, h) {
|
|
148
151
|
if (!h.connection()) return "[close] no browser session"
|
|
149
|
-
await h.closeSession()
|
|
150
|
-
return "[close] browser
|
|
152
|
+
const outcome = await h.closeSession()
|
|
153
|
+
if (outcome.lastUser && outcome.browserClosed) return "[close] shared browser closed (last user)"
|
|
154
|
+
if (outcome.lastUser) return "[close] released the shared browser (last user) — the browser is still running; the next instance reclaims it"
|
|
155
|
+
const others = Number(outcome.others) || 0
|
|
156
|
+
return `[close] released the shared browser (${others} other instance(s) still using it — the browser is left running)`
|
|
151
157
|
}
|
|
152
158
|
|
|
153
159
|
/** 基线八动作分发表(会话档并入总表——§5)。 */
|
package/browser/cdp.mjs
CHANGED
|
@@ -7,7 +7,11 @@
|
|
|
7
7
|
*
|
|
8
8
|
* 错误语义:CDP 回 `{ error: { message } }` ⇒ 拒以 `Error(message)`(BROWSER-TOOL.md §5)。
|
|
9
9
|
* 帽(§2.9 三层帽——层二 / 层三):`call` 缺省帽 15s(任何未显式配帽的调用也不悬挂);`connectCdp` open 帽
|
|
10
|
-
* 10s;`/json/new` fetch 帽 5s——动作内调用另随动作控制器(session 侧接线,预算先行)。
|
|
10
|
+
* 10s;`/json/new` ∥ `/json/close` fetch 帽 5s;`/json/version` 探针帽 2s——动作内调用另随动作控制器(session 侧接线,预算先行)。
|
|
11
|
+
*
|
|
12
|
+
* HTTP 面三只(共享池的接入面读数——`docs/core/design/BROWSER-TOOL.md` §12):`newTab`(回执携标签页
|
|
13
|
+
* `id`——本实例的标签页标识)∥ `closeTab`(`/json/close/<id>`)∥ `probeVersion`(端口答不答,2 s 帽——
|
|
14
|
+
* 布尔、零抛:判不了就答不通,由调用方按「端口答不通」那一路走)。
|
|
11
15
|
* 断连面:WS `onclose` / `onerror` ⇒ 拒在飞命令**并通知订阅者**(session 据此复位会话态——§2.10 源②)。
|
|
12
16
|
*/
|
|
13
17
|
|
|
@@ -15,8 +19,12 @@
|
|
|
15
19
|
export const DEFAULT_CALL_TIMEOUT_MS = 15_000
|
|
16
20
|
/** `connectCdp` open 帽(§2.9 层二)。 */
|
|
17
21
|
export const CONNECT_TIMEOUT_MS = 10_000
|
|
18
|
-
/** `/json/new` fetch 帽(§2.9 层二)。 */
|
|
22
|
+
/** `/json/new` ∥ `/json/close` fetch 帽(§2.9 层二)。 */
|
|
19
23
|
export const NEWTAB_TIMEOUT_MS = 5_000
|
|
24
|
+
/** `/json/version` 探针帽(§12「接入」判据——端口答不答的 2 s 帽)。 */
|
|
25
|
+
export const VERSION_TIMEOUT_MS = 2_000
|
|
26
|
+
/** `/json/close/<id>` fetch 帽(§12「摘自己」——失败不阻断)。 */
|
|
27
|
+
export const CLOSETAB_TIMEOUT_MS = 5_000
|
|
20
28
|
|
|
21
29
|
/** 与浏览器标签页的一条 CDP 连接。 */
|
|
22
30
|
export class CdpClient {
|
|
@@ -135,27 +143,47 @@ export async function connectCdp(wsUrl, { WebSocketImpl, openTimeoutMs = CONNECT
|
|
|
135
143
|
return new CdpClient(ws)
|
|
136
144
|
}
|
|
137
145
|
|
|
138
|
-
/**
|
|
139
|
-
|
|
140
|
-
const url = `http://${host}:${port}/json/new?about:blank`
|
|
146
|
+
/** HTTP 请求 + 硬帽:到点即拒(不悬挂),成功 ⇒ 解析后的 JSON。 */
|
|
147
|
+
async function httpJson(url, init, { fetchImpl, timeoutMs } = {}) {
|
|
141
148
|
let timer = null
|
|
142
149
|
const deadline = new Promise((_, reject) => {
|
|
143
|
-
timer = setTimeout(
|
|
144
|
-
() => reject(new Error(`browser did not answer /json/new within ${timeoutMs}ms (port ${port})`)),
|
|
145
|
-
timeoutMs,
|
|
146
|
-
)
|
|
150
|
+
timer = setTimeout(() => reject(new Error(`browser did not answer ${new URL(url).pathname} within ${timeoutMs}ms (port ${new URL(url).port})`)), timeoutMs)
|
|
147
151
|
timer.unref?.()
|
|
148
152
|
})
|
|
149
|
-
const fetchTab = async (init) => (await fetchImpl(url, init)).json()
|
|
150
153
|
try {
|
|
151
|
-
|
|
152
|
-
try { tab = await Promise.race([fetchTab({ method: "PUT" }), deadline]) }
|
|
153
|
-
catch { tab = await Promise.race([fetchTab(), deadline]) } // GET 兜底(同帽——到点即拒,不悬挂)
|
|
154
|
-
if (!tab?.webSocketDebuggerUrl) {
|
|
155
|
-
throw new Error(`browser did not return a debuggable tab from /json/new (port ${port})`)
|
|
156
|
-
}
|
|
157
|
-
return tab.webSocketDebuggerUrl
|
|
154
|
+
return await Promise.race([(await fetchImpl(url, init)).json(), deadline])
|
|
158
155
|
} finally {
|
|
159
156
|
if (timer) clearTimeout(timer)
|
|
160
157
|
}
|
|
161
158
|
}
|
|
159
|
+
|
|
160
|
+
/** 开一张标签页并取它的调试地址与**标签页 id**(`PUT /json/new`,GET 兜底——walkthrough 同式;fetch 帽 5s)。
|
|
161
|
+
* `id` = 本实例的标签页标识(`/json/close/<id>` 摘自己用),共享池按它逐实例开自己的标签页(§12)。 */
|
|
162
|
+
export async function newTab(port, { host = "127.0.0.1", fetchImpl = globalThis.fetch, timeoutMs = NEWTAB_TIMEOUT_MS } = {}) {
|
|
163
|
+
const url = `http://${host}:${port}/json/new?about:blank`
|
|
164
|
+
const opts = { fetchImpl, timeoutMs }
|
|
165
|
+
let tab
|
|
166
|
+
try { tab = await httpJson(url, { method: "PUT" }, opts) }
|
|
167
|
+
catch { tab = await httpJson(url, undefined, opts) } // GET 兜底(同帽——到点即拒,不悬挂)
|
|
168
|
+
if (!tab?.webSocketDebuggerUrl) {
|
|
169
|
+
throw new Error(`browser did not return a debuggable tab from /json/new (port ${port})`)
|
|
170
|
+
}
|
|
171
|
+
return { id: tab.id ?? null, wsUrl: tab.webSocketDebuggerUrl }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 关掉指定标签页(`/json/close/<id>`;帽 5s)。摘自己时调用——失败不阻断,故布尔、零抛。 */
|
|
175
|
+
export async function closeTab(port, id, { host = "127.0.0.1", fetchImpl = globalThis.fetch, timeoutMs = CLOSETAB_TIMEOUT_MS } = {}) {
|
|
176
|
+
if (!id) return false
|
|
177
|
+
try {
|
|
178
|
+
await httpJson(`http://${host}:${port}/json/close/${encodeURIComponent(id)}`, undefined, { fetchImpl, timeoutMs })
|
|
179
|
+
return true
|
|
180
|
+
} catch { return false }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 端口答不答(`/json/version`,帽 2s——§12「接入」判据):答通 ⇒ true;不应答 ∥ 解析失败 ⇒ false。零抛。 */
|
|
184
|
+
export async function probeVersion(port, { host = "127.0.0.1", fetchImpl = globalThis.fetch, timeoutMs = VERSION_TIMEOUT_MS } = {}) {
|
|
185
|
+
try {
|
|
186
|
+
const body = await httpJson(`http://${host}:${port}/json/version`, undefined, { fetchImpl, timeoutMs })
|
|
187
|
+
return Boolean(body) && typeof body === "object"
|
|
188
|
+
} catch { return false }
|
|
189
|
+
}
|
package/browser/launch.mjs
CHANGED
|
@@ -4,14 +4,16 @@
|
|
|
4
4
|
* 候选表与启动参数沿 `scripts/console-walkthrough.mjs`(Edge 先于 Chrome)∥ 同档启动参数段
|
|
5
5
|
* (`--headless=new` ∥ `--remote-debugging-port=0` ∥ `stdio:"ignore"` ∥ POSIX `detached`)——
|
|
6
6
|
* 本档不 import 该脚本,只内化其形。
|
|
7
|
-
* profile = `~/.thincoder/browser/profile`(`configDir` 同源——`config-io.mjs`)=
|
|
8
|
-
* (F-BT6
|
|
7
|
+
* profile = `~/.thincoder/browser/profile`(`configDir` 同源——`config-io.mjs`)= **持久且全机唯一一份**
|
|
8
|
+
* (F-BT6)。profile 的**归属与生命周期全在 `pool.mjs`**(共享池、四形判定、首开末关——BROWSER-TOOL.md §12):
|
|
9
|
+
* 本档只给路径 ∥ 启动 ∥ 回收 ∥ 杀树,不持持有者位的领取与释放(旧 `acquireProfileLock` ∥
|
|
10
|
+
* `releaseProfileLock` 两导出已退场——互斥拒文与共享池方向相反)。
|
|
9
11
|
*
|
|
10
|
-
* 注入缝(N-BT6):`resolveBrowser({platform, env, pathExists, which})`
|
|
11
|
-
*
|
|
12
|
+
* 注入缝(N-BT6):`resolveBrowser({platform, env, pathExists, which})` ∥ `reclaimProfileOrphans(profile, io)`
|
|
13
|
+
* ∥ `launchBrowser({exe, profile, timeoutMs, sleep})`——缺省回落真实现,单元测试零真实文件系统。
|
|
12
14
|
*/
|
|
13
15
|
import { execFileSync, spawn } from "node:child_process"
|
|
14
|
-
import { existsSync, mkdirSync, readFileSync, rmSync
|
|
16
|
+
import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"
|
|
15
17
|
import { dirname, join } from "node:path"
|
|
16
18
|
import { configDir } from "../config-io.mjs"
|
|
17
19
|
|
|
@@ -72,44 +74,23 @@ export function resolveBrowser({ platform = process.platform, env = process.env,
|
|
|
72
74
|
throw new Error(BROWSER_NOT_FOUND)
|
|
73
75
|
}
|
|
74
76
|
|
|
75
|
-
/**
|
|
77
|
+
/** 本工具的持久化面(共享池目录:profile ∥ 持有者登记 ∥ 用者登记 ∥ 截图)。
|
|
78
|
+
* 布局不变量:`session.lock` 与 `profile` **同父目录**(孤儿回收从 `dirname(profile)` 取锁);`users/` 同层。 */
|
|
76
79
|
export function browserPaths(base = configDir) {
|
|
77
80
|
const root = join(base, "browser")
|
|
78
|
-
return { root, profile: join(root, "profile"), lock: join(root, "session.lock"), shots: join(root, "shots") }
|
|
81
|
+
return { root, profile: join(root, "profile"), lock: join(root, "session.lock"), users: join(root, "users"), shots: join(root, "shots") }
|
|
79
82
|
}
|
|
80
83
|
|
|
81
84
|
function defaultPidAlive(pid) {
|
|
82
85
|
try { process.kill(pid, 0); return true }
|
|
83
|
-
catch (e) { return e?.code
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* profile 锁(单会话/进程——KD-5):他进程持有 ⇒ 抛 `browser profile in use by another
|
|
88
|
-
* ThinCoder instance (pid <N>)`;陈旧锁(pid 死)⇒ 接管。
|
|
89
|
-
* `io` = 注入缝(readText ∥ writeText ∥ isAlive ∥ pid)——缺省真文件系统。
|
|
90
|
-
*/
|
|
91
|
-
export function acquireProfileLock(lockPath, io = {}) {
|
|
92
|
-
const readText = io.readText ?? ((p) => { try { return readFileSync(p, "utf8") } catch { return "" } })
|
|
93
|
-
const writeText = io.writeText ?? ((p, text) => { mkdirSync(dirname(p), { recursive: true }); writeFileSync(p, text, "utf8") })
|
|
94
|
-
const isAlive = io.isAlive ?? defaultPidAlive
|
|
95
|
-
const pid = io.pid ?? process.pid
|
|
96
|
-
const held = Number(String(readText(lockPath) ?? "").trim())
|
|
97
|
-
if (Number.isInteger(held) && held > 0 && held !== pid && isAlive(held)) {
|
|
98
|
-
throw new Error(`browser profile in use by another ThinCoder instance (pid ${held})`)
|
|
99
|
-
}
|
|
100
|
-
writeText(lockPath, String(pid))
|
|
101
|
-
return { pid }
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
export function releaseProfileLock(lockPath, io = {}) {
|
|
105
|
-
const removeText = io.removeText ?? ((p) => { try { rmSync(p, { force: true }) } catch { /* 已被接管/清除 */ } })
|
|
106
|
-
removeText(lockPath)
|
|
86
|
+
catch (e) { return e?.code !== "ESRCH" } // 只有「不存在」算死;无权限等同「不确定」⇒ 算活(保守)
|
|
107
87
|
}
|
|
108
88
|
|
|
109
89
|
/** 同 profile 残留进程列表(平台分支——一次 exec 取全表;失败 ⇒ []——尽力面零抛):win32 = 一次
|
|
110
90
|
* Get-CimInstance(PowerShell——wmic 已从新系统移除);POSIX = 一次 ps(自持列表面:既有
|
|
111
|
-
* `process-probe-exec.mjs` 那条链按已知 pid 查 cmdline,本面是反查——零第三方依赖)。
|
|
112
|
-
|
|
91
|
+
* `process-probe-exec.mjs` 那条链按已知 pid 查 cmdline,本面是反查——零第三方依赖)。
|
|
92
|
+
* 导出面 = 两个消费者:孤儿回收(下面)与「锁无记录时的模式来源」(`pool.mjs` 读命令行里的 `--headless=new`)。 */
|
|
93
|
+
export function listProfileProcs(platform = process.platform) {
|
|
113
94
|
try {
|
|
114
95
|
if (platform === "win32") {
|
|
115
96
|
const out = execFileSync("powershell.exe",
|
|
@@ -124,12 +105,11 @@ function defaultListProfileProcs(platform = process.platform) {
|
|
|
124
105
|
} catch { return [] }
|
|
125
106
|
}
|
|
126
107
|
|
|
127
|
-
/** 同 `--user-data-dir` 残留浏览器进程树回收(#1304
|
|
128
|
-
*
|
|
129
|
-
*
|
|
108
|
+
/** 同 `--user-data-dir` 残留浏览器进程树回收(#1304——**调用时机由 `pool.mjs` 按「回收的唯一门槛」把守**,
|
|
109
|
+
* 本档只给执行体:端口答不通**不**证明没人连着(挂死 ∥ 忙等时连接未断),所以不收不看用者登记就收,
|
|
110
|
+
* 会在别人还连着时把浏览器收掉——故本函数不再由 `launchBrowser` 内部调用(BROWSER-TOOL.md §12)。
|
|
130
111
|
* `io` = 注入缝(`platform` ∥ `readText`/`isAlive`/`pid` ∥ `list` ⇒ [{pid, cmdline}] ∥ `kill(pid)`);
|
|
131
|
-
* 平台分支 + 尽力面零抛(列表 ∥
|
|
132
|
-
* ——默认杀器即复用它(pid 形)。 */
|
|
112
|
+
* 平台分支 + 尽力面零抛(列表 ∥ 单杀失败均不阻断启动);默认杀器 = `killBrowser`(pid 形)。 */
|
|
133
113
|
export function reclaimProfileOrphans(profile, io = {}) {
|
|
134
114
|
try {
|
|
135
115
|
const platform = io.platform ?? process.platform
|
|
@@ -137,8 +117,10 @@ export function reclaimProfileOrphans(profile, io = {}) {
|
|
|
137
117
|
const isAlive = io.isAlive ?? defaultPidAlive
|
|
138
118
|
const pid = io.pid ?? process.pid
|
|
139
119
|
const held = Number(String(readText(join(dirname(profile), "session.lock")) ?? "").trim())
|
|
140
|
-
|
|
141
|
-
|
|
120
|
+
// 此守卫只认旧形(裸 pid 一行);今锁写的是 JSON(`pool.mjs` 的持有者登记),`Number(...)` 对它为 NaN ⇒ 本行恒不成立。
|
|
121
|
+
// 「回收前先读用者登记」的门槛在 `pool.mjs`,本行留作旧锁形态的兼容面(BROWSER-TOOL.md §12 要求函数体零改)。
|
|
122
|
+
if (Number.isInteger(held) && held > 0 && held !== pid && isAlive(held)) return
|
|
123
|
+
const list = io.list ?? (() => listProfileProcs(platform))
|
|
142
124
|
const kill = io.kill ?? ((target) => killBrowser({ pid: target, kill: (signal) => process.kill(target, signal) }, { platform }))
|
|
143
125
|
const marker = `--user-data-dir=${profile}`
|
|
144
126
|
for (const row of list() ?? []) {
|
|
@@ -154,9 +136,11 @@ export function reclaimProfileOrphans(profile, io = {}) {
|
|
|
154
136
|
* 启动浏览器(spawn + `DevToolsActivePort` 轮询 ≤ 启动窗)。
|
|
155
137
|
* 启动窗 = `timeoutMs` 显式入参 > env `BROWSER_START_TIMEOUT_MS` > 缺省 25s(`browserStartTimeoutMs`)。
|
|
156
138
|
* 持久 profile ⇒ 启动前清陈旧端口文件(否则旧值被当本次读数——发现即失效)。
|
|
139
|
+
* 同 profile 的残留进程回收**不在本函数内**:调用方(`pool.mjs`)先过「回收的唯一门槛」再回收,
|
|
140
|
+
* 本函数只负责 spawn 与等 `DevToolsActivePort`。
|
|
157
141
|
* @returns {Promise<{child: import("node:child_process").ChildProcess, port: number, profile: string}>}
|
|
158
142
|
*/
|
|
159
|
-
export async function launchBrowser({ exe, headless = true, profile, timeoutMs = browserStartTimeoutMs(), sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
143
|
+
export async function launchBrowser({ exe, headless = true, profile, timeoutMs = browserStartTimeoutMs(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
160
144
|
const args = [
|
|
161
145
|
...(headless ? ["--headless=new"] : []),
|
|
162
146
|
"--disable-gpu", "--no-first-run", "--hide-scrollbars",
|
|
@@ -164,8 +148,6 @@ export async function launchBrowser({ exe, headless = true, profile, timeoutMs =
|
|
|
164
148
|
"--window-size=1440,900", "about:blank",
|
|
165
149
|
]
|
|
166
150
|
mkdirSync(profile, { recursive: true })
|
|
167
|
-
// #1304:锁空闲(调用序保证——`acquireProfileLock` 在前)⇒ 先回收同 profile 残留进程树,再 spawn。
|
|
168
|
-
reclaimProfileOrphans(profile, reclaimIo)
|
|
169
151
|
const portFile = join(profile, "DevToolsActivePort")
|
|
170
152
|
rmSync(portFile, { force: true })
|
|
171
153
|
const child = spawn(exe, args, { stdio: "ignore", detached: process.platform !== "win32" })
|