wave-code 1.0.6 → 1.0.8

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/dist/components/AgentsManager.d.ts +7 -0
  2. package/dist/components/AgentsManager.js +109 -0
  3. package/dist/components/ChatInterface.js +1 -1
  4. package/dist/components/ConfirmationDetails.d.ts +1 -0
  5. package/dist/components/ConfirmationDetails.js +5 -3
  6. package/dist/components/ConfirmationSelector.js +17 -3
  7. package/dist/components/InputBox.js +7 -21
  8. package/dist/components/LoginCommand.js +31 -2
  9. package/dist/components/MarketplaceAddForm.js +16 -2
  10. package/dist/components/RewindCommand.js +11 -4
  11. package/dist/constants/commands.js +6 -0
  12. package/dist/contexts/useChat.d.ts +18 -2
  13. package/dist/contexts/useChat.js +114 -9
  14. package/dist/daemon/commands.d.ts +49 -0
  15. package/dist/daemon/commands.js +341 -0
  16. package/dist/daemon/jsonRpcClient.d.ts +38 -0
  17. package/dist/daemon/jsonRpcClient.js +129 -0
  18. package/dist/daemon/socketClient.d.ts +13 -0
  19. package/dist/daemon/socketClient.js +26 -0
  20. package/dist/hooks/useInputManager.d.ts +2 -0
  21. package/dist/hooks/useInputManager.js +8 -0
  22. package/dist/index.js +88 -0
  23. package/dist/managers/inputHandlers.js +3 -0
  24. package/dist/managers/inputReducer.d.ts +4 -0
  25. package/dist/managers/inputReducer.js +8 -0
  26. package/dist/reducers/agentsManagerReducer.d.ts +26 -0
  27. package/dist/reducers/agentsManagerReducer.js +54 -0
  28. package/dist/stdio/agentBridge.d.ts +15 -0
  29. package/dist/stdio/agentBridge.js +101 -20
  30. package/dist/stdio/protocol.d.ts +1 -1
  31. package/dist/utils/usageSummary.d.ts +0 -4
  32. package/dist/utils/usageSummary.js +1 -34
  33. package/package.json +2 -2
  34. package/src/components/AgentsManager.tsx +290 -0
  35. package/src/components/ChatInterface.tsx +2 -0
  36. package/src/components/ConfirmationDetails.tsx +6 -0
  37. package/src/components/ConfirmationSelector.tsx +18 -3
  38. package/src/components/InputBox.tsx +54 -45
  39. package/src/components/LoginCommand.tsx +35 -2
  40. package/src/components/MarketplaceAddForm.tsx +17 -2
  41. package/src/components/RewindCommand.tsx +10 -4
  42. package/src/constants/commands.ts +6 -0
  43. package/src/contexts/useChat.tsx +146 -7
  44. package/src/daemon/commands.ts +444 -0
  45. package/src/daemon/jsonRpcClient.ts +158 -0
  46. package/src/daemon/socketClient.ts +34 -0
  47. package/src/hooks/useInputManager.ts +8 -0
  48. package/src/index.ts +130 -0
  49. package/src/managers/inputHandlers.ts +2 -0
  50. package/src/managers/inputReducer.ts +10 -0
  51. package/src/reducers/agentsManagerReducer.ts +91 -0
  52. package/src/stdio/agentBridge.ts +123 -19
  53. package/src/stdio/protocol.ts +4 -0
  54. package/src/utils/usageSummary.ts +2 -46
@@ -4,7 +4,6 @@ import { useInput, useStdout } from "ink";
4
4
  import { useAppConfig } from "./useAppConfig.js";
5
5
  import { Agent, OPERATION_CANCELLED_BY_USER, extractLatestTotalTokens, } from "wave-agent-sdk";
6
6
  import { logger } from "../utils/logger.js";
7
- import { throttle } from "../utils/throttle.js";
8
7
  import { displayUsageSummary } from "../utils/usageSummary.js";
9
8
  import { expandLongTextPlaceholders } from "../managers/inputHandlers.js";
10
9
  const ChatContext = createContext(null);
@@ -75,6 +74,86 @@ function createStreamingWindowThrottle(fn, wait) {
75
74
  };
76
75
  return throttled;
77
76
  }
