@oyasmi/pipiclaw 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/agent/channel-runner.d.ts +21 -4
- package/dist/agent/channel-runner.js +134 -18
- package/dist/agent/model-fallback.d.ts +64 -0
- package/dist/agent/model-fallback.js +125 -0
- package/dist/agent/run-queue.d.ts +2 -2
- package/dist/agent/runner-factory.d.ts +7 -2
- package/dist/agent/runner-factory.js +18 -6
- package/dist/agent/session-events.d.ts +2 -2
- package/dist/agent/status-render.d.ts +22 -0
- package/dist/agent/status-render.js +61 -0
- package/dist/agent/types.d.ts +9 -4
- package/dist/index.d.ts +2 -1
- package/dist/log.d.ts +7 -0
- package/dist/log.js +46 -24
- package/dist/main.js +15 -2
- package/dist/runtime/bootstrap.d.ts +17 -0
- package/dist/runtime/bootstrap.js +46 -76
- package/dist/runtime/channel-context.d.ts +44 -0
- package/dist/runtime/channel-context.js +15 -0
- package/dist/runtime/delivery.d.ts +3 -2
- package/dist/runtime/dingtalk.d.ts +1 -25
- package/dist/sandbox.js +7 -77
- package/dist/security/command-guard.js +0 -4
- package/dist/security/path-guard.js +0 -4
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +18 -0
- package/dist/shared/shell-escape.d.ts +0 -7
- package/dist/shared/shell-escape.js +0 -11
- package/dist/tools/bash.js +2 -2
- package/dist/tools/edit.js +2 -2
- package/dist/tools/read.js +6 -6
- package/dist/tools/write-content.js +3 -3
- package/dist/tui/app.d.ts +18 -0
- package/dist/tui/app.js +104 -0
- package/dist/tui/cli.d.ts +22 -0
- package/dist/tui/cli.js +116 -0
- package/dist/tui/colors.d.ts +9 -0
- package/dist/tui/colors.js +20 -0
- package/dist/tui/commands.d.ts +47 -0
- package/dist/tui/commands.js +64 -0
- package/dist/tui/pitui-frontend.d.ts +47 -0
- package/dist/tui/pitui-frontend.js +154 -0
- package/dist/tui/plain-frontend.d.ts +23 -0
- package/dist/tui/plain-frontend.js +56 -0
- package/dist/tui/renderer.d.ts +62 -0
- package/dist/tui/renderer.js +13 -0
- package/dist/tui/terminal-context.d.ts +27 -0
- package/dist/tui/terminal-context.js +84 -0
- package/dist/tui/turn-controller.d.ts +68 -0
- package/dist/tui/turn-controller.js +266 -0
- package/package.json +2 -1
- package/dist/security/platform.d.ts +0 -1
- package/dist/security/platform.js +0 -3
|
@@ -1,8 +1,7 @@
|
|
|
1
|
+
import type { FinalDelivery, ProgressStyle } from "./channel-context.js";
|
|
1
2
|
export type BusyMessageMode = "steer" | "followUp";
|
|
2
3
|
export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
|
|
3
4
|
export type ResponseMode = "full_progress_then_plain_final" | "rolling_progress_then_plain_final" | "final_card_only";
|
|
4
|
-
export type ProgressStyle = "full" | "rolling" | "none";
|
|
5
|
-
export type FinalDelivery = "plain" | "card";
|
|
6
5
|
export declare function progressStyleOf(mode: ResponseMode): ProgressStyle;
|
|
7
6
|
export declare function finalDeliveryOf(mode: ResponseMode): FinalDelivery;
|
|
8
7
|
export declare function isBusyMessageDefaultConfig(value: unknown): value is BusyMessageDefaultConfig;
|
|
@@ -31,29 +30,6 @@ export interface DingTalkEvent {
|
|
|
31
30
|
conversationId: string;
|
|
32
31
|
conversationType: string;
|
|
33
32
|
}
|
|
34
|
-
export interface DingTalkContext {
|
|
35
|
-
message: {
|
|
36
|
-
text: string;
|
|
37
|
-
rawText: string;
|
|
38
|
-
user: string;
|
|
39
|
-
userName?: string;
|
|
40
|
-
channel: string;
|
|
41
|
-
ts: string;
|
|
42
|
-
};
|
|
43
|
-
channelName?: string;
|
|
44
|
-
respond: (text: string, shouldLog?: boolean) => Promise<void>;
|
|
45
|
-
respondPlain: (text: string, shouldLog?: boolean) => Promise<boolean>;
|
|
46
|
-
replaceMessage: (text: string) => Promise<void>;
|
|
47
|
-
respondInThread: (text: string) => Promise<void>;
|
|
48
|
-
setTyping: (isTyping: boolean) => Promise<void>;
|
|
49
|
-
setWorking: (working: boolean) => Promise<void>;
|
|
50
|
-
deleteMessage: () => Promise<void>;
|
|
51
|
-
primeCard: (delayMs: number) => void;
|
|
52
|
-
flush: () => Promise<void>;
|
|
53
|
-
close: () => Promise<void>;
|
|
54
|
-
progressStyle: ProgressStyle;
|
|
55
|
-
finalDelivery: FinalDelivery;
|
|
56
|
-
}
|
|
57
33
|
export type BusyMessageResult = {
|
|
58
34
|
kind: "handled";
|
|
59
35
|
} | {
|
package/dist/sandbox.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { spawn
|
|
1
|
+
import { spawn } from "child_process";
|
|
2
2
|
import { shellEscape } from "./shared/shell-escape.js";
|
|
3
3
|
/**
|
|
4
4
|
* Error raised when sandbox configuration is invalid or the target sandbox is not
|
|
@@ -26,14 +26,6 @@ export function parseSandboxArg(value) {
|
|
|
26
26
|
}
|
|
27
27
|
export async function validateSandbox(config) {
|
|
28
28
|
if (config.type === "host") {
|
|
29
|
-
if (process.platform === "win32") {
|
|
30
|
-
try {
|
|
31
|
-
resolveWindowsHostShell();
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
throw new SandboxConfigError(error instanceof Error ? error.message : String(error));
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
29
|
return;
|
|
38
30
|
}
|
|
39
31
|
// Check if Docker is available
|
|
@@ -60,7 +52,6 @@ function execSimple(cmd, args) {
|
|
|
60
52
|
return new Promise((resolve, reject) => {
|
|
61
53
|
const child = spawn(cmd, args, {
|
|
62
54
|
stdio: ["ignore", "pipe", "pipe"],
|
|
63
|
-
windowsHide: true,
|
|
64
55
|
});
|
|
65
56
|
let stdout = "";
|
|
66
57
|
let stderr = "";
|
|
@@ -78,51 +69,6 @@ function execSimple(cmd, args) {
|
|
|
78
69
|
});
|
|
79
70
|
});
|
|
80
71
|
}
|
|
81
|
-
const WINDOWS_POSIX_SHELL_CANDIDATES = [
|
|
82
|
-
"bash",
|
|
83
|
-
"sh",
|
|
84
|
-
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
85
|
-
"C:\\Program Files\\Git\\usr\\bin\\bash.exe",
|
|
86
|
-
"C:\\Program Files (x86)\\Git\\bin\\bash.exe",
|
|
87
|
-
"C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",
|
|
88
|
-
];
|
|
89
|
-
let cachedWindowsHostShell;
|
|
90
|
-
function looksLikeUnixShellPath(shell) {
|
|
91
|
-
return shell.endsWith("/bash") || shell.endsWith("/sh");
|
|
92
|
-
}
|
|
93
|
-
function isUsablePosixShell(command) {
|
|
94
|
-
const result = spawnSync(command, ["-lc", "printf pipiclaw"], {
|
|
95
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
96
|
-
encoding: "utf-8",
|
|
97
|
-
windowsHide: true,
|
|
98
|
-
});
|
|
99
|
-
return !result.error && result.status === 0 && result.stdout === "pipiclaw";
|
|
100
|
-
}
|
|
101
|
-
function resolveWindowsHostShell() {
|
|
102
|
-
if (cachedWindowsHostShell) {
|
|
103
|
-
return cachedWindowsHostShell;
|
|
104
|
-
}
|
|
105
|
-
const configuredShell = process.env.PIPICLAW_SHELL?.trim();
|
|
106
|
-
const inheritedShell = process.env.SHELL?.trim();
|
|
107
|
-
const shellCandidates = [
|
|
108
|
-
configuredShell,
|
|
109
|
-
inheritedShell && looksLikeUnixShellPath(inheritedShell) ? inheritedShell.split("/").pop() : undefined,
|
|
110
|
-
...WINDOWS_POSIX_SHELL_CANDIDATES,
|
|
111
|
-
].filter((value) => Boolean(value));
|
|
112
|
-
for (const command of shellCandidates) {
|
|
113
|
-
if (isUsablePosixShell(command)) {
|
|
114
|
-
cachedWindowsHostShell = { command, args: ["-lc"] };
|
|
115
|
-
return cachedWindowsHostShell;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
throw new Error("Windows host sandbox requires a POSIX shell. Install Git Bash and ensure `bash` is on PATH, set `PIPICLAW_SHELL`, or use the Docker sandbox.");
|
|
119
|
-
}
|
|
120
|
-
function resolveHostShell() {
|
|
121
|
-
if (process.platform === "win32") {
|
|
122
|
-
return resolveWindowsHostShell();
|
|
123
|
-
}
|
|
124
|
-
return { command: "sh", args: ["-c"] };
|
|
125
|
-
}
|
|
126
72
|
/**
|
|
127
73
|
* Create an executor that runs commands either on host or in Docker container
|
|
128
74
|
*/
|
|
@@ -135,13 +81,11 @@ export function createExecutor(config) {
|
|
|
135
81
|
class HostExecutor {
|
|
136
82
|
async exec(command, options) {
|
|
137
83
|
return new Promise((resolve, reject) => {
|
|
138
|
-
const shell = resolveHostShell();
|
|
139
84
|
const child = (() => {
|
|
140
85
|
try {
|
|
141
|
-
return spawn(
|
|
86
|
+
return spawn("sh", ["-c", command], {
|
|
142
87
|
detached: true,
|
|
143
88
|
stdio: ["pipe", "pipe", "pipe"],
|
|
144
|
-
windowsHide: true,
|
|
145
89
|
});
|
|
146
90
|
}
|
|
147
91
|
catch (err) {
|
|
@@ -255,29 +199,15 @@ class DockerExecutor {
|
|
|
255
199
|
}
|
|
256
200
|
}
|
|
257
201
|
function killProcessTree(pid) {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
spawn("taskkill", ["/F", "/T", "/PID", String(pid)], {
|
|
261
|
-
stdio: "ignore",
|
|
262
|
-
detached: true,
|
|
263
|
-
windowsHide: true,
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
catch {
|
|
267
|
-
// Ignore errors
|
|
268
|
-
}
|
|
202
|
+
try {
|
|
203
|
+
process.kill(-pid, "SIGKILL");
|
|
269
204
|
}
|
|
270
|
-
|
|
205
|
+
catch {
|
|
271
206
|
try {
|
|
272
|
-
process.kill(
|
|
207
|
+
process.kill(pid, "SIGKILL");
|
|
273
208
|
}
|
|
274
209
|
catch {
|
|
275
|
-
|
|
276
|
-
process.kill(pid, "SIGKILL");
|
|
277
|
-
}
|
|
278
|
-
catch {
|
|
279
|
-
// Process already dead
|
|
280
|
-
}
|
|
210
|
+
// Process already dead
|
|
281
211
|
}
|
|
282
212
|
}
|
|
283
213
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { basename } from "node:path";
|
|
2
|
-
import { isWindowsPlatform } from "./platform.js";
|
|
3
2
|
const WHITESPACE = /\s+/;
|
|
4
3
|
function stripNullAndNormalize(text) {
|
|
5
4
|
return text.replace(/\0/g, "").normalize("NFKC");
|
|
@@ -549,9 +548,6 @@ export function guardCommand(command, config) {
|
|
|
549
548
|
if (!config.enabled) {
|
|
550
549
|
return { allowed: true };
|
|
551
550
|
}
|
|
552
|
-
if (isWindowsPlatform()) {
|
|
553
|
-
return { allowed: true };
|
|
554
|
-
}
|
|
555
551
|
const match = evaluateCommand(command, config, 0);
|
|
556
552
|
if (match) {
|
|
557
553
|
return {
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { existsSync, lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir, tmpdir } from "node:os";
|
|
3
3
|
import { basename, dirname, isAbsolute, normalize, resolve } from "node:path";
|
|
4
|
-
import { isWindowsPlatform } from "./platform.js";
|
|
5
4
|
const PRIVATE_KEY_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
|
6
5
|
const PRIVATE_KEY_NAME_HINTS = /(id_rsa|id_ed25519|private|secret|credentials)/i;
|
|
7
6
|
const PROC_MEM_PATH = /^\/proc\/\d+\/mem(?:\/|$)/;
|
|
@@ -198,9 +197,6 @@ export function guardPath(rawPath, operation, ctx) {
|
|
|
198
197
|
if (!ctx.config.enabled) {
|
|
199
198
|
return { allowed: true, operation, rawPath };
|
|
200
199
|
}
|
|
201
|
-
if (isWindowsPlatform()) {
|
|
202
|
-
return { allowed: true, operation, rawPath };
|
|
203
|
-
}
|
|
204
200
|
const homeDir = ctx.homeDir ?? homedir();
|
|
205
201
|
const effectiveCtx = {
|
|
206
202
|
...ctx,
|
package/dist/settings.d.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* This module currently provides only PipiclawSettingsManager.
|
|
8
8
|
*/
|
|
9
9
|
import type { Transport } from "@earendil-works/pi-ai";
|
|
10
|
+
import type { ResponseMode } from "./runtime/dingtalk.js";
|
|
10
11
|
import type { ConfigDiagnostic } from "./shared/config-diagnostics.js";
|
|
11
12
|
type PackageSource = string | {
|
|
12
13
|
source: string;
|
|
@@ -112,6 +113,8 @@ export interface PipiclawSettings {
|
|
|
112
113
|
defaultProvider?: string;
|
|
113
114
|
defaultModel?: string;
|
|
114
115
|
defaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
116
|
+
/** Single backup model reference (`provider/model`) used when the primary model's turn fails. */
|
|
117
|
+
fallbackModel?: string | null;
|
|
115
118
|
compaction?: Partial<PipiclawCompactionSettings>;
|
|
116
119
|
retry?: Partial<PipiclawRetrySettings>;
|
|
117
120
|
memoryRecall?: Partial<PipiclawMemoryRecallSettings>;
|
|
@@ -122,6 +125,17 @@ export interface PipiclawSettings {
|
|
|
122
125
|
logging?: Partial<Omit<PipiclawLoggingSettings, "file">> & {
|
|
123
126
|
file?: Partial<PipiclawLoggingSettings["file"]>;
|
|
124
127
|
};
|
|
128
|
+
tui?: Partial<PipiclawTuiSettings>;
|
|
129
|
+
}
|
|
130
|
+
export interface PipiclawTuiSettings {
|
|
131
|
+
/**
|
|
132
|
+
* Output shape for the terminal TUI, reusing the DingTalk response-mode
|
|
133
|
+
* vocabulary: `full_progress_then_plain_final` (default) streams full progress
|
|
134
|
+
* then a plain final answer; `rolling_progress_then_plain_final` keeps only
|
|
135
|
+
* recent progress; `final_card_only` hides progress. Independent of the
|
|
136
|
+
* DingTalk channel's `responseMode` in `channel.json`.
|
|
137
|
+
*/
|
|
138
|
+
responseMode: ResponseMode;
|
|
125
139
|
}
|
|
126
140
|
/**
|
|
127
141
|
* Settings manager for pipiclaw.
|
|
@@ -147,8 +161,14 @@ export declare class PipiclawSettingsManager {
|
|
|
147
161
|
getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
|
|
148
162
|
getSessionSearchSettings(): PipiclawSessionSearchSettings;
|
|
149
163
|
getLoggingSettings(): PipiclawLoggingSettings;
|
|
164
|
+
getTuiSettings(): PipiclawTuiSettings;
|
|
150
165
|
getRetryEnabled(): boolean;
|
|
151
166
|
setRetryEnabled(enabled: boolean): void;
|
|
167
|
+
/**
|
|
168
|
+
* Backup model reference (`provider/model`) for fallback, or null when unset.
|
|
169
|
+
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
170
|
+
*/
|
|
171
|
+
getFallbackModelReference(): string | null;
|
|
152
172
|
getDefaultModel(): string | undefined;
|
|
153
173
|
getDefaultProvider(): string | undefined;
|
|
154
174
|
setDefaultModelAndProvider(provider: string, modelId: string): void;
|
package/dist/settings.js
CHANGED
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
10
10
|
import { dirname, join } from "path";
|
|
11
11
|
import * as log from "./log.js";
|
|
12
|
+
const DEFAULT_TUI = {
|
|
13
|
+
responseMode: "full_progress_then_plain_final",
|
|
14
|
+
};
|
|
12
15
|
const DEFAULT_COMPACTION = {
|
|
13
16
|
enabled: true,
|
|
14
17
|
reserveTokens: 16384,
|
|
@@ -205,6 +208,9 @@ export class PipiclawSettingsManager {
|
|
|
205
208
|
},
|
|
206
209
|
};
|
|
207
210
|
}
|
|
211
|
+
getTuiSettings() {
|
|
212
|
+
return { ...DEFAULT_TUI, ...this.settings.tui };
|
|
213
|
+
}
|
|
208
214
|
getRetryEnabled() {
|
|
209
215
|
return this.settings.retry?.enabled ?? DEFAULT_RETRY.enabled;
|
|
210
216
|
}
|
|
@@ -212,6 +218,18 @@ export class PipiclawSettingsManager {
|
|
|
212
218
|
this.settings.retry = { ...this.settings.retry, enabled };
|
|
213
219
|
this.save();
|
|
214
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* Backup model reference (`provider/model`) for fallback, or null when unset.
|
|
223
|
+
* Empty / whitespace-only values are treated as unset (fallback disabled).
|
|
224
|
+
*/
|
|
225
|
+
getFallbackModelReference() {
|
|
226
|
+
const raw = this.settings.fallbackModel;
|
|
227
|
+
if (typeof raw !== "string") {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
const trimmed = raw.trim();
|
|
231
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
232
|
+
}
|
|
215
233
|
getDefaultModel() {
|
|
216
234
|
return this.settings.defaultModel;
|
|
217
235
|
}
|
|
@@ -3,10 +3,3 @@
|
|
|
3
3
|
* Wraps in single quotes and escapes internal single quotes.
|
|
4
4
|
*/
|
|
5
5
|
export declare function shellEscape(s: string): string;
|
|
6
|
-
/**
|
|
7
|
-
* Normalize filesystem paths for POSIX-style shells.
|
|
8
|
-
* On Windows we convert backslashes to forward slashes so Git Bash/MSYS tools
|
|
9
|
-
* can consume the path consistently.
|
|
10
|
-
*/
|
|
11
|
-
export declare function toShellPath(path: string): string;
|
|
12
|
-
export declare function shellEscapePath(path: string): string;
|
|
@@ -5,14 +5,3 @@
|
|
|
5
5
|
export function shellEscape(s) {
|
|
6
6
|
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
7
7
|
}
|
|
8
|
-
/**
|
|
9
|
-
* Normalize filesystem paths for POSIX-style shells.
|
|
10
|
-
* On Windows we convert backslashes to forward slashes so Git Bash/MSYS tools
|
|
11
|
-
* can consume the path consistently.
|
|
12
|
-
*/
|
|
13
|
-
export function toShellPath(path) {
|
|
14
|
-
return process.platform === "win32" ? path.replace(/\\/g, "/") : path;
|
|
15
|
-
}
|
|
16
|
-
export function shellEscapePath(path) {
|
|
17
|
-
return shellEscape(toShellPath(path));
|
|
18
|
-
}
|
package/dist/tools/bash.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { guardCommand } from "../security/command-guard.js";
|
|
4
4
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
5
5
|
import { logSecurityEvent } from "../security/logger.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
8
8
|
/**
|
|
9
9
|
* Default wall-clock timeout for bash commands when the caller supplies neither a
|
|
@@ -90,7 +90,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
90
90
|
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
91
91
|
const candidatePath = getSpillFilePath();
|
|
92
92
|
try {
|
|
93
|
-
const spillResult = await executor.exec(`cat > ${
|
|
93
|
+
const spillResult = await executor.exec(`cat > ${shellEscape(candidatePath)}`, {
|
|
94
94
|
signal,
|
|
95
95
|
stdin: output,
|
|
96
96
|
});
|
package/dist/tools/edit.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { writeContent } from "./write-content.js";
|
|
8
8
|
/**
|
|
9
9
|
* Generate a unified diff string with line numbers and context
|
|
@@ -126,7 +126,7 @@ export function createEditTool(executor, options = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
128
|
// Read the file
|
|
129
|
-
const readResult = await executor.exec(`cat ${
|
|
129
|
+
const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
130
130
|
if (readResult.code !== 0) {
|
|
131
131
|
throw new Error(readResult.stderr || `File not found: ${path}`);
|
|
132
132
|
}
|
package/dist/tools/read.js
CHANGED
|
@@ -3,7 +3,7 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
4
4
|
import { logSecurityEvent } from "../security/logger.js";
|
|
5
5
|
import { guardPath } from "../security/path-guard.js";
|
|
6
|
-
import {
|
|
6
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
7
7
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "./truncate.js";
|
|
8
8
|
/**
|
|
9
9
|
* Map of file extensions to MIME types for common image formats
|
|
@@ -76,7 +76,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
76
76
|
const mimeType = isImageFile(path);
|
|
77
77
|
if (mimeType) {
|
|
78
78
|
// Read as image (binary) - use base64
|
|
79
|
-
const result = await executor.exec(`base64 < ${
|
|
79
|
+
const result = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
|
|
80
80
|
if (result.code !== 0) {
|
|
81
81
|
throw new Error(result.stderr || `Failed to read file: ${path}`);
|
|
82
82
|
}
|
|
@@ -90,7 +90,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
90
90
|
};
|
|
91
91
|
}
|
|
92
92
|
// Get total line count first
|
|
93
|
-
const countResult = await executor.exec(`awk 'END { print NR }' ${
|
|
93
|
+
const countResult = await executor.exec(`awk 'END { print NR }' ${shellEscape(path)}`, { signal });
|
|
94
94
|
if (countResult.code !== 0) {
|
|
95
95
|
throw new Error(countResult.stderr || `Failed to read file: ${path}`);
|
|
96
96
|
}
|
|
@@ -106,10 +106,10 @@ export function createReadTool(executor, options = {}) {
|
|
|
106
106
|
// Read content with offset
|
|
107
107
|
let cmd;
|
|
108
108
|
if (startLine === 1) {
|
|
109
|
-
cmd = `cat ${
|
|
109
|
+
cmd = `cat ${shellEscape(path)}`;
|
|
110
110
|
}
|
|
111
111
|
else {
|
|
112
|
-
cmd = `tail -n +${startLine} ${
|
|
112
|
+
cmd = `tail -n +${startLine} ${shellEscape(path)}`;
|
|
113
113
|
}
|
|
114
114
|
const result = await executor.exec(cmd, { signal });
|
|
115
115
|
if (result.code !== 0) {
|
|
@@ -131,7 +131,7 @@ export function createReadTool(executor, options = {}) {
|
|
|
131
131
|
if (truncation.firstLineExceedsLimit) {
|
|
132
132
|
// First line at offset exceeds 50KB - tell model to use bash
|
|
133
133
|
const firstLineSize = formatSize(Buffer.byteLength(selectedContent.split("\n")[0], "utf-8"));
|
|
134
|
-
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${
|
|
134
|
+
outputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;
|
|
135
135
|
details = { truncation };
|
|
136
136
|
}
|
|
137
137
|
else if (truncation.truncated) {
|
|
@@ -2,7 +2,7 @@ import { dirname } from "node:path";
|
|
|
2
2
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
3
|
import { logSecurityEvent } from "../security/logger.js";
|
|
4
4
|
import { guardPath } from "../security/path-guard.js";
|
|
5
|
-
import {
|
|
5
|
+
import { shellEscape } from "../shared/shell-escape.js";
|
|
6
6
|
function getDir(path) {
|
|
7
7
|
return dirname(path);
|
|
8
8
|
}
|
|
@@ -42,8 +42,8 @@ export async function writeContent(executor, path, content, signal, options) {
|
|
|
42
42
|
throw new Error(lines.join("\n"));
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
const dirPrefix = createParentDir ? `mkdir -p ${
|
|
46
|
-
const result = await executor.exec(`${dirPrefix}cat > ${
|
|
45
|
+
const dirPrefix = createParentDir ? `mkdir -p ${shellEscape(getDir(path))} && ` : "";
|
|
46
|
+
const result = await executor.exec(`${dirPrefix}cat > ${shellEscape(path)}`, {
|
|
47
47
|
signal,
|
|
48
48
|
stdin: content,
|
|
49
49
|
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
|
|
2
|
+
import type { SandboxConfig } from "../sandbox.js";
|
|
3
|
+
export interface TuiAppOptions {
|
|
4
|
+
sandbox: SandboxConfig;
|
|
5
|
+
channel?: string;
|
|
6
|
+
/** One-shot, non-interactive run: process a single prompt then exit. */
|
|
7
|
+
print?: boolean;
|
|
8
|
+
/** Suppress progress/notice output (plain frontend). */
|
|
9
|
+
quiet?: boolean;
|
|
10
|
+
/** Force the plain frontend even on a TTY. */
|
|
11
|
+
plain?: boolean;
|
|
12
|
+
/** Initial prompt to run before handing control to the input loop. */
|
|
13
|
+
initialPrompt?: string;
|
|
14
|
+
io?: BootstrapIO;
|
|
15
|
+
paths?: BootstrapPaths;
|
|
16
|
+
}
|
|
17
|
+
export declare function resolveChannelId(raw: string | undefined, io?: BootstrapIO): string;
|
|
18
|
+
export declare function runTuiApp(options: TuiAppOptions): Promise<void>;
|
package/dist/tui/app.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal TUI runtime: transport-neutral app init (no DingTalk gate), channel
|
|
3
|
+
* resolution, and wiring of the collaborators the `TurnController` drives.
|
|
4
|
+
*
|
|
5
|
+
* The heavy lifting is reused as-is: `ChannelRunner` drives each turn, the
|
|
6
|
+
* `ChannelContext` is a terminal one (`terminal-context.ts`), and app
|
|
7
|
+
* preparation shares `prepareAppServices` with the DingTalk path.
|
|
8
|
+
*/
|
|
9
|
+
import { userInfo } from "node:os";
|
|
10
|
+
import { renderBuiltInHelp } from "../agent/commands.js";
|
|
11
|
+
import { getOrCreateRunner } from "../agent/index.js";
|
|
12
|
+
import { resetRunner } from "../agent/runner-factory.js";
|
|
13
|
+
import * as log from "../log.js";
|
|
14
|
+
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
15
|
+
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, prepareAppServices, printBootstrapSummary, readCliVersion, } from "../runtime/bootstrap.js";
|
|
16
|
+
import { ensureChannelDir } from "../runtime/channel-paths.js";
|
|
17
|
+
import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
|
|
18
|
+
import { handleEventsCommand } from "../runtime/event-commands.js";
|
|
19
|
+
import { ChannelStore } from "../runtime/store.js";
|
|
20
|
+
import { getUsageLedger } from "../usage/ledger.js";
|
|
21
|
+
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
22
|
+
import { TUI_SLASH_COMMANDS } from "./commands.js";
|
|
23
|
+
import { createFrontend } from "./renderer.js";
|
|
24
|
+
import { TurnController } from "./turn-controller.js";
|
|
25
|
+
const DEFAULT_CHANNEL_ID = "tui_local";
|
|
26
|
+
const CHANNEL_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
27
|
+
export function resolveChannelId(raw, io = console) {
|
|
28
|
+
const channel = raw?.trim() || DEFAULT_CHANNEL_ID;
|
|
29
|
+
if (!CHANNEL_ID_PATTERN.test(channel)) {
|
|
30
|
+
io.error(`Invalid --channel "${channel}": use letters, digits, dot, dash or underscore.`);
|
|
31
|
+
throw new BootstrapExitError(1);
|
|
32
|
+
}
|
|
33
|
+
return channel;
|
|
34
|
+
}
|
|
35
|
+
function safeUserName() {
|
|
36
|
+
try {
|
|
37
|
+
return userInfo().username || "you";
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return "you";
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export async function runTuiApp(options) {
|
|
44
|
+
const io = options.io ?? console;
|
|
45
|
+
const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
|
|
46
|
+
const { sandbox } = options;
|
|
47
|
+
const channelId = resolveChannelId(options.channel, io);
|
|
48
|
+
// The pi-tui frontend owns stdout; the plain frontend prints only the final
|
|
49
|
+
// answer. Either way the human-readable console log sink would corrupt output,
|
|
50
|
+
// so route logging to the file sink only. Turn progress and errors are still
|
|
51
|
+
// surfaced through the transcript.
|
|
52
|
+
log.setConsoleLoggingEnabled(false);
|
|
53
|
+
// Transport-neutral init. Unlike the DingTalk path, the TUI ignores
|
|
54
|
+
// channelTemplateCreated (it needs no channel.json) and shares app services
|
|
55
|
+
// (settings, diagnostics, sandbox check) with bootstrap via prepareAppServices.
|
|
56
|
+
printBootstrapSummary(bootstrapAppHome(paths), io, paths);
|
|
57
|
+
const { settingsManager } = await prepareAppServices(sandbox, paths, io);
|
|
58
|
+
log.configureLogging(settingsManager.getLoggingSettings());
|
|
59
|
+
log.logStartup(paths.workspaceDir, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
|
|
60
|
+
const channelDir = ensureChannelDir(paths.workspaceDir, channelId);
|
|
61
|
+
ensureChannelMemoryFilesSync(channelDir);
|
|
62
|
+
const store = new ChannelStore({ workingDir: paths.workspaceDir });
|
|
63
|
+
const runner = getOrCreateRunner(sandbox, channelId, channelDir, {
|
|
64
|
+
appHomeDir: paths.appHomeDir,
|
|
65
|
+
authConfigPath: paths.authConfigPath,
|
|
66
|
+
modelsConfigPath: paths.modelsConfigPath,
|
|
67
|
+
});
|
|
68
|
+
const tuiSettings = settingsManager.getTuiSettings();
|
|
69
|
+
const traits = {
|
|
70
|
+
progressStyle: progressStyleOf(tuiSettings.responseMode),
|
|
71
|
+
finalDelivery: finalDeliveryOf(tuiSettings.responseMode),
|
|
72
|
+
};
|
|
73
|
+
const interactive = !options.print;
|
|
74
|
+
const frontend = createFrontend({
|
|
75
|
+
plain: options.plain,
|
|
76
|
+
quiet: options.quiet,
|
|
77
|
+
interactive,
|
|
78
|
+
commands: TUI_SLASH_COMMANDS,
|
|
79
|
+
basePath: paths.workspaceDir,
|
|
80
|
+
});
|
|
81
|
+
const controller = new TurnController({
|
|
82
|
+
runner,
|
|
83
|
+
frontend,
|
|
84
|
+
store,
|
|
85
|
+
traits,
|
|
86
|
+
channelId,
|
|
87
|
+
userName: safeUserName(),
|
|
88
|
+
renderHelp: () => renderBuiltInHelp(),
|
|
89
|
+
renderUsage: (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
|
|
90
|
+
runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
|
|
91
|
+
statusInfo: { version: readCliVersion(), sandbox, startedAt: Date.now() },
|
|
92
|
+
});
|
|
93
|
+
try {
|
|
94
|
+
if (options.print) {
|
|
95
|
+
await controller.runOnce(options.initialPrompt);
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
await controller.startInteractive(options.initialPrompt);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
resetRunner(channelId);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pipiclaw tui` CLI: argument parsing and entry. Parsing is a pure function
|
|
3
|
+
* (`parseTuiArgs`) so it can be unit-tested; `runTui` wires it to `runTuiApp`.
|
|
4
|
+
*/
|
|
5
|
+
import { type BootstrapIO } from "../runtime/bootstrap.js";
|
|
6
|
+
import { type SandboxConfig } from "../sandbox.js";
|
|
7
|
+
export type ParsedTui = {
|
|
8
|
+
kind: "run";
|
|
9
|
+
channel?: string;
|
|
10
|
+
sandbox: SandboxConfig;
|
|
11
|
+
print: boolean;
|
|
12
|
+
quiet: boolean;
|
|
13
|
+
plain: boolean;
|
|
14
|
+
positional: string[];
|
|
15
|
+
} | {
|
|
16
|
+
kind: "help";
|
|
17
|
+
} | {
|
|
18
|
+
kind: "version";
|
|
19
|
+
};
|
|
20
|
+
/** Parse `pipiclaw tui` arguments (everything after the `tui` subcommand). */
|
|
21
|
+
export declare function parseTuiArgs(args: string[]): ParsedTui;
|
|
22
|
+
export declare function runTui(argv: string[], io?: BootstrapIO): Promise<void>;
|