advisers 0.2.3 → 0.3.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 (70) hide show
  1. package/LICENSE +0 -0
  2. package/NOTICE +0 -0
  3. package/README-zh.md +10 -6
  4. package/README.md +15 -6
  5. package/THIRD-PARTY-NOTICES.md +1 -1
  6. package/bin/advisers.js +3323 -222
  7. package/index.js +1 -1
  8. package/lib/agent.js +0 -0
  9. package/lib/attachments.js +0 -0
  10. package/lib/audit-anchor.js +683 -0
  11. package/lib/backup.js +1345 -0
  12. package/lib/capture.js +0 -0
  13. package/lib/context-window.js +0 -0
  14. package/lib/digest.js +0 -0
  15. package/lib/doc-review.js +0 -0
  16. package/lib/egress.js +0 -0
  17. package/lib/error-codes.js +1373 -0
  18. package/lib/evidence.js +202 -26
  19. package/lib/fs-safe.js +70 -7
  20. package/lib/ical.js +0 -0
  21. package/lib/imap.js +6 -2
  22. package/lib/importers.js +0 -0
  23. package/lib/learning.js +0 -0
  24. package/lib/ledger-read.js +608 -0
  25. package/lib/mcp-server.js +294 -38
  26. package/lib/model.js +0 -0
  27. package/lib/node-warning-filter.js +15 -0
  28. package/lib/notify.js +13 -3
  29. package/lib/nudge.js +0 -0
  30. package/lib/ocr.js +0 -0
  31. package/lib/pdf.js +0 -0
  32. package/lib/pet-brief-store.js +0 -0
  33. package/lib/pet-brief.js +102 -39
  34. package/lib/receipt-verify.js +213 -15
  35. package/lib/relative-date.js +0 -0
  36. package/lib/remind.js +91 -36
  37. package/lib/research.js +0 -0
  38. package/lib/review.js +0 -0
  39. package/lib/routine.js +0 -0
  40. package/lib/safety/classifier.js +0 -0
  41. package/lib/safety/explain.js +0 -0
  42. package/lib/safety/index.js +0 -0
  43. package/lib/safety/redact.js +0 -0
  44. package/lib/safety/rules.js +0 -0
  45. package/lib/scheduler.js +0 -0
  46. package/lib/source.js +0 -0
  47. package/lib/sqlite.js +1214 -24
  48. package/lib/sync.js +0 -0
  49. package/lib/text-safe.js +229 -0
  50. package/lib/timestamp.js +0 -0
  51. package/lib/tos/index.js +1 -1
  52. package/lib/tos/manifest.json +6 -6
  53. package/lib/tos/privacy.zh-CN.md +12 -9
  54. package/lib/tos/safety.zh-CN.md +4 -3
  55. package/lib/tos/summary.zh-CN.md +3 -3
  56. package/lib/tos/terms.zh-CN.md +8 -6
  57. package/lib/tui/color.js +164 -0
  58. package/lib/tui/index.js +33 -0
  59. package/lib/tui/json.js +124 -0
  60. package/lib/tui/labels.js +50 -0
  61. package/lib/tui/policy.js +108 -0
  62. package/lib/tui/render.js +371 -0
  63. package/lib/tui/sanitize.js +142 -0
  64. package/lib/tui/text-file.js +116 -0
  65. package/lib/tui/width.js +577 -0
  66. package/lib/ui.js +0 -0
  67. package/lib/undo.js +0 -0
  68. package/lib/untrusted.js +0 -0
  69. package/lib/vault.js +0 -0
  70. package/package.json +6 -5
package/lib/mcp-server.js CHANGED
@@ -27,15 +27,66 @@
27
27
  import { lstatSync, readFileSync, readdirSync, statSync } from 'node:fs'
28
28
  import { join, resolve } from 'node:path'
29
29
  import { StringDecoder } from 'node:string_decoder'
30
- import { evidenceForCommitment, evidenceForFact, evidenceForPreference, verifyPack } from './evidence.js'
30
+ import {
31
+ evidenceForCommitment,
32
+ evidenceForFact,
33
+ evidenceForPreference,
34
+ isEvidenceRecordAboveClearance,
35
+ verifyPack,
36
+ } from './evidence.js'
31
37
  import { buildReminders } from './remind.js'
