@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.
Files changed (54) hide show
  1. package/README.md +1 -0
  2. package/dist/agent/channel-runner.d.ts +21 -4
  3. package/dist/agent/channel-runner.js +134 -18
  4. package/dist/agent/model-fallback.d.ts +64 -0
  5. package/dist/agent/model-fallback.js +125 -0
  6. package/dist/agent/run-queue.d.ts +2 -2
  7. package/dist/agent/runner-factory.d.ts +7 -2
  8. package/dist/agent/runner-factory.js +18 -6
  9. package/dist/agent/session-events.d.ts +2 -2
  10. package/dist/agent/status-render.d.ts +22 -0
  11. package/dist/agent/status-render.js +61 -0
  12. package/dist/agent/types.d.ts +9 -4
  13. package/dist/index.d.ts +2 -1
  14. package/dist/log.d.ts +7 -0
  15. package/dist/log.js +46 -24
  16. package/dist/main.js +15 -2
  17. package/dist/runtime/bootstrap.d.ts +17 -0
  18. package/dist/runtime/bootstrap.js +46 -76
  19. package/dist/runtime/channel-context.d.ts +44 -0
  20. package/dist/runtime/channel-context.js +15 -0
  21. package/dist/runtime/delivery.d.ts +3 -2
  22. package/dist/runtime/dingtalk.d.ts +1 -25
  23. package/dist/sandbox.js +7 -77
  24. package/dist/security/command-guard.js +0 -4
  25. package/dist/security/path-guard.js +0 -4
  26. package/dist/settings.d.ts +20 -0
  27. package/dist/settings.js +18 -0
  28. package/dist/shared/shell-escape.d.ts +0 -7
  29. package/dist/shared/shell-escape.js +0 -11
  30. package/dist/tools/bash.js +2 -2
  31. package/dist/tools/edit.js +2 -2
  32. package/dist/tools/read.js +6 -6
  33. package/dist/tools/write-content.js +3 -3
  34. package/dist/tui/app.d.ts +18 -0
  35. package/dist/tui/app.js +104 -0
  36. package/dist/tui/cli.d.ts +22 -0
  37. package/dist/tui/cli.js +116 -0
  38. package/dist/tui/colors.d.ts +9 -0
  39. package/dist/tui/colors.js +20 -0
  40. package/dist/tui/commands.d.ts +47 -0
  41. package/dist/tui/commands.js +64 -0
  42. package/dist/tui/pitui-frontend.d.ts +47 -0
  43. package/dist/tui/pitui-frontend.js +154 -0
  44. package/dist/tui/plain-frontend.d.ts +23 -0
  45. package/dist/tui/plain-frontend.js +56 -0
  46. package/dist/tui/renderer.d.ts +62 -0
  47. package/dist/tui/renderer.js +13 -0
  48. package/dist/tui/terminal-context.d.ts +27 -0
  49. package/dist/tui/terminal-context.js +84 -0
  50. package/dist/tui/turn-controller.d.ts +68 -0
  51. package/dist/tui/turn-controller.js +266 -0
  52. package/package.json +2 -1
  53. package/dist/security/platform.d.ts +0 -1
  54. package/dist/security/platform.js +0 -3
