@gotcos/glasses-server 6.82.0 → 6.84.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.
- package/CHANGELOG.md +224 -0
- package/docs/work-orchestrator.md +184 -0
- package/managed-runtime-contract.json +2 -1
- package/package.json +8 -1
- package/server/index.ts +12 -0
- package/server/lib/claude-bridge.ts +4 -0
- package/server/lib/dictation-clean.ts +26 -3
- package/server/lib/dictation-format.ts +119 -0
- package/server/lib/dictation-polish-need.ts +4 -2
- package/server/lib/glossary-learn.ts +88 -10
- package/server/lib/hallucination-filter.ts +5 -0
- package/server/lib/meeting-batch-transcribe.ts +12 -4
- package/server/lib/profile.ts +3 -1
- package/server/lib/query-job-coordinator.ts +5 -1
- package/server/lib/unsaved-audio-quarantine.ts +36 -5
- package/server/lib/whisper-local.ts +31 -5
- package/server/lib/work-chat.ts +76 -9
- package/server/lib/work-lens-rounds.ts +445 -0
- package/server/lib/work-orchestrator/discovery.ts +99 -0
- package/server/lib/work-orchestrator/input.ts +109 -0
- package/server/lib/work-orchestrator/pickup.ts +85 -0
- package/server/lib/work-orchestrator/plan-log.ts +38 -0
- package/server/lib/work-orchestrator/redact.ts +41 -0
- package/server/lib/work-orchestrator/runtime.ts +74 -0
- package/server/lib/work-orchestrator/session-log.ts +114 -0
- package/server/lib/work-orchestrator/snapshot.ts +87 -0
- package/server/lib/work-orchestrator/tag-index.ts +272 -0
- package/server/lib/work-orchestrator/tags.ts +52 -0
- package/server/lib/work-orchestrator/usage-events.ts +30 -0
- package/server/lib/work-orchestrator/usage.ts +341 -0
- package/server/routes/glossary.ts +14 -2
- package/server/routes/meeting.ts +76 -1
- package/server/routes/prompt-drafts.ts +15 -2
- package/server/routes/transcribe-stream.ts +127 -10
- package/server/routes/work-chat.ts +54 -11
- package/server/routes/work-lens-rounds.ts +179 -0
- package/server/routes/work-orchestrator.ts +71 -0
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 6.83.0 (M3 planner input, canary C1): how much PLAN usage each provider has left (Miles, Q2: plan usage only; a key
|
|
3
|
+
* lane is never a silent fallback). Read without spending any of it.
|
|
4
|
+
*
|
|
5
|
+
* Claude `claude -p` stream-json control request `get_usage` with `skip_behaviors` (no turn, no transcript).
|
|
6
|
+
* Codex `codex app-server` JSON-RPC `account/rateLimits/read` with `excludeResetCreditDetails`. Never sends
|
|
7
|
+
* `supportsLunaReserve` (it records experiment exposure); never calls ConsumeAccountRateLimitResetCredit.
|
|
8
|
+
* Cursor unknown. Its only usage reader is the interactive TUI (which auto-updates the CLI) or a Keychain token;
|
|
9
|
+
* Miles has approved neither, so the server reads neither.
|
|
10
|
+
*
|
|
11
|
+
* Read ON DEMAND only (6.83.0 release decision, Miles has not approved a background poll for every user): a plan
|
|
12
|
+
* input (`POST /api/work/orchestrator/input`, the moment a fork or a new session is chosen) re-reads a provider whose
|
|
13
|
+
* reading is older than 2 minutes; `GET /api/work/orchestrator/usage` re-reads one older than 10 minutes (2 with
|
|
14
|
+
* `refresh=1`). Nothing reads usage on a timer unless the owner opts in with `COS_WORK_USAGE_POLL=1` (every 10 minutes).
|
|
15
|
+
* Passive refresh needs no probe: the `rate_limit_event` frames the server's own plan-lane Claude jobs already receive.
|
|
16
|
+
* A `provider_limit` failure marks the provider exhausted until the reset it states (or one hour), and that beats any
|
|
17
|
+
* cached percentage.
|
|
18
|
+
*
|
|
19
|
+
* How it stops: no timer by default; three failed probes in a row pause that provider's probe for an hour. Each probe
|
|
20
|
+
* runs in a fresh empty directory with hooks and MCP off, and is killed by its exact PID after 15 seconds.
|
|
21
|
+
*/
|
|
22
|
+
import { spawn } from 'node:child_process'
|
|
23
|
+
import { mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
|
|
24
|
+
import { tmpdir } from 'node:os'
|
|
25
|
+
import { dirname, join } from 'node:path'
|
|
26
|
+
import { atomicWriteFileSync } from '../atomic-fs.js'
|
|
27
|
+
import { resolveProviderBinary } from '../provider-binary.js'
|
|
28
|
+
|
|
29
|
+
export type UsageProvider = 'claude' | 'codex' | 'cursor'
|
|
30
|
+
export const USAGE_PROVIDERS: UsageProvider[] = ['claude', 'codex', 'cursor']
|
|
31
|
+
/** The opt-in poll's period (`COS_WORK_USAGE_POLL=1` only). */
|
|
32
|
+
export const USAGE_POLL_MS = 10 * 60_000
|
|
33
|
+
/** Before a plan (it may fork or start a session): a reading older than this is re-read. */
|
|
34
|
+
export const USAGE_FRESH_MS = 2 * 60_000
|
|
35
|
+
/** An on-demand usage read (GET /usage) answers from a reading younger than this. */
|
|
36
|
+
export const USAGE_CACHE_MS = 10 * 60_000
|
|
37
|
+
export const USAGE_STALE_MS = 25 * 60_000
|
|
38
|
+
export const USAGE_PROBE_TIMEOUT_MS = 15_000
|
|
39
|
+
export const USAGE_BREAKER_FAILURES = 3
|
|
40
|
+
export const USAGE_BREAKER_MS = 60 * 60_000
|
|
41
|
+
export const USAGE_LIMIT_DEFAULT_MS = 60 * 60_000
|
|
42
|
+
export const USAGE_LOW_HEADROOM = 15
|
|
43
|
+
|
|
44
|
+
export interface UsageWindow { kind: string; usedPct: number; resetsAt: string | null; durationMins?: number }
|
|
45
|
+
export interface UsageReading {
|
|
46
|
+
plan: string | null
|
|
47
|
+
windows: UsageWindow[]
|
|
48
|
+
/** Codex `ordinaryUsageAllowed`; Claude false only when a window reports a lock. Null: not stated. */
|
|
49
|
+
allowed: boolean | null
|
|
50
|
+
/** Claude `rate_limits_available: false` (an API key or a third-party login): no plan limits to read. */
|
|
51
|
+
available: boolean
|
|
52
|
+
}
|
|
53
|
+
export interface UsageEntry {
|
|
54
|
+
provider: UsageProvider
|
|
55
|
+
reading: UsageReading | null
|
|
56
|
+
observedAt: number | null
|
|
57
|
+
source: 'probe' | 'passive' | 'none'
|
|
58
|
+
lastError: string | null
|
|
59
|
+
failures: number
|
|
60
|
+
pausedUntil: number | null
|
|
61
|
+
/** Exhausted until this time, from a provider_limit failure or a rejected rate-limit frame. */
|
|
62
|
+
limitUntil: number | null
|
|
63
|
+
limitSource: string | null
|
|
64
|
+
warning: boolean
|
|
65
|
+
}
|
|
66
|
+
export type UsageState = 'ok' | 'low' | 'exhausted' | 'unknown'
|
|
67
|
+
/** What the planner sees: one line per provider. */
|
|
68
|
+
export interface UsageView { provider: UsageProvider; state: UsageState; headroomPct: number | null; resetsAt: string | null; ageSec: number | null; source: string; plan: string | null; stale: boolean; note: string }
|
|
69
|
+
|
|
70
|
+
/** The windows that bind: Claude's 5-hour session and weekly all-models; every Codex window; Cursor's included. */
|
|
71
|
+
const BINDING: Record<UsageProvider, (kind: string) => boolean> = {
|
|
72
|
+
claude: kind => kind === 'session' || kind === 'weekly_all',
|
|
73
|
+
codex: () => true,
|
|
74
|
+
cursor: kind => kind === 'included',
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
|
|
78
|
+
const iso = (s: number) => new Date(s * 1000).toISOString()
|
|
79
|
+
|
|
80
|
+
/** Claude `get_usage` response (`response.response`). Classify on `kind`, never on a label. Null when the shape is not one we know. */
|
|
81
|
+
export function parseClaudeUsage(r: unknown): UsageReading | null {
|
|
82
|
+
if (!r || typeof r !== 'object') return null
|
|
83
|
+
const v = r as Record<string, any>
|
|
84
|
+
if (v.rate_limits_available !== true) return typeof v.rate_limits_available === 'boolean' ? { plan: typeof v.subscription_type === 'string' ? v.subscription_type : null, windows: [], allowed: null, available: false } : null
|
|
85
|
+
const limits = v.rate_limits?.limits
|
|
86
|
+
if (!Array.isArray(limits)) return null
|
|
87
|
+
const windows: UsageWindow[] = []
|
|
88
|
+
let locked = false
|
|
89
|
+
for (const l of limits) {
|
|
90
|
+
if (!l || typeof l.kind !== 'string' || !num(l.percent) || l.percent < 0 || l.percent > 1000) return null
|
|
91
|
+
windows.push({ kind: l.kind, usedPct: l.percent, resetsAt: typeof l.resets_at === 'string' && !Number.isNaN(Date.parse(l.resets_at)) ? new Date(Date.parse(l.resets_at)).toISOString() : null })
|
|
92
|
+
if (l.severity === 'locked' || l.severity === 'blocked') locked = true
|
|
93
|
+
}
|
|
94
|
+
return { plan: typeof v.subscription_type === 'string' ? v.subscription_type : null, windows, allowed: locked ? false : null, available: true }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Codex `account/rateLimits/read` result. `ordinaryUsageAllowed` is authoritative over percentages (its schema says so). */
|
|
98
|
+
export function parseCodexUsage(r: unknown): UsageReading | null {
|
|
99
|
+
if (!r || typeof r !== 'object') return null
|
|
100
|
+
const v = r as Record<string, any>
|
|
101
|
+
const limits = v.rateLimitsByLimitId?.codex ?? v.rateLimits
|
|
102
|
+
if (!limits || typeof limits !== 'object') return null
|
|
103
|
+
const windows: UsageWindow[] = []
|
|
104
|
+
for (const [kind, w] of [['primary', limits.primary], ['secondary', limits.secondary]] as const) {
|
|
105
|
+
if (w == null) continue
|
|
106
|
+
if (typeof w !== 'object' || !num(w.usedPercent)) return null
|
|
107
|
+
windows.push({ kind, usedPct: w.usedPercent, resetsAt: num(w.resetsAt) ? iso(w.resetsAt) : null, ...(num(w.windowDurationMins) ? { durationMins: w.windowDurationMins } : {}) })
|
|
108
|
+
}
|
|
109
|
+
const reached = limits.rateLimitReachedType != null || limits.spendControlReached === true
|
|
110
|
+
const allowed = typeof v.ordinaryUsageAllowed === 'boolean' ? v.ordinaryUsageAllowed && !reached : reached ? false : null
|
|
111
|
+
return { plan: typeof limits.planType === 'string' ? limits.planType : null, windows, allowed, available: true }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A reset time named in a provider's own limit text ("resets 2026-10-21T05:50Z", "resets in 3h", "try again in 20 minutes"). */
|
|
115
|
+
export function parseLimitReset(message: string, now: number): number | null {
|
|
116
|
+
const isoMatch = /\b(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2}))/.exec(message)
|
|
117
|
+
if (isoMatch && !Number.isNaN(Date.parse(isoMatch[1]!))) return Date.parse(isoMatch[1]!)
|
|
118
|
+
const rel = /\b(?:resets?|try again|retry)\s+in\s+(\d+(?:\.\d+)?)\s*(h|hr|hrs|hours?|m|min|mins|minutes?)\b/i.exec(message)
|
|
119
|
+
if (rel) return now + Number(rel[1]) * (/^h/i.test(rel[2]!) ? 3_600_000 : 60_000)
|
|
120
|
+
const epoch = /\bresets?(?:At)?["':\s]+(\d{10})\b/.exec(message)
|
|
121
|
+
if (epoch) return Number(epoch[1]) * 1000
|
|
122
|
+
return null
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function headroomOf(provider: UsageProvider, reading: UsageReading | null): number | null {
|
|
126
|
+
if (!reading || !reading.available) return null
|
|
127
|
+
const bind = reading.windows.filter(w => BINDING[provider](w.kind))
|
|
128
|
+
if (!bind.length) return null
|
|
129
|
+
return Math.max(0, Math.round(100 - Math.max(...bind.map(w => w.usedPct))))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function viewOf(e: UsageEntry, now: number): UsageView {
|
|
133
|
+
const ageSec = e.observedAt ? Math.round((now - e.observedAt) / 1000) : null
|
|
134
|
+
const stale = !e.observedAt || now - e.observedAt > USAGE_STALE_MS
|
|
135
|
+
const headroom = headroomOf(e.provider, e.reading)
|
|
136
|
+
const bind = (e.reading?.windows ?? []).filter(w => BINDING[e.provider](w.kind))
|
|
137
|
+
const tightest = bind.length ? bind.reduce((a, b) => (b.usedPct > a.usedPct ? b : a)) : null
|
|
138
|
+
const base = { provider: e.provider, ageSec, source: e.source, plan: e.reading?.plan ?? null, stale }
|
|
139
|
+
// A stated limit beats any percentage (canary C1 rule), until the time it names.
|
|
140
|
+
if (e.limitUntil && e.limitUntil > now) {
|
|
141
|
+
return { ...base, state: 'exhausted', headroomPct: 0, resetsAt: new Date(e.limitUntil).toISOString(), source: e.limitSource ?? 'provider_limit', note: 'plan limit reached' }
|
|
142
|
+
}
|
|
143
|
+
if (e.reading?.allowed === false) return { ...base, state: 'exhausted', headroomPct: 0, resetsAt: tightest?.resetsAt ?? null, note: 'the provider says ordinary usage is not allowed now' }
|
|
144
|
+
if (e.provider === 'cursor' && !e.reading) return { ...base, state: 'unknown', headroomPct: null, resetsAt: null, note: 'not read: Cursor usage needs its app or a Keychain read, neither approved' }
|
|
145
|
+
if (!e.reading || headroom === null) return { ...base, state: 'unknown', headroomPct: null, resetsAt: null, note: e.reading && !e.reading.available ? 'no plan limits on this login' : e.lastError ? `not read: ${e.lastError}` : 'not read yet' }
|
|
146
|
+
const state: UsageState = headroom <= 0 ? 'exhausted' : headroom < USAGE_LOW_HEADROOM || e.warning ? 'low' : 'ok'
|
|
147
|
+
return { ...base, state, headroomPct: headroom, resetsAt: tightest?.resetsAt ?? null, note: stale ? 'reading is old' : '' }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The background poll runs only when the owner opted in: `COS_WORK_USAGE_POLL=1`, nothing else. */
|
|
151
|
+
export function usagePollOptedIn(env: NodeJS.ProcessEnv = process.env): boolean { return env.COS_WORK_USAGE_POLL === '1' }
|
|
152
|
+
|
|
153
|
+
export interface UsageProbes {
|
|
154
|
+
claude: () => Promise<UsageReading>
|
|
155
|
+
codex: () => Promise<UsageReading>
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface UsageMonitorOptions { path?: string; probes?: Partial<UsageProbes>; now?: () => number; pollEnabled?: boolean }
|
|
159
|
+
|
|
160
|
+
export class UsageMonitor {
|
|
161
|
+
private entries: Record<UsageProvider, UsageEntry>
|
|
162
|
+
private inflight: Partial<Record<UsageProvider, Promise<void>>> = {}
|
|
163
|
+
private timer: NodeJS.Timeout | null = null
|
|
164
|
+
private readonly now: () => number
|
|
165
|
+
private readonly probes: UsageProbes
|
|
166
|
+
constructor(private readonly options: UsageMonitorOptions = {}) {
|
|
167
|
+
this.now = options.now ?? Date.now
|
|
168
|
+
this.probes = { claude: options.probes?.claude ?? probeClaudeUsage, codex: options.probes?.codex ?? probeCodexUsage }
|
|
169
|
+
const blank = (provider: UsageProvider): UsageEntry => ({ provider, reading: null, observedAt: null, source: 'none', lastError: null, failures: 0, pausedUntil: null, limitUntil: null, limitSource: null, warning: false })
|
|
170
|
+
this.entries = { claude: blank('claude'), codex: blank('codex'), cursor: blank('cursor') }
|
|
171
|
+
if (options.path) {
|
|
172
|
+
try {
|
|
173
|
+
const saved = JSON.parse(readFileSync(options.path, 'utf8'))
|
|
174
|
+
for (const p of USAGE_PROVIDERS) if (saved?.[p]?.provider === p) this.entries[p] = { ...this.entries[p], ...saved[p], failures: 0, pausedUntil: null }
|
|
175
|
+
} catch { /* none saved yet */ }
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
private save(): void {
|
|
179
|
+
if (!this.options.path) return
|
|
180
|
+
try { mkdirSync(dirname(this.options.path), { recursive: true, mode: 0o700 }); atomicWriteFileSync(this.options.path, JSON.stringify(this.entries)) } catch { /* cache only */ }
|
|
181
|
+
}
|
|
182
|
+
entry(p: UsageProvider): UsageEntry { return this.entries[p] }
|
|
183
|
+
views(): UsageView[] { const now = this.now(); return USAGE_PROVIDERS.map(p => viewOf(this.entries[p], now)) }
|
|
184
|
+
/** Probe one provider now (shares a probe already running). Failures count toward the breaker; never throws. */
|
|
185
|
+
refresh(p: 'claude' | 'codex'): Promise<void> {
|
|
186
|
+
if (this.inflight[p]) return this.inflight[p]!
|
|
187
|
+
const e = this.entries[p]
|
|
188
|
+
if (e.pausedUntil && e.pausedUntil > this.now()) return Promise.resolve()
|
|
189
|
+
const run = (async () => {
|
|
190
|
+
try {
|
|
191
|
+
const reading = await this.probes[p]()
|
|
192
|
+
e.reading = reading; e.observedAt = this.now(); e.source = 'probe'; e.lastError = null; e.failures = 0; e.pausedUntil = null; e.warning = false
|
|
193
|
+
// A fresh reading that says usage is allowed again clears an older limit only when its own reset passed.
|
|
194
|
+
if (e.limitUntil && e.limitUntil <= this.now()) { e.limitUntil = null; e.limitSource = null }
|
|
195
|
+
} catch (error) {
|
|
196
|
+
e.lastError = String((error as Error)?.message ?? error).slice(0, 120)
|
|
197
|
+
e.failures++
|
|
198
|
+
if (e.failures >= USAGE_BREAKER_FAILURES) {
|
|
199
|
+
e.pausedUntil = this.now() + USAGE_BREAKER_MS
|
|
200
|
+
console.warn(`[work-orchestrator] usage probe ${p} paused for 1 h after ${e.failures} failures: ${e.lastError}`)
|
|
201
|
+
}
|
|
202
|
+
} finally { delete this.inflight[p]; this.save() }
|
|
203
|
+
})()
|
|
204
|
+
this.inflight[p] = run
|
|
205
|
+
return run
|
|
206
|
+
}
|
|
207
|
+
/** Re-read any provider whose reading is older than `maxAgeMs` (default 2 minutes), waiting at most `waitMs`. */
|
|
208
|
+
async ensureFresh(maxAgeMs = USAGE_FRESH_MS, waitMs = 16_000): Promise<void> {
|
|
209
|
+
const now = this.now()
|
|
210
|
+
const due = (['claude', 'codex'] as const).filter(p => !this.entries[p].observedAt || now - this.entries[p].observedAt! > maxAgeMs)
|
|
211
|
+
if (!due.length) return
|
|
212
|
+
await Promise.race([Promise.all(due.map(p => this.refresh(p))), new Promise(r => setTimeout(r, waitMs).unref?.())])
|
|
213
|
+
}
|
|
214
|
+
/** Before a plan (POST /input), which may fork or start a new session: re-read what is older than 2 minutes. */
|
|
215
|
+
async forPlan(): Promise<UsageView[]> { await this.ensureFresh(USAGE_FRESH_MS); return this.views() }
|
|
216
|
+
/** On demand (GET /usage): answer from a reading younger than 10 minutes; `refresh` tightens that to 2. */
|
|
217
|
+
async onDemand(refresh = false): Promise<UsageView[]> { await this.ensureFresh(refresh ? USAGE_FRESH_MS : USAGE_CACHE_MS); return this.views() }
|
|
218
|
+
/** A provider refused a plan-lane turn with its limit text. Never called for a key-lane turn. */
|
|
219
|
+
noteLimit(p: UsageProvider, message: string, source = 'provider_limit'): void {
|
|
220
|
+
const now = this.now()
|
|
221
|
+
const until = parseLimitReset(message, now) ?? now + USAGE_LIMIT_DEFAULT_MS
|
|
222
|
+
const e = this.entries[p]
|
|
223
|
+
e.limitUntil = Math.max(e.limitUntil ?? 0, until > now ? until : now + USAGE_LIMIT_DEFAULT_MS); e.limitSource = source
|
|
224
|
+
console.log(`[work-orchestrator] usage ${p} marked exhausted until ${new Date(e.limitUntil).toISOString()} (${source})`)
|
|
225
|
+
this.save()
|
|
226
|
+
}
|
|
227
|
+
/** A `rate_limit_event` frame from one of this server's own plan-lane Claude jobs (C1: free passive refresh). */
|
|
228
|
+
noteClaudeRateLimitEvent(frame: unknown): void {
|
|
229
|
+
const info = (frame as any)?.rate_limit_info
|
|
230
|
+
if (!info || typeof info !== 'object' || typeof info.status !== 'string') return
|
|
231
|
+
const e = this.entries.claude
|
|
232
|
+
if (info.status === 'rejected') {
|
|
233
|
+
const resetMs = num(info.resetsAt) ? info.resetsAt * 1000 : this.now() + USAGE_LIMIT_DEFAULT_MS
|
|
234
|
+
e.limitUntil = Math.max(e.limitUntil ?? 0, resetMs); e.limitSource = 'rate_limit_event'
|
|
235
|
+
} else if (info.status === 'allowed_warning') e.warning = true
|
|
236
|
+
else if (info.status === 'allowed') { e.warning = false; if (e.limitSource === 'rate_limit_event' && (e.limitUntil ?? 0) <= this.now()) e.limitUntil = null }
|
|
237
|
+
if (e.source === 'none') e.source = 'passive'
|
|
238
|
+
this.save()
|
|
239
|
+
}
|
|
240
|
+
/** The opt-in background poll. Off unless `pollEnabled` is true or the env says `COS_WORK_USAGE_POLL=1`. */
|
|
241
|
+
start(env: NodeJS.ProcessEnv = process.env): void {
|
|
242
|
+
if (this.timer || !(this.options.pollEnabled ?? usagePollOptedIn(env))) return
|
|
243
|
+
const tick = () => { void this.refresh('claude'); void this.refresh('codex') }
|
|
244
|
+
this.timer = setInterval(tick, USAGE_POLL_MS)
|
|
245
|
+
this.timer.unref?.()
|
|
246
|
+
setTimeout(tick, 30_000).unref?.()
|
|
247
|
+
}
|
|
248
|
+
stop(): void { if (this.timer) clearInterval(this.timer); this.timer = null }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ─── The real probes ───
|
|
252
|
+
|
|
253
|
+
interface LineChild { pid?: number; write(line: string): void; end(): void; kill(): void; onLine(fn: (o: Record<string, any>) => void): void; onExit(fn: (code: number | null) => void): void }
|
|
254
|
+
|
|
255
|
+
function spawnLines(bin: string, args: string[], cwd: string): LineChild {
|
|
256
|
+
const env = { ...process.env }
|
|
257
|
+
delete env.CLAUDECODE
|
|
258
|
+
const child = spawn(bin, args, { cwd, env, stdio: ['pipe', 'pipe', 'ignore'] })
|
|
259
|
+
let buffer = ''
|
|
260
|
+
const lineFns: Array<(o: Record<string, any>) => void> = []
|
|
261
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
262
|
+
buffer += chunk.toString('utf8')
|
|
263
|
+
let nl
|
|
264
|
+
while ((nl = buffer.indexOf('\n')) >= 0) {
|
|
265
|
+
const line = buffer.slice(0, nl); buffer = buffer.slice(nl + 1)
|
|
266
|
+
try { const o = JSON.parse(line); if (o && typeof o === 'object') for (const fn of lineFns) fn(o) } catch { /* not JSON */ }
|
|
267
|
+
}
|
|
268
|
+
})
|
|
269
|
+
child.stdin.on('error', () => {})
|
|
270
|
+
return {
|
|
271
|
+
pid: child.pid,
|
|
272
|
+
write: line => { try { child.stdin.write(line + '\n') } catch { /* closed */ } },
|
|
273
|
+
end: () => { try { child.stdin.end() } catch { /* closed */ } },
|
|
274
|
+
// Exact PID: this child, never a pattern.
|
|
275
|
+
kill: () => { try { if (child.exitCode === null) child.kill('SIGTERM') } catch { /* gone */ } },
|
|
276
|
+
onLine: fn => { lineFns.push(fn) },
|
|
277
|
+
onExit: fn => { child.on('exit', fn); child.on('error', () => fn(null)) },
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export type SpawnLines = (bin: string, args: string[], cwd: string) => LineChild
|
|
282
|
+
|
|
283
|
+
/** The stdin lines each probe sends, in order. Pinned by tests: no luna reserve, no reset-credit call. */
|
|
284
|
+
export const CLAUDE_USAGE_LINES = [
|
|
285
|
+
{ type: 'control_request', request_id: 'cos_init', request: { subtype: 'initialize' } },
|
|
286
|
+
{ type: 'control_request', request_id: 'cos_usage', request: { subtype: 'get_usage', skip_behaviors: true } },
|
|
287
|
+
]
|
|
288
|
+
export const CODEX_INIT = { id: 1, method: 'initialize', params: { clientInfo: { name: 'cos', title: null, version: '6.83.0' }, capabilities: null } }
|
|
289
|
+
export const CODEX_READ = { id: 2, method: 'account/rateLimits/read', params: { excludeResetCreditDetails: true } }
|
|
290
|
+
|
|
291
|
+
function withScratch<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
|
292
|
+
const dir = mkdtempSync(join(tmpdir(), 'cos-usage-'))
|
|
293
|
+
return fn(dir).finally(() => { try { rmSync(dir, { recursive: true, force: true }) } catch { /* best effort */ } })
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export function probeClaudeUsage(spawnFn: SpawnLines = spawnLines, timeoutMs = USAGE_PROBE_TIMEOUT_MS): Promise<UsageReading> {
|
|
297
|
+
const bin = resolveProviderBinary('claude')
|
|
298
|
+
return withScratch(dir => new Promise((resolve, reject) => {
|
|
299
|
+
const child = spawnFn(bin.ok ? bin.path : 'claude', ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',
|
|
300
|
+
'--strict-mcp-config', '--settings', JSON.stringify({ disableAllHooks: true })], dir)
|
|
301
|
+
let done = false
|
|
302
|
+
const finish = (err: Error | null, value?: UsageReading) => {
|
|
303
|
+
if (done) return
|
|
304
|
+
done = true; clearTimeout(timer); child.end(); setTimeout(() => child.kill(), 2000).unref?.()
|
|
305
|
+
if (err) reject(err); else resolve(value!)
|
|
306
|
+
}
|
|
307
|
+
const timer = setTimeout(() => { child.kill(); finish(new Error('timed out')) }, timeoutMs)
|
|
308
|
+
child.onLine(o => {
|
|
309
|
+
if (o.type !== 'control_response' || o.response?.request_id !== 'cos_usage') return
|
|
310
|
+
if (o.response?.subtype !== 'success') return finish(new Error('get_usage refused'))
|
|
311
|
+
const reading = parseClaudeUsage(o.response.response)
|
|
312
|
+
if (reading) finish(null, reading); else finish(new Error('unknown get_usage shape'))
|
|
313
|
+
})
|
|
314
|
+
child.onExit(code => finish(new Error(`exited ${code ?? 'on error'} before answering`)))
|
|
315
|
+
for (const line of CLAUDE_USAGE_LINES) child.write(JSON.stringify(line))
|
|
316
|
+
}))
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function probeCodexUsage(spawnFn: SpawnLines = spawnLines, timeoutMs = USAGE_PROBE_TIMEOUT_MS): Promise<UsageReading> {
|
|
320
|
+
const bin = resolveProviderBinary('codex')
|
|
321
|
+
if (!bin.ok) return Promise.reject(new Error('codex not found'))
|
|
322
|
+
return withScratch(dir => new Promise((resolve, reject) => {
|
|
323
|
+
const child = spawnFn(bin.path, ['app-server'], dir)
|
|
324
|
+
let done = false
|
|
325
|
+
const finish = (err: Error | null, value?: UsageReading) => {
|
|
326
|
+
if (done) return
|
|
327
|
+
done = true; clearTimeout(timer); child.end(); setTimeout(() => child.kill(), 2000).unref?.()
|
|
328
|
+
if (err) reject(err); else resolve(value!)
|
|
329
|
+
}
|
|
330
|
+
const timer = setTimeout(() => { child.kill(); finish(new Error('timed out')) }, timeoutMs)
|
|
331
|
+
child.onLine(o => {
|
|
332
|
+
if (o.id === 1 && !done) { child.write(JSON.stringify({ method: 'initialized' })); child.write(JSON.stringify(CODEX_READ)); return }
|
|
333
|
+
if (o.id !== 2) return
|
|
334
|
+
if (o.error) return finish(new Error('rateLimits/read refused'))
|
|
335
|
+
const reading = parseCodexUsage(o.result)
|
|
336
|
+
if (reading) finish(null, reading); else finish(new Error('unknown rateLimits shape'))
|
|
337
|
+
})
|
|
338
|
+
child.onExit(code => finish(new Error(`exited ${code ?? 'on error'} before answering`)))
|
|
339
|
+
child.write(JSON.stringify(CODEX_INIT))
|
|
340
|
+
}))
|
|
341
|
+
}
|
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
// left unchanged). whisper_corrections is stored as a JSON STRING in the
|
|
9
9
|
// profile (legacy decoder contract), so the route encodes/decodes it here.
|
|
10
10
|
// POST /api/transcription-glossary/correction {heard, written, source} → learn
|
|
11
|
-
// ONE correction and its spelling (6.73.11, Fix a word), logged for undo.
|
|
11
|
+
// ONE correction and its spelling (6.73.11, Fix a word), logged for undo. A
|
|
12
|
+
// written link, email or path is a correction only (6.83.1): the answer adds
|
|
13
|
+
// correctionOnly: true and a note, and the vocabulary is untouched.
|
|
12
14
|
// GET /api/transcription-glossary/recent → { entries } newest first.
|
|
13
15
|
// POST /api/transcription-glossary/correction/undo {id} → revert that entry.
|
|
14
16
|
// POST /api/transcription-glossary/vocabulary/add {term}, /vocabulary/remove {term},
|
|
@@ -32,6 +34,8 @@ import {
|
|
|
32
34
|
MAX_TERM_LEN,
|
|
33
35
|
addVocabulary,
|
|
34
36
|
appendLog,
|
|
37
|
+
CORRECTION_ONLY_NOTE,
|
|
38
|
+
isCorrectionOnly,
|
|
35
39
|
learnCorrection,
|
|
36
40
|
looksLikeUrlEmailPath,
|
|
37
41
|
parseLog,
|
|
@@ -219,7 +223,15 @@ export function glossaryLearnCorrection(body: unknown): Promise<Outcome> {
|
|
|
219
223
|
if (!learned.ok) return { status: learned.status, body: { error: learned.error } }
|
|
220
224
|
if (learned.unchanged) return { status: 200, body: { unchanged: true, entry: null, glossary: currentGlossary() } }
|
|
221
225
|
commitWords(learned.words, appendLog(previousLog, learned.entry), previousLog)
|
|
222
|
-
|
|
226
|
+
// 6.83.1: a link, email or path is kept as a correction only; say so in words a client can show.
|
|
227
|
+
const correctionOnly = isCorrectionOnly(learned.entry.written)
|
|
228
|
+
return {
|
|
229
|
+
status: 200,
|
|
230
|
+
body: {
|
|
231
|
+
unchanged: false, entry: learned.entry, glossary: currentGlossary(),
|
|
232
|
+
...(correctionOnly ? { correctionOnly: true, note: CORRECTION_ONLY_NOTE } : {}),
|
|
233
|
+
},
|
|
234
|
+
}
|
|
223
235
|
})
|
|
224
236
|
}
|
|
225
237
|
|
package/server/routes/meeting.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { readSpeakerPolicy, writeSpeakerPolicy, isSpeakerMode } from '../lib/mee
|
|
|
6
6
|
|
|
7
7
|
import { existsSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync } from 'node:fs'
|
|
8
8
|
import { isWorthRecovering } from '../lib/quarantine-auto-recover.js'
|
|
9
|
-
import { resolve } from 'node:path'
|
|
9
|
+
import { basename, resolve } from 'node:path'
|
|
10
10
|
import { createHash } from 'node:crypto'
|
|
11
11
|
import { Router } from 'express'
|
|
12
12
|
import { emitDisplay } from '../lib/display-bus.js'
|
|
@@ -129,6 +129,7 @@ import {
|
|
|
129
129
|
analyzeTranscriptGaps,
|
|
130
130
|
deleteSession,
|
|
131
131
|
assertMacCaptureComplete,
|
|
132
|
+
discardSilentMacCapture,
|
|
132
133
|
drainSessionAudioWrites,
|
|
133
134
|
durableSessionRecoveryHasRun,
|
|
134
135
|
getSessionChunkEntries,
|
|
@@ -805,6 +806,80 @@ export function createMeetingRouter(deps: MeetingRouteDependencies = {}): Router
|
|
|
805
806
|
})
|
|
806
807
|
})
|
|
807
808
|
|
|
809
|
+
// ── 6.83.2: discard a stranded Mac capture that held no sound ──────────────────────
|
|
810
|
+
// POST /meeting/sessions/:id/discard {confirm: true, serverInstanceId}. COS Control offers it only for a capture the
|
|
811
|
+
// server called no_speech or whose audio was all zeros; the server re-checks everything itself
|
|
812
|
+
// (transcribe-stream.ts discardSilentMacCapture) and never touches a capture with speech. Without `confirm: true`
|
|
813
|
+
// it answers 400 confirmation_required with what it WOULD do, and changes nothing.
|
|
814
|
+
router.post('/meeting/sessions/:sessionId/discard', async (req, res) => {
|
|
815
|
+
const sessionId = String(req.params.sessionId ?? '')
|
|
816
|
+
if (!/^[A-Za-z0-9:_-]{3,96}$/.test(sessionId)) {
|
|
817
|
+
res.status(400).json({ error: 'Invalid sessionId', reason: 'invalid_session_id' })
|
|
818
|
+
return
|
|
819
|
+
}
|
|
820
|
+
res.set('Cache-Control', 'private, no-store')
|
|
821
|
+
if (!MAC_CAPTURE_ID.test(sessionId)) {
|
|
822
|
+
res.status(400).json({ error: 'Only a Mac recording can be discarded here', reason: 'not_mac_capture' })
|
|
823
|
+
return
|
|
824
|
+
}
|
|
825
|
+
const body = (req.body ?? {}) as Record<string, unknown>
|
|
826
|
+
const serverInstanceId = getServerInstanceId()
|
|
827
|
+
if (!serverInstanceId) {
|
|
828
|
+
res.status(503).json({ error: 'Server identity unavailable', reason: 'server_identity_unavailable' })
|
|
829
|
+
return
|
|
830
|
+
}
|
|
831
|
+
const pin = suppliedServerPin(req, body.serverInstanceId)
|
|
832
|
+
if (!pin) {
|
|
833
|
+
res.status(400).json({ error: 'Server identity pin required', reason: 'server_identity_pin_required' })
|
|
834
|
+
return
|
|
835
|
+
}
|
|
836
|
+
if (pin !== serverInstanceId) {
|
|
837
|
+
res.status(409).json({ error: 'Server identity mismatch', reason: 'server_instance_mismatch' })
|
|
838
|
+
return
|
|
839
|
+
}
|
|
840
|
+
if (store.findBySessionId(sessionId)) {
|
|
841
|
+
res.status(409).json({ error: 'This recording is saved as a meeting', reason: 'already_saved' })
|
|
842
|
+
return
|
|
843
|
+
}
|
|
844
|
+
if (savingSessions.has(sessionId)) {
|
|
845
|
+
res.status(409).json({ error: 'This recording is being saved', reason: 'saving' })
|
|
846
|
+
return
|
|
847
|
+
}
|
|
848
|
+
const confirmed = body.confirm === true
|
|
849
|
+
const result = await discardSilentMacCapture(sessionId, { dryRun: !confirmed })
|
|
850
|
+
if (!result.ok && result.reason === 'session_not_found') {
|
|
851
|
+
// Already discarded (a retry after a lost answer): the quarantine says so, and the answer is the same.
|
|
852
|
+
const disposition = readCaptureDisposition(sessionId)
|
|
853
|
+
if (disposition?.quarantineReason === 'discarded_no_sound') {
|
|
854
|
+
res.json({ sessionId, discarded: true, replayed: true, quarantined: disposition.dirName, retainedUntil: disposition.retainedUntil })
|
|
855
|
+
return
|
|
856
|
+
}
|
|
857
|
+
res.status(404).json({ error: 'The server holds no live session for this recording', reason: 'session_not_found' })
|
|
858
|
+
return
|
|
859
|
+
}
|
|
860
|
+
if (!result.ok) {
|
|
861
|
+
const message: Record<string, string> = {
|
|
862
|
+
has_speech: 'This recording has speech; save it instead',
|
|
863
|
+
asr_in_progress: 'Audio is still being transcribed; try again in a moment',
|
|
864
|
+
chunk_in_progress: 'An audio chunk is still arriving; try again in a moment',
|
|
865
|
+
not_idle: 'This recording is still receiving audio',
|
|
866
|
+
not_mac_capture: 'Only a Mac recording can be discarded here',
|
|
867
|
+
}
|
|
868
|
+
res.status(409).json({ error: message[result.reason ?? ''] ?? 'Not discarded', reason: result.reason, receivedCount: result.receivedCount })
|
|
869
|
+
return
|
|
870
|
+
}
|
|
871
|
+
if (!confirmed) {
|
|
872
|
+
res.status(400).json({
|
|
873
|
+
error: 'Confirmation required', reason: 'confirmation_required',
|
|
874
|
+
preview: { sessionId, chunkFiles: result.chunkFiles, receivedCount: result.receivedCount, retentionHours: 24 },
|
|
875
|
+
})
|
|
876
|
+
return
|
|
877
|
+
}
|
|
878
|
+
console.warn(`[meeting/discard] Discarded no-sound Mac capture ${sessionId}: ${result.receivedCount} chunk(s) received, audio quarantined for 24 h`)
|
|
879
|
+
res.json({ sessionId, discarded: true, replayed: false, quarantined: result.quarantined ? basename(result.quarantined) : null,
|
|
880
|
+
chunkFiles: result.chunkFiles, receivedCount: result.receivedCount, retainedUntil: result.retainedUntil })
|
|
881
|
+
})
|
|
882
|
+
|
|
808
883
|
// ── Stop a live G2 meeting from the Mac (COS Control) ────────────────────────────
|
|
809
884
|
// The Mac never saves a live G2 session itself (lib/meeting-stop-requests.ts says why).
|
|
810
885
|
// It asks the glasses: POST records the request and puts `meeting_stop_requested` on the
|
|
@@ -49,7 +49,9 @@ import {
|
|
|
49
49
|
discardPolishPrewarm, isPrewarmModel, prewarmEnabled, PrewarmUnavailableError, runWarmPolish,
|
|
50
50
|
startPolishPrewarm, takePolishPrewarm,
|
|
51
51
|
} from '../lib/dictation-prewarm.js'
|
|
52
|
-
import { getVocabulary } from '../lib/profile.js'
|
|
52
|
+
import { getVocabulary, getWhisperCorrections } from '../lib/profile.js'
|
|
53
|
+
import { correctionOnlyForms } from '../lib/glossary-learn.js'
|
|
54
|
+
import { polishLinkProblem, renderSpokenPaths, spokenPathsEnabled } from '../lib/dictation-format.js'
|
|
53
55
|
import { createBreaker } from '../lib/claude-circuit.js'
|
|
54
56
|
import { logTokenAudit } from '../lib/token-audit.js'
|
|
55
57
|
import { emitDisplay } from '../lib/display-bus.js'
|
|
@@ -90,7 +92,7 @@ const autoCleanBreakers = {
|
|
|
90
92
|
const autoCleanDefaultEnabled = () => ['1', 'true', 'on'].includes((process.env.COS_DICTATION_AUTOCLEAN ?? '').toLowerCase())
|
|
91
93
|
|
|
92
94
|
/** 6.79.1, additive on finalize answers: why the polish model did not run (or did not finish). */
|
|
93
|
-
export type PolishSkipped = 'disabled' | 'too_long' | 'breaker_open' | 'daily_cap' | 'failed' | 'clean'
|
|
95
|
+
export type PolishSkipped = 'disabled' | 'too_long' | 'breaker_open' | 'daily_cap' | 'failed' | 'clean' | 'link_guard'
|
|
94
96
|
/** 6.79.2, additive when finalize was given a prewarmToken: what became of that warm process. */
|
|
95
97
|
export type PrewarmOutcome = 'used' | 'missed' | 'discarded'
|
|
96
98
|
|
|
@@ -144,6 +146,9 @@ async function polishOutboundDictation(
|
|
|
144
146
|
}
|
|
145
147
|
// 6.79.1: um/uh never survive a skipped polish. Meeting lines stay faithful.
|
|
146
148
|
if (opts.bucket !== 'meeting' && fillerPassEnabled()) cleaned = stripDisfluencies(cleaned)
|
|
149
|
+
// 6.83.1: "forward slash pricing," is "/pricing," even when the model is skipped. One word
|
|
150
|
+
// at a phrase end only; slugs of several words are the model's (dictation-format.ts).
|
|
151
|
+
if (opts.bucket !== 'meeting' && spokenPathsEnabled()) cleaned = renderSpokenPaths(cleaned)
|
|
147
152
|
if (!(opts.enabled ?? autoCleanDefaultEnabled())) return { text: cleaned, polishSkipped: 'disabled' }
|
|
148
153
|
const model = opts.model ?? 'haiku'
|
|
149
154
|
const autoCleanBreaker = autoCleanBreakers[model]
|
|
@@ -174,6 +179,14 @@ async function polishOutboundDictation(
|
|
|
174
179
|
source: 'g2-dictation-autoclean', model, inputChars: cleaned.length, outputChars: polished.length,
|
|
175
180
|
durationMs: Date.now() - startedAt, caller: `dictation_autoclean_${opts.bucket}`,
|
|
176
181
|
})
|
|
182
|
+
// 6.83.1: the model never invents a link and never drops one the dictionary wrote. Its
|
|
183
|
+
// answer is refused (the pre-polish text goes out, polishSkipped "link_guard") rather than
|
|
184
|
+
// pasting a URL nobody said. The call still counted: it ran.
|
|
185
|
+
const linkProblem = polished ? polishLinkProblem(cleaned, polished, correctionOnlyForms(getWhisperCorrections()), getVocabulary()) : null
|
|
186
|
+
if (linkProblem) {
|
|
187
|
+
console.warn(`[prompt-draft] auto-clean answer refused: ${linkProblem}`)
|
|
188
|
+
return { text: cleaned, ...(prewarm ? { prewarm } : {}), polishSkipped: 'link_guard' }
|
|
189
|
+
}
|
|
177
190
|
return { text: polished || cleaned, ...(prewarm ? { prewarm } : {}) }
|
|
178
191
|
} catch (err: any) {
|
|
179
192
|
autoCleanBreaker.recordFailure()
|