32
38
  import { inspectCaptureText } from './capture.js'
33
39
  import { classify, redact, safetyErrorFrom } from './safety/index.js'
34
40
 
41
+ /**
42
+ * Default MCP protocol version. Legacy clients that send no version (or an
43
+ * unknown one) keep getting 2024-11-05, i.e. the pre-0.3.0 behaviour.
44
+ */
35
45
  export const PROTOCOL_VERSION = '2024-11-05'
46
+ /**
47
+ * Legacy protocol versions negotiated by `initialize` (0.3.0 P0-T3).
48
+ *
49
+ * The 2025-06-18 / 2025-11-25 revisions keep the same initialize/tools/
50
+ * resources lifecycle this server implements, so echoing the client's
51
+ * supported version is safe; anything else (including the stateless
52
+ * 2026-07-28 modern revision, which needs server/discover) falls back to
53
+ * PROTOCOL_VERSION. The modern revisions are NOT implemented here: this
54
+ * server deliberately does not advertise server/discover, so a modern client
55
+ * probes once, gets an unknown-method error, and falls back to initialize.
56
+ */
57
+ export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(['2024-11-05', '2025-06-18', '2025-11-25'])
36
58
  export const SERVER_NAME = 'advisers'
37
59
  /** Hard cap for one stdio JSON-RPC line (bytes). */
38
60
  export const MAX_LINE_BYTES = 1024 * 1024
61
+ /**
62
+ * Output caps for every list-shaped tool result (0.3.0 P0-T3 / S2).
63
+ *
64
+ * The content-safety classifier fail-closes any mcp.tool egress surface above
65
+ * 100k characters (lib/safety/classifier.js MAX_SCAN_CHARS), so an unbounded
66
+ * ledger listing used to turn advisers_today/commit_ls/remind into
67
+ * CONTENT_BLOCKED errors on a large ledger. Every read model now truncates
68
+ * AFTER the per-item clearance filter and BEFORE the classifier runs, and
69
+ * reports the true post-filter count in `total`/`mineTotal`/`waitingTotal`
70
+ * with `truncated: true`. Small ledgers are byte-for-byte unchanged.
71
+ */
72
+ export const MCP_OUTPUT_LIMITS = Object.freeze({
73
+ todayCommitments: 20,
74
+ commitRows: 50,
75
+ commitRowsMax: 200,
76
+ whoRows: 20,
77
+ reminders: 20,
78
+ evidenceItems: 20,
79
+ })
80
+ /**
81
+ * Last-resort byte budget for one tool/resource payload. The per-tool row caps
82
+ * keep every normal result far below this, but a single commitment with a huge
83
+ * evidence array could still push a list over the classifier's 100k-character
84
+ * fail-closed threshold. When that happens the longest list is halved (and
85
+ * marked truncated) until the serialized payload fits, so the egress
86
+ * classifier never turns a large ledger into CONTENT_BLOCKED.
87
+ */
88
+ export const MCP_MAX_RESULT_BYTES = 64 * 1024
89
+ const PAYLOAD_LIST_KEYS = Object.freeze(['commitments', 'mine', 'waiting', 'reminders', 'sources', 'missing'])
39
90
  /** Receipt directories are small; refuse to slurp anything huge. */
40
91
  export const MAX_PACK_FILE_BYTES = 512 * 1024
41
92
  export const MAX_PACK_SUMS_BYTES = 64 * 1024