@@ -0,0 +1,84 @@
1
+ class TerminalDeliveryController {
2
+ constructor(input, renderer, store, traits) {
3
+ this.input = input;
4
+ this.renderer = renderer;
5
+ this.store = store;
6
+ this.traits = traits;
7
+ this.closed = false;
8
+ this.finalDelivered = false;
9
+ }
10
+ buildContext() {
11
+ const { text, user, userName, channel, ts } = this.input;
12
+ return {
13
+ message: { text, rawText: text, user, userName, channel, ts },
14
+ channelName: channel,
15
+ respond: async (progress, shouldLog = true) => this.appendProgress(progress, shouldLog),
16
+ respondPlain: async (final, shouldLog = true) => this.sendFinal(final, shouldLog),
17
+ replaceMessage: async (final) => this.replaceWithFinal(final),
18
+ respondInThread: async (notice) => {
19
+ if (notice.trim()) {
20
+ this.renderer.showNotice(notice);
21
+ }
22
+ },
23
+ setTyping: async () => { },
24
+ setWorking: async (working) => {
25
+ this.renderer.setWorking(working);
26
+ },
27
+ deleteMessage: async () => this.silence(),
28
+ primeCard: () => { },
29
+ flush: async () => { },
30
+ close: async () => {
31
+ this.closed = true;
32
+ },
33
+ progressStyle: this.traits.progressStyle,
34
+ finalDelivery: this.traits.finalDelivery,
35
+ };
36
+ }
37
+ appendProgress(text, shouldLog) {
38
+ if (this.closed || this.finalDelivered || !text.trim())
39
+ return;
40
+ // final_card_only shows no progress; drop stray progress writes.
41
+ if (this.traits.progressStyle === "none")
42
+ return;
43
+ this.renderer.appendProgress(text);
44
+ if (shouldLog) {
45
+ this.archive(text);
46
+ }
47
+ }
48
+ sendFinal(text, shouldLog) {
49
+ if (this.closed || this.finalDelivered)
50
+ return this.finalDelivered;
51
+ if (!text.trim())
52
+ return false;
53
+ this.renderer.showFinal(text);
54
+ if (shouldLog) {
55
+ this.archive(text);
56
+ }
57
+ this.finalDelivered = true;
58
+ return true;
59
+ }
60
+ replaceWithFinal(text) {
61
+ if (this.closed || this.finalDelivered)
62
+ return;
63
+ this.renderer.clearProgress();
64
+ if (text.trim()) {
65
+ this.renderer.showFinal(text);
66
+ }
67
+ this.finalDelivered = true;
68
+ }
69
+ silence() {
70
+ if (this.closed || this.finalDelivered)
71
+ return;
72
+ this.renderer.clearProgress();
73
+ this.finalDelivered = true;
74
+ }
75
+ archive(text) {
76
+ void this.store.logBotResponse(this.input.channel, text, Date.now().toString()).catch(() => {
77
+ // Best-effort: a failed archive must never break rendering. delivery.ts
78
+ // logs a warning here; the TUI keeps quiet to avoid corrupting the view.
79
+ });
80
+ }
81
+ }
82
+ export function createTerminalContext(input, renderer, store, traits) {
83
+ return new TerminalDeliveryController(input, renderer, store, traits).buildContext();
84
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The TUI run-state machine: one channel, one user, turns serialized while still
3
+ * accepting steer / follow-up / stop mid-turn, two-stage Ctrl-C, and graceful
4
+ * shutdown with a memory flush.
5
+ *
6
+ * Collaborators (runner, frontend, store) are injected so the machine can be
7
+ * unit-tested with fakes and a fake clock. `app.ts` builds the real ones.
8
+ */
9
+ import type { AgentRunner } from "../agent/types.js";
10
+ import type { ChannelStore } from "../runtime/store.js";
11
+ import type { SandboxConfig } from "../sandbox.js";
12
+ import type { Frontend } from "./renderer.js";
13
+ import { type DeliveryTraits } from "./terminal-context.js";
14
+ export interface TurnControllerDeps {
15
+ runner: AgentRunner;
16
+ frontend: Frontend;
17
+ store: ChannelStore;
18
+ traits: DeliveryTraits;
19
+ channelId: string;
20
+ userName: string;
21
+ /** Info commands that do not depend on run state. */
22
+ renderHelp: () => string;
23
+ renderUsage: (args: string) => string;
24
+ runEvents: (args: string) => Promise<string>;
25
+ /** Static bits the status renderer needs alongside the live run state. */
26
+ statusInfo: {
27
+ version: string;
28
+ sandbox: SandboxConfig;
29
+ startedAt: number;
30
+ };
31
+ /** Injectable clock for deterministic Ctrl-C timing in tests. */
32
+ now?: () => number;
33
+ }
34
+ export declare class TurnController {
35
+ private readonly deps;
36
+ private readonly now;
37
+ private readonly dispatchDeps;
38
+ private running;
39
+ private currentTaskText;
40
+ private currentTurn;
41
+ private readonly followups;
42
+ private submitChain;
43
+ private exitArmed;
44
+ private exiting;
45
+ private exitResolve;
46
+ private readonly exitPromise;
47
+ constructor(deps: TurnControllerDeps);
48
+ /** Interactive mode: wire input, run an optional first prompt, resolve on exit. */
49
+ startInteractive(initialPrompt?: string): Promise<void>;
50
+ /** One-shot mode: run a single prompt (if any) then shut down. */
51
+ runOnce(prompt?: string): Promise<void>;
52
+ /** Test/observability hook. */
53
+ isRunning(): boolean;
54
+ submit(text: string): void;
55
+ private processSubmit;
56
+ /** A plain message or /steer: steer the in-flight turn, else start a fresh one. */
57
+ private applyText;
58
+ private applyFollowup;
59
+ private beginTurn;
60
+ private drainFollowups;
61
+ private makeTurnInput;
62
+ private archiveIncoming;
63
+ private handleInterrupt;
64
+ private requestExit;
65
+ private buildWelcome;
66
+ private updateStatus;
67
+ private shutdown;
68
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The TUI run-state machine: one channel, one user, turns serialized while still
3
+ * accepting steer / follow-up / stop mid-turn, two-stage Ctrl-C, and graceful
4
+ * shutdown with a memory flush.
5
+ *
6
+ * Collaborators (runner, frontend, store) are injected so the machine can be
7
+ * unit-tested with fakes and a fake clock. `app.ts` builds the real ones.
8
+ */
9
+ import { renderStatus } from "../agent/status-render.js";
10
+ import * as log from "../log.js";
11
+ import { bold, dim } from "./colors.js";
12
+ import { dispatch } from "./commands.js";
13
+ import { createTerminalContext } from "./terminal-context.js";
14
+ const SHUTDOWN_ABORT_WAIT_MS = 5000;
15
+ // Cap the exit-time memory flush so a slow/stuck LLM consolidation can't trap
16
+ // the user in a non-responsive process. Memory may be partially saved on timeout.
17
+ const SHUTDOWN_FLUSH_WAIT_MS = 20_000;
18
+ function errorMessage(err) {
19
+ return err instanceof Error ? err.message : String(err);
20
+ }
21
+ export class TurnController {
22
+ constructor(deps) {
23
+ this.running = false;
24
+ this.currentTurn = Promise.resolve();
25
+ this.followups = [];
26
+ this.submitChain = Promise.resolve();
27
+ this.exitArmed = false;
28
+ this.exiting = false;
29
+ this.exitPromise = new Promise((resolve) => {
30
+ this.exitResolve = resolve;
31
+ });
32
+ this.deps = deps;
33
+ this.now = deps.now ?? Date.now;
34
+ this.dispatchDeps = {
35
+ renderHelp: deps.renderHelp,
36
+ renderUsage: deps.renderUsage,
37
+ runEvents: deps.runEvents,
38
+ renderStatus: () => renderStatus({
39
+ state: { running: this.running, currentTaskText: this.currentTaskText, runner: this.deps.runner },
40
+ version: deps.statusInfo.version,
41
+ uptimeMs: this.now() - deps.statusInfo.startedAt,
42
+ sandbox: deps.statusInfo.sandbox,
43
+ }),
44
+ };
45
+ }
46
+ /** Interactive mode: wire input, run an optional first prompt, resolve on exit. */
47
+ startInteractive(initialPrompt) {
48
+ this.deps.frontend.start({
49
+ onSubmit: (text) => this.submit(text),
50
+ onInterrupt: () => this.handleInterrupt(),
51
+ onEof: () => this.requestExit(),
52
+ });
53
+ this.deps.frontend.showBanner(this.buildWelcome());
54
+ this.updateStatus();
55
+ if (initialPrompt?.trim())
56
+ this.submit(initialPrompt);
57
+ return this.exitPromise;
58
+ }
59
+ /** One-shot mode: run a single prompt (if any) then shut down. */
60
+ async runOnce(prompt) {
61
+ const trimmed = prompt?.trim();
62
+ if (trimmed) {
63
+ this.beginTurn(trimmed);
64
+ await this.currentTurn;
65
+ }
66
+ await this.shutdown();
67
+ }
68
+ /** Test/observability hook. */
69
+ isRunning() {
70
+ return this.running;
71
+ }
72
+ submit(text) {
73
+ this.submitChain = this.submitChain
74
+ .then(() => this.processSubmit(text))
75
+ .catch((err) => {
76
+ log.logWarning(`[${this.deps.channelId}] TUI submit failed`, errorMessage(err));
77
+ });
78
+ }
79
+ async processSubmit(text) {
80
+ if (this.exiting)
81
+ return;
82
+ // Any submitted line disarms a pending "press Ctrl-C again to exit".
83
+ this.exitArmed = false;
84
+ const outcome = await dispatch(text, this.dispatchDeps);
85
+ switch (outcome.kind) {
86
+ case "noop":
87
+ if (outcome.text)
88
+ this.deps.frontend.showNotice(outcome.text);
89
+ return;
90
+ case "reply":
91
+ this.deps.frontend.showFinal(outcome.text);
92
+ return;
93
+ case "exit":
94
+ this.requestExit();
95
+ return;
96
+ case "stop":
97
+ if (this.running) {
98
+ void this.deps.runner.abort();
99
+ this.deps.frontend.showNotice("Stopping…");
100
+ }
101
+ else {
102
+ this.deps.frontend.showNotice("Nothing is running.");
103
+ }
104
+ return;
105
+ case "followup":
106
+ this.applyFollowup(outcome.text);
107
+ return;
108
+ case "steer":
109
+ case "run":
110
+ await this.applyText(outcome.text);
111
+ return;
112
+ }
113
+ }
114
+ /** A plain message or /steer: steer the in-flight turn, else start a fresh one. */
115
+ async applyText(text) {
116
+ if (this.running) {
117
+ try {
118
+ await this.deps.runner.queueSteer(text, this.deps.userName);
119
+ this.deps.frontend.showNotice("Queued as steer.");
120
+ return;
121
+ }
122
+ catch {
123
+ // The busy window closed between dispatch and here; run it fresh.
124
+ }
125
+ }
126
+ this.beginTurn(text);
127
+ }
128
+ applyFollowup(text) {
129
+ if (this.running) {
130
+ this.followups.push(text);
131
+ this.deps.frontend.showNotice("Queued as follow-up.");
132
+ return;
133
+ }
134
+ this.beginTurn(text);
135
+ }
136
+ beginTurn(text) {
137
+ if (this.running || this.exiting)
138
+ return;
139
+ this.running = true;
140
+ this.currentTaskText = text;
141
+ this.deps.frontend.setBusy(true);
142
+ this.updateStatus();
143
+ this.currentTurn = (async () => {
144
+ const input = this.makeTurnInput(text);
145
+ await this.archiveIncoming(input);
146
+ const ctx = createTerminalContext(input, this.deps.frontend, this.deps.store, this.deps.traits);
147
+ try {
148
+ await this.deps.runner.run(ctx, this.deps.store);
149
+ }
150
+ catch (err) {
151
+ this.deps.frontend.showNotice(`Run failed: ${errorMessage(err)}`);
152
+ }
153
+ finally {
154
+ await ctx.close();
155
+ this.running = false;
156
+ this.currentTaskText = undefined;
157
+ this.deps.frontend.setBusy(false);
158
+ this.updateStatus();
159
+ }
160
+ })();
161
+ void this.currentTurn.then(() => this.drainFollowups());
162
+ }
163
+ drainFollowups() {
164
+ if (this.exiting || this.running)
165
+ return;
166
+ const next = this.followups.shift();
167
+ if (next !== undefined)
168
+ this.beginTurn(next);
169
+ }
170
+ makeTurnInput(text) {
171
+ return {
172
+ text,
173
+ user: "tui",
174
+ userName: this.deps.userName,
175
+ channel: this.deps.channelId,
176
+ ts: Date.now().toString(),
177
+ };
178
+ }
179
+ async archiveIncoming(input) {
180
+ try {
181
+ await this.deps.store.logMessage(this.deps.channelId, {
182
+ date: new Date().toISOString(),
183
+ ts: input.ts,
184
+ user: input.user,
185
+ userName: input.userName,
186
+ text: input.text,
187
+ isBot: false,
188
+ });
189
+ }
190
+ catch (err) {
191
+ log.logWarning(`[${this.deps.channelId}] Failed to archive user message`, errorMessage(err));
192
+ }
193
+ }
194
+ handleInterrupt() {
195
+ if (this.running) {
196
+ void this.deps.runner.abort();
197
+ this.deps.frontend.showNotice("Stopping…");
198
+ return;
199
+ }
200
+ // Idle: first Ctrl-C arms the exit prompt, the next one exits (no time
201
+ // window — armed until the user submits something). Mirrors the Node REPL.
202
+ if (this.exitArmed) {
203
+ this.requestExit();
204
+ return;
205
+ }
206
+ this.exitArmed = true;
207
+ this.deps.frontend.showNotice("Press Ctrl-C again to exit.");
208
+ }
209
+ requestExit() {
210
+ void this.shutdown();
211
+ }
212
+ buildWelcome() {
213
+ let model = "";
214
+ try {
215
+ model = this.deps.runner.getStatusSnapshot().model;
216
+ }
217
+ catch {
218
+ // Snapshot may be unavailable before the first turn; omit the model.
219
+ }
220
+ const meta = model ? `${this.deps.channelId} · ${model}` : this.deps.channelId;
221
+ return [
222
+ `${bold("pipiclaw")} ${dim("· terminal chat")}`,
223
+ dim(meta),
224
+ dim("Type a message to start. /help for commands."),
225
+ ].join("\n");
226
+ }
227
+ updateStatus() {
228
+ try {
229
+ const snapshot = this.deps.runner.getStatusSnapshot();
230
+ let line = snapshot.model;
231
+ if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
232
+ line += ` · ctx ${((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(0)}%`;
233
+ }
234
+ line += this.running ? " · running" : " · idle";
235
+ this.deps.frontend.setStatus(`${this.deps.channelId} · ${line}`);
236
+ }
237
+ catch {
238
+ this.deps.frontend.setStatus(`${this.deps.channelId} · ${this.running ? "running" : "ready"}`);
239
+ }
240
+ }
241
+ async shutdown() {
242
+ if (this.exiting)
243
+ return;
244
+ this.exiting = true;
245
+ if (this.running) {
246
+ await this.deps.runner.abort().catch(() => { });
247
+ await Promise.race([
248
+ this.currentTurn,
249
+ new Promise((resolve) => setTimeout(resolve, SHUTDOWN_ABORT_WAIT_MS)),
250
+ ]);
251
+ }
252
+ // Tear the UI down first so the terminal is restored immediately — the
253
+ // memory flush below can take a moment (LLM consolidation), and a frozen
254
+ // full-screen frame feels like a hang. A short note on stderr explains the
255
+ // pause without polluting stdout (which carries the answer in --print).
256
+ this.deps.frontend.stop();
257
+ process.stderr.write("Saving session memory…\n");
258
+ await Promise.race([
259
+ this.deps.runner.flushMemoryForShutdown().catch((err) => {
260
+ log.logWarning(`[${this.deps.channelId}] Failed to flush memory on exit`, errorMessage(err));
261
+ }),
262
+ new Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_WAIT_MS)),
263
+ ]);
264
+ this.exitResolve();
265
+ }
266
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "An AI assistant runtime for coding and team workflows, with DingTalk AI Cards, sub-agents, memory, and scheduled events.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -37,6 +37,7 @@
37
37
  "@earendil-works/pi-agent-core": "0.80.3",
38
38
  "@earendil-works/pi-ai": "0.80.3",
39
39
  "@earendil-works/pi-coding-agent": "0.80.3",
40
+ "@earendil-works/pi-tui": "0.80.3",
40
41
  "@mozilla/readability": "^0.6.0",
41
42
  "axios": "^1.7.0",
42
43
  "croner": "^9.1.0",
@@ -1 +0,0 @@
1
- export declare function isWindowsPlatform(): boolean;
@@ -1,3 +0,0 @@
1
- export function isWindowsPlatform() {
2
- return process.platform === "win32";
3
- }