@teamvibe/poller 0.8.2-rc.2 → 0.8.3-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/classify-failed-iteration.d.ts +7 -0
  2. package/dist/classify-failed-iteration.js +12 -0
  3. package/dist/claude-quota.d.ts +15 -0
  4. package/dist/claude-quota.js +188 -0
  5. package/dist/claude-rate-limit.d.ts +19 -0
  6. package/dist/claude-rate-limit.js +44 -0
  7. package/dist/claude-spawner.d.ts +15 -0
  8. package/dist/claude-spawner.js +323 -25
  9. package/dist/config-client.d.ts +2 -0
  10. package/dist/config-client.js +3 -0
  11. package/dist/event-queue.js +2 -2
  12. package/dist/inbox-manager.d.ts +22 -1
  13. package/dist/inbox-manager.js +57 -3
  14. package/dist/inbox-watcher.d.ts +1 -1
  15. package/dist/inbox-watcher.js +42 -20
  16. package/dist/poller.d.ts +1 -0
  17. package/dist/poller.js +316 -54
  18. package/dist/pool-defer.d.ts +13 -0
  19. package/dist/pool-defer.js +81 -0
  20. package/dist/pool-logging.d.ts +18 -0
  21. package/dist/pool-logging.js +79 -0
  22. package/dist/pool-telemetry.d.ts +44 -0
  23. package/dist/pool-telemetry.js +107 -0
  24. package/dist/quota-pause.d.ts +16 -0
  25. package/dist/quota-pause.js +96 -0
  26. package/dist/session-store.d.ts +2 -2
  27. package/dist/session-store.js +6 -3
  28. package/dist/slack-client.d.ts +4 -1
  29. package/dist/slack-client.js +19 -1
  30. package/dist/subscription-pool-client.d.ts +35 -0
  31. package/dist/subscription-pool-client.js +143 -0
  32. package/dist/subscription-pool.d.ts +21 -0
  33. package/dist/subscription-pool.js +30 -0
  34. package/dist/subscription-runtime.d.ts +57 -0
  35. package/dist/subscription-runtime.js +126 -0
  36. package/dist/subscription-selection.d.ts +77 -0
  37. package/dist/subscription-selection.js +157 -0
  38. package/dist/subscription-usage-probe.d.ts +16 -0
  39. package/dist/subscription-usage-probe.js +106 -0
  40. package/dist/subscription-usage-store.d.ts +50 -0
  41. package/dist/subscription-usage-store.js +223 -0
  42. package/dist/types.d.ts +35 -10
  43. package/dist/usage-limit-messages.d.ts +22 -0
  44. package/dist/usage-limit-messages.js +44 -0
  45. package/dist/usage-probe-job.d.ts +17 -0
  46. package/dist/usage-probe-job.js +186 -0
  47. package/dist/worktree-manager.js +4 -0
  48. package/npm-shrinkwrap.json +78 -77
  49. package/package.json +1 -1
