@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
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export function formatTokenCount(count) {
|
|
2
|
+
if (count < 1000)
|
|
3
|
+
return count.toString();
|
|
4
|
+
if (count < 1_000_000)
|
|
5
|
+
return `${Math.round(count / 1000)}k`;
|
|
6
|
+
return `${(count / 1_000_000).toFixed(1)}M`;
|
|
7
|
+
}
|
|
8
|
+
export function formatUptime(ms) {
|
|
9
|
+
const totalSeconds = Math.floor(ms / 1000);
|
|
10
|
+
const days = Math.floor(totalSeconds / 86400);
|
|
11
|
+
const hours = Math.floor((totalSeconds % 86400) / 3600);
|
|
12
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
13
|
+
const parts = [];
|
|
14
|
+
if (days > 0)
|
|
15
|
+
parts.push(`${days}d`);
|
|
16
|
+
if (hours > 0)
|
|
17
|
+
parts.push(`${hours}h`);
|
|
18
|
+
parts.push(`${minutes}m`);
|
|
19
|
+
return parts.join(" ");
|
|
20
|
+
}
|
|
21
|
+
export function renderStatus(options) {
|
|
22
|
+
const { state, version, uptimeMs, sandbox } = options;
|
|
23
|
+
const lines = ["# Status"];
|
|
24
|
+
if (state?.running) {
|
|
25
|
+
const task = state.currentTaskText?.trim();
|
|
26
|
+
const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
|
|
27
|
+
lines.push(`- Run state: running${preview}`);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
lines.push("- Run state: idle");
|
|
31
|
+
}
|
|
32
|
+
if (state) {
|
|
33
|
+
try {
|
|
34
|
+
const snapshot = state.runner.getStatusSnapshot();
|
|
35
|
+
lines.push(`- Model: ${snapshot.model}`);
|
|
36
|
+
if (snapshot.fallback) {
|
|
37
|
+
const until = new Date(snapshot.fallback.cooldownUntilMs);
|
|
38
|
+
const hh = String(until.getHours()).padStart(2, "0");
|
|
39
|
+
const mm = String(until.getMinutes()).padStart(2, "0");
|
|
40
|
+
lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
|
|
41
|
+
}
|
|
42
|
+
if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
|
|
43
|
+
lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
|
|
44
|
+
}
|
|
45
|
+
if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
|
|
46
|
+
const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
|
|
47
|
+
lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
lines.push("- Model: no session started for this channel yet");
|
|
56
|
+
}
|
|
57
|
+
lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
|
|
58
|
+
lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
|
|
59
|
+
lines.push(`- Version: ${version}`);
|
|
60
|
+
return lines.join("\n");
|
|
61
|
+
}
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { MemoryMaintenanceRuntimeContext } from "../memory/scheduler.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ChannelContext } from "../runtime/channel-context.js";
|
|
3
3
|
import type { ChannelStore } from "../runtime/store.js";
|
|
4
4
|
import type { UsageTotals } from "../shared/types.js";
|
|
5
5
|
import type { BuiltInCommand } from "./commands.js";
|
|
@@ -8,13 +8,18 @@ export interface RunnerStatusSnapshot {
|
|
|
8
8
|
contextTokens?: number;
|
|
9
9
|
contextWindow: number;
|
|
10
10
|
thinkingLevel: string;
|
|
11
|
+
/** Present only while running on the backup model (spec 017). */
|
|
12
|
+
fallback?: {
|
|
13
|
+
primary: string;
|
|
14
|
+
cooldownUntilMs: number;
|
|
15
|
+
};
|
|
11
16
|
}
|
|
12
17
|
export interface AgentRunner {
|
|
13
|
-
run(ctx:
|
|
18
|
+
run(ctx: ChannelContext, store: ChannelStore): Promise<{
|
|
14
19
|
stopReason: string;
|
|
15
20
|
errorMessage?: string;
|
|
16
21
|
}>;
|
|
17
|
-
handleBuiltinCommand(ctx:
|
|
22
|
+
handleBuiltinCommand(ctx: ChannelContext, command: BuiltInCommand): Promise<void>;
|
|
18
23
|
queueSteer(text: string, userName?: string): Promise<void>;
|
|
19
24
|
flushMemoryForShutdown(): Promise<void>;
|
|
20
25
|
getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
|
|
@@ -44,7 +49,7 @@ export interface RunLogContext {
|
|
|
44
49
|
channelName?: string;
|
|
45
50
|
}
|
|
46
51
|
export interface RunState {
|
|
47
|
-
ctx:
|
|
52
|
+
ctx: ChannelContext | null;
|
|
48
53
|
logCtx: RunLogContext | null;
|
|
49
54
|
store: ChannelStore | null;
|
|
50
55
|
queue: RunQueue | null;
|
package/dist/index.d.ts
CHANGED
|
@@ -13,9 +13,10 @@ export { runSidecarTask, type SidecarResult, type SidecarTask, } from "./memory/
|
|
|
13
13
|
export { getApiKeyForModel } from "./models/api-keys.js";
|
|
14
14
|
export { findExactModelReferenceMatch, findModelReferenceMatch, formatModelList, formatModelReference, resolveInitialModel, } from "./models/utils.js";
|
|
15
15
|
export { APP_HOME_DIR, APP_NAME, AUTH_CONFIG_PATH, CHANNEL_CONFIG_PATH, MODELS_CONFIG_PATH, SECURITY_CONFIG_PATH, SETTINGS_CONFIG_PATH, SUB_AGENTS_DIR, SUB_AGENTS_DIR_NAME, TOOLS_CONFIG_PATH, WORKSPACE_DIR, } from "./paths.js";
|
|
16
|
+
export type { ChannelContext, ChannelContext as DingTalkContext, FinalDelivery, ProgressStyle, } from "./runtime/channel-context.js";
|
|
16
17
|
export { ensureChannelDir, getChannelDir, getChannelDirName, } from "./runtime/channel-paths.js";
|
|
17
18
|
export { createDingTalkContext } from "./runtime/delivery.js";
|
|
18
|
-
export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type
|
|
19
|
+
export { type BusyMessageDefaultConfig, type BusyMessageMode, DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler, finalDeliveryOf, isBusyMessageDefaultConfig, isResponseModeConfig, normalizeBusyMessageDefault, normalizeResponseMode, progressStyleOf, type ResponseMode, } from "./runtime/dingtalk.js";
|
|
19
20
|
export { createEventsWatcher, type EventAction, EventsWatcher, type ImmediateEvent, type OneShotEvent, type PeriodicEvent, type ScheduledEvent, } from "./runtime/events.js";
|
|
20
21
|
export { ChannelStore, type LoggedMessage, type LoggedSubAgentRun } from "./runtime/store.js";
|
|
21
22
|
export { createExecutor, type ExecOptions, type ExecResult, type Executor, parseSandboxArg, type SandboxConfig, validateSandbox, } from "./sandbox.js";
|
package/dist/log.d.ts
CHANGED
|
@@ -27,6 +27,12 @@ export interface LoggingConfig {
|
|
|
27
27
|
* have already applied at module load; this reconciles the two.
|
|
28
28
|
*/
|
|
29
29
|
export declare function configureLogging(config: LoggingConfig): void;
|
|
30
|
+
/**
|
|
31
|
+
* Toggle the human-readable console sink. The TUI disables it so structured
|
|
32
|
+
* logging does not corrupt the pi-tui frame (which owns stdout); the file sink
|
|
33
|
+
* is unaffected, so logs are still captured when file logging is enabled.
|
|
34
|
+
*/
|
|
35
|
+
export declare function setConsoleLoggingEnabled(enabled: boolean): void;
|
|
30
36
|
export declare function logUserMessage(ctx: LogContext, text: string): void;
|
|
31
37
|
export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
|
|
32
38
|
export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
|
|
@@ -37,6 +43,7 @@ export declare function logResponse(ctx: LogContext, text: string): void;
|
|
|
37
43
|
export declare function logInfo(message: string): void;
|
|
38
44
|
export declare function logWarning(message: string, details?: string): void;
|
|
39
45
|
export declare function logAgentError(ctx: LogContext | "system", error: string): void;
|
|
46
|
+
export declare function logModelFallback(ctx: LogContext, from: string, to: string, error: string): void;
|
|
40
47
|
export declare function logUsageSummary(ctx: LogContext, usage: {
|
|
41
48
|
input: number;
|
|
42
49
|
output: number;
|
package/dist/log.js
CHANGED
|
@@ -57,6 +57,19 @@ function emit(level, event, message, extra) {
|
|
|
57
57
|
};
|
|
58
58
|
void fileSink.append(record);
|
|
59
59
|
}
|
|
60
|
+
let consoleEnabled = true;
|
|
61
|
+
/**
|
|
62
|
+
* Toggle the human-readable console sink. The TUI disables it so structured
|
|
63
|
+
* logging does not corrupt the pi-tui frame (which owns stdout); the file sink
|
|
64
|
+
* is unaffected, so logs are still captured when file logging is enabled.
|
|
65
|
+
*/
|
|
66
|
+
export function setConsoleLoggingEnabled(enabled) {
|
|
67
|
+
consoleEnabled = enabled;
|
|
68
|
+
}
|
|
69
|
+
function con(...args) {
|
|
70
|
+
if (consoleEnabled)
|
|
71
|
+
console.log(...args);
|
|
72
|
+
}
|
|
60
73
|
function color(style, text) {
|
|
61
74
|
return styleText(style, text);
|
|
62
75
|
}
|
|
@@ -111,19 +124,19 @@ function formatToolArgs(args) {
|
|
|
111
124
|
}
|
|
112
125
|
// User messages
|
|
113
126
|
export function logUserMessage(ctx, text) {
|
|
114
|
-
|
|
127
|
+
con(color("green", `${timestamp()} ${formatContext(ctx)} ${text}`));
|
|
115
128
|
emit("info", "user_message", text, { ctx });
|
|
116
129
|
}
|
|
117
130
|
// Tool execution
|
|
118
131
|
export function logToolStart(ctx, toolName, label, args) {
|
|
119
132
|
const formattedArgs = formatToolArgs(args);
|
|
120
|
-
|
|
133
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));
|
|
121
134
|
if (formattedArgs) {
|
|
122
135
|
const indented = formattedArgs
|
|
123
136
|
.split("\n")
|
|
124
137
|
.map((line) => ` ${line}`)
|
|
125
138
|
.join("\n");
|
|
126
|
-
|
|
139
|
+
con(color("dim", indented));
|
|
127
140
|
}
|
|
128
141
|
emit("debug", "tool_start", `${toolName}: ${label}`, {
|
|
129
142
|
ctx,
|
|
@@ -133,14 +146,14 @@ export function logToolStart(ctx, toolName, label, args) {
|
|
|
133
146
|
}
|
|
134
147
|
export function logToolSuccess(ctx, toolName, durationMs, result) {
|
|
135
148
|
const duration = (durationMs / 1000).toFixed(1);
|
|
136
|
-
|
|
149
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));
|
|
137
150
|
const truncated = truncate(result, 1000);
|
|
138
151
|
if (truncated) {
|
|
139
152
|
const indented = truncated
|
|
140
153
|
.split("\n")
|
|
141
154
|
.map((line) => ` ${line}`)
|
|
142
155
|
.join("\n");
|
|
143
|
-
|
|
156
|
+
con(color("dim", indented));
|
|
144
157
|
}
|
|
145
158
|
emit("info", "tool_end", toolName, {
|
|
146
159
|
ctx,
|
|
@@ -150,13 +163,13 @@ export function logToolSuccess(ctx, toolName, durationMs, result) {
|
|
|
150
163
|
}
|
|
151
164
|
export function logToolError(ctx, toolName, durationMs, error) {
|
|
152
165
|
const duration = (durationMs / 1000).toFixed(1);
|
|
153
|
-
|
|
166
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));
|
|
154
167
|
const truncated = truncate(error, 1000);
|
|
155
168
|
const indented = truncated
|
|
156
169
|
.split("\n")
|
|
157
170
|
.map((line) => ` ${line}`)
|
|
158
171
|
.join("\n");
|
|
159
|
-
|
|
172
|
+
con(color("dim", indented));
|
|
160
173
|
emit("error", "tool_end", toolName, {
|
|
161
174
|
ctx,
|
|
162
175
|
details: truncated,
|
|
@@ -165,58 +178,67 @@ export function logToolError(ctx, toolName, durationMs, error) {
|
|
|
165
178
|
}
|
|
166
179
|
// Response streaming
|
|
167
180
|
export function logResponseStart(ctx) {
|
|
168
|
-
|
|
181
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} → Streaming response...`));
|
|
169
182
|
emit("debug", "response_start", "Streaming response...", { ctx });
|
|
170
183
|
}
|
|
171
184
|
export function logThinking(ctx, thinking) {
|
|
172
|
-
|
|
185
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💭 Thinking`));
|
|
173
186
|
const truncated = truncate(thinking, 1000);
|
|
174
187
|
const indented = truncated
|
|
175
188
|
.split("\n")
|
|
176
189
|
.map((line) => ` ${line}`)
|
|
177
190
|
.join("\n");
|
|
178
|
-
|
|
191
|
+
con(color("dim", indented));
|
|
179
192
|
emit("debug", "thinking", "Thinking", { ctx, details: truncated });
|
|
180
193
|
}
|
|
181
194
|
export function logResponse(ctx, text) {
|
|
182
|
-
|
|
195
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💬 Response`));
|
|
183
196
|
const truncated = truncate(text, 1000);
|
|
184
197
|
const indented = truncated
|
|
185
198
|
.split("\n")
|
|
186
199
|
.map((line) => ` ${line}`)
|
|
187
200
|
.join("\n");
|
|
188
|
-
|
|
201
|
+
con(color("dim", indented));
|
|
189
202
|
emit("info", "response", "Response", { ctx, details: truncated });
|
|
190
203
|
}
|
|
191
204
|
// System
|
|
192
205
|
export function logInfo(message) {
|
|
193
|
-
|
|
206
|
+
con(color("blue", `${timestamp()} [system] ${message}`));
|
|
194
207
|
emit("info", "system", message);
|
|
195
208
|
}
|
|
196
209
|
export function logWarning(message, details) {
|
|
197
|
-
|
|
210
|
+
con(color("yellow", `${timestamp()} [system] ⚠ ${message}`));
|
|
198
211
|
if (details) {
|
|
199
212
|
const indented = details
|
|
200
213
|
.split("\n")
|
|
201
214
|
.map((line) => ` ${line}`)
|
|
202
215
|
.join("\n");
|
|
203
|
-
|
|
216
|
+
con(color("dim", indented));
|
|
204
217
|
}
|
|
205
218
|
emit("warn", "system", message, { details });
|
|
206
219
|
}
|
|
207
220
|
export function logAgentError(ctx, error) {
|
|
208
221
|
const context = ctx === "system" ? "[system]" : formatContext(ctx);
|
|
209
|
-
|
|
222
|
+
con(color("yellow", `${timestamp()} ${context} ✗ Agent error`));
|
|
210
223
|
const indented = error
|
|
211
224
|
.split("\n")
|
|
212
225
|
.map((line) => ` ${line}`)
|
|
213
226
|
.join("\n");
|
|
214
|
-
|
|
227
|
+
con(color("dim", indented));
|
|
215
228
|
emit("error", "agent_error", "Agent error", {
|
|
216
229
|
ctx: ctx === "system" ? undefined : ctx,
|
|
217
230
|
details: error,
|
|
218
231
|
});
|
|
219
232
|
}
|
|
233
|
+
// Model fallback (spec 017)
|
|
234
|
+
export function logModelFallback(ctx, from, to, error) {
|
|
235
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} ⤳ Fallback ${from} → ${to}`));
|
|
236
|
+
emit("warn", "model_fallback", `Fallback ${from} → ${to}`, {
|
|
237
|
+
ctx,
|
|
238
|
+
details: error,
|
|
239
|
+
fields: { from, to, error },
|
|
240
|
+
});
|
|
241
|
+
}
|
|
220
242
|
// Usage summary
|
|
221
243
|
export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
222
244
|
const formatTokens = (count) => {
|
|
@@ -245,8 +267,8 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
|
245
267
|
lines.push(`**Total: $${usage.cost.total.toFixed(4)}** (incl. sub-agents)`);
|
|
246
268
|
const summary = lines.join("\n");
|
|
247
269
|
// Log to console
|
|
248
|
-
|
|
249
|
-
|
|
270
|
+
con(color("yellow", `${timestamp()} ${formatContext(ctx)} 💰 Usage`));
|
|
271
|
+
con(color("dim", ` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +
|
|
250
272
|
(usage.cacheRead > 0 || usage.cacheWrite > 0
|
|
251
273
|
? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`
|
|
252
274
|
: "") +
|
|
@@ -267,11 +289,11 @@ export function logUsageSummary(ctx, usage, contextTokens, contextWindow) {
|
|
|
267
289
|
}
|
|
268
290
|
// Startup
|
|
269
291
|
export function logStartup(workingDir, sandbox) {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
292
|
+
con("Starting pipiclaw...");
|
|
293
|
+
con(` Working directory: ${workingDir}`);
|
|
294
|
+
con(` Sandbox: ${sandbox}`);
|
|
273
295
|
}
|
|
274
296
|
export function logConnected() {
|
|
275
|
-
|
|
276
|
-
|
|
297
|
+
con("⚡️ pipiclaw connected and listening!");
|
|
298
|
+
con("");
|
|
277
299
|
}
|
package/dist/main.js
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { bootstrap, isBootstrapExitError } from "./runtime/bootstrap.js";
|
|
3
|
-
|
|
3
|
+
import { runTui } from "./tui/cli.js";
|
|
4
|
+
function handleError(error) {
|
|
4
5
|
if (isBootstrapExitError(error)) {
|
|
5
6
|
process.exit(error.code);
|
|
6
7
|
}
|
|
7
8
|
console.error(error);
|
|
8
9
|
process.exit(1);
|
|
9
|
-
}
|
|
10
|
+
}
|
|
11
|
+
if (process.argv[2] === "tui") {
|
|
12
|
+
// The TUI resolves when the user exits (Ctrl-C / Ctrl-D / /exit) or a one-shot
|
|
13
|
+
// --print finishes. Exit explicitly: raw-mode stdin and the runner session
|
|
14
|
+
// keep the event loop alive, so the process would otherwise hang after the UI
|
|
15
|
+
// tears down.
|
|
16
|
+
runTui(process.argv).then(() => process.exit(0), handleError);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
// The DingTalk runtime is a long-lived daemon; it does not resolve, so there
|
|
20
|
+
// is no success path to exit on — only surface fatal errors.
|
|
21
|
+
bootstrap(process.argv).catch(handleError);
|
|
22
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Executor, type SandboxConfig } from "../sandbox.js";
|
|
2
|
+
import { PipiclawSettingsManager } from "../settings.js";
|
|
2
3
|
import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
|
|
3
4
|
import { ChannelStore } from "./store.js";
|
|
4
5
|
export interface BootstrapPaths {
|
|
@@ -47,6 +48,7 @@ export declare class BootstrapExitError extends Error {
|
|
|
47
48
|
constructor(code: number, message?: string);
|
|
48
49
|
}
|
|
49
50
|
export declare function isBootstrapExitError(error: unknown): error is BootstrapExitError;
|
|
51
|
+
export declare function readCliVersion(): string;
|
|
50
52
|
export declare function bootstrapAppHome(paths?: BootstrapPaths): BootstrapResult;
|
|
51
53
|
export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
|
|
52
54
|
export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
|
|
@@ -71,5 +73,20 @@ interface RuntimeContextOptions {
|
|
|
71
73
|
export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
|
|
72
74
|
bot: DingTalkBot;
|
|
73
75
|
};
|
|
76
|
+
/**
|
|
77
|
+
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
78
|
+
* TUI: loads settings (surfacing load errors), reports tool/security config
|
|
79
|
+
* diagnostics, and validates the sandbox. Does NOT touch DingTalk config, so the
|
|
80
|
+
* TUI can call it without any DingTalk credentials.
|
|
81
|
+
*
|
|
82
|
+
* Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
|
|
83
|
+
* position (after `loadConfig`, before `logStartup`) so its behavior is
|
|
84
|
+
* unchanged. Logging configuration is intentionally left to each caller
|
|
85
|
+
* (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
|
|
86
|
+
* existing "diagnostics logged with default logging config" ordering.
|
|
87
|
+
*/
|
|
88
|
+
export declare function prepareAppServices(sandbox: SandboxConfig, paths?: BootstrapPaths, io?: BootstrapIO): Promise<{
|
|
89
|
+
settingsManager: PipiclawSettingsManager;
|
|
90
|
+
}>;
|
|
74
91
|
export declare function bootstrap(argv: string[], options?: BootstrapOptions): Promise<AppContext>;
|
|
75
92
|
export {};
|
|
@@ -3,6 +3,7 @@ import { join } from "path";
|
|
|
3
3
|
import { parseBuiltInCommand } from "../agent/commands.js";
|
|
4
4
|
import { getOrCreateRunner } from "../agent/index.js";
|
|
5
5
|
import { resetRunner } from "../agent/runner-factory.js";
|
|
6
|
+
import { renderStatus } from "../agent/status-render.js";
|
|
6
7
|
import * as log from "../log.js";
|
|
7
8
|
import { ensureChannelMemoryFilesSync } from "../memory/files.js";
|
|
8
9
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
@@ -168,7 +169,7 @@ export class BootstrapExitError extends Error {
|
|
|
168
169
|
export function isBootstrapExitError(error) {
|
|
169
170
|
return error instanceof BootstrapExitError;
|
|
170
171
|
}
|
|
171
|
-
function readCliVersion() {
|
|
172
|
+
export function readCliVersion() {
|
|
172
173
|
try {
|
|
173
174
|
const raw = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf-8"));
|
|
174
175
|
return typeof raw.version === "string" && raw.version.trim() ? raw.version : "0.0.0";
|
|
@@ -190,11 +191,10 @@ function writeJsonFileIfMissing(path, value, label, created, mode) {
|
|
|
190
191
|
}
|
|
191
192
|
// App-level config files that may hold secrets (DingTalk client secret, provider
|
|
192
193
|
// API keys, Brave key). They are created owner-only, and any pre-existing file with
|
|
193
|
-
// looser bits is tightened on startup.
|
|
194
|
-
// not apply.
|
|
194
|
+
// looser bits is tightened on startup.
|
|
195
195
|
const SECRET_FILE_MODE = 0o600;
|
|
196
196
|
function hardenExistingSecretFile(path) {
|
|
197
|
-
if (
|
|
197
|
+
if (!existsSync(path)) {
|
|
198
198
|
return;
|
|
199
199
|
}
|
|
200
200
|
try {
|
|
@@ -398,61 +398,6 @@ function flushInactiveChannelMemory(channelStates) {
|
|
|
398
398
|
function isNoRunningTaskQueueError(err) {
|
|
399
399
|
return err instanceof Error && err.message === "No task is currently running.";
|
|
400
400
|
}
|
|
401
|
-
function formatTokenCount(count) {
|
|
402
|
-
if (count < 1000)
|
|
403
|
-
return count.toString();
|
|
404
|
-
if (count < 1_000_000)
|
|
405
|
-
return `${Math.round(count / 1000)}k`;
|
|
406
|
-
return `${(count / 1_000_000).toFixed(1)}M`;
|
|
407
|
-
}
|
|
408
|
-
function formatUptime(ms) {
|
|
409
|
-
const totalSeconds = Math.floor(ms / 1000);
|
|
410
|
-
const days = Math.floor(totalSeconds / 86400);
|
|
411
|
-
const hours = Math.floor((totalSeconds % 86400) / 3600);
|
|
412
|
-
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
413
|
-
const parts = [];
|
|
414
|
-
if (days > 0)
|
|
415
|
-
parts.push(`${days}d`);
|
|
416
|
-
if (hours > 0)
|
|
417
|
-
parts.push(`${hours}h`);
|
|
418
|
-
parts.push(`${minutes}m`);
|
|
419
|
-
return parts.join(" ");
|
|
420
|
-
}
|
|
421
|
-
function renderStatus(options) {
|
|
422
|
-
const { state, version, uptimeMs, sandbox } = options;
|
|
423
|
-
const lines = ["# Status"];
|
|
424
|
-
if (state?.running) {
|
|
425
|
-
const task = state.currentTaskText?.trim();
|
|
426
|
-
const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
|
|
427
|
-
lines.push(`- Run state: running${preview}`);
|
|
428
|
-
}
|
|
429
|
-
else {
|
|
430
|
-
lines.push("- Run state: idle");
|
|
431
|
-
}
|
|
432
|
-
if (state) {
|
|
433
|
-
try {
|
|
434
|
-
const snapshot = state.runner.getStatusSnapshot();
|
|
435
|
-
lines.push(`- Model: ${snapshot.model}`);
|
|
436
|
-
if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
|
|
437
|
-
lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
|
|
438
|
-
}
|
|
439
|
-
if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
|
|
440
|
-
const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
|
|
441
|
-
lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
catch (err) {
|
|
445
|
-
lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
else {
|
|
449
|
-
lines.push("- Model: no session started for this channel yet");
|
|
450
|
-
}
|
|
451
|
-
lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
|
|
452
|
-
lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
|
|
453
|
-
lines.push(`- Version: ${version}`);
|
|
454
|
-
return lines.join("\n");
|
|
455
|
-
}
|
|
456
401
|
export function createRuntimeContext(options) {
|
|
457
402
|
const startServices = options.startServices ?? true;
|
|
458
403
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
@@ -480,7 +425,11 @@ export function createRuntimeContext(options) {
|
|
|
480
425
|
ensureChannelMemoryFilesSync(channelDir);
|
|
481
426
|
state = {
|
|
482
427
|
running: false,
|
|
483
|
-
runner: getOrCreateRunner(options.sandbox, channelId, channelDir
|
|
428
|
+
runner: getOrCreateRunner(options.sandbox, channelId, channelDir, {
|
|
429
|
+
appHomeDir: options.paths.appHomeDir,
|
|
430
|
+
authConfigPath: options.paths.authConfigPath,
|
|
431
|
+
modelsConfigPath: options.paths.modelsConfigPath,
|
|
432
|
+
}),
|
|
484
433
|
stopRequested: false,
|
|
485
434
|
};
|
|
486
435
|
channelStates.set(channelId, state);
|
|
@@ -715,7 +664,12 @@ export function createRuntimeContext(options) {
|
|
|
715
664
|
}
|
|
716
665
|
}
|
|
717
666
|
for (const channelId of channelStates.keys()) {
|
|
718
|
-
|
|
667
|
+
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
668
|
+
resetRunner(channelId, {
|
|
669
|
+
appHomeDir: options.paths.appHomeDir,
|
|
670
|
+
authConfigPath: options.paths.authConfigPath,
|
|
671
|
+
modelsConfigPath: options.paths.modelsConfigPath,
|
|
672
|
+
}, channelDir);
|
|
719
673
|
}
|
|
720
674
|
})();
|
|
721
675
|
return shutdownPromise;
|
|
@@ -744,21 +698,19 @@ export function createRuntimeContext(options) {
|
|
|
744
698
|
shutdown: shutdownWithReason,
|
|
745
699
|
};
|
|
746
700
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
const dingtalkConfig = loadConfig(paths, io);
|
|
761
|
-
dingtalkConfig.stateDir = paths.workspaceDir;
|
|
701
|
+
/**
|
|
702
|
+
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
703
|
+
* TUI: loads settings (surfacing load errors), reports tool/security config
|
|
704
|
+
* diagnostics, and validates the sandbox. Does NOT touch DingTalk config, so the
|
|
705
|
+
* TUI can call it without any DingTalk credentials.
|
|
706
|
+
*
|
|
707
|
+
* Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
|
|
708
|
+
* position (after `loadConfig`, before `logStartup`) so its behavior is
|
|
709
|
+
* unchanged. Logging configuration is intentionally left to each caller
|
|
710
|
+
* (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
|
|
711
|
+
* existing "diagnostics logged with default logging config" ordering.
|
|
712
|
+
*/
|
|
713
|
+
export async function prepareAppServices(sandbox, paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
|
|
762
714
|
const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
|
|
763
715
|
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
764
716
|
log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
|
|
@@ -779,6 +731,24 @@ export async function bootstrap(argv, options = {}) {
|
|
|
779
731
|
}
|
|
780
732
|
throw err;
|
|
781
733
|
}
|
|
734
|
+
return { settingsManager };
|
|
735
|
+
}
|
|
736
|
+
export async function bootstrap(argv, options = {}) {
|
|
737
|
+
const io = options.io ?? console;
|
|
738
|
+
const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
|
|
739
|
+
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
740
|
+
const startServices = options.startServices ?? true;
|
|
741
|
+
const parsedArgs = parseArgs(argv, paths, io);
|
|
742
|
+
const sandbox = parsedArgs.sandbox;
|
|
743
|
+
const bootstrapResult = bootstrapAppHome(paths);
|
|
744
|
+
printBootstrapSummary(bootstrapResult, io, paths);
|
|
745
|
+
if (bootstrapResult.channelTemplateCreated) {
|
|
746
|
+
io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
|
|
747
|
+
throw new BootstrapExitError(1);
|
|
748
|
+
}
|
|
749
|
+
const dingtalkConfig = loadConfig(paths, io);
|
|
750
|
+
dingtalkConfig.stateDir = paths.workspaceDir;
|
|
751
|
+
await prepareAppServices(sandbox, paths, io);
|
|
782
752
|
log.logStartup(paths.workspaceDir, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
|
|
783
753
|
const runtime = createRuntimeContext({
|
|
784
754
|
paths,
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-neutral delivery contract.
|
|
3
|
+
*
|
|
4
|
+
* `ChannelContext` is the surface a `ChannelRunner` turn writes to: progress
|
|
5
|
+
* updates, the final answer, side notices, and lifecycle hooks. The DingTalk
|
|
6
|
+
* transport implements it via AI Card streaming (`runtime/delivery.ts`); the
|
|
7
|
+
* terminal TUI implements it by rendering to the console (`tui/`). The runner
|
|
8
|
+
* and `session-events` depend only on this interface, never on a concrete
|
|
9
|
+
* transport.
|
|
10
|
+
*
|
|
11
|
+
* These declarations previously lived in `runtime/dingtalk.ts` under the name
|
|
12
|
+
* `DingTalkContext`; they were lifted here (and renamed) so a second transport
|
|
13
|
+
* can implement the contract without importing anything DingTalk-specific.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* How progress is surfaced during a run. Derived from the transport's response
|
|
17
|
+
* mode so callers never branch on the raw enum string.
|
|
18
|
+
*/
|
|
19
|
+
export type ProgressStyle = "full" | "rolling" | "none";
|
|
20
|
+
/** How the final answer is delivered. */
|
|
21
|
+
export type FinalDelivery = "plain" | "card";
|
|
22
|
+
export interface ChannelContext {
|
|
23
|
+
message: {
|
|
24
|
+
text: string;
|
|
25
|
+
rawText: string;
|
|
26
|
+
user: string;
|
|
27
|
+
userName?: string;
|
|
28
|
+
channel: string;
|
|
29
|
+
ts: string;
|
|
30
|
+
};
|
|
31
|
+
channelName?: string;
|
|
32
|
+
respond: (text: string, shouldLog?: boolean) => Promise<void>;
|
|
33
|
+
respondPlain: (text: string, shouldLog?: boolean) => Promise<boolean>;
|
|
34
|
+
replaceMessage: (text: string) => Promise<void>;
|
|
35
|
+
respondInThread: (text: string) => Promise<void>;
|
|
36
|
+
setTyping: (isTyping: boolean) => Promise<void>;
|
|
37
|
+
setWorking: (working: boolean) => Promise<void>;
|
|
38
|
+
deleteMessage: () => Promise<void>;
|
|
39
|
+
primeCard: (delayMs: number) => void;
|
|
40
|
+
flush: () => Promise<void>;
|
|
41
|
+
close: () => Promise<void>;
|
|
42
|
+
progressStyle: ProgressStyle;
|
|
43
|
+
finalDelivery: FinalDelivery;
|
|
44
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-neutral delivery contract.
|
|
3
|
+
*
|
|
4
|
+
* `ChannelContext` is the surface a `ChannelRunner` turn writes to: progress
|
|
5
|
+
* updates, the final answer, side notices, and lifecycle hooks. The DingTalk
|
|
6
|
+
* transport implements it via AI Card streaming (`runtime/delivery.ts`); the
|
|
7
|
+
* terminal TUI implements it by rendering to the console (`tui/`). The runner
|
|
8
|
+
* and `session-events` depend only on this interface, never on a concrete
|
|
9
|
+
* transport.
|
|
10
|
+
*
|
|
11
|
+
* These declarations previously lived in `runtime/dingtalk.ts` under the name
|
|
12
|
+
* `DingTalkContext`; they were lifted here (and renamed) so a second transport
|
|
13
|
+
* can implement the contract without importing anything DingTalk-specific.
|
|
14
|
+
*/
|
|
15
|
+
export {};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ChannelContext } from "./channel-context.js";
|
|
2
|
+
import type { DingTalkBot, DingTalkEvent } from "./dingtalk.js";
|
|
2
3
|
import type { ChannelStore } from "./store.js";
|
|
3
|
-
export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore):
|
|
4
|
+
export declare function createDingTalkContext(event: DingTalkEvent, bot: DingTalkBot, store: ChannelStore): ChannelContext;
|