pantheon-opencode 1.5.0-beta.9 → 1.5.1

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 (84) hide show
  1. package/AGENTS.md +14 -63
  2. package/CHANGELOG.md +326 -0
  3. package/README.md +77 -29
  4. package/README.pt-BR.md +5 -6
  5. package/commands/pantheon.md +1 -35
  6. package/package.json +2 -3
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +3 -5
  9. package/scripts/doctor.mjs +260 -5
  10. package/scripts/install/plugin.mjs +9 -12
  11. package/scripts/mcp_persistence_server.py +1 -1
  12. package/scripts/sync-tui.mjs +8 -11
  13. package/src/agents/apollo.md +1 -0
  14. package/src/agents/gaia.md +1 -0
  15. package/src/agents/mnemosyne.md +11 -1
  16. package/src/agents/zeus.md +10 -52
  17. package/src/instructions/memory-protocol.instructions.md +6 -3
  18. package/src/instructions/zeus-anti-stall.instructions.md +2 -4
  19. package/src/instructions/zeus-council-synthesis.instructions.md +3 -28
  20. package/src/instructions/zeus-timeout-retry.instructions.md +3 -28
  21. package/src/mcp/mcp_persistence_server.py +1 -1
  22. package/src/mcp/memory_mcp_server.py +81 -27
  23. package/src/pantheon/background-job-board.ts +4 -4
  24. package/src/pantheon/{delegation-compaction.ts → compaction-context.ts} +10 -100
  25. package/src/pantheon/cost-command.ts +1 -2
  26. package/src/pantheon/delegation-enforce.ts +59 -14
  27. package/src/pantheon/goal-loop.ts +1 -1
  28. package/src/pantheon/goal-store.ts +1 -1
  29. package/src/pantheon/idle-continuation.ts +4 -6
  30. package/src/pantheon/model-command.ts +1 -2
  31. package/src/pantheon/native-task-status.ts +2 -2
  32. package/src/pantheon/presets.d.mts +0 -20
  33. package/src/pantheon/presets.mjs +0 -64
  34. package/src/pantheon/session-guard.ts +2 -2
  35. package/src/pantheon/session-id.ts +30 -0
  36. package/src/pantheon/task-result-guard.ts +2 -3
  37. package/src/pantheon/todo-enforcer.ts +3 -3
  38. package/src/pantheon/tool-context.ts +23 -0
  39. package/src/pantheon/v2-bridge.ts +1 -4
  40. package/src/plugin-v2.ts +8 -21
  41. package/src/plugin.ts +61 -245
  42. package/src/plugins/pantheon-hooks.ts +2 -2
  43. package/src/plugins/tui/dist/tui.d.ts +229 -103
  44. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  45. package/src/plugins/tui/dist/tui.js +495 -333
  46. package/src/plugins/tui/package-lock.json +5 -2
  47. package/src/plugins/tui/package.json +5 -2
  48. package/src/plugins/tui/src/index.tsx +710 -409
  49. package/src/routing.yml +0 -16
  50. package/src/skills/context-compression/SKILL.md +1 -1
  51. package/scripts/generate-preset-docs.mjs +0 -300
  52. package/scripts/generate-prompts.sh +0 -222
  53. package/scripts/hash_verify.py +0 -192
  54. package/scripts/install/component.mjs +0 -24
  55. package/scripts/install/migrate-config.mjs +0 -302
  56. package/scripts/test-context-compression.sh +0 -169
  57. package/src/mcp/toon_codec.py +0 -491
  58. package/src/pantheon/auto-wake.ts +0 -85
  59. package/src/pantheon/chat-reminders.ts +0 -9
  60. package/src/pantheon/comment-checker.ts +0 -48
  61. package/src/pantheon/compaction-assert.ts +0 -160
  62. package/src/pantheon/compaction-handoff.ts +0 -304
  63. package/src/pantheon/cost-tracker.ts +0 -108
  64. package/src/pantheon/delegate-manager.ts +0 -766
  65. package/src/pantheon/delegation-classifier.ts +0 -307
  66. package/src/pantheon/delegation-finalize.ts +0 -406
  67. package/src/pantheon/delegation-notify.ts +0 -212
  68. package/src/pantheon/delegation-toast.ts +0 -73
  69. package/src/pantheon/delegation.ts +0 -1337
  70. package/src/pantheon/dispatch-guard.ts +0 -109
  71. package/src/pantheon/native-probe.ts +0 -234
  72. package/src/pantheon/permission-eval.ts +0 -284
  73. package/src/pantheon/preemptive-compact.ts +0 -76
  74. package/src/pantheon/provider-capabilities.ts +0 -221
  75. package/src/pantheon/provider-stream-tracker.ts +0 -182
  76. package/src/pantheon/retry-policy.ts +0 -212
  77. package/src/pantheon/step-cap.ts +0 -110
  78. package/src/pantheon/token-opt.ts +0 -689
  79. package/src/pantheon/toon-codec.ts +0 -481
  80. package/src/pantheon/v2-events.ts +0 -148
  81. package/src/pantheon/v2-hooks.ts +0 -287
  82. package/src/pantheon/v2-tool-definitions.ts +0 -331
  83. package/src/pantheon/zeus-delegate-with-retry.ts +0 -406
  84. package/src/plugins/tui/dist/tui.tsx +0 -2853