@@ -0,0 +1,223 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+ import { parseClaudeRateLimitInfo } from './claude-rate-limit.js';
5
+ import { normalizePassiveUsage, record, reactiveEligibleAt, PASSIVE_USAGE_TTL_MS } from './subscription-selection.js';
6
+ export function usageStateForSelection(state, now) {
7
+ const passive = state.passive ? normalizePassiveUsage(state.passive.rateLimitInfo, state.passive.observedAt) : undefined;
8
+ // Passive is primary while fresh; a completed optional probe may supplement a stale/missing snapshot.
9
+ const fresh = passive && passive.observedAt <= now && now < passive.observedAt + PASSIVE_USAGE_TTL_MS;
10
+ return { usage: fresh ? passive : state.probe?.status === 'ok' ? state.probe.usage : passive, reactive: state.reactive };
11
+ }
12
+ export class SubscriptionUsageStoreError extends Error {
13
+ constructor() { super('Subscription usage store unavailable'); this.name = 'SubscriptionUsageStoreError'; }
14
+ }
15
+ // Serialize atomic read/modify/write operations across instances in this process.
16
+ const writes = new Map();
17
+ async function serial(path, work) {
18
+ const previous = writes.get(path) ?? Promise.resolve();
19
+ const next = previous.catch(() => { }).then(work);
20
+ writes.set(path, next);
21
+ try {
22
+ return await next;
23
+ }
24
+ finally {
25
+ if (writes.get(path) === next)
26
+ writes.delete(path);
27
+ }
28
+ }
29
+ function validTime(now) {
30
+ if (typeof now !== 'number' || !Number.isFinite(now) || now <= 0 || now > 253402300799000)
31
+ throw new SubscriptionUsageStoreError();
32
+ }
33
+ export function safeRateLimitInfo(info) {
34
+ const parsed = parseClaudeRateLimitInfo(info) ?? {};
35
+ // Never persist arbitrary status strings or incidental stream fields.
36
+ if (parsed.status !== 'allowed' && parsed.status !== 'allowed_warning' && parsed.status !== 'rejected')
37
+ delete parsed.status;
38
+ if (parsed.rateLimitType && !/^(five_hour|seven_day)(?:_(sonnet|opus|haiku|fable))?$/.test(parsed.rateLimitType))
39
+ parsed.rateLimitType = 'uncertain';
40
+ delete parsed.overageStatus;
41
+ delete parsed.overageDisabledReason;
42
+ return parsed;
43
+ }
44
+ export function safeQuota(quota) {
45
+ const scope = typeof quota.modelScope === 'string' ? quota.modelScope.toLowerCase().match(/^(?:claude-)?(sonnet|opus|haiku)(?:-\d[\w.-]*)?$/)?.[1] : undefined;
46
+ const reset = typeof quota.resetAt === 'string' ? Date.parse(quota.resetAt) : NaN;
47
+ return {
48
+ reason: ['usage_limit', 'weekly_limit', 'session_limit', 'extra_usage'].includes(quota.reason) ? quota.reason : 'usage_limit',
49
+ ...(quota.window === 'five_hour' || quota.window === 'seven_day' ? { window: quota.window } : {}),
50
+ ...(quota.modelScope ? { modelScope: scope ?? 'uncertain' } : {}),
51
+ ...(Number.isFinite(reset) && reset > 0 ? { resetAt: new Date(reset).toISOString() } : {}),
52
+ };
53
+ }
54
+ function safeProbe(value) {
55
+ const obj = record(value);
56
+ const status = obj['status'];
57
+ if (typeof status !== 'string' || !['attempted', 'ok', 'unsupported', 'unauthorized', 'unavailable', 'cancelled'].includes(status))
58
+ throw new SubscriptionUsageStoreError();
59
+ const observedAt = obj['observedAt'];
60
+ if (typeof observedAt !== 'number')
61
+ throw new SubscriptionUsageStoreError();
62
+ validTime(observedAt);
63
+ const result = { status: status, observedAt };
64
+ if (status === 'ok' && obj['usage']) {
65
+ const usage = record(obj['usage']);
66
+ if (typeof usage['observedAt'] !== 'number' || !Array.isArray(usage['windows']))
67
+ throw new SubscriptionUsageStoreError();
68
+ validTime(usage['observedAt']);
69
+ const windows = usage['windows'].slice(0, 133).map(raw => {
70
+ const w = record(raw);
71
+ const window = w['window'] === 'five_hour' ? 'five_hour' : 'seven_day';
72
+ const scope = typeof w['scope'] === 'string' && ['global', 'sonnet', 'opus', 'haiku', 'fable'].includes(w['scope']) ? w['scope'] : 'uncertain';
73
+ const percent = typeof w['percent'] === 'number' && Number.isFinite(w['percent']) && w['percent'] >= 0 && w['percent'] <= 100 ? w['percent'] : undefined;
74
+ const resetAt = typeof w['resetAt'] === 'number' && Number.isFinite(w['resetAt']) && w['resetAt'] > 0 && w['resetAt'] <= 253402300799000 ? w['resetAt'] : undefined;
75
+ return { window, scope, percent, resetAt };
76
+ });
77
+ if (usage['windows'].length > 133)
78
+ windows.push({ window: 'seven_day', scope: 'uncertain' });
79
+ result.usage = { source: 'probe', observedAt: usage['observedAt'], windows };
80
+ }
81
+ return result;
82
+ }
83
+ function safeVersion(value) {
84
+ const state = {};
85
+ if (value.passive) {
86
+ validTime(value.passive.observedAt);
87
+ state.passive = { observedAt: value.passive.observedAt, rateLimitInfo: safeRateLimitInfo(value.passive.rateLimitInfo) };
88
+ }
89
+ if (value.probe)
90
+ state.probe = safeProbe(value.probe);
91
+ return state;
92
+ }
93
+ function safeReactive(value) {
94
+ if (!Array.isArray(value) || value.length > 64)
95
+ throw new SubscriptionUsageStoreError();
96
+ return value.map(raw => {
97
+ const obj = record(raw);
98
+ if (typeof obj['observedAt'] !== 'number' || !obj['quota'] || typeof obj['quota'] !== 'object')
99
+ throw new SubscriptionUsageStoreError();
100
+ validTime(obj['observedAt']);
101
+ return { observedAt: obj['observedAt'], quota: safeQuota(obj['quota']) };
102
+ });
103
+ }
104
+ /** One file per version + one reactive file per workspace/account. No credentials or raw provider bodies. */
105
+ export class FileSubscriptionUsageStore {
106
+ #directory;
107
+ constructor(directory) { this.#directory = resolve(directory); }
108
+ #path(key, version) {
109
+ const parts = version ? [key.workspaceId, key.accountId, key.credentialVersion] : [key.workspaceId, key.accountId];
110
+ if (parts.some(p => typeof p !== 'string' || !p))
111
+ throw new SubscriptionUsageStoreError();
112
+ return join(this.#directory, `${createHash('sha256').update(JSON.stringify(parts)).digest('hex')}.json`);
113
+ }
114
+ async #load(path, fallback) {
115
+ try {
116
+ const raw = await readFile(path, 'utf8');
117
+ if (raw.length > 1024 * 1024)
118
+ throw new SubscriptionUsageStoreError();
119
+ const value = JSON.parse(raw);
120
+ if (!value || typeof value !== 'object' || Array.isArray(value))
121
+ throw new SubscriptionUsageStoreError();
122
+ return value;
123
+ }
124
+ catch (error) {
125
+ if (error.code === 'ENOENT')
126
+ return fallback;
127
+ throw new SubscriptionUsageStoreError();
128
+ }
129
+ }
130
+ async #save(path, value) {
131
+ const temporary = `${path}.${randomUUID()}.tmp`;
132
+ try {
133
+ await mkdir(this.#directory, { recursive: true, mode: 0o700 });
134
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
135
+ await rename(temporary, path);
136
+ }
137
+ catch {
138
+ throw new SubscriptionUsageStoreError();
139
+ }
140
+ finally {
141
+ await rm(temporary, { force: true }).catch(() => { });
142
+ }
143
+ }
144
+ async read(key) {
145
+ const [version, account] = await Promise.all([
146
+ this.#load(this.#path(key, true), {}),
147
+ this.#load(this.#path(key, false), { reactive: [] }),
148
+ ]);
149
+ // Corrupt reactive data must never silently resurrect an exhausted account.
150
+ if (!Array.isArray(account.reactive) || account.reactive.some(r => !r || !Number.isFinite(r.observedAt) || !r.quota))
151
+ throw new SubscriptionUsageStoreError();
152
+ return { ...safeVersion(version), reactive: safeReactive(account.reactive) };
153
+ }
154
+ async recordPassive(key, rateLimitInfo, observedAt, options) {
155
+ validTime(observedAt);
156
+ const path = this.#path(key, true);
157
+ await serial(path, async () => {
158
+ const state = safeVersion(await this.#load(path, {}));
159
+ if (state.passive && state.passive.observedAt > observedAt && !options?.expireFutureObservations)
160
+ return;
161
+ state.passive = { rateLimitInfo: safeRateLimitInfo(rateLimitInfo), observedAt };
162
+ await this.#save(path, state);
163
+ });
164
+ }
165
+ async recordQuota(key, quota, observedAt, options) {
166
+ validTime(observedAt);
167
+ const path = this.#path(key, false);
168
+ await serial(path, async () => {
169
+ const state = await this.#load(path, { reactive: [] });
170
+ state.reactive = safeReactive(state.reactive).filter(r => !options?.expireFutureObservations || r.observedAt <= observedAt);
171
+ const next = { observedAt, quota: safeQuota(quota) };
172
+ const until = reactiveEligibleAt;
173
+ const sameScope = (r) => r.quota.modelScope === next.quota.modelScope && r.quota.window === next.quota.window;
174
+ const previous = state.reactive.find(sameScope);
175
+ const reactive = state.reactive.filter(r => !sameScope(r) && until(r) > observedAt);
176
+ const hasExplicitReset = (r) => r.quota.resetAt !== undefined && Date.parse(r.quota.resetAt) > r.observedAt;
177
+ // A recheck is not a reset. New matching quota evidence can replace that
178
+ // provisional deadline with its explicit reset, without clearing a known
179
+ // active reset or accepting an older observation as revalidation.
180
+ const revalidated = previous && next.observedAt >= previous.observedAt && !hasExplicitReset(previous) && hasExplicitReset(next);
181
+ reactive.push(previous && !revalidated && until(previous) > until(next) ? previous : next);
182
+ await this.#save(path, { reactive });
183
+ });
184
+ }
185
+ async beginProbe(key, observedAt) {
186
+ validTime(observedAt);
187
+ const path = this.#path(key, true);
188
+ return serial(path, async () => {
189
+ const state = safeVersion(await this.#load(path, {}));
190
+ if (state.probe)
191
+ return false;
192
+ state.probe = { status: 'attempted', observedAt };
193
+ await this.#save(path, state);
194
+ return true;
195
+ });
196
+ }
197
+ /** Request claims live in the local data directory, alongside usage, never in a brain. */
198
+ async claimProbeRequest(requestId, expiresAt) {
199
+ validTime(expiresAt);
200
+ const path = join(this.#directory, 'processed-probe-requests.json');
201
+ return serial(path, async () => {
202
+ const now = Date.now();
203
+ const stored = await this.#load(path, {});
204
+ if (Object.values(stored).some(expiry => !Number.isFinite(expiry)))
205
+ throw new SubscriptionUsageStoreError();
206
+ const claims = Object.fromEntries(Object.entries(stored).filter(([, expiry]) => expiry > now));
207
+ if (Object.hasOwn(claims, requestId))
208
+ return false;
209
+ claims[requestId] = Math.max(expiresAt, now + 30 * 60_000);
210
+ await this.#save(path, claims);
211
+ return true;
212
+ });
213
+ }
214
+ async finishProbe(key, observation) {
215
+ validTime(observation.observedAt);
216
+ const path = this.#path(key, true);
217
+ await serial(path, async () => {
218
+ const state = safeVersion(await this.#load(path, {}));
219
+ state.probe = safeProbe(observation);
220
+ await this.#save(path, state);
221
+ });
222
+ }
223
+ }
package/dist/types.d.ts CHANGED
@@ -4,7 +4,7 @@ export interface ControlMessage {
4
4
  action: 'restart' | 'update';
5
5
  targetVersion?: string;
6
6
  }
7
- export type QueueMessage = TeamVibeQueueMessage | ControlMessage;
7
+ export type QueueMessage = TeamVibeQueueMessage | ControlMessage | UsageProbeMessage;
8
8
  export interface TeamVibeQueueMessage {
9
9
  id: string;
10
10
  source: 'slack' | 'email' | 'cron' | 'maintenance' | 'webhook';
@@ -66,7 +66,20 @@ export interface TeamVibeQueueMessage {
66
66
  emailHookPrompt?: string;
67
67
  };
68
68
  }
69
+ export interface SubscriptionPin {
70
+ inboxFilename?: string;
71
+ resumePending?: boolean;
72
+ effectiveCwd?: string;
73
+ claudeConfigDir?: string;
74
+ sawSendMessageCall?: boolean;
75
+ workspaceId: string;
76
+ accountId: string;
77
+ credentialVersion: string;
78
+ model?: string;
79
+ modelSource?: import('./claude-spawner.js').ModelSource;
80
+ }
69
81
  export interface SessionRecord {
82
+ subscription_pin?: SubscriptionPin;
70
83
  PK: string;
71
84
  SK: string;
72
85
  session_id: string;
@@ -81,13 +94,25 @@ export interface SessionRecord {
81
94
  }
82
95
  export type SessionStatus = 'processing' | 'idle' | 'waiting_for_input';
83
96
  export interface SessionMetrics {
84
- duration_ms: number;
85
- duration_api_ms: number;
86
- num_turns: number;
87
- total_cost_usd: number;
88
- input_tokens: number;
89
- output_tokens: number;
90
- cache_read_input_tokens: number;
91
- cache_creation_input_tokens: number;
92
- model: string;
97
+ /** Input occupancy of the last assistant message, independent of run totals. */
98
+ context_tokens?: number;
99
+ context_window?: number;
100
+ duration_ms?: number;
101
+ duration_api_ms?: number;
102
+ num_turns?: number;
103
+ total_cost_usd?: number;
104
+ input_tokens?: number;
105
+ output_tokens?: number;
106
+ cache_read_input_tokens?: number;
107
+ cache_creation_input_tokens?: number;
108
+ model?: string;
109
+ }
110
+ export interface UsageProbeMessage {
111
+ kind: 'usage_probe';
112
+ id: string;
113
+ workspaceId: string;
114
+ accountId: string;
115
+ credentialVersion: string;
116
+ requestId: string;
117
+ expiresAt: number;
93
118
  }
@@ -0,0 +1,22 @@
1
+ /** Owner-facing account policy location. */
2
+ export declare const FULL_QUOTA_SETTINGS_PATH = "Settings \u2192 Connections (account menu \u2192 Use until exhausted)";
3
+ export interface UsageResetTiming {
4
+ resetAt?: number;
5
+ now?: number;
6
+ timeZone?: string;
7
+ }
8
+ export interface UsageLimitAccount {
9
+ useFullQuota?: boolean;
10
+ label?: string;
11
+ windows: readonly {
12
+ percent?: number;
13
+ }[];
14
+ rejected?: boolean;
15
+ }
16
+ export interface PoolUsageLimitNotice extends UsageResetTiming {
17
+ thresholdDeferred?: boolean;
18
+ accounts?: readonly UsageLimitAccount[];
19
+ }
20
+ export declare function formatUsageReset(input: UsageResetTiming): string | undefined;
21
+ export declare function formatPoolUsageLimitMessage(input: PoolUsageLimitNotice): string;
22
+ export declare function formatLegacyUsageLimitMessage(input: UsageResetTiming): string;
@@ -0,0 +1,44 @@
1
+ /** Owner-facing account policy location. */
2
+ export const FULL_QUOTA_SETTINGS_PATH = 'Settings → Connections (account menu → Use until exhausted)';
3
+ export function formatUsageReset(input) {
4
+ if (input.resetAt === undefined || !Number.isFinite(input.resetAt))
5
+ return undefined;
6
+ const now = input.now ?? Date.now();
7
+ let time;
8
+ try {
9
+ time = new Intl.DateTimeFormat('en-GB', {
10
+ timeZone: input.timeZone || 'UTC', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
11
+ }).format(input.resetAt) + (input.timeZone ? '' : ' UTC');
12
+ }
13
+ catch {
14
+ time = new Intl.DateTimeFormat('en-GB', {
15
+ timeZone: 'UTC', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
16
+ }).format(input.resetAt) + ' UTC';
17
+ }
18
+ // Round up so a reset less than a minute away is not advertised as immediate.
19
+ const minutes = Math.max(0, Math.ceil((input.resetAt - now) / 60_000));
20
+ const days = Math.floor(minutes / 1440);
21
+ const hours = Math.floor(minutes % 1440 / 60);
22
+ const remainder = minutes % 60;
23
+ const relative = [days ? `${days} d` : '', hours ? `${hours} h` : '', remainder || !minutes ? `${remainder} min` : ''].filter(Boolean).join(' ');
24
+ return `${time} (in ${relative})`;
25
+ }
26
+ export function formatPoolUsageLimitMessage(input) {
27
+ const accounts = input.accounts ?? [];
28
+ const headroom = accounts.filter(account => !account.useFullQuota && !account.rejected).map(account => {
29
+ const percentages = account.windows.map(w => w.percent).filter((p) => p !== undefined && Number.isFinite(p) && p >= 0 && p <= 100);
30
+ return { label: account.label, remaining: percentages.length ? 100 - Math.max(...percentages) : 0 };
31
+ });
32
+ const threshold = input.thresholdDeferred === true &&
33
+ !accounts.some(a => a.rejected) && headroom.reduce((sum, a) => sum + a.remaining, 0) > 0;
34
+ const reset = formatUsageReset(input);
35
+ if (threshold) {
36
+ const labels = headroom.filter(a => a.label && a.remaining > 0).map(a => `${a.label} ${Number(a.remaining.toFixed(2))} %`).join(', ');
37
+ return `⏳ All Claude accounts in this workspace are above 90 % of their usage limit, so I'm waiting for the next reset${reset ? ` at ${reset}` : ''}. Your message is saved and will run automatically.\n💡 There is still some capacity left${labels ? ` (${labels})` : ''}. A workspace owner can allow the full quota per account in ${FULL_QUOTA_SETTINGS_PATH}.`;
38
+ }
39
+ return `⏳ All Claude accounts in this workspace have hit their usage limit. Your message is saved and will run automatically after ${reset ? `the earliest reset at ${reset}` : 'the next reset'}.`;
40
+ }
41
+ export function formatLegacyUsageLimitMessage(input) {
42
+ const reset = formatUsageReset(input);
43
+ return `⏳ This poller's Claude login has hit its usage limit. Your message is saved and will run automatically after ${reset ? `the reset at ${reset}` : 'the next reset'}.`;
44
+ }
@@ -0,0 +1,17 @@
1
+ import type { UsageProbeMessage } from './types.js';
2
+ import type { PoolFetchResult } from './subscription-selection.js';
3
+ import type { SubscriptionAccount } from './subscription-pool-client.js';
4
+ import { type SubscriptionUsageStore } from './subscription-usage-store.js';
5
+ interface Options {
6
+ fetchPool: () => Promise<PoolFetchResult<SubscriptionAccount>>;
7
+ store: SubscriptionUsageStore;
8
+ cliPath: string;
9
+ timeoutMs?: number;
10
+ isAtCapacity: () => boolean;
11
+ emit: (type: string, channelId: string, metadata: Record<string, unknown>) => void;
12
+ log: (line: string) => void;
13
+ }
14
+ export declare function isUsageProbe(value: unknown): value is UsageProbeMessage;
15
+ /** This run deliberately has no message/session/brain context or normal spawn bookkeeping. */
16
+ export declare function handleUsageProbe(job: UsageProbeMessage, options: Options): Promise<void>;
17
+ export {};
@@ -0,0 +1,186 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdtemp, rm, mkdir } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { normalizePassiveUsage } from './subscription-selection.js';
6
+ import { safeRateLimitInfo, } from './subscription-usage-store.js';
7
+ import { parseClaudeRateLimitInfo, } from './claude-rate-limit.js';
8
+ export function isUsageProbe(value) {
9
+ return (!!value &&
10
+ typeof value === 'object' &&
11
+ value.kind === 'usage_probe');
12
+ }
13
+ /** This run deliberately has no message/session/brain context or normal spawn bookkeeping. */
14
+ export async function handleUsageProbe(job, options) {
15
+ let result = 'unknown';
16
+ let duplicate = false;
17
+ let cwd;
18
+ if (!['workspaceId', 'accountId', 'credentialVersion', 'requestId'].every((k) => {
19
+ const value = job[k];
20
+ return (typeof value === 'string' &&
21
+ /^[A-Za-z0-9_-]{1,128}$/.test(value) &&
22
+ !/sk-ant-/i.test(value));
23
+ }) ||
24
+ !Number.isFinite(job.expiresAt) ||
25
+ job.expiresAt <= Date.now())
26
+ return;
27
+ const metadata = {
28
+ workspaceId: job.workspaceId,
29
+ accountId: job.accountId,
30
+ credentialVersion: job.credentialVersion,
31
+ requestId: job.requestId,
32
+ source: 'probe',
33
+ };
34
+ try {
35
+ if (!(await options.store.claimProbeRequest(job.requestId, job.expiresAt))) {
36
+ duplicate = true;
37
+ options.log(`[Pool] usage probe request=${job.requestId} result=duplicate_ignored`);
38
+ return;
39
+ }
40
+ const pool = await options.fetchPool();
41
+ const account = pool.kind === 'ready'
42
+ ? pool.accounts.find((a) => a.workspaceId === job.workspaceId &&
43
+ a.accountId === job.accountId &&
44
+ a.credentialVersion === job.credentialVersion &&
45
+ a.enabled)
46
+ : undefined;
47
+ if (!account)
48
+ return;
49
+ if (options.isAtCapacity()) {
50
+ result = 'cli_at_capacity';
51
+ return;
52
+ }
53
+ cwd = await mkdtemp(join(tmpdir(), 'teamvibe-usage-'));
54
+ const configDir = join(cwd, 'config');
55
+ await mkdir(configDir);
56
+ // Allow only OS execution essentials. No ambient credentials, Slack, API,
57
+ // brain, hooks, or user's Claude settings reach this isolated child.
58
+ const env = {
59
+ PATH: process.env['PATH'],
60
+ HOME: cwd,
61
+ TMPDIR: cwd,
62
+ CLAUDE_CONFIG_DIR: configDir,
63
+ CLAUDE_CODE_OAUTH_TOKEN: account.credential.unwrap(),
64
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
65
+ };
66
+ let info;
67
+ const outcome = await new Promise((resolve) => {
68
+ let done = false, buffer = '', errorText = '';
69
+ const child = spawn(options.cliPath, [
70
+ '-p',
71
+ 'Reply OK.',
72
+ '--output-format',
73
+ 'stream-json',
74
+ '--verbose',
75
+ '--max-turns',
76
+ '1',
77
+ '--tools',
78
+ '',
79
+ '--strict-mcp-config',
80
+ '--mcp-config',
81
+ '{"mcpServers":{}}',
82
+ '--no-session-persistence',
83
+ '--setting-sources',
84
+ '',
85
+ ], { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
86
+ const kill = () => {
87
+ if (child.pid) {
88
+ try {
89
+ process.kill(-child.pid, 'SIGKILL');
90
+ }
91
+ catch {
92
+ child.kill('SIGKILL');
93
+ }
94
+ }
95
+ };
96
+ const finish = (reason) => {
97
+ if (done)
98
+ return;
99
+ done = true;
100
+ clearTimeout(timer);
101
+ resolve(reason);
102
+ };
103
+ const timer = setTimeout(() => {
104
+ kill();
105
+ finish('timeout');
106
+ }, Math.min(options.timeoutMs ?? 60_000, Math.max(1, job.expiresAt - Date.now())));
107
+ const line = (text) => {
108
+ try {
109
+ const event = JSON.parse(text);
110
+ if (event?.type === 'rate_limit_event')
111
+ info = parseClaudeRateLimitInfo(event.rate_limit_info);
112
+ if (event?.type === 'result' && event.is_error)
113
+ errorText = (errorText + String(event.result ?? '').slice(0, 4096)).slice(-8192);
114
+ }
115
+ catch { }
116
+ };
117
+ child.stdout.on('data', (chunk) => {
118
+ buffer += chunk.toString();
119
+ if (buffer.length > 1024 * 1024) {
120
+ kill();
121
+ finish('unknown');
122
+ return;
123
+ }
124
+ let end;
125
+ while ((end = buffer.indexOf('\n')) >= 0) {
126
+ line(buffer.slice(0, end));
127
+ buffer = buffer.slice(end + 1);
128
+ }
129
+ });
130
+ child.stderr.on('data', (chunk) => {
131
+ errorText = (errorText + chunk.toString()).slice(-8192);
132
+ });
133
+ child.once('error', () => finish('unknown'));
134
+ // Quota rejection is still a successful observation: it reveals reset
135
+ // time without requiring the account to complete an assistant turn.
136
+ child.once('close', (code) => {
137
+ if (buffer)
138
+ line(buffer);
139
+ finish(/401|unauthorized|invalid.*token|invalid api key|authentication.*(?:fail|error)/i.test(errorText)
140
+ ? 'token_rejected'
141
+ : /capacity|overloaded/i.test(errorText)
142
+ ? 'cli_at_capacity'
143
+ : info && (code === 0 || info.status === 'rejected')
144
+ ? 'ok'
145
+ : 'unknown');
146
+ });
147
+ });
148
+ result = outcome;
149
+ if (result !== 'ok' || !info)
150
+ return;
151
+ const now = Date.now();
152
+ const safe = safeRateLimitInfo(info);
153
+ const usage = {
154
+ ...normalizePassiveUsage(safe, now),
155
+ source: 'probe',
156
+ };
157
+ await options.store.finishProbe(account, {
158
+ status: 'ok',
159
+ observedAt: now,
160
+ usage,
161
+ });
162
+ options.emit('pool.usage_observed', 'usage_probe', {
163
+ ...metadata,
164
+ accountLabel: account.label ?? account.accountId,
165
+ reportedAt: now,
166
+ usage,
167
+ lastRateLimitInfo: safe,
168
+ probeStatus: 'ok',
169
+ probeObservedAt: now,
170
+ });
171
+ }
172
+ catch {
173
+ result = 'unknown';
174
+ }
175
+ finally {
176
+ if (cwd)
177
+ await rm(cwd, { recursive: true, force: true }).catch(() => { });
178
+ if (!duplicate && result !== 'ok')
179
+ options.emit('pool.probe_failed', 'usage_probe', {
180
+ ...metadata,
181
+ reason: result,
182
+ });
183
+ if (!duplicate)
184
+ options.log(`[Pool] usage probe account=${job.accountId} result=${result}`);
185
+ }
186
+ }
@@ -2,6 +2,7 @@ import { mkdir, readdir, stat, appendFile, readFile } from 'fs/promises';
2
2
  import { join } from 'path';
3
3
  import { execFile } from 'child_process';
4
4
  import { promisify } from 'util';
5
+ import { readInboxRuntime } from './inbox-manager.js';
5
6
  const execFileAsync = promisify(execFile);
6
7
  const WORKTREES_SUBDIR = '.worktrees';
7
8
  const EXCLUDE_ENTRY = `${WORKTREES_SUBDIR}/\n`;
@@ -94,6 +95,9 @@ export async function cleanupOrphanWorktrees(brainPath, maxAgeMs = 24 * 60 * 60
94
95
  const cutoffMs = Date.now() - maxAgeMs;
95
96
  for (const entry of entries) {
96
97
  const path = join(worktreesDir, entry);
98
+ const pending = readInboxRuntime(brainPath, entry);
99
+ if (pending?.pin.resumePending && pending.pin.effectiveCwd === path)
100
+ continue;
97
101
  try {
98
102
  const s = await stat(path);
99
103
  if (s.mtimeMs < cutoffMs) {