@@ -68,7 +119,7 @@ const RESOURCE_DEFINITIONS = Object.freeze([
68
119
  {
69
120
  uri: 'advisers://today',
70
121
  name: 'today',
71
- description: 'Open commitments and their count (same shape as advisers_today).',
122
+ description: 'Open commitments and their count (same shape as advisers_today; protected matters excluded at the server clearance).',
72
123
  mimeType: 'application/json',
73
124
  },
74
125
  {
@@ -176,6 +227,30 @@ function safeJson(value) {
176
227
  }
177
228
  }
178
229
 
230
+ /**
231
+ * Enforce MCP_MAX_RESULT_BYTES on a list-shaped payload, trimming the longest
232
+ * array until it fits and marking the result truncated (the total fields stay
233
+ * the true post-clearance counts). Non-list payloads are returned unchanged.
234
+ */
235
+ function boundPayload(data) {
236
+ if (Buffer.byteLength(safeJson(data), 'utf8') <= MCP_MAX_RESULT_BYTES) return data
237
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return data
238
+ const trimmed = { ...data }
239
+ for (;;) {
240
+ if (Buffer.byteLength(safeJson(trimmed), 'utf8') <= MCP_MAX_RESULT_BYTES) break
241
+ let target = null
242
+ for (const key of PAYLOAD_LIST_KEYS) {
243
+ const list = trimmed[key]
244
+ if (!Array.isArray(list) || list.length === 0) continue
245
+ if (target === null || list.length > trimmed[target].length) target = key
246
+ }
247
+ if (target === null) break
248
+ trimmed[target] = trimmed[target].slice(0, Math.floor(trimmed[target].length / 2))
249
+ trimmed.truncated = true
250
+ }
251
+ return trimmed
252
+ }
253
+
179
254
  /** Structured CONTENT_BLOCKED tool result: isError=true, no original text. */
180
255
  function toolBlocked(id, error) {
181
256
  const payload = {
@@ -242,6 +317,16 @@ function optionalBoolean(args, key) {
242
317
  return value
243
318
  }
244
319
 
320
+ /** Optional 1..max integer row limit (undefined keeps the tool default). */
321
+ function optionalLimit(args, key, max) {
322
+ const value = args[key]
323
+ if (value === undefined || value === null) return undefined
324
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > max) {
325
+ throw invalidParams(key + ' must be an integer between 1 and ' + max)
326
+ }
327
+ return value
328
+ }
329
+
245
330
  const ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/
246
331
 
247
332
  function optionalIsoDate(args, key) {
@@ -366,10 +451,21 @@ export function readReceiptDirectory(dir) {
366
451
  * @param {Function} [options.audit] Audit sink: ({actor, action, allowed, reason}) => unknown.
367
452
  * @param {Function} [options.readPack] Injectable receipt-directory reader returns {files, receiptPresent, extraFileCount}; defaults to readReceiptDirectory.
368
453
  * @param {Function|Date} [options.now] Clock used by reminders (defaults to new Date()).
454
+ * @param {number} [options.clearance=0] Read clearance of this MCP surface
455
+ * (0.2.5 A-2). Every read model excludes records whose matter secrecy is
456
+ * above it and reports `protectedExcluded`; 0 (fail closed) is the
457
+ * default and a client cannot raise it through a tool argument.
369
458
  * @returns {{protocolVersion: string, handle: Function, handleLine: Function, serve: Function, tools: Function, resources: Function}}
370
459
  */
371
- export function createMcpServer({ store, ledger, loadLedger, loadStore, version = '0.0.0', audit, readPack, now = () => new Date() } = {}) {
460
+ export function createMcpServer({ store, ledger, loadLedger, loadStore, version = '0.0.0', audit, readPack, now = () => new Date(), clearance = 0 } = {}) {
372
461
  const serverVersion = String(version ?? '0.0.0')
462
+ // Protocol version agreed by the last legacy `initialize` (advisory only:
463
+ // the legacy method surface is identical for every supported revision).
464
+ let negotiatedProtocolVersion = PROTOCOL_VERSION
465
+ // 0.2.5 A-2: clearance is process configuration, never a tool argument. An
466
+ // invalid/negative value falls back to the most restrictive level (0).
467
+ const requestedClearance = Number(clearance)
468
+ const clearanceLevel = Number.isFinite(requestedClearance) && requestedClearance >= 0 ? requestedClearance : 0
373
469
  // 0.2.3 P0-2: the CLI wires lazy loaders instead of a preloaded ledger/store so
374
470
  // `initialize` stays protocol-only (200k-row ledgers used to cost ~2s before the
375
471
  // first response). Anything that needs data resolves it on first use; an
@@ -410,46 +506,162 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
410
506
  return storeApi
411
507
  }
412
508
 
509
+ // 0.2.5 A-2 (MCP clearance): commitments/facts/preferences are judged by the
510
+ // secrecy of their OWN matter. The 'commitments' read path does not need the
511
+ // matters table for anything else, so resolve the small matters table too; with
512
+ // an embedder-provided ledger that has no getMatter we fail closed instead of
513
+ // returning unfiltered data.
514
+ let matterLedger
515
+ function matterSource() {
516
+ if (matterLedger !== undefined) return matterLedger
517
+ const primary = ledgerFor('commitments')
518
+ if (primary && typeof primary.getMatter === 'function') {
519
+ matterLedger = primary
520
+ } else {
521
+ const matters = ledgerFor('matters')
522
+ matterLedger = matters && typeof matters.getMatter === 'function' ? matters : primary ?? matters ?? {}
523
+ }
524
+ return matterLedger
525
+ }
526
+
527
+ /** True when the record's matter secrecy is above this server's clearance. */
528
+ function isHidden(kind, record) {
529
+ if (!record || typeof record !== 'object') return false
530
+ return isEvidenceRecordAboveClearance(matterSource(), kind, record, clearanceLevel)
531
+ }
532
+
533
+ /** Split a list into visible rows and the withheld count (never a row). */
534
+ function splitByClearance(kind, rows) {
535
+ const visible = []
536
+ let protectedExcluded = 0
537
+ for (const row of rows) {
538
+ if (isHidden(kind, row)) protectedExcluded += 1
539
+ else visible.push(row)
540
+ }
541
+ return { visible, protectedExcluded }
542
+ }
543
+
413
544
  /* ------------------------------ read models ------------------------------ */
414
545
 
415
546
  function todayData() {
416
547
  const open = requireLedger('commitments').openCommitments()
548
+ const view = splitByClearance('commitment', open)
549
+ // Cap AFTER clearance and BEFORE the egress classifier: `open` and `total`
550
+ // stay the true post-filter count, `truncated` says rows were withheld.
551
+ const commitments = view.visible.slice(0, MCP_OUTPUT_LIMITS.todayCommitments)
417
552
  return {
418
- open: open.length,
419
- commitments: open.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })),
553
+ open: view.visible.length,
554
+ commitments: commitments.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })),
555
+ clearance: clearanceLevel,
556
+ protectedExcluded: view.protectedExcluded,
557
+ total: view.visible.length,
558
+ truncated: view.visible.length > commitments.length,
420
559
  }
421
560
  }
