@oyasmi/pipiclaw 0.7.1 → 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 +8 -4
- package/dist/agent/channel-runner.js +14 -12
- 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 +4 -4
- package/dist/index.d.ts +2 -1
- package/dist/log.d.ts +6 -0
- package/dist/log.js +38 -25
- package/dist/main.js +15 -2
- package/dist/runtime/bootstrap.d.ts +17 -0
- package/dist/runtime/bootstrap.js +44 -79
- 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/settings.d.ts +13 -0
- package/dist/settings.js +6 -0
- 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
|
@@ -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";
|
|
@@ -397,67 +398,6 @@ function flushInactiveChannelMemory(channelStates) {
|
|
|
397
398
|
function isNoRunningTaskQueueError(err) {
|
|
398
399
|
return err instanceof Error && err.message === "No task is currently running.";
|
|
399
400
|
}
|
|
400
|
-
function formatTokenCount(count) {
|
|
401
|
-
if (count < 1000)
|
|
402
|
-
return count.toString();
|
|
403
|
-
if (count < 1_000_000)
|
|
404
|
-
return `${Math.round(count / 1000)}k`;
|
|
405
|
-
return `${(count / 1_000_000).toFixed(1)}M`;
|
|
406
|
-
}
|
|
407
|
-
function formatUptime(ms) {
|
|
408
|
-
const totalSeconds = Math.floor(ms / 1000);
|
|
409
|
-
const days = Math.floor(totalSeconds / 86400);
|
|
410
|
-
const hours = Math.floor((totalSeconds % 86400) / 3600);
|
|
411
|
-
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
412
|
-
const parts = [];
|
|
413
|
-
if (days > 0)
|
|
414
|
-
parts.push(`${days}d`);
|
|
415
|
-
if (hours > 0)
|
|
416
|
-
parts.push(`${hours}h`);
|
|
417
|
-
parts.push(`${minutes}m`);
|
|
418
|
-
return parts.join(" ");
|
|
419
|
-
}
|
|
420
|
-
function renderStatus(options) {
|
|
421
|
-
const { state, version, uptimeMs, sandbox } = options;
|
|
422
|
-
const lines = ["# Status"];
|
|
423
|
-
if (state?.running) {
|
|
424
|
-
const task = state.currentTaskText?.trim();
|
|
425
|
-
const preview = task ? `: ${task.length > 80 ? `${task.slice(0, 79)}…` : task}` : "";
|
|
426
|
-
lines.push(`- Run state: running${preview}`);
|
|
427
|
-
}
|
|
428
|
-
else {
|
|
429
|
-
lines.push("- Run state: idle");
|
|
430
|
-
}
|
|
431
|
-
if (state) {
|
|
432
|
-
try {
|
|
433
|
-
const snapshot = state.runner.getStatusSnapshot();
|
|
434
|
-
lines.push(`- Model: ${snapshot.model}`);
|
|
435
|
-
if (snapshot.fallback) {
|
|
436
|
-
const until = new Date(snapshot.fallback.cooldownUntilMs);
|
|
437
|
-
const hh = String(until.getHours()).padStart(2, "0");
|
|
438
|
-
const mm = String(until.getMinutes()).padStart(2, "0");
|
|
439
|
-
lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
|
|
440
|
-
}
|
|
441
|
-
if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
|
|
442
|
-
lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
|
|
443
|
-
}
|
|
444
|
-
if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
|
|
445
|
-
const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
|
|
446
|
-
lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
catch (err) {
|
|
450
|
-
lines.push(`- Model: unavailable (${err instanceof Error ? err.message : String(err)})`);
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
else {
|
|
454
|
-
lines.push("- Model: no session started for this channel yet");
|
|
455
|
-
}
|
|
456
|
-
lines.push(`- Sandbox: ${sandbox.type === "host" ? "host" : `docker:${sandbox.container}`}`);
|
|
457
|
-
lines.push(`- Uptime: ${formatUptime(uptimeMs)}`);
|
|
458
|
-
lines.push(`- Version: ${version}`);
|
|
459
|
-
return lines.join("\n");
|
|
460
|
-
}
|
|
461
401
|
export function createRuntimeContext(options) {
|
|
462
402
|
const startServices = options.startServices ?? true;
|
|
463
403
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
@@ -485,7 +425,11 @@ export function createRuntimeContext(options) {
|
|
|
485
425
|
ensureChannelMemoryFilesSync(channelDir);
|
|
486
426
|
state = {
|
|
487
427
|
running: false,
|
|
488
|
-
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
|
+
}),
|
|
489
433
|
stopRequested: false,
|
|
490
434
|
};
|
|
491
435
|
channelStates.set(channelId, state);
|
|
@@ -720,7 +664,12 @@ export function createRuntimeContext(options) {
|
|
|
720
664
|
}
|
|
721
665
|
}
|
|
722
666
|
for (const channelId of channelStates.keys()) {
|
|
723
|
-
|
|
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);
|
|
724
673
|
}
|
|
725
674
|
})();
|
|
726
675
|
return shutdownPromise;
|
|
@@ -749,21 +698,19 @@ export function createRuntimeContext(options) {
|
|
|
749
698
|
shutdown: shutdownWithReason,
|
|
750
699
|
};
|
|
751
700
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
const dingtalkConfig = loadConfig(paths, io);
|
|
766
|
-
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) {
|
|
767
714
|
const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
|
|
768
715
|
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
769
716
|
log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
|
|
@@ -784,6 +731,24 @@ export async function bootstrap(argv, options = {}) {
|
|
|
784
731
|
}
|
|
785
732
|
throw err;
|
|
786
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);
|
|
787
752
|
log.logStartup(paths.workspaceDir, sandbox.type === "host" ? "host" : `docker:${sandbox.container}`);
|
|
788
753
|
const runtime = createRuntimeContext({
|
|
789
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;
|
|
@@ -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/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;
|
|
@@ -124,6 +125,17 @@ export interface PipiclawSettings {
|
|
|
124
125
|
logging?: Partial<Omit<PipiclawLoggingSettings, "file">> & {
|
|
125
126
|
file?: Partial<PipiclawLoggingSettings["file"]>;
|
|
126
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;
|
|
127
139
|
}
|
|
128
140
|
/**
|
|
129
141
|
* Settings manager for pipiclaw.
|
|
@@ -149,6 +161,7 @@ export declare class PipiclawSettingsManager {
|
|
|
149
161
|
getMemoryMaintenanceSettings(): PipiclawMemoryMaintenanceSettings;
|
|
150
162
|
getSessionSearchSettings(): PipiclawSessionSearchSettings;
|
|
151
163
|
getLoggingSettings(): PipiclawLoggingSettings;
|
|
164
|
+
getTuiSettings(): PipiclawTuiSettings;
|
|
152
165
|
getRetryEnabled(): boolean;
|
|
153
166
|
setRetryEnabled(enabled: boolean): void;
|
|
154
167
|
/**
|
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
|
}
|
|
@@ -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>;
|
package/dist/tui/cli.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
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 { BootstrapExitError, readCliVersion } from "../runtime/bootstrap.js";
|
|
6
|
+
import { parseSandboxArg, SandboxConfigError } from "../sandbox.js";
|
|
7
|
+
import { runTuiApp } from "./app.js";
|
|
8
|
+
/** Parse `pipiclaw tui` arguments (everything after the `tui` subcommand). */
|
|
9
|
+
export function parseTuiArgs(args) {
|
|
10
|
+
let channel;
|
|
11
|
+
let sandbox = { type: "host" };
|
|
12
|
+
let print = false;
|
|
13
|
+
let quiet = false;
|
|
14
|
+
let plain = false;
|
|
15
|
+
const positional = [];
|
|
16
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
17
|
+
const arg = args[index];
|
|
18
|
+
if (arg === "--channel") {
|
|
19
|
+
channel = args[index + 1];
|
|
20
|
+
index += 1;
|
|
21
|
+
}
|
|
22
|
+
else if (arg.startsWith("--channel=")) {
|
|
23
|
+
channel = arg.slice("--channel=".length);
|
|
24
|
+
}
|
|
25
|
+
else if (arg === "--sandbox") {
|
|
26
|
+
sandbox = parseSandboxArg(args[index + 1] ?? "");
|
|
27
|
+
index += 1;
|
|
28
|
+
}
|
|
29
|
+
else if (arg.startsWith("--sandbox=")) {
|
|
30
|
+
sandbox = parseSandboxArg(arg.slice("--sandbox=".length));
|
|
31
|
+
}
|
|
32
|
+
else if (arg === "--print" || arg === "-p") {
|
|
33
|
+
print = true;
|
|
34
|
+
}
|
|
35
|
+
else if (arg === "--quiet" || arg === "-q") {
|
|
36
|
+
quiet = true;
|
|
37
|
+
}
|
|
38
|
+
else if (arg === "--plain") {
|
|
39
|
+
plain = true;
|
|
40
|
+
}
|
|
41
|
+
else if (arg === "--help" || arg === "-h") {
|
|
42
|
+
return { kind: "help" };
|
|
43
|
+
}
|
|
44
|
+
else if (arg === "--version") {
|
|
45
|
+
return { kind: "version" };
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
positional.push(arg);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { kind: "run", channel, sandbox, print, quiet, plain, positional };
|
|
52
|
+
}
|
|
53
|
+
function printTuiHelp(io) {
|
|
54
|
+
io.log("Usage: pipiclaw tui [options] [prompt]");
|
|
55
|
+
io.log("");
|
|
56
|
+
io.log("Chat with the pipiclaw agent in the terminal, reusing the same config,");
|
|
57
|
+
io.log("memory and session as the DingTalk runtime.");
|
|
58
|
+
io.log("");
|
|
59
|
+
io.log("Resume: there is no /resume command — a channel resumes itself.");
|
|
60
|
+
io.log("Re-running with the same --channel restores the previous conversation");
|
|
61
|
+
io.log("automatically (context is persisted per channel); memory carries longer-");
|
|
62
|
+
io.log("term facts across sessions. Use --channel to continue any past conversation.");
|
|
63
|
+
io.log("");
|
|
64
|
+
io.log("Options:");
|
|
65
|
+
io.log(" --channel <id> Channel to attach to (default: tui_local).");
|
|
66
|
+
io.log(" Use dm_<staffId> to share a DingTalk conversation's memory.");
|
|
67
|
+
io.log(" --sandbox=host Run tools on host (default)");
|
|
68
|
+
io.log(" --sandbox=docker:<name> Run tools in a Docker container");
|
|
69
|
+
io.log(" --print, -p One-shot: run [prompt] (or stdin), print the answer, exit");
|
|
70
|
+
io.log(" --quiet, -q Plain mode: print only the final answer");
|
|
71
|
+
io.log(" --plain Force the plain frontend (no full-screen UI)");
|
|
72
|
+
io.log(" --version Print the version and exit");
|
|
73
|
+
io.log("");
|
|
74
|
+
io.log("Note: do not attach --channel to a DingTalk conversation the daemon is actively serving.");
|
|
75
|
+
}
|
|
76
|
+
async function readStdin() {
|
|
77
|
+
const chunks = [];
|
|
78
|
+
for await (const chunk of process.stdin) {
|
|
79
|
+
chunks.push(chunk);
|
|
80
|
+
}
|
|
81
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
82
|
+
}
|
|
83
|
+
export async function runTui(argv, io = console) {
|
|
84
|
+
let parsed;
|
|
85
|
+
try {
|
|
86
|
+
parsed = parseTuiArgs(argv.slice(3));
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
if (err instanceof SandboxConfigError) {
|
|
90
|
+
io.error(`Error: ${err.message}`);
|
|
91
|
+
throw new BootstrapExitError(1);
|
|
92
|
+
}
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
if (parsed.kind === "help") {
|
|
96
|
+
printTuiHelp(io);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (parsed.kind === "version") {
|
|
100
|
+
io.log(readCliVersion());
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
let initialPrompt = parsed.positional.join(" ").trim() || undefined;
|
|
104
|
+
if (parsed.print && !initialPrompt && process.stdin.isTTY !== true) {
|
|
105
|
+
initialPrompt = (await readStdin()).trim() || undefined;
|
|
106
|
+
}
|
|
107
|
+
await runTuiApp({
|
|
108
|
+
sandbox: parsed.sandbox,
|
|
109
|
+
channel: parsed.channel,
|
|
110
|
+
print: parsed.print,
|
|
111
|
+
quiet: parsed.quiet,
|
|
112
|
+
plain: parsed.plain,
|
|
113
|
+
initialPrompt,
|
|
114
|
+
io,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const bold: (text: string) => string;
|
|
2
|
+
export declare const dim: (text: string) => string;
|
|
3
|
+
export declare const italic: (text: string) => string;
|
|
4
|
+
export declare const underline: (text: string) => string;
|
|
5
|
+
export declare const strikethrough: (text: string) => string;
|
|
6
|
+
export declare const red: (text: string) => string;
|
|
7
|
+
export declare const yellow: (text: string) => string;
|
|
8
|
+
export declare const cyan: (text: string) => string;
|
|
9
|
+
export declare const gray: (text: string) => string;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal ANSI color helpers for the TUI. pipiclaw has no chalk dependency, so
|
|
3
|
+
* these are hand-rolled SGR wrappers. Honors NO_COLOR (https://no-color.org) and
|
|
4
|
+
* a non-TTY stdout by degrading to identity functions.
|
|
5
|
+
*/
|
|
6
|
+
const enabled = !process.env.NO_COLOR && process.stdout.isTTY === true;
|
|
7
|
+
function sgr(open, close = 0) {
|
|
8
|
+
if (!enabled)
|
|
9
|
+
return (text) => text;
|
|
10
|
+
return (text) => `\x1b[${open}m${text}\x1b[${close}m`;
|
|
11
|
+
}
|
|
12
|
+
export const bold = sgr(1, 22);
|
|
13
|
+
export const dim = sgr(2, 22);
|
|
14
|
+
export const italic = sgr(3, 23);
|
|
15
|
+
export const underline = sgr(4, 24);
|
|
16
|
+
export const strikethrough = sgr(9, 29);
|
|
17
|
+
export const red = sgr(31);
|
|
18
|
+
export const yellow = sgr(33);
|
|
19
|
+
export const cyan = sgr(36);
|
|
20
|
+
export const gray = sgr(90);
|