@oyasmi/pipiclaw 0.7.1 → 0.7.3

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 (63) hide show
  1. package/README.md +8 -19
  2. package/dist/agent/channel-runner.d.ts +8 -4
  3. package/dist/agent/channel-runner.js +14 -12
  4. package/dist/agent/model-fallback.js +11 -5
  5. package/dist/agent/run-queue.d.ts +2 -2
  6. package/dist/agent/runner-factory.d.ts +7 -2
  7. package/dist/agent/runner-factory.js +18 -6
  8. package/dist/agent/session-events.d.ts +2 -2
  9. package/dist/agent/status-render.d.ts +22 -0
  10. package/dist/agent/status-render.js +61 -0
  11. package/dist/agent/type-guards.js +3 -4
  12. package/dist/agent/types.d.ts +7 -10
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +1 -1
  15. package/dist/log.d.ts +6 -0
  16. package/dist/log.js +38 -25
  17. package/dist/main.js +15 -2
  18. package/dist/memory/candidates.js +5 -17
  19. package/dist/memory/consolidation.js +1 -6
  20. package/dist/memory/files.d.ts +1 -0
  21. package/dist/memory/files.js +0 -0
  22. package/dist/memory/maintenance-jobs.js +1 -0
  23. package/dist/memory/session-corpus.js +3 -16
  24. package/dist/runtime/bootstrap.d.ts +17 -0
  25. package/dist/runtime/bootstrap.js +44 -79
  26. package/dist/runtime/channel-context.d.ts +44 -0
  27. package/dist/runtime/channel-context.js +15 -0
  28. package/dist/runtime/delivery.d.ts +3 -2
  29. package/dist/runtime/dingtalk.d.ts +1 -25
  30. package/dist/runtime/dingtalk.js +1 -1
  31. package/dist/runtime/event-commands.js +1 -3
  32. package/dist/runtime/events.js +1 -3
  33. package/dist/runtime/store.d.ts +1 -7
  34. package/dist/runtime/store.js +6 -80
  35. package/dist/settings.d.ts +13 -0
  36. package/dist/settings.js +6 -0
  37. package/dist/shared/fs-utils.d.ts +8 -0
  38. package/dist/shared/fs-utils.js +21 -0
  39. package/dist/shared/text-utils.d.ts +2 -0
  40. package/dist/shared/text-utils.js +4 -0
  41. package/dist/tools/index.d.ts +1 -7
  42. package/dist/tools/index.js +0 -20
  43. package/dist/tools/memory-save.d.ts +0 -1
  44. package/dist/tools/memory-save.js +0 -1
  45. package/dist/tui/app.d.ts +18 -0
  46. package/dist/tui/app.js +104 -0
  47. package/dist/tui/cli.d.ts +22 -0
  48. package/dist/tui/cli.js +116 -0
  49. package/dist/tui/colors.d.ts +9 -0
  50. package/dist/tui/colors.js +20 -0
  51. package/dist/tui/commands.d.ts +47 -0
  52. package/dist/tui/commands.js +64 -0
  53. package/dist/tui/pitui-frontend.d.ts +47 -0
  54. package/dist/tui/pitui-frontend.js +154 -0
  55. package/dist/tui/plain-frontend.d.ts +23 -0
  56. package/dist/tui/plain-frontend.js +56 -0
  57. package/dist/tui/renderer.d.ts +62 -0
  58. package/dist/tui/renderer.js +16 -0
  59. package/dist/tui/terminal-context.d.ts +27 -0
  60. package/dist/tui/terminal-context.js +84 -0
  61. package/dist/tui/turn-controller.d.ts +68 -0
  62. package/dist/tui/turn-controller.js +286 -0
  63. package/package.json +2 -1
