advisers 0.3.2 → 0.4.0

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 (44) hide show
  1. package/README-zh.md +13 -14
  2. package/README.md +32 -23
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2180 -92
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/error-codes.js +516 -7
  11. package/lib/evidence.js +697 -113
  12. package/lib/kb-extract.js +626 -0
  13. package/lib/kb-facts.js +429 -0
  14. package/lib/kb-pages.js +1084 -0
  15. package/lib/kb.js +1036 -0
  16. package/lib/mail-errors.js +46 -0
  17. package/lib/mail-extract.js +351 -0
  18. package/lib/mail-imap.js +446 -0
  19. package/lib/mail-import.js +176 -0
  20. package/lib/mail-parse.js +223 -0
  21. package/lib/mail-store.js +731 -0
  22. package/lib/mail.js +506 -0
  23. package/lib/mcp-server.js +196 -10
  24. package/lib/notify.js +265 -7
  25. package/lib/policy/decision.js +315 -0
  26. package/lib/policy/egress.js +268 -0
  27. package/lib/policy/errors.js +71 -0
  28. package/lib/policy/index.js +99 -0
  29. package/lib/policy/rules.js +468 -0
  30. package/lib/policy/surfaces.js +141 -0
  31. package/lib/receipt-verify.js +199 -19
  32. package/lib/receivables.js +1653 -0
  33. package/lib/scheduler.js +453 -9
  34. package/lib/shell.js +1406 -0
  35. package/lib/source.js +98 -3
  36. package/lib/sqlite.js +366 -49
  37. package/lib/tos/index.js +2 -2
  38. package/lib/tos/manifest.json +6 -6
  39. package/lib/tos/privacy.zh-CN.md +33 -20
  40. package/lib/tos/safety.zh-CN.md +7 -6
  41. package/lib/tos/summary.zh-CN.md +3 -2
  42. package/lib/tos/terms.zh-CN.md +31 -16
  43. package/lib/urgency.js +467 -0
  44. package/package.json +4 -4
