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/src/redact.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* redact — the one place that masks secrets and personal data.
|
|
3
|
+
*
|
|
4
|
+
* Two callers need the same answer to "does this text hold a secret": the
|
|
5
|
+
* Enterprise prompt uploader (team-prompts.js, masks right before upload) and
|
|
6
|
+
* every place sprag writes a user's words into a local file (the rule examples
|
|
7
|
+
* in model-rules.json and ratchet-model.md, the candidates route-scan caches).
|
|
8
|
+
* Claude Code's "don't ask again" has stored approved commands, passwords
|
|
9
|
+
* included, in .claude/settings.local.json and pushed them to public GitHub
|
|
10
|
+
* (Apiiro, 2026-11-05), so a local file is not private just because it is
|
|
11
|
+
* local. permission-secrets.js reuses findSecrets for the approval lists.
|
|
12
|
+
*
|
|
13
|
+
* Every secret shape is one entry in SECRET_RULES, and findSecrets,
|
|
14
|
+
* redactSecrets and maskPreview all read that table, so they cannot disagree.
|
|
15
|
+
* Conservative on purpose: over-masking a look-alike is fine, leaving a real
|
|
16
|
+
* token is not. Prose such as "token budget is 8000" must stay untouched.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const REDACTED = '[redacted]';
|
|
20
|
+
|
|
21
|
+
const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gd;
|
|
22
|
+
// key block cut off by the end of the text (a prompt, or an 80-char excerpt)
|
|
23
|
+
const PRIVATE_KEY_CUT = /-----BEGIN [A-Z ]*PRIVATE KEY-----(?![\s\S]*-----END [A-Z ]*PRIVATE KEY-----)[\s\S]*$/gd;
|
|
24
|
+
|
|
25
|
+
const FLAG_NAME = '--[a-z0-9-]*?(?:password|passwd|passphrase|pwd|token|secret|api-?key)';
|
|
26
|
+
// A value that is only a word cannot be told from prose ("--token budget"): demand a digit or symbol and 6+ chars.
|
|
27
|
+
const looksLikeValue = (v) => {
|
|
28
|
+
const bare = v.replace(/^["']|["']$/g, '');
|
|
29
|
+
return bare.length >= 6 && /[^A-Za-z]/.test(bare) && !/^[$<{-]/.test(bare);
|
|
30
|
+
};
|
|
31
|
+
const notReference = (v) => !/^["']?[$<{-]/.test(v) && v !== REDACTED;
|
|
32
|
+
|
|
33
|
+
/** @type {{kind: string, re: RegExp, group?: number, ok?: (value: string, match: RegExpExecArray) => boolean}[]} */
|
|
34
|
+
const SECRET_RULES = [
|
|
35
|
+
{ kind: 'private-key', re: PRIVATE_KEY_BLOCK },
|
|
36
|
+
{ kind: 'private-key', re: PRIVATE_KEY_CUT },
|
|
37
|
+
{ kind: 'anthropic-key', re: /\bsk-ant-[A-Za-z0-9_-]{16,}/gd },
|
|
38
|
+
{ kind: 'api-key', re: /\bsk-[A-Za-z0-9_-]{20,}/gd },
|
|
39
|
+
{ kind: 'github-token', re: /\bgh[pousr]_[A-Za-z0-9]{20,}/gd },
|
|
40
|
+
{ kind: 'github-token', re: /\bgithub_pat_[A-Za-z0-9_]{20,}/gd },
|
|
41
|
+
{ kind: 'gitlab-token', re: /\bglpat-[A-Za-z0-9_-]{20,}/gd },
|
|
42
|
+
{ kind: 'aws-key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/gd },
|
|
43
|
+
{ kind: 'slack-token', re: /\bxox[abpr]-[A-Za-z0-9-]{10,}/gd },
|
|
44
|
+
{ kind: 'slack-token', re: /\bxapp-\d-[A-Za-z0-9-]{10,}/gd },
|
|
45
|
+
{ kind: 'npm-token', re: /\bnpm_[A-Za-z0-9]{30,}/gd },
|
|
46
|
+
{ kind: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{35}/gd },
|
|
47
|
+
{ kind: 'google-refresh-token', re: /(?<![\w/])1\/\/[0-9A-Za-z_-]{40,}/gd },
|
|
48
|
+
{ kind: 'google-access-token', re: /\bya29\.[A-Za-z0-9_-]{30,}/gd },
|
|
49
|
+
{ kind: 'google-client-secret', re: /\bGOCSPX-[A-Za-z0-9_-]{20,}/gd },
|
|
50
|
+
{ kind: 'stripe-key', re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/gd },
|
|
51
|
+
{ kind: 'huggingface-token', re: /\bhf_[A-Za-z0-9]{30,}/gd },
|
|
52
|
+
{ kind: 'pypi-token', re: /\bpypi-AgEI[A-Za-z0-9_-]{20,}/gd },
|
|
53
|
+
{ kind: 'supabase-token', re: /\bsbp_[a-f0-9]{40}\b/gd },
|
|
54
|
+
{ kind: 'sendgrid-key', re: /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/gd },
|
|
55
|
+
{ kind: 'shopify-token', re: /\bshp(?:at|ss|ca|pa)_[a-f0-9]{32}\b/gd },
|
|
56
|
+
{ kind: 'jwt', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/gd },
|
|
57
|
+
// Authorization headers
|
|
58
|
+
{ kind: 'bearer', re: /\bBearer\s+([A-Za-z0-9._~+/=-]{16,})/gid, group: 1 },
|
|
59
|
+
{ kind: 'basic-auth', re: /\bBasic\s+([A-Za-z0-9+/]{12,}={0,2})(?![\w+/])/gd, group: 1, ok: (v) => /[0-9+/=]/.test(v) },
|
|
60
|
+
// scheme://user:password@host (a $VAR or <placeholder> password is not a secret)
|
|
61
|
+
{ kind: 'url-credentials', re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/?#'"]+:([^\s@/?#'"]+)@/gd, group: 1, ok: (v) => !/^[$<{]/.test(v) },
|
|
62
|
+
// curl -u user:password
|
|
63
|
+
{ kind: 'basic-auth', re: /\bcurl\b[^\n|;&]*?\s(?:-u|--user)\s+['"]?[^\s:'"]+:([^\s'"]+)/gd, group: 1, ok: (v) => !/^[$<{]/.test(v) },
|
|
64
|
+
// --password=value, --api-key=value, --refresh-token=value
|
|
65
|
+
{ kind: 'cli-flag', re: new RegExp(`(?<![\\w-])${FLAG_NAME}=("[^"\\n]*"|'[^'\\n]*'|[^\\s"']+)`, 'gid'), group: 1, ok: notReference },
|
|
66
|
+
// --password value (separated by space)
|
|
67
|
+
{ kind: 'cli-flag', re: new RegExp(`(?<![\\w-])${FLAG_NAME}[ \\t]+("[^"\\n]*"|'[^'\\n]*'|[^\\s"']+)`, 'gid'), group: 1, ok: looksLikeValue },
|
|
68
|
+
// NAME_KEY=value, PGPASSWORD=value, apiToken = "value" (not --max-tokens=1024)
|
|
69
|
+
{
|
|
70
|
+
kind: 'env-assignment',
|
|
71
|
+
re: /(?<![\w-])[A-Za-z0-9_]*(?:KEY|TOKEN|PASSWORD|PASSWD|SECRET|CREDENTIALS?)[A-Za-z0-9_]*\s*=(?![=>])\s*("[^"\n]*"|'[^'\n]*'|[^\s"']+)/gid,
|
|
72
|
+
group: 1,
|
|
73
|
+
ok: (v) => notReference(v) && v.replace(/^["']|["']$/g, '') !== '',
|
|
74
|
+
},
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
function* matchSpans(text) {
|
|
78
|
+
for (const { kind, re, group = 0, ok } of SECRET_RULES) {
|
|
79
|
+
re.lastIndex = 0;
|
|
80
|
+
let m;
|
|
81
|
+
while ((m = re.exec(text)) !== null) {
|
|
82
|
+
if (m[0] === '') { re.lastIndex += 1; continue; }
|
|
83
|
+
const idx = m.indices[group];
|
|
84
|
+
if (idx && (!ok || ok(m[group] ?? '', m))) yield { kind, start: idx[0], end: idx[1] };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Where secrets sit in `text`: [{ kind, start, end }], sorted, overlaps merged
|
|
91
|
+
* (the first kind found wins). The value itself is never returned, so a caller
|
|
92
|
+
* can print or log the result without leaking it.
|
|
93
|
+
*/
|
|
94
|
+
export function findSecrets(text) {
|
|
95
|
+
const s = String(text ?? '');
|
|
96
|
+
const spans = [...matchSpans(s)].sort((a, b) => a.start - b.start || b.end - a.end);
|
|
97
|
+
const merged = [];
|
|
98
|
+
for (const sp of spans) {
|
|
99
|
+
const last = merged[merged.length - 1];
|
|
100
|
+
if (last && sp.start <= last.end) { last.end = Math.max(last.end, sp.end); continue; }
|
|
101
|
+
merged.push({ ...sp });
|
|
102
|
+
}
|
|
103
|
+
return merged;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Replace obvious secrets with "[redacted]". Conservative: it may over-redact, never under-redact these shapes. */
|
|
107
|
+
export function redactSecrets(text) {
|
|
108
|
+
const s = String(text ?? '');
|
|
109
|
+
const spans = findSecrets(s);
|
|
110
|
+
if (!spans.length) return s;
|
|
111
|
+
let out = '';
|
|
112
|
+
let at = 0;
|
|
113
|
+
for (const { start, end } of spans) {
|
|
114
|
+
out += s.slice(at, start) + REDACTED;
|
|
115
|
+
at = end;
|
|
116
|
+
}
|
|
117
|
+
return out + s.slice(at);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A preview that is safe to print: secrets become "[redacted]", then the text
|
|
122
|
+
* is cut to `max` characters. Masking comes first so a cut never leaves half a token.
|
|
123
|
+
*/
|
|
124
|
+
export function maskPreview(text, max = Infinity) {
|
|
125
|
+
const one = redactSecrets(text).replace(/\s+/g, ' ').trim();
|
|
126
|
+
return one.length <= max ? one : `${one.slice(0, Math.max(0, max - 1))}…`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** An example excerpt for a rule file: personal data and secrets masked first, then cut to `max` characters. */
|
|
130
|
+
export function safeExcerpt(text, max = 80) {
|
|
131
|
+
const masked = redactSecrets(redactPersonal(text)).replace(/\s+/g, ' ');
|
|
132
|
+
return masked.slice(0, max);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
// Personal data (PII) redaction. Typed markers: [redacted:email] [redacted:phone] [redacted:rrn] [redacted:card].
|
|
137
|
+
// Tuned for coding prompts: a miss is acceptable, a mangled code snippet is not.
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
const MARK_EMAIL = '[redacted:email]';
|
|
141
|
+
const MARK_PHONE = '[redacted:phone]';
|
|
142
|
+
const MARK_RRN = '[redacted:rrn]';
|
|
143
|
+
const MARK_CARD = '[redacted:card]';
|
|
144
|
+
|
|
145
|
+
// local@a.b.tld: dotted domain, TLD of 2+ letters. `react@18.3.1` has no letter TLD; the `git@github.com` SSH remote user is skipped in the callback.
|
|
146
|
+
const EMAIL_RE = /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)\.[A-Za-z]{2,}(?![A-Za-z0-9-])/g;
|
|
147
|
+
// asset names such as logo@2x.png and a version with a prerelease tag such as react@18.3.1-beta.abc are not addresses
|
|
148
|
+
const looksLikeAssetOrVersion = (domain) => { const first = domain.split('.')[0]; return !/[A-Za-z]/.test(first) || /^\d+x$/i.test(first); };
|
|
149
|
+
|
|
150
|
+
const PHONE_RES = [
|
|
151
|
+
// mobile: 010 / 011 / 016 / 017 / 018 / 019, separators optional
|
|
152
|
+
/(?<![\w.])01[016789][-. ]?\d{3,4}[-. ]?\d{4}(?!\w)/g,
|
|
153
|
+
// international form of a mobile number: +82 10 ..., +82-10-..., +82 (0)10 ...
|
|
154
|
+
/(?<![\w])\+82[-. ]?(?:\(0\)[-. ]?)?10[-. ]?\d{3,4}[-. ]?\d{4}(?!\w)/g,
|
|
155
|
+
// landline and 070: area code only when joined by hyphens, so plain digit runs stay untouched
|
|
156
|
+
/(?<![\w-])0(?:[2-6][0-9]?|70)-\d{3,4}-\d{4}(?![\w-])/g,
|
|
157
|
+
];
|
|
158
|
+
|
|
159
|
+
// YYMMDD-GXXXXXX, G is 1-8 (birth century and sex, foreigners 5-8); month and day are range-checked below
|
|
160
|
+
const RRN_RE = /(?<![\w-])(\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])[- ][1-8]\d{6}(?!\w)/g;
|
|
161
|
+
|
|
162
|
+
// grouped (4-4-4-4, 4-4-4-4-3, 4-6-5) or contiguous 15-16 digits
|
|
163
|
+
const CARD_RE = /(?<![\w-])(?:\d{4}([ -])\d{4}\1\d{4}\1\d{4}(?:\1\d{3})?|\d{4}([ -])\d{6}\2\d{5}|\d{15,16})(?![\w-])/g;
|
|
164
|
+
const CARD_IIN_RE = /^(?:4|5[1-5]|222[1-9]|22[3-9]\d|2[3-6]\d\d|27[01]\d|2720|3[457]|6011|65|9)/;
|
|
165
|
+
|
|
166
|
+
function luhnOk(digits) {
|
|
167
|
+
let sum = 0;
|
|
168
|
+
for (let i = digits.length - 1, dbl = false; i >= 0; i--, dbl = !dbl) {
|
|
169
|
+
let d = digits.charCodeAt(i) - 48;
|
|
170
|
+
if (dbl) { d *= 2; if (d > 9) d -= 9; }
|
|
171
|
+
sum += d;
|
|
172
|
+
}
|
|
173
|
+
return sum % 10 === 0;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Mask email addresses, Korean phone numbers, resident registration numbers and card numbers with typed markers. */
|
|
177
|
+
export function redactPersonal(text) {
|
|
178
|
+
let s = String(text ?? '');
|
|
179
|
+
s = s.replace(EMAIL_RE, (m, domain) => (/^git@/i.test(m) || looksLikeAssetOrVersion(domain) ? m : MARK_EMAIL));
|
|
180
|
+
s = s.replace(CARD_RE, (m) => {
|
|
181
|
+
const digits = m.replace(/\D/g, '');
|
|
182
|
+
if (digits.length < 13 || digits.length > 19 || !luhnOk(digits)) return m;
|
|
183
|
+
if (/^\d+$/.test(m) && !CARD_IIN_RE.test(digits)) return m; // contiguous digits need a real issuer prefix
|
|
184
|
+
return MARK_CARD;
|
|
185
|
+
});
|
|
186
|
+
s = s.replace(RRN_RE, MARK_RRN);
|
|
187
|
+
for (const re of PHONE_RES) s = s.replace(re, MARK_PHONE);
|
|
188
|
+
return s;
|
|
189
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The offer to widen delegation until the usage window resets.
|
|
3
|
+
*
|
|
4
|
+
* When a window runs high the prompt hook tells the model to ask the user once
|
|
5
|
+
* whether to run `sprag routing relax`. "Once" is counted per limit window, not
|
|
6
|
+
* per session: a new session in the same window has already been offered, and
|
|
7
|
+
* the window resetting is what makes a new offer possible. The last window
|
|
8
|
+
* offered, identified by its resetsAt (epoch seconds), is kept in a small file
|
|
9
|
+
* under the user data directory.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { userDataDir } from './paths.js';
|
|
15
|
+
import { writeStateFile } from './state-file.js';
|
|
16
|
+
|
|
17
|
+
const FILE = 'relax-offer.json';
|
|
18
|
+
/** resetsAt values this close count as the same window (the reading jitters by seconds). */
|
|
19
|
+
const SAME_WINDOW_S = 600;
|
|
20
|
+
/** A window with no reset time is bucketed by this span instead. */
|
|
21
|
+
const FALLBACK_BUCKET_S = 5 * 60 * 60;
|
|
22
|
+
|
|
23
|
+
/** The window id used for the claim: its resetsAt, or a 5 hour bucket when the window has none. */
|
|
24
|
+
export function offerWindowId(resetsAt, nowMs = Date.now()) {
|
|
25
|
+
if (typeof resetsAt === 'number' && Number.isFinite(resetsAt) && resetsAt > 0) return resetsAt;
|
|
26
|
+
return Math.floor(nowMs / 1000 / FALLBACK_BUCKET_S) * FALLBACK_BUCKET_S;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* True the first time a window is offered, false after. Never throws: when the
|
|
31
|
+
* state file cannot be written the offer is skipped, so a failing disk cannot
|
|
32
|
+
* turn it into a line on every prompt.
|
|
33
|
+
*
|
|
34
|
+
* @param {number|null} resetsAt epoch seconds of the busiest window's reset
|
|
35
|
+
* @param {{dir?: string, nowMs?: number}} [opts]
|
|
36
|
+
*/
|
|
37
|
+
export function claimRelaxOffer(resetsAt, { dir, nowMs = Date.now() } = {}) {
|
|
38
|
+
try {
|
|
39
|
+
const file = join(dir || userDataDir(), FILE);
|
|
40
|
+
const id = offerWindowId(resetsAt, nowMs);
|
|
41
|
+
let last = null;
|
|
42
|
+
try {
|
|
43
|
+
if (existsSync(file)) last = Number(JSON.parse(readFileSync(file, 'utf8'))?.resetsAt);
|
|
44
|
+
} catch { /* unreadable reads as never offered */ }
|
|
45
|
+
if (Number.isFinite(last) && Math.abs(last - id) <= SAME_WINDOW_S) return false;
|
|
46
|
+
writeStateFile(file, JSON.stringify({ resetsAt: id, offeredAt: nowMs }) + '\n');
|
|
47
|
+
return true;
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/route-follow.js
CHANGED
|
@@ -22,6 +22,9 @@
|
|
|
22
22
|
* <sid>.calls one appended line per counted call (`c` or `g`); an append of
|
|
23
23
|
* a single short line is atomic enough that no count is lost
|
|
24
24
|
* <sid>.stop the counting for this turn is over
|
|
25
|
+
* <sid>.escalated created with the `wx` flag the first time the session gets
|
|
26
|
+
* the "move up to Opus" recommendation (claimEscalationNotice);
|
|
27
|
+
* no turn start or clear removes it, so it holds for the session
|
|
25
28
|
* <sid>.nudged created with the `wx` flag, so of several processes that all
|
|
26
29
|
* see "two lookups" exactly one wins and speaks
|
|
27
30
|
* All of it lives under <dir>/route-follow/. Events go to a separate JSONL
|
|
@@ -125,6 +128,45 @@ export function startFollow(sessionId, { agent = 'claude', category, label, targ
|
|
|
125
128
|
return true;
|
|
126
129
|
}
|
|
127
130
|
|
|
131
|
+
/**
|
|
132
|
+
* Claim the one "move up to Opus" recommendation a session gets. True the first
|
|
133
|
+
* time for a session id, false after that, so the second judgement request of a
|
|
134
|
+
* session passes without the line. A missing or malformed id, or a state
|
|
135
|
+
* directory that cannot be written, also reads as false: no line is better than
|
|
136
|
+
* the same line on every prompt.
|
|
137
|
+
*/
|
|
138
|
+
export function claimEscalationNotice(sessionId, { dir } = {}) {
|
|
139
|
+
if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
|
|
140
|
+
try {
|
|
141
|
+
const d = stateDir(dir);
|
|
142
|
+
mkdirSync(d, { recursive: true });
|
|
143
|
+
closeSync(openSync(join(d, `${sessionId}.escalated`), 'wx'));
|
|
144
|
+
return true;
|
|
145
|
+
} catch (e) {
|
|
146
|
+
if (e?.code !== 'EEXIST') debug('route-follow:escalated', e);
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Claim the one "raise the main session's effort" line a session gets, the same
|
|
153
|
+
* way claimEscalationNotice claims the model one. The two claims are separate
|
|
154
|
+
* files, so a session that was told to move up to Opus can still be told about
|
|
155
|
+
* its effort later.
|
|
156
|
+
*/
|
|
157
|
+
export function claimEffortNotice(sessionId, { dir } = {}) {
|
|
158
|
+
if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
|
|
159
|
+
try {
|
|
160
|
+
const d = stateDir(dir);
|
|
161
|
+
mkdirSync(d, { recursive: true });
|
|
162
|
+
closeSync(openSync(join(d, `${sessionId}.effort`), 'wx'));
|
|
163
|
+
return true;
|
|
164
|
+
} catch (e) {
|
|
165
|
+
if (e?.code !== 'EEXIST') debug('route-follow:effort', e);
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
128
170
|
/** Forget the session's hinted turn: the prompt that just arrived has no hint. */
|
|
129
171
|
export function clearFollow(sessionId, { dir } = {}) {
|
|
130
172
|
if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
|
package/src/route-inject.js
CHANGED
|
@@ -38,13 +38,14 @@
|
|
|
38
38
|
* A hint that fires on the wrong request costs more than one that stays quiet.
|
|
39
39
|
*/
|
|
40
40
|
|
|
41
|
-
import { categorizeScored, ESCALATE_RE, EDIT_RE, worthDelegating } from './route-scan.js';
|
|
41
|
+
import { categorizeScored, ESCALATE_RE, JUDGE_RE, EDIT_RE, worthDelegating } from './route-scan.js';
|
|
42
|
+
import { delegationGrade, normalizeDelegationGrade, gradeKeepsRule } from './routing-switch.js';
|
|
42
43
|
import { loadModelRules, budgetCapPhrase, ruleBudget } from './model-rules.js';
|
|
43
44
|
import { sharedProjectRoots, realProjectRoot, scopeRank } from './shared-model-rules.js';
|
|
44
45
|
import { agentPhrase, agentPhraseEn, resolveAgentName, agentForRule, TIER_MODEL } from './agents.js';
|
|
45
46
|
import { userLanguage } from './config.js';
|
|
46
47
|
import { aliasForRole, resolveModelAlias } from './model-alias.js';
|
|
47
|
-
import { isRecognizedModelId, modelRank } from './cost.js';
|
|
48
|
+
import { isRecognizedModelId, modelRank, TIER_TARGET_RANK } from './cost.js';
|
|
48
49
|
import { loadRecentSnapshot } from './caps-cache.js';
|
|
49
50
|
import { getSessionModel } from './parser.js';
|
|
50
51
|
import { labelForKey } from './window-labels.js';
|
|
@@ -233,11 +234,15 @@ export function unreachableTiers(env = process.env) {
|
|
|
233
234
|
* model filters nothing.
|
|
234
235
|
* @param {object} [opts.env] environment to read tier aliases from (see
|
|
235
236
|
* unreachableTiers)
|
|
237
|
+
* @param {string} [opts.grade] delegation grade (routing-switch.js), 'quality'
|
|
238
|
+
* unless a relax window is open. 'cost' gates on ESCALATE_RE alone; 'quality' also
|
|
239
|
+
* gates on JUDGE_RE and drops the T2 rules of every category but paste,
|
|
240
|
+
* read and translate.
|
|
236
241
|
* @returns {{cat: object, t2: object|undefined, t1: object|undefined, unreachable?: string[]}|null}
|
|
237
242
|
* `unreachable` is set, with neither t2 nor t1, when every matching tier is
|
|
238
243
|
* one this session cannot reach
|
|
239
244
|
*/
|
|
240
|
-
export function routeMatch(text, { rules, sessionRank = null, root, env = process.env } = {}) {
|
|
245
|
+
export function routeMatch(text, { rules, sessionRank = null, root, env = process.env, grade = delegationGrade() } = {}) {
|
|
241
246
|
const t = String(text || '').trim();
|
|
242
247
|
if (t.length < MIN_LEN) return null;
|
|
243
248
|
// A task notification or command echo is not a request, whatever words it holds.
|
|
@@ -246,6 +251,9 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
|
|
|
246
251
|
// before classification because such a request often looks like a light
|
|
247
252
|
// "run" or "check" in its wording.
|
|
248
253
|
if (ESCALATE_RE.test(t)) return null;
|
|
254
|
+
// At grade 'quality' the gate is wider: audits, recommendations, absence
|
|
255
|
+
// checks and research end in a judgement as well (JUDGE_RE).
|
|
256
|
+
if (isQualityGrade(grade) && JUDGE_RE.test(t)) return null;
|
|
249
257
|
// Same for implementation work dressed as a run or a check: an edit is not
|
|
250
258
|
// delegable, and with no tool calls yet only the wording can say so.
|
|
251
259
|
if (EDIT_RE.test(t)) return null;
|
|
@@ -277,7 +285,7 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
|
|
|
277
285
|
const roots = root ? sharedProjectRoots(root) : [];
|
|
278
286
|
const inScope = (r) => r.scope !== 'project' ||
|
|
279
287
|
(typeof r.targetRoot === 'string' && roots.includes(realProjectRoot(r.targetRoot)));
|
|
280
|
-
const matched = all.filter((r) => r && r.category === cat.id && inScope(r));
|
|
288
|
+
const matched = all.filter((r) => r && r.category === cat.id && inScope(r) && gradeKeepsRule(grade, r));
|
|
281
289
|
if (!matched.length) return null;
|
|
282
290
|
// A rule only saves anything when its target tier is cheaper than the model
|
|
283
291
|
// reading the hint. A T1 rule states "delegate to model: sonnet", which in a
|
|
@@ -304,6 +312,117 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
|
|
|
304
312
|
return t2 || t1 || t1h ? { cat, t2, t1, t1h } : null;
|
|
305
313
|
}
|
|
306
314
|
|
|
315
|
+
/** True for 'quality'; an unknown grade reads as the default. */
|
|
316
|
+
function isQualityGrade(grade) {
|
|
317
|
+
return (normalizeDelegationGrade(grade) ?? 'quality') === 'quality';
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* ESCALATE_RE terms that name an action rather than a question: store
|
|
322
|
+
* submission, deploy, release, merge, production access, a go-ahead. They keep
|
|
323
|
+
* the delegation quiet (an irreversible step stays on the main model) but
|
|
324
|
+
* "this request ends in a judgement" would be wrong for "배포해줘".
|
|
325
|
+
*/
|
|
326
|
+
const ACTION_RE = new RegExp(
|
|
327
|
+
/운영\s*(?:db|디비|데이터베이스|서버|환경)|프로덕션|\bprod(?:uction)?\s*(?:db|database|server|env)|승인\s*(?:할게|했어|했으니|했습니다|합니다|해줄게|완료)|\bapproved?\b|제출|배포|출시|퍼블리시|릴리[스즈](?!\s*노트)|(?<!나)머지|submit|deploy|release|publish|merge/.source, 'gi');
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Why a request is kept off the delegation path, for the grades that gate on
|
|
331
|
+
* judgement. routeMatch returns null for all of these; this says which gate it
|
|
332
|
+
* was so the caller can recommend a stronger model instead of staying silent.
|
|
333
|
+
*
|
|
334
|
+
* @returns {{judgement: true, kind: 'escalate'|'judge'|'action', cat: null}|null}
|
|
335
|
+
* 'escalate' is a design, diagnosis or comparison word (ESCALATE_RE), 'judge'
|
|
336
|
+
* an audit, recommendation, absence check or research (JUDGE_RE, only below
|
|
337
|
+
* grade 'quality'), 'action' an irreversible step with no judgement word.
|
|
338
|
+
*/
|
|
339
|
+
export function judgementMatch(text, { grade = delegationGrade() } = {}) {
|
|
340
|
+
const t = String(text || '').trim();
|
|
341
|
+
if (t.length < MIN_LEN || isSystemPrompt(t)) return null;
|
|
342
|
+
if (ESCALATE_RE.test(t)) {
|
|
343
|
+
const kind = ESCALATE_RE.test(t.replace(ACTION_RE, ' ')) ? 'escalate' : 'action';
|
|
344
|
+
return { judgement: true, kind, cat: null };
|
|
345
|
+
}
|
|
346
|
+
if (isQualityGrade(grade) && JUDGE_RE.test(t)) return { judgement: true, kind: 'judge', cat: null };
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* What grade 'cost' still sends up: diagnosis, audit and security asks. The
|
|
352
|
+
* other judgement words stay quiet there because that grade is the relax window, where
|
|
353
|
+
* the user chose to spend less.
|
|
354
|
+
*/
|
|
355
|
+
const COST_UP_RE = /원인\s*(?:분석|파악|확인|규명|조사)|원인을?\s*찾|root cause|버그|취약|vulnerabilit|보안\s*(?:점검|검토|감사|리뷰|이슈)|security (?:review|audit)|감사\s*(?:해\s*(?:줘|봐|주|보|라|볼)|좀|를\s*(?:해|돌|진행)|하자|요청|부탁)|\baudit(?!\s*(?:log|trail))/i;
|
|
356
|
+
|
|
357
|
+
/** Price rank of Opus: a session at or above it needs no recommendation to move up. */
|
|
358
|
+
const OPUS_RANK = TIER_TARGET_RANK.T1H;
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* The line that recommends Opus at effort high for a request that ends in a
|
|
362
|
+
* judgement, or null when none applies.
|
|
363
|
+
*
|
|
364
|
+
* Measured in the validation Lab (r8) on ten jobs whose result is a judgement:
|
|
365
|
+
* Sonnet at high reached the same conclusion as the reference 1 time, Opus at
|
|
366
|
+
* high 5 times, Opus at xhigh 6 times with 11 wrong claims against 3. So the
|
|
367
|
+
* line names high and never xhigh.
|
|
368
|
+
*
|
|
369
|
+
* Silent when the session already runs Opus or better, and when the session
|
|
370
|
+
* model is unknown (a guess could tell an Opus session to switch to itself).
|
|
371
|
+
* Grade 'quality' speaks for every judgement request; 'cost'
|
|
372
|
+
* only for diagnosis, audit and security (COST_UP_RE).
|
|
373
|
+
*
|
|
374
|
+
* @param {string} text the prompt just submitted
|
|
375
|
+
* @param {object} [opts]
|
|
376
|
+
* @param {number|null} [opts.sessionRank] see sessionModelRank
|
|
377
|
+
* @param {string} [opts.grade] delegation grade
|
|
378
|
+
* @param {string} [opts.lang] 'ko' | 'en'
|
|
379
|
+
* @param {object|null} [opts.judgement] a judgementMatch result the caller already has
|
|
380
|
+
*/
|
|
381
|
+
export function escalationNotice(text, { sessionRank = null, grade = delegationGrade(), lang = userLanguage(), judgement } = {}) {
|
|
382
|
+
if (sessionRank === null || sessionRank >= OPUS_RANK) return null;
|
|
383
|
+
const j = judgement === undefined ? judgementMatch(text, { grade }) : judgement;
|
|
384
|
+
if (!j || j.kind === 'action') return null;
|
|
385
|
+
if (!isQualityGrade(grade) && !COST_UP_RE.test(String(text || ''))) return null;
|
|
386
|
+
return lang === 'ko'
|
|
387
|
+
? '✇ [sprag] 이 요청은 판단이 결론인 일입니다. Sonnet보다 Opus(effort high)가 맡도록 권합니다. '
|
|
388
|
+
+ 'Opus 서브에이전트(t1h-worker)로 넘기거나 /model opus로 바꾸십시오. '
|
|
389
|
+
+ '근거는 판단형 10건에서 Sonnet high가 같은 결론 1건, Opus high가 5건이었던 측정입니다(sprag.io/proof).'
|
|
390
|
+
: '✇ [sprag] This request ends in a judgement. sprag recommends Opus at effort high over Sonnet: '
|
|
391
|
+
+ 'hand it to an Opus subagent (t1h-worker) or switch with /model opus. '
|
|
392
|
+
+ 'On 10 judgement jobs Sonnet high reached the same conclusion once and Opus high five times (sprag.io/proof).';
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* The line for a main session at effort low or medium that gets a request
|
|
397
|
+
* ending in a judgement. A hook cannot change the session's effort, so the line
|
|
398
|
+
* has the model hand the judgement part to an Opus subagent at effort high and
|
|
399
|
+
* tell the user about /effort high in one line. Null when no line applies.
|
|
400
|
+
*
|
|
401
|
+
* Same request gate as escalationNotice: a judgement request that is not an
|
|
402
|
+
* irreversible action, and at grade 'cost' only diagnosis, audit and security.
|
|
403
|
+
*
|
|
404
|
+
* @param {string} text the prompt just submitted
|
|
405
|
+
* @param {object} [opts]
|
|
406
|
+
* @param {string|null} [opts.sessionEffort] the level the statusline recorded (readSessionEffort)
|
|
407
|
+
* @param {string} [opts.grade] delegation grade
|
|
408
|
+
* @param {string} [opts.lang] 'ko' | 'en'
|
|
409
|
+
* @param {object|null} [opts.judgement] a judgementMatch result the caller already has
|
|
410
|
+
*/
|
|
411
|
+
export function effortNotice(text, { sessionEffort = null, grade = delegationGrade(), lang = userLanguage(), judgement } = {}) {
|
|
412
|
+
const level = typeof sessionEffort === 'string' ? sessionEffort.trim().toLowerCase() : '';
|
|
413
|
+
if (level !== 'low' && level !== 'medium') return null;
|
|
414
|
+
const j = judgement === undefined ? judgementMatch(text, { grade }) : judgement;
|
|
415
|
+
if (!j || j.kind === 'action') return null;
|
|
416
|
+
if (!isQualityGrade(grade) && !COST_UP_RE.test(String(text || ''))) return null;
|
|
417
|
+
return lang === 'ko'
|
|
418
|
+
? `✇ [sprag] 이 요청은 판단이 결론인 일인데 지금 세션의 effort가 ${level}입니다. `
|
|
419
|
+
+ '판단이 필요한 부분은 Opus effort high 서브에이전트(t1h-worker)에 맡기고, '
|
|
420
|
+
+ '답 끝에 "/effort high로 올리면 메인도 같은 수준으로 답합니다"를 한 줄 덧붙이십시오.'
|
|
421
|
+
: `✇ [sprag] This request ends in a judgement and the session runs at effort ${level}. `
|
|
422
|
+
+ 'Hand the part that needs judgement to an Opus subagent at effort high (t1h-worker), '
|
|
423
|
+
+ 'and end your answer with one line: "Raise the main session with /effort high to get the same level here."';
|
|
424
|
+
}
|
|
425
|
+
|
|
307
426
|
/** The budgets a match states, by tier: what the delegation guard repeats to the subagent. */
|
|
308
427
|
export function matchCaps(match) {
|
|
309
428
|
if (!match) return null;
|
|
@@ -398,6 +517,9 @@ export function pressureLine(pressure, { lang = userLanguage() } = {}) {
|
|
|
398
517
|
const label = labelForKey(pressure.key).short;
|
|
399
518
|
const pct = Math.round(pressure.pct);
|
|
400
519
|
const ko = lang === 'ko';
|
|
520
|
+
// The caller sets `offer` once per limit window when delegation is not
|
|
521
|
+
// relaxed (claimRelaxOffer). The offer stands in for the usual line.
|
|
522
|
+
if (pressure.offer) return relaxOfferLine(label, pct, lang);
|
|
401
523
|
if (pressure.level === 'critical') {
|
|
402
524
|
return ko
|
|
403
525
|
? `한도 위험: ${label} ${pct}%. 여러 단계 작업도 위임 대상으로 보고, 메인 모델을 바꾸는 것(/model)도 사용자에게 제안하십시오.`
|
|
@@ -408,6 +530,13 @@ export function pressureLine(pressure, { lang = userLanguage() } = {}) {
|
|
|
408
530
|
: `Usage limit pressure: ${label} ${pct}%. When in doubt, delegate.`;
|
|
409
531
|
}
|
|
410
532
|
|
|
533
|
+
/** The one-time offer to widen delegation until the limit window resets. */
|
|
534
|
+
export function relaxOfferLine(label, pct, lang = userLanguage()) {
|
|
535
|
+
return lang === 'ko'
|
|
536
|
+
? `✇ [sprag] ${label} 사용량이 ${pct}%입니다. 이번 한도 창이 끝날 때까지 위임 범위를 넓히면 사용량을 아낄 수 있습니다. 사용자에게 한 줄로 물어보고, 동의하면 sprag routing relax 를 실행하십시오. 창이 초기화되면 자동으로 원래대로 돌아옵니다.`
|
|
537
|
+
: `✇ [sprag] ${label} usage is at ${pct}%. Widening delegation until this limit window resets would save usage. Ask the user in one line, and if they agree run sprag routing relax. It switches back by itself when the window resets.`;
|
|
538
|
+
}
|
|
539
|
+
|
|
411
540
|
/**
|
|
412
541
|
* @param {string} text the prompt just submitted
|
|
413
542
|
* @param {object} [opts] as routeMatch, plus:
|
package/src/route-scan.js
CHANGED
|
@@ -34,6 +34,7 @@ import { modelRuleBaseText } from './model-rules.js';
|
|
|
34
34
|
import { RULE_CATEGORY_LABELS } from './rule-categories.js';
|
|
35
35
|
import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
|
|
36
36
|
import { agentForRule } from './agents.js';
|
|
37
|
+
import { safeExcerpt } from './redact.js';
|
|
37
38
|
|
|
38
39
|
// ── Tier bands (docs/TIER_CRITERIA.md §3) ────────────────────────────────
|
|
39
40
|
// T2 (haiku): finished in few calls, tiny output, near-zero mutation, no
|
|
@@ -82,6 +83,28 @@ export const MIN_DELEGABLE_OUT = 100;
|
|
|
82
83
|
// out: "승인된 룰" is a product noun in sprag's own ratchet flow.
|
|
83
84
|
export const ESCALATE_RE = /운영\s*(?:db|디비|데이터베이스|서버|환경)|프로덕션|\bprod(?:uction)?\s*(?:db|database|server|env)|승인\s*(?:할게|했어|했으니|했습니다|합니다|해줄게|완료)|\bapproved?\b|설계|아키텍처|리팩토링|원인\s*(?:분석|파악|확인|규명|조사)|원인을?\s*찾|버그|개선할|개선점|개선\s*(?:사항|방안)|검토해보|검수|코드\s*리뷰|리뷰\s*해|취약|보안\s*(?:점검|검토|감사|리뷰|이슈)|비교|왜(?=[\s?]|$)|이유|제출|배포|출시|퍼블리시|릴리[스즈](?!\s*노트)|(?<!나)머지|analyze|compare|evaluate|architect|refactor|submit|deploy|release|publish|merge|root cause|code review|security (?:review|audit)|vulnerabilit/i;
|
|
84
85
|
|
|
86
|
+
// Requests that end in a judgement but that ESCALATE_RE does not list: audits,
|
|
87
|
+
// recommendations, rankings, "is there none / is there any" absence checks,
|
|
88
|
+
// and research that needs searching. In the validation Lab (r8) the answer to
|
|
89
|
+
// ten such jobs was a judgement, and Sonnet at effort high reached the same
|
|
90
|
+
// conclusion as Opus in 1 of 10 against 5 of 10 for Opus at high. Request-shaped
|
|
91
|
+
// forms only: "감사합니다" is thanks and "audit log", "추천 위임 룰" (a product
|
|
92
|
+
// noun) and "<name>-research-summary.md" (a file name) are not requests.
|
|
93
|
+
//
|
|
94
|
+
// Measured 2026-11-08 on 1,351 distinct local prompts (type=user, text only,
|
|
95
|
+
// harness messages and sidechains removed, last 90 days): JUDGE_RE matches 351,
|
|
96
|
+
// of which ESCALATE_RE already gated 343, so it newly gates 8 (6 distinct
|
|
97
|
+
// texts, three of them repeats of one eval prompt). The first draft gated 23;
|
|
98
|
+
// the 15 it lost were file names holding "research" (<name>-research-summary.md,
|
|
99
|
+
// 6), "할 수 없는지" read as absence (1), a code-lookup question "is there a
|
|
100
|
+
// function that …" (5, one prompt) and "조사해" in the
|
|
101
|
+
// sense of reading a git stash (3, one prompt). All 8 that remain are a
|
|
102
|
+
// research or absence-check request (precision 8/8; 6/6 distinct), but the sample
|
|
103
|
+
// is small, so the figure says "no false positive seen", not "none exist".
|
|
104
|
+
// The pattern was not asked to catch "있는지" alone: "실행되고 있는지" and the
|
|
105
|
+
// like are ordinary checks, so only "없는지", "있는지 없는지" and "존재하는지" count.
|
|
106
|
+
export const JUDGE_RE = /감사\s*(?:해\s*(?:줘|봐|주|보|라|볼)|좀|를\s*(?:해|돌|진행)|하자|요청|부탁)|\baudit(?!\s*(?:log|trail))|추천\s*(?:해\s*(?:줘|주|봐|달)|좀|부탁)|추천해|\brecommend(?!ation\s*(?:letter|engine))|우선\s*순위|순위\s*(?:를|을)\s*(?:매기|매겨|정해|정하)|\bprioriti[sz]e|(?<![수순]\s*)없는지|있는지\s*없는지|존재하는지|조사\s*해\s*(?:보|줘|주|봐|달|라)|조사\s*(?:좀|부탁)|리서치|(?<![\w./-])research(?![\w./-])|\bfind\s+(?:me\s+)?(?:alternatives?|options|candidates)|\bis there (?:any|an?)\b(?!\s+(?:exported\s+|existing\s+)?(?:function|file|method|class|module|variable|constant|test|script|helper|field|key|line))[^?\n]{0,60}\b(?:that|which)\b/i;
|
|
107
|
+
|
|
85
108
|
// Implementation asks phrased around a run/check verb ("설치와 동시에 설정되도록
|
|
86
109
|
// 하자", "피드백 확인해주고 아이콘도 만들자"). Editing is not delegable, and at
|
|
87
110
|
// prompt time there is no tool mix to reveal it, so the wording has to. Offline
|
|
@@ -707,7 +730,8 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
707
730
|
const usable = ep.text.length > 10;
|
|
708
731
|
if ((!g.example && (usable || !g.exampleUsable))
|
|
709
732
|
|| (usable && (!g.exampleUsable || ep.text.length < g.example.length))) {
|
|
710
|
-
|
|
733
|
+
// Mask before cutting so a token cut in half at char 80 cannot slip through.
|
|
734
|
+
g.example = safeExcerpt(ep.text, 80);
|
|
711
735
|
g.exampleUsable = usable;
|
|
712
736
|
}
|
|
713
737
|
groups.set(key, g);
|
package/src/routing-switch.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { loadConfig, saveConfig } from './config.js';
|
|
12
|
+
import { formatResetClock } from './format-time.js';
|
|
12
13
|
|
|
13
14
|
export function routingEnabled(cfg = loadConfig()) {
|
|
14
15
|
try {
|
|
@@ -18,12 +19,116 @@ export function routingEnabled(cfg = loadConfig()) {
|
|
|
18
19
|
}
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Whether the prompt hook may tell a low or medium effort session to hand its
|
|
24
|
+
* judgement work to an Opus subagent (effortNotice). Only an explicit `false`
|
|
25
|
+
* in `effortHint` is off; routing off silences it too.
|
|
26
|
+
*/
|
|
27
|
+
export function effortHintEnabled(cfg = loadConfig()) {
|
|
28
|
+
try {
|
|
29
|
+
return routingEnabled(cfg) && cfg?.effortHint !== false;
|
|
30
|
+
} catch {
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function setEffortHint(on) {
|
|
36
|
+
const cfg = loadConfig();
|
|
37
|
+
cfg.effortHint = on !== false;
|
|
38
|
+
pruneExpiredRelax(cfg);
|
|
39
|
+
saveConfig(cfg);
|
|
40
|
+
}
|
|
41
|
+
|
|
21
42
|
export function setRoutingEnabled(on) {
|
|
22
43
|
const cfg = loadConfig();
|
|
23
44
|
cfg.routing = on !== false;
|
|
45
|
+
pruneExpiredRelax(cfg);
|
|
24
46
|
saveConfig(cfg);
|
|
25
47
|
}
|
|
26
48
|
|
|
49
|
+
/**
|
|
50
|
+
* How far delegation goes while routing is on. 'quality' hands off only work
|
|
51
|
+
* whose answer comes straight from tool output and sends judgement work up to
|
|
52
|
+
* Opus; 'cost' hands off as much as the rules allow. Routing off still wins
|
|
53
|
+
* over any grade.
|
|
54
|
+
*
|
|
55
|
+
* The grade is not a setting. It is 'quality' unless a relax window is open:
|
|
56
|
+
* `relaxUntil` in config.json holds an epoch-ms deadline, and until then the
|
|
57
|
+
* grade reads 'cost'. `sprag routing relax` opens the window up to the reset
|
|
58
|
+
* of the busiest usage window, and once the deadline passes the grade goes
|
|
59
|
+
* back to 'quality' by itself, with no write needed.
|
|
60
|
+
*/
|
|
61
|
+
export const DELEGATION_GRADES = ['quality', 'cost'];
|
|
62
|
+
export const DEFAULT_DELEGATION_GRADE = 'quality';
|
|
63
|
+
|
|
64
|
+
/** A grade name; null for anything else. */
|
|
65
|
+
export function normalizeDelegationGrade(value) {
|
|
66
|
+
return DELEGATION_GRADES.includes(value) ? value : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The stored relax deadline in epoch ms, or null when none is stored. It may already be past. */
|
|
70
|
+
export function relaxUntil(cfg = loadConfig()) {
|
|
71
|
+
try {
|
|
72
|
+
const v = cfg?.relaxUntil;
|
|
73
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : null;
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** True while the relax deadline is still ahead of `now`. */
|
|
80
|
+
export function isRelaxed(cfg = loadConfig(), now = Date.now()) {
|
|
81
|
+
const until = relaxUntil(cfg);
|
|
82
|
+
return until !== null && until > now;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function delegationGrade(cfg = loadConfig(), now = Date.now()) {
|
|
86
|
+
try {
|
|
87
|
+
return isRelaxed(cfg, now) ? 'cost' : DEFAULT_DELEGATION_GRADE;
|
|
88
|
+
} catch {
|
|
89
|
+
return DEFAULT_DELEGATION_GRADE;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Stores the relax deadline (epoch ms), or clears it with null. A deadline
|
|
95
|
+
* that has passed is dropped from the config on any write that goes through
|
|
96
|
+
* here or through the other setters in this file.
|
|
97
|
+
*/
|
|
98
|
+
export function setRelaxUntil(ms) {
|
|
99
|
+
const cfg = loadConfig();
|
|
100
|
+
if (typeof ms === 'number' && Number.isFinite(ms)) cfg.relaxUntil = ms;
|
|
101
|
+
else delete cfg.relaxUntil;
|
|
102
|
+
saveConfig(cfg);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Drops an expired relaxUntil from a config object about to be saved. */
|
|
106
|
+
function pruneExpiredRelax(cfg) {
|
|
107
|
+
const until = relaxUntil(cfg);
|
|
108
|
+
if (until !== null && until <= Date.now()) delete cfg.relaxUntil;
|
|
109
|
+
else if (cfg && 'relaxUntil' in cfg && until === null) delete cfg.relaxUntil;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The deadline as the user reads it: HH:MM, with the weekday ahead of it when it is not today. */
|
|
113
|
+
export function relaxClock(ms, now = new Date()) {
|
|
114
|
+
return formatResetClock(ms / 1000, now);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* At grade 'quality' a T2 (haiku) rule survives only for the categories whose
|
|
119
|
+
* answer is copied out of text the model is handed: pasted logs, reading and
|
|
120
|
+
* translating. A lookup, check or command run goes to T1 or stays on the main
|
|
121
|
+
* model, because a lookup that stops early is wrong without saying so. T1 and
|
|
122
|
+
* T1H rules are untouched, and so is grade 'cost'.
|
|
123
|
+
*/
|
|
124
|
+
export const QUALITY_T2_CATEGORIES = new Set(['paste', 'read', 'translate']);
|
|
125
|
+
|
|
126
|
+
/** False when this grade drops the rule (see QUALITY_T2_CATEGORIES). */
|
|
127
|
+
export function gradeKeepsRule(grade, rule) {
|
|
128
|
+
if ((normalizeDelegationGrade(grade) ?? DEFAULT_DELEGATION_GRADE) !== 'quality') return true;
|
|
129
|
+
return rule?.tier !== 'T2' || QUALITY_T2_CATEGORIES.has(rule.category);
|
|
130
|
+
}
|
|
131
|
+
|
|
27
132
|
// Preset ratchet rules (presets/ratchet-rules.json) whose text tells the model
|
|
28
133
|
// to delegate: fix-f558f9 sends simple lookups and commands to T2 agents and
|
|
29
134
|
// fix-777a15 sends multi-file implementation to the T1 worker. The other
|