pantheon-opencode 1.5.0-beta.1 → 1.5.0-beta.3
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.
- package/README.md +44 -15
- package/README.pt-BR.md +39 -12
- package/package.json +7 -3
- package/plugin.json +1 -1
- package/pyproject.toml +57 -0
- package/scripts/code_mode_server.py +101 -36
- package/scripts/cost.mjs +30 -14
- package/scripts/install/opencode.mjs +6 -0
- package/scripts/install/plugin.mjs +3 -33
- package/scripts/manifest-inventory.mjs +410 -0
- package/scripts/mcp_persistence_server.py +518 -128
- package/scripts/package-evidence.mjs +242 -0
- package/scripts/probe-context-rehydrate.mjs +240 -0
- package/scripts/probe-pantheon-cost.mjs +304 -0
- package/scripts/release-beta-version.mjs +61 -60
- package/scripts/sync-tui.mjs +5 -27
- package/scripts/test-opencode-v1-v2-sandbox.sh +367 -96
- package/scripts/validation-policy.mjs +7 -7
- package/scripts/version-check.mjs +113 -108
- package/scripts/versioning.mjs +131 -88
- package/src/mcp/code_mode_server.py +101 -36
- package/src/mcp/mcp_persistence_server.py +518 -128
- package/src/pantheon/compaction-handoff.ts +304 -0
- package/src/pantheon/cost-command.ts +49 -32
- package/src/pantheon/delegate-manager.ts +285 -0
- package/src/pantheon/provider-capabilities.ts +221 -0
- package/src/pantheon/provider-stream-tracker.ts +182 -0
- package/src/pantheon/token-opt.ts +237 -11
- package/src/plugin-v2.ts +2 -14
- package/src/plugin.ts +3 -8
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
- package/.pantheon/code-mode/.gitkeep +0 -0
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-1.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-10.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-11.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-2.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-3.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-4.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-5.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-6.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-7.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-8.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-9.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/heartbeat.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/session.json +0 -11
- package/src/pantheon/delegate-task-adapter.ts +0 -444
|
@@ -23,7 +23,14 @@
|
|
|
23
23
|
* @module delegate-manager
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import { z } from 'zod'
|
|
26
27
|
import type { BackgroundJobBoard, BackgroundJobRecord } from './background-job-board.ts'
|
|
28
|
+
import type { DelegationToolset } from './delegation.ts'
|
|
29
|
+
import {
|
|
30
|
+
DELEGATION_DEFAULTS,
|
|
31
|
+
type DelegationClient,
|
|
32
|
+
readDelegationReport,
|
|
33
|
+
} from './delegation-finalize.ts'
|
|
27
34
|
import {
|
|
28
35
|
buildStopInstruction,
|
|
29
36
|
cappedSummary,
|
|
@@ -113,6 +120,13 @@ export function isDelegationEnabled(
|
|
|
113
120
|
return (env.PANTHEON_DELEGATION ?? '').trim().toLowerCase() !== 'off'
|
|
114
121
|
}
|
|
115
122
|
|
|
123
|
+
export type DelegateMode = 'native' | 'legacy'
|
|
124
|
+
export function resolveDelegateMode(
|
|
125
|
+
env: Record<string, string | undefined> = process.env,
|
|
126
|
+
): DelegateMode {
|
|
127
|
+
return (env.PANTHEON_DELEGATE_MODE ?? '').trim().toLowerCase() === 'native' ? 'native' : 'legacy'
|
|
128
|
+
}
|
|
129
|
+
|
|
116
130
|
// ─── Helpers ───────────────────────────────────────────────────────────
|
|
117
131
|
|
|
118
132
|
const LINE_MAX = 160
|
|
@@ -382,3 +396,274 @@ export function createDelegateManager(options: DelegateManagerOptions): Delegate
|
|
|
382
396
|
},
|
|
383
397
|
}
|
|
384
398
|
}
|
|
399
|
+
|
|
400
|
+
// Native delegation tools live with the manager so the plugin mounts the
|
|
401
|
+
// manager directly; there is intentionally no adapter or kill-switch wrapper.
|
|
402
|
+
const delegateArgs = {
|
|
403
|
+
prompt: z.string().min(1),
|
|
404
|
+
agent: z.string().min(1),
|
|
405
|
+
description: z.string().optional(),
|
|
406
|
+
read_only: z.boolean().optional(),
|
|
407
|
+
model: z.string().optional(),
|
|
408
|
+
} satisfies z.ZodRawShape
|
|
409
|
+
const readArgs = { id: z.string().min(1) } satisfies z.ZodRawShape
|
|
410
|
+
const listArgs = {} satisfies z.ZodRawShape
|
|
411
|
+
export interface ToolContextLike {
|
|
412
|
+
sessionID: string
|
|
413
|
+
agent?: string
|
|
414
|
+
}
|
|
415
|
+
export interface SessionTaskOptions {
|
|
416
|
+
client: DelegationClient
|
|
417
|
+
board: BackgroundJobBoard
|
|
418
|
+
outputDir?: string
|
|
419
|
+
promptTimeoutMs?: number
|
|
420
|
+
settleTimeoutMs?: number
|
|
421
|
+
}
|
|
422
|
+
export function parseModelRef(model: string): { id: string; providerID: string } | undefined {
|
|
423
|
+
const idx = model.indexOf('/')
|
|
424
|
+
return idx > 0 && idx < model.length - 1
|
|
425
|
+
? { providerID: model.slice(0, idx), id: model.slice(idx + 1) }
|
|
426
|
+
: undefined
|
|
427
|
+
}
|
|
428
|
+
export function extractOutputSection(md: string | undefined): string {
|
|
429
|
+
if (md === undefined) return ''
|
|
430
|
+
const at = md.indexOf('## Output')
|
|
431
|
+
const body = at < 0 ? md : md.slice(at + 9)
|
|
432
|
+
const errAt = body.indexOf('\n**Error**:')
|
|
433
|
+
return (errAt < 0 ? body : body.slice(0, errAt)).trim()
|
|
434
|
+
}
|
|
435
|
+
async function promptAccept(
|
|
436
|
+
client: DelegationClient,
|
|
437
|
+
taskID: string,
|
|
438
|
+
agent: string,
|
|
439
|
+
prompt: string,
|
|
440
|
+
model: string | undefined,
|
|
441
|
+
signal: AbortSignal | undefined,
|
|
442
|
+
timeoutMs: number,
|
|
443
|
+
): Promise<void> {
|
|
444
|
+
const modelRef = model === undefined ? undefined : parseModelRef(model)
|
|
445
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
446
|
+
try {
|
|
447
|
+
await Promise.race([
|
|
448
|
+
client.session
|
|
449
|
+
.promptAsync({
|
|
450
|
+
path: { id: taskID },
|
|
451
|
+
body: {
|
|
452
|
+
agent,
|
|
453
|
+
...(modelRef === undefined ? {} : { model: modelRef }),
|
|
454
|
+
parts: [{ type: 'text', text: prompt }],
|
|
455
|
+
},
|
|
456
|
+
...(signal === undefined ? {} : { signal }),
|
|
457
|
+
})
|
|
458
|
+
.then(undefined, (error: unknown) => {
|
|
459
|
+
throw new Error(
|
|
460
|
+
`promptAsync rejected: ${error instanceof Error ? error.message : String(error)}`,
|
|
461
|
+
)
|
|
462
|
+
}),
|
|
463
|
+
new Promise<never>((_, reject) => {
|
|
464
|
+
timer = setTimeout(
|
|
465
|
+
() => reject(new Error(`promptAsync timed out after ${timeoutMs}ms`)),
|
|
466
|
+
timeoutMs,
|
|
467
|
+
)
|
|
468
|
+
timer.unref?.()
|
|
469
|
+
}),
|
|
470
|
+
])
|
|
471
|
+
} finally {
|
|
472
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
export function createSessionTaskFn(options: SessionTaskOptions): NativeTaskFn {
|
|
476
|
+
const {
|
|
477
|
+
client,
|
|
478
|
+
board,
|
|
479
|
+
outputDir = DELEGATION_DEFAULTS.outputDir,
|
|
480
|
+
promptTimeoutMs = 60_000,
|
|
481
|
+
settleTimeoutMs = DELEGATION_DEFAULTS.timeoutMs,
|
|
482
|
+
} = options
|
|
483
|
+
return async ({ agent, prompt, model, signal, taskID }) => {
|
|
484
|
+
await promptAccept(client, taskID, agent, prompt, model, signal, promptTimeoutMs)
|
|
485
|
+
const terminal = await board.waitForTerminal(taskID, settleTimeoutMs)
|
|
486
|
+
const md = await readDelegationReport(outputDir, terminal)
|
|
487
|
+
return { content: extractOutputSection(md) || terminal.resultSummary || '' }
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
export interface NativeDelegateWiring {
|
|
491
|
+
board: BackgroundJobBoard
|
|
492
|
+
client: DelegationClient
|
|
493
|
+
outputDir?: string
|
|
494
|
+
env?: Record<string, string | undefined>
|
|
495
|
+
isRootSession: (sessionID: string) => boolean
|
|
496
|
+
registerChildSession?: (sessionID: string, parentID: string) => void
|
|
497
|
+
registerReadOnlySession?: (
|
|
498
|
+
sessionID: string,
|
|
499
|
+
info: { agent: string; readOnlyFlag?: boolean },
|
|
500
|
+
) => void
|
|
501
|
+
isReadOnlyAgent?: (agent: string) => boolean
|
|
502
|
+
agentModel?: (agent: string) => string | undefined
|
|
503
|
+
managerOptions?: Partial<
|
|
504
|
+
Omit<DelegateManagerOptions, 'board' | 'task' | 'parentSessionID' | 'env'>
|
|
505
|
+
>
|
|
506
|
+
stepCap?: StepCapTracker
|
|
507
|
+
}
|
|
508
|
+
export interface NativeDelegateToolset {
|
|
509
|
+
pantheon_delegate: {
|
|
510
|
+
description: string
|
|
511
|
+
args: typeof delegateArgs
|
|
512
|
+
execute(args: z.infer<z.ZodObject<typeof delegateArgs>>, ctx: ToolContextLike): Promise<string>
|
|
513
|
+
}
|
|
514
|
+
pantheon_delegation_read: {
|
|
515
|
+
description: string
|
|
516
|
+
args: typeof readArgs
|
|
517
|
+
execute(args: z.infer<z.ZodObject<typeof readArgs>>, ctx: ToolContextLike): Promise<string>
|
|
518
|
+
}
|
|
519
|
+
pantheon_delegation_list: {
|
|
520
|
+
description: string
|
|
521
|
+
args: typeof listArgs
|
|
522
|
+
execute(args: z.infer<z.ZodObject<typeof listArgs>>, ctx: ToolContextLike): Promise<string>
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
function shortFirstLine(text: string, max = 60): string {
|
|
526
|
+
const line =
|
|
527
|
+
text
|
|
528
|
+
.split('\n')
|
|
529
|
+
.map((item) => item.trim())
|
|
530
|
+
.find(Boolean) ?? ''
|
|
531
|
+
return line.length > max ? `${line.slice(0, max - 1)}…` : line
|
|
532
|
+
}
|
|
533
|
+
export function createNativeDelegateTools(wiring: NativeDelegateWiring): NativeDelegateToolset {
|
|
534
|
+
const {
|
|
535
|
+
board,
|
|
536
|
+
client,
|
|
537
|
+
env = process.env,
|
|
538
|
+
isRootSession,
|
|
539
|
+
registerChildSession,
|
|
540
|
+
registerReadOnlySession,
|
|
541
|
+
isReadOnlyAgent,
|
|
542
|
+
agentModel,
|
|
543
|
+
managerOptions = {},
|
|
544
|
+
stepCap,
|
|
545
|
+
} = wiring
|
|
546
|
+
const task = createSessionTaskFn({
|
|
547
|
+
client,
|
|
548
|
+
board,
|
|
549
|
+
...(wiring.outputDir === undefined ? {} : { outputDir: wiring.outputDir }),
|
|
550
|
+
...(managerOptions.timeoutMs === undefined
|
|
551
|
+
? {}
|
|
552
|
+
: { promptTimeoutMs: managerOptions.timeoutMs }),
|
|
553
|
+
})
|
|
554
|
+
const managers = new Map<string, DelegateManager>()
|
|
555
|
+
const managerFor = (parentSessionID: string): DelegateManager => {
|
|
556
|
+
const existing = managers.get(parentSessionID)
|
|
557
|
+
if (existing !== undefined) return existing
|
|
558
|
+
const manager = createDelegateManager({
|
|
559
|
+
...managerOptions,
|
|
560
|
+
board,
|
|
561
|
+
task,
|
|
562
|
+
parentSessionID,
|
|
563
|
+
env,
|
|
564
|
+
...(stepCap === undefined ? {} : { stepCap }),
|
|
565
|
+
})
|
|
566
|
+
managers.set(parentSessionID, manager)
|
|
567
|
+
return manager
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
pantheon_delegate: {
|
|
571
|
+
description: 'Dispatch a background agent as a child session and return a verified receipt.',
|
|
572
|
+
args: delegateArgs,
|
|
573
|
+
execute: async (args, ctx) => {
|
|
574
|
+
if (!isDelegationEnabled(env))
|
|
575
|
+
throw new Error('pantheon delegation disabled (PANTHEON_DELEGATION=off)')
|
|
576
|
+
if (!isRootSession(ctx.sessionID))
|
|
577
|
+
throw new Error(
|
|
578
|
+
`pantheon_delegate rejected: session ${ctx.sessionID} is a sub-session — only root sessions can delegate`,
|
|
579
|
+
)
|
|
580
|
+
const model = args.model ?? agentModel?.(args.agent)
|
|
581
|
+
let childID: string
|
|
582
|
+
try {
|
|
583
|
+
const modelRef = model === undefined ? undefined : parseModelRef(model)
|
|
584
|
+
const created = await client.session.create({
|
|
585
|
+
body: {
|
|
586
|
+
parentID: ctx.sessionID,
|
|
587
|
+
title: args.description ?? shortFirstLine(args.prompt),
|
|
588
|
+
...(modelRef === undefined ? {} : { model: modelRef }),
|
|
589
|
+
},
|
|
590
|
+
})
|
|
591
|
+
childID = created.id
|
|
592
|
+
} catch (error) {
|
|
593
|
+
return `pantheon_delegate failed: session.create rejected: ${error instanceof Error ? error.message : String(error)}`
|
|
594
|
+
}
|
|
595
|
+
registerChildSession?.(childID, ctx.sessionID)
|
|
596
|
+
if (args.read_only === true || isReadOnlyAgent?.(args.agent) === true)
|
|
597
|
+
registerReadOnlySession?.(childID, {
|
|
598
|
+
agent: args.agent,
|
|
599
|
+
...(args.read_only === undefined ? {} : { readOnlyFlag: args.read_only }),
|
|
600
|
+
})
|
|
601
|
+
const receipt = await managerFor(ctx.sessionID).launch({
|
|
602
|
+
agent: args.agent,
|
|
603
|
+
prompt: args.prompt,
|
|
604
|
+
...(args.description === undefined ? {} : { description: args.description }),
|
|
605
|
+
...(args.model === undefined ? {} : { model: args.model }),
|
|
606
|
+
taskID: childID,
|
|
607
|
+
})
|
|
608
|
+
return receipt.line
|
|
609
|
+
},
|
|
610
|
+
},
|
|
611
|
+
pantheon_delegation_read: {
|
|
612
|
+
description: 'Block until a delegation finishes, then return its verified report.',
|
|
613
|
+
args: readArgs,
|
|
614
|
+
execute: async (args, ctx) => {
|
|
615
|
+
if (!isDelegationEnabled(env))
|
|
616
|
+
throw new Error('pantheon delegation disabled (PANTHEON_DELEGATION=off)')
|
|
617
|
+
return managerFor(ctx.sessionID).read(args.id)
|
|
618
|
+
},
|
|
619
|
+
},
|
|
620
|
+
pantheon_delegation_list: {
|
|
621
|
+
description: 'List background delegations.',
|
|
622
|
+
args: listArgs,
|
|
623
|
+
execute: async (_args, ctx) => {
|
|
624
|
+
if (!isDelegationEnabled(env))
|
|
625
|
+
throw new Error('pantheon delegation disabled (PANTHEON_DELEGATION=off)')
|
|
626
|
+
const lines = await managerFor(ctx.sessionID).list()
|
|
627
|
+
return lines.length > 0 ? lines.join('\n') : 'No delegations.'
|
|
628
|
+
},
|
|
629
|
+
},
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
export interface PluginNativeDelegationWiring {
|
|
633
|
+
board: BackgroundJobBoard
|
|
634
|
+
client: DelegationClient
|
|
635
|
+
isRootSession: (sessionID: string) => boolean
|
|
636
|
+
registerChildSession: (sessionID: string, parentID: string) => void
|
|
637
|
+
registerReadOnlySession: (
|
|
638
|
+
sessionID: string,
|
|
639
|
+
info: { agent: string; readOnlyFlag?: boolean },
|
|
640
|
+
) => void
|
|
641
|
+
readOnlyAgents: ReadonlySet<string>
|
|
642
|
+
agentModels: Record<string, string | undefined>
|
|
643
|
+
stepCap: StepCapTracker
|
|
644
|
+
wallClockTimeoutMs?: number
|
|
645
|
+
finalizeDelegation: DelegationToolset['finalizeDelegation']
|
|
646
|
+
}
|
|
647
|
+
export type PluginNativeDelegation = NativeDelegateToolset & {
|
|
648
|
+
finalizeDelegation: DelegationToolset['finalizeDelegation']
|
|
649
|
+
}
|
|
650
|
+
export function buildPluginNativeDelegation(
|
|
651
|
+
wiring: PluginNativeDelegationWiring,
|
|
652
|
+
): PluginNativeDelegation {
|
|
653
|
+
return {
|
|
654
|
+
...createNativeDelegateTools({
|
|
655
|
+
board: wiring.board,
|
|
656
|
+
client: wiring.client,
|
|
657
|
+
isRootSession: wiring.isRootSession,
|
|
658
|
+
registerChildSession: wiring.registerChildSession,
|
|
659
|
+
registerReadOnlySession: wiring.registerReadOnlySession,
|
|
660
|
+
isReadOnlyAgent: (agent) => wiring.readOnlyAgents.has(agent.toLowerCase()),
|
|
661
|
+
agentModel: (agent) => wiring.agentModels[agent.toLowerCase()],
|
|
662
|
+
stepCap: wiring.stepCap,
|
|
663
|
+
...(wiring.wallClockTimeoutMs === undefined
|
|
664
|
+
? {}
|
|
665
|
+
: { managerOptions: { timeoutMs: wiring.wallClockTimeoutMs } }),
|
|
666
|
+
}),
|
|
667
|
+
finalizeDelegation: wiring.finalizeDelegation,
|
|
668
|
+
}
|
|
669
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact provider usage contract and the independent V1/V2 capability probes.
|
|
3
|
+
*
|
|
4
|
+
* This module deliberately does not inspect credentials, call a provider, read
|
|
5
|
+
* the TUI, calculate percentages, or derive token counts from text. A provider
|
|
6
|
+
* is supported only when it supplies the complete numeric contract below.
|
|
7
|
+
*
|
|
8
|
+
* @module provider-capabilities
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The only capability statuses exposed by the usage contract. */
|
|
12
|
+
export const USAGE_STATUS = {
|
|
13
|
+
SUPPORTED: 'SUPPORTED',
|
|
14
|
+
UNSUPPORTED: 'UNSUPPORTED',
|
|
15
|
+
} as const
|
|
16
|
+
|
|
17
|
+
export type UsageStatus = (typeof USAGE_STATUS)[keyof typeof USAGE_STATUS]
|
|
18
|
+
|
|
19
|
+
/** Exact token counters supplied by the provider. No totals are inferred. */
|
|
20
|
+
export interface ExactProviderUsage {
|
|
21
|
+
inputTokens: number
|
|
22
|
+
outputTokens: number
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Exact context limit supplied by the provider. */
|
|
26
|
+
export interface ExactProviderLimit {
|
|
27
|
+
contextTokens: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Minimum complete provider payload accepted by either capability probe.
|
|
32
|
+
* `resetAt`, when present, is an exact non-negative numeric provider value;
|
|
33
|
+
* date strings and other reset representations are unsupported.
|
|
34
|
+
*/
|
|
35
|
+
export interface ExactProviderUsageData {
|
|
36
|
+
sessionId: string
|
|
37
|
+
providerId: string
|
|
38
|
+
modelId: string
|
|
39
|
+
usage: ExactProviderUsage
|
|
40
|
+
limit: ExactProviderLimit
|
|
41
|
+
resetAt?: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Stream event metadata required for de-duplication and freshness ordering. */
|
|
45
|
+
export interface ProviderUsageEvent extends ExactProviderUsageData {
|
|
46
|
+
eventId: string
|
|
47
|
+
partId: string
|
|
48
|
+
/** Optional provider sequence. When supplied, it must be an integer. */
|
|
49
|
+
sequence?: number
|
|
50
|
+
/** Optional provider observation time in milliseconds or another numeric scale. */
|
|
51
|
+
observedAt?: number
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A complete snapshot that has passed the exact contract validation. */
|
|
55
|
+
export interface ProviderUsageSnapshot extends ProviderUsageEvent {}
|
|
56
|
+
|
|
57
|
+
export type CapabilityProbeVersion = 'v1' | 'v2'
|
|
58
|
+
|
|
59
|
+
export type CapabilityProbeReason =
|
|
60
|
+
| 'MISSING_SESSION_ID'
|
|
61
|
+
| 'MISSING_PROVIDER_ID'
|
|
62
|
+
| 'MISSING_MODEL_ID'
|
|
63
|
+
| 'MISSING_USAGE'
|
|
64
|
+
| 'MISSING_LIMIT'
|
|
65
|
+
| 'INVALID_USAGE'
|
|
66
|
+
| 'INVALID_LIMIT'
|
|
67
|
+
| 'INVALID_RESET'
|
|
68
|
+
|
|
69
|
+
export type ProviderCapabilityResult =
|
|
70
|
+
| {
|
|
71
|
+
apiVersion: CapabilityProbeVersion
|
|
72
|
+
status: typeof USAGE_STATUS.SUPPORTED
|
|
73
|
+
data: ExactProviderUsageData
|
|
74
|
+
}
|
|
75
|
+
| {
|
|
76
|
+
apiVersion: CapabilityProbeVersion
|
|
77
|
+
status: typeof USAGE_STATUS.UNSUPPORTED
|
|
78
|
+
reason: CapabilityProbeReason
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type UnknownRecord = Record<string, unknown>
|
|
82
|
+
|
|
83
|
+
function isRecord(value: unknown): value is UnknownRecord {
|
|
84
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function isNonEmptyString(value: unknown): value is string {
|
|
88
|
+
return typeof value === 'string' && value.trim().length > 0
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isFiniteNonNegativeNumber(value: unknown): value is number {
|
|
92
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function hasOnlyKeys(value: UnknownRecord, allowed: readonly string[]): boolean {
|
|
96
|
+
return Object.keys(value).every((key) => allowed.includes(key))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function unsupported(
|
|
100
|
+
apiVersion: CapabilityProbeVersion,
|
|
101
|
+
reason: CapabilityProbeReason,
|
|
102
|
+
): ProviderCapabilityResult {
|
|
103
|
+
return { apiVersion, status: USAGE_STATUS.UNSUPPORTED, reason }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Validate the complete exact payload without coercion or estimation.
|
|
108
|
+
*
|
|
109
|
+
* This is intentionally shared only as a validator. V1 and V2 entry points
|
|
110
|
+
* below remain separate capability probes and do not fall back to one another.
|
|
111
|
+
*/
|
|
112
|
+
function probeExactData(
|
|
113
|
+
apiVersion: CapabilityProbeVersion,
|
|
114
|
+
input: unknown,
|
|
115
|
+
): ProviderCapabilityResult {
|
|
116
|
+
if (!isRecord(input)) return unsupported(apiVersion, 'MISSING_SESSION_ID')
|
|
117
|
+
|
|
118
|
+
if (!isNonEmptyString(input.sessionId)) {
|
|
119
|
+
return unsupported(apiVersion, 'MISSING_SESSION_ID')
|
|
120
|
+
}
|
|
121
|
+
if (!isNonEmptyString(input.providerId)) {
|
|
122
|
+
return unsupported(apiVersion, 'MISSING_PROVIDER_ID')
|
|
123
|
+
}
|
|
124
|
+
if (!isNonEmptyString(input.modelId)) {
|
|
125
|
+
return unsupported(apiVersion, 'MISSING_MODEL_ID')
|
|
126
|
+
}
|
|
127
|
+
if (!isRecord(input.usage)) return unsupported(apiVersion, 'MISSING_USAGE')
|
|
128
|
+
if (!isRecord(input.limit)) return unsupported(apiVersion, 'MISSING_LIMIT')
|
|
129
|
+
if (!hasOnlyKeys(input.usage, ['inputTokens', 'outputTokens'])) {
|
|
130
|
+
return unsupported(apiVersion, 'INVALID_USAGE')
|
|
131
|
+
}
|
|
132
|
+
if (!hasOnlyKeys(input.limit, ['contextTokens'])) {
|
|
133
|
+
return unsupported(apiVersion, 'INVALID_LIMIT')
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const usage = input.usage
|
|
137
|
+
if (!isFiniteNonNegativeNumber(usage.inputTokens)) {
|
|
138
|
+
return unsupported(apiVersion, 'INVALID_USAGE')
|
|
139
|
+
}
|
|
140
|
+
if (!isFiniteNonNegativeNumber(usage.outputTokens)) {
|
|
141
|
+
return unsupported(apiVersion, 'INVALID_USAGE')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const limit = input.limit
|
|
145
|
+
if (!isFiniteNonNegativeNumber(limit.contextTokens)) {
|
|
146
|
+
return unsupported(apiVersion, 'INVALID_LIMIT')
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let resetAt: number | undefined
|
|
150
|
+
if ('reset' in input) return unsupported(apiVersion, 'INVALID_RESET')
|
|
151
|
+
if ('resetAt' in input) {
|
|
152
|
+
const value = input.resetAt
|
|
153
|
+
if (!isFiniteNonNegativeNumber(value)) return unsupported(apiVersion, 'INVALID_RESET')
|
|
154
|
+
resetAt = value
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const data: ExactProviderUsageData = {
|
|
158
|
+
sessionId: input.sessionId,
|
|
159
|
+
providerId: input.providerId,
|
|
160
|
+
modelId: input.modelId,
|
|
161
|
+
usage: {
|
|
162
|
+
inputTokens: usage.inputTokens,
|
|
163
|
+
outputTokens: usage.outputTokens,
|
|
164
|
+
},
|
|
165
|
+
limit: { contextTokens: limit.contextTokens },
|
|
166
|
+
}
|
|
167
|
+
if (resetAt !== undefined) data.resetAt = resetAt
|
|
168
|
+
|
|
169
|
+
return { apiVersion, status: USAGE_STATUS.SUPPORTED, data }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Probe the V1 exact payload shape supplied by a caller.
|
|
174
|
+
*
|
|
175
|
+
* V1 does not inherit V2 capability, credentials, cache, or lifecycle data.
|
|
176
|
+
* The caller must pass the exact payload after its host-specific extraction.
|
|
177
|
+
*/
|
|
178
|
+
export function probeV1Capability(input: unknown): ProviderCapabilityResult {
|
|
179
|
+
return probeExactData('v1', input)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Probe the V2 exact payload shape supplied by a caller.
|
|
184
|
+
*
|
|
185
|
+
* V2 is intentionally independent from V1: no V1 event, retry, cache, or
|
|
186
|
+
* fallback value is consulted when the exact payload is absent.
|
|
187
|
+
*/
|
|
188
|
+
export function probeV2Capability(input: unknown): ProviderCapabilityResult {
|
|
189
|
+
return probeExactData('v2', input)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Validate one complete stream event using the same exact data contract. */
|
|
193
|
+
export function validateProviderUsageEvent(input: unknown): ProviderUsageEvent | null {
|
|
194
|
+
if (!isRecord(input)) return null
|
|
195
|
+
if (!isNonEmptyString(input.eventId) || !isNonEmptyString(input.partId)) return null
|
|
196
|
+
|
|
197
|
+
const data = probeExactData('v1', input)
|
|
198
|
+
if (data.status !== USAGE_STATUS.SUPPORTED) return null
|
|
199
|
+
|
|
200
|
+
let sequence: number | undefined
|
|
201
|
+
if ('sequence' in input) {
|
|
202
|
+
const value = input.sequence
|
|
203
|
+
if (!isFiniteNonNegativeNumber(value) || !Number.isInteger(value)) return null
|
|
204
|
+
sequence = value
|
|
205
|
+
}
|
|
206
|
+
let observedAt: number | undefined
|
|
207
|
+
if ('observedAt' in input) {
|
|
208
|
+
const value = input.observedAt
|
|
209
|
+
if (!isFiniteNonNegativeNumber(value)) return null
|
|
210
|
+
observedAt = value
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const event: ProviderUsageEvent = {
|
|
214
|
+
...data.data,
|
|
215
|
+
eventId: input.eventId,
|
|
216
|
+
partId: input.partId,
|
|
217
|
+
}
|
|
218
|
+
if (sequence !== undefined) event.sequence = sequence
|
|
219
|
+
if (observedAt !== undefined) event.observedAt = observedAt
|
|
220
|
+
return event
|
|
221
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure provider stream usage tracker.
|
|
3
|
+
*
|
|
4
|
+
* The tracker stores only complete exact provider snapshots. It has no timers,
|
|
5
|
+
* polling, persistence, TUI dependency, provider client, credential fallback,
|
|
6
|
+
* token/cost estimation, or compaction/FSM integration.
|
|
7
|
+
*
|
|
8
|
+
* @module provider-stream-tracker
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
type ProviderUsageEvent,
|
|
13
|
+
type ProviderUsageSnapshot,
|
|
14
|
+
USAGE_STATUS,
|
|
15
|
+
type UsageStatus,
|
|
16
|
+
validateProviderUsageEvent,
|
|
17
|
+
} from './provider-capabilities.ts'
|
|
18
|
+
|
|
19
|
+
export type TrackerUpdateReason = 'PUBLISHED' | 'DUPLICATE' | 'STALE' | 'OUT_OF_SCOPE' | 'INVALID'
|
|
20
|
+
|
|
21
|
+
export interface ProviderStreamTrackerOptions {
|
|
22
|
+
/** Optional exact stream scope. Events from another stream are unsupported. */
|
|
23
|
+
sessionId?: string
|
|
24
|
+
providerId?: string
|
|
25
|
+
modelId?: string
|
|
26
|
+
/** Injectable sink called only after a complete snapshot is stored. */
|
|
27
|
+
onSnapshot?: (snapshot: ProviderUsageSnapshot) => void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ProviderStreamTrackerResult {
|
|
31
|
+
status: UsageStatus
|
|
32
|
+
published: boolean
|
|
33
|
+
reason: TrackerUpdateReason
|
|
34
|
+
snapshot?: ProviderUsageSnapshot
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ProviderStreamTracker {
|
|
38
|
+
/** Ingest one raw event without coercion or heuristic recovery. */
|
|
39
|
+
ingest(input: unknown): ProviderStreamTrackerResult
|
|
40
|
+
/** Read one complete snapshot for an isolated session/provider/model stream. */
|
|
41
|
+
getSnapshot(
|
|
42
|
+
sessionId: string,
|
|
43
|
+
providerId: string,
|
|
44
|
+
modelId: string,
|
|
45
|
+
): ProviderUsageSnapshot | undefined
|
|
46
|
+
/** Read all complete snapshots, each isolated by stream identity. */
|
|
47
|
+
snapshots(): ProviderUsageSnapshot[]
|
|
48
|
+
/** Remove all in-memory stream state. */
|
|
49
|
+
clear(): void
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface StreamState {
|
|
53
|
+
snapshot: ProviderUsageSnapshot
|
|
54
|
+
eventIds: Set<string>
|
|
55
|
+
partIds: Set<string>
|
|
56
|
+
orderKind?: 'sequence' | 'observedAt'
|
|
57
|
+
orderValue?: number
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function streamKey(sessionId: string, providerId: string, modelId: string): string {
|
|
61
|
+
return JSON.stringify([sessionId, providerId, modelId])
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function copySnapshot(snapshot: ProviderUsageSnapshot): ProviderUsageSnapshot {
|
|
65
|
+
const copy: ProviderUsageSnapshot = {
|
|
66
|
+
eventId: snapshot.eventId,
|
|
67
|
+
partId: snapshot.partId,
|
|
68
|
+
sessionId: snapshot.sessionId,
|
|
69
|
+
providerId: snapshot.providerId,
|
|
70
|
+
modelId: snapshot.modelId,
|
|
71
|
+
usage: { ...snapshot.usage },
|
|
72
|
+
limit: { ...snapshot.limit },
|
|
73
|
+
}
|
|
74
|
+
if (snapshot.resetAt !== undefined) copy.resetAt = snapshot.resetAt
|
|
75
|
+
if (snapshot.sequence !== undefined) copy.sequence = snapshot.sequence
|
|
76
|
+
if (snapshot.observedAt !== undefined) copy.observedAt = snapshot.observedAt
|
|
77
|
+
return copy
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function result(
|
|
81
|
+
status: UsageStatus,
|
|
82
|
+
reason: TrackerUpdateReason,
|
|
83
|
+
snapshot?: ProviderUsageSnapshot,
|
|
84
|
+
): ProviderStreamTrackerResult {
|
|
85
|
+
return snapshot === undefined
|
|
86
|
+
? { status, published: false, reason }
|
|
87
|
+
: { status, published: true, reason, snapshot: copySnapshot(snapshot) }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isInScope(event: ProviderUsageEvent, options: ProviderStreamTrackerOptions): boolean {
|
|
91
|
+
return (
|
|
92
|
+
(options.sessionId === undefined || options.sessionId === event.sessionId) &&
|
|
93
|
+
(options.providerId === undefined || options.providerId === event.providerId) &&
|
|
94
|
+
(options.modelId === undefined || options.modelId === event.modelId)
|
|
95
|
+
)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isStale(event: ProviderUsageEvent, state: StreamState): boolean {
|
|
99
|
+
if (event.sequence !== undefined) {
|
|
100
|
+
if (state.orderKind === 'sequence' && state.orderValue !== undefined) {
|
|
101
|
+
return event.sequence <= state.orderValue
|
|
102
|
+
}
|
|
103
|
+
return false
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (event.observedAt !== undefined) {
|
|
107
|
+
if (state.orderKind === 'observedAt' && state.orderValue !== undefined) {
|
|
108
|
+
return event.observedAt <= state.orderValue
|
|
109
|
+
}
|
|
110
|
+
return state.orderKind === 'sequence'
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return state.orderKind !== undefined
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function updateOrder(event: ProviderUsageEvent, state: StreamState): void {
|
|
117
|
+
if (event.sequence !== undefined) {
|
|
118
|
+
state.orderKind = 'sequence'
|
|
119
|
+
state.orderValue = event.sequence
|
|
120
|
+
} else if (event.observedAt !== undefined) {
|
|
121
|
+
state.orderKind = 'observedAt'
|
|
122
|
+
state.orderValue = event.observedAt
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Create an in-memory tracker. With no scope options, multiple streams are
|
|
128
|
+
* tracked independently by their session/provider/model identity.
|
|
129
|
+
*/
|
|
130
|
+
export function createProviderStreamTracker(
|
|
131
|
+
options: ProviderStreamTrackerOptions = {},
|
|
132
|
+
): ProviderStreamTracker {
|
|
133
|
+
const streams = new Map<string, StreamState>()
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
ingest(input: unknown): ProviderStreamTrackerResult {
|
|
137
|
+
const event = validateProviderUsageEvent(input)
|
|
138
|
+
if (event === null) return result(USAGE_STATUS.UNSUPPORTED, 'INVALID')
|
|
139
|
+
if (!isInScope(event, options)) return result(USAGE_STATUS.UNSUPPORTED, 'OUT_OF_SCOPE')
|
|
140
|
+
|
|
141
|
+
const key = streamKey(event.sessionId, event.providerId, event.modelId)
|
|
142
|
+
const state = streams.get(key)
|
|
143
|
+
if (state?.eventIds.has(event.eventId) || state?.partIds.has(event.partId)) {
|
|
144
|
+
return result(USAGE_STATUS.SUPPORTED, 'DUPLICATE')
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (state !== undefined && isStale(event, state)) {
|
|
148
|
+
state.eventIds.add(event.eventId)
|
|
149
|
+
state.partIds.add(event.partId)
|
|
150
|
+
return result(USAGE_STATUS.SUPPORTED, 'STALE')
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const nextState: StreamState = state ?? {
|
|
154
|
+
snapshot: event,
|
|
155
|
+
eventIds: new Set<string>(),
|
|
156
|
+
partIds: new Set<string>(),
|
|
157
|
+
}
|
|
158
|
+
nextState.snapshot = event
|
|
159
|
+
nextState.eventIds.add(event.eventId)
|
|
160
|
+
nextState.partIds.add(event.partId)
|
|
161
|
+
updateOrder(event, nextState)
|
|
162
|
+
streams.set(key, nextState)
|
|
163
|
+
|
|
164
|
+
const snapshot = copySnapshot(event)
|
|
165
|
+
options.onSnapshot?.(snapshot)
|
|
166
|
+
return result(USAGE_STATUS.SUPPORTED, 'PUBLISHED', snapshot)
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
getSnapshot(sessionId: string, providerId: string, modelId: string) {
|
|
170
|
+
const state = streams.get(streamKey(sessionId, providerId, modelId))
|
|
171
|
+
return state === undefined ? undefined : copySnapshot(state.snapshot)
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
snapshots() {
|
|
175
|
+
return [...streams.values()].map((state) => copySnapshot(state.snapshot))
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
clear() {
|
|
179
|
+
streams.clear()
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
}
|