77
+ /**
78
+ * Per-tool window-concat throttle for pure-delta tool parameter streaming:
79
+ * `parametersChunk` deltas are accumulated independently per tool block id
80
+ * within the cooldown window, so interleaved multi-tool streams lose no delta
81
+ * (a plain throttle's single last-args slot would drop every earlier tool's
82
+ * deltas, leaving the first tool without streaming parameters). `start` /
83
+ * `running` apply immediately (one-shot snapshots); `end` flushes pending
84
+ * streaming deltas first, then applies the authoritative parameters/result.
85
+ */
86
+ export function createToolStreamingThrottle(fn, wait) {
87
+ let timer = null;
88
+ let pending = null;
89
+ const fire = () => {
90
+ if (pending && pending.chunks.size > 0) {
91
+ const { messageId, chunks } = pending;
92
+ pending = null;
93
+ for (const [id, chunk] of chunks) {
94
+ fn({ messageId, id, parametersChunk: chunk, stage: "streaming" });
95
+ }
96
+ }
97
+ };
98
+ const throttled = (params) => {
99
+ if (params.stage === "end") {
100
+ // Flush any deltas still pending inside the cooldown window first
101
+ if (timer) {
102
+ clearTimeout(timer);
103
+ timer = null;
104
+ }
105
+ fire();
106
+ fn(params);
107
+ return;
108
+ }
109
+ if (params.stage === "streaming") {
110
+ if (!pending) {
111
+ pending = { messageId: params.messageId, chunks: new Map() };
112
+ }
113
+ const prev = pending.chunks.get(params.id) || "";
114
+ pending.chunks.set(params.id, prev + (params.parametersChunk || ""));
115
+ if (!timer) {
116
+ timer = setTimeout(() => {
117
+ timer = null;
118
+ fire();
119
+ }, wait);
120
+ }
121
+ return;
122
+ }
123
+ // start / running — one-shot snapshots applied immediately. Drop this
124
+ // tool's buffered streaming deltas first: start/running carry the
125
+ // authoritative parameters, and a pending timer would otherwise fire late
126
+ // with a stale `streaming` event, regressing this tool block's stage back
127
+ // to streaming (yellow dot -> gray) mid-execution. Other tools' in-flight
128
+ // chunks are kept so interleaved multi-tool streaming still accumulates.
129
+ if (pending) {
130
+ pending.chunks.delete(params.id);
131
+ if (pending.chunks.size === 0) {
132
+ pending = null;
133
+ if (timer) {
134
+ clearTimeout(timer);
135
+ timer = null;
136
+ }
137
+ }
138
+ }
139
+ fn(params);
140
+ };
141
+ throttled.cancel = () => {
142
+ if (timer) {
143
+ clearTimeout(timer);
144
+ timer = null;
145
+ }
146
+ pending = null;
147
+ };
148
+ throttled.flush = () => {
149
+ if (timer) {
150
+ clearTimeout(timer);
151
+ timer = null;
152
+ }
153
+ fire();
154
+ };
155
+ return throttled;
156
+ }
78
157
  export const ChatProvider = ({ children, bypassPermissions, permissionMode: initialPermissionMode, pluginDirs, additionalDirectories, tools, allowedTools, disallowedTools, workdir, worktreeSession, originalCwd, version, model, mcpServers, }) => {
79
158
  const { restoreSessionId, continueLastSession } = useAppConfig();
80
159
  const { stdout } = useStdout();
@@ -142,8 +221,8 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
142
221
  };
143
222
  }));
144
223
  }, 500), []);
