@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.
Files changed (51) hide show
  1. package/.agents/plugins/marketplace.json +11 -0
  2. package/.claude-plugin/marketplace.json +8 -0
  3. package/.claude-plugin/plugin.json +5 -0
  4. package/.codex-plugin/plugin.json +6 -0
  5. package/INSTALL-AGENT.md +95 -0
  6. package/LICENSE +21 -0
  7. package/README.md +152 -2
  8. package/bin/byok-review +258 -0
  9. package/bin/claude-org +415 -0
  10. package/bin/model-route +303 -0
  11. package/bin/multi-model-kit +22 -0
  12. package/bin/quota-status +259 -0
  13. package/config/defaults.json +45 -0
  14. package/hooks/hooks.json +14 -0
  15. package/hooks/session-start.sh +77 -0
  16. package/install.sh +1606 -0
  17. package/mods/org-switch/.claude-plugin/plugin.json +5 -0
  18. package/mods/org-switch/hooks/hooks.json +1 -0
  19. package/mods/org-switch/hooks/register.ts +571 -0
  20. package/mods/org-switch/tsconfig.json +3 -0
  21. package/orgs.example.json +18 -0
  22. package/package.json +40 -4
  23. package/plugins/paseo-usage/bridge/capture-quota.cjs +59 -0
  24. package/plugins/paseo-usage/index.server.ts +47 -0
  25. package/plugins/paseo-usage/paseo-plugin.json +8 -0
  26. package/plugins/paseo-usage/server/usage.mjs +140 -0
  27. package/rules/multi-model.md +15 -0
  28. package/skills/dispatch/SKILL.md +148 -0
  29. package/skills/dispatch/references/brief-template.md +52 -0
  30. package/skills/dispatch/references/ce-config.example.yaml +19 -0
  31. package/skills/dispatch/references/paseo.md +87 -0
  32. package/skills/dispatch/references/roundtable.md +32 -0
  33. package/skills/dispatch/references/routing.md +83 -0
  34. package/skills/dispatch/references/watch-paseo.md +217 -0
  35. package/skills/dispatch/references/watch.md +42 -0
  36. package/skills/prompt-library/SKILL.md +60 -0
  37. package/skills/prompt-library/prompts/c01-first-principles.md +1 -0
  38. package/skills/prompt-library/prompts/c02-clarify-then-options.md +1 -0
  39. package/skills/prompt-library/prompts/c03-reframe-problem.md +1 -0
  40. package/skills/prompt-library/prompts/c04-second-order-effects.md +1 -0
  41. package/skills/prompt-library/prompts/c05-cross-domain.md +1 -0
  42. package/skills/prompt-library/prompts/c06-argue-against.md +1 -0
  43. package/skills/prompt-library/prompts/c07-git-history-legacy.md +1 -0
  44. package/skills/prompt-library/prompts/c08-onboarding-cost.md +1 -0
  45. package/skills/prompt-library/prompts/c09-slow-prs.md +1 -0
  46. package/skills/prompt-library/prompts/c10-rework-retro.md +1 -0
  47. package/skills/prompt-library/prompts/d01-complexity-to-system.md +11 -0
  48. package/skills/prompt-library/prompts/d02-motion.md +11 -0
  49. package/skills/task-handoff/SKILL.md +319 -0
  50. package/skills/task-handoff/references/handoff-template.md +134 -0
  51. package/skills/task-handoff/references/takeover-prompt.md +81 -0