package/lib/shell.js ADDED
@@ -0,0 +1,1406 @@
1
+ /**
2
+ * Advisers 0.4.0 interactive shell - library layer (no bin wiring).
3
+ *
4
+ * The shell is an append-only readline loop with a four-state machine, the result /
5
+ * status / error / confirmation blocks of the 0.3.x output kernel, and a strict
6
+ * "every human line goes through sanitizeDisplay" rule. It deliberately does NOT own
7
+ * business logic: the caller (bin/advisers.js) injects JSON-ready read-only views and
8
+ * one turn executor through `handlers`. That keeps this module testable without a
9
+ * store or a model, and keeps the 11k-line bin free of a second command surface.
10
+ *
11
+ * States (SHELL_STATES):
12
+ *
13
+ * IDLE --submit--> WORKING --done/failed--> IDLE
14
+ * ^ |--confirm--> CONFIRM --y--> WORKING / --n|Enter|Esc--> IDLE
15
+ * | +--Ctrl+C|Esc--> IDLE (interrupted block, AbortController)
16
+ * +-- /quit, /exit, Ctrl+D, EOF --> exit 0
17
+ * +-- input while WORKING --> QUEUED (buffered by readline; one prompt later)
18
+ *
19
+ * Keyboard semantics:
20
+ * - idle Ctrl+C: clear the current line, then exit on a second press within 2s;
21
+ * - working Ctrl+C / Esc: abort the in-flight turn through the AbortSignal;
22
+ * - confirm Ctrl+C / Esc: answer "no" (the default is always no);
23
+ * - Ctrl+D / EOF: leave with exit code 0;
24
+ * - plain mode (--plain/--accessible/non-TTY stdout) uses a canonical readline
25
+ * (terminal:false, zero ESC); there Esc is unavailable and Ctrl+C arrives as
26
+ * SIGINT, which the shell treats exactly like the raw-mode key.
27
+ *
28
+ * Non-TTY split:
29
+ * - stdin not a TTY: runShell() does not enter (entered:false); the caller keeps
30
+ * the existing "help and exit" behaviour;
31
+ * - stdin TTY + stdout pipe: prompt/status/confirmation go to stderr, results to
32
+ * stdout, one notice is written to stderr; no SGR/cursor control is emitted;
33
+ * - stdin TTY + stdout TTY: the normal shell.
34
+ *
35
+ * Injection defence: every line the shell writes (own literals, handler blocks, status
36
+ * lines, the paste notice) is passed through sanitizeDisplay() again; kernel renderers
37
+ * already sanitise, so this is belt-and-braces. Model/tool/store text always reaches
38
+ * the screen through the kernel renderers as data, never as terminal control.
39
+ *
40
+ * Public API (the bin integration contract):
41
+ *
42
+ * const result = await runShell({
43
+ * argv, env, stdin, stdout, stderr,
44
+ * store, // passed through to handlers via ctx.store
45
+ * allowPaths, // passed to handlers.turn and ctx.allowPaths
46
+ * handlers: {
47
+ * status(ctx) -> { today?, model?, local?, hint?, kind?, lines?, headline?, ... }
48
+ * turn(payload, ctx) -> turnResult (see TurnResult below)
49
+ * history(payload, ctx) -> block | { sessions: [{ n?, id, title?, updatedAt? }] }
50
+ * resume(payload, ctx) -> block ({ arg } is the user argument)
51
+ * newSession(ctx) -> block
52
+ * today(payload, ctx) -> block
53
+ * remind(payload, ctx) -> block
54
+ * who(payload, ctx) -> block
55
+ * client(payload, ctx) -> block ({ args, arg }; e.g. "list" or a client id)
56
+ * evidence(payload, ctx) -> block ({ arg } is the evidence id)
57
+ * legacyCommand(payload, ctx) -> block | undefined (old /commands; undefined = unknown)
58
+ * answer(payload, ctx) -> block (optional: answers a turn's follow-up question)
59
+ * opening(ctx) -> block | string[] (optional: <=2 startup lines)
60
+ * },
61
+ * onState, // optional test hook: ({ from, to, reason }) => void
62
+ * })
63
+ *
64
+ * `turnResult` is JSON-ready:
65
+ * { reply?, summary?, headline?, lines?, artifacts?, checks?, warnings?, next?,
66
+ * tools?: [{ name, ok }], durationMs?, internal?: string[], question?,
67
+ * interrupted?, error?: { title?, reason?, kept?, next?, code? } }
68
+ * Handler blocks are the kernel shapes: renderResult/renderError/renderConfirm input
69
+ * objects (or a plain string[]). Throwing an Error with a `code` property renders the
70
+ * failure block with that code.
71
+ *
72
+ * Run result: { entered, exitCode, reason, turns }. Reasons: interactive -> quit / eof /
73
+ * sigint / error; not entered -> stdin-not-tty / json-unsupported / disabled.
74
+ *
75
+ * Wiring note (0.4.0): bin/advisers.js keeps the TOS gate, model/store setup and the
76
+ * existing runTurnInner; it passes a turn handler that adapts runTurnInner to the
77
+ * turnResult shape. This module imports no bin code, reads no env at import time and
78
+ * performs no I/O until runShell() is called.
79
+ *
80
+ * @module lib/shell
81
+ */
82
+
83
+ import * as readline from 'node:readline'
84
+ import { StringDecoder } from 'node:string_decoder'
85
+ import { Transform } from 'node:stream'
86
+
87
+ import {
88
+ ALLOWED_SGR_CODES,
89
+ clampColumns,
90
+ envFlag,
91
+ renderConfirm,
92
+ renderError,
93
+ renderResult,
94
+ renderStatus,
95
+ resolveOutputPolicy,
96
+ sanitizeDisplay,
97
+ } from './tui/index.js'
98
+
99
+ /** Prompt printed before every input line (single static, sanitised string). */
100
+ export const SHELL_PROMPT = '\u203a '
101
+ /** The shell's four states. `queued` means input arrived while a turn was running. */
102
+ export const SHELL_STATES = Object.freeze({
103
+ IDLE: 'idle',
104
+ WORKING: 'working',
105
+ CONFIRM: 'confirm',
106
+ QUEUED: 'queued',
107
+ })
108
+ /** Core command surface shipped by the shell. */
109
+ export const SHELL_CORE_COMMANDS = Object.freeze([
110
+ '/help',
111
+ '/status',
112
+ '/history',
113
+ '/resume',
114
+ '/new',
115
+ '/file',
116
+ '/files',
117
+ '/clear',
118
+ '/retry',
119
+ '/verbose',
120
+ '/more',
121
+ '/quit',
122
+ '/today',
123
+ '/remind',
124
+ '/who',
125
+ '/client',
126
+ '/evidence',
127
+ '/exit',
128
+ ])
129
+ /** Bracketed-paste markers emitted by xterm/VTE/Windows Terminal 1.7+. */
130
+ export const PASTE_START = '\u001b[200~'
131
+ export const PASTE_END = '\u001b[201~'
132
+ /** Pasted text is merged to one line and capped at this many characters. */
133
+ export const PASTE_MAX_CHARS = 4000
134
+ /** A lone ESC is held this long so it cannot corrupt the next typed character. */
135
+ export const ESCAPE_HOLD_MS = 200
136
+ /** Second idle Ctrl+C within this window exits the shell. */
137
+ export const SIGINT_WINDOW_MS = 2000
138
+
139
+ const EOF = Symbol('shell-eof')
140
+ const CANCEL = Symbol('shell-cancel')
141
+
142
+ const LEGACY_COMMANDS = Object.freeze([
143
+ ['/deliveries', 'recent generated files'],
144
+ ['/correct <text>', 'record a correction (second time promotes it)'],
145
+ ['/matter use <id>', 'set the default matter for later writes'],
146
+ ['/agenda', '7-day agenda (commitments + calendar)'],
147
+ ['/memory', 'what I remember'],
148
+ ['/commit add|ls ...', 'commitments (business write: prefer the CLI)'],
149
+ ['/done <id> --evidence <text>', 'complete a commitment'],
150
+ ['/search <text>', 'full-text search old turns'],
151
+ ['/tick', 'due in the next 7 days'],
152
+ ['/week', 'last 7 days'],
153
+ ['/digest [day|week]', 'today/week digest'],
154
+ ['/diff', 'show the last changed file'],
155
+ ['/undo', 'restore the last overwritten/created file'],
156
+ ['/links', 'candidate/confirmed links'],
157
+ ['/forget <id>', 'forget a preference'],
158
+ ['/prefs', 'list preferences (including candidates)'],
159
+ ['/audit', 'verify and show the audit hash chain'],
160
+ ['/decay', 'apply 30-day preference decay'],
161
+ ['/why <pref-id>', 'explain a preference'],
162
+ ['/routine save', 'save the last task as a draft routine'],
163
+ ['/brief <text>', 'print the IntentBrief without calling the model'],
164
+ ['/debug', 'toggle full context'],
165
+ ])
166
+
167
+ /**
168
+ * Resolve the render width for one render pass. The width is re-read on every call
169
+ * (requirement: "width each render"), so a SIGWINCH is picked up without redraw logic.
170
+ *
171
+ * Precedence: `--width N` / `--width=N` argv, then `ADVISERS_SHELL_WIDTH` env, then
172
+ * `streamOrColumns.columns`; clamped to 40..200 by the kernel.
173
+ *
174
+ * @param {number | { columns?: number } | null | undefined} streamOrColumns
175
+ * @param {Record<string, unknown>} [env]
176
+ * @param {string[]} [argv]
177
+ * @returns {number}
178
+ */
179
+ export function resolveShellWidth(streamOrColumns, env = {}, argv = []) {
180
+ const fromArgv = readWidthArg(argv)
181
+ const fromEnv = Number.parseInt(String(env?.ADVISERS_SHELL_WIDTH ?? ''), 10)
182
+ const columns = typeof streamOrColumns === 'number' ? streamOrColumns : streamOrColumns?.columns
183
+ let candidate = fromArgv
184
+ if (candidate === undefined && Number.isFinite(fromEnv)) candidate = fromEnv
185
+ if (candidate === undefined) candidate = columns
186
+ return clampColumns(candidate)
187
+ }
188
+
189
+ function readWidthArg(argv) {
190
+ if (!Array.isArray(argv)) return undefined
191
+ for (let index = 0; index < argv.length; index += 1) {
192
+ const value = typeof argv[index] === 'string' ? argv[index] : ''
193
+ if (value === '--width') {
194
+ const next = Number.parseInt(String(argv[index + 1] ?? ''), 10)
195
+ if (Number.isFinite(next)) return next
196
+ index += 1
197
+ } else if (value.startsWith('--width=')) {
198
+ const next = Number.parseInt(value.slice('--width='.length), 10)
199
+ if (Number.isFinite(next)) return next
200
+ }
201
+ }
202
+ return undefined
203
+ }
204
+
205
+ /**
206
+ * Decide whether the interactive shell may run. Non-TTY stdin keeps the 0.3.x
207
+ * "print help, exit 0" path; `--json` is not supported by the human shell.
208
+ *
209
+ * @param {{ argv?: string[], env?: Record<string, unknown>, stdinIsTTY?: boolean, stdoutIsTTY?: boolean, stderrIsTTY?: boolean }} [options]
210
+ * @returns {Readonly<{ enter: boolean, reason: string, exitCode: number }>}
211
+ */
212
+ export function shouldEnterShell({ argv = [], env = {}, stdinIsTTY = false, stdoutIsTTY = false, stderrIsTTY = false } = {}) {
213
+ void stdoutIsTTY
214
+ void stderrIsTTY
215
+ if (Array.isArray(argv) && argv.includes('--json')) return Object.freeze({ enter: false, reason: 'json-unsupported', exitCode: 1 })
216
+ if (envFlag(env, 'ADVISERS_NO_SHELL')) return Object.freeze({ enter: false, reason: 'disabled', exitCode: 0 })
217
+ if (!stdinIsTTY) return Object.freeze({ enter: false, reason: 'stdin-not-tty', exitCode: 0 })
218
+ return Object.freeze({ enter: true, reason: 'interactive', exitCode: 0 })
219
+ }
220
+
221
+ /**
222
+ * Classify one input line. Rules:
223
+ * - blank -> empty;
224
+ * - a line starting with `//` sends the text starting with one `/`;
225
+ * - a line whose first character is whitespace but which trims to `/...` is text
226
+ * (the documented escape for a real message that begins with a slash);
227
+ * - otherwise `/name args...` is a command (name lower-cased) and everything else is
228
+ * natural-language text for the turn executor.
229
+ *
230
+ * @param {string} rawLine
231
+ * @returns {{ kind: 'empty'|'command'|'text', raw: string, text: string, name: string|null, args: string[], arg?: string }}
232
+ */
233
+ export function parseShellLine(rawLine) {
234
+ const raw = typeof rawLine === 'string' ? rawLine : String(rawLine ?? '')
235
+ if (raw.trim() === '') return { kind: 'empty', raw, text: '', name: null, args: [] }
236
+ if (raw.startsWith('//')) return { kind: 'text', raw, text: raw.slice(1), name: null, args: [] }
237
+ if (/^\s+\//.test(raw)) return { kind: 'text', raw, text: raw.replace(/^\s+/, ''), name: null, args: [] }
238
+ const line = raw.trim()
239
+ if (!line.startsWith('/')) return { kind: 'text', raw, text: line, name: null, args: [] }
240
+ const match = /^(\S+)(?:\s+([\s\S]*))?$/.exec(line)
241
+ const name = (match?.[1] ?? line).toLowerCase()
242
+ const arg = (match?.[2] ?? '').trim()
243
+ return { kind: 'command', raw, text: line, name, args: arg === '' ? [] : arg.split(/\s+/), arg }
244
+ }
245
+
246
+ /**
247
+ * Merge a bracketed-paste payload into one display line: strip terminal sequences,
248
+ * fold CR/LF/tabs to spaces, collapse runs of spaces, cap at `maxChars`.
249
+ *
250
+ * Pure function (unit-tested); used by PasteGuard and safe to call standalone.
251
+ *
252
+ * @param {string} raw
253
+ * @param {{ maxChars?: number }} [options]
254
+ * @returns {{ text: string, lines: number, chars: number, truncated: boolean }}
255
+ */
256
+ export function mergePastedText(raw, { maxChars = PASTE_MAX_CHARS } = {}) {
257
+ const source = typeof raw === 'string' ? raw : String(raw ?? '')
258
+ if (source === '') return { text: '', lines: 0, chars: 0, truncated: false }
259
+ const display = sanitizeDisplay(source, { expandTabs: true })
260
+ const lines = display.split('\n').length
261
+ let text = display.replace(/[\r\n]+/g, ' ').replace(/ {2,}/g, ' ').trim()
262
+ const limit = Number.isFinite(maxChars) && maxChars > 0 ? Math.floor(maxChars) : PASTE_MAX_CHARS
263
+ let truncated = false
264
+ if (text.length > limit) {
265
+ text = text.slice(0, limit) + '\u2026'
266
+ truncated = true
267
+ }
268
+ return { text, lines, chars: source.length, truncated }
269
+ }
270
+
271
+ /**
272
+ * Sanitise one line that the shell is about to write. Keeps leading indentation
273
+ * (block prefixes) but forbids multi-line output: escape sequences, OSC/DCS, bidi
274
+ * overrides, C0/C1 control characters are stripped by sanitizeDisplay.
275
+ *
276
+ * @param {unknown} value
277
+ * @returns {string}
278
+ */
279
+ export function sanitizeShellLine(value) {
280
+ const text = sanitizeDisplay(value === null || value === undefined ? '' : value, { expandTabs: true })
281
+ return text.replace(/\r?\n/g, ' ')
282
+ }
283
+
284
+ /**
285
+ * Sanitise one rendered line for the wire. In colour mode the kernel's whitelisted
286
+ * 16-colour SGR sequences are preserved (they are the only escape bytes the kernel can
287
+ * emit), everything else - including any non-whitelisted SGR, OSC, CSI, bidi - is
288
+ * stripped by sanitizeDisplay. In plain mode it is exactly sanitizeShellLine().
289
+ *
290
+ * @param {unknown} value
291
+ * @param {{ color?: boolean }} [options]
292
+ * @returns {string}
293
+ */
294
+ export function sanitizeRenderedLine(value, { color = false } = {}) {
295
+ const raw = typeof value === 'string' ? value : String(value === null || value === undefined ? '' : value)
296
+ if (!color) return sanitizeShellLine(raw)
297
+ const pattern = /\u001b\[([0-9;]+)m/g
298
+ let out = ''
299
+ let last = 0
300
+ let match
301
+ while ((match = pattern.exec(raw)) !== null) {
302
+ out += sanitizeDisplay(raw.slice(last, match.index), { expandTabs: true })
303
+ const codes = match[1].split(';').map((part) => Number.parseInt(part, 10))
304
+ if (codes.length > 0 && codes.every((code) => ALLOWED_SGR_CODES.includes(code))) out += match[0]
305
+ last = pattern.lastIndex
306
+ }
307
+ out += sanitizeDisplay(raw.slice(last), { expandTabs: true })
308
+ return out.replace(/\r?\n/g, ' ')
309
+ }
310
+
311
+ /**
312
+ * `/help` block (core commands, <=10 rendered lines at normal widths).
313
+ *
314
+ * @returns {{ headline: string, lines: Array<{ role: string, text: string }>, summary: string }}
315
+ */
316
+ export function shellHelpBlock() {
317
+ return {
318
+ headline: '核心命令(业务写操作留在 CLI)',
319
+ lines: [
320
+ { role: 'item', text: '/help /more 帮助 / 旧命令全量' },
321
+ { role: 'item', text: '/status 状态;/history /resume <n|id> /new 会话' },
322
+ { role: 'item', text: '/file <path> /files /clear 附件' },
323
+ { role: 'item', text: '/retry /verbose 重试上一轮 / 明细' },
324
+ { role: 'item', text: '/today /remind /who /client /evidence 只读视图' },
325
+ { role: 'item', text: '/quit(/exit、Ctrl+D)退出;Esc / Ctrl+C 中断本轮' },
326
+ ],
327
+ summary: '业务命令用 advisers --help;以空格或 // 开头可发送以 / 开头的文本。',
328
+ }
329
+ }
330
+
331
+ /**
332
+ * `/more` block: the pre-0.4 REPL command list, still routed through the caller's
333
+ * `legacyCommand` handler when wired.
334
+ *
335
+ * @returns {{ headline: string, lines: Array<{ role: string, text: string }> }}
336
+ */
337
+ export function shellMoreBlock() {
338
+ return {
339
+ headline: '旧命令(壳保留入口;写操作请用结果块给出的 advisers 命令)',
340
+ lines: LEGACY_COMMANDS.map(([name, description]) => ({ role: 'item', text: `${name} ${description}` })),
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Static readline completer for the `/` command surface.
346
+ *
347
+ * @param {readonly string[]} [names]
348
+ * @returns {(line: string) => [string[], string]}
349
+ */
350
+ export function createCommandCompleter(names = SHELL_CORE_COMMANDS) {
351
+ const table = Array.isArray(names) && names.length > 0 ? [...names] : [...SHELL_CORE_COMMANDS]
352
+ return (line) => {
353
+ const text = typeof line === 'string' ? line : String(line ?? '')
354
+ const trimmed = text.trimStart()
355
+ if (!trimmed.startsWith('/') || /\s/.test(trimmed)) return [[], text]
356
+ const hits = table.filter((name) => name.startsWith(trimmed))
357
+ return [hits.length > 0 ? hits : table, text]
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Positive answer for a confirmation. Everything else (including Enter and EOF) is
363
+ * "no": the default is always no.
364
+ *
365
+ * @param {unknown} value
366
+ * @returns {boolean}
367
+ */
368
+ export function isAffirmativeAnswer(value) {
369
+ if (typeof value !== 'string') return false
370
+ return /^(?:y|yes|\u662f)$/i.test(value.trim())
371
+ }
372
+
373
+ /** Largest suffix of `buffer` that is a proper prefix of `marker` (0..marker.length-1). */
374
+ function partialMarkerSuffix(buffer, marker) {
375
+ const max = Math.min(marker.length - 1, buffer.length)
376
+ for (let keep = max; keep > 0; keep -= 1) {
377
+ if (buffer.endsWith(marker.slice(0, keep))) return keep
378
+ }
379
+ return 0
380
+ }
381
+
382
+ /**
383
+ * Input normaliser placed between stdin and readline.
384
+ *
385
+ * It does three jobs that node:readline does not do for us:
386
+ * 1. bracketed paste (`ESC[200~` .. `ESC[201~`) is merged into one line so a
387
+ * multi-line paste cannot execute several turns; the hook receives
388
+ * `{ text, lines, chars, truncated }`;
389
+ * 2. in raw-terminal mode a lone ESC is recognised after a short hold and reported
390
+ * as an interrupt, instead of corrupting the next typed character;
391
+ * 3. in raw-terminal mode Ctrl+C (0x03) is reported as an interrupt and removed, so
392
+ * it works while readline is paused during a turn.
393
+ *
394
+ * It proxies setRawMode()/isTTY so readline can put the real terminal into raw mode
395
+ * even though its own input is this Transform.
396
+ *
397
+ * @param {{
398
+ * interactive?: boolean,
399
+ * onPaste?: (meta: { text: string, lines: number, chars: number, truncated: boolean }) => void,
400
+ * onInterrupt?: (kind: 'sigint'|'escape') => void,
401
+ * onActivity?: () => void,
402
+ * escapeDelay?: number,
403
+ * maxChars?: number,
404
+ * }} [options]
405
+ * @returns {Transform & { dispose: () => void, isTTY?: boolean, setRawMode?: (mode: boolean) => void }}
406
+ */
407
+ export function createPasteGuard(options = {}) {
408
+ const guard = new PasteGuard(options)
409
+ return guard
410
+ }
411
+
412
+ class PasteGuard extends Transform {
413
+ constructor({ interactive = true, onPaste = null, onInterrupt = null, onActivity = null, escapeDelay = ESCAPE_HOLD_MS, maxChars = PASTE_MAX_CHARS } = {}) {
414
+ super()
415
+ this.interactive = interactive !== false
416
+ this.pasteHook = typeof onPaste === 'function' ? onPaste : null
417
+ this.interruptHook = typeof onInterrupt === 'function' ? onInterrupt : null
418
+ this.activityHook = typeof onActivity === 'function' ? onActivity : null
419
+ this.escapeDelay = Number.isFinite(escapeDelay) ? Math.max(10, Math.floor(escapeDelay)) : ESCAPE_HOLD_MS
420
+ this.maxChars = Number.isFinite(maxChars) && maxChars > 0 ? Math.floor(maxChars) : PASTE_MAX_CHARS
421
+ this.decoder = new StringDecoder('utf8')
422
+ this.inPaste = false
423
+ this.pasteParts = []
424
+ this.pasteChars = 0
425
+ this.pasteNewlines = 0
426
+ this.pasteTruncated = false
427
+ this.hold = ''
428
+ this.holdTimer = null
429
+ this.disposed = false
430
+ this.isRaw = false
431
+ }
432
+
433
+ _transform(chunk, encoding, callback) {
434
+ let text
435
+ try {
436
+ text = this.decoder.write(chunk)
437
+ } catch (error) {
438
+ callback(error)
439
+ return
440
+ }
441
+ try {
442
+ this.consume(text)
443
+ callback()
444
+ } catch (error) {
445
+ callback(error)
446
+ }
447
+ }
448
+
449
+ _flush(callback) {
450
+ try {
451
+ this.consume(this.decoder.end())
452
+ this.flushHold()
453
+ callback()
454
+ } catch (error) {
455
+ callback(error)
456
+ }
457
+ }
458
+
459
+ dispose() {
460
+ this.disposed = true
461
+ this.clearHoldTimer()
462
+ this.hold = ''
463
+ this.pasteHook = null
464
+ this.interruptHook = null
465
+ this.activityHook = null
466
+ }
467
+
468
+ consume(text) {
469
+ if (this.disposed) return
470
+ if (text) this.emitActivity()
471
+ let buffer = this.hold + text
472
+ this.hold = ''
473
+ for (;;) {
474
+ if (this.inPaste) {
475
+ const endIndex = buffer.indexOf(PASTE_END)
476
+ if (endIndex !== -1) {
477
+ this.appendPaste(buffer.slice(0, endIndex))
478
+ buffer = buffer.slice(endIndex + PASTE_END.length)
479
+ this.finishPaste()
480
+ continue
481
+ }
482
+ const keep = partialMarkerSuffix(buffer, PASTE_END)
483
+ this.appendPaste(keep > 0 ? buffer.slice(0, buffer.length - keep) : buffer)
484
+ if (keep > 0) this.holdText(buffer.slice(buffer.length - keep))
485
+ return
486
+ }
487
+ const startIndex = buffer.indexOf(PASTE_START)
488
+ if (startIndex !== -1) {
489
+ this.plain(buffer.slice(0, startIndex))
490
+ buffer = buffer.slice(startIndex + PASTE_START.length)
491
+ this.inPaste = true
492
+ this.pasteParts = []
493
+ this.pasteChars = 0
494
+ this.pasteNewlines = 0
495
+ this.pasteTruncated = false
496
+ continue
497
+ }
498
+ const keep = partialMarkerSuffix(buffer, PASTE_START)
499
+ if (keep > 0) {
500
+ this.plain(buffer.slice(0, buffer.length - keep))
501
+ this.holdText(buffer.slice(buffer.length - keep))
502
+ } else {
503
+ this.plain(buffer)
504
+ }
505
+ return
506
+ }
507
+ }
508
+
509
+ plain(text) {
510
+ if (!text) return
511
+ let value = text
512
+ if (this.interactive) {
513
+ if (value.indexOf('\u0003') !== -1) {
514
+ value = value.split('\u0003').join('')
515
+ this.emitInterrupt('sigint')
516
+ }
517
+ if (value === '\u001b') {
518
+ this.emitInterrupt('escape')
519
+ return
520
+ }
521
+ }
522
+ if (!value) return
523
+ this.push(value)
524
+ }
525
+
526
+ appendPaste(segment) {
527
+ if (!segment) return
528
+ for (const char of segment) if (char === '\n') this.pasteNewlines += 1
529
+ if (this.pasteTruncated) return
530
+ const remaining = this.maxChars - this.pasteChars
531
+ if (remaining <= 0) {
532
+ this.pasteTruncated = true
533
+ return
534
+ }
535
+ if (segment.length > remaining) {
536
+ this.pasteParts.push(segment.slice(0, remaining))
537
+ this.pasteChars = this.maxChars
538
+ this.pasteTruncated = true
539
+ return
540
+ }
541
+ this.pasteParts.push(segment)
542
+ this.pasteChars += segment.length
543
+ }
544
+
545
+ finishPaste() {
546
+ const raw = this.pasteParts.join('')
547
+ const lines = raw === '' ? 0 : this.pasteNewlines + 1
548
+ const truncated = this.pasteTruncated
549
+ this.inPaste = false
550
+ this.pasteParts = []
551
+ this.pasteChars = 0
552
+ this.pasteNewlines = 0
553
+ this.pasteTruncated = false
554
+ const merged = mergePastedText(raw, { maxChars: this.maxChars })
555
+ const meta = {
556
+ text: merged.text,
557
+ lines: lines > 0 ? lines : merged.lines,
558
+ chars: merged.chars,
559
+ truncated: truncated || merged.truncated,
560
+ }
561
+ if (this.pasteHook) {
562
+ try {
563
+ this.pasteHook(meta)
564
+ } catch {}
565
+ }
566
+ if (merged.text) this.push(merged.text)
567
+ }
568
+
569
+ holdText(text) {
570
+ this.hold = text
571
+ this.clearHoldTimer()
572
+ this.holdTimer = setTimeout(() => {
573
+ this.holdTimer = null
574
+ this.flushHold()
575
+ }, this.escapeDelay)
576
+ if (this.holdTimer && typeof this.holdTimer.unref === 'function') this.holdTimer.unref()
577
+ }
578
+
579
+ flushHold() {
580
+ this.clearHoldTimer()
581
+ const held = this.hold
582
+ this.hold = ''
583
+ if (!held) return
584
+ if (this.inPaste) this.appendPaste(held)
585
+ else this.plain(held)
586
+ }
587
+
588
+ clearHoldTimer() {
589
+ if (this.holdTimer) {
590
+ clearTimeout(this.holdTimer)
591
+ this.holdTimer = null
592
+ }
593
+ }
594
+
595
+ emitActivity() {
596
+ if (!this.activityHook) return
597
+ try {
598
+ this.activityHook()
599
+ } catch {}
600
+ }
601
+
602
+ emitInterrupt(kind) {
603
+ if (!this.interruptHook) return
604
+ try {
605
+ this.interruptHook(kind)
606
+ } catch {}
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Run the Advisers 0.4.0 interactive shell.
612
+ *
613
+ * The caller owns the process: this function does not call process.exit(), does not
614
+ * touch the TOS gate/store/model and does not write to console.*; it only reads/writes
615
+ * the streams it was given. See the module header for the handler contract.
616
+ *
617
+ * @param {{
618
+ * argv?: string[],
619
+ * env?: Record<string, unknown>,
620
+ * stdin?: NodeJS.ReadableStream,
621
+ * stdout?: NodeJS.WritableStream,
622
+ * stderr?: NodeJS.WritableStream,
623
+ * store?: unknown,
624
+ * allowPaths?: string[],
625
+ * handlers?: Record<string, Function>,
626
+ * onState?: (transition: { from: string, to: string, reason: string }) => void,
627
+ * }} [options]
628
+ * @returns {Promise<Readonly<{ entered: boolean, exitCode: number, reason: string, turns: number }>>}
629
+ */
630
+ export async function runShell(options = {}) {
631
+ const opt = options && typeof options === 'object' ? options : {}
632
+ const argv = Array.isArray(opt.argv) ? opt.argv : []
633
+ const env = opt.env && typeof opt.env === 'object' ? opt.env : {}
634
+ const stdin = opt.stdin
635
+ const stdout = opt.stdout
636
+ const stderr = opt.stderr
637
+ const store = opt.store === undefined ? null : opt.store
638
+ const allowPaths = Array.isArray(opt.allowPaths) ? [...opt.allowPaths] : []
639
+ const handlers = opt.handlers && typeof opt.handlers === 'object' ? opt.handlers : {}
640
+ const onStateHook = typeof opt.onState === 'function' ? opt.onState : null
641
+
642
+ const stdinIsTTY = Boolean(stdin?.isTTY)
643
+ const stdoutIsTTY = Boolean(stdout?.isTTY)
644
+ const stderrIsTTY = Boolean(stderr?.isTTY)
645
+ const entry = shouldEnterShell({ argv, env, stdinIsTTY, stdoutIsTTY, stderrIsTTY })
646
+ if (!entry.enter) return Object.freeze({ entered: false, exitCode: entry.exitCode, reason: entry.reason, turns: 0 })
647
+
648
+ let policy
649
+ try {
650
+ policy = resolveOutputPolicy({ argv, env, stdinIsTTY, stdoutIsTTY, stderrIsTTY })
651
+ } catch {
652
+ return Object.freeze({ entered: false, exitCode: 1, reason: 'invalid-options', turns: 0 })
653
+ }
654
+ if (!stdin || typeof stdin.on !== 'function' || typeof stdin.pipe !== 'function' || !stdout || typeof stdout.write !== 'function' || !stderr || typeof stderr.write !== 'function') {
655
+ return Object.freeze({ entered: false, exitCode: 1, reason: 'invalid-streams', turns: 0 })
656
+ }
657
+
658
+ // Raw terminal (readline terminal:true) only when the policy keeps cursor control
659
+ // and the input is a terminal. --plain/--accessible/non-TTY stdout => canonical
660
+ // (terminal:false), which is the documented 0-ESC mode.
661
+ const terminal = stdinIsTTY && !policy.plain && !envFlag(env, 'ADVISERS_SHELL_CANONICAL')
662
+ // Where prompts, the status line and confirmation blocks go: stdout when it is a
663
+ // terminal, otherwise stderr (docs/TUI.md section 6: stdout stays pipe-clean).
664
+ const promptStream = stdoutIsTTY ? stdout : stderr
665
+ const uiStream = promptStream
666
+ const lineEnding = terminal ? '\r\n' : '\n'
667
+
668
+ let rl = null
669
+ let closed = false
670
+ let state = SHELL_STATES.IDLE
671
+ let exitReason = 'quit'
672
+ let exitCode = 0
673
+ let turns = 0
674
+ let lastFailure = null
675
+ let verbose = envFlag(env, 'ADVISERS_PROGRESS') || envFlag(env, 'ADVISERS_DEBUG')
676
+ let pendingFiles = []
677
+ let lastTurn = null
678
+ let pendingQuestion = null
679
+ let pendingPaste = null
680
+ let pendingConfirm = null
681
+ let lastSigintAt = 0
682
+ let activeAbort = null
683
+ const lineQueue = []
684
+ let lineWaiter = null
685
+
686
+ /** Re-read the width on every render (SIGWINCH safe, tests use the env override). */
687
+ function widthNow() {
688
+ return resolveShellWidth(stdout, env, argv)
689
+ }
690
+
691
+ function renderOptions(extra = {}) {
692
+ return {
693
+ width: widthNow(),
694
+ color: policy.color,
695
+ accessible: policy.accessible,
696
+ ...extra,
697
+ }
698
+ }
699
+
700
+ function writeLines(lines, stream = stdout) {
701
+ if (!stream || typeof stream.write !== 'function') return
702
+ const list = Array.isArray(lines) ? lines : [lines]
703
+ let payload = ''
704
+ for (const line of list) payload += sanitizeRenderedLine(line, { color: policy.color }) + lineEnding
705
+ if (payload) stream.write(payload)
706
+ }
707
+
708
+ function setState(next, reason = '') {
709
+ if (state === next) return
710
+ const from = state
711
+ state = next
712
+ if (onStateHook) {
713
+ try {
714
+ onStateHook({ from, to: next, reason })
715
+ } catch {}
716
+ }
717
+ }
718
+
719
+ function errorMessage(error) {
720
+ const raw = error && typeof error.message === 'string' && error.message !== '' ? error.message : String(error === undefined || error === null ? '未知错误' : error)
721
+ return sanitizeShellLine(raw).slice(0, 400)
722
+ }
723
+
724
+ function errorCode(error) {
725
+ return error && typeof error.code === 'string' ? error.code : undefined
726
+ }
727
+
728
+ function isCancellation(error) {
729
+ if (!error) return false
730
+ const code = typeof error.code === 'string' ? error.code : ''
731
+ return code === 'CANCELLED_BY_USER' || code === 'ABORT_ERR' || error.name === 'AbortError' || error.name === 'CanceledError'
732
+ }
733
+
734
+ function isBlockish(value) {
735
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
736
+ const keys = ['headline', 'summary', 'lines', 'artifacts', 'checks', 'warnings', 'next', 'prompt', 'tools', 'durationMs', 'title', 'reason', 'kept', 'code']
737
+ return keys.some((key) => value[key] !== undefined)
738
+ }
739
+
740
+ function resultBlock(value) {
741
+ const block = {}
742
+ if (value.headline !== undefined) block.headline = value.headline
743
+ if (value.summary !== undefined) block.summary = value.summary
744
+ else if (value.reply !== undefined) block.summary = value.reply
745
+ if (value.lines !== undefined) block.lines = value.lines
746
+ if (value.artifacts !== undefined) block.artifacts = value.artifacts
747
+ if (value.checks !== undefined) block.checks = value.checks
748
+ if (value.warnings !== undefined) block.warnings = value.warnings
749
+ if (value.next !== undefined) block.next = value.next
750
+ if (value.tools !== undefined) block.tools = value.tools
751
+ if (value.durationMs !== undefined) block.durationMs = value.durationMs
752
+ return block
753
+ }
754
+
755
+ function normalizeErrorBlock(value) {
756
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
757
+ return {
758
+ title: value.title ?? value.headline ?? value.what,
759
+ reason: value.reason ?? value.message,
760
+ kept: value.kept,
761
+ next: value.next,
762
+ code: value.code,
763
+ }
764
+ }
765
+ return { title: '操作失败', reason: String(value === undefined || value === null ? '未知错误' : value) }
766
+ }
767
+
768
+ function renderFailure(label, error) {
769
+ writeLines(renderError({
770
+ title: label,
771
+ reason: errorMessage(error),
772
+ next: '/retry 重试,或 /help 查看命令',
773
+ code: errorCode(error),
774
+ }, renderOptions()), stdout)
775
+ }
776
+
777
+ function renderInterrupted() {
778
+ writeLines(renderResult({
779
+ kind: 'notice',
780
+ headline: '已中断本轮',
781
+ summary: '结果没有保存;需要时用 /retry 重试。',
782
+ next: '/retry',
783
+ }, renderOptions()), stdout)
784
+ }
785
+
786
+ function renderSessions(sessions) {
787
+ const lines = []
788
+ for (let index = 0; index < sessions.length; index += 1) {
789
+ const session = sessions[index] && typeof sessions[index] === 'object' ? sessions[index] : {}
790
+ const number = session.n === undefined ? index + 1 : session.n
791
+ const title = session.title === undefined || session.title === null ? '(untitled)' : session.title
792
+ const id = session.id === undefined || session.id === null ? (session.conversationId ?? '') : session.id
793
+ lines.push({ role: 'item', text: String(number) + '. ' + String(title) + ' [' + String(id) + ']' })
794
+ }
795
+ writeLines(renderResult({
796
+ headline: '最近会话',
797
+ lines: lines.length > 0 ? lines : [{ role: 'fact', text: '(没有历史会话)' }],
798
+ next: '/resume <n|id> 恢复',
799
+ }, renderOptions({ maxItems: 100 })), stdout)
800
+ }
801
+
802
+ function renderHandlerOutcome(label, outcome) {
803
+ if (outcome.missing) {
804
+ writeLines(renderError({
805
+ title: '/' + label + ' 未接线',
806
+ reason: '当前构建没有接线这个只读视图。',
807
+ next: '在 CLI 里用 advisers ' + label,
808
+ }, renderOptions()), stdout)
809
+ return
810
+ }
811
+ if (!outcome.ok) {
812
+ renderFailure('/' + label + ' 失败', outcome.error)
813
+ return
814
+ }
815
+ const value = outcome.value
816
+ if (value === undefined || value === null) {
817
+ writeLines(renderResult({ kind: 'notice', headline: '完成' }, renderOptions()), stdout)
818
+ return
819
+ }
820
+ if (Array.isArray(value)) {
821
+ writeLines(renderResult({ lines: value }, renderOptions({ maxItems: 60 })), stdout)
822
+ return
823
+ }
824
+ if (typeof value === 'string') {
825
+ writeLines(renderResult({ summary: value }, renderOptions()), stdout)
826
+ return
827
+ }
828
+ if (value.error !== undefined && value.error !== null) {
829
+ writeLines(renderError(normalizeErrorBlock(value.error), renderOptions()), stdout)
830
+ return
831
+ }
832
+ if (value.kind === 'error') {
833
+ writeLines(renderError(normalizeErrorBlock(value), renderOptions()), stdout)
834
+ return
835
+ }
836
+ if (value.kind === 'confirm') {
837
+ writeLines(renderConfirm(value, renderOptions()), stdout)
838
+ return
839
+ }
840
+ if (Array.isArray(value.sessions)) {
841
+ renderSessions(value.sessions)
842
+ return
843
+ }
844
+ if (isBlockish(value)) {
845
+ writeLines(renderResult(resultBlock(value), renderOptions({ maxItems: 60 })), stdout)
846
+ return
847
+ }
848
+ writeLines(renderResult({ kind: 'notice', headline: '完成' }, renderOptions()), stdout)
849
+ }
850
+
851
+ function renderTurnOutcome(value) {
852
+ if (value === undefined || value === null) return
853
+ if (typeof value === 'string') {
854
+ writeLines(renderResult({ summary: value }, renderOptions()), stdout)
855
+ return
856
+ }
857
+ if (Array.isArray(value)) {
858
+ writeLines(renderResult({ lines: value }, renderOptions({ maxItems: 40 })), stdout)
859
+ return
860
+ }
861
+ if (value.interrupted === true) {
862
+ renderInterrupted()
863
+ return
864
+ }
865
+ if (value.error !== undefined && value.error !== null) {
866
+ writeLines(renderError(normalizeErrorBlock(value.error), renderOptions()), stdout)
867
+ return
868
+ }
869
+ if (value.kind === 'error') {
870
+ writeLines(renderError(normalizeErrorBlock(value), renderOptions()), stdout)
871
+ return
872
+ }
873
+ if (value.kind === 'confirm') {
874
+ writeLines(renderConfirm(value, renderOptions()), stdout)
875
+ return
876
+ }
877
+ if (value.kind === 'notice') {
878
+ writeLines(renderResult(value, renderOptions()), stdout)
879
+ return
880
+ }
881
+ const block = resultBlock(value)
882
+ writeLines(renderResult(block, renderOptions(verbose ? { verbose: true } : {})), stdout)
883
+ if (verbose && Array.isArray(value.internal)) {
884
+ writeLines(value.internal.map((line) => ' \u00b7 ' + sanitizeShellLine(line)), stdout)
885
+ }
886
+ if (typeof value.question === 'string' && value.question.trim() !== '') {
887
+ pendingQuestion = value.question.trim()
888
+ writeLines(renderResult({
889
+ kind: 'notice',
890
+ headline: '需要补充',
891
+ summary: pendingQuestion,
892
+ next: '直接回答;/retry 重试上一轮',
893
+ }, renderOptions()), stdout)
894
+ }
895
+ }
896
+
897
+ async function callHandler(name, payload = {}) {
898
+ const fn = handlers[name]
899
+ if (typeof fn !== 'function') return { ok: false, missing: true }
900
+ try {
901
+ return { ok: true, value: await fn(payload, ctx) }
902
+ } catch (error) {
903
+ return { ok: false, error }
904
+ }
905
+ }
906
+
907
+ const ctx = Object.freeze({
908
+ env,
909
+ store,
910
+ allowPaths: Object.freeze([...allowPaths]),
911
+ stdout,
912
+ stderr,
913
+ ui: uiStream,
914
+ width: () => widthNow(),
915
+ policy,
916
+ terminal,
917
+ })
918
+
919
+ async function renderIdleStatus() {
920
+ let data = {}
921
+ if (!lastFailure) {
922
+ const outcome = await callHandler('status')
923
+ if (outcome.ok && outcome.value && typeof outcome.value === 'object' && !Array.isArray(outcome.value)) data = outcome.value
924
+ }
925
+ const status = { ...data }
926
+ if (lastFailure) {
927
+ status.kind = 'error'
928
+ status.reason = lastFailure
929
+ } else if (status.kind === undefined) {
930
+ status.kind = 'idle'
931
+ }
932
+ writeLines([renderStatus(status, renderOptions())], uiStream)
933
+ }
934
+
935
+ function createConfirm() {
936
+ return async (request = {}) => {
937
+ const value = request && typeof request === 'object' ? request : {}
938
+ writeLines(renderConfirm({
939
+ title: value.title === undefined ? (value.what === undefined ? (value.path ? '覆盖写入' : '继续操作') : value.what) : value.title,
940
+ reason: value.reason,
941
+ write: value.write === undefined ? value.path : value.write,
942
+ summary: value.summary,
943
+ digest: value.digest,
944
+ prompt: value.prompt,
945
+ }, renderOptions()), uiStream)
946
+ setState(SHELL_STATES.CONFIRM, 'confirm')
947
+ try { rl.resume() } catch {}
948
+ try { rl.prompt() } catch {}
949
+ const answer = await new Promise((resolve) => {
950
+ pendingConfirm = (line) => {
951
+ pendingConfirm = null
952
+ resolve(line)
953
+ }
954
+ })
955
+ setState(SHELL_STATES.WORKING, 'confirm-answered')
956
+ try { rl.pause() } catch {}
957
+ return answer !== CANCEL && answer !== EOF && isAffirmativeAnswer(answer)
958
+ }
959
+ }
960
+
961
+ async function runTurn(text, turnOptions = {}) {
962
+ const attachments = turnOptions.attachments === undefined ? pendingFiles : turnOptions.attachments
963
+ const answerTo = turnOptions.answerTo === undefined ? null : turnOptions.answerTo
964
+ const fn = handlers.turn
965
+ if (typeof fn !== 'function') {
966
+ writeLines(renderError({
967
+ title: '对话未接线',
968
+ reason: '当前构建没有提供 turn handler。',
969
+ next: '使用 advisers --help 查看 CLI 命令',
970
+ }, renderOptions()), stdout)
971
+ return false
972
+ }
973
+ const files = Array.isArray(attachments) ? [...attachments] : []
974
+ const controller = new AbortController()
975
+ const payload = {
976
+ text: String(text === undefined || text === null ? '' : text),
977
+ attachments: files,
978
+ allowPaths: [...allowPaths],
979
+ signal: controller.signal,
980
+ confirm: createConfirm(),
981
+ answerTo,
982
+ store,
983
+ }
984
+ if (answerTo === null) lastTurn = { text: payload.text, attachments: files }
985
+ activeAbort = controller
986
+ turns += 1
987
+ setState(SHELL_STATES.WORKING, 'turn')
988
+ writeLines([renderStatus({ kind: 'busy' }, renderOptions())], uiStream)
989
+ try { rl.pause() } catch {}
990
+ let outcome
991
+ try {
992
+ outcome = { ok: true, value: await fn(payload, ctx) }
993
+ } catch (error) {
994
+ outcome = { ok: false, error }
995
+ } finally {
996
+ activeAbort = null
997
+ }
998
+ const cancelled = controller.signal.aborted
999
+ || (outcome.ok === false && isCancellation(outcome.error))
1000
+ || (outcome.ok === true && outcome.value !== null && typeof outcome.value === 'object' && outcome.value.interrupted === true)
1001
+ let success = false
1002
+ if (cancelled) {
1003
+ lastFailure = null
1004
+ renderInterrupted()
1005
+ } else if (!outcome.ok) {
1006
+ lastFailure = errorMessage(outcome.error)
1007
+ writeLines(renderError({
1008
+ title: '任务失败',
1009
+ reason: lastFailure,
1010
+ kept: '任务和会话;没有丢文件',
1011
+ next: '/retry 重试',
1012
+ code: errorCode(outcome.error),
1013
+ }, renderOptions()), stdout)
1014
+ } else {
1015
+ lastFailure = null
1016
+ success = true
1017
+ renderTurnOutcome(outcome.value)
1018
+ }
1019
+ setState(SHELL_STATES.IDLE, 'turn-done')
1020
+ await renderIdleStatus()
1021
+ return success
1022
+ }
1023
+
1024
+ async function commandStatus() {
1025
+ const outcome = await callHandler('status')
1026
+ if (outcome.missing) {
1027
+ renderHandlerOutcome('status', outcome)
1028
+ return
1029
+ }
1030
+ if (!outcome.ok) {
1031
+ renderFailure('/status 失败', outcome.error)
1032
+ return
1033
+ }
1034
+ const value = outcome.value
1035
+ if (value === undefined || value === null) {
1036
+ writeLines([renderStatus({ kind: 'idle' }, renderOptions())], stdout)
1037
+ return
1038
+ }
1039
+ if (isBlockish(value)) {
1040
+ renderHandlerOutcome('status', outcome)
1041
+ return
1042
+ }
1043
+ const status = { ...value }
1044
+ if (status.kind === undefined) status.kind = 'idle'
1045
+ writeLines([renderStatus(status, renderOptions())], stdout)
1046
+ }
1047
+
1048
+ async function commandReadOnly(name, payload) {
1049
+ const outcome = await callHandler(name, payload)
1050
+ renderHandlerOutcome(name, outcome)
1051
+ }
1052
+
1053
+ async function commandResume(arg) {
1054
+ if (!arg) {
1055
+ writeLines(renderError({ title: '用法', reason: '/resume <编号|会话 id>', next: '/history 查看编号' }, renderOptions()), stdout)
1056
+ return
1057
+ }
1058
+ const outcome = await callHandler('resume', { arg, args: [arg] })
1059
+ renderHandlerOutcome('resume', outcome)
1060
+ const failed = !outcome.ok || (outcome.value && typeof outcome.value === 'object' && (outcome.value.error || outcome.value.kind === 'error'))
1061
+ if (!failed) pendingFiles = []
1062
+ }
1063
+
1064
+ async function commandNew() {
1065
+ const outcome = await callHandler('newSession')
1066
+ if (outcome.missing) {
1067
+ writeLines(renderResult({
1068
+ kind: 'notice',
1069
+ headline: '新会话',
1070
+ summary: '当前构建没有接线 newSession;下一条消息仍写在当前会话。',
1071
+ next: 'advisers --help 查看 CLI 的会话命令',
1072
+ }, renderOptions()), stdout)
1073
+ return
1074
+ }
1075
+ renderHandlerOutcome('new', outcome)
1076
+ if (outcome.ok) {
1077
+ pendingFiles = []
1078
+ pendingQuestion = null
1079
+ }
1080
+ }
1081
+
1082
+ function commandAttach(arg) {
1083
+ const path = typeof arg === 'string' ? arg.trim() : ''
1084
+ if (!path) {
1085
+ writeLines(renderError({ title: '用法', reason: '/file <path>', next: '把文件放到工作区后重试' }, renderOptions()), stdout)
1086
+ return
1087
+ }
1088
+ pendingFiles.push(path)
1089
+ writeLines(renderResult({
1090
+ kind: 'notice',
1091
+ headline: '已附加',
1092
+ summary: path,
1093
+ next: String(pendingFiles.length) + ' 个待发送附件;/files 查看,/clear 清空',
1094
+ }, renderOptions()), stdout)
1095
+ }
1096
+
1097
+ function commandFiles() {
1098
+ if (pendingFiles.length === 0) {
1099
+ writeLines(renderResult({ kind: 'notice', headline: '没有待发送附件' }, renderOptions()), stdout)
1100
+ return
1101
+ }
1102
+ writeLines(renderResult({
1103
+ headline: '待发送附件',
1104
+ lines: pendingFiles.map((path) => ({ role: 'item', text: path })),
1105
+ next: '/clear 清空',
1106
+ }, renderOptions({ maxItems: 40 })), stdout)
1107
+ }
1108
+
1109
+ async function commandRetry() {
1110
+ if (!lastTurn) {
1111
+ writeLines(renderResult({ kind: 'notice', headline: '没有可重试的上一轮' }, renderOptions()), stdout)
1112
+ return
1113
+ }
1114
+ await runTurn(lastTurn.text, { attachments: lastTurn.attachments })
1115
+ }
1116
+
1117
+ async function commandLegacy(command) {
1118
+ const outcome = await callHandler('legacyCommand', { line: command.line, name: command.name, args: command.args, arg: command.arg })
1119
+ const unhandled = outcome.missing || (outcome.ok && (outcome.value === undefined || outcome.value === null || outcome.value === false))
1120
+ if (unhandled) {
1121
+ writeLines(renderError({
1122
+ title: '未知命令:' + command.name,
1123
+ reason: '壳里没有这个命令。',
1124
+ next: '/help 核心命令;/more 旧命令;以空格或 // 开头可发送以 / 开头的文本',
1125
+ }, renderOptions()), stdout)
1126
+ return
1127
+ }
1128
+ renderHandlerOutcome(command.name.replace(/^\//, ''), outcome)
1129
+ }
1130
+
1131
+ async function dispatchCommand(command) {
1132
+ switch (command.name) {
1133
+ case '/help':
1134
+ writeLines(renderResult(shellHelpBlock(), renderOptions({ maxItems: 20 })), stdout)
1135
+ return
1136
+ case '/more':
1137
+ writeLines(renderResult(shellMoreBlock(), renderOptions({ maxItems: 100 })), stdout)
1138
+ return
1139
+ case '/status':
1140
+ await commandStatus()
1141
+ return
1142
+ case '/verbose':
1143
+ verbose = !verbose
1144
+ writeLines(renderResult({
1145
+ kind: 'notice',
1146
+ headline: verbose ? '明细已开启' : '明细已关闭',
1147
+ summary: verbose ? '工具/耗时/内部行会显示在结果块里。' : undefined,
1148
+ }, renderOptions()), stdout)
1149
+ return
1150
+ case '/history':
1151
+ await commandReadOnly('history', { args: command.args, arg: command.arg })
1152
+ return
1153
+ case '/resume':
1154
+ await commandResume(command.arg)
1155
+ return
1156
+ case '/new':
1157
+ await commandNew()
1158
+ return
1159
+ case '/file':
1160
+ commandAttach(command.arg)
1161
+ return
1162
+ case '/files':
1163
+ commandFiles()
1164
+ return
1165
+ case '/clear':
1166
+ pendingFiles = []
1167
+ writeLines(renderResult({ kind: 'notice', headline: '附件已清空' }, renderOptions()), stdout)
1168
+ return
1169
+ case '/retry':
1170
+ await commandRetry()
1171
+ return
1172
+ case '/today':
1173
+ case '/remind':
1174
+ case '/who':
1175
+ case '/client':
1176
+ case '/evidence':
1177
+ await commandReadOnly(command.name.slice(1), { args: command.args, arg: command.arg })
1178
+ return
1179
+ default:
1180
+ await commandLegacy(command)
1181
+ }
1182
+ }
1183
+
1184
+ async function processLine(rawLine) {
1185
+ const parsed = parseShellLine(rawLine)
1186
+ if (parsed.kind === 'empty') return
1187
+ try { rl.pause() } catch {}
1188
+ setState(SHELL_STATES.IDLE, 'line')
1189
+ try {
1190
+ if (parsed.kind === 'command') {
1191
+ if (parsed.name === '/quit' || parsed.name === '/exit') {
1192
+ requestExit('quit', 0)
1193
+ return
1194
+ }
1195
+ await dispatchCommand(parsed)
1196
+ return
1197
+ }
1198
+ let text = parsed.text
1199
+ let answerTo = null
1200
+ if (pendingQuestion !== null) {
1201
+ answerTo = pendingQuestion
1202
+ pendingQuestion = null
1203
+ if (typeof handlers.answer === 'function') {
1204
+ const outcome = await callHandler('answer', { question: answerTo, answer: parsed.text, text: lastTurn ? lastTurn.text : '' })
1205
+ renderHandlerOutcome('answer', outcome)
1206
+ return
1207
+ }
1208
+ text = (lastTurn && lastTurn.text ? lastTurn.text + '\n' : '') + '补充:' + parsed.text
1209
+ }
1210
+ const ok = await runTurn(text, { answerTo })
1211
+ if (ok && answerTo === null) pendingFiles = []
1212
+ } catch (error) {
1213
+ writeLines(renderError({
1214
+ title: '壳命令失败',
1215
+ reason: errorMessage(error),
1216
+ next: '/help 或 /quit',
1217
+ code: errorCode(error),
1218
+ }, renderOptions()), stderr)
1219
+ }
1220
+ }
1221
+
1222
+ function nextLine() {
1223
+ if (lineQueue.length > 0) return Promise.resolve(lineQueue.shift())
1224
+ if (closed) return Promise.resolve(EOF)
1225
+ return new Promise((resolve) => {
1226
+ lineWaiter = resolve
1227
+ })
1228
+ }
1229
+
1230
+ function routeLine(line) {
1231
+ if (pendingConfirm) {
1232
+ const resolve = pendingConfirm
1233
+ pendingConfirm = null
1234
+ resolve(line)
1235
+ return
1236
+ }
1237
+ if (lineWaiter) {
1238
+ const resolve = lineWaiter
1239
+ lineWaiter = null
1240
+ resolve(line)
1241
+ return
1242
+ }
1243
+ lineQueue.push(line)
1244
+ }
1245
+
1246
+ function handleInterrupt(kind) {
1247
+ if (state === SHELL_STATES.CONFIRM) {
1248
+ if (pendingConfirm) {
1249
+ const resolve = pendingConfirm
1250
+ pendingConfirm = null
1251
+ resolve(CANCEL)
1252
+ }
1253
+ return
1254
+ }
1255
+ if (state === SHELL_STATES.WORKING || state === SHELL_STATES.QUEUED) {
1256
+ if (activeAbort && !activeAbort.signal.aborted) {
1257
+ try { activeAbort.abort() } catch {}
1258
+ }
1259
+ return
1260
+ }
1261
+ if (kind !== 'sigint') return
1262
+ const now = Date.now()
1263
+ if (now - lastSigintAt <= SIGINT_WINDOW_MS) {
1264
+ requestExit('sigint', 0)
1265
+ return
1266
+ }
1267
+ lastSigintAt = now
1268
+ showIdleSigintHint()
1269
+ }
1270
+
1271
+ function showIdleSigintHint() {
1272
+ if (closed) return
1273
+ try {
1274
+ rl.line = ''
1275
+ rl.cursor = 0
1276
+ } catch {}
1277
+ const hint = sanitizeShellLine('(再按一次 Ctrl+C 退出;或输入 /quit)')
1278
+ try {
1279
+ if (terminal) promptStream.write('\r\n' + hint + '\r\n')
1280
+ else promptStream.write('\n' + hint + '\n')
1281
+ } catch {}
1282
+ try { rl.prompt() } catch {}
1283
+ }
1284
+
1285
+ function requestExit(reason, code = 0) {
1286
+ if (closed) return
1287
+ exitReason = reason
1288
+ exitCode = code
1289
+ closed = true
1290
+ if (lineWaiter) {
1291
+ const resolve = lineWaiter
1292
+ lineWaiter = null
1293
+ resolve(EOF)
1294
+ }
1295
+ if (pendingConfirm) {
1296
+ const resolve = pendingConfirm
1297
+ pendingConfirm = null
1298
+ resolve(CANCEL)
1299
+ }
1300
+ try { rl.close() } catch {}
1301
+ }
1302
+
1303
+ function cleanup() {
1304
+ pendingConfirm = null
1305
+ lineWaiter = null
1306
+ try { if (activeAbort && !activeAbort.signal.aborted) activeAbort.abort() } catch {}
1307
+ try { if (rl && !rl.closed) rl.close() } catch {}
1308
+ try { if (typeof stdin.unpipe === 'function') stdin.unpipe(guard) } catch {}
1309
+ try { guard.dispose() } catch {}
1310
+ try { process.off('SIGINT', onProcessSigint) } catch {}
1311
+ }
1312
+
1313
+ const guard = createPasteGuard({
1314
+ interactive: terminal,
1315
+ onPaste: (meta) => { pendingPaste = meta },
1316
+ onInterrupt: (kind) => handleInterrupt(kind),
1317
+ onActivity: () => {
1318
+ if (state === SHELL_STATES.WORKING || state === SHELL_STATES.QUEUED) setState(SHELL_STATES.QUEUED, 'input-buffered')
1319
+ },
1320
+ })
1321
+ guard.isTTY = stdinIsTTY
1322
+ guard.isRaw = false
1323
+ guard.setRawMode = (mode) => {
1324
+ guard.isRaw = Boolean(mode)
1325
+ try { if (typeof stdin.setRawMode === 'function') stdin.setRawMode(mode) } catch {}
1326
+ }
1327
+ stdin.pipe(guard)
1328
+
1329
+ rl = readline.createInterface({
1330
+ input: guard,
1331
+ output: promptStream,
1332
+ terminal,
1333
+ historySize: 200,
1334
+ removeHistoryDuplicates: true,
1335
+ completer: createCommandCompleter(),
1336
+ })
1337
+ rl.setPrompt(SHELL_PROMPT)
1338
+ rl.on('line', routeLine)
1339
+ rl.on('close', () => {
1340
+ if (!closed) {
1341
+ exitReason = 'eof'
1342
+ exitCode = 0
1343
+ }
1344
+ closed = true
1345
+ if (pendingConfirm) {
1346
+ const resolve = pendingConfirm
1347
+ pendingConfirm = null
1348
+ resolve(EOF)
1349
+ }
1350
+ if (lineWaiter) {
1351
+ const resolve = lineWaiter
1352
+ lineWaiter = null
1353
+ resolve(EOF)
1354
+ }
1355
+ if (activeAbort && !activeAbort.signal.aborted) {
1356
+ try { activeAbort.abort() } catch {}
1357
+ }
1358
+ })
1359
+
1360
+ const onProcessSigint = () => handleInterrupt('sigint')
1361
+ const ownsProcessStdin = stdin === process.stdin
1362
+ if (ownsProcessStdin) process.on('SIGINT', onProcessSigint)
1363
+
1364
+ try {
1365
+ if (!stdoutIsTTY) writeLines(['advisers: 输出不是终端,提示与状态改到 stderr;结果在 stdout'], stderr)
1366
+ await renderIdleStatus()
1367
+ if (!envFlag(env, 'ADVISERS_SHELL_NO_OPENING')) {
1368
+ const opening = await callHandler('opening')
1369
+ if (opening.ok && opening.value !== undefined && opening.value !== null && opening.value !== false) {
1370
+ renderHandlerOutcome('opening', opening)
1371
+ }
1372
+ }
1373
+ try { rl.prompt() } catch {}
1374
+ while (!closed) {
1375
+ const line = await nextLine()
1376
+ if (line === EOF || line === CANCEL) break
1377
+ if (closed) break
1378
+ const paste = pendingPaste
1379
+ pendingPaste = null
1380
+ if (paste && (paste.lines > 1 || paste.truncated)) {
1381
+ const notice = paste.truncated
1382
+ ? '已合并 ' + String(paste.lines) + ' 行粘贴为一条输入(超过 ' + String(PASTE_MAX_CHARS) + ' 字,已截断)'
1383
+ : '已合并 ' + String(paste.lines) + ' 行粘贴为一条输入'
1384
+ writeLines(renderResult({ kind: 'notice', headline: notice }, renderOptions()), stdout)
1385
+ }
1386
+ await processLine(line)
1387
+ if (closed) break
1388
+ setState(SHELL_STATES.IDLE, 'prompt')
1389
+ try { rl.resume() } catch {}
1390
+ try { rl.prompt() } catch {}
1391
+ }
1392
+ } catch (error) {
1393
+ writeLines(renderError({
1394
+ title: '交互壳异常',
1395
+ reason: errorMessage(error),
1396
+ next: 'advisers --help',
1397
+ code: errorCode(error),
1398
+ }, renderOptions()), stderr)
1399
+ exitReason = 'error'
1400
+ exitCode = 1
1401
+ } finally {
1402
+ cleanup()
1403
+ }
1404
+
1405
+ return Object.freeze({ entered: true, exitCode, reason: exitReason, turns })
1406
+ }