422
561
 
423
- function commitRows(all) {
424
- return requireLedger('commitments')
562
+ function commitListData(all, requestedLimit) {
563
+ const rows = requireLedger('commitments')
425
564
  .listCommitments()
426
565
  .filter((c) => all || c.status === 'open')
427
- .map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor }))
566
+ const view = splitByClearance('commitment', rows)
567
+ const limit = Number.isInteger(requestedLimit) ? requestedLimit : MCP_OUTPUT_LIMITS.commitRows
568
+ const commitments = view.visible.slice(0, limit)
569
+ return {
570
+ commitments: commitments.map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor })),
571
+ clearance: clearanceLevel,
572
+ protectedExcluded: view.protectedExcluded,
573
+ total: view.visible.length,
574
+ truncated: view.visible.length > commitments.length,
575
+ limit,
576
+ }
428
577
  }
429
578
 
430
579
  function whoData() {
431
580
  const open = requireLedger('commitments').openCommitments()
581
+ const view = splitByClearance('commitment', open)
582
+ const mine = view.visible.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
583
+ const waiting = view.visible.filter((c) => c.debtor === 'third' || String(c.debtor).startsWith('third:'))
584
+ const limit = MCP_OUTPUT_LIMITS.whoRows
432
585
  return {
433
- mine: open.filter((c) => c.debtor === 'user' || c.debtor === 'agent'),
434
- waiting: open.filter((c) => c.debtor === 'third' || String(c.debtor).startsWith('third:')),
586
+ mine: mine.slice(0, limit),
587
+ waiting: waiting.slice(0, limit),
588
+ clearance: clearanceLevel,
589
+ protectedExcluded: view.protectedExcluded,
590
+ mineTotal: mine.length,
591
+ waitingTotal: waiting.length,
592
+ truncated: mine.length > limit || waiting.length > limit,
435
593
  }
436
594
  }
437
595
 
