sprag-cli 3.106.1 → 3.107.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/README.ko.md +2 -0
- package/README.md +2 -0
- package/bin/cli.js +60 -7
- package/package.json +2 -2
- package/presets/delegation/bounds.md +7 -1
- package/src/caps-cache.js +12 -2
- package/src/codex/delegation.js +24 -8
- package/src/codex/route-scan.js +2 -1
- package/src/commands/brief.js +45 -3
- package/src/commands/doc2md.js +7 -0
- package/src/commands/route-scan.js +15 -0
- package/src/commands/routing.js +57 -2
- package/src/commands/secrets.js +107 -0
- package/src/compact-window.js +2 -1
- package/src/delegation-guard.js +74 -5
- package/src/doc2md.cjs +38 -0
- package/src/formatters/statusline.js +145 -17
- package/src/glyphs.js +5 -0
- package/src/grade-counts.js +85 -0
- package/src/harness.js +7 -6
- package/src/installer.js +2 -0
- package/src/judgement-prompt.js +145 -0
- package/src/model-rules.js +44 -3
- package/src/permission-secrets.js +239 -0
- package/src/preset-ratchet.js +2 -1
- package/src/private-file.js +20 -0
- package/src/redact.js +189 -0
- package/src/relax-offer.js +51 -0
- package/src/route-follow.js +42 -0
- package/src/route-inject.js +133 -4
- package/src/route-scan.js +25 -1
- package/src/routing-switch.js +105 -0
- package/src/session-effort.js +71 -0
- package/src/session-records.js +10 -1
- package/src/statusline-running.js +116 -0
- package/src/team-prompts.js +4 -83
package/README.ko.md
CHANGED
|
@@ -239,6 +239,8 @@ Codex에는 기본 훅과 `AGENTS.md` 하네스, 범위별 래칫 규칙, 한국
|
|
|
239
239
|
| `sprag route-scan` | 내 기록에서 위임 후보 찾기 (LLM 호출 0회) |
|
|
240
240
|
| `sprag route-scan savings` | 라우팅 절감 원장 조회 |
|
|
241
241
|
| `sprag routing on\|off` | 모델 위임(룰과 힌트와 후보 안내) 켜기와 끄기 |
|
|
242
|
+
| `sprag routing relax [off]` | 가장 바쁜 사용량 창이 초기화될 때까지 위임 범위를 넓히거나(그 뒤에는 자동으로 돌아옵니다) 일찍 끝냅니다. `sprag routing status`에 `relax: off` 또는 `relax: until HH:MM`이 나옵니다 |
|
|
243
|
+
| `sprag secrets [fix]` | Claude Code 설정 파일의 승인 목록에서 비밀 값이 든 항목을 찾아 보여 주고(값은 출력하지 않습니다), `fix` 로 원본을 백업한 뒤 지웁니다. `sprag secrets off` 는 세션 시작 알림을 끕니다 |
|
|
242
244
|
| `sprag harness check` | 🅷 하네스 점수 확인 |
|
|
243
245
|
| `sprag doc2md <파일>` | 문서 한 건을 Markdown 으로 변환 |
|
|
244
246
|
|
package/README.md
CHANGED
|
@@ -300,6 +300,8 @@ The ratchet presets, model-routing presets and delegation agents in `presets/` a
|
|
|
300
300
|
| `sprag route-scan` | Find delegation candidates in your own history (0 LLM calls) |
|
|
301
301
|
| `sprag route-scan savings` | The routing-savings ledger |
|
|
302
302
|
| `sprag routing on\|off` | Turn model delegation (rules, hints, candidates) on or off |
|
|
303
|
+
| `sprag routing relax [off]` | Widen delegation until the busiest usage window resets (it switches back by itself), or end that early. `sprag routing status` shows `relax: off` or `relax: until HH:MM` |
|
|
304
|
+
| `sprag secrets [fix]` | List approval-list entries in Claude Code settings files that hold secrets (values are never shown), or remove them after backing up the original. `sprag secrets off` silences the session start notice |
|
|
303
305
|
| `sprag harness check` | Current 🅷 harness score |
|
|
304
306
|
| `sprag doc2md <file>` | Convert one document to Markdown |
|
|
305
307
|
|
package/bin/cli.js
CHANGED
|
@@ -118,7 +118,8 @@ function segmentsFromArgs() {
|
|
|
118
118
|
|
|
119
119
|
/**
|
|
120
120
|
* Terminal width for the statusline wrap: `--columns N`, else the COLUMNS that
|
|
121
|
-
* Claude Code exports to the statusline process, else 0 (
|
|
121
|
+
* Claude Code exports to the statusline process, else 0 (the caller decides; the
|
|
122
|
+
* live statusline then assumes 120). The demo
|
|
122
123
|
* passes `useEnv: false` so recordings do not change with the shell they run in.
|
|
123
124
|
*/
|
|
124
125
|
function columnsFromArgs({ useEnv = true } = {}) {
|
|
@@ -132,7 +133,7 @@ function columnsFromArgs({ useEnv = true } = {}) {
|
|
|
132
133
|
const KNOWN_SUBCOMMANDS = new Set([
|
|
133
134
|
'last', 'brief', 'history', 'handoff', 'install', 'uninstall', 'mode', 'korean', 'cohesion',
|
|
134
135
|
'doc2md', 'delegate', 'proof', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
|
|
135
|
-
'seed', 'litellm-budget', 'oauth-budget', 'profile-map', 'feedback', 'saved', 'cowork', 'team', 'presets', 'routing',
|
|
136
|
+
'seed', 'litellm-budget', 'oauth-budget', 'profile-map', 'feedback', 'saved', 'cowork', 'team', 'presets', 'routing', 'secrets',
|
|
136
137
|
]);
|
|
137
138
|
|
|
138
139
|
// Flags each entry path reads, collected from the hasFlag/getArg/numArg calls in
|
|
@@ -227,10 +228,11 @@ Usage:
|
|
|
227
228
|
sprag mode [keywords] statusline preferences (icon/text, en/ko, window, ttl)
|
|
228
229
|
sprag seed register the bundled starter rules, one answer at a time
|
|
229
230
|
sprag presets [status|sync|show] centrally published presets: source, fetch now, effective list
|
|
231
|
+
sprag secrets [fix] find (and remove) secrets saved in Claude Code approval lists
|
|
230
232
|
sprag cowork [sync|on|off|exclude <dir>|include <dir>] copy the ratchet rules into Cowork tab folders
|
|
231
233
|
sprag korean on|off|status Korean writing guidance + write-time check
|
|
232
234
|
sprag cohesion on|off|status English sentence-connection guidance
|
|
233
|
-
sprag routing on|off|status model delegation master switch (rules, hints, candidates)
|
|
235
|
+
sprag routing on|off|status|relax [off]|effort-hint on|off model delegation master switch (rules, hints, candidates); relax widens it until the usage window resets
|
|
234
236
|
sprag doc2md on|off|<file> convert documents to Markdown before the model reads them
|
|
235
237
|
sprag delegate on|off|status add bounds and context to Task/Agent delegation prompts
|
|
236
238
|
sprag proof [--json] replayed delegation cases behind the tier rules (https://sprag.io/proof/)
|
|
@@ -248,7 +250,7 @@ Usage:
|
|
|
248
250
|
sprag --uninstall-hook remove that hook
|
|
249
251
|
sprag --statusline one-line output for Claude Code statusline
|
|
250
252
|
--verbose / --no-color / --icon / --no-timer / --single-line
|
|
251
|
-
--columns N
|
|
253
|
+
--columns N fit lines to N cells (default: $COLUMNS, which Claude Code sets, else 120)
|
|
252
254
|
|
|
253
255
|
Run any subcommand with --help for its own options where available.
|
|
254
256
|
Bug reports & feature requests: https://github.com/rootstudioyaml/sprag/issues
|
|
@@ -413,9 +415,14 @@ async function main() {
|
|
|
413
415
|
|
|
414
416
|
// Subcommand: routing — master switch for model delegation (ratchet-model.md
|
|
415
417
|
// rules, prompt hints, route-scan candidates).
|
|
416
|
-
// sprag routing on | off | status
|
|
418
|
+
// sprag routing on | off | status | relax [off]
|
|
417
419
|
if (args[0] === 'routing') return (await import('../src/commands/routing.js')).run({ args, hasFlag });
|
|
418
420
|
|
|
421
|
+
// Subcommand: secrets — find (and remove) secrets that "don't ask again" saved
|
|
422
|
+
// in the permission lists of Claude Code settings files.
|
|
423
|
+
// sprag secrets | secrets fix [--yes] | secrets off | on
|
|
424
|
+
if (args[0] === 'secrets') return (await import('../src/commands/secrets.js')).run({ args, hasFlag });
|
|
425
|
+
|
|
419
426
|
// Subcommand: doc2md — convert pptx/xlsx/pdf/docx to Markdown before the
|
|
420
427
|
// model reads them, so an unreadable binary never enters the context window.
|
|
421
428
|
// sprag doc2md on | off | <file> | --clean
|
|
@@ -721,6 +728,11 @@ async function main() {
|
|
|
721
728
|
// not change their minds when the analysis window empties.
|
|
722
729
|
const effort = extractEffort(stdinJson);
|
|
723
730
|
const ultra = ultraChipFor(stdinJson);
|
|
731
|
+
|
|
732
|
+
try {
|
|
733
|
+
const sid = extractSessionId(stdinJson);
|
|
734
|
+
if (sid && effort) (await import('../src/session-effort.js')).recordSessionEffort(sid, effort);
|
|
735
|
+
} catch (e) { debug('session-effort:record', e); }
|
|
724
736
|
// Recorded here too: a fresh session can render before it has any request
|
|
725
737
|
// in the analysis window, and its first prompt is briefed from this.
|
|
726
738
|
const ctxLive = extractContextUsage(stdinJson);
|
|
@@ -796,6 +808,15 @@ async function main() {
|
|
|
796
808
|
// handed a transcript path asks; every other caller gets no ultra chip.
|
|
797
809
|
const effort = extractEffort(stdinJson);
|
|
798
810
|
const ultra = isStatusline ? ultraChipFor(stdinJson) : null;
|
|
811
|
+
// The prompt hook gets no effort in its payload; it reads back what this render saw.
|
|
812
|
+
if (isStatusline && effort) {
|
|
813
|
+
try {
|
|
814
|
+
const sid = extractSessionId(stdinJson);
|
|
815
|
+
if (sid) (await import('../src/session-effort.js')).recordSessionEffort(sid, effort);
|
|
816
|
+
} catch (e) {
|
|
817
|
+
debug('session-effort:record', e);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
799
820
|
const ctxLive = extractContextUsage(stdinJson);
|
|
800
821
|
// The prompt-submit briefing has no payload field for the window, so it reads
|
|
801
822
|
// back what this render was told (see src/ctx-window-cache.js).
|
|
@@ -1030,6 +1051,19 @@ async function main() {
|
|
|
1030
1051
|
} catch (e) {
|
|
1031
1052
|
debug('effort-raise-ledger:totals', e);
|
|
1032
1053
|
}
|
|
1054
|
+
// What the delegation grade did (judgement delegations raised to Opus) and
|
|
1055
|
+
// whether a relax window is open. Both are lookups, and the relax deadline stays out of
|
|
1056
|
+
// the data while routing is off, since it does nothing then.
|
|
1057
|
+
let gradeActions = null;
|
|
1058
|
+
let relaxUntilNow = null;
|
|
1059
|
+
try {
|
|
1060
|
+
const { gradeActionTotals } = await import('../src/grade-counts.js');
|
|
1061
|
+
gradeActions = gradeActionTotals();
|
|
1062
|
+
const { routingEnabled, isRelaxed, relaxUntil } = await import('../src/routing-switch.js');
|
|
1063
|
+
if (routingEnabled() && isRelaxed()) relaxUntilNow = relaxUntil();
|
|
1064
|
+
} catch (e) {
|
|
1065
|
+
debug('grade-counts:totals', e);
|
|
1066
|
+
}
|
|
1033
1067
|
// 'auto' unless the user pinned a bucket. Read here rather than in the
|
|
1034
1068
|
// statusline branch below because the table and JSON formatters want the
|
|
1035
1069
|
// same answer.
|
|
@@ -1048,6 +1082,7 @@ async function main() {
|
|
|
1048
1082
|
// This session's subagent runs, matched to the session Claude Code is
|
|
1049
1083
|
// drawing for by the transcript path / session id in its payload.
|
|
1050
1084
|
let sessionDelegation;
|
|
1085
|
+
let runningNow = null;
|
|
1051
1086
|
// Delegation-rule counts, read only when `--segments` names `rules`: the
|
|
1052
1087
|
// chip is opt-in, so nothing else would look at them.
|
|
1053
1088
|
let ruleStats;
|
|
@@ -1062,6 +1097,18 @@ async function main() {
|
|
|
1062
1097
|
} catch (e) {
|
|
1063
1098
|
debug('statusline-data:session-delegation', e);
|
|
1064
1099
|
}
|
|
1100
|
+
// Subagents working right now, from the session's subagent transcripts: one
|
|
1101
|
+
// readdir and a stat per file, never a parse of a whole transcript.
|
|
1102
|
+
try {
|
|
1103
|
+
const { runningSubagents } = await import('../src/statusline-running.js');
|
|
1104
|
+
const running = runningSubagents(extractTranscriptPath(stdinJson));
|
|
1105
|
+
if (running) {
|
|
1106
|
+
const { userLanguage } = await import('../src/config.js');
|
|
1107
|
+
runningNow = { ...running, lang: userLanguage() };
|
|
1108
|
+
}
|
|
1109
|
+
} catch (e) {
|
|
1110
|
+
debug('statusline-running', e);
|
|
1111
|
+
}
|
|
1065
1112
|
if (rulesRequested) {
|
|
1066
1113
|
try {
|
|
1067
1114
|
const { delegationRuleStats } = await import('../src/statusline-data.js');
|
|
@@ -1109,7 +1156,10 @@ async function main() {
|
|
|
1109
1156
|
// Statusline-only; left undefined elsewhere so --format json keeps its shape.
|
|
1110
1157
|
routeScanAt: isStatusline ? routeScanAt : undefined,
|
|
1111
1158
|
effortRaises: isStatusline ? effortRaises : undefined,
|
|
1159
|
+
gradeActions: isStatusline ? gradeActions : undefined,
|
|
1160
|
+
relaxUntil: isStatusline ? relaxUntilNow : undefined,
|
|
1112
1161
|
sessionDelegation,
|
|
1162
|
+
runningSubagents: runningNow,
|
|
1113
1163
|
ruleStats,
|
|
1114
1164
|
ttlBucket,
|
|
1115
1165
|
};
|
|
@@ -1122,7 +1172,7 @@ async function main() {
|
|
|
1122
1172
|
const { formatReport } = await import('../src/formatters/csv.js');
|
|
1123
1173
|
output = formatReport(data);
|
|
1124
1174
|
} else if (format === 'statusline') {
|
|
1125
|
-
const { formatReport } = await import('../src/formatters/statusline.js');
|
|
1175
|
+
const { formatReport, DEFAULT_COLUMNS } = await import('../src/formatters/statusline.js');
|
|
1126
1176
|
const { statuslineDefaults } = await import('../src/config.js');
|
|
1127
1177
|
const cfg = statuslineDefaults();
|
|
1128
1178
|
|
|
@@ -1149,7 +1199,10 @@ async function main() {
|
|
|
1149
1199
|
// multi-line statusline in some versions (anthropics/claude-code#35176)
|
|
1150
1200
|
// — --single-line restores the legacy one-line layout in that case.
|
|
1151
1201
|
singleLine: hasFlag('--single-line'),
|
|
1152
|
-
columns
|
|
1202
|
+
// `--columns`, else the COLUMNS Claude Code exports, else a 120 cell
|
|
1203
|
+
// terminal: an unknown width must not mean "no limit", since the lines
|
|
1204
|
+
// are then cut or folded by the terminal in the middle of a chip.
|
|
1205
|
+
columns: columnsFromArgs() || DEFAULT_COLUMNS,
|
|
1153
1206
|
});
|
|
1154
1207
|
} else {
|
|
1155
1208
|
// The first screen is the pitch: what share of recent work a cheaper model
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.107.1",
|
|
4
4
|
"description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"release:notes": "node scripts/release-notes.mjs",
|
|
24
24
|
"site:docs": "node scripts/build-site-docs.mjs",
|
|
25
25
|
"site:serve": "node scripts/serve-site.mjs",
|
|
26
|
-
"test": "node
|
|
26
|
+
"test": "node scripts/test.mjs",
|
|
27
27
|
"test:mods": "claude plugin test mod/sprag-doc2md && claude plugin test mod/sprag-delegation-meter && claude plugin test mod/sprag-statusline",
|
|
28
28
|
"version": "node scripts/sync-site-version.mjs"
|
|
29
29
|
},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Delegation bounds
|
|
2
2
|
|
|
3
|
-
You were spawned by a delegation call from another session. These
|
|
3
|
+
You were spawned by a delegation call from another session. These five rules
|
|
4
4
|
keep your exploration finite and your output usable by the caller that spawned
|
|
5
5
|
you.
|
|
6
6
|
|
|
@@ -28,3 +28,9 @@ you.
|
|
|
28
28
|
from memory. A citation lets the caller check your claim in one step; an
|
|
29
29
|
unattributed claim forces the caller to redo the very search you were
|
|
30
30
|
delegated to save it from doing.
|
|
31
|
+
|
|
32
|
+
5. **Write shell commands that survive zsh.** Print separators with
|
|
33
|
+
`printf '%s\n' '----'`, not `echo ====` (zsh reads a leading `=` as a
|
|
34
|
+
command lookup and fails). Quote any argument with `?`, `*` or `[`, URLs
|
|
35
|
+
above all. The shell tool is `Bash`, with a capital B. A refused command
|
|
36
|
+
line wastes a call and reads as a failure in the caller's records.
|
package/src/caps-cache.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import { readFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
13
13
|
import { join } from 'node:path';
|
|
14
14
|
import { userDataDir } from './paths.js';
|
|
15
|
-
import { writeViaTmp } from './state-file.js';
|
|
15
|
+
import { writeViaTmp, runHousekeeping, sweepStaleTmp } from './state-file.js';
|
|
16
16
|
|
|
17
17
|
const CACHE_PATH = join(userDataDir(), 'last-caps.json');
|
|
18
18
|
|
|
@@ -42,10 +42,18 @@ export function persistSnapshot(snapshot) {
|
|
|
42
42
|
// tmp + rename: the statusline reads this every tick and must never see a
|
|
43
43
|
// half-written file.
|
|
44
44
|
const tmp = `${CACHE_PATH}.${process.pid}.tmp`;
|
|
45
|
-
writeViaTmp(tmp, CACHE_PATH, JSON.stringify(payload) + '\n');
|
|
45
|
+
writeViaTmp(tmp, CACHE_PATH, JSON.stringify(payload) + '\n'); // removes tmp itself when the write or rename fails
|
|
46
46
|
} catch {
|
|
47
47
|
// best-effort cache, never blocks the statusline
|
|
48
48
|
}
|
|
49
|
+
// A killed statusline leaves `last-caps.json.<pid>.tmp` behind (hundreds had
|
|
50
|
+
// piled up). This runs on every render, so the sweep is limited to once a day.
|
|
51
|
+
try {
|
|
52
|
+
const dir = userDataDir();
|
|
53
|
+
runHousekeeping(dir, { 'stale-tmp': () => sweepStaleTmp(dir) });
|
|
54
|
+
} catch {
|
|
55
|
+
// clean-up never blocks the statusline
|
|
56
|
+
}
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
/**
|
|
@@ -113,6 +121,7 @@ function modelFamily(text) {
|
|
|
113
121
|
* @param {{caps?: object|null}|null} [opts.snapshot] defaults to the recent snapshot
|
|
114
122
|
* @param {string|null} [opts.sessionModel] model id or display name of the session
|
|
115
123
|
* @returns {{ level: 'normal'|'high'|'critical', pct: number, key: string,
|
|
124
|
+
* resetsAt: number|null (epoch seconds, when the busiest window resets),
|
|
116
125
|
* source: 'subscription'|'litellm' }|null}
|
|
117
126
|
* null when there is no fresh snapshot or no window with a usable percentage
|
|
118
127
|
*/
|
|
@@ -134,6 +143,7 @@ export function capPressure({ snapshot = loadRecentSnapshot(), sessionModel } =
|
|
|
134
143
|
level,
|
|
135
144
|
pct: top.usedPct,
|
|
136
145
|
key: top.key,
|
|
146
|
+
resetsAt: typeof top.resetsAt === 'number' && Number.isFinite(top.resetsAt) && top.resetsAt > 0 ? top.resetsAt : null,
|
|
137
147
|
source: top.key === 'litellm_budget' ? 'litellm' : 'subscription',
|
|
138
148
|
};
|
|
139
149
|
}
|
package/src/codex/delegation.js
CHANGED
|
@@ -5,7 +5,8 @@ import { parse } from 'smol-toml';
|
|
|
5
5
|
import { userDataDir } from '../paths.js';
|
|
6
6
|
import { writeViaTmp } from '../state-file.js';
|
|
7
7
|
import { codexUserDir, codexProviderName } from '../agent.js';
|
|
8
|
-
import { categorize, ESCALATE_RE, EDIT_RE } from '../route-scan.js';
|
|
8
|
+
import { categorize, ESCALATE_RE, JUDGE_RE, EDIT_RE } from '../route-scan.js';
|
|
9
|
+
import { delegationGrade, normalizeDelegationGrade, gradeKeepsRule } from '../routing-switch.js';
|
|
9
10
|
import { looksPasted, isSystemPrompt, isOpinionQuestion, looksLikeContextOrSpec } from '../route-inject.js';
|
|
10
11
|
import { newRouteId, recordCodexDelegation } from './ledger.js';
|
|
11
12
|
import { readCodexTailLines } from './parser.js';
|
|
@@ -223,22 +224,32 @@ export function removeCodexModelRule(index, { dir = userDataDir() } = {}) {
|
|
|
223
224
|
* The category a prompt can be routed under at runtime, or null. The route
|
|
224
225
|
* scan counts episodes with this same gate, so a rule it proposes is one the
|
|
225
226
|
* prompt hook can actually match.
|
|
227
|
+
*
|
|
228
|
+
* The gate follows the delegation grade like the Claude Code hint does:
|
|
229
|
+
* at grade 'quality' a JUDGE_RE request (audit, recommendation, absence check,
|
|
230
|
+
* research) is kept off the delegation path too.
|
|
231
|
+
*
|
|
232
|
+
* Not ported: the recommendation to move a Sonnet session up to Opus
|
|
233
|
+
* (escalationNotice in route-inject.js). Codex names its models differently
|
|
234
|
+
* and the Lab measurement behind the advice was run on Claude models, so there
|
|
235
|
+
* is nothing to say there yet.
|
|
226
236
|
*/
|
|
227
|
-
export function codexPromptCategory(text) {
|
|
237
|
+
export function codexPromptCategory(text, { grade = delegationGrade() } = {}) {
|
|
228
238
|
const prompt = typeof text === 'string' ? text.trim() : '';
|
|
229
239
|
// Same two gates as the Claude Code hint (routeMatch): a harness message is
|
|
230
240
|
// not a request, and an opinion question is judgement rather than a lookup.
|
|
231
241
|
if (isSystemPrompt(prompt) || isOpinionQuestion(prompt)) return null;
|
|
232
242
|
// The #16 gates: a reply, feedback, an outward action, an edit or a long spec.
|
|
233
243
|
if (looksLikeContextOrSpec(prompt)) return null;
|
|
244
|
+
if ((normalizeDelegationGrade(grade) ?? 'quality') === 'quality' && JUDGE_RE.test(prompt)) return null;
|
|
234
245
|
if (prompt.length < 8 || ESCALATE_RE.test(prompt) || EDIT_RE.test(prompt) || /\b(?:implement|modify|fix|delete|push|commit)\b/i.test(prompt)) return null;
|
|
235
246
|
const category = categorize(prompt, null);
|
|
236
247
|
if (!category || (category.id === 'paste' && !looksPasted(prompt))) return null;
|
|
237
248
|
return category;
|
|
238
249
|
}
|
|
239
250
|
|
|
240
|
-
export function matchCodexModelRule(text, { model, root, provider = codexProviderName(), rules = loadCodexModelRules() } = {}) {
|
|
241
|
-
const category = codexPromptCategory(text);
|
|
251
|
+
export function matchCodexModelRule(text, { model, root, provider = codexProviderName(), rules = loadCodexModelRules(), grade } = {}) {
|
|
252
|
+
const category = codexPromptCategory(text, { grade });
|
|
242
253
|
if (!category) return null;
|
|
243
254
|
const usable = rules.filter((r) => r?.status === 'active' && r.category === category.id && r.from === model &&
|
|
244
255
|
(!r.provider || r.provider === provider) &&
|
|
@@ -250,9 +261,12 @@ export function matchCodexModelRule(text, { model, root, provider = codexProvide
|
|
|
250
261
|
function matchingRoutes(text, opts) {
|
|
251
262
|
const own = matchCodexModelRule(text, { ...opts, rules: opts.rules ?? loadCodexModelRules({ dir: opts.dir }) });
|
|
252
263
|
if (own) return [own];
|
|
253
|
-
const category = codexPromptCategory(text);
|
|
264
|
+
const category = codexPromptCategory(text, { grade: opts.grade });
|
|
254
265
|
if (!category) return [];
|
|
255
|
-
|
|
266
|
+
// Grade 'quality' drops the T2 policies of every category but paste, read
|
|
267
|
+
// and translate, as the Claude Code hint does (gradeKeepsRule).
|
|
268
|
+
const grade = normalizeDelegationGrade(opts.grade) ?? delegationGrade();
|
|
269
|
+
return sharedCodexModelRules(opts).filter((r) => r.category === category.id && gradeKeepsRule(grade, r))
|
|
256
270
|
.sort((a, b) => SHARED_RULE_TIERS.indexOf(a.tier) - SHARED_RULE_TIERS.indexOf(b.tier));
|
|
257
271
|
}
|
|
258
272
|
|
|
@@ -338,7 +352,9 @@ export function codexRouteHint(payload, opts = {}) {
|
|
|
338
352
|
// user's real config by accident.
|
|
339
353
|
const cfg = opts.cfg ?? {};
|
|
340
354
|
const provider = payload?.model_provider || codexProviderName();
|
|
341
|
-
|
|
355
|
+
// The grade comes from that same config, so the gate and the config the hook
|
|
356
|
+
// loaded cannot disagree; a caller may still pass `grade` itself.
|
|
357
|
+
const routes = matchingRoutes(payload?.prompt, { cfg, provider, grade: delegationGrade(cfg), ...opts, model: payload?.model,
|
|
342
358
|
root: opts.root || payload?.cwd, start: payload?.cwd });
|
|
343
359
|
const rule = routes[0];
|
|
344
360
|
if (!rule) return null;
|
|
@@ -414,7 +430,7 @@ export function codexDelegationTool(payload, { cfg = {}, root = payload?.cwd ||
|
|
|
414
430
|
let rules = given;
|
|
415
431
|
if (!rules) { try { rules = loadCodexModelRules({ dir }); } catch { rules = []; } }
|
|
416
432
|
const provider = payload.model_provider || codexProviderName({ home });
|
|
417
|
-
const routes = explicit ? [] : matchingRoutes(input.message, { model: payload.model, provider, root, start: payload.cwd, rules, cfg, dir, home });
|
|
433
|
+
const routes = explicit ? [] : matchingRoutes(input.message, { model: payload.model, provider, root, start: payload.cwd, rules, cfg, dir, home, grade: delegationGrade(cfg) });
|
|
418
434
|
// Only the caller can choose a shared policy's tier. A shared match without a
|
|
419
435
|
// model goes back to the caller with the mapped choices instead of a guessed
|
|
420
436
|
// downgrade, or a default target that ignores the tier.
|
package/src/codex/route-scan.js
CHANGED
|
@@ -12,6 +12,7 @@ import { codexPromptCategory, loadCodexModelRules, sharedCodexModelRules, codexS
|
|
|
12
12
|
import { codexRunCost, codexPriceBook, isDirectOpenAI, readCodexPrices } from './cache-policy.js';
|
|
13
13
|
import { OPENAI_PRICES_CHECKED_AT } from '../openai-prices.js';
|
|
14
14
|
import { refreshCodexLedger } from './ledger.js';
|
|
15
|
+
import { safeExcerpt } from '../redact.js';
|
|
15
16
|
|
|
16
17
|
/*
|
|
17
18
|
* Codex route-scan: recurring easy turns become delegation-rule candidates.
|
|
@@ -172,7 +173,7 @@ export async function runCodexRouteScan({ days = 14, now = Date.now(), home, dir
|
|
|
172
173
|
.sort((a, b) => b.count - a.count || b.lastSeen - a.lastSeen)
|
|
173
174
|
.slice(0, MAX_CANDIDATES)
|
|
174
175
|
.map((g, i) => ({ id: i + 1, signature: g.signature, category: g.category, label: g.label, labelEn: g.labelEn,
|
|
175
|
-
from: g.from, provider: g.provider, projectRoot: g.projectRoot, count: g.count, tiers: g.tiers, example: g.example
|
|
176
|
+
from: g.from, provider: g.provider, projectRoot: g.projectRoot, count: g.count, tiers: g.tiers, example: safeExcerpt(g.example, 160), // masked before the cut, so no half-token survives
|
|
176
177
|
lastSeen: g.lastSeen || null, suggestedScope: 'project', ...pickTarget(g, { prices, known, home }) }));
|
|
177
178
|
const priceCheckedAt = prices?.checkedAt ?? ([...groups.values()].some((g) => isDirectOpenAI(g.provider, { home })) ? OPENAI_PRICES_CHECKED_AT : null);
|
|
178
179
|
const data = { version: 1, scannedAt: new Date(now).toISOString(), days, dataBytes, totalEpisodes: episodes.length,
|
package/src/commands/brief.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
import { readStdinJson } from '../stdin-payload.js';
|
|
19
19
|
import { debug } from '../debug.js';
|
|
20
|
-
import { routingEnabled } from '../routing-switch.js';
|
|
20
|
+
import { routingEnabled, delegationGrade, isRelaxed } from '../routing-switch.js';
|
|
21
21
|
|
|
22
22
|
export async function run({ hasFlag }) {
|
|
23
23
|
if (hasFlag('--hook-tool')) {
|
|
@@ -67,7 +67,7 @@ export async function run({ hasFlag }) {
|
|
|
67
67
|
} catch (e) { debug('brief:routing-off', e); }
|
|
68
68
|
}
|
|
69
69
|
if (routingOn) try {
|
|
70
|
-
const { routeHint, routeMatch, matchCaps, sessionModelRank, hintTarget, hintLabel } = await import('../route-inject.js');
|
|
70
|
+
const { routeHint, routeMatch, matchCaps, sessionModelRank, hintTarget, hintLabel, escalationNotice } = await import('../route-inject.js');
|
|
71
71
|
// The payload names the session but not its model, so the rank comes from
|
|
72
72
|
// the transcript: without it a Sonnet session is told to delegate to
|
|
73
73
|
// Sonnet, which saves nothing.
|
|
@@ -79,7 +79,8 @@ export async function run({ hasFlag }) {
|
|
|
79
79
|
// differ. Claude Code sends `cwd` for that reason and the PreToolUse hook
|
|
80
80
|
// already reads it (src/delegation-guard.js). A payload without the field
|
|
81
81
|
// leaves root undefined, which is the behaviour this had before.
|
|
82
|
-
const
|
|
82
|
+
const grade = delegationGrade();
|
|
83
|
+
const match = routeMatch(ctx.prompt, { sessionRank, root: ctx.cwd, grade });
|
|
83
84
|
// How near the usage limit is, from the statusline snapshot. Read only when
|
|
84
85
|
// a hint will be written, and only the file: no network in a prompt hook.
|
|
85
86
|
let pressure = null;
|
|
@@ -88,10 +89,51 @@ export async function run({ hasFlag }) {
|
|
|
88
89
|
const { capPressure } = await import('../caps-cache.js');
|
|
89
90
|
const { getSessionModel } = await import('../parser.js');
|
|
90
91
|
pressure = capPressure({ sessionModel: getSessionModel(ctx.transcript_path) });
|
|
92
|
+
// High usage while delegation is not widened: the hint offers
|
|
93
|
+
// `sprag routing relax` once per limit window instead of the plain
|
|
94
|
+
// pressure line. Relaxed, or already offered for this window, the
|
|
95
|
+
// plain line stays.
|
|
96
|
+
if (pressure && (pressure.level === 'high' || pressure.level === 'critical') && (match.t2 || match.t1 || match.t1h) && !isRelaxed()) {
|
|
97
|
+
const { claimRelaxOffer } = await import('../relax-offer.js');
|
|
98
|
+
if (claimRelaxOffer(pressure.resetsAt)) pressure = { ...pressure, offer: true };
|
|
99
|
+
}
|
|
91
100
|
} catch (e) { debug('brief:cap-pressure', e); }
|
|
92
101
|
}
|
|
93
102
|
const hint = routeHint(ctx.prompt, { sessionRank, root: ctx.cwd, match, pressure });
|
|
94
103
|
if (hint) parts.push(hint);
|
|
104
|
+
// A request that ends in a judgement gets no delegation hint (routeMatch is
|
|
105
|
+
// null for it). In a session below Opus it gets the recommendation to move
|
|
106
|
+
// up instead; the grade decides which requests count (escalationNotice).
|
|
107
|
+
// Once per session: the second judgement request of a session gets no
|
|
108
|
+
// line, since the first one already said it (claimEscalationNotice).
|
|
109
|
+
let escalationSaid = false;
|
|
110
|
+
if (!match) {
|
|
111
|
+
try {
|
|
112
|
+
const notice = escalationNotice(ctx.prompt, { sessionRank, grade });
|
|
113
|
+
if (notice) {
|
|
114
|
+
const { claimEscalationNotice } = await import('../route-follow.js');
|
|
115
|
+
if (claimEscalationNotice(ctx.session_id)) { parts.push(notice); escalationSaid = true; }
|
|
116
|
+
}
|
|
117
|
+
} catch (e) { debug('brief:escalation-notice', e); }
|
|
118
|
+
}
|
|
119
|
+
// A main session at effort low or medium gets the effort line for the same
|
|
120
|
+
// kind of request. The model line goes first: when the Sonnet session was
|
|
121
|
+
// just told to move up to Opus, this turn carries that line alone (the
|
|
122
|
+
// effort claim stays free for a later turn).
|
|
123
|
+
if (!match && !escalationSaid) {
|
|
124
|
+
try {
|
|
125
|
+
const { effortHintEnabled } = await import('../routing-switch.js');
|
|
126
|
+
if (effortHintEnabled()) {
|
|
127
|
+
const { effortNotice } = await import('../route-inject.js');
|
|
128
|
+
const { readSessionEffort } = await import('../session-effort.js');
|
|
129
|
+
const notice = effortNotice(ctx.prompt, { sessionEffort: readSessionEffort(ctx.session_id), grade });
|
|
130
|
+
if (notice) {
|
|
131
|
+
const { claimEffortNotice } = await import('../route-follow.js');
|
|
132
|
+
if (claimEffortNotice(ctx.session_id)) parts.push(notice);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} catch (e) { debug('brief:effort-notice', e); }
|
|
136
|
+
}
|
|
95
137
|
// Remember that this turn carried a delegation hint, so the PostToolUse
|
|
96
138
|
// hook can nudge when the model looks things up itself instead. The
|
|
97
139
|
// unreachable-only notice tells the model NOT to delegate, so it starts
|
package/src/commands/doc2md.js
CHANGED
|
@@ -55,6 +55,13 @@ export async function run({ args, hasFlag }) {
|
|
|
55
55
|
return;
|
|
56
56
|
}
|
|
57
57
|
if (out) console.log(out);
|
|
58
|
+
// After the answer is out: a converted copy keeps the document's whole text,
|
|
59
|
+
// so copies untouched for 30 days are removed, at most once a day.
|
|
60
|
+
try {
|
|
61
|
+
const { runHousekeeping } = await import('../state-file.js');
|
|
62
|
+
const { userDataDir } = await import('../paths.js');
|
|
63
|
+
runHousekeeping(userDataDir(), { 'doc2md-cache': () => doc2md.pruneCache() });
|
|
64
|
+
} catch { /* clean-up is best effort and never touches the Read */ }
|
|
58
65
|
return;
|
|
59
66
|
}
|
|
60
67
|
|
|
@@ -390,6 +390,19 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
390
390
|
if (doc2mdHookRegistered()) doc2mdBlock = require('../doc2md.cjs').sessionNote(lang);
|
|
391
391
|
} catch (e) { debug('route-scan:doc2md-note', e); /* the note is optional */ }
|
|
392
392
|
|
|
393
|
+
// Secrets that "don't ask again" saved in an approval list. One line per
|
|
394
|
+
// settings file, once per modification time (see permission-secrets.js);
|
|
395
|
+
// `sprag secrets off` switches it off.
|
|
396
|
+
let secretsBlock = null;
|
|
397
|
+
try {
|
|
398
|
+
const { loadConfig } = await import('../config.js');
|
|
399
|
+
if (loadConfig().secretScan !== false) {
|
|
400
|
+
const { secretsNotice } = await import('../permission-secrets.js');
|
|
401
|
+
const { findProjectRoot } = await import('../harness.js');
|
|
402
|
+
secretsBlock = secretsNotice({ root: findProjectRoot(hookCtx.cwd || process.cwd()), lang });
|
|
403
|
+
}
|
|
404
|
+
} catch (e) { debug('route-scan:secrets-notice', e); /* the notice is optional */ }
|
|
405
|
+
|
|
393
406
|
// Starter rules that the user has not answered yet (bundled presets, both
|
|
394
407
|
// model-fitting and ratchet). A fresh install has an empty model ratchet
|
|
395
408
|
// and an empty ratchet.md, so without this the tool delegates nothing
|
|
@@ -430,6 +443,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
430
443
|
} catch (e) { debug('route-scan:monthly-reset', e); /* the offer is optional */ }
|
|
431
444
|
|
|
432
445
|
if (open.length === 0 && reviewRules.length === 0) {
|
|
446
|
+
if (secretsBlock) console.log(secretsBlock);
|
|
433
447
|
if (teamBlock) console.log(teamBlock);
|
|
434
448
|
if (updateBlock) console.log(updateBlock);
|
|
435
449
|
if (monthlyResetBlock) console.log(monthlyResetBlock);
|
|
@@ -440,6 +454,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
440
454
|
if (cohesionBlock) console.log(cohesionBlock);
|
|
441
455
|
return; // nothing else to inject
|
|
442
456
|
}
|
|
457
|
+
if (secretsBlock) console.log(secretsBlock);
|
|
443
458
|
if (teamBlock) console.log(teamBlock);
|
|
444
459
|
if (updateBlock) console.log(updateBlock);
|
|
445
460
|
if (monthlyResetBlock) console.log(monthlyResetBlock);
|
package/src/commands/routing.js
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* sprag routing # status
|
|
5
5
|
* sprag routing on|off # turn every delegation path on or off
|
|
6
|
+
* sprag routing relax [off] # widen delegation until the busiest usage window resets, or end that early
|
|
7
|
+
* sprag routing effort-hint on|off # the effort line for low/medium sessions on judgement requests
|
|
6
8
|
*
|
|
7
9
|
* Off removes the delegation rules from ratchet-model.md and the preset
|
|
8
10
|
* ratchet, the per-prompt route hint, and the route-scan candidate and
|
|
@@ -13,7 +15,21 @@ export async function run({ args }) {
|
|
|
13
15
|
const sub = args[1];
|
|
14
16
|
const { userLanguage } = await import('../config.js');
|
|
15
17
|
const ko = userLanguage() === 'ko';
|
|
16
|
-
const { routingEnabled, setRoutingEnabled } = await import('../routing-switch.js');
|
|
18
|
+
const { routingEnabled, setRoutingEnabled, isRelaxed, relaxUntil, setRelaxUntil, relaxClock, effortHintEnabled, setEffortHint } = await import('../routing-switch.js');
|
|
19
|
+
|
|
20
|
+
// The reset of the busiest usage window in the statusline snapshot, in epoch
|
|
21
|
+
// ms; five hours from now when the snapshot is missing, stale or has no reset.
|
|
22
|
+
const relaxDeadline = async () => {
|
|
23
|
+
const fallback = Date.now() + 5 * 60 * 60 * 1000;
|
|
24
|
+
try {
|
|
25
|
+
const { capPressure } = await import('../caps-cache.js');
|
|
26
|
+
const p = capPressure();
|
|
27
|
+
const ms = p && p.resetsAt ? p.resetsAt * 1000 : null;
|
|
28
|
+
return ms !== null && ms > Date.now() ? ms : fallback;
|
|
29
|
+
} catch {
|
|
30
|
+
return fallback;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
17
33
|
|
|
18
34
|
const rules = async () => (await import('../model-rules.js')).loadModelRules().rules.length;
|
|
19
35
|
// Re-render the files that carry delegation text so the change shows without
|
|
@@ -53,12 +69,51 @@ export async function run({ args }) {
|
|
|
53
69
|
return;
|
|
54
70
|
}
|
|
55
71
|
|
|
72
|
+
if (sub === 'relax') {
|
|
73
|
+
const want = args[2];
|
|
74
|
+
if (want !== undefined && want !== 'off') {
|
|
75
|
+
console.error('Usage: sprag routing relax [off]');
|
|
76
|
+
process.exitCode = 2;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (want === 'off') {
|
|
80
|
+
setRelaxUntil(null);
|
|
81
|
+
await resync();
|
|
82
|
+
console.log(ko ? '✓ 위임 범위를 원래대로 돌렸습니다.' : '✓ Delegation is back to its usual range.');
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const until = await relaxDeadline();
|
|
86
|
+
setRelaxUntil(until);
|
|
87
|
+
await resync();
|
|
88
|
+
const clock = relaxClock(until);
|
|
89
|
+
console.log(ko
|
|
90
|
+
? `이번 한도 창이 끝나는 ${clock}까지 위임을 넓힙니다. 그 뒤에는 자동으로 돌아옵니다.`
|
|
91
|
+
: `Delegation is widened until ${clock}, when this limit window ends. It switches back by itself after that.`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (sub === 'effort-hint') {
|
|
96
|
+
const want = args[2];
|
|
97
|
+
if (want !== 'on' && want !== 'off') {
|
|
98
|
+
console.error('Usage: sprag routing effort-hint on|off');
|
|
99
|
+
process.exitCode = 2;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
setEffortHint(want === 'on');
|
|
103
|
+
console.log(want === 'on'
|
|
104
|
+
? (ko ? '✓ effort 안내를 켰습니다. 판단형 요청에서 세션 effort가 low나 medium이면 한 번 안내합니다.' : '✓ Effort hint is on. A low or medium effort session is told once on a judgement request.')
|
|
105
|
+
: (ko ? '✓ effort 안내를 껐습니다.' : '✓ Effort hint is off.'));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
56
109
|
if (sub === undefined || sub === 'status') {
|
|
57
110
|
const on = routingEnabled();
|
|
58
111
|
const n = await rules().catch(() => 0);
|
|
59
112
|
let agentsOn = true;
|
|
60
113
|
try { agentsOn = (await import('../delegation-agents.js')).delegationAgentStatus().enabled; } catch { /* default on */ }
|
|
61
114
|
console.log(`routing: ${on ? 'on' : 'off'}`);
|
|
115
|
+
console.log(isRelaxed() ? `relax: until ${relaxClock(relaxUntil())}` : 'relax: off');
|
|
116
|
+
console.log(`effort hint: ${effortHintEnabled() ? 'on' : 'off'}`);
|
|
62
117
|
console.log(ko ? `등록된 룰: ${n}건` : `registered rules: ${n}`);
|
|
63
118
|
console.log(`delegate agents: ${agentsOn ? 'on' : 'off'}`);
|
|
64
119
|
console.log(ko
|
|
@@ -67,6 +122,6 @@ export async function run({ args }) {
|
|
|
67
122
|
return;
|
|
68
123
|
}
|
|
69
124
|
|
|
70
|
-
console.log('Usage: sprag routing on|off|status');
|
|
125
|
+
console.log('Usage: sprag routing on|off|status|relax [off]|effort-hint on|off');
|
|
71
126
|
process.exitCode = 1;
|
|
72
127
|
}
|