@tea-agent/loop-agent 0.55.0-next.3 → 0.55.0-next.4
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 +9 -1
- package/dist/build-stamp.json +3 -3
- package/dist/worker/console/chat/browser-automation.js +497 -23
- package/dist/worker/console/chat/browser-cdp.js +145 -0
- package/dist/worker/console/chat/browser-evaluation.js +26 -25
- package/dist/worker/console/chat/browser-exposure.js +7 -6
- package/dist/worker/console/chat/browser-la.js +266 -0
- package/dist/worker/console/chat/browser-policy.js +5 -4
- package/dist/worker/console/chat/browser-preload.js +119 -0
- package/dist/worker/console/chat/browser-preloads/vcp.js +417 -0
- package/dist/worker/console/chat/browser-region-fingerprint.js +36 -0
- package/dist/worker/console/chat/browser-run.js +97 -0
- package/dist/worker/console/chat/browser-screenshot-result.js +2 -2
- package/dist/worker/console/chat/browser-scripts.js +42 -4
- package/dist/worker/console/chat/browser-timeline.js +4 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +72 -9
- package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +70 -0
- package/dist/worker/console/chat/pi-runtime.js +24 -3
- package/dist/worker/console/chat/png-fingerprint.js +189 -0
- package/dist/worker/console/chat/routes.js +30 -38
- package/dist/worker/console/chat/session-store.js +7 -21
- package/dist/worker/console/chat/terminal-sessions.js +1 -1
- package/dist/worker/console/chat/terminal-tools.js +1 -0
- package/dist/worker/console/chat/tool-exposure-catalog.js +2 -2
- package/dist/worker/console/chat/tools.js +2 -0
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C29lbS0T.js → abnfDiagram-N423BO3Z-DorTQneS.js} +1 -1
- package/dist/worker/console/static/assets/{arc--Vi-BzUR.js → arc-C9C1QC-T.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DwdFPJd-.js → architectureDiagram-T3A2C74G-BjUOrgf8.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BFuPq4yu.js → blockDiagram-VBNYF7ZC-BAGMZaHb.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-oKn9EfQa.js → c4Diagram-5PPSVZJV-CySIZtrC.js} +1 -1
- package/dist/worker/console/static/assets/channel-BG_uDZNA.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-TwXtrEhU.js → chunk-2GRJ4B5K-BkmWz795.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-Cc3zFHjT.js → chunk-2Q5K7J3B-CRmOCK3j.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-xJfu4YKo.js → chunk-5RXB4S5H-B8niEWUo.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-VBNdtRqb.js → chunk-5VM5RSS4-Y8foS4t5.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DxhJidW7.js → chunk-6Q2QTUOP-DJF0Bubr.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-P6N3qPX5.js → chunk-GF5L2VYU-EKpddtbq.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-LE21hHhq.js → chunk-JWPE2WC7-CIgPpaGU.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CZmtvzKZ.js → chunk-KBJHAD2P-DYMTSX0m.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-BQrw57-q.js → chunk-RYQCIY6F-4Rc5-0f5.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DSNQHlxO.js → chunk-XXDRQBXY-CEy2M6-D.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-jTs8Eyzt.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-jTs8Eyzt.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Ckm2oC4s.js → cose-bilkent-JH36ORCC-C51nJqVR.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-B7ecDXon.js → cynefinDiagram-MW4NZA55-DPQzOJZA.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-Cx_kCtwr.js → dagre-VZM6K2ZE-CG8IAqCo.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DTqfz-9k.js → diagram-7IWD3JNH-BG3tT1MS.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BH8nNNYl.js → diagram-B4RE2ZJO-DKOhR49M.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-mwUmtiIR.js → diagram-LBJQPF4R--nGLO7eB.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-B6_cW-cc.js → diagram-Q27KOJAE-CNDuz0fc.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-D1sGiHf5.js → diagram-UB23O5K3-BvEiy0I0.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-C07tYieV.js → ebnfDiagram-BXEA7PRR-BvjtUlUv.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-eHwocxI1.js → erDiagram-JOGREHBK-B-r_PRCK.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B1B-mb0t.js → flowDiagram-UKHOOZJN-DlGW_rBu.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-B2fpno6f.js → ganttDiagram-PKOTCBZU-CcJKXiNh.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DcM98HR9.js → gitGraphDiagram-DS77QQ5N-BXWxDYEd.js} +1 -1
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-edHmAaaC.js → infoDiagram-6WML65LV-asY8RPy4.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Df_rsjoZ.js → ishikawaDiagram-WSZJBQD7-6yhDpeCu.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BqK30536.js → journeyDiagram-NVQOT4AX-KybqaztS.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DCvcYw-F.js → kanban-definition-27J2QSJJ-BUdunoPK.js} +1 -1
- package/dist/worker/console/static/assets/{linear-4rMK0UAe.js → linear-BAwJ_AJw.js} +1 -1
- package/dist/worker/console/static/assets/main-CIG4h5Yv.css +1 -0
- package/dist/worker/console/static/assets/{main-CBjwyx0a.js → main-CoWJVNrX.js} +141 -141
- package/dist/worker/console/static/assets/{mermaid.core-CIeuqFlz.js → mermaid.core-BwGdPtCr.js} +4 -4
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-isklXv_u.js → mindmap-definition-FAOFIHXS-wo8SEwby.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DufJ3B32.js → pegDiagram-VL7TDLO6-DeuXnF7o.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-e-dscJOX.js → pieDiagram-7S7Q4E2Y-Hn7SpOAL.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BMXdwlfZ.js → quadrantDiagram-CIZ2JOQS-WZ9z9PP1.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BkLHnA2m.js → railroadDiagram-AXF67PYL-Dl4Y5VeR.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BzXmvm6l.js → requirementDiagram-LRYGKXZP-B-3z0VEC.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BZuur-BM.js → sankeyDiagram-W5VNT64P-D5LDd4et.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DbZxmtRn.js → sequenceDiagram-SI44F4Z6-CeeqbPrw.js} +1 -1
- package/dist/worker/console/static/assets/{sheet-workbook-D_6Enbgn.js → sheet-workbook-BVfUI4fR.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BHbP5ADt.js → sizeCapture-X5ZJPWSS-DdhhZwAv.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-CGNrvQQV.js → stateDiagram-OKZ733FA-DNTAm9ba.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B5Xi7PDb.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BWNaMfHj.js → swimlanes-SLNWSIFB-D8Jdwx7C.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DaLAC9v3.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BhI167N4.js → timeline-definition-Z64GVDOM-BaI43sL9.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BFHqLPNk.js → vennDiagram-T6HMQDX7-D5uEn-T3.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-D-ThxcCm.js → wardleyDiagram-T6FBY63Y-D76Tmp1x.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CeUzoGed.js → xychartDiagram-ELKLHX3M-Bv8QF2pr.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +140 -34
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +6 -0
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +5 -0
- package/docs/architecture/runtime-boundaries.md +5 -0
- package/package.json +3 -3
- package/dist/worker/console/static/assets/channel-o_uspxIc.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BAMhQfS-.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BAMhQfS-.js +0 -1
- package/dist/worker/console/static/assets/main-CGnkpKqw.css +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Oa0mw2RA.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CylkK52a.js +0 -8
|
@@ -6,6 +6,7 @@ import { BrowserBatchError, BROWSER_BATCH_SCHEMA, runBrowserBatch } from "../../
|
|
|
6
6
|
import { BROWSER_SCRIPT_SCHEMA, BrowserScriptError, BrowserScriptStore } from "../../browser-scripts.js";
|
|
7
7
|
import { browserAutomationEnabled } from "../../browser-exposure.js";
|
|
8
8
|
import { sdkExposureForCatalogTool } from "../../tool-exposure-catalog.js";
|
|
9
|
+
import { BROWSER_CANVAS_ID_PATTERN, BROWSER_DRAFT_KEY_PATTERN, BROWSER_DRAFT_REFOCUS_MODES, MAX_BROWSER_DRAFT_KEYS, MAX_BROWSER_IGNORE_HEIGHT, MAX_BROWSER_IGNORE_RECTS, MAX_BROWSER_IGNORE_WIDTH } from "../../browser-automation.js";
|
|
9
10
|
export async function buildBrowserTools(options) {
|
|
10
11
|
const [{ Type }, { defineTool }] = await Promise.all([import("typebox"), import("@earendil-works/pi-coding-agent")]);
|
|
11
12
|
const automation = options.automation;
|
|
@@ -33,6 +34,8 @@ export async function buildBrowserTools(options) {
|
|
|
33
34
|
const execute = async () => {
|
|
34
35
|
try {
|
|
35
36
|
const input = params;
|
|
37
|
+
const draftKeys = name === "browser_press" && input.keys !== undefined;
|
|
38
|
+
const uncertain = name === "browser_run" || name === "browser_script_run";
|
|
36
39
|
const independent = (name === "browser_tabs" && (input.action === "new" || input.action === "list")) || name.startsWith("browser_storage_") || name === "browser_cookies";
|
|
37
40
|
// defineTool's Static comes from Pi's nested typebox 1.3.27, while
|
|
38
41
|
// this file's Static is the root pin 1.3.7. The schemas are
|
|
@@ -40,7 +43,14 @@ export async function buildBrowserTools(options) {
|
|
|
40
43
|
const parsed = params;
|
|
41
44
|
const result = diagnostic
|
|
42
45
|
? await operation(parsed, signal)
|
|
43
|
-
: await automation.run({
|
|
46
|
+
: await automation.run({
|
|
47
|
+
tabId: independent ? undefined : input.tabId ?? selectedTab,
|
|
48
|
+
signal,
|
|
49
|
+
...((draftKeys || uncertain) ? { retainAbortedResult: (value) => {
|
|
50
|
+
const receipt = record(value);
|
|
51
|
+
return (draftKeys && typeof receipt.dispatched === "number" && receipt.dispatched > 0) || receipt.unknownEffects === true;
|
|
52
|
+
} } : {}),
|
|
53
|
+
}, async () => operation(parsed, signal));
|
|
44
54
|
const packageResult = async () => {
|
|
45
55
|
const metadata = record(result);
|
|
46
56
|
const page = record(metadata.page);
|
|
@@ -53,12 +63,26 @@ export async function buildBrowserTools(options) {
|
|
|
53
63
|
if (page.observation !== "omitted" && typeof page.snapshotId === "string")
|
|
54
64
|
details.nextSnapshotId = page.snapshotId;
|
|
55
65
|
const content = [];
|
|
66
|
+
const images = Array.isArray(details.images) ? details.images : [];
|
|
67
|
+
const seesImages = ctx?.model?.input.includes("image") === true;
|
|
56
68
|
if (screenshot) {
|
|
57
|
-
if (
|
|
69
|
+
if (seesImages)
|
|
58
70
|
content.push({ type: "image", data: screenshot.replace(/^data:image\/png;base64,/, ""), mimeType: "image/png" });
|
|
59
71
|
else
|
|
60
72
|
details.imageWarning = "IMAGE_UNSUPPORTED: current model does not declare image input; screenshot evidence was saved but not seen by the model";
|
|
61
73
|
}
|
|
74
|
+
let attached = screenshot && seesImages ? 1 : 0;
|
|
75
|
+
if (images.length > 0 && !seesImages)
|
|
76
|
+
details.imageWarning = "IMAGE_UNSUPPORTED: current model does not declare image input; screenshot evidence was saved but not seen by the model";
|
|
77
|
+
for (const image of images) {
|
|
78
|
+
if (seesImages && attached < 4 && typeof image.data === "string") {
|
|
79
|
+
content.push({ type: "image", data: image.data, mimeType: "image/png" });
|
|
80
|
+
attached += 1;
|
|
81
|
+
}
|
|
82
|
+
delete image.data;
|
|
83
|
+
}
|
|
84
|
+
if (seesImages && images.length + (screenshot ? 1 : 0) > 4)
|
|
85
|
+
details.imageWarning = "IMAGE_LIMIT: only the first 4 images were attached";
|
|
62
86
|
const text = JSON.stringify(details);
|
|
63
87
|
automation.performance?.metric("returnBytes", Buffer.byteLength(text));
|
|
64
88
|
content.unshift({ type: "text", text });
|
|
@@ -82,6 +106,15 @@ export async function buildBrowserTools(options) {
|
|
|
82
106
|
const diagnostics = object({ ...target, after: Type.Optional(Type.Integer({ minimum: 0 })), limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100 })), clear: Type.Optional(Type.Boolean()) });
|
|
83
107
|
const scopedCompletion = { observe: Type.Optional(BROWSER_OBSERVE_SCHEMA) };
|
|
84
108
|
const unscopedCompletion = { observe: Type.Optional(BROWSER_UNSCOPED_OBSERVE_SCHEMA) };
|
|
109
|
+
const region = object({ x: Type.Integer({ minimum: 0 }), y: Type.Integer({ minimum: 0 }), width: Type.Integer({ minimum: 1, maximum: 262_144 }), height: Type.Integer({ minimum: 1, maximum: 262_144 }) });
|
|
110
|
+
const screenshotParams = Object.assign(Type.Union([
|
|
111
|
+
object({ ...target, fullPage: Type.Optional(Type.Boolean()) }),
|
|
112
|
+
object({ tabId: Type.Integer({ minimum: 1 }), region, ignore: Type.Optional(Type.Array(object({ x: Type.Integer({ minimum: 0 }), y: Type.Integer({ minimum: 0 }), width: Type.Integer({ minimum: 1, maximum: MAX_BROWSER_IGNORE_WIDTH }), height: Type.Integer({ minimum: 1, maximum: MAX_BROWSER_IGNORE_HEIGHT }) }), { maxItems: MAX_BROWSER_IGNORE_RECTS })), since: Type.Optional(Type.String({ pattern: "^[0-9a-f]{64}\\.[0-9a-f]{64}$" })), waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 2000 })) }),
|
|
113
|
+
]), { type: "object" });
|
|
114
|
+
const pressParams = Object.assign(Type.Union([
|
|
115
|
+
object({ ...target, ...scopedCompletion, key: Type.String() }),
|
|
116
|
+
object({ tabId: Type.Integer({ minimum: 1 }), focusedCanvasId: Type.String({ pattern: BROWSER_CANVAS_ID_PATTERN }), keys: Type.Array(Type.String({ pattern: BROWSER_DRAFT_KEY_PATTERN }), { minItems: 1, maxItems: MAX_BROWSER_DRAFT_KEYS }), refocus: Type.Optional(Type.Union(BROWSER_DRAFT_REFOCUS_MODES.map((mode) => Type.Literal(mode)))) }),
|
|
117
|
+
]), { type: "object" });
|
|
85
118
|
const pageParams = object({ ...target, ...unscopedCompletion });
|
|
86
119
|
return [
|
|
87
120
|
tool("browser_console", "Read bounded per-tab console/page errors without launching or taking a snapshot. Cursor/gap describe history. Best-effort redaction is not a secret-free guarantee.", diagnostics, (p) => automation.consoleMessages({ ...p, tabId: p.tabId ?? selectedTab }), true),
|
|
@@ -162,7 +195,7 @@ export async function buildBrowserTools(options) {
|
|
|
162
195
|
return p.observe ? automation.closeTab(p.tabId, p.observe) : automation.closeTab(p.tabId);
|
|
163
196
|
}),
|
|
164
197
|
tool("browser_scroll", "Scroll the selected page; observe defaults to auto, or use supported scoped/none completion.", object({ ...target, ...scopedCompletion, direction: Type.Union([Type.Literal("up"), Type.Literal("down")]), amount: Type.Optional(Type.Integer({ minimum: 50, maximum: 3000 })) }), (p) => p.observe ? automation.scroll(p, p.observe) : automation.scroll(p)),
|
|
165
|
-
tool("browser_press", "Press a Playwright
|
|
198
|
+
tool("browser_press", "Press a Playwright key/chord, or batch draft keys (ASCII letters, digits, Space, Backspace, . - / = : , _) with an explicit tabId and focusedCanvasId. The batch never submits or retries. refocus defaults to never; body-once lets the batch refocus the same canvas once before the first key, only when the page has focus on BODY (receipt refocused 0|1). Browser acceptance is not guest receipt: verify the guest content separately.", pressParams, (p) => "keys" in p ? automation.pressDraftKeys(p) : automation.pressKey(p.key, p.observe)),
|
|
166
199
|
tool("browser_dialog", "Accept or dismiss a pending browser dialog. Observation supports auto/full/none; scoped is unavailable.", object({ ...target, ...unscopedCompletion, action: Type.Union([Type.Literal("accept"), Type.Literal("dismiss")]), promptText: Type.Optional(Type.String()) }), (p) => p.observe ? automation.handleDialog(p.action, p.promptText, p.observe) : automation.handleDialog(p.action, p.promptText)),
|
|
167
200
|
tool("browser_wait", "Wait for exactly one text (exact visible text), URL glob, or ref condition; ref requires snapshotId. Optional fixed ms is only a delay, not proof of business success.", object({
|
|
168
201
|
...target, ...scopedCompletion, text: Type.Optional(Type.String()), url: Type.Optional(Type.String()), ref: Type.Optional(ref), snapshotId: Type.Optional(snapshotId),
|
|
@@ -179,8 +212,8 @@ export async function buildBrowserTools(options) {
|
|
|
179
212
|
const { observe, ...condition } = p;
|
|
180
213
|
return observe ? automation.waitUntil(condition, observe) : automation.waitUntil(condition);
|
|
181
214
|
}),
|
|
182
|
-
tool("browser_screenshot", "Capture PNG visual evidence
|
|
183
|
-
tool("browser_eval", "Execute an arbitrary JS expression in the selected page; use an async IIFE for statements.
|
|
215
|
+
tool("browser_screenshot", "Capture PNG visual evidence. For a region use an explicit tabId and viewport CSS pixels; pass the prior fingerprint as since to omit unchanged images, optionally waiting up to 2 seconds. Optional ignore (up to 2 caret-sized rectangles, region-relative) excludes pixels from the fingerprint only, never from the image; unchanged then says nothing about masked pixels. Regions do not create ref snapshots. Images are saved outside the repo.", screenshotParams, (p) => "region" in p ? automation.screenshotRegion(p) : automation.screenshot(p)),
|
|
216
|
+
tool("browser_eval", "Execute an arbitrary JS expression in the selected page or a named child frame; use an async IIFE for statements. Oversized JSON is saved to a file. Node, Playwright and CDP belong in browser_run. Timeout or cancel leaves the page busy until the script promise settles. Page JS cannot read httpOnly cookies. Successful eval returns its execution tab and a new generation; stable observed refs need live identity validation, and newly created controls require observation.", object({ ...target, expression: Type.String({ minLength: 1, maxLength: 100000 }), timeoutMs, frame: Type.Optional(Type.String({ minLength: 1, maxLength: 500 })) }), (p) => automation.evaluate(p.expression, p)),
|
|
184
217
|
tool("browser_cookies", "Read context cookies including httpOnly. Values omitted by default; includeValues explicitly exposes credentials to this conversation.", object({ includeValues: Type.Optional(Type.Boolean()) }), (p) => automation.cookies(p.includeValues)),
|
|
185
218
|
tool("browser_storage_export", "Export cookies/localStorage to a private app-data JSON file. Returns path/counts, not values. No sessionStorage/IndexedDB/OPFS/passkeys. This does not read another Chrome profile or automatically load a frontend-test DAG.", object({}), () => automation.exportStorage()),
|
|
186
219
|
tool("browser_storage_import", "Merge cookies/localStorage from a JSON file in the browser storage directory (export provides the directory). Existing unlisted keys survive. Values are not echoed; current pages may need reload. No IndexedDB/sessionStorage import.", object({ path: Type.String(), mode: Type.Literal("merge") }), (p) => automation.importStorage(p.path, p.mode)),
|
|
@@ -192,14 +225,37 @@ export async function buildBrowserTools(options) {
|
|
|
192
225
|
}),
|
|
193
226
|
tool("browser_pick", "Ask the user to select one accessible control in the external controlled window; set multiple to select up to 16 controls with Ctrl/Cmd-click and Enter. Escape, timeout, empty commit and unsupported controls fail explicitly; unavailable in background mode. timeoutMs upper bound is relaxed to 300s so humans have time to read the overlay before committing.", object({ ...target, message: Type.String({ minLength: 1, maxLength: 500 }), timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 300_000 })), multiple: Type.Optional(Type.Boolean()), maxItems: Type.Optional(Type.Integer({ minimum: 1, maximum: 16 })) }), (p) => automation.pick(p)),
|
|
194
227
|
...(automationEnabled ? [
|
|
195
|
-
tool("browser_batch", "Preflight a strict 1-12
|
|
228
|
+
tool("browser_batch", "Preflight a strict 1-12 semantic-step itinerary before any effects; then execute on one tab. Use {op:'find',text:'Name',role:'textbox',saveAs:'name'} then {op:'act',type:'fill',target:'name',value:'Ada'}. Re-find after actions. Saved targets require one exact complete match in a declared scope. Opt into per-step collect:true for bounded content/find/page or screenshot artifact metadata with individual sources. Per-step verify:{text|url|ref,...} uses explicit conditions; failure skips later effects. Verification proves current state, not causal freshness. Collections <=8 KiB, total JSON <=32 KiB, acquisition is not bounded. Failures/cancellation retain completed evidence. unknownEffects means inspect fresh business state before retrying; references require rediscovery after cancellation. JavaScript and CDP belong in browser_run. There is no rollback.", BROWSER_BATCH_SCHEMA, (p, signal) => runBrowserBatch(automation, p, signal)),
|
|
229
|
+
tool("browser_cdp", "Send one raw CDP command to the page session, or to the browser when target is browser. No method allowlist. events.subscribe/unsubscribe records matching events; read them back with after and limit. A method refreshes the snapshot generation. Event-only reads do not. Oversized results and large binary fields are saved to files.", object({
|
|
230
|
+
...target,
|
|
231
|
+
method: Type.Optional(Type.String({ minLength: 1, maxLength: 200 })),
|
|
232
|
+
params: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
233
|
+
target: Type.Optional(Type.Union([Type.Literal("page"), Type.Literal("browser")])),
|
|
234
|
+
events: Type.Optional(object({
|
|
235
|
+
subscribe: Type.Optional(Type.Array(Type.String())),
|
|
236
|
+
unsubscribe: Type.Optional(Type.Array(Type.String())),
|
|
237
|
+
after: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
238
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500 })),
|
|
239
|
+
})),
|
|
240
|
+
}), (p) => automation.cdp(p)),
|
|
241
|
+
tool("browser_run", "Run an async function body in the Console process. ctx has page, context, cdp, la, args, log, artifact and signal. The runtime cannot preempt an in-flight Playwright call; timeout and cancel return unknownEffects. Coordinates for la are canvas guest pixels. Oversized return values are saved to files.", object({
|
|
242
|
+
...target,
|
|
243
|
+
code: Type.String({ minLength: 1, maxLength: 200_000 }),
|
|
244
|
+
args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
245
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 600_000 })),
|
|
246
|
+
}), (p, signal) => automation.runCode({ code: p.code, args: plainArgs(p.args), timeoutMs: p.timeoutMs }, signal)),
|
|
196
247
|
tool("browser_script_list", "List reusable browser scripts in the current project's .harness/browser-scripts directory.", object({}), async () => ({ scripts: await scripts().list() })),
|
|
197
|
-
tool("browser_script_save", "Explicitly save a reusable
|
|
198
|
-
tool("browser_script_run", "Run a saved project browser script
|
|
248
|
+
tool("browser_script_save", "Explicitly save a reusable browser script. Semantic steps reject credentials, JavaScript, snapshot ids, and existing names. kind:code saves a browser_run body with optional args schema. Does not record prior tool arguments automatically.", object({ script: BROWSER_SCRIPT_SCHEMA }), (p) => scripts().save(p.script)),
|
|
249
|
+
tool("browser_script_run", "Run a saved project browser script. Semantic scripts rediscover elements. kind:code runs through browser_run and accepts args, tabId and timeoutMs. Missing scripts and invalid files fail closed. Timeout or cancel can leave the page busy until the script promise settles.", object({
|
|
250
|
+
...target,
|
|
251
|
+
name: Type.String({ minLength: 1, maxLength: 63 }),
|
|
252
|
+
args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
253
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 600_000 })),
|
|
254
|
+
}), (p, signal) => scripts().run(p.name, automation, signal, plainArgs(p.args), p.timeoutMs)),
|
|
199
255
|
] : []),
|
|
200
256
|
...(options.onDiscover ? [tool("browserCapabilities", automationEnabled
|
|
201
257
|
? "Diagnostics, advanced, and automation browser tools are already loaded. This does not browse or run page actions. It only activates a named group for the next response when browser exposure is progressive."
|
|
202
|
-
: "Diagnostics and advanced browser tools are already loaded. Browser automation
|
|
258
|
+
: "Diagnostics and advanced browser tools are already loaded. Browser automation was disabled by CONSOLE_CHAT_BROWSER_AUTOMATION=0. This does not browse, run page actions, or activate automation.", object({ target: Type.Optional(Type.String({ maxLength: 80 })) }), (p) => options.onDiscover(p.target), true)] : []),
|
|
203
259
|
];
|
|
204
260
|
function scripts() {
|
|
205
261
|
if (!options.workspaceRoot)
|
|
@@ -210,3 +266,10 @@ export async function buildBrowserTools(options) {
|
|
|
210
266
|
function record(value) {
|
|
211
267
|
return value !== null && typeof value === "object" ? value : { value };
|
|
212
268
|
}
|
|
269
|
+
function plainArgs(value) {
|
|
270
|
+
if (value === undefined)
|
|
271
|
+
return undefined;
|
|
272
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
273
|
+
throw Object.assign(new Error("args must be a plain object"), { code: "INVALID_SCRIPT_ARGS" });
|
|
274
|
+
return value;
|
|
275
|
+
}
|
|
@@ -4,9 +4,50 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { access, mkdir, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import path from "node:path";
|
|
7
|
+
import { extractAssistantText } from "../assistant-content.js";
|
|
7
8
|
import { createConsoleShellTools } from "./shell-tools.js";
|
|
8
9
|
import { createConsoleGrepTool, createConsoleWriteTool } from "./file-tools.js";
|
|
9
10
|
import { getConsoleProxyEnvironment } from "../../network-proxy-runtime.js";
|
|
11
|
+
function resolveAssistantForkEntry(branch, anchor) {
|
|
12
|
+
const selected = anchor.messages.find(message => message.id === anchor.messageId);
|
|
13
|
+
const unmapped = () => new Error("FORK_MESSAGE_UNMAPPED");
|
|
14
|
+
if (!selected || selected.role !== "assistant" || selected.kind)
|
|
15
|
+
throw unmapped();
|
|
16
|
+
if (selected.piEntryId) {
|
|
17
|
+
const entry = branch.find(item => item.id === selected.piEntryId);
|
|
18
|
+
if (entry?.type !== "message" || entry.message.role !== "assistant")
|
|
19
|
+
throw unmapped();
|
|
20
|
+
return entry.id;
|
|
21
|
+
}
|
|
22
|
+
if (selected.interrupted)
|
|
23
|
+
throw unmapped();
|
|
24
|
+
// A historical record without an SDK ID can be matched only when the
|
|
25
|
+
// sequences agree through the anchor and the selected reply occurs once.
|
|
26
|
+
const visible = anchor.messages.filter(message => message.role === "user" || (message.role === "assistant" && !message.kind));
|
|
27
|
+
const entries = branch.flatMap(entry => {
|
|
28
|
+
if (entry.type !== "message")
|
|
29
|
+
return [];
|
|
30
|
+
const message = entry.message;
|
|
31
|
+
if (message.role === "assistant" && message.stopReason !== "error") {
|
|
32
|
+
return [{ id: entry.id, role: message.role, text: extractAssistantText(message) }];
|
|
33
|
+
}
|
|
34
|
+
if (message.role !== "user")
|
|
35
|
+
return [];
|
|
36
|
+
const text = typeof message.content === "string" ? message.content :
|
|
37
|
+
message.content.flatMap(block => block.type === "text" ? [block.text] : []).join("");
|
|
38
|
+
return [{ id: entry.id, role: message.role, text }];
|
|
39
|
+
});
|
|
40
|
+
const selectedIndex = visible.indexOf(selected);
|
|
41
|
+
const prefix = visible.slice(0, selectedIndex + 1);
|
|
42
|
+
if (prefix.some((message, index) => message.role !== entries[index]?.role ||
|
|
43
|
+
message.text !== entries[index]?.text ||
|
|
44
|
+
(message.piEntryId !== undefined && message.piEntryId !== entries[index]?.id)))
|
|
45
|
+
throw unmapped();
|
|
46
|
+
const matches = entries.filter(entry => entry.role === "assistant" && entry.text === selected.text);
|
|
47
|
+
if (matches.length !== 1)
|
|
48
|
+
throw unmapped();
|
|
49
|
+
return matches[0].id;
|
|
50
|
+
}
|
|
10
51
|
export async function safeGetAgentDir(bindings) {
|
|
11
52
|
try {
|
|
12
53
|
return await bindings.getAgentDir();
|
|
@@ -229,6 +270,35 @@ export function createDefaultPiSdkBindings() {
|
|
|
229
270
|
},
|
|
230
271
|
forkSessionManager: async (opts) => {
|
|
231
272
|
const sdk = (await loadSdk());
|
|
273
|
+
if (opts.assistantAnchor) {
|
|
274
|
+
await access(opts.sourcePath).catch(() => { throw new Error("FORK_MESSAGE_UNMAPPED"); });
|
|
275
|
+
const source = opts.activeSource ?? sdk.SessionManager.open(opts.sourcePath);
|
|
276
|
+
const entryId = resolveAssistantForkEntry(source.getBranch(), opts.assistantAnchor);
|
|
277
|
+
const timestamp = new Date().toISOString();
|
|
278
|
+
const targetPath = path.join(opts.targetSessionDir, `${timestamp.replace(/[:.]/g, "-")}_${opts.targetSessionId}.jsonl`);
|
|
279
|
+
const header = {
|
|
280
|
+
type: "session",
|
|
281
|
+
version: sdk.CURRENT_SESSION_VERSION,
|
|
282
|
+
id: opts.targetSessionId,
|
|
283
|
+
timestamp,
|
|
284
|
+
cwd: opts.targetCwd,
|
|
285
|
+
parentSession: path.resolve(opts.sourcePath),
|
|
286
|
+
};
|
|
287
|
+
// Pi forkFrom copies the entire tree. Persist the selected path with
|
|
288
|
+
// its entry IDs intact so copied Console messages remain anchors.
|
|
289
|
+
const lines = [header, ...source.getBranch(entryId)].map(entry => JSON.stringify(entry)).join("\n");
|
|
290
|
+
await mkdir(opts.targetSessionDir, { recursive: true, mode: 0o700 });
|
|
291
|
+
try {
|
|
292
|
+
await writeFile(targetPath, `${lines}\n`, { flag: "wx", mode: 0o600 });
|
|
293
|
+
return sdk.SessionManager.open(targetPath);
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
if (error.code !== "EEXIST") {
|
|
297
|
+
await rm(targetPath, { force: true }).catch(() => undefined);
|
|
298
|
+
}
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
232
302
|
return sdk.SessionManager.forkFrom(opts.sourcePath, opts.targetCwd, opts.targetSessionDir, { id: opts.targetSessionId });
|
|
233
303
|
},
|
|
234
304
|
openSessionManager: async (opts) => {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
* `createDefaultPiSdkBindings()`.
|
|
27
27
|
*/
|
|
28
28
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
29
|
-
import { stat } from "node:fs/promises";
|
|
29
|
+
import { rm, stat } from "node:fs/promises";
|
|
30
30
|
import path from "node:path";
|
|
31
31
|
import { projectExpandedSkillMessage, projectFailedSkillMessage, projectSkillReadArgs } from "./pi-runtime/skill-presentation.js";
|
|
32
32
|
import { takeSkillExpansionError } from "./pi-runtime/extension-bindings.js";
|
|
@@ -1648,6 +1648,7 @@ export class ConsolePiRuntime {
|
|
|
1648
1648
|
ownerSessionId: sessionId,
|
|
1649
1649
|
registry: this.options.terminalRegistry,
|
|
1650
1650
|
defaultCwd: this.options.cwd,
|
|
1651
|
+
environment: () => this.browserAutomation.shellEnvironment(),
|
|
1651
1652
|
}).catch((error) => {
|
|
1652
1653
|
process.stderr.write(`[console] chat terminal-tools build failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1653
1654
|
return [];
|
|
@@ -1855,7 +1856,20 @@ export class ConsolePiRuntime {
|
|
|
1855
1856
|
targetCwd: this.options.cwd,
|
|
1856
1857
|
targetSessionDir: this.options.sessionDir,
|
|
1857
1858
|
targetSessionId: sessionId,
|
|
1859
|
+
...(init.assistantAnchor ? { assistantAnchor: init.assistantAnchor } : {}),
|
|
1860
|
+
activeSource: init.sourceSessionId ? this.sessionManagers.get(init.sourceSessionId) : undefined,
|
|
1858
1861
|
});
|
|
1862
|
+
try {
|
|
1863
|
+
return await this.finishForkSession(sessionId, init, sessionMode, sessionManager);
|
|
1864
|
+
}
|
|
1865
|
+
catch (error) {
|
|
1866
|
+
const sessionFile = sessionManager.getSessionFile?.();
|
|
1867
|
+
if (sessionFile)
|
|
1868
|
+
await rm(sessionFile, { force: true }).catch(() => undefined);
|
|
1869
|
+
throw error;
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
async finishForkSession(sessionId, init, sessionMode, sessionManager) {
|
|
1859
1873
|
if (this.disposedSessions.has(sessionId))
|
|
1860
1874
|
throw new Error(`chat session fork aborted: ${sessionId}`);
|
|
1861
1875
|
if (init.throughUserMessageIndex !== undefined) {
|
|
@@ -3353,8 +3367,15 @@ export class ConsolePiRuntime {
|
|
|
3353
3367
|
: { outputTokens: usage.outputTokens }),
|
|
3354
3368
|
};
|
|
3355
3369
|
partialAssistant = undefined;
|
|
3356
|
-
if (!options?.signal?.aborted)
|
|
3357
|
-
|
|
3370
|
+
if (!options?.signal?.aborted && event.type === "message_end") {
|
|
3371
|
+
const manager = this.sessionManagers.get(sessionId);
|
|
3372
|
+
const message = event.message;
|
|
3373
|
+
const piEntryId = Promise.resolve().then(() => {
|
|
3374
|
+
const entry = manager?.getLeafEntry?.();
|
|
3375
|
+
return entry?.type === "message" && entry.message === message ? entry.id : undefined;
|
|
3376
|
+
});
|
|
3377
|
+
onEvent({ ...mapped, piEntryId, ...(timing ? { timing } : {}) });
|
|
3378
|
+
}
|
|
3358
3379
|
if (!options?.signal?.aborted && mapped.stopReason === "length") {
|
|
3359
3380
|
onEvent({
|
|
3360
3381
|
type: "turn_max_tokens",
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/** Pixel fingerprint of a Chromium PNG with optional ignored rectangles; the image itself is never modified. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { deflateSync, inflateSync } from "node:zlib";
|
|
4
|
+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
5
|
+
const CHANNELS = { 0: 1, 2: 3, 4: 2, 6: 4 };
|
|
6
|
+
export class PngFingerprintError extends Error {
|
|
7
|
+
}
|
|
8
|
+
/** Hash decoded pixels with the `ignore` rectangles zeroed. */
|
|
9
|
+
export function pngPixelFingerprint(png, ignore, expected) {
|
|
10
|
+
if (png.length < 33 || !png.subarray(0, 8).equals(PNG_SIGNATURE))
|
|
11
|
+
throw new PngFingerprintError("not a PNG image");
|
|
12
|
+
let width = 0, height = 0, channels = 0;
|
|
13
|
+
const data = [];
|
|
14
|
+
for (let offset = 8; offset + 12 <= png.length;) {
|
|
15
|
+
const length = png.readUInt32BE(offset);
|
|
16
|
+
const type = png.toString("latin1", offset + 4, offset + 8);
|
|
17
|
+
const body = png.subarray(offset + 8, offset + 8 + length);
|
|
18
|
+
if (body.length !== length)
|
|
19
|
+
throw new PngFingerprintError("truncated PNG chunk");
|
|
20
|
+
if (type === "IHDR") {
|
|
21
|
+
width = body.readUInt32BE(0);
|
|
22
|
+
height = body.readUInt32BE(4);
|
|
23
|
+
channels = CHANNELS[body[9]] ?? 0;
|
|
24
|
+
if (body[8] !== 8 || channels === 0 || body[12] !== 0)
|
|
25
|
+
throw new PngFingerprintError("unsupported PNG format");
|
|
26
|
+
}
|
|
27
|
+
else if (type === "IDAT")
|
|
28
|
+
data.push(body);
|
|
29
|
+
else if (type === "IEND")
|
|
30
|
+
break;
|
|
31
|
+
offset += 12 + length;
|
|
32
|
+
}
|
|
33
|
+
if (width !== expected.width || height !== expected.height)
|
|
34
|
+
throw new PngFingerprintError("image size does not match the region");
|
|
35
|
+
const stride = width * channels;
|
|
36
|
+
const raw = inflateSync(Buffer.concat(data));
|
|
37
|
+
if (raw.length !== (stride + 1) * height)
|
|
38
|
+
throw new PngFingerprintError("unexpected PNG data length");
|
|
39
|
+
const pixels = Buffer.alloc(stride * height);
|
|
40
|
+
for (let row = 0; row < height; row += 1) {
|
|
41
|
+
const filter = raw[row * (stride + 1)];
|
|
42
|
+
const source = row * (stride + 1) + 1;
|
|
43
|
+
const target = row * stride;
|
|
44
|
+
for (let i = 0; i < stride; i += 1) {
|
|
45
|
+
const left = i >= channels ? pixels[target + i - channels] : 0;
|
|
46
|
+
const up = row > 0 ? pixels[target - stride + i] : 0;
|
|
47
|
+
const upLeft = row > 0 && i >= channels ? pixels[target - stride + i - channels] : 0;
|
|
48
|
+
let predictor;
|
|
49
|
+
switch (filter) {
|
|
50
|
+
case 0:
|
|
51
|
+
predictor = 0;
|
|
52
|
+
break;
|
|
53
|
+
case 1:
|
|
54
|
+
predictor = left;
|
|
55
|
+
break;
|
|
56
|
+
case 2:
|
|
57
|
+
predictor = up;
|
|
58
|
+
break;
|
|
59
|
+
case 3:
|
|
60
|
+
predictor = (left + up) >> 1;
|
|
61
|
+
break;
|
|
62
|
+
case 4: {
|
|
63
|
+
const p = left + up - upLeft;
|
|
64
|
+
const pa = Math.abs(p - left), pb = Math.abs(p - up), pc = Math.abs(p - upLeft);
|
|
65
|
+
predictor = pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft;
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
default: throw new PngFingerprintError("unsupported PNG filter");
|
|
69
|
+
}
|
|
70
|
+
pixels[target + i] = (raw[source + i] + predictor) & 0xff;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
for (const rect of ignore) {
|
|
74
|
+
for (let y = rect.y; y < rect.y + rect.height; y += 1)
|
|
75
|
+
pixels.fill(0, y * stride + rect.x * channels, y * stride + (rect.x + rect.width) * channels);
|
|
76
|
+
}
|
|
77
|
+
return createHash("sha256").update(`${width}x${height}x${channels}:`).update(pixels).digest("hex");
|
|
78
|
+
}
|
|
79
|
+
/** Decode an 8-bit non-interlaced PNG. Callers that need a size check compare the result. */
|
|
80
|
+
export function decodePng(png) {
|
|
81
|
+
if (png.length < 33 || !png.subarray(0, 8).equals(PNG_SIGNATURE))
|
|
82
|
+
throw new PngFingerprintError("not a PNG image");
|
|
83
|
+
let width = 0, height = 0, channels = 0;
|
|
84
|
+
const data = [];
|
|
85
|
+
for (let offset = 8; offset + 12 <= png.length;) {
|
|
86
|
+
const length = png.readUInt32BE(offset);
|
|
87
|
+
const type = png.toString("latin1", offset + 4, offset + 8);
|
|
88
|
+
const body = png.subarray(offset + 8, offset + 8 + length);
|
|
89
|
+
if (body.length !== length)
|
|
90
|
+
throw new PngFingerprintError("truncated PNG chunk");
|
|
91
|
+
if (type === "IHDR") {
|
|
92
|
+
width = body.readUInt32BE(0);
|
|
93
|
+
height = body.readUInt32BE(4);
|
|
94
|
+
channels = CHANNELS[body[9]] ?? 0;
|
|
95
|
+
if (body[8] !== 8 || channels === 0 || body[12] !== 0)
|
|
96
|
+
throw new PngFingerprintError("unsupported PNG format");
|
|
97
|
+
}
|
|
98
|
+
else if (type === "IDAT")
|
|
99
|
+
data.push(body);
|
|
100
|
+
else if (type === "IEND")
|
|
101
|
+
break;
|
|
102
|
+
offset += 12 + length;
|
|
103
|
+
}
|
|
104
|
+
const stride = width * channels;
|
|
105
|
+
const raw = inflateSync(Buffer.concat(data));
|
|
106
|
+
if (raw.length !== (stride + 1) * height)
|
|
107
|
+
throw new PngFingerprintError("unexpected PNG data length");
|
|
108
|
+
const pixels = Buffer.alloc(stride * height);
|
|
109
|
+
for (let row = 0; row < height; row += 1) {
|
|
110
|
+
const filter = raw[row * (stride + 1)];
|
|
111
|
+
const source = row * (stride + 1) + 1;
|
|
112
|
+
const target = row * stride;
|
|
113
|
+
for (let i = 0; i < stride; i += 1) {
|
|
114
|
+
const left = i >= channels ? pixels[target + i - channels] : 0;
|
|
115
|
+
const up = row > 0 ? pixels[target - stride + i] : 0;
|
|
116
|
+
const upLeft = row > 0 && i >= channels ? pixels[target - stride + i - channels] : 0;
|
|
117
|
+
let predictor = 0;
|
|
118
|
+
switch (filter) {
|
|
119
|
+
case 0:
|
|
120
|
+
predictor = 0;
|
|
121
|
+
break;
|
|
122
|
+
case 1:
|
|
123
|
+
predictor = left;
|
|
124
|
+
break;
|
|
125
|
+
case 2:
|
|
126
|
+
predictor = up;
|
|
127
|
+
break;
|
|
128
|
+
case 3:
|
|
129
|
+
predictor = (left + up) >> 1;
|
|
130
|
+
break;
|
|
131
|
+
case 4: {
|
|
132
|
+
const p = left + up - upLeft;
|
|
133
|
+
const pa = Math.abs(p - left), pb = Math.abs(p - up), pc = Math.abs(p - upLeft);
|
|
134
|
+
predictor = pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft;
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
default: throw new PngFingerprintError("unsupported PNG filter");
|
|
138
|
+
}
|
|
139
|
+
pixels[target + i] = (raw[source + i] + predictor) & 0xff;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return { width, height, channels, pixels };
|
|
143
|
+
}
|
|
144
|
+
export function scalePngNearest(decoded, width, height) {
|
|
145
|
+
const pixels = Buffer.alloc(width * height * decoded.channels);
|
|
146
|
+
for (let y = 0; y < height; y += 1) {
|
|
147
|
+
const sourceY = Math.min(decoded.height - 1, Math.floor(y * decoded.height / height));
|
|
148
|
+
for (let x = 0; x < width; x += 1) {
|
|
149
|
+
const sourceX = Math.min(decoded.width - 1, Math.floor(x * decoded.width / width));
|
|
150
|
+
const from = (sourceY * decoded.width + sourceX) * decoded.channels;
|
|
151
|
+
const to = (y * width + x) * decoded.channels;
|
|
152
|
+
decoded.pixels.copy(pixels, to, from, from + decoded.channels);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { width, height, channels: decoded.channels, pixels };
|
|
156
|
+
}
|
|
157
|
+
export function encodePng(decoded) {
|
|
158
|
+
const stride = decoded.width * decoded.channels;
|
|
159
|
+
const raw = Buffer.alloc((stride + 1) * decoded.height);
|
|
160
|
+
for (let row = 0; row < decoded.height; row += 1) {
|
|
161
|
+
raw[row * (stride + 1)] = 0;
|
|
162
|
+
decoded.pixels.copy(raw, row * (stride + 1) + 1, row * stride, row * stride + stride);
|
|
163
|
+
}
|
|
164
|
+
const compressed = deflateSync(raw);
|
|
165
|
+
const ihdr = Buffer.alloc(13);
|
|
166
|
+
ihdr.writeUInt32BE(decoded.width, 0);
|
|
167
|
+
ihdr.writeUInt32BE(decoded.height, 4);
|
|
168
|
+
ihdr[8] = 8;
|
|
169
|
+
ihdr[9] = decoded.channels === 4 ? 6 : decoded.channels === 3 ? 2 : decoded.channels === 2 ? 4 : 0;
|
|
170
|
+
const chunks = [chunk("IHDR", ihdr), chunk("IDAT", compressed), chunk("IEND", Buffer.alloc(0))];
|
|
171
|
+
return Buffer.concat([PNG_SIGNATURE, ...chunks]);
|
|
172
|
+
}
|
|
173
|
+
function chunk(type, body) {
|
|
174
|
+
const out = Buffer.alloc(12 + body.length);
|
|
175
|
+
out.writeUInt32BE(body.length, 0);
|
|
176
|
+
out.write(type, 4, "latin1");
|
|
177
|
+
body.copy(out, 8);
|
|
178
|
+
out.writeUInt32BE(crc32(out.subarray(4, 8 + body.length)), 8 + body.length);
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
function crc32(buffer) {
|
|
182
|
+
let crc = 0xffffffff;
|
|
183
|
+
for (const byte of buffer) {
|
|
184
|
+
crc ^= byte;
|
|
185
|
+
for (let bit = 0; bit < 8; bit += 1)
|
|
186
|
+
crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
|
|
187
|
+
}
|
|
188
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
189
|
+
}
|
|
@@ -831,10 +831,12 @@ export async function handleForkChatSession(req, res, deps, sourceSessionId) {
|
|
|
831
831
|
});
|
|
832
832
|
return;
|
|
833
833
|
}
|
|
834
|
-
|
|
834
|
+
const sourceBusy = () => Boolean(deps.events.getActiveTurn(sourceSessionId)) ||
|
|
835
|
+
Object.values(deps.runtime.getSessionBusyFacts?.(sourceSessionId) ?? {}).some(value => value === true);
|
|
836
|
+
if (sourceBusy()) {
|
|
835
837
|
sendJson(res, 409, {
|
|
836
838
|
ok: false,
|
|
837
|
-
error: { code: "TURN_ACTIVE", message: "
|
|
839
|
+
error: { code: "TURN_ACTIVE", message: "等待当前回复结束后重试。" },
|
|
838
840
|
});
|
|
839
841
|
return;
|
|
840
842
|
}
|
|
@@ -853,38 +855,24 @@ export async function handleForkChatSession(req, res, deps, sourceSessionId) {
|
|
|
853
855
|
let forkPersisted = false;
|
|
854
856
|
try {
|
|
855
857
|
const body = await readJsonBody(req);
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
? source.messages.findIndex((message) => message.id === throughMessageId)
|
|
864
|
-
: -1;
|
|
865
|
-
if (throughMessageId && anchorIndex < 0) {
|
|
858
|
+
if (sourceBusy())
|
|
859
|
+
throw new Error("TURN_ACTIVE");
|
|
860
|
+
const requestedAnchor = Object.hasOwn(body, "sourceMessageId") ? body.sourceMessageId : body.throughMessageId;
|
|
861
|
+
const throughMessageId = typeof requestedAnchor === "string" ? requestedAnchor.trim() : undefined;
|
|
862
|
+
const anchorIndex = throughMessageId ? source.messages.findIndex(message => message.id === throughMessageId) : -1;
|
|
863
|
+
const anchor = source.messages[anchorIndex];
|
|
864
|
+
if (requestedAnchor !== undefined && (!anchor || (anchor.role !== "user" && anchor.role !== "assistant"))) {
|
|
866
865
|
throw new Error("FORK_MESSAGE_NOT_FOUND");
|
|
867
866
|
}
|
|
868
|
-
const throughUserMessageIndex =
|
|
869
|
-
? ((
|
|
870
|
-
const boundary = anchorIndex >= 0 && source.messages[anchorIndex]?.role === "assistant"
|
|
871
|
-
? (() => {
|
|
872
|
-
let index = anchorIndex;
|
|
873
|
-
while (index >= 0 && source.messages[index]?.role !== "user") {
|
|
874
|
-
index -= 1;
|
|
875
|
-
}
|
|
876
|
-
return index;
|
|
877
|
-
})()
|
|
878
|
-
: anchorIndex;
|
|
879
|
-
if (boundary < 0)
|
|
880
|
-
throw new Error("FORK_MESSAGE_TURN_USER_NOT_FOUND");
|
|
881
|
-
return source.messages
|
|
882
|
-
.slice(0, boundary + 1)
|
|
883
|
-
.filter((message) => message.role === "user").length - 1;
|
|
884
|
-
})()
|
|
867
|
+
const throughUserMessageIndex = anchor?.role === "user"
|
|
868
|
+
? source.messages.slice(0, anchorIndex).filter(message => message.role === "user").length
|
|
885
869
|
: undefined;
|
|
886
870
|
const handle = await deps.runtime.forkSession({
|
|
871
|
+
sourceSessionId,
|
|
887
872
|
sourceSessionFile: source.sessionFile ?? "",
|
|
873
|
+
...(anchor?.role === "assistant" ? {
|
|
874
|
+
assistantAnchor: { messageId: anchor.id, messages: source.messages },
|
|
875
|
+
} : {}),
|
|
888
876
|
...(source.systemPromptSuffix ? { systemPromptSuffix: source.systemPromptSuffix } : {}),
|
|
889
877
|
sessionMode: source.sessionMode,
|
|
890
878
|
...(source.modelProvider && source.modelId
|
|
@@ -895,6 +883,8 @@ export async function handleForkChatSession(req, res, deps, sourceSessionId) {
|
|
|
895
883
|
: {}),
|
|
896
884
|
});
|
|
897
885
|
forkedHandle = handle;
|
|
886
|
+
if (sourceBusy())
|
|
887
|
+
throw new Error("TURN_ACTIVE");
|
|
898
888
|
await deps.store.forkFrom({
|
|
899
889
|
sourceSessionId,
|
|
900
890
|
targetSessionId: handle.sessionId,
|
|
@@ -910,7 +900,7 @@ export async function handleForkChatSession(req, res, deps, sourceSessionId) {
|
|
|
910
900
|
targetSessionId: handle.sessionId,
|
|
911
901
|
targetTurnId: `${handle.sessionId}:fork`,
|
|
912
902
|
});
|
|
913
|
-
await deps.operationLinker.recoverSession(handle.sessionId);
|
|
903
|
+
await deps.operationLinker.recoverSession(handle.sessionId).catch(() => undefined);
|
|
914
904
|
sendJson(res, 201, {
|
|
915
905
|
ok: true,
|
|
916
906
|
sessionId: handle.sessionId,
|
|
@@ -924,18 +914,20 @@ export async function handleForkChatSession(req, res, deps, sourceSessionId) {
|
|
|
924
914
|
}
|
|
925
915
|
catch (error) {
|
|
926
916
|
if (forkedHandle && !forkPersisted) {
|
|
927
|
-
await deps.runtime.dispose(forkedHandle.sessionId);
|
|
917
|
+
await deps.runtime.dispose(forkedHandle.sessionId).catch(() => undefined);
|
|
928
918
|
await deps.store
|
|
929
919
|
.discardUnownedSession(forkedHandle.sessionId, forkedHandle.sessionFile)
|
|
930
920
|
.catch(() => undefined);
|
|
931
921
|
}
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
922
|
+
const reason = error instanceof Error ? error.message : "";
|
|
923
|
+
const failure = reason === "FORK_MESSAGE_NOT_FOUND"
|
|
924
|
+
? { code: reason, message: "找不到这条已保存的消息。请重新打开会话后选择一条回复。" }
|
|
925
|
+
: reason === "FORK_MESSAGE_UNMAPPED" || reason === "FORK_MESSAGE_ENTRY_NOT_FOUND"
|
|
926
|
+
? { code: "FORK_MESSAGE_UNMAPPED", message: "无法定位这条回复的模型上下文。请选择其他已保存的回复。" }
|
|
927
|
+
: reason === "TURN_ACTIVE"
|
|
928
|
+
? { code: reason, message: "等待当前回复结束后重试。" }
|
|
929
|
+
: { code: "SESSION_FORK_FAILED", message: "未能创建分支。请重试。" };
|
|
930
|
+
sendJson(res, reason === "FORK_MESSAGE_NOT_FOUND" ? 404 : 409, { ok: false, error: failure });
|
|
939
931
|
}
|
|
940
932
|
}
|
|
941
933
|
export async function handleBranchChatSession(req, res, deps, sessionId) {
|