The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Swarm routing: spend a weekly window about to reset with quota left (window pull, goals piece 6) (#2425)
0xken15f5aaa464cd4c
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 62b4605dd..aabbfc353 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -144,6 +144,20 @@ describe('routeTask', () => {expect(await routeTask(input, s, where as never, opener(), () => 'op')).toMatchObject({ instructions: { revision: 1, notes: [] } })expect(leftOut([{ title: 't', reason: 'x'.repeat(301), machine: 'm' }], [])).toEqual([{ machine: 'm', reasons: [`${'x'.repeat(299)}…`] }])})+ it('pulls the task onto the account whose weekly window resets soon with quota left, through its listed maker (piece 6)', async () => {+ const reading = (account: string, weeklyUsed: number, weeklyResetsIn: number) => ({ providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, account,+ body: { five_hour: { utilization: 20, resets_at: new Date(Date.now() + 3 * 3_600_000).toISOString() },+ seven_day: { utilization: weeklyUsed, resets_at: new Date(Date.now() + weeklyResetsIn).toISOString() } } }] })+ // m1 (remote-1) has a fresh week; m2 (mac) resets in 12 hours with 60% left.+ const machines = opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], usage: id === 'm2' ? reading('acct-soon', 40, 12 * 3_600_000) : reading('acct-fresh', 10, 5 * 86_400_000) }))+ const plain = await routeTask(input, scoped(), where as never, machines, () => 'op', undefined, [])+ expect(plain).toMatchObject({ ok: true, pick: { title: expect.stringContaining('remote-1') } })+ const s = scoped()+ const pulled = await routeTask(input, s, where as never, machines, () => 'op')+ expect(pulled).toMatchObject({ ok: true, pick: { title: expect.stringContaining('mac') } })+ expect(labels(s)[0]).toContain('Window pull: its account\'s weekly window resets in 12h')+ expect(JSON.stringify(pulled)).not.toContain('acct-soon')+ })it('answers exactly as before with no makers, and with makers that have nothing to say', async () => {vi.useFakeTimers({ toFake: ['Date'] })try {diff --git a/cli/src/superTabs/routePlugins.spec.ts b/cli/src/superTabs/routePlugins.spec.tsindex 1fa499927..2364a3cfd 100644--- a/cli/src/superTabs/routePlugins.spec.ts+++ b/cli/src/superTabs/routePlugins.spec.ts@@ -12,8 +12,9 @@ const skipped = (name: string, why: string) => `The routing plug-in "${name}" waafterEach(() => { vi.useRealTimers() })describe('makePlugins', () => {- it('has no makers yet, and an empty list makes no plug-ins and no warnings', async () => {- expect(ROUTE_PLUGIN_MAKERS).toEqual([])+ it('names every maker, and an empty list makes no plug-ins and no warnings', async () => {+ // Each piece adds its own maker (windowPull.spec.ts checks piece 6's is listed), so this pins no list.+ expect(ROUTE_PLUGIN_MAKERS.every(m => !!m.name && typeof m.make === 'function')).toBe(true)expect(await makePlugins([], input)).toEqual({ plugins: [], warnings: [] })})it('gives each maker the task, the backend read, the shared history and the request, and keeps the makers\' order whatever order they finish in', async () => {diff --git a/cli/src/superTabs/routePlugins.ts b/cli/src/superTabs/routePlugins.tsindex 09b5e0b81..e2280990a 100644--- a/cli/src/superTabs/routePlugins.ts+++ b/cli/src/superTabs/routePlugins.ts@@ -4,6 +4,7 @@* routeTask starts every maker together with the machine probes, so a maker's read costs no time of its own. */import { pluginSkipped, type Assessment, type Catalog, type RoutePlugin } from './route.js'import type { ScopedRequest } from './start.js'+import { windowPullMaker } from './windowPull.js'type Json = Record<string, unknown>@@ -23,7 +24,9 @@ export interface PluginInput {export interface PluginMaker { readonly name: string; make(input: PluginInput): Promise<RoutePlugin | null> }/** The makers, in the order their plug-ins run. One line per piece. */-export const ROUTE_PLUGIN_MAKERS: readonly PluginMaker[] = []+export const ROUTE_PLUGIN_MAKERS: readonly PluginMaker[] = [+ windowPullMaker(),+]/** As long as the route's other context reads wait (wire.ts within): a maker's read is context too, never worth holding the* route for. */diff --git a/cli/src/superTabs/windowPull.spec.ts b/cli/src/superTabs/windowPull.spec.tsnew file mode 100644index 000000000..c21b10fe6--- /dev/null+++ b/cli/src/superTabs/windowPull.spec.ts@@ -0,0 +1,223 @@+// cli/src/superTabs/windowPull.spec.ts+import { describe, expect, it } from 'vitest'+import { choose, decide, recordOf, type Assessment, type Catalog, type Commitment, type Fit, type Probe, type RoutePlugin } from './route.js'+import { makePlugins, ROUTE_PLUGIN_MAKERS, type PluginInput } from './routePlugins.js'+import { MAX_DISCOUNT, pendingPicks, PENDING_MS, WINDOW_PULL, windowPull, windowPullAdjust, windowPullMaker, weeklyUnused } from './windowPull.js'++/** Today's rows (route.spec.ts): Opus high and Codex default both strength 3, Codex cheaper; Sonnet weaker. */+const policy: Catalog = { grid: { strength: 1, models: [] }, models: [+ { engine: 'claude', model: 'opus', effort: 'high', strength: 3, cost: 3, offered: true },+ { engine: 'codex', model: 'default', effort: 'default', strength: 3, cost: 2, offered: true },+ { engine: 'claude', model: 'sonnet', effort: 'medium', strength: 2, cost: 2, offered: true },+] }+const NOW = 1_800_000_000_000, M = 60_000, H = 3_600_000, D = 86_400_000+const a = (patch: Partial<Assessment> = {}): Assessment => ({ difficulty: 'medium', risk: 'low', size: 'medium', why: 'API change.', needs: { tools: [], devices: [] }, ...patch })+/** A reading with a 5-hour and a weekly window, each as [percent left, resets in]. */+type Win = [left: number, resetsIn: number | null] | null+const windows = (five: Win, week: Win, account: string): Probe['quota'] => {+ const read = ([['5-hour', five], ['weekly', week]] as const).flatMap(([name, w]) => w ? [{ name, leftPercent: w[0], resetsAt: w[1] === null ? null : NOW + w[1] }] : [])+ return { known: true, leftPercent: Math.min(...read.map(w => w.leftPercent)), resetsAt: null, windows: read, account }+}+/** Fresh: a weekly window far from its reset. Soon: resets in 12 hours with 60% left, of which this week's pace (40% used over+ * 156 hours) would spend about 3%, so about 57% would go unused. */+const FRESH = windows([80, 3 * H], [90, 5 * D], 'acct-fresh'), SOON = windows([80, 3 * H], [60, 12 * H], 'acct-soon')+const codex = (machine: string, quota: Probe['quota'], patch: Partial<Probe> = {}): Probe => ({ kind: 'new', machineId: machine, machineName: machine,+ engine: 'codex', model: 'default', effort: 'default', quality: 3, cost: 2, quota, activity: 'new agent', known: true, refusals: [], notes: [], ...patch })+const opusMember = (machine: string, quota: Probe['quota']): Probe => ({ ...codex(machine, quota), kind: 'member', agentId: 'agent-1', name: 'Orion',+ engine: 'claude', model: 'opus', effort: 'high', cost: 3, activity: 'idle', frame: null })+const ok = (r: ReturnType<typeof choose>) => { if ('error' in r) throw new Error('no candidate'); return r }+const route = (probes: Probe[], plugins: RoutePlugin[], open: Commitment[] = [], task: Partial<Assessment> = {}) => ok(choose(probes, policy, a(task), NOW, open, [], [], plugins))+const pull = windowPull([])+const noteOf = (p: { notes: string[] }) => p.notes.find(n => n.startsWith(`${WINDOW_PULL}:`))+/** A candidate as the plug-in sees it, after the route's fit. */+const fitted = (p: Probe, fit: Partial<Fit> = {}): Probe & { fit: Fit } => ({ ...p, fit: { status: 'fits', coverage: 1, effectiveCost: p.cost, expiring: 0,+ spend: { '5-hour': 30, weekly: 4 }, account: p.quota.account ?? '', ...fit } })++describe('the window pull ranks', () => {+ it('an account whose weekly window resets soon with quota left first, and says why', () => {+ const probes = [codex('alpha', FRESH), codex('zulu', SOON)]+ // Without it, the two tie on strength, price and fit, and the title decides.+ expect(route(probes, []).shown.map(s => s.machineId)).toEqual(['alpha', 'zulu'])+ const choice = route(probes, [pull])+ expect(choice.shown.map(s => s.machineId)).toEqual(['zulu', 'alpha'])+ const reason = 'Window pull: its account\'s weekly window resets in 12h, and at this week\'s pace about 57% of it would go unused; this task spends it first'+ expect(choice.shown[0]!.notes).toContain(reason)+ expect(choice.shown[0]!.label).toContain(reason)+ expect(noteOf(choice.shown[1]!)).toBeUndefined()+ const verdict = decide(choice)+ expect(verdict.pick.machineId).toBe('zulu')+ expect(verdict.why).toContain('plug-ins')+ expect(JSON.stringify(recordOf(choice, verdict, a()))).toContain(reason)+ // What the candidate is shown and recorded as stays as measured.+ expect(choice.shown[0]!.fit.effectiveCost).toBe(2)+ })+ it('an idle agent on such an account over a cheaper new agent: it pulls the queued task', () => {+ const probes = [codex('alpha', FRESH), opusMember('zulu', SOON)]+ // Codex is cheaper than Opus at the same strength.+ expect(route(probes, []).shown[0]!.kind).toBe('new')+ const choice = route(probes, [pull])+ expect(choice.shown[0]).toMatchObject({ kind: 'member', agentId: 'agent-1' })+ expect(noteOf(choice.shown[0]!)).toMatch(/this idle agent takes queued work first$/)+ })+ it('never above a stronger model', () => {+ const sonnet = codex('zulu', SOON, { engine: 'claude', model: 'sonnet', effort: 'medium', quality: 2 })+ const choice = route([codex('alpha', FRESH), sonnet], [pull])+ expect(choice.shown.map(s => s.model)).toEqual(['default', 'sonnet'])+ expect(noteOf(choice.shown[1]!)).toBeDefined()+ })+ it('makes a choice at most half as costly, never free, so a clearly better record still wins (pieces 3 and 6 together)', () => {+ // At most half, however much would go unused.+ expect(windowPullAdjust(fitted(codex('zulu', SOON)), NOW, [])?.cost).toBe(-2 * MAX_DISCOUNT)+ expect(windowPullAdjust(fitted(codex('zulu', SOON), { effectiveCost: 1.2 }), NOW, [])?.cost).toBe(-0.6)+ // A stand-in for piece 3's measured plug-in until it merges: a first-review record worth more than half the price.+ const measured: RoutePlugin = { name: 'Measured', adjust: c => c.machineId === 'alpha' ? { cost: -1.2, reason: 'passed first review on 9 of its last 10 builds' } : null }+ const probes = [codex('alpha', FRESH), codex('zulu', SOON)]+ expect(route(probes, [pull]).shown[0]!.machineId).toBe('zulu')+ for (const plugins of [[measured, pull], [pull, measured]]) {+ const choice = route(probes, plugins)+ expect(choice.shown.map(s => s.machineId)).toEqual(['alpha', 'zulu'])+ expect(noteOf(choice.shown[1]!)).toBeDefined()+ }+ })+ it('takes off only the part of the task the window would leave unused', () => {+ // 16% left a day before the reset, at a pace of 84% over six days: about 2% unused, half the task's 4%.+ const thin = codex('zulu', windows([80, 3 * H], [16, 24 * H], 'acct-soon'))+ expect(weeklyUnused(thin, NOW, [])?.unused).toBeCloseTo(2)+ expect(windowPullAdjust(fitted(thin), NOW, [])?.cost).toBe(-0.5)+ })+})++describe('the window pull leaves alone', () => {+ const none = (p: Probe, fit: Partial<Fit> = {}, open: Commitment[] = []) => expect(windowPullAdjust(fitted(p, fit), NOW, open)).toBeNull()+ it('a candidate whose quota would run out partway, as the route\'s fit says', () => {+ const short = codex('zulu', windows([5, 3 * H], [60, 12 * H], 'acct-soon'))+ const choice = route([codex('alpha', FRESH), short], [pull])+ expect(choice.shown.find(s => s.machineId === 'zulu')!.fit.status).toBe('short')+ expect(choice.shown.every(s => !noteOf(s))).toBe(true)+ expect(choice.shown[0]!.machineId).toBe('alpha')+ })+ it('a candidate whose fit is not known to cover the task: a 5-hour window that could not be read (review of f97c022)', () => {+ // Opus with only its weekly window read: the fit is unknown, and half off would put it above a Codex that fits.+ const unread = { ...opusMember('zulu', windows(null, [60, 12 * H], 'acct-soon')), kind: 'new' as const, agentId: undefined, name: undefined }+ const choice = route([codex('alpha', FRESH), unread], [pull])+ expect(choice.shown.find(s => s.machineId === 'zulu')!.fit.status).toBe('unknown')+ expect(choice.shown[0]!.machineId).toBe('alpha')+ expect(choice.shown.every(s => !noteOf(s))).toBe(true)+ none(unread, { status: 'unknown' })+ })+ it('but pulls a Codex account that reports its weekly window alone, a complete reading that fits', () => {+ const weeklyOnly = codex('zulu', windows(null, [60, 12 * H], 'acct-soon'))+ const choice = route([codex('alpha', FRESH), weeklyOnly], [pull])+ expect(choice.shown[0]).toMatchObject({ machineId: 'zulu', fit: { status: 'fits' } })+ expect(noteOf(choice.shown[0]!)).toBeDefined()+ })+ it('a reading that says nothing of a weekly window about to reset', () => {+ none(codex('zulu', { known: false, leftPercent: null, resetsAt: null, account: 'acct-soon' }))+ none(codex('zulu', { known: true, leftPercent: null, resetsAt: null, metered: true }))+ none(codex('zulu', SOON, { gridModel: 'kimi-k3', gridName: 'grid' }))+ none(codex('zulu', { known: true, leftPercent: 60, resetsAt: null, account: 'acct-soon' }))+ none(codex('zulu', windows([80, 3 * H], null, 'acct-soon')))+ none(codex('zulu', windows([80, 3 * H], [60, null], 'acct-soon')))+ // A reset already past is a reading from before the window refilled.+ none(codex('zulu', windows([80, 3 * H], [60, -M], 'acct-soon')))+ none(codex('zulu', windows([80, 3 * H], [60, 0], 'acct-soon')))+ // More than two days away: this week's pace says too little yet.+ none(codex('zulu', windows([80, 3 * H], [90, 49 * H], 'acct-soon')))+ })+ it('an account whose pace this week would use what is left', () => {+ // 10% left a day before the reset, after 90% in six days.+ none(codex('zulu', windows([80, 3 * H], [10, 24 * H], 'acct-soon')))+ // Under 1% unused is no reason to move work.+ none(codex('zulu', windows([80, 3 * H], [15, 24 * H], 'acct-soon')))+ })+ it('a task that spends nothing of the week, or a candidate already free', () => {+ none(codex('zulu', SOON), { spend: { '5-hour': 0, weekly: 0 } })+ none(codex('zulu', SOON), { effectiveCost: 0 })+ })+ it('a window the picks still at work on that account already fill, but not one whose picks are over or elsewhere', () => {+ const thin = codex('zulu', windows([80, 3 * H], [16, 24 * H], 'acct-soon'))+ const held = (patch: Partial<Commitment>): Commitment => ({ account: 'acct-soon', spend: { weekly: 4 }, size: 'medium', createdAt: NOW - M, ...patch })+ none(thin, {}, [held({})])+ expect(windowPullAdjust(fitted(thin), NOW, [held({ createdAt: NOW - 2 * H })])).not.toBeNull()+ expect(windowPullAdjust(fitted(thin), NOW, [held({ account: 'acct-fresh' })])).not.toBeNull()+ expect(windowPullAdjust(fitted(thin), NOW, [held({ spend: { '5-hour': 30 } })])).not.toBeNull()+ // Through the route: its context's picks at work count.+ const choice = route([codex('alpha', FRESH), thin], [pull], [held({})])+ expect(choice.shown.every(s => !noteOf(s))).toBe(true)+ })+})++describe('the window pull\'s reason', () => {+ it('names the window, never the account or the machine a reading was relayed from', () => {+ const relayed = codex('zulu', { ...windows([80, 3 * H], [60, 40 * M], 'acct-7f3a9c'), from: 'Ken\'s MacBook Pro' })+ const reason = windowPullAdjust(fitted(relayed), NOW, [])!.reason+ expect(reason).toContain('resets in 40m')+ expect(reason).not.toMatch(/acct|7f3a9c|Ken|MacBook/)+ })+ it('built from another group\'s pick, names nothing of it: only numbers and the kind of candidate', async () => {+ // Another group's pick, not started yet, on the same account, carrying all a history row can: its group, title, person, path.+ const theirs = { id: 'd-secret', conversationId: 'payroll-group', title: 'Rotate the payroll keys for Dee', account: '[email protected]',+ spend: { weekly: 20 }, size: 'large', outcome: null, final: null, createdAt: new Date(NOW - M).toISOString(),+ via: 'order', assignmentId: 'as-9', cwd: '/Users/dee/payroll', person: 'Dee' }+ const made = await makePlugins([windowPullMaker(() => NOW)], { conversationId: 'g2', assessment: a(), read: {}, catalog: policy,+ history: Promise.resolve({ ok: true, value: { decisions: [theirs] } }), request: async () => ({ ok: true }) })+ const soon = codex('zulu', windows([80, 3 * H], [60, 12 * H], '[email protected]'))+ const choice = route([codex('alpha', FRESH), soon], made.plugins)+ const reason = noteOf(choice.shown.find(s => s.machineId === 'zulu')!)!+ // Their pick is counted: about 57% less its 20% (a minute of a 3-hour task over) is about 37%.+ expect(reason).toBe('Window pull: its account\'s weekly window resets in 12h, and at this week\'s pace about 37% of it would go unused; this task spends it first')+ for (const leak of ['payroll', 'Payroll', 'Dee', 'dee', 'acct', 'example.com', 'd-secret', 'as-9', '/Users', 'Rotate']) expect(reason).not.toContain(leak)+ })+})++describe('picks not started yet, from the route history', () => {+ const pick = (patch: Record<string, unknown> = {}) => ({ id: 'd1', conversationId: 'other', account: 'acct-soon', spend: { '5-hour': 30, weekly: 4 }, size: 'medium',+ outcome: null, final: null, createdAt: new Date(NOW - M).toISOString(), ...patch })+ const history = (decisions: unknown) => ({ ok: true, value: { decisions } })+ it('holds quota for another group\'s pick nobody started yet, as a pick at work does', () => {+ expect(pendingPicks(history([pick()]), 'g1', NOW)).toEqual([{ account: 'acct-soon', size: 'medium', createdAt: NOW - M, spend: { weekly: 4 } }])+ })+ it('leaves out what the route already holds or what holds nothing', () => {+ expect(pendingPicks(history([+ pick({ final: { kind: 'new', engine: 'codex', model: 'default' } }), // started: the route's own picks at work hold it+ pick({ outcome: 'superseded' }), pick({ outcome: 'done' }),+ pick({ conversationId: 'g1' }), // this group's own pick: routing it again supersedes it+ pick({ account: undefined }), pick({ size: 'huge' }), pick({ spend: null }), pick({ spend: 'x' }),+ pick({ createdAt: new Date(NOW - PENDING_MS).toISOString() }), pick({ createdAt: 'never' }), pick({ createdAt: new Date(NOW + 2 * M).toISOString() }),+ null, 'x',+ ]), 'g1', NOW)).toEqual([])+ })+ it('counts a pick the server stamped a little ahead of this clock as just made, and one with no weekly spend as nothing', () => {+ expect(pendingPicks(history([pick({ createdAt: new Date(NOW + 20_000).toISOString() }), pick({ spend: { weekly: 'lots' } })]), 'g1', NOW))+ .toEqual([{ account: 'acct-soon', size: 'medium', createdAt: NOW, spend: { weekly: 4 } }, { account: 'acct-soon', size: 'medium', createdAt: NOW - M, spend: {} }])+ })+ it('is unknown when the history could not be read', () => {+ for (const unread of [null, { ok: false }, { ok: true }, { ok: true, value: 'x' }, { ok: true, value: { decisionsUnreadable: true } }]) {+ expect(pendingPicks(unread as never, 'g1', NOW)).toBeNull()+ }+ })+})++describe('the window pull\'s maker', () => {+ const input = (history: unknown): PluginInput => ({ conversationId: 'g2', assessment: a(), read: {}, catalog: policy, history: Promise.resolve(history as never),+ request: async () => ({ ok: true }) })+ it('is in the route\'s list of makers', () => {+ expect(ROUTE_PLUGIN_MAKERS.map(m => m.name)).toContain(WINDOW_PULL)+ })+ it('two routes a minute apart do not both pull onto one window', async () => {+ // About 2% would go unused, half a medium task: the first route pulls; the second sees that pick, not yet started.+ const thin = windows([80, 3 * H], [16, 24 * H], 'acct-soon')+ const probes = [codex('alpha', FRESH), codex('zulu', thin)]+ const first = await makePlugins([windowPullMaker(() => NOW)], input({ ok: true, value: { decisions: [] } }))+ expect(route(probes, first.plugins).shown[0]!.machineId).toBe('zulu')+ const routed = { id: 'd1', conversationId: 'g1', account: 'acct-soon', spend: { weekly: 4 }, size: 'medium', outcome: null, final: null, createdAt: new Date(NOW - M).toISOString() }+ const second = await makePlugins([windowPullMaker(() => NOW)], input({ ok: true, value: { decisions: [routed] } }))+ const choice = route(probes, second.plugins)+ expect(choice.shown[0]!.machineId).toBe('alpha')+ expect(choice.shown.every(s => !noteOf(s))).toBe(true)+ })+ it('is left out, and the route answer says so, when the history could not be read', async () => {+ expect(await makePlugins([windowPullMaker()], input(null))).toEqual({ plugins: [],+ warnings: ['The routing plug-in "Window pull" was skipped: its maker failed. The route is ranked without it.'] })+ })+})diff --git a/cli/src/superTabs/windowPull.ts b/cli/src/superTabs/windowPull.tsnew file mode 100644index 000000000..c75788d7b--- /dev/null+++ b/cli/src/superTabs/windowPull.ts@@ -0,0 +1,105 @@+/** The window pull (Scholes's goals, piece 6: "token maxxing"): a subscription's weekly window that resets soon with quota+ * left loses that quota at the reset, so the route spends it first. A candidate whose account would otherwise leave part of+ * its weekly window unused is made cheaper by that part of the task, never stronger: a stronger model still ranks first, and+ * a candidate the route leaves out stays out (route.ts RoutePlugin). The route's members are idle agents, so an idle agent on+ * such an account takes the next queued task it can run.+ *+ * The windows ride on the candidates (routeCommand.ts probeMachine reads them from each machine's last report; one older+ * than 45 s is unknown quota, which this leaves alone). What it reads besides is the route history every maker shares: the+ * routes picked and not yet started, which the route's own fit does not count yet. */+import { accountOf, SIZES, type Adjustment, type Commitment, type Fit, type Probe, type RoutePlugin, type Size } from './route.js'+import type { PluginInput, PluginMaker } from './routePlugins.js'++type Json = Record<string, unknown>+export const WINDOW_PULL = 'Window pull'+/** How close a weekly reset must be for the pull to judge it. Earlier in the week, this week's pace says little about what+ * the rest of it will use: a quiet first day would pull every task onto one account. */+export const RESETS_SOON_MS = 48 * 3_600_000+/** Both engines' weekly windows are seven days long (cli superTabs/capacity.ts names a window of a day or more "weekly"). The+ * machines' reports carry no window length (backend superTabs/machines.ts takes name, used and reset only), so a window of+ * another length is read as seven days. */+export const WEEK_MS = 7 * 86_400_000+/** Less than this many percent of a week left unused is a rounding error, not quota worth moving work for. */+export const MIN_UNUSED_PERCENT = 1+/** The most the pull takes off a candidate's price: half. An expiring window makes a choice look at most half as costly,+ * never free, so a choice with a clearly better record (piece 3, measured cost and results) still beats one whose only edge+ * is quota about to reset (Lead, 10-31). */+export const MAX_DISCOUNT = 0.5+/** How long a pick nobody has started or assigned yet still holds its account's quota. A route is acted on within minutes;+ * one older than this was dropped, and holding quota for it would keep the window from pulling at all. */+export const PENDING_MS = 15 * 60_000++/** What [p]'s account would leave unused of its weekly window at its reset, in percent of that window, and how soon the reset+ * is; null when it is not known or nothing would be left. The account is projected to keep this week's pace until the reset+ * (what it has used, over the part of the week that is over), and the picks on it still at work or not yet started hold what+ * they have yet to spend, as the route's own fit counts them (route.ts sizeUp), so once enough work is routed there it pulls+ * no more. */+export function weeklyUnused(p: Probe, now: number, held: readonly Commitment[]): { unused: number; resetsIn: number } | null {+ // A model on the grid and a metered engine spend no subscription; an unknown reading says nothing.+ if (p.gridModel || p.quota.metered || !p.quota.known) return null+ const week = p.quota.windows?.find(w => w.name === 'weekly')+ if (!week || week.resetsAt === null) return null+ const resetsIn = week.resetsAt - now+ // A reset already past is a reading from before it: the window has refilled, and what it says is gone.+ if (resetsIn <= 0 || resetsIn > RESETS_SOON_MS) return null+ const pace = (100 - week.leftPercent) / (WEEK_MS - resetsIn)+ const account = accountOf(p)+ const committed = held.filter(c => c.account === account)+ .reduce((sum, c) => sum + (c.spend.weekly ?? 0) * Math.max(0, 1 - (now - c.createdAt) / (SIZES[c.size].minutes * 60_000)), 0)+ const unused = week.leftPercent - committed - pace * resetsIn+ return unused >= MIN_UNUSED_PERCENT ? { unused, resetsIn } : null+}++const round = (n: number) => Math.round(n * 100) / 100+/** A reset is told as how far away it is, as the route's labels tell it. */+const inTime = (ms: number) => ms < 3_600_000 ? `${Math.max(1, Math.round(ms / 60_000))}m` : `${Math.round(ms / 3_600_000)}h`++/** The pull's word on one candidate: its price less up to half ([MAX_DISCOUNT]), by the part of the task its account's weekly+ * window would otherwise leave unused. Only on a candidate whose quota is known to carry the task (fit `fits`; a Codex+ * reading of its weekly window alone is complete, route.ts sizeUp): one that would run out partway trades wasted weekly+ * quota for a stalled task, and one whose 5-hour window could not be read (`unknown`) would, since price ranks before fit,+ * beat an account known to fit on half a reading (review of f97c022). The reason names the window, never the account or+ * the machine a reading was relayed from, since every reader of the route log sees it. */+export function windowPullAdjust(p: Readonly<Probe & { fit: Fit }>, now: number, held: readonly Commitment[]): Adjustment | null {+ if (p.fit.status !== 'fits' || p.fit.spend.weekly <= 0 || p.fit.effectiveCost <= 0) return null+ const left = weeklyUnused(p, now, held)+ if (!left) return null+ const discount = p.fit.effectiveCost * MAX_DISCOUNT * Math.min(1, left.unused / p.fit.spend.weekly)+ const why = `its account's weekly window resets in ${inTime(left.resetsIn)}, and at this week's pace about ${Math.round(left.unused)}% of it would go unused`+ return { cost: -round(discount), reason: p.kind === 'member' ? `${why}; this idle agent takes queued work first` : `${why}; this task spends it first` }+}++/** The plug-in for one route. [pending]: picks of the Swarm's other routes not started or assigned yet, which the route's+ * picks still at work (its context's `open`) do not hold yet: two routes a minute apart must not both pull onto one window. */+export function windowPull(pending: readonly Commitment[]): RoutePlugin {+ return { name: WINDOW_PULL, adjust: (p, context) => windowPullAdjust(p, context.now, [...context.open, ...pending]) }+}++const SIZE_NAMES = Object.keys(SIZES)+/** How far ahead of this machine's clock the server's may stamp a pick and still have it count. */+const SKEW_MS = 60_000+/** The picks in the route history that hold quota and are not in the route's own `open` yet: no outcome, not started or+ * assigned (routeCommand.ts takes those that are), recorded in the last [PENDING_MS], and of another group (routing this+ * group again supersedes its own, backend routeDecisions.ts writeRouteEffects). Null when the history could not be read. */+export function pendingPicks(history: Json | null, conversationId: string, now: number): Commitment[] | null {+ const value = history?.ok === true && history.value && typeof history.value === 'object' ? history.value as Json : null+ if (!value || !Array.isArray(value.decisions)) return null+ return value.decisions.flatMap((d: Json): Commitment[] => {+ const createdAt = Date.parse(String(d?.createdAt))+ if (!d || typeof d !== 'object' || d.final || d.outcome != null || d.conversationId === conversationId || typeof d.account !== 'string'+ || !SIZE_NAMES.includes(String(d.size)) || !d.spend || typeof d.spend !== 'object' || !(now - createdAt < PENDING_MS && createdAt - now < SKEW_MS)) return []+ const weekly = (d.spend as Json).weekly+ // The server's clock may run a little ahead of this machine's: a pick just made still holds all it will spend.+ return [{ account: d.account, size: d.size as Size, createdAt: Math.min(createdAt, now), spend: typeof weekly === 'number' && Number.isFinite(weekly) ? { weekly } : {} }]+ })+}++/** Its maker: the shared route history, for the picks not started yet. Without it the pull could not tell whether another+ * route just pulled onto the same window, so it is left out, and the route answer says so (routePlugins.ts makePlugins). */+export function windowPullMaker(now: () => number = Date.now): PluginMaker {+ return { name: WINDOW_PULL, make: async (input: PluginInput) => {+ const pending = pendingPicks(await input.history, input.conversationId, now())+ if (!pending) throw new Error('the route history could not be read')+ return windowPull(pending)+ } }+}diff --git a/cli/vitest.super-tabs.config.ts b/cli/vitest.super-tabs.config.tsindex 1dc84741d..f285597d4 100644--- a/cli/vitest.super-tabs.config.ts+++ b/cli/vitest.super-tabs.config.ts@@ -6,7 +6,7 @@ import base from './vitest.config.js'* the core and services, which no other gate covers, held to 100% in every file. And the Swarm's side of the core's* process (superTabs/inCore/), which left the core's own 100% gate when the Swarm became a switch. */const IN_CORE = ['adoption', 'agents', 'attention', 'cards', 'deliveries', 'launch', 'role', 'teamApps', 'teamPurge', 'terminal'].map(name => `src/superTabs/inCore/${name}.ts`)-const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts', 'src/superTabs/routePlugins.ts', 'src/superTabs/shortCommand.ts', ...IN_CORE]+const FILES = ['src/superTabs/route.ts', 'src/superTabs/routeCommand.ts', 'src/superTabs/routePlugins.ts', 'src/superTabs/windowPull.ts', 'src/superTabs/shortCommand.ts', ...IN_CORE]export default defineConfig({test: {...base.test,