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
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compaction handoff coordinator.
|
|
3
|
+
*
|
|
4
|
+
* Coordinates the handoff of a compaction checkpoint from in-memory state to
|
|
5
|
+
* durable persistence. The coordinator is deliberately dependency-free: it
|
|
6
|
+
* does not import plugin, board, MCP, hooks, or provider modules.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface HandoffRecord {
|
|
10
|
+
digest: string
|
|
11
|
+
payload: string
|
|
12
|
+
version: number
|
|
13
|
+
sessionId: string
|
|
14
|
+
leaseToken: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PersistencePort {
|
|
18
|
+
prepare(input: HandoffRecord): Promise<void>
|
|
19
|
+
read(sessionId: string, key: string): Promise<HandoffRecord | null>
|
|
20
|
+
commit(sessionId: string, key: string, record: HandoffRecord): Promise<void>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface MemoryPort {
|
|
24
|
+
publishImmutable(sessionId: string, key: string, record: HandoffRecord): Promise<void>
|
|
25
|
+
readByIdempotencyKey(key: string): Promise<HandoffRecord | null>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type HandoffStatus =
|
|
29
|
+
| 'COMMITTED'
|
|
30
|
+
| 'UNAVAILABLE'
|
|
31
|
+
| 'CONFLICT'
|
|
32
|
+
| 'NOT_SUPPORTED'
|
|
33
|
+
| 'INVALID_INPUT'
|
|
34
|
+
|
|
35
|
+
/** Maximum allowed integer version value. */
|
|
36
|
+
export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
|
|
37
|
+
|
|
38
|
+
/** Maximum encoded payload size in bytes (128 KiB). */
|
|
39
|
+
export const MAX_PAYLOAD_BYTES = 65_536
|
|
40
|
+
|
|
41
|
+
/** Maximum length of URL-safe identifiers. */
|
|
42
|
+
export const MAX_ID_LENGTH = 128
|
|
43
|
+
|
|
44
|
+
const URL_SAFE_PATTERN = /^[A-Za-z0-9._~-]+$/
|
|
45
|
+
const DIGEST_PATTERN = /^[a-f0-9]{64}$/
|
|
46
|
+
|
|
47
|
+
/** Validate a URL-safe identifier: 1-128 chars, no control characters. */
|
|
48
|
+
function isValidIdentifier(value: unknown): value is string {
|
|
49
|
+
if (typeof value !== 'string') {
|
|
50
|
+
return false
|
|
51
|
+
}
|
|
52
|
+
if (value.length < 1 || value.length > MAX_ID_LENGTH) {
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
55
|
+
if (value.length > 0 && !URL_SAFE_PATTERN.test(value)) {
|
|
56
|
+
return false
|
|
57
|
+
}
|
|
58
|
+
return true
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Validate a lease token: 1-128 chars, no control characters. */
|
|
62
|
+
function isValidLeaseToken(value: unknown): value is string {
|
|
63
|
+
if (typeof value !== 'string') {
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
if (value.length < 1 || value.length > MAX_ID_LENGTH) {
|
|
67
|
+
return false
|
|
68
|
+
}
|
|
69
|
+
for (const char of value) {
|
|
70
|
+
const code = char.charCodeAt(0)
|
|
71
|
+
if (code < 0x20 || code === 0x7f) {
|
|
72
|
+
return false
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Validate a positive integer version within the safe integer range. */
|
|
79
|
+
function isValidVersion(value: unknown): value is number {
|
|
80
|
+
return (
|
|
81
|
+
typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= MAX_SAFE_INTEGER
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Validate a 64-character lowercase hex digest. */
|
|
86
|
+
function isValidDigest(value: unknown): value is string {
|
|
87
|
+
return typeof value === 'string' && DIGEST_PATTERN.test(value)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Validate that a payload is UTF-8 encodable and contains no NUL or control
|
|
92
|
+
* characters (tab, LF, and CR are permitted).
|
|
93
|
+
*/
|
|
94
|
+
function isValidPayload(value: unknown): value is string {
|
|
95
|
+
if (typeof value !== 'string') {
|
|
96
|
+
return false
|
|
97
|
+
}
|
|
98
|
+
if (value.length < 1 || value.length > MAX_PAYLOAD_BYTES) {
|
|
99
|
+
return false
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const bytes = Buffer.byteLength(value, 'utf8')
|
|
103
|
+
if (bytes < 1 || bytes > MAX_PAYLOAD_BYTES) {
|
|
104
|
+
return false
|
|
105
|
+
}
|
|
106
|
+
if (value.includes('\0')) {
|
|
107
|
+
return false
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
for (const char of value) {
|
|
111
|
+
const code = char.charCodeAt(0)
|
|
112
|
+
if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
|
|
113
|
+
return false
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return true
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Compute the digest over the exact UTF-8 encoded bytes of a payload.
|
|
121
|
+
*/
|
|
122
|
+
export function computeDigest(payload: string): string {
|
|
123
|
+
const bytes = Buffer.from(payload, 'utf8')
|
|
124
|
+
let hash = ''
|
|
125
|
+
for (const byte of bytes) {
|
|
126
|
+
hash += byte.toString(16).padStart(2, '0')
|
|
127
|
+
}
|
|
128
|
+
return hash
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Create a result describing a failed validation. */
|
|
132
|
+
function invalid(message: string): { status: 'INVALID_INPUT'; message: string } {
|
|
133
|
+
return { status: 'INVALID_INPUT', message }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Create a result describing a missing dependency. */
|
|
137
|
+
function notSupported(): { status: 'NOT_SUPPORTED' } {
|
|
138
|
+
return { status: 'NOT_SUPPORTED' }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Create a result describing a conflict. */
|
|
142
|
+
function conflict(message: string): { status: 'CONFLICT'; message: string } {
|
|
143
|
+
return { status: 'CONFLICT', message }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Create a result describing an unavailable memory port. */
|
|
147
|
+
function unavailable(message: string): { status: 'UNAVAILABLE'; message: string } {
|
|
148
|
+
return { status: 'UNAVAILABLE', message }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Create a successful committed result. */
|
|
152
|
+
function committed(digest: string): { status: 'COMMITTED'; digest: string } {
|
|
153
|
+
return { status: 'COMMITTED', digest }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Compaction handoff coordinator.
|
|
158
|
+
*
|
|
159
|
+
* The coordinator drives the handoff FSM:
|
|
160
|
+
*
|
|
161
|
+
* no record -> prepare -> PREPARED -> memory.publishImmutable
|
|
162
|
+
* -> memory.readByIdempotencyKey -> persistence.commit -> COMMITTED
|
|
163
|
+
*
|
|
164
|
+
* It never retries after memory becomes unavailable; the PREPARED state is
|
|
165
|
+
* left intact for a later explicit attempt.
|
|
166
|
+
*/
|
|
167
|
+
export class CompactionHandoffCoordinator {
|
|
168
|
+
private readonly persistence: PersistencePort | undefined
|
|
169
|
+
private readonly memory: MemoryPort | undefined
|
|
170
|
+
|
|
171
|
+
constructor(persistence?: PersistencePort, memory?: MemoryPort) {
|
|
172
|
+
this.persistence = persistence
|
|
173
|
+
this.memory = memory
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Attempt to hand off a compaction checkpoint.
|
|
178
|
+
*
|
|
179
|
+
* Returns immediately with INVALID_INPUT if any argument fails validation.
|
|
180
|
+
* Returns NOT_SUPPORTED if either required port is missing.
|
|
181
|
+
* Returns CONFLICT for digest or lease/version mismatches.
|
|
182
|
+
* Returns UNAVAILABLE if the memory port cannot publish/read the record.
|
|
183
|
+
* Returns COMMITTED when the record is durably committed.
|
|
184
|
+
*/
|
|
185
|
+
async prepare(
|
|
186
|
+
sessionId: string,
|
|
187
|
+
idempotencyKey: string,
|
|
188
|
+
leaseToken: string,
|
|
189
|
+
version: number,
|
|
190
|
+
digest: string,
|
|
191
|
+
payload: string,
|
|
192
|
+
): Promise<{ status: HandoffStatus; key?: string; digest?: string; message?: string }> {
|
|
193
|
+
// Validation first: no port calls are made before this block completes.
|
|
194
|
+
if (
|
|
195
|
+
!isValidIdentifier(sessionId) ||
|
|
196
|
+
!isValidIdentifier(idempotencyKey) ||
|
|
197
|
+
!isValidLeaseToken(leaseToken) ||
|
|
198
|
+
!isValidVersion(version) ||
|
|
199
|
+
!isValidDigest(digest) ||
|
|
200
|
+
!isValidPayload(payload)
|
|
201
|
+
) {
|
|
202
|
+
return invalid('Invalid handoff input')
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (this.persistence === undefined || this.memory === undefined) {
|
|
206
|
+
return notSupported()
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const _key = `${sessionId}:${idempotencyKey}`
|
|
210
|
+
|
|
211
|
+
// Check for an existing committed record before preparing a new one.
|
|
212
|
+
const existingRecord = await this.persistence.read(sessionId, idempotencyKey)
|
|
213
|
+
if (existingRecord !== null) {
|
|
214
|
+
if (existingRecord.digest === digest && existingRecord.sessionId === sessionId) {
|
|
215
|
+
// Idempotent replay: same digest and session. Verify lease/version match.
|
|
216
|
+
if (existingRecord.leaseToken !== leaseToken || existingRecord.version !== version) {
|
|
217
|
+
return conflict('Stale lease or version')
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Verify the record is also in memory. If missing, try to recover by publishing once.
|
|
221
|
+
let memoryRecord: HandoffRecord | null = null
|
|
222
|
+
try {
|
|
223
|
+
memoryRecord = await this.memory.readByIdempotencyKey(idempotencyKey)
|
|
224
|
+
} catch {
|
|
225
|
+
return unavailable('Memory port unavailable')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (memoryRecord === null) {
|
|
229
|
+
// Recovery: memory lost the record but persistence has it. Publish once.
|
|
230
|
+
try {
|
|
231
|
+
await this.memory.publishImmutable(sessionId, idempotencyKey, existingRecord)
|
|
232
|
+
} catch (_error) {
|
|
233
|
+
return unavailable('Memory port unavailable')
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
memoryRecord = await this.memory.readByIdempotencyKey(idempotencyKey)
|
|
237
|
+
} catch (_error) {
|
|
238
|
+
return unavailable('Memory port unavailable')
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (memoryRecord === null) {
|
|
243
|
+
return unavailable('Record not found in memory')
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
await this.persistence.commit(sessionId, idempotencyKey, existingRecord)
|
|
247
|
+
return committed(memoryRecord.digest)
|
|
248
|
+
}
|
|
249
|
+
// Different digest or session: conflict.
|
|
250
|
+
return conflict('Digest or session mismatch')
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Phase 1: prepare in persistence (PREPARED).
|
|
254
|
+
await this.persistence.prepare({ digest, payload, version, sessionId, leaseToken })
|
|
255
|
+
|
|
256
|
+
// Phase 2: publish the record to memory. If memory is unavailable, the
|
|
257
|
+
// coordinator stays in PREPARED and never retries automatically.
|
|
258
|
+
try {
|
|
259
|
+
await this.memory.publishImmutable(sessionId, idempotencyKey, {
|
|
260
|
+
digest,
|
|
261
|
+
payload,
|
|
262
|
+
version,
|
|
263
|
+
sessionId,
|
|
264
|
+
leaseToken,
|
|
265
|
+
})
|
|
266
|
+
} catch (_error) {
|
|
267
|
+
return unavailable('Memory port unavailable')
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Phase 3: read back from memory by idempotency key.
|
|
271
|
+
let memoryRecord: HandoffRecord | null = null
|
|
272
|
+
try {
|
|
273
|
+
memoryRecord = await this.memory.readByIdempotencyKey(idempotencyKey)
|
|
274
|
+
} catch (_error) {
|
|
275
|
+
return unavailable('Memory port unavailable')
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (memoryRecord === null) {
|
|
279
|
+
return unavailable('Record not found in memory')
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Stale lease or version check.
|
|
283
|
+
if (memoryRecord.leaseToken !== leaseToken || memoryRecord.version !== version) {
|
|
284
|
+
return conflict('Stale lease or version')
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Idempotent replay: same key and session is a success.
|
|
288
|
+
// The memory record is authoritative for recovery after crash.
|
|
289
|
+
if (memoryRecord.sessionId === sessionId) {
|
|
290
|
+
// Phase 4: commit to persistence.
|
|
291
|
+
try {
|
|
292
|
+
await this.persistence.commit(sessionId, idempotencyKey, memoryRecord)
|
|
293
|
+
} catch (_error) {
|
|
294
|
+
return conflict('Persistence commit failed')
|
|
295
|
+
}
|
|
296
|
+
return committed(memoryRecord.digest)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Same key, different digest or session: conflict.
|
|
300
|
+
return conflict('Digest or session mismatch')
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export default CompactionHandoffCoordinator
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* Token Command — `pantheon_cost` structural tool: token visibility for
|
|
3
|
+
* delegation traffic, straight from opencode.db.
|
|
4
4
|
*
|
|
5
|
-
* Reads the opencode session database READ-ONLY (sum
|
|
6
|
-
*
|
|
5
|
+
* Reads the opencode session database READ-ONLY (sum tokens by agent and
|
|
6
|
+
* phase over the last N days → markdown table). Zero new dependencies:
|
|
7
7
|
* - primary path: node:sqlite (DatabaseSync, readOnly) — node ≥ 22.5;
|
|
8
|
-
* - fallback: spawn scripts/cost.mjs
|
|
9
|
-
* direct import is unavailable;
|
|
8
|
+
* - CLI fallback: spawn scripts/cost.mjs with its explicit flag-based
|
|
9
|
+
* interface when the direct import is unavailable;
|
|
10
10
|
* - missing/unreadable db → FRIENDLY error string, never a crash (tools
|
|
11
11
|
* return errors as TEXT).
|
|
12
12
|
*
|
|
@@ -29,12 +29,13 @@ import type { ToolContextLike } from './delegation.ts'
|
|
|
29
29
|
|
|
30
30
|
const execFileAsync = promisify(execFile)
|
|
31
31
|
|
|
32
|
-
/** One aggregated
|
|
32
|
+
/** One aggregated token row (per agent and phase). */
|
|
33
33
|
export interface CostRow {
|
|
34
34
|
agent: string
|
|
35
|
-
|
|
35
|
+
phase: string
|
|
36
36
|
tokensInput: number
|
|
37
37
|
tokensOutput: number
|
|
38
|
+
tokensTotal: number
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
export interface CostCommandOptions {
|
|
@@ -123,7 +124,7 @@ function assertCompatibleSchema(db: {
|
|
|
123
124
|
}
|
|
124
125
|
}
|
|
125
126
|
|
|
126
|
-
/** Aggregate
|
|
127
|
+
/** Aggregate tokens by agent and phase via node:sqlite (read-only). */
|
|
127
128
|
async function queryWithNodeSqlite(dbPath: string, days: number): Promise<CostRow[]> {
|
|
128
129
|
const sqlite = await import('node:sqlite')
|
|
129
130
|
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
|
|
@@ -141,24 +142,28 @@ async function queryWithNodeSqlite(dbPath: string, days: number): Promise<CostRo
|
|
|
141
142
|
}
|
|
142
143
|
}
|
|
143
144
|
|
|
144
|
-
/**
|
|
145
|
+
/** CLI fallback: delegate the same aggregation to scripts/cost.mjs. */
|
|
145
146
|
async function queryWithScript(
|
|
146
147
|
scriptPath: string,
|
|
147
148
|
dbPath: string,
|
|
148
149
|
days: number,
|
|
149
150
|
): Promise<CostRow[]> {
|
|
150
|
-
const { stdout } = await execFileAsync(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
151
|
+
const { stdout } = await execFileAsync(
|
|
152
|
+
process.execPath,
|
|
153
|
+
[scriptPath, '--db-path', dbPath, '--days', String(days)],
|
|
154
|
+
{
|
|
155
|
+
timeout: 15_000,
|
|
156
|
+
encoding: 'utf8',
|
|
157
|
+
},
|
|
158
|
+
)
|
|
154
159
|
const parsed = JSON.parse(stdout) as { ok: boolean; rows?: CostRow[]; error?: string }
|
|
155
160
|
if (!parsed.ok) throw new Error(parsed.error ?? 'cost.mjs failed')
|
|
156
161
|
return parsed.rows ?? []
|
|
157
162
|
}
|
|
158
163
|
|
|
159
|
-
/** Parse message.data JSON rows and aggregate
|
|
164
|
+
/** Parse message.data JSON rows and aggregate tokens by assistant agent/phase. */
|
|
160
165
|
function aggregateMessages(dataValues: readonly string[]): CostRow[] {
|
|
161
|
-
const
|
|
166
|
+
const byAgentAndPhase = new Map<string, CostRow>()
|
|
162
167
|
for (const value of dataValues) {
|
|
163
168
|
try {
|
|
164
169
|
const outer = JSON.parse(value) as Record<string, unknown>
|
|
@@ -169,45 +174,57 @@ function aggregateMessages(dataValues: readonly string[]): CostRow[] {
|
|
|
169
174
|
if (info.role !== 'assistant') continue
|
|
170
175
|
const agent = typeof info.agent === 'string' && info.agent !== '' ? info.agent : null
|
|
171
176
|
if (agent === null) continue
|
|
172
|
-
const
|
|
177
|
+
const metadata = info.metadata as Record<string, unknown> | undefined
|
|
178
|
+
const phase =
|
|
179
|
+
(typeof info.phase === 'string' && info.phase) ||
|
|
180
|
+
(typeof metadata?.phase === 'string' && metadata.phase) ||
|
|
181
|
+
'unknown'
|
|
173
182
|
const tokens = (info.tokens ?? {}) as Record<string, unknown>
|
|
174
183
|
const tokensInput = Number(tokens.input) || 0
|
|
175
184
|
const tokensOutput = Number(tokens.output) || 0
|
|
176
|
-
const
|
|
177
|
-
acc.
|
|
185
|
+
const key = `${agent}\u0000${phase}`
|
|
186
|
+
const acc = byAgentAndPhase.get(key) ?? {
|
|
187
|
+
agent,
|
|
188
|
+
phase,
|
|
189
|
+
tokensInput: 0,
|
|
190
|
+
tokensOutput: 0,
|
|
191
|
+
tokensTotal: 0,
|
|
192
|
+
}
|
|
178
193
|
acc.tokensInput += tokensInput
|
|
179
194
|
acc.tokensOutput += tokensOutput
|
|
180
|
-
|
|
195
|
+
acc.tokensTotal += tokensInput + tokensOutput
|
|
196
|
+
byAgentAndPhase.set(key, acc)
|
|
181
197
|
} catch {
|
|
182
198
|
// Skip malformed rows — a partial ledger never breaks the report.
|
|
183
199
|
}
|
|
184
200
|
}
|
|
185
|
-
return [...
|
|
201
|
+
return [...byAgentAndPhase.values()].sort((a, b) => b.tokensTotal - a.tokensTotal)
|
|
186
202
|
}
|
|
187
203
|
|
|
188
204
|
/** Render the aggregate as a markdown table with a total row. */
|
|
189
205
|
function renderMarkdown(rows: readonly CostRow[], days: number): string {
|
|
190
206
|
if (rows.length === 0) {
|
|
191
|
-
return `##
|
|
207
|
+
return `## Token usage by agent and phase (last ${days} days)\n\nNo token records in the last ${days} days.`
|
|
192
208
|
}
|
|
193
209
|
const total = rows.reduce(
|
|
194
210
|
(acc, r) => {
|
|
195
|
-
acc.costUsd += r.costUsd
|
|
196
211
|
acc.tokensInput += r.tokensInput
|
|
197
212
|
acc.tokensOutput += r.tokensOutput
|
|
213
|
+
acc.tokensTotal += r.tokensTotal
|
|
198
214
|
return acc
|
|
199
215
|
},
|
|
200
|
-
{
|
|
216
|
+
{ tokensInput: 0, tokensOutput: 0, tokensTotal: 0 },
|
|
201
217
|
)
|
|
202
218
|
const lines = [
|
|
203
|
-
`##
|
|
219
|
+
`## Token usage by agent and phase (last ${days} days)`,
|
|
204
220
|
'',
|
|
205
|
-
'| Agent |
|
|
206
|
-
'
|
|
221
|
+
'| Agent | Phase | Tokens In | Tokens Out | Tokens Total |',
|
|
222
|
+
'|-------|-------|----------:|-----------:|-------------:|',
|
|
207
223
|
...rows.map(
|
|
208
|
-
(r) =>
|
|
224
|
+
(r) =>
|
|
225
|
+
`| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} |`,
|
|
209
226
|
),
|
|
210
|
-
`| **Total** |
|
|
227
|
+
`| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** |`,
|
|
211
228
|
'',
|
|
212
229
|
`Source: opencode.db (read-only)`,
|
|
213
230
|
]
|
|
@@ -218,14 +235,14 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
218
235
|
const scriptPath = new URL('../../scripts/cost.mjs', import.meta.url).pathname
|
|
219
236
|
|
|
220
237
|
const execute = async (args: { days?: number }, _ctx: ToolContextLike): Promise<string> => {
|
|
221
|
-
const days = args
|
|
238
|
+
const days = args?.days ?? 7
|
|
222
239
|
try {
|
|
223
240
|
const dbPath = findExistingDb(options?.dbPath)
|
|
224
241
|
if (dbPath === undefined) {
|
|
225
242
|
const expected = resolveCostDbPath(options)
|
|
226
243
|
return (
|
|
227
244
|
`pantheon_cost failed: opencode.db not found (expected at ${expected}). ` +
|
|
228
|
-
`No
|
|
245
|
+
`No token history is available until opencode has stored session data.`
|
|
229
246
|
)
|
|
230
247
|
}
|
|
231
248
|
const rows = await queryWithNodeSqlite(dbPath, days).catch(async (err: unknown) => {
|
|
@@ -243,7 +260,7 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
243
260
|
return {
|
|
244
261
|
pantheon_cost: {
|
|
245
262
|
description:
|
|
246
|
-
'Report
|
|
263
|
+
'Report input, output, and total token usage by agent and phase over the last N days, read from opencode.db (read-only, no monetary values).',
|
|
247
264
|
args: costArgs,
|
|
248
265
|
execute,
|
|
249
266
|
},
|