438
596
  function remindData() {
597
+ const ledgerApi = requireLedger('commitments')
598
+ let reminders
439
599
  try {
440
- return buildReminders(requireLedger('commitments'), { now: nowDate() })
600
+ reminders = buildReminders(ledgerApi, { now: nowDate() })
441
601
  } catch {
442
602
  throw new ToolError('reminder planning failed')
443
603
  }
604
+ let rows
605
+ try {
606
+ rows = ledgerApi.listCommitments()
607
+ } catch {
608
+ rows = []
609
+ }
610
+ const hiddenIds = new Set()
611
+ for (const row of rows) if (isHidden('commitment', row)) hiddenIds.add(row.id)
612
+ const visible = []
613
+ let protectedExcluded = 0
614
+ for (const reminder of reminders) {
615
+ if (hiddenIds.has(reminder.commitmentId)) protectedExcluded += 1
616
+ else visible.push(reminder)
617
+ }
618
+ const capped = visible.slice(0, MCP_OUTPUT_LIMITS.reminders)
619
+ return {
620
+ reminders: capped,
621
+ clearance: clearanceLevel,
622
+ protectedExcluded,
623
+ total: visible.length,
624
+ truncated: visible.length > capped.length,
625
+ }
444
626
  }
445
627
 
446
628
  function evidenceData(id) {
447
629
  const ledgerApi = requireLedger('full')
448
630
  const storeApi = storeFor()
449
- if (id.startsWith('cm_')) return evidenceForCommitment(storeApi, ledgerApi, id)
450
- if (id.startsWith('fact_')) return evidenceForFact(storeApi, ledgerApi, id)
451
- if (id.startsWith('pref_')) return evidenceForPreference(storeApi, ledgerApi, id)
452
- throw new ToolError('unknown evidence id prefix (want cm_/fact_/pref_)')
631
+ const kind = id.startsWith('cm_') ? 'commitment' : id.startsWith('fact_') ? 'fact' : id.startsWith('pref_') ? 'preference' : null
632
+ if (!kind) throw new ToolError('unknown evidence id prefix (want cm_/fact_/pref_)')
633
+ const result =
634
+ kind === 'commitment'
635
+ ? evidenceForCommitment(storeApi, ledgerApi, id)
636
+ : kind === 'fact'
637
+ ? evidenceForFact(storeApi, ledgerApi, id)
638
+ : evidenceForPreference(storeApi, ledgerApi, id)
639
+ if (result?.[kind] && isHidden(kind, result[kind])) {
640
+ // Excluded, never partially returned: no creditor/action/quote/missing
641
+ // rows from a protected record may reach the client.
642
+ return {
643
+ schemaVersion: 2,
644
+ clearance: clearanceLevel,
645
+ protectedExcluded: 1,
646
+ sources: [],
647
+ missing: [],
648
+ note: 'record belongs to a protected matter (secrecy above MCP clearance); content withheld',
649
+ }
650
+ }
651
+ // Same cap contract as the list tools: after clearance, before the
652
+ // classifier; totals describe the untruncated lists.
653
+ const sources = Array.isArray(result.sources) ? result.sources : []
654
+ const missing = Array.isArray(result.missing) ? result.missing : []
655
+ return {
656
+ ...result,
657
+ sources: sources.slice(0, MCP_OUTPUT_LIMITS.evidenceItems),
658
+ missing: missing.slice(0, MCP_OUTPUT_LIMITS.evidenceItems),
659
+ clearance: clearanceLevel,
660
+ protectedExcluded: 0,
661
+ sourcesTotal: sources.length,
662
+ missingTotal: missing.length,
663
+ truncated: sources.length > MCP_OUTPUT_LIMITS.evidenceItems || missing.length > MCP_OUTPUT_LIMITS.evidenceItems,
664
+ }
453
665
  }
454
666
 
455
667
  function evidenceIndex() {
@@ -463,17 +675,29 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
463
675
  sources: Array.isArray(result?.sources) ? result.sources.length : 0,
464
676
  missing: Array.isArray(result?.missing) ? result.missing.length : 0,
465
677
  })