145
- const throttledToolBlockUpdate = useMemo(() => throttle((params) => {
146
- const { messageId, id: toolBlockId, ...updates } = params;
224
+ const throttledToolBlockUpdate = useMemo(() => createToolStreamingThrottle((params) => {
225
+ const { messageId, id: toolBlockId, parametersChunk, ...updates } = params;
147
226
  setMessages((prev) => prev.map((m) => {
148
227
  if (m.id !== messageId)
149
228
  return m;
@@ -158,7 +237,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
158
237
  id: toolBlockId,
159
238
  name: updates.name || "",
160
239
  stage: updates.stage || "start",
161
- parameters: updates.parameters || "",
240
+ parameters: (updates.parameters || "") + (parametersChunk || ""),
162
241
  result: updates.result || "",
163
242
  ...updates,
164
243
  },
@@ -168,7 +247,18 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
168
247
  return {
169
248
  ...m,
170
249
  blocks: m.blocks.map((b, idx) => idx === toolBlockIndex && b.type === "tool"
171
- ? { ...b, ...updates }
250
+ ? {
251
+ ...b,
252
+ ...updates,
253
+ // Streaming carries only the delta; append it to the
254
+ // accumulated parameters. start/running/end carry the
255
+ // authoritative value and replace wholesale.
256
+ parameters: parametersChunk
257
+ ? (b.parameters || "") + parametersChunk
258
+ : updates.parameters !== undefined
259
+ ? updates.parameters
260
+ : b.parameters,
261
+ }
172
262
  : b),
173
263
  };
174
264
  }));
@@ -204,6 +294,8 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
204
294
  const [tasks, setTasks] = useState([]);
205
295
  // Command state
206
296
  const [slashCommands, setSlashCommands] = useState([]);
297
+ // Agent definitions (for /agents overlay)
298
+ const [agentDefinitions, setAgentDefinitions] = useState([]);
207
299
  // Permission state
208
300
  const [permissionMode, setPermissionModeState] = useState(initialPermissionMode ||
209
301
  (bypassPermissions ? "bypassPermissions" : "default"));
@@ -236,7 +328,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
236
328
  }
237
329
  }, []);
238
330
  // Permission confirmation methods with queue support
239
- const showConfirmation = useCallback(async (toolName, toolInput, suggestedPrefix, hidePersistentOption, planContent, permissionMode) => {
331
+ const showConfirmation = useCallback(async (toolName, toolInput, suggestedPrefix, hidePersistentOption, planContent, permissionMode, warning) => {
240
332
  return new Promise((resolve, reject) => {
241
333
  const queueItem = {
242
334
  toolName,
@@ -245,6 +337,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
245
337
  hidePersistentOption,
246
338
  planContent,
247
339
  permissionMode,
340
+ warning,
248
341
  resolver: resolve,
249
342
  reject,
250
343
  };
@@ -355,14 +448,20 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
355
448
  }
356
449
  : m));
357
450
  },
358
- onCompleteBangMessage: (command, exitCode, messageId) => {
451
+ onCompleteBangMessage: (command, exitCode, messageId, output) => {
359
452
  if (isExpandedRef.current)
360
453
  return;
361
454
  setMessages((prev) => prev.map((m) => m.id === messageId
362
455
  ? {
363
456
  ...m,
364
457
  blocks: m.blocks.map((b, idx) => idx === m.blocks.length - 1 && b.type === "bang"
365
- ? { ...b, command, exitCode, stage: "end" }
458
+ ? {
459
+ ...b,
460
+ command,
461
+ exitCode,
462
+ stage: "end",
463
+ ...(output !== undefined ? { output } : {}),
464
+ }
366
465
  : b),
367
466
  }
368
467
  : m));
@@ -418,7 +517,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
418
517
  // Create the permission callback inside the try block to access showConfirmation
419
518
  const permissionCallback = async (context) => {
420
519
  try {
421
- return await showConfirmation(context.toolName, context.toolInput, context.suggestedPrefix, context.hidePersistentOption, context.planContent, context.permissionMode);
520
+ return await showConfirmation(context.toolName, context.toolInput, context.suggestedPrefix, context.hidePersistentOption, context.planContent, context.permissionMode, context.warning);
422
521
  }
423
522
  catch {
424
523
  // If confirmation was cancelled or failed, deny the operation
@@ -481,6 +580,9 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
481
580
  // Get initial commands
482
581
  const agentSlashCommands = agent.getSlashCommands?.() || [];
483
582
  setSlashCommands(agentSlashCommands);
583
+ // Get initial agent definitions
584
+ const initialAgentDefinitions = agent.getSubagentConfigurations?.() || [];
585
+ setAgentDefinitions(initialAgentDefinitions);
484
586
  }
485
587
  catch (error) {
486
588
  console.error("Failed to initialize AI manager:", error);
@@ -520,6 +622,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
520
622
  setMessages([]);
521
623
  setMcpServerStatuses([]);
522
624
  setSlashCommands([]);
625
+ setAgentDefinitions([]);
523
626
  setSessionId("");
524
627
  setIsLoading(false);
525
628
  setLatestTotalTokens(0);
@@ -706,6 +809,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
706
809
  hidePersistentOption: next.hidePersistentOption,
707
810
  planContent: next.planContent,
708
811
  permissionMode: next.permissionMode,
812
+ warning: next.warning,
709
813
  });
710
814
  setIsConfirmationVisible(true);
711
815
  setConfirmationQueue((prev) => prev.slice(1));
@@ -841,6 +945,7 @@ export const ChatProvider = ({ children, bypassPermissions, permissionMode: init
841
945
  stopBackgroundTask,
842
946
  slashCommands,
843
947
  hasSlashCommand,
948
+ agentDefinitions,
844
949
  permissionMode,
845
950
  setPermissionMode,
846
951
  isConfirmationVisible,
@@ -0,0 +1,49 @@
1
+ /**
2
+ * `wave daemon` client subcommands — talk to the wave daemon's unix socket
3
+ * (JSON-RPC over newline-delimited JSON) to list hosted sessions, inspect
4
+ * progress, inject messages and respond to pending permission requests.
5
+ *
6
+ * All subcommands are non-interactive: results go to stdout, diagnostics to
7
+ * stderr, and every handler calls process.exit() itself (yargs would fall
8
+ * through to the TUI otherwise). Every command connects to the fixed default
9
+ * socket `~/.wave/daemon.sock` — the daemon only runs on remote hosts, so no
10
+ * `--socket` override is offered (spec: daemon-command.md).
11
+ *
12
+ * Attach semantics: `initialize {workdir, restoreSessionId}` + `restoreSession`
13
+ * re-attach to a live session in the daemon's in-memory registry, or reload a
14
+ * transcript from disk under the current working directory. A session that is
15
+ * nowhere (live registry or disk) silently starts a FRESH session under a
16
+ * different id — the only reliable existence check is the `restoreSession`
17
+ * rejection ("Session not found: <id>"), after which the junk fresh session
18
+ * must be destroyed via the envelope sessionId returned by `initialize`.
19
+ */
20
+ /** Fixed default daemon socket (spec: 默认 socket 固定,无 --socket 覆盖). */
21
+ export declare const DEFAULT_DAEMON_SOCKET: string;
22
+ export declare function daemonListCommand(socketPath: string): Promise<void>;
23
+ export declare function daemonStatusCommand(socketPath: string, sessionId: string, lines?: number): Promise<void>;
24
+ export interface SendOptions {
25
+ timeout: number;
26
+ }
27
+ /**
28
+ * Send a message and wait for the reply that corresponds to it.
29
+ *
30
+ * Completion detection: `sendMessage` on an idle session resolves only after
31
+ * the whole turn finishes (InteractionService awaits sendAIMessage), while on a
32
+ * busy session it enqueues and returns immediately — so stopping on a bare
33
+ * `loadingChange:false` would exit early on the PREVIOUS turn's completion when
34
+ * queued behind a busy session. Instead, track the message IDs: `ourUserMessage`
35
+ * is the user message added when OUR turn starts (userMessageAdded), and the
36
+ * reply is the last assistantMessageAdded observed after it. A stale
37
+ * loading:false can then never satisfy the wait condition early (the reply has
38
+ * not been added yet).
39
+ */
40
+ export declare function daemonSendCommand(socketPath: string, sessionId: string, message: string, options?: SendOptions): Promise<void>;
41
+ export interface RespondOptions {
42
+ allow?: boolean;
43
+ deny?: boolean;
44
+ reason?: string;
45
+ answer?: string;
46
+ rule?: string;
47
+ mode?: string;
48
+ }
49
+ export declare function daemonRespondCommand(socketPath: string, sessionId: string, requestId: string, options: RespondOptions): Promise<void>;
@@ -0,0 +1,341 @@
1
+ /**
2
+ * `wave daemon` client subcommands — talk to the wave daemon's unix socket
3
+ * (JSON-RPC over newline-delimited JSON) to list hosted sessions, inspect
4
+ * progress, inject messages and respond to pending permission requests.
5
+ *
6
+ * All subcommands are non-interactive: results go to stdout, diagnostics to
7
+ * stderr, and every handler calls process.exit() itself (yargs would fall
8
+ * through to the TUI otherwise). Every command connects to the fixed default
9
+ * socket `~/.wave/daemon.sock` — the daemon only runs on remote hosts, so no
10
+ * `--socket` override is offered (spec: daemon-command.md).
11
+ *
12
+ * Attach semantics: `initialize {workdir, restoreSessionId}` + `restoreSession`
13
+ * re-attach to a live session in the daemon's in-memory registry, or reload a
14
+ * transcript from disk under the current working directory. A session that is
15
+ * nowhere (live registry or disk) silently starts a FRESH session under a
16
+ * different id — the only reliable existence check is the `restoreSession`
17
+ * rejection ("Session not found: <id>"), after which the junk fresh session
18
+ * must be destroyed via the envelope sessionId returned by `initialize`.
19
+ */
20
+ import net from "node:net";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+ import { ASK_USER_QUESTION_TOOL_NAME, ENTER_PLAN_MODE_TOOL_NAME, EXIT_PLAN_MODE_TOOL_NAME, getMessageContent, } from "wave-agent-sdk";
24
+ import { SocketClient } from "./socketClient.js";
25
+ /** Fixed default daemon socket (spec: 默认 socket 固定,无 --socket 覆盖). */
26
+ export const DEFAULT_DAEMON_SOCKET = path.join(os.homedir(), ".wave", "daemon.sock");
27
+ const PERMISSION_MODES = [
28
+ "default",
29
+ "bypassPermissions",
30
+ "acceptEdits",
31
+ "plan",
32
+ "dontAsk",
33
+ ];
34
+ // ── Connection helpers ─────────────────────────────────────────
35
+ function connectDaemon(socketPath) {
36
+ return new Promise((resolve, reject) => {
37
+ const socket = net.createConnection(socketPath);
38
+ socket.once("connect", () => resolve(new SocketClient(socket)));
39
+ socket.once("error", (err) => {
40
+ socket.destroy();
41
+ reject(err);
42
+ });
43
+ });
44
+ }
45
+ /** Connect or fail fast with the spec'd error; daemon idle-exits after 60s. */
46
+ async function connectDaemonOrExit(socketPath) {
47
+ try {
48
+ return await connectDaemon(socketPath);
49
+ }
50
+ catch (err) {
51
+ const code = err.code;
52
+ console.error(`无法连接 daemon socket ${socketPath}:daemon 未运行?(daemon 空闲 60 秒自动退出)` +
53
+ (code ? ` (${code})` : ""));
54
+ process.exit(1);
55
+ }
56
+ }
57
+ function fail(message) {
58
+ console.error(message);
59
+ process.exit(1);
60
+ }
61
+ /**
62
+ * Attach to a session; returns the initialized sessionId + working directory.
63
+ * Exits (nonzero) with the spec'd error when the session exists neither in the
64
+ * daemon registry nor on disk, destroying the fresh session that `initialize`
65
+ * silently created.
66
+ */
67
+ async function attachSession(client, sessionId) {
68
+ const init = (await client.request("initialize", {
69
+ workdir: process.cwd(),
70
+ restoreSessionId: sessionId,
71
+ }));
72
+ const initId = init.sessionId;
73
+ try {
74
+ await client.request("restoreSession", { sessionId }, initId);
75
+ }
76
+ catch (err) {
77
+ if (err.message.includes("Session not found")) {
78
+ // initialize silently started a junk fresh session — remove it from the
79
+ // registry so the failed attach leaves no trace (spec: 会话不存在错误).
80
+ await client.request("destroy", undefined, initId).catch(() => { });
81
+ fail(`会话不存在或未被该 daemon 托管:${sessionId}`);
82
+ }
83
+ throw err;
84
+ }
85
+ return init;
86
+ }
87
+ async function listPendingPermissions(client) {
88
+ const result = (await client.request("listPendingPermissions"));
89
+ return result.requests ?? [];
90
+ }
91
+ function sleep(ms) {
92
+ return new Promise((resolve) => setTimeout(resolve, ms));
93
+ }
94
+ // ── list ───────────────────────────────────────────────────────
95
+ export async function daemonListCommand(socketPath) {
96
+ let client;
97
+ try {
98
+ client = await connectDaemonOrExit(socketPath);
99
+ const result = (await client.request("listDaemonSessions"));
100
+ const sessions = result.sessions ?? [];
101
+ if (sessions.length > 0) {
102
+ const rows = sessions.map((s) => ({
103
+ sessionId: s.sessionId,
104
+ status: s.isLoading ? "生成中" : "空闲",
105
+ messageCount: String(s.messageCount),
106
+ workingDirectory: s.workingDirectory,
107
+ }));
108
+ const width = (key) => Math.max(...rows.map((r) => r[key].length), key.length);
109
+ const pad = (value, w) => value.padEnd(w);
110
+ console.log(`${pad("会话", width("sessionId"))} ${pad("状态", width("status"))} ${pad("消息数", width("messageCount"))} 工作目录`);
111
+ for (const r of rows) {
112
+ console.log(`${pad(r.sessionId, width("sessionId"))} ${pad(r.status, width("status"))} ${pad(r.messageCount, width("messageCount"))} ${r.workingDirectory}`);
113
+ }
114
+ }
115
+ else {
116
+ // Daemon idle-exit is normal — an empty registry is not an error.
117
+ console.log("无会话");
118
+ }
119
+ }
120
+ catch (err) {
121
+ fail(`wave daemon list 失败:${err.message}`);
122
+ }
123
+ finally {
124
+ await client?.dispose();
125
+ }
126
+ // Exits outside the try so the success path's exit is never re-wrapped by the
127
+ // error handler above.
128
+ process.exit(0);
129
+ }
130
+ // ── status ─────────────────────────────────────────────────────
131
+ function summarizeToolInput(context) {
132
+ const input = context.toolInput;
133
+ if (!input || Object.keys(input).length === 0)
134
+ return "";
135
+ let text;
136
+ try {
137
+ text = JSON.stringify(input);
138
+ }
139
+ catch {
140
+ text = "";
141
+ }
142
+ return text.length > 80 ? `${text.slice(0, 80)}…` : text;
143
+ }
144
+ export async function daemonStatusCommand(socketPath, sessionId, lines = 20) {
145
+ let client;
146
+ try {
147
+ client = await connectDaemonOrExit(socketPath);
148
+ // Subscribe BEFORE initialize/restoreSession so the replayed loadingChange
149
+ // snapshot is captured (spec: 依据重放的 loadingChange 快照显示状态).
150
+ let loading = false;
151
+ client.onNotification("loadingChange", (params) => {
152
+ loading = params.loading;
153
+ });
154
+ const init = await attachSession(client, sessionId);
155
+ const initId = init.sessionId;
156
+ // listPendingPermissions is the authoritative "waiting for approval" signal
157
+ // (spec: 单凭消息无法区分等审批与执行中,须结合 listPendingPermissions).
158
+ const pending = (await listPendingPermissions(client)).filter((r) => r.sessionId === initId || r.sessionId === sessionId);
159
+ const messages = (await client.request("getMessages", undefined, initId));
160
+ const status = pending.length > 0 ? "等待审批" : loading ? "生成中" : "空闲";
161
+ console.log(`会话: ${initId}`);
162
+ console.log(`工作目录: ${init.workingDirectory}`);
163
+ console.log(`状态: ${status}`);
164
+ if (pending.length > 0) {
165
+ console.log("");
166
+ console.log("待审批请求:");
167
+ for (const r of pending) {
168
+ const params = summarizeToolInput(r.context);
169
+ console.log(` ${r.requestId} ${r.context.toolName}${params ? ` ${params}` : ""}`);
170
+ }
171
+ }
172
+ const recent = messages.messages.slice(-lines);
173
+ if (recent.length > 0) {
174
+ console.log("");
175
+ console.log(`最近消息 (${recent.length}):`);
176
+ for (const m of recent) {
177
+ const text = getMessageContent(m).replace(/\s+/g, " ").trim();
178
+ if (!text)
179
+ continue; // tool-only messages carry no readable text
180
+ console.log(` [${m.role}] ${text}`);
181
+ }
182
+ }
183
+ }
184
+ catch (err) {
185
+ fail(`wave daemon status 失败:${err.message}`);
186
+ }
187
+ finally {
188
+ await client?.dispose();
189
+ }
190
+ process.exit(0);
191
+ }
192
+ /**
193
+ * Send a message and wait for the reply that corresponds to it.
194
+ *
195
+ * Completion detection: `sendMessage` on an idle session resolves only after
196
+ * the whole turn finishes (InteractionService awaits sendAIMessage), while on a
197
+ * busy session it enqueues and returns immediately — so stopping on a bare
198
+ * `loadingChange:false` would exit early on the PREVIOUS turn's completion when
199
+ * queued behind a busy session. Instead, track the message IDs: `ourUserMessage`
200
+ * is the user message added when OUR turn starts (userMessageAdded), and the
201
+ * reply is the last assistantMessageAdded observed after it. A stale
202
+ * loading:false can then never satisfy the wait condition early (the reply has
203
+ * not been added yet).
204
+ */
205
+ export async function daemonSendCommand(socketPath, sessionId, message, options = { timeout: 600 }) {
206
+ // connectDaemonOrExit exits on failure — no client to dispose in that case.
207
+ const client = await connectDaemonOrExit(socketPath);
208
+ let loading = false;
209
+ let sent = false;
210
+ let ourUserMessageId;
211
+ let replyMessageId;
212
+ client.onNotification("userMessageAdded", (params) => {
213
+ if (!sent)
214
+ return; // ignore messages added during attach
215
+ ourUserMessageId = params.message.id;
216
+ });
217
+ client.onNotification("assistantMessageAdded", (params) => {
218
+ if (!sent || ourUserMessageId === undefined)
219
+ return; // not our turn yet
220
+ replyMessageId = params.message.id;
221
+ });
222
+ client.onNotification("loadingChange", (params) => {
223
+ loading = params.loading;
224
+ });
225
+ let initId;
226
+ try {
227
+ initId = (await attachSession(client, sessionId)).sessionId;
228
+ sent = true;
229
+ await client.request("sendMessage", { text: message }, initId);
230
+ }
231
+ catch (err) {
232
+ client.dispose();
233
+ fail(`wave daemon send 失败:${err.message}`);
234
+ }
235
+ // Wait for the reply that corresponds to our message.
236
+ const started = Date.now();
237
+ const timeoutMs = options.timeout === 0 ? Infinity : options.timeout * 1000;
238
+ while (!(loading === false && replyMessageId !== undefined)) {
239
+ if (Date.now() - started > timeoutMs) {
240
+ // Timeout backstop: the most likely cause is a session waiting on a
241
+ // permission approval — point the user at respond (spec: 不无限期挂起).
242
+ const pending = (await listPendingPermissions(client)).filter((r) => r.sessionId === sessionId || r.sessionId === initId);
243
+ client.dispose();
244
+ if (pending.length > 0) {
245
+ fail(`会话等待权限审批,请通过 \`wave daemon respond ${sessionId} ${pending[0].requestId}\` 处理后重试`);
246
+ }
247
+ fail(options.timeout === 0
248
+ ? "等待回复超时"
249
+ : `等待回复超时(${options.timeout} 秒),未收到助手回复`);
250
+ }
251
+ await sleep(200);
252
+ }
253
+ try {
254
+ const result = (await client.request("getMessages", undefined, initId));
255
+ const reply = result.messages.find((m) => m.id === replyMessageId);
256
+ // Pure final-reply text only; streaming deltas / subagent internals never
257
+ // reach stdout (spec: send 输出纯净性).
258
+ if (reply) {
259
+ const content = getMessageContent(reply).replace(/\s+/g, " ").trim();
260
+ if (content)
261
+ console.log(content);
262
+ }
263
+ }
264
+ catch (err) {
265
+ fail(`wave daemon send 失败:${err.message}`);
266
+ }
267
+ finally {
268
+ client.dispose();
269
+ }
270
+ process.exit(0);
271
+ }
272
+ export async function daemonRespondCommand(socketPath, sessionId, requestId, options) {
273
+ if (!!options.allow === !!options.deny) {
274
+ fail("请指定 --allow 或 --deny(二选一)");
275
+ }
276
+ let client;
277
+ try {
278
+ client = await connectDaemonOrExit(socketPath);
279
+ // The server silently ignores permissionResponse for unknown requestIds —
280
+ // validate first so the user is never misled into thinking approval landed.
281
+ const pending = await listPendingPermissions(client);
282
+ const req = pending.find((r) => r.requestId === requestId);
283
+ if (!req) {
284
+ fail("该请求不存在或已处理");
285
+ }
286
+ if (req.sessionId && req.sessionId !== sessionId) {
287
+ // Cross-check before notifying; never touch another session's request.
288
+ fail("会话不存在或未被该 daemon 托管");
289
+ }
290
+ let decision;
291
+ if (options.deny) {
292
+ decision = { behavior: "deny", message: options.reason };
293
+ }
294
+ else {
295
+ // Per-tool auto-completion, mirroring the desktop ConfirmationDialog
296
+ // semantics (spec: 决策并非单一 allow/deny,须按工具智能补全).
297
+ const toolName = req.context.toolName;
298
+ if (toolName === ENTER_PLAN_MODE_TOOL_NAME) {
299
+ decision = { behavior: "allow", newPermissionMode: "plan" };
300
+ }
301
+ else if (toolName === EXIT_PLAN_MODE_TOOL_NAME) {
302
+ decision = { behavior: "allow", newPermissionMode: "default" };
303
+ }
304
+ else if (toolName === ASK_USER_QUESTION_TOOL_NAME) {
305
+ if (!options.answer) {
306
+ fail("AskUserQuestion 请求需要 --answer 提供答案 JSON");
307
+ }
308
+ let answers;
309
+ try {
310
+ answers = JSON.parse(options.answer);
311
+ }
312
+ catch {
313
+ fail("--answer 不是合法的 JSON");
314
+ }
315
+ decision = { behavior: "allow", message: JSON.stringify(answers) };
316
+ }
317
+ else {
318
+ decision = { behavior: "allow" };
319
+ }
320
+ if (options.rule)
321
+ decision.newPermissionRule = options.rule;
322
+ if (options.mode) {
323
+ if (!PERMISSION_MODES.includes(options.mode)) {
324
+ fail(`无效的权限模式:${options.mode}(可选:${PERMISSION_MODES.join("、")})`);
325
+ }
326
+ decision.newPermissionMode = options.mode;
327
+ }
328
+ }
329
+ // Mirror desktop stdioAgent.sendPermissionResponse: envelope sessionId
330
+ // present, decision built from the pending request's tool.
331
+ client.notify("permissionResponse", { requestId, decision }, sessionId);
332
+ console.log(`已处理审批请求:${requestId}`);
333
+ }
334
+ catch (err) {
335
+ fail(`wave daemon respond 失败:${err.message}`);
336
+ }
337
+ finally {
338
+ await client?.dispose();
339
+ }
340
+ process.exit(0);
341
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * JsonRpcClient — minimal JSON-RPC transport over a line-delimited duplex
3
+ * stream (one JSON object per line).
4
+ *
5
+ * Used by `wave daemon` subcommands to talk to the wave daemon's unix socket.
6
+ * Mirrors packages/desktop/src/main/stdio/jsonRpcClient.ts (packages/code
7
+ * cannot import from packages/desktop). Subclasses own the transport and hook
8
+ * in:
9
+ * - `writeLine(message)` writes one JSON line to the peer.
10
+ * - `attachReadable(readable)` wires the inbound half (socket).
11
+ * - `handleClosed(reason)` marks the transport dead and rejects every pending
12
+ * request. Idempotent — safe to call from both dispose() and an exit/close
13
+ * event on the underlying transport.
14
+ */
15
+ import type { Readable } from "stream";
16
+ export type NotificationHandler = (params: unknown, sessionId?: string) => void;
17
+ export declare abstract class JsonRpcClient {
18
+ private nextId;
19
+ private pending;
20
+ private handlers;
21
+ private closedHandlers;
22
+ private closed;
23
+ protected abstract writeLine(message: string): void;
24
+ /** Wire an inbound Readable (socket) to the line parser. */
25
+ protected attachReadable(readable: Readable): void;
26
+ /** Mark the transport closed: reject every pending request. Idempotent. */
27
+ protected handleClosed(reason: string): void;
28
+ protected get isClosed(): boolean;
29
+ /** Close the transport and reject pending requests (subclass tears down its stream). */
30
+ abstract dispose(): void;
31
+ /** Observe transport teardown (dispose or unexpected close), fired once. */
32
+ onClosed(handler: () => void): void;
33
+ request(method: string, params?: unknown, sessionId?: string): Promise<unknown>;
34
+ notify(method: string, params?: unknown, sessionId?: string): void;
35
+ onNotification(method: string, handler: NotificationHandler): void;
36
+ offNotification(method: string, handler: NotificationHandler): void;
37
+ private handleLine;
38
+ }