@@ -0,0 +1,286 @@
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
+ // The turn is over whether it settled or its finally threw (e.g. a frontend
162
+ // method failing); drain either way and never leak an unhandled rejection.
163
+ void this.currentTurn.then(() => this.drainFollowups(), (err) => {
164
+ log.logWarning(`[${this.deps.channelId}] TUI turn finalizer failed`, errorMessage(err));
165
+ this.running = false;
166
+ this.drainFollowups();
167
+ });
168
+ }
169
+ drainFollowups() {
170
+ if (this.exiting || this.running)
171
+ return;
172
+ const next = this.followups.shift();
173
+ if (next !== undefined)
174
+ this.beginTurn(next);
175
+ }
176
+ makeTurnInput(text) {
177
+ return {
178
+ text,
179
+ user: "tui",
180
+ userName: this.deps.userName,
181
+ channel: this.deps.channelId,
182
+ ts: Date.now().toString(),
183
+ };
184
+ }
185
+ async archiveIncoming(input) {
186
+ try {
187
+ await this.deps.store.logMessage(this.deps.channelId, {
188
+ date: new Date().toISOString(),
189
+ ts: input.ts,
190
+ user: input.user,
191
+ userName: input.userName,
192
+ text: input.text,
193
+ isBot: false,
194
+ });
195
+ }
196
+ catch (err) {
197
+ log.logWarning(`[${this.deps.channelId}] Failed to archive user message`, errorMessage(err));
198
+ }
199
+ }
200
+ handleInterrupt() {
201
+ if (this.running) {
202
+ void this.deps.runner.abort();
203
+ this.deps.frontend.showNotice("Stopping…");
204
+ return;
205
+ }
206
+ // Idle: first Ctrl-C arms the exit prompt, the next one exits (no time
207
+ // window — armed until the user submits something). Mirrors the Node REPL.
208
+ if (this.exitArmed) {
209
+ this.requestExit();
210
+ return;
211
+ }
212
+ this.exitArmed = true;
213
+ this.deps.frontend.showNotice("Press Ctrl-C again to exit.");
214
+ }
215
+ requestExit() {
216
+ // shutdown() restores the terminal in a finally, so a rejection here means only
217
+ // the memory-flush bookkeeping failed — log it rather than leak an unhandled
218
+ // rejection that could abort the process before exitResolve runs.
219
+ this.shutdown().catch((err) => {
220
+ log.logWarning(`[${this.deps.channelId}] TUI shutdown failed`, errorMessage(err));
221
+ this.exitResolve();
222
+ });
223
+ }
224
+ buildWelcome() {
225
+ let model = "";
226
+ try {
227
+ model = this.deps.runner.getStatusSnapshot().model;
228
+ }
229
+ catch {
230
+ // Snapshot may be unavailable before the first turn; omit the model.
231
+ }
232
+ const meta = model ? `${this.deps.channelId} · ${model}` : this.deps.channelId;
233
+ return [
234
+ `${bold("pipiclaw")} ${dim("· terminal chat")}`,
235
+ dim(meta),
236
+ dim("Type a message to start. /help for commands."),
237
+ ].join("\n");
238
+ }
239
+ updateStatus() {
240
+ try {
241
+ const snapshot = this.deps.runner.getStatusSnapshot();
242
+ let line = snapshot.model;
243
+ if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
244
+ line += ` · ctx ${((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(0)}%`;
245
+ }
246
+ line += this.running ? " · running" : " · idle";
247
+ this.deps.frontend.setStatus(`${this.deps.channelId} · ${line}`);
248
+ }
249
+ catch {
250
+ this.deps.frontend.setStatus(`${this.deps.channelId} · ${this.running ? "running" : "ready"}`);
251
+ }
252
+ }
253
+ async shutdown() {
254
+ if (this.exiting)
255
+ return;
256
+ this.exiting = true;
257
+ if (this.running) {
258
+ await this.deps.runner.abort().catch(() => { });
259
+ // Never let a rejected turn (e.g. ctx.close() throwing in the turn's finally)
260
+ // escape the race — that would skip frontend.stop() and strand the terminal in
261
+ // raw mode. The turn already logs its own failures.
262
+ await Promise.race([
263
+ this.currentTurn.catch(() => { }),
264
+ new Promise((resolve) => setTimeout(resolve, SHUTDOWN_ABORT_WAIT_MS)),
265
+ ]);
266
+ }
267
+ try {
268
+ // Tear the UI down first so the terminal is restored immediately — the
269
+ // memory flush below can take a moment (LLM consolidation), and a frozen
270
+ // full-screen frame feels like a hang. A short note on stderr explains the
271
+ // pause without polluting stdout (which carries the answer in --print).
272
+ // Guaranteed via finally: a flush failure must not leave the terminal raw.
273
+ this.deps.frontend.stop();
274
+ process.stderr.write("Saving session memory…\n");
275
+ await Promise.race([
276
+ this.deps.runner.flushMemoryForShutdown().catch((err) => {
277
+ log.logWarning(`[${this.deps.channelId}] Failed to flush memory on exit`, errorMessage(err));
278
+ }),
279
+ new Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_WAIT_MS)),
280
+ ]);
281
+ }
282
+ finally {
283
+ this.exitResolve();
284
+ }
285
+ }
286
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oyasmi/pipiclaw",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
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",