@thincoder/core 0.11.5 → 0.12.1
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 +27 -0
- package/abort-provenance.mjs +23 -0
- package/advisor/citations.mjs +5 -1
- package/advisor/compaction.mjs +13 -10
- package/advisor/history.mjs +6 -1
- package/advisor/loop.mjs +35 -10
- package/advisor/messages.mjs +31 -43
- package/advisor/project-context.mjs +49 -45
- package/advisor/run.mjs +82 -26
- package/advisor.mjs +40 -11
- package/agent/assemble.mjs +5 -5
- package/agent/chat-call.mjs +21 -1
- package/agent/completion.mjs +1 -20
- package/agent/dispatch-gates.mjs +8 -3
- package/agent/dispatch-run.mjs +131 -20
- package/agent/dispatch.mjs +23 -22
- package/agent/family-tools.mjs +4 -7
- package/agent/goal-judge.mjs +99 -0
- package/agent/goal-state.mjs +96 -0
- package/agent/helpers.mjs +13 -4
- package/agent/offload.mjs +1 -1
- package/agent/planning-graph-guardrail.mjs +224 -0
- package/agent/planning-prompt.mjs +179 -0
- package/agent/planning-step.mjs +460 -173
- package/agent/post-turn.mjs +23 -33
- package/agent/record-results.mjs +8 -5
- package/agent/run-stages.mjs +18 -38
- package/agent/run-start.mjs +26 -19
- package/agent/setup-reminders.mjs +16 -14
- package/agent/setup.mjs +3 -2
- package/agent/spawn-child.mjs +17 -4
- package/agent/suspension.mjs +42 -21
- package/agent/task-lifecycle.mjs +165 -52
- package/agent/timers.mjs +9 -1
- package/agent/turn-loop.mjs +160 -69
- package/agent/turn-projection.mjs +26 -15
- package/agent/turn-task-state.mjs +4 -4
- package/agent/write-gate-ledger.mjs +1 -1
- package/agent/write-gate.mjs +14 -11
- package/agent-tools/advisor-async.mjs +2 -0
- package/agent-tools/advisor-launch.mjs +27 -13
- package/agent-tools/advisor-settle.mjs +19 -18
- package/agent-tools/advisor.mjs +90 -13
- package/agent-tools/bash-async.mjs +3 -3
- package/agent-tools/batch-ledger-bind.mjs +8 -5
- package/agent-tools/batch-read.mjs +42 -0
- package/agent-tools/batch-record-write.mjs +20 -12
- package/agent-tools/batch-segment-vocab.mjs +6 -4
- package/agent-tools/batch-skeleton.mjs +43 -12
- package/agent-tools/consult.mjs +5 -1
- package/agent-tools/context.mjs +5 -4
- package/agent-tools/design-slots.mjs +7 -4
- package/agent-tools/design-token.mjs +3 -2
- package/agent-tools/doc-graph.mjs +257 -95
- package/agent-tools/escalate-async.mjs +4 -1
- package/agent-tools/goal.mjs +28 -95
- package/agent-tools/plan.mjs +1 -1
- package/agent-tools/review-facts.mjs +56 -7
- package/agent-tools/settings.mjs +35 -1
- package/agent-tools/ssh-transport.mjs +23 -22
- package/agent-tools/step.mjs +24 -4
- package/agent-tools/subagent-actions.mjs +6 -2
- package/agent-tools/subagent-async.mjs +4 -2
- package/agent-tools/subagent.mjs +1 -1
- package/agent-tools/task.mjs +73 -65
- package/agent-tools.mjs +3 -3
- package/agent.mjs +12 -3
- package/auto-think.mjs +16 -3
- package/browser/actions.mjs +5 -1
- package/browser/cdp.mjs +1 -1
- package/browser/pool.mjs +110 -17
- package/compaction-work-state.mjs +103 -13
- package/compress-form.mjs +29 -3
- package/config-defaults.mjs +27 -3
- package/config-io.mjs +3 -14
- package/config-normalize.mjs +24 -4
- package/config-presets.mjs +40 -26
- package/config-warn.mjs +30 -0
- package/config.mjs +139 -63
- package/context-degrade.mjs +4 -4
- package/context-push.mjs +20 -9
- package/context.mjs +65 -20
- package/doc-graph/anchors.mjs +39 -40
- package/doc-graph/clusters.mjs +49 -0
- package/doc-graph/code-parsers.mjs +494 -0
- package/doc-graph/context-pack.mjs +392 -0
- package/doc-graph/dir-signals.mjs +228 -0
- package/doc-graph/edges.mjs +231 -0
- package/doc-graph/format.mjs +70 -0
- package/doc-graph/gc-cmd.mjs +104 -0
- package/doc-graph/gc.mjs +112 -0
- package/doc-graph/glob-work-graph.mjs +307 -0
- package/doc-graph/golden-set.mjs +131 -0
- package/doc-graph/ls-work-graph.mjs +534 -0
- package/doc-graph/outline.mjs +377 -0
- package/doc-graph/output-annotations.mjs +85 -0
- package/doc-graph/process-docs.mjs +68 -0
- package/doc-graph/read-work-graph.mjs +91 -0
- package/doc-graph/rebuild-cmd.mjs +75 -0
- package/doc-graph/resolvers.mjs +322 -0
- package/doc-graph/roots.mjs +86 -0
- package/doc-graph/schema.mjs +110 -0
- package/doc-graph/search-augment.mjs +418 -0
- package/doc-graph/store.mjs +231 -0
- package/doc-graph/target-resolve.mjs +352 -0
- package/doc-graph/walk.mjs +87 -0
- package/doc-graph.mjs +583 -707
- package/explore-distill.mjs +52 -17
- package/generate-title.mjs +7 -4
- package/ledger-close.mjs +6 -6
- package/ledger-cmd.mjs +3 -3
- package/ledger-consistency.mjs +8 -6
- package/ledger-db.mjs +45 -10
- package/ledger-migrate.mjs +25 -10
- package/ledger-read.mjs +1 -1
- package/ledger-write-ops.mjs +6 -6
- package/ledger.mjs +2 -2
- package/model-context.mjs +54 -18
- package/model-specs.mjs +86 -67
- package/package.json +1 -1
- package/prompt-overlays.mjs +3 -3
- package/prompts/advisor-round1.md +6 -5
- package/prompts/common.md +16 -6
- package/prompts/consult-base.md +2 -1
- package/prompts/discipline-engineering.md +1 -1
- package/prompts/discipline-normal.md +12 -8
- package/prompts/knowledge/doc-lookup.md +2 -2
- package/prompts/knowledge/normal-batch-discipline.md +2 -2
- package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
- package/prompts/knowledge/tool-advisor.md +2 -2
- package/prompts/knowledge/tool-apply-patch.md +1 -1
- package/prompts/knowledge/tool-bash.md +2 -2
- package/prompts/knowledge/tool-batch.md +4 -4
- package/prompts/knowledge/tool-glob.md +9 -2
- package/prompts/knowledge/tool-goal.md +9 -6
- package/prompts/knowledge/tool-grep.md +7 -2
- package/prompts/knowledge/tool-ls.md +11 -5
- package/prompts/knowledge/tool-lsp.md +1 -1
- package/prompts/knowledge/tool-operations.md +3 -2
- package/prompts/knowledge/tool-plan.md +1 -1
- package/prompts/knowledge/tool-read.md +7 -6
- package/prompts/knowledge/tool-repo-graph-read.md +12 -0
- package/prompts/knowledge/tool-repo-graph.md +12 -0
- package/prompts/knowledge/tool-step.md +1 -1
- package/prompts/knowledge/tool-subagent.md +2 -2
- package/prompts/knowledge/tool-task.md +10 -9
- package/prompts/knowledge/tool-tree.md +7 -1
- package/prompts/persona-eng-coder.md +1 -1
- package/prompts/persona-eng-designer.md +1 -1
- package/prompts/persona-engineering.md +2 -1
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-normal.md +7 -6
- package/prompts/persona-plan.md +2 -2
- package/prompts/planning-next-moves.md +7 -8
- package/provider/anthropic.mjs +53 -51
- package/provider/core.mjs +85 -34
- package/provider/errors.mjs +33 -10
- package/provider/google.mjs +244 -37
- package/provider/list-models.mjs +28 -14
- package/provider/responses-request.mjs +15 -9
- package/provider/responses.mjs +10 -8
- package/provider/sse.mjs +3 -6
- package/proxy-transport.mjs +228 -119
- package/rules-file.mjs +79 -0
- package/rules.mjs +13 -51
- package/session-lifecycle.mjs +32 -20
- package/team-ledger.mjs +7 -7
- package/think-off.mjs +37 -18
- package/token-window.mjs +48 -31
- package/tool-args.mjs +8 -8
- package/tool-docs/bash.md +1 -1
- package/tool-docs/glob.md +3 -1
- package/tool-docs/goal.md +2 -2
- package/tool-docs/grep.md +3 -1
- package/tool-docs/ls.md +7 -1
- package/tool-docs/read.md +1 -1
- package/tool-docs/repo_graph-read.md +3 -0
- package/tool-docs/repo_graph.md +3 -0
- package/tool-docs/tree.md +1 -1
- package/tools/bash.mjs +53 -8
- package/tools/browser.mjs +4 -4
- package/tools/file.mjs +34 -7
- package/tools/glob-dialect.mjs +57 -7
- package/tools/index.mjs +3 -7
- package/tools/patch.mjs +8 -7
- package/tools/process-doc-mark.mjs +13 -0
- package/tools/search.mjs +152 -37
- package/tools/shared.mjs +6 -0
- package/tools/tree.mjs +211 -8
- package/window-policy.mjs +205 -126
- package/prompts/knowledge/tool-doc-graph-read.md +0 -20
- package/prompts/knowledge/tool-doc-graph.md +0 -49
- package/prompts/knowledge/tool-peek.md +0 -10
- package/prompts/knowledge/tool-repo-outline.md +0 -4
- package/tool-docs/doc_graph-read.md +0 -3
- package/tool-docs/doc_graph.md +0 -3
- package/tool-docs/peek.md +0 -3
- package/tool-docs/repo_outline.md +0 -3
- package/tools/peek.mjs +0 -447
package/agent-tools/task.mjs
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
// F-CC4(CONTEXT-COMPACTION.md §6.16.5):task 列表变更 ⇒ 方向转换轻推(本档只调用;文案/去重单源 = agent-tools/context.mjs)
|
|
2
|
-
import { pushContextNudge } from "./context.mjs"
|
|
3
1
|
import { DESC } from "../tools/shared.mjs"
|
|
4
2
|
import { summarizeTaskList } from "../agent/task-lifecycle.mjs"
|
|
5
3
|
|
|
@@ -26,9 +24,48 @@ function normalizeStatus(raw) {
|
|
|
26
24
|
return STATUS_ALIASES[key] ?? STATUS_ALIASES[raw] ?? null
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
function
|
|
30
|
-
|
|
31
|
-
|
|
27
|
+
function queryTasks(agent, action, ref) {
|
|
28
|
+
const list = Array.isArray(agent?.tasks) ? agent.tasks : []
|
|
29
|
+
const view = (it, index) => ({
|
|
30
|
+
index: index + 1,
|
|
31
|
+
title: String(it?.title ?? ""),
|
|
32
|
+
status: it?.status ?? "pending",
|
|
33
|
+
})
|
|
34
|
+
if (action === "list") return JSON.stringify({ items: list.map(view) })
|
|
35
|
+
if (!String(ref ?? "").trim()) return "Error: action:'get' requires ref (1-based number or title substring)."
|
|
36
|
+
const index = resolveTaskMatchIndex(list, ref)
|
|
37
|
+
if (index === -1) return `Error: no task matched "${String(ref ?? "").trim()}"`
|
|
38
|
+
return JSON.stringify(view(list[index], index))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normalizeCompleteRefs(raw) {
|
|
42
|
+
if (Array.isArray(raw)) return raw.map((x) => String(x ?? "").trim()).filter(Boolean)
|
|
43
|
+
if (typeof raw === "string") {
|
|
44
|
+
const s = raw.trim()
|
|
45
|
+
if (!s) return []
|
|
46
|
+
if (s.startsWith("[")) {
|
|
47
|
+
try {
|
|
48
|
+
const parsed = JSON.parse(s)
|
|
49
|
+
if (Array.isArray(parsed)) return parsed.map((x) => String(x ?? "").trim()).filter(Boolean)
|
|
50
|
+
} catch { /* fall back to literal single ref */ }
|
|
51
|
+
}
|
|
52
|
+
return [s]
|
|
53
|
+
}
|
|
54
|
+
return []
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function normalizeItemsArg(raw) {
|
|
58
|
+
if (Array.isArray(raw)) return raw
|
|
59
|
+
if (typeof raw === "string") {
|
|
60
|
+
const s = raw.trim()
|
|
61
|
+
if (s.startsWith("[")) {
|
|
62
|
+
try {
|
|
63
|
+
const parsed = JSON.parse(s)
|
|
64
|
+
if (Array.isArray(parsed)) return parsed
|
|
65
|
+
} catch { /* ignore invalid JSON string */ }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return null
|
|
32
69
|
}
|
|
33
70
|
|
|
34
71
|
function resolveTaskMatchIndex(list, rawRef) {
|
|
@@ -46,8 +83,7 @@ function resolveTaskMatchIndex(list, rawRef) {
|
|
|
46
83
|
return list.findIndex((it) => String(it?.title ?? "").toLowerCase().includes(needle))
|
|
47
84
|
}
|
|
48
85
|
|
|
49
|
-
function applyIncrementalUpdates(list, { complete, start,
|
|
50
|
-
const cleanResult = typeof result === "string" ? result.trim().slice(0, 240) : ""
|
|
86
|
+
function applyIncrementalUpdates(list, { complete, start, warnings }) {
|
|
51
87
|
if (Array.isArray(complete) && complete.length > 0) {
|
|
52
88
|
const markAll = complete.some((r) => {
|
|
53
89
|
const s = String(r ?? "").trim().toLowerCase()
|
|
@@ -55,10 +91,7 @@ function applyIncrementalUpdates(list, { complete, start, result, warnings }) {
|
|
|
55
91
|
})
|
|
56
92
|
if (markAll) {
|
|
57
93
|
for (const it of list) {
|
|
58
|
-
if (it.status !== "done")
|
|
59
|
-
it.status = "done"
|
|
60
|
-
if (cleanResult) it.result = cleanResult
|
|
61
|
-
}
|
|
94
|
+
if (it.status !== "done") it.status = "done"
|
|
62
95
|
}
|
|
63
96
|
} else {
|
|
64
97
|
for (const ref of complete) {
|
|
@@ -68,7 +101,6 @@ function applyIncrementalUpdates(list, { complete, start, result, warnings }) {
|
|
|
68
101
|
continue
|
|
69
102
|
}
|
|
70
103
|
list[idx].status = "done"
|
|
71
|
-
if (cleanResult) list[idx].result = cleanResult
|
|
72
104
|
}
|
|
73
105
|
}
|
|
74
106
|
}
|
|
@@ -93,6 +125,15 @@ export const taskTool = {
|
|
|
93
125
|
parameters: {
|
|
94
126
|
type: "object",
|
|
95
127
|
properties: {
|
|
128
|
+
action: {
|
|
129
|
+
type: "string",
|
|
130
|
+
enum: ["list", "get"],
|
|
131
|
+
description: "Read current tasks without changing state. Use get with ref.",
|
|
132
|
+
},
|
|
133
|
+
ref: {
|
|
134
|
+
type: "string",
|
|
135
|
+
description: "1-based task number or title substring for action:'get'.",
|
|
136
|
+
},
|
|
96
137
|
items: {
|
|
97
138
|
type: "array",
|
|
98
139
|
description: "Full replacement list of tasks; pass [] to clear. Omit when using clear, complete, or start.",
|
|
@@ -101,23 +142,6 @@ export const taskTool = {
|
|
|
101
142
|
properties: {
|
|
102
143
|
title: { type: "string", description: "Short summary of this micro-step." },
|
|
103
144
|
status: { type: "string", enum: ["pending", "in_progress", "done"] },
|
|
104
|
-
targets: {
|
|
105
|
-
type: "array",
|
|
106
|
-
items: { type: "string" },
|
|
107
|
-
description: "Optional file paths touched in this micro-step slice (ideally 1-3).",
|
|
108
|
-
},
|
|
109
|
-
evidence: {
|
|
110
|
-
type: "string",
|
|
111
|
-
description: "Optional verified facts or anchors read before editing this step.",
|
|
112
|
-
},
|
|
113
|
-
verify: {
|
|
114
|
-
type: "string",
|
|
115
|
-
description: "Optional targeted check to run right after completing this step.",
|
|
116
|
-
},
|
|
117
|
-
result: {
|
|
118
|
-
type: "string",
|
|
119
|
-
description: "Optional observed verification reading recorded when marking this step done.",
|
|
120
|
-
},
|
|
121
145
|
},
|
|
122
146
|
required: ["title", "status"],
|
|
123
147
|
},
|
|
@@ -135,18 +159,25 @@ export const taskTool = {
|
|
|
135
159
|
type: "string",
|
|
136
160
|
description: "1-based task number (e.g. \"2\") or title substring to mark in_progress without resending items.",
|
|
137
161
|
},
|
|
138
|
-
result: {
|
|
139
|
-
type: "string",
|
|
140
|
-
description: "Optional observed verification reading attached to items completed via complete.",
|
|
141
|
-
},
|
|
142
162
|
},
|
|
143
163
|
},
|
|
144
164
|
readonly: true,
|
|
145
165
|
async execute(args = {}, ctx) {
|
|
146
|
-
const
|
|
147
|
-
|
|
166
|
+
const action = typeof args.action === "string" ? args.action.trim().toLowerCase() : ""
|
|
167
|
+
if (action) {
|
|
168
|
+
if (action !== "list" && action !== "get") return `Error: unsupported action "${action}"`
|
|
169
|
+
if (["items", "clear", "complete", "start"].some((key) => args[key] !== undefined)) {
|
|
170
|
+
return "Error: action:'list'/'get' cannot be combined with task updates."
|
|
171
|
+
}
|
|
172
|
+
return queryTasks(ctx.agent, action, args.ref)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const parsedItems = normalizeItemsArg(args.items)
|
|
176
|
+
const completeRefs = normalizeCompleteRefs(args.complete)
|
|
177
|
+
const hasItems = Array.isArray(parsedItems)
|
|
178
|
+
const hasComplete = completeRefs.length > 0
|
|
148
179
|
const hasStart = args.start !== undefined && args.start !== null && String(args.start).trim() !== ""
|
|
149
|
-
const wantsClear = args.clear === true || (hasItems &&
|
|
180
|
+
const wantsClear = args.clear === true || (hasItems && parsedItems.length === 0 && !hasComplete && !hasStart)
|
|
150
181
|
|
|
151
182
|
if (!wantsClear && !hasItems && !hasComplete && !hasStart) {
|
|
152
183
|
return "Error: pass items (full list), clear: true, or complete/start to update tasks."
|
|
@@ -155,9 +186,7 @@ export const taskTool = {
|
|
|
155
186
|
if (wantsClear) {
|
|
156
187
|
ctx.agent.tasks = []
|
|
157
188
|
ctx.agent._turnsSinceTaskUpdate = 0
|
|
158
|
-
ctx.agent._taskStaleNudgeSent = false
|
|
159
189
|
ctx.agent._onTaskUpdate?.([])
|
|
160
|
-
if (ctx.depth === 0) pushContextNudge(ctx.agent)
|
|
161
190
|
return "Task list cleared."
|
|
162
191
|
}
|
|
163
192
|
|
|
@@ -165,7 +194,7 @@ export const taskTool = {
|
|
|
165
194
|
const warnings = []
|
|
166
195
|
let working
|
|
167
196
|
if (hasItems) {
|
|
168
|
-
working =
|
|
197
|
+
working = parsedItems.map((it) => {
|
|
169
198
|
const normalized = normalizeStatus(it.status)
|
|
170
199
|
if (normalized && normalized !== it.status) {
|
|
171
200
|
warnings.push(`status "${it.status}" normalized to "${normalized}"`)
|
|
@@ -176,32 +205,22 @@ export const taskTool = {
|
|
|
176
205
|
if (!title) {
|
|
177
206
|
warnings.push(`empty title skipped (item was: ${JSON.stringify(it).slice(0, 100)})`)
|
|
178
207
|
}
|
|
179
|
-
|
|
208
|
+
return {
|
|
180
209
|
title,
|
|
181
210
|
status: normalized ?? "pending",
|
|
182
211
|
}
|
|
183
|
-
const targets = normalizeTargets(it.targets)
|
|
184
|
-
if (targets.length > 0) entry.targets = targets
|
|
185
|
-
const evidence = typeof it.evidence === "string" ? it.evidence.trim() : ""
|
|
186
|
-
if (evidence) entry.evidence = evidence.slice(0, 300)
|
|
187
|
-
const verify = typeof it.verify === "string" ? it.verify.trim() : ""
|
|
188
|
-
if (verify) entry.verify = verify.slice(0, 240)
|
|
189
|
-
const result = typeof it.result === "string" ? it.result.trim() : ""
|
|
190
|
-
if (result) entry.result = result.slice(0, 240)
|
|
191
|
-
return entry
|
|
192
212
|
}).filter((t) => t.title.length > 0)
|
|
193
213
|
} else {
|
|
194
214
|
working = (Array.isArray(ctx.agent.tasks) ? ctx.agent.tasks : []).map((it) => ({
|
|
195
|
-
|
|
196
|
-
|
|
215
|
+
title: it?.title,
|
|
216
|
+
status: it?.status,
|
|
197
217
|
}))
|
|
198
218
|
}
|
|
199
219
|
|
|
200
220
|
if (hasComplete || hasStart) {
|
|
201
221
|
applyIncrementalUpdates(working, {
|
|
202
|
-
complete:
|
|
222
|
+
complete: completeRefs,
|
|
203
223
|
start: args.start,
|
|
204
|
-
result: args.result,
|
|
205
224
|
warnings,
|
|
206
225
|
})
|
|
207
226
|
}
|
|
@@ -211,26 +230,15 @@ export const taskTool = {
|
|
|
211
230
|
const items = [...pending, ...recentDone].slice(0, 20)
|
|
212
231
|
ctx.agent.tasks = items
|
|
213
232
|
ctx.agent._turnsSinceTaskUpdate = 0
|
|
214
|
-
ctx.agent._taskStaleNudgeSent = false
|
|
215
233
|
ctx.agent._onTaskUpdate?.(items)
|
|
216
|
-
if (ctx.depth === 0) pushContextNudge(ctx.agent) // F-CC4 轻推(§6.16.5——depth-0 门:子代理拿不到 context 工具)
|
|
217
234
|
const info = summarizeTaskList(items, { maxOpen: 6 })
|
|
218
235
|
const active = items.filter((i) => i.status === "in_progress")
|
|
219
236
|
if (active.length > 1) {
|
|
220
237
|
warnings.push(`${active.length} items are in_progress — prefer 1 micro-step slice at a time`)
|
|
221
238
|
}
|
|
222
|
-
const activeLine = active.length === 1
|
|
223
|
-
? (() => {
|
|
224
|
-
const cur = active[0]
|
|
225
|
-
const parts = [`Active step: ${cur.title}`]
|
|
226
|
-
if (cur.targets?.length) parts.push(`targets: ${cur.targets.join(", ")}`)
|
|
227
|
-
if (cur.verify) parts.push(`verify: ${cur.verify}`)
|
|
228
|
-
return `\n${parts.join(" | ")}`
|
|
229
|
-
})()
|
|
230
|
-
: ""
|
|
231
239
|
const openLine = info.open > 0 ? `\nOpen: ${info.summary}` : ""
|
|
232
240
|
const warningText = warnings.length > 0 ? ` ⚠️ ${warnings.join("; ")}` : ""
|
|
233
241
|
return `Task list updated: ${info.done}/${items.length} done` +
|
|
234
|
-
(info.open > 0 ? ` — ${info.open} item(s) still open.` : " — all done.") + warningText +
|
|
242
|
+
(info.open > 0 ? ` — ${info.open} item(s) still open.` : " — all done.") + warningText + openLine
|
|
235
243
|
},
|
|
236
244
|
}
|
package/agent-tools.mjs
CHANGED
|
@@ -31,6 +31,6 @@ export { consultStartTool, consultStopTool } from "./agent-tools/consult.mjs"
|
|
|
31
31
|
// (depth>0 段装配——`agent/family-tools.mjs`;depth-0 / consult 不装配)。
|
|
32
32
|
export { parentChannelTool } from "./agent-tools/parent-channel.mjs"
|
|
33
33
|
export { docCheckTool } from "./agent-tools/doc-check.mjs" // 文档纪律机检(DOC-DISCIPLINE.md §3.20 条目 S——产品内建 · 报告态 · 非门禁)
|
|
34
|
-
//
|
|
35
|
-
// depth-0
|
|
36
|
-
export { docGraphTool, docGraphReadTool } from "./agent-tools/doc-graph.mjs"
|
|
34
|
+
// 项目知识图谱(`repo_graph`,设计 `docs/core/design/REPO-GRAPH.md`):六动作全只读、按 mtime 自动增量同步,
|
|
35
|
+
// depth-0、全部 depth>0 子代理与 advisor 同享。
|
|
36
|
+
export { repoGraphTool, repoGraphReadTool, docGraphTool, docGraphReadTool } from "./agent-tools/doc-graph.mjs"
|
package/agent.mjs
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
// 2026-09-29 P2 三拆(#579):起跑前段 ∕ 回合环 ∕ 模型调用逐字迁 agent/run-start.mjs ∕
|
|
10
10
|
// agent/turn-loop.mjs ∕ agent/chat-call.mjs——本档残留 = 编排 + 状态工厂 + 面(re-export 保面)。
|
|
11
11
|
import { beginRun } from "./agent/run-start.mjs"
|
|
12
|
+
// 派生运行视图(CONTEXT-COMPACTION.md §2.1 档位上下文上限):直接建 agent 的调用方(用例、端壳、ACP)拿到的 provider 也带档位与档位上限表。
|
|
13
|
+
import { bindProviderContextPolicy } from "./config.mjs"
|
|
12
14
|
import { runTurnLoop } from "./agent/turn-loop.mjs"
|
|
13
15
|
import { finalizeAgentTurn } from "./agent/run-stages.mjs"
|
|
14
16
|
// 跨轮机读投影(CONTEXT-COMPACTION §1.1 ∥ SESSION §2 · 台账 #2395):完成轮登记点住本档——
|
|
@@ -58,8 +60,15 @@ export function createAgent({
|
|
|
58
60
|
planMode = false, autoApprove = false,
|
|
59
61
|
goal = null, sessionStart = null,
|
|
60
62
|
}) {
|
|
63
|
+
bindProviderContextPolicy(provider, config) // 派生视图:档位与档位上限表(CONTEXT-COMPACTION.md §2.1)
|
|
61
64
|
return {
|
|
62
65
|
provider, tools, config, cwd, memory, _role: role,
|
|
66
|
+
// 会话视图:模型语义参数(temperature ∥ thinking ∥ reasoningEffort)——**设置层** `config.modelParams`
|
|
67
|
+
// 的同一份引用(与 `agent.provider` 同层,2026-12-03 批、台账 #133)。
|
|
68
|
+
// 模型参数不再是 provider 条目属性(用户裁定「不应该有任何 provider 级别的模型参数」):
|
|
69
|
+
// 每调用由调用方经 `chat(provider, { modelParams })` 下发;此处只是会话默认值的支点。
|
|
70
|
+
// 缺 `config`(用例/子代理的裸建面)⇒ 空对象(三键都不设,不发任何字段)。
|
|
71
|
+
modelParams: (config && typeof config === "object" ? config.modelParams : null) ?? {},
|
|
63
72
|
overlay, tasks, history,
|
|
64
73
|
planMode, autoApprove, goal,
|
|
65
74
|
_mutatedThisRun: false, _verifiedThisRun: false, _verifyPassed: undefined, _calledAdvisorThisRun: false,
|
|
@@ -81,8 +90,8 @@ export function createAgent({
|
|
|
81
90
|
_tok: null, _tokRatio: 1, // §6.17 估算自校准池化比({key,num,den};采样 = turn-loop,清空 = /new)
|
|
82
91
|
_compressFailures: 0,
|
|
83
92
|
_emptyRetries: 0, // empty-response retry budget (per-run; reset on a fresh user turn)
|
|
84
|
-
// §7.4 task 清单运行期追踪(AGENT-LOOP.md §
|
|
85
|
-
_turnsSinceTaskUpdate: 0,
|
|
93
|
+
// §7.4 task 清单运行期追踪(AGENT-LOOP.md §7.4):未更新轮数(供规划步判断清单是否陈旧,不发打扰提醒)。
|
|
94
|
+
_turnsSinceTaskUpdate: 0,
|
|
86
95
|
// §7.1 `wrote` 判据与注入帽的载体(AGENT-LOOP.md §7.1 · §3 续跑沿用):
|
|
87
96
|
// `_batchWrites` = `batch` 工具成功写盘的累计数(`onWritten` 各汇聚点自增);`_designTurnNotices` = 本链已注入的设计轮提醒条数。
|
|
88
97
|
_batchWrites: 0, _designTurnNotices: 0,
|
|
@@ -106,7 +115,7 @@ export async function runAgent(agent, input, callbacks = {}, { depth = 0, signal
|
|
|
106
115
|
try {
|
|
107
116
|
finalResponse = await runTurnLoop(agent, {
|
|
108
117
|
maxTurns, threshold, toolSchemas, toolByName, systemPrompt,
|
|
109
|
-
depth, signal, autoTurn, upstreamTurn, suspDriven, streamOutput, consumeInjected, consumeQueuedInput, callbacks, distillSignal,
|
|
118
|
+
depth, signal, autoTurn, upstreamTurn, timerTurn, suspDriven, streamOutput, consumeInjected, consumeQueuedInput, callbacks, distillSignal,
|
|
110
119
|
})
|
|
111
120
|
return finalResponse
|
|
112
121
|
} catch (e) {
|
package/auto-think.mjs
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* 1. Take the last user message from history
|
|
13
13
|
* 2. Send a minimal classification prompt (expects one-word reply)
|
|
14
14
|
* 3. Map difficulty → reasoningEffort using the model's valid effort enum
|
|
15
|
-
* 4. Set agent.
|
|
15
|
+
* 4. Set agent.modelParams.reasoningEffort before the real chat() call
|
|
16
16
|
*/
|
|
17
17
|
import { chat } from "./provider/core.mjs"
|
|
18
18
|
import { specForModel } from "./config.mjs"
|
|
@@ -94,8 +94,20 @@ export async function classifyAndApply(agent, turn) {
|
|
|
94
94
|
try {
|
|
95
95
|
// #860:关思考形(族别 off 形)+ 小预算 32(原 10 token 被思考吃光)+ reasoningEffort 清空
|
|
96
96
|
//(防父档外溢;effort 族 off 形由载荷门补发 reasoning_effort:"none")。
|
|
97
|
-
|
|
97
|
+
// 小预算走**每调用参数** `opts.reserveTokens`:它是 `chat()` 的参数,不是 provider 字段、也不是配置键
|
|
98
|
+
//——provider 对象上不再有任何模型侧的槽位(用户裁定「不应该有任何 provider 级别的模型参数」;
|
|
99
|
+
// 用户面的 `providers[].maxTokens` 也已于 2026-12-03 退役)。它走同一个 `budgetOf`,所以这里压小的
|
|
100
|
+
// 那份与发送面读的是同一个数。
|
|
101
|
+
const classifierProvider = { ...agent.provider }
|
|
98
102
|
const response = await chat(classifierProvider, {
|
|
103
|
+
// 会话设置(模型窗口声明 ∥ 档位上限)——分类调用的窗口封顶与会话同源(2026-12-03 批)。
|
|
104
|
+
settings: agent.config,
|
|
105
|
+
// 本次调用的输出预算(分类只要一个词;原给 10 被思考吃光)
|
|
106
|
+
reserveTokens: 32,
|
|
107
|
+
// 模型语义参数逐调用下发(2026-12-03 批,台账 #133):分类调用要 **关思考**(族别 off 形)
|
|
108
|
+
// + 清空 reasoningEffort(防父档外溢)——它们不再是 provider 克隆上的字段,
|
|
109
|
+
// 而是本次调用的 `opts.modelParams`(用户裁定「不应该有任何 provider 级别的模型参数」)。
|
|
110
|
+
modelParams: { temperature: agent.modelParams?.temperature, thinking: thinkOffShape(spec), reasoningEffort: null },
|
|
99
111
|
messages: [
|
|
100
112
|
{ role: "system", content: CLASSIFY_PROMPT },
|
|
101
113
|
{ role: "user", content: prompt },
|
|
@@ -137,6 +149,7 @@ export async function classifyAndApply(agent, turn) {
|
|
|
137
149
|
const matched = candidates.find(e => validEfforts.includes(e))
|
|
138
150
|
if (!matched) return null
|
|
139
151
|
|
|
140
|
-
agent.
|
|
152
|
+
agent.modelParams ??= {}
|
|
153
|
+
agent.modelParams.reasoningEffort = matched
|
|
141
154
|
return matched
|
|
142
155
|
}
|
package/browser/actions.mjs
CHANGED
|
@@ -146,12 +146,16 @@ async function actScreenshot(args, ctx, h) {
|
|
|
146
146
|
/** close(§2.2 ∥ §12):幂等——无会话 ⇒ `[close] no browser session`(成功态)。
|
|
147
147
|
* 有会话 ⇒ 摘自己;仍有用者则浏览器留着、回执明说还有几家在用;最后一个关 ⇒ 末关(浏览器关 + 删锁)。
|
|
148
148
|
* 两形回执不可互换:前者浏览器还在跑,后者它已经不在了(模型据此判断「还能不能接着用」)。
|
|
149
|
-
* 末关但浏览器没关成(中止 ∥ 关不下去)⇒
|
|
149
|
+
* 末关但浏览器没关成(中止 ∥ 关不下去)⇒ **不得报「已关」**:回执明说它还在跑、下一位持有者收它
|
|
150
|
+
* (§2.2 close 行第三形 ∥ §12「用者登记与末关」的「关不成 ⇒ 锁留着、关自己的标签页,回执报「仍在跑」」)。 */
|
|
150
151
|
async function actClose(args, ctx, h) {
|
|
151
152
|
if (!h.connection()) return "[close] no browser session"
|
|
152
153
|
const outcome = await h.closeSession()
|
|
153
154
|
if (outcome.lastUser && outcome.browserClosed) return "[close] shared browser closed (last user)"
|
|
154
155
|
if (outcome.lastUser) return "[close] released the shared browser (last user) — the browser is still running; the next instance reclaims it"
|
|
156
|
+
// 读不到他实例登记时不得报一个没读到的数字(2026-12-01 评审 #3):动作是保守的(不关浏览器),
|
|
157
|
+
// 回执也得说「读不到」而不是「还有 1 家在用」——模型靠这句判断能不能接着用。
|
|
158
|
+
if (outcome.readFailed) return "[close] released the shared browser (could not read the other instances' registrations — the browser is left running)"
|
|
155
159
|
const others = Number(outcome.others) || 0
|
|
156
160
|
return `[close] released the shared browser (${others} other instance(s) still using it — the browser is left running)`
|
|
157
161
|
}
|
package/browser/cdp.mjs
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* 拆成类以承载多动作会话(connect / call / on / close),并加 HTTP 面 `/json/new` 取标签页。
|
|
6
6
|
* `WebSocketImpl` = 注入缝(缺省 `globalThis.WebSocket`;单元测试注假传输——缺省回落真实现,`??`)。
|
|
7
7
|
*
|
|
8
|
-
* 错误语义:CDP 回 `{ error: { message } }` ⇒ 拒以 `Error(message)`(BROWSER-TOOL.md §
|
|
8
|
+
* 错误语义:CDP 回 `{ error: { message } }` ⇒ 拒以 `Error(message)`(BROWSER-TOOL.md §2.2 动作契约的失败形)。
|
|
9
9
|
* 帽(§2.9 三层帽——层二 / 层三):`call` 缺省帽 15s(任何未显式配帽的调用也不悬挂);`connectCdp` open 帽
|
|
10
10
|
* 10s;`/json/new` ∥ `/json/close` fetch 帽 5s;`/json/version` 探针帽 2s——动作内调用另随动作控制器(session 侧接线,预算先行)。
|
|
11
11
|
*
|
package/browser/pool.mjs
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*
|
|
20
20
|
* 注入缝(§12 机制落点:目录 ∥ 判活 ∥ 时钟):每个导出接 `io`,缺省回落真实现;`_deps` 供用例整体覆写。
|
|
21
21
|
*/
|
|
22
|
-
import { closeSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"
|
|
22
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs"
|
|
23
23
|
import { dirname, join } from "node:path"
|
|
24
24
|
import { closeTab, newTab, probeVersion } from "./cdp.mjs"
|
|
25
25
|
import { browserStartTimeoutMs, launchBrowser, listProfileProcs, reclaimProfileOrphans, resolveBrowser } from "./launch.mjs"
|
|
@@ -30,6 +30,9 @@ const PROBE_CAP_MS = 2_000
|
|
|
30
30
|
const WAIT_POLL_MS = 50
|
|
31
31
|
/** 原子领取 ∥ 摘陈旧位失败后的重判上限(防两实例互摘空转)。 */
|
|
32
32
|
const CLAIM_ATTEMPTS = 5
|
|
33
|
+
/** 读不懂的用者登记档的「新鲜」宽限(ms):刚写的半成品按活处置,超过这个宽限仍读不懂 ⇒ 陈旧位,摘除。
|
|
34
|
+
* 登记是单条小档、写侧非原子,抓到半写形是可能的;但一个永远读不懂的档不能永久挡住回收。 */
|
|
35
|
+
const UNREADABLE_ENTRY_GRACE_MS = 1_000
|
|
33
36
|
|
|
34
37
|
/** pid 活性(方向不对称——只有 ESRCH 算死,无权限等一律算活)。 */
|
|
35
38
|
function pidAlive(pid) {
|
|
@@ -45,7 +48,13 @@ function portOnDisk(profile) {
|
|
|
45
48
|
}
|
|
46
49
|
|
|
47
50
|
function readTextReal(path) {
|
|
48
|
-
try { return readFileSync(path, "utf8") }
|
|
51
|
+
try { return readFileSync(path, "utf8") }
|
|
52
|
+
catch (e) {
|
|
53
|
+
// 只把 ENOENT 当「不在盘」;其余读失败照旧抛——需求 §4「不把读失败当空集合」。
|
|
54
|
+
// (锁被读成「无锁」会走进「持有」形;端口档被读成空会走进「端口答不通」——两者都是拿读失败当事实。)
|
|
55
|
+
if (e?.code === "ENOENT") return ""
|
|
56
|
+
throw e
|
|
57
|
+
}
|
|
49
58
|
}
|
|
50
59
|
|
|
51
60
|
/** 在跑那台浏览器的模式(锁无记录时的模式来源——读命令行里的 `--headless=new`;读不到 ⇒ null = 不给值)。
|
|
@@ -63,16 +72,47 @@ function headlessFromCmdline(profile) {
|
|
|
63
72
|
const REAL = {
|
|
64
73
|
readText: readTextReal,
|
|
65
74
|
writeText: (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text, "utf8") },
|
|
66
|
-
/** 创建即领取:`wx`
|
|
75
|
+
/** 创建即领取:`wx` 成功才算获得;**锁已被抢 ⇒ 返回 false**(竞争失败,交给外层四形重判——
|
|
76
|
+
* 不是错误)。「先查后建」在两实例同时首开那一窗必漏;而把 EEXIST 往上抛则会让输家把
|
|
77
|
+
* 「别人正在启动」当失败交出去(2026-12-01 实测:`browser-shared-pool` 34-1 报 EEXIST)。 */
|
|
67
78
|
claim: (path, text) => {
|
|
68
79
|
mkdirSync(dirname(path), { recursive: true })
|
|
69
|
-
|
|
70
|
-
try {
|
|
80
|
+
let fd
|
|
81
|
+
try { fd = openSync(path, "wx") }
|
|
82
|
+
catch (e) {
|
|
83
|
+
if (e?.code === "EEXIST") return false
|
|
84
|
+
throw e // 磁盘满 ∥ 权限这类不是竞争,照旧抛
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
try { writeSync(fd, text) } finally { closeSync(fd) }
|
|
88
|
+
} catch (e) {
|
|
89
|
+
// 写失败(ENOSPC ∥ 权限)不能留一个空锁档:新契约下 EEXIST ⇒ false,空档会让后续每次领取
|
|
90
|
+
// 都判成「竞争失败」,五次烧完只报 did-not-settle,真正原因被掩埋。
|
|
91
|
+
try { rmSync(path, { force: true }) } catch { /* 已不在盘 */ }
|
|
92
|
+
throw e
|
|
93
|
+
}
|
|
71
94
|
return true
|
|
72
95
|
},
|
|
73
96
|
rename: (from, to) => renameSync(from, to),
|
|
74
97
|
remove: (path) => { try { rmSync(path, { force: true }) } catch { /* 已不在盘 */ } },
|
|
75
|
-
|
|
98
|
+
exists: (path) => existsSync(path),
|
|
99
|
+
mtime: (path) => {
|
|
100
|
+
try { return statSync(path).mtimeMs }
|
|
101
|
+
catch (e) {
|
|
102
|
+
if (e?.code === "ENOENT") return null
|
|
103
|
+
throw e
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
/** 列目录:**只把 ENOENT 当空集**(首次使用时目录尚未建,语义与空同);其余读失败照旧抛——
|
|
107
|
+
* `EACCES` ∥ `EPERM` ∥ `EIO` 当空集会让 `liveUsers` 报零条目,从而越过「有他实例活条目就不收、
|
|
108
|
+
* 不拉起」的门槛去回收同 profile 孤儿(需求 §4:不把读失败当空集合)。 */
|
|
109
|
+
listDir: (dir) => {
|
|
110
|
+
try { return readdirSync(dir) }
|
|
111
|
+
catch (e) {
|
|
112
|
+
if (e?.code === "ENOENT") return []
|
|
113
|
+
throw e
|
|
114
|
+
}
|
|
115
|
+
},
|
|
76
116
|
isAlive: pidAlive,
|
|
77
117
|
now: () => Date.now(),
|
|
78
118
|
sleep: (ms) => new Promise((resolve) => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
|
|
@@ -137,11 +177,25 @@ export function registerUser({ paths, pid, tabId }, io = {}) {
|
|
|
137
177
|
export function liveUsers({ paths, io = {} } = {}) {
|
|
138
178
|
const d = depsOf(io)
|
|
139
179
|
const alive = []
|
|
140
|
-
|
|
180
|
+
let names
|
|
181
|
+
try { names = d.listDir(paths.users) ?? [] }
|
|
182
|
+
catch (e) {
|
|
183
|
+
// 读不到登记 ⇒ 无法判断「有没有别人在用」⇒ 不收、不拉起,明确报错(方向不对称:误留只多留一台
|
|
184
|
+
// 浏览器,误收会关掉别人在用的)。ENOENT 已在 `listDir` 里当空集。
|
|
185
|
+
throw new Error(`cannot read the shared browser user registrations at ${paths.users} (${e?.code ?? e?.message ?? "read failed"}) — not reclaiming`)
|
|
186
|
+
}
|
|
187
|
+
for (const name of names) {
|
|
141
188
|
if (!String(name).endsWith(".json")) continue
|
|
142
189
|
const file = join(paths.users, String(name))
|
|
143
190
|
const record = parseJson(d.readText(file))
|
|
144
|
-
if (!record || !Number.isInteger(record.pid)) {
|
|
191
|
+
if (!record || !Number.isInteger(record.pid)) {
|
|
192
|
+
// 读不懂的档:宽限内按「活」处置(半写形是可能的;方向不对称——误留只多留一台浏览器);
|
|
193
|
+
// 过了宽限仍读不懂 ⇒ 陈旧半写档,摘掉(否则它永久占据「回收的唯一门槛」,只能人工删档)。
|
|
194
|
+
const age = d.now() - (d.mtime(file) ?? 0)
|
|
195
|
+
if (age > UNREADABLE_ENTRY_GRACE_MS) { d.remove(file); continue }
|
|
196
|
+
alive.push({ pid: null, tabId: null, joinedAt: 0, unreadable: true })
|
|
197
|
+
continue
|
|
198
|
+
}
|
|
145
199
|
if (d.isAlive(record.pid)) alive.push({ pid: record.pid, tabId: record.tabId ?? null, joinedAt: record.joinedAt ?? 0 })
|
|
146
200
|
else d.remove(file)
|
|
147
201
|
}
|
|
@@ -151,9 +205,11 @@ export function liveUsers({ paths, io = {} } = {}) {
|
|
|
151
205
|
const otherUsers = (paths, self, d) => liveUsers({ paths, io: d }).filter((user) => user.pid !== self)
|
|
152
206
|
|
|
153
207
|
/** 门槛命中时的显式失败(§12「被挡住时的出路」:让那些实例 close ∥ 退出后重试,不静默重试)。 */
|
|
154
|
-
function blockedError({ port, others }) {
|
|
208
|
+
function blockedError({ port, others, unreadable = false }) {
|
|
155
209
|
const where = port ? ` on port ${port}` : ""
|
|
156
|
-
|
|
210
|
+
// 含读不懂的登记时点名它——不把「没读到」报成一个确定的数量
|
|
211
|
+
const note = unreadable ? " (at least one registration could not be read)" : ""
|
|
212
|
+
return new Error(`the shared browser is unreachable${where} and ${others} other instance(s) hold live registrations${note} — not reclaiming`)
|
|
157
213
|
}
|
|
158
214
|
|
|
159
215
|
/** 模式沿用注记(§12「模式」条):只在**要的事与生效值不一致**时发(同值 ⇒ 零注记,§2.4)。 */
|
|
@@ -188,10 +244,16 @@ async function joinShared({ paths, d, self, port, wantedHeadless }) {
|
|
|
188
244
|
async function claimSlot({ paths, d, self, wantedHeadless }) {
|
|
189
245
|
const startedAt = d.now()
|
|
190
246
|
if (!d.claim(paths.lock, JSON.stringify({ pid: self, headless: null, port: null, startedAt }))) return null
|
|
191
|
-
|
|
247
|
+
let held
|
|
248
|
+
try { held = otherUsers(paths, self, d) }
|
|
249
|
+
catch (e) {
|
|
250
|
+
// 读不到登记 ⇒ 不收、不拉起;且自己刚建的位必须摘掉——留着会让后来者读到「pid 活」而白等一个启动窗
|
|
251
|
+
d.remove(paths.lock)
|
|
252
|
+
throw e
|
|
253
|
+
}
|
|
192
254
|
if (held.length) {
|
|
193
255
|
d.remove(paths.lock)
|
|
194
|
-
throw blockedError({ port: d.port(paths), others: held.length })
|
|
256
|
+
throw blockedError({ port: d.port(paths), others: held.length, unreadable: held.some((user) => user.unreadable) })
|
|
195
257
|
}
|
|
196
258
|
d.reclaim(paths.profile)
|
|
197
259
|
let launched
|
|
@@ -209,7 +271,7 @@ async function claimSlot({ paths, d, self, wantedHeadless }) {
|
|
|
209
271
|
/** 接管:门槛 → `rename` 摘陈旧位(原子——两方同时摘只有一个成功)→ 领取并拉起。 */
|
|
210
272
|
async function takeOver({ paths, d, self, wantedHeadless, holder }) {
|
|
211
273
|
const held = otherUsers(paths, self, d)
|
|
212
|
-
if (held.length) throw blockedError({ port: d.port(paths), others: held.length })
|
|
274
|
+
if (held.length) throw blockedError({ port: d.port(paths), others: held.length, unreadable: held.some((user) => user.unreadable) })
|
|
213
275
|
const stale = `${paths.lock}.stale-${holder.pid}`
|
|
214
276
|
try { d.rename(paths.lock, stale) } catch { return null } // 已被别人摘走 ⇒ 重判
|
|
215
277
|
d.remove(stale)
|
|
@@ -237,13 +299,30 @@ async function waitForPort({ paths, d, holder }) {
|
|
|
237
299
|
export async function attachOrLaunch({ paths, wantedHeadless = true, io = {} } = {}) {
|
|
238
300
|
const d = depsOf(io)
|
|
239
301
|
const self = d.pid()
|
|
302
|
+
// 锁在盘却读不出(空档 ∥ 半写)的连续观测次数:一次可能是赢家刚 `open` 还没 `write` 的亚毫秒窗,
|
|
303
|
+
// 连观测两次(中间隔一拍)仍读不出 ⇒ 真陈旧位。不摘它,`claim` 的 `EEXIST ⇒ false` 会让后来者永远卡在
|
|
304
|
+
// 「持有」形,五轮烧完只报 did-not-settle(2026-12-01 评审发现的死结)。
|
|
305
|
+
let unreadableStreak = 0
|
|
240
306
|
for (let attempt = 0; attempt < CLAIM_ATTEMPTS; attempt++) {
|
|
241
307
|
const port = d.port(paths)
|
|
242
308
|
if (port && (await d.probe(port))) return joinShared({ paths, d, self, port, wantedHeadless })
|
|
243
309
|
const holder = readHolder(paths.lock, d)
|
|
310
|
+
if (holder) unreadableStreak = 0 // 读得出合法持有者 ⇒ 「连续读不出」的计数断掉(否则累计值会跨轮污染)
|
|
244
311
|
if (!holder) {
|
|
312
|
+
const lockOnDisk = d.exists(paths.lock)
|
|
313
|
+
unreadableStreak = lockOnDisk ? unreadableStreak + 1 : 0
|
|
314
|
+
if (unreadableStreak >= 2) {
|
|
315
|
+
// 不可解析的陈旧位:`rename` 原子——两方同时摘只有一个成功,输家下一轮重判
|
|
316
|
+
try { d.rename(paths.lock, `${paths.lock}.stale-unreadable-${self}`) } catch { /* 已被别人摘走 */ }
|
|
317
|
+
d.remove(`${paths.lock}.stale-unreadable-${self}`)
|
|
318
|
+
unreadableStreak = 0
|
|
319
|
+
continue
|
|
320
|
+
}
|
|
245
321
|
const slot = await claimSlot({ paths, d, self, wantedHeadless })
|
|
246
322
|
if (slot) return slot
|
|
323
|
+
// 输掉领取(锁已被抢)⇒ 等赢家一步再重判:立即重试会把 `CLAIM_ATTEMPTS` 在它写回锁之前烧光,
|
|
324
|
+
// 落到「pool did not settle」那类假失败。与「等待」形的轮询同拍。
|
|
325
|
+
await d.sleep(WAIT_POLL_MS)
|
|
247
326
|
continue
|
|
248
327
|
}
|
|
249
328
|
const inWindow = d.now() - holder.startedAt <= d.startWindow()
|
|
@@ -253,10 +332,12 @@ export async function attachOrLaunch({ paths, wantedHeadless = true, io = {} } =
|
|
|
253
332
|
// 到点仍未答通 ⇒ 直接转「接管」(§12 四形表);接管抢输(陈旧位已被别人摘走)⇒ 重判
|
|
254
333
|
const slot = await takeOver({ paths, d, self, wantedHeadless, holder })
|
|
255
334
|
if (slot) return slot
|
|
335
|
+
await d.sleep(WAIT_POLL_MS)
|
|
256
336
|
continue
|
|
257
337
|
}
|
|
258
338
|
const slot = await takeOver({ paths, d, self, wantedHeadless, holder })
|
|
259
339
|
if (slot) return slot
|
|
340
|
+
await d.sleep(WAIT_POLL_MS)
|
|
260
341
|
}
|
|
261
342
|
throw new Error("the shared browser pool did not settle (repeated claim races) — run the action again")
|
|
262
343
|
}
|
|
@@ -273,10 +354,21 @@ export async function attachOrLaunch({ paths, wantedHeadless = true, io = {} } =
|
|
|
273
354
|
export async function releaseUser({ paths, tabId = null, closeBrowser = null, io = {} } = {}) {
|
|
274
355
|
const d = depsOf(io)
|
|
275
356
|
const self = d.pid()
|
|
276
|
-
|
|
277
|
-
|
|
357
|
+
// **先摘自己,再读端口**(2026-12-01 评审):端口档读失败(`EACCES` ∥ `EIO`)不得让释放路径停在
|
|
358
|
+
// 自己的登记被摘掉之前——那会留一个活条目永久挡住别人的回收门槛。端口只用于关自己的标签页,读不到就跳过。
|
|
278
359
|
d.remove(userFile(paths, self))
|
|
279
|
-
|
|
360
|
+
let port = null
|
|
361
|
+
try { port = d.port(paths) } catch { port = null }
|
|
362
|
+
const closeOwnTab = async () => { if (port && tabId) await d.closeTab(port, tabId) }
|
|
363
|
+
let others
|
|
364
|
+
try { others = otherUsers(paths, self, d).length }
|
|
365
|
+
catch {
|
|
366
|
+
// 读不到登记 ⇒ 按「还有人在用」保守处置:不关浏览器(关别人的浏览器是硬边界),只关自己的标签页。
|
|
367
|
+
// `others: 1` 是**哨兵值**(不是计数):回执面(`actClose`)已改判 `readFailed` 分形,
|
|
368
|
+
// 但 `releaseUserSync().others` 直接驱动退出钩子的杀树判据(`left === 0`)——那里需要一个「不杀」的值。
|
|
369
|
+
await closeOwnTab()
|
|
370
|
+
return { others: 1, lastUser: false, browserClosed: false, readFailed: true }
|
|
371
|
+
}
|
|
280
372
|
if (others > 0) {
|
|
281
373
|
await closeOwnTab() // 仍有人用 ⇒ 只关自己的标签页,浏览器留着(关别人的浏览器是硬边界)
|
|
282
374
|
return { others, lastUser: false, browserClosed: false }
|
|
@@ -295,5 +387,6 @@ export function releaseUserSync({ paths, io = {} } = {}) {
|
|
|
295
387
|
const d = depsOf(io)
|
|
296
388
|
const self = d.pid()
|
|
297
389
|
d.remove(userFile(paths, self))
|
|
298
|
-
return { others: otherUsers(paths, self, d).length }
|
|
390
|
+
try { return { others: otherUsers(paths, self, d).length } }
|
|
391
|
+
catch { return { others: 1, readFailed: true } } // 读不到 ⇒ 按「还有人在用」处置(退出钩子里不能抛)
|
|
299
392
|
}
|