@chatpanel/gateway 0.6.109 → 0.7.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 (80) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +1 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2290
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
@@ -1,6 +1 @@
1
- // VENDORED from @chatpanel/events/subject-kinds.js — edit there, then copy over.
2
- // The subject vocabulary, alone in a file so both halves of subject identity can name it
3
- // without either importing the other.
4
-
5
- /** What a subject can be. `title` is a record title someone linked to with [[…]]. */
6
- export const SUBJECT_KINDS = Object.freeze(['person', 'topic', 'tag', 'title']);
1
+ const e=Object.freeze(["person","topic","tag","title"]);export{e as SUBJECT_KINDS};
@@ -1,97 +1 @@
1
- // VENDORED from @chatpanel/events/subject-name.js — edit there, then copy over.
2
- // Naming a subject, and when one is big enough to deserve a page.
3
- //
4
- // The small, dependency-free half of subject identity: fold a name to its canonical form,
5
- // strip the decoration a directory hangs off it, and hold the evidence thresholds. Nothing
6
- // here resolves aliases, proposes merges or reaches for a Levenshtein — that is `entity.js`,
7
- // which imports this.
8
- //
9
- // The split is a load-time one, and it is the third time the lesson has come up here (see
10
- // `distance.js` and `redaction-tokens.js`). `knowledge.js` needs exactly `normalizeSubject`
11
- // to build a brief id, and the extension's brief store needs exactly `DEFAULT_THRESHOLD` —
12
- // and both are on the MV3 service worker's graph. Reaching them through `entity.js` put
13
- // entity resolution and merge suggestion on a worker that will never run either.
14
-
15
- import { SUBJECT_KINDS } from './subject-kinds.js';
16
-
17
- /**
18
- * A subject earns a brief with EVIDENCE, not on first sight (I-K4).
19
- *
20
- * PROVISIONAL. These numbers are the W0 measurement's whole point: `surveyCorpus()` reports
21
- * how many subjects clear them so they can be set from a real corpus instead of taste. Do
22
- * not treat them as decided until that report has been run.
23
- */
24
- export const DEFAULT_THRESHOLD = Object.freeze({ records: 3, mentions: 5 });
25
-
26
- /** Ceiling on the set of briefs, for the same reason memory.js caps memories. Provisional. */
27
- export const MAX_SUBJECTS = 500;
28
- /** Longest name we will treat as a subject — past this it is a sentence, not a subject. */
29
- export const MAX_SUBJECT_CHARS = 60;
30
- /**
31
- * Labels a meeting platform uses for the person holding the microphone.
32
- *
33
- * Zoom, Meet and Teams all write the local participant as "You" — so the user appears in
34
- * their own corpus under a name that is not a name, alongside however their colleagues'
35
- * clients spelled them. Resolving these needs one fact only the host has: who "you" IS.
36
- * `resolveSubjects` takes it rather than guessing, and with no `self` supplied these stay
37
- * unresolved instead of collapsing every meeting's local speaker into one fictional person.
38
- */
39
- export const SELF_LABELS = Object.freeze(['you', 'me', 'myself', 'yourself', 'i']);
40
-
41
- /**
42
- * Is this the platform's label for the local participant?
43
- *
44
- * Exported because two layers need the SAME exception and getting the order wrong is subtle:
45
- * a self-label fails `isSubjectCandidate` (it is a pronoun), so any pass that filters
46
- * candidacy BEFORE `resolveSubjects` can fold it has already thrown the user away. `curate.js
47
- * mentionsFrom` keeps them for exactly this reason and lets resolution decide.
48
- */
49
- export function isSelfLabel(name) {
50
- return SELF_LABELS.includes(normalizeSubject(name));
51
- }
52
-
53
- /**
54
- * Strip the decoration a directory or a conference client hangs off a person's name.
55
- *
56
- * The same human arrives as "Alex Rivera", "Alex Rivera (ACME)", "Alex Rivera - Host" and
57
- * "Alex Rivera (he/him)" depending on which client wrote the label. The part in parentheses
58
- * or after a dash is an org, a role or a pronoun set — decoration, never identity — so it is
59
- * removed before folding.
60
- *
61
- * NOT removed for non-person subjects: "Migration (Phase 2)" is a different topic from
62
- * "Migration", where "Alex Rivera (ACME)" is not a different person from "Alex Rivera".
63
- */
64
- export function stripQualifiers(name) {
65
- return String(name ?? '')
66
- .replace(/\s*[([{][^)\]}]*[)\]}]\s*/g, ' ') // (ACME), [external], {guest}
67
- .replace(/\s+[-–—|·,]\s+.*$/, '') // - Host, — Guest, | ACME
68
- .replace(/\s+/g, ' ')
69
- .trim();
70
- }
71
- /**
72
- * Fold a name to its canonical form: lowercase, Unicode-aware, separators collapsed.
73
- *
74
- * Spaces survive as spaces (unlike normalizeTag, which folds them to '-') because a person's
75
- * name is read back to the user and "alex rivera" has to be recognisable as one.
76
- */
77
- export function normalizeSubject(name) {
78
- const raw = String(name ?? '').normalize('NFKC').trim().replace(/^[#@]+/, '');
79
- if (!raw) return '';
80
- return raw
81
- .toLowerCase()
82
- .replace(/[^\p{L}\p{N}]+/gu, ' ')
83
- .trim()
84
- .slice(0, MAX_SUBJECT_CHARS)
85
- .trim();
86
- }
87
- /** `person:alex rivera` — the identity a brief is filed under. '' when nothing survives. */
88
- export function subjectKey(kind, name) {
89
- const norm = normalizeSubject(name);
90
- if (!norm || !SUBJECT_KINDS.includes(kind)) return '';
91
- return `${kind}:${norm}`;
92
- }
93
- /** Tokens of a canonical name. */
94
- export function subjectTokens(name) {
95
- const norm = normalizeSubject(name);
96
- return norm ? norm.split(' ').filter(Boolean) : [];
97
- }
1
+ import{SUBJECT_KINDS as n}from"./subject-kinds.js";const u=Object.freeze({records:3,mentions:5}),p=500,s=60,c=Object.freeze(["you","me","myself","yourself","i"]);function l(e){return c.includes(t(e))}function f(e){return String(e??"").replace(/\s*[([{][^)\]}]*[)\]}]\s*/g," ").replace(/\s+[-–—|·,]\s+.*$/,"").replace(/\s+/g," ").trim()}function t(e){const r=String(e??"").normalize("NFKC").trim().replace(/^[#@]+/,"");return r?r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim().slice(0,s).trim():""}function m(e,r){const o=t(r);return!o||!n.includes(e)?"":`${e}:${o}`}function S(e){const r=t(e);return r?r.split(" ").filter(Boolean):[]}export{u as DEFAULT_THRESHOLD,p as MAX_SUBJECTS,s as MAX_SUBJECT_CHARS,c as SELF_LABELS,l as isSelfLabel,t as normalizeSubject,f as stripQualifiers,m as subjectKey,S as subjectTokens};
package/src/team-board.js CHANGED
@@ -1,338 +1,6 @@
1
- // VENDORED from @chatpanel/events/team-board.js — edit there, then copy over.
2
- // The board — where a team's members meet: a message board, not a log.
3
- //
4
- // One board per run. A THREAD per task (and one per ask, discussion or proposal); POSTS in
5
- // threads — a member's findings, its notes, a question, a person's answer, a draft, a
6
- // decision — and REPLIES hanging off posts. Members do not read each other's transcripts:
7
- // a task ends with FINDINGS (claims with the refs they came from, I-K1), those become posts
8
- // in its thread, and a later task reads the threads it depends on, threaded and sized like a
9
- // shielded tool result. A member that disagrees replies where it disagrees; a member that
10
- // is stuck ASKS, and its task waits for a person — on either client — to answer. A person
11
- // posting is a member posting, and a person's decision on any post wins.
12
- //
13
- // The board is the run's record: durable (every change is an event the run store folds with
14
- // `foldBoard`), attributable per member, and — after a run — what can become draft briefs
15
- // and be promoted on convergence (W7), rather than evaporating with the run.
16
- //
17
- // Findings are parsed GENEROUSLY from a model's answer through the structured layer, and a
18
- // task whose answer cannot be read as findings is not lost: its whole answer becomes one
19
- // `draft` finding. A member that only wrote prose still contributed.
20
-
21
- import { defineSchema, describeSchema, coerce } from './structured.js';
22
-
23
- export const FINDING_KINDS = Object.freeze(['claim', 'draft', 'link', 'question', 'answer']);
24
- export const MAX_FINDINGS_PER_TASK = 40;
25
- export const BOARD_TEXT_MAX = 12_000;
26
-
27
- export const FINDINGS_SCHEMA = defineSchema({
28
- name: 'findings',
29
- purpose: 'what this task established, each item on its own with where it came from',
30
- fields: {
31
- findings: {
32
- type: 'object[]', required: true, maxItems: MAX_FINDINGS_PER_TASK,
33
- describe: 'one entry per fact, draft, link or open question — never a paragraph of several',
34
- fields: {
35
- kind: { type: 'enum', values: FINDING_KINDS, default: 'claim' },
36
- text: { type: 'string', required: true, max: 2000 },
37
- refs: { type: 'string[]', maxItems: 8, describe: 'record ids or URLs this rests on, when any' },
38
- confidence: { type: 'number', describe: '0–1, how sure' },
39
- },
40
- },
41
- },
42
- nothing: { findings: [] },
43
- });
44
-
45
- /** The instruction appended to every task so the answer can be read as findings. */
46
- export function findingsInstruction() {
47
- return `When you are done, end your answer with your findings in this shape:\n${describeSchema(FINDINGS_SCHEMA)}`;
48
- }
49
-
50
- /**
51
- * Read a task's answer into findings. The JSON block, when present; otherwise the whole
52
- * answer as one draft — a member that only wrote prose still contributed.
53
- */
54
- export function parseFindings(text, { role, taskId } = {}) {
55
- const raw = String(text || '').trim();
56
- if (!raw) return [];
57
- const got = coerce(raw, FINDINGS_SCHEMA);
58
- const list = Array.isArray(got?.value?.findings) ? got.value.findings.filter((f) => f && String(f.text || '').trim()) : [];
59
- const stamp = (f, i) => ({
60
- id: `${taskId || 't'}:${i + 1}`,
61
- kind: FINDING_KINDS.includes(f.kind) ? f.kind : 'claim',
62
- text: String(f.text).trim().slice(0, 2000),
63
- refs: Array.isArray(f.refs) ? f.refs.map(String).filter(Boolean).slice(0, 8) : [],
64
- // Absent or zero reads as "not stated": a model that gives no number is not 0% sure.
65
- confidence: Number.isFinite(Number(f.confidence)) && Number(f.confidence) > 0 ? Math.min(1, Number(f.confidence)) : null,
66
- role: role || null,
67
- taskId: taskId || null,
68
- });
69
- if (list.length) return list.slice(0, MAX_FINDINGS_PER_TASK).map(stamp);
70
- // No JSON block: the prose is the finding. Strip a fenced JSON tail that failed to parse.
71
- const prose = raw.replace(/```json[\s\S]*$/i, '').trim() || raw;
72
- return [stamp({ kind: 'draft', text: prose.slice(0, 2000), refs: [] }, 0)];
73
- }
74
-
75
- // ── threads, posts, asks ────────────────────────────────────────────────────────────────
76
-
77
- export const THREAD_KINDS = Object.freeze(['task', 'ask', 'discussion', 'proposal']);
78
- // `failed`: the task behind the thread ended without an answer (every model on the roster
79
- // tried, or a hard error) — not `resolved`, which read as "done" on the board.
80
- export const THREAD_STATUSES = Object.freeze(['open', 'waiting', 'resolved', 'failed', 'approved', 'rejected']);
81
- // `request`: a member asks for a piece of its task to be done by someone else — the runner
82
- // turns it into a sub-task with its own thread (team-subtask.js).
83
- export const POST_KINDS = Object.freeze(['finding', 'note', 'question', 'answer', 'draft', 'decision', 'request']);
84
- export const POST_STATUSES = Object.freeze(['open', 'proposed', 'approved', 'rejected']);
85
- export const ASK_TYPES = Object.freeze(['info', 'budget', 'permission', 'direction']);
86
- export const RUNNER = 'runner';
87
- export const PERSON = 'person';
88
- export const MAX_POST_TEXT = 4000;
89
-
90
- const clip = (t, n) => String(t || '').trim().slice(0, n);
91
- const refsOf = (r) => (Array.isArray(r) ? r.map(String).filter(Boolean).slice(0, 8) : []);
92
-
93
- /** The empty folded state — what a run record holds, what `foldBoard` grows. */
94
- export function emptyBoardState() { return { threads: [], posts: [] }; }
95
-
96
- /**
97
- * Fold one board event into a state (pure; the gateway's run store and both clients use it).
98
- * Ids dedupe: an answer posted through the gateway and echoed by the running client's runner
99
- * arrives twice with one id and lands once.
100
- */
101
- export function foldBoard(state, ev) {
102
- const s = state && Array.isArray(state.threads) && Array.isArray(state.posts) ? state : emptyBoardState();
103
- const type = String(ev?.type || '');
104
- const p = ev?.payload && typeof ev.payload === 'object' ? ev.payload : ev || {};
105
- if (type === 'board.thread' && p.thread?.id) {
106
- if (!s.threads.some((t) => t.id === p.thread.id)) s.threads.push({ ...p.thread });
107
- } else if (type === 'board.post' && p.post?.id) {
108
- if (Array.isArray(s.removed) && s.removed.includes(p.post.threadId)) return s;
109
- if (!s.posts.some((x) => x.id === p.post.id)) s.posts.push({ ...p.post });
110
- const t = s.threads.find((x) => x.id === p.post.threadId);
111
- if (t) { t.lastAt = p.post.at; t.lastBy = p.post.by; t.posts = (t.posts || 0) + 1; }
112
- } else if (type === 'board.decision' && p.postId) {
113
- const x = s.posts.find((q) => q.id === p.postId);
114
- if (x) { x.status = p.status; x.decidedBy = p.by; x.decidedAt = p.at ?? ev?.at; }
115
- } else if (type === 'board.thread-status' && p.threadId) {
116
- const t = s.threads.find((x) => x.id === p.threadId);
117
- if (t) { t.status = p.status; if (p.status !== 'waiting') t.waitingOn = null; if (p.holder) t.holder = p.holder; }
118
- } else if (type === 'board.thread-removed' && p.threadId) {
119
- // A person took the thread off the board: it and its posts go, and its id is kept so a
120
- // post a member still makes in it (its runner did not see the removal) lands nowhere.
121
- s.threads = s.threads.filter((x) => x.id !== p.threadId);
122
- s.posts = s.posts.filter((x) => x.threadId !== p.threadId);
123
- if (!Array.isArray(s.removed)) s.removed = [];
124
- if (!s.removed.includes(p.threadId)) s.removed.push(p.threadId);
125
- }
126
- return s;
127
- }
128
-
129
- /**
130
- * The live board a run works on. `state` seeds it (a resume); `onEvent` receives every
131
- * change as the event the run store folds. The legacy findings API (`add`, `all`, `byTask`)
132
- * stays: a finding is a post of kind `finding` in its task's thread.
133
- */
134
- export function createBoard({ now = () => Date.now(), newId = null, state = null, onEvent = null } = {}) {
135
- const st = state && Array.isArray(state.threads) ? { threads: state.threads.map((t) => ({ ...t })), posts: (state.posts || []).map((x) => ({ ...x })), ...(Array.isArray(state.removed) && state.removed.length ? { removed: [...state.removed] } : {}) } : emptyBoardState();
136
- const listeners = new Set();
137
- let seq = st.posts.length + st.threads.length;
138
- const mk = (prefix) => (newId ? newId(prefix) : `${prefix}_${(++seq).toString(36)}${Math.random().toString(36).slice(2, 6)}`);
139
- const say = (type, payload) => { const ev = { type, at: now(), ...payload }; if (onEvent) onEvent(type, ev); return ev; };
140
- const threadOf = (id) => st.threads.find((t) => t.id === id);
141
- const postOf = (id) => st.posts.find((x) => x.id === id);
142
- const threadForTask = (taskId) => st.threads.find((t) => t.kind === 'task' && t.taskId === taskId);
143
-
144
- const api = {
145
- /** Open a thread. A task's thread is opened once; asking for it again returns it. */
146
- openThread({ id = null, taskId = null, kind = 'discussion', title = '', by = RUNNER, status = 'open', ask = null, parent = null, holder = null } = {}) {
147
- if (kind === 'task' && taskId) { const had = threadForTask(taskId); if (had) return had; }
148
- // `parent`: the task this one was requested from (a sub-task's thread hangs under its
149
- // parent's on the board); `holder`: the member that took it.
150
- const thread = { id: id || mk('th'), kind: THREAD_KINDS.includes(kind) ? kind : 'discussion', taskId, title: clip(title, 200), by, status: THREAD_STATUSES.includes(status) ? status : 'open', at: now(), posts: 0, ...(ask ? { ask } : {}), ...(parent ? { parent } : {}), ...(holder ? { holder } : {}) };
151
- st.threads.push(thread);
152
- say('board.thread', { thread: { ...thread } });
153
- return thread;
154
- },
155
- /** A post in a thread; `replyTo` makes it a reply. */
156
- /** `proposal` rides on a draft a person decides on — `{ kind: 'agent', agent, jobId }` (§15.2): the card the host creates when the post is approved. */
157
- post({ id = null, threadId, by, kind = 'note', text = '', refs = [], replyTo = null, status = 'open', finding = null, ask = null, proposal = null } = {}) {
158
- const t = threadOf(threadId);
159
- if (!t) throw new Error(`no thread ${threadId}`);
160
- if (id && postOf(id)) return postOf(id);
161
- const post = {
162
- id: id || mk('p'), threadId, by: String(by || RUNNER), kind: POST_KINDS.includes(kind) ? kind : 'note',
163
- text: clip(text, MAX_POST_TEXT), refs: refsOf(refs), replyTo, status: POST_STATUSES.includes(status) ? status : 'open', at: now(),
164
- ...(finding ? { finding } : {}), ...(ask ? { ask } : {}), ...(proposal && typeof proposal === 'object' ? { proposal } : {}),
165
- };
166
- st.posts.push(post);
167
- t.lastAt = post.at; t.lastBy = post.by; t.posts = (t.posts || 0) + 1;
168
- say('board.post', { post: { ...post } });
169
- for (const l of listeners) l(post);
170
- return post;
171
- },
172
- /** A reply hangs off a post and lives in that post's thread. */
173
- reply({ postId, ...args }) {
174
- const target = postOf(postId || args.replyTo);
175
- if (!target) throw new Error(`no post ${postId}`);
176
- return api.post({ ...args, threadId: target.threadId, replyTo: target.id });
177
- },
178
- /** A person's (or the judge's) decision on a post. */
179
- decide(postId, status, by = PERSON) {
180
- const x = postOf(postId);
181
- if (!x || !['approved', 'rejected', 'proposed', 'open'].includes(status)) return null;
182
- x.status = status; x.decidedBy = by; x.decidedAt = now();
183
- say('board.decision', { postId, status, by, at: x.decidedAt });
184
- return x;
185
- },
186
- setThreadStatus(threadId, status, extra = {}) {
187
- const t = threadOf(threadId);
188
- if (!t || !THREAD_STATUSES.includes(status)) return null;
189
- t.status = status; if (status !== 'waiting') t.waitingOn = null; Object.assign(t, extra);
190
- say('board.thread-status', { threadId, status, ...extra });
191
- return t;
192
- },
193
- /**
194
- * A person takes a thread off the board (from either client — the store appends the
195
- * event, the running client's tail applies it here). Its posts go with it; a member's
196
- * later post in it lands nowhere. A waiting ask is not removed: answer it or stop the run.
197
- */
198
- removeThread(threadId, { by = PERSON } = {}) {
199
- const t = threadOf(threadId);
200
- if (!t || (t.kind === 'ask' && t.status === 'waiting')) return null;
201
- st.threads = st.threads.filter((x) => x.id !== threadId);
202
- st.posts = st.posts.filter((x) => x.threadId !== threadId);
203
- (st.removed ||= []).push(threadId);
204
- say('board.thread-removed', { threadId, by });
205
- return t;
206
- },
207
- /**
208
- * A member is stuck: open an ask thread (status `waiting`) with the question as its
209
- * first post. The runner waits on it; a person answers from either client.
210
- */
211
- ask({ taskId = null, by, type = 'info', text, options = [], timeoutMs = 0, title = '' } = {}) {
212
- const ask = { type: ASK_TYPES.includes(type) ? type : 'info', options: (Array.isArray(options) ? options : []).map(String).slice(0, 6), timeoutMs };
213
- const thread = api.openThread({ taskId, kind: 'ask', title: title || clip(text, 120), by, status: 'waiting', ask });
214
- thread.waitingOn = PERSON;
215
- const post = api.post({ threadId: thread.id, by, kind: 'question', text, ask });
216
- return { thread, post };
217
- },
218
- /** The answer to an ask — from a person, on any client. Resolves the thread. */
219
- answer(threadId, { id = null, text, by = PERSON } = {}) {
220
- const t = threadOf(threadId);
221
- if (!t) return null;
222
- const post = api.post({ id, threadId, by, kind: 'answer', text });
223
- api.setThreadStatus(threadId, 'resolved', { answeredAt: post.at });
224
- return post;
225
- },
226
- thread: threadOf,
227
- threadForTask,
228
- threads: () => st.threads.map((t) => ({ ...t })),
229
- posts: (threadId = null) => st.posts.filter((x) => !threadId || x.threadId === threadId).map((x) => ({ ...x })),
230
- postById: postOf,
231
- /** Every ask still waiting — what a client pins at the top. */
232
- waiting: () => st.threads.filter((t) => t.kind === 'ask' && t.status === 'waiting').map((t) => ({ ...t })),
233
- /** The whole board, for the run record and for a resume. */
234
- state: () => ({ threads: st.threads.map((t) => ({ ...t })), posts: st.posts.map((x) => ({ ...x })), ...(st.removed?.length ? { removed: [...st.removed] } : {}) }),
235
-
236
- // ── findings, as before: a finding is a post in its task's thread ──
237
- add(list, { by = null } = {}) {
238
- let n = 0;
239
- for (const f of Array.isArray(list) ? list : [list]) {
240
- if (!f || !f.text) continue;
241
- const t = f.taskId ? (threadForTask(f.taskId) || api.openThread({ taskId: f.taskId, kind: 'task', title: f.taskId })) : (st.threads.find((x) => x.kind === 'discussion' && x.title === 'findings') || api.openThread({ kind: 'discussion', title: 'findings' }));
242
- api.post({ id: f.id, threadId: t.id, by: by || f.role || RUNNER, kind: 'finding', text: f.text, refs: f.refs, finding: { kind: f.kind || 'claim', confidence: f.confidence ?? null } });
243
- n += 1;
244
- }
245
- return n;
246
- },
247
- all: () => st.posts.filter((x) => x.kind === 'finding').map(asFinding(st)),
248
- byTask: (taskId) => api.all().filter((f) => f.taskId === taskId),
249
- byRole: (role) => api.all().filter((f) => f.role === role),
250
- onFinding(fn) { const l = (p) => { if (p.kind === 'finding') fn(asFinding(st)(p)); }; listeners.add(l); return () => listeners.delete(l); },
251
- get size() { return st.posts.filter((x) => x.kind === 'finding').length; },
252
- };
253
- return api;
254
- }
255
-
256
- /** A finding post in the legacy finding shape (what merge, briefs and lanes read). */
257
- function asFinding(st) {
258
- return (p) => {
259
- const t = st.threads.find((x) => x.id === p.threadId);
260
- return { id: p.id, kind: p.finding?.kind || 'claim', text: p.text, refs: p.refs || [], confidence: p.finding?.confidence ?? null, role: p.by, taskId: t?.taskId || null, at: p.at, status: p.status, ...(p.finding?.prior ? { prior: true } : {}) };
261
- };
262
- }
263
-
264
- /** Findings from a folded state (a run record read from the store). */
265
- export function findingsOf(state) {
266
- const st = state && Array.isArray(state.posts) ? state : emptyBoardState();
267
- return st.posts.filter((x) => x.kind === 'finding').map(asFinding(st));
268
- }
269
-
270
- /**
271
- * What a later task READS: the findings of the tasks it depends on (or everything so far),
272
- * sized. Newest are kept whole; the oldest are what get cut, and the cut is stated.
273
- */
274
- export function boardText(source, { taskIds = null, max = BOARD_TEXT_MAX, role = null } = {}) {
275
- // A board (threads + posts) reads threaded; a bare findings array reads as before.
276
- const state = source && typeof source.state === 'function' ? source.state() : (source && Array.isArray(source.posts) ? source : null);
277
- const lines = state ? threadedLines(state, { taskIds, role }) : findingLines(source, taskIds);
278
- if (!lines.length) return '';
279
- const head = state ? 'The board so far' : 'Findings so far';
280
- const out = lines.join('\n');
281
- if (out.length <= max) return `${head}:\n${out}`;
282
- const kept = [];
283
- let size = 0;
284
- for (let i = lines.length - 1; i >= 0; i -= 1) {
285
- if (size + lines[i].length + 1 > max) break;
286
- kept.unshift(lines[i]);
287
- size += lines[i].length + 1;
288
- }
289
- return `${head} (${lines.length - kept.length} earlier lines omitted for length):\n${kept.join('\n')}`;
290
- }
291
-
292
- function findingLines(findings, taskIds) {
293
- return (findings || []).filter((f) => !taskIds || taskIds.includes(f.taskId))
294
- .map((f) => `- [${f.kind}${f.role ? ` · ${f.role}` : ''}${f.confidence != null ? ` · ${Math.round(f.confidence * 100)}%` : ''}] ${f.text}${f.refs?.length ? ` (refs: ${f.refs.join(', ')})` : ''}`);
295
- }
296
-
297
- /**
298
- * What a member READS: the task threads it depends on (or every task thread), the answered
299
- * asks and settled discussions — never rejected posts — threaded, a reply under its post.
300
- * A person's decision is marked so a member treats it as settled.
301
- */
302
- function threadedLines(state, { taskIds, role }) {
303
- const out = [];
304
- const posts = state.posts;
305
- const threads = state.threads.filter((t) => {
306
- if (t.kind === 'task') return !taskIds || taskIds.includes(t.taskId);
307
- if (t.kind === 'ask') return t.status === 'resolved' && (!role || t.by === role || t.by === RUNNER);
308
- if (t.kind === 'discussion') return true;
309
- return false; // a proposal is the run's output, not a member's input
310
- });
311
- for (const t of threads) {
312
- const own = posts.filter((x) => x.threadId === t.id && x.status !== 'rejected');
313
- if (!own.length) continue;
314
- out.push(`## ${t.kind}${t.by && t.by !== RUNNER ? ` by ${t.by}` : ''}: ${t.title}${t.holder ? ` (held by ${t.holder})` : ''}${t.status === 'resolved' && t.kind === 'ask' ? ' (answered)' : ''}`);
315
- const line = (x, depth) => {
316
- const tag = [x.kind === 'finding' ? (x.finding?.kind || 'claim') : x.kind, x.by, x.finding?.confidence != null ? `${Math.round(x.finding.confidence * 100)}%` : null, x.status === 'approved' ? 'APPROVED' : x.status === 'proposed' ? 'proposed' : null, x.kind === 'decision' || x.by === PERSON ? 'SETTLED' : null].filter(Boolean).join(' · ');
317
- out.push(`${' '.repeat(depth)}- [${tag}] ${x.text}${x.refs?.length ? ` (refs: ${x.refs.join(', ')})` : ''}`);
318
- for (const r of own.filter((y) => y.replyTo === x.id)) line(r, depth + 1);
319
- };
320
- for (const x of own.filter((y) => !y.replyTo)) line(x, 0);
321
- }
322
- return out;
323
- }
324
-
325
- /** Findings → the claim shape a draft brief takes (W7): text + refs as `{ kind, id }`. */
326
- export function toBriefClaims(findings) {
327
- return (findings || [])
328
- .filter((f) => f.kind === 'claim' && f.text)
329
- .map((f) => ({
330
- text: f.text,
331
- refs: (f.refs || []).map((r) => {
332
- const m = /^([a-z][a-z0-9_-]*):(?!\/\/)(.+)$/.exec(String(r));
333
- return m ? { kind: m[1], id: m[2] } : { kind: 'url', id: String(r) };
334
- }),
335
- by: f.role || 'team',
336
- confidence: f.confidence,
337
- }));
338
- }
1
+ import{defineSchema as R,describeSchema as F,coerce as q}from"./structured.js";const N=Object.freeze(["claim","draft","link","question","answer"]),E=40,M=12e3,B=R({name:"findings",purpose:"what this task established, each item on its own with where it came from",fields:{findings:{type:"object[]",required:!0,maxItems:E,describe:"one entry per fact, draft, link or open question — never a paragraph of several",fields:{kind:{type:"enum",values:N,default:"claim"},text:{type:"string",required:!0,max:2e3},refs:{type:"string[]",maxItems:8,describe:"record ids or URLs this rests on, when any"},confidence:{type:"number",describe:"0–1, how sure"}}}},nothing:{findings:[]}});function W(){return`When you are done, end your answer with your findings in this shape:
2
+ ${F(B)}`}function Y(d,{role:i,taskId:n}={}){const f=String(d||"").trim();if(!f)return[];const t=q(f,B),o=Array.isArray(t?.value?.findings)?t.value.findings.filter(u=>u&&String(u.text||"").trim()):[],a=(u,c)=>({id:`${n||"t"}:${c+1}`,kind:N.includes(u.kind)?u.kind:"claim",text:String(u.text).trim().slice(0,2e3),refs:Array.isArray(u.refs)?u.refs.map(String).filter(Boolean).slice(0,8):[],confidence:Number.isFinite(Number(u.confidence))&&Number(u.confidence)>0?Math.min(1,Number(u.confidence)):null,role:i||null,taskId:n||null});if(o.length)return o.slice(0,E).map(a);const m=f.replace(/```json[\s\S]*$/i,"").trim()||f;return[a({kind:"draft",text:m.slice(0,2e3),refs:[]},0)]}const P=Object.freeze(["task","ask","discussion","proposal"]),D=Object.freeze(["open","waiting","resolved","failed","approved","rejected"]),K=Object.freeze(["finding","note","question","answer","draft","decision","request"]),X=Object.freeze(["open","proposed","approved","rejected"]),L=Object.freeze(["info","budget","permission","direction"]),v="runner",x="person",U=4e3,j=(d,i)=>String(d||"").trim().slice(0,i),G=d=>Array.isArray(d)?d.map(String).filter(Boolean).slice(0,8):[];function O(){return{threads:[],posts:[]}}function J(d,i){const n=d&&Array.isArray(d.threads)&&Array.isArray(d.posts)?d:O(),f=String(i?.type||""),t=i?.payload&&typeof i.payload=="object"?i.payload:i||{};if(f==="board.thread"&&t.thread?.id)n.threads.some(o=>o.id===t.thread.id)||n.threads.push({...t.thread});else if(f==="board.post"&&t.post?.id){if(Array.isArray(n.removed)&&n.removed.includes(t.post.threadId))return n;n.posts.some(a=>a.id===t.post.id)||n.posts.push({...t.post});const o=n.threads.find(a=>a.id===t.post.threadId);o&&(o.lastAt=t.post.at,o.lastBy=t.post.by,o.posts=(o.posts||0)+1)}else if(f==="board.decision"&&t.postId){const o=n.posts.find(a=>a.id===t.postId);o&&(o.status=t.status,o.decidedBy=t.by,o.decidedAt=t.at??i?.at)}else if(f==="board.thread-status"&&t.threadId){const o=n.threads.find(a=>a.id===t.threadId);o&&(o.status=t.status,t.status!=="waiting"&&(o.waitingOn=null),t.holder&&(o.holder=t.holder))}else f==="board.thread-removed"&&t.threadId&&(n.threads=n.threads.filter(o=>o.id!==t.threadId),n.posts=n.posts.filter(o=>o.threadId!==t.threadId),Array.isArray(n.removed)||(n.removed=[]),n.removed.includes(t.threadId)||n.removed.push(t.threadId));return n}function Q({now:d=()=>Date.now(),newId:i=null,state:n=null,onEvent:f=null}={}){const t=n&&Array.isArray(n.threads)?{threads:n.threads.map(e=>({...e})),posts:(n.posts||[]).map(e=>({...e})),...Array.isArray(n.removed)&&n.removed.length?{removed:[...n.removed]}:{}}:O(),o=new Set;let a=t.posts.length+t.threads.length;const m=e=>i?i(e):`${e}_${(++a).toString(36)}${Math.random().toString(36).slice(2,6)}`,u=(e,r)=>{const l={type:e,at:d(),...r};return f&&f(e,l),l},c=e=>t.threads.find(r=>r.id===e),p=e=>t.posts.find(r=>r.id===e),w=e=>t.threads.find(r=>r.kind==="task"&&r.taskId===e),h={openThread({id:e=null,taskId:r=null,kind:l="discussion",title:s="",by:y=v,status:g="open",ask:S=null,parent:b=null,holder:k=null}={}){if(l==="task"&&r){const $=w(r);if($)return $}const A={id:e||m("th"),kind:P.includes(l)?l:"discussion",taskId:r,title:j(s,200),by:y,status:D.includes(g)?g:"open",at:d(),posts:0,...S?{ask:S}:{},...b?{parent:b}:{},...k?{holder:k}:{}};return t.threads.push(A),u("board.thread",{thread:{...A}}),A},post({id:e=null,threadId:r,by:l,kind:s="note",text:y="",refs:g=[],replyTo:S=null,status:b="open",finding:k=null,ask:A=null,proposal:$=null}={}){const I=c(r);if(!I)throw new Error(`no thread ${r}`);if(e&&p(e))return p(e);const T={id:e||m("p"),threadId:r,by:String(l||v),kind:K.includes(s)?s:"note",text:j(y,U),refs:G(g),replyTo:S,status:X.includes(b)?b:"open",at:d(),...k?{finding:k}:{},...A?{ask:A}:{},...$&&typeof $=="object"?{proposal:$}:{}};t.posts.push(T),I.lastAt=T.at,I.lastBy=T.by,I.posts=(I.posts||0)+1,u("board.post",{post:{...T}});for(const z of o)z(T);return T},reply({postId:e,...r}){const l=p(e||r.replyTo);if(!l)throw new Error(`no post ${e}`);return h.post({...r,threadId:l.threadId,replyTo:l.id})},decide(e,r,l=x){const s=p(e);return!s||!["approved","rejected","proposed","open"].includes(r)?null:(s.status=r,s.decidedBy=l,s.decidedAt=d(),u("board.decision",{postId:e,status:r,by:l,at:s.decidedAt}),s)},setThreadStatus(e,r,l={}){const s=c(e);return!s||!D.includes(r)?null:(s.status=r,r!=="waiting"&&(s.waitingOn=null),Object.assign(s,l),u("board.thread-status",{threadId:e,status:r,...l}),s)},removeThread(e,{by:r=x}={}){const l=c(e);return!l||l.kind==="ask"&&l.status==="waiting"?null:(t.threads=t.threads.filter(s=>s.id!==e),t.posts=t.posts.filter(s=>s.threadId!==e),(t.removed||=[]).push(e),u("board.thread-removed",{threadId:e,by:r}),l)},ask({taskId:e=null,by:r,type:l="info",text:s,options:y=[],timeoutMs:g=0,title:S=""}={}){const b={type:L.includes(l)?l:"info",options:(Array.isArray(y)?y:[]).map(String).slice(0,6),timeoutMs:g},k=h.openThread({taskId:e,kind:"ask",title:S||j(s,120),by:r,status:"waiting",ask:b});k.waitingOn=x;const A=h.post({threadId:k.id,by:r,kind:"question",text:s,ask:b});return{thread:k,post:A}},answer(e,{id:r=null,text:l,by:s=x}={}){if(!c(e))return null;const g=h.post({id:r,threadId:e,by:s,kind:"answer",text:l});return h.setThreadStatus(e,"resolved",{answeredAt:g.at}),g},thread:c,threadForTask:w,threads:()=>t.threads.map(e=>({...e})),posts:(e=null)=>t.posts.filter(r=>!e||r.threadId===e).map(r=>({...r})),postById:p,waiting:()=>t.threads.filter(e=>e.kind==="ask"&&e.status==="waiting").map(e=>({...e})),state:()=>({threads:t.threads.map(e=>({...e})),posts:t.posts.map(e=>({...e})),...t.removed?.length?{removed:[...t.removed]}:{}}),add(e,{by:r=null}={}){let l=0;for(const s of Array.isArray(e)?e:[e]){if(!s||!s.text)continue;const y=s.taskId?w(s.taskId)||h.openThread({taskId:s.taskId,kind:"task",title:s.taskId}):t.threads.find(g=>g.kind==="discussion"&&g.title==="findings")||h.openThread({kind:"discussion",title:"findings"});h.post({id:s.id,threadId:y.id,by:r||s.role||v,kind:"finding",text:s.text,refs:s.refs,finding:{kind:s.kind||"claim",confidence:s.confidence??null}}),l+=1}return l},all:()=>t.posts.filter(e=>e.kind==="finding").map(_(t)),byTask:e=>h.all().filter(r=>r.taskId===e),byRole:e=>h.all().filter(r=>r.role===e),onFinding(e){const r=l=>{l.kind==="finding"&&e(_(t)(l))};return o.add(r),()=>o.delete(r)},get size(){return t.posts.filter(e=>e.kind==="finding").length}};return h}function _(d){return i=>{const n=d.threads.find(f=>f.id===i.threadId);return{id:i.id,kind:i.finding?.kind||"claim",text:i.text,refs:i.refs||[],confidence:i.finding?.confidence??null,role:i.by,taskId:n?.taskId||null,at:i.at,status:i.status,...i.finding?.prior?{prior:!0}:{}}}}function Z(d){const i=d&&Array.isArray(d.posts)?d:O();return i.posts.filter(n=>n.kind==="finding").map(_(i))}function ee(d,{taskIds:i=null,max:n=M,role:f=null}={}){const t=d&&typeof d.state=="function"?d.state():d&&Array.isArray(d.posts)?d:null,o=t?C(t,{taskIds:i,role:f}):H(d,i);if(!o.length)return"";const a=t?"The board so far":"Findings so far",m=o.join(`
3
+ `);if(m.length<=n)return`${a}:
4
+ ${m}`;const u=[];let c=0;for(let p=o.length-1;p>=0&&!(c+o[p].length+1>n);p-=1)u.unshift(o[p]),c+=o[p].length+1;return`${a} (${o.length-u.length} earlier lines omitted for length):
5
+ ${u.join(`
6
+ `)}`}function H(d,i){return(d||[]).filter(n=>!i||i.includes(n.taskId)).map(n=>`- [${n.kind}${n.role?` · ${n.role}`:""}${n.confidence!=null?` · ${Math.round(n.confidence*100)}%`:""}] ${n.text}${n.refs?.length?` (refs: ${n.refs.join(", ")})`:""}`)}function C(d,{taskIds:i,role:n}){const f=[],t=d.posts,o=d.threads.filter(a=>a.kind==="task"?!i||i.includes(a.taskId):a.kind==="ask"?a.status==="resolved"&&(!n||a.by===n||a.by===v):a.kind==="discussion");for(const a of o){const m=t.filter(c=>c.threadId===a.id&&c.status!=="rejected");if(!m.length)continue;f.push(`## ${a.kind}${a.by&&a.by!==v?` by ${a.by}`:""}: ${a.title}${a.holder?` (held by ${a.holder})`:""}${a.status==="resolved"&&a.kind==="ask"?" (answered)":""}`);const u=(c,p)=>{const w=[c.kind==="finding"?c.finding?.kind||"claim":c.kind,c.by,c.finding?.confidence!=null?`${Math.round(c.finding.confidence*100)}%`:null,c.status==="approved"?"APPROVED":c.status==="proposed"?"proposed":null,c.kind==="decision"||c.by===x?"SETTLED":null].filter(Boolean).join(" · ");f.push(`${" ".repeat(p)}- [${w}] ${c.text}${c.refs?.length?` (refs: ${c.refs.join(", ")})`:""}`);for(const h of m.filter(e=>e.replyTo===c.id))u(h,p+1)};for(const c of m.filter(p=>!p.replyTo))u(c,0)}return f}function te(d){return(d||[]).filter(i=>i.kind==="claim"&&i.text).map(i=>({text:i.text,refs:(i.refs||[]).map(n=>{const f=/^([a-z][a-z0-9_-]*):(?!\/\/)(.+)$/.exec(String(n));return f?{kind:f[1],id:f[2]}:{kind:"url",id:String(n)}}),by:i.role||"team",confidence:i.confidence}))}export{L as ASK_TYPES,M as BOARD_TEXT_MAX,B as FINDINGS_SCHEMA,N as FINDING_KINDS,E as MAX_FINDINGS_PER_TASK,U as MAX_POST_TEXT,x as PERSON,K as POST_KINDS,X as POST_STATUSES,v as RUNNER,P as THREAD_KINDS,D as THREAD_STATUSES,ee as boardText,Q as createBoard,O as emptyBoardState,W as findingsInstruction,Z as findingsOf,J as foldBoard,Y as parseFindings,te as toBriefClaims};