package/bin/claude-org ADDED
@@ -0,0 +1,415 @@
1
+ #!/bin/sh
2
+ # claude-org — run Claude Code under one org, each org signed in with its own
3
+ # /login in its own config directory, and when the org-switch mod asks, restart
4
+ # under another org resuming the same session in this terminal.
5
+ #
6
+ # claude-org [org] [claude args...] start (no org: one with quota left)
7
+ # claude-org setup <org> create that org's config directory
8
+ #
9
+ # Orgs come from orgs.json next to this script's folder: key, name, config
10
+ # directory, cloud environment id. The org whose directory is ~/.claude runs
11
+ # with CLAUDE_CONFIG_DIR unset, exactly like a plain `claude`; every other org
12
+ # runs with CLAUDE_CONFIG_DIR pointing at its directory. This script never
13
+ # reads or writes a credential: each directory holds its own login.
14
+ #
15
+ # The mod gets CLAUDE_ORG, CLAUDE_ORGS and CLAUDE_ORG_HANDOFF (a file path); to
16
+ # switch it writes "next=<org>" and "session=<uuid>" there and exits, and this
17
+ # loop relaunches `claude --resume <uuid>` under that org with the original
18
+ # flags (minus -c / -r / --session-id; whatever follows a `--` is passed on as
19
+ # it is). Two orgs may not share one physical directory: that would be one
20
+ # login.
21
+ #
22
+ # When every org is out for a while, the mod also writes "codex=1" and
23
+ # "until=<epoch seconds>". With takeover enabled, this loop runs Codex in the
24
+ # foreground (files only, no commits), then agy if Codex hits a quota limit.
25
+ # It waits until the reset and passes any exit codes to the resumed session.
26
+ # Ctrl-C stops the foreground agent; Ctrl-C during the wait stops here and
27
+ # says how to resume. The old
28
+ # acct-switch mod is turned off
29
+ # for these processes only, through --settings; the shared settings file is
30
+ # untouched and claude-acct keeps working.
31
+ set -u
32
+
33
+ here=$(CDPATH= cd -P "$(dirname "$0")/.." && pwd)
34
+ ORGS_FILE=$here/orgs.json
35
+ MOD_DIR=$here/mods/org-switch
36
+ DEFAULT_DIR=$HOME/.claude
37
+ MAX_HANDOFFS=20
38
+ UUID_RE='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
39
+ ACCT_SWITCH_OFF='{"enabledPlugins":{"acct-switch@local-mods":false}}'
40
+ TAB=$(printf '\t')
41
+ CODEX_MODEL=gpt-6.2-astra
42
+ AGY_MODEL=gemini-4-neon
43
+ AGY_EFFORT=medium
44
+ TAKEOVER_CONFIG=${XDG_CONFIG_HOME:-"$HOME/.config"}/multi-model-kit/config.json
45
+ TAKEOVER_NOTES=.takeover-notes.md
46
+ TAKEOVER_PROMPT="读 .handoff.md,只做其中标为非界面的单元。只改文件:不要 git add、不要提交、不要推送。做完把做了什么追加写进仓库根目录的 ${TAKEOVER_NOTES}。"
47
+ CODEX_LIMIT_RE='^[[:space:]]*error:[[:space:]]*(.*[^[:alnum:]])?(rate[ _-]+limit(ed|s|ing)?|usage[ _-]+limit(s)?|quota[ _-]+((has been |was |is )?(exceeded|exhausted)|limit)|insufficient[ _-]+quota|exceeded (your |the |current )?quota|too many requests|http(/[0-9.]+)?[[:space:]:]+429|status([ _-]+code)?[[:space:]:]+429)([^[:alnum:]]|$)'
48
+
49
+ die() { echo "claude-org: $*" >&2; exit 1; }
50
+
51
+ # One line per org: key<TAB>config directory (~ expanded). Bad entries are skipped.
52
+ orgs() {
53
+ python3 -I - "$ORGS_FILE" "$HOME" <<'PY'
54
+ import json, os, re, sys
55
+ path, home = sys.argv[1], sys.argv[2]
56
+ for o in json.load(open(path)).get('orgs', []):
57
+ key, d = o.get('key', ''), o.get('configDir', '')
58
+ if not re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', key) or not isinstance(d, str):
59
+ continue
60
+ if d == '~' or d.startswith('~/'):
61
+ d = home + d[1:]
62
+ if os.path.isabs(d) and '\t' not in d and '\n' not in d:
63
+ print(key + '\t' + os.path.normpath(d))
64
+ PY
65
+ }
66
+
67
+ [ -f "$ORGS_FILE" ] || die "no $ORGS_FILE (copy orgs.example.json to orgs.json and fill it in)"
68
+ ORGS=$(orgs) || die "cannot read $ORGS_FILE"
69
+
70
+ dir_of() { printf '%s\n' "$ORGS" | awk -F "$TAB" -v k="$1" '$1 == k { print $2; exit }'; }
71
+ # Orgs whose directory exists, comma-separated: the ones a session can start or switch to.
72
+ ready() {
73
+ r=""
74
+ while IFS="$TAB" read -r k d; do
75
+ [ -n "$k" ] && [ -d "$d" ] && r="${r:+$r,}$k"
76
+ done <<EOT
77
+ $ORGS
78
+ EOT
79
+ printf '%s' "$r"
80
+ }
81
+ # Two orgs whose directories are one physical directory, as "a and b"; empty when
82
+ # all differ. Compared by device and inode, not by name: a link, or other letter
83
+ # case on a file system that ignores it, names the same directory differently.
84
+ same_dir() {
85
+ printf '%s\n' "$ORGS" | python3 -I -c '
86
+ import os, sys
87
+ seen = {}
88
+ for line in sys.stdin:
89
+ k, _, d = line.rstrip("\n").partition("\t")
90
+ try:
91
+ st = os.stat(d)
92
+ except OSError:
93
+ continue
94
+ if not os.path.isdir(d):
95
+ continue
96
+ if (st.st_dev, st.st_ino) in seen:
97
+ print(seen[(st.st_dev, st.st_ino)] + " and " + k)
98
+ break
99
+ seen[(st.st_dev, st.st_ino)] = k
100
+ '
101
+ }
102
+ distinct() {
103
+ dup=$(same_dir) || die "cannot compare the org directories"
104
+ [ -z "$dup" ] || die "orgs $dup resolve to the same directory; each org needs a login directory of its own"
105
+ }
106
+ in_list() { case ",$2," in *",$1,"*) return 0 ;; esac; return 1; }
107
+
108
+ # Names inside ~/.claude that belong to one login and so are not shared:
109
+ # the account state file and its backups, the stored credential, org policy
110
+ # and remote settings fetched for the signed-in org, auth caches, the daemon.
111
+ is_account_state() {
112
+ case "$1" in
113
+ .claude.json|.claude.json.*|.credentials*|backups|policy-limits.json*|remote-settings*|mcp-needs-auth-cache.json|daemon|daemon.log|daemon-auth-*) return 0 ;;
114
+ esac
115
+ return 1
116
+ }
117
+
118
+ setup() {
119
+ [ $# -eq 1 ] || die "usage: claude-org setup <org>"
120
+ dir=$(dir_of "$1")
121
+ [ -n "$dir" ] || die "no org '$1' in $ORGS_FILE"
122
+ [ "$dir" != "$DEFAULT_DIR" ] || die "$1 uses $DEFAULT_DIR, which is already set up"
123
+ distinct
124
+ if [ -e "$dir" ] && python3 -I -c 'import os, sys; sys.exit(not os.path.samefile(sys.argv[1], sys.argv[2]))' "$dir" "$DEFAULT_DIR" 2>/dev/null; then
125
+ die "$dir is the same directory as $DEFAULT_DIR; each org needs a login directory of its own"
126
+ fi
127
+ [ -d "$DEFAULT_DIR" ] || die "no $DEFAULT_DIR to link to"
128
+ if [ -e "$dir" ] || [ -L "$dir" ]; then
129
+ [ -d "$dir" ] && [ -z "$(ls -A "$dir")" ] || die "$dir already exists and is not empty; not touching it"
130
+ fi
131
+ mkdir -p "$dir" || exit 1
132
+ for src in "$DEFAULT_DIR"/* "$DEFAULT_DIR"/.[!.]* "$DEFAULT_DIR"/..?*; do
133
+ [ -e "$src" ] || [ -L "$src" ] || continue
134
+ name=${src##*/}
135
+ is_account_state "$name" && continue
136
+ ln -s "$src" "$dir/$name" || exit 1
137
+ done
138
+ echo "claude-org: linked $dir to $DEFAULT_DIR (everything but the account state)"
139
+
140
+ # Global MCP servers live in the account state file and may embed keys: copy them only when asked.
141
+ global=$HOME/.claude.json
142
+ if [ -f "$global" ]; then
143
+ printf 'Copy the global MCP servers from %s into %s/.claude.json? Their settings may hold keys. [y/N] ' "$global" "$dir"
144
+ ans=""
145
+ read -r ans || ans=""
146
+ case "$ans" in
147
+ y|Y|yes|YES)
148
+ (umask 077 && python3 -I - "$global" "$dir/.claude.json" <<'PY'
149
+ import json, os, sys
150
+ src, dst = sys.argv[1], sys.argv[2]
151
+ servers = json.load(open(src)).get('mcpServers') or {}
152
+ cfg = json.load(open(dst)) if os.path.exists(dst) else {}
153
+ cfg['mcpServers'] = {**(cfg.get('mcpServers') or {}), **servers}
154
+ tmp = dst + '.tmp'
155
+ with open(tmp, 'w') as f:
156
+ json.dump(cfg, f, indent=2)
157
+ os.replace(tmp, dst)
158
+ print('claude-org: copied %d MCP server(s)' % len(servers))
159
+ PY
160
+ ) || die "could not copy the MCP servers"
161
+ ;;
162
+ *) echo "claude-org: MCP servers not copied" ;;
163
+ esac
164
+ fi
165
+ echo "Now sign in to this org once (\`command\` skips any claude alias):"
166
+ echo " CLAUDE_CONFIG_DIR='$dir' command claude auth login"
167
+ echo " CLAUDE_CONFIG_DIR='$dir' command claude auth status"
168
+ }
169
+
170
+ # With no org named: from the mod's records, an org with quota left, the most
171
+ # recently used first; else the one that frees up first; else the first ready one.
172
+ pick_org() {
173
+ python3 -I - "$DEFAULT_DIR/plugins/store" "$1" "$here/config/defaults.json" 2>/dev/null <<'PY'
174
+ import glob, json, os, sys, time
175
+ from datetime import datetime
176
+ from pathlib import Path
177
+
178
+ store, orgs = sys.argv[1], sys.argv[2].split(',')
179
+ defaults = json.loads(Path(sys.argv[3]).read_text(encoding='utf-8'))['quota']
180
+ thr = defaults['switchPct']
181
+ config_home = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')
182
+ try:
183
+ overrides = json.loads((config_home / 'multi-model-kit/config.json').read_text(encoding='utf-8')).get('quota', {})
184
+ if isinstance(overrides, dict):
185
+ soft = overrides.get('softPct', defaults['softPct'])
186
+ switch = overrides.get('switchPct', thr)
187
+ if type(soft) is int and type(switch) is int and 0 < soft < switch <= 100:
188
+ thr = switch
189
+ except (OSError, ValueError, AttributeError):
190
+ pass
191
+ # The newest store file that parses and holds a well-formed reading; any other is skipped.
192
+ def mtime(p):
193
+ try:
194
+ return os.path.getmtime(p)
195
+ except OSError:
196
+ return 0
197
+ def good(l):
198
+ w = l.get('windows')
199
+ return isinstance(w, dict) and isinstance(l.get('seenAt', 0), (int, float)) and all(isinstance(x, dict) and isinstance(x.get('percentUsed', 0), (int, float)) for x in w.values())
200
+ d = {}
201
+ for p in sorted(glob.glob(os.path.join(store, 'org-switch_*.json')), key=mtime, reverse=True):
202
+ try:
203
+ c = json.load(open(p))
204
+ except (OSError, ValueError):
205
+ continue
206
+ ls = [v for k, v in c.items() if k.startswith('ledger:')] if isinstance(c, dict) else []
207
+ if ls and all(isinstance(v, dict) and good(v) for v in ls):
208
+ d = c
209
+ break
210
+ now = time.time() * 1000
211
+ def ts(s):
212
+ try:
213
+ return datetime.fromisoformat(str(s).replace('Z', '+00:00')).timestamp() * 1000
214
+ except ValueError:
215
+ return None
216
+ ranked = []
217
+ for o in orgs:
218
+ l, at = d.get('ledger:' + o) or {}, now
219
+ for w in (l.get('windows') or {}).values():
220
+ t = ts(w.get('resetsAt'))
221
+ if w.get('percentUsed', 0) >= thr and t and t > at:
222
+ at = t
223
+ b = d.get('block:' + o)
224
+ if isinstance(b, dict) and b.get('kind') == 'all' and isinstance(b.get('until'), (int, float)) and b['until'] > at:
225
+ at = b['until']
226
+ ranked.append((at > now, at if at > now else 0, -l.get('seenAt', 0), orgs.index(o), o))
227
+ print(sorted(ranked)[0][4])
228
+ PY
229
+ }
230
+
231
+ # Options end at `--`: what follows is the person's own text.
232
+ names_session() {
233
+ for a in "$@"; do
234
+ case "$a" in --) return 1 ;; -c|--continue|-r|--resume|--resume=*|--session-id|--session-id=*) return 0 ;; esac
235
+ done
236
+ return 1
237
+ }
238
+
239
+ takeover_enabled() {
240
+ python3 -I - "$TAKEOVER_CONFIG" "$here/config/defaults.json" <<'PY'
241
+ import json, sys
242
+ from pathlib import Path
243
+
244
+ user, defaults = map(Path, sys.argv[1:])
245
+ try:
246
+ default = json.loads(defaults.read_text(encoding='utf-8')).get('takeover', 'off')
247
+ config = json.loads(user.read_text(encoding='utf-8')) if user.exists() else {}
248
+ enabled = config.get('takeover', default) == 'on'
249
+ except (OSError, ValueError, AttributeError):
250
+ enabled = False
251
+ sys.exit(not enabled)
252
+ PY
253
+ }
254
+
255
+ # A FIFO captures stderr for quota detection while leaving stdout live and
256
+ # keeping Codex in the foreground so we can take its exit status directly.
257
+ run_codex() {
258
+ mkfifo "$run_dir/codex.pipe" || return 1
259
+ tee "$run_dir/codex.stderr" < "$run_dir/codex.pipe" >&2 &
260
+ capture_pid=$!
261
+ codex exec -C "$top" -s workspace-write -m "$CODEX_MODEL" "$TAKEOVER_PROMPT" 2> "$run_dir/codex.pipe"
262
+ result=$?
263
+ wait "$capture_pid"
264
+ rm -f "$run_dir/codex.pipe"
265
+ return "$result"
266
+ }
267
+
268
+ run_agy() {
269
+ if ! command -v agy >/dev/null 2>&1; then
270
+ agy_skip='the agy command is not installed'
271
+ elif [ ! -f "$top/.handoff.md" ]; then
272
+ agy_skip='the repository has no .handoff.md'
273
+ else
274
+ printf '\n## %s agy 接手(Claude 不提交,等恢复后审查)\n' "$(date '+%Y-%m-%d %H:%M')" >> "$notes"
275
+ echo "claude-org: Codex reached a quota limit; agy takes over (Ctrl-C stops it)" >&2
276
+ (CDPATH= cd "$top" && exec agy -p "$TAKEOVER_PROMPT" --mode accept-edits --effort "$AGY_EFFORT" --model "$AGY_MODEL")
277
+ agy_rc=$?
278
+ printf '\nagy 退出码 %s\n' "$agy_rc" >> "$notes"
279
+ return
280
+ fi
281
+ printf 'claude-org: agy was not started: %s. Waiting instead.\n' "$agy_skip" | tee -a "$notes" >&2
282
+ }
283
+
284
+ if [ "${1:-}" = setup ]; then shift; setup "$@"; exit; fi
285
+
286
+ distinct
287
+ READY=$(ready)
288
+ [ -n "$READY" ] || die "no org in $ORGS_FILE has its config directory yet"
289
+ org=""
290
+ if [ $# -gt 0 ] && [ -n "$(dir_of "$1")" ]; then
291
+ org=$1; shift
292
+ in_list "$org" "$READY" || die "$org has no config directory yet; run: claude-org setup $org"
293
+ fi
294
+ if [ -z "$org" ]; then
295
+ org=$(pick_org "$READY") || org=""
296
+ in_list "$org" "$READY" || org=${READY%%,*}
297
+ echo "claude-org: starting on $org" >&2
298
+ fi
299
+
300
+ run_dir=$(mktemp -d "${TMPDIR:-/tmp}/claude-org.XXXXXX") || exit 1
301
+ handoff=$run_dir/handoff
302
+ trap 'rm -rf "$run_dir"' EXIT
303
+ trap 'rm -f "$handoff"' INT
304
+ # With an agent in the foreground, TERM takes effect once the agent exits.
305
+ trap 'exit 143' TERM
306
+
307
+ n=0
308
+ codex_rc=
309
+ agy_rc=
310
+ while :; do
311
+ : > "$handoff"
312
+ if names_session "$@"; then resumed=1; else resumed=; fi
313
+ dir=$(dir_of "$org")
314
+ if [ "$dir" = "$DEFAULT_DIR" ]; then
315
+ env -u CLAUDE_CODE_OAUTH_TOKEN -u CLAUDE_CONFIG_DIR \
316
+ CLAUDE_ORG="$org" CLAUDE_ORGS="$READY" CLAUDE_ORG_HANDOFF="$handoff" CLAUDE_ORG_RESUMED="$resumed" CLAUDE_ORG_CODEX_EXIT="$codex_rc" CLAUDE_ORG_AGY_EXIT="$agy_rc" \
317
+ claude --plugin-dir "$MOD_DIR" --settings "$ACCT_SWITCH_OFF" "$@"
318
+ else
319
+ env -u CLAUDE_CODE_OAUTH_TOKEN CLAUDE_CONFIG_DIR="$dir" \
320
+ CLAUDE_ORG="$org" CLAUDE_ORGS="$READY" CLAUDE_ORG_HANDOFF="$handoff" CLAUDE_ORG_RESUMED="$resumed" CLAUDE_ORG_CODEX_EXIT="$codex_rc" CLAUDE_ORG_AGY_EXIT="$agy_rc" \
321
+ claude --plugin-dir "$MOD_DIR" --settings "$ACCT_SWITCH_OFF" "$@"
322
+ fi
323
+ rc=$?
324
+ codex_rc=
325
+ agy_rc=
326
+
327
+ next=$(sed -n 's/^next=//p' "$handoff" | head -n 1)
328
+ sid=$(sed -n 's/^session=//p' "$handoff" | head -n 1)
329
+ fresh=$(sed -n 's/^fresh=//p' "$handoff" | head -n 1)
330
+ reason=$(sed -n 's/^reason=//p' "$handoff" | head -n 1)
331
+ takeover=$(sed -n 's/^codex=//p' "$handoff" | head -n 1)
332
+ until=$(sed -n 's/^until=//p' "$handoff" | head -n 1)
333
+ [ -n "$next" ] && { [ -n "$sid" ] || [ "$fresh" = 1 ]; } || exit "$rc"
334
+
335
+ # The directories may have changed while that session ran: look again.
336
+ distinct
337
+ READY=$(ready)
338
+ if ! in_list "$next" "$READY" || [ -z "$(dir_of "$next")" ]; then
339
+ echo "claude-org: handoff names an org that cannot start; stopping" >&2; exit "$rc"
340
+ fi
341
+ if [ -n "$sid" ] && ! printf '%s' "$sid" | grep -Eq "$UUID_RE"; then
342
+ echo "claude-org: handoff session id is not a UUID; stopping" >&2; exit "$rc"
343
+ fi
344
+ n=$((n + 1))
345
+ if [ "$n" -gt "$MAX_HANDOFFS" ]; then
346
+ echo "claude-org: $n handoffs in one run; stopping" >&2; exit "$rc"
347
+ fi
348
+
349
+ if [ "$takeover" = 1 ]; then
350
+ case "$until" in ''|*[!0-9]*|0?*) echo "claude-org: handoff resume time is not a number; stopping" >&2; exit "$rc" ;; esac
351
+ # No quota window is longer than a week: a later time is a bad reading, not something to sleep through.
352
+ if [ "${#until}" -gt 11 ] || [ "$until" -gt $(( $(date +%s) + 8 * 86400 )) ]; then
353
+ echo "claude-org: handoff resume time is more than 8 days away; stopping" >&2; exit "$rc"
354
+ fi
355
+ [ -n "$sid" ] || { echo "claude-org: Codex handoff without a session id; stopping" >&2; exit "$rc"; }
356
+ wait_reason='every org is limited'
357
+ resume_hint='run:'
358
+ if takeover_enabled; then
359
+ top=$(git rev-parse --show-toplevel 2>/dev/null) || top=$PWD
360
+ notes=$top/$TAKEOVER_NOTES
361
+ # The notes leave the tree dirty, so the next limit won't hand it over again.
362
+ printf '\n## %s Codex 接手(Claude 不提交,等恢复后审查)\n' "$(date '+%Y-%m-%d %H:%M')" >> "$notes"
363
+ echo "claude-org: every org is limited; Codex works here until it is done (Ctrl-C stops it), then $next resumes${reason:+ ($reason)}" >&2
364
+ echo "claude-org: do not start another session in this directory until Claude is back; nothing stops one from editing the same files" >&2
365
+ trap : INT # Ctrl-C reaches the foreground agent; the launcher carries on
366
+ run_codex
367
+ codex_rc=$?
368
+ printf '\nCodex 退出码 %s\n' "$codex_rc" >> "$notes"
369
+ wait_reason="Codex exited ($codex_rc)"
370
+ if [ "$codex_rc" -gt 0 ] && [ "$codex_rc" -lt 128 ] &&
371
+ LC_ALL=C sed "s|$(printf '\033')\[[0-?]*[ -/]*[@-~]||g" "$run_dir/codex.stderr" |
372
+ grep -Eiq "$CODEX_LIMIT_RE"; then
373
+ run_agy
374
+ [ -z "$agy_rc" ] || wait_reason="agy exited ($agy_rc)"
375
+ fi
376
+ rm -f "$run_dir/codex.stderr"
377
+ resume_hint='review git status, then run:'
378
+ else
379
+ printf 'claude-org: automatic takeover is off. Set "takeover": "on" in %s to enable it.\n' "$TAKEOVER_CONFIG" >&2
380
+ reason='every org limited; automatic takeover is off'
381
+ fi
382
+ trap 'echo "claude-org: stopped before resuming; $resume_hint claude-org $next${sid:+ --resume $sid}" >&2; exit 130' INT
383
+ now=$(date +%s)
384
+ if [ "$until" -gt "$now" ]; then
385
+ echo "claude-org: $wait_reason; waiting $(( (until - now + 59) / 60 )) min for $next (Ctrl-C stops here)" >&2
386
+ sleep $((until - now))
387
+ fi
388
+ trap 'rm -f "$handoff"' INT
389
+ fi
390
+
391
+ # Rebuild the argument list: drop session selectors, keep everything else,
392
+ # and from `--` on keep every word as it is.
393
+ i=0; total=$#; rest=
394
+ while [ "$i" -lt "$total" ]; do
395
+ a=$1; shift; i=$((i + 1))
396
+ if [ -n "$rest" ]; then set -- "$@" "$a"; continue; fi
397
+ case "$a" in
398
+ --) rest=1; set -- "$@" "$a" ;;
399
+ -c|--continue) ;;
400
+ -r|--resume|--session-id)
401
+ if [ "$i" -lt "$total" ]; then
402
+ case "$1" in -*) ;; *) shift; i=$((i + 1)) ;; esac
403
+ fi ;;
404
+ --resume=*|--session-id=*) ;;
405
+ *) set -- "$@" "$a" ;;
406
+ esac
407
+ done
408
+ if [ -n "$sid" ]; then
409
+ set -- --resume "$sid" "$@"
410
+ echo "claude-org: $org -> $next, resuming $sid${reason:+ ($reason)}" >&2
411
+ else
412
+ echo "claude-org: $org -> $next, new session${reason:+ ($reason)}" >&2
413
+ fi
414
+ org=$next
415
+ done