@xingular/harness 1.3.1-unstable.2 → 1.3.1-unstable.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 +82 -0
- package/README.md +1 -1
- package/dist/cli.js +3680 -1947
- package/dist/sdk/cli.js +2 -0
- package/dist/sdk/commands/registry.d.ts +15 -0
- package/dist/sdk/commands/registry.js +2 -0
- package/dist/sdk/computer/screenshot.d.ts +32 -0
- package/dist/sdk/computer/screenshot.js +35 -0
- package/dist/sdk/context/attribution.d.ts +18 -0
- package/dist/sdk/context/attribution.js +295 -0
- package/dist/sdk/context/types.d.ts +94 -0
- package/dist/sdk/context/types.js +10 -0
- package/dist/sdk/index.d.ts +2 -1
- package/dist/sdk/index.js +2 -1
- package/dist/sdk/plugins/builtin.js +1 -0
- package/dist/sdk/prompt/compile.d.ts +42 -2
- package/dist/sdk/prompt/compile.js +87 -15
- package/dist/sdk/remote/addresses.d.ts +19 -0
- package/dist/sdk/remote/addresses.js +52 -0
- package/dist/sdk/remote/pairing.d.ts +59 -0
- package/dist/sdk/remote/pairing.js +160 -0
- package/dist/sdk/remote/seal.d.ts +28 -0
- package/dist/sdk/remote/seal.js +84 -0
- package/dist/sdk/remote/server.d.ts +28 -0
- package/dist/sdk/remote/server.js +158 -0
- package/dist/sdk/remote/service.d.ts +125 -0
- package/dist/sdk/remote/service.js +330 -0
- package/dist/sdk/remote/webClient.d.ts +4 -0
- package/dist/sdk/remote/webClient.js +444 -0
- package/dist/sdk/server/methods.js +3 -0
- package/dist/sdk/sessions/contracts.d.ts +4 -0
- package/dist/sdk/sessions/contracts.js +2 -0
- package/dist/sdk/sessions/planMode.d.ts +26 -1
- package/dist/sdk/sessions/planMode.js +48 -1
- package/dist/sdk/sessions/runner.d.ts +12 -0
- package/dist/sdk/sessions/runner.js +34 -2
- package/dist/sdk/sessions/sessions.js +1 -0
- package/dist/sdk/sessions/subagentService.d.ts +11 -1
- package/dist/sdk/sessions/subagentService.js +120 -38
- package/dist/sdk/sessions/subagents.d.ts +31 -0
- package/dist/sdk/sessions/subagents.js +45 -0
- package/dist/sdk/sessions/workSlice.d.ts +5 -9
- package/dist/sdk/sessions/workSlice.js +8 -149
- package/dist/sdk/terminal/client.d.ts +3 -1
- package/dist/sdk/terminal/client.js +15 -6
- package/dist/sdk/terminal/control.d.ts +1 -1
- package/dist/sdk/terminal/control.js +2 -2
- package/dist/sdk/terminal/controller.d.ts +22 -0
- package/dist/sdk/terminal/controller.js +104 -13
- package/dist/sdk/terminal/piExtension.js +106 -4
- package/dist/sdk/terminal/stallWatch.d.ts +13 -0
- package/dist/sdk/terminal/stallWatch.js +16 -0
- package/dist/sdk/terminal/standalone.d.ts +2 -0
- package/dist/sdk/terminal/standalone.js +9 -2
- package/dist/sdk/terminal/terminals.d.ts +14 -0
- package/dist/sdk/terminal/terminals.js +98 -2
- package/dist/sdk/terminal/tui/commandPages.d.ts +4 -1
- package/dist/sdk/terminal/tui/commandPages.js +12 -0
- package/dist/sdk/terminal/tui/commands.d.ts +3 -2
- package/dist/sdk/terminal/tui/commands.js +19 -5
- package/dist/sdk/terminal/tui/dialogs.d.ts +3 -2
- package/dist/sdk/terminal/tui/dialogs.js +4 -3
- package/dist/sdk/terminal/tui/keybindings.d.ts +1 -1
- package/dist/sdk/terminal/tui/keybindings.js +1 -1
- package/dist/sdk/terminal/tui/markdown.d.ts +16 -0
- package/dist/sdk/terminal/tui/markdown.js +55 -0
- package/dist/sdk/terminal/tui/modeChoices.d.ts +3 -2
- package/dist/sdk/terminal/tui/modeChoices.js +4 -4
- package/dist/sdk/terminal/tui/mouseReport.d.ts +30 -0
- package/dist/sdk/terminal/tui/mouseReport.js +80 -0
- package/dist/sdk/terminal/tui/pages/annotatePage.js +3 -2
- package/dist/sdk/terminal/tui/pages/browserPage.d.ts +1 -1
- package/dist/sdk/terminal/tui/pages/contextPage.d.ts +62 -0
- package/dist/sdk/terminal/tui/pages/contextPage.js +484 -0
- package/dist/sdk/terminal/tui/pages/remoteControlPage.d.ts +32 -0
- package/dist/sdk/terminal/tui/pages/remoteControlPage.js +170 -0
- package/dist/sdk/terminal/tui/pages/trajectoryPage.js +5 -4
- package/dist/sdk/terminal/tui/qr.d.ts +4 -0
- package/dist/sdk/terminal/tui/qr.js +35 -0
- package/dist/sdk/terminal/tui/runtime.js +8 -2
- package/dist/sdk/terminal/tui/search.js +3 -2
- package/dist/sdk/terminal/tui/sideQuestion.d.ts +1 -0
- package/dist/sdk/terminal/tui/sideQuestion.js +8 -3
- package/dist/sdk/terminal/tui/skillInvocation.d.ts +21 -2
- package/dist/sdk/terminal/tui/skillInvocation.js +31 -11
- package/dist/sdk/terminal/tui/status.d.ts +6 -0
- package/dist/sdk/terminal/tui/status.js +15 -1
- package/dist/sdk/terminal/tui/theme.d.ts +9 -0
- package/dist/sdk/terminal/tui/theme.js +9 -0
- package/dist/sdk/tools/defaultSkills.d.ts +19 -0
- package/dist/sdk/tools/defaultSkills.js +27 -1
- package/dist/sdk/tools/dispatch.js +8 -9
- package/dist/sdk/tools/spawnSubagent.d.ts +1 -1
- package/dist/sdk/tools/spawnSubagent.js +4 -2
- package/dist/terminal-opentui.js +1607 -492
- package/dist/terminal-pi.js +256 -144
- package/docs/README.md +1 -0
- package/docs/architecture/02-sessions-and-runs.md +55 -22
- package/docs/architecture/04-prompt.md +23 -4
- package/docs/architecture/07-tools-and-gate.md +4 -2
- package/docs/architecture/10-server-protocol.md +24 -0
- package/docs/architecture/11-terminal.md +52 -10
- package/docs/architecture/12-storage.md +5 -2
- package/docs/architecture/13-world-tools.md +17 -3
- package/docs/architecture/14-surfaces-and-parity.md +7 -3
- package/docs/architecture/15-remote-control.md +118 -0
- package/docs/architecture/README.md +3 -0
- package/docs/architecture/proposals/PROP-0049-context-attribution.md +409 -0
- package/docs/architecture/proposals/README.md +2 -1
- package/docs/decisions/ADR-0039-progress-aware-stall-guards.md +4 -0
- package/docs/decisions/ADR-0048-required-skills-from-a-message.md +42 -0
- package/docs/decisions/ADR-0050-approved-window-screenshots.md +19 -0
- package/docs/decisions/ADR-0051-terminal-decision-wait.md +10 -0
- package/docs/decisions/ADR-0052-per-profile-subagent-budgets.md +25 -0
- package/docs/decisions/ADR-0053-no-repeated-work-guard.md +45 -0
- package/docs/decisions/ADR-0054-terminal-reply-heartbeat-and-stall.md +52 -0
- package/docs/decisions/ADR-0055-plan-output-repair.md +51 -0
- package/docs/decisions/ADR-0056-remote-control.md +53 -0
- package/docs/decisions/ADR-0057-structured-plan-outcomes.md +39 -0
- package/docs/decisions/ADR-0058-ask-user-only-plan-clarification.md +36 -0
- package/docs/parity.md +14 -10
- package/docs/releases/1.3.1-unstable.3.md +54 -0
- package/docs/releases/1.3.1-unstable.4.md +56 -0
- package/docs/terminal-tui.md +43 -18
- package/package.json +3 -1
package/dist/terminal-opentui.js
CHANGED
|
@@ -20,12 +20,13 @@ import {
|
|
|
20
20
|
initTheme,
|
|
21
21
|
resizeImage
|
|
22
22
|
} from "@earendil-works/pi-coding-agent";
|
|
23
|
-
import { matchesKey as
|
|
23
|
+
import { matchesKey as matchesKey20 } from "@earendil-works/pi-tui";
|
|
24
24
|
|
|
25
25
|
// src/terminal/client.ts
|
|
26
26
|
import { createConnection } from "net";
|
|
27
27
|
var SOCKET_ENV = "XINGULAR_HARNESS_SOCKET";
|
|
28
28
|
var TOKEN_ENV = "XINGULAR_HARNESS_TOKEN";
|
|
29
|
+
var REMOTE_CONTROL_ENV = "XINGULAR_HARNESS_REMOTE_CONTROL";
|
|
29
30
|
|
|
30
31
|
class SocketError extends Error {
|
|
31
32
|
code;
|
|
@@ -70,18 +71,18 @@ function putIdle(path, stream) {
|
|
|
70
71
|
entries.add(entry);
|
|
71
72
|
idle.set(path, entries);
|
|
72
73
|
}
|
|
73
|
-
function request(connection, body, what, timeoutMs) {
|
|
74
|
+
function request(connection, body, what, timeoutMs, signal) {
|
|
74
75
|
const reused = takeIdle(connection.socket);
|
|
75
|
-
return attempt(connection, body, what, timeoutMs, reused).catch((error) => {
|
|
76
|
+
return attempt(connection, body, what, timeoutMs, reused, signal).catch((error) => {
|
|
76
77
|
if (reused && error instanceof StaleConnection)
|
|
77
|
-
return attempt(connection, body, what, timeoutMs, undefined);
|
|
78
|
+
return attempt(connection, body, what, timeoutMs, undefined, signal);
|
|
78
79
|
throw error;
|
|
79
80
|
});
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
class StaleConnection extends Error {
|
|
83
84
|
}
|
|
84
|
-
function attempt(connection, body, what, timeoutMs, reused) {
|
|
85
|
+
function attempt(connection, body, what, timeoutMs, reused, signal) {
|
|
85
86
|
return new Promise((resolve, reject) => {
|
|
86
87
|
const stream = reused ?? createConnection(connection.socket);
|
|
87
88
|
let buffer = "";
|
|
@@ -115,6 +116,7 @@ function attempt(connection, body, what, timeoutMs, reused) {
|
|
|
115
116
|
return;
|
|
116
117
|
settled = true;
|
|
117
118
|
clearTimeout(timer);
|
|
119
|
+
signal?.removeEventListener("abort", onAbort);
|
|
118
120
|
stream.off("connect", send);
|
|
119
121
|
stream.off("data", onData);
|
|
120
122
|
stream.off("error", onError);
|
|
@@ -131,6 +133,15 @@ function attempt(connection, body, what, timeoutMs, reused) {
|
|
|
131
133
|
stream.destroy();
|
|
132
134
|
finish(() => reject(new SocketError("timeout", `The harness did not answer ${what}.`)));
|
|
133
135
|
}, timeoutMs);
|
|
136
|
+
const onAbort = () => {
|
|
137
|
+
stream.destroy();
|
|
138
|
+
finish(() => reject(new SocketError("aborted", `${what} was cancelled.`)));
|
|
139
|
+
};
|
|
140
|
+
if (signal?.aborted) {
|
|
141
|
+
onAbort();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
134
145
|
stream.on("data", onData);
|
|
135
146
|
stream.on("error", onError);
|
|
136
147
|
stream.on("close", onClose);
|
|
@@ -140,8 +151,8 @@ function attempt(connection, body, what, timeoutMs, reused) {
|
|
|
140
151
|
stream.on("connect", send);
|
|
141
152
|
});
|
|
142
153
|
}
|
|
143
|
-
function socketCall(connection, call, params = {}, timeoutMs = 120000, control) {
|
|
144
|
-
return request(connection, { call, params, ...control ? { control } : {} }, call, timeoutMs);
|
|
154
|
+
function socketCall(connection, call, params = {}, timeoutMs = 120000, control, signal) {
|
|
155
|
+
return request(connection, { call, params, ...control ? { control } : {} }, call, timeoutMs, signal);
|
|
145
156
|
}
|
|
146
157
|
function terminalCall(event, data = {}, timeoutMs = 600000) {
|
|
147
158
|
return request(connectionFromEnv(), { event, data }, event, timeoutMs);
|
|
@@ -165,10 +176,10 @@ function claimTerminalControl(connection = connectionFromEnv()) {
|
|
|
165
176
|
}
|
|
166
177
|
return claim;
|
|
167
178
|
}
|
|
168
|
-
async function controlCall(call, params = {}, timeoutMs = 120000) {
|
|
179
|
+
async function controlCall(call, params = {}, timeoutMs = 120000, signal) {
|
|
169
180
|
const connection = connectionFromEnv();
|
|
170
181
|
const control = await claimTerminalControl(connection);
|
|
171
|
-
return socketCall(connection, call, params, timeoutMs, control);
|
|
182
|
+
return signal ? socketCall(connection, call, params, timeoutMs, control, signal) : socketCall(connection, call, params, timeoutMs, control);
|
|
172
183
|
}
|
|
173
184
|
|
|
174
185
|
// src/terminal/tui/chrome.ts
|
|
@@ -360,6 +371,7 @@ var CORE_COMMANDS = [
|
|
|
360
371
|
{ name: "session", aliases: ["resume"], args: "[path]", description: "Choose a saved session in this account and folder", group: "Session", kind: "session" },
|
|
361
372
|
{ name: "history", aliases: ["tree"], description: "Navigate branches in the current session", group: "Session", kind: "session", methods: ["sessions.tree", "sessions.navigate"] },
|
|
362
373
|
{ name: "fork", description: "Fork from an earlier message", group: "Session", kind: "session", methods: ["sessions.tree", "sessions.fork"] },
|
|
374
|
+
{ name: "remote-control", aliases: ["rc"], args: "[off|tailscale|lan]", description: "Continue this session from your phone or iPad", group: "Session", kind: "page", methods: ["terminal.remoteControl.start", "terminal.remoteControl.stop", "terminal.remoteControl.status"] },
|
|
363
375
|
{ name: "clone", description: "Clone this branch into a new session", group: "Session", kind: "session", methods: ["sessions.clone"] },
|
|
364
376
|
{ name: "model", args: "[search]", description: "Choose the model", group: "Model", kind: "session", methods: ["accounts.models"] },
|
|
365
377
|
{ name: "effort", args: "[level]", description: "Choose the thinking effort", group: "Model", kind: "session" },
|
|
@@ -387,6 +399,7 @@ var CORE_COMMANDS = [
|
|
|
387
399
|
{ name: "subagents", description: "Watch current subagent tasks and activity", group: "Harness", kind: "page" },
|
|
388
400
|
{ name: "agents", description: "Browse and edit agent profiles", group: "Harness", kind: "page", methods: ["agents.list"] },
|
|
389
401
|
{ name: "log", description: "Harness diagnostics and this conversation's run events", group: "Inspect", kind: "page" },
|
|
402
|
+
{ name: "context", args: "[growth]", description: "What the latest request was made of, and where the rest of the window went", group: "Inspect", kind: "page", methods: ["context.attribution"] },
|
|
390
403
|
{ name: "hotkeys", description: "Keyboard controls", group: "Core", kind: "local" },
|
|
391
404
|
{ name: "quit", description: "Restore the terminal and exit", group: "Core", kind: "local" }
|
|
392
405
|
];
|
|
@@ -584,19 +597,10 @@ function lines(text) {
|
|
|
584
597
|
}
|
|
585
598
|
var compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
586
599
|
|
|
587
|
-
// src/
|
|
588
|
-
import { existsSync as existsSync2,
|
|
589
|
-
import { dirname as dirname2, join as join3
|
|
590
|
-
|
|
591
|
-
// src/core/changes.ts
|
|
592
|
-
var listeners = new Set;
|
|
593
|
-
function noteChange(change) {
|
|
594
|
-
for (const listener of listeners) {
|
|
595
|
-
try {
|
|
596
|
-
listener(change);
|
|
597
|
-
} catch {}
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
+
// src/tools/defaultSkills.ts
|
|
601
|
+
import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync as statSync2 } from "fs";
|
|
602
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
603
|
+
import { fileURLToPath } from "url";
|
|
600
604
|
|
|
601
605
|
// src/core/frontmatter.ts
|
|
602
606
|
import { parse as parseYaml, stringify } from "yaml";
|
|
@@ -625,6 +629,17 @@ function parse(text) {
|
|
|
625
629
|
return null;
|
|
626
630
|
}
|
|
627
631
|
}
|
|
632
|
+
function bodyOf(text) {
|
|
633
|
+
const parts = split(text);
|
|
634
|
+
if (!parts)
|
|
635
|
+
return text;
|
|
636
|
+
try {
|
|
637
|
+
parseYaml(parts.yaml);
|
|
638
|
+
return parts.body;
|
|
639
|
+
} catch {
|
|
640
|
+
return text;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
628
643
|
function serialize(front, body) {
|
|
629
644
|
let yaml;
|
|
630
645
|
try {
|
|
@@ -639,6 +654,57 @@ ${body.trimEnd()}
|
|
|
639
654
|
`;
|
|
640
655
|
}
|
|
641
656
|
|
|
657
|
+
// src/tools/defaultSkills.ts
|
|
658
|
+
var SKILL_NAME = /^[a-z0-9][a-z0-9_-]*$/;
|
|
659
|
+
function defaultSkillPath() {
|
|
660
|
+
let dir = dirname2(fileURLToPath(import.meta.url));
|
|
661
|
+
for (;; ) {
|
|
662
|
+
const path = join3(dir, "builtin", "skills", "plugin-authoring", "SKILL.md");
|
|
663
|
+
if (existsSync2(path))
|
|
664
|
+
return path;
|
|
665
|
+
const parent = dirname2(dir);
|
|
666
|
+
if (parent === dir)
|
|
667
|
+
throw new Error("The bundled plugin-authoring skill is missing.");
|
|
668
|
+
dir = parent;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
function defaultSkillPaths(variantDir) {
|
|
672
|
+
return variantDir && existsSync2(join3(variantDir, "skills", "plugin-authoring", "SKILL.md")) ? [] : [defaultSkillPath()];
|
|
673
|
+
}
|
|
674
|
+
function readSkillFile(variantDir, name) {
|
|
675
|
+
const wanted = name.trim().replace(/^skills\//, "").replace(/`/g, "");
|
|
676
|
+
if (!SKILL_NAME.test(wanted))
|
|
677
|
+
return null;
|
|
678
|
+
const variant = variantDir ? join3(variantDir, "skills", wanted, "SKILL.md") : null;
|
|
679
|
+
const builtin = wanted === "plugin-authoring" && defaultSkillPaths(variantDir).length ? defaultSkillPath() : null;
|
|
680
|
+
const path = variant && existsSync2(variant) && statSync2(variant).isFile() ? variant : builtin;
|
|
681
|
+
if (!path)
|
|
682
|
+
return null;
|
|
683
|
+
const baseDir = dirname2(path);
|
|
684
|
+
const scripts = join3(baseDir, "scripts");
|
|
685
|
+
return {
|
|
686
|
+
name: wanted,
|
|
687
|
+
path,
|
|
688
|
+
baseDir,
|
|
689
|
+
body: bodyOf(readFileSync2(path, "utf8")),
|
|
690
|
+
helpers: existsSync2(scripts) ? readdirSync(scripts) : []
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// src/wiki/notes.ts
|
|
695
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync3 } from "fs";
|
|
696
|
+
import { dirname as dirname3, join as join4, relative, sep as sep2 } from "path";
|
|
697
|
+
|
|
698
|
+
// src/core/changes.ts
|
|
699
|
+
var listeners = new Set;
|
|
700
|
+
function noteChange(change) {
|
|
701
|
+
for (const listener of listeners) {
|
|
702
|
+
try {
|
|
703
|
+
listener(change);
|
|
704
|
+
} catch {}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
642
708
|
// src/core/secrets.ts
|
|
643
709
|
var SECRET_MARKERS = ["-----BEGIN", "sk-ant-", "sk-proj-", "ghp_", "github_pat_", "AKIA", "xoxb-"];
|
|
644
710
|
function looksSecret(text) {
|
|
@@ -649,10 +715,10 @@ function looksSecret(text) {
|
|
|
649
715
|
var LEGACY_FOLDERS = ["blocks", "facts", "raw", "revisions", "inbox", "operations", "trash"];
|
|
650
716
|
var MAX_NOTE = 400000;
|
|
651
717
|
function wikiDir(root) {
|
|
652
|
-
return
|
|
718
|
+
return join4(root, "wiki");
|
|
653
719
|
}
|
|
654
720
|
function historyDir(root) {
|
|
655
|
-
return
|
|
721
|
+
return join4(root, "wiki-history");
|
|
656
722
|
}
|
|
657
723
|
function cleanPath(path) {
|
|
658
724
|
const clean = String(path ?? "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "").replace(/\.md$/i, "");
|
|
@@ -670,7 +736,7 @@ function cleanPath(path) {
|
|
|
670
736
|
return clean;
|
|
671
737
|
}
|
|
672
738
|
function fileOf(root, path) {
|
|
673
|
-
return
|
|
739
|
+
return join4(wikiDir(root), `${cleanPath(path)}.md`);
|
|
674
740
|
}
|
|
675
741
|
function projectOfPath(path) {
|
|
676
742
|
const parts = path.split("/");
|
|
@@ -695,17 +761,17 @@ function safeParse(text) {
|
|
|
695
761
|
function walk(dir, into) {
|
|
696
762
|
let names;
|
|
697
763
|
try {
|
|
698
|
-
names =
|
|
764
|
+
names = readdirSync2(dir);
|
|
699
765
|
} catch {
|
|
700
766
|
return;
|
|
701
767
|
}
|
|
702
768
|
for (const name of names.sort()) {
|
|
703
769
|
if (name.startsWith("."))
|
|
704
770
|
continue;
|
|
705
|
-
const path =
|
|
771
|
+
const path = join4(dir, name);
|
|
706
772
|
let isDir = false;
|
|
707
773
|
try {
|
|
708
|
-
isDir =
|
|
774
|
+
isDir = statSync3(path).isDirectory();
|
|
709
775
|
} catch {
|
|
710
776
|
continue;
|
|
711
777
|
}
|
|
@@ -718,16 +784,16 @@ function walk(dir, into) {
|
|
|
718
784
|
function paths(root) {
|
|
719
785
|
const wiki = wikiDir(root);
|
|
720
786
|
const files = [];
|
|
721
|
-
if (
|
|
722
|
-
files.push(
|
|
723
|
-
walk(
|
|
724
|
-
walk(
|
|
787
|
+
if (existsSync3(join4(wiki, "home.md")))
|
|
788
|
+
files.push(join4(wiki, "home.md"));
|
|
789
|
+
walk(join4(wiki, "library"), files);
|
|
790
|
+
walk(join4(wiki, "projects"), files);
|
|
725
791
|
return files.map((file) => relative(wiki, file).split(sep2).join("/").replace(/\.md$/, ""));
|
|
726
792
|
}
|
|
727
793
|
function summary(root, path) {
|
|
728
794
|
const file = fileOf(root, path);
|
|
729
|
-
const text =
|
|
730
|
-
return { path, title: titleOf(path, text), project: projectOfPath(path), updatedAt:
|
|
795
|
+
const text = readFileSync3(file, "utf8");
|
|
796
|
+
return { path, title: titleOf(path, text), project: projectOfPath(path), updatedAt: statSync3(file).mtime.toISOString(), size: text.length };
|
|
731
797
|
}
|
|
732
798
|
function list(root, options = {}) {
|
|
733
799
|
return paths(root).filter((path) => options.project === undefined || projectOfPath(path) === options.project).map((path) => summary(root, path));
|
|
@@ -779,7 +845,7 @@ function graph(root) {
|
|
|
779
845
|
const titles = new Map(nodes.map((node) => [node.title.toLowerCase(), node.path]));
|
|
780
846
|
const edges = [];
|
|
781
847
|
for (const node of nodes) {
|
|
782
|
-
const body =
|
|
848
|
+
const body = readFileSync3(fileOf(root, node.path), "utf8");
|
|
783
849
|
for (const to of linksIn(body, node.path, known, titles))
|
|
784
850
|
edges.push({ from: node.path, to });
|
|
785
851
|
}
|
|
@@ -788,9 +854,9 @@ function graph(root) {
|
|
|
788
854
|
function read(root, path) {
|
|
789
855
|
const clean = cleanPath(path);
|
|
790
856
|
const file = fileOf(root, clean);
|
|
791
|
-
if (!
|
|
857
|
+
if (!existsSync3(file))
|
|
792
858
|
throw notFound(`The note ${clean}`);
|
|
793
|
-
const text =
|
|
859
|
+
const text = readFileSync3(file, "utf8");
|
|
794
860
|
const { nodes, edges } = graph(root);
|
|
795
861
|
const known = new Set(nodes.map((node) => node.path));
|
|
796
862
|
const titles = new Map(nodes.map((node) => [node.title.toLowerCase(), node.path]));
|
|
@@ -813,16 +879,16 @@ function write(root, path, body, options = {}) {
|
|
|
813
879
|
if (project && !projectsOrNone(root).some((known) => known.slug === project))
|
|
814
880
|
throw invalid(`There is no project with the slug ${project}.`);
|
|
815
881
|
const file = fileOf(root, clean);
|
|
816
|
-
if (
|
|
817
|
-
const current =
|
|
882
|
+
if (existsSync3(file)) {
|
|
883
|
+
const current = statSync3(file).mtime.toISOString();
|
|
818
884
|
if (options.expectedUpdatedAt && options.expectedUpdatedAt !== current)
|
|
819
885
|
throw new HarnessError("conflict", "The note changed since it was opened. Reload it and try again.");
|
|
820
|
-
const previous =
|
|
886
|
+
const previous = readFileSync3(file, "utf8");
|
|
821
887
|
if (previous === body)
|
|
822
888
|
return read(root, clean);
|
|
823
|
-
atomicWrite(
|
|
889
|
+
atomicWrite(join4(historyDir(root), clean, `${now().replace(/[:.]/g, "-")}.md`), previous);
|
|
824
890
|
}
|
|
825
|
-
mkdirSync2(
|
|
891
|
+
mkdirSync2(dirname3(file), { recursive: true });
|
|
826
892
|
atomicWrite(file, body);
|
|
827
893
|
noteChange({ wiki: wikiDir(root), id: clean, path: file, text: body, actor: options.actor ?? "user", reason: options.reason ?? "Saved" });
|
|
828
894
|
return read(root, clean);
|
|
@@ -830,15 +896,15 @@ function write(root, path, body, options = {}) {
|
|
|
830
896
|
function remove(root, path) {
|
|
831
897
|
const clean = cleanPath(path);
|
|
832
898
|
const file = fileOf(root, clean);
|
|
833
|
-
if (!
|
|
899
|
+
if (!existsSync3(file))
|
|
834
900
|
throw notFound(`The note ${clean}`);
|
|
835
|
-
atomicWrite(
|
|
901
|
+
atomicWrite(join4(historyDir(root), clean, `${now().replace(/[:.]/g, "-")}.md`), readFileSync3(file, "utf8"));
|
|
836
902
|
rmSync2(file);
|
|
837
903
|
}
|
|
838
904
|
function versions(root, path) {
|
|
839
|
-
const dir =
|
|
905
|
+
const dir = join4(historyDir(root), cleanPath(path));
|
|
840
906
|
try {
|
|
841
|
-
return
|
|
907
|
+
return readdirSync2(dir).filter((name) => name.endsWith(".md")).sort().reverse().map((name) => ({ id: name.replace(/\.md$/, ""), savedAt: statSync3(join4(dir, name)).mtime.toISOString() }));
|
|
842
908
|
} catch {
|
|
843
909
|
return [];
|
|
844
910
|
}
|
|
@@ -846,10 +912,10 @@ function versions(root, path) {
|
|
|
846
912
|
function version(root, path, id) {
|
|
847
913
|
if (!/^[0-9A-Za-z-]+$/.test(id))
|
|
848
914
|
throw invalid("Invalid version.");
|
|
849
|
-
const file =
|
|
850
|
-
if (!
|
|
915
|
+
const file = join4(historyDir(root), cleanPath(path), `${id}.md`);
|
|
916
|
+
if (!existsSync3(file))
|
|
851
917
|
throw notFound("That version");
|
|
852
|
-
return
|
|
918
|
+
return readFileSync3(file, "utf8");
|
|
853
919
|
}
|
|
854
920
|
function search(root, query, options = {}) {
|
|
855
921
|
const words = [...new Set(String(query ?? "").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((word) => word.length > 1))].slice(0, 16);
|
|
@@ -857,7 +923,7 @@ function search(root, query, options = {}) {
|
|
|
857
923
|
return [];
|
|
858
924
|
const hits = [];
|
|
859
925
|
for (const path of paths(root)) {
|
|
860
|
-
const text =
|
|
926
|
+
const text = readFileSync3(fileOf(root, path), "utf8");
|
|
861
927
|
const lower = text.toLowerCase();
|
|
862
928
|
const title = titleOf(path, text);
|
|
863
929
|
let score = 0;
|
|
@@ -887,15 +953,15 @@ function search(root, query, options = {}) {
|
|
|
887
953
|
}
|
|
888
954
|
function ensureLayout(root, productName) {
|
|
889
955
|
const wiki = wikiDir(root);
|
|
890
|
-
mkdirSync2(
|
|
891
|
-
mkdirSync2(
|
|
892
|
-
if (!
|
|
893
|
-
atomicWrite(
|
|
956
|
+
mkdirSync2(join4(wiki, "library"), { recursive: true });
|
|
957
|
+
mkdirSync2(join4(wiki, "projects"), { recursive: true });
|
|
958
|
+
if (!existsSync3(join4(wiki, "home.md")))
|
|
959
|
+
atomicWrite(join4(wiki, "home.md"), `# Home
|
|
894
960
|
|
|
895
961
|
Notes about your projects for ${productName}. Link notes with [[library/name]] or [[projects/<slug>/name]].
|
|
896
962
|
`);
|
|
897
963
|
for (const project of projectsOrNone(root))
|
|
898
|
-
mkdirSync2(
|
|
964
|
+
mkdirSync2(join4(wiki, "projects", project.slug), { recursive: true });
|
|
899
965
|
}
|
|
900
966
|
|
|
901
967
|
// src/world/untrusted.ts
|
|
@@ -953,6 +1019,7 @@ var contextSnapshotPayload = z.object({
|
|
|
953
1019
|
systemPrompt: z.string().max(1e5),
|
|
954
1020
|
contextUpdate: z.string().max(1e5).optional(),
|
|
955
1021
|
tools: z.array(z.object({ name: z.string(), description: z.string().max(2000), parameters: z.unknown() })).max(120),
|
|
1022
|
+
compaction: z.object({ enabled: z.boolean(), reserveTokens: z.number().nonnegative() }).optional(),
|
|
956
1023
|
systemPromptTruncated: z.boolean().optional(),
|
|
957
1024
|
contextUpdateTruncated: z.boolean().optional(),
|
|
958
1025
|
toolsTruncated: z.boolean().optional()
|
|
@@ -1491,9 +1558,28 @@ function sessionNameTool(current) {
|
|
|
1491
1558
|
|
|
1492
1559
|
// src/prompt/compile.ts
|
|
1493
1560
|
var SESSION_STATE_BUDGET = 1000;
|
|
1494
|
-
var
|
|
1561
|
+
var REQUIRED_SKILLS_BUDGET = 12000;
|
|
1562
|
+
var REQUIRED_SKILLS_POINTER = "Some required skill text was omitted to fit. Load the rest with skill_load.";
|
|
1563
|
+
var SECTION_ORDER = { harnessIdentity: 5, system: 25, sessionState: 30, guardrails: 40, memory: 45, references: 50, requiredSkills: 52, subagents: 64, scripts: 66, wiki: 80, tools: 90, reporting: 95 };
|
|
1495
1564
|
var NATIVE_GROUP = ["read", "grep", "find", "ls", "edit", "write", "bash"];
|
|
1496
1565
|
var CONNECTION_TOOLS = ["mcp_list_tools", "mcp_call_tool"];
|
|
1566
|
+
function fit(text, budget, pointer) {
|
|
1567
|
+
const trimmed = text.trim();
|
|
1568
|
+
if (charCount(trimmed) <= budget)
|
|
1569
|
+
return { body: trimmed, cut: false };
|
|
1570
|
+
const room = Math.max(0, budget - (charCount(pointer) + 2));
|
|
1571
|
+
const head = takeChars(trimmed, room);
|
|
1572
|
+
let index = head.lastIndexOf(`
|
|
1573
|
+
|
|
1574
|
+
`);
|
|
1575
|
+
if (index < 0)
|
|
1576
|
+
index = head.lastIndexOf(`
|
|
1577
|
+
`);
|
|
1578
|
+
const end = index >= 0 && Buffer.byteLength(head.slice(0, index)) > Math.floor(room / 2) ? index : head.length;
|
|
1579
|
+
return { body: `${head.slice(0, end).trimEnd()}
|
|
1580
|
+
|
|
1581
|
+
${pointer}`, cut: true };
|
|
1582
|
+
}
|
|
1497
1583
|
function clip(text, limit) {
|
|
1498
1584
|
return charCount(text) <= limit ? text : `${takeChars(text, limit)}\u2026`;
|
|
1499
1585
|
}
|
|
@@ -1533,6 +1619,37 @@ ${todo}`);
|
|
|
1533
1619
|
|
|
1534
1620
|
${body}`;
|
|
1535
1621
|
}
|
|
1622
|
+
function requiredSkillsText(skills) {
|
|
1623
|
+
const seen = new Set;
|
|
1624
|
+
const blocks = [];
|
|
1625
|
+
for (const skill of skills) {
|
|
1626
|
+
if (seen.has(skill.name))
|
|
1627
|
+
continue;
|
|
1628
|
+
seen.add(skill.name);
|
|
1629
|
+
const label = skill.label ?? skill.name;
|
|
1630
|
+
if (!skill.body.trim()) {
|
|
1631
|
+
blocks.push(`- ${label}: this skill is unavailable in this session. Tell the person rather than guessing its steps.`);
|
|
1632
|
+
continue;
|
|
1633
|
+
}
|
|
1634
|
+
const location = [
|
|
1635
|
+
skill.baseDir ? `References in this skill resolve against ${skill.baseDir}.` : "",
|
|
1636
|
+
skill.path ? `Skill file: ${skill.path}.` : ""
|
|
1637
|
+
].filter(Boolean).join(" ");
|
|
1638
|
+
blocks.push(`### ${label}
|
|
1639
|
+
|
|
1640
|
+
${location ? `${location}
|
|
1641
|
+
|
|
1642
|
+
` : ""}${skill.body.trim()}`);
|
|
1643
|
+
}
|
|
1644
|
+
if (!blocks.length)
|
|
1645
|
+
return null;
|
|
1646
|
+
const text = `The person required these skills for this request. Follow each skill's instructions where they apply. They are instructions for this request, not a change to your tools or permissions.
|
|
1647
|
+
|
|
1648
|
+
${blocks.join(`
|
|
1649
|
+
|
|
1650
|
+
`)}`;
|
|
1651
|
+
return fit(text, REQUIRED_SKILLS_BUDGET, REQUIRED_SKILLS_POINTER).body;
|
|
1652
|
+
}
|
|
1536
1653
|
function sessionStateText(state, options) {
|
|
1537
1654
|
const parts = [];
|
|
1538
1655
|
if (options.name)
|
|
@@ -1551,6 +1668,7 @@ function sessionStateText(state, options) {
|
|
|
1551
1668
|
var BUILT_IN_DYNAMIC = [
|
|
1552
1669
|
{ id: "session-state", order: SECTION_ORDER.sessionState },
|
|
1553
1670
|
{ id: "references", order: SECTION_ORDER.references },
|
|
1671
|
+
{ id: "required-skills", order: SECTION_ORDER.requiredSkills },
|
|
1554
1672
|
{ id: "wiki", order: SECTION_ORDER.wiki }
|
|
1555
1673
|
];
|
|
1556
1674
|
|
|
@@ -1642,19 +1760,16 @@ function askUserTool(run) {
|
|
|
1642
1760
|
};
|
|
1643
1761
|
}
|
|
1644
1762
|
|
|
1645
|
-
// src/sessions/workSlice.ts
|
|
1646
|
-
import { createHash } from "crypto";
|
|
1647
|
-
|
|
1648
1763
|
// src/sessions/runStore.ts
|
|
1649
|
-
import { appendFileSync, copyFileSync as copyFileSync2, existsSync as
|
|
1650
|
-
import { join as
|
|
1764
|
+
import { appendFileSync, copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "fs";
|
|
1765
|
+
import { join as join7 } from "path";
|
|
1651
1766
|
|
|
1652
1767
|
// src/sessions/runIndex.ts
|
|
1653
|
-
import { join as
|
|
1768
|
+
import { join as join6 } from "path";
|
|
1654
1769
|
|
|
1655
1770
|
// src/core/index.ts
|
|
1656
|
-
import { copyFileSync, existsSync as
|
|
1657
|
-
import { join as
|
|
1771
|
+
import { copyFileSync, existsSync as existsSync4, readdirSync as readdirSync3, rmSync as rmSync3 } from "fs";
|
|
1772
|
+
import { join as join5 } from "path";
|
|
1658
1773
|
import { DatabaseSync } from "node:sqlite";
|
|
1659
1774
|
var RECALL_SCHEMA = `CREATE TABLE recall_runs (run_id TEXT PRIMARY KEY, passages INTEGER NOT NULL, status TEXT NOT NULL);
|
|
1660
1775
|
CREATE VIRTUAL TABLE recall_fts USING fts5(run_id UNINDEXED, seq UNINDEXED, role UNINDEXED, at UNINDEXED,
|
|
@@ -1714,7 +1829,7 @@ var MIGRATIONS = [
|
|
|
1714
1829
|
];
|
|
1715
1830
|
var connections = new Map;
|
|
1716
1831
|
function dbPath(root) {
|
|
1717
|
-
return
|
|
1832
|
+
return join5(root, "index.sqlite");
|
|
1718
1833
|
}
|
|
1719
1834
|
function sqlError(error) {
|
|
1720
1835
|
return new HarnessError("index_error", error instanceof Error ? error.message : String(error), "Settings \u2192 Projects and Storage \u2192 Repair index.");
|
|
@@ -1750,7 +1865,7 @@ function migrate(path, migrations) {
|
|
|
1750
1865
|
if (current >= migrations.length)
|
|
1751
1866
|
return database;
|
|
1752
1867
|
const backup = `${path.replace(/\.sqlite$/, "")}.sqlite.bak-v${current}`;
|
|
1753
|
-
const hadFile =
|
|
1868
|
+
const hadFile = existsSync4(path) && current > 0;
|
|
1754
1869
|
if (hadFile) {
|
|
1755
1870
|
try {
|
|
1756
1871
|
database.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
@@ -1798,7 +1913,7 @@ function all(database, sql, ...params) {
|
|
|
1798
1913
|
}
|
|
1799
1914
|
function runFolders(root) {
|
|
1800
1915
|
try {
|
|
1801
|
-
return
|
|
1916
|
+
return readdirSync3(join5(root, "runs"));
|
|
1802
1917
|
} catch {
|
|
1803
1918
|
return [];
|
|
1804
1919
|
}
|
|
@@ -1809,7 +1924,7 @@ function readAllRuns(root) {
|
|
|
1809
1924
|
const records = [];
|
|
1810
1925
|
for (const name of runFolders(root)) {
|
|
1811
1926
|
try {
|
|
1812
|
-
const parsed = runRecordSchema.safeParse(upgradeRunRecord(readJson(
|
|
1927
|
+
const parsed = runRecordSchema.safeParse(upgradeRunRecord(readJson(join6(root, "runs", name, "run.json"))));
|
|
1813
1928
|
if (parsed.success)
|
|
1814
1929
|
records.push(parsed.data);
|
|
1815
1930
|
} catch {}
|
|
@@ -1819,9 +1934,9 @@ function readAllRuns(root) {
|
|
|
1819
1934
|
|
|
1820
1935
|
// src/sessions/runStore.ts
|
|
1821
1936
|
function runDir(root, runId) {
|
|
1822
|
-
return
|
|
1937
|
+
return join7(root, "runs", safeId(runId));
|
|
1823
1938
|
}
|
|
1824
|
-
var recordPath = (root, runId) =>
|
|
1939
|
+
var recordPath = (root, runId) => join7(runDir(root, runId), "run.json");
|
|
1825
1940
|
function readRecord(path) {
|
|
1826
1941
|
const parsed = runRecordSchema.safeParse(upgradeRunRecord(readJson(path)));
|
|
1827
1942
|
return parsed.success ? parsed.data : null;
|
|
@@ -1861,7 +1976,7 @@ function storedEvent(line) {
|
|
|
1861
1976
|
function readEvents(root, runId) {
|
|
1862
1977
|
let text;
|
|
1863
1978
|
try {
|
|
1864
|
-
text =
|
|
1979
|
+
text = readFileSync4(join7(runDir(root, runId), "events.jsonl"), "utf8");
|
|
1865
1980
|
} catch (error) {
|
|
1866
1981
|
if (error.code === "ENOENT")
|
|
1867
1982
|
return [];
|
|
@@ -1961,94 +2076,24 @@ function sliceLimitReached(policy, state, now = Date.now()) {
|
|
|
1961
2076
|
return null;
|
|
1962
2077
|
}
|
|
1963
2078
|
var HANDOFF_TOOLS = new Set(["checkpoint_write", "session_name"]);
|
|
1964
|
-
var POLLING_TOOLS = new Set(["wait_subagents", "subagents.list", "subagents.status"]);
|
|
1965
|
-
function looksLikeCheck(command) {
|
|
1966
|
-
return /\b(test|tests|typecheck|tsc|vitest|jest|cargo|check:|prove|lint|ci|build)\b/u.test(command);
|
|
1967
|
-
}
|
|
1968
|
-
function canonical(value, depth = 0) {
|
|
1969
|
-
if (depth > 8)
|
|
1970
|
-
return "\u2026";
|
|
1971
|
-
if (value === null || typeof value !== "object")
|
|
1972
|
-
return JSON.stringify(value) ?? "null";
|
|
1973
|
-
if (Array.isArray(value))
|
|
1974
|
-
return `[${value.map((item) => canonical(item, depth + 1)).join(",")}]`;
|
|
1975
|
-
const entries = Object.entries(value).filter(([, item]) => item !== undefined);
|
|
1976
|
-
entries.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
|
|
1977
|
-
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item, depth + 1)}`).join(",")}}`;
|
|
1978
|
-
}
|
|
1979
|
-
var signature = (name, input) => `${name}\x00${createHash("sha256").update(canonical(input ?? null)).digest("hex")}`;
|
|
1980
2079
|
var clip2 = (value, limit) => value.length <= limit ? value : `${value.slice(0, limit - 1)}\u2026`;
|
|
1981
2080
|
function handoffRequest(limit, state, checkpointAvailable = true) {
|
|
1982
2081
|
const handoff = checkpointAvailable ? "Call checkpoint_write now with what is done, the single next step, anything blocking, the files you touched and the checks that matter. Then tell the user in a few lines where you stopped." : "Stop using tools and return a concise partial research report with findings, blockers and the next useful research step. The Harness records an evidence-derived checkpoint.";
|
|
1983
2082
|
return clip2(`This reply reached its work-slice limit (${limit}; step ${state.steps}). ${handoff} Do not call other tools.`, 600);
|
|
1984
2083
|
}
|
|
1985
|
-
function stalledNote(reason, checkpointAvailable = true) {
|
|
1986
|
-
const handoff = checkpointAvailable ? "Choose a different approach, read what the earlier attempt returned, or call checkpoint_write with the blocker so the next slice can decide." : "Do not use more tools. Return concise findings and blockers in your final response; the Harness records an evidence-derived checkpoint.";
|
|
1987
|
-
return clip2(`You are repeating work: ${reason}. Do not repeat it. ${handoff}`, 600);
|
|
1988
|
-
}
|
|
1989
2084
|
function workSliceGuard(options) {
|
|
1990
2085
|
const { policy, state } = options;
|
|
1991
|
-
const calls = new Map;
|
|
1992
|
-
const checkCalls = new Set;
|
|
1993
|
-
const edits = new Map;
|
|
1994
|
-
const failures = new Map;
|
|
1995
|
-
let nudged = false;
|
|
1996
2086
|
const checkpointAvailable = () => typeof options.checkpointAvailable === "function" ? options.checkpointAvailable() : options.checkpointAvailable !== false;
|
|
1997
|
-
const resetRepetition = () => {
|
|
1998
|
-
calls.clear();
|
|
1999
|
-
checkCalls.clear();
|
|
2000
|
-
edits.clear();
|
|
2001
|
-
failures.clear();
|
|
2002
|
-
nudged = false;
|
|
2003
|
-
};
|
|
2004
2087
|
const end = (kind, limit) => {
|
|
2005
2088
|
state.endedBy = kind;
|
|
2006
2089
|
state.endedByLimit = limit;
|
|
2007
2090
|
options.onEnd?.(kind, limit);
|
|
2008
2091
|
const canCheckpoint = checkpointAvailable();
|
|
2009
|
-
const reason = kind === "
|
|
2092
|
+
const reason = kind === "compaction-thrash" ? handoffRequest("three context compactions in one reply", state, canCheckpoint) : handoffRequest(limit, state, canCheckpoint);
|
|
2010
2093
|
return { block: true, terminate: true, reason };
|
|
2011
2094
|
};
|
|
2012
|
-
const nudge = (reason) => {
|
|
2013
|
-
if (nudged)
|
|
2014
|
-
return end("stuck", reason);
|
|
2015
|
-
nudged = true;
|
|
2016
|
-
const canCheckpoint = checkpointAvailable();
|
|
2017
|
-
if (!canCheckpoint) {
|
|
2018
|
-
state.endedBy = "stuck";
|
|
2019
|
-
state.endedByLimit = reason;
|
|
2020
|
-
}
|
|
2021
|
-
return { block: true, reason: stalledNote(reason, canCheckpoint) };
|
|
2022
|
-
};
|
|
2023
|
-
const repeated = (name, input) => {
|
|
2024
|
-
if (POLLING_TOOLS.has(name))
|
|
2025
|
-
return null;
|
|
2026
|
-
const key = signature(name, input);
|
|
2027
|
-
if (name === "bash") {
|
|
2028
|
-
const command = input && typeof input === "object" ? String(input.command ?? "") : "";
|
|
2029
|
-
if (command && looksLikeCheck(command))
|
|
2030
|
-
checkCalls.add(key);
|
|
2031
|
-
}
|
|
2032
|
-
const count = (calls.get(key) ?? 0) + 1;
|
|
2033
|
-
calls.set(key, count);
|
|
2034
|
-
if (count < 3)
|
|
2035
|
-
return null;
|
|
2036
|
-
return name === "bash" ? `the same Bash command ${count} times (steps ending at ${state.steps})` : `the same ${name} call ${count} times (steps ending at ${state.steps})`;
|
|
2037
|
-
};
|
|
2038
|
-
const failing = (name, input) => {
|
|
2039
|
-
if (name !== "bash")
|
|
2040
|
-
return null;
|
|
2041
|
-
const command = input && typeof input === "object" ? String(input.command ?? "") : "";
|
|
2042
|
-
if (!command || !looksLikeCheck(command))
|
|
2043
|
-
return null;
|
|
2044
|
-
const count = failures.get(command) ?? 0;
|
|
2045
|
-
return count >= 2 ? `the check ${command} failed ${count} times` : null;
|
|
2046
|
-
};
|
|
2047
2095
|
return (pi) => {
|
|
2048
|
-
pi.on("agent_start", () =>
|
|
2049
|
-
resetSliceState(state);
|
|
2050
|
-
resetRepetition();
|
|
2051
|
-
});
|
|
2096
|
+
pi.on("agent_start", () => resetSliceState(state));
|
|
2052
2097
|
pi.on("message_end", (event) => {
|
|
2053
2098
|
const usage = event.message.usage;
|
|
2054
2099
|
if (event.message.role !== "assistant" || !usage)
|
|
@@ -2056,35 +2101,8 @@ function workSliceGuard(options) {
|
|
|
2056
2101
|
state.tokens += (usage.input ?? 0) + (usage.cacheWrite ?? 0) + (usage.output ?? 0);
|
|
2057
2102
|
});
|
|
2058
2103
|
pi.on("tool_result", (event) => {
|
|
2059
|
-
if (event.toolName === "checkpoint_write" && !event.isError)
|
|
2104
|
+
if (event.toolName === "checkpoint_write" && !event.isError)
|
|
2060
2105
|
state.checkpointWritten = true;
|
|
2061
|
-
nudged = false;
|
|
2062
|
-
}
|
|
2063
|
-
if ((event.toolName === "edit" || event.toolName === "write") && event.isError === false) {
|
|
2064
|
-
const path = event.input && typeof event.input === "object" ? String(event.input.path ?? "") : "";
|
|
2065
|
-
if (path) {
|
|
2066
|
-
edits.set(path, (edits.get(path) ?? 0) + 1);
|
|
2067
|
-
failures.clear();
|
|
2068
|
-
for (const key of checkCalls)
|
|
2069
|
-
calls.delete(key);
|
|
2070
|
-
checkCalls.clear();
|
|
2071
|
-
nudged = false;
|
|
2072
|
-
}
|
|
2073
|
-
}
|
|
2074
|
-
if (event.toolName !== "bash")
|
|
2075
|
-
return;
|
|
2076
|
-
const command = event.input && typeof event.input === "object" ? String(event.input.command ?? "") : "";
|
|
2077
|
-
if (!command || !looksLikeCheck(command))
|
|
2078
|
-
return;
|
|
2079
|
-
if (event.isError) {
|
|
2080
|
-
failures.set(command, (failures.get(command) ?? 0) + 1);
|
|
2081
|
-
return;
|
|
2082
|
-
}
|
|
2083
|
-
failures.delete(command);
|
|
2084
|
-
edits.clear();
|
|
2085
|
-
calls.clear();
|
|
2086
|
-
checkCalls.clear();
|
|
2087
|
-
nudged = false;
|
|
2088
2106
|
});
|
|
2089
2107
|
pi.on("tool_call", (event) => {
|
|
2090
2108
|
const name = event.toolName;
|
|
@@ -2111,25 +2129,6 @@ function workSliceGuard(options) {
|
|
|
2111
2129
|
state.refusedAt ??= state.steps;
|
|
2112
2130
|
return handoff ? undefined : { block: true, reason: handoffRequest(limit, state, canCheckpoint) };
|
|
2113
2131
|
}
|
|
2114
|
-
if (handoff)
|
|
2115
|
-
return;
|
|
2116
|
-
if (name === "todo_write")
|
|
2117
|
-
return;
|
|
2118
|
-
const edit = name === "edit" || name === "write";
|
|
2119
|
-
const path = edit && event.input && typeof event.input === "object" ? String(event.input.path ?? "") : "";
|
|
2120
|
-
if (edit && path) {
|
|
2121
|
-
const count = edits.get(path) ?? 0;
|
|
2122
|
-
if (count >= 4) {
|
|
2123
|
-
const reason = `${path} was edited ${count} times with no passing check between`;
|
|
2124
|
-
return nudge(reason);
|
|
2125
|
-
}
|
|
2126
|
-
}
|
|
2127
|
-
const repeat = repeated(name, event.input);
|
|
2128
|
-
const failure = failing(name, event.input);
|
|
2129
|
-
const reason = repeat ?? failure;
|
|
2130
|
-
if (!reason)
|
|
2131
|
-
return;
|
|
2132
|
-
return nudge(reason);
|
|
2133
2132
|
});
|
|
2134
2133
|
};
|
|
2135
2134
|
}
|
|
@@ -2197,6 +2196,8 @@ function reported(parentRunId, results, spawned) {
|
|
|
2197
2196
|
return { text: JSON.stringify({ results: included, ...results.length > included.length ? { remaining: results.slice(included.length).map((result) => result.runId) } : {} }), details: { [SUBAGENT_RECEIPT]: receipt } };
|
|
2198
2197
|
}
|
|
2199
2198
|
function subagentTools(service, parentRunId) {
|
|
2199
|
+
const quota = service.quota(parentRunId);
|
|
2200
|
+
const budget = `This run allows at most ${quota.children} children: ${Object.entries(quota.profiles).map(([name, value]) => `${value} ${name}`).join(", ")}, ${quota.other} of any other profile and ${quota.unprofiled} unprofiled; a refused spawn means do the work yourself.`;
|
|
2200
2201
|
const execute = (fn) => async (input) => {
|
|
2201
2202
|
try {
|
|
2202
2203
|
return await fn(input);
|
|
@@ -2209,7 +2210,7 @@ function subagentTools(service, parentRunId) {
|
|
|
2209
2210
|
return [{
|
|
2210
2211
|
name: SPAWN_SUBAGENT,
|
|
2211
2212
|
label: "Start a subagent",
|
|
2212
|
-
description: "Start a fresh child run for independent work. Delegate substantial, bounded tasks that benefit from a separate context, not simple lookups, tiny edits or tightly coupled steps. Prefer a named specialist profile; omit agent only when no profile fits. Plan mode permits only eligible read-only research profiles. Give a short title and a self-contained brief: the child has no conversation history and no more capabilities than you. The optional tools field only narrows the profile and parent intersection; in plan mode, omit it unless you need a stricter subset. Returns its run ID immediately by default so you can continue other useful work. Results arrive automatically before you finish. Use wait_subagents when you need results before proceeding, or wait: true for an inline result. Avoid overlapping write assignments. Stopping you stops your children. To resume a child that stopped before finishing (interrupted or failed), pass continue with its run ID and no title, agent or tools: it reopens that child's own conversation with the same profile and tools, and brief becomes an optional extra instruction.",
|
|
2213
|
+
description: "Start a fresh child run for independent work. Delegate substantial, bounded tasks that benefit from a separate context, not simple lookups, tiny edits or tightly coupled steps. Prefer a named specialist profile; omit agent only when no profile fits. Plan mode permits only eligible read-only research profiles. Give a short title and a self-contained brief: the child has no conversation history and no more capabilities than you. The optional tools field only narrows the profile and parent intersection; in plan mode, omit it unless you need a stricter subset. Returns its run ID immediately by default so you can continue other useful work. Results arrive automatically before you finish. Use wait_subagents when you need results before proceeding, or wait: true for an inline result. Avoid overlapping write assignments. Stopping you stops your children. To resume a child that stopped before finishing (interrupted or failed), pass continue with its run ID and no title, agent or tools: it reopens that child's own conversation with the same profile and tools, and brief becomes an optional extra instruction. " + budget,
|
|
2213
2214
|
planModeSafe: (input) => service.planSpawnRefusal(parentRunId, input) === null,
|
|
2214
2215
|
parameters: (Type) => Type.Object({
|
|
2215
2216
|
title: Type.Optional(Type.String({ description: `Required for a new child: a short imperative title for the roster, at most ${MAX_SUBAGENT_TITLE_WORDS} words, such as "Map the auth flow"` })),
|
|
@@ -3244,8 +3245,8 @@ function browserPluginPart(engine) {
|
|
|
3244
3245
|
}
|
|
3245
3246
|
|
|
3246
3247
|
// src/annotations/store.ts
|
|
3247
|
-
import { existsSync as
|
|
3248
|
-
import { join as
|
|
3248
|
+
import { existsSync as existsSync6, lstatSync, mkdirSync as mkdirSync4, readdirSync as readdirSync4, rmSync as rmSync4 } from "fs";
|
|
3249
|
+
import { join as join8 } from "path";
|
|
3249
3250
|
var MAX_NOTES = 1e4;
|
|
3250
3251
|
var MAX_HISTORY = 100;
|
|
3251
3252
|
var codepoints = (value) => Array.from(value).length;
|
|
@@ -3378,17 +3379,17 @@ function visibleTo(note, caller) {
|
|
|
3378
3379
|
return note.grants.some((grant) => grant.principal.sessionId && grant.principal.sessionId === caller.sessionId || grant.principal.agentId && grant.principal.agentId === caller.agentId);
|
|
3379
3380
|
}
|
|
3380
3381
|
function notesDir(root) {
|
|
3381
|
-
return
|
|
3382
|
+
return join8(root, "annotations");
|
|
3382
3383
|
}
|
|
3383
3384
|
function folder(root) {
|
|
3384
3385
|
const dir = notesDir(root);
|
|
3385
|
-
if (
|
|
3386
|
+
if (existsSync6(dir) && (lstatSync(dir).isSymbolicLink() || !lstatSync(dir).isDirectory()))
|
|
3386
3387
|
throw new HarnessError("invalid_data", "Note storage must be a plain folder.");
|
|
3387
3388
|
mkdirSync4(dir, { recursive: true });
|
|
3388
3389
|
return dir;
|
|
3389
3390
|
}
|
|
3390
3391
|
function file(root, id) {
|
|
3391
|
-
return
|
|
3392
|
+
return join8(folder(root), `${safeId(id)}.json`);
|
|
3392
3393
|
}
|
|
3393
3394
|
function validNote(note, id) {
|
|
3394
3395
|
if (!note || note.id !== id || note.author !== "user" || !Number.isSafeInteger(note.version) || note.version < 1 || !Array.isArray(note.grants) || !Array.isArray(note.history)) {
|
|
@@ -3414,7 +3415,7 @@ function upgradeDelivery(note) {
|
|
|
3414
3415
|
}
|
|
3415
3416
|
function read2(root, id) {
|
|
3416
3417
|
const path = file(root, id);
|
|
3417
|
-
if (!
|
|
3418
|
+
if (!existsSync6(path))
|
|
3418
3419
|
throw notFound("Note");
|
|
3419
3420
|
if (lstatSync(path).isSymbolicLink())
|
|
3420
3421
|
throw new HarnessError("invalid_data", "Note records must not be links.");
|
|
@@ -3422,7 +3423,7 @@ function read2(root, id) {
|
|
|
3422
3423
|
}
|
|
3423
3424
|
function all2(root) {
|
|
3424
3425
|
const notes = [];
|
|
3425
|
-
for (const name of
|
|
3426
|
+
for (const name of readdirSync4(folder(root))) {
|
|
3426
3427
|
if (!name.endsWith(".json"))
|
|
3427
3428
|
continue;
|
|
3428
3429
|
try {
|
|
@@ -3465,7 +3466,7 @@ function create(root, input) {
|
|
|
3465
3466
|
const target = validateTarget(input?.target);
|
|
3466
3467
|
const body = normalizeBody(input?.body);
|
|
3467
3468
|
const tags = normalizeTags(input?.tags);
|
|
3468
|
-
if (
|
|
3469
|
+
if (readdirSync4(folder(root)).filter((name) => name.endsWith(".json")).length >= MAX_NOTES) {
|
|
3469
3470
|
throw new HarnessError("annotation_limit", `At most ${MAX_NOTES} notes may be kept.`);
|
|
3470
3471
|
}
|
|
3471
3472
|
const at = now();
|
|
@@ -3531,7 +3532,7 @@ function importNotes(root, notes) {
|
|
|
3531
3532
|
if (!id)
|
|
3532
3533
|
throw invalid("A note needs an id.");
|
|
3533
3534
|
safeId(id);
|
|
3534
|
-
if (
|
|
3535
|
+
if (existsSync6(file(root, id))) {
|
|
3535
3536
|
skipped.push({ id, reason: "exists" });
|
|
3536
3537
|
continue;
|
|
3537
3538
|
}
|
|
@@ -4739,7 +4740,7 @@ function hubServerMethods(harness) {
|
|
|
4739
4740
|
}
|
|
4740
4741
|
|
|
4741
4742
|
// src/refine/runner.ts
|
|
4742
|
-
import { join as
|
|
4743
|
+
import { join as join9 } from "path";
|
|
4743
4744
|
|
|
4744
4745
|
// src/variant/surface.ts
|
|
4745
4746
|
var SYSTEM_PROMPT = "systemprompt.md";
|
|
@@ -4795,10 +4796,10 @@ var CONFORMANCE_BLOCK = `2. CONFORMANCE. Is it ONLY what was asked for? Where th
|
|
|
4795
4796
|
|
|
4796
4797
|
// src/refine/runner.ts
|
|
4797
4798
|
function refineDir(root, id) {
|
|
4798
|
-
return
|
|
4799
|
+
return join9(root, "refine", safeId(id));
|
|
4799
4800
|
}
|
|
4800
4801
|
function readSummary(root, id) {
|
|
4801
|
-
return readJson(
|
|
4802
|
+
return readJson(join9(refineDir(root, id), "summary.json"));
|
|
4802
4803
|
}
|
|
4803
4804
|
|
|
4804
4805
|
// src/refine/serverMethods.ts
|
|
@@ -4979,15 +4980,15 @@ function historyServerMethods(harness) {
|
|
|
4979
4980
|
}
|
|
4980
4981
|
|
|
4981
4982
|
// src/agents/profiles.ts
|
|
4982
|
-
import { existsSync as
|
|
4983
|
-
import { basename as basename2, dirname as
|
|
4983
|
+
import { existsSync as existsSync8, mkdirSync as mkdirSync5, readdirSync as readdirSync6, readFileSync as readFileSync6, rmSync as rmSync5, statSync as statSync4 } from "fs";
|
|
4984
|
+
import { basename as basename2, dirname as dirname4, join as join11 } from "path";
|
|
4984
4985
|
|
|
4985
4986
|
// src/core/effort.ts
|
|
4986
4987
|
var EFFORTS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
4987
4988
|
|
|
4988
4989
|
// src/variant/materialise.ts
|
|
4989
|
-
import { existsSync as
|
|
4990
|
-
import { join as
|
|
4990
|
+
import { existsSync as existsSync7, readdirSync as readdirSync5, readFileSync as readFileSync5 } from "fs";
|
|
4991
|
+
import { join as join10 } from "path";
|
|
4991
4992
|
function frontmatter(text, field) {
|
|
4992
4993
|
const m = new RegExp(`^${field}:\\s*(.+)$`, "m").exec(text.slice(0, 600));
|
|
4993
4994
|
return m?.[1]?.trim() ?? null;
|
|
@@ -4999,10 +5000,10 @@ function bodyAfterFrontmatter(text) {
|
|
|
4999
5000
|
function subagentOf(dir, name) {
|
|
5000
5001
|
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
5001
5002
|
return null;
|
|
5002
|
-
const path =
|
|
5003
|
-
if (!
|
|
5003
|
+
const path = join10(dir, "sub_agents", name, "AGENT.md");
|
|
5004
|
+
if (!existsSync7(path))
|
|
5004
5005
|
return null;
|
|
5005
|
-
const text =
|
|
5006
|
+
const text = readFileSync5(path, "utf8");
|
|
5006
5007
|
return { name, description: frontmatter(text, "description") ?? "", instructions: bodyAfterFrontmatter(text) };
|
|
5007
5008
|
}
|
|
5008
5009
|
|
|
@@ -5109,16 +5110,16 @@ var PROFILE_COLORS = ["blue", "green", "yellow", "red", "magenta", "cyan", "oran
|
|
|
5109
5110
|
function projectRoot(cwd) {
|
|
5110
5111
|
let dir = cwd;
|
|
5111
5112
|
for (;; ) {
|
|
5112
|
-
if (
|
|
5113
|
+
if (existsSync8(join11(dir, ".git")))
|
|
5113
5114
|
return dir;
|
|
5114
|
-
const parent =
|
|
5115
|
+
const parent = dirname4(dir);
|
|
5115
5116
|
if (parent === dir)
|
|
5116
5117
|
return cwd;
|
|
5117
5118
|
dir = parent;
|
|
5118
5119
|
}
|
|
5119
5120
|
}
|
|
5120
5121
|
function profileDirs(root, cwd) {
|
|
5121
|
-
return { global:
|
|
5122
|
+
return { global: join11(root, "agents"), project: cwd ? join11(projectRoot(cwd), ".xingular", "agents") : null };
|
|
5122
5123
|
}
|
|
5123
5124
|
function stringList(value, field) {
|
|
5124
5125
|
if (value === undefined || value === null)
|
|
@@ -5203,25 +5204,25 @@ function profileText(profile) {
|
|
|
5203
5204
|
return serialize(front, profile.instructions);
|
|
5204
5205
|
}
|
|
5205
5206
|
function readFolder(dir, source, into, problems) {
|
|
5206
|
-
if (!dir || !
|
|
5207
|
+
if (!dir || !existsSync8(dir))
|
|
5207
5208
|
return;
|
|
5208
|
-
for (const file of
|
|
5209
|
-
const path =
|
|
5209
|
+
for (const file of readdirSync6(dir).filter((entry) => entry.endsWith(".md")).sort()) {
|
|
5210
|
+
const path = join11(dir, file);
|
|
5210
5211
|
const name = file.slice(0, -3);
|
|
5211
5212
|
try {
|
|
5212
|
-
if (!
|
|
5213
|
+
if (!statSync4(path).isFile())
|
|
5213
5214
|
continue;
|
|
5214
|
-
into.set(name, parseProfile(
|
|
5215
|
+
into.set(name, parseProfile(readFileSync6(path, "utf8"), name, source, path));
|
|
5215
5216
|
} catch (error) {
|
|
5216
5217
|
problems.push({ name, source, path, error: error instanceof Error ? error.message : String(error) });
|
|
5217
5218
|
}
|
|
5218
5219
|
}
|
|
5219
5220
|
}
|
|
5220
5221
|
function variantDefinitions(variantDir) {
|
|
5221
|
-
const folder = variantDir ?
|
|
5222
|
-
if (!folder || !
|
|
5222
|
+
const folder = variantDir ? join11(variantDir, "sub_agents") : null;
|
|
5223
|
+
if (!folder || !existsSync8(folder))
|
|
5223
5224
|
return [];
|
|
5224
|
-
return
|
|
5225
|
+
return readdirSync6(folder).sort().flatMap((name) => {
|
|
5225
5226
|
const definition = RESERVED_PROFILE_NAMES.includes(name) ? null : subagentOf(variantDir, name);
|
|
5226
5227
|
if (!definition)
|
|
5227
5228
|
return [];
|
|
@@ -5236,7 +5237,7 @@ function variantDefinitions(variantDir) {
|
|
|
5236
5237
|
model: null,
|
|
5237
5238
|
effort: null,
|
|
5238
5239
|
source: "variant",
|
|
5239
|
-
path:
|
|
5240
|
+
path: join11(folder, name, "AGENT.md")
|
|
5240
5241
|
}];
|
|
5241
5242
|
});
|
|
5242
5243
|
}
|
|
@@ -5299,7 +5300,7 @@ function listProfiles(root, cwd, variantDir, packageProfiles = []) {
|
|
|
5299
5300
|
profiles.set(definition.name, definition);
|
|
5300
5301
|
for (const path of packageProfiles) {
|
|
5301
5302
|
try {
|
|
5302
|
-
const profile = parsePackageProfile(
|
|
5303
|
+
const profile = parsePackageProfile(readFileSync6(path, "utf8"), path);
|
|
5303
5304
|
if (!profiles.has(profile.name))
|
|
5304
5305
|
profiles.set(profile.name, profile);
|
|
5305
5306
|
else
|
|
@@ -5342,8 +5343,8 @@ function createProfile(root, cwd, input) {
|
|
|
5342
5343
|
if (input.scope !== "global" && input.scope !== "project")
|
|
5343
5344
|
throw invalid("scope must be global or project.");
|
|
5344
5345
|
const dir = scopeDir(root, cwd, input.scope);
|
|
5345
|
-
const path =
|
|
5346
|
-
if (
|
|
5346
|
+
const path = join11(dir, `${name}.md`);
|
|
5347
|
+
if (existsSync8(path))
|
|
5347
5348
|
throw invalid(`There is already a ${input.scope} profile named ${name}.`);
|
|
5348
5349
|
let source = { ...TEMPLATE, name };
|
|
5349
5350
|
if (input.from) {
|
|
@@ -5362,8 +5363,8 @@ function removeProfile(root, cwd, input) {
|
|
|
5362
5363
|
throw invalid("That is not a profile name.");
|
|
5363
5364
|
if (input.scope !== "global" && input.scope !== "project")
|
|
5364
5365
|
throw invalid("scope must be global or project.");
|
|
5365
|
-
const path =
|
|
5366
|
-
if (!
|
|
5366
|
+
const path = join11(scopeDir(root, cwd, input.scope), `${input.name}.md`);
|
|
5367
|
+
if (!existsSync8(path))
|
|
5367
5368
|
throw notFound(`The ${input.scope} profile ${input.name}`);
|
|
5368
5369
|
rmSync5(path);
|
|
5369
5370
|
}
|
|
@@ -5430,9 +5431,9 @@ function sideQuestionServerMethods(harness) {
|
|
|
5430
5431
|
|
|
5431
5432
|
// src/core/path.ts
|
|
5432
5433
|
import { execFileSync } from "child_process";
|
|
5433
|
-
import { accessSync, constants, statSync as
|
|
5434
|
+
import { accessSync, constants, statSync as statSync5 } from "fs";
|
|
5434
5435
|
import { homedir } from "os";
|
|
5435
|
-
import { delimiter, extname, isAbsolute as isAbsolute2, join as
|
|
5436
|
+
import { delimiter, extname, isAbsolute as isAbsolute2, join as join12 } from "path";
|
|
5436
5437
|
var resolved = null;
|
|
5437
5438
|
function searchPath() {
|
|
5438
5439
|
const platform = process.platform;
|
|
@@ -5453,7 +5454,7 @@ function searchPath() {
|
|
|
5453
5454
|
if (platform !== "win32") {
|
|
5454
5455
|
const home = homedir();
|
|
5455
5456
|
if (home)
|
|
5456
|
-
entries.push(...[".local/bin", ".bun/bin", ".npm-global/bin", ".cargo/bin"].map((folder) =>
|
|
5457
|
+
entries.push(...[".local/bin", ".bun/bin", ".npm-global/bin", ".cargo/bin"].map((folder) => join12(home, folder)));
|
|
5457
5458
|
entries.push("/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin");
|
|
5458
5459
|
}
|
|
5459
5460
|
const path = [...new Set(entries.filter(Boolean))].join(separator);
|
|
@@ -5469,7 +5470,7 @@ function pathSeparator(platform) {
|
|
|
5469
5470
|
function isExecutable(path) {
|
|
5470
5471
|
try {
|
|
5471
5472
|
accessSync(path, process.platform === "win32" ? constants.F_OK : constants.X_OK);
|
|
5472
|
-
return
|
|
5473
|
+
return statSync5(path).isFile();
|
|
5473
5474
|
} catch {
|
|
5474
5475
|
return false;
|
|
5475
5476
|
}
|
|
@@ -5486,7 +5487,7 @@ function findBinary(name) {
|
|
|
5486
5487
|
}
|
|
5487
5488
|
for (const directory of searchPath().split(pathSeparator(platform))) {
|
|
5488
5489
|
for (const candidateName of names) {
|
|
5489
|
-
const candidate =
|
|
5490
|
+
const candidate = join12(directory, candidateName);
|
|
5490
5491
|
if (isExecutable(candidate))
|
|
5491
5492
|
return candidate;
|
|
5492
5493
|
}
|
|
@@ -5632,7 +5633,7 @@ function connectedAppServerMethods(harness) {
|
|
|
5632
5633
|
}
|
|
5633
5634
|
|
|
5634
5635
|
// src/tools/dispatch.ts
|
|
5635
|
-
import { existsSync as existsSync9, readdirSync as
|
|
5636
|
+
import { existsSync as existsSync9, readdirSync as readdirSync7, readFileSync as readFileSync7 } from "fs";
|
|
5636
5637
|
import { join as join16 } from "path";
|
|
5637
5638
|
|
|
5638
5639
|
// src/accounts/store.ts
|
|
@@ -5843,11 +5844,11 @@ function readTool2(env, context, params) {
|
|
|
5843
5844
|
}
|
|
5844
5845
|
|
|
5845
5846
|
// src/plugins/proposals.ts
|
|
5846
|
-
import { createHash
|
|
5847
|
-
import { dirname as
|
|
5847
|
+
import { createHash, randomUUID as randomUUID2 } from "crypto";
|
|
5848
|
+
import { dirname as dirname5, join as join15 } from "path";
|
|
5848
5849
|
|
|
5849
5850
|
// src/pi/runtime.ts
|
|
5850
|
-
import { join as
|
|
5851
|
+
import { join as join13 } from "path";
|
|
5851
5852
|
import { pathToFileURL } from "url";
|
|
5852
5853
|
var PINNED_PI_VERSION = "1.4.0";
|
|
5853
5854
|
var HTTP_DISPATCHER_CHUNK = "dist/bundle/chunks/chunk-MM3LKT73.js";
|
|
@@ -5876,10 +5877,10 @@ function createPiLoader(importPi, importDispatcher) {
|
|
|
5876
5877
|
return loading;
|
|
5877
5878
|
};
|
|
5878
5879
|
}
|
|
5879
|
-
var loadPi = createPiLoader(() => import("@earendil-works/pi-coding-agent"), async (packageDir) => await import(pathToFileURL(
|
|
5880
|
+
var loadPi = createPiLoader(() => import("@earendil-works/pi-coding-agent"), async (packageDir) => await import(pathToFileURL(join13(packageDir, HTTP_DISPATCHER_CHUNK)).href));
|
|
5880
5881
|
|
|
5881
5882
|
// src/plugins/manifest.ts
|
|
5882
|
-
import { basename as basename3, join as
|
|
5883
|
+
import { basename as basename3, join as join14 } from "path";
|
|
5883
5884
|
import { z as z3 } from "zod";
|
|
5884
5885
|
var connectorTemplateSchema = z3.object({
|
|
5885
5886
|
id: z3.string().regex(/^[a-z0-9-]+$/),
|
|
@@ -5919,14 +5920,14 @@ var PLUGIN_MANIFESTS = ["plugin.json", ".claude-plugin/plugin.json", ".codex-plu
|
|
|
5919
5920
|
var text6 = (value) => typeof value === "string" && value.trim() ? value.trim() : null;
|
|
5920
5921
|
function pluginJson(packageRoot) {
|
|
5921
5922
|
for (const file of PLUGIN_MANIFESTS) {
|
|
5922
|
-
const found = readJsonOr(
|
|
5923
|
+
const found = readJsonOr(join14(packageRoot, file), null);
|
|
5923
5924
|
if (found && typeof found === "object" && !Array.isArray(found))
|
|
5924
5925
|
return found;
|
|
5925
5926
|
}
|
|
5926
5927
|
return {};
|
|
5927
5928
|
}
|
|
5928
5929
|
function packageManifest(packageRoot) {
|
|
5929
|
-
const manifest = readJsonOr(
|
|
5930
|
+
const manifest = readJsonOr(join14(packageRoot, "package.json"), {});
|
|
5930
5931
|
const plugin = text6(manifest.name) ? {} : pluginJson(packageRoot);
|
|
5931
5932
|
const own = manifest.harness && typeof manifest.harness === "object" && !Array.isArray(manifest.harness) ? manifest.harness : {};
|
|
5932
5933
|
const pluginName = text6(plugin.name);
|
|
@@ -5951,8 +5952,8 @@ var SKIPPED = new Set(["node_modules", ".git"]);
|
|
|
5951
5952
|
var MAX_FILES = 100;
|
|
5952
5953
|
var MAX_FILE_BYTES = 256 * 1024;
|
|
5953
5954
|
var MAX_TOTAL_BYTES = 1024 * 1024;
|
|
5954
|
-
var dir = (root) =>
|
|
5955
|
-
var pathOf = (root, id) =>
|
|
5955
|
+
var dir = (root) => join15(root, "plugin-proposals");
|
|
5956
|
+
var pathOf = (root, id) => join15(dir(root), `${safeId(id)}.json`);
|
|
5956
5957
|
function validate2(name, description, input) {
|
|
5957
5958
|
if (typeof name !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name))
|
|
5958
5959
|
throw invalid("Plugin name must be lowercase letters, digits, underscores or hyphens.");
|
|
@@ -5989,7 +5990,7 @@ function validate2(name, description, input) {
|
|
|
5989
5990
|
throw invalid("A file cannot also be a directory.");
|
|
5990
5991
|
const manifest = `${JSON.stringify({ name, version: "1.0.0", description }, null, 2)}
|
|
5991
5992
|
`;
|
|
5992
|
-
const hash =
|
|
5993
|
+
const hash = createHash("sha256").update(JSON.stringify([name, description, manifest, Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)])).digest("hex");
|
|
5993
5994
|
return { name, description, files, manifest, hash };
|
|
5994
5995
|
}
|
|
5995
5996
|
function create2(root, name, description, files) {
|
|
@@ -5999,26 +6000,6 @@ function create2(root, name, description, files) {
|
|
|
5999
6000
|
return proposal;
|
|
6000
6001
|
}
|
|
6001
6002
|
|
|
6002
|
-
// src/tools/defaultSkills.ts
|
|
6003
|
-
import { existsSync as existsSync8 } from "fs";
|
|
6004
|
-
import { dirname as dirname5, join as join15 } from "path";
|
|
6005
|
-
import { fileURLToPath } from "url";
|
|
6006
|
-
function defaultSkillPath() {
|
|
6007
|
-
let dir = dirname5(fileURLToPath(import.meta.url));
|
|
6008
|
-
for (;; ) {
|
|
6009
|
-
const path = join15(dir, "builtin", "skills", "plugin-authoring", "SKILL.md");
|
|
6010
|
-
if (existsSync8(path))
|
|
6011
|
-
return path;
|
|
6012
|
-
const parent = dirname5(dir);
|
|
6013
|
-
if (parent === dir)
|
|
6014
|
-
throw new Error("The bundled plugin-authoring skill is missing.");
|
|
6015
|
-
dir = parent;
|
|
6016
|
-
}
|
|
6017
|
-
}
|
|
6018
|
-
function defaultSkillPaths(variantDir) {
|
|
6019
|
-
return variantDir && existsSync8(join15(variantDir, "skills", "plugin-authoring", "SKILL.md")) ? [] : [defaultSkillPath()];
|
|
6020
|
-
}
|
|
6021
|
-
|
|
6022
6003
|
// src/tools/dispatch.ts
|
|
6023
6004
|
function str(params, key) {
|
|
6024
6005
|
const value = params[key];
|
|
@@ -6077,25 +6058,24 @@ ${tail}` : ""}`;
|
|
|
6077
6058
|
}
|
|
6078
6059
|
}
|
|
6079
6060
|
function loadSkill(variantDir, name) {
|
|
6080
|
-
const skills = variantDir && existsSync9(join16(variantDir, "skills")) ?
|
|
6081
|
-
|
|
6082
|
-
if (defaults.length)
|
|
6061
|
+
const skills = variantDir && existsSync9(join16(variantDir, "skills")) ? readdirSync7(join16(variantDir, "skills"), { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync9(join16(variantDir, "skills", entry.name, "SKILL.md"))).map((entry) => entry.name).sort() : [];
|
|
6062
|
+
if (!skills.includes("plugin-authoring") && defaultSkillPaths(variantDir).length)
|
|
6083
6063
|
skills.push("plugin-authoring");
|
|
6084
6064
|
skills.sort();
|
|
6085
6065
|
const wanted = name.trim().replace(/^skills\//, "").replace(/`/g, "");
|
|
6086
6066
|
if (!wanted)
|
|
6087
6067
|
return skills.length ? `Your skills: ${skills.join(", ")}. Load one with skill_load and its name.` : "You have no skills.";
|
|
6088
|
-
if (
|
|
6068
|
+
if (!SKILL_NAME.test(wanted))
|
|
6089
6069
|
throw invalid("A skill name is lowercase letters, digits, _ or -.");
|
|
6090
6070
|
if (!skills.includes(wanted))
|
|
6091
6071
|
return `There is no skill named ${wanted}.${skills.length ? ` Your skills: ${skills.join(", ")}.` : ""}`;
|
|
6092
|
-
|
|
6093
|
-
|
|
6094
|
-
|
|
6095
|
-
const
|
|
6096
|
-
return `${readFileSync6(join16(dir, "SKILL.md"), "utf8")}${helpers.length ? `
|
|
6072
|
+
const skill = readSkillFile(variantDir, wanted);
|
|
6073
|
+
if (!skill)
|
|
6074
|
+
return `There is no skill named ${wanted}.${skills.length ? ` Your skills: ${skills.join(", ")}.` : ""}`;
|
|
6075
|
+
const helperNote = skill.helpers.length ? `
|
|
6097
6076
|
|
|
6098
|
-
(This skill's helpers are in ${join16(
|
|
6077
|
+
(This skill's helpers are in ${join16(skill.baseDir, "scripts")}: ${skill.helpers.join(", ")}.)` : "";
|
|
6078
|
+
return `${readFileSync7(skill.path, "utf8")}${helperNote}`;
|
|
6099
6079
|
}
|
|
6100
6080
|
|
|
6101
6081
|
// src/tools/harnessTools.ts
|
|
@@ -6286,6 +6266,7 @@ var VARIANT_PLUGIN = {
|
|
|
6286
6266
|
{ id: "memory", name: "Memory", description: "c3: durable facts about this kind of work." },
|
|
6287
6267
|
{ id: "subagents", name: "Subagents", description: "c5: the list of this variant's subagents." },
|
|
6288
6268
|
{ id: "scripts", name: "Scripts", description: "c7: where this variant's scripts are." },
|
|
6269
|
+
{ id: "required-skills", name: "Required skills", description: "Skills the person named as required for one request." },
|
|
6289
6270
|
{ id: "reporting", name: "Reporting", description: "Fixed foundation text, not part of the variant: how the final reply is shaped." }
|
|
6290
6271
|
],
|
|
6291
6272
|
tools: tools(SKILL_TOOLS)
|
|
@@ -6692,7 +6673,80 @@ import { matchesKey as matchesKey4, truncateToWidth as truncateToWidth4 } from "
|
|
|
6692
6673
|
import { fuzzyFilter, matchesKey as matchesKey3, parseColor as parseColor2, truncateToWidth as truncateToWidth3, visibleWidth as visibleWidth4 } from "@earendil-works/pi-tui";
|
|
6693
6674
|
|
|
6694
6675
|
// src/terminal/tui/search.ts
|
|
6695
|
-
import {
|
|
6676
|
+
import { matchesKey as matchesKey2, truncateToWidth as truncateToWidth2, visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
|
|
6677
|
+
|
|
6678
|
+
// src/terminal/tui/mouseReport.ts
|
|
6679
|
+
import { Input } from "@earendil-works/pi-tui";
|
|
6680
|
+
var MOUSE_REPORT_TAIL_WINDOW_MS = 200;
|
|
6681
|
+
var REPORT = /^<\d{1,3};\d{1,4};\d{1,4}[Mm]$/;
|
|
6682
|
+
var PARTIAL = /^<\d{0,3}(;\d{0,4}){0,2}$/;
|
|
6683
|
+
var WHOLE = /^(?:\x1b\[)?<\d{1,3};\d{1,4};\d{1,4}[Mm]$/;
|
|
6684
|
+
var SGR_REPORT = /\x1b\[<\d+;\d+;\d+[Mm]|\\u001b\[<\d+;\d+;\d+[Mm]|\\x1b\[<\d+;\d+;\d+[Mm]/g;
|
|
6685
|
+
var X10_REPORT = /\x1b\[M[\u0020-\u00ff]{3}/g;
|
|
6686
|
+
|
|
6687
|
+
class MouseReportTail {
|
|
6688
|
+
text = "";
|
|
6689
|
+
startedAt = 0;
|
|
6690
|
+
push(sequence, nowMs = Date.now()) {
|
|
6691
|
+
if (WHOLE.test(sequence)) {
|
|
6692
|
+
this.reset();
|
|
6693
|
+
return { report: sequence.replace(/^\x1b\[/, ""), inserted: "" };
|
|
6694
|
+
}
|
|
6695
|
+
if (sequence.length !== 1) {
|
|
6696
|
+
this.reset();
|
|
6697
|
+
return;
|
|
6698
|
+
}
|
|
6699
|
+
if (sequence === "<") {
|
|
6700
|
+
this.text = "<";
|
|
6701
|
+
this.startedAt = nowMs;
|
|
6702
|
+
return;
|
|
6703
|
+
}
|
|
6704
|
+
if (!this.text)
|
|
6705
|
+
return;
|
|
6706
|
+
if (nowMs - this.startedAt > MOUSE_REPORT_TAIL_WINDOW_MS) {
|
|
6707
|
+
this.reset();
|
|
6708
|
+
return;
|
|
6709
|
+
}
|
|
6710
|
+
const next = this.text + sequence;
|
|
6711
|
+
if (REPORT.test(next)) {
|
|
6712
|
+
const inserted = this.text;
|
|
6713
|
+
this.reset();
|
|
6714
|
+
return { report: next, inserted };
|
|
6715
|
+
}
|
|
6716
|
+
if (!PARTIAL.test(next)) {
|
|
6717
|
+
this.reset();
|
|
6718
|
+
return;
|
|
6719
|
+
}
|
|
6720
|
+
this.text = next;
|
|
6721
|
+
return;
|
|
6722
|
+
}
|
|
6723
|
+
reset() {
|
|
6724
|
+
this.text = "";
|
|
6725
|
+
this.startedAt = 0;
|
|
6726
|
+
}
|
|
6727
|
+
}
|
|
6728
|
+
|
|
6729
|
+
class MouseSafeInput extends Input {
|
|
6730
|
+
mouseTail = new MouseReportTail;
|
|
6731
|
+
handleInput(data) {
|
|
6732
|
+
super.handleInput(data);
|
|
6733
|
+
const match = this.mouseTail.push(data);
|
|
6734
|
+
if (!match)
|
|
6735
|
+
return;
|
|
6736
|
+
const value = this.getValue();
|
|
6737
|
+
if (value.endsWith(match.report))
|
|
6738
|
+
this.setValue(value.slice(0, -match.report.length));
|
|
6739
|
+
}
|
|
6740
|
+
setValue(value) {
|
|
6741
|
+
this.mouseTail.reset();
|
|
6742
|
+
super.setValue(value);
|
|
6743
|
+
}
|
|
6744
|
+
}
|
|
6745
|
+
function stripMouseReports(text) {
|
|
6746
|
+
return text.replace(SGR_REPORT, "").replace(X10_REPORT, "");
|
|
6747
|
+
}
|
|
6748
|
+
|
|
6749
|
+
// src/terminal/tui/search.ts
|
|
6696
6750
|
var SEARCH_GLYPH = "\u2315";
|
|
6697
6751
|
var SEARCH_PLACEHOLDER = "Type to search";
|
|
6698
6752
|
var SEARCH_FIELD_ROWS = 5;
|
|
@@ -6709,7 +6763,7 @@ class SearchField {
|
|
|
6709
6763
|
input;
|
|
6710
6764
|
constructor(theme, placeholder = SEARCH_PLACEHOLDER) {
|
|
6711
6765
|
this.theme = theme;
|
|
6712
|
-
this.input = new
|
|
6766
|
+
this.input = new MouseSafeInput({ prompt: "", placeholder, placeholderStyle: (text) => this.theme().fg("dim", text) });
|
|
6713
6767
|
}
|
|
6714
6768
|
get value() {
|
|
6715
6769
|
return this.input.getValue();
|
|
@@ -11278,7 +11332,7 @@ var payloadOf2 = (event) => event.payload && typeof event.payload === "object" ?
|
|
|
11278
11332
|
var stringOf2 = (value) => typeof value === "string" ? value : undefined;
|
|
11279
11333
|
var numberOf2 = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
11280
11334
|
function safe2(value) {
|
|
11281
|
-
return stripTerminalSequences4(value).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, " ");
|
|
11335
|
+
return stripTerminalSequences4(stripMouseReports(value)).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, " ");
|
|
11282
11336
|
}
|
|
11283
11337
|
function timeOf2(value) {
|
|
11284
11338
|
const parsed = Date.parse(value);
|
|
@@ -11514,8 +11568,8 @@ class TrajectoryPage {
|
|
|
11514
11568
|
return this.events.map((event) => ({
|
|
11515
11569
|
id: String(event.sequence),
|
|
11516
11570
|
label: `${timeOf2(event.timestamp)} ${event.type}`,
|
|
11517
|
-
detail: eventDescription(event),
|
|
11518
|
-
searchText: `${event.timestamp} ${event.type} ${eventDescription(event)} ${safe2(JSON.stringify(payloadOf2(event)))}`,
|
|
11571
|
+
detail: safe2(eventDescription(event)),
|
|
11572
|
+
searchText: `${event.timestamp} ${event.type} ${safe2(eventDescription(event))} ${safe2(JSON.stringify(payloadOf2(event)))}`,
|
|
11519
11573
|
data: event
|
|
11520
11574
|
}));
|
|
11521
11575
|
}
|
|
@@ -11654,7 +11708,7 @@ class TrajectoryPage {
|
|
|
11654
11708
|
if (rows >= 4)
|
|
11655
11709
|
lines.push(theme.fg("muted", usageLine(this.events)));
|
|
11656
11710
|
if (rows >= 6)
|
|
11657
|
-
lines.push(theme.fg("dim", this.run.goal ? `Prompt: ${this.run.goal.replace(/\s+/g, " ").slice(0, 140)}` : "Prompt text unavailable"));
|
|
11711
|
+
lines.push(theme.fg("dim", this.run.goal ? `Prompt: ${safe2(this.run.goal).replace(/\s+/g, " ").slice(0, 140)}` : "Prompt text unavailable"));
|
|
11658
11712
|
if (this.error)
|
|
11659
11713
|
lines.push(theme.fg("error", `Read error: ${this.error}`));
|
|
11660
11714
|
return lines.slice(0, Math.min(rows, 5)).map((line) => truncateToWidth14(line, width, ""));
|
|
@@ -11961,7 +12015,7 @@ class WorktreesPage {
|
|
|
11961
12015
|
}
|
|
11962
12016
|
|
|
11963
12017
|
// src/terminal/tui/pages/annotatePage.ts
|
|
11964
|
-
import {
|
|
12018
|
+
import { matchesKey as matchesKey15, truncateToWidth as truncateToWidth16, visibleWidth as visibleWidth10 } from "@earendil-works/pi-tui";
|
|
11965
12019
|
|
|
11966
12020
|
// src/terminal/tui/annotateCommand.ts
|
|
11967
12021
|
function normalizeAddress(text) {
|
|
@@ -12233,7 +12287,7 @@ class AnnotatePage {
|
|
|
12233
12287
|
return "Load the bridge script in the app (shown at the top), then reload the app.";
|
|
12234
12288
|
}
|
|
12235
12289
|
openField(kind) {
|
|
12236
|
-
const input = new
|
|
12290
|
+
const input = new MouseSafeInput({ prompt: "", placeholder: FIELDS[kind].placeholder, placeholderStyle: (text) => this.options.theme().fg("dim", text) });
|
|
12237
12291
|
this.field = { kind, input };
|
|
12238
12292
|
this.syncFocus();
|
|
12239
12293
|
this.options.changed();
|
|
@@ -13029,6 +13083,10 @@ import { Theme } from "@earendil-works/pi-coding-agent";
|
|
|
13029
13083
|
* SOFTWARE.
|
|
13030
13084
|
*/
|
|
13031
13085
|
var orange = { dark: "#ffb347", light: "#9a7326" };
|
|
13086
|
+
var SERIES_COLORS = {
|
|
13087
|
+
dark: ["#3987e5", "#d95926", "#199e70", "#c98500"],
|
|
13088
|
+
light: ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
|
|
13089
|
+
};
|
|
13032
13090
|
var TITANIUM = {
|
|
13033
13091
|
brushedTitanium: "#151820",
|
|
13034
13092
|
darkTitanium: "#0f1216",
|
|
@@ -13950,90 +14008,737 @@ class UsagePage {
|
|
|
13950
14008
|
}
|
|
13951
14009
|
}
|
|
13952
14010
|
|
|
13953
|
-
// src/terminal/tui/
|
|
13954
|
-
|
|
13955
|
-
var
|
|
13956
|
-
|
|
13957
|
-
|
|
13958
|
-
|
|
13959
|
-
|
|
13960
|
-
|
|
13961
|
-
|
|
13962
|
-
|
|
13963
|
-
|
|
13964
|
-
|
|
13965
|
-
|
|
13966
|
-
|
|
13967
|
-
|
|
13968
|
-
|
|
13969
|
-
|
|
13970
|
-
|
|
13971
|
-
|
|
13972
|
-
|
|
13973
|
-
|
|
13974
|
-
|
|
13975
|
-
|
|
13976
|
-
|
|
13977
|
-
|
|
13978
|
-
|
|
13979
|
-
|
|
13980
|
-
|
|
13981
|
-
|
|
13982
|
-
|
|
13983
|
-
|
|
13984
|
-
|
|
13985
|
-
|
|
13986
|
-
|
|
13987
|
-
|
|
13988
|
-
|
|
13989
|
-
|
|
13990
|
-
|
|
13991
|
-
|
|
13992
|
-
|
|
13993
|
-
|
|
13994
|
-
|
|
13995
|
-
|
|
13996
|
-
|
|
13997
|
-
|
|
13998
|
-
|
|
13999
|
-
|
|
14000
|
-
|
|
14001
|
-
|
|
14002
|
-
|
|
14003
|
-
|
|
14004
|
-
|
|
14005
|
-
|
|
14006
|
-
|
|
14007
|
-
|
|
14008
|
-
|
|
14009
|
-
|
|
14010
|
-
|
|
14011
|
-
|
|
14012
|
-
|
|
14013
|
-
|
|
14014
|
-
|
|
14015
|
-
|
|
14016
|
-
|
|
14017
|
-
|
|
14018
|
-
|
|
14019
|
-
|
|
14020
|
-
|
|
14021
|
-
|
|
14022
|
-
label: "Private address access",
|
|
14023
|
-
value: browserSettings.allowPrivate ? "On" : "Off",
|
|
14024
|
-
description: "This device-wide setting affects agent browsing and annotation capture. When on, pages can reach localhost and private networks."
|
|
14025
|
-
});
|
|
14026
|
-
return result.sort((a, b) => GROUP_ORDER.indexOf(a.group) - GROUP_ORDER.indexOf(b.group));
|
|
14011
|
+
// src/terminal/tui/pages/contextPage.ts
|
|
14012
|
+
import { matchesKey as matchesKey18, parseColor as parseColor4, truncateToWidth as truncateToWidth22, visibleWidth as visibleWidth14, wrapTextWithAnsi as wrapTextWithAnsi14 } from "@earendil-works/pi-tui";
|
|
14013
|
+
var BARS2 = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
|
|
14014
|
+
var CHARS = 4;
|
|
14015
|
+
var OWNER_TITLES = {
|
|
14016
|
+
foundation: "Foundation \xB7 harness",
|
|
14017
|
+
variant: "Variant",
|
|
14018
|
+
application: "Your application",
|
|
14019
|
+
conversation: "Conversation",
|
|
14020
|
+
reserved: "Reserved and free"
|
|
14021
|
+
};
|
|
14022
|
+
var OWNER_ORDER = ["foundation", "variant", "application", "conversation", "reserved"];
|
|
14023
|
+
var KIND_ORDER = ["System prompt", "Tools", "Memory", "Skills", "Messages", "Reserved"];
|
|
14024
|
+
function kindOf(row) {
|
|
14025
|
+
if (row.group === "reserved")
|
|
14026
|
+
return "Reserved";
|
|
14027
|
+
if (row.id === "messages" || row.id === "context-update" || row.id === "references" || row.id === "required-skills" || row.id === "wiki" || row.id === "session-state")
|
|
14028
|
+
return "Messages";
|
|
14029
|
+
if (row.id === "memory")
|
|
14030
|
+
return "Memory";
|
|
14031
|
+
if (row.id === "skills")
|
|
14032
|
+
return "Skills";
|
|
14033
|
+
if (row.id === "tools" || row.id === "tools-harness" || row.id === "tools-application" || row.id === "tool-guidance")
|
|
14034
|
+
return "Tools";
|
|
14035
|
+
return "System prompt";
|
|
14036
|
+
}
|
|
14037
|
+
function count3(value) {
|
|
14038
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
14039
|
+
return "0";
|
|
14040
|
+
if (value >= 1e6)
|
|
14041
|
+
return `${(value / 1e6).toFixed(value % 1e6 === 0 ? 0 : 1)}M`;
|
|
14042
|
+
if (value >= 1000)
|
|
14043
|
+
return `${(value / 1000).toFixed(1)}K`;
|
|
14044
|
+
return String(Math.round(value));
|
|
14045
|
+
}
|
|
14046
|
+
function percent(value) {
|
|
14047
|
+
return value === null ? "?" : `${value.toFixed(1)}%`;
|
|
14048
|
+
}
|
|
14049
|
+
function tone(share) {
|
|
14050
|
+
if (share === null)
|
|
14051
|
+
return "dim";
|
|
14052
|
+
if (share >= 95)
|
|
14053
|
+
return "error";
|
|
14054
|
+
if (share >= 80)
|
|
14055
|
+
return "warning";
|
|
14056
|
+
return "success";
|
|
14057
|
+
}
|
|
14058
|
+
var SERIES_LABELS = {
|
|
14059
|
+
foundation: "foundation",
|
|
14060
|
+
variant: "variant",
|
|
14061
|
+
application: "your app",
|
|
14062
|
+
conversation: "conversation",
|
|
14063
|
+
reserved: "reserved"
|
|
14064
|
+
};
|
|
14065
|
+
function seriesColor(theme, index) {
|
|
14066
|
+
const palette = theme.appearance === "light" ? SERIES_COLORS.light : SERIES_COLORS.dark;
|
|
14067
|
+
return palette[index] ?? palette[palette.length - 1];
|
|
14068
|
+
}
|
|
14069
|
+
function allocateCells(values, total) {
|
|
14070
|
+
const cells = Math.max(0, Math.floor(total));
|
|
14071
|
+
const sum = values.reduce((acc, value) => acc + Math.max(0, value), 0);
|
|
14072
|
+
if (sum <= 0 || cells <= 0)
|
|
14073
|
+
return values.map(() => 0);
|
|
14074
|
+
const present = values.map((value, index) => ({ value: Math.max(0, value), index })).filter((entry) => entry.value > 0);
|
|
14075
|
+
if (cells < present.length) {
|
|
14076
|
+
const out = values.map(() => 0);
|
|
14077
|
+
for (const entry of [...present].sort((left, right) => right.value - left.value).slice(0, cells))
|
|
14078
|
+
out[entry.index] = 1;
|
|
14079
|
+
return out;
|
|
14027
14080
|
}
|
|
14028
|
-
|
|
14029
|
-
|
|
14030
|
-
|
|
14031
|
-
|
|
14032
|
-
|
|
14081
|
+
const exact = values.map((value) => Math.max(0, value) / sum * cells);
|
|
14082
|
+
const out = exact.map((value) => Math.floor(value));
|
|
14083
|
+
let left = cells - out.reduce((acc, value) => acc + value, 0);
|
|
14084
|
+
for (const entry of exact.map((value, index) => ({ rest: value - Math.floor(value), index })).sort((left_, right) => right.rest - left_.rest)) {
|
|
14085
|
+
if (left <= 0)
|
|
14086
|
+
break;
|
|
14087
|
+
out[entry.index] = (out[entry.index] ?? 0) + 1;
|
|
14088
|
+
left -= 1;
|
|
14033
14089
|
}
|
|
14034
|
-
|
|
14035
|
-
if (
|
|
14036
|
-
|
|
14090
|
+
for (const entry of present) {
|
|
14091
|
+
if ((out[entry.index] ?? 0) > 0)
|
|
14092
|
+
continue;
|
|
14093
|
+
const donor = out.map((value, index) => ({ value, index })).filter((candidate) => candidate.index !== entry.index && candidate.value > 1).sort((a, b) => b.value - a.value)[0];
|
|
14094
|
+
if (!donor)
|
|
14095
|
+
break;
|
|
14096
|
+
out[donor.index] = (out[donor.index] ?? 0) - 1;
|
|
14097
|
+
out[entry.index] = 1;
|
|
14098
|
+
}
|
|
14099
|
+
return out;
|
|
14100
|
+
}
|
|
14101
|
+
function contextBar(data, width, theme) {
|
|
14102
|
+
const room = Math.max(1, width - 2);
|
|
14103
|
+
const parts = OWNER_ORDER.slice(0, 4).map((group, index) => ({ group, tokens: data.totals[group], color: seriesColor(theme, index) })).filter((part) => part.tokens > 0);
|
|
14104
|
+
const window = data.window;
|
|
14105
|
+
const share = window === null || window <= 0 ? 100 : Math.min(100, data.used / window * 100);
|
|
14106
|
+
const filled = Math.max(0, Math.min(room, Math.round(share / 100 * room)));
|
|
14107
|
+
const cells = allocateCells(parts.map((part) => part.tokens), filled);
|
|
14108
|
+
const runs = parts.flatMap((part, index) => (cells[index] ?? 0) > 0 ? [{ text: "\u2588".repeat(cells[index]), color: part.color }] : []);
|
|
14109
|
+
const trackCells = Math.max(0, room - filled);
|
|
14110
|
+
const reserve = data.compaction?.reserveTokens ?? null;
|
|
14111
|
+
const markerAt = reserve !== null && window !== null && window > 0 ? Math.round((data.used + reserve) / window * room) : null;
|
|
14112
|
+
const inTrack = markerAt !== null && markerAt >= filled && markerAt < room ? markerAt - filled : null;
|
|
14113
|
+
const bar = "[" + runs.map((run) => theme.style(run.text, { fg: parseColor4(run.color) })).join("") + (trackCells > 0 ? theme.fg("dim", "\u2591".repeat(inTrack ?? trackCells)) + (inTrack === null ? "" : theme.fg("warning", "\u2502") + theme.fg("dim", "\u2591".repeat(Math.max(0, trackCells - inTrack - 1)))) : inTrack === null ? "" : theme.fg("warning", "\u2502")) + "]";
|
|
14114
|
+
const entries = parts.map((part) => ({ text: `\u258C${SERIES_LABELS[part.group]} ${count3(part.tokens)}`, color: part.color }));
|
|
14115
|
+
entries.push({ text: `free ${data.free === null ? "?" : count3(data.free)}`, color: null });
|
|
14116
|
+
if (reserve !== null)
|
|
14117
|
+
entries.push({ text: `\u2502 compaction at ${count3(Math.min(window ?? data.used + reserve, data.used + reserve))}`, color: null });
|
|
14118
|
+
const legend = [];
|
|
14119
|
+
let line = "";
|
|
14120
|
+
for (const entry of entries) {
|
|
14121
|
+
const piece = entry.color ? theme.style(entry.text, { fg: parseColor4(entry.color) }) : theme.fg("dim", entry.text);
|
|
14122
|
+
const candidate = line ? `${line} ${piece}` : piece;
|
|
14123
|
+
if (line && visibleWidth14(candidate) > width) {
|
|
14124
|
+
legend.push(line);
|
|
14125
|
+
line = piece;
|
|
14126
|
+
} else
|
|
14127
|
+
line = candidate;
|
|
14128
|
+
}
|
|
14129
|
+
if (line)
|
|
14130
|
+
legend.push(line);
|
|
14131
|
+
return { bar, legend };
|
|
14132
|
+
}
|
|
14133
|
+
function spread2(left, right, width) {
|
|
14134
|
+
if (!right)
|
|
14135
|
+
return truncateToWidth22(left, width, "");
|
|
14136
|
+
const room = Math.max(0, width - visibleWidth14(left) - 2);
|
|
14137
|
+
const value = truncateToWidth22(right, room, "");
|
|
14138
|
+
return left + " ".repeat(Math.max(1, width - visibleWidth14(left) - visibleWidth14(value))) + value;
|
|
14139
|
+
}
|
|
14140
|
+
|
|
14141
|
+
class ContextPage {
|
|
14142
|
+
options;
|
|
14143
|
+
presentation = "fullscreen";
|
|
14144
|
+
focused = false;
|
|
14145
|
+
tab;
|
|
14146
|
+
grouping = "owner";
|
|
14147
|
+
data = null;
|
|
14148
|
+
detail = null;
|
|
14149
|
+
selectedId = null;
|
|
14150
|
+
folded = new Set;
|
|
14151
|
+
offset = 0;
|
|
14152
|
+
detailOffset = 0;
|
|
14153
|
+
maxOffset = 0;
|
|
14154
|
+
scrollRows = 1;
|
|
14155
|
+
busy = false;
|
|
14156
|
+
reloadPending = false;
|
|
14157
|
+
error = null;
|
|
14158
|
+
disposed = false;
|
|
14159
|
+
constructor(options) {
|
|
14160
|
+
this.options = options;
|
|
14161
|
+
this.tab = options.initialTab ?? "request";
|
|
14162
|
+
}
|
|
14163
|
+
tabs() {
|
|
14164
|
+
return [{ id: "request", title: "Request" }, { id: "growth", title: "Growth" }];
|
|
14165
|
+
}
|
|
14166
|
+
activeTab() {
|
|
14167
|
+
return this.tab;
|
|
14168
|
+
}
|
|
14169
|
+
selectTab(id) {
|
|
14170
|
+
if (id !== "request" && id !== "growth")
|
|
14171
|
+
return;
|
|
14172
|
+
if (id === this.tab)
|
|
14173
|
+
return;
|
|
14174
|
+
this.tab = id;
|
|
14175
|
+
this.offset = 0;
|
|
14176
|
+
this.detail = null;
|
|
14177
|
+
this.options.changed();
|
|
14178
|
+
if (!this.data)
|
|
14179
|
+
this.load();
|
|
14180
|
+
}
|
|
14181
|
+
hint() {
|
|
14182
|
+
if (this.detail)
|
|
14183
|
+
return "\u2191/\u2193 scroll \xB7 esc close \xB7 q close page";
|
|
14184
|
+
return this.tab === "request" ? "\u2191/\u2193 move \xB7 space fold \xB7 enter text \xB7 g group \xB7 c compact \xB7 v variant \xB7 r refresh \xB7 q close" : "\u2191/\u2193 scroll \xB7 r refresh \xB7 q close";
|
|
14185
|
+
}
|
|
14186
|
+
activate() {
|
|
14187
|
+
if (!this.data)
|
|
14188
|
+
this.load();
|
|
14189
|
+
}
|
|
14190
|
+
dispose() {
|
|
14191
|
+
this.disposed = true;
|
|
14192
|
+
}
|
|
14193
|
+
async load(section) {
|
|
14194
|
+
if (this.disposed)
|
|
14195
|
+
return;
|
|
14196
|
+
if (this.busy) {
|
|
14197
|
+
this.reloadPending = true;
|
|
14198
|
+
return;
|
|
14199
|
+
}
|
|
14200
|
+
this.busy = true;
|
|
14201
|
+
this.error = null;
|
|
14202
|
+
this.options.changed();
|
|
14203
|
+
try {
|
|
14204
|
+
const answer = await this.options.call("terminal.context", section ? { section } : {});
|
|
14205
|
+
if (this.disposed)
|
|
14206
|
+
return;
|
|
14207
|
+
this.data = answer.attribution ?? null;
|
|
14208
|
+
if (!this.entries().some((entry) => entry.row.id === this.selectedId))
|
|
14209
|
+
this.selectedId = this.entries()[0]?.row.id ?? null;
|
|
14210
|
+
if (section) {
|
|
14211
|
+
if (answer.text)
|
|
14212
|
+
this.detail = answer.text;
|
|
14213
|
+
else
|
|
14214
|
+
this.error = "That row carries no text: it is measured, not written.";
|
|
14215
|
+
this.detailOffset = 0;
|
|
14216
|
+
}
|
|
14217
|
+
} catch (cause) {
|
|
14218
|
+
this.error = cause instanceof Error ? cause.message : "The context could not be read.";
|
|
14219
|
+
} finally {
|
|
14220
|
+
this.busy = false;
|
|
14221
|
+
this.options.changed();
|
|
14222
|
+
if (this.reloadPending) {
|
|
14223
|
+
this.reloadPending = false;
|
|
14224
|
+
this.load();
|
|
14225
|
+
}
|
|
14226
|
+
}
|
|
14227
|
+
}
|
|
14228
|
+
handleInput(data) {
|
|
14229
|
+
if (this.detail) {
|
|
14230
|
+
const page = Math.max(1, this.scrollRows - 2);
|
|
14231
|
+
if (matchesKey18(data, "up"))
|
|
14232
|
+
this.detailOffset = Math.max(0, this.detailOffset - 1);
|
|
14233
|
+
else if (matchesKey18(data, "down"))
|
|
14234
|
+
this.detailOffset += 1;
|
|
14235
|
+
else if (matchesKey18(data, "pageUp"))
|
|
14236
|
+
this.detailOffset = Math.max(0, this.detailOffset - page);
|
|
14237
|
+
else if (matchesKey18(data, "pageDown"))
|
|
14238
|
+
this.detailOffset += page;
|
|
14239
|
+
else if (matchesKey18(data, "escape") || data === "q") {
|
|
14240
|
+
this.detail = null;
|
|
14241
|
+
this.options.changed();
|
|
14242
|
+
} else
|
|
14243
|
+
return false;
|
|
14244
|
+
this.options.changed();
|
|
14245
|
+
return true;
|
|
14246
|
+
}
|
|
14247
|
+
if (matchesKey18(data, "tab") || matchesKey18(data, "shift+tab")) {
|
|
14248
|
+
const tabs = ["request", "growth"];
|
|
14249
|
+
const direction = matchesKey18(data, "shift+tab") ? -1 : 1;
|
|
14250
|
+
this.selectTab(tabs[(tabs.indexOf(this.tab) + direction + tabs.length) % tabs.length]);
|
|
14251
|
+
return true;
|
|
14252
|
+
}
|
|
14253
|
+
const entries = this.entries();
|
|
14254
|
+
const found = entries.findIndex((entry) => entry.row.id === this.selectedId);
|
|
14255
|
+
const current = found >= 0 ? found : 0;
|
|
14256
|
+
if (!entries.length)
|
|
14257
|
+
return false;
|
|
14258
|
+
if (matchesKey18(data, "up"))
|
|
14259
|
+
this.move(entries, current - 1);
|
|
14260
|
+
else if (matchesKey18(data, "down"))
|
|
14261
|
+
this.move(entries, current + 1);
|
|
14262
|
+
else if (matchesKey18(data, "home"))
|
|
14263
|
+
this.offset = 0;
|
|
14264
|
+
else if (matchesKey18(data, "end"))
|
|
14265
|
+
this.offset = this.maxOffset;
|
|
14266
|
+
else if (data === " " && entries[current]) {
|
|
14267
|
+
const row = entries[current].row;
|
|
14268
|
+
if (this.folded.has(row.group))
|
|
14269
|
+
this.folded.delete(row.group);
|
|
14270
|
+
else
|
|
14271
|
+
this.folded.add(row.group);
|
|
14272
|
+
} else if (matchesKey18(data, "enter") && entries[current]) {
|
|
14273
|
+
this.load(entries[current].row.id);
|
|
14274
|
+
return true;
|
|
14275
|
+
} else if (data === "g") {
|
|
14276
|
+
this.grouping = this.grouping === "owner" ? "kind" : "owner";
|
|
14277
|
+
this.folded.clear();
|
|
14278
|
+
this.offset = 0;
|
|
14279
|
+
} else if (data === "r") {
|
|
14280
|
+
this.load();
|
|
14281
|
+
return true;
|
|
14282
|
+
} else if (data === "c") {
|
|
14283
|
+
this.compact();
|
|
14284
|
+
return true;
|
|
14285
|
+
} else if (data === "v") {
|
|
14286
|
+
this.options.openVariant?.();
|
|
14287
|
+
return true;
|
|
14288
|
+
} else
|
|
14289
|
+
return false;
|
|
14290
|
+
this.options.changed();
|
|
14291
|
+
return true;
|
|
14292
|
+
}
|
|
14293
|
+
move(entries, index) {
|
|
14294
|
+
if (!entries.length)
|
|
14295
|
+
return;
|
|
14296
|
+
const next = entries[Math.max(0, Math.min(entries.length - 1, index))];
|
|
14297
|
+
if (next)
|
|
14298
|
+
this.selectedId = next.row.id;
|
|
14299
|
+
}
|
|
14300
|
+
async compact() {
|
|
14301
|
+
if (!this.options.compact)
|
|
14302
|
+
return;
|
|
14303
|
+
const free = this.data?.free === null || this.data?.free === undefined ? null : this.data.free;
|
|
14304
|
+
const question = free === null ? "Pi will summarize this conversation and start the next request from the summary." : `Pi will summarize this conversation. About ${count3(free)} tokens are free before it does.`;
|
|
14305
|
+
if (this.options.confirm && !await this.options.confirm("Compact the conversation now?", question))
|
|
14306
|
+
return;
|
|
14307
|
+
try {
|
|
14308
|
+
await this.options.compact();
|
|
14309
|
+
await this.load();
|
|
14310
|
+
} catch (cause) {
|
|
14311
|
+
this.error = cause instanceof Error ? cause.message : "Compaction failed.";
|
|
14312
|
+
this.options.changed();
|
|
14313
|
+
}
|
|
14314
|
+
}
|
|
14315
|
+
entries() {
|
|
14316
|
+
const rows = this.data?.rows ?? [];
|
|
14317
|
+
if (this.grouping === "owner") {
|
|
14318
|
+
const ordered = [...rows].sort((left, right) => OWNER_ORDER.indexOf(left.group) - OWNER_ORDER.indexOf(right.group));
|
|
14319
|
+
const out = [];
|
|
14320
|
+
for (const row of ordered) {
|
|
14321
|
+
const previous = out.at(-1)?.row.group;
|
|
14322
|
+
out.push({ row, heading: previous === row.group ? null : OWNER_TITLES[row.group] ?? row.group, folded: this.folded.has(row.group) });
|
|
14323
|
+
}
|
|
14324
|
+
return out;
|
|
14325
|
+
}
|
|
14326
|
+
const ordered = [...rows].sort((left, right) => KIND_ORDER.indexOf(kindOf(left)) - KIND_ORDER.indexOf(kindOf(right)));
|
|
14327
|
+
const out = [];
|
|
14328
|
+
let last = null;
|
|
14329
|
+
for (const row of ordered) {
|
|
14330
|
+
const kind = kindOf(row);
|
|
14331
|
+
const folded = this.folded.has(kind);
|
|
14332
|
+
out.push({ row, heading: last === kind ? null : kind, folded });
|
|
14333
|
+
last = kind;
|
|
14334
|
+
}
|
|
14335
|
+
return out;
|
|
14336
|
+
}
|
|
14337
|
+
render(width, rows) {
|
|
14338
|
+
if (width < 1 || rows < 1)
|
|
14339
|
+
return [];
|
|
14340
|
+
const theme = this.options.theme();
|
|
14341
|
+
const body = this.detail ? this.detailBody(width, theme) : this.tab === "growth" ? this.growthBody(width, theme) : this.requestBody(width, theme);
|
|
14342
|
+
const room = Math.max(1, rows);
|
|
14343
|
+
this.scrollRows = room;
|
|
14344
|
+
this.maxOffset = Math.max(0, body.length - room);
|
|
14345
|
+
const wanted = this.detail ? this.detailOffset : this.offset;
|
|
14346
|
+
const offset = Math.max(0, Math.min(wanted, this.maxOffset));
|
|
14347
|
+
if (this.detail)
|
|
14348
|
+
this.detailOffset = offset;
|
|
14349
|
+
else
|
|
14350
|
+
this.offset = offset;
|
|
14351
|
+
return body.slice(offset, offset + room).map((line) => truncateToWidth22(line, width, ""));
|
|
14352
|
+
}
|
|
14353
|
+
requestBody(width, theme) {
|
|
14354
|
+
const data = this.data;
|
|
14355
|
+
if (!data) {
|
|
14356
|
+
return [padded(theme.fg(this.error ? "error" : "dim", this.error ?? (this.busy ? "Reading the recorded context\u2026" : "No reply yet: the next request records what it is made of.")), width)];
|
|
14357
|
+
}
|
|
14358
|
+
const inner = Math.max(8, width - CHROME_PAD * 2);
|
|
14359
|
+
const body = [];
|
|
14360
|
+
body.push(padded(spread2(theme.fg("text", `${count3(data.used)} of ${data.window === null ? "an unknown window" : count3(data.window)}`), theme.fg(tone(data.share), `${percent(data.share)} used \xB7 ${data.source}`), inner), width));
|
|
14361
|
+
const chart = contextBar(data, inner, theme);
|
|
14362
|
+
body.push(padded(chart.bar, width));
|
|
14363
|
+
for (const line of chart.legend)
|
|
14364
|
+
body.push(padded(line, width));
|
|
14365
|
+
body.push("");
|
|
14366
|
+
for (const entry of this.entries()) {
|
|
14367
|
+
if (entry.heading) {
|
|
14368
|
+
const total = data.rows.filter((row) => this.grouping === "owner" ? OWNER_TITLES[row.group] === entry.heading : kindOf(row) === entry.heading).reduce((sum, row) => sum + row.tokens, 0);
|
|
14369
|
+
const owner = this.grouping === "owner" ? OWNER_ORDER.find((group) => OWNER_TITLES[group] === entry.heading) : undefined;
|
|
14370
|
+
const swatch = owner ? theme.style("\u2588 ", { fg: parseColor4(seriesColor(theme, OWNER_ORDER.indexOf(owner))) }) : "";
|
|
14371
|
+
body.push(padded(swatch + theme.bold(theme.fg("accent", entry.heading)) + theme.fg("dim", ` ${count3(total)}`), width));
|
|
14372
|
+
}
|
|
14373
|
+
if (entry.folded)
|
|
14374
|
+
continue;
|
|
14375
|
+
body.push(this.rowLine(entry.row, inner, width, theme));
|
|
14376
|
+
}
|
|
14377
|
+
if (data.onDemand.length) {
|
|
14378
|
+
body.push("");
|
|
14379
|
+
body.push(padded(theme.fg("accent", "On demand") + theme.fg("dim", " not in this request"), width));
|
|
14380
|
+
for (const item of data.onDemand) {
|
|
14381
|
+
const cost = item.tokensEach === null ? item.note ?? "" : `about ${count3(item.tokensEach)} each \xB7 ${item.note ?? ""}`;
|
|
14382
|
+
body.push(padded(` ${theme.fg("text", item.title)} ${theme.fg("dim", `${item.items} available \xB7 ${cost}`)}`, width));
|
|
14383
|
+
}
|
|
14384
|
+
}
|
|
14385
|
+
if (data.note) {
|
|
14386
|
+
body.push("");
|
|
14387
|
+
body.push(...wrapTextWithAnsi14(theme.fg("dim", data.note), inner).map((line) => padded(line, width)));
|
|
14388
|
+
}
|
|
14389
|
+
if (this.error)
|
|
14390
|
+
body.push(padded(theme.fg("error", this.error), width));
|
|
14391
|
+
return body;
|
|
14392
|
+
}
|
|
14393
|
+
rowLine(row, inner, width, theme) {
|
|
14394
|
+
const selected = row.id === this.selectedId;
|
|
14395
|
+
const marker = selected ? "\u276F " : row.always ? " " : "\xB7 ";
|
|
14396
|
+
const tail = `${count3(row.tokens).padStart(7)}${percent(row.share).padStart(7)}`;
|
|
14397
|
+
const extras = [
|
|
14398
|
+
row.note ? row.note : "",
|
|
14399
|
+
row.budget ? `${count3(row.chars ?? row.tokens * CHARS)} of ${count3(row.budget)} chars` : "",
|
|
14400
|
+
row.tools?.length ? row.tools.map((tool) => `${tool.group} ${tool.count}`).join(" \xB7 ") : ""
|
|
14401
|
+
].filter(Boolean);
|
|
14402
|
+
const room = () => Math.max(12, inner - visibleWidth14(tail) - 1 - (extras.length ? visibleWidth14(extras.join(" ")) + 2 : 0));
|
|
14403
|
+
let left = truncateToWidth22(`${marker}${row.title}`, room(), "\u2026");
|
|
14404
|
+
while (extras.length && visibleWidth14(left) + visibleWidth14(tail) + 2 + visibleWidth14(extras.join(" ")) > inner)
|
|
14405
|
+
extras.pop();
|
|
14406
|
+
const rest = extras.join(" ");
|
|
14407
|
+
const gap = Math.max(1, inner - visibleWidth14(left) - visibleWidth14(tail) - (rest ? visibleWidth14(rest) + 2 : 0));
|
|
14408
|
+
const line = `${left}${" ".repeat(gap)}${rest ? theme.fg("dim", rest) + " " : ""}${tail}`;
|
|
14409
|
+
if (selected)
|
|
14410
|
+
return selectedRow(padded(line, width), width, theme);
|
|
14411
|
+
return padded(line, width);
|
|
14412
|
+
}
|
|
14413
|
+
growthBody(width, theme) {
|
|
14414
|
+
const data = this.data;
|
|
14415
|
+
if (!data)
|
|
14416
|
+
return [padded(theme.fg("dim", this.busy ? "Reading the recorded context\u2026" : "No reply yet."), width)];
|
|
14417
|
+
const inner = Math.max(8, width - CHROME_PAD * 2);
|
|
14418
|
+
const body = [];
|
|
14419
|
+
const history = data.history.slice(-24);
|
|
14420
|
+
if (history.length) {
|
|
14421
|
+
const peak = Math.max(...history.map((point) => point.used), 1);
|
|
14422
|
+
const spark = history.map((point) => BARS2[Math.min(BARS2.length - 1, Math.round(point.used / peak * (BARS2.length - 1)))]).join("");
|
|
14423
|
+
body.push(padded(theme.fg("accent", spark), width));
|
|
14424
|
+
body.push(padded(theme.fg("dim", `${history.length} requests \xB7 peak ${count3(peak)}${data.compactions.length ? ` \xB7 ${data.compactions.length} compaction${data.compactions.length === 1 ? "" : "s"}` : ""}`), width));
|
|
14425
|
+
} else {
|
|
14426
|
+
body.push(padded(theme.fg("dim", "No measured request yet."), width));
|
|
14427
|
+
}
|
|
14428
|
+
body.push("");
|
|
14429
|
+
body.push(padded(spread2(theme.fg("dim", "REQUEST"), theme.fg("dim", "USED SHARE"), inner), width));
|
|
14430
|
+
for (const point of history.slice().reverse().slice(0, 12)) {
|
|
14431
|
+
body.push(padded(spread2(` ${point.request}`, `${count3(point.used).padStart(8)}${percent(point.share).padStart(8)}`, inner), width));
|
|
14432
|
+
}
|
|
14433
|
+
for (const compaction of data.compactions.slice(-3)) {
|
|
14434
|
+
const before = compaction.before === null ? "?" : count3(compaction.before);
|
|
14435
|
+
const after = compaction.after === null ? "?" : count3(compaction.after);
|
|
14436
|
+
body.push(padded(theme.fg("warning", ` compacted ${before} \u2192 ${after}`), width));
|
|
14437
|
+
}
|
|
14438
|
+
body.push("");
|
|
14439
|
+
body.push(...wrapTextWithAnsi14(theme.fg("dim", data.note ?? ""), inner).filter(Boolean).map((line) => padded(line, width)));
|
|
14440
|
+
return body;
|
|
14441
|
+
}
|
|
14442
|
+
detailBody(width, theme) {
|
|
14443
|
+
const detail = this.detail;
|
|
14444
|
+
const inner = Math.max(8, width - CHROME_PAD * 2);
|
|
14445
|
+
const body = [];
|
|
14446
|
+
body.push(padded(theme.bold(theme.fg("accent", detail.title)), width));
|
|
14447
|
+
body.push("");
|
|
14448
|
+
for (const line of detail.text.split(`
|
|
14449
|
+
`)) {
|
|
14450
|
+
if (!line.trim()) {
|
|
14451
|
+
body.push("");
|
|
14452
|
+
continue;
|
|
14453
|
+
}
|
|
14454
|
+
for (const wrapped of wrapTextWithAnsi14(theme.fg("text", line), inner))
|
|
14455
|
+
body.push(padded(wrapped, width));
|
|
14456
|
+
}
|
|
14457
|
+
return body;
|
|
14458
|
+
}
|
|
14459
|
+
}
|
|
14460
|
+
|
|
14461
|
+
// src/terminal/tui/pages/remoteControlPage.ts
|
|
14462
|
+
import { truncateToWidth as truncateToWidth23, visibleWidth as visibleWidth15, wrapTextWithAnsi as wrapTextWithAnsi15 } from "@earendil-works/pi-tui";
|
|
14463
|
+
|
|
14464
|
+
// src/terminal/tui/qr.ts
|
|
14465
|
+
import { encode } from "uqr";
|
|
14466
|
+
var QUIET = 2;
|
|
14467
|
+
var LIGHT_ON_DARK = "\x1B[38;5;231;48;5;16m";
|
|
14468
|
+
var RESET = "\x1B[0m";
|
|
14469
|
+
function qrModules(text) {
|
|
14470
|
+
const { data } = encode(text, { ecc: "L", border: 0 });
|
|
14471
|
+
const size = data.length + QUIET * 2;
|
|
14472
|
+
const blank = () => Array.from({ length: size }, () => false);
|
|
14473
|
+
return [
|
|
14474
|
+
...Array.from({ length: QUIET }, blank),
|
|
14475
|
+
...data.map((row) => [...Array.from({ length: QUIET }, () => false), ...row, ...Array.from({ length: QUIET }, () => false)]),
|
|
14476
|
+
...Array.from({ length: QUIET }, blank)
|
|
14477
|
+
];
|
|
14478
|
+
}
|
|
14479
|
+
function qrLines(text) {
|
|
14480
|
+
const modules = qrModules(text);
|
|
14481
|
+
const lines = [];
|
|
14482
|
+
for (let y = 0;y < modules.length; y += 2) {
|
|
14483
|
+
const top = modules[y];
|
|
14484
|
+
const bottom = modules[y + 1] ?? top.map(() => false);
|
|
14485
|
+
let line = "";
|
|
14486
|
+
for (let x = 0;x < top.length; x += 1) {
|
|
14487
|
+
const a = top[x];
|
|
14488
|
+
const b = bottom[x];
|
|
14489
|
+
line += !a && !b ? "\u2588" : !a && b ? "\u2580" : a && !b ? "\u2584" : " ";
|
|
14490
|
+
}
|
|
14491
|
+
lines.push(`${LIGHT_ON_DARK}${line}${RESET}`);
|
|
14492
|
+
}
|
|
14493
|
+
return lines;
|
|
14494
|
+
}
|
|
14495
|
+
|
|
14496
|
+
// src/terminal/tui/pages/remoteControlPage.ts
|
|
14497
|
+
var KIND_LABEL = { tailscale: "Tailscale", lan: "Wi-Fi" };
|
|
14498
|
+
|
|
14499
|
+
class RemoteControlPage {
|
|
14500
|
+
options;
|
|
14501
|
+
presentation = "fullscreen";
|
|
14502
|
+
status = null;
|
|
14503
|
+
error = null;
|
|
14504
|
+
showQr = true;
|
|
14505
|
+
busy = false;
|
|
14506
|
+
disposed = false;
|
|
14507
|
+
watching = null;
|
|
14508
|
+
constructor(options) {
|
|
14509
|
+
this.options = options;
|
|
14510
|
+
}
|
|
14511
|
+
tabs() {
|
|
14512
|
+
return [{ id: "remote", title: "Remote Control" }];
|
|
14513
|
+
}
|
|
14514
|
+
activeTab() {
|
|
14515
|
+
return "remote";
|
|
14516
|
+
}
|
|
14517
|
+
hint() {
|
|
14518
|
+
const status = this.status;
|
|
14519
|
+
if (status?.request)
|
|
14520
|
+
return "a allow \xB7 d deny";
|
|
14521
|
+
if (!status?.running)
|
|
14522
|
+
return "s start";
|
|
14523
|
+
const parts = ["space QR", "c copy link", "n new link"];
|
|
14524
|
+
if (status.kinds.length > 1)
|
|
14525
|
+
parts.push(`t use ${status.kind === "tailscale" ? "Wi-Fi" : "Tailscale"}`);
|
|
14526
|
+
parts.push("x stop");
|
|
14527
|
+
return parts.join(" \xB7 ");
|
|
14528
|
+
}
|
|
14529
|
+
activate() {
|
|
14530
|
+
this.watch();
|
|
14531
|
+
}
|
|
14532
|
+
dispose() {
|
|
14533
|
+
this.disposed = true;
|
|
14534
|
+
this.watching?.abort();
|
|
14535
|
+
}
|
|
14536
|
+
async watch() {
|
|
14537
|
+
const watching = new AbortController;
|
|
14538
|
+
this.watching = watching;
|
|
14539
|
+
let revision;
|
|
14540
|
+
while (!this.disposed && !watching.signal.aborted) {
|
|
14541
|
+
try {
|
|
14542
|
+
const status = await this.options.call(revision === undefined ? "terminal.remoteControl.status" : "terminal.remoteControl.status.wait", { revision });
|
|
14543
|
+
if (this.disposed)
|
|
14544
|
+
return;
|
|
14545
|
+
this.status = status;
|
|
14546
|
+
this.error = null;
|
|
14547
|
+
revision = status.revision;
|
|
14548
|
+
} catch (error) {
|
|
14549
|
+
if (this.disposed)
|
|
14550
|
+
return;
|
|
14551
|
+
this.error = error instanceof Error ? error.message : String(error);
|
|
14552
|
+
revision = undefined;
|
|
14553
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
14554
|
+
}
|
|
14555
|
+
this.options.changed();
|
|
14556
|
+
}
|
|
14557
|
+
}
|
|
14558
|
+
async act(method, params = {}, done) {
|
|
14559
|
+
if (this.busy)
|
|
14560
|
+
return;
|
|
14561
|
+
this.busy = true;
|
|
14562
|
+
this.options.changed();
|
|
14563
|
+
try {
|
|
14564
|
+
this.status = await this.options.call(method, params);
|
|
14565
|
+
this.error = null;
|
|
14566
|
+
if (done)
|
|
14567
|
+
this.options.notify(done);
|
|
14568
|
+
} catch (error) {
|
|
14569
|
+
this.error = error instanceof Error ? error.message : String(error);
|
|
14570
|
+
} finally {
|
|
14571
|
+
this.busy = false;
|
|
14572
|
+
this.options.changed();
|
|
14573
|
+
}
|
|
14574
|
+
}
|
|
14575
|
+
handleInput(data) {
|
|
14576
|
+
const status = this.status;
|
|
14577
|
+
if (status?.request) {
|
|
14578
|
+
if (data === "a" || data === "y")
|
|
14579
|
+
this.act("terminal.remoteControl.confirm", { requestId: status.request.id, allow: true }, `${status.request.label} can now control this session.`);
|
|
14580
|
+
else if (data === "d" || data === "n")
|
|
14581
|
+
this.act("terminal.remoteControl.confirm", { requestId: status.request.id, allow: false });
|
|
14582
|
+
return true;
|
|
14583
|
+
}
|
|
14584
|
+
if (!status?.running) {
|
|
14585
|
+
if (data === "s")
|
|
14586
|
+
this.act("terminal.remoteControl.start");
|
|
14587
|
+
return data === "s";
|
|
14588
|
+
}
|
|
14589
|
+
if (data === " ")
|
|
14590
|
+
this.showQr = !this.showQr;
|
|
14591
|
+
else if (data === "c" && status.url)
|
|
14592
|
+
this.options.copy(status.url).then(() => this.options.notify("Remote-control link copied"), (error) => this.options.notify(error instanceof Error ? error.message : String(error), "error"));
|
|
14593
|
+
else if (data === "n")
|
|
14594
|
+
this.act("terminal.remoteControl.rotate", {}, "New link. Paired devices were disconnected.");
|
|
14595
|
+
else if (data === "t" && status.kinds.length > 1)
|
|
14596
|
+
this.act("terminal.remoteControl.start", { interface: status.kind === "tailscale" ? "lan" : "tailscale" });
|
|
14597
|
+
else if (data === "x")
|
|
14598
|
+
this.act("terminal.remoteControl.stop", {}, "Remote control stopped.");
|
|
14599
|
+
else
|
|
14600
|
+
return false;
|
|
14601
|
+
return true;
|
|
14602
|
+
}
|
|
14603
|
+
render(width, rows) {
|
|
14604
|
+
const theme = this.options.theme();
|
|
14605
|
+
const status = this.status;
|
|
14606
|
+
const lines = [];
|
|
14607
|
+
const wrap = (text, color = "text") => {
|
|
14608
|
+
for (const line of wrapTextWithAnsi15(text, Math.max(1, width)))
|
|
14609
|
+
lines.push(theme.fg(color, line));
|
|
14610
|
+
};
|
|
14611
|
+
if (this.error) {
|
|
14612
|
+
wrap(this.error, "error");
|
|
14613
|
+
lines.push("");
|
|
14614
|
+
}
|
|
14615
|
+
if (!status) {
|
|
14616
|
+
wrap("Starting remote control\u2026", "dim");
|
|
14617
|
+
return lines.slice(0, rows);
|
|
14618
|
+
}
|
|
14619
|
+
if (status.request) {
|
|
14620
|
+
wrap(`${safeText(status.request.label)} wants to control this session.`, "warning");
|
|
14621
|
+
wrap("It will be able to send messages, stop replies, and answer approvals and questions. Press a to allow or d to deny.", "text");
|
|
14622
|
+
lines.push("");
|
|
14623
|
+
}
|
|
14624
|
+
if (!status.running) {
|
|
14625
|
+
wrap("Remote control is off.", "dim");
|
|
14626
|
+
wrap("Press s to start it, then scan the QR code with your phone or iPad.", "dim");
|
|
14627
|
+
return lines.slice(0, rows);
|
|
14628
|
+
}
|
|
14629
|
+
const kind = status.kind ? KIND_LABEL[status.kind] : "";
|
|
14630
|
+
lines.push(theme.fg("success", "\u25CF ") + theme.bold(`Remote control is on${kind ? ` \xB7 ${kind}` : ""}`));
|
|
14631
|
+
wrap(status.kind === "tailscale" ? "Scan with a phone or iPad signed in to the same Tailscale network, or open this link on it:" : "Scan with a phone or iPad on the same Wi-Fi, or open this link on it:", "dim");
|
|
14632
|
+
if (status.url)
|
|
14633
|
+
wrap(status.url, "accent");
|
|
14634
|
+
if (status.warning)
|
|
14635
|
+
wrap(safeText(status.warning), "warning");
|
|
14636
|
+
if (status.kind === "lan")
|
|
14637
|
+
wrap("On a network you do not trust, use Tailscale instead: anyone there can see that this computer is listening.", "dim");
|
|
14638
|
+
const devices = status.devices.length ? status.devices.map((device) => `${device.connected ? theme.fg("success", "\u25CF") : theme.fg("dim", "\u25CB")} ${safeText(device.label)}${device.connected ? "" : theme.fg("dim", " (paired, not connected)")}`) : [theme.fg("dim", "No device paired yet.")];
|
|
14639
|
+
const footer = ["", ...devices];
|
|
14640
|
+
if (this.showQr && status.url) {
|
|
14641
|
+
const qr = qrLines(status.url);
|
|
14642
|
+
const room = rows - lines.length - footer.length - 1;
|
|
14643
|
+
const qrWidth = visibleWidth15(qr[0] ?? "");
|
|
14644
|
+
if (qr.length <= room && qrWidth <= width) {
|
|
14645
|
+
lines.push("");
|
|
14646
|
+
const pad = " ".repeat(Math.max(0, Math.floor((width - qrWidth) / 2)));
|
|
14647
|
+
for (const line of qr)
|
|
14648
|
+
lines.push(pad + line);
|
|
14649
|
+
} else {
|
|
14650
|
+
lines.push("", theme.fg("dim", "Make the terminal larger to show the QR code, or press c to copy the link."));
|
|
14651
|
+
}
|
|
14652
|
+
}
|
|
14653
|
+
lines.push(...footer);
|
|
14654
|
+
return lines.slice(0, rows).map((line) => truncateToWidth23(line, width, ""));
|
|
14655
|
+
}
|
|
14656
|
+
}
|
|
14657
|
+
|
|
14658
|
+
// src/terminal/tui/settingsModel.ts
|
|
14659
|
+
var PRIVATE_ACCESS_ID = "browser.allowPrivate";
|
|
14660
|
+
var GROUP_ORDER = ["Theme", "Display", "Images", "Thinking", "Recovery", "Editor", "Queues", "Commands", "Terminal", "Keyboard", "Compaction", "Network"];
|
|
14661
|
+
function createSettingsModel(host) {
|
|
14662
|
+
let browserSettings = null;
|
|
14663
|
+
const booleans = (session) => {
|
|
14664
|
+
const settings = session.settingsManager;
|
|
14665
|
+
return [
|
|
14666
|
+
["Auto compaction", () => session.autoCompactionEnabled, (value) => session.setAutoCompactionEnabled(value)],
|
|
14667
|
+
["Auto retry", () => session.autoRetryEnabled, (value) => session.setAutoRetryEnabled(value)],
|
|
14668
|
+
["Show images", () => settings.getShowImages(), (value) => settings.setShowImages(value)],
|
|
14669
|
+
["Resize images", () => settings.getImageAutoResize(), (value) => settings.setImageAutoResize(value)],
|
|
14670
|
+
["Block images", () => settings.getBlockImages(), (value) => settings.setBlockImages(value)],
|
|
14671
|
+
["Skill commands", () => settings.getEnableSkillCommands(), (value) => settings.setEnableSkillCommands(value)],
|
|
14672
|
+
["Hide thinking", () => settings.getHideThinkingBlock(), (value) => settings.setHideThinkingBlock(value)],
|
|
14673
|
+
["Hardware cursor", () => settings.getShowHardwareCursor(), (value) => settings.setShowHardwareCursor(value)],
|
|
14674
|
+
["Terminal progress", () => settings.getShowTerminalProgress(), (value) => settings.setShowTerminalProgress(value)]
|
|
14675
|
+
];
|
|
14676
|
+
};
|
|
14677
|
+
const locations = [
|
|
14678
|
+
["Context", "Compaction"],
|
|
14679
|
+
["Model", "Recovery"],
|
|
14680
|
+
["Appearance", "Images"],
|
|
14681
|
+
["Appearance", "Images"],
|
|
14682
|
+
["Context", "Images"],
|
|
14683
|
+
["Interaction", "Commands"],
|
|
14684
|
+
["Appearance", "Display"],
|
|
14685
|
+
["Interaction", "Editor"],
|
|
14686
|
+
["Interaction", "Terminal"],
|
|
14687
|
+
["Model", "Thinking"],
|
|
14688
|
+
["Interaction", "Queues"],
|
|
14689
|
+
["Interaction", "Queues"],
|
|
14690
|
+
["Appearance", "Theme"],
|
|
14691
|
+
["Interaction", "Keyboard"]
|
|
14692
|
+
];
|
|
14693
|
+
const descriptions = [
|
|
14694
|
+
"Compact the context automatically when the session approaches its limit.",
|
|
14695
|
+
"Retry eligible provider failures automatically.",
|
|
14696
|
+
"Display actual image content returned by tools.",
|
|
14697
|
+
"Resize image attachments before provider requests.",
|
|
14698
|
+
"Block image attachments in provider requests.",
|
|
14699
|
+
"Expose commands for the skills loaded in this session.",
|
|
14700
|
+
"Collapse assistant thinking blocks in the transcript.",
|
|
14701
|
+
"Display the terminal hardware cursor for editing and input methods.",
|
|
14702
|
+
"Report active work through supported terminal progress controls.",
|
|
14703
|
+
"Reasoning effort for the current model.",
|
|
14704
|
+
"Delivery mode for messages that steer an active run.",
|
|
14705
|
+
"Delivery mode for messages queued after a run.",
|
|
14706
|
+
"Theme loaded from the trusted resource catalog.",
|
|
14707
|
+
"View the current application keyboard bindings."
|
|
14708
|
+
];
|
|
14709
|
+
const options = (session) => [
|
|
14710
|
+
...booleans(session).map(([label, get]) => `${label}: ${get() ? "on" : "off"}`),
|
|
14711
|
+
`Thinking: ${session.thinkingLevel}`,
|
|
14712
|
+
`Steering: ${session.steeringMode}`,
|
|
14713
|
+
`Follow-up: ${session.followUpMode}`,
|
|
14714
|
+
`Theme: ${host.ui.theme.name}`,
|
|
14715
|
+
"Keyboard controls"
|
|
14716
|
+
];
|
|
14717
|
+
function items() {
|
|
14718
|
+
const result = options(host.session()).map((option, index) => {
|
|
14719
|
+
const split = option.indexOf(":");
|
|
14720
|
+
return { id: String(index), tab: locations[index][0], group: locations[index][1], label: split < 0 ? option : option.slice(0, split), value: split < 0 ? "" : option.slice(split + 1).trim(), description: descriptions[index] };
|
|
14721
|
+
});
|
|
14722
|
+
if (browserSettings)
|
|
14723
|
+
result.push({
|
|
14724
|
+
id: PRIVATE_ACCESS_ID,
|
|
14725
|
+
tab: "Browser",
|
|
14726
|
+
group: "Network",
|
|
14727
|
+
label: "Private address access",
|
|
14728
|
+
value: browserSettings.allowPrivate ? "On" : "Off",
|
|
14729
|
+
description: "This device-wide setting affects agent browsing and annotation capture. When on, pages can reach localhost and private networks."
|
|
14730
|
+
});
|
|
14731
|
+
return result.sort((a, b) => GROUP_ORDER.indexOf(a.group) - GROUP_ORDER.indexOf(b.group));
|
|
14732
|
+
}
|
|
14733
|
+
async function load() {
|
|
14734
|
+
const config = await host.control("terminal.browser.config");
|
|
14735
|
+
if (!config || typeof config.allowPrivate !== "boolean")
|
|
14736
|
+
throw new Error("The Harness returned invalid browser settings.");
|
|
14737
|
+
browserSettings = { allowPrivate: config.allowPrivate };
|
|
14738
|
+
}
|
|
14739
|
+
async function apply(id) {
|
|
14740
|
+
if (id === PRIVATE_ACCESS_ID) {
|
|
14741
|
+
if (!browserSettings)
|
|
14037
14742
|
return;
|
|
14038
14743
|
const allowPrivate = !browserSettings.allowPrivate;
|
|
14039
14744
|
if (allowPrivate && !await host.ui.confirm("Allow private network addresses?", "This device-wide setting lets pages opened by agent browsing and annotation capture reach localhost and private networks."))
|
|
@@ -14086,6 +14791,20 @@ function createCommandPage(host, id, options = {}) {
|
|
|
14086
14791
|
const theme = () => host.ui.theme;
|
|
14087
14792
|
const notify = (message, type) => host.ui.notify(message, type === "error" || type === "warning" ? type : "info");
|
|
14088
14793
|
switch (id) {
|
|
14794
|
+
case "remote-control":
|
|
14795
|
+
return new RemoteControlPage({ theme, call: host.control, changed: host.changed, copy: host.copyText, notify });
|
|
14796
|
+
case "context":
|
|
14797
|
+
return new ContextPage({
|
|
14798
|
+
theme,
|
|
14799
|
+
call: host.control,
|
|
14800
|
+
changed: host.changed,
|
|
14801
|
+
initialTab: options.contextTab === "growth" ? "growth" : "request",
|
|
14802
|
+
openVariant: () => options.navigate?.("harness"),
|
|
14803
|
+
compact: async () => {
|
|
14804
|
+
await host.session().compact?.();
|
|
14805
|
+
},
|
|
14806
|
+
confirm: (title, message) => host.ui.confirm(title, message)
|
|
14807
|
+
});
|
|
14089
14808
|
case "usage":
|
|
14090
14809
|
return new UsagePage({ theme, call: host.control, changed: host.changed, initialTab: options.usageTab === "limit" ? "limits" : options.usageTab === "accounts" ? "accounts" : "analysis", ...options.usagePeriod ? { initialPeriod: options.usagePeriod } : {} });
|
|
14091
14810
|
case "doctor":
|
|
@@ -14378,15 +15097,6 @@ class ResumeSessionsPage {
|
|
|
14378
15097
|
}
|
|
14379
15098
|
}
|
|
14380
15099
|
|
|
14381
|
-
// src/terminal/tui/skillInvocation.ts
|
|
14382
|
-
function expandSkillInvocation(text, skills) {
|
|
14383
|
-
const trimmed = text.trimStart();
|
|
14384
|
-
const match = /^\$(\S+)(?=\s|$)/.exec(trimmed);
|
|
14385
|
-
if (!match || !skills.has(match[1]))
|
|
14386
|
-
return text;
|
|
14387
|
-
return `/skill:${match[1]}${trimmed.slice(match[0].length)}`;
|
|
14388
|
-
}
|
|
14389
|
-
|
|
14390
15100
|
// src/terminal/commandHelp.ts
|
|
14391
15101
|
function formatTerminalCommandLabel(name, aliases) {
|
|
14392
15102
|
return aliases?.length ? `${name} (${aliases.join(", ")})` : name;
|
|
@@ -14478,10 +15188,12 @@ function createTerminalCommands(host) {
|
|
|
14478
15188
|
return [];
|
|
14479
15189
|
return session.resourceLoader.getSkills().skills.map((skill) => ({ name: skill.name, description: skill.description }));
|
|
14480
15190
|
};
|
|
14481
|
-
const expandSkill = (text) => expandSkillInvocation(text, new Set(skills().map((skill) => skill.name)));
|
|
14482
15191
|
async function openPage(id, options = {}) {
|
|
14483
15192
|
let close = () => {};
|
|
14484
|
-
const page = createCommandPage(host, id, { ...options, close: () => close()
|
|
15193
|
+
const page = createCommandPage(host, id, { ...options, close: () => close(), navigate: (target) => {
|
|
15194
|
+
close();
|
|
15195
|
+
setTimeout(() => void openPage(target), 0);
|
|
15196
|
+
} });
|
|
14485
15197
|
await host.ui.custom((tui, _theme, _keys, done) => {
|
|
14486
15198
|
close = () => done(undefined);
|
|
14487
15199
|
return new PageOverlay({ page, tui, theme: () => host.ui.theme, close, changed: host.changed });
|
|
@@ -14897,6 +15609,23 @@ function createTerminalCommands(host) {
|
|
|
14897
15609
|
case "log":
|
|
14898
15610
|
await openPage("log");
|
|
14899
15611
|
break;
|
|
15612
|
+
case "context":
|
|
15613
|
+
await openPage("context", { contextTab: argument === "growth" ? "growth" : "request" });
|
|
15614
|
+
break;
|
|
15615
|
+
case "remote-control": {
|
|
15616
|
+
const choice = argument.toLowerCase();
|
|
15617
|
+
if (choice === "off" || choice === "stop") {
|
|
15618
|
+
await host.control("terminal.remoteControl.stop");
|
|
15619
|
+
notify("Remote control stopped.");
|
|
15620
|
+
break;
|
|
15621
|
+
}
|
|
15622
|
+
if (choice && !["tailscale", "lan", "wifi", "wi-fi"].includes(choice))
|
|
15623
|
+
throw new Error("Use /remote-control, /remote-control off, /remote-control tailscale or /remote-control lan.");
|
|
15624
|
+
await host.control("terminal.remoteControl.start", { interface: choice === "tailscale" ? "tailscale" : choice ? "lan" : "auto" });
|
|
15625
|
+
host.watchRemoteControl?.();
|
|
15626
|
+
await openPage("remote-control");
|
|
15627
|
+
break;
|
|
15628
|
+
}
|
|
14900
15629
|
case "compact":
|
|
14901
15630
|
await session.compact(argument || undefined);
|
|
14902
15631
|
break;
|
|
@@ -14930,7 +15659,7 @@ function createTerminalCommands(host) {
|
|
|
14930
15659
|
}
|
|
14931
15660
|
return true;
|
|
14932
15661
|
}
|
|
14933
|
-
return { execute, completions, skills,
|
|
15662
|
+
return { execute, completions, skills, legacyAliases };
|
|
14934
15663
|
}
|
|
14935
15664
|
|
|
14936
15665
|
// src/sessions/planMode.ts
|
|
@@ -15001,6 +15730,14 @@ function planBashRefusal(args) {
|
|
|
15001
15730
|
}
|
|
15002
15731
|
var PLAN_OPEN_TAG = "<proposed_plan>";
|
|
15003
15732
|
var PLAN_CLOSE_TAG = "</proposed_plan>";
|
|
15733
|
+
var PLAN_BLOCKED_OPEN_TAG = "<plan_blocked>";
|
|
15734
|
+
var PLAN_BLOCKED_CLOSE_TAG = "</plan_blocked>";
|
|
15735
|
+
var LEGACY_CLARIFICATION_TAGS = ["<plan_clarification>", "</plan_clarification>"];
|
|
15736
|
+
var PLAN_REPAIR_CUSTOM_TYPE = "xingular-plan-repair";
|
|
15737
|
+
var PLAN_REPAIR_INSTRUCTIONS = `Your last reply to this plan request did not end with the required plan block.
|
|
15738
|
+
- If you already proposed a sound plan, re-send it unchanged and complete inside one ${PLAN_OPEN_TAG} ... ${PLAN_CLOSE_TAG} block. Its first line must be the plan title as an H1 heading.
|
|
15739
|
+
- Do not research again or change an existing plan. If necessary user input is missing, call ${ASK_USER} when available, then return a complete plan informed by the answer. Never ask a question in free text.
|
|
15740
|
+
- Only if necessary input cannot be obtained because ${ASK_USER} is unavailable, return one ${PLAN_BLOCKED_OPEN_TAG} ... ${PLAN_BLOCKED_CLOSE_TAG} block with a nonempty explanation of the blocker, not a question. Do not invent an answer.`;
|
|
15004
15741
|
var PLAN_INSTRUCTIONS = `Plan mode is on for this request. Research and design; do not carry out the work.
|
|
15005
15742
|
- Classify the task and scale investigation and plan detail to it. For repository work, read the governing instructions and relevant source, callers and tests before asserting paths, symbols, behavior or checks. Cite inspected code as path:line; cite external research with source URLs, and mark unverified claims as unknown.
|
|
15006
15743
|
- Separate facts you can discover from user-owned preferences. Do not ask about facts repository or source inspection can answer. Use ${ASK_USER} for consequential choices that materially change the plan; batch related questions, explain trade-offs and recommend a default. State a reasonable assumption when interaction is unavailable and the task can proceed.
|
|
@@ -15019,7 +15756,7 @@ ${PLAN_OPEN_TAG}
|
|
|
15019
15756
|
# <Plan title>
|
|
15020
15757
|
<Markdown: Goal or Summary first; Findings when useful; ordered Steps with files and behavior; Verification with expected results; material Assumptions>
|
|
15021
15758
|
${PLAN_CLOSE_TAG}
|
|
15022
|
-
- If the user's input is necessary before a sound plan is possible, ask instead of
|
|
15759
|
+
- If the user's input is necessary before a sound plan is possible, call ${ASK_USER} when available and continue planning after the answer. Never ask the user a question in free text. Only when ${ASK_USER} is unavailable and necessary input cannot be obtained, end with exactly one ${PLAN_BLOCKED_OPEN_TAG} ... ${PLAN_BLOCKED_CLOSE_TAG} block containing a nonempty explanation of the blocker, not a question, instead of a plan. Do not invent an answer.`;
|
|
15023
15760
|
var PLAN_BASH = "bash";
|
|
15024
15761
|
function planModeTools(normal, readOnly = [], planOnlyQuestions = []) {
|
|
15025
15762
|
const allowed = new Set([...PLAN_READ_ONLY_TOOLS, ...PLAN_RESEARCH_TOOLS, SPAWN_SUBAGENT, PLAN_BASH, ...readOnly]);
|
|
@@ -15071,8 +15808,30 @@ function parseProposedPlan(text) {
|
|
|
15071
15808
|
complete
|
|
15072
15809
|
};
|
|
15073
15810
|
}
|
|
15811
|
+
function parsePlanOutcome(text) {
|
|
15812
|
+
if (LEGACY_CLARIFICATION_TAGS.some((tag) => text.includes(tag)))
|
|
15813
|
+
return { kind: "invalid" };
|
|
15814
|
+
const tags = [PLAN_OPEN_TAG, PLAN_CLOSE_TAG, PLAN_BLOCKED_OPEN_TAG, PLAN_BLOCKED_CLOSE_TAG];
|
|
15815
|
+
const counts = tags.map((tag) => text.split(tag).length - 1);
|
|
15816
|
+
if (counts[0] === 1 && counts[1] === 1 && counts[2] === 0 && counts[3] === 0) {
|
|
15817
|
+
const plan = parseProposedPlan(text);
|
|
15818
|
+
const start = text.indexOf(PLAN_OPEN_TAG) + PLAN_OPEN_TAG.length;
|
|
15819
|
+
const end = text.indexOf(PLAN_CLOSE_TAG);
|
|
15820
|
+
if (plan?.complete && end >= start && text.slice(start, end).trim())
|
|
15821
|
+
return { kind: "plan_ready", plan };
|
|
15822
|
+
}
|
|
15823
|
+
if (counts[0] === 0 && counts[1] === 0 && counts[2] === 1 && counts[3] === 1) {
|
|
15824
|
+
const start = text.indexOf(PLAN_BLOCKED_OPEN_TAG) + PLAN_BLOCKED_OPEN_TAG.length;
|
|
15825
|
+
const end = text.indexOf(PLAN_BLOCKED_CLOSE_TAG);
|
|
15826
|
+
const reason = end >= start ? text.slice(start, end).trim() : "";
|
|
15827
|
+
if (reason)
|
|
15828
|
+
return { kind: "blocked", reason };
|
|
15829
|
+
}
|
|
15830
|
+
return { kind: "invalid" };
|
|
15831
|
+
}
|
|
15832
|
+
|
|
15074
15833
|
// src/terminal/tui/dialogs.ts
|
|
15075
|
-
import { Editor,
|
|
15834
|
+
import { Editor, matchesKey as matchesKey19, stripTerminalSequences as stripTerminalSequences11, truncateToWidth as truncateToWidth24, visibleWidth as visibleWidth16, wrapTextWithAnsi as wrapTextWithAnsi16 } from "@earendil-works/pi-tui";
|
|
15076
15835
|
function selectTheme(theme) {
|
|
15077
15836
|
return {
|
|
15078
15837
|
selectedPrefix: (text) => selectionText(theme, text),
|
|
@@ -15083,13 +15842,13 @@ function selectTheme(theme) {
|
|
|
15083
15842
|
};
|
|
15084
15843
|
}
|
|
15085
15844
|
|
|
15086
|
-
class SecretInput extends
|
|
15845
|
+
class SecretInput extends MouseSafeInput {
|
|
15087
15846
|
render(width) {
|
|
15088
15847
|
const lines = super.render(width);
|
|
15089
15848
|
if (!this.getValue())
|
|
15090
15849
|
return lines;
|
|
15091
15850
|
const segments = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
15092
|
-
return lines.map((line) => line.split(/(\x1b(?:\[[0-9;?]*[ -/]*[@-~]|_[^\x07]*\x07))/g).map((part, index) => index % 2 ? part : [...segments.segment(part)].map((item) => "\u2022".repeat(
|
|
15851
|
+
return lines.map((line) => line.split(/(\x1b(?:\[[0-9;?]*[ -/]*[@-~]|_[^\x07]*\x07))/g).map((part, index) => index % 2 ? part : [...segments.segment(part)].map((item) => "\u2022".repeat(visibleWidth16(item.segment))).join("")).join(""));
|
|
15093
15852
|
}
|
|
15094
15853
|
}
|
|
15095
15854
|
var safe5 = safeText;
|
|
@@ -15145,7 +15904,7 @@ class SearchableSelect {
|
|
|
15145
15904
|
return this.list.handleMouse(event);
|
|
15146
15905
|
}
|
|
15147
15906
|
handleInput(data) {
|
|
15148
|
-
if (
|
|
15907
|
+
if (matchesKey19(data, "ctrl+c")) {
|
|
15149
15908
|
this.cancel();
|
|
15150
15909
|
return;
|
|
15151
15910
|
}
|
|
@@ -15162,7 +15921,7 @@ class SearchableSelect {
|
|
|
15162
15921
|
this.list.handleInput(data === "j" ? "\x1B[B" : "\x1B[A");
|
|
15163
15922
|
}
|
|
15164
15923
|
render(width) {
|
|
15165
|
-
return this.list.render(Math.max(4, width), this.windowRows() + this.searchRows()).map((line) =>
|
|
15924
|
+
return this.list.render(Math.max(4, width), this.windowRows() + this.searchRows()).map((line) => truncateToWidth24(line, width, ""));
|
|
15166
15925
|
}
|
|
15167
15926
|
}
|
|
15168
15927
|
|
|
@@ -15218,8 +15977,8 @@ class DialogPanel {
|
|
|
15218
15977
|
return mouseAware.handleMouse?.({ ...event, y: row });
|
|
15219
15978
|
}
|
|
15220
15979
|
handleInput(data) {
|
|
15221
|
-
if (this.detailTotal > this.detailRows && (
|
|
15222
|
-
const delta =
|
|
15980
|
+
if (this.detailTotal > this.detailRows && (matchesKey19(data, "pageUp") || matchesKey19(data, "pageDown"))) {
|
|
15981
|
+
const delta = matchesKey19(data, "pageUp") ? -1 : 1;
|
|
15223
15982
|
this.detailOffset = Math.max(0, Math.min(this.detailTotal - this.detailRows, this.detailOffset + delta * Math.max(1, this.detailRows)));
|
|
15224
15983
|
return;
|
|
15225
15984
|
}
|
|
@@ -15230,7 +15989,7 @@ class DialogPanel {
|
|
|
15230
15989
|
return [];
|
|
15231
15990
|
const theme = this.theme();
|
|
15232
15991
|
const inner = this.centered ? centerDialogContentWidth(width) : contentWidth(width);
|
|
15233
|
-
const details = this.message ?
|
|
15992
|
+
const details = this.message ? wrapTextWithAnsi16(stripTerminalSequences11(this.message).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").replace(/\t/g, " "), inner) : [];
|
|
15234
15993
|
const content = this.content.render(inner);
|
|
15235
15994
|
const frameRows = this.centered ? CENTER_DIALOG_PAD * 2 + 2 : CHROME_ROWS;
|
|
15236
15995
|
const maxHeight = this.maxRows ? Math.max(3, Math.floor(this.maxRows())) : details.length + content.length + frameRows;
|
|
@@ -15260,7 +16019,7 @@ class DialogPanel {
|
|
|
15260
16019
|
let footer = this.hint;
|
|
15261
16020
|
if (details.length > detailBudget) {
|
|
15262
16021
|
footer = `PgUp/PgDn details ${this.detailOffset + 1}-${this.detailOffset + detailBudget}/${details.length} \xB7 ${footer}`;
|
|
15263
|
-
if (
|
|
16022
|
+
if (visibleWidth16(footer) > inner)
|
|
15264
16023
|
footer = "PgUp/PgDn details \xB7 Enter \xB7 Esc";
|
|
15265
16024
|
}
|
|
15266
16025
|
const frame = { title: this.title, meta: seconds, body, footer, width, theme };
|
|
@@ -15357,7 +16116,7 @@ class TerminalDialogs {
|
|
|
15357
16116
|
}
|
|
15358
16117
|
input(title, placeholder, opts, secret = false) {
|
|
15359
16118
|
return this.show((done) => {
|
|
15360
|
-
const InputType = secret ? SecretInput :
|
|
16119
|
+
const InputType = secret ? SecretInput : MouseSafeInput;
|
|
15361
16120
|
const input = new InputType({ prompt: secret ? "" : "> ", placeholder, placeholderStyle: (text) => this.theme().fg("dim", text) });
|
|
15362
16121
|
input.onSubmit = done;
|
|
15363
16122
|
input.onEscape = () => done(undefined);
|
|
@@ -15377,9 +16136,9 @@ class TerminalDialogs {
|
|
|
15377
16136
|
editor.focused = value;
|
|
15378
16137
|
},
|
|
15379
16138
|
invalidate: () => editor.invalidate(),
|
|
15380
|
-
render: (width) => editor.render(Math.max(4, width)).map((line) =>
|
|
16139
|
+
render: (width) => editor.render(Math.max(4, width)).map((line) => truncateToWidth24(line, width, "")),
|
|
15381
16140
|
handleInput: (data) => {
|
|
15382
|
-
if (
|
|
16141
|
+
if (matchesKey19(data, "escape") || matchesKey19(data, "ctrl+c"))
|
|
15383
16142
|
done(undefined);
|
|
15384
16143
|
else
|
|
15385
16144
|
editor.handleInput(data);
|
|
@@ -15449,7 +16208,7 @@ class TerminalDialogs {
|
|
|
15449
16208
|
}
|
|
15450
16209
|
|
|
15451
16210
|
// src/terminal/tui/keybindings.ts
|
|
15452
|
-
import { readFileSync as
|
|
16211
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
15453
16212
|
import { join as join17 } from "path";
|
|
15454
16213
|
import { KeybindingsManager, TUI_KEYBINDINGS } from "@earendil-works/pi-tui";
|
|
15455
16214
|
var actions = {
|
|
@@ -15469,7 +16228,7 @@ var actions = {
|
|
|
15469
16228
|
"app.thinking.toggle": "ctrl+t",
|
|
15470
16229
|
"app.editor.external": "ctrl+g",
|
|
15471
16230
|
"app.message.copy": "ctrl+x",
|
|
15472
|
-
"app.message.
|
|
16231
|
+
"app.message.steer": ["super+enter", "ctrl+enter", "alt+enter"],
|
|
15473
16232
|
"app.message.dequeue": "alt+up",
|
|
15474
16233
|
"app.clipboard.pasteImage": process.platform === "darwin" ? ["ctrl+v", "alt+v"] : "ctrl+v",
|
|
15475
16234
|
"app.session.toggleNamedFilter": "ctrl+n",
|
|
@@ -15507,7 +16266,7 @@ var HARNESS_KEYBINDINGS = {
|
|
|
15507
16266
|
function readBindings(agentDir) {
|
|
15508
16267
|
let bindings = {};
|
|
15509
16268
|
try {
|
|
15510
|
-
const source = JSON.parse(
|
|
16269
|
+
const source = JSON.parse(readFileSync8(join17(agentDir, "keybindings.json"), "utf8"));
|
|
15511
16270
|
if (source && typeof source === "object" && !Array.isArray(source)) {
|
|
15512
16271
|
bindings = Object.fromEntries(Object.entries(source).filter(([, value]) => typeof value === "string" || Array.isArray(value) && value.every((key) => typeof key === "string")));
|
|
15513
16272
|
}
|
|
@@ -15576,6 +16335,7 @@ import { closeSync as closeSync2, existsSync as existsSync11, openSync as openSy
|
|
|
15576
16335
|
import { isAbsolute as isAbsolute5, join as join21, relative as relative4, resolve as resolve4, sep as sep5 } from "path";
|
|
15577
16336
|
|
|
15578
16337
|
// src/terminal/piExtension.ts
|
|
16338
|
+
import { readFileSync as readFileSync9 } from "fs";
|
|
15579
16339
|
import { createBashTool, createEditTool, createPowerShellTool, createWriteTool } from "@earendil-works/pi-coding-agent";
|
|
15580
16340
|
import { Type as Type2 } from "typebox";
|
|
15581
16341
|
|
|
@@ -15740,8 +16500,35 @@ function parseInitialBashCommand(input) {
|
|
|
15740
16500
|
return outside ? { command: input.slice(outside[0].length).trim(), workspaceWriteScope: "outside" } : { command: input, workspaceWriteScope: "workspace" };
|
|
15741
16501
|
}
|
|
15742
16502
|
|
|
16503
|
+
// src/terminal/tui/skillInvocation.ts
|
|
16504
|
+
var SKILL_TOKEN = /(?:^|[\s(])\$([^\s$]*)$/;
|
|
16505
|
+
var SKILL_INVOCATION = /(?:^|[\s(])\$([A-Za-z0-9][A-Za-z0-9_-]*)(?=[\s.,;:!?)]|$)/gu;
|
|
16506
|
+
function skillTokenAt(text, caret) {
|
|
16507
|
+
const match = SKILL_TOKEN.exec(text.slice(0, caret));
|
|
16508
|
+
if (!match)
|
|
16509
|
+
return null;
|
|
16510
|
+
const query = match[1] ?? "";
|
|
16511
|
+
return { query, from: caret - query.length - 1, to: caret };
|
|
16512
|
+
}
|
|
16513
|
+
function skillInvocationMatches(text) {
|
|
16514
|
+
const found = [];
|
|
16515
|
+
for (const match of text.matchAll(SKILL_INVOCATION)) {
|
|
16516
|
+
const from = match.index + match[0].indexOf("$");
|
|
16517
|
+
found.push({ name: match[1], from, to: from + 1 + match[1].length });
|
|
16518
|
+
}
|
|
16519
|
+
return found;
|
|
16520
|
+
}
|
|
16521
|
+
function skillInvocations(text, skills) {
|
|
16522
|
+
const found = [];
|
|
16523
|
+
for (const match of skillInvocationMatches(text)) {
|
|
16524
|
+
if (skills.has(match.name) && !found.includes(match.name))
|
|
16525
|
+
found.push(match.name);
|
|
16526
|
+
}
|
|
16527
|
+
return found;
|
|
16528
|
+
}
|
|
16529
|
+
|
|
15743
16530
|
// src/core/workspace.ts
|
|
15744
|
-
import { lstatSync as lstatSync2, realpathSync, statSync as
|
|
16531
|
+
import { lstatSync as lstatSync2, realpathSync, statSync as statSync6 } from "fs";
|
|
15745
16532
|
import { homedir as homedir2 } from "os";
|
|
15746
16533
|
import { basename as basename6, dirname as dirname7, isAbsolute as isAbsolute4, join as join19, relative as relative3, resolve as resolve2, sep as sep4 } from "path";
|
|
15747
16534
|
function resolveWritePath(candidate, cwd = process.cwd()) {
|
|
@@ -15751,7 +16538,7 @@ function resolveWritePath(candidate, cwd = process.cwd()) {
|
|
|
15751
16538
|
}
|
|
15752
16539
|
function isWithinWorkspace(workspaceRoot, canonicalCandidate) {
|
|
15753
16540
|
const canonicalRoot = realpathSync(workspaceRoot);
|
|
15754
|
-
if (!
|
|
16541
|
+
if (!statSync6(canonicalRoot).isDirectory())
|
|
15755
16542
|
throw invalid("The workspace root must be a directory.");
|
|
15756
16543
|
const fromRoot = relative3(canonicalRoot, canonicalCandidate);
|
|
15757
16544
|
return fromRoot === "" || fromRoot !== ".." && !fromRoot.startsWith(`..${sep4}`) && !isAbsolute4(fromRoot);
|
|
@@ -15760,7 +16547,7 @@ function verifyWorkspaceRoot(workspaceRoot) {
|
|
|
15760
16547
|
const canonicalRoot = realpathSync(workspaceRoot);
|
|
15761
16548
|
if (dirname7(canonicalRoot) === canonicalRoot)
|
|
15762
16549
|
throw invalid("The filesystem root cannot be used as an active project workspace.");
|
|
15763
|
-
if (canonicalRoot !== resolve2(workspaceRoot) || !
|
|
16550
|
+
if (canonicalRoot !== resolve2(workspaceRoot) || !statSync6(canonicalRoot).isDirectory()) {
|
|
15764
16551
|
throw invalid("The active project workspace changed after this run began.");
|
|
15765
16552
|
}
|
|
15766
16553
|
return canonicalRoot;
|
|
@@ -15811,7 +16598,7 @@ function inspectWorkspaceWrite(workspaceRoot, cwd, tool, input) {
|
|
|
15811
16598
|
import { Type } from "typebox";
|
|
15812
16599
|
|
|
15813
16600
|
// src/core/shell.ts
|
|
15814
|
-
import { accessSync as accessSync2, constants as constants2, statSync as
|
|
16601
|
+
import { accessSync as accessSync2, constants as constants2, statSync as statSync7 } from "fs";
|
|
15815
16602
|
import { win32 } from "path";
|
|
15816
16603
|
var POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"];
|
|
15817
16604
|
var POWERSHELL_UTF8 = `try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}
|
|
@@ -15864,7 +16651,7 @@ function isWslLauncher(path, env) {
|
|
|
15864
16651
|
function isFile(path) {
|
|
15865
16652
|
try {
|
|
15866
16653
|
accessSync2(path, constants2.F_OK);
|
|
15867
|
-
return
|
|
16654
|
+
return statSync7(path).isFile();
|
|
15868
16655
|
} catch {
|
|
15869
16656
|
return false;
|
|
15870
16657
|
}
|
|
@@ -15874,7 +16661,7 @@ function isFile(path) {
|
|
|
15874
16661
|
import { AsyncLocalStorage } from "async_hooks";
|
|
15875
16662
|
import { spawn } from "child_process";
|
|
15876
16663
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
15877
|
-
import { accessSync as accessSync3, constants as constants3, existsSync as existsSync10, lstatSync as lstatSync3, mkdtempSync, realpathSync as realpathSync2, readdirSync as
|
|
16664
|
+
import { accessSync as accessSync3, constants as constants3, existsSync as existsSync10, lstatSync as lstatSync3, mkdtempSync, realpathSync as realpathSync2, readdirSync as readdirSync8, rmSync as rmSync6, statSync as statSync8 } from "fs";
|
|
15878
16665
|
import { tmpdir } from "os";
|
|
15879
16666
|
import { join as join20 } from "path";
|
|
15880
16667
|
import { spawnSync } from "child_process";
|
|
@@ -15896,7 +16683,7 @@ function systemExecutable(candidates) {
|
|
|
15896
16683
|
for (const candidate of candidates) {
|
|
15897
16684
|
try {
|
|
15898
16685
|
accessSync3(candidate, constants3.X_OK);
|
|
15899
|
-
if (
|
|
16686
|
+
if (statSync8(candidate).isFile())
|
|
15900
16687
|
return candidate;
|
|
15901
16688
|
} catch {}
|
|
15902
16689
|
}
|
|
@@ -16133,7 +16920,7 @@ function assertNoExternalHardlinks(workspaceRoot) {
|
|
|
16133
16920
|
const visit = (directory) => {
|
|
16134
16921
|
let entries;
|
|
16135
16922
|
try {
|
|
16136
|
-
entries =
|
|
16923
|
+
entries = readdirSync8(directory, { withFileTypes: true });
|
|
16137
16924
|
} catch (error) {
|
|
16138
16925
|
throw new Error(`Workspace hard-link inspection failed at ${directory}; Bash was not run: ${error instanceof Error ? error.message : String(error)}`);
|
|
16139
16926
|
}
|
|
@@ -16267,8 +17054,8 @@ function withWorkspaceWriteScope(tool, note = "") {
|
|
|
16267
17054
|
// src/core/workspaceWriteOperations.ts
|
|
16268
17055
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
16269
17056
|
import { spawn as spawn2 } from "child_process";
|
|
16270
|
-
import { createHash as
|
|
16271
|
-
import { constants as fsConstants, realpathSync as realpathSync3, statSync as
|
|
17057
|
+
import { createHash as createHash2 } from "crypto";
|
|
17058
|
+
import { constants as fsConstants, realpathSync as realpathSync3, statSync as statSync9 } from "fs";
|
|
16272
17059
|
import { access, readFile } from "fs/promises";
|
|
16273
17060
|
import { dirname as dirname8, resolve as resolve3 } from "path";
|
|
16274
17061
|
var writeAuthorization = new AsyncLocalStorage2;
|
|
@@ -16342,7 +17129,7 @@ function nearestExistingDirectory(path) {
|
|
|
16342
17129
|
while (true) {
|
|
16343
17130
|
try {
|
|
16344
17131
|
const canonical = realpathSync3(current);
|
|
16345
|
-
if (!
|
|
17132
|
+
if (!statSync9(canonical).isDirectory())
|
|
16346
17133
|
throw new Error(`Write scope is not a directory: ${canonical}`);
|
|
16347
17134
|
return canonical;
|
|
16348
17135
|
} catch (error) {
|
|
@@ -16452,7 +17239,7 @@ var workspaceEditOperations = {
|
|
|
16452
17239
|
const content = await readFile(path);
|
|
16453
17240
|
const authorization = writeAuthorization.getStore();
|
|
16454
17241
|
if (authorization && resolve3(path) === authorization.path) {
|
|
16455
|
-
authorization.expectedContentHash =
|
|
17242
|
+
authorization.expectedContentHash = createHash2("sha256").update(content).digest("hex");
|
|
16456
17243
|
}
|
|
16457
17244
|
return content;
|
|
16458
17245
|
},
|
|
@@ -16478,6 +17265,7 @@ function withWorkspaceWriteAuthorization(tool, authorizations) {
|
|
|
16478
17265
|
}
|
|
16479
17266
|
|
|
16480
17267
|
// src/terminal/piExtension.ts
|
|
17268
|
+
var STREAM_FLUSH_MS = 150;
|
|
16481
17269
|
function resultSize(result) {
|
|
16482
17270
|
const content = result?.content;
|
|
16483
17271
|
if (!Array.isArray(content))
|
|
@@ -16504,8 +17292,12 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16504
17292
|
let subagentParent = false;
|
|
16505
17293
|
let stoppedChildren = null;
|
|
16506
17294
|
let timer = null;
|
|
17295
|
+
let heartbeat = null;
|
|
17296
|
+
let turnStartedAt = 0;
|
|
16507
17297
|
let polling = false;
|
|
16508
17298
|
let failure;
|
|
17299
|
+
let planRepairAttempted = false;
|
|
17300
|
+
let lastPlanText = "";
|
|
16509
17301
|
const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, requests: 0, costUsd: 0 });
|
|
16510
17302
|
let usage = emptyUsage();
|
|
16511
17303
|
let reasoningTokens;
|
|
@@ -16650,6 +17442,8 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16650
17442
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
16651
17443
|
context = ctx;
|
|
16652
17444
|
failure = undefined;
|
|
17445
|
+
planRepairAttempted = false;
|
|
17446
|
+
lastPlanText = "";
|
|
16653
17447
|
usage = emptyUsage();
|
|
16654
17448
|
reasoningTokens = undefined;
|
|
16655
17449
|
costReported = false;
|
|
@@ -16658,6 +17452,20 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16658
17452
|
if (!workspaceRoot)
|
|
16659
17453
|
throw new Error("The active project workspace could not be resolved; the turn was not started.");
|
|
16660
17454
|
pi.appendEntry(SUBAGENT_OWNER, { runId: begun.runId });
|
|
17455
|
+
turnStartedAt = Date.now();
|
|
17456
|
+
if (heartbeat)
|
|
17457
|
+
clearInterval(heartbeat);
|
|
17458
|
+
heartbeat = setInterval(() => {
|
|
17459
|
+
terminalCall("heartbeat", {
|
|
17460
|
+
steps: sliceState.steps,
|
|
17461
|
+
elapsedMs: Date.now() - turnStartedAt,
|
|
17462
|
+
lastTool: sliceState.lastTool,
|
|
17463
|
+
compactions: sliceState.compactions,
|
|
17464
|
+
slice: sliceState.slice,
|
|
17465
|
+
maxToolCalls: slicePolicy.enabled ? slicePolicy.maxToolCalls : 0
|
|
17466
|
+
}, 1e4).catch(() => {});
|
|
17467
|
+
}, 30000);
|
|
17468
|
+
heartbeat.unref?.();
|
|
16661
17469
|
stoppedChildren = null;
|
|
16662
17470
|
if (nativeSubagents) {
|
|
16663
17471
|
const snapshot = await controlCall("terminal.subagents.register", { tools: pi.getActiveTools(), model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : null, effort: pi.getThinkingLevel(), plan: planRun?.active === true, history: subagentHistory(ctx.sessionManager.getBranch()) });
|
|
@@ -16734,6 +17542,32 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16734
17542
|
if (notice)
|
|
16735
17543
|
return { message: { customType: SUBAGENT_RESULTS, content: notice.text, display: false, details: { [SUBAGENT_RECEIPT]: notice.receipt } } };
|
|
16736
17544
|
});
|
|
17545
|
+
pi.on("before_agent_start", async (event) => {
|
|
17546
|
+
if (event.messageType !== "user" || /^\s*!/u.test(event.prompt))
|
|
17547
|
+
return;
|
|
17548
|
+
if (pi.getSettings?.().enableSkillCommands === false)
|
|
17549
|
+
return;
|
|
17550
|
+
const skills = (pi.getCommands?.() ?? []).filter((command) => command.source === "skill").map((command) => ({
|
|
17551
|
+
name: command.name.replace(/^skill:/, ""),
|
|
17552
|
+
path: command.sourceInfo.path,
|
|
17553
|
+
...command.sourceInfo.baseDir ? { baseDir: command.sourceInfo.baseDir } : {}
|
|
17554
|
+
}));
|
|
17555
|
+
if (!skills.length)
|
|
17556
|
+
return;
|
|
17557
|
+
const names = skillInvocations(event.prompt, new Set(skills.map((skill) => skill.name)));
|
|
17558
|
+
if (!names.length)
|
|
17559
|
+
return;
|
|
17560
|
+
const entries = names.map((name) => {
|
|
17561
|
+
const skill = skills.find((candidate) => candidate.name === name);
|
|
17562
|
+
try {
|
|
17563
|
+
return { name, path: skill.path, baseDir: skill.baseDir, body: bodyOf(readFileSync9(skill.path, "utf8")) };
|
|
17564
|
+
} catch {
|
|
17565
|
+
return { name, path: skill.path, body: "" };
|
|
17566
|
+
}
|
|
17567
|
+
});
|
|
17568
|
+
const content = requiredSkillsText(entries);
|
|
17569
|
+
return content ? { message: { customType: "xingular-required-skills", content, display: false, details: { skills: names } } } : undefined;
|
|
17570
|
+
});
|
|
16737
17571
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
16738
17572
|
if (event.messageType !== "user")
|
|
16739
17573
|
return;
|
|
@@ -16777,15 +17611,53 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16777
17611
|
};
|
|
16778
17612
|
pi.on("turn_end", (event, ctx) => deliverChildren(event, ctx, false));
|
|
16779
17613
|
pi.on("agent_before_settle", (event, ctx) => deliverChildren(event, ctx, true));
|
|
17614
|
+
pi.on("agent_before_settle", (event, ctx) => {
|
|
17615
|
+
if (!planRun?.active || planRepairAttempted || event.outcome !== "completed" || event.continue || ctx.signal?.aborted || failure || sliceState.endedBy || parsePlanOutcome(lastPlanText).kind !== "invalid")
|
|
17616
|
+
return;
|
|
17617
|
+
planRepairAttempted = true;
|
|
17618
|
+
return {
|
|
17619
|
+
entries: [...event.entries, { type: "custom_message", customType: PLAN_REPAIR_CUSTOM_TYPE, content: PLAN_REPAIR_INSTRUCTIONS, display: false, details: { reason: "invalid_plan_outcome" } }],
|
|
17620
|
+
continue: true
|
|
17621
|
+
};
|
|
17622
|
+
});
|
|
17623
|
+
let streamId = null;
|
|
17624
|
+
let streamText = "";
|
|
17625
|
+
let streamTimer = null;
|
|
17626
|
+
let streamCount = 0;
|
|
17627
|
+
const flushStream = () => {
|
|
17628
|
+
streamTimer = null;
|
|
17629
|
+
if (!streamId || !streamText)
|
|
17630
|
+
return;
|
|
17631
|
+
const text = streamText;
|
|
17632
|
+
streamText = "";
|
|
17633
|
+
terminalCall("delta", { id: streamId, text }).catch(() => {
|
|
17634
|
+
return;
|
|
17635
|
+
});
|
|
17636
|
+
};
|
|
17637
|
+
pi.on("message_update", (event) => {
|
|
17638
|
+
const update = event.assistantMessageEvent;
|
|
17639
|
+
if (event.message.role !== "assistant" || update.type !== "text_delta" || !update.delta)
|
|
17640
|
+
return;
|
|
17641
|
+
streamId ??= `${Date.now().toString(36)}-${++streamCount}`;
|
|
17642
|
+
streamText += update.delta;
|
|
17643
|
+
streamTimer ??= setTimeout(flushStream, STREAM_FLUSH_MS);
|
|
17644
|
+
});
|
|
16780
17645
|
pi.on("message_end", async (event) => {
|
|
16781
17646
|
if (event.message.role !== "assistant")
|
|
16782
17647
|
return;
|
|
17648
|
+
const messageId = streamId;
|
|
17649
|
+
if (streamTimer)
|
|
17650
|
+
clearTimeout(streamTimer);
|
|
17651
|
+
streamTimer = null;
|
|
17652
|
+
streamText = "";
|
|
17653
|
+
streamId = null;
|
|
16783
17654
|
if (event.message.stopReason === "error" || event.message.stopReason === "aborted")
|
|
16784
17655
|
failure = event.message.errorMessage ?? `Pi stopped: ${event.message.stopReason}`;
|
|
16785
17656
|
const text = event.message.content.filter((part) => part.type === "text").map((part) => part.text).join(`
|
|
16786
17657
|
`);
|
|
17658
|
+
lastPlanText = text;
|
|
16787
17659
|
if (text)
|
|
16788
|
-
await terminalCall("message", { text });
|
|
17660
|
+
await terminalCall("message", messageId ? { id: messageId, text } : { text });
|
|
16789
17661
|
if (event.message.usage) {
|
|
16790
17662
|
const reported = event.message.usage;
|
|
16791
17663
|
usage.inputTokens += reported.input ?? 0;
|
|
@@ -16902,6 +17774,9 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16902
17774
|
await terminalCall("file", { path, change: "modified" });
|
|
16903
17775
|
});
|
|
16904
17776
|
pi.on("agent_settled", async (event, ctx) => {
|
|
17777
|
+
if (heartbeat)
|
|
17778
|
+
clearInterval(heartbeat);
|
|
17779
|
+
heartbeat = null;
|
|
16905
17780
|
if (subagentParent && !event.aborted && !failure) {
|
|
16906
17781
|
try {
|
|
16907
17782
|
await controlCall("terminal.subagents.verify", { history: subagentHistory(ctx.sessionManager.getBranch()) }, 2147483647);
|
|
@@ -16910,7 +17785,7 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16910
17785
|
}
|
|
16911
17786
|
}
|
|
16912
17787
|
subagentParent = false;
|
|
16913
|
-
const reason = sliceState.endedBy ?
|
|
17788
|
+
const reason = sliceState.endedBy ? "slice_complete" : undefined;
|
|
16914
17789
|
await terminalCall("settled", { error: failure, aborted: event.aborted, ...reason ? { reason } : {} });
|
|
16915
17790
|
});
|
|
16916
17791
|
pi.on("user_bash", async () => {
|
|
@@ -16920,6 +17795,9 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16920
17795
|
if (timer)
|
|
16921
17796
|
clearInterval(timer);
|
|
16922
17797
|
timer = null;
|
|
17798
|
+
if (heartbeat)
|
|
17799
|
+
clearInterval(heartbeat);
|
|
17800
|
+
heartbeat = null;
|
|
16923
17801
|
context = null;
|
|
16924
17802
|
sessionState = null;
|
|
16925
17803
|
stateDelivered = false;
|
|
@@ -16991,7 +17869,6 @@ async function piExtension_default(pi, planRun, getSession) {
|
|
|
16991
17869
|
});
|
|
16992
17870
|
await terminalCall("startup", { phase: "Pi hooks registered" });
|
|
16993
17871
|
}
|
|
16994
|
-
|
|
16995
17872
|
// src/usage/limits/capture.ts
|
|
16996
17873
|
var WRAPPED = Symbol("xingular-usage-observed");
|
|
16997
17874
|
function wrap(provider, method, observe) {
|
|
@@ -17111,7 +17988,7 @@ class ModeChoices {
|
|
|
17111
17988
|
this.quiet -= 1;
|
|
17112
17989
|
}
|
|
17113
17990
|
}
|
|
17114
|
-
async apply(session, mode, modelFor) {
|
|
17991
|
+
async apply(session, mode, modelFor, fallback) {
|
|
17115
17992
|
const choice = this.resolve(mode);
|
|
17116
17993
|
await this.quietly(async () => {
|
|
17117
17994
|
const model = choice.model ? modelFor(choice.model) : undefined;
|
|
@@ -17120,8 +17997,7 @@ class ModeChoices {
|
|
|
17120
17997
|
await session.setModel(model, { persist: false });
|
|
17121
17998
|
} catch {}
|
|
17122
17999
|
}
|
|
17123
|
-
|
|
17124
|
-
session.setThinkingLevel(choice.effort, { persist: false });
|
|
18000
|
+
session.setThinkingLevel(choice.effort ?? fallback, { persist: false });
|
|
17125
18001
|
});
|
|
17126
18002
|
}
|
|
17127
18003
|
async record(mode, patch) {
|
|
@@ -17271,7 +18147,11 @@ async function createTerminalRuntime(args, host) {
|
|
|
17271
18147
|
const modeChoices = new ModeChoices(choiceStore);
|
|
17272
18148
|
const recordingMode = () => planRun.active ? "plan" : currentMode;
|
|
17273
18149
|
const modelFor = (reference) => resolveCliModel({ cliModel: reference, modelRuntime }).model;
|
|
17274
|
-
const
|
|
18150
|
+
const defaultEffort = (session) => {
|
|
18151
|
+
const model = session.model;
|
|
18152
|
+
return (model ? session.settingsManager.getModelThinkingLevel(model.provider, model.id) : undefined) ?? session.settingsManager.getDefaultThinkingLevel() ?? "medium";
|
|
18153
|
+
};
|
|
18154
|
+
const applyMode = () => modeChoices.apply(native.session, currentMode, modelFor, defaultEffort(native.session));
|
|
17275
18155
|
const restoreChoice = async (session, previous) => {
|
|
17276
18156
|
if (previous.model && (session.model?.provider !== previous.model.provider || session.model?.id !== previous.model.id)) {
|
|
17277
18157
|
await session.setModel(previous.model, { persist: false }).catch(() => {
|
|
@@ -17467,7 +18347,7 @@ async function createTerminalRuntime(args, host) {
|
|
|
17467
18347
|
planRun.active = true;
|
|
17468
18348
|
try {
|
|
17469
18349
|
session.setActiveToolsByName(allowedTools);
|
|
17470
|
-
await modeChoices.apply(session, "plan", modelFor);
|
|
18350
|
+
await modeChoices.apply(session, "plan", modelFor, defaultEffort(session));
|
|
17471
18351
|
await session.prompt(text, { expandPromptTemplates: false, ...images?.length ? { images } : {} });
|
|
17472
18352
|
} finally {
|
|
17473
18353
|
planRun.active = false;
|
|
@@ -17623,7 +18503,60 @@ async function createTerminalRuntime(args, host) {
|
|
|
17623
18503
|
}
|
|
17624
18504
|
|
|
17625
18505
|
// src/terminal/tui/sideQuestion.ts
|
|
17626
|
-
import { truncateToWidth as
|
|
18506
|
+
import { truncateToWidth as truncateToWidth25, visibleWidth as visibleWidth17, wrapTextWithAnsi as wrapTextWithAnsi17 } from "@earendil-works/pi-tui";
|
|
18507
|
+
|
|
18508
|
+
// src/terminal/tui/markdown.ts
|
|
18509
|
+
import { Markdown, stripTerminalSequences as stripTerminalSequences12 } from "@earendil-works/pi-tui";
|
|
18510
|
+
function markdownTheme(theme) {
|
|
18511
|
+
return {
|
|
18512
|
+
heading: (text) => theme.fg("mdHeading", text),
|
|
18513
|
+
link: (text) => theme.fg("mdLink", text),
|
|
18514
|
+
linkUrl: (text) => theme.fg("mdLinkUrl", text),
|
|
18515
|
+
code: (text) => theme.fg("mdCode", text),
|
|
18516
|
+
codeBlock: (text) => theme.fg("mdCodeBlock", text),
|
|
18517
|
+
codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text),
|
|
18518
|
+
quote: (text) => theme.fg("mdQuote", text),
|
|
18519
|
+
quoteBorder: (text) => theme.fg("mdQuoteBorder", text),
|
|
18520
|
+
hr: (text) => theme.fg("mdHr", text),
|
|
18521
|
+
listBullet: (text) => theme.fg("mdListBullet", text),
|
|
18522
|
+
bold: (text) => theme.bold(text),
|
|
18523
|
+
italic: (text) => theme.italic(text),
|
|
18524
|
+
underline: (text) => theme.underline(text),
|
|
18525
|
+
strikethrough: (text) => theme.strikethrough(text),
|
|
18526
|
+
highlightCode: (code) => code.split(`
|
|
18527
|
+
`).map((line) => theme.fg("mdCodeBlock", line))
|
|
18528
|
+
};
|
|
18529
|
+
}
|
|
18530
|
+
function markdownSource(text) {
|
|
18531
|
+
return stripTerminalSequences12(text).replace(/\r\n?/gu, `
|
|
18532
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/gu, " ");
|
|
18533
|
+
}
|
|
18534
|
+
|
|
18535
|
+
class MarkdownBlock {
|
|
18536
|
+
component;
|
|
18537
|
+
theme;
|
|
18538
|
+
text = "";
|
|
18539
|
+
lines(text, width, theme) {
|
|
18540
|
+
if (width < 1 || !text.trim())
|
|
18541
|
+
return [];
|
|
18542
|
+
if (!this.component || this.theme !== theme) {
|
|
18543
|
+
this.component = new Markdown("", 0, 0, markdownTheme(theme));
|
|
18544
|
+
this.theme = theme;
|
|
18545
|
+
this.text = "";
|
|
18546
|
+
}
|
|
18547
|
+
if (this.text !== text) {
|
|
18548
|
+
this.component.setText(text);
|
|
18549
|
+
this.text = text;
|
|
18550
|
+
}
|
|
18551
|
+
const lines = this.component.render(width);
|
|
18552
|
+
let end = lines.length;
|
|
18553
|
+
while (end > 0 && !stripTerminalSequences12(lines[end - 1]).trim())
|
|
18554
|
+
end -= 1;
|
|
18555
|
+
return lines.slice(0, end);
|
|
18556
|
+
}
|
|
18557
|
+
}
|
|
18558
|
+
|
|
18559
|
+
// src/terminal/tui/sideQuestion.ts
|
|
17627
18560
|
var QUESTION_ROWS = 2;
|
|
17628
18561
|
var ANSWER_ROWS = 8;
|
|
17629
18562
|
var MAX_CLIENT_CONTEXT_CHARS = 300000;
|
|
@@ -17702,6 +18635,7 @@ class SideQuestion {
|
|
|
17702
18635
|
startedAt = 0;
|
|
17703
18636
|
afterSequence = -1;
|
|
17704
18637
|
answerOffset = 0;
|
|
18638
|
+
answerMarkdown = new MarkdownBlock;
|
|
17705
18639
|
dock;
|
|
17706
18640
|
constructor(options) {
|
|
17707
18641
|
this.options = options;
|
|
@@ -17831,21 +18765,20 @@ class SideQuestion {
|
|
|
17831
18765
|
const inner = contentWidth(width);
|
|
17832
18766
|
const spinner = this.current === "thinking" ? spinnerFrameAt(Date.now() - this.startedAt, getWorkingSpinnerFrames(process.env.TERM), SPINNER_INTERVAL_MS) : "";
|
|
17833
18767
|
const marker = `${spinner ? `${spinner} ` : ""}/btw`;
|
|
17834
|
-
const markerWidth =
|
|
17835
|
-
const asked =
|
|
18768
|
+
const markerWidth = visibleWidth17(marker) + 1;
|
|
18769
|
+
const asked = wrapTextWithAnsi17(safeText(this.question), Math.max(1, inner - markerWidth));
|
|
17836
18770
|
const question = asked.slice(0, QUESTION_ROWS).map((line, index) => {
|
|
17837
18771
|
const prefix = index === 0 ? `${theme.bold(theme.fg("accent", marker))} ` : " ".repeat(markerWidth);
|
|
17838
18772
|
return prefix + theme.fg("muted", line);
|
|
17839
18773
|
});
|
|
17840
18774
|
if (asked.length > QUESTION_ROWS)
|
|
17841
|
-
question[QUESTION_ROWS - 1] =
|
|
17842
|
-
const
|
|
17843
|
-
|
|
17844
|
-
const wrapped =
|
|
17845
|
-
`).flatMap((line) => line ? wrapTextWithAnsi15(safeText(line), inner) : [""]) : [];
|
|
18775
|
+
question[QUESTION_ROWS - 1] = truncateToWidth25(question[QUESTION_ROWS - 1], inner - 1, "") + theme.fg("muted", "\u2026");
|
|
18776
|
+
const answer = this.answerText ? this.answerMarkdown.lines(markdownSource(this.answerText), inner, theme) : [];
|
|
18777
|
+
const failure = this.current === "failed" ? wrapTextWithAnsi17(safeText(this.error ?? "The side question failed."), inner).map((line) => theme.fg("error", line)) : [];
|
|
18778
|
+
const wrapped = [...answer, ...answer.length && failure.length ? [""] : [], ...failure];
|
|
17846
18779
|
const maxOffset = Math.max(0, wrapped.length - ANSWER_ROWS);
|
|
17847
18780
|
this.answerOffset = Math.min(this.answerOffset, maxOffset);
|
|
17848
|
-
const shown = wrapped.slice(this.answerOffset, this.answerOffset + ANSWER_ROWS)
|
|
18781
|
+
const shown = wrapped.slice(this.answerOffset, this.answerOffset + ANSWER_ROWS);
|
|
17849
18782
|
const before = this.answerOffset;
|
|
17850
18783
|
const after = Math.max(0, wrapped.length - before - shown.length);
|
|
17851
18784
|
const textHint = before || after ? `PgUp/PgDn browse \xB7 ${before ? `${before} above` : ""}${before && after ? " \xB7 " : ""}${after ? `${after} below` : ""} \xB7 ` : "";
|
|
@@ -17855,13 +18788,13 @@ class SideQuestion {
|
|
|
17855
18788
|
...shown.length ? ["", ...shown.map((line) => padded(line, width))] : [],
|
|
17856
18789
|
"",
|
|
17857
18790
|
footerRow(`${textHint}Ctrl+X copy \xB7 /btw or Esc dismiss`, width, theme)
|
|
17858
|
-
].map((line) =>
|
|
18791
|
+
].map((line) => truncateToWidth25(line, width, ""));
|
|
17859
18792
|
}
|
|
17860
18793
|
}
|
|
17861
18794
|
|
|
17862
18795
|
// src/terminal/tui/ui.ts
|
|
17863
18796
|
import { Theme as Theme2 } from "@earendil-works/pi-coding-agent";
|
|
17864
|
-
import { stripTerminalSequences as
|
|
18797
|
+
import { stripTerminalSequences as stripTerminalSequences13 } from "@earendil-works/pi-tui";
|
|
17865
18798
|
function createTerminalUi(options) {
|
|
17866
18799
|
const state = {
|
|
17867
18800
|
theme: options.theme,
|
|
@@ -17946,7 +18879,7 @@ function createTerminalUi(options) {
|
|
|
17946
18879
|
changed();
|
|
17947
18880
|
},
|
|
17948
18881
|
setTitle(title) {
|
|
17949
|
-
options.tui.terminal.setTitle(
|
|
18882
|
+
options.tui.terminal.setTitle(stripTerminalSequences13(title).replace(/[\x00-\x1f\x7f]/g, " "));
|
|
17950
18883
|
},
|
|
17951
18884
|
pasteToEditor(text) {
|
|
17952
18885
|
const editor = options.getEditor?.();
|
|
@@ -19241,7 +20174,7 @@ class TranscriptModel {
|
|
|
19241
20174
|
}
|
|
19242
20175
|
|
|
19243
20176
|
// src/terminal/opentui/palette.ts
|
|
19244
|
-
import { stripTerminalSequences as
|
|
20177
|
+
import { stripTerminalSequences as stripTerminalSequences14, truncateToWidth as truncateToWidth26, wrapTextWithAnsi as wrapTextWithAnsi18 } from "@earendil-works/pi-tui";
|
|
19245
20178
|
function paletteCommandColumnWidth(items, terminalWidth) {
|
|
19246
20179
|
const widestName = items.reduce((width, item) => Math.max(width, formatTerminalCommandLabel(item.name, item.aliases).length + 1), 1);
|
|
19247
20180
|
const commandLimit = Math.max(1, Math.floor((terminalWidth - 8) / 2));
|
|
@@ -19249,13 +20182,13 @@ function paletteCommandColumnWidth(items, terminalWidth) {
|
|
|
19249
20182
|
}
|
|
19250
20183
|
function paletteTextLines(text, width) {
|
|
19251
20184
|
const columns = Math.max(1, width);
|
|
19252
|
-
const safe =
|
|
20185
|
+
const safe = stripTerminalSequences14(text).replace(/[\x00-\x09\x0b-\x1f\x7f]/gu, " ");
|
|
19253
20186
|
const lines = safe.split(`
|
|
19254
|
-
`).flatMap((line) => line ?
|
|
20187
|
+
`).flatMap((line) => line ? wrapTextWithAnsi18(line, columns) : [""]);
|
|
19255
20188
|
if (lines.length <= 3)
|
|
19256
20189
|
return lines;
|
|
19257
20190
|
const result = lines.slice(0, 3);
|
|
19258
|
-
result[2] = `${
|
|
20191
|
+
result[2] = `${truncateToWidth26(result[2] ?? "", columns - 1, "", false)}\u2026`;
|
|
19259
20192
|
return result;
|
|
19260
20193
|
}
|
|
19261
20194
|
function rank(item, query) {
|
|
@@ -19860,6 +20793,7 @@ class OpenTuiApplication {
|
|
|
19860
20793
|
host = new PiDialogHost(() => this.change());
|
|
19861
20794
|
transcript = new TranscriptModel;
|
|
19862
20795
|
listeners = new Set;
|
|
20796
|
+
animationListeners = new Set;
|
|
19863
20797
|
cleanup = [];
|
|
19864
20798
|
statuses = new Map;
|
|
19865
20799
|
widgets = new Map;
|
|
@@ -19884,8 +20818,10 @@ class OpenTuiApplication {
|
|
|
19884
20818
|
editorFactory;
|
|
19885
20819
|
customEditor;
|
|
19886
20820
|
draft = "";
|
|
20821
|
+
mouseTail = new MouseReportTail;
|
|
19887
20822
|
draftEpoch = 0;
|
|
19888
20823
|
draftCursorOffset = null;
|
|
20824
|
+
paletteCaret = null;
|
|
19889
20825
|
attachments = new ComposerAttachments;
|
|
19890
20826
|
insertion = null;
|
|
19891
20827
|
fileCompletion = null;
|
|
@@ -19930,8 +20866,12 @@ class OpenTuiApplication {
|
|
|
19930
20866
|
done = new Promise((resolve) => {
|
|
19931
20867
|
this.finish = resolve;
|
|
19932
20868
|
});
|
|
19933
|
-
pendingPolling = false;
|
|
19934
20869
|
pendingBusy = false;
|
|
20870
|
+
decisionWatch;
|
|
20871
|
+
remoteWatch;
|
|
20872
|
+
remoteState = null;
|
|
20873
|
+
remoteAsked = new Set;
|
|
20874
|
+
pendingRequests = [];
|
|
19935
20875
|
pendingAbort;
|
|
19936
20876
|
pendingId;
|
|
19937
20877
|
dismissedDecisions = new Set;
|
|
@@ -19955,14 +20895,17 @@ class OpenTuiApplication {
|
|
|
19955
20895
|
const target = raw ? linkTarget(raw, { base: this.runtime?.cwd }) : null;
|
|
19956
20896
|
const next = target ? `${target.kind}:${"url" in target ? target.url : ("address" in target) ? target.address : target.path}` : raw;
|
|
19957
20897
|
const entered = next !== this.hoveredLink;
|
|
20898
|
+
if (!entered && !next)
|
|
20899
|
+
return;
|
|
19958
20900
|
if (!entered && x === this.hoveredAt.x && y === this.hoveredAt.y)
|
|
19959
20901
|
return;
|
|
19960
20902
|
this.hoveredLink = next;
|
|
19961
20903
|
this.hoveredLinkId = next ? this.renderer?.getLinkIdAt(x, y) ?? 0 : 0;
|
|
19962
20904
|
this.hoveredAt = { x, y };
|
|
19963
|
-
if (entered)
|
|
20905
|
+
if (entered) {
|
|
19964
20906
|
this.renderer?.setMousePointer(next ? "pointer" : "default");
|
|
19965
|
-
|
|
20907
|
+
this.change();
|
|
20908
|
+
}
|
|
19966
20909
|
this.renderer?.requestRender();
|
|
19967
20910
|
}
|
|
19968
20911
|
activateLinkAt(x, y, modifiers = {}) {
|
|
@@ -20003,6 +20946,29 @@ class OpenTuiApplication {
|
|
|
20003
20946
|
this.listeners.delete(listener);
|
|
20004
20947
|
};
|
|
20005
20948
|
}
|
|
20949
|
+
subscribeAnimation(listener) {
|
|
20950
|
+
this.animationListeners.add(listener);
|
|
20951
|
+
return () => {
|
|
20952
|
+
this.animationListeners.delete(listener);
|
|
20953
|
+
};
|
|
20954
|
+
}
|
|
20955
|
+
animationView() {
|
|
20956
|
+
return {
|
|
20957
|
+
working: this.working(),
|
|
20958
|
+
subagents: subagentRoster(this.subagents, Math.max(20, this.host.columns - 4), this.workingSpinnerFrame(this.startedAt ?? Date.now()))
|
|
20959
|
+
};
|
|
20960
|
+
}
|
|
20961
|
+
animate() {
|
|
20962
|
+
if (this.startedAt !== null || this.compacting) {
|
|
20963
|
+
for (const listener of this.animationListeners) {
|
|
20964
|
+
try {
|
|
20965
|
+
listener();
|
|
20966
|
+
} catch {}
|
|
20967
|
+
}
|
|
20968
|
+
}
|
|
20969
|
+
if (this.sideQuestion?.state === "thinking")
|
|
20970
|
+
this.change();
|
|
20971
|
+
}
|
|
20006
20972
|
get hasFailure() {
|
|
20007
20973
|
return !!this.failure;
|
|
20008
20974
|
}
|
|
@@ -20242,7 +21208,8 @@ class OpenTuiApplication {
|
|
|
20242
21208
|
subagents: () => this.subagents,
|
|
20243
21209
|
editFile: (path) => this.editFile(path),
|
|
20244
21210
|
suspend: () => this.suspend(),
|
|
20245
|
-
hotkeys: () => this.hotkeys()
|
|
21211
|
+
hotkeys: () => this.hotkeys(),
|
|
21212
|
+
watchRemoteControl: () => this.watchRemoteControl()
|
|
20246
21213
|
});
|
|
20247
21214
|
this.cleanup.push(this.runtime.subscribe((event) => this.accept(event)));
|
|
20248
21215
|
this.cleanup.push(this.runtime.onBeforeSessionChange(() => this.resetPresentation()));
|
|
@@ -20255,16 +21222,18 @@ class OpenTuiApplication {
|
|
|
20255
21222
|
this.initialized = true;
|
|
20256
21223
|
this.refresh();
|
|
20257
21224
|
this.refreshSubagents(true);
|
|
21225
|
+
const decisionWatch = new AbortController;
|
|
21226
|
+
this.decisionWatch = decisionWatch;
|
|
21227
|
+
this.cleanup.push(() => decisionWatch.abort());
|
|
21228
|
+
this.watchDecisions(decisionWatch.signal);
|
|
20258
21229
|
let lastSubagentPoll = 0;
|
|
20259
21230
|
const tick = setInterval(() => {
|
|
20260
|
-
|
|
20261
|
-
this.change();
|
|
21231
|
+
this.animate();
|
|
20262
21232
|
const now = Date.now();
|
|
20263
21233
|
if (this.startedAt !== null && now - lastSubagentPoll >= 1000) {
|
|
20264
21234
|
lastSubagentPoll = now;
|
|
20265
21235
|
this.refreshSubagents();
|
|
20266
21236
|
}
|
|
20267
|
-
this.decisions();
|
|
20268
21237
|
}, 100);
|
|
20269
21238
|
const git = setInterval(() => {
|
|
20270
21239
|
this.refreshBranch();
|
|
@@ -20275,6 +21244,8 @@ class OpenTuiApplication {
|
|
|
20275
21244
|
});
|
|
20276
21245
|
await this.refreshBranch();
|
|
20277
21246
|
this.change();
|
|
21247
|
+
if (process.env[REMOTE_CONTROL_ENV] === "1")
|
|
21248
|
+
this.commands.execute("/remote-control");
|
|
20278
21249
|
} catch (error) {
|
|
20279
21250
|
this.failure = error instanceof Error ? error : new Error(String(error));
|
|
20280
21251
|
this.notify(this.failure.message, "error");
|
|
@@ -20570,20 +21541,82 @@ class OpenTuiApplication {
|
|
|
20570
21541
|
this.transcript.invalidate();
|
|
20571
21542
|
this.change();
|
|
20572
21543
|
}
|
|
20573
|
-
|
|
20574
|
-
if (this.
|
|
21544
|
+
watchRemoteControl() {
|
|
21545
|
+
if (this.remoteWatch || this.stopped)
|
|
20575
21546
|
return;
|
|
20576
|
-
|
|
20577
|
-
|
|
20578
|
-
|
|
20579
|
-
|
|
20580
|
-
|
|
20581
|
-
|
|
21547
|
+
const watch = new AbortController;
|
|
21548
|
+
this.remoteWatch = watch;
|
|
21549
|
+
this.cleanup.push(() => watch.abort());
|
|
21550
|
+
(async () => {
|
|
21551
|
+
let revision;
|
|
21552
|
+
try {
|
|
21553
|
+
while (!watch.signal.aborted && !this.stopped) {
|
|
21554
|
+
let status;
|
|
21555
|
+
try {
|
|
21556
|
+
status = await controlCall(revision === undefined ? "terminal.remoteControl.status" : "terminal.remoteControl.status.wait", { revision }, 25000, watch.signal);
|
|
21557
|
+
} catch {
|
|
21558
|
+
if (watch.signal.aborted || this.stopped)
|
|
21559
|
+
return;
|
|
21560
|
+
revision = undefined;
|
|
21561
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
21562
|
+
continue;
|
|
21563
|
+
}
|
|
21564
|
+
revision = status.revision;
|
|
21565
|
+
const state = !status.running ? null : status.devices.some((device) => device.connected) ? "connected" : "waiting";
|
|
21566
|
+
if (state !== this.remoteState) {
|
|
21567
|
+
this.remoteState = state;
|
|
21568
|
+
this.change();
|
|
21569
|
+
}
|
|
21570
|
+
const request = status.request;
|
|
21571
|
+
const ui = this.ui;
|
|
21572
|
+
if (request && ui && !this.remoteAsked.has(request.id) && !this.host.hasOverlay()) {
|
|
21573
|
+
this.remoteAsked.add(request.id);
|
|
21574
|
+
ui.confirm("Allow remote control?", `${request.label} wants to control this session: send messages, stop replies, and answer approvals and questions.`).then((allow) => controlCall("terminal.remoteControl.confirm", { requestId: request.id, allow })).catch((error) => this.notify(error instanceof Error ? error.message : String(error), "error"));
|
|
21575
|
+
}
|
|
21576
|
+
if (!status.running && !request)
|
|
21577
|
+
return;
|
|
21578
|
+
}
|
|
21579
|
+
} finally {
|
|
21580
|
+
if (this.remoteWatch === watch)
|
|
21581
|
+
this.remoteWatch = undefined;
|
|
21582
|
+
if (this.remoteState !== null) {
|
|
21583
|
+
this.remoteState = null;
|
|
21584
|
+
this.change();
|
|
21585
|
+
}
|
|
21586
|
+
}
|
|
21587
|
+
})();
|
|
21588
|
+
}
|
|
21589
|
+
async watchDecisions(signal) {
|
|
21590
|
+
let revision;
|
|
21591
|
+
while (!signal.aborted && !this.stopped) {
|
|
21592
|
+
try {
|
|
21593
|
+
const snapshot = await controlCall("terminal.pending.wait", { revision }, 25000, signal);
|
|
21594
|
+
revision = snapshot.revision;
|
|
21595
|
+
this.decisions(snapshot.requests);
|
|
21596
|
+
} catch (error) {
|
|
21597
|
+
if (signal.aborted || this.stopped)
|
|
21598
|
+
return;
|
|
20582
21599
|
this.notify(error instanceof Error ? error.message : String(error), "error");
|
|
20583
|
-
|
|
20584
|
-
|
|
20585
|
-
|
|
21600
|
+
revision = undefined;
|
|
21601
|
+
await new Promise((resolve) => {
|
|
21602
|
+
const timer = setTimeout(done, 1000);
|
|
21603
|
+
function done() {
|
|
21604
|
+
clearTimeout(timer);
|
|
21605
|
+
signal.removeEventListener("abort", done);
|
|
21606
|
+
resolve();
|
|
21607
|
+
}
|
|
21608
|
+
signal.addEventListener("abort", done, { once: true });
|
|
21609
|
+
if (signal.aborted)
|
|
21610
|
+
done();
|
|
21611
|
+
});
|
|
21612
|
+
}
|
|
20586
21613
|
}
|
|
21614
|
+
}
|
|
21615
|
+
async decisions(requests) {
|
|
21616
|
+
if (!this.runtime || this.stopped)
|
|
21617
|
+
return;
|
|
21618
|
+
requests ??= await this.runtime.pending();
|
|
21619
|
+
this.pendingRequests = requests;
|
|
20587
21620
|
if (this.pendingId && !requests.some((request) => request.requestId === this.pendingId))
|
|
20588
21621
|
this.pendingAbort?.abort();
|
|
20589
21622
|
if (this.pendingBusy)
|
|
@@ -20624,6 +21657,11 @@ class OpenTuiApplication {
|
|
|
20624
21657
|
this.pendingBusy = false;
|
|
20625
21658
|
this.pendingId = undefined;
|
|
20626
21659
|
this.pendingAbort = undefined;
|
|
21660
|
+
if (!this.stopped && this.pendingRequests.some((item) => !this.dismissedDecisions.has(item.requestId))) {
|
|
21661
|
+
setTimeout(() => {
|
|
21662
|
+
this.decisions(this.pendingRequests);
|
|
21663
|
+
}, 100);
|
|
21664
|
+
}
|
|
20627
21665
|
}
|
|
20628
21666
|
}
|
|
20629
21667
|
async showQuestionDock(questions, signal) {
|
|
@@ -20855,7 +21893,7 @@ class OpenTuiApplication {
|
|
|
20855
21893
|
this.session.setThinkingLevel(next);
|
|
20856
21894
|
}
|
|
20857
21895
|
extensionShortcut(data) {
|
|
20858
|
-
const shortcut = [...this.session.extensionRunner.getShortcuts(this.keybindings.getResolvedBindings()).entries()].find(([key]) =>
|
|
21896
|
+
const shortcut = [...this.session.extensionRunner.getShortcuts(this.keybindings.getResolvedBindings()).entries()].find(([key]) => matchesKey20(data, key));
|
|
20859
21897
|
if (!shortcut)
|
|
20860
21898
|
return false;
|
|
20861
21899
|
this.attempt(() => shortcut[1].handler(this.session.extensionRunner.createContext()));
|
|
@@ -20916,7 +21954,7 @@ class OpenTuiApplication {
|
|
|
20916
21954
|
if (this.paletteSuppressed)
|
|
20917
21955
|
return null;
|
|
20918
21956
|
const slash = /^\/([^\s]*)$/u.exec(this.draft);
|
|
20919
|
-
const skill =
|
|
21957
|
+
const skill = this.bashMode ? null : skillTokenAt(this.draft, this.paletteCaret ?? this.draft.length);
|
|
20920
21958
|
if (!this.paletteOpen && (this.bashMode || !slash && !skill))
|
|
20921
21959
|
return null;
|
|
20922
21960
|
let items = [];
|
|
@@ -20929,7 +21967,7 @@ class OpenTuiApplication {
|
|
|
20929
21967
|
} catch {
|
|
20930
21968
|
return null;
|
|
20931
21969
|
}
|
|
20932
|
-
const filter = this.paletteOpen ? this.paletteFilter : skill?.
|
|
21970
|
+
const filter = this.paletteOpen ? this.paletteFilter : skill?.query ?? slash?.[1] ?? "";
|
|
20933
21971
|
const matched = matchPalette(items, filter);
|
|
20934
21972
|
if (!matched.length)
|
|
20935
21973
|
return null;
|
|
@@ -20994,6 +22032,14 @@ class OpenTuiApplication {
|
|
|
20994
22032
|
this.paletteOpen = false;
|
|
20995
22033
|
this.paletteSuppressed = true;
|
|
20996
22034
|
this.paletteIndex = 0;
|
|
22035
|
+
const token = this.bashMode ? null : skillTokenAt(this.draft, this.paletteCaret ?? this.draft.length);
|
|
22036
|
+
if (token) {
|
|
22037
|
+
const tail = this.draft.slice(token.to);
|
|
22038
|
+
const suffix = tail === "" ? " " : /^[\s.,;:!?)]/u.test(tail) ? "" : " ";
|
|
22039
|
+
const inserted = `${item.prefix ?? "$"}${item.name}${suffix}`;
|
|
22040
|
+
this.setDraftExternal(`${this.draft.slice(0, token.from)}${inserted}${tail}`, token.from + inserted.length);
|
|
22041
|
+
return true;
|
|
22042
|
+
}
|
|
20997
22043
|
const text = `${item.prefix ?? "/"}${item.name} `;
|
|
20998
22044
|
this.setDraftExternal(text, text.length);
|
|
20999
22045
|
return true;
|
|
@@ -21007,7 +22053,7 @@ class OpenTuiApplication {
|
|
|
21007
22053
|
this.draftEpoch += 1;
|
|
21008
22054
|
this.change();
|
|
21009
22055
|
}
|
|
21010
|
-
setDraft(value) {
|
|
22056
|
+
setDraft(value, caret) {
|
|
21011
22057
|
if (this.paletteOpen) {
|
|
21012
22058
|
this.paletteFilter = value.startsWith("/") && !/\s/u.test(value) ? value.slice(1) : value;
|
|
21013
22059
|
this.paletteIndex = 0;
|
|
@@ -21015,15 +22061,20 @@ class OpenTuiApplication {
|
|
|
21015
22061
|
this.change();
|
|
21016
22062
|
return;
|
|
21017
22063
|
}
|
|
22064
|
+
let nextCaret = caret;
|
|
21018
22065
|
let modeChanged = false;
|
|
21019
22066
|
if (!this.bashMode) {
|
|
21020
22067
|
const bash = splitBashDraft(value);
|
|
21021
22068
|
if (bash.bashMode) {
|
|
21022
22069
|
modeChanged = true;
|
|
21023
22070
|
this.applyComposerMode("bash");
|
|
22071
|
+
if (nextCaret !== undefined)
|
|
22072
|
+
nextCaret = Math.max(0, nextCaret - (value.length - bash.body.length));
|
|
21024
22073
|
}
|
|
21025
22074
|
value = bash.body;
|
|
21026
22075
|
}
|
|
22076
|
+
if (nextCaret !== undefined)
|
|
22077
|
+
this.paletteCaret = nextCaret;
|
|
21027
22078
|
if (value === this.draft) {
|
|
21028
22079
|
if (modeChanged)
|
|
21029
22080
|
this.change();
|
|
@@ -21042,12 +22093,14 @@ class OpenTuiApplication {
|
|
|
21042
22093
|
this.change();
|
|
21043
22094
|
}
|
|
21044
22095
|
setDraftExternal(value, cursorOffset, preserveBashMode = false) {
|
|
22096
|
+
this.mouseTail.reset();
|
|
21045
22097
|
this.resetHistoryBrowse();
|
|
21046
22098
|
const bash = preserveBashMode ? { body: value, bashMode: this.bashMode } : splitBashDraft(value);
|
|
21047
22099
|
this.invalidateFileCompletion();
|
|
21048
22100
|
this.applyComposerMode(bash.bashMode ? "bash" : this.planMode ? "plan" : "normal");
|
|
21049
22101
|
const body = bash.body;
|
|
21050
22102
|
this.draft = body;
|
|
22103
|
+
this.paletteCaret = null;
|
|
21051
22104
|
this.attachments.retain(body);
|
|
21052
22105
|
this.draftCursorOffset = cursorOffset ?? null;
|
|
21053
22106
|
this.draftEpoch += 1;
|
|
@@ -21073,6 +22126,7 @@ class OpenTuiApplication {
|
|
|
21073
22126
|
this.invalidateFileCompletion();
|
|
21074
22127
|
this.applyComposerMode("bash");
|
|
21075
22128
|
this.draft = body;
|
|
22129
|
+
this.paletteCaret = null;
|
|
21076
22130
|
this.draftCursorOffset = null;
|
|
21077
22131
|
this.draftEpoch += 1;
|
|
21078
22132
|
this.paletteSuppressed = false;
|
|
@@ -21088,11 +22142,13 @@ class OpenTuiApplication {
|
|
|
21088
22142
|
this.change();
|
|
21089
22143
|
}
|
|
21090
22144
|
clearDraft() {
|
|
22145
|
+
this.mouseTail.reset();
|
|
21091
22146
|
this.resetHistoryBrowse();
|
|
21092
22147
|
this.invalidateFileCompletion();
|
|
21093
22148
|
this.applyComposerMode(this.planMode ? "plan" : "normal");
|
|
21094
22149
|
this.draft = "";
|
|
21095
22150
|
this.attachments.clear();
|
|
22151
|
+
this.paletteCaret = null;
|
|
21096
22152
|
this.draftCursorOffset = null;
|
|
21097
22153
|
this.draftEpoch += 1;
|
|
21098
22154
|
this.paletteSuppressed = false;
|
|
@@ -21136,7 +22192,8 @@ class OpenTuiApplication {
|
|
|
21136
22192
|
this.input(() => this.onSubmitPrompt());
|
|
21137
22193
|
}
|
|
21138
22194
|
onSubmitPrompt() {
|
|
21139
|
-
this.
|
|
22195
|
+
this.mouseTail.reset();
|
|
22196
|
+
this.submit(this.bashMode ? `!${this.draft}` : this.draft, true);
|
|
21140
22197
|
}
|
|
21141
22198
|
async runBash(text) {
|
|
21142
22199
|
const command = /^\s*!\s*([\s\S]+)$/u.exec(text)?.[1]?.trim();
|
|
@@ -21203,16 +22260,15 @@ class OpenTuiApplication {
|
|
|
21203
22260
|
this.enqueuePlan(text, images);
|
|
21204
22261
|
return;
|
|
21205
22262
|
}
|
|
21206
|
-
const expanded = this.commands.expandSkill(text);
|
|
21207
22263
|
if (this.planBarrierOpen) {
|
|
21208
|
-
this.deferredInputs.push({ kind: "prompt", text
|
|
22264
|
+
this.deferredInputs.push({ kind: "prompt", text, followUp, images });
|
|
21209
22265
|
this.notify("Message queued to run after the current response.");
|
|
21210
22266
|
this.change();
|
|
21211
22267
|
return;
|
|
21212
22268
|
}
|
|
21213
22269
|
if (!this.session.isIdle)
|
|
21214
22270
|
this.notify(followUp ? "Follow-up message queued." : "Steering message queued.");
|
|
21215
|
-
await this.runtime.submit(
|
|
22271
|
+
await this.runtime.submit(text, followUp, images);
|
|
21216
22272
|
} finally {
|
|
21217
22273
|
if (command)
|
|
21218
22274
|
this.commandBusy = false;
|
|
@@ -21230,9 +22286,16 @@ class OpenTuiApplication {
|
|
|
21230
22286
|
const last = this.session.messages.at(-1);
|
|
21231
22287
|
if (last?.role !== "assistant" || last.stopReason === "error" || last.stopReason === "aborted")
|
|
21232
22288
|
return;
|
|
21233
|
-
const
|
|
21234
|
-
if (
|
|
21235
|
-
this.planChoice.show(plan.title);
|
|
22289
|
+
const outcome = parsePlanOutcome(this.session.getLastAssistantText() ?? "");
|
|
22290
|
+
if (outcome.kind === "plan_ready")
|
|
22291
|
+
this.planChoice.show(outcome.plan.title);
|
|
22292
|
+
else {
|
|
22293
|
+
this.planChoice.clear();
|
|
22294
|
+
if (outcome.kind === "blocked")
|
|
22295
|
+
this.notify("Planning stopped because user input is unavailable.", "warning");
|
|
22296
|
+
else if (outcome.kind === "invalid")
|
|
22297
|
+
this.notify("The plan reply did not include a valid plan or blocked outcome.", "warning");
|
|
22298
|
+
}
|
|
21236
22299
|
}
|
|
21237
22300
|
implementPlan(title) {
|
|
21238
22301
|
this.planChoice.clear();
|
|
@@ -21353,6 +22416,7 @@ class OpenTuiApplication {
|
|
|
21353
22416
|
this.applyComposerMode(mode);
|
|
21354
22417
|
this.draft = parsed.body;
|
|
21355
22418
|
this.attachments.clearForDraft(this.draft);
|
|
22419
|
+
this.paletteCaret = null;
|
|
21356
22420
|
this.draftCursorOffset = this.draft.length;
|
|
21357
22421
|
this.draftEpoch += 1;
|
|
21358
22422
|
this.paletteSuppressed = true;
|
|
@@ -21607,9 +22671,9 @@ class OpenTuiApplication {
|
|
|
21607
22671
|
const hidden = !this.session.settingsManager.getHideThinkingBlock();
|
|
21608
22672
|
this.session.settingsManager.setHideThinkingBlock(hidden);
|
|
21609
22673
|
this.transcript.setThinkingHidden(hidden);
|
|
21610
|
-
} else if (is("app.message.
|
|
22674
|
+
} else if (is("app.message.steer")) {
|
|
21611
22675
|
const editor = this.customEditor;
|
|
21612
|
-
this.submit(editor?.getExpandedText?.() ?? (this.bashMode ? `!${this.draft}` : this.draft),
|
|
22676
|
+
this.submit(editor?.getExpandedText?.() ?? (this.bashMode ? `!${this.draft}` : this.draft), false);
|
|
21613
22677
|
} else if (is("app.message.dequeue")) {
|
|
21614
22678
|
const pending = this.session.clearQueue();
|
|
21615
22679
|
const deferred = this.deferredInputs.map((input) => input.kind === "plan" ? `/plan ${input.text}` : input.text);
|
|
@@ -21634,11 +22698,29 @@ class OpenTuiApplication {
|
|
|
21634
22698
|
this.attempt(() => this.commands.execute("/new"));
|
|
21635
22699
|
else if (data === "?" && this.draft === "")
|
|
21636
22700
|
this.notify(this.hotkeys());
|
|
22701
|
+
else if (this.dropMouseReportTail(key, data))
|
|
22702
|
+
return true;
|
|
21637
22703
|
else if (!this.extensionShortcut(data))
|
|
21638
22704
|
return false;
|
|
21639
22705
|
this.change();
|
|
21640
22706
|
return true;
|
|
21641
22707
|
}
|
|
22708
|
+
dropMouseReportTail(key, data) {
|
|
22709
|
+
const match = this.mouseTail.push(data);
|
|
22710
|
+
if (!match)
|
|
22711
|
+
return false;
|
|
22712
|
+
if (!match.inserted) {
|
|
22713
|
+
this.change();
|
|
22714
|
+
return true;
|
|
22715
|
+
}
|
|
22716
|
+
const caret = key.cursorOffset ?? this.draft.length;
|
|
22717
|
+
const start = caret - match.inserted.length;
|
|
22718
|
+
const at = start >= 0 && this.draft.slice(start, caret) === match.inserted ? start : this.draft.endsWith(match.inserted) ? this.draft.length - match.inserted.length : -1;
|
|
22719
|
+
if (at < 0)
|
|
22720
|
+
return false;
|
|
22721
|
+
this.setDraftExternal(this.draft.slice(0, at) + this.draft.slice(at + match.inserted.length), at);
|
|
22722
|
+
return true;
|
|
22723
|
+
}
|
|
21642
22724
|
hotkeys() {
|
|
21643
22725
|
return [
|
|
21644
22726
|
"Tab files/folders \xB7 Shift+Tab plan mode",
|
|
@@ -21647,7 +22729,7 @@ class OpenTuiApplication {
|
|
|
21647
22729
|
"Ctrl+L model",
|
|
21648
22730
|
"Ctrl+N new session",
|
|
21649
22731
|
"\u2191/\u2193 at either draft endpoint browse older/newer history \xB7 Ctrl+\u2191/\u2193 anywhere",
|
|
21650
|
-
"Enter send or
|
|
22732
|
+
"Enter send or queue \xB7 Cmd/Ctrl/Alt+Enter steer \xB7 Esc dismisses btw or stops reply",
|
|
21651
22733
|
"Ctrl+C clear or quit \xB7 Ctrl+D quit",
|
|
21652
22734
|
"PgUp/PgDn transcript"
|
|
21653
22735
|
].join(`
|
|
@@ -21714,6 +22796,7 @@ class OpenTuiApplication {
|
|
|
21714
22796
|
(widget.placement === "belowEditor" ? below : above).push(lines);
|
|
21715
22797
|
}
|
|
21716
22798
|
return {
|
|
22799
|
+
remoteControl: this.remoteState,
|
|
21717
22800
|
home: !transcript.hasMultilineNotice && transcript.items.every((item) => item.kind === "notice"),
|
|
21718
22801
|
sessionName: snapshot?.name,
|
|
21719
22802
|
cwd: snapshot?.cwd ?? process.cwd(),
|
|
@@ -21844,6 +22927,7 @@ class OpenTuiApplication {
|
|
|
21844
22927
|
insert(text) {
|
|
21845
22928
|
if (!text)
|
|
21846
22929
|
return;
|
|
22930
|
+
this.mouseTail.reset();
|
|
21847
22931
|
if (this.customEditor?.getExpandedText) {
|
|
21848
22932
|
const editor = this.customEditor;
|
|
21849
22933
|
if (editor.insertTextAtCursor) {
|
|
@@ -21910,6 +22994,8 @@ class OpenTuiApplication {
|
|
|
21910
22994
|
}
|
|
21911
22995
|
};
|
|
21912
22996
|
this.stopped = true;
|
|
22997
|
+
this.mouseTail.reset();
|
|
22998
|
+
this.decisionWatch?.abort();
|
|
21913
22999
|
protect(() => this.renderer?.setMousePointer("default"));
|
|
21914
23000
|
this.hoveredLink = null;
|
|
21915
23001
|
if (this.toastTimer)
|
|
@@ -22999,7 +24085,7 @@ function terminalSelectionText(selection) {
|
|
|
22999
24085
|
}
|
|
23000
24086
|
|
|
23001
24087
|
// src/terminal/opentui/composerMarks.ts
|
|
23002
|
-
import { visibleWidth as
|
|
24088
|
+
import { visibleWidth as visibleWidth18 } from "@earendil-works/pi-tui";
|
|
23003
24089
|
|
|
23004
24090
|
// src/terminal/opentui/slashCommandHighlight.ts
|
|
23005
24091
|
function leadingSlashCommandRange(text, names) {
|
|
@@ -23040,35 +24126,43 @@ function bufferOffset(text, index) {
|
|
|
23040
24126
|
`);
|
|
23041
24127
|
let offset = 0;
|
|
23042
24128
|
for (const [position, line] of lines.entries())
|
|
23043
|
-
offset +=
|
|
24129
|
+
offset += visibleWidth18(line) + (position < lines.length - 1 ? 1 : 0);
|
|
23044
24130
|
return offset;
|
|
23045
24131
|
}
|
|
23046
|
-
function
|
|
23047
|
-
|
|
23048
|
-
|
|
23049
|
-
|
|
23050
|
-
|
|
23051
|
-
|
|
23052
|
-
|
|
23053
|
-
|
|
23054
|
-
|
|
23055
|
-
for (const mark of marks)
|
|
23056
|
-
target.extmarks.delete(mark.id);
|
|
23057
|
-
return;
|
|
24132
|
+
function indexForBufferOffset(text, offset) {
|
|
24133
|
+
let cells = 0;
|
|
24134
|
+
let index = 0;
|
|
24135
|
+
for (const character of text) {
|
|
24136
|
+
if (cells >= offset)
|
|
24137
|
+
return index;
|
|
24138
|
+
cells += character === `
|
|
24139
|
+
` ? 1 : visibleWidth18(character);
|
|
24140
|
+
index += character.length;
|
|
23058
24141
|
}
|
|
23059
|
-
|
|
23060
|
-
|
|
23061
|
-
|
|
24142
|
+
return text.length;
|
|
24143
|
+
}
|
|
24144
|
+
function skillInvocationRanges(text, names) {
|
|
24145
|
+
return skillInvocationMatches(text).filter((match) => names.includes(match.name)).map((match) => ({ start: match.from, end: match.to }));
|
|
24146
|
+
}
|
|
24147
|
+
function syncTextMarks(target, ranges, typeId, styleId) {
|
|
24148
|
+
const expected = ranges.map((range) => {
|
|
24149
|
+
const start = bufferOffset(target.plainText, range.start);
|
|
24150
|
+
return { start, end: start + visibleWidth18(target.plainText.slice(range.start, range.end)) };
|
|
24151
|
+
});
|
|
24152
|
+
const marks = target.extmarks.getAllForTypeId(typeId).sort((left, right) => left.start - right.start);
|
|
24153
|
+
if (marks.length === expected.length && expected.every((range, index) => marks[index].start === range.start && marks[index].end === range.end))
|
|
23062
24154
|
return;
|
|
23063
24155
|
for (const mark of marks)
|
|
23064
24156
|
target.extmarks.delete(mark.id);
|
|
23065
|
-
|
|
24157
|
+
for (const range of expected)
|
|
24158
|
+
target.extmarks.create({ start: range.start, end: range.end, virtual: true, styleId, typeId });
|
|
23066
24159
|
}
|
|
23067
24160
|
function syncSlashCommandMark(target, names, typeId, styleId) {
|
|
23068
|
-
|
|
24161
|
+
const range = leadingSlashCommandRange(target.plainText, names);
|
|
24162
|
+
syncTextMarks(target, range ? [range] : [], typeId, styleId);
|
|
23069
24163
|
}
|
|
23070
24164
|
function syncSkillInvocationMark(target, names, typeId, styleId) {
|
|
23071
|
-
|
|
24165
|
+
syncTextMarks(target, skillInvocationRanges(target.plainText, names), typeId, styleId);
|
|
23072
24166
|
}
|
|
23073
24167
|
function syncAttachmentMarks(target, labels, typeId, styleId) {
|
|
23074
24168
|
const byId = new Map(labels.map((label) => [label.id, label]));
|
|
@@ -23111,6 +24205,12 @@ function syncAttachmentMarks(target, labels, typeId, styleId) {
|
|
|
23111
24205
|
}
|
|
23112
24206
|
|
|
23113
24207
|
// src/terminal/opentui/statusBar.ts
|
|
24208
|
+
function contextReading(percent, window) {
|
|
24209
|
+
if (percent === null || percent === undefined || !Number.isFinite(percent))
|
|
24210
|
+
return "?";
|
|
24211
|
+
const bounded = Math.max(0, Math.min(999, percent));
|
|
24212
|
+
return `${bounded.toFixed(1)}%/${window && window > 0 ? formatTokenCount(window) : "?"}`;
|
|
24213
|
+
}
|
|
23114
24214
|
function cacheHitRate(cacheReadTokens, inputTokens) {
|
|
23115
24215
|
const total = Number.isFinite(inputTokens) ? Math.max(0, inputTokens) : 0;
|
|
23116
24216
|
const reads = Number.isFinite(cacheReadTokens) ? Math.max(0, cacheReadTokens) : 0;
|
|
@@ -23124,15 +24224,19 @@ function statusBarGroups(state) {
|
|
|
23124
24224
|
return [
|
|
23125
24225
|
`${project}:${branch}`,
|
|
23126
24226
|
`${singleLine(state.account ?? "") || "account unknown"} ${model} ${singleLine(state.thinking) || "off"}`,
|
|
23127
|
-
|
|
23128
|
-
|
|
24227
|
+
[
|
|
24228
|
+
`\u2191${formatTokenCount(state.inputTokens)} ${cacheHitRate(state.cacheReadTokens, state.inputTokens)} \u2193${formatTokenCount(state.outputTokens)}`,
|
|
24229
|
+
state.contextPercent === undefined ? "" : contextReading(state.contextPercent, state.contextWindow)
|
|
24230
|
+
].filter(Boolean).join(" "),
|
|
24231
|
+
state.remoteControl === "connected" ? "rc \u25CF" : state.remoteControl === "waiting" ? "rc" : ""
|
|
24232
|
+
].filter(Boolean);
|
|
23129
24233
|
}
|
|
23130
24234
|
function statusBarText(state) {
|
|
23131
24235
|
return statusBarGroups(state).join(" | ");
|
|
23132
24236
|
}
|
|
23133
24237
|
|
|
23134
24238
|
// src/terminal/opentui/workingLine.ts
|
|
23135
|
-
import { stripTerminalSequences as
|
|
24239
|
+
import { stripTerminalSequences as stripTerminalSequences15, truncateToWidth as truncateToWidth27, visibleWidth as visibleWidth19 } from "@earendil-works/pi-tui";
|
|
23136
24240
|
var SHIMMER_INTERVAL_MS = 120;
|
|
23137
24241
|
var SHIMMER_RADIUS = 2;
|
|
23138
24242
|
function workingLineParts(state, width) {
|
|
@@ -23163,8 +24267,8 @@ function workingLineParts(state, width) {
|
|
|
23163
24267
|
return { prefix, label, suffix };
|
|
23164
24268
|
let remaining = Math.max(0, Math.floor(width));
|
|
23165
24269
|
const fit = (text) => {
|
|
23166
|
-
const fitted =
|
|
23167
|
-
remaining = Math.max(0, remaining -
|
|
24270
|
+
const fitted = stripTerminalSequences15(truncateToWidth27(text, remaining, "\u2026", false));
|
|
24271
|
+
remaining = Math.max(0, remaining - visibleWidth19(fitted));
|
|
23168
24272
|
return fitted;
|
|
23169
24273
|
};
|
|
23170
24274
|
return { prefix: fit(prefix), label: fit(label), suffix: fit(suffix) };
|
|
@@ -23215,7 +24319,7 @@ function homeBrand(productName) {
|
|
|
23215
24319
|
}
|
|
23216
24320
|
|
|
23217
24321
|
// src/terminal/opentui/pendingMessages.ts
|
|
23218
|
-
import { stripTerminalSequences as
|
|
24322
|
+
import { stripTerminalSequences as stripTerminalSequences16, truncateToWidth as truncateToWidth28 } from "@earendil-works/pi-tui";
|
|
23219
24323
|
var labels = {
|
|
23220
24324
|
steering: "Steering",
|
|
23221
24325
|
followUp: "Follow-up",
|
|
@@ -23229,7 +24333,7 @@ function pendingMessageLines(messages, width, maxRows = 4) {
|
|
|
23229
24333
|
if (!columns || !rows || !messages.length)
|
|
23230
24334
|
return [];
|
|
23231
24335
|
const shown = messages.length > rows ? rows - 1 : rows;
|
|
23232
|
-
const fit = (text) =>
|
|
24336
|
+
const fit = (text) => stripTerminalSequences16(truncateToWidth28(text, columns, "\u2026", false));
|
|
23233
24337
|
const result = messages.slice(0, shown).map((message) => {
|
|
23234
24338
|
const text = singleLine(message.text.replace(/[\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, " "));
|
|
23235
24339
|
return fit(`${labels[message.kind]} \xB7 ${text || "(empty)"}`);
|
|
@@ -23695,8 +24799,9 @@ function TranscriptItemView(props) {
|
|
|
23695
24799
|
}
|
|
23696
24800
|
if (item.kind === "plan") {
|
|
23697
24801
|
return (() => {
|
|
23698
|
-
var _el$23 = _$createElement2("box"), _el$24 = _$createElement2("text"), _el$25 = _$
|
|
24802
|
+
var _el$23 = _$createElement2("box"), _el$24 = _$createElement2("text"), _el$25 = _$createElement2("box"), _el$26 = _$createElement2("markdown");
|
|
23699
24803
|
_$insertNode2(_el$23, _el$24);
|
|
24804
|
+
_$insertNode2(_el$23, _el$25);
|
|
23700
24805
|
_$insertNode2(_el$23, _el$26);
|
|
23701
24806
|
_$setProp2(_el$23, "border", ["left"]);
|
|
23702
24807
|
_$setProp2(_el$23, "flexDirection", "column");
|
|
@@ -23705,7 +24810,6 @@ function TranscriptItemView(props) {
|
|
|
23705
24810
|
_$setProp2(_el$23, "paddingTop", 1);
|
|
23706
24811
|
_$setProp2(_el$23, "paddingBottom", 1);
|
|
23707
24812
|
_$setProp2(_el$23, "flexShrink", 0);
|
|
23708
|
-
_$insertNode2(_el$24, _el$25);
|
|
23709
24813
|
_$setProp2(_el$24, "wrapMode", "word");
|
|
23710
24814
|
_$insert2(_el$24, () => item.title, null);
|
|
23711
24815
|
_$insert2(_el$24, _$createComponent2(Show2, {
|
|
@@ -23718,14 +24822,16 @@ function TranscriptItemView(props) {
|
|
|
23718
24822
|
return t.dim;
|
|
23719
24823
|
},
|
|
23720
24824
|
attributes: 0,
|
|
23721
|
-
children: "
|
|
24825
|
+
children: " streaming\u2026"
|
|
23722
24826
|
});
|
|
23723
24827
|
}
|
|
23724
24828
|
}), null);
|
|
24829
|
+
_$setProp2(_el$25, "height", 1);
|
|
24830
|
+
_$setProp2(_el$25, "flexShrink", 0);
|
|
23725
24831
|
_$setProp2(_el$26, "bg", "transparent");
|
|
23726
24832
|
_$setProp2(_el$26, "conceal", true);
|
|
23727
24833
|
_$effect2((_p$) => {
|
|
23728
|
-
var { planMode: _v$16, panel: _v$17, planMode: _v$18 } = t, _v$19 = TextAttributes2.BOLD, _v$20 = addHeadingOneSpacing(item.body), _v$21 = item.streaming, _v$22 = props.syntax, _v$23 = t.text, _v$24 = {
|
|
24834
|
+
var { planMode: _v$16, panel: _v$17, planMode: _v$18 } = t, _v$19 = TextAttributes2.BOLD | TextAttributes2.UNDERLINE, _v$20 = addHeadingOneSpacing(item.body), _v$21 = item.streaming, _v$22 = props.syntax, _v$23 = t.text, _v$24 = {
|
|
23729
24835
|
borderColor: t.dim,
|
|
23730
24836
|
cellPaddingX: 1
|
|
23731
24837
|
};
|
|
@@ -24685,7 +25791,7 @@ function Prompt(props) {
|
|
|
24685
25791
|
} finally {
|
|
24686
25792
|
syncing = false;
|
|
24687
25793
|
}
|
|
24688
|
-
props.app.setDraft(area.plainText);
|
|
25794
|
+
props.app.setDraft(area.plainText, indexForBufferOffset(area.plainText, area.cursorOffset));
|
|
24689
25795
|
};
|
|
24690
25796
|
createEffect2(() => {
|
|
24691
25797
|
view().attachments;
|
|
@@ -25347,6 +26453,15 @@ function OpenTuiRoot(props) {
|
|
|
25347
26453
|
const [state, setState] = createStore(props.app.view());
|
|
25348
26454
|
const off = props.app.subscribe(() => setState(reconcile(props.app.view())));
|
|
25349
26455
|
onCleanup2(off);
|
|
26456
|
+
const offAnimation = props.app.subscribeAnimation(() => {
|
|
26457
|
+
const animation = props.app.animationView();
|
|
26458
|
+
setState("working", reconcile({
|
|
26459
|
+
...animation.working,
|
|
26460
|
+
sessionName: state.working.sessionName
|
|
26461
|
+
}));
|
|
26462
|
+
setState("subagents", reconcile(animation.subagents));
|
|
26463
|
+
});
|
|
26464
|
+
onCleanup2(offAnimation);
|
|
25350
26465
|
useSelectionHandler((selection) => {
|
|
25351
26466
|
const selectedText = terminalSelectionText(selection);
|
|
25352
26467
|
if (selectedText !== undefined)
|
|
@@ -25497,7 +26612,7 @@ function OpenTuiRoot(props) {
|
|
|
25497
26612
|
if (key.eventType !== "press" || !key.sequence)
|
|
25498
26613
|
return;
|
|
25499
26614
|
if (prompt?.focused)
|
|
25500
|
-
props.app.setDraft(prompt.plainText);
|
|
26615
|
+
props.app.setDraft(prompt.plainText, indexForBufferOffset(prompt.plainText, prompt.cursorOffset));
|
|
25501
26616
|
const current = view();
|
|
25502
26617
|
const page = Math.max(1, Math.floor((dimensions().height - 8) / 2));
|
|
25503
26618
|
if (!current.overlay && !current.questionDock && (key.name === "pageup" || key.name === "pagedown" || key.ctrl && (key.name === "home" || key.name === "end"))) {
|