@@ -1,481 +0,0 @@
1
- /**
2
- * WS3 TOON codec (PR #94) — Token-Oriented Object Notation, TypeScript mirror.
3
- *
4
- * Minimal deterministic encoding for board signals, checkpoints and KV
5
- * payloads. Semantics identical to JSON; structurally smaller (no braces,
6
- * no per-key quotes, no commas); JSON fallback when the parser is
7
- * absent/fails. Savings are per payload class (~11% content-dominated
8
- * board records up to ~49% large tabular checkpoints — see
9
- * `docs/ws3-token-opt-measurements.md` for the reproducible table).
10
- * Byte-compatible with `src/mcp/toon_codec.py` on the
11
- * supported subset (null/bool/int/string, dicts, lists, uniform tables).
12
- *
13
- * Pure TypeScript — zero dependencies, no LLM, no external gateway.
14
- *
15
- * @module toon-codec
16
- */
17
-
18
- export const TABLE_MARKER = '@table '
19
-
20
- /** JSON-compatible value subset covered by the codec. */
21
- export type ToonValue =
22
- | null
23
- | boolean
24
- | number
25
- | string
26
- | { [key: string]: ToonValue }
27
- | ToonValue[]
28
-
29
- export interface ToonSizeReport {
30
- jsonChars: number
31
- toonChars: number
32
- ratio: number
33
- savedPct: number
34
- jsonTokens: number
35
- toonTokens: number
36
- tokenRatio: number
37
- tokenSavedPct: number
38
- }
39
-
40
- /** Default cap on nested-block depth accepted by `toonDecode` (DoS guard). */
41
- export const TOON_MAX_DEPTH = 100
42
-
43
- /** Default cap on input length accepted by `toonDecode` (DoS guard). */
44
- export const TOON_MAX_CHARS = 1000000
45
-
46
- const BARE_KEY_RE = /^[A-Za-z0-9_][A-Za-z0-9_.@+~/-]*$/
47
- const INT_RE = /^-?\d+$/
48
- const FLOAT_RE = /^-?(?:\d+\.\d+|\d+\.\d*[eE][+-]?\d+|\d+[eE][+-]?\d+)$/
49
- const KEYLIKE_RE = /^(?:"(?:[^"\\]|\\.)*"|[A-Za-z0-9_][A-Za-z0-9_.@+~/-]*)\s*:(?:\s+|$)/
50
- const RESERVED = new Set(['null', 'true', 'false', '{}', '[]'])
51
-
52
- function looksNumeric(text: string): boolean {
53
- return INT_RE.test(text) || FLOAT_RE.test(text)
54
- }
55
-
56
- /** Nominal chars-per-token ratio (same fixed basis as token-opt metering). */
57
- export const CHARS_PER_TOKEN = 4
58
-
59
- function charsToTokens(chars: number): number {
60
- if (chars <= 0) return 0
61
- return Math.ceil(chars / CHARS_PER_TOKEN)
62
- }
63
-
64
- function quote(text: string): string {
65
- return JSON.stringify(text)
66
- }
67
-
68
- function isBareValue(text: string, inTable = false): boolean {
69
- if (text === '' || text !== text.trim()) return false
70
- if (RESERVED.has(text) || looksNumeric(text)) return false
71
- // In table cells a bare `|` would split the row — quote such values.
72
- if (inTable && text.includes('|')) return false
73
- if (text.includes('"') || text.includes('\\') || text.includes('\n') || text.includes('\r')) {
74
- return false
75
- }
76
- return true
77
- }
78
-
79
- function encodeScalar(value: ToonValue, itemPosition = false, tableCell = false): string {
80
- if (value === null) return 'null'
81
- if (value === true) return 'true'
82
- if (value === false) return 'false'
83
- if (typeof value === 'number') return String(value)
84
- const text = String(value)
85
- if (isBareValue(text, tableCell)) {
86
- if (itemPosition && KEYLIKE_RE.test(text)) return quote(text)
87
- return text
88
- }
89
- return quote(text)
90
- }
91
-
92
- function encodeKey(key: string): string {
93
- return BARE_KEY_RE.test(key) ? key : quote(key)
94
- }
95
-
96
- function isPlainObject(value: ToonValue): value is { [key: string]: ToonValue } {
97
- return typeof value === 'object' && value !== null && !Array.isArray(value)
98
- }
99
-
100
- function isUniformDictList(value: ToonValue): value is { [key: string]: ToonValue }[] {
101
- if (!Array.isArray(value) || value.length === 0) return false
102
- if (!value.every((item) => isPlainObject(item))) return false
103
- const firstKeys = Object.keys(value[0] as { [key: string]: ToonValue })
104
- if (firstKeys.length === 0) return false
105
- return (value as { [key: string]: ToonValue }[]).every((item) => {
106
- const keys = Object.keys(item)
107
- return keys.length === firstKeys.length && keys.every((k, i) => k === firstKeys[i])
108
- })
109
- }
110
-
111
- /** Split a table row on `|` outside double quotes. */
112
- function splitCells(line: string): string[] {
113
- const cells: string[] = []
114
- let current = ''
115
- let inQuotes = false
116
- let escaped = false
117
- for (const char of line) {
118
- if (escaped) {
119
- current += char
120
- escaped = false
121
- } else if (char === '\\' && inQuotes) {
122
- current += char
123
- escaped = true
124
- } else if (char === '"') {
125
- current += char
126
- inQuotes = !inQuotes
127
- } else if (char === '|' && !inQuotes) {
128
- cells.push(current)
129
- current = ''
130
- } else {
131
- current += char
132
- }
133
- }
134
- cells.push(current)
135
- return cells
136
- }
137
-
138
- /** Encode a value to a TOON string (deterministic). */
139
- export function toonEncode(value: ToonValue): string {
140
- return encodeValue(value, 0).join('\n')
141
- }
142
-
143
- function encodeValue(value: ToonValue, indent: number): string[] {
144
- const pad = ' '.repeat(indent)
145
- if (value === null || typeof value !== 'object') return [pad + encodeScalar(value)]
146
- if (isPlainObject(value)) {
147
- const entries = Object.entries(value)
148
- if (entries.length === 0) return [`${pad}{}`]
149
- const lines: string[] = []
150
- for (const [key, item] of entries) {
151
- const encodedKey = encodeKey(key)
152
- if (item === null || typeof item !== 'object') {
153
- lines.push(`${pad}${encodedKey}: ${encodeScalar(item)}`)
154
- } else if (isPlainObject(item) && Object.keys(item).length === 0) {
155
- lines.push(`${pad}${encodedKey}: {}`)
156
- } else if (Array.isArray(item) && item.length === 0) {
157
- lines.push(`${pad}${encodedKey}: []`)
158
- } else {
159
- lines.push(`${pad}${encodedKey}:`)
160
- lines.push(...encodeValue(item, indent + 2))
161
- }
162
- }
163
- return lines
164
- }
165
- if (value.length === 0) return [`${pad}[]`]
166
- if (isUniformDictList(value)) {
167
- const keys = Object.keys(value[0] as { [key: string]: ToonValue })
168
- const lines = [pad + TABLE_MARKER + keys.map((k) => encodeKey(k)).join('|')]
169
- for (const item of value) {
170
- lines.push(
171
- pad +
172
- keys
173
- .map((k) =>
174
- encodeScalar((item as Record<string, ToonValue>)[k] as ToonValue, true, true),
175
- )
176
- .join('|'),
177
- )
178
- }
179
- return lines
180
- }
181
- return (value as ToonValue[]).flatMap((item) => encodeItem(item, indent))
182
- }
183
-
184
- function encodeItem(item: ToonValue, indent: number): string[] {
185
- const pad = ' '.repeat(indent)
186
- if (item === null || typeof item !== 'object') return [`${pad}- ${encodeScalar(item, true)}`]
187
- if (isPlainObject(item) && Object.keys(item).length === 0) return [`${pad}- {}`]
188
- if (Array.isArray(item) && item.length === 0) return [`${pad}- []`]
189
- const sub = encodeValue(item, indent + 2)
190
- const first = sub[0]?.trim() ?? ''
191
- return [`${pad}- ${first}`, ...sub.slice(1)]
192
- }
193
-
194
- function parseScalar(token: string): ToonValue {
195
- if (token === 'null') return null
196
- if (token === 'true') return true
197
- if (token === 'false') return false
198
- if (token === '{}') return {}
199
- if (token === '[]') return []
200
- if (INT_RE.test(token)) return Number.parseInt(token, 10)
201
- if (FLOAT_RE.test(token)) return Number.parseFloat(token)
202
- if (token.startsWith('"')) return JSON.parse(token) as ToonValue
203
- return token
204
- }
205
-
206
- function indentOf(line: string): number {
207
- return line.length - line.trimStart().length
208
- }
209
-
210
- /**
211
- * Split `key: value` on the FIRST colon (values may contain colons).
212
- * A quoted key is parsed FIRST (mirror of the py `raw_decode` fix): the
213
- * colon is searched AFTER the closing quote, so `{"a:b": 2}` splits into
214
- * key `a:b` instead of breaking inside the quotes.
215
- */
216
- function splitKeyValue(text: string): [string, string] {
217
- if (text.startsWith('"')) {
218
- let i = 1
219
- let closed = -1
220
- while (i < text.length) {
221
- const ch = text[i]
222
- if (ch === '\\') {
223
- i += 2
224
- continue
225
- }
226
- if (ch === '"') {
227
- closed = i
228
- break
229
- }
230
- i += 1
231
- }
232
- if (closed < 0) throw new Error(`TOON: line without ':' separator: ${JSON.stringify(text)}`)
233
- const rest = text.slice(closed + 1).trimStart()
234
- if (!rest.startsWith(':')) {
235
- throw new Error(`TOON: line without ':' separator: ${JSON.stringify(text)}`)
236
- }
237
- let key: unknown
238
- try {
239
- key = JSON.parse(text.slice(0, closed + 1)) as unknown
240
- } catch {
241
- throw new Error(`TOON: line without ':' separator: ${JSON.stringify(text)}`)
242
- }
243
- if (typeof key !== 'string' || key === '') {
244
- throw new Error(`TOON: empty key in line: ${JSON.stringify(text)}`)
245
- }
246
- return [key, rest.slice(1).trim()]
247
- }
248
- const idx = text.indexOf(':')
249
- if (idx < 0) throw new Error(`TOON: line without ':' separator: ${JSON.stringify(text)}`)
250
- const rawKey = text.slice(0, idx).trim()
251
- if (rawKey === '') throw new Error(`TOON: empty key in line: ${JSON.stringify(text)}`)
252
- const key = rawKey.startsWith('"') ? (JSON.parse(rawKey) as string) : rawKey
253
- return [key, text.slice(idx + 1).trim()]
254
- }
255
-
256
- /**
257
- * Decode a TOON string back to the identical value (throws on invalid).
258
- * `maxDepth`/`maxChars` are DoS guards: oversized inputs fail with a
259
- * controlled `Error` instead of a stack overflow / memory blowup.
260
- */
261
- export function toonDecode(
262
- text: string,
263
- maxDepth: number = TOON_MAX_DEPTH,
264
- maxChars: number = TOON_MAX_CHARS,
265
- ): ToonValue {
266
- if (text.length > maxChars) {
267
- throw new Error(`TOON: input too large (${text.length} chars > maxChars=${maxChars})`)
268
- }
269
- const lines = text.split('\n').filter((line) => line.trim() !== '')
270
- if (lines.length === 0) throw new Error('TOON: empty input')
271
- const first = lines[0]?.trim() ?? ''
272
- if (first.startsWith('{') || first.startsWith('[')) {
273
- try {
274
- return JSON.parse(text) as ToonValue
275
- } catch {
276
- throw new Error('TOON: invalid JSON fallback')
277
- }
278
- }
279
- const [value, nextIdx] = parseBlock(lines, 0, 0, 0, maxDepth)
280
- if (nextIdx !== lines.length) throw new Error(`TOON: trailing content at line ${nextIdx + 1}`)
281
- return value
282
- }
283
-
284
- function parseBlock(
285
- lines: string[],
286
- idx: number,
287
- indent: number,
288
- depth: number,
289
- maxDepth: number,
290
- ): [ToonValue, number] {
291
- if (depth > maxDepth) throw new Error(`TOON: maxDepth=${maxDepth} exceeded`)
292
- const stripped = lines[idx]?.trim() ?? ''
293
- if (stripped.startsWith('@table ')) return parseTable(lines, idx, indent)
294
- if (stripped.startsWith('- ') || stripped === '-')
295
- return parseList(lines, idx, indent, depth, maxDepth)
296
- return parseDict(lines, idx, indent, depth, maxDepth)
297
- }
298
-
299
- function parseTable(lines: string[], idx: number, indent: number): [ToonValue, number] {
300
- const headerLine = lines[idx]?.trim() ?? ''
301
- const header = headerLine.slice(TABLE_MARKER.length)
302
- const keys = splitCells(header).map((cell) =>
303
- cell.startsWith('"') ? (JSON.parse(cell) as string) : cell,
304
- )
305
- if (keys.length === 0 || keys.some((k) => k === '')) {
306
- throw new Error(`TOON: bad @table header at line ${idx + 1}`)
307
- }
308
- const rows: { [key: string]: ToonValue }[] = []
309
- idx += 1
310
- while (idx < lines.length && indentOf(lines[idx] as string) === indent) {
311
- const rowStripped = (lines[idx] as string).trim()
312
- if (rowStripped.startsWith('@table ') || rowStripped.startsWith('- ') || rowStripped === '-') {
313
- break
314
- }
315
- if (rowStripped.includes(':') && KEYLIKE_RE.test(rowStripped)) break
316
- const cells = splitCells(rowStripped)
317
- if (cells.length !== keys.length) throw new Error(`TOON: row width mismatch at line ${idx + 1}`)
318
- const row: { [key: string]: ToonValue } = {}
319
- keys.forEach((k, i) => {
320
- row[k] = parseScalar(cells[i] as string)
321
- })
322
- rows.push(row)
323
- idx += 1
324
- }
325
- return [rows, idx]
326
- }
327
-
328
- function parseDict(
329
- lines: string[],
330
- idx: number,
331
- indent: number,
332
- depth: number,
333
- maxDepth: number,
334
- ): [ToonValue, number] {
335
- const result: { [key: string]: ToonValue } = {}
336
- while (idx < lines.length) {
337
- const line = lines[idx] as string
338
- if (line.trim() === '' || indentOf(line) !== indent) break
339
- const stripped = line.trim()
340
- if (stripped.startsWith('@table ') || stripped.startsWith('- ') || stripped === '-') break
341
- const [key, rest] = splitKeyValue(stripped)
342
- if (rest === '') {
343
- idx += 1
344
- const nestedLine = idx < lines.length ? (lines[idx] as string) : undefined
345
- if (nestedLine === undefined || indentOf(nestedLine) <= indent) {
346
- throw new Error(`TOON: missing nested block for key ${JSON.stringify(key)}`)
347
- }
348
- const [nested, next] = parseBlock(lines, idx, indentOf(nestedLine), depth + 1, maxDepth)
349
- result[key] = nested
350
- idx = next
351
- } else {
352
- result[key] = parseScalar(rest)
353
- idx += 1
354
- }
355
- }
356
- return [result, idx]
357
- }
358
-
359
- function parseList(
360
- lines: string[],
361
- idx: number,
362
- indent: number,
363
- depth: number,
364
- maxDepth: number,
365
- ): [ToonValue, number] {
366
- const items: ToonValue[] = []
367
- while (idx < lines.length) {
368
- const line = lines[idx] as string
369
- if (indentOf(line) !== indent) break
370
- const stripped = line.trim()
371
- if (!stripped.startsWith('- ') && stripped !== '-') break
372
- const rest = stripped.slice(1).trim()
373
- if (rest === '') {
374
- idx += 1
375
- const nestedLine = idx < lines.length ? (lines[idx] as string) : undefined
376
- if (nestedLine === undefined || indentOf(nestedLine) <= indent) {
377
- throw new Error(`TOON: missing nested block in list at line ${idx + 1}`)
378
- }
379
- const [nested, next] = parseBlock(lines, idx, indentOf(nestedLine), depth + 1, maxDepth)
380
- items.push(nested)
381
- idx = next
382
- continue
383
- }
384
- if (KEYLIKE_RE.test(rest)) {
385
- const [key, subRest] = splitKeyValue(rest)
386
- const item: { [key: string]: ToonValue } = {}
387
- if (subRest === '') {
388
- idx += 1
389
- const nestedLine = idx < lines.length ? (lines[idx] as string) : undefined
390
- if (nestedLine === undefined || indentOf(nestedLine) <= indent) {
391
- throw new Error(`TOON: missing nested block for key ${JSON.stringify(key)}`)
392
- }
393
- const [nested, next] = parseBlock(lines, idx, indentOf(nestedLine), depth + 1, maxDepth)
394
- item[key] = nested
395
- idx = next
396
- } else {
397
- item[key] = parseScalar(subRest)
398
- idx += 1
399
- }
400
- while (idx < lines.length && indentOf(lines[idx] as string) > indent) {
401
- const cont = (lines[idx] as string).trim()
402
- const [subKey, subValue] = splitKeyValue(cont)
403
- if (subValue === '') {
404
- idx += 1
405
- const nestedLine = idx < lines.length ? (lines[idx] as string) : undefined
406
- if (nestedLine === undefined || indentOf(nestedLine) <= indent) {
407
- throw new Error(`TOON: missing nested block for key ${JSON.stringify(subKey)}`)
408
- }
409
- const [nested, next] = parseBlock(lines, idx, indentOf(nestedLine), depth + 1, maxDepth)
410
- item[subKey] = nested
411
- idx = next
412
- } else {
413
- item[subKey] = parseScalar(subValue)
414
- idx += 1
415
- }
416
- }
417
- items.push(item)
418
- } else {
419
- items.push(parseScalar(rest))
420
- idx += 1
421
- }
422
- }
423
- return [items, idx]
424
- }
425
-
426
- /**
427
- * Decode TOON, falling back to JSON (mirrors "parser absent" mode).
428
- * Throws a consistent `TOON:` error when the input is neither valid TOON
429
- * nor valid JSON (never leaks the raw JSON parser message).
430
- */
431
- export function toonDecodeAuto(
432
- text: string,
433
- maxDepth: number = TOON_MAX_DEPTH,
434
- maxChars: number = TOON_MAX_CHARS,
435
- ): ToonValue {
436
- const stripped = text.trim()
437
- if (stripped.startsWith('{') || stripped.startsWith('[')) {
438
- try {
439
- return JSON.parse(text) as ToonValue
440
- } catch {
441
- throw new Error('TOON: invalid JSON fallback')
442
- }
443
- }
444
- try {
445
- return toonDecode(text, maxDepth, maxChars)
446
- } catch {
447
- try {
448
- return JSON.parse(text) as ToonValue
449
- } catch {
450
- throw new Error(
451
- `TOON: invalid input (neither TOON nor JSON): ${JSON.stringify(stripped.slice(0, 60))}`,
452
- )
453
- }
454
- }
455
- }
456
-
457
- /**
458
- * Compare JSON vs TOON sizes for a value.
459
- * Reports BOTH chars and tokens: token ratios on tiny payloads suffer
460
- * ceiling bias (`ceil` rounds 161→41 vs 143→36), so the char columns are
461
- * the honest basis and the token columns show what metering will debit.
462
- * Per-class numbers: see `docs/ws3-token-opt-measurements.md`.
463
- */
464
- export function toonSizeReport(value: ToonValue): ToonSizeReport {
465
- const compactJson = JSON.stringify(value)
466
- const toon = toonEncode(value)
467
- const ratio = compactJson.length > 0 ? toon.length / compactJson.length : 1
468
- const jsonTokens = charsToTokens(compactJson.length)
469
- const toonTokens = charsToTokens(toon.length)
470
- const tokenRatio = jsonTokens > 0 ? toonTokens / jsonTokens : 1
471
- return {
472
- jsonChars: compactJson.length,
473
- toonChars: toon.length,
474
- ratio: Math.round(ratio * 10000) / 10000,
475
- savedPct: Math.round((1 - ratio) * 10000) / 100,
476
- jsonTokens,
477
- toonTokens,
478
- tokenRatio: Math.round(tokenRatio * 10000) / 10000,
479
- tokenSavedPct: Math.round((1 - tokenRatio) * 10000) / 100,
480
- }
481
- }
@@ -1,148 +0,0 @@
1
- /**
2
- * V2 Event Handlers — Pantheon event subscriptions for the V2 plugin API.
3
- *
4
- * Subscribes to session lifecycle events (created, idle, error, compacted)
5
- * and routes them to the appropriate subsystem:
6
- * - session.created → seed session hierarchy + root sessions
7
- * - session.idle → delegation finalize / goal loop / todo enforcer
8
- * - session.error → delegation finalize as error
9
- * - session.compacted → todo preserve / compaction context
10
- *
11
- * These handlers are PURE — they depend only on structural interfaces,
12
- * not on the V1 PluginInput or V2 PluginContext.
13
- *
14
- * @module pantheon/v2-events
15
- */
16
-
17
- import type { BackgroundJobBoard } from './background-job-board.ts'
18
- import type { FinalizeInput } from './delegation-finalize.ts'
19
- import type { DelegationEventDeps, DelegationEventLike } from './delegation-notify.ts'
20
- import { handleDelegationEvent } from './delegation-notify.ts'
21
- import type { GoalLoopLike, TodoEnforcerLike } from './idle-continuation.ts'
22
- import { createIdleDispatcher, type IdleDispatcher } from './idle-continuation.ts'
23
- import { createPantheonLogger } from './logger.ts'
24
-
25
- const log = createPantheonLogger({ module: 'pantheon-v2-events' })
26
-
27
- // ─── Types ───────────────────────────────────────────────────────────────
28
-
29
- /**
30
- * Structural session info from session.created events.
31
- */
32
- export interface SessionInfo {
33
- id: string
34
- parentID?: string
35
- }
36
-
37
- /**
38
- * Structural event from the V2 event stream.
39
- */
40
- export interface V2SessionEvent {
41
- type: string
42
- properties?: Record<string, unknown>
43
- }
44
-
45
- /**
46
- * Dependencies for the V2 event dispatcher.
47
- */
48
- export interface V2EventDeps {
49
- board: BackgroundJobBoard
50
- finalize: (childSessionID: string, opts: FinalizeInput) => Promise<unknown>
51
- goalLoop: GoalLoopLike
52
- todoEnforcer: TodoEnforcerLike
53
- /** Callback to register a session in the hierarchy. */
54
- registerSession?: (info: SessionInfo) => void
55
- /** Callback to add a session as root. */
56
- addRootSession?: (sessionID: string) => void
57
- }
58
-
59
- /**
60
- * V2 Event Dispatcher — routes session events to subsystems.
61
- */
62
- export interface V2EventDispatcher {
63
- /** Process a session event. Returns true if handled. */
64
- handleEvent(event: V2SessionEvent): Promise<boolean>
65
- /** Cleanup subscriptions. */
66
- dispose(): void
67
- }
68
-
69
- // ─── Implementation ──────────────────────────────────────────────────────
70
-
71
- /**
72
- * Create the V2 event dispatcher. Routes session lifecycle events to
73
- * delegation finalize, goal loop, and todo enforcer.
74
- *
75
- * Usage:
76
- * ```ts
77
- * const dispatcher = createV2EventDispatcher(deps)
78
- * // In event subscription loop:
79
- * for await (const event of ctx.event.subscribe(...)) {
80
- * await dispatcher.handleEvent(event)
81
- * }
82
- * ```
83
- */
84
- export function createV2EventDispatcher(deps: V2EventDeps): V2EventDispatcher {
85
- const delegationDeps: DelegationEventDeps = {
86
- board: deps.board,
87
- finalize: deps.finalize,
88
- }
89
- const idleDispatcher: IdleDispatcher = createIdleDispatcher({
90
- goalLoop: deps.goalLoop,
91
- todoEnforcer: deps.todoEnforcer,
92
- })
93
-
94
- return {
95
- handleEvent: async (event: V2SessionEvent): Promise<boolean> => {
96
- try {
97
- // session.created → seed hierarchy + board put-if-absent for native children
98
- if (event.type === 'session.created') {
99
- const info = event.properties?.info as SessionInfo | undefined
100
- if (info) {
101
- deps.registerSession?.(info)
102
- if (info.parentID === undefined) {
103
- deps.addRootSession?.(info.id)
104
- } else {
105
- // Native task(background=true) child: register on the board
106
- // atomically (skip if V1 idle hook or re-dispatch already claimed it).
107
- try {
108
- await deps.board.registerLaunchIfAbsent({
109
- taskID: info.id,
110
- parentSessionID: info.parentID,
111
- agent: 'native',
112
- description: `native child ${info.id}`,
113
- })
114
- } catch (err) {
115
- // The per-agent concurrency limit can refuse the launch. Do not
116
- // abort the rest of the handler: this child is simply not
117
- // mirrored on the board, while finalize/idle dispatch for every
118
- // other event must still run.
119
- log.warn(`[Pantheon V2] native child ${info.id} not mirrored on board:`, err)
120
- }
121
- }
122
- }
123
- }
124
-
125
- // Delegate to handleDelegationEvent (covers idle + error for board children)
126
- const delegated = await handleDelegationEvent(event as DelegationEventLike, delegationDeps)
127
-
128
- // Non-board idle → idle dispatcher (goal loop / todo enforcer)
129
- if (!delegated && event.type === 'session.idle') {
130
- const sessionID = event.properties?.sessionID as string | undefined
131
- if (sessionID) {
132
- await idleDispatcher.onIdle(sessionID)
133
- }
134
- }
135
-
136
- return delegated
137
- } catch (err) {
138
- log.error('[Pantheon V2] Event handling failed:', err)
139
- return false
140
- }
141
- },
142
-
143
- dispose: () => {
144
- // No persistent subscriptions to clean up — the event stream
145
- // lifecycle is managed by the caller.
146
- },
147
- }
148
- }