466
- const commitments = ledgerApi
467
- .listCommitments()
468
- .slice(0, limit)
469
- .map((c) => summarize('commitment', c.id, evidenceForCommitment(storeApi, ledgerApi, c.id)))
470
- const facts = (typeof ledgerApi.listFacts === 'function' ? ledgerApi.listFacts() : [])
471
- .slice(0, limit)
472
- .map((f) => summarize('fact', f.id, evidenceForFact(storeApi, ledgerApi, f.id)))
473
- const preferences = (typeof ledgerApi.listPreferences === 'function' ? ledgerApi.listPreferences({ includeCandidates: false }) : [])
474
- .slice(0, limit)
475
- .map((p) => summarize('preference', p.id, evidenceForPreference(storeApi, ledgerApi, p.id)))
476
- return { limits: { perKind: limit }, commitments, facts, preferences }
678
+ const commitments = splitByClearance('commitment', ledgerApi.listCommitments())
679
+ const facts = splitByClearance(
680
+ 'fact',
681
+ typeof ledgerApi.listFacts === 'function' ? ledgerApi.listFacts() : [],
682
+ )
683
+ const preferences = splitByClearance(
684
+ 'preference',
685
+ typeof ledgerApi.listPreferences === 'function' ? ledgerApi.listPreferences({ includeCandidates: false }) : [],
686
+ )
687
+ return {
688
+ limits: { perKind: limit },
689
+ clearance: clearanceLevel,
690
+ protectedExcluded: commitments.protectedExcluded + facts.protectedExcluded + preferences.protectedExcluded,
691
+ commitments: commitments.visible
692
+ .slice(0, limit)
693
+ .map((c) => summarize('commitment', c.id, evidenceForCommitment(storeApi, ledgerApi, c.id))),
694
+ facts: facts.visible
695
+ .slice(0, limit)
696
+ .map((f) => summarize('fact', f.id, evidenceForFact(storeApi, ledgerApi, f.id))),
697
+ preferences: preferences.visible
698
+ .slice(0, limit)
699
+ .map((p) => summarize('preference', p.id, evidenceForPreference(storeApi, ledgerApi, p.id))),
700
+ }
477
701
  }
478
702
 
479
703
  /* ------------------------------ write tools ------------------------------ */
@@ -556,31 +780,43 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
556
780
 
557
781
  /* -------------------------------- tools --------------------------------- */
558
782
 
