@jaxonshaw/multi-model-kit 0.0.0-stage → 0.1.1
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/.agents/plugins/marketplace.json +11 -0
- package/.claude-plugin/marketplace.json +8 -0
- package/.claude-plugin/plugin.json +5 -0
- package/.codex-plugin/plugin.json +6 -0
- package/INSTALL-AGENT.md +95 -0
- package/LICENSE +21 -0
- package/README.md +152 -2
- package/bin/byok-review +258 -0
- package/bin/claude-org +415 -0
- package/bin/model-route +303 -0
- package/bin/multi-model-kit +22 -0
- package/bin/quota-status +259 -0
- package/config/defaults.json +45 -0
- package/hooks/hooks.json +14 -0
- package/hooks/session-start.sh +77 -0
- package/install.sh +1606 -0
- package/mods/org-switch/.claude-plugin/plugin.json +5 -0
- package/mods/org-switch/hooks/hooks.json +1 -0
- package/mods/org-switch/hooks/register.ts +571 -0
- package/mods/org-switch/tsconfig.json +3 -0
- package/orgs.example.json +18 -0
- package/package.json +40 -4
- package/plugins/paseo-usage/bridge/capture-quota.cjs +59 -0
- package/plugins/paseo-usage/index.server.ts +47 -0
- package/plugins/paseo-usage/paseo-plugin.json +8 -0
- package/plugins/paseo-usage/server/usage.mjs +140 -0
- package/rules/multi-model.md +15 -0
- package/skills/dispatch/SKILL.md +148 -0
- package/skills/dispatch/references/brief-template.md +52 -0
- package/skills/dispatch/references/ce-config.example.yaml +19 -0
- package/skills/dispatch/references/paseo.md +87 -0
- package/skills/dispatch/references/roundtable.md +32 -0
- package/skills/dispatch/references/routing.md +83 -0
- package/skills/dispatch/references/watch-paseo.md +217 -0
- package/skills/dispatch/references/watch.md +42 -0
- package/skills/prompt-library/SKILL.md +60 -0
- package/skills/prompt-library/prompts/c01-first-principles.md +1 -0
- package/skills/prompt-library/prompts/c02-clarify-then-options.md +1 -0
- package/skills/prompt-library/prompts/c03-reframe-problem.md +1 -0
- package/skills/prompt-library/prompts/c04-second-order-effects.md +1 -0
- package/skills/prompt-library/prompts/c05-cross-domain.md +1 -0
- package/skills/prompt-library/prompts/c06-argue-against.md +1 -0
- package/skills/prompt-library/prompts/c07-git-history-legacy.md +1 -0
- package/skills/prompt-library/prompts/c08-onboarding-cost.md +1 -0
- package/skills/prompt-library/prompts/c09-slow-prs.md +1 -0
- package/skills/prompt-library/prompts/c10-rework-retro.md +1 -0
- package/skills/prompt-library/prompts/d01-complexity-to-system.md +11 -0
- package/skills/prompt-library/prompts/d02-motion.md +11 -0
- package/skills/task-handoff/SKILL.md +319 -0
- package/skills/task-handoff/references/handoff-template.md +134 -0
- package/skills/task-handoff/references/takeover-prompt.md +81 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.ts"] }
|
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
// org-switch: under the claude-org launcher, watch this org's rate-limit
|
|
2
|
+
// windows and move the session to another org when one fills: optionally
|
|
3
|
+
// compact, write the target org and the session id to the handoff file, exit.
|
|
4
|
+
// The launcher then resumes the same session id under the other org's own
|
|
5
|
+
// config directory (each org signed in with its own /login).
|
|
6
|
+
//
|
|
7
|
+
// The launcher tells the mod, by environment:
|
|
8
|
+
// CLAUDE_ORG the org this process runs under
|
|
9
|
+
// CLAUDE_ORGS every org it can start, comma-separated
|
|
10
|
+
// CLAUDE_ORG_HANDOFF the file to write `next=` / `session=` / `fresh=` / `reason=` to
|
|
11
|
+
// CLAUDE_ORG_RESUMED "1" when the launch already names a conversation
|
|
12
|
+
// CLAUDE_ORG_CODEX_EXIT Codex's exit code, set only on the launch that follows a Codex takeover
|
|
13
|
+
// CLAUDE_ORG_AGY_EXIT agy's exit code, set only on the launch that follows an agy takeover
|
|
14
|
+
// and, from the person's own shell, CLAUDE_ORG_SOFT_PCT (default from config quota.softPct, 85): from that
|
|
15
|
+
// window percentage on, the main loop thinks one level less (never below
|
|
16
|
+
// medium) and the org is marked as saving quota until its windows read low.
|
|
17
|
+
//
|
|
18
|
+
// When every org stays limited for more than 20 minutes, the repository holds a
|
|
19
|
+
// .handoff.md and its working tree is clean, the mod hands the time over to
|
|
20
|
+
// Codex: it writes `codex=1` and `until=<epoch seconds>` with the target org and
|
|
21
|
+
// session, and exits. If takeover is enabled, the launcher runs Codex and,
|
|
22
|
+
// if Codex is quota-limited, agy. It waits for the reset and resumes Claude.
|
|
23
|
+
// The resumed session gets the agents' exit codes and reviews their changes.
|
|
24
|
+
//
|
|
25
|
+
// Without CLAUDE_ORG_HANDOFF (a process the launcher did not start, such as a
|
|
26
|
+
// T3 Code instance that sets CLAUDE_ORG and CLAUDE_ORGS itself) the mod only
|
|
27
|
+
// records: readings, the saving mark, the soft-threshold effort and the status
|
|
28
|
+
// line. It never switches, exits, waits or submits; bin/quota-status reads the
|
|
29
|
+
// readings and says which org to move to.
|
|
30
|
+
//
|
|
31
|
+
// The strategy (`decide`) is a pure function; the engine calls stay in the
|
|
32
|
+
// handlers below it.
|
|
33
|
+
import type { EngineInterface as Engine, Register, SessionRateLimit } from 'claude-code'
|
|
34
|
+
|
|
35
|
+
export type WindowSeen = { percentUsed: number; resetsAt?: string }
|
|
36
|
+
/** One org's last reading, stored under `ledger:<org>`. */
|
|
37
|
+
export type Ledger = { seenAt: number; windows: Record<string, WindowSeen> }
|
|
38
|
+
/** A limit seen as a failed request with no window to explain it, stored under `block:<org>`. */
|
|
39
|
+
export type Block = { kind: 'all' | 'fable'; until: number }
|
|
40
|
+
/** This org is past the soft threshold, stored under `saving:<org>`. */
|
|
41
|
+
export type Saving = { since: number; softAt: number }
|
|
42
|
+
/** The model a limit moved the session off, stored under `downgrade`. */
|
|
43
|
+
export type Downgrade = { from: string }
|
|
44
|
+
export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
|
|
45
|
+
export type OrgState = { ledger?: Ledger; block?: Block }
|
|
46
|
+
export type Why = 'window' | 'limit' | 'fable'
|
|
47
|
+
export type Situation = {
|
|
48
|
+
now: number
|
|
49
|
+
current: string
|
|
50
|
+
orgs: string[]
|
|
51
|
+
fable: boolean // the session runs a Fable model
|
|
52
|
+
why: Why // a window reached the threshold, or a turn failed on a limit (Fable's alone or any)
|
|
53
|
+
states: Record<string, OrgState>
|
|
54
|
+
lastSwitchAt?: number
|
|
55
|
+
}
|
|
56
|
+
export type Decision =
|
|
57
|
+
| { kind: 'stay' }
|
|
58
|
+
| { kind: 'move'; org: string; model?: string; go: boolean } // org may be the current one: a model change in place
|
|
59
|
+
| { kind: 'wait'; org: string; model?: string; at: number }
|
|
60
|
+
|
|
61
|
+
// A marketplace install can lack the repository's config/defaults.json.
|
|
62
|
+
const BUILTIN_QUOTA = { softPct: 85, switchPct: 98 }
|
|
63
|
+
const DEFAULTS_PATH = decodeURIComponent(new URL('../../../config/defaults.json', (import.meta as { url: string }).url).pathname)
|
|
64
|
+
|
|
65
|
+
function quotaConfig(text: string | undefined, fallback: typeof BUILTIN_QUOTA): typeof BUILTIN_QUOTA {
|
|
66
|
+
if (!text) return fallback
|
|
67
|
+
try {
|
|
68
|
+
const quota = JSON.parse(text)?.quota
|
|
69
|
+
if (quota === null || typeof quota !== 'object' || Array.isArray(quota)) return fallback
|
|
70
|
+
const { softPct = fallback.softPct, switchPct = fallback.switchPct } = quota
|
|
71
|
+
if (Number.isInteger(softPct) && Number.isInteger(switchPct) && 0 < softPct && softPct < switchPct && switchPct <= 100) {
|
|
72
|
+
return { softPct, switchPct }
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
// Ignore an unreadable quota section and use the previous defaults.
|
|
76
|
+
}
|
|
77
|
+
return fallback
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function readQuotaConfig($: Engine, path: string, fallback: typeof BUILTIN_QUOTA): Promise<typeof BUILTIN_QUOTA> {
|
|
81
|
+
try {
|
|
82
|
+
return quotaConfig(await $.fs.read(path), fallback)
|
|
83
|
+
} catch {
|
|
84
|
+
return fallback
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const TAKEOVER_AFTER_MS = 20 * 60_000 // Codex takes over only when Claude is out for longer than this
|
|
89
|
+
const COMPACT_AT = 50 // context % from which a switch compacts first
|
|
90
|
+
const PROBE_MS = 30 * 60_000 // an unexplained limit holds the org off this long; a wait probes this often
|
|
91
|
+
const SWITCH_COOLDOWN_MS = 2 * 60_000
|
|
92
|
+
const DOWNGRADE_MODEL = 'claude-opus-5-5'
|
|
93
|
+
const CONTINUE_TEXT = '继续'
|
|
94
|
+
export const RECORD_ONLY_SWITCH = '这个会话不是由 claude-org 启动的,换 org 请切换线程的模型实例。'
|
|
95
|
+
const COMPACT_RETRY_MS = 2000
|
|
96
|
+
const COMPACT_RETRIES = 150 // five minutes of "a turn is still running"
|
|
97
|
+
const NAME_RE = /^[a-z][a-z0-9_-]{0,31}$/
|
|
98
|
+
|
|
99
|
+
const isFable = (model: string) => /fable/i.test(model)
|
|
100
|
+
const LOWER: Partial<Record<Effort, Effort>> = { max: 'xhigh', xhigh: 'high', high: 'medium' }
|
|
101
|
+
/** One level less thinking, never below medium. */
|
|
102
|
+
export const lowerEffort = (e: Effort): Effort => LOWER[e] ?? e
|
|
103
|
+
const short = (kind: string) => (kind === 'five_hour' ? '5h' : kind === 'seven_day' ? '7d' : kind)
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* When an org can next serve the model: now when nothing binds, else the
|
|
107
|
+
* LATEST reset among its spent windows and any block, since every one must clear.
|
|
108
|
+
*/
|
|
109
|
+
export function availableAt(s: OrgState, fable: boolean, now: number, switchPct = BUILTIN_QUOTA.switchPct): number {
|
|
110
|
+
let at = now
|
|
111
|
+
for (const w of Object.values(s.ledger?.windows ?? {})) {
|
|
112
|
+
const t = w.resetsAt !== undefined ? Date.parse(w.resetsAt) : NaN
|
|
113
|
+
if (w.percentUsed >= switchPct && Number.isFinite(t) && t > at) at = t
|
|
114
|
+
}
|
|
115
|
+
const b = s.block
|
|
116
|
+
if (b !== undefined && b.until > now && (b.kind === 'all' || fable)) at = Math.max(at, b.until)
|
|
117
|
+
return at
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A failed turn no window explains holds this org off for a while (only Fable when it was Fable's). */
|
|
121
|
+
export function unexplainedBlock(why: Why, s: OrgState, fable: boolean, now: number, switchPct = BUILTIN_QUOTA.switchPct): Block | undefined {
|
|
122
|
+
if (why === 'window' || availableAt(s, fable, now, switchPct) > now) return undefined
|
|
123
|
+
return { kind: why === 'fable' ? 'fable' : 'all', until: now + PROBE_MS }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Another org that serves this model; else, on Fable, Opus on the first org that
|
|
128
|
+
* serves it (this one first); else wait for the org that frees first. A window
|
|
129
|
+
* near its end only moves to an org that is free: the turn still runs. Never
|
|
130
|
+
* switch org again within two minutes of the last switch.
|
|
131
|
+
*/
|
|
132
|
+
export function decide(s: Situation, switchPct = BUILTIN_QUOTA.switchPct): Decision {
|
|
133
|
+
const { now, current, fable } = s
|
|
134
|
+
const at = (org: string, f: boolean) => availableAt(s.states[org] ?? {}, f, now, switchPct)
|
|
135
|
+
const i = s.orgs.indexOf(current)
|
|
136
|
+
const others = s.orgs.map((_, k) => s.orgs[(i + 1 + k) % s.orgs.length] as string).filter(o => o !== current)
|
|
137
|
+
let d: Decision | undefined
|
|
138
|
+
const free = others.find(o => at(o, fable) <= now)
|
|
139
|
+
if (free !== undefined) d = { kind: 'move', org: free, go: s.why !== 'window' }
|
|
140
|
+
else if (s.why === 'window') return { kind: 'stay' }
|
|
141
|
+
else {
|
|
142
|
+
const all = [current, ...others]
|
|
143
|
+
const opus = fable ? all.find(o => at(o, false) <= now) : undefined
|
|
144
|
+
if (opus !== undefined) d = { kind: 'move', org: opus, model: DOWNGRADE_MODEL, go: true }
|
|
145
|
+
else {
|
|
146
|
+
let best: { org: string; at: number; model?: string } | undefined
|
|
147
|
+
for (const org of all) {
|
|
148
|
+
const t = at(org, fable)
|
|
149
|
+
if (best === undefined || t < best.at) best = { org, at: t }
|
|
150
|
+
if (fable) {
|
|
151
|
+
const o = at(org, false)
|
|
152
|
+
if (o < best.at) best = { org, at: o, model: DOWNGRADE_MODEL }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (best === undefined) return { kind: 'stay' }
|
|
156
|
+
return best.model === undefined ? { kind: 'wait', org: best.org, at: best.at } : { kind: 'wait', org: best.org, model: best.model, at: best.at }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (d.org !== current && s.lastSwitchAt !== undefined && now - s.lastSwitchAt < SWITCH_COOLDOWN_MS) {
|
|
160
|
+
const due = s.lastSwitchAt + SWITCH_COOLDOWN_MS
|
|
161
|
+
return d.model === undefined ? { kind: 'wait', org: d.org, at: due } : { kind: 'wait', org: d.org, model: d.model, at: due }
|
|
162
|
+
}
|
|
163
|
+
return d
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ---- the engine side ----
|
|
167
|
+
|
|
168
|
+
// Whether Codex may take over here. Exit codes name what is missing (CODEX_NOT_READY).
|
|
169
|
+
export const CODEX_READY_SH = `top=$(git rev-parse --show-toplevel 2> /dev/null) || exit 3
|
|
170
|
+
[ -f "$top/.handoff.md" ] || exit 4
|
|
171
|
+
s=$(git -C "$top" status --porcelain) && [ -z "$s" ] || exit 5
|
|
172
|
+
command -v codex > /dev/null 2>&1 || exit 6`
|
|
173
|
+
const CODEX_NOT_READY: Record<number, string> = {
|
|
174
|
+
3: 'this directory is not in a git repository',
|
|
175
|
+
4: 'the repository has no .handoff.md',
|
|
176
|
+
5: 'the working tree has uncommitted changes',
|
|
177
|
+
6: 'the codex command is not installed',
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export const takeoverText = (codexExit?: string, agyExit?: string) => {
|
|
181
|
+
const agents = [
|
|
182
|
+
...(codexExit === undefined ? [] : [`Codex(Codex 退出码 ${codexExit})`]),
|
|
183
|
+
...(agyExit === undefined ? [] : [`agy(agy 退出码 ${agyExit})`]),
|
|
184
|
+
]
|
|
185
|
+
return `刚才所有 org 额度用完期间,${agents.join('、')} 在这个工作目录里运行过,没有提交。` +
|
|
186
|
+
'请先看 git status、git diff 和 .takeover-notes.md,审查后再决定提交还是撤销,然后继续。'
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
type Resume = { go: boolean; model?: string }
|
|
190
|
+
|
|
191
|
+
const env: { org?: string; orgs: string[]; handoff?: string; resumed: boolean; softAt: number; switchPct: number; codexExit?: string; agyExit?: string } = {
|
|
192
|
+
orgs: [], resumed: false, softAt: BUILTIN_QUOTA.softPct, switchPct: BUILTIN_QUOTA.switchPct,
|
|
193
|
+
}
|
|
194
|
+
let conversed = false // a prompt went in during this process: the session id now names a conversation
|
|
195
|
+
let handoffStarted = false
|
|
196
|
+
let lastLimits: readonly SessionRateLimit[] = []
|
|
197
|
+
let contextPct = 0
|
|
198
|
+
let waitId = 0 // bumps to cancel a pending wait
|
|
199
|
+
let waiting = false
|
|
200
|
+
let waitWhy: Why | undefined // what the pending wait reacts to
|
|
201
|
+
let saving = false // this org is past the soft threshold
|
|
202
|
+
let restoreId = 0 // bumps to cancel a pending return to Fable
|
|
203
|
+
|
|
204
|
+
const active = () => env.org !== undefined && env.handoff !== undefined
|
|
205
|
+
const recordOnly = () => env.org !== undefined && env.handoff === undefined
|
|
206
|
+
const shouldCompact = () => contextPct >= COMPACT_AT
|
|
207
|
+
const exitCode = (rc: string | undefined) => rc !== undefined && /^[0-9]{1,3}$/.test(rc) ? rc : undefined
|
|
208
|
+
|
|
209
|
+
async function loadEnv($: Engine): Promise<void> {
|
|
210
|
+
const org = await $.env.get('CLAUDE_ORG')
|
|
211
|
+
env.orgs = ((await $.env.get('CLAUDE_ORGS')) ?? '').split(',').filter(o => NAME_RE.test(o))
|
|
212
|
+
env.org = org !== undefined && env.orgs.includes(org) ? org : undefined
|
|
213
|
+
const handoff = await $.env.get('CLAUDE_ORG_HANDOFF')
|
|
214
|
+
env.handoff = handoff !== undefined && handoff.startsWith('/') ? handoff : undefined
|
|
215
|
+
env.resumed = (await $.env.get('CLAUDE_ORG_RESUMED')) === '1'
|
|
216
|
+
const defaults = await readQuotaConfig($, DEFAULTS_PATH, BUILTIN_QUOTA)
|
|
217
|
+
const home = await $.env.get('HOME')
|
|
218
|
+
const configHome = (await $.env.get('XDG_CONFIG_HOME')) || (home ? `${home}/.config` : undefined)
|
|
219
|
+
const quota = configHome ? await readQuotaConfig($, `${configHome}/multi-model-kit/config.json`, defaults) : defaults
|
|
220
|
+
const override = ((await $.env.get('CLAUDE_ORG_SOFT_PCT')) ?? '').trim()
|
|
221
|
+
const soft = /^[+]?[0-9]{1,3}$/.test(override) ? Number(override) : 0
|
|
222
|
+
env.switchPct = quota.switchPct
|
|
223
|
+
env.softAt = soft > 0 && soft < env.switchPct ? soft : quota.softPct
|
|
224
|
+
env.codexExit = exitCode(await $.env.get('CLAUDE_ORG_CODEX_EXIT'))
|
|
225
|
+
env.agyExit = exitCode(await $.env.get('CLAUDE_ORG_AGY_EXIT'))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function readState($: Engine, org: string): Promise<OrgState> {
|
|
229
|
+
const l = await $.store.get(`ledger:${org}`)
|
|
230
|
+
const b = await $.store.get(`block:${org}`)
|
|
231
|
+
return {
|
|
232
|
+
ledger: l !== null && typeof l === 'object' ? (l as Ledger) : undefined,
|
|
233
|
+
block: b !== null && typeof b === 'object' ? (b as Block) : undefined,
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function readStates($: Engine): Promise<Record<string, OrgState>> {
|
|
238
|
+
const states: Record<string, OrgState> = {}
|
|
239
|
+
for (const org of env.orgs) states[org] = await readState($, org)
|
|
240
|
+
return states
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function writeLedger($: Engine, org: string, limits: readonly SessionRateLimit[]): Promise<void> {
|
|
244
|
+
const windows: Record<string, WindowSeen> = {}
|
|
245
|
+
for (const w of limits) windows[w.kind] = { percentUsed: w.percentUsed, resetsAt: w.resetsAt }
|
|
246
|
+
await $.store.set(`ledger:${org}`, { seenAt: await $.clock.now(), windows } satisfies Ledger)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const statusText = (org: string, limits: readonly SessionRateLimit[]) =>
|
|
250
|
+
[org, ...limits.map(w => `${short(w.kind)} ${Math.round(w.percentUsed)}%`), ...(saving ? ['省额度'] : [])].join(' · ')
|
|
251
|
+
|
|
252
|
+
/** Mark or clear saving mode from a fresh reading of this org's windows. */
|
|
253
|
+
async function updateSaving($: Engine, org: string, limits: readonly SessionRateLimit[]): Promise<void> {
|
|
254
|
+
const want = limits.some(w => w.percentUsed >= env.softAt)
|
|
255
|
+
if (want === saving) return
|
|
256
|
+
saving = want
|
|
257
|
+
if (want) await $.store.set(`saving:${org}`, { since: await $.clock.now(), softAt: env.softAt } satisfies Saving)
|
|
258
|
+
else await $.store.delete(`saving:${org}`)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function fmtIn(ms: number): string {
|
|
262
|
+
if (ms <= 0) return 'already'
|
|
263
|
+
const m = Math.round(ms / 60000)
|
|
264
|
+
return m < 60 ? `in ${m} min` : m < 2880 ? `in ${(m / 60).toFixed(1)} h` : `in ${Math.round(m / 1440)} d`
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function fmtAgo(ms: number): string {
|
|
268
|
+
const m = Math.round(ms / 60000)
|
|
269
|
+
return m < 1 ? 'just now' : m < 60 ? `${m} min ago` : m < 2880 ? `${(m / 60).toFixed(1)} h ago` : `${Math.round(m / 1440)} d ago`
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Starts the switch and returns the line to show. */
|
|
273
|
+
function startSwitch($: Engine, target: string, compact: boolean, reason: string, extra = ''): string {
|
|
274
|
+
if (handoffStarted) return 'org-switch: a switch is already under way.'
|
|
275
|
+
handoffStarted = true
|
|
276
|
+
$.ui.toast(`org-switch: ${reason}. ${compact ? 'Compacting, then switching' : 'Switching'} to ${target}.`, { timeoutMs: 8000 })
|
|
277
|
+
$.clock.after(0, () => { void runSwitch($, target, compact, reason, 0, extra) })
|
|
278
|
+
return `org-switch: ${compact ? 'compacting, then ' : ''}exiting so this session resumes under ${target}.`
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const EXIT_GRACE_MS = 5000
|
|
282
|
+
|
|
283
|
+
async function runSwitch($: Engine, target: string, compact: boolean, reason: string, attempt: number, extra: string): Promise<void> {
|
|
284
|
+
if (compact) {
|
|
285
|
+
try {
|
|
286
|
+
await $.command.run({
|
|
287
|
+
command: 'compact',
|
|
288
|
+
args: `The session is moving to the "${target}" org (${reason}). Keep the task in progress, its current state and the exact next step.`,
|
|
289
|
+
})
|
|
290
|
+
} catch (err) {
|
|
291
|
+
if (attempt < COMPACT_RETRIES) {
|
|
292
|
+
$.clock.after(COMPACT_RETRY_MS, () => { void runSwitch($, target, compact, reason, attempt + 1, extra) })
|
|
293
|
+
return
|
|
294
|
+
}
|
|
295
|
+
$.ui.toast(`org-switch: /compact never ran (${String(err)}); switching uncompacted.`, { timeoutMs: 8000 })
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const sid = await $.session.id()
|
|
299
|
+
// A session nobody has written to yet has no transcript to resume: start fresh under the new org instead.
|
|
300
|
+
const line = env.resumed || conversed ? `session=${sid}` : 'fresh=1'
|
|
301
|
+
await $.fs.write(env.handoff as string, `next=${target}\n${line}\n${extra}reason=${reason.replace(/[\r\n]+/g, ' ')}\n`)
|
|
302
|
+
$.ui.toast(`org-switch: exiting; resuming ${sid.slice(0, 8)} under ${target}.`, { timeoutMs: 8000 })
|
|
303
|
+
// The engine's own rate-limit dialog can hold /exit until a person answers it. Nobody may be there:
|
|
304
|
+
// if this process is still alive after the grace, end it. The launcher resumes the session either way.
|
|
305
|
+
$.clock.after(EXIT_GRACE_MS, () => { void $.process.run(['sh', '-c', 'kill -TERM "$PPID"']) })
|
|
306
|
+
try {
|
|
307
|
+
await $.command.run({ command: 'exit' })
|
|
308
|
+
} catch (err) {
|
|
309
|
+
$.ui.log(`org-switch: /exit refused (${String(err)}); sending SIGTERM to the engine`, { to: 'debug' })
|
|
310
|
+
await $.process.run(['sh', '-c', 'kill -TERM "$PPID"'])
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const sendContinue = ($: Engine) => $.prompt.submit({ text: CONTINUE_TEXT })
|
|
315
|
+
|
|
316
|
+
/** Carry out a move: a model change (and "继续") here, or a switch to another org that resumes the same way. */
|
|
317
|
+
async function moveTo($: Engine, org: string, model: string | undefined, go: boolean, reason: string): Promise<void> {
|
|
318
|
+
const was = await $.session.model()
|
|
319
|
+
if (model === DOWNGRADE_MODEL && isFable(was)) await $.store.set('downgrade', { from: was } satisfies Downgrade)
|
|
320
|
+
if (org === env.org) {
|
|
321
|
+
if (model !== undefined && was !== model) {
|
|
322
|
+
await $.command.run({ command: 'model', args: model })
|
|
323
|
+
$.ui.toast(`org-switch: ${reason}; now on ${model}.`, { timeoutMs: 8000 })
|
|
324
|
+
}
|
|
325
|
+
if (go) await sendContinue($)
|
|
326
|
+
await restoreFable($)
|
|
327
|
+
return
|
|
328
|
+
}
|
|
329
|
+
await $.store.set('lastSwitchAt', await $.clock.now())
|
|
330
|
+
// The other org's process starts on its own default model: carry this one over.
|
|
331
|
+
// A session nobody has written to starts fresh under the other org: there is nothing to resume, so nothing to record.
|
|
332
|
+
if (env.resumed || conversed) await $.store.set(`resume:${await $.session.id()}`, { go, model: model ?? was } satisfies Resume)
|
|
333
|
+
startSwitch($, org, shouldCompact(), reason)
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Wait for `org` to clear, looking again every PROBE_MS in case a limit lifted early. The timer only decides again. */
|
|
337
|
+
function waitFor($: Engine, d: { org: string; model?: string; at: number }, now: number, why: Why, detail: string): void {
|
|
338
|
+
waiting = true
|
|
339
|
+
waitWhy = why
|
|
340
|
+
const id = ++waitId
|
|
341
|
+
const due = Math.min(d.at, now + PROBE_MS)
|
|
342
|
+
const isDue = due >= d.at
|
|
343
|
+
$.ui.toast(
|
|
344
|
+
`org-switch: every org is limited. ${d.org}${d.model ? ` (${d.model})` : ''} frees ${fmtIn(d.at - now)}; ${isDue ? 'continuing then' : `retrying in ${Math.round((due - now) / 60000)} min for a reset`}.`,
|
|
345
|
+
{ timeoutMs: 15000 },
|
|
346
|
+
)
|
|
347
|
+
$.clock.after(Math.max(0, due - now) + 5000, () => {
|
|
348
|
+
if (id !== waitId) return
|
|
349
|
+
waiting = false
|
|
350
|
+
void react($, why, detail, !isDue)
|
|
351
|
+
})
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Every org is out for a while: if Codex may take over here, hand this session
|
|
356
|
+
* to the launcher to run Codex until `d.at`, then resume under `d.org`; true
|
|
357
|
+
* when that started. Otherwise say why and return false (the caller waits).
|
|
358
|
+
*/
|
|
359
|
+
async function handToCodex($: Engine, d: { org: string; model?: string; at: number }, now: number): Promise<boolean> {
|
|
360
|
+
const r = await $.process.run(['sh', '-c', CODEX_READY_SH])
|
|
361
|
+
if (r.exitCode !== 0) {
|
|
362
|
+
$.ui.toast(`org-switch: every org is limited for a while, but Codex was not started: ${CODEX_NOT_READY[r.exitCode] ?? `the check failed (exit ${r.exitCode})`}. Waiting instead.`, { timeoutMs: 15000 })
|
|
363
|
+
return false
|
|
364
|
+
}
|
|
365
|
+
const was = await $.session.model()
|
|
366
|
+
if (d.model === DOWNGRADE_MODEL && isFable(was)) await $.store.set('downgrade', { from: was } satisfies Downgrade)
|
|
367
|
+
await $.store.set(`resume:${await $.session.id()}`, { go: true, model: d.model ?? was } satisfies Resume)
|
|
368
|
+
startSwitch($, d.org, false, `every org limited; Codex works until ${d.org} frees ${fmtIn(d.at - now)}`, `codex=1\nuntil=${Math.ceil(d.at / 1000)}\n`)
|
|
369
|
+
return true
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Decide from the readings as they are now and carry it out. The first
|
|
374
|
+
* reaction to a limit and every timer set for it come through here with the
|
|
375
|
+
* trigger that started it, so a target is never older than this call and a
|
|
376
|
+
* window warning never turns into a "继续". `probe`: a wait's early look, which
|
|
377
|
+
* tries one "继续" when the wait is still on.
|
|
378
|
+
*/
|
|
379
|
+
async function react($: Engine, why: Why, detail: string, probe = false): Promise<void> {
|
|
380
|
+
if (!active() || handoffStarted) return
|
|
381
|
+
const cur = env.org as string
|
|
382
|
+
const now = await $.clock.now()
|
|
383
|
+
const last = await $.store.get('lastSwitchAt')
|
|
384
|
+
const d = decide({ now, current: cur, orgs: env.orgs, fable: isFable(await $.session.model()), why, states: await readStates($), lastSwitchAt: typeof last === 'number' ? last : undefined }, env.switchPct)
|
|
385
|
+
if (d.kind === 'stay') return $.ui.toast(`org-switch: ${cur}: ${detail}; no other org is free. Staying put.`, { timeoutMs: 8000 })
|
|
386
|
+
if (d.kind === 'wait' && d.at > now) {
|
|
387
|
+
// The probe fails cheaply if still limited, and that failure decides again.
|
|
388
|
+
if (probe) return void (await sendContinue($))
|
|
389
|
+
if (d.at - now > TAKEOVER_AFTER_MS && (await handToCodex($, d, now))) return
|
|
390
|
+
return waitFor($, d, now, why, detail)
|
|
391
|
+
}
|
|
392
|
+
const go = d.kind === 'move' ? d.go : why !== 'window'
|
|
393
|
+
await moveTo($, d.org, d.model, go, d.model !== undefined && d.org === cur ? 'Fable limited on every org' : `${cur}: ${detail}`)
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Back on the model a limit moved the session off, once its hold here has
|
|
398
|
+
* passed: from a timer set for then, else when a turn ends, so the next turn
|
|
399
|
+
* starts on it. (A prompt.submit hook may not change the model.)
|
|
400
|
+
*/
|
|
401
|
+
async function restoreFable($: Engine): Promise<void> {
|
|
402
|
+
const g = (await $.store.get('downgrade')) as Downgrade | null | undefined
|
|
403
|
+
if (g == null) return
|
|
404
|
+
if ((await $.session.model()) !== DOWNGRADE_MODEL) return void (await $.store.delete('downgrade')) // changed by hand
|
|
405
|
+
const now = await $.clock.now()
|
|
406
|
+
const at = availableAt(await readState($, env.org as string), true, now, env.switchPct)
|
|
407
|
+
const id = ++restoreId
|
|
408
|
+
if (at > now) {
|
|
409
|
+
$.clock.after(at - now, () => { if (id === restoreId) void restoreFable($) })
|
|
410
|
+
return
|
|
411
|
+
}
|
|
412
|
+
try {
|
|
413
|
+
await $.command.run({ command: 'model', args: g.from })
|
|
414
|
+
} catch {
|
|
415
|
+
return // a turn is running: its turn.complete tries again
|
|
416
|
+
}
|
|
417
|
+
await $.store.delete('downgrade')
|
|
418
|
+
$.ui.toast(`org-switch: Fable is free again; back on ${g.from}.`, { timeoutMs: 8000 })
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async function onLimited($: Engine, why: Why, detail: string): Promise<void> {
|
|
422
|
+
// A failed turn while only a window warning waits (the switch cooldown) takes that wait over: the turn must go on.
|
|
423
|
+
if (!active() || handoffStarted || (waiting && !(waitWhy === 'window' && why !== 'window'))) return
|
|
424
|
+
const cur = env.org as string
|
|
425
|
+
const now = await $.clock.now()
|
|
426
|
+
const fable = isFable(await $.session.model())
|
|
427
|
+
const block = unexplainedBlock(why, await readState($, cur), fable, now, env.switchPct)
|
|
428
|
+
if (block !== undefined) await $.store.set(`block:${cur}`, block)
|
|
429
|
+
await react($, why, detail)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function report($: Engine): Promise<string> {
|
|
433
|
+
const now = await $.clock.now()
|
|
434
|
+
const cur = env.org as string
|
|
435
|
+
const fmtWindow = (kind: string, w: WindowSeen) => {
|
|
436
|
+
const t = w.resetsAt !== undefined ? Date.parse(w.resetsAt) : NaN
|
|
437
|
+
return `${short(kind)} ${w.percentUsed}%${Number.isFinite(t) ? ` (resets ${fmtIn(t - now)})` : ''}`
|
|
438
|
+
}
|
|
439
|
+
const lines = [`on: ${cur} orgs: ${env.orgs.join(', ')} switch at ${env.switchPct}% context: ${Math.round(contextPct)}% (compacts on switch from ${COMPACT_AT}%)`]
|
|
440
|
+
const limits = lastLimits.length > 0 ? lastLimits : (await $.session.usage()).rateLimits
|
|
441
|
+
lines.push(limits.length > 0 ? `${cur} now: ${limits.map(w => fmtWindow(w.kind, w)).join(', ')}` : `${cur} now: no rate-limit reading yet`)
|
|
442
|
+
for (const org of env.orgs) {
|
|
443
|
+
if (org === cur) continue
|
|
444
|
+
const l = (await readState($, org)).ledger
|
|
445
|
+
if (l === undefined) continue
|
|
446
|
+
const ws = Object.entries(l.windows).map(([k, w]) => fmtWindow(k, w)).join(', ')
|
|
447
|
+
lines.push(`${org} (last seen ${fmtAgo(now - l.seenAt)}): ${ws === '' ? 'no reading' : ws}`)
|
|
448
|
+
}
|
|
449
|
+
return lines.join('\n')
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export const register: Register = on => {
|
|
453
|
+
on('session.start', async ($, e, next) => {
|
|
454
|
+
const started = await next(e)
|
|
455
|
+
await loadEnv($)
|
|
456
|
+
handoffStarted = false
|
|
457
|
+
if (env.org !== undefined) saving = (await $.store.get(`saving:${env.org}`)) != null
|
|
458
|
+
await $.command.register({ name: 'org', description: 'Org rate-limit windows; /org switch [org] moves this session to another org', argumentHint: '[status | switch [org]]' })
|
|
459
|
+
if (env.org === undefined) return started
|
|
460
|
+
// A reading can arrive before the launcher's environment is known here, and a full window
|
|
461
|
+
// never moves again: take what the status line has now, so this org's state is on record.
|
|
462
|
+
const usage = await $.session.usage()
|
|
463
|
+
if (usage.rateLimits.length > 0) {
|
|
464
|
+
lastLimits = usage.rateLimits
|
|
465
|
+
await writeLedger($, env.org as string, lastLimits)
|
|
466
|
+
await updateSaving($, env.org as string, lastLimits)
|
|
467
|
+
}
|
|
468
|
+
$.ui.status(statusText(env.org as string, lastLimits))
|
|
469
|
+
if (!active()) return started
|
|
470
|
+
// Resumed by a switch: restore the model it chose and continue the turn that
|
|
471
|
+
// failed; after a takeover, ask Claude to review the working tree.
|
|
472
|
+
const key = `resume:${await $.session.id()}`
|
|
473
|
+
const r = (await $.store.get(key)) as Resume | null | undefined
|
|
474
|
+
const { codexExit, agyExit } = env
|
|
475
|
+
const tookOver = codexExit !== undefined || agyExit !== undefined
|
|
476
|
+
if (r != null) await $.store.delete(key)
|
|
477
|
+
if (r != null || tookOver) {
|
|
478
|
+
$.clock.after(1000, () => {
|
|
479
|
+
void (async () => {
|
|
480
|
+
if (r?.model !== undefined) await $.command.run({ command: 'model', args: r.model })
|
|
481
|
+
await restoreFable($)
|
|
482
|
+
if (tookOver) await $.prompt.submit({ text: takeoverText(codexExit, agyExit) })
|
|
483
|
+
else if (r?.go) await sendContinue($)
|
|
484
|
+
})()
|
|
485
|
+
})
|
|
486
|
+
}
|
|
487
|
+
return started
|
|
488
|
+
})
|
|
489
|
+
|
|
490
|
+
on('session.measure', async ($, e, next) => {
|
|
491
|
+
lastLimits = e.rateLimits
|
|
492
|
+
contextPct = e.context.percent ?? contextPct
|
|
493
|
+
if (env.org !== undefined) {
|
|
494
|
+
const cur = env.org
|
|
495
|
+
if (e.rateLimits.length > 0) {
|
|
496
|
+
await writeLedger($, cur, e.rateLimits)
|
|
497
|
+
await updateSaving($, cur, e.rateLimits)
|
|
498
|
+
}
|
|
499
|
+
$.ui.status(statusText(cur, e.rateLimits))
|
|
500
|
+
const hot = active() && e.changed.includes('rateLimits') ? e.rateLimits.find(w => w.percentUsed >= env.switchPct) : undefined
|
|
501
|
+
if (hot !== undefined) await onLimited($, 'window', `${short(hot.kind)} window at ${hot.percentUsed}%`)
|
|
502
|
+
}
|
|
503
|
+
return next(e)
|
|
504
|
+
})
|
|
505
|
+
|
|
506
|
+
on('prompt.submit', ($, e, next) => {
|
|
507
|
+
conversed = true
|
|
508
|
+
return next(e)
|
|
509
|
+
})
|
|
510
|
+
|
|
511
|
+
// Saving quota: the main loop's requests think one level less.
|
|
512
|
+
on('turn.step', async function* ($, e, next) {
|
|
513
|
+
if (!saving || e.agentId !== undefined || typeof e.effort !== 'string') return yield* next(e)
|
|
514
|
+
return yield* next({ ...e, effort: lowerEffort(e.effort) })
|
|
515
|
+
})
|
|
516
|
+
|
|
517
|
+
// A turn that died on a limit: decide, after the engine has finished with it.
|
|
518
|
+
on('classic.StopFailure', async ($, e, next) => {
|
|
519
|
+
const r = await next(e)
|
|
520
|
+
if (e.error === 'rate_limit' && active()) {
|
|
521
|
+
const hit = lastLimits.find(w => w.percentUsed >= env.switchPct)
|
|
522
|
+
const fable = isFable(await $.session.model())
|
|
523
|
+
const why: Why = hit === undefined && fable ? 'fable' : 'limit'
|
|
524
|
+
const detail = hit !== undefined ? `${short(hit.kind)} window at ${hit.percentUsed}%` : fable ? 'Fable limit' : 'rate limit'
|
|
525
|
+
$.clock.after(0, () => { void onLimited($, why, detail) })
|
|
526
|
+
}
|
|
527
|
+
return r
|
|
528
|
+
})
|
|
529
|
+
|
|
530
|
+
// A turn that worked clears what held this org off and cancels any wait.
|
|
531
|
+
on('turn.complete', async ($, e, next) => {
|
|
532
|
+
const r = await next(e)
|
|
533
|
+
if (e.reason === 'answer' && e.agentId === undefined && active()) {
|
|
534
|
+
waitId++
|
|
535
|
+
waiting = false
|
|
536
|
+
const cur = env.org as string
|
|
537
|
+
const b = (await readState($, cur)).block
|
|
538
|
+
if (b !== undefined && (b.kind === 'all' || isFable(await $.session.model()))) await $.store.delete(`block:${cur}`)
|
|
539
|
+
await restoreFable($)
|
|
540
|
+
}
|
|
541
|
+
// A plugin that runs above this one can pass classic.StopFailure on without it ever reaching the
|
|
542
|
+
// hook above. A turn the API ended while a window is at the limit is that same failure, seen here.
|
|
543
|
+
if (e.reason === 'error' && e.agentId === undefined && active()) {
|
|
544
|
+
const hit = lastLimits.find(w => w.percentUsed >= env.switchPct)
|
|
545
|
+
if (hit !== undefined) {
|
|
546
|
+
$.clock.after(0, () => { void onLimited($, 'limit', `${short(hit.kind)} window at ${hit.percentUsed}%`) })
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return r
|
|
550
|
+
})
|
|
551
|
+
|
|
552
|
+
on('command.run', { command: 'org' }, async ($, e) => {
|
|
553
|
+
if (env.org === undefined) return { text: 'org-switch: this session was not started by claude-org; nothing to switch.' }
|
|
554
|
+
const cur = env.org
|
|
555
|
+
const usage = `usage: /org [status] | /org switch [org] (orgs: ${env.orgs.join(', ')})`
|
|
556
|
+
const words = e.args.trim().split(/\s+/).filter(Boolean)
|
|
557
|
+
if (words.length === 0 || (words[0] === 'status' && words.length === 1)) return { text: await report($) }
|
|
558
|
+
if (recordOnly() && words[0] === 'switch') return { text: RECORD_ONLY_SWITCH }
|
|
559
|
+
if (words[0] !== 'switch' || words.length > 2) return { text: usage }
|
|
560
|
+
let target = words[1]
|
|
561
|
+
if (target !== undefined && (!env.orgs.includes(target) || target === cur)) return { text: usage }
|
|
562
|
+
if (target === undefined) {
|
|
563
|
+
const now = await $.clock.now()
|
|
564
|
+
const fable = isFable(await $.session.model())
|
|
565
|
+
const states = await readStates($)
|
|
566
|
+
target = env.orgs.find(o => o !== cur && availableAt(states[o] ?? {}, fable, now, env.switchPct) <= now)
|
|
567
|
+
if (target === undefined) return { text: 'org-switch: every other org is limited; name one to go anyway: /org switch <org>' }
|
|
568
|
+
}
|
|
569
|
+
return { text: startSwitch($, target, shouldCompact(), 'manual /org switch') }
|
|
570
|
+
})
|
|
571
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"orgs": [
|
|
3
|
+
{
|
|
4
|
+
"key": "main",
|
|
5
|
+
"name": "Your first org name",
|
|
6
|
+
"configDir": "~/.claude",
|
|
7
|
+
"environmentId": "",
|
|
8
|
+
"t3Instance": "claudeAgent"
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"key": "org2",
|
|
12
|
+
"name": "Your second org name",
|
|
13
|
+
"configDir": "~/.claude-org2",
|
|
14
|
+
"environmentId": "",
|
|
15
|
+
"t3Instance": "claude-org2"
|
|
16
|
+
}
|
|
17
|
+
]
|
|
18
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jaxonshaw/multi-model-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Route coding work across models and keep handoffs recoverable.",
|
|
5
|
+
"bin": {
|
|
6
|
+
"multi-model-kit": "bin/multi-model-kit"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
".agents/plugins/marketplace.json",
|
|
10
|
+
".claude-plugin",
|
|
11
|
+
".codex-plugin",
|
|
12
|
+
"bin",
|
|
13
|
+
"config/defaults.json",
|
|
14
|
+
"hooks",
|
|
15
|
+
"install.sh",
|
|
16
|
+
"INSTALL-AGENT.md",
|
|
17
|
+
"mods/org-switch/.claude-plugin",
|
|
18
|
+
"mods/org-switch/hooks/hooks.json",
|
|
19
|
+
"mods/org-switch/hooks/register.ts",
|
|
20
|
+
"mods/org-switch/tsconfig.json",
|
|
21
|
+
"orgs.example.json",
|
|
22
|
+
"plugins/paseo-usage/bridge/capture-quota.cjs",
|
|
23
|
+
"plugins/paseo-usage/index.server.ts",
|
|
24
|
+
"plugins/paseo-usage/paseo-plugin.json",
|
|
25
|
+
"plugins/paseo-usage/server/usage.mjs",
|
|
26
|
+
"rules",
|
|
27
|
+
"skills"
|
|
28
|
+
],
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public",
|
|
32
|
+
"registry": "https://registry.npmjs.org/"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://thejason1997.github.io/multi-model-kit/",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/TheJason1997/multi-model-kit.git"
|
|
38
|
+
},
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/TheJason1997/multi-model-kit/issues"
|
|
41
|
+
}
|
|
42
|
+
}
|