783
+ const CLEARANCE_NOTE =
784
+ 'Records belonging to protected matters (matter secrecy above this server clearance, default 0) are excluded and only counted in protectedExcluded.'
559
785
  const tools = [
560
786
  {
561
787
  name: 'advisers_today',
562
- description: 'Read the open-commitment count and the open commitments (read-only).',
788
+ description: 'Read the open-commitment count and the open commitments (read-only). Returns at most ' + MCP_OUTPUT_LIMITS.todayCommitments + ' commitment rows; `open`/`total` are the true post-clearance count and `truncated` says rows were withheld. ' + CLEARANCE_NOTE,
563
789
  inputSchema: { type: 'object', properties: {} },
564
790
  annotations: READ_ONLY_ANNOTATIONS,
565
791
  run: () => todayData(),
566
792
  },
567
793
  {
568
794
  name: 'advisers_commit_ls',
569
- description: 'List commitments (open by default; pass all=true for every status). Read-only.',
570
- inputSchema: { type: 'object', properties: { all: { type: 'boolean', description: 'Include done/snoozed/dropped commitments.' } } },
795
+ description:
796
+ 'List commitments (open by default; pass all=true for every status). Returns {commitments, total, truncated, limit, clearance, protectedExcluded}; total is the post-clearance row count, so a truncated result is never mistaken for the whole ledger. Read-only. ' +
797
+ CLEARANCE_NOTE,
798
+ inputSchema: {
799
+ type: 'object',
800
+ properties: {
801
+ all: { type: 'boolean', description: 'Include done/snoozed/dropped commitments.' },
802
+ limit: { type: 'integer', minimum: 1, maximum: MCP_OUTPUT_LIMITS.commitRowsMax, description: 'Max rows to return (default ' + MCP_OUTPUT_LIMITS.commitRows + ', max ' + MCP_OUTPUT_LIMITS.commitRowsMax + ').' },
803
+ },
804
+ },
571
805
  annotations: READ_ONLY_ANNOTATIONS,
572
- run: (args) => commitRows(optionalBoolean(args, 'all')),
806
+ run: (args) => commitListData(optionalBoolean(args, 'all'), optionalLimit(args, 'limit', MCP_OUTPUT_LIMITS.commitRowsMax)),
573
807
  },
574
808
  {
575
809
  name: 'advisers_who',
576
- description: 'Who owes whom: mine (user/agent) versus waiting (third parties). Read-only.',
810
+ description: 'Who owes whom: mine (user/agent) versus waiting (third parties). Read-only. Each array is capped at ' + MCP_OUTPUT_LIMITS.whoRows + ' rows; mineTotal/waitingTotal/truncated report the full counts. ' + CLEARANCE_NOTE,
577
811
  inputSchema: { type: 'object', properties: {} },
578
812
  annotations: READ_ONLY_ANNOTATIONS,
579
813
  run: () => whoData(),
580
814
  },
581
815
  {
582
816
  name: 'advisers_evidence',
583
- description: 'Read the source turns for a commitment/fact/preference id. Read-only.',
817
+ description:
818
+ 'Read the source turns for a commitment/fact/preference id. Read-only. ' +
819
+ 'Evidence of a protected record is withheld (no id content) and reported as protectedExcluded.',
584
820
  inputSchema: {
585
821
  type: 'object',
586
822
  properties: { id: { type: 'string', description: 'cm_* commitment, fact_* fact, or pref_* preference id.' } },
@@ -591,7 +827,9 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
591
827
  },
592
828
  {
593
829
  name: 'advisers_remind',
594
- description: 'Read due reminders (no delivery, no network). Read-only.',
830
+ description:
831
+ 'Read due reminders (no delivery, no network). Returns {reminders, total, truncated, clearance, protectedExcluded}; total is the post-clearance reminder count. Read-only. ' +
832
+ CLEARANCE_NOTE,
595
833
  inputSchema: { type: 'object', properties: {} },
596
834
  annotations: READ_ONLY_ANNOTATIONS,
597
835
  run: () => remindData(),
@@ -665,9 +903,20 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
665
903
  return reply(id, { content: [{ type: 'text', text: message }], isError: true })
666
904
  }
667
905
 
668
- function initializeResult() {
906
+ /**
907
+ * Legacy `initialize` result. 0.3.0 P0-T3: echo the client's version when
908
+ * this server implements that legacy revision (2024-11-05 / 2025-06-18 /
909
+ * 2025-11-25); a missing or unknown version keeps the 2024-11-05 default so
910
+ * pre-0.3 clients observe exactly the old behaviour. 2026-07-28 modern is
911
+ * not advertised on purpose (it needs server/discover and stateless
912
+ * per-request `_meta`; see docs/MCP.md).
913
+ */
914
+ function initializeResult(requestedVersion) {
915
+ const requested = typeof requestedVersion === 'string' ? requestedVersion.trim() : ''
916
+ const negotiated = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSION
917
+ negotiatedProtocolVersion = negotiated
669
918
  return {
670
- protocolVersion: PROTOCOL_VERSION,
919
+ protocolVersion: negotiated,
671
920
  capabilities: {
672
921
  tools: { listChanged: false },
673
922
  resources: { subscribe: false, listChanged: false },
@@ -699,6 +948,8 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
699
948
  } catch (error) {
700
949
  outcome = { ok: false, error }
701
950
  }
951
+ // 0.3.0 P0-T3: cap the payload BEFORE the egress classifier scans it.
952
+ if (outcome.ok) outcome.data = boundPayload(outcome.data)
702
953
 
703
954
  // Gate 2: a tool must not relay block-level text (ledger data, receipt
704
955
  // metadata, ...). The returned payload is classified before it is sent.
@@ -737,12 +988,14 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
737
988
  if (typeof uri !== 'string' || !uri.trim()) throw invalidParams('uri must be a non-empty string')
738
989
  if (!RESOURCE_URIS.includes(uri)) return rpcError(id, -32002, 'resource not found')
739
990
  let data
991
+ // 0.2.5 A-2: resources read the same clearance-filtered models as the tools.
740
992
  if (uri === 'advisers://today') data = todayData()
741
- else if (uri === 'advisers://commitments') data = { commitments: commitRows(true) }
993
+ else if (uri === 'advisers://commitments') data = commitListData(true)
742
994
  else if (uri === 'advisers://who') data = whoData()
743
995
  else data = evidenceIndex()
744
996
  await recordAudit({ actor: 'mcp', action: 'mcp.call', allowed: true, reason: 'resource:' + uri })
745
- return reply(id, { contents: [{ uri, mimeType: 'application/json', text: JSON.stringify(data, null, 2) }] })
997
+ const bounded = boundPayload(data)
998
+ return reply(id, { contents: [{ uri, mimeType: 'application/json', text: JSON.stringify(bounded, null, 2) }] })
746
999
  }
747
1000
 
748
1001
  /**
@@ -764,7 +1017,10 @@ export function createMcpServer({ store, ledger, loadLedger, loadStore, version
764
1017
  const method = message.method
765
1018
 
766
1019
  try {
767
- if (method === 'initialize') return hasId ? reply(id, initializeResult()) : null
1020
+ if (method === 'initialize') {
1021
+ const params = paramsObject(message.params)
1022
+ return hasId ? reply(id, initializeResult(params.protocolVersion)) : null
1023
+ }
768
1024
  if (method === 'notifications/initialized') return hasId ? reply(id, {}) : null
769
1025
  if (method === 'ping') return hasId ? reply(id, {}) : null
770
1026
  if (method === 'tools/list') {
package/lib/model.js CHANGED
File without changes
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Suppress the one-time `node:sqlite is experimental` warning on Node 22.
3
+ *
4
+ * The warning is a runtime implementation detail, not part of the CLI
5
+ * contract; without this filter a plain `advisers status --json` writes it to
6
+ * stderr and breaks JSON-purity gates (and scripts that parse stderr).
7
+ * Only this exact warning is filtered; all other warnings pass through.
8
+ */
9
+ const originalEmitWarning = process.emitWarning.bind(process)
10
+
11
+ process.emitWarning = (warning, ...args) => {
12
+ const text = typeof warning === 'string' ? warning : String(warning?.message ?? '')
13
+ if (/SQLite is an experimental feature/i.test(text)) return
14
+ return originalEmitWarning(warning, ...args)
15
+ }
package/lib/notify.js CHANGED
@@ -10,6 +10,10 @@
10
10
  import { existsSync } from 'node:fs'
11
11
  import { spawn } from 'node:child_process'
12
12
  import { localDay } from './remind.js'
13
+ // 0.3.0 Wave 3 (docs/TUI.md §4): webhook/notifier failure detail is remote text
14
+ // and reaches stderr through bin's `webhook 未发送:` line. Sanitise at the library
15
+ // boundary so no caller can leak ANSI/C1/bidi or a second log line.
16
+ import { sanitizeConsoleText } from './text-safe.js'
13
17
 
14
18
  /**
15
19
  * Environment for the notification subprocess: an explicit allowlist.
@@ -43,7 +47,9 @@ function run(cmd, args, timeoutMs = 5000) {
43
47
  let err = ''
44
48
  child.stderr.on('data', (b) => { err += b.toString('utf8') })
45
49
  child.on('error', reject)
46
- child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`${cmd} exited ${code}: ${err.trim().slice(0, 200)}`)))
50
+ // A local notifier's stderr is untrusted text (it may include the reminder
51
+ // title the caller passed); keep it to one sanitised line.
52
+ child.on('close', (code) => code === 0 ? resolve() : reject(new Error(`${cmd} exited ${code}: ${sanitizeConsoleText(err.trim(), { max: 200 })}`)))
47
53
  })
48
54
  }
49
55
 
@@ -109,9 +115,13 @@ function resolveWebhookTarget(options) {
109
115
  }
110
116
  }
111
117
 
118
+ /**
119
+ * One sanitised console line for a remote failure detail (webhook response body,
120
+ * fetch/abort message). ANSI/OSC/C1/bidi and line breaks are removed before the
121
+ * value can reach stderr, and the result is capped at `limit` code points.
122
+ */
112
123
  function truncateDetail(value, limit = 200) {
113
- const text = typeof value === 'string' ? value : String(value ?? '')
114
- return text.length > limit ? text.slice(0, limit) : text
124
+ return sanitizeConsoleText(value, { max: limit })
115
125
  }
116
126
 
117
127
  /**
package/lib/nudge.js CHANGED
File without changes
package/lib/ocr.js CHANGED
File without changes
package/lib/pdf.js CHANGED
File without changes
File without changes